Files
museion/MuseionTests/EngineSmokeTests.swift
T
AlexKucera 06283b6287
CI / ci (push) Canceled after 0s
refactor(posts): route every library write through the write rail (#179)
One internal seam (PostsModelRail.swift) now pairs every library
verb store write with exactly one library rescan and owns the error
strip: saveDraft, newPostFromSession, rename, trash, createProject,
moveToProject, archivePost, restorePost, unarchiveProject,
importFiles, convertToPost, and runPass pass-state advance (12 sites
on this base; the pass snapshot/stats writes, the publish stamp, and
the editor flush stay outside by design).

The model owns the Home: boundHome is set by bind() alone (app
construction + Settings repoint); every public verb lost its home:
parameter (create post/outline/session-born, rename, move, archive,
restore, trash, convert, project creation, import, select, cards,
passes, blind read, publish).

The three rail entries are railWrite/railWriteReturningReason/
railWriteKeepingStrip — deliberately NOT overloads: a shared base
name let unlabeled trailing-closure calls resolve into the labeled
non-generic entry (Swift binds trailing closures to labeled first
parameters), silently bypassing the strip and the pairing.

Views + 11 test files swept to the homeless signatures (160 sites).
RED suite green: 3/3. Full unit suite: 654/654. Fixes #179
2026-11-10 03:05:48 +01:00

218 lines
8.4 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//
// EngineSmokeTests.swift
// MuseionTests
//
// Scenario: one real-process wire smoke per LLM surface
// From #178
// Given every engine-behaviour test now runs in-process at the transport seam
// When the real stdio wire contract must be guarded
// Then exactly one real-process end-to-end smoke per surface (chat on museion,
// pass1, pass2) drives the real ACPEngineClient + the zsh fake — the only
// child-spawning tests left in the suite.
//
import Foundation
@testable import Museion
import Testing
/// 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.
/// Local to this file: only the smokes observe real child pids anymore.
@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)
}
return kill(pid, 0) != 0
}
/// Bounded settle for the streamed turn: the text row and the fix-card row
/// land via notification hops that can settle just after the response
/// resumes the test (the house poll pattern).
@MainActor
private func pollStreamedTurn(of mentor: MentorSessionModel) async throws -> (streamed: Bool, card: Bool) {
var streamed = false
var card = false
for _ in 0 ..< 250 where !(streamed && card) {
streamed = mentor.rows.contains { row in
if case let .text(text, _, _) = row.content {
return text.contains("Hello mentor.")
}
return false
}
card = mentor.rows.contains { row in
if case let .fixCard(fix) = row.content {
return fix.pattern == "Blame tense"
}
return false
}
if !(streamed && card) {
try await Task.sleep(nanoseconds: 20_000_000)
}
}
return (streamed, card)
}
/// Bounded poll for the .crashed phase after the child kill.
@MainActor
private func pollCrashed(_ mentor: MentorSessionModel) async -> Bool {
for _ in 0 ..< 250 {
if case .crashed = mentor.phase {
return true
}
try? await Task.sleep(nanoseconds: 20_000_000)
}
return false
}
@Suite("EngineSmokeTests")
struct EngineSmokeTests {
/// Act 1 of the chat smoke, extracted (function_body_length): the two
/// held-turn wire contracts on the cancel-holding fake — see the test
/// below for the contracts' meaning.
@MainActor
private func heldTurnWireContracts(fake: String) async throws {
let held = MentorSessionModel(binaryPath: fake)
defer { held.shutdown() }
await held.openSession()
let heldTurn = Task { await held.sendPrompt("hold this") }
for _ in 0 ..< 250 where !held.isStreaming {
try await Task.sleep(nanoseconds: 20_000_000)
}
held.stopStreaming() // fire-and-forget session/cancel over the real pipe
#expect(await heldTurn.value == .cancelled)
// A second held turn, ended by teardown: shutdown SIGTERMs the parked
// child and reaps it — no child outlives the app.
let holdPid = try #require(held.childProcessIdentifier)
let holdTurn = Task { await held.sendPrompt("hold for teardown") }
for _ in 0 ..< 250 where !held.isStreaming {
try await Task.sleep(nanoseconds: 20_000_000)
}
held.shutdown()
_ = await holdTurn.value
#expect(try await pollReaped(holdPid))
}
/// The chat surface over the REAL stdio path, in two acts over one fake:
/// (1) the cancel + hung-teardown wire contracts — a held turn ends
/// `.cancelled` the moment the fire-and-forget session/cancel arrives
/// (#124), and shutdown SIGTERMs a child parked mid-hold (the
/// SIGTERM→grace→SIGKILL escalation, previously pinned by the retired
/// client tests); then the mode file flips and (2) a fresh model runs
/// the full lifecycle — handshake + version, a streamed turn (text +
/// fix card), a hard child kill (the real crash rail), restart onto a
/// fresh child with the OLD pid reaped, and teardown reaping the new
/// one. Mode `loadReplay` for act 2: restart() resumes the newest
/// rostered session over session/load, which the fake's default mode
/// never answers — this mode answers EVERYTHING act 2 drives.
@MainActor
@Test func `chat surface smoke — cancel, teardown, handshake, stream, crash, restart`() async throws {
let dir = acpTempDir("smoke-chat")
let fake = makeFakeACP(at: dir, mode: "hangOnPrompt")
// Act 1 — the held-turn wire contracts on the cancel-holding fake.
try await heldTurnWireContracts(fake: fake)
// Act 2 — the full chat lifecycle; the fresh child reads loadReplay.
try "loadReplay".write(
toFile: (dir as NSString).appendingPathComponent("hermes-acp-mode"),
atomically: true,
encoding: .utf8,
)
let mentor = MentorSessionModel(binaryPath: fake)
defer { mentor.shutdown() }
await mentor.openSession()
guard case .ready = mentor.phase else {
Issue.record("expected ready, got \(mentor.phase); stderr: \(mentor.stderrTail)")
return
}
#expect(mentor.engineVersion == "9.9.9")
let outcome = await mentor.sendPrompt("hello mentor")
#expect(outcome == .ended(stopReason: "end_turn"))
let turn = try await pollStreamedTurn(of: mentor)
#expect(turn.streamed)
#expect(turn.card)
// The real crash rail: kill the child, the connection loss must land.
let pid = try #require(mentor.childProcessIdentifier)
kill(pid, SIGKILL)
#expect(await pollCrashed(mentor))
await mentor.restart()
var newPid: pid_t?
for _ in 0 ..< 250 {
if mentor.phase.isReady, let respawned = mentor.childProcessIdentifier, respawned != pid {
newPid = respawned
break
}
try await Task.sleep(nanoseconds: 20_000_000)
}
#expect(newPid != nil, "chat engine never re-spawned onto a new child")
// The crashed child is reaped; teardown reaps the replacement.
#expect(try await pollReaped(pid))
mentor.shutdown()
#expect(try await pollReaped(#require(newPid)))
}
/// The Pass 1/Pass 2 surfaces over the REAL stdio path (parameterized —
/// one smoke case per surface): a one-shot pass engine spawns under its
/// own profile beside the resident chat engine (the spawn log pins
/// both), the verdict completes the pass (snapshot + the monotonic
/// stamp — passes run in any order, so both kinds stamp from First
/// Draft), and BOTH children die honestly — the pass child reaped at
/// the verdict, the chat child still alive at teardown.
@MainActor
@Test(arguments: [PassKind.pass1, PassKind.pass2])
func `pass surface smoke — own engine, spawn profile, teardown reap`(kind: PassKind) async throws {
let passNumber = kind == .pass1 ? 1 : 2
let dir = acpTempDir("smoke-pass\(passNumber)")
let fake = makeFakeACP(at: dir)
let (model, home) = try makeModelHome()
let mentor = MentorSessionModel(binaryPath: fake)
defer { mentor.shutdown() }
await mentor.openSession() // the resident chat engine
let chatPid = try #require(mentor.childProcessIdentifier)
let post = try PostStore.writeNew(body: "# Smoke Pass\n\nVerdict me.", home: home)
model.select(post.id)
for _ in 0 ..< 250 where !model.posts.contains(where: { $0.id == post.id }) {
try await Task.sleep(nanoseconds: 20_000_000)
}
// In a Task — the pass child's pid is only observable while it runs
// (the old EngineLifecycleTests poll; the zsh wire latency holds the
// turn open long enough to catch it).
let run = Task { await model.runPass(kind, mentor: mentor) }
var passPid: pid_t?
var polls = 0
while passPid == nil, polls < 250 {
passPid = mentor.passEngineChildPid
polls += 1
if passPid == nil {
try await Task.sleep(nanoseconds: 20_000_000)
}
}
_ = await run.value
// The verdict completed the pass: snapshot landed, the kind's stamp.
let piece = home.appendingPathComponent("projects/posts/\(post.id)")
let snapshot = try String(
contentsOf: piece.appendingPathComponent("passes/pass-\(passNumber).md"), encoding: .utf8,
)
#expect(snapshot.contains("Verdict me."))
let onDisk = try String(contentsOf: piece.appendingPathComponent("post.md"), encoding: .utf8)
#expect(onDisk.contains("pass_state: Pass-\(passNumber) Done"))
// Both engines spawned over the real wire, each under its profile.
let lines = try String(
contentsOfFile: (dir as NSString).appendingPathComponent("hermes-acp-spawn-log"),
encoding: .utf8,
).split(separator: "\n").map(String.init)
#expect(lines.contains("acp -p museion-pass\(passNumber)"))
#expect(lines.contains("acp -p museion"))
// The pass child is reaped at the verdict; the chat child lives on.
#expect(try await pollReaped(#require(passPid, "pass child pid never observed mid-run")))
#expect(kill(chatPid, 0) == 0)
#expect(mentor.phase.isReady)
}
}