diff --git a/.changeset/reference-pool-growth-status.md b/.changeset/reference-pool-growth-status.md new file mode 100644 index 0000000000..31811913ba --- /dev/null +++ b/.changeset/reference-pool-growth-status.md @@ -0,0 +1,7 @@ +--- +"@schlessera/brain-ui-sdk": minor +--- + +**Reference pool growth status (#3515).** `brain-native-store pool growth ` and the native manager client's `poolGrowth()` report residual growth on the host-only reference pool from the same simple-quota owner charges as admission. They report each worktree's and each changed refresh's charge against its chain's cold acquisition, and the sources retained per published repository and revision across views. A flag fires strictly above the ruled thresholds: 25 % for a worktree, 0.75× for a refresh, and more than two retained sources. Each flag carries the measured bytes and its threshold. + +The status is read-only, reports no forecast savings or freed capacity, and reads missing accounting as `unavailable`, never zero. Sealing now records each root's charge, so the basis survives release. Background deduplication is rejected, as recorded in the pool decision. diff --git a/api-report/ui-server.txt b/api-report/ui-server.txt index 5d70a46154..34e2487ae3 100644 --- a/api-report/ui-server.txt +++ b/api-report/ui-server.txt @@ -1630,6 +1630,54 @@ signatures (every public export and the types it is made of) } NativePoolCreatePurpose (packages/ui-sdk/src/server/native-brain-manager-protocol.ts) export type NativePoolCreatePurpose = Exclude; + NativePoolGrowth (packages/ui-sdk/src/server/native-brain-manager-protocol.ts) + export interface NativePoolGrowth { + basis: "btrfs-space-info-disk-used+simple-quota-owner"; + state: "available" | "unavailable"; + reason: string | null; + generation: string | null; + thresholds: { + worktreeRatio: number; + refreshRatio: number; + retainedSources: number; + }; + worktrees: NativePoolGrowthComparison[]; + refreshes: NativePoolGrowthComparison[]; + sources: NativePoolGrowthSources[]; + flags: NativePoolGrowthFlag[]; + omitted: number; + } + NativePoolGrowthComparison (packages/ui-sdk/src/server/native-brain-manager-protocol.ts) + export interface NativePoolGrowthComparison { + id: string; + from: string; + cold: string | null; + ownerBytes: number | null; + basisBytes: number | null; + thresholdBytes: number | null; + state: "available" | "unavailable"; + flagged: boolean; + } + NativePoolGrowthFlag (packages/ui-sdk/src/server/native-brain-manager-protocol.ts) + export interface NativePoolGrowthFlag { + kind: "worktree" | "refresh" | "retained-sources"; + subject: string; + observedBytes: number | null; + thresholdBytes: number | null; + threshold: number; + observedCount: number | null; + } + NativePoolGrowthSources (packages/ui-sdk/src/server/native-brain-manager-protocol.ts) + export interface NativePoolGrowthSources { + name: string; + roots: { + id: string; + view: string; + ownerBytes: number | null; + }[]; + ownerBytes: number | null; + flagged: boolean; + } NativePoolRecord (packages/ui-sdk/src/server/native-brain-manager-protocol.ts) export interface NativePoolRecord { id: string; @@ -2502,6 +2550,7 @@ signatures (every public export and the types it is made of) poolCheckpoint: (id: string, from: string, signal?: AbortSignal) => Promise; poolCreate: (id: string, purpose: NativePoolCreatePurpose, from: null | string, allowanceBytes: number, signal?: AbortSignal) => Promise; poolDelta: (from: string, to: string, signal?: AbortSignal) => Promise; + poolGrowth: (signal?: AbortSignal) => Promise; poolListCheckpoint: (id: string, path: string, expectedWorkerUid: number, signal?: AbortSignal) => Promise; poolPark: (id: string, signal?: AbortSignal) => Promise; poolPublish: (id: string, view: string, name: string, signal?: AbortSignal) => Promise; diff --git a/docs/decisions/reference-pool-accounting.md b/docs/decisions/reference-pool-accounting.md index 0f7886959e..69f2ad0db6 100644 --- a/docs/decisions/reference-pool-accounting.md +++ b/docs/decisions/reference-pool-accounting.md @@ -8,7 +8,7 @@ actual allocated disk. That decision left the mechanism to implementation. This record names the mechanism, the primary sources it relies on and the native observations that qualified it. The pool is managed by the existing host-only native manager -(`createNativeReferencePool`, `packages/ui-sdk/src/server/native-reference-pool.ts:273-988`). +(`createNativeReferencePool`, `packages/ui-sdk/src/server/native-reference-pool.ts:380-1129`). No consumer uses it yet. ## A separate volume, not another subvolume of the brain store @@ -224,7 +224,7 @@ directory its intent records. Sealing also makes the root's top directory `roots/` and `views/` join the mandatory worker masks. A worker sees reference source only through a view bound for it, and other domains' views stay invisible. `poolView` (#2432) opens a view's directory before its first -publication (`function viewOpen`, `packages/ui-sdk/src/server/native-reference-pool.ts:954-957`), +publication (`function viewOpen`, `packages/ui-sdk/src/server/native-reference-pool.ts:1095-1098`), so a worker that binds it at its start sees the domain's first publication on a later lookup ([agent tools](managed-worktrees.md#agent-tools)). @@ -269,6 +269,49 @@ directory itself. `access/` joins the mandatory worker masks. Census accepts a writable worktree only in the directory its intent records, and measurement adopts a grant or park interrupted between its rename and its record. +## Background deduplication is rejected; residual growth is reported (#3515) + +Preventive sharing stays the only mechanism: acquisition snapshots, worktree +snapshots and reflink copies. No duperemove, bees or other extent-rewriting +tool runs on the pool. The [measured investigation](../plans/repository-storage-dedupe.md) +found three reasons, each a conflict with a rule above: + +- **Cross-root owner re-attribution.** Deduplicating between two roots moves + the destination's data onto the source root's simple-quota charge. A + released source then stays `deleted` with that charge and is never + reclaimed while the destination lives. +- **Sealed-root modification.** Deduplicating into a sealed, read-only root + succeeds without refusal and leaves its recorded owner charge stale. +- **False checkpoint deltas.** Deduplicating inside a worktree between two + checkpoints makes the checkpoint delta report content edits that never + happened, and frees nothing while the older checkpoint lives. + +Residual growth is reported instead, by `brain-native-store pool growth` +(`referencePoolGrowth`, `packages/ui-sdk/src/server/native-reference-pool.ts:266-338`). +It reads one stable observation and the same owner charges as admission, with +no reconciliation, so it commits, deletes, resets and reserves nothing. Every +source chain starts at a cold acquisition, a source with no `from`. The charge +recorded when that root was sealed is the basis for the worktrees and refreshes +built on the chain, because a refresh holds only the extents it changed and a +released root keeps only what is still shared. The ruled thresholds are +`REFERENCE_POOL_GROWTH_THRESHOLDS`, from the #3513 baseline of +1.6 % for two +worktrees and 0.39x for a changed refresh. Each flag fires only strictly above +its threshold: + +- a worktree charged above 25 % of its source's cold acquisition; +- a changed refresh charged above 0.75x its chain's cold acquisition; +- more than two retained sources published under one name across views. The + name hashes the canonical repository and revision (`referenceSourceName`). + +A basis that cannot be read reads as `unavailable`, never as zero. That covers +a broken chain and a released cold acquisition sealed before the seal-time +charge was recorded. A root with no recorded owner charge reports null bytes, +and so does any retained-source sum that includes it. Evidence that admission would refuse, other than +capacity, makes the whole status unavailable. So does a published name that +does not resolve to a recorded sealed source in its own view. The status +reports measured bytes and thresholds only, never forecast savings or freed +capacity. + ## Native qualification `bun scripts/prove-reference-pool.ts` runs `reference-pool-fixture.py` inside diff --git a/docs/integration-contract.md b/docs/integration-contract.md index fa71e2e134..baa6395ca9 100644 --- a/docs/integration-contract.md +++ b/docs/integration-contract.md @@ -20,6 +20,17 @@ 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). +## Reference pool growth status (additive, 0.45.0, #3515) + +The host-only `brain-native-store pool` projection gains a read-only `growth` +action, the native manager client gains `poolGrowth()`, and the protocol gains +`NativePoolGrowth`. They report each worktree's and each changed refresh's +owner charge against its chain's cold acquisition, and retained sources per +published name across views. Flags apply the ruled thresholds and carry +measured bytes only. See +[the package API](integration-contract/package-api.md#reference-pool-growth-status-additive-0450-3515). +This ships in a minor; no breaking ruling is required. + ## Turn data trees on the managed volume (additive, 0.45.0, #2911) The native manager client and the lease owner gain `prepareTurnTree(id, diff --git a/docs/integration-contract/package-api.md b/docs/integration-contract/package-api.md index 6f4b9133d7..8f1c3f387f 100644 --- a/docs/integration-contract/package-api.md +++ b/docs/integration-contract/package-api.md @@ -4409,6 +4409,60 @@ No call accepts a host path, UID or mount. Worker masks now include the pool's The mechanism is recorded in the [pool decision](../decisions/reference-pool-accounting.md#worktree-checkpoints-and-access-generations-2430). + + +### Reference pool growth status (additive, 0.45.0, #3515) + +`brain-native-store pool growth ` prints the same envelope as `status`, +with `action: "growth"` and `growth`, and the same exit codes. The native +manager client gains `poolGrowth()`, which takes no identity, path or selector +and returns `NativePoolGrowth`: + +- `basis` is `btrfs-space-info-disk-used+simple-quota-owner`. `state` is + `available` or `unavailable`. `reason` says why the whole status is + unavailable; `generation` is the observation's filesystem generation. +- `thresholds` are `{ worktreeRatio: 0.25, refreshRatio: 0.75, retainedSources: 2 }`, + exported as `REFERENCE_POOL_GROWTH_THRESHOLDS`. +- `worktrees` (writable or sealed) and `refreshes` (sealed sources with a + `from`) are `NativePoolGrowthComparison`s: + - `id`, `from`, and `cold`, the cold acquisition at the root of the chain; + - `ownerBytes`, null when the accounting has no charge for the root; + - `basisBytes`, that acquisition's charge when it was sealed; + - `thresholdBytes`, `basisBytes` times the ratio, rounded down; + - `state`, and `flagged`, true when `ownerBytes` is strictly above + `thresholdBytes`. + + A basis or charge that cannot be read gives `state: "unavailable"` and null + bytes, never zero, and is never flagged. +- `sources` are `NativePoolGrowthSources`, one per published name: `name`, + `roots` (`id`, `view`, `ownerBytes`), their summed `ownerBytes`, and + `flagged` when more than `retainedSources` views publish the name. A root + with no recorded charge has `ownerBytes: null`, and so does the sum: never + zero. The count flag still applies. +- `flags` are `NativePoolGrowthFlag`s: `kind` (`worktree`, `refresh` or + `retained-sources`), `subject` (root id or name), `observedBytes` (null only + for a retained-sources sum that includes an unknown charge), + `thresholdBytes` (null for the count), `threshold`, and `observedCount` + (null for a ratio). +- `omitted` counts comparisons, groups or flags left out to keep one reply + within the 64 KiB control bound. Unflagged detail goes first. + +The status is read-only. It neither reconciles, deletes, resets nor reserves +anything, and nothing in it forecasts savings or freed capacity. It is +unavailable in these cases: + +- the pool refuses for any reason other than `capacity`; +- the owner accounting is unreadable; +- a view holds a non-link entry; +- a published name resolves to anything but a recorded sealed source in its + own view, such as a path, another view or a stale identity. + +The manager records each root's charge when it is sealed, so the basis +survives the root's release. Roots sealed before this release carry none. A +released one reads as unavailable, while a live sealed one uses its current, +unchanging charge. The rationale is in +[the pool decision](../decisions/reference-pool-accounting.md#background-deduplication-is-rejected-residual-growth-is-reported-3515). + ### Reference and worktree tools (additive, 0.44.0, #2432) diff --git a/packages/ui-sdk/src/bin/brain-native-store.ts b/packages/ui-sdk/src/bin/brain-native-store.ts index 3843b0f89a..8f02963199 100644 --- a/packages/ui-sdk/src/bin/brain-native-store.ts +++ b/packages/ui-sdk/src/bin/brain-native-store.ts @@ -8,6 +8,7 @@ import { nativeCheckpointId, NativeBrainManagerError } from "../server/native-br const usage = `Usage: brain-native-store /absolute/root-owned-config.json brain-native-store pool status /absolute/root-owned-config.json + brain-native-store pool growth /absolute/root-owned-config.json brain-native-store pool recovery [--after ] /absolute/root-owned-config.json brain-native-store pool release /absolute/root-owned-config.json`; function loadConfig(path: string): NativeBrainManagerConfig { @@ -36,13 +37,14 @@ async function pool(args: string[]): Promise { const action = args[0], config = args.at(-1); const after = action === "recovery" && args.length === 4 && args[1] === "--after" ? args[2]! : null; const id = action === "release" && args.length === 3 ? args[1]! : null; - const shaped = (action === "status" && args.length === 2) || (action === "recovery" && (args.length === 2 || after !== null)) || id !== null; + const shaped = ((action === "status" || action === "growth") && args.length === 2) || (action === "recovery" && (args.length === 2 || after !== null)) || id !== null; if (!shaped || !config || (after !== null && !nativeCheckpointId.safeParse(after).success) || (id !== null && !nativeCheckpointId.safeParse(id).success)) { console.error(usage); return 2; } const fixed = loadConfig(config), client = createNativeBrainManagerClient({ socketPath: fixed.socketPath, timeoutMs: fixed.operationTimeoutMs }); try { const result = action === "status" ? { action, status: await client.poolStatus() } + : action === "growth" ? { action, growth: await client.poolGrowth() } : action === "recovery" ? { action, ...(await client.listPoolRecovery(after)) } : { action, record: await client.poolRelease(id!) }; console.log(JSON.stringify({ schema_version: 1, ok: true, ...result })); 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 ef72185ebd..9632283832 100644 --- a/packages/ui-sdk/src/server/native-brain-manager-client.ts +++ b/packages/ui-sdk/src/server/native-brain-manager-client.ts @@ -6,7 +6,7 @@ import { consumeNativeStageAuthority, consumeNativeCheckpointRead, nativeCheckpo 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 NativeTurnTree, - type NativePoolAccess, type NativePoolCheckpoint, type NativePoolCreatePurpose, type NativePoolRecord, type NativePoolStatus } from "./native-brain-manager-protocol.js"; + type NativePoolAccess, type NativePoolCheckpoint, type NativePoolCreatePurpose, type NativePoolGrowth, type NativePoolRecord, type NativePoolStatus } from "./native-brain-manager-protocol.js"; export interface NativeDeltaStream { stream: ReadableStream; @@ -293,6 +293,8 @@ export function createNativeBrainManagerClient(input: { socketPath: string; time }; }, poolStatus: async (signal?: AbortSignal): Promise => control({ operation: "poolStatus" }, signal), + /** Read-only residual-growth status (#3515); reports measured charges and thresholds only. */ + poolGrowth: async (signal?: AbortSignal): Promise => control({ operation: "poolGrowth" }, signal), poolCreate: async (id: string, purpose: NativePoolCreatePurpose, from: string | null, allowanceBytes: number, signal?: AbortSignal): Promise => control({ operation: "poolCreate", id, purpose, from, allowanceBytes }, signal), poolSeal: async (id: string, signal?: AbortSignal): Promise => control({ operation: "poolSeal", id }, signal), 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 f9d6e3a992..90c1671f2c 100644 --- a/packages/ui-sdk/src/server/native-brain-manager-protocol.ts +++ b/packages/ui-sdk/src/server/native-brain-manager-protocol.ts @@ -33,6 +33,8 @@ export const nativeManagerRequest = z.discriminatedUnion("operation", [ // 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(), + // Read-only residual-growth status (#3515) over the same observation and owner charges. + z.object({ operation: z.literal("poolGrowth") }).strict(), z.object({ operation: z.literal("poolCreate"), id: nativeCheckpointId, purpose: z.enum(["source", "worktree", "staging"]), from: nativeCheckpointId.nullable(), allowanceBytes: z.number().int().positive() }).strict(), z.object({ operation: z.literal("poolSeal"), id: nativeCheckpointId }).strict(), @@ -213,6 +215,65 @@ export interface NativePoolStatus { counts: Record; identities: number; } +/** + * One measured comparison of the residual-growth status (#3515). `basisBytes` + * is the charge recorded when the chain's cold acquisition was sealed; null + * means the accounting needed for it is missing, never that it is zero. + */ +export interface NativePoolGrowthComparison { + id: string; + /** Sealed source this root was snapshotted from. */ + from: string; + /** Cold acquisition at the root of `from`'s chain: the one with no source. */ + cold: string | null; + /** The root's owner charge; null when the accounting has no charge for it, never zero. */ + ownerBytes: number | null; + basisBytes: number | null; + /** `basisBytes` times the ratio threshold; null when the basis is unavailable. */ + thresholdBytes: number | null; + state: "available" | "unavailable"; + flagged: boolean; +} +/** Retained sources published under one name (one repository and revision) across views. */ +export interface NativePoolGrowthSources { + name: string; + /** `ownerBytes` is null when the accounting has no charge for that root, never zero. */ + roots: { id: string; view: string; ownerBytes: number | null }[]; + /** Summed charge; null when any root's charge is missing. */ + ownerBytes: number | null; + flagged: boolean; +} +export interface NativePoolGrowthFlag { + kind: "worktree" | "refresh" | "retained-sources"; + /** Root identity, or the publication name for retained sources. */ + subject: string; + /** Measured charge; null only for a retained-sources count whose summed charge is unknown. */ + observedBytes: number | null; + /** Byte threshold for a ratio flag; null for the count flag. */ + thresholdBytes: number | null; + /** The ruled threshold: a ratio, or the retained-source count. */ + threshold: number; + /** Retained-source count; null for a ratio flag. */ + observedCount: number | null; +} +/** + * Read-only residual-growth status (#3515). It reports measured owner charges + * and the ruled thresholds only: never forecast savings or freed capacity. + */ +export interface NativePoolGrowth { + basis: "btrfs-space-info-disk-used+simple-quota-owner"; + state: "available" | "unavailable"; + /** Why the whole status is unavailable; comparisons and flags are then empty. */ + reason: string | null; + generation: string | null; + thresholds: { worktreeRatio: number; refreshRatio: number; retainedSources: number }; + worktrees: NativePoolGrowthComparison[]; + refreshes: NativePoolGrowthComparison[]; + sources: NativePoolGrowthSources[]; + flags: NativePoolGrowthFlag[]; + /** Comparisons and source groups left out to stay within the control bound, unflagged ones first. */ + omitted: number; +} /** The privileged helper inspects only its bounded upper layer after the worker exits. */ export interface NativeStageChange { pathHex: string; kind: "entry" | "whiteout" | "opaque" } export const NATIVE_CONTROL_BYTES = 64 * 1024; diff --git a/packages/ui-sdk/src/server/native-brain-manager.ts b/packages/ui-sdk/src/server/native-brain-manager.ts index 69aad8c890..b771cca38b 100644 --- a/packages/ui-sdk/src/server/native-brain-manager.ts +++ b/packages/ui-sdk/src/server/native-brain-manager.ts @@ -487,6 +487,7 @@ export async function createNativeBrainManager(config: NativeBrainManagerConfig, if (request.operation === "ready") return Response.json(await ready(signal)); if (!request.operation.startsWith("pool") && request.operation !== "listPoolRecovery") recoveryIndex.ensureAvailable(); if (request.operation === "poolStatus") return Response.json(await pool().status(signal)); + if (request.operation === "poolGrowth") return Response.json(await pool().growth(signal)); if (request.operation === "poolCreate") return Response.json(await pool().create(request, signal)); if (request.operation === "poolSeal") return Response.json(await pool().seal(request.id, signal)); if (request.operation === "poolRelease") { diff --git a/packages/ui-sdk/src/server/native-reference-pool.ts b/packages/ui-sdk/src/server/native-reference-pool.ts index ff054eaea4..cd9b8eb59c 100644 --- a/packages/ui-sdk/src/server/native-reference-pool.ts +++ b/packages/ui-sdk/src/server/native-reference-pool.ts @@ -21,7 +21,8 @@ import { constants, closeSync, existsSync, fstatSync, fsyncSync, lstatSync, mkdi import { randomUUID } from "node:crypto"; import { dirname, isAbsolute, join } from "node:path"; import { NativeBrainManagerError, nativeCheckpointId, nativePoolName, NATIVE_CONTROL_BYTES, REFERENCE_POOL_CHECKPOINT_BYTES, type NativePoolAccess, type NativePoolCheckpoint, type NativePoolRecord, - type NativePoolSpace, type NativePoolState, type NativePoolStatus } from "./native-brain-manager-protocol.js"; + type NativePoolGrowth, type NativePoolGrowthComparison, type NativePoolGrowthFlag, type NativePoolGrowthSources, type NativePoolSpace, type NativePoolState, + type NativePoolStatus } from "./native-brain-manager-protocol.js"; import { recordNativeRecoveryFailure } from "./native-recovery-diagnostics.js"; import { NativeRecoveryIndex } from "./native-recovery-index.js"; import { POOL_HELPER } from "./native-reference-pool-helper.js"; @@ -137,6 +138,12 @@ export interface PoolIntent extends NativePoolRecord { fsid: string; /** Filesystem generation at reservation; an adopted root must be created at or after it. */ reservedGeneration: string; + /** + * Owner charge recorded when the root was sealed (#3515). `ownerBytes` later + * shrinks to what a released root retains; this stays the cold-acquisition + * basis of the growth status. Absent on roots sealed before it existed. + */ + sealedBytes?: number | null; } /** Owner-charged bytes: referenced allocation plus any pending kernel reservation. */ @@ -230,6 +237,106 @@ export function referencePoolAccounting(input: { return { accounting, owner, refusal }; } +/** + * Residual-growth thresholds ruled on #3515 from the measured baseline of + * #3513 (two worktrees +1.6 % of their source, changed refresh 0.39x cold). + * A comparison is flagged only when strictly above its threshold. + */ +export const REFERENCE_POOL_GROWTH_THRESHOLDS = Object.freeze({ + /** A worktree's owner charge above this share of its source's cold acquisition. */ + worktreeRatio: 0.25, + /** A changed refresh's owner charge above this multiple of its chain's cold acquisition. */ + refreshRatio: 0.75, + /** More than this many retained sources of one repository and revision across views. */ + retainedSources: 2, +}); +/** Growth replies stay below the control response bound, leaving room for framing. */ +const GROWTH_REPLY_BYTES = NATIVE_CONTROL_BYTES - 1024; +/** One name read from a view directory, with its symlink target as found. */ +export interface PoolPublication { view: string; name: string; target: string } + +/** + * Pure residual-growth status over one observation's owner charges (#3515). + * Every source chain starts at a cold acquisition (a source with no `from`); + * its seal-time charge is the basis for the worktrees and refreshes built on + * it. A basis that cannot be read is `unavailable`, never zero. A published + * name that does not resolve to a recorded sealed source in its own view + * makes the whole status unavailable rather than guessing. + */ +export function referencePoolGrowth(input: { + intents: readonly PoolIntent[]; owner: ReadonlyMap | null; refusal: NativePoolStatus["refusal"]; + generation: string | null; publications: readonly PoolPublication[]; unavailable?: string | null; +}): NativePoolGrowth { + const thresholds = { ...REFERENCE_POOL_GROWTH_THRESHOLDS }; + const empty = (reason: string): NativePoolGrowth => ({ basis: "btrfs-space-info-disk-used+simple-quota-owner", state: "unavailable", reason, generation: input.generation, + thresholds, worktrees: [], refreshes: [], sources: [], flags: [], omitted: 0 }); + if (input.unavailable) return empty(input.unavailable); + // A capacity refusal still reports trustworthy charges; any other refusal means they are not. + if (input.refusal && input.refusal.code !== "capacity") return empty(input.refusal.message); + const owner = input.owner; + if (!owner) return empty("Reference pool owner accounting is unavailable."); + const byId = new Map(input.intents.map(intent => [intent.id, intent])); + /** The cold acquisition a sealed source descends from, or null when its chain is not fully recorded. */ + const coldOf = (id: string): PoolIntent | null => { + let current = byId.get(id); + for (let steps = 0; current && steps <= byId.size; steps++) { + if (current.purpose !== "source") return null; + if (current.from === null) return current; + current = byId.get(current.from); + } + return null; + }; + const basisOf = (cold: PoolIntent | null): number | null => { + if (!cold) return null; + if (cold.sealedBytes !== undefined && cold.sealedBytes !== null) return cold.sealedBytes; + // A live sealed root's charge cannot change: read-only, and its extents stay referenced. + return cold.state === "sealed" ? owner.get(cold.id) ?? null : null; + }; + const compare = (intent: PoolIntent, ratio: number): NativePoolGrowthComparison => { + const cold = coldOf(intent.from!), basis = basisOf(cold), charge = owner.get(intent.id); + const thresholdBytes = basis === null ? null : Math.floor(basis * ratio); + const available = thresholdBytes !== null && charge !== undefined; + return { id: intent.id, from: intent.from!, cold: cold?.id ?? null, ownerBytes: charge ?? null, basisBytes: available ? basis : null, thresholdBytes: available ? thresholdBytes : null, + state: available ? "available" : "unavailable", flagged: available && charge! > thresholdBytes! }; + }; + const worktrees = input.intents.filter(intent => intent.purpose === "worktree" && intent.from !== null && (intent.state === "writable" || intent.state === "sealed")) + .map(intent => compare(intent, thresholds.worktreeRatio)); + const refreshes = input.intents.filter(intent => intent.purpose === "source" && intent.from !== null && intent.state === "sealed") + .map(intent => compare(intent, thresholds.refreshRatio)); + const groups = new Map(); + for (const publication of input.publications) { + const target = byId.get(publication.target); + if (!UUID.test(publication.target) || !target || target.purpose !== "source" || target.state !== "sealed" || target.view !== publication.view) + return empty(`Reference view ${publication.view} name ${publication.name} does not resolve to a recorded sealed source in that view.`); + const group = groups.get(publication.name) ?? { name: publication.name, roots: [], ownerBytes: 0, flagged: false }; + // A root without a recorded charge is unknown, and so is any sum that includes it: never zero. + const charge = owner.get(target.id) ?? null; + group.roots.push({ id: target.id, view: publication.view, ownerBytes: charge }); + group.ownerBytes = charge === null || group.ownerBytes === null ? null : group.ownerBytes + charge; + groups.set(publication.name, group); + } + const sources = [...groups.values()].map(group => ({ ...group, flagged: group.roots.length > thresholds.retainedSources })); + const flags: NativePoolGrowthFlag[] = [ + ...worktrees.filter(item => item.flagged).map(item => ({ kind: "worktree" as const, subject: item.id, observedBytes: item.ownerBytes!, thresholdBytes: item.thresholdBytes, + threshold: thresholds.worktreeRatio, observedCount: null })), + ...refreshes.filter(item => item.flagged).map(item => ({ kind: "refresh" as const, subject: item.id, observedBytes: item.ownerBytes!, thresholdBytes: item.thresholdBytes, + threshold: thresholds.refreshRatio, observedCount: null })), + ...sources.filter(item => item.flagged).map(item => ({ kind: "retained-sources" as const, subject: item.name, observedBytes: item.ownerBytes, thresholdBytes: null, + threshold: thresholds.retainedSources, observedCount: item.roots.length })), + ]; + const result: NativePoolGrowth = { basis: "btrfs-space-info-disk-used+simple-quota-owner", state: "available", reason: null, generation: input.generation, thresholds, + worktrees, refreshes, sources, flags, omitted: 0 }; + // Stay within one control reply: unflagged detail goes first, then flagged detail; flags go last. + const lists = [result.worktrees, result.refreshes, result.sources] as Array>; + const size = () => Buffer.byteLength(JSON.stringify(result)); + for (const flagged of [false, true]) + for (const list of lists) + for (let index = list.length - 1; index >= 0 && size() > GROWTH_REPLY_BYTES; index--) + if (list[index]!.flagged === flagged) { list.splice(index, 1); result.omitted++; } + while (result.flags.length && size() > GROWTH_REPLY_BYTES) { result.flags.pop(); result.omitted++; } + return result; +} + /** Which managed directory holds a root: roots (both null), one view or one access generation; undefined is unmanaged. */ function poolPlace(dirId: string, input: { rootsDirId: string; viewDirIds?: ReadonlyMap; accessDirIds?: ReadonlyMap }) : { view: string | null; access: string | null } | undefined { @@ -394,11 +501,13 @@ export async function createNativeReferencePool(context: ReferencePoolContext) { // Intents recorded before publication or access existed carry neither. intent.view ??= null; intent.access ??= null; + // Roots sealed before the growth status (#3515) carry no seal-time charge. + intent.sealedBytes ??= null; const root = intent.root; if (intent.version !== 1 || intent.id !== id || intent.fsid !== pool.fsid || !STATES.includes(intent.state) || !PURPOSES.includes(intent.purpose) || (intent.from !== null && !nativeCheckpointId.safeParse(intent.from).success) || !page(intent.allowanceBytes) || !digits(intent.reservedGeneration) || (root !== null && (!digits(root?.rootId) || !/^[0-9a-f]{32}$/.test(root?.uuid ?? "") || !digits(root?.otransid))) - || (intent.ownerBytes !== null && !count(intent.ownerBytes)) || (intent.reason !== null && typeof intent.reason !== "string") + || (intent.ownerBytes !== null && !count(intent.ownerBytes)) || (intent.sealedBytes !== null && !count(intent.sealedBytes)) || (intent.reason !== null && typeof intent.reason !== "string") || (["writable", "sealed"].includes(intent.state) && root === null) || (intent.view !== null && (!nativeCheckpointId.safeParse(intent.view).success || ["reserved", "writable"].includes(intent.state))) || (intent.purpose === "checkpoint" && (intent.from === null || intent.state === "writable" || intent.view !== null)) @@ -604,6 +713,38 @@ export async function createNativeReferencePool(context: ReferencePoolContext) { accounting: null, physical: physicalView }; } } + /** Every published name in every manager-created view, with its link target as found; nothing is followed. */ + function publications(views: ReadonlyMap): PoolPublication[] { + const result: PoolPublication[] = []; + for (const view of views.values()) + for (const name of readdirSync(viewPath(view))) { + // Root directories carry their identity and are explained by the census; dot entries are an in-flight name swap. + if (UUID.test(name) || name.startsWith(".")) continue; + const entry = join(viewPath(view), name); + if (!lstatSync(entry).isSymbolicLink()) throw new NativeBrainManagerError("unknown", `Reference view ${view} entry ${name} is not a published name.`); + result.push({ view, name, target: readlinkSync(entry) }); + } + return result; + } + /** + * Read-only residual-growth status (#3515): one qualification and stable + * observation, without reconciliation, so nothing is committed, deleted, + * reset or reserved. Refused evidence reads as unavailable. + */ + async function growth(signal?: AbortSignal): Promise { + const recorded = [...intents.values()]; + try { + await qualify(signal); + const observation = await observe(signal), places = { viewDirIds: viewDirIds(), accessDirIds: accessDirIds() }; + const published = publications(places.viewDirIds); + const measured = referencePoolAccounting({ observation, intents: recorded, limits: pool, rootsDirId, ...places, + emergencyAllocatedBytes: emergencyAllocated(profileFactor(observation.spaces.data.profiles[0] ?? "") || 1) }); + return referencePoolGrowth({ intents: recorded, owner: measured.owner, refusal: measured.refusal, generation: observation.generation, publications: published }); + } catch (error) { + if (!(error instanceof NativeBrainManagerError) || error.code === "unavailable") throw error; + return referencePoolGrowth({ intents: recorded, owner: null, refusal: null, generation: null, publications: [], unavailable: error.message }); + } + } function publicRecord(intent: PoolIntent, owner?: number): NativePoolRecord { return { id: intent.id, purpose: intent.purpose, from: intent.from, allowanceBytes: intent.allowanceBytes, state: intent.state, root: intent.root, path: intent.state === "writable" || intent.state === "sealed" ? location(intent) : null, ownerBytes: owner ?? intent.ownerBytes, reason: intent.reason, view: intent.view, @@ -680,7 +821,7 @@ export async function createNativeReferencePool(context: ReferencePoolContext) { if (!measured.observation.stable) throw new NativeBrainManagerError("unavailable", "Reference pool allocation is still changing; the root stays charged at its allowance until a stable seal."); const qgroup = measured.observation.qgroups[level0(intent.root!.rootId)]; if (!qgroup) throw new NativeBrainManagerError("unknown", "Sealed reference pool root has no owner accounting."); - const sealed: PoolIntent = { ...intent, state: "sealed", ownerBytes: ownerCharge(qgroup) }; + const sealed: PoolIntent = { ...intent, state: "sealed", ownerBytes: ownerCharge(qgroup), sealedBytes: ownerCharge(qgroup) }; await commit(sealed, true); return publicRecord(sealed); } @@ -980,7 +1121,7 @@ export async function createNativeReferencePool(context: ReferencePoolContext) { return { /** Mandatory worker masks for pool private state, roots, views and access generations; a worker sees only what is bound for it. */ privatePaths: [privateRoot, roots, views, accessRoot, pool.devicePath, ...(backing?.backingPath ? [backing.backingPath] : []), ...(pool.headroomLedgerPath ? [dirname(pool.headroomLedgerPath)] : [])], - status, create, seal, release, publish, viewOpen, unpublish, withdraw, list, rearm: ensureEmergency, + status, growth, create, seal, release, publish, viewOpen, unpublish, withdraw, list, rearm: ensureEmergency, checkpoint, checkpointPath, deltaRoots, accessOpen, grant, park, accessClose, close() { index.close(); closeSync(stateFd); }, }; diff --git a/packages/ui-sdk/tests/native-reference-pool.test.ts b/packages/ui-sdk/tests/native-reference-pool.test.ts index f93b7c2540..3047507e68 100644 --- a/packages/ui-sdk/tests/native-reference-pool.test.ts +++ b/packages/ui-sdk/tests/native-reference-pool.test.ts @@ -1,8 +1,8 @@ import { expect, test } from "bun:test"; -import { nativeManagerRequest } from "../src/server/native-brain-manager-protocol"; +import { nativeManagerRequest, NATIVE_CONTROL_BYTES } from "../src/server/native-brain-manager-protocol"; import { validateNativeBrainManagerConfig } from "../src/server/native-brain-manager"; -import { parsePoolObservation, referencePoolAccounting, referencePoolMount, reservePhysical, poolReservationFactor, validateNativeReferencePoolConfig, - REFERENCE_POOL_COMBINED_BYTES, REFERENCE_POOL_OPERATION_BYTES, REFERENCE_POOL_QGROUP, type PoolIntent, type PoolObservation, type QualifiedReferencePoolConfig } from "../src/server/native-reference-pool"; +import { parsePoolObservation, referencePoolAccounting, referencePoolGrowth, referencePoolMount, reservePhysical, poolReservationFactor, validateNativeReferencePoolConfig, + REFERENCE_POOL_GROWTH_THRESHOLDS, REFERENCE_POOL_COMBINED_BYTES, REFERENCE_POOL_OPERATION_BYTES, REFERENCE_POOL_QGROUP, type PoolIntent, type PoolObservation, type QualifiedReferencePoolConfig } from "../src/server/native-reference-pool"; const MIB = 1024 ** 2; const ID = "11111111-1111-4111-8111-111111112428", SECOND = "22222222-2222-4222-8222-222222222428"; @@ -213,3 +213,112 @@ test("the pool mount may present access generations like other managed roots", ( expect(() => referencePoolMount(top + "52 25 0:41 /access/x /run/worktrees rw - btrfs /dev/ithaca-reference rw\n", "/srv/ithaca-reference", "/dev/ithaca-reference")).not.toThrow(); expect(() => referencePoolMount(top + "52 25 0:41 /accessory /run/worktrees rw - btrfs /dev/ithaca-reference rw\n", "/srv/ithaca-reference", "/dev/ithaca-reference")).toThrow(); }); + +// Residual-growth status (#3515): measured owner charges against the ruled thresholds. +const COLD = "55555555-5555-4555-8555-555555553515", TREE = "66666666-6666-4666-8666-666666663515", REFRESH = "77777777-7777-4777-8777-777777773515"; +const OTHER_VIEW = "88888888-8888-4888-8888-888888883515", THIRD_VIEW = "99999999-9999-4999-8999-999999993515"; +const root = (id: string, purpose: PoolIntent["purpose"], state: PoolIntent["state"], from: string | null, extra: Partial = {}): PoolIntent => + ({ ...intent(id, String(300 + Number.parseInt(id.slice(0, 2), 16)), state, from), purpose, ...extra }); +/** A 40 MiB cold acquisition, one worktree and one refresh of it, published in two views. */ +function growthPool(charges: { tree?: number; refresh?: number } = {}) { + const intents = [root(COLD, "source", "sealed", null, { sealedBytes: 40 * MIB, view: VIEW }), root(TREE, "worktree", "writable", COLD), + root(REFRESH, "source", "sealed", COLD, { sealedBytes: charges.refresh ?? 16 * MIB, view: OTHER_VIEW })]; + const owner = new Map([[COLD, 40 * MIB], [TREE, charges.tree ?? 4 * MIB], [REFRESH, charges.refresh ?? 16 * MIB]]); + const publications = [{ view: VIEW, name: "ithaca@main-0123456789", target: COLD }, { view: OTHER_VIEW, name: "ithaca@main-0123456789", target: REFRESH }]; + return { intents, owner, publications, refusal: null, generation: "40" }; +} + +test("a clean pool reports every measured comparison and no growth flag", () => { + const growth = referencePoolGrowth(growthPool()); + expect(growth.state, "REFERENCE_POOL_GROWTH_AVAILABLE").toBe("available"); + expect(growth.thresholds, "REFERENCE_POOL_GROWTH_RULED_THRESHOLDS").toEqual({ worktreeRatio: 0.25, refreshRatio: 0.75, retainedSources: 2 }); + expect(growth.worktrees, "REFERENCE_POOL_GROWTH_WORKTREE_BASIS").toEqual([{ id: TREE, from: COLD, cold: COLD, ownerBytes: 4 * MIB, basisBytes: 40 * MIB, + thresholdBytes: 10 * MIB, state: "available", flagged: false }]); + expect(growth.refreshes[0], "REFERENCE_POOL_GROWTH_REFRESH_BASIS").toMatchObject({ id: REFRESH, cold: COLD, ownerBytes: 16 * MIB, basisBytes: 40 * MIB, thresholdBytes: 30 * MIB, flagged: false }); + expect(growth.sources, "REFERENCE_POOL_GROWTH_SOURCES_PER_NAME").toEqual([{ name: "ithaca@main-0123456789", ownerBytes: 56 * MIB, flagged: false, + roots: [{ id: COLD, view: VIEW, ownerBytes: 40 * MIB }, { id: REFRESH, view: OTHER_VIEW, ownerBytes: 16 * MIB }] }]); + expect(growth.flags, "REFERENCE_POOL_GROWTH_CLEAN").toEqual([]); + // Measured bytes only: nothing forecasts savings or freed capacity. + expect(JSON.stringify(growth)).not.toMatch(/sav|free|reclaim/i); +}); + +test("each growth flag fires only strictly above its ruled threshold and carries observed bytes and threshold", () => { + const at = referencePoolGrowth(growthPool({ tree: 10 * MIB, refresh: 30 * MIB })); + expect(at.flags, "REFERENCE_POOL_GROWTH_AT_THRESHOLD_IS_CLEAN").toEqual([]); + const worktree = referencePoolGrowth(growthPool({ tree: 10 * MIB + 4096 })); + expect(worktree.flags, "REFERENCE_POOL_GROWTH_WORKTREE_FLAG").toEqual([{ kind: "worktree", subject: TREE, observedBytes: 10 * MIB + 4096, thresholdBytes: 10 * MIB, + threshold: REFERENCE_POOL_GROWTH_THRESHOLDS.worktreeRatio, observedCount: null }]); + const refresh = referencePoolGrowth(growthPool({ refresh: 30 * MIB + 4096 })); + expect(refresh.flags, "REFERENCE_POOL_GROWTH_REFRESH_FLAG").toEqual([{ kind: "refresh", subject: REFRESH, observedBytes: 30 * MIB + 4096, thresholdBytes: 30 * MIB, + threshold: REFERENCE_POOL_GROWTH_THRESHOLDS.refreshRatio, observedCount: null }]); + const retained = growthPool(), THIRD = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaa3515"; + retained.intents.push(root(THIRD, "source", "sealed", null, { sealedBytes: 40 * MIB, view: THIRD_VIEW })); retained.owner.set(THIRD, 40 * MIB); + retained.publications.push({ view: THIRD_VIEW, name: "ithaca@main-0123456789", target: THIRD }); + expect(referencePoolGrowth(retained).flags, "REFERENCE_POOL_GROWTH_RETAINED_FLAG").toEqual([{ kind: "retained-sources", subject: "ithaca@main-0123456789", + observedBytes: 96 * MIB, thresholdBytes: null, threshold: REFERENCE_POOL_GROWTH_THRESHOLDS.retainedSources, observedCount: 3 }]); +}); + +test("missing or unreadable accounting reads as unavailable, never as zero", () => { + // A released cold acquisition sealed before the seal-time charge existed: its basis is unknown. + const legacy = growthPool({ tree: 39 * MIB }); + legacy.intents[0] = { ...legacy.intents[0]!, state: "deleted", sealedBytes: null, view: null }; + legacy.publications.shift(); + const growth = referencePoolGrowth(legacy); + expect(growth.worktrees[0], "REFERENCE_POOL_GROWTH_UNAVAILABLE_NOT_ZERO").toMatchObject({ state: "unavailable", basisBytes: null, thresholdBytes: null, flagged: false }); + expect(growth.flags, "REFERENCE_POOL_GROWTH_UNAVAILABLE_NEVER_FLAGS").toEqual([]); + // A live sealed cold acquisition without the field still has an invariant charge. + const sealed = growthPool({ tree: 11 * MIB }); + sealed.intents[0] = { ...sealed.intents[0]!, sealedBytes: null }; + expect(referencePoolGrowth(sealed).worktrees[0], "REFERENCE_POOL_GROWTH_LIVE_SEALED_BASIS").toMatchObject({ basisBytes: 40 * MIB, flagged: true }); + // A broken chain has no cold acquisition to compare with. + const orphan = growthPool(); + orphan.intents.splice(0, 1); + expect(referencePoolGrowth({ ...orphan, publications: [] }).refreshes[0], "REFERENCE_POOL_GROWTH_BROKEN_CHAIN").toMatchObject({ cold: null, state: "unavailable" }); + for (const [label, override] of [["no owner accounting", { owner: null }], ["refused evidence", { refusal: { code: "unknown" as const, message: "Reference pool qgroup 0/999 has no recorded owner." } }], + ["changing allocation", { refusal: { code: "changing" as const, message: "changing" } }]] as const) { + const refused = referencePoolGrowth({ ...growthPool({ tree: 39 * MIB }), ...override }); + expect(refused, `REFERENCE_POOL_GROWTH_REFUSED ${label}`).toMatchObject({ state: "unavailable", worktrees: [], refreshes: [], sources: [], flags: [] }); + expect(refused.reason).toBeTruthy(); + } + // A root the owner accounting has no charge for reads as unknown, never as zero bytes. + const uncharged = growthPool(); + uncharged.owner.delete(TREE); uncharged.owner.delete(REFRESH); + const missing = referencePoolGrowth(uncharged); + expect(missing.worktrees[0], "REFERENCE_POOL_GROWTH_MISSING_CHARGE_NOT_ZERO").toMatchObject({ ownerBytes: null, state: "unavailable", flagged: false }); + expect(missing.sources[0], "REFERENCE_POOL_GROWTH_MISSING_SOURCE_CHARGE_NOT_ZERO").toMatchObject({ ownerBytes: null, + roots: [{ id: COLD, ownerBytes: 40 * MIB }, { id: REFRESH, ownerBytes: null }] }); + // Admission refusal for capacity leaves the measured charges trustworthy. + expect(referencePoolGrowth({ ...growthPool(), refusal: { code: "capacity", message: "full" } }).state, "REFERENCE_POOL_GROWTH_CAPACITY_STILL_MEASURES").toBe("available"); +}); + +test("a published name must resolve to a recorded sealed source in its own view", () => { + for (const [label, target, view] of [["symlink escape", "../../../etc", VIEW], ["absolute target", "/srv/ithaca", VIEW], ["unrecorded identity", "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbb3515", VIEW], + ["foreign view", COLD, OTHER_VIEW], ["worktree target", TREE, VIEW]] as const) { + const pool = growthPool(); + pool.publications.push({ view, name: "penelope@loom-0123456789", target }); + expect(referencePoolGrowth(pool), `REFERENCE_POOL_GROWTH_REFUSES ${label}`).toMatchObject({ state: "unavailable", flags: [] }); + } + const stale = growthPool(); + stale.intents[0] = { ...stale.intents[0]!, state: "deleted" }; + expect(referencePoolGrowth(stale), "REFERENCE_POOL_GROWTH_REFUSES stale identity").toMatchObject({ state: "unavailable" }); +}); + +test("a growth reply stays within one control response and keeps its flags", () => { + const pool = growthPool({ tree: 11 * MIB }); + for (let index = 0; index < 600; index++) { + const id = `cccccccc-cccc-4ccc-8ccc-${String(index).padStart(12, "0")}`; + pool.intents.push(root(id, "worktree", "writable", COLD)); pool.owner.set(id, MIB); + } + const growth = referencePoolGrowth(pool); + expect(Buffer.byteLength(JSON.stringify(growth)), "REFERENCE_POOL_GROWTH_BOUNDED").toBeLessThan(NATIVE_CONTROL_BYTES); + expect(growth.omitted, "REFERENCE_POOL_GROWTH_OMISSION_COUNTED").toBeGreaterThan(0); + expect(growth.worktrees.length + growth.omitted).toBe(601); + expect(growth.worktrees.some(item => item.id === TREE), "REFERENCE_POOL_GROWTH_FLAGGED_DETAIL_KEPT").toBe(true); + expect(growth.flags.map(flag => flag.subject), "REFERENCE_POOL_GROWTH_FLAGS_KEPT").toEqual([TREE]); +}); + +test("the growth request takes no identity, path or selector", () => { + expect(nativeManagerRequest.safeParse({ operation: "poolGrowth" }).success, "REFERENCE_POOL_GROWTH_REQUEST").toBe(true); + for (const extra of [{ path: "/srv/ithaca" }, { id: COLD }, { view: VIEW }]) + expect(nativeManagerRequest.safeParse({ operation: "poolGrowth", ...extra }).success, `REFERENCE_POOL_GROWTH_NO_SELECTOR ${Object.keys(extra)[0]}`).toBe(false); +}); diff --git a/packages/ui-server/tests/helpers/native-journal-fixture.ts b/packages/ui-server/tests/helpers/native-journal-fixture.ts index b17193a45c..5c2cfe306b 100644 --- a/packages/ui-server/tests/helpers/native-journal-fixture.ts +++ b/packages/ui-server/tests/helpers/native-journal-fixture.ts @@ -125,6 +125,7 @@ export function createNativeJournalFixture(brain: string, root: string, copy = ( 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 poolGrowth() { 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."); }, async poolRelease() { throw Error("Copied native fixture has no reference pool volume."); }, diff --git a/scripts/native-proof/README.md b/scripts/native-proof/README.md index 2445975830..7a8bcbd29f 100644 --- a/scripts/native-proof/README.md +++ b/scripts/native-proof/README.md @@ -347,6 +347,15 @@ edits a writable snapshot of sealed source, diffs two of its read-only checkpoints and grants it to a running non-root bubblewrap worker through an access generation, then parks it, adopts an interrupted grant on restart and closes the generation. +A growth case ([#3515](https://github.com/schlessera/brain-kit/issues/3515)) +acquires a generated Odysseus repository cold into two views. It adds a +worktree and a changed refresh, both within the ruled thresholds, and expects +`poolGrowth` to report no flag. Then it grows the worktree past 25 % of its +cold acquisition, refreshes with new data past 0.75x, and publishes a third +copy. It expects exactly those three flags, unchanged recovery records and the +same result from `brain-native-store pool growth`. Names planted in a view +that escape it or resolve to an unpublished root or a worktree make the status +unavailable. Case 18's S7 allocations use `createFixtureWorktrees`: at most three allocation attempts (the initial allocation plus two fresh identities). Only an diff --git a/scripts/native-proof/reference-pool.native.ts b/scripts/native-proof/reference-pool.native.ts index 1247708471..f794bb5f12 100644 --- a/scripts/native-proof/reference-pool.native.ts +++ b/scripts/native-proof/reference-pool.native.ts @@ -1,12 +1,12 @@ /** Real reference-pool qualification on owned Btrfs loop volumes (#2428). Runs only inside reference-pool-fixture.py. */ import { expect, spyOn } from "bun:test"; -import { closeSync, existsSync, linkSync, mkdirSync, openSync, readdirSync, readFileSync, readlinkSync, rmSync, statSync, truncateSync, unlinkSync, writeFileSync, writeSync, chmodSync, renameSync } from "node:fs"; +import { closeSync, existsSync, linkSync, mkdirSync, openSync, readdirSync, readFileSync, readlinkSync, rmSync, statSync, symlinkSync, truncateSync, unlinkSync, writeFileSync, writeSync, chmodSync, renameSync } from "node:fs"; import { join } from "node:path"; import { randomBytes, randomUUID } from "node:crypto"; import { createNativeBrainManager, serveNativeBrainManager, type NativeBrainManagerConfig } from "../../packages/ui-sdk/src/server/native-brain-manager.js"; import { createNativeBrainManagerClient } from "../../packages/ui-sdk/src/server/native-brain-manager-client.js"; import { reservePhysical } from "../../packages/ui-sdk/src/server/native-reference-pool.js"; -import type { NativePoolRecord, NativePoolStatus } from "../../packages/ui-sdk/src/server/native-brain-manager-protocol.js"; +import type { NativePoolGrowth, NativePoolRecord, NativePoolStatus } from "../../packages/ui-sdk/src/server/native-brain-manager-protocol.js"; import { createFixtureWorktrees } from "./reference-worktree-allocation.js"; import { NativeRecoveryIndex } from "../../packages/ui-sdk/src/server/native-recovery-index.js"; @@ -842,6 +842,91 @@ const shapes = await create("staging", 32 * MIB); manager = await createNativeBrainManager(config); } +// 20. Residual-growth status (#3515): generated Odysseus repositories acquired +// cold into two domains, a worktree and a changed refresh within the ruled +// thresholds report no flag; growth beyond each threshold flags exactly it. +// Unexplained view entries make the status unavailable; it never mutates. +{ + const srv = "/native-runtime/growth-srv", NAME = "ithaca@main-3515a1b2c3"; + const views = [randomUUID(), randomUUID(), randomUUID()]; + const git = (cwd: string, ...args: string[]) => command(["git", "-C", cwd, "-c", "user.name=Odysseus", "-c", "user.email=odysseus@ithaca.example", ...args]); + mkdirSync(join(srv, "books"), { recursive: true }); + git(srv, "init", "-q", "-b", "main"); + for (let book = 1; book <= 24; book++) + writeFileSync(join(srv, "books", `book-${book}.md`), Array.from({ length: 40 }, (_, line) => `Book ${book}, line ${line}: Odysseus keeps the ledger of the voyage home to Ithaca.`).join("\n")); + fill(join(srv, "chart.bin"), 4 * MIB); + git(srv, "add", "-A"); git(srv, "commit", "-q", "-m", "The voyage ledger"); + /** One cold acquisition: a full clone into a fresh source root, sealed and published in `view`. */ + /** A refresh instead snapshots `from`, applies `change` to its checkout and commits it. */ + const acquire = async (view: string, from: string | null = null, change?: (repo: string) => void) => { + const root = await create("source", 32 * MIB, from), repo = join(root.path!, "repo"); + if (from === null) command(["git", "clone", "-q", "--no-hardlinks", srv, repo]); + if (change) { change(repo); git(repo, "add", "-A"); git(repo, "commit", "-q", "-m", "Refreshed ledger"); } + sync(); await seal(root.id); + if (from === null) await call({ operation: "poolPublish", id: root.id, view, name: NAME }); + return root; + }; + const growth = async () => { sync(); return call({ operation: "poolGrowth" }); }; + const records = async () => (await call<{ records: NativePoolRecord[] }>({ operation: "listPoolRecovery", after: null })).records; + const first = await acquire(views[0]!), second = await acquire(views[1]!); + const worktree = await create("worktree", 16 * MIB, first.id); + writeFileSync(join(worktree.path!, "repo", "books", "book-1.md"), "Penelope rewrites one line of the first book.\n"); + const refresh = await acquire(views[0]!, first.id, repo => writeFileSync(join(repo, "books", "book-2.md"), "Telemachus corrects the second book.\n")); + const clean = await growth(); + note("growth-clean", clean as unknown as Record); + expect(clean.state, "REFERENCE_POOL_GROWTH_NATIVE_AVAILABLE").toBe("available"); + expect(clean.flags, "REFERENCE_POOL_GROWTH_NATIVE_CLEAN").toEqual([]); + const tree = clean.worktrees.find(item => item.id === worktree.id), changed = clean.refreshes.find(item => item.id === refresh.id); + expect(tree, "REFERENCE_POOL_GROWTH_NATIVE_WORKTREE_MEASURED").toMatchObject({ cold: first.id, state: "available", flagged: false }); + expect(tree!.basisBytes, "REFERENCE_POOL_GROWTH_NATIVE_COLD_BASIS").toBeGreaterThan(4 * MIB); + expect(changed, "REFERENCE_POOL_GROWTH_NATIVE_REFRESH_MEASURED").toMatchObject({ cold: first.id, state: "available", flagged: false }); + expect(clean.sources.find(item => item.name === NAME)?.roots.length, "REFERENCE_POOL_GROWTH_NATIVE_TWO_DOMAINS").toBe(2); + + // Growth beyond each threshold flags exactly that comparison. + fill(join(worktree.path!, "repo", "chart-copy.bin"), Math.ceil(tree!.basisBytes! * 0.3 / MIB) * MIB); + // New incompressible data: the checkout and its Git object each hold it, well above 0.75x cold. + const grown = await acquire(views[0]!, first.id, repo => fill(join(repo, "atlas.bin"), Math.ceil(tree!.basisBytes! * 0.8 / MIB) * MIB)); + const third = await acquire(views[2]!); + sync(); + const before = await records(); + const flagged = await growth(); + note("growth-flagged", flagged as unknown as Record); + // No intent moved: the status commits, releases and reserves nothing. + expect(await records(), "REFERENCE_POOL_GROWTH_NATIVE_READ_ONLY").toEqual(before); + const kinds = Object.fromEntries(flagged.flags.map(flag => [flag.kind, flag])); + expect(flagged.flags.length, "REFERENCE_POOL_GROWTH_NATIVE_EACH_FLAG_ONCE").toBe(3); + expect(kinds.worktree, "REFERENCE_POOL_GROWTH_NATIVE_WORKTREE_FLAG").toMatchObject({ subject: worktree.id, threshold: 0.25 }); + expect(kinds["retained-sources"], "REFERENCE_POOL_GROWTH_NATIVE_RETAINED_FLAG").toMatchObject({ subject: NAME, observedCount: 3, threshold: 2 }); + expect(kinds.refresh, "REFERENCE_POOL_GROWTH_NATIVE_REFRESH_FLAG").toMatchObject({ subject: grown.id, threshold: 0.75 }); + for (const flag of [kinds.worktree!, kinds.refresh!]) expect(flag.observedBytes, `REFERENCE_POOL_GROWTH_NATIVE_ABOVE ${flag.kind}`).toBeGreaterThan(flag.thresholdBytes!); + + // Names that escape, or resolve to anything but a recorded sealed source in their view, are refused. + const viewDir = join(POOL, "views", views[0]!); + for (const [label, target] of [["symlink escape", "../../.reference-native"], ["unpublished root", refresh.id], ["worktree", worktree.id]] as const) { + symlinkSync(target, join(viewDir, "penelope@loom-3515")); + const refused = await growth(); + unlinkSync(join(viewDir, "penelope@loom-3515")); + expect(refused, `REFERENCE_POOL_GROWTH_NATIVE_REFUSES ${label}`).toMatchObject({ state: "unavailable", flags: [], worktrees: [] }); + } + + // The operator projection prints the same status, with the CLI's exit code. + await manager.close(); + const served = await serveNativeBrainManager(config); + try { + writeFileSync("/native-runtime/config.json", JSON.stringify(config)); chmodSync("/native-runtime/config.json", 0o600); + const child = Bun.spawn(["/usr/local/bin/bun", "/repo/packages/ui-sdk/src/bin/brain-native-store.ts", "pool", "growth", "/native-runtime/config.json"], { stdout: "pipe", stderr: "pipe" }); + const [stdout, stderr, code] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]); + note("growth-cli", { code, stderr }); + expect(code, `REFERENCE_POOL_GROWTH_CLI_EXIT ${stderr}`).toBe(0); + const projected = JSON.parse(stdout); + expect(projected, "REFERENCE_POOL_GROWTH_CLI_SHAPE").toMatchObject({ schema_version: 1, ok: true, action: "growth", growth: { state: "available" } }); + expect(projected.growth.flags.map((flag: { kind: string }) => flag.kind).sort(), "REFERENCE_POOL_GROWTH_CLI_FLAGS").toEqual(["refresh", "retained-sources", "worktree"]); + } finally { await served.close(); } + manager = await createNativeBrainManager(config); + for (const id of [worktree.id, grown.id, refresh.id, third.id, second.id, first.id]) expect((await release(id)).state, `REFERENCE_POOL_GROWTH_NATIVE_RELEASED ${id}`).toBe("reclaimed"); + rmSync(srv, { recursive: true, force: true }); +} + // 14. Restart reconstruction and the deterministic host projection. { const kept = await create("source", 4 * MIB);