diff --git a/README.md b/README.md index f8058fd..585ee75 100644 --- a/README.md +++ b/README.md @@ -76,10 +76,13 @@ diagnostic operations, explicit source-sensitive local archive save/readback, strict schema-v1 validation, and shared recording/inspection controls in both host workflows. Step-07A corrects source-faithful empty/case-variant response round-trips, v2 archive validation, capture lifetime release, and visible -storage failures. Both worker reports retain their separate evidence; neither -worker completion is orchestrator acceptance. See the [Step-07 worker +storage failures. Step-07B removes the source-close versus callback-unregister +lock cycle while preserving shared disposal completion and failure reporting. +The three worker reports retain separate evidence; none is orchestrator +acceptance. See the [Step-07 worker report](prompts/Step-07-Report.md) and [Step-07A corrective worker -report](prompts/Step-07A-Report.md). +report](prompts/Step-07A-Report.md) and [Step-07B lock-safety corrective +report](prompts/Step-07B-Report.md). ### Planned diff --git a/docs/README.md b/docs/README.md index 33c9a7a..827d485 100644 --- a/docs/README.md +++ b/docs/README.md @@ -8,8 +8,10 @@ session-owned live dashboard, and the accepted Step-06/06A display-unit preference. Step-07 implements bounded session recording, local archive readback and shared host controls. Step-07A corrects archive fidelity and v2 validation, releases stopped capture owners and preserves visible storage -failures. The original Step-07 evidence and Step-07A corrective evidence are -separate; worker acceptance remains pending manual orchestrator review. +failures. Step-07B moves session cleanup outside the lifetime-registration +gate and shares its completion/failure among competing disposers. Each +worker report contains separate evidence; acceptance remains pending manual +orchestrator review. - [Architecture](architecture.md): actual nine-project graph, responsibilities, route ownership and provider/reference boundaries. @@ -58,5 +60,6 @@ historical/worker reports for their own execution evidence: [Step-06 worker report](../prompts/Step-06-Report.md), [Step-06A corrective worker report](../prompts/Step-06A-Report.md), and [Step-07 worker report](../prompts/Step-07-Report.md) and -[Step-07A corrective worker report](../prompts/Step-07A-Report.md). +[Step-07A corrective worker report](../prompts/Step-07A-Report.md) and +[Step-07B lock-safety corrective worker report](../prompts/Step-07B-Report.md). Handoffs are manual; acceptance remains the orchestrator's responsibility. diff --git a/docs/architecture.md b/docs/architecture.md index 8b0fde1..1bbbea5 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -133,6 +133,12 @@ for inspection/save. UI unmount does not own or stop capture. Stopped, failed or discarded capture owners are removed from the diagnostic session's lifetime-resource list; the workspace retains only the current inspection/save data. An active capture is still drained on source close. +Close marks the session closed, snapshots registrations and publishes the +shared disposal task under the lifetime gate, then releases the gate before +cancellation or resource/control/transport disposal begins. Concurrent +disposers await that same completed task or failure; late registrations are +rejected after close ownership is established. This keeps observer draining +and capture unregistration outside the registration lock. The Client persists only explicitly saved archives under its app-local `recordings` directory. Application owns schema-v1 validation and file-storage diff --git a/docs/build-and-test.md b/docs/build-and-test.md index c8ade6f..a0c114c 100644 --- a/docs/build-and-test.md +++ b/docs/build-and-test.md @@ -580,3 +580,55 @@ environment. See the [Step-07A corrective worker report](../prompts/Step-07A-Report.md) for the frozen-matrix mapping, pre/post-fix outputs, self-review and preservation review. Step-08 remains blocked pending manual review; no Step-08 work began. + +## Step-07B lock-safe session disposal verification + +The pre-fix reproduction used the real diagnostic protocol/session, capture and +provider transport with a test-only subscription wrapper exposing controlled +dispose barriers. It held a capture callback at limit or observation-error +detach after the capture lock was released, started close/reset until its +second unsubscribe was entered, then released the callback. Both actual tasks +remained incomplete: `Operation completed=False; close/reset completed=False.` +The two focused cases failed as expected after their five-second safety +deadlines (two failed, zero passed); the bounded `dotnet test` host exited +normally after reporting both cases, so no deadlocked process tree required +termination. Command: + +`dotnet test .\src\tests\AutoForge.IntegrationTests\AutoForge.IntegrationTests.csproj --configuration Release --filter "FullyQualifiedName~SessionCloseDuringCaptureDetach_DoesNotDeadlockOrLoseFailurePrefix"` (exit 1). + +These are deterministic barrier-forced lock-cycle observations, not a +stress-timing claim. + +The corrected session publishes one shared disposal completion and snapshots +the lifetime resources under the lifetime gate, then performs cancellation +and resource/control/transport disposal after releasing it. Concurrent callers +observe the same task and cleanup error; late registration rejects once close +ownership has been established. The focused set passed 29/29 recording tests, +including limit-close and error-reset, exact prefix/reason preservation, +replacement-session isolation, concurrent disposal and cleanup failure. +Commands and results: + +- `dotnet test .\src\tests\AutoForge.IntegrationTests\AutoForge.IntegrationTests.csproj --configuration Release --filter "FullyQualifiedName~SessionCloseDuringCaptureDetach_DoesNotDeadlockOrLoseFailurePrefix|FullyQualifiedName~ConcurrentSessionDispose_SharesCompletionAndReportsCleanupFailure"` (3 passed) +- `dotnet test .\src\tests\AutoForge.IntegrationTests\AutoForge.IntegrationTests.csproj --configuration Release --filter "FullyQualifiedName~TelemetryRecordingIntegrationTests"` (29 passed) +- `dotnet build .\src\AutoForge.slnx --configuration Release --no-restore` (nine projects; 0 warnings, 0 errors) +- `dotnet test .\src\AutoForge.slnx --configuration Release --no-build` (179 unit + 134 integration; 313 total, zero failed/skipped) + +The rebuilt Windows Client was rechecked through its local WebView2 DevTools +endpoint. Static v1 recorded two actual operations (DTC and signal reads), +stopped, closed its source while retaining the unsaved capture, then saved. +After app restart, the archive loaded with its raw bytes and decoded signals. +Dynamics v2 was explicitly stepped to model step 7 / 0.7 seconds, captured four +actual `read.signals` observations with gauges hidden, then stopped and closed +its source while retaining the unsaved capture before saving. A second app +restart loaded both static and dynamics archives with raw data and decoded +source/model context. Metric/Road preferences remained unchanged. The exact +task-owned capture IDs were `3b6bbb098a094ac2ba10c042dcd4fbf0` (static) and +`ac5b4d4e814d4905a0d454292b4dde87` (dynamics); their exact archive files and +task-owned temporary profiles were removed after closing the Client. + +The controlled integration tests prove the close/reset lock-cycle resolution; +the native smoke verifies unchanged normal record/stop/close/save/restart/ +readback behavior and does not claim native race injection. See the +[Step-07B worker report](../prompts/Step-07B-Report.md) for matrix mapping, +post-green source review and preservation checks. Step-07/07A remain NOT +ACCEPTED pending manual review; Step-08 remains blocked and was not started. diff --git a/prompts/ROADMAP.md b/prompts/ROADMAP.md index acfbefe..3bb5c94 100644 --- a/prompts/ROADMAP.md +++ b/prompts/ROADMAP.md @@ -3,15 +3,16 @@ ## Status and authority - Initialized: 2026-10-28. -- Current phase: Step-07A mostly corrected; source-close/capture-unregistration lock ordering remains. -- Active assignment: [Step-07B](Step-07B.md), ready for manual worker execution. -- Last accepted milestone: Step-06 with Step-06A, accepted 2026-10-30. -- Last accepted correction: Step-06A; all Step-06 findings closed. -- Outstanding correction: existing R-03 safe-close invariant; source disposal can deadlock with capture failure unregistration. +- Current phase: corrected recording/archive accepted; saved telemetry replay next. +- Active assignment: [Step-08](Step-08.md), ready for manual worker execution. +- Last accepted milestone: Step-07 with Step-07A/Step-07B, accepted 2026-10-30. +- Last accepted correction: Step-07B; all Step-07 findings closed. +- Outstanding corrections: none. - Step-05 status: ACCEPTED after Step-05A/Step-05B, 2026-10-29. - Step-06 status: ACCEPTED after Step-06A, 2026-10-30. -- Step-07 status: REQUIRES FOCUSED CORRECTION / NOT ACCEPTED, reviewed 2026-10-30. -- Step-08 status: recorded telemetry replay; BLOCKED / NOT ASSIGNED until Step-07 acceptance. +- Step-07 status: ACCEPTED after Step-07A/Step-07B, 2026-10-30. +- Step-08 status: READY FOR WORKER; replay controls/clock not implemented yet. +- Step-09 status: calibration/simulated programming; BLOCKED / NOT ASSIGNED until replay acceptance. - Current state and handoff: [STATE.md](STATE.md). - Authority: the master charter, repository/handoff amendment, and the owner's 2026-10-28 architectural realignment. The latest decision cancels the dual-shell @@ -375,10 +376,10 @@ Step-05 with Step-05A/05B is accepted: the configured static/dynamic workflow, single session owner, independent range/quality, safe gauges, decisive tests and native evidence have been reviewed. Corrected Step-06/06A is accepted: unit defaults/conversions, rejected selections, unavailable readouts and raw/source -preservation are closed on inspected evidence. Step-07A corrects valid-source -round trips, typed/strict archive validation, normal registration release and -visible storage failures. Source-close overlap still requires Step-07B; that is -the only active assignment. Step-08 replay remains blocked. +preservation are closed on inspected evidence. Corrected Step-07/07A/07B is +accepted: actual bounded capture, source-faithful/strict archives, released +ownership, visible I/O failures and deadlock-free source close are supported. +Step-08 is the only active assignment for saved-data replay, not resimulation. Dependencies indicate acceptance prerequisites, not permission for automatic handoff. Later assignments refine these scopes using actual implementation evidence; they must not silently discard required capabilities. @@ -400,11 +401,11 @@ evidence; they must not silently discard required capabilities. | 05B | Independent range status and decisive dashboard tests | Remaining 05A R-03/testing contract | ACCEPTED 2026-10-29 | Frozen five-case/five-criterion contract satisfied; reported 134 unit/91 integration passes, clean Release/native recheck and actual pre-fix failure | | 06 | Imperial-default metric/imperial display units | 05 and corrections accepted; owner request 2026-10-29 | ACCEPTED 2026-10-30 AFTER 06A | Shared persisted Imperial/Road default, exact conversions, source/canonical invariants and corrected rejection/unavailable readouts inspected | | 06A | Preference rejection and unavailable display readouts | 06 review R-01/R-02 | ACCEPTED 2026-10-30 | Frozen seven-case/five-criterion contract satisfied; reported 179 unit/105 integration passes, clean Release/native evidence and honest binding-event versus browser coverage | -| 07 | Bounded telemetry recording and archive readback | 06 and corrections accepted | REQUIRES FOCUSED CORRECTION / NOT ACCEPTED | Most original scope corrected; concurrent source disposal/capture failure cleanup must not deadlock | -| 07A | Source-faithful archives, bounded lifetime and visible storage failures | 07 review R-01 through R-04 | REVIEWED - FOCUSED FOLLOW-UP REQUIRED | Reported 179 unit/131 integration passes and clean Release/native evidence; archive/I-O fixes supported, existing R-03 close-overlap remains | -| 07B | Deadlock-free source disposal during capture cleanup | Remaining 07A R-03 safe-close contract | READY FOR WORKER | Release lifetime-registration gate before resource/cancellation callbacks; controlled close/limit/failure interleavings with preserved data and single disposal completion | -| 08 | Recorded telemetry replay | 07 and corrections accepted | BLOCKED / NOT ASSIGNED | Play/pause/stop/restart/seek/navigation/speed feed shared presentation from recorded data, with explicit Replay identity and no live reads or physics rerun | -| 09 | Calibration management and simulated programming | 08 | PLANNED | Versioned definitions/diffs, verified baseline and backup, approved simulated write, readback/unrelated-data checks, audit and supported restore; no physical writes | +| 07 | Bounded telemetry recording and archive readback | 06 and corrections accepted | ACCEPTED 2026-10-30 AFTER 07A/07B | Actual bounded observations, source-faithful strict archive save/readback, visible errors, retained capture data and controlled safe-close evidence inspected | +| 07A | Source-faithful archives, bounded lifetime and visible storage failures | 07 review R-01 through R-04 | ACCEPTED 2026-10-30 AFTER 07B | Archive/typed-validation/normal-release/panel fixes and source-close follow-up all closed | +| 07B | Deadlock-free source disposal during capture cleanup | Remaining 07A R-03 safe-close contract | ACCEPTED 2026-10-30 | Shared disposal task published under gate, cleanup outside; actual pre-fix close/reset deadlocks and controlled correction, reported 179 unit/134 integration passes and native baseline | +| 08 | Recorded telemetry replay | 07 and corrections accepted | READY FOR WORKER | Strict saved-archive load, RecordedReplay context, prefix-correct gauges/navigation and one cancellable playback owner; no live calls, resimulation, interpolation or archive mutation | +| 09 | Calibration management and simulated programming | 08 accepted | BLOCKED / NOT ASSIGNED | Versioned definitions/diffs, verified baseline and backup, approved simulated write, readback/unrelated-data checks, audit and supported restore; no physical writes | | 10 | Local AI, knowledge, and validated runbooks | 09 | PLANNED | Replaceable local inference, applicable knowledge retrieval, structured logical runbook, independent validation/approval and simulation-only execution | | 11 | Comparative evaluation and complete synthetic demonstration | 10 | PLANNED | Complete demonstration below plus deterministic fault/regression matrix and independent verification of intended and unintended changes | | 12 | Verified OBDX Pro GT read-only integration | 11 plus documented device research/access | PLANNED / HARDWARE GATE | Source-backed device support matrix, explicit physical target, real read-only identification/diagnostics/telemetry recording where supported; no write path | @@ -811,24 +812,40 @@ history, not repeated redesign without evidence. Worker reports 179 unit + 131 integration passes (310 total, zero failed/ skipped), clean complete Release build and native static/dynamic save/restart/ readback smoke. The orchestrator ran no application checks. -- Most corrective scope is satisfied. One tightly coupled source-close edge - remains: cleanup starts under the lifetime gate and can wait for an observation - callback that now needs that gate to unregister. Prepared single-issue +- At that review most corrective scope was satisfied, but cleanup under the + lifetime gate could wait for an observation callback needing that gate to + unregister. Prepared single-issue [Step-07B](Step-07B.md) under existing R-03/C-06, with no archive or replay scope. +- Reviewed and accepted Step-07B against its frozen five-case/four-criterion + contract. Close ownership/resource snapshot/shared completion are published + under the lifetime gate; cancellation and cleanup start outside it. + Actual protocol/subscription barriers cover limit-close and failure-reset, + preserve the one-observation prefix/reason and show replacement isolation. +- Worker reports actual pre-fix blocked-operation/close failures, corrected + concurrent disposal/same-error/count assertions, complete Release build zero + warnings/errors and 179 unit + 134 integration passes (313 total, zero failed/ + skipped), plus native stopped-unsaved/source-close/save/restart/readback. + The orchestrator ran no application checks. +- Accepted corrected Step-07/07A/07B with no Step-07C, and prepared + [Step-08](Step-08.md) for a single saved-data playback owner and shared + numeric/bar presentation. Original source/archive bytes and unit behavior stay + immutable; equal timestamps, seek prefixes and cleanup are frozen up front. ### Remaining -- Worker execution of Step-07B, then review the controlled safe-close interleaving - and preserved original/corrective evidence before playback. -- Step-08 replay is blocked and not assigned. Recording/archive exists but remains - unaccepted; display units and earlier milestones remain accepted. +- Worker execution of Step-08, then one consolidated review against its frozen + replay prefix/time/owner/UI matrix and shared quality gate. Correct genuine + unmet requirements as Step-08A before calibration work. +- Step-09 calibration is blocked and not assigned. Replay is assigned work, + not implemented functionality; recording/archive and earlier work are accepted. - Profile/module metadata, synthetic virtual-module communication and deterministic dynamics/v2 and corrected dashboard are accepted; later features remain planned. Preserve the complete sequence/safety gates. ### Known blockers and uncertainties -The single open Step-07 R-03 follow-up is source-close lock ordering: +No blocking Step-07 deficiency remains. Its source-close follow-up below is +historical and closed by accepted Step-07B: - DiagnosticSession.DisposeAsync holds _lifetimeGate while invoking DisposeResourcesAsync. Its synchronous prefix can call capture disposal, @@ -840,12 +857,11 @@ The single open Step-07 R-03 follow-up is source-close lock ordering: needs a controlled competing close/limit-or-error callback, while retaining shared disposal completion, cleanup failures and frozen capture data. -This is source inspection, not an orchestrator-executed deadlock reproduction. -Step-07B must reproduce the interleaving safely and fix the root lock ordering. +That was source inspection, not an orchestrator-executed reproduction. Step-07B +supplied the actual bounded failing tests and corrected source ordering. -The four original Step-07 findings below are historical. Step-07A has corrected -their inspected archive/I-O/normal-release paths; only the safe-close overlap -above remains: +The four original Step-07 findings below are historical. Step-07A corrected +their archive/I-O/normal-release paths and Step-07B closed the safe-close overlap: - R-01: archive validation requires response bytes for every ProtocolError, even though an actual empty reply yields that outcome with null source trace bytes. diff --git a/prompts/STATE.md b/prompts/STATE.md index 83b0b0d..b58561c 100644 --- a/prompts/STATE.md +++ b/prompts/STATE.md @@ -5,14 +5,14 @@ | Field | Value | |---|---| | Updated | 2026-10-30 | -| Phase | Step-07A mostly corrected; source-close lock-order follow-up remains | -| Active step | Step-07B - Deadlock-free source disposal during capture cleanup | -| Assignment | [Step-07B.md](Step-07B.md) | +| Phase | Corrected recording/archive accepted; saved telemetry replay next | +| Active step | Step-08 - Recorded telemetry replay | +| Assignment | [Step-08.md](Step-08.md) | | Assignment status | READY FOR WORKER / AWAITING MANUAL HANDOFF | -| Expected worker report | `prompts/Step-07B-Report.md` - not yet created | -| Last accepted correction | Step-06A - accepted 2026-10-30 | -| Last accepted major milestone | Step-06 with Step-06A - accepted 2026-10-30 | -| Outstanding correction | Existing R-03 safe-close invariant: lifetime/observer lock inversion during failure/limit unregistration | +| Expected worker report | `prompts/Step-08-Report.md` - not yet created | +| Last accepted correction | Step-07B - accepted 2026-10-30 | +| Last accepted major milestone | Step-07 with Step-07A/Step-07B - accepted 2026-10-30 | +| Outstanding corrections | None | | Step-02 status | ACCEPTED after Step-02A | | Step-03 status | ACCEPTED after Step-03A/Step-03B | | Step-04 status | ACCEPTED after Step-04A/Step-04B | @@ -20,11 +20,12 @@ | Step-05 status | ACCEPTED after Step-05A/Step-05B | | Step-05A review | All original corrective criteria closed with Step-05B | | Step-06 status | ACCEPTED after Step-06A | -| Step-07 status | REQUIRES FOCUSED CORRECTION / NOT ACCEPTED | -| Step-07A review | Archive/I-O/normal release corrected; concurrent source-close edge requires Step-07B | -| Step-08 status | Recorded telemetry replay; BLOCKED until Step-07 acceptance | -| Worker execution | Step-07A returned; Step-07B not invoked | -| Immediate next action | User manually directs the worker to execute Step-07B only; no replay work | +| Step-07 status | ACCEPTED after Step-07A/Step-07B | +| Step-07A review | All original corrective criteria closed with Step-07B | +| Step-08 status | READY FOR WORKER; saved-data replay only | +| Step-09 status | Calibration/simulated programming; BLOCKED until Step-08 acceptance | +| Worker execution | Step-07B returned and accepted; Step-08 not invoked | +| Immediate next action | User manually directs the worker to execute Step-08 and shared quality gate only | | Next orchestrator action | After manual return, inspect the assignment, report, implementation, tests, Git changes, documentation and recorded command evidence | ## Repository baseline at initialization @@ -928,11 +929,11 @@ no application build/test, native launch or failing reproduction. Preserve the returned report unchanged. [Step-07A](Step-07A.md) consolidates the four existing requirements; Step-08 remains blocked and no replay assignment is created. -## Step-07A review and focused safe-close follow-up +## Historical Step-07A review and focused safe-close follow-up -Decision: **MOST SCOPE CORRECTED; FOCUSED FOLLOW-UP REQUIRED**, 2026-10-30. -Step-07/07A remain unaccepted until [Step-07B](Step-07B.md) closes the existing -R-03 safe-close requirement. Do not redo the supported archive/I-O fixes. +Decision at that review: most scope was corrected, but Step-07B was required +for the existing R-03 safe-close overlap. The closing review below now accepts +corrected Step-07/07A/07B without redoing the supported archive/I-O fixes. Reviewed [Step-07A](Step-07A.md), its [report](Step-07A-Report.md), all changed source paths and new regression bodies, the shared v2 validator, resource @@ -976,7 +977,42 @@ early. Preserve a single shared disposal completion and aggregate cleanup behavi The worker's seven added integration cases and 310-case/clean Release/native evidence remain valid positive reports, distinct from the missing competing-close -proof. All original reports remain unchanged; Step-08 is still blocked. +proof at that review. All original reports remain unchanged; Step-08 was blocked +until the closing review below. + +## Step-07B acceptance and corrected Step-07 + +Decision: **ACCEPTED**, 2026-10-30. Frozen C-01..C-05 and AC-01..AC-04 are +satisfied. Step-07 with Step-07A/07B is accepted; no Step-07C is required. + +Reviewed [Step-07B](Step-07B.md), its [report](Step-07B-Report.md), the focused +source disposal change, actual protocol barrier theory and concurrent-disposal +regression, related docs/README and existing Release/native artifacts. + +| Criterion | Decision | Evidence | +|---|---|---| +| AC-01 | ACCEPTED | Actual pre-fix close/limit and reset/error lock-cycle failures; shared task/state published under gate and cleanup invoked after release; controlled operations/close/reset finish with exact frozen prefix/reason and isolated replacement | +| AC-02 | ACCEPTED | Concurrent callers get the same task and cleanup exception, controlled resource disposes once, late registration rejects; original resource/control/transport ordering and aggregation preserved | +| AC-03 | ACCEPTED ON WORKER EXECUTION EVIDENCE | Reported complete nine-project Release build zero warnings/errors; 179 unit + 134 integration passes (313 total, zero failed/skipped); native static/dynamic unsaved retention, source close, save/restart/readback | +| AC-04 | ACCEPTED | Actual pre/post and native/control distinction, own post-green source-path review, related docs and protected/history/manual workflow preserved | + +The two barrier theory cases and one concurrent-dispose case preserve the prior +310 and yield 313. The five-second deadline is a safety guard after explicit +barriers, not a probabilistic timing race. The pre-fix focused process reported +both tasks incomplete and exited with failures; no native race is claimed. + +The helper records genuine cleanup success/failure in the already-published +shared completion. It does not remove unregistration, drop accepted observations, +clear required unsaved data or publish success before disposal. +The orchestrator ran no application build/test/native/workload command and did +not execute the deadlock reproduction. Graph/source/artifacts corroborate worker +execution evidence, not independent runtime verification. + +Original Step-07 and both corrective findings are closed. Preserve the 303-/ +310-/313-case reports and original archive/raw/source/native evidence. +[Step-08](Step-08.md) is prepared for saved-data replay with explicit +RecordedReplay context, deterministic prefix reduction and one playback owner. +No live source/session, physics execution or archive rewrite is authorized. ## Prerequisites, limitations, and known issues @@ -1004,24 +1040,24 @@ proof. All original reports remain unchanged; Step-08 is still blocked. Step-04B. Step-05's original and follow-up findings are closed. Preserve the 190-/ 202-/207-case reports and original numerical/native evidence distinctly. - Profile metadata/UI, synthetic diagnostics, deterministic dynamics/v2 and the - corrected dashboard/display units are accepted. Recording/archive exists but - is unaccepted. Replay, calibration values, AI and physical hardware operations + corrected dashboard/display units/recording archive are accepted. + Replay, calibration values, AI and physical hardware operations remain unimplemented. - No application build or test has been executed by the orchestrator. ## Review and progression gate -On manual return, evaluate Step-07B and the original Step-07/07A safe-close contract/shared gate using the +On manual return, evaluate Step-08 and its frozen replay contract/shared gate using the assignment, worker report, actual code/tests, dependency graph, Git changes, README/docs, and recorded build/test evidence. Do not accept solely on a success claim; do not claim independent runtime verification. -- Inspect lifetime-gate release before callbacks, controlled close/limit/error - interleavings, shared disposal/error completion and preserved capture state. - Preserve prior archive/I-O/native evidence; no new playback requirements. -- If accepted: close Step-07A/07B, accept corrected Step-07, update roadmap/state, prepare Step-08 replay +- Inspect explicit replay provenance, exact prefix/seek/tie semantics, one clock + owner/drain/generation, source/error projection, shared gauges/units and true + offline behavior. Do not add interpolation/streaming/layout/format requirements. +- If accepted: accept Step-08, update roadmap/state, prepare a bounded Step-09 calibration assignment and stop for manual handoff. -- If deficient: issue narrowly scoped Step-07C only for a material unmet contract/ +- If deficient: issue narrowly scoped Step-08A only for a material unmet contract/ regression, then stop. Planned new features are not corrections. - If blocked: retain the active step, document the prerequisite and required worker evidence; do not advance or mark unexecuted checks as successful. @@ -1090,13 +1126,15 @@ claim; do not claim independent runtime verification. | 2026-10-30 | Step-07A returned and reviewed | Archive/I-O/normal unregistration fixes and reported 310-case/clean Release/native evidence inspected; most corrective scope supported | | 2026-10-30 | Existing R-03 close-overlap remains | Lifetime gate held during synchronous disposal prefix can wait for observer callback that needs the lifetime gate to unregister | | 2026-10-30 | Step-07B prepared | Single lock-order/safe-close correction with controlled reproduction and preserved disposal/data semantics; replay remains blocked | +| 2026-10-30 | Step-07B returned and ACCEPTED | Actual pre-fix close/reset deadlocks, corrected gate/task ordering, preserved prefix and shared cleanup-failure assertions plus reported 313-case/clean Release/native evidence inspected | +| 2026-10-30 | Corrected Step-07 ACCEPTED | Original and 07A/07B criteria closed; source archive/limits/storage/default-unit behavior preserved; no 07C | +| 2026-10-30 | Step-08 prepared | Saved validated archive, explicit RecordedReplay context, prefix-correct gauges/seek and one cancellable clock; manual handoff pending, calibration blocked | ## Manual handoff instruction -Provide [Step-07B.md](Step-07B.md), original [Step-07.md](Step-07.md), -[Step-07A.md](Step-07A.md) and the shared +Provide [Step-08.md](Step-08.md) and the shared [worker gate](WORKER-QUALITY-GATE.md) to the separate worker and request execution -of the focused correction only. The worker must produce `prompts/Step-07B-Report.md` -and stop for review. Do not begin Step-08 replay. +of that assignment only. The worker must produce `prompts/Step-08-Report.md` +and stop for review. Do not begin Step-09 calibration. Return manually to the orchestrator for review. Reports, including final chat reports, must follow the single plain triple-backtick copy-window requirement. diff --git a/prompts/Step-07B-Report.md b/prompts/Step-07B-Report.md new file mode 100644 index 0000000..65cc53f --- /dev/null +++ b/prompts/Step-07B-Report.md @@ -0,0 +1,139 @@ +``` +# Step-07B worker report + +## Status + +COMPLETE — Step-07B implementation and verification are complete. Manual +orchestrator review remains pending. Step-07 and Step-07A remain NOT ACCEPTED; +Step-08 remains blocked and was not started. + +## Implementation + +`DiagnosticSession.DisposeAsync` now uses `_lifetimeGate` only to establish +close ownership, publish the closed state, snapshot/clear registered resources +and publish a single shared disposal task. After releasing the gate, one +caller starts cancellation and resource/control/transport cleanup. Concurrent +callers return the same task and observe its actual completion or failure. +Late resource registration remains rejected after close ownership begins. +Existing resource ordering and error aggregation are unchanged. + +The test-only `BarrierObservationProtocolClient` forwards actual calls and +observations from `SyntheticDiagnosticProtocolClient` and places a controlled +barrier in the actual capture subscription's dispose path. It exposes no +production race selector and does not mock the session, capture or protocol. +The cleanup-error regression uses a task-owned `IAsyncDisposable` resource. + +Changed files: + +- [DiagnosticSessionService.cs](../src/AutoForge.Application/Features/Vehicles/Diagnostics/DiagnosticSessionService.cs) +- [TelemetryRecordingIntegrationTests.cs](../src/tests/AutoForge.IntegrationTests/TelemetryRecordingIntegrationTests.cs) +- [README.md](../README.md) +- [docs/README.md](../docs/README.md) +- [architecture.md](../docs/architecture.md) +- [build-and-test.md](../docs/build-and-test.md) + +## Pre-fix reproduction + +Command: + +`dotnet test .\src\tests\AutoForge.IntegrationTests\AutoForge.IntegrationTests.csproj --configuration Release --filter "FullyQualifiedName~SessionCloseDuringCaptureDetach_DoesNotDeadlockOrLoseFailurePrefix"` + +Exit 1: the two theory cases failed and zero passed. Each case used controlled +barriers to establish the exact order: an actual diagnostic operation reached +capture limit/error detach after releasing the capture lock; close/reset +entered the second subscription-dispose call while the callback still owned +observation dispatch; then the callback barrier was released. After the +five-second safety deadline the test reported, for both the close and reset +cases, `Operation completed=False; close/reset completed=False.` This is the +observed lock cycle, not an inferred timing race or a compile failure. The +bounded xUnit process exited normally with the failures; no process tree had +to be terminated and no intentionally blocked task remained in a normal +passing run. + +## Frozen corrective matrix + +| Requirement | Evidence and result | +|---|---| +| C-01 normal stop/close with or without active capture | Existing stop-drain, repeated-registration, source-close retention, stopped saveability and cross-scope tests remain in the focused suite. Native static/dynamics workflow was also repeated. PASSED. | +| C-02 limit-detach competing with source close | `SessionCloseDuringCaptureDetach_DoesNotDeadlockOrLoseFailurePrefix(reset: False)` forces the callback/close interleaving above. Post-fix both operation and close complete, the one-observation prefix remains `Incomplete / LimitExceeded`, and session registration is released. PASSED. | +| C-03 observation-error detach competing with reset | The same regression with `reset: True` forces error detach against `DiagnosticSessionService.ResetAsync`. Post-fix both operation and reset complete; the original one-observation prefix remains `Error / ObservationFailure`; the replacement has a new session identity and its real signal read does not mutate the old snapshot. PASSED. | +| C-04 concurrent disposal, late registration and cleanup failure | `ConcurrentSessionDispose_SharesCompletionAndReportsCleanupFailure` verifies concurrent callers receive the same `Task`, late registration throws `ObjectDisposedException`, the controlled resource is disposed once, and both callers receive the same explicit cleanup exception. Barrier release is in `finally`. PASSED. | +| C-05 existing archive/registration/storage/panel/source/model/unit/native paths | All 310 Step-07A cases remain in the 313-test full suite; the three new theory/test cases pass. Fixed archive and capture limits, source semantics and native record/save/readback are preserved. PASSED. | +| AC-01 C-01..C-03 safe close/reset | Actual pre-fix lock-cycle reproduction and controlled post-fix completion/prefix/reason/replacement assertions. PASSED. | +| AC-02 C-04 shared cleanup semantics | Concurrent disposal identity/count, rejection and shared cleanup error assertions plus source ordering review. PASSED. | +| AC-03 C-05 regressions/build/native | 179 unit + 134 integration tests, nine-project Release build and native static/dynamics smoke. PASSED. | +| AC-04 scope/history/docs/self-review/report | Related documentation updated; protected files/history preserved; this report saved and worker stops before Step-08. PASSED. | + +## Post-fix commands and results + +Focused, build and full-suite commands ran sequentially: + +| Command | Exit | Result | +|---|---:|---| +| `dotnet test .\src\tests\AutoForge.IntegrationTests\AutoForge.IntegrationTests.csproj --configuration Release --filter "FullyQualifiedName~SessionCloseDuringCaptureDetach_DoesNotDeadlockOrLoseFailurePrefix|FullyQualifiedName~ConcurrentSessionDispose_SharesCompletionAndReportsCleanupFailure"` | 0 | Three cases passed, zero failed/skipped. | +| `dotnet test .\src\tests\AutoForge.IntegrationTests\AutoForge.IntegrationTests.csproj --configuration Release --filter "FullyQualifiedName~TelemetryRecordingIntegrationTests"` | 0 | 29 passed, zero failed/skipped. | +| `dotnet build .\src\AutoForge.slnx --configuration Release --no-restore` | 0 | All nine projects, including Windows Client; zero warnings and zero errors. The XAML source-generation notice was informational. | +| `dotnet test .\src\AutoForge.slnx --configuration Release --no-build` | 0 | 179 unit + 134 integration = 313 passed; zero failed/skipped. | + +The full suite preserves the 310-case Step-07A baseline (179 unit and 131 +integration) and adds the two barrier theory cases plus one concurrent-dispose +case. Existing fixed limits remain 4,096 observations, 16 MiB encoded +observations, 1 MiB header, 32 MiB archive and JSON depth 128. + +## Native versus controlled evidence + +The rebuilt Windows Client was operated through its local WebView2 DevTools +endpoint: + +- Static v1 recorded two actual operations (`read.dtcs` and `read.signals`), + stopped, then closed its source while the unsaved capture remained + inspectable. It was explicitly saved afterward. After app restart, the + archive loaded with its original raw bytes and two decoded signals. +- Dynamics v2 was explicitly stepped to model step 7 / 0.7 seconds. With + gauges hidden, two actual telemetry reads captured four actual + `read.signals` observations at the same model context. The capture was + stopped and the source closed before save; the stopped unsaved data remained + inspectable. After app restart, the archive loaded with raw data and decoded + source/model/configuration/run context. +- Both archives were loaded after restart. Metric/Road preferences remained + unchanged. Exact task-owned IDs were `3b6bbb098a094ac2ba10c042dcd4fbf0` + (static v1, two observations) and `ac5b4d4e814d4905a0d454292b4dde87` + (dynamics v2, four observations). After closing the Client and DevTools + listener, only those exact verified archive files were removed. The app's + existing/default WebView profile and unrelated application data were not + removed or reset. + +Native evidence verifies normal static/dynamic record, stop, source close, +retained capture, explicit save, restart and readback. The exact race is +proved by controlled integration barriers, not by a human-timed native claim. + +## Documentation, self-review and preservation + +Updated the architecture contract to state that close ownership, closed-state +publication, resource snapshot and shared task publication occur under the +lifetime gate, while cancellation and resource/control/transport disposal run +after the gate is released. The root and docs READMEs now describe the +Step-07B correction and link this report. The build guide records the actual +pre-fix reproduction, final commands/counts and native/control distinction. +Step-07 and Step-07A reports and their positive archive/native evidence remain +unchanged. + +Post-green self-review traced `DiagnosticSession.DisposeAsync` through close, +reset, cancellation, capture `StopForSourceClose`, limit/error detach, +unregistration, control and transport disposal. The gate is no longer held +while callbacks or observer drain run. `_disposeTask` is published before +another caller can start cleanup; registration checks the closed state under +the same gate; unregistration remains available after the close snapshot. +Disposal error aggregation and completion ordering are preserved. The +barrier tests assert operation and close/reset completion together, the exact +failure prefix/reason, registration release and replacement isolation. The +concurrent cleanup test releases its barrier in `finally`. No additional +issue was found in the review. + +`git diff --check` passed. Only the six listed implementation/test/documentation +files and this requested report were changed. Step-07/07A assignment files, +historical reports, Step-07B assignment, state, roadmap and quality gate remain +unchanged. No package/project/system/workload changes, staging, commit, push, +or Step-08 work occurred. Step-07/07A acceptance remains for manual review. +Stop here. +``` diff --git a/prompts/Step-08.md b/prompts/Step-08.md new file mode 100644 index 0000000..840ad14 --- /dev/null +++ b/prompts/Step-08.md @@ -0,0 +1,332 @@ +# Step-08 - Recorded telemetry replay + +## STEP IDENTIFIER + +Step-08. Corrected Step-07/07A/07B was accepted on 2026-10-30. +This is the sole active implementation assignment. Step-09 calibration is blocked. + +## STEP TITLE + +Replay validated saved captures through shared numeric/bar presentation with +explicit recorded provenance, deterministic navigation and one playback owner. + +## OBJECTIVE + +One user outcome: open a saved capture and inspect/replay its recorded signals +without a vehicle session, original profile catalogue or running model. +One primary new contract: a cancellable archive-only playback clock and exact +observation-prefix projection. + +Read [STATE.md](STATE.md), [ROADMAP.md](ROADMAP.md), +[archive v1](../docs/telemetry-archive-v1.md), [dashboard contracts](../docs/live-dashboard.md) +and [WORKER-QUALITY-GATE.md](WORKER-QUALITY-GATE.md). +Make the frozen matrix executable before coding, self-review after the first +green run, write `prompts/Step-08-Report.md`, and STOP. + +## ARCHITECTURAL CONTEXT + +Keep all nine projects, one native Client and pure generic Components. +Application owns replay loading/control/reduction; UI owns a routed feature +and shared presentation. Existing local archive storage and schema-v1 reader +are the only data input. No new project, dependency, transport, protocol, schema, +physics clock, generic timeline/event framework or global active-vehicle registry. +Source/tests remain under `src`, tests under `src/tests`. + +Use the existing +[ExecutionTargetKind.RecordedReplay](../src/AutoForge.Core/ExecutionTargets/ExecutionTargetKind.cs:3) +for current replay context, plus a replay-instance identity and capture ID. +Retain the archive's original provider/target/session/profile/config/run as +original metadata, not a current Simulation/PhysicalHardware connection. +Do not fabricate a DiagnosticSession, live provider/feed or verified identity. + +## CURRENT IMPLEMENTATION STATE + +Accepted features supply strict bounded v1 archives, actual raw observations +with positive-operation-bound decoded signals, complete/incomplete/error captures, +local file list/load, source/diagnostic/model timing and shared unit preferences. +Worker baseline: 179 unit + 134 integration passes (313 total, zero failed/ +skipped), clean full Release build and native capture/save/restart/readback. +The orchestrator did not run those commands. + +Useful current surfaces: + +- [ITelemetryArchiveStore](../src/AutoForge.Application/Features/Vehicles/Telemetry/Recording/ITelemetryArchiveStore.cs) + and [archive models](../src/AutoForge.Application/Features/Vehicles/Telemetry/Recording/TelemetryArchiveModels.cs). +- [Dashboard models](../src/AutoForge.Application/Features/Vehicles/Telemetry/LiveDashboard/LiveDashboardModels.cs) + and [live projection](../src/AutoForge.Application/Features/Vehicles/Telemetry/LiveDashboard/LiveDashboardAcquisition.cs). +- [Display-unit presentation](../src/AutoForge.UI/Features/DisplayUnits/DisplayUnitPresentation.cs), + [generic gauge](../src/AutoForge.Components/LiveDashboardGauge.razor) and + [current panel/editor](../src/AutoForge.UI/Features/Vehicles/Telemetry/LiveDashboard/LiveDashboardPanel.razor). + +Replay does not yet exist. Inspect Git/prior art and preserve accepted source, +archive, lifetime, unit and safety behavior. Do not overwrite dirty work/history. + +## REQUIRED IMPLEMENTATION + +### Frozen contract matrix + +| ID | Input/precondition | Required result | +|---|---|---| +| C-01 | Valid saved archive, with original source/profile/model no longer available | Explicit user load produces RecordedReplay context, immutable original metadata and a stopped before-first cursor; no live source operation or autoplay | +| C-02 | Four-observation fixture below | Exact recorded prefix/value/quality/error state at each applied count; recorded time is not inferred from diagnostic/model clocks | +| C-03 | Time seek between records, backward seek, Next/Previous, First/Stop/Restart | Rebuild only the defined prefix; no future/previous-run cache leaks. Definitions survive same-archive navigation; Stop/First clear values to before-first, not retained future measurements. | +| C-04 | Equal-time records, all timestamps zero, empty archive and non-signal operations | Time seek/timed play apply complete due-time groups in sequence; manual Next applies exactly one. Empty/zero duration has no division error or fabricated sample; non-signal records change cursor/inspection, not signal values. | +| C-05 | 0.25x/1x/1000x, controlled waits and mid-interval pause/resume | Pacing scales captured elapsed intervals only; pause freezes the exact playhead and resume waits only the remaining interval. Replayed data/results are rate-independent. | +| C-06 | Repeated Play, pending Pause/Stop cleanup, close/unmount, delayed old wake or scheduler fault | One owner; repeated active Play is idempotent; competing start/navigation rejects before mutation during drain; no stale publication. Fault is visible, cleanup still works and no orphan Playing state remains. | +| C-07 | Invalid/unloaded/closed command, rate NaN/infinity/outside range, invalid seek/ordinal/definition | Typed visible rejection before mutation; previous data/context/definitions/position/rate/ownership intact. No clamping a bad request into success. | +| C-08 | Incomplete/Error source capture or end of its retained data | Prominent original completion/reason remains; explicit per-load acknowledgement required before Play/Next/seek. Reaching playback end never turns the source capture Complete or invents lost samples. | +| C-09 | Positive/failed read.signals, Unknown/Uncertain/non-numeric/missing/unit-change states | Shared accepted source/quality/range/last-Good rules apply; last-known data is clearly recorded Stale with original sample time. Only the affected module changes; no future fill, interpolation, false zero or fabricated reply. | +| C-10 | Zero-to-eight numeric/bar gauges and global unit changes | Reuse shared validated configuration/projection/rendering and accepted conversion/draft rules; exact source units/bounds remain canonical, invalid edits atomic, hides/remounts do not own playback | +| C-11 | Failed/cancelled/stale replacement load or overlapping command | Previous validated replay remains intact; replacement allowed only while quiescent. Old load/wake cannot publish after close or a newer generation. No failed load is disguised as a healthy empty replay. | +| C-12 | Current Replay versus original archived Simulation/Physical metadata | All primary controls/readouts are clearly recorded, never live/current vehicle evidence; no diagnostic factories/controls, catalogue backfill, model rerun or recording-workspace rebind | +| C-13 | Replay operations and live coexistence | Archive bytes/header/values/units/quality/times/raw payloads stay identical; store Save and live diagnostic/physics calls remain zero. Existing 313 regressions and nine-project Release build remain intact. | +| C-14 | Actual Client route and saved static-v1/dynamic-v2 captures | Real storage/codec/Application/UI path supports load/play/pause/navigation/units/hide/end/close, including restart without original profiles; native observations distinguished from controlled timing/fault tests | + +### A. Archive-only context and load lifetime + +Add a small factory/feature-owned replay session and a `/telemetry-replay` route +with shared navigation. The page owns replay lifetime; closing/unmounting it +cancels/drains playback and pending load. Individual gauge components do not. +Re-entering the page can create a fresh replay session; no disposed scoped +singleton must be reused accidentally. + +List/load by explicit saved capture ID through the existing real archive store +and strict reader. Do not use the recording workspace's current live/unsaved +capture as a substitute or change its binding. Loading never auto-plays. +Ordinary live-host cleanup on route navigation stays as previously intended; +replay actions themselves never operate a live source. + +A successful new load resets cursor/data/definitions/partial acknowledgement +and establishes a new replay identity. Keep valid runtime speed and global +display preference. Failed validation/I/O preserves the old replay and exposes +the actual error. Loading/replacing while Playing or draining is explicitly +rejected: pause/stop and finish cleanup first. Busy load rejects competing +commands; cancellation/disposal invalidates its generation before late results. + +Loaded source completion must be visible throughout. For Incomplete or Error, +require a clearly labeled explicit acknowledgement bound to that load/capture +before data-producing playback/navigation; inspection/Stop/Close remain allowed. +Do not rewrite completion, original target or origin to label replay. + +### B. Deterministic recorded prefix and navigation + +Core playhead is integer TimeSpan ticks in [0, duration], where duration is the +last observation's captureElapsedTicks, or zero when empty. UTC start/stop, +diagnostic ticks and model time are original metadata, not playback duration. +Do not invent an unrecorded trailing interval from UTC or model time. + +Expose applied observation count (0..N) separately from time. The loaded/rewound/ +stopped cursor is **before first**: count 0, position 0, no published values. +This differs intentionally from SeekTime(0) if zero-time observations exist. + +- Next applies exactly the next observation; Previous reconstructs one fewer + applied observation. Ordinal navigation reconstructs exactly the requested + count, including zero. Set playhead to that last record's elapsed time (or 0). +- Time seek applies every observation with elapsed time <= the requested tick, + including all ties, and preserves the exact requested playhead between records. +- Time-driven play applies all due observations in archive sequence before + publishing a coherent prefix. Equal-time records never reorder by module, + diagnostic ticks or model time. +- Manual navigation requires a fully quiescent Stopped/Paused/Completed player + and leaves Paused unless the entire nonempty archive is applied, then Completed. +- Stop cancels/drains, then resets to before-first while retaining definitions, + loaded archive, speed and acknowledgement. First/Rewind performs the same data + reset while already quiescent. Restart is rewind-plus-Play, also quiescent only. + Play resumes Stopped/Paused; Completed requires explicit Restart or navigation. +- Empty loaded archive has duration zero and no samples; Play/Restart completes + immediately without a timer. Seek(0)/Stop/First remain an empty stopped cursor; + Next/Previous has a visible no-records rejection. With all records at time zero, + Play/Seek(0) applies all; manual Next can pause inside that group. Completion + depends on applied count, not position==duration alone. + +Use prefix reconstruction/reduction bounded by the accepted maximum 4,096 +observations. Backward seek resets current/last-Good/module-status caches before +replaying the prefix. Never keep a later module value when earlier time has not +supplied it. + +Pre-index binding metadata from actual positive snapshots in the loaded archive, +using the same first-observed module/signal/unit/origin rules as accepted live +data. This permits configuration before playback and keeps valid definitions +editable across seeks. The immutable metadata index contains no current values +and does not authorize publishing a future sample. Keep definitions across +navigation but show no-sample state when the applied prefix has not supplied +their data. Never infer values/bindings from the current vehicle catalogue. + +Decisive fixture (10,000,000 ticks = 1 second): + +| Sequence | Capture time | Actual archived operation | +|---|---|---| +| 1 | 1 s | module A read.signals: 850 rpm, Good | +| 2 | 2 s | module B read.signals: 12.6 V, Good | +| 3 | 2 s | module A read.signals: 1000 rpm, Uncertain | +| 4 | 4 s | module A read.signals: Timeout, no decoded successful signals | + +Seek 1.5 s applies only #1: A=850 Good, B has no sample. Seek 2 s applies #1..#3: +A=1000 Uncertain, B=12.6 Good. Seek 4 s applies all: A retains **850**, the last +Good sample, visibly Stale with #1's time/reason; B remains 12.6 Good. +Previous from #4 reconstructs #1..#3 and restores Uncertain 1000, not Stale. +Before-first clears both. No interpolation/extrapolation/smoothing is assigned. + +Reduce failures only for the affected read.signals module; probe/identity/DTC/ +clear observations advance inspection/time but do not manufacture signal data. +Keep actual source quality/time/config/run and raw outcome. Unit/origin changes, +missing/non-numeric/Unknown values and no-prior-Good errors follow accepted +dashboard semantics. Archive facts themselves are never mutated. + +### C. One cancellable playback owner + +Speed defaults to 1x, accepts finite 0.25x..1000x inclusively and is runtime-only. +Change it only while quiescent; while Playing/draining, reject with visible +"pause first" behavior and unchanged rate/control value. Use proper binding +feedback for rejected UI changes, not a second uncommitted settings state. + +Use monotonic TimeProvider plus a small cancellable wait seam for deterministic +tests; no new clock project/package. Elapsed wall time * selected speed advances +the capture-time playhead. Publish states consistent with the applied prefix; +smooth animation and a hard real-time SLA are not required. + +Pause freezes playhead at the request instant, applies the due prefix and +cancels/drains the old wait without holding a gate needed by cleanup. Resume +rebases from that position, not from the last sample timestamp. +For example, from 1.5 s at 2x, the 2 s group is due after 0.25 wall seconds. +Pausing after 0.10 wall seconds freezes at 1.7 s; resume needs 0.15 more seconds. + +Repeated Play while Playing shares the active owner. Any new owner/navigation/ +replacement eligibility check precedes state mutation, including after end of +data while prior owner cleanup is pending. Use generation/owner guards on every +late wait/load publication; no orphan Playing state or duplicate frame. +Preserve one shared cleanup completion for repeated Stop/Close as appropriate. +Invalid inputs leave prior state intact except explicit error notification. + +Clock/wait failures become visible Faulted replay with the last committed prefix +and original sample state intact, not successful end-of-data. Stop/Close still +drains/releases resources; recovery is explicit after cleanup. +Use overflow-safe tick arithmetic and bounded individual waits for large gaps, +with responsive cancellation, not a negative wrap or silent tail truncation. + +### D. Shared presentation and actual UI + +Reuse/extract small pure gauge definition-validation/projection/rendering helpers +from the existing live feature; do not duplicate them or create a dummy live +feed/session. Preserve live behavior through its existing tests. The replay +context is distinct from live DiagnosticSessionIdentity even if shared value/ +definition models are reused. + +Provide explicit archive selection, partial acknowledgement, Play/Pause/Stop/ +Restart/First/Next/Previous, elapsed-time and ordinal seek, speed, playhead/count/ +duration and source completion. Numeric/bar gauges retain the accepted in-memory +0..8 editor, exact unit binding, canonical bounds, precision and pinned draft +rules. Global units project display only; no archive/layout/cursor persistence. + +All gauges say recorded/Replay, including Good quality, paused/completed state +and last-known values. Show original capture/provider/profile/session/target/ +config/run, observation ordinal/capture time and per-sample diagnostic/model +time without implying simultaneous modules or a current live vehicle. +Raw/decoded inspection shows the current applied observation, with explicit +before-first/empty state. Navigation changes the replay prefix, not live state. +Reaching the end of partial data means "end of retained data", not source Complete. + +Hiding/remounting gauges or unit changes cannot start/stop/seek/read the player. +Only the replay feature owns its clock/lifetime. Keep keyboard/accessibility/ +safe text/error presentation and the existing routes/controls intact. + +## FILES OR PROJECTS EXPECTED TO CHANGE + +Application replay/context/controller/reduction, minimal pure shared gauge helper +extraction, UI replay route/navigation and shared renderer/editor adaptation, +composition only as needed, focused tests and related README/docs. +No new project/dependency, Simulation/Core physics/oracle implementation change, +diagnostic transport/provider or archive schema change. +Under `prompts`, create only `Step-08-Report.md`. + +## INTERFACE AND DEPENDENCY REQUIREMENTS + +Keep all nine project references and one Client, generic Components, archive-v1 +strictness/limits, source bytes/types/units/quality/time, unit preferences, source +capture lifetime and existing diagnostic/partial-discovery/verified-clear gates. +Current kind is RecordedReplay; original source kind remains immutable metadata. +No source/hardware permission, catalogue backfill, arbitrary raw-command execution, +cloud/AI, broad catches/silent fallback, invented samples or success-shaped errors. +No package/system/workload install/update/repair/rollback, staging/commit/push +or destructive Git. Preserve protected/history/orchestration files and dirty work. + +## TESTING REQUIREMENTS + +Map C-01..C-14 to named meaningful tests before handoff: + +- Build real validated saved v1/v2 archives through the accepted recorder/codec/ + temporary filesystem. Then close the sources; replay without original profiles/ + configurations. Use a spy/failing live-port composition and archive Save counter + to prove zero live operations/model calls/file rewrites. +- Assert the four-record fixture, between-time/backward/ordinal seeks, ties, + all-zero duration, empty/non-signal data and cleared future value/status caches + exactly. Verify metadata-only pre-indexing permits configuration before playback + without publishing any future measurements. + Test recorded reset/repeated model time without sorting or reconstructing it. +- Controlled monotonic time/waits prove rates, mid-gap pause/resume, delayed old + wakes, held cleanup, duplicate Play, generation replacement/unmount and faults. + Barriers establish ordering; no sleeps/polling or elapsed-performance proxies. + Release resources in finally and do not hold cleanup's gate across awaits. +- Real DI/rendered controls/editor verify invalid requests/rejections are visible + and atomic, partial acknowledgement/end labels, shared units/range/Unknown/ + Uncertain/Stale/source context and no data/control action on gauge rerender. +- Compare archive bytes and canonical source metadata/definitions before/after + repeated playback/seek/unit operations. Preserve the 313 baseline cases; + map necessary UI-only assertion changes without deleting safety/error checks. + +Run focused cases, then sequentially: + +- `dotnet build .\src\AutoForge.slnx --configuration Release --no-restore` +- `dotnet test .\src\AutoForge.slnx --configuration Release --no-build` + +Build all nine projects/native Client. Install/restore nothing absent a genuine +chosen-command missing dependency. +Native smoke: real saved static/dynamic captures, no live source open, new route +load/step/play/pause/seek/backward/units/gauges/speed/end/partial warning and route +close/re-enter. Restart the app and replay again without reimporting profiles. +Normal native timing is not controlled interleaving/fault proof. Verify the real +app storage root; do not assume LOCALAPPDATA redirects MAUI app data. Clean only +exact task-owned captures/profiles; preserve unrelated files/preferences. + +## DOCUMENTATION REQUIREMENTS + +Update README/index/architecture/build guide and replay/dashboard usage: explicit +RecordedReplay provenance, before-first versus zero-time seek, tie/prefix/last-Good +rules, time sources, rate/owner/drain/replacement policy, partial acknowledgement, +source immutability and actual native/controlled evidence. +Step-07/07A/07B is accepted; Step-08 worker status stays pending orchestrator review. +No interpolation, new recording durability, calibration/AI/hardware or physical +vehicle verification is claimed. + +## ACCEPTANCE CRITERIA + +| ID | Criterion | Evidence | +|---|---|---| +| AC-01 | C-01/C-11/C-12 explicit strict offline load and RecordedReplay provenance, immutable source and atomic replacement | Real file/store/context tests with no catalogue/live fallback and meaningful failed-load assertions | +| AC-02 | C-02..C-04/C-08/C-09 exact prefix/navigation/ties/empty/partial/quality behavior | Independent fixture expected values/counts/times/states, no future fill or fabricated samples | +| AC-03 | C-05..C-07 single cancellable owner, correct rate/pause/resume/drain/fault and rejection behavior | Controlled time/barrier lifecycle tests with exact playhead and prefix assertions | +| AC-04 | C-10 shared gauges/editor/units and honest original/current context in the real UI | Real rendered command/editor failures, preserved canonical bounds/drafts/source fields | +| AC-05 | C-13/C-14 all 313 regressions, meaningful new coverage, complete nine-project Release build/native playback pass | Exact commands/exits/warnings/per-project counts, zero-live/write spies and native/control distinction | +| AC-06 | Frozen matrix/self-review/docs/README describe actual output/state/time semantics and limits | Named executed cases and own post-green source-path review across producers/consumers | +| AC-07 | History/protection/dependencies/manual workflow preserved; report saved and worker stops | Preservation review and `prompts/Step-08-Report.md` | + +## OUT-OF-SCOPE WORK + +Resimulation, live diagnosis/recording changes, hardware/programming/calibration/ +AI, interpolation/extrapolation/charts, layout/config/cursor persistence, +archive migration/edit/export or new schema/limits/streaming durability, +new project/package/host and unrelated cleanup. +No future assignment, agents, automatic handoff, orchestration/shared-gate edit, +stage, commit or push. + +## REPORTING REQUIREMENTS + +Save `prompts/Step-08-Report.md` wholly inside exactly one plain triple-backtick +fence, no language tag/outside text/nested fences. Include identifier/title/status, +functions/files/interfaces, C-01..C-14/AC-01..AC-07 matrix with named executed +evidence, exact prefix/playhead/rate/negative/lifecycle outcomes and zero-live/ +write proof, commands/exits/warnings/per-project counts, native versus controlled +coverage, docs/README, own post-green source-path self-review, 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-09. diff --git a/src/AutoForge.Application/Features/Vehicles/Diagnostics/DiagnosticSessionService.cs b/src/AutoForge.Application/Features/Vehicles/Diagnostics/DiagnosticSessionService.cs index 60147d8..41112cb 100644 --- a/src/AutoForge.Application/Features/Vehicles/Diagnostics/DiagnosticSessionService.cs +++ b/src/AutoForge.Application/Features/Vehicles/Diagnostics/DiagnosticSessionService.cs @@ -179,6 +179,8 @@ public sealed class DiagnosticSession( public ValueTask DisposeAsync() { IAsyncDisposable[] resources; + TaskCompletionSource disposalCompletion; + Task disposalTask; lock (_lifetimeGate) { if (_disposeTask is not null) @@ -189,8 +191,26 @@ public sealed class DiagnosticSession( Interlocked.Exchange(ref _closed, 1); resources = _lifetimeResources.ToArray(); _lifetimeResources.Clear(); - _disposeTask = DisposeResourcesAsync(resources); - return new ValueTask(_disposeTask); + disposalCompletion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + disposalTask = _disposeTask = disposalCompletion.Task; + } + + _ = CompleteDisposalAsync(resources, disposalCompletion); + return new ValueTask(disposalTask); + } + + private async Task CompleteDisposalAsync( + IReadOnlyList resources, + TaskCompletionSource disposalCompletion) + { + try + { + await DisposeResourcesAsync(resources).ConfigureAwait(false); + disposalCompletion.TrySetResult(); + } + catch (Exception exception) + { + disposalCompletion.TrySetException(exception); } } diff --git a/src/tests/AutoForge.IntegrationTests/TelemetryRecordingIntegrationTests.cs b/src/tests/AutoForge.IntegrationTests/TelemetryRecordingIntegrationTests.cs index 353d1d2..0d06186 100644 --- a/src/tests/AutoForge.IntegrationTests/TelemetryRecordingIntegrationTests.cs +++ b/src/tests/AutoForge.IntegrationTests/TelemetryRecordingIntegrationTests.cs @@ -783,6 +783,130 @@ public sealed class TelemetryRecordingIntegrationTests Assert.Equal(0, GetLifetimeResourceCount(session)); } + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task SessionCloseDuringCaptureDetach_DoesNotDeadlockOrLoseFailurePrefix(bool reset) + { + using var directory = new TemporaryDirectory(); + var clock = new ManualTimeProvider(); + using var provider = CreateProvider(directory.Path, clock); + var (session, protocol) = await OpenBarrierSessionAsync(provider); + var limits = reset + ? TelemetryCaptureLimits.Default + : TelemetryCaptureLimits.Default with { MaximumObservations = 1 }; + var workspace = new TelemetryRecordingWorkspace( + provider.GetRequiredService(), + clock, + limits); + var barrier = new SubscriptionDisposeBarrier(); + protocol.ArmNextSubscription(barrier); + workspace.Start(session); + var endpoint = EngineEndpoint(session); + + Assert.True((await session.ReadSignalsAsync(endpoint)).IsSuccess); + if (reset) + { + clock.Advance(TimeSpan.FromTicks(-1)); + } + + var operation = Task.Run(() => session.ReadSignalsAsync(endpoint)); + Task? closeOrReset = null; + DiagnosticSession? replacement = null; + try + { + await barrier.CallbackDisposeEntered.Task.WaitAsync(TimeSpan.FromSeconds(5)); + closeOrReset = reset + ? Task.Run(async () => + replacement = await provider.GetRequiredService() + .ResetAsync(session)) + : Task.Run(async () => await session.DisposeAsync()); + await barrier.ClosingDisposeEntered.Task.WaitAsync(TimeSpan.FromSeconds(5)); + } + finally + { + barrier.ReleaseCallbackDispose.TrySetResult(); + } + + try + { + var dependentWork = Task.WhenAll(operation, closeOrReset!); + await Task.WhenAny(dependentWork, Task.Delay(TimeSpan.FromSeconds(5))); + Assert.True( + dependentWork.IsCompleted, + $"Operation completed={operation.IsCompleted}; close/reset completed={closeOrReset!.IsCompleted}."); + Assert.True((await operation).IsSuccess); + await closeOrReset!; + + var snapshot = Assert.IsType(workspace.CurrentCapture); + Assert.Single(snapshot.Observations); + Assert.Equal(1, snapshot.Completion!.ObservationCount); + Assert.Equal( + reset ? TelemetryCaptureState.Error : TelemetryCaptureState.Incomplete, + snapshot.Completion.State); + Assert.Equal( + reset + ? TelemetryCaptureStopReason.ObservationFailure + : TelemetryCaptureStopReason.LimitExceeded, + snapshot.Completion.StopReason); + Assert.Equal(0, GetLifetimeResourceCount(session)); + + if (reset) + { + Assert.NotNull(replacement); + Assert.NotEqual(session.Identity.SessionIdentifier, replacement.Identity.SessionIdentifier); + Assert.True((await replacement.ReadSignalsAsync(EngineEndpoint(replacement))).IsSuccess); + Assert.Single(snapshot.Observations); + } + else + { + Assert.True(session.IsClosed); + } + } + finally + { + barrier.ReleaseCallbackDispose.TrySetResult(); + if (replacement is not null) + { + await replacement.DisposeAsync(); + } + } + } + + [Fact] + public async Task ConcurrentSessionDispose_SharesCompletionAndReportsCleanupFailure() + { + using var directory = new TemporaryDirectory(); + using var provider = CreateProvider(directory.Path); + var session = await OpenStaticSessionAsync(provider); + var resource = new ControlledDisposalResource( + new InvalidOperationException("controlled cleanup failure")); + session.RegisterLifetimeResource(resource); + + var firstDispose = session.DisposeAsync().AsTask(); + Task? secondDispose = null; + try + { + await resource.DisposeEntered.Task.WaitAsync(TimeSpan.FromSeconds(5)); + secondDispose = session.DisposeAsync().AsTask(); + Assert.Same(firstDispose, secondDispose); + Assert.Throws(() => + session.RegisterLifetimeResource(new ControlledDisposalResource(null))); + Assert.Equal(1, resource.DisposeCallCount); + } + finally + { + resource.ReleaseDispose(); + } + + Assert.NotNull(secondDispose); + var firstFailure = await Assert.ThrowsAsync(() => firstDispose); + var secondFailure = await Assert.ThrowsAsync(() => secondDispose!); + Assert.Same(firstFailure, secondFailure); + Assert.Equal("controlled cleanup failure", firstFailure.Message); + Assert.Equal(1, resource.DisposeCallCount); + } + [Fact] public async Task CaptureCountLimit_Accepts4096OperationsAndMarksTheNextOperationIncomplete() { @@ -1320,6 +1444,35 @@ public sealed class TelemetryRecordingIntegrationTests ExecutionTargetKind.Simulation); } + private static async Task<(DiagnosticSession Session, BarrierObservationProtocolClient Protocol)> + OpenBarrierSessionAsync(IServiceProvider provider) + { + var prototype = await OpenStaticSessionAsync(provider); + var profile = prototype.Profile; + var identity = prototype.Identity; + await prototype.DisposeAsync(); + + var factory = provider.GetServices() + .Single(candidate => StringComparer.OrdinalIgnoreCase.Equals( + candidate.Descriptor.Target.ProviderIdentifier, + identity.Target.ProviderIdentifier)); + var transport = factory.OpenTransport(profile, identity); + var protocol = new SyntheticDiagnosticProtocolClient( + profile, + identity, + transport, + new DiagnosticLogicalClock()); + var barrierProtocol = new BarrierObservationProtocolClient(protocol); + return ( + new DiagnosticSession( + profile, + identity, + barrierProtocol, + transport, + new CancellationTokenSource()), + barrierProtocol); + } + private static int GetLifetimeResourceCount(DiagnosticSession session) { var resources = (ICollection)typeof(DiagnosticSession) @@ -1708,6 +1861,111 @@ public sealed class TelemetryRecordingIntegrationTests _inner.LoadAsync(captureId, cancellationToken); } + private sealed class SubscriptionDisposeBarrier + { + public TaskCompletionSource CallbackDisposeEntered { get; } = + new(TaskCreationOptions.RunContinuationsAsynchronously); + public TaskCompletionSource ClosingDisposeEntered { get; } = + new(TaskCreationOptions.RunContinuationsAsynchronously); + public TaskCompletionSource ReleaseCallbackDispose { get; } = + new(TaskCreationOptions.RunContinuationsAsynchronously); + } + + private sealed class BarrierObservationProtocolClient( + SyntheticDiagnosticProtocolClient inner) : + IDiagnosticProtocolClient, + IDiagnosticOperationObservationSource + { + private readonly IDiagnosticOperationObservationSource _observationSource = inner; + private SubscriptionDisposeBarrier? _nextSubscriptionBarrier; + + public DiagnosticSessionIdentity Session => inner.Session; + public IReadOnlyList ExpectedEndpoints => inner.ExpectedEndpoints; + public DiagnosticTraceSnapshot Trace => inner.Trace; + public int ProtocolVersion => _observationSource.ProtocolVersion; + public string? ObservationDispatchError => _observationSource.ObservationDispatchError; + + public void ArmNextSubscription(SubscriptionDisposeBarrier barrier) => + Interlocked.Exchange(ref _nextSubscriptionBarrier, barrier); + + public IDisposable Subscribe(Action observer) + { + var subscription = _observationSource.Subscribe(observer); + var barrier = Interlocked.Exchange(ref _nextSubscriptionBarrier, null); + return barrier is null + ? subscription + : new BarrierSubscription(subscription, barrier); + } + + public Task DiscoverAsync(CancellationToken cancellationToken = default) => + inner.DiscoverAsync(cancellationToken); + + public Task> ReadIdentityAsync( + DiagnosticEndpoint endpoint, + CancellationToken cancellationToken = default) => + inner.ReadIdentityAsync(endpoint, cancellationToken); + + public Task> ReadTroubleCodesAsync( + DiagnosticEndpoint endpoint, + CancellationToken cancellationToken = default) => + inner.ReadTroubleCodesAsync(endpoint, cancellationToken); + + public Task> ClearTroubleCodesAsync( + DiagnosticEndpoint endpoint, + CancellationToken cancellationToken = default) => + inner.ClearTroubleCodesAsync(endpoint, cancellationToken); + + public Task> ReadSignalsAsync( + DiagnosticEndpoint endpoint, + CancellationToken cancellationToken = default) => + inner.ReadSignalsAsync(endpoint, cancellationToken); + + private sealed class BarrierSubscription( + IDisposable innerSubscription, + SubscriptionDisposeBarrier barrier) : IDisposable + { + private int _disposeCalls; + + public void Dispose() + { + if (Interlocked.Increment(ref _disposeCalls) == 1) + { + barrier.CallbackDisposeEntered.TrySetResult(); + barrier.ReleaseCallbackDispose.Task.GetAwaiter().GetResult(); + } + else + { + barrier.ClosingDisposeEntered.TrySetResult(); + } + + innerSubscription.Dispose(); + } + } + } + + private sealed class ControlledDisposalResource(Exception? failure) : IAsyncDisposable + { + private readonly TaskCompletionSource _releaseDispose = + new(TaskCreationOptions.RunContinuationsAsynchronously); + private int _disposeCallCount; + + public TaskCompletionSource DisposeEntered { get; } = + new(TaskCreationOptions.RunContinuationsAsynchronously); + public int DisposeCallCount => Volatile.Read(ref _disposeCallCount); + public void ReleaseDispose() => _releaseDispose.TrySetResult(); + + public async ValueTask DisposeAsync() + { + Interlocked.Increment(ref _disposeCallCount); + DisposeEntered.TrySetResult(); + await _releaseDispose.Task; + if (failure is not null) + { + throw failure; + } + } + } + private sealed class TestNavigationManager : NavigationManager { public TestNavigationManager(string uri)