Skip to content

fix(firmware): retain offline audio without trusting restored RTC time - #12102

Closed
Git-on-my-level wants to merge 6 commits into
mainfrom
fix/firmware-rtc-offline-storage-surfacing
Closed

Git-on-my-level wants to merge 6 commits into
mainfrom
fix/firmware-rtc-offline-storage-surfacing

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Aug 23, 2026 •

Copy link
Copy Markdown
Member

Summary

After power loss, the last persisted epoch can be hours or days stale. CV1 currently restores it as valid and writes plausible-looking UTC to offline audio until the next phone sync. This draft separates time-base availability from recording-time trust and retains audio in every clock state.

Extends this RTC-themed draft #12102 after merging origin/main (initially 34b3396; refreshed to 933b2f1 before publication) into fix/firmware-rtc-offline-storage-surfacing with a merge commit. The original rate-limited diagnostics and nonblocking worker summary remain useful, but now count packets retained with untrusted time, rather than packets discarded for lack of sync. Firmware only; no app/backend, version, OTA or release-workflow changes. Keep draft for David's hardware validation.

Design

  1. rtc_is_valid() keeps its existing meaning: an epoch base exists, restored or synced. rtc_is_trusted() means the phone has synced this boot.
  2. Settings restore and IMU boot adjustment establish only a diagnostic clock. The IMU setter is explicitly named rtc_restore_utc_time_ms(); neither restore path can establish trust.
  3. rtc_get_record_timestamp() samples trust and the epoch together under the RTC mutex. Trusted epochs in [1700000000, 2147483647] retain their existing wire form; every other state emits bit 31 plus low-31-bit seconds since boot.
  4. SD recording has no RTC/floor early return. Unset, restored, invalid-range and synced clocks all append the same 440 audio bytes. Existing queued/batched records are never rewritten when sync arrives.
  5. Storage status reports live trust (0 after restore, 1 after phone sync); flagged compatibility filenames carry zero/missing time rather than a fake epoch.

The shared timestamp primitive owns both provenance and range selection; call sites do not combine a separate trust check with a later time read. No clock-state capture gate or default-off flag is introduced.

Consumer audit

Consumer Result
rtc.c: all utc_valid reads/writes, epoch getters, restore and phone setter Availability semantics preserved; separate boot-local trust and atomic recording timestamp API added. Diagnostic epoch persistence/getters/formatter remain available.
imu.c / imu.h: boot adjustment Renamed millisecond setter to the explicitly untrusted restore API. The system-off rtc_is_valid() gate and diagnostic epoch persistence remain unchanged.
sd_card.c::process_write_data_req() Removed both clock-based discard gates; stamps through the shared recording API. Rate-limited retained-untrusted counter and best-effort sync summary stay SD-worker owned.
sd_card.c::format_timestamp_name() (both current-name and readback callers) Flagged record timestamps map to 00000000.txt, representing missing time. Unflagged names retain their format.
storage.c::storage_read_characteristic() RTC-valid wire field now reads rtc_is_trusted() live. Removed its obsolete cached atomic and cache-set writer.
main.c: LED warning and startup log Existing rtc_is_valid() availability checks unchanged; neither gates capture nor supplies record time.
transport.c: time write/read Phone write remains the sole trusted setter; GATT time read remains diagnostic. No transport/custody changes.

