// // 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. // brief-27 (acp-backpressure): plus the blocked-writer regression rig — a // never-reading /bin/sleep child (the finding probe's shape) pins that a full // stdin pipe cannot defeat the request deadline, Stop delivery, or a bounded // reaping close; a serverPing fake pins the healthy contract (round trip, // -32601 reply delivery, idempotent clean close). // 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) } // MARK: - brief-27 backpressure smokes (blocked-writer regression rig) /// brief-27: await an operation that may HANG on the unfixed transport /// (the RED shape) and report what it answered — nil when the window leg /// won. One deadline per call (the house rule). The bound is `window` /// only in the green world: withTaskGroup awaits stragglers at scope /// exit and `await task.value` is cancellation-blind, so a HUNG task /// holds this helper until IT settles — the real RED-world watchdog is /// the fake's `exec /bin/sleep 30` exit (~30 s, inside the rail's 60 s /// per-test timeout). Keep the fake's sleep short. @MainActor private func awaitBounded(_ task: Task, window: TimeInterval) async -> T? { await withTaskGroup(of: T?.self) { group in group.addTask { await task.value } group.addTask { try? await Task.sleep(nanoseconds: UInt64(window * 1_000_000_000)) return nil } let first = await group.next() ?? nil group.cancelAll() return first } } /// brief-27: run one request on a task and string-encode its outcome /// ("returned" or the error) — the observable the pins match on. @MainActor private func requestOutcome( _ client: ACPEngineClient, method: String, params: JSONValue?, timeout: TimeInterval, ) -> Task { Task { do { _ = try await client.request(method, params: params, timeout: timeout) return "returned" } catch { return String(describing: error) } } } /// brief-27: the blocked-writer rig — a real ACPEngineClient over the /// zsh fake in `neverRead` mode, which execs /bin/sleep without ever /// reading stdin (the finding's inert non-reading child; no real /// profile is anywhere near it). The oversized prompt fills the 64 KB /// pipe and wedges the writer. @MainActor private func makeBlockedWriterRig(label: String) throws -> (client: ACPEngineClient, pid: pid_t) { let dir = acpTempDir(label) let fake = makeFakeACP(at: dir, mode: "neverRead") let client = ACPEngineClient(binaryPath: fake) client.onMessage = { _, _ in } try client.start() return (client, client.childProcessIdentifier) } /// The pipe-filling payload: a 2,000,000-char prompt (the probe's size; /// the pipe holds 64 KB). private var blockedWriterPayload: JSONValue { .object(["prompt": .string(String(repeating: "x", count: 2_000_000))]) } /// brief-27 regression 1: the request deadline FIRES while the stdin /// write is blocked. On the unfixed transport the deadline sits on the /// same serial queue as the blocked send and never runs — the request /// stays pending forever (the finding's executed probe). @MainActor @Test func `request deadline fires while the stdin write is blocked`() async throws { let (client, pid) = try makeBlockedWriterRig(label: "smoke-blocked-deadline") defer { kill(pid, SIGKILL) // settle the blocked pipe FIRST — close's boundedness is the next smoke's pin, not this one's client.close() } let outcome = requestOutcome(client, method: "session/prompt", params: blockedWriterPayload, timeout: 0.5) let result = await awaitBounded(outcome, window: 5) #expect( result?.contains("timed out") == true, "deadline did not fire while the write was blocked: \(result ?? "still blocked after 5 s")", ) } /// brief-27 regression 2: Stop/cancellation stays deliverable while the /// write is blocked. The bytes cannot reach a non-reading child (the /// pipe is full — physics), so deliverable means the seam ACCEPTS the /// notification and lifecycle bookkeeping still answers: session/cancel /// is taken (a blocking notify would never let this test reach its /// assertion), and a follow-up request gets registered and reaches its /// OWN deadline. On the unfixed transport the follow-up's registration /// queues behind the stuck writer and never runs. @MainActor @Test func `stop notification and bookkeeping answer while the stdin write is blocked`() async throws { let (client, pid) = try makeBlockedWriterRig(label: "smoke-blocked-stop") defer { kill(pid, SIGKILL) client.close() } // Wedge the writer: the oversized prompt fills the pipe (outcome unobserved). Task { _ = try? await client.request("session/prompt", params: blockedWriterPayload, timeout: 8) } // Let the oversized write reach the pipe and wedge the writer first. try await Task.sleep(nanoseconds: 200_000_000) client.notify("session/cancel", params: .object(["sessionId": .string("sess-1")])) let second = requestOutcome( client, method: "session/new", params: .object(["cwd": .string("/tmp"), "mcpServers": .array([])]), timeout: 0.5, ) let result = await awaitBounded(second, window: 5) #expect( result?.contains("timed out") == true, "bookkeeping starved behind the blocked writer: \(result ?? "no answer within 5 s")", ) } /// brief-27 regression 3: close RETURNS BOUNDED while the write is /// blocked — child reaped, the SIGTERM→grace→SIGKILL escalation inside /// close actually reachable — without waiting on the blocked writer. /// On the unfixed transport close begins with a queue.sync behind the /// stuck send and never returns (the probe's watchdog hang). @MainActor @Test func `close returns bounded while the stdin write is blocked and reaps the child`() async throws { let (client, pid) = try makeBlockedWriterRig(label: "smoke-blocked-close") defer { kill(pid, SIGKILL) client.close() } // Wedge the writer: the oversized prompt fills the pipe (outcome unobserved). Task { _ = try? await client.request("session/prompt", params: blockedWriterPayload, timeout: 8) } // The write is in the pipe and the writer wedged before close runs. try await Task.sleep(nanoseconds: 200_000_000) let closeTask = Task { client.close() } let finished = await awaitBounded(closeTask, window: 5) #expect(finished != nil, "close did not return within 5 s — the blocked writer defeats teardown") #expect(try await pollReaped(pid), "child not reaped after the bounded close") } /// brief-27 regression 4: the healthy-child contract is unchanged — /// round trip (initialize → version), reply delivery (the engine's /// server→client request answered -32601 over the wire; the fake logs /// our reply), and a clean idempotent close that reaps the child. @MainActor @Test func `healthy engine round trip, server request answered, clean close`() async throws { let dir = acpTempDir("smoke-healthy-brief27") let fake = makeFakeACP(at: dir, mode: "serverPing") let client = ACPEngineClient(binaryPath: fake) client.onMessage = { _, _ in } try client.start() let pid = client.childProcessIdentifier defer { client.close() } let version = try await client.request("initialize", params: nil, timeout: 5) #expect(version?.objectValue?["agentInfo"]?.objectValue?["version"]?.stringValue == "9.9.9") let replyLog = (dir as NSString).appendingPathComponent("hermes-acp-reply-log") var reply: String? for _ in 0 ..< 250 where reply == nil { reply = try? String(contentsOfFile: replyLog, encoding: .utf8) if reply == nil { try await Task.sleep(nanoseconds: 20_000_000) } } #expect( reply?.contains("-32601") == true, "our -32601 reply to the server request never reached the engine: \(reply ?? "no reply logged")", ) client.close() client.close() // idempotent #expect(try await pollReaped(pid)) } }