fix(acp): engine backpressure cannot defeat deadlines or teardown [museion/acp-backpressure-defeats-timeout-and-shutdown] #199

Merged
AlexKucera merged 5 commits from fix/acp-backpressure-defeats-timeout-and-shutdown into main 2026-11-19 10:38:18 +01:00
8 changed files with 292 additions and 10 deletions

No files matched your search

+2
View File
@@ -6,6 +6,8 @@ All notable changes to this project will be documented in this file. The format
### Fixed
- **acp:** Engine backpressure can no longer defeat request deadlines, Stop, or teardown (finding `museion/acp-backpressure-defeats-timeout-and-shutdown`, argus cycle-4) — a hung engine that stops reading stdin fills the 64 KB pipe, and the ACP client's synchronous send blocked its ONE serial queue, the same queue carrying request-id allocation, pending registration, the timeout deadline, and close()'s bookkeeping barrier: the deadline never fired (a 0.1 s timeout on a 2 MB prompt stayed pending forever), a follow-up request hung at registration, Stop queued behind the stuck write, and close() synced behind it before SIGTERM was ever reachable — on MainActor (restart/quit) that was an app-wide unbounded hang. Stdin writes (and the stdin handle's own close, which a blocked write may still own) now ride a dedicated serial writer queue, leaving the state queue I/O-free: deadlines fire, Stop is accepted, bookkeeping answers, and close() runs SIGTERM → grace → SIGKILL → reap without queueing behind the writer. Wire order preserved (every send funnels through the one serial writer); healthy-engine contract untouched. +4 real-process smokes over two new zsh-fake modes (`neverRead` execs /bin/sleep — the probe's inert non-reading child, never a real profile; `serverPing` pins -32601 reply delivery): 3 RED-first at base on exactly the three mechanisms, healthy-contract pin green at base. Suite 697 (unticketed fix, brief-27)
- **search:** Library search results no longer go stale after library writes (finding `museion/library-search-stale-after-mutation`, the #144/#157 mounted gap) — the search snapshot's only task identity was the trimmed query, so nothing re-ran the sweep when the library moved underneath it: archiving or trashing a piece from a result row's own context menu left it sitting in the non-archived results after the rescan, and new, renamed, or externally edited pieces never entered or left the results until the query changed or the pane remounted. The #179 write rail's rescan now bumps a content revision whenever a scan sees the library change — a Post-list change OR any re-read post.md, so a body-only edit (which parses to an equal Post and is invisible to #143's equality-gated assignment) counts — and the mounted sweep keys on query + Home + that revision, rendering a landed snapshot only while it stays fresh for the current key (stale rows drop to the recompute spinner; panes never regroup — the assignment skip is untouched). +5 tests (pure key/gate pin; controller-level archive, trash, and same-query body-edit pins over the real rescan rail, red-first; an unchanged-rescan guard). Suite 686
- **session:** a deferred nil scope drains as an explicit clear (PR #184, finding class #176) — `pendingScopePieceTitle: String?` let "a scope request is pending" and "which piece it targets" ride the same optionality, so a nil-target request (the writer leaves the piece mid-stream or mid-replay: New Post, unsaved draft, external guest, nothing open) deferred correctly but at drain time read as "no pending request" and returned without touching `activeEntry` — the old piece's conversation stayed live under a nothing-open context, at all four drain sites. Pending-ness now rides `PendingScope` (`.none` | `.scope(String?)`): a nil target is an explicit clear everywhere it drains. Finish-audit fanout (3 reviewers): dead `Equatable` cut, the same-turn `pendingRestart` ceiling documented at the drain (the scope is lost in respawn's `.starting` window — consume-at-apply is the upgrade path), and the titled-apply half pinned for the first time over a new `hangOnPromptLoad` rig mode (prompt parks, load answers; flip-verified). Suite 654 (PR #184)
+45 -8
View File
@@ -75,6 +75,9 @@ nonisolated extension JSONValue {
/// matches responses to pending requests, and delivers notifications in wire
/// order. Requests are expected to be strictly sequential (initialize →
/// session/new → prompt), matching the pane's usage.
/// brief-27: stdin writes ride a dedicated writer queue, so engine
/// backpressure (a full pipe) can stall a send but never a deadline,
/// Stop delivery, or teardown.
///
/// Wire facts baked in (verified against adapter 0.20.6 + the acp SDK):
/// - `session/cancel` is a JSON-RPC *notification* (interfaces.py — CancelNotification).
@@ -94,6 +97,12 @@ final nonisolated class ACPEngineClient: @unchecked Sendable {
private let stderrPipe = Pipe()
/// All mutable state below is confined to this serial queue.
private let queue = DispatchQueue(label: "com.babylondreams.Museion.acp-client")
/// brief-27: stdin writes (and the stdin handle's own close) ride this
/// dedicated writer queue. The state queue NEVER touches the pipe — a
/// full pipe (hung engine not reading stdin) blocks only this writer, so
/// request deadlines, Stop delivery, and close()'s bookkeeping stay live
/// behind it. Serial = the wire order every send site already had.
private let writerQueue = DispatchQueue(label: "com.babylondreams.Museion.acp-client-writer")
private var pending: [Int: CheckedContinuation<JSONValue?, any Error>] = [:]
private var buffer = Data()
private var currentID = 0
@@ -148,6 +157,10 @@ final nonisolated class ACPEngineClient: @unchecked Sendable {
/// Send a JSON-RPC request and await its matching response result.
/// A request that gets no answer within `timeout` fails — a hung engine
/// must surface as an error (→ restart prompt), never an eternal await.
/// brief-27: a timed-out request's bytes may still reach the engine once
/// the child unblocks (the deadline fails the caller, never dequeues the
/// write) — phantom engine work only: ids are never reused and the
/// response path drops unknown ids, so a late reply can never misroute.
/// (No default arguments: the only caller is EngineHost, which rides the
/// seam — `EngineTransport.request`'s convenience owns the default shape.)
func request(_ method: String, params: JSONValue?, timeout: TimeInterval) async throws -> JSONValue? {
@@ -174,7 +187,9 @@ final nonisolated class ACPEngineClient: @unchecked Sendable {
continuation.resume(throwing: TransportError(message: "engine closed before \(method)"))
return
}
queue.async { self.send(raw) }
// brief-27: straight to the writer queue — never through the state
// queue, so a blocked write can't pin the deadline armed below.
send(raw)
// ponytail: deadline on the same serial queue — fires only if the
// response hasn't already resumed and removed the continuation.
queue.asyncAfter(deadline: .now() + timeout) {
@@ -194,11 +209,15 @@ final nonisolated class ACPEngineClient: @unchecked Sendable {
"params": params?.any ?? [String: Any](),
]
guard let raw = try? JSONSerialization.data(withJSONObject: payload) else { return }
queue.async { self.send(raw) }
// brief-27: writer queue, not the state queue (see request).
send(raw)
}
/// Graceful teardown: SIGTERM → 1 s grace → SIGKILL → reap, so the child
/// never outlives the app (same pattern as EngineProbe.terminateAndReap).
/// Graceful teardown: SIGTERM → 1 s grace → SIGKILL → reap, so the
/// child never outlives the app (same pattern as EngineProbe.terminateAndReap).
/// brief-27: bounded even when a stdin write is blocked on a full pipe —
/// bookkeeping syncs on the (I/O-free) state queue, and child
/// termination never queues behind the writer.
func close() {
let alreadyClosed = queue.sync {
if closed {
@@ -227,7 +246,14 @@ final nonisolated class ACPEngineClient: @unchecked Sendable {
}
}
process.waitUntilExit()
try? stdinPipe.fileHandleForWriting.close()
// brief-27: the stdin WRITE handle closes on the writer queue — a
// blocked write may still own it (it unblocks only once the child's
// read end died, which the kill above just arranged); closing under
// a live write would race Foundation. The reader handles have no
// writers — their handlers are already off, so they close here.
writerQueue.async {
try? self.stdinPipe.fileHandleForWriting.close()
}
try? stdoutPipe.fileHandleForReading.close()
try? stderrPipe.fileHandleForReading.close()
}
@@ -236,10 +262,21 @@ final nonisolated class ACPEngineClient: @unchecked Sendable {
/// Frame and write one NDJSON line. A failed write (child gone) is dropped:
/// the crash path owns the UX, not the send.
/// brief-27: the write runs on the WRITER queue, never the state queue —
/// a blocked write here starves no deadline and no teardown.
private func send(_ data: Data) {
var framed = Data(data)
framed.append(0x0A)
try? stdinPipe.fileHandleForWriting.write(contentsOf: framed)
// ponytail: queued sends are unbounded, and a send racing close() writes
// onto a closed handle (benign — write throws a catchable CocoaError 512
// that try? swallows; probe-verified by two independent reviewers).
// Bounded today by MentorSessionModel's sequential-send discipline (a
// request is awaited before the next; worst case one prompt + one
// cancel). Add a closed/depth guard here if a looping or
// non-MainActor caller ever appears.
writerQueue.async {
var framed = Data(data)
framed.append(0x0A)
try? self.stdinPipe.fileHandleForWriting.write(contentsOf: framed)
}
}
/// Fail every pending request and surface the crash — the one exit path
+1 -1
View File
@@ -84,7 +84,7 @@ The map and the contracts, one bullet per file. Pin-level detail lives in the te
## ACP bridge
- `EngineHost.swift` — #178: the engine lifecycle owner + the `EngineTransport` seam. The seam is the whole engine surface — `onMessage`/`onCrash`/`onStderrLine` hooks + `start() throws` + `request(_:params:timeout:)` + `notify` + `close()` — with two adapters: `ACPEngineClient` (real stdio, production) and `ScriptedEngine` (in-process, MuseionTests — engine-behaviour tests run without child processes). `EngineHost` (@MainActor) owns spawn (`makeTransport` factory, profile → transport, reads `binaryPath` at spawn time), the initialize handshake (advisory BASE-version drift note — the gate records the derived `0.21.5+build`, the handshake answers the base; never blocks), teardown, and the per-surface residency (ADR-0014): ONE resident chat engine (`startChat()`/`killChat()`) plus at most one one-shot engine (`withOneShot(profile:)` — spawn per run, teardown at the body's end = the verdict). Hook wiring lives in the host: each hook rides `DispatchQueue.main.async`, never `Task { @MainActor }` (the #28 main-queue FIFO wire-order guarantee); the one-shot transport gets `onMessage` ONLY — a pass crash must not flip the pane. `nonisolated(unsafe)` mirrors close children in deinit.
- `ACPEngineClient.swift` — hand-rolled thin NDJSON JSON-RPC stdio client (`hermes acp -p <profile>`; no Swift SDK exists), conforming to `EngineTransport` (notifications arrive on the `onMessage` property — always set before `start()`). Wire facts: stdout = wire, stderr = logs (never parsed for state); `session/new` REQUIRES `mcpServers` (Museion sends `[]`); `session/cancel` is a notification; requests time out (15 s default); crash/EOF fail pending requests and fire `onCrash` exactly once (latched); `close()` = handlers-off → SIGTERM → grace → SIGKILL → reap; SIGPIPE ignored.
- `ACPEngineClient.swift` — hand-rolled thin NDJSON JSON-RPC stdio client (`hermes acp -p <profile>`; no Swift SDK exists), conforming to `EngineTransport` (notifications arrive on the `onMessage` property — always set before `start()`). Wire facts: stdout = wire, stderr = logs (never parsed for state); `session/new` REQUIRES `mcpServers` (Museion sends `[]`); `session/cancel` is a notification; requests time out (15 s default); crash/EOF fail pending requests and fire `onCrash` exactly once (latched); `close()` = handlers-off → SIGTERM → grace → SIGKILL → reap; SIGPIPE ignored. brief-27: stdin writes AND the stdin write-handle close ride a dedicated serial `writerQueue` — the state queue NEVER touches the pipe, so a full pipe (hung engine) can block a send but never a deadline, Stop delivery, or teardown.
- `MentorSessionModel.swift` — @MainActor @Observable, and the ONLY observable the panes see (#178: engine processes live behind `EngineHost` — the model holds no transport, spawns nothing, and stays session + turn coordination; panes never touch the host). Lazy open on first `openSession()` (hosted-guarded; resumes the newest roster entry — a fresh transcript over an engine that knows the session would prompt/fork against unloaded state); spawn/handshake/teardown route through `host` (`startChat()` answers the engine version + the advisory drift note the pane displays). `sendPrompt` returns a `TurnOutcome` (a response missing `stopReason` maps to `.failed` — it never advances a pass); thought chunks stream to their OWN buffer (a collapsed `.thought` row, never the critique text); prompts ride a 1800 s timeout (the response arrives when the TURN ends, minutes into a pass); tool payloads decode through `ToolPayloads` (#177 — nested card-rail shape, flat fallback). #177 typed rail: text rows carry `(body, speaker, notice)` — `Speaker` agent|user|system, `NoticeKind` refused|interrupted|connectionLost|kickoff|failed|plain — typed at EVERY append site, never a stored `"Mentor: "`/`"You: "` prefix; the two wire-only classifications are sniffed ONCE at the append seam (`replayedUserContent` — a replayed "Pass Pass N…" kick-off → system/kickoff; `agentSpeakerNotice` — "Operation interrupted:" → system/interrupted); the refusal and connection-lost rows are agent-voice by pinned render; `draftCandidateText` is pure over `.agent, .plain` rows. Sessions: MULTIPLE engine-owned sessions on the one bridge; `SessionRoster` persists NAMES ONLY (id/name/pieceTitle/createdAt; transcripts are engine-owned per ADR-0007, replayed on demand); resume accepts BOTH load-response shapes (the real 0.21.5 id rides `_meta.hermes.sessionProvenance`; empty-everywhere = engine unknown → honest refusal row, never a fabricated session); fork/compact/brainstorm ride the same rails; research candidates route by PAYLOAD SHAPE (a top-level `notes` array) BEFORE the fix-card parse — titles are display text, never a routing key; candidates are session cargo (dispositions reset on resume). Per-surface engines (ADR-0014): passes and Blind Read run on ONE private one-shot rail (`runOneShot` → `host.withOneShot`, spawn per run + teardown at the verdict) into a TRANSIENT unrostered transcript (passes never mint sessions); the turn pipeline is one shared `turnCore`; `restart()`/`requestRestart()` share `respawn()` (deferred to turn end while streaming; resumes the PRE-restart active session; teardown + fresh spawn ride `host.killChat()`/`host.startChat()`). `PassReadiness` per kind (the enum + refresh live in `PassReadiness.swift`, #181 — the model only stores): `missingKey` names the provider and `runPass` guards it after the shared open-piece rail (still before anything touches disk); `.unknown` never blocks; credentials resolve through `ProviderCredential` (the Portal login path injectable).
- `MentorPaneView.swift` — header (serif title + engine status + session chip; ready = the semantic green dot + lowercase `ready`), shared transcript + composer (`SessionTranscriptView` — one conversation surface, two panes; interpreted markdown opens http(s) ONLY, every other scheme discards), crash card, `PassBarView` (Pass 1/2 tabs, token estimate, Cancel ↔ Blind Read ↔ Run Pass — disabled states carry the reason; the missing-key line links to Settings), the Fix Cards palette (a floating window; open cards first; **Apply = ask-before** — a blocking sheet showing the exact edit, never apply-all; demonstration → Done; stale anchor → Skip only; Promote = one confirm), and research candidate cards (Keep = ask-before sheet → `writeResearchNote`; Reject = no confirm).
- Wiring: `AppGateState.mentor` is the app-scoped model; quit teardown on `NSApplication.willTerminateNotification` → `mentor.shutdown()` (idempotent — scenePhase `.inactive` would fire on plain focus loss).
+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))
}
}
@@ -0,0 +1,53 @@
# ACP backpressure — a blocked stdin writer can no longer defeat deadlines, Stop, or close
> **Date:** 2026-11-17
> **Type:** fix (availability — APP-DOWN class)
> **Reference:** brief-27 `museion/acp-backpressure-defeats-timeout-and-shutdown` (unticketed; argus cycle-4 dedicated bugs pass, finding 3 — `~/argus-audits/audit/2026-11-16/museion-bugs.md`). Base `bb4bfa2675c3fd2776bd0235c01010baec2290df` (museion main tip at claim, re-verified via tea api + fetch). Scan SHA `11b196d6` — both touched source files byte-identical between scan SHA and base.
## Finding
A hung engine that stops reading stdin fills the 64 KB pipe, and `ACPEngineClient.send`'s synchronous `fileHandleForWriting.write` blocked the client's ONE serial queue — the same queue that carries request-id allocation, pending-registration, the `asyncAfter` deadline, and `close()`'s opening `queue.sync` barrier. A blocked writer therefore defeated the request timeout (the deadline sat queued behind the stuck send), starved Stop/lifecycle calls (a follow-up request hung at id-allocation `queue.sync`), and made `close()` block behind the write before SIGTERM/SIGKILL was ever reachable. `EngineHost`'s close callers (`killChat`, `withOneShot` defer, `shutdownAll`) run on MainActor — engine backpressure became an app-wide unbounded hang on restart/quit. Argus executed the repro standalone: complete HEAD `ACPEngineClient.swift` in an isolated process, child argv swapped to `/bin/sleep 30` (inert non-reading child), 2M-char request at timeout 0.1 s — no request completion, and an independent watchdog's `close()` never returned (probe killed at 12 s).
## What Was Done
- **Fix** (`Museion/ACPEngineClient.swift`, +34/−8): stdin writes — and the stdin write-handle's own close — moved off the state queue onto a dedicated serial `writerQueue`. `request`/`notify`/`dispatch`'s server-reply all funnel through it (wire order preserved: one serial FIFO queue, same enqueue-order semantics as before). The state queue is now I/O-free: id allocation, registration, deadlines, and `close()`'s bookkeeping barrier always run; `close()` then does SIGTERM → 1 s grace → SIGKILL → reap without ever queueing behind the writer. The stdin write-handle close rides the writer queue (a blocked write may still own the handle — closing under a live write would race Foundation); it unblocks with EPIPE once the child's read end died, which the kill just arranged. Reader handles close on the caller as before (handlers off first, no writers exist for them).
- **Rig** (`MuseionTests/ACPClientTests.swift`): two new zsh-fake modes. `neverRead` — execs `/bin/sleep 30` without reading a line (the probe's inert non-reading child; exec keeps sleep the DIRECT child so close's SIGTERM reaches it and no orphan holds the pipe); `serverPing` — full behaviour plus one server→client request (id 900) emitted at initialize, logging our reply line to `<name>-reply-log` (the reply-delivery observable).
- **Smokes** (`MuseionTests/EngineSmokeTests.swift`, +4): (1) request deadline fires while the stdin write is blocked (0.5 s deadline, 2M-char prompt, 5 s bounded window); (2) Stop accepted + bookkeeping answers while blocked (`session/cancel` notify returns, a follow-up request registers and reaches its OWN deadline); (3) close returns bounded while blocked (5 s window) and reaps the child; (4) healthy contract unchanged — round trip (initialize → 9.9.9), -32601 reply delivery over the real wire, idempotent clean close with reap. `awaitBounded` helper = the bounded window (house one-deadline rule); teardown in every blocked-writer smoke SIGKILLs the rig child FIRST so the base tree also settles without hanging the runner.
## Site-class enumeration (mandate — re-derived, seed not ceiling)
Included (fixed): all four `send` call sites (request L177-ish, notify L197-ish, dispatch server-reply L317-ish — the seeded set) plus the deadline scheduling and both `request`-path `queue.sync`s and `close()`'s barrier — all healed by the same writer-queue separation; the direct server-request reply path rides the same `send` (no second site to mint, as the brief noted).
Disproved with evidence:
- `EngineGate.execute` pre-spawn stdin write (EngineGate.swift:99-110): not queue-bound, and the write lands BEFORE `process.run()` — the reader does not exist yet, so it cannot block behind a hung engine; the in-source ceiling note (keep payloads well under 64 KB) plus the watchdog own it.
- `EngineGate.terminateAndReap` (EngineGate.swift:145-155): SIGTERM → grace → SIGKILL → reap with NO preceding queue.sync — nothing can block before it.
- `ReadingPresenter` apex render (ReadingPresenter.swift:137-154): a one-shot synchronous render helper (write → closeFile → waitUntilExit is the operation itself); no transport/lifecycle queue, no deadline machinery being defeated — adjacent, out of class.
- `MCPServer` fflush(stdout) (MCPServer.swift:39): the app IS the child there; no engine pipe parenting — out of class.
- `ScriptedEngine` (MuseionTests): mirrors the client's queue shape exactly, but performs zero FileHandle I/O (in-process) — its `queue.sync`s can never block on a pipe.
- `EngineHost` seeded sites (killChat 175-178, withOneShot defer 204-207, shutdownAll 223-227): synchronous close callers; post-fix they call a bounded close (bookkeeping sync on an I/O-free queue; ≤1 s SIGTERM-grace worst case + reap). No EngineHost change required — see Decisions.
## Gates
- Focused serialized `EngineSmokeTests` at base (RED commit `33b7fe0`): **6 executed / 3 passed / 3 failed** — exactly the three blocked-writer smokes failed, on mechanism (deadline expectation nil after 5 s; bookkeeping expectation nil; `finished != nil` false). Healthy-contract smoke + both existing surface smokes passed at base.
- Focused serialized `EngineSmokeTests` at fix (`89cd377`): **6 executed / 6 passed / 0 failed** (exit 0). Per-test: deadline 0.539 s, stop/bookkeeping 0.733 s, close bounded 0.232 s, healthy 0.195 s.
- Full suite at fix head via the rail (run dir `20261117T212755Z-Museion-serialized`): **697 executed / 697 passed / 0 failed / 0 skipped, xcodebuild exit 0** (xcresult-authoritative; the four new smokes' started/passed lines verified in the run log).
- swiftformat `0/149 files formatted`; swiftlint zero violations (repo gate is zero, not net-zero — base was clean).
- GitNexus: `analyze --skip-agents-md` in the worktree (AGENTS.md untouched); impact on every edited symbol — `send` LOW (5), `dispatch` LOW (3), `notify` LOW (0), `close` LOW (0), `request` UNKNOWN/0 (callers ride the EngineTransport existential; graph doesn't connect protocol witnesses) — no HIGH/CRITICAL, no user warning owed; detect-changes at the fix: 1 file / 8 symbols / 1 affected process (the transport), medium, expected.
## Decisions & Rationale
| Decision | Rationale |
|----------|-----------|
| Dedicated serial writer queue, blocking writes kept | Boring over clever: nonblocking fd + DispatchSourceWrite drain would add partial-write buffering and source lifecycle for zero additional contract (the API-level guarantees all hold once the state queue is I/O-free). A blocked writer now wedges only itself — it cannot pin a deadline, Stop, or close. |
| stdin write-handle closes ON the writer queue | After kill+reap a blocked write may still be in `write(2)` (unblocks on read-end death); Foundation FileHandle is not safe under concurrent write+close. The close job queues behind the last write — close() itself has already returned. Residual: a pathologic grandchild holding the pipe's read end past the child's death pins one writer-queue worker until it exits; the client is closed and reaped regardless. |
| `exec /bin/sleep` in neverRead (not `sleep 30` as a zsh child) | exec makes sleep the direct child: close's SIGTERM reaches it, and no orphan holds the pipe open — the smoke's teardown leaves nothing behind on either tree. |
| Case (2) pinned as accepted+unstarved, not bytes-delivered | The bytes cannot reach a non-reading child — the pipe is full; that is physics, identical before and after. "Deliverable" means the seam accepts the notification and lifecycle bookkeeping still answers; the RED leg (follow-up request registration starving at `queue.sync`) is the un-fixed behavior. |
| EngineHost left untouched; close stays synchronous but bounded | The fix direction's "no MainActor-blocking close path remains" read against the finding (backpressure → unbounded hang): the writer can no longer defeat close, and close is bounded (ms when the child honors SIGTERM; ≤ ~1 s grace + reap worst case). Making killChat/shutdownAll hop off MainActor would drop the reaped-before-return guarantee the teardown smokes pin (and the quit path relies on) — an EngineHost API change out of this finding's scope, disclosed to the dispatcher instead. |
| Zsh fake modes, never a real profile | Brief's probe discipline: the only child ever spawned by the dead-child tests is our own zsh fake execing /bin/sleep (pre-validated standalone: ps shows `/bin/sleep`, a 2 MB stdin write blocks, serverPing round-trips the -32601 reply). |
## Disclosures
- First focused RED run died at COMPILE (my `Task<String?, Never>` made `awaitBounded`'s `T?` a double optional — two `error:` lines, zero tests executed, the rail's vacuous guard caught it as 0-executed/exit 65). Fixed to `Task<String, Never>`; the recorded RED run is the second, clean one.
- No testmanagerd wedge encountered this brief (the known hazard did not fire; runs sequenced behind @athena's classis brief-26 verify, which finished 22:21:15 exit 0 before my first xcodebuild).
- AGENTS.md DOX updates (Museion/AGENTS.md ACP-bridge bullets, MuseionTests/AGENTS.md suite-map lines) are consent-gated → owner-apply patch beside the handoff, `git apply --check` clean vs branch head; the root AGENTS.md session-log 10-row window is left for the write-log tooling (INDEX.md carries the durable row).
- Docs commit (CHANGELOG + devlog + INDEX) is docs-only; the 697/697 suite ran at its parent (the fix commit) — code identical.
+1
View File
@@ -5,6 +5,7 @@ Complete history of session logs in this directory, newest first. One-line summa
<!-- write-log: full-index -->
| Date | Type | File | Summary |
|------|------|------|---------|
| 2026-11-17 | fix | [20261117-acp-backpressure-defeats-timeout-and-shutdown_log.md](20261117-acp-backpressure-defeats-timeout-and-shutdown_log.md) | Unticketed fix (brief-27, argus cycle-4): stdin writes move to a dedicated writer queue — engine backpressure can no longer defeat the request deadline, Stop, or a bounded reaping close; neverRead/serverPing fake modes, 3 RED-first smokes + healthy-contract pin, suite 697/697 |
| 2026-11-17 | issue | [20261117-issue193-split-fat-files-along-postsmodel-pattern_log.md](20261117-issue193-split-fat-files-along-postsmodel-pattern_log.md) | Three most-re-read files split into 8 domain-extension files, move-only (three audits concur); 693/693 |
| 2026-11-17 | issue | [20261117-issue192-collapse-gate-running-learnings-into-verify-rail-pointer_log.md](20261117-issue192-collapse-gate-running-learnings-into-verify-rail-pointer_log.md) | Root gate-running learnings collapse into the full-test.sh pointer; 8 deletions mapped to script/hook behavior; authoring rules retained; 693/693 |
| 2026-11-17 | issue | [20261117-issue197-repo-wide-swiftlint-green-documented-lint-contract_log.md](20261117-issue197-repo-wide-swiftlint-green-documented-lint-contract_log.md) | Lint-green doc truth (#197) + finish-audit; watcher-race test quiesced, symlink pin flip-verified, stale-xcodebuild hazard found; 693/693 |