Skip to content

fix(sync): keep open_loop_extractions decode off the transaction replay path; retry expired transactions under the bounded budget - #23738

Merged
Git-on-my-level merged 2 commits into
mainfrom
lane/sync-expired-tx
Oct 26, 2026
Merged

Git-on-my-level merged 2 commits into
mainfrom
lane/sync-expired-tx

Conversation

@Git-on-my-level

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

Copy link
Copy Markdown
Member

Problem and fix

Since the 87083b7 roll (#23718), sync assignment strictly decoded retained open_loop_extractions inside the transaction body — and paid that decrypt/decompress again on every SDK same-chain replay. Longer bodies plus the chronic contention storms pushed transaction chains past Firestore's server-side transaction lifetime, so commits began returning InvalidArgument … transaction has expired.

Diagnosis counts (ro-prod, counts only, 12:45–13:45Z window on 2026-10-26):

  • Inner expiry restarts: 454/hour vs ~1.75/hour on 10-25, in episodic storms (181 in the single minute 12:51), starting ~8 min after the ~12:43Z roll.
  • 11 expired lines across 9 distinct sync jobs in one hour ended partial_failure via sync_persistence_exception firestore_error=expired_transaction; 0 at finalize.
  • Outer sync_assignment contention stayed at its chronic baseline (508 events/hour, 13 exhausted): contention is old, the expiry escape is new in volume.

Fix:

  1. Structural — the decode is off the replay hot path. assign_sync_conversation's decode no longer decodes retained extractions; the encoded blob never enters the decoded row, so it can never reach the logical write encoder (the fix(sync): stop re-encoding stored open_loop_extractions on sync assignment #23718 invariant). encode_sync_assignment_plan carries the stored blob and its compressed marker verbatim when the row's protection level is unchanged (zero decode calls, byte-identical write), and strictly decodes + re-protects only when the plan's level differs from the stored row's; an unreadable blob still aborts before any write there. Processing-persist (_reapply_current_manual_assignments) and smart absorb already decode only on a level change; both keep that shape. Shorter bodies and replays are what stop chains outliving the server-side transaction lifetime.
  2. Equal-jitter backoff on the default-path expired restart. run_transactional's default path now sleeps the same equal-jitter delay as the transient=True path (at most 0.6 s across the two restarts, no Firestore lock held during the sleep), so an inner restart lands outside the spike that retired the previous id instead of inside it.

Dropped after review: classifying an expired transaction id as contention at the outer boundary (firestore_transaction_retry._is_transaction_contention). run_sync_assignment nests run_transactional (3 inner attempts) inside run_with_transaction_contention_retry (5 outer attempts), so the classification admitted up to 15 fresh transaction chains — each allowed to run for Firestore's 270 s server-side transaction maximum, far past the sync handler's 1,380 s budget, the 1,500 s dispatch deadline, and the 1,800 s run-lock TTL; batch projection holds a 300 s claim against the same nesting. A safe version needs one layer to own a deadline-aware budget, which is a redesign, not a classification tweak. It becomes a separate follow-up so this fix is not delayed by it; firestore_transaction_retry.py and its tests are back at main behaviour unchanged in this PR.

Tests

  • test_sync_assignment_contention_retry.py: new integrated replay regression. The real assign_sync_conversation → assign_in_transaction → encode path runs against an SDK-surface fake whose first commit raises Aborted once, so the SDK replays the whole production body on the same transaction id — assign_in_transaction is not stubbed. Asserts one transaction chain, two body executions of the stored-row read, zero decode_open_loop_extractions calls, and that the committed write carries the stored blob and compressed marker byte-identical — standard compressed and enhanced encrypted both covered.
  • test_open_loops_assignment.py: a same-level assignment on a row carrying real encoded extractions makes zero decode calls across append + retry and writes the blob and marker back byte-identical; a level change decodes the stored blob exactly once and re-protects it; an unreadable blob aborts a re-protecting write before any transaction write and is carried untouched at an unchanged level.
  • test_cap_publication_retry.py: the default-path expired restart sleeps equal-jitter delays and uses a fresh transaction per restart; non-expiry errors still never sleep.
  • fix(sync): stop re-encoding stored open_loop_extractions on sync assignment #23718's tests are kept and extended: donor merge byte-identical at the same level and logically equal after an upgrade, new-row encode/absent/null controls, protection migration atomic round-trip, reprocess preservation, and processor re-protection after a concurrent migration.

Verification

Hermetic tests only. No production reads, writes, API calls, or config changes; the counts above are the read-only diagnosis already on record. Selection through bin/omi-heavy at nice -n 15, per-file pytest isolation, rebased on origin/main (de8c741):

  • All test_open_loops_*.py, test_sync_*.py, test_firestore_*.py, plus the changed files' suites (test_sync_assignment_contention_retry.py, test_cap_publication_retry.py, test_conversation_persistence_transaction_expiry.py): 146 files, 4,571 passed, 3 skipped, 0 failed.
  • scripts/select_backend_unit_tests.py requires the full backend unit suite for backend/database/_client.py changes; CI runs that selection on this PR. The locally run set above is the prescribed subset.
  • make preflight: all checks pass with this PR body.

Failure-Class: FC-conversation-persistence-expired-transaction

Product invariants affected

none

Rollback: revert

…ay path; retry expired transactions under the bounded budget

Sync assignment decoded retained open_loop_extractions inside the
transaction body on every SDK same-chain replay since #23718; longer
bodies plus chronic contention pushed chains past Firestore's
server-side lifetime, escaping as expired_transaction (454 inner
restarts/hour vs ~1.75/hour on 10-25; ~9 jobs/hour ending
partial_failure).

- Assignment now carries the stored blob and its marker verbatim when
  the protection level is unchanged (zero decode calls, byte-identical
  write) and strictly decodes/re-protects only on a level change, which
  still aborts on unreadable input before any write.
- An expired transaction id is classified as contention at the outer
  boundary, so the bounded 5-attempt equal-jitter budget governs it
  instead of the error escaping after 3 inner restarts.
- run_transactional's default-path expired restart now backs off with
  the same equal-jitter delay as the transient path.

Failure-Class: FC-conversation-persistence-expired-transaction
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 26, 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-26T16:59:40.136748Z d7866bb 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.

Git-on-my-level added a commit that referenced this pull request Oct 26, 2026
Reverts #23731 (merged c5486dd), restoring the 8 FIRESTORE_READ_LEVERS
it set to 0.

Why: #23731 was a precaution against a backend-sync 5xx guard breach at
the 14Z tick (0.73% vs 0.11% ref). op1 attributed those 5xx: ~256 are
audio-merge manifest-retry 500s that predate the regression (722/h on
10-25), and ~110 align with Firestore expired_transaction storms caused
by #23718's in-transaction decode (fixed by #23738). None are
lever-linked, so the levers are exonerated and their read savings should
stay.

#23731 never deployed (the serving Cloud Run, listen and pusher
revisions predate c5486dd). Merging this before the next CR train keeps
the lever state unchanged in production.

