Skip to content

harden(app): route capture timers, streams and listeners through CaptureLifetime - #14549

Merged
Git-on-my-level merged 49 commits into
mainfrom
task/msd-core-c1-disposal
Sep 18, 2026
Merged

Git-on-my-level merged 49 commits into
mainfrom
task/msd-core-c1-disposal

Conversation

@Git-on-my-level

Copy link
Copy Markdown
Member

What changed and why

C1 cut (3): CaptureController now owns a CaptureLifetime wrapping the injected scheduler, so every _scheduling.once / periodic, the constructor connectivity listen, BLE finalized/stream subscriptions, and CaptureProvider's live-segment addListener cancel when dispose runs. The first commit restores the two why-comments removed to hold 2,710 lines (mute restore; custom-STT buffering UI) and pays for them with BleBridgeCaptureListeners. Production no-argument defaults stay.

This is the first C1 cut that changes behavior on purpose: the 15s voice-command timeout used to survive dispose and could still fire. It no longer does. Evidence class: 05c43c014d (late timer after teardown), 348d5f31dc (_bleButtonStream leak — already cancelled in dispose; now bag-owned so it cannot regress).

Stacked on the composition tip (task/msd-core-c1-composition / forthcoming PR stacked on #14361). origin/main does not yet contain #14361. capture_controller.dart shrinks 2710 → 2698.

No spine markers retired: remaining C1 contracts are generation/join, adoption, FGS, persistence — not this dispose drain.

Resource inventory (capture_controller.dart / capture_provider.dart)

Resource Lines Cancelled on dispose before? This PR
_keepAliveTimer (_scheduling.periodic 15s) field 107; create 1997; pause-cancel 2680 yes bag (_scheduling is the lifetime)
_inProgressConversationRefreshTimer field 112; create 2116 yes bag
_autoSyncFallbackTimer (30s ConversationEvent fallback) field 466; create 2252 yes bag — class of 05c43c014d
_voiceCommandTimeoutTimer (15s) field 518; create 966 no bag — the leak this cut closes
connectivity _connectivity.changes.listen ctor 245 yes lifetime.listen
BLE addBatchRecordingFinalizedListener ctor 246–252 yes (remove in dispose) lifetime.own
_bleBytesStream field 509; adopt 1165 yes lifetime.own + takeSubscription
_blePhotoStream field 510; adopt 1491 yes same
_bleButtonStream field 514; adopt 986 yes (348d5f31dc) same
_storageStream was dead, never assigned n/a removed
CaptureProvider.addListener(_persistLiveSegments) provider 28–29 yes (removeListener in dispose) lifetime.own; provider dispose override deleted
CaptureMetricsTracker Timer.periodic 5s capture_metrics_tracker.dart:124 yes via _metrics.dispose() left — uses dart:async Timer directly, not CaptureScheduling. Still cancelled in dispose. Migrating it would pull the metrics helper onto capture's clock; listed rather than expanded.
_socket?.unsubscribe(this) dispose 1576 yes left — socket-service listener, not a dart:async Timer
Future.delayed(20ms) image chunks now image_utils.dart emitBase64ImageChunks in-flight loop, not retained left — not a Timer held across dispose
_peopleRefreshFuture field 104; nulled on dispose future not cancelled left — async generation, next cut
unawaited(_captureSessionLocation / auth refresh) 1747, 1854, 1926, 1966, 2613 n/a left — generation/join, not lifetime

Product invariants affected

none

How it was verified

Not exercised as a live device recording session.

Commands run:

  • python3 scripts/check_spine_contracts.py — 47 pending markers; 17 protected files. No spine-test edits.
  • python3 scripts/check_mobile_boundaries.py --config app/contracts/capture/boundary-baseline.json — 65 changed paths; 0 errors.
  • TZ=UTC flutter test test/services/capture/capture_disposal_test.dart test/services/capture/capture_lifetime_test.dart test/spine/c1_lifetime_test.dart — 16 passed.
  • TZ=UTC bash app/test.sh — exit 0.
  • make mobile-verify ARGS="fast --paths app/lib/services/capture/capture_controller.dart app/lib/providers/capture_provider.dart" — executed 20, passed 20, failed 0 (full-suite fallback because capture_provider.dart is outside the capture-wal path rule; j5_capture_interruption_reconnect ran and passed).
  • OMI_PR_BODY_FILE=.local/pr-body-c1-disposal.md make preflight — 21 checks passed in 185.65s.

capture_controller.dart touched line ranges (working tree, 2698 lines):

  • 15: drop ble_bridge import (listeners go through BleBridgeCaptureListeners)
  • 27: import capture_lifetime.dart
  • 126–127: lifetime wraps the injected scheduler
  • 241–243: restored mute-restore comment
  • 245–252: lifetime.listen / lifetime.own for connectivity, BLE finalized, BLE streams
  • 519: dead _storageStream removed
  • 966: voice-command timeout still _scheduling.once (now bag-tracked)
  • 986–990: _bleButtonStream via takeSubscription
  • 1165: _bleBytesStream via takeSubscription
  • 1491–1512: _blePhotoStream via takeSubscription; image chunks extracted
  • 1572–1579: dispose — socket unsubscribe + metrics + lifetime.close()
  • 1987–1992: debugArmVoiceCommandTimeout test seam

CaptureConnectivityBoundary.production() remains the no-argument default.

Tests

Builder regressions in app/test/services/capture/capture_disposal_test.dart:

  • dispose cancels the voice-command timeout that old dispose leaked (arm, dispose, elapse 15s, no pending timers) — fails on the old code
  • a timeout armed after dispose never fires
  • dispose drops the connectivity listener so a later event does not mutate isConnected

capture_lifetime_test.dart: close() cancels every owned timer before the caller awaits (needed because dispose is void).

Failure class (fixes)

No fix: commits. This is a harden: adoption of the lifetime bag. The voice-command leak was unreleased C1 code, not a live production bug report.

Failure-Class: none


Part of the mobile self-driving program (App core lane, C1 step 3). Stacked on composition / #14361 / #14327. Implemented by Cursor Grok 4.6. Coordinator: metrics sampler, socket unsubscribe, in-flight Futures, and location/auth unawaited work are listed not migrated.


Part of the mobile self-driving program (App core lane, third C1 PR). Stacked on #14367. Implemented by Cursor cursor-grok-4.6-high. Coordinator verification on the head: spine check passes with no edits to protected tests; the disposal and lifetime tests pass (16); capture_controller.dart shrank from 2,710 to 2,698 lines; the two explanatory comments dropped in #14367 are restored. One genuinely leaked timer is closed here (_voiceCommandTimeoutTimer, 15 s, never cancelled on dispose). Resources deliberately left for later cuts are listed in the inventory above with the reason.

🤖 Generated with Claude Code

Review in cubic

Git-on-my-level and others added 30 commits September 17, 2026 13:42
Add strict Python/Dart pending contracts and introducing-commit protection.
Reserve the live-session CLI, wire, ownership/attachment seams and failing
builder acceptance tests. Add live attribution before freezing evidence v1.

Verification:
- bash scripts/dev-harness/run-tests.sh: 287 passed, 7 existing skips,
  40 strict xfailed (24 pending V1 markers), Python 3.11.15.
- make preflight: 16 checks passed, using supported PYTHON selection.
- make mobile-verify fast --paths harness/session contract inputs with an
  absolute evidence directory: 20 executed, 20 passed, no failures/skips.
- bash app/test.sh: 2014 passed, 5 skipped, one unchanged UTC+7
  search_rank_grouping_test failure; affected baseline inputs match main.
- Real module CLI refusals exit 2 without traceback; regression covered.
- Dart SDK probe proves ext. prefix required; marker-removal formatter
  probe proves no incidental Dart diff.

Runtime is intentionally unimplemented. App UI must repair current invalid
VM extension names before live acceptance; unsupported journeys block.
Simulator/emulator latency and detached-process acceptance remain V1 work.
make setup installed hooks but full backend wheel sync stalled; isolated
Python 3.11 harness dependencies ran the owner checks without any skip flag.

Failure-Class: none
The check protects files under the spine roots and their registry, so it only
needs to run when those change. A repo-wide trigger would run it, and its
full-history requirement, on every unrelated contributor PR.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
V1 must refuse live journey execution until a shared executable adapter exists;
B1 addressability alone cannot attach Dart integration tests. Pure admission
contracts remain valid with injected supported IDs.

Verification: harness 287 passed, 7 skipped, 40 strict xfailed;
make preflight passed 20 checks.
C1 pending contracts specify recovery, foreground service, socket and session ownership; no existing runtime path changed. Verified UTC app suite (2041 passed), harness (287 passed, 7 skipped, 40 strict xfailed), 20 hermetic journeys, and 21 preflight checks.
Specify inventory revision coalescing without losing explicit retries, late location-upload/finalization fences, and zero legacy actor adoption checks. Existing protected tests are unchanged. UTC app: 2048 passed; harness: 287 passed, 7 skipped, 40 strict xfailed; preflight: 21 passed. Correction to earlier verification record: C1 selected 3 journeys, all passed, not 20. One intermediate unchanged baseline replay test returned zero restored WALs; the full final run passed and its exact failure is retained in .local/c1-app-final.log.
…lities

Coordinator turn-4 review authorizes the V1 fixture correction. Exact before/after digests pin the revised oracle; immutable revision records do not permit builder assertion edits. Active tests reject missing/tampered records and prove the fake machine response. Verification: full harness 289 passed, 7 skipped, 40 strict xfailed; UTC app 2020 passed; spine 24 pending/7 protected; make preflight 16 passed. No live device acceptance claimed.
Track retained marker occurrences rather than counts so retiring a second test cannot restore the first test's retired marker. The active regression covers this swap and legitimate continued retirement. Verification: full harness 290 passed, 7 skipped, 40 strict xfailed; spine 24 pending/7 protected; make preflight 16 passed. Dart sources unchanged after the earlier UTC app 2020-pass run.
…rges

A squash can introduce a corrected contract and its review records in the same commit. Absorb only the revision prefix ending at that introducing file's exact digest, preserving immutable records and later marker-only edits. Active temp-repo regression covers multiple corrections in one squash and rejects restoring old or altered assertions. Verification: harness 291 passed, 7 skipped, 40 strict xfailed; B1 make preflight 20 passed; final B1 journeys 20/20. Dart unchanged after UTC app 41 opt-in and 2051 ordinary passed.
Needed so capture-replay WAL reconstruction tests pass; main carries the
await-WAL-timer-Futures-before-settle fix.
Timers, streams, and owned cancels drain on close even when one
cancel fails. Close is idempotent and invalidates first, so a late
acquisition after close dies immediately.

Co-authored-by: Cursor <[email protected]>
A day-long capture session would pin one dead cancel closure per
once()/listen() that completed on its own. Release on fire, caller
cancel, and stream done so the bag only holds live work.

Co-authored-by: Cursor <[email protected]>
composeCaptureProvider now passes WAL, mic, auth, clock, scheduling,
connectivity, preferences, BLE, and socket through CaptureProvider into
CaptureController. Production no-argument defaults stay;
composeProductionCaptureProvider refuses FLUTTER_TEST before any singleton.

Co-authored-by: Cursor <[email protected]>
…_TEST

Builder tests lock the cut-1 lazy passes: openSocket/WAL/mic must actually
be forwarded, and the production composer cannot construct ConnectivityService
with the health URL under test. Retires only the two composition spine
markers this cut satisfies.

Co-authored-by: Cursor <[email protected]>
Formatting only; required by the pre-push dart format gate.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Those comments record why-knowledge this file breaks without: mute must
survive process death so streamDeviceRecording can re-apply it, and custom
STT buffering is surfaced so the UI shows offline instead of Listening.
Pay for the lines by extracting BleBridgeCaptureListeners.

Co-authored-by: Cursor <[email protected]>
…ureLifetime

Wrap the injected scheduler in CaptureLifetime so once/periodic, connectivity
listen, BLE finalized/stream subscriptions, and the live-segment listener
cancel on dispose. close() now drains every sync cancel before returning so
void dispose() stays synchronous. Extract image-chunk emission so the
controller shrinks.

Co-authored-by: Cursor <[email protected]>
The only CaptureController timer that dispose did not cancel was the
15s voice-command timeout (the class of 05c43c0). After dispose,
advancing fake time leaves no pending timers. Also lock close() to
cancel every owned timer before the caller awaits.

Co-authored-by: Cursor <[email protected]>
Formatting only; required by the pre-push dart format gate.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…ookkeeping

A second close() while the first is still draining must wait for the same completion, asFuture must untrack even after it replaces inner callbacks, and replacement data/error/done handlers must not run after close begins.

Co-authored-by: Cursor <[email protected]>
Git-on-my-level and others added 17 commits September 18, 2026 01:50
Store the supplied SharedPreferencesUtil and route later reads and writes through it so batchMuted and the rest of the seam are not the global singleton, while ordinary construction still defaults.

Co-authored-by: Cursor <[email protected]>
…shes

Untracking a callback is not the same as teardown completing; close now waits
for in-flight own/subscription cancels without running them a second time.

Co-authored-by: Cursor <[email protected]>
Co-authored-by: Cursor <[email protected]>

# Conflicts:
#	.github/checks-manifest.yaml
#	contracts/spine/files.json
#	scripts/check_spine_contracts.py
#	scripts/dev-harness/LIVE_SESSIONS.md
#	scripts/dev-harness/PENDING_CONTRACTS.md
#	scripts/dev-harness/dev_harness/live_session.py
#	scripts/dev-harness/dev_harness/mobile_session.py
#	scripts/dev-harness/tests/spine/fake_flutter.py
#	scripts/dev-harness/tests/test_spine_mechanism.py
The merge-forward pre-commit hook reindented main's file and tripped INV-MEM-1 on a formatter-only diff. Lifetime does not own that page.

Co-authored-by: Cursor <[email protected]>
Conflict resolution dropped trailing commas while keeping a split layout the formatter will not emit. Let dart format rewrite those 14 files; no semantic change.

Co-authored-by: Cursor <[email protected]>
#14327 landed the C1 contract on main, so its files collide add/add with this
builder branch. Resolution, per file:

- app/test/spine/c1_lifetime_test.dart, c1_lifetime_drain_test.dart: kept this
  branch's copies. They differ from main only by the removal of four
  pendingContract('C1') lines, which is the one edit a builder may make there.
  Taking main's would restore retired markers, which the mechanism forbids.
- app/lib/services/capture/capture_lifetime.dart: kept this branch's copy. Main
  carries the 25-line contract skeleton; this is the 244-line implementation of
  it.
- contracts/spine/files.json: took main's. Main has 27 entries and this branch
  20, with zero entries unique to the branch, so main is a strict superset and
  taking ours would have dropped seven registry entries #14327 just landed.
- .github/checks-manifest.yaml: took main's. Identical 225 check ids on both
  sides; the only difference was two blank lines.

Verified after resolution: spine checker exit 0 at 74 pending markers and 27
protected files, formatter 0 changed, app/AGENTS.md 11227 of 11411.

Co-Authored-By: Claude Opus 5 <[email protected]>
#14327 landed c1_lifetime_review_test.dart and c1_lifetime_terminal_test.dart
on main with pendingContract('C1') still set. The behaviour they pin was
already implemented on this branch by f04ec71 and acdc197, so after the
merge-forward all five executed green and the contract harness failed them as
XPASS ("remove the pending marker") rather than as unmet contracts. No
implementation change is required, and none is made here; only the five stale
markers are removed, which is the one edit the spine protection allows.

What each contract pins, and the capture_lifetime.dart behaviour that
satisfies it:

- concurrent close joins outstanding cancellation: a second close() used to
  hand back a fresh completed future and report teardown finished while the
  first drain was still awaiting an own() cancel. close() now short-circuits
  only on _closeFinished and otherwise returns the memoised _closing future,
  so every caller joins the same drain.
- asFuture preserves completion untracking: _inner.asFuture replaces the
  subscription's done handler, so the listen-time drop() never ran and the
  registration outlived its future. _LifetimeSubscription.asFuture now chains
  whenComplete(_drop).
- C1 asFuture error completion releases its registration: the same path on the
  error completion - whenComplete(_drop) untracks on throw as well as on done.
- replaced callbacks and errors stay closed while cancellation drains: a
  handler installed through onData/onError after listen bypassed the closed
  guard and could still fire while close() was blocked on an earlier release.
  Those wrappers now consult _isClosed() before forwarding.
- C1 original and replacement done callbacks respect closing: both the
  listen-time onDone wrapper and an onDone replacement now drop() the
  registration but return without calling the owner once _closed is set.

Verified in this worktree at app/: flutter test 2161 passed, 0 failed.
scripts/check_spine_contracts.py exit 0, 69 pending markers (was 74),
27 protected files.

Co-Authored-By: Claude Opus 5 <[email protected]>
…posal

Co-authored-by: Cursor <[email protected]>

# Conflicts:
#	app/lib/services/capture/capture_controller.dart
#	app/lib/services/capture/capture_lifetime.dart
#	app/test/services/capture/capture_lifetime_test.dart
…osal

# Conflicts:
#	app/lib/services/capture/capture_controller.dart
#	app/lib/services/capture/capture_lifetime.dart
#	app/lib/services/capture/capture_seams.dart
#	app/lib/services/capture/stt_mode_resolver.dart
#	app/test/services/capture/capture_lifetime_test.dart
@Git-on-my-level

Copy link
Copy Markdown
Member Author

Merged origin/main forward into task/msd-core-c1-disposal at 97a0282 — flutter test test/services/capture/ fully green (32/32), pinned dart format clean, push verified via ls-remote. CaptureLifetime routing: dispose() fires unawaited(lifetime.close()) and main's kept _drain awaits each release behind Future.sync, so teardown completes asynchronously — CaptureProvider joins the drain via await lifetime.close() (idempotent _closing), and capture_disposal_test.dart now awaits close() before asserting pendingTimers is empty, preserving the guarantee that the voice-command timeout is cancelled rather than leaked.

dispose() previously only cancelled the keep-alive periodic through the
lifetime release, which runs behind the async drain. Tests that assert
the no-pending-timers invariant immediately after dispose() saw the 15s
periodic still pending. Cancel it synchronously in dispose() before
unawaited(lifetime.close()); the drain's release stays idempotent
(Timer.cancel on an already-cancelled timer is a no-op).

Captured in the chain-1 merge-forward: CI on 97a0282 failed
capture_provider_test 'shows reconnecting warning when socket closes
during phone mic recording' with the pending-timer assertion. Full
capture + provider suites green locally (118 passed).
@Git-on-my-level
Git-on-my-level merged commit 0e8c0bf into main Sep 18, 2026
37 checks passed
@Git-on-my-level
Git-on-my-level deleted the task/msd-core-c1-disposal branch September 18, 2026 13:36
summersmile1984 added a commit to summersmile1984/omi that referenced this pull request Sep 26, 2026
Upstream's capture ratchet (scripts/check_mobile_boundaries.py) drifted
against its own code: C1 (BasedHardware#14327) recorded singleton-reads 2, then
BasedHardware#14529/BasedHardware#14549/BasedHardware#14550 grew app/lib/services/capture/capture_seams.dart to
4 without updating the record, so the check fails at upstream/main itself
for any diff touching the file. This restates already-merged upstream
code with the check's own designed remedy (baseline records reviewed
debt; only adopted keys and the frozen rules are immutable).

Known limitation, recorded deliberately: for this sync push the file does
not exist at merge-base(origin/main, HEAD), so the check limits new
files to zero regardless of baseline and stays red once; after the sync
lands on origin/main, previous=4 and baseline 4 makes the steady-state
run green (baseline 2 would stay red forever).

Registered as T1 in dev/unified-main/upstream-touch-allowlist.yaml with a
PROPOSED upstream PR to carry the same line.

Evidence: check_mobile_boundaries now reports only the structural
new-file error (unchanged); check-upstream-touch --aggregate exit 0 with
both allowlist entries within budget after this commit.

Failure-Class: none
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