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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/2911-managed-turn-trees.md
Original file line number Diff line number Diff line change
@@ -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.
2 changes: 2 additions & 0 deletions api-report/ui-sdk.txt
Original file line number Diff line number Diff line change
Expand Up @@ -1390,6 +1390,7 @@ export "./internal" (./src/internal.ts)
type NativePoolRecord
type NativePoolState
type NativePoolStatus
type NativeTurnTree
ORIENTATION_MAX_BYTES
OUTWARD_VOICE_REFUSAL
type ObservedWorkerFile
Expand Down Expand Up @@ -1517,6 +1518,7 @@ export "./internal" (./src/internal.ts)
mountPointsUnder
nativeFileVersion
nativeObservationIdentity
nativeTurnTreeManager
nativeWorkerStartupInput
observeClassification
observeOutwardPlan
Expand Down
16 changes: 15 additions & 1 deletion api-report/ui-server.txt
Original file line number Diff line number Diff line change
Expand Up @@ -1718,13 +1718,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 {
Expand Down Expand Up @@ -1753,6 +1756,12 @@ signatures (every public export and the types it is made of)
changes: AsyncIterable<NativeStageChange>;
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;
Expand Down Expand Up @@ -2512,6 +2521,7 @@ signatures (every public export and the types it is made of)
}>;
poolWithdraw: (id: string, signal?: AbortSignal) => Promise<NativePoolRecord>;
prepareStage: (id: string, checkpointId: string, allowanceBytes: number, signal?: AbortSignal) => Promise<NativeStage>;
prepareTurnTree: (id: string, allowanceBytes: number, signal?: AbortSignal) => Promise<NativeTurnTree>;
readCheckpoint: (id: string, path: string, maximum: number, expectedWorkerUid: number, signal?: AbortSignal) => Promise<NativeCheckpointFile>;
readStage: (id: string, path: string, maximum: number, expectedWorkerUid: number, signal?: AbortSignal) => Promise<NativeCheckpointFile>;
ready: (signal?: AbortSignal) => Promise<NativeManagerReady>;
Expand All @@ -2523,6 +2533,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<NativeCheckpointMetadata | null>;
statStage: (id: string, path: string, expectedWorkerUid: number, signal?: AbortSignal) => Promise<NativeCheckpointMetadata | null>;
};
Expand Down
19 changes: 19 additions & 0 deletions docs/decisions/governed-writable-workers.md
Original file line number Diff line number Diff line change
Expand Up @@ -952,6 +952,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
Expand Down
70 changes: 70 additions & 0 deletions docs/decisions/native-brain-storage.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<pid>/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
Expand Down
9 changes: 9 additions & 0 deletions docs/integration-contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).

## JeV reranking through the provider relay (additive, 0.45.0, #3792)

The CLI provider relay gains the `typesafe` family, `x-brain-provider:
Expand Down
29 changes: 29 additions & 0 deletions docs/integration-contract/package-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -4246,6 +4246,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: `<store>/.brain-native/trees/<id>`, 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
Expand Down
4 changes: 2 additions & 2 deletions packages/ui-sdk/src/internal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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";

Expand Down
6 changes: 5 additions & 1 deletion packages/ui-sdk/src/server/native-brain-manager-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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<NativeStage> => 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<NativeTurnTree> => 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<NativeStageInspection> => {
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");
Expand Down
Loading
Loading