Skip to content

fix(firestore): release the transaction retry deadline scope across Context boundaries - #23928

Merged
Git-on-my-level merged 1 commit into
mainfrom
lane/ctxdeadline
Oct 29, 2026
Merged

Git-on-my-level merged 1 commit into
mainfrom
lane/ctxdeadline

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Oct 29, 2026 •

Copy link
Copy Markdown
Member

What

transaction_retry_deadline_scope now tolerates being released in a different
contextvars Context than the one it was entered in. Every release of the batch
projection follow-up's advisory claim raised
ValueError: <Token var=<ContextVar name='firestore_transaction_retry_deadline' ...> was created in a different Context>
because projection_followup._run enters projection_claim via claim.__enter__
in one run_blocking executor leaf and releases it via claim.__exit__ in a later
leaf — and each run_blocking leaf runs in its own contextvars.copy_context()
(utils/executors.py:401). The token created by the scope's set was reset in
another Context, so _retry_deadline.reset(token) raised on every release.

Measured by the lead on ro-prod backend-integration logs (2026-10-28/29):
~800/h ERROR utils.executors: background_task failed: batch_projection_followup — ValueError,
chronic (also ~130/10min on revision 01404 before 7bc941c, and present on it).
Every occurrence is the claim release in the follow-up's finally, i.e. after
finish_part/complete_content had already run.

Why the fix is safe

The exit Context never observed the scope's set — the scoped deadline lived and
died with the entry leaf's private context copy — so a token mismatch leaves
nothing to undo there. The scope catches the ValueError from reset and does
nothing for that case. Same-context scopes keep exact token-reset semantics
(nesting, None opt-out, restore-on-exit are unchanged).

routers/sync.py:3110 uses the same scope but enters and exits it inside one
coroutine Context, so it cannot hit this path today; the scope-level fix covers
any future split there too.

Deadline semantics kept intact, per the existing tests (all green, unchanged):

  • test_firestore_transaction_retry_deadline.py — ambient scope inheritance,
    override + reset, first-attempt-never-refused, reserve-based retry bounds.
  • test_batch_pipeline_projection.py — claim scopes the deadline to its full
    lease; the fail-open path keeps the same local lease budget; the lease bounds
    the retry storm.

Known pre-existing limitation (unchanged by this PR, stated for the record): in
the follow-up path the lease deadline never reached the nested transaction calls
(each leaf copies the ambient task context, which never carried it). Retries
there stay bounded by the attempt caps and by the follow-up's own
FOLLOWUP_TIMEOUT_SECONDS = 120 asyncio budget, which is tighter than the 300 s
lease; the lease-bounded deadline remains effective for same-context claim users
(assignment/owner-chain paths). No behavior change there.

Are lost follow-ups replayed?

Yes — and in the common case nothing was lost at all. The ValueError fired in
the finally release, after the follow-up's side effects committed; the task was
merely reported failed. For follow-ups whose body failed earlier, the persisted
receipts stay durable and the next sweep rediscovers them
(test_failed_followup_stays_durable_and_resumes_with_same_receipt). No data
repair is needed with this fix; rows that already completed are idempotent on
re-sweep via the existing receipt fences.

Tests

  • test_deadline_scope_exited_in_a_different_context_never_raises — scope
    entered in one copy_context() and exited in another (exactly the two
    run_blocking leaves); raised before the fix, passes after; exit context and
    ambient context stay untouched.
  • test_real_claim_released_across_run_blocking_leaves_never_fails_the_task —
    end-to-end through the real projection_claim + real run_blocking context
    copies with the follow-up runner; reproduced the exact production ValueError
    before the fix; after it, the task completes and the advisory lease is
    released (not left to its TTL).

Local shard (backend/test.sh, file-isolated): 118 passed across
test_firestore_transaction_retry_deadline.py,
test_batch_pipeline_projection_followup.py,
test_batch_pipeline_projection.py, test_sync_assignment_contention_retry.py.

