Skip to content

backend-go: add durable LLM gateway idempotency - #25819

Merged
Git-on-my-level merged 25 commits into
mainfrom
agent/m1-studio-codex-sol/32c93a64ee28-gateway
Nov 21, 2026
Merged

Git-on-my-level merged 25 commits into
mainfrom
agent/m1-studio-codex-sol/32c93a64ee28-gateway

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Nov 19, 2026 •

Copy link
Copy Markdown
Member

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.

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

@Git-on-my-level
Git-on-my-level marked this pull request as ready for review November 20, 2026 12:49
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-21T01:50:11.038434Z 252e228 New commits
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@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: e054bb3b5a

ℹ️ 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".

project = os.getenv(DATA_PLANE_ENV, '').strip()
if not project:
raise IdempotencyError(503, 'idempotency_store_unavailable')
from database._client import get_pinned_data_plane_firestore_client

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Move the new function-local imports to module scope

The backend guide explicitly requires “All imports at module top level — never inside functions.” This new function-local import violates that documented convention, as do the local imports in the two new idempotency test modules. Move these imports to module scope; the Firestore client can still be constructed lazily when the helper is called.

AGENTS.md reference: backend/AGENTS.md:L166-L168

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 390544d: the import is now at module scope in idempotency_store.py (from database import _client as firestore_clients, called through the module so existing monkeypatches still apply). The local imports in both idempotency test modules also moved to module top level. The gateway already imports database._client at module load through accounting_sink, so this adds no new import-time side effects.

Git-on-my-level and others added 3 commits November 21, 2026 05:08
Resolve the validate_rendered_deployment_contract.py conflict by keeping
both contract fields: the gateway's optional_scoped_secrets and main's
prod-only extra_secret for listen. Diagnostics stay value-free, as the
gateway review required, so the listen test now asserts the generic
message and checks that prod accepts the extra secret.

Move the function-local imports in idempotency_store.py and both
idempotency test modules to module scope (backend/AGENTS.md). The store
calls through the database._client module so existing monkeypatches
still apply.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Worker 1 FIX on 390544d:
- Validate secretKeyRef name and key as non-empty strings before the
  allowed-secret membership test, so a YAML list or mapping fails with a
  value-free diagnostic instead of an uncaught TypeError. Regression
  covers list, mapping and int for both fields.
- The listen prod check now builds a real prod Deployment fixture: both
  refs validate clean, and the private ref alone still yields the
  required shared-ref error.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Git-on-my-level added a commit that referenced this pull request Nov 21, 2026
