Repository navigation
fix(app): never strand a connected pendant without capture or uploads - #22873
Conversation
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]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 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".
| 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)); |
There was a problem hiding this comment.
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 👍 / 👎.
| // 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); |
There was a problem hiding this comment.
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 👍 / 👎.
| if (!_shouldReconnectTranscriptionSocket || _transcriptServiceReady) return; | ||
| if (recordingState == RecordingState.deviceRecord) _socketReconnectPending = true; | ||
| if (!(_keepAliveTimer?.isActive ?? false)) _startKeepAliveServices(); |
There was a problem hiding this comment.
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 👍 / 👎.
| 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 |
There was a problem hiding this comment.
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 👍 / 👎.
| 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; |
There was a problem hiding this comment.
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 👍 / 👎.
| 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); |
There was a problem hiding this comment.
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 👍 / 👎.
…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
There was a problem hiding this comment.
💡 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".
| Future<http.Response> _readMultipartBody(http.StreamedResponse response) => | ||
| http.Response.fromStream(response).timeout(multipartBodyReadTimeout); |
There was a problem hiding this comment.
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 👍 / 👎.
| final codec = await read().timeout(_codecReadTimeout); | ||
| _liveRecovery.codecByDevice[deviceId] = codec; | ||
| return codec; |
There was a problem hiding this comment.
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 👍 / 👎.
| OrphanAudioRoute.sink = _onOrphanAudio; | ||
| lifetime.own(() { | ||
| if (identical(OrphanAudioRoute.sink, _onOrphanAudio)) OrphanAudioRoute.sink = null; |
There was a problem hiding this comment.
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 👍 / 👎.
| _liveRecovery.deviceStoppedByCaller = false; | ||
| if (SyncWakeScope.syncOnly) { | ||
| if (device != null) updateRecordingDevice(device); | ||
| _deferDeviceStartPastSyncPass(); |
There was a problem hiding this comment.
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]>
There was a problem hiding this comment.
💡 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; |
There was a problem hiding this comment.
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 👍 / 👎.
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]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
There was a problem hiding this comment.
💡 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".
| } on TimeoutException { | ||
| _logOperationTimeout('read', characteristicUuid); | ||
| return []; |
There was a problem hiding this comment.
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 👍 / 👎.
…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)
## 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. -->
…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]>
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]>
## 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
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:
deviceConnectedpass.SyncWakeScope, soDeviceProvider._onDeviceConnectedandstreamDeviceRecordingsilently skipped the capture start, and the uplink fence blocked socket and audio opens.transport.cpusher, connected + unsubscribed branch).What changes
1. Capture is never stranded by an upload pass.
periodicwindow (BGTask) still fences live capture. Reconnect and watchdog passes no longer do (RecordingTransferCoordinator.fencesLiveCapture).DeviceProvideralways callsstreamDeviceRecording._inFlight.SyncProvidercancels the abandoned sync, and the coordinator schedules a retry.2. Pendant audio is never silently dropped.
NativeBleTransporthands audio notifications that arrive with no Dart listener toOrphanAudioRoute. These packets were previously dropped by the broadcast controller, because the native GATT subscription outlives capture's listener.omi/firmware/omi/src/lib/core/transport.cpusher). Unsubscribing is therefore not a fallback.3. Live socket recovery.
4. Upload worker.
ConnectivityService.onNetworkChange).cooldownElapsedis accepted in the background. Retries also run in the background, capped at 6 consecutive failures.watchdogwake runs every 10 minutes while recordings are pending and no pass is running.5. BLE timeouts.
NativeBleTransportread and write calls time out after 10 s. A timed-out read returns empty; a timed-out write throws.OmiBleManager: pending reads and writes are queued FIFO per characteristic instead of overwritten, and each fails withTIMEOUTafter 10 s.6. Telemetry.
Capture Recovery Observed, withkind(capture_start_skipped,capture_start_redriven,pendant_audio_orphaned,transfer_pass_timed_out) andtrigger, plus a consumer question.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:recording_transfer_coordinator_test.dartcovers:periodicfencing;native_ble_transport_test.dartcovers read and write timeouts and orphan delivery.Updated tests (these encoded the old contract):
periodic_recording_sync_testnow expects capture after the pass, and bounded background retries.tiered_capture_testandresume_sync_fence_testnow use theperiodicfence.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 -parseonly 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 throughflutter test.Each test asserts two things:
Faults covered:
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
LocalWalSyncImpl.currentCodec).checkWalSupported.ConnectivityService).onNetworkChangeis re-added on top of that version and has a unit test.Review round 2 (Grok) fixes
onAudioCodecChanged, so it cannot race a live start or wipe a session that subscribed in the meantime.dropped) and capture is restarted.catchpath.Review round 3 (Grok): mergeable
Product invariants affected
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