From 33b7fe0f9f8d4fcbf23fe2150974bfa85c40b9f1 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Tue, 17 Nov 2026 22:26:05 +0100 Subject: [PATCH] test(acp): pin blocked-writer backpressure regressions MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit RED at base for the acp-backpressure finding: on the unfixed transport a hung engine that stops reading stdin fills its pipe, and the synchronous send wedges the client's one serial queue — the request deadline never fires, follow-up bookkeeping starves, and close() blocks behind the stuck write (argus probe: 2M-char request, 0.1 s timeout, watchdog close never returned). Three smokes over the existing rig, using a new neverRead fake mode (execs /bin/sleep — the probe's inert non-reading child; never a real profile): deadline fires while blocked, Stop + bookkeeping answer while blocked, close returns bounded and reaps the child. A fourth smoke (new serverPing fake mode) pins the healthy contract — round trip, -32601 reply delivery over the wire, idempotent clean close — and passes at base. Focused serialized run at base: 6 executed / 3 passed / 3 failed — exactly the three blocked-writer smokes fail, on mechanism. --- MuseionTests/ACPClientTests.swift | 17 +++ MuseionTests/EngineSmokeTests.swift | 178 ++++++++++++++++++++++++++++ 2 files changed, 195 insertions(+) diff --git a/MuseionTests/ACPClientTests.swift b/MuseionTests/ACPClientTests.swift index 543b84a..6432df0 100644 --- a/MuseionTests/ACPClientTests.swift +++ b/MuseionTests/ACPClientTests.swift @@ -49,6 +49,13 @@ import Testing /// Mode `loadReplayHold` = loadReplay with session/load PARKED (after a /// "hold-load" stderr line) until a `load-go` file lands beside the fake — /// the finish-audit interleaving pin's in-flight observable. +/// Mode `neverRead` (brief-27): execs /bin/sleep 30 without reading one +/// line — the inert non-reading child of the backpressure smokes (the +/// pipe fills, the client's writer blocks; the finding's probe shape). +/// Mode `serverPing` (brief-27): full behaviour PLUS one server→client +/// request (id 900) emitted at initialize — the client must answer -32601 +/// over the wire; the fake logs our reply line to `-reply-log` +/// (the reply-delivery pin). /// The mode travels in a file next to the fake (self-locating — race-free /// under parallel suites, same convention as ProfileProvisionerTests). /// The fix-card payload travels base64-encoded so shell quoting can't break. @@ -69,6 +76,11 @@ func makeFakeACP(at dir: String, name: String = "hermes-acp", mode: String = "fu mode="full" [[ -f "${0:h}/\(name)-mode" ]] && mode=$(<"${0:h}/\(name)-mode") print -- "$@" >> "${0:h}/\(name)-spawn-log" # #137: every spawn's argv — tests pin which engine (profile) ran + if [[ "$mode" == "neverRead" ]]; then + # brief-27: /bin/sleep never reads stdin — the pipe fills and the client's writer blocks. + # exec keeps sleep the DIRECT child (close SIGTERMs it; no orphan holds the pipe open). + exec /bin/sleep 30 + fi card=$(print -- '\(fixCardB64)' | base64 -d) research=$(print -- '\(researchB64)' | base64 -d) researchstray=$(print -- '\(strayResearchPayloadB64())' | base64 -d) @@ -80,7 +92,12 @@ func makeFakeACP(at dir: String, name: String = "hermes-acp", mode: String = "fu [[ -z "$line" ]] && continue method=$(print -r -- "$line" | /usr/bin/python3 -c 'import json,sys; print(json.load(sys.stdin).get("method",""))') rid=$(print -r -- "$line" | /usr/bin/python3 -c 'import json,sys; d=json.load(sys.stdin).get("id"); print(d if d is not None else "x")') + if [[ "$mode" == "serverPing" && "$rid" == "900" && -z "$method" ]]; then + print -r -- "$line" >> "${0:h}/\(name)-reply-log" # brief-27: the client's -32601 reply to our server request, on the wire + continue + fi if [[ "$method" == "initialize" ]]; then + [[ "$mode" == "serverPing" ]] && echo '{"jsonrpc":"2.0","id":900,"method":"client/ping"}' echo $framing"$rid",'"result":{"protocolVersion":1,"agentInfo":{"name":"hermes-agent","title":"Hermes","version":"9.9.9"}}}' [[ "$mode" == "crashAfterHandshake" ]] && exit 1 elif [[ "$method" == "session/new" ]]; then diff --git a/MuseionTests/EngineSmokeTests.swift b/MuseionTests/EngineSmokeTests.swift index ab5abb4..c62ca53 100644 --- a/MuseionTests/EngineSmokeTests.swift +++ b/MuseionTests/EngineSmokeTests.swift @@ -9,6 +9,11 @@ // 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 @@ -214,4 +219,177 @@ struct EngineSmokeTests { #expect(kill(chatPid, 0) == 0) #expect(mentor.phase.isReady) } + + // MARK: - brief-27 backpressure smokes (blocked-writer regression rig) + + /// brief-27: bounded await for operations that HANG on the unfixed + /// transport (the RED shape) — nil when the task hasn't finished inside + /// `window` seconds. One deadline per call (the house rule). The losing + /// leg is cancelled; the task itself keeps running and settles at the + /// test's teardown (SIGKILL of the rig child unblocks the writer). + @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: 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 = Task { + do { + _ = try await client.request("session/prompt", params: blockedWriterPayload, timeout: 0.5) + return "returned" + } catch { + return String(describing: error) + } + } + 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() + } + _ = Task { + do { + _ = try await client.request("session/prompt", params: blockedWriterPayload, timeout: 8) + } catch { + return String(describing: error) + } + return "returned" + } + // 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 = Task { + do { + _ = try await client.request( + "session/new", + params: .object(["cwd": .string("/tmp"), "mcpServers": .array([])]), + timeout: 0.5, + ) + return "returned" + } catch { + return String(describing: error) + } + } + 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() + } + _ = Task { + do { + _ = try await client.request("session/prompt", params: blockedWriterPayload, timeout: 8) + } catch { + return String(describing: error) + } + return "returned" + } + // 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)) + } }