Compare commits

...
Author SHA1 Message Date
poli0981andClaude Fable 5.2 a4ec75538e fix(telemetry): one sensor library a process - every LibreHardwareMonitor Computer is opened and closed through LhmLibrary, serialised, and parked rather than closed while another is in use
Found in the owner's first sessions as administrator with PawnIO (0.1.0-beta.40): after seven of ten sessions the
Advanced reader's processor device threw NullReferenceException twice and was left alone, and once the reader's
Open threw ObjectDisposedException and the session stored 17 series instead of 212. The Agent holds up to three
Computers at once; the library keeps the driver it reads the processor through and its bus mutexes per process,
and Computer.Close() lets go of them whoever else is reading. Read from the log's timing, not reproduced: it needs
that elevation.

LhmLibrary (one per process; LhmComputerAdapter is its user): opens and closes never run at once, and a Computer
closed while another is in use is parked and handed to the next user of the same groups; the last user's close
closes them all, even when one throws. The reads are not serialised - the readers keep their own threads.

20_OPEN_QUESTIONS M13 records the first elevated run (119 processor, 14 memory, 21 motherboard series read; no
value compared with another tool) and stays open: whether the faults are gone is the owner's next sessions to
show. HANDOFF records what the same ledger says of beta.40's in-game readings.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 04:46:38 +07:00
8 changed files with 510 additions and 19 deletions

No files matched your search

