Skip to content

fix(app): stat recording inventory files in parallel batches (40 s diagnostics export) - #25525

Merged
Git-on-my-level merged 2 commits into
mainfrom
fix/diagnostics-export-parallel-stat
Nov 16, 2026
Merged

Git-on-my-level merged 2 commits into
mainfrom
fix/diagnostics-export-parallel-stat

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Nov 16, 2026 •

Copy link
Copy Markdown
Member

Problem

A user's device diagnostics export took ~40 s on iOS. The export's own timestamps show where:
ring_custody.local_recording_inventory.started_at_ms → completed_at_ms = 40.6 s, while the pendant reads in the same export took <1 s.

That phone had 164,029 audio files in Documents (9.8 GB; 159,950 unreferenced by any index, tracked separately). captureRecordingInventory listed the directory and then awaited one File.stat() per file. Listing is cheap; the cost is one sequential I/O-service round trip per stat.

Fix

List the directory first, then stat in batches of 64 with Future.wait. Per-file stat failures still count toward file_stat_errors, directory list failures still mark the root unreadable, and the output schema and values are unchanged.

Measurements (164k synthetic files, m5 macOS)

Path Before After
Walk only, plain Dart (idle) 38.5 s 2.9 s
Full captureRecordingInventory under flutter test, host load avg ~70–100 25.3 s 8.2–11.0 s

The phone-side number is not re-measured yet; it needs an export from a build with this change.

Tests

  • New recording_inventory_test.dart case: 199 files (three full batches plus a partial one). Checks audio/regular counts, referenced/unreferenced split, byte totals and zero stat errors.
  • flutter test test/unit/recording_inventory_test.dart: 6/6 pass. flutter analyze on both files: clean.

Product invariants affected

  • INV-CAP-1 (path match only: the inventory is a read-only diagnostics census; it reads metadata and never writes, moves or deletes audio or index files, so retention behavior is unchanged)

Failure-Class: none
UI-Evidence: none

🤖 Generated with Claude Code

View guided diff Turn on auto-fix

Git-on-my-level and others added 2 commits November 17, 2026 02:09
The diagnostics export's recording inventory awaited one File.stat() per
file in Documents. With ~164k audio files on a user's phone, that took
40.6 s of the export (inventory started_at_ms -> completed_at_ms in the
user's export). Listing the directory is cheap; the cost was one
sequential I/O-service round trip per stat.

List first, then stat in batches of 64 with Future.wait. Per-file stat
failures still count as file_stat_errors; output is unchanged.

Measured on 164k files (m5, macOS): walk alone 38.5 s -> 2.9 s in
plain Dart; full captureRecordingInventory under flutter test on a
loaded host 25.3 s -> 8-11 s.

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

chatgpt-codex-connector Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-16T19:16:57.506841Z 294ca78 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

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

@Git-on-my-level
Git-on-my-level merged commit b5bc851 into main Nov 16, 2026
62 of 64 checks passed
@Git-on-my-level
Git-on-my-level deleted the fix/diagnostics-export-parallel-stat branch November 16, 2026 20:13
Git-on-my-level added a commit that referenced this pull request Nov 17, 2026
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).
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