Repository navigation
backend-go: add the finalization LLM gateway adapter - #25803
Conversation
Current head is `252e228fe0157459ff5ec29bf37ef22305a91347`. It merges main (`7821f1a82103`, which includes the #25907 seal test fix and the #25910 flag-budget fix) onto Worker 1's shipped `d4db38f1ec6c`. The only manual resolution is a union of independent hash entries in `backend/tests/support/firestore_query_driver_registry.py`. There is no change to the gateway code or the validator. Worker 1's two findings on `390544de` are fixed: secretKeyRef name and key must be non-empty strings, and the listen test uses a real prod fixture. Earlier lead commits It resolves the validate_rendered_deployment_contract.py conflict by keeping both `optional_scoped_secrets` and main's prod-only listen `extra_secret`, with value-free diagnostics. It also moves the idempotency imports to module scope, per the module-scope review finding. ## Summary SCA-3176 adds durable idempotency to the Python LLM gateway. This gateway-only PR replaces the combined draft #25815. The Go adapter and its review fixes belong in #25803. - Keyed non-streaming calls claim the authenticated operation transactionally before a single provider dispatch. Matching requests replay the committed response. Lookup never dispatches, and unkeyed calls retain their existing behavior. - Firestore retains claims for 30 days from first claim and encrypted results for 24 hours from settlement, capped by claim expiry. Replays do not extend retention. A stale worker cannot settle an operation after the claim has expired or been replaced. - `LLM_GATEWAY_IDEMPOTENCY_ENABLED` defaults on. Setting it to `off` refuses keyed submissions and lookups before provider dispatch. Claim, settlement and lookup transactions read the account deletion marker. ## Queue horizon and rollout The default Go queue allows five work attempts, twenty reconciliation retries, one automatic work-budget requeue after 45 minutes, a 60-second lease and backoff capped at 30 seconds. Counting two full cycles, including a spare reconciliation slot per cycle, gives at most 123 minutes of nominal lease and scheduled-backoff time under those defaults. The calculation excludes time spent without a ready worker, larger caller delays, BYOK gates and operator redrive. The default BYOK abandonment interval is 14 days. The queue's count budgets do not impose an absolute job age. Before keyed Go traffic is enabled, the paid path must enforce a 29-day cutoff from durable job creation for every same-key submission, including takeover and manual redrive. The 30-day claim TTL then covers the entire allowed replay horizon, including a one-day margin. After Firestore deletes a claim, the gateway has no record of its prior key. The release owner must activate `expires_at` TTL on both Firestore collection groups before rollout. The production readback is zero excess provider dispatches per 1,000 keyed POSTs with replay traffic and complete accounting coverage. ## Verification - Backend Go `make check` with Postgres 16 and Firestore required. - Focused gateway unit tests through `backend/test.sh` and seven Firestore-emulator tests, including expired-claim and stale-settlement coverage. - Offline retention plan lists exactly the claim and result groups. The emulator test simulates TTL deletion because the emulator does not run the TTL sweeper. - Repository preflight and managed push hooks. | Rule | Test | | --- | --- | | Concurrent replay, body or credential conflict, scoped lookup and one accounted dispatch | `test_replay_and_lookup_use_one_dispatch_across_clients` | | Timeout and expired result never redispatch while the claim is retained | `test_provider_timeout_and_result_expiry_keep_the_claim` | | Fixed claim expiry and rejection of late settlement after deletion or replacement | `test_claim_expiry_does_not_renew_or_allow_a_stale_settlement` | | Lost commit acknowledgement and account deletion | `test_failed_commit_and_account_deletion_fail_closed`, `test_deletion_started_during_dispatch_prevents_settlement` | | Request and result size limits | `test_keyed_request_bounds_reject_before_storage_or_provider`, `test_oversized_result_is_never_returned_or_dispatched_again` | | Default-on protocol and fail-closed switch with unkeyed traffic preserved | `test_replay_and_lookup_use_one_dispatch_across_clients`, `test_kill_switch_fails_keyed_calls_closed_and_leaves_legacy_open` | ## Panel follow-up - F1 adds the gateway proofs to `backend-emulator-proofs.yml` for both push and PR changes and registers the suite in `run-emulator-proofs.sh`. The CI-budget inventory includes the trigger expansion and forecasts one additional daily run at the existing p50. - F2 pins the two Firestore TTL resources to the store collection constants with `test_ttl_policy_covers_exactly_the_gateway_claim_and_result_collections`. - F3 exercises simultaneous fresh claims in `test_concurrent_fresh_claims_have_one_winner`. The emulator returns one winner and one 409 pending. - On M1, the three focused unit tests, seven Firestore-emulator tests, runner shell syntax and full Go `make check` passed under `omi-heavy` with a 10-minute execution timeout. ## Astra follow-up - A1 pins keyed storage to the customer project through a dedicated setting and fails closed before a claim if the project is unset or cannot be resolved. The rendered dev values exercise the split between compute and customer projects. The release owner must verify the gateway identity's customer-plane permissions before admitting traffic. - A2 makes the dedicated operations POST the sole keyed submission URL. All keyed contract tests use it. The ordinary chat route rejects the header before dispatch. - A3 isolates claims and lookups in an eight-worker executor with eight queue slots and immediate 503 on saturation. The re-review adds separate reserved settlement capacity. - A4 uses the durable claims and ledger reconciliation below. When a crash can hide dispatch, the rate stays unknown. - A5 rejects proactivity feature or identity markers before claim and replay. Emulator tests exercise both request orders for each marker. - A6 records the key version per claim and supports two-key rolling rotation. The gateway-only rotation secret keeps the old key for 30 days after the last old writer drains. Mixed replicas can read both versions, and absent versions fail closed. - A7 requires an absent stream field or literal false. The request bounds test covers malformed values, and the emulator exercises a valid false. M1 verification via bounded `omi-heavy`: 62 tests passed across the gateway contract, rendered deployment, client-plane and real Firestore emulator suites, including all 12 gateway emulator cases. Rendered deployment validation passed for seven services in both environments. Three synthetic readback fixtures covered a fully accounted operation, a silent crash with a visible duplicate elsewhere, and an orphan ledger scope. Repository preflight passed 56 checks. Go `make check` passed with private PostgreSQL 16 and Firestore using `GOFLAGS=-p=1` after the parallel run hit a test that terminates matching database sessions across packages. The three panel fixes remain in this PR. ## Astra re-review follow-up - Reserve one of eight settlement slots before reading the keyed body or creating a claim. Only permit holders submit to the separate settlement executor. A canceled waiter cannot give away a running worker's permit. The emulator commits and replays a paid result while every claim and lookup slot is occupied. - Fingerprint ordered property names for each structured-output schema object, including nested objects. Reordered envelope fields still replay. - Look up ledger-only scopes by their customer Firestore claim path. A confirmed out-of-window claim drops out of the cohort. A genuinely missing claim still leaves coverage unknown. - Stamp originating environment on claims and keyed accounting rows. The first readback uses prod rows and the prod POST counter. Bounded M1 verification passed 57 tests, including 14 Firestore emulator cases, and deployment validation for 14 rendered service and environment combinations. The SQL fixture exercises a confirmed boundary claim, a genuinely missing claim, a silent crash and overlapping dev rows. ## Queued-settlement cancellation A submitted settlement outlives cancellation of the HTTP waiter, even if its worker has yet to start. The underlying worker future owns the permit through completion. The Firestore emulator regression holds a submitted settlement before worker start, cancels the POST, and verifies that lookup and replay recover the same result after exactly one provider dispatch. The regression reproduced early permit release on the prior head. Bounded M1 verification passed 58 tests, including 15 Firestore emulator cases, and all 14 rendered deployment contracts. ## CI follow-up after cancellation review Current head is `e054bb3b5a4b4f7b5e2ab30c03e2b5af1a015e5b`: a plain merge of main (`6216831cffb4`) onto the reviewed `8e3c2c76015b`, with no conflicts. All 65 checks are green at this head. The reviewed cancellation implementation and emulator regression are byte-identical to `1de8372393`. The automatic dev scope tests now verify both outputs, including workerd-only changes and an emulator-workflow-only no-op. Rendered deployment diagnostics report contract field names and generic render errors without logging actual manifest values or Helm output. Tests use synthetic values to exercise both paths. Bounded M1 verification passed 72 tests and verified all 14 rendered deployment combinations. ## YAML decoding diagnostic follow-up The Helm YAML decoder maps ordinary parser and constructor exceptions to one fixed error without chaining the original traceback. The CLI regression feeds a synthetic scalar to the real PyYAML boolean constructor and checks stdout, stderr, the exit status, and the controlled diagnostic. It exposed the marker on the previous implementation. The deploy-scope tests and cancellation implementation remain identical to the reviewed head. ## Production readback query Measure excess provider attempts per 1,000 keyed POSTs over a settled window that contains replay traffic. The first production readback uses only `prod`. The dev and prod charts set `LLM_GATEWAY_IDEMPOTENCY_ENVIRONMENT` explicitly. It stamps new claims, keyed ledger rows and the keyed POST counter. Use `sum(increase(llm_gateway_keyed_posts_total{environment="prod"}[<window>]))` as the denominator, evaluated at the window end. Collect the read-only inputs before claim TTL or account erasure can remove cohort records. - `claims` projects the customer Firestore claim document ID as `scope`, plus `state`, `started_at` and `environment`. Extract the chosen environment and `window_start <= started_at < window_end` from the `llm_gateway_idempotency_claims` collection group. If the range index is unavailable, scan those projected fields during the bounded rollout and apply the same filters in the extract. - `attempts` projects `idempotency_scope AS scope`, `attempt_id`, `occurred_at` as a timestamp, and `idempotency_environment AS environment` from the participating replicas' `llm_gateway_attempts` ledgers. Extract rows in the chosen environment for each cohort scope, including late rows after window end, and all scoped ledger rows occurring within the window. Keep `user_uid` for the next lookup only. - `claim_lookup` contains point reads in customer Firestore for every in-window ledger scope absent from the claim cohort. Read `users/{user_uid}/llm_gateway_idempotency_claims/{scope}` and project `scope`, `started_at` and `environment` for found documents. Only a matching-environment claim confirmed outside the window excludes a ledger-only scope. Missing claims, mismatched stamps, and found claims that should have been in the extract leave coverage unknown. Treat lookup errors as an incomplete measurement. Run the query with `@environment = 'prod'`, `@window_start` and `@window_end` matching the scrape window, and `@keyed_posts` set to the environment-filtered denominator. A committed pre-dispatch rejection with no ledger row is conservatively unknown as well. ```sql WITH cohort AS ( SELECT scope, state FROM claims WHERE environment = @Environment AND started_at >= @window_start AND started_at < @window_end ), by_scope AS ( SELECT scope, COUNT(DISTINCT attempt_id) AS attempts, MAX(CASE WHEN occurred_at >= @window_start AND occurred_at < @window_end THEN 1 ELSE 0 END) AS in_window FROM attempts WHERE environment = @Environment GROUP BY scope ), scoped AS ( SELECT c.scope, c.state, COALESCE(a.attempts, 0) AS attempts, 1 AS has_claim FROM cohort AS c LEFT JOIN by_scope AS a ON c.scope = a.scope UNION ALL SELECT a.scope, NULL AS state, a.attempts, 0 AS has_claim FROM by_scope AS a WHERE a.in_window = 1 AND NOT EXISTS (SELECT 1 FROM cohort AS c WHERE c.scope = a.scope) AND NOT EXISTS ( SELECT 1 FROM claim_lookup AS l WHERE l.scope = a.scope AND l.environment = @Environment AND (l.started_at < @window_start OR l.started_at >= @window_end) ) ), coverage AS ( SELECT COALESCE(SUM(CASE WHEN attempts > 1 THEN attempts - 1 ELSE 0 END), 0) AS observed_excess, COALESCE(SUM(CASE WHEN state = 'committed' AND attempts > 0 THEN 0 ELSE 1 END), 0) AS unknown_scopes, COALESCE(SUM(has_claim), 0) AS claims FROM scoped ) SELECT observed_excess, unknown_scopes, claims, CASE WHEN unknown_scopes = 0 AND claims > 0 THEN 1000.0 * observed_excess / NULLIF(@keyed_posts, 0) END AS excess_per_1000_keyed_posts FROM coverage; ``` Require complete claim and ledger extracts. Independently compare the keyed provider-attempt and accounting-delivery counter deltas from the same environment's scrape targets. A known extract or counter gap makes coverage unknown. Accept the zero target only with a nonempty cohort, replay traffic, and complete coverage. A claim removed by TTL or erasure makes the affected window incomplete. Track replay, conflict, pending, indeterminate, saturation and storage errors in `llm_gateway_idempotency_outcomes_total`. ## Environment isolation Gateway idempotency hashes the configured environment into the operation scope. Claim, replay, lookup and settlement reject records from a different environment. The Firestore emulator proof uses the same `based-hardware` customer project, caller, user, tenant, and key for dev and prod. It proves each environment dispatches once and can recover only its own response. It also exercises mismatched claim and result records. After merging `origin/main`, all 19 gateway Firestore emulator tests, 687 gateway unit tests, `make check` in `backend-go`, and the managed pre-push checks passed. The gateway dependency tests ran separately because the combined run leaves a mock configuration cached at both the pre-fix and fixed heads. ## Backend unit shard follow-up The pipeline lab proxy test matches each log row to its HTTP response using the call ID, since handlers can append rows out of response order. The runtime-image test fixture collects temporary objects after priming the checkout AST caches, and the synthetic COPY test reuses one registry template. The CI CPU-time limit and workflow diff are unchanged. Both files passed the CI unit runner with its one-second CPU-time guard (126 tests). All 19 gateway Firestore emulator cases and `make check` in `backend-go` also passed. ## Product invariants affected none
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 32767107c6
ℹ️ 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".
| if cause == CauseTransient || cause == CauseQuota || cause == CauseBYOKRateLimit || cause == CauseServiceAuth { | ||
| return queue.Classify(err, queue.Retry(cause, delay)) |
There was a problem hiding this comment.
Make BYOK throttle retries compatible with durable replay
When a forwarded BYOK call receives byok_rate_limit, this schedules a retry that cannot recover from the throttle. The gateway maps that failure to HTTP 429 (backend/llm_gateway/routers/openai_compatible.py::_status_code_for_error), and gateway/idempotency.py::complete commits every response below 500 and replays it on subsequent POSTs. Because Complete correctly preserves the same operation key, every retry receives the cached 429 without contacting the provider, even after the throttle clears; the job eventually exhausts its attempts without a completion. Coordinate the retry classification with gateway handling of retry-safe failures while preserving stable operation identity.
AGENTS.md reference: backend-go/AGENTS.md:L33-L35
Useful? React with 👍 / 👎.
Current head is
32767107c6e291114a5cacd83233c847998472a7: a clean merge of main (with gateway #25819 at4f32df47) onto62cad69d94e1, and the six adapter files are unchanged. Multica Worker 1 Codex (Sol) gave an independent SHIP at this exact head (SCA-3176, 02:48Z). The adapter is unwired, so paid rollout still requires the gateway to be serving.Summary
SCA-3176 adds the guarded Go adapter for finalization LLM calls and addresses the review panel. The Python storage and replay contract is in gateway-only PR #25819. This PR changes only the Go adapter.
The adapter sends a stable UUID derived from the guarded job and step to the required-key endpoint. An older gateway returns a retryable bare 404 without dispatch.
Replayableexposes paid submission and recovery together. The family port must require both methods and passRun.Job().CreatedAtunchanged. The adapter refuses a POST once the job reaches 29 days from that timestamp, inside the gateway's 30-day claim TTL. Recovery remains a tenant-scoped GET. Paid rollout requires #25819 to be deployed and both Firestore TTL policies to be active.First panel and verification
TestReplayableRecoversAndReplaysAfterTheFirstResponseIsLostexercises two independent clients and one provider dispatch after a lost response.TestOperationIDSurvivesReplayAndSeparatesJobsAndStepspins the UUID.TestOlderGatewayCannotDispatchThroughTheUnkeyedRoute,TestCompleteRejectsUnacknowledgedSuccessandTestCompleteFencesPaidReplayByJobCreatedAtcover rollout and retention fences.TestRecoverLooksUpTheSameKeyWithoutPostingcovers lookup results.TestBYOKControlsAndManagedOnlyLanesAreRejectedLocallycovers internal and trailing newline keys, v3 and both pilot bundles.TestGatewayFailureEnvelopesMapToQueueOutcomescovers BYOK provider failures wrapped in 401, transient service 401/403, and deterministic credential and deletion errors.TestCompleteSendsFeatureLaneAndAccountingsends an explicit L1 override and verifies the normalized header and payload.TestCanceledContextAndRedirectNeverDispatchcovers both canceled methods and a 302 from an uppercase-scheme base URL. Go's URL parser already normalizes the scheme.TestStrictSchemaRequiresGatewayLaneSupportcovers local rejection on unsupported lanes and schema forwarding on the three supported non-pilot lanes.TestStructuredBundlesUseStrictSchemaAndVersionMetadatacovers the pilots.TestGatewayFailureEnvelopesMapToQueueOutcomescovers HTTP status fallback when the error envelope exceeds the documented 64 KiB decoding window.go test -race ./internal/adapters/llmgatewaypassed.cd backend-go && TEST_FIRESTORE_REQUIRED=1 make checkpassed with Postgres 16 and the Firestore emulator.Second panel
conv_appsattribution as Python.TestCompleteSendsFeatureLaneAndAccountingverifies outbound headers and metadata.TestGatewayFailureEnvelopesMapToQueueOutcomescovers BYOK classification beyond 16 KiB, fallback beyond 64 KiB, retryable bare and non-JSON 404s, rejected model 404s, and indeterminate missing-claim POSTs.Closeon shutdown.TestGatewayPoolReusesConnectionsAndCloseReleasesThemverifies configuration and socket reuse before and after close.TestCompleteFencesPaidReplayByJobCreatedAtcovers one minute of clock skew, rejection past that allowance, and the exact replay cutoff on caller-supplied times. The family must supply the original durable timestamp.TestRecoverLooksUpTheSameKeyWithoutPostingcovers missing and mismatched acknowledgements. Both yieldErrNotCommitted.TestDispatchChecksTheGuardAfterRequestConstructionverifies an expired guard stops a previously constructed request at the shared dispatch boundary.The focused adapter race suite and full Go
make checkpassed on M1 underomi-heavywith a 10-minute execution timeout.Product invariants affected
none