From d6a79670faac65483325d385b50381ea261e28f5 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Wed, 4 Nov 2026 08:53:44 +0000 Subject: [PATCH] fix(ui-sdk): observe again after an empty worker mount table during sandbox setup (#2701) bubblewrap reports the worker PID before it builds its mounts. The kernel lists only mounts reachable from the root captured when mountinfo was opened, so a read opened just before pivot_root detaches that root is empty. The readiness loop treated that as a malformed table and refused. An empty read is now "not ready": the loop observes again within the same deadline and identity checks, and only a complete table holding every pin qualifies. A table that stays empty refuses at the deadline; a malformed record refuses at once; an empty read at the brain-view check refuses. Every refusal carries call site, bytes, lines, worker state/start and elapsed time. Refs #3559 Co-Authored-By: Claude Opus 5.5 --- .changeset/worker-mountinfo-empty-read.md | 5 ++ docs/decisions/governed-writable-workers.md | 4 +- .../ui-sdk/src/server/worker-protection.ts | 51 ++++++++--- .../tests/worker-mountinfo-read.test.ts | 90 +++++++++++++++++++ 4 files changed, 138 insertions(+), 12 deletions(-) create mode 100644 .changeset/worker-mountinfo-empty-read.md create mode 100644 packages/ui-sdk/tests/worker-mountinfo-read.test.ts diff --git a/.changeset/worker-mountinfo-empty-read.md b/.changeset/worker-mountinfo-empty-read.md new file mode 100644 index 0000000000..a2b4a93c96 --- /dev/null +++ b/.changeset/worker-mountinfo-empty-read.md @@ -0,0 +1,5 @@ +--- +"@schlessera/brain-ui-sdk": patch +--- + +A governed worker launch no longer refuses intermittently with `invalid worker mount record` while bubblewrap is still building the sandbox (#2701). The worker's PID is reported before its mounts exist, and a mount table opened just before bubblewrap's `pivot_root` detaches the old root reads empty. The folder qualification now observes again after an empty read, within the same deadline and worker-identity checks, and only a complete table that holds every retained folder qualifies. A table that stays empty still refuses at the deadline, and a malformed record still refuses at once. Each refusal now names the call site (`readiness` or `brain-view`), the read's byte and line count, the worker's process state and start time, and the elapsed observation time. diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index 96ab3673a2..1ca8f34ba3 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -2503,9 +2503,9 @@ coordinator. The server checks the handle's mount ID against the worker's own mount table: it must be the top mount at the brain path. It then runs the unchanged comparison of brain, pins, empty masks and the private index relative to the handle (`function requireWorkerBrainMount`, -`packages/ui-sdk/src/server/worker-protection.ts:344-351`; +`packages/ui-sdk/src/server/worker-protection.ts:370-379`; `export function verifyWorkerFolderMounts`, -`packages/ui-sdk/src/server/worker-protection.ts:354-392`). +`packages/ui-sdk/src/server/worker-protection.ts:382-423`). The server returns the handle before release, and the coordinator refuses to release the start gate, or open a second view, while one is held (`if operation == 'release':`, diff --git a/packages/ui-sdk/src/server/worker-protection.ts b/packages/ui-sdk/src/server/worker-protection.ts index ba07f3daf6..347a2f46f1 100644 --- a/packages/ui-sdk/src/server/worker-protection.ts +++ b/packages/ui-sdk/src/server/worker-protection.ts @@ -332,19 +332,47 @@ export function dataTreeMounts(brain: string, target: string, tree: WorkerDataTr export interface WorkerBrainView { open(): WorkerSteps; close(): WorkerSteps } interface MountRecord { readonly id: string; readonly parent: string; readonly point: string } -function mountRecords(pid: number): MountRecord[] { - return readFileSync(`/proc/${pid}/mountinfo`, "utf8").trim().split("\n").map(line => { +type MountSite = "readiness" | "brain-view"; +/** + * Read the worker's mount table, or `undefined` for an empty read (#2701). + * Bubblewrap reports its child's PID before it builds the sandbox. The kernel + * lists only mounts reachable from the root it captured when the file was + * opened, so a read opened just before a `pivot_root` detaches that root lists + * nothing. An empty table is never a qualified view; the caller decides + * whether to observe again. A malformed record refuses here, with the read's + * size, call site and worker state so any occurrence is attributable. + */ +function mountRecords(pid: number, site: MountSite, since: number): MountRecord[] | undefined { + const text = readFileSync(`/proc/${pid}/mountinfo`, "utf8"); + if (!text.trim()) return undefined; + return text.trim().split("\n").map((line, index) => { const [id, parent, , , field] = line.split(" "); - if (!id || !parent || !field) throw new Error("invalid worker mount record"); + if (!id || !parent || !field) throw new Error(`invalid worker mount record: malformed record ${index + 1} at ${site}${mountReadDetail(pid, text, since)}`); return { id, parent, point: field.replace(/\\([0-7]{3})/g, (_match, octal: string) => String.fromCharCode(parseInt(octal, 8))) }; }); } +/** Size, worker state/start time and elapsed observation for a refused mount read. Never mount sources or paths. */ +function mountReadDetail(pid: number, text: string, since: number): string { + let state: string; + try { + const fields = readFileSync(`/proc/${pid}/stat`, "utf8").replace(/^.*\) /s, "").split(" "); + state = `worker state ${fields[0]} start ${fields[19]}`; + } catch (error) { state = `worker state unavailable (${code(error)})`; } + return ` (${Buffer.byteLength(text)} bytes, ${text ? text.split("\n").length : 0} lines, ${state}, after ${Date.now() - since}ms)`; +} + +function emptyMountRead(pid: number, site: MountSite, since: number): Error { + return new Error(`invalid worker mount record: empty read at ${site}${mountReadDetail(pid, "", since)}`); +} + /** The handle must be the top mount at the brain path in this worker's own namespace. */ -function requireWorkerBrainMount(fd: number, pid: number, brain: string): void { +function requireWorkerBrainMount(fd: number, pid: number, brain: string, since: number): void { const id = /^mnt_id:\s*(\d+)$/m.exec(readFileSync(`/proc/self/fdinfo/${fd}`, "utf8"))?.[1]; // Mount IDs are unique system-wide, so a listed ID is a mount of this namespace. - const records = mountRecords(pid); + // Readiness already saw the complete table, so an empty read here refuses. + const records = mountRecords(pid, "brain-view", since); + if (!records) throw emptyMountRead(pid, "brain-view", since); if (!id || !records.some(record => record.id === id && record.point === brain) || records.some(record => record.parent === id && record.point === brain)) throw new Error("the brain view is not the worker's own brain mount"); @@ -371,14 +399,17 @@ export function* verifyWorkerFolderMountsSteps(brain: string, protection: Worker throw new Error("provider folder topology worker identity is unavailable"); return fields[19]!; }; + const since = Date.now(); try { const started = identity(); for (;;) { - const mounts = new Set(mountRecords(pid).map(record => record.point)); + const records = mountRecords(pid, "readiness", since); // The authenticated PID can be reported before bubblewrap finishes its - // mount sequence. No payload runs while this bounded observation waits. - if (qualified.pins.every(pin => mounts.has(join(brain, pin.rel)))) break; - if (Date.now() >= deadline) throw new Error("retained folder mount points are unavailable"); + // mount sequence. No payload runs while this bounded observation waits: + // an empty read is observed again, and only a complete table qualifies. + const mounts = new Set(records?.map(record => record.point)); + if (records && qualified.pins.every(pin => mounts.has(join(brain, pin.rel)))) break; + if (Date.now() >= deadline) throw records ? new Error("retained folder mount points are unavailable") : emptyMountRead(pid, "readiness", since); if (identity() !== started) throw new Error("worker identity changed"); yield* workerStepSleep(1); } @@ -387,7 +418,7 @@ export function* verifyWorkerFolderMountsSteps(brain: string, protection: Worker let handle: number | undefined; try { handle = view ? yield* view.open() : undefined; - if (handle !== undefined) requireWorkerBrainMount(handle, pid, brain); + if (handle !== undefined) requireWorkerBrainMount(handle, pid, brain, since); verifyMountedFolders(handle === undefined ? `/proc/${pid}/root${brain}` : `/proc/self/fd/${handle}`, qualified, masks); } finally { try { if (handle !== undefined) closeSync(handle); } finally { if (view) yield* view.close(); } diff --git a/packages/ui-sdk/tests/worker-mountinfo-read.test.ts b/packages/ui-sdk/tests/worker-mountinfo-read.test.ts new file mode 100644 index 0000000000..cd99bc5ea9 --- /dev/null +++ b/packages/ui-sdk/tests/worker-mountinfo-read.test.ts @@ -0,0 +1,90 @@ +// #2701: bubblewrap reports the worker's PID before it builds the sandbox's +// mount table. A `/proc//mountinfo` opened against a root that the next +// `pivot_root` detaches lists nothing, because the kernel skips every mount +// unreachable from the root captured at open. That empty read is "not ready +// yet", never a qualified view. A malformed record still refuses at once. +import { afterEach, expect, spyOn, test } from "bun:test"; +import * as fs from "node:fs"; +import { mkdirSync, mkdtempSync, realpathSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { resolveWorkerProtection, verifyWorkerFolderMounts } from "../src/server/worker-protection.js"; +import { workerStep } from "../src/server/worker-steps.js"; + +const roots: string[] = []; +const restores: (() => void)[] = []; +afterEach(() => { + for (const restore of restores.splice(0)) restore(); + for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); +}); + +/** A brain whose `group/private` folder is retained, qualified for this process as the "worker". */ +function qualifiedBrain() { + const brain = realpathSync(mkdtempSync(join(tmpdir(), "mountinfo-read-"))); roots.push(brain); + mkdirSync(join(brain, "group/private"), { recursive: true }); + const { protection, reason } = resolveWorkerProtection(brain, { paths: [], folderPaths: ["group/private"] }); + expect(reason, "FIXTURE_FOLDER_QUALIFIED").toBeUndefined(); + const complete = ["21 1 0:31 / / rw - tmpfs tmpfs rw", `22 21 0:32 / ${brain}/group rw - ext4 ext4 rw`, + `23 22 0:33 / ${brain}/group/private rw - ext4 ext4 rw`].join("\n") + "\n"; + return { brain, protection, retained: ["group/private"], complete }; +} + +/** Feed the worker's mountinfo reads from a script; the last entry repeats. */ +function scriptMountinfo(pid: number, reads: readonly string[]) { + const original = fs.readFileSync; + let served = 0; + const spy = spyOn(fs, "readFileSync").mockImplementation(((...args: Parameters) => { + if (String(args[0]) !== `/proc/${pid}/mountinfo`) return (original as (...a: unknown[]) => unknown)(...args); + const text = reads[Math.min(served++, reads.length - 1)]!; + return args[1] === undefined ? Buffer.from(text) : text; + }) as typeof fs.readFileSync); + restores.push(() => spy.mockRestore()); + return { served: () => served }; +} + +test("an empty mountinfo read during sandbox setup waits for the complete table and then qualifies", () => { + const { brain, protection, retained, complete } = qualifiedBrain(); + const reads = scriptMountinfo(process.pid, ["", "", complete]); + expect(() => verifyWorkerFolderMounts(brain, protection, retained, process.pid, Date.now() + 5_000), + "EMPTY_SETUP_READ_IS_NOT_A_MALFORMED_TABLE").not.toThrow(); + expect(reads.served(), "QUALIFIED_ONLY_FROM_THE_COMPLETE_TABLE").toBe(3); +}); + +test("a mount table that stays empty refuses at the deadline with its read diagnostics", () => { + const { brain, protection, retained } = qualifiedBrain(); + scriptMountinfo(process.pid, [""]); + let refusal: unknown; + try { verifyWorkerFolderMounts(brain, protection, retained, process.pid, Date.now() + 50); } catch (error) { refusal = error; } + const message = String(refusal); + expect(message, "EMPTY_TABLE_NEVER_QUALIFIES").toContain("provider folder topology could not be qualified before payload start: invalid worker mount record"); + expect(message, "DIAGNOSTIC_NAMES_EMPTY_READ_AND_CALL_SITE").toContain("empty read at readiness"); + expect(message, "DIAGNOSTIC_NAMES_BYTE_LENGTH").toContain("0 bytes"); + expect(message, "DIAGNOSTIC_NAMES_WORKER_STATE").toMatch(/worker state [A-Za-z] start \d+/); + expect(message, "DIAGNOSTIC_NAMES_ELAPSED").toMatch(/after \d+ms/); +}); + +test("a malformed mount record refuses at once, without waiting for the deadline", () => { + const { brain, protection, retained, complete } = qualifiedBrain(); + const reads = scriptMountinfo(process.pid, [`${complete}24 23\n`]); + const started = Date.now(); + let refusal: unknown; + try { verifyWorkerFolderMounts(brain, protection, retained, process.pid, Date.now() + 5_000); } catch (error) { refusal = error; } + expect(String(refusal), "MALFORMED_TABLE_STILL_REFUSES").toContain("invalid worker mount record: malformed record 4 at readiness"); + expect(String(refusal), "MALFORMED_DIAGNOSTIC_NAMES_BYTES").toContain(`${Buffer.byteLength(`${complete}24 23\n`)} bytes`); + expect(reads.served(), "MALFORMED_TABLE_IS_NOT_RETRIED").toBe(1); + expect(Date.now() - started, "MALFORMED_TABLE_REFUSES_BEFORE_THE_DEADLINE").toBeLessThan(2_000); +}); + +test("an empty read at the brain-view check refuses and names that call site", () => { + const { brain, protection, retained, complete } = qualifiedBrain(); + scriptMountinfo(process.pid, [complete, ""]); + let closed = 0; + const open = () => fs.openSync(brain, fs.constants.O_RDONLY | fs.constants.O_DIRECTORY), close = () => { closed++; }; + let refusal: unknown; + try { + verifyWorkerFolderMounts(brain, protection, retained, process.pid, Date.now() + 5_000, undefined, + { open: () => workerStep(open, async () => open()), close: () => workerStep(close, async () => close()) }); + } catch (error) { refusal = error; } + expect(String(refusal), "BRAIN_VIEW_EMPTY_READ_REFUSES").toContain("invalid worker mount record: empty read at brain-view"); + expect(closed, "REFUSED_BRAIN_VIEW_IS_RETURNED").toBe(1); +});