diff --git a/.changeset/3488-pi-teardown-reconciler-handoff.md b/.changeset/3488-pi-teardown-reconciler-handoff.md new file mode 100644 index 0000000000..42c43170bc --- /dev/null +++ b/.changeset/3488-pi-teardown-reconciler-handoff.md @@ -0,0 +1,5 @@ +--- +"@schlessera/brain-backend-pi": patch +--- + +A pi worker's refused turn-temp close now passes to the cleanup reconciler only once the teardown that awaited it has ended (#3488). Before, the hand-off happened when the close was refused. Both the loser of a concurrent duplicate resume and a prompted turn still wait for the bounded stdio release after that close, so a reconciler retry that came due during the release made a second close attempt before the busy refusal or the turn settled. The order of exit, close and stdio release is unchanged. A refused close still keeps its reservation charged, is still reported, and is still retried by the reconciler and by a later abort. diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index 261cdcb646..7373e6cdc9 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -1586,7 +1586,7 @@ model-directed code runs. The host accepts a count of zero as extension-free and any other count as unproven, whatever the configuration said; a worker that sends no count keeps the configuration's answer (`function createExecutionProof`, -`packages/ui-backend-pi/src/worker-session.ts:253-259`). An installed or +`packages/ui-backend-pi/src/worker-session.ts:257-263`). An installed or repo-local extension is counted, and the managed worker then refuses the turn anyway (`function unqualifiedResources`, `packages/ui-backend-pi/src/native-session-runtime.ts:143-145`). @@ -4040,11 +4040,11 @@ the path's existing cancellation or failure outcome. to pi cancellation before `prompt()`. The pool owns a late new or resumed acquisition until its awaited abort finishes, then disposes it and preserves the accepted cancellation (`cancelAcquiredSession`, -`packages/ui-backend-pi/src/session-pool.ts:176-183`). After acquisition the +`packages/ui-backend-pi/src/session-pool.ts:177-184`). After acquisition the runner awaits abort when cancellation prevents prompting. The signal handler may already have requested it, so the worker session shares one abort promise: `ended` revokes work but does not confirm teardown (`abort()`, -`packages/ui-backend-pi/src/worker-session.ts:212-228`). Its inactive path +`packages/ui-backend-pi/src/worker-session.ts:218-236`). Its inactive path awaits exit and protocol consumption, the awaited turn-temp close above, then stdio release even if exit or cleanup refuses. Failed cleanup keeps the reservation charged and remains retryable. Disposal and Stop signalling keep @@ -4055,9 +4055,13 @@ rule to the loser of two concurrent resumes of one session. The pool decides busy or reuse, and claims a reused entry, before it waits. It then awaits the losing worker's shared inactive abort, disposes it and re-raises the original outcome (`releaseLosingSession`, -`packages/ui-backend-pi/src/session-pool.ts:150-157`). A refused cleanup is +`packages/ui-backend-pi/src/session-pool.ts:151-158`). A refused cleanup is logged as a warning and cannot replace the busy refusal; the reservation stays -charged and the abort stays retryable. +charged and the abort stays retryable. That inactive abort, like a prompted +turn's teardown, still waits for stdio release after its turn-temp close, so the +supervision hands a refused close to the reconciler only once that teardown ends +(`const teardown`, `packages/ui-backend-pi/src/worker-launch.ts:343-350`). The +reconciler's timed retry cannot make a second attempt inside it. ### Outward actions (G5) diff --git a/packages/ui-backend-pi/src/worker-launch.ts b/packages/ui-backend-pi/src/worker-launch.ts index edb8a1fd10..b86190d089 100644 --- a/packages/ui-backend-pi/src/worker-launch.ts +++ b/packages/ui-backend-pi/src/worker-launch.ts @@ -294,6 +294,13 @@ export interface PiWorkerSupervision { * make the owner's awaited close a second attempt (#3544). */ claimTurnTempClose(): void; + /** + * Runs an owner's teardown — a prompted turn's, an inactive abort's — that + * still waits for stdio release after its turn-temp close. A close refused + * inside it passes to the cleanup reconciler only once it ends, so the + * reconciler's timed retry cannot add an attempt while it settles (#3488). + */ + teardown(run: () => Promise): Promise; /** The tail of the worker's stderr. */ diagnostic(): string; reportLimitHits(): void; @@ -323,13 +330,23 @@ export function superviseWorker(worker: { child: LaunchedWorker; reservation: Re const activity = env.cleanupActivity ?? turnContext.bridge?.activity; const cleanup = { bytes: held.bytes, turnTempBytes: held.turnTempBytes, close: () => closeStorage(), release: releaseReservation, report: (notice: import("@schlessera/brain-ui-sdk/internal").CleanupNotice) => activity?.({ kind: "worker_cleanup", ...notice }) }; + const handOff = (error: unknown) => (worker.cleanup ?? processCleanupReconciler()).retain(cleanup, error); + let tearingDown = 0; + let deferred: { error: unknown } | undefined; const closeStorage = (): Promise => turnTempClosing ??= (async () => { await turnTemp?.closeAsync(); })() .catch((error: unknown) => { turnTempClosing = undefined; - (worker.cleanup ?? processCleanupReconciler()).retain(cleanup, error); + if (tearingDown) deferred = { error }; else handOff(error); throw error; }); const closeTurnTemp = async () => { await closeStorage(); releaseReservation(); }; + const teardown = async (run: () => Promise): Promise => { + tearingDown++; + try { await run(); } + finally { + if (--tearingDown === 0 && deferred) { const { error } = deferred; deferred = undefined; handOff(error); } + } + }; // The turn_temp tool reaches this worker's /tmp only while it runs (#1703). let workerLive = true; void child.exited.finally(() => { workerLive = false; }).catch(() => {}); @@ -387,5 +404,5 @@ export function superviseWorker(worker: { child: LaunchedWorker; reservation: Re * settle only after this, which resolves once they are closed or its bound expires. */ const stdioReleased = (): Promise => { child.stdin.end(); return child.released(); }; - return { closeTurnTemp, releases, claimTurnTempClose: () => { claimed = true; }, diagnostic: () => diagnostic, reportLimitHits, limitEnded, send, stdioReleased }; + return { closeTurnTemp, releases, claimTurnTempClose: () => { claimed = true; }, teardown, diagnostic: () => diagnostic, reportLimitHits, limitEnded, send, stdioReleased }; } diff --git a/packages/ui-backend-pi/src/worker-session.ts b/packages/ui-backend-pi/src/worker-session.ts index f849e36db2..7c85060b7f 100644 --- a/packages/ui-backend-pi/src/worker-session.ts +++ b/packages/ui-backend-pi/src/worker-session.ts @@ -116,7 +116,7 @@ export async function openPiWorkerSession(backend: CreatePiBackendOptions, sessi const { workerSandbox, workerLock, workerSignal, toolExecution } = admission.hostEnv; const { child, sandbox, sandboxNote, turnTemp } = await launchPiWorker({ backend, env, admission, restricted, resumeId, execHelpers, confirmPatterns, startupStarted, turnContext }); - const { closeTurnTemp, releases, claimTurnTempClose, diagnostic, reportLimitHits, limitEnded, send, stdioReleased } = superviseWorker({ child, reservation, + const { closeTurnTemp, releases, claimTurnTempClose, teardown, diagnostic, reportLimitHits, limitEnded, send, stdioReleased } = superviseWorker({ child, reservation, turnTemp, env, turnContext, admission, answerText: () => receipts.answerText() }); function live(): void { if (!state.active || state.ended || !turnContext.bridge || !turnContext.signal || turnContext.signal.aborted) { @@ -208,8 +208,10 @@ export async function openPiWorkerSession(backend: CreatePiBackendOptions, sessi try { send({ type: "prompt", text: state.ownedPrompt?.text ?? text, options }); await done.promise; } finally { child.stdin.end(); child.kill("SIGKILL"); - try { await child.exited; await received; await receipts.promote({ turnTemp, sandbox, closeTurnTemp }); } - finally { try { await closeTurnTemp(); } finally { await stdioReleased(); } } + await teardown(async () => { + try { await child.exited; await received; await receipts.promote({ turnTemp, sandbox, closeTurnTemp }); } + finally { try { await closeTurnTemp(); } finally { await stdioReleased(); } } + }); } if (state.error) throw state.error; }, @@ -219,8 +221,10 @@ export async function openPiWorkerSession(backend: CreatePiBackendOptions, sessi return aborting ??= (async () => { if (!state.active) { state.ended = true; claimTurnTempClose(); child.stdin.end(); child.kill("SIGKILL"); - try { await child.exited; await received; } - finally { try { await closeTurnTemp(); } finally { await stdioReleased(); } } + await teardown(async () => { + try { await child.exited; await received; } + finally { try { await closeTurnTemp(); } finally { await stdioReleased(); } } + }); return; } if (state.ended) return; diff --git a/packages/ui-backend-pi/tests/duplicate-acquisition.test.ts b/packages/ui-backend-pi/tests/duplicate-acquisition.test.ts index 49c53d205c..1cf23b5f73 100644 --- a/packages/ui-backend-pi/tests/duplicate-acquisition.test.ts +++ b/packages/ui-backend-pi/tests/duplicate-acquisition.test.ts @@ -5,7 +5,9 @@ * result, a per-session busy refusal with no frames, and only the loser stopped. * #3488: the refusal settles only after the loser's worker has exited, its turn * temp is closed and its stdio release is awaited; a refused close is reported - * without replacing the refusal and stays retryable. + * without replacing the refusal and stays retryable. Its reconciler retry is + * handed over only after the teardown's last wait, so a retry that comes due + * while the stdio release is still in flight cannot add a second close. */ import { afterEach, expect, spyOn, test } from "bun:test"; import { mkdirSync, mkdtempSync, rmSync } from "node:fs"; @@ -55,6 +57,12 @@ for (const refused of [false, true]) test.skipIf(!native)(`a concurrent duplicat const log = (level: string, message: string) => { if (level === "warn") warnings.push(message); }; const cleanupRefusal = Object.assign(new Error("worker_identity_cleanup_unconfirmed: Odysseus fixture"), { cleanupUnconfirmed: true }); const baseline = worker.processStateLedger().turnTempHeld; + // The process reconciler's first retry comes due after a real second. Here a + // test-controlled schedule makes "it came due during the release" exact. + const retries: Array<() => void> = []; + const reconciler = worker.createCleanupReconciler({ schedule: run => { retries.push(run); return () => {}; }, log() {} }); + const owner = spyOn(worker, "processCleanupReconciler").mockReturnValue(reconciler); + cleanup.push(() => { reconciler.close(); owner.mockRestore(); }); const workers: Launched[] = []; const realLaunch = worker.launchAgentWorkerAsync; @@ -65,7 +73,12 @@ for (const refused of [false, true]) test.skipIf(!native)(`a concurrent duplicat workers.push(record); const kill = child.kill.bind(child), release = child.released.bind(child), turnTemp = child.turnTemp; child.kill = signal => { record.kills++; return kill(signal); }; - child.released = async () => { record.releases++; await release(); record.released++; }; + child.released = async () => { + record.releases++; + // Every retry already due fires while this release is in flight. + if (record.refuseClose) for (const run of retries.splice(0)) run(); + await release(); record.released++; + }; if (turnTemp) child.turnTemp = Object.assign(Object.create(Object.getPrototypeOf(turnTemp)), turnTemp, { closeAsync: async () => { record.closes++; if (record.refuseClose) throw cleanupRefusal; return turnTemp.closeAsync(); } }); return child; @@ -139,6 +152,8 @@ for (const refused of [false, true]) test.skipIf(!native)(`a concurrent duplicat if (refused) { expect(held, "PI_DUPLICATE_RESUME_REFUSED_LOSER_KEEPS_RESERVATION").toBe(bothHeld); expect(warnings.filter(message => message.includes(cleanupRefusal.message)), "PI_DUPLICATE_RESUME_REFUSED_LOSER_CLEANUP_REPORTED").toHaveLength(1); + expect(reconciler.held, "PI_DUPLICATE_RESUME_REFUSED_LOSER_HAS_RETRY_OWNER").toBe(1); + expect(retries, "PI_DUPLICATE_RESUME_REFUSED_LOSER_RETRY_SCHEDULED_AFTER_TEARDOWN").toHaveLength(1); } else { expect(held, "PI_DUPLICATE_RESUME_LEDGER_CHARGES_ONLY_WINNER").toBe(bothHeld / 2); expect(warnings, "PI_DUPLICATE_RESUME_CONFIRMED_LOSER_NO_WARNING").toEqual([]); diff --git a/packages/ui-backend-pi/tests/worker-session.test.ts b/packages/ui-backend-pi/tests/worker-session.test.ts index c78195ef5c..7f14b75629 100644 --- a/packages/ui-backend-pi/tests/worker-session.test.ts +++ b/packages/ui-backend-pi/tests/worker-session.test.ts @@ -229,6 +229,32 @@ test("Pi releases a turn's turn-temp reservation only once its awaited close con expect(worker.processStateLedger().turnTempHeld, "PI_CONFIRMED_RETRY_RELEASES_RESERVATION").toBe(baseline); expect(closes).toBe(2); }); +test("a prompted Pi turn hands its refused turn-temp close to the reconciler only after its stdio release (#3488)", async () => { + const base = launch.getMockImplementation()!; + // The reconciler's first retry comes due after a real second; this schedule + // fires it exactly while the turn's stdio release is in flight. + const retries: Array<() => void> = []; + const cleanup = worker.createCleanupReconciler({ schedule: run => { retries.push(run); return () => {}; }, log() {} }); + const owner = spyOn(worker, "processCleanupReconciler").mockReturnValue(cleanup); + const baseline = worker.processStateLedger().turnTempHeld; + let closes = 0; + launch.mockImplementation(async (...args: unknown[]) => ({ ...await base(...args), + released: async () => { for (const run of retries.splice(0)) run(); }, + turnTemp: { root, space: () => ({ total: 0, free: 0 }), + async closeAsync() { if (++closes <= 2) throw Object.assign(new Error("worker_identity_cleanup_unconfirmed: fixture"), { cleanupUnconfirmed: true }); } } })); + try { + await turn(null); + // promote's close and the teardown's own retry; no reconciler attempt inside the turn. + expect(closes, "PI_PROMPTED_TEARDOWN_CLOSES_ONLY_IN_FOREGROUND").toBe(2); + expect(cleanup.held, "PI_PROMPTED_REFUSAL_HAS_RETRY_OWNER").toBe(1); + expect(retries, "PI_PROMPTED_RETRY_SCHEDULED_AFTER_TEARDOWN").toHaveLength(1); + expect(worker.processStateLedger().turnTempHeld, "PI_PROMPTED_REFUSAL_KEEPS_RESERVATION").toBeGreaterThan(baseline); + retries.shift()!(); await Bun.sleep(0); + expect(closes).toBe(3); + expect(cleanup.held).toBe(0); + expect(worker.processStateLedger().turnTempHeld, "PI_PROMPTED_RECONCILED_CLOSE_RELEASES_RESERVATION").toBe(baseline); + } finally { cleanup.close(); owner.mockRestore(); } +}); for (const ending of ["inactive abort", "initialization failure"] as const) test(`a Pi worker that never ran a turn awaits its turn-temp close on ${ending} (#2854)`, async () => { const base = launch.getMockImplementation()!; const gate = Promise.withResolvers();