Skip to content

fix(app): never strand a connected pendant without capture or uploads - #22873

Merged
Git-on-my-level merged 7 commits into
mainfrom
fix/app-capture-recovery
Oct 20, 2026
Merged

Git-on-my-level merged 7 commits into
mainfrom
fix/app-capture-recovery

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Oct 20, 2026 •

Copy link
Copy Markdown
Member

Why

On 2026-10-20 a user lost about 4 hours of pendant audio, including a 2-hour conversation, and uploads stalled for the same 4 hours. A cold start fixed both. Two investigations traced it to several gaps that compound:

  1. Primary cause: a reconnect during a sync pass skipped capture, and nothing restarted it.
    • Every BLE connect wakes a deviceConnected pass.
    • That pass ran inside SyncWakeScope, so DeviceProvider._onDeviceConnected and streamDeviceRecording silently skipped the capture start, and the uplink fence blocked socket and audio opens.
    • Nothing re-drove the skipped start when the pass ended or when the app came to the foreground.
    • The pass itself could hang forever on an untimed BLE read. Every later wake (foreground, Retry) joined the stuck pass, so no uploads happened either.
    • A connected pendant on firmware 3.0.21 with no audio subscriber discards audio (transport.c pusher, connected + unsubscribed branch).
  2. Live socket recovery had dead ends.
    • A normal server close (1000/1001) waited for the 15 s keep-alive.
    • The keep-alive cancels itself permanently on several conditions.
    • A network change or app resume never re-armed it.
  3. The upload worker only ran on wake events.
    • A wifi→cellular handover never reports offline, so it caused no wake.
    • Retries and the cooldown-end wake were dropped in the background.
    • Nothing woke the worker while rows sat in "Waiting to sync".
  4. BLE reads and writes had no timeouts. On iOS, a second read of the same characteristic overwrote the first caller's completion, so the first caller's future never resolved.

What changes

1. Capture is never stranded by an upload pass.

  • Only the OS-granted periodic window (BGTask) still fences live capture. Reconnect and watchdog passes no longer do (RecordingTransferCoordinator.fencesLiveCapture).
  • DeviceProvider always calls streamDeviceRecording.
  • If a start lands inside a fenced pass, it is recorded and replayed when the fence drops.
  • Foreground resume starts a connected pendant that capture left idle.
  • Every pass has a hard time limit: 60 min, or 10 min when fenced. The limit sits inside the scope, so a hung stage releases the fence and _inFlight. SyncProvider cancels the abandoned sync, and the coordinator schedules a retry.

2. Pendant audio is never silently dropped.

  • NativeBleTransport hands audio notifications that arrive with no Dart listener to OrphanAudioRoute. These packets were previously dropped by the broadcast controller, because the native GATT subscription outlives capture's listener.
  • Capture writes them synchronously to the existing safety WAL while the WAL tracks the pendant codec. They then upload through the normal sync path.
  • Why the WAL and not unsubscribing: on shipped firmware, unsubscribing while connected makes the pendant discard audio. It writes flash only while disconnected (omi/firmware/omi/src/lib/core/transport.c pusher). Unsubscribing is therefore not a fallback.
  • Excluded: muted policy (user intent), a caller stop (the voice-profile flow), Transcribe Later (the native writer owns that audio), and phone or call ownership.

3. Live socket recovery.

  • A server close (except terminal codes 1008/4001/4002/4004/4005), a socket error, connectivity restore, a network-type change and app resume each kick an immediate reconnect.
  • Backoff is bounded: 1, 2, 5, 10 and 15 s over a 5-minute window, with the 15 s keep-alive still running underneath.
  • The kick re-arms a keep-alive that had cancelled itself, and re-installs a missing pendant audio stream while capture still owns it.

4. Upload worker.

  • Any connectivity change wakes the worker, including a network-type change (ConnectivityService.onNetworkChange).
  • cooldownElapsed is accepted in the background. Retries also run in the background, capped at 6 consecutive failures.
  • A new watchdog wake runs every 10 minutes while recordings are pending and no pass is running.
  • The multipart upload response-body read now has a 2-minute timeout.

5. BLE timeouts.

  • Dart NativeBleTransport read and write calls time out after 10 s. A timed-out read returns empty; a timed-out write throws.
  • Capture's codec read is bounded at 35 s and falls back to the last known codec.
  • iOS OmiBleManager: pending reads and writes are queued FIFO per characteristic instead of overwritten, and each fails with TIMEOUT after 10 s.

6. Telemetry.

  • New registered event Capture Recovery Observed, with kind (capture_start_skipped, capture_start_redriven, pendant_audio_orphaned, transfer_pass_timed_out) and trigger, plus a consumer question.
  • Debug-log markers: capture_start_skipped, capture_stopped_with_device_streaming, transfer_pass_stuck, ble_op_timeout.

Flags: none. These restore intended behaviour and ship on by default. Each new path is bounded (rate limits, retry cap, time limits) and fails toward recording.

