Compare commits

...
Author SHA1 Message Date
poli0981andClaude Opus 5.5 ba918f4fab fix(watch): a game started again while its last session finalizes is recorded when that session ends (beta.15 PR-3)
From the beta.14 audit (chip, folded into beta.15 by the owner). CaptureOrchestrator.Start turned a process away while a
session for its executable was still running ("one at a time"), and ProcessWatcher reports a pid once - so a game
started again during the previous session's finalize (driver profile up to 5 s, a crash reporter waited for up to
2.5 s, the transaction) never got a session. Verified on the code first: path (b), dropped, never picked up.

- The newest turned-away process per executable is remembered (Deferred: the event and the process's start time) and
  started from Reap when that session ends - if the session ended on its own (RunAndReportAsync records the result; a
  cancelled or faulted one starts nothing), the process is the same one (pid and start time) and it is then the
  executable's ONLY process. A helper of a multi-process game (NW.js, Electron) still has the game beside it, so it stays
  turned away, as before.
- The start happens outside the table's lock; the log says "recording it now".

Tests (CaptureOrchestratorTests, FakeRecorder.Pending holding finalize open): the restart is recorded when the session
ends (red before: one request), a helper of a game still running is not, a process that left meanwhile is not. The
existing one-at-a-time test keeps its behaviour.

Docs: 04_CAPTURE §Process watcher, HANDOFF trap, CHANGELOG.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 07:46:33 +07:00
5 changed files with 165 additions and 10 deletions

No files matched your search

+4
View File
@@ -30,6 +30,10 @@ numeric core and does not move; the heading is the full version — corrected 20
### Fixed
- **A game started again within a few seconds of closing was not recorded**: while FrameLedger was still saving the
session that had just ended, the new start was turned away ("one session at a time") and never looked at again. It is
recorded now, as soon as the session before it is saved — unless the game's other processes are still running beside
it, as a multi-process game's helpers are.
- **A game started through its launcher was never followed to the game itself** (the Agent's `--console launch`): when
the launcher exited or never drew a frame, FrameLedger was to find the game the launcher had started and record it, and
it never did — the launcher's process id was not passed on, so the search stopped before it began. It is passed on now,
+7 -1
View File
@@ -154,7 +154,13 @@ which makes the notification more important than it was, not less.
> row's path with its drive letter changed (an RPG Maker `Game.exe` has the same bytes in every game); and the
> running-session table is keyed by the executable's path, so a re-imported or merged entry's new id cannot start a
> second session for the same executable. The launch election registers its session there too, and skips a child the
> watcher already records. **Behaviour change:** a game whose folder moved (not its drive letter) records nothing until
> watcher already records. *(beta.15, 2026-10-06:)* a process turned away by that rule — "one at a time" — was never
> recorded, because the watcher reports a pid once: **a game started again while its last session was still finalizing**
> (the driver profile, a crash reporter waited for, the transaction — seconds) got no session at all. The orchestrator
> now remembers the newest such process per executable and starts its session when the running one ends, if that one
> ended on its own (not cancelled with the host), the process is the same (pid and start time) and it is then the
> executable's ONLY process — a helper of a game still running has the game beside it and stays turned away, as before
> (`CaptureOrchestratorTests`: the restart recorded, the helper not, a process that left meanwhile not). **Behaviour change:** a game whose folder moved (not its drive letter) records nothing until
> *Change executable* points its entry at the new file. `ProcessTree` reads ppid chains with the one rule that defeats pid
> reuse: a child that started before its parent is not its child. `DescendantElection` picks the newest-started
> descendant whose image is tracked — a launcher's consent does not extend to what it spawns, so the elected image
+3 -1
View File
@@ -1558,7 +1558,9 @@ và legal"), so the Legal Gate shows both once.
**Traps.**
- **A pid the watcher matched stays matched.** Switching recording off stops the session but leaves the process in
`ProcessWatcher`'s table, so switching it back on while the same process still runs starts nothing until it restarts.
A process the watcher never matched (off from the start) is picked up by the next poll.
A process the watcher never matched (off from the start) is picked up by the next poll. *(beta.15: one case of this is
fixed — a process turned away because its executable's session was still running is remembered and recorded when that
session ends, if it is then the executable's only process; 04_CAPTURE §Process watcher.)*
- **A migration that changes data needs its own rewind in a test.** `RewindSchemaAsync` leaves columns in place, so
`ScriptNineAddsTheRecordingSwitchOffForSteamToolsOnly` drops the column itself before re-applying 0009.
- **`SqliteGameRepository._columns` is read by ordinal** (`ReadMore`): a new column goes at the end of the list, and the
@@ -72,6 +72,11 @@ public sealed class CaptureOrchestrator
// not an entry's, and a launch that spawns five of them is said once.
private readonly Dictionary<int, string> _declined = [];
// beta.15: a process of an executable whose session was still running — often still FINALIZING — when it appeared:
// a game started again at once. The watcher reports a pid once, so until beta.15 it was never recorded. The newest one
// per executable is kept here, under the table's lock, and started when that session ends (Reap).
private readonly Dictionary<string, Deferred> _deferred = new(StringComparer.OrdinalIgnoreCase);
public CaptureOrchestrator(ISessionRecorder recorder, IGameRepository games, IProcessSnapshotSource processes,
IExecutableIdentitySource identity, OrchestratorOptions options, Action<string> log, ILaunchRecorderFactory? launches = null,
ExecutableRelocator? relocator = null, LatestProcessSnapshot? latest = null, CrashReporterWitness? reporters = null)
@@ -158,12 +163,12 @@ public sealed class CaptureOrchestrator
switch (e)
{
case TrackedProcessAppeared { StalePath: false } appeared:
Start(appeared, ct);
Start(appeared, StartedAt(snapshot, appeared.Pid), ct);
break;
case TrackedProcessAppeared nameOnly:
if (await AdoptIfMovedAsync(nameOnly, ct).ConfigureAwait(false) is { } adopted)
{
Start(adopted, ct);
Start(adopted, StartedAt(snapshot, adopted.Pid), ct);
}
else
{
@@ -183,10 +188,23 @@ public sealed class CaptureOrchestrator
}
}
Reap();
Reap(snapshot, ct);
return events;
}
private static DateTimeOffset? StartedAt(IReadOnlyList<ProcessSnapshot> snapshot, int pid)
{
foreach (ProcessSnapshot p in snapshot)
{
if (p.Pid == pid)
{
return p.StartedAt;
}
}
return null;
}
/// <summary>The entries FrameLedger watches for: the library minus those whose recording the user switched off.</summary>
private static List<GameRow> Recorded(IReadOnlyList<GameRow> library) => [.. library.Where(static g => g.RecordSessions)];
@@ -367,30 +385,33 @@ public sealed class CaptureOrchestrator
}
}
private void Start(TrackedProcessAppeared appeared, CancellationToken ct)
private void Start(TrackedProcessAppeared appeared, DateTimeOffset? startedAt, CancellationToken ct)
{
lock (_table)
{
if (_running.TryGetValue(appeared.ImagePath, out Running? current) && !current.Task.IsCompleted)
{
_log($"watch: pid {appeared.Pid} ({appeared.Game.Name}) appeared while a session for that executable is running; one at a time");
_deferred[appeared.ImagePath] = new Deferred(appeared, startedAt);
_log($"watch: pid {appeared.Pid} ({appeared.Game.Name}) appeared while a session for that executable is running; one at a time"
+ " - it is recorded when that session ends, if it is then the executable's only process");
return;
}
_log($"watch: pid {appeared.Pid} ({appeared.Game.Name}) appeared; starting a session");
var running = new Running(Guid.NewGuid(), appeared.Game.Id);
RecordRequest request = Attach(appeared.ImagePath, appeared.Game.Name, running.SessionGuid, running.Stop.Token);
running.Task = RunAndReportAsync(_recorder, request, ct);
running.Task = RunAndReportAsync(_recorder, request, running, ct);
_running[appeared.ImagePath] = running;
}
}
/// <summary>The session on its own task, reporting its own end; nothing else awaits a stored task.</summary>
private async Task RunAndReportAsync(ISessionRecorder recorder, RecordRequest request, CancellationToken ct)
private async Task RunAndReportAsync(ISessionRecorder recorder, RecordRequest request, Running? running, CancellationToken ct)
{
try
{
RecordedSession r = await Task.Run(() => recorder.RecordAsync(request, ct), ct).ConfigureAwait(false);
running?.Recorded = r;
Report(r, Name(request));
}
catch (OperationCanceledException)
@@ -481,8 +502,9 @@ public sealed class CaptureOrchestrator
};
}
private void Reap()
private void Reap(IReadOnlyList<ProcessSnapshot> snapshot, CancellationToken ct)
{
var restarts = new List<Deferred>();
lock (_table)
{
foreach ((string path, Running running) in _running.ToArray())
@@ -490,10 +512,21 @@ public sealed class CaptureOrchestrator
if (running.Task.IsCompleted)
{
_running.Remove(path);
if (_deferred.Remove(path, out Deferred? deferred) && deferred.StartsAfter(running, snapshot))
{
restarts.Add(deferred);
}
running.Dispose();
}
}
}
foreach (Deferred d in restarts)
{
_log($"watch: pid {d.Appeared.Pid} ({d.Appeared.Game.Name}) started while the last session of its executable was ending; recording it now");
Start(d.Appeared, d.StartedAt, ct);
}
}
private async Task DrainRunningAsync()
@@ -512,6 +545,27 @@ public sealed class CaptureOrchestrator
}
}
/// <summary>
/// A process turned away because its executable's session was running (beta.15). It is recorded when that session ends
/// only if the session ended on its own (a cancelled or faulted one — the host stopping — starts nothing), the process
/// is still the same one (pid and start time), and it is then the executable's ONLY process: a game started again has
/// replaced the old one, where a helper of a multi-process game (NW.js, Electron — one executable, many processes)
/// still has the game beside it, or several of its kind.
/// </summary>
private sealed record Deferred(TrackedProcessAppeared Appeared, DateTimeOffset? StartedAt)
{
public bool StartsAfter(Running ended, IReadOnlyList<ProcessSnapshot> snapshot)
{
if (ended.Recorded is null)
{
return false;
}
ProcessSnapshot[] same = [.. snapshot.Where(p => p.ImagePath is { } image && string.Equals(image, Appeared.ImagePath, StringComparison.OrdinalIgnoreCase))];
return same.Length == 1 && same[0].Pid == Appeared.Pid && (StartedAt is null || same[0].StartedAt == StartedAt);
}
}
/// <summary>One started session: its guid (chosen here, so the stop is addressable), its entry, its task, its stop token.</summary>
private sealed class Running(Guid sessionGuid, long gameId) : IDisposable
{
@@ -524,6 +578,9 @@ public sealed class CaptureOrchestrator
public Task Task { get; set; } = System.Threading.Tasks.Task.CompletedTask;
/// <summary>The session as recorded; null until it ended, and for one cancelled or faulted. Written before <see cref="Task"/> completes.</summary>
public RecordedSession? Recorded { get; set; }
public void Dispose() => Stop.Dispose();
}
}
@@ -439,6 +439,92 @@ public sealed class CaptureOrchestratorTests
log.Should().Contain(l => l.Contains("one at a time", StringComparison.Ordinal));
}
/// <summary>A session that ended because its game exited, as the recorder reports it.</summary>
private static RecordedSession GameExited(int targetPid) => new()
{
SessionGuid = Guid.NewGuid(),
Outcome = new CaptureOutcome { Reason = SessionEndReason.TargetExited, TargetPid = targetPid },
Row = SessionFixtures.Skeleton(),
ExitStatus = ExitStatus.Normal,
Finalize = new FinalizeOutcome(FinalizeStatus.Saved, 1, 0),
CrashPolicy = CrashPolicyOutcome.NotAnEarlyCrash,
CrashEventFound = false,
};
/// <summary>
/// beta.15: a game started again while its last session was still finalizing — the driver profile, a crash reporter
/// waited for, the transaction — was turned away once ("one at a time") and, the watcher reporting a pid once, never
/// recorded. It is recorded when that session ends, being then the executable's only process.
/// </summary>
[Fact]
public async Task AGameStartedAgainWhileItsLastSessionFinalizesIsRecordedWhenThatSessionEnds()
{
(CaptureOrchestrator o, FakeRecorder recorder, FakeSnapshots processes, List<string> log) = await BuildAsync().ConfigureAwait(true);
CancellationToken ct = TestContext.Current.CancellationToken;
processes.Processes.Add(new ProcessSnapshot(1, 1, "game.exe", _game, DateTimeOffset.UnixEpoch));
await o.PollOnceAsync(ct).ConfigureAwait(true);
await WaitForRequestsAsync(recorder, 1).ConfigureAwait(true);
// The game exits and starts again while the session is still being finalized (the fake holds it open).
processes.Processes.Clear();
processes.Processes.Add(new ProcessSnapshot(2, 1, "game.exe", _game, DateTimeOffset.UnixEpoch.AddMinutes(30)));
await o.PollOnceAsync(ct).ConfigureAwait(true);
recorder.Requests.Should().HaveCount(1, "one session per executable at a time");
recorder.Pending[0].SetResult(GameExited(targetPid: 1));
await WaitUntilAsync(() => o.RunningSessions == 0).ConfigureAwait(true);
await o.PollOnceAsync(ct).ConfigureAwait(true);
await WaitForRequestsAsync(recorder, 2).ConfigureAwait(true);
recorder.Requests.Should().HaveCount(2, "the game started again is recorded once the session before it has ended");
log.Should().Contain(l => l.Contains("recording it now", StringComparison.Ordinal));
}
/// <summary>
/// A helper of a game that is still running (one executable, many processes — NW.js, Electron) is turned away as before
/// and stays turned away when the session ends: the game is still beside it, so it is not a game started again.
/// </summary>
[Fact]
public async Task AHelperOfAGameStillRunningIsNotRecordedWhenTheSessionEnds()
{
(CaptureOrchestrator o, FakeRecorder recorder, FakeSnapshots processes, _) = await BuildAsync().ConfigureAwait(true);
CancellationToken ct = TestContext.Current.CancellationToken;
processes.Processes.Add(new ProcessSnapshot(1, 1, "game.exe", _game, DateTimeOffset.UnixEpoch));
await o.PollOnceAsync(ct).ConfigureAwait(true);
await WaitForRequestsAsync(recorder, 1).ConfigureAwait(true);
processes.Processes.Add(new ProcessSnapshot(3, 1, "game.exe", _game, DateTimeOffset.UnixEpoch.AddSeconds(5)));
await o.PollOnceAsync(ct).ConfigureAwait(true);
// The session ends (the user stopped it, say) while the game and its helper both still run.
recorder.Pending[0].SetResult(GameExited(targetPid: 1));
await WaitUntilAsync(() => o.RunningSessions == 0).ConfigureAwait(true);
await o.PollOnceAsync(ct).ConfigureAwait(true);
await o.PollOnceAsync(ct).ConfigureAwait(true);
recorder.Requests.Should().ContainSingle("two processes of the executable still run: the helper is not a game started again");
}
/// <summary>The process turned away has gone by the time the session ends: nothing to record, nothing started.</summary>
[Fact]
public async Task AProcessThatLeftBeforeTheSessionEndedStartsNothing()
{
(CaptureOrchestrator o, FakeRecorder recorder, FakeSnapshots processes, _) = await BuildAsync().ConfigureAwait(true);
CancellationToken ct = TestContext.Current.CancellationToken;
processes.Processes.Add(new ProcessSnapshot(1, 1, "game.exe", _game, DateTimeOffset.UnixEpoch));
await o.PollOnceAsync(ct).ConfigureAwait(true);
await WaitForRequestsAsync(recorder, 1).ConfigureAwait(true);
processes.Processes.Clear();
processes.Processes.Add(new ProcessSnapshot(2, 1, "game.exe", _game, DateTimeOffset.UnixEpoch.AddMinutes(30)));
await o.PollOnceAsync(ct).ConfigureAwait(true);
processes.Processes.Clear();
recorder.Pending[0].SetResult(GameExited(targetPid: 1));
await WaitUntilAsync(() => o.RunningSessions == 0).ConfigureAwait(true);
await o.PollOnceAsync(ct).ConfigureAwait(true);
recorder.Requests.Should().ContainSingle();
}
private static RecordedSession LauncherExited(int launcherPid) => new()
{
SessionGuid = Guid.NewGuid(),