Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
dc4fc99029 |
No files matched your search
@@ -178,7 +178,7 @@ jobs:
|
||||
}
|
||||
Get-ChildItem $dest | ForEach-Object { Write-Host (" {0,-64} {1,8:N0}" -f $_.Name, $_.Length) }
|
||||
|
||||
# What ships is what matters: the two entry points and the four shipped native
|
||||
# What ships is what matters: the two entry points and the five shipped native
|
||||
# binaries (versioninfo-check's list) must be in the tree, and the unshipped
|
||||
# capture host must not be (package-closure-check proves it statically; this
|
||||
# reads the directory).
|
||||
@@ -186,7 +186,7 @@ jobs:
|
||||
shell: pwsh
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$required = 'FrameLedger.exe', 'FrameLedger.Agent.exe', 'FrameLedger.Overlay.dll', 'FrameLedger.VkLayer.dll', 'FrameLedger.Guard.dll', 'FrameLedger.NvapiBridge.dll', 'rules/detection-rules.json',
|
||||
$required = 'FrameLedger.exe', 'FrameLedger.Agent.exe', 'FrameLedger.Overlay.dll', 'FrameLedger.VkLayer.dll', 'FrameLedger.Guard.dll', 'FrameLedger.NvapiBridge.dll', 'FrameLedger.ProcessStats.dll', 'rules/detection-rules.json',
|
||||
'licenses/nuget/INDEX.md', 'licenses/THIRD_PARTY_NOTICES.md', 'licenses/FrameLedger-GPL-3.0.txt', 'licenses/NOTICE.txt', 'licenses/mpl-2.0.txt', 'licenses/apache-2.0.txt'
|
||||
$missing = @($required | Where-Object { -not (Test-Path (Join-Path out/app $_)) })
|
||||
if ($missing.Count -gt 0) { throw "out/app is missing: $($missing -join ', ')" }
|
||||
|
||||
@@ -29,6 +29,22 @@ under a `## [x.y.z] - date` heading in the same commit that bumps `VERSION`, the
|
||||
|
||||
### Added
|
||||
|
||||
- **The game's own memory, measured from outside the game, in every session** (owner decision D43, beta.12). A new
|
||||
C++ library loaded by the Agent — never into a game — `FrameLedger.ProcessStats.dll`, reads once a second the game
|
||||
process's **dedicated and shared GPU memory** (the documented `GPU Process Memory` performance counters, which need no
|
||||
handle to the game) and its **private working set, working set and commit** (`GetProcessMemoryInfo` with
|
||||
`PROCESS_QUERY_LIMITED_INFORMATION` only) — the numbers Task Manager's Details tab shows. A hooked game is read through
|
||||
the handle the session already holds; a game that is not measured (anti-cheat, hooking off) through a handle opened for
|
||||
the read and closed after it, the same least right the watcher already uses on every process, every process running its
|
||||
executable added up, a reused pid refused. Measured before it was written in (`spike-notes` §16): a 512 MiB allocation
|
||||
read +512.0 MiB, the private working set equals Windows' own counter, one read costs 0.1 ms, 600 reads leak nothing.
|
||||
Stored as five new sensor series and, in schema **0018**, the median / mean / peak columns
|
||||
(`game_vram_dedicated_*`, `game_ram_private_*`, …), the process count, the sources, and every sensor series'
|
||||
n / mean / median / min / max in `sensor_stats_json`; carried live to the Dashboard (`SessionProgress`, `SessionHeld`)
|
||||
and through the crash-recovery file (a new chunk type; beta.11's files still recover). The video-memory **budget** is
|
||||
still not measured (`20_OPEN_QUESTIONS` §M11). The App shows all of it in the next change.
|
||||
- **Sensor statistics have a median and a minimum** beside the mean and the maximum (`SeriesAggregates`).
|
||||
|
||||
- **`NOTICE`, and the licence header in every source file** (owner decision D45, beta.12). FrameLedger's own material is
|
||||
GPL-3.0-only with three additional terms of the kinds GPLv3 §7 permits: keep the copyright line and the attribution in
|
||||
the program's legal notices (b), mark a modified version as different and do not call it "FrameLedger" alone (c), and
|
||||
@@ -47,6 +63,15 @@ under a `## [x.y.z] - date` heading in the same commit that bumps `VERSION`, the
|
||||
|
||||
### Fixed
|
||||
|
||||
- **A licence header written by a contributor no longer has to name poli0981**: `tools/notice-check.ps1` accepts any
|
||||
holder and year in the same form (`Copyright (C) <year> <holder> - additional terms under GPLv3 section 7: see NOTICE`),
|
||||
and `CONTRIBUTING.md` says so; seven self-test cases.
|
||||
- **Documents that described a per-process VRAM figure the Overlay never produced** are corrected in place
|
||||
(`03_METRICS`, `17_HOOK_ENGINE`, `18_GPU_VENDOR_APIS`, `20_OPEN_QUESTIONS` §M7/§H10), and the two that said an unmeasured
|
||||
session opens no process (`04_CAPTURE`, `19_SAFETY`) now say what it opens, with which right, and why. The accuracy block
|
||||
and `LIMITATIONS.md` say what is measured now. `ITelemetryPoller`'s remark that the descriptor is read at finalize — it is
|
||||
read at session start — is corrected.
|
||||
|
||||
- **The native binaries' version block named the wrong licence.** Every DLL's `LegalCopyright` read
|
||||
`GPL-3.0-or-later` while `LICENSE`, the EULA, the README and the third-party notices all say GPL-3.0-only; it now reads
|
||||
`Copyright (C) 2026 poli0981. GPL-3.0-only with additional terms: see NOTICE`.
|
||||
|
||||
@@ -47,7 +47,7 @@ A C++ DLL (`FrameLedger.Overlay.dll`) is injected into games the user explicitly
|
||||
| UI | WPF + WPF UI (`WPF-UI` pinned = 4.3.0) + CommunityToolkit.Mvvm — `docs/16_WPFUI_SYNTAX.md` |
|
||||
| App composition | .NET Generic Host + DI in `FrameLedger.App` |
|
||||
| Charts | ScottPlot 5 |
|
||||
| GPU telemetry | Layered: DXGI + PDH counters (all vendors) → LibreHardwareMonitorLib (MPL-2.0, all vendors) → **NVAPI (MIT, headers + `amd64/nvapi64.lib` vendored 2026-08-05** at `src/native/third_party/nvapi/`, consumed via the `fl_nvapi` target; NVIDIA extras + Reflex). **No AMD/Intel vendor SDK** — `docs/18_GPU_VENDOR_APIS.md`. ~~**No telemetry source exists in code yet**~~ **`LhmTelemetrySource` (L2) exists since 2026-09-03 (`20_OPEN_QUESTIONS` §M5 row R1, eight GPU fields unelevated); L1 (`BaselineTelemetrySource`: DXGI identity + the PDH adapter-memory counter, the first CsWin32 consumer), `CompositeTelemetrySource` and the 1 Hz `TelemetryPoller` since 2026-09-09; L3 (`NvapiTelemetrySource` over the native `FrameLedger.NvapiBridge.dll` — the only shipped binary linking `nvapi64.lib`, loaded by the Agent into its own process and never into a game) since 2026-09-10 (PR-E2)** — `ctest fl_nvapi_probe` was the only NVAPI consumer until then, and it exists so the vendoring is verified rather than asserted. This row said no source existed for six days after one did, recorded 2026-09-09 rather than repaired quietly. This row previously claimed the vendoring in the present tense while `third_party/` held only `vulkan-headers`; `legal/` had already caught the identical claim about itself and gained a bidirectional gate, which is what made the real vendoring a red-then-green |
|
||||
| GPU telemetry | **The game process's own memory since beta.12 (D43):** `FrameLedger.ProcessStats.dll` (C++, loaded by the Agent, never into a game) reads its dedicated/shared GPU memory from the `GPU Process Memory` counters and its working sets from `GetProcessMemoryInfo` — `18_GPU_VENDOR_APIS` §The game process's memory. Layered: DXGI + PDH counters (all vendors) → LibreHardwareMonitorLib (MPL-2.0, all vendors) → **NVAPI (MIT, headers + `amd64/nvapi64.lib` vendored 2026-08-05** at `src/native/third_party/nvapi/`, consumed via the `fl_nvapi` target; NVIDIA extras + Reflex). **No AMD/Intel vendor SDK** — `docs/18_GPU_VENDOR_APIS.md`. ~~**No telemetry source exists in code yet**~~ **`LhmTelemetrySource` (L2) exists since 2026-09-03 (`20_OPEN_QUESTIONS` §M5 row R1, eight GPU fields unelevated); L1 (`BaselineTelemetrySource`: DXGI identity + the PDH adapter-memory counter, the first CsWin32 consumer), `CompositeTelemetrySource` and the 1 Hz `TelemetryPoller` since 2026-09-09; L3 (`NvapiTelemetrySource` over the native `FrameLedger.NvapiBridge.dll` — the only shipped binary linking `nvapi64.lib`, loaded by the Agent into its own process and never into a game) since 2026-09-10 (PR-E2)** — `ctest fl_nvapi_probe` was the only NVAPI consumer until then, and it exists so the vendoring is verified rather than asserted. This row said no source existed for six days after one did, recorded 2026-09-09 rather than repaired quietly. This row previously claimed the vendoring in the present tense while `third_party/` held only `vulkan-headers`; `legal/` had already caught the identical claim about itself and gained a bidirectional gate, which is what made the real vendoring a red-then-green |
|
||||
| CPU/board sensors | LibreHardwareMonitorLib ≥ 0.9.6 (PawnIO) — **optional**, elevated only |
|
||||
| Tier-2 fallback | **There is none, and Tier 2 is not a measurement.** Owner decision 2026-08-28: the ladder is two rungs — hooked, or duration + sensors + the reason. ~~ETW-based, no injection~~; ~~Intel PresentMon console binary~~ dropped 2026-08-27 after §S31 retired it. Whether a shipped build ever regains a no-injection measurement is `docs/20_OPEN_QUESTIONS.md` §G |
|
||||
| Storage | SQLite via Microsoft.Data.Sqlite + Dapper (no EF) |
|
||||
@@ -137,7 +137,7 @@ rules/detection-rules.json # engine/platform/capability + anticheat blocklis
|
||||
docs/ legal/ legal/licenses/
|
||||
```
|
||||
|
||||
Dependency direction: `App/Agent → Application → Domain`; **`Application → Shared` since 2026-09-09** (P2 PR-A, decision D1 — `Application.Metrics.FrameSampleMapper` is where `FlFrameRecord` becomes Domain's `FrameSample`, and `Application.Capture.CaptureSession`, hosted there since PR-C the same day, is written over the record; `DrainResult` moved to Shared with it); `Infrastructure` implements `Application` ports; Domain references nothing. **The native layer is reachable only through `Infrastructure`** — no P/Invoke anywhere else. **Two facades since 2026-09-10:** `NativeAntiCheatGuard` (required — absent throws) and `NativeNvapiBridge` (optional — absent is a missing telemetry layer that reports itself), both by absolute path beside the assembly through its one `DllImport` resolver, `Infrastructure.Native.BesideThisAssembly`; the runtime allows one resolver per assembly, which is why a third facade claims a name there rather than setting its own.
|
||||
Dependency direction: `App/Agent → Application → Domain`; **`Application → Shared` since 2026-09-09** (P2 PR-A, decision D1 — `Application.Metrics.FrameSampleMapper` is where `FlFrameRecord` becomes Domain's `FrameSample`, and `Application.Capture.CaptureSession`, hosted there since PR-C the same day, is written over the record; `DrainResult` moved to Shared with it); `Infrastructure` implements `Application` ports; Domain references nothing. **The native layer is reachable only through `Infrastructure`** — no P/Invoke anywhere else. **~~Two~~ Three facades since ~~2026-09-10~~ 2026-10-03:** `NativeAntiCheatGuard` (required — absent throws), `NativeNvapiBridge` (optional — absent is a missing telemetry layer that reports itself) and, since beta.12 (D43), `NativeProcessStats` (optional — the game process's own memory, read from outside the game; absent reads N/A), all by absolute path beside the assembly through its one `DllImport` resolver, `Infrastructure.Native.BesideThisAssembly`; the runtime allows one resolver per assembly, which is why the third facade claims a name there rather than setting its own.
|
||||
|
||||
## Coding conventions
|
||||
|
||||
|
||||
+3
-1
@@ -37,7 +37,9 @@ The definition of done is the one in `CLAUDE.md`:
|
||||
- every new user-visible string exists in `en`, `vi` and `ja` (`docs/09_I18N.md`);
|
||||
- a change that makes a document wrong updates that document in the same PR;
|
||||
- a change under `src/` adds an entry under `## [Unreleased]` in `CHANGELOG.md`;
|
||||
- every new source file carries the licence header — `./tools/notice-check.ps1 -Fix` writes it.
|
||||
- every new source file carries the licence header — `./tools/notice-check.ps1 -Fix` writes it. A file you wrote
|
||||
yourself may name you in its second line instead, in the same form:
|
||||
`Copyright (C) <year> <your name> - additional terms under GPLv3 section 7: see NOTICE`.
|
||||
|
||||
The pull-request template lists the safety checks for changes to the capture layer.
|
||||
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
<Project>
|
||||
|
||||
<!--
|
||||
Ships FrameLedger.ProcessStats.dll beside the importing project's output (beta.12, owner decision D43).
|
||||
|
||||
The third P/Invoke facade after the guard's and the NVAPI bridge's (docs/18_GPU_VENDOR_APIS.md §L1, the game
|
||||
process's memory): NativeProcessStats loads it BY ABSOLUTE PATH from AppContext.BaseDirectory and never falls back
|
||||
to a search, so it has to actually be there. Read-only, and NEVER loaded into a game — the Agent (and the unshipped
|
||||
capture host) load it into their own process for the 1 Hz read of a game's dedicated/shared GPU memory (the
|
||||
GPU Process Memory counters) and its working sets (GetProcessMemoryInfo).
|
||||
|
||||
Imported by the same three projects as the bridge: FrameLedger.Agent, FrameLedger.CaptureHost and
|
||||
FrameLedger.Infrastructure.Tests (the mirror test and the real read P/Invoke into the real DLL).
|
||||
|
||||
Warn rather than fail when absent, as the bridge does: an absent reader is a missing measurement (every game-memory
|
||||
field reads N/A), not a safety hole.
|
||||
-->
|
||||
<PropertyGroup>
|
||||
<FlProcessStatsOutDir>$(MSBuildThisFileDirectory)build\native\x64-release\FrameLedger.ProcessStats\</FlProcessStatsOutDir>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Include="$(FlProcessStatsOutDir)FrameLedger.ProcessStats.dll" Condition="Exists('$(FlProcessStatsOutDir)FrameLedger.ProcessStats.dll')">
|
||||
<Link>FrameLedger.ProcessStats.dll</Link>
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
<Target Name="FlWarnOnMissingProcessStats" AfterTargets="Build"
|
||||
Condition="!Exists('$(FlProcessStatsOutDir)FrameLedger.ProcessStats.dll')">
|
||||
<Warning Text="FrameLedger.ProcessStats.dll was not found at $(FlProcessStatsOutDir). Run build.ps1 native first; the game's memory will read N/A." />
|
||||
</Target>
|
||||
|
||||
</Project>
|
||||
+17
-4
@@ -34,7 +34,8 @@ page lists them in plain words; each item links to the document that has the det
|
||||
## What an unmeasured session contains
|
||||
|
||||
When a game is not measured — any of the reasons above — its session still records **how long it ran, the
|
||||
machine's sensors (GPU temperature, load, power; CPU load; memory) and why nothing was measured.** Every
|
||||
machine's sensors (GPU temperature, load, power; CPU load; memory), how much memory the game itself used (read from
|
||||
Windows, outside the game) and why nothing was measured.** Every
|
||||
frame-rate, upscaler, frame-generation and ray-tracing value reads **N/A**, never 0. How the game's window was
|
||||
shown is recorded too, from outside the game. ([Capture](docs/04_CAPTURE.md))
|
||||
|
||||
@@ -63,9 +64,21 @@ shown is recorded too, from outside the game. ([Capture](docs/04_CAPTURE.md))
|
||||
- **Ray tracing** is *Yes*, *No* or *N/A* — measured from the game's ray-tracing calls on Direct3D 12, and
|
||||
N/A where FrameLedger could not look. **Path tracing is never stated as a fact**: there is no API signal
|
||||
for it. You can correct any of these by hand, and your correction is labelled as yours.
|
||||
- HDR output, NVIDIA Reflex latency, each game's own video-memory use and shader-compilation stutter are
|
||||
**not measured yet** — they read N/A. Video memory in use on the whole graphics card is recorded.
|
||||
([Accuracy](legal/ACCURACY.md))
|
||||
- HDR output, NVIDIA Reflex latency, the video-memory budget Windows gives a game, and shader-compilation
|
||||
stutter are **not measured yet** — they read N/A. ([Accuracy](legal/ACCURACY.md))
|
||||
|
||||
## The game's memory
|
||||
|
||||
- **What is shown is what Task Manager's Details tab shows** for the game's process — *Dedicated GPU memory*,
|
||||
*Shared GPU memory* and *Memory* (the private working set) — read from Windows once a second, from outside
|
||||
the game. FrameLedger never looks inside the game's memory to get it.
|
||||
- **One process.** A measured game is its own process; for a game that is not measured, every process running
|
||||
the game's executable is added together. Launchers, crash reporters and other helper programs are not counted.
|
||||
- **The private working set needs a recent Windows**: Windows 10 22H2 or Windows 11 with the September 2023
|
||||
update or later. Without it the working set is shown instead, labelled as such.
|
||||
- A game that has not created anything on the graphics card yet (its first second, a launcher screen) reads
|
||||
N/A for video memory. AMD and Intel graphics cards have not been tested.
|
||||
([Metrics](docs/03_METRICS.md))
|
||||
|
||||
## Display mode (full-screen, borderless, windowed)
|
||||
|
||||
|
||||
@@ -59,8 +59,14 @@
|
||||
> - **Engine version:** the exact Unreal Engine 4 or 5 version, read from the game's executable on disk and
|
||||
> labelled with what it rests on; `N/A` where the executable names none. Other engines show what their own
|
||||
> files state.
|
||||
> - **The game's own memory (since beta.12):** its dedicated and shared GPU memory and its private
|
||||
> working set — the numbers Task Manager's Details tab shows — with its working set and commit, read
|
||||
> once a second from Windows' own counters, from outside the game, in every session: a game
|
||||
> FrameLedger injects into through the handle it already holds, any other by opening it briefly with
|
||||
> the least access Windows offers (and adding up every process running its executable). Shown with
|
||||
> mean, median and peak. The game's other processes (launchers, helpers) are not counted.
|
||||
> - **Video memory:** in use on the whole graphics card, recorded from Windows and GPU-driver telemetry
|
||||
> and charted. **Not measured at all:** each game's own video-memory use and budget, which frame
|
||||
> and charted. **Not measured at all:** the video-memory budget Windows gives a game, which frame
|
||||
> spikes were shader compilation, PC latency (Reflex), and HDR. Stutter count and stutter time are
|
||||
> measured from frame times.
|
||||
> - **Processor and memory:** how busy the processor was (time busy, all cores together — not the
|
||||
|
||||
@@ -443,7 +443,7 @@ function Invoke-ProjectGates {
|
||||
}
|
||||
|
||||
# beta.12 (D45): GPLv3 section 7 wants additional terms named "in the relevant source files", so every
|
||||
# first-party source file opens with the SPDX line and the NOTICE pointer. Self-test first (six cases, both
|
||||
# first-party source file opens with the SPDX line and the NOTICE pointer. Self-test first (seven cases, both
|
||||
# directions), then the live pass over the tracked tree; ./tools/notice-check.ps1 -Fix writes a missing header.
|
||||
Write-Step 'notice-check'
|
||||
$noticeTool = Join-Path $repo 'tools/notice-check.ps1'
|
||||
|
||||
@@ -23,7 +23,8 @@
|
||||
│ ├ upscaler hooks: NGX · Streamline · FFX · XeSS │
|
||||
│ ├ RT hooks: CreateStateObject · DispatchRays · BuildRaytracingAS │
|
||||
│ ├ PSO hooks: pipeline creation (stutter attribution) │
|
||||
│ ├ per-process VRAM: IDXGIAdapter3::QueryVideoMemoryInfo │
|
||||
│ ├ (per-process VRAM via QueryVideoMemoryInfo: never built — D43 reads │
|
||||
│ │ the game's memory from outside, in the Agent's ProcessStats.dll) │
|
||||
│ └ ring writer (allocation-free, lock-free, SEH-guarded) │
|
||||
└───────────────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
+2
-2
@@ -39,9 +39,9 @@ Requirement IDs (`FR-x`, `NFR-x`) are referenced by other docs, commits, and tes
|
||||
- FR-4.2 **Native vs Displayed FPS + FG factor**, always shown together (`62 → 118 FPS (×1.9 FG)`).
|
||||
- FR-4.3 *(Tier 1)* Measured upscaler identity, quality preset, render resolution, output resolution, upscale ratio; mid-session changes captured as segments.
|
||||
- FR-4.4 *(Tier 1)* Measured RT activity (`rt_frame_pct`, `rays_per_pixel`, RT PSO count); RR from the NGX feature; PT as a confidence-scored suggestion only.
|
||||
- FR-4.5 *(Tier 1)* Per-process VRAM usage/budget and budget-exceeded percentage.
|
||||
- FR-4.5 *(Tier 1)* Per-process VRAM usage/budget and budget-exceeded percentage. *(beta.12, owner decision D43: the **usage** half is met for **both tiers** from outside the game — the game process's dedicated and shared GPU memory, Task Manager's columns — with its private working set, working set and commit beside it, mean / median / peak (`03_METRICS` §Game process memory). The budget and its exceeded percentage stay unmeasured, `20_OPEN_QUESTIONS` §M11.)*
|
||||
- FR-4.6 *(Tier 1)* PSO-compilation stutter attribution; *(Tier 1 + Reflex)* PC latency avg/p95.
|
||||
- FR-4.7 Telemetry aggregates: CPU/GPU temp, hotspot, loads, power, throttle %, RAM.
|
||||
- FR-4.7 Telemetry aggregates: CPU/GPU temp, hotspot, loads, power, throttle %, RAM. *(beta.12: every stored series also has its median and minimum, in `sensor_stats_json`.)*
|
||||
- FR-4.8 Sufficiency guards: 0.1% Low needs ≥ 10,000 app frames, 1% Low ≥ 1,000; else `N/A`.
|
||||
- FR-4.9 Any metric unavailable at the session's tier renders `N/A` — never an estimate presented as measurement.
|
||||
|
||||
|
||||
+44
-4
@@ -745,13 +745,53 @@ its Sessions column, three Trend metrics — *Exclusive fullscreen share %*, *Bo
|
||||
tier, and a mode switch is not a mid-session change for them (switching resizes the swap chain; the share is what that
|
||||
switch was) — three Compare rows, never ranked, and the CSV's `# display:` line (§Export schema) and the JSON's aggregates.
|
||||
|
||||
## Per-process VRAM (Tier 1)
|
||||
## Game process memory — both tiers (beta.12, owner decision D43)
|
||||
|
||||
`vramUsedMb` from `IDXGIAdapter3::QueryVideoMemoryInfo(LOCAL)` inside the game = **this game's** usage and budget. **MiB, truncating, and it must use the same divisor as `vramBudgetMb`** — the two are compared, and mismatched rounding would put a systematic bias into `budget_exceeded_pct`. Residual: a flip within 1 MiB of the budget, 0.004% of a 24 GiB card. Stored as its own series and clearly labelled apart from the adapter-wide figure from `18_GPU_VENDOR_APIS`. Aggregates: avg, max, and `budget_exceeded_pct` (share of samples where `CurrentUsage > Budget`, i.e. the driver was likely evicting — a genuinely useful stutter explanation).
|
||||
**What is measured since 2026-10-03:** the game process's own memory, read from OUTSIDE the game once a second by the
|
||||
Agent through `FrameLedger.ProcessStats.dll` (`18_GPU_VENDOR_APIS` §The game process's memory) — never from the game's
|
||||
memory (CLAUDE.md rule 4):
|
||||
|
||||
| Figure | Source | What it is |
|
||||
|---|---|---|
|
||||
| **Dedicated GPU memory** (`game_vram_dedicated`) | PDH `\GPU Process Memory(pid_<pid>_luid_…_phys_<n>)\Dedicated Usage`, every instance naming the pid summed | the number Task Manager's Details tab shows under that name |
|
||||
| Shared GPU memory (`game_vram_shared`) | the same counter set's `Shared Usage` | system memory the GPU uses on the game's behalf |
|
||||
| **Memory — private working set** (`game_ram_private`) | `GetProcessMemoryInfo`, `PROCESS_MEMORY_COUNTERS_EX2.PrivateWorkingSetSize` | Task Manager's "Memory" column; N/A on a Windows that predates EX2 (Windows 10 22H2 / 11 22H2 without the September 2023 update) |
|
||||
| Working set (`game_ram_ws`) | `WorkingSetSize` | the whole working set, shared pages included; what the card falls back to where the private working set is N/A |
|
||||
| Commit (`game_commit`) | `PrivateUsage` | private memory committed, resident or not |
|
||||
|
||||
**Which process.** A hooked session — and any session refused after the loop pinned the process — reads the pinned pid
|
||||
through the handle the session already holds (`SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION`). An unpinned Tier-2 hold
|
||||
(hooking off, blocked, unresolved, cannot pin) reads **every process running the game's executable** in the watcher's
|
||||
snapshot, each opened for the read with `PROCESS_QUERY_LIMITED_INFORMATION` and closed after it, and SUMS them; a process
|
||||
whose creation time is not the snapshot's (a reused pid), or that refuses even that right, is left out of both halves.
|
||||
`game_memory_processes` says how many were summed. Child processes of another executable (a launcher, a crash handler, a
|
||||
web view) are not counted.
|
||||
|
||||
**Dedicated is not the DXGI budget model's "local usage".** dwm.exe read 858 MB dedicated against 310 MB local at an idle
|
||||
desktop, and a test process holding a buffer read 4.5 MiB more dedicated than its own `QueryVideoMemoryInfo(LOCAL)` at
|
||||
both 8 MiB and 512 MiB (`spike-notes` §16, M3) — a constant per-device amount, not one that grows with the game's
|
||||
allocations. So dedicated is defined as Task Manager's column and is **never compared with a budget**: the budget and
|
||||
`budget_exceeded_pct` stay unmeasured (`20_OPEN_QUESTIONS` §M11), and `vram_proc_*` / `vram_budget_exceeded_pct` /
|
||||
`FlFrameRecord.vramUsedMb` stay reserved for that in-process figure.
|
||||
|
||||
**Aggregates** (schema 0018): dedicated avg / median / max, shared max, private working set avg / median / max, working
|
||||
set max, commit max, the process count, the sources (`counters,ex2,held,opened`), and every series' n / mean / median /
|
||||
min / max in `sensor_stats_json` (§Sensor aggregates). MiB stored; shown in GB as Task Manager does (1 GB = 1024 MiB).
|
||||
|
||||
> **The paragraph below is the design that was never built, kept as it stood** (struck 2026-10-03: the Overlay never
|
||||
> called `QueryVideoMemoryInfo` — `dllmain.cpp` lists `FL_MEASURED_VRAM` as unproduced, §H10 never settled where in the
|
||||
> game to call it — and D43 chose the outside read instead).
|
||||
|
||||
~~`vramUsedMb` from `IDXGIAdapter3::QueryVideoMemoryInfo(LOCAL)` inside the game = **this game's** usage and budget. **MiB, truncating, and it must use the same divisor as `vramBudgetMb`** — the two are compared, and mismatched rounding would put a systematic bias into `budget_exceeded_pct`. Residual: a flip within 1 MiB of the budget, 0.004% of a 24 GiB card. Stored as its own series and clearly labelled apart from the adapter-wide figure from `18_GPU_VENDOR_APIS`. Aggregates: avg, max, and `budget_exceeded_pct` (share of samples where `CurrentUsage > Budget`, i.e. the driver was likely evicting — a genuinely useful stutter explanation).~~
|
||||
|
||||
## Sensor aggregates
|
||||
|
||||
Per session over 1 Hz samples: `avg` (mean of non-null), `max`. Sensor timeline aligned to the frame timeline via the shared QPC epoch captured at session start. Fields with no data are `N/A`, never 0.
|
||||
Per session over 1 Hz samples: `avg` (mean of non-null), `max` — and since beta.12 the `median` (the linear-interpolation
|
||||
50th percentile: the middle sample of an odd count, the mean of the two middle ones of an even count) and the `min`
|
||||
(`Domain.Metrics.SeriesAggregates`). Every stored series' n / mean / median / min / max is written once at finalize to
|
||||
`sessions.sensor_stats_json`, so the summary's statistics read stored values and outlive a retention sweep of the raw
|
||||
series. Sensor timeline aligned to the frame timeline via the shared QPC epoch captured at session start. Fields with no
|
||||
data are `N/A`, never 0.
|
||||
|
||||
## Accuracy budget (shown in Help → About metrics)
|
||||
|
||||
@@ -762,7 +802,7 @@ Per session over 1 Hz samples: `avg` (mean of non-null), `max`. Sensor timeline
|
||||
| Upscaler + render resolution | **exact** (vendor API arguments) | not available |
|
||||
| RT active | measured per frame | not available |
|
||||
| Path tracing | heuristic, confidence-scored, never asserted | not available |
|
||||
| Per-process VRAM | exact | not available |
|
||||
| ~~Per-process VRAM~~ Game process memory (beta.12) | ~~exact~~ dedicated / shared GPU memory as Task Manager counts it — a known 512 MiB allocation read +512.0 MiB (`spike-notes` §16); private working set equal to Windows' own counter; read from outside the game | ~~not available~~ the same, from outside; an unpinned hold sums the executable's processes |
|
||||
| PC latency | as reported by Reflex | not available |
|
||||
| Display mode (beta.10) | per 100 ms sample: exclusive fullscreen as the swap chain answers it (DXGI; OpenGL and Vulkan cannot say), borderless, windowed, minimised; the window's size from user32 | per 1 s sample, from the window alone: windowed, minimised, or *fullscreen or borderless* — never split |
|
||||
| GPU temp / load / power | vendor API accuracy, ±1 s sampling | same |
|
||||
|
||||
+6
-2
@@ -86,7 +86,11 @@ it still holds.
|
||||
> watcher's own 1 Hz snapshot** (`ITargetResolver.IsRunning` over `LatestProcessSnapshot`, 2026-09-23; a process
|
||||
> whose path could not be read still counts by its name; the console verbs, where nothing polls, keep the name
|
||||
> list) when it never opened the process — by name, another game's `Game.exe` held an RPG Maker game's session
|
||||
> open. Nothing about the hold touches the target, and no process is opened for it. **And hooking-off is decided before the process is opened**: `RunAsync` reads the consent record
|
||||
> open. Nothing about the hold touches the target, and no process is opened for it. *(Corrected 2026-10-03, beta.12, D43:
|
||||
the hold now reads the game's own memory, once a second, by opening each process running the executable with
|
||||
`PROCESS_QUERY_LIMITED_INFORMATION` for the read and closing it after — the right the watcher's own snapshot already uses
|
||||
on every process each second; nothing is held, nothing is injected, and the memory's contents are never read. Its video
|
||||
memory comes from performance counters that need no handle at all; `03_METRICS` §Game process memory.)* **And hooking-off is decided before the process is opened**: `RunAsync` reads the consent record
|
||||
> first, and a row whose hooking is off — merely added, blocked by a finding, auto-disabled — goes straight to
|
||||
> the hold with `RefusedHookNotEnabled` (its verdict is the row's block when it has one, `PreviouslyBlocked`).
|
||||
> The resolver used to run first, and a hooking-off utility that runs elevated (Borderless Gaming, imported from
|
||||
@@ -468,7 +472,7 @@ Crash-within-60s-of-injection happening twice for the same game ⇒ **hooking au
|
||||
|
||||
## Live progress
|
||||
|
||||
`SessionProgress` at 1 Hz to the UI (`07_IPC`): rolling 5 s Native FPS, Displayed FPS, FG factor, current render→output resolution, upscaler + quality, RT active flag, GPU/CPU temp, per-process VRAM, elapsed. Suppressed when no UI client is connected. This is what makes the Dashboard live card genuinely useful — it is showing *measured* settings, not guesses.
|
||||
`SessionProgress` at 1 Hz to the UI (`07_IPC`): rolling 5 s Native FPS, Displayed FPS, FG factor, current render→output resolution, upscaler + quality, RT active flag, GPU/CPU temp, ~~per-process VRAM~~ the game process's dedicated GPU memory and private working set (beta.12, from the newest telemetry tick — `SessionHeld` carries the same two for a held session), elapsed. Suppressed when no UI client is connected. This is what makes the Dashboard live card genuinely useful — it is showing *measured* settings, not guesses.
|
||||
|
||||
> **Built 2026-09-13 (P3 PR-1, HANDOFF §P3 decision D13): `Application.Ipc.SessionProgressCalculator`**, over the last 5 s of the
|
||||
> ring's records through the same calculators the row uses — `FrameTimeSeries` for the presented rate, `FgWindow` + the FG ladder for
|
||||
|
||||
@@ -278,6 +278,16 @@ CREATE TABLE sessions (
|
||||
avg_gpu_load REAL, avg_cpu_load REAL, avg_ram_mb REAL,
|
||||
avg_gpu_power_w REAL, throttle_pct REAL,
|
||||
|
||||
-- schema 0018 (2026-10-03, beta.12, D43): the game process's own memory, read from outside it, both tiers
|
||||
-- (03_METRICS §Game process memory), MiB; and every sensor series' n/mean/median/min/max as JSON
|
||||
game_vram_dedicated_avg_mb REAL, game_vram_dedicated_median_mb REAL, game_vram_dedicated_max_mb REAL,
|
||||
game_vram_shared_max_mb REAL,
|
||||
game_ram_private_avg_mb REAL, game_ram_private_median_mb REAL, game_ram_private_max_mb REAL,
|
||||
game_ram_ws_max_mb REAL, game_commit_max_mb REAL,
|
||||
game_memory_processes INTEGER, -- processes summed: 1 pinned, every process of the executable for a held one
|
||||
game_memory_source TEXT, -- counters,ex2,ex,held,opened — the reads that answered
|
||||
sensor_stats_json TEXT, -- {"gpu_temp":{"N":…,"Mean":…,"Median":…,"Min":…,"Max":…}, …}
|
||||
|
||||
-- schema 0016 (2026-09-27, beta.10): the display mode, both tiers (03_METRICS §Display mode). Milliseconds per mode,
|
||||
-- each sample standing for the time until the next (100 ms hooked, 1 s at Tier 2), a pause not counted; nowindow is
|
||||
-- outside every share. NULL before, on a session recovered from its .partial file, and where the loop never sampled —
|
||||
@@ -343,6 +353,9 @@ CREATE TABLE sensor_blobs (
|
||||
-- schema 0008 (2026-09-22) DROPPED them with the feature (19_SAFETY §What a finding does to the game). Sessions that
|
||||
-- ran under it keep "guard-bypass=" in capture_notes.
|
||||
series TEXT NOT NULL, -- cpu_temp|gpu_temp|gpu_hotspot|gpu_load|gpu_power|vram_proc|vram_adapter|cpu_load|ram_mb
|
||||
-- (vram_proc was listed here from 0001 and never written); since schema 0018 (beta.12,
|
||||
-- D43) also game_vram_dedicated|game_vram_shared|game_ram_private|game_ram_ws|game_commit,
|
||||
-- MiB — the game process's own memory (Application.Recording.SensorSeriesCatalog)
|
||||
-- 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.
|
||||
@@ -592,6 +605,17 @@ Sequential embedded SQL (`Migrations/0001_init.sql`, `0002_*.sql`, …), applied
|
||||
> `SqliteGameConsentStoreTests.AnEndDuringTheTrialMarksTheGameAndNothingClearsIt`,
|
||||
> `SqliteGameMergeTests.AFailedExceptionTrialOnEitherTwinMarksTheSurvivor`.
|
||||
|
||||
> **`0018_game_memory.sql` (beta.12, 2026-10-03, owner decision D43) — the game process's own memory.** Twelve
|
||||
> columns, ADD COLUMN only: `game_vram_dedicated_{avg,median,max}_mb`, `game_vram_shared_max_mb`,
|
||||
> `game_ram_private_{avg,median,max}_mb`, `game_ram_ws_max_mb`, `game_commit_max_mb`, `game_memory_processes`,
|
||||
> `game_memory_source` and `sensor_stats_json`. Written by the recorder's aggregation for both tiers
|
||||
> (`SessionAggregator.WithSensorAggregates`); a session before it reads N/A. **Not `vram_proc_*`**: those name the
|
||||
> in-process DXGI figure compared with a budget (a different quantity, `03_METRICS` §Game process memory) and stay
|
||||
> reserved. The `.partial` gains chunk type 8 (`SensorsWide`, a 32-bit mask with the game fields); type 4 is still read,
|
||||
> so a beta.11 crash file recovers. `LatestVersion` is 18; `LedgerDatabaseTests.ScriptEighteenAddsTheGameMemoryColumnsAndAnEarlierSessionHasNone`,
|
||||
> `SqliteSessionRepositoryTests.ASessionRoundTripsColumnForColumn`,
|
||||
> `PartialSessionFileTests.TheGameMemoryRoundTripsAndANarrowSensorsChunkFromBeta11StillReads`.
|
||||
|
||||
> **Every open used to migrate, and one that should not have did — 2026-09-16.** The Agent's `--console sessions`,
|
||||
> a verb that prints, was run against the owner's ledger while the file on disk was at schema 2 and applied 0003 and
|
||||
> 0004 to it. `LedgerDatabase.OpenReadOnlyAsync` exists since that day: an existing file, `PRAGMA query_only`, no
|
||||
|
||||
+2
-2
@@ -399,8 +399,8 @@ Unchanged in spirit from v1, bumped to `v2` for the new message set.
|
||||
| `DeleteSessions` | UI→A | **Added 2026-10-03 (beta.11, D40).** `{ gameId? }` — every session of that game, or of every game when it is null, with their segments, frame and sensor series and annotations (they cascade) → `DeleteSessionsAck { gameId?, games, sessions }`. `Error SessionRunning` and nothing deleted while a session of that game — of any game, for all — is being recorded (`CaptureOrchestrator.IsRecording` / `IsRecordingAny`). The client names no rows beyond the game: they are the Agent's (§Writer ownership). Additive: an older Agent answers `Error UnknownType`, which the App says as "restart the agent". Carries no safety fact. |
|
||||
| `SweepRetention` | UI→A | **no payload** — a trigger, like `UpdateRules`: the Agent applies `06_DATA_MODEL` §Retention to every game with the `retention.raw_sessions_per_game` it reads itself → `SweepRetentionAck { keep, games, sessions }` (`keep` 0 = unlimited, and then nothing was swept). *(Built 2026-09-15, P4 PR-7, for Tools ▸ Database maintenance: `Application.Recording.RetentionSweep` over `ISessionRepository.SweepRetentionAllAsync`, composed into `AgentCommandHandler` under `--serve`. The client names no number because the rows are the Agent's (§Writer ownership). Additive: an older Agent answers `Error UnknownType`, which the dialog reads as "restart the Agent". Carries no safety fact.)* |
|
||||
| `SessionStarted` | A→UI | `{ sessionGuid, gameId, gameName, pid, tier, startedAt, hold? }` — **published once per session**: at the attach (tier 1, `startedAt` the attach), or — **since 2026-09-23** — at the first tick of a session held unhooked (tier 2, `startedAt` the session's start, `pid` 0 when the loop never opened the process, as a hooking-off hold never does). ~~a session that never attaches has no `SessionStarted`, only its `SessionCompleted` (tier 2)~~ — that was the beta.5 wire, and every hooking-off, refused or unreadable game read "Nothing is being captured." for as long as it ran. **`hold` (optional, tier 2 only)** is why nothing is measured: `{ reason, guardReason?, family?, signal?, hookingTurnedOff }` — the loop's `SessionEndReason` and, when the guard said anything but allow, its reason, family and signal: the same words the row's `capture_notes` will carry, so the live card and the summary read one sentence (`Formats.Tier2HoldReason` / `Tier2Reason`). The refusal's own event (`CaptureRefused` and the rest, below) goes out with this start rather than when the game exits, and is not repeated at the end |
|
||||
| `SessionHeld` | A→UI | **Added 2026-09-23.** 1 Hz while a client listens, for a session held unhooked only: `{ sessionGuid, elapsedS, gpuTempC?, cpuTempC?, gpuLoadPct?, cpuLoadPct? }` — how long it has run and the machine's sensors. **Never `SessionProgress`**: its `presents5s`, `presentedQualifier` and `fgMode` are required, and zeros there would put measured-looking numbers on the wire for a session that measures nothing (rule 6 has nothing to show and shows nothing) |
|
||||
| `SessionProgress` | A→UI | 1 Hz: `{ sessionGuid, elapsedS, presents5s, presentedFps5s?, presentedQualifier, nativeFps5s?, displayedFps5s?, fgFactor?, fgMode, upscaler?, upscalerQuality?, upscalerDriverReported?, renderW/H?, outputW/H?, rtActive?, gpuTempC?, cpuTempC?, cpuLoadPct?, vramProcMb?, latencyUs?, fgRefusal?, fgRuntimeCensus? }` — a 5 s rolling window over the ring through the SAME Domain calculators the row uses (`SessionProgressCalculator`, D13). **`upscalerDriverReported` added 2026-09-21, optional:** `dlss` when the NVIDIA driver reports an NGX super-resolution feature created and evaluated in the target (`03_METRICS` §The driver-reported rung), so the live card says `DLSS (driver-reported)` where no hook can name the upscaler; identity only. **`cpuLoadPct` added 2026-09-21, optional** (CPU time busy over the last telemetry tick, 0–100; `cpuTempC` has a producer from the same date, present only when the Agent is elevated with PawnIO). **Two fields added 2026-09-14, both optional (an older client ignores them, §C):** `fgRefusal` is the row's `fg_refusal` (schema 0003) — present when `fgMode` names a technology and `fgFactor` is absent, so the live card can say "DLSS-G active — factor not counted" rather than N/A; `fgRuntimeCensus` is the raw census so the `fg_runtime_loaded` chip can name the module. **Rule 6 at the wire (2026-09-13):** `nativeFps5s` / `displayedFps5s` / `fgFactor` are present only when frame generation was measured in the window; otherwise `presentedFps5s` stands alone with `presentedQualifier` (`census_not_run` · `no_fg_runtime` · `fg_runtime_loaded` · `none_withheld`, the row's `presented_qualifier` from the same function). Every unmeasured field is absent, never 0. Suppressed when no client is connected |
|
||||
| `SessionHeld` | A→UI | **Added 2026-09-23.** 1 Hz while a client listens, for a session held unhooked only: `{ sessionGuid, elapsedS, gpuTempC?, cpuTempC?, gpuLoadPct?, cpuLoadPct?, gameVramDedicatedMb?, gameRamPrivateMb? }` — how long it has run and the machine's sensors (and since beta.12 the game process's own memory, read from outside it — optional, an older client ignores them). **Never `SessionProgress`**: its `presents5s`, `presentedQualifier` and `fgMode` are required, and zeros there would put measured-looking numbers on the wire for a session that measures nothing (rule 6 has nothing to show and shows nothing) |
|
||||
| `SessionProgress` | A→UI | 1 Hz: `{ sessionGuid, elapsedS, presents5s, presentedFps5s?, presentedQualifier, nativeFps5s?, displayedFps5s?, fgFactor?, fgMode, upscaler?, upscalerQuality?, upscalerDriverReported?, renderW/H?, outputW/H?, rtActive?, gpuTempC?, cpuTempC?, cpuLoadPct?, vramProcMb?, latencyUs?, fgRefusal?, fgRuntimeCensus?, gameVramDedicatedMb?, gameRamPrivateMb? }` (the last two added 2026-10-03, beta.12, optional: the game process's dedicated GPU memory and private working set, MiB, from the newest telemetry tick; `vramProcMb` stays reserved for the in-process figure and has no producer) — a 5 s rolling window over the ring through the SAME Domain calculators the row uses (`SessionProgressCalculator`, D13). **`upscalerDriverReported` added 2026-09-21, optional:** `dlss` when the NVIDIA driver reports an NGX super-resolution feature created and evaluated in the target (`03_METRICS` §The driver-reported rung), so the live card says `DLSS (driver-reported)` where no hook can name the upscaler; identity only. **`cpuLoadPct` added 2026-09-21, optional** (CPU time busy over the last telemetry tick, 0–100; `cpuTempC` has a producer from the same date, present only when the Agent is elevated with PawnIO). **Two fields added 2026-09-14, both optional (an older client ignores them, §C):** `fgRefusal` is the row's `fg_refusal` (schema 0003) — present when `fgMode` names a technology and `fgFactor` is absent, so the live card can say "DLSS-G active — factor not counted" rather than N/A; `fgRuntimeCensus` is the raw census so the `fg_runtime_loaded` chip can name the module. **Rule 6 at the wire (2026-09-13):** `nativeFps5s` / `displayedFps5s` / `fgFactor` are present only when frame generation was measured in the window; otherwise `presentedFps5s` stands alone with `presentedQualifier` (`census_not_run` · `no_fg_runtime` · `fg_runtime_loaded` · `none_withheld`, the row's `presented_qualifier` from the same function). Every unmeasured field is absent, never 0. Suppressed when no client is connected |
|
||||
| `SessionCompleted` | A→UI | `{ sessionGuid, sessionId?, exitStatus, tier, finalize, reason, gameId?, gameName? }` — UI loads the full row from SQLite; `sessionId` is null and `finalize` is `discarded` when the row was not stored (under the minimum length), or `game_removed` when its entry was removed with its sessions while it ran (2026-09-23), or **`faulted` when the session's task threw before it could finalize** (2026-09-23: it follows the `CaptureError SessionFaulted`, with `exitStatus` `interrupted` and `reason` `SessionFaulted`, so the live card and the tray let go of a session that no longer runs; the `.partial` stays for recovery); `exitStatus` is the row's vocabulary (`normal` · `crashed` · `unhooked_safety` · `degraded`); `reason` is the loop's `SessionEndReason`. **`gameId` / `gameName` added 2026-09-23, optional:** the entry the session was stored under — the finalizer's owner when it re-keyed a session whose entry was removed, else the one it started under — so the notice names the session that completed, not whatever the live card last showed |
|
||||
| `CaptureRefused` | A→UI | `{ gameId, gameName, reason, family?, signal?, hookingTurnedOff }` — **guard fired**; `hookingTurnedOff` (2026-09-22) is true when the finding turned the game's hooking off (`19_SAFETY` §What a finding does to the game); UI shows the plain-language explanation — ~~and the Tier-2 offer~~; there is no alternative measurement to offer, only the option to record the session unmeasured (`08_UI` §Safety events). *(Built: for `RefusedByGuard`, `RefusedPreviouslyBlocked`, `RefusedKillSwitch` and `PreScanCouldNotVerify` — the last with no family, because "could not verify" is neither a hit nor a pass; `family`/`signal` are the verdict's. A game merely not enabled or not consented raises nothing: that is an ordinary Tier-2 row, not a refusal to explain.)* |
|
||||
| `CaptureDegraded` | A→UI | `{ sessionGuid, from: 1, to: 2, reason }` — Tier 1 → Tier 2 mid-flight, or overlay self-disabled. **Under a two-rung ladder this means measurement STOPPED**, not that it continued at lower fidelity, and the notice must say so. *(Built: `SupervisionLost`, `WriterSelfDisabled`, `WriterStoppedBlocklisted`, `WriterNeverInstalledHooks`, `SupervisionFaulted`, `KillSwitchEngaged` — `RecordedSessionEvents.Classify` is the table.)* |
|
||||
|
||||
+6
-2
@@ -232,7 +232,10 @@ document the app displays for acceptance (FR-11) is a defect, not a template.
|
||||
## Local quality gate (pre-push)
|
||||
|
||||
`./build.ps1 check`:
|
||||
1. `cmake --build --preset x64-release` (C++ `/W4 /WX`)
|
||||
1. `cmake --build --preset x64-release` (C++ `/W4 /WX`) — since beta.12 also `FrameLedger.ProcessStats.dll` (the game
|
||||
process's memory, D43; staged beside the Agent, CaptureHost and Infrastructure.Tests by
|
||||
`FrameLedger.ProcessStats.targets`), its ctest `fl_process_stats` (GPU_INSTANCE on a machine with a hardware adapter,
|
||||
NO_GPU_INSTANCE elsewhere) and the instrument `fl-probe-processstats` (`spike-notes` §16)
|
||||
2. native tests (Catch2)
|
||||
3. `clang-format --dry-run -Werror` over `src/native`
|
||||
4. `dotnet restore` + build (warnings as errors)
|
||||
@@ -248,7 +251,8 @@ document the app displays for acceptance (FR-11) is a defect, not a template.
|
||||
12. **`tools/package-closure-check.ps1`** — both halves: the self-test (5 cases, 4 of which must go RED) **and** a live pass over this repository. It walks the transitive `ProjectReference` closure of the two publish roots below and fails on anything outside the allowlist, naming the reference edge. `FrameLedger.CaptureHost` is an injecting entry point kept out of the package by construction, and `20_OPEN_QUESTIONS` §S27 is closed on exactly that basis
|
||||
13. `tools/license-check.ps1` — asserts every vendored third-party has a licence copy in `legal/licenses/`, and that no Intel IGCL / AMD ADLX material has appeared in the tree; since P4 PR-6 (§3) also that `legal/licenses/nuget/` is exactly what `tools/license-gather.ps1` writes for this build's restore output — every NuGet package the App and the Agent ship (77), both directions. `license-gather.ps1 -SelfTest` runs first: fourteen fixture cases, five that must be RED (a hand edit, a package that no longer ships, a URL-only licence with no reviewed override, an applied MPL Exhibit B, a missing restore output), and one run under tr-TR in a child process, because the output must not depend on the machine's culture
|
||||
13b. `tools/accuracy-check.ps1 -SelfTest`, then live — the accuracy block is ONE text (`legal/ACCURACY.md`) embedded verbatim in `README.md` and `legal/DISCLAIMER.md` §4; a copy that drifted, a copy with no markers, or an empty source is red. Four self-test cases, both directions (§S23-6, 2026-09-06)
|
||||
13c. **`tools/notice-check.ps1 -SelfTest`, then live** (beta.12, owner decision D45, 2026-10-03) — every first-party source file (`.cs .cpp .h .inl .ps1 .xaml`, tracked or new, minus `src/native/third_party/`) opens with `SPDX-License-Identifier: GPL-3.0-only` and `Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE` in its own comment syntax, because GPLv3 §7 wants additional terms named "in the relevant source files" (`NOTICE` carries them). Six self-test cases, both directions; `./tools/notice-check.ps1 -Fix` writes a missing header, and `tools/resx-gen.ps1` generates the accessor with it
|
||||
13c. **`tools/notice-check.ps1 -SelfTest`, then live** (beta.12, owner decision D45, 2026-10-03) — every first-party source file (`.cs .cpp .h .inl .ps1 .xaml`, tracked or new, minus `src/native/third_party/`) opens with `SPDX-License-Identifier: GPL-3.0-only` and `Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE` in its own comment syntax, because GPLv3 §7 wants additional terms named "in the relevant source files" (`NOTICE` carries them); the second line may name another holder and year in the same form (a contributor's own file).
|
||||
Seven self-test cases, both directions; `./tools/notice-check.ps1 -Fix` writes a missing header, and `tools/resx-gen.ps1` generates the accessor with it
|
||||
14. `tools/changelog-check.ps1 -SelfTest` — nine cases, five expected RED. The live half needs a pull request's changed-file list and is supplied by `ci.yml`
|
||||
14b. `tools/release-notes.ps1 -SelfTest` — five cases over a fixture changelog (a dated and an undated section, a missing one, a prefix that must not match, an empty one). The live half needs a tag's version and runs in `release.yml`, where a missing or empty section is a red release (P4 PR-5)
|
||||
15. `tools/resx-audit.ps1` — ~~**skipped loudly; it does not exist, and no `.resx` file does either**~~ **built 2026-09-13 (P3 PR-2)**: `-SelfTest` first (11 fixture cases, both directions), then the live pass over every `Strings.resx` family under `src/` — key sets equal across en/vi/ja, `Safety_*` in `ja` marked for review or signed, `Strings.Designer.cs` current with `tools/resx-gen.ps1`. A tree with no family is red (`09_I18N` §Translation workflow)
|
||||
|
||||
@@ -328,7 +328,7 @@ So:
|
||||
### Memory / latency
|
||||
| Hook / call | Yields |
|
||||
|---|---|
|
||||
| `IDXGIAdapter3::QueryVideoMemoryInfo` (we **call** it, not hook it, once per second from our own thread) | **Per-process VRAM** `CurrentUsage` + `Budget` — previously impossible; now exact |
|
||||
| ~~`IDXGIAdapter3::QueryVideoMemoryInfo` (we **call** it, not hook it, once per second from our own thread)~~ | ~~**Per-process VRAM** `CurrentUsage` + `Budget` — previously impossible; now exact~~ **Never built; superseded 2026-10-03 (D43):** the game's memory is read from OUTSIDE the game by the Agent (`18_GPU_VENDOR_APIS` §The game process's memory), so nothing in the Overlay calls it. Only the budget would need it, and that stays open (`20_OPEN_QUESTIONS` §M11) |
|
||||
| NVAPI Reflex: hook `NvAPI_D3D_SetSleepMode`, `NvAPI_D3D_SetLatencyMarker`; call `NvAPI_D3D_GetLatency` | Reflex on/off + PC latency breakdown. Declarations come from the vendored MIT NVAPI headers (`18_GPU_VENDOR_APIS` §L3); the Overlay links them like any other header. NVIDIA-only — the whole block compiles out to a no-op capability flag elsewhere |
|
||||
|
||||
### Explicitly not hooked
|
||||
|
||||
@@ -57,7 +57,32 @@ Implementations compose rather than compete:
|
||||
> poller sample is stamped with QPC (`TelemetrySample.QpcTicks`), the ring's clock, and
|
||||
> `QpcClockTests` pins `Stopwatch` / `TimeProvider.GetTimestamp` to the real counter.
|
||||
|
||||
> Per-process VRAM comes from the **Overlay** (`IDXGIAdapter3::QueryVideoMemoryInfo` inside the game), not from here. Adapter-wide VRAM is a separate series with a different label — they answer different questions and users will otherwise think one of them is broken.
|
||||
> ~~Per-process VRAM comes from the **Overlay** (`IDXGIAdapter3::QueryVideoMemoryInfo` inside the game), not from here.~~
|
||||
> **Corrected 2026-10-03 (beta.12, D43): the game process's memory is read from OUTSIDE the game** — §The game process's
|
||||
> memory below; the Overlay never called `QueryVideoMemoryInfo`. Adapter-wide VRAM is a separate series with a different
|
||||
> label — they answer different questions and users will otherwise think one of them is broken.
|
||||
|
||||
### The game process's memory (beta.12, owner decision D43)
|
||||
|
||||
`FrameLedger.ProcessStats.dll` — the third native facade the Agent loads beside itself (`NativeProcessStats`, after the
|
||||
guard's and the NVAPI bridge's), never into a game — reads one process's memory per call:
|
||||
|
||||
- **Video memory:** the documented performance counters `\GPU Process Memory(pid_<pid>_luid_…_phys_<n>)\Dedicated
|
||||
Usage` and `\Shared Usage` (`PdhAddEnglishCounterW` with a `*` instance, so a localised counter name does not matter;
|
||||
`PdhGetFormattedCounterArrayW` after each collection), every instance naming the pid **summed** — each adapter and
|
||||
physical index the process allocated on. This is the per-process figure, so the adapter-wide rule below ("filter to our
|
||||
adapter, don't sum blindly") does not apply to it. **No handle to the game is needed.**
|
||||
- **System memory:** `GetProcessMemoryInfo` with `PROCESS_MEMORY_COUNTERS_EX2` (its `PrivateWorkingSetSize` is Task
|
||||
Manager's "Memory"), retried with `PROCESS_MEMORY_COUNTERS_EX` where the OS refuses the larger structure; an EX2
|
||||
answer whose private working set was left as written (a sentinel) or reads zero beside a nonzero working set is N/A,
|
||||
never a measured zero. It needs `PROCESS_QUERY_LIMITED_INFORMATION` and
|
||||
nothing more: the session's held handle when it has one, else a handle opened for the read and closed after it, whose
|
||||
creation time must be the watcher's (a reused pid is refused, not read).
|
||||
- **Not `D3DKMTQueryStatistics`.** It answers the same per-process segment figures, but Microsoft documents it as
|
||||
"Reserved for system use"; the counters are the documented face of the same accounting.
|
||||
- Measured on the dev box (`spike-notes` §16): one collect + read costs 0.1 ms (max 0.22 ms), a 512 MiB allocation reads
|
||||
+512.0 MiB, the private working set equals `\Process V2(…)\Working Set - Private`, 600 collections leak nothing. One
|
||||
`GameMemoryReader` per session, on the session's `fl-telemetry` thread (`TelemetryPoller`'s third source).
|
||||
|
||||
## L1 — baseline (no licence, all vendors)
|
||||
|
||||
@@ -65,7 +90,8 @@ Implementations compose rather than compete:
|
||||
- **PDH performance counters** — the same source Task Manager uses, fully documented, vendor-neutral:
|
||||
- `\GPU Engine(*)\Utilization Percentage` (sum per engine type: 3D, Compute, Copy, VideoDecode)
|
||||
- `\GPU Adapter Memory(*)\Dedicated Usage`
|
||||
- `\GPU Process Memory(*)\Dedicated Usage` (cross-check against the Overlay's figure)
|
||||
- `\GPU Process Memory(*)\Dedicated Usage` ~~(cross-check against the Overlay's figure)~~ — **read since 2026-10-03
|
||||
as the game process's own figure** (§The game process's memory; the Overlay never produced one)
|
||||
- Instance names embed the LUID — parse and filter to our adapter, don't sum blindly across GPUs.
|
||||
|
||||
> **Built 2026-09-09 (PR-E1), one counter of the three:** `PdhAdapterMemoryCounter` binds
|
||||
@@ -75,8 +101,10 @@ Implementations compose rather than compete:
|
||||
> idle desktop, moving tick to tick. A machine without the counter set fails the open and the
|
||||
> field is N/A with the layer standing — not a fault. **`Utilization Percentage` is deliberately
|
||||
> not read** (`20_OPEN_QUESTIONS` §M10, decided): `LoadPct` is L2's vendor-reported load and is
|
||||
> labelled as such. `GPU Process Memory` is not read either — the Overlay's in-process figure is
|
||||
> the one the pipeline stores, and a cross-check is a diagnostic, not a field.
|
||||
> labelled as such. ~~`GPU Process Memory` is not read either — the Overlay's in-process figure is
|
||||
> the one the pipeline stores, and a cross-check is a diagnostic, not a field.~~ **Since 2026-10-03 (D43) `GPU Process
|
||||
> Memory` IS read** — by `FrameLedger.ProcessStats.dll`, as the game process's dedicated and shared GPU memory; there was
|
||||
> never an in-process figure to cross-check.
|
||||
- **Driver version:** ~~`SetupAPI` / registry adapter properties.~~ **`IDXGIAdapter::CheckInterfaceSupport(IDXGIDevice)`** — its documented second output is the user-mode driver version for that interface, four 16-bit fields of one 64-bit value (`32.0.16.1664` on the dev box, 2026-09-09; the WARP adapter answers with the OS build). Neither SetupAPI nor the registry is walked: both need a device-instance enumeration nothing else here has a reason to carry. Feeds the hardware snapshot and the trend-chart change markers (`06_DATA_MODEL`). This is the four-part form the vendor's own tooling shows, not the marketing number (`561.09`), which only L3 knows.
|
||||
- **Optional probe, P0 evaluation only:** `D3DKMTQueryAdapterInfo` with `KMTQAITYPE_ADAPTERPERFDATA` reportedly exposes temperature, power and fan for any vendor. The D3DKMT structures are **not fully documented and have changed across Windows builds**. Treat as an experiment: if it proves stable on both Win 10 22H2 and Win 11 during P0, keep it as an L1 extra behind a capability flag; if it looks fragile, drop it and let L2 handle temperatures. Never let it be load-bearing.
|
||||
|
||||
@@ -338,7 +366,7 @@ as the same thing.
|
||||
|---|---|---|---|
|
||||
| GPU utilisation | **deferred by decision** (§M10, 2026-09-09) — L2's vendor-reported load is what `LoadPct` carries, labelled as such; the engine counters are not read | untested | untested |
|
||||
| Adapter VRAM | ✓ **measured 2026-09-09** — PDH `GPU Adapter Memory … Dedicated Usage`, 1301 MB at an idle desktop, RTX 5080 (`QueryVideoMemoryInfo` measured **not** adapter-wide: 0 bytes from the Agent) | untested | untested |
|
||||
| Per-process VRAM | `arch` for L1 — the Overlay's in-process `QueryVideoMemoryInfo` is the figure stored; `GPU Process Memory` is not read | `arch` | `arch` |
|
||||
| Per-process VRAM | ~~`arch` for L1 — the Overlay's in-process `QueryVideoMemoryInfo` is the figure stored; `GPU Process Memory` is not read~~ ✓ **measured 2026-10-03** — `GPU Process Memory` Dedicated/Shared by pid from outside the game, +512.0 MiB for a 512 MiB buffer (`spike-notes` §16) | untested | untested |
|
||||
| Driver version | ✓ **measured 2026-09-09** — `CheckInterfaceSupport(IDXGIDevice)` → `32.0.16.1664` | untested | untested |
|
||||
| Core temp | ? (D3DKMT probe, Win 11 only — see below) | untested | untested |
|
||||
| Power | ? (D3DKMT probe) | untested | untested |
|
||||
|
||||
@@ -986,7 +986,12 @@ Consent is stored per game (`games.hook_consent_at`), **stamped by the Agent, ne
|
||||
> publishing `unhookRequested`, and keeps the Vulkan layer off by never setting `FRAMELEDGER_ENABLE_VK_LAYER`
|
||||
> on a launch.
|
||||
|
||||
The default for every newly added game is **hooking off — Tier 2**. Nothing is ever injected because the user merely added a game — and since 2026-09-22 nothing is *opened* either: a hooking-off row's Tier-2 session is held by ~~the executable's name~~ the executable's image path in the watcher's own snapshot (2026-09-23), with no `OpenProcess`, no resolver and no gate (`04_CAPTURE` §Tier selection).
|
||||
The default for every newly added game is **hooking off — Tier 2**. Nothing is ever injected because the user merely added a game — and since 2026-09-22 nothing is *opened* either: a hooking-off row's Tier-2 session is held by ~~the executable's name~~ the executable's image path in the watcher's own snapshot (2026-09-23), with no `OpenProcess`, no resolver and no gate (`04_CAPTURE` §Tier selection). *(Corrected 2026-10-03, beta.12, owner
|
||||
decision D43: such a hold now reads the game process's own memory once a second — its video memory from performance
|
||||
counters that open nothing, its system memory through a handle opened with `PROCESS_QUERY_LIMITED_INFORMATION` for the
|
||||
read and closed after it, the same least right the watcher's snapshot already opens every process with, each second. No
|
||||
handle is held, nothing is injected, the guard is not involved, and what is read is the kernel's accounting about the
|
||||
process, never its memory — rule 4 is untouched. A process that refuses even that right reads N/A.)*
|
||||
|
||||
### A moved drive is the same executable — owner ask 2026-09-22
|
||||
|
||||
|
||||
@@ -4277,6 +4277,11 @@ this item defers, and whether generated presents reach our vtable is what §H5 t
|
||||
|
||||
### H10 · Per-process VRAM thread inside the game process
|
||||
|
||||
🅓 **The usage half is answered from outside the game — 2026-10-03 (beta.12, owner decision D43); the budget half is
|
||||
deferred with §M11.** The game's dedicated and shared GPU memory are read by the Agent from the `GPU Process Memory`
|
||||
counters (`18_GPU_VENDOR_APIS` §The game process's memory), so no thread and no DXGI call is added inside the game for
|
||||
them. What only an in-process call could give is the budget, and nothing reads it. *(The question as it stood:)*
|
||||
|
||||
`17_HOOK_ENGINE` §Memory calls `QueryVideoMemoryInfo` "once per second from our
|
||||
own thread". Spawning a thread inside a host process we do not own is a heavier
|
||||
footprint than the rest of the design's posture, and DXGI calls off the render
|
||||
@@ -4300,10 +4305,11 @@ instead, which needs no thread at all.
|
||||
| M2 ✅ | ~~Does the pinned console binary still exist, run unelevated, and emit the 2.x column set?~~ | **Answered, then closed 2026-08-27.** It exists (2.5.1, 956,768 bytes, SHA256 `9BEC…A191`, **no VERSIONINFO at all**); it does **not** run unelevated (exit 6 — the account is in neither Administrators nor Performance Log Users, and the running `PresentMonSharedService` does not help because the console starts its own session); and the 2.x column set **is measured** — 24 columns, `spike-notes` §11. The parser ate three real CSVs and resolved `FrameType` correctly against a first column literally named `Application`. Closed because the binary is dropped, and kept in full because every one of those facts cost a measurement |
|
||||
| M5 ✅ | **Do LHM GPU sensors work unelevated, without PawnIO?** **YES — measured 2026-09-03, row R1 of the pre-committed table below**, NVIDIA RTX 5080 / 616.56 / LHM 0.9.6: eight fields unelevated (core and memory temperature, load, VRAM used, core and memory clock, package power, fan), the identical eight in the elevated control, PawnIO never opened. The three user-facing sentences stand. Numbers in `spike-notes` §10. *(The row as it stood while open follows, unchanged.)* This decides whether the default unelevated Agent has temperatures at all, and therefore how ADR-9 reads to users. **SEVERITY PROMOTED 2026-08-28, and the promotion is the point.** It used to decide how a design note read. It now decides whether a **user-facing claim is true**: the two-rung ladder says a Tier-2 session records duration and hardware telemetry, and that sentence is heading for `README`, the consent dialog and `legal/EULA.md`. If LHM needs elevation for GPU sensors, then the DEFAULT Agent's Tier-2 session is **duration only** and every one of those documents is wrong. Until it is measured, all three are worded *"whatever hardware telemetry this machine can provide"* — honest under either outcome, at the cost of vagueness. `18_GPU_VENDOR_APIS` §P0(b) already specifies the test and the dev box can run it |
|
||||
| M6 ✅ | ~~Elevation-free Tier 2~~ | **Closed by decision 2026-08-27.** Half was answered on 2026-08-20 in the direction nobody expected: `PresentMonSharedService` is installed and `Running` as LocalSystem and the console **still** fails, because it starts its own trace session. The other half — whether `Performance Log Users` suffices without admin — stays unmeasured and now has no subject. **The elevation question does not disappear with the tool**: ETW trace sessions are restricted by Windows, not by PresentMon, so whatever §G chooses inherits it. Re-ask it there |
|
||||
| M7 ✅ | ~~`18_GPU_VENDOR_APIS` §Runtime policy says telemetry is never read from the game process, but `17_HOOK_ENGINE` reads per-process VRAM and Reflex latency there. Reconcile the wording — the rule means "no vendor SDK polling loops in the game", not "no measurement in the game"~~ **Closed 2026-09-09 (PR-E1) by the code taking exactly that shape.** The rule is *no telemetry polling loop in the game*: the one 1 Hz loop is `TelemetryPoller` on the Agent's `fl-telemetry` thread, and it reads L1/L2/L3 only. Per-process VRAM stays an in-process read on the present path (`vram_proc`, `17_HOOK_ENGINE`), and PR-E1 measured why that must be so: `IDXGIAdapter3::QueryVideoMemoryInfo`'s `CurrentUsage` is the *calling process's* figure — 0 bytes from the Agent — so it is a measurement only where the game is. Adapter-wide usage is L1's PDH counter. §Runtime policy's sentence stands as written; this row is the reconciliation |
|
||||
| M7 ✅ | ~~`18_GPU_VENDOR_APIS` §Runtime policy says telemetry is never read from the game process, but `17_HOOK_ENGINE` reads per-process VRAM and Reflex latency there. Reconcile the wording — the rule means "no vendor SDK polling loops in the game", not "no measurement in the game"~~ **Closed 2026-09-09 (PR-E1) by the code taking exactly that shape.** The rule is *no telemetry polling loop in the game*: the one 1 Hz loop is `TelemetryPoller` on the Agent's `fl-telemetry` thread, and it reads L1/L2/L3 only. Per-process VRAM stays an in-process read on the present path (`vram_proc`, `17_HOOK_ENGINE`), and PR-E1 measured why that must be so: `IDXGIAdapter3::QueryVideoMemoryInfo`'s `CurrentUsage` is the *calling process's* figure — 0 bytes from the Agent — so it is a measurement only where the game is. **Corrected 2026-10-03 (beta.12, D43): "only where the game is" holds for `QueryVideoMemoryInfo` and not in general** — the `GPU Process Memory` performance counters give any process's dedicated and shared GPU memory from outside it, with no handle, and the Agent reads them since that day (`18_GPU_VENDOR_APIS` §The game process's memory; `spike-notes` §16). The in-process read was never built. Adapter-wide usage is L1's PDH counter. §Runtime policy's sentence stands as written; this row is the reconciliation |
|
||||
| M8 ✅ | ~~The `GpuSample` type has no latency field, yet L3 is credited with Reflex/PC latency. Latency is per-frame and arrives via the ring, not the 1 Hz sample. Fix the layering description~~ **Closed 2026-09-09 (PR-E1): the description now matches the type.** `GpuSample` has no latency field by design (its own remarks said so since 2026-09-03), `TelemetrySample` carries a 1 Hz reading stamped with QPC, and per-frame latency is `FlFrameRecord.reflexLatencyUs` in the ring. The §L3 table row "Reflex / PC latency" is an *in-process hook fact* the Overlay records (`SetSleepMode` / `SetLatencyMarker`, `17_HOOK_ENGINE`), never a poller field; `NvapiTelemetrySource` (PR-E2) will not call `NvAPI_D3D_GetLatency` |
|
||||
| M9 ✅ | **Closed 2026-08-02 by a decision.** The old file/module detection does not exist in this repository and the owner confirmed there is no copy elsewhere, so **"build a minimal static-hint detector as the measurement baseline" is now P0 item 3** (`15_ROADMAP`). It needs no guard and no injection. Until it exists, ADR-7's headline claim stays out of the README rather than being asserted unmeasured |
|
||||
| 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. | — |
|
||||
| M10 ✅ | ~~PDH `\GPU Engine(*)\Utilization Percentage` summed across engines does not reproduce the Task Manager figure the doc invokes. Decide what we actually report and label it accordingly~~ **Decided 2026-09-09 (PR-E1): L1 does not read the engine counters at all.** `LoadPct` is L2's vendor-reported `GPU Core` load (measured ✓ on NVIDIA, §M5 row R1) and is labelled *GPU load (vendor)* wherever it is shown; on a machine without L2 the field is N/A, never a sum that is not the number the user expects. What L1 does read from PDH is one counter, `\GPU Adapter Memory(luid_…_phys_0)\Dedicated Usage`, bound by LUID — the figure Task Manager labels "Dedicated GPU memory", measured 1301 MB at an idle desktop on the RTX 5080. Reopening this needs a measurement of `max(engine)` against Task Manager's own number, not a decision |
|
||||
|
||||
#### §M5 — the decision table, pre-committed 2026-09-03 BEFORE the first run
|
||||
|
||||
@@ -2584,3 +2584,49 @@ shipped `UnrealBuildReader` once it was. Nothing was copied or written; the numb
|
||||
that scanned only a PE's `.rdata` read Black Myth as `5.0.0` from the file version alone; the 1 MiB `.rdata` floor
|
||||
(`UnrealBuildReader.MinRdataBytes`) is what moved it to the stronger rung.
|
||||
- No UE3 title is installed; the rule does not detect UE3 at all.
|
||||
|
||||
## 16 · A game process's own memory, read from outside it *(2026-10-03, beta.12, owner decision D43)*
|
||||
|
||||
**Why this was measured.** Per-process VRAM had storage since 0001 and no producer: `17_HOOK_ENGINE` §Memory planned
|
||||
`IDXGIAdapter3::QueryVideoMemoryInfo` inside the game, `20_OPEN_QUESTIONS` §M7 (2026-09-09) recorded that its
|
||||
`CurrentUsage` is the calling process's own (0 bytes from the Agent) and concluded the figure could only be read in the
|
||||
game, and §H10 left open where in the game. The owner chose the other road (D43): the documented performance counters
|
||||
`\GPU Process Memory(pid_<pid>_luid_…_phys_<n>)\Dedicated Usage` / `Shared Usage` — the numbers Task Manager's Details tab
|
||||
shows — need no handle to the game at all, and `GetProcessMemoryInfo` needs only `PROCESS_QUERY_LIMITED_INFORMATION`.
|
||||
§M7's conclusion holds for `QueryVideoMemoryInfo` and not in general.
|
||||
|
||||
**Already seen before this section was written**, stated so the table below is not read as having preceded them:
|
||||
(1) the counter set exists on the dev box, 37 instances at an idle desktop (`Get-Counter`, 2026-10-03); (2) `Dedicated
|
||||
Usage` is not `Local Usage` — dwm.exe 858 MB against 310 MB — so "dedicated" is defined as Task Manager's column and never
|
||||
compared with a DXGI budget; (3) `ctest fl_process_stats` on the RTX 5080 while the reader was being written: a 256 MiB
|
||||
DEFAULT buffer moved this process's dedicated figure 12.9 → 269.0 MiB (+256.1), and `PROCESS_MEMORY_COUNTERS_EX2` answered
|
||||
(private working set 5.2 MiB) on Windows 11 29648.
|
||||
|
||||
**The decision table, written before the runs below** (instrument: `fl-probe-processstats`, `--hold-vram` in one
|
||||
process and `--read` against it in another):
|
||||
|
||||
| # | Measurement | Outcome → what it means |
|
||||
|---|---|---|
|
||||
| M1 | Cost of one collect + read, 60 samples at 1 s | median ≤ 5 ms → 1 Hz with the sensors; 5–20 ms → still 1 Hz, noted in `18_GPU_VENDOR_APIS`; > 20 ms → every 5 s, and said so |
|
||||
| M2 | Δ dedicated of a second process holding 512 MiB | within ±2 % → "Dedicated GPU memory, as Task Manager shows it" may be written; off by > 10 % → stop, the video half does not ship |
|
||||
| M3 | dedicated against that process's own `QueryVideoMemoryInfo(LOCAL).CurrentUsage` | recorded in `03_METRICS`, whichever way it falls — the source does not change |
|
||||
| M4 | `PrivateWorkingSetSize` (EX2) against `\Process V2(<name>:<pid>)\Working Set - Private` | equal → "the same as Task Manager's Memory column"; EX2 refused → the EX fallback, and Windows 10 stays unmeasured |
|
||||
| M5 | How soon a new process's counter instance appears | recorded; the first seconds of a session reading N/A is then expected, not a fault |
|
||||
| M6 | The probe's own private bytes after 600 collections | Δ < 1 MiB → keep one query per session; more → open and close per collection, then measure again |
|
||||
|
||||
**Results (2026-10-03, the same evening; RTX 5080, driver 617.14, Windows 11 29648.1000, `fl-probe-processstats`
|
||||
from this PR's build):**
|
||||
|
||||
| # | Measured | Row taken |
|
||||
|---|---|---|
|
||||
| M1 | 60 samples at 1 s: collect + read **median 0.098 ms, max 0.217 ms**; 600 back to back: median 0.028 ms, max 0.190 ms | ≤ 5 ms → 1 Hz with the sensors |
|
||||
| M2 | holder at 8 MiB: dedicated **21.0 MiB**; holder at 512 MiB: **525.0 MiB** → Δ **512.0 MiB** for 512 MiB allocated (0.0 %); the in-process ctest earlier: +256.1 MiB for 256 | within ±2 % → "Dedicated GPU memory, as Task Manager shows it" |
|
||||
| M3 | the holder's own `CurrentUsage(LOCAL)`: 16.5 MiB (8 MiB holder) and 520.5 MiB (512 MiB holder) against dedicated 21.0 and 525.0 — **dedicated reads 4.5 MiB more, the same 4.5 MiB at both sizes** | recorded in `03_METRICS`: the counter includes a constant per-device amount the DXGI budget group does not; the difference does not grow with what the game allocates |
|
||||
| M4 | private working set (EX2) **9.1 MiB** = `\Process V2(fl-probe-processstats:<pid>)\Working Set - Private` **9.1 MiB**, in all 60 samples | equal → "the same as Task Manager's Memory column" |
|
||||
| M5 | the holder's instance was present at the reader's first poll, ~50 ms after the holder started (its device and buffer had already been created) | an instance exists from the process's first GPU allocation; a game that has made none reads N/A, as specified |
|
||||
| M6 | 600 collections: the probe's private bytes moved by **0 bytes** (−44 KB over the 60 slow ones) | < 1 MiB → one query per session |
|
||||
|
||||
**What stays unmeasured:** Windows 10 22H2 (no machine; the reader falls back to `PROCESS_MEMORY_COUNTERS_EX` where EX2 is
|
||||
refused, and the private working set then reads N/A), AMD and Intel GPUs, a laptop with two adapters (the reader sums
|
||||
every adapter's instances for the pid), and a real game — the owner's beta.12 check (HANDOFF owner-only item 9) compares
|
||||
a session's figures with Task Manager's Details tab at the same moment.
|
||||
+7
-1
@@ -65,8 +65,14 @@
|
||||
> - **Engine version:** the exact Unreal Engine 4 or 5 version, read from the game's executable on disk and
|
||||
> labelled with what it rests on; `N/A` where the executable names none. Other engines show what their own
|
||||
> files state.
|
||||
> - **The game's own memory (since beta.12):** its dedicated and shared GPU memory and its private
|
||||
> working set — the numbers Task Manager's Details tab shows — with its working set and commit, read
|
||||
> once a second from Windows' own counters, from outside the game, in every session: a game
|
||||
> FrameLedger injects into through the handle it already holds, any other by opening it briefly with
|
||||
> the least access Windows offers (and adding up every process running its executable). Shown with
|
||||
> mean, median and peak. The game's other processes (launchers, helpers) are not counted.
|
||||
> - **Video memory:** in use on the whole graphics card, recorded from Windows and GPU-driver telemetry
|
||||
> and charted. **Not measured at all:** each game's own video-memory use and budget, which frame
|
||||
> and charted. **Not measured at all:** the video-memory budget Windows gives a game, which frame
|
||||
> spikes were shader compilation, PC latency (Reflex), and HDR. Stutter count and stutter time are
|
||||
> measured from frame times.
|
||||
> - **Processor and memory:** how busy the processor was (time busy, all cores together — not the
|
||||
|
||||
+7
-1
@@ -171,8 +171,14 @@ Frame timing is derived from high-resolution timestamps taken at the moment the
|
||||
> - **Engine version:** the exact Unreal Engine 4 or 5 version, read from the game's executable on disk and
|
||||
> labelled with what it rests on; `N/A` where the executable names none. Other engines show what their own
|
||||
> files state.
|
||||
> - **The game's own memory (since beta.12):** its dedicated and shared GPU memory and its private
|
||||
> working set — the numbers Task Manager's Details tab shows — with its working set and commit, read
|
||||
> once a second from Windows' own counters, from outside the game, in every session: a game
|
||||
> FrameLedger injects into through the handle it already holds, any other by opening it briefly with
|
||||
> the least access Windows offers (and adding up every process running its executable). Shown with
|
||||
> mean, median and peak. The game's other processes (launchers, helpers) are not counted.
|
||||
> - **Video memory:** in use on the whole graphics card, recorded from Windows and GPU-driver telemetry
|
||||
> and charted. **Not measured at all:** each game's own video-memory use and budget, which frame
|
||||
> and charted. **Not measured at all:** the video-memory budget Windows gives a game, which frame
|
||||
> spikes were shader compilation, PC latency (Reflex), and HDR. Stutter count and stutter time are
|
||||
> measured from frame times.
|
||||
> - **Processor and memory:** how busy the processor was (time busy, all cores together — not the
|
||||
|
||||
@@ -137,6 +137,7 @@ internal sealed class AgentRecording
|
||||
NvapiTelemetrySource? l3 = null;
|
||||
CompositeTelemetrySource? composite = null;
|
||||
SystemTelemetrySource? system = null;
|
||||
GameMemoryReader? game = null;
|
||||
try
|
||||
{
|
||||
pdh = new PdhAdapterMemoryCounter();
|
||||
@@ -154,9 +155,13 @@ internal sealed class AgentRecording
|
||||
// The machine beside the GPU (2026-09-21): CPU busy time and memory unprivileged, the CPU temperature only
|
||||
// where this process is elevated and PawnIO is installed. The poller owns it with the layers.
|
||||
system = SystemTelemetrySource.Create();
|
||||
var poller = new TelemetryPoller(composite, new TelemetryPollerOptions { Interval = interval }, TimeProvider.System, ownsSource: true, system);
|
||||
// The game process's own memory (beta.12, D43): read from outside it through FrameLedger.ProcessStats.dll, for
|
||||
// whichever process the capture loop tells the poller to follow. Absent DLL = N/A, never a fault.
|
||||
game = new GameMemoryReader(new NativeProcessStats());
|
||||
var poller = new TelemetryPoller(composite, new TelemetryPollerOptions { Interval = interval }, TimeProvider.System, ownsSource: true, system, game);
|
||||
composite = null;
|
||||
system = null;
|
||||
game = null;
|
||||
return poller;
|
||||
}
|
||||
finally
|
||||
@@ -167,6 +172,7 @@ internal sealed class AgentRecording
|
||||
l3?.Dispose();
|
||||
composite?.Dispose();
|
||||
system?.Dispose();
|
||||
game?.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -41,6 +41,7 @@
|
||||
-->
|
||||
<Import Project="$(MSBuildThisFileDirectory)..\..\FrameLedger.Guard.targets" />
|
||||
<Import Project="$(MSBuildThisFileDirectory)..\..\FrameLedger.NvapiBridge.targets" />
|
||||
<Import Project="$(MSBuildThisFileDirectory)..\..\FrameLedger.ProcessStats.targets" />
|
||||
|
||||
<!-- The seed the Agent installs to the product location on first run (§S20). -->
|
||||
<Import Project="$(MSBuildThisFileDirectory)..\..\FrameLedger.Rules.targets" />
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
using System.Diagnostics;
|
||||
using FrameLedger.Application.AntiCheat;
|
||||
using FrameLedger.Application.Consent;
|
||||
using FrameLedger.Application.Telemetry;
|
||||
using FrameLedger.Domain.AntiCheat;
|
||||
using FrameLedger.Domain.Consent;
|
||||
using FrameLedger.Shared;
|
||||
@@ -120,6 +121,9 @@ public sealed class CaptureSession(
|
||||
return await HoldUnhookedAsync(new CaptureOutcome { Reason = SessionEndReason.TargetCannotBePinned }, normalisedExePath, alive: null, pid, ct, stop).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// beta.12 (D43): the game's own memory is read through the pin from here on — declared after it, so it is let go
|
||||
// of before the handle closes.
|
||||
using MeasuringScope measuring = Measure(pid.Value, alive);
|
||||
if (ConsentRefusal(record, observed) is SessionEndReason refused)
|
||||
{
|
||||
return await HoldUnhookedAsync(new CaptureOutcome { Reason = refused }, normalisedExePath, alive, pid, ct, stop).ConfigureAwait(false);
|
||||
@@ -166,6 +170,9 @@ public sealed class CaptureSession(
|
||||
// game was exclusive. A hold that never opened the process finds the game by its image path in the watcher's
|
||||
// snapshot, and still opens nothing.
|
||||
var sampler = new DisplaySampler(display);
|
||||
// A hold with no pin reads the game's memory of every process running its executable (beta.12, D43), announced
|
||||
// whenever that set changes; a pinned hold's process was announced by the caller, with the pin.
|
||||
GameProcess? announced = null;
|
||||
while (!stop.IsCancellationRequested)
|
||||
{
|
||||
bool running = alive is not null ? !alive.HasExited : resolver.IsRunning(normalisedExePath);
|
||||
@@ -174,6 +181,7 @@ public sealed class CaptureSession(
|
||||
break;
|
||||
}
|
||||
|
||||
announced = alive is null ? AnnounceProcesses(normalisedExePath, announced) : announced;
|
||||
sampler.Sample(pid is { } p ? [p] : resolver.PidsOf(normalisedExePath), region: null, paused: false);
|
||||
observer?.Tick(held);
|
||||
await Task.Delay(options.HoldInterval, ct).ConfigureAwait(false);
|
||||
@@ -181,6 +189,11 @@ public sealed class CaptureSession(
|
||||
|
||||
sampler.Finish(paused: false);
|
||||
observer?.Tick(held);
|
||||
if (announced is not null)
|
||||
{
|
||||
observer?.Measuring(GameProcess.None);
|
||||
}
|
||||
|
||||
return refusal with { HeldUnhooked = true, TargetPid = pid ?? 0, ExitCode = alive?.ExitCode, Display = sampler.Summary() };
|
||||
}
|
||||
|
||||
@@ -218,6 +231,7 @@ public sealed class CaptureSession(
|
||||
}
|
||||
|
||||
using ITargetLiveness alive = launched.Value.Alive;
|
||||
using MeasuringScope measuring = Measure(launched.Value.Pid, alive);
|
||||
GameConsentRecord record = await store.FindAsync(normalisedExePath, ct).ConfigureAwait(false);
|
||||
if (ConsentRefusal(record, observed) is SessionEndReason refused)
|
||||
{
|
||||
@@ -228,6 +242,41 @@ public sealed class CaptureSession(
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Tells the observer the pinned process is the one to read the game's memory of, until the scope ends (beta.12, D43).</summary>
|
||||
private MeasuringScope Measure(int pid, ITargetLiveness alive)
|
||||
{
|
||||
observer?.Measuring(GameProcess.Pinned(pid, alive));
|
||||
return new MeasuringScope(observer);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// An unpinned hold's processes (beta.12, D43): announced when the set the watcher's snapshot names differs from the last
|
||||
/// one announced, never on a tick that changed nothing; null until the first non-empty set.
|
||||
/// </summary>
|
||||
private GameProcess? AnnounceProcesses(string normalisedExePath, GameProcess? announced)
|
||||
{
|
||||
if (observer is null)
|
||||
{
|
||||
return announced;
|
||||
}
|
||||
|
||||
IReadOnlyList<GameProcessId> now = resolver.ProcessesOf(normalisedExePath);
|
||||
if ((announced is null && now.Count == 0) || (announced is not null && announced.SameProcessesAs(now)))
|
||||
{
|
||||
return announced;
|
||||
}
|
||||
|
||||
GameProcess target = GameProcess.Unpinned(now);
|
||||
observer.Measuring(target);
|
||||
return target;
|
||||
}
|
||||
|
||||
/// <summary>Lets go of the pinned process before its handle closes: the telemetry thread reads nothing after this.</summary>
|
||||
private sealed class MeasuringScope(ICaptureObserver? observer) : IDisposable
|
||||
{
|
||||
public void Dispose() => observer?.Measuring(GameProcess.None);
|
||||
}
|
||||
|
||||
/// <summary>The two refusals the loop makes itself, before the gate (see <see cref="RunAsync"/>'s remarks).</summary>
|
||||
private static SessionEndReason? ConsentRefusal(GameConsentRecord record, ExecutableFingerprint? observed)
|
||||
{
|
||||
|
||||
@@ -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.Telemetry;
|
||||
using FrameLedger.Shared;
|
||||
|
||||
namespace FrameLedger.Application.Capture;
|
||||
@@ -22,4 +23,13 @@ public interface ICaptureObserver
|
||||
|
||||
/// <summary>After every drain, including the last one before the ring is released.</summary>
|
||||
void Tick(CaptureProgress progress);
|
||||
|
||||
/// <summary>
|
||||
/// Which process the game's own memory is read from (beta.12, D43): the pinned one as soon as the loop holds it, an
|
||||
/// unpinned hold's processes whenever their set changes, and <see cref="GameProcess.None"/> before the pin is released.
|
||||
/// The loop decides what may be opened; the observer only forwards it to the telemetry thread.
|
||||
/// </summary>
|
||||
void Measuring(GameProcess target)
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
|
||||
|
||||
using FrameLedger.Application.Telemetry;
|
||||
|
||||
namespace FrameLedger.Application.Capture;
|
||||
|
||||
/// <summary>How the host finds the process to capture. There is no pid argument anywhere.</summary>
|
||||
@@ -29,4 +31,11 @@ public interface ITargetResolver
|
||||
/// display sample then says "no window", never another program's.
|
||||
/// </summary>
|
||||
IReadOnlyList<int> PidsOf(string normalisedExePath);
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="PidsOf"/> with each process's creation time from the same snapshot (beta.12, D43): what an unpinned hold
|
||||
/// reads the game's memory of, so a pid reused between the snapshot and the read is refused rather than read off a
|
||||
/// stranger. A process whose creation time could not be read is left out. Empty where no watcher runs.
|
||||
/// </summary>
|
||||
IReadOnlyList<GameProcessId> ProcessesOf(string normalisedExePath) => [];
|
||||
}
|
||||
@@ -106,6 +106,15 @@ public sealed class SessionEventPublisher : ISessionObserver
|
||||
{
|
||||
t.LastGpu = drained[^1].Sample;
|
||||
t.LastSystem = drained[^1].System;
|
||||
// The newest tick that said anything about the game's memory (beta.12, D43): an empty one does not erase it.
|
||||
for (int i = drained.Count - 1; i >= 0; i--)
|
||||
{
|
||||
if (!drained[i].Game.IsEmpty)
|
||||
{
|
||||
t.LastGame = drained[i].Game;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (progress.Hold is { } hold && t.AttachedAt is null)
|
||||
@@ -206,7 +215,9 @@ public sealed class SessionEventPublisher : ISessionObserver
|
||||
t.LastGpu?.TempCoreC,
|
||||
t.LastSystem.CpuTempC,
|
||||
t.LastGpu?.LoadPct,
|
||||
t.LastSystem.CpuLoadPct));
|
||||
t.LastSystem.CpuLoadPct,
|
||||
t.LastGame.VramDedicatedMb,
|
||||
t.LastGame.RamPrivateMb));
|
||||
}
|
||||
|
||||
private void PublishProgress(Guid sessionGuid, Tracked t, CaptureProgress progress, long now)
|
||||
@@ -214,7 +225,7 @@ public sealed class SessionEventPublisher : ISessionObserver
|
||||
try
|
||||
{
|
||||
double elapsed = _clock.GetElapsedTime(t.AttachedTimestamp, now).TotalSeconds;
|
||||
SessionProgressEvent e = SessionProgressCalculator.Compute(sessionGuid, progress, t.Info.QpcFrequency, elapsed, t.LastGpu, t.LastSystem);
|
||||
SessionProgressEvent e = SessionProgressCalculator.Compute(sessionGuid, progress, t.Info.QpcFrequency, elapsed, t.LastGpu, t.LastSystem, t.LastGame);
|
||||
_pipe.Publish(IpcMessageType.SessionProgress, e);
|
||||
Interlocked.Increment(ref _progressPublished);
|
||||
}
|
||||
@@ -260,6 +271,8 @@ public sealed class SessionEventPublisher : ISessionObserver
|
||||
|
||||
public SystemReading LastSystem { get; set; }
|
||||
|
||||
public ProcessReading LastGame { get; set; }
|
||||
|
||||
/// <summary>Why a held session measures nothing; set by its first held tick (2026-09-23).</summary>
|
||||
public SessionHold? Hold { get; set; }
|
||||
|
||||
|
||||
@@ -31,7 +31,8 @@ public static class SessionProgressCalculator
|
||||
{
|
||||
public const double WindowSeconds = 5;
|
||||
|
||||
public static SessionProgressEvent Compute(Guid sessionGuid, CaptureProgress progress, long qpcFrequency, double elapsedSeconds, GpuSample? gpu, SystemReading system = default)
|
||||
public static SessionProgressEvent Compute(Guid sessionGuid, CaptureProgress progress, long qpcFrequency, double elapsedSeconds, GpuSample? gpu,
|
||||
SystemReading system = default, ProcessReading game = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(progress);
|
||||
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(qpcFrequency);
|
||||
@@ -75,6 +76,8 @@ public static class SessionProgressCalculator
|
||||
CpuLoadPct = system.CpuLoadPct,
|
||||
VramProcMb = Newest(w.All, MeasuredFields.Vram, static s => s.VramUsedMb > 0 ? (int)s.VramUsedMb : null),
|
||||
LatencyUs = Newest(w.All, MeasuredFields.Latency, static s => s.ReflexLatencyUs > 0 ? (int)s.ReflexLatencyUs : null),
|
||||
GameVramDedicatedMb = game.VramDedicatedMb,
|
||||
GameRamPrivateMb = game.RamPrivateMb,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -315,4 +315,32 @@ public sealed record SessionRow
|
||||
public int? DisplayMonitorH { get; init; }
|
||||
|
||||
public int? DisplayMonitorHz { get; init; }
|
||||
|
||||
// --- Schema 0018 (beta.12, D43): the game process's own memory, read from outside it, both tiers (03_METRICS §Game
|
||||
// process memory), MiB; and every sensor series' statistics as JSON. Null on a row written before beta.12, and where
|
||||
// nothing answered (the DLL absent, the counters missing, the process refused).
|
||||
|
||||
public double? GameVramDedicatedAvgMb { get; init; }
|
||||
|
||||
public double? GameVramDedicatedMedianMb { get; init; }
|
||||
|
||||
public double? GameVramDedicatedMaxMb { get; init; }
|
||||
|
||||
public double? GameVramSharedMaxMb { get; init; }
|
||||
|
||||
public double? GameRamPrivateAvgMb { get; init; }
|
||||
|
||||
public double? GameRamPrivateMedianMb { get; init; }
|
||||
|
||||
public double? GameRamPrivateMaxMb { get; init; }
|
||||
|
||||
public double? GameRamWorkingSetMaxMb { get; init; }
|
||||
|
||||
public double? GameCommitMaxMb { get; init; }
|
||||
|
||||
public int? GameMemoryProcesses { get; init; }
|
||||
|
||||
public string? GameMemorySource { get; init; }
|
||||
|
||||
public string? SensorStatsJson { get; init; }
|
||||
}
|
||||
@@ -12,6 +12,7 @@ namespace FrameLedger.Application.Recording;
|
||||
[JsonSerializable(typeof(NgxDriverWords))]
|
||||
[JsonSerializable(typeof(FgRefusalDetail))]
|
||||
[JsonSerializable(typeof(DriverProfileRecord))]
|
||||
[JsonSerializable(typeof(Dictionary<string, SensorSeriesStats>))]
|
||||
public sealed partial class RecordingJsonContext : JsonSerializerContext
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
|
||||
|
||||
using FrameLedger.Application.Telemetry;
|
||||
|
||||
namespace FrameLedger.Application.Recording;
|
||||
|
||||
/// <summary>
|
||||
/// Every 1 Hz series a session stores in <c>sensor_blobs</c>, by name, with the field of <see cref="TelemetrySample"/> it is
|
||||
/// read from (<c>06_DATA_MODEL</c> §sensor_blobs). One list for both consumers — the finalizer's blobs and the per-series
|
||||
/// statistics in <c>sessions.sensor_stats_json</c> (beta.12) — so a series cannot be stored without its statistics or the
|
||||
/// other way round.
|
||||
/// </summary>
|
||||
public static class SensorSeriesCatalog
|
||||
{
|
||||
public const string GpuTemp = "gpu_temp";
|
||||
public const string GpuHotspot = "gpu_hotspot";
|
||||
public const string GpuLoad = "gpu_load";
|
||||
public const string GpuPower = "gpu_power";
|
||||
public const string VramAdapter = "vram_adapter";
|
||||
public const string CpuLoad = "cpu_load";
|
||||
public const string CpuTemp = "cpu_temp";
|
||||
public const string RamSystem = "ram_mb";
|
||||
|
||||
/// <summary>The game process's dedicated GPU memory, MiB (beta.12, D43).</summary>
|
||||
public const string GameVramDedicated = "game_vram_dedicated";
|
||||
|
||||
/// <summary>The game process's shared GPU memory, MiB.</summary>
|
||||
public const string GameVramShared = "game_vram_shared";
|
||||
|
||||
/// <summary>The game process's private working set, MiB — Task Manager's "Memory".</summary>
|
||||
public const string GameRamPrivate = "game_ram_private";
|
||||
|
||||
/// <summary>The game process's whole working set, MiB.</summary>
|
||||
public const string GameRamWorkingSet = "game_ram_ws";
|
||||
|
||||
/// <summary>The game process's commit charge, MiB.</summary>
|
||||
public const string GameCommit = "game_commit";
|
||||
|
||||
/// <summary>The series in storage order. The first eight predate beta.12; their names are on disk and never change.</summary>
|
||||
public static IReadOnlyList<(string Name, Func<TelemetrySample, double?> Select)> All { get; } =
|
||||
[
|
||||
(GpuTemp, static s => s.Sample.TempCoreC),
|
||||
(GpuHotspot, static s => s.Sample.TempHotspotC),
|
||||
(GpuLoad, static s => s.Sample.LoadPct),
|
||||
(GpuPower, static s => s.Sample.PowerW),
|
||||
(VramAdapter, static s => s.Sample.VramAdapterMb),
|
||||
(CpuLoad, static s => s.System.CpuLoadPct),
|
||||
(CpuTemp, static s => s.System.CpuTempC),
|
||||
(RamSystem, static s => s.System.RamUsedMb),
|
||||
(GameVramDedicated, static s => s.Game.VramDedicatedMb),
|
||||
(GameVramShared, static s => s.Game.VramSharedMb),
|
||||
(GameRamPrivate, static s => s.Game.RamPrivateMb),
|
||||
(GameRamWorkingSet, static s => s.Game.RamWorkingSetMb),
|
||||
(GameCommit, static s => s.Game.CommitMb),
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
// 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.Domain.Metrics;
|
||||
|
||||
namespace FrameLedger.Application.Recording;
|
||||
|
||||
/// <summary>
|
||||
/// One series' statistics as <c>sessions.sensor_stats_json</c> stores them (beta.12; owner request "median, mean"):
|
||||
/// how many ticks carried a value, and their mean, median, minimum and maximum — computed once at finalize from the same
|
||||
/// samples the blob holds, so the summary reads stored values (<c>08_UI</c>: stat cards are never recomputed) and they
|
||||
/// survive a retention sweep of the raw series.
|
||||
/// </summary>
|
||||
/// <param name="N">Ticks that carried a value.</param>
|
||||
/// <param name="Mean">The mean, or null when <paramref name="N"/> is 0.</param>
|
||||
/// <param name="Median">The linear-interpolation median (<c>Percentile.Linear</c> at 0.5).</param>
|
||||
/// <param name="Min">The smallest value.</param>
|
||||
/// <param name="Max">The largest value.</param>
|
||||
public sealed record SensorSeriesStats(int N, double? Mean, double? Median, double? Min, double? Max)
|
||||
{
|
||||
/// <summary>The statistics of one series' aggregates.</summary>
|
||||
public static SensorSeriesStats From(SeriesAggregates a)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(a);
|
||||
return new SensorSeriesStats(a.Count, a.Average, a.Median, a.Min, a.Max);
|
||||
}
|
||||
|
||||
/// <summary>Every catalogued series that carried at least one value, as the column's JSON; null when none did.</summary>
|
||||
public static string? JsonOf(IReadOnlyList<Telemetry.TelemetrySample> sensors)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(sensors);
|
||||
var stats = new Dictionary<string, SensorSeriesStats>(StringComparer.Ordinal);
|
||||
foreach ((string name, Func<Telemetry.TelemetrySample, double?> select) in SensorSeriesCatalog.All)
|
||||
{
|
||||
SeriesAggregates a = SeriesAggregates.Of(sensors.Select(select));
|
||||
if (a.Count > 0)
|
||||
{
|
||||
stats[name] = From(a);
|
||||
}
|
||||
}
|
||||
|
||||
return stats.Count == 0 ? null : JsonSerializer.Serialize(stats, RecordingJsonContext.Default.DictionaryStringSensorSeriesStats);
|
||||
}
|
||||
|
||||
/// <summary>The column read back; an empty map for null or text this build cannot parse (never a throw into the UI).</summary>
|
||||
public static IReadOnlyDictionary<string, SensorSeriesStats> Parse(string? json)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(json))
|
||||
{
|
||||
return new Dictionary<string, SensorSeriesStats>(StringComparer.Ordinal);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
return JsonSerializer.Deserialize(json, RecordingJsonContext.Default.DictionaryStringSensorSeriesStats)
|
||||
?? new Dictionary<string, SensorSeriesStats>(StringComparer.Ordinal);
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return new Dictionary<string, SensorSeriesStats>(StringComparer.Ordinal);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -199,7 +199,7 @@ public static class SessionAggregator
|
||||
SeriesAggregates cpuLoad = SeriesAggregates.Of(sensors.Select(static t => t.System.CpuLoadPct));
|
||||
SeriesAggregates cpuTemp = SeriesAggregates.Of(sensors.Select(static t => t.System.CpuTempC));
|
||||
SeriesAggregates ram = SeriesAggregates.Of(sensors.Select(static t => t.System.RamUsedMb));
|
||||
return row with
|
||||
return (row with
|
||||
{
|
||||
AvgCpuLoad = cpuLoad.Average,
|
||||
AvgCpuTemp = cpuTemp.Average,
|
||||
@@ -212,9 +212,69 @@ public static class SessionAggregator
|
||||
AvgGpuPowerW = power.Average,
|
||||
VramAdapterMaxMb = adapter.Max,
|
||||
ThrottlePct = throttleSamples == 0 ? null : 100.0 * s.Count(static x => x.ThrottleReasons is > 0) / throttleSamples,
|
||||
}).WithGameMemory(sensors);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The game process's own memory (beta.12, D43; <c>03_METRICS</c> §Game process memory) and every series' statistics —
|
||||
/// both tiers, from the same 1 Hz samples. Null where no tick carried the field: a session before beta.12, the DLL
|
||||
/// absent, the counters missing, the process refused.
|
||||
/// </summary>
|
||||
private static SessionRow WithGameMemory(this SessionRow row, IReadOnlyList<TelemetrySample> sensors)
|
||||
{
|
||||
SeriesAggregates dedicated = SeriesAggregates.Of(sensors.Select(static t => t.Game.VramDedicatedMb));
|
||||
SeriesAggregates privateWs = SeriesAggregates.Of(sensors.Select(static t => t.Game.RamPrivateMb));
|
||||
ProcessReadingSources sources = sensors.Aggregate(ProcessReadingSources.None, static (all, t) => all | t.Game.Sources);
|
||||
int processes = sensors.Select(static t => t.Game.Processes).DefaultIfEmpty(0).Max();
|
||||
return row with
|
||||
{
|
||||
GameVramDedicatedAvgMb = dedicated.Average,
|
||||
GameVramDedicatedMedianMb = dedicated.Median,
|
||||
GameVramDedicatedMaxMb = dedicated.Max,
|
||||
GameVramSharedMaxMb = SeriesAggregates.Of(sensors.Select(static t => t.Game.VramSharedMb)).Max,
|
||||
GameRamPrivateAvgMb = privateWs.Average,
|
||||
GameRamPrivateMedianMb = privateWs.Median,
|
||||
GameRamPrivateMaxMb = privateWs.Max,
|
||||
GameRamWorkingSetMaxMb = SeriesAggregates.Of(sensors.Select(static t => t.Game.RamWorkingSetMb)).Max,
|
||||
GameCommitMaxMb = SeriesAggregates.Of(sensors.Select(static t => t.Game.CommitMb)).Max,
|
||||
GameMemoryProcesses = processes > 0 ? processes : null,
|
||||
GameMemorySource = SourceText(sources),
|
||||
SensorStatsJson = SensorSeriesStats.JsonOf(sensors),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary><c>sessions.game_memory_source</c>: which reads answered during the session, comma-separated; null when none did.</summary>
|
||||
private static string? SourceText(ProcessReadingSources sources)
|
||||
{
|
||||
var parts = new List<string>(5);
|
||||
if (sources.HasFlag(ProcessReadingSources.Counters))
|
||||
{
|
||||
parts.Add("counters");
|
||||
}
|
||||
|
||||
if (sources.HasFlag(ProcessReadingSources.PrivateWorkingSetRead))
|
||||
{
|
||||
parts.Add("ex2");
|
||||
}
|
||||
|
||||
if (sources.HasFlag(ProcessReadingSources.WorkingSetReadOnly))
|
||||
{
|
||||
parts.Add("ex");
|
||||
}
|
||||
|
||||
if (sources.HasFlag(ProcessReadingSources.HeldHandle))
|
||||
{
|
||||
parts.Add("held");
|
||||
}
|
||||
|
||||
if (sources.HasFlag(ProcessReadingSources.TransientHandle))
|
||||
{
|
||||
parts.Add("opened");
|
||||
}
|
||||
|
||||
return parts.Count == 0 ? null : string.Join(',', parts);
|
||||
}
|
||||
|
||||
private static SessionRow ApplyWitnesses(SessionRow row, Context c)
|
||||
{
|
||||
NgxDriverState ngx = c.Input.Ngx;
|
||||
|
||||
@@ -253,14 +253,13 @@ public sealed class SessionFinalizer
|
||||
{
|
||||
Blob("t_ms", sensors, s => (float)((s.QpcTicks - (long)qpcEpoch) * 1000.0 / qpcFrequency)),
|
||||
};
|
||||
AddIfAny(blobs, "gpu_temp", sensors, static s => s.Sample.TempCoreC);
|
||||
AddIfAny(blobs, "gpu_hotspot", sensors, static s => s.Sample.TempHotspotC);
|
||||
AddIfAny(blobs, "gpu_load", sensors, static s => s.Sample.LoadPct);
|
||||
AddIfAny(blobs, "gpu_power", sensors, static s => s.Sample.PowerW);
|
||||
AddIfAny(blobs, "vram_adapter", sensors, static s => s.Sample.VramAdapterMb);
|
||||
AddIfAny(blobs, "cpu_load", sensors, static s => s.System.CpuLoadPct);
|
||||
AddIfAny(blobs, "cpu_temp", sensors, static s => s.System.CpuTempC);
|
||||
AddIfAny(blobs, "ram_mb", sensors, static s => s.System.RamUsedMb);
|
||||
// One list (SensorSeriesCatalog) for the blobs and for sensor_stats_json; the game process's memory joined it in
|
||||
// beta.12 (D43) — five series, MiB, both tiers.
|
||||
foreach ((string name, Func<TelemetrySample, double?> select) in SensorSeriesCatalog.All)
|
||||
{
|
||||
AddIfAny(blobs, name, sensors, select);
|
||||
}
|
||||
|
||||
return blobs;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
|
||||
|
||||
using System.Globalization;
|
||||
using FrameLedger.Application.Capture;
|
||||
using FrameLedger.Application.Persistence;
|
||||
using FrameLedger.Application.Telemetry;
|
||||
@@ -332,6 +333,20 @@ public sealed class SessionRecorder : ISessionRecorder
|
||||
observer?.Attached(guid, pid, handshake);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The process the game's memory is read from (beta.12, D43): forwarded to the telemetry thread, and noted in the
|
||||
/// <c>.partial</c> when it changes so a recovered session says what it was reading.
|
||||
/// </summary>
|
||||
public void Measuring(GameProcess target)
|
||||
{
|
||||
poller?.Follow(target);
|
||||
writer.Note(target.IsNone
|
||||
? "memory: none"
|
||||
: target.Pid is int pid
|
||||
? $"memory: pid={pid} held"
|
||||
: "memory: " + string.Join(",", target.Processes.Select(static p => p.Pid.ToString(CultureInfo.InvariantCulture))));
|
||||
}
|
||||
|
||||
public void Tick(CaptureProgress progress)
|
||||
{
|
||||
_last = progress;
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
|
||||
|
||||
using FrameLedger.Application.Capture;
|
||||
|
||||
namespace FrameLedger.Application.Telemetry;
|
||||
|
||||
/// <summary>
|
||||
/// Which process the telemetry thread reads the game's memory of (beta.12, D43). The capture loop owns the process's
|
||||
/// identity and tells the poller (<see cref="ICaptureObserver.Measuring"/> → <see cref="ITelemetryPoller.Follow"/>); the
|
||||
/// poller only reads what it is told, so the rules about what may be opened stay in one place — <c>CaptureSession</c>.
|
||||
/// </summary>
|
||||
public sealed record GameProcess
|
||||
{
|
||||
private GameProcess(int? pid, ITargetLiveness? pinned, IReadOnlyList<GameProcessId> processes)
|
||||
{
|
||||
Pid = pid;
|
||||
PinnedBy = pinned;
|
||||
Processes = processes;
|
||||
}
|
||||
|
||||
/// <summary>Nothing to read: before a session has a process, and after the one it had was let go.</summary>
|
||||
public static GameProcess None { get; } = new(null, null, []);
|
||||
|
||||
/// <summary>The pinned process. Its handle is the session's own — held for liveness — so the read opens nothing.</summary>
|
||||
public int? Pid { get; }
|
||||
|
||||
/// <summary>The session's pin on <see cref="Pid"/>, whose handle the reader may use for the system half.</summary>
|
||||
public ITargetLiveness? PinnedBy { get; }
|
||||
|
||||
/// <summary>An unpinned Tier-2 hold's processes — every one running the game's executable in the watcher's snapshot.</summary>
|
||||
public IReadOnlyList<GameProcessId> Processes { get; }
|
||||
|
||||
public bool IsNone => Pid is null && Processes.Count == 0;
|
||||
|
||||
/// <summary>A process the session holds a handle to: the attach and launch paths, and a refusal after the pin.</summary>
|
||||
public static GameProcess Pinned(int pid, ITargetLiveness pinnedBy)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(pinnedBy);
|
||||
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(pid);
|
||||
return new GameProcess(pid, pinnedBy, []);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The processes of a hold that never opened the game — hooking off, blocked, unresolved, cannot pin. The reader opens
|
||||
/// each transiently with the least right that answers and refuses one whose creation time is not the snapshot's.
|
||||
/// </summary>
|
||||
public static GameProcess Unpinned(IReadOnlyList<GameProcessId> processes)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(processes);
|
||||
return processes.Count == 0 ? None : new GameProcess(null, null, [.. processes]);
|
||||
}
|
||||
|
||||
/// <summary>Whether two unpinned targets name the same processes (a hold re-announces only a changed set).</summary>
|
||||
public bool SameProcessesAs(IReadOnlyList<GameProcessId> other)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(other);
|
||||
return Pid is null && Processes.Count == other.Count && Processes.All(other.Contains);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
|
||||
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace FrameLedger.Application.Telemetry;
|
||||
|
||||
/// <summary>One process of an unpinned hold: its pid and the creation time the watcher's snapshot read.</summary>
|
||||
/// <param name="Pid">The process id.</param>
|
||||
/// <param name="StartedAt">The creation time from the snapshot; a reused pid's differs, and the read is refused.</param>
|
||||
[StructLayout(LayoutKind.Auto)]
|
||||
public readonly record struct GameProcessId(int Pid, DateTimeOffset StartedAt);
|
||||
@@ -0,0 +1,23 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
|
||||
|
||||
namespace FrameLedger.Application.Telemetry;
|
||||
|
||||
/// <summary>
|
||||
/// The game process's own memory, read from outside it (beta.12, owner decision D43): the telemetry thread's third source
|
||||
/// beside the GPU layers and the machine. <c>Infrastructure.Telemetry.GameMemoryReader</c> is the real one, over
|
||||
/// <c>FrameLedger.ProcessStats.dll</c>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <see cref="Follow"/> is called from the capture loop's task and <see cref="TryRead"/> from the telemetry thread: the
|
||||
/// target is a published reference, never a shared mutable list. A reader that cannot answer — the DLL absent, the
|
||||
/// counters missing, the process refused — returns false or an empty reading; it never throws into the poller.
|
||||
/// </remarks>
|
||||
public interface IGameMemorySource : IDisposable
|
||||
{
|
||||
/// <summary>The process to read from now on (<see cref="GameProcess.None"/> to stop).</summary>
|
||||
void Follow(GameProcess target);
|
||||
|
||||
/// <summary>One reading of the followed process; false when there is nothing to follow or nothing answered.</summary>
|
||||
bool TryRead(out ProcessReading reading);
|
||||
}
|
||||
@@ -16,10 +16,11 @@ namespace FrameLedger.Application.Telemetry;
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <see cref="Descriptor"/> is what <c>sessions.telemetry_source</c> stores: the layers still
|
||||
/// standing, lowest first, joined with <c>+</c> (<c>l1+lhm+nvapi</c>). It is read at finalize
|
||||
/// standing, lowest first, joined with <c>+</c> (<c>l1+lhm+nvapi</c>). ~~It is read at finalize
|
||||
/// time, so a layer disabled mid-session drops out of the descriptor the session is stored
|
||||
/// under — the descriptor names what the aggregates could have come from, not what was
|
||||
/// constructed.
|
||||
/// under.~~ **It is read when the session starts** (<c>SessionRecorder</c> puts it in the
|
||||
/// <c>.partial</c> header, and that is what is stored) — corrected 2026-10-03: the sentence said
|
||||
/// finalize, which the recorder never did, so a layer disabled mid-session stays in the descriptor.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public interface ITelemetryPoller : IDisposable
|
||||
@@ -34,4 +35,10 @@ public interface ITelemetryPoller : IDisposable
|
||||
|
||||
/// <summary>Move every queued sample into <paramref name="into"/>, oldest first. Returns how many.</summary>
|
||||
int Drain(ICollection<TelemetrySample> into);
|
||||
|
||||
/// <summary>
|
||||
/// The game process whose own memory the thread reads from now on (beta.12, D43) — told by the capture loop, which owns
|
||||
/// what may be opened (<see cref="GameProcess"/>). A poller with no game source ignores it.
|
||||
/// </summary>
|
||||
void Follow(GameProcess target) { }
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
|
||||
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace FrameLedger.Application.Telemetry;
|
||||
|
||||
/// <summary>
|
||||
/// The memory the game's own process uses on one tick (beta.12, owner decision D43; <c>03_METRICS</c> §Game process
|
||||
/// memory) — read from outside the game, never from its memory: the video half from the <c>GPU Process Memory</c>
|
||||
/// performance counters, the system half from <c>GetProcessMemoryInfo</c>. Every field nullable; null is <c>N/A</c>,
|
||||
/// never zero. MiB throughout (1 GB = 1024 MiB, Task Manager's counting).
|
||||
/// </summary>
|
||||
/// <param name="VramDedicatedMb">Dedicated GPU memory — Task Manager's Details column of that name. Not the DXGI budget-model "local usage": it reads a few MiB more per device (spike-notes §16, M3), and it is never compared with a budget.</param>
|
||||
/// <param name="VramSharedMb">Shared GPU memory — system memory the GPU uses on the process's behalf.</param>
|
||||
/// <param name="RamPrivateMb">The private working set — Task Manager's "Memory" column. Null where Windows predates <c>PROCESS_MEMORY_COUNTERS_EX2</c>.</param>
|
||||
/// <param name="RamWorkingSetMb">The whole working set, shared pages included.</param>
|
||||
/// <param name="CommitMb">The commit charge (<c>PrivateUsage</c>): private memory committed, resident or not.</param>
|
||||
/// <param name="Processes">How many processes the figures are summed over: 1 for a pinned game; every process running the game's executable for an unpinned Tier-2 hold.</param>
|
||||
/// <param name="Sources">Which reads answered, for <c>sessions.game_memory_source</c>.</param>
|
||||
[StructLayout(LayoutKind.Auto)]
|
||||
public readonly record struct ProcessReading(
|
||||
double? VramDedicatedMb,
|
||||
double? VramSharedMb,
|
||||
double? RamPrivateMb,
|
||||
double? RamWorkingSetMb,
|
||||
double? CommitMb,
|
||||
int Processes,
|
||||
ProcessReadingSources Sources)
|
||||
{
|
||||
/// <summary>No field carries a value: the tick has nothing to say about the game's memory.</summary>
|
||||
public bool IsEmpty => VramDedicatedMb is null && VramSharedMb is null && RamPrivateMb is null && RamWorkingSetMb is null && CommitMb is null;
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
|
||||
|
||||
namespace FrameLedger.Application.Telemetry;
|
||||
|
||||
/// <summary>What answered a <see cref="ProcessReading"/>; OR'd over a session for <c>sessions.game_memory_source</c>.</summary>
|
||||
[Flags]
|
||||
public enum ProcessReadingSources
|
||||
{
|
||||
None = 0,
|
||||
|
||||
/// <summary>The <c>GPU Process Memory</c> counters named the process.</summary>
|
||||
Counters = 1 << 0,
|
||||
|
||||
/// <summary><c>PROCESS_MEMORY_COUNTERS_EX2</c> answered (the private working set is there).</summary>
|
||||
PrivateWorkingSetRead = 1 << 1,
|
||||
|
||||
/// <summary>Only <c>PROCESS_MEMORY_COUNTERS_EX</c> answered: no private working set on this OS.</summary>
|
||||
WorkingSetReadOnly = 1 << 2,
|
||||
|
||||
/// <summary>The system half went through the handle the session already held.</summary>
|
||||
HeldHandle = 1 << 3,
|
||||
|
||||
/// <summary>The system half went through a handle opened for the read (<c>PROCESS_QUERY_LIMITED_INFORMATION</c>) and closed after it.</summary>
|
||||
TransientHandle = 1 << 4,
|
||||
}
|
||||
@@ -25,5 +25,6 @@ namespace FrameLedger.Application.Telemetry;
|
||||
/// <param name="QpcTicks">The raw performance counter at the read.</param>
|
||||
/// <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>
|
||||
[StructLayout(LayoutKind.Auto)]
|
||||
public readonly record struct TelemetrySample(long QpcTicks, GpuSample Sample, SystemReading System = default);
|
||||
public readonly record struct TelemetrySample(long QpcTicks, GpuSample Sample, SystemReading System = default, ProcessReading Game = default);
|
||||
@@ -1,6 +1,8 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
|
||||
|
||||
using FrameLedger.Application.Telemetry;
|
||||
|
||||
namespace FrameLedger.Application.Watch;
|
||||
|
||||
/// <summary>
|
||||
@@ -63,4 +65,18 @@ public sealed class LatestProcessSnapshot
|
||||
? [.. snapshot.Where(p => p.ImagePath is { } image && string.Equals(image, normalisedExePath, StringComparison.OrdinalIgnoreCase)).Select(static p => p.Pid)]
|
||||
: [];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="PidsOf"/> with each process's creation time (beta.12, D43): what an unpinned hold reads the game's memory
|
||||
/// of. A process whose creation time could not be read is left out — the read verifies against it, and an unverifiable
|
||||
/// pid is not read at all.
|
||||
/// </summary>
|
||||
public IReadOnlyList<GameProcessId> ProcessesOf(string normalisedExePath)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(normalisedExePath);
|
||||
return Current is { } snapshot
|
||||
? [.. snapshot.Where(p => p.StartedAt is not null && p.ImagePath is { } image && string.Equals(image, normalisedExePath, StringComparison.OrdinalIgnoreCase))
|
||||
.Select(static p => new GameProcessId(p.Pid, p.StartedAt!.Value))]
|
||||
: [];
|
||||
}
|
||||
}
|
||||
@@ -83,6 +83,7 @@
|
||||
-->
|
||||
<Import Project="$(MSBuildThisFileDirectory)..\..\FrameLedger.Guard.targets" />
|
||||
<Import Project="$(MSBuildThisFileDirectory)..\..\FrameLedger.NvapiBridge.targets" />
|
||||
<Import Project="$(MSBuildThisFileDirectory)..\..\FrameLedger.ProcessStats.targets" />
|
||||
<Import Project="$(MSBuildThisFileDirectory)..\..\FrameLedger.Rules.targets" />
|
||||
<Import Project="$(MSBuildThisFileDirectory)..\..\FrameLedger.Overlay.targets" />
|
||||
|
||||
|
||||
@@ -4,13 +4,19 @@
|
||||
namespace FrameLedger.Domain.Metrics;
|
||||
|
||||
/// <summary>
|
||||
/// <c>03_METRICS</c> §Sensor aggregates: the mean of the non-null samples and their maximum, and
|
||||
/// <b>N/A — never 0 — when there are none</b>.
|
||||
/// <c>03_METRICS</c> §Sensor aggregates: the mean of the non-null samples, their median, minimum and maximum, and
|
||||
/// <b>N/A — never 0 — when there are none</b>. The median is the linear-interpolation 50th percentile
|
||||
/// (<see cref="Percentile.Linear"/>): the middle sample of an odd count, the mean of the two middle ones of an even count.
|
||||
/// </summary>
|
||||
/// <remarks>The median and the minimum were added in beta.12 (owner request: "median, mean" for the game's memory and the sensors).</remarks>
|
||||
public sealed record SeriesAggregates
|
||||
{
|
||||
public required double? Average { get; init; }
|
||||
|
||||
public required double? Median { get; init; }
|
||||
|
||||
public required double? Min { get; init; }
|
||||
|
||||
public required double? Max { get; init; }
|
||||
|
||||
/// <summary>Samples that carried a value.</summary>
|
||||
@@ -20,9 +26,8 @@ public sealed record SeriesAggregates
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(samples);
|
||||
|
||||
var values = new List<double>();
|
||||
double sum = 0;
|
||||
double max = double.NegativeInfinity;
|
||||
int count = 0;
|
||||
foreach (double? s in samples)
|
||||
{
|
||||
if (s is not double v)
|
||||
@@ -30,16 +35,23 @@ public sealed record SeriesAggregates
|
||||
continue;
|
||||
}
|
||||
|
||||
count++;
|
||||
values.Add(v);
|
||||
sum += v;
|
||||
max = Math.Max(max, v);
|
||||
}
|
||||
|
||||
if (values.Count == 0)
|
||||
{
|
||||
return new SeriesAggregates { Average = null, Median = null, Min = null, Max = null, Count = 0 };
|
||||
}
|
||||
|
||||
values.Sort();
|
||||
return new SeriesAggregates
|
||||
{
|
||||
Average = count > 0 ? sum / count : null,
|
||||
Max = count > 0 ? max : null,
|
||||
Count = count,
|
||||
Average = sum / values.Count,
|
||||
Median = Percentile.Linear(values, 0.5),
|
||||
Min = values[0],
|
||||
Max = values[^1],
|
||||
Count = values.Count,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
|
||||
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace FrameLedger.Infrastructure.Capture;
|
||||
|
||||
/// <summary>
|
||||
/// A session's pin that lends its handle to a read about the process (beta.12, D43): <c>GameMemoryReader</c> reads the
|
||||
/// game's own memory through the handle the session already holds for liveness — <c>SYNCHRONIZE |
|
||||
/// PROCESS_QUERY_LIMITED_INFORMATION</c> and nothing more — so a pinned session opens nothing new for it.
|
||||
/// </summary>
|
||||
public interface IHeldProcessHandle
|
||||
{
|
||||
/// <summary>The held handle. Borrowed for a call, never disposed or stored by the borrower.</summary>
|
||||
SafeHandle ProcessHandle { get; }
|
||||
}
|
||||
@@ -28,7 +28,7 @@ namespace FrameLedger.Infrastructure.Capture;
|
||||
/// loop must not proceed to inject into a pid whose identity it could not pin.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public sealed class ProcessTargetLiveness(HeldProcessHandle handle, int pid) : ITargetLiveness
|
||||
public sealed class ProcessTargetLiveness(HeldProcessHandle handle, int pid) : ITargetLiveness, IHeldProcessHandle
|
||||
{
|
||||
private readonly HeldProcessHandle _handle = handle ?? throw new ArgumentNullException(nameof(handle));
|
||||
|
||||
@@ -49,5 +49,8 @@ public sealed class ProcessTargetLiveness(HeldProcessHandle handle, int pid) : I
|
||||
/// </remarks>
|
||||
public bool IsForeground => ForegroundWindowProbe.IsForeground(pid);
|
||||
|
||||
/// <summary>The held handle, lent to <c>GameMemoryReader</c> for the game's memory counters (beta.12, D43).</summary>
|
||||
public System.Runtime.InteropServices.SafeHandle ProcessHandle => _handle.Handle;
|
||||
|
||||
public void Dispose() => _handle.Dispose();
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
|
||||
using System.Diagnostics;
|
||||
using FrameLedger.Application.Capture;
|
||||
using FrameLedger.Application.Telemetry;
|
||||
using FrameLedger.Application.Watch;
|
||||
using FrameLedger.Infrastructure.Io;
|
||||
|
||||
@@ -97,6 +98,9 @@ public sealed class TargetResolver : ITargetResolver
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyList<int> PidsOf(string normalisedExePath) => _latest?.PidsOf(normalisedExePath) ?? [];
|
||||
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyList<GameProcessId> ProcessesOf(string normalisedExePath) => _latest?.ProcessesOf(normalisedExePath) ?? [];
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool IsRunning(string normalisedExePath)
|
||||
{
|
||||
|
||||
@@ -109,6 +109,12 @@ public sealed class HeldProcessHandle : IDisposable
|
||||
public int? ExitCode =>
|
||||
HasExited && GetExitCodeProcess(_handle, out uint code) && code != _stillActive ? unchecked((int)code) : null;
|
||||
|
||||
/// <summary>
|
||||
/// The held handle itself, for a read ABOUT the process through the same rights (beta.12, D43: the game's memory
|
||||
/// counters). Borrowed for one call — the marshaller add-refs it — and never disposed or kept by the borrower.
|
||||
/// </summary>
|
||||
public SafeProcessHandle Handle => _handle;
|
||||
|
||||
public void Dispose() => _handle.Dispose();
|
||||
|
||||
[DefaultDllImportSearchPaths(DllImportSearchPath.System32)]
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
-- 0018 (2026-10-03, beta.12, owner decision D43): the game process's own memory, both tiers (03_METRICS §Game process
|
||||
-- memory), and every sensor series' statistics.
|
||||
--
|
||||
-- Read from OUTSIDE the game once a second: the GPU Process Memory performance counters for its dedicated and shared GPU
|
||||
-- memory (Task Manager's two Details columns), GetProcessMemoryInfo for its private working set (Task Manager's "Memory"),
|
||||
-- working set and commit. A hooked session reads the pinned process through the handle the session already holds; an
|
||||
-- unpinned Tier-2 hold sums every process running the game's executable (game_memory_processes says how many).
|
||||
--
|
||||
-- NOT vram_proc_* (0001): those were defined as the in-process DXGI "local usage" compared with the budget, a different
|
||||
-- quantity (dedicated reads a few MiB more per device, spike-notes §16 M3) that stays reserved for §H10. MiB throughout.
|
||||
--
|
||||
-- sensor_stats_json is every sensor series' n / mean / median / min / max, computed once at finalize so the summary's
|
||||
-- statistics read STORED values (08_UI: stat cards are never recomputed) and outlive a retention sweep of the raw series.
|
||||
--
|
||||
-- Written by the Agent only (06_DATA_MODEL §Writer ownership: the sessions table is the recorder's); ADD COLUMN only.
|
||||
|
||||
ALTER TABLE sessions ADD COLUMN game_vram_dedicated_avg_mb REAL;
|
||||
ALTER TABLE sessions ADD COLUMN game_vram_dedicated_median_mb REAL;
|
||||
ALTER TABLE sessions ADD COLUMN game_vram_dedicated_max_mb REAL;
|
||||
ALTER TABLE sessions ADD COLUMN game_vram_shared_max_mb REAL;
|
||||
ALTER TABLE sessions ADD COLUMN game_ram_private_avg_mb REAL;
|
||||
ALTER TABLE sessions ADD COLUMN game_ram_private_median_mb REAL;
|
||||
ALTER TABLE sessions ADD COLUMN game_ram_private_max_mb REAL;
|
||||
ALTER TABLE sessions ADD COLUMN game_ram_ws_max_mb REAL;
|
||||
ALTER TABLE sessions ADD COLUMN game_commit_max_mb REAL;
|
||||
ALTER TABLE sessions ADD COLUMN game_memory_processes INTEGER;
|
||||
ALTER TABLE sessions ADD COLUMN game_memory_source TEXT;
|
||||
ALTER TABLE sessions ADD COLUMN sensor_stats_json TEXT;
|
||||
@@ -16,10 +16,10 @@ namespace FrameLedger.Infrastructure.Persistence;
|
||||
internal static class SessionRowColumns
|
||||
{
|
||||
public const string Insert =
|
||||
"INSERT INTO sessions (session_guid, game_id, snapshot_id, started_at, ended_at, duration_s, qpc_epoch, qpc_frequency, capture_tier, capture_mode, capture_notes, ac_exception_family, late_attach, telemetry_source, overlay_build_id, exit_status, drain_ticks, foreground_ticks, records_before_attach, dxgi_presents_before_hook, gap_count, guard_ticks_published, launch_wait_ms, api, present_mode, swap_effect, hdr_flag, hdr_source, sync_interval_mode, upscaler, upscaler_quality, upscaler_sharpness, upscaler_driver_reported, render_w, render_h, output_w, output_h, upscale_ratio, settings_changed_midsession, fg_mode, fg_source, fg_factor, fg_driver_reported, fg_runtime_census, fg_none_withheld_reason, fg_refusal, fg_refusal_detail, fg_factor_scope, fg_steady_share, presented_fps, presented_qualifier, dxgi_unseen_total, dxgi_present_samples, displayed_counted_by, sl_tag_census, sl_interposer_version, runtime_modules, driver_profile, executable_markers, ngx_driver_words, rt_flag, rt_source, pt_flag, pt_source, pt_confidence, rr_flag, rr_source, rt_frame_pct, rays_per_pixel, rt_pso_count, rt_tier, hooks_installed_mask, raster_pso_count, frame_count, app_frame_count, displayed_frame_count, dropped_frames, native_fps, displayed_fps, median_fps, p1_low_fps, p01_low_fps, displayed_p1_low_fps, min_fps, max_fps, frametime_stddev_ms, stutter_count, stutter_time_pct, pso_stutter_pct, reflex_active, latency_avg_us, latency_p95_us, dropped_records, fault_count, data_quality_warnings, writer_status_at_end, early_stop_family, loader_signals, vram_proc_avg_mb, vram_proc_max_mb, vram_budget_exceeded_pct, vram_adapter_max_mb, avg_cpu_temp, max_cpu_temp, avg_gpu_temp, max_gpu_temp, max_gpu_hotspot, avg_gpu_load, avg_cpu_load, avg_ram_mb, avg_gpu_power_w, throttle_pct, display_exclusive_ms, display_borderless_ms, display_windowed_ms, display_covers_ms, display_minimized_ms, display_nowindow_ms, display_changes, display_source, display_window_w, display_window_h, display_buffer_w, display_buffer_h, display_monitor_w, display_monitor_h, display_monitor_hz) "
|
||||
+ "VALUES (@session_guid, @game_id, @snapshot_id, @started_at, @ended_at, @duration_s, @qpc_epoch, @qpc_frequency, @capture_tier, @capture_mode, @capture_notes, @ac_exception_family, @late_attach, @telemetry_source, @overlay_build_id, @exit_status, @drain_ticks, @foreground_ticks, @records_before_attach, @dxgi_presents_before_hook, @gap_count, @guard_ticks_published, @launch_wait_ms, @api, @present_mode, @swap_effect, @hdr_flag, @hdr_source, @sync_interval_mode, @upscaler, @upscaler_quality, @upscaler_sharpness, @upscaler_driver_reported, @render_w, @render_h, @output_w, @output_h, @upscale_ratio, @settings_changed_midsession, @fg_mode, @fg_source, @fg_factor, @fg_driver_reported, @fg_runtime_census, @fg_none_withheld_reason, @fg_refusal, @fg_refusal_detail, @fg_factor_scope, @fg_steady_share, @presented_fps, @presented_qualifier, @dxgi_unseen_total, @dxgi_present_samples, @displayed_counted_by, @sl_tag_census, @sl_interposer_version, @runtime_modules, @driver_profile, @executable_markers, @ngx_driver_words, @rt_flag, @rt_source, @pt_flag, @pt_source, @pt_confidence, @rr_flag, @rr_source, @rt_frame_pct, @rays_per_pixel, @rt_pso_count, @rt_tier, @hooks_installed_mask, @raster_pso_count, @frame_count, @app_frame_count, @displayed_frame_count, @dropped_frames, @native_fps, @displayed_fps, @median_fps, @p1_low_fps, @p01_low_fps, @displayed_p1_low_fps, @min_fps, @max_fps, @frametime_stddev_ms, @stutter_count, @stutter_time_pct, @pso_stutter_pct, @reflex_active, @latency_avg_us, @latency_p95_us, @dropped_records, @fault_count, @data_quality_warnings, @writer_status_at_end, @early_stop_family, @loader_signals, @vram_proc_avg_mb, @vram_proc_max_mb, @vram_budget_exceeded_pct, @vram_adapter_max_mb, @avg_cpu_temp, @max_cpu_temp, @avg_gpu_temp, @max_gpu_temp, @max_gpu_hotspot, @avg_gpu_load, @avg_cpu_load, @avg_ram_mb, @avg_gpu_power_w, @throttle_pct, @display_exclusive_ms, @display_borderless_ms, @display_windowed_ms, @display_covers_ms, @display_minimized_ms, @display_nowindow_ms, @display_changes, @display_source, @display_window_w, @display_window_h, @display_buffer_w, @display_buffer_h, @display_monitor_w, @display_monitor_h, @display_monitor_hz) RETURNING id";
|
||||
"INSERT INTO sessions (session_guid, game_id, snapshot_id, started_at, ended_at, duration_s, qpc_epoch, qpc_frequency, capture_tier, capture_mode, capture_notes, ac_exception_family, late_attach, telemetry_source, overlay_build_id, exit_status, drain_ticks, foreground_ticks, records_before_attach, dxgi_presents_before_hook, gap_count, guard_ticks_published, launch_wait_ms, api, present_mode, swap_effect, hdr_flag, hdr_source, sync_interval_mode, upscaler, upscaler_quality, upscaler_sharpness, upscaler_driver_reported, render_w, render_h, output_w, output_h, upscale_ratio, settings_changed_midsession, fg_mode, fg_source, fg_factor, fg_driver_reported, fg_runtime_census, fg_none_withheld_reason, fg_refusal, fg_refusal_detail, fg_factor_scope, fg_steady_share, presented_fps, presented_qualifier, dxgi_unseen_total, dxgi_present_samples, displayed_counted_by, sl_tag_census, sl_interposer_version, runtime_modules, driver_profile, executable_markers, ngx_driver_words, rt_flag, rt_source, pt_flag, pt_source, pt_confidence, rr_flag, rr_source, rt_frame_pct, rays_per_pixel, rt_pso_count, rt_tier, hooks_installed_mask, raster_pso_count, frame_count, app_frame_count, displayed_frame_count, dropped_frames, native_fps, displayed_fps, median_fps, p1_low_fps, p01_low_fps, displayed_p1_low_fps, min_fps, max_fps, frametime_stddev_ms, stutter_count, stutter_time_pct, pso_stutter_pct, reflex_active, latency_avg_us, latency_p95_us, dropped_records, fault_count, data_quality_warnings, writer_status_at_end, early_stop_family, loader_signals, vram_proc_avg_mb, vram_proc_max_mb, vram_budget_exceeded_pct, vram_adapter_max_mb, avg_cpu_temp, max_cpu_temp, avg_gpu_temp, max_gpu_temp, max_gpu_hotspot, avg_gpu_load, avg_cpu_load, avg_ram_mb, avg_gpu_power_w, throttle_pct, display_exclusive_ms, display_borderless_ms, display_windowed_ms, display_covers_ms, display_minimized_ms, display_nowindow_ms, display_changes, display_source, display_window_w, display_window_h, display_buffer_w, display_buffer_h, display_monitor_w, display_monitor_h, display_monitor_hz, game_vram_dedicated_avg_mb, game_vram_dedicated_median_mb, game_vram_dedicated_max_mb, game_vram_shared_max_mb, game_ram_private_avg_mb, game_ram_private_median_mb, game_ram_private_max_mb, game_ram_ws_max_mb, game_commit_max_mb, game_memory_processes, game_memory_source, sensor_stats_json) "
|
||||
+ "VALUES (@session_guid, @game_id, @snapshot_id, @started_at, @ended_at, @duration_s, @qpc_epoch, @qpc_frequency, @capture_tier, @capture_mode, @capture_notes, @ac_exception_family, @late_attach, @telemetry_source, @overlay_build_id, @exit_status, @drain_ticks, @foreground_ticks, @records_before_attach, @dxgi_presents_before_hook, @gap_count, @guard_ticks_published, @launch_wait_ms, @api, @present_mode, @swap_effect, @hdr_flag, @hdr_source, @sync_interval_mode, @upscaler, @upscaler_quality, @upscaler_sharpness, @upscaler_driver_reported, @render_w, @render_h, @output_w, @output_h, @upscale_ratio, @settings_changed_midsession, @fg_mode, @fg_source, @fg_factor, @fg_driver_reported, @fg_runtime_census, @fg_none_withheld_reason, @fg_refusal, @fg_refusal_detail, @fg_factor_scope, @fg_steady_share, @presented_fps, @presented_qualifier, @dxgi_unseen_total, @dxgi_present_samples, @displayed_counted_by, @sl_tag_census, @sl_interposer_version, @runtime_modules, @driver_profile, @executable_markers, @ngx_driver_words, @rt_flag, @rt_source, @pt_flag, @pt_source, @pt_confidence, @rr_flag, @rr_source, @rt_frame_pct, @rays_per_pixel, @rt_pso_count, @rt_tier, @hooks_installed_mask, @raster_pso_count, @frame_count, @app_frame_count, @displayed_frame_count, @dropped_frames, @native_fps, @displayed_fps, @median_fps, @p1_low_fps, @p01_low_fps, @displayed_p1_low_fps, @min_fps, @max_fps, @frametime_stddev_ms, @stutter_count, @stutter_time_pct, @pso_stutter_pct, @reflex_active, @latency_avg_us, @latency_p95_us, @dropped_records, @fault_count, @data_quality_warnings, @writer_status_at_end, @early_stop_family, @loader_signals, @vram_proc_avg_mb, @vram_proc_max_mb, @vram_budget_exceeded_pct, @vram_adapter_max_mb, @avg_cpu_temp, @max_cpu_temp, @avg_gpu_temp, @max_gpu_temp, @max_gpu_hotspot, @avg_gpu_load, @avg_cpu_load, @avg_ram_mb, @avg_gpu_power_w, @throttle_pct, @display_exclusive_ms, @display_borderless_ms, @display_windowed_ms, @display_covers_ms, @display_minimized_ms, @display_nowindow_ms, @display_changes, @display_source, @display_window_w, @display_window_h, @display_buffer_w, @display_buffer_h, @display_monitor_w, @display_monitor_h, @display_monitor_hz, @game_vram_dedicated_avg_mb, @game_vram_dedicated_median_mb, @game_vram_dedicated_max_mb, @game_vram_shared_max_mb, @game_ram_private_avg_mb, @game_ram_private_median_mb, @game_ram_private_max_mb, @game_ram_ws_max_mb, @game_commit_max_mb, @game_memory_processes, @game_memory_source, @sensor_stats_json) RETURNING id";
|
||||
|
||||
public const string Select = "SELECT id, session_guid, game_id, snapshot_id, started_at, ended_at, duration_s, qpc_epoch, qpc_frequency, capture_tier, capture_mode, capture_notes, ac_exception_family, late_attach, telemetry_source, overlay_build_id, exit_status, drain_ticks, foreground_ticks, records_before_attach, dxgi_presents_before_hook, gap_count, guard_ticks_published, launch_wait_ms, api, present_mode, swap_effect, hdr_flag, hdr_source, sync_interval_mode, upscaler, upscaler_quality, upscaler_sharpness, upscaler_driver_reported, render_w, render_h, output_w, output_h, upscale_ratio, settings_changed_midsession, fg_mode, fg_source, fg_factor, fg_driver_reported, fg_runtime_census, fg_none_withheld_reason, fg_refusal, fg_refusal_detail, fg_factor_scope, fg_steady_share, presented_fps, presented_qualifier, dxgi_unseen_total, dxgi_present_samples, displayed_counted_by, sl_tag_census, sl_interposer_version, runtime_modules, driver_profile, executable_markers, ngx_driver_words, rt_flag, rt_source, pt_flag, pt_source, pt_confidence, rr_flag, rr_source, rt_frame_pct, rays_per_pixel, rt_pso_count, rt_tier, hooks_installed_mask, raster_pso_count, frame_count, app_frame_count, displayed_frame_count, dropped_frames, native_fps, displayed_fps, median_fps, p1_low_fps, p01_low_fps, displayed_p1_low_fps, min_fps, max_fps, frametime_stddev_ms, stutter_count, stutter_time_pct, pso_stutter_pct, reflex_active, latency_avg_us, latency_p95_us, dropped_records, fault_count, data_quality_warnings, writer_status_at_end, early_stop_family, loader_signals, vram_proc_avg_mb, vram_proc_max_mb, vram_budget_exceeded_pct, vram_adapter_max_mb, avg_cpu_temp, max_cpu_temp, avg_gpu_temp, max_gpu_temp, max_gpu_hotspot, avg_gpu_load, avg_cpu_load, avg_ram_mb, avg_gpu_power_w, throttle_pct, display_exclusive_ms, display_borderless_ms, display_windowed_ms, display_covers_ms, display_minimized_ms, display_nowindow_ms, display_changes, display_source, display_window_w, display_window_h, display_buffer_w, display_buffer_h, display_monitor_w, display_monitor_h, display_monitor_hz FROM sessions";
|
||||
public const string Select = "SELECT id, session_guid, game_id, snapshot_id, started_at, ended_at, duration_s, qpc_epoch, qpc_frequency, capture_tier, capture_mode, capture_notes, ac_exception_family, late_attach, telemetry_source, overlay_build_id, exit_status, drain_ticks, foreground_ticks, records_before_attach, dxgi_presents_before_hook, gap_count, guard_ticks_published, launch_wait_ms, api, present_mode, swap_effect, hdr_flag, hdr_source, sync_interval_mode, upscaler, upscaler_quality, upscaler_sharpness, upscaler_driver_reported, render_w, render_h, output_w, output_h, upscale_ratio, settings_changed_midsession, fg_mode, fg_source, fg_factor, fg_driver_reported, fg_runtime_census, fg_none_withheld_reason, fg_refusal, fg_refusal_detail, fg_factor_scope, fg_steady_share, presented_fps, presented_qualifier, dxgi_unseen_total, dxgi_present_samples, displayed_counted_by, sl_tag_census, sl_interposer_version, runtime_modules, driver_profile, executable_markers, ngx_driver_words, rt_flag, rt_source, pt_flag, pt_source, pt_confidence, rr_flag, rr_source, rt_frame_pct, rays_per_pixel, rt_pso_count, rt_tier, hooks_installed_mask, raster_pso_count, frame_count, app_frame_count, displayed_frame_count, dropped_frames, native_fps, displayed_fps, median_fps, p1_low_fps, p01_low_fps, displayed_p1_low_fps, min_fps, max_fps, frametime_stddev_ms, stutter_count, stutter_time_pct, pso_stutter_pct, reflex_active, latency_avg_us, latency_p95_us, dropped_records, fault_count, data_quality_warnings, writer_status_at_end, early_stop_family, loader_signals, vram_proc_avg_mb, vram_proc_max_mb, vram_budget_exceeded_pct, vram_adapter_max_mb, avg_cpu_temp, max_cpu_temp, avg_gpu_temp, max_gpu_temp, max_gpu_hotspot, avg_gpu_load, avg_cpu_load, avg_ram_mb, avg_gpu_power_w, throttle_pct, display_exclusive_ms, display_borderless_ms, display_windowed_ms, display_covers_ms, display_minimized_ms, display_nowindow_ms, display_changes, display_source, display_window_w, display_window_h, display_buffer_w, display_buffer_h, display_monitor_w, display_monitor_h, display_monitor_hz, game_vram_dedicated_avg_mb, game_vram_dedicated_median_mb, game_vram_dedicated_max_mb, game_vram_shared_max_mb, game_ram_private_avg_mb, game_ram_private_median_mb, game_ram_private_max_mb, game_ram_ws_max_mb, game_commit_max_mb, game_memory_processes, game_memory_source, sensor_stats_json FROM sessions";
|
||||
|
||||
public static Dictionary<string, object?> Parameters(SessionRow s)
|
||||
{
|
||||
@@ -29,10 +29,11 @@ internal static class SessionRowColumns
|
||||
Parameters2(d, s);
|
||||
Parameters3(d, s);
|
||||
Parameters4(d, s);
|
||||
Parameters5(d, s);
|
||||
return d;
|
||||
}
|
||||
|
||||
public static SessionRow Read(DbDataReader r) => Read4(Read3(Read2(Read1(Read0(r), r), r), r), r);
|
||||
public static SessionRow Read(DbDataReader r) => Read5(Read4(Read3(Read2(Read1(Read0(r), r), r), r), r), r);
|
||||
|
||||
|
||||
private static void Parameters0(Dictionary<string, object?> d, SessionRow s)
|
||||
@@ -332,6 +333,39 @@ internal static class SessionRowColumns
|
||||
DisplayMonitorHz = I(r, "display_monitor_hz"),
|
||||
};
|
||||
|
||||
// Schema 0018 (beta.12, D43): the game process's own memory and the sensor statistics.
|
||||
private static void Parameters5(Dictionary<string, object?> d, SessionRow s)
|
||||
{
|
||||
d["game_vram_dedicated_avg_mb"] = s.GameVramDedicatedAvgMb;
|
||||
d["game_vram_dedicated_median_mb"] = s.GameVramDedicatedMedianMb;
|
||||
d["game_vram_dedicated_max_mb"] = s.GameVramDedicatedMaxMb;
|
||||
d["game_vram_shared_max_mb"] = s.GameVramSharedMaxMb;
|
||||
d["game_ram_private_avg_mb"] = s.GameRamPrivateAvgMb;
|
||||
d["game_ram_private_median_mb"] = s.GameRamPrivateMedianMb;
|
||||
d["game_ram_private_max_mb"] = s.GameRamPrivateMaxMb;
|
||||
d["game_ram_ws_max_mb"] = s.GameRamWorkingSetMaxMb;
|
||||
d["game_commit_max_mb"] = s.GameCommitMaxMb;
|
||||
d["game_memory_processes"] = s.GameMemoryProcesses;
|
||||
d["game_memory_source"] = s.GameMemorySource;
|
||||
d["sensor_stats_json"] = s.SensorStatsJson;
|
||||
}
|
||||
|
||||
private static SessionRow Read5(SessionRow row, DbDataReader r) => row with
|
||||
{
|
||||
GameVramDedicatedAvgMb = D(r, "game_vram_dedicated_avg_mb"),
|
||||
GameVramDedicatedMedianMb = D(r, "game_vram_dedicated_median_mb"),
|
||||
GameVramDedicatedMaxMb = D(r, "game_vram_dedicated_max_mb"),
|
||||
GameVramSharedMaxMb = D(r, "game_vram_shared_max_mb"),
|
||||
GameRamPrivateAvgMb = D(r, "game_ram_private_avg_mb"),
|
||||
GameRamPrivateMedianMb = D(r, "game_ram_private_median_mb"),
|
||||
GameRamPrivateMaxMb = D(r, "game_ram_private_max_mb"),
|
||||
GameRamWorkingSetMaxMb = D(r, "game_ram_ws_max_mb"),
|
||||
GameCommitMaxMb = D(r, "game_commit_max_mb"),
|
||||
GameMemoryProcesses = I(r, "game_memory_processes"),
|
||||
GameMemorySource = S(r, "game_memory_source"),
|
||||
SensorStatsJson = S(r, "sensor_stats_json"),
|
||||
};
|
||||
|
||||
public static string ExitStatusText(ExitStatus status) => Vocabulary.ExitStatusText(status);
|
||||
|
||||
public static ExitStatus ParseExitStatus(string text) => text switch
|
||||
|
||||
@@ -28,4 +28,11 @@ internal enum PartialChunkType
|
||||
|
||||
/// <summary>N × <c>i64</c> QPC ticks at which the host touched the target.</summary>
|
||||
Touches = 7,
|
||||
|
||||
/// <summary>
|
||||
/// N × one telemetry sample in the wide form (beta.12): a 32-bit presence mask, so the game process's memory (D43)
|
||||
/// travels with the sensors. Written instead of <see cref="Sensors"/> from beta.12 on; <see cref="Sensors"/> is still
|
||||
/// read, so a beta.11 <c>.partial</c> recovers (without game memory, which it never had).
|
||||
/// </summary>
|
||||
SensorsWide = 8,
|
||||
}
|
||||
@@ -157,7 +157,8 @@ public static class PartialSessionFile
|
||||
{
|
||||
PartialChunkType.Records => Records(payload),
|
||||
PartialChunkType.Gaps => Int32s(payload, _gaps),
|
||||
PartialChunkType.Sensors => Sensors(payload),
|
||||
PartialChunkType.Sensors => Sensors(payload, wide: false),
|
||||
PartialChunkType.SensorsWide => Sensors(payload, wide: true),
|
||||
PartialChunkType.Tick => Tick(payload),
|
||||
PartialChunkType.Note => Note(payload),
|
||||
PartialChunkType.Touches => Int64s(payload, _touches),
|
||||
@@ -244,12 +245,12 @@ public static class PartialSessionFile
|
||||
return true;
|
||||
}
|
||||
|
||||
private bool Sensors(ReadOnlySpan<byte> payload)
|
||||
private bool Sensors(ReadOnlySpan<byte> payload, bool wide)
|
||||
{
|
||||
int at = 0;
|
||||
while (at < payload.Length)
|
||||
{
|
||||
int used = SensorSampleCodec.Read(payload[at..], out TelemetrySample sample);
|
||||
int used = SensorSampleCodec.Read(payload[at..], wide, out TelemetrySample sample);
|
||||
if (used == 0)
|
||||
{
|
||||
return false;
|
||||
@@ -351,7 +352,7 @@ public static class PartialSessionFile
|
||||
at += SensorSampleCodec.Write(payload.AsSpan(at), in s);
|
||||
}
|
||||
|
||||
Append(PartialChunkType.Sensors, payload);
|
||||
Append(PartialChunkType.SensorsWide, payload);
|
||||
}
|
||||
|
||||
public void AppendTick(PartialTick tick)
|
||||
|
||||
@@ -11,43 +11,55 @@ namespace FrameLedger.Infrastructure.Recording;
|
||||
/// presence mask and only the fields that carry a value — null stays null across the round trip, which
|
||||
/// is the whole point (N/A is never 0).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Two forms. The NARROW one (chunk type <c>Sensors</c>, written until beta.11) has a 16-bit mask over 15 fields. The WIDE
|
||||
/// one (chunk type <c>SensorsWide</c>, written from beta.12) has a 32-bit mask over the same 15 fields plus the game
|
||||
/// process's memory (D43): five MiB figures, the process count and the sources. Both are read; only the wide one is
|
||||
/// written.
|
||||
/// </remarks>
|
||||
internal static class SensorSampleCodec
|
||||
{
|
||||
// 12 GPU fields + 3 system fields (2026-09-21) in one 16-bit mask. A .partial written before that date has bits
|
||||
// 12 GPU fields + 3 system fields (2026-09-21) in the narrow 16-bit mask. A .partial written before that date has bits
|
||||
// 12..14 clear and reads back with an empty SystemReading, which is what it recorded.
|
||||
private const int _fieldCount = 15;
|
||||
private const int _fixedBytes = 8 + 8 + 1 + 2;
|
||||
private const int _narrowFields = 15;
|
||||
|
||||
public static int SizeOf(in TelemetrySample sample) => _fixedBytes + 8 * PresentCount(in sample);
|
||||
// + 5 game-memory figures, the process count and the sources (beta.12, D43) in the wide 32-bit mask.
|
||||
private const int _wideFields = 22;
|
||||
private const int _narrowFixedBytes = 8 + 8 + 1 + 2;
|
||||
private const int _wideFixedBytes = 8 + 8 + 1 + 4;
|
||||
|
||||
public static int SizeOf(in TelemetrySample sample) => _wideFixedBytes + 8 * Fields(in sample).Count(static f => f is not null);
|
||||
|
||||
/// <summary>Writes the wide form; returns the bytes written.</summary>
|
||||
public static int Write(Span<byte> into, in TelemetrySample sample)
|
||||
{
|
||||
GpuSample s = sample.Sample;
|
||||
BinaryPrimitives.WriteInt64LittleEndian(into, sample.QpcTicks);
|
||||
BinaryPrimitives.WriteInt64LittleEndian(into[8..], s.TakenAt.ToUnixTimeMilliseconds());
|
||||
into[16] = (byte)s.Layer;
|
||||
ushort mask = 0;
|
||||
int at = _fixedBytes;
|
||||
uint mask = 0;
|
||||
int at = _wideFixedBytes;
|
||||
double?[] fields = Fields(in sample);
|
||||
for (int i = 0; i < _fieldCount; i++)
|
||||
for (int i = 0; i < _wideFields; i++)
|
||||
{
|
||||
if (fields[i] is { } v)
|
||||
{
|
||||
mask |= (ushort)(1 << i);
|
||||
mask |= 1u << i;
|
||||
BinaryPrimitives.WriteDoubleLittleEndian(into[at..], v);
|
||||
at += 8;
|
||||
}
|
||||
}
|
||||
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(into[17..], mask);
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(into[17..], mask);
|
||||
return at;
|
||||
}
|
||||
|
||||
/// <summary>Reads one sample; returns the bytes consumed, or 0 when the span is too short.</summary>
|
||||
public static int Read(ReadOnlySpan<byte> from, out TelemetrySample sample)
|
||||
/// <summary>Reads one sample in either form; returns the bytes consumed, or 0 when the span is too short.</summary>
|
||||
public static int Read(ReadOnlySpan<byte> from, bool wide, out TelemetrySample sample)
|
||||
{
|
||||
sample = default;
|
||||
if (from.Length < _fixedBytes)
|
||||
int fixedBytes = wide ? _wideFixedBytes : _narrowFixedBytes;
|
||||
if (from.Length < fixedBytes)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
@@ -55,18 +67,19 @@ internal static class SensorSampleCodec
|
||||
long qpc = BinaryPrimitives.ReadInt64LittleEndian(from);
|
||||
long takenAt = BinaryPrimitives.ReadInt64LittleEndian(from[8..]);
|
||||
var layer = (TelemetryLayer)from[16];
|
||||
ushort mask = BinaryPrimitives.ReadUInt16LittleEndian(from[17..]);
|
||||
uint mask = wide ? BinaryPrimitives.ReadUInt32LittleEndian(from[17..]) : BinaryPrimitives.ReadUInt16LittleEndian(from[17..]);
|
||||
int count = wide ? _wideFields : _narrowFields;
|
||||
int present = System.Numerics.BitOperations.PopCount(mask);
|
||||
if (from.Length < _fixedBytes + 8 * present)
|
||||
if (from.Length < fixedBytes + 8 * present)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
var fields = new double?[_fieldCount];
|
||||
int at = _fixedBytes;
|
||||
for (int i = 0; i < _fieldCount; i++)
|
||||
var fields = new double?[_wideFields];
|
||||
int at = fixedBytes;
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
if ((mask & (1 << i)) != 0)
|
||||
if ((mask & (1u << i)) != 0)
|
||||
{
|
||||
fields[i] = BinaryPrimitives.ReadDoubleLittleEndian(from[at..]);
|
||||
at += 8;
|
||||
@@ -89,20 +102,28 @@ internal static class SensorSampleCodec
|
||||
ThrottleReasons = fields[9] is { } t ? (uint)t : null,
|
||||
PcieGen = fields[10] is { } g ? (int)g : null,
|
||||
PcieWidth = fields[11] is { } w ? (int)w : null,
|
||||
}, new SystemReading(fields[12], fields[13], fields[14]));
|
||||
}, new SystemReading(fields[12], fields[13], fields[14]), new ProcessReading(
|
||||
VramDedicatedMb: fields[15],
|
||||
VramSharedMb: fields[16],
|
||||
RamPrivateMb: fields[17],
|
||||
RamWorkingSetMb: fields[18],
|
||||
CommitMb: fields[19],
|
||||
Processes: fields[20] is { } n ? (int)n : 0,
|
||||
Sources: fields[21] is { } src ? (ProcessReadingSources)(int)src : ProcessReadingSources.None));
|
||||
return at;
|
||||
}
|
||||
|
||||
private static int PresentCount(in TelemetrySample sample) => Fields(in sample).Count(static f => f is not null);
|
||||
|
||||
private static double?[] Fields(in TelemetrySample sample)
|
||||
{
|
||||
GpuSample s = sample.Sample;
|
||||
ProcessReading game = sample.Game;
|
||||
return
|
||||
[
|
||||
s.TempCoreC, s.TempHotspotC, s.TempMemoryC, s.LoadPct, s.VramAdapterMb, s.CoreClockMhz, s.MemClockMhz,
|
||||
s.PowerW, s.FanRpm, s.ThrottleReasons, s.PcieGen, s.PcieWidth,
|
||||
sample.System.CpuLoadPct, sample.System.RamUsedMb, sample.System.CpuTempC,
|
||||
game.VramDedicatedMb, game.VramSharedMb, game.RamPrivateMb, game.RamWorkingSetMb, game.CommitMb,
|
||||
game.IsEmpty ? null : game.Processes, game.IsEmpty ? null : (int)game.Sources,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
|
||||
|
||||
using FrameLedger.Application.Telemetry;
|
||||
using FrameLedger.Infrastructure.Capture;
|
||||
|
||||
namespace FrameLedger.Infrastructure.Telemetry;
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="IGameMemorySource"/> over <c>FrameLedger.ProcessStats.dll</c> (beta.12, owner decision D43): the game
|
||||
/// process's dedicated and shared GPU memory from the <c>GPU Process Memory</c> counters, and its working sets and commit
|
||||
/// from <c>GetProcessMemoryInfo</c> — read from outside the game, on the telemetry thread, once per tick.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// <b>What it may open is decided upstream.</b> A pinned target (<see cref="GameProcess.Pinned"/>) is read through the
|
||||
/// session's own handle (<see cref="IHeldProcessHandle"/>) — nothing new is opened. An unpinned Tier-2 hold's processes
|
||||
/// are each opened for the read with <c>PROCESS_QUERY_LIMITED_INFORMATION</c> and closed after it, and a process whose
|
||||
/// creation time is not the watcher's (a reused pid) is left out entirely — both halves, since the counters name a pid,
|
||||
/// not a process. A process that refuses even that right is left out too: an unverifiable pid is not read at all.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <b>Sums.</b> The video half sums every counter instance naming the pid (each adapter, each physical index); an unpinned
|
||||
/// hold sums its processes, and the reading says how many (<see cref="ProcessReading.Processes"/>).
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Single-threaded by contract: <see cref="Follow"/> publishes a reference from the capture loop, and only the telemetry
|
||||
/// thread calls <see cref="TryRead"/>, which owns the reader handle.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public sealed class GameMemoryReader : IGameMemorySource
|
||||
{
|
||||
/// <summary>How many reads to wait before trying again to open the reader after a failure (the DLL absent, memory exhausted).</summary>
|
||||
public const int ReopenEvery = 30;
|
||||
|
||||
private const double _mib = 1024.0 * 1024.0;
|
||||
|
||||
// FL_PS_FIELD_* and FL_PS_RAM_* (fl_process_stats.h).
|
||||
private const uint _fieldWorkingSet = 0x01;
|
||||
private const uint _fieldPrivateWorkingSet = 0x02;
|
||||
private const uint _fieldCommit = 0x04;
|
||||
private const uint _fieldGpuDedicated = 0x08;
|
||||
private const uint _fieldGpuShared = 0x10;
|
||||
private const int _ramOk = 0;
|
||||
|
||||
private readonly IProcessStats _stats;
|
||||
private GameProcess _target = GameProcess.None;
|
||||
private IntPtr _reader;
|
||||
private int _sinceFailedOpen;
|
||||
private bool _disposed;
|
||||
|
||||
public GameMemoryReader(IProcessStats stats)
|
||||
{
|
||||
_stats = stats ?? throw new ArgumentNullException(nameof(stats));
|
||||
}
|
||||
|
||||
public void Follow(GameProcess target)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(target);
|
||||
Volatile.Write(ref _target, target);
|
||||
}
|
||||
|
||||
public bool TryRead(out ProcessReading reading)
|
||||
{
|
||||
reading = default;
|
||||
GameProcess target = Volatile.Read(ref _target);
|
||||
if (_disposed || target.IsNone || !EnsureReader())
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// A failed collection costs this tick's video half; the system half is still read.
|
||||
_ = _stats.Collect(_reader);
|
||||
reading = target.Pid is int pid ? ReadPinned(pid, target.PinnedBy) : ReadUnpinned(target.Processes);
|
||||
return !reading.IsEmpty;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_disposed = true;
|
||||
_stats.Close(_reader);
|
||||
_reader = IntPtr.Zero;
|
||||
}
|
||||
|
||||
private bool EnsureReader()
|
||||
{
|
||||
if (_reader != IntPtr.Zero)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if (_sinceFailedOpen > 0 && _sinceFailedOpen++ < ReopenEvery)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
_reader = _stats.Open();
|
||||
_sinceFailedOpen = _reader == IntPtr.Zero ? 1 : 0;
|
||||
return _reader != IntPtr.Zero;
|
||||
}
|
||||
|
||||
private ProcessReading ReadPinned(int pid, Application.Capture.ITargetLiveness? pinnedBy)
|
||||
{
|
||||
var sample = default(ProcessStatsSample);
|
||||
ProcessReadingSources through;
|
||||
try
|
||||
{
|
||||
int status;
|
||||
if (pinnedBy is IHeldProcessHandle held)
|
||||
{
|
||||
status = _stats.Read(_reader, (uint)pid, 0, held.ProcessHandle, ref sample);
|
||||
through = ProcessReadingSources.HeldHandle;
|
||||
}
|
||||
else
|
||||
{
|
||||
status = _stats.Read(_reader, (uint)pid, 0, null, ref sample);
|
||||
through = ProcessReadingSources.TransientHandle;
|
||||
}
|
||||
|
||||
if (status != 0)
|
||||
{
|
||||
return default;
|
||||
}
|
||||
}
|
||||
catch (ObjectDisposedException)
|
||||
{
|
||||
// The pin was released between the loop's Follow(None) and this read: nothing to say about a closed process.
|
||||
return default;
|
||||
}
|
||||
|
||||
return ToReading(sample, through);
|
||||
}
|
||||
|
||||
private ProcessReading ReadUnpinned(IReadOnlyList<GameProcessId> processes)
|
||||
{
|
||||
double? dedicated = null, shared = null, privateWs = null, workingSet = null, commit = null;
|
||||
ProcessReadingSources sources = ProcessReadingSources.None;
|
||||
int counted = 0;
|
||||
foreach (GameProcessId process in processes)
|
||||
{
|
||||
var sample = default(ProcessStatsSample);
|
||||
ulong created = (ulong)process.StartedAt.ToFileTime();
|
||||
if (_stats.Read(_reader, (uint)process.Pid, created, null, ref sample) != 0 || sample.RamStatus != _ramOk)
|
||||
{
|
||||
continue; // reused, refused or gone: an unverifiable pid is read for neither half
|
||||
}
|
||||
|
||||
ProcessReading one = ToReading(sample, ProcessReadingSources.TransientHandle);
|
||||
dedicated = Add(dedicated, one.VramDedicatedMb);
|
||||
shared = Add(shared, one.VramSharedMb);
|
||||
privateWs = Add(privateWs, one.RamPrivateMb);
|
||||
workingSet = Add(workingSet, one.RamWorkingSetMb);
|
||||
commit = Add(commit, one.CommitMb);
|
||||
sources |= one.Sources;
|
||||
counted++;
|
||||
}
|
||||
|
||||
return counted == 0 ? default : new ProcessReading(dedicated, shared, privateWs, workingSet, commit, counted, sources);
|
||||
}
|
||||
|
||||
private static ProcessReading ToReading(ProcessStatsSample s, ProcessReadingSources through)
|
||||
{
|
||||
uint present = s.Present;
|
||||
ProcessReadingSources sources = through;
|
||||
if (Has(present, _fieldGpuDedicated))
|
||||
{
|
||||
sources |= ProcessReadingSources.Counters;
|
||||
}
|
||||
|
||||
if (Has(present, _fieldPrivateWorkingSet))
|
||||
{
|
||||
sources |= ProcessReadingSources.PrivateWorkingSetRead;
|
||||
}
|
||||
else if (Has(present, _fieldWorkingSet))
|
||||
{
|
||||
sources |= ProcessReadingSources.WorkingSetReadOnly;
|
||||
}
|
||||
|
||||
return new ProcessReading(
|
||||
VramDedicatedMb: Has(present, _fieldGpuDedicated) ? s.GpuDedicatedBytes / _mib : null,
|
||||
VramSharedMb: Has(present, _fieldGpuShared) ? s.GpuSharedBytes / _mib : null,
|
||||
RamPrivateMb: Has(present, _fieldPrivateWorkingSet) ? s.PrivateWorkingSetBytes / _mib : null,
|
||||
RamWorkingSetMb: Has(present, _fieldWorkingSet) ? s.WorkingSetBytes / _mib : null,
|
||||
CommitMb: Has(present, _fieldCommit) ? s.CommitBytes / _mib : null,
|
||||
Processes: 1,
|
||||
Sources: sources);
|
||||
}
|
||||
|
||||
private static bool Has(uint present, uint field) => (present & field) != 0;
|
||||
|
||||
private static double? Add(double? sum, double? value) => value is null ? sum : (sum ?? 0) + value.Value;
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
|
||||
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace FrameLedger.Infrastructure.Telemetry;
|
||||
|
||||
/// <summary>
|
||||
/// <c>FrameLedger.ProcessStats.dll</c>'s four calls (beta.12, D43), behind a seam so <see cref="GameMemoryReader"/> can be
|
||||
/// tested without the DLL. <see cref="NativeProcessStats"/> is the real one.
|
||||
/// </summary>
|
||||
public interface IProcessStats
|
||||
{
|
||||
/// <summary>A reader (the PDH query); <see cref="IntPtr.Zero"/> when the DLL is absent or memory is exhausted.</summary>
|
||||
IntPtr Open();
|
||||
|
||||
/// <summary>One counter collection; 0, or the PDH status that refused it.</summary>
|
||||
int Collect(IntPtr reader);
|
||||
|
||||
/// <summary>
|
||||
/// <c>FlPsRead</c>: the video half from the latest collection, the system half through <paramref name="process"/> when
|
||||
/// given (a handle the caller holds), else through a handle the DLL opens with <c>PROCESS_QUERY_LIMITED_INFORMATION</c>
|
||||
/// and closes. <paramref name="creationTime"/> is a FILETIME (0 = do not check).
|
||||
/// </summary>
|
||||
int Read(IntPtr reader, uint pid, ulong creationTime, SafeHandle? process, ref ProcessStatsSample sample);
|
||||
|
||||
void Close(IntPtr reader);
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
|
||||
|
||||
using System.Runtime.InteropServices;
|
||||
using FrameLedger.Infrastructure.Native;
|
||||
|
||||
namespace FrameLedger.Infrastructure.Telemetry;
|
||||
|
||||
/// <summary>
|
||||
/// <c>FrameLedger.ProcessStats.dll</c> behind <see cref="IProcessStats"/> (beta.12, owner decision D43): the third P/Invoke
|
||||
/// facade after <c>NativeAntiCheatGuard</c> and <c>NativeNvapiBridge</c>, loaded the same way — by absolute path from beside
|
||||
/// this assembly, never from a search path.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// <b>Absent is not a fault.</b> A build without the native tree has no DLL beside the binary: <see cref="Open"/> answers
|
||||
/// <see cref="IntPtr.Zero"/> and every game-memory field of every session reads N/A, the way a missing telemetry layer
|
||||
/// does. The guard's absence is a safety hole and throws; this one's is a missing measurement and reports itself.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <b>Never loaded into a game.</b> The Agent loads it into its own process. What it reads about a game — the
|
||||
/// <c>GPU Process Memory</c> counters and <c>GetProcessMemoryInfo</c> — is the kernel's accounting about the process,
|
||||
/// never the process's memory (CLAUDE.md rule 4).
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public sealed class NativeProcessStats : IProcessStats
|
||||
{
|
||||
/// <summary><c>FL_PS_ABI_VERSION</c>, what this mirror was written against.</summary>
|
||||
public const uint AbiVersion = 1;
|
||||
|
||||
/// <summary>What <see cref="Read"/> answers when the DLL is not beside this assembly at all.</summary>
|
||||
public const int Unavailable = -1999;
|
||||
|
||||
private const string _dll = "FrameLedger.ProcessStats.dll";
|
||||
|
||||
static NativeProcessStats()
|
||||
{
|
||||
// Optional, like the NVAPI bridge: absent is a zero handle, a DllNotFoundException under the System32-only
|
||||
// default search, and N/A in every game-memory field -- never a search of anything else.
|
||||
BesideThisAssembly.Claim(_dll, required: false);
|
||||
}
|
||||
|
||||
/// <summary>Whether the DLL is beside this assembly, without loading it.</summary>
|
||||
public static bool IsPresent => File.Exists(BesideThisAssembly.PathOf(_dll));
|
||||
|
||||
/// <summary>The DLL's ABI version, or null when it is absent.</summary>
|
||||
public static uint? LoadedAbiVersion => Guard(static () => (uint?)FlPsAbiVersion(), null);
|
||||
|
||||
/// <summary>The DLL's <c>sizeof(FlPsSample)</c>, or null when it is absent.</summary>
|
||||
public static uint? LoadedSampleSize => Guard(static () => (uint?)FlPsSampleSize(), null);
|
||||
|
||||
/// <summary>The DLL's build id, or null when it is absent.</summary>
|
||||
public static string? LoadedBuildId => Guard(static () => Marshal.PtrToStringAnsi(FlPsBuildId()), null);
|
||||
|
||||
public IntPtr Open() => IsPresent ? Guard(FlPsOpen, IntPtr.Zero) : IntPtr.Zero;
|
||||
|
||||
public int Collect(IntPtr reader) => reader == IntPtr.Zero ? Unavailable : Guard(() => FlPsCollect(reader), Unavailable);
|
||||
|
||||
public int Read(IntPtr reader, uint pid, ulong creationTime, SafeHandle? process, ref ProcessStatsSample sample)
|
||||
{
|
||||
if (reader == IntPtr.Zero)
|
||||
{
|
||||
return Unavailable;
|
||||
}
|
||||
|
||||
sample.Size = (uint)Marshal.SizeOf<ProcessStatsSample>();
|
||||
try
|
||||
{
|
||||
// A held handle goes through the marshaller, which add-refs it for the call: a pin released mid-read throws
|
||||
// ObjectDisposedException here rather than handing the DLL a closed handle.
|
||||
return process is null
|
||||
? FlPsRead(reader, pid, creationTime, IntPtr.Zero, ref sample)
|
||||
: FlPsReadHeld(reader, pid, creationTime, process, ref sample);
|
||||
}
|
||||
catch (Exception ex) when (ex is DllNotFoundException or EntryPointNotFoundException or BadImageFormatException)
|
||||
{
|
||||
return Unavailable;
|
||||
}
|
||||
}
|
||||
|
||||
public void Close(IntPtr reader)
|
||||
{
|
||||
if (reader != IntPtr.Zero)
|
||||
{
|
||||
Guard(() =>
|
||||
{
|
||||
FlPsClose(reader);
|
||||
return 0;
|
||||
}, 0);
|
||||
}
|
||||
}
|
||||
|
||||
private static T Guard<T>(Func<T> call, T absent)
|
||||
{
|
||||
try
|
||||
{
|
||||
return call();
|
||||
}
|
||||
catch (Exception ex) when (ex is DllNotFoundException or EntryPointNotFoundException or BadImageFormatException)
|
||||
{
|
||||
return absent;
|
||||
}
|
||||
}
|
||||
|
||||
[DefaultDllImportSearchPaths(DllImportSearchPath.System32)]
|
||||
[DllImport(_dll, CallingConvention = CallingConvention.Cdecl)]
|
||||
private static extern IntPtr FlPsOpen();
|
||||
|
||||
[DefaultDllImportSearchPaths(DllImportSearchPath.System32)]
|
||||
[DllImport(_dll, CallingConvention = CallingConvention.Cdecl)]
|
||||
private static extern void FlPsClose(IntPtr reader);
|
||||
|
||||
[DefaultDllImportSearchPaths(DllImportSearchPath.System32)]
|
||||
[DllImport(_dll, CallingConvention = CallingConvention.Cdecl)]
|
||||
private static extern int FlPsCollect(IntPtr reader);
|
||||
|
||||
[DefaultDllImportSearchPaths(DllImportSearchPath.System32)]
|
||||
[DllImport(_dll, CallingConvention = CallingConvention.Cdecl)]
|
||||
private static extern int FlPsRead(IntPtr reader, uint pid, ulong creationTime, IntPtr process, ref ProcessStatsSample sample);
|
||||
|
||||
[DefaultDllImportSearchPaths(DllImportSearchPath.System32)]
|
||||
[DllImport(_dll, EntryPoint = "FlPsRead", CallingConvention = CallingConvention.Cdecl)]
|
||||
private static extern int FlPsReadHeld(IntPtr reader, uint pid, ulong creationTime, SafeHandle process, ref ProcessStatsSample sample);
|
||||
|
||||
[DefaultDllImportSearchPaths(DllImportSearchPath.System32)]
|
||||
[DllImport(_dll, CallingConvention = CallingConvention.Cdecl)]
|
||||
private static extern uint FlPsAbiVersion();
|
||||
|
||||
[DefaultDllImportSearchPaths(DllImportSearchPath.System32)]
|
||||
[DllImport(_dll, CallingConvention = CallingConvention.Cdecl)]
|
||||
private static extern uint FlPsSampleSize();
|
||||
|
||||
[DefaultDllImportSearchPaths(DllImportSearchPath.System32)]
|
||||
[DllImport(_dll, CallingConvention = CallingConvention.Cdecl)]
|
||||
private static extern IntPtr FlPsBuildId();
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
|
||||
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace FrameLedger.Infrastructure.Telemetry;
|
||||
|
||||
/// <summary>
|
||||
/// Mirror of <c>FlPsSample</c> (<c>fl_process_stats.h</c>, beta.12, D43). <see cref="Size"/> is set by the caller and checked
|
||||
/// by the DLL, so a drift between the two is refused (<c>FL_PS_BAD_SIZE</c>) rather than read; <c>ProcessStatsMirrorTests</c>
|
||||
/// compares <c>Marshal.SizeOf</c> against <c>FlPsSampleSize()</c> as well.
|
||||
/// </summary>
|
||||
[System.Diagnostics.CodeAnalysis.SuppressMessage("Performance", "CA1815:Override equals and operator equals on value types", Justification = "P/Invoke mirror of a native struct; never compared.")]
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public struct ProcessStatsSample
|
||||
{
|
||||
public uint Size;
|
||||
|
||||
public uint Present;
|
||||
|
||||
public ulong PrivateWorkingSetBytes;
|
||||
|
||||
public ulong WorkingSetBytes;
|
||||
|
||||
public ulong PeakWorkingSetBytes;
|
||||
|
||||
public ulong CommitBytes;
|
||||
|
||||
public ulong GpuDedicatedBytes;
|
||||
|
||||
public ulong GpuSharedBytes;
|
||||
|
||||
public uint GpuInstances;
|
||||
|
||||
public int RamStatus;
|
||||
|
||||
public uint RamError;
|
||||
|
||||
public int GpuStatus;
|
||||
|
||||
public uint PdhStatus;
|
||||
|
||||
public uint Reserved0;
|
||||
|
||||
public uint Reserved1;
|
||||
|
||||
public uint Reserved2;
|
||||
}
|
||||
@@ -33,6 +33,7 @@ public sealed class TelemetryPoller : ITelemetryPoller
|
||||
{
|
||||
private readonly IGpuTelemetrySource _source;
|
||||
private readonly ISystemTelemetrySource? _system;
|
||||
private readonly IGameMemorySource? _game;
|
||||
private readonly TelemetryPollerOptions _options;
|
||||
private readonly TimeProvider _clock;
|
||||
private readonly ConcurrentQueue<TelemetrySample> _queue = new();
|
||||
@@ -54,10 +55,13 @@ public sealed class TelemetryPoller : ITelemetryPoller
|
||||
/// builds the layers for one session and hands them over. False (the default) when the container owns them.
|
||||
/// </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>
|
||||
public TelemetryPoller(IGpuTelemetrySource source, TelemetryPollerOptions options, TimeProvider clock, bool ownsSource = false, ISystemTelemetrySource? system = null)
|
||||
/// <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>
|
||||
public TelemetryPoller(IGpuTelemetrySource source, TelemetryPollerOptions options, TimeProvider clock, bool ownsSource = false,
|
||||
ISystemTelemetrySource? system = null, IGameMemorySource? game = null)
|
||||
{
|
||||
_source = source ?? throw new ArgumentNullException(nameof(source));
|
||||
_system = system;
|
||||
_game = game;
|
||||
_ownsSource = ownsSource;
|
||||
_options = options ?? throw new ArgumentNullException(nameof(options));
|
||||
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
|
||||
@@ -110,14 +114,16 @@ public sealed class TelemetryPoller : ITelemetryPoller
|
||||
bool gpu = _source.TryRead(out GpuSample? sample);
|
||||
SystemReading system = default;
|
||||
bool machine = _system is not null && _system.TryRead(out system);
|
||||
if (!gpu && !machine)
|
||||
ProcessReading game = default;
|
||||
bool measured = _game is not null && _game.TryRead(out game);
|
||||
if (!gpu && !machine && !measured)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// A tick only the machine answered still carries its CPU and memory: the placeholder names no layer and no field.
|
||||
// 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));
|
||||
_queue.Enqueue(new TelemetrySample(_clock.GetTimestamp(), sample, system, game));
|
||||
if (Interlocked.Increment(ref _queued) > _options.QueueCapacity && _queue.TryDequeue(out _))
|
||||
{
|
||||
Interlocked.Decrement(ref _queued);
|
||||
@@ -125,6 +131,13 @@ public sealed class TelemetryPoller : ITelemetryPoller
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The game process whose memory the next ticks read (beta.12, D43); ignored without a game source.</summary>
|
||||
public void Follow(GameProcess target)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(target);
|
||||
_game?.Follow(target);
|
||||
}
|
||||
|
||||
public int Drain(ICollection<TelemetrySample> into)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(into);
|
||||
@@ -154,6 +167,7 @@ public sealed class TelemetryPoller : ITelemetryPoller
|
||||
{
|
||||
_source.Dispose();
|
||||
_system?.Dispose();
|
||||
_game?.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -190,7 +190,8 @@ public sealed record SessionStartedEvent(Guid SessionGuid, long GameId, string?
|
||||
/// telemetry. Never a frame-derived value — there is none (CLAUDE.md rule 6 has nothing to show, and shows nothing).
|
||||
/// Its own type rather than <see cref="SessionProgressEvent"/>, whose required fields would put measured-looking zeros on the wire.
|
||||
/// </summary>
|
||||
public sealed record SessionHeldEvent(Guid SessionGuid, double ElapsedS, double? GpuTempC = null, double? CpuTempC = null, double? GpuLoadPct = null, double? CpuLoadPct = null);
|
||||
public sealed record SessionHeldEvent(Guid SessionGuid, double ElapsedS, double? GpuTempC = null, double? CpuTempC = null, double? GpuLoadPct = null, double? CpuLoadPct = null,
|
||||
double? GameVramDedicatedMb = null, double? GameRamPrivateMb = null);
|
||||
|
||||
/// <summary>
|
||||
/// 1 Hz while a hooked session runs and a client is connected (<c>04_CAPTURE</c> §Live progress). A 5 s rolling
|
||||
@@ -273,6 +274,12 @@ public sealed record SessionProgressEvent
|
||||
|
||||
public int? VramProcMb { get; init; }
|
||||
|
||||
/// <summary>The game process's dedicated GPU memory, MiB, from the newest telemetry tick (beta.12, D43); read from outside the game.</summary>
|
||||
public double? GameVramDedicatedMb { get; init; }
|
||||
|
||||
/// <summary>The game process's private working set, MiB, from the newest telemetry tick (beta.12, D43).</summary>
|
||||
public double? GameRamPrivateMb { get; init; }
|
||||
|
||||
public int? LatencyUs { get; init; }
|
||||
}
|
||||
|
||||
|
||||
@@ -197,6 +197,7 @@ add_subdirectory(FrameLedger.Shm)
|
||||
add_subdirectory(FrameLedger.Overlay)
|
||||
add_subdirectory(FrameLedger.Injector)
|
||||
add_subdirectory(FrameLedger.NvapiBridge)
|
||||
add_subdirectory(FrameLedger.ProcessStats)
|
||||
add_subdirectory(FrameLedger.VkLayer)
|
||||
|
||||
# enable_testing() must be called from the TOP-LEVEL CMakeLists, not from a
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
# FrameLedger.ProcessStats — the C ABI the managed Agent reads a game process's own memory through
|
||||
# (beta.12, owner decision D43; docs/18_GPU_VENDOR_APIS.md §L1, docs/03_METRICS.md §Per-process memory).
|
||||
#
|
||||
# A SHARED library, because P/Invoke needs one and CLAUDE.md puts the native boundary in Infrastructure: the third
|
||||
# facade after the guard's and the NVAPI bridge's. Read-only by construction — the video half is the documented
|
||||
# `GPU Process Memory` performance counters (no handle to the game), the system half GetProcessMemoryInfo through a
|
||||
# PROCESS_QUERY_LIMITED_INFORMATION handle; neither reads the game's memory.
|
||||
#
|
||||
# NEVER LOADED INTO A GAME. The Agent loads it beside its own binary by absolute path; nothing injects it, and its
|
||||
# name carries none of the words the guard's §S18 heuristic scans a launcher's ancestors for.
|
||||
#
|
||||
# fl_native_flags only, NOT fl_hostile_env_flags: this runs in our own process. It ships, so
|
||||
# tools/versioninfo-check.ps1 covers it.
|
||||
add_library(FrameLedger.ProcessStats SHARED
|
||||
src/fl_process_stats.cpp
|
||||
)
|
||||
target_include_directories(FrameLedger.ProcessStats PUBLIC include)
|
||||
target_link_libraries(FrameLedger.ProcessStats PRIVATE FrameLedger.Shm fl_native_flags pdh)
|
||||
target_compile_definitions(FrameLedger.ProcessStats PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
|
||||
fl_add_version_resource(FrameLedger.ProcessStats "FrameLedger process memory statistics (read-only; loaded by the Agent, never into a game)")
|
||||
@@ -0,0 +1,103 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
|
||||
|
||||
// fl_process_stats.h — the C ABI the managed Agent reads A GAME PROCESS'S OWN MEMORY through (beta.12, owner
|
||||
// decision D43; docs/18_GPU_VENDOR_APIS.md §L1, docs/03_METRICS.md §Per-process memory).
|
||||
//
|
||||
// WHAT THIS IS. Two documented Windows sources, read from OUTSIDE the game:
|
||||
// - video memory: the performance counters `\GPU Process Memory(pid_<pid>_luid_<luid>_phys_<n>)\Dedicated Usage`
|
||||
// and `\Shared Usage` — the numbers Task Manager's Details tab shows as "Dedicated GPU memory" and "Shared GPU
|
||||
// memory". A counter query opens NO handle to the game at all.
|
||||
// - system memory: GetProcessMemoryInfo with PROCESS_MEMORY_COUNTERS_EX2 (its PrivateWorkingSetSize is Task
|
||||
// Manager's "Memory" column), falling back to PROCESS_MEMORY_COUNTERS_EX where the OS predates it. It needs a
|
||||
// handle with PROCESS_QUERY_LIMITED_INFORMATION and nothing more — the caller's held handle when it has one, else
|
||||
// one this call opens and closes before it returns.
|
||||
// Neither reads the game's memory: both are the kernel's bookkeeping ABOUT the process (CLAUDE.md rule 4 untouched).
|
||||
// D3DKMTQueryStatistics is deliberately not used: Microsoft documents it as "Reserved for system use".
|
||||
//
|
||||
// NEVER LOADED INTO A GAME. The Agent loads it beside its own binary by absolute path (the third facade after the
|
||||
// guard's and the NVAPI bridge's, Infrastructure.Native.BesideThisAssembly). Its name carries none of the words the
|
||||
// guard's §S18 heuristic scans for (guard / hook / inject / cheat / protect).
|
||||
//
|
||||
// VERSIONED STRUCTS, as fl_nvapi_bridge.h: the out-struct carries its own size, set by the caller and checked here.
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#ifdef FL_PS_BUILDING
|
||||
#define FL_PS_API __declspec(dllexport)
|
||||
#else
|
||||
#define FL_PS_API __declspec(dllimport)
|
||||
#endif
|
||||
|
||||
#define FL_PS_ABI_VERSION 1u
|
||||
|
||||
// Return codes. Zero is success; negatives are ours.
|
||||
#define FL_PS_OK 0
|
||||
#define FL_PS_BAD_SIZE (-1001)
|
||||
#define FL_PS_BAD_ARGUMENT (-1003)
|
||||
|
||||
// Which fields of FlPsSample carry a value. A clear bit is N/A, never 0 (03_METRICS §Sensor aggregates).
|
||||
#define FL_PS_FIELD_WORKING_SET 0x01u // workingSetBytes and peakWorkingSetBytes
|
||||
#define FL_PS_FIELD_PRIVATE_WS 0x02u // privateWorkingSetBytes (PROCESS_MEMORY_COUNTERS_EX2 only)
|
||||
#define FL_PS_FIELD_COMMIT 0x04u // commitBytes (PrivateUsage, the process's commit charge)
|
||||
#define FL_PS_FIELD_GPU_DEDICATED 0x08u // gpuDedicatedBytes
|
||||
#define FL_PS_FIELD_GPU_SHARED 0x10u // gpuSharedBytes
|
||||
|
||||
// Why the system-memory half is missing.
|
||||
#define FL_PS_RAM_OK 0
|
||||
#define FL_PS_RAM_OPEN_DENIED 1 // OpenProcess refused: gone, protected, another user's — ramError says which
|
||||
#define FL_PS_RAM_PID_REUSED 2 // the pid names a process created at another time: not the one asked about
|
||||
#define FL_PS_RAM_QUERY_FAILED 3 // GetProcessMemoryInfo refused both structure sizes
|
||||
|
||||
// Why the video-memory half is missing.
|
||||
#define FL_PS_GPU_OK 0
|
||||
#define FL_PS_GPU_NO_COUNTERS 1 // the GPU Process Memory counter set could not be opened on this machine
|
||||
#define FL_PS_GPU_NO_INSTANCE 2 // no counter instance names this pid (it has made no GPU allocation yet)
|
||||
#define FL_PS_GPU_NOT_COLLECTED 3 // FlPsCollect has not succeeded on this reader — pdhStatus says why
|
||||
|
||||
typedef struct FlPsSample {
|
||||
uint32_t size; // sizeof(FlPsSample), set by the caller
|
||||
uint32_t present; // FL_PS_FIELD_* bits
|
||||
uint64_t privateWorkingSetBytes;
|
||||
uint64_t workingSetBytes;
|
||||
uint64_t peakWorkingSetBytes;
|
||||
uint64_t commitBytes;
|
||||
uint64_t gpuDedicatedBytes; // summed over every instance naming the pid (every adapter, every physical index)
|
||||
uint64_t gpuSharedBytes;
|
||||
uint32_t gpuInstances; // how many counter instances were summed
|
||||
int32_t ramStatus; // FL_PS_RAM_*
|
||||
uint32_t ramError; // GetLastError behind ramStatus (0 on success)
|
||||
int32_t gpuStatus; // FL_PS_GPU_*
|
||||
uint32_t pdhStatus; // the PDH status behind gpuStatus (0 on success)
|
||||
uint32_t reserved[3];
|
||||
} FlPsSample;
|
||||
|
||||
// A reader: one PDH query over the two GPU Process Memory counters, plus the buffer their instance arrays are read
|
||||
// into. Null only when memory is exhausted; a machine without the counter set still gets a reader, whose GPU half
|
||||
// reports FL_PS_GPU_NO_COUNTERS. One reader per thread — the Agent has one per session's telemetry thread.
|
||||
FL_PS_API void* FlPsOpen(void);
|
||||
FL_PS_API void FlPsClose(void* reader);
|
||||
|
||||
// One counter collection; FlPsRead answers from the latest. Returns 0 or the PDH status that refused it.
|
||||
FL_PS_API int32_t FlPsCollect(void* reader);
|
||||
|
||||
// The memory of process `pid`: the video half from the reader's latest collection, the system half through
|
||||
// `process` when the caller holds a handle to it (PROCESS_QUERY_LIMITED_INFORMATION is enough), else through a handle
|
||||
// opened here with exactly that right and closed before returning. `creationTime` is the process's creation time as a
|
||||
// FILETIME value (0 = do not check); a different one means the pid was reused, and the system half is refused rather
|
||||
// than read off a stranger. Each half is independent: a refused one leaves its bits clear and says why.
|
||||
FL_PS_API int32_t FlPsRead(void* reader, uint32_t pid, uint64_t creationTime, void* process, FlPsSample* out);
|
||||
|
||||
// What the managed mirror test compares against, and what a build id check reads.
|
||||
FL_PS_API uint32_t FlPsAbiVersion(void);
|
||||
FL_PS_API uint32_t FlPsSampleSize(void);
|
||||
FL_PS_API const char* FlPsBuildId(void);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,335 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
|
||||
|
||||
// fl_process_stats.cpp — see fl_process_stats.h.
|
||||
//
|
||||
// EVERY CALL HERE IS A QUERY ABOUT A PROCESS, NEVER A READ OF IT. The performance counters are the graphics kernel's
|
||||
// own per-process accounting, published system-wide; GetProcessMemoryInfo is the memory manager's counters for a
|
||||
// process handle that carries PROCESS_QUERY_LIMITED_INFORMATION and nothing else. No PROCESS_VM_READ, no
|
||||
// ReadProcessMemory, no module walk: what is in the game's memory is not this file's business (CLAUDE.md rule 4).
|
||||
//
|
||||
// It runs in the Agent's own process on a telemetry thread, so it may allocate — the counter arrays grow with the
|
||||
// number of processes using a GPU — but it uses the process heap rather than the STL, because the native targets build
|
||||
// without C++ exceptions (src/native/CMakeLists.txt strips /EHsc) and a throwing container has nowhere to throw to.
|
||||
#define FL_PS_BUILDING
|
||||
#include "fl_process_stats.h"
|
||||
|
||||
#include <windows.h>
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstring>
|
||||
#include <cwchar>
|
||||
#include <pdh.h>
|
||||
#include <pdhmsg.h>
|
||||
#include <psapi.h>
|
||||
|
||||
namespace {
|
||||
|
||||
// English names: the counter set is localised on a Japanese or Vietnamese Windows, and PdhAddEnglishCounterW is the
|
||||
// one call that does not care (the adapter-wide counter in PdhAdapterMemoryCounter.cs does the same).
|
||||
constexpr wchar_t kDedicatedPath[] = L"\\GPU Process Memory(*)\\Dedicated Usage";
|
||||
constexpr wchar_t kSharedPath[] = L"\\GPU Process Memory(*)\\Shared Usage";
|
||||
|
||||
// PROCESS_MEMORY_COUNTERS_EX2 as Microsoft documents it (psapi.h, "Windows 10 22H2 with the September 2023
|
||||
// cumulative update or Windows 11 22H2 with the September 2023 cumulative update"), declared here so the build does not
|
||||
// depend on the SDK's NTDDI guard around it. The asserts tie it to the structure it extends.
|
||||
struct ProcessMemoryCountersEx2 {
|
||||
DWORD cb;
|
||||
DWORD PageFaultCount;
|
||||
SIZE_T PeakWorkingSetSize;
|
||||
SIZE_T WorkingSetSize;
|
||||
SIZE_T QuotaPeakPagedPoolUsage;
|
||||
SIZE_T QuotaPagedPoolUsage;
|
||||
SIZE_T QuotaPeakNonPagedPoolUsage;
|
||||
SIZE_T QuotaNonPagedPoolUsage;
|
||||
SIZE_T PagefileUsage;
|
||||
SIZE_T PeakPagefileUsage;
|
||||
SIZE_T PrivateUsage;
|
||||
SIZE_T PrivateWorkingSetSize;
|
||||
ULONG64 SharedCommitUsage;
|
||||
};
|
||||
static_assert(offsetof(ProcessMemoryCountersEx2, PrivateUsage) == offsetof(PROCESS_MEMORY_COUNTERS_EX, PrivateUsage));
|
||||
static_assert(sizeof(ProcessMemoryCountersEx2) == sizeof(PROCESS_MEMORY_COUNTERS_EX) + 2 * sizeof(ULONG64));
|
||||
|
||||
// One instance array, read after each collection and kept until the next.
|
||||
struct InstanceArray {
|
||||
BYTE* buffer;
|
||||
DWORD capacity;
|
||||
DWORD count;
|
||||
};
|
||||
|
||||
struct Reader {
|
||||
PDH_HQUERY query;
|
||||
PDH_HCOUNTER dedicated;
|
||||
PDH_HCOUNTER shared; // null when only the shared counter could not be added
|
||||
PDH_STATUS openStatus; // nonzero: the query or the dedicated counter could not be set up
|
||||
PDH_STATUS collectStatus; // the last collection's status; PDH_NO_DATA before the first
|
||||
bool collected; // the arrays below describe the last collection
|
||||
InstanceArray dedicatedItems;
|
||||
InstanceArray sharedItems;
|
||||
};
|
||||
|
||||
void FreeArray(InstanceArray& a) {
|
||||
if (a.buffer != nullptr) {
|
||||
HeapFree(GetProcessHeap(), 0, a.buffer);
|
||||
}
|
||||
a = InstanceArray{};
|
||||
}
|
||||
|
||||
// PdhGetFormattedCounterArrayW into a buffer that grows to fit. Three tries: a process can start using the GPU between
|
||||
// the size query and the read, and PDH answers PDH_MORE_DATA again.
|
||||
PDH_STATUS FetchArray(PDH_HCOUNTER counter, InstanceArray& into) {
|
||||
into.count = 0;
|
||||
for (int attempt = 0; attempt < 3; ++attempt) {
|
||||
DWORD size = into.capacity;
|
||||
DWORD items = 0;
|
||||
PDH_STATUS s = PdhGetFormattedCounterArrayW(counter, PDH_FMT_LARGE | PDH_FMT_NOCAP100, &size, &items,
|
||||
reinterpret_cast<PPDH_FMT_COUNTERVALUE_ITEM_W>(into.buffer));
|
||||
if (s == ERROR_SUCCESS) {
|
||||
into.count = items;
|
||||
return s;
|
||||
}
|
||||
if (s != static_cast<PDH_STATUS>(PDH_MORE_DATA) || size <= into.capacity) {
|
||||
return s;
|
||||
}
|
||||
BYTE* grown = static_cast<BYTE*>(HeapAlloc(GetProcessHeap(), 0, size));
|
||||
if (grown == nullptr) {
|
||||
return static_cast<PDH_STATUS>(PDH_MEMORY_ALLOCATION_FAILURE);
|
||||
}
|
||||
FreeArray(into);
|
||||
into.buffer = grown;
|
||||
into.capacity = size;
|
||||
}
|
||||
return static_cast<PDH_STATUS>(PDH_MORE_DATA);
|
||||
}
|
||||
|
||||
// "pid_12345_luid_0x00000000_0x0000D1A3_phys_0" names process 12345. Anything else is not a process instance.
|
||||
bool InstancePid(const wchar_t* name, uint32_t* pid) {
|
||||
if (name == nullptr || std::wcsncmp(name, L"pid_", 4) != 0) {
|
||||
return false;
|
||||
}
|
||||
uint64_t value = 0;
|
||||
int digits = 0;
|
||||
const wchar_t* p = name + 4;
|
||||
while (*p >= L'0' && *p <= L'9') {
|
||||
value = value * 10 + static_cast<uint64_t>(*p - L'0');
|
||||
if (value > 0xFFFFFFFFull) {
|
||||
return false;
|
||||
}
|
||||
++p;
|
||||
++digits;
|
||||
}
|
||||
if (digits == 0 || *p != L'_') {
|
||||
return false;
|
||||
}
|
||||
*pid = static_cast<uint32_t>(value);
|
||||
return true;
|
||||
}
|
||||
|
||||
// The sum over every instance that names `pid`; false when none does.
|
||||
bool SumFor(const InstanceArray& a, uint32_t pid, uint64_t* bytes, uint32_t* instances) {
|
||||
*bytes = 0;
|
||||
*instances = 0;
|
||||
const auto* items = reinterpret_cast<const PDH_FMT_COUNTERVALUE_ITEM_W*>(a.buffer);
|
||||
for (DWORD i = 0; i < a.count; ++i) {
|
||||
uint32_t named = 0;
|
||||
if (!InstancePid(items[i].szName, &named) || named != pid) {
|
||||
continue;
|
||||
}
|
||||
const DWORD status = items[i].FmtValue.CStatus;
|
||||
if (status != PDH_CSTATUS_VALID_DATA && status != PDH_CSTATUS_NEW_DATA) {
|
||||
continue;
|
||||
}
|
||||
if (items[i].FmtValue.largeValue > 0) {
|
||||
*bytes += static_cast<uint64_t>(items[i].FmtValue.largeValue);
|
||||
}
|
||||
++*instances;
|
||||
}
|
||||
return *instances > 0;
|
||||
}
|
||||
|
||||
uint64_t FileTimeValue(const FILETIME& t) {
|
||||
return (static_cast<uint64_t>(t.dwHighDateTime) << 32) | t.dwLowDateTime;
|
||||
}
|
||||
|
||||
void ReadSystemMemory(uint32_t pid, uint64_t creationTime, HANDLE held, FlPsSample* out) {
|
||||
HANDLE process = held;
|
||||
if (process == nullptr) {
|
||||
// The least right that answers: the one the watcher's own snapshot uses on every process it lists.
|
||||
process = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid);
|
||||
if (process == nullptr) {
|
||||
out->ramStatus = FL_PS_RAM_OPEN_DENIED;
|
||||
out->ramError = GetLastError();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (creationTime != 0) {
|
||||
FILETIME created{}, exited{}, kernel{}, user{};
|
||||
if (!GetProcessTimes(process, &created, &exited, &kernel, &user) || FileTimeValue(created) != creationTime) {
|
||||
out->ramStatus = FL_PS_RAM_PID_REUSED;
|
||||
out->ramError = GetLastError();
|
||||
if (held == nullptr) {
|
||||
CloseHandle(process);
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
ProcessMemoryCountersEx2 ex2{};
|
||||
ex2.cb = sizeof(ex2);
|
||||
// A sentinel in the one field EX2 adds that we read: an OS that accepts the larger size but fills only the EX part
|
||||
// leaves it as written. One that cleared the buffer first is caught by the second test — a live process always has
|
||||
// some private working set, so zero beside a nonzero working set is not a reading. Either way it is N/A.
|
||||
constexpr SIZE_T kNotFilled = static_cast<SIZE_T>(-1);
|
||||
ex2.PrivateWorkingSetSize = kNotFilled;
|
||||
if (GetProcessMemoryInfo(process, reinterpret_cast<PROCESS_MEMORY_COUNTERS*>(&ex2), sizeof(ex2))) {
|
||||
out->workingSetBytes = ex2.WorkingSetSize;
|
||||
out->peakWorkingSetBytes = ex2.PeakWorkingSetSize;
|
||||
out->commitBytes = ex2.PrivateUsage;
|
||||
out->present |= FL_PS_FIELD_WORKING_SET | FL_PS_FIELD_COMMIT;
|
||||
if (ex2.PrivateWorkingSetSize != kNotFilled && (ex2.PrivateWorkingSetSize > 0 || ex2.WorkingSetSize == 0)) {
|
||||
out->privateWorkingSetBytes = ex2.PrivateWorkingSetSize;
|
||||
out->present |= FL_PS_FIELD_PRIVATE_WS;
|
||||
}
|
||||
} else {
|
||||
PROCESS_MEMORY_COUNTERS_EX ex{};
|
||||
ex.cb = sizeof(ex);
|
||||
if (GetProcessMemoryInfo(process, reinterpret_cast<PROCESS_MEMORY_COUNTERS*>(&ex), sizeof(ex))) {
|
||||
out->workingSetBytes = ex.WorkingSetSize;
|
||||
out->peakWorkingSetBytes = ex.PeakWorkingSetSize;
|
||||
out->commitBytes = ex.PrivateUsage;
|
||||
out->present |= FL_PS_FIELD_WORKING_SET | FL_PS_FIELD_COMMIT;
|
||||
} else {
|
||||
out->ramStatus = FL_PS_RAM_QUERY_FAILED;
|
||||
out->ramError = GetLastError();
|
||||
}
|
||||
}
|
||||
|
||||
if (held == nullptr) {
|
||||
CloseHandle(process);
|
||||
}
|
||||
}
|
||||
|
||||
void ReadVideoMemory(const Reader& r, uint32_t pid, FlPsSample* out) {
|
||||
if (r.openStatus != ERROR_SUCCESS) {
|
||||
out->gpuStatus = FL_PS_GPU_NO_COUNTERS;
|
||||
out->pdhStatus = static_cast<uint32_t>(r.openStatus);
|
||||
return;
|
||||
}
|
||||
if (!r.collected) {
|
||||
out->gpuStatus = FL_PS_GPU_NOT_COLLECTED;
|
||||
out->pdhStatus = static_cast<uint32_t>(r.collectStatus);
|
||||
return;
|
||||
}
|
||||
|
||||
uint64_t dedicated = 0;
|
||||
uint32_t instances = 0;
|
||||
if (!SumFor(r.dedicatedItems, pid, &dedicated, &instances)) {
|
||||
out->gpuStatus = FL_PS_GPU_NO_INSTANCE;
|
||||
return;
|
||||
}
|
||||
out->gpuDedicatedBytes = dedicated;
|
||||
out->gpuInstances = instances;
|
||||
out->present |= FL_PS_FIELD_GPU_DEDICATED;
|
||||
|
||||
uint64_t shared = 0;
|
||||
uint32_t sharedInstances = 0;
|
||||
if (r.shared != nullptr && SumFor(r.sharedItems, pid, &shared, &sharedInstances)) {
|
||||
out->gpuSharedBytes = shared;
|
||||
out->present |= FL_PS_FIELD_GPU_SHARED;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" {
|
||||
|
||||
FL_PS_API void* FlPsOpen(void) {
|
||||
auto* r = static_cast<Reader*>(HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(Reader)));
|
||||
if (r == nullptr) {
|
||||
return nullptr;
|
||||
}
|
||||
r->collectStatus = static_cast<PDH_STATUS>(PDH_NO_DATA);
|
||||
|
||||
r->openStatus = PdhOpenQueryW(nullptr, 0, &r->query);
|
||||
if (r->openStatus == ERROR_SUCCESS) {
|
||||
r->openStatus = PdhAddEnglishCounterW(r->query, kDedicatedPath, 0, &r->dedicated);
|
||||
}
|
||||
if (r->openStatus == ERROR_SUCCESS &&
|
||||
PdhAddEnglishCounterW(r->query, kSharedPath, 0, &r->shared) != ERROR_SUCCESS) {
|
||||
r->shared = nullptr; // the dedicated figure stands on its own; shared reads N/A
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
FL_PS_API void FlPsClose(void* reader) {
|
||||
auto* r = static_cast<Reader*>(reader);
|
||||
if (r == nullptr) {
|
||||
return;
|
||||
}
|
||||
if (r->query != nullptr) {
|
||||
PdhCloseQuery(r->query);
|
||||
}
|
||||
FreeArray(r->dedicatedItems);
|
||||
FreeArray(r->sharedItems);
|
||||
HeapFree(GetProcessHeap(), 0, r);
|
||||
}
|
||||
|
||||
FL_PS_API int32_t FlPsCollect(void* reader) {
|
||||
auto* r = static_cast<Reader*>(reader);
|
||||
if (r == nullptr) {
|
||||
return FL_PS_BAD_ARGUMENT;
|
||||
}
|
||||
if (r->openStatus != ERROR_SUCCESS) {
|
||||
return static_cast<int32_t>(r->openStatus);
|
||||
}
|
||||
|
||||
r->collected = false;
|
||||
r->collectStatus = PdhCollectQueryData(r->query);
|
||||
if (r->collectStatus != ERROR_SUCCESS) {
|
||||
return static_cast<int32_t>(r->collectStatus);
|
||||
}
|
||||
r->collectStatus = FetchArray(r->dedicated, r->dedicatedItems);
|
||||
if (r->collectStatus != ERROR_SUCCESS) {
|
||||
return static_cast<int32_t>(r->collectStatus);
|
||||
}
|
||||
if (r->shared != nullptr && FetchArray(r->shared, r->sharedItems) != ERROR_SUCCESS) {
|
||||
r->sharedItems.count = 0; // shared reads N/A for this collection; dedicated stands
|
||||
}
|
||||
r->collected = true;
|
||||
return FL_PS_OK;
|
||||
}
|
||||
|
||||
FL_PS_API int32_t FlPsRead(void* reader, uint32_t pid, uint64_t creationTime, void* process, FlPsSample* out) {
|
||||
if (out == nullptr) {
|
||||
return FL_PS_BAD_ARGUMENT;
|
||||
}
|
||||
if (out->size != sizeof(FlPsSample)) {
|
||||
return FL_PS_BAD_SIZE;
|
||||
}
|
||||
auto* r = static_cast<Reader*>(reader);
|
||||
if (r == nullptr || pid == 0) {
|
||||
return FL_PS_BAD_ARGUMENT;
|
||||
}
|
||||
|
||||
std::memset(out, 0, sizeof(FlPsSample));
|
||||
out->size = sizeof(FlPsSample);
|
||||
ReadVideoMemory(*r, pid, out);
|
||||
ReadSystemMemory(pid, creationTime, static_cast<HANDLE>(process), out);
|
||||
return FL_PS_OK;
|
||||
}
|
||||
|
||||
FL_PS_API uint32_t FlPsAbiVersion(void) {
|
||||
return FL_PS_ABI_VERSION;
|
||||
}
|
||||
|
||||
FL_PS_API uint32_t FlPsSampleSize(void) {
|
||||
return sizeof(FlPsSample);
|
||||
}
|
||||
|
||||
FL_PS_API const char* FlPsBuildId(void) {
|
||||
return FL_BUILD_ID;
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
@@ -27,6 +27,21 @@ set_tests_properties(fl_nvapi_bridge PROPERTIES
|
||||
PASS_REGULAR_EXPRESSION "BRANCH: (AVAILABLE|DEGRADED)"
|
||||
FAIL_REGULAR_EXPRESSION "FAILED:;[0-9]+ failed")
|
||||
|
||||
# The process-memory reader's C ABI (beta.12, D43). Same shape as the bridge above: the SHIPPED DLL, copied beside
|
||||
# the test, a branch line that says which machine this is (a CI runner has no hardware adapter, so the video half
|
||||
# takes NO_GPU_INSTANCE there), and a failed assertion fails the test whatever the branch.
|
||||
add_executable(fl_process_stats_test process_stats_test.cpp)
|
||||
target_link_libraries(fl_process_stats_test PRIVATE FrameLedger.ProcessStats fl_native_flags Catch2::Catch2WithMain)
|
||||
target_compile_options(fl_process_stats_test PRIVATE /EHsc)
|
||||
target_compile_definitions(fl_process_stats_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
|
||||
add_custom_command(TARGET fl_process_stats_test POST_BUILD
|
||||
COMMAND ${CMAKE_COMMAND} -E copy_if_different
|
||||
$<TARGET_FILE:FrameLedger.ProcessStats> $<TARGET_FILE_DIR:fl_process_stats_test>)
|
||||
add_test(NAME fl_process_stats COMMAND fl_process_stats_test)
|
||||
set_tests_properties(fl_process_stats PROPERTIES
|
||||
PASS_REGULAR_EXPRESSION "BRANCH: (GPU_INSTANCE|NO_GPU_INSTANCE)"
|
||||
FAIL_REGULAR_EXPRESSION "FAILED:;[0-9]+ failed")
|
||||
|
||||
# The safety-guard matrix. 20_OPEN_QUESTIONS §S13(a) put the guard in C++, which
|
||||
# made Catch2 a PREREQUISITE of the guard rather than a later nicety: 14_TESTING
|
||||
# requires forcing EnumProcessModulesEx failures, partial module lists and
|
||||
|
||||
@@ -0,0 +1,220 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
|
||||
|
||||
// FrameLedger.ProcessStats's C ABI (beta.12, owner decision D43): against this test's own process for the system
|
||||
// half, and — on a machine with a hardware GPU — against a buffer this test allocates for the video half. Links the
|
||||
// SHIPPED DLL, copied beside the test, because what the managed side loads is that DLL's export table.
|
||||
//
|
||||
// Green on both kinds of machine and it says which: a CI runner has no hardware adapter, so the video half takes the
|
||||
// NO_GPU_INSTANCE branch there and the GPU_INSTANCE branch only where a real device exists (the same alternation
|
||||
// fl_nvapi_bridge pins, for the same reason).
|
||||
#include <windows.h>
|
||||
|
||||
#include <d3d11.h>
|
||||
#include <dxgi1_2.h>
|
||||
|
||||
#include <catch2/catch_test_macros.hpp>
|
||||
#include <cstdio>
|
||||
|
||||
#include "fl_process_stats.h"
|
||||
|
||||
#pragma comment(lib, "d3d11.lib")
|
||||
#pragma comment(lib, "dxgi.lib")
|
||||
|
||||
namespace {
|
||||
|
||||
uint64_t CreationTimeOfThisProcess() {
|
||||
FILETIME c{}, e{}, k{}, u{};
|
||||
REQUIRE(GetProcessTimes(GetCurrentProcess(), &c, &e, &k, &u));
|
||||
return (static_cast<uint64_t>(c.dwHighDateTime) << 32) | c.dwLowDateTime;
|
||||
}
|
||||
|
||||
FlPsSample NewSample() {
|
||||
FlPsSample s{};
|
||||
s.size = sizeof(s);
|
||||
return s;
|
||||
}
|
||||
|
||||
double Mib(uint64_t bytes) {
|
||||
return static_cast<double>(bytes) / (1024.0 * 1024.0);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
TEST_CASE("the ABI the managed mirror reads") {
|
||||
REQUIRE(FlPsAbiVersion() == FL_PS_ABI_VERSION);
|
||||
REQUIRE(FlPsSampleSize() == sizeof(FlPsSample));
|
||||
REQUIRE(FlPsBuildId() != nullptr);
|
||||
REQUIRE(FlPsBuildId()[0] != '\0');
|
||||
}
|
||||
|
||||
TEST_CASE("arguments are checked before anything is read") {
|
||||
void* reader = FlPsOpen();
|
||||
REQUIRE(reader != nullptr);
|
||||
const auto pid = static_cast<uint32_t>(GetCurrentProcessId());
|
||||
|
||||
FlPsSample wrong = NewSample();
|
||||
wrong.size = sizeof(FlPsSample) - 8;
|
||||
REQUIRE(FlPsRead(reader, pid, 0, nullptr, &wrong) == FL_PS_BAD_SIZE);
|
||||
|
||||
FlPsSample s = NewSample();
|
||||
REQUIRE(FlPsRead(nullptr, pid, 0, nullptr, &s) == FL_PS_BAD_ARGUMENT);
|
||||
REQUIRE(FlPsRead(reader, 0, 0, nullptr, &s) == FL_PS_BAD_ARGUMENT);
|
||||
REQUIRE(FlPsRead(reader, pid, 0, nullptr, nullptr) == FL_PS_BAD_ARGUMENT);
|
||||
REQUIRE(FlPsCollect(nullptr) == FL_PS_BAD_ARGUMENT);
|
||||
|
||||
FlPsClose(reader);
|
||||
FlPsClose(nullptr); // a null reader is a no-op, never a fault
|
||||
}
|
||||
|
||||
TEST_CASE("this process's system memory, through a handle opened with the least right") {
|
||||
void* reader = FlPsOpen();
|
||||
FlPsSample s = NewSample();
|
||||
REQUIRE(FlPsRead(reader, static_cast<uint32_t>(GetCurrentProcessId()), CreationTimeOfThisProcess(), nullptr, &s) ==
|
||||
FL_PS_OK);
|
||||
|
||||
REQUIRE(s.size == sizeof(FlPsSample));
|
||||
REQUIRE(s.ramStatus == FL_PS_RAM_OK);
|
||||
REQUIRE((s.present & FL_PS_FIELD_WORKING_SET) != 0);
|
||||
REQUIRE((s.present & FL_PS_FIELD_COMMIT) != 0);
|
||||
REQUIRE(s.workingSetBytes > 0);
|
||||
REQUIRE(s.commitBytes > 0);
|
||||
REQUIRE(s.peakWorkingSetBytes >= s.workingSetBytes);
|
||||
if ((s.present & FL_PS_FIELD_PRIVATE_WS) != 0) {
|
||||
REQUIRE(s.privateWorkingSetBytes > 0);
|
||||
REQUIRE(s.privateWorkingSetBytes <= s.workingSetBytes);
|
||||
}
|
||||
// No collection has run on this reader: the video half says so instead of reading zero.
|
||||
REQUIRE((s.present & (FL_PS_FIELD_GPU_DEDICATED | FL_PS_FIELD_GPU_SHARED)) == 0);
|
||||
REQUIRE(s.gpuStatus != FL_PS_GPU_OK);
|
||||
std::printf("RAM: working set %.1f MiB, private working set %.1f MiB (%s), commit %.1f MiB\n",
|
||||
Mib(s.workingSetBytes), Mib(s.privateWorkingSetBytes),
|
||||
(s.present & FL_PS_FIELD_PRIVATE_WS) != 0 ? "EX2" : "N/A on this OS", Mib(s.commitBytes));
|
||||
FlPsClose(reader);
|
||||
}
|
||||
|
||||
TEST_CASE("a held handle is used as given and left open") {
|
||||
HANDLE held = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, GetCurrentProcessId());
|
||||
REQUIRE(held != nullptr);
|
||||
void* reader = FlPsOpen();
|
||||
FlPsSample s = NewSample();
|
||||
REQUIRE(FlPsRead(reader, static_cast<uint32_t>(GetCurrentProcessId()), 0, held, &s) == FL_PS_OK);
|
||||
REQUIRE(s.ramStatus == FL_PS_RAM_OK);
|
||||
REQUIRE(GetProcessId(held) == GetCurrentProcessId()); // still a valid handle: the reader did not close it
|
||||
CloseHandle(held);
|
||||
FlPsClose(reader);
|
||||
}
|
||||
|
||||
TEST_CASE("a pid that names a process created at another time is refused, not read") {
|
||||
void* reader = FlPsOpen();
|
||||
FlPsSample s = NewSample();
|
||||
REQUIRE(FlPsRead(reader, static_cast<uint32_t>(GetCurrentProcessId()), CreationTimeOfThisProcess() + 1, nullptr,
|
||||
&s) == FL_PS_OK);
|
||||
REQUIRE(s.ramStatus == FL_PS_RAM_PID_REUSED);
|
||||
REQUIRE((s.present & (FL_PS_FIELD_WORKING_SET | FL_PS_FIELD_PRIVATE_WS | FL_PS_FIELD_COMMIT)) == 0);
|
||||
REQUIRE(s.workingSetBytes == 0);
|
||||
FlPsClose(reader);
|
||||
}
|
||||
|
||||
TEST_CASE("a process that cannot be opened is a refusal with its reason") {
|
||||
void* reader = FlPsOpen();
|
||||
FlPsSample s = NewSample();
|
||||
// Pids are multiples of four; this one is never handed out on a desktop machine.
|
||||
REQUIRE(FlPsRead(reader, 0xFFFFFFF0u, 0, nullptr, &s) == FL_PS_OK);
|
||||
REQUIRE(s.ramStatus == FL_PS_RAM_OPEN_DENIED);
|
||||
REQUIRE(s.ramError != 0);
|
||||
REQUIRE((s.present & FL_PS_FIELD_WORKING_SET) == 0);
|
||||
FlPsClose(reader);
|
||||
}
|
||||
|
||||
TEST_CASE("video memory: a buffer this process allocates on a hardware adapter is counted as its dedicated memory") {
|
||||
void* reader = FlPsOpen();
|
||||
REQUIRE(reader != nullptr);
|
||||
const auto pid = static_cast<uint32_t>(GetCurrentProcessId());
|
||||
|
||||
// The first adapter that is not a software rasteriser and has memory of its own. A CI runner has none.
|
||||
IDXGIFactory1* factory = nullptr;
|
||||
IDXGIAdapter1* adapter = nullptr;
|
||||
if (SUCCEEDED(CreateDXGIFactory1(__uuidof(IDXGIFactory1), reinterpret_cast<void**>(&factory)))) {
|
||||
for (UINT i = 0; factory->EnumAdapters1(i, &adapter) != DXGI_ERROR_NOT_FOUND; ++i) {
|
||||
DXGI_ADAPTER_DESC1 d{};
|
||||
adapter->GetDesc1(&d);
|
||||
if ((d.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) == 0 && d.DedicatedVideoMemory > 0) {
|
||||
break;
|
||||
}
|
||||
adapter->Release();
|
||||
adapter = nullptr;
|
||||
}
|
||||
factory->Release();
|
||||
}
|
||||
|
||||
ID3D11Device* device = nullptr;
|
||||
ID3D11DeviceContext* context = nullptr;
|
||||
const bool hardware =
|
||||
adapter != nullptr && SUCCEEDED(D3D11CreateDevice(adapter, D3D_DRIVER_TYPE_UNKNOWN, nullptr, 0, nullptr, 0,
|
||||
D3D11_SDK_VERSION, &device, nullptr, &context));
|
||||
if (!hardware || FlPsCollect(reader) != FL_PS_OK) {
|
||||
std::printf(
|
||||
"BRANCH: NO_GPU_INSTANCE (no hardware adapter, or the GPU Process Memory counters did not collect)\n");
|
||||
if (device != nullptr) {
|
||||
context->Release();
|
||||
device->Release();
|
||||
}
|
||||
if (adapter != nullptr) {
|
||||
adapter->Release();
|
||||
}
|
||||
FlPsClose(reader);
|
||||
return;
|
||||
}
|
||||
|
||||
FlPsSample before = NewSample();
|
||||
REQUIRE(FlPsRead(reader, pid, 0, nullptr, &before) == FL_PS_OK);
|
||||
|
||||
constexpr UINT kMib = 256;
|
||||
D3D11_BUFFER_DESC bd{};
|
||||
bd.ByteWidth = kMib * 1024u * 1024u;
|
||||
bd.Usage = D3D11_USAGE_DEFAULT;
|
||||
bd.BindFlags = D3D11_BIND_UNORDERED_ACCESS;
|
||||
bd.MiscFlags = D3D11_RESOURCE_MISC_BUFFER_ALLOW_RAW_VIEWS;
|
||||
ID3D11Buffer* buffer = nullptr;
|
||||
REQUIRE(SUCCEEDED(device->CreateBuffer(&bd, nullptr, &buffer)));
|
||||
D3D11_UNORDERED_ACCESS_VIEW_DESC uav{};
|
||||
uav.Format = DXGI_FORMAT_R32_TYPELESS;
|
||||
uav.ViewDimension = D3D11_UAV_DIMENSION_BUFFER;
|
||||
uav.Buffer.NumElements = bd.ByteWidth / 4;
|
||||
uav.Buffer.Flags = D3D11_BUFFER_UAV_FLAG_RAW;
|
||||
ID3D11UnorderedAccessView* view = nullptr;
|
||||
REQUIRE(SUCCEEDED(device->CreateUnorderedAccessView(buffer, &uav, &view)));
|
||||
const UINT fill[4] = {1, 2, 3, 4};
|
||||
context->ClearUnorderedAccessViewUint(view, fill);
|
||||
context->Flush();
|
||||
|
||||
// The counter provider reads the kernel's accounting at each collection; allow it a few seconds to see the
|
||||
// allocation become resident.
|
||||
FlPsSample after = NewSample();
|
||||
for (int attempt = 0; attempt < 30; ++attempt) {
|
||||
REQUIRE(FlPsCollect(reader) == FL_PS_OK);
|
||||
REQUIRE(FlPsRead(reader, pid, 0, nullptr, &after) == FL_PS_OK);
|
||||
if ((after.present & FL_PS_FIELD_GPU_DEDICATED) != 0 &&
|
||||
after.gpuDedicatedBytes >= before.gpuDedicatedBytes + bd.ByteWidth * 98ull / 100ull) {
|
||||
break;
|
||||
}
|
||||
Sleep(100);
|
||||
}
|
||||
|
||||
std::printf(
|
||||
"BRANCH: GPU_INSTANCE dedicated %.1f -> %.1f MiB (+%.1f, allocated %u), shared %.1f MiB, %u instance(s)\n",
|
||||
Mib(before.gpuDedicatedBytes), Mib(after.gpuDedicatedBytes),
|
||||
Mib(after.gpuDedicatedBytes - before.gpuDedicatedBytes), kMib, Mib(after.gpuSharedBytes), after.gpuInstances);
|
||||
REQUIRE((after.present & FL_PS_FIELD_GPU_DEDICATED) != 0);
|
||||
REQUIRE(after.gpuStatus == FL_PS_GPU_OK);
|
||||
REQUIRE(after.gpuInstances >= 1);
|
||||
REQUIRE(after.gpuDedicatedBytes >= before.gpuDedicatedBytes + bd.ByteWidth * 98ull / 100ull);
|
||||
|
||||
view->Release();
|
||||
buffer->Release();
|
||||
context->Release();
|
||||
device->Release();
|
||||
adapter->Release();
|
||||
FlPsClose(reader);
|
||||
}
|
||||
@@ -4,6 +4,7 @@ add_subdirectory(fl-probe-guard)
|
||||
add_subdirectory(fl-probe-hookprofile)
|
||||
add_subdirectory(fl-probe-interposer)
|
||||
add_subdirectory(fl-probe-nvapi)
|
||||
add_subdirectory(fl-probe-processstats)
|
||||
add_subdirectory(fl-probe-signer)
|
||||
add_subdirectory(fl-probe-vklayer)
|
||||
add_subdirectory(vendor-stubs)
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
# fl-probe-processstats — the instrument behind spike-notes §16 (beta.12, D43): what FrameLedger.ProcessStats.dll
|
||||
# reads about a process, what it costs, and whether it agrees with the process's own QueryVideoMemoryInfo. A tool,
|
||||
# not shipped; it builds with ordinary C++ (exceptions on) because it is our own process and uses the STL freely.
|
||||
add_executable(fl-probe-processstats main.cpp)
|
||||
target_link_libraries(fl-probe-processstats PRIVATE FrameLedger.ProcessStats fl_native_flags)
|
||||
target_compile_options(fl-probe-processstats PRIVATE /EHsc)
|
||||
target_compile_definitions(fl-probe-processstats PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX UNICODE _UNICODE)
|
||||
add_custom_command(TARGET fl-probe-processstats POST_BUILD
|
||||
COMMAND ${CMAKE_COMMAND} -E copy_if_different
|
||||
$<TARGET_FILE:FrameLedger.ProcessStats> $<TARGET_FILE_DIR:fl-probe-processstats>)
|
||||
@@ -0,0 +1,241 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
|
||||
|
||||
// fl-probe-processstats — the instrument behind spike-notes §16 (beta.12, owner decision D43): what
|
||||
// FrameLedger.ProcessStats.dll reads about a process, how much it costs, and whether it agrees with what the process
|
||||
// says about itself. Not shipped; never pointed at a game by anything in the repository.
|
||||
//
|
||||
// fl-probe-processstats --hold-vram <MiB> <seconds>
|
||||
// BE the measured process: create a D3D11 device on the first HARDWARE adapter, allocate <MiB> in a DEFAULT
|
||||
// buffer, and print this process's own IDXGIAdapter3::QueryVideoMemoryInfo(LOCAL) before and after — the
|
||||
// figure a game sees about itself. Exit 77 when the machine has no hardware adapter (a CI runner).
|
||||
// fl-probe-processstats --read <pid> [--samples N] [--interval-ms M] [--v2-name <image name without .exe>]
|
||||
// Read <pid> N times through the DLL: dedicated and shared video memory, working set, private working set,
|
||||
// commit, and the time each collect + read took; at the end the median and maximum time, and how much this
|
||||
// probe's own private bytes grew (the leak check). --v2-name also reads
|
||||
// `\Process V2(<name>:<pid>)\Working Set - Private` for the comparison with PrivateWorkingSetSize.
|
||||
#include <windows.h>
|
||||
|
||||
#include <d3d11.h>
|
||||
#include <dxgi1_4.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cwchar>
|
||||
#include <pdh.h>
|
||||
#include <psapi.h>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "fl_process_stats.h"
|
||||
|
||||
#pragma comment(lib, "d3d11.lib")
|
||||
#pragma comment(lib, "dxgi.lib")
|
||||
#pragma comment(lib, "pdh.lib")
|
||||
|
||||
namespace {
|
||||
|
||||
double Mib(uint64_t bytes) {
|
||||
return static_cast<double>(bytes) / (1024.0 * 1024.0);
|
||||
}
|
||||
|
||||
int HoldVram(int mib, int seconds) {
|
||||
IDXGIFactory1* factory = nullptr;
|
||||
if (FAILED(CreateDXGIFactory1(__uuidof(IDXGIFactory1), reinterpret_cast<void**>(&factory)))) {
|
||||
std::printf("SKIP: no DXGI factory\n");
|
||||
return 77;
|
||||
}
|
||||
IDXGIAdapter1* adapter = nullptr;
|
||||
for (UINT i = 0; factory->EnumAdapters1(i, &adapter) != DXGI_ERROR_NOT_FOUND; ++i) {
|
||||
DXGI_ADAPTER_DESC1 d{};
|
||||
adapter->GetDesc1(&d);
|
||||
if ((d.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) == 0 && d.DedicatedVideoMemory > 0) {
|
||||
std::printf("adapter: %ls (dedicated %.0f MiB)\n", d.Description, Mib(d.DedicatedVideoMemory));
|
||||
break;
|
||||
}
|
||||
adapter->Release();
|
||||
adapter = nullptr;
|
||||
}
|
||||
factory->Release();
|
||||
if (adapter == nullptr) {
|
||||
std::printf("SKIP: no hardware adapter with dedicated memory\n");
|
||||
return 77;
|
||||
}
|
||||
|
||||
ID3D11Device* device = nullptr;
|
||||
ID3D11DeviceContext* context = nullptr;
|
||||
if (FAILED(D3D11CreateDevice(adapter, D3D_DRIVER_TYPE_UNKNOWN, nullptr, 0, nullptr, 0, D3D11_SDK_VERSION, &device,
|
||||
nullptr, &context))) {
|
||||
std::printf("SKIP: D3D11CreateDevice failed on the hardware adapter\n");
|
||||
adapter->Release();
|
||||
return 77;
|
||||
}
|
||||
IDXGIAdapter3* adapter3 = nullptr;
|
||||
adapter->QueryInterface(__uuidof(IDXGIAdapter3), reinterpret_cast<void**>(&adapter3));
|
||||
|
||||
auto report = [&](const char* when) {
|
||||
DXGI_QUERY_VIDEO_MEMORY_INFO info{};
|
||||
if (adapter3 != nullptr &&
|
||||
SUCCEEDED(adapter3->QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &info))) {
|
||||
std::printf("pid=%lu %s local_current_usage=%llu (%.1f MiB) budget=%llu (%.1f MiB)\n",
|
||||
GetCurrentProcessId(), when, static_cast<unsigned long long>(info.CurrentUsage),
|
||||
Mib(info.CurrentUsage), static_cast<unsigned long long>(info.Budget), Mib(info.Budget));
|
||||
}
|
||||
std::fflush(stdout);
|
||||
};
|
||||
|
||||
report("before");
|
||||
D3D11_BUFFER_DESC bd{};
|
||||
bd.ByteWidth = static_cast<UINT>(mib) * 1024u * 1024u;
|
||||
bd.Usage = D3D11_USAGE_DEFAULT;
|
||||
bd.BindFlags = D3D11_BIND_UNORDERED_ACCESS;
|
||||
bd.MiscFlags = D3D11_RESOURCE_MISC_BUFFER_ALLOW_RAW_VIEWS;
|
||||
ID3D11Buffer* buffer = nullptr;
|
||||
if (FAILED(device->CreateBuffer(&bd, nullptr, &buffer))) {
|
||||
std::printf("FAILED: CreateBuffer(%d MiB)\n", mib);
|
||||
return 2;
|
||||
}
|
||||
// Touch it so it is resident, not merely reserved.
|
||||
D3D11_UNORDERED_ACCESS_VIEW_DESC uav{};
|
||||
uav.Format = DXGI_FORMAT_R32_TYPELESS;
|
||||
uav.ViewDimension = D3D11_UAV_DIMENSION_BUFFER;
|
||||
uav.Buffer.NumElements = bd.ByteWidth / 4;
|
||||
uav.Buffer.Flags = D3D11_BUFFER_UAV_FLAG_RAW;
|
||||
ID3D11UnorderedAccessView* view = nullptr;
|
||||
if (SUCCEEDED(device->CreateUnorderedAccessView(buffer, &uav, &view))) {
|
||||
const UINT zero[4] = {1, 2, 3, 4};
|
||||
context->ClearUnorderedAccessViewUint(view, zero);
|
||||
}
|
||||
context->Flush();
|
||||
report("after");
|
||||
std::printf("holding %d MiB for %d s\n", mib, seconds);
|
||||
std::fflush(stdout);
|
||||
Sleep(static_cast<DWORD>(seconds) * 1000u);
|
||||
report("end");
|
||||
if (view != nullptr) {
|
||||
view->Release();
|
||||
}
|
||||
buffer->Release();
|
||||
context->Release();
|
||||
device->Release();
|
||||
if (adapter3 != nullptr) {
|
||||
adapter3->Release();
|
||||
}
|
||||
adapter->Release();
|
||||
return 0;
|
||||
}
|
||||
|
||||
uint64_t OwnPrivateBytes() {
|
||||
PROCESS_MEMORY_COUNTERS_EX ex{};
|
||||
ex.cb = sizeof(ex);
|
||||
GetProcessMemoryInfo(GetCurrentProcess(), reinterpret_cast<PROCESS_MEMORY_COUNTERS*>(&ex), sizeof(ex));
|
||||
return ex.PrivateUsage;
|
||||
}
|
||||
|
||||
uint64_t CreationTime(uint32_t pid) {
|
||||
HANDLE h = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid);
|
||||
if (h == nullptr) {
|
||||
return 0;
|
||||
}
|
||||
FILETIME c{}, e{}, k{}, u{};
|
||||
uint64_t value = 0;
|
||||
if (GetProcessTimes(h, &c, &e, &k, &u)) {
|
||||
value = (static_cast<uint64_t>(c.dwHighDateTime) << 32) | c.dwLowDateTime;
|
||||
}
|
||||
CloseHandle(h);
|
||||
return value;
|
||||
}
|
||||
|
||||
int Read(uint32_t pid, int samples, int intervalMs, const wchar_t* v2Name) {
|
||||
void* reader = FlPsOpen();
|
||||
if (reader == nullptr) {
|
||||
std::printf("FAILED: FlPsOpen\n");
|
||||
return 2;
|
||||
}
|
||||
|
||||
PDH_HQUERY v2Query = nullptr;
|
||||
PDH_HCOUNTER v2Counter = nullptr;
|
||||
if (v2Name != nullptr) {
|
||||
wchar_t path[512];
|
||||
std::swprintf(path, 512, L"\\Process V2(%ls:%lu)\\Working Set - Private", v2Name,
|
||||
static_cast<unsigned long>(pid));
|
||||
if (PdhOpenQueryW(nullptr, 0, &v2Query) != ERROR_SUCCESS ||
|
||||
PdhAddEnglishCounterW(v2Query, path, 0, &v2Counter) != ERROR_SUCCESS) {
|
||||
std::printf("note: Process V2 counter unavailable for %ls\n", path);
|
||||
v2Counter = nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
const uint64_t created = CreationTime(pid);
|
||||
const uint64_t ownBefore = OwnPrivateBytes();
|
||||
std::vector<double> costs;
|
||||
LARGE_INTEGER freq{};
|
||||
QueryPerformanceFrequency(&freq);
|
||||
for (int i = 0; i < samples; ++i) {
|
||||
LARGE_INTEGER t0{}, t1{};
|
||||
QueryPerformanceCounter(&t0);
|
||||
const int32_t collected = FlPsCollect(reader);
|
||||
FlPsSample s{};
|
||||
s.size = sizeof(s);
|
||||
const int32_t read = FlPsRead(reader, pid, created, nullptr, &s);
|
||||
QueryPerformanceCounter(&t1);
|
||||
const double ms = static_cast<double>(t1.QuadPart - t0.QuadPart) * 1000.0 / static_cast<double>(freq.QuadPart);
|
||||
costs.push_back(ms);
|
||||
|
||||
double v2 = -1;
|
||||
if (v2Counter != nullptr && PdhCollectQueryData(v2Query) == ERROR_SUCCESS) {
|
||||
PDH_FMT_COUNTERVALUE value{};
|
||||
if (PdhGetFormattedCounterValue(v2Counter, PDH_FMT_LARGE, nullptr, &value) == ERROR_SUCCESS) {
|
||||
v2 = Mib(static_cast<uint64_t>(value.largeValue));
|
||||
}
|
||||
}
|
||||
std::printf(
|
||||
"#%03d collect=%d read=%d ms=%.3f dedicated=%.1f shared=%.1f inst=%u gpu=%d ws=%.1f private_ws=%.1f "
|
||||
"commit=%.1f ram=%d v2_private_ws=%.1f present=0x%02x\n",
|
||||
i, collected, read, ms, Mib(s.gpuDedicatedBytes), Mib(s.gpuSharedBytes), s.gpuInstances, s.gpuStatus,
|
||||
Mib(s.workingSetBytes), Mib(s.privateWorkingSetBytes), Mib(s.commitBytes), s.ramStatus, v2, s.present);
|
||||
std::fflush(stdout);
|
||||
if (intervalMs > 0 && i + 1 < samples) {
|
||||
Sleep(static_cast<DWORD>(intervalMs));
|
||||
}
|
||||
}
|
||||
const uint64_t ownAfter = OwnPrivateBytes();
|
||||
std::sort(costs.begin(), costs.end());
|
||||
const double median = costs.empty() ? 0 : costs[costs.size() / 2];
|
||||
const double worst = costs.empty() ? 0 : costs.back();
|
||||
std::printf("SUMMARY samples=%d cost_median_ms=%.3f cost_max_ms=%.3f probe_private_bytes_delta=%lld\n", samples,
|
||||
median, worst, static_cast<long long>(ownAfter) - static_cast<long long>(ownBefore));
|
||||
if (v2Query != nullptr) {
|
||||
PdhCloseQuery(v2Query);
|
||||
}
|
||||
FlPsClose(reader);
|
||||
return 0;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int wmain(int argc, wchar_t** argv) {
|
||||
if (argc >= 4 && std::wcscmp(argv[1], L"--hold-vram") == 0) {
|
||||
return HoldVram(_wtoi(argv[2]), _wtoi(argv[3]));
|
||||
}
|
||||
if (argc >= 3 && std::wcscmp(argv[1], L"--read") == 0) {
|
||||
const auto pid = static_cast<uint32_t>(std::wcstoul(argv[2], nullptr, 10));
|
||||
int samples = 60;
|
||||
int intervalMs = 1000;
|
||||
const wchar_t* v2Name = nullptr;
|
||||
for (int i = 3; i + 1 < argc; i += 2) {
|
||||
if (std::wcscmp(argv[i], L"--samples") == 0) {
|
||||
samples = _wtoi(argv[i + 1]);
|
||||
} else if (std::wcscmp(argv[i], L"--interval-ms") == 0) {
|
||||
intervalMs = _wtoi(argv[i + 1]);
|
||||
} else if (std::wcscmp(argv[i], L"--v2-name") == 0) {
|
||||
v2Name = argv[i + 1];
|
||||
}
|
||||
}
|
||||
return Read(pid, samples, intervalMs, v2Name);
|
||||
}
|
||||
std::printf("usage: fl-probe-processstats --hold-vram <MiB> <seconds>\n"
|
||||
" fl-probe-processstats --read <pid> [--samples N] [--interval-ms M] [--v2-name <image>]\n");
|
||||
return 64;
|
||||
}
|
||||
@@ -7,6 +7,7 @@ using FrameLedger.Application.AntiCheat;
|
||||
using FrameLedger.Application.Capture;
|
||||
using FrameLedger.Application.Consent;
|
||||
using FrameLedger.Application.Recording;
|
||||
using FrameLedger.Application.Telemetry;
|
||||
using FrameLedger.Application.Tests.AntiCheat;
|
||||
using FrameLedger.Domain.AntiCheat;
|
||||
using FrameLedger.Domain.Consent;
|
||||
@@ -1159,6 +1160,95 @@ public sealed class CaptureSessionTests : IAsyncDisposable
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>What the loop told the observer to read the game's memory of (beta.12, D43), in order.</summary>
|
||||
private sealed class MeasuringRecorder : ICaptureObserver
|
||||
{
|
||||
public List<GameProcess> Targets { get; } = [];
|
||||
|
||||
public void Attached(int pid, FlShmHandshake handshake)
|
||||
{
|
||||
}
|
||||
|
||||
public void Tick(CaptureProgress progress)
|
||||
{
|
||||
}
|
||||
|
||||
public void Measuring(GameProcess target) => Targets.Add(target);
|
||||
}
|
||||
|
||||
/// <summary>A resolver whose watcher snapshot names a different set of processes after a few hold ticks.</summary>
|
||||
private sealed class ChangingProcesses(int runningTicks, IReadOnlyList<GameProcessId> first, IReadOnlyList<GameProcessId> then, int switchAfter) : ITargetResolver
|
||||
{
|
||||
private int _running = runningTicks;
|
||||
private int _asked;
|
||||
|
||||
public int? Resolve(string normalisedExePath, out SessionEndReason reason)
|
||||
{
|
||||
reason = SessionEndReason.Running;
|
||||
return _pid;
|
||||
}
|
||||
|
||||
public bool IsRunning(string normalisedExePath) => _running-- > 0;
|
||||
|
||||
public IReadOnlyList<int> PidsOf(string normalisedExePath) => [];
|
||||
|
||||
public IReadOnlyList<GameProcessId> ProcessesOf(string normalisedExePath) => _asked++ < switchAfter ? first : then;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// beta.12 (D43): a session refused after the pin is held through that pin, and the game's memory is read through it —
|
||||
/// the observer hears the pinned process first and "none" before the pin is released, nothing in between.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task ARefusalAfterThePinReadsTheGamesMemoryThroughThePinAndLetsGoBeforeItCloses()
|
||||
{
|
||||
var guard = new CountingGuard { Verdict = AntiCheatVerdict.Refused(AntiCheatRefusalReason.BlockedDriver, "Riot Vanguard", "vgk.sys") };
|
||||
using var alive = new FakeLiveness { ExitAfterChecks = 3 };
|
||||
var measuring = new MeasuringRecorder();
|
||||
|
||||
await With(await StoreWithAsync(), guard, new FixedResolver(_pid, SessionEndReason.Running), alive, measuring)
|
||||
.RunAsync(_exe, Fingerprint, "payload.dll", TestContext.Current.CancellationToken);
|
||||
|
||||
measuring.Targets.Should().HaveCount(2);
|
||||
measuring.Targets[0].Pid.Should().Be(_pid);
|
||||
measuring.Targets[0].PinnedBy.Should().BeSameAs(alive, "the session's own pin, whose handle the read borrows");
|
||||
measuring.Targets[1].IsNone.Should().BeTrue("let go of before the pin's handle closes");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// beta.12 (D43): a hooking-off hold never opens the game for itself; it names the processes the watcher's snapshot
|
||||
/// lists for the executable, re-announces only when that set changes, and lets go at the end.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task AnUnpinnedHoldAnnouncesItsProcessesWhenTheSetChangesAndLetsGoAtTheEnd()
|
||||
{
|
||||
var t = DateTimeOffset.UnixEpoch;
|
||||
GameProcessId[] one = [new(100, t)];
|
||||
GameProcessId[] two = [new(100, t), new(200, t.AddSeconds(3))];
|
||||
var resolver = new ChangingProcesses(runningTicks: 8, first: one, then: two, switchAfter: 3);
|
||||
var measuring = new MeasuringRecorder();
|
||||
var guard = new CountingGuard();
|
||||
|
||||
CaptureOutcome r = await With(await StoreWithAsync(enabled: false), guard, new FixedResolver(_pid, SessionEndReason.Running, runningTicks: 0), observer: measuring)
|
||||
.RunAsync(_exe, Fingerprint, "payload.dll", TestContext.Current.CancellationToken);
|
||||
r.HeldUnhooked.Should().BeTrue();
|
||||
measuring.Targets.Should().BeEmpty("a hold whose snapshot names no process announces nothing");
|
||||
|
||||
var held = new MeasuringRecorder();
|
||||
await new CaptureSession(await StoreWithAsync(enabled: false), new HookedCaptureGate(guard), guard, resolver,
|
||||
new DelegateLivenessSource(_ => new FakeLiveness()), new DelegateRingAttacher(_ => (null, ShmAttachRefusal.BuildIdMismatch)),
|
||||
new CaptureOptions { HoldInterval = TimeSpan.FromMilliseconds(1), HoldUnhooked = true, MaxDuration = TimeSpan.FromSeconds(5) },
|
||||
observer: held)
|
||||
.RunAsync(_exe, Fingerprint, "payload.dll", TestContext.Current.CancellationToken);
|
||||
|
||||
held.Targets.Should().HaveCount(3, "the first set, the changed set, and none at the end — never a repeat of an unchanged set");
|
||||
held.Targets[0].Processes.Should().Equal(one);
|
||||
held.Targets[0].PinnedBy.Should().BeNull("nothing was pinned: each process is opened only for its read, by the reader");
|
||||
held.Targets[1].Processes.Should().Equal(two);
|
||||
held.Targets[2].IsNone.Should().BeTrue();
|
||||
guard.InjectCalls.Should().Be(0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TheOperatorHostTakesARefusalAsTheAnswer()
|
||||
{
|
||||
|
||||
@@ -133,6 +133,65 @@ public sealed class SessionFinalizerTests
|
||||
hot.Sensors.Select(s => s.Series).Should().Contain("cpu_temp");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// beta.12 (D43): the game process's memory becomes five series beside the sensors, its median / mean / peak columns
|
||||
/// (both tiers — this row is Tier 2), the sources that answered, and every series' statistics in sensor_stats_json.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void TheGamesMemoryBecomesItsSeriesItsColumnsAndTheStatisticsOfEverySeries()
|
||||
{
|
||||
(SessionFinalizer finalizer, _) = Make();
|
||||
List<Application.Telemetry.TelemetrySample> sensors = SessionFixtures.SensorsWithSystem(4);
|
||||
double?[] dedicated = [8000, 9000, null, 7000];
|
||||
for (int i = 0; i < sensors.Count; i++)
|
||||
{
|
||||
sensors[i] = sensors[i] with
|
||||
{
|
||||
Game = dedicated[i] is { } d
|
||||
? new Application.Telemetry.ProcessReading(d, 512, 6000 + i, 6500 + i, 7000 + i, 2,
|
||||
Application.Telemetry.ProcessReadingSources.Counters | Application.Telemetry.ProcessReadingSources.PrivateWorkingSetRead | Application.Telemetry.ProcessReadingSources.TransientHandle)
|
||||
: default,
|
||||
};
|
||||
}
|
||||
|
||||
FinalizedSession built = finalizer.Build(new FinalizeInput { Skeleton = SessionFixtures.Skeleton(tier: CaptureTier.NotHooked), Sensors = sensors });
|
||||
|
||||
built.Sensors.Select(s => s.Series).Should().ContainInOrder("ram_mb", "game_vram_dedicated", "game_vram_shared", "game_ram_private", "game_ram_ws", "game_commit");
|
||||
RawSeriesCodec.Floats(built.Sensors.Single(s => string.Equals(s.Series, SensorSeriesCatalog.GameVramDedicated, StringComparison.Ordinal)).Data).Should().Equal(8000f, 9000f, SessionFinalizer.SensorMissing, 7000f);
|
||||
SessionRow row = built.Row;
|
||||
row.GameVramDedicatedMedianMb.Should().Be(8000, "the middle of 7000, 8000, 9000 — the tick with no reading is not a zero");
|
||||
row.GameVramDedicatedAvgMb.Should().Be(8000);
|
||||
row.GameVramDedicatedMaxMb.Should().Be(9000);
|
||||
row.GameVramSharedMaxMb.Should().Be(512);
|
||||
row.GameRamPrivateMedianMb.Should().Be(6001);
|
||||
row.GameRamPrivateMaxMb.Should().Be(6003);
|
||||
row.GameRamWorkingSetMaxMb.Should().Be(6503);
|
||||
row.GameCommitMaxMb.Should().Be(7003);
|
||||
row.GameMemoryProcesses.Should().Be(2);
|
||||
row.GameMemorySource.Should().Be("counters,ex2,opened");
|
||||
|
||||
IReadOnlyDictionary<string, SensorSeriesStats> stats = SensorSeriesStats.Parse(row.SensorStatsJson);
|
||||
stats[SensorSeriesCatalog.GameVramDedicated].Should().Be(new SensorSeriesStats(3, 8000, 8000, 7000, 9000));
|
||||
stats[SensorSeriesCatalog.RamSystem].N.Should().Be(4);
|
||||
stats.Should().ContainKey(SensorSeriesCatalog.GpuTemp).And.NotContainKey(SensorSeriesCatalog.CpuTemp, "no tick carried a CPU temperature");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ASessionWithoutAnyGameReadingKeepsEveryGameColumnNull()
|
||||
{
|
||||
(SessionFinalizer finalizer, _) = Make();
|
||||
|
||||
SessionRow row = finalizer.Build(new FinalizeInput { Skeleton = SessionFixtures.Skeleton(tier: CaptureTier.NotHooked), Sensors = SessionFixtures.Sensors(3) }).Row;
|
||||
|
||||
row.GameVramDedicatedMaxMb.Should().BeNull("N/A, never 0");
|
||||
row.GameRamPrivateMedianMb.Should().BeNull();
|
||||
row.GameMemoryProcesses.Should().BeNull();
|
||||
row.GameMemorySource.Should().BeNull();
|
||||
SensorSeriesStats.Parse(row.SensorStatsJson).Should().ContainKey(SensorSeriesCatalog.GpuTemp, "the sensors still have their statistics");
|
||||
SensorSeriesStats.Parse(null).Should().BeEmpty();
|
||||
SensorSeriesStats.Parse("{not json").Should().BeEmpty("text this build cannot read is no statistics, never a throw into the UI");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TooShortIsDiscardedAndNothingIsWritten()
|
||||
{
|
||||
|
||||
@@ -17,14 +17,34 @@ public sealed class AggregatesTests
|
||||
|
||||
s.Count.Should().Be(3);
|
||||
s.Average.Should().Be(65);
|
||||
s.Median.Should().Be(65, "the middle of 60, 65, 70");
|
||||
s.Min.Should().Be(60);
|
||||
s.Max.Should().Be(70);
|
||||
|
||||
SeriesAggregates none = SeriesAggregates.Of([null, null]);
|
||||
none.Count.Should().Be(0);
|
||||
none.Average.Should().BeNull();
|
||||
none.Median.Should().BeNull("N/A, never 0");
|
||||
none.Min.Should().BeNull();
|
||||
none.Max.Should().BeNull();
|
||||
}
|
||||
|
||||
/// <summary>beta.12: the median of an even count is the mean of the two middle values, and it does not care about order.</summary>
|
||||
[Fact]
|
||||
public void TheMedianOfAnEvenCountIsTheMeanOfTheTwoMiddleValuesInAnyOrder()
|
||||
{
|
||||
SeriesAggregates s = SeriesAggregates.Of([9000.0, 1000.0, null, 3000.0, 5000.0]);
|
||||
|
||||
s.Count.Should().Be(4);
|
||||
s.Median.Should().Be(4000, "(3000 + 5000) / 2 — the samples arrive unsorted");
|
||||
s.Average.Should().Be(4500);
|
||||
s.Min.Should().Be(1000);
|
||||
s.Max.Should().Be(9000);
|
||||
|
||||
SeriesAggregates one = SeriesAggregates.Of([42.0]);
|
||||
(one.Median, one.Min, one.Max, one.Average).Should().Be((42.0, 42.0, 42.0, 42.0));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void VramAggregatesUseTheClaimingSamplesAndTheWritersBudget()
|
||||
{
|
||||
|
||||
@@ -35,6 +35,7 @@
|
||||
-->
|
||||
<Import Project="$(MSBuildThisFileDirectory)..\..\FrameLedger.Guard.targets" />
|
||||
<Import Project="$(MSBuildThisFileDirectory)..\..\FrameLedger.NvapiBridge.targets" />
|
||||
<Import Project="$(MSBuildThisFileDirectory)..\..\FrameLedger.ProcessStats.targets" />
|
||||
|
||||
<!--
|
||||
The packaged seed, so the seeder tests run against the artifact that ships
|
||||
|
||||
@@ -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.Infrastructure.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// The test classes that open a LibreHardwareMonitor <c>Computer</c>, run one at a time. The library's CPU code is not safe
|
||||
/// against a second <c>Computer</c> updating beside it: measured 2026-10-03, <c>GenericCpu.Update</c> threw a
|
||||
/// NullReferenceException in the local gate while <see cref="Telemetry.LhmRealHardwareTests"/> ran in parallel with
|
||||
/// <see cref="Startup.PrivilegeFootprintTests"/>, and passed five times out of five alone. The Agent's own reads are
|
||||
/// already contained (<c>SystemTelemetrySource</c> catches a throwing CPU-temperature read: that tick's reading is N/A);
|
||||
/// the test calls <c>Read</c> bare, so here the race is a red gate. An implicit collection: no fixture, so no definition
|
||||
/// class is needed (the same shape as App.Tests' <c>StringsCultureCollection</c>).
|
||||
/// </summary>
|
||||
internal static class LibreHardwareMonitorCollection
|
||||
{
|
||||
public const string Name = "LibreHardwareMonitor";
|
||||
}
|
||||
@@ -137,6 +137,48 @@ public sealed class LedgerDatabaseTests
|
||||
cancellationToken: Ct)).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Schema 0018 (2026-10-03, beta.12, D43): the game process's own memory and the sensor statistics, twelve columns, ADD
|
||||
/// COLUMN only — a session written before has none of them (N/A, never a zero), and a new one writes and reads each.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task ScriptEighteenAddsTheGameMemoryColumnsAndAnEarlierSessionHasNone()
|
||||
{
|
||||
await using LedgerFixture f = await LedgerFixture.OpenAsync();
|
||||
MigrationRunner.LatestVersion.Should().BeGreaterThanOrEqualTo(18);
|
||||
long gameId = (await new SqliteGameRepository(f.Db).EnsureAsync(
|
||||
new() { ExePath = @"C:\Games\M\m.exe", SizeBytes = 1, MtimeUnixMs = 2 }, "M", 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 c17 = new SqliteConnection(new SqliteConnectionStringBuilder { DataSource = path, Pooling = false }.ToString());
|
||||
await using (c17.ConfigureAwait(true))
|
||||
{
|
||||
await c17.OpenAsync(Ct).ConfigureAwait(true);
|
||||
await RewindToAsync(c17, 17).ConfigureAwait(true);
|
||||
await c17.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-000000000018', @gameId, @snapshotId, 0, 60000, 60, 0, 10000000, 2, 'attach', 'normal', 0, 0, 0, 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);
|
||||
long columns = await migrated.ReadAsync((c, ct) => c.ExecuteScalarAsync<long>(new CommandDefinition(
|
||||
"SELECT COUNT(*) FROM pragma_table_info('sessions') WHERE (substr(name, 1, 5) = 'game_' AND name <> 'game_id') OR name = 'sensor_stats_json'", cancellationToken: ct)), Ct)
|
||||
.ConfigureAwait(true);
|
||||
columns.Should().Be(12);
|
||||
SessionRow before = (await new SqliteSessionRepository(migrated).FindAsync(Guid.Parse("00000000-0000-0000-0000-000000000018"), Ct).ConfigureAwait(true))!;
|
||||
before.GameVramDedicatedMaxMb.Should().BeNull("a session recorded before beta.12 has no game memory, and reads N/A");
|
||||
before.GameRamPrivateMedianMb.Should().BeNull();
|
||||
before.GameMemorySource.Should().BeNull();
|
||||
before.SensorStatsJson.Should().BeNull();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Schema 0017 (2026-10-03, beta.11, D38): <c>games.ac_exception_trial_failed_at</c>, NULL on every row written before — a
|
||||
/// grant made under D33 keeps everything it had and carries no failed trial.
|
||||
|
||||
@@ -76,6 +76,19 @@ public sealed class SqliteSessionRepositoryTests
|
||||
DisplayMonitorW = 2560,
|
||||
DisplayMonitorH = 1440,
|
||||
DisplayMonitorHz = 165,
|
||||
// Schema 0018 (beta.12, D43): every game-memory column non-null, or the round trip would pass without reading one.
|
||||
GameVramDedicatedAvgMb = 8123.5,
|
||||
GameVramDedicatedMedianMb = 8100,
|
||||
GameVramDedicatedMaxMb = 9216,
|
||||
GameVramSharedMaxMb = 512.25,
|
||||
GameRamPrivateAvgMb = 6000.5,
|
||||
GameRamPrivateMedianMb = 5990,
|
||||
GameRamPrivateMaxMb = 7100,
|
||||
GameRamWorkingSetMaxMb = 7600,
|
||||
GameCommitMaxMb = 8800,
|
||||
GameMemoryProcesses = 1,
|
||||
GameMemorySource = "counters,ex2,held",
|
||||
SensorStatsJson = "{\"gpu_temp\":{\"N\":3,\"Mean\":61,\"Median\":61,\"Min\":60,\"Max\":62}}",
|
||||
};
|
||||
|
||||
private static FrameBlobs Frames(int n) => new()
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
|
||||
|
||||
using System.Buffers.Binary;
|
||||
using FluentAssertions;
|
||||
using FrameLedger.Application.Recording;
|
||||
using FrameLedger.Application.Telemetry;
|
||||
@@ -112,6 +113,72 @@ public sealed class PartialSessionFileTests : IDisposable
|
||||
p.Notes[1].At.Should().Be(_t0.AddSeconds(2));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// beta.12 (D43): the game process's memory rides the sensors chunk in its wide form, nulls kept null; and a beta.11
|
||||
/// <c>.partial</c> — whose sensors are the narrow chunk type 4 — still recovers, with no game memory, which it never had.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void TheGameMemoryRoundTripsAndANarrowSensorsChunkFromBeta11StillReads()
|
||||
{
|
||||
string path = Path.Combine(_dir, "wide.partial");
|
||||
using (IPartialSessionWriter w = PartialSessionFile.Create(path, Header(Guid.NewGuid())))
|
||||
{
|
||||
var game = new ProcessReading(VramDedicatedMb: 9216, VramSharedMb: 512, RamPrivateMb: null, RamWorkingSetMb: 7000, CommitMb: 8000,
|
||||
Processes: 2, Sources: ProcessReadingSources.Counters | ProcessReadingSources.WorkingSetReadOnly | ProcessReadingSources.TransientHandle);
|
||||
w.AppendSensors([Sample(1_100_000, 60, 3000) with { Game = game }, Sample(1_200_000, 61, 3001)]);
|
||||
}
|
||||
|
||||
// A narrow (type 4) chunk as beta.11 wrote it: qpc, wall clock, layer, a 16-bit mask (core temperature, system RAM).
|
||||
var narrow = new byte[8 + 8 + 1 + 2 + 16];
|
||||
BinaryPrimitives.WriteInt64LittleEndian(narrow, 1_300_000);
|
||||
BinaryPrimitives.WriteInt64LittleEndian(narrow.AsSpan(8), _t0.ToUnixTimeMilliseconds());
|
||||
narrow[16] = (byte)TelemetryLayer.Lhm;
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(narrow.AsSpan(17), (ushort)((1 << 0) | (1 << 13)));
|
||||
BinaryPrimitives.WriteDoubleLittleEndian(narrow.AsSpan(19), 55.0);
|
||||
BinaryPrimitives.WriteDoubleLittleEndian(narrow.AsSpan(27), 8000.0);
|
||||
AppendRawChunk(path, 4, narrow);
|
||||
|
||||
PartialSession p = PartialSessionFile.Read(path)!;
|
||||
|
||||
p.Sensors.Should().HaveCount(3);
|
||||
p.Sensors[0].Game.VramDedicatedMb.Should().Be(9216);
|
||||
p.Sensors[0].Game.VramSharedMb.Should().Be(512);
|
||||
p.Sensors[0].Game.RamPrivateMb.Should().BeNull("no private working set on that OS: N/A stays N/A");
|
||||
p.Sensors[0].Game.RamWorkingSetMb.Should().Be(7000);
|
||||
p.Sensors[0].Game.CommitMb.Should().Be(8000);
|
||||
p.Sensors[0].Game.Processes.Should().Be(2);
|
||||
p.Sensors[0].Game.Sources.Should().Be(ProcessReadingSources.Counters | ProcessReadingSources.WorkingSetReadOnly | ProcessReadingSources.TransientHandle);
|
||||
p.Sensors[1].Game.IsEmpty.Should().BeTrue("a tick that read nothing of the game reads back with nothing");
|
||||
p.Sensors[2].QpcTicks.Should().Be(1_300_000);
|
||||
p.Sensors[2].Sample.TempCoreC.Should().Be(55);
|
||||
p.Sensors[2].System.RamUsedMb.Should().Be(8000);
|
||||
p.Sensors[2].Game.IsEmpty.Should().BeTrue("a beta.11 chunk carries no game memory");
|
||||
}
|
||||
|
||||
/// <summary>One chunk framed as the file frames it: type, length, payload, CRC-32 (IEEE) over the frame and payload.</summary>
|
||||
private static void AppendRawChunk(string path, uint type, byte[] payload)
|
||||
{
|
||||
var frame = new byte[8];
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(frame, type);
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(frame.AsSpan(4), (uint)payload.Length);
|
||||
uint crc = 0xFFFFFFFFu;
|
||||
foreach (byte b in frame.Concat(payload))
|
||||
{
|
||||
crc ^= b;
|
||||
for (int k = 0; k < 8; k++)
|
||||
{
|
||||
crc = (crc & 1) != 0 ? 0xEDB88320u ^ (crc >> 1) : crc >> 1;
|
||||
}
|
||||
}
|
||||
|
||||
var trailer = new byte[4];
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(trailer, crc ^ 0xFFFFFFFFu);
|
||||
using var stream = new FileStream(path, FileMode.Append, FileAccess.Write);
|
||||
stream.Write(frame);
|
||||
stream.Write(payload);
|
||||
stream.Write(trailer);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AKillAtEveryByteOffsetYieldsExactlyTheChunksThatWereComplete()
|
||||
{
|
||||
|
||||
@@ -22,6 +22,7 @@ namespace FrameLedger.Infrastructure.Tests.Startup;
|
||||
/// is that nothing here enables a powerful privilege that was not already on. If a library ever enables one, this goes
|
||||
/// red on CI — and that is a question for the owner, not a line to relax.
|
||||
/// </remarks>
|
||||
[Collection(LibreHardwareMonitorCollection.Name)]
|
||||
public sealed class PrivilegeFootprintTests
|
||||
{
|
||||
private static readonly string[] _powerful =
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
|
||||
|
||||
using System.Runtime.InteropServices;
|
||||
using FluentAssertions;
|
||||
using FrameLedger.Application.Capture;
|
||||
using FrameLedger.Application.Telemetry;
|
||||
using FrameLedger.Infrastructure.Capture;
|
||||
using FrameLedger.Infrastructure.Telemetry;
|
||||
using Microsoft.Win32.SafeHandles;
|
||||
|
||||
namespace FrameLedger.Infrastructure.Tests.Telemetry;
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="GameMemoryReader"/> over a scripted <see cref="IProcessStats"/> (beta.12, D43): what it may open, what it
|
||||
/// sums, and what it refuses to read — the rules <c>03_METRICS</c> §Game process memory states.
|
||||
/// </summary>
|
||||
public sealed class GameMemoryReaderTests
|
||||
{
|
||||
private const double _mib = 1024.0 * 1024.0;
|
||||
|
||||
private sealed class ScriptedStats : IProcessStats
|
||||
{
|
||||
public Dictionary<uint, ProcessStatsSample> Answers { get; } = [];
|
||||
|
||||
public List<(uint Pid, ulong Created, bool Held)> Reads { get; } = [];
|
||||
|
||||
public int Opens { get; private set; }
|
||||
|
||||
public int Collects { get; private set; }
|
||||
|
||||
public bool OpenFails { get; set; }
|
||||
|
||||
public IntPtr Open()
|
||||
{
|
||||
Opens++;
|
||||
return OpenFails ? IntPtr.Zero : new IntPtr(1);
|
||||
}
|
||||
|
||||
public int Collect(IntPtr reader)
|
||||
{
|
||||
Collects++;
|
||||
return 0;
|
||||
}
|
||||
|
||||
public int Read(IntPtr reader, uint pid, ulong creationTime, SafeHandle? process, ref ProcessStatsSample sample)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(process is { IsClosed: true }, process!);
|
||||
Reads.Add((pid, creationTime, process is not null));
|
||||
sample = Answers.TryGetValue(pid, out ProcessStatsSample a) ? a : new ProcessStatsSample { RamStatus = 1 };
|
||||
return 0;
|
||||
}
|
||||
|
||||
public void Close(IntPtr reader)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class HeldPin(SafeHandle handle) : ITargetLiveness, IHeldProcessHandle
|
||||
{
|
||||
public SafeHandle ProcessHandle => handle;
|
||||
|
||||
public bool HasExited => false;
|
||||
|
||||
public int? ExitCode => null;
|
||||
|
||||
public bool IsForeground => true;
|
||||
|
||||
public void Dispose() => handle.Dispose();
|
||||
}
|
||||
|
||||
private static ProcessStatsSample Full(double dedicatedMib, double privateMib) => new()
|
||||
{
|
||||
Present = 0x01 | 0x02 | 0x04 | 0x08 | 0x10,
|
||||
GpuDedicatedBytes = (ulong)(dedicatedMib * _mib),
|
||||
GpuSharedBytes = (ulong)(64 * _mib),
|
||||
PrivateWorkingSetBytes = (ulong)(privateMib * _mib),
|
||||
WorkingSetBytes = (ulong)((privateMib + 100) * _mib),
|
||||
CommitBytes = (ulong)((privateMib + 200) * _mib),
|
||||
GpuInstances = 1,
|
||||
};
|
||||
|
||||
[Fact]
|
||||
public void NothingFollowedReadsNothingAndOpensNothing()
|
||||
{
|
||||
var stats = new ScriptedStats();
|
||||
using var reader = new GameMemoryReader(stats);
|
||||
|
||||
reader.TryRead(out ProcessReading reading).Should().BeFalse();
|
||||
reading.IsEmpty.Should().BeTrue();
|
||||
stats.Opens.Should().Be(0, "no session has a process yet: the counter query is not even opened");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void APinnedGameIsReadThroughTheHandleTheSessionHolds()
|
||||
{
|
||||
var stats = new ScriptedStats();
|
||||
stats.Answers[4242] = Full(9216, 6000);
|
||||
using var reader = new GameMemoryReader(stats);
|
||||
using var handle = new SafeProcessHandle(new IntPtr(-1), ownsHandle: false);
|
||||
using var pin = new HeldPin(handle);
|
||||
|
||||
reader.Follow(GameProcess.Pinned(4242, pin));
|
||||
reader.TryRead(out ProcessReading r).Should().BeTrue();
|
||||
|
||||
stats.Reads.Should().ContainSingle().Which.Should().Be((4242u, 0ul, true), "the pin's own handle; no creation-time check is needed while it is held");
|
||||
r.VramDedicatedMb.Should().BeApproximately(9216, 0.001);
|
||||
r.VramSharedMb.Should().BeApproximately(64, 0.001);
|
||||
r.RamPrivateMb.Should().BeApproximately(6000, 0.001);
|
||||
r.RamWorkingSetMb.Should().BeApproximately(6100, 0.001);
|
||||
r.CommitMb.Should().BeApproximately(6200, 0.001);
|
||||
r.Processes.Should().Be(1);
|
||||
r.Sources.Should().Be(ProcessReadingSources.Counters | ProcessReadingSources.PrivateWorkingSetRead | ProcessReadingSources.HeldHandle);
|
||||
stats.Collects.Should().Be(1, "one counter collection per tick");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AnUnpinnedHoldSumsItsVerifiedProcessesAndLeavesOutAReusedOrRefusedPid()
|
||||
{
|
||||
var stats = new ScriptedStats();
|
||||
stats.Answers[100] = Full(1000, 500);
|
||||
stats.Answers[200] = Full(2000, 700);
|
||||
stats.Answers[300] = Full(4000, 900) with { RamStatus = 2 }; // FL_PS_RAM_PID_REUSED: another process now
|
||||
// 400 has no answer: the scripted DLL says OPEN_DENIED.
|
||||
using var reader = new GameMemoryReader(stats);
|
||||
DateTimeOffset t = DateTimeOffset.FromFileTime(133_000_000_000_000_000);
|
||||
|
||||
reader.Follow(GameProcess.Unpinned([new(100, t), new(200, t.AddSeconds(1)), new(300, t), new(400, t)]));
|
||||
reader.TryRead(out ProcessReading r).Should().BeTrue();
|
||||
|
||||
stats.Reads.Select(static x => x.Held).Should().AllBeEquivalentTo(false, "a hold that never pinned the game opens each process for the read");
|
||||
stats.Reads.First(static x => x.Pid == 200).Created.Should().Be((ulong)t.AddSeconds(1).ToFileTime(), "the snapshot's creation time is what the DLL checks");
|
||||
r.Processes.Should().Be(2, "only the two processes whose identity was verified count");
|
||||
r.VramDedicatedMb.Should().BeApproximately(3000, 0.001, "1000 + 2000 — never the reused pid's 4000");
|
||||
r.RamPrivateMb.Should().BeApproximately(1200, 0.001);
|
||||
r.Sources.Should().HaveFlag(ProcessReadingSources.TransientHandle);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AFieldNoProcessAnsweredStaysNullAndAnEmptyReadingIsNotAReading()
|
||||
{
|
||||
var stats = new ScriptedStats();
|
||||
stats.Answers[7] = new ProcessStatsSample { Present = 0x01 | 0x04, WorkingSetBytes = (ulong)(300 * _mib), CommitBytes = (ulong)(400 * _mib) };
|
||||
using var reader = new GameMemoryReader(stats);
|
||||
using var handle = new SafeProcessHandle(new IntPtr(-1), ownsHandle: false);
|
||||
using var pin = new HeldPin(handle);
|
||||
|
||||
reader.Follow(GameProcess.Pinned(7, pin));
|
||||
reader.TryRead(out ProcessReading r).Should().BeTrue();
|
||||
|
||||
r.VramDedicatedMb.Should().BeNull("no counter instance named the process: N/A, never 0");
|
||||
r.RamPrivateMb.Should().BeNull("Windows without PROCESS_MEMORY_COUNTERS_EX2: the private working set is N/A");
|
||||
r.RamWorkingSetMb.Should().BeApproximately(300, 0.001);
|
||||
r.Sources.Should().HaveFlag(ProcessReadingSources.WorkingSetReadOnly);
|
||||
|
||||
stats.Answers[7] = default;
|
||||
reader.TryRead(out ProcessReading none).Should().BeFalse();
|
||||
none.IsEmpty.Should().BeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void APinReleasedBeforeTheReadIsNothingToSayAndNeverAThrow()
|
||||
{
|
||||
var stats = new ScriptedStats();
|
||||
stats.Answers[9] = Full(100, 100);
|
||||
using var reader = new GameMemoryReader(stats);
|
||||
using var handle = new SafeProcessHandle(new IntPtr(-1), ownsHandle: true);
|
||||
using (var pin = new HeldPin(handle))
|
||||
{
|
||||
reader.Follow(GameProcess.Pinned(9, pin));
|
||||
}
|
||||
|
||||
reader.TryRead(out ProcessReading r).Should().BeFalse();
|
||||
r.IsEmpty.Should().BeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AReaderThatCouldNotOpenTriesAgainOnlyEveryFewTicksAndNoneIsFollowedAfterward()
|
||||
{
|
||||
var stats = new ScriptedStats { OpenFails = true };
|
||||
using var reader = new GameMemoryReader(stats);
|
||||
using var handle = new SafeProcessHandle(new IntPtr(-1), ownsHandle: false);
|
||||
using var pin = new HeldPin(handle);
|
||||
reader.Follow(GameProcess.Pinned(5, pin));
|
||||
|
||||
for (int i = 0; i < GameMemoryReader.ReopenEvery; i++)
|
||||
{
|
||||
reader.TryRead(out _).Should().BeFalse();
|
||||
}
|
||||
|
||||
stats.Opens.Should().Be(1, "the DLL is absent or out of memory: asking again every tick would only repeat the answer");
|
||||
stats.OpenFails = false;
|
||||
stats.Answers[5] = Full(10, 10);
|
||||
reader.TryRead(out ProcessReading r).Should().BeTrue("the back-off is over: the reader opens and reads");
|
||||
stats.Opens.Should().Be(2);
|
||||
r.VramDedicatedMb.Should().BeApproximately(10, 0.001);
|
||||
|
||||
reader.Follow(GameProcess.None);
|
||||
reader.TryRead(out _).Should().BeFalse("the session let the process go");
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,7 @@ namespace FrameLedger.Infrastructure.Tests.Telemetry;
|
||||
/// <c>spike-notes</c> §10 — this case only proves the port behaves under the real library.
|
||||
/// </remarks>
|
||||
[Trait("Category", "Integration")]
|
||||
[Collection(LibreHardwareMonitorCollection.Name)]
|
||||
public sealed class LhmRealHardwareTests
|
||||
{
|
||||
[Fact]
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
|
||||
|
||||
using System.Diagnostics;
|
||||
using System.Runtime.InteropServices;
|
||||
using FluentAssertions;
|
||||
using FrameLedger.Application.Telemetry;
|
||||
using FrameLedger.Infrastructure.Telemetry;
|
||||
|
||||
namespace FrameLedger.Infrastructure.Tests.Telemetry;
|
||||
|
||||
/// <summary>
|
||||
/// The managed mirror of <c>FlPsSample</c> against <c>FrameLedger.ProcessStats.dll</c>'s own size and ABI version (beta.12,
|
||||
/// D43), and one real read of this test's own process through the real DLL. Fails rather than skips when the DLL is not
|
||||
/// staged: a mirror test that quietly does nothing is a gate that cannot fail.
|
||||
/// </summary>
|
||||
public sealed class ProcessStatsMirrorTests
|
||||
{
|
||||
[Fact]
|
||||
public void TheMirrorIsTheSizeTheDllAnswersAndTheAbiVersionIsTheOneWeWroteAgainst()
|
||||
{
|
||||
NativeProcessStats.IsPresent.Should().BeTrue("FrameLedger.ProcessStats.dll must be staged beside the test binary (FrameLedger.ProcessStats.targets)");
|
||||
NativeProcessStats.LoadedAbiVersion.Should().Be(NativeProcessStats.AbiVersion);
|
||||
((uint)Marshal.SizeOf<ProcessStatsSample>()).Should().Be(NativeProcessStats.LoadedSampleSize);
|
||||
Marshal.SizeOf<ProcessStatsSample>().Should().Be(88);
|
||||
NativeProcessStats.LoadedBuildId.Should().NotBeNullOrEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ThisProcessesOwnMemoryReadsThroughTheRealDllWithTheLeastRight()
|
||||
{
|
||||
using var reader = new GameMemoryReader(new NativeProcessStats());
|
||||
using var self = Process.GetCurrentProcess();
|
||||
reader.Follow(GameProcess.Unpinned([new GameProcessId(self.Id, new DateTimeOffset(self.StartTime))]));
|
||||
|
||||
reader.TryRead(out ProcessReading r).Should().BeTrue("a process may always read its own counters");
|
||||
|
||||
r.Processes.Should().Be(1);
|
||||
r.RamWorkingSetMb.Should().BePositive();
|
||||
r.CommitMb.Should().BePositive();
|
||||
if (r.RamPrivateMb is { } privateWs)
|
||||
{
|
||||
privateWs.Should().BePositive().And.BeLessThanOrEqualTo(r.RamWorkingSetMb!.Value);
|
||||
}
|
||||
|
||||
// The video half depends on the machine: a test host that made no GPU allocation has no counter instance (N/A).
|
||||
r.Sources.Should().HaveFlag(ProcessReadingSources.TransientHandle);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AReusedPidIsRefusedRatherThanReadOffAStranger()
|
||||
{
|
||||
using var reader = new GameMemoryReader(new NativeProcessStats());
|
||||
using var self = Process.GetCurrentProcess();
|
||||
reader.Follow(GameProcess.Unpinned([new GameProcessId(self.Id, new DateTimeOffset(self.StartTime).AddSeconds(-5))]));
|
||||
|
||||
reader.TryRead(out ProcessReading r).Should().BeFalse("the creation time is not this process's");
|
||||
r.IsEmpty.Should().BeTrue();
|
||||
}
|
||||
}
|
||||
@@ -85,6 +85,53 @@ public sealed class TelemetryPollerTests
|
||||
system.Disposed.Should().BeTrue("the poller owns the system source with the layers");
|
||||
}
|
||||
|
||||
private sealed class FakeGame : IGameMemorySource
|
||||
{
|
||||
public List<GameProcess> Followed { get; } = [];
|
||||
|
||||
public ProcessReading? Next { get; set; }
|
||||
|
||||
public bool Disposed { get; private set; }
|
||||
|
||||
public void Follow(GameProcess target) => Followed.Add(target);
|
||||
|
||||
public bool TryRead(out ProcessReading reading)
|
||||
{
|
||||
reading = Next ?? default;
|
||||
return Next is not null;
|
||||
}
|
||||
|
||||
public void Dispose() => Disposed = true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// beta.12 (D43): the game process's memory rides the same tick, a tick only it answered is still queued, the target the
|
||||
/// capture loop names reaches the game source, and the poller owns it with the layers.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void TheGamesMemoryRidesTheSameTickAndTheFollowedProcessReachesItsSource()
|
||||
{
|
||||
using var layer = new FakeLayer(TelemetryLayer.Lhm);
|
||||
using var game = new FakeGame { Next = new ProcessReading(8192, 256, 6000, 6500, 7000, 1, ProcessReadingSources.Counters) };
|
||||
var poller = new TelemetryPoller(layer, new TelemetryPollerOptions(), new ManualTimeProvider(), ownsSource: true, system: null, game: game);
|
||||
GameProcess target = GameProcess.Unpinned([new GameProcessId(4242, DateTimeOffset.UnixEpoch)]);
|
||||
|
||||
poller.Follow(target);
|
||||
layer.Publish(null);
|
||||
poller.PollOnce();
|
||||
game.Next = null;
|
||||
poller.PollOnce();
|
||||
|
||||
var drained = new List<TelemetrySample>();
|
||||
poller.Drain(drained).Should().Be(1, "the second tick: nothing answered at all, so nothing is queued");
|
||||
drained[0].Game.VramDedicatedMb.Should().Be(8192);
|
||||
drained[0].Sample.Layer.Should().Be(TelemetryLayer.None, "only the game answered; the placeholder names no GPU layer");
|
||||
game.Followed.Should().Equal(target);
|
||||
|
||||
poller.Dispose();
|
||||
game.Disposed.Should().BeTrue("the poller owns the game source with the layers");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WithNoSystemSourceEverySampleCarriesAnEmptyReading()
|
||||
{
|
||||
|
||||
+24
-2
@@ -18,7 +18,9 @@
|
||||
Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
|
||||
|
||||
in its own comment syntax: `//` for C# and C++ (.cs .cpp .h .inl), `#` for PowerShell, `<!-- -->` for XAML
|
||||
(after an XML declaration when the file has one). The set is the tracked files with those extensions, minus
|
||||
(after an XML declaration when the file has one). The second line may name another copyright holder and year
|
||||
(`Copyright (C) <year> <holder> - additional terms under GPLv3 section 7: see NOTICE`, beta.12): a file a
|
||||
contributor wrote is theirs, under the same licence and the same additional terms (CONTRIBUTING.md). The set is the tracked files with those extensions, minus
|
||||
src/native/third_party/ (other people's code under their own licences). Generated files are generated WITH the
|
||||
header (tools/resx-gen.ps1), so a regenerated file passes as written.
|
||||
|
||||
@@ -38,6 +40,8 @@ $ErrorActionPreference = 'Stop'
|
||||
|
||||
$script:SpdxLine = 'SPDX-License-Identifier: GPL-3.0-only'
|
||||
$script:NoticeLine = 'Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE'
|
||||
# Any holder and year in the same form: a contributor's own file names its own copyright (CONTRIBUTING.md).
|
||||
$script:NoticePattern = '^Copyright \(C\) \d{4}(-\d{4})? \S.* - additional terms under GPLv3 section 7: see NOTICE$'
|
||||
$script:Extensions = @('.cs', '.cpp', '.h', '.inl', '.ps1', '.xaml')
|
||||
$script:Excluded = @('src/native/third_party/')
|
||||
|
||||
@@ -84,11 +88,21 @@ function Split-Preamble([byte[]]$Bytes, [string]$Extension) {
|
||||
return [pscustomobject]@{ Bom = $bom; Declaration = $declaration; Body = $text }
|
||||
}
|
||||
|
||||
# The second header line in its comment syntax, with any holder and year (the pattern above).
|
||||
function Test-NoticeLine([string]$Line, [string]$Extension) {
|
||||
$inner = switch ($Extension) {
|
||||
'.ps1' { if ($Line.StartsWith('# ', [StringComparison]::Ordinal)) { $Line.Substring(2) } else { $null } }
|
||||
'.xaml' { if ($Line.StartsWith('<!-- ', [StringComparison]::Ordinal) -and $Line.EndsWith(' -->', [StringComparison]::Ordinal)) { $Line.Substring(5, $Line.Length - 9) } else { $null } }
|
||||
default { if ($Line.StartsWith('// ', [StringComparison]::Ordinal)) { $Line.Substring(3) } else { $null } }
|
||||
}
|
||||
return $null -ne $inner -and $inner -cmatch $script:NoticePattern
|
||||
}
|
||||
|
||||
function Test-File([string]$Path, [string]$Extension) {
|
||||
$parts = Split-Preamble ([IO.File]::ReadAllBytes($Path)) $Extension
|
||||
$lines = $parts.Body -split "`r?`n", 3
|
||||
$want = Get-HeaderLines $Extension
|
||||
if ($lines.Count -ge 2 -and $lines[0] -ceq $want[0] -and $lines[1] -ceq $want[1]) { return $null }
|
||||
if ($lines.Count -ge 2 -and $lines[0] -ceq $want[0] -and (Test-NoticeLine $lines[1] $Extension)) { return $null }
|
||||
if ($lines.Count -ge 1 -and $lines[0] -match 'SPDX-License-Identifier') { return 'differs' }
|
||||
return 'missing'
|
||||
}
|
||||
@@ -195,6 +209,14 @@ if ($SelfTest) {
|
||||
if ($fixedStale -cne (((Get-HeaderLines '.cs') -join $crlf) + $crlf + $crlf + "namespace B;$crlf")) { throw 'self-test: a stale header must be replaced, not stacked' }
|
||||
$cases++
|
||||
|
||||
# 7. A contributor's own copyright line in the same form passes; one that drops the NOTICE pointer does not.
|
||||
[IO.File]::WriteAllText((Join-Path $tmp 'src/App/Theirs.cs'), "// $script:SpdxLine$crlf// Copyright (C) 2027 Jane Doe - additional terms under GPLv3 section 7: see NOTICE$crlf${crlf}namespace C;$crlf")
|
||||
[IO.File]::WriteAllText((Join-Path $tmp 'src/App/NoPointer.cs'), "// $script:SpdxLine$crlf// Copyright (C) 2027 Jane Doe$crlf${crlf}namespace D;$crlf")
|
||||
$r = Invoke-Check $tmp $false
|
||||
if ($r.Problems.Count -ne 1 -or $r.Problems[0] -notmatch 'NoPointer\.cs - header') { throw "self-test: another holder's line should pass and a line without the NOTICE pointer fail, got: $($r.Problems -join '; ')" }
|
||||
Remove-Item (Join-Path $tmp 'src/App/NoPointer.cs')
|
||||
$cases++
|
||||
|
||||
Write-Host "notice-check self-test OK - $cases cases, both directions"
|
||||
}
|
||||
finally {
|
||||
|
||||
@@ -40,7 +40,7 @@ Set-StrictMode -Version Latest
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
# Every binary that can end up inside a process we do not own.
|
||||
$required = @('FrameLedger.Overlay.dll', 'FrameLedger.VkLayer.dll', 'FrameLedger.Guard.dll', 'FrameLedger.NvapiBridge.dll')
|
||||
$required = @('FrameLedger.Overlay.dll', 'FrameLedger.VkLayer.dll', 'FrameLedger.Guard.dll', 'FrameLedger.NvapiBridge.dll', 'FrameLedger.ProcessStats.dll')
|
||||
|
||||
if (-not (Test-Path $BuildDir)) {
|
||||
Write-Host "VERSIONINFO CHECK FAILED: no native build at $BuildDir" -ForegroundColor Red
|
||||
|
||||
Reference in new issue
Block a user