refactor(session): extract the engine host
CI / ci (push) Canceled after 0s

Engine lifecycle policy — spawn, handshake, respawn-on-crash, teardown,
and the per-surface residency rules (resident chat engine; one-shot
pass engines spawned per run, torn down at the verdict, ADR-0014) —
moves out of MentorSessionModel into EngineHost behind the
EngineTransport seam. The model keeps session + turn coordination and
stays the only observable the panes see; ACPEngineClient becomes the
seam's production adapter, and a scripted in-process engine
(ScriptedEngine) becomes the second adapter — engine-behaviour tests
(streaming, crash, cancel, restart, per-surface spawn) now run without
child processes, retiring the zsh fake-server rigs from logic tests
(#30 flake family). Exactly one real-process wire smoke per LLM
surface survives (chat two-act + parameterized pass1/pass2): the
held-turn cancel contract, hung-child SIGTERM teardown, handshake,
streamed turn, crash, restart.

One-shot teardown is structural (withOneShot closes at body end, every
exit path); the one-shot slot is claimed before the first suspension so
the at-most-one invariant holds across the spawn/handshake awaits.

Suite: 652 executed / 652 passed / 0 failed (653 argument cases),
counted from the xcresult; swiftformat idempotent, swiftlint clean on
touched files.

Closes #178
This commit is contained in:
AlexKucera committed 2026-11-09 18:26:16 +01:00
1 parent d14cb40e73
commit 627ecf515e
18 files changed
+1663 -639

No files matched your search

+76 -106
View File
@@ -6,39 +6,33 @@
// own ONE-SHOT engines (spawned per run on the pass profile, torn down at
// the verdict, never rostered per #129) and the Chat model-change restart
// posture (restart in place when idle, defer to turn end while streaming).
// Real client + fake ACP path; the fake's spawn log pins WHICH engine ran.
// #178: runs IN-PROCESS over ScriptedEngines rigs at the EngineTransport
// seam — the rig's spawnedProfiles pin WHICH engine ran; pid pins became
// transport-identity/closed pins (host.chat/host.oneShot identity +
// ScriptedEngine.isClosed).
//
import Foundation
@testable import Museion
import Testing
/// makePassRig's shape plus the fake's directory — the spawn log beside
/// the fake is the "which engine (profile) spawned" observable (#137).
/// Poll for the pass engine's transport while the run is in flight —
/// host.oneShot is only observable mid-run (the host nils it at teardown).
/// For HELD passes only: a full-mode scripted pass can complete inside a
/// single 20 ms poll sleep, so completed runs capture via spawnedProfiles.
@MainActor
private struct EngineRig {
let model: PostsModel
let home: URL
let mentor: MentorSessionModel
let fakeDir: String
}
@MainActor
private func makeEngineRig(mode: String = "full") throws -> EngineRig {
let (model, home) = try makeModelHome()
let dir = acpTempDir("engine-lifecycle")
let fake = makeFakeACP(at: dir, mode: mode)
return EngineRig(model: model, home: home, mentor: MentorSessionModel(binaryPath: fake), fakeDir: dir)
}
/// Bounded poll until a child is reaped (kill(pid, 0) fails) — the house
/// 250×20 ms pattern, 100 rounds for a close() that reaps synchronously.
@MainActor
private func pollReaped(_ pid: pid_t) async throws -> Bool {
for _ in 0 ..< 100 where kill(pid, 0) == 0 {
try await Task.sleep(nanoseconds: 20_000_000)
private func pollOneShot(of mentor: MentorSessionModel) async throws -> ScriptedEngine? {
var engine: ScriptedEngine?
var polls = 0
while engine == nil, polls < 250 {
if let transport = mentor.host.oneShot, let scripted = transport as? ScriptedEngine {
engine = scripted
} else {
polls += 1
try await Task.sleep(nanoseconds: 20_000_000)
}
}
return kill(pid, 0) != 0
return engine
}
// Scenario: A pass run lives on its own engine
@@ -51,10 +45,10 @@ private func pollReaped(_ pid: pid_t) async throws -> Bool {
// engine keeps running untouched.
@Test @MainActor func `a pass run lives on its own engine and rosters nothing`() async throws {
let rig = try makeEngineRig()
defer { rig.mentor.shutdown() } // #124: at rig creation — the children die with the test
let rig = try makeScriptedRig()
defer { rig.mentor.shutdown() }
await rig.mentor.openSession()
let chatPid = try #require(rig.mentor.childProcessIdentifier)
let chatBefore = rig.mentor.host.chat
let rosterBefore = rig.mentor.roster.count
let post = try PostStore.writeNew(body: "# Own Engine\n\nVerdict me.", home: rig.home)
rig.model.select(post.id, home: rig.home)
@@ -62,18 +56,13 @@ private func pollReaped(_ pid: pid_t) async throws -> Bool {
try await Task.sleep(nanoseconds: 20_000_000)
}
// In a Task — the pass child's pid is only observable while it runs.
// In a Task — a full-mode scripted pass can complete inside one poll
// sleep (no child-process latency anymore), so the pass ENGINE is
// captured after the run from the spawn records, not polled mid-flight.
let run = Task { await rig.model.runPass(.pass1, home: rig.home, mentor: rig.mentor) }
var passPid: pid_t?
var polls = 0
while passPid == nil, polls < 250 {
passPid = rig.mentor.passEngineChildPid
polls += 1
if passPid == nil {
try await Task.sleep(nanoseconds: 20_000_000)
}
}
_ = await run.value
let passEngine = rig.engines.engines.last { $0.spawnedProfile == "museion-pass1" }
let passEngineClosed = try #require(passEngine, "pass engine never spawned")
// The run completed as today: snapshot landed, Pass-1 Done stamped.
let piece = rig.home.appendingPathComponent("projects/posts/\(post.id)")
@@ -82,22 +71,15 @@ private func pollReaped(_ pid: pid_t) async throws -> Bool {
let onDisk = try String(contentsOf: piece.appendingPathComponent("post.md"), encoding: .utf8)
#expect(onDisk.contains("pass_state: Pass-1 Done"))
// The pass engine spawned under its own profile; the chat engine under museion.
let lines = try String(
contentsOfFile: (rig.fakeDir as NSString).appendingPathComponent("hermes-acp-spawn-log"),
encoding: .utf8,
).split(separator: "\n").map(String.init)
#expect(lines.contains("acp -p museion-pass1"))
#expect(lines.contains("acp -p museion"))
#expect(rig.engines.spawnedProfiles.contains("museion-pass1"))
#expect(rig.engines.spawnedProfiles.contains("museion"))
// Nothing pass-shaped stays resident…
#expect(rig.mentor.roster.count == rosterBefore)
#expect(!rig.mentor.isPassEngineRunning)
if let passPid {
#expect(try await pollReaped(passPid))
} else {
Issue.record("pass engine pid never observed while the run was in flight")
}
// …and the chat engine is untouched.
#expect(kill(chatPid, 0) == 0)
#expect(rig.mentor.host.oneShot == nil)
#expect(passEngineClosed.isClosed) // the in-process reaped pin
// …and the chat engine is untouched (identity, not pid).
#expect(rig.mentor.host.chat === chatBefore)
#expect(rig.mentor.phase.isReady)
// The label row and the streamed critique rendered on the active surface.
#expect(textRows(of: rig.mentor).contains("Pass 1 · \(post.title)"))
@@ -114,10 +96,10 @@ private func pollReaped(_ pid: pid_t) async throws -> Bool {
}
/// A1 cancel: the pass bar's Cancel reaches the PASS engine — the held turn
/// ends cancelled, the pass child is reaped, the roster never grew, and the
/// pre-pass snapshot still landed (pre-pass is unconditional).
/// ends cancelled, the pass engine is torn down, the roster never grew, and
/// the pre-pass snapshot still landed (pre-pass is unconditional).
@Test @MainActor func `cancelling a live pass cancels the turn and reaps the pass engine`() async throws {
let rig = try makeEngineRig(mode: "hangOnPrompt")
let rig = try makeScriptedRig(mode: "hangOnPrompt")
defer { rig.mentor.shutdown() }
await rig.mentor.openSession()
let rosterBefore = rig.mentor.roster.count
@@ -125,16 +107,7 @@ private func pollReaped(_ pid: pid_t) async throws -> Bool {
rig.model.select(post.id, home: rig.home)
let run = Task { await rig.model.runPass(.pass1, home: rig.home, mentor: rig.mentor) }
var passPid: pid_t?
var polls = 0
while passPid == nil, polls < 250 {
passPid = rig.mentor.passEngineChildPid
polls += 1
if passPid == nil {
try await Task.sleep(nanoseconds: 20_000_000)
}
}
let heldPid = try #require(passPid, "pass engine never spawned")
let heldEngine = try #require(await pollOneShot(of: rig.mentor), "pass engine never spawned")
#expect(rig.mentor.isPassEngineRunning)
rig.model.cancelPass(mentor: rig.mentor) // the pass bar's Cancel rail
@@ -150,7 +123,8 @@ private func pollReaped(_ pid: pid_t) async throws -> Bool {
let onDisk = try String(contentsOf: piece.appendingPathComponent("post.md"), encoding: .utf8)
#expect(onDisk.contains("pass_state: First Draft"))
#expect(!rig.mentor.isPassEngineRunning)
#expect(try await pollReaped(heldPid))
#expect(rig.mentor.host.oneShot == nil)
#expect(heldEngine.isClosed) // the in-process reaped pin
#expect(rig.mentor.roster.count == rosterBefore)
}
@@ -163,32 +137,32 @@ private func pollReaped(_ pid: pid_t) async throws -> Bool {
// place and replays the active rostered session — while idle, it restarts
// immediately.
/// A2 idle: requestRestart re-spawns in place — old child reaped, new child
/// alive, phase back to .ready, and the PRE-restart active rostered session
/// is resumed with its transcript replayed from the engine.
/// A2 idle: requestRestart re-spawns in place — old engine closed, new
/// transport resident, phase back to .ready, and the PRE-restart active
/// rostered session is resumed with its transcript replayed from the engine.
@Test @MainActor func `idle requestRestart respawns in place and replays the active rostered session`() async throws {
let rig = try makeEngineRig(mode: "loadReplay")
let rig = try makeScriptedRig(mode: "loadReplay")
defer { rig.mentor.shutdown() }
await rig.mentor.openSession()
let active = try #require(rig.mentor.activeEntry)
_ = await rig.mentor.sendPrompt("hello mentor") // history in the active session
let oldPid = try #require(rig.mentor.childProcessIdentifier)
let oldEngine = try #require(rig.mentor.host.chat as? ScriptedEngine)
rig.mentor.requestRestart()
var newPid: pid_t?
var newChat: (any EngineTransport)?
var polls = 0
while newPid == nil, polls < 250 {
if rig.mentor.phase.isReady, let pid = rig.mentor.childProcessIdentifier, pid != oldPid {
newPid = pid
while newChat == nil, polls < 250 {
if rig.mentor.phase.isReady, let chat = rig.mentor.host.chat, chat !== oldEngine {
newChat = chat
} else {
polls += 1
try await Task.sleep(nanoseconds: 20_000_000)
}
}
let respawned = try #require(newPid, "chat engine never re-spawned")
#expect(try await pollReaped(oldPid))
#expect(kill(respawned, 0) == 0)
let respawned = try #require(newChat, "chat engine never re-spawned")
#expect(oldEngine.isClosed) // the in-process reaped pin
#expect(rig.mentor.host.chat === respawned) // the new engine stays resident
// The writer stays where they were: same rostered session, replayed.
#expect(rig.mentor.activeEntry == active)
var replayed = false
@@ -203,13 +177,14 @@ private func pollReaped(_ pid: pid_t) async throws -> Bool {
}
/// A2 deferred ordering pin: requested mid-turn, the restart holds (same
/// child, still streaming) until the turn ends — the pid swap happens only
/// AFTER the turn.
/// transport, still streaming) until the turn ends — the engine swap
/// happens only AFTER the turn.
@Test @MainActor func `requestRestart mid-turn defers the respawn until the turn ends`() async throws {
let rig = try makeEngineRig(mode: "hangOnPrompt")
let rig = try makeScriptedRig(mode: "hangOnPrompt")
defer { rig.mentor.shutdown() }
await rig.mentor.openSession()
let chatPid = try #require(rig.mentor.childProcessIdentifier)
let chatBefore = rig.mentor.host.chat
let oldEngine = try #require(chatBefore as? ScriptedEngine)
let turn = Task { await rig.mentor.sendPrompt("hold this") }
for _ in 0 ..< 250 where !rig.mentor.isStreaming {
@@ -219,27 +194,26 @@ private func pollReaped(_ pid: pid_t) async throws -> Bool {
rig.mentor.requestRestart() // Settings fires — mid-turn
try await Task.sleep(for: .milliseconds(300))
// Still streaming, same child: the restart deferred, never mid-reply.
// Still streaming, same engine: the restart deferred, never mid-reply.
#expect(rig.mentor.isStreaming)
#expect(rig.mentor.childProcessIdentifier == chatPid)
#expect(kill(chatPid, 0) == 0)
#expect(rig.mentor.host.chat === chatBefore)
rig.mentor.stopStreaming() // ends the held turn — the restart fires now
_ = await turn.value
#expect(!rig.mentor.isStreaming)
var newPid: pid_t?
var newChat: (any EngineTransport)?
var polls = 0
while newPid == nil, polls < 250 {
if rig.mentor.phase.isReady, let pid = rig.mentor.childProcessIdentifier, pid != chatPid {
newPid = pid
while newChat == nil, polls < 250 {
if rig.mentor.phase.isReady, let chat = rig.mentor.host.chat, chat !== chatBefore {
newChat = chat
} else {
polls += 1
try await Task.sleep(nanoseconds: 20_000_000)
}
}
#expect(newPid != nil, "the deferred pid swap never happened after turn end")
#expect(try await pollReaped(chatPid))
#expect(newChat != nil, "the deferred engine swap never happened after turn end")
#expect(oldEngine.isClosed) // the in-process reaped pin
}
// Scenario: Run Pass names the missing key instead of failing silently
@@ -309,7 +283,7 @@ private func pollReaped(_ pid: pid_t) async throws -> Bool {
/// provider in lastError — and fires BEFORE the open-piece guard's
/// snapshot, so nothing lands on disk.
@Test @MainActor func `run pass names the missing provider key and writes nothing`() async throws {
let rig = try makeEngineRig()
let rig = try makeScriptedRig()
defer { rig.mentor.shutdown() }
await rig.mentor.openSession()
let writer = RecordingWriter()
@@ -336,11 +310,11 @@ private func pollReaped(_ pid: pid_t) async throws -> Bool {
/// #137 audit (finish): a session/load that STARTED before a pass and
/// COMPLETES mid-pass must not steal the pass surface — the post-await
/// claimActive guard refuses, Cancel keeps routing to the pass engine.
/// loadReplayHold parks the load until `load-go` lands beside the fake
/// (SessionLifecycleTests' in-flight seam), which makes the interleaving
/// deterministic instead of lucky.
/// loadReplayHold parks the load until releaseHeldLoad() (the rig's
/// in-flight seam), which makes the interleaving deterministic instead of
/// lucky.
@Test @MainActor func `a resume completing mid-pass does not steal the pass surface`() async throws {
let rig = try makeEngineRig(mode: "loadReplayHold")
let rig = try makeScriptedRig(mode: "loadReplayHold")
defer { rig.mentor.shutdown() }
await rig.mentor.openSession() // default Mentor session (sess-1)
_ = await rig.mentor.newSession(name: "Second", pieceTitle: nil) // sess-2 active
@@ -351,7 +325,7 @@ private func pollReaped(_ pid: pid_t) async throws -> Bool {
try await Task.sleep(nanoseconds: 20_000_000)
}
// Park a resume of sess-1. The fake announces the park with a
// Park a resume of sess-1. The engine announces the park with a
// `hold-load` stderr line (the chat engine's stderrTail surfaces it).
let resume = Task { await rig.mentor.resumeSession(target) }
for _ in 0 ..< 250 where !rig.mentor.stderrTail.contains(where: { $0.contains("hold-load") }) {
@@ -359,15 +333,11 @@ private func pollReaped(_ pid: pid_t) async throws -> Bool {
}
try #require(rig.mentor.stderrTail.contains(where: { $0.contains("hold-load") }))
// Deterministic window: flip the mode file to hangOnPrompt BEFORE the
// pass engine spawns (each child reads the mode at startup) — the pass
// prompt then HOLDS, so isStreaming is guaranteed when the parked load
// completes, and the #124 Cancel rail frees it afterwards.
try "hangOnPrompt".write(
toFile: (rig.fakeDir as NSString).appendingPathComponent("hermes-acp-mode"),
atomically: true,
encoding: .utf8,
)
// Deterministic window: flip the rig's mode to hangOnPrompt BEFORE the
// pass engine spawns (each spawn reads the mode at factory time) — the
// pass prompt then HOLDS, so isStreaming is guaranteed when the parked
// load completes, and the #124 Cancel rail frees it afterwards.
rig.engines.mode = "hangOnPrompt"
let run = Task { await rig.model.runPass(.pass1, home: rig.home, mentor: rig.mentor) }
for _ in 0 ..< 250 where !rig.mentor.isPassEngineRunning {
try await Task.sleep(nanoseconds: 20_000_000)
@@ -376,7 +346,7 @@ private func pollReaped(_ pid: pid_t) async throws -> Bool {
// Free the parked load — its completion lands while the pass holds
// (nothing blocks the load; the held pass makes the direct await safe).
try Data().write(to: URL(fileURLWithPath: (rig.fakeDir as NSString).appendingPathComponent("load-go")))
rig.engines.releaseHeldLoad()
// The resume refused post-await while the pass still held the surface…
#expect(await resume.value == false)
#expect(rig.mentor.activeEntry?.sessionId == MentorSessionModel.passTranscriptKey)