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/2878-index-wal-index-publication.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@schlessera/brain-ui-sdk": patch
---

Native index publication no longer refuses a refresh because a read-only search connection touched the index's SQLite wal-index. Before, a worker's `brain_search` reading the live index while a refresh was being prepared changed `.brain-index/brain.db-shm`, and the whole refresh failed with `stale maintenance output: .brain-index/brain.db-shm`. Search then kept serving the old index until a later refresh happened to succeed. Now the wal-index follows its database: it is replaced with a fresh empty file whenever `brain.db` or `brain.db-wal` publishes, so no new connection shares a wal-index an earlier reader still holds. A concurrent change to the database, its WAL or any other output is still refused. A changed stage file refused before or during its copy (`Native output changed before copy`) now names the inspected and the found stamp.
43 changes: 38 additions & 5 deletions docs/decisions/governed-writable-workers.md
Original file line number Diff line number Diff line change
Expand Up @@ -1594,7 +1594,7 @@ from Markdown, and restoring an old copy over a newer one only makes it stale.
below), and a `.brain-index/.maintenance-<uuid>` publication copy,
by journal-relative path in the brain root's own capture, named from the shared
index location constants (`export function journalMetadataOnlyPath`,
`packages/ui-server/src/brain/native-journal-policy.ts:31-33`). Another name
`packages/ui-server/src/brain/native-journal-policy.ts:32-34`). Another name
inside `.brain-index/`, another root's `.brain-index/` (a workspace or a
managed worktree) and a similarly named file elsewhere stay ordinary content
with retained bytes.
Expand Down Expand Up @@ -1667,7 +1667,7 @@ keeps beside the index; it carries no authoritative content either.
the sidecars SQLite may create beside it, and the journal's family is
`INDEX_FAMILY` plus that list under `.brain-index/`
(`export const INDEX_FAMILY_PATHS`,
`packages/ui-server/src/brain/native-journal-policy.ts:9`). Observation,
`packages/ui-server/src/brain/native-journal-policy.ts:10`). Observation,
before-version capture, removal coverage, history, preview, download and
revert therefore treat it exactly as the index. A similarly named file,
`.brain-index/brain.db.embedding-lock.db.bak` or `notes/brain.db.embedding-lock.db`,
Expand Down Expand Up @@ -1724,6 +1724,39 @@ after every turn on a large journal (#2913).
before the admitted index below. The purge-only enforcement exception remains
scoped to its second commit; ordinary collection keeps enforcement enabled.

### The index's wal-index at native publication — 2026-11-15 (#2878)

Native publication compares each changed output's live entry with the one
its worker started from and refuses a difference (`stale maintenance
output`). For `.brain-index/brain.db-shm` that comparison was wrong. The
file is SQLite's wal-index: shared memory, not data. A read-only
`brain_search` connection on the live index writes its read mark into the
file, or creates it when it is missing. So the live bytes differed from the
checkpoint's while nothing indexed had changed, and the whole refresh was
refused. Search then served the old index until a later refresh happened to
succeed.

**The ruling.** The wal-index follows its database. It is never hashed,
compared or copied. Whenever `brain.db` or `brain.db-wal` publishes, a fresh
empty file replaces it, or it is removed when the refresh removed its own. A
fresh inode is required, not just allowed: a reader that is still open keeps
its wal-index mapped. A new connection that paired the published WAL with
that file would follow frames that file still describes, and fail with
`SQLITE_IOERR_SHORT_READ`. The first connection to open an inode nobody
holds discards its contents and rebuilds it from the WAL, so the empty file
loses nothing. Publication still refuses a wal-index that is a link or a
directory. Every write to the index changes the database or its WAL, and
those two keep the full stale-input refusal, so a concurrent writer is still
refused (`const WAL_INDEX`,
`packages/ui-sdk/src/server/worker-native-output.ts:231-240`). A refusal of a
changed stage file before or during its copy now names the inspected and the
found stamp, so a recurrence identifies what changed.

**Not covered.** Copy-staged publication (`worker-output.ts`), used without
native storage, has the same comparison (#4009). Which stage writer
changed `brain.db` before its copy in the earlier timing runs is #4010.
Publishing the family is still a sequence of renames, not one atomic step.

### Admitted object-pin index and near-cap recovery — 2026-10-26 (#2913)

> **Maintainer ruling (2026-10-25), option A.** Index pins by hash through an
Expand Down Expand Up @@ -2338,9 +2371,9 @@ owner prepares each concrete command; the synchronous launcher consumes its
private plan once, bound to the stage/checkpoint, keeper identity, command and
stage generation. Stale, foreign, closed or unprepared protected inputs refuse
before payload (`prepareNativeMaintenanceMasks`,
`packages/ui-sdk/src/server/worker-native-output.ts:101-120`),
`packages/ui-sdk/src/server/worker-native-output.ts:103-122`),
(`consumeNativeMaintenanceMasks`,
`packages/ui-sdk/src/server/worker-native-output.ts:133-138`).
`packages/ui-sdk/src/server/worker-native-output.ts:135-140`).

