AutoForge/prompts/Step-07B.md

170 lines
9.6 KiB
Markdown

# Step-07B - Deadlock-free source disposal during capture cleanup
## STEP IDENTIFIER
Step-07B, single-issue follow-up to existing Step-07A R-03 / C-06 / AC-03.
Step-07/07A remain NOT ACCEPTED. Corrected Step-06 and earlier work stay accepted.
This is the sole active assignment; Step-08 replay remains blocked.
## STEP TITLE
Prevent the lifetime-registration/observation-drain lock cycle during source
close or reset while capture failure/limit cleanup unregisters.
## OBJECTIVE
Correct one lock-order issue in the existing safe-close contract.
Preserve the fixed archives, exact source comparisons, shared v2 validator,
bounded registration release, visible save/list errors and native behavior.
Read [STATE.md](STATE.md), [Step-07](Step-07.md), [Step-07A](Step-07A.md),
its preserved [report](Step-07A-Report.md) and
[WORKER-QUALITY-GATE.md](WORKER-QUALITY-GATE.md).
Write only `prompts/Step-07B-Report.md` under `prompts`, then STOP for review.
## ARCHITECTURAL CONTEXT
Keep all nine projects, one Client, existing session/capture/observation/storage
ports and pure Components. No new package, host, general lifetime framework,
archive version, protocol, model/clock or recording feature.
All source/tests remain under `src`, tests under `src/tests`.
## CURRENT IMPLEMENTATION STATE
Step-07A corrects source-faithful round trips, typed/v2 archive validation,
normal unregistration, barrier-finally cleanup and panel save failure visibility.
Worker reports 179 unit + 131 integration passes (310 total, zero failed/
skipped), clean full Release build and native static/dynamic save/restart/load/
source-close evidence. Preserve the 303 prior cases and seven additions.
One existing overlap remains in these actual paths:
- [DiagnosticSession.DisposeAsync](../src/AutoForge.Application/Features/Vehicles/Diagnostics/DiagnosticSessionService.cs:179)
holds _lifetimeGate while calling DisposeResourcesAsync.
- That async method starts synchronously and can invoke capture.DisposeAsync,
then block in observer unsubscription before an incomplete await yields.
- [Protocol observation dispatch](../src/AutoForge.Diagnostics/SyntheticDiagnosticProtocolClient.cs:618)
holds _observersGate during OnObservation.
- [Capture failure/limit cleanup](../src/AutoForge.Application/Features/Vehicles/Telemetry/Recording/SessionTelemetryCapture.cs:327)
calls UnregisterLifetimeResource, which needs _lifetimeGate.
If close begins unsubscribe while the callback is completing its detach,
close can wait for the observer gate while the callback waits for the lifetime
gate. The existing sequential resource-count and normal-close tests do not
force this overlap.
This is source-inspection evidence, not an orchestrator-executed reproduction.
Reinspect Git and preserve existing worker changes/history before editing.
## REQUIRED IMPLEMENTATION
Make the smallest sound coordination/ordering change so the registration gate
is used only to establish close ownership and snapshot shared state. Do not run
cancellation/resource-disposal callbacks, or wait for observer drain, while
holding that gate.
Publish a single shared disposal completion safely before competing callers can
start cleanup twice; all callers must observe the real completed cleanup or its
failure. Keep closed-state publication, late-registration rejection, resource/
control/transport disposal and existing error aggregation intact.
Do not just remove UnregisterLifetimeResource, restore retained capture history,
drop accepted callbacks, clear unsaved data, use a broad catch, publish success
before cleanup, or add sleeps/retry loops to mask the cycle.
Audit close/reset and both limit/error detach paths touched by the fix.
### Frozen corrective matrix
| ID | Input/precondition | Required result |
|---|---|---|
| C-01 | Normal stop/close, with and without active recording | Existing draining, bounded registration counts and stopped source-faithful saveable snapshots remain correct |
| C-02 | Callback owns observation dispatch and reaches limit detach; close begins draining it before callback unregisters | After controlled barriers release, both operation and close complete; no lifetime/observer lock cycle, lost prefix or false complete status |
| C-03 | Same competing close/reset with capture observation-error detach | Same no-deadlock policy; original Error/Incomplete reason/data retained; replacement session receives no old callback/data |
| C-04 | Multiple concurrent DisposeAsync calls; cleanup failure or attempted late registration | Cleanup runs once with shared completion/error, failures remain explicit, registration rejects once closing starts and unregistration cannot strand close |
| C-05 | Existing archive, registration, storage/panel, source/model/unit and native paths | All 310 cases plus focused regressions pass; fixed limits/schema/source semantics and native record/save/readback baseline preserved |
## FILES OR PROJECTS EXPECTED TO CHANGE
Existing diagnostic-session disposal coordination and, only if required, narrow
capture/observation cleanup ordering. Focused real integration tests/test-only
barrier helpers and directly related lifecycle/build/README text.
Only `prompts/Step-07B-Report.md` under `prompts`; no assignment, roadmap/state,
shared gate, historical report or protected instruction edits.
## INTERFACE AND DEPENDENCY REQUIREMENTS
Preserve the nine-project graph, one source/capture owner and shared disposal
task, immutable saved/unsaved captures, exact source bytes/unit/time/context,
archive-v1 validation, all fixed limits, no-overwrite publication and visible I/O.
No protocol/physics/calibration/hardware authority or engine oracle changes.
No dependency/system/workload install/update/repair/rollback, staging/commit/push
or destructive Git action.
## TESTING REQUIREMENTS
1. Establish the exact interleaving with controlled barriers, not a stress race.
Hold the observation at failure/limit detach after it releases the capture
lock; begin source close and its unsubscribe/drain; then allow callback
unregistration to proceed. A test-only subscription wrapper can expose these
barriers while forwarding actual protocol observations. Do not mock away the
session/recorder or add a production fault/race selector.
2. Record actual pre-fix blocked-state/behavioral evidence, not a compilation
failure or hypothetical timing claim. A deadlock reproduction may need a
bounded task-owned focused test process. Capture barrier/timeout evidence
and terminate only that exact process tree in finally if necessary; never
strand intentionally deadlocked tasks in the normal suite or kill by name.
3. After the fix, await real operation/close/reset completion and assert frozen
prefix/count/completion reason, resource release and no late old publication.
Cover both limit and observation-failure detach, and concurrent disposal/
cleanup-error behavior. Deadline guards are safety nets, not race proof.
4. Release every barrier before observer/source disposal and await dependent
work in finally. Preserve the normal and failed-assertion cleanup tests.
Run focused cases, then sequentially:
- `dotnet build .\src\AutoForge.slnx --configuration Release --no-restore`
- `dotnet test .\src\AutoForge.slnx --configuration Release --no-build`
Preserve the 310 baseline cases (179 unit, 131 integration) plus meaningful new
assertions. Record exact commands/exits/warnings/per-project counts.
Install/restore nothing absent a genuine chosen-command missing dependency.
Native recheck: actual static/dynamic recording, source close with retained
capture, explicit save/restart/readback and unchanged unit/source context.
The exact race is controlled test evidence, not a human-timed native claim.
Clean only exact task-owned captures/profiles; preserve unrelated app data.
## DOCUMENTATION REQUIREMENTS
Document the safe close ownership/lock boundary and matching execution evidence.
Keep original Step-07/07A reports and their positive archive/native results
unchanged. Do not claim Step-07 accepted, a new archive version or replay.
## ACCEPTANCE CRITERIA
| ID | Criterion | Evidence |
|---|---|---|
| AC-01 | C-01..C-03 close/reset and limit/error callback detach cannot form the lock cycle | Actual safely bounded pre-fix reproduction, controlled post-fix completion/prefix/reason assertions |
| AC-02 | C-04 single disposal completion, rejection and cleanup-error behavior preserved | Concurrent-caller/count/error tests and source-path ordering review |
| AC-03 | C-05 all 310 regressions, new cases, full nine-project Release build and native baseline pass | Exact complete worker results and native/control distinction |
| AC-04 | Original scope/history/protection preserved; docs/self-review/report complete and worker stops | Matrix, own post-green source-path review and `prompts/Step-07B-Report.md` |
## OUT-OF-SCOPE WORK
Archive/I-O/UI redesign, new format/limits, playback/seek/speed controls, live disk
streaming, new unit family/project/package/host, model/clock/AI/hardware and
unrelated cleanup. No future assignment, agents, automatic handoff, orchestration/
shared-gate edit, staging, commit or push.
## REPORTING REQUIREMENTS
Save `prompts/Step-07B-Report.md` wholly inside exactly one plain triple-backtick
fence, no language tag/outside content/nested fences. Include identifier/title/
status, implementation/files/interfaces, C-01..C-05/AC-01..AC-04 mapping,
actual pre/post barrier/state evidence and safe process cleanup if used,
commands/exits/warnings/test counts, native versus controlled coverage,
docs/README, self-review after first green, limitations/deviations/blockers
and preservation review.
COMPLETE requires all assigned checks; otherwise report INCOMPLETE/BLOCKED with
the precise unmet criterion. Save and STOP; do not begin Step-08.