acdream/tests/AcDream.Launcher.Core.Tests/Status/StatusFileTailerTests.cs
Erik 26feba8186 fix(launcher): Campaign LA LA3 review fixes — contract paths omission, probe composition, graceful stop, hygiene
Opus review of LA3 returned FIX FIRST; this addresses every finding in
scope (F1-F5, F7-F12; F6 CI-lane addition excluded per instructions):

- F1 (CRITICAL): SessionProcessSettings.Paths is now nullable and left
  null by SessionConfigComposer unless a caller supplies overrides, so
  the JSON key is entirely absent instead of "paths":{} — the App-side
  loader's strict UnmappedMemberHandling.Disallow would otherwise reject
  every gui/guiSelect session-config document at load.
- F2: added SessionConfigComposer.ComposeProbe and a nullable
  SessionDescriptor.Mode field ("probe", omitted for normal play) per
  the pinned contract — no character/policy/plugins/loginCommands.
- F3: LauncherProcessSupervisor.Stop now tries
  ILauncherChildProcess.TryRequestGracefulStop (Linux: libc SIGINT via
  LibraryImport, K4-proven graceful headless logout) before
  CloseMainWindow. Windows has no reliable no-window-console equivalent
  today; filed docs/ISSUES.md #397 with the CREATE_NEW_PROCESS_GROUP +
  CTRL_BREAK fix direction. Stop()'s blocking-timeout contract is now
  documented for LA4.
- F4: LauncherProfileStore.Save chmods the Linux temp file to 0600
  immediately after creation, before any credential is serialized;
  failure paths and Load() clean up a stale .tmp.
- F5: added LauncherCoreDependencyBoundaryTests asserting Launcher.Core
  references exactly AcDream.Platform and no packages.
- F7: StatusEventParser.Parse no longer throws on a whitespace/null
  line; StatusFileTailer.ReadNewEvents swallows the File.Exists/open
  TOCTOU window (FileNotFoundException/DirectoryNotFoundException/
  IOException) instead of throwing.
- F8: Start() now kills (entire process tree) and disposes a child that
  started successfully but failed while being fed its stdin password,
  instead of orphaning it.
- F9: SetState is monotonic — once Exited, no later transition applies
  or fires StateChanged, closing a Start()-path race where a
  synchronously-exiting child could be "resurrected" to Running.
- F10: CharacterIdFormat.TryParse now requires the "0x" prefix (an
  unprefixed hand-typed decimal id is also valid hex and was silently
  misread); a parsed id of 0 is treated as unusable and falls back to
  the name selector; LauncherProfileStore.MergeRoster normalizes both
  sides through TryParse/ToHexString instead of raw string equality, so
  a legacy unprefixed-hex row self-heals via name match instead of
  duplicating.
- F11: StatusCharacterEntry.SecondsGreyedOut is now uint, matching
  CharacterRosterEntry and the host writer.
- F12: added MalformedStatusEvent, returned for a recognized `e` whose
  payload doesn't match its shape, distinguished from UnknownStatusEvent
  (an unrecognized `e`).

AllowUnsafeBlocks was added to AcDream.Launcher.Core.csproj — required
by the LibraryImport source generator's function-pointer marshalling
stub for F3's Linux SIGINT P/Invoke.

Verification: dotnet build AcDream.slnx -c Release green (0 errors);
dotnet test tests/AcDream.Launcher.Core.Tests -c Release green at 94/94
on native Windows and under WSL (Ubuntu, verified across multiple runs
for the timing-sensitive SIGINT/sharing-violation tests, no flakes
observed).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-14 16:29:39 +02:00

199 lines
6.7 KiB
C#

