Repository navigation
fix: preserve live held audio through transient staging failures - #23309
Conversation
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 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".
| 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') |
There was a problem hiding this comment.
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 👍 / 👎.
| 'stage_seconds': seconds, | ||
| 'seconds': 0, # Only seal increments the published summary. |
There was a problem hiding this comment.
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 👍 / 👎.
| 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__ | ||
| ) |
There was a problem hiding this comment.
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 👍 / 👎.
| 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 |
There was a problem hiding this comment.
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 👍 / 👎.
| identity = source.identity if standalone else f'late:{source.identity}' | ||
| fragment_id = f'pending:{source.identity}' if standalone else source.identity |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
💡 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) |
There was a problem hiding this comment.
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: |
There was a problem hiding this comment.
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 👍 / 👎.
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-42re-raises after two lifetime attempts.backend/utils/sync/live_cap_hold.py:87-94propagated that failure throughflush;backend/routers/listen/receiver.py:2545and:2583callmark_listen_internal_error(:189, 1011). The updater had an unguarded await atbackend/utils/sync/live_cap_hold.py:531, reached from the WS task spawned atbackend/routers/listen/receiver.py:2407.Retry and custody
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.cap_held_updatescatches/logs each iteration's exception and continues. Sealing or quota-refund errors cannot revoke already durable custody.SHUTDOWN_DELIVERY_SECONDSlimit. 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 useStagingRetryOutcomethroughreason_label, including initialization; the reason-label debt baseline is unchanged.retainedcounts every non-final both-stores-down flush that still holds volatile PCM, independently of the 60s per-hold warning limit;deferredmeans 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 ofretainedfor 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, viaomi-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 viaBACKEND_PYTEST_WORKERS=4 BACKEND_UNIT_TEST_FILE_LIST=/Volumes/Ephemeral/scratch/cap-staging-review-tests.txt nice -n 10 ./test.shthroughomi-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 preflightandscripts/pr-preflight --pr-body-fileeach 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.shrunner (cap-staging-enum-tests.txt: the 30 files below plustest_reason_label_enums.pyandtest_reserved_capacity_only.py). The latter also passed 68/68 on a clean detachedorigin/maincheckout at2c214b0cf77395e1201205a066658d2eec8a266e. The old shard 2/6 log reports 68 passed for reserved capacity and identifies onlytest_reason_label_enums.pyas 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)