## Product invariants affected

- INV-MEM-4 (path match on backend/deploy/runtime_env.yaml only; this
revert restores Firestore read-lever values and does not change memory
promotion behavior)

Rollback: re-merge #23731.

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

Review of #23738 found the outer-boundary classification nests: 3 inner
run_transactional attempts inside 5 outer contention attempts admit up to
15 fresh transaction chains, each allowed Firestore's 270 s chain
lifetime - past the sync handler budget (1,380 s), the dispatch deadline
(1,500 s) and the run-lock TTL (1,800 s), and past batch projection's
300 s claim. Revert firestore_transaction_retry.py, its tests and the
guard-artifact listing to main; is_expired_transaction_error returns to
database/_client. A deadline-aware retry budget becomes a separate
follow-up.

Keep the replay-path decode removal (byte-identical passthrough at an
unchanged protection level) and the default-path equal-jitter backoff.
Add the integrated replay regression Luna's review asked for: the real
assign_sync_conversation -> assign_in_transaction -> encode path under
one Aborted commit and the SDK's same-chain replay, asserting zero
decode calls across both body executions and a byte-identical blob and
marker write (standard compressed and enhanced encrypted).

Failure-Class: FC-conversation-persistence-expired-transaction

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

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

# whole production body on the same transaction id. Nothing may be stubbed:
# the real assign_sync_conversation -> assign_in_transaction -> encode path
# must carry the stored blob verbatim on both body executions.
store = _ReplayFirestoreClient(commit_errors=[Aborted('commit contention')])

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 Cover retained-extraction replay with the Firestore emulator

