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
5 changes: 5 additions & 0 deletions .changeset/2915-observation-steps.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@schlessera/brain-ui-server": minor
---

Attribute more of journal begin in a turn's lifecycle steps. The `journal` phase now also reports `observe_reserve` (the wait for room behind earlier checkpoint releases), `observe_release_reads`, `observe_worktrees`, and `observe_publish` and `observe_facts` beside `observe_record`. The record steps now repeat once per other active turn the observation records, and are absent when there is none.
55 changes: 55 additions & 0 deletions docs/decisions/governed-writable-workers.md
Original file line number Diff line number Diff line change
Expand Up @@ -1976,6 +1976,61 @@ send 1 to 2 ms each); the rest of the hold is not attributed
(#2915). The targets are
reported as unmet, not relaxed.

### Where an observation's time goes — 2026-11-15 (#2915)

**What is measured.** `--observation-timing` now attributes each observed
writer's worker hold and each harbour turn's journal begin and finish to their
steps. The journal reports every step of a held observation to an internal
trace (`observationTrace`, `packages/ui-server/src/brain/turn-journal.ts`),
the hold itself last, and the native manager reports each request's wait for
its single operation lock, the operation it waited behind, and its checkpoint,
release and delta steps (`trace`, `NativeBrainManagerOptions`,
`packages/ui-sdk/src/server/native-brain-manager.ts`). The app child and the
fixture's manager stamp both with `performance.timeOrigin + performance.now()`.
A checkpoint or delta step is broken down by the one manager request that
arrived inside it. The run fails unless every such step pairs with exactly one
request and each checkpoint answered before its step ended: that is the proof
that the two processes' clocks agree
(`scripts/native-proof/observation-phases.ts`). Nothing is traced unless a
caller passes a trace, and no step, check or durability write changed.
Admission's lifecycle steps gain the same new names (`observe_reserve`,
`observe_release_reads`, `observe_worktrees`, `observe_publish`,
`observe_facts`), additively.

**Measured.** pi, governed, UID 1000, 2,000 notes, on hosted GitHub runners
(1-minute load 1 to 2), on 2026-11-15. The first row is one run; the other two
ran back to back on one runner. Median added ms / p95 with the median worker
hold, and journal begin plus finish as the median / p95 of paired totals:

| | `write_file` | `edit_file` | Writing `bash` | Begin + finish |
| --- | --- | --- | --- | --- |
| This change, run 1 | 71 / 494, held 45 | 59 / 249, held 33 | 86 / 614, held 57 | 218 / 1,577 |
| Base `3f8ff293`, paired | 67 / 97, held 38 | 69 / 74, held 38 | 76 / 96, held 40 | 62 / 181 |
| This change, paired | 68 / 126, held 38 | 68 / 80, held 40 | 72 / 79, held 38 | 68 / 144 |

