Skip to content

fix(app): flush pendant custody writes before tests delete storage (#20500) - #20638

Merged
kodjima33 merged 6 commits into
BasedHardware:mainfrom
sanjayJ369:fix/custody-test-drain-20500
Oct 7, 2026
Merged

kodjima33 merged 6 commits into
BasedHardware:mainfrom
sanjayJ369:fix/custody-test-drain-20500

Conversation

@sanjayJ369

@sanjayJ369 sanjayJ369 commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

What changed and why

Fixes #20500. The issue cites four CI failures. The CI logs show two different causes, and this PR fixes both.

1. Custody writes outlive test teardown (main at 0c00747665, and PR #20497 run 37147694253). Ring-custody checkpoint writes are serialized on PendantRingCustody._saveQueue and PendantCustodyStore._ioQueue. Live marks persist lazily on each open session's mark chain. Mismatch invalidation, ring reincarnation and live marks persist without awaiting, and nothing let a caller wait for those writes. Tests deleted their custody directory after a fixed 50 ms _settle(). Under CI load a queued .json.tmp → rename then ran after teardown and failed the suite with PathNotFoundException "after test completion".

  • PendantCustodyStore.flush() completes once the I/O queue is idle, re-checking for work queued while it waited.
  • PendantRingCustody.flush() waits on the checkpoint queue, every open session's mark chain and the store. It repeats until neither the checkpoint queue nor any mark chain changed while it waited.
  • Both are additive. No production caller changes.

2. Fixed sleeps in two tests (PR #20497 run 37150132070 attempt 1, and main at 4e938058d9, run 37145070911). Neither failure was a custody write, so flush() alone could not fix them.

  • ring_custody_download_test.dart, "CAP_APP_ACK_RECLAIM: incremental advance fires on each durable chunk…", failed with Expected: >= 1, Actual: <0>. It counted advances after a fixed 300 ms sleep. Under load the first chunk was written about 235 ms after the read started. The advance that chunk triggers comes only after the checkpoint persist and proof validation, and it had not reached the card when the sleep ended. The fake card now completes a future on its first advance. The test waits for it (bounded at 10 s) before it sends the last records and DONE, so the advance it counts is still mid-transfer.
  • pendant_custody_main_red_test.dart, "pendant BLE frames drain to disk within the 10s custody window", failed with Expected: non-empty, Actual: []. It fired the drain timer's callback, dropped the returned Future, and read the WAL index after a fixed 300 ms sleep. The failed expectation skipped sync.stop(), so teardown deleted tempDir under the still-running WalFileManager._saveWals. That caused a second failure "after test completion" on wals.json.tmp. The test now drives its timers with the existing ManualScheduler: it elapses the 10 s window and awaits waitForCallbackIo(), which completes once the drain, its audio write and the index save have finished. The body runs in try/finally with await sync.stop(). stop() queues behind any drain still running on LocalWalSyncImpl._bufferQueue, so no index write outlives tempDir even when an expectation fails.

Changed suites:

Suite Change
pendant_ring_custody_flush_test.dart (new) 8 tests pinning flush() (below).
omi_ring_custody_test.dart The replay and rejected-opt-in tests end the session with disconnect(), flush every custody they built, then delete. The disconnect test flushes in finally.
ring_custody_download_test.dart tearDown flushes every custody before removing the path_provider mock. The CAP_APP_ACK_RECLAIM test waits for the first advance instead of sleeping.
pendant_custody_main_red_test.dart tearDown flushes PendantRingCustody.shared. The 10 s window test awaits the drain through ManualScheduler and stops the sync in finally.
pendant_ring_custody_test.dart tearDown flushes every custody a test built. The u16-wrap test ends its session in addTearDown, which drops its ~3300 queued mark persists.
local_wal_live_custody_test.dart tearDown flushes every custody manager() handed out.

Product invariants affected

none

How it was verified

Unless noted otherwise, every run below used head ac9a46070b with Flutter 3.44.5 (Dart 3.12.2), the version CI uses. The machine has 8 cores and was under a load average of about 11 to 14 from other work. Earlier revisions of this description reported results from d15a282c. That was before flush() gained the store re-check and mark-chain wait, before two more suites changed, and before the timing fixes. The results below replace them.

  • The two timing fixes: ring_custody_download_test.dart and pendant_custody_main_red_test.dart (9 tests), run 5 times in each CI time-zone lane (UTC, Pacific/Kiritimati, Pacific/Pago_Pago). 15/15 runs passed (+9: All tests passed!). No log contains PathNotFoundException or a failure "after test completion".
  • Related sweep: the 28 app test files that import pendant_ring_custody.dart, local_wal_sync.dart, ring_storage_sync.dart, omi_connection.dart or wal_file_manager.dart, run once per lane. This includes all six changed suites and the new flush test. Each lane: +341 ~9: All tests passed!, with no PathNotFoundException and no failure "after test completion". The only custody "persist failed" line is the existing reincarnation persist failed for omi-1: Binding has not yet been initialized. from the untouched omi_ring_custody_test.dart "a lost ENABLE ack keeps ring-id custody" test, which also appears on main and in PR fix(app): load the app catalog on Integrations when apps came from the cache #20497's CI log.
  • Slow I/O makes the old tests fail and the new ones pass. The old versions passed 5/5 here at that load, so ambient load did not reproduce the CI flake. I added a temporary, test-only delay instead: 400 ms in the download test's proof validator, and 500 ms before each WAL index save in the 10 s window test. Both tests at 5b448a974b then failed with the same assertions as CI, Actual: <0> and Actual: WhereIterable<Wal>:[]. The follow-on "after test completion" error did not reproduce locally. Both tests on this head passed, and so did the whole 10 s window file (+3).
  • The new waits still catch real breakage. I made each production change temporarily and reverted it:
    • With the incremental advance disabled in ring_storage_sync.dart, the CAP_APP_ACK_RECLAIM test fails at the 10 s bound with Expected: >= 1, Actual: <0>.
    • With _drainPendantTail skipping its _flush, the 10 s window test fails with "pendant frames must reach the disk index…".
    • With the pendant drain timer set to 11 s, it fails with "a pendant drain timer must fire within 10s…".
  • flutter analyze on the 7 touched Dart files: No issues found!. dart format --line-length 120 --set-exit-if-changed: 0 changed.
  • CI logs: I read the logs for all four failures cited in Flaky: pendant ring-custody tests fail after completion when a custody write outlives the test #20500, and they confirm the split above.
    • Both custody failures stack through PendantCustodyStore.saveJson → _File.rename, from PendantRingCustody._persist ← beginConnection.
    • The download failure is a bare assertion on the count taken after the sleep.
    • The 10 s window failure is an assertion, followed by a _File.rename of wals.json.tmp from WalFileManager._saveWals ← LocalWalSyncImpl._flush ← _drainPendantTail.
  • LocalWalSyncImpl.stop() waits for an in-flight drain. Each queued operation chains on the previous one, and _flush awaits the audio write and the index save.
  • git diff --check is clean. check-mobile-changelog.py --base origin/main --head HEAD and mobile-changelog.py validate pass, and scripts/pr-preflight --pr-body-file with this body passes.

Tests

app/test/unit/pendant_ring_custody_flush_test.dart holds the store's directory behind a gate, so a fire-and-forget write is provably pending without sleeps. Its 8 tests:

  • flush() waits for a pending reincarnation write, and for a pending mismatch-invalidation write.
  • flush() waits for a write queued while it was already waiting, and for a checkpoint queued while it waited on the store.
  • flush() waits for live-mark writes still queued on an open session. Deleting the directory after flush() does not recreate it.
  • PendantCustodyStore.flush() waits for I/O queued while it was already waiting.
  • Both flushes complete immediately when nothing is queued.
  • A teardown that flushes leaves the last write on disk and no .tmp file before the directory is deleted.

The two timing fixes are covered by their own tests, which now wait on a completion instead of a fixed sleep. Each still fails if the behavior is missing. With no incremental advance, the count stays 0 after the 10 s bound. With no drain inside the 10 s window, either no timer fires or the index has no disk WAL.

Failure class (fixes)

Failure-Class: new

Failure-class transition narrative (only when needed)

  • Violated contract: a serialized write queue that callers feed without awaiting must expose a completion that covers every queued write, and whoever tears down the storage those writes target must await it first. Otherwise a queued temp-file write and rename runs after its directory is deleted. It then fails after the owning test has passed, or silently recreates storage that was just torn down.
  • Why new: the nearest existing classes have other owners. FC-continuation-resumed-after-unmount is a widget State continuation. FC-run-loop-timer-outlives-owner is a desktop run-loop timer. FC-dropped-derived-future-rethrows-handled-error re-emits an already-handled error. None covers queued storage writes outliving storage teardown.
  • Canonical guard: a flush() on the queue owner, awaited before storage teardown. The pinning test is app/test/unit/pendant_ring_custody_flush_test.dart, and the class file is .github/failure-classes/FC-queued-write-outlives-storage-teardown.json.
  • Evidence for this class:
  • Not evidence for this class: the CAP_APP_ACK_RECLAIM failure (run 37150132070 attempt 1) and the 10 s window failure (main at 4e938058d9) were fixed-sleep timing failures, described above.
    • The 10 s window test's assertion failure matches FC-virtual-idle-before-durable-io: a test fired a timer callback, dropped its Future, and then read durable state. The fix reuses that class's existing guard, ManualScheduler.waitForCallbackIo(). This PR does not change that class's definition.
    • Its follow-on wals.json.tmp error has this class's shape: a queued WAL index write outlived teardown. It ran late only because the failed assertion skipped sync.stop(), and the finally now covers that.

Review in cubic

…asedHardware#20500)

Ring-custody checkpoint writes are serialized on a save/IO queue, and
mismatch invalidation and ring reincarnation persist them fire-and-forget.
Nothing let a caller wait for queued writes, so tests that delete their
custody directory after a fixed 50ms settle raced them: the queued
`.json.tmp` -> rename ran after teardown and failed the suite with
PathNotFoundException "after it has completed" (main and unrelated PRs).

- PendantRingCustody.flush() / PendantCustodyStore.flush(): complete once
  every write queued so far has landed, re-checking for writes queued while
  waiting.
- The three flaky suites end the custody session (disconnect) and flush
  before deleting storage; ring_custody_download_test flushes every custody
  it creates before removing the path_provider mock, and
  pendant_custody_main_red_test flushes the shared custody.
- pendant_ring_custody_flush_test.dart gates the store's directory so a
  fire-and-forget write is provably pending and pins flush() semantics.
@sanjayJ369
sanjayJ369 requested a review from mdmohsin7 as a code owner October 4, 2026 07:33

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 7 files

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

@Git-on-my-level

Copy link
Copy Markdown
Member

Thanks @sanjayJ369 — clean, well-scoped fix for #20500. I verified the code at the PR head; per-file notes:

  • app/lib/services/wals/pendant_ring_custody.dart — the drain-loop shape of both flush() implementations is right: _persist chains saveQueue behind catchError(() {}) and PendantCustodyStore does the same for _ioQueue, so awaiting the queue cannot throw into teardown, and the !identical(queued, _saveQueue) re-check correctly catches writes enqueued while flush was already waiting (including the saveJson that _persist schedules onto the store). Purely additive; no existing caller changes behavior.
  • app/test/unit/pendant_ring_custody_flush_test.dart — the _GatedDirectory gate is a nice touch: the fire-and-forget write is provably still pending instead of relying on timing, and the third test covers the write-queued-while-flush-is-waiting race explicitly.
  • app/test/unit/omi_ring_custody_test.dart — _drainCustody disconnecting before flushing is the correct ordering (once the session ends, no new write can be enqueued). The conn → connection rename in the rejected-opt-in test is harmless churn.
  • app/test/unit/ring_custody_download_test.dart — hoisting each custody into the custodies list before assigning testCustody keeps the tearDown flush coverage complete.
  • app/test/unit/pendant_custody_main_red_test.dart — flushing PendantRingCustody.shared before the path_provider mock is removed addresses the exact failure mechanism (writes resolving their directory through a mock that no longer exists).
  • .github/failure-classes/FC-queued-write-outlives-storage-teardown.json — matches the existing failure-class schema; scope hints point at the right directories.
  • app/changelog/unreleased/20261004-custody-test-flush.json — kind: none is accurate; no shipping app behavior changes.

One non-blocking observation: flush() is currently test-facing only. If the app ever tears down or swaps custody storage at runtime (e.g. account switch), the same write-outlives-teardown hazard exists there — worth keeping in mind, not a change request for this PR.

The stress runs in the description weren't independently reproduced by this review, but CI's reviewer check passes and the mechanism is convincing. Looks ready for maintainer merge consideration.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

@Git-on-my-level Git-on-my-level added flutter flutter work positive-signal Automation verified a genuine fix/quality contribution labels Oct 4, 2026
A checkpoint queued while flush() waited on the store reached the I/O queue
only after its predecessor's save, so flush() could return with it still
pending. flush() now waits on the store inside the checkpoint-queue loop.

The teardown regression test asserted on uncaught errors, but noteInfo
already logs and swallows a failed write, so it passed without flush().
It now checks what reached disk before the directory is deleted, and a new
test pins the store-wait race.
flush() only waited on the checkpoint queue, but an open session's live
marks enqueue their persists lazily on its mark chain, so a test could
flush, delete storage, and have a later mark write recreate it. flush()
now also waits on every open session's mark chain until both are stable.

Every custody test that deletes storage now flushes each custody it built
first: pendant_ring_custody_test and local_wal_live_custody_test leaked
recreated temp dirs on every run. The two wrap tests that queue thousands
of marks end their session so the queued persists are dropped, and the
disconnect test flushes in finally. The flush tests read the checkpoint
from disk synchronously so an early return cannot hide behind the store
queue, and a new test pins the store-level loop.
The u16 wrap test queues about 3300 mark persists; it now ends its session
through addTearDown right after beginConnection, so a failing expectation
does not leave teardown's flush writing them one by one past the timeout.
The two-mark wrap test no longer needs that. A comment now says why
flush() re-checks the mark chains as well as the save queue.

@kodjima33 kodjima33 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

3/5 confidence: real linked bug (#20500) with root cause and new regression test, but diff 382 lines >300 and mergeStateStatus UNSTABLE with no CI run yet -- approve only, do not merge.

Copy link
Copy Markdown
Contributor Author

Ready for full review. Could a maintainer please add the ci:full label? I'll re-run all jobs on the latest commit once it's on. Thanks!


Generated by Claude Code

@Git-on-my-level Git-on-my-level added the ci:full Maintainer-granted: run full CI on this fork PR label Oct 5, 2026
@Git-on-my-level

Copy link
Copy Markdown
Member

ci:full is now on, so the full CI suite should pick up the latest commit (you may need to re-run the jobs as you mentioned). My earlier review on this head stands; nothing new to add since. Thanks for the careful red-first guard test with the gated directory — the write-queued-while-flush-waits coverage is exactly the corner this class of bug hides in.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

…asedHardware#20500)

The CAP_APP_ACK_RECLAIM download test sampled the card's advances after a
fixed 300 ms sleep. Under CI load the first chunk's checkpoint persist and
proof validation had not finished by then, so the incremental advance
landed after the snapshot and the test failed with 0 advances (PR BasedHardware#20497
run 37150132070, attempt 1). This was a timing flake, not a custody write
outliving teardown.

The fake card now completes a future on its first advance, and the test
waits for it, bounded at 10 s, before sending the last records and DONE.
A missing incremental advance still fails the existing expectation.
…rdware#20500)

The 10s custody-window test fired the drain timer's callback by hand,
dropped the Future it returned, and read the WAL index after a fixed
300 ms sleep. Under CI load the index save had not landed by then, so
the test failed with no disk WAL (main at 4e93805). Because that
skipped sync.stop(), teardown then deleted tempDir under the still
running save, which failed again "after test completion" renaming
wals.json.tmp. That is a WAL index write, so the custody flush in
tearDown could not cover it.

The test now drives the timers with the existing ManualScheduler: it
elapses the 10s window and awaits waitForCallbackIo(), which completes
once the drain, its audio write and the index save have finished. The
body runs in try/finally with sync.stop(), which queues behind any
drain still running, so no index write outlives tempDir even when an
expectation fails. The changelog exemption reason now covers both
timing fixes.

@kodjima33 kodjima33 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approve only (confidence ~3/5): real linked bug (#20500, third-party issue) and test added, but diff is 382 lines (over the 300 budget) and no CI checks have run yet.

@Git-on-my-level

Copy link
Copy Markdown
Member

Reviewed the full diff against #20500 — the approach (an awaitable flush() over the fire-and-forget custody write queues, adopted by test teardowns, plus replacing fixed sleeps with awaited completions) addresses both failure causes cited in the issue, and the production change is purely additive with no caller changes.

Per-file notes:

  • app/lib/services/wals/pendant_ring_custody.dart — PendantRingCustody.flush() re-checks both _saveQueue and every open session's markTask after awaiting the store, which closes the race where a mark step chained during the wait has not queued its persist yet (the identical()/_sameFutures re-check is what makes the loop sound rather than lucky). PendantCustodyStore.flush()'s do/while on _ioQueue covers I/O queued while waiting. Both return immediately when idle since the queue roots are Future.value(). I also confirmed noteMismatch()/noteInfo() really are void fire-and-forget persists, so before this PR a caller genuinely had no completion to wait on — the design premise holds.
  • app/test/unit/pendant_ring_custody_flush_test.dart — strong guard coverage: _GatedDirectory makes a pending write provably pending without sleeps, and the tests pin reincarnation, mismatch invalidation, writes queued while flush is already waiting (at both custody and store level), live-mark chains, and the silent storage-recreation variant.
  • app/test/unit/ring_custody_download_test.dart — the firstAdvance completer replaces the flaky 300 ms sleep; the 10 s bound only prevents a hang while the advance-count expectation still fails the test. Teardown flushes the tracked custody before the path_provider mock is removed.
  • app/test/unit/pendant_custody_main_red_test.dart — ManualScheduler/VirtualClock plus waitForCallbackIo() awaits the drain callback's actual I/O instead of a fixed sleep, and moving sync.stop() into finally stops an in-flight drain WAL-index write from outliving tempDir when an expectation fails.
  • app/test/unit/local_wal_live_custody_test.dart, app/test/unit/omi_ring_custody_test.dart, app/test/unit/pendant_ring_custody_test.dart — consistent teardown pattern: track every custody created, flush before deleting storage; _drainCustody disconnects the session first so it cannot enqueue more writes mid-flush. The addTearDown(endConnection) in the u16-wrap test avoids flushing thousands of lazily queued mark persists one by one — good attention to teardown cost.
  • .github/failure-classes/FC-queued-write-outlives-storage-teardown.json — matches the existing failure-class schema and the contract/prevention text accurately describes the fix.
  • app/changelog/unreleased/20261004-custody-test-flush.json — kind: none is correct for a no-shipping-behavior change; accurate since flush() has no production callers yet.

Checks are green (Dart Analyze & Tests, Android JVM Unit Tests, Android Emulator Acceptance, Backend Hermetic Merge Gate). Already human-approved; from the automation side this is in good shape for merge — no blocking concerns. Thanks for the careful diagnosis of the two distinct flake causes and for the sleep-free guard tests.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

@kodjima33 kodjima33 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fix(app): flush pendant custody writes before test teardown — fixes #20500 (flaky CI, filed by mdmohsin7), stated root cause, CI green, tests added. 4/5 confidence (diff slightly over 300-line guideline but scoped to the fix).

@kodjima33
kodjima33 merged commit 636651f into BasedHardware:main Oct 7, 2026
39 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci:full Maintainer-granted: run full CI on this fork PR flutter flutter work positive-signal Automation verified a genuine fix/quality contribution

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Flaky: pendant ring-custody tests fail after completion when a custody write outlives the test

3 participants