Repository navigation
fix(backend): preserve audio custody with a durable outbox and backpressure - #23542
Conversation
…essure Commit immutable audio and generation-pinned frame manifests before retiring PCM. Retain raw packs on pressure/failure, gate transcript/send boundaries, and expose independent audio receipts and would-be-drop telemetry.
Persist adapter metadata and validate create-only/generation preconditions so the real listen/pusher harness can exercise the default durable path.
…ommit Keep the frozen pack retryable if task creation fails, and refuse a custody barrier that still has an uncommitted pack. Cover the supervisor-close race.
Keep the frame loop within the type analyzer's complexity budget, use the public storage accessor, and preserve shared historical protocol fixtures.
Pair the refusal/failure counters with a last-risk timestamp so a new pod's first event cannot disappear behind an unobserved zero baseline.
… custody Check hydrated PCM order and sample counts, retain both conflicting capture receipts, and preserve the existing timeline-write telemetry on projection.
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: 3a8a39643d
ℹ️ 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".
| audio_files = await run_blocking( | ||
| storage_executor, conversations_db.create_audio_files_from_chunks, uid, conv_id | ||
| ) |
There was a problem hiding this comment.
Deduplicate raw custody coverage before publishing audio files
With the deployed READ=true and STOP_PCM=false settings, each batch now has both per-run raw-live objects and a projected legacy chunk. create_audio_files_from_chunks() calls storage.list_audio_chunks(), whose raw-pack filter only checks whether an existing chunk's start falls inside the pack, not whether the chunk covers it. Consequently, a 60-second projected chunk plus sixty one-second custody objects produces 119 seconds of listed coverage and two overlapping AudioFile groups; I reproduced this using the production listing and grouping functions. Exclude already-covered raw intervals before updating audio_files, so normal recordings do not expose the same audio twice.
Useful? React with 👍 / 👎.
| if durable_queue.full(): | ||
| BACKPRESSURE.labels(stage='pusher_queue').inc() | ||
| record_would_drop('pusher_queue') | ||
| await durable_queue.put(receipt) |
There was a problem hiding this comment.
Apply v2 overlap trimming to the durable projection queue
For an overlapping v2 replay, this queues the entire original receipt before receive_tasks() performs its existing duplicate detection and overlap trimming. The durable worker subsequently hydrates that receipt rather than the trimmed audio_data, so the trimming no longer protects playback projection. For example, after accepting [0,1), a conflicting replay covering [0.5,1.5) can project its conflicting [0.5,1) prefix as another chunk, whereas the existing v2 handler explicitly discards that prefix and retains only [1,1.5). Preserve the complete original for custody, but queue only the accepted range for derivative projection.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 09a36e3927
ℹ️ 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".
| 'span': { | ||
| 'start': ref.start, | ||
| 'samples': ref.samples, | ||
| 'sample_rate': ref.sample_rate, | ||
| }, |
There was a problem hiding this comment.
Preserve legacy timing semantics for non-v2 producers
For non-v2 connections, including multichannel and custom-STT sessions, ListenPusherSession._audio_bytes_flush() still timestamps each envelope using last_received - duration, not a continuous capture clock. The durable worker nevertheless assigns authoritative spans here and applies the 1 ms continuity check unconditionally. Ordinary arrival jitter therefore flushes nearly every envelope separately, and group_chunks_by_coverage() publishes separate AudioFiles for those small gaps or overlaps instead of the previous continuous recording. For example, three one-second envelopes starting at 1000, 1001.02 and 1002.01 produce three AudioFiles. Keep legacy derivative batching and span semantics for connections that did not negotiate v2, while retaining the original custody receipts.
Useful? React with 👍 / 👎.
Keep spanless legacy batches continuous despite arrival jitter while retaining every original in immutable custody. Mark estimated clocks explicitly and recover these originals by receipt instead of fabricating positioned raw playback. Cover exact bytes and the single legacy projection in regression QA.
Retain the new-buyer flag and the default-on audio custody kill switch. Group audio flags together to avoid top-of-registry insertion conflicts. Preserve main's subscription metrics, episode changes and test runner.
Drive the real pusher handler through 21 pending conversations with failed projection uploads. Use event latches instead of elapsed-time assumptions, and verify every original through its immutable receipt.
Separate precise raw and projected source positions from millisecond filename aliases. Preserve old AudioFile requests without redirecting a full projected chunk to a tiny raw fragment, and keep raw selections out of batch aliases. Add batch/non-batch byte-integrity regressions and use the canonical critical notification policy plus an existing dashboard link for custody alerts.
Resolve legacy timestamp views only against the entire stored immutable manifest, and pass the proven source selection through both artifact builders. Keep old handles for uniquely covering groups without trusting stale artifacts. Exercise old projected and raw-only identities, both builder guards, and changed or removed generations. Match the Python deadline clock in Darwin's local sync gauntlet; leave Linux runtime, request budgets and safety guards unchanged.
The durable outbox (BasedHardware#23542, default-on since 10-25 06:00Z) ran commit_pcm on every opcode-101 audio message: one raw-live media object plus one audio-outbox manifest per ~0.5-1 s message. Fleet-wide that was ~15-18M GCS Class A writes/day (~$4-5k/mo at $9.0/M), plus the PCM bytes written twice during the STOP_PCM interim and custody media retained forever. Lead ruling 759d9c: batch the commits; audio-loss protection stays (no switch-off). Windows ride the flush boundaries the batched .batch.enc path always used — 60 s of audio (PRIVATE_CLOUD_CHUNK_DURATION), conversation switch, v2 discontinuity, process_conversation, and shutdown — so the durable branch of _queue_private_cloud_chunk now commits one commit_pcm_window media+manifest pair for the whole buffered window instead of no-op'ing, and the per-message archive_private_audio/queue_private_projection closures are gone. What does not change: - Custody semantics: immutable, generation-pinned, content-addressed, never-delete, fail-closed. A receipt still exists only after both objects commit, so nothing acknowledged is ever uncommitted; a mid-session commit failure still fails the session closed (1011) at the next boundary, and a shutdown tail failure records window_tail failures/would-drops and closes 1011 so the producer replays the unacknowledged tail. - The .batch.enc projection is byte-identical: the window holds exactly the accepted (post-replay-trim) stream that the per-message reads used to concatenate; spans/timestamps aggregate to the same values. - Unlinked pre-103 audio still commits (under 'unlinked' at the next flush). - Zero runs are kept (custody never drops captured audio; the GCS-4 silent skip stays legacy-projection-only). What does change (deliberate): the custody media stores the accepted stream per window instead of the untrimmed bytes per message. Replay duplicates are byte-verified or conflict-dropped by the v2 logic before acceptance, so no audio-distinct bytes are lost; conflicting "originals" are no longer stored twice. Exposure to a hard pod crash is bounded by one window (<=60 s) of unacknowledged audio — the same bound the raw-live pack path has always had, and the client replays unacknowledged audio on reconnect. Ops effect: custody writes return to ~2 objects per 60 s window per conversation (hundreds of thousands/day fleet-wide vs ~15-18M), and the projector's PCM hydration becomes one read per window instead of per message. New coverage: one custody pair per window (frames pinned per message), conversation-switch boundary commits under the old conversation id, shutdown tail failure never acks and closes 1011, mid-session boundary failure fails closed with zero acks, and queue backpressure keeps every receipt after a failing projection (the per-message pending-map overflow scenario is replaced by the now-reachable queue-cap path; the pending-map branch stays as defense in depth). Failure-Class: none
…mmediate (#23656) LISTEN's one-second relay and transcript barriers forced a durable raw-pack flush on every cycle after #23542. The investigation reports attribute approximately 20–21k private-sync object writes/minute and +5.5M Firestore reads/hour to those commits. This change implements lead rulings e9e7ed and 316c46; it keeps the durable outbox enabled. The relay neither waits for storage uploads nor flushes an active pack. Packs commit at their existing 60-second, conversation/hour/size, 4096-frame and disconnect boundaries. Fence, tombstone and protection reads therefore run per window; no privacy authority is cached. Original bytes remain in active/frozen packs until immutable media and manifest receipts exist. Only client custody ACKs wait behind those commits. The retired relay-barrier dependency is removed from the session/runtime together. Transcript persistence and live STT delivery continue immediately. Coverage ledger writes and `capture_committed` ACKs wait behind an accepted-frame checkpoint, including earlier failed commits. A bounded queue keeps a frozen oldest snapshot and one coalesced cumulative successor per conversation, so continuous transcript arrivals cannot starve ACK progress. Queue overflow withholds the optional coverage ACK. Audio-only receipts retain their existing opt-in contract and emit only after both objects commit. Storage-consent contract (lead ruling 895e42): that raw-audio gate applies to consenting captures. With private cloud audio storage disabled or absent, preserve the pre-#23542 semantics exactly: coverage publication/WAL release follows the successful durable transcript transaction, never an empty archive checkpoint. It emits no audio-only receipt and creates no audio-storage obligation. Failed transcript persistence emits no coverage ACK. This prevents unbounded phone retention for an upload that consent forbids. With storage consent, an archive that accepted no frames cannot certify coverage. Client WAL impact: time-to-ACK grows from roughly one relay cycle to pack completion: up to an active 60-second window plus storage latency for audio-only receipts, or an earlier boundary. A coalesced coverage snapshot can include the next pack, so coverage-based WAL release may retain into the following active window as well. An idle partial window remains unacknowledged until more audio closes the window or disconnect flushes the tail. Storage failures retain WAL through successful retry. A pod crash mid-window issues no audio/coverage ACK for uncommitted frames. Installed legacy clients' retention behavior remains a separate client compatibility constraint. Validation (local, BasedHardware/omi task worktree): - `omi-heavy run -- nice -n 19 env BACKEND_PYTEST_WORKERS=1 BACKEND_UNIT_TEST_FILE_LIST=/Volumes/Ephemeral/scratch/listencustody/tests.txt bash backend/test.sh`: 194 passed across custody, capture coverage, relay-session and archive tests, rerun at the final consent delta. Covers mid-window crash, disconnect tail, out-of-order failure/retry, bounded ACK coalescing/progress, real relay sends including a deliberately blocked in-flight upload, pack boundaries, and zero storage/fence/tombstone/protection calls across 59 one-second relay gates followed by one media+manifest pair at 60 seconds. Consent regressions cover no audio writes/receipts for storage-off, legacy coverage release after durable transcript success, no release after transaction failure, and refusal to certify an empty consented archive. - `omi-heavy run -- nice -n 19 bash backend/testing/e2e/run.sh -q --tb=short`: 135 passed, 3 skipped, 2 expected failures. - Additional preflight/static results are recorded in the lane handoff. Release: lead merges and rolls LISTEN in the next off-peak train. No deployment, flag flip or production data access occurs in this PR. After deployment, use ro-prod aggregate metrics to require private-sync WriteObject ~120–140k/hour and LISTEN Firestore reads <=2M/hour, with serving image/release identity and latency/custody failure checks. Savings remain unverified until that live acceptance. Rollback is a lead-approved revert/redeploy of this PR; keep `AUDIO_DURABLE_OUTBOX_ENABLED` on. Failure-Class: new UI-Evidence: none -- reason: backend custody scheduling only; no client UI changes Owns: listencustody
Pusher could evict the only PCM copy at queue, byte-budget and pending-conversation caps before archive upload. LiveAudioArchive could also clear uncommitted packs on capacity or upload failure. This fixes the custody failure behind the 2026-10-22..24 incident.
The default path commits original media and an immutable, generation-pinned frame manifest before relinquishing custody. Pusher queues bounded durable references and backpressures listen; raw capacity waits and failed/cancelled uploads retain frozen packs. Listen gates transcript persistence and outbound audio flushes on the archive barrier. Optional audio-only receipts remain separate from transcript coverage. Metrics and a source Grafana alert cover would-be drops and archive/projection failures. Only literal
AUDIO_DURABLE_OUTBOX_ENABLED=falserestores emergency legacy behavior.Playback discovers uncovered raw intervals without replacing accepted projected bytes. Exact sample selections participate in immutable fingerprints. Persisted rounded AudioFile requests remain valid only when their complete original source manifest still matches; generation changes and missing sources fail closed. Authoritative deletion fences and purge paths include custody objects.
Failure-Class: new
Root cause: process-local caps and successful socket/transcript operations were treated as custody while the only audio could still be in a pod. The shared prevention primitive is
commit_capture(media + frame manifest + immutable generations/digests), enforced by the producer durability barrier. The incident contract and reusable fault matrix are inbackend/docs/runbooks/audio-durable-outbox.mdandFC-pre-durability-audio-eviction.Product invariants affected
None of the locked invariant path scopes change. This supports the audio-retention principle in INV-CAP-1.
Line-Count-Exception: backend/routers/listen/receiver.py | 2782 -> 2796 | Preserve original malformed/undecodable frames and source mappings in the existing receive branches before derivative processing.
Line-Count-Exception: backend/routers/listen/transcripts.py | 1662 -> 1670 | Gate the existing transcript transaction on immutable raw-audio durability before issuing transcript coverage evidence.
Line-Count-Exception: backend/utils/other/storage.py | 2563 -> 2617 | Fence custody commits against deletion, bind playback to PCM identity, and separate precise raw/projection positions from millisecond compatibility aliases.
Line-Count-Exception: backend/testing/listen_pusher_stack/run.py | 1865 -> 1868 | Give each ASGI scenario its own hermetic local storage root and bucket so the real default-on custody barrier participates in the harness.
Line-Count-Exception: backend/utils/metrics.py | 1537 -> 1550 | Materialize bounded pusher queue counter children at startup so the new audio-loss alert has an observable zero baseline.
Validation and review
Final source:
41a14c797692ade086b016ab93469818b2751e0e, integrated with main646e54d738e156ecce3c3f9aa069ebf937bc92f4. All local test/build/preflight commands useomi-heavyandnice -n 19; backend tests use canonicalbackend/test.sh, four workers and explicit file lists.db01a7ande667dcauthorized the narrow follow-ups. Final delta review: SHIP, no findings (exec-crunch-version-code-dinosaur-limit-struggle,891bfa4..41a14c7). No review was cancelled. Current exact-head terminal CI is tracked by the GitHub checks on this PR.Lead handoff and release acceptance
No self-merge and no deployment by this lane. Per lead ruling
e667dc, deploy during David's day with a watch window. Lead owns merge, coordinated listen/pusher train, alert provisioning/delivery verification and serving release-identity checks.Installed-client WAL retention/audio-only release adoption still requires device acceptance. Server archive barriers protect transcript commits and outbound sends, but this PR alone cannot certify every installed producer. Unknown device positions stay unknown. Before release acceptance, measure staging playback byte integrity, listen latency and actual GCS operation spend. Each custody commit adds two immutable uploads and two generation reloads before projection hydration; production cost and latency are unmeasured.
No GCP tier was used. No production account reads/writes, IAM/secrets changes, historical data repair, user notifications or workflow changes were performed. Full local evidence and acceptance owners are in the workspace handoff
data/run-2026-10-13-two-lane-nemotron/outbox-pusher-durable-audio-report.md.