There is no separate timestamp-marker stream in the current CV1 SD writer: the four-byte BE record prefix at the former line 698 is the timestamp. It now carries the existing untrusted/uptime flag; legacy filename timestamps are suppressed to zero. The current ring parser RingProtocol.readRecordTimestamp() returns 0 for flagged records (also supported by rust-sdk #22481). The legacy audio parser ignores the four-byte prefix, preserving payload framing. No new marker parser is needed.

Related PRs and integration

Product invariants affected

  • INV-CAP-1 — clock state must never discard, pause or skip sampled audio. Both RTC discard returns are removed; the host harness commits and reads back every payload across unset, restored, synced and invalid-range states. Existing unrelated queue/media/ring-full limitations are not a new zero-loss guarantee.

Failure-Class: FC-recovery-time-used-as-event-time
UI-Evidence: none -- firmware only

Verification

  • make -C omi/firmware/omi/tests/clock run — PASS. Compiles production rtc.c, sd_card.c and storage.c against host stubs; all 10 payloads commit/read back intact across unset/restore/IMU/sync/bad-clock transitions, GATT trust changes without cache refresh, and 50,000 concurrent timestamp reads never expose a restored epoch as trusted.
  • make -C omi/firmware/omi/tests/clock run BUILD_DIR=build/sanitize CFLAGS='-std=c11 -Wall -Wextra -Werror -Wno-unused-parameter -Wno-unused-variable -pthread -fsanitize=address,undefined -fno-omit-frame-pointer' — PASS; no ASan/UBSan reports.
  • make preflight — PASS, all 12 selected local checks, with this PR body supplied through OMI_PR_BODY_FILE.
  • scripts/pr-preflight --pr-body-file /Volumes/Ephemeral/scratch/firmware-restored-clock/pr-body.md — PASS, all 12 selected checks.
  • clang-format 18 --dry-run --Werror on changed C/H (including stubs), and git diff --check — PASS.

Tests/builds/preflights ran through the workspace bin/omi-heavy. Host tests exercise production logic with fake hardware; they are not a Zephyr/nRF build or on-device acceptance. The host's default clang-format 20 rejects the existing C++-only config for .c files, so formatting and hooks used installed LLVM 18, matching repository CI. Initial harness link failures were missing fake GPIO/subscription functions; the completed harness passes.

The documented NCS 2.9.0 toolchain is unavailable locally: west is absent from PATH and docker info fails because no Docker daemon is running. No nRF5340 firmware build/compile claim. No release workflow was dispatched, no device flashed, no production data or GCP accessed.

Hardware acceptance for David (required before ready/merge)

  1. Sync a CV1 pendant with the phone; capture distinguishable spoken time markers. Power off for more than 10 minutes (also test a day-long gap), then boot and record offline before reconnecting.
  2. Before phone sync, inspect status: RTC-valid field must be 0, records must carry bit 31 with uptime in the low bits, and no stale restored epoch/marker may anchor audio. Verify every expected spoken marker and audio duration survives download; inspect the resulting app clock run/conversations, not just ACKs.
  3. Reconnect and sync time while recording. Status must become 1 immediately; subsequent records must carry correct phone UTC. Earlier flagged records must remain flagged, including within a mixed batch; verify no audio gap at the transition.
  4. Repeat after settings wipe/no prior epoch, software reboot, and system-off/IMU wake. IMU adjustment must not make time trusted before phone sync.
  5. Reboot with synced and untrusted backlog, then download with the current app. Verify estimation/run separation prevents cross-day merging and no audio is dropped because of clock state. Confirm normal already-synced recording still has accurate UTC.

Open questions / limits

🤖 Generated with Claude Code

Implemented-By: codex gpt-5.6-sol
Co-Authored-By: Claude Fable 5 <[email protected]>
@Git-on-my-level
Git-on-my-level requested a review from TuEmb as a code owner August 23, 2026 17:53
The hook's callers are the BLE GATT RX thread and the system workqueue;
a 500ms blocking put on a full priority queue would stall both for a
best-effort log message. Matches sd_notify_ble_state's pattern.

Review-Swarm: glm-5.3 x4 (concurrency, build, field, kconfig lenses)
Co-Authored-By: Claude Fable 5 <[email protected]>
@Git-on-my-level

Copy link
Copy Markdown
Member Author

Adversarial review swarm (4× glm-5.3: concurrency / build / field-failure / kconfig lenses) — results:

All reviewers: SHIP, no blockers. Findings acted on or noted:

  • Fixed in 77cde506ab: the REQ_TIME_SYNCED enqueue used k_msgq_put(..., K_MSEC(500)), but the hook's callers are the BLE GATT RX thread (transport.c:264) and the system workqueue (rtc.c:32) — a full priority queue during an SD stall would have parked either for 500ms for the sake of a best-effort log line. Now K_NO_WAIT, matching sd_notify_ble_state. (Flagged independently by two reviewers.)
  • Known limitation (deliberate, worth stating): production builds set CONFIG_LOG=n (omi.conf:168), so the added warnings are compiled out on fleet devices — this PR gives observability on debug/bench builds and CI, not OTA telemetry. Surfacing the drop counter to the app over BLE was deliberately kept out of scope; it can be a follow-up if fleet visibility is wanted.
  • Minor edge (accepted): a phone syncing a pre-2023 epoch keeps rtc_is_valid() true while writes fail the RAW_MIN_VALID_UTC_TIME floor; the drop warning then says "never synced" and the summary/reset is suppressed by the same floor guard. Requires a badly misconfigured phone clock; self-limiting via the power-of-two rate limit.
  • Verified clean by the swarm: enum renumbering safe (no default: cases, type never persisted/serialized), counter strictly single-writer on the SD worker, no init-order hazard (K_MSGQ_DEFINE is link-time; boot RTC restore doesn't fire the hook), watchdog unaffected, clang-format/CI lint pass, devkit app unaffected.

🤖 Generated with Claude Code

@Git-on-my-level

Copy link
Copy Markdown
Member Author

Monitor fix — Hygiene failure-class-protocol failure resolved (no code changes):

  • Root cause: both commits use fix(firmware): subjects but the PR body carried no Failure-Class: declaration, so the failure-class-protocol check failed with missing_declaration.
  • Fix: added a ## Failure class (fixes) section declaring Failure-Class: none to the PR body, then re-ran the failed Hygiene job → success. Verified locally with scripts/failure-class validate before editing (old body FAIL / new body passes the declaration check), and re-read the body from the API after the edit.
  • Why none: the registry (139 classes at this head) has no firmware/RTC/SD-surface or silent-discard class; this PR is deliberately scoped as observability-only, and minting a new class here would expand it into a registry-lifecycle change, which belongs in a separate PR per AGENTS.md.
  • State: no failing or pending checks remain on 77cde506; the PR is now blocked only on required review. No review threads were open, so none were resolved or rejected.

@Git-on-my-level

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@Git-on-my-level
Git-on-my-level marked this pull request as draft August 27, 2026 19:54
@Git-on-my-level

Copy link
Copy Markdown
Member Author

Need to make this PR useful by shipping from device -> app -> cloud first before merge

Separate restored diagnostic time from phone-synced recording time. Use flagged uptime records without clock-based capture drops and report live trust in storage status. Retain the draft RTC diagnostics as stored-untrusted counters.

Failure-Class: FC-recovery-time-used-as-event-time
@Git-on-my-level Git-on-my-level changed the title fix(firmware): log and count offline-audio drops while RTC is unsynced fix(firmware): retain offline audio without trusting restored RTC time Oct 21, 2026
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)
@Git-on-my-level

Copy link
Copy Markdown
Member Author

Closing as part of a stale-PR cleanup David asked for on 2026-11-26 (Shipping lead agent): it is a draft with no activity for days. Nothing is lost: the branch stays, and anyone can reopen this PR if the work is still wanted. If it still matters, reopen it and refresh it against main.

@github-actions

Copy link
Copy Markdown
Contributor

Hey @Git-on-my-level 👋

Thank you so much for taking the time to contribute to Omi! We truly appreciate you putting in the effort to submit this pull request.

After careful review, we've decided not to merge this particular PR. Please don't take this personally — we genuinely try to merge as many contributions as possible, but sometimes we have to make tough calls based on:

  • Project standards — Ensuring consistency across the codebase
  • User needs — Making sure changes align with what our users need
  • Code best practices — Maintaining code quality and maintainability
  • Project direction — Keeping aligned with our product principles and locked invariants

Before your next PR, please skim:

  • PRODUCT.md — product north star
  • Product invariants — locked rules (shared chat, memory tiers, agent control plane, integrations, brand)

If this was declined for direction or taste, maintainers should cite an invariant ID or open a proposed one — ask if that citation is missing.

Your contribution is still valuable to us, and we'd love to see you contribute again in the future! If you'd like feedback on how to improve this PR or want to discuss alternative approaches, please don't hesitate to reach out.

Thank you for being part of the Omi community!

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