Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9e7dff85c3
|
No files matched your search
@@ -76,6 +76,20 @@ numeric core and does not move; the heading is the full version — corrected 20
|
||||
values a second — and showed that one refresh of the sensor library takes 14 ms of processor time, so the reader
|
||||
refreshes it every five seconds, where NVIDIA's own figures (0.4 ms) stay at one a second.
|
||||
|
||||
- **The ledger can hold Advanced metrics — and holds none yet.** Schema 23 adds two tables: one for the facts of
|
||||
the PC, stored once per distinct set, and one for what a session recorded with the option on knows — its own
|
||||
facts, which sources answered and why the others did not, and the statistics of its extra series. Nothing is
|
||||
added to the session row itself, so what the JSON export and a bug bundle carry does not grow. The extra series
|
||||
are stored beside the others under names of their own, with a real "no reading" for a second in which a sensor
|
||||
was not read. One hour of them is about 0.2 MB. **A session recorded with the option off stores nothing of this**,
|
||||
and the option does not exist yet. *A 0.1.0-beta.38 cannot open a ledger a later build has migrated.*
|
||||
|
||||
### Changed
|
||||
|
||||
- **A crash file from a newer build no longer loses its tail in an older one.** The file a session writes as it goes
|
||||
(so that a crash keeps what was recorded) is made of chunks; a reader that met a chunk of a kind it did not know
|
||||
stopped there. It now passes over a whole chunk it does not know and reads on.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **A sentence in the documents that kept a function from being called.** `docs/18_GPU_VENDOR_APIS.md` said the
|
||||
|
||||
@@ -112,7 +112,9 @@ src/
|
||||
# (one reader for the Agent, on its own thread, only while held - D107) over
|
||||
# NvapiAdvancedReader (the bridge's ABI 3) and LhmAdvancedReader (LhmGroups:
|
||||
# the card; as administrator with PawnIO the processor, memory and board -
|
||||
# never storage, D103). No Agent code composes it yet.
|
||||
# never storage, D103). No Agent code composes it yet. Recording/
|
||||
# AdvancedSessionBuilder stores what a session's samples carried (schema 0023:
|
||||
# machine_profiles + session_advanced, adv.* series with NaN for a gap, D102).
|
||||
FrameLedger.Infrastructure/ # SQLite, shm reader, vendor APIs, injector interop, parsers,
|
||||
# and Capture/ (PR-C): ShmRingAttacher/ShmCaptureSink over the
|
||||
# reader, HeldProcessLivenessSource, TargetResolver (path only,
|
||||
|
||||
+48
-1
@@ -2,7 +2,7 @@
|
||||
|
||||
`%LOCALAPPDATA%\FrameLedger\ledger.db`. Pragmas: `journal_mode=WAL`, `synchronous=NORMAL`, `foreign_keys=ON`, `busy_timeout=5000`. `Microsoft.Data.Sqlite` + Dapper; all writes in explicit transactions.
|
||||
|
||||
**Writer ownership:** Agent writes `sessions`, `session_segments`, `frame_blobs`, `sensor_blobs`, `hardware_snapshots`, the hook-state columns on `games`, **and since P4 PR-1 (2026-09-14) the *detected* columns on `games`** — `engine`, `engine_version`, `platform` under the per-field provenance rule (`05_DETECTION` §Caching: a `user` field is never touched), `capability_flags` whole, and the cache key `detection_rules_version` / `detection_exe_size_bytes` / `detection_exe_mtime_ms`, and since schema 0011 (2026-09-25) the executable's own facts `exe_machine` / `exe_file_version` / `exe_product_version` / `library_versions`, written whole like the flags — through `IGameRepository.ApplyDetectionAsync` only. The UI and the Agent were both already writers of `games`; this adds columns to the Agent's half, not a third writer (HANDOFF §P4). **And since P4 PR-4 the UI's library import writes `platform`, `store_id` and `game_version` through `ApplyStoreMetadataAsync`** — the same per-field provenance rule, badged `detected` (a store's record is not the user's typing), on columns the UI already owned. **And since 2026-09-23 the Agent's relocator merges two entries for one executable under two drive letters** (`IGameMerge`, HANDOFF D26, `19_SAFETY` §A moved drive is the same executable): in one transaction it re-parents the dropped entry's `sessions` to the survivor (before the delete — `sessions.game_id` cascades), carries a block or a crash auto-disable still in force to the survivor (`hook_enabled` only ever to 0; `hook_blocked_reason` is copied, never originated or cleared), adds the crash counts, deletes the dropped `games` row, and then moves the survivor to the file's path (after the delete — `exe_path` is UNIQUE). It was the one Agent write that deletes a `games` row until beta.19; it never touches a consent column. **And since beta.19 (2026-10-12, D55) the Agent removes an entry whose game is no longer installed** (`IGamePrune`, `SqliteGamePrune`, asked by the detection sweep through `UninstalledEntryPrune`): one `DELETE` that holds every stored condition in the same statement — the same row at the same path, `removed_at` NULL, no session stored (`NOT EXISTS` on `sessions` — nothing cascades), no `hook_blocked_reason`, `hook_prescan_state` not `blocked`, no `ac_exception_at` and no `ac_exception_trial_failed_at` — behind `retention.remove_uninstalled_games`; a block, a grant and D38's mark are never removed with their entry (`19_SAFETY` §What a finding does to the game, *What clears it*). **And since 2026-09-23 the UI writes `record_sessions`** (schema 0009, FR-1.6): the entry's recording switch, which the Agent only reads — off, the watcher does not watch for the program. The script's one data change switches it off for entries an old import made for Steam's own tools (`SteamLibrarySource.KnownTools`, the ids as of the script); a twin merge keeps it off when either twin had it off. **And since 2026-09-25 the Agent's pre-scan of the library (`19_SAFETY` §What a finding does to the game) writes the hook-state columns of every entry, not only of those the user asked to hook** — `hook_prescan_state`, and on a finding `hook_enabled = 0` and `hook_blocked_reason` — and its own key, `hook_prescan_rules_version` / `hook_prescan_exe_size_bytes` / `hook_prescan_exe_mtime_ms` (schema 0010), through `IGameConsentStore.RecordPreScanAsync` only: columns that were already the Agent's, never over a block, never a new row. **And since 2026-09-26 (schema 0014, D33) the Agent writes the user-mode exception's columns** — `ac_exception_*` on `games` through `IGameConsentStore` only (eligibility from the sweep, a grant from the `SetAntiCheatException` command, every end), and `sessions.ac_exception_family` with the session — the grant only after the user accepted its disclosure in the UI, which asks and never writes. **And since 2026-10-03 (beta.11, D40) the Agent deletes sessions on request** — every session of one game or of every game, `DeleteSessions` over the pipe, through `ISessionRepository.DeleteSessionsAsync` in one transaction (segments, blobs and annotations cascade), never while one is being recorded; the UI asks and never deletes a session row itself *(for Delete all sessions; FR-1.4's removal is the App's own cascade, above — corrected 2026-10-04)*. **Maintenance (P4 PR-7) adds no writer:** the retention sweep on demand is the Agent's, asked over the pipe; the UI's `VACUUM` rewrites pages with the same contents and changes no row (§Retention built note). UI writes `games` (user-editable fields — since P3 PR-3 that is the FR-1.3 metadata, the `*_default` tri-states, and `removed_at`; ~~never a `hook_*` column~~ **and two downgrades** *(corrected 2026-10-04)*: *Change executable* (2026-09-21, `GameLibrary.ChangeExecutableAsync`) turns hooking off, clears the consent and pre-scan columns and ends an exception grant — it never writes a block or a grant — and *Remove game ▸ DeLine truncated
|
||||
**Writer ownership:** Agent writes `sessions`, `session_segments`, `frame_blobs`, `sensor_blobs`, `hardware_snapshots`, *(since schema 0023, 2026-11-11)* `machine_profiles` and `session_advanced`, the hook-state columns on `games`, **and since P4 PR-1 (2026-09-14) the *detected* columns on `games`** — `engine`, `engine_version`, `platform` under the per-field provenance rule (`05_DETECTION` §Caching: a `user` field is never touched), `capability_flags` whole, and the cache key `detection_rules_version` / `detection_exe_size_bytes` / `detection_exe_mtime_ms`, and since schema 0011 (2026-09-25) the executable's own facts `exe_machine` / `exe_file_version` / `exe_product_version` / `library_versions`, written whole like the flags — through `IGameRepository.ApplyDetectionAsync` only. The UI and the Agent were both already writers of `games`; this adds columns to the Agent's half, not a third writer (HANDOFF §P4). **And since P4 PR-4 the UI's library import writes `platform`, `store_id` and `game_version` through `ApplyStoreMetadataAsync`** — the same per-field provenance rule, badged `detected` (a store's record is not the user's typing), on columns the UI already owned. **And since 2026-09-23 the Agent's relocator merges two entries for one executable under two drive letters** (`IGameMerge`, HANDOFF D26, `19_SAFETY` §A moved drive is the same executable): in one transaction it re-parents the dropped entry's `sessions` to the survivor (before the delete — `sessions.game_id` cascades), carries a block or a crash auto-disable still in force to the survivor (`hook_enabled` only ever to 0; `hook_blocked_reason` is copied, never originated or cleared), adds the crash counts, deletes the dropped `games` row, and then moves the survivor to the file's path (after the delete — `exe_path` is UNIQUE). It was the one Agent write that deletes a `games` row until beta.19; it never touches a consent column. **And since beta.19 (2026-10-12, D55) the Agent removes an entry whose game is no longer installed** (`IGamePrune`, `SqliteGamePrune`, asked by the detection sweep through `UninstalledEntryPrune`): one `DELETE` that holds every stored condition in the same statement — the same row at the same path, `removed_at` NULL, no session stored (`NOT EXISTS` on `sessions` — nothing cascades), no `hook_blocked_reason`, `hook_prescan_state` not `blocked`, no `ac_exception_at` and no `ac_exception_trial_failed_at` — behind `retention.remove_uninstalled_games`; a block, a grant and D38's mark are never removed with their entry (`19_SAFETY` §What a finding does to the game, *What clears it*). **And since 2026-09-23 the UI writes `record_sessions`** (schema 0009, FR-1.6): the entry's recording switch, which the Agent only reads — off, the watcher does not watch for the program. The script's one data change switches it off for entries an old import made for Steam's own tools (`SteamLibrarySource.KnownTools`, the ids as of the script); a twin merge keeps it off when either twin had it off. **And since 2026-09-25 the Agent's pre-scan of the library (`19_SAFETY` §What a finding does to the game) writes the hook-state columns of every entry, not only of those the user asked to hook** — `hook_prescan_state`, and on a finding `hook_enabled = 0` and `hook_blocked_reason` — and its own key, `hook_prescan_rules_version` / `hook_prescan_exe_size_bytes` / `hook_prescan_exe_mtime_ms` (schema 0010), through `IGameConsentStore.RecordPreScanAsync` only: columns that were already the Agent's, never over a block, never a new row. **And since 2026-09-26 (schema 0014, D33) the Agent writes the user-mode exception's columns** — `ac_exception_*` on `games` through `IGameConsentStore` only (eligibility from the sweep, a grant from the `SetAntiCheatException` command, every end), and `sessions.ac_exception_family` with the session — the grant only after the user accepted its disclosure in the UI, which asks and never writes. **And since 2026-10-03 (beta.11, D40) the Agent deletes sessions on request** — every session of one game or of every game, `DeleteSessions` over the pipe, through `ISessionRepository.DeleteSessionsAsync` in one transaction (segments, blobs and annotations cascade), never while one is being recorded; the UI asks and never deletes a session row itself *(for Delete all sessions; FR-1.4's removal is the App's own cascade, above — corrected 2026-10-04)*. **Maintenance (P4 PR-7) adds no writer:** the retention sweep on demand is the Agent's, asked over the pipe; the UI's `VACUUM` rewrites pages with the same contents and changes no row (§Retention built note). UI writes `games` (user-editable fields — since P3 PR-3 that is the FR-1.3 metadata, the `*_default` tri-states, and `removed_at`; ~~never a `hook_*` column~~ **and two downgrades** *(corrected 2026-10-04)*: *Change executable* (2026-09-21, `GameLibrary.ChangeExecutableAsync`) turns hooking off, clears the consent and pre-scan columns and ends an excepLine truncated
|
||||
|
||||
## Schema (v2 — hook architecture)
|
||||
|
||||
@@ -399,6 +399,9 @@ CREATE TABLE sensor_blobs (
|
||||
-- beta.14 (D49) also gpu_core_clock|gpu_mem_clock (MHz), gpu_fan (RPM), gpu_mem_temp (°C)
|
||||
-- and gpu_power_limit|gpu_thermal_limit (100 or 0 per tick, NVIDIA only) — a series name
|
||||
-- needs no migration
|
||||
-- since schema 0023 (2026-11-11, D102) also the ADVANCED series, every one under a name
|
||||
-- that starts with `adv.` (Application.Advanced.AdvancedMetricCatalog): NaN, not -1,
|
||||
-- for a tick with no reading, and read by FindAdvancedSensorsAsync only
|
||||
-- cpu_load / ram_mb / cpu_temp and sessions.avg_cpu_load, avg_cpu_temp, max_cpu_temp,
|
||||
-- avg_ram_mb were in schema 0001 with NO producer until 2026-09-21 (Telemetry.SystemTelemetrySource
|
||||
-- on the poller's tick). Rows before that date hold NULL, which is what they measured; no migration.
|
||||
@@ -491,6 +494,18 @@ Because Tier-1 and Tier-2 sessions carry different fields, every query that comp
|
||||
> axis (a gap's interval is stored as 0), so a series still drifts ahead of its sensors past each gap.
|
||||
> Sensor series are aligned to `t_ms` (milliseconds from `qpc_epoch`) and a tick with no reading is stored as
|
||||
> **−1** — never 0, which would be a reading — because temperatures, loads, power and memory are never negative.
|
||||
>
|
||||
> **The advanced series are the exception, and say so by their name (schema 0023, owner decision D102).** A series
|
||||
> whose name starts with `adv.` stores **NaN** for a tick with no reading: a motherboard's −12 V rail is negative, so
|
||||
> −1 cannot mark a gap, and most of its ticks are gaps — the sensor library is read every fifth. They go through a
|
||||
> second encoder, `ISeriesCodec.EncodeSparseFloat32`, which allows NaN and still refuses an infinity; **the rule
|
||||
> above is not relaxed**: `EncodeFloat32` throws on a NaN as before, because a frame time has no gaps. Both decode
|
||||
> with `DecodeFloat32`. `ISessionRepository.FindSensorsAsync` — what every summary, chart and export reads — leaves
|
||||
> the `adv.` rows out (`series NOT LIKE 'adv.%'`), since those readers drop every negative value as "no reading";
|
||||
> `FindAdvancedSensorsAsync` returns them with `t_ms` first. One session stores at most 256 of them
|
||||
> (`AdvancedSessionBuilder.MaxSeries`); what is beyond is counted in its directory, not stored.
|
||||
> **Size, measured 2026-11-11** on values shaped like the dev box's reader (17 series with a reading every tick, 41
|
||||
> with one every fifth): one hour is 816 KiB raw and **189 KiB stored** — well inside NFR-5's 3 MB an hour.
|
||||
|
||||
## The `.partial` file
|
||||
|
||||
@@ -513,6 +528,16 @@ Because Tier-1 and Tier-2 sessions carry different fields, every query that comp
|
||||
> | 6 `Note` | wall clock + UTF-8 text: a state transition | each transition |
|
||||
> | 7 `Touches` | N × `i64` QPC at which the host touched the target | each flush |
|
||||
> | 8 `SensorsWide` | the same samples under a 32-bit presence mask that carries the game process's memory (D43) | each flush, since beta.12 *(row added 2026-10-04)* |
|
||||
> | 9 `SensorsAdvanced` | the advanced readings of the samples of the type-8 chunk before it (D101): `u16` names, then per name `u16` bytes and UTF-8; `u32` samples, then per sample `i64` QPC, `u16` readings and per reading `u16` name, `f64` value. Each chunk carries its own names, so it reads without any earlier chunk | each flush **in which a sample carries any** — with Advanced metrics off, never; the file is then byte for byte what it was (2026-11-11) |
|
||||
> | 10 `AdvancedContext` | UTF-8 JSON (`AdvancedJson.OfContext`): the PC's facts, the session's, its series' directory, each source's state; the last one wins | the first flush after the recorder set it, and again only when it changed (2026-11-11) |
|
||||
>
|
||||
> **A chunk of a type the reader does not know is skipped, not the end of the file (owner decision D106,
|
||||
> 2026-11-11).** Its length and checksum have been verified by then, so it is a whole chunk a newer build wrote.
|
||||
> Until that day `_ => false` ended the read there, and a build one release older lost everything after the first
|
||||
> new chunk — the price types 9 and 10 would have charged a beta.38 reading a beta.39 file. A chunk of a KNOWN type
|
||||
> that does not parse still ends the read: that is a torn or a wrong file, not a newer one.
|
||||
> (`PartialSessionFileAdvancedTests`: an unknown type between two known ones; the same with its checksum broken;
|
||||
> a kill at every byte offset of a file that holds both new types.)
|
||||
>
|
||||
> Recovery (`PartialRecovery`): a file whose guid is already a row is deleted (the finalize had landed);
|
||||
> one under the minimum session length is discarded; one with no readable header is dropped; the rest
|
||||
@@ -718,6 +743,28 @@ Sequential embedded SQL (`Migrations/0001_init.sql`, `0002_*.sql`, …), applied
|
||||
> from its crash file (which carries no module list). `LatestVersion` is 21;
|
||||
> `LedgerDatabaseTests.ScriptTwentyOneAddsTheModuleSourcesColumnAndAnEarlierSessionHasNone`, the repository round trip.
|
||||
|
||||
> **`0023_advanced_metrics.sql` (2026-11-11, owner decisions D101 and D102) — what Advanced metrics stores.** Two
|
||||
> tables and **no column on `sessions`** — the first `CREATE TABLE` since 0001. Every read of a `sessions` row, the
|
||||
> JSON export and the bug bundle carry the whole row, and a driver profile does not belong in a bug bundle.
|
||||
> `machine_profiles(id, hash UNIQUE, facts_json, captured_at)` holds the facts of the PC, one row per distinct set
|
||||
> (`hash` = SHA-256 of `facts_json`); it stands beside `hardware_snapshots`, not in it, because that table's hash
|
||||
> feeds the trend's hardware-change markers and a set of facts that exists only while an option is on would raise a
|
||||
> marker each time the option is switched. `session_advanced(session_id PRIMARY KEY → sessions ON DELETE CASCADE,
|
||||
> machine_profile_id → machine_profiles, facts_json, stats_json, series_json)` holds one row per session **recorded
|
||||
> with the option on**: its facts and each source's state, the statistics of its advanced series (the form of
|
||||
> `sensor_stats_json`), and the directory of the series that are members of a family. **A session recorded with the
|
||||
> option off has no row** — that absence is how the App says "the option was off when this was recorded" rather than
|
||||
> "nothing answered" — and is never given one. The JSON is `Application.Advanced.AdvancedJson`'s (camel case, nulls
|
||||
> left out, a status by its name); writing is strict, reading is tolerant, and **only a fact whose catalog entry is
|
||||
> read may be written** (`AdvancedJson.Storable`), so no identifier reaches either table (D104). A session deleted
|
||||
> takes its row with it; a profile no session points to is left, as a hardware snapshot is; the retention sweep
|
||||
> removes a session's `adv.` series with its other raw series and keeps its row. Written by the Agent only, in the
|
||||
> session's own transaction (`SqliteSessionRepository.InsertAdvancedAsync`). `LatestVersion` is 23;
|
||||
> `LedgerDatabaseTests.ScriptTwentyThreeCreatesTheTwoAdvancedTablesAndAnEarlierSessionHasNoRow` (whose helper now
|
||||
> undoes a script's `CREATE TABLE` and `CREATE INDEX` as well as its `ADD COLUMN`), the repository's four cases.
|
||||
> **Nothing produces a row yet**: the option that switches the reader on is the next pull request's.
|
||||
> **A beta.38 cannot open a ledger a later build migrated.**
|
||||
|
||||
> **`0022_dlss_nr.sql` (beta.34, 2026-11-06, owner decision D84) — DLSS 5's neural rendering, measured.** One REAL column,
|
||||
> ADD COLUMN only: `dlss_nr_pct`, the share (0–100) of the presents that drained a Streamline evaluation on which the game
|
||||
> evaluated `kFeatureDLSS_NR` (`Domain.Metrics.NeuralRendering`). Written by the recorder's aggregation
|
||||
|
||||
@@ -611,6 +611,20 @@ and labelled with the hardware's words. A sensor with no family is not read.
|
||||
sensor has no reading — its last value is not repeated. The same refresh is what the L2 telemetry layer does once
|
||||
a second in every session: that cost is not this feature's, and is `20_OPEN_QUESTIONS` §M16.
|
||||
|
||||
### From the reader to the ledger (built 2026-11-11; produced by nothing yet)
|
||||
|
||||
- **The poller attaches, it does not read.** `TelemetryPoller` takes an optional `IAdvancedHardware`, holds it from
|
||||
`Start` to `Dispose`, and at each poll takes `Latest` — a read of one reference. A snapshot it has not taken yet
|
||||
rides on that poll's `TelemetrySample.Advanced`; one it has already taken is not attached again, because a
|
||||
reading is of one tick. Null — the option off — composes nothing, and a sample is what it always was.
|
||||
- **The `.partial`** carries those readings in a chunk of their own after the sensor chunk (type 9) and the
|
||||
session's context in another (type 10), so a recovered session keeps both; with the option off neither is
|
||||
written. An unknown chunk type is now skipped rather than the end of the file (D106). `06_DATA_MODEL` §The
|
||||
`.partial` file.
|
||||
- **The finalizer** (`AdvancedSessionBuilder`, both tiers) turns the samples' readings into one series each,
|
||||
aligned to `t_ms` with NaN for a tick with none, and builds the session's row: facts, sources, statistics,
|
||||
directory. Schema 0023 and the rule for NaN are `06_DATA_MODEL` §Blob encoding and §Migrations.
|
||||
|
||||
### What belongs to what
|
||||
|
||||
| Scope | What it is | Stored | Shown |
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
|
||||
|
||||
namespace FrameLedger.Application.Advanced;
|
||||
|
||||
/// <summary>An <see cref="AdvancedSessionData"/> as the <c>.partial</c> carries it, so a session that is recovered keeps its facts.</summary>
|
||||
internal sealed record AdvancedContextDocument
|
||||
{
|
||||
public List<AdvancedFactDocument> Machine { get; init; } = [];
|
||||
|
||||
public List<AdvancedFactDocument> Session { get; init; } = [];
|
||||
|
||||
public List<AdvancedSeriesInfoDocument> Series { get; init; } = [];
|
||||
|
||||
public AdvancedSources? Sources { get; init; }
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
|
||||
|
||||
namespace FrameLedger.Application.Advanced;
|
||||
|
||||
/// <summary>One <see cref="AdvancedFact"/> as it is stored: its id, which member of a family, and its value in whichever one shape it has.</summary>
|
||||
internal sealed record AdvancedFactDocument
|
||||
{
|
||||
public string Id { get; init; } = string.Empty;
|
||||
|
||||
public string? Instance { get; init; }
|
||||
|
||||
public double? Number { get; init; }
|
||||
|
||||
public string? Text { get; init; }
|
||||
|
||||
public List<string>? Tokens { get; init; }
|
||||
|
||||
public List<AdvancedRowDocument>? Rows { get; init; }
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
|
||||
|
||||
using System.Text.Json;
|
||||
using FrameLedger.Application.Recording;
|
||||
|
||||
namespace FrameLedger.Application.Advanced;
|
||||
|
||||
/// <summary>
|
||||
/// The one JSON form of what "Advanced metrics" stores and carries (owner decision D102): the facts of a PC, the facts
|
||||
/// of a session, the directory of its series, and — in a <c>.partial</c> — all of it together.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// <b>Writing is strict and reading is tolerant</b>, like every JSON column here: what is written is exactly what the
|
||||
/// types hold; what is read back and does not fit — a ledger edited by hand, a value in two shapes, a word that is not
|
||||
/// a token — is left out, never thrown, and never guessed at.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <b>Only what the catalog says is read is written</b> (<see cref="Storable"/>). The readers have no way to produce
|
||||
/// an identifier (D104); this is the same rule held once more at the door of the ledger, where a mistake would last.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public static class AdvancedJson
|
||||
{
|
||||
/// <summary>
|
||||
/// The facts a ledger may hold: those whose id is a catalog entry this build reads. A fact of an entry that is an
|
||||
/// identifier, the player's state, or simply unknown is not among them.
|
||||
/// </summary>
|
||||
public static IReadOnlyList<AdvancedFact> Storable(IReadOnlyList<AdvancedFact> facts)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(facts);
|
||||
return [.. facts.Where(static f => AdvancedMetricCatalog.Find(f.Id) is { IsRead: true })];
|
||||
}
|
||||
|
||||
public static string OfFacts(IReadOnlyList<AdvancedFact> facts)
|
||||
=> JsonSerializer.Serialize(Documents(facts), AdvancedJsonContext.Default.ListAdvancedFactDocument);
|
||||
|
||||
public static IReadOnlyList<AdvancedFact> ParseFacts(string? json)
|
||||
=> Read(json, AdvancedJsonContext.Default.ListAdvancedFactDocument) is { } documents ? Facts(documents) : [];
|
||||
|
||||
public static string OfSession(IReadOnlyList<AdvancedFact> facts, AdvancedSources sources)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(sources);
|
||||
return JsonSerializer.Serialize(new AdvancedSessionDocument { Facts = Documents(facts), Sources = sources }, AdvancedJsonContext.Default.AdvancedSessionDocument);
|
||||
}
|
||||
|
||||
public static (IReadOnlyList<AdvancedFact> Facts, AdvancedSources Sources) ParseSession(string? json)
|
||||
=> Read(json, AdvancedJsonContext.Default.AdvancedSessionDocument) is { } document
|
||||
? (Facts(document.Facts), document.Sources ?? AdvancedSources.Unknown)
|
||||
: ([], AdvancedSources.Unknown);
|
||||
|
||||
public static string OfSeries(IReadOnlyList<AdvancedSeriesInfo> series, int dropped)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(series);
|
||||
ArgumentOutOfRangeException.ThrowIfNegative(dropped);
|
||||
return JsonSerializer.Serialize(new AdvancedSeriesDocument { Series = SeriesDocuments(series), Dropped = dropped }, AdvancedJsonContext.Default.AdvancedSeriesDocument);
|
||||
}
|
||||
|
||||
public static (IReadOnlyList<AdvancedSeriesInfo> Series, int Dropped) ParseSeries(string? json)
|
||||
=> Read(json, AdvancedJsonContext.Default.AdvancedSeriesDocument) is { } document
|
||||
? (Series(document.Series), Math.Max(0, document.Dropped))
|
||||
: ([], 0);
|
||||
|
||||
public static string OfStats(IReadOnlyDictionary<string, SensorSeriesStats> stats)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(stats);
|
||||
return JsonSerializer.Serialize(new Dictionary<string, SensorSeriesStats>(stats, StringComparer.Ordinal), AdvancedJsonContext.Default.DictionaryStringSensorSeriesStats);
|
||||
}
|
||||
|
||||
public static IReadOnlyDictionary<string, SensorSeriesStats> ParseStats(string? json)
|
||||
=> Read(json, AdvancedJsonContext.Default.DictionaryStringSensorSeriesStats) ?? new Dictionary<string, SensorSeriesStats>(StringComparer.Ordinal);
|
||||
|
||||
/// <summary>A session's whole advanced context, for the <c>.partial</c>.</summary>
|
||||
public static string OfContext(AdvancedSessionData data)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(data);
|
||||
return JsonSerializer.Serialize(
|
||||
new AdvancedContextDocument
|
||||
{
|
||||
Machine = Documents(data.MachineFacts),
|
||||
Session = Documents(data.SessionFacts),
|
||||
Series = SeriesDocuments(data.Series),
|
||||
Sources = data.Sources,
|
||||
},
|
||||
AdvancedJsonContext.Default.AdvancedContextDocument);
|
||||
}
|
||||
|
||||
/// <summary>The context a <c>.partial</c> carried, or null when it carried none that reads.</summary>
|
||||
public static AdvancedSessionData? ParseContext(string? json)
|
||||
=> Read(json, AdvancedJsonContext.Default.AdvancedContextDocument) is { } document
|
||||
? new AdvancedSessionData(Facts(document.Machine), Facts(document.Session), Series(document.Series), document.Sources ?? AdvancedSources.Unknown)
|
||||
: null;
|
||||
|
||||
private static T? Read<T>(string? json, System.Text.Json.Serialization.Metadata.JsonTypeInfo<T> type)
|
||||
where T : class
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(json))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
return JsonSerializer.Deserialize(json, type);
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static List<AdvancedFactDocument> Documents(IReadOnlyList<AdvancedFact> facts)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(facts);
|
||||
return
|
||||
[
|
||||
.. facts.Select(static f => new AdvancedFactDocument
|
||||
{
|
||||
Id = f.Id,
|
||||
Instance = f.Instance,
|
||||
Number = f.Value.Number,
|
||||
Text = f.Value.Text,
|
||||
Tokens = f.Value.Tokens is { } tokens ? [.. tokens] : null,
|
||||
Rows = f.Value.Rows is { } rows ? [.. rows.Select(static r => new AdvancedRowDocument { Name = r.Name, Value = r.Value, Token = r.Token })] : null,
|
||||
}),
|
||||
];
|
||||
}
|
||||
|
||||
private static List<AdvancedFact> Facts(List<AdvancedFactDocument>? documents)
|
||||
{
|
||||
var facts = new List<AdvancedFact>(documents?.Count ?? 0);
|
||||
foreach (AdvancedFactDocument d in documents ?? [])
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(d?.Id) && ValueOf(d) is { } value)
|
||||
{
|
||||
facts.Add(new AdvancedFact(d.Id, string.IsNullOrWhiteSpace(d.Instance) ? null : d.Instance, value));
|
||||
}
|
||||
}
|
||||
|
||||
return facts;
|
||||
}
|
||||
|
||||
/// <summary>The value of a stored fact when it has exactly one shape and that shape is well formed; null otherwise.</summary>
|
||||
private static AdvancedValue? ValueOf(AdvancedFactDocument d)
|
||||
{
|
||||
int shapes = (d.Number is null ? 0 : 1) + (d.Text is null ? 0 : 1) + (d.Tokens is null ? 0 : 1) + (d.Rows is null ? 0 : 1);
|
||||
if (shapes != 1)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (d.Number is { } number)
|
||||
{
|
||||
return double.IsFinite(number) ? AdvancedValue.Of(number) : null;
|
||||
}
|
||||
|
||||
if (d.Text is { } text)
|
||||
{
|
||||
return string.IsNullOrWhiteSpace(text) ? null : AdvancedValue.OfText(text);
|
||||
}
|
||||
|
||||
if (d.Tokens is { } tokens)
|
||||
{
|
||||
return tokens.TrueForAll(static t => AdvancedValue.IsToken(t)) ? AdvancedValue.OfTokens(tokens) : null;
|
||||
}
|
||||
|
||||
// A row with no name or no value is not a row: the whole fact is left out rather than shown with a hole in it.
|
||||
var rows = new List<AdvancedRow>(d.Rows!.Count);
|
||||
foreach (AdvancedRowDocument? r in d.Rows)
|
||||
{
|
||||
if (r?.Name is not { } name || r.Value is not { } value)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
rows.Add(new AdvancedRow(name, value, r.Token));
|
||||
}
|
||||
|
||||
return AdvancedValue.OfRows(rows);
|
||||
}
|
||||
|
||||
private static List<AdvancedSeriesInfoDocument> SeriesDocuments(IReadOnlyList<AdvancedSeriesInfo> series)
|
||||
=> [.. series.Select(static s => new AdvancedSeriesInfoDocument { Series = s.Series, MetricId = s.MetricId, Label = s.Label })];
|
||||
|
||||
/// <summary>The directory lines that are whole and name an advanced series; any other is left out.</summary>
|
||||
private static List<AdvancedSeriesInfo> Series(List<AdvancedSeriesInfoDocument>? documents)
|
||||
{
|
||||
var series = new List<AdvancedSeriesInfo>(documents?.Count ?? 0);
|
||||
foreach (AdvancedSeriesInfoDocument? d in documents ?? [])
|
||||
{
|
||||
if (d?.Series is { } name && d.MetricId is { } metric && d.Label is { } label && name.StartsWith(AdvancedMetric.SeriesPrefix, StringComparison.Ordinal))
|
||||
{
|
||||
series.Add(new AdvancedSeriesInfo(name, metric, label));
|
||||
}
|
||||
}
|
||||
|
||||
return series;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
|
||||
|
||||
using System.Text.Json.Serialization;
|
||||
using FrameLedger.Application.Recording;
|
||||
|
||||
namespace FrameLedger.Application.Advanced;
|
||||
|
||||
/// <summary>Source-generated JSON for what "Advanced metrics" stores (D102); no reflection. Names are camel case, nulls are left out, and a status is its name.</summary>
|
||||
[JsonSourceGenerationOptions(
|
||||
WriteIndented = false,
|
||||
PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase,
|
||||
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
|
||||
UseStringEnumConverter = true)]
|
||||
[JsonSerializable(typeof(List<AdvancedFactDocument>))]
|
||||
[JsonSerializable(typeof(AdvancedSessionDocument))]
|
||||
[JsonSerializable(typeof(AdvancedSeriesDocument))]
|
||||
[JsonSerializable(typeof(AdvancedContextDocument))]
|
||||
[JsonSerializable(typeof(Dictionary<string, SensorSeriesStats>))]
|
||||
internal sealed partial class AdvancedJsonContext : JsonSerializerContext
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
|
||||
|
||||
namespace FrameLedger.Application.Advanced;
|
||||
|
||||
/// <summary>
|
||||
/// An <see cref="AdvancedRow"/> as it is stored. Every member is nullable because a stored document is read
|
||||
/// tolerantly: a ledger edited by hand can hold a row with no name, and the reader leaves that fact out rather than
|
||||
/// trusting an annotation the text never promised to keep.
|
||||
/// </summary>
|
||||
internal sealed record AdvancedRowDocument
|
||||
{
|
||||
public string? Name { get; init; }
|
||||
|
||||
public string? Value { get; init; }
|
||||
|
||||
public string? Token { get; init; }
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
|
||||
|
||||
namespace FrameLedger.Application.Advanced;
|
||||
|
||||
/// <summary>
|
||||
/// <c>session_advanced.series_json</c>: what each stored series that is a member of a family is, and how many series
|
||||
/// were left out because the session had more than the most one session stores.
|
||||
/// </summary>
|
||||
internal sealed record AdvancedSeriesDocument
|
||||
{
|
||||
public List<AdvancedSeriesInfoDocument> Series { get; init; } = [];
|
||||
|
||||
public int Dropped { get; init; }
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
|
||||
|
||||
namespace FrameLedger.Application.Advanced;
|
||||
|
||||
/// <summary>An <see cref="AdvancedSeriesInfo"/> as it is stored — nullable throughout, for the same reason as <see cref="AdvancedRowDocument"/>.</summary>
|
||||
internal sealed record AdvancedSeriesInfoDocument
|
||||
{
|
||||
public string? Series { get; init; }
|
||||
|
||||
public string? MetricId { get; init; }
|
||||
|
||||
public string? Label { get; init; }
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
|
||||
|
||||
namespace FrameLedger.Application.Advanced;
|
||||
|
||||
/// <summary>
|
||||
/// What one session knows of advanced metrics beside its series (owner decision D102): the PC's facts as they were
|
||||
/// when it ran, its own facts, what each series is, and which sources answered.
|
||||
/// </summary>
|
||||
/// <param name="MachineFacts">The facts of the PC — stored once per distinct set, in <c>machine_profiles</c>.</param>
|
||||
/// <param name="SessionFacts">The facts of this session — <c>session_advanced.facts_json</c>.</param>
|
||||
/// <param name="Series">What each series that is a member of a family is, with the hardware's own label.</param>
|
||||
/// <param name="Sources">Which sources answered while it ran, and why the others did not.</param>
|
||||
public sealed record AdvancedSessionData(
|
||||
IReadOnlyList<AdvancedFact> MachineFacts,
|
||||
IReadOnlyList<AdvancedFact> SessionFacts,
|
||||
IReadOnlyList<AdvancedSeriesInfo> Series,
|
||||
AdvancedSources Sources);
|
||||
@@ -0,0 +1,12 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
|
||||
|
||||
namespace FrameLedger.Application.Advanced;
|
||||
|
||||
/// <summary><c>session_advanced.facts_json</c>: one session's facts and the state of each source while it ran.</summary>
|
||||
internal sealed record AdvancedSessionDocument
|
||||
{
|
||||
public List<AdvancedFactDocument> Facts { get; init; } = [];
|
||||
|
||||
public AdvancedSources? Sources { get; init; }
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
|
||||
|
||||
namespace FrameLedger.Application.Persistence;
|
||||
|
||||
/// <summary>
|
||||
/// What a session stores of advanced metrics beside its series (owner decision D102, schema 0023): one row of
|
||||
/// <c>session_advanced</c>, and the row of <c>machine_profiles</c> it points to.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// A session recorded with the option off has none — that absence is how the page knows to say "the option was off
|
||||
/// when this was recorded" rather than "nothing answered". Every member is JSON in <c>Application.Advanced.AdvancedJson</c>'s form.
|
||||
/// </remarks>
|
||||
public sealed record AdvancedSessionRow
|
||||
{
|
||||
/// <summary>The PC's facts, or null when no source had any. Stored once per distinct <see cref="MachineHash"/>.</summary>
|
||||
public string? MachineFactsJson { get; init; }
|
||||
|
||||
/// <summary>SHA-256 of <see cref="MachineFactsJson"/>, lower-case hexadecimal; null with it.</summary>
|
||||
public string? MachineHash { get; init; }
|
||||
|
||||
/// <summary>The session's own facts and the state of each source while it ran.</summary>
|
||||
public required string FactsJson { get; init; }
|
||||
|
||||
/// <summary>Count, mean, median, minimum and maximum of each stored series; null when the session stored none.</summary>
|
||||
public string? StatsJson { get; init; }
|
||||
|
||||
/// <summary>What each stored series that is a member of a family is, and how many series were left out.</summary>
|
||||
public required string SeriesJson { get; init; }
|
||||
}
|
||||
@@ -13,4 +13,10 @@ public sealed record FinalizedSession
|
||||
public FrameBlobs? Frames { get; init; }
|
||||
|
||||
public IReadOnlyList<SensorBlob> Sensors { get; init; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// The session's row of <c>session_advanced</c> (owner decision D102, schema 0023), or null when it was recorded
|
||||
/// with Advanced metrics off. Its series are among <see cref="Sensors"/>, under names that start with <c>adv.</c>.
|
||||
/// </summary>
|
||||
public AdvancedSessionRow? Advanced { get; init; }
|
||||
}
|
||||
@@ -15,6 +15,13 @@ public interface ISeriesCodec
|
||||
|
||||
byte[] EncodeFloat32(ReadOnlySpan<float> values);
|
||||
|
||||
/// <summary>
|
||||
/// A float series in which <b>NaN means "no reading on this tick"</b> — the advanced series only (owner decision
|
||||
/// D102), whose values may be negative, so −1 cannot mark a gap. Every other value must be finite. It is read back
|
||||
/// with the same decoder as <see cref="EncodeFloat32"/>, which still refuses NaN: a frame time has no gaps.
|
||||
/// </summary>
|
||||
byte[] EncodeSparseFloat32(ReadOnlySpan<float> values);
|
||||
|
||||
byte[] EncodeUInt16(ReadOnlySpan<ushort> values);
|
||||
|
||||
byte[] EncodeUInt32(ReadOnlySpan<uint> values);
|
||||
|
||||
@@ -74,6 +74,23 @@ public interface ISessionRepository
|
||||
/// <summary>The session's segments in frame order (the ribbon, <c>08_UI</c> §Session summary).</summary>
|
||||
ValueTask<IReadOnlyList<SegmentRow>> FindSegmentsAsync(long sessionId, CancellationToken ct = default);
|
||||
|
||||
/// <summary>The session's sensor series, still encoded (the sensor strip decodes what it draws).</summary>
|
||||
/// <summary>
|
||||
/// The session's sensor series, still encoded (the sensor strip decodes what it draws). <b>The fixed series only</b>:
|
||||
/// an advanced series (a name that starts with <c>adv.</c>, schema 0023) is not among them — it stores NaN for a
|
||||
/// tick with no reading and may be negative, where every reader of these drops a negative value as "no reading",
|
||||
/// and a session can hold a hundred of them that a summary never draws.
|
||||
/// </summary>
|
||||
ValueTask<IReadOnlyList<SensorBlob>> FindSensorsAsync(long sessionId, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// The session's advanced series (owner decision D102), still encoded, with <c>t_ms</c> — the clock every one of
|
||||
/// them is aligned to — first. For a session that stored no advanced series that is <c>t_ms</c> alone, or nothing.
|
||||
/// </summary>
|
||||
ValueTask<IReadOnlyList<SensorBlob>> FindAdvancedSensorsAsync(long sessionId, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// The session's row of <c>session_advanced</c> with the machine profile it points to, or null: it was recorded
|
||||
/// with Advanced metrics off (or before they existed).
|
||||
/// </summary>
|
||||
ValueTask<AdvancedSessionRow?> FindAdvancedAsync(long sessionId, CancellationToken ct = default);
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
|
||||
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using FrameLedger.Application.Advanced;
|
||||
using FrameLedger.Application.Persistence;
|
||||
using FrameLedger.Application.Telemetry;
|
||||
using FrameLedger.Domain.Metrics;
|
||||
|
||||
namespace FrameLedger.Application.Recording;
|
||||
|
||||
/// <summary>
|
||||
/// What a session stores of advanced metrics (owner decision D102): one series per advanced reading its samples
|
||||
/// carried, aligned to the session's <c>t_ms</c>, and the row that holds its facts, its statistics and its directory.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// <b>A tick with no reading is NaN, not −1.</b> The fixed series store −1 for a missing tick and their readers drop
|
||||
/// every negative value; an advanced series may be negative — a −12 V rail — and most of its ticks have no reading at
|
||||
/// all, since the sensor library is read every fifth. The <c>adv.</c> prefix is how a reader tells which rule applies.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <b>Nothing in, nothing out.</b> A session whose samples carry no advanced reading and that was given no context —
|
||||
/// the option was off — stores no series and no row, and is byte for byte what it was before this existed.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public static class AdvancedSessionBuilder
|
||||
{
|
||||
/// <summary>
|
||||
/// The most advanced series one session stores. A PC with a card, a processor of thirty-two threads and a board
|
||||
/// full of headers has about a hundred and fifty; what is beyond this is counted in the directory, not stored.
|
||||
/// </summary>
|
||||
public const int MaxSeries = 256;
|
||||
|
||||
public static (IReadOnlyList<SensorBlob> Blobs, AdvancedSessionRow? Row) Build(IReadOnlyList<TelemetrySample> sensors, AdvancedSessionData? data, ISeriesCodec codec)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(sensors);
|
||||
ArgumentNullException.ThrowIfNull(codec);
|
||||
(List<string> names, Dictionary<string, int> indexOf, int dropped) = SeriesOf(sensors);
|
||||
if (names.Count == 0 && data is null)
|
||||
{
|
||||
return ([], null);
|
||||
}
|
||||
|
||||
float[][] columns = Columns(sensors, names.Count, indexOf);
|
||||
var blobs = new List<SensorBlob>(names.Count);
|
||||
var stats = new Dictionary<string, SensorSeriesStats>(StringComparer.Ordinal);
|
||||
for (int s = 0; s < names.Count; s++)
|
||||
{
|
||||
blobs.Add(new SensorBlob { Series = names[s], Hz = 1, Codec = codec.Tag, Data = codec.EncodeSparseFloat32(columns[s]) });
|
||||
SeriesAggregates aggregates = SeriesAggregates.Of(columns[s].Select(static v => float.IsNaN(v) ? (double?)null : v));
|
||||
if (aggregates.Count > 0)
|
||||
{
|
||||
stats[names[s]] = SensorSeriesStats.From(aggregates);
|
||||
}
|
||||
}
|
||||
|
||||
IReadOnlyList<AdvancedFact> machine = AdvancedJson.Storable(data?.MachineFacts ?? []);
|
||||
string? machineJson = machine.Count == 0 ? null : AdvancedJson.OfFacts(machine);
|
||||
AdvancedSeriesInfo[] directory = [.. (data?.Series ?? []).Where(i => indexOf.ContainsKey(i.Series))];
|
||||
return (blobs, new AdvancedSessionRow
|
||||
{
|
||||
MachineFactsJson = machineJson,
|
||||
MachineHash = machineJson is null ? null : Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(machineJson))),
|
||||
FactsJson = AdvancedJson.OfSession(AdvancedJson.Storable(data?.SessionFacts ?? []), data?.Sources ?? AdvancedSources.Unknown),
|
||||
StatsJson = stats.Count == 0 ? null : AdvancedJson.OfStats(stats),
|
||||
SeriesJson = AdvancedJson.OfSeries(directory, dropped),
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>The series the samples carry, in the order they first appear, up to <see cref="MaxSeries"/>; and how many more there were.</summary>
|
||||
private static (List<string> Names, Dictionary<string, int> IndexOf, int Dropped) SeriesOf(IReadOnlyList<TelemetrySample> sensors)
|
||||
{
|
||||
var names = new List<string>();
|
||||
var indexOf = new Dictionary<string, int>(StringComparer.Ordinal);
|
||||
var beyond = new HashSet<string>(StringComparer.Ordinal);
|
||||
foreach (TelemetrySample sample in sensors)
|
||||
{
|
||||
foreach (AdvancedReading reading in sample.Advanced ?? [])
|
||||
{
|
||||
// Only what carries the prefix is an advanced series: a name without it could be taken for a fixed one.
|
||||
if (reading.Series is null || !reading.Series.StartsWith(AdvancedMetric.SeriesPrefix, StringComparison.Ordinal) || indexOf.ContainsKey(reading.Series))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (names.Count < MaxSeries)
|
||||
{
|
||||
indexOf[reading.Series] = names.Count;
|
||||
names.Add(reading.Series);
|
||||
}
|
||||
else
|
||||
{
|
||||
beyond.Add(reading.Series);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return (names, indexOf, beyond.Count);
|
||||
}
|
||||
|
||||
private static float[][] Columns(IReadOnlyList<TelemetrySample> sensors, int series, Dictionary<string, int> indexOf)
|
||||
{
|
||||
float[][] columns = new float[series][];
|
||||
for (int s = 0; s < series; s++)
|
||||
{
|
||||
columns[s] = new float[sensors.Count];
|
||||
Array.Fill(columns[s], float.NaN);
|
||||
}
|
||||
|
||||
for (int i = 0; i < sensors.Count; i++)
|
||||
{
|
||||
foreach (AdvancedReading reading in sensors[i].Advanced ?? [])
|
||||
{
|
||||
if (reading.Series is not null && indexOf.TryGetValue(reading.Series, out int s) && double.IsFinite(reading.Value))
|
||||
{
|
||||
columns[s][i] = (float)reading.Value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return columns;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
|
||||
|
||||
using FrameLedger.Application.Advanced;
|
||||
using FrameLedger.Application.Persistence;
|
||||
using FrameLedger.Application.Telemetry;
|
||||
|
||||
@@ -17,6 +18,12 @@ public sealed record FinalizeInput
|
||||
|
||||
public IReadOnlyList<TelemetrySample> Sensors { get; init; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// The session's advanced context (owner decision D101): the PC's facts, its own, its series' directory and the
|
||||
/// state of each source. Null when it was recorded with Advanced metrics off — it then stores nothing of them.
|
||||
/// </summary>
|
||||
public AdvancedSessionData? Advanced { get; init; }
|
||||
|
||||
/// <summary><c>06_DATA_MODEL</c> §Retention: raw blobs for the last N sessions per game.</summary>
|
||||
public int RetentionKeep { get; init; } = SessionFinalizer.DefaultRetentionKeep;
|
||||
|
||||
|
||||
@@ -24,4 +24,10 @@ public interface IPartialSessionWriter : IDisposable
|
||||
void AppendTouches(ReadOnlySpan<long> touchQpc);
|
||||
|
||||
void AppendNote(DateTimeOffset at, string text);
|
||||
|
||||
/// <summary>
|
||||
/// The session's advanced context as JSON (owner decision D101); a later one replaces an earlier one. Never
|
||||
/// called for a session recorded with Advanced metrics off.
|
||||
/// </summary>
|
||||
void AppendAdvancedContext(string json);
|
||||
}
|
||||
@@ -157,7 +157,9 @@ public sealed class PartialRecovery
|
||||
TotalDropped = partial.LastTick?.TotalDropped ?? 0,
|
||||
};
|
||||
|
||||
return new FinalizeInput { Skeleton = skeleton, Hooked = aggregation, Sensors = partial.Sensors };
|
||||
// A session recorded with Advanced metrics on carries its context in the file (D101); one recorded with them
|
||||
// off carries none, and stores none.
|
||||
return new FinalizeInput { Skeleton = skeleton, Hooked = aggregation, Sensors = partial.Sensors, Advanced = Advanced.AdvancedJson.ParseContext(partial.AdvancedContextJson) };
|
||||
}
|
||||
|
||||
/// <summary>The <c>build=…</c> word of the recorder's <c>attached</c> note, or null.</summary>
|
||||
|
||||
@@ -30,4 +30,10 @@ public sealed record PartialSession
|
||||
|
||||
/// <summary>True when the file ended inside a chunk, or a chunk failed its check: the tail was lost.</summary>
|
||||
public required bool Truncated { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// The session's advanced context as the file last carried it (<c>AdvancedJson.ParseContext</c> reads it), or null:
|
||||
/// it was recorded with Advanced metrics off, or by a build before they existed.
|
||||
/// </summary>
|
||||
public string? AdvancedContextJson { get; init; }
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
|
||||
|
||||
using FrameLedger.Application.Advanced;
|
||||
using FrameLedger.Application.Capture;
|
||||
using FrameLedger.Application.Telemetry;
|
||||
using FrameLedger.Shared;
|
||||
@@ -26,6 +27,8 @@ public sealed class PartialSessionWriter : IDisposable
|
||||
private readonly TimeSpan _interval;
|
||||
private readonly List<TelemetrySample> _sensors = [];
|
||||
|
||||
private string? _advancedContext;
|
||||
private string? _advancedContextWritten;
|
||||
private int _recordsWritten;
|
||||
private int _gapsWritten;
|
||||
private int _sensorsWritten;
|
||||
@@ -53,6 +56,21 @@ public sealed class PartialSessionWriter : IDisposable
|
||||
_sensors.AddRange(samples);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The session's advanced context (owner decision D101), kept for the finalizer and written to the file with the
|
||||
/// next flush — and again only when it has changed, so a context that stays the same is in the file once. Never
|
||||
/// called for a session recorded with Advanced metrics off.
|
||||
/// </summary>
|
||||
public void SetAdvancedContext(AdvancedSessionData data)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(data);
|
||||
Advanced = data;
|
||||
_advancedContext = AdvancedJson.OfContext(data);
|
||||
}
|
||||
|
||||
/// <summary>The context last given to <see cref="SetAdvancedContext"/>, or null.</summary>
|
||||
public AdvancedSessionData? Advanced { get; private set; }
|
||||
|
||||
/// <summary>A state transition: written at once, never batched, because it is the breadcrumb.</summary>
|
||||
public void Note(string text)
|
||||
{
|
||||
@@ -95,6 +113,12 @@ public sealed class PartialSessionWriter : IDisposable
|
||||
_sensorsWritten = _sensors.Count;
|
||||
}
|
||||
|
||||
if (_advancedContext is not null && !string.Equals(_advancedContext, _advancedContextWritten, StringComparison.Ordinal))
|
||||
{
|
||||
_file.AppendAdvancedContext(_advancedContext);
|
||||
_advancedContextWritten = _advancedContext;
|
||||
}
|
||||
|
||||
if (progress.TouchQpc.Count > _touchesWritten)
|
||||
{
|
||||
_file.AppendTouches([.. progress.TouchQpc.Skip(_touchesWritten)]);
|
||||
|
||||
@@ -56,6 +56,10 @@ public sealed class SessionFinalizer
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(input);
|
||||
SessionRow row = input.Skeleton;
|
||||
|
||||
// Advanced metrics (D102), both tiers: they are read by the Agent, not by a hook, so a session that was not
|
||||
// hooked has them all the same. Nothing when the option was off - no series, no row.
|
||||
(IReadOnlyList<SensorBlob> advancedBlobs, AdvancedSessionRow? advanced) = AdvancedSessionBuilder.Build(input.Sensors, input.Advanced, _codec);
|
||||
if (input.Hooked is null)
|
||||
{
|
||||
// A Tier-2 row has no frames and every sensor the machine provided (2026-09-22): the same averages a
|
||||
@@ -63,7 +67,8 @@ public sealed class SessionFinalizer
|
||||
return new FinalizedSession
|
||||
{
|
||||
Row = SessionAggregator.WithSensorAggregates(row with { Tier = CaptureTier.NotHooked }, input.Sensors),
|
||||
Sensors = EncodeSensors(input.Sensors, row.QpcEpoch, row.QpcFrequency),
|
||||
Sensors = [.. EncodeSensors(input.Sensors, row.QpcEpoch, row.QpcFrequency), .. advancedBlobs],
|
||||
Advanced = advanced,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -77,7 +82,8 @@ public sealed class SessionFinalizer
|
||||
{
|
||||
FirstPresentMs = FirstPresentMs(r.Dominant, row.QpcEpoch, row.QpcFrequency),
|
||||
},
|
||||
Sensors = EncodeSensors(input.Sensors, row.QpcEpoch, row.QpcFrequency),
|
||||
Sensors = [.. EncodeSensors(input.Sensors, row.QpcEpoch, row.QpcFrequency), .. advancedBlobs],
|
||||
Advanced = advanced,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
|
||||
|
||||
using System.Runtime.InteropServices;
|
||||
using FrameLedger.Application.Advanced;
|
||||
|
||||
namespace FrameLedger.Application.Telemetry;
|
||||
|
||||
@@ -26,5 +27,10 @@ namespace FrameLedger.Application.Telemetry;
|
||||
/// <param name="Sample">The GPU layers' composed sample; a placeholder with <see cref="TelemetryLayer.None"/> and no field on a tick only the system source answered.</param>
|
||||
/// <param name="System">The machine beside the GPU on the same tick (2026-09-21): CPU busy %, memory in use, CPU temperature where readable. Empty when no system source is composed, which is every sample recorded before that date.</param>
|
||||
/// <param name="Game">The game process's own memory on the same tick (beta.12, D43): read from outside the game. Empty when no game source is composed or nothing was followed yet — every sample recorded before beta.12.</param>
|
||||
/// <param name="Advanced">
|
||||
/// The advanced readings of the same tick (owner decision D101): the one snapshot of the shared advanced reader that
|
||||
/// was new at this poll, or null — the option is off, or that reader published nothing since the last poll. Null on
|
||||
/// every sample recorded before it existed. Never a repeat of an earlier tick's readings: a reading is of one tick.
|
||||
/// </param>
|
||||
[StructLayout(LayoutKind.Auto)]
|
||||
public readonly record struct TelemetrySample(long QpcTicks, GpuSample Sample, SystemReading System = default, ProcessReading Game = default);
|
||||
public readonly record struct TelemetrySample(long QpcTicks, GpuSample Sample, SystemReading System = default, ProcessReading Game = default, IReadOnlyList<AdvancedReading>? Advanced = null);
|
||||
@@ -12,6 +12,8 @@ public sealed class DeflateSeriesCodec : ISeriesCodec
|
||||
|
||||
public byte[] EncodeFloat32(ReadOnlySpan<float> values) => SeriesCodec.EncodeFloat32(values.ToArray());
|
||||
|
||||
public byte[] EncodeSparseFloat32(ReadOnlySpan<float> values) => SeriesCodec.EncodeSparseFloat32(values.ToArray());
|
||||
|
||||
public byte[] EncodeUInt16(ReadOnlySpan<ushort> values) => SeriesCodec.EncodeUInt16(values.ToArray());
|
||||
|
||||
public byte[] EncodeUInt32(ReadOnlySpan<uint> values) => SeriesCodec.EncodeUInt32(values.ToArray());
|
||||
|
||||
@@ -38,6 +38,30 @@ public static class SeriesCodec
|
||||
return Deflate(raw);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A float series in which NaN means "no reading on this tick" (owner decision D102: the advanced series, whose
|
||||
/// values may be negative). The rule above is not relaxed by this — it is a second encoder, for a series that has
|
||||
/// gaps by nature, and <see cref="EncodeFloat32"/> still throws on a NaN. An infinity is refused here as there:
|
||||
/// no sensor reads one.
|
||||
/// </summary>
|
||||
public static byte[] EncodeSparseFloat32(IReadOnlyList<float> values)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(values);
|
||||
|
||||
byte[] raw = new byte[values.Count * sizeof(float)];
|
||||
for (int i = 0; i < values.Count; i++)
|
||||
{
|
||||
if (float.IsInfinity(values[i]))
|
||||
{
|
||||
throw new ArgumentException($"infinity at index {i}: a sparse series carries finite values and NaN for a gap (06_DATA_MODEL §Blob encoding)", nameof(values));
|
||||
}
|
||||
|
||||
BinaryPrimitives.WriteSingleLittleEndian(raw.AsSpan(i * sizeof(float)), values[i]);
|
||||
}
|
||||
|
||||
return Deflate(raw);
|
||||
}
|
||||
|
||||
public static float[] DecodeFloat32(byte[] blob)
|
||||
{
|
||||
byte[] raw = Inflate(blob, sizeof(float));
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
-- 0023 (2026-11-11, owner decisions D101 and D102): what "Advanced metrics" stores.
|
||||
--
|
||||
-- Two tables of their own and no column on `sessions`: every read of a sessions row, the JSON export and the bug bundle
|
||||
-- carry the whole row, and a driver profile does not belong in a bug bundle. The first CREATE TABLE since 0001.
|
||||
--
|
||||
-- machine_profiles - the facts of the PC (the card's firmware and architecture, the driver's package, what a display
|
||||
-- can do, the driver's global profile), ONE ROW PER DISTINCT SET: `hash` is the SHA-256 of
|
||||
-- `facts_json`. Beside hardware_snapshots, not in it: that table's hash feeds the trend's
|
||||
-- hardware-change markers, and a set of facts that exists only while an option is on would raise a
|
||||
-- marker each time the option is switched.
|
||||
-- session_advanced - one row per session recorded with the option ON: its own facts and the state of each source
|
||||
-- (facts_json), the statistics of its advanced series (stats_json), what each series that is one of
|
||||
-- a family is (series_json), and the machine profile that was true when it ran. A session recorded
|
||||
-- with the option off has NO row - that absence is how the App says "the option was off when this
|
||||
-- was recorded" rather than "nothing answered". The series themselves are rows of sensor_blobs
|
||||
-- under names that start with `adv.`, with NaN for a tick that has no reading.
|
||||
--
|
||||
-- No identifier is in either (D104): no serial number, no unique id, no EDID, no other program's process id.
|
||||
-- Written by the Agent only (06_DATA_MODEL section Writer ownership). A session deleted takes its row with it; a
|
||||
-- machine profile no session points to any more is left, as a hardware snapshot is.
|
||||
|
||||
CREATE TABLE machine_profiles (
|
||||
id INTEGER PRIMARY KEY,
|
||||
hash TEXT NOT NULL UNIQUE, -- sha256 of facts_json, lower-case hex
|
||||
facts_json TEXT NOT NULL, -- Application.Advanced.AdvancedJson: a list of facts
|
||||
captured_at INTEGER NOT NULL -- unix ms: the start of the first session that had this set
|
||||
);
|
||||
|
||||
CREATE TABLE session_advanced (
|
||||
session_id INTEGER PRIMARY KEY REFERENCES sessions(id) ON DELETE CASCADE,
|
||||
machine_profile_id INTEGER REFERENCES machine_profiles(id), -- NULL: no source had a fact of the PC
|
||||
facts_json TEXT NOT NULL, -- the session's facts and each source's state
|
||||
stats_json TEXT, -- per advanced series: n, mean, median, min, max; NULL: it stored none
|
||||
series_json TEXT NOT NULL -- the directory of its family members, and how many series were left out
|
||||
);
|
||||
|
||||
CREATE INDEX ix_session_advanced_profile ON session_advanced(machine_profile_id);
|
||||
@@ -51,7 +51,28 @@ public sealed class SqliteSessionRepository : ISessionRepository
|
||||
"SELECT swapchain_id, start_frame, end_frame, render_w, render_h, output_w, output_h, upscaler, upscaler_quality, fg_mode, "
|
||||
+ "native_fps, displayed_fps, p1_low_fps FROM session_segments WHERE session_id = @sessionId ORDER BY start_frame, swapchain_id";
|
||||
|
||||
private const string _selectSensors = "SELECT series, hz, codec, data FROM sensor_blobs WHERE session_id = @sessionId ORDER BY series";
|
||||
// The fixed series; an advanced one (schema 0023) is a row of the same table under a name that starts with 'adv.'.
|
||||
// In LIKE the dot is a literal and the only wildcard is the trailing %, so 'adv.%' is exactly that prefix.
|
||||
private const string _selectSensors =
|
||||
"SELECT series, hz, codec, data FROM sensor_blobs WHERE session_id = @sessionId AND series NOT LIKE 'adv.%' ORDER BY series";
|
||||
|
||||
private const string _selectAdvancedSensors =
|
||||
"SELECT series, hz, codec, data FROM sensor_blobs WHERE session_id = @sessionId AND (series = 't_ms' OR series LIKE 'adv.%') "
|
||||
+ "ORDER BY CASE WHEN series = 't_ms' THEN 0 ELSE 1 END, series";
|
||||
|
||||
// One row per distinct set of facts: a second session with the same set finds the first one's row.
|
||||
private const string _insertMachineProfile =
|
||||
"INSERT INTO machine_profiles (hash, facts_json, captured_at) VALUES (@hash, @facts, @at) ON CONFLICT(hash) DO NOTHING";
|
||||
|
||||
private const string _selectMachineProfile = "SELECT id FROM machine_profiles WHERE hash = @hash";
|
||||
|
||||
private const string _insertAdvanced =
|
||||
"INSERT INTO session_advanced (session_id, machine_profile_id, facts_json, stats_json, series_json) "
|
||||
+ "VALUES (@id, @profileId, @facts, @stats, @series)";
|
||||
|
||||
private const string _selectAdvanced =
|
||||
"SELECT a.facts_json, a.stats_json, a.series_json, m.hash, m.facts_json FROM session_advanced a "
|
||||
+ "LEFT JOIN machine_profiles m ON m.id = a.machine_profile_id WHERE a.session_id = @sessionId";
|
||||
|
||||
// One pass over the aggregate columns; SUM(capture_tier = 1) is SQLite's boolean-as-integer idiom.
|
||||
private const string _summarise =
|
||||
@@ -111,6 +132,11 @@ public sealed class SqliteSessionRepository : ISessionRepository
|
||||
}
|
||||
|
||||
await InsertSensorsAsync(c, tx, id, session.Sensors, token).ConfigureAwait(false);
|
||||
if (session.Advanced is AdvancedSessionRow advanced)
|
||||
{
|
||||
await InsertAdvancedAsync(c, tx, id, advanced, session.Row.StartedAt, token).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return id;
|
||||
}, ct);
|
||||
}
|
||||
@@ -186,6 +212,23 @@ public sealed class SqliteSessionRepository : ISessionRepository
|
||||
c, new CommandDefinition(_selectSensors, new { sessionId }, cancellationToken: token),
|
||||
static r => new SensorBlob { Series = r.GetString(0), Hz = r.GetDouble(1), Codec = r.GetString(2), Data = (byte[])r.GetValue(3) }), ct);
|
||||
|
||||
public ValueTask<IReadOnlyList<SensorBlob>> FindAdvancedSensorsAsync(long sessionId, CancellationToken ct = default) =>
|
||||
_db.ReadAsync((c, token) => SqliteReaders.ReadAllAsync(
|
||||
c, new CommandDefinition(_selectAdvancedSensors, new { sessionId }, cancellationToken: token),
|
||||
static r => new SensorBlob { Series = r.GetString(0), Hz = r.GetDouble(1), Codec = r.GetString(2), Data = (byte[])r.GetValue(3) }), ct);
|
||||
|
||||
public ValueTask<AdvancedSessionRow?> FindAdvancedAsync(long sessionId, CancellationToken ct = default) =>
|
||||
_db.ReadAsync((c, token) => SqliteReaders.ReadOneAsync(
|
||||
c, new CommandDefinition(_selectAdvanced, new { sessionId }, cancellationToken: token),
|
||||
static r => new AdvancedSessionRow
|
||||
{
|
||||
FactsJson = r.GetString(0),
|
||||
StatsJson = r.IsDBNull(1) ? null : r.GetString(1),
|
||||
SeriesJson = r.GetString(2),
|
||||
MachineHash = r.IsDBNull(3) ? null : r.GetString(3),
|
||||
MachineFactsJson = r.IsDBNull(4) ? null : r.GetString(4),
|
||||
}), ct);
|
||||
|
||||
public ValueTask<IReadOnlyList<SessionRow>> ListRecentAsync(int count, CancellationToken ct = default)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(count);
|
||||
@@ -330,6 +373,23 @@ public sealed class SqliteSessionRepository : ISessionRepository
|
||||
|
||||
private static object Optional(ReadOnlyMemory<byte>? blob) => blob is { } b ? b.ToArray() : DBNull.Value;
|
||||
|
||||
/// <summary>
|
||||
/// The session's row of <c>session_advanced</c>, and the machine profile it points to — found by its hash when a
|
||||
/// session before it had the same facts, inserted when none had. Inside the session's own transaction.
|
||||
/// </summary>
|
||||
private static async Task InsertAdvancedAsync(SqliteConnection c, SqliteTransaction tx, long id, AdvancedSessionRow advanced, DateTimeOffset startedAt, CancellationToken ct)
|
||||
{
|
||||
long? profileId = null;
|
||||
if (advanced is { MachineHash: { } hash, MachineFactsJson: { } facts })
|
||||
{
|
||||
await c.ExecuteAsync(new CommandDefinition(_insertMachineProfile, new { hash, facts, at = startedAt.ToUnixTimeMilliseconds() }, tx, cancellationToken: ct)).ConfigureAwait(false);
|
||||
profileId = await c.ExecuteScalarAsync<long>(new CommandDefinition(_selectMachineProfile, new { hash }, tx, cancellationToken: ct)).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await c.ExecuteAsync(new CommandDefinition(
|
||||
_insertAdvanced, new { id, profileId, facts = advanced.FactsJson, stats = advanced.StatsJson, series = advanced.SeriesJson }, tx, cancellationToken: ct)).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private static async Task InsertSensorsAsync(SqliteConnection c, SqliteTransaction tx, long id, IReadOnlyList<SensorBlob> sensors, CancellationToken ct)
|
||||
{
|
||||
foreach (SensorBlob sensor in sensors)
|
||||
|
||||
@@ -0,0 +1,205 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
|
||||
|
||||
using System.Buffers.Binary;
|
||||
using System.Text;
|
||||
using FrameLedger.Application.Advanced;
|
||||
using FrameLedger.Application.Telemetry;
|
||||
|
||||
namespace FrameLedger.Infrastructure.Recording;
|
||||
|
||||
/// <summary>
|
||||
/// The advanced readings of a batch of telemetry samples as bytes, for the <c>.partial</c> (chunk type
|
||||
/// <c>SensorsAdvanced</c>, owner decision D101): the names the batch uses, once, then per sample its QPC and its
|
||||
/// readings as (name index, value).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// <b>Beside the wide sensor chunk, not instead of it.</b> The samples of a batch are written as they always were
|
||||
/// (<see cref="SensorSampleCodec"/>), byte for byte; this chunk follows it and carries only what is new, keyed by the
|
||||
/// QPC each sample already has. A session recorded with the option off never writes one.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <b>Each chunk stands alone</b>: its names are in it. A reader needs nothing from an earlier chunk to read it, so a
|
||||
/// file cut anywhere still reads up to its last whole chunk — the property the whole format is built on.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Layout, little-endian: <c>u16 names</c>, then per name <c>u16 bytes</c> and its UTF-8; <c>u32 samples</c>, then per
|
||||
/// sample <c>i64 qpc</c>, <c>u16 readings</c> and per reading <c>u16 name</c>, <c>f64 value</c>.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
internal static class AdvancedSampleCodec
|
||||
{
|
||||
/// <summary>A name longer than this is not a series name this project writes; a chunk claiming one is refused.</summary>
|
||||
private const int _maxNameBytes = 256;
|
||||
|
||||
private const int _readingBytes = 2 + 8;
|
||||
private const int _sampleHeaderBytes = 8 + 2;
|
||||
|
||||
/// <summary>The chunk for the samples of <paramref name="samples"/> that carry advanced readings, or null when none does.</summary>
|
||||
public static byte[]? Write(ReadOnlySpan<TelemetrySample> samples)
|
||||
{
|
||||
var names = new List<string>();
|
||||
var indexOf = new Dictionary<string, ushort>(StringComparer.Ordinal);
|
||||
int carrying = 0;
|
||||
int bytes = 2 + 4;
|
||||
foreach (ref readonly TelemetrySample sample in samples)
|
||||
{
|
||||
if (sample.Advanced is not { Count: > 0 } readings)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
carrying++;
|
||||
bytes += _sampleHeaderBytes;
|
||||
foreach (AdvancedReading reading in readings)
|
||||
{
|
||||
if (!Writable(reading.Series) || (!indexOf.ContainsKey(reading.Series) && names.Count >= ushort.MaxValue))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (indexOf.TryAdd(reading.Series, (ushort)names.Count))
|
||||
{
|
||||
names.Add(reading.Series);
|
||||
bytes += 2 + Encoding.UTF8.GetByteCount(reading.Series);
|
||||
}
|
||||
|
||||
bytes += _readingBytes;
|
||||
}
|
||||
}
|
||||
|
||||
return carrying == 0 ? null : Fill(new byte[bytes], samples, names, indexOf, carrying);
|
||||
}
|
||||
|
||||
/// <summary>The readings of each sample in a chunk, by the sample's QPC; false when the chunk is not well formed.</summary>
|
||||
public static bool TryRead(ReadOnlySpan<byte> payload, List<(long Qpc, IReadOnlyList<AdvancedReading> Readings)> into)
|
||||
{
|
||||
int at = 0;
|
||||
if (!TryReadNames(payload, ref at, out string[] names) || payload.Length - at < 4)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
uint samples = BinaryPrimitives.ReadUInt32LittleEndian(payload[at..]);
|
||||
at += 4;
|
||||
var read = new List<(long, IReadOnlyList<AdvancedReading>)>();
|
||||
for (uint s = 0; s < samples; s++)
|
||||
{
|
||||
if (payload.Length - at < _sampleHeaderBytes)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
long qpc = BinaryPrimitives.ReadInt64LittleEndian(payload[at..]);
|
||||
int count = BinaryPrimitives.ReadUInt16LittleEndian(payload[(at + 8)..]);
|
||||
at += _sampleHeaderBytes;
|
||||
if (payload.Length - at < count * _readingBytes)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var readings = new AdvancedReading[count];
|
||||
for (int r = 0; r < count; r++)
|
||||
{
|
||||
int index = BinaryPrimitives.ReadUInt16LittleEndian(payload[at..]);
|
||||
if (index >= names.Length)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
readings[r] = new AdvancedReading(names[index], BinaryPrimitives.ReadDoubleLittleEndian(payload[(at + 2)..]));
|
||||
at += _readingBytes;
|
||||
}
|
||||
|
||||
read.Add((qpc, readings));
|
||||
}
|
||||
|
||||
if (at != payload.Length)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
into.AddRange(read);
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool Writable(string? series) => series is not null && Encoding.UTF8.GetByteCount(series) is > 0 and <= _maxNameBytes;
|
||||
|
||||
private static byte[] Fill(byte[] payload, ReadOnlySpan<TelemetrySample> samples, List<string> names, Dictionary<string, ushort> indexOf, int carrying)
|
||||
{
|
||||
int at = 0;
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(payload.AsSpan(at), (ushort)names.Count);
|
||||
at += 2;
|
||||
foreach (string name in names)
|
||||
{
|
||||
int length = Encoding.UTF8.GetBytes(name, payload.AsSpan(at + 2));
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(payload.AsSpan(at), (ushort)length);
|
||||
at += 2 + length;
|
||||
}
|
||||
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(payload.AsSpan(at), (uint)carrying);
|
||||
at += 4;
|
||||
foreach (ref readonly TelemetrySample sample in samples)
|
||||
{
|
||||
if (sample.Advanced is not { Count: > 0 } readings)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
BinaryPrimitives.WriteInt64LittleEndian(payload.AsSpan(at), sample.QpcTicks);
|
||||
int countAt = at + 8;
|
||||
at += _sampleHeaderBytes;
|
||||
ushort count = 0;
|
||||
foreach (AdvancedReading reading in readings)
|
||||
{
|
||||
if (reading.Series is null || !indexOf.TryGetValue(reading.Series, out ushort index))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(payload.AsSpan(at), index);
|
||||
BinaryPrimitives.WriteDoubleLittleEndian(payload.AsSpan(at + 2), reading.Value);
|
||||
at += _readingBytes;
|
||||
count++;
|
||||
}
|
||||
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(payload.AsSpan(countAt), count);
|
||||
}
|
||||
|
||||
return at == payload.Length ? payload : payload[..at];
|
||||
}
|
||||
|
||||
private static bool TryReadNames(ReadOnlySpan<byte> payload, ref int at, out string[] names)
|
||||
{
|
||||
names = [];
|
||||
if (payload.Length - at < 2)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
int count = BinaryPrimitives.ReadUInt16LittleEndian(payload[at..]);
|
||||
at += 2;
|
||||
string[] read = new string[count];
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
if (payload.Length - at < 2)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
int length = BinaryPrimitives.ReadUInt16LittleEndian(payload[at..]);
|
||||
at += 2;
|
||||
if (length is 0 or > _maxNameBytes || payload.Length - at < length)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
read[i] = Encoding.UTF8.GetString(payload.Slice(at, length));
|
||||
at += length;
|
||||
}
|
||||
|
||||
names = read;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -35,4 +35,18 @@ internal enum PartialChunkType
|
||||
/// read, so a beta.11 <c>.partial</c> recovers (without game memory, which it never had).
|
||||
/// </summary>
|
||||
SensorsWide = 8,
|
||||
|
||||
/// <summary>
|
||||
/// The advanced readings of the samples of the <see cref="SensorsWide"/> chunk before it (owner decision D101):
|
||||
/// <c>AdvancedSampleCodec</c> — the names used, then per sample its QPC and its (name, value) pairs. Written only
|
||||
/// when a sample of the batch carries any, so a session recorded with the option off has none.
|
||||
/// </summary>
|
||||
SensorsAdvanced = 9,
|
||||
|
||||
/// <summary>
|
||||
/// UTF-8 JSON of the session's advanced context — the PC's facts, its own, its series' directory, each source's
|
||||
/// state (<c>Application.Advanced.AdvancedJson.OfContext</c>) — so a session that is recovered keeps them. The
|
||||
/// last one wins.
|
||||
/// </summary>
|
||||
AdvancedContext = 10,
|
||||
}
|
||||
@@ -5,6 +5,7 @@ using System.Buffers.Binary;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using FrameLedger.Application.Advanced;
|
||||
using FrameLedger.Application.Recording;
|
||||
using FrameLedger.Application.Telemetry;
|
||||
using FrameLedger.Shared;
|
||||
@@ -145,6 +146,7 @@ public static class PartialSessionFile
|
||||
private readonly List<long> _touches = [];
|
||||
private readonly List<PartialNote> _notes = [];
|
||||
private PartialTick? _tick;
|
||||
private string? _advancedContext;
|
||||
|
||||
public bool Apply(PartialChunkType type, ReadOnlySpan<byte> payload)
|
||||
{
|
||||
@@ -162,7 +164,15 @@ public static class PartialSessionFile
|
||||
PartialChunkType.Tick => Tick(payload),
|
||||
PartialChunkType.Note => Note(payload),
|
||||
PartialChunkType.Touches => Int64s(payload, _touches),
|
||||
_ => false,
|
||||
PartialChunkType.SensorsAdvanced => AdvancedSensors(payload),
|
||||
PartialChunkType.AdvancedContext => AdvancedContext(payload),
|
||||
|
||||
// A type this build does not know, in a chunk whose length and checksum are right (TryReadChunk has
|
||||
// verified both): a newer build wrote it, and it is passed over (owner decision D106, 2026-11-11).
|
||||
// Until then it ended the read, so a build one release older lost everything after the first new
|
||||
// chunk - where a chunk it does know and cannot read still ends it, because that is a torn or a
|
||||
// wrong file, not a newer one.
|
||||
_ => true,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -172,6 +182,7 @@ public static class PartialSessionFile
|
||||
Records = _records,
|
||||
GapBefore = _gaps,
|
||||
Sensors = _sensors,
|
||||
AdvancedContextJson = _advancedContext,
|
||||
TouchQpc = _touches,
|
||||
Notes = _notes,
|
||||
LastTick = _tick,
|
||||
@@ -263,6 +274,40 @@ public static class PartialSessionFile
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The advanced readings of samples already read: each is attached to the sample with its QPC — the last one
|
||||
/// that has none yet, since the chunk follows the sensor chunk of the same flush. A reading whose sample is not
|
||||
/// there is left out; it has no tick to belong to.
|
||||
/// </summary>
|
||||
private bool AdvancedSensors(ReadOnlySpan<byte> payload)
|
||||
{
|
||||
var read = new List<(long Qpc, IReadOnlyList<AdvancedReading> Readings)>();
|
||||
if (!AdvancedSampleCodec.TryRead(payload, read))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach ((long qpc, IReadOnlyList<AdvancedReading> readings) in read)
|
||||
{
|
||||
for (int i = _sensors.Count - 1; i >= 0; i--)
|
||||
{
|
||||
if (_sensors[i].QpcTicks == qpc && _sensors[i].Advanced is null)
|
||||
{
|
||||
_sensors[i] = _sensors[i] with { Advanced = readings };
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private bool AdvancedContext(ReadOnlySpan<byte> payload)
|
||||
{
|
||||
_advancedContext = Encoding.UTF8.GetString(payload);
|
||||
return true;
|
||||
}
|
||||
|
||||
private bool Tick(ReadOnlySpan<byte> payload)
|
||||
{
|
||||
int stateBytes = Marshal.SizeOf<FlWriterState>();
|
||||
@@ -353,6 +398,19 @@ public static class PartialSessionFile
|
||||
}
|
||||
|
||||
Append(PartialChunkType.SensorsWide, payload);
|
||||
|
||||
// The advanced readings of the same samples, in a chunk of their own after it - and only when there are
|
||||
// any, so with the option off the file is byte for byte what it was (D101).
|
||||
if (AdvancedSampleCodec.Write(samples) is byte[] advanced)
|
||||
{
|
||||
Append(PartialChunkType.SensorsAdvanced, advanced);
|
||||
}
|
||||
}
|
||||
|
||||
public void AppendAdvancedContext(string json)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(json);
|
||||
Append(PartialChunkType.AdvancedContext, Encoding.UTF8.GetBytes(json));
|
||||
}
|
||||
|
||||
public void AppendTick(PartialTick tick)
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
|
||||
|
||||
using System.Collections.Concurrent;
|
||||
using FrameLedger.Application.Advanced;
|
||||
using FrameLedger.Application.Telemetry;
|
||||
|
||||
namespace FrameLedger.Infrastructure.Telemetry;
|
||||
@@ -41,6 +42,12 @@ public sealed class TelemetryPoller : ITelemetryPoller
|
||||
|
||||
private readonly bool _ownsSource;
|
||||
|
||||
// Advanced metrics (owner decision D101): the Agent's one shared reader, held while this poller runs and never
|
||||
// owned by it. Null when the option is off - then nothing below does anything, and a sample is what it always was.
|
||||
private readonly IAdvancedHardware? _advanced;
|
||||
private IDisposable? _advancedHold;
|
||||
private AdvancedSnapshot? _lastAdvanced;
|
||||
|
||||
private Thread? _thread;
|
||||
private int _queued;
|
||||
private long _dropped;
|
||||
@@ -56,12 +63,14 @@ public sealed class TelemetryPoller : ITelemetryPoller
|
||||
/// </param>
|
||||
/// <param name="system">The machine beside the GPU, read on the same tick (2026-09-21); owned and disposed with <paramref name="source"/> when <paramref name="ownsSource"/> is set. Null composes none, and every sample's <see cref="TelemetrySample.System"/> is empty.</param>
|
||||
/// <param name="game">The game process's own memory (beta.12, D43), read on the same tick for the process <see cref="Follow"/> named; owned and disposed with the others when <paramref name="ownsSource"/> is set. Null composes none, and every sample's <see cref="TelemetrySample.Game"/> is empty.</param>
|
||||
/// <param name="advanced">The Agent's shared reader of advanced metrics (owner decision D101), held while this poller runs and never owned by it: each of its ticks is attached to one sample. Null - the option is off - composes none, and every sample's <see cref="TelemetrySample.Advanced"/> is null.</param>
|
||||
public TelemetryPoller(IGpuTelemetrySource source, TelemetryPollerOptions options, TimeProvider clock, bool ownsSource = false,
|
||||
ISystemTelemetrySource? system = null, IGameMemorySource? game = null)
|
||||
ISystemTelemetrySource? system = null, IGameMemorySource? game = null, IAdvancedHardware? advanced = null)
|
||||
{
|
||||
_source = source ?? throw new ArgumentNullException(nameof(source));
|
||||
_system = system;
|
||||
_game = game;
|
||||
_advanced = advanced;
|
||||
_ownsSource = ownsSource;
|
||||
_options = options ?? throw new ArgumentNullException(nameof(options));
|
||||
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
|
||||
@@ -94,6 +103,9 @@ public sealed class TelemetryPoller : ITelemetryPoller
|
||||
return;
|
||||
}
|
||||
|
||||
// Held from here to Dispose: the shared reader runs while a session samples, and closes some seconds after
|
||||
// the last session and the page have let go (D107).
|
||||
_advancedHold = _advanced?.Acquire();
|
||||
_thread = new Thread(Loop)
|
||||
{
|
||||
IsBackground = true,
|
||||
@@ -116,14 +128,15 @@ public sealed class TelemetryPoller : ITelemetryPoller
|
||||
bool machine = _system is not null && _system.TryRead(out system);
|
||||
ProcessReading game = default;
|
||||
bool measured = _game is not null && _game.TryRead(out game);
|
||||
if (!gpu && !machine && !measured)
|
||||
IReadOnlyList<AdvancedReading>? advanced = NewAdvancedReadings();
|
||||
if (!gpu && !machine && !measured && advanced is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// A tick only the machine or the game answered still carries them: the placeholder names no layer and no field.
|
||||
sample ??= new GpuSample { TakenAt = _clock.GetUtcNow(), Layer = TelemetryLayer.None };
|
||||
_queue.Enqueue(new TelemetrySample(_clock.GetTimestamp(), sample, system, game));
|
||||
_queue.Enqueue(new TelemetrySample(_clock.GetTimestamp(), sample, system, game, advanced));
|
||||
if (Interlocked.Increment(ref _queued) > _options.QueueCapacity && _queue.TryDequeue(out _))
|
||||
{
|
||||
Interlocked.Decrement(ref _queued);
|
||||
@@ -132,6 +145,23 @@ public sealed class TelemetryPoller : ITelemetryPoller
|
||||
}
|
||||
|
||||
/// <summary>The adapter the game presents on (beta.13): handed to the source, which points its layers at it.</summary>
|
||||
/// <summary>
|
||||
/// The readings of the shared advanced reader's latest tick, when that tick is one this poller has not taken yet:
|
||||
/// a read of one reference, never a wait. Each of its ticks is attached to at most one sample — a reading is of
|
||||
/// one tick, and is not repeated on the next because nothing newer arrived. The two run a second apart on their own
|
||||
/// clocks, so now and then a tick of the reader falls between two polls and is not stored; none is stored twice.
|
||||
/// </summary>
|
||||
private IReadOnlyList<AdvancedReading>? NewAdvancedReadings()
|
||||
{
|
||||
if (_advanced?.Latest is not { } snapshot || ReferenceEquals(snapshot, _lastAdvanced))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
_lastAdvanced = snapshot;
|
||||
return snapshot.Readings.Count > 0 ? snapshot.Readings : null;
|
||||
}
|
||||
|
||||
public bool FollowAdapter(ulong luid) => _source is IGpuAdapterSelector selector && selector.SelectAdapter(luid);
|
||||
|
||||
/// <summary>The game process whose memory the next ticks read (beta.12, D43); ignored without a game source.</summary>
|
||||
@@ -166,6 +196,7 @@ public sealed class TelemetryPoller : ITelemetryPoller
|
||||
_stop.Set();
|
||||
_thread?.Join(TimeSpan.FromSeconds(2));
|
||||
_stop.Dispose();
|
||||
_advancedHold?.Dispose();
|
||||
if (_ownsSource)
|
||||
{
|
||||
_source.Dispose();
|
||||
|
||||
@@ -141,6 +141,10 @@ public sealed class SeriesDigestTests
|
||||
|
||||
public ValueTask<IReadOnlyList<SensorBlob>> FindSensorsAsync(long sessionId, CancellationToken ct = default) => inner.FindSensorsAsync(sessionId, ct);
|
||||
|
||||
public ValueTask<IReadOnlyList<SensorBlob>> FindAdvancedSensorsAsync(long sessionId, CancellationToken ct = default) => inner.FindAdvancedSensorsAsync(sessionId, ct);
|
||||
|
||||
public ValueTask<AdvancedSessionRow?> FindAdvancedAsync(long sessionId, CancellationToken ct = default) => inner.FindAdvancedAsync(sessionId, ct);
|
||||
|
||||
public ValueTask<long> InsertFinalizedAsync(FinalizedSession session, CancellationToken ct = default) => inner.InsertFinalizedAsync(session, ct);
|
||||
|
||||
public ValueTask<long?> ResolveOwnerAsync(long gameId, string? exePath, DateTimeOffset startedAt, CancellationToken ct = default) => inner.ResolveOwnerAsync(gameId, exePath, startedAt, ct);
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
|
||||
|
||||
using FluentAssertions;
|
||||
using FrameLedger.Application.Advanced;
|
||||
using FrameLedger.Application.Recording;
|
||||
|
||||
namespace FrameLedger.Application.Tests.Advanced;
|
||||
|
||||
/// <summary>
|
||||
/// The stored form of Advanced metrics (owner decision D102): what is written reads back as it was, what does not fit
|
||||
/// is left out rather than thrown or guessed at, and only what the catalog says is read may be written at all.
|
||||
/// </summary>
|
||||
public sealed class AdvancedJsonTests
|
||||
{
|
||||
private static readonly AdvancedFact[] _facts =
|
||||
[
|
||||
new("nvapi.gpu.rt_cores", Instance: null, AdvancedValue.Of(84)),
|
||||
new("nvapi.gpu.external", Instance: null, AdvancedValue.Of(false)),
|
||||
new("nvapi.gpu.vbios_version", Instance: null, AdvancedValue.OfText("98.03.6c.00.68")),
|
||||
new("nvapi.display.hdr_formats", "1", AdvancedValue.OfTokens("hdr10", "dolby_vision")),
|
||||
new("nvapi.driver.package", Instance: null, AdvancedValue.OfTokens()),
|
||||
new("nvapi.driver.global_profile", Instance: null, AdvancedValue.OfRows([new AdvancedRow("Vertical Sync (0x00A879CF)", "0x60925292", "user_set"), new AdvancedRow("0x10E41DF3", string.Empty)])),
|
||||
];
|
||||
|
||||
private static readonly AdvancedSources _sources = new(AdvancedSourceStatus.NotPresent, NvapiCode: -6, AdvancedSourceStatus.Reading, AdvancedSourceStatus.PawnIoMissing);
|
||||
|
||||
[Fact]
|
||||
public void FactsReadBackAsTheyWereInEveryShape()
|
||||
{
|
||||
IReadOnlyList<AdvancedFact> back = AdvancedJson.ParseFacts(AdvancedJson.OfFacts(_facts));
|
||||
|
||||
back.Should().HaveCount(_facts.Length);
|
||||
back.Select(static f => (f.Id, f.Instance)).Should().Equal(_facts.Select(static f => (f.Id, f.Instance)));
|
||||
back[0].Value.Number.Should().Be(84);
|
||||
back[1].Value.Number.Should().Be(0, "a flag that is off was read");
|
||||
back[2].Value.Text.Should().Be("98.03.6c.00.68");
|
||||
back[3].Value.Tokens.Should().Equal("hdr10", "dolby_vision");
|
||||
back[4].Value.Tokens.Should().BeEmpty("the source answered, and named nothing: that is kept apart from not answering");
|
||||
back[5].Value.Rows.Should().Equal(new AdvancedRow("Vertical Sync (0x00A879CF)", "0x60925292", "user_set"), new AdvancedRow("0x10E41DF3", string.Empty));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheFormIsCamelCaseLeavesOutWhatIsNullAndSpellsAStatusByItsName()
|
||||
{
|
||||
string facts = AdvancedJson.OfFacts([_facts[0]]);
|
||||
string session = AdvancedJson.OfSession([], _sources);
|
||||
|
||||
facts.Should().Be("[{\"id\":\"nvapi.gpu.rt_cores\",\"number\":84}]", "a hash is taken of this text, so it has one form");
|
||||
session.Should().Be("{\"facts\":[],\"sources\":{\"nvapi\":\"NotPresent\",\"nvapiCode\":-6,\"sensors\":\"Reading\",\"elevatedSensors\":\"PawnIoMissing\"}}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ASessionsFactsAndTheStateOfEachSourceReadBack()
|
||||
{
|
||||
(IReadOnlyList<AdvancedFact> facts, AdvancedSources sources) = AdvancedJson.ParseSession(AdvancedJson.OfSession([_facts[0], _facts[3]], _sources));
|
||||
|
||||
facts.Select(static f => f.Id).Should().Equal("nvapi.gpu.rt_cores", "nvapi.display.hdr_formats");
|
||||
sources.Should().Be(_sources);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheDirectoryAndTheStatisticsReadBack()
|
||||
{
|
||||
AdvancedSeriesInfo[] series = [new("adv.lhm.cpu.temperature.intelcpu_0_3", "lhm.cpu.temperature", "Intel Core i7-14700K - CPU Core #3")];
|
||||
var stats = new Dictionary<string, SensorSeriesStats>(StringComparer.Ordinal) { ["adv.nvapi.pstate"] = new SensorSeriesStats(60, 0.5, 0, 0, 8) };
|
||||
|
||||
(IReadOnlyList<AdvancedSeriesInfo> backSeries, int dropped) = AdvancedJson.ParseSeries(AdvancedJson.OfSeries(series, dropped: 3));
|
||||
IReadOnlyDictionary<string, SensorSeriesStats> backStats = AdvancedJson.ParseStats(AdvancedJson.OfStats(stats));
|
||||
|
||||
backSeries.Should().Equal(series);
|
||||
dropped.Should().Be(3);
|
||||
backStats.Should().ContainKey("adv.nvapi.pstate").WhoseValue.Should().Be(new SensorSeriesStats(60, 0.5, 0, 0, 8));
|
||||
FluentActions.Invoking(static () => AdvancedJson.OfSeries([], dropped: -1)).Should().Throw<ArgumentOutOfRangeException>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AWholeContextReadsBackForTheRecoveryOfASession()
|
||||
{
|
||||
var data = new AdvancedSessionData([_facts[0]], [_facts[3]], [new AdvancedSeriesInfo("adv.lhm.gpu.fan.gpu_nvidia_0_1", "lhm.gpu.fan", "RTX 5080 - GPU Fan 1")], _sources);
|
||||
|
||||
AdvancedSessionData back = AdvancedJson.ParseContext(AdvancedJson.OfContext(data))!;
|
||||
|
||||
back.MachineFacts.Should().ContainSingle().Which.Value.Number.Should().Be(84);
|
||||
back.SessionFacts.Should().ContainSingle().Which.Instance.Should().Be("1");
|
||||
back.Series.Should().Equal(data.Series);
|
||||
back.Sources.Should().Be(_sources);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)]
|
||||
[InlineData("")]
|
||||
[InlineData(" ")]
|
||||
[InlineData("not json")]
|
||||
[InlineData("{\"facts\":")]
|
||||
[InlineData("42")]
|
||||
public void WhatIsNotThereOrDoesNotParseReadsAsNothingAndNeverThrows(string? json)
|
||||
{
|
||||
AdvancedJson.ParseFacts(json).Should().BeEmpty();
|
||||
(IReadOnlyList<AdvancedFact> sessionFacts, AdvancedSources sources) = AdvancedJson.ParseSession(json);
|
||||
sessionFacts.Should().BeEmpty();
|
||||
sources.Should().Be(AdvancedSources.Unknown, "nobody said: never read as a source that answers");
|
||||
AdvancedJson.ParseSeries(json).Series.Should().BeEmpty();
|
||||
AdvancedJson.ParseStats(json).Should().BeEmpty();
|
||||
AdvancedJson.ParseContext(json).Should().BeNull();
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("[{\"id\":\"nvapi.gpu.rt_cores\",\"number\":84,\"text\":\"84\"}]", "a value in two shapes")]
|
||||
[InlineData("[{\"id\":\"nvapi.gpu.rt_cores\"}]", "a value in no shape")]
|
||||
[InlineData("[{\"id\":\"\",\"number\":1}]", "no id")]
|
||||
[InlineData("[{\"number\":1}]", "no id at all")]
|
||||
[InlineData("[{\"id\":\"nvapi.gpu.type\",\"tokens\":[\"Discrete\"]}]", "a word that is not a token")]
|
||||
[InlineData("[{\"id\":\"nvapi.gpu.vbios_version\",\"text\":\" \"}]", "empty words")]
|
||||
[InlineData("[{\"id\":\"nvapi.driver.global_profile\",\"rows\":[{\"name\":null,\"value\":\"1\"}]}]", "a row with no name")]
|
||||
[InlineData("[null]", "a null entry")]
|
||||
public void AStoredFactThatDoesNotFitIsLeftOutAndTheOnesBesideItAreKept(string broken, string why)
|
||||
{
|
||||
string json = "[{\"id\":\"nvapi.gpu.core_count\",\"number\":10752}," + broken[1..];
|
||||
|
||||
IReadOnlyList<AdvancedFact> facts = AdvancedJson.ParseFacts(json);
|
||||
|
||||
facts.Should().ContainSingle(why).Which.Id.Should().Be("nvapi.gpu.core_count");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ADirectoryLineThatIsNotAnAdvancedSeriesIsLeftOutAndANegativeCountReadsAsNone()
|
||||
{
|
||||
string json = "{\"series\":[{\"series\":\"gpu_temp\",\"metricId\":\"x\",\"label\":\"y\"},{\"series\":\"adv.nvapi.pstate\",\"metricId\":\"nvapi.pstate\",\"label\":\"P-state\"},null],\"dropped\":-4}";
|
||||
|
||||
(IReadOnlyList<AdvancedSeriesInfo> series, int dropped) = AdvancedJson.ParseSeries(json);
|
||||
|
||||
series.Should().ContainSingle().Which.Series.Should().Be("adv.nvapi.pstate");
|
||||
dropped.Should().Be(0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void OnlyWhatTheCatalogSaysIsReadMayBeStored()
|
||||
{
|
||||
// D104, held once more at the door of the ledger. The readers cannot produce the first three; if one ever
|
||||
// could, it would stop here.
|
||||
AdvancedFact[] mixed =
|
||||
[
|
||||
new("nvapi.gpu.rt_cores", Instance: null, AdvancedValue.Of(84)),
|
||||
new("nvapi.gpu.board_serial", Instance: null, AdvancedValue.OfText("0123456789")),
|
||||
new("nvapi.display.edid", "1", AdvancedValue.OfText("00ffffffffffff00")),
|
||||
new("sl.constants.camera", Instance: null, AdvancedValue.OfText("1.0 2.0 3.0")),
|
||||
new("sl.dlss.presets", Instance: null, AdvancedValue.OfText("K")),
|
||||
new("no.such.metric", Instance: null, AdvancedValue.Of(1)),
|
||||
new("lhm.board.model", Instance: null, AdvancedValue.OfText("ASUS ROG STRIX Z790-E")),
|
||||
];
|
||||
|
||||
AdvancedJson.Storable(mixed).Select(static f => f.Id).Should().Equal("nvapi.gpu.rt_cores", "lhm.board.model");
|
||||
FluentActions.Invoking(static () => AdvancedJson.Storable(null!)).Should().Throw<ArgumentNullException>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheWritersRefuseNull()
|
||||
{
|
||||
FluentActions.Invoking(static () => AdvancedJson.OfFacts(null!)).Should().Throw<ArgumentNullException>();
|
||||
FluentActions.Invoking(static () => AdvancedJson.OfSession([], null!)).Should().Throw<ArgumentNullException>();
|
||||
FluentActions.Invoking(static () => AdvancedJson.OfSeries(null!, 0)).Should().Throw<ArgumentNullException>();
|
||||
FluentActions.Invoking(static () => AdvancedJson.OfStats(null!)).Should().Throw<ArgumentNullException>();
|
||||
FluentActions.Invoking(static () => AdvancedJson.OfContext(null!)).Should().Throw<ArgumentNullException>();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
|
||||
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using FluentAssertions;
|
||||
using FrameLedger.Application.Advanced;
|
||||
using FrameLedger.Application.Capture;
|
||||
using FrameLedger.Application.Persistence;
|
||||
using FrameLedger.Application.Recording;
|
||||
using FrameLedger.Application.Telemetry;
|
||||
using FrameLedger.Domain.Sessions;
|
||||
|
||||
namespace FrameLedger.Application.Tests.Recording;
|
||||
|
||||
/// <summary>
|
||||
/// What a session stores of Advanced metrics (owner decision D102): a series per advanced reading, aligned to the
|
||||
/// sensors' ticks with NaN where a tick had none; the row of its facts, statistics and directory; and nothing at all
|
||||
/// when the option was off.
|
||||
/// </summary>
|
||||
public sealed class AdvancedSessionBuilderTests
|
||||
{
|
||||
private static readonly AdvancedSources _sources = new(AdvancedSourceStatus.Reading, NvapiCode: null, AdvancedSourceStatus.Reading, AdvancedSourceStatus.NotElevated);
|
||||
|
||||
private static readonly AdvancedSessionData _data = new(
|
||||
[new AdvancedFact("nvapi.gpu.rt_cores", Instance: null, AdvancedValue.Of(84))],
|
||||
[new AdvancedFact("nvapi.session.vrr_enabled", Instance: null, AdvancedValue.Of(true))],
|
||||
[new AdvancedSeriesInfo("adv.lhm.board.voltage.lpc_0_7", "lhm.board.voltage", "Chip - -12V"), new AdvancedSeriesInfo("adv.lhm.gpu.fan.gone", "lhm.gpu.fan", "a series no sample carried")],
|
||||
_sources);
|
||||
|
||||
/// <summary>Five ticks: the card's state on every one, a rail on the first and the last, nothing on the third.</summary>
|
||||
private static List<TelemetrySample> Samples()
|
||||
{
|
||||
List<TelemetrySample> samples = SessionFixtures.Sensors(5);
|
||||
samples[0] = samples[0] with { Advanced = [new AdvancedReading("adv.nvapi.pstate", 0), new AdvancedReading("adv.lhm.board.voltage.lpc_0_7", -11.97)] };
|
||||
samples[1] = samples[1] with { Advanced = [new AdvancedReading("adv.nvapi.pstate", 8)] };
|
||||
samples[3] = samples[3] with { Advanced = [new AdvancedReading("adv.nvapi.pstate", 8)] };
|
||||
samples[4] = samples[4] with { Advanced = [new AdvancedReading("adv.nvapi.pstate", 0), new AdvancedReading("adv.lhm.board.voltage.lpc_0_7", -12.03)] };
|
||||
return samples;
|
||||
}
|
||||
|
||||
private static float[] Decode(SensorBlob blob) => MemoryMarshal.Cast<byte, float>(blob.Data.Span).ToArray();
|
||||
|
||||
[Fact]
|
||||
public void WithTheOptionOffNothingIsStoredAtAll()
|
||||
{
|
||||
(IReadOnlyList<SensorBlob> blobs, AdvancedSessionRow? row) = AdvancedSessionBuilder.Build(SessionFixtures.Sensors(5), data: null, new RawSeriesCodec());
|
||||
|
||||
blobs.Should().BeEmpty();
|
||||
row.Should().BeNull("no row is how the App knows the option was off when the session was recorded");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EachSeriesIsAlignedToTheSensorsTicksWithNaNWhereATickHadNoReading()
|
||||
{
|
||||
(IReadOnlyList<SensorBlob> blobs, _) = AdvancedSessionBuilder.Build(Samples(), _data, new RawSeriesCodec());
|
||||
|
||||
blobs.Select(static b => b.Series).Should().Equal("adv.nvapi.pstate", "adv.lhm.board.voltage.lpc_0_7");
|
||||
blobs.Should().OnlyContain(static b => b.Hz == 1 && string.Equals(b.Codec, "raw-le-test", StringComparison.Ordinal));
|
||||
float[] pstate = Decode(blobs[0]);
|
||||
float[] rail = Decode(blobs[1]);
|
||||
pstate.Should().HaveCount(5);
|
||||
pstate[0].Should().Be(0f, "P0 is a state, not a gap");
|
||||
pstate[1].Should().Be(8f);
|
||||
float.IsNaN(pstate[2]).Should().BeTrue("the third tick carried nothing: it is not given the second's value");
|
||||
rail[0].Should().Be(-11.97f, "a negative rail is a reading");
|
||||
rail.Skip(1).Take(3).Should().OnlyContain(static v => float.IsNaN(v), "the sensor library is read every fifth tick");
|
||||
rail[4].Should().Be(-12.03f);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheRowHoldsTheFactsTheSourcesTheStatisticsAndTheDirectoryOfWhatWasStored()
|
||||
{
|
||||
(_, AdvancedSessionRow? built) = AdvancedSessionBuilder.Build(Samples(), _data, new RawSeriesCodec());
|
||||
|
||||
AdvancedSessionRow row = built.Should().BeOfType<AdvancedSessionRow>().Subject;
|
||||
row.MachineFactsJson.Should().Be("[{\"id\":\"nvapi.gpu.rt_cores\",\"number\":84}]");
|
||||
row.MachineHash.Should().Be(Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(row.MachineFactsJson!))));
|
||||
(IReadOnlyList<AdvancedFact> facts, AdvancedSources sources) = AdvancedJson.ParseSession(row.FactsJson);
|
||||
facts.Should().ContainSingle().Which.Id.Should().Be("nvapi.session.vrr_enabled");
|
||||
sources.Should().Be(_sources);
|
||||
IReadOnlyDictionary<string, SensorSeriesStats> stats = AdvancedJson.ParseStats(row.StatsJson);
|
||||
stats["adv.nvapi.pstate"].Should().Be(new SensorSeriesStats(4, 4, 4, 0, 8), "four ticks had a reading; the one that had none is not a zero in the mean");
|
||||
stats["adv.lhm.board.voltage.lpc_0_7"].N.Should().Be(2);
|
||||
stats["adv.lhm.board.voltage.lpc_0_7"].Min.Should().BeApproximately(-12.03, 1e-5);
|
||||
(IReadOnlyList<AdvancedSeriesInfo> directory, int dropped) = AdvancedJson.ParseSeries(row.SeriesJson);
|
||||
directory.Should().ContainSingle("only a series that was stored is in the directory").Which.Label.Should().Be("Chip - -12V");
|
||||
dropped.Should().Be(0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ASessionWithTheOptionOnAndNoReadingStillSaysWhichSourcesAnsweredAndWhy()
|
||||
{
|
||||
var nothing = new AdvancedSessionData([], [], [], new AdvancedSources(AdvancedSourceStatus.NotPresent, NvapiCode: -6, AdvancedSourceStatus.Faulted, AdvancedSourceStatus.NotElevated));
|
||||
|
||||
(IReadOnlyList<SensorBlob> blobs, AdvancedSessionRow? row) = AdvancedSessionBuilder.Build(SessionFixtures.Sensors(5), nothing, new RawSeriesCodec());
|
||||
|
||||
blobs.Should().BeEmpty();
|
||||
AdvancedSessionRow stored = row.Should().BeOfType<AdvancedSessionRow>("the option was on: what is stored is that nothing answered, and why").Subject;
|
||||
stored.MachineFactsJson.Should().BeNull();
|
||||
stored.MachineHash.Should().BeNull();
|
||||
stored.StatsJson.Should().BeNull();
|
||||
AdvancedJson.ParseSession(stored.FactsJson).Sources.Nvapi.Should().Be(AdvancedSourceStatus.NotPresent);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TwoSessionsOnTheSamePcHaveTheSameMachineHashAndAChangedFactChangesIt()
|
||||
{
|
||||
AdvancedSessionRow first = AdvancedSessionBuilder.Build(Samples(), _data, new RawSeriesCodec()).Row!;
|
||||
AdvancedSessionRow second = AdvancedSessionBuilder.Build(SessionFixtures.Sensors(3), _data with { SessionFacts = [] }, new RawSeriesCodec()).Row!;
|
||||
AdvancedSessionRow changed = AdvancedSessionBuilder.Build(Samples(), _data with { MachineFacts = [new AdvancedFact("nvapi.gpu.rt_cores", Instance: null, AdvancedValue.Of(96))] }, new RawSeriesCodec()).Row!;
|
||||
|
||||
second.MachineHash.Should().Be(first.MachineHash, "the hash is of the PC's facts alone, so every session on it finds one row");
|
||||
changed.MachineHash.Should().NotBe(first.MachineHash);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AFactTheCatalogDoesNotSayIsReadNeverReachesTheRow()
|
||||
{
|
||||
// D104 at the door of the ledger.
|
||||
AdvancedSessionData leaky = _data with
|
||||
{
|
||||
MachineFacts = [.. _data.MachineFacts, new AdvancedFact("nvapi.gpu.board_serial", Instance: null, AdvancedValue.OfText("0123456789"))],
|
||||
SessionFacts = [.. _data.SessionFacts, new AdvancedFact("sl.constants.camera", Instance: null, AdvancedValue.OfText("1 2 3"))],
|
||||
};
|
||||
|
||||
AdvancedSessionRow row = AdvancedSessionBuilder.Build(Samples(), leaky, new RawSeriesCodec()).Row!;
|
||||
|
||||
row.MachineFactsJson.Should().NotContain("board_serial").And.NotContain("0123456789");
|
||||
row.FactsJson.Should().NotContain("camera");
|
||||
row.MachineHash.Should().Be(AdvancedSessionBuilder.Build(Samples(), _data, new RawSeriesCodec()).Row!.MachineHash, "what is not stored does not change the hash");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ANameWithoutThePrefixANonNumberAndASeriesBeyondTheMostAreNotStored()
|
||||
{
|
||||
List<TelemetrySample> samples = SessionFixtures.Sensors(2);
|
||||
var many = new List<AdvancedReading> { new("gpu_temp", 99), new("adv.nvapi.pstate", double.NaN), new("adv.nvapi.clock.video", double.PositiveInfinity) };
|
||||
many.AddRange(Enumerable.Range(0, AdvancedSessionBuilder.MaxSeries + 3).Select(static i => new AdvancedReading($"adv.lhm.cpu.load.c_{i}", i)));
|
||||
samples[0] = samples[0] with { Advanced = many };
|
||||
|
||||
(IReadOnlyList<SensorBlob> blobs, AdvancedSessionRow? row) = AdvancedSessionBuilder.Build(samples, _data, new RawSeriesCodec());
|
||||
|
||||
blobs.Should().HaveCount(AdvancedSessionBuilder.MaxSeries);
|
||||
blobs.Should().NotContain(static b => string.Equals(b.Series, "gpu_temp", StringComparison.Ordinal), "a name without the prefix could be taken for a fixed series");
|
||||
Decode(blobs.Single(static b => string.Equals(b.Series, "adv.nvapi.pstate", StringComparison.Ordinal))).Should().OnlyContain(static v => float.IsNaN(v), "a value that is not a number is not a reading");
|
||||
AdvancedJson.ParseSeries(row!.SeriesJson).Dropped.Should().Be(5, "two series were named before the first of the family, so five of them did not fit: counted, not stored");
|
||||
AdvancedJson.ParseStats(row.StatsJson).Should().NotContainKey("adv.nvapi.pstate", "a series with no reading has no statistics");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheFinalizerStoresThemWithBothTiersAndLeavesAFixedSessionAsItWas()
|
||||
{
|
||||
var finalizer = new SessionFinalizer(new FakeSessionRepository(), new RawSeriesCodec());
|
||||
FinalizeInput off = new() { Skeleton = SessionFixtures.Skeleton(tier: CaptureTier.NotHooked), Sensors = SessionFixtures.Sensors(5) };
|
||||
FinalizeInput on = off with { Sensors = Samples(), Advanced = _data };
|
||||
|
||||
FinalizedSession before = finalizer.Build(off);
|
||||
FinalizedSession unhooked = finalizer.Build(on);
|
||||
FinalizedSession hooked = finalizer.Build(on with
|
||||
{
|
||||
Skeleton = SessionFixtures.Skeleton(),
|
||||
Hooked = SessionFixtures.Hooked(SessionFixtures.Stream(600, Shared.FlMeasured.OutputRes | Shared.FlMeasured.PresentArgs)),
|
||||
});
|
||||
|
||||
before.Advanced.Should().BeNull();
|
||||
before.Sensors.Should().NotContain(static s => s.Series.StartsWith("adv.", StringComparison.Ordinal));
|
||||
unhooked.Advanced.Should().NotBeNull("a session that was not hooked has them all the same: the Agent reads them, not a hook");
|
||||
unhooked.Sensors.Select(static s => s.Series).Should().StartWith(before.Sensors.Select(static s => s.Series), "the fixed series come first and are untouched");
|
||||
unhooked.Sensors.Select(static s => s.Series).Should().EndWith(["adv.nvapi.pstate", "adv.lhm.board.voltage.lpc_0_7"]);
|
||||
unhooked.Row.Should().BeEquivalentTo(before.Row, "no column of sessions knows of them (D102)");
|
||||
hooked.Advanced.Should().NotBeNull();
|
||||
hooked.Sensors.Should().Contain(static s => string.Equals(s.Series, "adv.nvapi.pstate", StringComparison.Ordinal));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheWriterPutsTheContextInTheFileOnceAndAgainOnlyWhenItChanges()
|
||||
{
|
||||
var store = new FakePartialSessionStore();
|
||||
var entry = (FakePartialSessionStore.Entry)store.Create(new PartialHeader
|
||||
{
|
||||
SessionGuid = Guid.NewGuid(),
|
||||
StartedAt = SessionFixtures.StartedAt,
|
||||
QpcEpoch = SessionFixtures.QpcEpoch,
|
||||
QpcFrequency = SessionFixtures.QpcFrequency,
|
||||
GameId = 7,
|
||||
SnapshotId = 3,
|
||||
ExePath = @"C:\Games\T\t.exe",
|
||||
Pid = 1,
|
||||
Tier = CaptureTier.NotHooked,
|
||||
Mode = CaptureMode.Attach,
|
||||
});
|
||||
using var writer = new PartialSessionWriter(entry, TimeProvider.System, TimeSpan.Zero);
|
||||
|
||||
writer.Advanced.Should().BeNull();
|
||||
writer.OnTick(CaptureProgress.Unhooked, force: true);
|
||||
entry.AdvancedContexts.Should().BeEmpty("with the option off the file carries none");
|
||||
|
||||
writer.SetAdvancedContext(_data);
|
||||
writer.OnTick(CaptureProgress.Unhooked, force: true);
|
||||
writer.OnTick(CaptureProgress.Unhooked, force: true);
|
||||
entry.AdvancedContexts.Should().ContainSingle("a context that stays the same is in the file once");
|
||||
|
||||
writer.SetAdvancedContext(_data with { SessionFacts = [] });
|
||||
writer.OnTick(CaptureProgress.Unhooked, force: true);
|
||||
|
||||
entry.AdvancedContexts.Should().HaveCount(2);
|
||||
writer.Advanced!.SessionFacts.Should().BeEmpty();
|
||||
AdvancedJson.ParseContext(entry.AdvancedContexts[^1])!.MachineFacts.Should().ContainSingle();
|
||||
FluentActions.Invoking(() => writer.SetAdvancedContext(null!)).Should().Throw<ArgumentNullException>();
|
||||
}
|
||||
}
|
||||
@@ -95,6 +95,10 @@ internal sealed class FakePartialSessionStore : IPartialSessionStore
|
||||
|
||||
public void AppendNote(DateTimeOffset at, string text) => Notes.Add(new PartialNote(at, text));
|
||||
|
||||
public List<string> AdvancedContexts { get; } = [];
|
||||
|
||||
public void AppendAdvancedContext(string json) => AdvancedContexts.Add(json);
|
||||
|
||||
public void Dispose() => Disposed = true;
|
||||
|
||||
public PartialSession ToSession() => new()
|
||||
@@ -103,6 +107,7 @@ internal sealed class FakePartialSessionStore : IPartialSessionStore
|
||||
Records = Records,
|
||||
GapBefore = Gaps,
|
||||
Sensors = Sensors,
|
||||
AdvancedContextJson = AdvancedContexts.Count == 0 ? null : AdvancedContexts[^1],
|
||||
TouchQpc = Touches,
|
||||
Notes = Notes,
|
||||
LastTick = LastTick,
|
||||
|
||||
@@ -126,5 +126,15 @@ internal sealed class FakeSessionRepository : ISessionRepository
|
||||
ValueTask.FromResult(sessionId >= 1 && sessionId <= Stored.Count ? Stored[(int)sessionId - 1].Segments : []);
|
||||
|
||||
public ValueTask<IReadOnlyList<SensorBlob>> FindSensorsAsync(long sessionId, CancellationToken ct = default) =>
|
||||
ValueTask.FromResult(sessionId >= 1 && sessionId <= Stored.Count ? Stored[(int)sessionId - 1].Sensors : []);
|
||||
ValueTask.FromResult<IReadOnlyList<SensorBlob>>(sessionId >= 1 && sessionId <= Stored.Count
|
||||
? [.. Stored[(int)sessionId - 1].Sensors.Where(static s => !s.Series.StartsWith("adv.", StringComparison.Ordinal))]
|
||||
: []);
|
||||
|
||||
public ValueTask<IReadOnlyList<SensorBlob>> FindAdvancedSensorsAsync(long sessionId, CancellationToken ct = default) =>
|
||||
ValueTask.FromResult<IReadOnlyList<SensorBlob>>(sessionId >= 1 && sessionId <= Stored.Count
|
||||
? [.. Stored[(int)sessionId - 1].Sensors.Where(static s => string.Equals(s.Series, "t_ms", StringComparison.Ordinal) || s.Series.StartsWith("adv.", StringComparison.Ordinal))]
|
||||
: []);
|
||||
|
||||
public ValueTask<AdvancedSessionRow?> FindAdvancedAsync(long sessionId, CancellationToken ct = default) =>
|
||||
ValueTask.FromResult(sessionId >= 1 && sessionId <= Stored.Count ? Stored[(int)sessionId - 1].Advanced : null);
|
||||
}
|
||||
@@ -2,7 +2,9 @@
|
||||
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
|
||||
|
||||
using FluentAssertions;
|
||||
using FrameLedger.Application.Advanced;
|
||||
using FrameLedger.Application.Recording;
|
||||
using FrameLedger.Application.Telemetry;
|
||||
using FrameLedger.Domain.Sessions;
|
||||
using FrameLedger.Shared;
|
||||
|
||||
@@ -210,4 +212,46 @@ public sealed class PartialRecoveryTests
|
||||
first.Should().BeEmpty();
|
||||
second.Should().BeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ARecoveredSessionKeepsItsAdvancedReadingsAndItsContextAndOneWithoutAnyStoresNone()
|
||||
{
|
||||
// Owner decision D101: the file carries the readings beside each sample and the context in a chunk of its own,
|
||||
// so an Agent that died mid-session loses neither. A file with no context was recorded with the option off.
|
||||
(PartialRecovery recovery, FakePartialSessionStore store, FakeSessionRepository repo) = Make();
|
||||
var on = Guid.NewGuid();
|
||||
var off = Guid.NewGuid();
|
||||
List<TelemetrySample> sensors = SessionFixtures.Sensors(40);
|
||||
sensors[0] = sensors[0] with { Advanced = [new AdvancedReading("adv.nvapi.pstate", 0)] };
|
||||
sensors[5] = sensors[5] with { Advanced = [new AdvancedReading("adv.nvapi.pstate", 8)] };
|
||||
var data = new AdvancedSessionData(
|
||||
[new AdvancedFact("nvapi.gpu.rt_cores", Instance: null, AdvancedValue.Of(84))],
|
||||
[],
|
||||
[],
|
||||
new AdvancedSources(AdvancedSourceStatus.Reading, NvapiCode: null, AdvancedSourceStatus.Reading, AdvancedSourceStatus.NotElevated));
|
||||
foreach (Guid guid in (Guid[])[on, off])
|
||||
{
|
||||
var entry = (FakePartialSessionStore.Entry)store.Create(Header(guid));
|
||||
entry.AppendRecords(0, SessionFixtures.Stream(4_000, FlMeasured.OutputRes | FlMeasured.PresentArgs).ToArray());
|
||||
entry.AppendSensors((guid == on ? sensors : SessionFixtures.Sensors(40)).ToArray());
|
||||
if (guid == on)
|
||||
{
|
||||
entry.AppendAdvancedContext(AdvancedJson.OfContext(data));
|
||||
}
|
||||
|
||||
entry.AppendTick(new PartialTick(400, 400, 0, 0, 2, SessionFixtures.StartedAt.AddSeconds(41).ToUnixTimeMilliseconds(),
|
||||
new FlWriterState { Status = 1, HooksInstalledMask = 1, FaultCount = 0 }));
|
||||
}
|
||||
|
||||
IReadOnlyList<RecoveryOutcome> outcomes = await recovery.RecoverAsync(TestContext.Current.CancellationToken);
|
||||
|
||||
outcomes.Should().HaveCount(2).And.OnlyContain(static o => o.Status == RecoveryStatus.Recovered);
|
||||
Persistence.FinalizedSession withThem = repo.Stored.Single(s => s.Row.SessionGuid == on);
|
||||
Persistence.FinalizedSession without = repo.Stored.Single(s => s.Row.SessionGuid == off);
|
||||
withThem.Advanced.Should().NotBeNull();
|
||||
withThem.Advanced!.MachineFactsJson.Should().Contain("nvapi.gpu.rt_cores");
|
||||
withThem.Sensors.Should().Contain(static s => string.Equals(s.Series, "adv.nvapi.pstate", StringComparison.Ordinal));
|
||||
without.Advanced.Should().BeNull();
|
||||
without.Sensors.Should().NotContain(static s => s.Series.StartsWith("adv.", StringComparison.Ordinal));
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,8 @@ internal sealed class RawSeriesCodec : ISeriesCodec
|
||||
|
||||
public byte[] EncodeFloat32(ReadOnlySpan<float> values) => MemoryMarshal.AsBytes(values).ToArray();
|
||||
|
||||
public byte[] EncodeSparseFloat32(ReadOnlySpan<float> values) => MemoryMarshal.AsBytes(values).ToArray();
|
||||
|
||||
public byte[] EncodeUInt16(ReadOnlySpan<ushort> values) => MemoryMarshal.AsBytes(values).ToArray();
|
||||
|
||||
public byte[] EncodeUInt32(ReadOnlySpan<uint> values) => MemoryMarshal.AsBytes(values).ToArray();
|
||||
|
||||
@@ -89,4 +89,33 @@ public sealed class SeriesCodecRoundTripTests
|
||||
|
||||
[Fact]
|
||||
public void TheCodecTagIsTheOneTheSchemaStores() => SeriesCodec.Tag.Should().Be("deflate-le-v1");
|
||||
|
||||
[Fact]
|
||||
public void ASparseSeriesKeepsItsGapsAsNaNAndItsNegativeValues()
|
||||
{
|
||||
// Owner decision D102: an advanced series has ticks with no reading, and may be negative, so -1 cannot mark a gap.
|
||||
float[] rail = [-11.97f, float.NaN, float.NaN, -12.03f, 0f];
|
||||
|
||||
float[] back = SeriesCodec.DecodeFloat32(SeriesCodec.EncodeSparseFloat32(rail));
|
||||
|
||||
back.Should().HaveCount(5);
|
||||
back[0].Should().Be(-11.97f);
|
||||
float.IsNaN(back[1]).Should().BeTrue();
|
||||
float.IsNaN(back[2]).Should().BeTrue();
|
||||
back[3].Should().Be(-12.03f);
|
||||
back[4].Should().Be(0f, "a zero is a reading");
|
||||
new DeflateSeriesCodec().EncodeSparseFloat32(rail).Should().Equal(SeriesCodec.EncodeSparseFloat32(rail));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ASparseSeriesStillRefusesAnInfinityAndTheOrdinaryEncoderStillRefusesNaN()
|
||||
{
|
||||
Action infinite = () => SeriesCodec.EncodeSparseFloat32([1f, float.PositiveInfinity]);
|
||||
Action nan = () => SeriesCodec.EncodeFloat32([1f, float.NaN]);
|
||||
|
||||
infinite.Should().Throw<ArgumentException>().WithMessage("*infinity at index 1*");
|
||||
nan.Should().Throw<ArgumentException>("the rule for frame times is not relaxed by the second encoder");
|
||||
SeriesCodec.DecodeFloat32(SeriesCodec.EncodeSparseFloat32([])).Should().BeEmpty();
|
||||
FluentActions.Invoking(static () => SeriesCodec.EncodeSparseFloat32(null!)).Should().Throw<ArgumentNullException>();
|
||||
}
|
||||
}
|
||||
@@ -23,7 +23,7 @@ public sealed class LedgerDatabaseTests
|
||||
private static readonly string[] _tables =
|
||||
[
|
||||
"schema_migrations", "games", "hardware_snapshots", "sessions", "session_segments", "frame_blobs",
|
||||
"sensor_blobs", "session_annotations", "settings", "legal_acceptance",
|
||||
"sensor_blobs", "session_annotations", "settings", "legal_acceptance", "machine_profiles", "session_advanced",
|
||||
];
|
||||
|
||||
[Fact]
|
||||
@@ -125,6 +125,19 @@ public sealed class LedgerDatabaseTests
|
||||
{
|
||||
foreach (string sql in MigrationRunner.Scripts().Where(p => p.Key > version).OrderByDescending(static p => p.Key).Select(static p => p.Value))
|
||||
{
|
||||
// 0023 is the first script since 0001 that creates a table: what a later script created is dropped, an
|
||||
// index before its table and the tables in the reverse of the order they were created in (the second one
|
||||
// references the first).
|
||||
foreach (Match m in Regex.Matches(sql, @"^CREATE\s+INDEX\s+(?<name>\w+)", RegexOptions.IgnoreCase | RegexOptions.Multiline, TimeSpan.FromSeconds(1)))
|
||||
{
|
||||
await c.ExecuteAsync(new CommandDefinition($"DROP INDEX IF EXISTS {m.Groups["name"].Value}", cancellationToken: Ct)).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
foreach (Match m in Regex.Matches(sql, @"^CREATE\s+TABLE\s+(?<name>\w+)", RegexOptions.IgnoreCase | RegexOptions.Multiline, TimeSpan.FromSeconds(1)).Reverse())
|
||||
{
|
||||
await c.ExecuteAsync(new CommandDefinition($"DROP TABLE IF EXISTS {m.Groups["name"].Value}", cancellationToken: Ct)).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
foreach (Match m in Regex.Matches(sql, @"ALTER\s+TABLE\s+(?<table>\w+)\s+ADD\s+COLUMN\s+(?<column>\w+)", RegexOptions.IgnoreCase,
|
||||
TimeSpan.FromSeconds(1)).Reverse())
|
||||
{
|
||||
@@ -901,4 +914,65 @@ public sealed class LedgerDatabaseTests
|
||||
scripts.Keys.Should().BeInAscendingOrder().And.OnlyHaveUniqueItems();
|
||||
scripts[1].Should().Contain("CREATE TABLE games");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Schema 0023 (2026-11-11, owner decisions D101 and D102): two tables of their own for Advanced metrics — the first
|
||||
/// CREATE TABLE since 0001 — and nothing added to <c>sessions</c>. A session written before has no row in either.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task ScriptTwentyThreeCreatesTheTwoAdvancedTablesAndAnEarlierSessionHasNoRow()
|
||||
{
|
||||
await using LedgerFixture f = await LedgerFixture.OpenAsync();
|
||||
MigrationRunner.LatestVersion.Should().BeGreaterThanOrEqualTo(23);
|
||||
long gameId = (await new SqliteGameRepository(f.Db).EnsureAsync(
|
||||
new() { ExePath = @"C:\Games\A\a.exe", SizeBytes = 1, MtimeUnixMs = 2 }, "A", Ct).ConfigureAwait(true)).Id;
|
||||
long snapshotId = await new SqliteHardwareSnapshotRepository(f.Db).EnsureAsync(new HardwareSnapshot { GpuName = "g" }, DateTimeOffset.UnixEpoch, Ct)
|
||||
.ConfigureAwait(true);
|
||||
string path = f.Path;
|
||||
await f.Db.DisposeAsync().ConfigureAwait(true);
|
||||
var c22 = new SqliteConnection(new SqliteConnectionStringBuilder { DataSource = path, Pooling = false }.ToString());
|
||||
await using (c22.ConfigureAwait(true))
|
||||
{
|
||||
await c22.OpenAsync(Ct).ConfigureAwait(true);
|
||||
await RewindToAsync(c22, 22).ConfigureAwait(true);
|
||||
(await c22.ExecuteScalarAsync<long>(new CommandDefinition(
|
||||
"SELECT COUNT(*) FROM sqlite_master WHERE name IN ('machine_profiles', 'session_advanced', 'ix_session_advanced_profile')", cancellationToken: Ct)).ConfigureAwait(true))
|
||||
.Should().Be(0, "a ledger at schema 22 has neither table");
|
||||
await c22.ExecuteAsync(new CommandDefinition(
|
||||
"INSERT INTO sessions (session_guid, game_id, snapshot_id, started_at, ended_at, duration_s, qpc_epoch, qpc_frequency, capture_tier, capture_mode, exit_status, frame_count, app_frame_count, displayed_frame_count, dropped_frames) "
|
||||
+ "VALUES ('00000000-0000-0000-0000-000000000023', @gameId, @snapshotId, 0, 60000, 60, 0, 10000000, 1, 'attach', 'normal', 6000, 6000, 6000, 0)",
|
||||
new { gameId, snapshotId }, cancellationToken: Ct)).ConfigureAwait(true);
|
||||
}
|
||||
|
||||
LedgerDatabase migrated = await LedgerDatabase.OpenAsync(path, ct: Ct).ConfigureAwait(true);
|
||||
await using (migrated.ConfigureAwait(true))
|
||||
{
|
||||
migrated.SchemaVersion.Should().Be(MigrationRunner.LatestVersion);
|
||||
IReadOnlyList<string> profileColumns = await migrated.ReadAsync(async (c, ct) => (IReadOnlyList<string>)[.. await c.QueryAsync<string>(new CommandDefinition(
|
||||
"SELECT name FROM pragma_table_info('machine_profiles') ORDER BY cid", cancellationToken: ct)).ConfigureAwait(false)], Ct).ConfigureAwait(true);
|
||||
IReadOnlyList<string> sessionColumns = await migrated.ReadAsync(async (c, ct) => (IReadOnlyList<string>)[.. await c.QueryAsync<string>(new CommandDefinition(
|
||||
"SELECT name FROM pragma_table_info('session_advanced') ORDER BY cid", cancellationToken: ct)).ConfigureAwait(false)], Ct).ConfigureAwait(true);
|
||||
profileColumns.Should().Equal("id", "hash", "facts_json", "captured_at");
|
||||
sessionColumns.Should().Equal("session_id", "machine_profile_id", "facts_json", "stats_json", "series_json");
|
||||
|
||||
var sessions = new SqliteSessionRepository(migrated);
|
||||
SessionRow before = (await sessions.FindAsync(Guid.Parse("00000000-0000-0000-0000-000000000023"), Ct).ConfigureAwait(true))!;
|
||||
(await sessions.FindAdvancedAsync(before.Id, Ct).ConfigureAwait(true)).Should().BeNull("a session recorded before Advanced metrics existed has none, and is never given any");
|
||||
(await sessions.FindAdvancedSensorsAsync(before.Id, Ct).ConfigureAwait(true)).Should().BeEmpty();
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ScriptTwentyThreeAddsNoColumnToSessionsAndNamesNoIdentifier()
|
||||
{
|
||||
// D102: every read of a sessions row, the JSON export and the bug bundle carry the whole row. D104: neither
|
||||
// table has a column for a serial number, a unique id, an EDID or another program's process id.
|
||||
string sql = MigrationRunner.Scripts()[23];
|
||||
string statements = string.Join('\n', sql.Split('\n').Where(static l => !l.TrimStart().StartsWith("--", StringComparison.Ordinal)).Select(static l => l.Split("--")[0]));
|
||||
|
||||
statements.Should().NotContain("ALTER TABLE");
|
||||
statements.Should().NotContainAny("serial", "uuid", "edid", "pid");
|
||||
Regex.Matches(statements, @"CREATE\s+TABLE\s+(?<name>\w+)", RegexOptions.ExplicitCapture, TimeSpan.FromSeconds(1)).Select(static m => m.Groups["name"].Value)
|
||||
.Should().Equal("machine_profiles", "session_advanced");
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
|
||||
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using Dapper;
|
||||
using FluentAssertions;
|
||||
using FrameLedger.Application.Persistence;
|
||||
@@ -504,4 +506,108 @@ public sealed class SqliteSessionRepositoryTests
|
||||
(await repo.CountSuccessfulUnderGrantAsync(gameId, "NetEase Yidun", granted.AddMinutes(30), Ct)).Should().Be(1, "a later grant starts its own trial");
|
||||
(await repo.CountSuccessfulUnderGrantAsync(gameId + 1, "NetEase Yidun", granted, Ct)).Should().Be(0);
|
||||
}
|
||||
|
||||
private const string _advancedFacts = "{\"facts\":[{\"id\":\"nvapi.session.vrr_enabled\",\"number\":1}],\"sources\":{\"nvapi\":\"Reading\",\"sensors\":\"Reading\",\"elevatedSensors\":\"NotElevated\"}}";
|
||||
|
||||
private static AdvancedSessionRow Advanced(string? machineFacts = "[{\"id\":\"nvapi.gpu.rt_cores\",\"number\":84}]") => new()
|
||||
{
|
||||
MachineFactsJson = machineFacts,
|
||||
MachineHash = machineFacts is null ? null : Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(machineFacts))),
|
||||
FactsJson = _advancedFacts,
|
||||
StatsJson = "{\"adv.nvapi.pstate\":{\"n\":2,\"mean\":0,\"median\":0,\"min\":0,\"max\":0}}",
|
||||
SeriesJson = "{\"series\":[],\"dropped\":0}",
|
||||
};
|
||||
|
||||
private static SensorBlob[] SensorsWithAdvanced() =>
|
||||
[
|
||||
new() { Series = "t_ms", Hz = 1, Codec = SeriesCodec.Tag, Data = SeriesCodec.EncodeFloat32([0f, 1000f, 2000f]) },
|
||||
new() { Series = "gpu_temp", Hz = 1, Codec = SeriesCodec.Tag, Data = SeriesCodec.EncodeFloat32([60f, 61f, 62f]) },
|
||||
new() { Series = "adv.nvapi.pstate", Hz = 1, Codec = SeriesCodec.Tag, Data = SeriesCodec.EncodeSparseFloat32([0f, float.NaN, 0f]) },
|
||||
new() { Series = "adv.lhm.board.voltage.lpc_0_7", Hz = 1, Codec = SeriesCodec.Tag, Data = SeriesCodec.EncodeSparseFloat32([-11.97f, float.NaN, float.NaN]) },
|
||||
];
|
||||
|
||||
[Fact]
|
||||
public async Task AnAdvancedSessionStoresItsRowAndItsSeriesAndTheFixedReadNeverSeesThem()
|
||||
{
|
||||
// Schema 0023 (owner decision D102). The advanced series are rows of sensor_blobs, and the read every summary
|
||||
// and chart uses leaves them out: they hold NaN and may be negative, which those readers would misread.
|
||||
await using LedgerFixture f = await LedgerFixture.OpenAsync();
|
||||
(long gameId, long snapshotId) = await SeedAsync(f);
|
||||
var repo = new SqliteSessionRepository(f.Db);
|
||||
AdvancedSessionRow advanced = Advanced();
|
||||
|
||||
long id = await repo.InsertFinalizedAsync(new FinalizedSession { Row = Row(gameId, snapshotId), Sensors = SensorsWithAdvanced(), Advanced = advanced }, Ct);
|
||||
|
||||
(await repo.FindAdvancedAsync(id, Ct)).Should().Be(advanced);
|
||||
(await repo.FindSensorsAsync(id, Ct)).Select(static s => s.Series).Should().Equal("gpu_temp", "t_ms");
|
||||
IReadOnlyList<SensorBlob> series = await repo.FindAdvancedSensorsAsync(id, Ct);
|
||||
series.Select(static s => s.Series).Should().Equal("t_ms", "adv.lhm.board.voltage.lpc_0_7", "adv.nvapi.pstate");
|
||||
float[] rail = SeriesCodec.DecodeFloat32(series[1].Data.ToArray());
|
||||
rail[0].Should().Be(-11.97f, "a negative reading is a reading");
|
||||
float.IsNaN(rail[1]).Should().BeTrue("a tick with no reading is NaN");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ASessionRecordedWithTheOptionOffHasNoAdvancedRow()
|
||||
{
|
||||
await using LedgerFixture f = await LedgerFixture.OpenAsync();
|
||||
(long gameId, long snapshotId) = await SeedAsync(f);
|
||||
var repo = new SqliteSessionRepository(f.Db);
|
||||
|
||||
long id = await repo.InsertFinalizedAsync(new FinalizedSession { Row = Row(gameId, snapshotId), Sensors = [.. SensorsWithAdvanced().Take(2)] }, Ct);
|
||||
|
||||
(await repo.FindAdvancedAsync(id, Ct)).Should().BeNull("that absence is how the App says the option was off when it was recorded");
|
||||
(await repo.FindAdvancedSensorsAsync(id, Ct)).Select(static s => s.Series).Should().Equal("t_ms");
|
||||
(await f.Db.ReadAsync((c, ct) => c.ExecuteScalarAsync<long>(new CommandDefinition("SELECT COUNT(*) FROM machine_profiles", cancellationToken: ct)), Ct)).Should().Be(0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TheFactsOfThePcAreStoredOncePerDistinctSet()
|
||||
{
|
||||
await using LedgerFixture f = await LedgerFixture.OpenAsync();
|
||||
(long gameId, long snapshotId) = await SeedAsync(f);
|
||||
var repo = new SqliteSessionRepository(f.Db);
|
||||
DateTimeOffset t0 = DateTimeOffset.FromUnixTimeMilliseconds(1_700_000_000_000);
|
||||
|
||||
long first = await repo.InsertFinalizedAsync(new FinalizedSession { Row = Row(gameId, snapshotId, started: t0), Advanced = Advanced() }, Ct);
|
||||
long second = await repo.InsertFinalizedAsync(new FinalizedSession { Row = Row(gameId, snapshotId, started: t0.AddHours(1)), Advanced = Advanced() }, Ct);
|
||||
long changed = await repo.InsertFinalizedAsync(new FinalizedSession { Row = Row(gameId, snapshotId, started: t0.AddHours(2)), Advanced = Advanced("[{\"id\":\"nvapi.gpu.rt_cores\",\"number\":96}]") }, Ct);
|
||||
long none = await repo.InsertFinalizedAsync(new FinalizedSession { Row = Row(gameId, snapshotId, started: t0.AddHours(3)), Advanced = Advanced(machineFacts: null) }, Ct);
|
||||
|
||||
IReadOnlyList<(long Session, long? Profile)> links = await f.Db.ReadAsync(async (c, ct) => (IReadOnlyList<(long, long?)>)[.. await c.QueryAsync<(long, long?)>(new CommandDefinition(
|
||||
"SELECT session_id, machine_profile_id FROM session_advanced ORDER BY session_id", cancellationToken: ct)).ConfigureAwait(false)], Ct);
|
||||
links.Select(static l => l.Session).Should().Equal(first, second, changed, none);
|
||||
links[0].Profile.Should().NotBeNull().And.Be(links[1].Profile, "the same facts are one row");
|
||||
links[2].Profile.Should().NotBeNull().And.NotBe(links[0].Profile, "a card with other facts is another row");
|
||||
links[3].Profile.Should().BeNull("no source had a fact of the PC");
|
||||
(await f.Db.ReadAsync((c, ct) => c.ExecuteScalarAsync<long>(new CommandDefinition("SELECT COUNT(*) FROM machine_profiles", cancellationToken: ct)), Ct)).Should().Be(2);
|
||||
(await f.Db.ReadAsync((c, ct) => c.ExecuteScalarAsync<long>(new CommandDefinition("SELECT captured_at FROM machine_profiles ORDER BY id LIMIT 1", cancellationToken: ct)), Ct))
|
||||
.Should().Be(t0.ToUnixTimeMilliseconds(), "the first session that had the set dates it");
|
||||
(await repo.FindAdvancedAsync(none, Ct))!.MachineFactsJson.Should().BeNull();
|
||||
(await repo.FindAdvancedAsync(second, Ct))!.MachineFactsJson.Should().Be(Advanced().MachineFactsJson);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeletingASessionTakesItsAdvancedRowAndTheSweepTakesItsSeriesAndKeepsTheRow()
|
||||
{
|
||||
await using LedgerFixture f = await LedgerFixture.OpenAsync();
|
||||
(long gameId, long snapshotId) = await SeedAsync(f);
|
||||
var repo = new SqliteSessionRepository(f.Db);
|
||||
DateTimeOffset t0 = DateTimeOffset.FromUnixTimeMilliseconds(1_700_000_000_000);
|
||||
long older = await repo.InsertFinalizedAsync(new FinalizedSession { Row = Row(gameId, snapshotId, started: t0), Sensors = SensorsWithAdvanced(), Advanced = Advanced() }, Ct);
|
||||
long newer = await repo.InsertFinalizedAsync(new FinalizedSession { Row = Row(gameId, snapshotId, started: t0.AddHours(1)), Sensors = SensorsWithAdvanced(), Advanced = Advanced() }, Ct);
|
||||
|
||||
// Retention keeps the raw series of the last session only: the older one's advanced series go with its others,
|
||||
// and its facts and statistics - aggregates - stay.
|
||||
await repo.SweepRetentionAsync(gameId, keep: 1, Ct);
|
||||
|
||||
(await repo.FindAdvancedSensorsAsync(older, Ct)).Should().BeEmpty();
|
||||
(await repo.FindAdvancedAsync(older, Ct)).Should().NotBeNull("the facts and the statistics outlive the raw series");
|
||||
(await repo.FindAdvancedSensorsAsync(newer, Ct)).Should().HaveCount(3);
|
||||
|
||||
await repo.DeleteSessionsAsync(gameId, Ct);
|
||||
|
||||
(await f.Db.ReadAsync((c, ct) => c.ExecuteScalarAsync<long>(new CommandDefinition("SELECT COUNT(*) FROM session_advanced", cancellationToken: ct)), Ct)).Should().Be(0, "a session deleted takes its row with it");
|
||||
(await f.Db.ReadAsync((c, ct) => c.ExecuteScalarAsync<long>(new CommandDefinition("SELECT COUNT(*) FROM machine_profiles", cancellationToken: ct)), Ct)).Should().Be(1, "a profile no session points to is left, as a hardware snapshot is");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,304 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
|
||||
|
||||
using System.Buffers.Binary;
|
||||
using System.Text;
|
||||
using FluentAssertions;
|
||||
using FrameLedger.Application.Advanced;
|
||||
using FrameLedger.Application.Recording;
|
||||
using FrameLedger.Application.Telemetry;
|
||||
using FrameLedger.Domain.Sessions;
|
||||
using FrameLedger.Infrastructure.Recording;
|
||||
|
||||
namespace FrameLedger.Infrastructure.Tests.Recording;
|
||||
|
||||
/// <summary>
|
||||
/// The <c>.partial</c> and Advanced metrics (owner decisions D101 and D106): a sample's advanced readings and the
|
||||
/// session's context survive the round trip; with the option off the file is byte for byte what it was; a file cut at
|
||||
/// every byte still reads up to its last whole chunk; and a chunk of a type this build does not know is passed over.
|
||||
/// </summary>
|
||||
public sealed class PartialSessionFileAdvancedTests : IDisposable
|
||||
{
|
||||
private static readonly DateTimeOffset _t0 = new(2026, 11, 11, 9, 0, 0, TimeSpan.Zero);
|
||||
|
||||
private readonly string _dir = Path.Combine(Path.GetTempPath(), "fl-partial-adv-" + Guid.NewGuid().ToString("N"));
|
||||
|
||||
public PartialSessionFileAdvancedTests() => Directory.CreateDirectory(_dir);
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
try
|
||||
{
|
||||
Directory.Delete(_dir, recursive: true);
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
private static PartialHeader Header() => new()
|
||||
{
|
||||
SessionGuid = Guid.Parse("00000000-0000-0000-0000-0000000000a1"),
|
||||
StartedAt = _t0,
|
||||
QpcEpoch = 1_000_000,
|
||||
QpcFrequency = 10_000_000,
|
||||
GameId = 7,
|
||||
SnapshotId = 3,
|
||||
ExePath = @"C:\Games\Title\game.exe",
|
||||
Pid = 4242,
|
||||
Tier = CaptureTier.NotHooked,
|
||||
Mode = CaptureMode.Attach,
|
||||
TelemetryDescriptor = "l1+lhm+nvapi",
|
||||
};
|
||||
|
||||
private static TelemetrySample Sample(long qpc, params AdvancedReading[] advanced) => new(
|
||||
qpc,
|
||||
new GpuSample { TakenAt = _t0.AddSeconds(qpc / 10_000_000.0), Layer = TelemetryLayer.Lhm, TempCoreC = 60 },
|
||||
Advanced: advanced.Length == 0 ? null : advanced);
|
||||
|
||||
private static AdvancedReading[] CardAndRail() =>
|
||||
[
|
||||
new("adv.nvapi.pstate", 0),
|
||||
new("adv.nvapi.vram.in_use", 1128.652),
|
||||
new("adv.lhm.board.voltage.lpc_nct6798d_0_7", -11.97),
|
||||
];
|
||||
|
||||
[Fact]
|
||||
public void ASamplesAdvancedReadingsRoundTripAndASampleWithoutAnyHasNone()
|
||||
{
|
||||
string path = Path.Combine(_dir, "adv.partial");
|
||||
using (IPartialSessionWriter w = PartialSessionFile.Create(path, Header()))
|
||||
{
|
||||
w.AppendSensors([Sample(1_100_000, CardAndRail()), Sample(1_200_000), Sample(1_300_000, new AdvancedReading("adv.nvapi.pstate", 8))]);
|
||||
w.AppendSensors([Sample(1_400_000, new AdvancedReading("adv.nvapi.pstate", 0))]);
|
||||
}
|
||||
|
||||
PartialSession p = PartialSessionFile.Read(path)!;
|
||||
|
||||
p.Truncated.Should().BeFalse();
|
||||
p.Sensors.Should().HaveCount(4);
|
||||
p.Sensors[0].Advanced.Should().Equal(CardAndRail());
|
||||
p.Sensors[0].Advanced![2].Value.Should().Be(-11.97, "a negative rail is a reading");
|
||||
p.Sensors[1].Advanced.Should().BeNull("a tick the advanced reader did not publish on carries none, and is not given the last one's");
|
||||
p.Sensors[2].Advanced.Should().Equal(new AdvancedReading("adv.nvapi.pstate", 8));
|
||||
p.Sensors[3].Advanced.Should().Equal(new AdvancedReading("adv.nvapi.pstate", 0));
|
||||
p.Sensors.Select(static s => s.Sample.TempCoreC).Should().OnlyContain(static t => t == 60, "the fixed fields are what they always were");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WithTheOptionOffTheFileIsByteForByteWhatItWasBeforeAdvancedMetricsExisted()
|
||||
{
|
||||
// No sample carries a reading, no context is given: no chunk 9, no chunk 10. The bytes are compared with the
|
||||
// same samples written with a reading attached, which differ by exactly the chunk that carries it.
|
||||
string off = Path.Combine(_dir, "off.partial");
|
||||
string on = Path.Combine(_dir, "on.partial");
|
||||
using (IPartialSessionWriter w = PartialSessionFile.Create(off, Header()))
|
||||
{
|
||||
w.AppendSensors([Sample(1_100_000), Sample(1_200_000)]);
|
||||
w.AppendNote(_t0, "end");
|
||||
}
|
||||
|
||||
using (IPartialSessionWriter w = PartialSessionFile.Create(on, Header()))
|
||||
{
|
||||
w.AppendSensors([Sample(1_100_000, new AdvancedReading("adv.nvapi.pstate", 0)), Sample(1_200_000)]);
|
||||
w.AppendNote(_t0, "end");
|
||||
}
|
||||
|
||||
ChunkTypes(File.ReadAllBytes(off)).Should().Equal(1u, 8u, 6u);
|
||||
ChunkTypes(File.ReadAllBytes(on)).Should().Equal(1u, 8u, 9u, 6u);
|
||||
byte[] offBytes = File.ReadAllBytes(off);
|
||||
byte[] onBytes = File.ReadAllBytes(on);
|
||||
int advancedChunk = ChunkOffsets(onBytes)[2];
|
||||
int advancedLength = 12 + BitConverter.ToInt32(onBytes, advancedChunk + 4);
|
||||
onBytes.AsSpan(0, advancedChunk).ToArray().Should().Equal(offBytes.AsSpan(0, advancedChunk).ToArray(), "the sensor chunk does not change when readings ride beside it");
|
||||
onBytes.AsSpan(advancedChunk + advancedLength).ToArray().Should().Equal(offBytes.AsSpan(advancedChunk).ToArray());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheSessionsContextRoundTripsAndTheLastOneWins()
|
||||
{
|
||||
var first = new AdvancedSessionData([], [], [], AdvancedSources.Unknown);
|
||||
var last = new AdvancedSessionData(
|
||||
[new AdvancedFact("nvapi.gpu.rt_cores", Instance: null, AdvancedValue.Of(84))],
|
||||
[new AdvancedFact("nvapi.session.vrr_enabled", Instance: null, AdvancedValue.Of(true))],
|
||||
[new AdvancedSeriesInfo("adv.lhm.board.voltage.lpc_nct6798d_0_7", "lhm.board.voltage", "Nuvoton NCT6798D - -12V")],
|
||||
new AdvancedSources(AdvancedSourceStatus.Reading, NvapiCode: null, AdvancedSourceStatus.Reading, AdvancedSourceStatus.NotElevated));
|
||||
string path = Path.Combine(_dir, "context.partial");
|
||||
using (IPartialSessionWriter w = PartialSessionFile.Create(path, Header()))
|
||||
{
|
||||
w.AppendAdvancedContext(AdvancedJson.OfContext(first));
|
||||
w.AppendSensors([Sample(1_100_000, CardAndRail())]);
|
||||
w.AppendAdvancedContext(AdvancedJson.OfContext(last));
|
||||
}
|
||||
|
||||
PartialSession p = PartialSessionFile.Read(path)!;
|
||||
|
||||
AdvancedSessionData context = AdvancedJson.ParseContext(p.AdvancedContextJson)!;
|
||||
context.MachineFacts.Should().ContainSingle().Which.Value.Number.Should().Be(84);
|
||||
context.SessionFacts.Should().ContainSingle().Which.Id.Should().Be("nvapi.session.vrr_enabled");
|
||||
context.Series.Should().Equal(last.Series);
|
||||
context.Sources.Should().Be(last.Sources);
|
||||
ChunkTypes(File.ReadAllBytes(path)).Should().Equal(1u, 10u, 8u, 9u, 10u);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AFileWithNoContextHasNone()
|
||||
{
|
||||
string path = Path.Combine(_dir, "none.partial");
|
||||
using (IPartialSessionWriter w = PartialSessionFile.Create(path, Header()))
|
||||
{
|
||||
w.AppendSensors([Sample(1_100_000)]);
|
||||
}
|
||||
|
||||
PartialSessionFile.Read(path)!.AdvancedContextJson.Should().BeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AKillAtEveryByteOffsetYieldsExactlyTheAdvancedChunksThatWereComplete()
|
||||
{
|
||||
string path = Path.Combine(_dir, "cut.partial");
|
||||
using (IPartialSessionWriter w = PartialSessionFile.Create(path, Header()))
|
||||
{
|
||||
w.AppendSensors([Sample(1_100_000, CardAndRail()), Sample(1_200_000, new AdvancedReading("adv.nvapi.pstate", 8))]);
|
||||
w.AppendAdvancedContext(AdvancedJson.OfContext(new AdvancedSessionData([], [], [], AdvancedSources.Unknown)));
|
||||
w.AppendSensors([Sample(1_300_000, new AdvancedReading("adv.nvapi.pstate", 0))]);
|
||||
}
|
||||
|
||||
byte[] whole = File.ReadAllBytes(path);
|
||||
List<int> starts = ChunkOffsets(whole);
|
||||
ChunkTypes(whole).Should().Equal(1u, 8u, 9u, 10u, 8u, 9u);
|
||||
int[] ends = [.. starts.Skip(1), whole.Length];
|
||||
|
||||
for (int cut = ends[0]; cut <= whole.Length; cut++)
|
||||
{
|
||||
PartialSession p = PartialSessionFile.Parse(whole.AsSpan(0, cut))!;
|
||||
int complete = ends.Count(e => e <= cut);
|
||||
|
||||
p.Sensors.Should().HaveCount(complete >= 5 ? 3 : complete >= 2 ? 2 : 0, $"cut at {cut}, {complete} complete chunk(s)");
|
||||
p.Sensors.Count(static s => s.Advanced is not null).Should().Be(complete >= 6 ? 3 : complete >= 3 ? 2 : 0, $"cut at {cut}: readings arrive with their own chunk and never before it");
|
||||
(p.AdvancedContextJson is not null).Should().Be(complete >= 4, $"cut at {cut}");
|
||||
p.Truncated.Should().Be(cut != whole.Length && !ends.Contains(cut), $"cut at {cut}");
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AChunkOfATypeThisBuildDoesNotKnowIsPassedOverAndWhatFollowsIsRead()
|
||||
{
|
||||
// Owner decision D106. Until 2026-11-11 an unknown type ended the read, so a build one release older lost
|
||||
// everything after the first chunk a newer build had added.
|
||||
string path = Path.Combine(_dir, "unknown.partial");
|
||||
using (IPartialSessionWriter w = PartialSessionFile.Create(path, Header()))
|
||||
{
|
||||
w.AppendNote(_t0, "before");
|
||||
}
|
||||
|
||||
byte[] head = File.ReadAllBytes(path);
|
||||
byte[] future = Chunk(type: 4242, Encoding.UTF8.GetBytes("something a later build writes"));
|
||||
string tailPath = Path.Combine(_dir, "tail.partial");
|
||||
using (IPartialSessionWriter w = PartialSessionFile.Create(tailPath, Header()))
|
||||
{
|
||||
w.AppendSensors([Sample(1_100_000, CardAndRail())]);
|
||||
w.AppendNote(_t0.AddSeconds(1), "after");
|
||||
}
|
||||
|
||||
byte[] tailFile = File.ReadAllBytes(tailPath);
|
||||
byte[] tail = tailFile[ChunkOffsets(tailFile)[1]..];
|
||||
|
||||
PartialSession p = PartialSessionFile.Parse([.. head, .. future, .. tail])!;
|
||||
|
||||
p.Truncated.Should().BeFalse("a chunk whose length and checksum are right is not a torn file");
|
||||
p.Notes.Select(static n => n.Text).Should().Equal("before", "after");
|
||||
p.Sensors.Should().ContainSingle().Which.Advanced.Should().Equal(CardAndRail());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AnUnknownChunkWhoseChecksumIsWrongStillEndsTheRead()
|
||||
{
|
||||
string path = Path.Combine(_dir, "torn.partial");
|
||||
using (IPartialSessionWriter w = PartialSessionFile.Create(path, Header()))
|
||||
{
|
||||
w.AppendNote(_t0, "before");
|
||||
}
|
||||
|
||||
byte[] future = Chunk(type: 4242, [1, 2, 3, 4]);
|
||||
future[^1] ^= 0xFF;
|
||||
byte[] note = Chunk(type: 6, [.. BitConverter.GetBytes(_t0.ToUnixTimeMilliseconds()), .. Encoding.UTF8.GetBytes("after")]);
|
||||
|
||||
PartialSession p = PartialSessionFile.Parse([.. File.ReadAllBytes(path), .. future, .. note])!;
|
||||
|
||||
p.Truncated.Should().BeTrue("skipping is for a chunk that is whole; one that is not is where the file ends");
|
||||
p.Notes.Should().ContainSingle().Which.Text.Should().Be("before");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AnAdvancedChunkThatIsNotWellFormedEndsTheReadLikeAnyKnownChunkThatIsNot()
|
||||
{
|
||||
string path = Path.Combine(_dir, "bad.partial");
|
||||
using (IPartialSessionWriter w = PartialSessionFile.Create(path, Header()))
|
||||
{
|
||||
w.AppendSensors([Sample(1_100_000)]);
|
||||
}
|
||||
|
||||
// One name declared, and a reading that points at a second one that is not there.
|
||||
byte[] payload = [1, 0, 1, 0, (byte)'a', 1, 0, 0, 0, .. BitConverter.GetBytes(1_100_000L), 1, 0, 5, 0, .. BitConverter.GetBytes(1.0)];
|
||||
byte[] note = Chunk(type: 6, [.. BitConverter.GetBytes(_t0.ToUnixTimeMilliseconds()), .. Encoding.UTF8.GetBytes("after")]);
|
||||
|
||||
PartialSession p = PartialSessionFile.Parse([.. File.ReadAllBytes(path), .. Chunk(type: 9, payload), .. note])!;
|
||||
|
||||
p.Truncated.Should().BeTrue();
|
||||
p.Sensors.Should().ContainSingle().Which.Advanced.Should().BeNull();
|
||||
p.Notes.Should().BeEmpty("nothing after a chunk that failed is trusted");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ReadingsWhoseSampleIsNotInTheFileBelongToNoTickAndAreLeftOut()
|
||||
{
|
||||
string path = Path.Combine(_dir, "orphan.partial");
|
||||
using (IPartialSessionWriter w = PartialSessionFile.Create(path, Header()))
|
||||
{
|
||||
w.AppendSensors([Sample(1_100_000)]);
|
||||
}
|
||||
|
||||
// A well-formed chunk for a QPC no sample has.
|
||||
byte[] payload = [1, 0, 1, 0, (byte)'a', 1, 0, 0, 0, .. BitConverter.GetBytes(9_999_999L), 1, 0, 0, 0, .. BitConverter.GetBytes(1.0)];
|
||||
|
||||
PartialSession p = PartialSessionFile.Parse([.. File.ReadAllBytes(path), .. Chunk(type: 9, payload)])!;
|
||||
|
||||
p.Truncated.Should().BeFalse();
|
||||
p.Sensors.Should().ContainSingle().Which.Advanced.Should().BeNull();
|
||||
}
|
||||
|
||||
/// <summary>One chunk as the format frames it: type, length, payload, then the IEEE CRC-32 of the first three.</summary>
|
||||
private static byte[] Chunk(uint type, byte[] payload)
|
||||
{
|
||||
byte[] chunk = new byte[12 + payload.Length];
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(chunk, type);
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(chunk.AsSpan(4), (uint)payload.Length);
|
||||
payload.CopyTo(chunk, 8);
|
||||
uint crc = 0xFFFFFFFFu;
|
||||
foreach (byte b in chunk.AsSpan(0, 8 + payload.Length))
|
||||
{
|
||||
crc ^= b;
|
||||
for (int bit = 0; bit < 8; bit++)
|
||||
{
|
||||
crc = (crc & 1) != 0 ? (crc >> 1) ^ 0xEDB88320u : crc >> 1;
|
||||
}
|
||||
}
|
||||
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(chunk.AsSpan(8 + payload.Length), crc ^ 0xFFFFFFFFu);
|
||||
return chunk;
|
||||
}
|
||||
|
||||
private static List<int> ChunkOffsets(byte[] file)
|
||||
{
|
||||
var offsets = new List<int>();
|
||||
for (int at = 0; at < file.Length; at += 12 + BitConverter.ToInt32(file, at + 4))
|
||||
{
|
||||
offsets.Add(at);
|
||||
}
|
||||
|
||||
return offsets;
|
||||
}
|
||||
|
||||
private static uint[] ChunkTypes(byte[] file) => [.. ChunkOffsets(file).Select(at => BitConverter.ToUInt32(file, at))];
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
|
||||
|
||||
using FluentAssertions;
|
||||
using FrameLedger.Application.Advanced;
|
||||
using FrameLedger.Application.Telemetry;
|
||||
using FrameLedger.Infrastructure.Telemetry;
|
||||
|
||||
namespace FrameLedger.Infrastructure.Tests.Telemetry;
|
||||
|
||||
/// <summary>
|
||||
/// The poller and the shared advanced reader (owner decision D101): it holds the reader while it runs, attaches each
|
||||
/// of the reader's ticks to one sample and to no other, and with no reader composed a sample is what it always was.
|
||||
/// </summary>
|
||||
public sealed class TelemetryPollerAdvancedTests
|
||||
{
|
||||
private static readonly DateTimeOffset _t0 = new(2026, 11, 11, 9, 0, 0, TimeSpan.Zero);
|
||||
|
||||
private sealed class Clock : TimeProvider
|
||||
{
|
||||
public long Ticks { get; set; } = 1_000_000;
|
||||
|
||||
public override DateTimeOffset GetUtcNow() => _t0;
|
||||
|
||||
public override long GetTimestamp() => Ticks;
|
||||
}
|
||||
|
||||
private sealed class FakeHub : IAdvancedHardware
|
||||
{
|
||||
public int Acquired { get; private set; }
|
||||
|
||||
public int Released { get; private set; }
|
||||
|
||||
public AdvancedSnapshot? Latest { get; set; }
|
||||
|
||||
public IDisposable Acquire()
|
||||
{
|
||||
Acquired++;
|
||||
return new Hold(this);
|
||||
}
|
||||
|
||||
public IReadOnlyList<AdvancedFact> ReadSessionFacts(AdvancedSessionTarget target) => [];
|
||||
|
||||
public void Publish(params AdvancedReading[] readings)
|
||||
=> Latest = new AdvancedSnapshot(_t0, readings, [], [], AdvancedSources.Unknown);
|
||||
|
||||
private sealed class Hold(FakeHub hub) : IDisposable
|
||||
{
|
||||
public void Dispose() => hub.Released++;
|
||||
}
|
||||
}
|
||||
|
||||
private static List<TelemetrySample> Drained(TelemetryPoller poller)
|
||||
{
|
||||
var samples = new List<TelemetrySample>();
|
||||
poller.Drain(samples);
|
||||
return samples;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EachTickOfTheReaderIsAttachedToOneSampleAndIsNotRepeatedOnTheNext()
|
||||
{
|
||||
using var layer = new FakeLayer(TelemetryLayer.Lhm);
|
||||
layer.Publish(layer.Sample(_t0, load: 50));
|
||||
var hub = new FakeHub();
|
||||
using var poller = new TelemetryPoller(layer, new TelemetryPollerOptions(), new Clock(), advanced: hub);
|
||||
|
||||
hub.Publish(new AdvancedReading("adv.nvapi.pstate", 0), new AdvancedReading("adv.lhm.board.voltage.lpc_0_7", -11.97));
|
||||
poller.PollOnce();
|
||||
poller.PollOnce();
|
||||
hub.Publish(new AdvancedReading("adv.nvapi.pstate", 8));
|
||||
poller.PollOnce();
|
||||
|
||||
List<TelemetrySample> samples = Drained(poller);
|
||||
samples.Should().HaveCount(3);
|
||||
samples[0].Advanced.Should().Equal(new AdvancedReading("adv.nvapi.pstate", 0), new AdvancedReading("adv.lhm.board.voltage.lpc_0_7", -11.97));
|
||||
samples[1].Advanced.Should().BeNull("nothing newer arrived: a reading is of one tick, and the last one's is not repeated");
|
||||
samples[2].Advanced.Should().Equal(new AdvancedReading("adv.nvapi.pstate", 8));
|
||||
samples.Should().OnlyContain(static s => s.Sample.LoadPct == 50, "the fixed fields are untouched");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ATickTheReaderPublishedWithNoReadingAttachesNothing()
|
||||
{
|
||||
using var layer = new FakeLayer(TelemetryLayer.Lhm);
|
||||
layer.Publish(layer.Sample(_t0, load: 50));
|
||||
var hub = new FakeHub();
|
||||
using var poller = new TelemetryPoller(layer, new TelemetryPollerOptions(), new Clock(), advanced: hub);
|
||||
|
||||
hub.Publish();
|
||||
poller.PollOnce();
|
||||
|
||||
Drained(poller).Should().ContainSingle().Which.Advanced.Should().BeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ATickOnlyTheAdvancedReaderAnsweredIsStillASample()
|
||||
{
|
||||
using var layer = new FakeLayer(TelemetryLayer.Lhm);
|
||||
var hub = new FakeHub();
|
||||
using var poller = new TelemetryPoller(layer, new TelemetryPollerOptions(), new Clock { Ticks = 77_000 }, advanced: hub);
|
||||
|
||||
poller.PollOnce();
|
||||
Drained(poller).Should().BeEmpty("nothing answered at all");
|
||||
|
||||
hub.Publish(new AdvancedReading("adv.nvapi.pstate", 0));
|
||||
poller.PollOnce();
|
||||
|
||||
TelemetrySample only = Drained(poller).Should().ContainSingle().Subject;
|
||||
only.QpcTicks.Should().Be(77_000);
|
||||
only.Sample.Layer.Should().Be(TelemetryLayer.None, "the placeholder names no layer and no field");
|
||||
only.Advanced.Should().ContainSingle();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WithNoReaderComposedASampleIsWhatItAlwaysWas()
|
||||
{
|
||||
using var layer = new FakeLayer(TelemetryLayer.Lhm);
|
||||
layer.Publish(layer.Sample(_t0, load: 50));
|
||||
using var poller = new TelemetryPoller(layer, new TelemetryPollerOptions(), new Clock());
|
||||
|
||||
poller.PollOnce();
|
||||
|
||||
Drained(poller).Should().ContainSingle().Which.Advanced.Should().BeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheReaderIsHeldFromStartToDisposeAndNeverOwned()
|
||||
{
|
||||
using var layer = new FakeLayer(TelemetryLayer.Lhm);
|
||||
var hub = new FakeHub();
|
||||
var poller = new TelemetryPoller(layer, new TelemetryPollerOptions(), new Clock(), ownsSource: false, advanced: hub);
|
||||
|
||||
hub.Acquired.Should().Be(0, "a poller that was never started holds nothing");
|
||||
poller.Start();
|
||||
poller.Start();
|
||||
hub.Acquired.Should().Be(1);
|
||||
hub.Released.Should().Be(0);
|
||||
|
||||
poller.Dispose();
|
||||
poller.Dispose();
|
||||
|
||||
hub.Released.Should().Be(1, "some seconds after the last holder lets go the shared reader closes (D107)");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void APollerThatWasNeverStartedReleasesNothing()
|
||||
{
|
||||
using var layer = new FakeLayer(TelemetryLayer.Lhm);
|
||||
var hub = new FakeHub();
|
||||
var poller = new TelemetryPoller(layer, new TelemetryPollerOptions(), new Clock(), advanced: hub);
|
||||
|
||||
poller.Dispose();
|
||||
|
||||
hub.Acquired.Should().Be(0);
|
||||
hub.Released.Should().Be(0);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user