From 036723d6a1e696af04c1958b1c42404d6cf6a281 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 15 Nov 2026 20:53:03 +0000 Subject: [PATCH 1/4] CONTRACT: feat(ui-sdk,ui-server): place a turn's data tree on the managed volume by reflink (#2911) A strict, voice or autonomous turn on managed native storage now gets its data tree from the native manager: an app-owned directory in the manager's private trees/ area, outside the live brain and every checkpoint, filled with COPYFILE_FICLONE_FORCE so it shares the checkpoint's extents. A copy that cannot share extents fails the turn instead of copying in full. The manager charges each tree's allowance (metadata, twice the seeded index, the 64 MiB effect bound) against the volume's free space with one emergency reserve of headroom, records it as a kind "tree" intent with an independent allowance record, refuses to remove a tree any process still mounts, removes it with a descriptor-relative walk and credits the charge only after an observed filesystem commit. The lease owner records tree leases before each request and recovers dead owners' trees. Contract: the native manager client and lease owner gain prepareTurnTree and releaseTurnTree; NativeRecoveryRecord.kind gains "tree" and an optional treeRequest (package-api.md, integration-contract.md). Co-Authored-By: Claude Opus 5.5 --- .changeset/2911-managed-turn-trees.md | 6 + api-report/ui-sdk.txt | 2 + api-report/ui-server.txt | 16 +- docs/decisions/governed-writable-workers.md | 19 ++ docs/decisions/native-brain-storage.md | 70 ++++++ docs/integration-contract.md | 9 + docs/integration-contract/package-api.md | 29 +++ packages/ui-sdk/src/internal.ts | 4 +- .../src/server/native-brain-manager-client.ts | 6 +- .../server/native-brain-manager-protocol.ts | 22 +- .../ui-sdk/src/server/native-brain-manager.ts | 181 ++++++++++--- .../ui-sdk/src/server/native-turn-trees.ts | 48 ++++ .../ui-sdk/src/server/worker-startup-view.ts | 17 +- .../tests/native-manager-turn-trees.test.ts | 238 ++++++++++++++++++ .../src/brain/native-brain-leases.ts | 27 +- .../ui-server/src/brain/native-lease-store.ts | 11 +- .../ui-server/src/brain/turn-data-tree.ts | 180 ++++++++++--- .../tests/helpers/native-journal-fixture.ts | 2 + .../tests/native-brain-leases.test.ts | 70 ++++++ .../tests/turn-data-tree-placement.test.ts | 118 +++++++++ 20 files changed, 988 insertions(+), 87 deletions(-) create mode 100644 .changeset/2911-managed-turn-trees.md create mode 100644 packages/ui-sdk/src/server/native-turn-trees.ts create mode 100644 packages/ui-sdk/tests/native-manager-turn-trees.test.ts create mode 100644 packages/ui-server/tests/turn-data-tree-placement.test.ts diff --git a/.changeset/2911-managed-turn-trees.md b/.changeset/2911-managed-turn-trees.md new file mode 100644 index 0000000000..68ef4ddc5a --- /dev/null +++ b/.changeset/2911-managed-turn-trees.md @@ -0,0 +1,6 @@ +--- +"@schlessera/brain-ui-sdk": minor +"@schlessera/brain-ui-server": minor +--- + +Keep a turn's data tree on the managed native volume. A strict, voice or autonomous turn on managed storage now gets its data tree from the native manager, in an app-owned directory beside the live brain, and fills it by reflinks from its checkpoint, so concurrent turns no longer each hold a full copy of the documents and index. A copy that cannot share extents fails the turn instead of copying in full. The native manager client and lease owner gain `prepareTurnTree` and `releaseTurnTree`. The manager charges each tree's allowance against the volume, keeps one emergency reserve of headroom, refuses to remove a tree a worker still mounts, and credits the space only after the filesystem has reclaimed it. A turn's committed changes may write at most 64 MiB into its tree. diff --git a/api-report/ui-sdk.txt b/api-report/ui-sdk.txt index e5c0f781ed..8a18445020 100644 --- a/api-report/ui-sdk.txt +++ b/api-report/ui-sdk.txt @@ -1300,6 +1300,7 @@ export "./internal" (./src/internal.ts) type NativePoolRecord type NativePoolState type NativePoolStatus + type NativeTurnTree ORIENTATION_MAX_BYTES OUTWARD_VOICE_REFUSAL type ObservedWorkerFile @@ -1427,6 +1428,7 @@ export "./internal" (./src/internal.ts) mountPointsUnder nativeFileVersion nativeObservationIdentity + nativeTurnTreeManager nativeWorkerStartupInput observeClassification observeOutwardPlan diff --git a/api-report/ui-server.txt b/api-report/ui-server.txt index 4d2f8993af..394e0ac1bf 100644 --- a/api-report/ui-server.txt +++ b/api-report/ui-server.txt @@ -1714,13 +1714,16 @@ signatures (every public export and the types it is made of) id: string; state: "creating" | "sealed" | "deleting" | "deleted"; checkpoint?: NativeCheckpoint; - kind?: "stage"; + kind?: "stage" | "tree"; stage?: NativeStage; stageRequest?: { checkpointId: string; checkpointUuid: string; allowanceBytes: number; }; + treeRequest?: { + allowanceBytes: number; + }; } NativeStage (packages/ui-sdk/src/server/native-brain-manager-protocol.ts) export interface NativeStage { @@ -1749,6 +1752,12 @@ signatures (every public export and the types it is made of) changes: AsyncIterable; completed: NativeDeltaStream["completed"]; } + NativeTurnTree (packages/ui-sdk/src/server/native-brain-manager-protocol.ts) + export interface NativeTurnTree { + id: string; + path: string; + allowanceBytes: number; + } Observability (packages/ui-server/src/observability/index.ts) export interface Observability { logger(scope: string): Logger; @@ -2508,6 +2517,7 @@ signatures (every public export and the types it is made of) }>; poolWithdraw: (id: string, signal?: AbortSignal) => Promise; prepareStage: (id: string, checkpointId: string, allowanceBytes: number, signal?: AbortSignal) => Promise; + prepareTurnTree: (id: string, allowanceBytes: number, signal?: AbortSignal) => Promise; readCheckpoint: (id: string, path: string, maximum: number, expectedWorkerUid: number, signal?: AbortSignal) => Promise; readStage: (id: string, path: string, maximum: number, expectedWorkerUid: number, signal?: AbortSignal) => Promise; ready: (signal?: AbortSignal) => Promise; @@ -2519,6 +2529,10 @@ signatures (every public export and the types it is made of) id: string; state: "deleted"; }>; + releaseTurnTree: (id: string, signal?: AbortSignal) => Promise<{ + id: string; + state: "deleted"; + }>; statCheckpoint: (id: string, path: string, expectedWorkerUid: number, signal?: AbortSignal) => Promise; statStage: (id: string, path: string, expectedWorkerUid: number, signal?: AbortSignal) => Promise; }; diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index 4c627403c0..0d16e8a0d6 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -949,6 +949,25 @@ configuration still loads from the frozen view at the brain path. readers that require one link (`checkGovernancePolicy`, the embedding policy, storage-attachment facts) and cannot cross subvolumes. The tree still holds one copy per concurrent turn on the temporary directory. +- **On managed storage the tree shares the checkpoint's extents (#2911).** + The maintainer's ruling of 2026-10-25 on + [#2911](https://github.com/schlessera/brain-kit/issues/2911) supplies the + manager-provisioned location the bullet above lacked. A view the native + manager acquired gets its tree from that manager: an app-owned directory in + the manager's private `trees/` area on the same volume, outside the live + brain and every checkpoint, with the documents in `data/` and an unmasked + turn's index in `index/`. Admission still plans and pools the copy, but + requires a reflink (`COPYFILE_FICLONE_FORCE`): a file that cannot share the + checkpoint's extents fails the turn instead of being copied in full. The + worker still receives only its own tree, read-only at the fixed path; the + manager's area is masked in every worker, so it cannot reach a peer's tree. + The tree's committed effects are bounded (`TURN_TREE_EFFECT_BYTES`, 64 MiB): + past it the tree stops recording and the turn's index reads refuse. At the + turn's end the server asks the manager to remove the tree, which it does + only once no process mounts it. A masked turn's private index stays on the + server's temporary directory, as do trees for views no manager acquired. + Ownership, capacity and recovery are in the + [native storage decision](native-brain-storage.md#turn-data-trees-on-the-managed-volume-2911). - **Committed bytes enter the tree inside the commit boundary.** Each application hands the tree its committed effects with the live base each one replaced, partial staged failures included; an archive writes the diff --git a/docs/decisions/native-brain-storage.md b/docs/decisions/native-brain-storage.md index 64c607dfb7..14aebbd524 100644 --- a/docs/decisions/native-brain-storage.md +++ b/docs/decisions/native-brain-storage.md @@ -194,6 +194,76 @@ workloads, complete path changes, worker restrictions, overlapping consumers, crashes, exhaustion and independent HTTP/WebSocket/cancellation measurements. Native runtime qualification precedes any production migration. +## Turn data trees on the managed volume (#2911) + +A strict, voice or autonomous turn reads a data tree copied from its startup +checkpoint ([the data-tree ruling](governed-writable-workers.md#a-turns-own-applications-reach-its-reads-maintainer-2026-10-25)). +On a temporary directory every tree is a full copy of the view's documents and +index. The maintainer's ruling on +[#2911](https://github.com/schlessera/brain-kit/issues/2911) (2026-10-25, +option A) places it on the managed volume instead, where it shares the +checkpoint's extents. + +**Placement and ownership.** The manager keeps a root-owned `trees/` +directory (`0710`, the app's group) beside `stages/` under its private root. +`prepareTurnTree` creates one directory per caller-generated identity there, +owned by the fixed app UID and group with mode `0710`; the app creates the +tree's `data/` and `index/` inside it. The directory is outside the live +subvolume, so governed peers cannot write it and no checkpoint snapshots it. +The private root is already a mandatory worker mask, so a worker reaches only +the tree the launcher binds read-only at its fixed path. The worker identity +shares the app's group and can only traverse the directory to that bind. No +request names a path, owner or mode. + +**Placement requires sharing.** The app copies with +`COPYFILE_FICLONE_FORCE`. A file that cannot be reflinked fails the turn's +admission and releases its tree; no full copy is made in its place. A managed +view whose manager cannot place a tree is refused the same way. Trees for +views no manager acquired keep the temporary-directory copy. + +**Allocation and admission.** Each tree carries a page-aligned allowance: its +admission charge for what it can newly allocate. Shared document extents are +not charged as copies. The charge counts the tree's metadata (4 KiB per +entry), twice the seeded index (every page rewritten, with its log), the +turn's bounded effects (`TURN_TREE_EFFECT_BYTES`, 64 MiB, enforced by the +tree) and 1 MiB of overhead. Admission reads the volume's free space with +`statfs`, which counts every allocation once, shared extents included. It +admits a tree only while the live trees' allowances, this one and one +emergency reserve's worth of headroom fit in that free space. It also needs +an armed reserve. A tree's own growth therefore lowers free space while its +allowance stays charged. That is conservative and never enlarges the +configured capacity. The headroom keeps trees from driving checkpoint and +intent writes onto the emergency reserve, which tree writes can never consume +directly. Qgroups stay disabled; the allowance is an admission charge, not a +kernel quota. + +**Durable records.** A tree is a `kind: "tree"` intent in the manager's +existing intent store, with its allowance also recorded beside its directory, +so an unreadable intent keeps its charge. A quarantined tree whose allowance +is unknown refuses tree admission only. Checkpoints, stages and recovery keep +working. Deleted intents fence delayed creation requests, as for stages. The +app's lease owner records each tree as a `tree` root lease before the request, +with the same owner identity as checkpoint and stage leases. + +**Release and recovery.** The owner releases a tree after its workers exit. +The manager refuses while any process's mount namespace still holds a mount +of the tree, read from every `/proc//mountinfo`. An unreadable census +refuses too. Otherwise it marks the intent `deleting`, removes the directory +with a descriptor-relative walk that follows no link, and observes a +filesystem commit. Only then does it credit the charge and record `deleted`. +A refused or interrupted release keeps the charge and the lease's `deleting` +intent. The lease owner's dead-owner recovery releases a dead owner's trees, +and any tree whose release was already intended, by the same rule. It never +removes a live owner's tree, an unrecorded directory or another identity. +Removal runs in the manager, outside the app's event loop, bounded by its +operation timeout. + +The receipts that qualify this placement are the native `--apply-timing` run +and the separate-UID identity cell. The first records each strict tree's +`btrfs filesystem du` total, exclusive and shared bytes at seed and at close +in `apply-timing.json`. The second proves a worker reads its own tree, cannot +write it, and cannot reach a peer tree or the manager's area. + ## Alternatives Watchers can provide hints, but notifications alone neither preserve overwritten diff --git a/docs/integration-contract.md b/docs/integration-contract.md index d741bf1aaa..bafcc2e400 100644 --- a/docs/integration-contract.md +++ b/docs/integration-contract.md @@ -20,6 +20,15 @@ same-commit update of the index or relevant authoritative component. How they ar The reasoning is in [decisions/contract-versioning.md](decisions/contract-versioning.md). +## Turn data trees on the managed volume (additive, 0.45.0, #2911) + +The native manager client and the lease owner gain `prepareTurnTree(id, +allowanceBytes)`, returning `NativeTurnTree` (`{ id, path, allowanceBytes }`), +and `releaseTurnTree(id)`. `NativeRecoveryRecord.kind` gains `tree`, with an +optional `treeRequest`. A strict, voice or autonomous turn on managed storage +now keeps its data tree there, filled by reflinks. Described in +[the package API](integration-contract/package-api.md#managed-turn-data-trees-additive-0450-2911). + ## The Start card's persona choice (additive, 0.45.0, #3698) In `@schlessera/brain-ui-react`, the conversation client's state adds diff --git a/docs/integration-contract/package-api.md b/docs/integration-contract/package-api.md index 260306317f..91106f8828 100644 --- a/docs/integration-contract/package-api.md +++ b/docs/integration-contract/package-api.md @@ -4203,6 +4203,35 @@ retain existing owned checkpoint authority and storage caps; they do not authorize arbitrary host paths. See the [host boundary](../hosting/agent-workers.md#separate-worker-identity) for descriptor transfer, supervision, cleanup and best-effort limits. +### Managed turn data trees (additive, 0.45.0, #2911) + +The native manager client gains two operations, and the lease owner wraps +both: + +- `prepareTurnTree(id, allowanceBytes)` returns `NativeTurnTree` + (`{ id, path, allowanceBytes }`). `id` is a caller-generated UUID and + `allowanceBytes` a positive multiple of 4096. The manager alone chooses the + path: `/.brain-native/trees/`, owned by its fixed app UID and + group with mode `0710`. It refuses with `capacity` when the live trees' + allowances, this one and one emergency reserve's worth of headroom do not + fit the volume's free space, or while the emergency reserve is consumed. A + retry with the same identity and allowance returns the same tree; a + released identity refuses with `released`. +- `releaseTurnTree(id)` returns `{ id, state: "deleted" }` once the manager has + removed the directory and observed a filesystem commit. It refuses with + `unavailable`, removing nothing, while any process still mounts the tree. An + unrecorded directory refuses with `unknown`. An unknown identity with no + directory is recorded as deleted, which fences a later create. + +`NativeRecoveryRecord.kind` gains `tree`, and records gain an optional +`treeRequest` (`{ allowanceBytes }`). Checkpoint operations refuse a tree +identity with `invalid`, and the tree operations refuse a checkpoint or stage +identity the same way. The lease owner records a `tree` root lease before each +request. It releases only its own trees, or a dead owner's during recovery, +and its lease table migrates in place. No call accepts a host path, UID or +mode. The rules are in the +[native storage decision](../decisions/native-brain-storage.md#turn-data-trees-on-the-managed-volume-2911). + ### Reference pool storage (additive, #2428) The root-owned `brain-native-store` configuration accepts an optional diff --git a/packages/ui-sdk/src/internal.ts b/packages/ui-sdk/src/internal.ts index bf964f83cf..27c3fda01c 100644 --- a/packages/ui-sdk/src/internal.ts +++ b/packages/ui-sdk/src/internal.ts @@ -44,7 +44,7 @@ export { workerHostProven, HOST_MASKS, MAINTENANCE_HOME, WORKER_PROVIDER_RELAY_D export { CREDENTIAL_FREE_ENV, prepareMaintenanceGitInput, prepareMaintenanceWorker, launchMaintenanceWorker, launchMaintenanceWorkerAsync, maintenanceLaunch, probeNativeMaintenanceWorker, runMaintenanceWorker, runMaintenanceWorkerSync } from "./server/maintenance-worker.js"; export type { MaintenanceHost, MaintenanceCommand, MaintenanceResult } from "./server/maintenance-worker.js"; export { MaintenanceTempBusyError, reserveMaintenanceTemp, type MaintenanceTempKind } from "./server/maintenance-temp-budget.js"; -export { prepareNativeWorkerStartupView, retainWorkerStartupView, nativeWorkerStartupInput, isManagedWorkerStartupView, assertManagedTurnStartupView, UNMANAGED_TURN_STORAGE, hasManagedNativeStorage } from "./server/worker-startup-view.js"; +export { prepareNativeWorkerStartupView, retainWorkerStartupView, nativeWorkerStartupInput, isManagedWorkerStartupView, nativeTurnTreeManager, assertManagedTurnStartupView, UNMANAGED_TURN_STORAGE, hasManagedNativeStorage } from "./server/worker-startup-view.js"; export type { WorkerStartupView } from "./server/worker-startup-view.js"; export function maintenanceGitEntry(): string { return Bun.resolveSync("./server/maintenance-git-entry", import.meta.dir); } export { isEnvName, protectedPaths, PROTECTED_ENV_PREFIX, PROTECTED_TIER_A, PROTECTED_TIER_B } from "./server/protected-paths.js"; @@ -75,7 +75,7 @@ export { prepareNativeWorkerOutput, type PreparedWorkerOutput, type WorkerOutput export { createNativeBrainManagerClient } from "./server/native-brain-manager-client.js"; export { NATIVE_MANAGER_OPERATION_TIMEOUT_MS, NATIVE_MANAGER_MAX_DELTA_BYTES, NativeBrainManagerError } from "./server/native-brain-manager-protocol.js"; -export type { NativePoolRecord, NativePoolStatus, NativePoolState, NativePoolCheckpoint, NativePoolAccess, NativePoolCreatePurpose } from "./server/native-brain-manager-protocol.js"; +export type { NativePoolRecord, NativePoolStatus, NativePoolState, NativePoolCheckpoint, NativePoolAccess, NativePoolCreatePurpose, NativeTurnTree } from "./server/native-brain-manager-protocol.js"; // Runtime-neutral: the pool module reaches `bun:sqlite`, which this entry's Node build must never load. export { REFERENCE_POOL_CHECKPOINT_BYTES } from "./server/native-brain-manager-protocol.js"; diff --git a/packages/ui-sdk/src/server/native-brain-manager-client.ts b/packages/ui-sdk/src/server/native-brain-manager-client.ts index b0ce8fde25..ef72185ebd 100644 --- a/packages/ui-sdk/src/server/native-brain-manager-client.ts +++ b/packages/ui-sdk/src/server/native-brain-manager-client.ts @@ -5,7 +5,7 @@ import { Readable } from "node:stream"; import { consumeNativeStageAuthority, consumeNativeCheckpointRead, nativeCheckpointReaderPath, type NativeCheckpointReadTicket } from "./native-checkpoint-reader.js"; import { nativeCheckpointId } from "./native-brain-manager-protocol.js"; import { NativeBrainManagerError, nativeManagerRequest, NATIVE_CONTROL_BYTES, NATIVE_DATA_CHUNK_BYTES, NATIVE_MANAGER_OPERATION_TIMEOUT_MS, NATIVE_MANAGER_MAX_DELTA_BYTES, - type NativeCheckpoint, type NativeManagerErrorCode, type NativeManagerReady, type NativeManagerRequest, type NativeRecoveryRecord, type NativeStage, type NativeStageChange, + type NativeCheckpoint, type NativeManagerErrorCode, type NativeManagerReady, type NativeManagerRequest, type NativeRecoveryRecord, type NativeStage, type NativeStageChange, type NativeTurnTree, type NativePoolAccess, type NativePoolCheckpoint, type NativePoolCreatePurpose, type NativePoolRecord, type NativePoolStatus } from "./native-brain-manager-protocol.js"; export interface NativeDeltaStream { @@ -254,6 +254,10 @@ export function createNativeBrainManagerClient(input: { socketPath: string; time release: async (id: string, signal?: AbortSignal): Promise<{ id: string; state: "deleted" }> => control({ operation: "release", id }, signal), prepareStage: async (id: string, checkpointId: string, allowanceBytes: number, signal?: AbortSignal): Promise => control({ operation: "prepareStage", id, checkpointId, allowanceBytes }, signal), releaseStage: async (id: string, signal?: AbortSignal): Promise<{ id: string; state: "deleted" }> => control({ operation: "releaseStage", id }, signal), + /** A turn data tree's directory on the managed volume (#2911); `allowanceBytes` is whole pages. */ + prepareTurnTree: async (id: string, allowanceBytes: number, signal?: AbortSignal): Promise => control({ operation: "prepareTurnTree", id, allowanceBytes }, signal), + /** Remove it once no worker mounts it; its charge is credited after observed reclamation. */ + releaseTurnTree: async (id: string, signal?: AbortSignal): Promise<{ id: string; state: "deleted" }> => control({ operation: "releaseTurnTree", id }, signal), inspectStage: async (id: string, signal?: AbortSignal): Promise => { const response = await call({ operation: "inspectStage", id }, signal); const checkpointId = response.headers.get("x-brain-stage-checkpoint"), checkpointUuid = response.headers.get("x-brain-stage-lower"); 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 8ab30c1229..f9d6e3a992 100644 --- a/packages/ui-sdk/src/server/native-brain-manager-protocol.ts +++ b/packages/ui-sdk/src/server/native-brain-manager-protocol.ts @@ -25,6 +25,11 @@ export const nativeManagerRequest = z.discriminatedUnion("operation", [ maximum: z.number().int().nonnegative(), }).strict(), z.object({ operation: z.literal("cancelCheckpointRead"), id: nativeCheckpointId }).strict(), + // Turn data trees (#2911): one app-owned directory per turn on the managed + // volume, outside the live brain and every checkpoint. The manager alone + // chooses its path and removes it; the allowance is its admission charge. + z.object({ operation: z.literal("prepareTurnTree"), id: nativeCheckpointId, allowanceBytes: z.number().int().positive() }).strict(), + z.object({ operation: z.literal("releaseTurnTree"), id: nativeCheckpointId }).strict(), // Reference pool (#2428). Identities are caller-generated UUIDs; the manager // alone chooses paths, qgroups and limits within its configured allowance. z.object({ operation: z.literal("poolStatus") }).strict(), @@ -93,9 +98,24 @@ export interface NativeRecoveryRecord { id: string; state: "creating" | "sealed" | "deleting" | "deleted"; checkpoint?: NativeCheckpoint; - kind?: "stage"; + kind?: "stage" | "tree"; stage?: NativeStage; stageRequest?: { checkpointId: string; checkpointUuid: string; allowanceBytes: number }; + /** A turn data tree's admission charge (#2911). */ + treeRequest?: { allowanceBytes: number }; +} +/** + * A turn's data-tree directory on the managed volume (#2911): created by the + * manager for the fixed app identity, outside the live brain and every + * checkpoint, so a copy from a checkpoint into it can share the checkpoint's + * extents. `allowanceBytes` stays charged against the volume until the + * manager has removed the directory and observed the filesystem commit. + */ +export interface NativeTurnTree { + id: string; + /** Host-created directory; never supplied by the requester. */ + path: string; + allowanceBytes: number; } export interface NativeStage { 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 121e639860..69aad8c890 100644 --- a/packages/ui-sdk/src/server/native-brain-manager.ts +++ b/packages/ui-sdk/src/server/native-brain-manager.ts @@ -7,9 +7,10 @@ import { isWithin } from "@schlessera/brain-common/internal/safe-path"; import { constants, openSync, closeSync, fsyncSync, fstatSync, writeFileSync, readFileSync, renameSync, lstatSync, statSync, mkdirSync, chmodSync, chownSync, readdirSync, realpathSync, existsSync, unlinkSync, ftruncateSync } from "node:fs"; -import { dirname, isAbsolute, join } from "node:path"; +import { dirname, isAbsolute, join, relative } from "node:path"; import { nativeCheckpointId, nativeManagerRequest, nativeManagerFrame, NativeBrainManagerError, NATIVE_CONTROL_BYTES, NATIVE_DATA_CHUNK_BYTES, NATIVE_MANAGER_OPERATION_TIMEOUT_MS, NATIVE_MANAGER_MAX_DELTA_BYTES, - type NativeCheckpoint, type NativeManagerReady, type NativeManagerRequest, type NativeRecoveryRecord } from "./native-brain-manager-protocol.js"; + type NativeCheckpoint, type NativeManagerReady, type NativeManagerRequest, type NativeRecoveryRecord, type NativeTurnTree } from "./native-brain-manager-protocol.js"; +import { NATIVE_TREE_REMOVAL, nativeTurnTreeReaders } from "./native-turn-trees.js"; import { startNativeStage } from "./native-brain-stage.js"; import { randomUUID } from "node:crypto"; import { nativeCheckpointReaderPath, startNativeCheckpointRead } from "./native-checkpoint-reader.js"; @@ -61,6 +62,8 @@ export interface NativeBrainManagerOptions { } type RootInfo = { rootId: string; uuid: string; parentUuid: string; receivedUuid: string; transaction: string; readOnly: boolean; fsid: string; devices: number }; type Intent = NativeRecoveryRecord & { version: 1; sourceUuid: string }; +/** Filesystem block every turn-tree allowance is a whole number of. */ +const PAGE = 4096; export function validateNativeBrainManagerConfig(config: NativeBrainManagerConfig): void { for (const key of ["storePath", "devicePath", "socketPath"] as const) @@ -88,10 +91,10 @@ export function validateNativeBrainManagerConfig(config: NativeBrainManagerConfi const unescapeMount = (text: string) => text.replace(/\\(040|011|012|134)/g, (_all, digits: string) => String.fromCharCode(parseInt(digits, 8))); /** No nested mount is omitted by the live root's checkpoint. */ -export function nativeStoreMount(mountinfo: string, store: string, brain: string): { options: string[]; source: string } { +export function nativeStoreMount(mountinfo: string, store: string, brain: string): { options: string[]; source: string; device: string } { const rows = mountinfo.trim().split("\n").map(line => { const [left, right] = line.split(" - "), fields = left!.split(" "), fs = right?.split(" "); - return { root: unescapeMount(fields[3] ?? ""), path: unescapeMount(fields[4] ?? ""), options: [...(fields[5] ?? "").split(","), ...(fs?.[2] ?? "").split(",")], type: fs?.[0], source: unescapeMount(fs?.[1] ?? "") }; + return { device: fields[2] ?? "", root: unescapeMount(fields[3] ?? ""), path: unescapeMount(fields[4] ?? ""), options: [...(fields[5] ?? "").split(","), ...(fs?.[2] ?? "").split(",")], type: fs?.[0], source: unescapeMount(fs?.[1] ?? "") }; }); const mounted = rows.filter(row => row.path === store); if (mounted.length !== 1 || mounted[0]!.type !== "btrfs" || mounted[0]!.root !== "/" || !mounted[0]!.options.includes("rw")) @@ -130,7 +133,7 @@ export async function createNativeBrainManager(config: NativeBrainManagerConfig, validateNativeBrainManagerConfig(config); if (process.platform !== "linux" || process.arch !== "x64" || process.geteuid?.() !== 0) throw new NativeBrainManagerError("unsupported", "Native manager requires the separately qualified trusted Linux x86-64 root service; the app and workers remain unprivileged."); - const fixed = Object.freeze({ ...config, operationTimeoutMs: config.operationTimeoutMs ?? NATIVE_MANAGER_OPERATION_TIMEOUT_MS, maxDeltaBytes: config.maxDeltaBytes ?? NATIVE_MANAGER_MAX_DELTA_BYTES }), brain = join(fixed.storePath, "brain"), privateRoot = join(fixed.storePath, ".brain-native"), state = join(privateRoot, "state"), roots = join(privateRoot, "checkpoints"), reserve = join(privateRoot, "emergency"), stages = join(privateRoot, "stages"); + const fixed = Object.freeze({ ...config, operationTimeoutMs: config.operationTimeoutMs ?? NATIVE_MANAGER_OPERATION_TIMEOUT_MS, maxDeltaBytes: config.maxDeltaBytes ?? NATIVE_MANAGER_MAX_DELTA_BYTES }), brain = join(fixed.storePath, "brain"), privateRoot = join(fixed.storePath, ".brain-native"), state = join(privateRoot, "state"), roots = join(privateRoot, "checkpoints"), reserve = join(privateRoot, "emergency"), stages = join(privateRoot, "stages"), trees = join(privateRoot, "trees"); trustedAncestors(fixed.storePath); trustedAncestors(dirname(fixed.socketPath)); if (realpathSync(fixed.storePath) !== fixed.storePath || isWithin(brain, fixed.socketPath)) throw new NativeBrainManagerError("unsupported", "Native store and socket require protected canonical paths outside the live brain."); @@ -143,6 +146,11 @@ export async function createNativeBrainManager(config: NativeBrainManagerConfig, const stageReservations = new Map(); const checkpointReaders = new Map }>(); let stagedBytes = 0; + /** Live turn trees' allowances (#2911), charged from intent creation until observed reclamation. */ + const treeReservations = new Map(); + let treeBytes = 0; + /** The store filesystem's `major:minor` in mountinfo, for the reader census. */ + let storeDevice = ""; const trace = options.trace, clock = () => performance.timeOrigin + performance.now(); /** The operation holding the lock, for a traced wait behind it. */ let holder: string | null = null, requests = 0; @@ -218,6 +226,7 @@ export async function createNativeBrainManager(config: NativeBrainManagerConfig, async function qualify(signal?: AbortSignal): Promise { trustedDirectory(fixed.storePath); const mount = nativeStoreMount(readFileSync("/proc/self/mountinfo", "utf8"), fixed.storePath, brain); + storeDevice = mount.device; // Btrfs emits enabled sync/async discard in mountinfo; nodiscard itself is omitted. if (mount.options.some(option => option === "discard" || option.startsWith("discard="))) throw new NativeBrainManagerError("unsupported", "Native managed store requires explicitly disabled discard, including for fully allocated loop backing."); @@ -253,7 +262,7 @@ export async function createNativeBrainManager(config: NativeBrainManagerConfig, const abandon = (error: unknown): never => { void inspector.close(); throw error; }; try { await qualify(); - for (const [path, mode] of [[privateRoot, 0o710], [state, 0o700], [roots, 0o750], [stages, 0o710]] as const) { + for (const [path, mode] of [[privateRoot, 0o710], [state, 0o700], [roots, 0o750], [stages, 0o710], [trees, 0o710]] as const) { if (!existsSync(path)) { mkdirSync(path, { mode }); chownSync(path, 0, fixed.appGid); chmodSync(path, mode); } trustedDirectory(path, mode); } @@ -288,7 +297,7 @@ export async function createNativeBrainManager(config: NativeBrainManagerConfig, try { const info = fstatSync(fd); if (!info.isFile() || info.uid !== 0 || info.nlink !== 1 || info.size > NATIVE_CONTROL_BYTES) throw Error("Untrusted native intent."); const result = JSON.parse(readFileSync(fd, "utf8")) as Intent; - if ((result.kind !== undefined && result.kind !== "stage") || result.version !== 1 || result.id !== id || result.sourceUuid !== fixed.brainUuid || !["creating", "sealed", "deleting", "deleted"].includes(result.state)) throw Error("Invalid native intent."); + if ((result.kind !== undefined && result.kind !== "stage" && result.kind !== "tree") || result.version !== 1 || result.id !== id || result.sourceUuid !== fixed.brainUuid || !["creating", "sealed", "deleting", "deleted"].includes(result.state)) throw Error("Invalid native intent."); return result; } finally { closeSync(fd); } } @@ -317,6 +326,7 @@ export async function createNativeBrainManager(config: NativeBrainManagerConfig, 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 === "tree") return rememberTree(intent); if (intent.kind !== "stage") return; const old = stageReservations.get(intent.id); if (old) { stagedBytes -= old.allowanceBytes; stageReservations.delete(intent.id); } @@ -328,6 +338,16 @@ export async function createNativeBrainManager(config: NativeBrainManagerConfig, stageReservations.set(intent.id, request); stagedBytes += request.allowanceBytes; if (!Number.isSafeInteger(stagedBytes)) throw new NativeBrainManagerError("unknown", "Native stage reservation accounting overflowed."); } + function rememberTree(intent: Intent): void { + const old = treeReservations.get(intent.id); + if (old !== undefined) { treeBytes -= old; treeReservations.delete(intent.id); } + if (intent.state === "deleted") return; + const allowance = intent.treeRequest?.allowanceBytes; + if (!Number.isSafeInteger(allowance) || allowance! <= 0 || allowance! % PAGE) + throw new NativeBrainManagerError("unknown", "Native turn-tree reservation receipt is incomplete; no new tree admission is authorized."); + treeReservations.set(intent.id, allowance!); treeBytes += allowance!; + if (!Number.isSafeInteger(treeBytes)) throw new NativeBrainManagerError("unknown", "Native turn-tree reservation accounting overflowed."); + } // Recover bounded stage accounting once at service startup; warm admission // never rescans all checkpoint tombstones or any live-brain bytes. let recoveredIds: string[] = []; @@ -338,18 +358,19 @@ export async function createNativeBrainManager(config: NativeBrainManagerConfig, // 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); + // A turn tree's allowance is persisted the same way, beside its directory (#2911). + const allowancePath = (id: string, parent = stages) => join(parent, `${id}.allowance`); + function syncStages(parent = stages): void { + const fd = openSync(parent, 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); + function recordStageAllowance(id: string, bytes: number, parent = stages): void { + const fd = openSync(allowancePath(id, parent), constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600); try { writeFileSync(fd, String(bytes)); fsyncSync(fd); } finally { closeSync(fd); } - syncStages(); + syncStages(parent); } - function readStageAllowance(id: string): number { - const fd = openSync(allowancePath(id), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK); + function readStageAllowance(id: string, parent = stages): number { + const fd = openSync(allowancePath(id, parent), 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) @@ -364,24 +385,30 @@ export async function createNativeBrainManager(config: NativeBrainManagerConfig, // 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 { - const allowance = readStageAllowance(id); - // Still validate later records, but Infinity already means unknown, not - // a new arithmetic overflow attributable to each subsequent identity. - if (Number.isFinite(quarantinedStageBytes)) { - quarantinedStageBytes += allowance; - if (!Number.isSafeInteger(quarantinedStageBytes)) throw Error("Native quarantine capacity exceeds safe accounting range"); + // The same holds for a quarantined identity's turn tree, charged to tree admission (#2911). + const quarantinedCharge = (parent: string, label: string): number => { + let bytes = 0; + for (const id of quarantinedIntents) { + if (!nativeCheckpointId.safeParse(id).success) continue; + try { lstatSync(join(parent, id)); } + catch (error) { if (errorCode(error) === "ENOENT") continue; } + try { + const allowance = readStageAllowance(id, parent); + // Still validate later records, but Infinity already means unknown, not + // a new arithmetic overflow attributable to each subsequent identity. + if (Number.isFinite(bytes)) { + bytes += allowance; + if (!Number.isSafeInteger(bytes)) throw Error("Native quarantine capacity exceeds safe accounting range"); + } + } catch (error) { + bytes = Infinity; + recordNativeRecoveryFailure(join(privateRoot, "recovery-diagnostics"), id, label, error); } - } catch (error) { - quarantinedStageBytes = Infinity; - recordNativeRecoveryFailure(join(privateRoot, "recovery-diagnostics"), id, "native-brain-manager.recoverStageAllowance", error); } - } + return bytes; + }; + const quarantinedStageBytes = quarantinedCharge(stages, "native-brain-manager.recoverStageAllowance"); + const quarantinedTreeBytes = quarantinedCharge(trees, "native-brain-manager.recoverTreeAllowance"); // 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 = (() => { @@ -406,14 +433,14 @@ export async function createNativeBrainManager(config: NativeBrainManagerConfig, }; const rootPath = (id: string) => join(roots, id); async function verifyOwned(intent: Intent, signal?: AbortSignal): Promise { - if (intent.kind === "stage") throw new NativeBrainManagerError("invalid", "A staged namespace is not a native checkpoint identity."); + if (intent.kind !== undefined) throw new NativeBrainManagerError("invalid", "A staged namespace or turn tree is not a native checkpoint identity."); const info = await inspect(rootPath(intent.id), signal); if (!info.readOnly || info.parentUuid !== fixed.brainUuid || (intent.checkpoint && (info.uuid !== intent.checkpoint.uuid || info.rootId !== intent.checkpoint.rootId || info.transaction !== intent.checkpoint.transaction))) throw new NativeBrainManagerError("unknown", "Recorded checkpoint native identity or immutability changed; no deletion or use is authorized."); return { id: intent.id, sourceUuid: info.parentUuid, path: rootPath(intent.id), fsid: fixed.fsid, rootId: info.rootId, uuid: info.uuid, transaction: info.transaction, readOnly: true }; } async function reconcile(intent: Intent, signal?: AbortSignal): Promise { - if (intent.kind === "stage") return intent; + if (intent.kind !== undefined) return intent; if (intent.state === "creating" && existsSync(rootPath(intent.id))) { const checkpoint = await verifyOwned(intent, signal); intent = { ...intent, state: "sealed", checkpoint }; await writeIntent(intent); } @@ -510,7 +537,7 @@ export async function createNativeBrainManager(config: NativeBrainManagerConfig, if (request.operation === "poolReadCheckpoint") checkpoint = await pool().checkpointPath(request.id, signal); else { const intent = readIntent(request.id); - if (!intent || intent.kind === "stage" || intent.state !== "sealed") + if (!intent || intent.kind !== undefined || intent.state !== "sealed") throw new NativeBrainManagerError("unknown", "Checkpoint reading requires one retained sealed checkpoint identity."); end = step?.("verify"); checkpoint = await verifyOwned(intent, signal); @@ -541,7 +568,7 @@ export async function createNativeBrainManager(config: NativeBrainManagerConfig, if (start !== stage.namespaceStart || stage.appUid !== fixed.appUid || stage.appGid !== fixed.appGid) throw new NativeBrainManagerError("unavailable", "Stage keeper identity changed before attestation."); const source = readIntent(stage.checkpointId); - if (!source || source.kind === "stage" || source.state !== "sealed") + if (!source || source.kind !== undefined || source.state !== "sealed") throw new NativeBrainManagerError("unknown", "Stage checkpoint authority is no longer retained."); const checkpoint = await verifyOwned(source, signal); if (checkpoint.uuid !== stage.checkpointUuid) throw new NativeBrainManagerError("unknown", "Stage checkpoint identity changed."); @@ -571,7 +598,8 @@ export async function createNativeBrainManager(config: NativeBrainManagerConfig, const record = await reconcile(readIntent(id)!, signal); const publicRecord: NativeRecoveryRecord = { id: record.id, state: record.state, ...(record.checkpoint ? { checkpoint: record.checkpoint } : {}), ...(record.kind ? { kind: record.kind } : {}), - ...(record.stage ? { stage: record.stage } : {}), ...(record.stageRequest ? { stageRequest: record.stageRequest } : {}) }; + ...(record.stage ? { stage: record.stage } : {}), ...(record.stageRequest ? { stageRequest: record.stageRequest } : {}), + ...(record.treeRequest ? { treeRequest: record.treeRequest } : {}) }; if (Buffer.byteLength(JSON.stringify({ records: [...records, publicRecord], next: id })) > NATIVE_CONTROL_BYTES) break; records.push(publicRecord); last = id; } @@ -595,7 +623,7 @@ export async function createNativeBrainManager(config: NativeBrainManagerConfig, } if (intent) throw new NativeBrainManagerError("unavailable", "Interrupted stage preparation must be released before retry with a new identity."); const source = readIntent(request.checkpointId); - if (!source || source.kind === "stage" || source.state !== "sealed") throw new NativeBrainManagerError("unknown", "Native staging requires one retained sealed checkpoint."); + if (!source || source.kind !== undefined || source.state !== "sealed") throw new NativeBrainManagerError("unknown", "Native staging requires one retained sealed checkpoint."); const checkpoint = await verifyOwned(source, signal); const recoveryRefusal = stagingRecoveryRefusal(request.allowanceBytes); if (recoveryRefusal) throw new NativeBrainManagerError("unknown", recoveryRefusal); @@ -662,6 +690,8 @@ export async function createNativeBrainManager(config: NativeBrainManagerConfig, return new Response(body, { headers: { "content-type": "application/x-brain-native-stage", "x-brain-stage-id": request.id, "x-brain-stage-checkpoint": handle.stage.checkpointId, "x-brain-stage-lower": handle.stage.checkpointUuid } }); } + if (request.operation === "prepareTurnTree") return Response.json(await prepareTurnTree(request.id, request.allowanceBytes, signal)); + if (request.operation === "releaseTurnTree") return Response.json(await releaseTurnTree(request.id, signal)); if (request.operation === "checkpoint") { end = step?.("qualify"); await qualify(signal); @@ -701,6 +731,7 @@ export async function createNativeBrainManager(config: NativeBrainManagerConfig, throw new NativeBrainManagerError("unavailable", "Close the checkpoint's active fixed-reader handle before releasing its native view."); let intent = readIntent(request.id); if (intent?.kind === "stage") throw new NativeBrainManagerError("invalid", "Use releaseStage for staged namespace ownership."); + if (intent?.kind === "tree") throw new NativeBrainManagerError("invalid", "Use releaseTurnTree for turn-tree ownership."); if ([...stageReservations.values()].some(stage => stage.checkpointId === request.id)) throw new NativeBrainManagerError("unavailable", "Release the checkpoint's staged output references before its native view."); if (!intent) { @@ -740,6 +771,82 @@ export async function createNativeBrainManager(config: NativeBrainManagerConfig, return response; } finally { if (!handedToStream) release(); } } + const treePath = (id: string) => join(trees, id); + const treeReceipt = (id: string, allowanceBytes: number): NativeTurnTree => ({ id, path: treePath(id), allowanceBytes }); + /** + * Admit one turn's data tree (#2911): an app-owned directory on this volume, + * outside the live brain and every checkpoint. Its allowance is charged from + * the durable intent until removal is observed, and admission leaves the + * live trees' charges plus one emergency reserve's worth of the volume + * unallocated, so trees never bring checkpoint and intent writes to the + * reserve. Shared extents are not charged twice; a tree's own growth is. + */ + async function prepareTurnTree(id: string, allowanceBytes: number, signal?: AbortSignal): Promise { + if (fixed.appUid === undefined) throw new NativeBrainManagerError("unsupported", "Configure the fixed app UID before native turn-tree admission."); + if (!Number.isSafeInteger(allowanceBytes) || allowanceBytes <= 0 || allowanceBytes % PAGE || allowanceBytes > fixed.capacityBytes) + throw new NativeBrainManagerError("capacity", "Requested turn-tree allowance is not whole pages within the managed volume."); + const intent = readIntent(id), path = treePath(id); + if (intent && intent.kind !== "tree") throw new NativeBrainManagerError("invalid", "This identity belongs to a checkpoint or stage, not a turn tree."); + if (intent?.state === "deleted" || intent?.state === "deleting") throw new NativeBrainManagerError("released", "This turn-tree identity was released; it cannot be recreated."); + if (intent?.state === "sealed") { + // A retry after a lost reply receives the same tree, never a different one. + if (intent.treeRequest?.allowanceBytes !== allowanceBytes) throw new NativeBrainManagerError("invalid", "An existing turn tree cannot change its allowance."); + return treeReceipt(id, allowanceBytes); + } + if (intent) throw new NativeBrainManagerError("unavailable", "Interrupted turn-tree preparation must be released before retry with a new identity."); + if (!Number.isFinite(quarantinedTreeBytes)) throw new NativeBrainManagerError("unknown", "Native turn-tree admission is blocked: a quarantined tree's storage size is unknown. " + + "Inspect the host-private recovery diagnostics and restore its allowance record from proof of its original size, then restart the native manager and the server."); + await ensureReserve(signal); + if (reserveConsumed) throw new NativeBrainManagerError("capacity", "Native recovery consumed emergency allocation; rearm capacity before turn-tree admission."); + const { statfsSync } = await import("node:fs"), space = statfsSync(fixed.storePath); + if (space.type !== BTRFS_MAGIC) throw new NativeBrainManagerError("unsupported", "Native store filesystem type changed."); + const available = space.bavail * space.bsize; + if (treeBytes + quarantinedTreeBytes + allowanceBytes + fixed.recoveryReserveBytes > available) + throw new NativeBrainManagerError("capacity", "The managed volume has no room for another turn's data tree; nothing ran."); + if (existsSync(path) || existsSync(allowancePath(id, trees))) throw new NativeBrainManagerError("unknown", "Unrecorded turn-tree storage occupies this identity."); + const created: Intent = { version: 1, id, sourceUuid: fixed.brainUuid, kind: "tree", state: "creating", treeRequest: { allowanceBytes } }; + await writeIntent(created); + recordStageAllowance(id, allowanceBytes, trees); + signal?.throwIfAborted(); + // Only the app owns it; the worker identity, in the app's group, can only + // traverse it to reach the directories the app gives it. + mkdirSync(path, { mode: 0o700 }); chownSync(path, fixed.appUid, fixed.appGid); chmodSync(path, 0o710); + syncStages(trees); + await writeIntent({ ...created, state: "sealed" }); + return treeReceipt(id, allowanceBytes); + } + /** + * Remove one turn tree once no process mounts it. The owner calls this after + * its workers exit; recovery calls it for a dead owner. The charge stays + * until removal and a filesystem commit have been observed, and an unknown + * identity is fenced instead of removed. + */ + async function releaseTurnTree(id: string, signal?: AbortSignal): Promise<{ id: string; state: "deleted" }> { + const intent = readIntent(id), path = treePath(id); + if (!intent) { + if (existsSync(path)) throw new NativeBrainManagerError("unknown", "Unrecorded turn-tree storage cannot be released."); + await writeIntent({ version: 1, id, sourceUuid: fixed.brainUuid, kind: "tree", state: "deleted" }); + return { id, state: "deleted" }; + } + if (intent.kind !== "tree") throw new NativeBrainManagerError("invalid", "This identity belongs to a checkpoint or stage, not a turn tree."); + if (intent.state === "deleted") return { id, state: "deleted" }; + const readers = nativeTurnTreeReaders(storeDevice, `/${relative(fixed.storePath, path)}`); + if (readers.length) throw new NativeBrainManagerError("unavailable", `A worker still mounts this turn tree (${readers.length} process${readers.length === 1 ? "" : "es"}); release it after every reader exits.`); + await writeIntent({ ...intent, state: "deleting" }); + let info; + try { info = lstatSync(path); } catch (error) { if (errorCode(error) !== "ENOENT") throw error; } + if (info) { + if (!info.isDirectory()) throw new NativeBrainManagerError("unknown", "Turn-tree identity is unsafe; no removal is authorized."); + await command([PYTHON, "-I", "-S", "-c", NATIVE_TREE_REMOVAL, path], signal); + } + // The charge is credited only once the freed extents are committed. + await command([BTRFS, "filesystem", "sync", fixed.storePath], signal); + syncStages(trees); + try { unlinkSync(allowancePath(id, trees)); } catch (error) { if (errorCode(error) !== "ENOENT") throw error; } + syncStages(trees); + await writeIntent({ ...intent, state: "deleted" }); + return { id, state: "deleted" }; + } /** Stream one metadata-only send between two verified read-only roots; the lock is released when the send ends. */ function sendDelta(parent: string, child: string, signal: AbortSignal | undefined, release: () => void): Response { const running = spawn([BTRFS, "send", "--no-data", "--proto", "1", "-p", parent, child], signal); diff --git a/packages/ui-sdk/src/server/native-turn-trees.ts b/packages/ui-sdk/src/server/native-turn-trees.ts new file mode 100644 index 0000000000..3698ac4fe5 --- /dev/null +++ b/packages/ui-sdk/src/server/native-turn-trees.ts @@ -0,0 +1,48 @@ +/** + * Turn data trees on the managed volume (#2911): the manager's reader census + * and removal program. A turn's tree lives under the manager's private + * `trees/` directory, outside the live brain and every checkpoint, so a copy + * from the turn's checkpoint into it shares that checkpoint's extents. + */ +import { isWithin } from "@schlessera/brain-common/internal/safe-path"; +import { readdirSync, readFileSync } from "node:fs"; + +/** + * Removes one tree with the standard library's descriptor-relative walk, + * which never follows a link the app or a worker left inside it. It refuses + * where that walk is unavailable, and a top-level path that is not a plain + * directory. + */ +export const NATIVE_TREE_REMOVAL = `import os,sys,stat,shutil +if not shutil.rmtree.avoids_symlink_attacks: raise SystemExit("descriptor-relative removal is unavailable") +path=sys.argv[1] +try: info=os.lstat(path) +except FileNotFoundError: raise SystemExit(0) +if not stat.S_ISDIR(info.st_mode): raise SystemExit("turn tree is not a plain directory") +shutil.rmtree(path) +`; + +const unescape = (text: string) => text.replace(/\\(040|011|012|134)/g, (_all, digits: string) => String.fromCharCode(parseInt(digits, 8))); +const code = (error: unknown) => (error as NodeJS.ErrnoException)?.code; + +/** + * The processes whose mount namespace holds a mount of `root` (a path inside + * the store filesystem `device`, as `major:minor`) or of anything under it: a + * worker's read-only bind of its tree. A process that exits while it is read + * is no reader; any other read failure is thrown, so the caller refuses + * instead of treating an unknown as no reader. + */ +export function nativeTurnTreeReaders(device: string, root: string, proc = "/proc"): number[] { + const readers: number[] = []; + for (const name of readdirSync(proc)) { + if (!/^[1-9][0-9]*$/.test(name)) continue; + let text: string; + // ESRCH and ENOENT: it exited. EINVAL: a zombie, which has no mount namespace. + try { text = readFileSync(`${proc}/${name}/mountinfo`, "utf8"); } catch (error) { if (["ENOENT", "ESRCH", "EINVAL"].includes(code(error) ?? "")) continue; throw error; } + for (const line of text.split("\n")) { + const fields = line.split(" "); + if (fields[2] === device && fields[3] !== undefined && isWithin(root, unescape(fields[3]))) { readers.push(Number(name)); break; } + } + } + return readers; +} diff --git a/packages/ui-sdk/src/server/worker-startup-view.ts b/packages/ui-sdk/src/server/worker-startup-view.ts index db158ad695..9ec5983983 100644 --- a/packages/ui-sdk/src/server/worker-startup-view.ts +++ b/packages/ui-sdk/src/server/worker-startup-view.ts @@ -21,7 +21,8 @@ export interface WorkerStartupView { } type NativeClient = ReturnType; -const nativeInputs = new WeakMap & Partial> }>(); +type NativeViewManager = Pick & Partial>; +const nativeInputs = new WeakMap(); /** Trusted acquisition metadata; no request-supplied manager or checkpoint is accepted. */ export function nativeWorkerStartupInput(view: WorkerStartupView) { if (releasedViews.has(view)) throw new Error("native startup checkpoint owner is closed"); @@ -39,6 +40,18 @@ export function isManagedWorkerStartupView(view: WorkerStartupView | undefined): const input = nativeInputs.get(view); return Boolean(input?.manager.prepareStage && input.manager.inspectStage && input.manager.releaseStage); } +/** + * The manager that acquired a live managed view, for placing the turn's data + * tree on the same volume (#2911); undefined for an unmanaged view. A managed + * view whose manager cannot place one is refused, never given a full copy. + */ +export function nativeTurnTreeManager(view: WorkerStartupView): Pick | undefined { + if (!isManagedWorkerStartupView(view)) return undefined; + const manager = nativeInputs.get(view)!.manager; + if (!manager.prepareTurnTree || !manager.releaseTurnTree) + throw new Error("The native manager that acquired this startup view cannot place a turn data tree on the managed volume; no full-copy fallback runs."); + return manager as Pick; +} /** Why a governed or strict turn whose startup view is not on managed native storage is refused (#3314). */ export const UNMANAGED_TURN_STORAGE = "Governed and strict turns need a startup view the native manager acquired on managed native storage, where the turn egress relay runs; this turn's view is not one, so it is refused."; /** @@ -107,7 +120,7 @@ export function retainWorkerStartupView(view: WorkerStartupView): WorkerStartupV * await the owner's cleanup. A lost RPC releases/reconciles the same identity. */ export async function prepareNativeWorkerStartupView(brainPath: string, - manager: Pick & Partial>, + manager: NativeViewManager, signal?: AbortSignal): Promise { signal?.throwIfAborted(); const brain = realpathSync(brainPath), id = randomUUID(); diff --git a/packages/ui-sdk/tests/native-manager-turn-trees.test.ts b/packages/ui-sdk/tests/native-manager-turn-trees.test.ts new file mode 100644 index 0000000000..834a430c4b --- /dev/null +++ b/packages/ui-sdk/tests/native-manager-turn-trees.test.ts @@ -0,0 +1,238 @@ +/** + * Turn data trees on the managed volume (#2911): the manager's admission + * charge, reserve headroom, reader refusal, observed reclamation and + * identity fences. Real manager, intents and filesystem; only privileged + * kernel operations are doubled. + */ +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 { NativeStage, NativeTurnTree } from "../src/server/native-brain-manager-protocol"; +import { nativeTurnTreeReaders } from "../src/server/native-turn-trees"; + +const id = (n: number) => `29110000-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 turn-tree fixture cleanup failed"); +}); + +/** Real manager, intents and filesystem; only privileged kernel operations are doubled. */ +function fixture() { + const root = fs.mkdtempSync(join(tmpdir(), "odysseus-native-trees-")); + 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"), treeRoot = join(root, ".brain-native/trees"); + fs.mkdirSync(state, { recursive: true, mode: 0o700 }); fs.chmodSync(state, 0o700); fs.chmodSync(dirname(state), 0o710); + fs.mkdirSync(stageRoot, { mode: 0o710 }); fs.chmodSync(stageRoot, 0o710); + /** Processes the reader census sees, each with its mountinfo text. */ + const processes = new Map(); + const commands: string[][] = [], owners: Array<{ path: string; uid: number; gid: number }> = []; + let bavail = 1000, failSync = false; + 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(((path: string, uid: number, gid: number) => { owners.push({ path, uid, gid }); }) as typeof fs.chownSync), + 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"; + const proc = /^\/proc\/([0-9]+)\/mountinfo$/.exec(String(path)); + if (proc) { const text = processes.get(proc[1]!); if (text === undefined) throw Object.assign(Error("gone"), { code: "ENOENT" }); return text; } + return read(path, options); + }) as typeof fs.readFileSync), + spyOn(fs, "readdirSync").mockImplementation(((path: string, options?: never) => + path === `/sys/fs/btrfs/${config.fsid}/devices` ? ["device"] : path === "/proc" ? ["self", ...processes.keys()] : path === state ? list(path).sort() : list(path, options)) as typeof fs.readdirSync), + spyOn(fs, "statfsSync").mockImplementation((() => ({ type: 0x9123683e, bavail, bsize: 4096 })) as unknown as typeof fs.statfsSync), + 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; + commands.push(argv); + if (argv[0] === "/usr/bin/python3") fs.rmSync(argv.at(-1)!, { recursive: true, force: true }); + else 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[1] === "filesystem" && argv[2] === "sync" && failSync) { errors = "Odysseus's filesystem commit stalled"; code = 1; } + 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, treeRoot, prepared, processes, commands, owners, setAvailablePages(pages: number) { bavail = pages; }, setFailSync(fail: boolean) { failSync = fail; }, 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 }; + } }; +} + + +const PAGE = 4096; +const prepare = async (manager: { run: (request: never) => Promise }, n: number, pages: number) => + (await (await manager.run({ operation: "prepareTurnTree", id: id(n), allowanceBytes: pages * PAGE } as never)).json()) as NativeTurnTree; +const release = async (manager: { run: (request: never) => Promise }, n: number) => + (await (await manager.run({ operation: "releaseTurnTree", id: id(n) } as never)).json()) as { id: string; state: string }; +/** One worker's read-only bind of `path` (inside the store filesystem, device 0:38), as mountinfo lists it. */ +const bind = (path: string, device = "0:38") => `120 41 ${device} ${path} /tmp/brain-worker-data ro,nosuid,nodev - btrfs /dev/odysseus rw\n`; +const intent = (f: { state: string }, n: number) => JSON.parse(fs.readFileSync(join(f.state, `${id(n)}.json`), "utf8")); + +test("a turn tree is an app-owned directory outside the live brain and every checkpoint", async () => { + const f = fixture(), manager = await f.manager(); + const tree = await prepare(manager, 2, 250); + expect(tree.path, "TREE_UNDER_MANAGER_AREA").toBe(join(f.treeRoot, id(2))); + expect(tree.path.startsWith(join(f.config.storePath, "brain") + "/") || tree.path.startsWith(join(f.config.storePath, ".brain-native/checkpoints") + "/"), + "TREE_OUTSIDE_BRAIN_AND_CHECKPOINTS").toBe(false); + expect(f.owners, "TREE_OWNED_BY_THE_APP_IDENTITY").toContainEqual({ path: tree.path, uid: 1000, gid: 1000 }); + expect(fs.statSync(tree.path).mode & 0o777, "WORKER_GROUP_CAN_ONLY_TRAVERSE").toBe(0o710); + expect(fs.statSync(f.treeRoot).mode & 0o777).toBe(0o710); + expect(intent(f, 2)).toMatchObject({ kind: "tree", state: "sealed", treeRequest: { allowanceBytes: 250 * PAGE } }); + expect(await prepare(manager, 2, 250), "LOST_REPLY_RETRY_RETURNS_SAME_TREE").toEqual(tree); + await expect(prepare(manager, 2, 251), "TREE_ALLOWANCE_IS_FIXED").rejects.toMatchObject({ code: "invalid" }); + await expect(manager.run({ operation: "release", id: id(2) }), "TREE_IS_NOT_A_CHECKPOINT").rejects.toMatchObject({ code: "invalid" }); + await expect(manager.run({ operation: "checkpoint", id: id(2) }), "TREE_IS_NOT_A_CHECKPOINT").rejects.toMatchObject({ code: "invalid" }); + await manager.run({ operation: "checkpoint", id: id(3) }); + await expect(manager.run({ operation: "releaseTurnTree", id: id(3) }), "CHECKPOINT_IS_NOT_A_TREE").rejects.toMatchObject({ code: "invalid" }); + await expect(manager.run({ operation: "prepareTurnTree", id: id(3), allowanceBytes: PAGE }), "CHECKPOINT_IS_NOT_A_TREE").rejects.toMatchObject({ code: "invalid" }); + await expect(manager.run({ operation: "prepareTurnTree", id: id(4), allowanceBytes: PAGE + 1 }), "TREE_ALLOWANCE_IS_WHOLE_PAGES").rejects.toMatchObject({ code: "capacity" }); +}); + +test("admission charges live allowances plus one emergency reserve of headroom, and refuses near capacity", async () => { + // 1000 free pages; the configured reserve is one page. + const f = fixture(), manager = await f.manager(); + await prepare(manager, 2, 500); + await prepare(manager, 3, 499); + await expect(prepare(manager, 4, 1), "REFUSES_PAST_RESERVE_HEADROOM").rejects.toMatchObject({ code: "capacity" }); + expect(fs.existsSync(join(f.treeRoot, id(4))) || fs.existsSync(join(f.state, `${id(4)}.json`)), "REFUSAL_RUNS_NOTHING").toBe(false); + // Live trees' growth lowers free space; admission sees it without a larger limit. + await release(manager, 3); + f.setAvailablePages(600); + await expect(prepare(manager, 5, 100), "OBSERVED_ALLOCATION_COUNTS").rejects.toMatchObject({ code: "capacity" }); + expect((await prepare(manager, 6, 99)).id, "ADMITS_UP_TO_RESERVE_HEADROOM").toBe(id(6)); +}); + +test("release credits the charge only after removal and an observed filesystem commit", async () => { + const f = fixture(), manager = await f.manager(); + const tree = await prepare(manager, 2, 990); + fs.mkdirSync(join(tree.path, "data/notes"), { recursive: true }); + fs.writeFileSync(join(tree.path, "data/notes/ithaca.md"), "Odysseus returns.\n"); + fs.symlinkSync("/etc", join(tree.path, "data/escape")); + await expect(prepare(manager, 3, 10)).rejects.toMatchObject({ code: "capacity" }); + f.setFailSync(true); + const before = f.commands.length; + await expect(release(manager, 2), "UNOBSERVED_COMMIT_REFUSES").rejects.toThrow("commit stalled"); + expect(intent(f, 2).state).toBe("deleting"); + await expect(prepare(manager, 3, 10), "UNOBSERVED_RECLAMATION_RETAINS_CHARGE").rejects.toMatchObject({ code: "capacity" }); + f.setFailSync(false); + expect(await release(manager, 2)).toEqual({ id: id(2), state: "deleted" }); + const after = f.commands.slice(before); + const removal = after.findIndex(argv => argv[0] === "/usr/bin/python3" && argv.at(-1) === tree.path); + const commit = after.findLastIndex(argv => argv[1] === "filesystem" && argv[2] === "sync"); + expect(removal, "MANAGER_REMOVES_THE_TREE").toBeGreaterThanOrEqual(0); + expect(commit, "COMMIT_OBSERVED_AFTER_REMOVAL").toBeGreaterThan(removal); + expect(fs.existsSync(tree.path)).toBe(false); + expect(fs.existsSync("/etc"), "A_LINK_IN_THE_TREE_IS_NOT_FOLLOWED").toBe(true); + expect((await prepare(manager, 3, 10)).id, "RECLAIMED_CHARGE_IS_CREDITED").toBe(id(3)); +}); + +test("a tree a worker still mounts is neither removed nor credited", async () => { + const f = fixture(), manager = await f.manager(); + const tree = await prepare(manager, 2, 990); + await prepare(manager, 3, 1); + // Mounts of another tree or another filesystem are no readers of this one. + f.processes.set("4241", bind(`/.brain-native/trees/${id(3)}/data`)); + f.processes.set("4243", bind(`/.brain-native/trees/${id(2)}/data`, "0:99")); + f.processes.set("4242", bind(`/.brain-native/trees/${id(2)}/index\\040(deleted)`)); + await expect(release(manager, 2), "LIVE_READER_REFUSES_CLEANUP").rejects.toMatchObject({ code: "unavailable" }); + expect(fs.existsSync(tree.path), "LIVE_READER_KEEPS_THE_TREE").toBe(true); + expect(intent(f, 2).state).toBe("sealed"); + await expect(prepare(manager, 4, 9), "LIVE_READER_KEEPS_THE_CHARGE").rejects.toMatchObject({ code: "capacity" }); + f.processes.delete("4242"); + expect(await release(manager, 2)).toEqual({ id: id(2), state: "deleted" }); + expect(fs.existsSync(join(f.treeRoot, id(3))), "PEER_TREE_UNTOUCHED").toBe(true); +}); + +test("restart keeps live trees charged, and released or foreign identities are never recreated or removed", async () => { + const f = fixture(); + let manager = await f.manager(); + const tree = await prepare(manager, 2, 900); + await manager.close(); + manager = await f.manager(); + await expect(prepare(manager, 3, 200), "RESTART_RETAINS_TREE_CHARGE").rejects.toMatchObject({ code: "capacity" }); + expect(await prepare(manager, 2, 900), "RESTART_RETAINS_LIVE_TREE").toEqual(tree); + await release(manager, 2); + await expect(prepare(manager, 2, 900), "RELEASED_TREE_CANNOT_BE_RECREATED").rejects.toMatchObject({ code: "released" }); + expect(await release(manager, 7)).toEqual({ id: id(7), state: "deleted" }); + await expect(prepare(manager, 7, 1), "DELAYED_CREATE_IS_FENCED").rejects.toMatchObject({ code: "released" }); + fs.mkdirSync(join(f.treeRoot, id(8))); + fs.writeFileSync(join(f.treeRoot, id(8), "penelope.md"), "Not this turn's.\n"); + await expect(release(manager, 8), "FOREIGN_TREE_NOT_DELETED").rejects.toMatchObject({ code: "unknown" }); + expect(fs.existsSync(join(f.treeRoot, id(8), "penelope.md"))).toBe(true); + await expect(prepare(manager, 8, 1), "FOREIGN_TREE_NOT_ADOPTED").rejects.toMatchObject({ code: "unknown" }); +}); + +test("an unreadable tree receipt restricts tree admission only", async () => { + const f = fixture(); + let manager = await f.manager(); + await prepare(manager, 2, 100); + await manager.close(); + fs.writeFileSync(join(f.state, `${id(2)}.json`), "{broken"); + manager = await f.manager(); + // Its independent allowance record still bounds its charge. + await expect(prepare(manager, 3, 900), "QUARANTINED_TREE_STAYS_CHARGED").rejects.toMatchObject({ code: "capacity" }); + expect((await prepare(manager, 4, 800)).id).toBe(id(4)); + await expect(release(manager, 2), "QUARANTINED_TREE_IS_NOT_REMOVED").rejects.toThrow("quarantined"); + await manager.close(); + fs.unlinkSync(join(f.treeRoot, `${id(2)}.allowance`)); + manager = await f.manager(); + await expect(prepare(manager, 5, 1), "UNKNOWN_TREE_CHARGE_REFUSES_AS_RECOVERY").rejects.toMatchObject({ code: "unknown", message: expect.stringContaining("diagnostics") }); + expect((await (await manager.run({ operation: "checkpoint", id: id(6) })).json()).id, "QUARANTINE_IS_PROPORTIONATE").toBe(id(6)); +}); + +test("the reader census reads every process's mounts and refuses what it cannot read", () => { + const proc = fs.mkdtempSync(join(tmpdir(), "odysseus-proc-")); + cleanups.push(() => fs.rmSync(proc, { recursive: true, force: true })); + for (const [pid, text] of [["11", bind("/.brain-native/trees/a/data")], ["12", bind("/.brain-native/trees/ab/data")], ["13", bind("/.brain-native/trees/a", "0:7")]] as const) { + fs.mkdirSync(join(proc, pid)); fs.writeFileSync(join(proc, pid, "mountinfo"), text); + } + fs.mkdirSync(join(proc, "14")); + fs.mkdirSync(join(proc, "self")); + expect(nativeTurnTreeReaders("0:38", "/.brain-native/trees/a", proc), "CENSUS_MATCHES_ONLY_THIS_TREE").toEqual([11]); + fs.mkdirSync(join(proc, "15")); fs.mkdirSync(join(proc, "15", "mountinfo")); + expect(() => nativeTurnTreeReaders("0:38", "/.brain-native/trees/a", proc), "UNREADABLE_CENSUS_IS_NOT_EMPTY").toThrow(); +}); diff --git a/packages/ui-server/src/brain/native-brain-leases.ts b/packages/ui-server/src/brain/native-brain-leases.ts index ca09897a70..4372a9f0b9 100644 --- a/packages/ui-server/src/brain/native-brain-leases.ts +++ b/packages/ui-server/src/brain/native-brain-leases.ts @@ -12,7 +12,7 @@ import { reviveNativeLeaseError, type NativeLeaseOwner } from "./native-lease-st type Client = ReturnType; type PoolLease = { id: string; purpose: "source" | "worktree" | "staging" | "checkpoint"; from_id: string | null; allowance: number; state: "creating" | "held" | "releasing" }; -type Lease = { id: string; kind: "checkpoint" | "stage"; checkpoint_uuid: string | null; stage_lower_id: string | null; stage_allowance: number | null; owner_pid: number; owner_start: string; owner_generation: string; owner_boot: string; owner_pid_namespace: string; state: "creating" | "sealed" | "deleting" }; +type Lease = { id: string; kind: "checkpoint" | "stage" | "tree"; checkpoint_uuid: string | null; stage_lower_id: string | null; stage_allowance: number | null; owner_pid: number; owner_start: string; owner_generation: string; owner_boot: string; owner_pid_namespace: string; state: "creating" | "sealed" | "deleting" }; export async function createNativeBrainLeaseManager(raw: Client, options: { statePath: string; brainPath: string; fsid: string; brainUuid: string; @@ -57,7 +57,7 @@ export async function createNativeBrainLeaseManager(raw: Client, options: { throw Error("Native lease state requires durable SQLite WAL/FULL mode before any manager request."); db.exec(`CREATE TABLE IF NOT EXISTS native_lease_store (id INTEGER PRIMARY KEY CHECK(id=1),version INTEGER NOT NULL,brain TEXT NOT NULL,fsid TEXT NOT NULL,brain_uuid TEXT NOT NULL); CREATE TABLE IF NOT EXISTS native_pool_leases (id TEXT PRIMARY KEY,purpose TEXT NOT NULL CHECK(purpose IN ('source','worktree','staging','checkpoint')),from_id TEXT,allowance INTEGER NOT NULL,state TEXT NOT NULL CHECK(state IN ('creating','held','releasing'))); - CREATE TABLE IF NOT EXISTS native_root_leases (id TEXT PRIMARY KEY,owner_pid INTEGER NOT NULL,owner_start TEXT NOT NULL,owner_generation TEXT NOT NULL,owner_boot TEXT NOT NULL,owner_pid_namespace TEXT NOT NULL,state TEXT NOT NULL CHECK(state IN ('creating','sealed','deleting')),kind TEXT NOT NULL DEFAULT 'checkpoint' CHECK(kind IN ('checkpoint','stage')),checkpoint_uuid TEXT,stage_lower_id TEXT,stage_allowance INTEGER);`); + CREATE TABLE IF NOT EXISTS native_root_leases (id TEXT PRIMARY KEY,owner_pid INTEGER NOT NULL,owner_start TEXT NOT NULL,owner_generation TEXT NOT NULL,owner_boot TEXT NOT NULL,owner_pid_namespace TEXT NOT NULL,state TEXT NOT NULL CHECK(state IN ('creating','sealed','deleting')),kind TEXT NOT NULL DEFAULT 'checkpoint' CHECK(kind IN ('checkpoint','stage','tree')),checkpoint_uuid TEXT,stage_lower_id TEXT,stage_allowance INTEGER);`); // Pool leases recorded before worktree checkpoints (#2430) keep every row; only the purpose check widens. if (!(db.query("SELECT sql FROM sqlite_master WHERE type='table' AND name='native_pool_leases'").get() as { sql: string }).sql.includes("'checkpoint'")) db.transaction(() => db.exec(`ALTER TABLE native_pool_leases RENAME TO native_pool_leases_v1; @@ -69,6 +69,12 @@ export async function createNativeBrainLeaseManager(raw: Client, options: { db.exec("ALTER TABLE native_root_leases ADD COLUMN kind TEXT NOT NULL DEFAULT 'checkpoint' CHECK(kind IN ('checkpoint','stage'))"); for (const [name, type] of [["checkpoint_uuid", "TEXT"], ["stage_lower_id", "TEXT"], ["stage_allowance", "INTEGER"]] as const) if (!(db.query("PRAGMA table_info(native_root_leases)").all() as { name: string }[]).some(column => column.name === name)) db.exec(`ALTER TABLE native_root_leases ADD COLUMN ${name} ${type}`); + // Leases recorded before turn trees (#2911) keep every row; only the kind check widens. + if (!(db.query("SELECT sql FROM sqlite_master WHERE type='table' AND name='native_root_leases'").get() as { sql: string }).sql.includes("'tree'")) + db.transaction(() => db.exec(`ALTER TABLE native_root_leases RENAME TO native_root_leases_v1; + CREATE TABLE native_root_leases (id TEXT PRIMARY KEY,owner_pid INTEGER NOT NULL,owner_start TEXT NOT NULL,owner_generation TEXT NOT NULL,owner_boot TEXT NOT NULL,owner_pid_namespace TEXT NOT NULL,state TEXT NOT NULL CHECK(state IN ('creating','sealed','deleting')),kind TEXT NOT NULL DEFAULT 'checkpoint' CHECK(kind IN ('checkpoint','stage','tree')),checkpoint_uuid TEXT,stage_lower_id TEXT,stage_allowance INTEGER); + INSERT INTO native_root_leases SELECT id,owner_pid,owner_start,owner_generation,owner_boot,owner_pid_namespace,state,kind,checkpoint_uuid,stage_lower_id,stage_allowance FROM native_root_leases_v1; + DROP TABLE native_root_leases_v1;`)).immediate(); const bind = db.transaction(() => { const old = db.query("SELECT * FROM native_lease_store WHERE id=1").get() as { version: number; brain: string; fsid: string; brain_uuid: string } | null; if (old && (old.version !== 1 || old.brain !== brain || old.fsid !== options.fsid || old.brain_uuid !== options.brainUuid)) @@ -112,7 +118,7 @@ export async function createNativeBrainLeaseManager(raw: Client, options: { await run("UPDATE native_root_leases SET state='deleting' WHERE id=?", lease.id); if (lease.kind === "checkpoint" && db.query("SELECT 1 FROM native_root_leases WHERE kind='stage' AND stage_lower_id=? LIMIT 1").get(lease.id)) throw new NativeBrainManagerError("unknown", "A retained native stage still depends on this checkpoint; reconcile stage deletion first."); - const result = await (lease.kind === "stage" ? raw.releaseStage(lease.id, signal) : raw.release(lease.id, signal)); + const result = await (lease.kind === "stage" ? raw.releaseStage(lease.id, signal) : lease.kind === "tree" ? raw.releaseTurnTree(lease.id, signal) : raw.release(lease.id, signal)); if (result.id !== lease.id || result.state !== "deleted") throw new NativeBrainManagerError("unknown", "Native lease deletion receipt is unreadable; retain and reconcile the same identity."); await run("DELETE FROM native_root_leases WHERE id=? AND owner_pid=? AND owner_start=? AND owner_generation=?", lease.id, lease.owner_pid, lease.owner_start, lease.owner_generation); return result; @@ -149,6 +155,21 @@ export async function createNativeBrainLeaseManager(raw: Client, options: { if (!mine(lease) && lease.state !== "deleting" && live(lease) !== false) throw new NativeBrainManagerError("unknown", "This native stage is still pinned by another live app or cron owner."); return releaseOwned(lease, signal); }); }, + prepareTurnTree(id, allowanceBytes, signal) { return operation(async () => { + signal?.throwIfAborted(); + await leases.call("treeIntent", id, allowanceBytes); + const tree = await raw.prepareTurnTree(id, allowanceBytes, signal); + if (tree.id !== id || tree.allowanceBytes !== allowanceBytes || tree.path !== join(dirname(brain), ".brain-native", "trees", id)) + throw new NativeBrainManagerError("unknown", "Native turn-tree reply does not match its durable lease identity."); + await run("UPDATE native_root_leases SET state='sealed' WHERE id=? AND owner_pid=? AND owner_start=? AND owner_generation=? AND state='creating'", id, SELF.pid, SELF.start, generation); + return tree; + }); }, + releaseTurnTree(id, signal) { return operation(async () => { + const lease = row(id); + if (!lease || lease.kind !== "tree") throw new NativeBrainManagerError("unknown", "This turn tree has no recorded lease; arbitrary broker trees cannot be deleted."); + if (!mine(lease) && lease.state !== "deleting" && live(lease) !== false) throw new NativeBrainManagerError("unknown", "This turn tree is still held by another live app or cron owner."); + return releaseOwned(lease, signal); + }); }, poolCreate(id, purpose, from, allowanceBytes, signal) { return operation(async () => { signal?.throwIfAborted(); await leases.call("poolIntent", id, purpose, from, allowanceBytes); diff --git a/packages/ui-server/src/brain/native-lease-store.ts b/packages/ui-server/src/brain/native-lease-store.ts index 6b36ed461d..124805aaf7 100644 --- a/packages/ui-server/src/brain/native-lease-store.ts +++ b/packages/ui-server/src/brain/native-lease-store.ts @@ -15,7 +15,7 @@ export const url = import.meta.url; /** This owner's identity: the manager instance's generation on this boot and PID namespace. */ export interface NativeLeaseOwner { generation: string; boot: string; pidNamespace: string } -type Lease = { kind: "checkpoint" | "stage"; checkpoint_uuid: string | null; stage_lower_id: string | null; stage_allowance: number | null; owner_pid: number; owner_start: string; owner_generation: string; owner_boot: string; owner_pid_namespace: string; state: "creating" | "sealed" | "deleting" }; +type Lease = { kind: "checkpoint" | "stage" | "tree"; checkpoint_uuid: string | null; stage_lower_id: string | null; stage_allowance: number | null; owner_pid: number; owner_start: string; owner_generation: string; owner_boot: string; owner_pid_namespace: string; state: "creating" | "sealed" | "deleting" }; type PoolLease = { purpose: string; from_id: string | null; allowance: number; state: "creating" | "held" | "releasing" }; export function reviveNativeLeaseError(wire: WireError): Error | undefined { @@ -48,6 +48,15 @@ export function setup(db: Database, owner: NativeLeaseOwner): WriteProcedures { }).immediate(); return lowerUuid; }, + /** A turn data tree (#2911); its allowance is kept in `stage_allowance`. */ + treeIntent(id: string, allowanceBytes: number): void { + db.transaction(() => { + const lease = row(id); + if (poolRow(id)) throw new NativeBrainManagerError("unknown", "This identity already belongs to a reference pool lease."); + if (lease && (!mine(lease) || lease.kind !== "tree" || lease.state === "deleting" || lease.stage_allowance !== allowanceBytes)) throw new NativeBrainManagerError("unknown", "Turn-tree identity belongs to another owner or deletion."); + if (!lease) db.query("INSERT INTO native_root_leases(id,owner_pid,owner_start,owner_generation,owner_boot,owner_pid_namespace,state,kind,stage_allowance) VALUES (?,?,?,?,?,?,'creating','tree',?)").run(id, SELF.pid, SELF.start, owner.generation, owner.boot, owner.pidNamespace, allowanceBytes); + }).immediate(); + }, poolIntent(id: string, purpose: string, from: string | null, allowanceBytes: number): void { db.transaction(() => { const lease = poolRow(id); diff --git a/packages/ui-server/src/brain/turn-data-tree.ts b/packages/ui-server/src/brain/turn-data-tree.ts index b9a36d6ea9..c0d194b804 100644 --- a/packages/ui-server/src/brain/turn-data-tree.ts +++ b/packages/ui-server/src/brain/turn-data-tree.ts @@ -15,6 +15,13 @@ * so the server cannot write through it. Only the view's own bytes and this * turn's effects ever enter the tree. * + * A view the native manager acquired gets its tree from that manager, on the + * same volume and outside the live brain and every checkpoint (#2911). There + * each file and the index seed is a reflink of the checkpoint's, required + * rather than requested: a copy that cannot share extents fails the turn + * instead of allocating a full copy. The manager charges the tree's allowance + * against the volume and removes the tree once no worker mounts it. + * * A turn under provider rules keeps the masked folders, the generated-text * caches (#2725) and the operational-state folders out of the tree, and its index is * the turn's private one. An effect enters the tree only if its path is @@ -30,11 +37,12 @@ import { chmodSync, chownSync, closeSync, constants, fstatSync, lstatSync, mkdir import { chmod, copyFile, utimes } from "node:fs/promises"; import { tmpdir } from "node:os"; import { dirname, join, normalize, relative } from "node:path"; +import { randomUUID } from "node:crypto"; import { Database, constants as sqlite } from "bun:sqlite"; import { parseFrontmatter } from "@schlessera/brain-common/internal/frontmatter"; import { INDEX_DIR } from "@schlessera/brain-common/internal/index-location"; import { isEnvName } from "@schlessera/brain-common/internal/protected-paths"; -import { envMaskedPaths, launchAgentWorker, prepareWorkerSandbox, PROVIDER_CACHE_DIR, PROVIDER_CACHE_FILES, retainWorkerStartupView, workerIdentityHelper, WORKER_DATA_ROOT, +import { envMaskedPaths, launchAgentWorker, nativeTurnTreeManager, prepareWorkerSandbox, PROVIDER_CACHE_DIR, PROVIDER_CACHE_FILES, retainWorkerStartupView, workerIdentityHelper, WORKER_DATA_ROOT, type WorkerDataTree, type WorkerStartupView } from "@schlessera/brain-ui-sdk/internal"; import { createIndexBatch, type IndexBatch } from "./index-batch.js"; import { isProviderMasked } from "./provider-mask-refusal.js"; @@ -99,6 +107,30 @@ const errno = (error: unknown) => (error as NodeJS.ErrnoException)?.code; */ const COPY_WIDTH = 16; const COPY_FLAGS = constants.COPYFILE_EXCL | constants.COPYFILE_FICLONE; +/** On the managed volume a file that cannot share the checkpoint's extents is an error, not a full copy (#2911). */ +const SHARED_FLAGS = constants.COPYFILE_EXCL | constants.COPYFILE_FICLONE_FORCE; + +/** + * Bytes this turn's committed effects may write into its tree. A turn that + * writes more keeps its committed Markdown, but the tree stops recording it and + * the turn's index reads refuse, as for any other failed tree write. + */ +export const TURN_TREE_EFFECT_BYTES = 64 * 1024 * 1024; +const PAGE = 4096; +/** Filesystem metadata charged per copied entry: its inode, names and extent references, kept twice. */ +const ENTRY_OVERHEAD_BYTES = PAGE; +const page = (bytes: number) => Math.ceil(bytes / PAGE) * PAGE; + +/** + * A managed tree's admission charge (#2911): what it can newly allocate on the + * volume. The documents share the checkpoint's extents and cost only their + * metadata; the seeded index can be rewritten page by page, with its log, up + * to twice its size; the turn's effects are bounded by `TURN_TREE_EFFECT_BYTES`. + * Shared extents are not charged as copies, and are not assumed to stay free. + */ +export function turnTreeAllowance(entries: number, indexBytes: number): number { + return page(2 * indexBytes + TURN_TREE_EFFECT_BYTES + entries * ENTRY_OVERHEAD_BYTES + 1024 * 1024); +} /** * Run `jobs` at most `COPY_WIDTH` at a time. The first failure, or an abort, @@ -125,10 +157,9 @@ async function pooled(jobs: readonly (() => Promise)[], signal?: AbortSign * are made here; the returned jobs copy the files, and `finish` then gives * each directory its mode and times, deepest first. */ -function planCopy(view: string, target: string, skip: (rel: string) => boolean): { files: (() => Promise)[]; finish(): void } { - let entries = 0; +function planCopy(view: string, skip: (rel: string) => boolean): { entries: number; apply(target: string, flags: number): { files: (() => Promise)[]; finish(): void } } { const unreadable = (error: unknown) => errno(error) === "EACCES"; - const files: (() => Promise)[] = [], directories: { to: string; info: import("node:fs").Stats }[] = []; + const planned: { path: string; info: import("node:fs").Stats }[] = []; const walk = (rel: string, depth: number) => { if (depth > COPY_DEPTH) throw new Error("The startup view exceeds the data tree's directory depth bound."); let listed: import("node:fs").Dirent[]; @@ -136,29 +167,44 @@ function planCopy(view: string, target: string, skip: (rel: string) => boolean): for (const entry of listed) { const path = rel ? `${rel}/${entry.name}` : entry.name; if (skip(path)) continue; - if (++entries > COPY_ENTRIES) throw new Error(`The startup view exceeds the data tree's ${COPY_ENTRIES} entry bound.`); - const from = join(view, path), to = join(target, path), info = lstatSync(from); + if (planned.length >= COPY_ENTRIES) throw new Error(`The startup view exceeds the data tree's ${COPY_ENTRIES} entry bound.`); + const info = lstatSync(join(view, path)); + planned.push({ path, info }); + if (info.isDirectory()) walk(path, depth + 1); + } + }; + walk("", 0); + return { entries: planned.length, apply(target, flags) { + const files: (() => Promise)[] = [], directories: { to: string; info: import("node:fs").Stats }[] = []; + // A directory is walked before everything in it, so it exists first. + for (const { path, info } of planned) { + const from = join(view, path), to = join(target, path); if (info.isSymbolicLink()) symlinkSync(readlinkSync(from), to); - else if (info.isDirectory()) { mkdirSync(to, { mode: 0o700 }); directories.push({ to, info }); walk(path, depth + 1); } - else if (info.isFile()) files.push(async () => { - try { await copyFile(from, to, COPY_FLAGS); } catch (error) { if (unreadable(error)) return; throw error; } + else if (info.isDirectory()) { + // A directory the server could not list stays empty, as it was left out before. + mkdirSync(to, { mode: 0o700 }); directories.push({ to, info }); + } else if (info.isFile()) files.push(async () => { + try { await copyFile(from, to, flags); } catch (error) { if (unreadable(error)) return; throw error; } await chmod(to, info.mode & 0o7777); await utimes(to, info.atime, info.mtime); }); } - }; - walk("", 0); - // A directory is planned before everything in it, so the reverse order - // closes each one after its contents. - return { files, finish() { for (const { to, info } of directories.reverse()) { chmodSync(to, info.mode & 0o7777); utimesSync(to, info.atime, info.mtime); } } }; + // The reverse order closes each directory after its contents. + return { files, finish() { for (const { to, info } of directories.reverse()) { chmodSync(to, info.mode & 0o7777); utimesSync(to, info.atime, info.mtime); } } }; + } }; } /** Jobs that seed `index` with the view's index files. The updater runs as the worker identity, which shares the server's group. */ -function seedIndex(view: string, index: string, separateIdentity: boolean): (() => Promise)[] { +function indexSeed(view: string): { names: string[]; bytes: number } { const source = join(view, INDEX_DIR); - const names = (() => { try { return readdirSync(source, { withFileTypes: true }); } catch (error) { if (errno(error) === "ENOENT") return []; throw error; } })(); - return names.filter(entry => entry.isFile()).map(entry => async () => { - const to = join(index, entry.name); - await copyFile(join(source, entry.name), to, COPY_FLAGS); + const listed = (() => { try { return readdirSync(source, { withFileTypes: true }); } catch (error) { if (errno(error) === "ENOENT") return []; throw error; } })(); + const names = listed.filter(entry => entry.isFile()).map(entry => entry.name); + return { names, bytes: names.reduce((sum, name) => sum + lstatSync(join(source, name)).size, 0) }; +} +function seedIndex(view: string, names: readonly string[], index: string, separateIdentity: boolean, flags: number): (() => Promise)[] { + const source = join(view, INDEX_DIR); + return names.map(name => async () => { + const to = join(index, name); + await copyFile(join(source, name), to, flags); await chmod(to, separateIdentity ? 0o660 : 0o600); }); } @@ -304,6 +350,54 @@ async function runOnTree(options: { } } +/** + * Where a new tree goes. A managed view's manager admits a directory on its + * volume (#2911), holding `data/` and, unless the turn brought its private + * index, `index/`; the copy then requires reflinks, and only the manager + * removes the tree. Any other view's tree is a host temporary directory, copied + * with a reflink where the filesystem offers one. + */ +async function placeTree(view: WorkerStartupView, allowanceBytes: number, separateIdentity: boolean, privateIndex: string | undefined, + signal?: AbortSignal): Promise<{ root: string; index: string; flags: number; remove(): Promise }> { + const manager = nativeTurnTreeManager(view); + if (!manager) { + const root = mkdtempSync(join(tmpdir(), "brain-turn-data-")); + let index: string | undefined; + try { + if (separateIdentity) { chownSync(root, process.getuid!(), process.getgid!()); chmodSync(root, 0o750); } + index = privateIndex ?? createPrivateIndexDirectory(); + } catch (error) { removeCopy(root); throw error; } + const created = index; + return { root, index: created, flags: COPY_FLAGS, async remove() { + try { removeCopy(root); } finally { if (!privateIndex) removePrivateIndexDirectory(created); } + } }; + } + const id = randomUUID(), expected = join(dirname(view.brain), ".brain-native", "trees", id); + // Neither a lost reply nor the removal of a tree that failed to fill may be + // cancelled by the admission's abort: the same identity is released. + const release = async () => { await manager.releaseTurnTree(id); }; + try { + const tree = await manager.prepareTurnTree(id, allowanceBytes, signal); + const info = lstatSync(expected, { throwIfNoEntry: false }); + if (tree.id !== id || tree.path !== expected || tree.allowanceBytes !== allowanceBytes || !info?.isDirectory() || info.uid !== process.getuid?.()) + throw new Error("The native manager did not return this turn's own data-tree directory."); + const root = join(expected, "data"), index = privateIndex ?? join(expected, "index"); + mkdirSync(root, { mode: 0o700 }); + if (separateIdentity) chmodSync(root, 0o750); + if (!privateIndex) { + mkdirSync(index, { mode: 0o700 }); + // The worker identity shares the server's primary group; setgid keeps + // what its index update creates in that group. + if (separateIdentity) chmodSync(index, 0o2770); + } + return { root, index, flags: SHARED_FLAGS, remove: release }; + } catch (error) { + try { await release(); } + catch (releaseError) { throw new AggregateError([error, releaseError], `Native turn tree ${id} has an unknown outcome; its lease is reconciled by owner recovery.`); } + throw error; + } +} + /** * Copy the view into a new tree, before the worker launches. `index` is the * masked turn's private index, already built; an unmasked turn's is seeded @@ -331,29 +425,34 @@ export async function createTurnDataTree(options: { signal?: AbortSignal; }): Promise { const separateIdentity = Boolean(workerIdentityHelper()); - const root = mkdtempSync(join(tmpdir(), "brain-turn-data-")); - let index: string | undefined; + // The legacy root-level caches stay out under any provider rule; + // `.brain-cache/` only while a folder is masked (#2725). + const masks = options.masks, caches = Boolean(masks || options.providerRules); + // The `.env*` masks cover link targets at the brain path only, so the tree + // leaves those targets out as well. + const hidden = [...(masks?.buildFolders ?? []), ...envMaskedPaths(options.view.root, options.brainPath)]; + const copyPlan = planCopy(options.view.root, rel => { + const top = !rel.includes("/"); + if (top && (OMITTED.has(rel) || isEnvName(rel) || (caches && PROVIDER_CACHE_FILES.includes(rel)) || (masks && rel === PROVIDER_CACHE_DIR))) return true; + return hidden.some(folder => isWithin(folder, rel)); + }); + const seed = options.index ? { names: [], bytes: 0 } : indexSeed(options.view.root); + const placed = await placeTree(options.view, turnTreeAllowance(copyPlan.entries + seed.names.length, seed.bytes), separateIdentity, options.index, options.signal); + const { root, index, flags } = placed; try { - if (separateIdentity) { chownSync(root, process.getuid!(), process.getgid!()); chmodSync(root, 0o750); } - // The legacy root-level caches stay out under any provider rule; - // `.brain-cache/` only while a folder is masked (#2725). - const masks = options.masks, caches = Boolean(masks || options.providerRules); - // The `.env*` masks cover link targets at the brain path only, so the tree - // leaves those targets out as well. - const hidden = [...(masks?.buildFolders ?? []), ...envMaskedPaths(options.view.root, options.brainPath)]; - const copy = planCopy(options.view.root, root, rel => { - const top = !rel.includes("/"); - if (top && (OMITTED.has(rel) || isEnvName(rel) || (caches && PROVIDER_CACHE_FILES.includes(rel)) || (masks && rel === PROVIDER_CACHE_DIR))) return true; - return hidden.some(folder => isWithin(folder, rel)); - }); mkdirSync(join(root, INDEX_DIR), { mode: 0o755 }); - index = options.index ?? createPrivateIndexDirectory(); + const copy = copyPlan.apply(root, flags); // The index files are the largest; they start first. - await pooled([...options.index ? [] : seedIndex(options.view.root, index, separateIdentity), ...copy.files], options.signal); + try { await pooled([...seedIndex(options.view.root, seed.names, index, separateIdentity, flags), ...copy.files], options.signal); } + catch (error) { + if (flags === SHARED_FLAGS && ["EXDEV", "EOPNOTSUPP", "ENOTSUP", "EINVAL"].includes(errno(error) ?? "")) + throw new Error(`The turn's data tree cannot share the startup view's extents on the managed volume (${errno(error)}); no full copy is made in their place.`, { cause: error }); + throw error; + } copy.finish(); settleIndex(index, separateIdentity); } catch (error) { - try { removeCopy(root); } finally { if (index && !options.index) removePrivateIndexDirectory(index); } + await placed.remove(); throw error; } const tree: WorkerDataTree = Object.freeze({ root, index, ...(options.masks || options.providerRules @@ -380,7 +479,7 @@ export async function createTurnDataTree(options: { if (seen === null || effect.base === null) return seen === effect.base; return typeof effect.base === "string" ? seen.toString("utf8") === effect.base : seen.equals(effect.base); }; - let closed: Promise | undefined; + let closed: Promise | undefined, written = 0; return { ...(options.mount ? { mount: tree } : {}), index, @@ -389,7 +488,10 @@ export async function createTurnDataTree(options: { try { for (const effect of effects) { applied.add(effect.path); - writeTree(root, effect.path, admitted(effect) ? effect.content : null); + const content = admitted(effect) ? effect.content : null; + written += content === null ? 0 : typeof content === "string" ? Buffer.byteLength(content) : content.byteLength; + if (written > TURN_TREE_EFFECT_BYTES) throw new Error(`this turn's changes exceed its data tree's ${TURN_TREE_EFFECT_BYTES / 1024 / 1024} MiB allowance`); + writeTree(root, effect.path, content); } } catch (error) { // The Markdown is committed; the index cannot vouch for it any more. @@ -406,7 +508,7 @@ export async function createTurnDataTree(options: { close() { return closed ??= (async () => { await batch.idle(); - try { removeCopy(root); } finally { if (!options.index) removePrivateIndexDirectory(index!); } + await placed.remove(); })(); }, }; diff --git a/packages/ui-server/tests/helpers/native-journal-fixture.ts b/packages/ui-server/tests/helpers/native-journal-fixture.ts index 23cfcdf3f2..b17193a45c 100644 --- a/packages/ui-server/tests/helpers/native-journal-fixture.ts +++ b/packages/ui-server/tests/helpers/native-journal-fixture.ts @@ -122,6 +122,8 @@ export function createNativeJournalFixture(brain: string, root: string, copy = ( async prepareStage() { throw Error("Copied native fixture does not qualify output-stage runtime; provide explicit prepared worker test output."); }, async inspectStage() { throw Error("Copied native fixture has no output stage to inspect."); }, async releaseStage(id) { return { id, state: "deleted" }; }, + async prepareTurnTree() { throw Error("Copied native fixture has no managed volume for turn data trees."); }, + async releaseTurnTree(id) { return { id, state: "deleted" }; }, async poolStatus() { throw Error("Copied native fixture has no reference pool volume."); }, async poolCreate() { throw Error("Copied native fixture has no reference pool volume."); }, async poolSeal() { throw Error("Copied native fixture has no reference pool volume."); }, diff --git a/packages/ui-server/tests/native-brain-leases.test.ts b/packages/ui-server/tests/native-brain-leases.test.ts index f3dd1fa1ae..0c5112e125 100644 --- a/packages/ui-server/tests/native-brain-leases.test.ts +++ b/packages/ui-server/tests/native-brain-leases.test.ts @@ -354,3 +354,73 @@ test("pool leases recorded before checkpoints migrate without losing a row", asy expect(() => state.query("INSERT INTO native_pool_leases VALUES (?,'checkpoint',?,4096,'creating')").run(OTHER, ID), "REFERENCE_POOL_LEASES_ACCEPT_CHECKPOINTS").not.toThrow(); } finally { state.close(); await owner.close().catch(() => {}); await native.close(); rmSync(root, { recursive: true, force: true }); } }); + +/** A manager double that records turn-tree calls (#2911); `refuse` makes the next release fail, as a live reader does. */ +function treeManager(f: Awaited>) { + const calls: string[] = [], before: unknown[] = []; + let refuse: string | undefined; + f.native.client.prepareTurnTree = async (id, allowanceBytes) => { + before.push(f.state.query("SELECT state,kind,stage_allowance FROM native_root_leases WHERE id=?").get(id)); + calls.push(`prepare ${id}`); + return { id, path: join(f.root, ".brain-native", "trees", id), allowanceBytes }; + }; + f.native.client.releaseTurnTree = async id => { + calls.push(`release ${id}`); + if (refuse) { const message = refuse; refuse = undefined; throw Error(message); } + return { id, state: "deleted" as const }; + }; + return { calls, before, refuseNextRelease(message: string) { refuse = message; } }; +} + +test("turn trees are durable leases before RPC; only their owner, or recovery after its death, releases them", async () => { + const f = await fixture(), trees = treeManager(f); + const second = await createNativeBrainLeaseManager(f.native.client, f.options); + try { + expect(await f.owner.client.prepareTurnTree(ID, 8192)).toMatchObject({ id: ID, allowanceBytes: 8192 }); + expect(trees.before, "TREE_LEASE_DURABLE_BEFORE_CREATION_RPC").toEqual([{ state: "creating", kind: "tree", stage_allowance: 8192 }]); + expect(f.state.query("SELECT state FROM native_root_leases WHERE id=?").get(ID)).toEqual({ state: "sealed" }); + await expectRejection(second.client.releaseTurnTree(ID), "another live"); + await expectRejection(second.client.prepareTurnTree(ID, 8192), "another owner"); + expect(await second.recoverDeadOwners(), "LIVE_OWNER_KEEPS_ITS_TREE").toMatchObject({ released: [], retainedLive: 1 }); + expect(trees.calls.filter(call => call.startsWith("release"))).toEqual([]); + // The owner's process is gone: its tree is abandoned and recovered once. + f.state.query("UPDATE native_root_leases SET owner_start=owner_start||'-reused' WHERE id=?").run(ID); + trees.refuseNextRelease("A worker still mounts this turn tree"); + expect(await second.recoverDeadOwners(), "A_REFUSED_RELEASE_IS_RETAINED").toMatchObject({ released: [], unknown: [ID] }); + expect(f.state.query("SELECT state FROM native_root_leases WHERE id=?").get(ID)).toEqual({ state: "deleting" }); + expect(await second.recoverDeadOwners(), "DEAD_OWNER_TREE_RECOVERED").toMatchObject({ released: [ID], unknown: [] }); + expect(f.state.query("SELECT count(*) AS n FROM native_root_leases").get()).toEqual({ n: 0 }); + // A wrong path in the reply is never accepted as this lease's tree. + f.native.client.prepareTurnTree = async (id, allowanceBytes) => ({ id, path: join(f.root, "brain", id), allowanceBytes }); + await expectRejection(f.owner.client.prepareTurnTree(OTHER, 8192), "does not match"); + await expectRejection(f.owner.client.releaseTurnTree("33333333-3333-4333-8333-333333331790"), "no recorded lease"); + } finally { await second.close(); await f.close(); } +}); + +test("close releases this owner's turn trees", async () => { + const f = await fixture(), trees = treeManager(f); + try { + await f.owner.client.prepareTurnTree(ID, 4096); + await f.owner.close(); + expect(trees.calls, "CLOSE_RELEASES_OWNED_TREES").toEqual([`prepare ${ID}`, `release ${ID}`]); + expect(f.state.query("SELECT count(*) AS n FROM native_root_leases").get()).toEqual({ n: 0 }); + } finally { await f.close(); } +}); + +test("root leases recorded before turn trees migrate without losing a row", async () => { + const root = mkdtempSync(join(tmpdir(), "odysseus-native-lease-migrate-")), brain = join(root, "brain"), statePath = join(root, "native-leases.sqlite"); mkdirSync(brain); + const native = createNativeJournalFixture(brain, root), ready = await native.client.ready(); + const old = new Database(statePath); + old.exec(`CREATE TABLE native_root_leases (id TEXT PRIMARY KEY,owner_pid INTEGER NOT NULL,owner_start TEXT NOT NULL,owner_generation TEXT NOT NULL,owner_boot TEXT NOT NULL,owner_pid_namespace TEXT NOT NULL,state TEXT NOT NULL CHECK(state IN ('creating','sealed','deleting')),kind TEXT NOT NULL DEFAULT 'checkpoint' CHECK(kind IN ('checkpoint','stage')),checkpoint_uuid TEXT,stage_lower_id TEXT,stage_allowance INTEGER); + INSERT INTO native_root_leases VALUES ('${ID}',1,'1','old','previous-boot','1','sealed','stage','${"a".repeat(32)}','${OTHER}',4096);`); + old.close(); chmodSync(statePath, 0o600); + native.client.releaseStage = async id => ({ id, state: "deleted" as const }); + const owner = await createNativeBrainLeaseManager(native.client, { statePath, brainPath: brain, fsid: ready.fsid, brainUuid: ready.brainUuid }); + const state = new Database(statePath); + try { + expect(state.query("SELECT id,kind,stage_lower_id,stage_allowance FROM native_root_leases").all(), "ROOT_LEASES_SURVIVE_MIGRATION") + .toEqual([{ id: ID, kind: "stage", stage_lower_id: OTHER, stage_allowance: 4096 }]); + expect(() => state.query("INSERT INTO native_root_leases(id,owner_pid,owner_start,owner_generation,owner_boot,owner_pid_namespace,state,kind) VALUES (?,1,'1','g','b','1','creating','tree')").run(OTHER), + "ROOT_LEASES_ACCEPT_TREES").not.toThrow(); + } finally { state.close(); await owner.close().catch(() => {}); await native.close(); rmSync(root, { recursive: true, force: true }); } +}); diff --git a/packages/ui-server/tests/turn-data-tree-placement.test.ts b/packages/ui-server/tests/turn-data-tree-placement.test.ts new file mode 100644 index 0000000000..be060a4262 --- /dev/null +++ b/packages/ui-server/tests/turn-data-tree-placement.test.ts @@ -0,0 +1,118 @@ +/** + * Where a turn's data tree goes (#2911). A view the native manager acquired + * gets its tree from that manager, on the managed volume, filled only by + * reflinks; a copy that cannot share extents fails instead of allocating a + * full one, and only the manager removes the tree. The manager and Btrfs are + * doubled: the manager's own rules are proven in the ui-sdk suite and on the + * native host. + */ +import { afterEach, expect, spyOn, test } from "bun:test"; +import * as fs from "node:fs"; +import * as fsp from "node:fs/promises"; +import { Database } from "bun:sqlite"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { prepareNativeWorkerStartupView } from "../../ui-sdk/src/server/worker-startup-view"; +import { createTurnDataTree, TURN_TREE_EFFECT_BYTES, turnTreeAllowance } from "../src/brain/turn-data-tree"; + +const cleanups: Array<() => void | Promise> = []; +afterEach(async () => { for (const cleanup of cleanups.splice(0).reverse()) await cleanup(); }); +const NOTE = "---\ntype: note\ntitle: \"The voyage home\"\ncreated: 2026-07-12\nupdated: 2026-07-12\n---\n\nOdysseus sails for Ithaca.\n"; + +/** A managed store with one brain; `tree` decides whether its manager can place turn trees. */ +async function fixture(options: { tree?: boolean } = {}) { + const store = fs.mkdtempSync(join(tmpdir(), "odysseus-tree-placement-")), brain = join(store, "brain"); + cleanups.push(() => fs.rmSync(store, { recursive: true, force: true })); + fs.mkdirSync(join(brain, "notes"), { recursive: true }); + fs.writeFileSync(join(brain, "notes/voyage.md"), NOTE); + fs.mkdirSync(join(brain, ".brain-index")); + const db = new Database(join(brain, ".brain-index/brain.db")); + db.run("CREATE TABLE odysseus (crew TEXT)"); db.run("INSERT INTO odysseus VALUES ('Eurylochus')"); db.close(); + const actual = fs.statfsSync(store), statfs = spyOn(fs, "statfsSync").mockReturnValue({ ...actual, type: 0x9123683e }); + cleanups.push(() => statfs.mockRestore()); + const calls: string[] = []; + const manager = { + async checkpoint(id: string) { + const path = join(store, ".brain-native", "checkpoints", id); fs.cpSync(brain, path, { recursive: true }); + return { id, path, readOnly: true as const, sourceUuid: "0123456789abcdef0123456789abcdef", fsid: "00000000-0000-0000-0000-000000000001", + uuid: "00000000000000000000000000000002", rootId: "256", transaction: "12" }; + }, + async release(id: string) { fs.rmSync(join(store, ".brain-native", "checkpoints", id), { recursive: true, force: true }); return { id, state: "deleted" as const }; }, + async prepareStage(): Promise { throw Error("no stage in this fixture"); }, + async inspectStage(): Promise { throw Error("no stage in this fixture"); }, + async releaseStage(id: string) { return { id, state: "deleted" as const }; }, + ...(options.tree === false ? {} : { + async prepareTurnTree(id: string, allowanceBytes: number) { + calls.push(`prepare ${allowanceBytes}`); + const path = join(store, ".brain-native", "trees", id); fs.mkdirSync(path, { recursive: true }); + return { id, path, allowanceBytes }; + }, + async releaseTurnTree(id: string) { + calls.push("release"); + fs.rmSync(join(store, ".brain-native", "trees", id), { recursive: true, force: true }); + return { id, state: "deleted" as const }; + }, + }), + }; + const view = await prepareNativeWorkerStartupView(brain, manager); + cleanups.push(() => view.cleanup()); + // Reflinks are what is asked for; a host without Btrfs copies for the test. + const copy = fsp.copyFile, flags: number[] = []; + let refuse: string | undefined; + const spy = spyOn(fsp, "copyFile").mockImplementation((async (from: string, to: string, mode = 0) => { + flags.push(mode); + if (refuse) throw Object.assign(Error(`Odysseus's copy refused: ${refuse}`), { code: refuse }); + await copy(from, to, (mode & ~fs.constants.COPYFILE_FICLONE_FORCE) | fs.constants.COPYFILE_FICLONE); + }) as typeof fsp.copyFile); + cleanups.push(() => spy.mockRestore()); + const tmpTrees = () => fs.readdirSync(tmpdir()).filter(name => name.startsWith("brain-turn-data-")); + const before = new Set(tmpTrees()); + return { store, brain, view, calls, flags, refuse(code?: string) { refuse = code; }, + newTmpTrees: () => tmpTrees().filter(name => !before.has(name)), + create: () => createTurnDataTree({ brainPath: brain, view, maskPaths: [], mount: true, update: async () => {}, plan: async () => ({}) }) }; +} + +test("a managed view's tree is the manager's directory on the volume, filled only by reflinks", async () => { + const f = await fixture(), tree = await f.create(); + const base = join(f.store, ".brain-native", "trees"); + expect(tree.mount!.root.startsWith(base + "/") && tree.mount!.root.endsWith("/data"), "TREE_ON_THE_MANAGED_VOLUME").toBe(true); + expect(tree.index, "INDEX_BESIDE_THE_TREE").toBe(join(dirname(tree.mount!.root), "index")); + expect(fs.readFileSync(join(tree.mount!.root, "notes/voyage.md"), "utf8")).toBe(NOTE); + expect(fs.existsSync(join(tree.index, "brain.db"))).toBe(true); + expect(f.flags.length, "DOCUMENTS_AND_INDEX_COPIED").toBe(2); + expect(f.flags.every(mode => (mode & fs.constants.COPYFILE_FICLONE_FORCE) === fs.constants.COPYFILE_FICLONE_FORCE), "REFLINK_REQUIRED_NOT_REQUESTED").toBe(true); + // Two view entries (notes/ and its note) and one index file. + expect(f.calls, "ALLOWANCE_CHARGES_INDEX_AND_EFFECTS").toEqual([`prepare ${turnTreeAllowance(3, fs.statSync(join(f.brain, ".brain-index/brain.db")).size)}`]); + expect(turnTreeAllowance(2, 0) % 4096).toBe(0); + expect(f.newTmpTrees(), "NO_TEMPORARY_COPY").toEqual([]); + await tree.close(); + expect(f.calls.at(-1), "THE_MANAGER_REMOVES_THE_TREE").toBe("release"); + expect(fs.existsSync(tree.mount!.root)).toBe(false); +}); + +test.each(["EOPNOTSUPP", "EXDEV"])("a copy that cannot share extents fails the turn instead of copying: %s", async code => { + const f = await fixture(); + f.refuse(code); + await expect(f.create(), "NO_FULL_COPY_FALLBACK").rejects.toThrow("cannot share the startup view's extents"); + expect(f.calls.at(-1), "FAILED_TREE_RELEASED").toBe("release"); + expect(f.newTmpTrees(), "NO_TEMPORARY_COPY").toEqual([]); + expect(fs.readdirSync(join(f.store, ".brain-native", "trees"))).toEqual([]); +}); + +test("a managed view whose manager cannot place a tree is refused, not given a temporary copy", async () => { + const f = await fixture({ tree: false }); + await expect(f.create(), "MANAGED_VIEW_NEEDS_MANAGED_TREE").rejects.toThrow("no full-copy fallback"); + expect(f.newTmpTrees()).toEqual([]); +}); + +test("a turn's effects past the tree's allowance stop entering it and its index reads refuse", async () => { + const f = await fixture(), tree = await f.create(); + try { + tree.commit([{ path: "notes/ithaca.md", content: NOTE, base: null }]); + await tree.barrier(); + expect(fs.existsSync(join(tree.mount!.root, "notes/ithaca.md"))).toBe(true); + tree.commit([{ path: "notes/epic.md", content: new Uint8Array(TURN_TREE_EFFECT_BYTES), base: null }]); + expect(fs.existsSync(join(tree.mount!.root, "notes/epic.md")), "EFFECT_PAST_ALLOWANCE_NOT_WRITTEN").toBe(false); + await expect(tree.barrier(), "EFFECT_PAST_ALLOWANCE_REFUSES_INDEX_READS").rejects.toThrow("allowance"); + } finally { await tree.close(); } +}); From 358cc819ca1c544404ec0e45ba34f97d63544ee0 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 15 Nov 2026 20:53:03 +0000 Subject: [PATCH 2/4] test(native-proof): record turn-tree allocation and separate-UID tree isolation (#2911) --apply-timing records each mounted tree's btrfs filesystem du totals at seed and close and fails unless a seeded tree's exclusive bytes are below a tenth of its total. The separate-UID identity cell's strict provider-index turn applies the manager's private-path masks as the app does, and its worker proves it reads its own tree, cannot write it, and can reach neither a peer tree nor the manager's trees/ area. Co-Authored-By: Claude Opus 5.5 --- scripts/native-proof/README.md | 11 +++++++-- scripts/native-proof/hosted-app-child.ts | 22 ++++++++++++++++- scripts/native-proof/hosted-app.test.ts | 12 ++++++++++ scripts/native-proof/provider-index-worker.ts | 16 ++++++++++++- scripts/native-proof/provider-index.native.ts | 24 +++++++++++++++---- 5 files changed, 77 insertions(+), 8 deletions(-) diff --git a/scripts/native-proof/README.md b/scripts/native-proof/README.md index 09cff0defc..2445975830 100644 --- a/scripts/native-proof/README.md +++ b/scripts/native-proof/README.md @@ -32,7 +32,11 @@ barrier is timed at the bridge, and the copy and seed of the turn's data tree at admission, with the host load before and after, in `apply-timing.json`. The run fails unless both medians are at most 300 ms, the in-worker search sees all 20 edited notes, Claude's MCP server reads the data tree and pi's reader and -shell see the edits. It is a measurement, not part of the default +shell see the edits. Each mounted tree's Btrfs allocation (`btrfs filesystem +du`: total, exclusive and shared bytes) is recorded once seeded and again when +the turn closes it (#2911). The run fails unless every seeded tree's exclusive +bytes are below a tenth of its total, the proof that it shares the +checkpoint's extents. It is a measurement, not part of the default qualification. `--observation-timing` measures the turn journal's per-call cost (#2834). For @@ -80,7 +84,10 @@ for the short helper's entry into the authenticated manager stage mount namespace; dropping it makes the actual managed-stage launch refuse. The same cell reuses the owned 4 GiB Btrfs fixture for sealed stage authority and private checkpoint capture, and runs the fixed reader's descriptor/bounds/cancellation -controls. Its outer container permits the +controls. Its strict provider-index turn places its data tree on the managed +volume (#2911): the separate-UID worker reads its own tree, gets `EROFS` +writing it, and can neither read a peer turn's tree nor list the manager's +`trees/` area, and the manager has removed the tree once the turn ends. Its outer container permits the fixture helper's UID transition; the actual worker must still prove `NoNewPrivs=1` and zero effective capabilities. The other native cells retain their existing outer `no-new-privileges` setting. No helper is installed on the diff --git a/scripts/native-proof/hosted-app-child.ts b/scripts/native-proof/hosted-app-child.ts index 759f60c895..928e9d74f1 100644 --- a/scripts/native-proof/hosted-app-child.ts +++ b/scripts/native-proof/hosted-app-child.ts @@ -37,9 +37,29 @@ if (APPLY_TIMING) { // #2848: how long admission takes to copy the turn's data tree and seed its index. const trees = await import(join(source!, "packages/ui-server/src/brain/turn-data-tree.ts")); const createTurnDataTree = trees.createTurnDataTree; + // #2911: the tree's actual allocation on the managed volume, as Btrfs counts + // it, once seeded and again when the turn closes it: total (a plain copy's + // bytes), exclusive (allocated for this tree alone) and shared within it. + const allocation = async (stage: string, tree: { mount?: { root: string }; index: string }, masked: boolean) => { + if (!tree.mount) return; + // A masked turn's private index is outside the volume. + const paths = masked ? [tree.mount.root] : [tree.mount.root, tree.index]; + await Bun.spawn(["sync", "-f", tree.mount.root], { stdout: "ignore", stderr: "ignore" }).exited; + const run = Bun.spawn(["/usr/bin/btrfs", "filesystem", "du", "-s", "--raw", ...paths], { stdout: "pipe", stderr: "pipe" }); + const [out, errors, code] = await Promise.all([new Response(run.stdout).text(), new Response(run.stderr).text(), run.exited]); + const rows = out.trim().split("\n").slice(1).map(line => { + const [total, exclusive, shared, ...name] = line.trim().split(/\s+/); + return { path: name.join(" "), total: Number(total), exclusive: Number(exclusive), shared: Number(shared) }; + }); + event("turn_tree_allocation", { stage, masked, code, errors: errors.slice(-400), rows }); + }; spyOn(trees, "createTurnDataTree").mockImplementation(async (...args: Parameters) => { const start = performance.now(); const tree = await createTurnDataTree(...args); - event("turn_tree_seed", { ms: performance.now() - start, masked: Boolean((args[0] as { masks?: unknown }).masks), mounted: Boolean(tree.mount) }); + const masked = Boolean((args[0] as { masks?: unknown }).masks); + event("turn_tree_seed", { ms: performance.now() - start, masked, mounted: Boolean(tree.mount) }); + await allocation("seed", tree, masked); + const close = tree.close; + tree.close = async () => { await allocation("close", tree, masked); return close.call(tree); }; return tree; }); const bridges = await import(join(source!, "packages/ui-server/src/ws/bridge.ts")); diff --git a/scripts/native-proof/hosted-app.test.ts b/scripts/native-proof/hosted-app.test.ts index 9d5e5e9857..f0cadca98d 100644 --- a/scripts/native-proof/hosted-app.test.ts +++ b/scripts/native-proof/hosted-app.test.ts @@ -285,8 +285,14 @@ print(json.dumps(result))`; return { calls: ms.length, medianMs: ms.length ? median(ms) : null, p95Ms: ms.length ? [...ms].sort((a, b) => a - b)[Math.ceil(ms.length * 0.95) - 1] : null, maxMs: ms.length ? Math.max(...ms) : null, ms }; }; const search = rows.find(row => row.kind === "scheria_search"); const seeds = rows.filter(row => row.kind === "turn_tree_seed").map(row => ({ ms: row.ms, masked: row.masked, mounted: row.mounted })); + // #2911: each mounted tree's Btrfs allocation at seed and at close. + type Allocation = { stage: string; masked: boolean; code: number; errors: string; rows: { path: string; total: number; exclusive: number; shared: number }[] }; + const allocations = rows.filter(row => row.kind === "turn_tree_allocation") as unknown as Allocation[]; + const bytes = (row: Allocation, key: "total" | "exclusive" | "shared") => row.rows.reduce((sum, entry) => sum + entry[key], 0); const timing = { backend: BACKEND, appUid: APP_UID, files: FILES, bytes: BYTES, loadBefore, loadAfter, elapsedMs: performance.now() - timingStart, write: cell("write"), edit: cell("edit"), barriers: barriers.map(row => ({ name: row.name, ms: row.ms, ok: row.ok })), seeds, + allocations: allocations.map(row => ({ stage: row.stage, masked: row.masked, code: row.code, errors: row.errors, + totalBytes: bytes(row, "total"), exclusiveBytes: bytes(row, "exclusive"), sharedBytes: bytes(row, "shared"), rows: row.rows })), results: applies.map(row => ({ operation: row.operation, ok: row.ok, indexed: row.indexed, indexStatus: row.indexStatus })), search, terminal: sender.frames.filter(f => f.receiptAt >= timingStart && (f.type === "result" || f.type === "error")) }; writeFileSync(join(ARTIFACTS, "apply-timing.json"), JSON.stringify(timing, null, 2)); @@ -300,6 +306,12 @@ print(json.dumps(result))`; // live index still receives every edit when the turn ends. expect(barriers.some(row => row.ok && (row.name === "brain_search" || row.name === "mcp__brain__brain_search")), "APPLY_TIMING_SEARCH_WAITED_FOR_INDEX").toBe(true); expect(seeds.length, `APPLY_TIMING_TURN_TREE_SEEDED: ${JSON.stringify(seeds)}`).toBeGreaterThan(0); + // The trees share the checkpoint's extents: a plain copy would allocate + // every total byte (#2911). Growth is what the turn's own changes allocated. + const seeded = allocations.filter(row => row.stage === "seed"), closed = allocations.filter(row => row.stage === "close"); + expect(seeded.length > 0 && seeded.every(row => row.code === 0 && row.rows.length > 0), `APPLY_TIMING_TREE_ALLOCATION_RECEIPT: ${JSON.stringify(allocations)}`).toBe(true); + for (const row of seeded) expect(bytes(row, "exclusive"), `APPLY_TIMING_TREE_SHARES_THE_CHECKPOINT: ${JSON.stringify(row)}`).toBeLessThan(bytes(row, "total") / 10); + expect(closed.length, `APPLY_TIMING_TREE_GROWTH_RECORDED: ${JSON.stringify(allocations)}`).toBeGreaterThan(0); const live = new Database(join(brain, ".brain-index", "brain.db"), { readonly: true }); try { const indexed = (live.query("SELECT d.path FROM documents_fts f JOIN documents d ON d.id = f.rowid WHERE documents_fts MATCH 'harbour AND Nausicaa' ORDER BY d.path").all() as { path: string }[]).map(row => row.path); diff --git a/scripts/native-proof/provider-index-worker.ts b/scripts/native-proof/provider-index-worker.ts index e42400d37b..f858ec4414 100644 --- a/scripts/native-proof/provider-index-worker.ts +++ b/scripts/native-proof/provider-index-worker.ts @@ -1,6 +1,6 @@ /** Real CLI search/rebuild and core capture inside the admitted native worker. */ import { expect } from "bun:test"; -import { copyFileSync, mkdirSync, readdirSync, readFileSync, statSync } from "node:fs"; +import { copyFileSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { initContext } from "../../packages/core/src/lib/context.js"; import { openDatabase } from "../../packages/core/src/lib/db.js"; @@ -81,4 +81,18 @@ expect(readFileSync(join(captureRoot, capturePath), "utf8"), "NATIVE_CAPTURE_MAR expect(search(captured), "NATIVE_SCRATCH_CAPTURE_NEVER_WRITES_THE_PRIVATE_INDEX").toEqual([]); expect(search(sentinel), "NATIVE_CAPTURE_NEVER_EXPOSES_MASKED_DOCUMENT").toEqual([]); expect(sentinelFiles(), "NATIVE_PRIVATE_INDEX_HOLDS_NO_SENTINEL_BYTE_AT_TURN_END").toEqual([]); +// #2911: a strict worker's tree is on the managed volume. It reads its own +// tree, cannot change it, and cannot reach the manager's area or a peer's tree. +const peerTree = process.argv[5]; +if (profile === "strict") { + if (!peerTree) throw Error("The strict proof names a peer turn tree"); + const data = "/tmp/brain-worker-data"; + expect(readFileSync(join(data, "notes/provider-voyage.md"), "utf8"), "NATIVE_WORKER_READS_ITS_OWN_TREE").toContain(permitted); + const write = (() => { try { writeFileSync(join(data, "notes/odysseus-tree-write.md"), "Not this worker's to write.\n"); return "written"; } catch (error) { return (error as NodeJS.ErrnoException).code; } })(); + expect(write, "NATIVE_WORKER_CANNOT_MUTATE_ITS_TREE").toBe("EROFS"); + const peer = (() => { try { return readFileSync(join(peerTree, "data/odysseus-peer.md"), "utf8"); } catch (error) { return (error as NodeJS.ErrnoException).code; } })(); + expect(["ENOENT", "EACCES"], `NATIVE_WORKER_CANNOT_REACH_A_PEER_TREE: ${peer}`).toContain(peer ?? "unknown"); + const area = (() => { try { return readdirSync("/brain-fixture/.brain-native/trees"); } catch { return []; } })(); + expect(area, "NATIVE_WORKER_SEES_NO_TREE_AREA").toEqual([]); +} console.log(JSON.stringify({ nativeProviderIndexWorker: "pass", profile, uid: process.getuid?.(), capturePath })); diff --git a/scripts/native-proof/provider-index.native.ts b/scripts/native-proof/provider-index.native.ts index 64a2152c4f..6c9c2fbca5 100644 --- a/scripts/native-proof/provider-index.native.ts +++ b/scripts/native-proof/provider-index.native.ts @@ -32,6 +32,7 @@ export async function proveNativeProviderIndex(brain: string, manager: ReturnTyp writeFileSync(join(brain, "notes/provider-peer.md"), document("Odysseus shared raft", "A peer may change this note mid-turn.")); writeFileSync(join(brain, "context/policies/governance.md"), "---\nschema_version: 1\nproviders: [{ paths: [me/**], allow: [anthropic] }]\n---\nOdysseus keeps his oath with one provider.\n"); + const peerTrees: string[] = []; try { writeFileSync(join(brain, ".gitignore"), ".brain/scratch/\n.brain-index/\n"); const git = Bun.spawnSync(["/usr/bin/git", "init", "--shared=group", "-q", brain], @@ -45,19 +46,21 @@ export async function proveNativeProviderIndex(brain: string, manager: ReturnTyp try { expect(initial.query("SELECT path FROM documents WHERE content LIKE ?").all(`%${sentinel}%`), "NATIVE_REAL_INDEX_POSITIVE_SENTINEL_CONTROL").toEqual([{ path: "me/oath.md" }]); } finally { initial.close(); } + // The manager's private paths are every worker's masks, as the app applies them (#2911). + const privatePaths = (await manager.ready()).privatePaths; for (const profile of ["strict", "governed"] as const) { const root = `/identity-fixture/provider-index-${profile}`; mkdirSync(root, { mode: 0o700 }); const dbPath = join(root, "ui.db"), db = createUiDb(dbPath); const reports: string[] = []; - const execution = createHostExecution({ brainPath: brain, dbPath, nativeManager: manager, profile, requireGate: true }); + const execution = createHostExecution({ brainPath: brain, dbPath, nativeManager: manager, nativeMaskPaths: privatePaths, profile, requireGate: true }); execution.attach(db); - const turns = createGovernedTurns({ nativeManager: manager, brainPath: brain, execution, profile, maskPaths: [], + const turns = createGovernedTurns({ nativeManager: manager, brainPath: brain, execution, profile, maskPaths: privatePaths, index: async () => {}, report: message => reports.push(message), privateIndexCommand: [process.execPath, "/repo/packages/core/src/cli/brain.ts"] }); let hold: Awaited> | undefined; let prepared: Awaited> | undefined; - let privateIndex: string | undefined; + let privateIndex: string | undefined, treeRoot: string | undefined; try { hold = await turns.begin(`native-private-index-${profile}`, new AbortController().signal); expect(hold.managedStorage, "NATIVE_PROVIDER_INDEX_MANAGED_ADMISSION").toBe(true); @@ -66,6 +69,7 @@ export async function proveNativeProviderIndex(brain: string, manager: ReturnTyp const scratch = hold.sandbox.areas.find(area => area.name === "scratch")?.mount; expect(scratch?.writable, `NATIVE_PROVIDER_INDEX_WRITABLE_SCRATCH: ${JSON.stringify(scratch)}`).toBe(true); privateIndex = hold.sandbox.providerMasks!.index!; + treeRoot = hold.sandbox.dataTree?.root; const info = statSync(privateIndex); // The worker's user namespace deliberately does not map the server UID. expect(info.uid, "NATIVE_PRIVATE_INDEX_SERVER_OWNER").toBe(21001); @@ -99,10 +103,20 @@ export async function proveNativeProviderIndex(brain: string, manager: ReturnTyp expect(command, "NATIVE_STRICT_PROVIDER_INDEX_KEEPER_NAMESPACE").toContain(Bun.which("nsenter")!); expect(command, "NATIVE_STRICT_PROVIDER_INDEX_KEEPER_PID").toContain(String(storage.namespacePid)); } else expect(hold.startupView, "NATIVE_GOVERNED_PROVIDER_INDEX_LIVE_BRAIN").toBeUndefined(); + // #2911: the strict tree is the manager's, on the managed volume; a + // peer's tree beside it holds a note the worker must never reach. + let peerTree = ""; + if (profile === "strict") { + const root = hold.sandbox.dataTree?.root ?? ""; + expect(root.startsWith(join(brain, "..", ".brain-native", "trees") + "/"), `NATIVE_STRICT_TREE_ON_THE_MANAGED_VOLUME: ${root}`).toBe(true); + const peer = await manager.prepareTurnTree(crypto.randomUUID(), 1024 * 1024); + peerTrees.push(peer.id); peerTree = peer.path; + mkdirSync(join(peer.path, "data")); writeFileSync(join(peer.path, "data/odysseus-peer.md"), document("Another turn's note", "Not this turn's.")); + } const launch = { brainPath: brain, sandbox: hold.sandbox, ...(prepared ? { startupView: prepared.view, preparedOutput: prepared } : {}), stateBytes: MIB, turnTempBytes: 16 * MIB, env: { PATH: "/usr/local/bin:/usr/bin:/bin", BRAIN_ROOT: brain, HOME: "/tmp", NO_COLOR: "1" }, - command: [process.execPath, "/repo/scripts/native-proof/provider-index-worker.ts", profile, `${info.dev}:${info.ino}`, `applied:${applied}:notes/provider-applied-${profile}.md`] }; + command: [process.execPath, "/repo/scripts/native-proof/provider-index-worker.ts", profile, `${info.dev}:${info.ino}`, `applied:${applied}:notes/provider-applied-${profile}.md`, peerTree] }; const result = await (async () => { const worker = launchAgentWorker(launch), timer = setTimeout(() => worker.kill("SIGKILL"), 30_000); worker.stdin.end(); @@ -134,6 +148,7 @@ export async function proveNativeProviderIndex(brain: string, manager: ReturnTyp } } expect(privateIndex && existsSync(privateIndex), "NATIVE_PRIVATE_INDEX_REMOVED_AFTER_TURN").toBe(false); + expect(treeRoot && existsSync(treeRoot), "NATIVE_MANAGER_REMOVED_THE_TREE_AFTER_TURN").toBe(false); // The peer's copy is live, permitted text now; the next profile's turn // would rightly index it. Restore the note before that turn's checkpoint. writeFileSync(join(brain, "notes/provider-peer.md"), document("Odysseus shared raft", "A peer may change this note mid-turn.")); @@ -206,6 +221,7 @@ export async function proveNativeProviderIndex(brain: string, manager: ReturnTyp console.log(JSON.stringify({ nativeProviderHardlink: "refused", profile })); } } finally { + for (const id of peerTrees) await manager.releaseTurnTree(id); for (const rel of ["me", "context", ".git", ".gitignore", ".brain-index", ".brain-cache", "notes/provider-voyage.md", "notes/provider-peer.md", "notes/provider-applied-strict.md", "notes/provider-applied-governed.md", "notes/oath-alias.txt", ".brain/scratch/provider-index-strict", ".brain/scratch/provider-index-governed"]) rmSync(join(brain, rel), { recursive: true, force: true }); From 39157a0341dc3a4da62a679f888ca25a67cd33b1 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 16 Nov 2026 01:27:18 +0000 Subject: [PATCH 3/4] test(ui-server): a view no manager acquired keeps the temporary tree (#2911) Policy suites stand a copied view in for a managed one by spying isManagedWorkerStartupView; nativeTurnTreeManager now reads the view's own acquisition instead, so such a view keeps the temporary copy. The merge commit before this one carries that fix and the native proof's peer-tree argument, which named an absolute path the launcher binds back in. Co-Authored-By: Claude Opus 5.5 --- .../tests/turn-data-tree-placement.test.ts | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/packages/ui-server/tests/turn-data-tree-placement.test.ts b/packages/ui-server/tests/turn-data-tree-placement.test.ts index be060a4262..7e8048b861 100644 --- a/packages/ui-server/tests/turn-data-tree-placement.test.ts +++ b/packages/ui-server/tests/turn-data-tree-placement.test.ts @@ -12,7 +12,9 @@ import * as fsp from "node:fs/promises"; import { Database } from "bun:sqlite"; import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; +import * as startup from "../../ui-sdk/src/server/worker-startup-view"; import { prepareNativeWorkerStartupView } from "../../ui-sdk/src/server/worker-startup-view"; +import { createFixtureWorkerStartupView } from "../../ui-sdk/tests/helpers/worker-startup-view-fixture"; import { createTurnDataTree, TURN_TREE_EFFECT_BYTES, turnTreeAllowance } from "../src/brain/turn-data-tree"; const cleanups: Array<() => void | Promise> = []; @@ -116,3 +118,18 @@ test("a turn's effects past the tree's allowance stop entering it and its index await expect(tree.barrier(), "EFFECT_PAST_ALLOWANCE_REFUSES_INDEX_READS").rejects.toThrow("allowance"); } finally { await tree.close(); } }); + +test("a view no manager acquired keeps the temporary copy, even where another check treats it as managed", async () => { + const store = fs.mkdtempSync(join(tmpdir(), "odysseus-tree-unmanaged-")), brain = join(store, "brain"); + cleanups.push(() => fs.rmSync(store, { recursive: true, force: true })); + fs.mkdirSync(join(brain, "notes"), { recursive: true }); fs.writeFileSync(join(brain, "notes/voyage.md"), NOTE); + const view = createFixtureWorkerStartupView(brain); + cleanups.push(() => view.cleanup()); + // Policy suites stand a copied view in for a managed one this way. + const managed = spyOn(startup, "isManagedWorkerStartupView").mockReturnValue(true); + cleanups.push(() => managed.mockRestore()); + expect(startup.nativeTurnTreeManager(view), "UNACQUIRED_VIEW_HAS_NO_TREE_MANAGER").toBeUndefined(); + const tree = await createTurnDataTree({ brainPath: brain, view, maskPaths: [], mount: true, update: async () => {}, plan: async () => ({}) }); + try { expect(tree.mount!.root.startsWith(join(tmpdir(), "brain-turn-data-")), "UNACQUIRED_VIEW_TREE_IS_TEMPORARY").toBe(true); } + finally { await tree.close(); } +}); From 24787de0031b0f5dc0896b7f62d45d70e8163781 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 16 Nov 2026 02:29:28 +0000 Subject: [PATCH 4/4] test(native-proof): a governed provider-index turn has no mounted tree to remove (#2911) The tree-removal check read the governed turn's absent mount as a failure. Only the strict turn mounts a tree; the governed one now asserts it has none. Co-Authored-By: Claude Opus 5.5 --- scripts/native-proof/provider-index.native.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/scripts/native-proof/provider-index.native.ts b/scripts/native-proof/provider-index.native.ts index 1d1b10d890..47c0151ca0 100644 --- a/scripts/native-proof/provider-index.native.ts +++ b/scripts/native-proof/provider-index.native.ts @@ -150,7 +150,9 @@ export async function proveNativeProviderIndex(brain: string, manager: ReturnTyp } } expect(privateIndex && existsSync(privateIndex), "NATIVE_PRIVATE_INDEX_REMOVED_AFTER_TURN").toBe(false); - expect(treeRoot && existsSync(treeRoot), "NATIVE_MANAGER_REMOVED_THE_TREE_AFTER_TURN").toBe(false); + // A governed turn's tree feeds only its index updates and is never mounted. + if (profile === "strict") expect(treeRoot?.startsWith("/") && existsSync(treeRoot), `NATIVE_MANAGER_REMOVED_THE_TREE_AFTER_TURN: ${treeRoot}`).toBe(false); + else expect(treeRoot, "NATIVE_GOVERNED_TREE_IS_NOT_MOUNTED").toBeUndefined(); // The peer's copy is live, permitted text now; the next profile's turn // would rightly index it. Restore the note before that turn's checkpoint. writeFileSync(join(brain, "notes/provider-peer.md"), document("Odysseus shared raft", "A peer may change this note mid-turn."));