Skip to content

[codex] Fix Gemini proxy timeout handling - #8640

Merged
Git-on-my-level merged 2 commits into
mainfrom
codex/gemini-proxy-timeouts
Jun 29, 2026
Merged

Git-on-my-level merged 2 commits into
mainfrom
codex/gemini-proxy-timeouts

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Jun 29, 2026 •

Copy link
Copy Markdown
Member

Summary

Closes #8633.

This makes the desktop Gemini proxy own upstream timeout behavior instead of letting long generateContent calls run into the Cloud Run request deadline.

Root cause

The Rust proxy forwarded Gemini requests synchronously through fresh reqwest::Client::new() instances with no explicit non-streaming upstream deadline. Desktop clients also waited 300 seconds, so slow Gemini/Vertex calls often reached Cloud Run's outer request deadline and surfaced as platform 504s or generic 502s.

Changes

  • Add shared Gemini proxy HTTP clients to AppState:
    • non-streaming client has a 10s connect timeout and 120s total upstream timeout
    • streaming client has a 10s connect timeout only, preserving long SSE responses
  • Map upstream request/body-read timeouts to sanitized JSON 504 Gateway Timeout responses with retry-after before Cloud Run kills the request.
  • Add sanitized upstream result logging with provider, model, action, payload bucket, duration bucket, and status.
  • Update macOS Gemini client error handling so timeout/deadline/504 errors show a clear recoverable message and are not auto-retried after a long wait; 502 remains transient/retryable.
  • Add focused backend tests for timeout policy, timeout response shape, and metric buckets.
  • Add the required macOS changelog fragment.

Validation

  • cd desktop/macos/Backend-Rust && cargo test proxy
  • cd desktop/macos/Backend-Rust && cargo test
  • cd desktop/macos && xcrun swift build -c debug --package-path Desktop

Swift build completed with existing warnings outside this change.

Review in cubic

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 issue found across 4 files

Confidence score: 2/5

  • In desktop/macos/Backend-Rust/src/routes/proxy.rs, raw reqwest error logging can include the upstream URL and leak the Gemini API key when AI Studio requests fail, creating a concrete secret-exposure risk in backend logs; sanitize/redact server-key request errors (or strip query/credential-bearing URL parts) before merging.

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: b6a48def7d

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@Git-on-my-level
Git-on-my-level merged commit 8a435b3 into main Jun 29, 2026
3 checks passed
@Git-on-my-level
Git-on-my-level deleted the codex/gemini-proxy-timeouts branch June 29, 2026 23:19
Git-on-my-level added a commit that referenced this pull request Jul 13, 2026
## Summary

- replace the permanently cached Redis connection with a
generation-aware, single-flight recovery owner
- classify Redis failures, retry safe commands once, and never replay
outcome-ambiguous metering scripts
- fail managed Gemini/chat/TTS requests closed when Redis metering is
unavailable while preserving BYOK bypasses
- expose Redis dependency state at `/ready` without removing
Redis-independent traffic from Kubernetes service readiness
- give non-streaming Gemini work one 75-second end-to-end budget,
propagate downstream cancellation, preserve request correlation, and
emit bounded phase-owned outcomes

Addresses #9524.

## Root cause and recurrence

The Rust backend cached one multiplexed Redis connection for the process
lifetime. A broken pipe was returned to the caller, but no owner
invalidated that connection, so every later metered request reused the
stale generation until process restart. The same owner also allowed
concurrent cold-start connections.

The Gemini timeout class recurred after #8640 and #8911 because those
fixes only moved a per-attempt timeout to the current infrastructure
boundary. Token acquisition, provider fallback, dispatch, and body drain
did not share one logical deadline, and timeout outcomes were not
separated from auth or generic provider failures.

## Durable guard

- Redis leases carry generation and age; stale failures conditionally
invalidate only their own generation.
- Connection creation is single-flight with bounded connect/command
deadlines, per-instance jitter, and cooldown after exhaustion.
- Transport failures reconnect; auth/config, capacity, and command/data
errors do not masquerade as stale transport.
- Reads and idempotent final-state writes replay at most once.
Rate-limit Lua scripts and task acceptance never replay after an
outcome-unknown transport failure.
- Redis operation telemetry has bounded operation/failure/reconnect
fields and production-visible success denominators.
- Managed-key metering fails closed with retryable 503 responses; BYOK
remains Redis-independent.
- Gemini uses one logical deadline below the observed 90-second
boundary. Auth timeout, provider timeout, 429, provider 5xx, transport
failure, and cancellation are distinct bounded outcomes; provider/mode
changes use the shared fallback event.
- Request IDs are returned on proxy-owned provider errors and logged
without prompts, bodies, keys, or user content.

