Compare commits

...
Author SHA1 Message Date
poli0981andClaude Fable 5.1 136d2a0829 fix(ledger): a print verb no longer migrates the ledger it prints, and a close checkpoints the WAL it wrote
`FrameLedger.Agent --console sessions`, run against the owner's own ledger while
its on-disk file was at schema 2, applied scripts 0003 and 0004 to it: every
verb opened through the one migrating `LedgerDatabase.OpenAsync`. Found while
investigating a ledger whose day of rows lived only in a WAL a fresh connection
discarded (salt one generation behind the header, no checkpoint into the main
file); the mechanism is unrecorded and 06_DATA_MODEL §Migrations carries what
was observed.

- `LedgerDatabase.OpenReadOnlyAsync`: existing file, `query_only`, no
  MigrationRunner; older AND newer schemas refused with the reason;
  WriteAsync/MaintainAsync throw.
- Agent: `sessions`, `consent list`, `killswitch status` open read-only
  (`Program.PrintsOnly`); `db path` opens nothing; a refusal is a console line
  with exit 7, not a crash dump. App `--diag` opens read-only.
- `OpenAsync` runs a passive checkpoint after migrating and reports it;
  `DisposeAsync` runs `wal_checkpoint(TRUNCATE)` and reports it, through the new
  `diagnostics` sink (one log line each in agent-*.log / ui-*.log).
- Tests: LedgerDatabaseTests (older schema refused byte-for-byte unchanged,
  read-only reads and refuses writes, missing file creates nothing, a close
  leaves the row readable through immutable=1); AgentReadOnlyVerbsTests.
- Docs: 06_DATA_MODEL, 12_BUILD, 10_LOGGING, HANDOFF §Traps, CHANGELOG.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-16 18:25:31 +07:00
12 changed files with 561 additions and 28 deletions

No files matched your search

