Skip to content

fix: preserve live held audio through transient staging failures - #23309

Merged
Git-on-my-level merged 7 commits into
mainfrom
lane/cap-staging-resilience
Oct 22, 2026
Merged

Git-on-my-level merged 7 commits into
mainfrom
lane/cap-staging-resilience

Conversation

@Git-on-my-level

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

Copy link
Copy Markdown
Member

Problem and behavior

A transient GCS timeout/503 burst exhausted the live held-audio upload budget and escaped both the receive/final-flush boundary (1011) and cap_held_updates. Keep PCM until an immutable publication or owner-fenced encrypted journal confirms custody, and recover journals with the existing staging sweep. Open for review only; do not merge or deploy.

Root cause

At base 800f812686b, backend/utils/sync/live_cap_upload.py:41-42 re-raises after two lifetime attempts. backend/utils/sync/live_cap_hold.py:87-94 propagated that failure through flush; backend/routers/listen/receiver.py:2545 and :2583 call mark_listen_internal_error (:189, 1011). The updater had an unguarded await at backend/utils/sync/live_cap_hold.py:531, reached from the WS task spawned at backend/routers/listen/receiver.py:2407.

Retry and custody

  • Two upload attempts, 1.5-second socket timeout, 4-second per-attempt async wait, 8-second total including exponential backoff with scaled uniform jitter. Retry timeouts, resets, HTTP 408/429 and 5xx. Other 4xx get one attempt and the permanent outcome. Backoff uses min(0.2 * 2**(n-1), 1.0) * U(0.5, 1.5) seconds (100–300ms for the one backoff with two attempts). Both encoder passes use the original 20-second subprocess timeout; the 8s upload budget excludes encoding, and the outer 28s shutdown deadline still applies.
  • Exhausted/permanent uploads hand off encrypted Opus (at most 128KiB plus encrypted metadata) to an immediately eligible, non-expiring staging journal under the existing owner/deletion fence. No new query, index, local durable-file assumption or scheduler. Restore uses immutable fragment provenance and the existing claim ledger; ambiguous original commits count once. Standalone/fragmentation-off journals use the original receipt identity.
  • PCM stays owned until that handoff succeeds. Existing 15s per-session bound (60s with fragmentation off), plus 600s aggregate per pod. Full bounds force publication/handoff before accepting more audio; never evict old chunks. If both stores are unavailable, retain and retry while space remains. At a full bound/final close, inability to transfer custody remains a real error: 1011 is allowed only when continuing would risk losing audio.
  • cap_held_updates catches/logs each iteration's exception and continues. Sealing or quota-refund errors cannot revoke already durable custody.
  • Close and lifespan share the 28s SHUTDOWN_DELIVERY_SECONDS limit. A deferred fragment already has its durable redrive journal before the live flush returns; close/SIGTERM do not depend on GCS recovering. Late upload workers retain encoded bytes only and cannot publish receipts.

Metrics

omi_held_content_staging_retry_total{outcome="retried_ok|deferred|exhausted|permanent|retained"}, omi_held_content_deferred_seconds_total (cumulative journal handoffs), omi_held_content_pcm_custody_seconds (current process-local pending PCM). Existing publication/redrive signals remain. No identity labels. All five staging outcomes use StagingRetryOutcome through reason_label, including initialization; the reason-label debt baseline is unchanged. retained counts every non-final both-stores-down flush that still holds volatile PCM, independently of the 60s per-hold warning limit; deferred means a durable journal exists. Updater and publication-observer warnings are also limited per hold/outcome to once per 60s. The PCM occupancy gauge refreshes on capture/retirement and each one-second updater tick; an unchanged idle value is valid while PCM remains held. Use increases of retained for new custody-risk events, not gauge movement as a heartbeat.

Validation

Synthetic/hermetic only: no production calls, production logs, Firestore service, or GCP tier used.