This incident regression is covered only by a newly implemented transaction fake, whereas backend/AGENTS.md explicitly requires emulator coverage first for retry or contention behavior. The existing backend/scripts/sync_assignment_contention_emulator_test.py exercises read-abort recovery and concurrent appends but never seeds retained extractions or checks their preservation across commit-time replay; searching emulator/Firestore test and harness files found no such coverage. Add an emulator-backed regression for this retained-blob replay scenario before relying on the hermetic fake, so the incident's transaction and storage behavior is validated against the real service boundary.

AGENTS.md reference: backend/AGENTS.md:L232-L232

Useful? React with 👍 / 👎.

@Git-on-my-level
Git-on-my-level merged commit 016c4eb into main Oct 26, 2026
59 checks passed
@Git-on-my-level
Git-on-my-level deleted the lane/sync-expired-tx branch October 26, 2026 17:09
Git-on-my-level added a commit that referenced this pull request Oct 26, 2026
…d transactions within it (#23745)

## Problem

Expired Firestore transactions (`InvalidArgument … transaction has
expired`) escape the bounded outer contention budget: the outer helper
classifies only `Aborted`, so once the inner expired-id restarts spend
themselves the error surfaces to the segment pipeline and the job run
ends `partial_failure`. In the diagnosis window this ended about 21
backend-sync job runs per hour (about 9 distinct jobs in one sampled
hour); inner expiry restarts measured 454/hour against a ~1.75/hour
baseline before the roll that lengthened transaction bodies.

Classifying expiry as contention alone (the item dropped from #23738) is
not safe: the nested budget — 3 `run_transactional` attempts inside 5
outer attempts — admits up to 15 fresh transaction chains, each allowed
Firestore's 270 s chain lifetime: about 67 minutes of retry wall time,
against the sync handler budget (1,380 s), the dispatch deadline (1,500
s), the run-lock TTL (1,800 s), and batch projection's 300 s claim
(blocking review of #23738).

## Design

1. **One layer owns the budget.** Nested callers (`run_sync_assignment`,
batch projection's `ProjectionStore.run`) now run the inner
`run_transactional` with `attempts=1`; the outer helper owns every
attempt. An expired chain costs exactly one bounded outer retry, so the
worst case is 5 chains for every caller instead of 15 nested.
2. **Deadline-aware guard that never refuses the first attempt.**
`run_with_transaction_contention_retry` takes a monotonic `deadline` —
or inherits the ambient `transaction_retry_deadline_scope` ContextVar,
which `run_blocking` copies into executor leaves. A caller that reached
the transaction always gets one try: the deadline gates only retries
(attempt 2 onward), so scoping a deadline can only remove retries, never
the attempt itself — the change cannot be worse than today. A retry
starts only while the remaining budget covers `max(last attempt's
observed duration × 1.5, 30 s)`, and a post-failure jitter sleep never
runs past the deadline. Fast Aborted contention (near-zero observed
durations) therefore still spends the 5-attempt cap inside a short
budget, while a chain that already consumed real time raises the reserve
so the next full chain still fits. When the reserve does not fit, the
loop stops and raises
`FirestoreContentionExhausted(reason='deadline_exhausted')` (the
existing exhaustion type; new closed token `deadline_exhausted`, also
carried by the pipeline's `firestore_error` classification).
3. **Expiry classified as contention, under that guard.** An expired
chain is atomic and wrote nothing, exactly like an aborted one; it is
replayed only inside the bounded, deadline-aware budget. With no
deadline in scope, expired-id retries keep today's ceiling of 3 fresh
chains (`run_transactional`'s default); Aborted contention keeps the
5-attempt policy either way.
4. **Deadline inputs.** The sync job handler scopes its request-budget
deadline minus a 120 s safety margin around the whole attempt. Batch
projection's `projection_claim` anchors its deadline at claim start over
the full 300 s lease — the Redis-unavailable fail-open path carries the
same local 300 s budget, so no claim path ever falls back to the attempt
count without a wall-time bound. Callers that pass no deadline keep
today's bounds or tighter.
5. **Preserved.** Idempotency contracts, the equal-jitter schedule (the
inner default path keeps its ≤0.6 s backoff), and the existing telemetry
tokens (`retry`/`recovered`/`exhausted`).

## Worst-case retry wall time per caller

| Caller | Before | After |
|---|---|---|
| sync assignment (v2 job, default budget) | up to 15 chains ≈ 4,050 s |
retry window 1,260 s (1,380 − 120 margin), ≤ 5 chains; ≈ 1,082 s for
uniform full chains; total ≤ window + one in-flight chain (≤ 1,500 s) |
| batch projection under its claim | up to 15 chains ≈ 4,050 s vs a 300
s claim | deadline = claim start + full 300 s; first chain always runs,
fast Aborted retries spend the 5-attempt cap, total ≤ 300 s + one
in-flight chain (≤ 540 s) |
| batch projection claim, Redis unavailable | fail-open with no
wall-time bound | same local 300 s budget as a held claim |
| any other outer-helper caller, no deadline | expiry escaped after 3
inner restarts; Aborted ≤ 5 chains | expiry ≤ 3 fresh chains (today's
ceiling); Aborted ≤ 5 chains |
| inner `run_transactional` without an outer budget | 3 attempts, ≤ 0.6
s jitter | unchanged |

Bound argument: the first attempt is never gated, each retry starts only
while the remaining budget covers `max(last attempt × 1.5, 30 s)`, and
the jitter sleep never runs past the deadline. The loop cannot stop an
attempt already running, and Firestore retires any chain at 270 s, so
the accepted bound is **total ≤ deadline + one in-flight attempt** — in
practice ≤ deadline + 240 s, because the last attempt always started
with at least the 30 s reserve floor remaining. For the sync handler
that is ≤ 1,500 s against the 1,380 s handler budget (whose asyncio
timeout is the hard stop for the response), the 1,500 s dispatch
deadline and the 1,800 s run-lock TTL (which covers an orphaned chain);
the 120 s margin absorbs the normal tail. For the claim it is ≤ 540 s.
Fake-clock tests assert the bound for each caller configuration with
full 270 s attempts at maximum jitter.

## Tests

- `tests/unit/test_firestore_transaction_retry_deadline.py` (16):
fake-clock worst-case bound per caller at full 270 s attempts and
maximum jitter (no deadline → 5 Aborted attempts; sync budget → 4
attempts; claim budget → 1 attempt; zero remaining → attempt 1 still
runs) with `total ≤ deadline + one chain` asserted; observed-duration
reserve; attempt 1 never refused even past the deadline; jitter sleep
never past the deadline; the no-deadline expiry ceiling (3 chains,
Aborted keeps 5, a deadline lifts expiry to the attempt policy); expiry
recovery within budget; ambient scope inherit/opt-out/reset; expiry
classification (commit, streaming-read `Aborted`, SDK wrapper cause
chain) and non-classification of plain `InvalidArgument`; unchanged
outcome tokens.
- `tests/unit/test_sync_assignment_contention_retry.py` (19, all green):
nested expiry keeps one chain per attempt and today's 3-chain
no-deadline ceiling; repeated expiry stops before the scoped deadline (4
attempts under a 500 s budget with 100 s chains); expiry recovers within
budget when time allows.
- `tests/unit/test_batch_pipeline_projection.py` (47, all green): the
claim scopes the deadline to its full lease (no margin); the
Redis-unavailable fail-open path carries the same 300 s budget; with the
production retry configuration and 31 s of elapsed claim-to-helper time
the first chain runs, fast Aborted retries spend the 5-attempt cap
inside the lease, and a full 270 s expired chain stops the storm within
lease + one in-flight chain.
- `tests/unit/test_sync_assignment_recovery.py` (35, all green): bounded
`firestore_error` tokens distinguish attempt vs deadline exhaustion.
- Required set green via `backend/test.sh` file isolation: the touched
suites plus every `test_sync_*`, `test_firestore_*`, and batch-pipeline
projection suite (139 files), plus `make preflight`.

## Late-writer safety

The batch projection claim
(`database/batch_pipeline_projection_claim.py`) is **advisory — never a
mutation fence**; the Firestore projection receipts and the
watermark/revision checks inside the projection transaction are the
write authority. The accepted bound (`deadline + one in-flight chain`)
means a writer's 300 s claim lease can expire while its chain is still
in flight and another writer can take the claim. Tests prove the late
writer cannot corrupt projection state:

-
`backend/tests/unit/test_batch_pipeline_projection.py::test_late_writer_after_claim_takeover_replays_receipt_and_keeps_replacement_claim`
(StrictFirestore + the Redis claim fixture): writer A's lease expires
mid-flight and writer B takes the same owner claim; A's late transaction
body fences on B's committed receipt (`ProjectionReplay`, nothing
staged), A's late completion replays B's committed result with zero
writes, and A's token-fenced release never evicts B's live claim.
-
`backend/tests/integration/test_batch_pipeline_projection_firestore.py::test_late_writer_after_claim_takeover_replays_committed_receipt`
(Firestore emulator, real transactions): A's assignment chain is aborted
mid-flight (contention injected at the BatchGet transport boundary, the
qualified contention pattern), its lease expires, writer B takes the
claim and fully projects and commits the same segment; A's late body
then reaches commit on a fresh transaction and replays B's receipt — one
conversation copy, a single `sync_content_revision` increment, one
enrichment obligation, one usage charge, byte-identical ledger and
receipt, and B's live claim token intact after A's release. Run with
`FIRESTORE_EMULATOR_HOST=<loopback> pytest <file>::<name>` from
`backend/`.

Follow-up (not blocking): claim renewal/heartbeat for long projection
chains, so the advisory claim itself covers deadline + one in-flight
chain instead of relying on the takeover path.

## Rollback

Rollback: revert.

Failure-Class: FC-conversation-persistence-expired-transaction

Line-Count-Exception: backend/routers/sync.py | 4007 -> 4026 | one
deadline scope around the job attempt body plus its safety-margin
constant; no new logic blocks
Line-Count-Exception: backend/utils/sync/pipeline.py | 3758 -> 3764 |
bounded firestore_error token mapping for the retry budget's two
terminal reasons
kriegcloud pushed a commit to kriegcloud/omi that referenced this pull request Oct 26, 2026
…d transactions within it

Expired Firestore transactions (InvalidArgument "transaction has expired")
escaped the bounded outer contention budget, which classified only Aborted:
once the inner expired-id restarts spent themselves the error surfaced to
the segment pipeline, ending about 21 backend-sync job runs per hour as
partial_failure. Classifying expiry as contention alone was unsafe because
the nested budget (3 inner run_transactional attempts inside 5 outer
attempts) admitted up to 15 fresh transaction chains, each allowed
Firestore's 270 s chain lifetime - about 67 minutes, past the sync handler
budget (1,380 s), the dispatch deadline (1,500 s), the run-lock TTL
(1,800 s), and batch projection's 300 s claim (blocking review of BasedHardware#23738).

One layer now owns the budget: nested callers run the inner
run_transactional with attempts=1 and the outer helper owns every attempt
(5 chains maximum). The outer helper is deadline-aware: before each attempt
it requires the remaining budget (explicit deadline, or the ambient
transaction_retry_deadline_scope ContextVar that run_blocking copies into
executor leaves) to cover max(270 s, the last attempt's observed duration),
and otherwise stops with FirestoreContentionExhausted(reason
'deadline_exhausted'). Expired chains are classified as contention under
those bounds. The sync job handler scopes its request-budget deadline minus
a 120 s safety margin around the attempt; batch projection's claim scopes
its 300 s lease minus 30 s. Callers without a deadline keep today's bounds
or tighter; idempotency contracts, the equal-jitter schedule, and the
existing telemetry tokens are preserved, with a new closed
deadline_exhausted token on the helper log line and the pipeline's
firestore_error classification.

Worst-case retry wall time: sync assignment <= 1,260 s (was ~4,050 s);
batch projection under its claim <= 270 s (was ~4,050 s against a 300 s
claim); every other outer-helper caller stays at 5 attempts, now with
expiry included instead of escaping after 3 inner restarts.

Failure-Class: FC-conversation-persistence-expired-transaction
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