Skip to content

CONTRACT: feat(ui-sdk,ui-server): place a turn's data tree on the managed volume by reflink (#2911) - #4050

Merged
schlessera merged 6 commits into
mainfrom
refactor/2911-managed-turn-trees
Nov 16, 2026
Merged

schlessera merged 6 commits into
mainfrom
refactor/2911-managed-turn-trees

Conversation

@schlessera

@schlessera schlessera commented Nov 15, 2026 •

Copy link
Copy Markdown
Owner

Refs #2911

What changed

A strict, voice or autonomous turn on managed native storage now keeps its data tree on the managed Btrfs volume, beside the live brain, instead of making a full copy on the server's temporary directory. The tree shares its checkpoint's extents. This is option A of the 2026-10-25 maintainer ruling.

  • Manager. prepareTurnTree(id, allowanceBytes) creates <store>/.brain-native/trees/<id>, owned by the fixed app UID and group with mode 0710. It sits under a root-owned trees/ directory (0710) that is outside the live subvolume and every checkpoint. releaseTurnTree(id) refuses while any process's mount namespace still holds a mount of the tree, which it reads from every /proc/<pid>/mountinfo. Otherwise it removes the tree with Python's descriptor-relative shutil.rmtree, observes btrfs filesystem sync, and only then credits the charge. Trees are kind: "tree" intents in the existing intent store, with an independent <id>.allowance record, so a quarantined receipt keeps its charge. Deleted intents fence a delayed create. (packages/ui-sdk/src/server/native-brain-manager.ts, native-turn-trees.ts)
  • Admission. A tree is admitted only while the live trees' allowances, this one and one emergency reserve's worth of headroom fit in statfs free space, and only with an armed reserve. statfs counts shared extents once, so they are never charged as copies. A tree's own growth lowers free space while its allowance stays charged, which is conservative. The allowance (turnTreeAllowance) is 4 KiB of metadata per entry, plus twice the seeded index, plus the 64 MiB effect bound, plus 1 MiB.
  • Server. createTurnDataTree asks the view's manager for the tree when the view is managed (nativeTurnTreeManager). It plans the copy before it creates anything, puts the documents in data/ and an unmasked turn's index in index/, and copies with COPYFILE_FICLONE_FORCE. A file that cannot be reflinked fails admission and releases the tree; no full copy runs. A managed view whose manager cannot place a tree is refused. Committed effects past TURN_TREE_EFFECT_BYTES (64 MiB) stop entering the tree, and the turn's index reads then refuse. close() hands removal to the manager. Unmanaged views (test fixtures) keep the temporary-directory copy. A masked turn's private index stays where it is built.
  • Lease owner. Each tree is a tree root lease, recorded before the request. Only its owner releases it, or dead-owner recovery does once the owner is gone. close() releases this owner's trees. The lease table's kind check migrates in place.
  • Docs. New section in docs/decisions/native-brain-storage.md (placement, ownership, allocation, records, release and recovery), an amendment to the data-tree ruling in governed-writable-workers.md, the contract index, package-api.md, the API reports and a minor changeset.

Contract

Additive. The native manager client and lease owner gain prepareTurnTree/releaseTurnTree and NativeTurnTree. NativeRecoveryRecord.kind gains tree and an optional treeRequest. Ready facts and storage limits are unchanged, and no field is removed or retyped. The CONTRACT: commit carries the docs.

Guard checklist (proportionate containment)

  • Trigger. Three guards. (1) Tree admission refuses (capacity) when the allowances plus reserve headroom exceed free space, or the reserve is consumed. It refuses (unknown) when a quarantined tree's allowance is unknown. (2) Tree release refuses (unavailable) while a process mounts the tree or the mount census is unreadable. (3) The managed copy fails when a reflink is refused. None of them covers growth past an admitted allowance: qgroups stay off by decision. The volume's hard bound and the separately allocated emergency reserve bound that growth.
  • Restriction. (1) and (3) refuse one turn's admission. (2) keeps one tree and its charge. Checkpoints, stages, recovery and other turns are untouched, and nothing narrower than the turn or the tree holds the uncertain state.
  • Restricted mode considered. For (1) and (3), a full copy on the temporary directory. The ruling rejects it as an unbounded fallback ("do not silently substitute an unbounded full-copy fallback"). For (2), removing anyway, which could pull a live worker's input away.
  • Clearing. Automatic. (1) clears when trees release and reclamation is observed. (2) clears when the reader exits: the lease stays deleting and owner recovery retries it. (3) is a host qualification fact. Only an unknown quarantined allowance needs the owner, to restore its record from proof, as for stages.
  • Record. The refusal message reaches the turn's error. Quarantine goes to the manager's host-private recovery diagnostics. A retained deleting lease is in the lease database.
  • Scope test. an unreadable tree receipt restricts tree admission only (checkpoint admission still works) and a tree a worker still mounts is neither removed nor credited (a peer tree is untouched), in packages/ui-sdk/tests/native-manager-turn-trees.test.ts.

