feat(ipc): the C# mirror exists, and the gate that guards it stops being a Test-Path (#47)
CLAUDE.md calls the struct mirror the mechanism protecting the shared-memory ABI. NINE files described it in the present tense and none of it existed (20_OPEN_QUESTIONS R10): src/FrameLedger.Shared held a .csproj and no .cs files. The ring, the handshake and a real writer landed in #40-#44, so there is now a live ABI with nothing binding it to a managed reader -- which is the state the gate exists to prevent, not the one that made it unnecessary. ShmLayout.cs mirrors all four structs and their enums. It is driven by tools/fl-layout-dump's JSON rather than a transcribed table: a hand-written offset table in C# is a SECOND statement of the layout, and two statements of one fact drift, which is the defect the mirror exists to catch reintroduced inside the catcher. Same choice rules-validate.ps1 makes for the rules bounds. THE TEST ASSERTS BLITTABILITY, AND THAT IS NOT DECORATION. MEASURED: swap the `fixed byte BuildId[32]` for [MarshalAs(ByValTStr, SizeConst = 32)] public string -- the idiom this repository ALREADY USES, correctly, on NativeAntiCheatGuard's P/Invoke struct -- and Marshal.SizeOf stays 64 while every single Marshal.OffsetOf assertion still passes. Unsafe.SizeOf collapses to 40, because the string is an 8-byte reference rather than 32 inline bytes. That mirror looks correct by every obvious check and cannot be read out of a MemoryMappedViewAccessor, which is the one thing it exists for. Offsets structurally cannot see this, so RuntimeHelpers.IsReferenceOrContainsReferences and Unsafe.SizeOf are asserted alongside them. BOTH DIRECTIONS. The offset walk iterates the NATIVE field list, so a field added natively and forgotten here fails. A second test walks the other way, and it caught something on its first run: fl-layout-dump was not emitting the `reserved` tails, so the C# mirror declared members the dump could not confirm. Fixed in the dump rather than excluded from the check -- a dump that quietly stops reporting a field would otherwise shrink what the mirror verifies while every assertion still passed. THE GATE WAS THE BIGGER FINDING. build.ps1's struct-mirror step was `Test-Path src/FrameLedger.Shared/ShmLayout.cs` and then printed "covered by dotnet test". It never looked for the test. So creating an EMPTY ShmLayout.cs would have turned an honest loud skip into a silent green, and deleting or renaming the mirror test afterwards would have kept it green forever -- a gate whose verdict is decided before it looks, guarding the mechanism CLAUDE.md calls the protection for the shm ABI. It now reads the trx from the run that just happened (--logger trx added to the test step) and requires the named class to have EXECUTED and passed. dotnet test makes a regression red; this makes DELETING the regression test red, which is a different failure and the one a Test-Path can never see. THREE CANARIES, EACH PROVEN RED, PLUS RECOVERY: RED offsets swap OutputW/OutputH -> "Expected 22 ... but found 24" RED blittability ByValTStr string -> "Expected Unsafe.SizeOf to be 64 ... found 40" RED the GATE rename the test class away The third is the one that matters and it had to be built carefully: with the class renamed, the build succeeds, dotnet format is clean, and ALL 132 MANAGED TESTS PASS -- all 8 mirror assertions included, just under another name. The only thing that fails is the gate, at build.ps1:358. Restored: PASSED WITH 1 SKIPPED GATE(S), 8 mirror assertions executed. The skip count drops from 2 to 1. MY CANARY HARNESS WAS BROKEN TWICE BEFORE IT PROVED ANYTHING, which is the fourth and fifth time on this project. First the renamed class tripped MA0048 (file name must match type name) and the run died at BUILD, never reaching the gate. Then `sed` rewrote the file with LF endings and the run died at dotnet format, also never reaching the gate. Both printed a failure, and a failure that stops before the gate proves nothing about the gate. The restore stamps LastWriteTime for the same family of reason. Analyzer suppressions are scoped to FrameLedger.Shared and each is justified in the csproj: obeying CA1028 (widen the enum), CA1711 (rename FlRtFlags), CA1051 (properties instead of fields) or CA1815 (implement Equals) would BREAK the mirror or make it unaddressable by Marshal.OffsetOf. MA0048 and CA1716 are scoped-down style rules. AnalysisLevel is not turned down. STILL OPEN, and marked half-closed rather than closed: S23-1. The mirror can now READ buildId out of the handshake, but the Agent has no build id of its OWN to compare it against, so 07_IPC's refuse-to-attach-on-mismatch still cannot run. The drain PR owns that half. The eight remaining present-tense claims are flipped in the same commit -- CLAUDE.md, fl_shm.h, the Shared csproj, 12_BUILD (which contradicted itself across 86 lines), 14_TESTING, fl-layout-dump's CMakeLists and main.cpp, and build.ps1's own explanatory comment. build.ps1 check: PASSED WITH 1 SKIPPED GATE(S) in 54s, 15/15 ctests, 132 managed tests. The one remaining skip is resx-audit. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
2efa1701fe
commit
bff0f6a81c
13 files changed
+715
-66
No files matched your search
@@ -79,9 +79,13 @@ Dependency direction unchanged: `App/Agent → Application → Domain`; `Infrast
|
||||
|
||||
**C++ —** `clang-format` (LLVM base, 4-space, 120 col) enforced in CI. No STL containers that allocate in hook paths. No `std::mutex` in hook paths. `-D_HAS_EXCEPTIONS=0` in the Overlay target. Every hook entry point wrapped per the `FL_HOOK_GUARD` macro (`17_HOOK_ENGINE`). Static analysis: `/analyze` + clang-tidy (`bugprone-*`, `cert-*`, `concurrency-*`).
|
||||
|
||||
**Struct mirroring —** `FlFrameRecord` is **specified** to exist twice (C++ header, C# `[StructLayout(LayoutKind.Sequential)]`), with a test asserting `sizeof` and every field offset on both sides, and a version constant in the shm header that must match or the Agent refuses to attach.
|
||||
**Struct mirroring —** `FlFrameRecord`, `FlShmHandshake`, `FlWriterState` and `FlControlBlock` each exist twice: `src/native/FrameLedger.Shm/include/fl_shm.h` (**normative**) and `src/FrameLedger.Shared/ShmLayout.cs` as `[StructLayout(LayoutKind.Sequential)]`. `ShmLayoutMirrorTests` asserts size and every field offset on both sides **against JSON emitted by `tools/fl-layout-dump`**, never a transcribed table, and walks the field list in both directions so a field added on either side alone fails.
|
||||
|
||||
**It exists once.** This paragraph was in the present tense until 2026-08-05 and was false: `src/FrameLedger.Shared/` holds a `.csproj` and no `.cs` files, `grep -rn FlFrameRecord src tests --include=*.cs` returns nothing, and `FL_BUILD_ID` — the input to the refuse-to-attach comparison — has a producer and no reader. `build.ps1:324-329` enumerates **nine** files that described the mechanism as live, including `fl_shm.h` (normative) and `fl-layout-dump/CMakeLists.txt` (a build file); `build.ps1:335-342` skips the gate loudly instead of pretending it runs. Tracked as `20_OPEN_QUESTIONS` §R10 and scheduled in §S24. **Until it lands, changing a field in `fl_shm.h` breaks the Agent at runtime rather than at build time** — treat the layout as frozen unless you are the one building the mirror. Same reading rule as §Dev mode below, and the same reason: a doc that says a gate runs is worse than one that says it is missing.
|
||||
It also asserts **blittability** (`RuntimeHelpers.IsReferenceOrContainsReferences`), because offsets cannot see it: measured 2026-08-05, swapping the `fixed byte BuildId[32]` for this repo's own `[MarshalAs(ByValTStr)] string` idiom keeps `Marshal.SizeOf` at 64 and every offset correct while `Unsafe.SizeOf` collapses to **40** — a mirror that passes the obvious checks and cannot be read out of a memory-mapped view.
|
||||
|
||||
`build.ps1`'s `struct-mirror` gate reads the run's `.trx` and fails when that test class did not execute, so **deleting the test is red too** — it used to `Test-Path` a source file and report on a test it never looked for.
|
||||
|
||||
> **Still open:** the version handshake is only half wired. `FL_BUILD_ID` has a producer and the mirror can now read it out of the handshake, but the Agent has **no build id of its own** to compare against, so `07_IPC`'s refuse-to-attach-on-mismatch cannot yet run (`20_OPEN_QUESTIONS` §S23-1). The drain PR owns that.
|
||||
|
||||
**Dev mode —** `FL_MOCK=1` is **specified but not implemented** — `grep -rn FL_MOCK src tests tools build.ps1` returns nothing (recorded 2026-08-04). When it exists it runs the whole app with a synthetic frame source and no injection at all, and it is how the UI is meant to be developed; until then, do not plan work on the assumption that it is there. `tools/hook-harness` is a dummy **D3D11 + D3D12** app used to exercise hooks without a real game; Vulkan and OpenGL modes are unwritten (`docs/12_BUILD.md` §Targets is the accurate list).
|
||||
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
<Project>
|
||||
|
||||
<!--
|
||||
Ships fl-layout-dump.exe beside the importing project's output.
|
||||
|
||||
It emits the native shared-memory struct layout as JSON, and
|
||||
ShmLayoutMirrorTests consumes it to assert that the C# mirrors in
|
||||
FrameLedger.Shared match fl_shm.h field for field. That is the mechanism
|
||||
CLAUDE.md §Struct mirroring calls the protection for the shm ABI, and until
|
||||
2026-08-05 it did not exist: nine files described it in the present tense
|
||||
while src/FrameLedger.Shared held only a .csproj.
|
||||
|
||||
WHY THE DUMP AND NOT A TABLE IN THE TEST. A hand-written offset table in C#
|
||||
is a SECOND statement of the layout, and two statements of one fact drift —
|
||||
which is the defect the whole mirror exists to catch, reintroduced in the
|
||||
thing catching it. tools/rules-validate.ps1 makes the same choice for the
|
||||
rules bounds: extract the constants from the header, and FAIL rather than
|
||||
skip if they cannot be read.
|
||||
|
||||
Imported by exactly one project: FrameLedger.Infrastructure.Tests.
|
||||
|
||||
Unlike FrameLedger.Guard.targets this stages a TOOL, not a shipped artifact.
|
||||
It never reaches out/app: nothing in the product runs it, and an executable
|
||||
that dumps internal layout has no business in a release.
|
||||
-->
|
||||
<PropertyGroup>
|
||||
<FlLayoutDumpDir>$(MSBuildThisFileDirectory)build\native\x64-release\tools\fl-layout-dump\</FlLayoutDumpDir>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Include="$(FlLayoutDumpDir)fl-layout-dump.exe" Condition="Exists('$(FlLayoutDumpDir)fl-layout-dump.exe')">
|
||||
<Link>fl-layout-dump.exe</Link>
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
<!--
|
||||
Warn at BUILD time, fail at TEST time. build.ps1 runs the native build first,
|
||||
so by the time this evaluates the exe exists; a hard error here would make
|
||||
`dotnet build` on a fresh clone fail for a reason unrelated to managed code.
|
||||
|
||||
The test itself does NOT extend that courtesy: a mirror test that cannot find
|
||||
its native input reports FAILED, never "skipped", because "could not look"
|
||||
reading as "looked and it matched" is exactly the defect class this
|
||||
repository keeps recording.
|
||||
-->
|
||||
<Target Name="FlWarnOnMissingLayoutDump" AfterTargets="Build"
|
||||
Condition="!Exists('$(FlLayoutDumpDir)fl-layout-dump.exe')">
|
||||
<Warning Text="fl-layout-dump.exe was not found at $(FlLayoutDumpDir). Run build.ps1 native first; ShmLayoutMirrorTests will fail without it." />
|
||||
</Target>
|
||||
|
||||
</Project>
|
||||
@@ -234,8 +234,11 @@ function Invoke-Managed([bool]$FixFormat) {
|
||||
# Clear them so the gate below sees this run and only this run.
|
||||
Get-ChildItem (Join-Path $repo 'tests') -Directory -Filter 'TestResults' -Recurse -ErrorAction SilentlyContinue |
|
||||
Remove-Item -Recurse -Force -ErrorAction SilentlyContinue
|
||||
# --logger trx so downstream gates can assert that a NAMED test executed,
|
||||
# not merely that the run was green. The struct-mirror gate below reads it.
|
||||
Invoke-Checked 'dotnet test' {
|
||||
dotnet test $solution -c $Configuration --no-build --collect:"XPlat Code Coverage"
|
||||
dotnet test $solution -c $Configuration --no-build --collect:"XPlat Code Coverage" `
|
||||
--logger 'trx;LogFileName=results.trx'
|
||||
}
|
||||
|
||||
# The cobertura reports above were produced and ignored from the day the
|
||||
@@ -322,25 +325,45 @@ function Invoke-ProjectGates {
|
||||
}
|
||||
|
||||
# The shared-memory struct mirror. CLAUDE.md §Struct mirroring calls this the
|
||||
# mechanism protecting the shm ABI, and NINE files describe it in the present
|
||||
# tense — including fl_shm.h itself, which is normative, and
|
||||
# fl-layout-dump/CMakeLists.txt, which says a test consumes its output. None
|
||||
# of it exists: src/FrameLedger.Shared holds only a .csproj, nothing under
|
||||
# tests/ references FlFrameRecord, and fl-layout-dump has no add_test.
|
||||
# mechanism protecting the shm ABI, and NINE files described it in the present
|
||||
# tense while none of it existed. It exists as of 2026-08-05.
|
||||
#
|
||||
# Named and SKIPPED LOUDLY rather than omitted, which is the discipline
|
||||
# 20_OPEN_QUESTIONS §R10 asks for: a doc that says a gate runs is worse than
|
||||
# one that says it is missing, because the second prompts someone to write it.
|
||||
# Not urgent — the ring is P1 and there is nothing to mirror yet.
|
||||
# THIS GATE USED TO BE A Test-Path ON A SOURCE FILE, and printed "covered by
|
||||
# dotnet test" from that alone. It never looked for the test. So creating an
|
||||
# EMPTY ShmLayout.cs would have turned the loud skip into a silent green, and
|
||||
# deleting or renaming the mirror test afterwards would have kept it green
|
||||
# forever — a gate whose verdict is decided before it looks, guarding the one
|
||||
# mechanism CLAUDE.md calls the protection for the shm ABI.
|
||||
#
|
||||
# It now reads the trx from the run that just happened and requires the named
|
||||
# test class to have EXECUTED and passed. `dotnet test` is what makes a
|
||||
# regression red; this makes DELETING the regression test red too, which is a
|
||||
# different failure and the one a Test-Path can never see.
|
||||
Write-Step 'struct-mirror'
|
||||
$mirrorTest = Join-Path $repo 'src/FrameLedger.Shared/ShmLayout.cs'
|
||||
if (Test-Path $mirrorTest) {
|
||||
Write-Host ' covered by dotnet test (FrameLedger.Infrastructure.Tests)' -ForegroundColor DarkGray
|
||||
$trx = Get-ChildItem (Join-Path $repo 'tests') -Recurse -Filter 'results.trx' -ErrorAction SilentlyContinue
|
||||
if (-not $trx) {
|
||||
throw "struct-mirror: no results.trx from this run — the gate cannot confirm the mirror test executed"
|
||||
}
|
||||
else {
|
||||
Skip-Gate 'struct-mirror' 'the C# mirror of fl_shm.h does not exist yet (20_OPEN_QUESTIONS §R10) — the shm ABI has no drift gate'
|
||||
|
||||
$mirrorResults = @()
|
||||
foreach ($file in $trx) {
|
||||
$xml = [xml](Get-Content -LiteralPath $file.FullName -Raw)
|
||||
$mirrorResults += $xml.TestRun.Results.UnitTestResult |
|
||||
Where-Object { $_ -and $_.testName -and $_.testName -match 'ShmLayoutMirrorTests' }
|
||||
}
|
||||
|
||||
if ($mirrorResults.Count -eq 0) {
|
||||
# The failure mode the old gate could not express: the mirror test is
|
||||
# gone, renamed or filtered out, and everything else is still green.
|
||||
throw "struct-mirror: ShmLayoutMirrorTests did not run. The shm ABI has no drift gate — a mirror test that is absent must fail, not pass quietly (20_OPEN_QUESTIONS §R10)"
|
||||
}
|
||||
|
||||
$failed = @($mirrorResults | Where-Object { $_.outcome -ne 'Passed' })
|
||||
if ($failed.Count -gt 0) {
|
||||
throw "struct-mirror: $($failed.Count) of $($mirrorResults.Count) mirror assertions did not pass"
|
||||
}
|
||||
Write-Host " $($mirrorResults.Count) mirror assertion(s) executed and passed (fl_shm.h vs FrameLedger.Shared)" -ForegroundColor DarkGray
|
||||
|
||||
Write-Step 'placeholder guard'
|
||||
# {{RELEASE_DATE}} is substituted at release time and is the only token
|
||||
# allowed to survive. Anything else in a document FR-11 displays for
|
||||
|
||||
+2
-2
@@ -49,9 +49,9 @@ Compiler/linker flags (enforced in CMake, not per-target ad hoc): `/std:c++20 /M
|
||||
- **Native output reaches the managed side through `.targets` files imported by `FrameLedger.Agent`**, not through `FrameLedger.Infrastructure`: `/FrameLedger.Guard.targets` (the guard DLL), `/FrameLedger.Overlay.targets` (the payload, §S22) and `/FrameLedger.Rules.targets` (the blocklist seed). Ordering comes from `build.ps1`, which runs the native build first — **not** from the solution: `FrameLedger.slnx` contains no native project.
|
||||
|
||||
> **This bullet was wrong in four ways and is corrected 2026-08-04.** It named a copy of `FrameLedger.Injector.exe`, which §S9 closed and which line 25 above says does not exist, 24 lines earlier in the same document. It attributed the copying to a build target in `FrameLedger.Infrastructure.csproj`, which contains no `<Target>` at all. It said the copies happen there, when the guard DLL was deliberately moved out to a `.targets` file so it would stop flowing to every referencing project (§S18 blocker 3). And it credited the solution with an ordering the solution cannot express.
|
||||
- **Struct mirror check — ⏳ SPECIFIED, NOT BUILT.** The intent: a test in `FrameLedger.Infrastructure.Tests` reads offsets emitted by a generated header dump from the native build and asserts they match the C# `[StructLayout]` mirror. Struct drift between the two layers is the most dangerous silent bug in this architecture.
|
||||
- **Struct mirror check — ✅ built 2026-08-05.** `ShmLayoutMirrorTests` runs `tools/fl-layout-dump`, reads its JSON, and asserts size plus every field offset against the C# `[StructLayout]` mirrors in `FrameLedger.Shared` — in **both directions**, so a field on either side alone fails. It also asserts blittability, which offsets cannot see. The `struct-mirror` gate reads the run's `.trx` and fails when that test class did not execute, so deleting the test is red as well as breaking it. Struct drift between the two layers is the most dangerous silent bug in this architecture; the build now genuinely catches it.
|
||||
|
||||
> **The last clause used to read "the build catches it", in the present tense, and it does not.** `src/FrameLedger.Shared/` holds a `.csproj` and no `.cs` files; nothing under `tests/` references `FlFrameRecord`; `build.ps1` skips the gate loudly for exactly this reason. **This document contradicted itself** — line 138 below has said so correctly all along. `20_OPEN_QUESTIONS` §R10 tracks it and §S24 schedules it. When the mirror lands, this bullet and the eight other present-tense sites `build.ps1:324-329` enumerates flip together.
|
||||
> Until 2026-08-05 this bullet ended "the build catches it" in the present tense, while `src/FrameLedger.Shared/` held a `.csproj` and no `.cs` files — **and this document contradicted itself**, because line 138 below said correctly all along that the gate did not exist. `20_OPEN_QUESTIONS` §R10 has the history.
|
||||
|
||||
## Debugging
|
||||
|
||||
|
||||
+1
-1
@@ -20,7 +20,7 @@ The anti-cheat guard is the one component where a bug can cost someone an accoun
|
||||
- **Ring buffer:** SPSC correctness under a hammering writer thread; seqlock torn-read detection; wrap and overwrite-oldest semantics; power-of-two capacity assumptions. Include the **one-full-lap case**: a reader stalled exactly `capacity` records must not validate a different frame as unchanged (this is what the never-reset `seq` counter defends, `07_IPC` §Protocol rules).
|
||||
- **Drop accounting:** the reader-side computation (`writeIndex - readIndex > capacity`) reports the right count and resumes at the right index. The writer has no drop counter to test — by design.
|
||||
- **Torn records produce gap markers,** not silently shortened streams; a golden test asserts the gap does not appear as a stutter.
|
||||
- **Record and header layout:** `static_assert(sizeof(...) == 64)` and `offsetof` assertions for `FlFrameRecord` **and all three header structs** (`FlShmHandshake`, `FlWriterState`, `FlControlBlock`) — the Agent reads across the process boundary in every one of them. The native half is done — `layout_test.cpp` plus the `static_assert`s in `fl_shm.h`, ctest `fl_shm_layout`. **The managed half is not: `tools/fl-layout-dump` emits the runtime offset dump and nothing consumes it** (`20_OPEN_QUESTIONS` §R10, scheduled in §S24). This clause read "Runtime offset dump consumed by the managed struct-mirror test" until 2026-08-05, which described a consumer that does not exist.
|
||||
- **Record and header layout:** `static_assert(sizeof(...) == 64)` and `offsetof` assertions for `FlFrameRecord` **and all three header structs** (`FlShmHandshake`, `FlWriterState`, `FlControlBlock`) — the Agent reads across the process boundary in every one of them. Both halves exist as of 2026-08-05: the native side is `layout_test.cpp` plus the `static_assert`s (ctest `fl_shm_layout`), and the runtime offset dump from `tools/fl-layout-dump` is consumed by `ShmLayoutMirrorTests`, which walks the field list in **both directions** and additionally asserts blittability — `Marshal.SizeOf` and every offset stay correct for a mirror that uses `[MarshalAs(ByValTStr)] string`, while `Unsafe.SizeOf` drops from 64 to 40 and the struct can no longer be read from a mapped view.
|
||||
- **Fault policy:** injected SEH faults in a fake hook body → counter increments, original still called, self-disable at 3.
|
||||
- **Hook index verification, by behaviour.** A vtable slot carries no identity, so "check that slot 8 *is* `Present`" is not a question the runtime can answer — the earlier wording here required something unimplementable. What is answerable: patch the slot, call the method, see whether the detour ran (`17_HOOK_ENGINE` §Getting vtable addresses; proved for slots 8, 13 and 22 in `spike-notes.md` §H4). Runs headless on CI via WARP and `CreateSwapChainForComposition`. A deliberate mismatch aborts installation instead of patching.
|
||||
- **Every probe must be shown to fail.** A probe that ends in an unconditional assertion is green by construction and its ctest is decorative — `fl_proxy_swapchain` shipped in exactly that state. Before a probe counts as a regression net, break the thing it watches and watch it go red.
|
||||
|
||||
@@ -57,7 +57,7 @@ or it becomes the next stale status claim this file exists to record.
|
||||
| **S13(c)** | 🅓 **deferred, rationale written** | Same decision as S1; (a) and (b) were already settled |
|
||||
| **S19(b)** | 🅓 **deferred, rationale written** | Its true shape is a `CryptCATAdmin*` PR, and `WinVerifyTrust`'s default revocation check does network I/O from inside the hard gate (NFR-10) |
|
||||
| **S14** | 🔨 **scheduled — exe-name half only** | Owner decision 2026-08-05: wire it, empty list, unresolvable identity refuses. The **store-id half is blocked** on the platform metadata extractors and cannot be reached through the guard ABI by design |
|
||||
| **S23-1** | 🔨 **scheduled** | `FL_BUILD_ID` gets its first reader with the C# mirror |
|
||||
| **S23-1** | ◐ **half closed 2026-08-05** | The C# mirror can now READ `buildId` out of the handshake. The Agent still has **no build id of its own** to compare it against, so `07_IPC`'s refuse-to-attach-on-mismatch still cannot run. The drain PR owns the other half |
|
||||
| **S23-4** | ✅ **resolved 2026-08-05** | `19_SAFETY` §During a session said "the module scan and the driver scan"; `EvaluateImpl` runs four. Reworded to "every pre-injection check" so it cannot go stale when a check is added, with the two omissions named — `services` is the only tier measured firing on real anti-cheat, and the pre-scan is the only one touching the filesystem |
|
||||
| **S2 part three** | ⏳ **open, sequenced** | In-layer supervision lands with `vkQueuePresentKHR` (P1). Building it sooner would be a predicate whose wrong answer changes nothing observable |
|
||||
| **S4 signing** | ⏳ **open, residual accepted** | HTTPS authenticates the host, not the content. Recorded rather than closed — needs a rationale written or a decision |
|
||||
|
||||
@@ -4,21 +4,71 @@
|
||||
IPC contracts (System.Text.Json source-generated contexts, docs/07_IPC.md)
|
||||
and the C# mirrors of the native shared-memory structs.
|
||||
|
||||
THIS PROJECT IS EMPTY. It contains no .cs files, and the paragraph below
|
||||
described its intended contents in the PRESENT TENSE until 2026-08-05:
|
||||
"each exist twice", "a test ... asserts". Neither is true: the mirrors exist
|
||||
only in C++ (src/native/FrameLedger.Shm/include/fl_shm.h) and no managed
|
||||
test references FlFrameRecord. build.ps1:335-342 skips the gate loudly and
|
||||
says why; build.ps1:324-329 enumerates the nine files that claimed
|
||||
otherwise, of which this was one.
|
||||
The mirrors are the dangerous part: FlFrameRecord, FlShmHandshake,
|
||||
FlWriterState and FlControlBlock each exist twice, once in C++
|
||||
(src/native/FrameLedger.Shm/include/fl_shm.h, which is NORMATIVE) and once
|
||||
here as [StructLayout(LayoutKind.Sequential)]. ShmLayoutMirrorTests asserts
|
||||
size AND every field offset on both sides against the JSON emitted by
|
||||
tools/fl-layout-dump, and asserts that every mirror is BLITTABLE — offsets
|
||||
alone cannot see the difference between a fixed buffer and a marshalled
|
||||
string, and only one of those can be read out of a memory-mapped view.
|
||||
|
||||
THE INTENT, unchanged and now scheduled (20_OPEN_QUESTIONS §R10, §S24):
|
||||
FlFrameRecord, FlShmHandshake, FlWriterState and FlControlBlock each exist
|
||||
twice, once in C++ and once here as [StructLayout(LayoutKind.Sequential)],
|
||||
with a test in FrameLedger.Infrastructure.Tests asserting sizeof AND every
|
||||
field offset on both sides against the dump emitted by tools/fl-layout-dump.
|
||||
Struct drift between the two layers is the most dangerous silent bug in this
|
||||
architecture (CLAUDE.md §Struct mirroring, docs/12_BUILD.md §Managed build).
|
||||
architecture: nothing crashes, the Agent just reads garbage into fields that
|
||||
look plausible (CLAUDE.md §Struct mirroring, docs/12_BUILD.md §Managed build).
|
||||
|
||||
The IPC contracts half is still unwritten; only the mirrors are here.
|
||||
-->
|
||||
|
||||
<PropertyGroup>
|
||||
<!--
|
||||
For `fixed byte BuildId[32]` and `fixed uint Reserved[N]`. Those are the
|
||||
native char[32] / uint32[N] arrays, and a fixed buffer is the only C#
|
||||
construct that reproduces them WITHOUT making the struct non-blittable.
|
||||
[MarshalAs(ByValTStr)] would satisfy every offset assertion and then fail
|
||||
to read out of a MemoryMappedViewAccessor, which is the entire purpose.
|
||||
-->
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
|
||||
<!--
|
||||
FOUR ANALYZER RULES ARE SUPPRESSED FOR THIS PROJECT ONLY, and each is
|
||||
suppressed because obeying it would BREAK THE MIRROR. That is the whole
|
||||
justification: these types are not a C# API, they are a byte-for-byte
|
||||
restatement of fl_shm.h, and every one of these rules is advice about
|
||||
idiomatic C# API design.
|
||||
|
||||
CA1028 "make the underlying type Int32". The native enums are uint32_t
|
||||
(FlStatus) and uint8_t (FlApi, FlUpscaler, FlFgMode, FlRtFlags,
|
||||
FlMeasured). Widening any of them changes the size of the field
|
||||
that carries it and the mirror test fails, which is the test
|
||||
doing its job against a change this rule would have caused.
|
||||
CA1711 "do not end a type name in 'Flags'". FlRtFlags IS the native
|
||||
name. Renaming it makes the two sides harder to diff by eye,
|
||||
which is how a drifting field gets missed in review.
|
||||
CA1716 the namespace FrameLedger.Shared collides with a VB keyword.
|
||||
It is the namespace CLAUDE.md §Solution layout assigns, it
|
||||
predates this file, and renaming it is a solution-wide change
|
||||
for a language this project does not target.
|
||||
MA0048 one type per file. This file mirrors ONE header, and the four
|
||||
structs plus their enums are a single contract that has to be
|
||||
read together — the region offsets only make sense beside the
|
||||
structs they bound. Splitting a 64-byte ABI across ten files
|
||||
makes the thing this project exists to keep consistent harder
|
||||
to check, and the mirror test is what enforces it either way.
|
||||
CA1051 "do not declare visible instance fields". Public fields are the
|
||||
point: Marshal.OffsetOf and the mirror test address them by
|
||||
name, and properties have no defined offset at all. A property
|
||||
cannot mirror a struct member.
|
||||
CA1815 "override Equals and ==". These are windows onto shared memory,
|
||||
not values anyone compares. Two records with identical bytes are
|
||||
two different frames, so a meaningful Equals does not exist —
|
||||
and writing one over a `fixed byte[32]` would be ceremony that
|
||||
obscures the layout this file exists to state plainly.
|
||||
|
||||
Everything else stays on: this is a targeted list, not AnalysisLevel
|
||||
turned down.
|
||||
-->
|
||||
<NoWarn>$(NoWarn);CA1028;CA1711;CA1716;MA0048;CA1051;CA1815</NoWarn>
|
||||
</PropertyGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,304 @@
|
||||
// The C# half of the shared-memory ABI. The C++ half is
|
||||
// src/native/FrameLedger.Shm/include/fl_shm.h and it is NORMATIVE: where the two
|
||||
// disagree, that header is right and this file is the bug.
|
||||
//
|
||||
// WHY THESE ARE FIXED BUFFERS AND NOT [MarshalAs(ByValTStr)] string.
|
||||
//
|
||||
// The obvious idiom for a native `char[32]` is
|
||||
// `[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string BuildId`,
|
||||
// and this repository already uses it once (NativeAntiCheatGuard's FlGuardResult,
|
||||
// which is fine there -- that struct crosses a P/Invoke boundary, where the
|
||||
// marshaller runs). It would pass every offset assertion in the mirror test and
|
||||
// still be wrong here, because a struct containing a `string` is NOT BLITTABLE:
|
||||
// it cannot be read straight out of a MemoryMappedViewAccessor, which is the one
|
||||
// thing this type exists to do. The test asserts blittability directly
|
||||
// (RuntimeHelpers.IsReferenceOrContainsReferences) precisely because offsets
|
||||
// cannot see the difference.
|
||||
//
|
||||
// Every struct is `Size = 64` to match `alignas(64)` on the native side. The
|
||||
// three header regions are separate cache lines on purpose (fl_shm.h): the
|
||||
// Overlay writes region 2 every frame while the Agent writes region 3 every
|
||||
// second, and sharing a line would put a cross-process cache-line bounce on the
|
||||
// hot path.
|
||||
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace FrameLedger.Shared;
|
||||
|
||||
/// <summary>Constants mirrored from <c>fl_shm.h</c>. Drift here is caught by the mirror test.</summary>
|
||||
public static class ShmLayout
|
||||
{
|
||||
/// <summary>
|
||||
/// Bumped whenever ANY struct below changes. The Agent refuses to attach on mismatch and tells the
|
||||
/// user to restart the game — the DLL lives inside a running process, so the two sides cannot be
|
||||
/// assumed to update in lockstep.
|
||||
/// </summary>
|
||||
public const uint LayoutVersion = 2u;
|
||||
|
||||
public const uint HandshakeOffset = 0x00u;
|
||||
public const uint WriterOffset = 0x40u;
|
||||
public const uint ControlOffset = 0x80u;
|
||||
public const uint RingOffset = 0xC0u;
|
||||
|
||||
/// <summary>8192 × 64 B = 512 KiB, ≈16 s at 500 fps.</summary>
|
||||
public const uint DefaultCapacity = 8192u;
|
||||
|
||||
/// <summary>
|
||||
/// How long a capture side keeps observing without seeing <c>guardTicks</c> advance: two missed
|
||||
/// 30 s scans, because one late tick is noise and a tick is late whenever the machine is busy.
|
||||
/// </summary>
|
||||
public const uint GuardTickDeadlineMs = 65000u;
|
||||
|
||||
/// <summary>Total mapping size for a given ring capacity. Mirrors <c>FlShmSizeForCapacity</c>.</summary>
|
||||
public static long SizeForCapacity(uint capacity) => RingOffset + ((long)capacity * 64L);
|
||||
}
|
||||
|
||||
/// <summary>Values published in <see cref="FlWriterState.Status"/>.</summary>
|
||||
public enum FlStatus : uint
|
||||
{
|
||||
Init = 0,
|
||||
Ready = 1,
|
||||
|
||||
/// <summary>Three hook faults; see <c>17_HOOK_ENGINE</c> §Fault policy.</summary>
|
||||
SelfDisabled = 2,
|
||||
Unhooked = 3,
|
||||
}
|
||||
|
||||
/// <summary>Bits in <see cref="FlWriterState.ApiMask"/>, and the value of <see cref="FlFrameRecord.Api"/>.</summary>
|
||||
public enum FlApi : byte
|
||||
{
|
||||
Unknown = 0,
|
||||
D3D11 = 1,
|
||||
D3D12 = 2,
|
||||
Vulkan = 3,
|
||||
OpenGL = 4,
|
||||
|
||||
// No D3D9: those titles are almost entirely 32-bit and the Overlay is x64-only.
|
||||
}
|
||||
|
||||
public enum FlUpscaler : byte
|
||||
{
|
||||
None = 0,
|
||||
Dlss = 1,
|
||||
DlssRr = 2,
|
||||
Fsr2 = 3,
|
||||
Fsr3 = 4,
|
||||
Fsr4 = 5,
|
||||
XeSS = 6,
|
||||
Nis = 7,
|
||||
|
||||
/// <summary>A hook ran and could not identify what it saw. Different from "not measured".</summary>
|
||||
Unknown = 0xFF,
|
||||
}
|
||||
|
||||
public enum FlFgMode : byte
|
||||
{
|
||||
None = 0,
|
||||
DlssG = 1,
|
||||
FsrFg = 2,
|
||||
XeFg = 3,
|
||||
|
||||
/// <summary>A hook ran and could not identify what it saw. Different from "not measured".</summary>
|
||||
Unknown = 0xFF,
|
||||
|
||||
// No AFMF: driver-side frame generation happens after present and is invisible to an in-process hook.
|
||||
}
|
||||
|
||||
/// <summary>Bits in <see cref="FlFrameRecord.RtFlags"/>.</summary>
|
||||
[Flags]
|
||||
public enum FlRtFlags : byte
|
||||
{
|
||||
None = 0,
|
||||
|
||||
/// <summary>Catches inline RayQuery, which DispatchRays alone misses.</summary>
|
||||
AsBuild = 1 << 0,
|
||||
DispatchRays = 1 << 1,
|
||||
PsoAlive = 1 << 2,
|
||||
|
||||
/// <summary>
|
||||
/// "We did not look." When this is set the other three carry no information and the Agent must map
|
||||
/// the frame to N/A, never to No — zero would otherwise be a MEASURED negative, and a present-only
|
||||
/// writer with no RT hooks would assert "this title does not ray-trace" ~118 times a second.
|
||||
/// </summary>
|
||||
NotMeasured = 1 << 3,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Which fields a frame actually MEASURED. A bit CLEAR means "not measured": render N/A and do not
|
||||
/// aggregate. The zero-defaults elsewhere in the record are affirmative negatives, and a writer that has
|
||||
/// not installed the corresponding hook is not entitled to make them.
|
||||
/// </summary>
|
||||
[Flags]
|
||||
public enum FlMeasured : byte
|
||||
{
|
||||
None = 0,
|
||||
Upscaler = 1 << 0,
|
||||
Fg = 1 << 1,
|
||||
Rt = 1 << 2,
|
||||
Pso = 1 << 3,
|
||||
Vram = 1 << 4,
|
||||
Latency = 1 << 5,
|
||||
|
||||
/// <summary>From the swapchain description, not a feature hook.</summary>
|
||||
OutputRes = 1 << 6,
|
||||
Hdr = 1 << 7,
|
||||
}
|
||||
|
||||
/// <summary>Region 1 — write-once by the Overlay at init, except <see cref="AdapterLuid"/>.</summary>
|
||||
[StructLayout(LayoutKind.Sequential, Size = 64)]
|
||||
public unsafe struct FlShmHandshake
|
||||
{
|
||||
public uint LayoutVersion;
|
||||
public uint RecordSize;
|
||||
public uint Capacity;
|
||||
public uint Pid;
|
||||
|
||||
/// <summary>
|
||||
/// <c>FL_BUILD_ID</c>, from the git description of the commit the DLL was built from. NUL-terminated
|
||||
/// ASCII. Read it with <see cref="BuildIdString"/> rather than marshalling the struct.
|
||||
/// </summary>
|
||||
public fixed byte BuildId[32];
|
||||
|
||||
/// <summary>Session time base, shared with sensor samples.</summary>
|
||||
public ulong QpcEpoch;
|
||||
|
||||
/// <summary>
|
||||
/// 0 = NOT YET KNOWN, and it stays 0 until the first present, when the swapchain is known. The Agent
|
||||
/// must not resolve adapter-scoped telemetry against 0 — at init the Overlay is two steps before any
|
||||
/// graphics module is resolved, and a confident answer about the wrong GPU is worse than an admission.
|
||||
/// </summary>
|
||||
public ulong AdapterLuid;
|
||||
|
||||
/// <summary>The build id as a string, stopping at the first NUL. Empty if the field is unset.</summary>
|
||||
public string BuildIdString()
|
||||
{
|
||||
fixed (byte* p = BuildId)
|
||||
{
|
||||
int n = 0;
|
||||
while (n < 32 && p[n] != 0)
|
||||
{
|
||||
n++;
|
||||
}
|
||||
|
||||
return System.Text.Encoding.ASCII.GetString(p, n);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Region 2 — Overlay-written; <see cref="WriteIndex"/> is touched every present. Plain integers, not
|
||||
/// atomics: <c>std::atomic<T></c> has no guaranteed layout and could not be mirrored here at all.
|
||||
/// </summary>
|
||||
[StructLayout(LayoutKind.Sequential, Size = 64)]
|
||||
public unsafe struct FlWriterState
|
||||
{
|
||||
/// <summary>Monotonic; release-stored by the writer. Read it with <c>Volatile.Read</c>.</summary>
|
||||
public ulong WriteIndex;
|
||||
|
||||
public uint Status;
|
||||
public uint ApiMask;
|
||||
public uint FaultCount;
|
||||
|
||||
/// <summary>
|
||||
/// <c>IDXGIAdapter3</c> Budget, refreshed at 1 Hz. NOTE: no producer exists yet — the Overlay
|
||||
/// installs no <c>QueryVideoMemoryInfo</c> call, so this reads 0 and 0 means "nobody wrote it".
|
||||
/// </summary>
|
||||
public uint VramBudgetMb;
|
||||
|
||||
/// <summary>Must be zero; room for additive fields.</summary>
|
||||
public fixed uint Reserved[10];
|
||||
|
||||
// There is deliberately NO droppedRecords here. The writer has no reader index and cannot know
|
||||
// whether the slot it overwrites was ever consumed; the Agent computes drops from its own read index.
|
||||
}
|
||||
|
||||
/// <summary>Region 3 — Agent-written.</summary>
|
||||
[StructLayout(LayoutKind.Sequential, Size = 64)]
|
||||
public unsafe struct FlControlBlock
|
||||
{
|
||||
public uint PauseRequested;
|
||||
|
||||
/// <summary>Set when the guard fires mid-session. The capture side removes its hooks.</summary>
|
||||
public uint UnhookRequested;
|
||||
|
||||
/// <summary>In-game overlay draw toggle (v1.1). No consumer yet.</summary>
|
||||
public uint OverlayEnabled;
|
||||
|
||||
/// <summary>
|
||||
/// COMPLETED GUARD EVALUATIONS, not a timer, and the difference is the whole point of the field. A
|
||||
/// timer-driven tick attests that the Agent PROCESS is alive, which is not the question: the guard
|
||||
/// loop can be dead — a swallowed exception, a blocked service query, a stall on one unreadable
|
||||
/// process — while a timer keeps bumping, and the capture side would keep observing precisely
|
||||
/// because the thing supervising it had stopped. Increment at exactly one site, after a verdict
|
||||
/// returns.
|
||||
/// </summary>
|
||||
public uint GuardTicks;
|
||||
|
||||
/// <summary>Must be zero.</summary>
|
||||
public fixed uint Reserved[12];
|
||||
}
|
||||
|
||||
/// <summary>Region 4 — the ring. Exactly 64 bytes, no implicit padding.</summary>
|
||||
[StructLayout(LayoutKind.Sequential, Size = 64)]
|
||||
public struct FlFrameRecord
|
||||
{
|
||||
/// <summary>Present entry timestamp.</summary>
|
||||
public ulong Qpc;
|
||||
|
||||
public uint FrameIndex;
|
||||
public uint PresentFlags;
|
||||
public ushort SyncInterval;
|
||||
|
||||
/// <summary>0 = unknown. Only meaningful when <see cref="FlMeasured.Upscaler"/> is set.</summary>
|
||||
public ushort RenderW;
|
||||
|
||||
public ushort RenderH;
|
||||
public ushort OutputW;
|
||||
public ushort OutputH;
|
||||
public byte Api;
|
||||
public byte Upscaler;
|
||||
|
||||
/// <summary>Vendor enum; 0xFF unknown.</summary>
|
||||
public byte UpscalerQuality;
|
||||
|
||||
public byte FgMode;
|
||||
public byte RtFlags;
|
||||
public byte Hdr;
|
||||
|
||||
/// <summary>
|
||||
/// Sum of W×H×D this frame — a VOLUME, not a call count, and 32-bit for a reason: one 3840×2160
|
||||
/// primary-ray dispatch is 8,294,400 rays, 126× a ushort's range.
|
||||
/// </summary>
|
||||
public uint DispatchRaysVolume;
|
||||
|
||||
/// <summary>Compile COUNT, not a flag.</summary>
|
||||
public ushort PsoCreatedThisFrame;
|
||||
|
||||
public byte MaxTraceRecursionDepth;
|
||||
|
||||
/// <summary><see cref="FlMeasured"/> — which fields this frame actually measured.</summary>
|
||||
public byte MeasuredMask;
|
||||
|
||||
public ulong VramUsedBytes;
|
||||
|
||||
/// <summary>0 = unavailable.</summary>
|
||||
public uint ReflexLatencyUs;
|
||||
|
||||
/// <summary>FG feature evaluations this frame. <c>F_app = presents − Σ fgEvaluations</c>.</summary>
|
||||
public uint FgEvaluations;
|
||||
|
||||
/// <summary>
|
||||
/// Seqlock counter. Monotonic per slot and NEVER reset, so a full lap of the ring always changes it —
|
||||
/// otherwise a reader stalled exactly one lap would validate a different frame as unchanged. Odd
|
||||
/// means a write is in progress.
|
||||
/// </summary>
|
||||
public uint Seq;
|
||||
|
||||
/// <summary>
|
||||
/// Stable per-swapchain id; 0 = unidentified, which the Agent must treat as "one undifferentiated
|
||||
/// stream" and never as a valid id. Patching a vtable slot patches the SHARED class vtable, so one
|
||||
/// hook sees every swapchain in the process and a title with a separate UI or video swapchain would
|
||||
/// otherwise inflate Displayed FPS.
|
||||
/// </summary>
|
||||
public uint SwapchainId;
|
||||
}
|
||||
@@ -1,21 +1,20 @@
|
||||
// FrameLedger shared-memory layout.
|
||||
//
|
||||
// NORMATIVE. This header and docs/07_IPC.md must agree; the static_asserts
|
||||
// below are what enforce it.
|
||||
// below are what enforce it. Mirrored in C# by FrameLedger.Shared's
|
||||
// ShmLayout.cs, and ShmLayoutMirrorTests compares both sides against the
|
||||
// offsets emitted by tools/fl-layout-dump (CLAUDE.md §Struct mirroring).
|
||||
//
|
||||
// THE C# MIRROR DOES NOT EXIST YET. Until 2026-08-05 the line above continued
|
||||
// "Mirrored in C# by FrameLedger.Shared, and a test in
|
||||
// FrameLedger.Infrastructure.Tests compares both sides against the offsets
|
||||
// emitted by tools/fl-layout-dump" -- present tense, in the file that defines
|
||||
// the ABI, about a mirror and a test that do not exist. src/FrameLedger.Shared
|
||||
// holds a .csproj and no .cs files. That is the intent (CLAUDE.md
|
||||
// §Struct mirroring), tracked as 20_OPEN_QUESTIONS §R10 and scheduled in §S24;
|
||||
// build.ps1 skips the gate loudly rather than pretending it runs.
|
||||
// That sentence was present tense and FALSE from the day this file was written
|
||||
// until 2026-08-05 -- there was no mirror and no test. It is true now, and the
|
||||
// reason it is worth a note is where the false claim sat: in the normative
|
||||
// header, where a reader is most entitled to trust it. build.ps1:324-329
|
||||
// enumerates the other eight sites.
|
||||
//
|
||||
// Read the consequence, not just the correction: the static_asserts below bind
|
||||
// this header to itself and to 07_IPC. NOTHING binds it to a managed reader,
|
||||
// so until the mirror lands, changing a field here breaks the Agent silently
|
||||
// and at runtime rather than at build time.
|
||||
// SO: A FIELD CHANGED HERE MUST BE CHANGED IN ShmLayout.cs, and the build tells
|
||||
// you. Add it to tools/fl-layout-dump too -- the test walks the dump's field
|
||||
// list in BOTH directions, so a field this header gains and the dump does not
|
||||
// report is a field the mirror silently stops checking.
|
||||
//
|
||||
// Header-only by design: the Overlay writes these structs from inside a game
|
||||
// process and the Agent reads them from outside, so there must be exactly one
|
||||
|
||||
@@ -1,17 +1,22 @@
|
||||
# Emits the native struct offsets as JSON.
|
||||
# Emits the native struct offsets as JSON. FrameLedger.Infrastructure.Tests
|
||||
# (ShmLayoutMirrorTests) runs this and asserts the C# [StructLayout] mirrors
|
||||
# match field for field. Struct drift between the two layers is the most
|
||||
# dangerous silent bug in this architecture (CLAUDE.md §Struct mirroring) --
|
||||
# this is what catches it.
|
||||
#
|
||||
# NOTHING CONSUMES THIS YET. The comment here used to say
|
||||
# "FrameLedger.Infrastructure.Tests reads this and asserts the C# [StructLayout]
|
||||
# mirrors match field for field ... this is what catches it" -- present tense, in
|
||||
# a build file, about a test that does not exist. src/FrameLedger.Shared holds a
|
||||
# .csproj and no .cs files, and no managed test references FlFrameRecord.
|
||||
# build.ps1:324-329 enumerates the nine files that made this claim; this was one
|
||||
# of the two strongest sites, because a build file reads as a wiring fact rather
|
||||
# than as prose.
|
||||
# True since 2026-08-05, and it was written here in the present tense long
|
||||
# before it was: this was one of nine sites claiming a mechanism that did not
|
||||
# exist (build.ps1:324-329), and one of the two strongest, because a build file
|
||||
# reads as a wiring fact rather than as prose.
|
||||
#
|
||||
# Struct drift between the two layers is still the most dangerous silent bug in
|
||||
# this architecture (CLAUDE.md §Struct mirroring) -- which is the reason the gap
|
||||
# is named here rather than left implied. 20_OPEN_QUESTIONS §R10 tracks it,
|
||||
# §S24 schedules it. This tool is the intended input when it lands.
|
||||
# NO add_test HERE, deliberately. fl_shm.h's static_asserts already pin every
|
||||
# size and offset at compile time and layout_test.cpp says compiling IS the
|
||||
# test, so a ctest over this tool's stdout would be a second hand-maintained
|
||||
# copy of the same constants -- the exact thing the mirror exists to prevent.
|
||||
# The consumer that changes a verdict is the managed test.
|
||||
#
|
||||
# FrameLedger.LayoutDump.targets stages the exe beside that test. It is NOT
|
||||
# shipped: nothing in the product runs it, and an executable that dumps internal
|
||||
# layout has no business in a release.
|
||||
add_executable(fl-layout-dump main.cpp)
|
||||
target_link_libraries(fl-layout-dump PRIVATE FrameLedger.Shm fl_native_flags)
|
||||
@@ -1,9 +1,17 @@
|
||||
// Emits the native shared-memory struct layout as JSON.
|
||||
//
|
||||
// FrameLedger.Infrastructure.Tests consumes this and asserts that the C#
|
||||
// [StructLayout(LayoutKind.Sequential)] mirrors in FrameLedger.Shared match
|
||||
// field for field. CLAUDE.md §Struct mirroring requires a test that checks
|
||||
// sizeof AND every field offset on both sides; this is the native half.
|
||||
// FrameLedger.Infrastructure.Tests consumes this (ShmLayoutMirrorTests) and
|
||||
// asserts that the C# [StructLayout(LayoutKind.Sequential)] mirrors in
|
||||
// FrameLedger.Shared match field for field. CLAUDE.md §Struct mirroring requires
|
||||
// a test that checks sizeof AND every field offset on both sides; this is the
|
||||
// native half, and as of 2026-08-05 the managed half exists -- this comment was
|
||||
// present tense about a consumer that did not, which is what
|
||||
// 20_OPEN_QUESTIONS §R10 recorded.
|
||||
//
|
||||
// EMIT EVERY FIELD, including the reserved tails. The test walks this list in
|
||||
// both directions: a field here and not in C# fails, and a field in C# and not
|
||||
// here fails too. A dump that quietly stops reporting a field would otherwise
|
||||
// shrink what the mirror checks while every assertion still passed.
|
||||
//
|
||||
// Struct drift between C++ and C# is the most dangerous silent bug in this
|
||||
// architecture: nothing crashes, the Agent just reads garbage into fields that
|
||||
@@ -45,14 +53,20 @@ int main() {
|
||||
Field("status", offsetof(FlWriterState, status), sizeof(uint32_t));
|
||||
Field("apiMask", offsetof(FlWriterState, apiMask), sizeof(uint32_t));
|
||||
Field("faultCount", offsetof(FlWriterState, faultCount), sizeof(uint32_t));
|
||||
Field("vramBudgetMb", offsetof(FlWriterState, vramBudgetMb), sizeof(uint32_t), true);
|
||||
Field("vramBudgetMb", offsetof(FlWriterState, vramBudgetMb), sizeof(uint32_t));
|
||||
// The reserved tail is emitted too. It is part of the layout -- "room for
|
||||
// additive fields" is a promise about WHERE they may go -- and a mirror that
|
||||
// declares it while the dump stays silent cannot be checked in both
|
||||
// directions. Found by the managed test's reverse walk on 2026-08-05.
|
||||
Field("reserved", offsetof(FlWriterState, reserved), sizeof(uint32_t) * 10, true);
|
||||
std::printf(" ] },\n");
|
||||
|
||||
std::printf(" \"FlControlBlock\": { \"size\": %zu, \"fields\": [\n", sizeof(FlControlBlock));
|
||||
Field("pauseRequested", offsetof(FlControlBlock, pauseRequested), sizeof(uint32_t));
|
||||
Field("unhookRequested", offsetof(FlControlBlock, unhookRequested), sizeof(uint32_t));
|
||||
Field("overlayEnabled", offsetof(FlControlBlock, overlayEnabled), sizeof(uint32_t));
|
||||
Field("guardTicks", offsetof(FlControlBlock, guardTicks), sizeof(uint32_t), true);
|
||||
Field("guardTicks", offsetof(FlControlBlock, guardTicks), sizeof(uint32_t));
|
||||
Field("reserved", offsetof(FlControlBlock, reserved), sizeof(uint32_t) * 12, true);
|
||||
std::printf(" ] },\n");
|
||||
|
||||
std::printf(" \"FlFrameRecord\": { \"size\": %zu, \"fields\": [\n", sizeof(FlFrameRecord));
|
||||
|
||||
@@ -36,4 +36,11 @@
|
||||
-->
|
||||
<Import Project="$(MSBuildThisFileDirectory)..\..\FrameLedger.Rules.targets" />
|
||||
|
||||
<!--
|
||||
fl-layout-dump.exe, whose JSON is the native side of the struct-mirror
|
||||
assertion. ShmLayoutMirrorTests runs it rather than restating its numbers,
|
||||
because a second copy of the layout is what the mirror exists to catch.
|
||||
-->
|
||||
<Import Project="$(MSBuildThisFileDirectory)..\..\FrameLedger.LayoutDump.targets" />
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,191 @@
|
||||
using System.Diagnostics;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text.Json;
|
||||
using FluentAssertions;
|
||||
using FrameLedger.Shared;
|
||||
|
||||
namespace FrameLedger.Infrastructure.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// The struct-mirror gate. CLAUDE.md §Struct mirroring calls this the mechanism protecting the
|
||||
/// shared-memory ABI; until 2026-08-05 nine files described it in the present tense and none of it
|
||||
/// existed (<c>20_OPEN_QUESTIONS</c> §R10).
|
||||
/// <para>
|
||||
/// The native side is <c>tools/fl-layout-dump</c>, which is RUN rather than transcribed. A hand-written
|
||||
/// offset table here would be a second statement of the layout, and two statements of one fact drift —
|
||||
/// which is the defect this test exists to catch, reintroduced inside the catcher.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Every failure to obtain the native answer is a FAILURE, never a skip. "Could not look" reading as
|
||||
/// "looked and it matched" is the defect class this repository keeps recording, and a mirror test that
|
||||
/// silently skips on a machine without the native build is a gate that cannot fail.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public sealed class ShmLayoutMirrorTests
|
||||
{
|
||||
private static readonly Lazy<JsonElement> _nativeLayout = new(RunLayoutDump);
|
||||
|
||||
private static JsonElement RunLayoutDump()
|
||||
{
|
||||
string exe = Path.Combine(AppContext.BaseDirectory, "fl-layout-dump.exe");
|
||||
File.Exists(exe).Should().BeTrue(
|
||||
"fl-layout-dump.exe must sit beside the test binary (FrameLedger.LayoutDump.targets). "
|
||||
+ "Run build.ps1 native first. This is a FAILURE and not a skip on purpose: without the "
|
||||
+ "native answer this test would assert the C# mirror against itself.");
|
||||
|
||||
using var process = new Process
|
||||
{
|
||||
StartInfo = new ProcessStartInfo(exe)
|
||||
{
|
||||
RedirectStandardOutput = true,
|
||||
RedirectStandardError = true,
|
||||
UseShellExecute = false,
|
||||
CreateNoWindow = true,
|
||||
},
|
||||
};
|
||||
|
||||
process.Start().Should().BeTrue("fl-layout-dump.exe must be launchable");
|
||||
string json = process.StandardOutput.ReadToEnd();
|
||||
process.WaitForExit(30_000).Should().BeTrue("fl-layout-dump.exe must exit promptly");
|
||||
process.ExitCode.Should().Be(0, "fl-layout-dump.exe must succeed, not print a partial layout");
|
||||
json.Should().NotBeNullOrWhiteSpace("an empty dump would make every offset assertion vacuous");
|
||||
|
||||
// Parse failure throws, which is the intended outcome — a malformed dump must not read as clean.
|
||||
using var document = JsonDocument.Parse(json);
|
||||
return document.RootElement.Clone();
|
||||
}
|
||||
|
||||
private static JsonElement StructOf(string name)
|
||||
{
|
||||
JsonElement structs = _nativeLayout.Value.GetProperty("structs");
|
||||
structs.TryGetProperty(name, out JsonElement element).Should().BeTrue(
|
||||
$"fl-layout-dump must emit {name}; a struct that disappears from the dump would otherwise "
|
||||
+ "silently stop being checked");
|
||||
return element;
|
||||
}
|
||||
|
||||
private static void AssertMirror<T>(string nativeName)
|
||||
where T : struct
|
||||
{
|
||||
JsonElement native = StructOf(nativeName);
|
||||
|
||||
// Size, both ways. Marshal.SizeOf is the marshalled size; Unsafe.SizeOf is what the runtime
|
||||
// actually lays out and therefore what a memory-mapped read sees. They can differ, and only the
|
||||
// second one is the property the reader depends on.
|
||||
int nativeSize = native.GetProperty("size").GetInt32();
|
||||
nativeSize.Should().Be(64, $"{nativeName} is one cache line in fl_shm.h");
|
||||
Marshal.SizeOf<T>().Should().Be(nativeSize, $"{typeof(T).Name} marshalled size must match {nativeName}");
|
||||
Unsafe.SizeOf<T>().Should().Be(nativeSize, $"{typeof(T).Name} runtime size must match {nativeName}");
|
||||
|
||||
// BLITTABILITY, which offsets structurally cannot see.
|
||||
//
|
||||
// The repository's existing idiom for a native char[N] is
|
||||
// [MarshalAs(ByValTStr, SizeConst = N)] public string (NativeAntiCheatGuard's FlGuardResult,
|
||||
// where it is correct because that struct crosses a P/Invoke boundary and the marshaller runs).
|
||||
// Used here it would satisfy every offset assertion above and below, and then fail to read out
|
||||
// of a MemoryMappedViewAccessor — which is the one thing these types exist for.
|
||||
RuntimeHelpers.IsReferenceOrContainsReferences<T>().Should().BeFalse(
|
||||
$"{typeof(T).Name} must be blittable: it is read straight out of a memory-mapped view, and a "
|
||||
+ "managed reference anywhere inside it makes that impossible. Offsets cannot detect this.");
|
||||
|
||||
foreach (JsonElement field in native.GetProperty("fields").EnumerateArray())
|
||||
{
|
||||
string nativeField = field.GetProperty("name").GetString()!;
|
||||
int nativeOffset = field.GetProperty("offset").GetInt32();
|
||||
|
||||
// The C# names are PascalCase mirrors of the native camelCase ones.
|
||||
string managedField = char.ToUpperInvariant(nativeField[0]) + nativeField[1..];
|
||||
typeof(T).GetField(managedField).Should().NotBeNull(
|
||||
$"{typeof(T).Name} must mirror {nativeName}.{nativeField}; a field present natively and "
|
||||
+ "absent here means the Agent reads a value nobody mapped");
|
||||
|
||||
int managedOffset = Marshal.OffsetOf<T>(managedField).ToInt32();
|
||||
managedOffset.Should().Be(
|
||||
nativeOffset,
|
||||
$"{typeof(T).Name}.{managedField} must sit at the same offset as {nativeName}.{nativeField}");
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheLayoutVersionMatches()
|
||||
{
|
||||
// The version the Agent compares against the handshake before attaching. If this drifts, the
|
||||
// Agent refuses every session or accepts an incompatible one — and 11_UPDATER makes it a SemVer
|
||||
// MAJOR, so it must never move by accident.
|
||||
_nativeLayout.Value.GetProperty("layoutVersion").GetUInt32().Should().Be(ShmLayout.LayoutVersion);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheRegionOffsetsMatch()
|
||||
{
|
||||
JsonElement regions = _nativeLayout.Value.GetProperty("regions");
|
||||
regions.GetProperty("handshake").GetUInt32().Should().Be(ShmLayout.HandshakeOffset);
|
||||
regions.GetProperty("writer").GetUInt32().Should().Be(ShmLayout.WriterOffset);
|
||||
regions.GetProperty("control").GetUInt32().Should().Be(ShmLayout.ControlOffset);
|
||||
regions.GetProperty("ring").GetUInt32().Should().Be(ShmLayout.RingOffset);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheHandshakeMirrorMatches() => AssertMirror<FlShmHandshake>("FlShmHandshake");
|
||||
|
||||
[Fact]
|
||||
public void TheWriterStateMirrorMatches() => AssertMirror<FlWriterState>("FlWriterState");
|
||||
|
||||
[Fact]
|
||||
public void TheControlBlockMirrorMatches() => AssertMirror<FlControlBlock>("FlControlBlock");
|
||||
|
||||
[Fact]
|
||||
public void TheFrameRecordMirrorMatches() => AssertMirror<FlFrameRecord>("FlFrameRecord");
|
||||
|
||||
[Fact]
|
||||
public void EveryNativeFieldIsMirrored()
|
||||
{
|
||||
// AssertMirror walks the NATIVE field list, so a field added natively and forgotten here fails.
|
||||
// This walks the other way: a field added HERE that the dump does not emit means either the
|
||||
// mirror invented something or fl-layout-dump stopped reporting it, and the second is how the
|
||||
// check above would quietly start testing less than it claims.
|
||||
(string Native, Type Managed)[] pairs =
|
||||
[
|
||||
("FlShmHandshake", typeof(FlShmHandshake)),
|
||||
("FlWriterState", typeof(FlWriterState)),
|
||||
("FlControlBlock", typeof(FlControlBlock)),
|
||||
("FlFrameRecord", typeof(FlFrameRecord)),
|
||||
];
|
||||
|
||||
foreach ((string nativeName, Type managed) in pairs)
|
||||
{
|
||||
HashSet<string> nativeFields = StructOf(nativeName)
|
||||
.GetProperty("fields")
|
||||
.EnumerateArray()
|
||||
.Select(f => f.GetProperty("name").GetString()!)
|
||||
.Select(n => char.ToUpperInvariant(n[0]) + n[1..])
|
||||
.ToHashSet(StringComparer.Ordinal);
|
||||
|
||||
nativeFields.Should().NotBeEmpty($"{nativeName} must report fields, or its assertions are vacuous");
|
||||
|
||||
IEnumerable<string> managedFields = managed
|
||||
.GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance)
|
||||
.Select(f => f.Name);
|
||||
|
||||
foreach (string name in managedFields)
|
||||
{
|
||||
nativeFields.Should().Contain(
|
||||
name,
|
||||
$"{managed.Name}.{name} has no counterpart in {nativeName} — either it was invented "
|
||||
+ "here, or fl-layout-dump stopped emitting it and the offset walk silently shrank");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheRecordSizeUsedForRingArithmeticMatches()
|
||||
{
|
||||
// SizeForCapacity is what the reader will use to bound the mapping. Deriving it from a hardcoded
|
||||
// 64 would be a third statement of the record size.
|
||||
int recordSize = StructOf("FlFrameRecord").GetProperty("size").GetInt32();
|
||||
ShmLayout.SizeForCapacity(ShmLayout.DefaultCapacity)
|
||||
.Should()
|
||||
.Be(ShmLayout.RingOffset + ((long)ShmLayout.DefaultCapacity * recordSize));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user