refactor(session): extract the engine host
CI / ci (push) Canceled after 0s
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:
1 parent
d14cb40e73
commit
627ecf515e
18 files changed
+1663
-639
No files matched your search
@@ -6,10 +6,15 @@
|
||||
// freeform new + piece association, resume of engine-owned history
|
||||
// (user turns included) with an honest refusal for unknown sessions,
|
||||
// fork, compact over the prompt rail, and roster persistence across
|
||||
// model instances. Runs over the real client + fake ACP server
|
||||
// (ACPClientTests' fake in its `loadReplay` lifecycle mode).
|
||||
// model instances. #178: runs IN-PROCESS over ScriptedEngines rigs at
|
||||
// the EngineTransport seam (the `loadReplay` lifecycle mode) — no child
|
||||
// process; the real stdio wire contract is guarded by EngineSmokeTests.
|
||||
//
|
||||
|
||||
// swiftlint:disable file_length
|
||||
// One lifecycle story: the roster/resume/fork/compact pins + the
|
||||
// finish-audit and draft-candidate extensions — same suite, same file.
|
||||
|
||||
import Foundation
|
||||
@testable import Museion
|
||||
import Testing
|
||||
@@ -91,8 +96,8 @@ struct SessionLifecycleTests {
|
||||
let rosterDir = acpTempDir("resume-roster")
|
||||
let ghost = SessionEntry(sessionId: "ghost", name: "Ghost", pieceTitle: nil, createdAt: Date())
|
||||
SessionRoster.save([ghost], directory: rosterDir)
|
||||
let fake = makeFakeACP(at: acpTempDir("resume"), mode: "loadReplay")
|
||||
let mentor = MentorSessionModel(binaryPath: fake, rosterDirectory: rosterDir)
|
||||
let engines = ScriptedEngines(mode: "loadReplay")
|
||||
let mentor = engines.makeMentor(rosterDirectory: rosterDir)
|
||||
defer { mentor.shutdown() }
|
||||
await mentor.openSession()
|
||||
// The rostered entry is back and active — and the default open
|
||||
@@ -160,8 +165,8 @@ struct SessionLifecycleTests {
|
||||
let rosterDir = acpTempDir("fork-roster")
|
||||
let source = SessionEntry(sessionId: "sess-1", name: "Essay", pieceTitle: "Pt", createdAt: Date())
|
||||
SessionRoster.save([source], directory: rosterDir)
|
||||
let fake = makeFakeACP(at: acpTempDir("fork"), mode: "loadReplay")
|
||||
let mentor = MentorSessionModel(binaryPath: fake, rosterDirectory: rosterDir)
|
||||
let engines = ScriptedEngines(mode: "loadReplay")
|
||||
let mentor = engines.makeMentor(rosterDirectory: rosterDir)
|
||||
defer { mentor.shutdown() }
|
||||
await mentor.openSession()
|
||||
_ = await mentor.sendPrompt("hello mentor") // history in the original's transcript
|
||||
@@ -181,10 +186,8 @@ struct SessionLifecycleTests {
|
||||
let refusalDir = acpTempDir("fork-refusal")
|
||||
let ghost = SessionEntry(sessionId: "ghost", name: "Ghost", pieceTitle: nil, createdAt: Date())
|
||||
SessionRoster.save([ghost], directory: refusalDir)
|
||||
let refuser = MentorSessionModel(
|
||||
binaryPath: makeFakeACP(at: acpTempDir("fork-refuser"), mode: "loadReplay"),
|
||||
rosterDirectory: refusalDir,
|
||||
)
|
||||
let refuserEngines = ScriptedEngines(mode: "loadReplay")
|
||||
let refuser = refuserEngines.makeMentor(rosterDirectory: refusalDir)
|
||||
defer { refuser.shutdown() }
|
||||
await refuser.openSession()
|
||||
let refused = await refuser.forkActiveSession()
|
||||
@@ -281,8 +284,8 @@ struct SessionLifecycleTests {
|
||||
/// history replays from the engine (nothing fabricated locally).
|
||||
@Test @MainActor func `roster survives relaunch transcripts do not`() async throws {
|
||||
let rosterDir = acpTempDir("relaunch-roster")
|
||||
let fake = makeFakeACP(at: acpTempDir("relaunch"), mode: "loadReplay")
|
||||
let first = MentorSessionModel(binaryPath: fake, rosterDirectory: rosterDir)
|
||||
let firstEngines = ScriptedEngines(mode: "loadReplay")
|
||||
let first = firstEngines.makeMentor(rosterDirectory: rosterDir)
|
||||
defer { first.shutdown() }
|
||||
await first.openSession() // creates + persists the default 'Mentor'
|
||||
let notes = await first.newSession(name: "Notes", pieceTitle: "Essay X")
|
||||
@@ -295,7 +298,8 @@ struct SessionLifecycleTests {
|
||||
let firstEntry = (raw as? [[String: Any]])?.first ?? [:]
|
||||
#expect(Set(firstEntry.keys) == ["sessionId", "name", "pieceTitle", "createdAt"])
|
||||
|
||||
let second = MentorSessionModel(binaryPath: fake, rosterDirectory: rosterDir)
|
||||
let secondEngines = ScriptedEngines(mode: "loadReplay")
|
||||
let second = secondEngines.makeMentor(rosterDirectory: rosterDir)
|
||||
defer { second.shutdown() }
|
||||
#expect(second.roster.count == 2)
|
||||
#expect(second.roster.first == notes) // newest-first, all four fields equal
|
||||
@@ -333,70 +337,6 @@ struct SessionLifecycleTests {
|
||||
#expect(SessionsPaneView.openPiece(in: model)?.id == post.id)
|
||||
}
|
||||
|
||||
/// Finish-audit (converged, 3 reviewers): ONE replay slot — a second
|
||||
/// resume while a session/load is in flight refuses instead of diverting
|
||||
/// the first's replayed chunks into live streaming buffers.
|
||||
/// `loadReplayHold` parks the load until `load-go` lands beside the
|
||||
/// fake; the pre-hold "hold-load" stderr line is the in-flight
|
||||
/// observable.
|
||||
@Test @MainActor func `concurrent resume refuses while a replay is in flight`() async throws {
|
||||
let dir = acpTempDir("hold-load")
|
||||
let fake = makeFakeACP(at: dir, mode: "loadReplayHold")
|
||||
let rosterDir = acpTempDir("hold-roster")
|
||||
let known = SessionEntry(sessionId: "sess-9", name: "Known", pieceTitle: nil, createdAt: Date())
|
||||
SessionRoster.save([known], directory: rosterDir)
|
||||
let mentor = MentorSessionModel(binaryPath: fake, rosterDirectory: rosterDir)
|
||||
defer { mentor.shutdown() }
|
||||
_ = Task { await mentor.openSession() } // parks inside the auto-resume's load
|
||||
var inFlight = false
|
||||
for _ in 0 ..< 250 {
|
||||
if mentor.stderrTail.contains(where: { $0.contains("hold-load") }) {
|
||||
inFlight = true
|
||||
break
|
||||
}
|
||||
try await Task.sleep(nanoseconds: 20_000_000)
|
||||
}
|
||||
#expect(inFlight)
|
||||
|
||||
// The slot is taken: the second resume refuses honestly.
|
||||
let other = SessionEntry(sessionId: "ghost-2", name: "Other", pieceTitle: nil, createdAt: Date())
|
||||
let ok = await mentor.resumeSession(other)
|
||||
#expect(!ok)
|
||||
#expect(texts(in: mentor.transcriptRows(of: known)).contains { $0.contains("another session is loading") })
|
||||
|
||||
// Release the hold: the parked resume completes and replays.
|
||||
try "go".write(toFile: (dir as NSString).appendingPathComponent("load-go"), atomically: true, encoding: .utf8)
|
||||
var replayed = false
|
||||
for _ in 0 ..< 250 {
|
||||
if texts(in: mentor.transcriptRows(of: known)).contains(where: { $0.contains("earlier ask") }) {
|
||||
replayed = true
|
||||
break
|
||||
}
|
||||
try await Task.sleep(nanoseconds: 20_000_000)
|
||||
}
|
||||
#expect(replayed)
|
||||
}
|
||||
|
||||
/// Finish-audit: resume refusals belong to the ENTRY — a dead row's
|
||||
/// refusal lands in its own store, never in the active session's
|
||||
/// transcript.
|
||||
@Test @MainActor func `resume refusal is attributed to the entry not the active session`() async throws {
|
||||
let rosterDir = acpTempDir("attrib-roster")
|
||||
let ghost = SessionEntry(sessionId: "ghost", name: "Ghost", pieceTitle: nil, createdAt: Date())
|
||||
SessionRoster.save([ghost], directory: rosterDir)
|
||||
let fake = makeFakeACP(at: acpTempDir("attrib"), mode: "loadReplay")
|
||||
let mentor = MentorSessionModel(binaryPath: fake, rosterDirectory: rosterDir)
|
||||
defer { mentor.shutdown() }
|
||||
await mentor.openSession() // activates ghost; its load refuses (unknown id)
|
||||
let second = await mentor.newSession(name: "Second", pieceTitle: nil)
|
||||
#expect(second != nil)
|
||||
|
||||
_ = await mentor.resumeSession(ghost) // refuses again
|
||||
#expect(texts(in: mentor.transcriptRows(of: ghost)).contains { $0.contains("does not know") })
|
||||
let secondEntry = try #require(second)
|
||||
#expect(!texts(in: mentor.transcriptRows(of: secondEntry)).contains { $0.contains("does not know") })
|
||||
}
|
||||
|
||||
/// Finish-audit: the creation rail refuses while a turn streams — a
|
||||
/// programmatic caller must not switch the active session out from
|
||||
/// under a live turn (Stop would cancel the wrong session).
|
||||
@@ -426,22 +366,91 @@ struct SessionLifecycleTests {
|
||||
let perms = try FileManager.default.attributesOfItem(atPath: url.path)[.posixPermissions] as? Int
|
||||
#expect(perms == 0o600)
|
||||
}
|
||||
}
|
||||
|
||||
// Scenario: the one replay slot + the crash-restart rail — finish-audit
|
||||
// pins over the loadReplay modes. File-scope extension —
|
||||
// type_body_length posture; same suite, same file.
|
||||
@MainActor
|
||||
extension SessionLifecycleTests {
|
||||
/// Finish-audit (converged, 3 reviewers): ONE replay slot — a second
|
||||
/// resume while a session/load is in flight refuses instead of diverting
|
||||
/// the first's replayed chunks into live streaming buffers.
|
||||
/// `loadReplayHold` parks the load until the rig's `releaseHeldLoad()`;
|
||||
/// the pre-hold "hold-load" stderr line is the in-flight observable.
|
||||
@Test func `concurrent resume refuses while a replay is in flight`() async throws {
|
||||
let rosterDir = acpTempDir("hold-roster")
|
||||
let engines = ScriptedEngines(mode: "loadReplayHold")
|
||||
let known = SessionEntry(sessionId: "sess-9", name: "Known", pieceTitle: nil, createdAt: Date())
|
||||
SessionRoster.save([known], directory: rosterDir)
|
||||
let mentor = engines.makeMentor(rosterDirectory: rosterDir)
|
||||
defer { mentor.shutdown() }
|
||||
_ = Task { await mentor.openSession() } // parks inside the auto-resume's load
|
||||
var inFlight = false
|
||||
for _ in 0 ..< 250 {
|
||||
if mentor.stderrTail.contains(where: { $0.contains("hold-load") }) {
|
||||
inFlight = true
|
||||
break
|
||||
}
|
||||
try await Task.sleep(nanoseconds: 20_000_000)
|
||||
}
|
||||
#expect(inFlight)
|
||||
|
||||
// The slot is taken: the second resume refuses honestly.
|
||||
let other = SessionEntry(sessionId: "ghost-2", name: "Other", pieceTitle: nil, createdAt: Date())
|
||||
let secondLoad = await mentor.resumeSession(other)
|
||||
#expect(!secondLoad)
|
||||
#expect(texts(in: mentor.transcriptRows(of: known)).contains { $0.contains("another session is loading") })
|
||||
|
||||
// Release the hold: the parked resume completes and replays.
|
||||
engines.releaseHeldLoad()
|
||||
var replayed = false
|
||||
for _ in 0 ..< 250 {
|
||||
if texts(in: mentor.transcriptRows(of: known)).contains(where: { $0.contains("earlier ask") }) {
|
||||
replayed = true
|
||||
break
|
||||
}
|
||||
try await Task.sleep(nanoseconds: 20_000_000)
|
||||
}
|
||||
#expect(replayed)
|
||||
}
|
||||
|
||||
/// Finish-audit: resume refusals belong to the ENTRY — a dead row's
|
||||
/// refusal lands in its own store, never in the active session's
|
||||
/// transcript.
|
||||
@Test func `resume refusal is attributed to the entry not the active session`() async throws {
|
||||
let rosterDir = acpTempDir("attrib-roster")
|
||||
let ghost = SessionEntry(sessionId: "ghost", name: "Ghost", pieceTitle: nil, createdAt: Date())
|
||||
SessionRoster.save([ghost], directory: rosterDir)
|
||||
let engines = ScriptedEngines(mode: "loadReplay")
|
||||
let mentor = engines.makeMentor(rosterDirectory: rosterDir)
|
||||
defer { mentor.shutdown() }
|
||||
await mentor.openSession() // activates ghost; its load refuses (unknown id)
|
||||
let second = await mentor.newSession(name: "Second", pieceTitle: nil)
|
||||
#expect(second != nil)
|
||||
|
||||
_ = await mentor.resumeSession(ghost) // refuses again
|
||||
#expect(texts(in: mentor.transcriptRows(of: ghost)).contains { $0.contains("does not know") })
|
||||
let secondEntry = try #require(second)
|
||||
#expect(!texts(in: mentor.transcriptRows(of: secondEntry)).contains { $0.contains("does not know") })
|
||||
}
|
||||
|
||||
/// Finish-audit: restart() REPLAYS the active transcript from the
|
||||
/// engine (ADR-0007 — the engine owns the words; the pre-crash local
|
||||
/// rows are replaced by the replay, not preserved).
|
||||
@Test @MainActor func `restart replays the active transcript from the engine`() async throws {
|
||||
/// rows are replaced by the replay, not preserved). #178: the crash is
|
||||
/// driven in-process (crashNow — the kill(pid, SIGKILL) rail's twin);
|
||||
/// the pid pins became transport-identity/isClosed pins.
|
||||
@Test func `restart replays the active transcript from the engine`() async throws {
|
||||
let rosterDir = acpTempDir("restart-roster")
|
||||
let fake = makeFakeACP(at: acpTempDir("restart"), mode: "loadReplay")
|
||||
let mentor = MentorSessionModel(binaryPath: fake, rosterDirectory: rosterDir)
|
||||
let engines = ScriptedEngines(mode: "loadReplay")
|
||||
let mentor = engines.makeMentor(rosterDirectory: rosterDir)
|
||||
defer { mentor.shutdown() }
|
||||
await mentor.openSession()
|
||||
_ = await mentor.sendPrompt("hello") // a turn lands in the active session
|
||||
#expect(try !mentor.transcriptRows(of: #require(mentor.activeEntry)).isEmpty)
|
||||
|
||||
if let pid = mentor.childProcessIdentifier {
|
||||
kill(pid, SIGKILL) // crash the child
|
||||
}
|
||||
let oldEngine = try #require(mentor.host.chat as? ScriptedEngine)
|
||||
oldEngine.crashNow()
|
||||
var crashed = false
|
||||
for _ in 0 ..< 250 {
|
||||
if case .crashed = mentor.phase {
|
||||
@@ -453,6 +462,17 @@ struct SessionLifecycleTests {
|
||||
#expect(crashed)
|
||||
|
||||
await mentor.restart()
|
||||
// Ready again on a NEW transport; the old one is closed (the reaped pin).
|
||||
var respawned = false
|
||||
for _ in 0 ..< 250 {
|
||||
if mentor.phase.isReady, mentor.host.chat !== oldEngine {
|
||||
respawned = true
|
||||
break
|
||||
}
|
||||
try await Task.sleep(nanoseconds: 20_000_000)
|
||||
}
|
||||
#expect(respawned)
|
||||
#expect(oldEngine.isClosed)
|
||||
// The post-restart transcript is the ENGINE's replay — the replay
|
||||
// marker proves the words came from the engine, not the local copy.
|
||||
let rows = try mentor.transcriptRows(of: #require(mentor.activeEntry))
|
||||
|
||||
Reference in new issue
Block a user