Proof

bun run check:pr --base origin/main    # Local preflight passed (1286 tests in affected files), after merging origin/main (#4035, #4037)
bun run typecheck                      # clean
bun run build                          # clean (exports changed)
bun run api-report                     # regenerated
{"version":1,"kind":"brain-check-pr-receipt","head":"0fb9b18e8cc5df0e4d8451e9c24ec97c9d15b19a","base":"origin/main","mode":"focused","startedAt":"2026-11-16T05:32:16.619Z","finishedAt":"2026-11-16T05:33:46.550Z","checks":[{"name":"all lint and leakage gates","categories":["changeset"],"outcome":"passed","elapsedMs":12637.662516},{"name":"environment documentation","categories":["changeset"],"outcome":"passed","elapsedMs":115.01394400000027},{"name":"pending changeset package names","categories":["changeset"],"outcome":"passed","elapsedMs":73.58440900000096},{"name":"contribution changeset","categories":["changeset"],"outcome":"passed","elapsedMs":21.488292},{"name":"affected fast invariants","categories":["verify","unit"],"outcome":"passed","elapsedMs":77067.296422}]}

New tests:

  • packages/ui-sdk/tests/native-manager-turn-trees.test.ts (7). Real manager, intents and filesystem; only the kernel operations are doubled. Covers ownership and placement outside the brain and checkpoints; the reserve headroom and capacity refusal; reclamation credited only after an observed commit (a failing commit keeps the charge, and a link inside the tree is not followed); live-reader refusal (a peer's mount or another filesystem is no reader); restart and identity fences; quarantine proportionality; and the census refusing an unreadable mountinfo.
  • packages/ui-server/tests/turn-data-tree-placement.test.ts (5): the managed tree lands in the manager's directory, every copy requests FICLONE_FORCE, the allowance matches turnTreeAllowance, and no temporary copy is made. EOPNOTSUPP/EXDEV fail the turn and release the tree. A managed view without tree operations is refused. Effects past the bound refuse index reads.
  • packages/ui-server/tests/native-brain-leases.test.ts (+3): the lease is durable before the RPC; a live owner keeps its tree; a refused release is retained and then recovered; a wrong reply path is rejected; close releases this owner's trees; the old lease table migrates without losing a row.

Mutation receipts (each restored; the named assertion failed):

Mutation Failed
drop + fixed.recoveryReserveBytes from tree admission REFUSES_PAST_RESERVE_HEADROOM, LIVE_READER_KEEPS_THE_CHARGE, QUARANTINED_TREE_STAYS_CHARGED
drop treeBytes (live charges) from admission REFUSES_PAST_RESERVE_HEADROOM, RESTART_RETAINS_TREE_CHARGE
skip the live-reader refusal LIVE_READER_REFUSES_CLEANUP
drop the observed btrfs filesystem sync before crediting UNOBSERVED_COMMIT_REFUSES
managed copy with COPYFILE_FICLONE instead of _FORCE REFLINK_REQUIRED_NOT_REQUESTED, NO_FULL_COPY_FALLBACK
always place on the temporary directory TREE_ON_THE_MANAGED_VOLUME, NO_FULL_COPY_FALLBACK
nativeTurnTreeManager returns undefined instead of refusing MANAGED_VIEW_NEEDS_MANAGED_TREE
drop the effect bound EFFECT_PAST_ALLOWANCE_NOT_WRITTEN
skip the lease-table migration ROOT_LEASES_ACCEPT_TREES
nativeTurnTreeManager trusts isManagedWorkerStartupView (the first head's code) UNACQUIRED_VIEW_HAS_NO_TREE_MANAGER fails with the CI TypeError

Sandbox-only failures, identical on an untouched origin/main worktree: two worker-launch cases in turn-data-tree.test.ts (no user namespaces), and four in native-host-inputs.test.ts/native-worker-startup-view.test.ts. The manager suites need umask 022 here, the same as on main.

Native proof (pending hosted heavy feedback)

This host has no root or loop device, so the native cells run through hosted heavy feedback on this draft:

  • prove-native-host.ts --apply-timing: apply-timing.json now records each mounted tree's btrfs filesystem du total, exclusive and shared bytes at seed and at close, which is the allocation receipt plus changed-extent growth. It fails unless the seeded exclusive bytes are below a tenth of the total. The seed ms keeps the admission comparison against the ui-server: a strict turn's data tree copies the whole startup view at every admission #2891 pool.
  • prove-worker-identity.ts (separate UID): the strict provider-index turn now applies the manager's private-path masks as the app does. The worker proves it reads its own tree, gets EROFS writing it, and can read neither a peer tree's note nor the manager's trees/ listing. The manager has removed the tree once the turn ends.

Heavy feedback runs 43760955496 and 43766434173 both timed out at admission waiting for a slot. Their proof jobs were skipped, so neither is a test result. Run 43772552411 ran at 358cc819. Browser, layout, captures, endurance, pack, verify, runtime and unit (1) passed. Two real failures came from this PR, and both are fixed at 39157a03:

  • unit (2)–unit (4): private-index-cache, provider-allowed-route and provider-recipient-session stand a copied view in for a managed one by spying isManagedWorkerStartupView. The first head's nativeTurnTreeManager trusted that check and then crashed on nativeInputs.get(view)! (TypeError). It now reads the view's own acquisition, so such a view keeps the temporary copy. The new regression test fails with that same TypeError against the old code. Locally those three files still fail 8 cases on worker launch (no user namespaces in this sandbox), and an untouched origin/main worktree fails the same 8. The odysseus/penelope PLANNED_WORKER_FAILURE_AFTER_DIAGNOSTICS lines are a planned failure inside another suite's fixture, not a failing test.
  • runtime_host: in prove-worker-identity.ts, the new NATIVE_WORKER_CANNOT_REACH_A_PEER_TREE check read the peer's note. The proof had passed the peer tree's absolute path as a worker command argument, and the launcher binds an existing absolute command argument back in as a runtime read path. That is the proof exposing itself, not a placement gap: the worker's other checks held (it read its own tree and got EROFS writing it). The worker now receives only the peer's identity and builds the path itself. Every prove-native-host.ts cell passed. The pi UID 0 hosted-app.test.ts failure in the log is the job's labelled expected-failure control.

Run 43789449215 at 39157a03 confirmed both fixes. All four unit shards, browser, layout, runtime, captures, endurance, pack and verify passed, and so did the strict provider-index turn's isolation checks (its own tree readable, EROFS on write, no peer tree, no trees/ listing, tree removed after the turn). runtime_host failed on one more assertion of this PR's proof: NATIVE_MANAGER_REMOVED_THE_TREE_AFTER_TURN ran in the governed iteration too, where no tree is mounted, so undefined && … is not false. At 24787de0 that check runs only for the strict turn, and the governed turn instead asserts it has no mounted tree. The confirming run 43800954882 at 24787de0 passed in every category, runtime_host included.

Open verification item: hosted CI never passes --apply-timing, so the allocation receipt still needs one native-host run of bun scripts/prove-native-host.ts --backend=pi --app-uid=1000 --apply-timing, with its apply-timing.json allocations and seeds posted here.

Anything left open

Acceptance criteria 2 and 5 of #2911 require the native --apply-timing measurement, and hosted CI cannot run it. So this PR uses Refs #2911, and the issue stays open with needs: human for one run of bun scripts/prove-native-host.ts --backend=pi --app-uid=1000 --apply-timing on a native host (root, loop device, Btrfs). The completion evidence is its apply-timing.json: allocations with seeded exclusive bytes below a tenth of the total, the close-time growth, and seeds milliseconds compared against the #2891 pool. Everything else in the criteria is in this PR and its hosted proof.

Collisions

bun scripts/collisions.ts --json --pr 4050 at head 24787de0031b0f5dc0896b7f62d45d70e8163781: textual overlap with #4060 (native-brain-leases.test.ts, both append tests), with #4064 (native-brain-manager-client.ts, docs/integration-contract.md), with #4073 (packages/ui-sdk/src/internal.ts), and with #4067 (docs/integration-contract.md index entry). Each is an adjacent additive section, method or export. The rest are closure overlaps only.

🤖 Generated with Claude Code

schlessera and others added 2 commits November 15, 2026 20:53
…aged 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 <noreply@anthropic.com>
… 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 <noreply@anthropic.com>
@schlessera schlessera added this to the 0.45.0 milestone Nov 15, 2026
@schlessera schlessera added type: refactor Structure changes; behaviour does not. No changeset-visible effect. area: ui-sdk Wire protocol, runtime schemas, the server and client SDK surfaces. area: ui-server Hono app factory: turn coordinator, auth, session catalog, routes, cron. contract Touches the integration contract: CONTRACT: commit, contract doc updated in the same commit. labels Nov 15, 2026
This was referenced Nov 15, 2026
schlessera and others added 2 commits November 16, 2026 01:27
…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 <noreply@anthropic.com>
…e 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 <noreply@anthropic.com>
@schlessera
schlessera marked this pull request as ready for review November 16, 2026 05:36
@schlessera
schlessera merged commit 8e35d4c into main Nov 16, 2026
52 of 54 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: ui-sdk Wire protocol, runtime schemas, the server and client SDK surfaces. area: ui-server Hono app factory: turn coordinator, auth, session catalog, routes, cron. contract Touches the integration contract: CONTRACT: commit, contract doc updated in the same commit. type: refactor Structure changes; behaviour does not. No changeset-visible effect.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant