Files
frameledger/tests/FrameLedger.Infrastructure.Tests/Persistence/LedgerDatabaseTests.cs
T
poli0981andClaude Opus 5.5 c9b0aab862 feat: DLSS 5 is named where the game ran its neural rendering (schema 0022, rules 2026.11.2, Privacy 2.14); Streamline headers re-vendored at v2.14.16 (D84) (beta.34 PR-3) (#358)
The owner, 2026-11-06: Hogwarts Legacy with Neural Rendering on loaded DLSS 5's runtime
(nvngx_dlssnr.dll 310.9.16.0, from the game's folder) and the session could say only "DLSS 5
runtime loaded". Then: check what changed in recent Streamline versions, fix it if needed.

- Streamline: the vendored closure was v2.12.0 byte for byte; v2.14.16 changes three of its
  eleven files (kFeatureDLSS_NR = 1004, the uplift buffer types 70-72, kStructVersion7, the
  version). Re-vendored byte for byte; README provenance, THIRD_PARTY_NOTICES row.
- Overlay (hook path): the slEvaluateFeature detour decodes kFeatureDLSS_NR into its own bit;
  RecordPresent sets FL_FEAT_SL_NEURAL_RENDERING (feature byte bit 7, an enumerator - no layout
  change) under the condition every Streamline fact shares; the evaluate row's family also claims
  FL_HOOK_SL_NEURAL_RENDERING (bit 12), published with the detour. Overhead: decode unchanged
  within noise (4.7 ns a call), +0.14..0.19 ns a present.
- Agent: Domain.Metrics.NeuralRendering.SharePct; sessions.dlss_nr_pct (schema 0022) only from a
  writer that published the family - an older Overlay's silence is never a measured 0 %.
  CensusNames records sl.dlss_nr.dll.
- Rules 2026.11.2: capability dlss_nr -> "Supports DLSS 5 Neural Rendering".
- App (D84): DLSS 5 heads the DLSS line where it ran ("DLSS 5 (neural rendering on 97.3% of
  rendered frames)"); its library listed with version and source; measured 0 -> "runtime loaded,
  not seen running"; nothing to tell -> "runtime loaded" as before. CSV basis/pct.
- CaptureHost dev census: a kFeatureDLSS_NR bucket.
- Privacy Policy 2.14 (neural-rendering libraries); the accuracy block's DLSS 5 sentence.
- Tests: native guard_test (the new harness mode through an injected Overlay; 0xF00D lights no NR
  fact; the token case's exact mask gains the family), NeuralRenderingTests, SessionAggregatorTests,
  DlssGenerationTests, DlssTextTests (a row shaped from session 132), LedgerDatabaseTests (0022),
  the repository round trip, the rules fixture, RuntimeModuleSourcesTests, SlCensusTests.
- Docs: 05_DETECTION, 06_DATA_MODEL, 17_HOOK_ENGINE, LIMITATIONS, guide/03, guide/10, the accuracy
  block, spike-notes 26 (+ owner-only item 30(a)'s decision table), HANDOFF (D84), CHANGELOG.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 08:39:42 +00:00

905 lines
56 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",
];
[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))
{
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 (string, string, string, string?)[]
{
(@"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(((string?)null, (string?)null, (string?)null, (string?)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(((string?)null, (long?)null, (long?)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 = [.. System.Text.RegularExpressions.Regex.Matches(list, @"'(?<id>\d+)'", System.Text.RegularExpressions.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");
}
}