diff --git a/.changeset/contain-single-host-failures.md b/.changeset/contain-single-host-failures.md new file mode 100644 index 0000000000..16ada72063 --- /dev/null +++ b/.changeset/contain-single-host-failures.md @@ -0,0 +1,6 @@ +--- +"@schlessera/brain-ui-sdk": minor +"@schlessera/brain-ui-server": minor +--- + +Recover failed writer-gate deletes and disposable native indexes automatically; quarantine corrupt history and unreadable native intents without refusing host startup. Preserve each surviving stage's historical storage bound and expose native recovery restrictions in authenticated status. diff --git a/api-report/ui-sdk.txt b/api-report/ui-sdk.txt index 68b8281450..36cb2a2553 100644 --- a/api-report/ui-sdk.txt +++ b/api-report/ui-sdk.txt @@ -12190,6 +12190,11 @@ signatures (every public export and the types it is made of) } SystemStatus (packages/ui-sdk/src/protocol.ts) export interface SystemStatus { + nativeRecovery?: { + quarantinedIntents: number; + stagingChargedBytes: number | null; + diagnosticsPath: string; + }; healthy: boolean; uptime: number; version: string; diff --git a/api-report/ui-server.txt b/api-report/ui-server.txt index f892c6d7af..64eb805679 100644 --- a/api-report/ui-server.txt +++ b/api-report/ui-server.txt @@ -1590,6 +1590,11 @@ signatures (every public export and the types it is made of) availableBytes: number; recoveryReserveBytes: number; reserveAllocatedBytes: number; + recovery?: { + quarantinedIntents: number; + stagingChargedBytes: number | null; + diagnosticsPath: string; + }; } NativePoolAccess (packages/ui-sdk/src/server/native-brain-manager-protocol.ts) export interface NativePoolAccess { diff --git a/docs/decisions/bounded-multi-read.md b/docs/decisions/bounded-multi-read.md index 7355a9c9f5..178a271924 100644 --- a/docs/decisions/bounded-multi-read.md +++ b/docs/decisions/bounded-multi-read.md @@ -151,7 +151,7 @@ parallel default, with concurrency 1. proves only `read_file`, `write_file` and `edit_file`. So (`toolObservation`, `packages/ui-server/src/brain/tool-observation.ts:37-42`) calls it `unproven`, and - (`toolEnded`, `packages/ui-server/src/brain/turn-journal.ts:551-558`) + (`toolEnded`, `packages/ui-server/src/brain/turn-journal.ts:555-562`) observes every result and marks the turn lasting. Four reads made four observations, sequential or parallel. One batch call made one. That is a real host-side saving, small in time (8.3 ms against 1.4 ms on the fixture). diff --git a/docs/decisions/claude-code-runtime.md b/docs/decisions/claude-code-runtime.md index 1a08652888..4d0203e9f6 100644 --- a/docs/decisions/claude-code-runtime.md +++ b/docs/decisions/claude-code-runtime.md @@ -268,7 +268,7 @@ than refuses on a mismatch.** first proof of that. - **Where it shows.** `/api/status`, which is behind the auth guard and already reports the source commit (`Operational status`, - `packages/ui-server/src/routes/health.ts:61-79`), and the run record. Not + `packages/ui-server/src/routes/health.ts:62-80`), and the run record. Not `/api/health`: it is public and deliberately carries no version (`Public liveness probe`, `health.ts:15-17`). Not `brain doctor`: it runs on the user's machine against a different binary. diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index 29689114d5..9bbb86ee3a 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:246-267`), +(`function held`, `packages/ui-server/src/brain/turn-journal.ts:250-271`), 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:551-558`). Admission, turn end, +`packages/ui-server/src/brain/turn-journal.ts:555-562`). Admission, turn end, the 15-second timer, scope-limit observations, approved policy writes and removal coverage observe exactly as before. @@ -1602,11 +1602,11 @@ with retained bytes. **What the journal records.** Observation and before-version capture classify these versions as metadata-only and never open them for retention (`const retained = (entry`, -`packages/ui-server/src/brain/native-journal-capture.ts:40`). A version keeps +`packages/ui-server/src/brain/native-journal-capture.ts:41`). A version keeps 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:81`), +(`const identity`, `packages/ui-server/src/brain/turn-journal.ts:82`), 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:74-79`). +(`const presented`, `packages/ui-server/src/brain/turn-journal.ts:75-80`). 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 @@ -1675,11 +1675,11 @@ keeps its bytes. **The purge.** It runs once, on the journal's write worker, when the journal opens, after interrupted turns have been ended -(`while (await ledger.call`, `packages/ui-server/src/brain/turn-journal.ts:121`), +(`while (await ledger.call`, `packages/ui-server/src/brain/turn-journal.ts:122`), in at most two accounted commits whose progress is recorded in `turn_journal_allocation.index_purge` (`purgeIndexVersions(): IndexPurgeResult`, -`packages/ui-server/src/brain/journal-store.ts:184-223`): +`packages/ui-server/src/brain/journal-store.ts:186-225`): 1. Every recorded index-family version, in history and in revert records, is rewritten to the metadata-only form a new one has: kind, mode, size and the @@ -1743,7 +1743,7 @@ migrations before accounting can admit them. **Admission before storage.** The upgrade runs on the journal write worker, through the same `BEGIN IMMEDIATE`, `synchronous=FULL` accounting as its data writes (`function ensureObjectRefIndex`, -`packages/ui-server/src/brain/journal-accounting.ts:164-193`). Under that lock, +`packages/ui-server/src/brain/journal-accounting.ts:169-198`). Under that lock, it reserves a conservative allowance for index records, b-tree fill/interior pages and schema/pointer-map overhead, plus the WAL capacity over the enlarged file and all existing WAL debt, objects and reservations. It assumes no reuse @@ -1773,7 +1773,7 @@ attempts it without making recovery depend on success. Ordinary collection tries before deleting, runs the existing integrity-checked path if it was refused, and retries after the freed object bytes make room (`collectObjects(): void`, -`packages/ui-server/src/brain/journal-store.ts:157-163`). Freeing rows alone +`packages/ui-server/src/brain/journal-store.ts:159-165`). Freeing rows alone does not credit persistent pages: they remain charged until reclamation is observed. Every pin and reservation keeps its object throughout success, refusal, failure and restart, and foreign keys remain enabled on every ordinary @@ -1816,7 +1816,7 @@ fresh globals per request, with the path as its only argument, and answers with the program's output, its exit status and the traceback a fresh launch printed, without the loop's own frame. The manager turns a failure into the same refusal a failed launch produced (`async function inspection`, -`packages/ui-sdk/src/server/native-brain-manager.ts:186-190`). Every +`packages/ui-sdk/src/server/native-brain-manager.ts:189-193`). Every `qualify` and `verifyOwned` still inspects the live path on every operation; nothing is cached between requests. An interrupted, timed-out, oversized or malformed exchange, or one with an interpreter that died, kills the @@ -2535,7 +2535,7 @@ A peer whose plan only lacks a root is waited for, up to are planned only once a turn has translated it under the current policy hash, so writers admitted before that translation predate them, and every later writer inherits them from the held plan -(`waitForPeerFolderPlans`, `packages/ui-server/src/brain/writer-gate.ts:342-353`). +(`waitForPeerFolderPlans`, `packages/ui-server/src/brain/writer-gate.ts:381-392`). The translation is recorded in the UI database, so after the first one under a policy hash, writers in every process, the cron runner's and a restarted server's included, plan its folders without waiting (#2836). @@ -3170,7 +3170,7 @@ index refresh or a cron job, retains them and the next turn's peer check passes. Admission records that translation in the UI database, one row per canonical brain holding the exact policy hash and its folders, so it reaches the cron runner's process and survives a restart (#2836; -`function recordedTypeFolders`, `packages/ui-server/src/brain/writer-gate.ts:173-182`). +`function recordedTypeFolders`, `packages/ui-server/src/brain/writer-gate.ts:175-184`). The host never translates it itself: only admission does, under its worker boundary. A missing, unreadable or other-hash record plans no type folder, and a stale one only retains an extra folder. Admission still refuses a peer @@ -4319,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:380-445`). +(`async function observe`, `packages/ui-server/src/brain/turn-journal.ts:384-449`). Claude auto-memory persists outside the authoritative brain. Its validated native copy-out wraps each changed direct `.md` note in host journal retention: @@ -4342,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:657-687`; destination-bound recovery +`packages/ui-server/src/brain/turn-journal.ts:662-692`; destination-bound recovery is `const target`, `packages/ui-server/src/brain/turn-revert.ts:113-123`. ### Concurrent edits diff --git a/docs/decisions/http-api-boundary.md b/docs/decisions/http-api-boundary.md index 22f9b00e99..90cade1288 100644 --- a/docs/decisions/http-api-boundary.md +++ b/docs/decisions/http-api-boundary.md @@ -48,9 +48,9 @@ The source audit on 2026-09-30 used `e0875269b21b707482545be9e94901acb897893b`. The public health mount precedes auth (`createHealthRoutes`, `packages/ui-server/src/app.ts:1019`), the API guard follows public ceremonies (`authGuard`, `packages/ui-server/src/app.ts:1040`), and the -WebSocket admission is separate (`"/ws"`, `packages/ui-server/src/app.ts:1260`). +WebSocket admission is separate (`"/ws"`, `packages/ui-server/src/app.ts:1261`). Static serving is conditional (`if (options.staticRoot)`, -`packages/ui-server/src/app.ts:1280-1301`). That order establishes access; +`packages/ui-server/src/app.ts:1281-1302`). That order establishes access; it does not select compatibility status. A hermetic real-app launch, with temporary brain root, in-memory database, diff --git a/docs/decisions/journal-database.md b/docs/decisions/journal-database.md index a56c0fe498..ccd87f6b74 100644 --- a/docs/decisions/journal-database.md +++ b/docs/decisions/journal-database.md @@ -28,7 +28,7 @@ that no pre-charge covers. The evidence is on the issue. `DB_PATH` names one journal. Every page in it is the journal's, so the measurement is the file's page count and the journal's own WAL, read without walking - (`function measure(`, `packages/ui-server/src/brain/journal-accounting.ts:67-81`). + (`function measure(`, `packages/ui-server/src/brain/journal-accounting.ts:72-86`). Other components' pages and WAL frames are no longer the journal's charge. - **The tables move on start.** Migrations up to `063` create journal tables in the UI database. Before any later migration, and again after the last, @@ -93,11 +93,11 @@ that no pre-charge covers. The evidence is on the issue. capture took an inventory at all, which it does only for an observation that saw a change. Per-turn arrays from earlier releases move into sets at open, a bounded batch per accounted commit, because SQLite cannot hash - (`migrateConfigurationSets(limit`, `packages/ui-server/src/brain/journal-store.ts:230-238`); + (`migrateConfigurationSets(limit`, `packages/ui-server/src/brain/journal-store.ts:232-240`); 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:738-744`). + (`configurationCoverage(): ConfigurationCoverageRead`, `packages/ui-server/src/brain/turn-journal.ts:743-749`). The sets table is an ordinary rowid table, as every journal table is: the operational backup copies and compares journal rows in rowid order. @@ -111,3 +111,24 @@ and the ledger's attach is then a no-op. A `roadblock` event a journal-reader failure records is not replayed: its payload carries timings that the journal does not keep. The journal's `missing` record of that path stays authoritative. + +## Corrupt interrupted publication (#3816) + +Recovery quarantines a published object that fails verification in +`turn_journal_object_quarantine`. The cause includes error class, message, time +and call site. The bytes stay at their original hash and remain charged, while +read leases and new reservations for that hash refuse. The interrupted writer's +reservation is cleared in the same accounted transaction that records quarantine +and marks every referencing history path incomplete. Other history stays usable. +The history details expose `retained_object_corrupt`; normal expiry eventually +collects the quarantined bytes and their diagnostic row. A later disk repair +does not silently turn the old incomplete history into complete history. + +Later captures of a quarantined hash record only the affected path as missing +(`retained_object_corrupt`); the shared observation and other active turns +continue. No replacement is trusted and old gap facts stay intact. An I/O error +while testing existence or verification proves neither corruption nor absence: +the reservation, object state and charge remain unchanged for the next recovery +pass. Only a verified mismatch or confirmed absence of retained content can +quarantine it. Recovery marks live owners' paths without changing their running +state; their normal completion preserves the gap. diff --git a/docs/decisions/managed-worktrees.md b/docs/decisions/managed-worktrees.md index 03b5b1319e..7e55b56afe 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:563-575`; -`// Each managed worktree is observed through its own checkpoints`, `packages/ui-server/src/brain/turn-journal.ts:397-411`). +(`attachWorktree(turnId: string`, `packages/ui-server/src/brain/turn-journal.ts:567-579`; +`// Each managed worktree is observed through its own checkpoints`, `packages/ui-server/src/brain/turn-journal.ts:401-415`). 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/native-brain-storage.md b/docs/decisions/native-brain-storage.md index d750b23c05..59a6236d9e 100644 --- a/docs/decisions/native-brain-storage.md +++ b/docs/decisions/native-brain-storage.md @@ -108,9 +108,10 @@ individual page with mutations. Pages do not promise a multi-request snapshot: an identity inserted below an already-consumed cursor is not returned later. Intent rename and parent-directory fsync precede index insertion. If insertion -fails, the mutation has an unknown outcome and the index refuses subsequent -pages until restart rebuilds it. Losing the in-memory index or a transport reply -does not lose the durable identity. Deleted intents remain present and continue +fails, the manager builds a complete replacement from those durable intents +before continuing. A failed rebuild refuses dependent admission and pages; +each later request retries the rebuild in the same process. Losing the +in-memory index or a transport reply does not lose the durable identity. Deleted intents remain present and continue to fence delayed create requests; no identity retirement or tombstone lifetime policy is introduced. @@ -208,3 +209,45 @@ Reduced undo remains a distinct product choice: committed-version restoration or mediated-tool-only undo can avoid universal preimages. Removing only the whole-turn revert action cannot. This ruling keeps existing observed-version undo and changes its storage mechanism instead. + +## Containing recovery failures (#3816) + +An unreadable native intent stays in place as an identity fence. Startup records +its error class, message, site and timestamp under the manager's private +`recovery-diagnostics/` directory, and continues. `ready` reports the count, +diagnostic directory and conservatively charged staging bytes; authenticated +`/api/status` exposes that boot report as `nativeRecovery`. An invalid UUID +cannot own a stage and has no staging charge. A confirmed absent stage directory +also charges zero: the directory precedes namespace setup and is removed only +after confirmed close. The malformed receipt remains quarantined in both cases. + +Before starting a stage, the manager durably records its exact tmpfs allowance +in a separate root-owned `stages/.allowance` file. A surviving or unreadable +directory retains that cap even if today's configured allowance is smaller. +The allowance record is removed only after close and durable directory removal; +neither a failed close nor an I/O error releases it. Healthy stages can use the +remaining aggregate budget. An old stage without this independent record, or a +damaged/unreadable record, has no provable historical bound. Its charge stays +unknown (`null`), new staging returns an explicit recovery refusal instead of a +retryable capacity error, and authenticated status reports `healthy: false`. +The cause stays in the private diagnostics directory. Repair requires proof of +the historical cap or confirmed cleanup, never a guess based on current config. +No historical checkpoint dependency is released while a quarantined receipt +could own it. +Healthy checkpoint creation and reads remain available; +new roots created after recovery can also be released, since a historical stage +cannot refer to those native identities. A recovery +page touching that identity refuses explicitly. Repairing an authoritative +receipt requires owner judgment; restart after that repair reconstructs the +known reservation. Unknown identities are never adopted or deleted. + +Index rebuilds use the same diagnostics directory; they need no owner action. +The reference pool refreshes its accounting map from the same durable intents +before it reopens dependent admission. + +Diagnostic writes are best-effort and cannot gate mechanical recovery. If the +private diagnostic directory refuses a write, the structured stderr record +retains both the original cause and that write failure; the authoritative bad +intent remains on disk. A disposable index rebuild publishes only its complete +replacement, and retries pending diagnostic writes on later requests separately +from admission. diff --git a/docs/decisions/proportionate-containment.md b/docs/decisions/proportionate-containment.md index 3addfc27a8..b47b60e27d 100644 --- a/docs/decisions/proportionate-containment.md +++ b/docs/decisions/proportionate-containment.md @@ -65,7 +65,7 @@ design, not an afterthought. non-restorable. - Disproportionate: one corrupt undo object stops the server from starting (`recover(objects)`, - `packages/ui-server/src/brain/journal-accounting.ts:225-239`). + `packages/ui-server/src/brain/journal-accounting.ts:231-245`). 5. **Diagnosable.** Every latch, give-up, quarantine or restricted boot records its cause durably (error class, message, call site, scope, time), writes one structured log line, and is visible to the owner. A cause that is only in a diff --git a/docs/decisions/reference-pool-accounting.md b/docs/decisions/reference-pool-accounting.md index 25b09c9aed..0f7886959e 100644 --- a/docs/decisions/reference-pool-accounting.md +++ b/docs/decisions/reference-pool-accounting.md @@ -8,7 +8,7 @@ actual allocated disk. That decision left the mechanism to implementation. This record names the mechanism, the primary sources it relies on and the native observations that qualified it. The pool is managed by the existing host-only native manager -(`createNativeReferencePool`, `packages/ui-sdk/src/server/native-reference-pool.ts:272-964`). +(`createNativeReferencePool`, `packages/ui-sdk/src/server/native-reference-pool.ts:273-988`). No consumer uses it yet. ## A separate volume, not another subvolume of the brain store @@ -224,7 +224,7 @@ directory its intent records. Sealing also makes the root's top directory `roots/` and `views/` join the mandatory worker masks. A worker sees reference source only through a view bound for it, and other domains' views stay invisible. `poolView` (#2432) opens a view's directory before its first -publication (`function viewOpen`, `packages/ui-sdk/src/server/native-reference-pool.ts:940-943`), +publication (`function viewOpen`, `packages/ui-sdk/src/server/native-reference-pool.ts:954-957`), so a worker that binds it at its start sees the domain's first publication on a later lookup ([agent tools](managed-worktrees.md#agent-tools)). diff --git a/docs/decisions/session-principals.md b/docs/decisions/session-principals.md index c10fa0eb93..aa2817c267 100644 --- a/docs/decisions/session-principals.md +++ b/docs/decisions/session-principals.md @@ -98,7 +98,7 @@ Both reviewers verified every row below against the source. | Global revoke | `auth.ts:321-330` | `setSetting` (overflow-guarded) + `clients.closeAll(1008, …)` | | Auth routes | `authRoutes`, `app.ts:1025` | mounted **before** the guard at `authGuard(authMode`, `app.ts:1040`; logout guards itself (`resolveCookiePrincipal(c, auth, deps.db)`, `auth.ts:798`) | | Passkey management | `passkeyManagementRoutes`, `app.ts:1049` | mounted **after** the guard ("Mount AFTER the auth guard") | -| WS guard | `"/ws"`, `app.ts:1260-1277` | origin → `isWsAuthorized` (returns a boolean, `auth.ts:221-237`) → capacity → upgrade | +| WS guard | `"/ws"`, `app.ts:1261-1278` | origin → `isWsAuthorized` (returns a boolean, `auth.ts:221-237`) → capacity → upgrade | | WS upgrade | `ws/connection.ts:262-264` | `createWsUpgrade` ignores the request context | | WS admission | `ws/connection.ts:84` | `clients.add(ws)` — the socket's identity is unknown | | Turn record | `ws/run-session.ts:136-144` | recorder built from `{turnId, sessionId, billing}`; `RunningTurn` (`ws/turns.ts:55-77`) has no actor | diff --git a/docs/hosting/agent-workers.md b/docs/hosting/agent-workers.md index 9f36a8aaa3..b30d6adda5 100644 --- a/docs/hosting/agent-workers.md +++ b/docs/hosting/agent-workers.md @@ -1038,7 +1038,7 @@ root-owned files and connect to root-owned and abstract Unix sockets. Native storage accepts the server's fixed UID/GID, including UID 0 under this same warning (`validateNativeBrainManagerConfig`, -`packages/ui-sdk/src/server/native-brain-manager.ts:50-72`). This does not give +`packages/ui-sdk/src/server/native-brain-manager.ts:53-75`). This does not give the worker capabilities or remove its masks, filesystem filter or read-only root `/proc`. The host still has to qualify for user namespaces. Since Linux 5.12, mapping a child namespace to parent UID 0 requires `CAP_SETFCAP` at the diff --git a/docs/http-api.md b/docs/http-api.md index ea0206bef4..5eb16eb1f2 100644 --- a/docs/http-api.md +++ b/docs/http-api.md @@ -357,7 +357,7 @@ healthy does not certify upstream model or brain CLI availability. **GET /api/status** is protected, accepts no inputs, and returns `{ healthy: boolean, uptime, version, software, cronJobs, activeSession, metrics, -runtime?, subscription?, backendAvailability? }`. `version` is the configured source commit (default +runtime?, subscription?, backendAvailability?, nativeRecovery? }`. `version` is the configured source commit (default `"dev"`), not a release; `software` is `{ release, sourceCommit }`. `cronJobs` contains `{ name, lastRunAt, lastStatus, lastDurationMs, lastError }`, nullable when a job has not run; it includes recorded jobs and configured in-process @@ -376,6 +376,14 @@ are never constructed or routed to. Correct the package/runtime or host configuration and start again to revalidate. Prior records alone do not imply current degradation. +`nativeRecovery`, when present, reports native intent quarantine at server boot: +`{ quarantinedIntents, stagingChargedBytes, diagnosticsPath }`. A null charge +means its bound could not be established; it never means zero, and `healthy` is +false while that recovery restriction remains. A numeric zero means no stage +storage can belong to the quarantined identities. The diagnostics +path is host-private and appears only behind authentication, never on `/health`. +Healthy identities remain usable within provably available staging capacity. + `runtime.workerHost` is whether this host can run agent workers (#1632): `{ ordinary?, restricted? }`, each `{ available, checkedAt, trigger }` plus `requirement` when unavailable. `checkedAt` is ISO UTC; `trigger` is `"boot"`, diff --git a/docs/integration-contract/http.md b/docs/integration-contract/http.md index 00d84be77b..572bdf7a82 100644 --- a/docs/integration-contract/http.md +++ b/docs/integration-contract/http.md @@ -160,6 +160,22 @@ conflicts, unavailable detail, unknown outcomes and partial work remain explicit voice, agent and autonomous execution do not gain a history action. This is additive in 0.42.0; no existing read or CLI/MCP shape changes. + + +### Native intent recovery (additive, #3816) + +Authenticated `GET /api/status` adds optional `nativeRecovery`: +`{ quarantinedIntents: number, stagingChargedBytes: number | null, +diagnosticsPath: string }`, also declared by `SystemStatus`. It reports the +manager's boot quarantine and conservative staging charge. Invalid UUIDs and +confirmed absent stage directories charge zero; surviving stages retain their +independently recorded historical tmpfs allowance. The charge includes known +stage reservations at boot. `null` means no safe bound is proven, never zero: +`healthy` is false and staging refuses with a recovery diagnostic rather than +claiming a temporary busy slot. Other operations remain available. The private +diagnostics path and causes are never exposed by unauthenticated `/api/health`. +This optional reporting is additive in 0.45.0; no CLI/MCP shape changes. + ### Degraded backend availability and unknown expiry (additive, #3817) diff --git a/docs/integration-contract/package-api.md b/docs/integration-contract/package-api.md index 97d7941358..ceae012373 100644 --- a/docs/integration-contract/package-api.md +++ b/docs/integration-contract/package-api.md @@ -5187,6 +5187,22 @@ 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. +### Native recovery quarantine status (#3816) + +`NativeManagerReady` gains optional `recovery` with `quarantinedIntents`, +`stagingChargedBytes` (null when no safe stage bound is known) and +`diagnosticsPath`. It is present when historical native +intents cannot be read. Those identities remain fenced; staging capacity and +unknown checkpoint dependencies remain charged. The manager serves readiness +and unrelated checkpoint operations. A recovery page containing a quarantined +identity refuses explicitly rather than reporting an incomplete inventory as +complete. Causes remain in the host-private diagnostics directory. Authenticated +`GET /api/status` exposes the boot report as optional `nativeRecovery`, also +added to `SystemStatus`. A null staging charge makes `healthy` false and new +staging returns a recovery refusal, not a retryable capacity error. A confirmed +absent stage directory or invalid UUID charges zero; a surviving stage retains +its independently persisted historical tmpfs cap. Public `/api/health` remains +unchanged. The journal host's additive `cleanupStatus()` method (#3815) returns `{ retained: { pending, failed, retainedBytes }, lastFailure }`, the same diff --git a/docs/integration-contract/wire.md b/docs/integration-contract/wire.md index d330c2aab6..67dd7e75b3 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:52-55`). +(`const KEPT_CHANGE`, `packages/ui-server/src/brain/turn-journal.ts:53-56`). **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/chat-history-deletion.md b/docs/plans/chat-history-deletion.md index 9a11d2924d..38f4a08466 100644 --- a/docs/plans/chat-history-deletion.md +++ b/docs/plans/chat-history-deletion.md @@ -334,7 +334,7 @@ Preserve the existing bounded-wait ownership distinction during that drain. writers; rejection retains the original cleanup continuation, writer and reader until genuine settlement, rather than authorizing their replacement (`guardSqliteCleanup`, `packages/ui-server/src/db/write-worker.ts:206-234`; -`close: () => closing ??= guardSqliteCleanup`, `packages/ui-server/src/app.ts:1370-1420`). +`close: () => closing ??= guardSqliteCleanup`, `packages/ui-server/src/app.ts:1371-1421`). The native lease manager retains its own pending operations and durable unknown root outcomes through close (`return { client, writer, recoverDeadOwners`, `packages/ui-server/src/brain/native-brain-leases.ts:274-287`). A caller deadline diff --git a/packages/ui-sdk/src/protocol.ts b/packages/ui-sdk/src/protocol.ts index a8cd5933a4..910cf561a3 100644 --- a/packages/ui-sdk/src/protocol.ts +++ b/packages/ui-sdk/src/protocol.ts @@ -1893,6 +1893,8 @@ export type GovernedStatus = { & ({ available: true } | { available: false; reason: GovernedUnavailableReason; detail: string }); export interface SystemStatus { + /** Native quarantine reported at server boot; only on authenticated status. */ + nativeRecovery?: { quarantinedIntents: number; stagingChargedBytes: number | null; diagnosticsPath: string }; healthy: boolean; uptime: number; /** The configured source commit (`"dev"` by default), never a release. */ diff --git a/packages/ui-sdk/src/server/native-brain-manager-protocol.ts b/packages/ui-sdk/src/server/native-brain-manager-protocol.ts index 738f808aa5..a2a5b38e11 100644 --- a/packages/ui-sdk/src/server/native-brain-manager-protocol.ts +++ b/packages/ui-sdk/src/server/native-brain-manager-protocol.ts @@ -86,6 +86,8 @@ export interface NativeManagerReady { availableBytes: number; recoveryReserveBytes: number; reserveAllocatedBytes: number; + /** Historical unreadable receipts stay fenced and conservatively charged. */ + recovery?: { quarantinedIntents: number; stagingChargedBytes: number | null; diagnosticsPath: string }; } export interface NativeRecoveryRecord { id: string; diff --git a/packages/ui-sdk/src/server/native-brain-manager.ts b/packages/ui-sdk/src/server/native-brain-manager.ts index 89bbf8fa5a..f3eb2fd7e9 100644 --- a/packages/ui-sdk/src/server/native-brain-manager.ts +++ b/packages/ui-sdk/src/server/native-brain-manager.ts @@ -13,6 +13,8 @@ import { nativeCheckpointId, nativeManagerRequest, nativeManagerFrame, NativeBra import { startNativeStage } from "./native-brain-stage.js"; import { randomUUID } from "node:crypto"; import { nativeCheckpointReaderPath, startNativeCheckpointRead } from "./native-checkpoint-reader.js"; +import { recoverNativeIntents } from "./native-intent-recovery.js"; +import { recordNativeRecoveryFailure } from "./native-recovery-diagnostics.js"; import { NativeRecoveryIndex } from "./native-recovery-index.js"; import { createNativeReferencePool, validateNativeReferencePoolConfig, type NativeReferencePool, type NativeReferencePoolConfig } from "./native-reference-pool.js"; import { createNativeIdentityInspector, type NativeInspection } from "./native-identity-inspector.js"; @@ -256,7 +258,12 @@ export async function createNativeBrainManager(config: NativeBrainManagerConfig) } // A full existing store must still serve release/recovery. Ready/checkpoint refuse until rearmed. try { await ensureReserve(); } catch (error) { if (plainError(error).code !== "capacity") { closeSync(stateFd); abandon(error); } reserveConsumed = true; } + let quarantinedIntents = new Set(); + // Historical unreadable stages cannot refer to a native root created after + // recovery. Keep that proof local to this lifetime, never infer it at restart. + const createdAfterRecovery = new Set(); function readIntent(id: string): Intent | null { + if (quarantinedIntents.has(id)) throw new NativeBrainManagerError("unknown", "Native intent is quarantined; inspect the host-private recovery diagnostics and repair its authoritative receipt before retrying."); const path = join(state, `${id}.json`); if (!existsSync(path)) return null; const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW); @@ -286,10 +293,10 @@ export async function createNativeBrainManager(config: NativeBrainManagerConfig) try { write(); } catch (again) { throw plainError(again); } } // The durable intent remains authoritative if indexing is interrupted. - // An index failure refuses later pages until a restart rebuilds it. - try { recoveryIndex.remember(intent.id); } - catch { throw new NativeBrainManagerError("unknown", "Native intent is durable but recovery indexing failed; restart the manager to rebuild it."); } + // Rebuild a failed disposable index before admitting the next operation. rememberStage(intent); + try { recoveryIndex.remember(intent.id); } + catch { throw new NativeBrainManagerError("unknown", "Native intent is durable but recovery indexing failed; rebuilding from durable intents is unavailable; retry the operation."); } } function rememberStage(intent: Intent): void { if (intent.kind !== "stage") return; @@ -305,19 +312,61 @@ export async function createNativeBrainManager(config: NativeBrainManagerConfig) } // Recover bounded stage accounting once at service startup; warm admission // never rescans all checkpoint tombstones or any live-brain bytes. - const recoveredIds: string[] = []; + let recoveredIds: string[] = []; try { - for (const name of readdirSync(state).filter(name => name.endsWith(".json"))) { - const id = name.slice(0, -5); - if (!nativeCheckpointId.safeParse(id).success) throw new NativeBrainManagerError("unknown", "Native state contains an unrecognized identity."); - rememberStage(readIntent(id)!); - recoveredIds.push(id); - } + const recovered = recoverNativeIntents(state, join(privateRoot, "recovery-diagnostics"), id => rememberStage(readIntent(id)!)); + recoveredIds = recovered.ids; quarantinedIntents = recovered.quarantined; } catch (error) { closeSync(stateFd); abandon(error); } + // Persist the exact tmpfs cap independently of the mutable intent, before + // creating its directory/namespace. Never substitute today's configuration + // for a historical stage's (possibly larger) bound. + const allowancePath = (id: string) => join(stages, `${id}.allowance`); + function syncStages(): void { + const fd = openSync(stages, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW); + try { fsyncSync(fd); } finally { closeSync(fd); } + } + function recordStageAllowance(id: string, bytes: number): void { + const fd = openSync(allowancePath(id), constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600); + try { writeFileSync(fd, String(bytes)); fsyncSync(fd); } finally { closeSync(fd); } + syncStages(); + } + function readStageAllowance(id: string): number { + const fd = openSync(allowancePath(id), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK); + try { + const info = fstatSync(fd); + if (!info.isFile() || info.uid !== 0 || info.nlink !== 1 || (info.mode & 0o077) || info.size > 16) + throw Error("Untrusted native stage allowance record"); + const value = readFileSync(fd, "utf8"), bytes = Number(value); + if (!/^[1-9][0-9]*$/.test(value) || !Number.isSafeInteger(bytes) || bytes % 4096) + throw Error("Invalid native stage allowance record"); + return bytes; + } finally { closeSync(fd); } + } + // No directory proves no stage storage: mkdir precedes namespace setup and + // rmdir follows confirmed close. Invalid protocol IDs cannot own stages. + // Otherwise retain that identity's independent cap, even on an lstat error. + // Legacy/damaged caps remain unknown; never guess or release their charge. + let quarantinedStageBytes = 0; + for (const id of quarantinedIntents) { + if (!nativeCheckpointId.safeParse(id).success) continue; + try { lstatSync(join(stages, id)); } + catch (error) { if (errorCode(error) === "ENOENT") continue; } + try { + quarantinedStageBytes += readStageAllowance(id); + if (!Number.isSafeInteger(quarantinedStageBytes)) throw Error("Native quarantine capacity exceeds safe accounting range"); + } catch (error) { + quarantinedStageBytes = Infinity; + recordNativeRecoveryFailure(join(privateRoot, "recovery-diagnostics"), id, "native-brain-manager.recoverStageAllowance", error); + } + } // This one-time rebuild remains O(history). The private in-memory B-tree // is disposable; neither its loss nor a lost reply retires an identity. const recoveryIndex = (() => { - try { return new NativeRecoveryIndex(recoveredIds); } + try { return new NativeRecoveryIndex(recoveredIds, () => { + const ids = readdirSync(state).filter(name => name.endsWith(".json")).map(name => name.slice(0, -5)); + for (const id of ids) if (!nativeCheckpointId.safeParse(id).success && !quarantinedIntents.has(id)) throw new NativeBrainManagerError("unknown", "Native state contains an unrecognized identity."); + return ids.filter(id => nativeCheckpointId.safeParse(id).success); + }, (error, log) => recordNativeRecoveryFailure(join(privateRoot, "recovery-diagnostics"), "recovery-index", "native-brain-manager.writeIntent", error, log)); } catch (error) { closeSync(stateFd); return abandon(error); } })(); // The pool qualifies independently: its refusal never blocks brain status or recovery. @@ -359,12 +408,15 @@ export async function createNativeBrainManager(config: NativeBrainManagerConfig) return { brainPath: brain, brainUuid: identity.uuid, brainRootId: identity.rootId, privatePaths: [...new Set([privateRoot, dirname(fixed.socketPath), fixed.devicePath, ...(backingPath ? [backingPath] : []), ...(referencePool?.privatePaths ?? [])])], fsid: fixed.fsid, capacityBytes: fixed.capacityBytes, availableBytes: space.bavail * space.bsize, recoveryReserveBytes: fixed.recoveryReserveBytes, - reserveAllocatedBytes: lstatSync(reserve).blocks * 512 }; + reserveAllocatedBytes: lstatSync(reserve).blocks * 512, + ...(quarantinedIntents.size ? { recovery: { quarantinedIntents: quarantinedIntents.size, + stagingChargedBytes: Number.isSafeInteger(stagedBytes + quarantinedStageBytes) ? stagedBytes + quarantinedStageBytes : null, diagnosticsPath: join(privateRoot, "recovery-diagnostics") } } : {}) }; } async function run(request: NativeManagerRequest, signal?: AbortSignal): Promise { nativeManagerRequest.parse(request); const release = await acquire(signal); let handedToStream = false; try { if (request.operation === "ready") return Response.json(await ready(signal)); + if (!request.operation.startsWith("pool") && request.operation !== "listPoolRecovery") recoveryIndex.ensureAvailable(); if (request.operation === "poolStatus") return Response.json(await pool().status(signal)); if (request.operation === "poolCreate") return Response.json(await pool().create(request, signal)); if (request.operation === "poolSeal") return Response.json(await pool().seal(request.id, signal)); @@ -501,13 +553,16 @@ export async function createNativeBrainManager(config: NativeBrainManagerConfig) const source = readIntent(request.checkpointId); if (!source || source.kind === "stage" || source.state !== "sealed") throw new NativeBrainManagerError("unknown", "Native staging requires one retained sealed checkpoint."); const checkpoint = await verifyOwned(source, signal); - if (stagedBytes + request.allowanceBytes > fixed.stageBudgetBytes) throw new NativeBrainManagerError("capacity", "Native output staging aggregate budget is busy; nothing ran."); + if (!Number.isFinite(quarantinedStageBytes)) throw new NativeBrainManagerError("unknown", "Native staging recovery cannot establish a quarantined stage's storage bound. Inspect the host-private recovery diagnostics and repair its allowance or authoritative receipt; waiting for another conversation will not resolve it."); + if (stagedBytes + quarantinedStageBytes + request.allowanceBytes > fixed.stageBudgetBytes) throw new NativeBrainManagerError("capacity", "Native output staging aggregate budget is busy; nothing ran."); const path = join(stages, request.id); if (!intent) { if (existsSync(path)) throw new NativeBrainManagerError("unknown", "Unrecorded staging storage occupies this identity."); intent = { version: 1, id: request.id, sourceUuid: fixed.brainUuid, kind: "stage", state: "creating", stageRequest: { checkpointId: request.checkpointId, checkpointUuid: checkpoint.uuid, allowanceBytes: request.allowanceBytes } }; await writeIntent(intent); + recordStageAllowance(request.id, request.allowanceBytes); mkdirSync(path, { mode: 0o700 }); + syncStages(); } else if (existsSync(path)) throw new NativeBrainManagerError("unavailable", "Interrupted stage preparation must be released before retry with a new identity."); let handle: Awaited> | undefined; try { @@ -529,11 +584,18 @@ export async function createNativeBrainManager(config: NativeBrainManagerConfig) if (intent.state === "deleted") return Response.json({ id: request.id, state: "deleted" }); await writeIntent({ ...intent, state: "deleting" }); await activeStages.get(request.id)?.close(); activeStages.delete(request.id); - if (existsSync(path)) { - const info = lstatSync(path); if (!info.isDirectory() || info.uid !== 0 || readdirSync(path).length) + let info; + try { info = lstatSync(path); } catch (error) { if (errorCode(error) !== "ENOENT") throw error; } + if (info) { + if (!info.isDirectory() || info.uid !== 0 || readdirSync(path).length) throw new NativeBrainManagerError("unknown", "Stage placeholder identity is unsafe; no removal is authorized."); const { rmdirSync } = await import("node:fs"); rmdirSync(path); } + // Confirm directory removal durably before discarding the independent + // bound; a failed close/removal must retain both accounting receipts. + syncStages(); + try { unlinkSync(allowancePath(request.id)); } catch (error) { if (errorCode(error) !== "ENOENT") throw error; } + syncStages(); await writeIntent({ ...intent, state: "deleted" }); return Response.json({ id: request.id, state: "deleted" }); } if (request.operation === "inspectStage") { @@ -557,6 +619,7 @@ export async function createNativeBrainManager(config: NativeBrainManagerConfig) } if (request.operation === "checkpoint") { await qualify(signal); + let createdNow = false; let intent = readIntent(request.id); if (intent) intent = await reconcile(intent, signal); if (intent?.state === "deleted" || intent?.state === "deleting") throw new NativeBrainManagerError("released", "This checkpoint identity was released; it cannot be recreated."); @@ -565,14 +628,19 @@ export async function createNativeBrainManager(config: NativeBrainManagerConfig) if (!intent) { if (existsSync(rootPath(request.id))) throw new NativeBrainManagerError("unknown", "An unrecorded checkpoint occupies the requested identity."); intent = { version: 1, id: request.id, sourceUuid: fixed.brainUuid, state: "creating" }; await writeIntent(intent); + createdNow = true; } if (reserveConsumed) throw new NativeBrainManagerError("capacity", "Native recovery consumed emergency allocation; rearm capacity before checkpoint admission."); signal?.throwIfAborted(); await command([BTRFS, "subvolume", "snapshot", "-r", brain, rootPath(request.id)], signal); const checkpoint = await verifyOwned(intent, signal); await writeIntent({ ...intent, state: "sealed", checkpoint }); + if (createdNow) createdAfterRecovery.add(request.id); return Response.json(checkpoint); } if (request.operation === "release") { + // An unreadable receipt may own a stage referring to any checkpoint. + // No inferred absence can authorize deleting that lower root. + if (quarantinedIntents.size && !createdAfterRecovery.has(request.id)) throw new NativeBrainManagerError("unknown", "Quarantined native intents may retain historical checkpoint dependencies; repair their receipts before releasing those roots."); if ([...checkpointReaders.values()].some(reader => reader.checkpointId === request.id)) throw new NativeBrainManagerError("unavailable", "Close the checkpoint's active fixed-reader handle before releasing its native view."); let intent = readIntent(request.id); diff --git a/packages/ui-sdk/src/server/native-intent-recovery.ts b/packages/ui-sdk/src/server/native-intent-recovery.ts new file mode 100644 index 0000000000..517c25d5c0 --- /dev/null +++ b/packages/ui-sdk/src/server/native-intent-recovery.ts @@ -0,0 +1,23 @@ +import { readdirSync } from "node:fs"; +import { nativeCheckpointId } from "./native-brain-manager-protocol.js"; +import { recordNativeRecoveryFailure } from "./native-recovery-diagnostics.js"; + +/** Recover independent records; keep unreadable originals as permanent identity fences. */ +export function recoverNativeIntents(state: string, diagnostics: string, recover: (id: string) => void): { ids: string[]; quarantined: Set } { + const ids: string[] = [], quarantined = new Set(); + // A failure to enumerate the store is still store-wide uncertainty. + for (const name of readdirSync(state).filter(name => name.endsWith(".json"))) { + const id = name.slice(0, -5); + try { + if (!nativeCheckpointId.safeParse(id).success) throw Error("Native state contains an unrecognized identity."); + recover(id); + } catch (error) { + quarantined.add(id); + recordNativeRecoveryFailure(diagnostics, name, "native-brain-manager.recoverIntent", error); + } + // Even a quarantined valid UUID stays in the index. A page containing it + // refuses explicitly instead of silently presenting an incomplete census. + if (nativeCheckpointId.safeParse(id).success) ids.push(id); + } + return { ids, quarantined }; +} diff --git a/packages/ui-sdk/src/server/native-recovery-diagnostics.ts b/packages/ui-sdk/src/server/native-recovery-diagnostics.ts new file mode 100644 index 0000000000..c45d479439 --- /dev/null +++ b/packages/ui-sdk/src/server/native-recovery-diagnostics.ts @@ -0,0 +1,23 @@ +/** Host-private recovery causes, retained beside the authoritative native intents. */ +import { closeSync, constants, fsyncSync, mkdirSync, openSync, renameSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { createHash } from "node:crypto"; + +export function recordNativeRecoveryFailure(root: string, scope: string, site: string, error: unknown, log = true): boolean { + const cause = { scope, site, at: Date.now(), errorClass: error instanceof Error ? error.name : "Error", + message: (error instanceof Error ? error.message : String(error)).slice(0, 2000) }; + const name = createHash("sha256").update(`${site}:${scope}`).digest("hex"); + let diagnosticError: string | undefined; + try { + mkdirSync(root, { recursive: true, mode: 0o700 }); + const directory = openSync(root, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW); + try { + const path = (suffix: string) => `/proc/self/fd/${directory}/${name}${suffix}`; + const fd = openSync(path(".tmp"), constants.O_CREAT | constants.O_TRUNC | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600); + try { writeFileSync(fd, JSON.stringify(cause)); fsyncSync(fd); } finally { closeSync(fd); } + renameSync(path(".tmp"), path(".json")); fsyncSync(directory); + } finally { closeSync(directory); } + } catch (error) { diagnosticError = String(error); } + if (log) console.error(JSON.stringify({ kind: "native_recovery_failure", ...cause, ...(diagnosticError ? { diagnosticError } : {}), diagnostics: join(root, `${name}.json`) })); + return diagnosticError === undefined; +} diff --git a/packages/ui-sdk/src/server/native-recovery-index.ts b/packages/ui-sdk/src/server/native-recovery-index.ts index 0251367937..53caefa5f6 100644 --- a/packages/ui-sdk/src/server/native-recovery-index.ts +++ b/packages/ui-sdk/src/server/native-recovery-index.ts @@ -3,42 +3,100 @@ import { Database } from "bun:sqlite"; import { nativeCheckpointId } from "./native-brain-manager-protocol"; export class NativeRecoveryIndex { - private readonly db = new Database(":memory:"); - private readonly insert; - private readonly select; + private db: Database; private failed = false; + private closed = false; + private diagnostic: { error: unknown; logged?: boolean } | undefined; - constructor(ids: Iterable) { + constructor(ids: Iterable, private readonly reload?: () => Iterable, + private readonly report?: (error: unknown, log: boolean) => boolean | void) { + this.db = this.build(ids); + } + + private build(ids: Iterable): Database { + const db = new Database(":memory:"); + try { + db.exec("CREATE TABLE identities (id TEXT PRIMARY KEY) WITHOUT ROWID"); + const insert = db.query("INSERT OR IGNORE INTO identities (id) VALUES (?)"); + db.transaction(() => { + for (const id of ids) { + if (!nativeCheckpointId.safeParse(id).success) throw Error("Invalid native recovery identity."); + insert.run(id); + } + })(); + return db; + } catch (error) { db.close(); throw error; } + } + + private rebuild(): void { + if (!this.reload) throw Error("Native recovery index is unavailable; restart the manager to rebuild it."); + // Publish only a complete replacement. A refused rebuild leaves admission + // closed, and the next operation retries without needing a process restart. + try { + const replacement = this.build(this.reload()); + this.db.close(); this.db = replacement; this.failed = false; + this.reportPending(); + } catch (error) { + this.failed = true; this.diagnostic ??= { error }; + this.reportPending(); + throw error; + } + } + + private reportPending(): void { + const pending = this.diagnostic; + if (!pending) return; try { - this.db.exec("CREATE TABLE identities (id TEXT PRIMARY KEY) WITHOUT ROWID"); - this.insert = this.db.query("INSERT OR IGNORE INTO identities (id) VALUES (?)"); - this.select = this.db.query<{ id: string }, [string]>("SELECT id FROM identities WHERE id > ? ORDER BY id LIMIT 65"); - this.db.transaction(() => { for (const id of ids) this.remember(id); })(); - } catch (error) { this.db.close(); throw error; } + const written = this.report?.(pending.error, !pending.logged); + pending.logged = true; + if (written !== false) this.diagnostic = undefined; + } + catch (error) { + // Preserve the original cause for the next request; diagnostics never + // gate a complete rebuild. Log one failure per pending cause. + if (!pending.logged) { + console.error(JSON.stringify({ kind: "native_recovery_diagnostic_failure", site: "NativeRecoveryIndex.reportPending", at: Date.now(), + cause: String(pending.error), diagnosticError: String(error) })); + pending.logged = true; + } + } + } + + private use(operation: () => T): T { + if (this.closed) throw Error("Native recovery index is closed."); + if (this.failed) this.rebuild(); else this.reportPending(); + try { return operation(); } + catch (error) { + this.failed = true; this.diagnostic ??= { error }; + this.rebuild(); + try { return operation(); } + catch (again) { this.failed = true; this.diagnostic ??= { error: again }; throw again; } + } + } + + /** Dependent admission waits for a complete rebuild after any failed write. */ + ensureAvailable(): void { + if (this.closed) throw Error("Native recovery index is closed."); + if (this.failed) this.rebuild(); else this.reportPending(); } /** Called only after the JSON rename and parent-directory fsync complete. */ remember(id: string): void { - try { - if (this.failed || !nativeCheckpointId.safeParse(id).success) throw Error("Native recovery index is unavailable; restart the manager to rebuild it."); - this.insert.run(id); - } catch (error) { this.failed = true; throw error; } + if (!nativeCheckpointId.safeParse(id).success) { this.failed = true; throw Error("Invalid native recovery identity."); } + this.use(() => { this.db.query("INSERT OR IGNORE INTO identities (id) VALUES (?)").run(id); }); } /** Called only after the JSON intent was removed and its directory synced. */ forget(id: string): void { - try { - if (this.failed) throw Error("Native recovery index is unavailable; restart the manager to rebuild it."); - this.db.query("DELETE FROM identities WHERE id = ?").run(id); - } catch (error) { this.failed = true; throw error; } + this.use(() => { this.db.query("DELETE FROM identities WHERE id = ?").run(id); }); } - /** 64 response candidates and one lookahead; no complete-history scan. */ + /** 64 response candidates and one lookahead; only recovery scans history. */ page(after: string | null): string[] { - if (this.failed) throw Error("Native recovery index is unavailable; restart the manager to rebuild it."); if (after !== null && !nativeCheckpointId.safeParse(after).success) throw Error("Invalid native recovery cursor."); - return this.select.all(after ?? "").map(row => row.id); + return this.use(() => this.db.query<{ id: string }, [string]>("SELECT id FROM identities WHERE id > ? ORDER BY id LIMIT 65") + .all(after ?? "").map(row => row.id)); } - close(): void { this.db.close(); } + close(): void { this.closed = true; this.db.close(); } } diff --git a/packages/ui-sdk/src/server/native-reference-pool.ts b/packages/ui-sdk/src/server/native-reference-pool.ts index 3e1d211130..ff054eaea4 100644 --- a/packages/ui-sdk/src/server/native-reference-pool.ts +++ b/packages/ui-sdk/src/server/native-reference-pool.ts @@ -22,6 +22,7 @@ import { randomUUID } from "node:crypto"; import { dirname, isAbsolute, join } from "node:path"; import { NativeBrainManagerError, nativeCheckpointId, nativePoolName, NATIVE_CONTROL_BYTES, REFERENCE_POOL_CHECKPOINT_BYTES, type NativePoolAccess, type NativePoolCheckpoint, type NativePoolRecord, type NativePoolSpace, type NativePoolState, type NativePoolStatus } from "./native-brain-manager-protocol.js"; +import { recordNativeRecoveryFailure } from "./native-recovery-diagnostics.js"; import { NativeRecoveryIndex } from "./native-recovery-index.js"; import { POOL_HELPER } from "./native-reference-pool-helper.js"; @@ -427,8 +428,9 @@ export async function createNativeReferencePool(context: ReferencePoolContext) { emergencyConsumed = true; await context.command([BTRFS, "filesystem", "sync", pool.storePath]); try { write(); } catch (again) { throw new NativeBrainManagerError("capacity", String(again)); } } + intents.set(intent.id, intent); try { index.remember(intent.id); } - catch { throw new NativeBrainManagerError("unknown", "Reference pool intent is durable but recovery indexing failed; restart the manager to rebuild it."); } + catch { throw new NativeBrainManagerError("unknown", "Reference pool intent is durable but recovery indexing failed; rebuilding from durable intents is unavailable; retry the operation."); } } const ids: string[] = []; for (const name of readdirSync(state)) { @@ -438,9 +440,20 @@ export async function createNativeReferencePool(context: ReferencePoolContext) { try { readIntent(id); } catch (error) { closeSync(stateFd); throw error; } ids.push(id); } - const index = (() => { try { return new NativeRecoveryIndex(ids); } catch (error) { closeSync(stateFd); throw error; } })(); - // Startup reads every retained intent once; identities stay bounded by maxIdentities. + // Durable mutations update both accounting and the disposable index before replying. const intents = new Map(ids.map(id => [id, readIntent(id)!])); + const index = (() => { try { return new NativeRecoveryIndex(ids, () => { + const replacement = new Map(); + for (const name of readdirSync(state)) { + if (name.endsWith(".tmp")) continue; + const id = name.slice(0, -5); + if (!name.endsWith(".json") || !nativeCheckpointId.safeParse(id).success) throw new NativeBrainManagerError("unknown", "Reference pool state contains an unrecognized identity."); + replacement.set(id, readIntent(id)!); + } + intents.clear(); for (const [id, intent] of replacement) intents.set(id, intent); + return replacement.keys(); + }, (error, log) => recordNativeRecoveryFailure(join(privateRoot, "recovery-diagnostics"), "recovery-index", "native-reference-pool.writeIntent", error, log)); } + catch (error) { closeSync(stateFd); throw error; } })(); // A publication interrupted between unseal and reseal leaves a sealed root writable. try { for (const intent of intents.values()) { @@ -560,6 +573,7 @@ export async function createNativeReferencePool(context: ReferencePoolContext) { try { return lstatSync(emergency).blocks * 512 * dataFactor; } catch { return 0; } } async function measure(signal?: AbortSignal) { + index.ensureAvailable(); const observation = await observe(signal), places = { viewDirIds: viewDirIds(), accessDirIds: accessDirIds() }; await reconcile(observation, places, signal); const result = referencePoolAccounting({ observation, intents: [...intents.values()], limits: pool, rootsDirId, ...places, diff --git a/packages/ui-sdk/tests/native-intent-recovery.test.ts b/packages/ui-sdk/tests/native-intent-recovery.test.ts new file mode 100644 index 0000000000..10b6dc4646 --- /dev/null +++ b/packages/ui-sdk/tests/native-intent-recovery.test.ts @@ -0,0 +1,43 @@ +import { expect, spyOn, test } from "bun:test"; +import { mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { recoverNativeIntents } from "../src/server/native-intent-recovery.js"; + +test("malformed native intents preserve identity and cause while other identities recover", () => { + const root = mkdtempSync(join(tmpdir(), "odysseus-intent-")), state = join(root, "state"), diagnostics = join(root, "diagnostics"); + mkdirSync(state); + const bad = "11111111-1111-4111-8111-111111111790", good = "22222222-2222-4222-8222-222222221790"; + writeFileSync(join(state, `${bad}.json`), "{broken"); + writeFileSync(join(state, `${good}.json`), JSON.stringify({ id: good, state: "sealed" })); + const recovered: string[] = []; + try { + const result = recoverNativeIntents(state, diagnostics, id => { JSON.parse(readFileSync(join(state, `${id}.json`), "utf8")); recovered.push(id); }); + expect(recovered, "NATIVE_OTHER_IDENTITY_RECOVERS").toEqual([good]); + expect(result.ids.sort()).toEqual([bad, good]); + expect([...result.quarantined], "NATIVE_MALFORMED_ID_STAYS_FENCED").toEqual([bad]); + expect(readFileSync(join(state, `${bad}.json`), "utf8")).toBe("{broken"); + const cause = JSON.parse(readFileSync(join(diagnostics, readdirSync(diagnostics)[0]!), "utf8")); + expect(cause).toMatchObject({ scope: `${bad}.json`, site: "native-brain-manager.recoverIntent", errorClass: "SyntaxError" }); + expect(cause.at).toBeGreaterThan(0); + } finally { rmSync(root, { recursive: true, force: true }); } +}); + + +test("a failed native diagnostic write does not abandon healthy intent recovery", () => { + const root = mkdtempSync(join(tmpdir(), "odysseus-diagnostics-")), state = join(root,"state"), diagnostics = join(root,"diagnostics"); + mkdirSync(state); writeFileSync(diagnostics,"unwritable directory"); + const bad = "11111111-1111-4111-8111-111111111790", good = "22222222-2222-4222-8222-222222221790"; + writeFileSync(join(state, `${bad}.json`), "{broken"); writeFileSync(join(state, `${good}.json`), "{}"); + const recovered: string[] = [], logs: string[] = []; + const logger = spyOn(console,"error").mockImplementation(line => { logs.push(String(line)); }); + try { + expect(() => recoverNativeIntents(state, diagnostics, id => { + JSON.parse(readFileSync(join(state, `${id}.json`), "utf8")); recovered.push(id); + }), "NATIVE_DIAGNOSTIC_FAILURE_DOES_NOT_BLOCK_BOOT").not.toThrow(); + expect(recovered).toEqual([good]); + expect(logs).toHaveLength(1); + expect(JSON.parse(logs[0]!)).toMatchObject({kind:"native_recovery_failure",scope:`${bad}.json`,errorClass:"SyntaxError"}); + expect(JSON.parse(logs[0]!).diagnosticError).toContain("EEXIST"); + } finally { logger.mockRestore(); rmSync(root,{recursive:true,force:true}); } +}); diff --git a/packages/ui-sdk/tests/native-manager-capacity.test.ts b/packages/ui-sdk/tests/native-manager-capacity.test.ts new file mode 100644 index 0000000000..f3677a395c --- /dev/null +++ b/packages/ui-sdk/tests/native-manager-capacity.test.ts @@ -0,0 +1,156 @@ +import { afterEach, expect, spyOn, test } from "bun:test"; +import * as fs from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import * as inspection from "../src/server/native-identity-inspector"; +import * as stages from "../src/server/native-brain-stage"; +import { createNativeBrainManager } from "../src/server/native-brain-manager"; +import type { NativeManagerReady, NativeStage } from "../src/server/native-brain-manager-protocol"; + +const id = (n: number) => `38160000-0000-4000-8000-${String(n).padStart(12, "0")}`; +const cleanups: Array<() => void | Promise> = []; +afterEach(async () => { + const failures: unknown[] = []; + for (const cleanup of cleanups.splice(0).reverse()) try { await cleanup(); } catch (error) { failures.push(error); } + if (failures.length) throw new AggregateError(failures, "Native capacity fixture cleanup failed"); +}); + +/** Real manager, intents and filesystem; only privileged kernel operations are doubled. */ +function fixture() { + const root = fs.mkdtempSync(join(tmpdir(), "odysseus-native-capacity-")); + cleanups.push(() => fs.rmSync(root, { recursive: true, force: true })); + const config = { storePath: root, devicePath: join(root, "device"), socketPath: join(root, "manager.sock"), + fsid: id(1), brainUuid: "a".repeat(32), capacityBytes: 1024 ** 3, recoveryReserveBytes: 4096, + appUid: 1000, appGid: 1000, stageAllowanceBytes: 4096, stageBudgetBytes: 4096 }; + const state = join(root, ".brain-native/state"), stageRoot = join(root, ".brain-native/stages"); + fs.mkdirSync(state, { recursive: true, mode: 0o700 }); fs.chmodSync(dirname(state), 0o710); + fs.mkdirSync(stageRoot, { mode: 0o710 }); + const lstat = fs.lstatSync, stat = fs.statSync, fstat = fs.fstatSync, read = fs.readFileSync, list = fs.readdirSync, exists = fs.existsSync; + let inspectionError: string | undefined; + const faults: Array<{ mockRestore(): void }> = [ + spyOn(process, "geteuid").mockReturnValue(0), + spyOn(fs, "chownSync").mockImplementation(() => {}), + spyOn(fs, "existsSync").mockImplementation(path => path === join(stageRoot, id(2)) && inspectionError ? false : exists(path)), + spyOn(fs, "lstatSync").mockImplementation(((path: string, options?: never) => { + if (path === join(stageRoot, id(2)) && inspectionError) throw Object.assign(Error(inspectionError), { code: inspectionError }); + const value = lstat(path, options); value.uid = 0; + if (!path.startsWith(root)) value.mode &= ~0o022; + return value; + }) as typeof fs.lstatSync), + spyOn(fs, "fstatSync").mockImplementation(((...args: Parameters) => { + const value = fstat(...args); value.uid = 0; return value; + }) as typeof fs.fstatSync), + spyOn(fs, "statSync").mockImplementation(((path: string, options?: never) => { + if (path === config.devicePath) return { isBlockDevice: () => true, rdev: 256n }; + if (["/usr/bin/btrfs", "/usr/bin/python3", "/usr/bin/fallocate"].includes(path)) return { isFile: () => true, uid: 0, mode: 0o755 }; + return stat(path, options); + }) as typeof fs.statSync), + spyOn(fs, "readFileSync").mockImplementation(((path: string | number, options?: never) => { + if (path === "/proc/self/mountinfo") return `41 25 0:38 / ${root} rw - btrfs ${config.devicePath} rw\n`; + if (path === "/sys/dev/block/1:0/size") return String(config.capacityBytes / 512); + if (path === `/sys/fs/btrfs/${config.fsid}/devices/device/dev`) return "1:0"; + return read(path, options); + }) as typeof fs.readFileSync), + spyOn(fs, "readdirSync").mockImplementation(((path: string, options?: never) => + path === `/sys/fs/btrfs/${config.fsid}/devices` ? ["device"] : list(path, options)) as typeof fs.readdirSync), + spyOn(fs, "statfsSync").mockReturnValue({ type: 0x9123683e, bavail: 1000, bsize: 4096 } as fs.StatsFs), + spyOn(inspection, "createNativeIdentityInspector").mockReturnValue({ launches: 0, async close() {}, async run(_program, path) { + return { code: 0, errors: "", text: JSON.stringify({ fsid: config.fsid, devices: 1, uuid: path === join(root, "brain") ? config.brainUuid : "b".repeat(32), + parentUuid: config.brainUuid, receivedUuid: "0".repeat(32), rootId: "256", transaction: "1", readOnly: path !== join(root, "brain") }) }; + } }), + spyOn(Bun, "spawn").mockImplementation(((argv: string[]) => { + let errors = "", code = 0; + if (argv[0] === "/usr/bin/fallocate") fs.writeFileSync(argv[3]!, new Uint8Array(Number(argv[2]))); + else if (argv[1] === "qgroup") { errors = "quota not enabled"; code = 1; } + else if (argv[2] === "snapshot") fs.mkdirSync(argv[5]!); + else if (argv[2] !== "list" && argv[2] !== "sync") throw Error(`Unexpected native command: ${argv}`); + return { stdout: new Response("").body!, stderr: new Response(errors).body!, exited: Promise.resolve(code), kill() {} }; + }) as typeof Bun.spawn), + ]; + let closeStage = async () => {}; + const prepared: NativeStage[] = []; + faults.push(spyOn(stages, "startNativeStage").mockImplementation(async options => { + const stage: NativeStage = { ...options, namespacePid: process.pid, namespaceStart: "1", rootDevice: "1", rootInode: "2" }; + prepared.push(stage); + return { stage, mountNamespaceInode: "1", mergedDevice: "1", mergedInode: "2", async close() { await closeStage(); }, + async read() { return { async close() {} }; }, async *inspect() {} }; + })); + cleanups.push(() => { for (const fault of faults.reverse()) fault.mockRestore(); }); + return { config, state, stageRoot, prepared, setInspectionError(code?: string) { inspectionError = code; }, + setCloseStage(close: () => Promise) { closeStage = close; }, + async manager(override: Partial = {}) { + const manager = await createNativeBrainManager({ ...config, ...override }); + let closed = false; + const close = async () => { if (!closed) { closed = true; closeStage = async () => {}; await manager.close(); } }; + cleanups.push(close); return { ...manager, close }; + } }; +} + +test("malformed receipt without a stage admits a healthy stage at a one-allowance budget", async () => { + const f = fixture(); fs.writeFileSync(join(f.state, `${id(2)}.json`), "{broken"); + for (let boot = 0; boot < 2; boot++) { + const manager = await f.manager(); + await manager.run({ operation: "checkpoint", id: id(3 + boot * 10) }); + const stage = await manager.run({ operation: "prepareStage", id: id(4 + boot * 10), checkpointId: id(3 + boot * 10), allowanceBytes: 4096 }); + expect((await stage.json()).id, "NATIVE_ABSENT_STAGE_SINGLE_SLOT_PREPARES").toBe(id(4 + boot * 10)); + await manager.run({ operation: "releaseStage", id: id(4 + boot * 10) }); + expect(((await (await manager.run({ operation: "ready" })).json()) as NativeManagerReady).recovery?.stagingChargedBytes).toBe(0); + await expect(manager.run({ operation: "checkpoint", id: id(2) })).rejects.toThrow("quarantined"); + await manager.close(); + } + expect(f.prepared).toHaveLength(2); +}); + +test("a non-UUID receipt is quarantined without charging impossible staging storage", async () => { + const f = fixture(); fs.writeFileSync(join(f.state, "invalid.json"), "{broken"); + const manager = await f.manager(); + await manager.run({ operation: "checkpoint", id: id(3) }); + const stage = await manager.run({ operation: "prepareStage", id: id(4), checkpointId: id(3), allowanceBytes: 4096 }); + expect((await stage.json()).id, "NATIVE_INVALID_NAME_CANNOT_OWN_STAGE").toBe(id(4)); + expect(fs.readFileSync(join(f.state, "invalid.json"), "utf8")).toBe("{broken"); +}); + +test.each([undefined, "EACCES"])("surviving quarantined stage retains its original bound across smaller configuration: %s", async inspectionError => { + const f = fixture(); let manager = await f.manager({ stageAllowanceBytes: 8192, stageBudgetBytes: 12288 }); + await manager.run({ operation: "checkpoint", id: id(3) }); + await manager.run({ operation: "prepareStage", id: id(2), checkpointId: id(3), allowanceBytes: 8192 }); + await manager.close(); + fs.writeFileSync(join(f.state, `${id(2)}.json`), "{broken"); + f.setInspectionError(inspectionError); + manager = await f.manager({ stageBudgetBytes: 12288 }); + expect(((await (await manager.run({ operation: "ready" })).json()) as NativeManagerReady).recovery?.stagingChargedBytes, + "NATIVE_QUARANTINE_RETAINS_HISTORICAL_ALLOWANCE").toBe(8192); + await manager.run({ operation: "prepareStage", id: id(4), checkpointId: id(3), allowanceBytes: 4096 }); + await expect(manager.run({ operation: "prepareStage", id: id(5), checkpointId: id(3), allowanceBytes: 4096 }), + "NATIVE_QUARANTINE_CHARGE_REMAINS_RESERVED").rejects.toMatchObject({ code: "capacity" }); + await expect(manager.run({ operation: "releaseStage", id: id(2) })).rejects.toThrow("quarantined"); +}); + +for (const fault of ["missing bound", "EACCES"] as const) test(`unproven stage capacity reports recovery, not a retryable busy slot: ${fault}`, async () => { + const f = fixture(); fs.writeFileSync(join(f.state, `${id(2)}.json`), "{broken"); + fs.mkdirSync(join(f.stageRoot, id(2))); + if (fault === "EACCES") f.setInspectionError(fault); + const manager = await f.manager(); await manager.run({ operation: "checkpoint", id: id(3) }); + expect(((await (await manager.run({ operation: "ready" })).json()) as NativeManagerReady).recovery?.stagingChargedBytes).toBeNull(); + await expect(manager.run({ operation: "prepareStage", id: id(4), checkpointId: id(3), allowanceBytes: 4096 }), + "NATIVE_UNBOUNDED_QUARANTINE_IS_RECOVERY_NOT_BUSY").rejects.toMatchObject({ code: "unknown", message: expect.stringContaining("recovery") }); +}); + +test("stage close failure retains its charge and independent bound until confirmed removal", async () => { + const f = fixture(), manager = await f.manager(); + await manager.run({ operation: "checkpoint", id: id(3) }); + await manager.run({ operation: "prepareStage", id: id(2), checkpointId: id(3), allowanceBytes: 4096 }); + f.setCloseStage(async () => { throw Error("Odysseus close is unresolved"); }); + await expect(manager.run({ operation: "releaseStage", id: id(2) })).rejects.toThrow("close is unresolved"); + expect(fs.existsSync(join(f.stageRoot, `${id(2)}.allowance`)), "NATIVE_BOUND_SURVIVES_UNCONFIRMED_CLOSE").toBe(true); + await expect(manager.run({ operation: "prepareStage", id: id(4), checkpointId: id(3), allowanceBytes: 4096 })).rejects.toMatchObject({ code: "capacity" }); + f.setCloseStage(async () => {}); + f.setInspectionError("EACCES"); + await expect(manager.run({ operation: "releaseStage", id: id(2) })).rejects.toMatchObject({ code: "EACCES" }); + expect(fs.readFileSync(join(f.stageRoot, `${id(2)}.allowance`), "utf8"), "NATIVE_BOUND_SURVIVES_UNCONFIRMED_REMOVAL").toBe("4096"); + await expect(manager.run({ operation: "prepareStage", id: id(4), checkpointId: id(3), allowanceBytes: 4096 })).rejects.toMatchObject({ code: "capacity" }); + f.setInspectionError(); + await manager.run({ operation: "releaseStage", id: id(2) }); + expect(fs.existsSync(join(f.stageRoot, `${id(2)}.allowance`))).toBe(false); + await manager.run({ operation: "prepareStage", id: id(4), checkpointId: id(3), allowanceBytes: 4096 }); +}); diff --git a/packages/ui-sdk/tests/native-recovery-index.test.ts b/packages/ui-sdk/tests/native-recovery-index.test.ts index b9fad63230..99660d2aa6 100644 --- a/packages/ui-sdk/tests/native-recovery-index.test.ts +++ b/packages/ui-sdk/tests/native-recovery-index.test.ts @@ -1,5 +1,9 @@ -import { expect, test } from "bun:test"; +import { expect, spyOn, test } from "bun:test"; import { NativeRecoveryIndex } from "../src/server/native-recovery-index"; +import { recordNativeRecoveryFailure } from "../src/server/native-recovery-diagnostics"; +import { mkdtempSync, readFileSync, readdirSync, rmSync, unlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; const id = (n: number) => `17920000-0000-4000-8000-${String(n).padStart(12, "0")}`; @@ -28,3 +32,68 @@ test("unindexed durable identity uncertainty refuses pages until restart rebuild try { expect(rebuilt.page(null)).toEqual([id(1), id(2)]); } finally { rebuilt.close(); } }); + +for (const operation of ["remember", "forget"] as const) test(`a failed index ${operation} rebuilds from durable identities in place`, () => { + const durable = new Set([id(1)]); + const index = new NativeRecoveryIndex(durable, () => durable); + try { + (index as unknown as { db: import("bun:sqlite").Database }).db.exec("PRAGMA query_only = ON"); + if (operation === "remember") durable.add(id(2)); else durable.delete(id(1)); + expect(() => index[operation](operation === "remember" ? id(2) : id(1)), "RECOVERY_INDEX_REBUILDS_FAILED_WRITE").not.toThrow(); + expect(index.page(null)).toEqual([...durable]); + durable.add(id(3)); index.remember(id(3)); + expect(index.page(null), "RECOVERY_INDEX_NEXT_CHECKPOINT_WORKS").toEqual([...durable]); + } finally { index.close(); } +}); + +test("a failed rebuild keeps pages closed and retries on the next admission", () => { + let unavailable = true; + const index = new NativeRecoveryIndex([id(1)], () => { + if (unavailable) throw Error("Odysseus intent directory unavailable"); + return [id(1), id(2)]; + }); + try { + (index as unknown as { db: import("bun:sqlite").Database }).db.exec("PRAGMA query_only = ON"); + expect(() => index.remember(id(2))).toThrow("intent directory unavailable"); + expect(() => index.page(null), "RECOVERY_INDEX_NO_PARTIAL_PAGE").toThrow("intent directory unavailable"); + unavailable = false; + expect(index.page(null), "RECOVERY_INDEX_RECOVERS_WITHOUT_RESTART").toEqual([id(1), id(2)]); + } finally { index.close(); } +}); + + +test("index recovery retains a cause whose diagnostic write initially failed", () => { + const causes: string[] = []; let fail = true; + const index = new NativeRecoveryIndex([id(1)], () => [id(1), id(2)], error => { + if (fail) { fail = false; throw Error("Odysseus diagnostics unavailable"); } + causes.push(String(error)); + }); + try { + (index as unknown as { db: import("bun:sqlite").Database }).db.exec("PRAGMA query_only = ON"); + expect(() => index.remember(id(2)), "RECOVERY_INDEX_DIAGNOSTIC_DOES_NOT_BLOCK_REBUILD").not.toThrow(); + expect(index.page(null)).toEqual([id(1), id(2)]); + expect(causes[0], "RECOVERY_INDEX_ORIGINAL_CAUSE_SURVIVES_REPORT_FAILURE").toContain("readonly"); + } finally { index.close(); } +}); + +test("the concrete diagnostic writer retries the pending cause after storage recovers", () => { + const root = mkdtempSync(join(tmpdir(), "odysseus-index-cause-")), diagnostics = join(root, "diagnostics"); + writeFileSync(diagnostics, "not a directory"); + const log = spyOn(console, "error").mockImplementation(() => {}); + const index = new NativeRecoveryIndex([id(1)], () => [id(1), id(2)], + (error, log) => recordNativeRecoveryFailure(diagnostics, "recovery-index", "native-brain-manager.writeIntent", error, log)); + try { + (index as unknown as { db: import("bun:sqlite").Database }).db.exec("PRAGMA query_only = ON"); + index.remember(id(2)); + expect(index.page(null)).toEqual([id(1), id(2)]); + unlinkSync(diagnostics); + index.ensureAvailable(); + expect(readdirSync(root), "RECOVERY_INDEX_RETRIES_CONCRETE_DIAGNOSTIC_WRITE").toContain("diagnostics"); + const files = readdirSync(diagnostics); + expect(files).toHaveLength(1); + const cause = JSON.parse(readFileSync(join(diagnostics, files[0]!), "utf8")); + expect(cause.message).toContain("readonly"); + expect(cause.site).toBe("native-brain-manager.writeIntent"); + expect(log).toHaveBeenCalledTimes(1); + } finally { log.mockRestore(); index.close(); rmSync(root, { recursive: true, force: true }); } +}); diff --git a/packages/ui-server/migrations/085_journal_object_quarantine.journal.sql b/packages/ui-server/migrations/085_journal_object_quarantine.journal.sql new file mode 100644 index 0000000000..09793b49bc --- /dev/null +++ b/packages/ui-server/migrations/085_journal_object_quarantine.journal.sql @@ -0,0 +1,9 @@ +-- Corrupt retained bytes remain charged and unavailable until normal expiry +-- removes their last owner and collects them. Never accept them as undo data. +CREATE TABLE journal.turn_journal_object_quarantine ( + hash TEXT PRIMARY KEY REFERENCES turn_journal_objects(hash) ON DELETE CASCADE, + at INTEGER NOT NULL, + error_class TEXT NOT NULL, + message TEXT NOT NULL, + call_site TEXT NOT NULL +); diff --git a/packages/ui-server/src/app.ts b/packages/ui-server/src/app.ts index 5f9b0a5a8d..75928d592f 100644 --- a/packages/ui-server/src/app.ts +++ b/packages/ui-server/src/app.ts @@ -1065,6 +1065,7 @@ export async function createApp(options: CreateAppOptions = {}): Promise journal.cleanupStatus(), sourceCommit: config.sourceCommit, getBackendAvailability: () => backendAvailability, + getNativeRecovery: () => nativeReady.recovery, getContentRenderers: async signal => brain.modules ? declaredContentRenderers((await brain.modules({ signal })).enabled) : undefined, getCronStatus: () => cron.getCronStatus(), isTurnActive: () => host.coordinator.isTurnActive(), diff --git a/packages/ui-server/src/brain/journal-accounting.ts b/packages/ui-server/src/brain/journal-accounting.ts index 10a39a078a..1073292a5c 100644 --- a/packages/ui-server/src/brain/journal-accounting.ts +++ b/packages/ui-server/src/brain/journal-accounting.ts @@ -13,6 +13,11 @@ export class JournalStorageUnavailable extends Error { constructor(message: string) { super(`The change journal cannot safely retain this observation: ${message}`); } } +/** A known quarantined hash is local to one captured path, not the journal. */ +export class JournalObjectQuarantined extends Error { + constructor() { super("The retained object is quarantined."); } +} + /** * Connection-local triggers: a journal row changed outside an accounted * write is refused, so no journal storage reaches the disk unadmitted. @@ -206,6 +211,7 @@ export function createJournalAccounting(db: Database, dbPath: string, options: { const id = crypto.randomUUID(); write(() => { assertOwner?.(); + if (db.query("SELECT 1 FROM turn_journal_object_quarantine WHERE hash=?").get(hash)) throw new JournalStorageUnavailable("the retained object is quarantined"); if (!db.query("SELECT 1 FROM turn_journal_objects WHERE hash=? AND state='present'").get(hash)) throw new JournalStorageUnavailable("the retained object is unavailable"); db.query("INSERT INTO turn_journal_reservations (id,bytes,pid,pid_start,created_at,hash,kind) VALUES (?,0,?,?,?,?,'read')").run(id, SELF.pid, SELF.start, Date.now(), hash); }); return id; @@ -236,18 +242,50 @@ export function createJournalAccounting(db: Database, dbPath: string, options: { }); continue; } - const published = objects.has(row.hash); - if (published && !objects.verify(row.hash, row.bytes)) throw new JournalStorageUnavailable("a published interrupted object failed integrity verification"); + let published = false, corrupt: unknown; + try { + published = objects.has(row.hash); + if (published && !objects.verify(row.hash, row.bytes)) corrupt = new Error("Published interrupted object failed integrity verification"); + } catch (error) { + // An I/O refusal proves neither existence nor corruption. Keep the + // reservation and its state untouched for the next recovery pass. + process.stderr.write(JSON.stringify({ kind: "journal_object_recovery_pending", hash: row.hash, site: "journal-accounting.recover", at: Date.now(), + errorClass: error instanceof Error ? error.name : "Error", message: String(error) }) + "\n"); + continue; + } + if (!published && db.query("SELECT 1 FROM turn_journal_object_refs WHERE hash=? LIMIT 1").get(row.hash)) + corrupt = new Error("Retained interrupted object is absent"); + let quarantined = false; write(() => { // Verify liveness again under the database write lock; neither a live // writer nor a new reservation sharing this hash is collected. const current = db.query("SELECT pid,pid_start FROM turn_journal_reservations WHERE id=?").get(row.id) as { pid: number; pid_start: string } | null; if (!current || processAlive(current.pid, current.pid_start)) return; objects.discardPending(row.id); - if (published) db.query("UPDATE turn_journal_objects SET state='present' WHERE hash=?").run(row.hash); + if (corrupt) { + const cause = { errorClass: corrupt instanceof Error ? corrupt.name : "Error", message: (corrupt instanceof Error ? corrupt.message : String(corrupt)).slice(0, 2000) }; + db.query("INSERT OR IGNORE INTO turn_journal_object_quarantine VALUES (?,?,?,?,?)").run(row.hash, Date.now(), cause.errorClass, cause.message, "journal-accounting.recover"); + // Logical quarantine keeps the bytes at their original hash, charged, + // but no read or replacement reservation can use them. Only normal + // expiry/collection removes them after their owners release them. + db.query("UPDATE turn_journal_objects SET state='present' WHERE hash=?").run(row.hash); + const owners = db.query("SELECT t.turn_id,t.missing FROM turn_journal_turns t JOIN turn_journal_object_refs r ON r.turn_id=t.turn_id WHERE r.hash=?").all(row.hash) as {turn_id:string;missing:string}[]; + for (const owner of owners) { + const paths = db.query(`SELECT path FROM turn_journal_changes WHERE turn_id=?1 AND (json_extract(before_json,'$.hash')=?2 OR json_extract(after_json,'$.hash')=?2) + UNION SELECT path FROM turn_journal_claude_memory WHERE turn_id=?1 AND (json_extract(before_json,'$.hash')=?2 OR json_extract(after_json,'$.hash')=?2) + UNION SELECT p.path FROM turn_journal_revert_paths p JOIN turn_journal_revert_operations o ON o.id=p.operation_id WHERE o.journal_turn_id=?1 AND (json_extract(p.before_json,'$.hash')=?2 OR json_extract(p.after_json,'$.hash')=?2)`) + .all(owner.turn_id, row.hash) as {path:string}[]; + const missing = JSON.parse(owner.missing) as {path:string;reason:string}[]; + for (const {path} of paths.length ? paths : [{path:"."}]) if (!missing.some(item => item.path === path && item.reason === "retained_object_corrupt")) missing.push({path,reason:"retained_object_corrupt"}); + db.query("UPDATE turn_journal_turns SET state=CASE WHEN state='expired' OR ended_at IS NULL THEN state ELSE 'partial' END,missing=? WHERE turn_id=?").run(JSON.stringify(missing), owner.turn_id); + } + quarantined = true; + } else if (published) db.query("UPDATE turn_journal_objects SET state='present' WHERE hash=?").run(row.hash); db.query("DELETE FROM turn_journal_reservations WHERE id=?").run(row.id); - if (!published) db.query("DELETE FROM turn_journal_objects WHERE hash=? AND state='pending' AND NOT EXISTS (SELECT 1 FROM turn_journal_reservations WHERE hash=?)").run(row.hash, row.hash); + if (!published && !corrupt) db.query("DELETE FROM turn_journal_objects WHERE hash=? AND state='pending' AND NOT EXISTS (SELECT 1 FROM turn_journal_reservations WHERE hash=?)").run(row.hash, row.hash); }); + if (quarantined) process.stderr.write(JSON.stringify({ kind: "journal_object_quarantined", hash: row.hash, site: "journal-accounting.recover", at: Date.now(), + errorClass: corrupt instanceof Error ? corrupt.name : "Error", message: corrupt instanceof Error ? corrupt.message : String(corrupt) }) + "\n"); } }, reserve(bytes, hash) { @@ -255,6 +293,7 @@ export function createJournalAccounting(db: Database, dbPath: string, options: { if (!/^[a-f0-9]{64}$/.test(hash)) throw new JournalStorageUnavailable("invalid content identity"); const id = crypto.randomUUID(); write(() => { + if (db.query("SELECT 1 FROM turn_journal_object_quarantine WHERE hash=?").get(hash)) throw new JournalObjectQuarantined(); db.query("INSERT OR IGNORE INTO turn_journal_objects VALUES (?, ?, 'pending')").run(hash, bytes); db.query("INSERT INTO turn_journal_reservations (id,bytes,pid,pid_start,created_at,hash) VALUES (?, ?, ?, ?, ?, ?)").run(id, bytes, SELF.pid, SELF.start, Date.now(), hash); }); diff --git a/packages/ui-server/src/brain/journal-store.ts b/packages/ui-server/src/brain/journal-store.ts index 31187bb246..bfeb6b8098 100644 --- a/packages/ui-server/src/brain/journal-store.ts +++ b/packages/ui-server/src/brain/journal-store.ts @@ -11,7 +11,7 @@ import type { JournalObservationReference, JournalVersion } from "@schlessera/br import type { WireError, WriteProcedures } from "../db/write-worker.js"; import { recordGovernanceEvent } from "../governance/events.js"; import { sessionTaint } from "../governance/session-taint.js"; -import { createJournalAccounting, JournalStorageUnavailable } from "./journal-accounting.js"; +import { JournalObjectQuarantined, createJournalAccounting, JournalStorageUnavailable } from "./journal-accounting.js"; import { configurationSet, recordedConfigurationSet } from "./journal-configuration-sets.js"; import { createJournalObjects, JournalCapacityError, type JournalObjectReservation } from "./journal-objects.js"; import { INDEX_FAMILY_PATHS, INDEX_PUBLICATION_COPY } from "./native-journal-policy.js"; @@ -35,7 +35,8 @@ export const journalCheck = (sql: string, refusal: string, ...params: SQLQueryBi /** Journal refusals keep their class and message across the worker boundary. */ export function reviveJournalError(wire: WireError): Error | undefined { - const error = wire.name === "JournalCapacityError" ? new JournalCapacityError(wire.message) + const error = wire.name === "JournalObjectQuarantined" ? new JournalObjectQuarantined() + : wire.name === "JournalCapacityError" ? new JournalCapacityError(wire.message) : wire.name === "JournalStorageUnavailable" ? new JournalStorageUnavailable("") : wire.name === "JournalStatementRefused" ? new JournalStatementRefused(wire.message) : undefined; if (error) error.message = wire.message; @@ -115,6 +116,7 @@ export function setup(db: Database, options: JournalStoreOptions): WriteProcedur const unused = db.query("SELECT hash,bytes FROM turn_journal_objects WHERE state='present' AND hash NOT IN (SELECT hash FROM turn_journal_object_refs) AND hash NOT IN (SELECT hash FROM turn_journal_reservations WHERE hash IS NOT NULL)").all() as { hash: string; bytes: number }[]; for (const row of unused) { if (objects.has(row.hash)) objects.remove(row.hash); + db.query("DELETE FROM turn_journal_object_quarantine WHERE hash=?").run(row.hash); db.query("DELETE FROM turn_journal_objects WHERE hash=?").run(row.hash); } return { objects: unused.length, bytes: unused.reduce((sum, row) => sum + row.bytes, 0) }; @@ -286,6 +288,7 @@ export function setup(db: Database, options: JournalStoreOptions): WriteProcedur for (const item of record.unreadable) { const { ms, ...known } = item; missing.set(item.path, known); + if (item.reason === "retained_object_corrupt") continue; // Quarantine already owns the durable cause. const signature = `journal_reader:${item.kind ?? "unknown"}:${item.bytes ?? "unknown"}:${item.path}`.slice(0, 1000); recordGovernanceEvent(db, { kind: "roadblock", sessionId: metadata.session_id, turnId, actor: metadata.actor, model: metadata.model, profile: metadata.profile, at, dedupeKey: `journal-reader:${turnId}:${item.path}`, diff --git a/packages/ui-server/src/brain/native-journal-capture.ts b/packages/ui-server/src/brain/native-journal-capture.ts index 1f4a4aa3c6..4917ead2f0 100644 --- a/packages/ui-server/src/brain/native-journal-capture.ts +++ b/packages/ui-server/src/brain/native-journal-capture.ts @@ -1,4 +1,5 @@ /** Changed versions only; checkpoint advancement follows the journal commit. */ +import { JournalObjectQuarantined } from "./journal-accounting.js"; import { createNativeJournalObserver, type NativeJournalManager, type NativeJournalMetadata, type NativeJournalUnreadable } from "./native-journal-observer.js"; import { freezeNativeJournalPolicy, journalMetadataOnlyPath, journalPathScope } from "./native-journal-policy.js"; import { nativeJournalPermissionDenied, readNativeJournalFile, withNativeJournalFile, type NativeJournalReadContext } from "./native-journal-read.js"; @@ -78,6 +79,11 @@ export function createNativeJournalCapture(manager: NativeJournalManager, retain const privateRead = context(root, signal), started = performance.now(); try { hash = await withNativeJournalFile(root.path, metadata.path, metadata.bytes, privateRead, file => retain(file.fd, metadata.bytes, signal)); } catch (error) { + if (error instanceof JournalObjectQuarantined) { + unreadable.set(metadata.path, {path:metadata.path, bytes:metadata.bytes, mode:metadata.mode, kind:metadata.kind, + reason:"retained_object_corrupt", ms:0}); + return result; + } if (!privateRead || !nativeJournalPermissionDenied(error)) throw error; unreadable.set(metadata.path, { path: metadata.path, bytes: metadata.bytes, mode: metadata.mode, kind: metadata.kind, reason: "worker_reader_unavailable", ms: Math.max(0, Math.round(performance.now() - started)) }); return result; diff --git a/packages/ui-server/src/brain/native-journal-observer.ts b/packages/ui-server/src/brain/native-journal-observer.ts index e6b05becd3..03f0af51f9 100644 --- a/packages/ui-server/src/brain/native-journal-observer.ts +++ b/packages/ui-server/src/brain/native-journal-observer.ts @@ -32,7 +32,7 @@ interface NativeJournalChange { } export interface NativeJournalUnreadable { path: string; bytes: number | null; mode?: number; kind?: NativeJournalMetadata["kind"]; - reason: "worker_reader_unavailable"; + reason: "worker_reader_unavailable" | "retained_object_corrupt"; ms: number; } export class NativeJournalObservationError extends Error { diff --git a/packages/ui-server/src/brain/turn-journal.ts b/packages/ui-server/src/brain/turn-journal.ts index 13aa48f48b..72f6aebb3c 100644 --- a/packages/ui-server/src/brain/turn-journal.ts +++ b/packages/ui-server/src/brain/turn-journal.ts @@ -119,9 +119,9 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { // Governance events live in the UI database; a commit split between the // two files is completed from the journal's rows (#2789). await createGovernanceWrites(db, writer).replaySteering(); - const interrupted = (db.query("SELECT turn_id,pid,pid_start FROM turn_journal_turns WHERE ended_at IS NULL").all() as { turn_id: string; pid: number; pid_start: string }[]) + const interrupted = (db.query("SELECT turn_id,pid,pid_start,missing FROM turn_journal_turns WHERE ended_at IS NULL").all() as { turn_id: string; pid: number; pid_start: string; missing: string }[]) .filter(row => !processAlive(row.pid, row.pid_start)); - for (const row of interrupted) await ledger.call("statements", [statement("UPDATE turn_journal_turns SET state='partial',ended_at=?,missing=? WHERE turn_id=?", now(), JSON.stringify([{ path: ".", reason: "interrupted_observation" }]), row.turn_id)]); + for (const row of interrupted) await ledger.call("statements", [statement("UPDATE turn_journal_turns SET state='partial',ended_at=?,missing=? WHERE turn_id=?", now(), JSON.stringify([...JSON.parse(row.missing), { path: ".", reason: "interrupted_observation" }]), row.turn_id)]); // Index bytes earlier releases retained are purged once, a step per // commit, after interrupted turns have ended (#2903). A refused step is // left for the next open; until then history already presents them as @@ -623,7 +623,7 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { if (!active.size) { clearInterval(scopeTimer); scopeTimer = undefined; } await write([ ...(failures.has(turnId) ? [statement("UPDATE turn_journal_turns SET state='partial',failure=? WHERE turn_id=?", failures.get(turnId)!.padEnd(64), turnId)] : []), - statement("UPDATE turn_journal_turns SET ended_at=?,failure=trim(failure),state=CASE WHEN state='partial' THEN state ELSE 'complete' END WHERE turn_id=?", now(), turnId), + statement("UPDATE turn_journal_turns SET ended_at=?,failure=trim(failure),state=CASE WHEN state='partial' OR missing!='[]' THEN 'partial' ELSE 'complete' END WHERE turn_id=?", now(), turnId), statement("DELETE FROM turn_journal_manifests WHERE turn_id=?", turnId), statement("DELETE FROM turn_journal_object_refs WHERE turn_id=? AND NOT EXISTS (SELECT 1 FROM turn_journal_changes c WHERE c.turn_id=? AND (json_extract(c.before_json,'$.hash')=turn_journal_object_refs.hash OR json_extract(c.after_json,'$.hash')=turn_journal_object_refs.hash)) AND NOT EXISTS (SELECT 1 FROM turn_journal_claude_memory m WHERE m.turn_id=? AND m.state!='saved' AND (json_extract(m.before_json,'$.hash')=turn_journal_object_refs.hash OR json_extract(m.after_json,'$.hash')=turn_journal_object_refs.hash))", turnId, turnId, turnId), ]); @@ -649,7 +649,8 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { }); }, hasRetainedVersion(turnId: string, selected: JournalVersion): boolean { if (!selected.hash || selected.ignored || selected.metadataOnly || selected.kind !== "file" || ["unknown", "expired"].includes(summary(turnId).state)) return false; - if (!db.query("SELECT 1 FROM turn_journal_object_refs WHERE turn_id=? AND hash=?").get(turnId, selected.hash)) return false; + if (!db.query("SELECT 1 FROM turn_journal_object_refs WHERE turn_id=? AND hash=?").get(turnId, selected.hash) + || db.query("SELECT 1 FROM turn_journal_object_quarantine WHERE hash=?").get(selected.hash)) return false; try { return objects.verify(selected.hash, selected.bytes); } catch { return false; } }, /** @@ -763,7 +764,8 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { version(sessionId: string, turnId: string, sequence: number, side: "before" | "after") { const details = this.details(sessionId, turnId), change = details?.changes.find(item => item.sequence === sequence); const selected = change?.[side]; - if (!selected?.hash || selected.metadataOnly || details?.summary.state === "expired") return null; + if (!selected?.hash || selected.metadataOnly || details?.summary.state === "expired" + || db.query("SELECT 1 FROM turn_journal_object_quarantine WHERE hash=?").get(selected.hash)) return null; return { selected, bytes: (maxBytes: number) => objects.read(selected.hash!, maxBytes), async stream() { const lease = await call("openRead", selected.hash!); const release = () => releaseRead(lease); diff --git a/packages/ui-server/src/brain/writer-gate.ts b/packages/ui-server/src/brain/writer-gate.ts index 16f0f067da..af58214497 100644 --- a/packages/ui-server/src/brain/writer-gate.ts +++ b/packages/ui-server/src/brain/writer-gate.ts @@ -28,6 +28,7 @@ import { join } from "node:path"; import { randomUUID } from "node:crypto"; import { createGovernancePolicyReader, providerFolderRoots, retainedFolderRoots, type TurnGovernancePolicy } from "./governance-policy.js"; import { ensureRetainedDirectories } from "./index-directory.js"; +import { recordGovernanceEvent } from "../governance/events.js"; import { procedureCaller, type SqliteWriter, type WireError, type WriteProcedures } from "../db/write-worker.js"; export type GateMode = "shared" | "exclusive"; @@ -112,9 +113,12 @@ const PEER_FOLDER_PLAN_WAIT_MS = 30_000; const UNRETAINED_PEER = "An active peer did not retain the requested provider folders; finish that peer and retry admission"; -function pause(ms: number, signal?: AbortSignal): Promise { +function pause(ms: number, signal?: AbortSignal, background = false): Promise { return new Promise((resolve, reject) => { const timer = setTimeout(() => { signal?.removeEventListener("abort", stop); resolve(); }, ms); + // A background retry never keeps the process alive: an exited process's + // row is stale, and the next gate read prunes it. + if (background) timer.unref?.(); const stop = () => { clearTimeout(timer); reject(signal!.reason); }; signal?.addEventListener("abort", stop, { once: true }); }); @@ -271,6 +275,12 @@ export function gateProcedures(db: Database, brain: string): WriteProcedures { // the host process exists. The recorded roots are always empty. db.query("UPDATE writer_gate SET folder_topology = ? WHERE id = ?").run(JSON.stringify({ kind: "unpinned_host", roots: folderPaths }), id); }).immediate(), + cleanupFailure(id: string, operation: string, cause: string, at: number) { + recordGovernanceEvent(db, { kind: "roadblock", actor: "server", sessionId: null, turnId: null, model: null, profile: null, at, + dedupeKey: `writer-gate:${operation}:${id}`, payload: { category: "retry", family: "writer_gate_cleanup", signature: `${operation}:${id}`, + failures: [{ toolCallId: null, category: "retry", signature: cause }], resolution: null, remedy: "capability", + waste: { tokens: null, costUsd: null, ms: 0 }, eventIds: [] } }); + }, release(id: string) { db.query("DELETE FROM writer_gate WHERE id = ?").run(id); }, ungated: () => db.transaction(() => { prune(); @@ -309,6 +319,37 @@ export function createWriterGate(db: Database, brainPath: string, options: { pol void done.then(() => {}, () => {}).then(() => pending.delete(done)); return done; }; + // These deletes are idempotent. A failed commit retains its hold/waiter, + // and remains owned until the delete commits. Reporting cannot gate cleanup. + const cleanup = (operation: "release" | "dequeue", id: string): Promise => { + const done = (async () => { + let cause: { message: string; at: number } | undefined, recorded = false; + let attempt = 0; + for (;;) { + try { + await submit(operation, id); + if (cause && !recorded) { + try { await submit("cleanupFailure", id, operation, cause.message, cause.at); } + catch { /* Original structured cause was logged; never retain a released hold for reporting. */ } + } + return; + } catch (error) { + if (!cause) { + cause = { message: `${error instanceof Error ? error.name : "Error"}: ${error instanceof Error ? error.message : String(error)}`.slice(0, 1000), at: Date.now() }; + process.stderr.write(JSON.stringify({ kind: "writer_gate_cleanup", operation, id, ...cause }) + "\n"); + } + if (!recorded) { + try { await submit("cleanupFailure", id, operation, cause.message, cause.at); recorded = true; } + catch { /* Retry the independent diagnostic after the next delete attempt. */ } + } + await pause(Math.min(30_000, Math.max(1, pollMs) * 2 ** Math.min(attempt++, 10)), undefined, true); + } + } + })(); + pending.add(done); + void done.finally(() => pending.delete(done)); + return done; + }; return { async acquire(mode, purpose, { signal, turn = false, queueTurns = false } = {}) { signal?.throwIfAborted(); @@ -326,7 +367,7 @@ export function createWriterGate(db: Database, brainPath: string, options: { pol let released = false, unpinnedHost = false; let releasing: Promise | undefined; const checkPeerFolderPlans = async (paths: readonly string[]): Promise => { - if (released) throw new Error("Writer folder plan was already released"); + if (released || releasing) throw new Error("Writer folder plan was already released"); const requested = mergeFolderPlans([], paths); if (!requested.length) return false; if (unpinnedHost) throw new Error("An unpinned host writer cannot qualify provider folder admission"); @@ -334,7 +375,7 @@ export function createWriterGate(db: Database, brainPath: string, options: { pol return submit("peers", id, requested); }; const hold: GateHold = { id, mode, get folderPaths() { return folderPaths; }, async retainFolders(paths) { - if (released) throw new Error("Writer folder plan was already released"); + if (released || releasing) throw new Error("Writer folder plan was already released"); if (unpinnedHost) throw new Error("An unpinned host writer cannot upgrade its folder plan"); folderPaths = await submit("retain", id, folderPaths, paths); return folderPaths; @@ -355,15 +396,14 @@ export function createWriterGate(db: Database, brainPath: string, options: { pol // Submitted at once, so every later gate write of this process // sees it; the returned promise settles once it has committed. if (releasing) return releasing; - released = true; hostWriterMarkers.delete(hold); - releasing = submit("release", id); + releasing = cleanup("release", id).then(() => { released = true; }); // A caller that does not wait still never leaves it unhandled. releasing.catch(() => {}); return releasing; } }; hostWriterMarkers.set(hold, async () => { - if (released) throw new Error("Writer folder plan was already released"); + if (released || releasing) throw new Error("Writer folder plan was already released"); if (unpinnedHost) return; await submit("unpinned", id, folderPaths); unpinnedHost = true; @@ -372,7 +412,7 @@ export function createWriterGate(db: Database, brainPath: string, options: { pol } await pause(pollMs, signal); } } finally { - if (waiter) await submit("dequeue", waiter); + if (waiter) await cleanup("dequeue", waiter); } }, assertUngatedHostFallback: () => submit("ungated"), diff --git a/packages/ui-server/src/routes/health.ts b/packages/ui-server/src/routes/health.ts index cd6b28dd33..58d9155de6 100644 --- a/packages/ui-server/src/routes/health.ts +++ b/packages/ui-server/src/routes/health.ts @@ -3,7 +3,7 @@ import { Hono } from "hono"; import type { Database } from "bun:sqlite"; import type { ContentRendererDeclaration } from "@schlessera/brain-ui-sdk"; -import type { WorkerHostStatus } from "@schlessera/brain-ui-sdk/protocol"; +import type { SystemStatus, WorkerHostStatus } from "@schlessera/brain-ui-sdk/protocol"; import type { RuntimeStatusSnapshot } from "../activity/runtime-status.js"; import type { BackendBootFailure } from "../agent/backend.js"; @@ -44,6 +44,7 @@ interface StatusDeps { /** Retained checkpoint cleanup and its durable historical cause. */ getJournalCleanup?(): unknown; getBackendAvailability?(): { unavailable: BackendBootFailure[]; lastFailures: BackendBootFailure[] }; + getNativeRecovery?(): SystemStatus["nativeRecovery"]; /** Trusted metadata from configured modules; absent with an older CLI. */ getContentRenderers?(signal?: AbortSignal): Promise; /** Git SHA baked at build time (SOURCE_COMMIT), "dev" when unset. */ @@ -66,11 +67,13 @@ interface StatusDeps { export function createStatusRoutes(deps: StatusDeps): Hono { return new Hono().get("/status", async (c) => { const backendAvailability = deps.getBackendAvailability?.(); + const nativeRecovery = deps.getNativeRecovery?.(); const subscription = deps.getSubscription ? await deps.getSubscription() : undefined; const contentRenderers = await deps.getContentRenderers?.(c.req.raw.signal).catch(() => undefined); return c.json({ + ...(nativeRecovery ? { nativeRecovery } : {}), ...(contentRenderers !== undefined ? { contentRenderers } : {}), - healthy: !backendAvailability?.unavailable.length, + healthy: !backendAvailability?.unavailable.length && nativeRecovery?.stagingChargedBytes !== null, ...(backendAvailability ? { backendAvailability } : {}), ...(deps.getJournalCleanup ? { journalCleanup: deps.getJournalCleanup() } : {}), uptime: Date.now() - startTime, diff --git a/packages/ui-server/tests/journal-accounting.test.ts b/packages/ui-server/tests/journal-accounting.test.ts index c1bea40566..337ef36064 100644 --- a/packages/ui-server/tests/journal-accounting.test.ts +++ b/packages/ui-server/tests/journal-accounting.test.ts @@ -1,5 +1,5 @@ import { expect, test } from "bun:test"; -import { mkdtempSync, readFileSync, rmSync, statSync } from "node:fs"; +import { mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { createUiDb } from "../src/db/client.js"; @@ -160,3 +160,58 @@ test("a killed private reader owner leaves a recoverable reservation without cla expect(db.query("SELECT count(*) AS n FROM turn_journal_objects").get()).toEqual({ n: 0 }); } finally { db.close(); rmSync(root, { recursive: true, force: true }); } }); + +for (const absent of [false, true]) test(`a ${absent ? "missing" : "corrupt"} published interrupted object is quarantined without poisoning other history`, async () => { + const root = mkdtempSync(join(tmpdir(), "journal-quarantine-odysseus-")), path = join(root, "ui.db"); + const db = createUiDb(path), ledger = createJournalAccounting(db, path), objects = createJournalObjects(join(root, "objects"), ledger); + try { + const bad = await objects.putBytes(Buffer.from("Odysseus")), good = await objects.putBytes(Buffer.from("Athena")); + ledger.write(() => { + for (const [id, hash, bytes] of [["odysseus", bad, 8], ["penelope", bad, 8], ["athena", good, 6]] as const) { + db.query("INSERT INTO turn_journal_turns (turn_id,actor,profile,started_at,ended_at,state) VALUES (?,'interactive','governed',0,1,'complete')").run(id); + db.query("INSERT INTO turn_journal_object_refs VALUES (?,?)").run(id, hash); + db.query("INSERT INTO turn_journal_changes (turn_id,sequence,path,scope,before_json) VALUES (?,1,?,'brain',?)").run(id, `notes/${id}.md`, JSON.stringify({kind:"file",hash,bytes})); + } + db.query("INSERT INTO turn_journal_reservations (id,bytes,pid,pid_start,created_at,hash) VALUES (?,8,?,'gone',0,?)").run(crypto.randomUUID(), process.pid, bad); + }); + if (absent) rmSync(join(root,"objects",bad)); else writeFileSync(join(root, "objects", bad), "damaged!"); + expect(() => ledger.recover(objects), "JOURNAL_CORRUPT_OBJECT_DOES_NOT_REFUSE_BOOT").not.toThrow(); + expect(db.query("SELECT * FROM turn_journal_reservations").all()).toEqual([]); + expect(db.query("SELECT turn_id,state FROM turn_journal_turns ORDER BY turn_id").all()).toEqual([ + {turn_id:"athena",state:"complete"},{turn_id:"odysseus",state:"partial"},{turn_id:"penelope",state:"partial"}]); + expect(db.query("SELECT hash FROM turn_journal_object_quarantine").all()).toEqual([{hash:bad}]); + expect(() => ledger.openRead(bad), "JOURNAL_QUARANTINE_DENIES_RESTORE").toThrow("quarantined"); + const lease = ledger.openRead(good); + expect(objects.read(good, 6), "JOURNAL_UNRELATED_VERSION_RESTORES").toEqual(Buffer.from("Athena")); ledger.releaseRead(lease); + expect(db.query("SELECT bytes,state FROM turn_journal_objects WHERE hash=?").get(bad), "JOURNAL_QUARANTINE_BYTES_STAY_CHARGED").toEqual({bytes:8,state:"present"}); + ledger.write(() => { + db.query("UPDATE turn_journal_turns SET ended_at=NULL,state='recording',pid=?,pid_start=? WHERE turn_id='penelope'").run(process.pid,"live"); + db.query("INSERT INTO turn_journal_reservations (id,bytes,pid,pid_start,created_at,hash) VALUES (?,8,?,'gone',0,?)").run(crypto.randomUUID(),process.pid,bad); + }); + ledger.recover(objects); + expect(db.query("SELECT state FROM turn_journal_turns WHERE turn_id='penelope'").get(), "QUARANTINE_PRESERVES_OPEN_TURN_LIFECYCLE").toEqual({state:"recording"}); + expect(db.query("SELECT count(*) AS n FROM turn_journal_object_quarantine").get()).toEqual({n:1}); + } finally { objects.close(); db.close(); rmSync(root, {recursive:true,force:true}); } +}); + + +for (const operation of ["has", "verify"] as const) for (const code of ["EMFILE", "EIO", "EACCES"]) test(`journal recovery retries unresolved ${operation} ${code} without inventing corruption`, async () => { + const root = mkdtempSync(join(tmpdir(), "journal-unresolved-")), path = join(root,"ui.db"); + const db = createUiDb(path), ledger = createJournalAccounting(db,path), objects = createJournalObjects(join(root,"objects"),ledger); + try { + const hash = await objects.putBytes(Buffer.from("Odysseus")); + ledger.write(() => { + db.query("UPDATE turn_journal_objects SET state='pending' WHERE hash=?").run(hash); + db.query("INSERT INTO turn_journal_reservations (id,bytes,pid,pid_start,created_at,hash) VALUES (?,8,?,'gone',0,?)").run(crypto.randomUUID(),process.pid,hash); + }); + const before = ledger.usage(); + expect(() => ledger.recover({...objects,[operation]() { throw Object.assign(new Error(code),{code}); }})).not.toThrow(); + expect(db.query("SELECT hash FROM turn_journal_object_quarantine").all(), "JOURNAL_IO_ERROR_IS_NOT_CORRUPTION").toEqual([]); + expect(db.query("SELECT state FROM turn_journal_objects WHERE hash=?").get(hash)).toEqual({state:"pending"}); + expect(db.query("SELECT bytes FROM turn_journal_reservations").all(), "JOURNAL_UNRESOLVED_CHARGE_RETAINED").toEqual([{bytes:8}]); + expect(ledger.usage()).toBe(before); + ledger.recover(objects); + expect(db.query("SELECT * FROM turn_journal_reservations").all()).toEqual([]); + expect(db.query("SELECT state FROM turn_journal_objects WHERE hash=?").get(hash)).toEqual({state:"present"}); + } finally { objects.close(); db.close(); rmSync(root,{recursive:true,force:true}); } +}); diff --git a/packages/ui-server/tests/journal-database.test.ts b/packages/ui-server/tests/journal-database.test.ts index c473eaec4f..e8bc232b25 100644 --- a/packages/ui-server/tests/journal-database.test.ts +++ b/packages/ui-server/tests/journal-database.test.ts @@ -226,9 +226,11 @@ test("the derived journal index name cannot hide an incompatible backup schema", test("migrations after the split keep the journal file and the UI database apart", () => { const migrations = join(import.meta.dir, "../migrations"); for (const file of readdirSync(migrations).filter(name => name.endsWith(".sql") && name.slice(0, 3) > JOURNAL_SPLIT_MIGRATION)) { - // Comments are not statements, and a trigger's `UPDATE [OF columns] ON t` - // event names only the table after ON. + // Comments are not statements, a trigger's `UPDATE [OF columns] ON t` + // event names only the table after ON, and a foreign key's + // `ON DELETE|UPDATE ` names no object at all. const sql = readFileSync(join(migrations, file), "utf8").replace(/--[^\n]*/g, "") + .replace(/\bON\s+(?:DELETE|UPDATE)\s+(?:CASCADE|RESTRICT|NO\s+ACTION|SET\s+NULL|SET\s+DEFAULT)\b/gi, "") .replace(/\bUPDATE\s+(?:OF\s+\w+(?:\s*,\s*\w+)*\s+)?(?=ON\s)/gi, ""); const named = [...sql.matchAll(/\b(?:TABLE|INTO|UPDATE|FROM|ON|INDEX|TRIGGER|REFERENCES)\s+(?:IF (?:NOT )?EXISTS\s+)?(?:\w+\.)?"?(\w+)"?/gi)].map(match => match[1]!); // A journal migration commits with its receipt only if it touches the journal file alone: diff --git a/packages/ui-server/tests/journal-index-purge.test.ts b/packages/ui-server/tests/journal-index-purge.test.ts index be5aba465f..9f95ff6515 100644 --- a/packages/ui-server/tests/journal-index-purge.test.ts +++ b/packages/ui-server/tests/journal-index-purge.test.ts @@ -113,6 +113,7 @@ test("journal open purges the index bytes earlier releases retained, keeping the const f = fixture(); try { await seedLegacyHistory(f); + f.raw(db => db.query("INSERT INTO turn_journal_object_quarantine VALUES (?,0,'Error','Odysseus interrupted publication','fixture')").run(INDEX_HASHES[0]!)); const before = f.raw(dump); expect(INDEX_HASHES.every(hash => f.files().has(hash)), "LEGACY_INDEX_OBJECTS_RETAINED_BEFORE_PURGE").toBe(true); const accountedBefore = f.raw(objectBytes); @@ -128,6 +129,7 @@ test("journal open purges the index bytes earlier releases retained, keeping the } expect(accountedBefore - objectBytes(f.db), "PURGE_RECLAIMS_ACCOUNTED_BYTES").toBe(INDEX_BYTES); expect(after.state, "PURGE_COMPLETE").toBe(2); + expect(f.db.query("SELECT hash FROM turn_journal_object_quarantine").all(), "PURGE_REMOVES_QUARANTINE_WITH_FOREIGN_KEYS_DISABLED").toEqual([]); // Every index row stays, with its size evidence, as the metadata-only entry history already showed. const index = after.changes.filter(row => indexPaths.has((row as { path: string }).path)) as { path: string; sequence: number; before_json: string | null; after_json: string }[]; diff --git a/packages/ui-server/tests/software-status.test.ts b/packages/ui-server/tests/software-status.test.ts index e8a00f4a92..f1ff54c33c 100644 --- a/packages/ui-server/tests/software-status.test.ts +++ b/packages/ui-server/tests/software-status.test.ts @@ -1,4 +1,4 @@ -import { expect, test } from "bun:test"; +import { expect, spyOn, test } from "bun:test"; import type { SystemStatus } from "@schlessera/brain-ui-sdk/protocol"; import { version } from "@schlessera/brain-ui-server/package.json"; import { createTestApp } from "./helpers/test-app"; @@ -33,3 +33,28 @@ test("the status envelope carries the typed SystemStatus software object", async expect(typeof body.activeSession).toBe("boolean"); } finally { await t.teardown(); } }); + + +test.each([0, 4096, null])("mounted authenticated status exposes native quarantine with charge %s while public health stays minimal", async stagingChargedBytes => { + const fixtures = await import("./helpers/native-journal-fixture.js"); + const create = fixtures.createNativeJournalFixture; + const recovery = {quarantinedIntents:1,stagingChargedBytes,diagnosticsPath:"/native-fixture/recovery-diagnostics"}; + const fault = spyOn(fixtures,"createNativeJournalFixture").mockImplementation((...args) => { + const fixture = create(...args), ready = fixture.client.ready; + fixture.client.ready = async () => ({...await ready(),recovery}); + return fixture; + }); + const t = await createTestApp({env:{AUTH_MODE:"password",BRAIN_UI_PASSWORD_HASH:await Bun.password.hash("Odysseus"),COOKIE_SECRET:"odysseus-cookie-secret-1792000000000000"}}).finally(() => fault.mockRestore()); + try { + expect((await t.fetch("/api/status")).status, "NATIVE_DIAGNOSTICS_REQUIRE_AUTH").toBe(401); + const login = await t.fetch("/api/auth/login",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({password:"Odysseus"})}); + expect(login.status).toBe(200); + const cookie = login.headers.get("set-cookie")!.split(";")[0]!; + const status = await t.fetch("/api/status",{headers:{cookie}}); + expect(status.status).toBe(200); + const body = await status.json(); + expect(body.nativeRecovery, "NATIVE_QUARANTINE_VISIBLE_TO_OWNER").toEqual(recovery); + expect(body.healthy, "NATIVE_UNBOUNDED_QUARANTINE_IS_UNHEALTHY").toBe(stagingChargedBytes !== null); + expect(Object.keys(await (await t.fetch("/api/health")).json()).sort()).toEqual(["status","timestamp","uptime"]); + } finally { await t.teardown(); } +}); diff --git a/packages/ui-server/tests/turn-journal.test.ts b/packages/ui-server/tests/turn-journal.test.ts index e6335ea34c..7e578168f2 100644 --- a/packages/ui-server/tests/turn-journal.test.ts +++ b/packages/ui-server/tests/turn-journal.test.ts @@ -727,6 +727,61 @@ test("native capture excludes an alternate trusted index identity without a publ } finally { await capture.close(); await f.close(); } }); +test("journal startup quarantines one corrupt object and preserves unrelated history", async () => { + const f = fixture(); + let reopened: ReturnType | undefined; + try { + await f.begin("odysseus-corrupt"); + writeFileSync(join(f.brain, "notes/odysseus.md"), "# New voyage\n"); + await f.journal.finish("odysseus-corrupt"); + await f.begin("athena-healthy"); + writeFileSync(join(f.brain, "notes/athena.md"), "# Guidance\n"); + await f.journal.finish("athena-healthy"); + const before = f.journal.details("ithaca", "odysseus-corrupt")!.changes.find(change => change.path === "notes/odysseus.md")!.before!; + await f.journal.close(); + // Reproduce an interrupted publisher on an existing retained object. + const {createJournalAccounting} = await import("../src/brain/journal-accounting.js"); + const accounting = createJournalAccounting(f.db, join(f.root, "ui.db")); + accounting.write(() => f.db.query("INSERT INTO turn_journal_reservations (id,bytes,pid,pid_start,created_at,hash) VALUES (?,?,?,'gone',0,?)") + .run(crypto.randomUUID(), before.bytes, process.pid, before.hash!)); + accounting.write(() => f.db.query("UPDATE turn_journal_turns SET ended_at=NULL,state='recording',pid=?,pid_start='gone' WHERE turn_id='odysseus-corrupt'").run(process.pid)); + writeFileSync(join(f.root, "objects", before.hash!), Buffer.alloc(before.bytes)); + reopened = createTurnJournal(f.db, {nativeManager:f.native.manager,brainPath:f.brain,dbPath:join(f.root,"ui.db"),objectsRoot:join(f.root,"objects")}); + await reopened.ready; + expect(reopened.summary("odysseus-corrupt").state, "JOURNAL_READY_AFTER_CORRUPT_PUBLICATION").toBe("partial"); + expect(reopened.details("ithaca", "odysseus-corrupt")!.missing).toContainEqual({path:"notes/odysseus.md",reason:"retained_object_corrupt"}); + expect(reopened.hasRetainedVersion("odysseus-corrupt", before)).toBe(false); + const other = reopened.details("ithaca", "athena-healthy")!; + expect(other.summary.state, "JOURNAL_OTHER_HISTORY_STAYS_COMPLETE").toBe("complete"); + expect(reopened.hasRetainedVersion("athena-healthy", other.changes.find(change => change.path === "notes/athena.md")!.after!)).toBe(true); + const stopped: Error[] = []; + for (const id of ["telemachus-active", "penelope-active"]) await reopened.begin(id, + {sessionId:"ithaca",actor:"interactive",model:null,profile:"governed",policyHash:null}, error => stopped.push(error)); + writeFileSync(join(f.brain, "notes/odysseus.md"), "# Ithaca\r\n"); + writeFileSync(join(f.brain, "notes/athena.md"), "# More guidance\n"); + const observed = await reopened.finish("telemachus-active").then(() => null, error => error); + expect(stopped, "JOURNAL_RECAPTURE_DOES_NOT_STOP_OTHER_ACTIVE_TURNS").toEqual([]); + expect(observed, "JOURNAL_QUARANTINE_RECAPTURE_COMPLETES_OBSERVATION").toBeNull(); + await reopened.finish("penelope-active"); + expect(reopened.details("ithaca", "penelope-active")!.missing.find(item => item.path === "notes/odysseus.md")).toMatchObject({reason:"retained_object_corrupt"}); + const healthy = reopened.details("ithaca", "penelope-active")!.changes.find(change => change.path === "notes/athena.md")!; + expect(reopened.version("ithaca", "penelope-active", healthy.sequence, "after")!.bytes(100)).toEqual(Buffer.from("# More guidance\n")); + expect(reopened.hasRetainedVersion("odysseus-corrupt", before), "JOURNAL_OLD_GAP_NEVER_CLEARS").toBe(false); + } finally { await reopened?.close(); await f.close(); } +}); + + +test("a quarantine gap added by recovery preserves an open turn until normal completion", async () => { + const f = fixture(); + try { + await f.begin("odysseus-live"); + await f.journal.writeOperation([journalStatement("UPDATE turn_journal_turns SET missing=? WHERE turn_id='odysseus-live'",JSON.stringify([{path:"notes/odysseus.md",reason:"retained_object_corrupt"}]))]); + expect(f.journal.summary("odysseus-live").state).toBe("recording"); + await f.journal.finish("odysseus-live"); + expect(f.journal.summary("odysseus-live").state,"JOURNAL_FINISH_PRESERVES_RECOVERY_GAP").toBe("partial"); + expect(f.journal.details("ithaca","odysseus-live")!.missing).toContainEqual({path:"notes/odysseus.md",reason:"retained_object_corrupt"}); + } finally { await f.close(); } +}); test("idle checkpoint cleanup records its cause durably before any turn exists and exposes authenticated status", async () => { const f = fixture(); diff --git a/packages/ui-server/tests/writer-gate.test.ts b/packages/ui-server/tests/writer-gate.test.ts index 9dc566a345..5b0cb1bb5a 100644 --- a/packages/ui-server/tests/writer-gate.test.ts +++ b/packages/ui-server/tests/writer-gate.test.ts @@ -5,7 +5,7 @@ * The server and the cron runner are separate processes, so it lives in the * UI database: two handles on one file stand in for the two processes. */ -import { afterEach, describe, expect, test } from "bun:test"; +import { afterEach, describe, expect, spyOn, test } from "bun:test"; import { mkdtempSync, mkdirSync, writeFileSync, realpathSync, rmSync, symlinkSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -442,3 +442,57 @@ describe("unpinned host writer provenance", () => { } finally { w.close(); } }); }); + +for (const operation of ["release", "dequeue"] as const) test(`a failed writer-gate ${operation} retries without restarting`, async () => { + const w = world(); + const query = w.db.query.bind(w.db); + let attempts = 0; + const sql = operation === "release" ? "DELETE FROM writer_gate WHERE id = ?" : "DELETE FROM writer_gate_turn_waiters WHERE id = ?"; + const fault = spyOn(w.db, "query").mockImplementation(((text: string) => { + if (text === sql && attempts++ === 0) throw new Error("Odysseus transient DELETE failure"); + return query(text); + }) as typeof w.db.query); + try { + if (operation === "release") { + const hold = await w.server.acquire("exclusive", "user revert"); + await hold.release(); + } else { + const held = await w.server.acquire("shared", "active turn"); + const abort = new AbortController(); + const waiting = w.server.acquire("exclusive", "user revert", { queueTurns: true, signal: abort.signal }).catch(error => error); + await settle(); abort.abort(new Error("Odysseus cancelled")); + const error = await waiting; + expect(String(error)).toContain("Odysseus cancelled"); + await held.release(); + } + expect(attempts, "GATE_FAILED_DELETE_RETRIED").toBeGreaterThanOrEqual(2); + const causes = w.db.query("SELECT payload,at FROM governance_events WHERE kind='roadblock'").all() as {payload:string;at:number}[]; + expect(causes, "GATE_CLEANUP_CAUSE_IS_DURABLE").toHaveLength(1); + expect(JSON.parse(causes[0]!.payload)).toMatchObject({family:"writer_gate_cleanup",failures:[{signature:"Error: Odysseus transient DELETE failure"}]}); + expect(JSON.parse(causes[0]!.payload).signature).toStartWith(operation + ":"); + expect(causes[0]!.at).toBeGreaterThan(0); + const next = await w.server.acquire("shared", "next turn", { turn: true, signal: AbortSignal.timeout(1000) }); + await next.release(); + expect(w.server.holders()).toEqual([]); + expect(w.db.query("SELECT * FROM writer_gate_turn_waiters").all()).toEqual([]); + } finally { fault.mockRestore(); w.close(); } +}); + + +test("a failed gate diagnostic never prevents release or the next writer", async () => { + const w = world(), query = w.db.query.bind(w.db); + let attempts = 0; + const fault = spyOn(w.db,"query").mockImplementation(((sql: string) => { + if (sql === "DELETE FROM writer_gate WHERE id = ?" && attempts++ === 0) throw Error("Odysseus transient DELETE failure"); + if (sql.includes("INSERT") && sql.includes("governance_events")) throw Error("Odysseus diagnostic unavailable"); + return query(sql); + }) as typeof w.db.query); + let release: Promise | undefined; + try { + const hold = await w.server.acquire("exclusive","user revert"); + release = Promise.resolve(hold.release()); + const next = await w.cron.acquire("shared","healthy turn",{signal:AbortSignal.timeout(300)}); + expect(attempts, "GATE_DIAGNOSTICS_DO_NOT_BLOCK_DELETE").toBeGreaterThanOrEqual(2); + await release; await next.release(); + } finally { fault.mockRestore(); await release; await w.server.settled(); w.close(); } +}); diff --git a/scripts/native-proof/recovery-inventory.ts b/scripts/native-proof/recovery-inventory.ts index 7b028695f4..06e256f3f3 100644 --- a/scripts/native-proof/recovery-inventory.ts +++ b/scripts/native-proof/recovery-inventory.ts @@ -77,15 +77,20 @@ export async function proveRecoveryInventory(artifacts: string): Promise { let manager = await createNativeBrainManager(config); const remember = NativeRecoveryIndex.prototype.remember; // A real SQLite write failure AFTER the production JSON rename/fsync. - // Reading the surviving JSON is not a substitute for the restart below. + // The same live manager must rebuild and admit the next checkpoint. const failedWrite = spyOn(NativeRecoveryIndex.prototype, "remember").mockImplementation(function(this: NativeRecoveryIndex, value: string) { if (value === failedId) (this as unknown as { db: Database }).db.exec("PRAGMA query_only = ON"); return remember.call(this, value); }); try { - await expect(manager.run({ operation: "release", id: failedId }), "NATIVE_RECOVERY_INTERRUPTED_INDEX_OUTCOME_UNKNOWN").rejects.toThrow("indexing failed"); + expect(await (await manager.run({ operation: "release", id: failedId })).json(), "NATIVE_RECOVERY_FAILED_WRITE_REBUILDS_IN_PLACE").toEqual({id:failedId,state:"deleted"}); expect(JSON.parse(fs.readFileSync(join(state, `${failedId}.json`), "utf8")).state).toBe("deleted"); - await expect(manager.run({ operation: "listRecovery", after: id(100000) }), "NATIVE_RECOVERY_POISONED_INDEX_REFUSES_PARTIAL_PAGE").rejects.toThrow("restart"); + const page = await (await manager.run({ operation: "listRecovery", after: id(100000) })).json() as {records:{id:string}[]}; + expect(page.records.some(record => record.id === failedId), "NATIVE_RECOVERY_REBUILD_INCLUDES_DURABLE_INTENT").toBe(true); + const nextId = id(100003); + const next = await (await manager.run({ operation: "checkpoint", id: nextId })).json() as {id:string}; + expect(next.id, "NATIVE_RECOVERY_NEXT_CHECKPOINT_WORKS").toBe(nextId); + await manager.run({operation:"release",id:nextId}); } finally { failedWrite.mockRestore(); await manager.close(); } manager = await createNativeBrainManager(config); try { @@ -112,4 +117,59 @@ export async function proveRecoveryInventory(artifacts: string): Promise { const page = await (await manager.run({ operation: "listRecovery", after: id(100000) })).json() as { records: { id: string; state: string }[] }; expect(page.records.filter(row => [failedId, lostId].includes(row.id))).toEqual([{ id: failedId, state: "deleted" }, { id: lostId, state: "deleted" }]); } finally { await manager.close(); } + + const malformedId = id(100004), healthyId = id(100005), historicalId = id(100007); + manager = await createNativeBrainManager(config); + try { await manager.run({operation:"checkpoint",id:historicalId}); } finally { await manager.close(); } + fs.writeFileSync(join(state, `${malformedId}.json`), "{malformed", {mode:0o600}); + manager = await createNativeBrainManager({...config, appUid:1000, stageAllowanceBytes:4096, stageBudgetBytes:4096}); + try { + const ready = await (await manager.run({operation:"ready"})).json() as {recovery:{quarantinedIntents:number;stagingChargedBytes:number;diagnosticsPath:string}}; + + expect(fs.readdirSync(ready.recovery.diagnosticsPath).length).toBeGreaterThan(0); + const healthy = await (await manager.run({operation:"checkpoint",id:healthyId})).json() as {id:string}; + expect(healthy.id, "NATIVE_MALFORMED_INTENT_OTHER_CHECKPOINT_WORKS").toBe(healthyId); + await expect(manager.run({operation:"checkpoint",id:malformedId}), "NATIVE_QUARANTINE_ID_CANNOT_BE_REUSED").rejects.toThrow("quarantined"); + const stage = await (await manager.run({operation:"prepareStage",id:id(100006),checkpointId:healthyId,allowanceBytes:4096})).json() as {id:string}; + expect(stage.id, "NATIVE_MALFORMED_INTENT_HEALTHY_STAGE_PREPARES").toBe(id(100006)); + expect(ready.recovery, "NATIVE_ABSENT_STAGE_HAS_NO_STORAGE_CHARGE").toMatchObject({quarantinedIntents:1,stagingChargedBytes:0}); + await expect(manager.run({operation:"prepareStage",id:id(100008),checkpointId:healthyId,allowanceBytes:4096}), "NATIVE_ACTIVE_STAGE_CHARGE_REMAINS_RESERVED").rejects.toThrow("budget"); + await manager.run({operation:"releaseStage",id:stage.id}); + await expect(manager.run({operation:"release",id:historicalId}), "NATIVE_UNKNOWN_STAGE_DEPENDENCIES_NOT_RELEASED").rejects.toThrow("dependencies"); + expect(await (await manager.run({operation:"release",id:healthyId})).json(), "NATIVE_QUARANTINE_NEW_CHECKPOINT_RELEASES").toEqual({id:healthyId,state:"deleted"}); + expect(fs.readFileSync(join(state, `${malformedId}.json`), "utf8")).toBe("{malformed"); + } finally { await manager.close(); } + // The independent cap is written by actual stage creation, and survives an + // unreadable intent plus a smaller configured allowance on the next boot. + const boundedId = id(100011), boundedPath = join("/brain-fixture/.brain-native/stages", boundedId); + manager = await createNativeBrainManager({...config,appUid:1000,stageAllowanceBytes:8192,stageBudgetBytes:8192}); + try { await manager.run({operation:"prepareStage",id:boundedId,checkpointId:historicalId,allowanceBytes:8192}); } + finally { await manager.close(); } + fs.writeFileSync(join(state, `${boundedId}.json`), "{broken", {mode:0o600}); + manager = await createNativeBrainManager({...config,appUid:1000,stageAllowanceBytes:4096,stageBudgetBytes:12288}); + try { + const ready = await (await manager.run({operation:"ready"})).json() as {recovery:{stagingChargedBytes:number}}; + expect(ready.recovery.stagingChargedBytes,"NATIVE_QUARANTINE_RETAINS_REAL_TMPFS_CAP").toBe(8192); + await manager.run({operation:"prepareStage",id:id(100012),checkpointId:historicalId,allowanceBytes:4096}); + await expect(manager.run({operation:"prepareStage",id:id(100013),checkpointId:historicalId,allowanceBytes:4096}), + "NATIVE_QUARANTINE_CHARGE_REMAINS_RESERVED").rejects.toMatchObject({code:"capacity"}); + await manager.run({operation:"releaseStage",id:id(100012)}); + } finally { + await manager.close(); fs.rmdirSync(boundedPath); fs.unlinkSync(`${boundedPath}.allowance`); fs.unlinkSync(join(state, `${boundedId}.json`)); + } + // An old namespace placeholder may outlive changed configuration. Never + // replace an unknown historical allowance with today's smaller limit. + const uncertainStage = join("/brain-fixture/.brain-native/stages", malformedId); + fs.mkdirSync(uncertainStage,{mode:0o700}); + manager = await createNativeBrainManager({...config,appUid:1000,stageAllowanceBytes:4096,stageBudgetBytes:8192}); + try { + const ready = await (await manager.run({operation:"ready"})).json() as {recovery:{stagingChargedBytes:number|null}}; + expect(ready.recovery.stagingChargedBytes,"NATIVE_UNKNOWN_HISTORICAL_STAGE_BOUND_STAYS_UNKNOWN").toBeNull(); + const nextId = id(100009); + await manager.run({operation:"checkpoint",id:nextId}); + await expect(manager.run({operation:"prepareStage",id:id(100010),checkpointId:nextId,allowanceBytes:4096}),"NATIVE_UNKNOWN_STAGE_CAPACITY_NOT_RELEASED").rejects.toMatchObject({code:"unknown",message:expect.stringContaining("recovery")}); + await manager.run({operation:"release",id:nextId}); + } finally { await manager.close(); fs.rmdirSync(uncertainStage); fs.unlinkSync(join(state, `${malformedId}.json`)); } + manager = await createNativeBrainManager(config); + try { await manager.run({operation:"release",id:historicalId}); } finally { await manager.close(); } } diff --git a/scripts/native-proof/reference-pool.native.ts b/scripts/native-proof/reference-pool.native.ts index 425f92a1f0..f6fb7d8f29 100644 --- a/scripts/native-proof/reference-pool.native.ts +++ b/scripts/native-proof/reference-pool.native.ts @@ -1,5 +1,5 @@ /** Real reference-pool qualification on owned Btrfs loop volumes (#2428). Runs only inside reference-pool-fixture.py. */ -import { expect } from "bun:test"; +import { expect, spyOn } from "bun:test"; import { closeSync, existsSync, linkSync, mkdirSync, openSync, readdirSync, readFileSync, readlinkSync, rmSync, statSync, truncateSync, unlinkSync, writeFileSync, writeSync, chmodSync, renameSync } from "node:fs"; import { join } from "node:path"; import { randomBytes, randomUUID } from "node:crypto"; @@ -9,6 +9,8 @@ import { reservePhysical } from "../../packages/ui-sdk/src/server/native-referen import type { NativePoolRecord, NativePoolStatus } from "../../packages/ui-sdk/src/server/native-brain-manager-protocol.js"; import { createFixtureWorktrees } from "./reference-worktree-allocation.js"; +import { NativeRecoveryIndex } from "../../packages/ui-sdk/src/server/native-recovery-index.js"; +import type { Database } from "bun:sqlite"; import { settledWorktreeRelease } from "./reference-worktree-release.js"; const MIB = 1024 ** 2, POOL = "/reference-pool", ARTIFACTS = process.env.BRAIN_REFERENCE_POOL_ARTIFACTS ?? "/proof"; @@ -63,6 +65,23 @@ function bounded(name: string, before: NonNullable({operation:"poolCheckpoint",id:randomUUID(),from:source.id}); + expect(checkpoint.state, "POOL_RECOVERY_INDEX_NEXT_CHECKPOINT_WORKS").toBe("sealed"); + await release(checkpoint.id); await release(source.id); + } finally { fault.mockRestore(); } +} + // 1. Qualification and baseline. const first = await status(); note("qualified", { status: first });