From e73a9def3f957bc47c5553c363d768c750ca400d Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 3 Nov 2026 14:12:43 +0000 Subject: [PATCH 1/3] fix(backend-claude): retry a refused end-of-turn worker cleanup and release its reservation once confirmed A Claude turn whose worker handle cleanup is refused still fails and keeps its runtime-state reservation charged (#2854), but now hands the retryable close and the reservation to a process-owned reconciler. It retries with finite attempts and capped exponential backoff, releases exactly once only after a confirmed close, logs a terminal failure with the allowance it keeps charged, and on shutdown stops retrying, reports what is held and releases nothing. Refs #2871 Co-Authored-By: Claude Opus 5.5 --- .../src/cleanup-reconciler.ts | 137 ++++++++++++++ .../ui-backend-claude/src/worker-spawn.ts | 24 ++- .../tests/cleanup-reconciler.test.ts | 168 ++++++++++++++++++ .../tests/worker-cleanup.test.ts | 16 +- 4 files changed, 335 insertions(+), 10 deletions(-) create mode 100644 packages/ui-backend-claude/src/cleanup-reconciler.ts create mode 100644 packages/ui-backend-claude/tests/cleanup-reconciler.test.ts diff --git a/packages/ui-backend-claude/src/cleanup-reconciler.ts b/packages/ui-backend-claude/src/cleanup-reconciler.ts new file mode 100644 index 0000000000..50b3d956aa --- /dev/null +++ b/packages/ui-backend-claude/src/cleanup-reconciler.ts @@ -0,0 +1,137 @@ +/** + * The owner of a refused end-of-turn worker cleanup (#2871). + * + * A Claude turn awaits its worker's handle cleanup before it releases the + * turn's runtime-state reservation, and an unconfirmed close keeps that + * reservation charged (#2854). The turn still fails, and nothing of the turn + * waits for this owner. It retains the retryable close and the reservation, + * retries the close a finite number of times with backoff, and releases the + * reservation exactly once, only after a close is confirmed. A retry that is + * still refused after the last attempt is logged with the allowance it keeps + * charged. Shutdown stops the retries, reports what is still held and + * releases nothing. + */ +import { mib } from "@schlessera/brain-ui-sdk/internal"; + +/** One refused cleanup, handed over by the turn that could not confirm it. */ +export interface RetainedCleanup { + /** The runtime-state bytes the reservation keeps charged. */ + readonly bytes: number; + /** The turn-temp bytes the reservation keeps charged. */ + readonly turnTempBytes: number; + /** Resolves only once the cleanup is confirmed; rejects, retryably, while it is not. */ + close(): Promise; + /** Releases the reservation; called once, after a confirmed close. */ + release(): void; +} + +export interface CleanupReconcilerOptions { + /** Retries before a refusal is terminal. */ + attempts?: number; + /** The delay before the first retry; each later one doubles it. */ + baseDelayMs?: number; + /** The longest delay between two retries. */ + maxDelayMs?: number; + /** Host diagnostics; never the wire. */ + log?: (message: string, error?: unknown) => void; + /** Schedules a retry and returns its cancel. Defaults to an unreferenced timer, so a retry never holds the process open. */ + schedule?: (run: () => void, delayMs: number) => () => void; +} + +export interface CleanupReconciler { + /** Takes ownership of a refused cleanup and its reservation. */ + retain(cleanup: RetainedCleanup): void; + /** Cleanups still charged, retrying or terminal. */ + readonly held: number; + /** + * Stops every retry without releasing anything or waiting for a close in + * flight, and logs what is still charged. Idempotent. + */ + close(): { held: number; bytes: number; turnTempBytes: number }; +} + +export const CLEANUP_RETRY_ATTEMPTS = 5; +export const CLEANUP_RETRY_BASE_MS = 1_000; +export const CLEANUP_RETRY_MAX_MS = 30_000; + +const unreferencedTimer = (run: () => void, delayMs: number) => { + const timer = setTimeout(run, delayMs); + (timer as { unref?: () => void }).unref?.(); + return () => clearTimeout(timer); +}; + +const allowance = (bytes: number, turnTempBytes: number) => + `${mib(bytes)} of runtime state and ${mib(turnTempBytes)} of turn temp`; + +export function createCleanupReconciler(options: CleanupReconcilerOptions = {}): CleanupReconciler { + const attempts = options.attempts ?? CLEANUP_RETRY_ATTEMPTS; + const baseDelayMs = options.baseDelayMs ?? CLEANUP_RETRY_BASE_MS; + const maxDelayMs = options.maxDelayMs ?? CLEANUP_RETRY_MAX_MS; + const log = options.log ?? ((message: string, error?: unknown) => { + if (error === undefined) console.error(message); else console.error(message, error); + }); + const schedule = options.schedule ?? unreferencedTimer; + /** Every cleanup still charged, with its pending retry's cancel, if any. */ + const held = new Map void) | undefined>(); + let closed = false; + + const attempt = (cleanup: RetainedCleanup, made: number) => { + held.set(cleanup, undefined); + void (async () => { + try { await cleanup.close(); } + catch (error) { + if (closed || !held.has(cleanup)) return; + if (made + 1 < attempts) { plan(cleanup, made + 1); return; } + // Terminal: the allowance stays charged until the server restarts. + log(`Claude worker cleanup is still unconfirmed after ${attempts} retries; ` + + `${allowance(cleanup.bytes, cleanup.turnTempBytes)} stay charged until the server restarts.`, error); + return; + } + // Shutdown releases nothing, even a close confirmed after it began. + if (closed || !held.delete(cleanup)) return; + cleanup.release(); + })(); + }; + + const plan = (cleanup: RetainedCleanup, made: number) => { + const delay = Math.min(baseDelayMs * 2 ** made, maxDelayMs); + held.set(cleanup, schedule(() => { if (!closed && held.has(cleanup)) attempt(cleanup, made); }, delay)); + }; + + return { + get held() { return held.size; }, + retain(cleanup) { + if (held.has(cleanup)) return; + if (closed) { + held.set(cleanup, undefined); + log(`Claude worker cleanup is unconfirmed during shutdown; ${allowance(cleanup.bytes, cleanup.turnTempBytes)} stay charged.`); + return; + } + if (attempts <= 0) { held.set(cleanup, undefined); return; } + plan(cleanup, 0); + }, + close() { + let bytes = 0, turnTempBytes = 0; + for (const [cleanup, cancel] of held) { cancel?.(); held.set(cleanup, undefined); bytes += cleanup.bytes; turnTempBytes += cleanup.turnTempBytes; } + const summary = { held: held.size, bytes, turnTempBytes }; + if (!closed && summary.held) { + log(`Claude worker cleanup reconciliation stopped with ${summary.held} unconfirmed cleanup${summary.held === 1 ? "" : "s"} ` + + `still holding ${allowance(bytes, turnTempBytes)}.`); + } + closed = true; + return summary; + }, + }; +} + +// One per process, as the ledger it releases into is (`processStateLedger`). +const PROCESS_RECONCILER = Symbol.for(["@schlessera", "brain-backend-claude", "cleanup-reconciler"].join("/")); +/** The server process's one reconciler; it stops and reports when the process exits. */ +export function processCleanupReconciler(): CleanupReconciler { + const slot = globalThis as { [PROCESS_RECONCILER]?: CleanupReconciler }; + if (!slot[PROCESS_RECONCILER]) { + const reconciler = slot[PROCESS_RECONCILER] = createCleanupReconciler(); + process.once("exit", () => { reconciler.close(); }); + } + return slot[PROCESS_RECONCILER]; +} diff --git a/packages/ui-backend-claude/src/worker-spawn.ts b/packages/ui-backend-claude/src/worker-spawn.ts index ecf15eca59..3eee86fc65 100644 --- a/packages/ui-backend-claude/src/worker-spawn.ts +++ b/packages/ui-backend-claude/src/worker-spawn.ts @@ -13,6 +13,7 @@ import { prepareRecoveredWorkerFiles, workerExecHelpers, createTurnTempPromoter, import { FIRST_PARTY_FAILURE_CLASSES, type StateRoomObservation } from "@schlessera/brain-ui-sdk/protocol"; import { wrapCommand, type ExecWrapperConfig, type TurnFailure, type KeyedLock } from "@schlessera/brain-ui-sdk/server"; import { restoreArchivedSession } from "./transcript-archive.js"; +import { processCleanupReconciler, type CleanupReconciler } from "./cleanup-reconciler.js"; import { processStateLedger } from "./worker-state-budget.js"; import { createClaudeWorkerState, validateSessionId, workerStateSaveFailure, workerStateSaveReason } from "./worker-state.js"; @@ -93,7 +94,8 @@ export const CLAUDE_INFERENCE_ENV: readonly string[] = Object.freeze(["CLAUDE_CO export function createWorkerSpawn(brainPath: string, config: ExecWrapperConfig, immediateSignal: AbortSignal, restricted?: { inferenceDir: string }, sandbox?: WorkerSandbox, limitsPlan?: WorkerLimitsPlan, promotion?: WorkerPromotion, - stateOptions: Pick[2]>, "limits" | "ledger" | "turnTempLimits"> = {}, + stateOptions: Pick[2]>, "limits" | "ledger" | "turnTempLimits"> + & { /** Owns a refused end-of-turn cleanup (#2871); defaults to the process's one. */ cleanup?: CleanupReconciler } = {}, outputLock?: KeyedLock, workerStarted?: import("@schlessera/brain-ui-sdk/server").StartTurnRequest["workerStarted"], startupView?: import("@schlessera/brain-ui-sdk/internal").WorkerStartupView, persistMemory?: import("@schlessera/brain-ui-sdk/server").StartTurnRequest["persistClaudeMemory"], @@ -146,7 +148,7 @@ export function createWorkerSpawn(brainPath: string, config: ExecWrapperConfig, preparation.throwIfAborted(); let state: ReturnType; try { - state = prepareClaudeWorkerState(brainPath, env, args, { ...stateOptions, limits: stateLimits, turnTempLimits, + state = prepareClaudeWorkerState(brainPath, env, args, { ledger: stateOptions.ledger, limits: stateLimits, turnTempLimits, ephemeral: Boolean(restricted), hostInference: Boolean(egress), // The host's actual masks: any provider folder hidden makes the turn provider-denied (#2726). omitMemory: Boolean(sandbox?.providerMasks?.folders.length) }); @@ -265,10 +267,20 @@ export function createWorkerSpawn(brainPath: string, config: ExecWrapperConfig, if (liveTurnTemp === turnTemp) liveTurnTemp = undefined; // Awaited: a separate-UID worker's last handle closes its broker off // the event loop, and the reservation is released only once that - // cleanup is confirmed. A refusal keeps it charged (#2854). - const closed = await Promise.allSettled([handle.closeAsync(), turnTemp?.closeAsync()]); - const refused = closed.find(result => result.status === "rejected"); - if (refused) throw refused.reason; + // cleanup is confirmed. A refusal keeps it charged (#2854) and fails + // the turn; the reconciler retries the close and releases the + // reservation only once it is confirmed (#2871). + const close = async () => { + const closed = await Promise.allSettled([handle.closeAsync(), turnTemp?.closeAsync()]); + const refused = closed.find(result => result.status === "rejected"); + if (refused) throw refused.reason; + }; + try { await close(); } + catch (error) { + (stateOptions.cleanup ?? processCleanupReconciler()).retain({ bytes: state.bytes, turnTempBytes: state.turnTempBytes, + close, release: () => state.release() }); + throw error; + } state.release(); }) // The exit is reported above, but the worker's stdio can still be open diff --git a/packages/ui-backend-claude/tests/cleanup-reconciler.test.ts b/packages/ui-backend-claude/tests/cleanup-reconciler.test.ts new file mode 100644 index 0000000000..9515f6af52 --- /dev/null +++ b/packages/ui-backend-claude/tests/cleanup-reconciler.test.ts @@ -0,0 +1,168 @@ +/** + * A refused end-of-turn Claude worker cleanup has an owner (#2871): the + * reconciler retains the retryable close and the reservation, retries with + * finite attempts and backoff, and releases exactly once, only after a close + * is confirmed. Shutdown neither releases nor waits. + */ +import { expect, spyOn, test } from "bun:test"; +import { mkdirSync, mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { PassThrough } from "node:stream"; +import * as internal from "@schlessera/brain-ui-sdk/internal"; +import { createCleanupReconciler, type CleanupReconcilerOptions, type RetainedCleanup } from "../src/cleanup-reconciler.js"; +import { createWorkerSpawn } from "../src/worker-spawn.js"; +import { createStateLedger } from "../src/worker-state-budget.js"; + +const MiB = 1024 * 1024; +const refusal = () => Object.assign(new Error("worker_identity_cleanup_unconfirmed: Odysseus fixture"), { cleanupUnconfirmed: true }); + +/** Retries run only when the test says so; delays are recorded. */ +function manualClock() { + const pending: Array<{ run: () => void; delayMs: number; cancelled: boolean }> = []; + const schedule: NonNullable = (run, delayMs) => { + const entry = { run, delayMs, cancelled: false }; + pending.push(entry); + return () => { entry.cancelled = true; }; + }; + return { + schedule, + delays: () => pending.map(entry => entry.delayMs), + live: () => pending.filter(entry => !entry.cancelled).length, + /** Runs every retry scheduled so far, then lets their closes settle. */ + async tick() { + for (const entry of pending.splice(0)) if (!entry.cancelled) entry.run(); + for (let i = 0; i < 5; i++) await Promise.resolve(); + await Bun.sleep(0); + }, + }; +} + +function refusingCleanup(refusals: number) { + let calls = 0, released = 0; + const cleanup: RetainedCleanup = { bytes: 4 * MiB, turnTempBytes: MiB, + close: async () => { calls++; if (calls <= refusals) throw refusal(); }, + release: () => { released++; } }; + return { cleanup, calls: () => calls, released: () => released }; +} + +test("a cleanup refused N times is retried with backoff and released exactly once, only after confirmation", async () => { + const clock = manualClock(), logs: string[] = []; + const reconciler = createCleanupReconciler({ attempts: 5, baseDelayMs: 10, maxDelayMs: 25, schedule: clock.schedule, log: message => { logs.push(message); } }); + const fixture = refusingCleanup(3); + reconciler.retain(fixture.cleanup); + reconciler.retain(fixture.cleanup); + expect(fixture.calls(), "RETAIN_DOES_NOT_CLOSE_SYNCHRONOUSLY").toBe(0); + for (let refused = 1; refused <= 3; refused++) { + await clock.tick(); + expect(fixture.calls(), "ONE_CLOSE_PER_RETRY").toBe(refused); + expect(fixture.released(), "RESERVATION_HELD_WHILE_CLOSE_REFUSED").toBe(0); + expect(reconciler.held, "RECONCILER_KEEPS_THE_REFUSED_CLEANUP").toBe(1); + } + await clock.tick(); + expect(fixture.calls(), "CONFIRMING_CLOSE_ATTEMPTED").toBe(4); + expect(fixture.released(), "CONFIRMED_CLOSE_RELEASES_ONCE").toBe(1); + expect(reconciler.held, "CONFIRMED_CLEANUP_NO_LONGER_HELD").toBe(0); + expect(clock.delays(), "NO_RETRY_AFTER_CONFIRMATION").toEqual([]); + // Repeated retention and shutdown after confirmation release nothing again. + reconciler.retain(fixture.cleanup); + reconciler.close(); + await clock.tick(); + expect(fixture.released(), "RELEASED_EXACTLY_ONCE").toBe(1); + expect(logs.filter(line => line.includes("after")), "NO_TERMINAL_FAILURE_ON_CONFIRMATION").toEqual([]); +}); + +test("retry delays double from the base and stop at the maximum", async () => { + const clock = manualClock(), seen: number[] = []; + const schedule: NonNullable = (run, delayMs) => { seen.push(delayMs); return clock.schedule(run, delayMs); }; + const reconciler = createCleanupReconciler({ attempts: 5, baseDelayMs: 10, maxDelayMs: 25, schedule, log: () => {} }); + reconciler.retain(refusingCleanup(Infinity).cleanup); + for (let i = 0; i < 6; i++) await clock.tick(); + expect(seen, "BOUNDED_EXPONENTIAL_BACKOFF").toEqual([10, 20, 25, 25, 25]); +}); + +test("a permanently refusing cleanup ends in an observable terminal failure with its allowance still charged", async () => { + const clock = manualClock(), logs: Array<{ message: string; error: unknown }> = []; + const reconciler = createCleanupReconciler({ attempts: 3, baseDelayMs: 1, schedule: clock.schedule, log: (message, error) => { logs.push({ message, error }); } }); + const fixture = refusingCleanup(Infinity); + reconciler.retain(fixture.cleanup); + for (let i = 0; i < 6; i++) await clock.tick(); + expect(fixture.calls(), "FINITE_ATTEMPTS").toBe(3); + expect(clock.live(), "NO_RETRY_AFTER_TERMINAL_FAILURE").toBe(0); + expect(fixture.released(), "TERMINAL_FAILURE_NEVER_RELEASES").toBe(0); + expect(reconciler.held, "TERMINAL_FAILURE_STAYS_HELD").toBe(1); + expect(logs.length, "TERMINAL_FAILURE_LOGGED_ONCE").toBe(1); + expect(logs[0]!.message, "TERMINAL_FAILURE_NAMES_THE_HELD_ALLOWANCE").toContain("4 MiB of runtime state and 1 MiB of turn temp stay charged"); + expect(String(logs[0]!.error), "TERMINAL_FAILURE_KEEPS_THE_CAUSE").toContain("worker_identity_cleanup_unconfirmed"); + // Shutdown reports what the terminal failure still holds. + expect(reconciler.close(), "SHUTDOWN_REPORTS_TERMINAL_HOLD").toEqual({ held: 1, bytes: 4 * MiB, turnTempBytes: MiB }); +}); + +test("shutdown during a retry neither releases nor waits for the close in flight", async () => { + const clock = manualClock(), logs: string[] = []; + const reconciler = createCleanupReconciler({ attempts: 5, baseDelayMs: 1, schedule: clock.schedule, log: message => { logs.push(message); } }); + const gate = Promise.withResolvers(); + let released = 0, calls = 0; + const inFlight: RetainedCleanup = { bytes: 2 * MiB, turnTempBytes: MiB, close: () => { calls++; return gate.promise; }, release: () => { released++; } }; + const waiting = refusingCleanup(0); + reconciler.retain(inFlight); + await clock.tick(); + expect(calls, "CLOSE_IN_FLIGHT").toBe(1); + reconciler.retain(waiting.cleanup); + // Synchronous: it cannot wait for the held close. + const summary = reconciler.close(); + expect(summary, "SHUTDOWN_REPORTS_EVERYTHING_HELD").toEqual({ held: 2, bytes: 6 * MiB, turnTempBytes: 2 * MiB }); + expect(logs.some(line => line.includes("stopped with 2 unconfirmed cleanups")), "SHUTDOWN_LOGS_WHAT_IS_HELD").toBe(true); + gate.resolve(); + await clock.tick(); + expect(released, "SHUTDOWN_DOES_NOT_RELEASE_A_CLOSE_CONFIRMED_AFTER_IT").toBe(0); + expect(waiting.calls(), "SHUTDOWN_CANCELS_PENDING_RETRIES").toBe(0); + expect(waiting.released(), "SHUTDOWN_RELEASES_NOTHING").toBe(0); + expect(reconciler.close().held, "SHUTDOWN_IS_IDEMPOTENT").toBe(2); +}); + +/** A worker whose handles behave as the launcher's; only its turn temp's awaited close is scripted. */ +function fakeLaunch(root: string, turnTempClose: () => Promise) { + const handle = (name: string, closeAsync: () => Promise) => { + const path = join(root, name); + mkdirSync(path, { recursive: true }); + return { root: path, space: () => ({ total: 4 * MiB, free: 4 * MiB }), close() {}, closeAsync }; + }; + return spyOn(internal, "launchAgentWorkerAsync").mockImplementation((async () => { + const stderr = new PassThrough(), stdout = new PassThrough(), stdin = new PassThrough(); + stderr.end(); stdout.end(); + return { pid: 0, exited: Promise.resolve(0), released: async () => {}, kill() {}, stdin, stdout, stderr, + limitReport: () => ({}), state: handle("state", async () => {}), turnTemp: handle("tmp", turnTempClose) }; + }) as never); +} + +test("a turn whose end-of-turn cleanup is refused hands it to the reconciler, which releases the reservation once a retry confirms", async () => { + const root = mkdtempSync(join(tmpdir(), "odysseus-cleanup-retry-")); + const brain = join(root, "brain"), inferenceDir = join(root, "inference"); + mkdirSync(brain); mkdirSync(inferenceDir); + const host = spyOn(internal, "requireWorkerHostAsync").mockImplementation((async () => {}) as never); + let refusals = 2, closes = 0; + const launch = fakeLaunch(root, async () => { closes++; if (refusals-- > 0) throw refusal(); }); + const clock = manualClock(); + const cleanup = createCleanupReconciler({ attempts: 3, baseDelayMs: 1, schedule: clock.schedule, log: () => {} }); + const ledger = createStateLedger(); + try { + const spawner = createWorkerSpawn(brain, {}, new AbortController().signal, { inferenceDir }, undefined, undefined, undefined, + { ledger, cleanup, limits: { allowanceBytes: 4 * MiB, budgetBytes: 8 * MiB }, turnTempLimits: { allowanceBytes: MiB, budgetBytes: 2 * MiB } }); + const child = spawner.spawn({ command: "/bin/true", args: [], env: { HOME: root }, signal: new AbortController().signal } as never); + child.on("error", () => {}); + await expect(spawner.finish(), "REFUSED_CLEANUP_STILL_FAILS_THE_TURN").rejects.toThrow("worker_identity_cleanup_unconfirmed"); + expect(closes, "TURN_CLOSED_ONCE").toBe(1); + expect(ledger.live, "REFUSED_CLEANUP_KEEPS_RESERVATION").toBe(1); + expect(cleanup.held, "REFUSED_CLEANUP_HANDED_TO_RECONCILER").toBe(1); + await clock.tick(); + expect(closes, "RECONCILER_RETRIES_THE_TURN_TEMP_CLOSE").toBe(2); + expect(ledger.live, "RESERVATION_HELD_WHILE_RETRY_REFUSED").toBe(1); + await clock.tick(); + expect(closes, "SECOND_RETRY_CONFIRMS").toBe(3); + expect(ledger.live, "CONFIRMED_RETRY_RELEASES_RESERVATION").toBe(0); + expect(ledger.held, "NO_RUNTIME_STATE_STILL_CHARGED").toBe(0); + expect(ledger.turnTempHeld, "NO_TURN_TEMP_STILL_CHARGED").toBe(0); + expect(cleanup.held, "RECONCILER_NO_LONGER_HOLDS_IT").toBe(0); + } finally { launch.mockRestore(); host.mockRestore(); cleanup.close(); rmSync(root, { recursive: true, force: true }); } +}); diff --git a/packages/ui-backend-claude/tests/worker-cleanup.test.ts b/packages/ui-backend-claude/tests/worker-cleanup.test.ts index fd6c73a98e..02d6d42fe4 100644 --- a/packages/ui-backend-claude/tests/worker-cleanup.test.ts +++ b/packages/ui-backend-claude/tests/worker-cleanup.test.ts @@ -2,7 +2,8 @@ * A Claude worker's runtime-state reservation is released only once its * handles' awaited cleanup is confirmed (#2854). A separate-UID worker's last * handle closes its identity broker off the event loop, so the backend awaits - * that close; a refusal keeps the reservation charged. + * that close; a refusal keeps the reservation charged until the reconciler's + * retry confirms it (#2871). */ import { expect, spyOn, test } from "bun:test"; import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; @@ -10,6 +11,7 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import * as internal from "@schlessera/brain-ui-sdk/internal"; import { prepareWorkerSandbox } from "@schlessera/brain-ui-sdk/internal"; +import { createCleanupReconciler } from "../src/cleanup-reconciler.js"; import { createWorkerSpawn } from "../src/worker-spawn.js"; import { createStateLedger } from "../src/worker-state-budget.js"; @@ -33,9 +35,10 @@ test.skipIf(!native)("Claude keeps a worker's reservation charged until its awai turnTemp.closeAsync = async () => { closing.resolve(); await gate.promise; await close(); }; return worker; }); + const cleanup = createCleanupReconciler({ attempts: 3, baseDelayMs: 50, log: () => {} }); const turn = async (ledger: ReturnType) => { const spawner = createWorkerSpawn(brain, {}, new AbortController().signal, undefined, sandbox, undefined, undefined, - { ledger, limits: { allowanceBytes: 4 * MiB, budgetBytes: 8 * MiB }, turnTempLimits: { allowanceBytes: MiB, budgetBytes: 2 * MiB } }); + { ledger, cleanup, limits: { allowanceBytes: 4 * MiB, budgetBytes: 8 * MiB }, turnTempLimits: { allowanceBytes: MiB, budgetBytes: 2 * MiB } }); const child = spawner.spawn({ command: "/bin/true", args: [], env: { CLAUDE_CONFIG_DIR: saved, HOME: home }, signal: new AbortController().signal } as never); child.stdout.resume(); child.stdin.end(); child.on("error", () => {}); await closing.promise; @@ -58,7 +61,12 @@ test.skipIf(!native)("Claude keeps a worker's reservation charged until its awai gate.reject(Object.assign(new Error("worker_identity_cleanup_unconfirmed: fixture"), { cleanupUnconfirmed: true })); await expect(refusing, "CLAUDE_UNCONFIRMED_CLOSE_REJECTS_THE_LIFECYCLE").rejects.toThrow("worker_identity_cleanup_unconfirmed"); expect(refused.live, "CLAUDE_UNCONFIRMED_CLOSE_KEEPS_RESERVATION").toBe(1); - // The refused handle can still be closed later. + // The reconciler retries the refused handle's close; a confirmed retry releases it. + expect(cleanup.held, "CLAUDE_REFUSED_CLEANUP_RETAINED").toBe(1); + gate = Promise.withResolvers(); gate.resolve(); + for (let waited = 0; refused.live && waited < 100; waited++) await Bun.sleep(20); + expect(refused.live, "CLAUDE_CONFIRMED_RETRY_RELEASES_RESERVATION").toBe(0); + expect(cleanup.held, "CLAUDE_CONFIRMED_RETRY_NOT_HELD").toBe(0); await retries.at(-1)!(); - } finally { launch.mockRestore(); rmSync(root, { recursive: true, force: true }); } + } finally { cleanup.close(); launch.mockRestore(); rmSync(root, { recursive: true, force: true }); } }); From 2a6ce7dec78057ce1b873bbd760baf1b7af16b77 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 3 Nov 2026 14:14:08 +0000 Subject: [PATCH 2/3] test(backend-claude): drive cleanup retries manually and assert shutdown cancels them Refs #2871 Co-Authored-By: Claude Opus 5.5 --- packages/ui-backend-claude/tests/cleanup-reconciler.test.ts | 1 + packages/ui-backend-claude/tests/worker-cleanup.test.ts | 6 +++++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/packages/ui-backend-claude/tests/cleanup-reconciler.test.ts b/packages/ui-backend-claude/tests/cleanup-reconciler.test.ts index 9515f6af52..6f9fe93416 100644 --- a/packages/ui-backend-claude/tests/cleanup-reconciler.test.ts +++ b/packages/ui-backend-claude/tests/cleanup-reconciler.test.ts @@ -113,6 +113,7 @@ test("shutdown during a retry neither releases nor waits for the close in flight const summary = reconciler.close(); expect(summary, "SHUTDOWN_REPORTS_EVERYTHING_HELD").toEqual({ held: 2, bytes: 6 * MiB, turnTempBytes: 2 * MiB }); expect(logs.some(line => line.includes("stopped with 2 unconfirmed cleanups")), "SHUTDOWN_LOGS_WHAT_IS_HELD").toBe(true); + expect(clock.live(), "SHUTDOWN_CANCELS_RETRY_TIMERS").toBe(0); gate.resolve(); await clock.tick(); expect(released, "SHUTDOWN_DOES_NOT_RELEASE_A_CLOSE_CONFIRMED_AFTER_IT").toBe(0); diff --git a/packages/ui-backend-claude/tests/worker-cleanup.test.ts b/packages/ui-backend-claude/tests/worker-cleanup.test.ts index 02d6d42fe4..7b70034a97 100644 --- a/packages/ui-backend-claude/tests/worker-cleanup.test.ts +++ b/packages/ui-backend-claude/tests/worker-cleanup.test.ts @@ -35,7 +35,9 @@ test.skipIf(!native)("Claude keeps a worker's reservation charged until its awai turnTemp.closeAsync = async () => { closing.resolve(); await gate.promise; await close(); }; return worker; }); - const cleanup = createCleanupReconciler({ attempts: 3, baseDelayMs: 50, log: () => {} }); + // Retries run when the test says so, not on a timer racing the worker's release wait. + const scheduled: Array<() => void> = []; + const cleanup = createCleanupReconciler({ attempts: 3, log: () => {}, schedule: run => { scheduled.push(run); return () => {}; } }); const turn = async (ledger: ReturnType) => { const spawner = createWorkerSpawn(brain, {}, new AbortController().signal, undefined, sandbox, undefined, undefined, { ledger, cleanup, limits: { allowanceBytes: 4 * MiB, budgetBytes: 8 * MiB }, turnTempLimits: { allowanceBytes: MiB, budgetBytes: 2 * MiB } }); @@ -64,6 +66,8 @@ test.skipIf(!native)("Claude keeps a worker's reservation charged until its awai // The reconciler retries the refused handle's close; a confirmed retry releases it. expect(cleanup.held, "CLAUDE_REFUSED_CLEANUP_RETAINED").toBe(1); gate = Promise.withResolvers(); gate.resolve(); + expect(scheduled.length, "CLAUDE_REFUSED_CLEANUP_RETRY_SCHEDULED").toBe(1); + scheduled.shift()!(); for (let waited = 0; refused.live && waited < 100; waited++) await Bun.sleep(20); expect(refused.live, "CLAUDE_CONFIRMED_RETRY_RELEASES_RESERVATION").toBe(0); expect(cleanup.held, "CLAUDE_CONFIRMED_RETRY_NOT_HELD").toBe(0); From 0f7bb08c73848c3dd8ff2ba6b677422bb257b616 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 3 Nov 2026 14:14:08 +0000 Subject: [PATCH 3/3] docs(backend-claude): record the end-of-turn cleanup retry owner ruling Refs #2871 Co-Authored-By: Claude Opus 5.5 --- .changeset/claude-cleanup-retry-owner.md | 4 +++ docs/decisions/claude-code-runtime.md | 2 +- docs/decisions/governed-writable-workers.md | 27 ++++++++++++++++++++- docs/hosting/agent-workers.md | 6 ++++- 4 files changed, 36 insertions(+), 3 deletions(-) create mode 100644 .changeset/claude-cleanup-retry-owner.md diff --git a/.changeset/claude-cleanup-retry-owner.md b/.changeset/claude-cleanup-retry-owner.md new file mode 100644 index 0000000000..9bfbb9bfb3 --- /dev/null +++ b/.changeset/claude-cleanup-retry-owner.md @@ -0,0 +1,4 @@ +--- +"@schlessera/brain-backend-claude": patch +--- +A Claude turn whose worker cleanup the supervisor cannot confirm no longer keeps its runtime-state and turn-temp reservation until the server restarts. The turn still fails, but the backend now retries the cleanup a few times with growing delays and releases the reservation once a retry is confirmed. If every retry is refused, the server log names the allowance that stays charged. Shutdown stops the retries, logs what is still held and releases nothing. diff --git a/docs/decisions/claude-code-runtime.md b/docs/decisions/claude-code-runtime.md index 3311478275..dd28732655 100644 --- a/docs/decisions/claude-code-runtime.md +++ b/docs/decisions/claude-code-runtime.md @@ -59,7 +59,7 @@ next to it. spawned it directly at this baseline. #1037 subsequently made worker execution unconditional; #1808 retired this unused adapter. The optional exec wrapper now runs inside the worker (`createWorkerSpawn`, - `packages/ui-backend-claude/src/worker-spawn.ts:94-353`). + `packages/ui-backend-claude/src/worker-spawn.ts:95-365`). - **Updated.** Nothing in the tree installs, updates, pins or reads the version of this binary. The only version probe in the server is for the `brain` CLI (`Probe the selected content CLI`, diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index 1e338b8702..1ec5bdc6e6 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -3281,7 +3281,7 @@ list. **Where the switch happens.** Neither the worker nor the exec wrapper can make it. The exec wrapper runs inside the worker -(`export function createWorkerSpawn`, `packages/ui-backend-claude/src/worker-spawn.ts:94`). +(`export function createWorkerSpawn`, `packages/ui-backend-claude/src/worker-spawn.ts:95`). An unprivileged user namespace cannot change its outside uid, and bubblewrap cannot either. The uid therefore changes *before* `bwrap` starts, through a helper the host provides: @@ -3626,6 +3626,31 @@ that run after an asynchronous launch has returned. Termination and the signal requests stay synchronous; this ruling does not cover them. +### A refused end-of-turn cleanup has a retry owner — 2026-10-25 + +The maintainer selected [option 1 on #2871](https://github.com/schlessera/brain-kit/issues/2871): +a bounded, server-owned reconciliation owner takes over a Claude turn's +end-of-turn cleanup that the awaited close above could not confirm. + +- **The turn still fails.** The refusal is the turn's, as before; the + reconciler only takes ownership of the retryable close and the reservation. +- **Finite retries, then observable failure.** It retries the close with + capped exponential backoff and a finite number of attempts. A close still + refused after the last attempt is logged with the runtime-state and + turn-temp allowance it keeps charged until the server restarts. +- **Release once, only on confirmation.** The reservation is released exactly + once, after a retry resolves. An unconfirmed close never releases it. +- **Shutdown releases nothing and waits for nothing.** It cancels pending + retries, does not wait for a close in flight, and reports what is still + held. The process's one reconciler stops when the process exits; its timers + never hold the process open. + +The owner is the reconciler +(`export function createCleanupReconciler`, `packages/ui-backend-claude/src/cleanup-reconciler.ts:66-125`), and the turn +hands its refusal over where it awaits the close +(`const close = async`, `packages/ui-backend-claude/src/worker-spawn.ts:273-284`). Pi and a launch +whose own cleanup is unconfirmed are outside this ruling. + ### Turn completion includes worker teardown — 2026-10-25 The maintainer's [#2863 lifecycle ruling](https://github.com/schlessera/brain-kit/issues/2863#issuecomment-6391630082) diff --git a/docs/hosting/agent-workers.md b/docs/hosting/agent-workers.md index a45ff9d74f..06cb3d4792 100644 --- a/docs/hosting/agent-workers.md +++ b/docs/hosting/agent-workers.md @@ -133,7 +133,11 @@ Recovery copies reserve the existing aggregate output-staging budget in addition to retained source storage. Closing a handle aborts its pending copy; the copy reservation remains until that work drains and owned cleanup is confirmed. An unconfirmed cleanup retains ownership and reservations for -reconciliation rather than reporting successful reclamation. +reconciliation rather than reporting successful reclamation. For a Claude +turn's end-of-turn cleanup, the server retries the close a few times with +growing delays and releases the reservation once a retry is confirmed. If +every retry is refused, the server log names the allowance that stays charged +until the server restarts. Files made private are read by fixed, uncredentialed worker-UID code through authorized retained roots: no repository imports/evaluation, path escapes,