Files
frameledger/tests/FrameLedger.CaptureHost.Tests/CaptureHostEndToEndTests.cs
T
poli0981andClaude Opus 5.5 24a87159f4 fix: the owner's eight sessions of 2026-10-20 - a x2.52 state, the driver's DLSS word lost at exit, Start directly losing the game Steam starts, two summary windows, display sizes, a bare DLSS line; the Steam note; the two load-flaky tests (beta.27 PR-1) (#330)
The owner ran the installed 0.1.0-beta.26 (sessions 64-71) and asked for the results to be checked,
the two flaky tests fixed, bugs fixed, and a release if there were bugs. Read from a backup copy of
the ledger and the logs (docs/spike-notes/23-owner-runs-2026-10-20.md).

- FgWindow.IsNearWholeMultiplier: a window is a state's only within 10 % of a whole multiplier of two
  or more (FgSlices.Slice.IsActive); FgMixRecord.Parse reads stored rows by the same rule. Silent Hill
  2 under Dynamic MFG listed x2.52 for 12.8 s - windows where the multiplier stepped; it now reads
  x2.0, x3.0, none and 7.36 % not classified.
- NgxDriverState / CaptureSession: the driver is not asked after the game has gone, and CREATED |
  EVALUATE stand once a reading carried them. The last NGX reading, taken after the target exited,
  replaced every in-game one: none of the 14 answered sessions kept the two bits, so DLSS
  (driver-reported) and the NVIDIA App's mode (D63) never showed on an NGX-direct title.
- CaptureOrchestrator: a launch says it ended on its own (Recorded) with the pids it recorded
  (Targets), so a process turned away while it ran - the game Steam starts after Lies of P hands
  itself over - is recorded when it ends; the launch's own process never is.
- SessionSummaryOpener: one window per session; opening it again brings it forward.
- DisplayTally: the sizes are the mode's last sample that saw the window (a game leaving exclusive
  fullscreen closes it first; five sessions stored none).
- DlssText.Line: no line that says only "DLSS".
- Tests: the guard's scan set includes the test host above the harness, which under a full gate
  releases modules while it starts its other classes - ModuleScanFailed (reproduced 1 run in 12 of
  the assembly with coverage; 15 of 15 green after), ProcessUnreadable on 2026-10-19.
  ShmDrainIntegrationTests.InjectAsync asks again on those two reasons only (4 times at most, 250 ms
  apart); the pause case waits for READY; every injection suite waits for the harness's flushed
  "presenting" line instead of 800 ms (tests/Shared/HarnessReady.cs).
- Docs: 03_METRICS (the mix, the driver-reported rung, display sizes), 04_CAPTURE, 06_DATA_MODEL,
  08_UI, 14_TESTING, 18_GPU_VENDOR_APIS, 19_SAFETY (direct starts counted by the crash safety -
  measured, the policy unchanged), LIMITATIONS, guide (troubleshooting, results), spike-notes section
  23, HANDOFF items 20 and 21, CHANGELOG.

Then, on the owner's word about Steam games (Play > Start directly says a Steam game may hand itself to Steam - the notice, the tooltip and Settings (en/vi/ja); why a note rather than a fixed Steam rule (beta.27 PR-1)):

The owner, 2026-10-20: Steam games hand themselves to Steam; a note in the UI, or a fixed setting
that Steam's games always go through the Steam client - the choice left open. The note:

- GamePlayer: PlayResult.SteamGame - the game the agent starts (Start directly, or an App running as
  administrator, or a Steam record with no link) is one Steam's own records name; the notice then
  reads Play_Started_Steam_Format / Play_Elevated_Steam_Format. Store records are read once a press.
- Strings: Play_ToolTip_Direct and Settings_PlayMode_Body say a Steam game may hand itself to Steam
  and the game Steam then starts is recorded; Settings adds that a few will not start outside Steam
  at all. en/vi/ja, ja marked review; Strings.Designer regenerated.
- Why not the fixed rule: three of the five Steam games started directly on 2026-10-20 ran and were
  measured from their first frame, and a Vulkan game is measured only when FrameLedger starts it
  (Everhex Demo) - recorded in 08_UI.
- Docs: 08_UI, guide/08-settings, LIMITATIONS, CHANGELOG.
- Tests: GamePlayerTests (Steam started directly and elevated say it; a loose or GOG game does not).

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 10:31:47 +07:00

659 lines
33 KiB
C#

// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
using System.Diagnostics;
using System.IO.MemoryMappedFiles;
using FluentAssertions;
using FrameLedger.Application.Capture;
using FrameLedger.Application.Consent;
using FrameLedger.Application.Persistence;
using FrameLedger.Application.Recording;
using FrameLedger.Domain.Consent;
using FrameLedger.Domain.Sessions;
using FrameLedger.Infrastructure.Persistence;
using FrameLedger.Infrastructure.Recording;
using FrameLedger.Shared;
using FrameLedger.Testing;
namespace FrameLedger.CaptureHost.Tests;
/// <summary>
/// The host as a separate process, which is the only arrangement that can show
/// <c>guardTicks</c> advancing from a NON-TEST binary.
/// </summary>
/// <remarks>
/// <para>
/// <b>hook-harness is the only thing this suite ever injects into</b> — our own
/// dummy D3D app, built from this tree, carrying no anti-cheat and belonging to no
/// publisher. Injecting into it raises no consent question at all: no game, no
/// account, no terms of service. <c>TheTargetAndTheConsentRecordAreBothOurOwnHarness</c>
/// asserts that constraint on the suite itself, so it cannot grow into §S9's
/// user-runnable injector by increments.
/// </para>
/// <para>
/// <b>The self-constraint covers the CONSENT RECORD as well as the target</b>, which
/// <c>ShmDrainIntegrationTests</c>' original version did not need to. That test could
/// only ever inject where its own hardcoded fixture pointed; this one writes a
/// record that satisfies the opt-in gate, and nothing about a record limits which
/// executable it names. One edited string would generalise it to any binary on the
/// machine, so the record's path is pinned too.
/// </para>
/// <para>
/// <b>Category=Integration — and CI runs it.</b> This paragraph said CI would not (corrected 2026-10-07): §S19(b), the
/// guard refusing a .NET test host that had loaded a <c>protect</c>-matching module, was answered on 2026-09-06 by the
/// signer check, and <c>./build.ps1 check</c> runs the Integration category on CI since (<c>13_CI_CD</c> §ci.yml). A green
/// CI is evidence for this suite, and a race in it fails a merge: two did on 2026-10-07 (the two cases below that say so).
/// </para>
/// </remarks>
[Trait("Category", "Integration")]
public sealed class CaptureHostEndToEndTests : IDisposable
{
private static string Harness => Path.Combine(AppContext.BaseDirectory, "hook-harness.exe");
private static string Host => Path.Combine(AppContext.BaseDirectory, "FrameLedger.CaptureHost.exe");
/// <summary>This test's scratch directory: the harness copy it consents to, and nothing else.</summary>
private readonly string _scratch = Path.Combine(Path.GetTempPath(), "fl-capturehost-e2e-" + Guid.NewGuid().ToString("N"));
/// <summary>
/// The ONE executable this suite may write a consent record for: our harness, copied under a run-unique name
/// (beta.16). The host resolves its target BY NAME (<c>TargetResolver</c>), and <c>build.ps1</c> runs the test projects as
/// parallel processes: a <c>hook-harness.exe</c> another project was still starting - its module list a partial copy -
/// is an unreadable process of the same name, which the resolver must count, and it refused <c>TargetAmbiguous</c>
/// (#269's first CI run). No other test starts a process of this name.
/// </summary>
/// <remarks>
/// Every write goes through here, so "which binary did the suite consent to?" has
/// one answer and one place to change it — and changing it is what the assertion
/// below turns red.
/// </remarks>
private string ConsentedExecutable => Path.Combine(_scratch, "hook-harness-" + Path.GetFileName(_scratch) + ".exe");
/// <summary>The host's own ledger, beside its binary (P2 PR-B): the same SQLite adapter the Agent will use.</summary>
private static string HostLedger => Path.Combine(Path.GetDirectoryName(Host)!, LedgerPaths.DatabaseFileName);
/// <summary>Writes the ONE consent record this suite may write, through the real store, and closes the ledger again.</summary>
private async Task<ConsentWriteOutcome> GrantConsentAsync()
{
StageTarget();
ExecutableFingerprint fingerprint = FrameLedger.Infrastructure.Io.ExecutableIdentity.Read(ConsentedExecutable)!.Value;
LedgerDatabase db = await LedgerDatabase.OpenAsync(HostLedger, ct: TestContext.Current.CancellationToken).ConfigureAwait(false);
await using (db.ConfigureAwait(false))
{
return await new SqliteGameConsentStore(db).RecordOperatorAcknowledgementAsync(new OperatorAcknowledgement
{
Fingerprint = fingerprint,
DisclosureVersion = OperatorDisclosure.Version,
AcknowledgedAt = DateTimeOffset.UtcNow,
}, TestContext.Current.CancellationToken).ConfigureAwait(false);
}
}
private async Task<GameConsentRecord> FindConsentAsync()
{
LedgerDatabase db = await LedgerDatabase.OpenAsync(HostLedger, ct: TestContext.Current.CancellationToken).ConfigureAwait(false);
await using (db.ConfigureAwait(false))
{
return await new SqliteGameConsentStore(db).FindAsync(
FrameLedger.Infrastructure.Io.ExecutableIdentity.Normalise(ConsentedExecutable), TestContext.Current.CancellationToken).ConfigureAwait(false);
}
}
/// <summary>The ledger and WAL's two sidecars; a guarded delete of each.</summary>
/// <summary>
/// Deletes the host's ledger, retrying for a few seconds: a host this suite just killed may still hold the file
/// while Windows tears the process down, and a delete that silently failed is how the refusal case found a
/// leftover consent record on CI (2026-09-16, three runs in one evening).
/// </summary>
private static void DeleteHostLedger()
{
foreach (string suffix in new[] { "", "-wal", "-shm" })
{
string path = HostLedger + suffix;
for (int attempt = 0; attempt < 20 && File.Exists(path); attempt++)
{
try
{
File.Delete(path);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Thread.Sleep(250);
}
}
}
}
public void Dispose()
{
// The host writes beside its own binary, which for a ProjectReference'd exe is this test's
// output directory. Leaving a consent record there would make the NEXT run of the refusal case
// pass for the wrong reason.
DeleteHostLedger();
try
{
Directory.Delete(_scratch, recursive: true);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
// A harness this test killed may still hold its image for a moment; the directory is the temp folder's.
}
}
[Fact]
public void TheTargetAndTheConsentRecordAreBothOurOwnHarness()
{
StageTarget();
Path.GetFileName(Harness).Should().Be("hook-harness.exe");
Path.GetDirectoryName(Harness).Should().Be(
AppContext.BaseDirectory.TrimEnd(Path.DirectorySeparatorChar));
Path.GetFileName(ConsentedExecutable).Should().StartWith("hook-harness-");
Path.GetDirectoryName(ConsentedExecutable).Should().Be(_scratch, "the copy lives in this test's scratch directory and nowhere else");
File.ReadAllBytes(ConsentedExecutable).Should().Equal(File.ReadAllBytes(Harness), "the target IS hook-harness, byte for byte, under another name");
Path.GetFileName(Host).Should().Be("FrameLedger.CaptureHost.exe");
}
/// <summary>This run's copy of hook-harness, once per test; its overlay logs are this assembly's to remove (<c>17_HOOK_ENGINE</c> §Native logging).</summary>
private void StageTarget()
{
if (File.Exists(ConsentedExecutable))
{
return;
}
File.Exists(Harness).Should().BeTrue(
"hook-harness.exe must be staged beside the test binary (FrameLedger.DrainFixtures.targets). "
+ "This FAILS rather than skipping: an integration test that quietly does nothing when its fixture "
+ "is absent is a gate that cannot fail.");
Directory.CreateDirectory(_scratch);
HarnessOverlayLogSweep.Own(_scratch);
File.Copy(Harness, ConsentedExecutable);
}
private async Task<Process> StartHarnessAsync(string arguments)
{
StageTarget();
File.Exists(Host).Should().BeTrue("the host must be built and copied beside this test");
var p = Process.Start(new ProcessStartInfo(ConsentedExecutable, arguments)
{
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardOutput = true,
})!;
bool presenting = await HarnessReady.WaitUntilPresentingAsync(p, TestContext.Current.CancellationToken).ConfigureAwait(false);
if (!presenting && !p.HasExited)
{
p.Kill(entireProcessTree: true);
}
presenting.Should().BeTrue("the harness must reach its present loop before anything looks for it or is injected into it (HarnessReady)");
p.HasExited.Should().BeFalse("the harness must be running before the host looks for it");
return p;
}
private static Process StartHost(params string[] args)
{
var psi = new ProcessStartInfo(Host)
{
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
};
foreach (string a in args)
{
psi.ArgumentList.Add(a);
}
return Process.Start(psi)!;
}
/// <summary>
/// Kills the process tree AND waits for it to be gone. `Kill` returns before the process has released its
/// files; the kill-and-recover case then opened the `.partial` the dead host still held ("being used by another
/// process"), and the refusal case's ledger delete failed the same way — the two CaptureHost flakes CI kept
/// producing (13_CI_CD's tally). A wait bounded at 15 s: a process that will not die is a failure to report.
/// </summary>
private static void Kill(Process p)
{
try
{
if (!p.HasExited)
{
p.Kill(entireProcessTree: true);
p.WaitForExit(15_000).Should().BeTrue("a killed process must be gone before its files are read or deleted");
}
}
catch (InvalidOperationException)
{
}
p.Dispose();
}
[Fact]
public async Task WithNoConsentRecordTheHostRefusesAndNothingIsEverInjected()
{
// HANDOFF's acceptance criterion for item 1, from OUTSIDE the process: the refusal happens and
// FlGuardedInject is never reached.
//
// THE HARNESS IS STARTED FIRST, and that is load-bearing. The host resolves its target before
// it consults consent — a HookRequest cannot be built without a pid — so with nothing running
// it would exit at TargetNotRunning, both structural assertions would still hold, and the
// canary would be inert: a host mutated to call GuardedInjectAsync directly would ALSO exit at
// TargetNotRunning and this would stay green with the chokepoint removed.
// THE PRECONDITION IS ASSERTED, not assumed, and it is asserted because this test failed once
// for exactly that reason: a consent record left behind by a sibling case made the host refuse
// for a DIFFERENT reason, and the run before it had passed. A test whose verdict depends on
// what ran before it is one this repository does not accept, so the leftover is now a failure
// with its own message rather than an outcome that happens to differ.
// Directory first, then a guarded delete. `File.Delete` on a path whose PARENT does not exist
// throws DirectoryNotFoundException, and the parent is created only when some test actually
// writes a record — so on a clean build output this line threw, and the case's verdict depended
// on which sibling had run before it. In the very test whose comment says a test whose verdict
// depends on what ran before it is one this repository does not accept.
DeleteHostLedger();
(await FindConsentAsync()).IsFromStore.Should().BeFalse(
"this case is about an ABSENT record; a leftover one from a sibling test would make the "
+ "host refuse for a different reason and the assertions below would say nothing");
Process harness = await StartHarnessAsync("--real --hold-presenting 20");
try
{
using Process host = StartHost("capture", "--exe", ConsentedExecutable);
string stdout = await host.StandardOutput.ReadToEndAsync(TestContext.Current.CancellationToken);
await host.WaitForExitAsync(TestContext.Current.CancellationToken);
stdout.Should().Contain(nameof(SessionEndReason.RefusedHookNotEnabled),
"an absent record is not-enabled before it is unconsented, and the two are different sentences");
host.ExitCode.Should().NotBe(0);
// THE STRONGEST EXTERNAL EVIDENCE AVAILABLE that FlGuardedInject was never reached: the
// Overlay creates Local\FrameLedger.Ring.<pid> on its init thread, so if the section does
// not exist, nothing was loaded into that process.
harness.HasExited.Should().BeFalse("the target must still be alive for the next assertion to mean anything");
Action open = () => MemoryMappedFile.OpenExisting(
$@"Local\FrameLedger.Ring.{harness.Id}", MemoryMappedFileRights.Read).Dispose();
open.Should().Throw<FileNotFoundException>("no ring means no Overlay means no injection");
}
finally
{
Kill(harness);
}
}
[Fact]
public async Task AConsentedSessionAdvancesGuardTicksFromANonTestBinary()
{
// The other half of HANDOFF's acceptance: "guardTicks advancing from a non-test binary".
//
// The record is written through the real store rather than through `consent grant`, which
// refuses redirected stdin by design. That is the suite standing in for a human, so the
// self-constraint above pins WHICH executable it may stand in for.
(await GrantConsentAsync()).Should().Be(ConsentWriteOutcome.Written);
Process harness = await StartHarnessAsync("--real --hold-presenting 40");
Process? host = null;
try
{
host = StartHost("capture", "--exe", ConsentedExecutable);
// THE TEST READS THE CONTROL BLOCK WITH ITS OWN VIEW, and never writes to it. PublishGuardResult
// being the single writer of guardTicks and unhookRequested is what holds the publish ORDER
// that ShmRingReader documents; a second writer would take that away.
uint ticks = await PollGuardTicksAsync(harness.Id, atLeast: 1, TimeSpan.FromSeconds(20));
ticks.Should().BeGreaterThanOrEqualTo(1u,
"the host publishes its first tick immediately on attach, because the Overlay's 65 s "
+ "supervision clock starts when the mapping is published and not when we adopt it");
FlWriterState state = await PollWriterPastInitAsync(harness.Id, TimeSpan.FromSeconds(15));
// INIT after the budget is not a slow start — it is MinHook or the dummy-device probe having
// failed, which means the ring will never move. That is CaptureSession's
// WriterNeverInstalledHooks, and it must not read as a passing session here either.
state.Status.Should().Be((uint)FlStatus.Ready,
"the Overlay hooked and is recording; INIT past the budget means InstallPresentHooks "
+ "failed and no frame will ever be written");
state.FaultCount.Should().Be(0u);
(state.ApiMask & (1u << (int)FlApi.D3D11)).Should().NotBe(0u);
}
finally
{
if (host is not null)
{
Kill(host);
}
Kill(harness);
}
}
[Fact]
public async Task LaunchModeStartsTheHarnessItselfAndReportsWhatRanUnhooked()
{
// P1 item 2, from OUTSIDE the process: the host starts the consented harness, the guard waits
// for dxgi to map and injects, and the report carries the two numbers 20_OPEN_QUESTIONS §S1
// deferred on -- the wait, and DXGI's count of presents before the first hooked one.
(await GrantConsentAsync()).Should().Be(ConsentWriteOutcome.Written);
using Process host = StartHost("launch", "--exe", ConsentedExecutable, "--args", "--real --hold-presenting 9",
"--seconds", "6");
string stdout = await host.StandardOutput.ReadToEndAsync(TestContext.Current.CancellationToken);
await host.WaitForExitAsync(TestContext.Current.CancellationToken);
stdout.Should().Contain("launch: the guard injected", "the wait is printed, because it is the number §S1 lacked");
stdout.Should().Contain("presents before the first hooked present:");
stdout.Should().NotContain("not read", "the harness presents, so the first hooked present happened");
host.ExitCode.Should().Be(0, stdout);
// P2 PR-D, THE MILESTONE'S FIRST HALF from outside the process: the session is a ROW in the host's
// own ledger, with the blobs beside it, written by the same code path the Agent will use.
stdout.Should().Contain("ledger: session ").And.Contain("SAVED as sessions.id=", stdout);
LedgerDatabase db = await LedgerDatabase.OpenAsync(HostLedger, ct: TestContext.Current.CancellationToken).ConfigureAwait(true);
await using (db.ConfigureAwait(true))
{
var sessions = new SqliteSessionRepository(db);
IReadOnlyList<SessionRow> rows = await sessions.ListRecentAsync(1, TestContext.Current.CancellationToken).ConfigureAwait(true);
SessionRow row = rows.Should().ContainSingle().Subject;
row.Tier.Should().Be(CaptureTier.Hooked);
row.Mode.Should().Be(CaptureMode.Launch);
row.ExitStatus.Should().Be(ExitStatus.Normal, "the harness was still presenting when the bounded capture ended");
row.FrameCount.Should().BeGreaterThan(100, "6 s at ~120/s");
row.PresentedFps.Should().BeGreaterThan(30);
row.Api.Should().Be("d3d11");
row.GuardTicksPublished.Should().BeGreaterThanOrEqualTo(1);
row.LaunchWaitMs.Should().NotBeNull();
row.OverlayBuildId.Should().NotBeNullOrEmpty("the handshake names the Overlay build");
row.TelemetrySource.Should().Contain("l1", "the host composes L1 + L2 for every session");
row.QpcFrequency.Should().Be(System.Diagnostics.Stopwatch.Frequency);
FrameBlobs? frames = await sessions.FindFramesAsync(row.Id, TestContext.Current.CancellationToken).ConfigureAwait(true);
frames.Should().NotBeNull("the blobs land in the same transaction as the row");
frames!.SampleCount.Should().Be(row.FrameCount);
// THIS session's .partial is gone; a sibling case kills a host on purpose and leaves one behind.
string guid = System.Text.RegularExpressions.Regex.Match(stdout, @"ledger: session (?<guid>[0-9a-f]{32}) SAVED",
System.Text.RegularExpressions.RegexOptions.ExplicitCapture, TimeSpan.FromSeconds(1)).Groups["guid"].Value;
guid.Should().HaveLength(32, stdout);
File.Exists(Path.Combine(PartialDirectory, guid + ".partial")).Should().BeFalse("finalize deletes the .partial");
}
}
private static string PartialDirectory => Path.Combine(Path.GetDirectoryName(Host)!, "tmp");
private static async Task AssertInterruptedRowAsync(Guid guid, int expectedFrames)
{
LedgerDatabase db = await LedgerDatabase.OpenAsync(HostLedger, ct: TestContext.Current.CancellationToken).ConfigureAwait(false);
await using (db.ConfigureAwait(false))
{
SessionRow? row = await new SqliteSessionRepository(db).FindAsync(guid, TestContext.Current.CancellationToken).ConfigureAwait(false);
row.Should().NotBeNull();
row!.ExitStatus.Should().Be(ExitStatus.Interrupted);
row.Tier.Should().Be(CaptureTier.Hooked);
row.FrameCount.Should().Be(expectedFrames, "the prefix is the session");
row.DurationSeconds.Should().BeGreaterThanOrEqualTo(5, "ended at the last flush, past the host's minimum");
row.CaptureNotes.Should().Contain("recovered from .partial");
}
}
[Fact]
public async Task AKilledHostLeavesAPartialThatRecoverTurnsIntoAnInterruptedSession()
{
// P2 PR-D, the recovery half from OUTSIDE the process: the host is killed mid-session, the file it
// flushed every 3 s is the only record, and `recover` -- what the Agent runs first at every start --
// turns it into an `interrupted` row and removes it. Nothing here waits on a clock it does not own:
// the guard tick is polled for, and the kill comes after two flushes have had time to land.
(await GrantConsentAsync()).Should().Be(ConsentWriteOutcome.Written);
Directory.CreateDirectory(PartialDirectory);
HashSet<string> before = [.. Directory.EnumerateFiles(PartialDirectory, "*.partial")];
Process harness = await StartHarnessAsync("--real --hold-presenting 40");
Process? host = null;
string? file = null;
try
{
host = StartHost("capture", "--exe", ConsentedExecutable);
await PollGuardTicksAsync(harness.Id, atLeast: 1, TimeSpan.FromSeconds(20));
await Task.Delay(TimeSpan.FromSeconds(8), TestContext.Current.CancellationToken);
Kill(host);
file = Directory.EnumerateFiles(PartialDirectory, "*.partial").Should().ContainSingle(f => !before.Contains(f),
"the killed host left exactly one file, its own").Subject;
PartialSession? partial = PartialSessionFile.Read(file);
partial.Should().NotBeNull();
partial!.LastTick.Should().NotBeNull("two 3 s flushes fit inside 8 s");
partial.Records.Should().NotBeEmpty();
using Process recover = StartHost("recover");
string stdout = await recover.StandardOutput.ReadToEndAsync(TestContext.Current.CancellationToken);
await recover.WaitForExitAsync(TestContext.Current.CancellationToken);
recover.ExitCode.Should().Be(0, stdout);
string guid = Path.GetFileNameWithoutExtension(file);
stdout.Should().Contain(guid + ": Recovered as session", stdout);
File.Exists(file).Should().BeFalse("recovery removes what it stored");
await AssertInterruptedRowAsync(Guid.ParseExact(guid, "N"), partial.Records.Count);
}
finally
{
if (host is not null)
{
Kill(host);
}
Kill(harness);
if (file is not null && File.Exists(file))
{
File.Delete(file);
}
}
}
[Fact]
public async Task LaunchModeOnAVulkanTargetAttachesToTheLayersRingAndInjectsNothing()
{
// P1 item 3, from OUTSIDE the process: the host launches the harness in its Vulkan mode with the
// layer's environment, the guard passes and injects nothing (TargetIsVulkanLayered), and the
// records come from the layer's ring. Skipped honestly where there is no Vulkan loader or no
// presentable device -- the harness says so itself, with exit 77 and a "[SKIP]" line.
if (!File.Exists(Path.Combine(Environment.SystemDirectory, "vulkan-1.dll")))
{
Assert.Skip("no Vulkan loader on this machine");
}
// ASKED BEFORE THE HOST RUNS, of the harness itself (beta.18). This used to be read off the host's run: its output
// for the harness's "[SKIP]" line, or the session's LaunchTargetExited. Neither holds on a hosted runner, which has
// the loader and no device. The runner is elevated, so the host starts the harness through CreateProcessWithTokenW
// (UnelevatedProcess), which hands the child no stdout -- the line never reached the host's output -- and the
// harness's exit races the guard's poll: #288's CI run scanned it while it died and ended RefusedByGuard
// (ModuleScanFailed, "a module list came back incomplete"), failing where it should have skipped. Run directly, the
// harness's own output and exit code are this test's; and once it HAS presented here, every failure below is real.
(int probeExit, string probeOutput) = await ProbeVulkanAsync();
if (probeExit == 77)
{
Assert.Skip("the harness found no presentable Vulkan device on this machine: " + probeOutput);
}
probeExit.Should().Be(0, "the harness presents through Vulkan on this machine, or says why it cannot: " + probeOutput);
(await GrantConsentAsync()).Should().Be(ConsentWriteOutcome.Written);
using Process host = StartHost("launch", "--exe", ConsentedExecutable, "--args", "--vulkan --hold-presenting 8",
"--seconds", "5");
Task<string> stderrTask = host.StandardError.ReadToEndAsync(TestContext.Current.CancellationToken);
string stdout = await host.StandardOutput.ReadToEndAsync(TestContext.Current.CancellationToken);
await host.WaitForExitAsync(TestContext.Current.CancellationToken);
stdout += "\n---- stderr ----\n" + await stderrTask + $"\n---- exit {host.ExitCode} ----\n";
stdout.Should().Contain("vulkan layer: ", "the launch names the manifest it wrote and the enable-list entry");
stdout.Should().Contain("capture side: the Vulkan implicit layer", stdout);
stdout.Should().Contain("apiMask=0x8", "FL_API_VULKAN is bit 3; the ring is the layer's, not an Overlay's");
stdout.Should().NotContain("records: 0 ", stdout);
host.ExitCode.Should().Be(0, stdout);
}
/// <summary>
/// The plain harness asked to present through Vulkan for a second, under its own name — never the consented copy, whose
/// name the host resolves its target by — with its output and exit code read here: 77 and a "[SKIP]" line where this
/// machine cannot, 0 where it can. Bounded: a driver that hangs is a failure to report, not a test that never ends.
/// </summary>
private static async Task<(int ExitCode, string Output)> ProbeVulkanAsync()
{
using var probe = Process.Start(new ProcessStartInfo(Harness, "--vulkan --hold-presenting 1")
{
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardOutput = true,
})!;
using var bound = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken);
bound.CancelAfter(TimeSpan.FromSeconds(60));
try
{
string output = await probe.StandardOutput.ReadToEndAsync(bound.Token).ConfigureAwait(false);
await probe.WaitForExitAsync(bound.Token).ConfigureAwait(false);
return (probe.ExitCode, output);
}
catch (OperationCanceledException e) when (!TestContext.Current.CancellationToken.IsCancellationRequested)
{
probe.Kill(entireProcessTree: true);
throw new TimeoutException("hook-harness --vulkan --hold-presenting 1 did not end within 60 s", e);
}
}
[Fact]
public async Task WhenTheTargetExitsTheHostStopsAndSaysWhy()
{
// §S29(e). The writer leaves status READY and writeIndex frozen on the way out — DllMain has no
// DLL_PROCESS_DETACH teardown — so this can only come from the held process handle.
(await GrantConsentAsync()).Should().Be(ConsentWriteOutcome.Written);
// 15 s, not 6 (beta.18): the host resolves its target once, as it starts, and on a loaded runner a host that took
// longer than the hold found the harness gone and ended TargetNotRunning — #286's first CI run, as on 2026-09-21
// and before. The host prints nothing until its session ends, so there is no "attached" to wait for; the hold is
// the margin, and the case's run time with it.
Process harness = await StartHarnessAsync("--real --hold-presenting 15");
Process? host = null;
try
{
host = StartHost("capture", "--exe", ConsentedExecutable);
string stdout = await host.StandardOutput.ReadToEndAsync(TestContext.Current.CancellationToken);
await host.WaitForExitAsync(TestContext.Current.CancellationToken);
stdout.Should().Contain(nameof(SessionEndReason.TargetExited));
stdout.Should().Contain("guard ticks published:");
host.ExitCode.Should().Be(0, "a game closing is the ordinary end of a session");
}
finally
{
if (host is not null)
{
Kill(host);
}
Kill(harness);
}
}
/// <summary>
/// Waits for the writer to leave <see cref="FlStatus.Init"/>, because a tick and
/// <c>INIT</c> are a legitimate simultaneous state.
/// </summary>
/// <remarks>
/// <para>
/// <b>A real ordering in <c>InitThread</c>, not flakiness.</b> <c>PublishHandshake</c>
/// writes <c>layoutVersion</c> at step 2; <c>InstallPresentHooks</c> — which creates a
/// throwaway WARP D3D11 device and swapchain to read the vtable, tens of milliseconds
/// — runs at step 5; <c>status</c> becomes <c>READY</c> only at step 6.
/// <c>TryAttach</c> succeeds as soon as <c>layoutVersion</c> lands, and the host
/// publishes its first tick immediately on attach BY DESIGN, because the Overlay's
/// 65 s supervision clock starts at mapping publish. So reading status once after the
/// first tick asserts a race rather than the property.
/// </para>
/// <para>
/// Found by the post-merge run on a machine whose WARP had degraded — D3D12 WARP
/// returning <c>DXGI_ERROR_DRIVER_INTERNAL_ERROR</c>, measured — which widened step 5
/// enough to lose a race that had been won every previous time. The machine state was
/// the trigger; this was the defect, and it was mine.
/// </para>
/// </remarks>
private static async Task<FlWriterState> PollWriterPastInitAsync(int pid, TimeSpan budget)
{
FlWriterState state = default;
DateTimeOffset deadline = DateTimeOffset.UtcNow + budget;
while (DateTimeOffset.UtcNow < deadline)
{
using (MemoryMappedFile mmf = MemoryMappedFile.OpenExisting(
$@"Local\FrameLedger.Ring.{pid}", MemoryMappedFileRights.Read))
using (MemoryMappedViewAccessor view = mmf.CreateViewAccessor(0, 0, MemoryMappedFileAccess.Read))
{
state = ReadWriterState(view);
}
// "HOOKED AND RECORDING" IS TWO EVENTS, AND apiMask IS THE SECOND ONE. status becomes READY
// at InitThread step 6, immediately after the hooks are installed and BEFORE any present has
// gone through them; apiMask is set inside FindOrAdd, on the first present the hook actually
// sees. So READY with apiMask 0 is a legitimate window, and waiting only for READY left the
// apiMask assertion racing — it failed once in five full-suite runs on 2026-08-06 and never
// once in six isolated ones, which is the signature of a window widened by contention.
//
// A status that is neither INIT nor READY (SELF_DISABLED, UNHOOKED) is terminal: return it
// and let the assertions report what it is, rather than spinning to the budget.
bool stillStarting = state.Status == (uint)FlStatus.Init
|| (state.Status == (uint)FlStatus.Ready && state.ApiMask == 0);
if (!stillStarting)
{
return state;
}
await Task.Delay(100, TestContext.Current.CancellationToken).ConfigureAwait(false);
}
return state;
}
private static async Task<uint> PollGuardTicksAsync(int pid, uint atLeast, TimeSpan budget)
{
DateTimeOffset deadline = DateTimeOffset.UtcNow + budget;
uint last = 0;
while (DateTimeOffset.UtcNow < deadline)
{
try
{
using MemoryMappedFile mmf = MemoryMappedFile.OpenExisting(
$@"Local\FrameLedger.Ring.{pid}", MemoryMappedFileRights.Read);
using MemoryMappedViewAccessor view = mmf.CreateViewAccessor(0, 0, MemoryMappedFileAccess.Read);
last = view.ReadUInt32(ShmLayout.ControlOffset + 12); // FlControlBlock.guardTicks @12
if (last >= atLeast)
{
return last;
}
}
catch (FileNotFoundException)
{
// The host has not injected yet.
}
await Task.Delay(100, TestContext.Current.CancellationToken).ConfigureAwait(false);
}
return last;
}
private static unsafe FlWriterState ReadWriterState(MemoryMappedViewAccessor view)
{
byte* p = null;
view.SafeMemoryMappedViewHandle.AcquirePointer(ref p);
try
{
return *(FlWriterState*)(p + ShmLayout.WriterOffset);
}
finally
{
view.SafeMemoryMappedViewHandle.ReleasePointer();
}
}
}