+19
View File
@@ -251,6 +251,25 @@ under a `## [x.y.z] - date` heading in the same commit that bumps `VERSION`, the
### Fixed
- **A print verb no longer migrates the ledger it prints, and a close checkpoints the WAL it wrote (2026-09-16).**
`FrameLedger.Agent --console sessions`, run against the owner's own ledger while its on-disk file was at schema 2,
applied scripts 0003 and 0004 to it: every verb opened through the one migrating `LedgerDatabase.OpenAsync`. Found
while investigating a ledger whose day of rows lived only in a 4 MB WAL whose 1006 frames carried a salt one
generation older than the WAL header, over a main file no checkpoint had reached — a fresh connection (the console,
a next launch) saw the 14 September state, while the running App and Agent saw the day through the shared WAL
index. The mechanism is unrecorded (`06_DATA_MODEL` §Migrations carries what was observed and what is not known);
the data was rebuilt from the old-salt chain by hand. What changed: `LedgerDatabase.OpenReadOnlyAsync` — an
existing file, `query_only`, no pragma that writes, no `MigrationRunner`; a schema newer OR older than the build is
refused with the reason, and `WriteAsync`/`MaintainAsync` throw. The Agent's `sessions`, `consent list`,
`killswitch status` use it (`Program.PrintsOnly`), `db path` opens nothing at all, and a refusal is a console line
with exit 7, never a crash dump; the App's `--diag` uses it too. `OpenAsync` now runs a passive checkpoint after
migrating and reports it (`LedgerDatabase.OpenDiagnostics`, one `ledger: wal at open` log line), and
`DisposeAsync` runs `wal_checkpoint(TRUNCATE)` and reports that, so a clean close leaves the main file complete
whether or not SQLite's own close-time checkpoint runs. Tests: `LedgerDatabaseTests` (an older schema is refused
byte-for-byte unchanged; a read-only open reads and refuses to write; a missing file creates nothing; a close leaves
the row readable through `immutable=1`), `AgentReadOnlyVerbsTests` (the print-verb set, the refusal's exit code and
the untouched file, `db path` without a ledger). Docs: `06_DATA_MODEL` §Migrations, `12_BUILD` §Debugging,
`10_LOGGING` §Diagnostics, HANDOFF §Traps.
- **A start that fails says so on screen (2026-09-15).** When `App.RunAsync` caught its own exception — a ledger
that would not open (a newer schema, a locked file), a host that would not start — FrameLedger wrote a Fatal line to
`ui-*.log` and exited with code 1 with nothing on screen, so a user saw a click do nothing. It now shows
+26
View File
@@ -422,6 +422,32 @@ Sequential embedded SQL (`Migrations/0001_init.sql`, `0002_*.sql`, …), applied
> which are the consent fingerprint the gate reads and which a background scan must never refresh.
> `LatestVersion` is 4; `LedgerDatabaseTests` asserts the columns.
> **Every open used to migrate, and one that should not have did — 2026-09-16.** The Agent's `--console sessions`,
> a verb that prints, was run against the owner's ledger while the file on disk was at schema 2 and applied 0003 and
> 0004 to it. `LedgerDatabase.OpenReadOnlyAsync` exists since that day: an existing file, `PRAGMA query_only`, no
> `MigrationRunner`, and a refusal (`LedgerSchemaException`) for a schema **older** than the build as well as newer —
> the older file needs the App or `--serve` to bring it forward, not a verb whose name says it reads. The Agent's
> `sessions`, `consent list` and `killswitch status` open that way (`Program.PrintsOnly` is the list, pinned by
> `AgentReadOnlyVerbsTests`), `db path` opens nothing, and the App's `--diag` does the same.
>
> **What that run found, recorded because the mechanism is not known.** The on-disk `ledger.db` was 94 KB, 23 pages,
> dated 14 September, at schema 2 with three test games and no sessions; the day's 41 imported games and 18 sessions
> were in `ledger.db-wal` — 4 MB, 1006 frames — and every one of those frames carried salt-1 one **lower** than the
> WAL header's, with a checkpoint sequence of 1 and a single frame under the new salt. That is the shape SQLite leaves
> after a checkpoint has moved every frame into the main file and the next writer restarts the log; but no checkpoint
> had reached this main file (645 pages of data, 23 on disk, and the file's own time stamp two days old). A fresh
> connection therefore recovered one frame and saw the 14 September state, while the App and Agent that were running
> saw the whole day through the wal-index they shared. Neither process closed cleanly enough to fix it: the Agent's
> stop at 17:57 and the console's exit at 17:58 both left the WAL in place, and `-wal`/`-shm` then vanished between
> 18:00 and 18:04 with no FrameLedger process alive. The data was rebuilt by applying the old-salt chain to the main
> file (176 commits, `integrity_check` ok) and the broken set kept beside it. **Nothing in this repository writes the
> main file behind SQLite's back, replaces it, or restarts the WAL by hand**; what the code can do about an unknown
> mechanism is make the next occurrence visible, and it does: `OpenAsync` runs `wal_checkpoint(PASSIVE)` after
> migrating and logs the frame count it found and moved (`LedgerDatabase.OpenDiagnostics`), and `DisposeAsync` runs
> `wal_checkpoint(TRUNCATE)` and logs that, so a clean close leaves the main file complete and a WAL that will not
> checkpoint is a logged number rather than a silent one. A WAL at open holding frames a passive checkpoint cannot
> move, with no other FrameLedger process running, is the signature to look for.
> **Built 2026-09-09 (P2 PR-B):** `Infrastructure.Persistence.MigrationRunner` over scripts embedded in
> the assembly (so the schema a build applies is the one it was tested against), one transaction per
> script, under `Local\FrameLedger.Ledger.Migrate` — session-local rather than `Global\`, because the
+4
View File
@@ -144,6 +144,10 @@ Tails the active files (shared read), level filter, text search, pause autoscrol
- **Never include a game's own logs, saves, or config files** in a bug bundle, even when a crash looks game-related. We ship our logs only.
- `--diag` CLI flag on the App prints environment + capability report to stdout (support requests).
> **Read-only since 2026-09-16:** `DiagAsync` opens the ledger through `LedgerDatabase.OpenReadOnlyAsync`, so a
> diagnostic run against a ledger at another schema reports that fact (the schema line reads the refusal) rather
> than migrating the file it was asked to describe.
>
> **Built 2026-09-14 (P3 PR-8a).** `App.OnStartup` sees `--diag` and runs `DiagAsync` instead of the host: no
> window, no Agent, the ledger opened read-only for its schema version and the settings, then
> `Services/DiagReport.Build` (app version, OS and bitness, runtime, locale, elevation, data and logs
+5
View File
@@ -100,6 +100,11 @@ Agent flags: `--serve`, `--console`, ~~`--diag`~~ (the App's — `FrameLedger.ex
> shipped `FrameLedger.Agent.exe` against `hook-harness` with a scratch `--data-dir` and reads the one
> `sessions` row back — the milestone's technical half, in the merge gate.
> **The print verbs open the ledger read-only (2026-09-16).** `sessions`, `consent list` and `killswitch status`
> migrate nothing and refuse — exit 7, the reason on stderr — a ledger at a schema older or newer than the build;
> `db path` opens no file at all. Until then every verb went through the migrating open, and `sessions` run against
> the owner's ledger applied two scripts to it (`06_DATA_MODEL` §Migrations). `AgentReadOnlyVerbsTests` pins the set.
## Bundled assets
- ~~`assets/native/PresentMon.exe` (pinned, SHA-256 verified at build) for the Tier-2 fallback~~ — **DROPPED 2026-08-27, and there are no bundled native assets at all.** §S31 measured PresentMon classifying every frame of a ×4 capture as an application frame (row P2); the owner then dropped it outright. It is not bundled, not fetched, not used, and `tools/frametype-oracle.ps1` — the parser that consumed its output — is deleted with it. `assets/` does not exist and now has no reason to. **And since 2026-08-28 Tier 2 is not a measurement at all**: the ladder is two rungs, `EtwFrameSource` is deleted from the design, and whether a shipped build ever regains a no-injection measurement is `20_OPEN_QUESTIONS` §G.
+8
View File
@@ -1410,6 +1410,14 @@ deferred with a written rationale.
The mechanical ones live in the toolchain notes; these are the ones that cost a *wrong
diagnosis*.
- **A VERB THAT PRINTS WAS A WRITER UNTIL 2026-09-16, AND THE OWNER'S LEDGER IS NOT A FIXTURE.** `--console
sessions` against `%LOCALAPPDATA%\FrameLedger\ledger.db` applied two migration scripts, because every verb opened
through the one migrating path. The print verbs open read-only now (`Program.PrintsOnly`; a schema older than the
build is refused, exit 7) — but the rule that outlives the fix is: **nothing from a session is run against the
owner's data directory unless the owner asks for exactly that**; `--data-dir` exists for everything else. The same
day's ledger held a whole day of rows only in a WAL a fresh connection discarded (`06_DATA_MODEL` §Migrations
carries the shape); if `ledger: wal at open` in `agent-*.log` or `ui-*.log` reports frames that a passive checkpoint
did not move while no other FrameLedger process is running, stop and read that note before touching the file.
- **THE TESTS WRITE INTO THE REAL DATA FOLDER, AND THAT IS NOT A SWITCH TO ADD.** The Overlay's log path is
`SHGetKnownFolderPath`, never the environment (§S21), and the tests inject the shipped DLL, so 2492 hook-harness
logs had piled up in the owner's `%LOCALAPPDATA%\FrameLedger\logs` by 2026-09-15. Each test binary now sweeps the
+66 -11
View File
@@ -32,6 +32,7 @@ internal static class Program
private const int _exitUsage = 1;
private const int _exitNotImplemented = 2;
private const int _exitRulesFailed = 3;
private const int _exitLedgerRefused = 7;
private static int _crashReported;
@@ -40,16 +41,9 @@ internal static class Program
ArgumentNullException.ThrowIfNull(args);
AgentCommandLine cmd = AgentCommandLine.Parse(args);
if (cmd.Error is not null)
if (AnswerWithoutLogging(cmd) is { } answered)
{
AgentConsole.Problem(cmd.Error);
return _exitUsage;
}
if (cmd.Verb == AgentVerb.NotImplemented)
{
AgentConsole.Problem($"{cmd.Flag}: not this binary's — FrameLedger.exe --diag writes the report (10_LOGGING §Diagnostics extras)");
return _exitNotImplemented;
return answered;
}
AgentPaths paths = cmd.DataDirectory is { } dir ? new AgentPaths(Path.GetFullPath(dir)) : AgentPaths.Default;
@@ -69,10 +63,14 @@ internal static class Program
return _exitRulesFailed;
}
LedgerDatabase db = await LedgerDatabase.OpenAsync(paths.Database).ConfigureAwait(false);
LedgerDatabase? db = await OpenLedgerOrSayWhyAsync(cmd.Verb, paths).ConfigureAwait(false);
if (db is null)
{
return cmd.Verb == AgentVerb.DbPath ? _exitOk : _exitLedgerRefused;
}
await using (db.ConfigureAwait(false))
{
Log.Information("ledger: {Path} (schema {Schema}, migration {Migration})", db.Path, db.SchemaVersion, db.Migration);
return cmd.Verb switch
{
AgentVerb.Serve => await ServeAsync(db, paths).ConfigureAwait(false),
@@ -95,6 +93,63 @@ internal static class Program
}
}
/// <summary>A usage error or a flag this binary does not implement is answered before any file is touched.</summary>
private static int? AnswerWithoutLogging(AgentCommandLine cmd)
{
if (cmd.Error is not null)
{
AgentConsole.Problem(cmd.Error);
return _exitUsage;
}
if (cmd.Verb == AgentVerb.NotImplemented)
{
AgentConsole.Problem($"{cmd.Flag}: not this binary's — FrameLedger.exe --diag writes the report (10_LOGGING §Diagnostics extras)");
return _exitNotImplemented;
}
return null;
}
/// <summary>
/// The verbs that only print open the ledger read-only — no migration, no write — so that running one against a
/// ledger at another schema changes nothing on disk (2026-09-16: <c>sessions</c> against the owner's own ledger
/// applied two scripts to it). Every other verb is a writer and opens read-write, migrating as before.
/// </summary>
internal static bool PrintsOnly(AgentVerb verb) =>
verb is AgentVerb.Sessions or AgentVerb.ConsentList or AgentVerb.KillSwitchStatus or AgentVerb.DbPath;
/// <summary>
/// Null when a print verb refuses the ledger — at another schema, or not there — said on the console and in the log
/// rather than as a crash: nothing about this machine is broken.
/// </summary>
private static async Task<LedgerDatabase?> OpenLedgerOrSayWhyAsync(AgentVerb verb, AgentPaths paths)
{
if (verb == AgentVerb.DbPath)
{
// Prints a path; opens nothing. A machine with no ledger yet still has an answer, and the verb never reaches
// ConsoleVerbs because the answer is complete here.
AgentConsole.Line(paths.Database);
return null;
}
try
{
LedgerDatabase db = PrintsOnly(verb)
? await LedgerDatabase.OpenReadOnlyAsync(paths.Database).ConfigureAwait(false)
: await LedgerDatabase.OpenAsync(paths.Database, diagnostics: static line => Log.Information("{Line}", line)).ConfigureAwait(false);
Log.Information("ledger: {Path} (schema {Schema}, migration {Migration}{ReadOnly})", db.Path, db.SchemaVersion, db.Migration,
db.IsReadOnly ? ", read-only" : string.Empty);
return db;
}
catch (Exception ex) when (ex is LedgerSchemaException or FileNotFoundException)
{
AgentConsole.Problem(ex.Message);
Log.Warning("ledger: {Message}", ex.Message);
return null;
}
}
private static void ConfigureLogging(AgentPaths paths)
{
Directory.CreateDirectory(paths.Logs);
+3 -2
View File
@@ -85,7 +85,7 @@ public partial class App : System.Windows.Application
int exitCode = 0;
try
{
_db = await LedgerDatabase.OpenAsync(UiPaths.Database).ConfigureAwait(true);
_db = await LedgerDatabase.OpenAsync(UiPaths.Database, diagnostics: static line => Log.Information("{Line}", line)).ConfigureAwait(true);
var store = new SqliteSettingsStore(_db);
var appearance = new AppearanceSettings(store);
await appearance.LoadAsync().ConfigureAwait(true);
@@ -135,7 +135,8 @@ public partial class App : System.Windows.Application
var values = new Dictionary<string, string>(StringComparer.Ordinal);
try
{
LedgerDatabase db = await LedgerDatabase.OpenAsync(UiPaths.Database).ConfigureAwait(true);
// Read-only: a diagnostic run against a ledger at another schema must report it, not migrate it (2026-09-16).
LedgerDatabase db = await LedgerDatabase.OpenReadOnlyAsync(UiPaths.Database).ConfigureAwait(true);
await using (db.ConfigureAwait(true))
{
schema = db.SchemaVersion;
@@ -1,3 +1,4 @@
using System.Globalization;
using Dapper;
using Microsoft.Data.Sqlite;
@@ -20,6 +21,23 @@ namespace FrameLedger.Infrastructure.Persistence;
/// a guess; <see cref="OpenAsync"/> throws <see cref="LedgerSchemaException"/> and the caller tells the
/// user to update.
/// </para>
/// <para>
/// <b>A read-only open migrates nothing (2026-09-16).</b> <see cref="OpenReadOnlyAsync"/> is for the verbs that
/// only print — the Agent's <c>sessions</c>, <c>db path</c>, <c>consent list</c>, <c>killswitch status</c> and the
/// App's <c>--diag</c>. Until it existed, every one of them went through <see cref="OpenAsync"/>, and a
/// "read-only" verb run against a ledger at an older schema <em>applied the missing scripts</em> to it — measured
/// on the owner's own ledger, whose on-disk file was at schema 2 while the running App and Agent saw schema 4
/// through the shared WAL index. A verb whose name says it reads must not be a writer by accident.
/// </para>
/// <para>
/// <b>The WAL is checkpointed at open and at close, and both are reported.</b> The same incident found a
/// 4 MB WAL whose 1006 frames carried a salt one generation older than the WAL header, over a main file that
/// no checkpoint had reached: a fresh connection saw nothing written that day. The mechanism is unrecorded
/// (<c>06_DATA_MODEL</c> §Migrations carries what was observed); what this class can do about it is make the
/// next occurrence visible — <see cref="OpenDiagnostics"/> says how many frames the WAL held at open and how
/// many a passive checkpoint moved, and <see cref="DisposeAsync"/> runs a truncating checkpoint so a clean
/// close leaves the main file holding everything.
/// </para>
/// </remarks>
public sealed class LedgerDatabase : IAsyncDisposable
{
@@ -28,13 +46,18 @@ public sealed class LedgerDatabase : IAsyncDisposable
private readonly SqliteConnection _connection;
private readonly SemaphoreSlim _gate = new(1, 1);
private readonly Action<string>? _diagnostics;
private LedgerDatabase(string path, SqliteConnection connection, MigrationOutcome migration, long schemaVersion)
private LedgerDatabase(string path, SqliteConnection connection, MigrationOutcome migration, long schemaVersion,
bool isReadOnly, LedgerWalCheckpoint? openCheckpoint, Action<string>? diagnostics)
{
Path = path;
_connection = connection;
Migration = migration;
SchemaVersion = schemaVersion;
IsReadOnly = isReadOnly;
OpenDiagnostics = openCheckpoint;
_diagnostics = diagnostics;
}
/// <summary>The file this instance opened.</summary>
@@ -46,12 +69,22 @@ public sealed class LedgerDatabase : IAsyncDisposable
/// <summary>The schema version after opening.</summary>
public long SchemaVersion { get; }
/// <summary>True when opened by <see cref="OpenReadOnlyAsync"/>: no migration ran, and <see cref="WriteAsync{T}"/> refuses.</summary>
public bool IsReadOnly { get; }
/// <summary>
/// The passive checkpoint <see cref="OpenAsync"/> ran after migrating, or null for a read-only open. A WAL with
/// frames that a passive checkpoint could not move is another process's live write set — or the incident above.
/// </summary>
public LedgerWalCheckpoint? OpenDiagnostics { get; }
/// <summary>
/// Opens (creating the file and its directory if needed), sets the pragmas, migrates. A path is
/// REQUIRED: <see cref="LedgerPaths.DefaultDatabase"/> is the Agent's; anything else says why.
/// <paramref name="diagnostics"/> receives one line per checkpoint (open and close) when given.
/// </summary>
public static async Task<LedgerDatabase> OpenAsync(string path, int busyTimeoutMs = DefaultBusyTimeoutMs,
CancellationToken ct = default)
Action<string>? diagnostics = null, CancellationToken ct = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(path);
ArgumentOutOfRangeException.ThrowIfNegative(busyTimeoutMs);
@@ -59,33 +92,80 @@ public sealed class LedgerDatabase : IAsyncDisposable
string full = System.IO.Path.GetFullPath(path);
Directory.CreateDirectory(System.IO.Path.GetDirectoryName(full)!);
var connection = new SqliteConnection(new SqliteConnectionStringBuilder
{
DataSource = full,
Mode = SqliteOpenMode.ReadWriteCreate,
Pooling = false,
}.ToString());
SqliteConnection connection = Connect(full, SqliteOpenMode.ReadWriteCreate);
try
{
await connection.OpenAsync(ct).ConfigureAwait(false);
// 06_DATA_MODEL's four pragmas. busy_timeout first: WAL's own journal switch can contend.
await connection.ExecuteAsync(new CommandDefinition("PRAGMA busy_timeout = " + busyTimeoutMs.ToString(System.Globalization.CultureInfo.InvariantCulture), cancellationToken: ct)).ConfigureAwait(false);
await BusyTimeoutAsync(connection, busyTimeoutMs, ct).ConfigureAwait(false);
await connection.ExecuteAsync(new CommandDefinition("PRAGMA journal_mode = WAL", cancellationToken: ct)).ConfigureAwait(false);
await connection.ExecuteAsync(new CommandDefinition("PRAGMA synchronous = NORMAL", cancellationToken: ct)).ConfigureAwait(false);
await connection.ExecuteAsync(new CommandDefinition("PRAGMA foreign_keys = ON", cancellationToken: ct)).ConfigureAwait(false);
MigrationOutcome migration = await MigrationRunner.ApplyAsync(connection, ct).ConfigureAwait(false);
long version = await connection.ExecuteScalarAsync<long?>(new CommandDefinition(
"SELECT MAX(version) FROM schema_migrations", cancellationToken: ct)).ConfigureAwait(false) ?? 0;
long version = await VersionAsync(connection, ct).ConfigureAwait(false);
if (migration == MigrationOutcome.NewerThanThisBuild)
{
throw new LedgerSchemaException(
$"{full} is at schema version {version}, newer than this build's {MigrationRunner.LatestVersion}; refusing to read it");
}
return new LedgerDatabase(full, connection, migration, version);
LedgerWalCheckpoint atOpen = await CheckpointAsync(connection, "passive", ct).ConfigureAwait(false);
diagnostics?.Invoke($"ledger: wal at open — {atOpen}");
return new LedgerDatabase(full, connection, migration, version, isReadOnly: false, atOpen, diagnostics);
}
catch
{
await connection.DisposeAsync().ConfigureAwait(false);
throw;
}
}
/// <summary>
/// Opens an EXISTING ledger for reading only: no migration, no pragma that writes, and every statement under
/// <c>query_only</c>. Refuses a schema newer than this build (as <see cref="OpenAsync"/> does) AND one older than
/// it — the older file needs a read-write open to migrate, and this one will not do it on a print verb's behalf.
/// </summary>
/// <remarks>
/// The connection is <see cref="SqliteOpenMode.ReadWrite"/> rather than <see cref="SqliteOpenMode.ReadOnly"/>
/// because a WAL database needs its <c>-shm</c> index created by whoever opens it first, and SQLite's read-only
/// mode cannot create it; <c>PRAGMA query_only</c> is what keeps this connection from changing a row, and the
/// absence of <see cref="MigrationRunner"/> is what keeps it from changing the schema.
/// </remarks>
public static async Task<LedgerDatabase> OpenReadOnlyAsync(string path, int busyTimeoutMs = DefaultBusyTimeoutMs,
CancellationToken ct = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(path);
ArgumentOutOfRangeException.ThrowIfNegative(busyTimeoutMs);
string full = System.IO.Path.GetFullPath(path);
if (!File.Exists(full))
{
throw new FileNotFoundException($"{full} does not exist; a read-only open creates nothing", full);
}
SqliteConnection connection = Connect(full, SqliteOpenMode.ReadWrite);
try
{
await connection.OpenAsync(ct).ConfigureAwait(false);
await BusyTimeoutAsync(connection, busyTimeoutMs, ct).ConfigureAwait(false);
await connection.ExecuteAsync(new CommandDefinition("PRAGMA query_only = 1", cancellationToken: ct)).ConfigureAwait(false);
long version = await VersionAsync(connection, ct).ConfigureAwait(false);
if (version > MigrationRunner.LatestVersion)
{
throw new LedgerSchemaException(
$"{full} is at schema version {version}, newer than this build's {MigrationRunner.LatestVersion}; refusing to read it");
}
if (version < MigrationRunner.LatestVersion)
{
throw new LedgerSchemaException(
$"{full} is at schema version {version}, older than this build's {MigrationRunner.LatestVersion}; a read-only open migrates nothing — run the App or the Agent's --serve once to bring it forward");
}
return new LedgerDatabase(full, connection, MigrationOutcome.AlreadyCurrent, version, isReadOnly: true, openCheckpoint: null, diagnostics: null);
}
catch
{
@@ -118,6 +198,7 @@ public sealed class LedgerDatabase : IAsyncDisposable
public async ValueTask<T> MaintainAsync<T>(Func<SqliteConnection, CancellationToken, Task<T>> work, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(work);
RefuseIfReadOnly();
await _gate.WaitAsync(ct).ConfigureAwait(false);
try
@@ -138,6 +219,7 @@ public sealed class LedgerDatabase : IAsyncDisposable
CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(work);
RefuseIfReadOnly();
await _gate.WaitAsync(ct).ConfigureAwait(false);
try
@@ -164,9 +246,63 @@ public sealed class LedgerDatabase : IAsyncDisposable
}
}
/// <summary>
/// A read-write instance checkpoints the WAL (<c>TRUNCATE</c>) before closing, so that a clean close leaves the
/// main file complete whether or not SQLite's own close-time checkpoint runs; the result goes to the diagnostics
/// sink. A checkpoint that cannot complete — another process holds a read transaction — is reported, not thrown.
/// </summary>
public async ValueTask DisposeAsync()
{
if (!IsReadOnly)
{
try
{
LedgerWalCheckpoint atClose = await CheckpointAsync(_connection, "truncate", CancellationToken.None).ConfigureAwait(false);
_diagnostics?.Invoke($"ledger: wal at close — {atClose}");
}
catch (SqliteException ex)
{
_diagnostics?.Invoke($"ledger: wal at close — checkpoint failed: {ex.Message}");
}
}
await _connection.DisposeAsync().ConfigureAwait(false);
_gate.Dispose();
}
private static SqliteConnection Connect(string full, SqliteOpenMode mode) => new(new SqliteConnectionStringBuilder
{
DataSource = full,
Mode = mode,
Pooling = false,
}.ToString());
private static Task<int> BusyTimeoutAsync(SqliteConnection connection, int busyTimeoutMs, CancellationToken ct) =>
connection.ExecuteAsync(new CommandDefinition("PRAGMA busy_timeout = " + busyTimeoutMs.ToString(CultureInfo.InvariantCulture), cancellationToken: ct));
private static async Task<long> VersionAsync(SqliteConnection connection, CancellationToken ct)
{
bool hasTable = await connection.ExecuteScalarAsync<long>(new CommandDefinition(
"SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'schema_migrations'",
cancellationToken: ct)).ConfigureAwait(false) > 0;
return hasTable
? await connection.ExecuteScalarAsync<long?>(new CommandDefinition(
"SELECT MAX(version) FROM schema_migrations", cancellationToken: ct)).ConfigureAwait(false) ?? 0
: 0;
}
private static async Task<LedgerWalCheckpoint> CheckpointAsync(SqliteConnection connection, string mode, CancellationToken ct)
{
(long busy, long log, long checkpointed) = await connection.QuerySingleAsync<(long, long, long)>(new CommandDefinition(
"PRAGMA wal_checkpoint(" + mode + ")", cancellationToken: ct)).ConfigureAwait(false);
return new LedgerWalCheckpoint(mode, Busy: busy != 0, WalFrames: log, Checkpointed: checkpointed);
}
private void RefuseIfReadOnly()
{
if (IsReadOnly)
{
throw new InvalidOperationException($"{Path} was opened read-only; this verb prints and does not write");
}
}
}
@@ -0,0 +1,16 @@
namespace FrameLedger.Infrastructure.Persistence;
/// <summary>
/// What one <c>PRAGMA wal_checkpoint</c> reported: SQLite's three columns, named. <paramref name="WalFrames"/> is the
/// number of frames the WAL held (−1 when the database is not in WAL mode); <paramref name="Checkpointed"/> is how
/// many of them reached the main file; <paramref name="Busy"/> is true when another connection kept it from finishing.
/// A read-write open records one of these (<see cref="LedgerDatabase.OpenDiagnostics"/>) and a close reports another.
/// </summary>
public sealed record LedgerWalCheckpoint(string Mode, bool Busy, long WalFrames, long Checkpointed)
{
/// <summary>True when every frame the WAL held is now in the main file.</summary>
public bool Complete => !Busy && WalFrames <= Checkpointed;
public override string ToString() =>
$"{Mode}: {WalFrames} frame(s) in the wal, {Checkpointed} checkpointed{(Busy ? ", busy" : string.Empty)}";
}
@@ -0,0 +1,120 @@
using System.Diagnostics;
using Dapper;
using FluentAssertions;
using FrameLedger.Agent.Cli;
using FrameLedger.Infrastructure.Persistence;
using Microsoft.Data.Sqlite;
namespace FrameLedger.Agent.Tests;
/// <summary>
/// 2026-09-16: <c>FrameLedger.Agent --console sessions</c>, run against the owner's own ledger while its on-disk file
/// was at schema 2, applied scripts 0003 and 0004 to it — a verb whose name says it prints was a writer, because every
/// verb opened the ledger through the one migrating path. The print verbs now open read-only and refuse a schema they
/// would have had to migrate; the file is byte-identical afterwards, and the refusal is a console line with its own exit
/// code, never a crash dump.
/// </summary>
public sealed class AgentReadOnlyVerbsTests : IDisposable
{
private const int _exitLedgerRefused = 7;
private static CancellationToken Ct => TestContext.Current.CancellationToken;
private static string Agent => Path.Combine(AppContext.BaseDirectory, "FrameLedger.Agent.exe");
private readonly string _dataDir = Path.Combine(Path.GetTempPath(), "fl-agent-ro-" + Guid.NewGuid().ToString("N"));
private string Ledger => Path.Combine(_dataDir, LedgerPaths.DatabaseFileName);
public void Dispose()
{
try
{
Directory.Delete(_dataDir, recursive: true);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
}
}
[Fact]
public void ThePrintVerbsAreExactlyThese()
{
// Each of these prints and changes nothing; every other verb writes (consent, capture, recovery, the kill switch,
// the maintenance flags) and keeps the migrating open. A verb added here must not write.
AgentVerb[] printsOnly = [.. Enum.GetValues<AgentVerb>().Where(Program.PrintsOnly)];
printsOnly.Should().BeEquivalentTo([AgentVerb.Sessions, AgentVerb.ConsentList, AgentVerb.KillSwitchStatus, AgentVerb.DbPath]);
}
[Fact]
public async Task SessionsAgainstAnOlderLedgerRefusesAndLeavesTheFileAlone()
{
await MakeOlderLedgerAsync().ConfigureAwait(true);
byte[] before = await File.ReadAllBytesAsync(Ledger, Ct).ConfigureAwait(true);
(string output, int exit) = await RunAsync("sessions", "--last", "1").ConfigureAwait(true);
exit.Should().Be(_exitLedgerRefused, output);
output.Should().Contain("older than this build").And.NotContain("crash dump", output);
byte[] after = await File.ReadAllBytesAsync(Ledger, Ct).ConfigureAwait(true);
after.Should().Equal(before, "the print verb migrated nothing");
Directory.Exists(Path.Combine(_dataDir, "crashdumps")).Should().BeFalse("a refusal is not a crash");
}
[Fact]
public async Task SessionsAgainstNoLedgerSaysSoAndCreatesNone()
{
Directory.CreateDirectory(_dataDir);
(string output, int exit) = await RunAsync("sessions").ConfigureAwait(true);
exit.Should().Be(_exitLedgerRefused, output);
output.Should().Contain("does not exist");
File.Exists(Ledger).Should().BeFalse("a read-only open creates nothing");
}
[Fact]
public async Task DbPathNeedsNoLedgerAtAll()
{
Directory.CreateDirectory(_dataDir);
(string output, int exit) = await RunAsync("db", "path").ConfigureAwait(true);
exit.Should().Be(0, output);
output.Should().Contain(Ledger);
File.Exists(Ledger).Should().BeFalse();
}
private async Task MakeOlderLedgerAsync()
{
Directory.CreateDirectory(_dataDir);
LedgerDatabase db = await LedgerDatabase.OpenAsync(Ledger, ct: Ct).ConfigureAwait(false);
await db.DisposeAsync().ConfigureAwait(false);
var c = new SqliteConnection(new SqliteConnectionStringBuilder { DataSource = Ledger, 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 > 2", cancellationToken: Ct)).ConfigureAwait(false);
await c.ExecuteAsync(new CommandDefinition("PRAGMA wal_checkpoint(TRUNCATE)", cancellationToken: Ct)).ConfigureAwait(false);
}
}
private async Task<(string Output, int Exit)> RunAsync(params string[] consoleArgs)
{
File.Exists(Agent).Should().BeTrue("the Agent must be built and copied beside this test");
var psi = new ProcessStartInfo(Agent) { UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardError = true };
psi.ArgumentList.Add("--console");
psi.ArgumentList.Add("--data-dir");
psi.ArgumentList.Add(_dataDir);
foreach (string a in consoleArgs)
{
psi.ArgumentList.Add(a);
}
using Process p = Process.Start(psi)!;
Task<string> err = p.StandardError.ReadToEndAsync(Ct);
string stdout = await p.StandardOutput.ReadToEndAsync(Ct).ConfigureAwait(false);
await p.WaitForExitAsync(Ct).ConfigureAwait(false);
return (stdout + "\n---- stderr ----\n" + await err.ConfigureAwait(false) + $"\n---- exit {p.ExitCode} ----\n", p.ExitCode);
}
}
@@ -1,6 +1,8 @@
using Dapper;
using FluentAssertions;
using FluentAssertions.Specialized;
using FrameLedger.Infrastructure.Persistence;
using Microsoft.Data.Sqlite;
namespace FrameLedger.Infrastructure.Tests.Persistence;
@@ -128,6 +130,147 @@ public sealed class LedgerDatabaseTests
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()
{
@@ -17,13 +17,13 @@ internal sealed class LedgerFixture : IAsyncDisposable
public static async Task<LedgerFixture> OpenAsync(int busyTimeoutMs = LedgerDatabase.DefaultBusyTimeoutMs)
{
var f = new LedgerFixture();
f.Db = await LedgerDatabase.OpenAsync(f.Path, busyTimeoutMs, TestContext.Current.CancellationToken).ConfigureAwait(false);
f.Db = await LedgerDatabase.OpenAsync(f.Path, busyTimeoutMs, ct: TestContext.Current.CancellationToken).ConfigureAwait(false);
return f;
}
/// <summary>A second, independent connection to the same file — another process, as far as SQLite is concerned.</summary>
public Task<LedgerDatabase> OpenAnotherAsync(CancellationToken ct, int busyTimeoutMs = LedgerDatabase.DefaultBusyTimeoutMs) =>
LedgerDatabase.OpenAsync(Path, busyTimeoutMs, ct);
LedgerDatabase.OpenAsync(Path, busyTimeoutMs, ct: ct);
public async ValueTask DisposeAsync()
{