Files
poli0981andClaude Fable 5.2 dca740e94b feat(input): a session can store what it was played with - schema 0024, the .partial file's chunk 11, both tiers (D160)
Nine columns on sessions (the time in front and its four classes, the switches of method, the sources that answered,
the controllers as JSON) and three on games (what a store lists of controller support), ADD COLUMN only. The .partial
file gains chunk 11, so a session recovered after the Agent died keeps its readings. SessionFinalizer.Build stores
them before the tier branch: hooked, unhooked and recovered sessions alike. The input series are sensor_blobs rows
named input.*, which the sensors' read now leaves out and FindInputSensorsAsync returns.

Nothing produces a reading yet. A ledger this build has opened cannot be opened by 0.1.0-beta.49 or earlier.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-14 21:54:13 +07:00

668 lines
38 KiB
C#

// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
using System.Security.Cryptography;
using System.Text;
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) => WithSchema19(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}}",
});
/// <summary>Schema 0019 (beta.14, D49): every value distinct and non-null, for the same reason as the rest of <see cref="Row"/>.</summary>
private static SessionRow WithSchema19(SessionRow row) => row with
{
TimeBelow30Pct = 1.25,
TimeBelow60Pct = 9.5,
TimeBelowRefreshPct = 42.75,
FrametimeDeltaMeanMs = 0.875,
VsyncPresentPct = 25.5,
TearingAllowedPct = 74.5,
AvgGpuCoreClockMhz = 2655.5,
AvgGpuMemClockMhz = 15001,
AvgGpuFanRpm = 1450.25,
MaxGpuMemTemp = 78,
PowerLimitPct = 33.25,
ThermalLimitPct = 2.5,
AppFramesPerJoule = 0.3125,
RuntimeModuleSourcesJson = "{\"nvngx_dlss.dll\":\"graphics_driver\"}",
DlssNrPct = 97.25,
InputObservedMs = 5_400_000,
InputForegroundMs = 5_000_000,
InputControllerMs = 3_500_000,
InputKeyboardMouseMs = 900_000,
InputBothMs = 100_000,
InputIdleMs = 500_000,
InputMethodSwitches = 4,
InputSource = "rawinput+xinput+lastinput",
InputDevicesJson = "{\"V\":1,\"Devices\":[{\"Index\":1,\"Family\":\"playstation\",\"Model\":\"DualSense\"}]}",
FgMixJson = "{\"Rows\":[{\"Kind\":\"generated\",\"Factor\":3.99,\"NativeFps\":70.5,\"DisplayedFps\":281.3,\"Seconds\":120,\"Share\":0.75,\"Windows\":24}]}",
};
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, null, 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);
}
private const string _advancedFacts = "{\"facts\":[{\"id\":\"nvapi.session.vrr_enabled\",\"number\":1}],\"sources\":{\"nvapi\":\"Reading\",\"sensors\":\"Reading\",\"elevatedSensors\":\"NotElevated\"}}";
private static AdvancedSessionRow Advanced(string? machineFacts = "[{\"id\":\"nvapi.gpu.rt_cores\",\"number\":84}]") => new()
{
MachineFactsJson = machineFacts,
MachineHash = machineFacts is null ? null : Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(machineFacts))),
FactsJson = _advancedFacts,
StatsJson = "{\"adv.nvapi.pstate\":{\"n\":2,\"mean\":0,\"median\":0,\"min\":0,\"max\":0}}",
SeriesJson = "{\"series\":[],\"dropped\":0}",
};
private static SensorBlob[] SensorsWithAdvanced() =>
[
new() { Series = "t_ms", Hz = 1, Codec = SeriesCodec.Tag, Data = SeriesCodec.EncodeFloat32([0f, 1000f, 2000f]) },
new() { Series = "gpu_temp", Hz = 1, Codec = SeriesCodec.Tag, Data = SeriesCodec.EncodeFloat32([60f, 61f, 62f]) },
new() { Series = "adv.nvapi.pstate", Hz = 1, Codec = SeriesCodec.Tag, Data = SeriesCodec.EncodeSparseFloat32([0f, float.NaN, 0f]) },
new() { Series = "adv.lhm.board.voltage.lpc_0_7", Hz = 1, Codec = SeriesCodec.Tag, Data = SeriesCodec.EncodeSparseFloat32([-11.97f, float.NaN, float.NaN]) },
];
[Fact]
public async Task AnAdvancedSessionStoresItsRowAndItsSeriesAndTheFixedReadNeverSeesThem()
{
// Schema 0023 (owner decision D102). The advanced series are rows of sensor_blobs, and the read every summary
// and chart uses leaves them out: they hold NaN and may be negative, which those readers would misread.
await using LedgerFixture f = await LedgerFixture.OpenAsync();
(long gameId, long snapshotId) = await SeedAsync(f);
var repo = new SqliteSessionRepository(f.Db);
AdvancedSessionRow advanced = Advanced();
long id = await repo.InsertFinalizedAsync(new FinalizedSession { Row = Row(gameId, snapshotId), Sensors = SensorsWithAdvanced(), Advanced = advanced }, Ct);
(await repo.FindAdvancedAsync(id, Ct)).Should().Be(advanced);
(await repo.FindSensorsAsync(id, Ct)).Select(static s => s.Series).Should().Equal("gpu_temp", "t_ms");
IReadOnlyList<SensorBlob> series = await repo.FindAdvancedSensorsAsync(id, Ct);
series.Select(static s => s.Series).Should().Equal("t_ms", "adv.lhm.board.voltage.lpc_0_7", "adv.nvapi.pstate");
float[] rail = SeriesCodec.DecodeFloat32(series[1].Data.ToArray());
rail[0].Should().Be(-11.97f, "a negative reading is a reading");
float.IsNaN(rail[1]).Should().BeTrue("a tick with no reading is NaN");
}
[Fact]
public async Task TheInputSeriesAreReadOnTheirOwnAndTheFixedReadNeverSeesThem()
{
// Schema 0024 (D155-D163). The input series are rows of sensor_blobs too, and the read every summary and chart
// uses leaves them out: a class's number is not a sensor's value, and NaN marks a tick with nothing to say.
await using LedgerFixture f = await LedgerFixture.OpenAsync();
(long gameId, long snapshotId) = await SeedAsync(f);
var repo = new SqliteSessionRepository(f.Db);
SensorBlob[] sensors =
[
.. SensorsWithAdvanced(),
new() { Series = "input.class", Hz = 1, Codec = SeriesCodec.Tag, Data = SeriesCodec.EncodeSparseFloat32([1f, float.NaN, 2f]) },
new() { Series = "input.dev.1.active", Hz = 1, Codec = SeriesCodec.Tag, Data = SeriesCodec.EncodeSparseFloat32([1f, float.NaN, 0f]) },
];
long id = await repo.InsertFinalizedAsync(new FinalizedSession { Row = Row(gameId, snapshotId), Sensors = sensors, Advanced = Advanced() }, Ct);
long without = await repo.InsertFinalizedAsync(new FinalizedSession { Row = Row(gameId, snapshotId, started: DateTimeOffset.FromUnixTimeMilliseconds(1_700_000_000_000)), Sensors = [.. SensorsWithAdvanced().Take(2)] }, Ct);
(await repo.FindSensorsAsync(id, Ct)).Select(static s => s.Series).Should().Equal("gpu_temp", "t_ms");
(await repo.FindAdvancedSensorsAsync(id, Ct)).Select(static s => s.Series).Should().NotContain(static s => s.StartsWith("input.", StringComparison.Ordinal));
IReadOnlyList<SensorBlob> series = await repo.FindInputSensorsAsync(id, Ct);
series.Select(static s => s.Series).Should().Equal("t_ms", "input.class", "input.dev.1.active");
float[] timeline = SeriesCodec.DecodeFloat32(series[1].Data.ToArray());
timeline[0].Should().Be(1f);
float.IsNaN(timeline[1]).Should().BeTrue("a tick with the game not in front has no class");
(await repo.FindInputSensorsAsync(without, Ct)).Select(static s => s.Series).Should().Equal("t_ms");
}
[Fact]
public async Task TheAdvancedListNamesOnlySessionsRecordedWithTheOptionOnNewestFirst()
{
// What the Advanced page offers to look at (owner decision D101): a session with no row was recorded with the
// option off, and is not on the list.
await using LedgerFixture f = await LedgerFixture.OpenAsync();
(long gameId, long snapshotId) = await SeedAsync(f);
var repo = new SqliteSessionRepository(f.Db);
DateTimeOffset t0 = DateTimeOffset.FromUnixTimeMilliseconds(1_700_000_000_000);
long older = await repo.InsertFinalizedAsync(new FinalizedSession { Row = Row(gameId, snapshotId, started: t0), Sensors = SensorsWithAdvanced(), Advanced = Advanced() }, Ct);
await repo.InsertFinalizedAsync(new FinalizedSession { Row = Row(gameId, snapshotId, started: t0.AddHours(1)), Sensors = [.. SensorsWithAdvanced().Take(2)] }, Ct);
long newer = await repo.InsertFinalizedAsync(new FinalizedSession { Row = Row(gameId, snapshotId, started: t0.AddHours(2)), Sensors = SensorsWithAdvanced(), Advanced = Advanced() }, Ct);
(await repo.ListAdvancedAsync(10, Ct)).Select(static s => s.Id).Should().Equal(newer, older);
(await repo.ListAdvancedAsync(1, Ct)).Select(static s => s.Id).Should().Equal(newer);
}
[Fact]
public async Task ASessionRecordedWithTheOptionOffHasNoAdvancedRow()
{
await using LedgerFixture f = await LedgerFixture.OpenAsync();
(long gameId, long snapshotId) = await SeedAsync(f);
var repo = new SqliteSessionRepository(f.Db);
long id = await repo.InsertFinalizedAsync(new FinalizedSession { Row = Row(gameId, snapshotId), Sensors = [.. SensorsWithAdvanced().Take(2)] }, Ct);
(await repo.FindAdvancedAsync(id, Ct)).Should().BeNull("that absence is how the App says the option was off when it was recorded");
(await repo.FindAdvancedSensorsAsync(id, Ct)).Select(static s => s.Series).Should().Equal("t_ms");
(await f.Db.ReadAsync((c, ct) => c.ExecuteScalarAsync<long>(new CommandDefinition("SELECT COUNT(*) FROM machine_profiles", cancellationToken: ct)), Ct)).Should().Be(0);
}
[Fact]
public async Task TheFactsOfThePcAreStoredOncePerDistinctSet()
{
await using LedgerFixture f = await LedgerFixture.OpenAsync();
(long gameId, long snapshotId) = await SeedAsync(f);
var repo = new SqliteSessionRepository(f.Db);
DateTimeOffset t0 = DateTimeOffset.FromUnixTimeMilliseconds(1_700_000_000_000);
long first = await repo.InsertFinalizedAsync(new FinalizedSession { Row = Row(gameId, snapshotId, started: t0), Advanced = Advanced() }, Ct);
long second = await repo.InsertFinalizedAsync(new FinalizedSession { Row = Row(gameId, snapshotId, started: t0.AddHours(1)), Advanced = Advanced() }, Ct);
long changed = await repo.InsertFinalizedAsync(new FinalizedSession { Row = Row(gameId, snapshotId, started: t0.AddHours(2)), Advanced = Advanced("[{\"id\":\"nvapi.gpu.rt_cores\",\"number\":96}]") }, Ct);
long none = await repo.InsertFinalizedAsync(new FinalizedSession { Row = Row(gameId, snapshotId, started: t0.AddHours(3)), Advanced = Advanced(machineFacts: null) }, Ct);
IReadOnlyList<(long Session, long? Profile)> links = await f.Db.ReadAsync(async (c, ct) => (IReadOnlyList<(long, long?)>)[.. await c.QueryAsync<(long, long?)>(new CommandDefinition(
"SELECT session_id, machine_profile_id FROM session_advanced ORDER BY session_id", cancellationToken: ct)).ConfigureAwait(false)], Ct);
links.Select(static l => l.Session).Should().Equal(first, second, changed, none);
links[0].Profile.Should().NotBeNull().And.Be(links[1].Profile, "the same facts are one row");
links[2].Profile.Should().NotBeNull().And.NotBe(links[0].Profile, "a card with other facts is another row");
links[3].Profile.Should().BeNull("no source had a fact of the PC");
(await f.Db.ReadAsync((c, ct) => c.ExecuteScalarAsync<long>(new CommandDefinition("SELECT COUNT(*) FROM machine_profiles", cancellationToken: ct)), Ct)).Should().Be(2);
(await f.Db.ReadAsync((c, ct) => c.ExecuteScalarAsync<long>(new CommandDefinition("SELECT captured_at FROM machine_profiles ORDER BY id LIMIT 1", cancellationToken: ct)), Ct))
.Should().Be(t0.ToUnixTimeMilliseconds(), "the first session that had the set dates it");
(await repo.FindAdvancedAsync(none, Ct))!.MachineFactsJson.Should().BeNull();
(await repo.FindAdvancedAsync(second, Ct))!.MachineFactsJson.Should().Be(Advanced().MachineFactsJson);
}
[Fact]
public async Task DeletingASessionTakesItsAdvancedRowAndTheSweepTakesItsSeriesAndKeepsTheRow()
{
await using LedgerFixture f = await LedgerFixture.OpenAsync();
(long gameId, long snapshotId) = await SeedAsync(f);
var repo = new SqliteSessionRepository(f.Db);
DateTimeOffset t0 = DateTimeOffset.FromUnixTimeMilliseconds(1_700_000_000_000);
long older = await repo.InsertFinalizedAsync(new FinalizedSession { Row = Row(gameId, snapshotId, started: t0), Sensors = SensorsWithAdvanced(), Advanced = Advanced() }, Ct);
long newer = await repo.InsertFinalizedAsync(new FinalizedSession { Row = Row(gameId, snapshotId, started: t0.AddHours(1)), Sensors = SensorsWithAdvanced(), Advanced = Advanced() }, Ct);
// Retention keeps the raw series of the last session only: the older one's advanced series go with its others,
// and its facts and statistics - aggregates - stay.
await repo.SweepRetentionAsync(gameId, keep: 1, Ct);
(await repo.FindAdvancedSensorsAsync(older, Ct)).Should().BeEmpty();
(await repo.FindAdvancedAsync(older, Ct)).Should().NotBeNull("the facts and the statistics outlive the raw series");
(await repo.FindAdvancedSensorsAsync(newer, Ct)).Should().HaveCount(3);
await repo.DeleteSessionsAsync(gameId, Ct);
(await f.Db.ReadAsync((c, ct) => c.ExecuteScalarAsync<long>(new CommandDefinition("SELECT COUNT(*) FROM session_advanced", cancellationToken: ct)), Ct)).Should().Be(0, "a session deleted takes its row with it");
(await f.Db.ReadAsync((c, ct) => c.ExecuteScalarAsync<long>(new CommandDefinition("SELECT COUNT(*) FROM machine_profiles", cancellationToken: ct)), Ct)).Should().Be(1, "a profile no session points to is left, as a hardware snapshot is");
}
}