Skip to content

fix(desktop): stop cutting off long-context Gemini calls at 90s (#9135) - #9583

Merged
kodjima33 merged 1 commit into
mainfrom
watchdog/issue-9135-gemini-proxy-timeout
Jul 12, 2026
Merged

kodjima33 merged 1 commit into
mainfrom
watchdog/issue-9135-gemini-proxy-timeout

Conversation

@kodjima33

@kodjima33 kodjima33 commented Jul 12, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #9135.

Bug (live on prod)

The desktop Gemini proxy returns persistent 504s on
/v1/proxy/gemini/models/gemini-2.5-flash:generateContent while /health stays green.

Root cause

The proxy — not the upstream — was the binding deadline.

GEMINI_UPSTREAM_TIMEOUT was hardcoded to 90s, with the comment "keep non-streaming upstream calls
below observed Cloud Run request boundaries". But desktop-backend's Cloud Run request timeout is
actually 300s (gcloud run services describe desktop-backend --format='value(spec.template.spec.timeoutSeconds)' → 300),
and the Swift client waits 300s (GeminiClient.swift) and deliberately does not auto-retry timeouts.

So the 90s guess was ~3.3x tighter than the real bound, and it aborted generations the model had
already spent the money to produce.

Prod evidence (last 6h, desktop-backend Cloud Logging)

  • 11 of 1000 /v1/proxy/gemini unary calls returned 504 (~1.1%).
  • Every 504 had latency 90.03–90.13s — our own timeout firing, not an upstream failure.
  • All were phase=request status=timeout provider=vertex_ai model=gemini-2.5-flash,
    payload_bucket 16–512kb.
  • Successful calls reach 84.5s, and 6 completed in the 60-120s bucket — the latency tail
    straddles the cap, so the cap was slicing through live traffic.

Upstream premise verified against real prod Vertex AI

Long-context 2.5-flash spends most of its wall-clock thinking, before the first response byte:

request result
181 KB / 40k prompt tokens 200 in 64.3s (7,863 thinking tokens)
741 KB / 150k prompt tokens 200 in 95.5s, full valid answer

The second one would have been 504'd at 90s — a successful generation thrown away, and the user
shown "AI request took too long".

Fix

Derive the deadline from the platform bound instead of hardcoding a guess:

const CLOUD_RUN_REQUEST_TIMEOUT: Duration = Duration::from_secs(300);
const GEMINI_UPSTREAM_HEADROOM_SECS: u64 = 60;
const GEMINI_UPSTREAM_TIMEOUT: Duration =
    Duration::from_secs(CLOUD_RUN_REQUEST_TIMEOUT.as_secs() - GEMINI_UPSTREAM_HEADROOM_SECS); // 240s

This closes the failure class rather than re-tuning a number: the deadline can no longer drift above
the platform timeout, so the proxy always remains the component that gives up first and clients keep
getting our typed, retryable upstream_timeout JSON instead of an opaque platform 504.

Streaming is untouched (it correctly has no total-response timeout). Error classification, structured
upstream_result logging, and the typed 504 body already landed in #8911 — this fixes the remaining
defect: the deadline itself.

Regression test

The existing test hardcoded the very bound that was wrong (GEMINI_UPSTREAM_TIMEOUT <= 90s), so it
would have locked the bug in. It now asserts the real contract: strictly below the platform
timeout, ≥30s flush headroom, and generous enough to cover the observed completion tail.

Verification

  • cargo test proxy:: → 78 passed, 0 failed
  • cargo clippy → clean (no warnings)
  • cargo check → clean
  • Prod log analysis + real prod Vertex timing runs above

Not exercised: an authenticated >90s request through the running proxy — that needs a signed-in
desktop session and Omi Dev is not signed in on this machine. The upstream premise and the constant
contract are proven; the passthrough itself is not path-exercised.

🤖 automated by hourly watchdog

Review in cubic

The desktop Gemini proxy self-imposed a 90s deadline on non-streaming
generateContent. The constant was sized to stay "below observed Cloud Run
request boundaries", but desktop-backend's actual Cloud Run request timeout
is 300s and the Swift client waits 300s -- so the 90s guess was ~3.3x too
tight and destroyed generations the model had already paid for.

Root cause: the proxy, not the upstream, was the binding deadline.

Prod evidence (last 6h, desktop-backend):
- 11 of 1000 /v1/proxy/gemini unary calls returned 504 (~1.1%)
- every 504 latency was 90.03-90.13s -- our own timeout, not upstream
- all were phase=request status=timeout, provider=vertex_ai,
  model=gemini-2.5-flash, payload_bucket 16-512kb
- successes reach 84.5s, and 6 completed in the 60-120s bucket: the tail
  straddles the cap

Upstream premise verified against real prod Vertex AI:
- 181KB / 40k-token request -> 200 in 64.3s (7,863 thinking tokens)
- 741KB / 150k-token request -> 200 in 95.5s with a full valid answer
The second would have been 504'd at 90s. Long-context 2.5-flash spends most
of its time thinking before the first response byte.

Fix: derive the deadline from the platform bound (300s - 60s headroom = 240s)
instead of hardcoding a guess, so it can never drift above Cloud Run's timeout
and the proxy still owns timeout mapping (typed, retryable upstream_timeout
body rather than an opaque platform 504).

The existing test hardcoded the wrong bound (<= 90s); it now asserts the real
contract: below the platform timeout, with >= 30s flush headroom, and generous
enough to cover the observed completion tail.

Verification: cargo test proxy:: -> 78 passed; cargo clippy clean; cargo check
clean. NOT exercised: an authenticated >90s request through the running proxy
(needs a signed-in desktop session; Omi Dev is not signed in on this machine).
@kodjima33
kodjima33 merged commit f2cf866 into main Jul 12, 2026
23 of 26 checks passed
@kodjima33
kodjima33 deleted the watchdog/issue-9135-gemini-proxy-timeout branch July 12, 2026 18:18
Git-on-my-level added a commit that referenced this pull request Jul 29, 2026
…, sync annotation ratchet (#9634)

## What this is

Three mechanical regression guardrails plus the written rules behind
them, derived from an internal audit of our own recent merge history. No
behavior changes; the bug fixes the research surfaced will land as
separate PRs.

> **Revised after review** (thanks @Git-on-my-level): the PR scope check
is now **advisory-only** — it reports and warns but never blocks, so it
can never force a feature split. The override/label machinery that
existed to waive the old fail tier is deleted. Details in item 1.

## The research

We audited the last ~30 merged PRs and found **9 confirmed regression
pairs** — a merged PR that introduced a production bug, and a later PR
that fixed it. Three PRs each shipped 2+ regressions. We then ran a
controlled replay experiment: 18 independent blind pre-merge reviews
across 7 of the bug-introducing PRs (reviewers were never told a bug
existed), scored against pre-registered ground truth.

Key findings:

1. **Diff size predicts regressions.** Every recent PR above ~2,400
changed production-source lines shipped at least one regression (2,475
lines → 3 regressions incl. a paying user locked out of sync; 2,652 → 1;
51,564 → 4+ regressions). Review catch-rate collapses with size: a
one-line type bug in a 61-file PR evaded six independent reviewers.
2. **CI coverage can silently rot.** The 51k-line PR also deleted two
pytest invocations from `backend/test.sh` while the test files stayed in
the tree; nothing failed. (A later runner rewrite to directory discovery
happened to heal it — by luck, not by guard.)
3. **Type confusion ships when annotations are missing.** The
`source=unknown` misattribution bug (fixed in #9588) flowed through an
*unannotated* `source` parameter in `utils/sync/pipeline.py` that a
metering string shadowed. The enforced pyright lane had nothing to
check.
4. Two recurring patterns had no written rule: new fail-closed gates
shipping with no satisfiable path for existing users/clients/keys (two
incidents), and tests rewritten in the same PR to assert the new — wrong
— constant (shipped a 9-day prod timeout regression, fixed in #9583).

## What this PR adds

**1. PR scope advisor** (`.github/scripts/check_pr_scope.py`, manifest
check `pr-scope` — runs in the local pre-push lane and CI,
**advisory-only, never blocks**)
Counts changed production-source lines (tests across all platform
conventions, docs, l10n, lockfiles, generated files excluded;
rename/quotePath-safe via `--no-renames` + C-quote handling). ≥1,500
emits a warning annotation; ≥3,000 warns that in the audited merge
history every PR this size shipped a regression review missed — so the
reviewer calibrates skepticism to the diff, and splits only when the
pieces are independently verifiable without extra human verification
passes. Exit code is always 0 on a countable diff; push events
(post-merge `main`) are notice-only. Because nothing blocks, there is no
waiver machinery — no override label, no env escape hatch, no label
plumbing.

**2. Unit-test discovery ratchet**
(`backend/scripts/check_unit_test_discovery.py`, wired into Backend Unit
Tests before dependency install)
Fails when any test file under `backend/tests/` or `backend/testing/` is
not selected by the unit runner, not verified against its dedicated
runner workflow (the workflow file must exist and actually reference the
tree — or, for explicit-list workflows like the GPU suite, name the
individual file), not policy-excluded (live integration/eval), and not
allowlisted. Allowlists only shrink. This audit itself surfaced that
`tests/container/test_parakeet_vram_stress.py` is currently run by no
workflow — it is now explicitly tracked as a manual-only harness instead
of being silently vouched for.

**3. Parameter-annotation ratchet for the sync pipeline**
(`backend/pyrightconfig.json` + annotations)
`executionEnvironments` elevates `reportMissingParameterType` to error
for `utils/sync/` only, and this PR adds the five missing annotations —
one of which is the exact `source` parameter from finding #3. Verified
against the introducing PR's merge state: the rule flags that
unannotated parameter at `pipeline.py:746`. Typed parameters make
str-vs-enum confusion visible to pyright at annotated sinks and
same-scope assignments (verified in isolation on pyright 1.1.403).

**4. AGENTS.md rules** — PR size is *reported, not bounded* (matching
the advisory check), mechanical discovery enforcement, the
legacy-principal test rule for new fail-closed gates, and the
rewritten-test review lens. Each rule names its enforcement or the
shipped failure it prevents. The latter two rules cost agent/review
effort rather than human verification time.

## What this deliberately does not do

- No bug fixes — the still-open defects the audit found are being
filed/fixed separately.
- No blocking on size, in either direction: small diffs also ship bugs
(a 348-line PR shipped a blocker), and forcing large diffs to split
multiplies human verification passes. The advisor only informs review
depth.
- The scope check lives in the checks manifest like every other
deterministic check (no exemptions).

## Verification

- `python3 .github/scripts/test_check_pr_scope.py` → 9 tests OK
(classification, counting, advisory tiers, push notice-only).
- Replayed the advisor against the four historical PRs listed above (892
/ 2,738 / 2,665 / 47,938 lines) → notice/warn/warn/warn, all exit 0; on
this PR itself → 472 changed production-source lines (notice).
- `backend/scripts/check_unit_test_discovery.py` on the real tree → `564
selected, 49 covered by other runners/allowlist, 0 orphans`; a seeded
`tests/<newdir>/test_orphan.py` fails the check with an actionable
message.
- `pytest tests/unit/test_check_unit_test_discovery.py` → 8 passed.
- `bash backend/scripts/typecheck.sh` (enforced pyright lane, pinned
1.1.403, full deps) with the new ratchet → **0 errors**; the rule
replayed against the introducing PR's merge state flags the unannotated
`source` param.
- `python3 -m py_compile backend/utils/sync/pipeline.py` → passes;
annotations are runtime-inert.
- `actionlint` on both changed workflows → clean.
`.github/scripts/test_run_checks.py` (manifest drift guard) → OK.
`.github/scripts/test_pr_preflight.py` → OK.
- Full local manifest lane after the advisory rework → 16 checks passed.
- Post-review hardening verified earlier in the PR: Swift/JS test-tree
classification, quoted non-ASCII paths, seeded unwired
`tests/container/` file IS flagged, pyright lane 0 errors, sync unit
files 273 passed, Agent Runtime tool-surfaces 104 passed.
- Full `backend/test.sh` run (564 files): 562 files green in the
parallel run; the two failures were environmental and pass on rerun —
`test_rendered_deployment_contract.py` needed `helm` on PATH (8 passed
once installed), and `test_sync_v2.py` tripped only the per-test
CPU-timing guard under saturated parallel load (all 161 tests pass;
clean and fast in isolation).

## Product invariants affected

None — no product behavior changes; CI/tooling, type annotations, and
docs only.


## Failure class
Failure-Class: none

(This PR ships CI guardrail tooling; its fix commits repair the
guardrail scripts themselves, not a registered product failure class.)
@undivisible undivisible added the AI label Aug 10, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

desktop-backend Gemini proxy returns persistent 504s while /health stays green

2 participants