Failure-Class: none

View guided diff Turn on auto-fix

…aries

batch_projection_followup enters the projection claim (and its
transaction_retry_deadline_scope) via claim.__enter__ in one run_blocking
executor leaf and releases it via claim.__exit__ in a later leaf. Each
run_blocking leaf runs in its own contextvars.copy_context(), so the
ContextVar token created by the scope's set is reset in a different
Context and _retry_deadline.reset(token) raises "Token was created in a
different Context" on every release - backend-integration logged ~800/h
of background_task failed: batch_projection_followup, each after the
follow-up's work had already committed.

The exit context never observed the scope's set (the scoped value lived
and died with the entry leaf's private copy), so a token mismatch leaves
nothing to undo: tolerate it instead of raising. Same-context scopes keep
exact token-reset semantics and the nested-retry deadline bounds are
unchanged (test_firestore_transaction_retry_deadline.py, the claim-lease
tests in test_batch_pipeline_projection.py). routers/sync.py enters and
exits the scope in one coroutine Context and cannot hit this path; the
scope-level fix covers a future split there too.

Follow-ups that reported this failure are not lost: the release error
fired in the finally after finish_part/complete_content, and durable
receipts keep any unfinished row rediscoverable by the next sweep
(test_failed_followup_stays_durable_and_resumes_with_same_receipt).
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 29, 2026 •

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-29T00:26:46.504744Z 989b872 PR opened
ℹ️ 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: 989b8720b3

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

Comment on lines +182 to +184
import fakeredis

from database import batch_pipeline_projection_claim as claims

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 test imports to module scope

The new regression tests introduce function-local imports (fakeredis and claims here, and contextvars in the deadline test), contrary to the explicit backend requirement that all imports be at module top level, never inside functions. Move these imports to their respective module import sections; the Redis monkeypatch can remain inside the test.

AGENTS.md reference: backend/AGENTS.md:L165-L167

Useful? React with 👍 / 👎.