The paired runs show the trace costs nothing measurable. The phases cover
98 to 99 % of the measured hold, begin and finish by median, and at least
92.9 % of every single sample. In the paired run a writer's 38 ms hold is the
queue for the journal and the workers' freeze (3.7 ms), the checkpoint
(18.1 ms: qualification 4.5, the two fsynced intents 4.3, the snapshot 5.8, the
Unix round trip 2.4), the delta (3.9), content capture of the written file
(6.9), and the record, publication and facts query (about 3). Finish is the
same observation plus its end record (1.2) and object collection (0.7). The
release owner (#2872) rarely delays anything any more: a writer's checkpoint
waited behind a release in 2 of 60 calls in run 1.

**Targets.** On these runners both #2834 targets are met, at the base and with
this change: writers add 67 to 76 ms (target under 150) and begin plus finish
takes 62 to 68 ms (target at most 300). Run 1 shows what the slower host in
#2872's runs paid for. Finish's median was 139 ms and its p95 1.6 s, and almost
all of it sat in two required durability steps: the checkpoint's intent fsync
(110 ms median) or the snapshot, whichever met the btrfs writeback of the
turn's and the index refresh's dirty data first. Nothing was cut. Every
remaining phase is a qualification check, an identity check, a durability
write, a journal capture or the hold mechanism itself, and none may be skipped
or cached. Moving that writeback out of the hold is a separate question
(#4019).

## Monitoring

**Where it lives.** All monitoring is host operational state in `brain-ui.db`
Expand Down
9 changes: 7 additions & 2 deletions docs/integration-contract/wire.md
Original file line number Diff line number Diff line change
Expand Up @@ -599,8 +599,13 @@ not apply to a turn is absent. The current names are:
`type_translation_refresh`, `peer_folder_plans`, `private_index`, `data_tree`,
`record_policy`, `startup_view_cleanup`, `exposure_records`, `manifest_begin`.
- `journal`: `hold_wait`, `initialize`, `refused_admissions`, `observe` (with
`observe_checkpoint`, `observe_delta`, `observe_metadata`, `observe_capture`,
`observe_record`, `observe_commit`), `expiry`, `turn_insert`, `policy`.
`observe_release_reads`, `observe_reserve`, `observe_checkpoint`,
`observe_delta`, `observe_metadata`, `observe_capture`, `observe_worktrees`,
`observe_record`, `observe_publish`, `observe_facts`, `observe_commit`),
`expiry`, `turn_insert`, `policy`. `observe_reserve` waits for room behind
earlier checkpoint releases; `observe_record`, `observe_publish` and
`observe_facts` repeat once per other active turn the observation records,
and are absent when there is none (#2915).

Records written before this field have no `subPhases`; nothing is backfilled.

Expand Down
66 changes: 58 additions & 8 deletions packages/ui-sdk/src/server/native-brain-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,18 @@ export interface NativeBrainManagerConfig {
/** Optional separate Btrfs reference volume (#2428); no consumer is enabled by configuring it. */
referencePool?: NativeReferencePoolConfig;
}
/**
* @internal One timed span of a manager operation (#2915), stamped with
* `performance.timeOrigin + performance.now()` so another process on the host
* can align it with its own. `lock_wait` names the operation that held the
* single operation lock when the wait began; `held` spans the lock itself.
* `request` numbers one operation's spans.
*/
export interface NativeManagerSpan { request: number; operation: string; phase: string; startedAt: number; endedAt: number; holder?: string | null }
export interface NativeBrainManagerOptions {
/** @internal Diagnostic timing only; called synchronously, so it must be cheap. */
trace?: (span: NativeManagerSpan) => void;
}
type RootInfo = { rootId: string; uuid: string; parentUuid: string; receivedUuid: string; transaction: string; readOnly: boolean; fsid: string; devices: number };
type Intent = NativeRecoveryRecord & { version: 1; sourceUuid: string };

Expand Down Expand Up @@ -114,7 +126,7 @@ async function collect(stream: ReadableStream<Uint8Array>, maximum: number): Pro
for (const part of pieces) { result.set(part, offset); offset += part.byteLength; } return result;
}

export async function createNativeBrainManager(config: NativeBrainManagerConfig) {
export async function createNativeBrainManager(config: NativeBrainManagerConfig, options: NativeBrainManagerOptions = {}) {
validateNativeBrainManagerConfig(config);
if (process.platform !== "linux" || process.arch !== "x64" || process.geteuid?.() !== 0)
throw new NativeBrainManagerError("unsupported", "Native manager requires the separately qualified trusted Linux x86-64 root service; the app and workers remain unprivileged.");
Expand All @@ -131,13 +143,19 @@ export async function createNativeBrainManager(config: NativeBrainManagerConfig)
const stageReservations = new Map<string, { checkpointId: string; allowanceBytes: number }>();
const checkpointReaders = new Map<string, { checkpointId: string; close(): Promise<void> }>();
let stagedBytes = 0;
async function acquire(signal?: AbortSignal): Promise<() => void> {
const trace = options.trace, clock = () => performance.timeOrigin + performance.now();
/** The operation holding the lock, for a traced wait behind it. */
let holder: string | null = null, requests = 0;
async function acquire(signal?: AbortSignal, operation: string | null = null): Promise<() => void> {
signal?.throwIfAborted(); if (closed) throw new NativeBrainManagerError("unavailable", "Native manager is closing.");
let release!: () => void;
const before = pending; pending = new Promise<void>(done => { release = done; });
await before;
if (closed || signal?.aborted) { release(); signal?.throwIfAborted(); throw new NativeBrainManagerError("unavailable", "Native manager is closing."); }
return release;
if (!trace) return release;
holder = operation;
let released = false;
return () => { if (released) return; released = true; holder = null; release(); };
}
function spawn(command: string[], signal?: AbortSignal) {
const controller = new AbortController(); active.add(controller);
Expand Down Expand Up @@ -429,7 +447,15 @@ export async function createNativeBrainManager(config: NativeBrainManagerConfig)
stagingChargedBytes: Number.isSafeInteger(stagedBytes + quarantinedStageBytes) ? stagedBytes + quarantinedStageBytes : null, diagnosticsPath: join(privateRoot, "recovery-diagnostics") } } : {}) };
}
async function run(request: NativeManagerRequest, signal?: AbortSignal): Promise<Response> {
nativeManagerRequest.parse(request); const release = await acquire(signal); let handedToStream = false;
nativeManagerRequest.parse(request);
const operation = request.operation, waited = trace ? clock() : 0, behind = holder, id = ++requests;
const step = trace ? (phase: string) => { const startedAt = clock(); return () => trace({ request: id, operation, phase, startedAt, endedAt: clock() }); } : undefined;
const locked = await acquire(signal, operation);
if (trace) trace({ request: id, operation, phase: "lock_wait", startedAt: waited, endedAt: clock(), holder: behind });
// A streamed send keeps the lock until it ends; `sending` times that part.
const held = step?.("held"); let sending: (() => void) | undefined;
const release = held ? () => { sending?.(); sending = undefined; held(); locked(); } : locked;
let handedToStream = false, end: (() => void) | undefined;
try {
if (request.operation === "ready") return Response.json(await ready(signal));
if (!request.operation.startsWith("pool") && request.operation !== "listPoolRecovery") recoveryIndex.ensureAvailable();
Expand Down Expand Up @@ -486,7 +512,9 @@ export async function createNativeBrainManager(config: NativeBrainManagerConfig)
const intent = readIntent(request.id);
if (!intent || intent.kind === "stage" || intent.state !== "sealed")
throw new NativeBrainManagerError("unknown", "Checkpoint reading requires one retained sealed checkpoint identity.");
end = step?.("verify");
checkpoint = await verifyOwned(intent, signal);
end?.();
}
const maximum = Math.min(request.maximum, request.action === "file" ? fixed.capacityBytes : fixed.maxDeltaBytes);
const id = randomUUID(), token = randomUUID(), socketPath = nativeCheckpointReaderPath(fixed.socketPath, id);
Expand Down Expand Up @@ -635,22 +663,33 @@ export async function createNativeBrainManager(config: NativeBrainManagerConfig)
"x-brain-stage-checkpoint": handle.stage.checkpointId, "x-brain-stage-lower": handle.stage.checkpointUuid } });
}
if (request.operation === "checkpoint") {
end = step?.("qualify");
await qualify(signal);
end?.();
let createdNow = false;
let intent = readIntent(request.id);
if (intent) intent = await reconcile(intent, signal);
if (intent) { end = step?.("reconcile"); intent = await reconcile(intent, signal); end?.(); }
if (intent?.state === "deleted" || intent?.state === "deleting") throw new NativeBrainManagerError("released", "This checkpoint identity was released; it cannot be recreated.");
if (intent?.state === "sealed") return Response.json(await verifyOwned(intent, signal));
end = step?.("reserve");
await ensureReserve(signal);
end?.();
if (!intent) {
if (existsSync(rootPath(request.id))) throw new NativeBrainManagerError("unknown", "An unrecorded checkpoint occupies the requested identity.");
end = step?.("intent");
intent = { version: 1, id: request.id, sourceUuid: fixed.brainUuid, state: "creating" }; await writeIntent(intent);
end?.();
createdNow = true;
}
if (reserveConsumed) throw new NativeBrainManagerError("capacity", "Native recovery consumed emergency allocation; rearm capacity before checkpoint admission.");
signal?.throwIfAborted();
end = step?.("snapshot");
await command([BTRFS, "subvolume", "snapshot", "-r", brain, rootPath(request.id)], signal);
const checkpoint = await verifyOwned(intent, signal); await writeIntent({ ...intent, state: "sealed", checkpoint });
end?.(); end = step?.("verify");
const checkpoint = await verifyOwned(intent, signal);
end?.(); end = step?.("intent");
await writeIntent({ ...intent, state: "sealed", checkpoint });
end?.();
if (createdNow) createdAfterRecovery.add(request.id);
return Response.json(checkpoint);
}
Expand All @@ -671,20 +710,31 @@ export async function createNativeBrainManager(config: NativeBrainManagerConfig)
await writeIntent({ version: 1, id: request.id, sourceUuid: fixed.brainUuid, state: "deleted" });
return Response.json({ id: request.id, state: "deleted" });
}
end = step?.("reconcile");
intent = await reconcile(intent, signal);
end?.();
if (intent.state === "deleted") return Response.json({ id: request.id, state: "deleted" });
if (intent.state === "creating" && !existsSync(rootPath(request.id))) { await writeIntent({ ...intent, state: "deleted" }); return Response.json({ id: request.id, state: "deleted" }); }
end = step?.("verify");
const checkpoint = await verifyOwned(intent, signal);
end?.(); end = step?.("intent");
await writeIntent({ ...intent, state: "deleting", checkpoint });
end?.();
signal?.throwIfAborted();
end = step?.("delete");
await command([BTRFS, "subvolume", "delete", "--commit-after", rootPath(request.id)], signal);
end?.(); end = step?.("sync");
await syncDeleted(checkpoint.rootId, signal);
end?.(); end = step?.("intent");
await writeIntent({ ...intent, state: "deleted", checkpoint });
end?.();
return Response.json({ id: request.id, state: "deleted" });
}
const from = readIntent(request.from), to = readIntent(request.to);
if (!from || !to || from.state !== "sealed" || to.state !== "sealed") throw new NativeBrainManagerError("unknown", "Native delta requires two retained sealed checkpoint identities.");
end = step?.("verify");
await verifyOwned(from, signal); await verifyOwned(to, signal);
end?.(); sending = step?.("send");
const response = sendDelta(rootPath(from.id), rootPath(to.id), signal, release);
handedToStream = true;
return response;
Expand Down Expand Up @@ -737,8 +787,8 @@ export async function createNativeBrainManager(config: NativeBrainManagerConfig)
}

