Repository navigation
SCA-2303: tell the server when a pendant recording ended - #25311
Conversation
The phone already knows when the user stopped, the pendant left, or speech stopped; the server waited 600 s after the last upload because nothing told it. CaptureEndDetector keeps the last VAD speech time (never cleared by the 2 s chunk seal) and CaptureEndReporter posts the end to /v2/sync-capture-end, then again when the recording's last sealed file is accepted. Latency information only: no custody, seal, upload or delete path reads it. Kill switch: PostHog upload_end_marker_off; the server can also withdraw the silence timer. Co-Authored-By: Claude Fable 5.2 <[email protected]>
Co-Authored-By: Claude Fable 5.2 <[email protected]>
Co-Authored-By: Claude Fable 5.2 <[email protected]>
… change) Co-Authored-By: Claude Fable 5.2 <[email protected]>
Codex Review Summary: ✅ CompletedThis 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: 354f189dfd
ℹ️ 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".
| // No wall timer: the silence end is checked as packets arrive. | ||
| if (batched) _reportCaptureEnd(_captureEnd.packet(activeRecordingId, DateTime.now())); |
There was a problem hiding this comment.
Invalidate the silence clock when audio leaves the batch lane
If a recording starts in Standard batch mode, then switches to live transcription while the transcript is visible, speech during that interval never reaches _captureEnd: its only speech source is the batch lane's VAD. Returning to batch mode after the silence threshold therefore immediately emits a silence_backstop using the old timestamp, even if the user spoke continuously throughout the live interval. MobileStandardBatch.eligible explicitly permits this visibility-driven handoff, and route() bypasses VAD for those live frames. Clear or suspend the detector across unobserved intervals, or keep feeding it speech evidence while live, so the server is not told that an ongoing recording ended.
Useful? React with 👍 / 👎.
| _reportCaptureEnd(_captureEnd.stopped( | ||
| activeRecordingId, | ||
| cleanDevice ? CaptureEndType.disconnect : CaptureEndType.userInitiated, | ||
| DateTime.now(), | ||
| )); |
There was a problem hiding this comment.
Drain pending VAD inference before deciding the stop marker
If the pendant stops or disconnects while its first speech frames are still awaiting VAD inference, this call sees no speech and returns no marker. MobileStandardBatch.route() delivers onSpeech asynchronously after vad.probability(), but the device-stop stages only revoke batch authorization, close the transport and finalize the ordinary WAL; none awaits the lane's pendingInference. The eventual speech callback then populates the detector after the terminal stop has already been handled, with no subsequent packets or stop event to report that recording's end. Drain the admitted VAD work before taking the terminal detector snapshot so short recordings and stops under inference backlog retain their explicit end marker.
Useful? React with 👍 / 👎.
| int pendingWalsForRecording(String recordingSessionId) => _wals | ||
| .where((wal) => | ||
| wal.recordingSessionId == recordingSessionId && | ||
| (wal.status == WalStatus.inProgress || wal.status == WalStatus.miss)) |
There was a problem hiding this comment.
Count retryable upload refusals as pending files
When a recording contains a WAL in uploadRejected, this predicate excludes it even though the server never accepted its bytes and Wal.refusalRetryDue() permits daily recovery for seven days for retryable refusal reasons. If another file from that recording is accepted, the reporter can consequently send pending_wals: 0 and remove the recording from its tracking maps while the refused file still awaits upload. Its later successful retry then cannot update the marker. Include unaccepted, retryable refusal states in the pending count so zero does not falsely advertise that the recording has drained.
Useful? React with 👍 / 👎.
…hunk is a file, report a stop with no speech Review findings on #25311: 1. Only two accepted reports per end: the first, and the one at zero pending. Intermediate acceptances send nothing; an unaccepted first report still retries. 2. The chunk open at the end is sealed and registered before the first count, so the marker cannot say nothing is pending while the final file is still being published. The count is limited to audio up to the end. 3. An explicit stop or a lost pendant with no detected speech is reported with no speech time, never an invented one. Co-Authored-By: Claude Fable 5.2 <[email protected]>
…d but never proves it Review finding 3 on the app half (#25311): an explicit stop or lost pendant with no detected speech must still be reportable, without an invented speech time. last_speech_at is optional; proof returns no_speech_clock for it. Co-Authored-By: Claude Fable 5.2 <[email protected]>
…buffer Custody finding on #25311: the previous fix had the reporter seal the open chunk before counting, which let a marker drive WAL sealing and move a chunk boundary while capture continued. Removed. The buffer now exposes the audio it has not yet registered as a file (the open chunk and chunks still publishing), and the pending count includes it, so the marker still cannot say zero while the final audio is open, publishing or unaccepted. Co-Authored-By: Claude Fable 5.2 <[email protected]>
…t reads (#25331) Offline Sync keeps valid audio ahead of unknown/future capture clocks, with one isolated clock-recovery batch after at most 36 valid batch attempts. The shared budget is now saved on waiting WALs in the owner-fenced index before valid uploads, so repeated iOS process restarts cannot erase the turn. A recovery batch resets the shared budget after entering the gate, allowing valid work to resume. No request mixes valid and unknown-clock files. Only `invalidCaptureTime` (`invalid_capture_time`) retries daily during the first week, then weekly indefinitely until accepted. Other refusal reasons retain their existing expiry. The 25-refusal-per-drain cap and single-file isolation remain. A server rollout may start disabled and enable recovery later: an already expired refusal becomes eligible on its next weekly due date without user action or a new app install. Weekly probes cost at most five full-file requests per affected file per rolling 30 days after the first week (roughly 4–5 times its bytes plus request overhead), and stop on acceptance. This is a schedule bound, not a measured currency cost. The install migration is removed. It is unnecessary with non-expiring paced recovery and introduced an eager startup index save that blocked `walReady` in the gated-save test and consumed the first injected save failure. The existing flush still awaits the durable audio/index before publishing live custody proof or issuing pendant ADVANCE. Strengthened regressions assert no persisted row, proof, or ADVANCE while the actual audio index write is blocked or fails, followed by proof only after a successful save. Neither stored refusal clock is reset, so there is no migration/receipt crash boundary. Deterministic refusals remain aggregated without user attention or an immediate same-pass retry; the only deliberate policy difference is the slow, persisted invalid-date schedule. Rows retain the existing “Invalid recording date” label until accepted, then follow the existing uploaded/processing states. A settled pendant read failure gives the phone backlog its upload turn. Cancellation during a queued phone flush remains cancelled before the gate, including the new budget checkpoint. Pass serialization, the upload mutex, owner fencing, durability and acknowledgment rules remain in place. LittleFS first parsed DATA and subsequent audio idle both have conservative 60-second deadlines. Firmware 3.0.17–3.0.19 permits 500ms queueing plus 15s for an SD read, then unbounded BLE-buffer retries without a progress heartbeat. The tests cover first DATA arriving after 20 seconds, a healthy 45-second inter-DATA gap, and ACK-only traffic still failing at 60 seconds. Incomplete transfers retain the original device record, save parsed audio durably, never skip the unread head, and report failure after cleanup. Evidence: `app/docs/offline-storage-liveness.md`. The app does not rename existing files because the companion server fix accepts both `..._<timestamp>_uN.bin` and `..._uN_<timestamp>.bin` forms. New collision names keep the timestamp last. Rollback defines, all compile-time and default false: `OMI_WAL_CLOCK_PRIORITY_OFF`, `OMI_PHONE_AFTER_DEVICE_FAILURE_OFF`, `OMI_STORAGE_AUDIO_LIVENESS_OFF`, `OMI_DEVICE_COLLISION_TIMESTAMP_LAST_OFF`, and `OMI_INVALID_CAPTURE_TIME_RECOVERY_OFF`. The last restores seven-day expiry without changing stored state. The storage define restores the original five-second any-packet first-data detection and disables audio idle; it does not restore silent incomplete-transfer success, remove cleanup, or weaken custody/delete proof. These are not remote-config switches. Release notes for the lead: the normal store route is Codemagic with validated release tags, exact-source Release Eligibility and Mobile Release Eligibility receipts, then store approval and the documented phased/staged train. App/lib PRs need the ordinary source/review/CI gates, invariant/failure-class metadata, changelog fragment and UI evidence declaration; this service-only change declares no UI evidence. Codemagic contains Shorebird iOS/Android patch workflows and `app/shorebird.yaml`, so these Dart-only changes are patch candidates only for an installed binary already built with a compatible Shorebird release. Current store lanes use ordinary `flutter build`; updater compatibility of the owner's 1.0.592+1560 is unverified. Server-side recovery/parser work can ship separately, but cannot change this client's scheduling/timers or filename generation. Product invariant: INV-CAP-1. Failure-Class: FC-batch-fault-domain-head-of-line-poison UI-Evidence: none -- Changes are confined to WAL scheduling, transfer liveness and persistence; no widgets, layouts or user-facing strings were changed. Line-Count-Exception: app/lib/services/wals/local_wal_sync.dart | 2754 -> 2789 | Preserve the existing ledger authority and cancellation fences, checkpoint the bounded clock-class turn, and conservatively observe unaccepted unknown-clock audio for the merged end marker; index durability and restart regressions cover the shared state. Merged origin/main at `2d59f75eace67a03cc31dd07effa7ab73b8e15a5` into local head `f5758dd1afa9846ca4eaf6c864388c7efcf9d6e0`, preserving #25311 capture-end reporting and #25332 upload tracing. The only textual conflict was at the bulk-upload gate in `local_wal_sync.dart`; both clock-turn bookkeeping and trace preparation remain after the cancellation check. The marker remains an observer. Unknown-clock or refused WALs in its session, including future-clock chunks awaiting index publication, cannot produce a false zero watermark; accepted files and trusted trailing silence stay excluded. Focused regressions cover both clock classes accepted serially and failed publication. The fetched main uses a `pending_wals` JSON watermark and an `X-Omi-Upload-Trace` timing header; it contains no separate upload-watermark header. The capture-end observer now counts retained batch journals directly from disk instead of relying on the current writer and publishing list. Failed seal flush/close, failed append/publish, cancellation and process loss cannot erase the count. Replayed journals may overlap the ledger until server acceptance; they are excluded only for acknowledged files whose current byte length matches the accepted length, with no retained torn original. Transport-only synced, terminal-refused and corrupted rows stay conservatively pending. Unreadable evidence over-counts; an unavailable directory or unknown ledger suppresses the marker. An append during the asynchronous scan invalidates that observation and retains the end for a later accepted-file wake. Reports are bound to the account and WAL generation before queuing and after the scan. No new startup save, uploader, cleanup authority or audio deletion is added. Focused real-ledger regressions cover both failed seal operations, cancellation, replay and eventual zero after actual upload acceptance; additional cases cover append failures, account changes, unreadable evidence and a growing accepted prefix. Validation on local head `46a179598fb40829d679bddea9dca040c6719ede` completed 2026-11-15T00:32:09Z through `bin/omi-heavy`, Flutter 3.44.5 / Dart 3.12.2: full CI `app/test.sh` **8,837 passed, 5 skipped, zero failures across all 981 Dart files**; separate dev-controls spine **138 passed**; three exact CI timezone runs **39 passed each**. Focused four-file regression run **98 passed**. Format checked **23 Dart files**, unchanged. Nine touched Dart files analyze with no issues; full analyzer ratchet passed without baseline change. Expanded directory analysis reports 11 existing infos outside changed files, zero errors/warnings. The actual pre-push hook passed, including all **29 preflight checks**, generated-output validation and formatting. Backend type/unit selectors ran with no applicable backend delta, no skip overrides. Source clean; no push or release. The two failed-seal paths, account races, restart/replay, concurrent append and original CI custody/refusal regressions all passed. Full enumeration, files and logs: `Q12-I-durable-pending.md`, `evidence/q12-i-durable-pending/`. The lead owns publication, fresh CI and independent review.
… wait (server) [SCA-2344] (#25309) # End-of-recording proof: notes start when the phone proves a recording has landed Builds on #25304, which is merged; base is `main`. Tracking: SCA-1766, SCA-1767. App half: #25311 (merged). Design: `DESIGN:` comment on SCA-1767 and the change note `backend/docs/listen_pusher_pipeline/changes/2026-11-14-capture-end-proof.md`. Notes on uploaded audio wait 600 s after the last content arrival because the server cannot tell an ended recording from one with uploads still coming. The phone knows. This is the server half: it accepts the phone's end marker and uses it. Old clients send nothing and behave exactly as today. Line-Count-Exception: backend/routers/sync.py | 3883 -> 3945 | the capture-end route and the trace header sit beside the upload route they extend; policy and storage are in new modules, and splitting this router is separate debt Line-Count-Exception: backend/utils/sync/pipeline.py | 4031 -> 4041 | the frozen legacy copy of the enrichment callback must mirror the callback's admission call (parity test), and the sync writer declares the clock shift it applied to the stored times; one argument, one import, one field Line-Count-Exception: backend/utils/sync/assignment.py | 1568 -> 1574 | pass the writer's clock shift to the hold state on the assignment write that already happens; no new read or write Line-Count-Exception: backend/routers/listen/receiver.py | 2978 -> 2980 | one field on the existing batch admission status event and its import Failure-Class: none UI-Evidence: none -- the only client files changed are generated API type definitions for the new route; no screen, layout or copy changes ## Clock skew (review round 2, goal-owner ruling on SCA-2344) The marker is on the phone clock. Production's sync writer stores uploads from a phone running ahead shifted onto the server clock by a per-request offset (median 171 s), so the first version read a complete recording as `content_behind` and kept the quiet wait. Fix: the writer passes the shift it applied, the hold state keeps it (`content_clock_offset`) beside the row end it describes (`content_clock_end`), and the proof adds it back so both sides are on the phone clock. The three proof rules, the 5 s tolerance and the quiet fallback are unchanged. A row whose end has moved since reads `clock_unknown` and waits. Rows that were never shifted carry neither field. Tests: `test_a_phone_clock_171_seconds_ahead_still_proves_a_complete_recording` (complete, behind, after the end, no recorded shift, moved end), `test_the_hold_keeps_the_shift_only_for_the_arrival_that_sets_the_row_end`, and the stored-row assertion in `test_sync_capture_time_skew.py`. ## What changed - **`POST /v2/sync-capture-end`** (`routers/sync.py`): `recording_session_id`, `end_type`, `last_speech_at`, `end_decided_at`, `sent_at`, `pending_wals`. Stored as one field, `capture_end`, on the recording's session document (`database/capture_end.py`). It never creates a session, changes a binding, finalizes, deletes or alters custody. No session: `accepted: false, retry: true`. - `last_speech_at` may be null: a stop with no detected speech is stored as it is. It types the end but can never prove it (`no_speech_clock`), because an accepted upload is not yet a transcript. - **End proof in hold admission** (`utils/sync/processing_hold.py`, `utils/enrichment/callback.py`): a row that would otherwise wait and carries `external_data.recording_session_id` reads that one document. The wait is skipped (outcome `end_proof`) only when the phone has no file left to upload, assigned content reaches the phone's last speech, and nothing on the row is later than the end. Unchanged, immaterial and late-cap rules still apply. Any other result, a read failure included, leaves the quiet rule as it is. - The frozen legacy copy of the callback in `utils/sync/pipeline.py` mirrors the same admission call, as its parity test requires; both call the shared `database.capture_end.proven`. - **Why the session and not the conversation:** uploaded audio does not always land in the conversation bound to the recording (assignment can fall back to recorded time, live overlap or the temporal index). - **Ledger end fields** (`database/pipeline_ledger.py`): `record_end` sets `end_type`, `end_at`, `end_observed_at`, `last_speech_at` on an existing row without moving its stage; a known end is never replaced by a weaker one. Server-known ends are typed when a finalization intent is accepted (`utils/conversations/lifecycle.py`): client finalize `user_initiated`, server recovery `silence_backstop`, bare capture end `unknown`. - **Upload trace** header `X-Omi-Upload-Trace` on `/v2/sync-local-files`: measurement only, feeds `omi_sync_seal_to_accept_seconds{gate}`. - **`end_silence_seconds`** on the `mobile_batch_admission` status event (`SYNC_CAPTURE_END_SILENCE_SECONDS`, default 120, clamped 60..1800, `0` withdraws it). - Route policy entry, app-client OpenAPI and generated Dart, TypeScript and Swift types. ## Reads and writes Per recording: one or two calls, each one transaction with one read and at most one write on the session document, plus one ledger transaction (one read, one write) when the marker is new. At admission: one read per evaluation that would otherwise wait, only for rows with a recording session id. No query, no scan. ## Kill switch and rollback `SYNC_UPLOAD_WATERMARK_ENABLED=false` (default on): the route stores nothing, admission reads nothing, the trace header is ignored, phones get no silence timer. Revert is clean: the only stored state is one field on session documents. ## Risk Notes written before late audio lands. Bounded by the existing `MAX_LATE_RUNS = 1`: one extra notes run, never lost audio. Watch `late_runs > 0` against its baseline. ## Tests - `tests/unit/test_sync_capture_end.py` (new): marker shape and refusals, proof rule, store idempotence and supersession, admission with and without proof, ledger end fields and precedence, trigger typing, silence timer bounds, callback read gating, kill switch. - `tests/unit/test_sync_v2.py`: route stores and types the ledger end; malformed marker 422; store outage 503; kill switch stores nothing. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
App: tell the server when a pendant recording ended
Client half of the end-of-recording event. Server half: #25309 (stacked on #25304). Tracking: SCA-1767.
Independent of both: against a server without the route the call fails quietly and nothing else changes.
Notes on uploaded pendant audio wait 600 s after the last upload because the server cannot tell an ended
recording from one with uploads still coming. The phone knows. This makes it say so.
Line-Count-Exception: app/lib/services/capture/capture_controller.dart | 4916 -> 4941 | four call sites that must sit where the events happen (lane install, packet routing, status event, device stop); the detector and reporter are in a new file
Line-Count-Exception: app/lib/services/wals/local_wal_sync.dart | 2725 -> 2740 | a pending-file count and one callback at the two existing upload acceptance sites
Failure-Class: none
UI-Evidence: none -- no screen, layout or copy changes
What changed
CaptureEndDetector(app/lib/services/capture/capture_end.dart): keeps the last time the on-phoneVAD heard speech for the current recording. That clock is separate from the 2 s chunk seal, which keeps
clearing its own. It reports an end on an explicit stop (
user_initiated), a lost or removed pendant(
disconnect, never claimed as user intent), or when the server-provided silence timer runs out(
silence_backstop). No wall timer: the silence end is one comparison per incoming packet. Speech after asilence end re-opens the recording, and the next end supersedes the earlier one.
CaptureEndReporter: posts the end toPOST /v2/sync-capture-endwith the number of sealed files notyet accepted, and once more when the recording's last file is accepted, so the final copy says nothing is
pending. At most two accepted calls per end. It is an observer only: it never seals, flushes, publishes or
uploads, and it changes no chunk boundary. Audio up to the end that is still being written or published is
counted as pending (
MobileBatchBuffer.unregisteredStarts) until the capture lifecycle seals it and theserver accepts it, so the marker cannot say zero early. Sends are serialized; an unaccepted first report
retries on the next accepted file; at most 16 open ends are tracked.
MobileStandardBatch.onSpeech: the lane's VAD reports speech frames with their capture time.MessageServiceStatusEvent.endSilenceSeconds: read from themobile_batch_admissionstatus event.Absent means the phone sends no silence end.
LocalWalSyncImpl:pendingWalsForRecordingand anonRecordingUploadAcceptedcallback at the twoupload acceptance sites.
What it does not touch
Custody. The marker never seals, uploads, deletes or releases a WAL, and no custody rule reads it
(
app/lib/services/wals/CUSTODY.md, new section). It is held in memory: an app killed before the resendtakes the server's ordinary wait.
Kill switches
upload_end_marker_off: true stops the marker; absent, false or unreadable sends it. It deletesnothing, so unknown keeps it on.
end_silence_secondsto stop silence ends;SYNC_UPLOAD_WATERMARK_ENABLED=falseignores themarker entirely.
Battery
No new radio wake on its own: the first report rides the stop, and the resend rides an upload that just
completed. One comparison per packet while the pendant streams.
Not in this PR
The per-file upload trace header (seal time, first attempt, gate). It needs skip reasons plumbed through the
upload coordinator and gets its own PR.
Product invariants affected
about a recording, not a control: it closes no uplink, unsubscribes nothing, fences no sync and discards no
frame. A silence end does not stop capture or transmission; frames keep going to the batch journal or the
socket exactly as before, and speech after a silence end simply produces a later end. No retention or
transmission path reads the detector or the reporter.
Tests
app/test/services/capture/capture_end_test.dart(new, 14 cases): silence end fires once at last speechplus the timer; speech re-opens; no timer means no silence end; stop and disconnect are typed apart; a
recording without speech has no end; the reporter's resend, dedupe, retry, kill switch, replacement,
transport failure and bound.
app/test/backend/http/capture_end_api_test.dart(new): request shape; "not bound yet" is a successful false;an old server or an outage is a typed failure (
ApiResult), never a silent null.app/test/services/wals/mobile_standard_batch_test.dart: an end reported while the final chunk is opensends pending 1, seals nothing, leaves the next frame in the same chunk, and reports zero only after the
capture lifecycle seals and the file is accepted; a chunk whose publish fails stays counted.
2 s seal does not un-report it.
🤖 Generated with Claude Code