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

1052 lines
67 KiB
C#

// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
using System.Text.RegularExpressions;
using Dapper;
using FluentAssertions;
using FluentAssertions.Specialized;
using FrameLedger.Application.Persistence;
using FrameLedger.Infrastructure.Import;
using FrameLedger.Infrastructure.Persistence;
using Microsoft.Data.Sqlite;
namespace FrameLedger.Infrastructure.Tests.Persistence;
/// <summary>
/// <c>14_TESTING</c>: "SQLite migrations apply cleanly from an empty file to the current schema, and re-applying
/// is a no-op" — plus the pragmas, the refusal of a newer schema, and the transaction guarantee.
/// </summary>
public sealed class LedgerDatabaseTests
{
private static CancellationToken Ct => TestContext.Current.CancellationToken;
private static readonly string[] _tables =
[
"schema_migrations", "games", "hardware_snapshots", "sessions", "session_segments", "frame_blobs",
"sensor_blobs", "session_annotations", "settings", "legal_acceptance", "machine_profiles", "session_advanced",
];
[Fact]
public async Task AnEmptyFileMigratesToTheCurrentSchema()
{
await using LedgerFixture f = await LedgerFixture.OpenAsync();
f.Db.Migration.Should().Be(MigrationOutcome.Applied);
f.Db.SchemaVersion.Should().Be(MigrationRunner.LatestVersion);
IReadOnlyList<string> tables = await f.Db.ReadAsync(async (c, ct) =>
(IReadOnlyList<string>)[.. await c.QueryAsync<string>(new CommandDefinition(
"SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name", cancellationToken: ct)).ConfigureAwait(false)], Ct);
tables.Should().Contain(_tables);
}
/// <summary>Schema 0003 (2026-09-14): <c>sessions.fg_refusal</c>, the reason an identified frame generation has no factor.</summary>
[Fact]
public async Task ScriptThreeAddsTheFgRefusalColumn()
{
await using LedgerFixture f = await LedgerFixture.OpenAsync();
MigrationRunner.LatestVersion.Should().BeGreaterThanOrEqualTo(3);
IReadOnlyList<string> columns = await f.Db.ReadAsync(async (c, ct) =>
(IReadOnlyList<string>)[.. await c.QueryAsync<string>(new CommandDefinition(
"SELECT name FROM pragma_table_info('sessions')", cancellationToken: ct)).ConfigureAwait(false)], Ct);
columns.Should().Contain("fg_refusal").And.Contain("fg_none_withheld_reason", "0003 appends beside 0001's columns, it edits nothing");
}
/// <summary>Schema 0004 (P4 PR-1): the detection cache key's exe half on <c>games</c>, apart from the consent fingerprint.</summary>
[Fact]
public async Task ScriptFourAddsTheDetectionCacheColumns()
{
await using LedgerFixture f = await LedgerFixture.OpenAsync();
MigrationRunner.LatestVersion.Should().BeGreaterThanOrEqualTo(4);
IReadOnlyList<string> columns = await f.Db.ReadAsync(async (c, ct) =>
(IReadOnlyList<string>)[.. await c.QueryAsync<string>(new CommandDefinition(
"SELECT name FROM pragma_table_info('games')", cancellationToken: ct)).ConfigureAwait(false)], Ct);
columns.Should().Contain("detection_exe_size_bytes").And.Contain("detection_exe_mtime_ms")
.And.Contain("exe_size_bytes", "the consent fingerprint keeps its own columns; the sweep never writes them");
}
/// <summary>Schema 0005 (2026-09-16): <c>sessions.fg_refusal_detail</c>, the numbers behind the refusal.</summary>
[Fact]
public async Task ScriptFiveAddsTheFgRefusalDetailColumn()
{
await using LedgerFixture f = await LedgerFixture.OpenAsync();
MigrationRunner.LatestVersion.Should().BeGreaterThanOrEqualTo(5);
IReadOnlyList<string> columns = await f.Db.ReadAsync(async (c, ct) =>
(IReadOnlyList<string>)[.. await c.QueryAsync<string>(new CommandDefinition(
"SELECT name FROM pragma_table_info('sessions')", cancellationToken: ct)).ConfigureAwait(false)], Ct);
columns.Should().Contain("fg_refusal_detail").And.Contain("fg_refusal", "0005 appends beside 0003's column, it edits nothing");
}
/// <summary>Schema 0006 (2026-09-17): which part of the session <c>fg_factor</c> describes, and how much of it.</summary>
[Fact]
public async Task ScriptSixAddsTheFgScopeColumns()
{
await using LedgerFixture f = await LedgerFixture.OpenAsync();
MigrationRunner.LatestVersion.Should().BeGreaterThanOrEqualTo(6);
IReadOnlyList<string> columns = await f.Db.ReadAsync(async (c, ct) =>
(IReadOnlyList<string>)[.. await c.QueryAsync<string>(new CommandDefinition(
"SELECT name FROM pragma_table_info('sessions')", cancellationToken: ct)).ConfigureAwait(false)], Ct);
columns.Should().Contain("fg_factor_scope").And.Contain("fg_steady_share").And.Contain("fg_refusal_detail", "0006 appends beside 0005's column, it edits nothing");
}
/// <summary>
/// Schema 0008 (2026-09-22): the bypass is withdrawn and its five columns go with it — the one DROP COLUMN in the
/// migration set, which is why the engine's version floor is asserted beside it (SQLite ≥ 3.35.0).
/// </summary>
[Fact]
public async Task ScriptEightDropsTheBypassColumns()
{
await using LedgerFixture f = await LedgerFixture.OpenAsync();
MigrationRunner.LatestVersion.Should().BeGreaterThanOrEqualTo(8);
string? version = await f.Db.ReadAsync((c, ct) => c.ExecuteScalarAsync<string>(new CommandDefinition("SELECT sqlite_version()", cancellationToken: ct)), Ct);
Version.Parse(version ?? string.Empty).Should().BeGreaterThanOrEqualTo(new Version(3, 35, 0), "ALTER TABLE ... DROP COLUMN needs it");
IReadOnlyList<string> games = await f.Db.ReadAsync(async (c, ct) =>
(IReadOnlyList<string>)[.. await c.QueryAsync<string>(new CommandDefinition(
"SELECT name FROM pragma_table_info('games')", cancellationToken: ct)).ConfigureAwait(false)], Ct);
IReadOnlyList<string> sessions = await f.Db.ReadAsync(async (c, ct) =>
(IReadOnlyList<string>)[.. await c.QueryAsync<string>(new CommandDefinition(
"SELECT name FROM pragma_table_info('sessions')", cancellationToken: ct)).ConfigureAwait(false)], Ct).ConfigureAwait(true);
games.Should().NotContain("guard_bypass_at").And.NotContain("guard_bypass_disclosure_version")
.And.Contain("hook_blocked_reason", "the block is what a finding writes now");
sessions.Should().NotContain("guard_bypassed").And.NotContain("guard_bypass_family").And.NotContain("guard_bypass_signal");
}
/// <summary>
/// Take a migrated ledger back to <paramref name="version"/>: every column a later script ADDED is dropped, newest first,
/// and those scripts' <c>schema_migrations</c> rows go. The runner applies what is above MAX(version), so a rewind that
/// left a later script's columns in place would fail on its ALTER the moment that script re-ran — which is what the
/// hand-written rewind this replaced (2026-09-25) would have done as soon as schema 0010 existed.
/// </summary>
private static async Task RewindToAsync(SqliteConnection c, int version)
{
foreach (string sql in MigrationRunner.Scripts().Where(p => p.Key > version).OrderByDescending(static p => p.Key).Select(static p => p.Value))
{
// 0023 is the first script since 0001 that creates a table: what a later script created is dropped, an
// index before its table and the tables in the reverse of the order they were created in (the second one
// references the first).
foreach (Match m in Regex.Matches(sql, @"^CREATE\s+INDEX\s+(?<name>\w+)", RegexOptions.IgnoreCase | RegexOptions.Multiline, TimeSpan.FromSeconds(1)))
{
await c.ExecuteAsync(new CommandDefinition($"DROP INDEX IF EXISTS {m.Groups["name"].Value}", cancellationToken: Ct)).ConfigureAwait(false);
}
foreach (Match m in Regex.Matches(sql, @"^CREATE\s+TABLE\s+(?<name>\w+)", RegexOptions.IgnoreCase | RegexOptions.Multiline, TimeSpan.FromSeconds(1)).Reverse())
{
await c.ExecuteAsync(new CommandDefinition($"DROP TABLE IF EXISTS {m.Groups["name"].Value}", cancellationToken: Ct)).ConfigureAwait(false);
}
foreach (Match m in Regex.Matches(sql, @"ALTER\s+TABLE\s+(?<table>\w+)\s+ADD\s+COLUMN\s+(?<column>\w+)", RegexOptions.IgnoreCase,
TimeSpan.FromSeconds(1)).Reverse())
{
await c.ExecuteAsync(new CommandDefinition($"ALTER TABLE {m.Groups["table"].Value} DROP COLUMN {m.Groups["column"].Value}",
cancellationToken: Ct)).ConfigureAwait(false);
}
}
await c.ExecuteAsync(new CommandDefinition($"DELETE FROM schema_migrations WHERE version > {version}; PRAGMA wal_checkpoint(TRUNCATE);",
cancellationToken: Ct)).ConfigureAwait(false);
}
/// <summary>
/// Schema 0018 (2026-10-03, beta.12, D43): the game process's own memory and the sensor statistics, twelve columns, ADD
/// COLUMN only — a session written before has none of them (N/A, never a zero), and a new one writes and reads each.
/// </summary>
[Fact]
public async Task ScriptEighteenAddsTheGameMemoryColumnsAndAnEarlierSessionHasNone()
{
await using LedgerFixture f = await LedgerFixture.OpenAsync();
MigrationRunner.LatestVersion.Should().BeGreaterThanOrEqualTo(18);
long gameId = (await new SqliteGameRepository(f.Db).EnsureAsync(
new() { ExePath = @"C:\Games\M\m.exe", SizeBytes = 1, MtimeUnixMs = 2 }, "M", Ct).ConfigureAwait(true)).Id;
long snapshotId = await new SqliteHardwareSnapshotRepository(f.Db).EnsureAsync(new HardwareSnapshot { GpuName = "g" }, DateTimeOffset.UnixEpoch, Ct)
.ConfigureAwait(true);
string path = f.Path;
await f.Db.DisposeAsync().ConfigureAwait(true);
var c17 = new SqliteConnection(new SqliteConnectionStringBuilder { DataSource = path, Pooling = false }.ToString());
await using (c17.ConfigureAwait(true))
{
await c17.OpenAsync(Ct).ConfigureAwait(true);
await RewindToAsync(c17, 17).ConfigureAwait(true);
await c17.ExecuteAsync(new CommandDefinition(
"INSERT INTO sessions (session_guid, game_id, snapshot_id, started_at, ended_at, duration_s, qpc_epoch, qpc_frequency, capture_tier, capture_mode, exit_status, frame_count, app_frame_count, displayed_frame_count, dropped_frames) "
+ "VALUES ('00000000-0000-0000-0000-000000000018', @gameId, @snapshotId, 0, 60000, 60, 0, 10000000, 2, 'attach', 'normal', 0, 0, 0, 0)",
new { gameId, snapshotId }, cancellationToken: Ct)).ConfigureAwait(true);
}
LedgerDatabase migrated = await LedgerDatabase.OpenAsync(path, ct: Ct).ConfigureAwait(true);
await using (migrated.ConfigureAwait(true))
{
migrated.SchemaVersion.Should().Be(MigrationRunner.LatestVersion);
long columns = await migrated.ReadAsync((c, ct) => c.ExecuteScalarAsync<long>(new CommandDefinition(
"SELECT COUNT(*) FROM pragma_table_info('sessions') WHERE (substr(name, 1, 5) = 'game_' AND name <> 'game_id') OR name = 'sensor_stats_json'", cancellationToken: ct)), Ct)
.ConfigureAwait(true);
columns.Should().Be(12);
SessionRow before = (await new SqliteSessionRepository(migrated).FindAsync(Guid.Parse("00000000-0000-0000-0000-000000000018"), Ct).ConfigureAwait(true))!;
before.GameVramDedicatedMaxMb.Should().BeNull("a session recorded before beta.12 has no game memory, and reads N/A");
before.GameRamPrivateMedianMb.Should().BeNull();
before.GameMemorySource.Should().BeNull();
before.SensorStatsJson.Should().BeNull();
}
}
/// <summary>
/// Schema 0019 (2026-10-06, beta.14, D49): pacing, the present arguments, the card's clocks and limits and efficiency,
/// thirteen REAL columns, ADD COLUMN only — a session written before has none of them and reads N/A, never a zero.
/// </summary>
[Fact]
public async Task ScriptNineteenAddsThePacingAndCardColumnsAndAnEarlierSessionHasNone()
{
await using LedgerFixture f = await LedgerFixture.OpenAsync();
MigrationRunner.LatestVersion.Should().BeGreaterThanOrEqualTo(19);
long gameId = (await new SqliteGameRepository(f.Db).EnsureAsync(
new() { ExePath = @"C:\Games\P\p.exe", SizeBytes = 1, MtimeUnixMs = 2 }, "P", Ct).ConfigureAwait(true)).Id;
long snapshotId = await new SqliteHardwareSnapshotRepository(f.Db).EnsureAsync(new HardwareSnapshot { GpuName = "g" }, DateTimeOffset.UnixEpoch, Ct)
.ConfigureAwait(true);
string path = f.Path;
await f.Db.DisposeAsync().ConfigureAwait(true);
var c18 = new SqliteConnection(new SqliteConnectionStringBuilder { DataSource = path, Pooling = false }.ToString());
await using (c18.ConfigureAwait(true))
{
await c18.OpenAsync(Ct).ConfigureAwait(true);
await RewindToAsync(c18, 18).ConfigureAwait(true);
await c18.ExecuteAsync(new CommandDefinition(
"INSERT INTO sessions (session_guid, game_id, snapshot_id, started_at, ended_at, duration_s, qpc_epoch, qpc_frequency, capture_tier, capture_mode, exit_status, frame_count, app_frame_count, displayed_frame_count, dropped_frames, avg_gpu_power_w) "
+ "VALUES ('00000000-0000-0000-0000-000000000019', @gameId, @snapshotId, 0, 60000, 60, 0, 10000000, 1, 'attach', 'normal', 6000, 6000, 6000, 0, 250)",
new { gameId, snapshotId }, cancellationToken: Ct)).ConfigureAwait(true);
}
LedgerDatabase migrated = await LedgerDatabase.OpenAsync(path, ct: Ct).ConfigureAwait(true);
await using (migrated.ConfigureAwait(true))
{
migrated.SchemaVersion.Should().Be(MigrationRunner.LatestVersion);
IReadOnlyList<string> added = await migrated.ReadAsync(async (c, ct) => (IReadOnlyList<string>)[.. await c.QueryAsync<string>(new CommandDefinition(
"SELECT name FROM pragma_table_info('sessions') WHERE name IN ('time_below_30_pct', 'time_below_60_pct', 'time_below_refresh_pct', "
+ "'frametime_delta_mean_ms', 'vsync_present_pct', 'tearing_allowed_pct', 'avg_gpu_core_clock_mhz', 'avg_gpu_mem_clock_mhz', "
+ "'avg_gpu_fan_rpm', 'max_gpu_mem_temp', 'power_limit_pct', 'thermal_limit_pct', 'app_frames_per_joule') AND type = 'REAL'",
cancellationToken: ct)).ConfigureAwait(false)], Ct).ConfigureAwait(true);
added.Should().HaveCount(13);
SessionRow before = (await new SqliteSessionRepository(migrated).FindAsync(Guid.Parse("00000000-0000-0000-0000-000000000019"), Ct).ConfigureAwait(true))!;
before.AvgGpuPowerW.Should().Be(250, "the row keeps everything it had");
before.TimeBelow60Pct.Should().BeNull("a session recorded before beta.14 has no pacing, and reads N/A");
before.VsyncPresentPct.Should().BeNull();
before.AvgGpuCoreClockMhz.Should().BeNull();
before.PowerLimitPct.Should().BeNull();
before.AppFramesPerJoule.Should().BeNull("never computed after the fact from the stored averages");
}
}
/// <summary>
/// Schema 0020 (2026-10-19, beta.24, D62): <c>sessions.fg_mix</c>, every frame-generation state a session held, as JSON
/// — ADD COLUMN only; a session written before has none and is never rebuilt from its stored frames.
/// </summary>
[Fact]
public async Task ScriptTwentyAddsTheFgMixColumnAndAnEarlierSessionHasNone()
{
await using LedgerFixture f = await LedgerFixture.OpenAsync();
MigrationRunner.LatestVersion.Should().BeGreaterThanOrEqualTo(20);
long gameId = (await new SqliteGameRepository(f.Db).EnsureAsync(
new() { ExePath = @"C:\Games\M\m.exe", SizeBytes = 1, MtimeUnixMs = 2 }, "M", Ct).ConfigureAwait(true)).Id;
long snapshotId = await new SqliteHardwareSnapshotRepository(f.Db).EnsureAsync(new HardwareSnapshot { GpuName = "g" }, DateTimeOffset.UnixEpoch, Ct)
.ConfigureAwait(true);
string path = f.Path;
await f.Db.DisposeAsync().ConfigureAwait(true);
var c19 = new SqliteConnection(new SqliteConnectionStringBuilder { DataSource = path, Pooling = false }.ToString());
await using (c19.ConfigureAwait(true))
{
await c19.OpenAsync(Ct).ConfigureAwait(true);
await RewindToAsync(c19, 19).ConfigureAwait(true);
await c19.ExecuteAsync(new CommandDefinition(
"INSERT INTO sessions (session_guid, game_id, snapshot_id, started_at, ended_at, duration_s, qpc_epoch, qpc_frequency, capture_tier, capture_mode, exit_status, frame_count, app_frame_count, displayed_frame_count, dropped_frames, fg_mode, fg_factor, fg_factor_scope, fg_steady_share) "
+ "VALUES ('00000000-0000-0000-0000-000000000020', @gameId, @snapshotId, 0, 60000, 60, 0, 10000000, 1, 'attach', 'normal', 6000, 1500, 6000, 0, 'dlssg', 4.0, 'steady', 0.75)",
new { gameId, snapshotId }, cancellationToken: Ct)).ConfigureAwait(true);
}
LedgerDatabase migrated = await LedgerDatabase.OpenAsync(path, ct: Ct).ConfigureAwait(true);
await using (migrated.ConfigureAwait(true))
{
migrated.SchemaVersion.Should().Be(MigrationRunner.LatestVersion);
IReadOnlyList<string> added = await migrated.ReadAsync(async (c, ct) => (IReadOnlyList<string>)[.. await c.QueryAsync<string>(new CommandDefinition(
"SELECT name FROM pragma_table_info('sessions') WHERE name = 'fg_mix' AND type = 'TEXT'", cancellationToken: ct)).ConfigureAwait(false)], Ct).ConfigureAwait(true);
added.Should().ContainSingle();
SessionRow before = (await new SqliteSessionRepository(migrated).FindAsync(Guid.Parse("00000000-0000-0000-0000-000000000020"), Ct).ConfigureAwait(true))!;
before.FgFactor.Should().Be(4.0, "the row keeps everything it had");
before.FgSteadyShare.Should().Be(0.75);
before.FgMixJson.Should().BeNull("a session recorded before beta.24 has no mix, and is not rebuilt from its frames");
}
}
/// <summary>
/// Schema 0021 (2026-10-19, beta.24, D64): <c>sessions.runtime_module_sources</c>, each loaded module's folder class — ADD
/// COLUMN only; a session written before has none.
/// </summary>
[Fact]
public async Task ScriptTwentyOneAddsTheModuleSourcesColumnAndAnEarlierSessionHasNone()
{
await using LedgerFixture f = await LedgerFixture.OpenAsync();
MigrationRunner.LatestVersion.Should().BeGreaterThanOrEqualTo(21);
long gameId = (await new SqliteGameRepository(f.Db).EnsureAsync(
new() { ExePath = @"C:\Games\N\n.exe", SizeBytes = 1, MtimeUnixMs = 2 }, "N", Ct).ConfigureAwait(true)).Id;
long snapshotId = await new SqliteHardwareSnapshotRepository(f.Db).EnsureAsync(new HardwareSnapshot { GpuName = "g" }, DateTimeOffset.UnixEpoch, Ct)
.ConfigureAwait(true);
string path = f.Path;
await f.Db.DisposeAsync().ConfigureAwait(true);
var c20 = new SqliteConnection(new SqliteConnectionStringBuilder { DataSource = path, Pooling = false }.ToString());
await using (c20.ConfigureAwait(true))
{
await c20.OpenAsync(Ct).ConfigureAwait(true);
await RewindToAsync(c20, 20).ConfigureAwait(true);
await c20.ExecuteAsync(new CommandDefinition(
"INSERT INTO sessions (session_guid, game_id, snapshot_id, started_at, ended_at, duration_s, qpc_epoch, qpc_frequency, capture_tier, capture_mode, exit_status, frame_count, app_frame_count, displayed_frame_count, dropped_frames, runtime_modules) "
+ "VALUES ('00000000-0000-0000-0000-000000000021', @gameId, @snapshotId, 0, 60000, 60, 0, 10000000, 1, 'attach', 'normal', 6000, 6000, 6000, 0, '{\"nvngx_dlss.dll\":\"310,9,1,0\"}')",
new { gameId, snapshotId }, cancellationToken: Ct)).ConfigureAwait(true);
}
LedgerDatabase migrated = await LedgerDatabase.OpenAsync(path, ct: Ct).ConfigureAwait(true);
await using (migrated.ConfigureAwait(true))
{
migrated.SchemaVersion.Should().Be(MigrationRunner.LatestVersion);
IReadOnlyList<string> added = await migrated.ReadAsync(async (c, ct) => (IReadOnlyList<string>)[.. await c.QueryAsync<string>(new CommandDefinition(
"SELECT name FROM pragma_table_info('sessions') WHERE name = 'runtime_module_sources' AND type = 'TEXT'", cancellationToken: ct)).ConfigureAwait(false)], Ct).ConfigureAwait(true);
added.Should().ContainSingle();
SessionRow before = (await new SqliteSessionRepository(migrated).FindAsync(Guid.Parse("00000000-0000-0000-0000-000000000021"), Ct).ConfigureAwait(true))!;
before.RuntimeModulesJson.Should().Be("{\"nvngx_dlss.dll\":\"310,9,1,0\"}", "the row keeps everything it had");
before.RuntimeModuleSourcesJson.Should().BeNull("a session recorded before beta.24 has no folder classes");
}
}
/// <summary>
/// Schema 0022 (2026-11-06, beta.34, D84): <c>sessions.dlss_nr_pct</c>, DLSS 5's neural rendering measured — ADD COLUMN
/// only; a session written before has none, and is not rebuilt (its frames keep no feature byte).
/// </summary>
[Fact]
public async Task ScriptTwentyTwoAddsTheNeuralRenderingColumnAndAnEarlierSessionHasNone()
{
await using LedgerFixture f = await LedgerFixture.OpenAsync();
MigrationRunner.LatestVersion.Should().BeGreaterThanOrEqualTo(22);
long gameId = (await new SqliteGameRepository(f.Db).EnsureAsync(
new() { ExePath = @"C:\Games\H\h.exe", SizeBytes = 1, MtimeUnixMs = 2 }, "H", Ct).ConfigureAwait(true)).Id;
long snapshotId = await new SqliteHardwareSnapshotRepository(f.Db).EnsureAsync(new HardwareSnapshot { GpuName = "g" }, DateTimeOffset.UnixEpoch, Ct)
.ConfigureAwait(true);
string path = f.Path;
await f.Db.DisposeAsync().ConfigureAwait(true);
var c21 = new SqliteConnection(new SqliteConnectionStringBuilder { DataSource = path, Pooling = false }.ToString());
await using (c21.ConfigureAwait(true))
{
await c21.OpenAsync(Ct).ConfigureAwait(true);
await RewindToAsync(c21, 21).ConfigureAwait(true);
await c21.ExecuteAsync(new CommandDefinition(
"INSERT INTO sessions (session_guid, game_id, snapshot_id, started_at, ended_at, duration_s, qpc_epoch, qpc_frequency, capture_tier, capture_mode, exit_status, frame_count, app_frame_count, displayed_frame_count, dropped_frames, runtime_modules) "
+ "VALUES ('00000000-0000-0000-0000-000000000022', @gameId, @snapshotId, 0, 60000, 60, 0, 10000000, 1, 'attach', 'normal', 6000, 6000, 6000, 0, '{\"nvngx_dlssnr.dll\":\"310,9,16,0\"}')",
new { gameId, snapshotId }, cancellationToken: Ct)).ConfigureAwait(true);
}
LedgerDatabase migrated = await LedgerDatabase.OpenAsync(path, ct: Ct).ConfigureAwait(true);
await using (migrated.ConfigureAwait(true))
{
migrated.SchemaVersion.Should().Be(MigrationRunner.LatestVersion);
IReadOnlyList<string> added = await migrated.ReadAsync(async (c, ct) => (IReadOnlyList<string>)[.. await c.QueryAsync<string>(new CommandDefinition(
"SELECT name FROM pragma_table_info('sessions') WHERE name = 'dlss_nr_pct' AND type = 'REAL'", cancellationToken: ct)).ConfigureAwait(false)], Ct).ConfigureAwait(true);
added.Should().ContainSingle();
SessionRow before = (await new SqliteSessionRepository(migrated).FindAsync(Guid.Parse("00000000-0000-0000-0000-000000000022"), Ct).ConfigureAwait(true))!;
before.RuntimeModulesJson.Should().Be("{\"nvngx_dlssnr.dll\":\"310,9,16,0\"}", "the row keeps everything it had");
before.DlssNrPct.Should().BeNull("a session recorded before beta.34 says only that DLSS 5's runtime was loaded");
}
}
/// <summary>
/// Schema 0017 (2026-10-03, beta.11, D38): <c>games.ac_exception_trial_failed_at</c>, NULL on every row written before — a
/// grant made under D33 keeps everything it had and carries no failed trial.
/// </summary>
[Fact]
public async Task ScriptSeventeenAddsTheTrialMarkAndChangesNoRow()
{
await using LedgerFixture f = await LedgerFixture.OpenAsync();
MigrationRunner.LatestVersion.Should().BeGreaterThanOrEqualTo(17);
string path = f.Path;
await f.Db.DisposeAsync().ConfigureAwait(true);
var c16 = new SqliteConnection(new SqliteConnectionStringBuilder { DataSource = path, Pooling = false }.ToString());
await using (c16.ConfigureAwait(true))
{
await c16.OpenAsync(Ct).ConfigureAwait(true);
await RewindToAsync(c16, 16).ConfigureAwait(true);
await c16.ExecuteAsync(new CommandDefinition(
"INSERT INTO games (name, exe_path, hook_blocked_reason, hook_prescan_state, ac_exception_at, ac_exception_family, ac_exception_sessions, "
+ "added_at, updated_at) VALUES ('GF2', 'C:\\GF2\\GF2_Exilium.exe', 'AntiCheatFile|NetEase Yidun|NEP2.dll', 'blocked', 1000, 'NetEase Yidun', 3, 0, 0)",
cancellationToken: Ct)).ConfigureAwait(true);
}
LedgerDatabase migrated = await LedgerDatabase.OpenAsync(path, ct: Ct).ConfigureAwait(true);
await using (migrated.ConfigureAwait(true))
{
migrated.SchemaVersion.Should().Be(MigrationRunner.LatestVersion);
long columns = await migrated.ReadAsync((c, ct) => c.ExecuteScalarAsync<long>(new CommandDefinition(
"SELECT COUNT(*) FROM pragma_table_info('games') WHERE name = 'ac_exception_trial_failed_at'", cancellationToken: ct)), Ct).ConfigureAwait(true);
columns.Should().Be(1);
GameRow row = (await new SqliteGameRepository(migrated).FindAsync(@"C:\GF2\GF2_Exilium.exe", Ct).ConfigureAwait(true))!;
row.AcException.IsGranted.Should().BeTrue("0017 edits no row: a D33 grant stays in force");
row.AcException.Sessions.Should().Be(3);
row.AcException.TrialFailedAt.Should().BeNull();
}
}
/// <summary>
/// Schema 0016 (2026-09-27, beta.10): the display mode's fifteen columns, ADD COLUMN only — a session written before it
/// has none of them (N/A, never a zero), and a new one writes and reads each.
/// </summary>
[Fact]
public async Task ScriptSixteenAddsTheDisplayColumnsAndAnEarlierSessionHasNone()
{
await using LedgerFixture f = await LedgerFixture.OpenAsync();
MigrationRunner.LatestVersion.Should().BeGreaterThanOrEqualTo(16);
long gameId = (await new SqliteGameRepository(f.Db).EnsureAsync(
new() { ExePath = @"C:\Games\D\d.exe", SizeBytes = 1, MtimeUnixMs = 2 }, "D", Ct).ConfigureAwait(true)).Id;
long snapshotId = await new SqliteHardwareSnapshotRepository(f.Db).EnsureAsync(new HardwareSnapshot { GpuName = "g" }, DateTimeOffset.UnixEpoch, Ct)
.ConfigureAwait(true);
string path = f.Path;
await f.Db.DisposeAsync().ConfigureAwait(true);
var c15 = new SqliteConnection(new SqliteConnectionStringBuilder { DataSource = path, Pooling = false }.ToString());
await using (c15.ConfigureAwait(true))
{
await c15.OpenAsync(Ct).ConfigureAwait(true);
await RewindToAsync(c15, 15).ConfigureAwait(true);
await c15.ExecuteAsync(new CommandDefinition(
"INSERT INTO sessions (session_guid, game_id, snapshot_id, started_at, ended_at, duration_s, qpc_epoch, qpc_frequency, capture_tier, capture_mode, exit_status, frame_count, app_frame_count, displayed_frame_count, dropped_frames) "
+ "VALUES ('00000000-0000-0000-0000-000000000016', @gameId, @snapshotId, 0, 60000, 60, 0, 10000000, 2, 'attach', 'normal', 0, 0, 0, 0)",
new { gameId, snapshotId }, cancellationToken: Ct)).ConfigureAwait(true);
}
LedgerDatabase migrated = await LedgerDatabase.OpenAsync(path, ct: Ct).ConfigureAwait(true);
await using (migrated.ConfigureAwait(true))
{
migrated.SchemaVersion.Should().Be(MigrationRunner.LatestVersion);
long columns = await migrated.ReadAsync((c, ct) => c.ExecuteScalarAsync<long>(new CommandDefinition(
"SELECT COUNT(*) FROM pragma_table_info('sessions') WHERE substr(name, 1, 8) = 'display_'", cancellationToken: ct)), Ct).ConfigureAwait(true);
columns.Should().Be(15);
SessionRow before = (await new SqliteSessionRepository(migrated).FindAsync(Guid.Parse("00000000-0000-0000-0000-000000000016"), Ct).ConfigureAwait(true))!;
before.DisplayExclusiveMs.Should().BeNull("a session recorded before beta.10 has no display facts, and reads N/A");
before.DisplaySource.Should().BeNull();
before.DisplayMonitorHz.Should().BeNull();
}
}
/// <summary>
/// Schema 0015 (2026-09-27, beta.10): <c>games.engine_version_source</c>, and the bare "4"/"5" the old Unreal rule wrote
/// removed — only where detection wrote it. A value the user typed, one with no provenance badge, another engine's, and a
/// row whose provenance cannot even be parsed are left exactly as they were, and the last does not fail the migration.
/// </summary>
[Fact]
public async Task ScriptFifteenAddsTheWitnessAndRemovesOnlyTheOldRulesDetectedDigit()
{
await using LedgerFixture f = await LedgerFixture.OpenAsync();
MigrationRunner.LatestVersion.Should().BeGreaterThanOrEqualTo(15);
string path = f.Path;
await f.Db.DisposeAsync().ConfigureAwait(true);
var c14 = new SqliteConnection(new SqliteConnectionStringBuilder { DataSource = path, Pooling = false }.ToString());
await using (c14.ConfigureAwait(true))
{
await c14.OpenAsync(Ct).ConfigureAwait(true);
await RewindToAsync(c14, 14).ConfigureAwait(true);
foreach ((string exe, string engine, string version, string? provenance) in new[]
{
(@"C:\a\A-Win64-Shipping.exe", "unreal", "5", "{\"engine\":\"detected\",\"engine_version\":\"detected\"}"),
(@"C:\b\B-Win64-Shipping.exe", "unreal", "4", "{\"engine_version\":\"user\"}"),
(@"C:\c\C-Win64-Shipping.exe", "unreal", "5", null),
(@"C:\d\D.exe", "unity", "5", "{\"engine_version\":\"detected\"}"),
(@"C:\e\E-Win64-Shipping.exe", "unreal", "4", "{not json"),
(@"C:\f\F-Win64-Shipping.exe", "unreal", "4.27", "{\"engine_version\":\"detected\"}"),
})
{
await c14.ExecuteAsync(new CommandDefinition(
"INSERT INTO games (name, exe_path, engine, engine_version, field_provenance, added_at, updated_at) VALUES (@exe, @exe, @engine, @version, @provenance, 0, 0)",
new { exe, engine, version, provenance }, cancellationToken: Ct)).ConfigureAwait(true);
}
}
LedgerDatabase migrated = await LedgerDatabase.OpenAsync(path, ct: Ct).ConfigureAwait(true);
await using (migrated.ConfigureAwait(true))
{
migrated.SchemaVersion.Should().Be(MigrationRunner.LatestVersion);
var repo = new SqliteGameRepository(migrated);
(await repo.FindAsync(@"C:\a\A-Win64-Shipping.exe", Ct).ConfigureAwait(true))!.EngineVersion.Should().BeNull("the old rule's digit, detected");
(await repo.FindAsync(@"C:\b\B-Win64-Shipping.exe", Ct).ConfigureAwait(true))!.EngineVersion.Should().Be("4", "the user typed it");
(await repo.FindAsync(@"C:\c\C-Win64-Shipping.exe", Ct).ConfigureAwait(true))!.EngineVersion.Should().Be("5", "no badge reads as the user's");
(await repo.FindAsync(@"C:\d\D.exe", Ct).ConfigureAwait(true))!.EngineVersion.Should().Be("5", "another engine's version is not the old Unreal rule's");
(await repo.FindAsync(@"C:\e\E-Win64-Shipping.exe", Ct).ConfigureAwait(true))!.EngineVersion.Should().Be("4", "unreadable provenance is the user's");
GameRow full = (await repo.FindAsync(@"C:\f\F-Win64-Shipping.exe", Ct).ConfigureAwait(true))!;
full.EngineVersion.Should().Be("4.27", "only the bare digit is the old rule's signature");
full.EngineVersionSource.Should().BeNull("no row has a witness until the sweep reads it again");
}
}
/// <summary>
/// Schema 0014 (2026-09-26, D33): the user-mode exception's columns, ADD COLUMN only — a row blocked before it keeps its
/// block, is not eligible and carries no grant; a session written before it ran under no exception.
/// </summary>
[Fact]
public async Task ScriptFourteenAddsTheExceptionColumnsAndChangesNoRow()
{
await using LedgerFixture f = await LedgerFixture.OpenAsync();
MigrationRunner.LatestVersion.Should().BeGreaterThanOrEqualTo(14);
string path = f.Path;
await f.Db.DisposeAsync().ConfigureAwait(true);
var c13 = new SqliteConnection(new SqliteConnectionStringBuilder { DataSource = path, Pooling = false }.ToString());
await using (c13.ConfigureAwait(true))
{
await c13.OpenAsync(Ct).ConfigureAwait(true);
await RewindToAsync(c13, 13).ConfigureAwait(true);
await c13.ExecuteAsync(new CommandDefinition(
"INSERT INTO games (name, exe_path, hook_blocked_reason, hook_prescan_state, added_at, updated_at) "
+ "VALUES ('GF2', 'C:\\GF2\\GF2_Exilium.exe', 'AntiCheatFile|NetEase Yidun|NEP2.dll', 'blocked', 0, 0)", cancellationToken: Ct)).ConfigureAwait(true);
}
LedgerDatabase migrated = await LedgerDatabase.OpenAsync(path, ct: Ct).ConfigureAwait(true);
await using (migrated.ConfigureAwait(true))
{
migrated.SchemaVersion.Should().Be(MigrationRunner.LatestVersion);
IReadOnlyList<string> games = await migrated.ReadAsync(async (c, ct) =>
(IReadOnlyList<string>)[.. await c.QueryAsync<string>(new CommandDefinition(
"SELECT name FROM pragma_table_info('games') WHERE name LIKE 'ac_exception_%'", cancellationToken: ct)).ConfigureAwait(false)], Ct).ConfigureAwait(true);
games.Should().HaveCount(15, "0014's fourteen, and since 0017 the trial mark");
long sessions = await migrated.ReadAsync((c, ct) => c.ExecuteScalarAsync<long>(new CommandDefinition(
"SELECT COUNT(*) FROM pragma_table_info('sessions') WHERE name = 'ac_exception_family'", cancellationToken: ct)), Ct).ConfigureAwait(true);
sessions.Should().Be(1);
GameRow row = (await new SqliteGameRepository(migrated).FindAsync(@"C:\GF2\GF2_Exilium.exe", Ct).ConfigureAwait(true))!;
row.HookBlockedReason.Should().Be("AntiCheatFile|NetEase Yidun|NEP2.dll", "0014 edits no row");
row.AcException.Should().BeEquivalentTo(AntiCheatExceptionState.None, "no eligibility and no grant until the Agent and the user say so");
}
}
/// <summary>Schema 0013 (2026-09-25): <c>frame_blobs.first_present_ms</c>, NULL for every row written before.</summary>
[Fact]
public async Task ScriptThirteenAddsTheFirstPresentColumn()
{
await using LedgerFixture f = await LedgerFixture.OpenAsync();
MigrationRunner.LatestVersion.Should().BeGreaterThanOrEqualTo(13);
string path = f.Path;
await f.Db.DisposeAsync().ConfigureAwait(true);
var c12 = new SqliteConnection(new SqliteConnectionStringBuilder { DataSource = path, Pooling = false }.ToString());
await using (c12.ConfigureAwait(true))
{
await c12.OpenAsync(Ct).ConfigureAwait(true);
await RewindToAsync(c12, 12).ConfigureAwait(true);
}
LedgerDatabase migrated = await LedgerDatabase.OpenAsync(path, ct: Ct).ConfigureAwait(true);
await using (migrated.ConfigureAwait(true))
{
migrated.SchemaVersion.Should().Be(MigrationRunner.LatestVersion);
long columns = await migrated.ReadAsync((c, ct) => c.ExecuteScalarAsync<long>(new CommandDefinition(
"SELECT COUNT(*) FROM pragma_table_info('frame_blobs') WHERE name = 'first_present_ms'", cancellationToken: ct)), Ct).ConfigureAwait(true);
columns.Should().Be(1);
}
}
/// <summary>Schema 0012 (2026-09-25): <c>sessions.driver_profile</c>, NULL for every row written before.</summary>
[Fact]
public async Task ScriptTwelveAddsTheDriverProfileColumn()
{
await using LedgerFixture f = await LedgerFixture.OpenAsync();
MigrationRunner.LatestVersion.Should().BeGreaterThanOrEqualTo(12);
string path = f.Path;
await f.Db.DisposeAsync().ConfigureAwait(true);
var c11 = new SqliteConnection(new SqliteConnectionStringBuilder { DataSource = path, Pooling = false }.ToString());
await using (c11.ConfigureAwait(true))
{
await c11.OpenAsync(Ct).ConfigureAwait(true);
await RewindToAsync(c11, 11).ConfigureAwait(true);
}
LedgerDatabase migrated = await LedgerDatabase.OpenAsync(path, ct: Ct).ConfigureAwait(true);
await using (migrated.ConfigureAwait(true))
{
migrated.SchemaVersion.Should().Be(MigrationRunner.LatestVersion);
long columns = await migrated.ReadAsync((c, ct) => c.ExecuteScalarAsync<long>(new CommandDefinition(
"SELECT COUNT(*) FROM pragma_table_info('sessions') WHERE name = 'driver_profile'", cancellationToken: ct)), Ct).ConfigureAwait(true);
columns.Should().Be(1);
}
}
/// <summary>
/// Schema 0011 (2026-09-25): what a game's files say about themselves — what the executable runs as, its two PE versions,
/// the capability files it ships. Applied from schema 10 to a ledger holding a row: the four columns exist and read NULL,
/// and a NULL <c>exe_machine</c> is what makes the detection sweep read the row once more.
/// </summary>
[Fact]
public async Task ScriptElevenAddsTheExecutableFactsEmptyForExistingRows()
{
await using LedgerFixture f = await LedgerFixture.OpenAsync();
MigrationRunner.LatestVersion.Should().BeGreaterThanOrEqualTo(11);
string path = f.Path;
await f.Db.WriteAsync((c, tx, ct) => c.ExecuteAsync(new CommandDefinition(
"INSERT INTO games (name, exe_path, added_at, updated_at) VALUES ('A game', 'D:\\g\\game.exe', 1, 1)",
transaction: tx, cancellationToken: ct)), Ct).ConfigureAwait(true);
await f.Db.DisposeAsync().ConfigureAwait(true);
var c10 = new SqliteConnection(new SqliteConnectionStringBuilder { DataSource = path, Pooling = false }.ToString());
await using (c10.ConfigureAwait(true))
{
await c10.OpenAsync(Ct).ConfigureAwait(true);
await RewindToAsync(c10, 10).ConfigureAwait(true);
}
LedgerDatabase migrated = await LedgerDatabase.OpenAsync(path, ct: Ct).ConfigureAwait(true);
await using (migrated.ConfigureAwait(true))
{
migrated.SchemaVersion.Should().Be(MigrationRunner.LatestVersion);
(string? Machine, string? File, string? Product, string? Libraries) facts = await migrated.ReadAsync((c, ct) =>
c.QuerySingleAsync<(string?, string?, string?, string?)>(new CommandDefinition(
"SELECT exe_machine, exe_file_version, exe_product_version, library_versions FROM games", cancellationToken: ct)), Ct).ConfigureAwait(true);
facts.Should().Be((null, null, null, null));
}
}
/// <summary>
/// Schema 0010 (2026-09-25): the Agent's pre-scan of the library keeps its own key — the rules version and the
/// executable's size and mtime it last scanned under. Applied from schema 9 to a ledger holding a row: the three
/// columns exist and read NULL for it, which the sweep reads as "never scanned".
/// </summary>
[Fact]
public async Task ScriptTenAddsThePreScanKeyEmptyForExistingRows()
{
await using LedgerFixture f = await LedgerFixture.OpenAsync();
MigrationRunner.LatestVersion.Should().BeGreaterThanOrEqualTo(10);
string path = f.Path;
await f.Db.WriteAsync((c, tx, ct) => c.ExecuteAsync(new CommandDefinition(
"INSERT INTO games (name, exe_path, added_at, updated_at) VALUES ('A game', 'D:\\g\\game.exe', 1, 1)",
transaction: tx, cancellationToken: ct)), Ct).ConfigureAwait(true);
await f.Db.DisposeAsync().ConfigureAwait(true);
var c9 = new SqliteConnection(new SqliteConnectionStringBuilder { DataSource = path, Pooling = false }.ToString());
await using (c9.ConfigureAwait(true))
{
await c9.OpenAsync(Ct).ConfigureAwait(true);
await RewindToAsync(c9, 9).ConfigureAwait(true);
}
LedgerDatabase migrated = await LedgerDatabase.OpenAsync(path, ct: Ct).ConfigureAwait(true);
await using (migrated.ConfigureAwait(true))
{
migrated.SchemaVersion.Should().Be(MigrationRunner.LatestVersion);
(string? Rules, long? Size, long? Mtime) key = await migrated.ReadAsync((c, ct) => c.QuerySingleAsync<(string?, long?, long?)>(
new CommandDefinition("SELECT hook_prescan_rules_version, hook_prescan_exe_size_bytes, hook_prescan_exe_mtime_ms FROM games",
cancellationToken: ct)), Ct).ConfigureAwait(true);
key.Should().Be((null, null, null));
}
}
/// <summary>
/// Schema 0009 (2026-09-23): the recording switch — on for every entry, and off once for the entries an old import made
/// for Steam's own tools (the owner's Borderless Gaming, recorded at every boot since it starts with Windows). Applied
/// here from schema 8 to a ledger holding a tool, a game, and a hand-added row that only shares the tool's id.
/// </summary>
[Fact]
public async Task ScriptNineAddsTheRecordingSwitchOffForSteamToolsOnly()
{
await using LedgerFixture f = await LedgerFixture.OpenAsync();
MigrationRunner.LatestVersion.Should().BeGreaterThanOrEqualTo(9);
string path = f.Path;
await f.Db.WriteAsync((c, tx, ct) => c.ExecuteAsync(new CommandDefinition(
"INSERT INTO games (name, exe_path, platform, store_id, added_at, updated_at) VALUES "
+ "('Borderless Gaming', 'D:\\bg\\BorderlessGaming.exe', 'steam', '388080', 1, 1), "
+ "('A game', 'D:\\g\\game.exe', 'steam', '1091500', 1, 1), "
+ "('Hand-added', 'D:\\h\\h.exe', 'none', '388080', 1, 1)", transaction: tx, cancellationToken: ct)), Ct).ConfigureAwait(true);
await f.Db.DisposeAsync().ConfigureAwait(true);
var c8 = new SqliteConnection(new SqliteConnectionStringBuilder { DataSource = path, Pooling = false }.ToString());
await using (c8.ConfigureAwait(true))
{
await c8.OpenAsync(Ct).ConfigureAwait(true);
await RewindToAsync(c8, 8).ConfigureAwait(true);
}
LedgerDatabase migrated = await LedgerDatabase.OpenAsync(path, ct: Ct).ConfigureAwait(true);
await using (migrated.ConfigureAwait(true))
{
migrated.SchemaVersion.Should().Be(MigrationRunner.LatestVersion);
IReadOnlyList<(string Name, long Record)> rows = await migrated.ReadAsync(async (c, ct) =>
(IReadOnlyList<(string, long)>)[.. await c.QueryAsync<(string, long)>(new CommandDefinition(
"SELECT name, record_sessions FROM games ORDER BY name", cancellationToken: ct)).ConfigureAwait(false)], Ct).ConfigureAwait(true);
rows.Should().Equal(("A game", 1L), ("Borderless Gaming", 0L), ("Hand-added", 1L));
}
}
/// <summary>The ids script 0009 switches off are Steam tools the import already skips (<see cref="SteamLibrarySource.KnownTools"/>), never a guess of its own.</summary>
[Fact]
public void ScriptNineSwitchesOffOnlyKnownSteamTools()
{
using Stream script = typeof(MigrationRunner).Assembly.GetManifestResourceStream("FrameLedger.Infrastructure.Persistence.Migrations.0009_record_sessions.sql")!;
using var reader = new StreamReader(script);
string text = reader.ReadToEnd();
string list = text[text.IndexOf("store_id IN", StringComparison.Ordinal)..];
List<string> ids = [.. Regex.Matches(list, @"'(?<id>\d+)'", RegexOptions.ExplicitCapture, TimeSpan.FromSeconds(1))
.Select(static m => m.Groups["id"].Value)];
ids.Should().NotBeEmpty().And.OnlyHaveUniqueItems().And.Contain("388080", "Borderless Gaming, the owner's case");
ids.Should().BeSubsetOf(SteamLibrarySource.KnownTools);
}
[Fact]
public async Task ReopeningIsANoOp()
{
await using LedgerFixture f = await LedgerFixture.OpenAsync();
await using LedgerDatabase again = await f.OpenAnotherAsync(Ct);
again.Migration.Should().Be(MigrationOutcome.AlreadyCurrent);
again.SchemaVersion.Should().Be(f.Db.SchemaVersion);
long rows = await again.ReadAsync((c, ct) => c.ExecuteScalarAsync<long>(new CommandDefinition("SELECT COUNT(*) FROM schema_migrations", cancellationToken: ct)), Ct);
rows.Should().Be(MigrationRunner.LatestVersion, "one row per applied script, and nothing re-applied");
}
[Fact]
public async Task ThePragmasAreTheDocumentedOnes()
{
await using LedgerFixture f = await LedgerFixture.OpenAsync(busyTimeoutMs: 1234);
(string journal, long sync, long fk, long busy) = await f.Db.ReadAsync(async (c, ct) => (
(await c.ExecuteScalarAsync<string?>(new CommandDefinition("PRAGMA journal_mode", cancellationToken: ct)).ConfigureAwait(false))!,
await c.ExecuteScalarAsync<long>(new CommandDefinition("PRAGMA synchronous", cancellationToken: ct)).ConfigureAwait(false),
await c.ExecuteScalarAsync<long>(new CommandDefinition("PRAGMA foreign_keys", cancellationToken: ct)).ConfigureAwait(false),
await c.ExecuteScalarAsync<long>(new CommandDefinition("PRAGMA busy_timeout", cancellationToken: ct)).ConfigureAwait(false)), Ct);
journal.Should().Be("wal");
sync.Should().Be(1, "NORMAL");
fk.Should().Be(1);
busy.Should().Be(1234);
}
[Fact]
public async Task ASchemaNewerThanThisBuildIsRefusedNotGuessedAt()
{
await using LedgerFixture f = await LedgerFixture.OpenAsync();
await f.Db.WriteAsync((c, tx, ct) => c.ExecuteAsync(new CommandDefinition(
"INSERT INTO schema_migrations (version, applied_at) VALUES (999, 0)", transaction: tx, cancellationToken: ct)), Ct);
Func<Task> open = async () => await f.OpenAnotherAsync(Ct).ConfigureAwait(false);
(await open.Should().ThrowAsync<LedgerSchemaException>().ConfigureAwait(true)).Which.Message.Should().Contain("999");
}
[Fact]
public async Task AWriteThatThrowsIsRolledBackWhole()
{
await using LedgerFixture f = await LedgerFixture.OpenAsync();
Func<Task> write = async () => await f.Db.WriteAsync<int>(async (c, tx, ct) =>
{
await c.ExecuteAsync(new CommandDefinition("INSERT INTO settings (key, value) VALUES ('a', '1')", transaction: tx, cancellationToken: ct)).ConfigureAwait(false);
throw new InvalidOperationException("half-way");
}, Ct).ConfigureAwait(false);
await write.Should().ThrowAsync<InvalidOperationException>();
long rows = await f.Db.ReadAsync((c, ct) => c.ExecuteScalarAsync<long>(new CommandDefinition("SELECT COUNT(*) FROM settings", cancellationToken: ct)), Ct);
rows.Should().Be(0, "the transaction rolled back, so the first statement went with the second");
}
[Fact]
public async Task TwoConnectionsSerialiseThroughBusyTimeoutRatherThanFailing()
{
await using LedgerFixture f = await LedgerFixture.OpenAsync();
await using LedgerDatabase other = await f.OpenAnotherAsync(Ct);
await f.Db.WriteAsync((c, tx, ct) => c.ExecuteAsync(new CommandDefinition("INSERT INTO settings (key, value) VALUES ('k', 'one')", transaction: tx, cancellationToken: ct)), Ct);
await other.WriteAsync((c, tx, ct) => c.ExecuteAsync(new CommandDefinition("UPDATE settings SET value = 'two' WHERE key = 'k'", transaction: tx, cancellationToken: ct)), Ct);
string? value = await f.Db.ReadAsync((c, ct) => c.ExecuteScalarAsync<string?>(new CommandDefinition("SELECT value FROM settings WHERE key = 'k'", cancellationToken: ct)), Ct);
value.Should().Be("two", "WAL lets a second opener write once the first's transaction has committed");
}
/// <summary>
/// 2026-09-16: a "read-only" verb run against the owner's ledger applied two migration scripts to it, because every
/// open went through <see cref="LedgerDatabase.OpenAsync"/>. A read-only open of an OLDER schema refuses and leaves
/// the file byte-identical.
/// </summary>
[Fact]
public async Task AReadOnlyOpenOfAnOlderSchemaRefusesAndChangesNothing()
{
await using LedgerFixture f = await LedgerFixture.OpenAsync();
string path = f.Path;
await InsertAsync(f.Db).ConfigureAwait(true);
await f.Db.DisposeAsync().ConfigureAwait(true);
await RewindSchemaAsync(path, 2).ConfigureAwait(true);
byte[] before = await File.ReadAllBytesAsync(path, Ct).ConfigureAwait(true);
Func<Task> open = async () => await LedgerDatabase.OpenReadOnlyAsync(path, ct: Ct).ConfigureAwait(false);
ExceptionAssertions<LedgerSchemaException> refused = await open.Should().ThrowAsync<LedgerSchemaException>().ConfigureAwait(true);
refused.WithMessage("*older than this build*");
byte[] after = await File.ReadAllBytesAsync(path, Ct).ConfigureAwait(true);
after.Should().Equal(before, "a read-only open migrates nothing");
WalIsEmpty(path).Should().BeTrue("a read-only open of a checkpointed file writes no frame");
}
[Fact]
public async Task AReadOnlyOpenReadsAndRefusesToWrite()
{
await using LedgerFixture f = await LedgerFixture.OpenAsync();
string path = f.Path;
await InsertAsync(f.Db).ConfigureAwait(true);
await f.Db.DisposeAsync().ConfigureAwait(true);
byte[] before = await File.ReadAllBytesAsync(path, Ct).ConfigureAwait(true);
LedgerDatabase ro = await LedgerDatabase.OpenReadOnlyAsync(path, ct: Ct).ConfigureAwait(true);
await using (ro.ConfigureAwait(true))
{
ro.IsReadOnly.Should().BeTrue();
ro.Migration.Should().Be(MigrationOutcome.AlreadyCurrent);
ro.SchemaVersion.Should().Be(MigrationRunner.LatestVersion);
ro.OpenDiagnostics.Should().BeNull("a read-only open checkpoints nothing");
string? value = await ro.ReadAsync((c, ct) => c.ExecuteScalarAsync<string?>(new CommandDefinition("SELECT value FROM settings WHERE key = 'k'", cancellationToken: ct)), Ct).ConfigureAwait(true);
value.Should().Be("v");
Func<Task> write = async () => await ro.WriteAsync((c, tx, ct) => c.ExecuteAsync(new CommandDefinition("DELETE FROM settings", transaction: tx, cancellationToken: ct)), Ct).ConfigureAwait(false);
await write.Should().ThrowAsync<InvalidOperationException>().ConfigureAwait(true);
Func<Task> maintain = async () => await ro.MaintainAsync((c, ct) => c.ExecuteAsync(new CommandDefinition("VACUUM", cancellationToken: ct)), Ct).ConfigureAwait(false);
await maintain.Should().ThrowAsync<InvalidOperationException>().ConfigureAwait(true);
Func<Task> raw = async () => await ro.ReadAsync((c, ct) => c.ExecuteAsync(new CommandDefinition("DELETE FROM settings", cancellationToken: ct)), Ct).ConfigureAwait(false);
await raw.Should().ThrowAsync<SqliteException>("query_only refuses a statement that slipped past the gate").ConfigureAwait(true);
}
byte[] after = await File.ReadAllBytesAsync(path, Ct).ConfigureAwait(true);
after.Should().Equal(before);
}
[Fact]
public async Task AReadOnlyOpenOfAMissingFileCreatesNothing()
{
string dir = Path.Combine(Path.GetTempPath(), "fl-ledger-ro-" + Guid.NewGuid().ToString("N"));
string path = Path.Combine(dir, LedgerPaths.DatabaseFileName);
Func<Task> open = async () => await LedgerDatabase.OpenReadOnlyAsync(path, ct: Ct).ConfigureAwait(false);
await open.Should().ThrowAsync<FileNotFoundException>().ConfigureAwait(true);
File.Exists(path).Should().BeFalse();
Directory.Exists(dir).Should().BeFalse("not even the directory");
}
/// <summary>
/// 2026-09-16: the owner's ledger held a day's rows only in a WAL whose frames a fresh connection discarded, over
/// a main file no checkpoint had reached. A read-write close now checkpoints explicitly and reports it, and the
/// main file alone must hold every row afterwards.
/// </summary>
[Fact]
public async Task AReadWriteCloseLeavesTheMainFileCompleteAndSaysSo()
{
string dir = Path.Combine(Path.GetTempPath(), "fl-ledger-ckpt-" + Guid.NewGuid().ToString("N"));
string path = Path.Combine(dir, LedgerPaths.DatabaseFileName);
List<string> lines = [];
try
{
LedgerDatabase db = await LedgerDatabase.OpenAsync(path, diagnostics: lines.Add, ct: Ct).ConfigureAwait(true);
await using (db.ConfigureAwait(true))
{
db.OpenDiagnostics.Should().NotBeNull();
db.OpenDiagnostics!.Mode.Should().Be("passive");
await InsertAsync(db).ConfigureAwait(true);
}
lines.Should().HaveCount(2).And.SatisfyRespectively(
open => open.Should().StartWith("ledger: wal at open — passive:"),
close => close.Should().StartWith("ledger: wal at close — truncate:").And.NotContain("busy"));
WalIsEmpty(path).Should().BeTrue("TRUNCATE leaves nothing in the wal");
string? value = await ReadMainFileOnlyAsync(path).ConfigureAwait(true);
value.Should().Be("v", "the main file alone holds the row");
}
finally
{
try
{
Directory.Delete(dir, recursive: true);
}
catch (IOException)
{
}
}
}
private static Task<int> InsertAsync(LedgerDatabase db) =>
db.WriteAsync((c, tx, ct) => c.ExecuteAsync(new CommandDefinition("INSERT INTO settings (key, value) VALUES ('k', 'v')", transaction: tx, cancellationToken: ct)), Ct).AsTask();
private static bool WalIsEmpty(string path) => !File.Exists(path + "-wal") || new FileInfo(path + "-wal").Length == 0;
/// <summary>Reads through a connection that ignores any wal (<c>immutable=1</c>): the main file is the only thing consulted.</summary>
private static async Task<string?> ReadMainFileOnlyAsync(string path)
{
var main = new SqliteConnection(new SqliteConnectionStringBuilder
{
DataSource = "file:" + path.Replace('\\', '/') + "?immutable=1",
Mode = SqliteOpenMode.ReadOnly,
Pooling = false,
}.ToString());
await using (main.ConfigureAwait(false))
{
await main.OpenAsync(Ct).ConfigureAwait(false);
return await main.ExecuteScalarAsync<string?>(new CommandDefinition("SELECT value FROM settings WHERE key = 'k'", cancellationToken: Ct)).ConfigureAwait(false);
}
}
/// <summary>Makes a current ledger look like one written by an older build: the rows above <paramref name="version"/> go, the columns stay.</summary>
private static async Task RewindSchemaAsync(string path, int version)
{
var c = new SqliteConnection(new SqliteConnectionStringBuilder { DataSource = path, Pooling = false }.ToString());
await using (c.ConfigureAwait(false))
{
await c.OpenAsync(Ct).ConfigureAwait(false);
await c.ExecuteAsync(new CommandDefinition("DELETE FROM schema_migrations WHERE version > @version", new { version }, cancellationToken: Ct)).ConfigureAwait(false);
await c.ExecuteAsync(new CommandDefinition("PRAGMA wal_checkpoint(TRUNCATE)", cancellationToken: Ct)).ConfigureAwait(false);
}
}
[Fact]
public void TheDefaultLocationIsTheAgentsDirectory()
{
LedgerPaths.DefaultDatabase.Should().StartWith(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData));
LedgerPaths.DefaultDatabase.Should().EndWith(@"FrameLedger\ledger.db");
}
[Fact]
public void TheScriptsAreNumberedFromOne()
{
SortedDictionary<int, string> scripts = MigrationRunner.Scripts();
scripts.Keys.Should().StartWith(1);
scripts.Keys.Should().BeInAscendingOrder().And.OnlyHaveUniqueItems();
scripts[1].Should().Contain("CREATE TABLE games");
}
/// <summary>
/// Schema 0023 (2026-11-11, owner decisions D101 and D102): two tables of their own for Advanced metrics — the first
/// CREATE TABLE since 0001 — and nothing added to <c>sessions</c>. A session written before has no row in either.
/// </summary>
[Fact]
public async Task ScriptTwentyThreeCreatesTheTwoAdvancedTablesAndAnEarlierSessionHasNoRow()
{
await using LedgerFixture f = await LedgerFixture.OpenAsync();
MigrationRunner.LatestVersion.Should().BeGreaterThanOrEqualTo(23);
long gameId = (await new SqliteGameRepository(f.Db).EnsureAsync(
new() { ExePath = @"C:\Games\A\a.exe", SizeBytes = 1, MtimeUnixMs = 2 }, "A", Ct).ConfigureAwait(true)).Id;
long snapshotId = await new SqliteHardwareSnapshotRepository(f.Db).EnsureAsync(new HardwareSnapshot { GpuName = "g" }, DateTimeOffset.UnixEpoch, Ct)
.ConfigureAwait(true);
string path = f.Path;
await f.Db.DisposeAsync().ConfigureAwait(true);
var c22 = new SqliteConnection(new SqliteConnectionStringBuilder { DataSource = path, Pooling = false }.ToString());
await using (c22.ConfigureAwait(true))
{
await c22.OpenAsync(Ct).ConfigureAwait(true);
await RewindToAsync(c22, 22).ConfigureAwait(true);
(await c22.ExecuteScalarAsync<long>(new CommandDefinition(
"SELECT COUNT(*) FROM sqlite_master WHERE name IN ('machine_profiles', 'session_advanced', 'ix_session_advanced_profile')", cancellationToken: Ct)).ConfigureAwait(true))
.Should().Be(0, "a ledger at schema 22 has neither table");
await c22.ExecuteAsync(new CommandDefinition(
"INSERT INTO sessions (session_guid, game_id, snapshot_id, started_at, ended_at, duration_s, qpc_epoch, qpc_frequency, capture_tier, capture_mode, exit_status, frame_count, app_frame_count, displayed_frame_count, dropped_frames) "
+ "VALUES ('00000000-0000-0000-0000-000000000023', @gameId, @snapshotId, 0, 60000, 60, 0, 10000000, 1, 'attach', 'normal', 6000, 6000, 6000, 0)",
new { gameId, snapshotId }, cancellationToken: Ct)).ConfigureAwait(true);
}
LedgerDatabase migrated = await LedgerDatabase.OpenAsync(path, ct: Ct).ConfigureAwait(true);
await using (migrated.ConfigureAwait(true))
{
migrated.SchemaVersion.Should().Be(MigrationRunner.LatestVersion);
IReadOnlyList<string> profileColumns = await migrated.ReadAsync(async (c, ct) => (IReadOnlyList<string>)[.. await c.QueryAsync<string>(new CommandDefinition(
"SELECT name FROM pragma_table_info('machine_profiles') ORDER BY cid", cancellationToken: ct)).ConfigureAwait(false)], Ct).ConfigureAwait(true);
IReadOnlyList<string> sessionColumns = await migrated.ReadAsync(async (c, ct) => (IReadOnlyList<string>)[.. await c.QueryAsync<string>(new CommandDefinition(
"SELECT name FROM pragma_table_info('session_advanced') ORDER BY cid", cancellationToken: ct)).ConfigureAwait(false)], Ct).ConfigureAwait(true);
profileColumns.Should().Equal("id", "hash", "facts_json", "captured_at");
sessionColumns.Should().Equal("session_id", "machine_profile_id", "facts_json", "stats_json", "series_json");
var sessions = new SqliteSessionRepository(migrated);
SessionRow before = (await sessions.FindAsync(Guid.Parse("00000000-0000-0000-0000-000000000023"), Ct).ConfigureAwait(true))!;
(await sessions.FindAdvancedAsync(before.Id, Ct).ConfigureAwait(true)).Should().BeNull("a session recorded before Advanced metrics existed has none, and is never given any");
(await sessions.FindAdvancedSensorsAsync(before.Id, Ct).ConfigureAwait(true)).Should().BeEmpty();
}
}
/// <summary>
/// Schema 0024 (2026-11-14, owner decisions D155-D163): what a session was played with, nine columns of
/// <c>sessions</c>, and what a game's store lists of controller support, three of <c>games</c> - ADD COLUMN only. A
/// session and a game written before have none of them: N/A, never a zero.
/// </summary>
[Fact]
public async Task ScriptTwentyFourAddsTheInputColumnsAndAnEarlierSessionAndGameHaveNone()
{
await using LedgerFixture f = await LedgerFixture.OpenAsync();
MigrationRunner.LatestVersion.Should().BeGreaterThanOrEqualTo(24);
long gameId = (await new SqliteGameRepository(f.Db).EnsureAsync(
new() { ExePath = @"C:\Games\A\a.exe", SizeBytes = 1, MtimeUnixMs = 2 }, "A", Ct).ConfigureAwait(true)).Id;
long snapshotId = await new SqliteHardwareSnapshotRepository(f.Db).EnsureAsync(new HardwareSnapshot { GpuName = "g" }, DateTimeOffset.UnixEpoch, Ct)
.ConfigureAwait(true);
string path = f.Path;
await f.Db.DisposeAsync().ConfigureAwait(true);
var c23 = new SqliteConnection(new SqliteConnectionStringBuilder { DataSource = path, Pooling = false }.ToString());
await using (c23.ConfigureAwait(true))
{
await c23.OpenAsync(Ct).ConfigureAwait(true);
await RewindToAsync(c23, 23).ConfigureAwait(true);
(await c23.ExecuteScalarAsync<long>(new CommandDefinition(
"SELECT COUNT(*) FROM pragma_table_info('sessions') WHERE name LIKE 'input!_%' ESCAPE '!'", cancellationToken: Ct)).ConfigureAwait(true))
.Should().Be(0, "a ledger at schema 23 has no input column");
await c23.ExecuteAsync(new CommandDefinition(
"INSERT INTO sessions (session_guid, game_id, snapshot_id, started_at, ended_at, duration_s, qpc_epoch, qpc_frequency, capture_tier, capture_mode, exit_status, frame_count, app_frame_count, displayed_frame_count, dropped_frames) "
+ "VALUES ('00000000-0000-0000-0000-000000000024', @gameId, @snapshotId, 0, 60000, 60, 0, 10000000, 2, 'attach', 'normal', 0, 0, 0, 0)",
new { gameId, snapshotId }, cancellationToken: Ct)).ConfigureAwait(true);
}
LedgerDatabase migrated = await LedgerDatabase.OpenAsync(path, ct: Ct).ConfigureAwait(true);
await using (migrated.ConfigureAwait(true))
{
migrated.SchemaVersion.Should().Be(MigrationRunner.LatestVersion);
IReadOnlyList<string> sessionColumns = await migrated.ReadAsync(async (c, ct) => (IReadOnlyList<string>)[.. await c.QueryAsync<string>(new CommandDefinition(
"SELECT name FROM pragma_table_info('sessions') WHERE name LIKE 'input!_%' ESCAPE '!' ORDER BY cid", cancellationToken: ct)).ConfigureAwait(false)], Ct).ConfigureAwait(true);
IReadOnlyList<string> gameColumns = await migrated.ReadAsync(async (c, ct) => (IReadOnlyList<string>)[.. await c.QueryAsync<string>(new CommandDefinition(
"SELECT name FROM pragma_table_info('games') WHERE name LIKE 'controller!_%' ESCAPE '!' ORDER BY cid", cancellationToken: ct)).ConfigureAwait(false)], Ct).ConfigureAwait(true);
sessionColumns.Should().Equal(
"input_observed_ms", "input_foreground_ms", "input_controller_ms", "input_km_ms", "input_both_ms", "input_idle_ms", "input_method_switches", "input_source", "input_devices");
gameColumns.Should().Equal("controller_support", "controller_support_source", "controller_support_at");
var sessions = new SqliteSessionRepository(migrated);
SessionRow before = (await sessions.FindAsync(Guid.Parse("00000000-0000-0000-0000-000000000024"), Ct).ConfigureAwait(true))!;
before.InputObservedMs.Should().BeNull("a session recorded before the reading existed has none - N/A, never a zero");
before.InputForegroundMs.Should().BeNull();
before.InputMethodSwitches.Should().BeNull();
before.InputSource.Should().BeNull();
before.InputDevicesJson.Should().BeNull();
before.InputSharePercent(before.InputControllerMs).Should().BeNull();
(await sessions.FindInputSensorsAsync(before.Id, Ct).ConfigureAwait(true)).Should().BeEmpty();
GameRow game = (await new SqliteGameRepository(migrated).FindByIdAsync(gameId, Ct).ConfigureAwait(true))!;
game.ControllerSupport.Should().BeNull();
game.ControllerSupportSource.Should().BeNull();
game.ControllerSupportAt.Should().BeNull();
}
}
[Fact]
public void ScriptTwentyFourOnlyAddsColumnsAndNamesNoIdentifier()
{
// D160: the numbers are columns of sessions on purpose - the trend, the comparison, the export and the bug bundle
// read a session's row. What may never be a column: a controller's serial number, its address, its path.
string sql = MigrationRunner.Scripts()[24];
string statements = string.Join('\n', sql.Split('\n').Where(static l => !l.TrimStart().StartsWith("--", StringComparison.Ordinal)).Select(static l => l.Split("--")[0]));
statements.Should().NotContainAny("CREATE", "DROP", "UPDATE", "DELETE");
statements.Should().NotContainAny("serial", "address", "path", "mac", "uuid");
Regex.Matches(statements, @"ALTER\s+TABLE\s+(?<table>\w+)\s+ADD\s+COLUMN", RegexOptions.ExplicitCapture, TimeSpan.FromSeconds(1)).Select(static m => m.Groups["table"].Value)
.Distinct(StringComparer.Ordinal).Should().Equal("sessions", "games");
}
[Fact]
public void ScriptTwentyThreeAddsNoColumnToSessionsAndNamesNoIdentifier()
{
// D102: every read of a sessions row, the JSON export and the bug bundle carry the whole row. D104: neither
// table has a column for a serial number, a unique id, an EDID or another program's process id.
string sql = MigrationRunner.Scripts()[23];
string statements = string.Join('\n', sql.Split('\n').Where(static l => !l.TrimStart().StartsWith("--", StringComparison.Ordinal)).Select(static l => l.Split("--")[0]));
statements.Should().NotContain("ALTER TABLE");
statements.Should().NotContainAny("serial", "uuid", "edid", "pid");
Regex.Matches(statements, @"CREATE\s+TABLE\s+(?<name>\w+)", RegexOptions.ExplicitCapture, TimeSpan.FromSeconds(1)).Select(static m => m.Groups["name"].Value)
.Should().Equal("machine_profiles", "session_advanced");
}
}