Repository navigation
fix(custody): recover orphan audio with phone-wide upload consent - #25573
Conversation
Failure-Class: FC-phone-durable-pendant-proof
Codex Review Summary: ✅ CompletedThis 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: 3af2f4fe29
ℹ️ 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".
| ..frameSize = info.frameSize; | ||
| // Only Documents files may use the ledger's rebased relative path. | ||
| // Configured native roots remain classified but are never adopted here. | ||
| if (!snapshot.isDocumentsFile(candidate)) continue; |
There was a problem hiding this comment.
Exclude outside-Documents files before reserving recovery budget
When batchAudioDir points outside Documents and contains older recoverable orphans, those files enter the sorted candidate list and consume the persisted daily reservation even though this check always skips their adoption. With at least 200 such files, every pass selects the same unadoptable prefix; two passes exhaust the 400-file daily budget without recovering any eligible Documents files. Filter candidates with snapshot.isDocumentsFile before sorting, applying caps, and reserving budget, while retaining outside-directory files in the classification summary.
Useful? React with 👍 / 👎.
| totalFrames: candidate.frames, | ||
| storage: WalStorage.disk, | ||
| status: WalStatus.miss, | ||
| filePath: path.basename(candidate.filePath), |
There was a problem hiding this comment.
Preserve local-only restrictions when adopting unknown-policy audio
If the app stops after _flush writes a local-transcription safety copy but before it saves the index, that file becomes an orphan with an ordinary filename: onFrameCaptured latches onDeviceOnly and capturedOnDeviceOnly, but neither flag is encoded in the filename. This constructor recreates it with both restrictions unset and status miss, so isAutoUploadEligible now permits cloud upload of audio that the original row explicitly prohibited uploading. A same-owner index containing other recordings is sufficient for the census to admit it. Retain unknown-policy files without automatic upload, or require durable evidence of the original upload policy before creating an upload-eligible row.
Useful? React with 👍 / 👎.
…udio local The live on-device controller can switch to keeping audio on the phone before its persisted preference lands; include it in the automatic-upload hold. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Automatically reclaim stranded Documents audio only with a complete #25573 census, no reference in any index generation, memory bucket, ring, batch journal, owner receipt or held row, and both filename capture time and mtime strictly older than 45 days. Working files stay retained. David’s 2026-11-17 ruling item 2 explicitly permits multi-account phones. Depends on #25573 (merged 2026-11-17 at 14:12 UTC). This lane started from its exact head 80bd311 and targets main. Do not merge this PR. Failure-Class: FC-phone-durable-pendant-proof UI-Evidence: none Line-Count-Exception: app/lib/services/wals/local_wal_sync.dart | 2947 -> 2959 | Wire ledger-owned reclaim test seams and part; deletion remains in its separate part. Line-Count-Exception: app/lib/services/wals/recording_inventory.dart | 519 -> 520 | Import the canonical capture-committed receipt parser for strict off-UI census validation in its existing part. ## Product invariants affected - INV-CAP-1 — add the dated ruling’s explicit aged, entirely unreferenced orphan exception; indexed/held/foreign files remain protected. - INV-PERF-1 — census stays outside capture queue, capped 200/pass with five-file queue turns and yields; bounded synchronous metadata/unlinks close the race, with durable batch checkpoints outside the capture queue. - INV-UI-3 — no UI changes or alarming user flow; aggregate diagnostics only. - `app/lib/services/wals/CUSTODY.md` — one ledger owns deletion, session/admission/foreground fences, tombstone lifecycle. ## Behavior and durability Reuses census/classifier reference proof independently of recovery’s single-owner gate. After durable batch intent and a resolved flag read, rechecks generation, UID, admission, headless/lifecycle, raw legacy preferences, every source/directory stamp, current memory and legacy basename references, file type/size/mtime/ctime and precise age immediately before each delete. No await crosses that fence and unlink. Unknown clocks, symlinks, outside-Documents and changed/incomplete sources retain. More than 512 sources/four directories defer. A non-blocking device-local OS lease serializes reclaim writers. A flushed atomic tombstone ring keeps 200 recent attempts; malformed/oversized state stops reclaim. Pending intent is never replay authority: a restart needs a fresh census and metadata/reference proof. Batch intent is flushed before entering the queue; sidecar precedes audio unlink, with no await from final fences through unlink. Completion is flushed off the queue. Only our synchronous unlink advances the Documents stamp. Aggregate event reports files/bytes deleted, skip reasons and result, with no identifiers. ## Ramp and rollback `orphan_audio_reclaim_off` follows destructive `watch_copy_dedupe`: only resolved false permits deletion. True, unknown and unreadable retain, so this defaults to no deletion until the rollout row resolves false. - Cohorts: David’s device first, then the whole fleet within one week, by **2026-11-24**. - Metrics: census unreferenced count falls by exactly deleted count; missing-recording reports do not rise. - Owner/expander: **mobile custody lead**. The lead enables David’s cohort first and expands by that date after clean evidence. - Rollback: set the kill switch true; deleted bytes cannot be restored. No PostHog configuration is created or enabled by this PR. ## Validation Pinned Flutter 3.44.5 / Dart 3.12.2; hermetic fixtures only; heavy commands run through `/Users/dazheng/workspace/omi/bin/omi-heavy run --` in app/ unless stated. ```sh flutter test --no-pub test/unit/wal_orphan_reclaim_test.dart --reporter expanded flutter test --no-pub test/unit/wal_orphan_reclaim_test.dart test/unit/wal_orphan_recovery_test.dart test/unit/orphan_inventory_contract_test.dart test/unit/recording_inventory_test.dart test/unit/wal_startup_admission_test.dart test/unit/local_recordings_auto_upload_test.dart --reporter expanded flutter analyze --no-pub lib/services/wals/local_wal_sync.dart lib/services/wals/orphan_audio_classifier.dart lib/services/wals/wal_orphan_reclaim.dart lib/services/wals/wal_orphan_recovery.dart lib/services/experiments/orphan_audio_reclaim.dart test/unit/wal_orphan_reclaim_test.dart flutter analyze --no-pub lib/services/wals/orphan_audio_classifier.dart lib/services/wals/wal_orphan_reclaim.dart test/unit/wal_orphan_reclaim_test.dart flutter test --no-pub test/unit/wal_orphan_reclaim_test.dart --plain-name 'legacy Limitless' --reporter expanded flutter test --no-pub test/unit/wal_orphan_reclaim_test.dart --plain-name 'later successful batch' --reporter expanded flutter analyze --no-pub lib/services/wals/local_wal_sync.dart lib/services/wals/orphan_audio_classifier.dart lib/services/wals/recording_inventory.dart lib/services/wals/recording_inventory_sources.dart lib/services/wals/wal_orphan_reclaim.dart lib/services/wals/wal_orphan_recovery.dart lib/services/experiments/orphan_audio_reclaim.dart lib/utils/analytics/registry/events.g.dart test/unit/wal_orphan_reclaim_test.dart # root # dart format -l 120 run on all Lane H Dart source/test files python3 scripts/check_event_registry.py --write python3 scripts/render_feature_flag_registry.py git diff --check OMI_PR_BODY_FILE=/Volumes/Ephemeral/scratch/lane-h-body.md make preflight scripts/pr-preflight --pr-body-file /Volumes/Ephemeral/scratch/lane-h-body.md ``` **Final focused suite: 223 passed. All nine changed Dart files (including generated event output) analyze clean (23.1s).** Format/diff checks pass. Initial committed-tree preflight passed all 35 checks; normal push/preflight/codegen/format gates passed on the first two heads. **Final follow-up head 0a129dd passed the normal push gate: 35 shared preflight checks (38.73s), generated-output validation, and Dart formatting with zero changes.** Before implementation the reclaim suite failed to compile on #25573 because reclaim did not exist. Eight unsafe predicate/order mutations caused runtime assertion failures and were restored. After moving journal fsync outside the queue, removing the asynchronous intent checkpoint again failed three durability tests. Additional before-failing regressions proved that a legacy pending path through a directory alias could lose audio, that malformed capture-committed lists were wrongly complete (three cases), that reclaim did not publish its frame cache, and that an exception plus stop was mislabeled background. Fixed with a precomputed off-UI conservative legacy basename fence, canonical receipt parsing/unknown-field rejection, generation-fenced cache refresh, and honest failure results. The accepted legacy Limitless regression failed before its fix (old unreferenced file retained), and the telemetry regression failed with expected sources_changed / actual completed before its fix. Five legacy-format cases now cover successful reclaim plus capture/mtime/reference/working exclusions. Tests also cover every reference generation/bucket/source, incomplete or missing-memory census, admission/headless/background, unknown/throwing/closing flag, changed/re-referenced files, generation changes, pass cap/census-count delta, outside-Documents files, symlinks, tombstone persistence failures, both crash windows and replacement/new-reference retries. ## Reviews and remaining risk Single scope panel **scope-20261117t134503-0e28** completed with three members. Applied: missing-memory-snapshot fence, independent multi-account/age predicate, separate destructive flag and event, own-directory mutation accounting, bounded queue turns/journal and crash tests. Pending intent never grants replay authority, so a new/replaced file requires a new census; sidecar-first unlink prevents an absent-audio sidecar replay. Retained existing conservative treatment of corrupt sources; rejected suggestions to reset unreadable state, impose single-owner deletion or lengthen the ruling’s age by owner. A separately refreshed census after recovery avoids using reference proof invalidated by adoption; this can repeat cold I/O, and timing remains a device gate. No new daily budget: the requested batch cap/paced wake bounds work without another durable scheduler. Scope reports have no F-number finding IDs; decisions are recorded here. Review round 1: **review-20261117t140935-ff77** on 20d0d1d. Luna and GLM completed; DeepSeek failed with empty_terminal_result and supplied no review. Every finding is CLI-triaged, none missing: F1 accept/fixed (known legacy Limitless timestamp format for reclaim only); F2 accept/fixed (source-fence result cannot reset to completed on later batches); F3 reject (inherited #25573 future-clock recovery-budget hold is deliberate fail-closed availability behavior, outside reclaim scope and unaffected by deletion). Final second panel **review-20261117t144634-ab53** reviewed **a7a7447d6874bd43248c773480be7460e258ca12** and reported **SHIP**, with GLM and DeepSeek answers collected (the latter completed after the collection deadline, before cleanup; no new execution was launched). Luna could not launch because agentctl journal access was busy. All F1–F8 are CLI-triaged, none missing: - F1 accept/fixed: an actual in-pass exception always reports failed, even with a lifecycle fence. - F2 reject: stop synchronously cancels the timer; no await crosses each final foreground fence/unlink. A stop-inside-batch test retains all eight files. Generation changes must not invalidate the existing final capture flush. - F3 accept/fixed: validate each capture-committed row with the canonical parser and reject unknown fields; valid/empty foreign journals still permit multi-account reclaim. - F4 reject: pinned Dart documents exclusive/shared as non-blocking; blockingExclusive/blockingShared are distinct modes. Clarified advisory process scope; OS locks do not serialize isolates in one process. - F5 accept/fixed: publish the census framing cache after the session/complete fences, including when recovery is off. - F6 accept/fixed: remove duplicate source validation, retaining one complete source check immediately before every unlink, as the ruling requires. No source-check hoist across multiple unlinks; device queue latency remains unmeasured. - F7 accept/fixed: assert the actual kill-switch result and zero census calls, plus a complete actual outside-Documents census and its skip reason. - F8 reject: inherited #25573 uniform held-row drain defense is unchanged and outside reclaim scope. Additional implementer finding accepted/fixed: the alias-reference fixture lost audio before the final conservative basename fence. Names are computed once off UI, with O(1) lookup per unlink. This can retain extra same-basename files in other directories, which is intentional uncertainty retention. **Exactly two review rounds. No third review of these final follow-up fixes**, per the requested process limit. Review SHIP applies to a7a7447..., not the final follow-up commit; final changes are covered by the before-failing regressions and clean local validation. Initial-head CI was terminal green. On a7a7447..., Android JVM job 134121342891 in run 44106684811 failed dependency resolution before tests: Maven Central returned HTTP 429 for androidx.test:runner metadata. GitHub refused a targeted job rerun while the parent workflow was still active. Final source head **0a129ddf3473c7f98ac00b4ed57298ddb2d4f66f** starts fresh CI; **pending at handoff**, watched by a bounded ci-wait 25604 monitor plus heartbeat outside the worktree. The monitor verifies the head, exits on first failure/terminal state, and stops its heartbeat when finished. No CI gate was bypassed. Physical-device acceptance, native multi-engine timing, final stat/unlink queue latency and actual reclaimed space/ramp metrics are unmeasured. Journal fsync now occurs before entering/after leaving the capture queue, one checkpoint per five-file batch; final revalidation and unlinks have no await. Recovery retains its existing future-clock budget hold. First-round review coverage is partial because one member failed. This records source/test evidence, not a device or storage outcome. No production account data, GCP tier, deploy or merge. PR #25500 and its branch untouched. ## Final handoff Ready PR, base main, head **0a129ddf3473c7f98ac00b4ed57298ddb2d4f66f**. **223 focused tests pass; nine-file analyzer clean; formatting, all 35 preflight checks and normal generated-output/pre-push gate pass.** The final alias/receipt/cache/telemetry/test-strengthening fixes were not sent through a third review, as requested. All returned findings from both rounds are CLI-triaged with no missing calls. No merge, deploy, production account data, GCP tier or flag enablement. Worktree clean. Source-only result: device acceptance, actual reclaimed storage and ramp metrics remain unmeasured. CI is pending with a bounded monitored waiter; its later outcome does not change the recorded local evidence. ## Final review (lead takeover) Panel `review-20261117t153802-6ffd` reviewed `0a129dd`. Luna and GLM completed. DeepSeek returned an empty result, so it contributed no review. - **F1 (blocking), accepted and fixed:** a reference that differs only in case is now reserved by its case-folded basename, both when building candidates (`recording_inventory.dart`) and in the final pre-unlink check (`wal_orphan_reclaim.dart`). The new regression test `an index reference differing only in case retains the audio` fails before the fix and passes after. - **F2, rejected:** census work is already bounded. It runs in the foreground only, at most once per 15-minute coalesced wake, off the UI isolate. Framing is cached by path, size and mtime, so only the stat walk repeats; #25525 measured that walk at 2.9 s for 164k files. - **F3, accepted and fixed:** torn tombstone JSON reports `journal_unavailable`. The new test fails before the fix and passes after. **Added ramp gate:** before expanding past David's device, measure foreground census and reclaim pass duration there (the `Orphan Audio Reclaim` event plus the debug log). **Verification:** focused suite (wal_orphan_reclaim, wal_orphan_recovery, recording_inventory, wal_startup_admission) 207 passed; analyzer clean. Panel `review-20261117t155959-13cf` (on `00b2683`, Luna and GLM; DeepSeek returned an empty result). All five findings were accepted and fixed: - **F1:** frames are read only for owned files inside the 28-day recovery window, so unowned and expired files cost no audio reads. Reclaim needs only age and references. Unparseable results are cached for 24 h. - **F2:** `duration_ms` is added to the reclaim event and its analytics contract, so the ramp gate can be measured. - **F3:** the commit-time reference check in recovery is case-folded. - **F4:** recovery reports actual failures as `failed`. - **F5:** an unknown result string falls back to `failed` instead of dropping the event. Tests: - New: `unowned and out-of-window orphans are classified without reading audio`. - The scale/cache test now pins the one-day negative cache. - Focused suite: 208 passed. Analyzer clean. The C7 event registry is current. Panel `review-20261117t161835-0ffb` (on `aae8b1f`) returned **SHIP**. - F1 rejected: pre-2024 filename clocks predate any Omi capture, so they are treated as bad clocks and retained. - F2 accepted: the test-only commit adds `one foreground wake runs recovery, then reclaim after recovery settles`. The recovery suite passes (131 tests).
With single-owner proof, recover eligible unindexed phone audio into
miss, oldest first. David's 2026-11-17 ruling permits automatic upload only when no current/backup/tmp/quarantined generation or live/retired/foreign bucket shows local-only/held history, and the account permits cloud upload. Otherwise the recovered row is held for explicit user action. Unknown ownership remains retained and unpublished. This PR never deletes or rewrites audio.Failure-Class: FC-phone-durable-pendant-proof
UI-Evidence: none
Line-Count-Exception: app/lib/services/wals/local_wal_sync.dart | 2909 -> 2947 | Wire ledger-owned recovery, paced foreground wakes and read-only inventory policy flags; recovery/classification remain separate parts.
Line-Count-Exception: app/lib/services/wals/wal.dart | 1324 -> 1345 | Persist a recovered-orphan marker and stable filename-hash identity so same-second files do not share playback/share caches; existing ids and source filenames stay unchanged.
Product invariants affected
app/lib/services/wals/CUSTODY.md— one ledger/uploader, held explicit actions, no orphan deletion here.Behavior
Validation
Head
b6a9647bcb18f63f38f36ca38c2f5ce3a0b44666: 180 focused tests pass; final two-file analyzer clean, with the other 13 PR-changed Dart files unchanged since all 15 were clean; format/diff checks pass; all 34 preflight checks pass (139.78s); normal pre-push/generated-output gate passes. Hermetic fixtures only, pinned Flutter 3.44.5 / Dart 3.12.2. Heavy commands run through/Users/dazheng/workspace/omi/bin/omi-heavy run --.Regressions failed before their fixes: clean-phone automatic policy; durable/malformed STT choices; malformed legacy/ring inputs; seven ambiguous WAL-reference schemas; distinct same-second recovered ids (five files had three ids). Actual index reload now preserves five distinct ids and legacy id stability. Removing the held-budget guard makes its persisted-counter test fail (35 becomes36); the mutation was restored and guard suite passes. Tests also cover all generations/buckets, consent/reference races, real persisted ring envelope, actual delta-worker failure/rollback/durable retry, save/background publication, caps, startup no-discovery, retained bytes and 3,000-file framing-cache reuse.
Reviews
Every returned finding is CLI-triaged. Fresh exact-head review
review-20261117t124527-9387is running on7229be5; CI is separate and running on that head. Do not merge.review-20261117t054947-82dc,review-20261117t074637-8215,review-20261117t082949-9e51: accepted fixes for consent/ownership, framing cache/outside-root filtering, producer suffixes/fresh age.review-20261117t085532-dc2c: SHIP; rollback/export fixes accepted; resetting other-owner reservations rejected.review-20261117t093651-83d9: explicit manual retry was pre-existing, event spelling was style-only; rejected with source evidence.review-20261117t102334-0a22: raw consent, strict ring, raw legacy completeness/revalidation, publication and privacy guards fixed. Resetting unknown/spent quota and treating invalid clocks as expiry rejected.review-20261117t110240-5324: accepted real delta-failure/local-route/ring-store guards and documented archive bound. Legacy optional-false defaults and actual saveJson version envelope verified; phone-wide pacing, cold-I/O and conservative quota retained.review-20261117t114059-3f6b: returned storage/path finding accepted/fixed; second member hit its 35-minute deadline and was cancelled by execution ID. Partial coverage disclosed.review-20261117t121258-b3e9: both answers collected. F3/F4 accepted/fixed (durable per-file id; held budget guard). F1 pruning unknown archives rejected as unsafe; F2 unproven-owner adoption rejected against David's retained single-owner rule; F5 rejected with source lines 468-470, already including active/retired/foreign witnesses. No finding untriaged.Adoption scope
scope-20261117t094122-0ab7found durable STT consent, fixed. Reclaim scopescope-20261117t094355-77d5is complete for the separate stacked PR; deletion is not included here.Risk and rollback
Original-phone acceptance, device-scale timing/cache memory and actual uploads/storage outcomes are unmeasured. Cold/malformed framing costs I/O. Unknown index archives/schemas/preferences can defer or hold recovery; >512 sources defers commit. Malformed budget requires repair; spent reservations age out without zero-reset. Existing preference-quarantine pruning removes archives after seven days, then defined current defaults apply; this creates no permanent unknown-consent marker. Unknown clocks and old/outside-root files remain retained.
Set orphan_audio_recovery_off=true or revert to stop new adoption. Already-admitted rows keep their hold/automatic policy; normal confirmation/retention still governs bytes. No production account read, GCP tier, deployment, merge or physical-device/reclaimed-space claim. PR #25500 untouched.
Latest raw-STT fix tree: 35 additional malformed Omi-config cases failed before this fix. Validate the complete current serialized shape (including nullable text, port, request kind, string maps and response schema); unknown fields or malformed structured data hold rather than granting cloud consent. Valid complete/default Omi configs still auto-adopt. All 180 focused tests pass; final two-file analyzer clean. This accepted finding came from review-20261117t124527-9387; remaining answer/CLI triage and final exact-head re-review follow.
Review review-20261117t124527-9387 completed with both answers; sole F1 raw-config finding accepted and fixed with 35 before-failing regressions and two canonical positive fixtures. CLI triage has no missing findings. Latest pushed head b6a9647; No merge or production access.
Final review (lead takeover)
Panel
review-20261117t132116-87a5reviewedb6a9647. Luna returned one blocking finding: the automatic-upload hold could miss on-device overflow retention during the window before its preference write landed. It was accepted and fixed: the hold now also checksOnDeviceTranscriptionController.instance.shouldKeepAudioLocal, the same pattern the ledger uses atlocal_wal_sync.dart:2058. The change is fail-closed, since it can only hold more files, never upload more. No new unit test was added: the controller is a process singleton with no injection seam in this suite. The DeepSeek member exited with code 2, so there was no review from it.Focused suite (wal_orphan_recovery, wal_startup_admission, recording_inventory): 142 passed. Analyzer clean. This is the ninth panel round on this PR; every finding is triaged.