Skip to content

refactor(backend): retry only immutable held-audio uploads - #23023

Merged
Git-on-my-level merged 9 commits into
mainfrom
lane/cap-publication-timeout
Oct 21, 2026
Merged

Git-on-my-level merged 9 commits into
mainfrom
lane/cap-publication-timeout

Conversation

@Git-on-my-level

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

Copy link
Copy Markdown
Member

Problem and change

A live held session closed 1011 with publication_failed exception_type=ReadTimeout after #22966. At the reported 25% cohort this was approximately one held-session failure/hour among 1,800 sessions/hour. #22966 retries Firestore transient classes, while GCS uses Requests with retries disabled.

This revision replaces the broad GLM retry/deadline approach with one retry at the immutable live GCS upload boundary. The async sink awaits an upload-only worker, then runs the existing receipt transaction. Late upload workers cannot commit Firestore writes. Both attempts use the same Publication identity and if_generation_match=0; a 412 is adopted only after reload verifies generation, opaque capture metadata, stored length metadata and the fragment/minute size bound. Re-encoded bytes may differ in length; staging uses the verified stored length.

The retry predicate unwraps Requests / urllib3 / google.auth transport timeout and connection errors (including RetryError causes and MaxRetryError reasons). API responses, Firestore errors and permanent faults do not opt in. There is exactly one retry, no backoff, and later flush/close calls cannot start a third upload for this Publication. Unknown futures and any verified fields/generation stay attached to its identity. Manifest recovery no longer deletes an uploaded object after an absence read: that read cannot fence an earlier in-flight commit. Uncertain objects may remain as storage debt.

omi_held_content_publication_retry_total retains the closed-set cause=throttle|timeout|connection|other label; upload retries report timeout or connection.

Reverted scope

  • backend/database/_client.py is byte-identical to the pre-PR base, retaining fix: retry live cap publication when a Firestore transaction expires #22966 unchanged. Removed transport classification/retries there, budget/commit-timeout arguments, and the private Transaction._commit rebind.
  • Restored commit_publication and its existing transient Firestore retry semantics. Removed the publication-wide budgets, new recovery-leaf retries, Firestore read timeout changes, seal/recovery deadlines and cleanup deferral changes.
  • Kept only the upload coordinator, immutable-object verification, persistent custody identity/generation and the metric cause label. Existing receipt/summary atomic writes, count-once checks and fragment claims remain unchanged.

Timeout numbers and limits

Each upload attempt uses a 1.5-second socket inactivity timeout, with SDK retry disabled, plus a 4-second async wait deadline. The deadline includes executor queueing, encoding, privacy checks, upload and 412 reload. Two waits total at most 8 seconds plus event-loop scheduling, comfortably below 12 seconds for one fragment's upload wait. A Requests timeout alone cannot enforce this: a slow response can reset socket inactivity repeatedly. The async guard stops waiting but does not cancel the underlying upload; its worker retains scratch until actual I/O completes and has no receipt-commit code. Generation-zero puts make overlapping late attempts safe. The normal object sizes are bounded to 32 KiB per fragment / 128 KiB per minute, plus 32 bytes encryption framing.

This is not a 15-second whole-flush guarantee. Pre-existing paths remain outside this change:

  • ensure_summary: a 30-second polling/lease window, plus Firestore RPC latency.
  • Capacity reservation, privacy-authority reads, receipt reads/commits and SDK rollback: no application-wide wall deadline. The pinned Firestore SDK has 60-second RPC timeouts / retry deadlines on relevant methods; those are not a finite total transaction or flush bound.
  • Waiting for the sink lock or an executor slot for commit/seal: no application wait deadline.
  • _flush drains all queued items under one lock; for N items, upload waiting alone can be 8N seconds, plus those unchanged database/processing paths. Each continuous minute can also seal/compose and clean up parts. Compose/reload use the pre-existing 10-second socket inactivity timeouts, which are not wall-clock deadlines.
  • close() calls flush and seal, adding sequential work. Consequently these unchanged paths can still exceed 15 seconds; there is no finite application-level upper bound for a full flush. They are deliberately outside this PR.

Validation

Only the file-isolated test.sh runner was used for backend tests:

cd backend && BACKEND_PYTEST_WORKERS=4 BACKEND_UNIT_TEST_FILE_LIST=/Volumes/Ephemeral/scratch/cap-tests.txt nice -n 10 ./test.sh

The list contains tests/unit/test_cap_publication_retry.py, test_sync_cap_hold.py, test_cap_hold_durability.py, test_live_cap_hold.py, and the CI-flagged test_action_item_dedup.py, test_rate_limiting.py, test_background_task_ratchet.py, test_clean_sweep_migrations.py (each under tests/unit/).

Coverage includes first upload timeout then success, second timeout preserving today's failure, an actual wall-deadline guard retaining late results/scratch, ambiguous upload or reload followed by verified 412 adoption (mismatches rejected), unchanged #22966 Firestore cases, and an old commit landing after recovery's absence read while audio remains present.

