After Step 8
This commit is contained in:
parent
65eed575cb
commit
866831f864
25
README.md
25
README.md
|
|
@ -69,7 +69,7 @@ supported vehicle modules.
|
|||
constraint; supplied values must match a known module identity and never fill
|
||||
unknown module data. See the schema guide for exact grammar and limits.
|
||||
|
||||
### Implemented, pending manual review
|
||||
### Accepted recording/archive milestone
|
||||
|
||||
Step-07 adds bounded in-memory recording of actual static-v1 and dynamic-v2
|
||||
diagnostic operations, explicit source-sensitive local archive save/readback,
|
||||
|
|
@ -78,17 +78,29 @@ host workflows. Step-07A corrects source-faithful empty/case-variant response
|
|||
round-trips, v2 archive validation, capture lifetime release, and visible
|
||||
storage failures. Step-07B removes the source-close versus callback-unregister
|
||||
lock cycle while preserving shared disposal completion and failure reporting.
|
||||
The three worker reports retain separate evidence; none is orchestrator
|
||||
acceptance. See the [Step-07 worker
|
||||
Step-07 with Step-07A/Step-07B was accepted on 2026-10-30. The three
|
||||
worker reports retain separate historical execution evidence. See the [Step-07 worker
|
||||
report](prompts/Step-07-Report.md) and [Step-07A corrective worker
|
||||
report](prompts/Step-07A-Report.md) and [Step-07B lock-safety corrective
|
||||
report](prompts/Step-07B-Report.md).
|
||||
|
||||
### Implemented, pending manual review
|
||||
|
||||
Step-08 adds `/telemetry-replay`: explicit saved-capture loading without a
|
||||
profile catalogue, vehicle session or running model. One page-owned,
|
||||
cancellable playback clock projects exact recorded observation prefixes into
|
||||
the shared numeric/bar gauge editor. Navigation, partial-source acknowledgement,
|
||||
recorded provenance and runtime speed are explicit; source archives are never
|
||||
rewritten. See [replay usage and contracts](docs/telemetry-replay.md) and the
|
||||
[Step-08 worker report](prompts/Step-08-Report.md). Worker completion is not
|
||||
orchestrator acceptance.
|
||||
|
||||
### Planned
|
||||
|
||||
Replay, calibration values/editing/backups, AI and real hardware operations
|
||||
Calibration values/editing/backups, AI and real hardware operations
|
||||
require later approved assignments. Saved recordings are local file archives,
|
||||
not crash-durable live streaming or playback. Dynamics estimates are synthetic,
|
||||
not crash-durable live streaming. Replay does not resimulate or interpolate.
|
||||
Dynamics estimates are synthetic,
|
||||
not manufacturer prediction, vehicle compatibility, physical access, safe
|
||||
tuning advice or authorization. No capability is implemented merely because
|
||||
it appears in the product vision or roadmap.
|
||||
|
|
@ -105,7 +117,7 @@ browser-hosted WASM shell, Blazor Server host or second application executable.
|
|||
The application slices provide explicit target metadata resolution,
|
||||
vehicle-profile metadata import/list/select/export, dynamics configuration
|
||||
catalog/import/export, simulation-only diagnostic sessions, bounded session
|
||||
recording and archive inspection, and a shared display-unit preference with a
|
||||
recording, archive inspection and offline recorded replay, and a shared display-unit preference with a
|
||||
native local-preference adapter. The Client
|
||||
composes separate static and dynamics synthetic providers through
|
||||
provider-neutral factory contracts and a session-lifetime in-memory profile/
|
||||
|
|
@ -218,6 +230,7 @@ acceptance remains the orchestrator's responsibility.
|
|||
- [Simulation definitions and state](docs/simulation.md)
|
||||
- [Live dashboard usage and contracts](docs/live-dashboard.md)
|
||||
- [Telemetry archive schema v1 and recording](docs/telemetry-archive-v1.md)
|
||||
- [Recorded telemetry replay](docs/telemetry-replay.md)
|
||||
- [Vehicle-profile schema v1 and usage](docs/vehicle-profile-schema-v1.md)
|
||||
- [Build, tests and native smoke guide](docs/build-and-test.md)
|
||||
- [ADR-0001: historical .NET foundation](docs/adr-0001-headless-foundation.md)
|
||||
|
|
|
|||
|
|
@ -9,9 +9,10 @@ preference. Step-07 implements bounded session recording, local archive
|
|||
readback and shared host controls. Step-07A corrects archive fidelity and v2
|
||||
validation, releases stopped capture owners and preserves visible storage
|
||||
failures. Step-07B moves session cleanup outside the lifetime-registration
|
||||
gate and shares its completion/failure among competing disposers. Each
|
||||
worker report contains separate evidence; acceptance remains pending manual
|
||||
orchestrator review.
|
||||
gate and shares its completion/failure among competing disposers. Corrected
|
||||
Step-07/07A/07B is accepted. Step-08 adds offline saved telemetry replay,
|
||||
exact prefix navigation, one page-owned clock and the shared gauge editor.
|
||||
Step-08 worker status remains pending manual orchestrator review.
|
||||
|
||||
- [Architecture](architecture.md): actual nine-project graph, responsibilities,
|
||||
route ownership and provider/reference boundaries.
|
||||
|
|
@ -29,6 +30,9 @@ orchestrator review.
|
|||
- [Telemetry archive schema v1 and recording](telemetry-archive-v1.md): capture
|
||||
cutover, actual-operation observations, bounded limits, local save/readback,
|
||||
failure states and strict archive validation.
|
||||
- [Recorded telemetry replay](telemetry-replay.md): offline RecordedReplay
|
||||
provenance, before-first/time/ordinal semantics, exact quality and last-Good
|
||||
reduction, rates, cancellation/drain, partial acknowledgement and shared gauges.
|
||||
- [ADR-0001: Headless .NET 10 foundation](adr-0001-headless-foundation.md):
|
||||
historical foundation decisions; dual-shell/deferred-host decision superseded.
|
||||
- [ADR-0002: Single native shell and feature slices](adr-0002-single-shell-vsa.md):
|
||||
|
|
@ -61,5 +65,6 @@ historical/worker reports for their own execution evidence:
|
|||
[Step-06A corrective worker report](../prompts/Step-06A-Report.md), and
|
||||
[Step-07 worker report](../prompts/Step-07-Report.md) and
|
||||
[Step-07A corrective worker report](../prompts/Step-07A-Report.md) and
|
||||
[Step-07B lock-safety corrective worker report](../prompts/Step-07B-Report.md).
|
||||
[Step-07B lock-safety corrective worker report](../prompts/Step-07B-Report.md) and
|
||||
[Step-08 worker report](../prompts/Step-08-Report.md).
|
||||
Handoffs are manual; acceptance remains the orchestrator's responsibility.
|
||||
|
|
|
|||
|
|
@ -9,11 +9,10 @@ There is no web/server host, WASM host or backend process.
|
|||
|
||||
## Current milestone status
|
||||
|
||||
Steps 04/04A/04B, 05/05A/05B and 06/06A are accepted. Step-07 adds bounded
|
||||
session-owned capture, strict local archive readback and shared host controls.
|
||||
The nine-project Release build, full test suite and native capture/save/restart/
|
||||
readback smoke are complete. Step-07 worker status remains pending manual
|
||||
orchestrator review.
|
||||
Steps 04/04A/04B, 05/05A/05B, 06/06A and corrected 07/07A/07B are accepted.
|
||||
Step-08 adds archive-only recorded replay with exact prefix reduction and one
|
||||
page-owned cancellable clock. Step-08 worker status remains pending manual
|
||||
orchestrator review; its execution evidence is separate from acceptance.
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
|
|
@ -48,7 +47,7 @@ All nine projects are in [AutoForge.slnx](../src/AutoForge.slnx):
|
|||
| [Core](../src/AutoForge.Core/AutoForge.Core.csproj) | `net10.0`; platform-neutral target/profile invariants and immutable dynamics configuration/status contracts | None |
|
||||
| [Diagnostics](../src/AutoForge.Diagnostics/AutoForge.Diagnostics.csproj) | `net10.0`; provider/session/transport/control contracts, strict synthetic protocol v1/v2 client, typed results and bounded trace | Core |
|
||||
| [Simulation](../src/AutoForge.Simulation/AutoForge.Simulation.csproj) | `net10.0`; validated static modules, fixed-step engine, isolated state, explicit provider factories and transports | Core, Diagnostics |
|
||||
| [Application](../src/AutoForge.Application/AutoForge.Application.csproj) | `net10.0`; target/profile/diagnostic-session, dynamics-configuration, display-unit, live-dashboard and telemetry-recording/archive feature slices | Core, Diagnostics |
|
||||
| [Application](../src/AutoForge.Application/AutoForge.Application.csproj) | `net10.0`; target/profile/diagnostic-session, dynamics-configuration, display-unit, shared gauge projection, live-dashboard, telemetry-recording/archive and replay feature slices | Core, Diagnostics |
|
||||
| [Components](../src/AutoForge.Components/AutoForge.Components.csproj) | `net10.0` RCL; generic `StatusNotice` and numeric/bar gauge with accessible state and safe rendering | None |
|
||||
| [UI](../src/AutoForge.UI/AutoForge.UI.csproj) | `net10.0` RCL; all application routes, navigation, layout and presentation, including shared dashboard and recording/archive inspection controls | Application, Components, Diagnostics |
|
||||
| [Client](../src/AutoForge.Client/AutoForge.Client.csproj) | `net10.0-windows10.0.26100.0`; only MAUI Blazor Hybrid application executable, native preference adapter and app-local archive root | Application, Simulation, UI |
|
||||
|
|
@ -73,8 +72,9 @@ configuration, run identity, control capability and protocol-v2 frames.
|
|||
factory registrations used for transport resolution. Target
|
||||
metadata resolution remains a separate, metadata-only action. The profile
|
||||
catalog is process-local; importing does not select a revision or open a session.
|
||||
Replay and physical kinds have no operational implementation and are never
|
||||
substituted with Simulation.
|
||||
RecordedReplay is an archive-only Application context, not a diagnostic
|
||||
provider or simulated connection. Physical kinds have no operational
|
||||
implementation; neither kind is substituted with Simulation.
|
||||
|
||||
## UI ownership and real routes
|
||||
|
||||
|
|
@ -88,6 +88,7 @@ assembly, not the native Client assembly.
|
|||
| `/vehicle-profiles` | `Features/Vehicles/Profiles/VehicleProfilesPage.razor` | Explicit schema-v1 import, exact revision selection, metadata/provenance inspection and read-only export |
|
||||
| `/diagnostics` | `Features/Vehicles/Diagnostics/DiagnosticsPage.razor` | Explicit saved profile/revision/provider/kind selection, static-v1 session lifecycle, separate expected/probed/identified counts, retained partial probe services, identity-gated DTC/static signal operations, clear acknowledgement plus fresh-empty-readback verification, raw/decoded trace, shared live dashboard and session recording/archive inspection |
|
||||
| `/simulation` | `Features/Vehicles/Simulation/SimulationPage.razor` | Explicit profile/config/provider selection, JSON import/export, stopped-by-default dynamics session, lifecycle/step/pacing/scenario controls, source/unit/quality/model-time/config/run-aware telemetry over diagnostic protocol v2, and the same dashboard and recording/archive controls |
|
||||
| `/telemetry-replay` | `Features/Vehicles/Telemetry/Replay/TelemetryReplayPage.razor` | Strict saved capture selection/load, distinct RecordedReplay instance and immutable original metadata, exact time/ordinal prefix navigation, one cancellable clock, partial acknowledgement and shared recorded numeric/bar gauges |
|
||||
| Any unmatched route | `Features/Foundation/NotFoundPage.razor` via UI `Routes.razor` | Explicit not-found page and supported navigation |
|
||||
|
||||
The generic [StatusNotice](../src/AutoForge.Components/StatusNotice.razor)
|
||||
|
|
@ -146,13 +147,29 @@ contracts; save writes and flushes a task-specific temporary file before
|
|||
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. V2 archive checks share the source validator for
|
||||
archive persistence, not live disk streaming, crash durability or cryptographic
|
||||
authenticity. 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 replay factory creates a fresh `TelemetryReplaySession` for each routed
|
||||
page. Its only inputs are the existing archive store, monotonic `TimeProvider`
|
||||
and cancellable wait seam; it cannot resolve profiles, open diagnostic sessions,
|
||||
call models or save archives. Explicit strict load commits a new replay identity
|
||||
only after validation, preserving the previous context on failure/cancellation.
|
||||
The current kind is `RecordedReplay`; original provider/target/profile/session/
|
||||
config/run and source completion remain unchanged archive metadata.
|
||||
The page drains loading/playback on close or unmount. Gauges own only render
|
||||
subscriptions. Playback uses capture elapsed ticks and a bounded prefix rebuild,
|
||||
not UTC, diagnostic ticks or model time. Binding pre-indexing contains metadata,
|
||||
never current values. Shared `DashboardGaugeProjection` enforces definitions,
|
||||
unit/origin, quality, range and last-Good rules for both live and recorded data.
|
||||
The existing panel shares its editor/conversions/generic renderer through
|
||||
separate live-session or replay inputs; it creates no dummy live feed for replay.
|
||||
See [replay contracts](telemetry-replay.md) for owner/drain and partial-data rules.
|
||||
|
||||
The feature-local target-selection view model adapts explicit input to the
|
||||
existing Application resolver. The same target resolver is populated from the
|
||||
diagnostic factories' descriptors, so `/execution-targets` shows the actual
|
||||
|
|
@ -204,7 +221,7 @@ manufacturer accuracy or permission. Static v1 signals remain static. Protocol
|
|||
v2 dynamic telemetry is computed from an explicitly configured simplified
|
||||
model; it is not real sensor data or validated prediction. Virtual DTC clear
|
||||
mutates only selected in-memory module/session state and has no physical write
|
||||
path. No real vehicle, physical adapter, replay provider, programming,
|
||||
path. No real vehicle, physical adapter, programming,
|
||||
calibration values, backups, AI, live streaming, crash-durable capture or cloud
|
||||
service is implemented. Saved recordings are local source-sensitive files and
|
||||
must be treated as potentially sensitive data. A `SUPPORTED` declaration,
|
||||
|
|
|
|||
|
|
@ -41,8 +41,57 @@ actual vehicle, database, backend, model or cloud account is required.
|
|||
```powershell
|
||||
dotnet test .\src\tests\AutoForge.UnitTests\AutoForge.UnitTests.csproj --configuration Release
|
||||
dotnet test .\src\tests\AutoForge.IntegrationTests\AutoForge.IntegrationTests.csproj --configuration Release
|
||||
dotnet test .\src\tests\AutoForge.IntegrationTests\AutoForge.IntegrationTests.csproj --configuration Release --no-restore --filter "FullyQualifiedName~TelemetryReplayTests|FullyQualifiedName~LiveDashboardAcquisitionTests|FullyQualifiedName~DisplayUnitControlTests"
|
||||
```
|
||||
|
||||
## Step-08 recorded replay verification
|
||||
|
||||
Corrected Step-07/07A/07B is accepted; the Step-08 worker remains pending
|
||||
orchestrator review. The final focused command above passed 49 cases. It covers
|
||||
37 new replay cases plus accepted live-dashboard/unit-selector regressions.
|
||||
The required sequential nine-project Release build passed with zero warnings
|
||||
and errors, followed by 179 unit and 171 integration tests: **350 passed,
|
||||
zero failed/skipped**, preserving all 313 baseline cases.
|
||||
|
||||
The replay tests construct real recorder/codec/file-store inputs, then dispose
|
||||
their original sources and load without profile/configuration catalogues.
|
||||
Independent four-observation assertions cover exact prefixes, last-Good versus
|
||||
Uncertain, ties, before-first, zero/empty/non-signal archives and model reset/
|
||||
repeated time. Controlled monotonic waits/barriers prove 0.25x/1x/1000x pacing,
|
||||
1.5-to-1.7-second mid-gap pause at 2x, remaining 0.15-second resume, held cleanup,
|
||||
fault recovery (including faults during pending Pause/Stop cleanup), stale
|
||||
loads/wakes and unmount. Actual rendered route/editor
|
||||
events prove committed selector feedback, persistent actual fault reasons despite
|
||||
older command errors, partial acknowledgement, pinned units and atomic edits.
|
||||
A real simultaneously open dynamics source retains
|
||||
its trace, model state and unsaved recording with zero additional transport,
|
||||
model-control or archive Save calls during replay. Shared gauge hide/units/
|
||||
unmount also leaves an active replay owner untouched.
|
||||
|
||||
Native smoke uses the actual Windows Client through a task-local WebView2
|
||||
DevTools endpoint, not a second web host. Saved static-v1 and dynamic-v2 captures
|
||||
were recorded through native controls, stopped, source-closed and saved.
|
||||
After app restart, the profile catalogue was empty; both files replayed without
|
||||
reimporting profiles or recreating a model/configuration. Native checks include
|
||||
explicit load/no autoplay, numeric/bar gauges, Play/Pause/Stop/First/Restart,
|
||||
time/ordinal/backward navigation, rejected speed feedback, hide/show, end,
|
||||
route close/re-entry, raw/decoded inspection and restored Metric/Road
|
||||
preferences. A recorded 88.02090573589594 degC source showed 88.02 degC or
|
||||
190.44 degF; draft 32..212 degF saved without changing canonical 0..100 degC
|
||||
bounds. Time seek 40,000,000 ticks retained exactly two of four dynamic records.
|
||||
|
||||
The native partial warning/acknowledgement/end check used a separately named,
|
||||
strict-reader-validated derived static fixture; it is not evidence that native
|
||||
recording exhausted a limit. Actual limit/error capture and controlled timing/
|
||||
fault/interleaving evidence remain in headless tests. Static/dynamic archive
|
||||
SHA-256 hashes were unchanged after playback. Exact task-owned capture IDs,
|
||||
storage path, cleanup and native preparation limitations are recorded in the
|
||||
[Step-08 worker report](../prompts/Step-08-Report.md).
|
||||
|
||||
MAUI storage was verified at its real app-local directory, not inferred from
|
||||
`LOCALAPPDATA`. Only individually named task-owned capture files and task-owned
|
||||
WebView profile/helper were cleaned up; unrelated app data/preferences remain.
|
||||
|
||||
The unit suite covers existing Core/Application behavior, rendered generic
|
||||
components, profile invariants and strict codec behavior, plus protocol v1
|
||||
round-trip/snapshot contracts and bounded trace behavior. The integration suite
|
||||
|
|
|
|||
|
|
@ -140,6 +140,15 @@ advance a paused or stopped dynamics run. See the [v1 protocol](synthetic-diagno
|
|||
|
||||
## Ownership and cleanup
|
||||
|
||||
The [recorded replay route](telemetry-replay.md) reuses the same validated
|
||||
0..8 definitions, pinned-unit editor, display conversion and numeric/bar
|
||||
renderer. It supplies a distinct archive-only source, never a fake live
|
||||
session/feed. Every replay card and accessible reading is explicitly recorded,
|
||||
including Good, Paused, Completed and last-known Stale values. Its page owns
|
||||
playback; hide/show, unit changes and gauge remounts do not own a timer or
|
||||
operate a source. Before-first has no values even though positive archived
|
||||
binding metadata is available to configure gauges.
|
||||
|
||||
The Application feed is bound to the page's actual `DiagnosticSession`; repeated
|
||||
factory access for that session shares its owner. The feed discovers and reads
|
||||
through the session's verified diagnostic ports and groups each cycle by
|
||||
|
|
|
|||
|
|
@ -8,8 +8,8 @@ dashboard, issue commands, step dynamics or decode guessed payloads. Captures
|
|||
are held in memory until the user stops and explicitly saves them. The saved
|
||||
file is local and source-sensitive; it is not a trusted statement about a real
|
||||
vehicle, manufacturer data, current vehicle state or cryptographic authenticity.
|
||||
Playback, live disk streaming, unlimited retention and crash recovery are not
|
||||
implemented.
|
||||
Saved-data playback is a separate [archive-only replay feature](telemetry-replay.md).
|
||||
Live disk streaming, unlimited retention and crash recovery are not implemented.
|
||||
|
||||
The shared panel is available in both `/diagnostics` (synthetic protocol v1)
|
||||
and `/simulation` (synthetic protocol v2). Hiding or unmounting a dashboard or
|
||||
|
|
@ -220,6 +220,11 @@ Valid incomplete archives remain incomplete on readback. Readback proves
|
|||
file/schema consistency only; it does not validate authenticity or source
|
||||
truth.
|
||||
|
||||
The `/telemetry-replay` route lists and explicitly loads these same files using
|
||||
the strict reader. Playback never calls Save, rebinds the recording workspace,
|
||||
changes original completion or uses the original profile/model as a fallback.
|
||||
Current RecordedReplay identity is separate from the archived source identity.
|
||||
|
||||
## Verification
|
||||
|
||||
The focused `TelemetryRecordingIntegrationTests` exercise real v1/v2 sessions,
|
||||
|
|
|
|||
|
|
@ -0,0 +1,138 @@
|
|||
# Recorded telemetry replay
|
||||
|
||||
## Open a saved capture offline
|
||||
|
||||
Open **Recorded telemetry replay** (`/telemetry-replay`) from the shared
|
||||
navigation. Refresh validates files in the Client's existing app-local
|
||||
recordings directory. Select an explicit capture ID and choose **Load saved
|
||||
capture**. Loading never auto-plays. No profile import, diagnostic session,
|
||||
live feed, vehicle, model or configuration catalogue is required.
|
||||
|
||||
The current execution kind is **RecordedReplay**, with a fresh replay-instance
|
||||
identifier and the saved capture ID. Provider, target kind, profile revision,
|
||||
vehicle/session/configuration/run identifiers, protocol and completion are
|
||||
**original archived metadata**, not current vehicle evidence or verified
|
||||
identity. Raw/decoded inspection shows the last applied observation; before
|
||||
first and empty archives have an explicit no-observation/no-sample state.
|
||||
The source archive is never edited, saved again or rebound into the recording
|
||||
workspace by replay. Readback establishes consistency, not authenticity.
|
||||
|
||||
Incomplete and Error captures retain a prominent original state/reason/error.
|
||||
Before Play, Next, Previous or either seek, explicitly acknowledge that load's
|
||||
partial/error source. Stop, First, inspection and Close remain available.
|
||||
Acknowledgement survives navigation within the same load, but not a replacement
|
||||
load. Reaching the end means **end of retained data**, never a newly Complete
|
||||
source or recovery of unrecorded samples.
|
||||
|
||||
## Two independent cursor values
|
||||
|
||||
- Position is integer `TimeSpan` ticks in `[0, duration]`. One second is
|
||||
10,000,000 ticks. Duration is the last observation's capture elapsed time,
|
||||
or zero when empty; no trailing UTC/model interval is invented.
|
||||
- Applied count is the exact prefix length from zero to the retained count.
|
||||
Load, First and Stop mean **before first**: count zero, position zero and
|
||||
no current values. This differs from time seek zero if zero-time records exist.
|
||||
|
||||
Next applies exactly one observation. Previous rebuilds one fewer. Ordinal seek
|
||||
rebuilds exactly the requested count and sets position to that last record's
|
||||
capture time (zero for count zero). Time seek includes every record whose
|
||||
capture time is less than or equal to the requested tick, including all ties,
|
||||
but preserves the requested position between records. Manual navigation leaves
|
||||
Paused, or Completed when every record of a nonempty archive is applied.
|
||||
Empty seek zero remains Stopped; empty Next/Previous is visibly rejected.
|
||||
|
||||
Time-driven playback applies whole due-time groups in recorded sequence before
|
||||
publishing. All-zero archives complete without a timer; manual Next can still
|
||||
inspect a single record inside a tie. Completion depends on applied count, not
|
||||
position equalling duration. Completed requires explicit Restart or navigation,
|
||||
not an implicit replay when Play is pressed again.
|
||||
|
||||
Diagnostic logical ticks and model step/time remain per-sample source context.
|
||||
They do not determine ordering or duration: model resets and repeated model
|
||||
times remain exactly recorded. Modules are not represented as simultaneous.
|
||||
There is no interpolation, extrapolation, smoothing or model rerun.
|
||||
|
||||
## Exact quality and last-Good reduction
|
||||
|
||||
Bindings are pre-indexed from actual positive archived signal snapshots using
|
||||
the first-observed module/signal/exact unit/origin rules. This index permits
|
||||
configuration before playback but contains no current measurements.
|
||||
Every navigation reconstructs the bounded prefix from scratch (maximum 4,096
|
||||
observations), clearing current, last-Good and per-module status caches first.
|
||||
No later value can leak into an earlier prefix.
|
||||
|
||||
Only `read.signals` observations change signal state. A failed operation changes
|
||||
only that module. A prior finite Good sample may be retained as visibly
|
||||
**recorded Stale**, with its original observation/capture/diagnostic/model time
|
||||
and failure reason. Uncertain is not last-Good authority. Without a prior Good,
|
||||
a failed read is Error/`--`, never zero. Unknown, null/non-numeric, missing
|
||||
signals and unit/origin changes use the same source-quality/range/last-Good
|
||||
rules as the [live dashboard](live-dashboard.md). Unsupported origin changes
|
||||
are also rejected at the existing strict archive boundary.
|
||||
|
||||
Example: A=850 Good at 1 s; B=12.6 Good at 2 s; A=1000 Uncertain at 2 s;
|
||||
A Timeout at 4 s. Seek 1.5 s yields only A=850 Good, with no B sample.
|
||||
Seek 2 s applies three records, A=1000 Uncertain and B=12.6 Good. Seek 4 s
|
||||
retains A=850 Stale from 1 s, not 1000, and leaves B Good. Previous restores
|
||||
the exact three-record Uncertain prefix; First clears both.
|
||||
|
||||
## One cancellable owner and explicit controls
|
||||
|
||||
Play resumes Stopped/Paused. Restart is rewind-plus-Play and requires quiescence.
|
||||
Repeated active Play is idempotent and shares the owner. Pause freezes the
|
||||
position at the request instant, applies the due prefix, then cancels/drains
|
||||
the old wait. Resume rebases from that position, waiting only the remaining
|
||||
capture interval. Stop drains then clears to before-first while retaining the
|
||||
archive, definitions, speed and acknowledgement.
|
||||
|
||||
Speed defaults to 1x and accepts finite 0.25x through 1000x inclusive. Only
|
||||
capture elapsed intervals are scaled; source facts and results are unchanged.
|
||||
Pause and finish cleanup before changing speed, seeking, restarting, replacing
|
||||
or refreshing an archive. Rejected speed input rerenders to the committed
|
||||
value; invalid inputs are never clamped into success. Gauge edits remain atomic
|
||||
and may rerender during playback without advancing it; archive/drain operations
|
||||
reject overlapping edits.
|
||||
|
||||
The clock uses monotonic `TimeProvider` and a cancellable wait seam, decimal
|
||||
overflow-safe tick scaling and individual waits bounded at 30 wall seconds.
|
||||
This is not a hard real-time SLA or smooth-animation promise. A clock/wait
|
||||
failure is visibly Faulted, preserving the last committed prefix/sample state;
|
||||
the actual fault reason remains visible even after another command is rejected.
|
||||
A non-cancellation failure during pending Pause/Stop cleanup also remains
|
||||
Faulted rather than becoming a successful reset. Stop/First after cleanup
|
||||
provides explicit recovery.
|
||||
|
||||
The factory returns a fresh session per page, not a disposed scoped singleton.
|
||||
The page drains loading/playback on Close or unmount. Generation/owner checks
|
||||
prevent delayed old loads/wakes from publishing. While an archive command or
|
||||
cleanup is pending, competing starts/navigation/replacements reject before
|
||||
mutation. Failed/cancelled replacements retain the previous validated context,
|
||||
definitions, values, rate and position, with a visible actual error rather
|
||||
than a healthy empty replacement.
|
||||
|
||||
## Shared recorded gauges and display units
|
||||
|
||||
Use the shared in-memory editor to add zero through eight numeric/bar gauges.
|
||||
Exact source units and bounds remain canonical; only labels/readouts are
|
||||
projected to global display units. An open draft pins its selected display
|
||||
units until save/cancel/reset. Invalid edits are atomic, and unedited bounds
|
||||
retain their exact original source values. All gauges are labeled Recorded
|
||||
replay, even Good or Paused/Completed readings. Hide/show, remounting and global
|
||||
unit changes never start/stop/seek/read the player.
|
||||
|
||||
Only the existing global unit preference persists. Layout, definitions,
|
||||
cursor, acknowledgement and speed are runtime-only; a new load clears
|
||||
definitions/cursor/acknowledgement but keeps valid speed and global units.
|
||||
|
||||
## Verification boundaries
|
||||
|
||||
`TelemetryReplayTests` covers real recorder/codec/temporary-filesystem input,
|
||||
offline DI, independent exact-prefix fixtures, controlled monotonic waits and
|
||||
barriers, typed atomic rejections, faults, replacement/unmount, source-byte
|
||||
immutability, zero live/model calls and zero Save calls, plus actual rendered
|
||||
route/editor events. Existing live-source regressions remain intact.
|
||||
Native evidence uses the real Windows Client, app storage and saved static-v1/
|
||||
dynamic-v2 captures; it is not controlled timing, race or fault proof.
|
||||
Commands, counts, native observations and limitations are recorded separately
|
||||
in the [Step-08 worker report](../prompts/Step-08-Report.md).
|
||||
Step-07/07A/07B is accepted; Step-08 remains pending orchestrator review.
|
||||
|
|
@ -3,16 +3,17 @@
|
|||
## Status and authority
|
||||
|
||||
- Initialized: 2026-10-28.
|
||||
- Current phase: corrected recording/archive accepted; saved telemetry replay next.
|
||||
- Active assignment: [Step-08](Step-08.md), ready for manual worker execution.
|
||||
- Last accepted milestone: Step-07 with Step-07A/Step-07B, accepted 2026-10-30.
|
||||
- Current phase: recorded telemetry replay accepted; bounded synthetic calibration authoring next.
|
||||
- Active assignment: [Step-09](Step-09.md), ready for manual worker execution.
|
||||
- Last accepted milestone: Step-08, accepted 2026-10-30.
|
||||
- Last accepted correction: Step-07B; all Step-07 findings closed.
|
||||
- Outstanding corrections: none.
|
||||
- Step-05 status: ACCEPTED after Step-05A/Step-05B, 2026-10-29.
|
||||
- Step-06 status: ACCEPTED after Step-06A, 2026-10-30.
|
||||
- Step-07 status: ACCEPTED after Step-07A/Step-07B, 2026-10-30.
|
||||
- Step-08 status: READY FOR WORKER; replay controls/clock not implemented yet.
|
||||
- Step-09 status: calibration/simulated programming; BLOCKED / NOT ASSIGNED until replay acceptance.
|
||||
- Step-08 status: ACCEPTED 2026-10-30; no Step-08A required.
|
||||
- Step-09 status: READY FOR WORKER; synthetic definitions/proposals/diffs only.
|
||||
- Step-10 status: verified simulated programming; BLOCKED / NOT ASSIGNED until authoring acceptance.
|
||||
- Current state and handoff: [STATE.md](STATE.md).
|
||||
- Authority: the master charter, repository/handoff amendment, and the owner's
|
||||
2026-10-28 architectural realignment. The latest decision cancels the dual-shell
|
||||
|
|
@ -191,6 +192,27 @@ explicit persistence, not crash-durable live streaming or unlimited history.
|
|||
Longer-duration/streaming capture remains a future telemetry expansion; it is
|
||||
not claimed by Step-07. The assignment freezes loss/limit/close/I/O outcomes.
|
||||
|
||||
## Prospective calibration scope split - 2026-10-30
|
||||
|
||||
The former calibration/programming envelope combines definition/version
|
||||
authoring with backup, approval, write/readback and recovery lifecycles.
|
||||
Apply the existing bounded-scope policy before execution:
|
||||
|
||||
- Step-09: in-memory synthetic calibration definitions, immutable baseline/
|
||||
proposed revisions, scalar/fixed-axis table editing and exact structured diffs.
|
||||
Bind explicitly to a selected immutable dynamics configuration; authoring
|
||||
never changes that configuration or a module/run.
|
||||
- Step-10: verified baseline/backup, approval bound to an exact proposal/source,
|
||||
simulated write/readback/unrelated-value checks, audit and supported restore.
|
||||
Only after Step-09 acceptance; still no physical programming.
|
||||
- Former unassigned Steps 10-22 become 11-23 below. Completed history/assignments
|
||||
keep their numbers; letters remain reserved for actual corrections.
|
||||
|
||||
The first authoring slice has no calibration file format/storage, approval
|
||||
state machine, programming service or model integration. A configuration-derived
|
||||
synthetic baseline is not an ECU read or verified backup. Those distinctions are
|
||||
frozen in Step-09's UI/validation/evidence contract, not postponed by implication.
|
||||
|
||||
## Architecture baseline
|
||||
|
||||
### Existing accepted foundation, preserved
|
||||
|
|
@ -379,7 +401,10 @@ defaults/conversions, rejected selections, unavailable readouts and raw/source
|
|||
preservation are closed on inspected evidence. Corrected Step-07/07A/07B is
|
||||
accepted: actual bounded capture, source-faithful/strict archives, released
|
||||
ownership, visible I/O failures and deadlock-free source close are supported.
|
||||
Step-08 is the only active assignment for saved-data replay, not resimulation.
|
||||
Step-08 replay is accepted: exact prefixes/ties, one playback owner, offline
|
||||
RecordedReplay context, source immutability and shared gauges/units are supported.
|
||||
Step-09 is the only active assignment for bounded synthetic calibration
|
||||
authoring; simulated programming is separated into Step-10.
|
||||
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.
|
||||
|
|
@ -404,23 +429,24 @@ evidence; they must not silently discard required capabilities.
|
|||
| 07 | Bounded telemetry recording and archive readback | 06 and corrections accepted | ACCEPTED 2026-10-30 AFTER 07A/07B | Actual bounded observations, source-faithful strict archive save/readback, visible errors, retained capture data and controlled safe-close evidence inspected |
|
||||
| 07A | Source-faithful archives, bounded lifetime and visible storage failures | 07 review R-01 through R-04 | ACCEPTED 2026-10-30 AFTER 07B | Archive/typed-validation/normal-release/panel fixes and source-close follow-up all closed |
|
||||
| 07B | Deadlock-free source disposal during capture cleanup | Remaining 07A R-03 safe-close contract | ACCEPTED 2026-10-30 | Shared disposal task published under gate, cleanup outside; actual pre-fix close/reset deadlocks and controlled correction, reported 179 unit/134 integration passes and native baseline |
|
||||
| 08 | Recorded telemetry replay | 07 and corrections accepted | READY FOR WORKER | Strict saved-archive load, RecordedReplay context, prefix-correct gauges/navigation and one cancellable playback owner; no live calls, resimulation, interpolation or archive mutation |
|
||||
| 09 | Calibration management and simulated programming | 08 accepted | BLOCKED / NOT ASSIGNED | Versioned definitions/diffs, verified baseline and backup, approved simulated write, readback/unrelated-data checks, audit and supported restore; no physical writes |
|
||||
| 10 | Local AI, knowledge, and validated runbooks | 09 | PLANNED | Replaceable local inference, applicable knowledge retrieval, structured logical runbook, independent validation/approval and simulation-only execution |
|
||||
| 11 | Comparative evaluation and complete synthetic demonstration | 10 | PLANNED | Complete demonstration below plus deterministic fault/regression matrix and independent verification of intended and unintended changes |
|
||||
| 12 | Verified OBDX Pro GT read-only integration | 11 plus documented device research/access | PLANNED / HARDWARE GATE | Source-backed device support matrix, explicit physical target, real read-only identification/diagnostics/telemetry recording where supported; no write path |
|
||||
| 13 | Advanced dashboards, analysis, and comparisons | 11; 12 for real captures | PLANNED | Persist configurable layouts/thresholds, linked charts, larger-capture analysis, raw-data inspection and multi-run/multi-vehicle comparisons with lineage/uncertainty |
|
||||
| 14 | Broader diagnostic protocols and hardware adapters | 12 | PLANNED | Conformance-backed additional CAN/ISO-TP/UDS/KWP2000/J2534 or legacy adapters where verified; same application ports and capability restrictions |
|
||||
| 15 | Curated vehicle knowledge and research workflow | 10; 14 where needed | PLANNED | Sourced profile/module/calibration knowledge, review/promotion workflow, exact applicability, licensing/access controls; research cannot authorize writes |
|
||||
| 16 | Higher-fidelity simulation and virtual module coverage | 11; 15 for verified datasets | PLANNED | Validated model extensions, richer transmissions/environment/module interactions and reproducible fault coverage; published fidelity limits |
|
||||
| 17 | AI evaluation and optional specialization | 10, 11, 15 and adequate datasets | PLANNED | Held-out deterministic runbook evaluations, refusal/uncertainty cases, memory/latency measurements; LoRA/QLoRA only if justified by measured benefit |
|
||||
| 18 | Programming qualification without physical writes | 09, 11, 12, applicable 14/15 evidence | PLANNED | Module-specific safety case, bench plan, voltage/state/identity checks, interruption/recovery tests in simulation, legal authorization and defined go/no-go criteria |
|
||||
| 19 | Explicitly authorized controlled bench programming | 18 and separate user authorization | PLANNED / AUTHORIZATION GATE | Authorized supported bench target only; verified backup completeness, transfer/readback/recovery evidence and audit; no general vehicle-write enablement |
|
||||
| 20 | Approved vehicle/module-specific programming | 19 and separate vehicle-operation authorization | PLANNED / AUTHORIZATION GATE | Explicit per-operation approvals, compatibility/operating-state/power/security checks and proven recovery limits; strict module-specific support matrix |
|
||||
| 21 | Packaging, extensibility, and additional platforms | 06, 11; feature-specific gates remain | PLANNED | Offline-friendly reproducible releases, documented supported hosts, feature manifests/DI, compatibility/migration regression evidence |
|
||||
| 22 | Optional MCP and firmware-emulation research | 10, 15; isolated research approvals | OPTIONAL / PLANNED | Concrete benefit and separate ADR; restricted tools retain validator/approval boundary; emulation limitations and proprietary-data rights documented |
|
||||
| 08 | Recorded telemetry replay | 07 and corrections accepted | ACCEPTED 2026-10-30 | Exact recorded prefix/tie/navigation, controlled rate/owner/fault cleanup, shared gauges/units and offline native replay; reported 179 unit/171 integration passes |
|
||||
| 09 | Synthetic calibration authoring and immutable proposals | 08 accepted | READY FOR WORKER | Explicit configuration/module applicability, validated scalar/fixed-axis table revisions, exact diffs and no source/model mutation; in-memory only |
|
||||
| 10 | Verified simulated programming and recovery | 09 accepted | BLOCKED / NOT ASSIGNED | Verified baseline/backup, exact approval binding, simulated write/readback/unrelated-value checks, audit and supported restore; no physical writes |
|
||||
| 11 | Local AI, knowledge, and validated runbooks | 10 | PLANNED | Replaceable local inference, applicable knowledge retrieval, structured logical runbook, independent validation/approval and simulation-only execution |
|
||||
| 12 | Comparative evaluation and complete synthetic demonstration | 11 | PLANNED | Complete demonstration below plus deterministic fault/regression matrix and independent verification of intended and unintended changes |
|
||||
| 13 | Verified OBDX Pro GT read-only integration | 12 plus documented device research/access | PLANNED / HARDWARE GATE | Source-backed device support matrix, explicit physical target, real read-only identification/diagnostics/telemetry recording where supported; no write path |
|
||||
| 14 | Advanced dashboards, analysis, and comparisons | 12; 13 for real captures | PLANNED | Persist configurable layouts/thresholds, linked charts, larger-capture analysis, raw-data inspection and multi-run/multi-vehicle comparisons with lineage/uncertainty |
|
||||
| 15 | Broader diagnostic protocols and hardware adapters | 13 | PLANNED | Conformance-backed additional CAN/ISO-TP/UDS/KWP2000/J2534 or legacy adapters where verified; same application ports and capability restrictions |
|
||||
| 16 | Curated vehicle knowledge and research workflow | 11; 15 where needed | PLANNED | Sourced profile/module/calibration knowledge, review/promotion workflow, exact applicability, licensing/access controls; research cannot authorize writes |
|
||||
| 17 | Higher-fidelity simulation and virtual module coverage | 12; 16 for verified datasets | PLANNED | Validated model extensions, richer transmissions/environment/module interactions and reproducible fault coverage; published fidelity limits |
|
||||
| 18 | AI evaluation and optional specialization | 11, 12, 16 and adequate datasets | PLANNED | Held-out deterministic runbook evaluations, refusal/uncertainty cases, memory/latency measurements; LoRA/QLoRA only if justified by measured benefit |
|
||||
| 19 | Programming qualification without physical writes | 10, 12, 13, applicable 15/16 evidence | PLANNED | Module-specific safety case, bench plan, voltage/state/identity checks, interruption/recovery tests in simulation, legal authorization and defined go/no-go criteria |
|
||||
| 20 | Explicitly authorized controlled bench programming | 19 and separate user authorization | PLANNED / AUTHORIZATION GATE | Authorized supported bench target only; verified backup completeness, transfer/readback/recovery evidence and audit; no general vehicle-write enablement |
|
||||
| 21 | Approved vehicle/module-specific programming | 20 and separate vehicle-operation authorization | PLANNED / AUTHORIZATION GATE | Explicit per-operation approvals, compatibility/operating-state/power/security checks and proven recovery limits; strict module-specific support matrix |
|
||||
| 22 | Packaging, extensibility, and additional platforms | 06, 12; feature-specific gates remain | PLANNED | Offline-friendly reproducible releases, documented supported hosts, feature manifests/DI, compatibility/migration regression evidence |
|
||||
| 23 | Optional MCP and firmware-emulation research | 11, 16; isolated research approvals | OPTIONAL / PLANNED | Concrete benefit and separate ADR; restricted tools retain validator/approval boundary; emulation limitations and proprietary-data rights documented |
|
||||
|
||||
### Scope details for Steps 02-12
|
||||
### Scope details for Steps 02-13
|
||||
|
||||
- **01A accepted prerequisite:** one thin MAUI Client, two RCLs, feature-organized
|
||||
target selection, actual headless rendered tests and worker native build/smoke
|
||||
|
|
@ -477,7 +503,7 @@ evidence; they must not silently discard required capabilities.
|
|||
unavailable/stale/error states, with one source/session-aware acquisition owner.
|
||||
Supply a contract matrix for invalid ranges, missing signals and session
|
||||
replacement before coding. No charts, drag/drop or new clock/protocol/backend.
|
||||
Larger dashboard composition remains Step-13 scope. Client stays thin and no
|
||||
Larger dashboard composition remains Step-14 scope. Client stays thin and no
|
||||
alternate host is introduced. Dashboard configuration is in-memory only for
|
||||
this slice; persistence/schema work is not bundled into the feed state machine.
|
||||
- **06:** newly approved display-only unit preference and conversions, Imperial
|
||||
|
|
@ -490,23 +516,25 @@ evidence; they must not silently discard required capabilities.
|
|||
- **08:** replay accepted archives with play/pause/stop/restart/seek/navigation/
|
||||
speed; feed shared gauges without a live source or physics rerun. Keep original
|
||||
capture/source/model time distinct from playback time and label incomplete data.
|
||||
- **09:** scalar/table definitions with ranges/scaling/units and dependencies;
|
||||
original/proposed/tested/approved versions, structured diffs, verified backup
|
||||
completeness, approval binding, audit, readback, unrelated-data preservation,
|
||||
restoration where supported, explicit failure/recovery outcomes.
|
||||
- **10:** local inference provider configuration, structured queries plus optional
|
||||
- **09:** bounded in-memory synthetic scalar/fixed-axis table authoring, exact
|
||||
configuration/module applicability, immutable baseline/proposed revisions and
|
||||
structured diffs. A valid proposal is not tested, approved, applied or backed up.
|
||||
- **10:** verified simulated baseline/backup, approval bound to source/proposal,
|
||||
write/readback/unrelated-value checks, audit, restore and explicit recovery.
|
||||
No physical writes or assumed manufacturer calibration knowledge.
|
||||
- **11:** local inference provider configuration, structured queries plus optional
|
||||
semantic retrieval, source-backed applicability checks, versioned runbook schema
|
||||
and restricted tools. Include natural-language diagnostics, driving scenarios,
|
||||
and calibration planning; AI cannot emit arbitrary hardware frames/offset writes.
|
||||
Missing knowledge and disconnected inference produce explicit outcomes without
|
||||
disabling non-AI functionality.
|
||||
- **11:** equivalent baseline/modified scenarios and initial state, independent
|
||||
- **12:** equivalent baseline/modified scenarios and initial state, independent
|
||||
calibration oracle, behavioral/fuel/shift comparisons with confidence labels,
|
||||
fault reports, replay/raw-trace inspection and an auditable verification report.
|
||||
Include timeout, unsupported service, malformed response, wrong identity/version,
|
||||
interruption, corruption/checksum, partial write, reset, incompatible config,
|
||||
DTC and failed-verification cases.
|
||||
- **12:** verify OBDX Pro GT protocols, drivers, OS/architecture constraints,
|
||||
- **13:** verify OBDX Pro GT protocols, drivers, OS/architecture constraints,
|
||||
manufacturer libraries/SDKs, actual J2534 support and C# integration using
|
||||
attributable sources before implementation. Missing device/driver access means
|
||||
real-hardware verification is blocked, not passed by mocks. Restrict services to
|
||||
|
|
@ -515,7 +543,7 @@ evidence; they must not silently discard required capabilities.
|
|||
|
||||
### Longer-term scope preservation
|
||||
|
||||
Steps 13-22 retain richer gauges/clusters/charts and dashboard editing, comparison
|
||||
Steps 14-23 retain richer gauges/clusters/charts and dashboard editing, comparison
|
||||
and analysis, more vehicle/module/protocol coverage, independently validated
|
||||
research, curated datasets, advanced dynamics and transmission modeling, local
|
||||
model evaluation/specialization, authorized programming, and supported release
|
||||
|
|
@ -532,7 +560,7 @@ continue only independent safe work through an explicit new assignment.
|
|||
|
||||
## Required synthetic end-to-end demonstration
|
||||
|
||||
Target acceptance: Step-11. Use the explicitly synthetic AutoForge test truck,
|
||||
Target acceptance: Step-12. Use the explicitly synthetic AutoForge test truck,
|
||||
initial warm idle 650 RPM and proposed warm idle 1,250 RPM. These values and any
|
||||
memory layout are synthetic, not manufacturer calibration data.
|
||||
|
||||
|
|
@ -830,20 +858,40 @@ history, not repeated redesign without evidence.
|
|||
[Step-08](Step-08.md) for a single saved-data playback owner and shared
|
||||
numeric/bar presentation. Original source/archive bytes and unit behavior stay
|
||||
immutable; equal timestamps, seek prefixes and cleanup are frozen up front.
|
||||
- Reviewed Step-08's archive-only load/context, exact prefix/reduction, shared
|
||||
gauge extraction, cancellable owner/clock, routed UI/editor and all new tests,
|
||||
docs and Release artifacts. Worker reports 179 unit + 171 integration passes
|
||||
(350 total, zero failed/skipped), clean nine-project Release build and offline
|
||||
native static/dynamic replay/restart/source-hash preservation.
|
||||
- Accepted Step-08 against C-01..C-14/AC-01..AC-07 without Step-08A. Controlled
|
||||
timing/error/drain/live-coexistence evidence is distinct from native smoke;
|
||||
no application checks were executed by the orchestrator.
|
||||
- Prepared [Step-09](Step-09.md), splitting authoring/versioning/diffs from
|
||||
subsequent Step-10 simulated programming under the existing scope policy.
|
||||
Only unassigned future envelopes/dependencies shifted; no completed history
|
||||
or prior assignment/report was renumbered.
|
||||
|
||||
### Remaining
|
||||
|
||||
- Worker execution of Step-08, then one consolidated review against its frozen
|
||||
replay prefix/time/owner/UI matrix and shared quality gate. Correct genuine
|
||||
unmet requirements as Step-08A before calibration work.
|
||||
- Step-09 calibration is blocked and not assigned. Replay is assigned work,
|
||||
not implemented functionality; recording/archive and earlier work are accepted.
|
||||
- Worker execution of Step-09, then one consolidated review against its frozen
|
||||
authoring/applicability/version/diff/UI matrix and shared quality gate.
|
||||
Correct genuine unmet requirements as Step-09A before simulated programming.
|
||||
- Step-10 programming is blocked and not assigned. Calibration authoring is
|
||||
assigned work, not implemented functionality; replay and earlier work are accepted.
|
||||
- Profile/module metadata, synthetic virtual-module communication and deterministic
|
||||
dynamics/v2 and corrected dashboard are accepted; later features remain planned.
|
||||
Preserve the complete sequence/safety gates.
|
||||
|
||||
### Known blockers and uncertainties
|
||||
|
||||
No blocking Step-08 deficiency was identified against its frozen contract.
|
||||
The worker disclosed an existing recording-panel initialization race when a
|
||||
Save-followup refresh is still pending during host navigation. That unchanged
|
||||
recording flow is outside Step-08; no replay check is claimed to cover/fix it.
|
||||
Native preparation was restarted and final-binary replay passed without the
|
||||
error overlay. Retain the issue for a separately scoped recording follow-up,
|
||||
not a retrospective replay criterion or automatic Step-09 cleanup.
|
||||
|
||||
No blocking Step-07 deficiency remains. Its source-close follow-up below is
|
||||
historical and closed by accepted Step-07B:
|
||||
|
||||
|
|
|
|||
102
prompts/STATE.md
102
prompts/STATE.md
|
|
@ -5,13 +5,13 @@
|
|||
| Field | Value |
|
||||
|---|---|
|
||||
| Updated | 2026-10-30 |
|
||||
| Phase | Corrected recording/archive accepted; saved telemetry replay next |
|
||||
| Active step | Step-08 - Recorded telemetry replay |
|
||||
| Assignment | [Step-08.md](Step-08.md) |
|
||||
| Phase | Recorded replay accepted; bounded synthetic calibration authoring next |
|
||||
| Active step | Step-09 - Synthetic calibration authoring and immutable proposals |
|
||||
| Assignment | [Step-09.md](Step-09.md) |
|
||||
| Assignment status | READY FOR WORKER / AWAITING MANUAL HANDOFF |
|
||||
| Expected worker report | `prompts/Step-08-Report.md` - not yet created |
|
||||
| Expected worker report | `prompts/Step-09-Report.md` - not yet created |
|
||||
| Last accepted correction | Step-07B - accepted 2026-10-30 |
|
||||
| Last accepted major milestone | Step-07 with Step-07A/Step-07B - accepted 2026-10-30 |
|
||||
| Last accepted major milestone | Step-08 - accepted 2026-10-30 |
|
||||
| Outstanding corrections | None |
|
||||
| Step-02 status | ACCEPTED after Step-02A |
|
||||
| Step-03 status | ACCEPTED after Step-03A/Step-03B |
|
||||
|
|
@ -22,10 +22,11 @@
|
|||
| Step-06 status | ACCEPTED after Step-06A |
|
||||
| Step-07 status | ACCEPTED after Step-07A/Step-07B |
|
||||
| Step-07A review | All original corrective criteria closed with Step-07B |
|
||||
| Step-08 status | READY FOR WORKER; saved-data replay only |
|
||||
| Step-09 status | Calibration/simulated programming; BLOCKED until Step-08 acceptance |
|
||||
| Worker execution | Step-07B returned and accepted; Step-08 not invoked |
|
||||
| Immediate next action | User manually directs the worker to execute Step-08 and shared quality gate only |
|
||||
| Step-08 status | ACCEPTED 2026-10-30; no correction required |
|
||||
| Step-09 status | READY FOR WORKER; synthetic definitions/proposals/diffs only |
|
||||
| Step-10 status | Verified simulated programming; BLOCKED until authoring acceptance |
|
||||
| Worker execution | Step-08 returned and accepted; Step-09 not invoked |
|
||||
| Immediate next action | User manually directs the worker to execute Step-09 and shared quality gate only |
|
||||
| Next orchestrator action | After manual return, inspect the assignment, report, implementation, tests, Git changes, documentation and recorded command evidence |
|
||||
|
||||
## Repository baseline at initialization
|
||||
|
|
@ -701,7 +702,8 @@ outputs. Original scope decisions:
|
|||
Remaining findings, limited to existing criteria:
|
||||
|
||||
1. **R-01:** In
|
||||
[CreateGaugeValueLocked](../src/AutoForge.Application/Features/Vehicles/Telemetry/LiveDashboard/LiveDashboardAcquisition.cs:581),
|
||||
[CreateGaugeValueLocked](../src/AutoForge.Application/Features/Vehicles/Telemetry/LiveDashboard/LiveDashboardAcquisition.cs)
|
||||
at that review (its pure projection was later extracted in Step-08),
|
||||
Uncertain values call CreateValue without GetRangeState. CreateValue does not
|
||||
derive range from that quality, so -10/1100 over 0..1000 has no low/high label.
|
||||
Existing Step-05 C-02/C-03 and Step-05A R-03 require independent quality/range.
|
||||
|
|
@ -1014,6 +1016,61 @@ Original Step-07 and both corrective findings are closed. Preserve the 303-/
|
|||
RecordedReplay context, deterministic prefix reduction and one playback owner.
|
||||
No live source/session, physics execution or archive rewrite is authorized.
|
||||
|
||||
## Step-08 acceptance
|
||||
|
||||
Decision: **ACCEPTED**, 2026-10-30. Frozen C-01..C-14 and AC-01..AC-07 are
|
||||
satisfied on reviewed source and worker evidence. No Step-08A is required.
|
||||
|
||||
Reviewed [Step-08](Step-08.md), its [report](Step-08-Report.md), all replay
|
||||
models/load/owner/prefix paths, pure shared gauge extraction and live consumers,
|
||||
routed UI/editor changes, all four new test partials, docs/README, graph and
|
||||
existing Release outputs.
|
||||
|
||||
| Criterion | Decision | Evidence |
|
||||
|---|---|---|
|
||||
| AC-01 | ACCEPTED | Real strict archive/file load into fresh RecordedReplay identity; no profiles/model required; failed/cancelled/stale replacement preserves previous context and close drains |
|
||||
| AC-02 | ACCEPTED | Exact four-record fixture/last-Good 850 after Uncertain 1000 then Timeout; backward/ordinal/zero-time/ties/empty/non-signal/partial acknowledgement and original completion retained |
|
||||
| AC-03 | ACCEPTED | Controlled 0.25x/1x/1000x waits and exact 1.7-second pause/resume; one owner, held-cleanup/reentry/generation checks, visible clock/wait/drain faults and explicit recovery |
|
||||
| AC-04 | ACCEPTED | Shared definition/projection/editor/generic renderer with canonical/pinned unit bounds, actual control-event rejection and no gauge-owned clock; original/current source clearly separated |
|
||||
| AC-05 | ACCEPTED ON WORKER EXECUTION EVIDENCE | Reported complete nine-project Release build zero warnings/errors; 179 unit + 171 integration passes (350 total, zero failed/skipped), zero live/model/write counters and offline native static/dynamic final-binary replay |
|
||||
| AC-06 | ACCEPTED | Executable case mapping, post-green self-review/fixes and expanded fault/coexistence tests, aligned docs with native/control/known-preparation limitations |
|
||||
| AC-07 | ACCEPTED | Nine-project graph, dependency policy/Core/Diagnostics/Simulation/history/protected files preserved; no stage/commit/push/agents or subsequent work; task-owned native data cleaned |
|
||||
|
||||
The 37 added integration cases preserve the prior 313. Source-case inventory,
|
||||
unchanged reference graph and existing artifacts corroborate worker execution;
|
||||
the orchestrator ran no application builds/tests/native/workload commands.
|
||||
The worker reports SDK patch 10.0.403 under the existing allowed roll-forward,
|
||||
with no SDK/workload/package installation/update performed.
|
||||
|
||||
Native evidence includes real saved v1/v2 archives, an empty profile catalogue
|
||||
after restart, four speed styles/units, exact source hashes before/after, editor
|
||||
draft pinning, hide/show, pause/navigation/end/close, partial acknowledgement and
|
||||
another final-binary restart. Exact timing/drain/fault proof is controlled tests,
|
||||
not human-speed native observations.
|
||||
|
||||
The worker disclosed an unchanged recording-panel initialization error during
|
||||
source preparation while a previous Save-refresh was pending. It was not called
|
||||
a passing smoke or changed under replay scope. Preparation was restarted; final
|
||||
replay checks passed. Track separately, do not add it to Step-09.
|
||||
|
||||
## Prospective calibration split and Step-09 handoff
|
||||
|
||||
The former calibration/programming envelope combines data authoring/versioning
|
||||
with backup, approval, write/readback and recovery lifecycles. Apply the existing
|
||||
bounded-scope policy before execution:
|
||||
|
||||
- Step-09: in-memory synthetic scalar/fixed-axis table definitions, exact
|
||||
immutable configuration/module binding, baseline/proposed revisions and diffs.
|
||||
- Step-10: separately verified simulated baseline/backup, approval/source/proposal
|
||||
binding, write/readback/unrelated-value proof, audit and restore.
|
||||
- Former unassigned Steps 10-22 become 11-23; no completed assignment/history
|
||||
renumbered and no planned feature disguised as a corrective letter.
|
||||
|
||||
[Step-09](Step-09.md) uses explicit configuration-derived synthetic data, not an
|
||||
ECU read or verified backup. Proposal validation grants no Tested/Approved/
|
||||
Applied status, simulation mutation or hardware authority. No calibration disk
|
||||
format/storage or programming service is assigned in this slice.
|
||||
|
||||
## Prerequisites, limitations, and known issues
|
||||
|
||||
- Step-01A worker evidence establishes portable and native Windows compatibility
|
||||
|
|
@ -1040,24 +1097,24 @@ No live source/session, physics execution or archive rewrite is authorized.
|
|||
Step-04B. Step-05's original and follow-up findings are closed. Preserve the 190-/
|
||||
202-/207-case reports and original numerical/native evidence distinctly.
|
||||
- Profile metadata/UI, synthetic diagnostics, deterministic dynamics/v2 and the
|
||||
corrected dashboard/display units/recording archive are accepted.
|
||||
Replay, calibration values, AI and physical hardware operations
|
||||
corrected dashboard/display units/recording archive/replay are accepted.
|
||||
Calibration authoring/programming, AI and physical hardware operations
|
||||
remain unimplemented.
|
||||
- No application build or test has been executed by the orchestrator.
|
||||
|
||||
## Review and progression gate
|
||||
|
||||
On manual return, evaluate Step-08 and its frozen replay contract/shared gate using the
|
||||
On manual return, evaluate Step-09 and its frozen authoring 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 explicit replay provenance, exact prefix/seek/tie semantics, one clock
|
||||
owner/drain/generation, source/error projection, shared gauges/units and true
|
||||
offline behavior. Do not add interpolation/streaming/layout/format requirements.
|
||||
- If accepted: accept Step-08, update roadmap/state, prepare a bounded Step-09 calibration assignment
|
||||
- Inspect exact source/definition applicability, immutable baseline/proposal
|
||||
history, atomic validation/head checks, precise scalar/table diffs and unchanged
|
||||
model/source behavior. Do not add deferred programming/storage/approval scope.
|
||||
- If accepted: accept Step-09, update roadmap/state, prepare a bounded Step-10 simulated-programming assignment
|
||||
and stop for manual handoff.
|
||||
- If deficient: issue narrowly scoped Step-08A only for a material unmet contract/
|
||||
- If deficient: issue narrowly scoped Step-09A 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.
|
||||
|
|
@ -1129,12 +1186,15 @@ claim; do not claim independent runtime verification.
|
|||
| 2026-10-30 | Step-07B returned and ACCEPTED | Actual pre-fix close/reset deadlocks, corrected gate/task ordering, preserved prefix and shared cleanup-failure assertions plus reported 313-case/clean Release/native evidence inspected |
|
||||
| 2026-10-30 | Corrected Step-07 ACCEPTED | Original and 07A/07B criteria closed; source archive/limits/storage/default-unit behavior preserved; no 07C |
|
||||
| 2026-10-30 | Step-08 prepared | Saved validated archive, explicit RecordedReplay context, prefix-correct gauges/seek and one cancellable clock; manual handoff pending, calibration blocked |
|
||||
| 2026-10-30 | Step-08 returned and ACCEPTED | Frozen replay contract satisfied; reported 350-case/clean Release/offline native evidence, exact prefixes/time/owner/source/units and self-review inspected; no 08A |
|
||||
| 2026-10-30 | Calibration envelope split prospectively | Step-09 authoring/versioning/diffs, Step-10 simulated programming; former unassigned 10-22 become 11-23; completed history preserved |
|
||||
| 2026-10-30 | Step-09 prepared | Configuration-derived synthetic baseline, immutable scalar/table proposals and exact diffs; no model mutation, approval/backup/programming or physical writes |
|
||||
|
||||
## Manual handoff instruction
|
||||
|
||||
Provide [Step-08.md](Step-08.md) and the shared
|
||||
Provide [Step-09.md](Step-09.md) and the shared
|
||||
[worker gate](WORKER-QUALITY-GATE.md) to the separate worker and request execution
|
||||
of that assignment only. The worker must produce `prompts/Step-08-Report.md`
|
||||
and stop for review. Do not begin Step-09 calibration.
|
||||
of that assignment only. The worker must produce `prompts/Step-09-Report.md`
|
||||
and stop for review. Do not begin Step-10 simulated programming.
|
||||
Return manually to the orchestrator for review. Reports, including final chat
|
||||
reports, must follow the single plain triple-backtick copy-window requirement.
|
||||
|
|
|
|||
|
|
@ -0,0 +1,302 @@
|
|||
```
|
||||
# Step-08 - Recorded telemetry replay
|
||||
|
||||
## Status
|
||||
|
||||
COMPLETE. Implementation, controlled/rendered verification, the complete
|
||||
nine-project Release build, all regressions and native saved-data replay
|
||||
checks passed. Step-08 remains pending manual orchestrator review; this report
|
||||
does not grant acceptance. Accepted Step-07/07A/07B is preserved. Step-09 was
|
||||
not started. No agents, automatic handoff, staging, commit or push occurred.
|
||||
|
||||
## Implemented functions, files and interfaces
|
||||
|
||||
Application:
|
||||
|
||||
- [TelemetryReplayModels.cs](../src/AutoForge.Application/Features/Vehicles/Telemetry/Replay/TelemetryReplayModels.cs):
|
||||
separate RecordedReplay instance/capture context, cursor/count/state,
|
||||
immutable original archive, typed command failures, recorded sample
|
||||
observation/time context and a persistent actual fault reason.
|
||||
- [TelemetryReplaySession.cs](../src/AutoForge.Application/Features/Vehicles/Telemetry/Replay/TelemetryReplaySession.cs):
|
||||
fresh-session factory, strict explicit load/list, atomic replacement,
|
||||
per-load partial acknowledgement, definitions/rate validation, time/ordinal/
|
||||
Next/Previous/First navigation, Play/Pause/Stop/Restart, shared cleanup and
|
||||
asynchronous close. Its inputs are only ITelemetryArchiveStore,
|
||||
TimeProvider and IReplayWaiter. It has no diagnostic/profile/model/save port.
|
||||
- [ReplayPrefixProjection.cs](../src/AutoForge.Application/Features/Vehicles/Telemetry/Replay/ReplayPrefixProjection.cs):
|
||||
metadata-only positive-snapshot binding index and bounded exact-prefix
|
||||
rebuilding with per-module current/last-Good/status caches and original
|
||||
sample positions. It does not infer a catalogue, fill future values, sort
|
||||
model time or modify archive objects.
|
||||
- [DashboardGaugeProjection.cs](../src/AutoForge.Application/Features/Vehicles/Telemetry/LiveDashboard/DashboardGaugeProjection.cs):
|
||||
pure shared definition/binding validation and numeric/quality/range/
|
||||
last-Good projection extracted from the accepted live feature.
|
||||
[LiveDashboardAcquisition.cs](../src/AutoForge.Application/Features/Vehicles/Telemetry/LiveDashboard/LiveDashboardAcquisition.cs)
|
||||
consumes those helpers while retaining its actual session/acquisition owner.
|
||||
|
||||
UI:
|
||||
|
||||
- [TelemetryReplayPage.razor](../src/AutoForge.UI/Features/Vehicles/Telemetry/Replay/TelemetryReplayPage.razor)
|
||||
owns /telemetry-replay, a fresh replay session, list/load, recorded provenance,
|
||||
original completion, acknowledgement, all playback/navigation/rate controls,
|
||||
current raw/decoded inspection and close/unmount drainage.
|
||||
- [LiveDashboardPanel.razor](../src/AutoForge.UI/Features/Vehicles/Telemetry/LiveDashboard/LiveDashboardPanel.razor)
|
||||
shares the existing editor, pinned-unit draft handling, canonical bounds,
|
||||
display conversion and generic numeric/bar rendering through a distinct
|
||||
Replay input. It creates no live feed for replay and does not own its clock.
|
||||
Recorded labels include Good, Paused, Completed, unavailable and Stale
|
||||
values, plus actual observation/capture/diagnostic/model context.
|
||||
- [AddAutoForgeUi.cs](../src/AutoForge.UI/Features/Foundation/AddAutoForgeUi.cs),
|
||||
[MainLayout.razor](../src/AutoForge.UI/Layout/MainLayout.razor) and
|
||||
[Home.razor](../src/AutoForge.UI/Features/Foundation/Home.razor) wire factory
|
||||
composition and shared navigation.
|
||||
|
||||
New tests are the TelemetryReplayTests partial class in
|
||||
[TelemetryReplayTests.cs](../src/tests/AutoForge.IntegrationTests/TelemetryReplayTests.cs),
|
||||
[TelemetryReplayLifecycleTests.cs](../src/tests/AutoForge.IntegrationTests/TelemetryReplayLifecycleTests.cs),
|
||||
[TelemetryReplayPresentationTests.cs](../src/tests/AutoForge.IntegrationTests/TelemetryReplayPresentationTests.cs)
|
||||
and [TelemetryReplaySourceCoexistenceTests.cs](../src/tests/AutoForge.IntegrationTests/TelemetryReplaySourceCoexistenceTests.cs).
|
||||
The initial fixture, timing, rejection and rendered contracts were written
|
||||
before production implementation; additional interleavings were added during
|
||||
the post-green source-path review.
|
||||
|
||||
No new project, dependency, schema, transport, protocol, physics clock,
|
||||
DiagnosticSessionIdentity, global vehicle registry or generic timeline framework
|
||||
was introduced.
|
||||
|
||||
## Frozen C-01..C-14 matrix
|
||||
|
||||
All rows below are PASSED. Named methods are executed tests, not proposals.
|
||||
|
||||
| ID | Named evidence and exact outcome |
|
||||
|---|---|
|
||||
| C-01 | OfflineLoad_PreindexesOnlyMetadataAndReconstructsTheExactFourRecordPrefix; DynamicArchive_ReplaysOfflineWithRepeatedModelTimeAndOriginalCanonicalBytes. Real recorder/codec/filesystem input survives source disposal; offline DI has no original profiles/configurations. Explicit load establishes RecordedReplay plus a new instance and capture ID, Stopped, count 0, position 0, no measurements and no autoplay. |
|
||||
| C-02 | OfflineLoad_PreindexesOnlyMetadataAndReconstructsTheExactFourRecordPrefix. At 1.5 s: count 1, A=850 Good and no B sample. At 2 s: count 3, A=1000 Uncertain, B=12.6 Good. At 4 s: count 4, A=850 Stale from observation 1 / 1 s, B remains 12.6 Good. The Uncertain 1000 is never promoted into last-Good authority. |
|
||||
| C-03 | The same independent fixture and MidGapPause_DrainsOneOwnerAndResumeWaitsOnlyTheRemainingInterval. Previous from count 4 reconstructs count 3 / Uncertain 1000; ordinal 1 clears B and its later module status. First/Stop clear all values and caches to count 0 / time 0, retaining definitions, valid speed and acknowledgement. Seek time preserves the exact requested between-record playhead. Restart is explicit rewind-plus-Play; Completed does not silently replay. |
|
||||
| C-04 | EqualAndZeroTimes_ManualNextIsOneButTimeSeekAndPlayApplyCompleteGroups; EmptyAndNonSignalArchives_NeverFabricateMeasurementsOrUseUtcDuration. Next applies one even inside a tie; time seek/Play apply whole due groups in sequence. Four zero-time records complete without a wait. Empty Play/Restart completes without a timer; empty seek zero is Stopped; empty Next/Previous visibly rejects. DTC observations change inspection/count/time but never invent signals/module read status. |
|
||||
| C-05 | ControlledPacing_ScalesCaptureIntervalsWithoutChangingRecordedResults at 0.25x, 1x and 1000x; MidGapPause_DrainsOneOwnerAndResumeWaitsOnlyTheRemainingInterval. First 1 s interval waits 4 s, 1 s or 1 ms respectively; the next 1 s interval and final 2 s interval scale identically. Final recorded values/prefixes are identical at every rate. At 2x from 1.5 s, the next group waits 0.25 wall seconds; a 0.10-second pause freezes exactly 1.7 s/count 1, and resume waits exactly 0.15 more seconds despite wall time advancing while paused. |
|
||||
| C-06 | MidGapPause_DrainsOneOwnerAndResumeWaitsOnlyTheRemainingInterval; EndPublication_RejectsReentryBeforeThePriorOwnerFinishesCleanup; CloseWithDelayedOldWake_NeverPublishesIntoClosedOrFreshFactorySession; WaitFault_IsVisibleAndKeepsCommittedPrefixUntilExplicitRecovery; ClockFaults_AreVisibleWithoutChangingTheLastCommittedSampleAndCanBeStopped (start/wake/pause); WaitFailureDuringPauseOrStop_DrainsButCannotMasqueradeAsSuccessfulCleanup (Pause/Stop). Repeated active Play creates one wait; pending drainage rejects competing starts/navigation/replacement before mutation. Seven end-publication reentries reject Busy. Repeated Stop and Close share their completion. Delayed wakes never publish into a closed/fresh context. Faults retain the committed prefix/sample state, remain visible after cleanup and require explicit recovery; a fault during Stop is not rewritten into successful empty Stopped state. |
|
||||
| C-07 | InvalidRequests_AreTypedVisibleAndAtomicIncludingClosedAndUnloadedPlayers; ActualRouteControls_ReconcileRejectedRateRequirePartialAcknowledgementAndDrainOnUnmount. Undefined/unloaded/closed and invalid time/count/rate commands reject without context/value/definition/position/rate/ownership mutation, except explicit error notification. NaN, both infinities, 0.249x and 1000.001x reject; 0.25x and 1000x are accepted. Invalid exact unit, label, kind, range, precision, duplicate identifier and ninth gauge reject atomically. Eight and zero gauges are accepted. Actual bound speed input returns to committed 1 after rejecting 1000 while Playing. |
|
||||
| C-08 | PartialAcknowledgement_IsPerLoadAndEndNeverRewritesOriginalCompletion (Incomplete/Error); ActualRouteControls_ReconcileRejectedRateRequirePartialAcknowledgementAndDrainOnUnmount; native partial warning check. Play/Next/seek require that load's explicit acknowledgement. Stop/First/inspection/Close remain allowed. End means Completed replay/end of retained data while original Incomplete or Error and its reason remain unchanged. Reload creates a new instance, clears acknowledgement/definitions/cursor and retains valid speed/global units. |
|
||||
| C-09 | RecordedQualityAndUnitChanges_UseSharedRulesWithoutFutureOrCrossModuleFill (Unknown/null/text/nonfinite/unit-change/real-zero); MissingSignalOrNoPriorGood_UsesRecordedStaleOrExplicitErrorOnlyForTheAffectedModule; CorruptReplacementAndChangedOrigin_AreRejectedByTheActualStrictReaderWithoutReplacingReplay. Missing/unit-changed reads retain prior Good only as recorded Stale; without any prior Good, failed A is Error/--. B remains Good. A real Good zero remains numeric and later Stale zero, not a fabricated missing value. Unknown/non-numeric/nonfinite values stay unavailable. Uncertain 1000 over a 0..900 range retains Uncertain plus high-range status and 100% geometry; a later timeout restores 850 Stale, with original time. Unsupported source-origin edits fail strict loading atomically. |
|
||||
| C-10 | RenderedRecordedRouteAndSharedEditor_ShowRejectionsPinnedUnitsAndNoGaugeOwnedClock; ActivePlayback_SharedGaugeHideUnitsAndUnmountCannotOwnTheClock; InvalidRequests_AreTypedVisibleAndAtomicIncludingClosedAndUnloadedPlayers; native temperature/bar draft check. Shared configuration supports 0..8 gauges. Invalid real editor events retain the committed definition. An Imperial draft stays pinned across a global Metric switch, and an unedited 40 m/s canonical bound remains exactly 40. Hiding/showing, unit changes, definition removal and gauge unmount during active playback neither cancel nor add a wait; the same owner continues with zero gauges. |
|
||||
| C-11 | FailedCancelledAndLateLoads_PreserveValidatedContextAndCloseDrainsWithoutStalePublication; CorruptReplacementAndChangedOrigin_AreRejectedByTheActualStrictReaderWithoutReplacingReplay; CloseWithDelayedOldWake_NeverPublishesIntoClosedOrFreshFactorySession. Missing/corrupt/cancelled replacements retain the prior archive/context/data/definitions/position/rate. A held store deliberately ignores cancellation until released; close invalidates its generation first, shares an unfinished completion, drains it and prevents late publication. Busy loads reject overlapping commands. No failure is represented as a healthy empty replacement. |
|
||||
| C-12 | OriginalPhysicalMetadata_IsNotRewrittenIntoCurrentReplayOrVehicleEvidence; DynamicArchive_ReplaysOfflineWithRepeatedModelTimeAndOriginalCanonicalBytes; actual rendered route/native provenance. Current kind is RecordedReplay; original Simulation or PhysicalHardware metadata remains unchanged. ModelResetAndRepeatedModelTime_RemainRecordedFactsNotPlaybackOrdering verifies actual recorded model steps 3,0,0,0 at capture times 1,2,2,4 seconds, including backward reconstruction of step 3. No diagnostic factory/control or catalogue fallback is used by replay. |
|
||||
| C-13 | ReplayCoexistsWithRealLiveSource_WithoutReadsModelCallsOrRecordingWorkspaceRebind and the byte assertions throughout. A simultaneously open real dynamics source stays at step 7 with unchanged trace/status; transport-call delta=0, model-control-call delta=0 and archive Save calls=0 during replay/seek/unit operations. Its stopped unsaved recording serializes identically and is not rebound. An explicit subsequent live read succeeds and increments only the transport counter by one. Offline rendered DI also has failing live/model ports with both counters zero. Actual source archive bytes remain identical. All 313 accepted baseline cases remain present and pass. |
|
||||
| C-14 | ActualRouteControls_ReconcileRejectedRateRequirePartialAcknowledgementAndDrainOnUnmount; RenderedRecordedRouteAndSharedEditor_ShowRejectionsPinnedUnitsAndNoGaugeOwnedClock; RenderedClockFault_RemainsVisibleDespitePriorCommandErrorAndRejectedRecoveryNavigation; native checks below. The real store/strict reader/Application/shared editor/native route supports saved static-v1/dynamic-v2 replay after app restart with an empty profile catalogue, normal controls, units, hide/show, end and close/re-entry. Timing/fault/race proof is controlled, not attributed to native human-speed observations. |
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
| ID | Result | Evidence |
|
||||
|---|---|---|
|
||||
| AC-01 | PASSED | C-01/C-11/C-12 real file loading, offline DI, atomic failed/cancelled replacement, generation guards and distinct current/original provenance. |
|
||||
| AC-02 | PASSED | C-02..C-04/C-08/C-09 independent exact value/count/time/status assertions, before-first/ties/empty/partial handling and affected-module last-Good reduction. |
|
||||
| AC-03 | PASSED | C-05..C-07 controlled monotonic waits/barriers, exact pause/resume, held cleanup, reentry, clock/wait/drain faults, typed rejections and explicit recovery. |
|
||||
| AC-04 | PASSED | C-10/C-12 real rendered controls/editor and native numeric/bar/unit/draft/provenance checks; accepted live tests remain green. |
|
||||
| AC-05 | PASSED | Final nine-project Release build: zero warnings/errors. 179 unit + 171 integration = 350 passes, zero failed/skipped. Native static/dynamic offline playback passed, including a final-binary restart confirmation. Zero live/model/write counters and unchanged native source hashes corroborate isolation. |
|
||||
| AC-06 | PASSED | Executable frozen matrix, post-green source-path review/fixes, related documentation and truthful native-versus-controlled evidence below. |
|
||||
| AC-07 | PASSED | main/65eed57 unchanged; no protected/history/orchestration/dependency changes, no staging/commit/push/agents, task-owned native data/helpers cleaned, and this single fenced report saved. Worker stops here. |
|
||||
|
||||
## Final commands and outcomes
|
||||
|
||||
SDK: dotnet --version -> 10.0.403 under the existing global.json roll-forward.
|
||||
The framework/platform is existing xUnit v2/VSTest, not MTP. No packages,
|
||||
SDKs, workloads or tools were installed, updated, repaired or restored.
|
||||
|
||||
The following ran sequentially after the final implementation/self-review:
|
||||
|
||||
| Exact command | Exit | Result |
|
||||
|---|---:|---|
|
||||
| dotnet test .\src\tests\AutoForge.IntegrationTests\AutoForge.IntegrationTests.csproj --configuration Release --no-restore --filter "FullyQualifiedName~TelemetryReplayTests|FullyQualifiedName~LiveDashboardAcquisitionTests|FullyQualifiedName~DisplayUnitControlTests" | 0 | 49 passed, zero failed/skipped: 37 new replay cases plus 12 accepted live-dashboard/unit-selector cases. |
|
||||
| dotnet build .\src\AutoForge.slnx --configuration Release --no-restore | 0 | All nine projects, including native Windows Client; 0 warnings, 0 errors. MAUI XAML source-generation output was informational. |
|
||||
| dotnet test .\src\AutoForge.slnx --configuration Release --no-build | 0 | 179 unit + 171 integration = 350 passed, zero failed/skipped. |
|
||||
| git --no-pager diff --check | 0 | No whitespace errors. Git reported only its existing LF-to-CRLF conversion notices for README/build guide. |
|
||||
| git --no-pager diff --exit-code -- prompts Directory.Build.props Directory.Packages.props global.json NuGet.Config src\AutoForge.Core src\AutoForge.Diagnostics src\AutoForge.Simulation | 0 | Existing assignments/history/state/gate, dependency policy and foundational source implementations unchanged before adding this report. |
|
||||
|
||||
Per-project build result: AutoForge.Core, AutoForge.Diagnostics,
|
||||
AutoForge.Simulation, AutoForge.Application, AutoForge.Components,
|
||||
AutoForge.UI, AutoForge.Client, AutoForge.UnitTests and
|
||||
AutoForge.IntegrationTests all PASSED. Portable projects remain net10.0;
|
||||
Client remains net10.0-windows10.0.26100.0 / win-x64.
|
||||
|
||||
The 313-case baseline is 179 unit + 134 integration. This step adds 37
|
||||
integration cases and deletes or weakens no baseline tests.
|
||||
Existing limits remain 4,096 observations, 16 MiB encoded observations,
|
||||
1 MiB header, 32 MiB archive and JSON depth 128. Gauge limits remain 0..8
|
||||
with precision 0..3; valid rates are 0.25x..1000x inclusive. Individual waits
|
||||
are bounded at 30 wall seconds with cancellable monotonic pacing.
|
||||
|
||||
Earlier iterations are not disguised as passing evidence:
|
||||
|
||||
- Initial compilation failed on the extracted unused key, Razor binding
|
||||
quoting/nullability, a test-method insertion and nullable fault-message
|
||||
flow. Each was corrected and the applicable checks rerun.
|
||||
- The first executable focused run had 26 passes/4 failures: the shared live
|
||||
missing-signal reason changed, the dynamic fixture selected a nonexistent
|
||||
body endpoint, and an InlineData integer could not bind to nullable double.
|
||||
The original live reason was restored and fixture/type errors corrected.
|
||||
- Later focused runs exposed a too-exact floating-point text expectation and
|
||||
an optimized Action event callback in the test renderer. The test now
|
||||
verifies the independent conversion numerically and dispatches actual
|
||||
renderer events with field feedback, rather than casting callbacks.
|
||||
- First green was 30 cases. The post-green review expanded this to the final
|
||||
49 focused cases and 350 full passes. Compilation failures are not claimed
|
||||
as behavioral pre-fix reproductions; this was a new feature, not a claim
|
||||
that replay existed before this assignment.
|
||||
|
||||
## Native observations and controlled-evidence distinction
|
||||
|
||||
The actual Release AutoForge.Client executable was launched with task-owned
|
||||
WebView2 user data and local DevTools port 9378. A temporary Node/built-in
|
||||
WebSocket helper operated the actual native WebView controls; there was no
|
||||
new web host, dependency or production debug feature.
|
||||
|
||||
The real MAUI storage root was verified as:
|
||||
|
||||
C:\Users\g3\AppData\Local\User Name\com.companyname.autoforge.client\Data\recordings
|
||||
|
||||
LOCALAPPDATA was not assumed to redirect FileSystem.AppDataDirectory.
|
||||
The archive directory initially contained zero files.
|
||||
|
||||
Normal native evidence:
|
||||
|
||||
1. Static v1 capture 5ae80280d3454f73bfc1fd001d2d88d2 retained four actual
|
||||
operations, including engine/body DTC and signal reads. It was stopped,
|
||||
source-closed and saved. After restart the profile catalogue was empty;
|
||||
the replay route loaded it explicitly at count/time zero, configured a
|
||||
numeric gauge before data, applied a non-signal first record without
|
||||
fabricating a value, then displayed recorded 850 rpm from observation 2.
|
||||
2. Static Play/Pause exposed a frozen between-record playhead. A speed edit
|
||||
to 1000 while Playing visibly rejected and reset the actual input to 1.
|
||||
Quiescent 1000x reached all four retained observations; Previous and Stop
|
||||
worked, and Stop cleared readings to -- while retaining the definition.
|
||||
3. Dynamic v2 capture 82af7a5151e74820a9a31eeb12de71a1 retained four actual
|
||||
read.signals operations at stopped model step 7 / 0.7 seconds, with original
|
||||
configuration/run. It was stopped, source-closed and saved, then replayed
|
||||
after restart without reimporting profiles or recreating a model.
|
||||
4. The dynamic horizontal bar displayed source 88.02090573589594 degC as
|
||||
88.02 degC or 190.44 degF. An edit opened in Imperial units showed 32..212
|
||||
degF; changing global units to Metric kept the draft pinned to Imperial/
|
||||
degF, and an unedited save retained exact canonical 0..100 degC bounds.
|
||||
Hide/show did not change count/playhead. Seek 40,000,000 ticks retained
|
||||
exactly two records; Next/Previous, Play/Pause, end, First, active-play
|
||||
route unmount and fresh Unloaded re-entry were exercised.
|
||||
5. Warning-only fixture c91b0cd68fef4f18b10d4de81f648b35 was a separately
|
||||
named derived copy of the real static observations, with explicit
|
||||
Incomplete/LimitExceeded fixture completion. The actual strict store
|
||||
validated it. Native Next rejected before acknowledgement at count zero;
|
||||
acknowledgement and ordinal end retained original Incomplete and the
|
||||
"end of retained data" warning. This is native warning/acknowledgement
|
||||
evidence, NOT evidence of native count-limit exhaustion.
|
||||
6. After the final fault/cleanup refinements and final 350-pass build, new
|
||||
native confirmation captures were produced:
|
||||
db553b85c9fd4e55a3c887801fafda7b (static v1, two actual operations) and
|
||||
5f6516fdd718411f96bdb0e00229ce78 (dynamic v2, four actual operations at
|
||||
model step 7). The app was restarted again. Its profile catalogue was
|
||||
explicitly confirmed empty. The final binary loaded both stopped before
|
||||
first, navigated/played them to counts 2/2 and 4/4, showed correct v1/v2
|
||||
original provenance, stopped and closed with cleanup pending False.
|
||||
Static duration was 217,926 ticks; dynamic duration was 92,006 ticks.
|
||||
|
||||
Source immutability was checked before and after native playback:
|
||||
|
||||
| Native capture | Unchanged SHA-256 |
|
||||
|---|---|
|
||||
| 5ae80280d3454f73bfc1fd001d2d88d2 | 07336400F122570ADA157C3A7B9B9EEAB8433D2B68121239BF95C4E03FF47DCA |
|
||||
| 82af7a5151e74820a9a31eeb12de71a1 | 3B6339FAA09C75BEC8518E4E0345B3FAD984819FF279B5237D58364224798ABC |
|
||||
| db553b85c9fd4e55a3c887801fafda7b | A31C968EC2A88A48CD5F3BB4BBFA03B52E7804488C71897081E0690CF645E87C |
|
||||
| 5f6516fdd718411f96bdb0e00229ce78 | E7D4712AE417C4128036EEFBF5A6AD7101A19D5E2AE56D8C4ECDF39123C76C3D |
|
||||
|
||||
Native timing is normal UI observation only. Exact rates/mid-gap resume,
|
||||
large-gap overflow bounds, concurrent ownership, malformed/cancelled/late
|
||||
loads, source limits/errors and injected clock/wait/drain faults are proved
|
||||
by controlled headless tests, not native elapsed-time claims.
|
||||
|
||||
Native preparation limitation: navigating between the existing recording
|
||||
hosts while a Save-triggered refresh was pending exposed their pre-existing
|
||||
uncaught "Another archive command is pending" initialization failure. A
|
||||
brief enabled control/saved label can precede that follow-up refresh. This
|
||||
stack was in unchanged TelemetryRecordingWorkspace.RefreshAsync and
|
||||
TelemetryRecordingPanel.OnInitializedAsync, not the replay route. It was
|
||||
not silently called a successful smoke or broadened into a recording change.
|
||||
Source preparation was restarted; final confirmation captures were prepared
|
||||
in separate app runs, then replayed after another restart. Assigned replay
|
||||
checks subsequently passed with no native error overlay.
|
||||
|
||||
Cleanup PASSED: all seven task-launched Client process sessions completed;
|
||||
only their specific PIDs were terminated, with replay/source already closed
|
||||
where applicable. The five exact named task-owned archive files above
|
||||
(including the warning fixture) were removed after verification; the archive
|
||||
directory again contains zero files. The task-only WebView profile and helper
|
||||
were removed, no task WebView processes remained, and port 9378 had no
|
||||
listener. The existing/default WebView data and unrelated app data were not
|
||||
removed. Original Metric/Road preference values were restored and observed.
|
||||
|
||||
## Post-green source-path self-review
|
||||
|
||||
Reviewed actual producers/consumers from factory -> strict store/codec ->
|
||||
metadata index/prefix reduction -> owner/control snapshots -> routed page ->
|
||||
shared editor/display converter/generic renderer. Public entry points reviewed
|
||||
were Create, RefreshSavedCapturesAsync, LoadAsync, ReplaceDefinitions,
|
||||
AcknowledgePartial, SetRate, SeekTime, SeekOrdinal, Next, Previous, First,
|
||||
PlayAsync, RestartAsync, PauseAsync, StopAsync and DisposeAsync.
|
||||
|
||||
Normal, invalid, partial, equal/zero-time, backward, cancelled, faulted and
|
||||
overlapping paths were walked against C-01..C-14. Eligibility is checked before
|
||||
mutation. Resource release and the shared completion occur before ownership
|
||||
becomes eligible for reuse; cancellation/drain awaits do not hold the state
|
||||
gate. Data publication requires the current owner/generation; late closed
|
||||
loads/wakes cannot publish. Metadata pre-indexing never supplies current
|
||||
values. Faults retain original sample state, not a false successful end.
|
||||
|
||||
Findings fixed within Step-08:
|
||||
|
||||
- Removed the small cleanup/reuse eligibility window by releasing cancellation
|
||||
resources before clearing owner/load eligibility and completing the shared
|
||||
task under the state gate.
|
||||
- Explicitly rejected data navigation/restart from Faulted until Stop/First
|
||||
after cleanup; added exact atomic-state assertions.
|
||||
- Preserved actual fault reason separately so an older UI command error or
|
||||
later rejection cannot conceal a scheduler fault.
|
||||
- Kept a non-cancellation wait fault during pending Pause/Stop visible Faulted,
|
||||
rather than ignoring it as a stale wake or resetting it into success.
|
||||
- Corrected native protocol-version Razor rendering and retained accepted
|
||||
live missing-signal wording during shared projection extraction.
|
||||
- Added real simultaneous live-source/unsaved-recording isolation and active
|
||||
gauge-unmount/zero-gauge owner tests instead of relying on render counts
|
||||
or an offline-only proxy.
|
||||
|
||||
All affected focused checks and required full build/regressions were rerun
|
||||
after these fixes; final results are the 49/350 passes recorded above.
|
||||
The final binary's normal saved-capture path was then checked natively again.
|
||||
No known unresolved defect in the assigned replay exit contract remains.
|
||||
|
||||
## Documentation and preservation
|
||||
|
||||
Updated [README.md](../README.md),
|
||||
[documentation index](../docs/README.md),
|
||||
[architecture](../docs/architecture.md),
|
||||
[build/test guide](../docs/build-and-test.md),
|
||||
[live dashboard contracts](../docs/live-dashboard.md) and
|
||||
[archive-v1 guide](../docs/telemetry-archive-v1.md); added
|
||||
[recorded replay usage/contracts](../docs/telemetry-replay.md).
|
||||
They distinguish accepted corrected recording from Step-08 pending review,
|
||||
current replay versus original provenance, before-first versus zero-time seek,
|
||||
exact prefixes/ties/last-Good, independent clocks, rates/drain/replacement,
|
||||
partial acknowledgement, source immutability and native/control limitations.
|
||||
|
||||
The worktree began clean on main at 65eed57 and HEAD is unchanged. Existing
|
||||
prompts/history/state/roadmap/assignment/shared gate were not edited; this is
|
||||
the only new prompts file. No protected instruction file was created or
|
||||
modified. The index remains empty. All nine projects/references and central
|
||||
dependency/SDK policy remain unchanged; source/tests stay under src and
|
||||
src/tests. Core/Diagnostics/Simulation implementations and physics/oracle
|
||||
surfaces are unchanged.
|
||||
|
||||
Out of scope remains interpolation/resimulation, persistence of replay layouts/
|
||||
cursor/rate, archive editing/migration/new durability, calibration/programming,
|
||||
hardware access, AI and real-vehicle verification. No future step or
|
||||
automatic orchestration action is authorized by this report.
|
||||
|
||||
STOP.
|
||||
```
|
||||
|
|
@ -0,0 +1,257 @@
|
|||
# Step-09 - Synthetic calibration authoring and immutable proposals
|
||||
|
||||
## STEP IDENTIFIER
|
||||
|
||||
Step-09. Step-08 was accepted on 2026-10-30 with no corrective assignment.
|
||||
This is the sole active implementation assignment. Step-10 programming is blocked.
|
||||
|
||||
## STEP TITLE
|
||||
|
||||
Author validated synthetic scalar/table proposals with immutable source-bound
|
||||
versions and exact diffs, without changing a model, module or source configuration.
|
||||
|
||||
## OBJECTIVE
|
||||
|
||||
One user outcome: select an existing immutable synthetic dynamics configuration,
|
||||
inspect its authoring baseline, edit supported values and compare saved proposals.
|
||||
One primary new contract: source-bound, validate-before-commit version authoring.
|
||||
|
||||
This is process-memory authoring only. No device read, verified backup, approval,
|
||||
programming, model application or calibration file format is assigned.
|
||||
Read [STATE.md](STATE.md), [ROADMAP.md](ROADMAP.md) and
|
||||
[WORKER-QUALITY-GATE.md](WORKER-QUALITY-GATE.md), establish the frozen matrix
|
||||
before coding, self-review after the first green run, write
|
||||
`prompts/Step-09-Report.md`, and STOP.
|
||||
|
||||
## ARCHITECTURAL CONTEXT
|
||||
|
||||
Keep all nine projects and one Client. Core may own small immutable calibration
|
||||
definition/value/applicability contracts; Application owns source selection,
|
||||
validation/history/diff use cases through existing configuration/profile services;
|
||||
UI owns a routed editor. Generic Components remains independent.
|
||||
No new dependency/project/host, general tuning framework, protocol, schema or
|
||||
Simulation implementation/oracle change. All source/tests stay under `src`,
|
||||
tests under `src/tests`.
|
||||
|
||||
Use the existing
|
||||
[DynamicsConfigurationService](../src/AutoForge.Application/Features/Vehicles/Simulation/DynamicsConfigurationService.cs)
|
||||
for exact configuration selection, and actual
|
||||
[DynamicsConfiguration](../src/AutoForge.Core/Simulation/DynamicsConfiguration.cs)
|
||||
metadata/parameters. Do not open a DiagnosticSession, infer live ECU values or
|
||||
guess a module from its role. This authoring template is explicitly synthetic.
|
||||
|
||||
## CURRENT IMPLEMENTATION STATE
|
||||
|
||||
Accepted features supply immutable profiles/configuration fingerprints, coupled
|
||||
dynamics, actual static/dynamic diagnostics, recording/archive, offline replay,
|
||||
shared gauges and remembered unit preferences.
|
||||
Worker baseline: clean full Release build; 179 unit + 171 integration passes
|
||||
(350 total, zero failed/skipped) and native replay evidence. The orchestrator
|
||||
did not run those checks. No calibration authoring implementation exists.
|
||||
|
||||
The warm example has IdleSpeedRpm=650, MaximumEngineSpeedRpm=5000,
|
||||
WarmIdleTargetRpm=650 and torque pairs:
|
||||
(650,240), (1000,300), (2000,360), (3200,350), (4200,300), (5000,180)
|
||||
in rpm and N*m. These are configuration facts, not a readback or verified
|
||||
vehicle calibration. Preserve all original source/configuration values.
|
||||
Inspect Git/prior art and preserve dirty work and historical assignments/reports.
|
||||
|
||||
## REQUIRED IMPLEMENTATION
|
||||
|
||||
### Frozen contract matrix
|
||||
|
||||
| ID | Input/precondition | Required result |
|
||||
|---|---|---|
|
||||
| C-01 | Explicit saved warm configuration and its actual EngineModuleIdentifier | One immutable synthetic baseline bound to exact config/profile revision/module/model/definition; 650 rpm and six actual source torque rows; no role/default/live fallback |
|
||||
| C-02 | Change only warm-idle target 650 -> 1250 rpm | New Proposed revision with exact parent/head; one scalar diff before=650, after=1250, delta=600; baseline/config/source remain unchanged |
|
||||
| C-03 | Also edit torque at 2000 rpm from 360 -> 350 N*m | Exactly two diff entries versus baseline: scalar and that axis-keyed value (delta=-10); unchanged cells/axes omitted; compare versus preceding revision shows only the new table edit |
|
||||
| C-04 | Non-finite/out-of-range scalar/cell, wrong unit/key/axis/count, malformed definition or source mismatch | Typed visible rejection before history/head/source/version mutation; no clipping, axis sorting, silent unknown field or partial save |
|
||||
| C-05 | Exact allowed bounds; no-change save; changed-back proposal | Bounds inclusive; identical head content returns same revision without consuming capacity; changing back after a different proposal creates a new immutable Proposed revision whose baseline diff is empty |
|
||||
| C-06 | Two requests based on the same head, sequential or controlled concurrent commits | At most one changed proposal commits; stale expected head/source token rejects atomically. No lost update, automatic merge or branched history |
|
||||
| C-07 | Mutate caller arrays/lists after creation/save, or inspect old revision after later edits | All definition/baseline/proposal/diff snapshots stay immutable and defensively copied; exact before/after values and parent lineage retained |
|
||||
| C-08 | Different config/profile revision/module/model/definition selected or invalid reference | No cross-source compare/save/rebind. Prior workspace stays intact on rejection; replacing a workspace requires explicit action and cannot silently discard its proposals |
|
||||
| C-09 | Metric/Imperial switch or editor rerender with unsaved torque input | Display conversion/draft input unit is explicit and pinned; canonical N*m/axis/bounds/history unchanged by toggle or unedited Save; convert edited value once before validation |
|
||||
| C-10 | First/latest/history/diff UI and invalid command | Real Application path, exact selected versions/source, visible validation; Baseline/Proposed only, never Tested/Approved/Applied/verified-backup claims |
|
||||
| C-11 | 32 saved revisions including baseline, then changed/identical save | Exact limit enforced; changed 33rd rejects without mutation, identical no-op still returns head. No disk/history eviction or unbounded hidden workspace accumulation |
|
||||
| C-12 | Authoring while a real live source/replay exists; full verification | Zero new transport/model/store-save/approval calls; source configuration export/fingerprint/recordings/replay state unchanged, 350 baseline cases and full nine-project Release/native UI pass |
|
||||
|
||||
### A. Small explicit definition and applicability
|
||||
|
||||
Support one versioned synthetic engine-authoring definition, not arbitrary
|
||||
firmware layouts. Its exact applicability includes profile identifier/revision,
|
||||
explicit configuration fingerprint, EngineModuleIdentifier, ModelIdentifier/
|
||||
ModelVersion and definition identifier/revision. Resolve the real module through
|
||||
the selected profile; preserve optional hardware/software/firmware/calibration
|
||||
metadata as supplied, not proof or automatically filled applicability.
|
||||
|
||||
Use existing identifier comparison policies for profile/module identity; config
|
||||
fingerprints, parameter/table IDs, source units and model/definition identity
|
||||
compare exactly. Unknown/mismatched references reject visibly before creation.
|
||||
No manufacturer address/offset, VIN autodetection or role-based module inference.
|
||||
|
||||
Required logical values:
|
||||
|
||||
- `engine.warm-idle-target`: finite scalar, source unit rpm, inclusive range
|
||||
[selected Model.IdleSpeedRpm, selected Model.MaximumEngineSpeedRpm].
|
||||
- `engine.torque-curve`: fixed ordered rpm axis copied exactly from the selected
|
||||
Model.EngineTorqueCurve, with editable finite N*m cell values in [1,1000].
|
||||
Support 2..32 rows; axis points remain finite, strictly increasing and within
|
||||
[0, MaximumEngineSpeedRpm]. No insertion/deletion/reordering/interpolation.
|
||||
|
||||
These authoring bounds are synthetic policy, not manufacturer-safe limits.
|
||||
If an otherwise valid configuration is outside this template (e.g. too many
|
||||
rows or a torque value outside [1,1000]), reject it explicitly; never truncate/
|
||||
normalize it or pretend all possible configurations are supported.
|
||||
Use identity value scaling only (1/offset 0); raw binary encoding is not assigned.
|
||||
Required scalar/table keys, shape, axes, units and exact counts are validated
|
||||
as a whole, not only individual editor cells.
|
||||
|
||||
### B. Immutable baseline, proposals and exact structured diff
|
||||
|
||||
Create a baseline from the selected immutable configuration on explicit action.
|
||||
Its label is "Synthetic configuration-derived baseline", not original ECU backup.
|
||||
Copy all definition/source/value collections. Baseline is revision 1/read-only;
|
||||
every valid changed save creates a new Proposed revision with a unique identity,
|
||||
monotonic revision number and exact parent/head identity.
|
||||
|
||||
Only save against the current head of the same workspace/source/definition.
|
||||
Take the expected head as an explicit command precondition and validate every
|
||||
input before committing any version/counter/head change. Reject stale commands,
|
||||
including two real competing saves; no merge/branch/latest-source fallback.
|
||||
No-change saves are idempotent and do not consume history.
|
||||
|
||||
Keep one bounded authoring workspace with at most 32 saved revisions including
|
||||
baseline. Replacement requires an explicit UI action confirming the old in-memory
|
||||
history/draft will be discarded; invalid replacement preserves it. A history
|
||||
inspection choice does not silently change the current editable head.
|
||||
No persistence/import/export format or multiple-workspace repository is assigned.
|
||||
Clearly disclose that process restart loses this in-memory authoring work.
|
||||
|
||||
Diff any two explicitly selected revisions of the same applicability/definition.
|
||||
Return only changed scalar/cells in deterministic parameter/axis order, with
|
||||
logical ID, exact axis coordinate for table cells, original source unit, before,
|
||||
after and signed delta. Compare canonical doubles, not rounded display text;
|
||||
do not hide small changes behind a UI tolerance. A changed-back proposal is still
|
||||
a proposal, not a restored device, approved rollback or verified original.
|
||||
|
||||
No automatic Tested/Approved/Applied status, write command, backup claim, model
|
||||
configuration replacement, physics step or active-source mutation.
|
||||
Future programming must independently verify a real simulated target and bind
|
||||
its approval/backup contract; authoring validation alone grants no authority.
|
||||
|
||||
### C. Real UI and existing unit preferences
|
||||
|
||||
Add `/calibration` (or an equally clear documented route) and shared navigation.
|
||||
Select exact saved configuration; allow use of the existing explicit warm-example
|
||||
creation workflow, not hidden seeded workspaces. Show full binding/provenance,
|
||||
baseline/scalar/table, editable latest proposal, history and version-pair diffs.
|
||||
Use ordinary numeric/table controls; no map visualizer or layout designer.
|
||||
|
||||
Keep definition/axes/source units read-only. Validate visible parse errors and
|
||||
the complete candidate through the real Application service; rejected saves
|
||||
preserve the current head/history/source. Identify the expected head explicitly
|
||||
so another editor cannot overwrite unnoticed. Unsaved fields must not mutate
|
||||
saved versions by binding through shared references.
|
||||
|
||||
Use the accepted shared unit converter for torque N*m/lbf*ft display and inputs;
|
||||
rpm stays rpm. Pin an active draft's input selection until Save/Cancel, preserve
|
||||
original canonical values on unedited Save and apply precision for display only.
|
||||
Show canonical source units/bounds alongside synthetic constraints and labels.
|
||||
Global unit changes/renders do not save proposals or alter source/application
|
||||
state. Keep safe text, accessible labels, visible errors and the old routes.
|
||||
Feature draft state must survive its rerenders; source/workspace replacement is
|
||||
explicit. No new generic navigation-guard or settings framework is required.
|
||||
|
||||
## FILES OR PROJECTS EXPECTED TO CHANGE
|
||||
|
||||
Focused Core calibration contracts if justified, Application authoring/validation/
|
||||
version/diff and registration, UI route/editor/navigation, tests and related
|
||||
README/docs. Client DI only if needed. No Simulation/Diagnostics model/protocol
|
||||
or archive/replay behavior change, new project/dependency or binary fixture.
|
||||
Under `prompts`, create only `Step-09-Report.md`.
|
||||
|
||||
## INTERFACE AND DEPENDENCY REQUIREMENTS
|
||||
|
||||
Preserve nine projects/references, one Client, generic Components, current exact
|
||||
profile/config/source/unit semantics, recording/replay bytes and clock ownership.
|
||||
No hardware/model write, unchecked binary offset, profile capability promotion,
|
||||
fallback source, oracle shortcut, broad catch or success-shaped invalid input.
|
||||
Do not fix the separately disclosed recording refresh/navigation issue here.
|
||||
No dependency/system/workload install/update/repair/rollback, staging/commit/push
|
||||
or destructive Git. Preserve protected/history/orchestration files and dirty work.
|
||||
|
||||
## TESTING REQUIREMENTS
|
||||
|
||||
Map C-01..C-12 to meaningful named tests before handoff:
|
||||
|
||||
- Real profile/configuration-service baseline and exact example values; scalar/
|
||||
table proposal/diff vectors, same-content no-op, changed-back and comparisons
|
||||
with exact versions/source/units/axes. Do not test just JSON/string equality.
|
||||
- Independent invalid vectors for scalar/cell NaN/infinities/bounds, axis/shape/
|
||||
key/unit/source identity, stale head, wrong configuration/model/definition;
|
||||
assert prior head/history/source snapshots remain exactly unchanged.
|
||||
- Defensive-copy tests, deterministic competing-head saves and exact 32/33
|
||||
revision boundary. Use controlled barriers rather than sleeps or stress races.
|
||||
- Real DI/rendered editor commands, invalid input, history/diff selection,
|
||||
source replacement confirmation, pinned torque-unit draft and canonical
|
||||
equality across repeated preference changes and unedited saves.
|
||||
- Actual live source/replay coexistence with counted diagnostic/model/store
|
||||
boundaries; authoring must add zero calls and leave config export/fingerprint/
|
||||
recordings/replay state unchanged. Do not mock away the authoring service.
|
||||
|
||||
Run focused cases, then sequentially:
|
||||
|
||||
- `dotnet build .\src\AutoForge.slnx --configuration Release --no-restore`
|
||||
- `dotnet test .\src\AutoForge.slnx --configuration Release --no-build`
|
||||
|
||||
Preserve 350 baseline cases (179 unit, 171 integration) plus meaningful new
|
||||
coverage. Map intentional UI-only assertion changes without deleting safety/
|
||||
error/source checks. Build all nine projects/native Client. Install/restore
|
||||
nothing absent a genuine chosen-command missing dependency.
|
||||
|
||||
Native smoke: explicitly create/select real warm configuration, open authoring
|
||||
baseline, save 650->1250 proposal and one torque-cell change, inspect exact
|
||||
version-pair diff, reject invalid edit/stale source, toggle units with a draft
|
||||
open, verify original configuration/live diagnostic values were not applied,
|
||||
then navigate/reopen existing routes. No real device or programming operation.
|
||||
Distinguish native observations from controlled stale/concurrent/limit proof.
|
||||
Clean only exact task-owned test artifacts; do not reset user data/preferences.
|
||||
|
||||
## DOCUMENTATION REQUIREMENTS
|
||||
|
||||
Update README/index/architecture/build guide and calibration authoring guide:
|
||||
synthetic applicability/ranges/template limits, exact version/head/diff semantics,
|
||||
in-memory lifetime, display versus canonical values, and no backup/test/approval/
|
||||
apply/real-vehicle claims. Step-08 is accepted; Step-09 worker status stays
|
||||
pending orchestrator review. Step-10 simulated programming is separate and
|
||||
unimplemented; physical writes retain their later authorization gates.
|
||||
|
||||
## ACCEPTANCE CRITERIA
|
||||
|
||||
| ID | Criterion | Evidence |
|
||||
|---|---|---|
|
||||
| AC-01 | C-01/C-04/C-08 explicit supported definition/source applicability and atomic rejection | Real configuration/profile/model references and independent negative vectors |
|
||||
| AC-02 | C-02/C-03/C-05..C-07/C-11 immutable linear proposals, exact diffs/no-op/stale-head/limits | Exact independent scalar/table/parent results, defensive copies and controlled commits |
|
||||
| AC-03 | C-09/C-10 real editor/history/diff uses canonical units and truthful authoring-only status | Actual rendered actions, parse/validation failures, source confirmation and pinned-draft/unit tests |
|
||||
| AC-04 | C-12 no authoring side effects; 350 regressions/new coverage, full Release/native build and required smoke pass | Counted real coexistence, unchanged source/config/archive/replay and exact worker commands/results |
|
||||
| AC-05 | Matrix/self-review/docs/README describe actual output/state/limits, with history/protection/manual workflow preserved | Own post-green source-path review, named executed evidence and `prompts/Step-09-Report.md` |
|
||||
|
||||
## OUT-OF-SCOPE WORK
|
||||
|
||||
Programming/readback/restore/verified backup, Tested/Approved status/workflow,
|
||||
model application, calibration file persistence/import/export, multidimensional/
|
||||
editable-axis maps, arbitrary scaling/firmware memory, AI/hardware, new project/
|
||||
package/host and unrelated cleanup. No future assignment, agents, automatic
|
||||
handoff, orchestration/shared-gate edit, stage, commit or push.
|
||||
|
||||
## REPORTING REQUIREMENTS
|
||||
|
||||
Save `prompts/Step-09-Report.md` wholly inside exactly one plain triple-backtick
|
||||
fence, no language tag/outside text/nested fences. Include identifier/title/status,
|
||||
functions/files/interfaces, C-01..C-12/AC-01..AC-05 matrix with named executed
|
||||
evidence, exact baseline/proposal/diff/negative/head/limit results and zero-write
|
||||
proof, commands/exits/warnings/per-project counts, native versus controlled
|
||||
coverage, docs/README, own post-green source-path self-review, limitations/
|
||||
deviations/blockers and preservation review.
|
||||
COMPLETE requires all assigned checks; otherwise report INCOMPLETE/BLOCKED with
|
||||
the precise unmet criterion. Save and STOP; do not begin Step-10.
|
||||
|
|
@ -0,0 +1,166 @@
|
|||
using System.Globalization;
|
||||
using System.Text.Json;
|
||||
using AutoForge.Diagnostics;
|
||||
|
||||
namespace AutoForge.Application.Features.Vehicles.Telemetry.LiveDashboard;
|
||||
|
||||
public static class DashboardGaugeProjection
|
||||
{
|
||||
public static void ValidateDefinitions(
|
||||
IReadOnlyList<DashboardGaugeDefinition> definitions,
|
||||
IReadOnlyList<DashboardSignalBinding> available)
|
||||
{
|
||||
if (definitions.Count > 8)
|
||||
{
|
||||
throw new DashboardConfigurationException("A dashboard supports no more than eight gauges.");
|
||||
}
|
||||
|
||||
var identifiers = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var definition in definitions)
|
||||
{
|
||||
if (definition is null)
|
||||
{
|
||||
throw new DashboardConfigurationException("Dashboard gauge definitions cannot contain null.");
|
||||
}
|
||||
if (string.IsNullOrWhiteSpace(definition.GaugeIdentifier) ||
|
||||
!StringComparer.Ordinal.Equals(definition.GaugeIdentifier, definition.GaugeIdentifier.Trim()) ||
|
||||
!identifiers.Add(definition.GaugeIdentifier))
|
||||
{
|
||||
throw new DashboardConfigurationException("Gauge identifiers must be nonblank, trimmed and unique ignoring case.");
|
||||
}
|
||||
if (string.IsNullOrWhiteSpace(definition.Label) ||
|
||||
!StringComparer.Ordinal.Equals(definition.Label, definition.Label.Trim()))
|
||||
{
|
||||
throw new DashboardConfigurationException("Gauge labels must be nonblank and contain no surrounding whitespace.");
|
||||
}
|
||||
if (!Enum.IsDefined(definition.Kind))
|
||||
{
|
||||
throw new DashboardConfigurationException("The selected gauge kind is undefined.");
|
||||
}
|
||||
if (string.IsNullOrWhiteSpace(definition.ModuleIdentifier) ||
|
||||
string.IsNullOrWhiteSpace(definition.SignalIdentifier) ||
|
||||
string.IsNullOrWhiteSpace(definition.Unit))
|
||||
{
|
||||
throw new DashboardConfigurationException("Gauge module, signal and unit bindings must be explicit.");
|
||||
}
|
||||
if (!double.IsFinite(definition.Minimum) || !double.IsFinite(definition.Maximum) ||
|
||||
!double.IsFinite(definition.Maximum - definition.Minimum) || definition.Maximum <= definition.Minimum)
|
||||
{
|
||||
throw new DashboardConfigurationException("Gauge range must have finite minimum, maximum and positive finite span.");
|
||||
}
|
||||
if (definition.DecimalPrecision is < 0 or > 3)
|
||||
{
|
||||
throw new DashboardConfigurationException("Gauge decimal precision must be an integer from 0 through 3.");
|
||||
}
|
||||
|
||||
var binding = available.FirstOrDefault(item =>
|
||||
StringComparer.OrdinalIgnoreCase.Equals(item.ModuleIdentifier, definition.ModuleIdentifier) &&
|
||||
StringComparer.Ordinal.Equals(item.SignalIdentifier, definition.SignalIdentifier));
|
||||
if (binding is null)
|
||||
{
|
||||
throw new DashboardConfigurationException(
|
||||
$"Signal '{definition.SignalIdentifier}' on module '{definition.ModuleIdentifier}' has not been observed in a validated positive source snapshot.");
|
||||
}
|
||||
if (!StringComparer.Ordinal.Equals(definition.Unit, binding.Unit))
|
||||
{
|
||||
throw new DashboardConfigurationException(
|
||||
$"Gauge unit '{definition.Unit}' does not exactly match source unit '{binding.Unit}'; display conversion does not change binding.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal static void ValidateBindings(IEnumerable<DiagnosticSignal> signals, IEnumerable<DashboardSignalBinding> known)
|
||||
{
|
||||
foreach (var signal in signals)
|
||||
{
|
||||
var previous = known.FirstOrDefault(binding =>
|
||||
StringComparer.OrdinalIgnoreCase.Equals(binding.ModuleIdentifier, signal.ModuleIdentifier) &&
|
||||
StringComparer.Ordinal.Equals(binding.SignalIdentifier, signal.SignalIdentifier));
|
||||
if (previous is not null &&
|
||||
(!StringComparer.Ordinal.Equals(previous.Unit, signal.Unit) ||
|
||||
!StringComparer.Ordinal.Equals(previous.Origin, signal.Origin)))
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
$"Signal '{signal.SignalIdentifier}' on '{signal.ModuleIdentifier}' changed its verified unit or origin.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal static DashboardGaugeValue Project(
|
||||
DashboardGaugeDefinition definition,
|
||||
DiagnosticSignal? signal,
|
||||
DiagnosticSignal? lastGood,
|
||||
DashboardModuleStatus? module,
|
||||
string? terminalError = null,
|
||||
string? missingReason = null)
|
||||
{
|
||||
if (terminalError is not null)
|
||||
{
|
||||
return LastOrError(definition, lastGood, terminalError);
|
||||
}
|
||||
if (module is { Outcome: not DiagnosticOutcome.PositiveResponse })
|
||||
{
|
||||
return LastOrError(definition, lastGood, module.Error ?? $"Source read outcome: {module.Outcome}.");
|
||||
}
|
||||
if (signal is null)
|
||||
{
|
||||
return LastOrError(definition, lastGood,
|
||||
missingReason ?? "The previously bound signal is missing from the latest source response.", DashboardReadingState.Unavailable);
|
||||
}
|
||||
if (signal.Quality == SignalQuality.Unknown || !TryGetFiniteNumber(signal, out var value))
|
||||
{
|
||||
return new DashboardGaugeValue(definition, DashboardReadingState.Unknown, "--", null, null,
|
||||
signal.Quality == SignalQuality.Unknown
|
||||
? "The source quality is Unknown."
|
||||
: "The source value is null, non-numeric or non-finite.", signal);
|
||||
}
|
||||
if (signal.Quality == SignalQuality.Uncertain)
|
||||
{
|
||||
return CreateValue(definition, DashboardReadingState.Uncertain, value, signal,
|
||||
"The source marked this finite value Uncertain.", GetRangeState(value, definition));
|
||||
}
|
||||
if (signal.Quality != SignalQuality.Good)
|
||||
{
|
||||
return new DashboardGaugeValue(definition, DashboardReadingState.Unknown, "--", null, null,
|
||||
"The source quality is undefined.", signal);
|
||||
}
|
||||
return CreateValue(definition, GetRangeState(value, definition), value, signal, null);
|
||||
}
|
||||
|
||||
internal static DashboardGaugeValue LastOrError(
|
||||
DashboardGaugeDefinition definition, DiagnosticSignal? last, string error,
|
||||
DashboardReadingState missingState = DashboardReadingState.Error)
|
||||
{
|
||||
if (last is not null && TryGetFiniteNumber(last, out var value))
|
||||
{
|
||||
return CreateValue(definition, DashboardReadingState.Stale, value, last,
|
||||
$"{error} Retaining last-known sample from logical tick {last.LogicalTimeTicks}.",
|
||||
GetRangeState(value, definition));
|
||||
}
|
||||
return new DashboardGaugeValue(definition, missingState, "--", null, null, error, null);
|
||||
}
|
||||
|
||||
internal static DashboardGaugeValue CreateValue(
|
||||
DashboardGaugeDefinition definition, DashboardReadingState state, double value,
|
||||
DiagnosticSignal signal, string? reason, DashboardReadingState? rangeState = null)
|
||||
{
|
||||
var outOfRangeState = rangeState ?? (state is DashboardReadingState.OutOfRangeLow or DashboardReadingState.OutOfRangeHigh ? state : null);
|
||||
var displayState = state is DashboardReadingState.OutOfRangeLow or DashboardReadingState.OutOfRangeHigh
|
||||
? DashboardReadingState.Good : state;
|
||||
var barPercent = Math.Clamp((value - definition.Minimum) / (definition.Maximum - definition.Minimum) * 100, 0, 100);
|
||||
return new DashboardGaugeValue(definition, displayState,
|
||||
value.ToString($"F{definition.DecimalPrecision}", CultureInfo.InvariantCulture),
|
||||
value, barPercent, reason, signal, outOfRangeState);
|
||||
}
|
||||
|
||||
internal static DashboardReadingState GetRangeState(double value, DashboardGaugeDefinition definition) =>
|
||||
value < definition.Minimum ? DashboardReadingState.OutOfRangeLow :
|
||||
value > definition.Maximum ? DashboardReadingState.OutOfRangeHigh : DashboardReadingState.Good;
|
||||
|
||||
internal static bool TryGetFiniteNumber(DiagnosticSignal signal, out double value)
|
||||
{
|
||||
value = default;
|
||||
return signal.Value.ValueKind == JsonValueKind.Number &&
|
||||
signal.Value.TryGetDouble(out value) && double.IsFinite(value);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,10 +1,9 @@
|
|||
using System.Globalization;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Text.Json;
|
||||
using AutoForge.Application.Features.Vehicles.Diagnostics;
|
||||
using AutoForge.Diagnostics;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.DependencyInjection.Extensions;
|
||||
using static AutoForge.Application.Features.Vehicles.Telemetry.LiveDashboard.DashboardGaugeProjection;
|
||||
|
||||
namespace AutoForge.Application.Features.Vehicles.Telemetry.LiveDashboard;
|
||||
|
||||
|
|
@ -100,7 +99,7 @@ public sealed class LiveDashboardFeed : IAsyncDisposable
|
|||
lock (_gate)
|
||||
{
|
||||
EnsureNotDisposed();
|
||||
ValidateDefinitions(proposed);
|
||||
DashboardGaugeProjection.ValidateDefinitions(proposed, _knownBindings.Values.ToArray());
|
||||
_definitions = Array.AsReadOnly(proposed.ToArray());
|
||||
_snapshot = CreateSnapshotLocked();
|
||||
}
|
||||
|
|
@ -331,23 +330,15 @@ public sealed class LiveDashboardFeed : IAsyncDisposable
|
|||
signal => signal.SignalIdentifier,
|
||||
signal => signal,
|
||||
StringComparer.Ordinal);
|
||||
ValidateBindings(snapshot.Signals, _knownBindings.Values);
|
||||
var bindings = new List<DashboardSignalBinding>(snapshot.Signals.Count);
|
||||
foreach (var signal in snapshot.Signals)
|
||||
{
|
||||
var key = (moduleIdentifier, signal.SignalIdentifier);
|
||||
var binding = new DashboardSignalBinding(
|
||||
signal.ModuleIdentifier,
|
||||
signal.SignalIdentifier,
|
||||
signal.Unit,
|
||||
signal.Origin);
|
||||
if (_knownBindings.TryGetValue(key, out var previous) &&
|
||||
(!StringComparer.Ordinal.Equals(previous.Unit, binding.Unit) ||
|
||||
!StringComparer.Ordinal.Equals(previous.Origin, binding.Origin)))
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
$"Signal '{signal.SignalIdentifier}' on '{moduleIdentifier}' changed its verified unit or origin.");
|
||||
}
|
||||
|
||||
bindings.Add(binding);
|
||||
}
|
||||
|
||||
|
|
@ -423,77 +414,6 @@ public sealed class LiveDashboardFeed : IAsyncDisposable
|
|||
}
|
||||
}
|
||||
|
||||
private void ValidateDefinitions(IReadOnlyList<DashboardGaugeDefinition> definitions)
|
||||
{
|
||||
if (definitions.Count > 8)
|
||||
{
|
||||
throw new DashboardConfigurationException("A live dashboard supports no more than eight gauges.");
|
||||
}
|
||||
|
||||
var identifiers = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var definition in definitions)
|
||||
{
|
||||
if (definition is null)
|
||||
{
|
||||
throw new DashboardConfigurationException("Dashboard gauge definitions cannot contain null.");
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(definition.GaugeIdentifier) ||
|
||||
!StringComparer.Ordinal.Equals(definition.GaugeIdentifier, definition.GaugeIdentifier.Trim()) ||
|
||||
!identifiers.Add(definition.GaugeIdentifier))
|
||||
{
|
||||
throw new DashboardConfigurationException(
|
||||
"Gauge identifiers must be nonblank, trimmed and unique ignoring case.");
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(definition.Label) ||
|
||||
!StringComparer.Ordinal.Equals(definition.Label, definition.Label.Trim()))
|
||||
{
|
||||
throw new DashboardConfigurationException("Gauge labels must be nonblank and contain no surrounding whitespace.");
|
||||
}
|
||||
|
||||
if (!Enum.IsDefined(definition.Kind))
|
||||
{
|
||||
throw new DashboardConfigurationException("The selected gauge kind is undefined.");
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(definition.ModuleIdentifier) ||
|
||||
string.IsNullOrWhiteSpace(definition.SignalIdentifier) ||
|
||||
string.IsNullOrWhiteSpace(definition.Unit))
|
||||
{
|
||||
throw new DashboardConfigurationException("Gauge module, signal and unit bindings must be explicit.");
|
||||
}
|
||||
|
||||
if (!double.IsFinite(definition.Minimum) ||
|
||||
!double.IsFinite(definition.Maximum) ||
|
||||
!double.IsFinite(definition.Maximum - definition.Minimum) ||
|
||||
definition.Maximum <= definition.Minimum)
|
||||
{
|
||||
throw new DashboardConfigurationException(
|
||||
"Gauge range must have finite minimum, maximum and positive finite span.");
|
||||
}
|
||||
|
||||
if (definition.DecimalPrecision is < 0 or > 3)
|
||||
{
|
||||
throw new DashboardConfigurationException("Gauge decimal precision must be an integer from 0 through 3.");
|
||||
}
|
||||
|
||||
if (!_knownBindings.TryGetValue(
|
||||
(definition.ModuleIdentifier, definition.SignalIdentifier),
|
||||
out var binding))
|
||||
{
|
||||
throw new DashboardConfigurationException(
|
||||
$"Signal '{definition.SignalIdentifier}' on module '{definition.ModuleIdentifier}' has not been read from an identity-verified endpoint in this session.");
|
||||
}
|
||||
|
||||
if (!StringComparer.Ordinal.Equals(definition.Unit, binding.Unit))
|
||||
{
|
||||
throw new DashboardConfigurationException(
|
||||
$"Gauge unit '{definition.Unit}' does not exactly match source unit '{binding.Unit}'; unit conversion is not supported.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private LiveDashboardSnapshot CreateSnapshotLocked()
|
||||
{
|
||||
var available = Array.AsReadOnly(_knownBindings.Values
|
||||
|
|
@ -544,123 +464,16 @@ public sealed class LiveDashboardFeed : IAsyncDisposable
|
|||
|
||||
if (_state == DashboardFeedState.Error)
|
||||
{
|
||||
return LastOrError(definition, _error ?? "Dashboard acquisition stopped after an unexpected source error.");
|
||||
_lastFiniteSignals.TryGetValue((definition.ModuleIdentifier, definition.SignalIdentifier), out var last);
|
||||
return LastOrError(definition, last, _error ?? "Dashboard acquisition stopped after an unexpected source error.");
|
||||
}
|
||||
|
||||
DiagnosticSignal? signal = null;
|
||||
_lastSignals.TryGetValue(definition.ModuleIdentifier, out var moduleSignals);
|
||||
moduleSignals?.TryGetValue(definition.SignalIdentifier, out signal);
|
||||
if (_moduleStatuses.TryGetValue(definition.ModuleIdentifier, out var moduleStatus) &&
|
||||
moduleStatus.Outcome != DiagnosticOutcome.PositiveResponse)
|
||||
{
|
||||
return LastOrError(definition, moduleStatus.Error ?? $"Source read outcome: {moduleStatus.Outcome}.");
|
||||
}
|
||||
|
||||
if (signal is null)
|
||||
{
|
||||
return LastOrError(
|
||||
definition,
|
||||
"The previously bound signal is missing from the latest source response.",
|
||||
DashboardReadingState.Unavailable);
|
||||
}
|
||||
|
||||
if (signal.Quality == SignalQuality.Unknown || !TryGetFiniteNumber(signal, out var value))
|
||||
{
|
||||
return new DashboardGaugeValue(
|
||||
definition,
|
||||
DashboardReadingState.Unknown,
|
||||
"--",
|
||||
null,
|
||||
null,
|
||||
signal.Quality == SignalQuality.Unknown
|
||||
? "The source quality is Unknown."
|
||||
: "The source value is null, non-numeric or non-finite.",
|
||||
signal);
|
||||
}
|
||||
|
||||
if (signal.Quality == SignalQuality.Uncertain)
|
||||
{
|
||||
return CreateValue(
|
||||
definition,
|
||||
DashboardReadingState.Uncertain,
|
||||
value,
|
||||
signal,
|
||||
"The source marked this finite value Uncertain.",
|
||||
GetRangeState(value, definition));
|
||||
}
|
||||
|
||||
if (signal.Quality != SignalQuality.Good)
|
||||
{
|
||||
return new DashboardGaugeValue(
|
||||
definition, DashboardReadingState.Unknown, "--", null, null,
|
||||
"The source quality is undefined.", signal);
|
||||
}
|
||||
|
||||
_lastFiniteSignals[(definition.ModuleIdentifier, definition.SignalIdentifier)] = signal;
|
||||
return CreateValue(definition, GetRangeState(value, definition), value, signal, null);
|
||||
}
|
||||
|
||||
private DashboardGaugeValue LastOrError(
|
||||
DashboardGaugeDefinition definition,
|
||||
string error,
|
||||
DashboardReadingState missingState = DashboardReadingState.Error)
|
||||
{
|
||||
if (_lastFiniteSignals.TryGetValue((definition.ModuleIdentifier, definition.SignalIdentifier), out var last) &&
|
||||
TryGetFiniteNumber(last, out var lastValue))
|
||||
{
|
||||
var rangeState = GetRangeState(lastValue, definition);
|
||||
return CreateValue(
|
||||
definition,
|
||||
DashboardReadingState.Stale,
|
||||
lastValue,
|
||||
last,
|
||||
$"{error} Retaining last-known sample from logical tick {last.LogicalTimeTicks}.",
|
||||
rangeState);
|
||||
}
|
||||
|
||||
return new DashboardGaugeValue(
|
||||
definition, missingState, "--", null, null, error, null);
|
||||
}
|
||||
|
||||
private static DashboardGaugeValue CreateValue(
|
||||
DashboardGaugeDefinition definition,
|
||||
DashboardReadingState state,
|
||||
double value,
|
||||
DiagnosticSignal signal,
|
||||
string? reason,
|
||||
DashboardReadingState? rangeState = null)
|
||||
{
|
||||
var outOfRangeState = rangeState ?? (state is DashboardReadingState.OutOfRangeLow or DashboardReadingState.OutOfRangeHigh
|
||||
? state
|
||||
: null);
|
||||
var displayState = state is DashboardReadingState.OutOfRangeLow or DashboardReadingState.OutOfRangeHigh
|
||||
? DashboardReadingState.Good
|
||||
: state;
|
||||
var barPercent = Math.Clamp((value - definition.Minimum) / (definition.Maximum - definition.Minimum) * 100, 0, 100);
|
||||
return new DashboardGaugeValue(
|
||||
definition,
|
||||
displayState,
|
||||
value.ToString($"F{definition.DecimalPrecision}", CultureInfo.InvariantCulture),
|
||||
value,
|
||||
barPercent,
|
||||
reason,
|
||||
signal,
|
||||
outOfRangeState);
|
||||
}
|
||||
|
||||
private static DashboardReadingState GetRangeState(double value, DashboardGaugeDefinition definition) =>
|
||||
value < definition.Minimum
|
||||
? DashboardReadingState.OutOfRangeLow
|
||||
: value > definition.Maximum
|
||||
? DashboardReadingState.OutOfRangeHigh
|
||||
: DashboardReadingState.Good;
|
||||
|
||||
private static bool TryGetFiniteNumber(DiagnosticSignal signal, out double value)
|
||||
{
|
||||
value = default;
|
||||
return signal.Value.ValueKind == JsonValueKind.Number &&
|
||||
signal.Value.TryGetDouble(out value) &&
|
||||
double.IsFinite(value);
|
||||
_moduleStatuses.TryGetValue(definition.ModuleIdentifier, out var moduleStatus);
|
||||
_lastFiniteSignals.TryGetValue((definition.ModuleIdentifier, definition.SignalIdentifier), out var lastGood);
|
||||
return Project(definition, signal, lastGood, moduleStatus);
|
||||
}
|
||||
|
||||
private void EnsureNotDisposed()
|
||||
|
|
|
|||
|
|
@ -0,0 +1,116 @@
|
|||
using AutoForge.Application.Features.Vehicles.Telemetry.LiveDashboard;
|
||||
using AutoForge.Application.Features.Vehicles.Telemetry.Recording;
|
||||
using AutoForge.Diagnostics;
|
||||
|
||||
namespace AutoForge.Application.Features.Vehicles.Telemetry.Replay;
|
||||
|
||||
internal sealed class ReplayPrefixProjection
|
||||
{
|
||||
private readonly Dictionary<string, Dictionary<string, DiagnosticSignal>> _signals = new(StringComparer.OrdinalIgnoreCase);
|
||||
private readonly Dictionary<string, DashboardModuleStatus> _modules = new(StringComparer.OrdinalIgnoreCase);
|
||||
private readonly Dictionary<DiagnosticSignal, ReplaySampleContext> _contexts = new(ReferenceEqualityComparer.Instance);
|
||||
private readonly Dictionary<string, Dictionary<string, DiagnosticSignal>> _lastGood = new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
public static IReadOnlyList<DashboardSignalBinding> Index(TelemetryCaptureSnapshot archive)
|
||||
{
|
||||
var known = new List<DashboardSignalBinding>();
|
||||
foreach (var observation in archive.Observations)
|
||||
{
|
||||
if (observation is not { Service: DiagnosticServices.ReadSignals,
|
||||
Outcome: DiagnosticOutcome.PositiveResponse, SignalSnapshot: { } snapshot })
|
||||
{
|
||||
continue;
|
||||
}
|
||||
var signals = snapshot.Signals.Select(ToSignal).ToArray();
|
||||
try
|
||||
{
|
||||
DashboardGaugeProjection.ValidateBindings(signals, known);
|
||||
}
|
||||
catch (InvalidOperationException)
|
||||
{
|
||||
// A later unit/origin change is a module error, not new binding authority.
|
||||
continue;
|
||||
}
|
||||
foreach (var signal in signals)
|
||||
{
|
||||
if (!known.Any(binding =>
|
||||
StringComparer.OrdinalIgnoreCase.Equals(binding.ModuleIdentifier, signal.ModuleIdentifier) &&
|
||||
StringComparer.Ordinal.Equals(binding.SignalIdentifier, signal.SignalIdentifier)))
|
||||
{
|
||||
known.Add(new(signal.ModuleIdentifier, signal.SignalIdentifier, signal.Unit, signal.Origin));
|
||||
}
|
||||
}
|
||||
}
|
||||
return Array.AsReadOnly(known.OrderBy(binding => binding.ModuleIdentifier, StringComparer.OrdinalIgnoreCase)
|
||||
.ThenBy(binding => binding.SignalIdentifier, StringComparer.Ordinal).ToArray());
|
||||
}
|
||||
|
||||
public static ReplayPrefixProjection Rebuild(
|
||||
TelemetryCaptureSnapshot archive, int count, IReadOnlyList<DashboardSignalBinding> bindings)
|
||||
{
|
||||
var projection = new ReplayPrefixProjection();
|
||||
foreach (var observation in archive.Observations.Take(count))
|
||||
{
|
||||
if (observation.Service != DiagnosticServices.ReadSignals)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
var module = observation.ModuleIdentifier;
|
||||
if (observation is not { Outcome: DiagnosticOutcome.PositiveResponse, SignalSnapshot: { } snapshot })
|
||||
{
|
||||
projection._modules[module] = new(module, observation.Outcome, observation.Error);
|
||||
continue;
|
||||
}
|
||||
var signals = snapshot.Signals.Select(ToSignal).ToArray();
|
||||
try
|
||||
{
|
||||
DashboardGaugeProjection.ValidateBindings(signals, bindings);
|
||||
}
|
||||
catch (InvalidOperationException exception)
|
||||
{
|
||||
projection._modules[module] = new(module, DiagnosticOutcome.ProtocolError, exception.Message);
|
||||
continue;
|
||||
}
|
||||
projection._signals[module] = signals.ToDictionary(signal => signal.SignalIdentifier, StringComparer.Ordinal);
|
||||
projection._modules[module] = new(module, observation.Outcome, null);
|
||||
if (!projection._lastGood.TryGetValue(module, out var good))
|
||||
{
|
||||
good = new(StringComparer.Ordinal);
|
||||
projection._lastGood.Add(module, good);
|
||||
}
|
||||
foreach (var signal in signals)
|
||||
{
|
||||
projection._contexts.Add(signal, new(observation.Sequence, observation.CaptureElapsedTicks));
|
||||
if (signal.Quality == SignalQuality.Good && DashboardGaugeProjection.TryGetFiniteNumber(signal, out _))
|
||||
{
|
||||
good[signal.SignalIdentifier] = signal;
|
||||
}
|
||||
}
|
||||
}
|
||||
return projection;
|
||||
}
|
||||
|
||||
public IReadOnlyList<DashboardModuleStatus> Modules =>
|
||||
Array.AsReadOnly(_modules.Values.OrderBy(module => module.ModuleIdentifier, StringComparer.OrdinalIgnoreCase).ToArray());
|
||||
|
||||
public DashboardGaugeValue Project(DashboardGaugeDefinition definition)
|
||||
{
|
||||
_signals.TryGetValue(definition.ModuleIdentifier, out var signals);
|
||||
_lastGood.TryGetValue(definition.ModuleIdentifier, out var good);
|
||||
_modules.TryGetValue(definition.ModuleIdentifier, out var module);
|
||||
DiagnosticSignal? current = null;
|
||||
DiagnosticSignal? last = null;
|
||||
signals?.TryGetValue(definition.SignalIdentifier, out current);
|
||||
good?.TryGetValue(definition.SignalIdentifier, out last);
|
||||
return DashboardGaugeProjection.Project(definition, current, last, module,
|
||||
missingReason: module is null ? "No recorded sample in the applied observation prefix." : null);
|
||||
}
|
||||
|
||||
public ReplaySampleContext? Context(DashboardGaugeValue value) =>
|
||||
value.Signal is { } signal && _contexts.TryGetValue(signal, out var context) ? context : null;
|
||||
|
||||
private static DiagnosticSignal ToSignal(TelemetryRecordedSignal signal) =>
|
||||
new(signal.SignalIdentifier, signal.ModuleIdentifier, signal.Value, signal.Unit, signal.Quality,
|
||||
signal.LogicalTimeTicks, signal.Origin, signal.ModelStepIndex, signal.ModelTimeSeconds,
|
||||
signal.ModelConfigurationIdentifier, signal.ModelRunIdentifier);
|
||||
}
|
||||
|
|
@ -0,0 +1,69 @@
|
|||
using AutoForge.Application.Features.Vehicles.Telemetry.LiveDashboard;
|
||||
using AutoForge.Application.Features.Vehicles.Telemetry.Recording;
|
||||
using AutoForge.Core.ExecutionTargets;
|
||||
|
||||
namespace AutoForge.Application.Features.Vehicles.Telemetry.Replay;
|
||||
|
||||
public enum ReplayState
|
||||
{
|
||||
Unloaded,
|
||||
Stopped,
|
||||
Playing,
|
||||
Paused,
|
||||
Completed,
|
||||
Faulted,
|
||||
Closed
|
||||
}
|
||||
|
||||
public enum ReplayFailure
|
||||
{
|
||||
NotLoaded,
|
||||
Closed,
|
||||
Busy,
|
||||
InvalidRate,
|
||||
InvalidPosition,
|
||||
InvalidCommand,
|
||||
NoRecords,
|
||||
AcknowledgementRequired,
|
||||
Faulted
|
||||
}
|
||||
|
||||
public sealed class TelemetryReplayException(ReplayFailure failure, string message) : Exception(message)
|
||||
{
|
||||
public ReplayFailure Failure { get; } = failure;
|
||||
}
|
||||
|
||||
public sealed record TelemetryReplayContext(string InstanceIdentifier, string CaptureId)
|
||||
{
|
||||
public ExecutionTargetKind Kind => ExecutionTargetKind.RecordedReplay;
|
||||
}
|
||||
|
||||
public sealed record ReplaySampleContext(long Sequence, long CaptureElapsedTicks);
|
||||
|
||||
public sealed record TelemetryReplaySnapshot(
|
||||
TelemetryReplayContext? Context,
|
||||
TelemetryCaptureSnapshot? Archive,
|
||||
ReplayState State,
|
||||
bool IsLoading,
|
||||
bool IsDraining,
|
||||
long PositionTicks,
|
||||
long DurationTicks,
|
||||
int AppliedCount,
|
||||
double Rate,
|
||||
bool PartialAcknowledged,
|
||||
IReadOnlyList<TelemetrySavedCapture> SavedCaptures,
|
||||
IReadOnlyList<DashboardSignalBinding> AvailableSignals,
|
||||
IReadOnlyList<DashboardGaugeDefinition> Definitions,
|
||||
IReadOnlyList<DashboardGaugeValue> Values,
|
||||
IReadOnlyList<DashboardModuleStatus> Modules,
|
||||
IReadOnlyDictionary<string, ReplaySampleContext> SampleContexts,
|
||||
string? Error,
|
||||
string? FaultReason = null)
|
||||
{
|
||||
public TelemetryRecordedObservation? CurrentObservation =>
|
||||
AppliedCount == 0 ? null : Archive!.Observations[AppliedCount - 1];
|
||||
|
||||
public bool RequiresAcknowledgement =>
|
||||
Archive?.Completion?.State is TelemetryCaptureState.Incomplete or TelemetryCaptureState.Error &&
|
||||
!PartialAcknowledged;
|
||||
}
|
||||
|
|
@ -0,0 +1,677 @@
|
|||
using System.Collections.ObjectModel;
|
||||
using AutoForge.Application.Features.Vehicles.Telemetry.LiveDashboard;
|
||||
using AutoForge.Application.Features.Vehicles.Telemetry.Recording;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.DependencyInjection.Extensions;
|
||||
|
||||
namespace AutoForge.Application.Features.Vehicles.Telemetry.Replay;
|
||||
|
||||
public interface IReplayWaiter
|
||||
{
|
||||
Task WaitAsync(TimeSpan interval, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
public sealed class SystemReplayWaiter(TimeProvider timeProvider) : IReplayWaiter
|
||||
{
|
||||
public Task WaitAsync(TimeSpan interval, CancellationToken cancellationToken) =>
|
||||
Task.Delay(interval, timeProvider, cancellationToken);
|
||||
}
|
||||
|
||||
public interface ITelemetryReplayFactory
|
||||
{
|
||||
TelemetryReplaySession Create();
|
||||
}
|
||||
|
||||
public sealed class TelemetryReplayFactory(
|
||||
ITelemetryArchiveStore store, TimeProvider timeProvider, IReplayWaiter waiter) : ITelemetryReplayFactory
|
||||
{
|
||||
public TelemetryReplaySession Create() => new(store, timeProvider, waiter);
|
||||
}
|
||||
|
||||
public static class TelemetryReplayServiceCollectionExtensions
|
||||
{
|
||||
public static IServiceCollection AddAutoForgeTelemetryReplay(this IServiceCollection services)
|
||||
{
|
||||
services.TryAddSingleton<TimeProvider>(TimeProvider.System);
|
||||
services.TryAddSingleton<IReplayWaiter, SystemReplayWaiter>();
|
||||
services.TryAddSingleton<ITelemetryReplayFactory, TelemetryReplayFactory>();
|
||||
return services;
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class TelemetryReplaySession : IAsyncDisposable
|
||||
{
|
||||
public static readonly TimeSpan MaximumWait = TimeSpan.FromSeconds(30);
|
||||
private readonly object _gate = new();
|
||||
private readonly ITelemetryArchiveStore _store;
|
||||
private readonly TimeProvider _clock;
|
||||
private readonly IReplayWaiter _waiter;
|
||||
private TelemetryReplaySnapshot _snapshot;
|
||||
private ReplayPrefixProjection _projection = new();
|
||||
private PlaybackOwner? _owner;
|
||||
private ArchiveOperation? _archiveOperation;
|
||||
private Task? _closeTask;
|
||||
private long _generation;
|
||||
private long _basePosition;
|
||||
private long _baseTimestamp;
|
||||
|
||||
public TelemetryReplaySession(ITelemetryArchiveStore store, TimeProvider clock, IReplayWaiter waiter)
|
||||
{
|
||||
_store = store ?? throw new ArgumentNullException(nameof(store));
|
||||
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
|
||||
_waiter = waiter ?? throw new ArgumentNullException(nameof(waiter));
|
||||
_snapshot = new(null, null, ReplayState.Unloaded, false, false, 0, 0, 0, 1, false,
|
||||
[], [], [], [], [], new ReadOnlyDictionary<string, ReplaySampleContext>(new Dictionary<string, ReplaySampleContext>()), null);
|
||||
}
|
||||
|
||||
public event Action? Changed;
|
||||
|
||||
public TelemetryReplaySnapshot Snapshot
|
||||
{
|
||||
get { lock (_gate) return _snapshot; }
|
||||
}
|
||||
|
||||
public Task RefreshSavedCapturesAsync(CancellationToken cancellationToken = default) =>
|
||||
BeginArchiveOperationAsync(null, cancellationToken);
|
||||
|
||||
public Task LoadAsync(string captureId, CancellationToken cancellationToken = default) =>
|
||||
BeginArchiveOperationAsync(captureId ?? string.Empty, cancellationToken);
|
||||
|
||||
private Task BeginArchiveOperationAsync(string? captureId, CancellationToken token)
|
||||
{
|
||||
ArchiveOperation operation;
|
||||
lock (_gate)
|
||||
{
|
||||
EnsureQuiescentLocked(requireLoaded: false);
|
||||
if (captureId is not null &&
|
||||
(captureId.Length != 32 || !Guid.TryParseExact(captureId, "N", out var id) || id.ToString("N") != captureId))
|
||||
{
|
||||
throw RejectLocked(ReplayFailure.InvalidCommand, "Choose an explicit valid saved capture ID; no replay was replaced.");
|
||||
}
|
||||
token.ThrowIfCancellationRequested();
|
||||
operation = new(++_generation, CancellationTokenSource.CreateLinkedTokenSource(token));
|
||||
_archiveOperation = operation;
|
||||
_snapshot = _snapshot with { IsLoading = true, Error = null };
|
||||
}
|
||||
Changed?.Invoke();
|
||||
return RunArchiveOperationAsync(operation, captureId);
|
||||
}
|
||||
|
||||
private async Task RunArchiveOperationAsync(ArchiveOperation operation, string? captureId)
|
||||
{
|
||||
try
|
||||
{
|
||||
var token = operation.Token;
|
||||
if (captureId is null)
|
||||
{
|
||||
var saved = await _store.ListAsync(token).ConfigureAwait(false);
|
||||
lock (_gate)
|
||||
{
|
||||
EnsureCurrentLoadLocked(operation);
|
||||
_snapshot = _snapshot with { SavedCaptures = Array.AsReadOnly(saved.ToArray()), Error = null };
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
var loaded = await _store.LoadAsync(captureId, token).ConfigureAwait(false);
|
||||
token.ThrowIfCancellationRequested();
|
||||
var archive = TelemetryArchiveCodec.Deserialize(TelemetryArchiveCodec.Serialize(loaded));
|
||||
if (!StringComparer.Ordinal.Equals(archive.Header.CaptureId, captureId))
|
||||
{
|
||||
throw new TelemetryArchiveException(TelemetryArchiveFailure.InvalidArchive,
|
||||
"The loaded archive does not match the explicitly requested capture ID.");
|
||||
}
|
||||
var bindings = ReplayPrefixProjection.Index(archive);
|
||||
lock (_gate)
|
||||
{
|
||||
EnsureCurrentLoadLocked(operation);
|
||||
_projection = new();
|
||||
_snapshot = _snapshot with
|
||||
{
|
||||
Context = new(Guid.NewGuid().ToString("N"), captureId),
|
||||
Archive = archive,
|
||||
State = ReplayState.Stopped,
|
||||
PositionTicks = 0,
|
||||
DurationTicks = archive.Observations.LastOrDefault()?.CaptureElapsedTicks ?? 0,
|
||||
AppliedCount = 0,
|
||||
PartialAcknowledged = false,
|
||||
AvailableSignals = bindings,
|
||||
Definitions = [],
|
||||
Values = [],
|
||||
Modules = [],
|
||||
SampleContexts = EmptyContexts(),
|
||||
FaultReason = null,
|
||||
Error = null
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (IsCurrentLoadLocked(operation))
|
||||
{
|
||||
_snapshot = _snapshot with { Error = $"Archive operation failed: {exception.Message}" };
|
||||
}
|
||||
}
|
||||
throw;
|
||||
}
|
||||
finally
|
||||
{
|
||||
var notify = false;
|
||||
operation.Release();
|
||||
lock (_gate)
|
||||
{
|
||||
if (ReferenceEquals(_archiveOperation, operation))
|
||||
{
|
||||
_archiveOperation = null;
|
||||
_snapshot = _snapshot with { IsLoading = false };
|
||||
notify = _snapshot.State != ReplayState.Closed;
|
||||
}
|
||||
operation.Done.TrySetResult();
|
||||
}
|
||||
if (notify) Changed?.Invoke();
|
||||
}
|
||||
}
|
||||
|
||||
public void ReplaceDefinitions(IEnumerable<DashboardGaugeDefinition> definitions)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
EnsureOpenLocked();
|
||||
if (_snapshot.IsLoading || _snapshot.IsDraining ||
|
||||
(_owner is not null && _snapshot.State != ReplayState.Playing))
|
||||
{
|
||||
throw RejectLocked(ReplayFailure.Busy, "Wait for the pending archive/playback cleanup before editing recorded gauges.");
|
||||
}
|
||||
EnsureLoadedLocked();
|
||||
if (definitions is null)
|
||||
{
|
||||
throw RejectLocked(ReplayFailure.InvalidCommand, "Gauge definitions must be explicit.");
|
||||
}
|
||||
var proposed = definitions.ToArray();
|
||||
try
|
||||
{
|
||||
DashboardGaugeProjection.ValidateDefinitions(proposed, _snapshot.AvailableSignals);
|
||||
}
|
||||
catch (DashboardConfigurationException exception)
|
||||
{
|
||||
_snapshot = _snapshot with { Error = exception.Message };
|
||||
throw;
|
||||
}
|
||||
_snapshot = _snapshot with { Definitions = Array.AsReadOnly(proposed), Error = null };
|
||||
ProjectValuesLocked();
|
||||
}
|
||||
Changed?.Invoke();
|
||||
}
|
||||
|
||||
public void AcknowledgePartial()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
EnsureQuiescentLocked();
|
||||
_snapshot = _snapshot with { PartialAcknowledged = true, Error = null };
|
||||
}
|
||||
Changed?.Invoke();
|
||||
}
|
||||
|
||||
public void SetRate(double rate)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
EnsureQuiescentLocked();
|
||||
if (!double.IsFinite(rate) || rate is < 0.25 or > 1000)
|
||||
{
|
||||
throw RejectLocked(ReplayFailure.InvalidRate, "Replay speed must be finite and between 0.25x and 1000x; the previous speed is unchanged.");
|
||||
}
|
||||
_snapshot = _snapshot with { Rate = rate, Error = null };
|
||||
}
|
||||
Changed?.Invoke();
|
||||
}
|
||||
|
||||
public void SeekTime(long ticks)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
EnsureNavigationLocked();
|
||||
if (ticks < 0 || ticks > _snapshot.DurationTicks)
|
||||
{
|
||||
throw RejectLocked(ReplayFailure.InvalidPosition, "Replay time must be within the recorded duration; the cursor is unchanged.");
|
||||
}
|
||||
ApplyPrefixLocked(CountDueLocked(ticks), ticks);
|
||||
SetNavigationStateLocked();
|
||||
}
|
||||
Changed?.Invoke();
|
||||
}
|
||||
|
||||
public void SeekOrdinal(int appliedCount)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
EnsureNavigationLocked();
|
||||
SeekOrdinalLocked(appliedCount);
|
||||
}
|
||||
Changed?.Invoke();
|
||||
}
|
||||
|
||||
public void Next() => MoveOrdinal(1);
|
||||
public void Previous() => MoveOrdinal(-1);
|
||||
|
||||
private void MoveOrdinal(int delta)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
EnsureNavigationLocked();
|
||||
if (_snapshot.Archive!.Observations.Count == 0)
|
||||
{
|
||||
throw RejectLocked(ReplayFailure.NoRecords, "This recorded archive has no observations to navigate.");
|
||||
}
|
||||
SeekOrdinalLocked(_snapshot.AppliedCount + delta);
|
||||
}
|
||||
Changed?.Invoke();
|
||||
}
|
||||
|
||||
public void First()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
EnsureQuiescentLocked();
|
||||
ResetLocked();
|
||||
}
|
||||
Changed?.Invoke();
|
||||
}
|
||||
|
||||
public Task RestartAsync()
|
||||
{
|
||||
PlaybackOwner owner;
|
||||
lock (_gate)
|
||||
{
|
||||
EnsureNavigationLocked();
|
||||
var timestamp = ReadStartTimestampLocked();
|
||||
ResetLocked();
|
||||
owner = StartLocked(timestamp);
|
||||
}
|
||||
Changed?.Invoke();
|
||||
_ = RunOwnerAsync(owner);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task PlayAsync()
|
||||
{
|
||||
PlaybackOwner owner;
|
||||
lock (_gate)
|
||||
{
|
||||
EnsureOpenLocked();
|
||||
if (_snapshot.State == ReplayState.Playing && _owner is not null && !_snapshot.IsDraining)
|
||||
{
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
EnsureNavigationLocked();
|
||||
if (_snapshot.State == ReplayState.Completed)
|
||||
{
|
||||
throw RejectLocked(ReplayFailure.InvalidCommand, "End of retained data. Use Restart or navigate before playing again.");
|
||||
}
|
||||
owner = StartLocked(ReadStartTimestampLocked());
|
||||
}
|
||||
Changed?.Invoke();
|
||||
_ = RunOwnerAsync(owner);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private long ReadStartTimestampLocked()
|
||||
{
|
||||
try
|
||||
{
|
||||
return _clock.GetTimestamp();
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
var reason = $"Replay clock failed: {exception.Message}";
|
||||
SetFaultLocked(reason);
|
||||
throw new TelemetryReplayException(ReplayFailure.Faulted, reason);
|
||||
}
|
||||
}
|
||||
|
||||
private PlaybackOwner StartLocked(long timestamp)
|
||||
{
|
||||
var owner = new PlaybackOwner(++_generation);
|
||||
_owner = owner;
|
||||
_basePosition = _snapshot.PositionTicks;
|
||||
_baseTimestamp = timestamp;
|
||||
_snapshot = _snapshot with { State = ReplayState.Playing, Error = null };
|
||||
return owner;
|
||||
}
|
||||
|
||||
public Task PauseAsync()
|
||||
{
|
||||
PlaybackOwner? owner;
|
||||
lock (_gate)
|
||||
{
|
||||
EnsureOpenLocked();
|
||||
if (_owner is { } draining && _snapshot.IsDraining)
|
||||
{
|
||||
return draining.Done.Task;
|
||||
}
|
||||
EnsureLoadedLocked();
|
||||
if (_snapshot.IsLoading)
|
||||
{
|
||||
throw RejectLocked(ReplayFailure.Busy, "Wait for the archive operation to drain before changing playback.");
|
||||
}
|
||||
if (_snapshot.State != ReplayState.Playing || _owner is null)
|
||||
{
|
||||
throw RejectLocked(ReplayFailure.InvalidCommand, "Pause requires an active recorded playback.");
|
||||
}
|
||||
owner = _owner;
|
||||
try
|
||||
{
|
||||
var position = CurrentPositionLocked();
|
||||
ApplyPrefixLocked(CountDueLocked(position), position);
|
||||
SetNavigationStateLocked();
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
SetFaultLocked($"Replay clock failed: {exception.Message}");
|
||||
}
|
||||
_snapshot = _snapshot with { IsDraining = true };
|
||||
}
|
||||
Changed?.Invoke();
|
||||
owner.Cancel();
|
||||
return owner.Done.Task;
|
||||
}
|
||||
|
||||
public Task StopAsync()
|
||||
{
|
||||
PlaybackOwner? owner;
|
||||
lock (_gate)
|
||||
{
|
||||
EnsureOpenLocked();
|
||||
EnsureLoadedLocked();
|
||||
if (_snapshot.IsLoading)
|
||||
{
|
||||
throw RejectLocked(ReplayFailure.Busy, "Wait for the archive operation to drain before stopping playback.");
|
||||
}
|
||||
owner = _owner;
|
||||
if (owner is null)
|
||||
{
|
||||
ResetLocked();
|
||||
}
|
||||
else
|
||||
{
|
||||
owner.ResetAfterDrain = true;
|
||||
_snapshot = _snapshot with { IsDraining = true };
|
||||
}
|
||||
}
|
||||
Changed?.Invoke();
|
||||
if (owner is null) return Task.CompletedTask;
|
||||
owner.Cancel();
|
||||
return owner.Done.Task;
|
||||
}
|
||||
|
||||
private async Task RunOwnerAsync(PlaybackOwner owner)
|
||||
{
|
||||
try
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
TimeSpan wait;
|
||||
bool complete;
|
||||
lock (_gate)
|
||||
{
|
||||
if (!IsCurrentOwnerLocked(owner)) return;
|
||||
var position = CurrentPositionLocked();
|
||||
ApplyPrefixLocked(CountDueLocked(position), position);
|
||||
complete = _snapshot.AppliedCount == _snapshot.Archive!.Observations.Count;
|
||||
if (complete)
|
||||
{
|
||||
_snapshot = _snapshot with { State = ReplayState.Completed, IsDraining = true };
|
||||
wait = TimeSpan.Zero;
|
||||
}
|
||||
else
|
||||
{
|
||||
var next = _snapshot.Archive.Observations[_snapshot.AppliedCount].CaptureElapsedTicks;
|
||||
var wallTicks = decimal.Ceiling((next - position) / (decimal)_snapshot.Rate);
|
||||
wait = TimeSpan.FromTicks((long)Math.Min(MaximumWait.Ticks, Math.Max(1, wallTicks)));
|
||||
}
|
||||
}
|
||||
Changed?.Invoke();
|
||||
if (complete) return;
|
||||
await _waiter.WaitAsync(wait, owner.Token).ConfigureAwait(false);
|
||||
owner.Token.ThrowIfCancellationRequested();
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) when (owner.Token.IsCancellationRequested)
|
||||
{
|
||||
// Pause/Stop/Close already committed their cutover before cancellation.
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (ReferenceEquals(_owner, owner) && owner.Generation == _generation &&
|
||||
_snapshot.State != ReplayState.Closed)
|
||||
{
|
||||
SetFaultLocked($"Recorded playback failed: {exception.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
var notify = false;
|
||||
owner.Release();
|
||||
lock (_gate)
|
||||
{
|
||||
if (ReferenceEquals(_owner, owner))
|
||||
{
|
||||
_owner = null;
|
||||
if (_snapshot.State != ReplayState.Closed)
|
||||
{
|
||||
if (owner.ResetAfterDrain && _snapshot.State != ReplayState.Faulted) ResetLocked();
|
||||
_snapshot = _snapshot with { IsDraining = false };
|
||||
notify = true;
|
||||
}
|
||||
}
|
||||
owner.Done.TrySetResult();
|
||||
}
|
||||
if (notify) Changed?.Invoke();
|
||||
}
|
||||
}
|
||||
|
||||
public ValueTask DisposeAsync()
|
||||
{
|
||||
TaskCompletionSource completion;
|
||||
PlaybackOwner? owner;
|
||||
ArchiveOperation? operation;
|
||||
lock (_gate)
|
||||
{
|
||||
if (_closeTask is not null) return new(_closeTask);
|
||||
completion = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
_closeTask = completion.Task;
|
||||
++_generation;
|
||||
owner = _owner;
|
||||
operation = _archiveOperation;
|
||||
_snapshot = _snapshot with { State = ReplayState.Closed, IsDraining = owner is not null || operation is not null };
|
||||
}
|
||||
_ = CloseCoreAsync(owner, operation, completion);
|
||||
return new(_closeTask);
|
||||
}
|
||||
|
||||
private async Task CloseCoreAsync(PlaybackOwner? owner, ArchiveOperation? operation, TaskCompletionSource completion)
|
||||
{
|
||||
try
|
||||
{
|
||||
owner?.Cancel();
|
||||
operation?.Cancel();
|
||||
if (owner is not null) await owner.Done.Task.ConfigureAwait(false);
|
||||
if (operation is not null) await operation.Done.Task.ConfigureAwait(false);
|
||||
lock (_gate)
|
||||
{
|
||||
_snapshot = _snapshot with { IsDraining = false, IsLoading = false };
|
||||
Changed = null;
|
||||
}
|
||||
completion.TrySetResult();
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
lock (_gate) _snapshot = _snapshot with { Error = $"Replay close failed: {exception.Message}" };
|
||||
completion.TrySetException(exception);
|
||||
}
|
||||
}
|
||||
|
||||
private long CurrentPositionLocked()
|
||||
{
|
||||
var elapsed = _clock.GetElapsedTime(_baseTimestamp, _clock.GetTimestamp());
|
||||
if (elapsed < TimeSpan.Zero) throw new InvalidOperationException("The replay clock moved backwards.");
|
||||
var advance = decimal.Truncate(elapsed.Ticks * (decimal)_snapshot.Rate);
|
||||
return advance >= _snapshot.DurationTicks - _basePosition
|
||||
? _snapshot.DurationTicks : _basePosition + (long)advance;
|
||||
}
|
||||
|
||||
private int CountDueLocked(long position)
|
||||
{
|
||||
var observations = _snapshot.Archive!.Observations;
|
||||
var count = 0;
|
||||
while (count < observations.Count && observations[count].CaptureElapsedTicks <= position) count++;
|
||||
return count;
|
||||
}
|
||||
|
||||
private void SeekOrdinalLocked(int count)
|
||||
{
|
||||
var observations = _snapshot.Archive!.Observations;
|
||||
if (count < 0 || count > observations.Count)
|
||||
{
|
||||
throw RejectLocked(ReplayFailure.InvalidPosition, "The applied observation count must be between zero and the retained count.");
|
||||
}
|
||||
ApplyPrefixLocked(count, count == 0 ? 0 : observations[count - 1].CaptureElapsedTicks);
|
||||
SetNavigationStateLocked();
|
||||
}
|
||||
|
||||
private void SetNavigationStateLocked() =>
|
||||
_snapshot = _snapshot with
|
||||
{
|
||||
State = _snapshot.Archive!.Observations.Count == 0 ? ReplayState.Stopped :
|
||||
_snapshot.AppliedCount == _snapshot.Archive.Observations.Count ? ReplayState.Completed : ReplayState.Paused,
|
||||
Error = null
|
||||
};
|
||||
|
||||
private void ResetLocked()
|
||||
{
|
||||
ApplyPrefixLocked(0, 0);
|
||||
_snapshot = _snapshot with { State = ReplayState.Stopped, Error = null, FaultReason = null };
|
||||
}
|
||||
|
||||
private void SetFaultLocked(string reason) =>
|
||||
_snapshot = _snapshot with { State = ReplayState.Faulted, Error = reason, FaultReason = reason };
|
||||
|
||||
private void ApplyPrefixLocked(int count, long position)
|
||||
{
|
||||
var projection = ReplayPrefixProjection.Rebuild(_snapshot.Archive!, count, _snapshot.AvailableSignals);
|
||||
_projection = projection;
|
||||
_snapshot = _snapshot with { AppliedCount = count, PositionTicks = position };
|
||||
ProjectValuesLocked();
|
||||
}
|
||||
|
||||
private void ProjectValuesLocked()
|
||||
{
|
||||
var values = _snapshot.Definitions.Select(_projection.Project).ToArray();
|
||||
var contexts = new Dictionary<string, ReplaySampleContext>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var value in values)
|
||||
{
|
||||
if (_projection.Context(value) is { } context) contexts.Add(value.Definition.GaugeIdentifier, context);
|
||||
}
|
||||
_snapshot = _snapshot with
|
||||
{
|
||||
Values = Array.AsReadOnly(values), Modules = _projection.Modules,
|
||||
SampleContexts = new ReadOnlyDictionary<string, ReplaySampleContext>(contexts)
|
||||
};
|
||||
}
|
||||
|
||||
private static IReadOnlyDictionary<string, ReplaySampleContext> EmptyContexts() =>
|
||||
new ReadOnlyDictionary<string, ReplaySampleContext>(new Dictionary<string, ReplaySampleContext>());
|
||||
|
||||
private void EnsureNavigationLocked()
|
||||
{
|
||||
EnsureQuiescentLocked();
|
||||
if (_snapshot.State == ReplayState.Faulted)
|
||||
{
|
||||
throw RejectLocked(ReplayFailure.Faulted, "Replay faulted. Use Stop or First after cleanup before playback/navigation.");
|
||||
}
|
||||
if (_snapshot.RequiresAcknowledgement)
|
||||
{
|
||||
throw RejectLocked(ReplayFailure.AcknowledgementRequired,
|
||||
"Acknowledge this load's original partial/error capture before Play, Next, Previous or seek.");
|
||||
}
|
||||
}
|
||||
|
||||
private void EnsureQuiescentLocked(bool requireLoaded = true)
|
||||
{
|
||||
EnsureOpenLocked();
|
||||
if (_snapshot.IsLoading || _snapshot.IsDraining || _owner is not null)
|
||||
{
|
||||
throw RejectLocked(ReplayFailure.Busy, "Pause first and wait for the previous replay owner/archive operation to finish cleanup.");
|
||||
}
|
||||
if (requireLoaded) EnsureLoadedLocked();
|
||||
}
|
||||
|
||||
private void EnsureOpenLocked()
|
||||
{
|
||||
if (_snapshot.State == ReplayState.Closed) throw RejectLocked(ReplayFailure.Closed, "This replay instance is closed.");
|
||||
}
|
||||
|
||||
private void EnsureLoadedLocked()
|
||||
{
|
||||
if (_snapshot.Archive is null) throw RejectLocked(ReplayFailure.NotLoaded, "Explicitly load a saved capture before operating replay.");
|
||||
}
|
||||
|
||||
private TelemetryReplayException RejectLocked(ReplayFailure failure, string message)
|
||||
{
|
||||
_snapshot = _snapshot with { Error = message };
|
||||
return new(failure, message);
|
||||
}
|
||||
|
||||
private bool IsCurrentOwnerLocked(PlaybackOwner owner) =>
|
||||
ReferenceEquals(_owner, owner) && owner.Generation == _generation &&
|
||||
_snapshot.State == ReplayState.Playing && !_snapshot.IsDraining && !owner.Token.IsCancellationRequested;
|
||||
|
||||
private bool IsCurrentLoadLocked(ArchiveOperation operation) =>
|
||||
ReferenceEquals(_archiveOperation, operation) && operation.Generation == _generation && _snapshot.State != ReplayState.Closed;
|
||||
|
||||
private void EnsureCurrentLoadLocked(ArchiveOperation operation)
|
||||
{
|
||||
operation.Token.ThrowIfCancellationRequested();
|
||||
if (!IsCurrentLoadLocked(operation)) throw new OperationCanceledException("The archive operation belongs to an old or closed replay generation.");
|
||||
}
|
||||
|
||||
private sealed class PlaybackOwner(long generation) : ReplayOperation(generation, new CancellationTokenSource())
|
||||
{
|
||||
public bool ResetAfterDrain { get; set; }
|
||||
}
|
||||
|
||||
private sealed class ArchiveOperation(long generation, CancellationTokenSource cancellation) : ReplayOperation(generation, cancellation);
|
||||
|
||||
private class ReplayOperation(long generation, CancellationTokenSource cancellation)
|
||||
{
|
||||
private readonly object _cancellationGate = new();
|
||||
private bool _released;
|
||||
public long Generation { get; } = generation;
|
||||
public CancellationToken Token { get; } = cancellation.Token;
|
||||
public TaskCompletionSource Done { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
|
||||
public void Cancel()
|
||||
{
|
||||
lock (_cancellationGate)
|
||||
{
|
||||
if (!_released) cancellation.Cancel();
|
||||
}
|
||||
}
|
||||
|
||||
public void Release()
|
||||
{
|
||||
lock (_cancellationGate)
|
||||
{
|
||||
_released = true;
|
||||
cancellation.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -5,6 +5,7 @@ using AutoForge.UI.Features.Vehicles.Simulation;
|
|||
using AutoForge.Application.Features.Vehicles.Simulation;
|
||||
using AutoForge.Application.Features.Vehicles.Telemetry.LiveDashboard;
|
||||
using AutoForge.Application.Features.Vehicles.Telemetry.Recording;
|
||||
using AutoForge.Application.Features.Vehicles.Telemetry.Replay;
|
||||
using AutoForge.Application.Features.DisplayUnits;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
|
|
@ -20,6 +21,7 @@ public static class ServiceCollectionExtensions
|
|||
services.AddAutoForgeLiveDashboard();
|
||||
services.AddAutoForgeDisplayUnits();
|
||||
services.AddAutoForgeTelemetryRecordingFallback();
|
||||
services.AddAutoForgeTelemetryReplay();
|
||||
services.AddScoped<ExecutionTargetSelectionViewModel>();
|
||||
services.AddScoped<DiagnosticPageViewModel>();
|
||||
services.AddScoped<VehicleProfilePageViewModel>();
|
||||
|
|
|
|||
|
|
@ -15,4 +15,5 @@
|
|||
<p>
|
||||
<a href="/diagnostics">Open synthetic diagnostics</a>
|
||||
<a href="/simulation">Open vehicle simulation</a>
|
||||
<a href="/telemetry-replay">Replay saved telemetry offline (recorded, not live)</a>
|
||||
</p>
|
||||
|
|
|
|||
|
|
@ -2,13 +2,19 @@
|
|||
@inject ILiveDashboardFeedFactory FeedFactory
|
||||
|
||||
<section class="live-dashboard-panel" aria-labelledby="@HeadingId">
|
||||
<h2 id="@HeadingId">Session live dashboard</h2>
|
||||
@if (Session is null)
|
||||
<h2 id="@HeadingId">@(Replay is null ? "Session live dashboard" : "Recorded replay gauges")</h2>
|
||||
@if (Session is null && Replay is null)
|
||||
{
|
||||
<p>Open the host's explicit diagnostic session to configure monitoring.</p>
|
||||
}
|
||||
else if (_feed is { } feed)
|
||||
else if (_feed is not null || Replay is not null)
|
||||
{
|
||||
@if (Replay is { } replay)
|
||||
{
|
||||
<p>Recorded replay only: @replay.Snapshot.State. No current vehicle, live feed or verified vehicle identity.</p>
|
||||
}
|
||||
else if (_feed is { } feed)
|
||||
{
|
||||
<p>
|
||||
Source: @feed.Snapshot.Source.Target.ProviderIdentifier
|
||||
(@feed.Snapshot.Source.Target.Kind);
|
||||
|
|
@ -46,9 +52,13 @@
|
|||
}
|
||||
</ul>
|
||||
}
|
||||
}
|
||||
<div class="live-dashboard-actions">
|
||||
@if (Replay is null)
|
||||
{
|
||||
<button type="button" @onclick="StartAsync" disabled="@IsStartDisabled">Start monitoring</button>
|
||||
<button type="button" @onclick="StopAsync" disabled="@IsStopDisabled">Stop monitoring</button>
|
||||
}
|
||||
<button type="button" @onclick="() => _showEditor = !_showEditor" aria-expanded="@_showEditor">
|
||||
@(_showEditor ? "Hide editor" : "Show editor")
|
||||
</button>
|
||||
|
|
@ -70,7 +80,7 @@
|
|||
<option value="@DashboardGaugeKind.Numeric">Numeric</option>
|
||||
<option value="@DashboardGaugeKind.HorizontalBar">Horizontal bar</option>
|
||||
</select>
|
||||
<label for="@($"{HeadingId}-gauge-module")">Verified module</label>
|
||||
<label for="@($"{HeadingId}-gauge-module")">@(Replay is null ? "Verified module" : "Recorded module")</label>
|
||||
<select id="@($"{HeadingId}-gauge-module")" @bind="_moduleIdentifier" @bind:after="OnModuleChanged">
|
||||
<option value="">Choose an observed module</option>
|
||||
@foreach (var module in AvailableModules)
|
||||
|
|
@ -109,7 +119,7 @@
|
|||
}
|
||||
@if (AvailableBindings.Count == 0)
|
||||
{
|
||||
<p>Start monitoring to acquire identity-verified signal choices from this session.</p>
|
||||
<p>@(Replay is null ? "Start monitoring to acquire identity-verified signal choices from this session." : "This archive has no positive recorded signal bindings.")</p>
|
||||
}
|
||||
else if (_draftSelection is { } draftSelection)
|
||||
{
|
||||
|
|
@ -128,24 +138,36 @@
|
|||
|
||||
@if (_showGauges)
|
||||
{
|
||||
@if (feed.Snapshot.Values.Count == 0)
|
||||
@if (Values.Count == 0)
|
||||
{
|
||||
<p>No gauges configured. Monitoring may remain active with an empty dashboard.</p>
|
||||
<p>@(Replay is null ? "No gauges configured. Monitoring may remain active with an empty dashboard." : "No gauges configured. Recorded playback is owned by the page, not the gauges.")</p>
|
||||
}
|
||||
<div class="live-dashboard-grid">
|
||||
@foreach (var gauge in feed.Snapshot.Values)
|
||||
@foreach (var gauge in Values)
|
||||
{
|
||||
var rangeState = gauge.RangeState;
|
||||
var display = ProjectGauge(gauge);
|
||||
var hasDisplayValue = gauge.NumericValue is not null && display.IsAvailable;
|
||||
<article class="live-dashboard-card" data-gauge="@gauge.Definition.GaugeIdentifier">
|
||||
@if (Replay is { } recorded)
|
||||
{
|
||||
<p>Recorded replay / @recorded.Snapshot.State. Not live.</p>
|
||||
@if (recorded.Snapshot.SampleContexts.TryGetValue(gauge.Definition.GaugeIdentifier, out var context))
|
||||
{
|
||||
<p>Original observation @context.Sequence; capture elapsed ticks @context.CaptureElapsedTicks.</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<p>No recorded sample in the applied prefix.</p>
|
||||
}
|
||||
}
|
||||
<LiveDashboardGauge
|
||||
Label="@gauge.Definition.Label"
|
||||
ValueText="@(hasDisplayValue ? DisplayUnitConverter.Format(display, gauge.Definition.DecimalPrecision) : "--")"
|
||||
Unit="@display.Unit"
|
||||
Kind="@(gauge.Definition.Kind == DashboardGaugeKind.HorizontalBar ? "bar" : "numeric")"
|
||||
State="@gauge.State.ToString()"
|
||||
StateDescription="@DisplayStateDescription(gauge.State, display.Error)"
|
||||
StateDescription="@($"{(Replay is null ? "" : $"Recorded replay / {Replay.Snapshot.State}; not live. ")}{DisplayStateDescription(gauge.State, display.Error)}")"
|
||||
RangeDescription="@(rangeState is null ? null : RangeDescription(rangeState.Value, gauge.Definition, DisplaySelection))"
|
||||
Reason="@JoinReason(gauge.Reason, display.Error ?? display.Notice)"
|
||||
Percent="@(hasDisplayValue ? gauge.BarPercent : null)" />
|
||||
|
|
@ -161,7 +183,7 @@
|
|||
<dt>Module / signal</dt>
|
||||
<dd>@signal.ModuleIdentifier / @signal.SignalIdentifier</dd>
|
||||
<dt>Exact source value / unit</dt>
|
||||
<dd>@signal.Value @signal.Unit</dd>
|
||||
<dd>@DisplayUnitPresentation.FormatSourceValue(signal.Value) @signal.Unit</dd>
|
||||
<dt>Display range</dt>
|
||||
<dd>@DisplayBounds(gauge.Definition, DisplaySelection)</dd>
|
||||
<dt>Origin and diagnostic request time</dt>
|
||||
|
|
@ -175,7 +197,7 @@
|
|||
}
|
||||
</dl>
|
||||
}
|
||||
@if (feed.Snapshot.FeedState == DashboardFeedState.Stopped)
|
||||
@if (Replay is null && _feed?.Snapshot.FeedState == DashboardFeedState.Stopped)
|
||||
{
|
||||
<span>Not live: monitoring stopped.</span>
|
||||
}
|
||||
|
|
@ -197,9 +219,12 @@
|
|||
</style>
|
||||
|
||||
@code {
|
||||
[Parameter, EditorRequired]
|
||||
[Parameter]
|
||||
public DiagnosticSession? Session { get; set; }
|
||||
|
||||
[Parameter]
|
||||
public AutoForge.Application.Features.Vehicles.Telemetry.Replay.TelemetryReplaySession? Replay { get; set; }
|
||||
|
||||
[Parameter]
|
||||
public string HeadingId { get; set; } = "live-dashboard-heading";
|
||||
|
||||
|
|
@ -208,6 +233,8 @@
|
|||
|
||||
private LiveDashboardFeed? _feed;
|
||||
private DiagnosticSession? _boundSession;
|
||||
private AutoForge.Application.Features.Vehicles.Telemetry.Replay.TelemetryReplaySession? _boundReplay;
|
||||
private string? _boundReplayInstance;
|
||||
private bool _disposed;
|
||||
private bool _showEditor = true;
|
||||
private bool _showGauges = true;
|
||||
|
|
@ -236,23 +263,34 @@
|
|||
: null;
|
||||
|
||||
private IReadOnlyList<DashboardSignalBinding> AvailableBindings =>
|
||||
_feed?.Snapshot.AvailableSignals
|
||||
AvailableSignals
|
||||
.Where(item => StringComparer.OrdinalIgnoreCase.Equals(item.ModuleIdentifier, _moduleIdentifier))
|
||||
.ToArray() ?? [];
|
||||
.ToArray();
|
||||
|
||||
private IReadOnlyList<DashboardSignalBinding> AvailableSignals =>
|
||||
Replay?.Snapshot.AvailableSignals ?? _feed?.Snapshot.AvailableSignals ?? [];
|
||||
|
||||
private IReadOnlyList<DashboardGaugeDefinition> Definitions =>
|
||||
Replay?.Snapshot.Definitions ?? _feed?.Snapshot.Definitions ?? [];
|
||||
|
||||
private IReadOnlyList<DashboardGaugeValue> Values =>
|
||||
Replay?.Snapshot.Values ?? _feed?.Snapshot.Values ?? [];
|
||||
|
||||
private IReadOnlyList<string> AvailableModules =>
|
||||
_feed?.Snapshot.AvailableSignals
|
||||
AvailableSignals
|
||||
.Select(item => item.ModuleIdentifier)
|
||||
.Distinct(StringComparer.OrdinalIgnoreCase)
|
||||
.OrderBy(item => item, StringComparer.OrdinalIgnoreCase)
|
||||
.ToArray() ?? [];
|
||||
.ToArray();
|
||||
|
||||
private bool IsStartDisabled => _feed?.Snapshot.FeedState is DashboardFeedState.Starting or DashboardFeedState.Running or DashboardFeedState.Stopping;
|
||||
private bool IsStopDisabled => _feed?.Snapshot.FeedState is not (DashboardFeedState.Starting or DashboardFeedState.Running or DashboardFeedState.Stopping or DashboardFeedState.Error);
|
||||
|
||||
protected override void OnParametersSet()
|
||||
{
|
||||
if (ReferenceEquals(Session, _boundSession))
|
||||
var replayInstance = Replay?.Snapshot.Context?.InstanceIdentifier;
|
||||
if (ReferenceEquals(Session, _boundSession) && ReferenceEquals(Replay, _boundReplay) &&
|
||||
replayInstance == _boundReplayInstance)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
|
@ -261,14 +299,25 @@
|
|||
{
|
||||
_feed.Changed -= OnFeedChanged;
|
||||
}
|
||||
if (_boundReplay is not null)
|
||||
{
|
||||
_boundReplay.Changed -= OnFeedChanged;
|
||||
}
|
||||
|
||||
_boundSession = Session;
|
||||
_feed = Session is { IsClosed: false } session ? FeedFactory.Create(session) : null;
|
||||
_boundReplay = Replay;
|
||||
_boundReplayInstance = replayInstance;
|
||||
_feed = Replay is null && Session is { IsClosed: false } session ? FeedFactory.Create(session) : null;
|
||||
if (_feed is not null)
|
||||
{
|
||||
_feed.Changed += OnFeedChanged;
|
||||
}
|
||||
if (_boundReplay is not null)
|
||||
{
|
||||
_boundReplay.Changed += OnFeedChanged;
|
||||
}
|
||||
|
||||
ResetEditor();
|
||||
_error = null;
|
||||
}
|
||||
|
||||
|
|
@ -325,12 +374,12 @@
|
|||
|
||||
private void OnSignalChanged()
|
||||
{
|
||||
if (_feed is null || _moduleIdentifier is null || _signalIdentifier is null)
|
||||
if ((_feed is null && Replay is null) || _moduleIdentifier is null || _signalIdentifier is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var binding = _feed.Snapshot.AvailableSignals.FirstOrDefault(item =>
|
||||
var binding = AvailableSignals.FirstOrDefault(item =>
|
||||
StringComparer.OrdinalIgnoreCase.Equals(item.ModuleIdentifier, _moduleIdentifier) &&
|
||||
StringComparer.Ordinal.Equals(item.SignalIdentifier, _signalIdentifier));
|
||||
if (binding is not null)
|
||||
|
|
@ -347,7 +396,7 @@
|
|||
|
||||
private void SaveGauge()
|
||||
{
|
||||
if (_feed is null)
|
||||
if (_feed is null && Replay is null)
|
||||
{
|
||||
_error = "No open diagnostic session is available for configuration.";
|
||||
return;
|
||||
|
|
@ -361,7 +410,7 @@
|
|||
return;
|
||||
}
|
||||
|
||||
var proposed = _feed.Snapshot.Definitions.ToList();
|
||||
var proposed = Definitions.ToList();
|
||||
var sourceMinimum = minimum;
|
||||
var sourceMaximum = maximum;
|
||||
if (_editingGaugeId is not null)
|
||||
|
|
@ -422,11 +471,11 @@
|
|||
|
||||
try
|
||||
{
|
||||
_feed.ReplaceDefinitions(proposed);
|
||||
ReplaceDefinitions(proposed);
|
||||
_error = null;
|
||||
ResetEditor();
|
||||
}
|
||||
catch (DashboardConfigurationException exception)
|
||||
catch (Exception exception) when (exception is DashboardConfigurationException or AutoForge.Application.Features.Vehicles.Telemetry.Replay.TelemetryReplayException)
|
||||
{
|
||||
_error = exception.Message;
|
||||
}
|
||||
|
|
@ -470,24 +519,24 @@
|
|||
|
||||
private void RemoveGauge(string gaugeIdentifier)
|
||||
{
|
||||
if (_feed is null)
|
||||
if (_feed is null && Replay is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var remaining = _feed.Snapshot.Definitions
|
||||
var remaining = Definitions
|
||||
.Where(item => !StringComparer.OrdinalIgnoreCase.Equals(item.GaugeIdentifier, gaugeIdentifier))
|
||||
.ToArray();
|
||||
try
|
||||
{
|
||||
_feed.ReplaceDefinitions(remaining);
|
||||
ReplaceDefinitions(remaining);
|
||||
_error = null;
|
||||
if (StringComparer.OrdinalIgnoreCase.Equals(_editingGaugeId, gaugeIdentifier))
|
||||
{
|
||||
ResetEditor();
|
||||
}
|
||||
}
|
||||
catch (DashboardConfigurationException exception)
|
||||
catch (Exception exception) when (exception is DashboardConfigurationException or AutoForge.Application.Features.Vehicles.Telemetry.Replay.TelemetryReplayException)
|
||||
{
|
||||
_error = exception.Message;
|
||||
}
|
||||
|
|
@ -499,6 +548,22 @@
|
|||
_error = null;
|
||||
}
|
||||
|
||||
private void ReplaceDefinitions(IEnumerable<DashboardGaugeDefinition> definitions)
|
||||
{
|
||||
if (Replay is not null)
|
||||
{
|
||||
Replay.ReplaceDefinitions(definitions);
|
||||
}
|
||||
else if (_feed is not null)
|
||||
{
|
||||
_feed.ReplaceDefinitions(definitions);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new DashboardConfigurationException("No dashboard source is bound.");
|
||||
}
|
||||
}
|
||||
|
||||
private void ResetEditor()
|
||||
{
|
||||
_editingGaugeId = null;
|
||||
|
|
@ -530,10 +595,20 @@
|
|||
_ => state.ToString()
|
||||
};
|
||||
|
||||
private static string DisplayStateDescription(DashboardReadingState state, string? displayError) =>
|
||||
displayError is null
|
||||
? StateDescription(state)
|
||||
: $"{StateDescription(state)}; display conversion unavailable";
|
||||
private string DisplayStateDescription(DashboardReadingState state, string? displayError)
|
||||
{
|
||||
var description = Replay is null ? StateDescription(state) : state switch
|
||||
{
|
||||
DashboardReadingState.Good => "Good recorded sample",
|
||||
DashboardReadingState.Uncertain => "Uncertain recorded source quality",
|
||||
DashboardReadingState.Unknown => "Recorded source quality or value is unknown",
|
||||
DashboardReadingState.Stale => "Stale last-Good recorded sample",
|
||||
DashboardReadingState.Error => "Recorded reading unavailable after a failed source operation",
|
||||
DashboardReadingState.Unavailable => "No recorded sample available in this prefix",
|
||||
_ => $"Recorded {state}"
|
||||
};
|
||||
return displayError is null ? description : $"{description}; display conversion unavailable";
|
||||
}
|
||||
|
||||
private static string RangeDescription(
|
||||
DashboardReadingState state,
|
||||
|
|
@ -594,5 +669,9 @@
|
|||
{
|
||||
_feed.Changed -= OnFeedChanged;
|
||||
}
|
||||
if (_boundReplay is not null)
|
||||
{
|
||||
_boundReplay.Changed -= OnFeedChanged;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,230 @@
|
|||
@page "/telemetry-replay"
|
||||
@using AutoForge.Application.Features.Vehicles.Telemetry.Replay
|
||||
@implements IAsyncDisposable
|
||||
@inject ITelemetryReplayFactory ReplayFactory
|
||||
|
||||
<PageTitle>Recorded telemetry replay</PageTitle>
|
||||
<h1>Recorded telemetry replay</h1>
|
||||
<p>Inspect saved observations offline. RecordedReplay is not a live vehicle connection, diagnostic session or verification.</p>
|
||||
|
||||
@if (_player is { } player)
|
||||
{
|
||||
var snapshot = player.Snapshot;
|
||||
<section aria-label="Saved capture selection">
|
||||
<button id="replay-refresh" type="button" @onclick="RefreshAsync">Refresh saved captures</button>
|
||||
<label for="replay-capture">Saved capture ID</label>
|
||||
<select id="replay-capture" @bind="_selectedCapture">
|
||||
<option value="">Choose a saved capture</option>
|
||||
@foreach (var capture in snapshot.SavedCaptures)
|
||||
{
|
||||
<option value="@capture.CaptureId">@capture.CaptureId / @capture.ProfileIdentifier / @capture.State / @capture.ObservationCount observations</option>
|
||||
}
|
||||
</select>
|
||||
<button id="replay-load" type="button" @onclick="LoadAsync">Load saved capture</button>
|
||||
</section>
|
||||
@if (_error is not null || snapshot.Error is not null)
|
||||
{
|
||||
<p id="replay-error" role="alert">@(_error ?? snapshot.Error)</p>
|
||||
}
|
||||
@if (snapshot.FaultReason is { } fault)
|
||||
{
|
||||
<p id="replay-fault" role="alert">Recorded replay fault: @fault</p>
|
||||
}
|
||||
<p id="replay-status" role="status" aria-live="polite">
|
||||
Recorded replay: @snapshot.State; loading @snapshot.IsLoading; cleanup pending @snapshot.IsDraining.
|
||||
</p>
|
||||
@if (snapshot.Archive is { } archive && snapshot.Context is { } context)
|
||||
{
|
||||
<section aria-label="Recorded source and current replay context">
|
||||
<h2>Recorded provenance</h2>
|
||||
<p>Current context: @context.Kind; replay instance @context.InstanceIdentifier; capture @context.CaptureId.</p>
|
||||
<p>
|
||||
Original archived source only: provider @archive.Header.ProviderIdentifier; target @archive.Header.TargetKind;
|
||||
profile @archive.Header.ProfileIdentifier revision @archive.Header.ProfileRevision;
|
||||
vehicle metadata @archive.Header.VehicleIdentifier; session @archive.Header.SessionIdentifier;
|
||||
protocol @archive.Header.ProtocolName v@(archive.Header.ProtocolVersion);
|
||||
configuration @(archive.Header.DynamicsConfigurationIdentifier ?? "none (static)");
|
||||
run @(archive.Header.DynamicsRunIdentifier ?? "none (static)").
|
||||
</p>
|
||||
<p>Original UTC window @archive.Header.StartedAtUtc to @archive.Completion!.StoppedAtUtc. UTC, diagnostic and model clocks do not determine playback duration.</p>
|
||||
<p id="replay-source-completion" role="status">
|
||||
Original capture completion: @archive.Completion.State / @archive.Completion.StopReason.
|
||||
@archive.Completion.Error
|
||||
@if (archive.Completion.State != TelemetryCaptureState.Complete)
|
||||
{
|
||||
<strong>Partial/error source. Lost or unrecorded observations are not recoverable. End means end of retained data, not a Complete capture.</strong>
|
||||
}
|
||||
</p>
|
||||
@if (snapshot.RequiresAcknowledgement)
|
||||
{
|
||||
<button id="replay-acknowledge" type="button" @onclick="Acknowledge">
|
||||
Acknowledge this partial/error capture for recorded playback
|
||||
</button>
|
||||
}
|
||||
else if (snapshot.PartialAcknowledged)
|
||||
{
|
||||
<p>Partial/error capture acknowledgement applies to this load only.</p>
|
||||
}
|
||||
</section>
|
||||
<section aria-label="Recorded playback controls">
|
||||
<h2>Recorded playback</h2>
|
||||
<p id="replay-position">
|
||||
Capture elapsed ticks @snapshot.PositionTicks / @snapshot.DurationTicks;
|
||||
@Seconds(snapshot.PositionTicks) / @Seconds(snapshot.DurationTicks) seconds;
|
||||
applied observations @snapshot.AppliedCount / @archive.Observations.Count.
|
||||
@if (snapshot.State == ReplayState.Completed)
|
||||
{
|
||||
<strong>End of retained data. Original completion remains @archive.Completion.State.</strong>
|
||||
}
|
||||
</p>
|
||||
<div class="replay-actions">
|
||||
<button id="replay-play" type="button" @onclick="() => CommandAsync(player.PlayAsync)">Play recorded</button>
|
||||
<button id="replay-pause" type="button" @onclick="() => CommandAsync(player.PauseAsync)">Pause recorded</button>
|
||||
<button id="replay-stop" type="button" @onclick="() => CommandAsync(player.StopAsync)">Stop / before first</button>
|
||||
<button id="replay-restart" type="button" @onclick="() => CommandAsync(player.RestartAsync)">Restart recorded</button>
|
||||
<button id="replay-first" type="button" @onclick="() => Command(player.First)">First / before first</button>
|
||||
<button id="replay-previous" type="button" @onclick="() => Command(player.Previous)">Previous observation</button>
|
||||
<button id="replay-next" type="button" @onclick="() => Command(player.Next)">Next observation</button>
|
||||
<button id="replay-close" type="button" @onclick="CloseAsync">Close replay</button>
|
||||
</div>
|
||||
<label for="replay-rate">Recorded playback speed (0.25x-1000x; pause first)</label>
|
||||
<input id="replay-rate" type="number" step="any"
|
||||
@bind:get="RateText" @bind:set="SetRate" />
|
||||
<label for="replay-seek-time">Seek capture elapsed ticks (includes all ties)</label>
|
||||
<input id="replay-seek-time" type="number" step="1" @bind="_seekTicks" />
|
||||
<button id="replay-seek-time-apply" type="button" @onclick="SeekTime">Seek recorded time</button>
|
||||
<label for="replay-seek-ordinal">Applied observation count (0 is before first)</label>
|
||||
<input id="replay-seek-ordinal" type="number" step="1" @bind="_seekOrdinal" />
|
||||
<button id="replay-seek-ordinal-apply" type="button" @onclick="SeekOrdinal">Seek observation count</button>
|
||||
</section>
|
||||
<LiveDashboardPanel Replay="player" HeadingId="recorded-dashboard" />
|
||||
<section aria-label="Current recorded observation">
|
||||
<h2>Recorded raw / decoded inspection</h2>
|
||||
@if (snapshot.CurrentObservation is { } observation)
|
||||
{
|
||||
<p>
|
||||
Recorded observation @observation.Sequence; capture elapsed ticks @observation.CaptureElapsedTicks;
|
||||
module @observation.ModuleIdentifier / address @observation.Address;
|
||||
@observation.Service / @observation.Outcome; correlation @observation.CorrelationIdentifier.
|
||||
Diagnostic logical ticks @observation.StartLogicalTicks-@observation.EndLogicalTicks.
|
||||
@observation.DecodedSummary @observation.Error
|
||||
</p>
|
||||
<p>Original request bytes (base64): <code>@observation.RequestPayloadBase64</code></p>
|
||||
<p>Original response bytes (base64): <code>@(observation.ResponsePayloadBase64 ?? "No recorded response bytes")</code></p>
|
||||
@if (observation.SignalSnapshot is { } signals)
|
||||
{
|
||||
<ul aria-label="Recorded decoded signals">
|
||||
@foreach (var signal in signals.Signals)
|
||||
{
|
||||
<li>
|
||||
Recorded @signal.ModuleIdentifier / @signal.SignalIdentifier:
|
||||
@DisplayUnitPresentation.FormatSourceValue(signal.Value) @signal.Unit;
|
||||
@signal.Quality / @signal.Origin; diagnostic sample tick @signal.LogicalTimeTicks;
|
||||
model step @signal.ModelStepIndex / time @signal.ModelTimeSeconds s;
|
||||
configuration @signal.ModelConfigurationIdentifier / run @signal.ModelRunIdentifier.
|
||||
</li>
|
||||
}
|
||||
</ul>
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
<p>@(archive.Observations.Count == 0 ? "Empty recorded archive; no observations or samples." : "Before first recorded observation; no current samples. Seek time zero differs when zero-time records exist.")</p>
|
||||
}
|
||||
</section>
|
||||
}
|
||||
}
|
||||
|
||||
@code {
|
||||
private TelemetryReplaySession? _player;
|
||||
private string _selectedCapture = string.Empty;
|
||||
private string _seekTicks = "0";
|
||||
private string _seekOrdinal = "0";
|
||||
private string? _error;
|
||||
private bool _disposed;
|
||||
private string RateText => _player!.Snapshot.Rate.ToString("R", CultureInfo.InvariantCulture);
|
||||
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
_player = ReplayFactory.Create();
|
||||
_player.Changed += OnChanged;
|
||||
await RefreshAsync();
|
||||
}
|
||||
|
||||
private Task RefreshAsync() => CommandAsync(() => _player!.RefreshSavedCapturesAsync());
|
||||
private Task LoadAsync() => CommandAsync(() => _player!.LoadAsync(_selectedCapture));
|
||||
private void Acknowledge() => Command(_player!.AcknowledgePartial);
|
||||
|
||||
private void SetRate(string? text)
|
||||
{
|
||||
if (!double.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture, out var rate))
|
||||
{
|
||||
_error = "Enter a finite recorded playback speed between 0.25x and 1000x. The previous speed remains active.";
|
||||
return;
|
||||
}
|
||||
Command(() => _player!.SetRate(rate));
|
||||
}
|
||||
|
||||
private void SeekTime()
|
||||
{
|
||||
if (!long.TryParse(_seekTicks, NumberStyles.Integer, CultureInfo.InvariantCulture, out var ticks))
|
||||
{
|
||||
_error = "Enter an integer capture elapsed tick within the recorded duration.";
|
||||
return;
|
||||
}
|
||||
Command(() => _player!.SeekTime(ticks));
|
||||
}
|
||||
|
||||
private void SeekOrdinal()
|
||||
{
|
||||
if (!int.TryParse(_seekOrdinal, NumberStyles.Integer, CultureInfo.InvariantCulture, out var ordinal))
|
||||
{
|
||||
_error = "Enter an integer applied observation count from zero to the retained count.";
|
||||
return;
|
||||
}
|
||||
Command(() => _player!.SeekOrdinal(ordinal));
|
||||
}
|
||||
|
||||
private void Command(Action action)
|
||||
{
|
||||
try { action(); _error = null; }
|
||||
catch (Exception exception) when (exception is TelemetryReplayException or DashboardConfigurationException)
|
||||
{
|
||||
_error = exception.Message;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task CommandAsync(Func<Task> action)
|
||||
{
|
||||
try { await action(); _error = null; }
|
||||
catch (Exception exception) when (exception is TelemetryReplayException or TelemetryArchiveException or OperationCanceledException)
|
||||
{
|
||||
if (!_disposed) _error = exception.Message;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task CloseAsync()
|
||||
{
|
||||
if (_player is null) return;
|
||||
await _player.DisposeAsync();
|
||||
_error = null;
|
||||
}
|
||||
|
||||
private void OnChanged()
|
||||
{
|
||||
if (_disposed) return;
|
||||
_ = InvokeAsync(() => { if (!_disposed) StateHasChanged(); });
|
||||
}
|
||||
|
||||
private static string Seconds(long ticks) => ((decimal)ticks / TimeSpan.TicksPerSecond).ToString("0.#######", CultureInfo.InvariantCulture);
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
_disposed = true;
|
||||
if (_player is not null)
|
||||
{
|
||||
_player.Changed -= OnChanged;
|
||||
await _player.DisposeAsync();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -11,6 +11,7 @@
|
|||
<NavLink href="/vehicle-profiles">Vehicle profiles</NavLink>
|
||||
<NavLink href="/diagnostics">Synthetic diagnostics</NavLink>
|
||||
<NavLink href="/simulation">Vehicle simulation</NavLink>
|
||||
<NavLink href="/telemetry-replay">Recorded telemetry replay</NavLink>
|
||||
</nav>
|
||||
<section aria-label="Display units">
|
||||
<label for="display-unit-system">Unit system</label>
|
||||
|
|
|
|||
|
|
@ -0,0 +1,245 @@
|
|||
using System.Text;
|
||||
using System.Text.Json.Nodes;
|
||||
using AutoForge.Application.Features.Vehicles.Telemetry.LiveDashboard;
|
||||
using AutoForge.Application.Features.Vehicles.Telemetry.Recording;
|
||||
using AutoForge.Application.Features.Vehicles.Telemetry.Replay;
|
||||
using AutoForge.Core.ExecutionTargets;
|
||||
|
||||
namespace AutoForge.IntegrationTests;
|
||||
|
||||
public sealed partial class TelemetryReplayTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task EndPublication_RejectsReentryBeforeThePriorOwnerFinishesCleanup()
|
||||
{
|
||||
using var fixture = await ReplayFixture.CreateAsync(allZero: true);
|
||||
await using var player = fixture.CreatePlayer();
|
||||
await player.LoadAsync(fixture.CaptureId);
|
||||
Configure(player);
|
||||
var failures = new List<ReplayFailure>();
|
||||
var observed = false;
|
||||
void OnChanged()
|
||||
{
|
||||
if (observed || player.Snapshot.State != ReplayState.Completed || !player.Snapshot.IsDraining) return;
|
||||
observed = true;
|
||||
foreach (var command in new Action[]
|
||||
{
|
||||
player.Next, player.First, () => player.SetRate(2),
|
||||
() => player.SeekOrdinal(0), () => player.PlayAsync(),
|
||||
() => player.RestartAsync(), () => player.LoadAsync(fixture.CaptureId)
|
||||
})
|
||||
{
|
||||
try { command(); }
|
||||
catch (TelemetryReplayException exception) { failures.Add(exception.Failure); }
|
||||
}
|
||||
}
|
||||
player.Changed += OnChanged;
|
||||
try
|
||||
{
|
||||
await player.PlayAsync();
|
||||
Assert.True(observed);
|
||||
Assert.Equal(7, failures.Count);
|
||||
Assert.All(failures, failure => Assert.Equal(ReplayFailure.Busy, failure));
|
||||
Assert.Equal(4, player.Snapshot.AppliedCount);
|
||||
Assert.Equal(1, player.Snapshot.Rate);
|
||||
Assert.False(player.Snapshot.IsDraining);
|
||||
player.First();
|
||||
Assert.Equal(0, player.Snapshot.AppliedCount);
|
||||
}
|
||||
finally
|
||||
{
|
||||
player.Changed -= OnChanged;
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("start")]
|
||||
[InlineData("wake")]
|
||||
[InlineData("pause")]
|
||||
public async Task ClockFaults_AreVisibleWithoutChangingTheLastCommittedSampleAndCanBeStopped(string phase)
|
||||
{
|
||||
using var fixture = await ReplayFixture.CreateAsync();
|
||||
await using var player = fixture.CreatePlayer();
|
||||
await player.LoadAsync(fixture.CaptureId);
|
||||
Configure(player);
|
||||
player.SeekOrdinal(1);
|
||||
try
|
||||
{
|
||||
if (phase == "start")
|
||||
{
|
||||
fixture.Clock.Failure = new IOException("controlled clock fault");
|
||||
var exception = await Assert.ThrowsAsync<TelemetryReplayException>(() => player.PlayAsync());
|
||||
Assert.Equal(ReplayFailure.Faulted, exception.Failure);
|
||||
}
|
||||
else
|
||||
{
|
||||
await player.PlayAsync();
|
||||
var wait = await fixture.Waiter.TakeAsync();
|
||||
fixture.Clock.Failure = new IOException("controlled clock fault");
|
||||
if (phase == "pause")
|
||||
{
|
||||
var pause = player.PauseAsync();
|
||||
wait.Release();
|
||||
await pause.WaitAsync(Deadline);
|
||||
}
|
||||
else
|
||||
{
|
||||
wait.Release();
|
||||
await WaitForStateAsync(player, ReplayState.Faulted);
|
||||
}
|
||||
}
|
||||
Assert.Equal(ReplayState.Faulted, player.Snapshot.State);
|
||||
Assert.Contains("controlled clock fault", player.Snapshot.Error);
|
||||
Assert.Equal(1, player.Snapshot.AppliedCount);
|
||||
Assert.Equal(TimeSpan.TicksPerSecond, player.Snapshot.PositionTicks);
|
||||
Assert.Equal(850, player.Snapshot.Values[0].NumericValue);
|
||||
Assert.Equal(DashboardReadingState.Good, player.Snapshot.Values[0].State);
|
||||
await player.StopAsync();
|
||||
Assert.Equal(ReplayState.Stopped, player.Snapshot.State);
|
||||
}
|
||||
finally
|
||||
{
|
||||
fixture.Clock.Failure = null;
|
||||
fixture.Waiter.ReleaseAll();
|
||||
await player.StopAsync();
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CorruptReplacementAndChangedOrigin_AreRejectedByTheActualStrictReaderWithoutReplacingReplay()
|
||||
{
|
||||
using var fixture = await ReplayFixture.CreateAsync();
|
||||
await using var player = fixture.CreatePlayer();
|
||||
await player.LoadAsync(fixture.CaptureId);
|
||||
Configure(player);
|
||||
player.SeekOrdinal(1);
|
||||
var before = player.Snapshot;
|
||||
var archive = JsonNode.Parse(fixture.Bytes)!.AsObject();
|
||||
archive["observations"]![0]!["signalSnapshot"]!["signals"]![0]!["origin"] = "CURRENT_VEHICLE";
|
||||
RecalculateBytes(archive);
|
||||
await File.WriteAllTextAsync(fixture.ArchivePath, archive.ToJsonString());
|
||||
var origin = await Assert.ThrowsAsync<TelemetryArchiveException>(() => player.LoadAsync(fixture.CaptureId));
|
||||
Assert.Equal(TelemetryArchiveFailure.InvalidArchive, origin.Failure);
|
||||
AssertUnchanged(before, player.Snapshot);
|
||||
await File.WriteAllTextAsync(fixture.ArchivePath, "{truncated");
|
||||
var malformed = await Assert.ThrowsAsync<TelemetryArchiveException>(() => player.LoadAsync(fixture.CaptureId));
|
||||
Assert.Equal(TelemetryArchiveFailure.InvalidArchive, malformed.Failure);
|
||||
AssertUnchanged(before, player.Snapshot);
|
||||
Assert.NotNull(player.Snapshot.Error);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(true)]
|
||||
[InlineData(false)]
|
||||
public async Task MissingSignalOrNoPriorGood_UsesRecordedStaleOrExplicitErrorOnlyForTheAffectedModule(bool missing)
|
||||
{
|
||||
using var fixture = await ReplayFixture.CreateAsync();
|
||||
var archive = JsonNode.Parse(fixture.Bytes)!.AsObject();
|
||||
if (missing)
|
||||
{
|
||||
ChangeSignalArray(archive, 2, signals => signals.Clear());
|
||||
}
|
||||
else
|
||||
{
|
||||
ChangeSignalArray(archive, 0, signals => signals[0]!["quality"] = "Uncertain");
|
||||
archive["observations"]![0]!["signalSnapshot"]!["signals"]![0]!["quality"] = "uncertain";
|
||||
}
|
||||
RecalculateBytes(archive);
|
||||
await File.WriteAllTextAsync(fixture.ArchivePath, archive.ToJsonString());
|
||||
await using var player = fixture.CreatePlayer();
|
||||
await player.LoadAsync(fixture.CaptureId);
|
||||
Configure(player);
|
||||
player.SeekOrdinal(missing ? 3 : 4);
|
||||
Assert.Equal(missing ? DashboardReadingState.Stale : DashboardReadingState.Error, player.Snapshot.Values[0].State);
|
||||
Assert.Equal(missing ? 850d : null, player.Snapshot.Values[0].NumericValue);
|
||||
Assert.Equal(12.6, player.Snapshot.Values[1].NumericValue);
|
||||
Assert.Equal(DashboardReadingState.Good, player.Snapshot.Values[1].State);
|
||||
Assert.Equal(missing ? 1 : 0, player.Snapshot.SampleContexts.ContainsKey("a") ? 1 : 0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task OriginalPhysicalMetadata_IsNotRewrittenIntoCurrentReplayOrVehicleEvidence()
|
||||
{
|
||||
using var fixture = await ReplayFixture.CreateAsync();
|
||||
var original = TelemetryArchiveCodec.Deserialize(fixture.Bytes);
|
||||
var physicalMetadata = new TelemetryCaptureSnapshot(original.Header with { TargetKind = ExecutionTargetKind.PhysicalHardware },
|
||||
original.Observations, original.Completion);
|
||||
await File.WriteAllBytesAsync(fixture.ArchivePath, TelemetryArchiveCodec.Serialize(physicalMetadata));
|
||||
await using var player = fixture.CreatePlayer();
|
||||
await player.LoadAsync(fixture.CaptureId);
|
||||
Assert.Equal(ExecutionTargetKind.RecordedReplay, player.Snapshot.Context!.Kind);
|
||||
Assert.Equal(ExecutionTargetKind.PhysicalHardware, player.Snapshot.Archive!.Header.TargetKind);
|
||||
player.SeekOrdinal(4);
|
||||
Assert.Equal(ExecutionTargetKind.PhysicalHardware, player.Snapshot.Archive.Header.TargetKind);
|
||||
Assert.Equal(0, fixture.Store.SaveCalls);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ModelResetAndRepeatedModelTime_RemainRecordedFactsNotPlaybackOrdering()
|
||||
{
|
||||
using var fixture = await ReplayFixture.CreateAsync(dynamic: true, resetModel: true);
|
||||
await using var player = fixture.CreatePlayer();
|
||||
await player.LoadAsync(fixture.CaptureId);
|
||||
var archive = player.Snapshot.Archive!;
|
||||
Assert.Equal([3L, 0L, 0L, 0L], archive.Observations.Select(item => item.SignalSnapshot!.ModelStepIndex!.Value));
|
||||
Assert.Equal([1L, 2L, 2L, 4L], archive.Observations.Select(item => item.CaptureElapsedTicks / TimeSpan.TicksPerSecond));
|
||||
player.SeekOrdinal(1);
|
||||
Assert.Equal(3, player.Snapshot.CurrentObservation!.SignalSnapshot!.ModelStepIndex);
|
||||
player.SeekTime(TimeSpan.FromSeconds(2).Ticks);
|
||||
Assert.Equal(3, player.Snapshot.AppliedCount);
|
||||
Assert.Equal(3, player.Snapshot.CurrentObservation!.Sequence);
|
||||
Assert.Equal(0, player.Snapshot.CurrentObservation.SignalSnapshot!.ModelStepIndex);
|
||||
player.SeekOrdinal(1);
|
||||
Assert.Equal(3, player.Snapshot.CurrentObservation!.SignalSnapshot!.ModelStepIndex);
|
||||
Assert.Equal(fixture.Bytes, await File.ReadAllBytesAsync(fixture.ArchivePath));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(true)]
|
||||
[InlineData(false)]
|
||||
public async Task WaitFailureDuringPauseOrStop_DrainsButCannotMasqueradeAsSuccessfulCleanup(bool pause)
|
||||
{
|
||||
using var fixture = await ReplayFixture.CreateAsync();
|
||||
await using var player = fixture.CreatePlayer();
|
||||
await player.LoadAsync(fixture.CaptureId);
|
||||
Configure(player);
|
||||
player.SeekOrdinal(1);
|
||||
await player.PlayAsync();
|
||||
var wait = await fixture.Waiter.TakeAsync();
|
||||
try
|
||||
{
|
||||
var cleanup = pause ? player.PauseAsync() : player.StopAsync();
|
||||
await wait.CancellationRequested.Task.WaitAsync(Deadline);
|
||||
Assert.False(cleanup.IsCompleted);
|
||||
wait.Fail(new IOException("controlled fault during cleanup"));
|
||||
await cleanup.WaitAsync(Deadline);
|
||||
Assert.Equal(ReplayState.Faulted, player.Snapshot.State);
|
||||
Assert.False(player.Snapshot.IsDraining);
|
||||
Assert.Equal(1, player.Snapshot.AppliedCount);
|
||||
Assert.Equal(850, player.Snapshot.Values[0].NumericValue);
|
||||
Assert.Contains("controlled fault during cleanup", player.Snapshot.FaultReason);
|
||||
await player.StopAsync();
|
||||
Assert.Equal(ReplayState.Stopped, player.Snapshot.State);
|
||||
Assert.Equal(0, player.Snapshot.AppliedCount);
|
||||
Assert.Null(player.Snapshot.FaultReason);
|
||||
}
|
||||
finally
|
||||
{
|
||||
var stop = player.StopAsync();
|
||||
fixture.Waiter.ReleaseAll();
|
||||
await stop.WaitAsync(Deadline);
|
||||
}
|
||||
}
|
||||
|
||||
private static void ChangeSignalArray(JsonObject archive, int index, Action<JsonArray> change)
|
||||
{
|
||||
var observation = archive["observations"]![index]!;
|
||||
var raw = JsonNode.Parse(Convert.FromBase64String(observation["responsePayloadBase64"]!.GetValue<string>()))!;
|
||||
change(raw["data"]!["signals"]!.AsArray());
|
||||
if (raw["data"]!["signals"]!.AsArray().Count == 0)
|
||||
{
|
||||
observation["signalSnapshot"]!["signals"]!.AsArray().Clear();
|
||||
}
|
||||
observation["responsePayloadBase64"] = Convert.ToBase64String(Encoding.UTF8.GetBytes(raw.ToJsonString()));
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,516 @@
|
|||
using System.Text;
|
||||
using System.Text.Json.Nodes;
|
||||
using AutoForge.Application.Features.DisplayUnits;
|
||||
using AutoForge.Application.Features.Vehicles.Diagnostics;
|
||||
using AutoForge.Application.Features.Vehicles.Profiles;
|
||||
using AutoForge.Application.Features.Vehicles.Telemetry.LiveDashboard;
|
||||
using AutoForge.Application.Features.Vehicles.Telemetry.Recording;
|
||||
using AutoForge.Application.Features.Vehicles.Telemetry.Replay;
|
||||
using AutoForge.Diagnostics;
|
||||
using AutoForge.Core.ExecutionTargets;
|
||||
using AutoForge.Core.Simulation;
|
||||
using AutoForge.UI;
|
||||
using AutoForge.UI.Features.Vehicles.Telemetry.LiveDashboard;
|
||||
using AutoForge.UI.Features.Vehicles.Telemetry.Replay;
|
||||
using Microsoft.AspNetCore.Components;
|
||||
using Microsoft.AspNetCore.Components.Rendering;
|
||||
using Microsoft.AspNetCore.Components.RenderTree;
|
||||
using Microsoft.AspNetCore.Components.Web;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
#pragma warning disable BL0006
|
||||
|
||||
namespace AutoForge.IntegrationTests;
|
||||
|
||||
public sealed partial class TelemetryReplayTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData("Unknown", "850", "rpm", DashboardReadingState.Unknown, null)]
|
||||
[InlineData("Good", "null", "rpm", DashboardReadingState.Unknown, null)]
|
||||
[InlineData("Good", "\"not numeric\"", "rpm", DashboardReadingState.Unknown, null)]
|
||||
[InlineData("Good", "1e999", "rpm", DashboardReadingState.Unknown, null)]
|
||||
[InlineData("Good", "0", "rpm", DashboardReadingState.Good, 0d)]
|
||||
[InlineData("Good", "1000", "RPM", DashboardReadingState.Stale, 850d)]
|
||||
public async Task RecordedQualityAndUnitChanges_UseSharedRulesWithoutFutureOrCrossModuleFill(
|
||||
string quality, string jsonValue, string unit, DashboardReadingState expected, double? number)
|
||||
{
|
||||
using var fixture = await ReplayFixture.CreateAsync();
|
||||
await RewriteThirdSnapshotAsync(fixture, quality, jsonValue, unit);
|
||||
await using var player = fixture.CreatePlayer();
|
||||
await player.LoadAsync(fixture.CaptureId);
|
||||
Configure(player);
|
||||
player.SeekOrdinal(3);
|
||||
Assert.Equal(expected, player.Snapshot.Values[0].State);
|
||||
Assert.Equal(number, player.Snapshot.Values[0].NumericValue);
|
||||
Assert.Equal(12.6, player.Snapshot.Values[1].NumericValue);
|
||||
Assert.Equal(DashboardReadingState.Good, player.Snapshot.Values[1].State);
|
||||
player.SeekOrdinal(4);
|
||||
Assert.Equal(expected == DashboardReadingState.Good ? number : 850, player.Snapshot.Values[0].NumericValue);
|
||||
Assert.Equal(DashboardReadingState.Stale, player.Snapshot.Values[0].State);
|
||||
player.SeekOrdinal(0);
|
||||
Assert.All(player.Snapshot.Values, value => Assert.Null(value.Signal));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DynamicArchive_ReplaysOfflineWithRepeatedModelTimeAndOriginalCanonicalBytes()
|
||||
{
|
||||
using var fixture = await ReplayFixture.CreateAsync(dynamic: true);
|
||||
var source = await fixture.Store.LoadAsync(fixture.CaptureId);
|
||||
Assert.Equal(2, source.Header.ProtocolVersion);
|
||||
Assert.NotNull(source.Header.DynamicsConfigurationIdentifier);
|
||||
Assert.Single(source.Observations.Select(observation => observation.SignalSnapshot!.ModelTimeSeconds).Distinct());
|
||||
var services = new ServiceCollection();
|
||||
services.AddLogging();
|
||||
services.AddAutoForgeVehicleProfiles();
|
||||
services.AddAutoForgeUi();
|
||||
services.AddSingleton<ITelemetryArchiveStore>(fixture.Store);
|
||||
services.AddSingleton<TimeProvider>(fixture.Clock);
|
||||
services.AddSingleton<IReplayWaiter>(fixture.Waiter);
|
||||
using var provider = services.BuildServiceProvider();
|
||||
Assert.Empty(provider.GetRequiredService<IVehicleProfileService>().List());
|
||||
var factory = provider.GetRequiredService<ITelemetryReplayFactory>();
|
||||
await using var player = factory.Create();
|
||||
await player.LoadAsync(fixture.CaptureId);
|
||||
var binding = player.Snapshot.AvailableSignals.First(item => item.Unit == "m/s");
|
||||
player.ReplaceDefinitions([new("speed", "Recorded speed", DashboardGaugeKind.HorizontalBar,
|
||||
binding.ModuleIdentifier, binding.SignalIdentifier, binding.Unit, 0, 40, 3)]);
|
||||
player.SeekOrdinal(1);
|
||||
var number = player.Snapshot.Values.Single().NumericValue;
|
||||
var definitions = player.Snapshot.Definitions;
|
||||
var canonical = TelemetryArchiveCodec.Serialize(player.Snapshot.Archive!);
|
||||
player.SeekTime(TimeSpan.FromSeconds(2).Ticks);
|
||||
Assert.Equal(3, player.Snapshot.AppliedCount);
|
||||
player.SeekOrdinal(4);
|
||||
player.SeekOrdinal(1);
|
||||
Assert.Equal(number, player.Snapshot.Values.Single().NumericValue);
|
||||
Assert.Equal(definitions, player.Snapshot.Definitions);
|
||||
Assert.Equal(canonical, TelemetryArchiveCodec.Serialize(player.Snapshot.Archive!));
|
||||
Assert.Equal(fixture.Bytes, await File.ReadAllBytesAsync(fixture.ArchivePath));
|
||||
Assert.Equal(0, fixture.Store.SaveCalls);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task VeryLargeGap_UsesBoundedPositiveWaitsAndCancellationRatherThanTickOverflow()
|
||||
{
|
||||
using var fixture = await ReplayFixture.CreateAsync();
|
||||
var archive = JsonNode.Parse(fixture.Bytes)!.AsObject();
|
||||
archive["observations"]![3]!["captureElapsedTicks"] = long.MaxValue;
|
||||
RecalculateBytes(archive);
|
||||
await File.WriteAllTextAsync(fixture.ArchivePath, archive.ToJsonString());
|
||||
await using var player = fixture.CreatePlayer();
|
||||
await player.LoadAsync(fixture.CaptureId);
|
||||
player.SeekOrdinal(3);
|
||||
player.SetRate(0.25);
|
||||
await player.PlayAsync();
|
||||
var wait = await fixture.Waiter.TakeAsync();
|
||||
try
|
||||
{
|
||||
Assert.True(wait.Interval > TimeSpan.Zero);
|
||||
Assert.True(wait.Interval <= TelemetryReplaySession.MaximumWait);
|
||||
var stop = player.StopAsync();
|
||||
wait.Release();
|
||||
await stop.WaitAsync(Deadline);
|
||||
Assert.Equal(0, player.Snapshot.AppliedCount);
|
||||
}
|
||||
finally
|
||||
{
|
||||
fixture.Waiter.ReleaseAll();
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RenderedRecordedRouteAndSharedEditor_ShowRejectionsPinnedUnitsAndNoGaugeOwnedClock()
|
||||
{
|
||||
using var fixture = await ReplayFixture.CreateAsync(dynamic: true);
|
||||
var services = new ServiceCollection();
|
||||
services.AddLogging();
|
||||
services.AddAutoForgeUi();
|
||||
services.AddSingleton<ITelemetryArchiveStore>(fixture.Store);
|
||||
services.AddSingleton<TimeProvider>(fixture.Clock);
|
||||
services.AddSingleton<IReplayWaiter>(fixture.Waiter);
|
||||
using var provider = services.BuildServiceProvider();
|
||||
var factory = provider.GetRequiredService<ITelemetryReplayFactory>();
|
||||
await using var player = factory.Create();
|
||||
await player.LoadAsync(fixture.CaptureId);
|
||||
var binding = player.Snapshot.AvailableSignals.First(item => item.Unit == "m/s");
|
||||
var definition = new DashboardGaugeDefinition("speed", "Recorded speed", DashboardGaugeKind.HorizontalBar,
|
||||
binding.ModuleIdentifier, binding.SignalIdentifier, binding.Unit, 0, 40, 3);
|
||||
player.ReplaceDefinitions([definition]);
|
||||
player.SeekOrdinal(1);
|
||||
await using var renderer = new ReplayEventRenderer(provider, provider.GetRequiredService<ILoggerFactory>());
|
||||
var root = renderer.Attach(new ReplayGaugeHost { Player = player });
|
||||
await renderer.Dispatcher.InvokeAsync(() => renderer.RenderAsync(root));
|
||||
var originalPosition = player.Snapshot.PositionTicks;
|
||||
var originalCount = player.Snapshot.AppliedCount;
|
||||
Assert.Contains("Recorded replay", renderer.Text(root));
|
||||
Assert.DoesNotContain("Start monitoring", renderer.Text(root));
|
||||
await renderer.Dispatcher.InvokeAsync(() => renderer.ClickByTextAsync(root, "Edit"));
|
||||
Assert.Equal(40 / 0.44704, double.Parse(
|
||||
renderer.Attribute(root, "replay-test-gauge-maximum", "value")!.ToString()!,
|
||||
System.Globalization.CultureInfo.InvariantCulture), 12);
|
||||
await renderer.Dispatcher.InvokeAsync(() => renderer.ChangeAsync(root, "replay-test-gauge-label", ""));
|
||||
await renderer.Dispatcher.InvokeAsync(() => renderer.ClickByTextAsync(root, "Save gauge"));
|
||||
Assert.Equal(definition, player.Snapshot.Definitions.Single());
|
||||
Assert.Contains("Gauge labels must be nonblank", renderer.Text(root));
|
||||
await renderer.Dispatcher.InvokeAsync(() => renderer.ChangeAsync(root, "replay-test-gauge-label", "Updated recorded speed"));
|
||||
await renderer.Dispatcher.InvokeAsync(() => renderer.SetMetricAsync(root));
|
||||
Assert.Contains("Range input is pinned to ImperialUS", renderer.Text(root));
|
||||
await renderer.Dispatcher.InvokeAsync(() => renderer.ClickByTextAsync(root, "Save gauge"));
|
||||
Assert.Equal(40, player.Snapshot.Definitions.Single().Maximum);
|
||||
await renderer.Dispatcher.InvokeAsync(() => renderer.ClickByTextAsync(root, "Hide gauges"));
|
||||
await renderer.Dispatcher.InvokeAsync(() => renderer.ClickByTextAsync(root, "Show gauges"));
|
||||
Assert.Equal(originalPosition, player.Snapshot.PositionTicks);
|
||||
Assert.Equal(originalCount, player.Snapshot.AppliedCount);
|
||||
Assert.Equal(0, fixture.Waiter.WaitCount);
|
||||
Assert.Equal(0, fixture.Store.SaveCalls);
|
||||
|
||||
var routeAttributes = typeof(TelemetryReplayPage).GetCustomAttributes(typeof(RouteAttribute), false).Cast<RouteAttribute>();
|
||||
Assert.Contains(routeAttributes, attribute => attribute.Template == "/telemetry-replay");
|
||||
await using var html = new HtmlRenderer(provider, provider.GetRequiredService<ILoggerFactory>());
|
||||
var route = await html.Dispatcher.InvokeAsync(() => html.RenderComponentAsync<TelemetryReplayPage>());
|
||||
var text = await html.Dispatcher.InvokeAsync(route.ToHtmlString);
|
||||
Assert.Contains("Recorded telemetry replay", text);
|
||||
Assert.Contains(fixture.CaptureId, text);
|
||||
Assert.Contains("Load saved capture", text);
|
||||
Assert.DoesNotContain("Start monitoring", text);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ActualRouteControls_ReconcileRejectedRateRequirePartialAcknowledgementAndDrainOnUnmount()
|
||||
{
|
||||
using var fixture = await ReplayFixture.CreateAsync(partial: TelemetryCaptureState.Incomplete);
|
||||
var services = new ServiceCollection();
|
||||
services.AddLogging();
|
||||
services.AddAutoForgeVehicleProfiles();
|
||||
services.AddAutoForgeUi();
|
||||
services.AddSingleton<ITelemetryArchiveStore>(fixture.Store);
|
||||
services.AddSingleton<TimeProvider>(fixture.Clock);
|
||||
services.AddSingleton<IReplayWaiter>(fixture.Waiter);
|
||||
var forbidden = new ForbiddenLiveService();
|
||||
services.AddSingleton<IDiagnosticSessionService>(forbidden);
|
||||
var factory = new TrackingReplayFactory(new TelemetryReplayFactory(fixture.Store, fixture.Clock, fixture.Waiter));
|
||||
services.AddSingleton<ITelemetryReplayFactory>(factory);
|
||||
using var provider = services.BuildServiceProvider();
|
||||
var renderer = new ReplayEventRenderer(provider, provider.GetRequiredService<ILoggerFactory>());
|
||||
try
|
||||
{
|
||||
var root = renderer.Attach(typeof(TelemetryReplayPage));
|
||||
await renderer.Dispatcher.InvokeAsync(() => renderer.RenderAsync(root));
|
||||
await renderer.Dispatcher.InvokeAsync(() => renderer.ChangeAsync(root, "replay-capture", fixture.CaptureId));
|
||||
await renderer.Dispatcher.InvokeAsync(() => renderer.ClickAsync(root, "replay-load"));
|
||||
var player = factory.Last!;
|
||||
Assert.Equal(ReplayState.Stopped, player.Snapshot.State);
|
||||
Assert.Contains("autoforge.synthetic-diagnostics v1", renderer.Text(root));
|
||||
Assert.DoesNotContain("v@archive", renderer.Text(root));
|
||||
await renderer.Dispatcher.InvokeAsync(() => renderer.ClickAsync(root, "replay-next"));
|
||||
Assert.Contains("Acknowledge this load", renderer.Text(root));
|
||||
Assert.Equal(0, player.Snapshot.AppliedCount);
|
||||
await renderer.Dispatcher.InvokeAsync(() => renderer.ClickAsync(root, "replay-acknowledge"));
|
||||
await renderer.Dispatcher.InvokeAsync(() => renderer.ClickAsync(root, "replay-next"));
|
||||
Assert.Equal(1, player.Snapshot.AppliedCount);
|
||||
await renderer.Dispatcher.InvokeAsync(() => renderer.ClickAsync(root, "replay-play"));
|
||||
var wait = await fixture.Waiter.TakeAsync();
|
||||
await renderer.Dispatcher.InvokeAsync(() => renderer.ChangeAsync(root, "replay-rate", "1000"));
|
||||
Assert.Equal(1, player.Snapshot.Rate);
|
||||
Assert.Equal("1", renderer.Attribute(root, "replay-rate", "value")?.ToString());
|
||||
Assert.Contains("Pause first", renderer.Text(root));
|
||||
await renderer.Dispatcher.InvokeAsync(() => renderer.ClickAsync(root, "replay-play"));
|
||||
Assert.Equal(1, fixture.Waiter.WaitCount);
|
||||
var pause = renderer.Dispatcher.InvokeAsync(() => renderer.ClickAsync(root, "replay-pause"));
|
||||
await wait.CancellationRequested.Task.WaitAsync(Deadline);
|
||||
Assert.True(player.Snapshot.IsDraining);
|
||||
wait.Release();
|
||||
await pause.WaitAsync(Deadline);
|
||||
await renderer.Dispatcher.InvokeAsync(() => renderer.ChangeAsync(root, "replay-seek-time", "-1"));
|
||||
await renderer.Dispatcher.InvokeAsync(() => renderer.ClickAsync(root, "replay-seek-time-apply"));
|
||||
Assert.Contains("within the recorded duration", renderer.Text(root));
|
||||
await renderer.Dispatcher.InvokeAsync(() => renderer.ChangeAsync(root, "replay-seek-ordinal", "4"));
|
||||
await renderer.Dispatcher.InvokeAsync(() => renderer.ClickAsync(root, "replay-seek-ordinal-apply"));
|
||||
Assert.Contains("End of retained data", renderer.Text(root));
|
||||
Assert.Contains("Incomplete", renderer.Text(root));
|
||||
await renderer.Dispatcher.InvokeAsync(() => renderer.ClickAsync(root, "replay-restart"));
|
||||
var restarted = await fixture.Waiter.TakeAsync();
|
||||
var disposal = renderer.DisposeAsync().AsTask();
|
||||
await restarted.CancellationRequested.Task.WaitAsync(Deadline);
|
||||
Assert.False(disposal.IsCompleted);
|
||||
restarted.Release();
|
||||
await disposal.WaitAsync(Deadline);
|
||||
Assert.Equal(ReplayState.Closed, player.Snapshot.State);
|
||||
Assert.Empty(provider.GetRequiredService<IVehicleProfileService>().List());
|
||||
Assert.Equal(0, forbidden.LiveCalls);
|
||||
Assert.Equal(0, forbidden.ModelCalls);
|
||||
Assert.Equal(0, fixture.Store.SaveCalls);
|
||||
Assert.Equal(fixture.Bytes, await File.ReadAllBytesAsync(fixture.ArchivePath));
|
||||
var fresh = factory.Create();
|
||||
await using (fresh)
|
||||
{
|
||||
Assert.Equal(ReplayState.Unloaded, fresh.Snapshot.State);
|
||||
Assert.NotSame(player, fresh);
|
||||
}
|
||||
}
|
||||
|
||||
finally
|
||||
{
|
||||
fixture.Waiter.ReleaseAll();
|
||||
await renderer.DisposeAsync();
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ActivePlayback_SharedGaugeHideUnitsAndUnmountCannotOwnTheClock()
|
||||
{
|
||||
using var fixture = await ReplayFixture.CreateAsync();
|
||||
var services = new ServiceCollection();
|
||||
services.AddLogging();
|
||||
services.AddAutoForgeUi();
|
||||
using var provider = services.BuildServiceProvider();
|
||||
await using var player = fixture.CreatePlayer();
|
||||
await player.LoadAsync(fixture.CaptureId);
|
||||
Configure(player);
|
||||
await player.PlayAsync();
|
||||
var wait = await fixture.Waiter.TakeAsync();
|
||||
var renderer = new ReplayEventRenderer(provider, provider.GetRequiredService<ILoggerFactory>());
|
||||
try
|
||||
{
|
||||
var root = renderer.Attach(new ReplayGaugeHost { Player = player });
|
||||
await renderer.Dispatcher.InvokeAsync(() => renderer.RenderAsync(root));
|
||||
await renderer.Dispatcher.InvokeAsync(() => renderer.ClickByTextAsync(root, "Hide gauges"));
|
||||
await renderer.Dispatcher.InvokeAsync(() => renderer.SetMetricAsync(root));
|
||||
await renderer.Dispatcher.InvokeAsync(() => renderer.ClickByTextAsync(root, "Show gauges"));
|
||||
player.ReplaceDefinitions([]);
|
||||
await renderer.DisposeAsync();
|
||||
Assert.Equal(ReplayState.Playing, player.Snapshot.State);
|
||||
Assert.Equal(0, player.Snapshot.PositionTicks);
|
||||
Assert.Equal(0, player.Snapshot.AppliedCount);
|
||||
Assert.Equal(1, fixture.Waiter.WaitCount);
|
||||
Assert.False(wait.CancellationRequested.Task.IsCompleted);
|
||||
fixture.Clock.Advance(TimeSpan.FromSeconds(1));
|
||||
wait.Release();
|
||||
var continued = await fixture.Waiter.TakeAsync();
|
||||
Assert.Equal(1, player.Snapshot.AppliedCount);
|
||||
Assert.Equal(ReplayState.Playing, player.Snapshot.State);
|
||||
Assert.Empty(player.Snapshot.Values);
|
||||
var stop = player.StopAsync();
|
||||
continued.Release();
|
||||
await stop.WaitAsync(Deadline);
|
||||
}
|
||||
finally
|
||||
{
|
||||
var stop = player.StopAsync();
|
||||
fixture.Waiter.ReleaseAll();
|
||||
await stop.WaitAsync(Deadline);
|
||||
await renderer.DisposeAsync();
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RenderedClockFault_RemainsVisibleDespitePriorCommandErrorAndRejectedRecoveryNavigation()
|
||||
{
|
||||
using var fixture = await ReplayFixture.CreateAsync();
|
||||
var services = new ServiceCollection();
|
||||
services.AddLogging();
|
||||
services.AddAutoForgeUi();
|
||||
services.AddSingleton<ITelemetryArchiveStore>(fixture.Store);
|
||||
var factory = new TrackingReplayFactory(new TelemetryReplayFactory(fixture.Store, fixture.Clock, fixture.Waiter));
|
||||
services.AddSingleton<ITelemetryReplayFactory>(factory);
|
||||
using var provider = services.BuildServiceProvider();
|
||||
var renderer = new ReplayEventRenderer(provider, provider.GetRequiredService<ILoggerFactory>());
|
||||
try
|
||||
{
|
||||
var root = renderer.Attach(typeof(TelemetryReplayPage));
|
||||
await renderer.Dispatcher.InvokeAsync(() => renderer.RenderAsync(root));
|
||||
await renderer.Dispatcher.InvokeAsync(() => renderer.ChangeAsync(root, "replay-capture", fixture.CaptureId));
|
||||
await renderer.Dispatcher.InvokeAsync(() => renderer.ClickAsync(root, "replay-load"));
|
||||
await renderer.Dispatcher.InvokeAsync(() => renderer.ClickAsync(root, "replay-play"));
|
||||
var wait = await fixture.Waiter.TakeAsync();
|
||||
await renderer.Dispatcher.InvokeAsync(() => renderer.ChangeAsync(root, "replay-rate", "1000"));
|
||||
wait.Fail(new IOException("controlled rendered wait fault"));
|
||||
await WaitForStateAsync(factory.Last!, ReplayState.Faulted);
|
||||
await renderer.Dispatcher.InvokeAsync(() => renderer.ClickAsync(root, "replay-next"));
|
||||
await renderer.Dispatcher.InvokeAsync(() =>
|
||||
{
|
||||
Assert.Contains("controlled rendered wait fault", renderer.Text(root));
|
||||
Assert.Contains("Use Stop or First", renderer.Text(root));
|
||||
});
|
||||
Assert.Equal(0, factory.Last!.Snapshot.AppliedCount);
|
||||
Assert.Equal(1, factory.Last.Snapshot.Rate);
|
||||
Assert.Contains("controlled rendered wait fault", factory.Last.Snapshot.FaultReason);
|
||||
await renderer.Dispatcher.InvokeAsync(() => renderer.ClickAsync(root, "replay-stop"));
|
||||
Assert.Null(factory.Last.Snapshot.FaultReason);
|
||||
}
|
||||
finally
|
||||
{
|
||||
fixture.Waiter.ReleaseAll();
|
||||
await renderer.DisposeAsync();
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class TrackingReplayFactory(ITelemetryReplayFactory inner) : ITelemetryReplayFactory
|
||||
{
|
||||
public TelemetryReplaySession? Last { get; private set; }
|
||||
public TelemetryReplaySession Create() => Last = inner.Create();
|
||||
}
|
||||
|
||||
private sealed class ForbiddenLiveService : IDiagnosticSessionService
|
||||
{
|
||||
public int LiveCalls { get; private set; }
|
||||
public int ModelCalls { get; private set; }
|
||||
public IReadOnlyList<DiagnosticProviderDescriptor> Providers => [];
|
||||
public Task<DiagnosticSession> OpenAsync(string profileIdentifier, int profileRevision,
|
||||
string providerIdentifier, ExecutionTargetKind targetKind, CancellationToken cancellationToken = default)
|
||||
{
|
||||
LiveCalls++;
|
||||
throw new InvalidOperationException("Replay attempted a live diagnostic operation.");
|
||||
}
|
||||
public Task<DiagnosticSession> OpenDynamicsAsync(string profileIdentifier, int profileRevision,
|
||||
string providerIdentifier, ExecutionTargetKind targetKind, DynamicsConfiguration configuration,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ModelCalls++;
|
||||
throw new InvalidOperationException("Replay attempted a model operation.");
|
||||
}
|
||||
public Task<DiagnosticSession> ResetAsync(DiagnosticSession session, CancellationToken cancellationToken = default)
|
||||
{
|
||||
LiveCalls++;
|
||||
throw new InvalidOperationException("Replay attempted a live reset.");
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task RewriteThirdSnapshotAsync(ReplayFixture fixture, string quality, string value, string unit)
|
||||
{
|
||||
var archive = JsonNode.Parse(fixture.Bytes)!.AsObject();
|
||||
var observation = archive["observations"]![2]!;
|
||||
var decoded = observation["signalSnapshot"]!["signals"]![0]!;
|
||||
decoded["quality"] = quality.ToLowerInvariant();
|
||||
decoded["value"] = JsonNode.Parse(value);
|
||||
decoded["unit"] = unit;
|
||||
var raw = JsonNode.Parse(Convert.FromBase64String(observation["responsePayloadBase64"]!.GetValue<string>()))!;
|
||||
raw["data"]!["signals"]![0]!["quality"] = quality;
|
||||
raw["data"]!["signals"]![0]!["value"] = JsonNode.Parse(value);
|
||||
raw["data"]!["signals"]![0]!["unit"] = unit;
|
||||
observation["responsePayloadBase64"] = Convert.ToBase64String(Encoding.UTF8.GetBytes(raw.ToJsonString()));
|
||||
RecalculateBytes(archive);
|
||||
await File.WriteAllTextAsync(fixture.ArchivePath, archive.ToJsonString());
|
||||
}
|
||||
|
||||
private static void RecalculateBytes(JsonObject archive) =>
|
||||
archive["completion"]!["observationBytes"] = archive["observations"]!.AsArray()
|
||||
.Sum(observation => (long)Encoding.UTF8.GetByteCount(observation!.ToJsonString()));
|
||||
|
||||
private sealed class ReplayGaugeHost : ComponentBase
|
||||
{
|
||||
public required TelemetryReplaySession Player { get; init; }
|
||||
private DisplayUnitSelection _selection = DisplayUnitSelection.Default;
|
||||
public void SetMetric()
|
||||
{
|
||||
_selection = new DisplayUnitSelection(DisplayUnitSystem.Metric, SpeedDisplayMode.Road);
|
||||
StateHasChanged();
|
||||
}
|
||||
protected override void BuildRenderTree(RenderTreeBuilder builder)
|
||||
{
|
||||
builder.OpenComponent<CascadingValue<DisplayUnitSelection>>(0);
|
||||
builder.AddAttribute(1, "Value", _selection);
|
||||
builder.AddAttribute(2, "ChildContent", (RenderFragment)(child =>
|
||||
{
|
||||
child.OpenComponent<LiveDashboardPanel>(0);
|
||||
child.AddAttribute(1, nameof(LiveDashboardPanel.Replay), Player);
|
||||
child.AddAttribute(2, nameof(LiveDashboardPanel.HeadingId), "replay-test");
|
||||
child.CloseComponent();
|
||||
}));
|
||||
builder.CloseComponent();
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class ReplayEventRenderer(IServiceProvider services, ILoggerFactory loggerFactory) : Renderer(services, loggerFactory)
|
||||
{
|
||||
private readonly Dictionary<int, IComponent> _roots = [];
|
||||
public override Dispatcher Dispatcher { get; } = Dispatcher.CreateDefault();
|
||||
public int Attach(IComponent component)
|
||||
{
|
||||
var id = AssignRootComponentId(component);
|
||||
_roots[id] = component;
|
||||
return id;
|
||||
}
|
||||
public int Attach(Type type) => Attach(InstantiateComponent(type));
|
||||
public Task RenderAsync(int id) => RenderRootComponentAsync(id, ParameterView.Empty);
|
||||
public Task SetMetricAsync(int id)
|
||||
{
|
||||
((ReplayGaugeHost)_roots[id]).SetMetric();
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
public string Text(int id) => string.Concat(Frames(id).Select(frame => frame.FrameType switch
|
||||
{
|
||||
RenderTreeFrameType.Text => frame.TextContent,
|
||||
RenderTreeFrameType.Markup => frame.MarkupContent,
|
||||
_ => string.Empty
|
||||
}));
|
||||
public object? Attribute(int id, string elementId, string name) =>
|
||||
ElementFrames(id, elementId).FirstOrDefault(frame => frame.FrameType == RenderTreeFrameType.Attribute && frame.AttributeName == name).AttributeValue;
|
||||
public Task ChangeAsync(int id, string elementId, string value)
|
||||
{
|
||||
var element = ElementNode(id, elementId);
|
||||
return DispatchEventAsync(element.Frames.Single(frame =>
|
||||
frame.FrameType == RenderTreeFrameType.Attribute && frame.AttributeName == "onchange").AttributeEventHandlerId,
|
||||
new EventFieldInfo { ComponentId = element.ComponentId, FieldValue = value },
|
||||
new ChangeEventArgs { Value = value });
|
||||
}
|
||||
public Task ClickAsync(int id, string elementId) =>
|
||||
DispatchEventAsync(ElementFrames(id, elementId).Single(frame =>
|
||||
frame.FrameType == RenderTreeFrameType.Attribute && frame.AttributeName == "onclick").AttributeEventHandlerId,
|
||||
null, new MouseEventArgs());
|
||||
public Task ClickByTextAsync(int id, string text)
|
||||
{
|
||||
foreach (var componentId in ComponentIds(id))
|
||||
{
|
||||
var frames = GetCurrentRenderTreeFrames(componentId);
|
||||
for (var index = 0; index < frames.Count; index++)
|
||||
{
|
||||
if (frames.Array[index].FrameType != RenderTreeFrameType.Element ||
|
||||
frames.Array[index].ElementName != "button") continue;
|
||||
var element = frames.Array.Skip(index).Take(frames.Array[index].ElementSubtreeLength).ToArray();
|
||||
var label = string.Concat(element.Where(frame => frame.FrameType == RenderTreeFrameType.Text).Select(frame => frame.TextContent)).Trim();
|
||||
if (label != text) continue;
|
||||
var callback = element.Single(frame => frame.FrameType == RenderTreeFrameType.Attribute && frame.AttributeName == "onclick");
|
||||
return DispatchEventAsync(callback.AttributeEventHandlerId, null, new MouseEventArgs());
|
||||
}
|
||||
}
|
||||
throw new InvalidOperationException($"Button '{text}' not rendered.");
|
||||
}
|
||||
private IEnumerable<RenderTreeFrame> ElementFrames(int id, string elementId) => ElementNode(id, elementId).Frames;
|
||||
|
||||
private (int ComponentId, RenderTreeFrame[] Frames) ElementNode(int id, string elementId)
|
||||
{
|
||||
foreach (var componentId in ComponentIds(id))
|
||||
{
|
||||
var frames = GetCurrentRenderTreeFrames(componentId);
|
||||
for (var index = 0; index < frames.Count; index++)
|
||||
{
|
||||
if (frames.Array[index].FrameType != RenderTreeFrameType.Element) continue;
|
||||
var element = frames.Array.Skip(index).Take(frames.Array[index].ElementSubtreeLength).ToArray();
|
||||
if (element.Skip(1).TakeWhile(frame => frame.FrameType == RenderTreeFrameType.Attribute)
|
||||
.Any(frame => frame.AttributeName == "id" && frame.AttributeValue?.ToString() == elementId)) return (componentId, element);
|
||||
}
|
||||
}
|
||||
throw new InvalidOperationException($"Element '{elementId}' not rendered.");
|
||||
}
|
||||
private IEnumerable<int> ComponentIds(int id)
|
||||
{
|
||||
yield return id;
|
||||
var frames = GetCurrentRenderTreeFrames(id);
|
||||
for (var index = 0; index < frames.Count; index++)
|
||||
{
|
||||
if (frames.Array[index].FrameType != RenderTreeFrameType.Component) continue;
|
||||
foreach (var nested in ComponentIds(frames.Array[index].ComponentId)) yield return nested;
|
||||
}
|
||||
}
|
||||
private IEnumerable<RenderTreeFrame> Frames(int id) => ComponentIds(id).SelectMany(componentId =>
|
||||
{
|
||||
var frames = GetCurrentRenderTreeFrames(componentId);
|
||||
return frames.Array.Take(frames.Count);
|
||||
});
|
||||
protected override void HandleException(Exception exception) => throw new InvalidOperationException("Replay rendering failed.", exception);
|
||||
protected override Task UpdateDisplayAsync(in RenderBatch renderBatch) => Task.CompletedTask;
|
||||
}
|
||||
#pragma warning restore BL0006
|
||||
}
|
||||
|
|
@ -0,0 +1,129 @@
|
|||
using AutoForge.Application.Features.DisplayUnits;
|
||||
using AutoForge.Application.Features.Vehicles.Diagnostics;
|
||||
using AutoForge.Application.Features.Vehicles.Profiles;
|
||||
using AutoForge.Application.Features.Vehicles.Simulation;
|
||||
using AutoForge.Application.Features.Vehicles.Telemetry.Recording;
|
||||
using AutoForge.Application.Features.Vehicles.Telemetry.Replay;
|
||||
using AutoForge.Core.ExecutionTargets;
|
||||
using AutoForge.Core.Simulation;
|
||||
using AutoForge.Core.Vehicles;
|
||||
using AutoForge.Diagnostics;
|
||||
using AutoForge.Simulation;
|
||||
using AutoForge.UI;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace AutoForge.IntegrationTests;
|
||||
|
||||
public sealed partial class TelemetryReplayTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task ReplayCoexistsWithRealLiveSource_WithoutReadsModelCallsOrRecordingWorkspaceRebind()
|
||||
{
|
||||
using var fixture = await ReplayFixture.CreateAsync();
|
||||
var source = new CountingDynamicsFactory(
|
||||
new DynamicsDiagnosticTransportFactory(SyntheticDiagnosticExamples.CreateDefinitions()));
|
||||
var services = new ServiceCollection();
|
||||
services.AddAutoForgeVehicleProfiles();
|
||||
services.AddAutoForgeDiagnostics([source]);
|
||||
services.AddAutoForgeDynamicsConfigurations();
|
||||
services.AddAutoForgeUi();
|
||||
services.AddSingleton<ITelemetryArchiveStore>(fixture.Store);
|
||||
services.AddSingleton<TimeProvider>(fixture.Clock);
|
||||
services.AddSingleton<IReplayWaiter>(fixture.Waiter);
|
||||
services.AddSingleton<IDisplayUnitPreferenceStore, IsolatedDisplayUnitPreferenceStore>();
|
||||
using var provider = services.BuildServiceProvider();
|
||||
provider.GetRequiredService<IVehicleProfileService>().Import(
|
||||
File.ReadAllText(Path.Combine(AppContext.BaseDirectory, "Fixtures", "synthetic-truck-baseline.json")));
|
||||
var configuration = provider.GetRequiredService<IDynamicsConfigurationService>().CreateExample(ProfileId, 1);
|
||||
await using var live = await provider.GetRequiredService<IDiagnosticSessionService>().OpenDynamicsAsync(
|
||||
ProfileId, 1, source.Descriptor.Target.ProviderIdentifier, ExecutionTargetKind.Simulation, configuration);
|
||||
await live.DynamicsControl!.StepAsync(7);
|
||||
var workspace = provider.GetRequiredService<TelemetryRecordingWorkspace>();
|
||||
workspace.Start(live);
|
||||
var endpoint = live.ExpectedEndpoints.Single(item => item.ModuleIdentifier == ModuleA);
|
||||
Assert.True((await live.ReadSignalsAsync(endpoint)).IsSuccess);
|
||||
workspace.Stop();
|
||||
var oldRecording = TelemetryArchiveCodec.Serialize(workspace.CurrentCapture!);
|
||||
var oldTrace = live.Trace.Entries.Count;
|
||||
var oldStatus = live.DynamicsControl.Status;
|
||||
var sourceCalls = source.TransportCalls;
|
||||
var modelCalls = source.ModelCalls;
|
||||
var factory = provider.GetRequiredService<ITelemetryReplayFactory>();
|
||||
await using var player = factory.Create();
|
||||
try
|
||||
{
|
||||
await player.LoadAsync(fixture.CaptureId);
|
||||
Configure(player);
|
||||
player.SeekTime(TimeSpan.FromSeconds(4).Ticks);
|
||||
player.Previous();
|
||||
player.First();
|
||||
var preference = provider.GetRequiredService<DisplayUnitPreferenceService>();
|
||||
Assert.True(preference.TrySet(new DisplayUnitSelection(DisplayUnitSystem.Metric, SpeedDisplayMode.Road)));
|
||||
Assert.True(preference.TrySet(DisplayUnitSelection.Default));
|
||||
await player.PlayAsync();
|
||||
var wait = await fixture.Waiter.TakeAsync();
|
||||
var stop = player.StopAsync();
|
||||
wait.Release();
|
||||
await stop.WaitAsync(Deadline);
|
||||
Assert.Equal(sourceCalls, source.TransportCalls);
|
||||
Assert.Equal(modelCalls, source.ModelCalls);
|
||||
Assert.Equal(oldTrace, live.Trace.Entries.Count);
|
||||
Assert.Equal(oldStatus, live.DynamicsControl.Status);
|
||||
Assert.Equal(oldRecording, TelemetryArchiveCodec.Serialize(workspace.CurrentCapture!));
|
||||
Assert.NotEqual(workspace.CurrentCapture!.Header.CaptureId, player.Snapshot.Context!.CaptureId);
|
||||
Assert.Equal(0, fixture.Store.SaveCalls);
|
||||
Assert.Equal(fixture.Bytes, await File.ReadAllBytesAsync(fixture.ArchivePath));
|
||||
Assert.True((await live.ReadSignalsAsync(endpoint)).IsSuccess);
|
||||
Assert.Equal(sourceCalls + 1, source.TransportCalls);
|
||||
Assert.Equal(modelCalls, source.ModelCalls);
|
||||
Assert.Equal(oldRecording, TelemetryArchiveCodec.Serialize(workspace.CurrentCapture!));
|
||||
}
|
||||
finally
|
||||
{
|
||||
fixture.Waiter.ReleaseAll();
|
||||
await player.StopAsync();
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class CountingDynamicsFactory(IDynamicsDiagnosticTransportFactory inner) : IDynamicsDiagnosticTransportFactory
|
||||
{
|
||||
public int TransportCalls { get; private set; }
|
||||
public int ModelCalls { get; private set; }
|
||||
public DiagnosticProviderDescriptor Descriptor => inner.Descriptor;
|
||||
public IDiagnosticTransport OpenTransport(VehicleProfile profile, DiagnosticSessionIdentity identity) =>
|
||||
throw new InvalidOperationException("This counting source requires an explicit dynamics configuration.");
|
||||
public DynamicsSessionBinding OpenDynamicsTransport(VehicleProfile profile, DiagnosticSessionIdentity identity, DynamicsConfiguration configuration)
|
||||
{
|
||||
var binding = inner.OpenDynamicsTransport(profile, identity, configuration);
|
||||
return new(new CountingTransport(binding.Transport, () => TransportCalls++),
|
||||
new CountingControl(binding.Control, () => ModelCalls++));
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class CountingTransport(IDiagnosticTransport inner, Action count) : IDiagnosticTransport
|
||||
{
|
||||
public IReadOnlyList<DiagnosticEndpoint> ExpectedEndpoints => inner.ExpectedEndpoints;
|
||||
public ValueTask<TransportReply> SendAsync(ReadOnlyMemory<byte> request, CancellationToken cancellationToken)
|
||||
{
|
||||
count();
|
||||
return inner.SendAsync(request, cancellationToken);
|
||||
}
|
||||
public ValueTask DisposeAsync() => inner.DisposeAsync();
|
||||
}
|
||||
|
||||
private sealed class CountingControl(IDynamicsControl inner, Action count) : IDynamicsControl
|
||||
{
|
||||
public DynamicsRunStatus Status => inner.Status;
|
||||
public double PacingFactor => inner.PacingFactor;
|
||||
private Task<DynamicsRunStatus> Invoke(Func<Task<DynamicsRunStatus>> action) { count(); return action(); }
|
||||
public Task<DynamicsRunStatus> StartAsync(CancellationToken cancellationToken = default) => Invoke(() => inner.StartAsync(cancellationToken));
|
||||
public Task<DynamicsRunStatus> PauseAsync(CancellationToken cancellationToken = default) => Invoke(() => inner.PauseAsync(cancellationToken));
|
||||
public Task<DynamicsRunStatus> ResumeAsync(CancellationToken cancellationToken = default) => Invoke(() => inner.ResumeAsync(cancellationToken));
|
||||
public Task<DynamicsRunStatus> StopAsync(CancellationToken cancellationToken = default) => Invoke(() => inner.StopAsync(cancellationToken));
|
||||
public Task<DynamicsRunStatus> ResetAsync(CancellationToken cancellationToken = default) => Invoke(() => inner.ResetAsync(cancellationToken));
|
||||
public Task<DynamicsRunStatus> StepAsync(int stepCount = 1, CancellationToken cancellationToken = default) => Invoke(() => inner.StepAsync(stepCount, cancellationToken));
|
||||
public Task<DynamicsRunStatus> SetPacingFactorAsync(double factor, CancellationToken cancellationToken = default) => Invoke(() => inner.SetPacingFactorAsync(factor, cancellationToken));
|
||||
public Task<DynamicsRunStatus> RunScenarioAsync(CancellationToken cancellationToken = default) => Invoke(() => inner.RunScenarioAsync(cancellationToken));
|
||||
public ValueTask DisposeAsync() => inner.DisposeAsync();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,666 @@
|
|||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using System.Threading.Channels;
|
||||
using AutoForge.Application.Features.DisplayUnits;
|
||||
using AutoForge.Application.Features.Vehicles.Diagnostics;
|
||||
using AutoForge.Application.Features.Vehicles.Profiles;
|
||||
using AutoForge.Application.Features.Vehicles.Simulation;
|
||||
using AutoForge.Application.Features.Vehicles.Telemetry.LiveDashboard;
|
||||
using AutoForge.Application.Features.Vehicles.Telemetry.Recording;
|
||||
using AutoForge.Application.Features.Vehicles.Telemetry.Replay;
|
||||
using AutoForge.Core.ExecutionTargets;
|
||||
using AutoForge.Diagnostics;
|
||||
using AutoForge.Simulation;
|
||||
using AutoForge.UI;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace AutoForge.IntegrationTests;
|
||||
|
||||
public sealed partial class TelemetryReplayTests
|
||||
{
|
||||
private const string ProfileId = "autoforge.synthetic.test-truck";
|
||||
private const string ModuleA = "module.engine.primary";
|
||||
private const string ModuleB = "module.cabin.body";
|
||||
private const string SignalId = "recorded.measurement";
|
||||
private static readonly TimeSpan Deadline = TimeSpan.FromSeconds(10);
|
||||
|
||||
[Fact]
|
||||
public async Task OfflineLoad_PreindexesOnlyMetadataAndReconstructsTheExactFourRecordPrefix()
|
||||
{
|
||||
using var fixture = await ReplayFixture.CreateAsync();
|
||||
await using var player = fixture.CreatePlayer();
|
||||
await player.LoadAsync(fixture.CaptureId);
|
||||
var source = player.Snapshot.Archive!;
|
||||
var context = player.Snapshot.Context!;
|
||||
Assert.Equal(ExecutionTargetKind.RecordedReplay, context.Kind);
|
||||
Assert.Equal(fixture.CaptureId, context.CaptureId);
|
||||
Assert.Equal(ExecutionTargetKind.Simulation, source.Header.TargetKind);
|
||||
Assert.Equal(ReplayState.Stopped, player.Snapshot.State);
|
||||
Assert.Equal(0, player.Snapshot.AppliedCount);
|
||||
Assert.Equal(0, player.Snapshot.PositionTicks);
|
||||
Assert.Equal(4 * TimeSpan.TicksPerSecond, player.Snapshot.DurationTicks);
|
||||
Assert.Equal(2, player.Snapshot.AvailableSignals.Count);
|
||||
Configure(player);
|
||||
Assert.All(player.Snapshot.Values, value => Assert.Null(value.Signal));
|
||||
|
||||
player.SeekTime(TimeSpan.FromSeconds(1.5).Ticks);
|
||||
AssertPrefix(player, 1, 1.5, 850, DashboardReadingState.Good, null);
|
||||
player.SeekTime(TimeSpan.FromSeconds(2).Ticks);
|
||||
AssertPrefix(player, 3, 2, 1000, DashboardReadingState.Uncertain, 12.6);
|
||||
Assert.Equal(DashboardReadingState.OutOfRangeHigh, player.Snapshot.Values[0].RangeState);
|
||||
Assert.Equal(100, player.Snapshot.Values[0].BarPercent);
|
||||
player.SeekTime(TimeSpan.FromSeconds(4).Ticks);
|
||||
AssertPrefix(player, 4, 4, 850, DashboardReadingState.Stale, 12.6);
|
||||
var stale = player.Snapshot.Values[0];
|
||||
Assert.Equal(source.Observations[0].SignalSnapshot!.Signals[0].LogicalTimeTicks, stale.Signal!.LogicalTimeTicks);
|
||||
Assert.Equal(1, player.Snapshot.SampleContexts[stale.Definition.GaugeIdentifier].Sequence);
|
||||
Assert.Equal(TimeSpan.TicksPerSecond, player.Snapshot.SampleContexts[stale.Definition.GaugeIdentifier].CaptureElapsedTicks);
|
||||
Assert.Contains("Timeout", stale.Reason);
|
||||
Assert.Equal(ReplayState.Completed, player.Snapshot.State);
|
||||
Assert.Equal(850d / 900 * 100, player.Snapshot.Values[0].BarPercent);
|
||||
|
||||
player.Previous();
|
||||
AssertPrefix(player, 3, 2, 1000, DashboardReadingState.Uncertain, 12.6);
|
||||
player.SeekOrdinal(1);
|
||||
AssertPrefix(player, 1, 1, 850, DashboardReadingState.Good, null);
|
||||
Assert.DoesNotContain(player.Snapshot.Modules, status => status.ModuleIdentifier == ModuleB);
|
||||
player.First();
|
||||
Assert.Equal(0, player.Snapshot.AppliedCount);
|
||||
Assert.All(player.Snapshot.Values, value => Assert.Null(value.NumericValue));
|
||||
Assert.Empty(player.Snapshot.Modules);
|
||||
Assert.Equal(2, player.Snapshot.Definitions.Count);
|
||||
Assert.Same(context, player.Snapshot.Context);
|
||||
Assert.Equal(0, fixture.Store.SaveCalls);
|
||||
Assert.Equal(fixture.Bytes, await File.ReadAllBytesAsync(fixture.ArchivePath));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EqualAndZeroTimes_ManualNextIsOneButTimeSeekAndPlayApplyCompleteGroups()
|
||||
{
|
||||
using var fixture = await ReplayFixture.CreateAsync(allZero: true);
|
||||
await using var player = fixture.CreatePlayer();
|
||||
await player.LoadAsync(fixture.CaptureId);
|
||||
Configure(player);
|
||||
Assert.Equal(0, player.Snapshot.DurationTicks);
|
||||
player.Next();
|
||||
Assert.Equal(1, player.Snapshot.AppliedCount);
|
||||
Assert.Equal(ReplayState.Paused, player.Snapshot.State);
|
||||
player.Next();
|
||||
Assert.Equal(2, player.Snapshot.AppliedCount);
|
||||
player.SeekTime(0);
|
||||
Assert.Equal(4, player.Snapshot.AppliedCount);
|
||||
Assert.Equal(ReplayState.Completed, player.Snapshot.State);
|
||||
player.First();
|
||||
await player.PlayAsync();
|
||||
Assert.Equal(4, player.Snapshot.AppliedCount);
|
||||
Assert.Equal(ReplayState.Completed, player.Snapshot.State);
|
||||
Assert.Equal(0, fixture.Waiter.WaitCount);
|
||||
await player.StopAsync();
|
||||
Assert.Equal(0, player.Snapshot.AppliedCount);
|
||||
Assert.All(player.Snapshot.Values, value => Assert.Null(value.Signal));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EmptyAndNonSignalArchives_NeverFabricateMeasurementsOrUseUtcDuration()
|
||||
{
|
||||
using var fixture = await ReplayFixture.CreateAsync(empty: true);
|
||||
await using var player = fixture.CreatePlayer();
|
||||
await player.LoadAsync(fixture.CaptureId);
|
||||
Assert.Empty(player.Snapshot.AvailableSignals);
|
||||
Assert.Equal(0, player.Snapshot.DurationTicks);
|
||||
await player.PlayAsync();
|
||||
Assert.Equal(ReplayState.Completed, player.Snapshot.State);
|
||||
Assert.Equal(0, fixture.Waiter.WaitCount);
|
||||
player.SeekTime(0);
|
||||
Assert.Equal(ReplayState.Stopped, player.Snapshot.State);
|
||||
AssertRejected(player, () => player.Next(), ReplayFailure.NoRecords);
|
||||
AssertRejected(player, () => player.Previous(), ReplayFailure.NoRecords);
|
||||
await player.RestartAsync();
|
||||
Assert.Equal(ReplayState.Completed, player.Snapshot.State);
|
||||
|
||||
using var nonSignal = await ReplayFixture.CreateAsync(nonSignal: true);
|
||||
await using var other = nonSignal.CreatePlayer();
|
||||
await other.LoadAsync(nonSignal.CaptureId);
|
||||
other.Next();
|
||||
Assert.Equal(DiagnosticServices.ReadTroubleCodes, other.Snapshot.CurrentObservation!.Service);
|
||||
Assert.Empty(other.Snapshot.Values);
|
||||
Assert.Empty(other.Snapshot.Modules);
|
||||
Assert.Equal(1, other.Snapshot.AppliedCount);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0.25)]
|
||||
[InlineData(1)]
|
||||
[InlineData(1000)]
|
||||
public async Task ControlledPacing_ScalesCaptureIntervalsWithoutChangingRecordedResults(double rate)
|
||||
{
|
||||
using var fixture = await ReplayFixture.CreateAsync();
|
||||
await using var player = fixture.CreatePlayer();
|
||||
await player.LoadAsync(fixture.CaptureId);
|
||||
Configure(player);
|
||||
player.SetRate(rate);
|
||||
await player.PlayAsync();
|
||||
var firstWait = await fixture.Waiter.TakeAsync();
|
||||
try
|
||||
{
|
||||
Assert.Equal(TimeSpan.FromSeconds(1 / rate), firstWait.Interval);
|
||||
fixture.Clock.Advance(firstWait.Interval);
|
||||
firstWait.Release();
|
||||
var secondWait = await fixture.Waiter.TakeAsync();
|
||||
Assert.Equal(1, player.Snapshot.AppliedCount);
|
||||
Assert.Equal(TimeSpan.FromSeconds(1 / rate), secondWait.Interval);
|
||||
fixture.Clock.Advance(secondWait.Interval);
|
||||
secondWait.Release();
|
||||
var thirdWait = await fixture.Waiter.TakeAsync();
|
||||
AssertPrefix(player, 3, 2, 1000, DashboardReadingState.Uncertain, 12.6);
|
||||
Assert.Equal(TimeSpan.FromSeconds(2 / rate), thirdWait.Interval);
|
||||
fixture.Clock.Advance(thirdWait.Interval);
|
||||
thirdWait.Release();
|
||||
await WaitForStateAsync(player, ReplayState.Completed);
|
||||
AssertPrefix(player, 4, 4, 850, DashboardReadingState.Stale, 12.6);
|
||||
}
|
||||
finally
|
||||
{
|
||||
fixture.Waiter.ReleaseAll();
|
||||
await player.StopAsync();
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task MidGapPause_DrainsOneOwnerAndResumeWaitsOnlyTheRemainingInterval()
|
||||
{
|
||||
using var fixture = await ReplayFixture.CreateAsync();
|
||||
await using var player = fixture.CreatePlayer();
|
||||
await player.LoadAsync(fixture.CaptureId);
|
||||
Configure(player);
|
||||
player.SeekTime(TimeSpan.FromSeconds(1.5).Ticks);
|
||||
player.SetRate(2);
|
||||
await player.PlayAsync();
|
||||
var wait = await fixture.Waiter.TakeAsync();
|
||||
try
|
||||
{
|
||||
Assert.Equal(TimeSpan.FromSeconds(0.25), wait.Interval);
|
||||
await player.PlayAsync();
|
||||
Assert.Equal(1, fixture.Waiter.WaitCount);
|
||||
fixture.Clock.Advance(TimeSpan.FromSeconds(0.10));
|
||||
var pause = player.PauseAsync();
|
||||
Assert.False(pause.IsCompleted);
|
||||
Assert.True(player.Snapshot.IsDraining);
|
||||
Assert.Equal(TimeSpan.FromSeconds(1.7).Ticks, player.Snapshot.PositionTicks);
|
||||
Assert.Equal(1, player.Snapshot.AppliedCount);
|
||||
var state = player.Snapshot;
|
||||
AssertRejected(player, () => player.Next(), ReplayFailure.Busy);
|
||||
AssertRejected(player, () => player.SetRate(10), ReplayFailure.Busy);
|
||||
await Assert.ThrowsAsync<TelemetryReplayException>(() => player.PlayAsync());
|
||||
await Assert.ThrowsAsync<TelemetryReplayException>(() => player.LoadAsync(fixture.CaptureId));
|
||||
Assert.Equal(state.Context, player.Snapshot.Context);
|
||||
fixture.Clock.Advance(TimeSpan.FromSeconds(3));
|
||||
wait.Release();
|
||||
await pause.WaitAsync(Deadline);
|
||||
Assert.Equal(TimeSpan.FromSeconds(1.7).Ticks, player.Snapshot.PositionTicks);
|
||||
Assert.False(player.Snapshot.IsDraining);
|
||||
await player.PlayAsync();
|
||||
var resumed = await fixture.Waiter.TakeAsync();
|
||||
Assert.Equal(TimeSpan.FromSeconds(0.15), resumed.Interval);
|
||||
fixture.Clock.Advance(resumed.Interval);
|
||||
resumed.Release();
|
||||
var next = await fixture.Waiter.TakeAsync();
|
||||
AssertPrefix(player, 3, 2, 1000, DashboardReadingState.Uncertain, 12.6);
|
||||
var stop = player.StopAsync();
|
||||
Assert.Same(stop, player.StopAsync());
|
||||
Assert.False(stop.IsCompleted);
|
||||
AssertRejected(player, () => player.First(), ReplayFailure.Busy);
|
||||
next.Release();
|
||||
await stop.WaitAsync(Deadline);
|
||||
Assert.Equal(ReplayState.Stopped, player.Snapshot.State);
|
||||
Assert.All(player.Snapshot.Values, value => Assert.Null(value.Signal));
|
||||
}
|
||||
finally
|
||||
{
|
||||
fixture.Waiter.ReleaseAll();
|
||||
await player.StopAsync();
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task WaitFault_IsVisibleAndKeepsCommittedPrefixUntilExplicitRecovery()
|
||||
{
|
||||
using var fixture = await ReplayFixture.CreateAsync();
|
||||
await using var player = fixture.CreatePlayer();
|
||||
await player.LoadAsync(fixture.CaptureId);
|
||||
Configure(player);
|
||||
player.SeekOrdinal(1);
|
||||
await player.PlayAsync();
|
||||
var wait = await fixture.Waiter.TakeAsync();
|
||||
wait.Fail(new IOException("controlled replay wait failure"));
|
||||
await WaitForStateAsync(player, ReplayState.Faulted);
|
||||
Assert.Equal(1, player.Snapshot.AppliedCount);
|
||||
Assert.Equal(850, player.Snapshot.Values[0].NumericValue);
|
||||
Assert.Equal(DashboardReadingState.Good, player.Snapshot.Values[0].State);
|
||||
Assert.Contains("controlled replay wait failure", player.Snapshot.Error);
|
||||
await Assert.ThrowsAsync<TelemetryReplayException>(() => player.PlayAsync());
|
||||
AssertRejected(player, () => player.Next(), ReplayFailure.Faulted);
|
||||
AssertRejected(player, () => player.SeekTime(0), ReplayFailure.Faulted);
|
||||
AssertRejected(player, () => player.SeekOrdinal(0), ReplayFailure.Faulted);
|
||||
await Assert.ThrowsAsync<TelemetryReplayException>(() => player.RestartAsync());
|
||||
await player.StopAsync();
|
||||
Assert.Equal(ReplayState.Stopped, player.Snapshot.State);
|
||||
Assert.Equal(0, player.Snapshot.AppliedCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InvalidRequests_AreTypedVisibleAndAtomicIncludingClosedAndUnloadedPlayers()
|
||||
{
|
||||
using var fixture = await ReplayFixture.CreateAsync();
|
||||
await using var player = fixture.CreatePlayer();
|
||||
AssertRejected(player, () => player.Next(), ReplayFailure.NotLoaded);
|
||||
await player.LoadAsync(fixture.CaptureId);
|
||||
Configure(player);
|
||||
player.SeekOrdinal(1);
|
||||
foreach (var rate in new[] { double.NaN, double.PositiveInfinity, double.NegativeInfinity, 0.249, 1000.001 })
|
||||
{
|
||||
AssertRejected(player, () => player.SetRate(rate), ReplayFailure.InvalidRate);
|
||||
}
|
||||
AssertRejected(player, () => player.SeekTime(-1), ReplayFailure.InvalidPosition);
|
||||
AssertRejected(player, () => player.SeekTime(player.Snapshot.DurationTicks + 1), ReplayFailure.InvalidPosition);
|
||||
AssertRejected(player, () => player.SeekOrdinal(5), ReplayFailure.InvalidPosition);
|
||||
AssertRejected(player, () => player.SeekOrdinal(-1), ReplayFailure.InvalidPosition);
|
||||
var original = player.Snapshot.Definitions;
|
||||
var invalid = original[0] with { Unit = "RPM" };
|
||||
Assert.Throws<DashboardConfigurationException>(() => player.ReplaceDefinitions([invalid]));
|
||||
Assert.Equal(original, player.Snapshot.Definitions);
|
||||
Assert.Throws<DashboardConfigurationException>(() => player.ReplaceDefinitions(
|
||||
Enumerable.Range(0, 9).Select(index => original[0] with { GaugeIdentifier = $"g{index}" })));
|
||||
Assert.Equal(original, player.Snapshot.Definitions);
|
||||
foreach (var definition in new[]
|
||||
{
|
||||
original[0] with { Label = " " },
|
||||
original[0] with { Kind = (DashboardGaugeKind)99 },
|
||||
original[0] with { Minimum = double.NaN },
|
||||
original[0] with { Minimum = -double.MaxValue, Maximum = double.MaxValue },
|
||||
original[0] with { Minimum = 1, Maximum = 1 },
|
||||
original[0] with { DecimalPrecision = 4 }
|
||||
})
|
||||
{
|
||||
var before = player.Snapshot;
|
||||
Assert.Throws<DashboardConfigurationException>(() => player.ReplaceDefinitions([definition]));
|
||||
AssertUnchanged(before, player.Snapshot);
|
||||
}
|
||||
Assert.Throws<DashboardConfigurationException>(() => player.ReplaceDefinitions([original[0], original[0] with { GaugeIdentifier = "A" }]));
|
||||
player.ReplaceDefinitions(Enumerable.Range(0, 8).Select(index => original[0] with { GaugeIdentifier = $"g{index}" }));
|
||||
Assert.Equal(8, player.Snapshot.Values.Count);
|
||||
player.ReplaceDefinitions([]);
|
||||
Assert.Empty(player.Snapshot.Values);
|
||||
Assert.Equal(1, player.Snapshot.AppliedCount);
|
||||
await player.DisposeAsync();
|
||||
AssertRejected(player, () => player.Next(), ReplayFailure.Closed);
|
||||
Assert.Equal(0, fixture.Store.SaveCalls);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(TelemetryCaptureState.Incomplete)]
|
||||
[InlineData(TelemetryCaptureState.Error)]
|
||||
public async Task PartialAcknowledgement_IsPerLoadAndEndNeverRewritesOriginalCompletion(TelemetryCaptureState sourceState)
|
||||
{
|
||||
using var fixture = await ReplayFixture.CreateAsync(partial: sourceState);
|
||||
await using var player = fixture.CreatePlayer();
|
||||
await player.LoadAsync(fixture.CaptureId);
|
||||
AssertRejected(player, () => player.Next(), ReplayFailure.AcknowledgementRequired);
|
||||
AssertRejected(player, () => player.SeekTime(0), ReplayFailure.AcknowledgementRequired);
|
||||
AssertRejected(player, () => player.SeekOrdinal(0), ReplayFailure.AcknowledgementRequired);
|
||||
await Assert.ThrowsAsync<TelemetryReplayException>(() => player.PlayAsync());
|
||||
player.First();
|
||||
await player.StopAsync();
|
||||
player.AcknowledgePartial();
|
||||
player.SeekOrdinal(4);
|
||||
Assert.Equal(sourceState, player.Snapshot.Archive!.Completion!.State);
|
||||
Assert.Equal(ReplayState.Completed, player.Snapshot.State);
|
||||
await player.StopAsync();
|
||||
Assert.True(player.Snapshot.PartialAcknowledged);
|
||||
player.SetRate(0.25);
|
||||
var identity = player.Snapshot.Context;
|
||||
await player.LoadAsync(fixture.CaptureId);
|
||||
Assert.NotEqual(identity, player.Snapshot.Context);
|
||||
Assert.False(player.Snapshot.PartialAcknowledged);
|
||||
Assert.Equal(0.25, player.Snapshot.Rate);
|
||||
Assert.Empty(player.Snapshot.Definitions);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task FailedCancelledAndLateLoads_PreserveValidatedContextAndCloseDrainsWithoutStalePublication()
|
||||
{
|
||||
using var fixture = await ReplayFixture.CreateAsync();
|
||||
await using var player = fixture.CreatePlayer();
|
||||
await player.LoadAsync(fixture.CaptureId);
|
||||
Configure(player);
|
||||
player.SeekOrdinal(1);
|
||||
var before = player.Snapshot;
|
||||
await Assert.ThrowsAsync<TelemetryArchiveException>(() => player.LoadAsync(new string('f', 32)));
|
||||
AssertUnchanged(before, player.Snapshot);
|
||||
Assert.NotNull(player.Snapshot.Error);
|
||||
using var cancellation = new CancellationTokenSource();
|
||||
fixture.Store.HoldLoads = true;
|
||||
var load = player.LoadAsync(fixture.CaptureId, cancellation.Token);
|
||||
await fixture.Store.LoadEntered.Task.WaitAsync(Deadline);
|
||||
AssertRejected(player, () => player.Next(), ReplayFailure.Busy);
|
||||
cancellation.Cancel();
|
||||
fixture.Store.ReleaseLoad();
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => load);
|
||||
AssertUnchanged(before, player.Snapshot);
|
||||
|
||||
fixture.Store.ResetLoadBarrier();
|
||||
var late = player.LoadAsync(fixture.CaptureId);
|
||||
await fixture.Store.LoadEntered.Task.WaitAsync(Deadline);
|
||||
var close = player.DisposeAsync().AsTask();
|
||||
Assert.Same(close, player.DisposeAsync().AsTask());
|
||||
Assert.False(close.IsCompleted);
|
||||
fixture.Store.ReleaseLoad();
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => late);
|
||||
await close.WaitAsync(Deadline);
|
||||
Assert.Equal(ReplayState.Closed, player.Snapshot.State);
|
||||
Assert.Same(before.Context, player.Snapshot.Context);
|
||||
Assert.Same(before.Archive, player.Snapshot.Archive);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CloseWithDelayedOldWake_NeverPublishesIntoClosedOrFreshFactorySession()
|
||||
{
|
||||
using var fixture = await ReplayFixture.CreateAsync();
|
||||
await using var player = fixture.CreatePlayer();
|
||||
await player.LoadAsync(fixture.CaptureId);
|
||||
await player.PlayAsync();
|
||||
var wait = await fixture.Waiter.TakeAsync();
|
||||
try
|
||||
{
|
||||
var close = player.DisposeAsync().AsTask();
|
||||
Assert.False(close.IsCompleted);
|
||||
fixture.Clock.Advance(TimeSpan.FromSeconds(20));
|
||||
await using var fresh = fixture.CreatePlayer();
|
||||
await fresh.LoadAsync(fixture.CaptureId);
|
||||
wait.Release();
|
||||
await close.WaitAsync(Deadline);
|
||||
Assert.Equal(ReplayState.Closed, player.Snapshot.State);
|
||||
Assert.Equal(0, player.Snapshot.AppliedCount);
|
||||
Assert.Equal(ReplayState.Stopped, fresh.Snapshot.State);
|
||||
Assert.Equal(0, fresh.Snapshot.AppliedCount);
|
||||
Assert.NotEqual(player.Snapshot.Context, fresh.Snapshot.Context);
|
||||
}
|
||||
finally
|
||||
{
|
||||
fixture.Waiter.ReleaseAll();
|
||||
}
|
||||
}
|
||||
|
||||
private static void Configure(TelemetryReplaySession player) => player.ReplaceDefinitions(
|
||||
[
|
||||
new("a", "Recorded A", DashboardGaugeKind.HorizontalBar, ModuleA, SignalId, "rpm", 0, 900, 0),
|
||||
new("b", "Recorded B", DashboardGaugeKind.Numeric, ModuleB, SignalId, "V", 0, 15, 1)
|
||||
]);
|
||||
|
||||
private static void AssertPrefix(TelemetryReplaySession player, int count, double seconds,
|
||||
double a, DashboardReadingState state, double? b)
|
||||
{
|
||||
var snapshot = player.Snapshot;
|
||||
Assert.Equal(count, snapshot.AppliedCount);
|
||||
Assert.Equal(TimeSpan.FromSeconds(seconds).Ticks, snapshot.PositionTicks);
|
||||
Assert.Equal(a, snapshot.Values[0].NumericValue);
|
||||
Assert.Equal(state, snapshot.Values[0].State);
|
||||
Assert.Equal(b, snapshot.Values[1].NumericValue);
|
||||
if (b is null)
|
||||
{
|
||||
Assert.Null(snapshot.Values[1].Signal);
|
||||
}
|
||||
}
|
||||
|
||||
private static void AssertRejected(TelemetryReplaySession player, Action command, ReplayFailure failure)
|
||||
{
|
||||
var previous = player.Snapshot;
|
||||
var exception = Assert.Throws<TelemetryReplayException>(command);
|
||||
Assert.Equal(failure, exception.Failure);
|
||||
AssertUnchanged(previous, player.Snapshot);
|
||||
Assert.Equal(exception.Message, player.Snapshot.Error);
|
||||
}
|
||||
|
||||
private static void AssertUnchanged(TelemetryReplaySnapshot previous, TelemetryReplaySnapshot current)
|
||||
{
|
||||
Assert.Same(previous.Context, current.Context);
|
||||
Assert.Same(previous.Archive, current.Archive);
|
||||
Assert.Equal(previous.State, current.State);
|
||||
Assert.Equal(previous.PositionTicks, current.PositionTicks);
|
||||
Assert.Equal(previous.AppliedCount, current.AppliedCount);
|
||||
Assert.Equal(previous.Rate, current.Rate);
|
||||
Assert.Equal(previous.Definitions, current.Definitions);
|
||||
Assert.Equal(previous.Values, current.Values);
|
||||
Assert.Equal(previous.IsDraining, current.IsDraining);
|
||||
}
|
||||
|
||||
private static async Task WaitForStateAsync(TelemetryReplaySession player, ReplayState state)
|
||||
{
|
||||
var completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
void Check()
|
||||
{
|
||||
if (player.Snapshot.State == state && !player.Snapshot.IsDraining)
|
||||
{
|
||||
completion.TrySetResult();
|
||||
}
|
||||
}
|
||||
player.Changed += Check;
|
||||
try
|
||||
{
|
||||
Check();
|
||||
await completion.Task.WaitAsync(Deadline);
|
||||
}
|
||||
finally
|
||||
{
|
||||
player.Changed -= Check;
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class ManualReplayClock : TimeProvider
|
||||
{
|
||||
private long _ticks;
|
||||
public Exception? Failure { get; set; }
|
||||
public override long TimestampFrequency => TimeSpan.TicksPerSecond;
|
||||
public override long GetTimestamp() => Failure is { } failure ? throw failure : Interlocked.Read(ref _ticks);
|
||||
public override DateTimeOffset GetUtcNow() => DateTimeOffset.UnixEpoch.AddTicks(GetTimestamp());
|
||||
public void Advance(TimeSpan amount) => Interlocked.Add(ref _ticks, amount.Ticks);
|
||||
}
|
||||
|
||||
private sealed class ControlledReplayWaiter : IReplayWaiter
|
||||
{
|
||||
private readonly Channel<WaitRequest> _requests = Channel.CreateUnbounded<WaitRequest>();
|
||||
private readonly List<WaitRequest> _all = [];
|
||||
private bool _releasedAll;
|
||||
public int WaitCount { get; private set; }
|
||||
public async Task WaitAsync(TimeSpan interval, CancellationToken cancellationToken)
|
||||
{
|
||||
var request = new WaitRequest(interval, cancellationToken);
|
||||
lock (_all)
|
||||
{
|
||||
_all.Add(request);
|
||||
WaitCount++;
|
||||
if (_releasedAll) request.Release();
|
||||
}
|
||||
using var registration = cancellationToken.Register(() => request.CancellationRequested.TrySetResult());
|
||||
_requests.Writer.TryWrite(request);
|
||||
await request.Completion.Task;
|
||||
}
|
||||
public async Task<WaitRequest> TakeAsync() => await _requests.Reader.ReadAsync().AsTask().WaitAsync(Deadline);
|
||||
public void ReleaseAll()
|
||||
{
|
||||
lock (_all)
|
||||
{
|
||||
_releasedAll = true;
|
||||
foreach (var request in _all)
|
||||
{
|
||||
request.Release();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private sealed record WaitRequest(TimeSpan Interval, CancellationToken Cancellation)
|
||||
{
|
||||
public TaskCompletionSource Completion { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
public TaskCompletionSource CancellationRequested { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
public void Release() => Completion.TrySetResult();
|
||||
public void Fail(Exception exception) => Completion.TrySetException(exception);
|
||||
}
|
||||
|
||||
private sealed class ReadOnlySpyStore(ITelemetryArchiveStore inner) : ITelemetryArchiveStore
|
||||
{
|
||||
private TaskCompletionSource _release = NewBarrier();
|
||||
public TaskCompletionSource LoadEntered { get; private set; } = NewBarrier();
|
||||
public bool HoldLoads { get; set; }
|
||||
public int SaveCalls { get; private set; }
|
||||
public Task SaveAsync(TelemetryCaptureSnapshot capture, CancellationToken cancellationToken = default)
|
||||
{
|
||||
SaveCalls++;
|
||||
throw new InvalidOperationException("Replay attempted an archive write.");
|
||||
}
|
||||
public Task<IReadOnlyList<TelemetrySavedCapture>> ListAsync(CancellationToken cancellationToken = default) =>
|
||||
inner.ListAsync(cancellationToken);
|
||||
public async Task<TelemetryCaptureSnapshot> LoadAsync(string captureId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (HoldLoads)
|
||||
{
|
||||
LoadEntered.TrySetResult();
|
||||
await _release.Task;
|
||||
}
|
||||
return await inner.LoadAsync(captureId, CancellationToken.None);
|
||||
}
|
||||
public void ReleaseLoad() => _release.TrySetResult();
|
||||
public void ResetLoadBarrier()
|
||||
{
|
||||
_release = NewBarrier();
|
||||
LoadEntered = NewBarrier();
|
||||
}
|
||||
private static TaskCompletionSource NewBarrier() => new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
}
|
||||
|
||||
private sealed class ReplayFixture : IDisposable
|
||||
{
|
||||
public string DirectoryPath { get; } = Path.Combine(Path.GetTempPath(), $"autoforge-step08-{Guid.NewGuid():N}");
|
||||
public string CaptureId { get; private set; } = string.Empty;
|
||||
public string ArchivePath => Path.Combine(DirectoryPath, $"{CaptureId}.json");
|
||||
public byte[] Bytes { get; private set; } = [];
|
||||
public ManualReplayClock Clock { get; } = new();
|
||||
public ControlledReplayWaiter Waiter { get; } = new();
|
||||
public ReadOnlySpyStore Store { get; private set; } = null!;
|
||||
public TelemetryReplaySession CreatePlayer() => new(Store, Clock, Waiter);
|
||||
|
||||
public static async Task<ReplayFixture> CreateAsync(bool allZero = false, bool empty = false,
|
||||
bool nonSignal = false, TelemetryCaptureState? partial = null, bool dynamic = false, bool resetModel = false)
|
||||
{
|
||||
var fixture = new ReplayFixture();
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(fixture.DirectoryPath);
|
||||
var services = new ServiceCollection();
|
||||
services.AddAutoForgeVehicleProfiles();
|
||||
var call = 0;
|
||||
var original = new SimulatedDiagnosticTransportFactory(SyntheticDiagnosticExamples.CreateDefinitions());
|
||||
var transport = new RewritingDiagnosticTransportFactory(original, async (inner, request, bytes, token) =>
|
||||
{
|
||||
if (request.Service != DiagnosticServices.ReadSignals)
|
||||
{
|
||||
return await inner.SendAsync(bytes, token);
|
||||
}
|
||||
call++;
|
||||
if (call == 4)
|
||||
{
|
||||
return new TransportReply(TransportOutcome.Timeout, ReadOnlyMemory<byte>.Empty, 1, "Timeout fixture");
|
||||
}
|
||||
var reply = await inner.SendAsync(bytes, token);
|
||||
var node = JsonNode.Parse(reply.Payload.Span)!.AsObject();
|
||||
node["data"]!["signals"] = new JsonArray(new JsonObject
|
||||
{
|
||||
["signalIdentifier"] = SignalId,
|
||||
["value"] = call == 2 ? JsonValue.Create(12.6) : JsonValue.Create(call == 3 ? 1000 : 850),
|
||||
["unit"] = call == 2 ? "V" : "rpm",
|
||||
["quality"] = call == 3 ? "Uncertain" : "Good"
|
||||
});
|
||||
return new TransportReply(TransportOutcome.Response, Encoding.UTF8.GetBytes(node.ToJsonString()), reply.ElapsedTicks);
|
||||
});
|
||||
services.AddAutoForgeDiagnostics([transport, new DynamicsDiagnosticTransportFactory(SyntheticDiagnosticExamples.CreateDefinitions())]);
|
||||
services.AddAutoForgeDynamicsConfigurations();
|
||||
services.AddAutoForgeTelemetryRecording(fixture.DirectoryPath);
|
||||
services.AddSingleton<TimeProvider>(fixture.Clock);
|
||||
services.AddAutoForgeTelemetryRecordingFallback();
|
||||
using (var provider = services.BuildServiceProvider())
|
||||
{
|
||||
provider.GetRequiredService<IVehicleProfileService>().Import(
|
||||
File.ReadAllText(Path.Combine(AppContext.BaseDirectory, "Fixtures", "synthetic-truck-baseline.json")));
|
||||
var sessionService = provider.GetRequiredService<IDiagnosticSessionService>();
|
||||
var session = dynamic
|
||||
? await sessionService.OpenDynamicsAsync(ProfileId, 1, DynamicsDiagnosticTransportFactory.ProviderIdentifier,
|
||||
ExecutionTargetKind.Simulation, provider.GetRequiredService<IDynamicsConfigurationService>().CreateExample(ProfileId, 1))
|
||||
: await sessionService.OpenAsync(ProfileId, 1, original.Descriptor.Target.ProviderIdentifier, ExecutionTargetKind.Simulation);
|
||||
await using (session)
|
||||
{
|
||||
if (resetModel) await session.DynamicsControl!.StepAsync(3);
|
||||
var recording = provider.GetRequiredService<TelemetryRecordingWorkspace>();
|
||||
recording.Start(session);
|
||||
if (!empty)
|
||||
{
|
||||
var a = session.ExpectedEndpoints.Single(endpoint => endpoint.ModuleIdentifier == ModuleA);
|
||||
var b = session.ExpectedEndpoints.Single(endpoint =>
|
||||
endpoint.ModuleIdentifier == (dynamic ? "module.transmission.primary" : ModuleB));
|
||||
if (nonSignal)
|
||||
{
|
||||
fixture.Clock.Advance(TimeSpan.FromSeconds(1));
|
||||
Assert.True((await session.ReadTroubleCodesAsync(a)).IsSuccess);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (!allZero) fixture.Clock.Advance(TimeSpan.FromSeconds(1));
|
||||
Assert.True((await session.ReadSignalsAsync(a)).IsSuccess);
|
||||
if (resetModel) await session.DynamicsControl!.ResetAsync();
|
||||
if (!allZero) fixture.Clock.Advance(TimeSpan.FromSeconds(1));
|
||||
Assert.True((await session.ReadSignalsAsync(b)).IsSuccess);
|
||||
Assert.True((await session.ReadSignalsAsync(a)).IsSuccess);
|
||||
if (!allZero) fixture.Clock.Advance(TimeSpan.FromSeconds(2));
|
||||
var last = await session.ReadSignalsAsync(a);
|
||||
Assert.Equal(dynamic ? DiagnosticOutcome.PositiveResponse : DiagnosticOutcome.Timeout, last.Outcome);
|
||||
}
|
||||
}
|
||||
recording.Stop();
|
||||
var capture = recording.CurrentCapture!;
|
||||
if (partial is { } state)
|
||||
{
|
||||
capture = new TelemetryCaptureSnapshot(capture.Header, capture.Observations,
|
||||
capture.Completion! with
|
||||
{
|
||||
State = state,
|
||||
StopReason = state == TelemetryCaptureState.Incomplete
|
||||
? TelemetryCaptureStopReason.LimitExceeded : TelemetryCaptureStopReason.ObservationFailure,
|
||||
Error = state == TelemetryCaptureState.Error ? "Recorded source error" : null
|
||||
});
|
||||
}
|
||||
fixture.CaptureId = capture.Header.CaptureId;
|
||||
await provider.GetRequiredService<ITelemetryArchiveStore>().SaveAsync(capture);
|
||||
}
|
||||
}
|
||||
fixture.Bytes = await File.ReadAllBytesAsync(fixture.ArchivePath);
|
||||
fixture.Store = new ReadOnlySpyStore(new FileTelemetryArchiveStore(fixture.DirectoryPath));
|
||||
return fixture;
|
||||
}
|
||||
catch
|
||||
{
|
||||
fixture.Dispose();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Waiter.ReleaseAll();
|
||||
Store?.ReleaseLoad();
|
||||
if (Directory.Exists(DirectoryPath))
|
||||
{
|
||||
Directory.Delete(DirectoryPath, recursive: true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue