Repository navigation
Commit durable audio custody per window, not per message - #23641
Conversation
The durable outbox (#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
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: 0a5da41b7f
ℹ️ 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 private_cloud_sync_enabled and (current_conversation_id or durable_audio): | ||
| if private_cloud_chunk_start_time is None: | ||
| # Use timestamp from first buffer of this 5-second chunk | ||
| private_cloud_chunk_start_time = buffer_start_timestamp |
There was a problem hiding this comment.
Flush unlinked audio before assigning the first conversation
When PCM arrives before the first opcode-103 message, this new branch retains it in the window, but the opcode-103 handler only flushes when current_conversation_id is already truthy. It then assigns the new conversation and resets audio_timeline_last_end without clearing the buffered PCM. Subsequent audio is therefore concatenated with the unlinked audio even if their timestamps are discontinuous, and the entire window is committed and projected under the new conversation as one continuous span. Flush the unlinked window before assigning the first conversation so its ownership and timeline remain intact.
Useful? React with 👍 / 👎.
| if audio_custody == 1: | ||
| await websocket.send_bytes(audio_custody_ack_frame(receipt.to_dict())) | ||
| if receipt.conversation_id and receipt.samples: |
There was a problem hiding this comment.
Enqueue committed tail audio even when its ACK cannot be sent
For audio_custody=1 sessions, the new shutdown flush calls this helper after receiving WebSocketDisconnect. If sending the ACK on the closed connection raises, execution never reaches durable_queue.put, so the successfully archived final window never gets its playback projection. This can strand up to 60 seconds of audio on ordinary disconnects; legacy arrival_estimate archives are explicitly excluded from automatic raw playback discovery. Queue the committed receipt independently of ACK delivery, and treat a failed ACK as a transport failure rather than preventing projection. The test socket currently accepts sends after disconnect, so the shutdown tests do not exercise this path.
AGENTS.md reference: backend/AGENTS.md:L319-L319
Useful? React with 👍 / 👎.
| try: | ||
| await _queue_private_cloud_chunk() |
There was a problem hiding this comment.
Bound the shutdown flush when the projection worker has died
If the durable projection worker crashes while its queue is full—for example, seal_record_audio raises while producers have filled the queue—the supervisor cancels the receiver and waits for it at await receive_task. The receiver now enters this asynchronous final flush, which commits the remaining window and waits indefinitely on durable_queue.put; the only consumer has already exited, and the original cancellation does not interrupt awaits entered in finally. Consequently, the handler never reaches its bounded drain or closes the socket. Make finalization consumer-aware or bound its enqueue wait, retaining the committed archive for recovery when projection cannot proceed.
AGENTS.md reference: backend/AGENTS.md:L298-L298
Useful? React with 👍 / 👎.
| elif frame_checkpoint is not None: | ||
| durable_window_frames.append(frame_checkpoint) |
There was a problem hiding this comment.
Reject empty audio before accumulating window checkpoints
On a connection without timeline-v2 handling, opcode-101 messages with an empty PCM payload pass frame_header validation and now append a checkpoint here. Each append reserves zero bytes, while the window flush threshold depends exclusively on PCM buffer length, so repeated empty messages grow durable_window_frames indefinitely without consuming the byte budget or triggering a commit. The previous archive path explicitly ignored empty payloads. Reject or skip empty audio before creating checkpoints, or enforce a separate checkpoint-count bound, to prevent an otherwise bounded connection from exhausting process memory.
Useful? React with 👍 / 👎.
…ush, alignment, 104 await) Luna r1 on the window commit (#23641) found two gaps and the diff review surfaced a third: - P1: opcode-101 audio that arrives before the first opcode-103 buffered fine, but the 103 switch only flushed when a conversation id was already set, so pre-ID audio rode into the first conversation's window and was committed under it. The switch now flushes a buffered pre-ID window first, committing it under 'unlinked' exactly like the per-message path did. - P2: the per-message commit rejected non-sample-aligned PCM (len % 2) with a protocol error; buffering let two odd payloads merge into a silently zero-sample receipt. The durable buffer edge now enforces the same alignment contract, closing the session 1003 like before. - The process_conversation (104) flush call was not awaited after the queue helper became async, silently no-op'ing the window commit before finalization. Await it. Failure-Class: none
… ones (#23690) ## Summary Pusher has logged ~988/h `omi_audio_custody_failures_total{stage="projection"}` since the durable relay-custody path rolled out fleet-wide with #23641 (2026-10-26 00:20Z). Custody itself is intact (commit failures 3-7/h, no audio loss): these are failures of the OPTIONAL timeline projection (`flush_refs` in `backend/routers/pusher.py`), whose single `except Exception` records one unlabeled counter per dropped batch — no retry, no error class, no route — so the counter cannot be broken down from metrics, and every transient GCS/Firestore hiccup drops the projection outright (the legacy non-durable path retries three times; the durable path shipped with zero in #23641). Changes: 1. `omi_audio_custody_failures_total` gains a bounded `reason` label (`other|conflict|transient`) with pre-created zero baselines and closed-set coercion (`bounded_custody_failure_reason`, registered as a CLOSED_HELPERS helper in the reason-label enum contract). Existing single-argument call sites keep `other`. 2. `flush_refs` splits its catch-all. A deterministic upload conflict — different bytes already live at the run's content-addressed name, now raised as the dedicated `AudioChunkContentConflict(ValueError)` — records `reason="conflict"` and drops the batch once; a retry re-runs the same collision. Any other exception (including the uploader's plain-`ValueError` probe/read wrappers and custody read-back mismatches) requeues the receipts for a bounded `PROJECTION_RETRY_BUDGET` (2) of drain-loop passes while the session is live — the loop's existing age (60s)/duration/next-ref scans re-flush without a new scheduler — and only exhaustion records `reason="transient"` (drop semantics at teardown unchanged: there is no later pass to wait for). The requeue restores `queued_at`; the retry budget is cleared on both success and terminal drop so a later independent batch of the same conversation starts fresh; the map stays bounded (128) like the session's other sets. Review round 1 (Luna, FIX-FIRST) resolved: - P1: transient `blob.exists()` probe errors are wrapped as plain `ValueError` by the uploader and were about to be classified conflict/no-retry. Fixed by classifying ONLY `AudioChunkContentConflict` as terminal; plain ValueError now retries (regression test included). - P2: the retry budget was only cleared on success, so one exhausted batch poisoned later independent batches and leaked entries toward the 128 cap. Now cleared on terminal drop as well (regression test included). No flag flips, no `.github/` changes, no IAM, no data mutation. Alert expressions already `sum()` over label sets, so the new label changes no rule. ## Testing - `backend/test.sh` with `BACKEND_UNIT_TEST_FILE_LIST` covering `tests/unit/test_audio_durable_outbox.py` (63 passed, 3 consecutive runs) and `tests/unit/test_reason_label_enums.py` (19 passed), `BACKEND_PYTEST_WORKERS=4`. - New tests: transient failure requeues then lands (no failure recorded, audio_files applied); conflict never re-uploads a span and withholds the record close; budget exhaustion drops exactly once after exactly `1 + PROJECTION_RETRY_BUDGET` attempts; a plain-ValueError probe failure retries (P1); a later batch gets a fresh budget after a terminal drop (P2); the reason label vocabulary is bounded and coerces unknown values to `other`. Retry tests hold the socket open deterministically — teardown flushes correctly never requeue, so ungated tests race the disconnect. ## Product invariants affected none Line-Count-Exception: backend/routers/pusher.py | 1507 -> 1551 | durable flush_refs splits its catch-all into conflict/transient classes with a bounded requeue; the retry budget and both failure arms are one cohesion unit inside the session drain loop Line-Count-Exception: backend/utils/other/storage.py | 2672 -> 2683 | one dedicated AudioChunkContentConflict exception class so the durable projection can distinguish the single deterministic conflict from retryable plain-ValueError probe/read wrappers ## Failure class (fixes) Failure-Class: none Optional-projection reliability/observability hardening; no classified failure-class definition matches (no custody/projection class exists yet) and no guard was bypassed.
… ones
~988/h omi_audio_custody_failures_total{stage="projection"} since the BasedHardware#23641
fleet roll (2026-10-26 00:20Z): the durable flush_refs catch-all records one
unlabeled failure per dropped batch with no retry and no error class, so the
counter cannot be broken down by class or route from metrics, and every
transient GCS/Firestore hiccup drops the projection outright (the legacy
non-durable path retries three times; the durable path shipped with zero).
- omi_audio_custody_failures_total gains a bounded reason label
(other|conflict|transient) with pre-created zero baselines and closed-set
coercion (bounded_custody_failure_reason, registered in the reason-label
enum contract), so the next RCA can split classes from Prometheus alone.
- flush_refs splits its catch-all: deterministic ValueError (millisecond-keyed
chunk-name content collision, custody read-back verify mismatch) records
reason="conflict" and drops once — retrying replays the same collision; any
other exception requeues the receipts for a bounded PROJECTION_RETRY_BUDGET
(2) drain-loop passes while the session is live (teardown keeps today's
drop semantics; the loop's existing age/duration scans re-flush), and only
exhaustion records reason="transient".
…ound (#24090) # Pusher durable projection: gone-owner no-op on NotFound + raising-frame attribution Failure-Class: none Line-Count-Exception: backend/routers/pusher.py | 1542 -> 1611 | NotFound gone-owner arm (deletion-intent read + drop without custody failure) and raising-frame attribution per lead ruling 2026-10-30 06:00Z No existing failure class covers the pusher durable-projection surface; this change stops a permanent gone-owner condition from being classified as a transient projection failure (deterministic retry churn plus `failed_recordings` poisoning at the 128-entry session cap). Adding a new class definition would require `.github/` changes, which are out of scope for this PR. ## What - `flush_refs` now catches `NotFound` before the generic projection handler. If the conversation is tombstoned (`conversation_tombstones.is_deleted`, the same read the custody write gate uses) or its conversation doc no longer exists, the purged refs drop as a gone-owner no-op: no `record_barrier.fail_recording`, no `failed_recordings` entry, no `record_failure`/`record_fallback`, no retry churn — one info line `Durable audio projection skipped; conversation gone`. - A **live** conversation keeps today's transient retry/terminal paths unchanged (NotFound on live audio is never hidden as a gone owner). The extra deletion-intent read runs only on the NotFound arm; if that read itself fails, the arm fails open to the transient path instead of propagating out of the drain loop. - The existing warning `Durable audio projection failure class: %s` now also names the innermost raising frame (walking `exc.__traceback__` to the last frame, `co_name` only — never the message or args), so the unattributed InvalidArgument minority becomes diagnosable from logs without a redeploy. ## Why Read-only verdict (2026-10-30, swarm/state/refs/projfail-verdict-2026-10-30.md): the dominant NotFound stream (~1,000 class lines/10m, ~460 conversations/h) is `read_pcm` hitting objects purged by sanctioned conversation deletion (user delete, merge, empty-recording cleanup) while the receipts still sit in the pusher durable queue. Retries are deterministic (requeue:terminal ratio 2.0 — retries rescue nothing), and every terminal conversation enters `failed_recordings`, where the 128-entry session cap flips `record_upload_failed=True` session-globally and can fail-mark later healthy conversations of the same websocket session. Chronic since #23641; made visible by #24084's class logging. No rollback indicated (attributed in the verdict); this PR removes the churn and the poisoning path. ## Tests `backend/tests/unit/test_audio_durable_outbox.py`: - `test_notfound_on_tombstoned_conversation_drops_refs_without_custody_failure` — purged read + tombstone: refs dropped on the first NotFound (no requeue), zero custody failures, zero `fail_recording` (observed via `mark_record_upload_failed`), receipts still acked and readable. - `test_notfound_on_hard_deleted_conversation_doc_drops_refs` — tombstone false + missing conversation doc: same gone-owner no-op. - `test_notfound_on_live_conversation_keeps_transient_retry_and_terminal_paths` — live conversation: exactly `1 + PROJECTION_RETRY_BUDGET` attempts, the terminal `('projection', 'transient')` drop, record close withheld, and the class line attributes `NotFound raised by purged_read` with the exception message never logged. - Existing budget/conflict/retry tests updated for the new class-line format and a message-leak assertion. Local verification (layer: backend unit suite, selected by the CI changed-file selector for this diff — 34 files, all green): ``` BACKEND_UNIT_TEST_FILE_LIST=<selection> bash backend/test.sh # 34 files, exit 0 ``` <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/BasedHardware/omi/pull/24090?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="View guided diff" src="https://www.cubic.dev/buttons/review-in-cubic-light.svg"></picture></a> <a href="https://www.cubic.dev/action/auto-fix/pr/BasedHardware/omi/24090?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F24090&source=description" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"><img alt="Turn on auto-fix" src="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"></picture></a> <!-- End of auto-generated description by cubic. -->
Commit durable audio custody per window, not per message (X4 #1, c3gcs)
Implements lead ruling 759d9c (option a) for the custody write surge measured
10-25: since the 06:00Z custody roll, pusher wrote 2 GCS objects per device
audio message (raw-live media + audio-outbox manifest per ~0.5–1 s
opcode-101 frame) — WriteObject went 77k/h → 750–830k/h, ≈ +15–18M Class A
writes/day ≈ +$4.1–4.7k/mo, plus PCM bytes written twice during the STOP_PCM
interim and custody media retained forever.
Change
Windows ride the flush boundaries the batched
.batch.encpath always used —60 s of audio, conversation switch, v2 discontinuity, process_conversation,
shutdown. The durable branch of
_queue_private_cloud_chunkcommits ONEcommit_pcm_windowmedia+manifest pair for the buffered window (framescheckpoints pinned per message in the manifest); per-message
archive_private_audio/queue_private_projectionare removed. Theprojector hydrates one read per window instead of per message.
What is preserved (tests pin each)
a receipt exists only after both objects commit.
boundary, zero acks. Shutdown tail failure →
window_tailfailure +would-drop counters and a 1011 close so the producer replays the
unacknowledged tail.
.batch.encprojection is byte-identical (window = the acceptedpost-trim stream the per-message reads concatenated; spans aggregate the
same).
unlinked).What is deliberate (delta)
bytes per message: replay duplicates are byte-verified or conflict-dropped
before acceptance, so no audio-distinct bytes are lost; conflicting
"originals" are no longer stored twice.
— the same bound the raw-live pack path always had; acked ⇒ committed.
audio_custody=1acks move to window boundaries (no known clients yet —the flag shipped this morning).
Ops effect
Custody writes return to ~2 objects / 60 s / conversation (hundreds of
thousands per day fleet-wide vs ~15–18M), removing the +$4–5k/mo Class A
regression and unblocking the STOP_PCM ramp math (X4 lever 2).
Tests
Local shard (backend/test.sh, BACKEND_UNIT_TEST_FILE_LIST, 11 files incl.
test_audio_durable_outbox, durable queue, pusher protocol/timeline/dispatch/
drain/delete-race, listen timeline stack): green. New: window-batching,
switch-boundary commits, shutdown-tail no-ack + 1011, mid-stream fail-closed,
queue backpressure keeps every receipt. Updated: per-message receipt counts →
window counts; the pending-map overflow scenario (per-message artifact)
replaced by the reachable queue-cap path, with the pending-map branch kept as
defense in depth.
Failure-Class: none
UI-Evidence: none -- reason: no web/admin/app changes
Line-Count-Exception: backend/routers/pusher.py | 1402 -> 1507 | window custody per lead ruling 759d9c: window-commit helpers extracted at module level (pyright complexity budget), frame checkpoints, unlinked/alignment guards; the frame loop itself nets +~30 with the closures it replaced
Owns: (this PR — lane c3gcs)