Required runner: from backend, BACKEND_PYTEST_WORKERS=4 BACKEND_UNIT_TEST_FILE_LIST=/Volumes/Ephemeral/scratch/cap-staging-tests.txt nice -n 10 ./test.sh, via omi-heavy. Expanded selection covers all hold/staging/publication and listen receiver tests plus cap recovery and shutdown regressions. Current qualification: 2,528 tests passed across all 30 files; the seven-file affected suite separately passed 168 tests via BACKEND_PYTEST_WORKERS=4 BACKEND_UNIT_TEST_FILE_LIST=/Volumes/Ephemeral/scratch/cap-staging-review-tests.txt nice -n 10 ./test.sh through omi-heavy. The suite includes 23 resilience cases plus the restored-encoder-budget regression, retained-counter/warning limits, permanent updater/observer warning limits, idle gauge refresh, and journal preservation after a failed redrive upload. make preflight and scripts/pr-preflight --pr-body-file each passed all 33 manifest checks. Standard pre-push passed, including type checking (zero errors), related tests, runtime source closure and OpenAPI compatibility. The receiver line count is unchanged (4 added / 4 removed).

Latest enum qualification: 2,615 passed across 32 files through the same test.sh runner (cap-staging-enum-tests.txt: the 30 files below plus test_reason_label_enums.py and test_reserved_capacity_only.py). The latter also passed 68/68 on a clean detached origin/main checkout at 2c214b0cf77395e1201205a066658d2eec8a266e. The old shard 2/6 log reports 68 passed for reserved capacity and identifies only test_reason_label_enums.py as failed; the apparent Dream failure is interleaved output. No Dream code changed.

The new behavioral tests cover timeout/503 bursts, permanent 403 custody, exact-once redrive, both stores unavailable, task containment, bounds, late workers at client close/SIGTERM, and the real receive/final-flush path.

Product invariants affected

none

Failure-Class: FC-recoverable-provider-failure-terminal

Required runner file selection (30 files)
tests/unit/test_cap_hold_batch_admission.py
tests/unit/test_cap_hold_batch_debit.py
tests/unit/test_cap_hold_durability.py
tests/unit/test_cap_hold_hygiene.py
tests/unit/test_cap_hold_summary_rebuild.py
tests/unit/test_cap_publication_retry.py
tests/unit/test_cap_recovery_pacing.py
tests/unit/test_cap_staging_resilience.py
tests/unit/test_listen_receiver_decode_failure_report.py
tests/unit/test_listen_receiver_frame_recovery.py
tests/unit/test_listen_receiver_opus_frame_capacity.py
tests/unit/test_listen_runtime_regressions.py
tests/unit/test_live_cap_capture_order.py
tests/unit/test_live_cap_codec.py
tests/unit/test_live_cap_hold.py
tests/unit/test_live_recovery_shutdown_tail.py
tests/unit/test_stt_cap_cohort_lanes.py
tests/unit/test_stt_cap_dispatch.py
tests/unit/test_stt_cap_dispatch_http.py
tests/unit/test_stt_cap_recovery_cohort.py
tests/unit/test_stt_cap_runtime_cohort.py
tests/unit/test_sync_cap_content.py
tests/unit/test_sync_cap_coordinator.py
tests/unit/test_sync_cap_hold.py
tests/unit/test_sync_cap_hold_recovery.py
tests/unit/test_sync_cap_reconciliation_metrics.py
tests/unit/test_sync_cap_recovery_audio.py
tests/unit/test_sync_cap_recovery_checkpoint.py
tests/unit/test_sync_cap_recovery_dispatch_signal.py
tests/unit/test_sync_cap_recovery_plan.py

View guided diff Turn on auto-fix

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 22, 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-22T15:40:10.356429Z a5f998c 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: 90d60cb4a4

ℹ️ 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 578 to +581
if self.buffered_seconds() + len(part) / (2 * rate) > self.bound + 1e-9:
raise RuntimeError('live held audio packet exceeds custody bound')
if pod_pending_seconds() + len(part) / (2 * rate) > MAX_POD_PENDING_SECONDS + 1e-9:
raise RuntimeError('live held audio pod custody bound reached')

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 Flush synchronous capture before enforcing custody bounds

When denied or replay capture arrives through the synchronous capture_observer path, reaching the 15-second session limit or 600-second pod limit raises here without attempting the forced handoff implemented by _packet_parts. A replay burst can therefore propagate this exception into receive_data, set close code 1011, and disconnect the client even when storage is currently able to accept the buffered audio; route this path through async backpressure or otherwise flush before rejecting the next packet.

Useful? React with 👍 / 👎.

Comment on lines +45 to +46
'stage_seconds': seconds,
'seconds': 0, # Only seal increments the published summary.

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 Include journaled duration in pending backlog totals

