Merge pull request 'fix(acp): engine backpressure cannot defeat deadlines or teardown [museion/acp-backpressure-defeats-timeout-and-shutdown]' (#199) from fix/acp-backpressure-defeats-timeout-and-shutdown into main
CI / ci (push) Canceled after 0s

This commit was merged in pull request #199.
This commit is contained in:
AlexKucera committed 2026-11-19 10:38:17 +01:00
commit 55be3d1a2f
8 files changed
+292 -10

No files matched your search

+17
View File
@@ -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 `<name>-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
+1 -1
View File
@@ -32,7 +32,7 @@ Conventions every suite follows. Per-suite pin inventories are NOT kept here —
- `EngineGateTests`, `GatelessLaunchTests` — engine probe; gateless launch seam, status-pill and header state mappings.
- `ACPClientTests` — turn-outcome seam + view predicates over the scripted engine (#178: the client wire contract itself lives in EngineSmokeTests; `makeFakeACP`/`acpTempDir` remain here as the shared wire fixture).
- `ScriptedEngine.swift` — #178: the scripted in-process `EngineTransport` adapter, shared payloads, and the scripted rig roots every engine suite builds on.
- `EngineSmokeTests` — #178: the ONLY child-spawning suite — one real-process end-to-end wire smoke per LLM Surface (chat on `museion`: handshake/stream/verdict/crash/restart/teardown; pass1/pass2: own engine under its profile, teardown reap, chat engine untouched).
- `EngineSmokeTests` — #178: the ONLY child-spawning suite — one real-process end-to-end wire smoke per LLM Surface (chat on `museion`: handshake/stream/verdict/crash/restart/teardown; pass1/pass2: own engine under its profile, teardown reap, chat engine untouched); brief-27: the blocked-writer regression rig (never-reading `/bin/sleep` fake mode — deadline/Stop-delivery/bounded-close stay live behind a full stdin pipe) + the `serverPing` healthy-contract smoke.
- `ProfileLayoutTests`, `HermesConfigRailTests` — #182: the layout's one pinning suite (root default + every per-profile path builder against literals) and the config-set rail's ONE contract suite (argv+`--force`, provider-first hoisting, ✓-line verification, unset idempotence, structured Failure) — both over the shared fake-hermes double; callers' suites pin only their own key lists.
- `ProfileProvisionerTests`, `ProfileSurfaceTests`, `ProfileSkillMigrationTests`, `ProfileProvisionerFailureTests`, `ProfileBackupTests` — provisioning, symlink migration, failure paths, backup (one fake-`hermes` harness).
- `PostLibraryTests`, `PostStoreTests`, `PostStorePassTests`, `PostFrontmatterTests` — scan, write side, pass substrate, stats capture, research notes, the frontmatter codec (#180: posture round-trips, lenient decode, named eligibility predicates).
+172
View File
@@ -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,171 @@ struct EngineSmokeTests {
#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<T: Sendable>(_ task: Task<T, Never>, 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<String, Never> {
Task<String, Never> {
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<Void, Never> { 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))
}
}