Skip to content

harden(app): CaptureLifetime — every capture timer, subscription and listener is cancelled on dispose - #14361

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

Git-on-my-level merged 31 commits into
mainfrom
task/msd-core-c1-lifetime

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Sep 17, 2026 •

Copy link
Copy Markdown
Member

What changed and why

Implements CaptureLifetime (once / periodic / listen / own / close) so every capture timer, stream, and owned cancel is registered immediately and drained on close. Close invalidates first and is idempotent; a failed cancel still drains the rest; a late acquisition after close dies immediately. Not wired into CaptureController or main.dart in this PR.

Review of the first commit found a leak: _releases only shrank at close(), so every fired once() and completed listen() left a dead cancel closure in the bag (and pinned the callback captures). Capture is always-on for hours; reconnect backoff, flush debounce, and delayed recovery re-arm call once() repeatedly (capture_controller.dart _autoSyncFallbackTimer, voice-command timeout, keep-alive t.cancel()). The follow-up commit untracks on fire (before the callback), on caller cancel() via a Timer/StreamSubscription wrapper, on stream onDone / cancelOnError, and via CaptureOwned.release(). listen forwards optional onError / onDone / cancelOnError rather than swallowing stream errors.

Stacked on task/msd-spine-a-seams (4f9ad87be7). This branch also contains a merge of origin/main (898118d6e4); until the spine branches are brought up to date with main, a PR diff against the seams base will include main's commits. The reviewable change is the two lifetime commits (harden(app): implement CaptureLifetime resource bag and the leak follow-up).

Product invariants affected

none

How it was verified

CaptureLifetime is not yet on the production capture path, so verification is the contract tests plus the app suite, not a live recording session.

Commands run (all green):

  • python3 scripts/check_spine_contracts.py — 49 pending markers; 17 protected files. Diff of app/test/spine/c1_lifetime_test.dart is only the two pendingContract('C1'); lines removed (unchanged in the leak follow-up).
  • python3 scripts/check_mobile_boundaries.py --config app/contracts/capture/boundary-baseline.json — 0 errors.
  • TZ=UTC bash app/test.sh — exit 0.
  • make mobile-verify ARGS="fast --paths app/lib/services/capture/capture_lifetime.dart" — executed 3, passed 3.
  • OMI_PR_BODY_FILE=.local/pr-body-c1-lifetime.md make preflight — 21 checks passed in 105.59s.

Not exercised live: no device capture session. This PR does not change constructor injection, defaults, or capture_controller.dart.

Tests

Spine app/test/spine/c1_lifetime_test.dart (markers retired, not re-edited): close cancels timers/streams/owned listeners including late acquisition; one failed cancel still drains the rest.

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

  • close does not cancel timers the bag did not register
  • once after close never fires
  • close invalidates before awaiting a slow own, so a mid-close once dies
  • two failing cancels both run; the first error is rethrown
  • after N fired once() timers, debugTrackedCount is 0
  • once untracks before a throwing callback
  • caller-side cancel untracks; close() does not run the owned cancel again
  • a completed stream is untracked
  • listen forwards onError; cancelOnError untracks
  • after that completed work, close() is still idempotent and still drains survivors when one release throws

Failure class (fixes)

No fix: commits. This is a harden: extraction. The leak was found in review of unreleased code, not a live production bug.

Failure-Class: none


Part of the mobile self-driving program (App core lane, first C1 PR). Stacked on #14327, which carries the contract tests this satisfies. Implemented by Cursor cursor-grok-4.6-high against tests written by Codex gpt-6-astra. Coordinator verification on the head: the only edits to the protected spine test are two pending-marker removals (python3 scripts/check_spine_contracts.py passes, 49 pending); the spine lifetime test and the 10 builder tests pass (12 total). Review found one defect in the first version, fixed here: registrations were never released when a one-shot timer fired or a stream completed, so an always-on capture session would accumulate one dead closure per timer for its whole life; stream errors were also silently dropped.

🤖 Generated with Claude Code

Review in cubic

Git-on-my-level and others added 21 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]>
@Git-on-my-level

