Skip to content

backend-go: make finalization gateway calls idempotent - #25815

Closed
Git-on-my-level wants to merge 7 commits into
mainfrom
agent/m1-studio-codex-sol/32c93a64ee28-idempotency
Closed

Git-on-my-level wants to merge 7 commits into
mainfrom
agent/m1-studio-codex-sol/32c93a64ee28-idempotency

Conversation

@Git-on-my-level

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

Copy link
Copy Markdown
Member

Summary

SCA-3176 follow-up to #25803. This draft targets main and includes the original adapter commit while #25803 is open. The follow-up adds durable Python gateway idempotency, then switches the Go adapter to the keyed protocol.

  • A Firestore claim fences the authenticated caller, owner, tenant and UUID before a single provider attempt. The gateway replays a matching committed POST and rejects changes to the canonical body or credential context.
  • A committed result is encrypted and readable for 24 hours. The claim survives expiry and blocks redispatch after a crash, possible submission or lost result. Account deletion fences claim, lookup and settlement.
  • Go derives the key from the queue operation and uses the required-key endpoint. Older gateways return 404 on that endpoint without dispatch. Recover performs an authenticated GET for the same operation.
  • The protocol defaults on. LLM_GATEWAY_IDEMPOTENCY_ENABLED=off closes both keyed endpoints without disrupting unkeyed traffic.

Rollout and measurement

Enable the Firestore result TTL policy and verify that the gateway replicas have the keyed endpoint and encryption secret before admitting paid Go finalization traffic. The policy and operator procedure are in the gateway docs. Production configuration and rollout are separate from this PR.

A new successful key costs four reads, three writes and one eventual TTL delete. A committed replay or lookup costs three reads. Watch for zero excess attempts per 1,000 keyed POSTs while replay traffic is present. The docs give the ledger grouping, the keyed attempt counter and the accounting-coverage comparison.

Verification

  • The Go adapter tests cover operation-key stability, required-key submission, recovery, pending and indeterminate classifications, and rejection of an unacknowledged success.
  • Gateway unit tests cover request bounds, the kill switch and existing unkeyed behavior.
  • Five Firestore-emulator tests exercise concurrent submission, exact replay and lookup, changed credentials, timeout and expiry, an ambiguous commit acknowledgement, result size and account deletion. Provider calls are counted inside the fake provider.
  • make check in backend-go passed with Postgres 16 and the Firestore emulator. Focused gateway unit tests and the Firestore-emulator suite passed locally.
  • The scoped TTL plan was rendered offline against a demo project. Production metrics and TTL activation are rollout verification.

Product invariants affected

none

View guided diff Turn on auto-fix

@github-actions

Copy link
Copy Markdown
Contributor

Hey @Git-on-my-level 👋

Thank you so much for taking the time to contribute to Omi! We truly appreciate you putting in the effort to submit this pull request.

After careful review, we've decided not to merge this particular PR. Please don't take this personally — we genuinely try to merge as many contributions as possible, but sometimes we have to make tough calls based on:

  • Project standards — Ensuring consistency across the codebase
  • User needs — Making sure changes align with what our users need
  • Code best practices — Maintaining code quality and maintainability
  • Project direction — Keeping aligned with our product principles and locked invariants

Before your next PR, please skim:

  • PRODUCT.md — product north star
  • Product invariants — locked rules (shared chat, memory tiers, agent control plane, integrations, brand)

If this was declined for direction or taste, maintainers should cite an invariant ID or open a proposed one — ask if that citation is missing.

Your contribution is still valuable to us, and we'd love to see you contribute again in the future! If you'd like feedback on how to improve this PR or want to discuss alternative approaches, please don't hesitate to reach out.

Thank you for being part of the Omi community!

Git-on-my-level added a commit that referenced this pull request Nov 21, 2026
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
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