Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .changeset/claude-cleanup-retry-owner.md
Original file line number Diff line number Diff line change
@@ -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.
2 changes: 1 addition & 1 deletion docs/decisions/claude-code-runtime.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`,
Expand Down
27 changes: 26 additions & 1 deletion docs/decisions/governed-writable-workers.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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)
Expand Down
6 changes: 5 additions & 1 deletion docs/hosting/agent-workers.md
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
137 changes: 137 additions & 0 deletions packages/ui-backend-claude/src/cleanup-reconciler.ts
Original file line number Diff line number Diff line change
@@ -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<void>;
/** 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<RetainedCleanup, (() => 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];
}
24 changes: 18 additions & 6 deletions packages/ui-backend-claude/src/worker-spawn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand Down Expand Up @@ -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<NonNullable<Parameters<typeof createClaudeWorkerState>[2]>, "limits" | "ledger" | "turnTempLimits"> = {},
stateOptions: Pick<NonNullable<Parameters<typeof createClaudeWorkerState>[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"],
Expand Down Expand Up @@ -146,7 +148,7 @@ export function createWorkerSpawn(brainPath: string, config: ExecWrapperConfig,
preparation.throwIfAborted();
let state: ReturnType<typeof createClaudeWorkerState>;
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) });
Expand Down Expand Up @@ -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
Expand Down
Loading
Loading