# Step-13A - Retain comparison ownership through cleanup and drain completion ## STEP IDENTIFIER Step-13A, corrective follow-up to [Step-13](Step-13.md). Original C-07 / AC-03 has one remaining ownership-tail gap, R-01. Step-13 is not accepted; Step-14 remains blocked/unassigned. Read [STATE.md](STATE.md), the preserved [Step-13 report](Step-13-Report.md) and [WORKER-QUALITY-GATE.md](WORKER-QUALITY-GATE.md). ## STEP TITLE Prevent another comparison/save owner from replacing an unfinished previous owner/drain, and make Close include all admitted cleanup. ## OBJECTIVE Fix R-01 only. Complete release/cleanup outside required state gates while keeping the admitted owner/busy/drain identity reserved until terminal completion is settled atomically. Execute a real controlled pre-fix regression, correct the source order, verify behavior and preserve all supported Step-13 functionality. No new model/hardware/project/format/feature or permission-form work. ## ARCHITECTURAL CONTEXT The Application comparison session owns one evaluation/save operation and its cancellation/drain. UI releases Hybrid command events and drains that owner on unmount. Keep the nine-project graph, real Dynamics/v2/capture/store/target boundaries and private test oracle isolation. The orchestrator owns review/handoffs only; worker executes code/tests/native. ## CURRENT IMPLEMENTATION STATE Most Step-13 scope is supported by reviewed code and worker evidence: current preview-to-pinned draft, trusted actual owning readback proof, exact NEW config projection, equivalent real full scenarios, canonical metrics, bounded real captures, partial-save/readback/replay and native model path. Worker reports clean nine-project Release and 179 unit + 466 integration = 645 passes, zero failed/skipped; all 596 earlier cases preserved. Do not rewrite its report or claim these are new corrective executions. R-01 in [CalibrationComparisonSession.cs](../src/AutoForge.Application/Features/Vehicles/Calibration/CalibrationComparisonSession.cs:311): 1. ObserveAsync finishes awaited operation work. 2. Under `_gate`, it clears `_owner` and sets `IsBusy=false`/terminal state. 3. Outside `_gate`, it calls `owner.Release()`. 4. Only afterwards does it settle the completion task stored in `_drain`. Start checks only `_owner != null`. A competing Evaluate/Save can therefore admit after step 2 while the old release/completion is unfinished, replacing `_drain`. A later Close can then follow only the newer completion. Owner.Cancel invokes linked cancellation callbacks under its own gate; a delayed callback can keep Release pending and make this a real cleanup interval, not merely a sequential call after a completed await. The orchestrator identified source ordering and ran no reproduction/build/test. The worker must reproduce the actual endpoint behavior before fixing it. Existing held signal/final-read/save cases do not hold this completion tail. Accepted prior art: [local-generation completion](../src/AutoForge.Application/Features/Vehicles/Runbooks/LocalRunbookGenerationSession.cs:205) releases the owner outside the state gate BEFORE atomic owner/completion/drain publication. Reuse the pattern; no general lifetime framework. ## REQUIRED IMPLEMENTATION ### Frozen corrective matrix | ID | Controlled condition | Required result | |---|---|---| | C-01 | Operation work returns while old cancellation/release completion remains held; competing Evaluate and Save | Both reject Busy before new work/admission/config/capture/store effects; same old drain retained, IsBusy truthful until cleanup settles | | C-02 | Close/Dispose competes with that pending completion tail | Shared Close stays pending through the old cleanup/drain, no replacement completion, all owned resources released once, then Closed with no late result | | C-03 | Release/drain settlement after success, failure or cancellation | Cleanup outside required state gates, then atomic terminal state/owner removal/completion publication; primary error/cancel and per-ID save evidence preserved, no false success or hung waiter | | C-04 | After real full drain, next legitimate operation or fresh page lifetime | New owner can admit normally only while open; old completion cannot clear/overwrite it; closed sessions remain closed and fresh entry independent | | C-05 | Existing evaluation/partial-save/model/native flows and full baseline | All 645 cases retained, focused new regressions and nine-project Release/native affected-lifecycle checks pass; exact data/proof/capture/metrics unaffected | Keep `_owner` (or equivalent admission reservation) and the specific drain until its release is complete. Publish terminal state, clear ownership and settle that same completion under a coherent gate. Do not expose idle before the preceding operation has drained or allow `_drain` replacement in the tail. Preserve shared Close/cancellation and current-result retirement semantics. Do NOT put potentially blocking release or cancellation callbacks under the comparison state gate: a callback can read state or take another required gate. Avoid a new inverse lock order or awaiting work needed by cleanup while locked. Observe any cleanup failure explicitly, preserve the original operation error/ partial-save evidence and settle waiters truthfully; no success-shaped finally. Do not fix by merely adding sleeps, relying on current callbacks being quick, suppressing errors or hiding the Busy state. Do not stop/unload runtime/models, roll back published files or modify proof/value/physics validation. ## FILES OR PROJECTS EXPECTED TO CHANGE Focused comparison completion/admission/Close code, directly related controlled tests (reuse existing real comparison fixtures/store/transport seams), and related comparison/build/status documentation. UI changes only if directly needed to preserve the affected lifetime behavior. Only `prompts/Step-13A-Report.md` under `prompts`; all old prompts/reports unchanged. ## INTERFACE AND DEPENDENCY REQUIREMENTS Preserve public comparison/source/projection/archive contracts, proof/current- head guards, canonical values/metrics/fingerprints, 3900-step/1562-scheduled- observation cadence and unchanged archive bounds. Preserve single explicit owner/no unassigned business mutation, partial per-ID save truth and replay. No new dependencies/projects/hosts, runtime/model installation/configuration, hardware programming, model permission forms, cloud, tools or Git backup work. ## TESTING REQUIREMENTS Before production fix, add and EXECUTE the failing real feature-boundary test. Hold cancellation/release after operation work can finish, not only transport before its reply. Show competing Evaluate/Save actually admits too early or Close can finish with old admitted cleanup/drain unfinished. Record exact behavioral failure; compilation failure or a prose sequence is not reproduction. Prefer a controlled cancellation callback/cleanup resource below the real comparison boundary. If an internal cleanup observation seam is unavoidable, keep it minimal/internal, explain it and exercise actual public workflow with the same code; no public test controls or mocked comparison coordinator. Use barriers/schedulers, not arbitrary sleeps or polling for a lucky race. Release callbacks/barriers/resources in finally so failed assertions drain. Then verify C-01..C-04 for normal success, operation failure and cancellation: Busy identity/call counts, old drain/Close pending state, once-only cleanup, failure/result/save retention, legitimate retry after full drain and fresh page. An existing pre-work held HTTP test alone does not prove the corrected tail. Do not weaken source/target/model/archive checks to make lifetime tests pass. Run the smallest combined focused selectors covering comparison/new owner cases, then sequentially: - `dotnet build .\src\AutoForge.slnx --configuration Release --no-restore` - `dotnet test .\src\AutoForge.slnx --configuration Release --no-build` All nine projects/645 cases plus new cases must pass. Restore only after a genuine chosen-command missing dependency; no SDK/workload/runtime/model update. Recheck actual native affected Evaluate/Busy/Cancel/Close/unmount/fresh-entry behavior on the rebuilt Client, including one legitimate completed comparison/ save/report. Retain exact numerical/proof/capture semantics and old manual/ unit/source behaviors. Controlled tail barriers are not native timing claims. Existing real-model content in the original report remains historical evidence, not a newly executed LLM response; no repeated inference claimed unless run. The original report's intermittent unchanged dynamics-owner TaskCanceledException and known recording-navigation Busy issue are separate disclosures. Do not change those unrelated files or infer causality from one flaky run. If a new failure is causally tied to this correction, investigate and fix that cause; otherwise report exact evidence honestly without waiver or unrelated cleanup. ## DOCUMENTATION REQUIREMENTS Update directly related comparison ownership/drain/error and build/native evidence docs/README. Step-13/13A remain pending manual acceptance. Original 645-case/model/numerical/archive report remains unchanged. No hardware or new milestone claims. ## ACCEPTANCE CRITERIA | ID | Criterion | Evidence | |---|---|---| | AC-01 | Actual pre-fix R-01 failure and C-01 corrected competing-admission behavior | Executed real comparison boundary with held release tail, exact old drain and zero new side-effect calls | | AC-02 | C-02/C-03 safe shared Close/Dispose and atomic terminal completion | Controlled callback/release/drain interleavings, once-only cleanup, truthful success/error/cancel/save evidence and no deadlock | | AC-03 | C-04 no premature/late owner publication and valid post-drain retry | Same old task/owner reservation until completion, legitimate new work afterwards, independent closed/fresh lifetimes | | AC-04 | C-05 original 645 regressions/new cases/nine-project Release and affected native paths pass | Exact commands/exits/warnings/counts and native-versus-controlled distinction; original data/authority invariants retained | | AC-05 | Shared gate, source-path self-review, docs/history/manual stop | Producer/consumer review after green and precise `prompts/Step-13A-Report.md` | ## OUT-OF-SCOPE WORK Projection/physics/schema/metrics redesign, additional comparison capabilities, model/runtime setup or policy questions, new owner framework, hardware, recording navigation fixes, unproven unrelated dynamics fixes, packages/hosts/ projects, staging/commit/push, agents/automatic handoff or Step-14. ## REPORTING REQUIREMENTS Save `prompts/Step-13A-Report.md` entirely inside exactly one plain triple-backtick fence, no language tag/outside text/nested fences. Include Step/title/status/R-01; actual pre-fix failure; C-01..C-05/AC-01..AC-05 named executed evidence; owner/release/drain/Busy/Close/callback order and pending/completed state; primary errors and partial-save preservation; files/ interfaces; exact commands/exits/warnings/per-project counts; native versus controlled outcomes; post-green source-path self-review; docs, deviations/ blockers, preservation and exact task-only cleanup. COMPLETE requires all assigned checks; otherwise INCOMPLETE/BLOCKED precisely. Save and STOP for manual orchestrator review. No old report rewrite or Step-14.