Known trade-off: on firmware that has opted into live persistence (draft #20450, not released), orphan audio is also on the ring. The pendant ring custody contract (app/lib/services/wals/PENDANT_RING_CUSTODY.md) prefers keeping both copies over losing one.

Tests

Run as targeted Flutter tests under nice -n 19. Results:

  • test/services + test/providers: 1638 passed.
  • test/spine (OMI_DEV_CONTROLS=1): 138 passed.
  • test/unit + test/backend: passed.

New tests:

  • test/services/capture/capture_live_recovery_test.dart, through the real controller, socket service and WAL with a scripted transport. It covers:
    • a normal close reconnecting within 2 s;
    • repeated closes backing off but never stopping;
    • a network handover, and separately an app resume, re-arming a keep-alive that had cancelled itself;
    • terminal close codes not kicking a reconnect;
    • a reconnect during a fenced pass still yielding capture once the pass ends;
    • a hung fenced pass aborted by its time limit, after which capture starts;
    • reconnect passes not fencing at all;
    • orphan packets being persisted, while muted and caller-stopped pendants are left alone.
  • recording_transfer_coordinator_test.dart covers:
    • a hung pass being abandoned, releasing the fence and the joined wakes;
    • only periodic fencing;
    • a network handover waking a pass;
    • the watchdog waking only while work is pending;
    • background cooldown and bounded background retries.
  • native_ble_transport_test.dart covers read and write timeouts and orphan delivery.

Updated tests (these encoded the old contract):

  • periodic_recording_sync_test now expects capture after the pass, and bounded background retries.
  • tiered_capture_test and resume_sync_fence_test now use the periodic fence.
  • capture_recovery_replay_scenarios_test: connectivity restore now reconnects immediately rather than at the next 15 s tick.

Not verified: on-device behaviour (no physical pendant run), and the iOS native change. The Swift change was syntax-checked with swiftc -parse only and needs the iOS CI build.

Regression guard for #20837

Fault-injection tests in app/test/services/capture/capture_live_recovery_test.dart, group "regression guard for #20837 (fault injection)". They run in CI through flutter test.

Each test asserts two things:

  • live capture (a connected socket plus the pendant audio subscription) is running again within 3 s of virtual time;
  • no pendant packet is dropped: every packet emitted while the pendant was connected is durable in the safety WAL.

Faults covered:

  • A Wi-Fi to cellular handover during an upload pass. The socket dies on the old interface, a network change follows, and the reconnect pass is still running.
  • A normal server close (1000) of the live socket.
  • A pendant BLE drop and reconnect in the middle of a fenced pass. Packets arriving while capture is deferred reach the orphan route and are persisted, and capture starts when the fence drops.
  • A hung pass that never finishes. The hard time limit ends it, and capture starts.

By construction, each of these fails on the pre-PR code (reasoned from the code paths; not executed against the old tree): either there is no capture restart, or the restart comes at the 15 s keep-alive, beyond the 3 s bound.

Review round 1 (Grok) fixes

  • FIX-FIRST, replay under phone or call ownership. A start swallowed by a fence is now replayed unless the pendant already owns capture, is suspended, or was stopped by a caller. The reducer records the pendant as suspended while a phone recording or call holds capture, and resumes it afterwards. New test: "a start swallowed while a phone recording owns capture resumes the pendant after it".
  • FIX-FIRST, orphan WAL priming race.
    • The codec boundary is taken only while the transport still has no listener and no phone or call owns capture, and this is rechecked after the await.
    • No boundary is taken when the WAL already tracks the pendant codec (new LocalWalSyncImpl.currentCodec).
    • The backlog is written only while the WAL codec matches. Otherwise it is dropped rather than written under the wrong codec.
    • A full backlog drops the oldest packet.
  • FIX-FIRST, an abandoned pass keeps running.
    • A timed-out pass is marked stale by a pass generation and stops at its next stage boundary.
    • It holds an extra transfer keep-alive until it actually exits.
    • No later pass discovers or drains beside it. That block is bounded by a second time limit, after which the pass is presumed dead.
    • The test now asserts that there is no second discovery or drain while the body runs, and that the keep-alive is balanced.
  • SHOULD-FIX, iOS GATT queue. Only the queue head is issued to CoreBluetooth, which allows one outstanding read or write per characteristic. The next request is issued when the head completes or times out.
  • Not changed:
    • A timed-out Dart read still returns empty. That matches every other native read failure, which also maps to empty, and the watchdog and reconnect wakes retry.
    • Only Opus goes to the safety WAL. That matches the primary capture path's checkWalSupported.
    • Fenced foreground periodic windows are capped at 10 min, as noted in the review's NIT.
  • Merge with main: the change is merged with main (fix: preserve transcription through Wi-Fi and provider settings changes #22197 rewrote ConnectivityService). onNetworkChange is re-added on top of that version and has a unit test.

Review round 2 (Grok) fixes

  • FIX-FIRST, orphan priming race (supersedes the round-1 priming).
    • Orphan audio is now written synchronously, and only while the WAL already tracks the pendant's codec. That holds in the incident shape, where the pendant was the last source.
    • The orphan path never calls onAudioCodecChanged, so it cannot race a live start or wipe a session that subscribed in the meantime.
    • When the codecs differ, packets are counted (dropped) and capture is restarted.
    • New test: "orphan packets never move the WAL off another source's codec".
  • FIX-FIRST, gate on an abandoned pass.
    • An abandoned pass now blocks discovery and drain until it actually exits. There is no time-based release any more.
    • Its sync is cancelled on timeout, and every BLE and HTTP await beneath it is now bounded, so it does exit.
    • Every stage returns once the pass is stale. That includes the tail after the drain (refresh and reconcile) and the catch path.
  • SHOULD-FIX, iOS late GATT replies. After a timeout, the next operation waits for CoreBluetooth's late reply, or a 5 s grace, before it is issued. The late reply is never handed to the next waiter.

Review round 3 (Grok): mergeable

  • Grok's verdict: every FIX-FIRST from rounds 1 and 2 is resolved.
  • SHOULD-FIX taken: a deferred start that is swallowed again by a periodic fence raised in the same turn now re-arms and loops, instead of being stranded.
  • Not taken in this PR (follow-ups):
    • correlate a late iOS GATT reply by operation id on notifying characteristics;
    • make a timed-out Dart read throw instead of returning empty, so a storage list read that times out is retried rather than counted as "no files".

Product invariants affected

  • INV-CAP-1: this extends it. A sync pass, a dead socket or a missing listener must not stop consumption of pendant audio while the connected firmware discards unconsumed frames.

UI-Evidence: none -- no UI change; capture, sync and BLE plumbing only

Failure-Class: FC-automatic-capture-pause-without-retention

Line-Count-Exception: app/lib/services/capture/capture_controller.dart | 4520 -> 4531 | recovery hooks only (part directive, state field, resume/close/connectivity/stop hooks, sync dispose cancel); logic lives in the new capture_live_recovery.dart part
Line-Count-Exception: app/lib/services/wals/local_wal_sync.dart | 2757 -> 2758 | one read-only currentCodec getter so orphan audio never forces a codec boundary on a WAL that already tracks the pendant codec

🤖 Generated with Claude Code

Git-on-my-level and others added 2 commits October 20, 2026 21:38
A pendant reconnect landing inside its own reconnect sync pass skipped capture
start, nothing re-drove it, and the pass could hang forever on an untimed BLE
read. A connected but unsubscribed legacy pendant discards audio, so ~4 h was
lost (2026-10-20). Uploads stalled behind the same stuck pass.

- Only the OS periodic window fences live capture; a swallowed pendant start
  is replayed when the fence drops; foreground starts an idle connected pendant.
- Transfer passes get a hard time limit (60 min, 10 min fenced) that releases
  the fence and the in-flight pass; the watchdog wakes while rows are pending;
  any network change wakes a pass; retries and cooldown-end run in background.
- Server close, network change and resume kick an immediate bounded-backoff
  socket reconnect; the keep-alive can no longer die for good.
- Pendant audio reaching the transport with no capture listener is persisted
  to the safety WAL (unless muted or caller-stopped).
- BLE read/write timeouts in Dart; iOS queues same-characteristic reads and
  writes FIFO with a 10 s timeout instead of orphaning the first caller.
- Capture Recovery Observed analytics event; multipart body read timeout.

Failure-Class: FC-automatic-capture-pause-without-retention

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-20T16:17:54.564393Z a9b92cc New commits
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 0daf292b3b

ℹ️ 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".

Comment on lines +156 to +159
final codec = state.codecByDevice[deviceId];
final persistable = codec != null && codec.isOpusSupported();
if (persistable) {
if (state.orphanBacklog.length < _orphanBacklogLimit) state.orphanBacklog.add(List<int>.from(packet));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Retain orphan packets until their codec becomes known

When orphan audio arrives before _getAudioCodec has succeeded for this controller—for example, native restores audio notifications while a periodic fence defers the first capture start—codecByDevice is empty, so persistable is false and the packet is neither backlogged nor written to the WAL. A later deferred start may populate the cache, but the already-arrived audio is irretrievably discarded; buffer these packets until codec lookup completes rather than dropping them.

Useful? React with 👍 / 👎.

Comment on lines +405 to +407
// The limit sits inside the scope, so a hung stage cannot hold the capture
// fence or `_inFlight` (which every later wake joins) past it.
Future<void> body() => _runPassBody(trigger).timeout(limit);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Cancel timed-out pass bodies before starting another pass

If a discovery, refresh, or drain operation completes after the limit rather than never completing, Future.timeout only stops awaiting it; _runPassBody continues running after _inFlight is cleared and a retry is scheduled. The timeout hook sets the WAL cancellation flag, but the next syncAll resets that shared flag at app/lib/services/wals/wal_syncs.dart:248, allowing the abandoned and replacement passes to resume concurrently and potentially duplicate BLE pulls or uploads. Use a pass generation/cancellation token and prevent another pass from starting until the old body has actually terminated.

Useful? React with 👍 / 👎.

Comment on lines +100 to +102
if (!_shouldReconnectTranscriptionSocket || _transcriptServiceReady) return;
if (recordingState == RecordingState.deviceRecord) _socketReconnectPending = true;
if (!(_keepAliveTimer?.isActive ?? false)) _startKeepAliveServices();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Invalidate ready sockets on network handover

On a Wi-Fi-to-cellular handover where the old TCP connection remains half-open, no close or error callback clears _transcriptServiceReady; the new network-change listener calls this method, but this guard immediately returns, so it neither schedules the immediate reconnect nor re-arms keep-alive. This leaves capture on the dead interface in the exact handover scenario the new signal is intended to recover; mark the socket stale or explicitly close/probe it on network_change before applying the readiness guard.

Useful? React with 👍 / 👎.

Comment thread app/ios/Runner/Ble/OmiBleManager.swift Outdated
Comment on lines +578 to +581
guard let self, var queue = self.readCompletions[key],
let index = queue.firstIndex(where: { $0.id == operationId }) else { return }
let pending = queue.remove(at: index)
self.readCompletions[key] = queue.isEmpty ? nil : queue

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Prevent late GATT callbacks from completing a retry

After a read or write times out, this removes its queue entry even though CoreBluetooth may still deliver that operation's callback. If a retry on the same characteristic is queued before the late callback arrives, didUpdateValueFor or didWriteValueFor blindly removes the new first entry and completes the retry with the timed-out operation's result—for example, a delayed successful write can conceal the retry's later failure. Because the callbacks contain no operation ID, serialize issuance or explicitly consume stale callbacks before completing subsequent requests.

Useful? React with 👍 / 👎.

Comment on lines +279 to +284
if (!state.deferredStart) return;
state.deferredStart = false;
// Replays exactly the start the pass swallowed, for any pendant and mode.
final device = _recordingDevice;
if (device == null || state.deviceStoppedByCaller || _capture.stagedReadModel.phase != CapturePhase.idle) {
return;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Replay deferred starts while another source owns capture

If a pendant connects during a fenced periodic pass while the phone mic or a call owns capture, the fence records a deferred start, but when the fence drops this idle-only guard clears and discards it. A normal DeviceStartRequested in that state creates a pendant suspension debt so the pendant starts when the phone or call ends; bypassing the reducer means no debt exists and the connected pendant can remain uncaptured afterward. Dispatch the deferred start through the reducer unless it was explicitly cancelled, rather than requiring the phase to already be idle.

Useful? React with 👍 / 👎.

Comment on lines +188 to +193
await phone.onAudioCodecChanged(codec);
final model = _activeSource?.deviceModel ?? 'Omi';
phone.setDeviceInfo(deviceId, model);
state.orphanSource = BleDeviceSource(codec: codec, deviceId: deviceId, deviceModel: model);
state.orphanWalPrimed = true;
if (_orphanAudioAdmitted(deviceId)) _flushOrphanBacklog(deviceId, codec);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Key orphan WAL priming to the current device

If the connected pendant changes while onAudioCodecChanged is awaiting its WAL flush, this stale continuation still installs an orphanSource and marks the shared state primed for the old device. Orphan packets from the new device can then be flushed through the old device's source and metadata, while the shared backlog may also contain packets from both devices. Capture a device/generation token around the await and discard or separately finalize stale priming work before updating the current orphan state.

Useful? React with 👍 / 👎.

Git-on-my-level and others added 2 commits October 20, 2026 22:02
…ence orphan WAL priming, stop abandoned passes

- A start swallowed by a sync fence is replayed unless the pendant already
  owns capture or a caller stopped it; the reducer records a suspension when
  a phone recording or call owns capture.
- Orphan WAL priming takes a codec boundary only while the transport still
  has no listener, rechecks after the await, skips it when the WAL already
  tracks the pendant codec, and drops (never mis-tags) packets otherwise;
  a full backlog drops the oldest packet.
- A timed-out pass is marked stale and stops at its next stage boundary; it
  keeps the transfer keep-alive until it exits, and no later pass discovers
  or drains beside it (bounded by a second time limit).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	app/lib/services/connectivity_service.dart

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 323ee1420d

ℹ️ 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".

Comment on lines +806 to +807
Future<http.Response> _readMultipartBody(http.StreamedResponse response) =>
http.Response.fromStream(response).timeout(multipartBodyReadTimeout);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Cancel the response stream when the body deadline expires

When the pooled multipart endpoint sends headers but never finishes its body, Future.timeout completes only the wrapper future; it does not cancel http.Response.fromStream or its subscription. The failed upload can therefore be retried while the original response continues holding a shared-client connection and buffering data indefinitely, so repeated stalls can exhaust resources despite releasing the transfer pass. Use a cancellable stream read or abort the underlying request when this deadline fires.

Useful? React with 👍 / 👎.

Comment on lines +73 to +75
final codec = await read().timeout(_codecReadTimeout);
_liveRecovery.codecByDevice[deviceId] = codec;
return codec;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve the cached codec when native reads return empty

When an Opus pendant reconnects and the production GATT codec read times out, NativeBleTransport.readCharacteristic catches that timeout and returns an empty list, and DeviceConnection.performGetAudioCodec converts the empty result to pcm8. Consequently this successful return bypasses the catch here and overwrites the known Opus codec with pcm8, causing the socket and WAL parser to interpret subsequent Opus packets as PCM and making orphan packets non-persistable. Treat the empty/error sentinel as a failed codec lookup so the last known codec is retained.

Useful? React with 👍 / 👎.

Comment on lines +64 to +66
OrphanAudioRoute.sink = _onOrphanAudio;
lifetime.own(() {
if (identical(OrphanAudioRoute.sink, _onOrphanAudio)) OrphanAudioRoute.sink = null;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Clear the orphan sink with the installed callback instance

When a capture controller is disposed before a replacement is installed, evaluating _onOrphanAudio here creates another bound-method tear-off, which is not the identical function object assigned to the static sink. The guard can therefore leave OrphanAudioRoute.sink retaining the disposed controller and routing every later native audio notification to its dead handler, leaking the controller graph and dropping those packets until another controller overwrites the sink. Retain the installed tear-off and compare against that exact instance during cleanup.

Useful? React with 👍 / 👎.

Comment on lines +3181 to +3184
_liveRecovery.deviceStoppedByCaller = false;
if (SyncWakeScope.syncOnly) {
if (device != null) updateRecordingDevice(device);
_deferDeviceStartPastSyncPass();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve explicit stops across fenced reconnects

When the voice-profile flow has explicitly called stopStreamDeviceRecording, a pendant reconnect during a periodic sync fence now enters this method through DeviceProvider and clears deviceStoppedByCaller before deferring the automatic start. Once the fence drops, _runDeferredDeviceStart therefore no longer recognizes the explicit stop and restarts pendant capture while the voice-profile flow is still using the microphone. Clear this flag only for an intentional resume, not before an automatically deferred reconnect.

Useful? React with 👍 / 👎.

…e abandoned-pass gate, honour late GATT replies

- Orphan audio is written synchronously and only while the WAL already
  tracks the pendant codec; it never takes a codec boundary, so it cannot
  race a live start or wipe a session that subscribed meanwhile.
- An abandoned transfer pass blocks discovery and drain until it really
  exits (no time-based release); every stage, including the post-drain
  refresh/reconcile tail and the catch path, returns once the pass is stale.
- iOS: after a GATT timeout the next op waits for CoreBluetooth's late reply
  (or a 5 s grace) and that reply is never handed to the next waiter.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 930bfaaa51

ℹ️ 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".

state.orphanPackets++;
final codec = state.codecByDevice[deviceId];
final phone = _wal.getSyncs().phone;
final persistable = codec != null && codec.isOpusSupported() && phone.currentCodec == codec;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Require the orphan WAL to match the pendant identity

When the controller has cached codecs for two Opus pendants, switching back to pendant B during a fenced/no-listener interval can leave the phone WAL configured for pendant A while codecByDevice[B] is already Opus. This codec-only admission then sends B's frames to onFrameCaptured, which still uses A's _deviceId for custody and WAL metadata (local_wal_sync.dart:634-637, 1872-1874), mixing recordings under the wrong device. Require both the codec and current WAL device identity to match, or establish a safe device boundary, before persisting orphan frames.

Useful? React with 👍 / 👎.

Git-on-my-level and others added 2 commits October 20, 2026 22:55
Wifi-to-cellular handover during an upload pass, a normal server close, a
pendant BLE drop and reconnect mid-pass, and a hung pass: each asserts live
capture is back within 3 s and every emitted pendant packet is durable.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: a9b92cca1a

ℹ️ 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".

Comment on lines +322 to +324
} on TimeoutException {
_logOperationTimeout('read', characteristicUuid);
return [];

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Propagate storage read timeouts instead of returning empty

When a ring-status or storage-inventory read exceeds this deadline, returning [] makes performGetRingStatus/performGetStorageFileStats report no data, after which RingStorageSync.refreshWalsFromDevice or StorageSync.refreshWalsFromDevice clears its discovered WALs. Because the new watchdog is gated by locally known pending WALs (SyncProvider's hasPendingWork), device-only recordings then receive no retry and remain stranded until some unrelated external wake; propagate a retryable timeout/error instead of representing it as an empty characteristic value.

Useful? React with 👍 / 👎.

@Git-on-my-level
Git-on-my-level merged commit 20cd605 into main Oct 20, 2026
44 checks passed
@Git-on-my-level
Git-on-my-level deleted the fix/app-capture-recovery branch October 20, 2026 17:03
Git-on-my-level added a commit that referenced this pull request Oct 20, 2026
…itor, rollout-hop capture health (#22892)

## Why

Builds 1.0.560–563 (#20837) skipped the pendant capture start whenever a
BLE reconnect landed during an upload pass, and nothing restarted it.
Firmware 3.0.21 discards audio while a phone is connected but not
subscribed, so the audio was recorded nowhere. About 640 users hit
`Capture Wedge Detected trigger=connected_no_bytes` over a week, and
nobody noticed until David lost a dinner on 10-20.

The app fix is #22873. This PR adds the gates that catch the next
regression of this class: at dev time first, on TestFlight at the
latest, and before a store rollout widens.

**Stacked on #22873** (`fix/app-capture-recovery` @ a9b92cc). It
contains that diff until #22873 merges; merge #22873 first.

## What changes

### 1. Dev time: capture-continuity suite
(`app/test/services/capture/capture_continuity_test.dart`)
- **`SimulatedPendant`** gives every BLE packet a unique frame id. The
link models firmware 3.0.21:
  - subscribed: the packet is notified;
  - disconnected: the pendant stores it on its own flash;
- connected with no listener: the orphan route (#22873), or a drop on a
fresh link.
- **`PendantFrameLedger`** finds every frame id in socket sends, the WAL
buffer, in-memory chunks, WAL files and uploads
(`ScriptedUploads.onUploadFiles`). It asserts the invariant **every
frame the pendant notifies is streamed to the live socket or persisted
in the local WAL**, and that live capture resumes within 5 s. It also
checks that both custody paths saw frames, so a broken decoder cannot
pass.
- **Scenarios** run through the real controller, socket service, WAL and
transfer coordinator:
- the exact 10-20 path: a reconnect 45 s into a stuck `deviceConnected`
pass, which must resume *while the pass is still stuck*;
  - background and foreground, with a close while backgrounded;
  - the layer-2 declaration;
- a 10-minute soak with every fault: wifi to cellular, a 1000 close,
reconnects mid-pass, and background with a drop.
- **Not duplicated:** #22873's count-based single-fault guards
(78b11b7).
- **Runtime:** about 6 s.
- **Discriminates (verified):**
- On the pre-#22873 tree (9e75c89, which contains #20837), the reconnect
scenario loses **125 s** of audio and the soak **320 s**.
- Mutations on #22873 fail too: removing the orphan route, or fencing
every pass (the #20837 contract).

### 2. Debug and TestFlight: capture-continuity invariant monitor
- **The gap it closes:** the existing `connected_no_bytes` watchdog only
watches *open capture sessions*. In the #20837 state there was no
session, so it was blind. It is also already exempt from the
`mobile-capture-recovery-v1` gate, so making it "unconditional" would
not have helped.
- **The check:** `CaptureContinuityMonitor` checks every 15 s while a
pendant is connected. It declares `Capture Wedge Detected` with
`trigger=connected_not_capturing` when all of these hold for 60 s:
- capture is expected (not muted, not Transcribe Later, no caller stop,
no phone or call owning capture);
  - there is no capture subscription;
- no frame reached custody. Orphan audio persisted to the WAL counts as
custody, so it stays quiet.
- **Output:**
- the event is emitted in every build, mirrored to the replacement
collector;
  - `Capture Recovery Resolved` fires when capture returns;
- the Home banner (`CaptureContinuityDogfoodBanner`) shows only in
`kDebugMode || Env.isTestFlight` builds.
- **Telemetry only:** it never retries or restarts anything.
- **Timer:** it runs only while a pendant is connected; idle controllers
hold no timer.

### 3. Store rollout hops: capture-health hold
(`app/scripts/mobile_capture_health.py`)
- **Placement:** the iOS phased jump to 100%
(`ios_phased_release_should_complete`) and each Android ladder hop
(`run_android`), the two exposure-expanding steps with no health check.
Dispatch itself stays gated by the operator release gate.
- **Rubric:** mirrors the operator gate's judge (Hermes
`omi_capture_wedge.py`, Observability). The rate is wedge users,
reweighted by 100/`omi_sample_pct`, over pendant users (`Device Session
Ended`), per (`$os`, `$app_build`) over 48 h. A build is **BAD at more
than 2x the previous build** (the largest build below it with at least
20 pendant users) **or at more than 50 wedge users a day**.
- **Deliberate differences from the operator gate:**
- the build is exact: the Android version code, or the iOS build
attached to the live App Store version (`GET
/v1/appStoreVersions/{id}/build`), never a same-version sibling;
  - the triggers include `connected_not_capturing` from layer 2;
  - a missing build or a failed query **HOLDS** (fail closed).
- **Override:** `capture_health_override=<reason>` on
`mobile_daily_train.yml` and on `mobile_rollout_watch.yml` (new manual
`workflow_dispatch`) lets one run through, with the reason logged. No
new workflow file.
- **Verified read-only against live PostHog 10-20**, matching the
operator gate:

| Build | Verdict | Detail |
|---|---|---|
| iOS 1389 (1.0.563) | BAD | 34%, 100 a day |
| iOS 1409 | BAD | |
| iOS 1417 (1.0.566) | BAD | |
| Android 1461 (1.0.566) | BAD | 13% against 0% |
| Android 1445 | ok | |

## Before merge (decision for a maintainer)
- **Codemagic needs a read-only PostHog key.** `mobile-daily-train` and
`mobile-rollout-advance` only have the `google_play` env group. Add
`POSTHOG_PERSONAL_API_KEY` (query read) to a Codemagic group and list it
in both workflows in `codemagic.yaml`. Until then, every hop **fails
closed (HOLD)**; use the override input to advance deliberately.
- **1.0.566 will hold** on both platforms once the key is in. That is
the gate working: the build predates #22873.

## Review
- **Grok round 1** (fixed):
  - iOS is judged on the exact store build from App Store Connect;
- any PostHog read failure HOLDS instead of raising (an `IncompleteRead`
could have aborted the train);
- the continuity timer is cancelled synchronously on dispose and
re-synced on stage-only device updates;
- the ledger requires the synthetic fill, so real 80-byte Opus audio can
never count as a pendant frame.
- **Grok round 2** (fixed): a malformed App Store Connect build resource
now returns "unknown build" (HOLD) instead of raising out of the iOS
train. Otherwise the round-1 fixes were confirmed sound.
- **Declined, by design:**
- the baseline is the lower build with the most pendant users (the
operator gate's `previous_build`), not the highest build number;
- the per-day cap is window users x 24 / hours, as in the operator
`judge`.

## Tests
All targeted, under `nice -n 19`:
- `flutter test test/services/capture test/services/wals test/providers
test/pages/conversations`: 1434 passed.
- `test/spine` (`OMI_DEV_CONTROLS=1`): 138 passed.
- `flutter analyze` on the changed files: clean.
- `python3 app/scripts/mobile_capture_health_test.py` (14),
`mobile_daily_train_test.py` (91, including the hop wiring), and both
dispatcher tests: OK.
- `run_checks.py --lane local` on the changed files: all selected checks
pass.

**Not verified:** on-device behaviour of the monitor and banner (no
physical pendant run), and Codemagic runs of the hold (no key
provisioned).

## Product invariants affected
- INV-CAP-1 (pendant audio retention): enforced, not changed. Layer 1
asserts it end to end (no notified pendant frame may miss both the
socket and the WAL), layer 2 detects it at runtime (a connected pendant
nobody consumes), and layer 3 holds a rollout that violates it in the
field. Capture behaviour is unchanged; the only controller edits are the
continuity-watch hooks.

Failure-Class: none

Line-Count-Exception: app/lib/services/capture/capture_controller.dart |
4520 -> 4539 | 4520 -> 4531 is #22873 (stacked); this PR adds 8 hook
lines (import, part directive, timer field, two watch syncs on device
update, dispose cancel, custody mark); logic lives in the new
capture_continuity_watch.dart part
Line-Count-Exception: app/lib/services/wals/local_wal_sync.dart | 2757
-> 2758 | #22873 (stacked): one read-only currentCodec getter; this PR
does not touch the file

UI-Evidence: none -- the only UI is a debug/TestFlight-only diagnostic
banner (never shown in store builds), covered by a widget test in
capture_continuity_monitor_test.dart

🤖 Generated with [Claude Code](https://claude.com/claude-code)
Git-on-my-level added a commit that referenced this pull request Oct 20, 2026
## Why

David approved submitting iOS 1.0.568 (build 1423, Codemagic 6ad7a5c7,
from fbb197a) to App Store review. It carries the pendant capture fix
#22873. `mobile-store-promote` requires
`app/changelog/releases/1.0.568.json` on main.

## What

- `mobile-changelog.py collect --version 1.0.568` consumed all
unreleased fragments. The fragment set on main is identical to
fbb197a's, so every fragment describes code that is in the build.
- The release file holds a short curated What's New list (7 lines, 717
iOS characters) led by the capture-recovery line. Most collected
fragments already reached users through the train's derived notes for
1.0.565 and 1.0.566, so repeating them would overstate this release.
- No code changes; changelog data only. Store submission is MANUAL
release; David presses Release after approval.

## Verification

- `python3 .github/scripts/mobile-changelog.py validate`: passes.
- `store-notes --version 1.0.568 --store ios` (717 chars) and `--store
android` derive cleanly with no cross-platform mention.

🤖 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/22908?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/22908?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F22908&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. -->
kriegcloud pushed a commit to kriegcloud/omi that referenced this pull request Oct 20, 2026
…itor, rollout-hop capture health

Builds 1.0.560-563 (BasedHardware#20837) skipped pendant capture after a reconnect during
an upload pass, and ~640 users lost audio for a week before anyone noticed.
Three layers so the next one is caught at dev time, on TestFlight, or before
a store rollout widens:

1. Dev time: capture_continuity_test.dart streams a simulated pendant (unique
   frame ids) through the real controller, socket service, WAL and transfer
   coordinator: the exact 10-20 reconnect during a stuck upload pass,
   background/foreground, and a ten-minute soak with every fault (network
   change, server close, reconnects mid-pass, background). It complements
   BasedHardware#22873's count-based single-fault guards. PendantFrameLedger asserts every notified frame is streamed or
   persisted (incl. uploaded), and live capture resumes within 5 s. On the
   pre-BasedHardware#22873 tree it loses 125 s (RCA path) and 320 s (soak).

2. Debug/TestFlight: CaptureContinuityMonitor declares Capture Wedge Detected
   trigger=connected_not_capturing when a connected pendant that should be
   captured has no capture subscription and no frame reaches custody for 60 s
   (the state connected_no_bytes cannot see: no capture session). Event in all
   builds; Home banner only in debug/TestFlight. Telemetry only.

3. Store hops: mobile_capture_health.py mirrors the operator gate's judge
   (wedge users reweighted by omi_sample_pct / pendant users per os+build;
   BAD at >2x the previous build or >50 wedge users/day) and holds the iOS
   phased jump and the Android ladder hop. Fails closed; one-shot
   capture_health_override input on the train and rollout-watch workflows.

Stacked on BasedHardware#22873 (fix/app-capture-recovery).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
kriegcloud pushed a commit to kriegcloud/omi that referenced this pull request Oct 20, 2026
Collects the unreleased changelog fragments into releases/1.0.568.json for the
iOS 1.0.568 (build 1423) store submission, which carries the pendant capture
fix BasedHardware#22873. The What's New text is a short curated list led by the capture fix;
most collected fragments already shipped to users in 1.0.565 and 1.0.566.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Git-on-my-level added a commit that referenced this pull request Oct 21, 2026
## Problem and result

Pendant packets arriving during a reconnect could be appended to the WAL
buffer after its old contents were drained, then erased by
`onAudioCodecChanged` after disk I/O. This is a product audio-loss bug,
not a polling fixture bug. Seal the complete old pendant tail and
advance codec and device identity synchronously before the flush;
packets arriving during I/O stay in the new buffer under the new
source's custody. The pendant capture caller supplies identity at this
boundary because native BLE continues delivering during the flush. Phone
capture starts only after its flush and identity update both finish, so
its existing ordering and protected spine oracle remain unchanged. Reuse
the existing pendant custody construction and preserve the phone
chunk/tail policy.

The existing `capture_live_recovery_test` packet count and three-second
recovery bound are unchanged. New barrier tests force the exact I/O
interval on same-codec reconnects and codec changes, then read the
durable index and files to prove every packet appears exactly once, in
order, under the correct codec.

## Causal evidence

- The pre-fix product fails the new write-barrier test: 50 initial
packets + 10 during the blocked write produces only 50 durable packets,
expected 60. With this fix the barrier and original capture recovery
suites pass.
- `git log -S 'pendant BLE drop'` and blame locate the failing
regression case at `78b11b7ac95` in #22873. The same PR introduced the
orphan route in `c6f8014808f`, finalized as synchronous delivery in
`930bfaaa519`, exposing an existing codec-reset race: the post-await
buffer clear traces to `f3aa85e9e16`, with the pendant drain/flush queue
added in `c0c766c0dce1` (#20462).
- #22987's CI still reports 210 expected / 200 actual despite its longer
15-second wait:
https://github.com/BasedHardware/omi/actions/runs/39554266739/job/119071092410
. Coordination and mechanism are posted on that PR. Its timeout-only
approach does not fix this race, so this is a separate product fix.
- The original test passes on a fast local filesystem; the write barrier
reproduces the packet loss independently of host timing. No test is
skipped, quarantined, retried, or weakened.

## Verification

All local checks run through `/Users/dazheng/workspace/omi/bin/omi-heavy
run -- nice -n 19`.

- Baseline: `bash test.sh
test/services/capture/capture_live_recovery_test.dart` (138 protected
spine tests and 17 capture recovery tests passed).
- Red: the new same-codec write-barrier regression against unmodified
main fails 60 expected / 50 actual.
- Green after source-identity correction: `flutter test
test/unit/local_wal_durability_seam_test.dart
test/unit/local_wal_sync_test.dart
test/unit/local_wal_live_custody_test.dart
test/unit/local_wal_sync_session_generation_test.dart
test/unit/local_wal_sync_owner_uid_test.dart test/services/capture
test/services/wals`, 633 passed. Includes same-codec and changed-codec
write barriers, two-pendant ring custody during flush, exact file
payloads, session generation fencing and unchanged live recovery
assertions.
- `flutter test --dart-define=OMI_DEV_CONTROLS=1 test/spine`: 138 passed
after the correction.
- `scripts/pr-preflight --pr-body-file ...`: 25 checks passed.
`OMI_PR_BODY_FILE=... make preflight`: 25 checks passed. Push hooks also
run without bypasses.

This is source-level and hermetic disk evidence. No physical-device run
or production account data was used. A read-only App Store Connect check
on 2026-10-21 confirms iOS 1.0.568 build 1423 is still
`WAITING_FOR_REVIEW`, release `MANUAL`; public iOS is 1.0.566 build
1417. Codemagic identifies iOS1423 and Android1471's source as
`fbb197a6bf4fb56b432280140beb6c8c797e5927`, containing #22873 and the
vulnerable clear. The existing rollout receipt
`6ad848373ac160f4685c9479` at 05:06 UTC confirms Android 1.0.568/1471
advanced from 1% to 10% production. Public Play still lists 1.0.567, so
the listing alone missed staged exposure. The later internal 1.0.569
candidates (iOS1427, Android1475; source `bbede22e1e4`) also contain the
vulnerable code. Field-loss prevalence was not measured. A rebuilt
mobile artifact is needed; no backend deployment is needed.

## Review follow-through

- Round 1 full Grok review: SHIP at `6fc768e8375`.
- Automated P1: moving codec before I/O must also move device identity.
A two-pendant write barrier reproduces missing ring evidence on the
first head; the fix moves codec/device together for the pendant caller
and checks exact old/new device, codec, ring, epoch and frame counts.
- The unchanged stop/ingress race noted as minor in round 1 is tracked
in #22996. This PR changes the automatic reconnect/source boundary.

## Product invariants affected

- INV-CAP-1: preserve every admitted pendant packet across automatic
reconnect and WAL source changes, including arrivals during durable
writes.

Failure-Class: new

UI-Evidence: none -- WAL buffering and hermetic regressions only; no UI
change.

Line-Count-Exception: app/lib/services/wals/local_wal_sync.dart | 2756
-> 2764 | extract one synchronous pendant-sealing primitive shared by
tail drain and source rollover so asynchronous flushes cannot erase
later arrivals or bind them to the previous device
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