using System.Text;
using AcDream.Launcher.Core.Status;
namespace AcDream.Launcher.Core.Tests.Status;
public sealed class StatusFileTailerTests : IDisposable
{
private readonly string _root;
private readonly string _path;
public StatusFileTailerTests()
{
_root = Path.Combine(
Path.GetTempPath(),
"acdream-launcher-tailer-tests",
Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(_root);
_path = Path.Combine(_root, "status.jsonl");
}
public void Dispose()
{
if (Directory.Exists(_root))
{
Directory.Delete(_root, recursive: true);
}
}
[Fact]
public void ReturnsNoEventsWhenTheFileDoesNotExistYet()
{
var tailer = new StatusFileTailer(_path);
IReadOnlyList<StatusEvent> events = tailer.ReadNewEvents();
Assert.Empty(events);
}
[Fact]
public void ReturnsNoEventsWhenNothingHasBeenAppendedSinceTheLastPoll()
{
AppendShared(Line("started", "s1"));
var tailer = new StatusFileTailer(_path);
Assert.Single(tailer.ReadNewEvents());
IReadOnlyList<StatusEvent> events = tailer.ReadNewEvents();
Assert.Empty(events);
}
[Fact]
public void ReadsMultipleCompleteLinesInOnePoll()
{
AppendShared(Line("started", "s1") + Line("connected", "s1"));
var tailer = new StatusFileTailer(_path);
IReadOnlyList<StatusEvent> events = tailer.ReadNewEvents();
Assert.Equal(2, events.Count);
Assert.IsType<StartedStatusEvent>(events[0]);
Assert.IsType<ConnectedStatusEvent>(events[1]);
}
[Fact]
public void TolerateAPartialLastLineAndCompletesItOnALaterPoll()
{
string full = Line("started", "s1");
int splitAt = full.Length - 10; // cut mid-object, before the closing brace/newline
AppendShared(full[..splitAt]);
var tailer = new StatusFileTailer(_path);
IReadOnlyList<StatusEvent> firstPoll = tailer.ReadNewEvents();
Assert.Empty(firstPoll);
AppendShared(full[splitAt..]);
IReadOnlyList<StatusEvent> secondPoll = tailer.ReadNewEvents();
StatusEvent onlyEvent = Assert.Single(secondPoll);
Assert.IsType<StartedStatusEvent>(onlyEvent);
}
[Fact]
public void APartialLineFollowedByAFullLineOnlyEmitsTheCompleteOne()
{
AppendShared(Line("started", "s1"));
string partial = """{"v":1,"e":"connected","t":"2026-08-14T12:00:00Z","sessionId":"s1"""; // no closing
AppendShared(partial);
var tailer = new StatusFileTailer(_path);
IReadOnlyList<StatusEvent> events = tailer.ReadNewEvents();
StatusEvent onlyEvent = Assert.Single(events);
Assert.IsType<StartedStatusEvent>(onlyEvent);
// Completing the second line on a later poll produces exactly
// one more event, proving the partial bytes were retained (not
// dropped and not double-counted).
AppendShared("\"}\n");
IReadOnlyList<StatusEvent> secondPoll = tailer.ReadNewEvents();
StatusEvent completed = Assert.Single(secondPoll);
Assert.IsType<ConnectedStatusEvent>(completed);
}
[Fact]
public void SkipsBlankLines()
{
AppendShared("\n" + Line("started", "s1") + "\n" + Line("connected", "s1"));
var tailer = new StatusFileTailer(_path);
IReadOnlyList<StatusEvent> events = tailer.ReadNewEvents();
Assert.Equal(2, events.Count);
}
[Fact]
public void ReadsWithAWriterHoldingTheFileOpenForAppend()
{
// Share-tolerant reads: the writer's handle stays open the whole
// time (FileShare.ReadWrite on both sides), matching a live host
// process appending status.jsonl while the launcher tails it.
using var writer = new FileStream(
_path,
FileMode.Create,
FileAccess.Write,
FileShare.ReadWrite | FileShare.Delete);
var tailer = new StatusFileTailer(_path);
byte[] first = Encoding.UTF8.GetBytes(Line("started", "s1"));
writer.Write(first, 0, first.Length);
writer.Flush();
IReadOnlyList<StatusEvent> firstPoll = tailer.ReadNewEvents();
Assert.Single(firstPoll);
byte[] second = Encoding.UTF8.GetBytes(Line("connected", "s1"));
writer.Write(second, 0, second.Length);
writer.Flush();
IReadOnlyList<StatusEvent> secondPoll = tailer.ReadNewEvents();
Assert.Single(secondPoll);
Assert.IsType<ConnectedStatusEvent>(secondPoll[0]);
}
[Fact]
public void ReadNewEventsReturnsEmptyRatherThanThrowingOnASharingViolation()
{
// A deterministic proxy for the File.Exists -> new FileStream
// TOCTOU window (review finding F7): Windows enforces FileShare
// at the OS level, so holding an exclusive (FileShare.None)
// handle open while the tailer tries to open the same path
// reliably reproduces the IOException the tailer must now
// swallow instead of throwing out of a method documented never
// to throw. (.NET's FileStream doesn't apply mandatory locking
// on Linux by default, so this specific scenario isn't
// reproducible there — the fix itself is platform-agnostic, only
// this particular deterministic trigger is Windows-only.)
if (!OperatingSystem.IsWindows())
return;
AppendShared(Line("started", "s1"));
using var exclusiveHandle = new FileStream(
_path, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
var tailer = new StatusFileTailer(_path);
IReadOnlyList<StatusEvent> events = tailer.ReadNewEvents();
Assert.Empty(events);
}
[Fact]
public void RestartsFromTheTopWhenTheFileIsTruncatedOrReplaced()
{
AppendShared(Line("started", "s1") + Line("connected", "s1"));
var tailer = new StatusFileTailer(_path);
Assert.Equal(2, tailer.ReadNewEvents().Count);
File.Delete(_path);
AppendShared(Line("started", "s2"));
IReadOnlyList<StatusEvent> events = tailer.ReadNewEvents();
StatusEvent onlyEvent = Assert.Single(events);
Assert.Equal("s2", onlyEvent.SessionId);
}
private static string Line(string e, string sessionId) =>
$$"""{"v":1,"e":"{{e}}","t":"2026-08-14T12:00:00Z","sessionId":"{{sessionId}}"}""" + "\n";
private void AppendShared(string text)
{
using var stream = new FileStream(
_path,
FileMode.Append,
FileAccess.Write,
FileShare.ReadWrite | FileShare.Delete);
byte[] bytes = Encoding.UTF8.GetBytes(text);
stream.Write(bytes, 0, bytes.Length);
}
}