@Git-on-my-level
Git-on-my-level merged commit d60cd2e into main Oct 29, 2026
63 checks passed
@Git-on-my-level
Git-on-my-level deleted the lane/ctxdeadline branch October 29, 2026 00:38
Git-on-my-level added a commit that referenced this pull request Oct 29, 2026
…ay (#23943)

## Problem and change

Batch projection fixes have needed another production ramp to encounter
deterministic unit-shape failures. Add a fixed offline adapter and `make
batch-replay REF=<sha> BASE=<sha> CORPUS=<path> OUTPUT=<path>` so the
lead can compare immutable product revisions before deploying.

The adapter runs the real owner walk, VAD span validator,
partition/build, assignment transaction planner against StrictFirestore
targets, source-audio slicing against synthetic PCM, and follow-up
claims with real fakeredis Lua across copied executor Contexts. It
blocks outbound sockets, gRPC channels, and cloud client construction.
Bridge/summary external effects are fake leaves.

## Capture allowlist and limits

Read-only `ro-prod` capture selects numeric durations/VAD sample counts;
owner/unit/content/conversation/predecessor/watermark/sibling
identities; lane, state, attempts, retry presence, recovery state; and
target lifecycle/route/privacy flags. It never requests whole
`speech_spans` or `manifest.references` arrays: Firestore cannot mask
element subfields, so requesting them could read nested text or paths.
The exact RPC field projections are in
`backend/testing/batch_replay/capture.py`, the README and each corpus.
Geometry slots remain null; only synthetic inputs supply geometry. IDs
are HMAC-SHA256 with a fresh private corpus salt. No transcript, audio,
names, emails, URIs, or error messages are persisted. Corpus/salt stay
mode 0600 under a 0700 scratch directory, outside Git.

Live capture contains 2,000 units. All 2,000 lack decoded durations, VAD
span arrays and manifest geometry in Firestore. Lead ruling `a76a1a`
explicitly forbids artifact export/decryption and accepts Firestore
chain/state/assignment structures plus labelled synthetic geometry. The
normal gate always adds the incident fixture and a duration-quantile
boundary matrix (EOF minus/exact/plus one sample, invalid VAD overrun,
first/last valid slices and invalid source/capture slices). Invalid
shapes must be rejected. Reports name
`coverage_scope=firestore-structure+synthetic-boundaries` and retain all
missing captured geometry in `coverage_limits`. Optional strict
captured-geometry mode fails those gaps. This PASS cannot claim replay
of captured audio/VAD geometry. The follow-up corpus includes one-hop
redirect-target lifecycle states. Delete private corpus/salt after the
program (David ruling `a5c4f6`); lead owns that handoff. Tracked in anx
`card:batch-replay-gate-20261029`. No production deploy or data mutation
is part of this PR.

## Validation

- Targeted backend shard:
`BACKEND_UNIT_TEST_FILE_LIST=/Volumes/Ephemeral/scratch/replay/unit-files.txt
BACKEND_PYTEST_WORKERS=4 bash backend/test.sh`, through `omi-heavy` and
`nice -n 19`.
- Historical synthetic corpus: baseline
`7bc941c43d57409f02ce2d18c18bfa3eee7c8db1` reproduces the one-sample EOF
VAD ValueError and discarded-backfill owner-chain block; main
`91d5616fa922e8f77fe02dbea40fa85ef8f45f1e` clears those with
#23926/#23932. The corpus also exercises cross-Context follow-up claim
release (#23928).
- Real-corpus initial strict gate vs `7bc941c`: zero new exception sites
or blocked units; FAIL for missing geometry. Subsequent accepted-scope
gate adds mandatory synthetic distributions and captures referenced
redirect states. Reports stay under `/Volumes/Ephemeral/scratch/replay/`
(private local artifacts).

Gate fails new exception sites, regressions on previously exercised
units, newly blocked units, synthetic oracle/incident failures, or
missing structural coverage. Fixing a head can expose a known downstream
conflict on an already-blocked baseline unit; that is recorded
separately, while new classes/sites always fail. No `.github/` change.
Lead owns merges/deploys; one Luna review round is required.

## Review fixes

The first Luna review requested a tighter read boundary and
dispatch/verdict fidelity. Capture now excludes whole geometry arrays at
the RPC mask and never inspects them in sanitization. Unknown outcomes,
terminal-empty results without proof, and unknown lanes block replay as
coverage gaps. Both main-corpus and incident boundary lists are checked
explicitly, independently of exception flattening. Quantiles retain
observed duration frequency, and per-unit exception counters catch
repeated failures at an existing site. Targeted regressions cover all
six review findings; round two is limited to this delta.
Git-on-my-level added a commit that referenced this pull request Oct 29, 2026
…taxonomy, shard spread, boundary geometry, real claim) (#23946)

## Summary

David, 10-29 (simtests lane): tonight's batch wedges were deterministic
and testable, but no test covered the property that failed. This PR adds
the five CI invariants from tonight's brief, wired into the existing
backend unit suite (no new workflow), plus the minimal product fix one
of them demands.

**The wedge class still live on main:** a committed result or manifest
that violates the payload contract raised `ValueError` through
`assign_parts` with no disposition. The owner-chain walk retries a chain
head forever, so a permanently invalid payload at the head froze every
later capture behind it — the same head-of-line shape as #23932's
unhandled record-target conflict, and the deterministic driver behind
the #23926 EOF-span refusals (4,952 refusals on one revision). The fix
takes the held disposition for the closed set of payload-contract
`ValueError`s, exactly like a structural assignment conflict: quarantine
receipt, watermark advance, recovery owns the unit, audio retained. The
Firestore commit-contention `ValueError` shape stays retryable.

## The five invariants

1. **Poison-head matrix** (`test_pipeline_sim_poison_head.py`): for
every failure kind the projection walk can raise — all 16 bounded
assignment-conflict subtypes plus the unlabeled fallback, five
payload-contract `ValueError` sites (duration mismatch, split duration,
no words, missing VAD spans, corrupt source manifest), the
contention-shaped `ValueError`, ambiguous generation, and a busy claim —
inject it permanently at an owner's chain head. Advancing kinds
quarantine-hold within K=2 walk attempts (watermark moves, later units
project, audio retained); wait kinds stay in a bounded, observable
pending state. Would have caught #23932 and the payload wedge.
2. **Exception-taxonomy coverage contract**
(`test_batch_projection_exception_taxonomy.py`): AST-scans the walk's
callee modules for constructor-raise sites; a new raise class without a
`TAXONOMY` disposition fails the suite with instructions, and every
injectable kind must appear in the poison-head matrix. Also pins the
strike-rule sets (the one deliberately unclassified subtype,
`bridge_source_not_tombstone`, waits on every lane).
3. **Multi-worker shard-spread sim**
(`test_batch_pipeline_shard_spread.py`): `SpreadMemoryStore` models the
real spread-mode candidate semantics (service primary, worker affinity
on ties, exclusions, pull claims) plus Firestore write-write behavior —
a control write on a shard committed by another puller after this
puller's candidate read aborts. Six real `Scheduler`s over twelve shards
from a shared per-round snapshot: writes spread (no shard > 2x mean, no
round piles onto one document), every job leases exactly once with
unique tokens, claims fence every pull, and stale-write contention stays
far under the legacy no-affinity shape (measured 24 vs 240 aborts on
this workload). Invisible with one simulated worker (#23927).
4. **Boundary-geometry property tests**
(`test_batch_pipeline_boundary_geometry.py`): the ±1-sample boundaries
of every duration fence — EOF VAD spans at each sample of the decode
tolerance (#23926), measured-VAD tolerance, bound worker receipts, word
clocks at EOF, manifest slices at the capture edge, and the projection
payload's 0.1 s duration tolerance including its deterministic float
asymmetries (nominal −0.1 s passes where +0.1 s rejects, one float ulp
past the fence).
5. **Real-claim rule** (`test_projection_followup_real_claim_rule.py`):
the projection_followup suite must keep at least one non-skipped test
exercising the REAL `projection_claim` against fakeredis — the stubbed
claim hid #23928's cross-Context token reset.

## Self-testing (definition of done)

Layer: backend unit shard — the exact CI changed-file selection from
`scripts/select_backend_unit_tests.py` for this diff (18 files,
including the Firestore guard set the selector attaches to the
`projection.py` change):

```
BACKEND_UNIT_TEST_FILE_LIST=<selection> BACKEND_PYTEST_WORKERS=4 bash backend/test.sh
# green, exit 0, duration guard clean
```

Discrimination evidence (each invariant fails against the bug it exists
for):
- poison-head payload kinds fail without the parent fix's disposition;
- the shard-spread sim was measured against
`BATCH_SHARD_SPREAD_ENABLED=false`: 240 stale-write aborts and 49
one-lease rounds vs 24 aborts and 13 rounds with spread — the legacy
flag also zeroes the claim counter;
- the boundary sweep pins the exact clamp/reject sample where #23926's
fence flipped.

## Review

Round 1 (Luna, FIX-FIRST) — one P1: the result-load phase sat outside
the disposition, so a corrupt committed artifact (invalid envelope,
oversized body, bad reference — or valid JSON that is not an object
reaching `payload.get` as an `AttributeError`) still wedged the chain
head. Fixed: the load phase is inside the contract try, and a non-object
body is normalized to the contract `ValueError`. Two new poison-head
kinds pin it (`payload:corrupt-artifact`, `payload:non-object-result`).

Round 2 (Luna, FIX-FIRST) — two P1s, both fixed:
- The pre-loop catch lacked the `payload_contract_violation` gate: a
contention-shaped `ValueError` from the load seam's Firestore-backed
authorization would have quarantined a valid capture. Both catches now
gate through the discriminator, and the `contention-value-error` poison
kind injects at the load seam to pin it.
- A correctly-sized artifact with altered ciphertext fails
`AESGCM.decrypt` as `InvalidTag`, not `ValueError` — it escaped the
disposition. `InvalidTag` is now part of the contract class set
(`payload:tampered-artifact` pins it; the unit-level discriminator test
asserts it). `artifacts.py` joined the taxonomy scan;
`PermissionError`/`TimeoutError` entries document the authorization-wait
and transient classes.

Failure-Class: FC-unresolved-head-blocks-projection

Line-Count-Exception: backend/utils/batch_pipeline/projection.py | 1504
-> 1558 | payload-contract quarantine disposition: one discriminator
helper plus one catch per assign path section, mirroring the #23932
structural-conflict handlers; review rounds added the load-phase cover
and the InvalidTag class

UI-Evidence: none -- reason: no web/admin/app paths touched.
YinkaAdepoju pushed a commit to YinkaAdepoju/omi that referenced this pull request Oct 29, 2026
Tonight's batch failures were deterministic and testable, but no test
covered the property that failed. Five invariants, wired into the existing
backend unit suite (no new workflow):

1. Poison-head matrix (test_pipeline_sim_poison_head.py): for every failure
   kind the projection walk can raise — all 16 assignment-conflict subtypes
   plus the unlabeled fallback, five payload-contract ValueErrors,
   contention-shaped ValueError, ambiguous generation, busy claim — inject
   it permanently at an owner's chain head. Advancing kinds quarantine-hold
   within K=2 walk attempts (watermark moves, later units project, audio
   retained); wait kinds stay in a bounded, observable pending state. Would
   have caught BasedHardware#23932 and the payload wedge fixed in the parent commit.
2. Exception-taxonomy coverage contract
   (test_batch_projection_exception_taxonomy.py): AST-scans the walk's
   callee modules for constructor-raise sites; a new raise class without a
   TAXONOMY disposition fails the suite, and every injectable kind must
   appear in the poison-head matrix.
3. Multi-worker shard-spread sim (test_batch_pipeline_shard_spread.py):
   SpreadMemoryStore models the real candidate semantics (service primary,
   worker affinity on ties, exclusions, pull claims) plus Firestore
   write-write behavior (a control write on a shard committed after the
   puller's candidate read aborts). Six real Schedulers over twelve shards
   from a shared per-round snapshot: writes spread (no shard > 2x mean, no
   round piles onto one document), every job leases exactly once, claims
   fence every pull, stale-write contention stays far under the legacy
   no-affinity shape (measured 24 vs 240 on this workload). Invisible with
   one simulated worker (BasedHardware#23927).
4. Boundary-geometry property tests
   (test_batch_pipeline_boundary_geometry.py): the +-1-sample boundaries of
   every duration fence — EOF VAD spans at each sample of the decode
   tolerance (BasedHardware#23926), measured-VAD tolerance, bound worker receipts, word
   clocks at EOF, manifest slices at the capture edge, and the projection
   payload's 0.1s duration tolerance including its deterministic float
   asymmetries (0.9 passes where 1.1 rejects).
5. Real-claim rule (test_projection_followup_real_claim_rule.py): the
   projection_followup suite must keep at least one non-skipped test
   exercising the REAL projection_claim against fakeredis — the stubbed
   claim hid BasedHardware#23928's cross-Context token reset.

Local verification (layer: backend unit shard, the exact CI changed-file
selection from scripts/select_backend_unit_tests.py for this diff — 18
files): BACKEND_UNIT_TEST_FILE_LIST=<selection> bash backend/test.sh —
green, duration guard clean.

Failure-Class: FC-unresolved-head-blocks-projection
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