+9
View File
@@ -37,6 +37,15 @@ numeric core and does not move; the heading is the full version — corrected 20
### Fixed
- **Advanced metrics: the processor's sensors no longer drop out after a session, and a session no longer loses its
sensors at the start.** With the agent running as administrator and PawnIO installed, the sensor library was being
closed by one part of the agent while another part was still reading it. After most sessions the Advanced page
lost the processor's readings until it was reopened, and one session in ten stored only the graphics driver's
seventeen series instead of two hundred and twelve. The agent now opens and closes the sensor library in one
place, and does not close it while anything is still reading. Found in the first sessions recorded that way; the
cause was read from the log and could not be reproduced without that setup, so the next sessions will show
whether it is gone — the agent's log should no longer say *a device is left alone* or *the sensor library did not
open*. Nothing changes in the code loaded into a game.
- **Two comparisons in the Advanced-metrics code say what they mean.** Whether a game gave FSR one field of view or
a range of them was decided by comparing two decimal numbers for equality; it is now decided by comparing the two
stored values bit for bit. Nothing you see changes. (Found by SonarCloud after 0.1.0-beta.40 was merged.)
+11
View File
@@ -632,6 +632,17 @@ and labelled with the hardware's words. A sensor with no family is not read.
`RecorderOptions.AdvancedMetrics` through `SettingsRecorderPolicy`, at each session's start like the other recording
settings; exactly `1` is on. From there:
- **The process has one sensor library** *(2026-11-12)*. One *reader* was never the whole of it: a session's L2
source and its CPU-temperature reader each open a LibreHardwareMonitor `Computer` of their own beside the
Advanced reader's, and the library keeps part of its state — the driver it reads the processor through, its bus
mutexes — per process. `Computer.Close()` lets go of that part whoever else is still reading. The first sessions
recorded as administrator with PawnIO showed it (`20_OPEN_QUESTIONS` §M13): a processor device that faulted out
some seconds after each session's sources closed, and one session whose reader could not open at all. Every
`Computer` is now opened and closed through `Infrastructure.Telemetry.LhmLibrary` (`LhmComputerAdapter` is its
user): opens and closes never run at once, and a `Computer` closed while another is in use is **parked** — left
open, read by nobody, handed to the next user of the same groups — until the last user lets go, when all are
closed. The reads are not serialised: the readers keep their own threads, so a sensor that hangs in one still
holds up neither the other nor the pipe.
- **The Agent has one reader** — `AgentServices` registers `AdvancedHardwareHub` as `IAdvancedHardware`, a tick a
second and a linger of ten — and nothing starts it but a holder. `SessionRecorder` holds it for a session's length
**only when the option is on**, and `AgentRecording` gives the session's `TelemetryPoller` the reader on the same
+1 -1
View File
@@ -1861,7 +1861,7 @@ Moved verbatim, in this order.
| M10 ❓ | **§CPU — is the CPU temperature this build reads the right sensor, and does it read at all on the owner's machine?** `LhmCpuTemperatureReader` (2026-09-21) opens a CPU-only LibreHardwareMonitor `Computer` when the Agent is elevated AND `PawnIo.IsInstalled`, takes the package sensor (`CPU Package` / `Core (Tctl/Tdie)`) and falls back to the hottest core. It was written against LHM's sensor names and a fake `ILhmComputer`; **no elevated run with PawnIO has been taken.** | **The measurement is one session:** Agent elevated, PawnIO installed, a five-minute capture with HWiNFO or Ryzen Master open beside it. Pre-committed: `max_cpu_temp` within 3 °C of the reference's package peak → keep; a core sensor picked where a package sensor exists, or a reading tens of degrees off (a distance-to-TjMax sensor mistaken for a temperature) → fix `Pick` and re-run; nothing read at all → `cpu_temp` stays N/A and `legal/ACCURACY.md` says processor temperature is not measured. CPU **load** and memory are not in question: `TheRealCountersAnswerOnThisMachine` reads them on every gate run. |
| M11 🅓 | **The game's VRAM budget and `budget_exceeded_pct` (FR-4.5's second half), 2026-10-03.** D43 reads the game's usage from outside (the `GPU Process Memory` counters); the budget the OS grants the process is what DXGI's `QueryVideoMemoryInfo` returns to the *calling* process (§M7), so only an in-process call — the Overlay's background thread, which today only checks for a stop — or `D3DKMTQueryStatistics`' `PROCESS_SEGMENT_GROUP` query (documented "Reserved for system use") could read it. **Deferred by decision:** neither is built; `vram_budget_exceeded_pct` stays NULL and the budget N/A, and the in-process route would change what the Disclaimer says the Overlay's thread does. Reopening it needs that decision, not a measurement. | — |
| M12 ❓ | **Advanced metrics — which NVAPI rows answer on real hardware (D101, 2026-11-11).** `18_GPU_VENDOR_APIS` §The inventory lists sixty `nvapi.` rows whose reach is `Agent`. They are declared in the vendored headers; **none has been called on a GPU**, and CI has no driver, so it never takes that branch. Unknown per row: whether the RTX 5080 on the current driver answers or returns `NVAPI_NOT_SUPPORTED` (the memory-temperature target already does not exist on that card). | **The measurement is the bridge's probe on the owner's PC**, then the page itself (the release's owner-only item). Pre-committed: a call that does not answer → that row is N/A with NVAPI's own status as the reason, and nothing is put in its place; a call that hangs or faults twice → the row is off for the session (§Runtime policy); a value that contradicts the vendor's own tool → the row is withheld until it is explained. **Half answered the same day, by the bridge's own test on the dev box** (ctest `fl_nvapi_bridge`, AVAILABLE branch; RTX 5080): every fact answers (`present = 0xFFFFF`), eight of ten live groups answer (`0x33F` — no board and no power-supply temperature sensor on this card: N/A, by the first pre-committed outcome), the display answers its four groups, the global profile lists 24 settings; figures in `18_GPU_VENDOR_APIS` §L3. **Still open**: the same values on the page beside the vendor's own tool, and the session rows (`nvapi.session.*`), which need a game. **And one thing seen once and not explained**: in one test run of about a dozen that day, `FlNvReadLive` came back with no field at all although `FlNvReadFacts`, a moment earlier in the same process, had answered everything; nine further runs did not show it. A handle the driver invalidated is the usual cause of that shape, and nothing here re-enumerates after `FlNvInit`. Pre-committed for the reader that owns the thread: two readings in a row with no field → release and initialise the bridge again, once, and say so in the log; if that does not bring the fields back the layer is off for the session, as any layer that fails twice is. |
| M13 ❓ | **Advanced metrics — LibreHardwareMonitor's CPU, memory, motherboard and storage groups, elevated, with PawnIO (D103, 2026-11-11).** Never opened by any build: §M10's elevated run has not been taken either, and this is a larger surface — a sensor chip on the LPC bus, the embedded controller, SPD over SMBus, SMART. Unknown: whether each group opens on the owner's board, what a refresh costs, whether opening the storage group touches removable drives (this PC once had a failing USB drive), and whether any group enables a privilege (`PrivilegeFootprintTests`). | **One elevated run with the probe verb, before the option exists.** Pre-committed: the storage group cannot be opened without touching removable drives → `lhm.storage.*` stays N/A in beta.39 and its reach reads `Deferred`; a node that throws twice → skipped for the session; the Agent above 1% of one core or 150 MB with the option on (NFR-2) → the slow groups are read less often or dropped before the release; a privilege enabled by a group → that group is not opened, and the owner is asked. **Two of the four answered 2026-11-11, before the option exists.** (1) **Storage: not opened, by the first outcome.** LibreHardwareMonitor 0.9.6's `StorageGroup` lists every drive through DiskInfoToolkit's `ReloadStorages` with no filter by bus and follows drives plugged in later — it cannot be opened without touching removable drives. `lhm.storage.*` reads `Deferred`, and `LhmGroups` has no member for it. (2) **Cost, unelevated, measured with `probe-advanced`** on the dev box: one refresh of the graphics-card group alone is 14 ms of processor time (62 ms elapsed) — 1.4% of one core at one a second, above NFR-2 — and one NVAPI read 0.4 ms. By the third outcome the sensor library is read every fifth tick (0.28%). **Still open, and the owner's**: the same probe as administrator with PawnIO — whether the processor, memory and motherboard groups open on this board, what they cost, and `PrivilegeFootprintTests`' new case on a token that holds the privileges (CI's does; the dev box's unelevated run passes by construction). |
| M13 ❓ | **Advanced metrics — LibreHardwareMonitor's CPU, memory, motherboard and storage groups, elevated, with PawnIO (D103, 2026-11-11).** Never opened by any build: §M10's elevated run has not been taken either, and this is a larger surface — a sensor chip on the LPC bus, the embedded controller, SPD over SMBus, SMART. Unknown: whether each group opens on the owner's board, what a refresh costs, whether opening the storage group touches removable drives (this PC once had a failing USB drive), and whether any group enables a privilege (`PrivilegeFootprintTests`). | **One elevated run with the probe verb, before the option exists.** Pre-committed: the storage group cannot be opened without touching removable drives → `lhm.storage.*` stays N/A in beta.39 and its reach reads `Deferred`; a node that throws twice → skipped for the session; the Agent above 1% of one core or 150 MB with the option on (NFR-2) → the slow groups are read less often or dropped before the release; a privilege enabled by a group → that group is not opened, and the owner is asked. **Two of the four answered 2026-11-11, before the option exists.** (1) **Storage: not opened, by the first outcome.** LibreHardwareMonitor 0.9.6's `StorageGroup` lists every drive through DiskInfoToolkit's `ReloadStorages` with no filter by bus and follows drives plugged in later — it cannot be opened without touching removable drives. `lhm.storage.*` reads `Deferred`, and `LhmGroups` has no member for it. (2) **Cost, unelevated, measured with `probe-advanced`** on the dev box: one refresh of the graphics-card group alone is 14 ms of processor time (62 ms elapsed) — 1.4% of one core at one a second, above NFR-2 — and one NVAPI read 0.4 ms. By the third outcome the sensor library is read every fifth tick (0.28%). **Still open, and the owner's**: the same probe as administrator with PawnIO — whether the processor, memory and motherboard groups open on this board, what they cost, and `PrivilegeFootprintTests`' new case on a token that holds the privileges (CI's does; the dev box's unelevated run passes by construction). **The first run was taken on 2026-11-12, by the owner, in ordinary use** (0.1.0-beta.40, the Agent as administrator with PawnIO, an i7-14700KF on a board with an IT8689E chip, an RTX 5080), and read here from a copy of the ledger and the Agent's log, not from a probe. **The groups open and read**: nine of ten sessions stored 119 processor series (a clock and a load per thread, temperatures, powers, voltages), 14 memory series and 21 motherboard series (six fans, six temperatures, nine voltages) beside the card's 41 — 195 from the sensor library in all. **No value was compared with another tool**; that is still the owner's. **Two faults, one cause** (`Infrastructure.Telemetry.LhmLibrary`): the Agent held up to three `Computer`s at once, and the library keeps the driver it reads the processor through and its bus mutexes per process — closing one `Computer` let go of them under the others. After seven sessions the Advanced reader's processor device threw `NullReferenceException` twice and was left alone (the page lost the processor until the reader reopened); once a session's start met another instance's close, the reader's `Open` threw `ObjectDisposedException`, and that session stored 17 series instead of 212. **Fixed 2026-11-12**: opens and closes are serialised and a `Computer` is parked, not closed, while another is in use. The cause is read from the log's timing and was not reproduced — it needs this elevation — so **whether the faults are gone is the owner's next sessions to show**: no `advanced: a device is left alone` and no `did not open` in the Agent's log. |
| M16 ✅ | **The L2 telemetry layer's cost — the first number, and it is above NFR-2 (found 2026-11-11, measuring something else).** `LhmTelemetrySource` refreshes LibreHardwareMonitor's graphics-card group once a second in every recorded session. `probe-advanced` measured that refresh, through the same library and the same group, at **14 ms of processor time** on the dev box (RTX 5080, 41 mapped sensors, about twenty of them the Direct3D engine nodes the library enumerates per card) — 1.4% of one core, where NFR-2 allows the whole Agent 1% during capture and `14_TESTING` §Hook overhead's Agent figure has never been measured. This is a measurement of the call, not yet of a session: L2's own poller was not instrumented. | **Measure L2 in a session** (the Agent's processor time over a ten-minute capture, telemetry at 1000 ms and at 2000 ms). Pre-committed: at or under 1% → this row closes with the number; above → the owner chooses between a slower default for `telemetry.interval_ms`, reading the sensors the layer keeps from NVAPI on NVIDIA cards (L3 already has most, at 0.4 ms), or amending NFR-2 to what is measured. Not decided here, and nothing about L2 changes in the Advanced-metrics train. **Measured in a real Agent, 2026-11-11 (owner decision D110), and answered (D117).** `tools/agent-cost.ps1` runs the shipped `FrameLedger.Agent.exe --console capture` against a copy of hook-harness in a scratch data folder — a session that is not hooked, so the telemetry poller runs as in every session and nothing drains frames — and reads the Agent process's own processor time at exit; the cost per second is the slope between a 45 s and a 165 s session, two runs of each. Dev box (RTX 5080, not elevated, layers `l1+lhm+nvapi`): **19.3 ms of processor time per second of session = 1.93 % of one core with Advanced metrics off** (2,312 and 2,312 ms over 45 s; 4,594 and 4,656 ms over 165 s), **20.4 ms = 2.04 % with it on** (2,984 and 3,000; 5,547 and 5,344); peak working set 113 MiB and 119 MiB. A first pass with 30 s and 90 s sessions gave 1.56 % and 2.21 % — its two short runs differed by 670 ms, which is why the lengths were raised. So the probe's number holds in a session: the Agent's steady cost is about twice NFR-2's 1 %, nearly all of it the layer every session has always used, and the new option adds about a tenth of a percent. **The owner's answer: NFR-2 is amended to ≤ 2.5 % of one core** — the limit had never been measured, the sensors keep their one reading a second, and nothing in the code changes. Not measured: a hooked session (the drain's cost on top), a session with the Agent elevated and PawnIO's groups open, another PC. |
| M14 ❓ | **Reflex latency per frame — is there a route within rules 4 and 5? (Train C, 2026-11-11.)** `17_HOOK_ENGINE` §Memory / latency names hooks on `NvAPI_D3D_SetSleepMode` / `SetLatencyMarker` and a call to `NvAPI_D3D_GetLatency`. NVAPI resolves all three through `nvapi_QueryInterface` by id — they are not exports, so a hook on them is a patch at an address learned at run time, the class refused on 2026-08-09. The route to try first needs no hook: the Overlay's own background thread **calls** `GetLatency` with the device of the swap chain it already hooks, once a second (the call returns the last 64 frames' reports). Unknown: whether calling into the driver from that thread is safe on every device kind, what it costs, what it returns when the game never enabled Reflex, and what it means for the Disclaimer's sentence about that thread. | **A spike on `hook-harness` and a stub first, then one real title.** Pre-committed: no route without a patch at a run-time address or a loader-lock call on the game's thread → Reflex stays N/A and the page says why; overhead above NFR-1 → the same. The owner says go or no on the spike's result. |
| M15 ❓ | **The Streamline state behind `slGetFeatureFunction` — re-examined, not reopened (Train D, 2026-11-11).** The owner asked for the refusal in `handoff/history/p0-queue-1-6.md` to be looked at again. `18_GPU_VENDOR_APIS` §The trains states the route to try (hook the export, hand back a wrapper for a fixed list of names) and what it raises: the wrapper is a write to what the game receives, which rule 4 forbids as written; a wrapper must outlive the Overlay's unhook; a game that fetched its functions before the hook existed is never seen. | **A written design against each of the five grounds, then a spike.** Pre-committed: any ground unanswered → the route stays refused, and `sl.dlssg.*`, `sl.reflex.*` and the rest of that block read N/A with "refused" as the reason. Proceeding needs the owner's amendment of rule 4, asked with the rule quoted. |
+30
View File
@@ -159,6 +159,31 @@ None of these is an owner decision; each was found while building, and is writte
- **Whether any shipping title chains `sl::DLSSOptions` into `slEvaluateFeature`** is not known. If none of the
owner's games does, the six `sl.dlss.*` entries read N/A everywhere until train D, and the page already says why.
- **The aliasable part of FSR's memory** is read and published and not shown: the catalog has one memory entry.
- **What the owner's first evening with it showed** (2026-11-12, read from a copy of the ledger and the Agent's log;
ten hooked sessions on eight games, no fault in any, the Overlay `Ready` at every end):
- **Read from a real game for the first time: Lies of P** (FSR 3 through `amd_fidelityfx_dx12.dll` 1.0.1, the
SDK 1.1.x monolith) — sharpening on at 0.5, jitter up to 0.48 / 0.49 of a pixel, pre-exposure 0.25–1, a vertical
field of view from 21.6° to 73.7°, no flag, and a reported frame time whose median is 16.67 ms beside a native
rate of 55.6 FPS. The series starts 83 seconds in and has no gap after. Whether these match the game's own
settings is still the owner's to say (item 38 (c)).
- **`cameraNear` is absent there and `cameraFar` is 10.** Most likely the game runs an inverted, infinite depth
and passes `FLT_MAX` for the plane at infinity, which the Overlay refuses as a value nobody set. "Infinite" would
be the true answer. It is a change in code loaded into a game: decide it in beta.41's plan, not before.
- **Every other game said *the game made none of the calls***, as expected: all ran DLSS. Dying Light: The Beast
evaluates DLSS through Streamline and chains no `DLSSOptions` — the first evidence on that open question, and
it is a no. Valor Mortis, Phantom Blade Zero, Clair Obscur and Kingdom Come: Deliverance II ship AMD's FSR 3.1+
libraries and did not upscale through them in these sessions, so **no FSR 3.1+ title has been read yet**.
- **The option off stored nothing** (Black Myth: Wukong, one session each way), and **a game under the user-mode
anti-cheat exception ran with it on** (Girls' Frontline 2, trial 1 of 2).
- **Valor Mortis ended with an access violation 51 seconds after injection, once**; the next launch ran fourteen
minutes on the same build. The Overlay counted no fault and Windows logged no application error. Not attributed
and not ruled out; its crash count stands at 1, and a second such end switches its hooking off.
- **The sensor library was closed under its other users** — a defect of train A that only an elevated Agent with
PawnIO can show. `20_OPEN_QUESTIONS` §M13 has what was seen; `LhmLibrary` is the fix; the owner's next sessions
say whether it holds.
- **`LIMITATIONS.md` and the accuracy statement still say the processor's, the memory's and the motherboard's
sensors "have never been read on real hardware".** They have now been read on one PC and compared with nothing.
The sentence is the owner's to reword.
- ~~**SonarCloud on #398** had not answered when this was written; #397's three findings are fixed in #398.~~
**It answered after the merge, with three findings on new code**, handled in the pull request after the release:
two `csharpsquid:S1244` in `InGameAdvancedSampler` — a lowest and a highest float compared with `==` to tell one
@@ -173,6 +198,11 @@ None of these is an owner decision; each was found while building, and is writte
### Traps this train paid for
- **A library that is "one object per user" may still be one per process underneath.** Three `Computer`s of
LibreHardwareMonitor shared a driver handle and mutexes; each was tested alone, unelevated, where the shared part
is never opened. Before composing a second instance of anything that talks to a driver, ask what its `Close`
closes. And `first ??= TryClose(x)` in a loop stops closing at the first throw — the test for "all are closed
even when one throws" caught it in the fix itself.
- **A heredoc in the tool's shell breaks on an odd number of apostrophes** — a script with `game's` in it fails with
"unexpected EOF while looking for matching `'`" before Python ever runs. Write the script to a file and run the
file.
@@ -24,6 +24,12 @@ namespace FrameLedger.Infrastructure.Telemetry;
/// reader that opens them counts faults per device and reads on a thread of its own.
/// </para>
/// <para>
/// <b>Amended 2026-11-12: a user of <see cref="LhmLibrary"/>, not the owner of a <c>Computer</c>.</b> The library keeps
/// part of its state per process, and closing one <c>Computer</c> took it from under the others — found in the first
/// sessions recorded as administrator with PawnIO. Opening and closing now go through the process's one
/// <see cref="LhmLibrary"/>, which serialises them and parks a closed <c>Computer</c> while another is in use.
/// </para>
/// <para>
/// Consumed <b>unmodified</b>, as an ordinary NuGet package reference. MPL-2.0 §3.3 is what
/// makes that combinable with GPLv3; modifying a file of it would change the obligation
/// (<c>legal/THIRD_PARTY_NOTICES.md</c> §GPL-3.0 compatibility).
@@ -31,35 +37,43 @@ namespace FrameLedger.Infrastructure.Telemetry;
/// </remarks>
public sealed class LhmComputerAdapter : ILhmComputer
{
private readonly Computer _computer;
private readonly LhmLibrary _library;
private readonly LhmGroups _groups;
private ILhmComputer? _computer;
public LhmComputerAdapter(bool enableCpuAndMemory, bool enableGpu = true)
: this((enableGpu ? LhmGroups.Gpu : LhmGroups.None) | (enableCpuAndMemory ? LhmGroups.Cpu | LhmGroups.Memory : LhmGroups.None))
{
_computer = new Computer
{
IsGpuEnabled = enableGpu,
IsCpuEnabled = enableCpuAndMemory,
IsMemoryEnabled = enableCpuAndMemory,
};
}
/// <summary>The groups <paramref name="groups"/> names, and no other (D103).</summary>
public LhmComputerAdapter(LhmGroups groups)
: this(groups, LhmLibrary.Process)
{
_computer = new Computer
{
IsGpuEnabled = groups.HasFlag(LhmGroups.Gpu),
IsCpuEnabled = groups.HasFlag(LhmGroups.Cpu),
IsMemoryEnabled = groups.HasFlag(LhmGroups.Memory),
IsMotherboardEnabled = groups.HasFlag(LhmGroups.Motherboard),
};
}
public IReadOnlyList<IHardware> Hardware => [.. _computer.Hardware];
/// <summary>The same, over a library of the caller's: the tests', which opens no driver.</summary>
public LhmComputerAdapter(LhmGroups groups, LhmLibrary library)
{
_groups = groups;
_library = library ?? throw new ArgumentNullException(nameof(library));
}
public void Open() => _computer.Open();
/// <summary>The tree of the open <c>Computer</c>; empty before <see cref="Open"/> and after <see cref="Close"/>.</summary>
public IReadOnlyList<IHardware> Hardware => _computer?.Hardware ?? [];
public void Update() => _computer.Accept(new UpdateVisitor());
/// <summary>Opens once: a second call while open changes nothing.</summary>
public void Open() => _computer ??= _library.Open(_groups);
public void Close() => _computer.Close();
public void Update() => _computer?.Update();
/// <summary>Lets go once: the library decides whether the <c>Computer</c> is closed now or parked.</summary>
public void Close()
{
if (_computer is { } computer)
{
_computer = null;
_library.Close(_groups, computer);
}
}
}
@@ -0,0 +1,183 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
using System.Runtime.ExceptionServices;
using LibreHardwareMonitor.Hardware;
namespace FrameLedger.Infrastructure.Telemetry;
/// <summary>
/// The one LibreHardwareMonitor a process has: every <c>Computer</c> this product opens is opened and closed
/// through here, one at a time, and none is really closed while another is still in use.
/// </summary>
/// <remarks>
/// <para>
/// <b>WHY (2026-11-12, the first sessions recorded as administrator with PawnIO).</b> The Agent holds up to three
/// <c>Computer</c>s at once — a session's L2 source, its CPU-temperature reader, and the shared reader of Advanced
/// metrics — each opened and closed on its own schedule, from its own thread. LibreHardwareMonitorLib keeps part of
/// its state per process, not per <c>Computer</c>: the driver it reads the processor through and the mutexes it
/// guards the buses with. <c>Computer.Close()</c> lets go of that shared part whoever else still has a
/// <c>Computer</c> open. On the owner's PC, with an i7-14700KF:
/// </para>
/// <list type="bullet">
/// <item>after seven sessions of ten, some seconds after the session's own sources closed, the Advanced reader's
/// processor device threw <c>NullReferenceException</c> on two updates running and was left alone — the page lost
/// the processor's sensors until the reader was opened again;</item>
/// <item>once, a session's start and another instance's close met: the Advanced reader's <c>Open</c> threw
/// <c>ObjectDisposedException</c> on a wait handle, and that session stored the NVIDIA driver's seventeen series
/// and none of the sensor library's hundred and ninety-five.</item>
/// </list>
/// <para>
/// Neither can be seen unelevated — without PawnIO the processor group reads nothing through a driver — which is why
/// no test met it before a real run did. The cause is read from the timing in the Agent's log, not reproduced: the
/// tests here hold the two rules below, and whether they end the faults is the owner's next sessions to show.
/// </para>
/// <para>
/// <b>THE TWO RULES.</b> (1) <c>Open</c> and <c>Close</c> are serialised: no two run at once. (2) A <c>Computer</c>
/// closed by its user while another is open is <b>parked</b> — left open, read by nobody — and handed to the next user
/// who asks for the same groups; the library is closed for real when its last user lets go, and then every parked
/// one is closed with it. So the shared part goes only when nobody is reading.
/// </para>
/// <para>
/// <b>WHAT IS NOT SERIALISED: the reads.</b> A reader updates its devices on its own thread, as before. A lock around
/// every read would put the session's once-a-second L2 poll behind the Advanced reader's — the two were put on
/// separate threads so that a sensor that hangs in one holds up neither the other nor the pipe
/// (<c>18_GPU_VENDOR_APIS</c> §Advanced metrics). Two <c>Computer</c>s reading side by side is what ten real sessions
/// did without a fault; it is one closing under the other that failed.
/// </para>
/// <para>Parked instances are bounded by how many users were ever open at once — three in the Agent.</para>
/// </remarks>
public sealed class LhmLibrary
{
private readonly Func<LhmGroups, ILhmComputer> _create;
private readonly Lock _gate = new();
private readonly List<(LhmGroups Groups, ILhmComputer Computer)> _parked = [];
private int _users;
/// <summary>A library over <paramref name="create"/>; the process has one (<see cref="Process"/>), a test makes its own.</summary>
/// <param name="create">Makes a <c>Computer</c> with exactly these groups, not yet opened.</param>
public LhmLibrary(Func<LhmGroups, ILhmComputer> create) => _create = create ?? throw new ArgumentNullException(nameof(create));
/// <summary>The process's own: every <see cref="LhmComputerAdapter"/> goes through it.</summary>
public static LhmLibrary Process { get; } = new(static groups => new RealComputer(groups));
/// <summary>How many users hold a <c>Computer</c> now.</summary>
public int Users
{
get
{
lock (_gate)
{
return _users;
}
}
}
/// <summary>How many <c>Computer</c>s are open with no user, waiting for the next one or for the last close.</summary>
public int Parked
{
get
{
lock (_gate)
{
return _parked.Count;
}
}
}
/// <summary>
/// An open <c>Computer</c> with these groups: a parked one where there is one, else a new one, opened here. An
/// open that throws leaves nothing behind and counts no user.
/// </summary>
public ILhmComputer Open(LhmGroups groups)
{
lock (_gate)
{
int at = _parked.FindIndex(p => p.Groups == groups);
ILhmComputer computer;
if (at >= 0)
{
computer = _parked[at].Computer;
_parked.RemoveAt(at);
}
else
{
computer = _create(groups);
computer.Open();
}
_users++;
return computer;
}
}
/// <summary>
/// Lets go of a <c>Computer</c> that <see cref="Open"/> returned. While another user remains it is parked, still
/// open; the last user's close closes it and every parked one — all of them, even when one throws, and then the
/// first exception is thrown on.
/// </summary>
public void Close(LhmGroups groups, ILhmComputer computer)
{
ArgumentNullException.ThrowIfNull(computer);
lock (_gate)
{
if (_users > 0)
{
_users--;
}
if (_users > 0)
{
_parked.Add((groups, computer));
return;
}
// Every one is closed whatever the one before it did: `first ??= TryClose(...)` would stop closing at the
// first throw, which is the one outcome this method exists to rule out.
ExceptionDispatchInfo? first = null;
foreach ((LhmGroups _, ILhmComputer parked) in _parked)
{
ExceptionDispatchInfo? thrown = TryClose(parked);
first ??= thrown;
}
_parked.Clear();
ExceptionDispatchInfo? last = TryClose(computer);
(first ?? last)?.Throw();
}
}
private static ExceptionDispatchInfo? TryClose(ILhmComputer computer)
{
try
{
computer.Close();
return null;
}
catch (Exception e) when (e is not OperationCanceledException)
{
// Kept, not thrown here: the others are still to be closed, and the shared part of the library with them.
return ExceptionDispatchInfo.Capture(e);
}
}
/// <summary>The real <c>Computer</c>, with the groups asked for and no other (D103).</summary>
private sealed class RealComputer(LhmGroups groups) : ILhmComputer
{
private readonly Computer _computer = new()
{
IsGpuEnabled = groups.HasFlag(LhmGroups.Gpu),
IsCpuEnabled = groups.HasFlag(LhmGroups.Cpu),
IsMemoryEnabled = groups.HasFlag(LhmGroups.Memory),
IsMotherboardEnabled = groups.HasFlag(LhmGroups.Motherboard),
};
public IReadOnlyList<IHardware> Hardware => [.. _computer.Hardware];
public void Open() => _computer.Open();
public void Update() => _computer.Accept(new UpdateVisitor());
public void Close() => _computer.Close();
}
}
@@ -0,0 +1,201 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
using FluentAssertions;
using FrameLedger.Infrastructure.Telemetry;
using LibreHardwareMonitor.Hardware;
namespace FrameLedger.Infrastructure.Tests.Telemetry;
/// <summary>
/// The two rules of <see cref="LhmLibrary"/> (2026-11-12): opens and closes never run at once, and a <c>Computer</c>
/// is not really closed while another is in use. The fault they exist for - one instance's close taking the
/// library's per-process state from under another - needs an elevated Agent with PawnIO and was met on the owner's
/// PC; here the rules are held on scripted instances, which is what can be held without a driver.
/// </summary>
public sealed class LhmLibraryTests
{
private const LhmGroups _session = LhmGroups.Gpu;
private const LhmGroups _advanced = LhmGroups.Gpu | LhmGroups.Cpu | LhmGroups.Memory | LhmGroups.Motherboard;
/// <summary>A library whose instances are scripted, each remembered with the groups it was made for.</summary>
private sealed class Script
{
public List<(LhmGroups Groups, FakeLhmComputer Computer)> Made { get; } = [];
public bool NextOpenThrows { get; set; }
public bool EveryCloseThrows { get; set; }
public LhmLibrary Library => field ??= new LhmLibrary(groups =>
{
var computer = new FakeLhmComputer { OpenThrows = NextOpenThrows, CloseThrows = EveryCloseThrows };
NextOpenThrows = false;
Made.Add((groups, computer));
return computer;
});
}
[Fact]
public void OneUserOpensItsComputerAndClosingItClosesIt()
{
var script = new Script();
var only = new LhmComputerAdapter(_session, script.Library);
only.Hardware.Should().BeEmpty("nothing is open yet");
only.Open();
only.Open();
script.Made.Should().ContainSingle("a second Open while open changes nothing").Which.Computer.Opens.Should().Be(1);
script.Library.Users.Should().Be(1);
only.Close();
only.Close();
script.Made[0].Computer.Closes.Should().Be(1, "and it lets go once");
script.Library.Users.Should().Be(0);
script.Library.Parked.Should().Be(0);
}
[Fact]
public void AComputerIsNotClosedWhileAnotherIsInUse()
{
// THE DEFECT. A session ends and closes its source while the Advanced reader - held by the page - reads on.
// The session's Computer must stay open: closing it lets go of what the reader's processor device reads through.
var script = new Script();
var reader = new LhmComputerAdapter(_advanced, script.Library);
var session = new LhmComputerAdapter(_session, script.Library);
reader.Open();
session.Open();
session.Close();
script.Made.Should().HaveCount(2);
script.Made.Should().OnlyContain(static m => m.Computer.Closes == 0, "nothing is closed while the reader is open");
script.Library.Users.Should().Be(1);
script.Library.Parked.Should().Be(1);
session.Hardware.Should().BeEmpty("the session's user has let go, whatever the library keeps");
// The last user closes the library: its own Computer and the parked one, then there is nothing left.
reader.Close();
script.Made.Should().OnlyContain(static m => m.Computer.Closes == 1);
script.Library.Users.Should().Be(0);
script.Library.Parked.Should().Be(0);
}
[Fact]
public void TheNextSessionTakesTheParkedComputerOfItsGroupsSoNothingPilesUp()
{
// The page stays open all evening and ten sessions come and go: one parked Computer, handed on, not ten.
var script = new Script();
var reader = new LhmComputerAdapter(_advanced, script.Library);
reader.Open();
for (int n = 0; n < 10; n++)
{
var session = new LhmComputerAdapter(_session, script.Library);
session.Open();
session.Close();
}
script.Made.Should().HaveCount(2, "the reader's, and one for every session after the first found it parked");
script.Made[1].Computer.Opens.Should().Be(1, "a parked Computer is still open: it is handed over, not opened again");
script.Library.Parked.Should().Be(1);
// Another set of groups is another Computer: a parked GPU-only one cannot stand in for the processor's.
var temperature = new LhmComputerAdapter(LhmGroups.Cpu | LhmGroups.Memory, script.Library);
temperature.Open();
script.Made.Should().HaveCount(3);
script.Made[2].Groups.Should().Be(LhmGroups.Cpu | LhmGroups.Memory);
temperature.Close();
reader.Close();
script.Made.Should().OnlyContain(static m => m.Computer.Closes == 1);
}
[Fact]
public void AnOpenThatThrowsCountsNoUserAndLeavesNothingBehind()
{
var script = new Script { NextOpenThrows = true };
var failing = new LhmComputerAdapter(_advanced, script.Library);
failing.Invoking(static a => a.Open()).Should().Throw<InvalidOperationException>();
script.Library.Users.Should().Be(0);
script.Library.Parked.Should().Be(0);
failing.Close();
script.Made[0].Computer.Closes.Should().Be(0, "what never opened is not closed");
// And the next user is the first: its close is the last close.
var next = new LhmComputerAdapter(_session, script.Library);
next.Open();
next.Close();
script.Made[1].Computer.Closes.Should().Be(1);
}
[Fact]
public void TheLastCloseClosesEveryComputerEvenWhenOneThrowsAndThenSaysSo()
{
var script = new Script { EveryCloseThrows = true };
var reader = new LhmComputerAdapter(_advanced, script.Library);
var session = new LhmComputerAdapter(_session, script.Library);
reader.Open();
session.Open();
session.Close();
reader.Invoking(static a => a.Close()).Should().Throw<InvalidOperationException>("the caller is told, as it was before");
script.Made.Should().OnlyContain(static m => m.Computer.Closes == 1, "a throw from one does not leave the other open");
script.Library.Users.Should().Be(0);
script.Library.Parked.Should().Be(0, "and the library starts afresh for the next user");
}
[Fact]
public async Task OpensAndClosesFromManyThreadsNeverRunAtOnce()
{
// Rule 1. Each scripted instance says so if it is entered while another Open or Close is inside.
int inside = 0;
int overlaps = 0;
var library = new LhmLibrary(_ => new Probe(() =>
{
if (Interlocked.Increment(ref inside) != 1)
{
Interlocked.Increment(ref overlaps);
}
Thread.SpinWait(200);
Interlocked.Decrement(ref inside);
}));
Task[] users = [.. Enumerable.Range(0, 8).Select(n => Task.Run(() =>
{
LhmGroups groups = (n % 2 == 0) ? _session : _advanced;
for (int i = 0; i < 200; i++)
{
var user = new LhmComputerAdapter(groups, library);
user.Open();
user.Close();
}
}, TestContext.Current.CancellationToken))];
await Task.WhenAll(users);
overlaps.Should().Be(0);
library.Users.Should().Be(0);
library.Parked.Should().Be(0);
}
/// <summary>An instance that runs <paramref name="entered"/> inside every Open and Close.</summary>
private sealed class Probe(Action entered) : ILhmComputer
{
public IReadOnlyList<IHardware> Hardware => [];
public void Open() => entered();
public void Update()
{
}
public void Close() => entered();
}
}
@@ -21,6 +21,49 @@ namespace FrameLedger.Infrastructure.Tests.Telemetry;
[Collection(LibreHardwareMonitorCollection.Name)]
public sealed class LhmRealHardwareTests
{
[Fact]
public void TwoUsersOfTheRealLibraryOneLetsGoAndTheOtherStillReads()
{
// The shape that failed on the owner's PC (2026-11-12): a session's source closes while the Advanced reader
// reads on. Unelevated this cannot show the fault itself - that needs PawnIO and the processor group - so it
// asserts what LhmLibrary promises of the real Computer: the second user's tree is still there and still
// updates, the first one's Computer is parked and handed to the next user, and the last close leaves nothing.
LhmLibrary library = LhmLibrary.Process;
int usersBefore = library.Users;
int parkedBefore = library.Parked;
var reader = new LhmComputerAdapter(LhmGroups.Gpu);
var session = new LhmComputerAdapter(LhmGroups.Gpu);
try
{
reader.Open();
session.Open();
int devices = reader.Hardware.Count;
session.Close();
library.Users.Should().Be(usersBefore + 1);
reader.Invoking(static r => r.Update()).Should().NotThrow("its library was not closed under it");
reader.Hardware.Should().HaveCount(devices);
var next = new LhmComputerAdapter(LhmGroups.Gpu);
next.Open();
library.Parked.Should().Be(parkedBefore, "the next session took the parked Computer rather than opening another");
next.Hardware.Should().HaveCount(devices);
next.Close();
}
finally
{
session.Close();
reader.Close();
}
library.Users.Should().Be(usersBefore);
if (usersBefore == 0)
{
library.Parked.Should().Be(0, "the last user's close closes every parked Computer with its own");
}
}
[Fact]
public void TheRealLibraryEitherSamplesOrDisablesAndNeverClaimsAFieldItDidNotRead()
{