Skip to content

fix(firestore): deadline-aware transaction retry budget; retry expired transactions within it - #23745

Merged
Git-on-my-level merged 4 commits into
mainfrom
lane/sync-expiry-budget
Oct 26, 2026
Merged

Git-on-my-level merged 4 commits into
mainfrom
lane/sync-expiry-budget

Conversation

@Git-on-my-level

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

Copy link
Copy Markdown
Member

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

…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 #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
… artifact list only

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-26T20:16:27.925107Z af4fc78 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: a8f19ad3f5

ℹ️ 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 +56 to +57
with transaction_retry_deadline_scope(time.monotonic() + LEASE_SECONDS - CLAIM_RETRY_MARGIN_SECONDS):
yield acquired

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 Leave enough claim budget to admit the first transaction

When Redis is available and projection contention retries are enabled, this scope prevents projection transactions from running at all. LEASE_SECONDS - CLAIM_RETRY_MARGIN_SECONDS is exactly 270 seconds, equal to the retry helper's default per-attempt estimate; by the time ProjectionStore.run() reaches its entry gate, the remaining budget is already strictly below 270 seconds, so it raises deadline_exhausted without invoking the operation. This affects the claim-held assignment paths in utils/batch_pipeline/projection.py, even without contention. A reproduction using the real clock produces zero operation calls; the new claim retry test masks this by overriding the estimate to 250 seconds. Adjust the claim budget/admission policy so normal first attempts can actually start.

Useful? React with 👍 / 👎.

Comment on lines +56 to +57
with transaction_retry_deadline_scope(time.monotonic() + LEASE_SECONDS - CLAIM_RETRY_MARGIN_SECONDS):
yield acquired

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Keep claim deadline tokens within their originating context

When Redis is available, ProjectionFollowups._run() enters and exits projection_claim through separate run_blocking() calls (utils/batch_pipeline/projection_followup.py:164,192). Each call creates a fresh copied context in utils/executors.py, so adding this ContextVar scope makes claim exit raise ValueError: Token ... was created in a different Context. Every such follow-up now ends with an uncaught cleanup exception, including successful and claim-busy runs; the deadline also never propagates from the entry worker back to the coordinator's subsequent database calls. Establish the scope in the async coordinator, or otherwise ensure entry, scoped operations, and reset share the same context.

Useful? React with 👍 / 👎.

Comment on lines +81 to 82
if isinstance(current, FirestoreAborted) or _is_expired_transaction(current):
return True

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Remove the remaining inner expiry retries in retention

For repeated expired-transaction errors, the newly expanded classifier also retries run_retention_transaction() in utils/batch_pipeline/retention.py:306-311, but that caller still invokes run_transactional() with its default three attempts. Consequently, retention now executes 15 fresh transactions before exhausting instead of three, reproducing the nested retry amplification removed from the other callers in this commit. This is reached by Projector.complete_content() during async follow-ups; their 120-second asyncio timeout cannot interrupt the blocking retention worker, so repeated slow expiries can keep a postprocessing thread occupied long after the follow-up times out. Update the retention caller to pass attempts=1 as well so the outer retry budget actually owns every attempt.

Useful? React with 👍 / 👎.

…e-based retry deadline

Review follow-up on the deadline-aware retry budget:

- The deadline gate now applies only before attempts >= 2: a caller that
  reached the transaction always gets one try, so a deadline scope can
  only remove retries, never the attempt itself. A retry requires
  remaining >= max(last attempt duration x 1.5, 30 s) instead of a fixed
  270 s, so fast Aborted contention still spends the attempt cap inside
  a claim lease or handler window while a long chain raises the reserve.
  Accepted bound: total <= deadline + one in-flight attempt.
- The post-failure jitter sleep is clamped to the deadline: remaining
  time below the delay stops with deadline_exhausted instead of sleeping
  past the 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.
- The batch projection claim anchors its deadline at claim start over
  the full 300 s lease (no 30 s margin, which suppressed the first
  transaction once work had elapsed), and the Redis-unavailable
  fail-open path carries the same local 300 s budget.
The advisory projection claim can expire mid-chain (deadline + one
in-flight chain); the Firestore receipts are the fence. Unit: StrictFirestore
prepare/complete replay with zero staged writes and a token-fenced release.
Emulator: A's aborted assignment chain resumes on a fresh transaction after
B's takeover commit — one conversation copy, one revision increment, one
usage charge, B's live claim token intact.
@Git-on-my-level
Git-on-my-level merged commit 7cb7bbb into main Oct 26, 2026
61 checks passed
@Git-on-my-level
Git-on-my-level deleted the lane/sync-expiry-budget branch October 26, 2026 20:26
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