Repository navigation
fix(desktop): stop cutting off long-context Gemini calls at 90s (#9135) - #9583
Merged
Merged
Conversation
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).
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.)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #9135.
Bug (live on prod)
The desktop Gemini proxy returns persistent
504s on/v1/proxy/gemini/models/gemini-2.5-flash:generateContentwhile/healthstays green.Root cause
The proxy — not the upstream — was the binding deadline.
GEMINI_UPSTREAM_TIMEOUTwas hardcoded to 90s, with the comment "keep non-streaming upstream callsbelow observed Cloud Run request boundaries". But
desktop-backend's Cloud Run request timeout isactually 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-backendCloud Logging)/v1/proxy/geminiunary calls returned504(~1.1%).504had latency 90.03–90.13s — our own timeout firing, not an upstream failure.phase=request status=timeout provider=vertex_ai model=gemini-2.5-flash,payload_bucket16–512kb.60-120sbucket — the latency tailstraddles 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:
200in 64.3s (7,863 thinking tokens)200in 95.5s, full valid answerThe 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:
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_timeoutJSON instead of an opaque platform 504.Streaming is untouched (it correctly has no total-response timeout). Error classification, structured
upstream_resultlogging, and the typed 504 body already landed in #8911 — this fixes the remainingdefect: the deadline itself.
Regression test
The existing test hardcoded the very bound that was wrong (
GEMINI_UPSTREAM_TIMEOUT <= 90s), so itwould 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 failedcargo clippy→ clean (no warnings)cargo check→ cleanNot 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