Copy link
Copy Markdown
Member Author

Architect conformance review: conforms, with required changes

Reviewed at immutable ref d523313d3ff00d48097aeab6b90573035a6b9fb7. The design conforms to
the C1 contract and the coordinator's completed-timer/stream correction is present. Five
additional tests, covering three defect classes, fail against this exact implementation.

Required changes in app/lib/services/capture/capture_lifetime.dart:

  1. :113 — a second close returns early while the first is still awaiting cancellation, so a
    caller can treat disposal as complete while owned work is still alive. Join the in-flight
    drain. Preserve the existing no-op behavior of a later close after completion.
  2. :185 — forwarding asFuture replaces the inner subscription's completion and error
    callbacks
    , bypassing the untracking callback, so a completed stream still occupies the
    bag. Keep terminal bookkeeping through asFuture, including error completion.
  3. :81 and :170 — onError/onDone and replacement onData/onError callbacks bypass
    the closed guard.
    During a slow earlier cancellation, replacement data and error
    callbacks still mutate state after close has begun. Every callback path must respect the
    same lifetime, while still delivering normal pre-close behavior.

These are lifecycle contract defects, not a demand for a state-management framework. The
protected follow-up oracles that encode them — c1_lifetime_review_test.dart and
c1_lifetime_terminal_test.dart — are pending on #14327; you retire their markers by fixing
the implementation. No default CaptureController and no production connectivity was
constructed by the review.

This PR can proceed: it is already marked ready and its parent #14327 has to merge before it
gets CI at all. Fix these three on this branch.

…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

Copy link
Copy Markdown
Member Author

Architect conformance review, round 2: conforms, with one required change

Reviewed at f04ec717092d7c66d0c953368c85a6acbb7d4b34. All three previous findings are
fixed
— the five original adversarial cases pass, completed callbacks and asFuture untrack,
original and replacement callbacks respect close, and a concurrent close joins its drain. The 14
implementation tests pass too.

One further class remains, in app/lib/services/capture/capture_lifetime.dart:101–112,
:122–130 and :177–180. Explicit CaptureOwned.release() and subscription cancel() remove
their registration before the asynchronous cancellation completes, so a subsequent close()
sees an empty bag and returns while that cancellation is still in flight. Both variants
reproduce.

The distinction the review draws is the useful part: an unregistered callback is not the same
as unfinished owned teardown.
Keep terminal callback bookkeeping bounded as you have it, but
track and join the cancellation futures until they actually finish — without cancelling twice.

A new protected c1_lifetime_drain_test.dart pins both cases, and the contract skeleton adds
only your existing release-handle signature, no implementation.

🤖 Generated with Claude Code

Git-on-my-level and others added 3 commits September 18, 2026 03:55
…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]>
@Git-on-my-level

Copy link
Copy Markdown
Member Author

Required change addressed — b4c296abb0

close() now joins owned teardown until it actually finishes. The distinction the review drew
is the one implemented: untracking a callback is not the same as cancellation completing.
CaptureOwned.release() and subscription cancel() still drop their bag bookkeeping
immediately and still cancel exactly once, but close() waits on those in-flight futures rather
than seeing an empty bag and returning. c1_lifetime_drain_test.dart pins both variants.

TZ=UTC bash app/test.sh 2103 passed; spine 0 pending; make preflight 21/21; format clean;
mobile-verify j5 3/3.

This branch was also merged forward into task/msd-core-c1-composition and
task/msd-core-c1-socket-generation, so the two dependents no longer sit on the unfixed
CaptureLifetime.

🤖 Generated with Claude Code

Git-on-my-level and others added 3 commits September 18, 2026 07:37
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]>
@Git-on-my-level
Git-on-my-level changed the base branch from task/msd-spine-a-seams to main September 18, 2026 03:03
Git-on-my-level and others added 3 commits September 18, 2026 10:12
#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]>
@Git-on-my-level
Git-on-my-level merged commit 45f87b4 into main Sep 18, 2026
37 checks passed
@Git-on-my-level
Git-on-my-level deleted the task/msd-core-c1-lifetime branch September 18, 2026 08:07
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