Compare commits

...
Author SHA1 Message Date
poli0981andClaude Opus 5.5 6973bfb7f2 fix: a session whose entry was removed lands where its executable lives, or is dropped; one bad .partial never stops the watcher
Two GIRLS' FRONTLINE 2 sessions on the owner's machine (2026-09-22 23:26, 2026-09-23 00:25) died on the
sessions.game_id foreign key because their entry was removed and re-imported while the game ran, and each
left a .partial that the next start's recovery would have failed on the same way - stopping the host, since
recovery runs before the watcher and the Generic Host stops on a background service's exception.

- ISessionRepository.ResolveOwnerAsync: the row the session started under when it predates the session or
  holds its executable, else the row that holds the executable now, else FinalizeStatus.GameRemoved.
- The write re-checks the row inside its transaction (SessionOwnerMissingException), never the FK error.
- PartialRecovery never throws: an unfinalizable file is quarantined as <guid>.partial.failed.
- Log lines name the session, the game and the executable; the host logs into agent-*.log (AddSerilog).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 02:00:29 +07:00
29 changed files with 573 additions and 34 deletions

No files matched your search

+12 -1
View File
@@ -27,7 +27,18 @@ under a `## [x.y.z] - date` heading in the same commit that bumps `VERSION`, the
## [Unreleased]
_Nothing yet — entries continue here after `0.1.0-beta.5`._
### Fixed
- **A game removed from the library while it runs no longer loses its session — or stops the Agent at the next
start.** On 2026-09-22 23:26 and 2026-09-23 00:25 a GIRLS' FRONTLINE 2 session ended `FAULTED` on the database's
foreign key: its entry had been removed (and re-imported) while the game ran, and the session was written under the
id it started with. Each left a `.partial` file, and the recovery that runs at every start would have failed on it
the same way — with no guard, so the Agent's host would have stopped at every start and nothing would have been
captured. Now the session is stored under the entry that holds its executable when the one it started with is gone
(the re-imported entry); when no entry does — the game was removed with its sessions — it is dropped with a log line
that says so. Recovery never throws: a file it cannot finalize is set aside as `<guid>.partial.failed`, kept for a bug
report, and the next file is recovered. The `FAULTED` and end-of-session log lines now name the session, the game and
its executable, and the Agent's host logs its own warnings and errors into `agent-*.log`.
## [0.1.0-beta.5] - 2026-09-22
+16
View File
@@ -340,6 +340,22 @@ because a layer cannot leave a running game's loader chain.
**Discard rule:** duration < min session length (default 30 s) → discard silently (log only).
> **A session whose entry was removed while it ran (2026-09-23).** Step 5 wrote under the id the session *started*
> with, and the owner's GIRLS' FRONTLINE 2 entry was removed — and re-imported — twice while the game ran: both
> sessions died on the foreign key (`session: FAULTED SqliteException: … FOREIGN KEY constraint failed`, 2026-09-22
> 23:26 and 2026-09-23 00:25), and each left a `.partial` whose recovery would have died the same way at the next
> start — stopping the host, because recovery ran before the watcher with no guard. As built:
> - **The owner is looked up, not assumed** (`ISessionRepository.ResolveOwnerAsync`, `FinalizeInput.ExePath`): the id
> the session started under when that row predates the session or holds its executable (an id SQLite reused for a
> later game is neither — `games.id` has no AUTOINCREMENT), else the row that holds the executable's path now (the
> re-imported entry), else **`GameRemoved`**: the user removed the game with its sessions and this was one of them.
> Nothing is written, the `.partial` is deleted, and the log says which. The write transaction re-checks the row, so a
> removal between the lookup and the insert is the same answer rather than the foreign key's exception.
> - **Recovery never throws.** A file it cannot finalize is set aside as `<guid>.partial.failed` (never retried, kept for
> a bug report) and reported `Failed`; the next file is recovered, and the watcher starts either way.
> - The Agent's host logs through Serilog since the same day: a background service that stops the host is now in
> `agent-*.log`, where before it was in no file at all.
> **Built 2026-09-10 (P2 PR-D): `Application.Recording`.** The state machine above is the intent; what
> runs is one class per box. `SessionRecorder` owns a session end to end — the row's identity and time
> base (`session_guid`, `qpc_epoch`/`qpc_frequency` from `TimeProvider.GetTimestamp`, which is QPC), the
+10
View File
@@ -389,6 +389,16 @@ Because Tier-1 and Tier-2 sessions carry different fields, every query that comp
> column computed from the prefix exactly as a live finalize would. **Rejected:** a `sessions_in_progress`
> table — a blob churn every minute, a lock fight with the UI in P3, and `04_CAPTURE` had already named a
> file under `tmp\`.
>
> **The header's `game_id` is where the session started, not necessarily where it lands (2026-09-23).** A live
> finalize and a recovery both ask `ISessionRepository.ResolveOwnerAsync`: that id when the row predates the session
> or holds the header's exe path; else the row that holds the exe path now (an entry removed and re-imported while
> the game ran); else nothing — `FinalizeStatus.GameRemoved` / `RecoveryStatus.GameRemoved`, file deleted, nothing
> written. `games.id` is `INTEGER PRIMARY KEY` without AUTOINCREMENT, so a deleted id can be handed to the next row
> added; `added_at` after the session's start and another path is how that row is told apart. A file recovery cannot
> finalize for any other reason is renamed `<guid>.partial.failed` (`IPartialSessionStore.Quarantine`) — not listed
> again, not retried, kept for a bug report — and recovery goes on to the next file: it runs before the watcher on
> every start, and one file used to be able to stop them all.
## Retention
+1 -1
View File
@@ -335,7 +335,7 @@ Unchanged in spirit from v1, bumped to `v2` for the new message set.
| `SweepRetention` | UI→A | **no payload** — a trigger, like `UpdateRules`: the Agent applies `06_DATA_MODEL` §Retention to every game with the `retention.raw_sessions_per_game` it reads itself → `SweepRetentionAck { keep, games, sessions }` (`keep` 0 = unlimited, and then nothing was swept). *(Built 2026-09-15, P4 PR-7, for Tools ▸ Database maintenance: `Application.Recording.RetentionSweep` over `ISessionRepository.SweepRetentionAllAsync`, composed into `AgentCommandHandler` under `--serve`. The client names no number because the rows are the Agent's (§Writer ownership). Additive: an older Agent answers `Error UnknownType`, which the dialog reads as "restart the Agent". Carries no safety fact.)* |
| `SessionStarted` | A→UI | `{ sessionGuid, gameId, gameName, pid, tier, startedAt }` — **published at the attach**, i.e. when the session becomes Tier 1 and the live card has something to show; a session that never attaches has no `SessionStarted`, only its `SessionCompleted` (tier 2) and, when a refusal or error caused that, the event below that names it |
| `SessionProgress` | A→UI | 1 Hz: `{ sessionGuid, elapsedS, presents5s, presentedFps5s?, presentedQualifier, nativeFps5s?, displayedFps5s?, fgFactor?, fgMode, upscaler?, upscalerQuality?, upscalerDriverReported?, renderW/H?, outputW/H?, rtActive?, gpuTempC?, cpuTempC?, cpuLoadPct?, vramProcMb?, latencyUs?, fgRefusal?, fgRuntimeCensus? }` — a 5 s rolling window over the ring through the SAME Domain calculators the row uses (`SessionProgressCalculator`, D13). **`upscalerDriverReported` added 2026-09-21, optional:** `dlss` when the NVIDIA driver reports an NGX super-resolution feature created and evaluated in the target (`03_METRICS` §The driver-reported rung), so the live card says `DLSS (driver-reported)` where no hook can name the upscaler; identity only. **`cpuLoadPct` added 2026-09-21, optional** (CPU time busy over the last telemetry tick, 0–100; `cpuTempC` has a producer from the same date, present only when the Agent is elevated with PawnIO). **Two fields added 2026-09-14, both optional (an older client ignores them, §C):** `fgRefusal` is the row's `fg_refusal` (schema 0003) — present when `fgMode` names a technology and `fgFactor` is absent, so the live card can say "DLSS-G active — factor not counted" rather than N/A; `fgRuntimeCensus` is the raw census so the `fg_runtime_loaded` chip can name the module. **Rule 6 at the wire (2026-09-13):** `nativeFps5s` / `displayedFps5s` / `fgFactor` are present only when frame generation was measured in the window; otherwise `presentedFps5s` stands alone with `presentedQualifier` (`census_not_run` · `no_fg_runtime` · `fg_runtime_loaded` · `none_withheld`, the row's `presented_qualifier` from the same function). Every unmeasured field is absent, never 0. Suppressed when no client is connected |
| `SessionCompleted` | A→UI | `{ sessionGuid, sessionId?, exitStatus, tier, finalize, reason }` — UI loads the full row from SQLite; `sessionId` is null and `finalize` is `discarded` when the row was not stored (under the minimum length); `exitStatus` is the row's vocabulary (`normal` · `crashed` · `unhooked_safety` · `degraded`); `reason` is the loop's `SessionEndReason` |
| `SessionCompleted` | A→UI | `{ sessionGuid, sessionId?, exitStatus, tier, finalize, reason }` — UI loads the full row from SQLite; `sessionId` is null and `finalize` is `discarded` when the row was not stored (under the minimum length), or `game_removed` when its entry was removed with its sessions while it ran (2026-09-23); `exitStatus` is the row's vocabulary (`normal` · `crashed` · `unhooked_safety` · `degraded`); `reason` is the loop's `SessionEndReason` |
| `CaptureRefused` | A→UI | `{ gameId, gameName, reason, family?, signal?, hookingTurnedOff }` — **guard fired**; `hookingTurnedOff` (2026-09-22) is true when the finding turned the game's hooking off (`19_SAFETY` §What a finding does to the game); UI shows the plain-language explanation — ~~and the Tier-2 offer~~; there is no alternative measurement to offer, only the option to record the session unmeasured (`08_UI` §Safety events). *(Built: for `RefusedByGuard`, `RefusedPreviouslyBlocked`, `RefusedKillSwitch` and `PreScanCouldNotVerify` — the last with no family, because "could not verify" is neither a hit nor a pass; `family`/`signal` are the verdict's. A game merely not enabled or not consented raises nothing: that is an ordinary Tier-2 row, not a refusal to explain.)* |
| `CaptureDegraded` | A→UI | `{ sessionGuid, from: 1, to: 2, reason }` — Tier 1 → Tier 2 mid-flight, or overlay self-disabled. **Under a two-rung ladder this means measurement STOPPED**, not that it continued at lower fidelity, and the notice must say so. *(Built: `SupervisionLost`, `WriterSelfDisabled`, `WriterStoppedBlocklisted`, `WriterNeverInstalledHooks`, `SupervisionFaulted`, `KillSwitchEngaged` — `RecordedSessionEvents.Classify` is the table.)* |
| `SafetyUnhook` | A→UI | `{ sessionGuid, family?, signal?, hookingTurnedOff }` — anti-cheat appeared mid-session; prominent UI notice; `hookingTurnedOff` as on `CaptureRefused`. *(Built: the verdict that FIRED, not the pass that started the session — `CaptureOutcome.Verdict` carries the supervisor's last verdict on this reason since 2026-09-13.)* |
+15
View File
@@ -1470,6 +1470,21 @@ fact stands.
- **Meziantou MA0004 fires on the SECOND await of a test method** once a lambda inside it used `ConfigureAwait(false)`.
- **A patch script must not carry `\r\n` inside a bash heredoc**; the helper module is written with the Write tool.
## 2026-09-23 — the beta.6 train: a file name is not an identity, one entry per executable, Tier 2 shown live
*Status is `CHANGELOG.md` `[Unreleased]` until the tag; this is what no other file carries. The owner's list and the
evidence behind each item are in the approved plan the PRs cite; the decisions it took are D25–D28.*
**Traps.**
- **A background service that throws stops the Agent's host, and until 2026-09-23 it said so nowhere.** The Generic
Host's default `BackgroundServiceExceptionBehavior` is `StopHost`, and `ServeAsync` never routed
Microsoft.Extensions.Logging into Serilog, so the reason reached no file. `WatcherHostedService` runs recovery before
the watcher: one `.partial` whose finalize threw would have stopped every start, and the App would have started a new
Agent into the same failure each time. `PartialRecovery` never throws now, and the host logs through `AddSerilog`.
- **Removing an entry while its game runs used to lose the session.** Both of the owner's GIRLS' FRONTLINE 2 faults
were a removal (to clean up an `H:` twin) under a running session. The finalize now resolves the owner; a test that
deletes a row mid-session must expect `GameRemoved` or a re-keyed row, never an exception.
## Owner-only — no PR can close these
1. **§S23-2 — branch protection.** `Rules / validate` is not a required status check on
@@ -14,16 +14,26 @@ namespace FrameLedger.Agent.Hosting;
/// a session somebody lost, and it becomes an <c>interrupted</c> row before any new session can write beside
/// it. Then the orchestrator polls until the host stops; its sessions finalize inside the host's shutdown
/// grace, and one that does not make it leaves its <c>.partial</c> for the next start — the same rule.
/// <b>Nothing recovery does can keep the watcher from starting (2026-09-23)</b>: the host's default for a background
/// service that throws is to stop the whole Agent, so a file recovery could not finalize would have stopped every start
/// after it. <see cref="PartialRecovery"/> no longer throws; the guard here is for what it cannot foresee.
/// </remarks>
internal sealed class WatcherHostedService(PartialRecovery recovery, CaptureOrchestrator orchestrator) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
IReadOnlyList<RecoveryOutcome> recovered = await recovery.RecoverAsync(stoppingToken).ConfigureAwait(false);
Log.Information("recover: {Count} pending .partial file(s)", recovered.Count);
foreach (RecoveryOutcome o in recovered)
try
{
Log.Information("recover: {Guid} {Status} {Detail}", o.SessionGuid.ToString("N"), o.Status, o.Detail);
IReadOnlyList<RecoveryOutcome> recovered = await recovery.RecoverAsync(stoppingToken).ConfigureAwait(false);
Log.Information("recover: {Count} pending .partial file(s)", recovered.Count);
foreach (RecoveryOutcome o in recovered)
{
Log.Information("recover: {Guid} {Status} {Detail}", o.SessionGuid.ToString("N"), o.Status, o.Detail);
}
}
catch (Exception ex) when (ex is not OperationCanceledException and not OutOfMemoryException)
{
Log.Warning(ex, "recover: did not complete; the watcher starts anyway and the files stay for the next start");
}
Log.Information("serve: watching the games table at 1 Hz; hooking only where a game is enabled and consented ({Elevation}, pid {Pid})",
+6
View File
@@ -200,6 +200,9 @@ internal static class Program
Directory.CreateDirectory(paths.Logs);
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Information()
// The host's own lines reach this file since 2026-09-23 (ServeAsync's AddSerilog): its warnings and errors —
// a background service that stopped the host — not its start/stop chatter.
.MinimumLevel.Override("Microsoft", Serilog.Events.LogEventLevel.Warning)
.WriteTo.File(Path.Combine(paths.Logs, "agent-.log"), formatProvider: System.Globalization.CultureInfo.InvariantCulture,
rollingInterval: RollingInterval.Day, retainedFileCountLimit: 14)
.CreateLogger();
@@ -236,6 +239,9 @@ internal static class Program
private static async Task<int> ServeAsync(LedgerDatabase db, AgentPaths paths)
{
HostApplicationBuilder builder = Host.CreateApplicationBuilder();
// The host's log into agent-*.log (2026-09-23). A background service that threw stopped the host with nothing in
// the file: the Generic Host logs that through Microsoft.Extensions.Logging, which was never routed here.
builder.Services.AddSerilog();
// Before the composition, so its TryAdd keeps this one: Shutdown over the pipe stops the host (PR-1b).
builder.Services.AddSingleton<IAgentLifetime, HostAgentLifetime>();
builder.Services.AddFrameLedgerAgent(db, paths);
@@ -104,6 +104,7 @@ public static class RecordedSessionEvents
FinalizeStatus.Saved => "saved",
FinalizeStatus.Discarded => "discarded",
FinalizeStatus.AlreadyStored => "already_stored",
FinalizeStatus.GameRemoved => "game_removed",
_ => status.ToString(),
};
@@ -7,8 +7,21 @@ namespace FrameLedger.Application.Persistence;
/// </summary>
public interface ISessionRepository
{
/// <summary>
/// Writes the session under <c>session.Row.GameId</c>, in one transaction. Throws <see cref="SessionOwnerMissingException"/>
/// — never the foreign key's <c>SqliteException</c> — when that row no longer exists at the moment of the write.
/// </summary>
ValueTask<long> InsertFinalizedAsync(FinalizedSession session, CancellationToken ct = default);
/// <summary>
/// The <c>games</c> row a finishing session belongs to (2026-09-23), or null when there is none any more:
/// <paramref name="gameId"/> when that row existed before the session started or holds its executable (an id SQLite
/// reused for a later game is neither), else the row that holds <paramref name="exePath"/> — the game re-imported
/// while the session ran. Two GIRLS' FRONTLINE 2 sessions on 2026-09-22/23 died on the foreign key because their
/// entry was removed and re-imported mid-session.
/// </summary>
ValueTask<long?> ResolveOwnerAsync(long gameId, string? exePath, DateTimeOffset startedAt, CancellationToken ct = default);
ValueTask<bool> ExistsAsync(Guid sessionGuid, CancellationToken ct = default);
ValueTask<SessionRow?> FindAsync(Guid sessionGuid, CancellationToken ct = default);
@@ -0,0 +1,24 @@
namespace FrameLedger.Application.Persistence;
/// <summary>
/// The session's <c>games</c> row was deleted between the finalizer's owner lookup and its write (2026-09-23): the
/// repository checks inside the write transaction and throws this rather than letting the foreign key throw a
/// <c>SqliteException</c> the caller cannot tell from a real fault. The finalizer answers it as
/// <c>FinalizeStatus.GameRemoved</c>.
/// </summary>
public sealed class SessionOwnerMissingException : Exception
{
public SessionOwnerMissingException()
{
}
public SessionOwnerMissingException(string message)
: base(message)
{
}
public SessionOwnerMissingException(string message, Exception innerException)
: base(message, innerException)
{
}
}
@@ -19,4 +19,11 @@ public sealed record FinalizeInput
/// <summary><c>04_CAPTURE</c> §Discard rule: shorter than this is dropped. The Agent keeps the default; the unshipped host lowers it for bounded operator captures.</summary>
public TimeSpan MinimumSessionLength { get; init; } = SessionFinalizer.MinimumSessionLength;
/// <summary>
/// The normalised executable the session ran (2026-09-23): how the finalizer finds the session's row when the one it
/// started under is gone — removed while it ran, or its id reused by another game (<c>games.id</c> has no
/// AUTOINCREMENT). Null keeps the old behaviour: the skeleton's <c>GameId</c>, or nothing when that row is gone.
/// </summary>
public string? ExePath { get; init; }
}
@@ -2,6 +2,9 @@ using System.Runtime.InteropServices;
namespace FrameLedger.Application.Recording;
/// <summary>What finalizing did.</summary>
/// <summary>
/// What finalizing did. <see cref="GameId"/> is the row the session was stored under when that is known — the one it
/// started under, or the row that holds its executable's path when that one was removed while it ran (2026-09-23).
/// </summary>
[StructLayout(LayoutKind.Auto)]
public readonly record struct FinalizeOutcome(FinalizeStatus Status, long? SessionId, int RetentionSwept);
public readonly record struct FinalizeOutcome(FinalizeStatus Status, long? SessionId, int RetentionSwept, long? GameId = null);
@@ -10,4 +10,11 @@ public enum FinalizeStatus
/// <summary>A session with this guid was already stored — recovery ran after a finalize that did land.</summary>
AlreadyStored,
/// <summary>
/// No <c>games</c> row owns the session any more (2026-09-23): its entry was removed with its sessions while it ran,
/// and no row holds its executable's path either. Nothing is written; the caller deletes the <c>.partial</c> as it does
/// for <see cref="Discarded"/>. Until this value existed the insert died on the foreign key and the session FAULTED.
/// </summary>
GameRemoved,
}
@@ -19,4 +19,11 @@ public interface IPartialSessionStore
/// <summary>Removes the file; a missing file is not an error.</summary>
void Delete(Guid sessionGuid);
/// <summary>
/// Sets the file aside as <c>&lt;guid&gt;.partial.failed</c> (2026-09-23): out of <see cref="ListPending"/>, never
/// retried, kept for a bug report. What recovery does with a file it could not finalize, so that one bad file cannot
/// stop every later start. A missing file is not an error.
/// </summary>
void Quarantine(Guid sessionGuid);
}
@@ -6,9 +6,16 @@ namespace FrameLedger.Application.Recording;
/// <summary>
/// The Agent's first act at startup (<c>04_CAPTURE</c> §Session recorder: <c>Interrupted → recovered from
/// .partial</c>): every pending file becomes an <c>interrupted</c> session from its valid prefix, or is
/// dropped for one of three stated reasons — already stored, too short, unreadable. Nothing is retried,
/// nothing is left behind.
/// dropped for one of four stated reasons — already stored, too short, unreadable, its game removed. Nothing is
/// retried, nothing is left behind.
/// </summary>
/// <remarks>
/// <b>Recovery never throws (2026-09-23).</b> It runs before the watcher on every start, and the host stops on a
/// background service's exception: one file whose finalize failed — two GIRLS' FRONTLINE 2 sessions whose entry was
/// removed mid-session left exactly that — would have stopped every start from then on, and with it every capture.
/// A file that cannot be finalized is set aside (<see cref="IPartialSessionStore.Quarantine"/>) and reported as
/// <see cref="RecoveryStatus.Failed"/>; the next file is recovered.
/// </remarks>
public sealed class PartialRecovery
{
private readonly IPartialSessionStore _store;
@@ -29,14 +36,48 @@ public sealed class PartialRecovery
public async ValueTask<IReadOnlyList<RecoveryOutcome>> RecoverAsync(CancellationToken ct = default)
{
var outcomes = new List<RecoveryOutcome>();
foreach (Guid guid in _store.ListPending())
IReadOnlyList<Guid> pending;
try
{
outcomes.Add(await RecoverOneAsync(guid, ct).ConfigureAwait(false));
pending = _store.ListPending();
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
outcomes.Add(new RecoveryOutcome(Guid.Empty, RecoveryStatus.Failed, null, $"the pending files could not be listed — {ex.GetType().Name}: {ex.Message}"));
return outcomes;
}
foreach (Guid guid in pending)
{
outcomes.Add(await RecoverOrSetAsideAsync(guid, ct).ConfigureAwait(false));
}
return outcomes;
}
private async ValueTask<RecoveryOutcome> RecoverOrSetAsideAsync(Guid guid, CancellationToken ct)
{
try
{
return await RecoverOneAsync(guid, ct).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OperationCanceledException and not OutOfMemoryException)
{
string aside;
try
{
_store.Quarantine(guid);
aside = "set aside as .partial.failed";
}
catch (Exception move) when (move is IOException or UnauthorizedAccessException)
{
aside = $"and could not be set aside ({move.GetType().Name}: {move.Message}); it will be tried again at the next start";
}
return new RecoveryOutcome(guid, RecoveryStatus.Failed, null, $"{ex.GetType().Name}: {ex.Message} — {aside}");
}
}
private async ValueTask<RecoveryOutcome> RecoverOneAsync(Guid guid, CancellationToken ct)
{
PartialSession? partial = _store.Read(guid);
@@ -46,14 +87,17 @@ public sealed class PartialRecovery
return new RecoveryOutcome(guid, RecoveryStatus.Unreadable, null, "no readable header");
}
FinalizeInput input = ToInput(partial) with { MinimumSessionLength = _minimumSessionLength };
FinalizeInput input = ToInput(partial) with { MinimumSessionLength = _minimumSessionLength, ExePath = partial.Header.ExePath };
FinalizeOutcome result = await _finalizer.FinalizeAsync(input, ct).ConfigureAwait(false);
_store.Delete(guid);
return result.Status switch
{
FinalizeStatus.Saved => new RecoveryOutcome(guid, RecoveryStatus.Recovered, result.SessionId,
$"{partial.Records.Count} record(s), {partial.Sensors.Count} sensor sample(s){(partial.Truncated ? ", tail truncated" : "")}"),
$"{partial.Records.Count} record(s), {partial.Sensors.Count} sensor sample(s){(partial.Truncated ? ", tail truncated" : "")}"
+ (result.GameId is { } owner && owner != partial.Header.GameId ? $"; stored under games row {owner}, which holds {partial.Header.ExePath} now" : "")),
FinalizeStatus.AlreadyStored => new RecoveryOutcome(guid, RecoveryStatus.AlreadyStored, null, "the finalize had landed"),
FinalizeStatus.GameRemoved => new RecoveryOutcome(guid, RecoveryStatus.GameRemoved, null,
$"games row {partial.Header.GameId} is gone and no row holds {partial.Header.ExePath}: its game was removed with its sessions"),
_ => new RecoveryOutcome(guid, RecoveryStatus.Discarded, null,
$"{input.Skeleton.DurationSeconds:0.#} s is under the {input.MinimumSessionLength.TotalSeconds:0} s minimum"),
};
@@ -13,4 +13,13 @@ public enum RecoveryStatus
/// <summary>No readable header: nothing to recover, and the file is gone.</summary>
Unreadable,
/// <summary>Its game is no longer in the ledger and no row holds its executable's path: nothing written, the file is gone.</summary>
GameRemoved,
/// <summary>
/// Recovering it threw. The file is set aside as <c>&lt;guid&gt;.partial.failed</c> — kept for a bug report, never
/// retried — and recovery goes on to the next file, so one bad file can never stop the watcher from starting.
/// </summary>
Failed,
}
@@ -15,7 +15,7 @@ namespace FrameLedger.Application.Recording;
/// <b>Step 1 is the caller's</b>: the loop already asked the Overlay to stop and drained once more before
/// it let go of the ring; what arrives here is final. <b>Step 5's delete of the <c>.partial</c> is the
/// caller's too</b>, because only the caller holds the file, and it deletes only on
/// <see cref="FinalizeStatus.Saved"/> or <see cref="FinalizeStatus.Discarded"/>.
/// <see cref="FinalizeStatus.Saved"/>, <see cref="FinalizeStatus.Discarded"/> or <see cref="FinalizeStatus.GameRemoved"/>.
/// </para>
/// <para>
/// <b>Every series in <c>06_DATA_MODEL</c> is written, or is null because nothing measured it</b> — never
@@ -75,7 +75,16 @@ public sealed class SessionFinalizer
};
}
/// <summary>The discard rule, then step 5: one transaction, then the retention sweep.</summary>
/// <summary>
/// The discard rule, the owner, then step 5: one transaction, then the retention sweep.
/// </summary>
/// <remarks>
/// <b>The owner is looked up, not assumed (2026-09-23).</b> The skeleton carries the id the session started under,
/// and the entry can be removed — or removed and re-imported — while the game runs: two GIRLS' FRONTLINE 2 sessions
/// died on the foreign key that way and left their <c>.partial</c> files for a recovery that would have died the same
/// way. The session lands on the row that owns it now (<see cref="ISessionRepository.ResolveOwnerAsync"/>), and with no
/// owner it is <see cref="FinalizeStatus.GameRemoved"/>: the user removed the game with its sessions, and this was one.
/// </remarks>
public async ValueTask<FinalizeOutcome> FinalizeAsync(FinalizeInput input, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(input);
@@ -89,10 +98,26 @@ public sealed class SessionFinalizer
return new FinalizeOutcome(FinalizeStatus.AlreadyStored, null, 0);
}
FinalizedSession session = Build(input);
long id = await _sessions.InsertFinalizedAsync(session, ct).ConfigureAwait(false);
int swept = await _sessions.SweepRetentionAsync(session.Row.GameId, input.RetentionKeep, ct).ConfigureAwait(false);
return new FinalizeOutcome(FinalizeStatus.Saved, id, swept);
long? owner = await _sessions.ResolveOwnerAsync(input.Skeleton.GameId, input.ExePath, input.Skeleton.StartedAt, ct).ConfigureAwait(false);
if (owner is not { } gameId)
{
return new FinalizeOutcome(FinalizeStatus.GameRemoved, null, 0);
}
FinalizedSession session = Build(gameId == input.Skeleton.GameId ? input : input with { Skeleton = input.Skeleton with { GameId = gameId } });
long id;
try
{
id = await _sessions.InsertFinalizedAsync(session, ct).ConfigureAwait(false);
}
catch (SessionOwnerMissingException)
{
// Removed between the lookup and the write: the same answer, reached one statement later.
return new FinalizeOutcome(FinalizeStatus.GameRemoved, null, 0);
}
int swept = await _sessions.SweepRetentionAsync(gameId, input.RetentionKeep, ct).ConfigureAwait(false);
return new FinalizeOutcome(FinalizeStatus.Saved, id, swept, gameId);
}
/// <summary>The full <c>frame_blobs</c> row over every record in drained order.</summary>
@@ -157,6 +157,7 @@ public sealed class SessionRecorder : ISessionRecorder
Sensors = writer.Sensors,
RetentionKeep = options.RetentionKeep,
MinimumSessionLength = options.MinimumSessionLength,
ExePath = request.NormalisedExePath,
};
FinalizedSession built = _finalizer.Build(input);
@@ -165,18 +166,22 @@ public sealed class SessionRecorder : ISessionRecorder
writer.Dispose();
_partials.Delete(header.SessionGuid);
// The row the session was stored under (2026-09-23): the one it started with, or — when that entry was removed
// and re-imported while the game ran — the one that holds its executable now. A removed game has none, and
// neither the injection stamp nor the crash policy has a row to write to.
long ownerId = saved.GameId ?? game.Id;
CrashPolicyOutcome crash = CrashPolicyOutcome.NotAnEarlyCrash;
if (hooked)
if (hooked && saved.Status != FinalizeStatus.GameRemoved)
{
await _games.RecordInjectionAsync(game.Id, run.AttachedAt ?? header.StartedAt, ct).ConfigureAwait(false);
crash = await _crashPolicy.ApplyAsync(game.Id, exit, run.AttachedAt, endedAt, ct).ConfigureAwait(false);
await _games.RecordInjectionAsync(ownerId, run.AttachedAt ?? header.StartedAt, ct).ConfigureAwait(false);
crash = await _crashPolicy.ApplyAsync(ownerId, exit, run.AttachedAt, endedAt, ct).ConfigureAwait(false);
}
return new RecordedSession
{
SessionGuid = header.SessionGuid,
Outcome = outcome,
Row = built.Row with { Id = saved.SessionId ?? 0 },
Row = built.Row with { Id = saved.SessionId ?? 0, GameId = ownerId },
ExitStatus = exit,
Finalize = saved,
CrashPolicy = crash,
@@ -246,18 +246,23 @@ public sealed class CaptureOrchestrator
try
{
RecordedSession r = await Task.Run(() => recorder.RecordAsync(request, ct), ct).ConfigureAwait(false);
Report(r);
Report(r, Name(request));
}
catch (OperationCanceledException)
{
_log("session: cancelled before it could finalize; the .partial stays for recovery");
_log($"session {SessionId(request)}: cancelled before it could finalize; the .partial stays for recovery — {Name(request)}");
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
_log($"session: FAULTED {ex.GetType().Name}: {ex.Message}");
_log($"session {SessionId(request)}: FAULTED {ex.GetType().Name}: {ex.Message} — {Name(request)} ({request.NormalisedExePath})");
}
}
/// <summary>The game a log line is about (2026-09-23: the owner's log said "FAULTED" twice and not which game or session).</summary>
private static string Name(RecordRequest request) => request.GameName ?? Path.GetFileName(request.NormalisedExePath);
private static string SessionId(RecordRequest request) => request.SessionGuid?.ToString("N") ?? "(unnamed)";
/// <summary>Launch mode on its own task: the environment, the session, the election, each reported.</summary>
private async Task RunLaunchAsync(GameRow game, string arguments, Guid sessionGuid, CancellationToken stop, CancellationToken ct)
{
@@ -278,26 +283,26 @@ public sealed class CaptureOrchestrator
StopToken = stop,
};
RecordedSession r = await Task.Run(() => launch.Recorder.RecordAsync(request, ct), ct).ConfigureAwait(false);
Report(r);
Report(r, game.Name);
RecordedSession? elected = await ElectAfterLaunchAsync(r, ct).ConfigureAwait(false);
if (elected is not null)
{
Report(elected);
Report(elected, $"elected after {game.Name}");
}
}
catch (OperationCanceledException)
{
_log("session: cancelled before it could finalize; the .partial stays for recovery");
_log($"session {sessionGuid:N}: cancelled before it could finalize; the .partial stays for recovery — {game.Name}");
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
_log($"session: FAULTED {ex.GetType().Name}: {ex.Message}");
_log($"session {sessionGuid:N}: FAULTED {ex.GetType().Name}: {ex.Message} — {game.Name} ({game.Fingerprint.ExePath})");
}
}
private void Report(RecordedSession r) =>
_log($"session {r.SessionGuid:N}: {r.Outcome.Reason}; {r.Finalize.Status} (tier {(int)r.Row.Tier}, exit={r.ExitStatus}, frames={r.Row.FrameCount}){GuardDetail(r.Outcome)}");
private void Report(RecordedSession r, string game) =>
_log($"session {r.SessionGuid:N}: {r.Outcome.Reason}; {r.Finalize.Status} (tier {(int)r.Row.Tier}, exit={r.ExitStatus}, frames={r.Row.FrameCount}){GuardDetail(r.Outcome)} — {game}");
/// <summary>
/// What the guard said, when it said anything but a plain allow (2026-09-21). A SafetyUnhook on the owner's machine
@@ -34,6 +34,16 @@ public sealed class SqliteSessionRepository : ISessionRepository
private const string _exists = "SELECT COUNT(*) FROM sessions WHERE session_guid = @guid";
// The row a finishing session belongs to (2026-09-23; ISessionRepository.ResolveOwnerAsync). The id it started under,
// when that row predates the session or holds its executable — an id SQLite handed to a LATER game (no AUTOINCREMENT)
// is neither — and otherwise the row that holds the executable now. exe_path is COLLATE NOCASE, so '=' is too.
private const string _ownerById =
"SELECT id FROM games WHERE id = @gameId AND (added_at <= @startedAt OR (@path IS NOT NULL AND exe_path = @path))";
private const string _ownerByPath = "SELECT id FROM games WHERE exe_path = @path";
private const string _ownerExists = "SELECT COUNT(*) FROM games WHERE id = @gameId";
private const string _selectSegments =
"SELECT swapchain_id, start_frame, end_frame, render_w, render_h, output_w, output_h, upscaler, upscaler_quality, fg_mode, "
+ "native_fps, displayed_fps, p1_low_fps FROM session_segments WHERE session_id = @sessionId ORDER BY start_frame, swapchain_id";
@@ -82,6 +92,13 @@ public sealed class SqliteSessionRepository : ISessionRepository
throw new InvalidOperationException($"session {session.Row.SessionGuid:D} is already stored");
}
// Inside the write transaction, so a removal cannot slip between this and the insert (one writer): the entry
// removed while its session ran is a named outcome, not the foreign key's SqliteException (2026-09-23).
if (await c.ExecuteScalarAsync<long>(new CommandDefinition(_ownerExists, new { gameId = session.Row.GameId }, tx, cancellationToken: token)).ConfigureAwait(false) == 0)
{
throw new SessionOwnerMissingException($"session {session.Row.SessionGuid:D}: games row {session.Row.GameId} no longer exists");
}
long id = await c.ExecuteScalarAsync<long>(new CommandDefinition(
SessionRowColumns.Insert, SessionRowColumns.Parameters(session.Row), tx, cancellationToken: token)).ConfigureAwait(false);
await InsertSegmentsAsync(c, tx, id, session.Segments, token).ConfigureAwait(false);
@@ -98,6 +115,19 @@ public sealed class SqliteSessionRepository : ISessionRepository
public ValueTask<bool> ExistsAsync(Guid sessionGuid, CancellationToken ct = default) =>
_db.ReadAsync((c, token) => ExistsInAsync(c, null, sessionGuid, token), ct);
public ValueTask<long?> ResolveOwnerAsync(long gameId, string? exePath, DateTimeOffset startedAt, CancellationToken ct = default) =>
_db.ReadAsync(async (c, token) =>
{
var p = new { gameId, path = exePath, startedAt = startedAt.ToUnixTimeMilliseconds() };
long? byId = await c.ExecuteScalarAsync<long?>(new CommandDefinition(_ownerById, p, cancellationToken: token)).ConfigureAwait(false);
if (byId is not null || exePath is null)
{
return byId;
}
return await c.ExecuteScalarAsync<long?>(new CommandDefinition(_ownerByPath, p, cancellationToken: token)).ConfigureAwait(false);
}, ct);
public ValueTask<SessionRow?> FindAsync(Guid sessionGuid, CancellationToken ct = default) =>
_db.ReadAsync((c, token) => SqliteReaders.ReadOneAsync(
c,
@@ -11,6 +11,8 @@ public sealed class PartialSessionStore : IPartialSessionStore
{
private const string _extension = ".partial";
private const string _quarantined = ".failed";
public PartialSessionStore(string directory)
{
ArgumentException.ThrowIfNullOrWhiteSpace(directory);
@@ -49,5 +51,16 @@ public sealed class PartialSessionStore : IPartialSessionStore
public void Delete(Guid sessionGuid) => File.Delete(PathOf(sessionGuid));
/// <inheritdoc />
public void Quarantine(Guid sessionGuid)
{
string path = PathOf(sessionGuid);
if (File.Exists(path))
{
// "<guid>.partial.failed": its name has no Guid-shaped stem under "*.partial", so ListPending never lists it again.
File.Move(path, path + _quarantined, overwrite: true);
}
}
private string PathOf(Guid guid) => Path.Combine(Directory, guid.ToString("N", CultureInfo.InvariantCulture) + _extension);
}
@@ -22,7 +22,7 @@ internal sealed class FakePartialSessionStore : IPartialSessionStore
return entry;
}
public IReadOnlyList<Guid> ListPending() => [.. Files.Keys];
public IReadOnlyList<Guid> ListPending() => ListFailure is { } failure ? throw failure : [.. Files.Keys];
public PartialSession? Read(Guid sessionGuid) => Files.TryGetValue(sessionGuid, out Entry? e) ? e.ToSession() : null;
@@ -32,6 +32,18 @@ internal sealed class FakePartialSessionStore : IPartialSessionStore
Files.Remove(sessionGuid);
}
/// <summary>Files set aside by recovery, out of <see cref="ListPending"/> but not deleted.</summary>
public List<Guid> Quarantined { get; } = [];
/// <summary>When set, <see cref="ListPending"/> throws it (a folder recovery cannot read).</summary>
public Exception? ListFailure { get; set; }
public void Quarantine(Guid sessionGuid)
{
Quarantined.Add(sessionGuid);
Files.Remove(sessionGuid);
}
internal sealed class Entry(PartialHeader header) : IPartialSessionWriter
{
public PartialHeader Header { get; } = header;
@@ -12,8 +12,16 @@ internal sealed class FakeSessionRepository : ISessionRepository
public int SweptPerCall { get; set; }
/// <summary>When set, <see cref="InsertFinalizedAsync"/> throws it instead of storing (a write that fails).</summary>
public Exception? InsertFailure { get; set; }
public ValueTask<long> InsertFinalizedAsync(FinalizedSession session, CancellationToken ct = default)
{
if (InsertFailure is { } failure)
{
throw failure;
}
if (PreExisting.Contains(session.Row.SessionGuid) || Stored.Any(s => s.Row.SessionGuid == session.Row.SessionGuid))
{
throw new InvalidOperationException("session_guid already stored");
@@ -26,6 +34,18 @@ internal sealed class FakeSessionRepository : ISessionRepository
public ValueTask<bool> ExistsAsync(Guid sessionGuid, CancellationToken ct = default) =>
ValueTask.FromResult(PreExisting.Contains(sessionGuid) || Stored.Any(s => s.Row.SessionGuid == sessionGuid));
/// <summary>Who owns a finishing session: by default the id it started under, as if nothing had been removed.</summary>
public Func<long, string?, DateTimeOffset, long?> Owner { get; set; } = static (gameId, _, _) => gameId;
/// <summary>Every owner lookup, in order.</summary>
public List<(long GameId, string? ExePath)> OwnerLookups { get; } = [];
public ValueTask<long?> ResolveOwnerAsync(long gameId, string? exePath, DateTimeOffset startedAt, CancellationToken ct = default)
{
OwnerLookups.Add((gameId, exePath));
return ValueTask.FromResult(Owner(gameId, exePath, startedAt));
}
public ValueTask<SessionRow?> FindAsync(Guid sessionGuid, CancellationToken ct = default) =>
ValueTask.FromResult(Stored.Select(s => s.Row).FirstOrDefault(r => r.SessionGuid == sessionGuid));
@@ -116,6 +116,86 @@ public sealed class PartialRecoveryTests
repo.Stored.Single().Sensors.Should().NotBeEmpty();
}
/// <summary>A file with a minute of Tier-2 sensors: long enough to be kept if it has an owner.</summary>
private static Guid TierTwoFile(FakePartialSessionStore store, string exePath = @"C:\Games\Title\game.exe")
{
var guid = Guid.NewGuid();
var entry = (FakePartialSessionStore.Entry)store.Create(Header(guid, CaptureTier.NotHooked) with { ExePath = exePath });
entry.AppendSensors(SessionFixtures.Sensors(60).ToArray());
return guid;
}
/// <summary>
/// The owner's two GIRLS' FRONTLINE 2 files (2026-09-22 23:26, 2026-09-23 00:25): the entry was removed while the game
/// ran. Its executable's path is now held by the re-imported entry, so the session is stored there.
/// </summary>
[Fact]
public async Task AFileWhoseEntryWasRemovedAndReimportedIsStoredUnderTheRowThatHoldsItsExecutable()
{
(PartialRecovery recovery, FakePartialSessionStore store, FakeSessionRepository repo) = Make();
repo.Owner = static (_, path, _) => path is not null ? 99 : null;
Guid guid = TierTwoFile(store);
RecoveryOutcome outcome = (await recovery.RecoverAsync(TestContext.Current.CancellationToken)).Single();
outcome.Status.Should().Be(RecoveryStatus.Recovered);
outcome.Detail.Should().Contain("games row 99").And.Contain(@"C:\Games\Title\game.exe");
repo.Stored.Single().Row.GameId.Should().Be(99);
repo.OwnerLookups.Should().Equal((7L, @"C:\Games\Title\game.exe"));
store.Deleted.Should().Equal(guid);
}
[Fact]
public async Task AFileWhoseGameWasRemovedWithItsSessionsIsDroppedAndSaysWhy()
{
(PartialRecovery recovery, FakePartialSessionStore store, FakeSessionRepository repo) = Make();
repo.Owner = static (_, _, _) => null;
Guid guid = TierTwoFile(store);
RecoveryOutcome outcome = (await recovery.RecoverAsync(TestContext.Current.CancellationToken)).Single();
outcome.Status.Should().Be(RecoveryStatus.GameRemoved);
outcome.Detail.Should().Contain("games row 7").And.Contain("removed");
repo.Stored.Should().BeEmpty();
store.Deleted.Should().Equal(guid);
store.Files.Should().BeEmpty();
}
/// <summary>
/// Recovery runs before the watcher on every start, and a background service that throws stops the Agent: one file
/// that cannot be finalized must be set aside, and the next one recovered, rather than stop every start after it.
/// </summary>
[Fact]
public async Task AFileThatCannotBeFinalizedIsSetAsideAndTheNextIsStillRecovered()
{
(PartialRecovery recovery, FakePartialSessionStore store, FakeSessionRepository repo) = Make();
const string poisoned = @"C:\Games\Broken\game.exe";
repo.Owner = static (gameId, path, _) => string.Equals(path, poisoned, StringComparison.Ordinal) ? throw new InvalidOperationException("the ledger said no") : gameId;
Guid bad = TierTwoFile(store, poisoned);
Guid good = TierTwoFile(store);
IReadOnlyList<RecoveryOutcome> outcomes = await recovery.RecoverAsync(TestContext.Current.CancellationToken);
outcomes.Single(o => o.SessionGuid == bad).Status.Should().Be(RecoveryStatus.Failed);
outcomes.Single(o => o.SessionGuid == bad).Detail.Should().Contain("the ledger said no").And.Contain(".partial.failed");
outcomes.Single(o => o.SessionGuid == good).Status.Should().Be(RecoveryStatus.Recovered);
store.Quarantined.Should().Equal(bad);
store.Files.Should().BeEmpty("the bad file is set aside and the good one is stored");
repo.Stored.Should().ContainSingle();
}
[Fact]
public async Task AFolderThatCannotBeListedIsReportedNotThrown()
{
(PartialRecovery recovery, FakePartialSessionStore store, _) = Make();
store.ListFailure = new IOException("access denied");
IReadOnlyList<RecoveryOutcome> outcomes = await recovery.RecoverAsync(TestContext.Current.CancellationToken);
outcomes.Should().ContainSingle().Which.Status.Should().Be(RecoveryStatus.Failed);
outcomes[0].Detail.Should().Contain("access denied");
}
[Fact]
public async Task RecoveryIsIdempotentOnAnEmptyStore()
{
@@ -148,4 +148,52 @@ public sealed class SessionFinalizerTests
again.Status.Should().Be(FinalizeStatus.AlreadyStored, "recovery after a finalize that landed must not store the session twice");
repo.Stored.Should().ContainSingle();
}
/// <summary>
/// 2026-09-22 23:26 and 2026-09-23 00:25 on the owner's machine: a GIRLS' FRONTLINE 2 session's entry was removed
/// while it ran, and the insert died on the foreign key ("FAULTED SqliteException … FOREIGN KEY constraint failed").
/// With no row left for the session, that is an outcome with a name, and nothing is written.
/// </summary>
[Fact]
public async Task ASessionWhoseGameWasRemovedWhileItRanIsNotWrittenAndSaysSo()
{
(SessionFinalizer finalizer, FakeSessionRepository repo) = Make();
repo.Owner = static (_, _, _) => null;
var input = new FinalizeInput { Skeleton = SessionFixtures.Skeleton(), ExePath = @"D:\SteamLibrary\steamapps\common\GF2\GF2_Exilium.exe" };
FinalizeOutcome outcome = await finalizer.FinalizeAsync(input, TestContext.Current.CancellationToken);
outcome.Status.Should().Be(FinalizeStatus.GameRemoved);
outcome.SessionId.Should().BeNull();
repo.Stored.Should().BeEmpty();
repo.Sweeps.Should().BeEmpty();
repo.OwnerLookups.Should().Equal((7L, @"D:\SteamLibrary\steamapps\common\GF2\GF2_Exilium.exe"));
}
[Fact]
public async Task ASessionWhoseEntryWasReimportedIsStoredUnderTheRowThatHoldsItsExecutableNow()
{
(SessionFinalizer finalizer, FakeSessionRepository repo) = Make();
repo.Owner = static (_, path, _) => path is null ? null : 42;
var input = new FinalizeInput { Skeleton = SessionFixtures.Skeleton(), ExePath = @"D:\Games\Title\game.exe", RetentionKeep = 5 };
FinalizeOutcome outcome = await finalizer.FinalizeAsync(input, TestContext.Current.CancellationToken);
outcome.Status.Should().Be(FinalizeStatus.Saved);
outcome.GameId.Should().Be(42, "the row that holds the session's executable now");
repo.Stored.Should().ContainSingle().Which.Row.GameId.Should().Be(42);
repo.Sweeps.Should().Equal((42L, 5));
}
[Fact]
public async Task ARemovalBetweenTheLookupAndTheWriteIsTheSameAnswer()
{
(SessionFinalizer finalizer, FakeSessionRepository repo) = Make();
repo.InsertFailure = new SessionOwnerMissingException("games row 7 no longer exists");
FinalizeOutcome outcome = await finalizer.FinalizeAsync(new FinalizeInput { Skeleton = SessionFixtures.Skeleton() }, TestContext.Current.CancellationToken);
outcome.Status.Should().Be(FinalizeStatus.GameRemoved, "the write transaction's own check, not the foreign key");
repo.Sweeps.Should().BeEmpty();
}
}
@@ -389,6 +389,43 @@ public sealed class SessionRecorderTests : IAsyncDisposable
first.Row.CaptureNotes.Should().Contain("exit_code=-1073741819");
}
/// <summary>
/// 2026-09-23 00:24–00:25 on the owner's machine: GIRLS' FRONTLINE 2's entry was removed and re-imported while its
/// session ran, and the finalize died on the foreign key ("session: FAULTED … FOREIGN KEY constraint failed"), leaving
/// a <c>.partial</c> that would have stopped the next start. The session lands on the row that holds its executable now,
/// and the injection stamp follows it there.
/// </summary>
[Fact]
public async Task AnEntryRemovedAndReimportedMidSessionGetsTheSessionAndTheInjectionStamp()
{
Harness h = await MakeAsync();
h.Sessions.Owner = static (_, path, _) => string.Equals(path, _exe, StringComparison.OrdinalIgnoreCase) ? 42 : null;
RecordedSession r = await h.Recorder.RecordAsync(Request(), TestContext.Current.CancellationToken);
r.Finalize.Status.Should().Be(FinalizeStatus.Saved);
r.Finalize.GameId.Should().Be(42);
r.Row.GameId.Should().Be(42);
h.Sessions.Stored.Single().Row.GameId.Should().Be(42);
h.Games.Injections.Should().ContainSingle().Which.GameId.Should().Be(42, "the stamp goes to the row that owns the session now");
h.Partials.Files.Should().BeEmpty();
}
[Fact]
public async Task AnEntryRemovedWithItsSessionsMidSessionEndsAsGameRemovedAndLeavesNoPartial()
{
Harness h = await MakeAsync();
h.Sessions.Owner = static (_, _, _) => null;
RecordedSession r = await h.Recorder.RecordAsync(Request(), TestContext.Current.CancellationToken);
r.Finalize.Status.Should().Be(FinalizeStatus.GameRemoved, "the user removed the game and its sessions; this was one of them");
h.Sessions.Stored.Should().BeEmpty();
h.Games.Injections.Should().BeEmpty("there is no row to stamp");
h.Partials.Files.Should().BeEmpty("nothing is left for a recovery that would only reach the same answer");
h.Partials.Deleted.Should().Equal(r.SessionGuid);
}
[Fact]
public async Task WithoutAPollerTheSessionStillRecordsAndTheDescriptorIsNull()
{
@@ -127,6 +127,25 @@ public sealed class CaptureOrchestratorTests
o.RunningSessions.Should().Be(0);
}
/// <summary>
/// The owner's log on 2026-09-22 23:26 and 2026-09-23 00:25 read "session: FAULTED SqliteException: …" and nothing
/// about which session or which game; it took the UI log's import line to find out it was GIRLS' FRONTLINE 2.
/// </summary>
[Fact]
public async Task AFaultedSessionIsLoggedWithItsGuidItsGameAndItsPath()
{
(CaptureOrchestrator o, FakeRecorder recorder, FakeSnapshots processes, List<string> log) = await BuildAsync().ConfigureAwait(true);
processes.Processes.Add(new ProcessSnapshot(7, 1, "game.exe", _game, DateTimeOffset.UnixEpoch));
await o.PollOnceAsync(TestContext.Current.CancellationToken).ConfigureAwait(true);
await WaitForRequestsAsync(recorder, 1).ConfigureAwait(true);
recorder.Pending[0].SetException(new InvalidOperationException("the ledger said no"));
await WaitUntilAsync(() => log.Exists(l => l.Contains("FAULTED", StringComparison.Ordinal))).ConfigureAwait(true);
string line = log.Single(l => l.Contains("FAULTED", StringComparison.Ordinal));
line.Should().Contain(recorder.Requests[0].SessionGuid!.Value.ToString("N")).And.Contain("Title").And.Contain(_game).And.Contain("the ledger said no");
}
[Fact]
public async Task StopSessionCancelsTheRequestsOwnStopTokenAndNothingElse()
{
@@ -174,6 +174,49 @@ public sealed class SqliteSessionRepositoryTests
await again.Should().ThrowAsync<InvalidOperationException>("the recovery path asks ExistsAsync first, and the store refuses regardless");
}
/// <summary>
/// 2026-09-22/23: two GIRLS' FRONTLINE 2 sessions died on the foreign key because their entry was removed (and then
/// re-imported) while they ran. The write now names that case instead of surfacing SQLite's constraint error.
/// </summary>
[Fact]
public async Task AWriteForAGameThatIsGoneSaysSoInsteadOfFailingTheForeignKey()
{
await using LedgerFixture f = await LedgerFixture.OpenAsync();
(long gameId, long snapshotId) = await SeedAsync(f);
var repo = new SqliteSessionRepository(f.Db);
SessionRow row = Row(gameId + 1000, snapshotId);
Func<Task> insert = async () => await repo.InsertFinalizedAsync(new FinalizedSession { Row = row }, Ct).ConfigureAwait(false);
await insert.Should().ThrowAsync<SessionOwnerMissingException>();
(await repo.ExistsAsync(row.SessionGuid, Ct)).Should().BeFalse();
}
[Fact]
public async Task TheOwnerIsTheRowItStartedUnderElseTheRowHoldingItsExecutableElseNone()
{
await using LedgerFixture f = await LedgerFixture.OpenAsync();
var games = new SqliteGameRepository(f.Db);
var repo = new SqliteSessionRepository(f.Db);
GameRow original = await games.EnsureAsync(_game, "T", Ct);
DateTimeOffset afterOriginal = original.AddedAt.AddSeconds(1);
// The row it started under, still there — or repointed while it ran (Change executable, a moved drive).
(await repo.ResolveOwnerAsync(original.Id, _game.ExePath, afterOriginal, Ct)).Should().Be(original.Id);
(await repo.ResolveOwnerAsync(original.Id, @"C:\Games\T\before-the-change.exe", afterOriginal, Ct)).Should().Be(original.Id);
// Gone, and its executable held by a re-imported row: that row, whatever the path's case.
(await repo.ResolveOwnerAsync(original.Id + 1000, _game.ExePath.ToUpperInvariant(), afterOriginal, Ct)).Should().Be(original.Id);
// An id SQLite handed to a LATER game with another executable is not the session's game (no AUTOINCREMENT).
GameRow later = await games.EnsureAsync(new ExecutableFingerprint { ExePath = @"C:\Games\Other\o.exe", SizeBytes = 3, MtimeUnixMs = 4 }, "O", Ct);
(await repo.ResolveOwnerAsync(later.Id, @"C:\Games\Removed\r.exe", later.AddedAt.AddSeconds(-1), Ct)).Should().BeNull();
// Gone with nothing at its path, and a caller that knows no path: no owner.
(await repo.ResolveOwnerAsync(original.Id + 1000, @"C:\Games\Removed\r.exe", afterOriginal, Ct)).Should().BeNull();
(await repo.ResolveOwnerAsync(original.Id + 1000, null, afterOriginal, Ct)).Should().BeNull();
}
[Fact]
public async Task RetentionKeepsTheLastNSessionsRawSeriesAndEveryAggregate()
{
@@ -54,4 +54,23 @@ public sealed class PartialSessionStoreTests : IDisposable
store.Delete(a);
store.ListPending().Should().Equal(b);
}
/// <summary>A file recovery could not finalize is kept for a bug report and never listed again (2026-09-23).</summary>
[Fact]
public void AQuarantinedFileIsKeptBesideTheOthersAndNeverListedAgain()
{
var store = new PartialSessionStore(Path.Combine(_dir, "tmp"));
var bad = Guid.NewGuid();
var good = Guid.NewGuid();
store.Create(Header(bad)).Dispose();
store.Create(Header(good)).Dispose();
store.Quarantine(bad);
store.Quarantine(bad);
store.Quarantine(Guid.NewGuid());
store.ListPending().Should().Equal(good);
store.Read(bad).Should().BeNull("it is no longer a pending file");
File.Exists(Path.Combine(store.Directory, bad.ToString("N") + ".partial.failed")).Should().BeTrue("kept, for a bug report");
}
}