Repository navigation
fix(listen): a mobile socket drop no longer ends the conversation - #25460
Merged
Merged
Conversation
Listen teardown finalized every batch-owned conversation on socket close. That is right for desktop, where close means stop, but with mobile batch at 100% every phone/pendant reconnect split one recording into many. A batch-owned ios/android omi/phone capture now commits this socket's audio tail without the archive-close barrier and stays in_progress, provided a durable quiet check owns it and committed audio exists. A reconnect inside the timeout resumes it; otherwise the quiet check finalizes it through the existing raw-only batch handoff. Desktop, web, multi-channel, other mobile sources, empty captures, explicit client reasons and failed arms keep immediate finalization.
Git-on-my-level
added a commit
that referenced
this pull request
Nov 16, 2026
…ncing (#25466) ## Summary Build on #25460, which stopped mobile socket drops from immediately finalizing batch captures. Bound the hold for known recording origins/devices to a configurable reconnect grace, default 120 seconds, rather than waiting the full occasion quiet window. Resume the same conversation only for the same recording origin, device and source. Preserve #25460 recovery for older or identity-less sessions. The existing durable quiet-check outbox owns expiry and normal finalization; explicit stop and earlier quiet/calendar/day/span boundaries still end it. Producer tokens fence competing sockets, stale teardown and late original-audio metadata writes. Archive packs remain immutable per socket, custody ACKs still require durable receipts, and finalization/batch IDs, generations, leases and paid-work admission stay authoritative. Sealed or terminal batch obligations are never reopened. Lead-approved scope: prevention through bounded reconnect grace only. Terminal-successor composition and historical consolidation (A2) remain with the Home redesign/sync projection owners; duration presentation (A3) is separate. No app UI, sync merge/projection-session, pusher relay, production configuration or workflow changes. Main advanced during implementation; the rebased PR preserves the earlier fix and its regression tests. ## Verification Synthetic tests cover 18 short sockets across an hour yielding one conversation and one deterministic batch registration, exact expiry, restart/replay, explicit end, real quiet timeout, calendar/day/span boundaries, concurrent producer claims, reconnect ABA, late writes, archive-drain failure, manual title edits, terminal immutability, all close-code classes, and kill-switch off. Q12-R31 regressions additionally disable between disconnect and the real controller resume path, prove due-now finalization without token replacement or terminal reopen, exercise off-reader expiry before stored grace, and model dark-deploy/enable/drain transitions. - `backend/.venv/bin/python -m pytest -q -p no:cacheprovider tests/unit/test_listen_batch_reconnect_grace.py` - Existing reconnect, quiet-finalization, server-batch completion and flag-budget suites, one file per process through `omi-heavy`, without Google or CLOUDSDK credentials. - `firebase emulators:exec --only firestore --project demo-listen --config <isolated-scratch-config> "backend/.venv/bin/python backend/scripts/listen_lifecycle_emulator_test.py"`: passed real competing producer transactions, ABA and late-write fences plus existing lifecycle contention contracts. - Async blocker and test import-isolation scans passed. Repository CI-lane checks and bounded pre-push checks are recorded in the implementation report. These are local synthetic/runtime-controller and emulator results. No live authenticated endpoint, device acceptance, production deployment, vendor billing measurement or measured fleet chapter reduction is claimed. ## Rollout and rollback `LISTEN_BATCH_RECONNECT_ENABLED` now defaults **false**, per the Q12-R31 lead decision. Only trimmed case-insensitive `true` enables enrollment. Dark deployment preserves origin/main behavior for unmarked recordings. `LISTEN_BATCH_RECONNECT_GRACE_SECONDS` defaults 120 and clamps to 1..120, well below the 1,800-second occasion timeout; packet timing supported this bounded window. Processing admission is due at expiry; queue/STT/summary retain existing latency. **Activation gate:** Release deploys upgraded finalization/reconciler/backend readers and then every listen pod through its train with the flag off. Verify running SHAs, zero old listen pods and zero sockets on old revisions, including terminating instances. Only then enable consistently on readers and listen. Use a small canary percentage if routing can keep every reconnect in the enabled pool; otherwise activate fleet after that gate. This PR adds no percentage selector. Quality reviews each clean window; Release expands through its train, with proposed completion/flag review **2026-11-20**. Keep off and report a block if the gate/window is unavailable. **Clean metrics:** chapters per hour per active recording, finalization lag within grace plus observed reconciler latency for drained holds, zero drained `in_progress` rows older than grace plus reconciler period, and exactly one batch obligation per finalized generation. Local tests do not establish those production metrics. **Rollback gate:** set the switch off on all upgraded listeners and readers, keep those binaries running, and drain active sockets there. Marked holds refuse resume, durably end and rearm due now on reconnect; off readers also bypass stored grace. Wait **more than 120 seconds plus one observed reconciler period** after the last enabled process/socket drains (source default 60 s with quiet finalization on: >180 s minimum). Verify aggregate counts of all marked `in_progress` rows, held rows and overdue holds are zero before rolling back listen. Keep upgraded readers until outstanding finalization work drains. Any nonzero/unknown count or unavailable reconciler blocks rollback. A projection-only collection-group readback recipe is in [the rollout note](https://github.com/Git-on-my-level/omi/blob/lane/q12-reconnect-continuity/backend/docs/listen_pusher_pipeline/changes/2026-11-16-batch-reconnect-grace.md#rollback-gate-and-aggregate-readback); this lane did not execute it. **Residual mixed-version risk:** old listeners can resume marked in-progress rows and write/close metadata without tokens. There is no safe cheap existing exclusion field: deleted/discarded/locked also alter privacy/finalization/presentation. The default-off and all-new-listener drain gates are required; mixed active listener versions are unsafe. No deployed-fleet guard or production flag/config change is claimed. Pusher retains its existing upload/close wire protocol. Expected effect: a continuous one-hour meeting with same-origin reconnects under the grace and no semantic boundary stays one chapter instead of a chapter per socket. The local synthetic shape is 18 sockets to 1 chapter; this is not a measured fleet outcome. Reconnects after expiry or terminal admission still create separate chapters. ## Product invariants affected INV-CAP-1: no new capture pause or permission to reclaim audio; failed drain publishes no grace/close proof and grants no acknowledgement for uncommitted audio. Line-Count-Exception: backend/database/conversation_finalization_jobs.py | 3630 -> 3639 | Keep the small reconnect ownership/deadline hook at its existing lifecycle boundary; the protocol implementation is isolated in new bounded modules. Line-Count-Exception: backend/routers/listen/runtime.py | 1555 -> 1570 | Keep the small reconnect ownership/deadline hook at its existing lifecycle boundary; the protocol implementation is isolated in new bounded modules. Failure-Class: none 🤖 Generated with [Claude Code](https://claude.com/claude-code)
kodjima33
added a commit
that referenced
this pull request
Nov 16, 2026
…right away (#25536) ## Why #25460 keeps a mobile conversation open when its `/v4/listen` socket closes, so a phone or pendant reconnect continues the same conversation. A deliberate Stop now looks the same as a network drop, so the server waits for the durable quiet check (~5-8 min) before it finalizes, and notes arrive late. The backend already accepts an explicit signal on the listen socket, `{"type":"finalization_reason","reason":"user_stop"}` (`backend/routers/listen/receiver.py`, `finalization_reason` branch). Any finalization reason makes `resumable_after_drop` (`backend/routers/listen/batch_close.py`) return false, so teardown finalizes right away. The app never sent it. ## What - `TranscriptSegmentSocketService.stop(userStop: true)` sends that frame right before the socket closes. It is best-effort: skipped when the socket is not connected, and a send error is logged and never blocks the close. - Phone live recording: `_stopPhoneLiveBody` passes `userStop` only for reason `user_stopped` (Stop on the live page, the Home button, Siri, and the voice-profile handoff). - Pendant: the explicit stop (`DeviceStopRequested(cleanDevice: false)`) carries `userStop` through the `SocketClose` effect. - Nothing else sends it: network drops, server closes, automatic reconnects, BLE disconnects (`cleanDevice: true` / `DeviceUpdated(null)`), source restarts, transcription-settings reconnects and app backgrounding all leave the conversation open as #25460 intends. Phone batch stop does not close the socket, so it is unchanged. - Custom STT composite sockets: the frame reaches Omi. The custom STT primaries already drop text frames, the same as client-state frames. ## Tests New `app/test/services/capture/capture_user_stop_finalization_test.dart` drives the real `CaptureController` and `TranscriptSegmentSocketService` over the scripted transport, which now records an ordered `wire` log of sends and closes: - Phone Stop sends exactly one `user_stop`, after the last audio frame and immediately before close. - A phone socket drop and its reconnect send none; the later Stop sends exactly one, on the live socket. - Pendant explicit stop sends exactly one, right before close. - Pendant BLE disconnect closes the socket with none. - A dead socket gets no frame and still closes; a send that throws never blocks the close. Mutation check: with the send removed, 3 tests fail. With BLE disconnect also marked `userStop`, 1 test fails. Ran locally with the pinned Flutter 3.44.5: - `flutter test test/services/capture/ test/services/sockets/ test/unit/capture_recovery_replay_scenarios_test.dart test/unit/composite_transcription_socket_test.dart test/unit/capture_mute_admission_test.dart test/services/live_preview/`: 677 passed - `flutter test --dart-define=OMI_DEV_CONTROLS=1 test/spine`: 138 passed - `app/scripts/analyze_ratchet.sh`: passed; `dart format --line-length 120`: no changes ## Product invariants affected - INV-CAP-1: unchanged. This adds no new close, unsubscribe or fence. The frame rides closes that already happen on a user stop, so pendant audio delivery and retention are untouched. ## Failure class (fixes) Failure-Class: FC-transport-drop-terminalizes-resumable-capture This is the client half of that class's prevention ("key immediate finalization on the client's close semantics ... and an explicit client finalization reason"). With the server keeping drops open, the explicit reason is what keeps a deliberate Stop immediate. UI-Evidence: none -- protocol only, no visible UI change Line-Count-Exception: app/lib/services/capture/capture_coordinator.dart | 3026 -> 3027 | the user-stop flag on the SocketClose effect 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/BasedHardware/omi/pull/25536?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/25536?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F25536&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. -->
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What changed and why
Bug (P0, fleet-wide, seen on prod 2026-11-16). When a mobile
/v4/listensocket (phone mic, or the Omi pendant through the iOS/Android app) disconnects, the backend finalizes the in-progress conversation right away. The app reconnects a few seconds later with the sameclient_conversation_id. By then the bound conversation is already completed, socreate_new_in_progress_conversationrolls over to a new one. One continuous 2-hour talk became 15 conversations, one per socket connect (21:00:20, 21:01:26, 21:44:04, 21:44:57, 21:46:44, 21:47:40, 21:49:43 NY, and so on). Fleet sample for 2026-11-16 03:00-03:30Z: 110 of 290 connected users (38%) had at least one reconnect within 120 s. That window had 471 quick reconnects.Cause. The
server_batch_owned(conversation)arm of the listen teardown inbackend/routers/listen/runtime.pycame from ef2e2ed (2026-10-27) for desktop, where socket close means the user stopped. Prod setSERVER_BATCH_ONLY_MOBILE_PERCENT=100on 2026-11-02 (90c537c), which made every mobile conversation batch-owned. Since then every mobile disconnect has finalized immediately. Before that, a mobile conversation stayedin_progresson disconnect. A reconnect insideconversation_timeoutresumed it, and the durable quiet check finalized it if nobody came back.Fix. Teardown now keeps a batch-owned capture open when all of these hold:
client_platformisios/androidand source isomi/phone.finalization_reason.quiet_finalization.armconfirms a durable quiet check owns the row.armnow returns that as a bool.resumable_after_drop(new,routers/listen/batch_close.py) commits this socket's archive tail, the re-read row is stillin_progresswith committed audio.No audio is lost. The helper runs
LiveAudioArchive.close(), which flushes and commits every pack and merges the bounds throughnote_server_batch_audio. It does not publish theserver_batch_audio_closedbarrier, so the capture can still resume. A reconnect binds the same row through the existing continuation path, and new audio merges into the same monotonic bounds. If nobody comes back, the quiet check admitsSERVER_RECOVERY, and the raw-only finalizer registersrecord_pendingand completes the capture. That is the same unclosed-but-committed shape the in-session silence timeout and theprepare()rollover already finalize today. The'server batch archive is not closed'guard only fires on rows with no audio, and those keep immediate finalization.Desktop, web, multi-channel, mobile sources without a quiet check (for example
limitless), empty captures, explicit client reasons, refused or failed arms, and rows finalized meanwhile all keep immediate finalization. No capture is left without a finalization owner. There is no new flag. The existingLISTEN_QUIET_FINALIZATION_ENABLED=falsealso restores today's immediate finalization, because a disabled quiet check never arms.Change note:
backend/docs/listen_pusher_pipeline/changes/2026-11-16-mobile-batch-socket-drop.md.Product invariants affected
none
How it was verified
backend/.venv/bin/python -m pytest -q tests/unit/test_mobile_batch_disconnect.py: 16 passed. With theruntime.pychange reverted, the 4 phone-drop cases fail (process_conversationawaited once) and the rest pass, so the test pins the bug.make preflightandscripts/pr-preflight --pr-body-fileon this body.Not verified: a real phone reconnect against a deployed listen pod. The resume test drives the real
LiveConversationController.prepare()and continuation resolution against the strict Firestore fixture, not a device.Tests
backend/tests/unit/test_mobile_batch_disconnect.py:_teardown_components. It never callsprocess_conversation, arms the quiet check, commits the archive tail, and leaves the rowin_progresswith no close barrier.finalization_reason, no committed audio, a source with no quiet check, web platform, and a row finalized meanwhile.queued,server_recovery).record_pendingregistered, completion called, noarchive is not closederror).Line-Count-Exception: backend/routers/listen/runtime.py | 1551 -> 1555 | the teardown owns the close-or-keep-open decision; its logic lives in batch_close.py and runtime.py only gains the call site and the arm result
UI evidence
UI-Evidence: none -- backend-only lifecycle change
Failure class (fixes)
Failure-Class: new
Failure-class transition narrative (only when needed)
Adds
FC-transport-drop-terminalizes-resumable-capture. Violated contract: a socket close counts as a stop only on a client whose close means stop. A client that reconnects to the same recording has to keep that capture open, with a durable finalization owner. The desktop close-means-stop rule leaked to mobile through a cohort flag. Canonical guard: key immediate finalization on the client's close semantics, and skip it only with a confirmed durable owner and committed audio. The guard artifact is the teardown contract testbackend/tests/unit/test_mobile_batch_disconnect.py. Evidence: this PR, plus the 2026-11-16 prod split and fleet sample above.Remaining risk
omi/phone(wearables such aslimitless/bee/plaud) still finalize on every drop and can still split. They have no quiet check, andrecovery_admission_refusalonly admitsomi/phone, so widening them is a separate change.attach_closed_batch_capture), which needs the close barrier. The in-session timeout path already behaves this way, and finalization stays the documented repair path.