From 72fde42c3cb424cea5094dcebc6ce903674cda49 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 15 Nov 2026 13:25:57 +0000 Subject: [PATCH 1/2] fix(ui-sdk): let a read-only index connection not refuse native publication A read-only brain_search connection on the live index writes its read mark into .brain-index/brain.db-shm, or creates it, so native publication's stale-input check saw a changed sidecar and refused the whole refresh. The wal-index is shared memory, not data: it now follows its database, is never compared or copied, and is replaced by a fresh empty inode whenever the database or its WAL publishes, so no new connection pairs the published WAL with a wal-index an earlier reader still holds. Changes to the database, its WAL and every other output still refuse. Before-copy refusals now name the inspected and found stamps. Refs #2878 Co-Authored-By: Claude Opus 5.5 --- .../2878-index-wal-index-publication.md | 5 + docs/decisions/governed-writable-workers.md | 42 +++++++- .../ui-sdk/src/server/worker-native-output.ts | 65 ++++++++++- .../tests/fixtures/index-sqlite-connection.ts | 23 ++++ .../tests/native-worker-publication.test.ts | 101 +++++++++++++++++- .../src/brain/native-journal-policy.ts | 2 +- 6 files changed, 226 insertions(+), 12 deletions(-) create mode 100644 .changeset/2878-index-wal-index-publication.md create mode 100644 packages/ui-sdk/tests/fixtures/index-sqlite-connection.ts diff --git a/.changeset/2878-index-wal-index-publication.md b/.changeset/2878-index-wal-index-publication.md new file mode 100644 index 0000000000..6ad0e9819b --- /dev/null +++ b/.changeset/2878-index-wal-index-publication.md @@ -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. diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index 9c25a99843..bc6081d3f6 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -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-` 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. @@ -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`, @@ -1724,6 +1724,38 @@ 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 and is tracked separately. +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 @@ -2338,9 +2370,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 @@ -2365,7 +2397,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 diff --git a/packages/ui-sdk/src/server/worker-native-output.ts b/packages/ui-sdk/src/server/worker-native-output.ts index 6a1b32ed7b..24d6092616 100644 --- a/packages/ui-sdk/src/server/worker-native-output.ts +++ b/packages/ui-sdk/src/server/worker-native-output.ts @@ -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"; @@ -216,6 +217,28 @@ function currentVersion(root: string, rel: string): string | undefined { let handle: ReturnType; 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; 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 { @@ -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 { + 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(); @@ -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(), after = new Map(); - 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()) @@ -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}`); } @@ -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"); } @@ -432,14 +472,16 @@ export async function prepareNativeWorkerOutput(brain: string, options: { startu catch (error) { closeSync(source.fd); throw error; } let target: Awaited> | 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(); } } @@ -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 @@ -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); } @@ -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; } } diff --git a/packages/ui-sdk/tests/fixtures/index-sqlite-connection.ts b/packages/ui-sdk/tests/fixtures/index-sqlite-connection.ts new file mode 100644 index 0000000000..d4d7533b1e --- /dev/null +++ b/packages/ui-sdk/tests/fixtures/index-sqlite-connection.ts @@ -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(); diff --git a/packages/ui-sdk/tests/native-worker-publication.test.ts b/packages/ui-sdk/tests/native-worker-publication.test.ts index bc37e183a4..f8e196dcd7 100644 --- a/packages/ui-sdk/tests/native-worker-publication.test.ts +++ b/packages/ui-sdk/tests/native-worker-publication.test.ts @@ -1,7 +1,7 @@ /** Actual async publication over copied acquisition metadata; native storage is qualified separately. */ import { expect,spyOn,test } from "bun:test"; import * as fs from "node:fs"; -import { join } from "node:path"; +import { dirname, join } from "node:path"; import { prepareNativeWorkerStartupView } from "../src/server/worker-startup-view.js"; import { prepareNativeWorkerOutput } from "../src/server/worker-native-output.js"; import type { NativeStageChange } from "../src/server/native-brain-manager-protocol.js"; @@ -61,3 +61,102 @@ for (const rel of ["context", ".git", "notes", "group", "group/private"]) test(` } } finally {await output?.cleanup();await view.cleanup();pretend.mockRestore();fs.rmSync(store,{recursive:true,force:true});} }); + +// #2878: a worker's `brain_search` holds a real read-only connection on the +// live index. SQLite writes that connection's read mark into `brain.db-shm`, +// so the live sidecar's bytes differ from the checkpoint's although nothing +// indexed changed. Each SQLite connection runs in its own process, as in a +// hosted brain, so its locks and shared-memory mapping are not the test's. +const INDEX = ".brain-index/brain.db", CONNECTION = join(import.meta.dir, "fixtures/index-sqlite-connection.ts"); +const CHILD = [process.execPath, "--no-env-file", "--preload", join(import.meta.dir, "../../../scripts/test-network-child-preload.ts"), CONNECTION]; +function sqlite(mode: "seed" | "write" | "read", path: string, value?: string) { + const result = Bun.spawnSync([...CHILD, mode, path, ...(value ? [value] : [])], { env: { PATH: process.env.PATH }, stdout: "pipe", stderr: "pipe" }); + expect(result.exitCode, result.stderr.toString()).toBe(0); + return result.stdout.toString().trim(); +} +async function holdReader(path: string, mode: "hold" | "pin" = "hold") { + const child = Bun.spawn([...CHILD, mode, path], { env: { PATH: process.env.PATH }, stdin: "pipe", stdout: "pipe", stderr: "pipe" }); + const lines = child.stdout.getReader(), stderr = new Response(child.stderr).text(); + const first = await lines.read(); + expect(new TextDecoder().decode(first.value).trim(), "READONLY_CONNECTION_READ_THE_LIVE_INDEX").toBe(JSON.stringify({ value: "Ogygia" })); + return { alive: () => child.exitCode === null, async stop() { child.stdin.end(); const code = await child.exited; await lines.cancel(); expect(code, await stderr).toBe(0); } }; +} +async function indexPublication(interleave: (paths: { live: string; checkpoint: string; stage: string }) => Promise<(() => Promise) | void>, options: { withoutShm?: boolean; beforeCheckpoint?: (live: string) => Promise<() => Promise> } = {}) { + const store=fs.mkdtempSync("/tmp/odysseus-index-publication-"),brain=join(store,"brain"),sourceUuid="11111111111141118111111111111790",uuid="22222222222242228222222222221790"; + fs.mkdirSync(join(brain,"notes"),{recursive:true});fs.writeFileSync(join(brain,"notes/odysseus.md"),"Odysseus leaves Ogygia"); + sqlite("seed",join(brain,INDEX));if(options.withoutShm)fs.rmSync(join(brain,`${INDEX}-shm`)); + const statfs=fs.statfsSync,pretend=spyOn(fs,"statfsSync").mockImplementation(((path:any,options:any)=>{const value=statfs(path,options);return {...value,type:typeof value.type==="bigint"?0x9123683en:0x9123683e};}) as typeof fs.statfsSync); + const checkpoints=new Map(),family=["brain.db","brain.db-wal","brain.db-shm","brain.db-journal"].map(name=>`.brain-index/${name}`); + const start=fs.readFileSync(`/proc/${process.pid}/stat`,"utf8").replace(/^.*\) /s,"").split(" ")[19]!; + const manager={ + async checkpoint(id:string){const path=join(store,".brain-native/checkpoints",id);fs.cpSync(brain,path,{recursive:true});checkpoints.set(id,path);return {id,path,sourceUuid,uuid,fsid:"11111111-1111-4111-8111-111111111790",rootId:"257",transaction:"8",readOnly:true as const};}, + async release(id:string){fs.rmSync(checkpoints.get(id)!,{recursive:true,force:true});return{id,state:"deleted" as const};}, + async prepareStage(id:string,checkpointId:string,allowanceBytes:number){const path=join(store,".brain-native/stages",id);fs.mkdirSync(path,{recursive:true});fs.cpSync(checkpoints.get(checkpointId)!,join(path,"merged"),{recursive:true});const info=fs.statSync(path,{bigint:true});return{id,path,checkpointId,checkpointUuid:uuid,sourceUuid,allowanceBytes,namespacePid:process.pid,namespaceStart:start,appUid:process.getuid!(),appGid:process.getgid!(),rootDevice:String(info.dev),rootInode:String(info.ino)};}, + async inspectStage(){return{checkpointId:[...checkpoints.keys()][0]!,checkpointUuid:uuid,changes:(async function*(){for(const rel of [...family,"notes/odysseus.md"])yield {pathHex:Buffer.from(rel).toString("hex"),kind:"entry"} as NativeStageChange;})(),completed:Promise.resolve({exitCode:0 as const,bytes:0})};}, + async releaseStage(id:string){fs.rmSync(join(store,".brain-native/stages",id),{recursive:true,force:true});return{id,state:"deleted" as const};}, + }; + let early:(()=>Promise)|undefined,view:Awaited>|undefined,output:Awaited>|undefined,stop:(()=>Promise)|void=undefined; + try { + early=await options.beforeCheckpoint?.(brain); + view=await prepareNativeWorkerStartupView(brain,manager); + output=await prepareNativeWorkerOutput(brain,{startupView:view}); + // The maintenance worker's refresh: a real writer on the stage's index, then the note it indexed. + sqlite("write",join(output.output.source,INDEX),"Ithaca");fs.writeFileSync(join(output.output.source,"notes/odysseus.md"),"Odysseus reaches Ithaca"); + stop=await interleave({live:brain,checkpoint:view.root,stage:output.output.source}); + const live=()=>JSON.stringify([...family,"notes/odysseus.md"].map(rel=>{const path=join(brain,rel),info=fs.lstatSync(path,{throwIfNoEntry:false}); + return info?.isSymbolicLink()?["link",fs.readlinkSync(path)]:info?["file",fs.readFileSync(path).toString("hex")]:undefined;})); + const before=live();let failure:unknown;try{await output.publish();}catch(error){failure=error;} + // A new connection while every earlier reader is still open. + const attempt=failure?undefined:Bun.spawnSync([...CHILD,"read",join(brain,INDEX)],{env:{PATH:process.env.PATH},stdout:"pipe",stderr:"pipe"}); + const fresh=attempt&&(attempt.exitCode===0?attempt.stdout.toString().trim():attempt.stderr.toString().match(/SQLITE_[A-Z_]+/)?.[0]??`exit ${attempt.exitCode}`); + return {failure,brain,unchanged:before===live(),fresh,note:()=>fs.readFileSync(join(brain,"notes/odysseus.md"),"utf8")}; + } finally {try{await stop?.();await early?.();}finally{await output?.cleanup();await view?.cleanup();pretend.mockRestore();}} +} + +for (const [name,options] of [ + ["holds",{}],["creates an absent sidecar while it holds",{withoutShm:true}],["holds while the refresh removed its sidecar",{removeStageShm:true}], +] as const) test(`a concurrent read-only index connection that ${name} does not refuse the refreshed index`,async()=>{ + let reader:Awaited>|undefined,overlapped=false,shmChanged=false; + const result=await indexPublication(async({live,checkpoint,stage})=>{ + if("removeStageShm" in options)fs.rmSync(join(stage,`${INDEX}-shm`)); + reader=await holdReader(join(live,INDEX)); + const before=fs.existsSync(join(checkpoint,`${INDEX}-shm`))?fs.readFileSync(join(checkpoint,`${INDEX}-shm`)):undefined; + shmChanged=!before||!fs.readFileSync(join(live,`${INDEX}-shm`)).equals(before); + return async()=>{overlapped=reader!.alive();await reader!.stop();}; + },"withoutShm" in options?{withoutShm:true}:{}); + try { + expect(shmChanged,"REAL_READONLY_CONNECTION_CHANGED_LIVE_SHM").toBe(true); + expect(result.failure,"READONLY_SEARCH_MUST_NOT_BLOCK_INDEX_REFRESH").toBeUndefined(); + expect(overlapped,"READONLY_CONNECTION_OVERLAPPED_PUBLICATION").toBe(true); + expect(result.fresh,"REFRESHED_INDEX_IS_VISIBLE_TO_A_NEW_CONNECTION").toBe(JSON.stringify({value:"Ithaca"})); + expect(result.note()).toBe("Odysseus reaches Ithaca"); + } finally {fs.rmSync(dirname(result.brain),{recursive:true,force:true});} +}); + +for (const removed of [false,true]) test(`the refreshed index never shares a wal-index an earlier reader still holds${removed?" after the refresh removed its sidecar":""}`,async()=>{ + // A search still inside its read transaction keeps the last writer's + // checkpoint from resetting the live WAL, so the wal-index that reader holds + // describes frames. The refresh's own writer checkpoints and truncates its WAL. + const result=await indexPublication(async({stage})=>{if(removed)fs.rmSync(join(stage,`${INDEX}-shm`));},{beforeCheckpoint:async live=>{ + const reader=await holdReader(join(live,INDEX),"pin");sqlite("write",join(live,INDEX),"Aeaea"); + expect(fs.statSync(join(live,`${INDEX}-wal`)).size,"LIVE_WAL_KEEPS_UNCHECKPOINTED_FRAMES").toBeGreaterThan(0); + return ()=>reader.stop(); + }}); + try { + expect(result.failure,"READONLY_SEARCH_MUST_NOT_BLOCK_INDEX_REFRESH").toBeUndefined(); + expect(result.fresh,"NEW_CONNECTION_READS_THE_REFRESH_NOT_THE_OLD_WAL_INDEX").toBe(JSON.stringify({value:"Ithaca"})); + } finally {fs.rmSync(dirname(result.brain),{recursive:true,force:true});} +}); + +for (const [name,interleave,refusal] of [ + ["a concurrent index writer",async({live}:{live:string})=>{sqlite("write",join(live,INDEX),"Scheria");},/^stale maintenance output: \.brain-index\/brain\.db(-wal)?$/], + ["a concurrent note writer",async({live}:{live:string})=>{fs.writeFileSync(join(live,"notes/odysseus.md"),"Odysseus reaches Scheria");},/^stale maintenance output: notes\/odysseus\.md$/], + ["a link planted over the shared-memory sidecar",async({live}:{live:string})=>{fs.rmSync(join(live,`${INDEX}-shm`));fs.symlinkSync("../notes/odysseus.md",join(live,`${INDEX}-shm`));},/^stale maintenance output: \.brain-index\/brain\.db-shm$/], +] as const) test(`native index publication still refuses ${name}`,async()=>{ + const result=await indexPublication(interleave); + try { + expect(result.failure,"OTHER_CONCURRENT_OUTPUT_CHANGE_STILL_REFUSES").toBeInstanceOf(Error); + expect((result.failure as Error).message).toMatch(refusal); + expect(result.unchanged,"REFUSAL_PUBLISHED_NO_INDEX_OR_NOTE_BYTES").toBe(true); + } finally {fs.rmSync(dirname(result.brain),{recursive:true,force:true});} +}); diff --git a/packages/ui-server/src/brain/native-journal-policy.ts b/packages/ui-server/src/brain/native-journal-policy.ts index 4b934534ca..a29d26a4cd 100644 --- a/packages/ui-server/src/brain/native-journal-policy.ts +++ b/packages/ui-server/src/brain/native-journal-policy.ts @@ -12,7 +12,7 @@ const indexFamilyPaths = new Set(INDEX_FAMILY_PATHS); /** * Maintenance publication stages each changed file as `.maintenance-` * beside its target, then renames it over the target (`const handle = { fd: preparationDirectory(brain, rel), name:`, - * `packages/ui-sdk/src/server/worker-native-output.ts:397`; `const temporary = at(handle.fd,`, + * `packages/ui-sdk/src/server/worker-native-output.ts:443`; `const temporary = at(handle.fd,`, * `packages/ui-sdk/src/server/worker-output.ts:180`). Inside the index * directory such a copy is an index refresh in progress. As a SQLite GLOB. */ From a3293ee80e96348623d7ddf307180da015b7faec Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 15 Nov 2026 13:26:54 +0000 Subject: [PATCH 2/2] docs(decisions): link the wal-index publication follow-ups Refs #2878 Co-Authored-By: Claude Opus 5.5 --- docs/decisions/governed-writable-workers.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index bc6081d3f6..55f8318215 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -1753,7 +1753,8 @@ 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 and is tracked separately. +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)