…teEnv (#25907)

## What


`test_record_seal_cluster_repair_deploy.py::test_cpu_admission_switch_is_declared_in_runtime_manifest_and_listen_chart`
fails on main. It renders the backend-listen chart with `--set-string
privateEnv.<key>=false` for every stage. Since #25660 the chart fails
when `privateEnv` is set alongside `privateSecretEnv`, which prod now
uses, so prod's `helm template` exits 1.

Main's changed-file selector rarely picks this file, so it hid until PRs
touching the charts selected it. It showed up on #25819.

## Change

Head `f2618fc6fa05e0562ad5040d4b894803461b9838`. Test, selector and docs
only.
- On stages whose values set `privateSecretEnv` (prod), the test asserts
the chart refuses the literal overlay with the "privateEnv is retired"
message. That is the stronger guarantee now: the switch can only change
through the Secret Manager document.
- Dev keeps the existing override render check.

- Prod also renders without the overlay and asserts the switch is
`true`. The branch matches the chart guard (`privateSecretEnv.keys`).
- `select_backend_unit_tests.py` selects this test for
`backend/charts/backend-listen/` changes, so it can't go stale
unselected again.
- `listen_pusher_pipeline.mdx` no longer tells operators to roll back
the seal overlap switch on prod listen with a `privateEnv` override,
which prod refuses. It documents the values-file PR plus listen deploy
path instead. Change note:
`docs/listen_pusher_pipeline/changes/2026-11-20-seal-overlap-rollback-prod-listen.md`.

These address all six panel findings (review-20261120t232252-b825).
There is no chart, manifest or runtime change.

## Verification

`pytest tests/unit/test_record_seal_cluster_repair_deploy.py` passes
15/15 locally with Helm, and 205 pass across the selector,
workflow-contract and seal tests. The prior prod failure reproduced at
main `9bf1acd`.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
kriegcloud pushed a commit to kriegcloud/omi that referenced this pull request Nov 21, 2026
…teEnv

Since BasedHardware#25660 the backend-listen chart fails when privateEnv is set
alongside privateSecretEnv, which prod now uses. The CPU admission switch
test still passed --set-string privateEnv.<key>=false for every stage,
so prod's helm render exited 1. Main's selector rarely picks this file,
so it hid until PRs touching the chart selected it (seen on BasedHardware#25819).

On stages with privateSecretEnv, assert the chart refuses the literal
overlay, the stronger guarantee now. Dev keeps the existing override
render check.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Git-on-my-level added a commit that referenced this pull request Nov 21, 2026
…ts extension (#25910)

## What

The flag budget's `review_by` for `LISTEN_BATCH_RECONNECT_ENABLED` was
2026-11-20. That date lapsed at 00:00Z Nov 21, so
`test_flag_budget.py::test_pipeline_env_surface_holds_its_budget` fails
on every branch that selects it. It showed up on #25819.

## Change

Head `b53d19f5da84366018c45db8d0c09bae7878245d`. This is config and test
only.
- `config/feature-flags.yaml` already extends this flag the reviewed
way: `extension.until: 2026-11-23`, from David's 2026-11-17 bulk ruling
("extend; next step due 2026-11-23"). The registry check forbids moving
`review_by` later directly, so the registry is **unchanged**.
- `backend/config/flag_budget.json` renews only the budget `review_by`
to 2026-11-23, with a reason.
- `test_reconnect_dark_rollout_has_a_dated_release_ramp` now asserts
that the budget `review_by` equals `extension.until`. The registry dates
stay pinned at 2026-11-20.

There is no runtime change. The flag stays default-off and fail-closed,
and expansion stays with Release and Quality. The next step is due
2026-11-23. Rollback is a revert.

## Verification

- `tests/unit/test_flag_budget.py`: 26 passed.
- `scripts/check_feature_flag_registry.py`: exit 0.
- Wider registry-reading suites: 565 passed.

🤖 Generated with [Claude Code](https://claude.com/claude-code)


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/25910?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="View guided diff"
src="https://www.cubic.dev/buttons/review-in-cubic-light.svg"></picture></a>
<a
href="https://www.cubic.dev/action/auto-fix/pr/BasedHardware/omi/25910?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F25910&source=description"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"><img
alt="Turn on auto-fix"
src="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"></picture></a>
<!-- End of auto-generated description by cubic. -->
@Git-on-my-level
Git-on-my-level merged commit 4f32df4 into main Nov 21, 2026
69 checks passed
@Git-on-my-level
Git-on-my-level deleted the agent/m1-studio-codex-sol/32c93a64ee28-gateway branch November 21, 2026 02:07
Git-on-my-level added a commit that referenced this pull request Nov 21, 2026
Current head is `32767107c6e291114a5cacd83233c847998472a7`: a clean
merge of main (with gateway #25819 at `4f32df47`) onto `62cad69d94e1`,
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. `Replayable` exposes paid submission and recovery
together. The family port must require both methods and pass
`Run.Job().CreatedAt` unchanged. 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

| Finding | Evidence |
| --- | --- |
| F1 and F5, stable paid key, recovery and replay capability |
`TestReplayableRecoversAndReplaysAfterTheFirstResponseIsLost` exercises
two independent clients and one provider dispatch after a lost response.
`TestOperationIDSurvivesReplayAndSeparatesJobsAndSteps` pins the UUID.
`TestOlderGatewayCannotDispatchThroughTheUnkeyedRoute`,
`TestCompleteRejectsUnacknowledgedSuccess` and
`TestCompleteFencesPaidReplayByJobCreatedAt` cover rollout and retention
fences. `TestRecoverLooksUpTheSameKeyWithoutPosting` covers lookup
results. |
| F2 and F9, malformed BYOK keys and managed-only lanes |
`TestBYOKControlsAndManagedOnlyLanesAreRejectedLocally` covers internal
and trailing newline keys, v3 and both pilot bundles. |
| F3 and F4, transient provider and service-auth faults |
`TestGatewayFailureEnvelopesMapToQueueOutcomes` covers BYOK provider
failures wrapped in 401, transient service 401/403, and deterministic
credential and deletion errors. |
| F6, accounting overrides | `TestCompleteSendsFeatureLaneAndAccounting`
sends an explicit L1 override and verifies the normalized header and
payload. |
| F7 and F11, cancellation, redirects and scheme casing |
`TestCanceledContextAndRedirectNeverDispatch` covers both canceled
methods and a 302 from an uppercase-scheme base URL. Go's URL parser
already normalizes the scheme. |
| F8, schema capability | `TestStrictSchemaRequiresGatewayLaneSupport`
covers local rejection on unsupported lanes and schema forwarding on the
three supported non-pilot lanes.
`TestStructuredBundlesUseStrictSchemaAndVersionMetadata` covers the
pilots. |
| F10, bounded error envelopes |
`TestGatewayFailureEnvelopesMapToQueueOutcomes` covers HTTP status
fallback when the error envelope exceeds the documented 64 KiB decoding
window. |

- `go test -race ./internal/adapters/llmgateway` passed.
- `cd backend-go && TEST_FIRESTORE_REQUIRED=1 make check` passed with
Postgres 16 and the Firestore emulator.

## Second panel

| Finding | Resolution and evidence |
| --- | --- |
| F1 | Both app lanes use the same `conv_apps` attribution as Python.
`TestCompleteSendsFeatureLaneAndAccounting` verifies outbound headers
and metadata. |
| F2–F4 | `TestGatewayFailureEnvelopesMapToQueueOutcomes` covers BYOK
classification beyond 16 KiB, fallback beyond 64 KiB, retryable bare and
non-JSON 404s, rejected model 404s, and indeterminate missing-claim
POSTs. |
| F5 | The binary can size the idle pool to its worker count and call
`Close` on shutdown.
`TestGatewayPoolReusesConnectionsAndCloseReleasesThem` verifies
configuration and socket reuse before and after close. |
| F6–F7 | `TestCompleteFencesPaidReplayByJobCreatedAt` covers 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. |
| F8 | `TestRecoverLooksUpTheSameKeyWithoutPosting` covers missing and
mismatched acknowledgements. Both yield `ErrNotCommitted`. |
| F9 | `TestDispatchChecksTheGuardAfterRequestConstruction` verifies an
expired guard stops a previously constructed request at the shared
dispatch boundary. |

The focused adapter race suite and full Go `make check` passed on M1
under `omi-heavy` with a 10-minute execution timeout.

## Product invariants affected

none
Git-on-my-level added a commit that referenced this pull request Nov 21, 2026
…eapply (#25911)

## Summary

A gateway-only production release can now skip reapplying the shared
`<env>-omi-backend-secrets`. The gateway credential presence check still
runs.

- `.github/workflows/gcp_llm_gateway.yml`: new `workflow_dispatch` input
`skip_backend_secrets`. It defaults to `false`, so current behaviour is
unchanged. It is passed to the deploy step as `SKIP_BACKEND_SECRETS`,
which `deploy-llm-gateway.sh` already honors.
- `backend/scripts/deploy-llm-gateway.sh`: the skip branch now wraps
only `deploy-backend-secrets.sh`. The read-only presence check for
`ANTHROPIC_API_KEY`, `METRICS_SECRET` and
`OMI_LLM_GATEWAY_SERVICE_TOKEN` moves out of it and runs on every
non-dry-run release. A skipped reapply still fails closed on a missing
or empty credential.
- `backend/tests/unit/test_llm_gateway_deploy_contract.py`: pins the
ordering, the input and the step env. It fails against the previous
script.
- `.github/ci-budget.yaml`: records the new dispatch input, plus a
one-minute p50 bump on both gateway jobs, following the precedent for
trigger changes. The workflow is still manual-only, with no PR runs.

Why: SCA-3305. Release is holding the #25819 gateway rollout because the
only prod path writes the shared backend secret. Release recommended a
reviewed gateway workflow that skips that write.

Rollback: revert this PR. The default-false input means no behaviour
change until a dispatch sets it.

## Verification

Head: 52363b3


- `pytest backend/tests/unit/test_llm_gateway_deploy_contract.py`:
passes. Mutation check: the new test fails on the old script.
- `python3 .github/scripts/check_ci_budget.py --base origin/main`:
passed.

## Product invariants affected

- INV-DATA-1: unaffected. The change routes nothing and changes no
project or endpoint. It only lets a dispatch skip a secret write; the
target cluster, image and data plane are unchanged.

Failure-Class: none

🤖 Generated with [Claude Code](https://claude.com/claude-code)


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/25911?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="View guided diff"
src="https://www.cubic.dev/buttons/review-in-cubic-light.svg"></picture></a>
<a
href="https://www.cubic.dev/action/auto-fix/pr/BasedHardware/omi/25911?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F25911&source=description"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"><img
alt="Turn on auto-fix"
src="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"></picture></a>
<!-- End of auto-generated description by cubic. -->
aryanorastar pushed a commit to TassioSales/omi that referenced this pull request Nov 21, 2026
…eapply

The production LLM gateway workflow always reapplies the shared
<env>-omi-backend-secrets before its Helm rollout, and it exposes no way
to skip that. A gateway-only release (BasedHardware#25819, SCA-3305) therefore needs a
shared-secret write that the change does not require. Release is holding
the rollout on it.

deploy-llm-gateway.sh already honors SKIP_BACKEND_SECRETS. Expose it as
the workflow input skip_backend_secrets, default false so current
behaviour is unchanged. Move the read-only credential presence check out
of the reapply branch, so a skipped reapply still fails closed when
ANTHROPIC_API_KEY, METRICS_SECRET or OMI_LLM_GATEWAY_SERVICE_TOKEN is
missing or empty. A contract test pins that ordering and the input; it
fails against the previous script.

Failure-Class: none
Co-Authored-By: Claude Opus 5.5 <[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.

1 participant