The old shard 3/6 and 4/6 failures were import errors, not timing failures: ModuleNotFoundError: No module named 'google.auth' in action-item dedup and rate-limiting fixtures that stub Google modules. The new import in database/_client.py caused both; restoring that file removes it. Logs: shard 3, shard 4.

Local results: 147 passed across the four requested suites (test_cap_publication_retry: 64; test_sync_cap_hold: 35; test_cap_hold_durability: 28; test_live_cap_hold: 20). The two CI regression files pass locally: 113 passed, 1 skipped (test_action_item_dedup: 23; test_rate_limiting: 90 passed, 1 skipped). The two additional CI guard files also pass: background-task ratchet 5, clean-sweep migrations 55. Total: 320 passed, 1 skipped. The bounded push gate passed all 32 manifest checks, full backend Pyright (0 errors), its selected unit suites and formatting. Metadata validation passed separately. Follow-up CI found two guard violations: the Requests utility import ban and unrecognized future consumption. The final tree isolates pure SDK exception policy under config/ and explicitly reads the owned completed future after its async wait. No guard or baseline was weakened. A cancelled waiter also cannot trigger another upload while the retained attempt is still pending; a later flush only adopts its completed result. Pushed head: ed95e2838073c380407d3d2083167f3ad2e868ad. GitHub checks for this head are the authoritative CI result. No production account data was read, no deployment was performed, and no GCP tier was used.

Product invariants affected

none

A GCS upload or Firestore call whose HTTP/gRPC reply never arrived closed
the live held-audio socket with 1011 because run_transactional(transient=True)
restarted only Firestore throttle/contention classes; a requests ReadTimeout
surfaced from recover() and failed the flush (stt_cap_live_held
outcome=publication_failed, omi_held_content_publication_retry_total at 0).

Route transport faults through the transient predicate instead: requests
timeouts/connection errors/chunked truncation, urllib3 ProtocolError,
builtin ConnectionError, google.auth TransportError, and api_core RetryError
now restart the idempotent publication transaction with the existing
equal-jitter backoff (3 attempts, sleeps under 0.6s; worst case adds two
10s RPC timeouts per operation). The callables already re-read and refuse a
second increment, and GCS uploads replay against if_generation_match=0, so
an ambiguous success resolves as 412-plus-reload. upload_held_audio now
verifies the stored length on that 412 path (opt-in bound: manifest 128K,
fragments 32K) so a retry never adopts a foreign object at that identity.

Custody-deciding recovery reads and preconditioned cleanup writes outside
the transaction get a bounded no-sleep leaf retry, and post-commit garbage
cleanup defers on a transport fault instead of closing the socket over
durable audio. omi_held_content_publication_retry_total gains a closed-set
cause label (throttle|timeout|connection|other) so these episodes are
visible. Deliberately unchanged: bare TimeoutError (asyncio alias) stays
non-retryable, and _publish_for_recovery keeps its one-shot budget.
Required cases: a ReadTimeout on upload followed by success publishes once
with retried_ok/timeout and no 1011; persistent timeouts exhaust the
budget and fail closed exactly as today, counted; an ambiguous upload that
landed before a lost commit reply is reused via the generation
precondition and never duplicated; a Firestore commit/read transport fault
(ReadTimeout, api_core RetryError) restarts once and is counted once.

Also covers the 412 size verification in upload_held_audio, the
no-sleep recovery-leaf retry, post-commit cleanup deferral, and the
closed-set cause labels. Existing single-throttle verification-read
scenarios moved from staged_unverified to retried_ok/throttle because the
bounded leaf retry now confirms the stored row.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 21, 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-21T13:44:20.503305Z ed95e28 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.

The retry budget could outlast the client heartbeat: a 10s GCS upload
replayed 3 times plus backoff stalls the listen receiver's inline flush
~30s under the sink lock, past the app's 20s ping/pong close window, and
leaf reads rode the Firestore client defaults (60s timeout under a 60s
retry deadline) rather than any caller deadline.

One PublicationBudget now spans every attempt, backoff sleep, and
custody-deciding leaf read of a live publication:

- run_transactional accepts the budget: restarts begin only while a 2s
  minimum slice remains, backoff never sleeps past the deadline, and an
  early stop is recorded as the same exhausted outcome (today's staged
  hand-off / 1011 fallback then runs with the failure it has).
- Every RPC timeout is derived from the time remaining at call time:
  reads and uploads shrink below the 10s ceiling, and each attempt's
  commit gets an explicit retry=None and remaining-time timeout via an
  instance-level _commit bind (google-cloud-firestore 2.20's Transaction
  commit forwards no timeout kwargs; the gapic defaults are 60s).
- Leaf retries pass explicit timeout=/retry=None, floored at a 2s
  confirmation slice so the fallback can still confirm a staged row just
  past a spent deadline; they stop retrying once it is spent.
- The redrive sweep shares seal(), so seal builds the larger 60s
  recovery deadline for expired_only visits; the live flush keeps 12s.
  Post-commit garbage cleanup derives from the same budget and defers to
  the sweep when it is spent.

Exception classification no longer trusts wrappers: an api_core
RetryError or google.auth TransportError is retried (and labeled) by its
inner fault, mirroring google-cloud-storage 2.18's retry predicate; one
wrapping a permanent fault or nothing at all stays non-retryable.
…ification