During a GCS outage, every deferred journal records its duration only in stage_seconds while setting seconds to zero. The existing fleet snapshot sums seconds for all staging rows, so omi_held_content_pending_seconds reports zero for the journaled audio precisely while the outage backlog is accumulating; preserve the duration in the field used by the snapshot and avoid double-adding it when restoration appends the fragment.

Useful? React with 👍 / 👎.

Comment on lines +661 to +666
except Exception as error:
# Audio already has durable custody. A failed quota refund
# cannot justify an internal-error close or erase that data.
logger.warning(
'event=stt_cap_live_held outcome=refund_deferred exception_type=%s', type(error).__name__
)

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 Retain failed capacity refunds for retry

When live_cap_capacity.release fails, this branch only logs the error and _close subsequently removes the sink from ACTIVE, while no durable reconciler records the Capacity identity. The reservation therefore remains open and the monthly quota counters retain all 64 reserved slots (and the associated block bytes), so repeated short sessions closing during a Firestore outage can exhaust a user's held-audio quota despite little stored audio; persist the refund obligation or keep it reachable for retry after custody has closed.

Useful? React with 👍 / 👎.

Comment on lines +136 to +141
except Exception as error:
if live_cap_upload.transient(error) or await run_blocking(
db_executor, is_retryable_firestore_transaction_error, error
):
raise StagingDeferred('live staging retains process custody') from error
raise publication_error from error

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 Retain PCM after permanent dual-store failures

When the original GCS operation fails permanently (for example, HTTP 403) and the journal create also gets a non-retryable Firestore error, this rethrows the original permanent upload error instead of StagingDeferred. An ordinary non-final flush does not suppress that error, so it escapes the receive path and closes the socket with 1011 even when the sink is still below its custody bound; classify every failed journal handoff as retained process custody until a bound or final close requires failing closed.

Useful? React with 👍 / 👎.

Comment on lines +37 to +38
identity = source.identity if standalone else f'late:{source.identity}'
fragment_id = f'pending:{source.identity}' if standalone else source.identity

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 Clean up ambiguous standalone upload objects

With fragmentation disabled, a timed-out immutable upload can still complete in GCS after the coordinator has created this journal. Recovery deliberately uploads a different pending:<source> fragment and seals that object into the receipt, but no row or cleanup task retains the generation of the original chunks/{uid}/cap-held/{source}.opus.enc object, leaving up to 128 KiB of encrypted customer audio orphaned for every such ambiguous upload until account deletion; persist enough provenance to delete the original after the journal wins.

Useful? React with 👍 / 👎.

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

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

live_size_limit=live_cap_codec.MAX_OBJECT_BYTES,
rpc_timeout=1.5,
)
append(uid, path, Publication(uid, identity=identity), source, metadata, row['stage_seconds'], emergency=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.

P1 Badge Clear the inline journal after fallback restoration

When this emergency append's Firestore transaction exhausts after producing staged_updates, live_cap_staging.append falls back through _stage_for_redrive to ref.update(merged). That update preserves the unmentioned stage_pending fields, so the recursively invoked seal sees the journal again; subsequent appends detect the restored part and return without ever clearing the journal, leaving the row unable to seal and causing repeated restoration/uploads or recursion failures on every sweep. Ensure every emergency-append fallback atomically removes the inline journal fields after recording the part.

Useful? React with 👍 / 👎.

await run_blocking(db_executor, live_cap_capacity.release, self.capacity)
self.capacity = None
if self.capacity is None or (self.capacity.used == live_cap_capacity.BLOCK_GROUPS and self._group is None):
if self.capacity is None or self.capacity.used == live_cap_capacity.BLOCK_GROUPS:

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 Defer block rollover until the open group is sealed

When the first fragment of the 64th group consumes the final slot, later fragments of that same still-open group now trigger acquisition of another 64-group block even though the group already owns capacity. Near the monthly limit—or during a Firestore outage—this acquisition can reject or defer the remaining fragments and ultimately fail the socket despite no new group being created; keep using the full block while _group is open and acquire the next block only after sealing it.

Useful? React with 👍 / 👎.

@Git-on-my-level
Git-on-my-level merged commit f034ee3 into main Oct 22, 2026
63 of 65 checks passed
@Git-on-my-level
Git-on-my-level deleted the lane/cap-staging-resilience branch October 22, 2026 16:01
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