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
Showing only changes of commit 89cd377814 - Show all commits
+32 -6
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
@@ -174,7 +183,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 +205,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 +242,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 +258,14 @@ 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) {
writerQueue.async {
var framed = Data(data)
framed.append(0x0A)
try? stdinPipe.fileHandleForWriting.write(contentsOf: framed)
try? self.stdinPipe.fileHandleForWriting.write(contentsOf: framed)
}
}
/// Fail every pending request and surface the crash — the one exit path