Repository navigation
feat(firmware): pendant ring custody v1 — reclaim only on app ADVANCE, persist while live - #20450
Merged
Merged
Conversation
Preserve packed frames and make live packet boundaries explicit for app-owned reclaim. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Negotiate live persistence per connection and bind reclaim to durable, incarnation-scoped app advances instead of Bluetooth delivery. Order SD batch commits before metadata and cover recovery with native fault tests. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
… 18 and 19+
The Formatting check runs the ubuntu-24.04 default clang-format (18.1.x),
which rejects the cast-space and brace-in-macro style that clang-format 19+
produces (and vice versa), so the new test stubs could not satisfy both.
- Guard the contested BT_GATT_*/BT_UUID_INIT_128/GPIO_DT_SPEC_GET_OR/K_* stub
macros with clang-format off/on regions kept in compact hand-written form.
- Replace the (sd_ring_info_t) {...} reset in test_storage.c with direct
field assignments.
Verified: all 29 changed C files pass clang-format --dry-run --Werror under
both 18.1.3 and 20.1.8; tests/ suites pass (custody 47 checks, sd_card and
storage harnesses 0 failures).
Git-on-my-level
force-pushed
the
lane/ring-custody-fw
branch
from
October 3, 2026 14:48
0520659 to
b6c43ba
Compare
Member
Author
|
Monitor fix for the failed CI's
Verification: all 29 changed C files pass |
Git-on-my-level
added a commit
that referenced
this pull request
Oct 20, 2026
…#22873) ## 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 (#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](https://claude.com/claude-code)
Git-on-my-level
added a commit
that referenced
this pull request
Nov 8, 2026
<!-- claude-projects-attribution: {"github_login":"Git-on-my-level"} -->
_Requested by **David**_
## Status 2026-11-08: verified, ready for release review
All the pre-release gates listed further down have passed. The one left
is David's go. After that, the rollout coordinator handles a staged OTA.
- **Field path proven:** 3.0.21 to 3.0.23 over BLE OTA, on the jig
running the factory 3.0.8 bootloader (the bootloader shipped units
have). Slot1 went to pending+permanent, and after reset slot0 ran the
new image, active and confirmed, with DIS reporting 3.0.23. An earlier
install from an RC start image also passed.
- **Safe mode:** the bench check and all four fault proofs (hard fault,
driver hang, settings hang, watchdog starvation) passed on 6a09d7c. Same
code hash as this head.
- **Host and CI:** firmware host suites, the OTA slot geometry check and
preflight pass. All required CI checks are green. The two red `Analyze`
jobs are CodeQL failing at the SARIF upload step with no alerts. They
aren't required checks and GitHub won't rerun them.
- **Why there is no separate 3.0.22:** safe mode was going to ship alone
as 3.0.22. Its OTA was never proven, because the jig's stock MCUboot
lacks the Omi SD init and erased slot1. Once the jig had the factory
bootloader, the full candidate was proven instead, so safe mode ships
inside 3.0.23.
- **Known telemetry gap:** the boot record decides the update outcome
from the DIS string plus the MCUboot header version, which is 0.0.0 on
every image. So a field unit's first 3.0.23 boot reports UNKNOWN, and a
same-version reinstall reports NOT_INSTALLED. The app's post-reset hash
check stays the authority. A follow-up will switch to image-hash
identity.
- **Still not measured on hardware:** current draw, charger behavior,
and storage after power loss.
Evidence:
`data/run-2026-11-07-cv1-rc/factory-bootloader-install-proof.md` in the
workspace repo. Bench tooling: #24813.
## Update 2026-11-07: safe-mode SD fix, boot telemetry, pinned flash
layout
Four commits on top of the 11-04 head:
- `7a7a6aaa9dd` Safe mode now brings up the SD card before anything
reads the NOR on the shared SPI3 bus. Without that, an uninitialized SD
card drives MISO and corrupts NOR reads. Also adds the persisted boot
record, the saved update outcome, and storage health counters (NOR
read-check failures, SD init failures). These are telemetry items 4-6.
Recovery characteristic `19B10042` moves to v2 (96 bytes, same 16-byte
prefix, version byte 2). `19B10041` is unchanged.
- `481bab7ead1` Docs: `docs/verification/2026-11-07-boot-telemetry.md`,
GATT map.
- `44180c0060a` Hang guard: if SD init hangs and the watchdog fires,
later SAFE boots skip SD init and count a failure instead of looping.
- `6a09d7cbbe5` Pins the app, littlefs, settings and EMPTY_0 partitions
in `boards/omi/pm_static.yml` to the fielded 3.0.21 map. The partition
manager orders the "before: end" partitions in a Python set, so without
the pin the layout depended on the hash seed.
`tests/check_ota_slot_geometry.py` now asserts the pinned map.
Bench evidence on the jig (6a09d7c): the bench check passed, and so did
all four fault proofs (hard fault, driver hang, settings hang, watchdog
starvation). ALL OK at 2026-11-06T22:18:12Z. The jig was restored to
3.0.21 afterwards.
Since proven (see Status above): the jig now runs the factory 3.0.8
bootloader, and a real 3.0.21 to 3.0.23 BLE install passed.
## 3.0.23: merged with safe mode (update 2026-11-04)
This head merges `origin/main` into the backlog candidate. Main now
carries CV1 safe mode (#24505) and its interrupted-update retry fix
(#24514). The version is bumped to **3.0.23**. The original plan was to
ship safe mode alone first, as 3.0.22. That was dropped, and safe mode
ships inside 3.0.23 (see Status above).
- `safe_mode.c`, the retained record layout, the app overlay and the
development-only fault guard match main exactly.
- The replacement SD host joins deferred initialization. The backlog
shutdown worker starts only in normal mode, so SAFE still skips all
application startup.
- **Diagnostics:** the service is registered once, after storage.
`19B10041` keeps the 25-byte telemetry the shipped app parses. Safe
mode's 16-byte recovery state moves to `19B10042`. SAFE exposes only
`42` and Zephyr's static recovery services. `gatt-map.md` matches the
code.
- The merge had seven conflicts: gatt-map, CMakeLists, Kconfig,
diagnostics.h, transport.c, main.c and settings.c. Both sides' behavior
is kept.
- Verified: the host firmware suite and backlog regressions pass, and
preflight passes all 37 checks. Native simulation was skipped because no
Docker daemon was available on the build host.
- **Before any release** (all done except David's go, 2026-11-08):
- An independent review of the merge.
- A build-only CI image of this exact head.
- A normal-mode jig cycle.
- All four safe-mode fault proofs, rerun on this image.
- An app DFU to the jig in SAFE.
- David's go.
## What changed and why
Release candidate for the next CV1 firmware. It combines separately
written PRs so they can be tested together, and fixes what only showed
up once they were combined.
| PR | Author | What it brings |
|---|---|---|
| #24381 (#24137, #19469) | @rgr4y, David | Compiler warning cleanup,
Opus size check, BLE device diagnostics |
| #20450 | David | Ring custody: audio is kept when connected but not
subscribed, and reclaimed only after the phone confirms it |
| #14293 | @apoorvdarshan | Mute survives disconnect and reboot |
| #22659 | @esixce | SD CMD12 reply fix |
| #19719 | David | Per-unit serial number over DIS |
| #13342 | @gianluca-disanto | Audio chunks bounded to ATT MTU |
| #20483 (battery part only) | David | Battery percent doesn't jump on
the charger, and reads correctly after unplugging |
| #23735 (adapted) | @ducanh3005 | BLE power control: resume, pause
capture, power off |
| #23743 (firmware part) | @ducanh3005 | A user-set device name that
persists and advertises |
Also adds `omi/firmware/docs/gatt-map.md`, which assigns each
characteristic UUID to one owner so open PRs stop colliding.
David chose #20450 as the retention fix, accepting that going back to
older firmware loses unsynced audio on the pendant. Release and OTA
publication still need David's go.
**Fixes made on top of the merges:**
- Queued audio could still reach the phone after a mute. A mute now
stops it before sending.
- An unreadable stored mute setting fell back to unmuted, which could
resume capture after a reboot. It now stays muted until an explicit
unmute rewrites the setting. The tradeoff is that a corrupted setting
pauses capture rather than risking recording a user who paused. The app
reads this state back.
- Failed batch media syncs now count as storage errors in diagnostics.
- `check_cv1_mtu.py` passed on its fallback simulation when its compile
failed. A compile failure now fails the check, and only a missing
compiler falls back.
- New `check_ota_slot_geometry.py` keeps OTA slots at the addresses in
every recorded baseline build. It fails on #13855's map.
**Changes from the original PRs:**
- #20483 keeps only the battery fix. Its new diagnostics characteristic
is out, because the existing 25-byte diagnostics packet already covers
this. Diagnostics now report the uncorrected ADC voltage, while critical
shutdown still uses the corrected one.
- #23735 moves from UUID `19B10014` to the allocated `19B10016`, and
from feature bit 9 to bit 11. Pause now uses the same persistent mute as
`19B10015`, so a disconnect or AAD wake can't clear it. Sampling may
continue while paused, with sending and storage both stopped, so this
pause doesn't promise a power saving. A write acknowledges that shutdown
was queued, not that it finished.
- #23743 keeps only the firmware. Its app changes don't apply on this
base, so no app can set a name yet. A name now loads only from a
complete NVS record, and Bluetooth RX can't change it during an
advertising update. A new name takes effect after disconnect, because
advertising is off while connected. The name also moves from the
advertising packet to the scan response, so a passive scanner won't see
it.
**Left out:** #13855, merged and then reverted here. It shrinks both OTA
slots from `0xf0000` to `0xe8000` and moves external network staging and
settings. MCUboot compiles its slot addresses in and OTA doesn't replace
it, while mcumgr uses the app's map. So from reading the design, an app
on that map would write later images and upgrade trailers where the
installed bootloader doesn't look, and OTAs would stop applying.
Settings would also move from `0xfc000`, losing bonds and mute on
update. This hasn't been reproduced on hardware. Generated baseline
builds already end the app at `0xf6000`, below littlefs and settings, so
#5400 needs a fix that keeps the slots where they are.
Also left out: #12102, because #20450 already keeps audio when the clock
is untrusted and its test doesn't link on this branch. Also #14156, held
because it keeps the mic on while connected and that battery cost hasn't
been measured, and #20838 (the retention alternative), #12943 and
#14240.
## Product invariants affected
- INV-CAP-1
This changes what happens to audio while connected but not subscribed,
which is the invariant's main case. Custody host harnesses pass, and the
RC ran on hardware through BLE install and safe-mode fault proofs.
## How it was verified
At `2810eaf`, this head, from a clean clone on the bench Mac, with no
device access:
- `quick-host` and `compile-only` against pinned NCS 2.9.0 pass.
- Host regressions and the OTA slot geometry check pass. The geometry
check also fails on #13855's map, as intended.
- The mute test passes, including new cases for an unreadable setting.
- Custody `make run` passes: `sd_card` and `storage` harnesses report 0
failures.
- The MTU check passes 15 of 15 on the production C seam.
An independent review covered how the merged PRs interact; its three
findings are fixed above. It was a static read and ran no tests.
At the merge of #20483, #23735 and #23743, on the bare CV1 board on the
jig: one app-only cycle passed. The exact image CI built at `07f3866`,
this head, also passed one (build-only run 41523746903, nothing
published). It flashed and verified this image, ran the 30-second boot
check, then restored and verified baseline 3.0.21. The generated slot
map matches the baseline. The same cycle also passed at `2810eaf`. It
proves the image boots and the board can be restored, and nothing about
BLE or audio. Host tests for all three additions pass, and their merge
compiles, links and signs for the real target.
**Not verified at that point (11-04):** anything on hardware beyond that
boot. BLE, GATT, OTA and safe-mode recovery have since been verified
(see Status above). Still open: the new power-off path, renaming,
charger behavior, storage after power loss, the v1 to v2 media upgrade,
and current draw. Going back to pre-#20450 firmware orphans unsynced
audio on the pendant.
## Tests
`omi/firmware/omi/tests/`: custody, `sd_card`, `storage`, capture mute,
OTA slot geometry and host regressions, plus
`omi/firmware/scripts/check_cv1_mtu.py`.
## Failure class
Carried from #14293, which brings these app changes:
Failure-Class: new
Failure-Class-ID: FC-device-mute-cleared-on-disconnect
Line-Count-Exception: app/lib/services/capture/capture_controller.dart |
4609 -> 4670 | Keep durable pendant mute confirmation in the existing
capture owner; unrelated ownership extraction is outside this privacy
fix.
Line-Count-Exception: app/lib/services/capture/capture_coordinator.dart
| 2964 -> 3017 | Confirm device mute before local policy and restore
winning hardware intent on supersession in the existing serialized
owner.
## UI evidence
UI-Evidence: none -- firmware only; the app changes come from #14293 and
aren't exercised in this PR's verification
🤖 Generated with [Claude Code](https://claude.com/claude-code)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Draft only. Do not merge or create a firmware release. The parallel app custody PR must merge first, and the app lane must reconcile the precise live-boundary and timestamp clarifications below with
app/lib/services/wals/PENDANT_RING_CUSTODY.md.Firmware version: 3.0.21 → 3.0.22 for the current Omi CV1 pendant. Changes are confined to
omi/firmware/omi/; there are no app, backend, devkit, or workflow changes.Bluetooth delivery is not durable phone custody. This change removes bulk-send checkpoint reclaim on send completion, DONE, and disconnect. Ring space is reclaimed by explicit app ADVANCE/CLEAR, except for the unchanged overwrite-oldest policy when full. ADVANCE is serviced between READ chunks and is idempotent for seq ≤ read_seq; seq > write_seq still returns status 10. Status/free-space caches follow committed ring state, not bytes delivered over BLE.
INFO is exactly 41 bytes: its original 31 bytes, caps 0x0F at byte 31, version 1 at byte 32, and ring_id u64 BE at 33–40. The control buffer fits it, the configured TX MTU is 498, and INFO waits for negotiated ATT MTU ≥44 rather than truncating (bounded 5-second wait, status 9 on timeout).
CMD_CUSTODY_ENABLE(0x14) negotiates live persistence per connection. Old subscribed apps do not persist live audio. Opted-in apps persist alongside live BLE through the async SD queue, with live sends before packing/enqueue and K_NO_WAIT writes. Disconnected and connected-but-unsubscribed capture persists. Storage failure does not stop live BLE; counters distinguish queued records from dropped records/frames. Marks are emitted only after batch durability and validated against the live grant and ring incarnation.Random, nonzero hardware-RNG ring_id is persisted in CRC-protected v2 metadata.
CMD_RING_ADVANCE_ID(0x15) compares incarnation and advances atomically in the SD worker; mismatches return status 11 without reclaim. CLEAR/fresh metadata/sequence-invalidating recovery rotate ring_id. Ordinary reboot, write, advance, and overwrite retain it. Legacy metadata/batches migrate without intentionally clearing audio. A private data-lineage ID permits retained batches to remain readable after a public ring_id recovery rotation. Blank/formatted replacement media is the fresh-metadata path; CV1 has no separate format/factory-reset command in this tree. Legacy clear/delete aliases route through the same CLEAR operation.Every committed batch now follows data write → successful media sync → metadata write → successful media sync. Failed commits do not announce a new write_seq or live mark. An uncertain metadata sync must resolve its exact pending state before newer mutations; full dirty batches and queued shutdown writes are retained for retry. This is batch-level ordering, not fsync per frame. Power-off does not proceed when the write drain or media sync fails.
Contract clarifications / amendments for the app lane
Opt-in and ACK, no opcode/layout divergence: send
[0x14, 0x01, requested_caps]after each connection. Success ACK is[0x01, 0x00, requested_caps & 0x0F]. Only bit 0x02 enables live persistence; other advertised caps apply unconditionally. Reserved request bits are ignored. Wrong length/version returns status 6 without changing the grant. Connect/disconnect/transport shutdown revoke the grant, and a repeated enable invalidates marks from the previous grant. INFO advertises supported caps, not a connection's current grant.Exact live_index definition: the unchanged audio header is
[packet_index u16 LE, fragment_index u8, fragment bytes]. packet_index increments once per BLE fragment; fragment_index restarts at zero for each Opus frame.live_indexin[0x06, ring_id u64 BE, ring_seq u64 BE, live_index u16 BE]is the exclusive next fragment counter after the final fragment of the last Opus frame included in the committed record prefix, modulo 65536. It is not a frame count. The next frame need not have arrived yet. Multiple variable-size Opus frames fit in one 440-byte audio payload, with a reserved zero padding byte for the old parser. An overflow closes the previous record with the previous frame's boundary, not the triggering frame's boundary. All covered fragments were successfully queued on audio before their record entered the SD queue and before its mark is queued. The app must durably flush all complete frames strictly before this exclusive boundary, detect missing fragments, and interpret wrap relative to its packet history.Safe-prefix amendment to section 3's “whenever a ring record is committed”: a mark is suppressed while its prefix would include unread offline, mixed-session, unsubscribed, or failed-live-send records. Those records need READ plus durable app ADVANCE first. Only a contiguous run of successfully queued live frames on one grant, with earlier non-live records already reclaimed, can authorize a live prefix. Suppression or a dropped mark means retain/re-download; it never authorizes skipping a gap. The wire format and existing app durable-before-advance rule are unchanged. Do not assume mark cadence is a fixed 3–4 seconds: batching/partial drains/INFO can change cadence.
RTC timestamp amendment: the unchanged 4-byte BE record timestamp uses
0x80000000asOMI_TS_FLAG_UPTIME. When set,timestamp & 0x7FFFFFFFis seconds since this boot at SD-worker dequeue, not UTC; it must never anchor a WAL as epoch time. Unflagged UTC is used only with a valid RTC and a value in [1700000000, 2147483647]. New apps must check the flag even when the device's current RTC is valid, because earlier records can predate clock sync. Flagged uptime cannot identify a boot on its own; use receipt-time/duration fallback when wall-clock placement is unprovable. UTC beyond the signed-31-bit range also uses flagged fallback. Old apps can still parse the record framing, but an old app may misdate flagged records if the RTC becomes valid before sync; this compatibility limit needs hardware/app-lane confirmation before merge.The capability promise excludes the explicitly retained overwrite-oldest behavior: ring-full loss still increments dropped. No new stop-on-full policy is introduced.
Compatibility matrix
Verification
make -C omi/firmware/omi/tests run: three native binaries pass. The pure production helper has 47 checks; SD and storage harnesses compile productionsd_card.candstorage.cagainst fake hardware, covering commit ordering/failure injection, uncertain CLEAR, metadata migration/recovery, retained audio, exact overwrite accounting, opt-in/epoch rejection, active READ/ADVANCE, interrupted READ, INFO layout, and MTU gating.clang-format --dry-run --Werroron changed C/H, including host stubs: passes.git diff --check: passes.make preflightandscripts/pr-preflight --pr-body-file .agent-briefs/pr-body.md: both pass all 14 selected checks. The local gates required a canonical macOS TMPDIR and removal of inherited production ADC from the test process environment; no repository policy or code was bypassed.052065999d(NCS 2.9.0 Docker/sysbuild, Omi CV1 nRF5340). Artifact:Omi_CV1_v3.0.22. The release guard/token/release steps were all skipped. Dispatched onlane/ring-custody-fwwith no release input; no release was created. No local west/toolchain is installed.Manual hardware test plan (required before merge)
Use a CV1 pendant with this build and compare INFO/read_seq/write_seq/ring_id/dropped with the app's durable WAL files. Capture distinguishable spoken time markers; assess playback/transcription, not just successful ACKs.
Open questions / merge gates
Product invariants affected
none (no registered INV-* path citation is selected for these firmware-only files). The binding product requirement is explicit durable app custody before reclaim, subject to the ring-full exception described above.
Failure-Class: none
Generated with Devin