diff --git a/.changeset/3815-reconcile-uncertain-charges.md b/.changeset/3815-reconcile-uncertain-charges.md new file mode 100644 index 0000000000..edbf0176c9 --- /dev/null +++ b/.changeset/3815-reconcile-uncertain-charges.md @@ -0,0 +1,8 @@ +--- +"@schlessera/brain-ui-sdk": minor +"@schlessera/brain-backend-claude": patch +"@schlessera/brain-backend-pi": patch +"@schlessera/brain-ui-server": minor +--- + +Keep reconciling refused worker cleanup and unreadable compute jobs without a restart, retaining their reservations until confirmation. Retry superseded checkpoint cleanup without stopping active turns unless the retained-checkpoint bound blocks a safe observation. Record cleanup causes and recovery in Activity, and expose durable checkpoint cleanup diagnostics in authenticated status. diff --git a/api-report/ui-sdk.txt b/api-report/ui-sdk.txt index d237edc006..68b8281450 100644 --- a/api-report/ui-sdk.txt +++ b/api-report/ui-sdk.txt @@ -1208,10 +1208,16 @@ export "./internal" (./src/internal.ts) BRAIN_INTERACTION_GUIDANCE BRAIN_SCRATCH_DIR BRAIN_WORKSPACES_DIR + CLEANUP_RETRY_ATTEMPTS + CLEANUP_RETRY_BASE_MS + CLEANUP_RETRY_MAX_MS CREDENTIAL_FREE_ENV type ClassificationAnswers type ClassificationPlan type ClassificationRequest + type CleanupNotice + type CleanupReconciler + type CleanupReconcilerOptions type CompiledWorkerCommandPolicy DEFAULT_TURN_TEMP_BYTES type EgressRecord @@ -1268,6 +1274,7 @@ export "./internal" (./src/internal.ts) RTK_WORKER_ENV type RemovalRun type Reservation + type RetainedCleanup STALE_SAFETY_ADMISSION SUBPROCESS_ENV type SessionPromptFacts @@ -1331,6 +1338,7 @@ export "./internal" (./src/internal.ts) commitOutwardPlan compileWorkerCommandPolicy conversationOrientation + createCleanupReconciler createLimitTracker createNativeBrainManagerClient createSessionRetirement @@ -1389,6 +1397,7 @@ export "./internal" (./src/internal.ts) probeNativeMaintenanceWorker probeWorkerHost probeWorkerHostAsync + processCleanupReconciler processStateLedger projectConversationGuidance promptPrefixFingerprint @@ -5887,6 +5896,13 @@ signatures (every public export and the types it is made of) }>; BackendActivityEvent (packages/ui-sdk/src/server/backend.ts) export type BackendActivityEvent = { + kind: "worker_cleanup"; + state: "retrying" | "resolved"; + bytes: number; + turnTempBytes: number; + errorClass?: string; + message?: string; + } | { kind: "prompt_prefix"; prefix: import("../protocol.js").PromptPrefixFingerprint; resumed: boolean; diff --git a/api-report/ui-server.txt b/api-report/ui-server.txt index 892061ffa2..f892c6d7af 100644 --- a/api-report/ui-server.txt +++ b/api-report/ui-server.txt @@ -1573,6 +1573,12 @@ signatures (every public export and the types it is made of) statCheckpoint?: ReturnType["statCheckpoint"]; listCheckpoint?: ReturnType["listCheckpoint"]; } + NativeJournalReleaseAccounting (packages/ui-server/src/brain/native-journal-observer.ts) + export interface NativeJournalReleaseAccounting { + pending: number; + failed: number; + retainedBytes: number; + } NativeManagerReady (packages/ui-sdk/src/server/native-brain-manager-protocol.ts) export interface NativeManagerReady { brainPath: string; @@ -2198,6 +2204,7 @@ signatures (every public export and the types it is made of) referenceCheckpoints?: ReferenceWorktreeCheckpointLedger; changed?: (turnId: string, sessionId: string, summary: TurnJournalSummary) => void; idleObservationMs?: number; + log?: Logger; } VoiceConfig (packages/ui-server/src/config/env.ts) export interface VoiceConfig { @@ -2529,6 +2536,10 @@ signatures (every public export and the types it is made of) inode: string; note: string; }; + cleanupStatus(): { + lastFailure: unknown; + retained: import("./native-journal-observer.js").NativeJournalReleaseAccounting; + }; close(): Promise; configurationCoverage(): ConfigurationCoverageRead; coverPaths(turnId: string, paths: readonly string[]): void; diff --git a/docs/decisions/external-compute.md b/docs/decisions/external-compute.md index 1910ffc081..261c171944 100644 --- a/docs/decisions/external-compute.md +++ b/docs/decisions/external-compute.md @@ -638,7 +638,7 @@ maintainer ruled on four more questions on 2026-11-02. - **Configuration as data.** The host reads `brain config check --json`'s new `compute` summary in a credential-free strict worker that sees only the policy's protected paths, once per turn, as it reads the taxonomy - (`readHostedComputeConfig`, `packages/ui-server/src/brain/compute-host.ts:977-989`). A + (`readHostedComputeConfig`, `packages/ui-server/src/brain/compute-host.ts:980-992`). A provider value is reported by id only. A job keeps the instance configuration it was admitted under, so its driver never reaches another account however the brain changes later. @@ -717,8 +717,10 @@ These refine the notes above; where they differ, these hold. tracked, and is retried. A job the host abandons settles its reservation as unknown, and at boot a reservation left without a job record settles as unknown; both keep counting at the reserved amount, never zero. A job the - driver stops advancing after repeated failures keeps its reservation active - and its run flagged stuck until the next restart reattaches it. + driver cannot advance after repeated failures keeps its reservation active + and its run flagged stuck, with the cause in Activity. Under #3815 it keeps + visiting at the capped interval until settlement can be confirmed, without + requiring a restart or another admitted turn. - **Activity over HTTP.** `GET /api/activity/runs` and `GET /api/activity/runs/:runId` return `compute` runs only to a request that declares the capability, as the live stream does. diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index 25d1086326..29689114d5 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -1469,7 +1469,7 @@ starts one per result and carries on (`void host.journal?.toolEnded`, `packages/ui-server/src/ws/bridge-capabilities/emission.ts:272`). The wait is the observation's hold. `held` takes it synchronously, before it queues the capture -(`function held`, `packages/ui-server/src/brain/turn-journal.ts:240-261`), +(`function held`, `packages/ui-server/src/brain/turn-journal.ts:246-267`), and the scope monitor's hold freezes every active turn's productive workers until the capture completes (`before() {`, `packages/ui-server/src/brain/turn-scope.ts:158-166`). Pi's agent loop runs in @@ -1481,7 +1481,7 @@ tracked the hold, not the bridge call. proven read-only, no other call of an active turn is still running, and no active turn has run a call whose effects may outlast it (`toolEnded(turnId: string, toolUseId: string)`, -`packages/ui-server/src/brain/turn-journal.ts:550-557`). Admission, turn end, +`packages/ui-server/src/brain/turn-journal.ts:551-558`). Admission, turn end, the 15-second timer, scope-limit observations, approved policy writes and removal coverage observe exactly as before. @@ -1606,7 +1606,7 @@ these versions as metadata-only and never open them for retention kind, mode, size and its ignored flag, carries `metadataOnly: true` and records its opaque change stamp, with no content hash and no symlink target. Two versions of equal size are told apart by that stamp, as ignored ones are -(`const identity`, `packages/ui-server/src/brain/turn-journal.ts:76`), +(`const identity`, `packages/ui-server/src/brain/turn-journal.ts:81`), so every observed refresh remains a recorded change. A metadata-only version is an intentional observation state: it adds no `missing` entry and does not make the turn partial. Removal coverage never treats the family as eligible, and history @@ -1618,7 +1618,7 @@ stays now counts its largest size once too, rather than each version. **History.** History presents every index-family version as metadata-only however it was recorded, so a version an earlier release retained is no longer read -(`const presented`, `packages/ui-server/src/brain/turn-journal.ts:69-74`). +(`const presented`, `packages/ui-server/src/brain/turn-journal.ts:74-79`). The reader groups these entries as the search index, recorded by size and timestamps only, with no review action. Preview reports `metadata_only` and download has nothing to serve. History revert and Undo read that same @@ -1853,7 +1853,7 @@ brain and every managed worktree, has its own owner, and each owner keeps at most `NATIVE_RELEASE_BACKLOG`, two, previous checkpoints retained, whether queued or failed. An observation makes room before it takes its own checkpoint (`async function reserveRelease`, -`packages/ui-server/src/brain/native-journal-observer.ts:330-336`): it waits +`packages/ui-server/src/brain/native-journal-observer.ts:349-355`): it waits inside the hold for the oldest queued release, or, when failed releases fill the bound, retries the oldest one inside the hold, as every release ran before. If that retry fails, the observation is refused before it takes a @@ -1861,7 +1861,7 @@ checkpoint, so the bound is never exceeded. Each retained checkpoint is charged it holds that the live root no longer has: the bytes of every file version replaced or removed since it was taken (`releases(): NativeJournalReleaseAccounting`, -`packages/ui-server/src/brain/native-journal-observer.ts:483-487`). +`packages/ui-server/src/brain/native-journal-observer.ts:505-509`). Directory and other metadata extents are not counted. The store's free space, which the `free_space_floor` scope limit reads, counts the actual extents until each release completes. Shutdown waits for every queued release, retries @@ -1870,17 +1870,15 @@ checkpoint still retained; startup recovery releases those. A release that never settles is bounded by the manager client's transport deadline, not by the owner. -**A failed release.** The checkpoint stays retained and charged until a -retry, and the journal treats the failure as the hold did -(`const releaseFailed`, `packages/ui-server/src/brain/turn-journal.ts:182-190`): -every active turn stops and its record is partial, a hold the failure -overlaps kills its held workers instead of resuming them, and an admission -requested before the failure, even one still queued behind other journal work, -is refused. A turn that finished before the failure keeps its record: -its terminal capture was recorded before the release began, and the failure -concerns storage cleanup, not what the journal holds. A failure inside the -hold, of a checkpoint, a delta, a capture, the retry of a failed release or the -release of an aborted observation, is unchanged. +**A failed release (revised by #3815).** The superseded checkpoint stays +retained and charged, and its owner retries every thirty seconds without a new +observation. Its replacement observation already committed, so the failure +neither stops active turns nor makes their records partial, and admissions +continue while the retained-checkpoint bound has room. The cause and checkpoint +identity are logged and recorded in the affected turns' authenticated Activity. +Only a full backlog that cannot make room refuses the next safe observation. +Failures taking a checkpoint, reading its delta, capturing its versions or +committing the observation retain their existing containment. **Tests.** A fresh launch and the shared interpreter answer each refused inspection with the same exit status, output and traceback; every request sees @@ -3707,10 +3705,10 @@ 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. +- **Capped backoff without giving up (revised by #3815).** Both backends + retain a retry owner, including Pi initialization failures. After the + foreground retry count, the owner continues at the capped delay. Activity + records the cause, charged allowances and later confirmation. - **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 @@ -3719,10 +3717,10 @@ end-of-turn cleanup that the awaited close above could not confirm. 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 +(`export function createCleanupReconciler`, `packages/ui-sdk/src/server/cleanup-reconciler.ts:75-148`), 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. +(`const close = async`, `packages/ui-backend-claude/src/worker-spawn.ts:273-284`). Pi supervision now uses the same owner; launch failures before a handle is +returned remain the launcher's responsibility. ### Turn completion includes worker teardown — 2026-10-25 @@ -4321,7 +4319,7 @@ attribution. If an existing same-session/turn taint event precedes an agent observation, the journal retains its source ID with that change. Replay never infers taint from a later event, and absence of evidence does not assert complete untrusted-input detection. User history operations are not tainted agent writes -(`async function observe`, `packages/ui-server/src/brain/turn-journal.ts:375-440`). +(`async function observe`, `packages/ui-server/src/brain/turn-journal.ts:380-445`). Claude auto-memory persists outside the authoritative brain. Its validated native copy-out wraps each changed direct `.md` note in host journal retention: @@ -4344,7 +4342,7 @@ memory completion of the earlier 0.42.0 steering slice, not a widening of memory providers or a claim of capturing intervening external writes. The copy-out boundary is `const write`, `packages/ui-backend-claude/src/worker-state.ts:210-224`; retention/finalization is `persistClaudeMemory`, -`packages/ui-server/src/brain/turn-journal.ts:647-677`; destination-bound recovery +`packages/ui-server/src/brain/turn-journal.ts:657-687`; destination-bound recovery is `const target`, `packages/ui-server/src/brain/turn-revert.ts:113-123`. ### Concurrent edits diff --git a/docs/decisions/journal-database.md b/docs/decisions/journal-database.md index 69f7290a0a..a56c0fe498 100644 --- a/docs/decisions/journal-database.md +++ b/docs/decisions/journal-database.md @@ -97,7 +97,7 @@ that no pre-charge covers. The evidence is on the issue. readers understand the arrays until then, and an empty legacy array stays "no set recorded". The brain's current set is the one the most recent complete, inventoried turn recorded - (`configurationCoverage(): ConfigurationCoverageRead`, `packages/ui-server/src/brain/turn-journal.ts:728-734`). + (`configurationCoverage(): ConfigurationCoverageRead`, `packages/ui-server/src/brain/turn-journal.ts:738-744`). The sets table is an ordinary rowid table, as every journal table is: the operational backup copies and compares journal rows in rowid order. diff --git a/docs/decisions/managed-worktrees.md b/docs/decisions/managed-worktrees.md index dd2fd6d226..03b5b1319e 100644 --- a/docs/decisions/managed-worktrees.md +++ b/docs/decisions/managed-worktrees.md @@ -125,8 +125,8 @@ A managed worktree is not inside the brain, so the brain's checkpoints never cover it. The turn journal observes each covered worktree as its own root, through that worktree's read-only checkpoints and deltas and the same observer and capture as the brain -(`attachWorktree(turnId: string`, `packages/ui-server/src/brain/turn-journal.ts:562-574`; -`// Each managed worktree is observed through its own checkpoints`, `packages/ui-server/src/brain/turn-journal.ts:392-406`). +(`attachWorktree(turnId: string`, `packages/ui-server/src/brain/turn-journal.ts:563-575`; +`// Each managed worktree is observed through its own checkpoints`, `packages/ui-server/src/brain/turn-journal.ts:397-411`). Coverage starts with a baseline checkpoint and inventory before the grant, and every journal observation, periodic, at a scope cap or at the turn's end, then observes the worktree too. diff --git a/docs/decisions/proportionate-containment.md b/docs/decisions/proportionate-containment.md index 54fe965703..3addfc27a8 100644 --- a/docs/decisions/proportionate-containment.md +++ b/docs/decisions/proportionate-containment.md @@ -55,8 +55,7 @@ design, not an afterthought. - Proportionate: an uncertain worker cleanup stays charged and is retried until a close is confirmed. - Disproportionate: after five refused closes, the allowance stays charged - until the server restarts (`const attempt`, - `packages/ui-backend-claude/src/cleanup-reconciler.ts:78-90`). + until the server restarts (the terminal give-up removed by #3815). 4. **Boot.** A recoverable historical record (a corrupt object, a malformed intent, an interrupted cleanup) is quarantined and marked, and the host boots. If it must, it boots restricted, with the unsafe operation still diff --git a/docs/hosting/agent-workers.md b/docs/hosting/agent-workers.md index 9423380e3d..9f36a8aaa3 100644 --- a/docs/hosting/agent-workers.md +++ b/docs/hosting/agent-workers.md @@ -133,11 +133,13 @@ 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. 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. +reconciliation rather than reporting successful reclamation. For +end-of-turn cleanup, both backends keep retrying with capped backoff +and release the reservation only once a close is confirmed. Pi initialization +failures retain the same retry owner. The original turn's Activity events +record the cleanup cause, retained allowances and eventual confirmation, +including confirmation after the turn has ended. After five failed retries a +host diagnostic reports slow reconciliation; retries continue without a restart. Files made private are read by fixed, uncredentialed worker-UID code through authorized retained roots: no repository imports/evaluation, path escapes, diff --git a/docs/http-api.md b/docs/http-api.md index a19e02ffd7..ea0206bef4 100644 --- a/docs/http-api.md +++ b/docs/http-api.md @@ -2070,3 +2070,10 @@ principal, generation, finalized-exposure and permanent retirement fences in the writer and SQLite trigger. Resolving a known event cannot repair unknown detector coverage, recording loss or another unresolved event. No model/voice tool, WS mutation frame, Settings rule or provider transcript edit is added. + + +The authenticated status response also includes `journalCleanup` (#3815): +current retained-checkpoint counts and bytes, plus `lastFailure`, a durable +historical cause even when cleanup failed before the first turn. The historical +record survives successful cleanup; current retained charges are reported +separately. It is never part of public `/health`. diff --git a/docs/integration-contract/http.md b/docs/integration-contract/http.md index 95ee486290..00d84be77b 100644 --- a/docs/integration-contract/http.md +++ b/docs/integration-contract/http.md @@ -1088,3 +1088,14 @@ Saved-audio PUT binds `Speech-Provider` before claim/body consumption; absent headers preserve effective-provider resolution. Retry provider changes return 409 `transcription_provider_mismatch` with the receipt. Settings revisions, error codes, response schemas and operation binding are supported HTTP promises. + + +### Checkpoint cleanup diagnostics (additive, #3815) + +Authenticated `GET /api/status` adds `journalCleanup`: `retained` contains +`pending`, `failed` and `retainedBytes` for this process's superseded checkpoints; +`lastFailure` is null or the durable historical failure with `kind`, +`checkpointId`, `at` (epoch milliseconds), `scope`, `errorClass`, `cause` and +`retrying: true` at the time it was recorded. The historical cause survives +recovery and restart; it does not assert a currently blocked turn. Current +charges remain separate in `retained`. No field changes public `/health`. diff --git a/docs/integration-contract/package-api.md b/docs/integration-contract/package-api.md index d813545279..97d7941358 100644 --- a/docs/integration-contract/package-api.md +++ b/docs/integration-contract/package-api.md @@ -814,6 +814,13 @@ and error answers. Server checkpoint settlement uses these receipts as described in the [budget guide](../inbox-budget.md). Backends without this optional reporting retain conservative missing-receipt settlement. +The additive server-only `BackendActivityEvent` variant `worker_cleanup` +(#3815) contains `{ state: "retrying" | "resolved", bytes, turnTempBytes, +errorClass?, message? }`. Both backends report retained cleanup allowances and +their confirmation, including after a turn ends. The host records these as +`worker_cleanup` Activity events on the original run without changing its +terminal outcome. They never enter provider history and add no client frame. + The additive server-only `BackendActivityEvent` variant `resource_limit` (#1660) contains `{ limits, fatal }`: each new host resource-limit hit of the turn's worker, `{ limit, source, value, events }`, reported next to the step @@ -5179,3 +5186,9 @@ model tool or publication seam. Historical receipt projections and fresh its read-only reason additionally accepts `owner_required` or null; optional literal review lifetime/body bounds describe a supporting host. Absent or unsupported capability remains unavailable and grants no mutation authority. + + +The journal host's additive `cleanupStatus()` method (#3815) returns +`{ retained: { pending, failed, retainedBytes }, lastFailure }`, the same +current accounting and historical diagnostic record exposed as +[`journalCleanup` on authenticated status](http.md#checkpoint-cleanup-diagnostics-additive-3815). diff --git a/docs/integration-contract/wire.md b/docs/integration-contract/wire.md index 0729a6cb44..d330c2aab6 100644 --- a/docs/integration-contract/wire.md +++ b/docs/integration-contract/wire.md @@ -55,7 +55,7 @@ reports the paths observed so far, a lower bound, and an empty partial reports summary retained before this field, or sent by an older server, omits it or reports `null`: the count is unknown, never zero, and a client names the `changedFiles` figure as recorded entries rather than files. The count is -(`const KEPT_CHANGE`, `packages/ui-server/src/brain/turn-journal.ts:47-50`). +(`const KEPT_CHANGE`, `packages/ui-server/src/brain/turn-journal.ts:52-55`). **Configuration coverage set (additive, #3257).** Untraced configuration inputs are a property of the brain's configuration, so the host stores each distinct diff --git a/docs/plans/host-owned-web-search.md b/docs/plans/host-owned-web-search.md index 7474c52d54..65779a7b16 100644 --- a/docs/plans/host-owned-web-search.md +++ b/docs/plans/host-owned-web-search.md @@ -216,7 +216,7 @@ runtime authority or a public plugin seam. Both candidates need them: Current source confirms why a bridge is needed: ordinary initialization copies only auth/models/settings (`const init`, -`packages/ui-backend-pi/src/worker-launch.ts:114-116`), then selects private Pi +`packages/ui-backend-pi/src/worker-launch.ts:115-117`), then selects private Pi state. The worker RPC schema has an existing bounded, grant-checked bridge but no search method (`export const piWorkerMessage`, `packages/ui-backend-pi/src/worker-protocol.ts:71-82`). Resource discovery remains diff --git a/packages/ui-backend-claude/src/cleanup-reconciler.ts b/packages/ui-backend-claude/src/cleanup-reconciler.ts index 50b3d956aa..86cfcf301f 100644 --- a/packages/ui-backend-claude/src/cleanup-reconciler.ts +++ b/packages/ui-backend-claude/src/cleanup-reconciler.ts @@ -1,137 +1,3 @@ -/** - * 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]; -} +/** Shared by both backends; retain the original internal import location. */ +export { createCleanupReconciler, processCleanupReconciler, CLEANUP_RETRY_ATTEMPTS, CLEANUP_RETRY_BASE_MS, CLEANUP_RETRY_MAX_MS } from "@schlessera/brain-ui-sdk/internal"; +export type { CleanupReconciler, CleanupReconcilerOptions, RetainedCleanup } from "@schlessera/brain-ui-sdk/internal"; diff --git a/packages/ui-backend-claude/src/sdk-options.ts b/packages/ui-backend-claude/src/sdk-options.ts index 170cd96c1b..9ffc940c49 100644 --- a/packages/ui-backend-claude/src/sdk-options.ts +++ b/packages/ui-backend-claude/src/sdk-options.ts @@ -465,7 +465,7 @@ function assembleClaudeSdkTurn( } }, log: (level, message) => log(level, message), - }, { limits: stateLimits, turnTempLimits }, req.workerLock, req.workerStarted, req.workerStartupView, req.persistClaudeMemory, options.hostInference, credentialEnv); + }, { limits: stateLimits, turnTempLimits, reportCleanup: notice => req.bridge.activity?.({ kind: "worker_cleanup", ...notice }) }, req.workerLock, req.workerStarted, req.workerStartupView, req.persistClaudeMemory, options.hostInference, credentialEnv); sdkOptions.spawnClaudeCodeProcess = worker.spawn; if (!req.autonomous) addStateRoomWarning(sdkOptions, req, worker); /** This turn's answer text so far: what it links in turn temp is promoted, so a purge keeps it. */ diff --git a/packages/ui-backend-claude/src/worker-spawn.ts b/packages/ui-backend-claude/src/worker-spawn.ts index 3eee86fc65..818ba770e1 100644 --- a/packages/ui-backend-claude/src/worker-spawn.ts +++ b/packages/ui-backend-claude/src/worker-spawn.ts @@ -95,7 +95,7 @@ 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"> - & { /** Owns a refused end-of-turn cleanup (#2871); defaults to the process's one. */ cleanup?: CleanupReconciler } = {}, + & { /** Owns a refused end-of-turn cleanup (#2871); defaults to the process's one. */ cleanup?: CleanupReconciler; reportCleanup?: (notice: import("@schlessera/brain-ui-sdk/internal").CleanupNotice) => void } = {}, 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"], @@ -278,7 +278,7 @@ export function createWorkerSpawn(brainPath: string, config: ExecWrapperConfig, try { await close(); } catch (error) { (stateOptions.cleanup ?? processCleanupReconciler()).retain({ bytes: state.bytes, turnTempBytes: state.turnTempBytes, - close, release: () => state.release() }); + close, release: () => state.release(), report: stateOptions.reportCleanup }, error); throw error; } state.release(); diff --git a/packages/ui-backend-claude/tests/cleanup-reconciler.test.ts b/packages/ui-backend-claude/tests/cleanup-reconciler.test.ts index 6f9fe93416..42271df238 100644 --- a/packages/ui-backend-claude/tests/cleanup-reconciler.test.ts +++ b/packages/ui-backend-claude/tests/cleanup-reconciler.test.ts @@ -1,7 +1,7 @@ /** * 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 + * capped backoff without giving up, and releases exactly once, only after a close * is confirmed. Shutdown neither releases nor waits. */ import { expect, spyOn, test } from "bun:test"; @@ -78,24 +78,29 @@ test("retry delays double from the base and stop at the maximum", async () => { 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]); + expect(seen, "BOUNDED_EXPONENTIAL_BACKOFF").toEqual([10, 20, 25, 25, 25, 25, 25]); + reconciler.close(); }); -test("a permanently refusing cleanup ends in an observable terminal failure with its allowance still charged", async () => { +test("a cleanup refused beyond the foreground limit keeps retrying and releases only on confirmation", 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); + const fixture = refusingCleanup(6); 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.calls(), "RETRIES_BEYOND_FOREGROUND_LIMIT").toBe(6); + expect(clock.live(), "RECONCILIATION_REMAINS_OWNED").toBe(1); 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 }); + await clock.tick(); + expect(fixture.released(), "LATE_CONFIRMATION_RELEASES_ONCE").toBe(1); + expect(reconciler.held).toBe(0); + await clock.tick(); + expect(fixture.released()).toBe(1); + reconciler.close(); }); test("shutdown during a retry neither releases nor waits for the close in flight", async () => { @@ -147,9 +152,10 @@ test("a turn whose end-of-turn cleanup is refused hands it to the reconciler, wh const clock = manualClock(); const cleanup = createCleanupReconciler({ attempts: 3, baseDelayMs: 1, schedule: clock.schedule, log: () => {} }); const ledger = createStateLedger(); + const notices: unknown[] = []; 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 } }); + { ledger, cleanup, reportCleanup: notice => notices.push(notice), 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"); @@ -165,5 +171,6 @@ test("a turn whose end-of-turn cleanup is refused hands it to the reconciler, wh 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); + expect(notices).toMatchObject([{ state: "retrying", message: expect.stringContaining("worker_identity_cleanup_unconfirmed") }, { state: "resolved" }]); } finally { launch.mockRestore(); host.mockRestore(); cleanup.close(); rmSync(root, { recursive: true, force: true }); } }); diff --git a/packages/ui-backend-pi/src/backend-options.ts b/packages/ui-backend-pi/src/backend-options.ts index f65f556310..fe9ee64a18 100644 --- a/packages/ui-backend-pi/src/backend-options.ts +++ b/packages/ui-backend-pi/src/backend-options.ts @@ -200,6 +200,8 @@ export interface SessionCaps { /** What one session's system prompt and toolset are conditioned on. */ export interface SessionEnv { + /** Host-only cleanup diagnostics, captured before worker initialization. */ + cleanupActivity?: BackendBridge["activity"]; /** Internal static limits and current actionable budget context. */ sessionBudgetLimits?: string; budgetContext?: string; diff --git a/packages/ui-backend-pi/src/session-pool.ts b/packages/ui-backend-pi/src/session-pool.ts index 826fb838fa..634582f84a 100644 --- a/packages/ui-backend-pi/src/session-pool.ts +++ b/packages/ui-backend-pi/src/session-pool.ts @@ -50,7 +50,7 @@ export function createSessionPool(runtime: SessionRuntime, retainSessions = true autonomous: req.autonomous, enforceAllowedTools: req.enforceAllowedTools === true, noGrantSurface: req.noGrantSurface === true }; const available = (name: string) => piToolAvailabilityRefusal(currentTurn, name) === undefined; const env: SessionEnv = { - workerSignal: req.signal, + workerSignal: req.signal, cleanupActivity: req.bridge.activity, sessionBudgetLimits: req.sessionBudgetLimits, budgetContext: req.budgetContext, ...(req.workerStartupView ? { workerStartupView: req.workerStartupView } : {}), diff --git a/packages/ui-backend-pi/src/worker-launch.ts b/packages/ui-backend-pi/src/worker-launch.ts index 138e943691..634a4867b0 100644 --- a/packages/ui-backend-pi/src/worker-launch.ts +++ b/packages/ui-backend-pi/src/worker-launch.ts @@ -8,7 +8,7 @@ */ import { isWithin } from "@schlessera/brain-common/internal/safe-path"; import { brainWorkerPath } from "@schlessera/brain-common/internal/worker-areas"; -import { workerCleanupUnconfirmed, WORKER_PROVIDER_CREDENTIAL_ENV, workerProviderCredentials } from "@schlessera/brain-ui-sdk/internal"; +import { processCleanupReconciler, type CleanupReconciler, workerCleanupUnconfirmed, WORKER_PROVIDER_CREDENTIAL_ENV, workerProviderCredentials } from "@schlessera/brain-ui-sdk/internal"; import { existsSync, readFileSync, realpathSync, statSync } from "node:fs"; import { join, relative, isAbsolute } from "node:path"; import { stateRoomCopy, stateRoomWarning, type StateRoomObservation } from "@schlessera/brain-ui-sdk/protocol"; @@ -100,7 +100,7 @@ export async function admitPiWorker(request: PiWorkerAdmissionRequest): Promise< const path = join(agentDir, name); if (existsSync(path)) agentFiles[name] = readFileSync(path, "utf8"); } - const { workerSandbox, workerProviderMasks, workerDataTree, workerLock, workerStarted, workerStartupView, workerSignal, toolExecution, ...workerSessionEnv } = env; + const { workerSandbox, workerProviderMasks, workerDataTree, workerLock, workerStarted, workerStartupView, workerSignal, toolExecution, cleanupActivity: _cleanupActivity, ...workerSessionEnv } = env; const npmPath = envelope ? undefined : join(agentDir, "npm", "node_modules"); let cachedNpmModules: string | undefined; if (npmPath && existsSync(npmPath)) { @@ -287,7 +287,7 @@ export interface PiWorkerSupervision { * turn temp, relays, locks, stderr and host-limit reports. */ export function superviseWorker(worker: { child: LaunchedWorker; reservation: Reservation; turnTemp: WorkerStateHandle | undefined; - env: SessionEnv; turnContext: TurnContext; admission: Pick; answerText(): string }): PiWorkerSupervision { + env: SessionEnv; turnContext: TurnContext; admission: Pick; answerText(): string; cleanup?: CleanupReconciler }): PiWorkerSupervision { const { child, reservation, turnTemp, env, turnContext, answerText } = worker; const { envelope, hostInference } = worker.admission; const held = reservation; @@ -298,8 +298,18 @@ export function superviseWorker(worker: { child: LaunchedWorker; reservation: Re * separate-UID worker's broker cleanup is confirmed; a refusal keeps it * charged, and the next call tries again (#2854). */ - const closeTurnTemp = (): Promise => turnTempClosing ??= (async () => { await turnTemp?.closeAsync(); held.release(); })() - .catch((error: unknown) => { turnTempClosing = undefined; throw error; }); + let released = false; + const releaseReservation = () => { if (!released) { released = true; held.release(); } }; + 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 closeStorage = (): Promise => turnTempClosing ??= (async () => { await turnTemp?.closeAsync(); })() + .catch((error: unknown) => { + turnTempClosing = undefined; + (worker.cleanup ?? processCleanupReconciler()).retain(cleanup, error); + throw error; + }); + const closeTurnTemp = async () => { await closeStorage(); releaseReservation(); }; // The turn_temp tool reaches this worker's /tmp only while it runs (#1703). let workerLive = true; void child.exited.finally(() => { workerLive = false; }).catch(() => {}); diff --git a/packages/ui-backend-pi/tests/worker-session.test.ts b/packages/ui-backend-pi/tests/worker-session.test.ts index b223788973..a4c6002b3a 100644 --- a/packages/ui-backend-pi/tests/worker-session.test.ts +++ b/packages/ui-backend-pi/tests/worker-session.test.ts @@ -453,3 +453,34 @@ test("host exec survives the Pi worker init boundary; omitted factory options re if (old === undefined) delete process.env.BRAIN_UI_EXEC_WRAPPER; else process.env.BRAIN_UI_EXEC_WRAPPER = old; } }); + +test("initialization failure keeps a cleanup owner beyond the foreground retry limit", async () => { + const base = launch.getMockImplementation()!; + let closes = 0; + const pending: Array<() => void> = []; + const cleanup = worker.createCleanupReconciler({ attempts: 2, schedule: run => { pending.push(run); return () => {}; }, log() {} }); + const owner = spyOn(worker, "processCleanupReconciler").mockReturnValue(cleanup); + const baseline = worker.processStateLedger().turnTempHeld; + const notices: unknown[] = []; + launch.mockImplementation(async (...args: unknown[]) => { + const launched = await base(...args) as any; + launched.stdin = new Writable({ write(_chunk, _encoding, callback) { sendPipe(launched.stdout, { type: "error", message: "Odysseus refused the voyage" }); callback(); } }); + return { ...launched, turnTemp: { root, space: () => ({ total: 0, free: 0 }), + async closeAsync() { if (++closes <= 7) throw new Error("worker_identity_cleanup_unconfirmed"); } } }; + }); + try { + await expect(openPiWorkerSession({ brainPath: brain }, sessionDir, { caps: {} as never, cleanupActivity: notice => notices.push(notice) })).rejects.toThrow("Odysseus refused the voyage"); + expect(closes).toBe(1); + expect(cleanup.held, "PI_STARTUP_REFUSAL_HAS_RETRY_OWNER").toBe(1); + for (let i = 0; i < 6; i++) { + pending.shift()!(); await Bun.sleep(0); + expect(worker.processStateLedger().turnTempHeld, "PI_RETRY_REFUSAL_KEEPS_ALLOWANCE").toBeGreaterThan(baseline); + } + pending.shift()!(); await Bun.sleep(0); + expect(closes, "PI_RETRIES_PAST_FOREGROUND_LIMIT").toBe(8); + expect(cleanup.held).toBe(0); + expect(worker.processStateLedger().turnTempHeld, "PI_LATE_CONFIRMATION_RELEASES_ALLOWANCE").toBe(baseline); + expect(pending).toHaveLength(0); + expect(notices).toMatchObject([{ kind: "worker_cleanup", state: "retrying", message: "Error: worker_identity_cleanup_unconfirmed" }, { kind: "worker_cleanup", state: "resolved" }]); + } finally { cleanup.close(); owner.mockRestore(); } +}); diff --git a/packages/ui-sdk/src/internal.ts b/packages/ui-sdk/src/internal.ts index 0964b9d252..d1dbf996cc 100644 --- a/packages/ui-sdk/src/internal.ts +++ b/packages/ui-sdk/src/internal.ts @@ -96,3 +96,6 @@ export type { RemovalRun, SessionRetirement, SessionRetirementOptions } from "./ export { sessionReplayLocation } from "./server/session-replay.js"; export { sessionPromptContextLocation } from "./server/session-prompt-context.js"; export { nativeObservationIdentity } from "./server/native-observation-storage.js"; + +export { createCleanupReconciler, processCleanupReconciler, CLEANUP_RETRY_ATTEMPTS, CLEANUP_RETRY_BASE_MS, CLEANUP_RETRY_MAX_MS } from "./server/cleanup-reconciler.js"; +export type { CleanupNotice, CleanupReconciler, CleanupReconcilerOptions, RetainedCleanup } from "./server/cleanup-reconciler.js"; diff --git a/packages/ui-sdk/src/server/backend.ts b/packages/ui-sdk/src/server/backend.ts index 754e317ffa..de8a6c9cfd 100644 --- a/packages/ui-sdk/src/server/backend.ts +++ b/packages/ui-sdk/src/server/backend.ts @@ -317,6 +317,9 @@ interface PolicyCommandRecord { } export type BackendActivityEvent = + | { /** Host cleanup facts may arrive after the turn ended; no provider-facing content. */ + kind: "worker_cleanup"; state: "retrying" | "resolved"; bytes: number; turnTempBytes: number; + errorClass?: string; message?: string } | { kind: "prompt_prefix"; prefix: import("../protocol.js").PromptPrefixFingerprint; resumed: boolean } | { kind: "first_request_cache"; usage: import("../protocol.js").FirstRequestCacheUsage } diff --git a/packages/ui-sdk/src/server/cleanup-reconciler.ts b/packages/ui-sdk/src/server/cleanup-reconciler.ts new file mode 100644 index 0000000000..4eec6f8c1f --- /dev/null +++ b/packages/ui-sdk/src/server/cleanup-reconciler.ts @@ -0,0 +1,151 @@ +/** + * The owner of a refused end-of-turn worker cleanup (#2871). + * + * A 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 indefinitely with capped backoff, and releases the + * reservation exactly once, only after a close is confirmed. The transition + * to slow reconciliation is logged with its cause and retained allowance. Shutdown stops the retries, reports what is still held and + * releases nothing. + */ +import { mib } from "./worker-state-limits.js"; + +/** One refused cleanup, handed over by the turn that could not confirm it. */ +export interface CleanupNotice { + state: "retrying" | "resolved"; + bytes: number; + turnTempBytes: number; + errorClass?: string; + message?: string; +} + +export interface RetainedCleanup { + /** Captured host recorder, retained after the turn ends; never provider history. */ + report?(notice: CleanupNotice): void; + /** 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 reporting slow reconciliation; never a terminal limit. */ + 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, error?: unknown): void; + /** Cleanups still charged, awaiting confirmation. */ + 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>(); + const completed = new WeakSet(); + 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 === Math.max(1, attempts)) { + try { log(`Worker cleanup is still unconfirmed after ${made + 1} retries; ` + + `${allowance(cleanup.bytes, cleanup.turnTempBytes)} stay charged; reconciliation continues.`, error); } catch { /* Diagnostics cannot strand cleanup. */ } + } + plan(cleanup, Math.min(made + 1, 1024)); + return; + } + // Shutdown releases nothing, even a close confirmed after it began. + if (closed || !held.delete(cleanup)) return; + completed.add(cleanup); + cleanup.release(); + try { cleanup.report?.({ state: "resolved", bytes: cleanup.bytes, turnTempBytes: cleanup.turnTempBytes }); } catch { /* Observation only. */ } + })(); + }; + + 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, error) { + if (held.has(cleanup) || completed.has(cleanup)) return; + try { cleanup.report?.({ state: "retrying", bytes: cleanup.bytes, turnTempBytes: cleanup.turnTempBytes, + errorClass: error instanceof Error ? error.name : "UnknownError", message: String(error).slice(0, 2000) }); } catch { /* Observation only. */ } + if (closed) { + held.set(cleanup, undefined); + log(`Worker cleanup is unconfirmed during shutdown; ${allowance(cleanup.bytes, cleanup.turnTempBytes)} stay charged.`); + 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(`Worker cleanup reconciliation stopped with ${summary.held} unconfirmed cleanup${summary.held === 1 ? "" : "s"} ` + + `still holding ${allowance(bytes, turnTempBytes)}.`); + } + closed = true; + return summary; + }, + }; +} + +// Both backends share this owner, just as they share the reservation ledger. +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-server/src/activity/recorder.ts b/packages/ui-server/src/activity/recorder.ts index 73e2433bf6..1baaf2e802 100644 --- a/packages/ui-server/src/activity/recorder.ts +++ b/packages/ui-server/src/activity/recorder.ts @@ -464,6 +464,16 @@ export function createTurnRecorder( observeActivity(event) { guard(() => { + // Cleanup owns a reservation after its turn ends. Its receipt still + // belongs to this run; it never changes the run's terminal outcome. + if (event.kind === "worker_cleanup") { + ensureRoot(); + store.appendEvent(rootSpanId, "worker_cleanup", event); + log?.emit({ severityText: event.state === "retrying" ? "WARN" : "INFO", body: "Worker cleanup reconciliation", + attributes: { turnId: runId, ...event } }); + onWrite?.(); + return; + } if (finished) return; switch (event.kind) { diff --git a/packages/ui-server/src/app.ts b/packages/ui-server/src/app.ts index 41780621c1..5f9b0a5a8d 100644 --- a/packages/ui-server/src/app.ts +++ b/packages/ui-server/src/app.ts @@ -717,7 +717,7 @@ export async function createApp(options: CreateAppOptions = {}): Promise host.turnTimeoutMs }, { writer, catalog }); // Idle passes keep the observer initialized and current, and expire old // turns, off the next admission's path (#3355). - const journal = createTurnJournal(db, { nativeManager, brainPath: config.brainPath, dbPath: config.dbPath, objectsRoot: journalRoot, writer, idleObservationMs: 60_000, + const journal = createTurnJournal(db, { nativeManager, brainPath: config.brainPath, dbPath: config.dbPath, objectsRoot: journalRoot, writer, idleObservationMs: 60_000, log: brainLog, ...(referencePoolConfigured ? { referencePool: nativeManager, referenceCheckpoints: (() => { const owner = referenceWorktreeOwner(); return { record: (id: string, worktreeId: string) => recordReferenceWorktreeCheckpoint(db, owner, id, worktreeId), forget: (id: string) => forgetReferenceWorktreeCheckpoint(db, id) }; @@ -1062,6 +1062,7 @@ export async function createApp(options: CreateAppOptions = {}): Promise journal.cleanupStatus(), sourceCommit: config.sourceCommit, getBackendAvailability: () => backendAvailability, getContentRenderers: async signal => brain.modules ? declaredContentRenderers((await brain.modules({ signal })).enabled) : undefined, diff --git a/packages/ui-server/src/brain/compute-host.ts b/packages/ui-server/src/brain/compute-host.ts index a79661be2b..8e1d938502 100644 --- a/packages/ui-server/src/brain/compute-host.ts +++ b/packages/ui-server/src/brain/compute-host.ts @@ -549,7 +549,7 @@ export function createComputeHost(options: ComputeHostOptions): ComputeHost { // ------------------------------------------------------------------ driver - const tracked = new Map(); + const tracked = new Map(); const initialDelay = options.driver?.initialDelayMs ?? 2_000; const maxDelay = options.driver?.maxDelayMs ?? 15_000; const perPass = options.driver?.visitsPerPass ?? 16; @@ -580,10 +580,11 @@ export function createComputeHost(options: ComputeHostOptions): ComputeHost { async function pass(): Promise { if (closed) return; + if (busy) return busy; let finish!: () => void; busy = new Promise(resolve => { finish = resolve; }); try { - for (const id of [...tracked.keys()].slice(0, perPass)) { + for (const id of [...tracked].filter(([, entry]) => !entry.retryAt || entry.retryAt <= now()).slice(0, perPass).map(([id]) => id)) { if (closed) break; const entry = tracked.get(id); if (!entry) continue; @@ -591,14 +592,16 @@ export function createComputeHost(options: ComputeHostOptions): ComputeHost { try { if (await visit(id) === "keep") tracked.set(id, { failures: 0 }); } catch (error) { - if (entry.failures + 1 < maxFailures) tracked.set(id, { failures: entry.failures + 1 }); - else { - // Its reservation stays active, counting at its reserved amount, and - // the run stays open, flagged, until a restart reattaches it. - log("WARN", `hosted compute stopped advancing ${id} after ${maxFailures} failed visits; it is reattached at the next restart`, { error: String(error) }); + const failures = Math.min(entry.failures + 1, maxFailures); + tracked.set(id, { failures, ...(failures >= maxFailures ? { retryAt: now() + maxDelay } : {}) }); + if (entry.failures < maxFailures && failures >= maxFailures) { + // Keep the reservation and retry owner until positive settlement. + const cause = error instanceof Error ? `${error.name}: ${error.message}` : String(error); + log("WARN", `hosted compute ${id} entered slow reconciliation after ${maxFailures} failed visits`, { error: cause, retrying: true }); const row = jobRow(id), store = options.activity?.store; if (row && row.settled_at === null && store) activityWrite("stuck", () => store.patchSpan(row.run_id, { attrs: { "brain.compute.stuck": true, - "brain.compute.uncertain": `the host stopped advancing it after ${maxFailures} failed visits; it is reattached at the next restart` } })); + "brain.compute.uncertain": `Visits failed: ${cause}; reconciliation continues with its reservation held`, + "brain.compute.reconcile_failed_at": now() } })); } } } diff --git a/packages/ui-server/src/brain/native-journal-capture.ts b/packages/ui-server/src/brain/native-journal-capture.ts index fe3afad93c..1f4a4aa3c6 100644 --- a/packages/ui-server/src/brain/native-journal-capture.ts +++ b/packages/ui-server/src/brain/native-journal-capture.ts @@ -16,7 +16,7 @@ export function createNativeJournalCapture(manager: NativeJournalManager, retain */ rootScope: { steering: boolean; index: boolean } = { steering: true, index: true }, /** A previous checkpoint's release failed after its observation committed (#2872). */ - releaseFailed?: (error: unknown) => void) { + releaseFailed?: (error: unknown, checkpointId: string) => void) { const workerUid = () => { if (!identity || !workerIdentityHelper()) return undefined; const actual = verifiedWorkerIdentity(identity.brainPath); diff --git a/packages/ui-server/src/brain/native-journal-observer.ts b/packages/ui-server/src/brain/native-journal-observer.ts index 7c133b91f6..e6b05becd3 100644 --- a/packages/ui-server/src/brain/native-journal-observer.ts +++ b/packages/ui-server/src/brain/native-journal-observer.ts @@ -275,7 +275,7 @@ export interface NativeJournalReleaseAccounting { * `releaseFailed` is told when a previous checkpoint's release fails after its * observation committed, outside the caller's hold. */ -export function createNativeJournalObserver(native: NativeJournalManager, workerUid?: () => number | undefined, releaseFailed?: (error: unknown) => void) { +export function createNativeJournalObserver(native: NativeJournalManager, workerUid?: () => number | undefined, releaseFailed?: (error: unknown, checkpointId: string) => void, releaseRetryMs = 30_000) { let index = new MetadataIndex(), root: NativeJournalCheckpoint | undefined; let missingInventory = new Map(); const uncertain = (path: string) => { @@ -307,8 +307,18 @@ export function createNativeJournalObserver(native: NativeJournalManager, worker } // The cleanup owner of previous checkpoints: one release at a time, in commit // order, once the capture that superseded each is recorded (#2872). - const outstanding = new Map(); + const outstanding = new Map(); let releasing: Promise | undefined; + let retryTimer: ReturnType | undefined; + function retryLater(): void { + if (closed || retryTimer || ![...outstanding.values()].some(entry => entry.state === "failed")) return; + retryTimer = setTimeout(() => { + retryTimer = undefined; + for (const entry of outstanding.values()) if (entry.state === "failed") entry.state = "pending"; + releaseNext(); + }, releaseRetryMs); + retryTimer.unref?.(); + } const settledWaiters = new Set<() => void>(); const queued = () => [...outstanding.values()].filter(entry => entry.state === "pending").length; function releaseNext(): void { @@ -318,8 +328,12 @@ export function createNativeJournalObserver(native: NativeJournalManager, worker const [id, entry] = next; releasing = release(id).then(() => { outstanding.delete(id); }, error => { // The checkpoint stays retained and charged until a retry releases it. - entry.state = "failed"; - try { releaseFailed?.(error); } catch { /* Reporting never blocks the next release. */ } + entry.state = "failed"; entry.error = error; + if (!entry.reported) { + entry.reported = true; + try { releaseFailed?.(error, id); } catch { /* Reporting never blocks the next release. */ } + } + retryLater(); }).finally(() => { releasing = undefined; releaseNext(); }); } function releasesSettled(): Promise { @@ -335,8 +349,11 @@ export function createNativeJournalObserver(native: NativeJournalManager, worker async function reserveRelease(): Promise { while (outstanding.size >= NATIVE_RELEASE_BACKLOG) { if (queued()) { await releasing; continue; } - const [id] = outstanding.keys(); - await release(id!); outstanding.delete(id!); + const [id, entry] = outstanding.entries().next().value!; + entry.state = "pending"; + releaseNext(); + await releasing; + if (outstanding.get(id)?.state === "failed") throw entry.error; } } function deferRelease(id: string, bytes: number): void { @@ -494,7 +511,7 @@ export function createNativeJournalObserver(native: NativeJournalManager, worker releasesSettled, /** Drains queued releases, retries failed ones, and reports any checkpoint still retained. */ async close() { - closed = true; shutdown.abort(new Error("native_observer_closed")); + closed = true; clearTimeout(retryTimer); retryTimer = undefined; shutdown.abort(new Error("native_observer_closed")); await initializing?.catch(() => {}); await inFlight?.catch(() => {}); if (pending) await pending.abort().catch(() => {}); await releasesSettled(); diff --git a/packages/ui-server/src/brain/turn-journal.ts b/packages/ui-server/src/brain/turn-journal.ts index 3d37da396b..13aa48f48b 100644 --- a/packages/ui-server/src/brain/turn-journal.ts +++ b/packages/ui-server/src/brain/turn-journal.ts @@ -1,4 +1,5 @@ /** Concrete host journal: observations, durable ownership and completed-turn collection. */ +import type { Logger } from "@opentelemetry/api-logs"; import { isWithin } from "@schlessera/brain-common/internal/safe-path"; import type { Database, SQLQueryBindings } from "bun:sqlite"; import type { ConfigurationCoverageRead, JournalVersion, TurnJournalDetails, TurnJournalSummary, JournalOutwardAction, JournalObservationReference } from "@schlessera/brain-ui-sdk/protocol"; @@ -23,6 +24,10 @@ import { constants, lstatSync, realpathSync } from "node:fs"; import { open, unlink } from "node:fs/promises"; import { join } from "node:path"; +import { getSetting } from "../db/settings.js"; +import { createSettingsWrites } from "../db/settings-writes.js"; +import { createOffloopActivityStore } from "../activity/store-writes.js"; + import { queryGovernanceEvents } from "../governance/events.js"; const RETENTION_MS = 30 * 24 * 60 * 60 * 1000; @@ -93,6 +98,8 @@ export interface TurnJournalOptions { * next admission does not. Absent, all of that waits for an admission. */ idleObservationMs?: number; + /** Structured log for cleanup retries; absent, they are recorded durably only. */ + log?: Logger; } export function createTurnJournal(db: Database, options: TurnJournalOptions) { @@ -172,21 +179,23 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { await reservation.release(); throw error; } } }; - /** - * A previous checkpoint is released after the observation that superseded it - * committed, and the hold does not wait for it (#2872). A failed release keeps - * the outcome it had inside the hold: every active turn stops and its record - * is partial, a hold it overlaps kills its held workers instead of resuming - * them, and an admission requested before it is refused. - */ - let releaseFailures = 0; - const releaseFailed = (error: unknown) => { - releaseFailures++; - const failure = storageError(error); - for (const [id, turn] of active) { - void fail(id, failure).catch(() => {}); - try { turn.stop(failure); } catch { /* Continue stopping every participant. */ } + const cleanupActivity = createOffloopActivityStore(db, writer); + const cleanupSettings = createSettingsWrites(db, writer); + /** Superseded checkpoint cleanup reclaims space; its committed observation remains valid. */ + const releaseFailed = (error: unknown, checkpointId: string) => { + const notice = { kind: "checkpoint_release_retry", checkpointId, at: now(), scope: "superseded_checkpoint", + errorClass: error instanceof Error ? error.name : "UnknownError", cause: String(error).slice(0, 2000), retrying: true }; + options.log?.emit({ severityText: "WARN", body: `Superseded checkpoint ${checkpointId} release failed; retrying`, + attributes: { "journal.cleanup.scope": notice.scope, "journal.cleanup.checkpoint": checkpointId, "error.type": notice.errorClass, "journal.cleanup.retrying": true } }); + tracked(Promise.resolve(cleanupSettings.setSetting("journal.cleanup.lastFailure", notice))).catch(() => {}); + // The root span is kept with the turn in authenticated Activity, even + // though its observation is complete and its workers keep running. + const ids = [...active.keys()]; + if (!ids.length) { + const latest = db.query("SELECT turn_id FROM turn_journal_turns ORDER BY started_at DESC LIMIT 1").get() as { turn_id: string } | null; + if (latest) ids.push(latest.turn_id); } + for (const id of ids) tracked(Promise.resolve(cleanupActivity.appendEvent(`${id}:turn`, "checkpoint_release_retry", notice))).catch(() => {}); }; const capture = createNativeJournalCapture(options.nativeManager, retainVersion, {}, readIdentity, undefined, releaseFailed); /** @@ -246,7 +255,6 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { let acquired = 0; try { for (const holder of holders) { acquired++; holder.before(); } } catch (error) { holds--; for (const holder of holders.slice(0, acquired)) holder.after(false); return Promise.reject(error); } - const releasesBefore = releaseFailures; return serialize(async () => { let completed = false; const failedBefore = observationFailures; @@ -254,8 +262,8 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { finally { // A cancelled/refused new admission made no worker writes. Existing // participants resume when their shared observation itself succeeded, - // and no release failed while they were held. - const safe = (completed || admission && observationFailures === failedBefore) && releaseFailures === releasesBefore; + // even if reclaiming a superseded checkpoint failed. + const safe = (completed || admission && observationFailures === failedBefore); holds--; for (const holder of holders) holder.after(safe); } }); @@ -463,8 +471,6 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { }, begin(turnId: string, metadata: { sessionId: string | null; actor: "interactive" | "voice" | "user"; model: string | null; profile: "strict" | "governed"; policyHash: string | null; coveredPaths?: readonly string[] }, stop: (error: Error) => void, signal?: AbortSignal, /** Each step of the admission (#3355); a failed step is left unended. */ timing?: PhaseTimer) { - // Taken when the admission is requested, before it queues behind other journal work. - const releasesBefore = releaseFailures; const waited = timing?.("hold_wait"); return held(async () => { waited?.(); @@ -489,8 +495,6 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { const policy = await capture.policy(metadata.coveredPaths); end?.(); signal?.throwIfAborted(); - // A release that failed during this admission refuses it, as it did when it failed this admission's observation. - if (releaseFailures !== releasesBefore) throw new JournalStorageUnavailable("a native checkpoint release failed during admission"); active.set(turnId, { policy, stop, sequence: 0, sessionId: metadata.sessionId }); publish(turnId); if (!scopeTimer) { scopeTimer = setInterval(() => { @@ -576,6 +580,15 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { /** Worktrees an active turn's journal observes. */ worktrees(turnId: string): string[] { return [...worktrees].filter(([, root]) => root.turnId === turnId).map(([id]) => id); }, isHeld(): boolean { return holds > 0; }, + /** Current retained charges, plus the durable historical cause even before any turn existed. */ + cleanupStatus() { + const retained = capture.releases(); + for (const root of worktrees.values()) { + const other = root.capture.releases(); + retained.pending += other.pending; retained.failed += other.failed; retained.retainedBytes += other.retainedBytes; + } + return { retained, lastFailure: getSetting(db, "journal.cleanup.lastFailure", null) }; + }, /** @internal Settles once every previous checkpoint handed to release so far has been attempted (#2872). */ async releasesSettled(): Promise { await capture.releasesSettled(); diff --git a/packages/ui-server/src/inbox/autonomous-turn.ts b/packages/ui-server/src/inbox/autonomous-turn.ts index 967713a19a..3f4141f26a 100644 --- a/packages/ui-server/src/inbox/autonomous-turn.ts +++ b/packages/ui-server/src/inbox/autonomous-turn.ts @@ -278,7 +278,7 @@ async function executeAutonomousTurn( const bridge: BackendBridge = { ...inbox, emit, - activity: (event) => { if (!closed) { checkPrincipal(); recorder.observeActivity(event); } }, + activity: (event) => { if (event.kind === "worker_cleanup") recorder.observeActivity(event); else if (!closed) { checkPrincipal(); recorder.observeActivity(event); } }, checkpointPermission: (request) => checkpoint({ kind: "permission", request }), requestPermission: async (request) => { checkpoint({ kind: "permission", request }); diff --git a/packages/ui-server/src/routes/health.ts b/packages/ui-server/src/routes/health.ts index c2bbbc2f70..cd6b28dd33 100644 --- a/packages/ui-server/src/routes/health.ts +++ b/packages/ui-server/src/routes/health.ts @@ -41,6 +41,8 @@ export function createHealthRoutes(deps: { db: Database; degradedReasons?(): str } interface StatusDeps { + /** Retained checkpoint cleanup and its durable historical cause. */ + getJournalCleanup?(): unknown; getBackendAvailability?(): { unavailable: BackendBootFailure[]; lastFailures: BackendBootFailure[] }; /** Trusted metadata from configured modules; absent with an older CLI. */ getContentRenderers?(signal?: AbortSignal): Promise; @@ -70,6 +72,7 @@ export function createStatusRoutes(deps: StatusDeps): Hono { ...(contentRenderers !== undefined ? { contentRenderers } : {}), healthy: !backendAvailability?.unavailable.length, ...(backendAvailability ? { backendAvailability } : {}), + ...(deps.getJournalCleanup ? { journalCleanup: deps.getJournalCleanup() } : {}), uptime: Date.now() - startTime, version: deps.sourceCommit, software: { release: packageInfo.version, sourceCommit: deps.sourceCommit }, diff --git a/packages/ui-server/tests/activity-recorder.test.ts b/packages/ui-server/tests/activity-recorder.test.ts index 6d1e6071eb..c121e819e1 100644 --- a/packages/ui-server/tests/activity-recorder.test.ts +++ b/packages/ui-server/tests/activity-recorder.test.ts @@ -353,3 +353,19 @@ describe("a denial the host never saw (#110)", () => { ).toContain("approval_decision"); }); }); + +test("cleanup diagnostics remain durable after the turn finishes without changing its outcome", async () => { + const { db, store, recorder } = setup("odysseus-cleanup"); + try { + recorder.finish("error"); + recorder.observeActivity({ kind: "worker_cleanup", state: "retrying", bytes: 4096, turnTempBytes: 8192, + errorClass: "Error", message: "worker_identity_cleanup_unconfirmed" }); + await recorder.settled(); + const events = db.query("SELECT payload FROM activity_events WHERE span_id=? AND event_type='worker_cleanup'").all("odysseus-cleanup:turn"); + expect(JSON.stringify(events), "OWNER_CLEANUP_CAUSE_DURABLE").toContain("worker_identity_cleanup_unconfirmed"); + recorder.observeActivity({ kind: "worker_cleanup", state: "resolved", bytes: 4096, turnTempBytes: 8192 }); + await recorder.settled(); + expect(JSON.stringify(db.query("SELECT * FROM activity_events WHERE span_id=?").all("odysseus-cleanup:turn"))).toContain("resolved"); + expect(store.getSpan("odysseus-cleanup:turn")!.outcome).toBe("error"); + } finally { db.close(); } +}); diff --git a/packages/ui-server/tests/compute-host.test.ts b/packages/ui-server/tests/compute-host.test.ts index 7fb317810b..f530d55dd0 100644 --- a/packages/ui-server/tests/compute-host.test.ts +++ b/packages/ui-server/tests/compute-host.test.ts @@ -458,7 +458,7 @@ describe("ledger settlement", () => { } } as never } }); await f.begin("t-1"); const started = ok(await f.host.forTurn(f.turn("t-1"))(run())); - for (let i = 0; i < 3; i++) await f.host.drive(); + for (let i = 0; i < 8; i++) await f.host.drive(); expect({ released: f.fake.liveSandboxes(), reservation: reservation(f, started.job.id), row: hostRow(f, started.job.id), outcome: f.store.getSpan(`compute:${started.job.id}`)!.outcome }, "FAILED_SETTLE_KEEPS_JOB_OPEN").toEqual({ released: 0, reservation: { status: "active", actual_usd: null }, row: null, outcome: null }); failing = false; @@ -527,3 +527,26 @@ describe("boot", () => { expect(warnings).toEqual([expect.stringContaining("hosted external compute is off: the host compute state directory is not masked from workers")]); }); }); + +test("failed compute visits reconcile beyond maxFailures without a restart or new turn", async () => { + let failing = false, visits = 0; + const f = fixture({ config: summary({ "boat-small": { hourlyCeilingUsd: 0.6 } }), host: { + driver: { initialDelayMs: 2, maxDelayMs: 10, maxFailures: 2 }, + credential() { if (failing) { visits++; throw new Error("Odysseus credential store unavailable"); } return SENTINEL; }, + } }); + await f.begin("t-1"); + const started = ok(await f.host.forTurn(f.turn("t-1"))(run())); + failing = true; + try { + await until(() => visits >= 8, "COMPUTE_RETRIES_BEYOND_FOREGROUND_LIMIT", 1000); + expect(f.db.query("SELECT status FROM compute_budget_reservations WHERE job_id=?").get(started.job.id), "COMPUTE_UNCERTAIN_RESERVATION_HELD").toEqual({ status: "active" }); + expect(f.budgets.receipt("t-1").scopes[0]!.costUsd, "COMPUTE_UNCERTAIN_CHARGE_RETAINED").toBeCloseTo(0.6); + const span = f.store.getSpan(`compute:${started.job.id}`)!; + expect(span.attrs["brain.compute.stuck"]).toBe(true); + expect(span.attrs["brain.compute.uncertain"]).toContain("Odysseus credential store unavailable"); + failing = false; + await until(() => f.store.getSpan(`compute:${started.job.id}`)!.outcome === "success", "COMPUTE_AUTOMATIC_LATE_SETTLEMENT"); + expect(f.db.query("SELECT status FROM compute_budget_reservations WHERE job_id=?").get(started.job.id)).toEqual({ status: "settled" }); + expect(f.store.getSpan(`compute:${started.job.id}`)!.attrs["brain.compute.stuck"]).toBe(false); + } finally { failing = false; } +}); diff --git a/packages/ui-server/tests/native-journal-observer.test.ts b/packages/ui-server/tests/native-journal-observer.test.ts index eba4c16a7e..a544af6879 100644 --- a/packages/ui-server/tests/native-journal-observer.test.ts +++ b/packages/ui-server/tests/native-journal-observer.test.ts @@ -155,14 +155,14 @@ test("invalid UTF-8 initial names refuse and release the initial root",async()=> }); /** Copied roots whose releases wait for the test, one deferred per release. */ -function releaseFixture() { +function releaseFixture(retryMs?: number) { const root=mkdtempSync(join(tmpdir(),"native-observer-release-odysseus-")),brain=join(root,"brain"); mkdirSync(join(brain,"notes"),{recursive:true});writeFileSync(join(brain,"notes","ithaca.md"),"Penelope waits at Ithaca.\n"); const native=createNativeJournalFixture(brain,root),release=native.manager.release.bind(native.manager),checkpoint=native.manager.checkpoint.bind(native.manager); const counts={checkpoints:0};native.manager.checkpoint=(id,signal)=>{counts.checkpoints++;return checkpoint(id,signal);}; const waiting:{id:string;settle(error?:Error):void}[]=[],unsettled=new Set<{settle(error?:Error):void}>(),failures:unknown[]=[]; native.manager.release=id=>new Promise((resolve,reject)=>{const entry={id,settle(error?:Error){unsettled.delete(entry);if(error)reject(error);else resolve(release(id));}};unsettled.add(entry);waiting.push(entry);}); - const observer=createNativeJournalObserver(native.manager,undefined,error=>failures.push(error)); + const observer=createNativeJournalObserver(native.manager,undefined,error=>failures.push(error),retryMs); const next=async()=>{for(let attempt=0;attempt<200&&!waiting.length;attempt++)await Bun.sleep(5);return waiting.shift()!;}; return {brain,native,observer,waiting,failures,next,counts,async close(){native.manager.release=release;waiting.length=0;for(const entry of [...unsettled])entry.settle();await observer.close().catch(()=>{});await native.close();rmSync(root,{recursive:true,force:true});}}; } @@ -296,3 +296,26 @@ test("repeating a commit hands its checkpoint over once, and retries it after a expect(f.observer.releases()).toEqual({pending:0,failed:0,retainedBytes:0}); }finally{await f.close();} }); + + +test("a superseded checkpoint retries without another observation and keeps its bytes until confirmed", async () => { + const f = releaseFixture(5); + try { + await f.observer.initialize(); + const first = f.observer.currentRoot(); + writeFileSync(join(f.brain, "notes", "ithaca.md"), "The suitors are gone.\n"); + await (await f.observer.observe()).commit(); + const failed = await f.next(); + expect(failed.id).toBe(first.id); + failed.settle(new Error("Odysseus checkpoint delete refused")); + await f.observer.releasesSettled(); + expect(f.observer.releases().retainedBytes).toBe("Penelope waits at Ithaca.\n".length); + const retry = await f.next(); + expect(retry, "CHECKPOINT_BACKGROUND_RETRY_OWNED").toBeDefined(); + expect(retry.id).toBe(first.id); + expect(f.observer.releases().retainedBytes).toBe("Penelope waits at Ithaca.\n".length); + retry.settle(); + await f.observer.releasesSettled(); + expect(f.observer.releases()).toEqual({ pending: 0, failed: 0, retainedBytes: 0 }); + } finally { await f.close(); } +}); diff --git a/packages/ui-server/tests/turn-journal.test.ts b/packages/ui-server/tests/turn-journal.test.ts index 577d9fc44f..e6335ea34c 100644 --- a/packages/ui-server/tests/turn-journal.test.ts +++ b/packages/ui-server/tests/turn-journal.test.ts @@ -7,12 +7,14 @@ import { expectRejection } from "./helpers/expect-rejection.js"; import { closeSync, fstatSync, mkdtempSync, mkdirSync, openSync, rmSync, writeFileSync, readFileSync, statSync, existsSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; +import { createActivityStore } from "../src/activity/store.js"; import { createUiDb } from "../src/db/client.js"; import { createNativeJournalCapture } from "../src/brain/native-journal-capture.js"; import { createTurnJournal } from "../src/brain/turn-journal.js"; import { journalStatement } from "../src/brain/journal-store.js"; import { configurationSet } from "../src/brain/journal-configuration-sets.js"; import { recordGovernanceEvent, queryGovernanceEvents } from "../src/governance/events.js"; +import { createStatusRoutes } from "../src/routes/health.js"; import { createJournalRoutes } from "../src/routes/journal.js"; import { exportInboxSnapshot } from "../src/inbox/snapshot.js"; @@ -243,13 +245,15 @@ test("a delayed observation holds authority synchronously until its complete ser } finally { resume(); await f.close(); } }); -test("a previous checkpoint is released after the hold, and a release failure found there still stops every active turn", async () => { +test("a previous checkpoint is released after the hold, and a release failure leaves every active turn running", async () => { const f = fixture(); const release = f.native.manager.release; let fail: ((error: Error) => void) | undefined, entered!: () => void; const started = new Promise(resolve => { entered = resolve; }); try { const stopped: Error[] = []; + const activity = createActivityStore(f.db); + for (const id of ["telemachus", "penelope"]) activity.startSpan({ spanId: `${id}:turn`, runId: id, name: "Voyage", kind: "turn", origin: "session" }); for (const id of ["telemachus", "penelope"]) await f.journal.begin(id, { sessionId: "ithaca", actor: "interactive", model: null, profile: "governed", policyHash: null }, error => stopped.push(error)); await f.journal.releasesSettled(); @@ -263,16 +267,19 @@ test("a previous checkpoint is released after the hold, and a release failure fo expect(f.journal.summary("telemachus").state).toBe("recording"); fail!(new Error("Odysseus release refused")); await f.journal.releasesSettled(); - expect(stopped.length, "JOURNAL_LATE_RELEASE_FAILURE_STOPS_EVERY_ACTIVE_TURN").toBe(2); + expect(stopped, "JOURNAL_RELEASE_FAILURE_LEAVES_TURNS_RUNNING").toEqual([]); await f.journal.idle(); - for (const id of ["telemachus", "penelope"]) expect(f.journal.summary(id).state, `JOURNAL_LATE_RELEASE_FAILURE_PARTIAL ${id}`).toBe("partial"); + for (const id of ["telemachus", "penelope"]) expect(f.journal.summary(id).state, `JOURNAL_RELEASE_FAILURE_STILL_RECORDING ${id}`).toBe("recording"); + const diagnostics = f.db.query("SELECT payload FROM activity_events WHERE event_type='checkpoint_release_retry'").all(); + expect(diagnostics, "CHECKPOINT_CAUSE_DURABLE_FOR_BOTH_TURNS").toHaveLength(2); + expect(JSON.stringify(diagnostics)).toContain("Odysseus release refused"); f.native.manager.release = release; for (const id of ["telemachus", "penelope"]) await f.journal.finish(id); - expect(f.journal.summary("telemachus").state).toBe("partial"); + expect(f.journal.summary("telemachus").state).toBe("complete"); } finally { fail?.(new Error("Odysseus cleanup")); f.native.manager.release = release; await f.close(); } }); -test("a release failing during an admission refuses it and fails the hold it overlaps", async () => { +test("a release failing during admission preserves admission and resumes its hold", async () => { const f = fixture(); const release = f.native.manager.release; try { @@ -282,17 +289,17 @@ test("a release failing during an admission refuses it and fails the hold it ove f.journal.onObservation(() => {}, { before() {}, after(ok) { completed.push(ok); } }); // The release begun by this admission's observation fails before the admission registers its turn. f.native.manager.release = async () => { throw new Error("Odysseus release refused"); }; - await expectRejection(f.begin("penelope"), "release failed during admission"); + await f.begin("penelope"); await f.journal.releasesSettled(); await f.journal.idle(); - expect(f.journal.summary("penelope").state, "JOURNAL_ADMISSION_REFUSED_BY_LATE_RELEASE_FAILURE").not.toBe("recording"); - expect(stopped.length, "JOURNAL_ACTIVE_TURN_STOPPED_BY_LATE_RELEASE_FAILURE").toBe(1); - expect(completed, "JOURNAL_OVERLAPPED_HOLD_DOES_NOT_RESUME").toEqual([false]); + expect(f.journal.summary("penelope").state, "JOURNAL_ADMISSION_SURVIVES_RELEASE_FAILURE").toBe("recording"); + expect(stopped, "JOURNAL_RELEASE_FAILURE_STOPS_NOTHING").toEqual([]); + expect(completed, "JOURNAL_OVERLAPPED_HOLD_RESUMES").toEqual([true]); f.native.manager.release = release; await f.journal.finish("telemachus"); await f.journal.finish("penelope"); } finally { f.native.manager.release = release; await f.close(); } }); -test("an admission queued behind other journal work is refused when a release fails while it waits", async () => { +test("an admission queued behind other journal work survives a superseded release failure", async () => { const f = fixture(); const release = f.native.manager.release, delta = f.native.manager.delta; let fail: ((error: Error) => void) | undefined, resume!: () => void, entered!: () => void; @@ -311,9 +318,9 @@ test("an admission queued behind other journal work is refused when a release fa fail!(new Error("Odysseus release refused")); fail = undefined; f.native.manager.release = release; f.native.manager.delta = delta; resume(); await occupied.catch(() => {}); - await expectRejection(queued, "release failed during admission"); - expect(stopped.length, "JOURNAL_ACTIVE_TURN_STOPPED_BY_LATE_RELEASE_FAILURE").toBe(1); - expect(f.journal.summary("penelope").state, "JOURNAL_QUEUED_ADMISSION_REFUSED_BY_RELEASE_FAILURE").not.toBe("recording"); + await queued; + expect(stopped, "JOURNAL_RELEASE_FAILURE_STOPS_NOTHING").toEqual([]); + expect(f.journal.summary("penelope").state, "JOURNAL_QUEUED_ADMISSION_SURVIVES_RELEASE_FAILURE").toBe("recording"); await f.journal.finish("telemachus"); await f.journal.finish("penelope"); } finally { fail?.(new Error("Odysseus cleanup")); resume(); f.native.manager.release = release; f.native.manager.delta = delta; await f.close(); } }); @@ -719,3 +726,25 @@ test("native capture excludes an alternate trusted index identity without a publ } catch (error) { await observed.abort(); throw error; } } finally { await capture.close(); await f.close(); } }); + + +test("idle checkpoint cleanup records its cause durably before any turn exists and exposes authenticated status", async () => { + const f = fixture(); + const release = f.native.manager.release; + try { + f.native.manager.release = async () => { throw new Error("Odysseus idle checkpoint release refused"); }; + await f.journal.observe(); + await f.journal.releasesSettled(); await f.journal.idle(); + expect(f.db.query("SELECT count(*) AS n FROM turn_journal_turns").get()).toEqual({ n: 0 }); + const saved = new Database(join(f.root, "ui.db"), { readonly: true }); + try { + const failure = saved.query("SELECT value FROM settings WHERE key='journal.cleanup.lastFailure'").get(); + expect(failure, "IDLE_CLEANUP_CAUSE_DURABLE").not.toBeNull(); + expect(failure).toMatchObject({ value: expect.stringContaining("Odysseus idle checkpoint release refused") }); + } finally { saved.close(); } + const routes = createStatusRoutes({ sourceCommit: "fixture", getCronStatus: () => [], isTurnActive: () => false, + getJournalCleanup: () => f.journal.cleanupStatus() }); + const status = await (await routes.request("/status")).json() as any; + expect(status.journalCleanup).toMatchObject({ retained: { failed: 1 }, lastFailure: { cause: "Error: Odysseus idle checkpoint release refused" } }); + } finally { f.native.manager.release = release; await f.close(); } +}); diff --git a/scripts/check-unused-exports.ts b/scripts/check-unused-exports.ts index b5a063b337..84db313648 100644 --- a/scripts/check-unused-exports.ts +++ b/scripts/check-unused-exports.ts @@ -64,7 +64,6 @@ export const ALLOWLIST: AllowlistEntry[] = [ { file: "packages/ui-react/src/stores/session-list-state.ts", name: "SessionListState", reason: INFERRED("createBrainStores") }, { file: "packages/ui-react/src/stores/share-state.ts", name: "ShareIntakeState", reason: INFERRED("useShareStore and createBrainStores") }, { file: "packages/ui-react/src/stores/tracker-state.ts", name: "TrackerStoreState", reason: INFERRED("createBrainStores") }, - { file: "packages/ui-server/src/brain/native-journal-observer.ts", name: "NativeJournalReleaseAccounting", reason: INFERRED("createNativeJournalCapture") }, { file: "packages/ui-server/src/inbox/cleanup.ts", name: "CleanupReport", reason: INFERRED("createInboxRuntime") }, { file: "packages/ui-server/src/inbox/cleanup.ts", name: "CleanupRequest", reason: INFERRED("createInboxRuntime") }, // Readers of source text rather than importers.