Skip to content

fix(listen): a mobile socket drop no longer ends the conversation - #25460

Merged
kodjima33 merged 1 commit into
mainfrom
fix/listen-mobile-socket-drop
Nov 16, 2026
Merged

kodjima33 merged 1 commit into
mainfrom
fix/listen-mobile-socket-drop

Conversation

@kodjima33

@kodjima33 kodjima33 commented Nov 16, 2026 •

Copy link
Copy Markdown
Collaborator

What changed and why

Bug (P0, fleet-wide, seen on prod 2026-11-16). When a mobile /v4/listen socket (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 same client_conversation_id. By then the bound conversation is already completed, so create_new_in_progress_conversation rolls 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 in backend/routers/listen/runtime.py came from ef2e2ed (2026-10-27) for desktop, where socket close means the user stopped. Prod set SERVER_BATCH_ONLY_MOBILE_PERCENT=100 on 2026-11-02 (90c537c), which made every mobile conversation batch-owned. Since then every mobile disconnect has finalized immediately. Before that, a mobile conversation stayed in_progress on disconnect. A reconnect inside conversation_timeout resumed 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_platform is ios/android and source is omi/phone.
  • The client sent no finalization_reason.
  • quiet_finalization.arm confirms a durable quiet check owns the row. arm now returns that as a bool.
  • After resumable_after_drop (new, routers/listen/batch_close.py) commits this socket's archive tail, the re-read row is still in_progress with committed audio.

No audio is lost. The helper runs LiveAudioArchive.close(), which flushes and commits every pack and merges the bounds through note_server_batch_audio. It does not publish the server_batch_audio_closed barrier, 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 admits SERVER_RECOVERY, and the raw-only finalizer registers record_pending and completes the capture. That is the same unclosed-but-committed shape the in-session silence timeout and the prepare() 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 existing LISTEN_QUIET_FINALIZATION_ENABLED=false also 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 the runtime.py change reverted, the 4 phone-drop cases fail (process_conversation awaited once) and the rest pass, so the test pins the bug.
  • 64 related unit files (everything referencing quiet finalization, batch close, listen runtime teardown, or server batch; 2502 tests): all passed.
  • make preflight and scripts/pr-preflight --pr-body-file on 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:

  • Phone drop (ios/android x omi/phone) runs the real _teardown_components. It never calls process_conversation, arms the quiet check, commits the archive tail, and leaves the row in_progress with no close barrier.
  • A desktop batch socket close still finalizes immediately.
  • Fallbacks keep immediate finalization: arm refused, arm raising, client finalization_reason, no committed audio, a source with no quiet check, web platform, and a row finalized meanwhile.
  • A reconnect at +35 s resumes the same batch-owned conversation id. The control case, where the first socket's row is completed as before this fix, rolls into a new id.
  • On the strict Firestore fixture, the real quiet check admits an open batch capture that has committed audio and no close barrier (queued, server_recovery).
  • The recovery finalizer hands that unclosed committed capture to batch (record_pending registered, completion called, no archive is not closed error).

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 test backend/tests/unit/test_mobile_batch_disconnect.py. Evidence: this PR, plus the 2026-11-16 prod split and fleet sample above.

Remaining risk

  • Mobile sources other than omi/phone (wearables such as limitless/bee/plaud) still finalize on every drop and can still split. They have no quiet check, and recovery_admission_refusal only admits omi/phone, so widening them is a separate change.
  • A quiet-finalized capture does not run the close-time episode attach (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.
  • The empty-generation edge case keeps today's behaviour: a socket that committed no audio is finalized (deleted) immediately.

View guided diff Turn on auto-fix

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.
@kodjima33
kodjima33 merged commit fc303dc into main Nov 16, 2026
67 checks passed
@kodjima33
kodjima33 deleted the fix/listen-mobile-socket-drop branch November 16, 2026 06:24
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. -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant