Files
frameledger/tests/FrameLedger.Infrastructure.Tests/Persistence/SqliteSessionRepositoryTests.cs
T
poli0981andClaude Opus 5.5 2ce8251d31 feat: the game's own memory, measured from outside the game in every session - a C++ reader of the GPU Process Memory counters and GetProcessMemoryInfo, median and mean, schema 0018 (D43, beta.12 PR-2) (#254)
- FrameLedger.ProcessStats.dll (C++20, loaded by the Agent, never into a game): the game process's dedicated and shared
  GPU memory from the documented `GPU Process Memory` performance counters (no handle to the game, every instance of the
  pid summed) and its private working set / working set / commit from GetProcessMemoryInfo (EX2, falling back to EX)
  through PROCESS_QUERY_LIMITED_INFORMATION only (a sentinel refuses an EX2 answer whose private working set was not
  filled). Not D3DKMTQueryStatistics ("Reserved for system use").
  ctest fl_process_stats (GPU_INSTANCE on a hardware adapter, NO_GPU_INSTANCE on CI) and fl-probe-processstats.
- Measured first, decision table in spike-notes §16 written before the runs: +512.0 MiB for a 512 MiB buffer,
  private working set equal to Windows' own counter, 0.1 ms per read, nothing leaked over 600 reads; dedicated reads a
  constant 4.5 MiB above DXGI's local usage, so it is never compared with a budget.
- NativeProcessStats (third facade), GameMemoryReader: a pinned session reads through its held handle; an unpinned
  Tier-2 hold opens each process of the executable for the read, refuses a reused pid, sums. CaptureSession tells the
  observer which process (ICaptureObserver.Measuring), the recorder forwards it to the poller (ITelemetryPoller.Follow).
- TelemetrySample.Game; five sensor series; schema 0018 (game_vram_dedicated_*, game_ram_private_*, ..., sensor_stats_json);
  SeriesAggregates gains Median and Min; a wide .partial sensors chunk (type 8) with type 4 still read; SessionProgress
  and SessionHeld carry the game's memory live.
- notice-check accepts a contributor's own copyright line in the same form.
- Tests: the two classes that open a LibreHardwareMonitor Computer run one at a time - GenericCpu.Update threw a
  NullReferenceException in the local gate when they ran in parallel (the Agent's own read is already contained).
- Docs corrected in place: 03_METRICS, 18_GPU_VENDOR_APIS, 17_HOOK_ENGINE, 20_OPEN_QUESTIONS (§M7, §H10, new §M11),
  04_CAPTURE, 19_SAFETY, 06_DATA_MODEL, 07_IPC, 02_SPEC, 01_ARCHITECTURE, 12_BUILD, CLAUDE.md; the accuracy block and
  LIMITATIONS.md.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 23:21:45 +07:00

487 lines
26 KiB
C#

// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
using Dapper;
using FluentAssertions;
using FrameLedger.Application.Persistence;
using FrameLedger.Domain.Consent;
using FrameLedger.Domain.Sessions;
using FrameLedger.Infrastructure.Blobs;
using FrameLedger.Infrastructure.Persistence;
namespace FrameLedger.Infrastructure.Tests.Persistence;
/// <summary>
/// The session row, its segments and its blobs land in ONE transaction; a guid is stored once; retention keeps
/// the last N sessions' raw series and every aggregate.
/// </summary>
public sealed class SqliteSessionRepositoryTests
{
private static CancellationToken Ct => TestContext.Current.CancellationToken;
private static readonly ExecutableFingerprint _game = new() { ExePath = @"C:\Games\T\t.exe", SizeBytes = 1, MtimeUnixMs = 2 };
private static async Task<(long GameId, long SnapshotId)> SeedAsync(LedgerFixture f)
{
long gameId = (await new SqliteGameRepository(f.Db).EnsureAsync(_game, "T", Ct).ConfigureAwait(false)).Id;
long snapshotId = await new SqliteHardwareSnapshotRepository(f.Db).EnsureAsync(
new HardwareSnapshot { GpuName = "RTX 5080", CpuName = "i7-14700KF" }, DateTimeOffset.UnixEpoch, Ct).ConfigureAwait(false);
return (gameId, snapshotId);
}
private static SessionRow Row(long gameId, long snapshotId, Guid? guid = null, DateTimeOffset? started = null) => new()
{
SessionGuid = guid ?? Guid.NewGuid(),
GameId = gameId,
SnapshotId = snapshotId,
StartedAt = started ?? DateTimeOffset.FromUnixTimeMilliseconds(1_700_000_000_000),
EndedAt = (started ?? DateTimeOffset.FromUnixTimeMilliseconds(1_700_000_000_000)).AddSeconds(90),
QpcEpoch = 123_456_789_012,
QpcFrequency = 10_000_000,
Tier = CaptureTier.Hooked,
Mode = CaptureMode.Launch,
ExitStatus = ExitStatus.Normal,
AcExceptionFamily = "NetEase Yidun",
FrameCount = 5400,
AppFrameCount = 5400,
DisplayedFrameCount = 5400,
DroppedFrames = 0,
Upscaler = "dlss",
FgMode = "none",
FgSource = "none",
FgFactor = 1.0,
FgFactorScope = "steady",
FgSteadyShare = 0.75,
FgRefusalDetail = "{}",
RtFlag = "yes",
RtSource = "measured",
NativeFps = 60.0,
MedianFps = 60.5,
P1LowFps = 48.2,
ReflexActive = true,
SwapEffect = "flip_discard",
// Schema 0016 (beta.10): the display mode, every column set so the round trip covers each.
DisplayExclusiveMs = 1_000,
DisplayBorderlessMs = 80_000,
DisplayWindowedMs = 7_000,
DisplayCoversMs = 0,
DisplayMinimizedMs = 2_000,
DisplayNoWindowMs = 500,
DisplayChanges = 3,
DisplaySource = "swapchain",
DisplayWindowW = 2560,
DisplayWindowH = 1440,
DisplayBufferW = 2560,
DisplayBufferH = 1440,
DisplayMonitorW = 2560,
DisplayMonitorH = 1440,
DisplayMonitorHz = 165,
// Schema 0018 (beta.12, D43): every game-memory column non-null, or the round trip would pass without reading one.
GameVramDedicatedAvgMb = 8123.5,
GameVramDedicatedMedianMb = 8100,
GameVramDedicatedMaxMb = 9216,
GameVramSharedMaxMb = 512.25,
GameRamPrivateAvgMb = 6000.5,
GameRamPrivateMedianMb = 5990,
GameRamPrivateMaxMb = 7100,
GameRamWorkingSetMaxMb = 7600,
GameCommitMaxMb = 8800,
GameMemoryProcesses = 1,
GameMemorySource = "counters,ex2,held",
SensorStatsJson = "{\"gpu_temp\":{\"N\":3,\"Mean\":61,\"Median\":61,\"Min\":60,\"Max\":62}}",
};
private static FrameBlobs Frames(int n) => new()
{
Codec = SeriesCodec.Tag,
SampleCount = n,
FrameTimes = SeriesCodec.EncodeFloat32([.. Enumerable.Repeat(16.6f, n)]),
FrameFlags = SeriesCodec.EncodeBytes(new byte[n]),
LatencyUs = SeriesCodec.EncodeUInt32([.. Enumerable.Repeat(12_000u, n)]),
FirstPresentMs = 18_250.5,
};
[Fact]
public async Task ASessionRoundTripsColumnForColumn()
{
await using LedgerFixture f = await LedgerFixture.OpenAsync();
(long gameId, long snapshotId) = await SeedAsync(f);
var repo = new SqliteSessionRepository(f.Db);
SessionRow row = Row(gameId, snapshotId);
long id = await repo.InsertFinalizedAsync(new FinalizedSession
{
Row = row,
Segments = [new SegmentRow { SwapchainId = 1, StartFrame = 0, EndFrame = 5399, RenderW = 1485, RenderH = 835, OutputW = 2560, OutputH = 1440, Upscaler = "dlss", NativeFps = 60 }],
Frames = Frames(5400),
Sensors = [new SensorBlob { Series = "gpu_temp", Hz = 1, Codec = SeriesCodec.Tag, Data = SeriesCodec.EncodeFloat32([60f, 61f, 62f]) }],
}, Ct);
SessionRow back = (await repo.FindAsync(row.SessionGuid, Ct))!;
back.Should().BeEquivalentTo(row with { Id = id });
(await repo.ExistsAsync(row.SessionGuid, Ct)).Should().BeTrue();
(await repo.ListRecentAsync(10, Ct)).Should().ContainSingle().Which.SessionGuid.Should().Be(row.SessionGuid);
FrameBlobs frames = (await repo.FindFramesAsync(id, Ct))!;
frames.SampleCount.Should().Be(5400);
SeriesCodec.DecodeFloat32(frames.FrameTimes.ToArray()).Should().HaveCount(5400).And.OnlyContain(t => t == 16.6f);
SeriesCodec.DecodeUInt32(frames.LatencyUs!.Value.ToArray()).Should().OnlyContain(v => v == 12_000u);
string? kinds = await f.Db.ReadAsync((c, ct) => c.ExecuteScalarAsync<string?>(new CommandDefinition(
"SELECT typeof(render_res) || '/' || typeof(latency_us) || '/' || typeof(frame_index) FROM frame_blobs", cancellationToken: ct)), Ct);
kinds.Should().Be("null/blob/null", "an optional series that was not measured is stored as NULL");
frames.RenderRes.HasValue.Should().BeFalse("nothing varied, so the column stayed NULL");
frames.LatencyUs.HasValue.Should().BeTrue();
frames.FirstPresentMs.Should().Be(18_250.5, "schema 0013: where the charted stream starts on the sensors' clock");
// unix-ms on the row itself, and the tri-state text is what 06_DATA_MODEL says.
(long startedAt, string? fg, string? rt) = await f.Db.ReadAsync(async (c, ct) => (
await c.ExecuteScalarAsync<long>(new CommandDefinition("SELECT started_at FROM sessions", cancellationToken: ct)).ConfigureAwait(false),
await c.ExecuteScalarAsync<string?>(new CommandDefinition("SELECT fg_mode FROM sessions", cancellationToken: ct)).ConfigureAwait(false),
await c.ExecuteScalarAsync<string?>(new CommandDefinition("SELECT rt_flag FROM sessions", cancellationToken: ct)).ConfigureAwait(false)), Ct);
startedAt.Should().Be(1_700_000_000_000);
fg.Should().Be("none");
rt.Should().Be("yes");
}
[Fact]
public async Task ATierTwoSessionStoresTheHeaderAndNullEverywhereElse()
{
await using LedgerFixture f = await LedgerFixture.OpenAsync();
(long gameId, long snapshotId) = await SeedAsync(f);
var repo = new SqliteSessionRepository(f.Db);
var row = new SessionRow
{
SessionGuid = Guid.NewGuid(),
GameId = gameId,
SnapshotId = snapshotId,
StartedAt = DateTimeOffset.UnixEpoch,
EndedAt = DateTimeOffset.UnixEpoch.AddSeconds(120),
QpcEpoch = 0,
QpcFrequency = 10_000_000,
Tier = CaptureTier.NotHooked,
Mode = CaptureMode.Attach,
ExitStatus = ExitStatus.Normal,
CaptureNotes = "RefusedHookNotEnabled",
// beta.10: a Tier-2 session still has its window (schema 0016), and nothing to say about a swap chain.
DisplayCoversMs = 118_000,
DisplayMinimizedMs = 2_000,
DisplayExclusiveMs = 0,
DisplayBorderlessMs = 0,
DisplayWindowedMs = 0,
DisplayNoWindowMs = 0,
DisplayChanges = 2,
DisplaySource = "window",
DisplayWindowW = 1920,
DisplayWindowH = 1080,
};
await repo.InsertFinalizedAsync(new FinalizedSession { Row = row }, Ct);
SessionRow back = (await repo.FindAsync(row.SessionGuid, Ct))!;
back.Tier.Should().Be(CaptureTier.NotHooked);
back.NativeFps.Should().BeNull();
back.FgFactor.Should().BeNull();
back.FgMode.Should().Be("na", "the DEFAULT is na, never none");
back.RtFlag.Should().Be("na");
back.Upscaler.Should().BeNull();
back.CaptureNotes.Should().Be("RefusedHookNotEnabled");
(back.DisplayCoversMs, back.DisplayMinimizedMs, back.DisplayChanges, back.DisplaySource).Should().Be((118_000L, 2_000L, 2L, "window"));
(back.DisplayWindowW, back.DisplayBufferW, back.DisplayMonitorHz).Should().Be((1920, (int?)null, (int?)null));
(await repo.FindFramesAsync(back.Id, Ct)).Should().BeNull();
}
[Fact]
public async Task AFailingBlobInsertLeavesNoSessionRowBehind()
{
// 04_CAPTURE §Finalizing step 5, the whole point: two sensor blobs with the same series violate the
// primary key, and the row inserted a moment earlier must roll back with them.
await using LedgerFixture f = await LedgerFixture.OpenAsync();
(long gameId, long snapshotId) = await SeedAsync(f);
var repo = new SqliteSessionRepository(f.Db);
SessionRow row = Row(gameId, snapshotId);
SensorBlob blob = new() { Series = "gpu_temp", Hz = 1, Codec = SeriesCodec.Tag, Data = SeriesCodec.EncodeFloat32([1f]) };
Func<Task> insert = async () => await repo.InsertFinalizedAsync(new FinalizedSession { Row = row, Sensors = [blob, blob] }, Ct).ConfigureAwait(false);
await insert.Should().ThrowAsync<Microsoft.Data.Sqlite.SqliteException>();
(await repo.ExistsAsync(row.SessionGuid, Ct)).Should().BeFalse("the transaction rolled back whole");
long rows = await f.Db.ReadAsync((c, ct) => c.ExecuteScalarAsync<long>(new CommandDefinition("SELECT COUNT(*) FROM sessions", cancellationToken: ct)), Ct);
rows.Should().Be(0);
}
[Fact]
public async Task AGuidIsStoredOnce()
{
await using LedgerFixture f = await LedgerFixture.OpenAsync();
(long gameId, long snapshotId) = await SeedAsync(f);
var repo = new SqliteSessionRepository(f.Db);
SessionRow row = Row(gameId, snapshotId);
await repo.InsertFinalizedAsync(new FinalizedSession { Row = row }, Ct);
Func<Task> again = async () => await repo.InsertFinalizedAsync(new FinalizedSession { Row = row }, Ct).ConfigureAwait(false);
await again.Should().ThrowAsync<InvalidOperationException>("the recovery path asks ExistsAsync first, and the store refuses regardless");
}
/// <summary>
/// 2026-09-22/23: two GIRLS' FRONTLINE 2 sessions died on the foreign key because their entry was removed (and then
/// re-imported) while they ran. The write now names that case instead of surfacing SQLite's constraint error.
/// </summary>
[Fact]
public async Task AWriteForAGameThatIsGoneSaysSoInsteadOfFailingTheForeignKey()
{
await using LedgerFixture f = await LedgerFixture.OpenAsync();
(long gameId, long snapshotId) = await SeedAsync(f);
var repo = new SqliteSessionRepository(f.Db);
SessionRow row = Row(gameId + 1000, snapshotId);
Func<Task> insert = async () => await repo.InsertFinalizedAsync(new FinalizedSession { Row = row }, Ct).ConfigureAwait(false);
await insert.Should().ThrowAsync<SessionOwnerMissingException>();
(await repo.ExistsAsync(row.SessionGuid, Ct)).Should().BeFalse();
}
[Fact]
public async Task TheOwnerIsTheRowItStartedUnderElseTheRowHoldingItsExecutableElseNone()
{
await using LedgerFixture f = await LedgerFixture.OpenAsync();
var games = new SqliteGameRepository(f.Db);
var repo = new SqliteSessionRepository(f.Db);
GameRow original = await games.EnsureAsync(_game, "T", Ct);
DateTimeOffset afterOriginal = original.AddedAt.AddSeconds(1);
// The row it started under, still there — or repointed while it ran (Change executable, a moved drive).
(await repo.ResolveOwnerAsync(original.Id, _game.ExePath, afterOriginal, Ct)).Should().Be(original.Id);
(await repo.ResolveOwnerAsync(original.Id, @"C:\Games\T\before-the-change.exe", afterOriginal, Ct)).Should().Be(original.Id);
// Gone, and its executable held by a re-imported row: that row, whatever the path's case.
(await repo.ResolveOwnerAsync(original.Id + 1000, _game.ExePath.ToUpperInvariant(), afterOriginal, Ct)).Should().Be(original.Id);
// An id SQLite handed to a LATER game with another executable is not the session's game (no AUTOINCREMENT).
GameRow later = await games.EnsureAsync(new ExecutableFingerprint { ExePath = @"C:\Games\Other\o.exe", SizeBytes = 3, MtimeUnixMs = 4 }, "O", Ct);
(await repo.ResolveOwnerAsync(later.Id, @"C:\Games\Removed\r.exe", later.AddedAt.AddSeconds(-1), Ct)).Should().BeNull();
// Gone with nothing at its path, and a caller that knows no path: no owner.
(await repo.ResolveOwnerAsync(original.Id + 1000, @"C:\Games\Removed\r.exe", afterOriginal, Ct)).Should().BeNull();
(await repo.ResolveOwnerAsync(original.Id + 1000, null, afterOriginal, Ct)).Should().BeNull();
}
[Fact]
public async Task RetentionKeepsTheLastNSessionsRawSeriesAndEveryAggregate()
{
await using LedgerFixture f = await LedgerFixture.OpenAsync();
(long gameId, long snapshotId) = await SeedAsync(f);
var repo = new SqliteSessionRepository(f.Db);
var ids = new List<long>();
for (int i = 0; i < 5; i++)
{
ids.Add(await repo.InsertFinalizedAsync(new FinalizedSession
{
Row = Row(gameId, snapshotId, started: DateTimeOffset.UnixEpoch.AddHours(i)),
Frames = Frames(10),
Sensors = [new SensorBlob { Series = "gpu_temp", Hz = 1, Codec = SeriesCodec.Tag, Data = SeriesCodec.EncodeFloat32([1f]) }],
}, Ct));
}
int swept = await repo.SweepRetentionAsync(gameId, keep: 2, Ct);
swept.Should().Be(3);
(await repo.FindFramesAsync(ids[0], Ct)).Should().BeNull("the oldest lost its raw series");
(await repo.FindFramesAsync(ids[4], Ct)).Should().NotBeNull("the newest kept its raw series");
(await repo.ListRecentAsync(10, Ct)).Should().HaveCount(5, "aggregates and segments are kept forever");
long sensors = await f.Db.ReadAsync((c, ct) => c.ExecuteScalarAsync<long>(new CommandDefinition("SELECT COUNT(*) FROM sensor_blobs", cancellationToken: ct)), Ct);
sensors.Should().Be(2);
}
[Fact]
public async Task SweepingEveryGameKeepsTheNewestNOfEachAndCountsWhatWent()
{
// P4 PR-7: Tools ▸ Database maintenance's sweep, the per-game rule above applied to every game in one statement.
await using LedgerFixture f = await LedgerFixture.OpenAsync();
(long first, long snapshotId) = await SeedAsync(f);
long second = (await new SqliteGameRepository(f.Db).EnsureAsync(new ExecutableFingerprint { ExePath = @"C:\Games\U\u.exe", SizeBytes = 3, MtimeUnixMs = 4 }, "U", Ct)).Id;
var repo = new SqliteSessionRepository(f.Db);
var firstIds = new List<long>();
for (int i = 0; i < 4; i++)
{
firstIds.Add(await repo.InsertFinalizedAsync(new FinalizedSession { Row = Row(first, snapshotId, started: DateTimeOffset.UnixEpoch.AddHours(i)), Frames = Frames(10) }, Ct));
}
// The second game's oldest session carries sensors only (a recording nothing measured): swept, and counted once.
await repo.InsertFinalizedAsync(new FinalizedSession
{
Row = Row(second, snapshotId, started: DateTimeOffset.UnixEpoch),
Sensors = [new SensorBlob { Series = "gpu_temp", Hz = 1, Codec = SeriesCodec.Tag, Data = SeriesCodec.EncodeFloat32([1f]) }],
}, Ct);
long secondNew = await repo.InsertFinalizedAsync(new FinalizedSession { Row = Row(second, snapshotId, started: DateTimeOffset.UnixEpoch.AddHours(9)), Frames = Frames(10) }, Ct);
await repo.InsertFinalizedAsync(new FinalizedSession { Row = Row(second, snapshotId, started: DateTimeOffset.UnixEpoch.AddHours(10)), Frames = Frames(10) }, Ct);
RetentionSweepResult result = await repo.SweepRetentionAllAsync(keep: 2, Ct);
result.Should().Be(new RetentionSweepResult(Games: 2, Sessions: 3));
(await repo.FindFramesAsync(firstIds[0], Ct)).Should().BeNull();
(await repo.FindFramesAsync(firstIds[1], Ct)).Should().BeNull();
(await repo.FindFramesAsync(firstIds[2], Ct)).Should().NotBeNull("each game keeps its own newest two");
(await repo.FindFramesAsync(secondNew, Ct)).Should().NotBeNull();
long sensors = await f.Db.ReadAsync((c, ct) => c.ExecuteScalarAsync<long>(new CommandDefinition("SELECT COUNT(*) FROM sensor_blobs", cancellationToken: ct)), Ct);
sensors.Should().Be(0);
(await repo.ListRecentAsync(10, Ct)).Should().HaveCount(7, "aggregates and segments are kept forever");
(await repo.SweepRetentionAllAsync(keep: 2, Ct)).Should().Be(new RetentionSweepResult(Games: 2, Sessions: 0), "a second sweep finds nothing left to remove");
Func<Task> zero = async () => await repo.SweepRetentionAllAsync(keep: 0, Ct).ConfigureAwait(false);
await zero.Should().ThrowAsync<ArgumentOutOfRangeException>("a keep of zero would delete every raw series; unlimited is the caller's to honour by not sweeping");
}
[Fact]
public async Task ListRecentIsNewestFirstAndBounded()
{
await using LedgerFixture f = await LedgerFixture.OpenAsync();
(long gameId, long snapshotId) = await SeedAsync(f);
var repo = new SqliteSessionRepository(f.Db);
for (int i = 0; i < 3; i++)
{
await repo.InsertFinalizedAsync(new FinalizedSession { Row = Row(gameId, snapshotId, started: DateTimeOffset.UnixEpoch.AddHours(i)) }, Ct);
}
IReadOnlyList<SessionRow> recent = await repo.ListRecentAsync(2, Ct);
recent.Should().HaveCount(2);
recent[0].StartedAt.Should().BeAfter(recent[1].StartedAt);
}
[Fact]
public async Task HardwareSnapshotsAreDeduplicatedByHash()
{
await using LedgerFixture f = await LedgerFixture.OpenAsync();
var repo = new SqliteHardwareSnapshotRepository(f.Db);
var a = new HardwareSnapshot { GpuName = "RTX 5080", GpuDriver = "616.64", RamGb = 32 };
var b = new HardwareSnapshot { GpuName = " rtx 5080 ", GpuDriver = "616.64", RamGb = 32 };
var c = new HardwareSnapshot { GpuName = "RTX 5080", GpuDriver = "616.88", RamGb = 32 };
long idA = await repo.EnsureAsync(a, DateTimeOffset.UnixEpoch, Ct);
long idB = await repo.EnsureAsync(b, DateTimeOffset.UnixEpoch.AddDays(1), Ct);
long idC = await repo.EnsureAsync(c, DateTimeOffset.UnixEpoch.AddDays(2), Ct);
idB.Should().Be(idA, "the hash is over normalised fields — trimmed and case-folded");
idC.Should().NotBe(idA, "a driver update is a different machine state (FR-6.3)");
(await repo.FindAsync(idA, Ct))!.GpuName.Should().Be("RTX 5080");
(await repo.FindAsync(999, Ct)).Should().BeNull();
}
[Fact]
public async Task TheGameRepositoryRecordsCrashesInjectionsAndTheAutoDisable()
{
await using LedgerFixture f = await LedgerFixture.OpenAsync();
var games = new SqliteGameRepository(f.Db);
GameRow row = await games.EnsureAsync(_game, "T", Ct);
row.HookEnabled.Should().BeFalse("hooking is off for every newly added game");
(await games.EnsureAsync(_game, "T-again", Ct)).Id.Should().Be(row.Id, "one row per path");
(await games.RecordInjectionAsync(row.Id, DateTimeOffset.UnixEpoch.AddSeconds(5), Ct)).Should().BeTrue();
(await games.RecordCrashAsync(row.Id, Ct)).Should().Be(1);
(await games.RecordCrashAsync(row.Id, Ct)).Should().Be(2);
(await games.AutoDisableHookAsync(row.Id, "crashed twice within 60 s of injection", DateTimeOffset.UnixEpoch.AddSeconds(9), Ct)).Should().BeTrue();
GameRow after = (await games.FindAsync(_game.ExePath, Ct))!;
after.HookCrashCount.Should().Be(2);
after.HookEnabled.Should().BeFalse();
after.HookAutoDisabledReason.Should().Contain("twice");
after.HookLastInjectedAt.Should().Be(DateTimeOffset.UnixEpoch.AddSeconds(5));
(await games.AutoDisableHookAsync(999, "nobody", DateTimeOffset.UnixEpoch, Ct)).Should().BeFalse();
}
[Fact]
public async Task SettingsAndLegalAcceptanceReadWhatWasWritten()
{
await using LedgerFixture f = await LedgerFixture.OpenAsync();
var settings = new SqliteSettingsStore(f.Db);
var legal = new SqliteLegalAcceptanceStore(f.Db);
(await settings.GetAsync("hooking.kill_switch", Ct)).Should().BeNull();
await settings.SetAsync("hooking.kill_switch", "1", Ct);
await settings.SetAsync("hooking.kill_switch", "0", Ct);
(await settings.GetAsync("hooking.kill_switch", Ct)).Should().Be("0", "the second write replaces the first");
(await legal.FindAsync("EULA", Ct)).Should().BeNull("nothing in the Agent writes legal_acceptance; the UI does");
await f.Db.WriteAsync((c, tx, ct) => c.ExecuteAsync(new CommandDefinition(
"INSERT INTO legal_acceptance (doc, version, accepted_at) VALUES ('EULA', '2026-09', 1700000000000)", transaction: tx, cancellationToken: ct)), Ct);
LegalAcceptance accepted = (await legal.FindAsync("EULA", Ct))!;
accepted.Version.Should().Be("2026-09");
accepted.AcceptedAt.Should().Be(DateTimeOffset.FromUnixTimeMilliseconds(1_700_000_000_000));
}
/// <summary>
/// beta.11 (owner decision D40): Delete all sessions — one game's, then every game's — takes their segments, frame and
/// sensor series with them (they cascade), leaves the other game's sessions until asked, and never a games row.
/// </summary>
[Fact]
public async Task DeletingSessionsTakesTheirSeriesAndLeavesTheGames()
{
await using LedgerFixture f = await LedgerFixture.OpenAsync();
(long gameId, long snapshotId) = await SeedAsync(f);
long other = (await new SqliteGameRepository(f.Db).EnsureAsync(new() { ExePath = @"C:\Games\Other\other.exe", SizeBytes = 1, MtimeUnixMs = 1 }, "O", Ct)).Id;
var repo = new SqliteSessionRepository(f.Db);
foreach (long owner in new[] { gameId, gameId, other })
{
await repo.InsertFinalizedAsync(new FinalizedSession
{
Row = Row(owner, snapshotId),
Segments = [new SegmentRow { SwapchainId = 1, StartFrame = 0, EndFrame = 9 }],
Frames = Frames(10),
Sensors = [new SensorBlob { Series = "gpu_temp", Hz = 1, Codec = SeriesCodec.Tag, Data = SeriesCodec.EncodeFloat32([60f]) }],
}, Ct);
}
(await repo.DeleteSessionsAsync(gameId, Ct)).Should().Be(new RetentionSweepResult(1, 2));
(await repo.ListByGameAsync(gameId, 10, Ct)).Should().BeEmpty();
(await repo.ListByGameAsync(other, 10, Ct)).Should().ContainSingle("only the game asked for");
(await CountAsync(f, "frame_blobs")).Should().Be(1, "the series went with their sessions");
(await CountAsync(f, "sensor_blobs")).Should().Be(1);
(await CountAsync(f, "session_segments")).Should().Be(1);
(await repo.DeleteSessionsAsync(null, Ct)).Should().Be(new RetentionSweepResult(1, 1));
(await CountAsync(f, "sessions")).Should().Be(0);
(await CountAsync(f, "frame_blobs")).Should().Be(0);
(await CountAsync(f, "games")).Should().Be(2, "the library stays");
(await repo.DeleteSessionsAsync(null, Ct)).Should().Be(new RetentionSweepResult(0, 0));
}
private static Task<long> CountAsync(LedgerFixture f, string table) =>
f.Db.ReadAsync((c, ct) => c.ExecuteScalarAsync<long>(new CommandDefinition("SELECT COUNT(*) FROM " + table, cancellationToken: ct)), Ct).AsTask();
/// <summary>
/// D38 (owner decision 2026-10-03): a grant's trial counts its own sessions — hooked under that family, from the grant on,
/// frames recorded, <c>normal</c> — and nothing else: a crash, a safety unhook, a degraded or Tier-2 session, one that
/// recorded no frame, one under no exception or another family, and one from before the grant do not count.
/// </summary>
[Fact]
public async Task OnlyHookedNormalSessionsWithFramesUnderTheGrantCount()
{
await using LedgerFixture f = await LedgerFixture.OpenAsync();
(long gameId, long snapshotId) = await SeedAsync(f);
var repo = new SqliteSessionRepository(f.Db);
DateTimeOffset granted = DateTimeOffset.FromUnixTimeMilliseconds(1_700_000_000_000);
SessionRow[] rows =
[
Row(gameId, snapshotId),
Row(gameId, snapshotId) with { ExitStatus = ExitStatus.Crashed },
Row(gameId, snapshotId) with { ExitStatus = ExitStatus.UnhookedSafety },
Row(gameId, snapshotId) with { ExitStatus = ExitStatus.Degraded },
Row(gameId, snapshotId) with { Tier = CaptureTier.NotHooked },
Row(gameId, snapshotId) with { FrameCount = 0, AppFrameCount = 0, DisplayedFrameCount = 0 },
Row(gameId, snapshotId) with { AcExceptionFamily = null },
Row(gameId, snapshotId) with { AcExceptionFamily = "Anybrain" },
Row(gameId, snapshotId, started: granted.AddMinutes(-5)),
Row(gameId, snapshotId, started: granted.AddHours(1)),
];
foreach (SessionRow row in rows)
{
await repo.InsertFinalizedAsync(new FinalizedSession { Row = row }, Ct);
}
(await repo.CountSuccessfulUnderGrantAsync(gameId, "NetEase Yidun", granted, Ct)).Should().Be(2);
(await repo.CountSuccessfulUnderGrantAsync(gameId, "NetEase Yidun", granted.AddMinutes(30), Ct)).Should().Be(1, "a later grant starts its own trial");
(await repo.CountSuccessfulUnderGrantAsync(gameId + 1, "NetEase Yidun", granted, Ct)).Should().Be(0);
}
}