Fake-clock coverage for the 12s end-to-end budget: persistent upload
timeouts end inside the deadline counted exhausted and fail closed with
1011; per-attempt read/upload timeouts shrink as the deadline drains
(10s, then what is left); the fallback's leaf reads run on the floored
2s confirmation slice with retry=None and never retry past a spent
deadline; seal() takes the 60s recovery deadline only for expired_only
sweep visits; run_transactional stops restarting with attempts left and
records exhausted, and the SDK commit bind issues retry=None with the
remaining timeout (and leaves non-SDK transactions untouched).

Wrapper-cause classification: a RetryError or TransportError wrapping a
retryable fault keeps the inner, accurate label (ReadTimeout -> timeout,
ConnectionError -> connection, DeadlineExceeded -> deadline_exceeded),
while one wrapping a permanent fault — or nothing at all — is not
retried.
@Git-on-my-level Git-on-my-level changed the title feat(backend): retry transport timeouts in live held publication refactor(backend): retry only immutable held-audio uploads Oct 21, 2026

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

ℹ️ 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 thread backend/utils/sync/live_cap_upload.py Outdated
deadline = asyncio.timeout(UPLOAD_ATTEMPT_SECONDS)
try:
async with deadline:
fields = await asyncio.shield(asyncio.wrap_future(future))

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 Keep late uploads fenced through account deletion

When encoding or uploading outlives the four-second wait, shielding this future lets its worker continue after prepare() returns a timeout. The worker's storage fence is only a point-in-time, nontransactional read, so an account deletion can subsequently acquire its gate, perform the single owner-prefix sweep in services/users/account_deletion.py, and complete before this late generation-zero put recreates held audio for the deleted user; the later receipt fence cannot help because this worker performs only the upload. Keep in-flight uploads transactionally fenced through completion, or make deletion await and re-sweep them.

Useful? React with 👍 / 👎.

Comment on lines +83 to +84
future: Future[dict] = submit_with_context(storage_executor, upload)
source.upload_attempts.append(future)

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 Bound the overlapping upload work

When storage_executor is saturated or _upload_audio exceeds four seconds—its FFmpeg step alone permits 20 seconds—this submission remains queued or running while the loop immediately submits a second identical attempt. Because the shared storage executor has an unbounded queue and each closure retains the raw PCM, a storage slowdown causes two abandoned jobs per fragment to accumulate, amplifying the outage into memory exhaustion and starving unrelated storage work. Use bounded/dedicated capacity or avoid overlapping an attempt whose worker has not finished.

AGENTS.md reference: backend/AGENTS.md:L263-L268

Useful? React with 👍 / 👎.

Comment thread backend/utils/sync/live_cap_upload.py Outdated
Comment on lines +100 to +104
cause = transport_cause(last_error)
if cause is None:
raise last_error
record_publication_retry('exhausted', transport_cause(last_error) or 'timeout')
raise last_error or requests.exceptions.ReadTimeout('immutable live upload outcome unknown')

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 Recheck late successes before reporting exhaustion

If the first worker crosses its four-second deadline but finishes successfully while the second attempt is being awaited, its fields remain only on the first future. When the second attempt times out or fails, this path raises last_error without revisiting that now-completed successful future, so _publish_audio() can fail the flush and close the listen socket even though the immutable object is already durable. Rescan all retained attempts before raising a permanent error or exhaustion.

Useful? React with 👍 / 👎.

Comment on lines +83 to +84
future: Future[dict] = submit_with_context(storage_executor, upload)
source.upload_attempts.append(future)

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 Avoid fire-and-forget logging for awaited upload failures

When the first upload raises a transport error that this function successfully retries, submit_with_context() still runs its done callback and logs the exception at ERROR before the awaiting code consumes it. Consequently, every recovered first-attempt timeout or connection reset emits a misleading background task ... failed traceback and reaches error reporting despite the publication succeeding; use a caller-owned context-preserving submission without the fire-and-forget error callback, or otherwise suppress failures acknowledged here.

AGENTS.md reference: backend/AGENTS.md:L263-L267

Useful? React with 👍 / 👎.

Comment on lines +94 to +96
'cause separates Firestore throttling (throttle) from transport timeouts (timeout) '
'and dropped connections (connection). Labels are a closed set and never identify a person',
['outcome', 'cause'],

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 Record Firestore throttling under the throttle cause

The new metric contract says cause="throttle" identifies Firestore throttling, but the Firestore retry path in live_cap_publication.commit_publication() still calls record_publication_retry() without a cause, so every ResourceExhausted retry and exhaustion is emitted as cause="other" and the throttle series remains permanently zero. Pass the classified Firestore cause when recording those outcomes so dashboards can distinguish the failure modes advertised by this label.

Useful? React with 👍 / 👎.

@Git-on-my-level
Git-on-my-level merged commit 65120c8 into main Oct 21, 2026
69 checks passed
@Git-on-my-level
Git-on-my-level deleted the lane/cap-publication-timeout branch October 21, 2026 14:27
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