## Verification

- `cd desktop/macos && bash test.sh` — launcher checks passed, Rust
suite passed, and 237 Swift suites passed in isolation
- `cd desktop/macos/Backend-Rust && cargo test --locked` — 346 passed
- `cd desktop/macos/Backend-Rust && cargo check --locked` — passed
- `cd desktop/macos/Backend-Rust && cargo fmt -- --check` — passed
- `make preflight` — all 9 selected manifest checks passed; no locked
product invariants apply
- independent agent review — approved with no remaining blocker

The fault tests exercise the production Redis client against scripted
RESP sockets: first-command connection close, safe replay recovery,
non-replayable EVAL, eight concurrent stale callers, reconnect
exhaustion, repeated stale generations, and auth/config rejection.
Gemini tests exercise a hanging local upstream plus a real Axum HTTP
downstream disconnect, proving the upstream request is dropped without
detached work.

## Rollout notes

No production mutation is included in this PR. After deployment, verify
the exact revision with a controlled Redis connection close,
authenticated managed-key TTS, and a natural-traffic window longer than
the prior short soak. Roll back on retry amplification, duplicate
metering, or a new TTS failure cluster.

The repository does not own the external release-health dashboard/alert
consumer. This PR supplies bounded `gemini_provider_request` outcomes so
#9523 can exclude provider timeouts from release-regression aggregation
while continuing to report the provider SLO separately.


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/9533?utm_source=github"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img
alt="Review in cubic"
src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a>
<!-- End of auto-generated description by cubic. -->
aryanorastar added a commit to aryanorastar/omi that referenced this pull request Jul 23, 2026
The provider-timeout class (FC-per-hop-timeout: BasedHardware#8640, BasedHardware#8911, BasedHardware#9135,
chat path now owns one admission budget instead:

- RequestDeadline (240s inside the 300s platform bound, mirroring the
  Gemini proxy) is created in route middleware before extractors and
  body extraction; auth, BYOK, and paywall waits are bounded by it and
  budget exhaustion returns a typed 504 instead of a 401.
- All provider sends go through send_with_deadline; the retry loop is a
  budget-aware policy: attempts never start on an expired budget, a
  retry or pause_turn continuation starts only above a 10s floor, and
  backoff sleeps truncate at the budget edge. A transient status on the
  final available attempt still passes through unchanged.
- The budget governs everything before the first client-visible semantic
  SSE event. The stream idle timer now measures SEMANTIC progress:
  raw bytes and Anthropic ping events no longer reset it, closing the
  live gap where a ping-only upstream could hold a client forever with
  nothing visible. Streaming still has no total response timeout by
  design (BasedHardware#9135): a visible-delta stream survives budget expiry.
- The detached Firestore usage write runs through a spawn seam that
  never inherits the request deadline.

Behavioral tests drive the policy and the real stream translator with
tokio::time::pause: budget-floor retry stop, backoff truncation at the
edge, long visible streams surviving expiry, ping-only turns ending in a
typed terminal SSE error, semantic-idle stalls independent of budget,
and detached-write completion after expiry.

Fixes BasedHardware#9835.

Co-Authored-By: Claude Fable 5 <[email protected]>
aryanorastar added a commit to aryanorastar/omi that referenced this pull request Jul 23, 2026
Static tripwire (labeled as such): raw reqwest builders are not covered
by signatures alone, so new direct .send() calls in routes/chat/ fail
the manifest lanes. Behavioral coverage lives in the paused-time
deadline tests. Caught class: BasedHardware#8640/BasedHardware#8911/BasedHardware#9135/BasedHardware#9644 (BasedHardware#9835).

Co-Authored-By: Claude Fable 5 <[email protected]>
aryanorastar added a commit to aryanorastar/omi that referenced this pull request Jul 23, 2026
The provider-timeout class (FC-per-hop-timeout: BasedHardware#8640, BasedHardware#8911, BasedHardware#9135,
chat path now owns one admission budget instead:

- RequestDeadline (240s inside the 300s platform bound, mirroring the
  Gemini proxy) is created in route middleware before extractors and
  body extraction; auth, BYOK, and paywall waits are bounded by it and
  budget exhaustion returns a typed 504 instead of a 401.
- All provider sends go through send_with_deadline; the retry loop is a
  budget-aware policy: attempts never start on an expired budget, a
  retry or pause_turn continuation starts only above a 10s floor, and
  backoff sleeps truncate at the budget edge. A transient status on the
  final available attempt still passes through unchanged.
- The budget governs everything before the first client-visible semantic
  SSE event. The stream idle timer now measures SEMANTIC progress:
  raw bytes and Anthropic ping events no longer reset it, closing the
  live gap where a ping-only upstream could hold a client forever with
  nothing visible. Streaming still has no total response timeout by
  design (BasedHardware#9135): a visible-delta stream survives budget expiry.
- The detached Firestore usage write runs through a spawn seam that
  never inherits the request deadline.

Behavioral tests drive the policy and the real stream translator with
tokio::time::pause: budget-floor retry stop, backoff truncation at the
edge, long visible streams surviving expiry, ping-only turns ending in a
typed terminal SSE error, semantic-idle stalls independent of budget,
and detached-write completion after expiry.

Fixes BasedHardware#9835.

Co-Authored-By: Claude Fable 5 <[email protected]>
aryanorastar added a commit to aryanorastar/omi that referenced this pull request Jul 23, 2026
Static tripwire (labeled as such): raw reqwest builders are not covered
by signatures alone, so new direct .send() calls in routes/chat/ fail
the manifest lanes. Behavioral coverage lives in the paused-time
deadline tests. Caught class: BasedHardware#8640/BasedHardware#8911/BasedHardware#9135/BasedHardware#9644 (BasedHardware#9835).

Co-Authored-By: Claude Fable 5 <[email protected]>
aryanorastar added a commit to aryanorastar/omi that referenced this pull request Jul 24, 2026
The provider-timeout class (FC-per-hop-timeout: BasedHardware#8640, BasedHardware#8911, BasedHardware#9135,
chat path now owns one admission budget instead:

- RequestDeadline (240s inside the 300s platform bound, mirroring the
  Gemini proxy) is created in route middleware before extractors and
  body extraction; auth, BYOK, and paywall waits are bounded by it and
  budget exhaustion returns a typed 504 instead of a 401.
- All provider sends go through send_with_deadline; the retry loop is a
  budget-aware policy: attempts never start on an expired budget, a
  retry or pause_turn continuation starts only above a 10s floor, and
  backoff sleeps truncate at the budget edge. A transient status on the
  final available attempt still passes through unchanged.
- The budget governs everything before the first client-visible semantic
  SSE event. The stream idle timer now measures SEMANTIC progress:
  raw bytes and Anthropic ping events no longer reset it, closing the
  live gap where a ping-only upstream could hold a client forever with
  nothing visible. Streaming still has no total response timeout by
  design (BasedHardware#9135): a visible-delta stream survives budget expiry.
- The detached Firestore usage write runs through a spawn seam that
  never inherits the request deadline.

Behavioral tests drive the policy and the real stream translator with
tokio::time::pause: budget-floor retry stop, backoff truncation at the
edge, long visible streams surviving expiry, ping-only turns ending in a
typed terminal SSE error, semantic-idle stalls independent of budget,
and detached-write completion after expiry.

Fixes BasedHardware#9835.

Co-Authored-By: Claude Fable 5 <[email protected]>
aryanorastar added a commit to aryanorastar/omi that referenced this pull request Jul 24, 2026
Static tripwire (labeled as such): raw reqwest builders are not covered
by signatures alone, so new direct .send() calls in routes/chat/ fail
the manifest lanes. Behavioral coverage lives in the paused-time
deadline tests. Caught class: BasedHardware#8640/BasedHardware#8911/BasedHardware#9135/BasedHardware#9644 (BasedHardware#9835).

Co-Authored-By: Claude Fable 5 <[email protected]>
aryanorastar added a commit to aryanorastar/omi that referenced this pull request Jul 24, 2026
The provider-timeout class (FC-per-hop-timeout: BasedHardware#8640, BasedHardware#8911, BasedHardware#9135,
chat path now owns one admission budget instead:

- RequestDeadline (240s inside the 300s platform bound, mirroring the
  Gemini proxy) is created in route middleware before extractors and
  body extraction; auth, BYOK, and paywall waits are bounded by it and
  budget exhaustion returns a typed 504 instead of a 401.
- All provider sends go through send_with_deadline; the retry loop is a
  budget-aware policy: attempts never start on an expired budget, a
  retry or pause_turn continuation starts only above a 10s floor, and
  backoff sleeps truncate at the budget edge. A transient status on the
  final available attempt still passes through unchanged.
- The budget governs everything before the first client-visible semantic
  SSE event. The stream idle timer now measures SEMANTIC progress:
  raw bytes and Anthropic ping events no longer reset it, closing the
  live gap where a ping-only upstream could hold a client forever with
  nothing visible. Streaming still has no total response timeout by
  design (BasedHardware#9135): a visible-delta stream survives budget expiry.
- The detached Firestore usage write runs through a spawn seam that
  never inherits the request deadline.

Behavioral tests drive the policy and the real stream translator with
tokio::time::pause: budget-floor retry stop, backoff truncation at the
edge, long visible streams surviving expiry, ping-only turns ending in a
typed terminal SSE error, semantic-idle stalls independent of budget,
and detached-write completion after expiry.

Fixes BasedHardware#9835.

Co-Authored-By: Claude Fable 5 <[email protected]>
aryanorastar added a commit to aryanorastar/omi that referenced this pull request Jul 24, 2026
Static tripwire (labeled as such): raw reqwest builders are not covered
by signatures alone, so new direct .send() calls in routes/chat/ fail
the manifest lanes. Behavioral coverage lives in the paused-time
deadline tests. Caught class: BasedHardware#8640/BasedHardware#8911/BasedHardware#9135/BasedHardware#9644 (BasedHardware#9835).

Co-Authored-By: Claude Fable 5 <[email protected]>
aryanorastar added a commit to aryanorastar/omi that referenced this pull request Jul 26, 2026
The provider-timeout class (FC-per-hop-timeout: BasedHardware#8640, BasedHardware#8911, BasedHardware#9135,
chat path now owns one admission budget instead:

- RequestDeadline (240s inside the 300s platform bound, mirroring the
  Gemini proxy) is created in route middleware before extractors and
  body extraction; auth, BYOK, and paywall waits are bounded by it and
  budget exhaustion returns a typed 504 instead of a 401.
- All provider sends go through send_with_deadline; the retry loop is a
  budget-aware policy: attempts never start on an expired budget, a
  retry or pause_turn continuation starts only above a 10s floor, and
  backoff sleeps truncate at the budget edge. A transient status on the
  final available attempt still passes through unchanged.
- The budget governs everything before the first client-visible semantic
  SSE event. The stream idle timer now measures SEMANTIC progress:
  raw bytes and Anthropic ping events no longer reset it, closing the
  live gap where a ping-only upstream could hold a client forever with
  nothing visible. Streaming still has no total response timeout by
  design (BasedHardware#9135): a visible-delta stream survives budget expiry.
- The detached Firestore usage write runs through a spawn seam that
  never inherits the request deadline.

Behavioral tests drive the policy and the real stream translator with
tokio::time::pause: budget-floor retry stop, backoff truncation at the
edge, long visible streams surviving expiry, ping-only turns ending in a
typed terminal SSE error, semantic-idle stalls independent of budget,
and detached-write completion after expiry.

Fixes BasedHardware#9835.

Co-Authored-By: Claude Fable 5 <[email protected]>
aryanorastar added a commit to aryanorastar/omi that referenced this pull request Jul 26, 2026
Static tripwire (labeled as such): raw reqwest builders are not covered
by signatures alone, so new direct .send() calls in routes/chat/ fail
the manifest lanes. Behavioral coverage lives in the paused-time
deadline tests. Caught class: BasedHardware#8640/BasedHardware#8911/BasedHardware#9135/BasedHardware#9644 (BasedHardware#9835).

Co-Authored-By: Claude Fable 5 <[email protected]>
kodjima33 pushed a commit that referenced this pull request Jul 28, 2026
…10054)

* fix(chat): consume one request deadline budget on the Anthropic path

The provider-timeout class (FC-per-hop-timeout: #8640, #8911, #9135,
chat path now owns one admission budget instead:

- RequestDeadline (240s inside the 300s platform bound, mirroring the
  Gemini proxy) is created in route middleware before extractors and
  body extraction; auth, BYOK, and paywall waits are bounded by it and
  budget exhaustion returns a typed 504 instead of a 401.
- All provider sends go through send_with_deadline; the retry loop is a
  budget-aware policy: attempts never start on an expired budget, a
  retry or pause_turn continuation starts only above a 10s floor, and
  backoff sleeps truncate at the budget edge. A transient status on the
  final available attempt still passes through unchanged.
- The budget governs everything before the first client-visible semantic
  SSE event. The stream idle timer now measures SEMANTIC progress:
  raw bytes and Anthropic ping events no longer reset it, closing the
  live gap where a ping-only upstream could hold a client forever with
  nothing visible. Streaming still has no total response timeout by
  design (#9135): a visible-delta stream survives budget expiry.
- The detached Firestore usage write runs through a spawn seam that
  never inherits the request deadline.

Behavioral tests drive the policy and the real stream translator with
tokio::time::pause: budget-floor retry stop, backoff truncation at the
edge, long visible streams surviving expiry, ping-only turns ending in a
typed terminal SSE error, semantic-idle stalls independent of budget,
and detached-write completion after expiry.

Fixes #9835.

Co-Authored-By: Claude Fable 5 <[email protected]>

* harden(ci): reject chat provider sends that bypass send_with_deadline

Static tripwire (labeled as such): raw reqwest builders are not covered
by signatures alone, so new direct .send() calls in routes/chat/ fail
the manifest lanes. Behavioral coverage lives in the paused-time
deadline tests. Caught class: #8640/#8911/#9135/#9644 (#9835).

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(chat): count reasoning deltas as semantic progress

ThinkingDelta chunks reach the client as `reasoning_content`, but they did not
refresh the semantic idle timer — only text deltas did. So after the initial
role chunk, a Claude reasoning phase that kept emitting visible reasoning for
longer than STREAM_IDLE_TIMEOUT was ended as "no semantic progress" while the
client was actively receiving output, regressing the "a long visible stream is
not an error" contract (#9135) for reasoning streams.

Refresh the timer when a reasoning chunk is yielded, matching the text-delta
path. Regression test drives a reasoning-only stream 200s past the 60s idle
bound on the paused clock: it fails on the old code (1 of 4 reasoning deltas
delivered, turn killed at the bound) and passes with the fix.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* fix(chat): register deadline guard artifact

Failure-Class: FC-per-hop-timeout

---------

Co-authored-by: Claude Fable 5 <[email protected]>
Co-authored-by: Max Carter 祁明思 <[email protected]>
undivisible added a commit to Archit-lal/omi that referenced this pull request Jul 29, 2026
…asedHardware#10054)

* fix(chat): consume one request deadline budget on the Anthropic path

The provider-timeout class (FC-per-hop-timeout: BasedHardware#8640, BasedHardware#8911, BasedHardware#9135,
chat path now owns one admission budget instead:

- RequestDeadline (240s inside the 300s platform bound, mirroring the
  Gemini proxy) is created in route middleware before extractors and
  body extraction; auth, BYOK, and paywall waits are bounded by it and
  budget exhaustion returns a typed 504 instead of a 401.
- All provider sends go through send_with_deadline; the retry loop is a
  budget-aware policy: attempts never start on an expired budget, a
  retry or pause_turn continuation starts only above a 10s floor, and
  backoff sleeps truncate at the budget edge. A transient status on the
  final available attempt still passes through unchanged.
- The budget governs everything before the first client-visible semantic
  SSE event. The stream idle timer now measures SEMANTIC progress:
  raw bytes and Anthropic ping events no longer reset it, closing the
  live gap where a ping-only upstream could hold a client forever with
  nothing visible. Streaming still has no total response timeout by
  design (BasedHardware#9135): a visible-delta stream survives budget expiry.
- The detached Firestore usage write runs through a spawn seam that
  never inherits the request deadline.

Behavioral tests drive the policy and the real stream translator with
tokio::time::pause: budget-floor retry stop, backoff truncation at the
edge, long visible streams surviving expiry, ping-only turns ending in a
typed terminal SSE error, semantic-idle stalls independent of budget,
and detached-write completion after expiry.

Fixes BasedHardware#9835.

Co-Authored-By: Claude Fable 5 <[email protected]>

* harden(ci): reject chat provider sends that bypass send_with_deadline

Static tripwire (labeled as such): raw reqwest builders are not covered
by signatures alone, so new direct .send() calls in routes/chat/ fail
the manifest lanes. Behavioral coverage lives in the paused-time
deadline tests. Caught class: BasedHardware#8640/BasedHardware#8911/BasedHardware#9135/BasedHardware#9644 (BasedHardware#9835).

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(chat): count reasoning deltas as semantic progress

ThinkingDelta chunks reach the client as `reasoning_content`, but they did not
refresh the semantic idle timer — only text deltas did. So after the initial
role chunk, a Claude reasoning phase that kept emitting visible reasoning for
longer than STREAM_IDLE_TIMEOUT was ended as "no semantic progress" while the
client was actively receiving output, regressing the "a long visible stream is
not an error" contract (BasedHardware#9135) for reasoning streams.

Refresh the timer when a reasoning chunk is yielded, matching the text-delta
path. Regression test drives a reasoning-only stream 200s past the 60s idle
bound on the paused clock: it fails on the old code (1 of 4 reasoning deltas
delivered, turn killed at the bound) and passes with the fix.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* fix(chat): register deadline guard artifact

Failure-Class: FC-per-hop-timeout

---------

Co-authored-by: Claude Fable 5 <[email protected]>
Co-authored-by: Max Carter 祁明思 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

desktop-backend: Gemini proxy generateContent requests time out with 504/502

1 participant