/** Unix socket only; filesystem ownership is authentication, and workers must mask the endpoint. */
export async function serveNativeBrainManager(config: NativeBrainManagerConfig) {
const fixed = Object.freeze({ ...config }), manager = await createNativeBrainManager(fixed);
export async function serveNativeBrainManager(config: NativeBrainManagerConfig, options: NativeBrainManagerOptions = {}) {
const fixed = Object.freeze({ ...config }), manager = await createNativeBrainManager(fixed, options);
if (existsSync(fixed.socketPath)) { await manager.close(); throw new NativeBrainManagerError("unsupported", "Native manager socket already exists; reconcile its service ownership before starting."); }
let server: ReturnType<typeof Bun.serve>;
try {
Expand Down
5 changes: 4 additions & 1 deletion packages/ui-server/src/brain/native-journal-observer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -388,11 +388,14 @@ export function createNativeJournalObserver(native: NativeJournalManager, worker
}
async function prepare(signal?: AbortSignal, timing?: PhaseTimer): Promise<NativeJournalObservation> {
await initialize(signal);
// The wait for room behind earlier releases (#2915), before any checkpoint.
let end = timing?.("observe_reserve");
await reserveRelease();
end?.();
const active = signalFor(signal), before = root!;
let after: NativeJournalCheckpoint | undefined, reader: RootMetadataReader | undefined;
try {
let end = timing?.("observe_checkpoint");
end = timing?.("observe_checkpoint");
after = await checkpoint(active);
end?.(); end = timing?.("observe_delta");
const job = await native.delta(before.id, after.id, active);
Expand Down
Loading
Loading