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
CI / ci (push) Canceled after 0s
This commit was merged in pull request #199.
This commit is contained in:
commit
55be3d1a2f
8 files changed
+292
-10
No files matched your search
@@ -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
@@ -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).
|
||||
|
||||
Reference in new issue
Block a user