diff --git a/README.md b/README.md index 089ba1f..f8058fd 100644 --- a/README.md +++ b/README.md @@ -74,10 +74,12 @@ supported vehicle modules. Step-07 adds bounded in-memory recording of actual static-v1 and dynamic-v2 diagnostic operations, explicit source-sensitive local archive save/readback, strict schema-v1 validation, and shared recording/inspection controls in both -host workflows. The complete nine-project Release build, all 303 tests, native -capture/save/restart/readback smoke, and route-unmount retention check passed. -Worker completion is not orchestrator acceptance; see the -[Step-07 worker report](prompts/Step-07-Report.md). +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 +report](prompts/Step-07-Report.md) and [Step-07A corrective worker +report](prompts/Step-07A-Report.md). ### Planned diff --git a/docs/README.md b/docs/README.md index 3a28df7..33c9a7a 100644 --- a/docs/README.md +++ b/docs/README.md @@ -6,9 +6,10 @@ synthetic diagnostic vertical slice with its integrity corrections, the accepted Step-04/04A/04B synthetic dynamics work, the accepted Step-05/05A/05B 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. The full nine-project Release build, tests -and native save/restart/readback smoke are complete; worker acceptance remains -pending manual orchestrator review. +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. - [Architecture](architecture.md): actual nine-project graph, responsibilities, route ownership and provider/reference boundaries. @@ -56,5 +57,6 @@ historical/worker reports for their own execution evidence: [Step-05B corrective worker report](../prompts/Step-05B-Report.md), and [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). +[Step-07 worker report](../prompts/Step-07-Report.md) and +[Step-07A corrective worker report](../prompts/Step-07A-Report.md). Handoffs are manual; acceptance remains the orchestrator's responsibility. diff --git a/docs/architecture.md b/docs/architecture.md index 351a6d2..8b0fde1 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -130,6 +130,9 @@ observations, 16 MiB encoded observations, 1 MiB encoded header and 32 MiB archive input/output. A rejected next observation freezes an explicitly incomplete prefix. Close/reset stops capture but retains the old source context 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. The Client persists only explicitly saved archives under its app-local `recordings` directory. Application owns schema-v1 validation and file-storage @@ -138,7 +141,11 @@ no-overwrite publication. Readback uses a new store instance and does not rebind profiles or sessions. The format preserves capture elapsed time, diagnostic logical ticks and model time as distinct values. This is local archive persistence, not live disk streaming, crash durability, cryptographic -authenticity or playback. See the [archive-v1 guide](telemetry-archive-v1.md). +authenticity or playback. V2 archive checks share the source validator for +signal IDs, units, JSON kinds and finite values; v1 retains its opaque value +contract. Missing first-use storage is an empty catalogue, while invalid roots, +listing failures and save failures remain visible. See the +[archive-v1 guide](telemetry-archive-v1.md). The feature-local target-selection view model adapts explicit input to the existing Application resolver. The same target resolver is populated from the diff --git a/docs/build-and-test.md b/docs/build-and-test.md index c750239..c8ade6f 100644 --- a/docs/build-and-test.md +++ b/docs/build-and-test.md @@ -530,3 +530,53 @@ temporary directories and were removed. Metric/Road preferences were observed but not changed. See the [Step-07 worker report](../prompts/Step-07-Report.md) for frozen-matrix evidence, self-review and preservation details. Worker completion remains pending manual orchestrator review; no Step-08 work began. + +## Step-07A corrective recording verification + +Step-07 remains historically **NOT ACCEPTED**; this correction preserves its +303-case baseline and native smoke evidence. Before the fixes, the focused +recording selection ran 23 tests with 17 passing and 6 failing. The failures +reproduced actual boundary defects: an empty `TransportOutcome.Response` was +rejected before it could be archived; source-accepted case-variant identities +were rejected on readback; a positive signal read with a null snapshot escaped +as `NullReferenceException`; a stopped capture remained in the session +registration list; an existing file used as the storage root listed as empty; +and an actual panel save collision was followed by catalogue refresh, which +replaced the visible save error with a malformed-archive error. The latter was +also rerun against the real panel event before correction and failed because +the rendered error no longer contained the collision message. + +After correction, `TelemetryRecordingIntegrationTests` passed 26/26. The tests +exercise the actual v1/v2 observation and save/read paths, coherent raw-and- +decoded v2 mutation cases, deterministic stop/error/limit registration release, +invalid and missing storage roots, and the actual panel collision/error/retry +flow. The full Release build completed all nine solution projects, including +the Windows Client, with zero warnings and zero errors; the MAUI XAML source- +generation notice was informational. The full suite passed 179 unit and 131 +integration tests (310 total, zero failed and zero skipped). Exact commands: + +- `dotnet test .\src\tests\AutoForge.IntegrationTests\AutoForge.IntegrationTests.csproj --configuration Release --filter "FullyQualifiedName~TelemetryRecordingIntegrationTests"` (26/26) +- `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 + 131 integration; 310 total) + +The rebuilt Windows Client was exercised through its local WebView2 DevTools +endpoint. Static v1 captured seven actual operations, then stopped/saved, +closed its source, restarted the app, and loaded/inspected the archive. +Dynamics v2 was paused at model step 7 / 0.7 seconds; with gauges hidden, it +captured four actual `read.signals` operations, then stopped/saved, closed its +source, restarted, and loaded/inspected the archive. Both readbacks exposed raw +bytes and decoded signals/context; Metric/Road preferences remained unchanged. +Native captures were `034e287ae82e4e14aa4d55e78581cbf1` (static) and +`69def5834cf742ce9fa729dd4bea1b16` (dynamics). Those exact task-generated +archive files and temporary WebView2/profile directories were removed after +the Client and DevTools listener were closed. + +Native evidence verifies the normal record/stop/save/restart/load/source-close +workflow; it does not claim native filesystem-fault injection. Invalid roots, +save collisions, coherent malformed archives, and error/limit lifetime +cleanup are covered by controlled integration tests. The `LOCALAPPDATA` +override did not redirect MAUI `FileSystem.AppDataDirectory` in this +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. diff --git a/docs/telemetry-archive-v1.md b/docs/telemetry-archive-v1.md index a11808f..eb282a0 100644 --- a/docs/telemetry-archive-v1.md +++ b/docs/telemetry-archive-v1.md @@ -30,10 +30,12 @@ Stop establishes a cutover by detaching the observer through the session's serialized observation dispatcher. Callbacks already in dispatch drain before Stop freezes the result; operations dispatched after detachment are excluded. Repeated Start on the active owner is idempotent. A second owner for that -session is rejected. Session close/reset stops and detaches the old capture but -retains its source identity and samples for inspection and saving. A new source -does not inherit old samples. Unsaved capture replacement requires explicit -Save or Discard. +session is rejected. Stopped, failed, discarded and replaced owners are +unregistered from the source session's lifetime list; the workspace retains +the current stopped data needed for inspection/save. Session close/reset stops +and drains an active capture, then retains its source identity and samples for +inspection and saving. A new source does not inherit old samples. Unsaved +capture replacement requires explicit Save or Discard. The archive keeps three independent time values: @@ -127,14 +129,19 @@ responsePayloadBase64 signalSnapshot ``` -`sequence` starts at 1 and is contiguous. Raw payloads are canonical base64; -the nullable response is null only when no response bytes were received. -Outcomes are the defined diagnostic outcome tokens. Positive and negative -responses, and recorded protocol errors, require response bytes; timeout, -no-response and cancellation outcomes prohibit them. The raw synthetic request -and any well-formed positive/negative response are checked against the recorded -session, profile, configuration, correlation, endpoint, service, protocol -version and outcome. +`sequence` starts at 1 and is contiguous. Non-null raw payloads are canonical +base64. A null response means the trace retained no response bytes; this +includes an actual empty `TransportOutcome.Response` that became a +`ProtocolError`. The archive preserves that representation and does not invent +placeholder bytes. Positive and negative responses require response bytes; +timeout, no-response and cancellation outcomes prohibit them. A `ProtocolError` +may preserve malformed response bytes or have null bytes for an empty response. +The raw synthetic request and any positive/negative response are checked +against the recorded session, profile, configuration, correlation, endpoint, +service, protocol version and outcome. Identity fields use the source client's +existing comparison rules: selected response-envelope and module identities +are case-insensitive, while exact protocol tokens, signal IDs, units, payload +bytes and model/configuration values remain exact. `signalSnapshot` is null except for a successful `read.signals`. It contains: @@ -167,6 +174,11 @@ modelRunIdentifier properties inside that value are not interpreted as archive schema. Unit, quality, origin, diagnostic time and optional model/run context are source metadata, not display-unit projections. +Protocol v1 retains its nullable, non-numeric and otherwise opaque source +values. Protocol v2 uses the existing source contract: known signal IDs, exact +units and JSON kinds, finite numeric values, unique signal IDs within the +snapshot and nonnegative model time. Raw and decoded v2 values are both checked +against that contract and against each other. `completion` contains exactly: @@ -199,17 +211,24 @@ file; they are not silently hidden. List and Load enforce the 32 MiB input bound and validate the full schema. Corrupt matching files, unsupported versions, malformed/truncated JSON, unknown or duplicate schema properties, bad base64, inconsistent counts, -times, outcomes or source context are visible typed failures. Invalid data does -not replace an existing inspection. Valid incomplete archives remain -incomplete on readback. Readback proves file/schema consistency only; it does -not validate authenticity or source truth. +times, outcomes or source context are visible typed failures. A missing +first-use directory lists as empty; an existing file used as the storage root +or another listing failure is a typed visible error, not an empty catalogue. +The panel refreshes after a successful save only, preserving a failed save's +error and unsaved state. Invalid data does not replace an existing inspection. +Valid incomplete archives remain incomplete on readback. Readback proves +file/schema consistency only; it does not validate authenticity or source +truth. ## Verification The focused `TelemetryRecordingIntegrationTests` exercise real v1/v2 sessions, -more than 200 operations, all observed outcomes, controlled capture time, -ownership/Stop draining, session reset, exact count/observation/header/archive -boundaries, filesystem round-trip, collision/cancellation/I/O failures, -corrupt-file rejection and rendered controls in both routes. The complete -Release test totals, native-build status and manual-review limitations are -recorded in the [Step-07 worker report](../prompts/Step-07-Report.md). +more than 200 operations, all observed outcomes (including an actual empty +reply), case-variant source identities, coherent v2 archive edits, controlled +capture time, deterministic owner release, Stop draining, session reset, exact +count/observation/header/archive boundaries, filesystem round-trip, +collision/cancellation/I/O failures, corrupt-file rejection and actual panel +save/retry behavior. The original implementation evidence is preserved in the +[Step-07 worker report](../prompts/Step-07-Report.md); corrective execution +evidence and manual-review limitations are recorded in the +[Step-07A worker report](../prompts/Step-07A-Report.md). diff --git a/prompts/ROADMAP.md b/prompts/ROADMAP.md index bf660dc..acfbefe 100644 --- a/prompts/ROADMAP.md +++ b/prompts/ROADMAP.md @@ -3,14 +3,14 @@ ## Status and authority - Initialized: 2026-10-28. -- Current phase: Step-07 reviewed; source-fidelity, validation, lifetime and visible-I/O correction required. -- Active assignment: [Step-07A](Step-07A.md), ready for manual worker execution. +- 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 corrections: Step-07 R-01 through R-04 against the existing capture/archive contract. +- Outstanding correction: existing R-03 safe-close invariant; source disposal can deadlock with capture failure unregistration. - 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 CORRECTION / NOT ACCEPTED, reviewed 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. - Current state and handoff: [STATE.md](STATE.md). - Authority: the master charter, repository/handoff amendment, and the owner's @@ -375,9 +375,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-07 recording/archive exists -but is unaccepted pending Step-07A's four consolidated original-scope findings. -Step-07A is the only active assignment; Step-08 replay remains blocked. +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. 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. @@ -399,8 +400,9 @@ 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 CORRECTION / NOT ACCEPTED | Real capture/limits/storage/native paths exist; valid-source archive rejection, invalid-data boundary, released-capture retention and hidden I/O errors remain | -| 07A | Source-faithful archives, bounded lifetime and visible storage failures | 07 review R-01 through R-04 | READY FOR WORKER | Original C-04..C-11: valid traces round-trip, malformed archives reject with typed errors, discarded owners release, I/O failures remain visible | +| 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 | | 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 | @@ -803,11 +805,21 @@ history, not repeated redesign without evidence. context and native unsaved cross-route retention are supported. Withheld acceptance for four consolidated original-scope findings in [Step-07A](Step-07A.md); playback remains deferred, not a corrective requirement. +- Reviewed Step-07A's source-approved empty/case-variant round trips, shared + v2 shape validator, typed null-snapshot rejection, registration release, + failure-safe barrier test and actual panel save error/retry path. + 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 + [Step-07B](Step-07B.md) under existing R-03/C-06, with no archive or replay scope. ### Remaining -- Worker execution of Step-07A, then one consolidated review against its focused - matrix, original Step-07 contract and shared quality gate before playback. +- 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. - Profile/module metadata, synthetic virtual-module communication and deterministic @@ -816,7 +828,24 @@ history, not repeated redesign without evidence. ### Known blockers and uncertainties -Step-07 has four open findings against its original contract: +The single open Step-07 R-03 follow-up is source-close lock ordering: + +- DiagnosticSession.DisposeAsync holds _lifetimeGate while invoking + DisposeResourcesAsync. Its synchronous prefix can call capture disposal, + which waits for the protocol's _observersGate to drain an observation callback. +- A limit/error callback holds _observersGate and newly calls + UnregisterLifetimeResource, which needs _lifetimeGate. If close begins + unsubscribe before that callback finishes, the two sides can wait forever. +- Existing release-count and normal close tests are sequential. The correction + 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. + +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: - R-01: archive validation requires response bytes for every ProtocolError, even though an actual empty reply yields that outcome with null source trace bytes. @@ -834,9 +863,9 @@ Step-07 has four open findings against its original contract: empty directory. The panel always refreshes after SaveAsync, including after the workspace reports failure, clearing that error with a successful list status. -These are source-path findings, not orchestrator-executed reproductions. Step-07A -must prove the applicable pre-fix failures and preserve all supported recording/ -limit/native behavior. No archive-format expansion or playback is requested. +Step-07A supplied actual pre-fix failures and corrected protocol/file/registration/ +panel tests plus native recheck. Those results remain preserved; no archive-format +expansion or playback is requested by the focused follow-up. No blocking Step-06 deficiency remains. Its two findings below are historical and closed by accepted Step-06A: diff --git a/prompts/STATE.md b/prompts/STATE.md index 2723a2f..83b0b0d 100644 --- a/prompts/STATE.md +++ b/prompts/STATE.md @@ -5,14 +5,14 @@ | Field | Value | |---|---| | Updated | 2026-10-30 | -| Phase | Step-07 reviewed; archive/lifetime/visible-I/O correction required | -| Active step | Step-07A - Source-faithful archives and bounded capture cleanup | -| Assignment | [Step-07A.md](Step-07A.md) | +| 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) | | Assignment status | READY FOR WORKER / AWAITING MANUAL HANDOFF | -| Expected worker report | `prompts/Step-07A-Report.md` - not yet created | +| 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 corrections | Step-07 R-01 through R-04 against original frozen criteria | +| Outstanding correction | Existing R-03 safe-close invariant: lifetime/observer lock inversion during failure/limit unregistration | | 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,10 +20,11 @@ | 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 CORRECTION / NOT ACCEPTED | +| 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-07 returned; Step-07A not invoked | -| Immediate next action | User manually directs the worker to execute Step-07A with original Step-07 and shared quality gate | +| 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 | | Next orchestrator action | After manual return, inspect the assignment, report, implementation, tests, Git changes, documentation and recorded command evidence | ## Repository baseline at initialization @@ -879,9 +880,9 @@ allowed. Recording remains in memory until explicit save after Stop; no crash-durable/live-streaming or unlimited-duration claim is made. The next review must not demand the deferred Step-08 playback controls. -## Step-07 review and required correction +## Historical Step-07 review and required correction -Decision: **REQUIRES CORRECTION / NOT ACCEPTED**, 2026-10-30. +Decision at that review: **REQUIRES CORRECTION / NOT ACCEPTED**, 2026-10-30. Reviewed [Step-07](Step-07.md), its [report](Step-07-Report.md), all observation/ capture/workspace/codec/filesystem/UI changes, actual new integration tests, related docs/README, source lifetime registration, graph and Release artifacts. @@ -927,6 +928,56 @@ 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 + +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. + +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 +registration/disposal/observation lock flow, docs, graph and Release artifacts. + +| Area | Decision | Evidence | +|---|---|---| +| R-01 valid-source round trips | Corrected on inspected evidence | Empty received payload now reaches protocol validation as ProtocolError/null trace bytes; source-approved case-insensitive associations preserve original data/spellings; real source/file tests | +| R-02 strict typed archive boundary | Corrected on inspected evidence | Association guard precedes dereference; shared exact v2 ID/unit/kind/finite validation, duplicate IDs and negative model time; coherent raw/decoded test edits update byte bookkeeping | +| R-03 bounded release/teardown | Normal paths corrected; close overlap remains | Deterministic stopped/limit/error resource-count assertions and finally-based barrier release; new unregister call creates the lock cycle described below | +| R-04 storage/panel errors | Corrected on inspected evidence | Missing directory versus bad file root classified; explicit boolean save outcome prevents failed-save refresh; actual panel collision/error/retry and retained catalogue tests | +| Full build/tests/native/history | Positive evidence supported | Worker reports clean complete Release build, 179 unit + 131 integration passes (310 total, zero failed/skipped), native static/dynamic save/restart/load/close and protected history | + +### Remaining existing criterion: source close must not deadlock cleanup + +[DiagnosticSession.DisposeAsync](../src/AutoForge.Application/Features/Vehicles/Diagnostics/DiagnosticSessionService.cs:179) +calls DisposeResourcesAsync while holding _lifetimeGate. An async method executes +its synchronous prefix immediately; that prefix calls capture.DisposeAsync and +can block in source observation unsubscription before yielding. + +The protocol dispatch holds _observersGate while invoking capture callbacks. +On a limit/error stop, +[OnObservation](../src/AutoForge.Application/Features/Vehicles/Telemetry/Recording/SessionTelemetryCapture.cs:244) +now unregisters the capture through the same _lifetimeGate. + +Allowed interleaving: + +1. A callback owns the observer-dispatch gate and reaches failure/limit detach. +2. Source close owns the lifetime gate and starts unsubscribing/draining that callback. +3. The callback proceeds to unregister, waiting for the lifetime gate. +4. Close waits for the observer gate; neither side can finish. + +This is the existing Step-07 C-05/C-06 and Step-07A R-03/C-06 safe-close contract, +not new functionality. The orchestrator identified it by source inspection; +no deadlock test or application build/test/native/workload command was executed. +Step-07B requires a controlled, safely bounded actual reproduction. + +Do not resolve this by removing unregistration (restoring retained history), +weakening Stop drain, swallowing disposal errors or publishing close success +early. Preserve a single shared disposal completion and aggregate cleanup behavior. + +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. + ## Prerequisites, limitations, and known issues - Step-01A worker evidence establishes portable and native Windows compatibility @@ -960,17 +1011,17 @@ requirements; Step-08 remains blocked and no replay assignment is created. ## Review and progression gate -On manual return, evaluate Step-07A and the original Step-07 capture/archive contract/shared gate using the +On manual return, evaluate Step-07B and the original Step-07/07A safe-close 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 valid-source round trips, typed/strict archive rejection, bounded - lifetime release/finally cleanup and actual panel/catalogue failure visibility. - Preserve prior positive capture/native evidence; no new playback requirements. -- If accepted: close Step-07A, accept corrected Step-07, update roadmap/state, prepare Step-08 replay +- 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 and stop for manual handoff. -- If deficient: issue narrowly scoped Step-07B only for a material unmet contract/ +- If deficient: issue narrowly scoped Step-07C 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. @@ -1036,12 +1087,16 @@ claim; do not claim independent runtime verification. | 2026-10-30 | Step-07 returned and reviewed | Real observer/capture/archive/UI implementation and reported 303-case/clean Release/native save/restart/readback/unmount evidence inspected | | 2026-10-30 | Step-07 requires correction | Four original-scope findings: valid-source round trips, typed/strict archive semantics, released-capture retention/test cleanup, and catalogue/panel I/O visibility | | 2026-10-30 | Step-07A prepared | Consolidated corrective matrix with real pre-fix/negative/lifecycle/panel evidence; prior recording/unit/source behavior preserved and replay blocked | +| 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 | ## Manual handoff instruction -Provide [Step-07A.md](Step-07A.md), original [Step-07.md](Step-07.md) and the shared +Provide [Step-07B.md](Step-07B.md), original [Step-07.md](Step-07.md), +[Step-07A.md](Step-07A.md) and the shared [worker gate](WORKER-QUALITY-GATE.md) to the separate worker and request execution -of the correction only. The worker must produce `prompts/Step-07A-Report.md` +of the focused correction only. The worker must produce `prompts/Step-07B-Report.md` and stop for review. Do not begin Step-08 replay. 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-07A-Report.md b/prompts/Step-07A-Report.md new file mode 100644 index 0000000..87f1b0c --- /dev/null +++ b/prompts/Step-07A-Report.md @@ -0,0 +1,160 @@ +``` +# Step-07A worker report + +## Status + +COMPLETE — Step-07A worker execution and verification are complete. Manual +orchestrator review remains pending. Step-07 remains NOT ACCEPTED; Step-08 +remains blocked and was not started. + +## Contract and implementation + +Step-07A corrected the original Step-07 R-01 through R-04 without expanding +the archive format or changing the recorder design: + +- R-01: permitted an actual empty `TransportOutcome.Response` while preserving + its trace representation as `ProtocolError` with null response bytes; applied + only the source-approved case-insensitive identity comparisons for response + envelopes and module identities. +- R-02: validates signal association before dereference and reuses the shared + pure v2 signal-shape validator for known IDs, exact units/JSON kinds, finite + values and duplicate IDs. Negative model time is rejected; v1 opaque, + nullable and non-numeric values remain supported. +- R-03: removes stopped, failed, limit-stopped and source-closed captures from + the diagnostic session lifetime list and session ownership map while keeping + current stopped samples available for save/inspection. The controlled + Stop-drain regression releases its observer barrier in `finally`. +- R-04: distinguishes a legitimate missing first-use directory from invalid + roots/listing failures and preserves actual panel save errors by refreshing + only after explicit save success. + +Production changes are in [ProviderContracts.cs](../src/AutoForge.Diagnostics/ProviderContracts.cs), +[SyntheticDynamicSignalContract.cs](../src/AutoForge.Diagnostics/SyntheticDynamicSignalContract.cs), +[SyntheticDiagnosticProtocolClient.cs](../src/AutoForge.Diagnostics/SyntheticDiagnosticProtocolClient.cs), +[DiagnosticSessionService.cs](../src/AutoForge.Application/Features/Vehicles/Diagnostics/DiagnosticSessionService.cs), +[SessionTelemetryCapture.cs](../src/AutoForge.Application/Features/Vehicles/Telemetry/Recording/SessionTelemetryCapture.cs), +[TelemetryArchiveCodec.cs](../src/AutoForge.Application/Features/Vehicles/Telemetry/Recording/TelemetryArchiveCodec.cs), +[FileTelemetryArchiveStore.cs](../src/AutoForge.Application/Features/Vehicles/Telemetry/Recording/FileTelemetryArchiveStore.cs), +[TelemetryRecordingWorkspace.cs](../src/AutoForge.Application/Features/Vehicles/Telemetry/Recording/TelemetryRecordingWorkspace.cs), +and [TelemetryRecordingPanel.razor](../src/AutoForge.UI/Features/Vehicles/Telemetry/Recording/TelemetryRecordingPanel.razor). +Regression coverage is in +[TelemetryRecordingIntegrationTests.cs](../src/tests/AutoForge.IntegrationTests/TelemetryRecordingIntegrationTests.cs). + +## Frozen corrective matrix and acceptance mapping + +| Requirement | Evidence and result | +|---|---| +| R-01 / C-01 | Pre-fix the transport constructor rejected empty `Response` payloads. Post-fix `CaptureRecordsActualPositiveNegativeTimeoutNoResponseCancellationAndMalformedReplyBytes` exercises real observations; the empty reply stays `ProtocolError` with null response bytes and round-trips through save/new-store load without fabricated bytes or successful signals. PASSED. | +| R-01 / C-02 | Pre-fix case-variant source-approved envelope/module identities failed archive association validation. `CaptureArchive_AcceptsCaseInsensitiveProtocolAssociations` exercises the real positive source response and archive round trip, retaining original bytes and spellings; exact request, signal ID, unit, protocol token and dynamics identities remain exact. PASSED. | +| R-02 / C-03 | Pre-fix a positive signal read with null snapshot escaped as `NullReferenceException`. `ArchiveWithPositiveSignalReadAndNullSnapshot_IsRejectedAsTypedInvalidArchive` now verifies typed `InvalidArchive` and that prior workspace inspection remains unchanged. PASSED. | +| R-02 / C-04 | `DynamicArchive_RejectsCoherentEditsThatViolateTheV2SignalContract` updates raw and decoded values coherently and recalculates encoded-byte bookkeeping for wrong unit/JSON kind, unknown/duplicate IDs and negative model time; the source contract is not weakened. PASSED. | +| R-02 / C-05 | Existing v1 nullable/non-numeric/opaque/Unknown handling, valid v1/v2 readbacks, malformed-reply evidence, exact source/context association and workspace inspection preservation remain covered by recording integration tests. PASSED. | +| R-03 / C-06 | `StoppedCapture_IsRemovedFromSessionLifetimeResources`, `CaptureFailure_ReleasesSessionLifetimeRegistration`, the count/byte-limit assertions, discard/replacement, and source-close tests check registration/ownership deterministically while stopped unsaved data remains inspectable/saveable and close draining remains intact. PASSED. | +| R-03 / C-07 | `CaptureOwnership_RejectsCompetingOwnerAndStopDrainsAcceptedCallbackBeforeReturning` releases the controlled observer barrier in `finally` before observer disposal/drain. PASSED. | +| R-04 / C-08 | `FileArchive_CancellationAndFilesystemFailureAreTypedAndLeaveNoPublishedArchive` and storage listing assertions verify an existing-file root/list failures are typed while a missing first-use directory remains empty. No permissions were changed. PASSED. | +| R-04 / C-09 | Pre-fix actual panel event evidence: `ActualPanelSaveFailure_RemainsVisibleAndSuccessfulRetryRefreshesCatalogue` failed because the collision error was replaced by a malformed-archive catalogue error after refresh. Post-fix it verifies the collision error remains rendered, the capture stays unsaved, the existing file is unchanged, and retry succeeds and refreshes. PASSED. | +| C-10 | The 303-test Step-07 baseline (179 unit + 124 integration) remains represented; seven additional focused integration cases yield 179 unit + 131 integration (310 total). Existing limits and source/model behavior pass, along with full Release and native workflow checks. PASSED. | +| AC-01 | Actual pre-fix R-01 reproductions and post-fix real protocol/file round trips for empty response and case-variant identities. PASSED. | +| AC-02 | Typed null-snapshot rejection, coherent v2 semantic negatives, and preserved valid v1/v2 cases. PASSED. | +| AC-03 | Deterministic owner registration checks for normal stop, failure/limit stop, discard/replacement and source close; barrier cleanup in `finally`. PASSED. | +| AC-04 | Typed store/workspace outcomes, invalid-root behavior and actual panel error/retry rendering. PASSED. | +| AC-05 | 303 prior cases plus seven integration cases, exact configured limits, nine-project Release build, full test suite and native baseline. PASSED. | +| AC-06 | Frozen matrix, documentation, post-green self-review, protected-file/history check, this report and stop-before-Step-08. PASSED. | + +## Actual pre-fix results + +The focused recording selection before correction ran 23 tests: 17 passed and +6 failed (exit code 1). Observed behavioral failures were: + +- Empty `TransportOutcome.Response` was rejected by the transport constructor + with `ArgumentException`, preventing the actual empty-reply trace from being + recorded and archived. +- Source-accepted case-variant response/module identities were rejected by + archive validation. +- A positive `read.signals` with null `signalSnapshot` escaped as + `NullReferenceException`. +- A stopped capture remained registered in the open diagnostic session + (observed resource count 1 where 0 was required). +- A storage root that was an existing file returned an empty catalogue rather + than a typed failure. +- The actual panel save collision path refreshed the catalogue after the + workspace had recorded the save error, replacing the visible collision + message with a malformed-archive message. + +The actual panel event was separately rerun before correction using: + +`dotnet test .\src\tests\AutoForge.IntegrationTests\AutoForge.IntegrationTests.csproj --configuration Release --filter "FullyQualifiedName~ActualPanelSaveFailure_RemainsVisibleAndSuccessfulRetryRefreshesCatalogue"` + +It failed as expected (1 failed, exit code 1): the rendered/workspace error +did not contain the collision message after the real handler refreshed the +catalogue. This was behavioral evidence, not a compilation failure. + +## Post-fix commands and results + +Commands ran sequentially after focused validation: + +| Command | Exit | Result | +|---|---:|---| +| `dotnet test .\src\tests\AutoForge.IntegrationTests\AutoForge.IntegrationTests.csproj --configuration Release --filter "FullyQualifiedName~TelemetryRecordingIntegrationTests"` | 0 | 26 passed, 0 failed, 0 skipped. | +| `dotnet build .\src\AutoForge.slnx --configuration Release --no-restore` | 0 | All nine projects, including Windows Client; 0 warnings, 0 errors. MAUI XAML source-generation notice was informational. | +| `dotnet test .\src\AutoForge.slnx --configuration Release --no-build` | 0 | Unit: 179 passed. Integration: 131 passed. Total: 310 passed, 0 failed, 0 skipped. | + +The focused final run includes actual source observations, coherent archive +mutations, registration-release tests, the actual panel handler/render +collision and retry test, and the 4,096-operation, 16 MiB observation, 1 MiB +header and 32 MiB archive boundaries. JSON depth remains 128. No limits were +raised. + +## Native versus controlled evidence + +The rebuilt Windows Client was exercised using its local WebView2 DevTools +endpoint: + +- Static v1 captured seven actual operations. It was stopped and saved, the + source was closed, and after app restart the archive loaded with its raw + request/response bytes and decoded source signals. +- Dynamics v2 was paused at model step 7 / 0.7 seconds. With gauges hidden, it + captured four actual `read.signals` operations. It was stopped and saved, + the source was closed, and after restart the archive loaded with raw bytes + and decoded signal/model context. +- Metric/Road preferences remained unchanged. Native captures were + `034e287ae82e4e14aa4d55e78581cbf1` (static) and + `69def5834cf742ce9fa729dd4bea1b16` (dynamics). Those exact task-generated + archive files and temporary WebView2/profile directories were removed + after closing the Client and DevTools listener. + +Native evidence covers the normal record/stop/save/restart/load/source-close +flow. Filesystem failures, malformed coherent archives and controlled +lifetime/barrier cases were tested through the actual store, codec, session, +workspace and panel integration paths; no native storage-fault injection is +claimed. In this environment the `LOCALAPPDATA` override did not redirect +MAUI `FileSystem.AppDataDirectory`; only exact task-owned captures were +removed, with no reset of app data or modification of preferences. + +## Documentation, self-review and preservation + +Updated [README.md](../README.md), [docs/README.md](../docs/README.md), +[docs/architecture.md](../docs/architecture.md), +[docs/telemetry-archive-v1.md](../docs/telemetry-archive-v1.md), and +[docs/build-and-test.md](../docs/build-and-test.md). They describe exact +source identity rules, v1/v2 archive validation, empty-response representation, +bounded capture ownership, typed catalogue failures, successful-save-only +refresh, the corrected build/test evidence and the native/controlled boundary. +The historical Step-07 results remain unchanged. + +Post-green self-review traced the actual transport-to-trace-to-capture-to-codec +path, the store/workspace/panel save and refresh path, session close and owner +unregistration, failure/limit cleanup, and controlled Stop drain. Validation +occurs before archive publication/inspection; invalid data does not replace +prior inspection; errors remain explicit; stopped in-memory snapshots remain +available when required. Rejected save does not mark the capture saved or +overwrite an existing file. Success refreshes as before. No additional issue +was found in this review. + +The 303 baseline cases, all nine projects, public source/profile/configuration +contracts and fixed capture/archive limits were preserved. No package, +workload, system or project was added or changed. Protected assignment/state/ +roadmap/gate/history files were unchanged. Only the requested new report was +added under `prompts`; no staging, commit, push, orchestration edit or Step-08 +work was performed. Stop here for manual review. +``` diff --git a/prompts/Step-07B.md b/prompts/Step-07B.md new file mode 100644 index 0000000..ce38b68 --- /dev/null +++ b/prompts/Step-07B.md @@ -0,0 +1,169 @@ +# 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. diff --git a/src/AutoForge.Application/Features/Vehicles/Diagnostics/DiagnosticSessionService.cs b/src/AutoForge.Application/Features/Vehicles/Diagnostics/DiagnosticSessionService.cs index 882daab..60147d8 100644 --- a/src/AutoForge.Application/Features/Vehicles/Diagnostics/DiagnosticSessionService.cs +++ b/src/AutoForge.Application/Features/Vehicles/Diagnostics/DiagnosticSessionService.cs @@ -107,6 +107,15 @@ public sealed class DiagnosticSession( } } + internal void UnregisterLifetimeResource(IAsyncDisposable resource) + { + ArgumentNullException.ThrowIfNull(resource); + lock (_lifetimeGate) + { + _lifetimeResources.Remove(resource); + } + } + public Task DiscoverAsync(CancellationToken cancellationToken = default) => InvokeAsync(protocol.DiscoverAsync, cancellationToken); diff --git a/src/AutoForge.Application/Features/Vehicles/Telemetry/Recording/FileTelemetryArchiveStore.cs b/src/AutoForge.Application/Features/Vehicles/Telemetry/Recording/FileTelemetryArchiveStore.cs index 88f9337..263e04d 100644 --- a/src/AutoForge.Application/Features/Vehicles/Telemetry/Recording/FileTelemetryArchiveStore.cs +++ b/src/AutoForge.Application/Features/Vehicles/Telemetry/Recording/FileTelemetryArchiveStore.cs @@ -116,7 +116,14 @@ public sealed class FileTelemetryArchiveStore : ITelemetryArchiveStore { if (!Directory.Exists(_rootDirectory)) { - return Array.Empty(); + if (IsMissingDirectoryRoot()) + { + return Array.Empty(); + } + + throw new TelemetryArchiveException( + TelemetryArchiveFailure.ReadFailure, + $"Recording storage root '{_rootDirectory}' is not an accessible directory."); } var captures = new List(); @@ -289,6 +296,51 @@ public sealed class FileTelemetryArchiveStore : ITelemetryArchiveStore Guid.TryParseExact(value, "N", out var parsed) && StringComparer.Ordinal.Equals(parsed.ToString("N"), value); + private bool IsMissingDirectoryRoot() + { + try + { + _ = File.GetAttributes(_rootDirectory); + return false; + } + catch (FileNotFoundException) + { + return HasNoFileAncestor(); + } + catch (DirectoryNotFoundException) + { + return HasNoFileAncestor(); + } + } + + private bool HasNoFileAncestor() + { + var ancestor = Path.GetDirectoryName(_rootDirectory); + while (ancestor is not null) + { + if (File.Exists(ancestor)) + { + return false; + } + + try + { + _ = File.GetAttributes(ancestor); + return true; + } + catch (FileNotFoundException) + { + ancestor = Path.GetDirectoryName(ancestor); + } + catch (DirectoryNotFoundException) + { + ancestor = Path.GetDirectoryName(ancestor); + } + } + + return true; + } + private static bool IsFileFailure(Exception exception) => exception is IOException or UnauthorizedAccessException or SecurityException or ArgumentException; diff --git a/src/AutoForge.Application/Features/Vehicles/Telemetry/Recording/SessionTelemetryCapture.cs b/src/AutoForge.Application/Features/Vehicles/Telemetry/Recording/SessionTelemetryCapture.cs index 51b5fa3..a4251c0 100644 --- a/src/AutoForge.Application/Features/Vehicles/Telemetry/Recording/SessionTelemetryCapture.cs +++ b/src/AutoForge.Application/Features/Vehicles/Telemetry/Recording/SessionTelemetryCapture.cs @@ -120,6 +120,7 @@ public sealed class SessionTelemetryCapture : IAsyncDisposable catch { subscription?.Dispose(); + session.UnregisterLifetimeResource(capture); ReleaseSessionOwnership(session, capture); throw; } @@ -215,6 +216,7 @@ public sealed class SessionTelemetryCapture : IAsyncDisposable } ReleaseSessionOwnership(_session, this); + _session.UnregisterLifetimeResource(this); Changed?.Invoke(); } @@ -322,6 +324,7 @@ public sealed class SessionTelemetryCapture : IAsyncDisposable } ReleaseSessionOwnership(_session, this); + _session.UnregisterLifetimeResource(this); } if (changed) @@ -383,6 +386,7 @@ public sealed class SessionTelemetryCapture : IAsyncDisposable } ReleaseSessionOwnership(_session, this); + _session.UnregisterLifetimeResource(this); Changed?.Invoke(); } diff --git a/src/AutoForge.Application/Features/Vehicles/Telemetry/Recording/TelemetryArchiveCodec.cs b/src/AutoForge.Application/Features/Vehicles/Telemetry/Recording/TelemetryArchiveCodec.cs index 05ee46a..cf30843 100644 --- a/src/AutoForge.Application/Features/Vehicles/Telemetry/Recording/TelemetryArchiveCodec.cs +++ b/src/AutoForge.Application/Features/Vehicles/Telemetry/Recording/TelemetryArchiveCodec.cs @@ -213,7 +213,7 @@ public static class TelemetryArchiveCodec } var requiresResponse = observation.Outcome is - DiagnosticOutcome.PositiveResponse or DiagnosticOutcome.NegativeResponse or DiagnosticOutcome.ProtocolError; + DiagnosticOutcome.PositiveResponse or DiagnosticOutcome.NegativeResponse; var prohibitsResponse = observation.Outcome is DiagnosticOutcome.NoResponse or DiagnosticOutcome.Timeout or DiagnosticOutcome.Cancelled; if ((requiresResponse && observation.ResponsePayloadBase64 is null) || @@ -222,12 +222,6 @@ public static class TelemetryArchiveCodec throw Invalid($"Observation {expectedSequence} response bytes do not match its operation outcome."); } - ValidateRequestAssociation(header, observation); - if (observation.Outcome is DiagnosticOutcome.PositiveResponse or DiagnosticOutcome.NegativeResponse) - { - ValidateResponseAssociation(header, observation); - } - var isSignalRead = StringComparer.Ordinal.Equals(observation.Service, DiagnosticServices.ReadSignals); var hasSignals = observation.SignalSnapshot is not null; if (hasSignals != (isSignalRead && observation.Outcome == DiagnosticOutcome.PositiveResponse)) @@ -235,13 +229,19 @@ public static class TelemetryArchiveCodec throw Invalid($"Observation {expectedSequence} has an incoherent decoded signal association."); } + ValidateRequestAssociation(header, observation); + if (observation.Outcome is DiagnosticOutcome.PositiveResponse or DiagnosticOutcome.NegativeResponse) + { + ValidateResponseAssociation(header, observation); + } + if (!hasSignals) { return; } var snapshot = observation.SignalSnapshot!; - if (!StringComparer.Ordinal.Equals(snapshot.ModuleIdentifier, observation.ModuleIdentifier) || + if (!StringComparer.OrdinalIgnoreCase.Equals(snapshot.ModuleIdentifier, observation.ModuleIdentifier) || snapshot.Signals is null || (header.ProtocolVersion == 1 && (snapshot.ModelStepIndex is not null || @@ -252,6 +252,7 @@ public static class TelemetryArchiveCodec (snapshot.ModelStepIndex is null or < 0 || snapshot.ModelTimeSeconds is null || !double.IsFinite(snapshot.ModelTimeSeconds.Value) || + snapshot.ModelTimeSeconds.Value < 0 || !StringComparer.Ordinal.Equals(snapshot.ModelConfigurationIdentifier, header.DynamicsConfigurationIdentifier) || !StringComparer.Ordinal.Equals(snapshot.ModelRunIdentifier, header.DynamicsRunIdentifier)))) { @@ -283,6 +284,15 @@ public static class TelemetryArchiveCodec } } + if (header.ProtocolVersion == 2 && + (snapshot.Signals.Select(signal => signal.SignalIdentifier) + .Distinct(StringComparer.OrdinalIgnoreCase).Count() != snapshot.Signals.Count || + snapshot.Signals.Any(signal => + !SyntheticDynamicSignalContract.IsValidValue(signal.SignalIdentifier, signal.Value, signal.Unit)))) + { + throw Invalid($"Observation {expectedSequence} contains a v2 signal that violates the source signal contract."); + } + ValidateDecodedSignals(header, observation, snapshot); } @@ -347,11 +357,11 @@ public static class TelemetryArchiveCodec if (!root.GetProperty("version").TryGetInt32(out var responseVersion) || responseVersion != header.ProtocolVersion || - !StringComparer.Ordinal.Equals(root.GetProperty("sessionIdentifier").GetString(), header.SessionIdentifier) || - !StringComparer.Ordinal.Equals(root.GetProperty("configurationIdentifier").GetString(), expectedConfiguration) || - !StringComparer.Ordinal.Equals(root.GetProperty("correlationIdentifier").GetString(), observation.CorrelationIdentifier) || - !StringComparer.Ordinal.Equals(root.GetProperty("targetAddress").GetString(), observation.Address) || - !StringComparer.Ordinal.Equals(root.GetProperty("service").GetString(), observation.Service) || + !StringComparer.OrdinalIgnoreCase.Equals(root.GetProperty("sessionIdentifier").GetString(), header.SessionIdentifier) || + !StringComparer.OrdinalIgnoreCase.Equals(root.GetProperty("configurationIdentifier").GetString(), expectedConfiguration) || + !StringComparer.OrdinalIgnoreCase.Equals(root.GetProperty("correlationIdentifier").GetString(), observation.CorrelationIdentifier) || + !StringComparer.OrdinalIgnoreCase.Equals(root.GetProperty("targetAddress").GetString(), observation.Address) || + !StringComparer.OrdinalIgnoreCase.Equals(root.GetProperty("service").GetString(), observation.Service) || root.GetProperty("success").ValueKind is not (JsonValueKind.True or JsonValueKind.False) || root.GetProperty("success").GetBoolean() != success || request is null) @@ -369,7 +379,7 @@ public static class TelemetryArchiveCodec data.ValueKind != JsonValueKind.Object || !data.TryGetProperty("moduleIdentifier", out var moduleIdentifier) || moduleIdentifier.ValueKind != JsonValueKind.String || - !StringComparer.Ordinal.Equals(moduleIdentifier.GetString(), observation.ModuleIdentifier)) + !StringComparer.OrdinalIgnoreCase.Equals(moduleIdentifier.GetString(), observation.ModuleIdentifier)) { throw Invalid($"Observation {observation.Sequence} positive response envelope or module identity is incoherent."); } @@ -410,7 +420,7 @@ public static class TelemetryArchiveCodec "signals" ] : ["moduleIdentifier", "logicalTimeTicks", "origin", "signals"]); - if (!StringComparer.Ordinal.Equals(data.GetProperty("moduleIdentifier").GetString(), observation.ModuleIdentifier) || + if (!StringComparer.OrdinalIgnoreCase.Equals(data.GetProperty("moduleIdentifier").GetString(), observation.ModuleIdentifier) || !StringComparer.Ordinal.Equals(data.GetProperty("origin").GetString(), isV2 ? "SYNTHETIC_DYNAMIC" : "SYNTHETIC_STATIC")) { throw Invalid($"Observation {observation.Sequence} decoded signal source does not match its endpoint."); @@ -428,6 +438,8 @@ public static class TelemetryArchiveCodec (!data.GetProperty("modelStepIndex").TryGetInt64(out var stepIndex) || stepIndex != snapshot.ModelStepIndex || !data.GetProperty("modelTimeSeconds").TryGetDouble(out var modelTime) || + !double.IsFinite(modelTime) || + modelTime < 0 || modelTime != snapshot.ModelTimeSeconds || !StringComparer.Ordinal.Equals( data.GetProperty("configurationIdentifier").GetString(), diff --git a/src/AutoForge.Application/Features/Vehicles/Telemetry/Recording/TelemetryRecordingWorkspace.cs b/src/AutoForge.Application/Features/Vehicles/Telemetry/Recording/TelemetryRecordingWorkspace.cs index 4f3a2a4..6674c08 100644 --- a/src/AutoForge.Application/Features/Vehicles/Telemetry/Recording/TelemetryRecordingWorkspace.cs +++ b/src/AutoForge.Application/Features/Vehicles/Telemetry/Recording/TelemetryRecordingWorkspace.cs @@ -197,11 +197,12 @@ public sealed class TelemetryRecordingWorkspace( NotifyChanged(); } - public async Task SaveAsync(bool savePartial, CancellationToken cancellationToken = default) + public async Task SaveAsync(bool savePartial, CancellationToken cancellationToken = default) { TelemetryCaptureSnapshot capture; SessionTelemetryCapture? owner; long generation; + var saved = false; lock (_gate) { EnsureNotBusy(); @@ -261,6 +262,8 @@ public sealed class TelemetryRecordingWorkspace( : $"Partial capture {capture.Header.CaptureId} was saved locally with an explicit incomplete state."; Error = null; } + + saved = true; } catch (TelemetryArchiveException exception) { @@ -279,6 +282,8 @@ public sealed class TelemetryRecordingWorkspace( NotifyChanged(); } + + return saved; } public async Task RefreshAsync(CancellationToken cancellationToken = default) diff --git a/src/AutoForge.Diagnostics/ProviderContracts.cs b/src/AutoForge.Diagnostics/ProviderContracts.cs index fb32605..e83ae61 100644 --- a/src/AutoForge.Diagnostics/ProviderContracts.cs +++ b/src/AutoForge.Diagnostics/ProviderContracts.cs @@ -182,11 +182,6 @@ public sealed class TransportReply throw new ArgumentOutOfRangeException(nameof(elapsedTicks)); } - if (outcome == TransportOutcome.Response && payload.IsEmpty) - { - throw new ArgumentException("A response outcome must contain a payload.", nameof(payload)); - } - if (outcome != TransportOutcome.Response && !payload.IsEmpty) { throw new ArgumentException("A non-response outcome cannot contain a response payload.", nameof(payload)); diff --git a/src/AutoForge.Diagnostics/SyntheticDiagnosticProtocolClient.cs b/src/AutoForge.Diagnostics/SyntheticDiagnosticProtocolClient.cs index da68366..fb44da2 100644 --- a/src/AutoForge.Diagnostics/SyntheticDiagnosticProtocolClient.cs +++ b/src/AutoForge.Diagnostics/SyntheticDiagnosticProtocolClient.cs @@ -9,25 +9,6 @@ public sealed class SyntheticDiagnosticProtocolClient : IDiagnosticOperationObservationSource { private const long DefaultTimeoutTicks = 5; - private static readonly IReadOnlyDictionary DynamicSignalShape = - new Dictionary(StringComparer.Ordinal) - { - ["engine.running"] = ("boolean", JsonValueKind.True), - ["engine.speed"] = ("rpm", JsonValueKind.Number), - ["vehicle.speed"] = ("m/s", JsonValueKind.Number), - ["engine.throttle"] = ("ratio", JsonValueKind.Number), - ["engine.load"] = ("ratio", JsonValueKind.Number), - ["engine.torque"] = ("N*m", JsonValueKind.Number), - ["engine.fuel-rate"] = ("kg/s", JsonValueKind.Number), - ["engine.fuel-consumed"] = ("kg", JsonValueKind.Number), - ["engine.temperature"] = ("degC", JsonValueKind.Number), - ["vehicle.distance"] = ("m", JsonValueKind.Number), - ["vehicle.acceleration"] = ("m/s^2", JsonValueKind.Number), - ["driver.brake"] = ("ratio", JsonValueKind.Number), - ["transmission.gear"] = ("gear", JsonValueKind.Number), - ["transmission.shift-count"] = ("count", JsonValueKind.Number), - ["transmission.coupling-slip"] = ("ratio", JsonValueKind.Number) - }; private readonly VehicleProfile _profile; private readonly IDiagnosticTransport _transport; private readonly IDiagnosticLogicalClock _clock; @@ -841,12 +822,11 @@ public sealed class SyntheticDiagnosticProtocolClient : string unit, string moduleIdentifier) { - if (!DynamicSignalShape.TryGetValue(signalIdentifier, out var shape) || - !StringComparer.Ordinal.Equals(unit, shape.Unit)) + if (!SyntheticDynamicSignalContract.IsValidValue(signalIdentifier, value, unit)) { throw new DiagnosticProtocolException( "INVALID_RESPONSE", - $"Dynamic signal '{signalIdentifier}' is unknown or has an invalid unit."); + $"Dynamic signal '{signalIdentifier}' is unknown or has an invalid unit or value."); } var engineSignal = signalIdentifier is @@ -865,23 +845,6 @@ public sealed class SyntheticDiagnosticProtocolClient : "INVALID_RESPONSE", $"Dynamic signal '{signalIdentifier}' came from the wrong module."); } - - if (shape.Kind == JsonValueKind.True) - { - if (value.ValueKind is not (JsonValueKind.True or JsonValueKind.False)) - { - throw new DiagnosticProtocolException("INVALID_RESPONSE", $"Dynamic signal '{signalIdentifier}' must be boolean."); - } - - return; - } - - if (value.ValueKind != JsonValueKind.Number || - !value.TryGetDouble(out var number) || - !double.IsFinite(number)) - { - throw new DiagnosticProtocolException("INVALID_RESPONSE", $"Dynamic signal '{signalIdentifier}' must be a finite JSON number."); - } } private static bool Same(string left, string right) => diff --git a/src/AutoForge.Diagnostics/SyntheticDynamicSignalContract.cs b/src/AutoForge.Diagnostics/SyntheticDynamicSignalContract.cs new file mode 100644 index 0000000..0ce298f --- /dev/null +++ b/src/AutoForge.Diagnostics/SyntheticDynamicSignalContract.cs @@ -0,0 +1,44 @@ +using System.Text.Json; + +namespace AutoForge.Diagnostics; + +public static class SyntheticDynamicSignalContract +{ + private static readonly IReadOnlyDictionary SignalShapes = + new Dictionary(StringComparer.Ordinal) + { + ["engine.running"] = ("boolean", JsonValueKind.True), + ["engine.speed"] = ("rpm", JsonValueKind.Number), + ["vehicle.speed"] = ("m/s", JsonValueKind.Number), + ["engine.throttle"] = ("ratio", JsonValueKind.Number), + ["engine.load"] = ("ratio", JsonValueKind.Number), + ["engine.torque"] = ("N*m", JsonValueKind.Number), + ["engine.fuel-rate"] = ("kg/s", JsonValueKind.Number), + ["engine.fuel-consumed"] = ("kg", JsonValueKind.Number), + ["engine.temperature"] = ("degC", JsonValueKind.Number), + ["vehicle.distance"] = ("m", JsonValueKind.Number), + ["vehicle.acceleration"] = ("m/s^2", JsonValueKind.Number), + ["driver.brake"] = ("ratio", JsonValueKind.Number), + ["transmission.gear"] = ("gear", JsonValueKind.Number), + ["transmission.shift-count"] = ("count", JsonValueKind.Number), + ["transmission.coupling-slip"] = ("ratio", JsonValueKind.Number) + }; + + public static bool IsValidValue(string signalIdentifier, JsonElement value, string unit) + { + if (!SignalShapes.TryGetValue(signalIdentifier, out var shape) || + !StringComparer.Ordinal.Equals(unit, shape.Unit)) + { + return false; + } + + if (shape.Kind == JsonValueKind.True) + { + return value.ValueKind is JsonValueKind.True or JsonValueKind.False; + } + + return value.ValueKind == JsonValueKind.Number && + value.TryGetDouble(out var number) && + double.IsFinite(number); + } +} diff --git a/src/AutoForge.UI/Features/Vehicles/Telemetry/Recording/TelemetryRecordingPanel.razor b/src/AutoForge.UI/Features/Vehicles/Telemetry/Recording/TelemetryRecordingPanel.razor index 433d0ed..900d37d 100644 --- a/src/AutoForge.UI/Features/Vehicles/Telemetry/Recording/TelemetryRecordingPanel.razor +++ b/src/AutoForge.UI/Features/Vehicles/Telemetry/Recording/TelemetryRecordingPanel.razor @@ -257,9 +257,12 @@ { try { - await Recording.SaveAsync(savePartial); + var saved = await Recording.SaveAsync(savePartial); _interactionError = null; - await Recording.RefreshAsync(); + if (saved) + { + await Recording.RefreshAsync(); + } } catch (InvalidOperationException exception) { diff --git a/src/tests/AutoForge.IntegrationTests/TelemetryRecordingIntegrationTests.cs b/src/tests/AutoForge.IntegrationTests/TelemetryRecordingIntegrationTests.cs index 816f9cb..353d1d2 100644 --- a/src/tests/AutoForge.IntegrationTests/TelemetryRecordingIntegrationTests.cs +++ b/src/tests/AutoForge.IntegrationTests/TelemetryRecordingIntegrationTests.cs @@ -1,3 +1,5 @@ +using System.Collections; +using System.Reflection; using System.Text; using System.Text.Json; using System.Text.Json.Nodes; @@ -8,6 +10,7 @@ using AutoForge.Application.Features.Vehicles.Simulation; using AutoForge.Application.Features.Vehicles.Telemetry.Recording; using AutoForge.Core.ExecutionTargets; using AutoForge.Core.Simulation; +using AutoForge.Core.Vehicles; using AutoForge.Diagnostics; using AutoForge.Simulation; using AutoForge.UI; @@ -16,6 +19,8 @@ using AutoForge.UI.Features.Vehicles.Simulation; using AutoForge.UI.Features.Vehicles.Telemetry.Recording; using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.Routing; +using Microsoft.AspNetCore.Components.RenderTree; +using Microsoft.AspNetCore.Components.Rendering; using Microsoft.AspNetCore.Components.Web; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; @@ -232,6 +237,11 @@ public sealed class TelemetryRecordingIntegrationTests return new TransportReply(TransportOutcome.Response, Encoding.UTF8.GetBytes("{"), 0); } + if (index == 7) + { + return new TransportReply(TransportOutcome.Response, ReadOnlyMemory.Empty, 0); + } + return await inner.SendAsync(requestBytes, cancellationToken); }); using var provider = CreateProvider(directory.Path, transportFactory: rewritingFactory); @@ -254,6 +264,9 @@ public sealed class TelemetryRecordingIntegrationTests var cancelledResult = await cancelledOperation; Assert.Equal(DiagnosticOutcome.Cancelled, cancelledResult.Outcome); + Assert.Equal( + DiagnosticOutcome.ProtocolError, + (await session.ReadSignalsAsync(endpoint)).Outcome); Assert.Equal( DiagnosticOutcome.ProtocolError, (await session.ReadSignalsAsync(endpoint)).Outcome); @@ -269,6 +282,7 @@ public sealed class TelemetryRecordingIntegrationTests DiagnosticOutcome.Timeout, DiagnosticOutcome.NoResponse, DiagnosticOutcome.Cancelled, + DiagnosticOutcome.ProtocolError, DiagnosticOutcome.ProtocolError ], observations.Select(item => item.Outcome)); @@ -284,11 +298,239 @@ public sealed class TelemetryRecordingIntegrationTests Assert.Null(observations[3].ResponsePayloadBase64); Assert.Null(observations[4].ResponsePayloadBase64); Assert.Equal("{", Encoding.UTF8.GetString(Convert.FromBase64String(observations[5].ResponsePayloadBase64!))); + Assert.Null(observations[6].ResponsePayloadBase64); Assert.Equal("controlled negative response", observations[1].Error); Assert.Contains("not valid synthetic protocol", observations[5].Error); - Assert.Equal(6, session.Trace.Entries.Count); + Assert.Equal(7, session.Trace.Entries.Count); Assert.Equal(DiagnosticOutcome.Cancelled, session.Trace.Entries[4].Outcome); Assert.Null(session.Trace.Entries[4].ResponsePayload); + Assert.Null(session.Trace.Entries[^1].ResponsePayload); + var archiveStore = new FileTelemetryArchiveStore(Path.Combine(directory.Path, "empty-response")); + await archiveStore.SaveAsync(currentCapture); + var restoredEmptyReply = await new FileTelemetryArchiveStore(Path.Combine(directory.Path, "empty-response")) + .LoadAsync(currentCapture.Header.CaptureId); + Assert.Equal(DiagnosticOutcome.ProtocolError, restoredEmptyReply.Observations[^1].Outcome); + Assert.Equal(observations[^1].Error, restoredEmptyReply.Observations[^1].Error); + Assert.Equal(observations[^1].RequestPayloadBase64, restoredEmptyReply.Observations[^1].RequestPayloadBase64); + Assert.Null(restoredEmptyReply.Observations[^1].ResponsePayloadBase64); + Assert.Null(restoredEmptyReply.Observations[^1].SignalSnapshot); + } + + [Fact] + public async Task CaptureArchive_AcceptsCaseInsensitiveProtocolAssociations() + { + using var directory = new TemporaryDirectory(); + var innerFactory = new SimulatedDiagnosticTransportFactory(SyntheticDiagnosticExamples.CreateDefinitions()); + var rewritingFactory = new RewritingDiagnosticTransportFactory( + innerFactory, + async (inner, request, requestBytes, cancellationToken) => + { + var reply = await inner.SendAsync(requestBytes, cancellationToken); + var response = JsonNode.Parse(reply.Payload.Span)!.AsObject(); + foreach (var property in new[] + { + "sessionIdentifier", + "configurationIdentifier", + "correlationIdentifier", + "targetAddress", + "service" + }) + { + response[property] = response[property]!.GetValue().ToUpperInvariant(); + } + + return new TransportReply( + TransportOutcome.Response, + Encoding.UTF8.GetBytes(response.ToJsonString()), + reply.ElapsedTicks, + reply.Detail); + }); + using var provider = CreateProvider( + directory.Path, + transportFactory: new CaseVariantEndpointTransportFactory(rewritingFactory)); + await using var session = await OpenStaticSessionAsync(provider); + var workspace = provider.GetRequiredService(); + + workspace.Start(session); + var endpoint = session.ExpectedEndpoints.Single(endpoint => + StringComparer.OrdinalIgnoreCase.Equals(endpoint.ModuleIdentifier, EngineModuleIdentifier)); + Assert.True((await session.ReadSignalsAsync(endpoint)).IsSuccess); + workspace.Stop(); + + var archiveStore = new FileTelemetryArchiveStore(directory.Path); + var capture = workspace.CurrentCapture!; + await archiveStore.SaveAsync(capture); + var restored = await new FileTelemetryArchiveStore(directory.Path).LoadAsync(capture.Header.CaptureId); + Assert.Equal(EngineModuleIdentifier.ToUpperInvariant(), restored.Observations[0].ModuleIdentifier); + Assert.Equal(DiagnosticServices.ReadSignals, restored.Observations[0].Service); + Assert.Equal( + EngineModuleIdentifier, + restored.Observations[0].SignalSnapshot!.ModuleIdentifier); + using var rawResponse = JsonDocument.Parse(Convert.FromBase64String(restored.Observations[0].ResponsePayloadBase64!)); + Assert.Equal( + "READ.SIGNALS", + rawResponse.RootElement.GetProperty("service").GetString()); + Assert.Equal( + EngineModuleIdentifier, + rawResponse.RootElement.GetProperty("data").GetProperty("moduleIdentifier").GetString()); + } + + [Fact] + public async Task ArchiveWithPositiveSignalReadAndNullSnapshot_IsRejectedAsTypedInvalidArchive() + { + using var directory = new TemporaryDirectory(); + using var provider = CreateProvider(directory.Path); + await using var session = await OpenStaticSessionAsync(provider); + var workspace = provider.GetRequiredService(); + workspace.Start(session); + Assert.True((await session.ReadSignalsAsync(EngineEndpoint(session))).IsSuccess); + workspace.Stop(); + + var archive = JsonNode.Parse(TelemetryArchiveCodec.Serialize(workspace.CurrentCapture!))!.AsObject(); + var observation = archive["observations"]![0]!.AsObject(); + observation["signalSnapshot"] = null; + RecalculateObservationBytes(archive); + var archiveBytes = Encoding.UTF8.GetBytes(archive.ToJsonString()); + + var exception = Assert.Throws(() => + TelemetryArchiveCodec.Deserialize(archiveBytes)); + Assert.Equal(TelemetryArchiveFailure.InvalidArchive, exception.Failure); + + var captureId = workspace.CurrentCapture!.Header.CaptureId; + Assert.True(await workspace.SaveAsync(savePartial: false)); + await workspace.LoadAsync(captureId); + var priorInspectionId = workspace.CurrentCapture!.Header.CaptureId; + await File.WriteAllBytesAsync(Path.Combine(directory.Path, $"{captureId}.json"), archiveBytes); + await workspace.LoadAsync(captureId); + + Assert.Equal(priorInspectionId, workspace.CurrentCapture!.Header.CaptureId); + Assert.NotNull(workspace.Error); + Assert.Contains("decoded signal association", workspace.Error); + } + + [Fact] + public async Task DynamicArchive_RejectsCoherentEditsThatViolateTheV2SignalContract() + { + using var directory = new TemporaryDirectory(); + using var provider = CreateProvider(directory.Path); + var configuration = PrepareDynamicsConfiguration(provider); + var session = await provider.GetRequiredService().OpenDynamicsAsync( + ProfileIdentifier, + ProfileRevision, + DynamicsDiagnosticTransportFactory.ProviderIdentifier, + ExecutionTargetKind.Simulation, + configuration); + await using var ownedSession = session; + await session.DynamicsControl!.StartAsync(); + await session.DynamicsControl.PauseAsync(); + await session.DynamicsControl.StepAsync(2); + var workspace = provider.GetRequiredService(); + workspace.Start(session); + Assert.True((await session.ReadSignalsAsync(EngineEndpoint(session))).IsSuccess); + workspace.Stop(); + + var capture = workspace.CurrentCapture!; + var baseline = TelemetryArchiveCodec.Serialize(capture); + Assert.Equal(capture.Observations[0].SignalSnapshot!.Signals.Count, + TelemetryArchiveCodec.Deserialize(baseline).Observations[0].SignalSnapshot!.Signals.Count); + var mutations = new Action[] + { + archive => + { + var context = GetArchiveSignalContext(archive); + context.RawSignals[0]!["unit"] = "invalid-unit"; + context.DecodedSignals[0]!["unit"] = "invalid-unit"; + SaveRawResponse(context); + }, + archive => + { + var context = GetArchiveSignalContext(archive); + context.RawSignals[0]!["value"] = "not-a-number"; + context.DecodedSignals[0]!["value"] = "not-a-number"; + SaveRawResponse(context); + }, + archive => + { + var context = GetArchiveSignalContext(archive); + context.RawSignals[0]!["signalIdentifier"] = "unknown.signal"; + context.DecodedSignals[0]!["signalIdentifier"] = "unknown.signal"; + SaveRawResponse(context); + }, + archive => + { + var context = GetArchiveSignalContext(archive); + var duplicateIndex = Enumerable.Range(0, context.DecodedSignals.Count) + .Single(index => context.DecodedSignals[index]!["signalIdentifier"]!.GetValue() == "engine.load"); + Assert.Contains(context.DecodedSignals, signal => + signal!["signalIdentifier"]!.GetValue() == "engine.throttle"); + context.RawSignals[duplicateIndex]!["signalIdentifier"] = "engine.throttle"; + context.DecodedSignals[duplicateIndex]!["signalIdentifier"] = "engine.throttle"; + SaveRawResponse(context); + }, + archive => + { + var context = GetArchiveSignalContext(archive); + context.RawResponse["data"]!["modelTimeSeconds"] = -1; + var decodedSnapshot = context.Observation["signalSnapshot"]!.AsObject(); + decodedSnapshot["modelTimeSeconds"] = -1; + foreach (var signal in decodedSnapshot["signals"]!.AsArray()) + { + signal!["modelTimeSeconds"] = -1; + } + + SaveRawResponse(context); + } + }; + + foreach (var mutation in mutations) + { + var edited = JsonNode.Parse(baseline)!.AsObject(); + mutation(edited); + RecalculateObservationBytes(edited); + var exception = Assert.Throws(() => + TelemetryArchiveCodec.Deserialize(Encoding.UTF8.GetBytes(edited.ToJsonString()))); + Assert.Equal(TelemetryArchiveFailure.InvalidArchive, exception.Failure); + } + } + + [Fact] + public async Task StoppedCapture_IsRemovedFromSessionLifetimeResources() + { + using var directory = new TemporaryDirectory(); + using var provider = CreateProvider(directory.Path); + await using var session = await OpenStaticSessionAsync(provider); + + for (var index = 0; index < 3; index++) + { + var capture = SessionTelemetryCapture.Start(session); + Assert.Equal(1, GetLifetimeResourceCount(session)); + + capture.Stop(); + + Assert.Equal(0, GetLifetimeResourceCount(session)); + } + + var workspace = new TelemetryRecordingWorkspace( + new FileTelemetryArchiveStore(directory.Path), + TimeProvider.System); + workspace.Start(session); + Assert.Equal(1, GetLifetimeResourceCount(session)); + Assert.True((await session.ReadSignalsAsync(EngineEndpoint(session))).IsSuccess); + workspace.Stop(); + var stopped = workspace.CurrentCapture!; + Assert.Equal(0, GetLifetimeResourceCount(session)); + Assert.Single(stopped.Observations); + Assert.True(await workspace.SaveAsync(savePartial: false)); + Assert.True(workspace.CurrentCapture!.IsSaved); + + workspace.Start(session); + Assert.Equal(1, GetLifetimeResourceCount(session)); + Assert.True((await session.ReadSignalsAsync(EngineEndpoint(session))).IsSuccess); + workspace.Stop(); + Assert.Equal(0, GetLifetimeResourceCount(session)); + workspace.Discard(); + Assert.Null(workspace.CurrentCapture); + Assert.Equal(0, GetLifetimeResourceCount(session)); } [Fact] @@ -344,18 +586,28 @@ public sealed class TelemetryRecordingIntegrationTests } }; var operation = Task.Run(() => session.ReadSignalsAsync(EngineEndpoint(session))); - await observationEntered.Task.WaitAsync(TimeSpan.FromSeconds(5)); - var stop = Task.Run(workspace.Stop); - await draining.Task.WaitAsync(TimeSpan.FromSeconds(5)); + Task? stop = null; + try + { + await observationEntered.Task.WaitAsync(TimeSpan.FromSeconds(5)); + stop = Task.Run(workspace.Stop); + await draining.Task.WaitAsync(TimeSpan.FromSeconds(5)); - Assert.True(workspace.IsStopping); - await Assert.ThrowsAsync(() => - Task.Run(() => workspace.Start(session)).WaitAsync(TimeSpan.FromSeconds(5))); - Assert.Equal(firstId, workspace.CurrentCapture!.Header.CaptureId); + Assert.True(workspace.IsStopping); + await Assert.ThrowsAsync(() => + Task.Run(() => workspace.Start(session)).WaitAsync(TimeSpan.FromSeconds(5))); + Assert.Equal(firstId, workspace.CurrentCapture!.Header.CaptureId); + } + finally + { + releaseObservation.TrySetResult(); + } - releaseObservation.TrySetResult(); Assert.True((await operation.WaitAsync(TimeSpan.FromSeconds(5))).IsSuccess); - await stop.WaitAsync(TimeSpan.FromSeconds(5)); + if (stop is not null) + { + await stop.WaitAsync(TimeSpan.FromSeconds(5)); + } var completed = workspace.CurrentCapture; Assert.NotNull(completed); @@ -383,6 +635,7 @@ public sealed class TelemetryRecordingIntegrationTests Assert.Equal(firstSession.Identity.SessionIdentifier, oldCapture.Header.SessionIdentifier); Assert.Equal(TelemetryCaptureStopReason.SourceClosed, oldCapture.Completion!.StopReason); Assert.Single(oldCapture.Observations); + Assert.Equal(0, GetLifetimeResourceCount(firstSession)); Assert.Throws(() => workspace.Start(newSession)); Assert.Equal(firstSession.Identity.SessionIdentifier, workspace.CurrentCapture!.Header.SessionIdentifier); @@ -465,6 +718,7 @@ public sealed class TelemetryRecordingIntegrationTests Assert.Equal(2, countLimited.Observations.Count); Assert.Equal(TelemetryCaptureState.Incomplete, countLimited.Completion!.State); Assert.Equal(TelemetryCaptureStopReason.LimitExceeded, countLimited.Completion.StopReason); + Assert.Equal(0, GetLifetimeResourceCount(countSession)); Assert.Equal(3, countSession.Trace.Entries.Count); await Assert.ThrowsAsync(() => countWorkspace.SaveAsync(savePartial: false)); await countWorkspace.SaveAsync(savePartial: true); @@ -508,6 +762,25 @@ public sealed class TelemetryRecordingIntegrationTests Assert.Empty(byteLimited.Observations); Assert.Equal(TelemetryCaptureState.Incomplete, byteLimited.Completion!.State); Assert.Equal(TelemetryCaptureStopReason.LimitExceeded, byteLimited.Completion.StopReason); + Assert.Equal(0, GetLifetimeResourceCount(oneBelowByteSession)); + } + + [Fact] + public async Task CaptureFailure_ReleasesSessionLifetimeRegistration() + { + using var directory = new TemporaryDirectory(); + var clock = new ManualTimeProvider(); + using var provider = CreateProvider(directory.Path, clock); + await using var session = await OpenStaticSessionAsync(provider); + var capture = SessionTelemetryCapture.Start(session, clock); + Assert.Equal(1, GetLifetimeResourceCount(session)); + + clock.Advance(TimeSpan.FromTicks(-1)); + Assert.True((await session.ReadSignalsAsync(EngineEndpoint(session))).IsSuccess); + + Assert.Equal(TelemetryCaptureState.Error, capture.Snapshot.Completion!.State); + Assert.Equal(TelemetryCaptureStopReason.ObservationFailure, capture.Snapshot.Completion.StopReason); + Assert.Equal(0, GetLifetimeResourceCount(session)); } [Fact] @@ -654,6 +927,10 @@ public sealed class TelemetryRecordingIntegrationTests public async Task FileArchive_CancellationAndFilesystemFailureAreTypedAndLeaveNoPublishedArchive() { using var directory = new TemporaryDirectory(); + var firstUseStore = new FileTelemetryArchiveStore(Path.Combine(directory.Path, "first-use", "recordings")); + Assert.Empty(await firstUseStore.ListAsync()); + Assert.False(Directory.Exists(Path.Combine(directory.Path, "first-use", "recordings"))); + using var provider = CreateProvider(directory.Path); await using var session = await OpenStaticSessionAsync(provider); var workspace = provider.GetRequiredService(); @@ -677,6 +954,88 @@ public sealed class TelemetryRecordingIntegrationTests Assert.Equal(TelemetryArchiveFailure.WriteFailure, failed.Failure); Assert.False(File.Exists(Path.Combine(fileAsDirectory, $"{capture.Header.CaptureId}.json"))); Assert.Equal("occupied", await File.ReadAllTextAsync(fileAsDirectory)); + + var listFailure = await Assert.ThrowsAsync(() => failingStore.ListAsync()); + Assert.Equal(TelemetryArchiveFailure.ReadFailure, listFailure.Failure); + } + + [Fact] + public async Task WorkspaceSaveFailure_ReturnsUnsuccessfulWithoutMarkingCaptureSaved() + { + using var directory = new TemporaryDirectory(); + var fileAsDirectory = Path.Combine(directory.Path, "not-a-directory"); + await File.WriteAllTextAsync(fileAsDirectory, "occupied"); + using var provider = CreateProvider(directory.Path); + await using var session = await OpenStaticSessionAsync(provider); + var workspace = new TelemetryRecordingWorkspace( + new FileTelemetryArchiveStore(fileAsDirectory), + TimeProvider.System); + workspace.Start(session); + Assert.True((await session.ReadSignalsAsync(EngineEndpoint(session))).IsSuccess); + workspace.Stop(); + + var saved = await workspace.SaveAsync(savePartial: false); + Assert.False(saved); + Assert.NotNull(workspace.Error); + Assert.False(workspace.CurrentCapture!.IsSaved); + } + + [Fact] + public async Task ActualPanelSaveFailure_RemainsVisibleAndSuccessfulRetryRefreshesCatalogue() + { + using var directory = new TemporaryDirectory(); + var archiveStore = new CollisionOnceArchiveStore(directory.Path); + using var provider = CreateProvider(directory.Path, archiveStore: archiveStore); + await using var session = await OpenStaticSessionAsync(provider); + var workspace = provider.GetRequiredService(); + workspace.Start(session); + Assert.True((await session.ReadSignalsAsync(EngineEndpoint(session))).IsSuccess); + workspace.Stop(); + + await using var renderer = new EventTestRenderer( + provider, + provider.GetRequiredService()); + var componentId = renderer.Attach(typeof(TelemetryRecordingPanel)); + await renderer.Dispatcher.InvokeAsync(() => renderer.RenderAsync( + componentId, + ParameterView.FromDictionary(new Dictionary + { + [nameof(TelemetryRecordingPanel.Session)] = session + }))); + + Assert.Equal(1, archiveStore.ListCallCount); + await renderer.Dispatcher.InvokeAsync(() => renderer.FindEventCallback( + componentId, + "telemetry-capture-save", + "onclick") + .InvokeAsync()); + + Assert.False(workspace.CurrentCapture!.IsSaved); + Assert.Contains("already exists", workspace.Error); + Assert.Contains("already exists", renderer.RenderedText(componentId)); + Assert.Equal(1, archiveStore.ListCallCount); + Assert.Equal( + CollisionOnceArchiveStore.ExistingArchiveContents, + await File.ReadAllTextAsync(archiveStore.CollisionPath!)); + + File.Delete(archiveStore.CollisionPath!); + await renderer.Dispatcher.InvokeAsync(() => renderer.FindEventCallback( + componentId, + "telemetry-capture-save", + "onclick") + .InvokeAsync()); + + Assert.True(workspace.CurrentCapture!.IsSaved); + Assert.Null(workspace.Error); + Assert.Single(workspace.SavedCaptures); + Assert.Equal(2, archiveStore.ListCallCount); + Assert.Contains("Saved locally", renderer.RenderedText(componentId)); + + archiveStore.FailListing = true; + await workspace.RefreshAsync(); + Assert.NotNull(workspace.Error); + Assert.Single(workspace.SavedCaptures); + Assert.Contains(workspace.Error, renderer.RenderedText(componentId)); } [Fact] @@ -911,7 +1270,8 @@ public sealed class TelemetryRecordingIntegrationTests string recordingsDirectory, TimeProvider? timeProvider = null, IDiagnosticTransportFactory? transportFactory = null, - string uri = "http://localhost/diagnostics") + string uri = "http://localhost/diagnostics", + ITelemetryArchiveStore? archiveStore = null) { var services = new ServiceCollection(); services.AddLogging(); @@ -933,6 +1293,14 @@ public sealed class TelemetryRecordingIntegrationTests services.AddSingleton(); services.AddSingleton(); services.AddAutoForgeTelemetryRecording(recordingsDirectory); + if (archiveStore is not null) + { + services.AddSingleton(archiveStore); + services.AddSingleton(new TelemetryRecordingWorkspace( + archiveStore, + timeProvider ?? TimeProvider.System)); + } + services.AddAutoForgeUi(); return services.BuildServiceProvider(new ServiceProviderOptions { ValidateOnBuild = true }); } @@ -952,6 +1320,45 @@ public sealed class TelemetryRecordingIntegrationTests ExecutionTargetKind.Simulation); } + private static int GetLifetimeResourceCount(DiagnosticSession session) + { + var resources = (ICollection)typeof(DiagnosticSession) + .GetField("_lifetimeResources", BindingFlags.Instance | BindingFlags.NonPublic)! + .GetValue(session)!; + return resources.Count; + } + + private static ( + JsonObject Observation, + JsonObject RawResponse, + JsonArray RawSignals, + JsonArray DecodedSignals) GetArchiveSignalContext(JsonObject archive) + { + var observation = archive["observations"]![0]!.AsObject(); + var responseBytes = Convert.FromBase64String(observation["responsePayloadBase64"]!.GetValue()); + var response = JsonNode.Parse(responseBytes)!.AsObject(); + return ( + observation, + response, + response["data"]!["signals"]!.AsArray(), + observation["signalSnapshot"]!["signals"]!.AsArray()); + } + + private static void SaveRawResponse(( + JsonObject Observation, + JsonObject RawResponse, + JsonArray RawSignals, + JsonArray DecodedSignals) context) => + context.Observation["responsePayloadBase64"] = + Convert.ToBase64String(Encoding.UTF8.GetBytes(context.RawResponse.ToJsonString())); + + private static void RecalculateObservationBytes(JsonObject archive) + { + var bytes = archive["observations"]!.AsArray() + .Sum(observation => (long)Encoding.UTF8.GetByteCount(observation!.ToJsonString())); + archive["completion"]!["observationBytes"] = bytes; + } + private static DynamicsConfiguration PrepareDynamicsConfiguration(IServiceProvider provider) { var profiles = provider.GetRequiredService(); @@ -1060,6 +1467,106 @@ public sealed class TelemetryRecordingIntegrationTests }); } +#pragma warning disable BL0006 + private sealed class EventTestRenderer(IServiceProvider services, ILoggerFactory loggerFactory) + : Renderer(services, loggerFactory) + { + public override Dispatcher Dispatcher { get; } = Dispatcher.CreateDefault(); + + public int Attach(Type componentType) => AssignRootComponentId(InstantiateComponent(componentType)); + + public Task RenderAsync(int componentId, ParameterView parameters) => + RenderRootComponentAsync(componentId, parameters); + + public EventCallback FindEventCallback( + int componentId, + string elementId, + string attributeName) + { + var result = FindNode(componentId, elementId, attributeName); + return result?.EventCallback is EventCallback callback + ? callback + : throw new InvalidOperationException( + $"Event callback '{attributeName}' for '{elementId}' was not rendered."); + } + + public string RenderedText(int componentId) + { + var frames = GetCurrentRenderTreeFrames(componentId); + var text = new System.Text.StringBuilder(); + for (var index = 0; index < frames.Count; index++) + { + if (frames.Array[index].FrameType == RenderTreeFrameType.Text) + { + text.Append(frames.Array[index].TextContent); + } + } + + return text.ToString(); + } + + protected override void HandleException(Exception exception) => + throw new InvalidOperationException("The test component renderer failed.", exception); + + protected override Task UpdateDisplayAsync(in RenderBatch renderBatch) => Task.CompletedTask; + + private NodeResult? FindNode(int componentId, string elementId, string targetAttribute) + { + var frames = GetCurrentRenderTreeFrames(componentId); + for (var index = 0; index < frames.Count; index++) + { + var frame = frames.Array[index]; + if (frame.FrameType == RenderTreeFrameType.Component) + { + var nested = FindNode(frame.ComponentId, elementId, targetAttribute); + if (nested is not null) + { + return nested; + } + + continue; + } + + if (frame.FrameType != RenderTreeFrameType.Element) + { + continue; + } + + var subtreeEnd = index + frame.ElementSubtreeLength; + var foundId = false; + object? eventCallback = null; + var attributeIndex = index + 1; + while (attributeIndex < subtreeEnd && + frames.Array[attributeIndex].FrameType == RenderTreeFrameType.Attribute) + { + var attributeFrame = frames.Array[attributeIndex]; + if (attributeFrame.AttributeName == "id" && + StringComparer.Ordinal.Equals(attributeFrame.AttributeValue?.ToString(), elementId)) + { + foundId = true; + } + + if (foundId && attributeFrame.AttributeName == targetAttribute) + { + eventCallback = attributeFrame.AttributeValue; + } + + attributeIndex++; + } + + if (foundId) + { + return new NodeResult(eventCallback); + } + } + + return null; + } + + private sealed record NodeResult(object? EventCallback); + } +#pragma warning restore BL0006 + private sealed class ManualTimeProvider : TimeProvider { private DateTimeOffset _utcNow = DateTimeOffset.Parse("2026-10-30T12:00:00.0000000+00:00"); @@ -1130,6 +1637,77 @@ public sealed class TelemetryRecordingIntegrationTests public void ReleaseSave() => _saveRelease.TrySetResult(); } + private sealed class CaseVariantEndpointTransportFactory(IDiagnosticTransportFactory inner) + : IDiagnosticTransportFactory + { + public DiagnosticProviderDescriptor Descriptor => inner.Descriptor; + + public IDiagnosticTransport OpenTransport(VehicleProfile profile, DiagnosticSessionIdentity identity) => + new CaseVariantEndpointTransport(inner.OpenTransport(profile, identity)); + + private sealed class CaseVariantEndpointTransport(IDiagnosticTransport innerTransport) + : IDiagnosticTransport + { + public IReadOnlyList ExpectedEndpoints => + Array.AsReadOnly(innerTransport.ExpectedEndpoints + .Select(endpoint => new DiagnosticEndpoint( + endpoint.ModuleIdentifier.ToUpperInvariant(), + endpoint.Address)) + .ToArray()); + + public ValueTask SendAsync( + ReadOnlyMemory request, + CancellationToken cancellationToken) => + innerTransport.SendAsync(request, cancellationToken); + + public ValueTask DisposeAsync() => innerTransport.DisposeAsync(); + } + } + + private sealed class CollisionOnceArchiveStore(string rootDirectory) : ITelemetryArchiveStore + { + private readonly FileTelemetryArchiveStore _inner = new(rootDirectory); + private int _failNextSave = 1; + private int _listCallCount; + + public const string ExistingArchiveContents = "protected existing archive"; + public int ListCallCount => Volatile.Read(ref _listCallCount); + public bool FailListing { get; set; } + public string? CollisionPath { get; private set; } + + public async Task SaveAsync( + TelemetryCaptureSnapshot capture, + CancellationToken cancellationToken = default) + { + if (Interlocked.Exchange(ref _failNextSave, 0) == 1) + { + CollisionPath = Path.Combine(rootDirectory, $"{capture.Header.CaptureId}.json"); + await File.WriteAllTextAsync(CollisionPath, ExistingArchiveContents, cancellationToken); + } + + await _inner.SaveAsync(capture, cancellationToken); + } + + public async Task> ListAsync( + CancellationToken cancellationToken = default) + { + Interlocked.Increment(ref _listCallCount); + if (FailListing) + { + throw new TelemetryArchiveException( + TelemetryArchiveFailure.ReadFailure, + "controlled list failure"); + } + + return await _inner.ListAsync(cancellationToken); + } + + public Task LoadAsync( + string captureId, + CancellationToken cancellationToken = default) => + _inner.LoadAsync(captureId, cancellationToken); + } + private sealed class TestNavigationManager : NavigationManager { public TestNavigationManager(string uri)