Configured-helper credential-free maintenance uses the same verified launcher
as agent workers. It retains one execution view and binds the owned stage drain
Expand All @@ -2365,7 +2398,7 @@ publication also checks live absence and excludes only those exact validated
empty directories. Protected descendants and unregistered changes still refuse.
Partial installation poisons the disposable stage; cleanup retains the existing
owned drain (`validateGitScaffolds`,
`packages/ui-sdk/src/server/worker-native-output.ts:310-322`).
`packages/ui-sdk/src/server/worker-native-output.ts:347-363`).

### Owned runtime placement beneath `/tmp` — 2026-10-14

Expand Down
65 changes: 60 additions & 5 deletions packages/ui-sdk/src/server/worker-native-output.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
/** Changed-only publication from a root-inspected trusted OverlayFS stage. */
import { isWithin } from "@schlessera/brain-common/internal/safe-path";
import { INDEX_DB_PATH } from "@schlessera/brain-common/internal/index-location";
import { closeSync, constants, fstatSync, fchmodSync, lstatSync, linkSync, mkdirSync, openSync, readFileSync, readdirSync, readlinkSync, renameSync, rmSync, rmdirSync, symlinkSync, unlinkSync } from "node:fs";
import { open } from "node:fs/promises";
import { createHash, randomUUID } from "node:crypto";
Expand Down Expand Up @@ -216,6 +217,28 @@ function currentVersion(root: string, rel: string): string | undefined {
let handle: ReturnType<typeof parent>; try { handle = parent(root, rel); } catch (error) { if (absent(error)) return undefined; throw error; }
try { return versionAt(handle.fd, handle.name); } finally { closeSync(handle.fd); }
}
/**
* SQLite's wal-index for the index database (#2878). It is shared memory, not
* data: every connection maps it, and a read-only `brain_search` writes its
* read mark into it or creates it, so its bytes differ from the checkpoint's
* while nothing indexed changed. The first connection to open an inode nobody
* holds discards its contents and rebuilds it from the WAL. It is therefore
* never compared or copied: whenever the database or its WAL publishes, a
* fresh empty inode replaces it, so no new connection pairs the new WAL with a
* wal-index an old reader still holds. Every write to the index still changes
* the database or its WAL, which keep the full stale-input refusal.
*/
const WAL_INDEX = `${INDEX_DB_PATH}-shm`, WAL_INDEX_FAMILY = [INDEX_DB_PATH, `${INDEX_DB_PATH}-wal`];
/** Only its kind and mode: a regular file, an absent name, or something publication refuses. */
function walIndexAt(fd: number, name: string): Entry | undefined {
const info = lstatSync(at(fd, name), { bigint: true, throwIfNoEntry: false });
if (!info) return undefined;
return info.isFile() ? { type: "file", mode: Number(info.mode & 0o777n) } : { type: info.isDirectory() ? "directory" : "symlink", mode: Number(info.mode & 0o7777n) };
}
function walIndexEntry(root: string, rel: string): Entry | undefined {
let handle: ReturnType<typeof parent>; try { handle = parent(root, rel); } catch (error) { if (absent(error)) return undefined; throw error; }
try { return walIndexAt(handle.fd, handle.name); } finally { closeSync(handle.fd); }
}
function processStart(pid: number) { return Bun.file(`/proc/${pid}/stat`).text().then(t => t.replace(/^.*\) /s, "").split(" ")[19]); }
/** Acquisition completes before any synchronous SDK spawn callback. No copy/userxattr fallback. */
export async function prepareNativeWorkerOutput(brain: string, options: { startupView: WorkerStartupView; areas?: readonly string[]; folderPaths?: readonly string[]; signal?: AbortSignal }): Promise<PreparedWorkerOutput> {
Expand Down Expand Up @@ -314,6 +337,13 @@ export async function prepareNativeWorkerOutput(brain: string, options: { startu
if ((await privateStat(stageInput, rel))?.stamp !== info.stamp) throw Error("Native private output changed while hashing");
return { entry: { type: "file", mode: info.mode, hash: hash.digest("hex") }, stamp: version };
}
async function walIndexInput(stageInput: boolean): Promise<Captured> {
try { return { entry: walIndexEntry(stageInput ? output.source : view.root, WAL_INDEX), stamp: undefined }; }
catch (error) { if (!identityTicket || !permissionDenied(error)) throw error; }
const info = await privateStat(stageInput, WAL_INDEX);
if (!info) return { entry: undefined, stamp: undefined };
return { entry: info.kind === "file" ? { type: "file", mode: info.mode } : { type: info.kind === "directory" ? "directory" : "symlink", mode: info.mode }, stamp: undefined };
}
async function validateGitScaffolds(signal?: AbortSignal, live = false) {
if (!gitParentInode && gitScaffolds.size === 0) return;
const uid = await readerUid();
Expand Down Expand Up @@ -363,11 +393,15 @@ export async function prepareNativeWorkerOutput(brain: string, options: { startu
if (receipt.checkpointId !== native.checkpoint.id || receipt.checkpointUuid !== native.checkpoint.uuid) throw Error("Native output inspection changed its lower identity");
const selected = (rel: string) => !options.areas || options.areas.some(area => isWithin(area, rel));
const before = new Map<string, Captured>(), after = new Map<string, Captured>();
for (const rel of [...candidates].filter(selected).sort()) {
for (const rel of [...candidates].filter(rel => selected(rel) && rel !== WAL_INDEX).sort()) {
const next = await inspectInput(true, rel); after.set(rel, next);
before.set(rel, await inspectInput(false, rel, !next.entry));
}
const changed = [...before.keys()].filter(rel => !equal(before.get(rel)!.entry, after.get(rel)!.entry));
if (selected(WAL_INDEX) && changed.some(rel => WAL_INDEX_FAMILY.includes(rel))) {
before.set(WAL_INDEX, await walIndexInput(false)); after.set(WAL_INDEX, await walIndexInput(true));
changed.push(WAL_INDEX); changed.sort();
}
const releases: (() => void)[] = [];
try {
if (lock) for (const rel of [...new Set([...changed, ...[...gitScaffolds.keys()].map(name => `.git/${name}`)])].sort())
Expand All @@ -386,6 +420,11 @@ export async function prepareNativeWorkerOutput(brain: string, options: { startu
const target = resolve(brain, join(rel, ".."), next.link!);
if (!isWithin(brain, target) || rel.startsWith(".git/") || PROTECTED_TIER_A.some(p => isWithin(rel, p, { includeRoot: false }))) throw Error(`maintenance output has an escaping link: ${rel}`);
}
if (rel === WAL_INDEX) {
const live = walIndexEntry(brain, rel);
if (next && next.type !== "file" || live && live.type !== "file") throw Error(`stale maintenance output: ${rel}`);
continue;
}
const live = await inspect(brain, rel, previous?.type === "directory" && !next); authoritative.set(rel, live);
if (!equal(previous, live.entry, previous?.type === "directory" && !next)) throw Error(`stale maintenance output: ${rel}`);
}
Expand All @@ -404,10 +443,11 @@ export async function prepareNativeWorkerOutput(brain: string, options: { startu
const handle = { fd: preparationDirectory(brain, rel), name: `.maintenance-${randomUUID()}` }, temporary = at(handle.fd, handle.name);
pending.push({ rel, ...handle, temporary, next });
if (next.type === "symlink") symlinkSync(next.link!, temporary);
else if (rel === WAL_INDEX) { const target = await open(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL, next.mode); try { await target.chmod(next.mode); } finally { await target.close(); } }
else {
if (after.get(rel)!.stamp?.startsWith("worker:")) {
const beforeRead = await privateStat(true, rel);
if (`worker:${beforeRead?.stamp}:${beforeRead?.mode}:${beforeRead?.kind}` !== after.get(rel)!.stamp) throw Error(`Native private output changed before copy: ${rel}`);
if (`worker:${beforeRead?.stamp}:${beforeRead?.mode}:${beforeRead?.kind}` !== after.get(rel)!.stamp) throw Error(`Native private output changed before copy: ${rel} (inspected ${after.get(rel)!.stamp}, found worker:${beforeRead?.stamp}:${beforeRead?.mode}:${beforeRead?.kind})`);
try {
pending.at(-1)!.recovery = processStateLedger().reserve(undefined, undefined, { allowanceBytes: beforeRead!.bytes, budgetBytes: hostOutputStagingLimits().budgetBytes });
} catch { throw Error("Native private output recovery capacity unavailable; the turn already executed and its output was not published"); }
Expand All @@ -432,14 +472,16 @@ export async function prepareNativeWorkerOutput(brain: string, options: { startu
catch (error) { closeSync(source.fd); throw error; }
let target: Awaited<ReturnType<typeof open>> | undefined;
try {
if (stamp(await input.stat({ bigint: true })) !== after.get(rel)!.stamp) throw Error(`Native output changed before copy: ${rel}`);
const found = stamp(await input.stat({ bigint: true }));
if (found !== after.get(rel)!.stamp) throw Error(`Native output changed before copy: ${rel} (inspected ${after.get(rel)!.stamp}, found ${found})`);
target = await open(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL, next.mode);
const buffer = Buffer.alloc(64 * 1024);
for (;;) { const { bytesRead } = await input.read(buffer); if (!bytesRead) break; let written = 0;
while (written < bytesRead) written += (await target.write(buffer, written, bytesRead - written)).bytesWritten;
await Bun.sleep(0);
}
if (stamp(await input.stat({ bigint: true })) !== after.get(rel)!.stamp) throw Error(`Native output changed during copy: ${rel}`);
const copied = stamp(await input.stat({ bigint: true }));
if (copied !== after.get(rel)!.stamp) throw Error(`Native output changed during copy: ${rel} (inspected ${after.get(rel)!.stamp}, found ${copied})`);
await target.chmod(next.mode);
} finally { closeSync(source.fd); await input.close(); await target?.close(); }
}
Expand All @@ -448,6 +490,7 @@ export async function prepareNativeWorkerOutput(brain: string, options: { startu
if (await processStart(stage!.namespacePid).catch(() => undefined) !== stage!.namespaceStart) throw Error("Native output stage was lost; discard outputs and reconcile ownership");
// Recheck all bases after async preparation and before the first mutation.
for (const rel of changed) {
if (rel === WAL_INDEX) { const live = walIndexEntry(brain, rel); if (live && live.type !== "file") throw Error(`stale maintenance output: ${rel}`); continue; }
const current = currentVersion(brain, rel), expected = authoritative.get(rel)!.stamp;
// Parent-local preparation changes only directory timestamps. The
// established directory predicate guards inode/mode; deletion also
Expand All @@ -456,7 +499,14 @@ export async function prepareNativeWorkerOutput(brain: string, options: { startu
if (directory ? current?.split(":").slice(0,3).join(":") !== expected?.split(":").slice(0,3).join(":") : current !== expected) throw Error(`stale maintenance output: ${rel}`);
}
for (const rel of changed.filter(p => !after.get(p)!.entry).sort((a,b) => b.split("/").length-a.split("/").length)) {
const handle = parent(brain, rel); try { const current = versionAt(handle.fd, handle.name), expected = authoritative.get(rel)!.stamp;
const handle = parent(brain, rel); try {
if (rel === WAL_INDEX) {
const current = walIndexAt(handle.fd, handle.name);
if (current && current.type !== "file") throw Error(`stale maintenance output: ${rel}`);
try { unlinkSync(at(handle.fd, handle.name)); } catch (error) { if (!absent(error)) throw error; }
continue;
}
const current = versionAt(handle.fd, handle.name), expected = authoritative.get(rel)!.stamp;
if (before.get(rel)!.entry!.type === "directory" ? current?.split(":").slice(0,3).join(":") !== expected?.split(":").slice(0,3).join(":") : current !== expected) throw Error(`stale maintenance output: ${rel}`);
if (before.get(rel)!.entry!.type === "directory") rmdirSync(at(handle.fd, handle.name)); else unlinkSync(at(handle.fd, handle.name));
} finally { closeSync(handle.fd); }
Expand All @@ -474,6 +524,11 @@ export async function prepareNativeWorkerOutput(brain: string, options: { startu
for (const item of pending) {
const destination = parent(brain, item.rel);
try {
if (item.rel === WAL_INDEX) {
const current = walIndexAt(destination.fd, destination.name);
if (current && current.type !== "file") throw Error(`stale maintenance output: ${item.rel}`);
renameSync(item.temporary!, at(destination.fd,destination.name)); continue;
}
if (versionAt(destination.fd, destination.name) !== authoritative.get(item.rel)!.stamp) throw Error(`stale maintenance output: ${item.rel}`);
if (before.get(item.rel)!.entry) renameSync(item.temporary!, at(destination.fd,destination.name));
else { try { linkSync(item.temporary!, at(destination.fd,destination.name)); } catch (error) { if ((error as NodeJS.ErrnoException).code === "EEXIST") throw Error(`stale maintenance output: ${item.rel}`); throw error; } }
Expand Down
23 changes: 23 additions & 0 deletions packages/ui-sdk/tests/fixtures/index-sqlite-connection.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/**
* One real SQLite connection on a fictional index, opened with the product's
* own opener in its own process, so its POSIX locks and shared-memory mapping
* are a separate connection's rather than the test's (#2878).
*
* `seed` creates the table, `write` replaces its one value, `read` prints it,
* and `hold` reads it read-only like a worker's `brain_search`, then keeps that
* connection open until its stdin closes. `pin` does the same inside an open
* read transaction, as a search still running holds its snapshot.
*/
import { openDatabase } from "../../../core/src/lib/db.ts";

const [mode, path, value] = process.argv.slice(2);
if (!path || !["seed", "write", "read", "hold", "pin"].includes(mode ?? "")) throw Error("INDEX_CONNECTION_USAGE");
const reader = mode === "read" || mode === "hold" || mode === "pin";
const db = openDatabase(path, { readonly: reader });
if (mode === "seed") { db.run("CREATE TABLE odysseus (value TEXT NOT NULL)"); db.run("INSERT INTO odysseus VALUES ('Ogygia')"); }
if (mode === "write") db.run("UPDATE odysseus SET value = ?", [value ?? "Ithaca"]);
if (mode === "pin") db.run("BEGIN");
if (reader) console.log(JSON.stringify(db.query("SELECT value FROM odysseus").get()));
if (mode === "hold" || mode === "pin") await new Response(Bun.stdin.stream()).text();
if (mode === "pin") db.run("COMMIT");
db.close();
Loading
Loading