From b3fcbfae46cc9c0b5b8101da124d73b7fd6bb7ce Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 3 Nov 2026 09:47:47 +0000 Subject: [PATCH 1/3] test: publish polled files atomically and refuse PID 0 in planning-observer and ci-runner An existence poll could read the planning namespace or the ci-runner command PID while the child had created but not yet written the file. An empty namespace made CANCELLED_NAMESPACE_HAS_NO_LIVING_DESCENDANTS pass vacuously; an empty PID made the ci-runner cleanup call process.kill(-0), which signals the test's own process group. Add tests/helpers/atomic-file.ts (publishFile, positivePid, readPositivePid), publish both files by rename, and refuse an unpublished namespace or a non-positive PID before it is used. Refs #3435 Co-Authored-By: Claude Opus 5.5 --- tests/ci-runner.test.ts | 10 ++++-- tests/helpers/atomic-file.ts | 37 +++++++++++++++++++++++ tests/helpers/planning-control-fixture.ts | 3 +- tests/planning-observer.test.ts | 3 ++ 4 files changed, 49 insertions(+), 4 deletions(-) create mode 100644 tests/helpers/atomic-file.ts diff --git a/tests/ci-runner.test.ts b/tests/ci-runner.test.ts index 9b3caaeb53..4e7d8c6f34 100644 --- a/tests/ci-runner.test.ts +++ b/tests/ci-runner.test.ts @@ -4,6 +4,7 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { runCommands, verificationCommands, type Command } from "../scripts/ci-runner"; import { planChecks } from "../scripts/ci-plan"; +import { positivePid, readPositivePid } from "./helpers/atomic-file"; const dirs: string[] = []; afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); }); @@ -171,14 +172,17 @@ test("SIGTERM cleans only owned children and never emits a successful finish rec test("hard-killed coordinator leaves missing end receipt rather than invented completion", async () => { const dir = fixture(); const child = recordedRunner(dir, [{ name: "unfinished", argv: [process.execPath, "-e", ` - await Bun.write("pid", String(process.pid)); setInterval(() => {}, 60000);`] }]); + const fs = require("node:fs"); fs.writeFileSync("pid.tmp", String(process.pid)); fs.renameSync("pid.tmp", "pid"); setInterval(() => {}, 60000);`] }]); try { - await waitForFile(join(dir, "pid")); child.kill("SIGKILL"); + await waitForFile(join(dir, "pid")); readPositivePid(join(dir, "pid"), "OWNED_COMMAND_PID_PUBLISHED"); child.kill("SIGKILL"); expect(await child.exited).not.toBe(0); expect(receipts(dir).map(r => r.event)).toEqual(["start"]); } finally { child.kill("SIGKILL"); - if (existsSync(join(dir, "pid"))) { try { process.kill(-Number(readFileSync(join(dir, "pid"), "utf8")), "SIGKILL"); } catch {} } + // The command publishes its PID atomically. Even so, never signal group 0: + // process.kill(-0) is this test's own process group. + const owned = existsSync(join(dir, "pid")) ? positivePid(readFileSync(join(dir, "pid"), "utf8")) : undefined; + if (owned !== undefined) { try { process.kill(-owned, "SIGKILL"); } catch {} } await child.exited; } }); diff --git a/tests/helpers/atomic-file.ts b/tests/helpers/atomic-file.ts new file mode 100644 index 0000000000..8f98432d20 --- /dev/null +++ b/tests/helpers/atomic-file.ts @@ -0,0 +1,37 @@ +/** Publishing and reading files that a test polls for (#3401, #3432, #3435). + * + * `writeFileSync` and `Bun.write` create a file before they write it, so a + * reader that polls with `existsSync` can see the file empty or partial. A PID + * read that way is `Number("") === 0`, and PID 0 is never a real process: + * `/proc/0` never exists, and `process.kill(0)` or `process.kill(-0)` signals + * the caller's own process group. A writer publishes with `publishFile`; a + * reader that takes a PID from such a file uses `readPositivePid` or + * `positivePid`, so a bad value fails on a named error instead of being used. + * + * A child that runs from inline source and cannot import this module uses the + * same shape inline: write `.tmp`, then rename it onto ``. */ +import { readFileSync, renameSync, writeFileSync } from "node:fs"; + +/** Write `text` to a temporary sibling and rename it onto `path`, so `path` + * appears only with its complete content. */ +export function publishFile(path: string, text: string): void { + const temporary = `${path}.${process.pid}.tmp`; + writeFileSync(temporary, text); + renameSync(temporary, path); +} + +/** The PID `text` names, or `undefined` unless it is a positive decimal integer. + * Zero, negatives, empty and partial text are all refused. */ +export function positivePid(text: string): number | undefined { + const trimmed = text.trim(); + return /^[1-9][0-9]*$/.test(trimmed) ? Number(trimmed) : undefined; +} + +/** Read a published PID, throwing an error that starts with `label` unless the + * file holds a positive integer. */ +export function readPositivePid(path: string, label: string): number { + const text = readFileSync(path, "utf8"); + const pid = positivePid(text); + if (pid === undefined) throw new Error(`${label}: expected a positive integer PID, read ${JSON.stringify(text)}`); + return pid; +} diff --git a/tests/helpers/planning-control-fixture.ts b/tests/helpers/planning-control-fixture.ts index d01e15d65c..9e8c3bf0a8 100644 --- a/tests/helpers/planning-control-fixture.ts +++ b/tests/helpers/planning-control-fixture.ts @@ -2,6 +2,7 @@ import assert from "node:assert/strict"; import { existsSync, readFileSync, readlinkSync, readdirSync, writeFileSync } from "node:fs"; import { join } from "node:path"; +import { publishFile } from "./atomic-file"; import { observePlanning, type PlanningRecord } from "./planning-observer"; import { burnCpu, bunControl, census, pause, runControl, until, withCompetitors } from "./planning-control"; @@ -22,7 +23,7 @@ if (mode === "competitor-child") { pause(15_000); } else if (mode === "hold") { await withCompetitors(dir, 1, async () => { - writeFileSync(join(dir, "holding"), readlinkSync("/proc/self/ns/pid")); + publishFile(join(dir, "holding"), readlinkSync("/proc/self/ns/pid")); await Bun.sleep(15_000); }); } else if (mode === "sync-child") { diff --git a/tests/planning-observer.test.ts b/tests/planning-observer.test.ts index 372b9f9c1a..be261d9732 100644 --- a/tests/planning-observer.test.ts +++ b/tests/planning-observer.test.ts @@ -127,6 +127,9 @@ test.skipIf(process.platform !== "linux")("cancelling an owned namespace drains while (!existsSync(join(dir, "holding")) && performance.now() < deadline) await Bun.sleep(5); expect(existsSync(join(dir, "holding")), "OWNED_DESCENDANT_STARTED_BEFORE_CANCELLATION").toBe(true); const namespace = readFileSync(join(dir, "holding"), "utf8"); + // The fixture publishes atomically. An empty namespace would match no process + // and make the descendant check below pass without proving anything. + expect(namespace, "OWNED_NAMESPACE_PUBLISHED").toMatch(/^pid:\[[1-9][0-9]*\]$/); child.kill("SIGKILL"); await drained; // A descendant retaining either pipe prevents this from completing. const living = () => readdirSync("/proc").filter(pid => { From 91917333c10e6a75229a9a65acc117ce0121c824 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 3 Nov 2026 09:47:47 +0000 Subject: [PATCH 2/3] test: publish the remaining polled fixture files atomically Every file a test polls for and then reads is now written to a temporary sibling and renamed into place: the storage-collection PID (now also read as a positive PID), the integration-command helper record, the invocation-worker sibling records, the native-suite timeout checkpoint, the inbox-dispatch and native-proof ready.json files, the storage-notify dispatch marker, the turn-temp reports and the boot-probe killer log. Closes #3435 Co-Authored-By: Claude Opus 5.5 --- packages/ui-sdk/tests/worker-turn-temp.test.ts | 4 +++- packages/ui-server/tests/boot-probe-deadline.test.ts | 2 +- packages/ui-server/tests/fixtures/inbox-dispatch-host.ts | 3 ++- .../ui-server/tests/fixtures/storage-notify-process.ts | 5 +++-- packages/ui-server/tests/helpers/native-suite-timeout.ts | 3 ++- packages/ui-server/tests/storage-collection.test.ts | 8 +++++--- scripts/native-proof/hosted-app-child.ts | 6 ++++-- scripts/native-proof/reference-integration-child.ts | 6 ++++-- tests/integration-command.test.ts | 4 ++-- tests/test-invocation-workers.test.ts | 4 ++-- tests/turn-temp-backends.test.ts | 5 +++-- 11 files changed, 31 insertions(+), 19 deletions(-) diff --git a/packages/ui-sdk/tests/worker-turn-temp.test.ts b/packages/ui-sdk/tests/worker-turn-temp.test.ts index fcda2e7211..31505721fc 100644 --- a/packages/ui-sdk/tests/worker-turn-temp.test.ts +++ b/packages/ui-sdk/tests/worker-turn-temp.test.ts @@ -223,7 +223,9 @@ describe("turn temp (#1655, #1703)", () => { test.skipIf(!LINUX)("runtime state mounted below /tmp is never read as turn temp, even unexcluded", async () => { const f = fixture(); const program = `import * as fs from "node:fs"; - fs.writeFileSync(${JSON.stringify(WORKER_STATE)} + "/transcript.jsonl", "Calypso: private."); + // Published by rename: the test polls for the file and then reads it. + fs.writeFileSync(${JSON.stringify(WORKER_STATE)} + "/transcript.jsonl.tmp", "Calypso: private."); + fs.renameSync(${JSON.stringify(WORKER_STATE)} + "/transcript.jsonl.tmp", ${JSON.stringify(WORKER_STATE)} + "/transcript.jsonl"); // Wait until the server has read: the state mount only exists while the namespace lives. await Bun.stdin.text();`; const sandbox = prepareWorkerSandbox(f.brain, { home: f.home }); diff --git a/packages/ui-server/tests/boot-probe-deadline.test.ts b/packages/ui-server/tests/boot-probe-deadline.test.ts index 2071324934..7383ae84eb 100644 --- a/packages/ui-server/tests/boot-probe-deadline.test.ts +++ b/packages/ui-server/tests/boot-probe-deadline.test.ts @@ -367,7 +367,7 @@ describe("boot probe deadline", () => { }); test(`${kind} calls the group killer at the deadline while the probe is alive`, async () => { const f = fixture(kind === "brain" ? MIN_BRAIN_CLI_VERSION : "2.0.0 (Claude Code)"); - const killer = executable(join(f.dir, "killer"), `state=dead\nkill -0 "$1" 2>/dev/null && state=alive\necho "$1 $2 $state" > '${f.dir}/killer.log'\nkill -"$2" -"$1"`); + const killer = executable(join(f.dir, "killer"), `state=dead\nkill -0 "$1" 2>/dev/null && state=alive\necho "$1 $2 $state" > '${f.dir}/killer.log.tmp'\nmv '${f.dir}/killer.log.tmp' '${f.dir}/killer.log'\nkill -"$2" -"$1"`); const result = await probe(kind, f, killer); const pid = readFileSync(join(f.dir, "probe.pid"), "utf8").trim(); const record = join(f.dir, "killer.log"); diff --git a/packages/ui-server/tests/fixtures/inbox-dispatch-host.ts b/packages/ui-server/tests/fixtures/inbox-dispatch-host.ts index b15579d70b..582ef46bab 100644 --- a/packages/ui-server/tests/fixtures/inbox-dispatch-host.ts +++ b/packages/ui-server/tests/fixtures/inbox-dispatch-host.ts @@ -12,6 +12,7 @@ */ import { existsSync, readFileSync, writeFileSync } from "node:fs"; import { join } from "node:path"; +import { publishFile } from "../../../../tests/helpers/atomic-file"; import type { AgentBackend, BrainApplicationInput } from "@schlessera/brain-ui-sdk/server"; import { createKeyedLock } from "@schlessera/brain-ui-sdk/server"; import { type CreateAppOptions } from "../../src/app"; @@ -64,5 +65,5 @@ const app = await createApp({ } as CreateAppOptions); const principal = createPrincipal(app.db, { authMethod: "password", label: "Odysseus", ttlSeconds: 3600 }); const server = Bun.serve({ port: 0, hostname: "127.0.0.1", fetch: app.fetch, websocket: app.websocket }); -writeFileSync(join(dir, "ready.json"), JSON.stringify({ port: server.port, principalId: principal.id, pid: process.pid })); +publishFile(join(dir, "ready.json"), JSON.stringify({ port: server.port, principalId: principal.id, pid: process.pid })); process.on("SIGTERM", async () => { server.stop(true); await app.close(); process.exit(0); }); diff --git a/packages/ui-server/tests/fixtures/storage-notify-process.ts b/packages/ui-server/tests/fixtures/storage-notify-process.ts index 14b7124bf2..3bdd20ad5c 100644 --- a/packages/ui-server/tests/fixtures/storage-notify-process.ts +++ b/packages/ui-server/tests/fixtures/storage-notify-process.ts @@ -1,5 +1,6 @@ -import { appendFileSync, writeFileSync } from "node:fs"; +import { appendFileSync } from "node:fs"; import { join } from "node:path"; +import { publishFile } from "../../../../tests/helpers/atomic-file"; import { createUiDb } from "../../src/db/client.js"; import { createStorageHistory } from "../../src/storage/history-store.js"; import { createStorageNotifier } from "../../src/storage/notify.js"; @@ -9,7 +10,7 @@ const at = Number(rawAt), db = createUiDb(join(root, "operations.sqlite")); const history = createStorageHistory(db, root, { now: () => at }), notices = createStorageNotifier(db, history); const sender = createPushSender(db, { send: async () => { appendFileSync(join(root, "transport-attempts.txt"), "attempt\n"); - if (mode === "crash") { writeFileSync(marker, "DISPATCHED\n"); Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 60_000); } + if (mode === "crash") { publishFile(marker, "DISPATCHED\n"); Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 60_000); } } }); console.log("READY"); await Bun.stdin.text(); console.log(JSON.stringify({ attempts: await sender.deliverStorage(notices, at) })); db.close(); diff --git a/packages/ui-server/tests/helpers/native-suite-timeout.ts b/packages/ui-server/tests/helpers/native-suite-timeout.ts index 520cd166e6..90b8d9adec 100644 --- a/packages/ui-server/tests/helpers/native-suite-timeout.ts +++ b/packages/ui-server/tests/helpers/native-suite-timeout.ts @@ -94,7 +94,8 @@ export function registerTimeoutControl(directory: string) { const fs = require("node:fs"); const stat = fs.readFileSync("/proc/self/stat", "utf8"); const group = Number(stat.slice(stat.lastIndexOf(")") + 2).split(" ")[2]); - fs.writeFileSync(${JSON.stringify(checkpoint)}, JSON.stringify({ pid: process.pid, group })); + fs.writeFileSync(${JSON.stringify(checkpoint + ".tmp")}, JSON.stringify({ pid: process.pid, group })); + fs.renameSync(${JSON.stringify(checkpoint + ".tmp")}, ${JSON.stringify(checkpoint)}); setInterval(() => {}, 60000); `; writeFileSync(heldTest, ` diff --git a/packages/ui-server/tests/storage-collection.test.ts b/packages/ui-server/tests/storage-collection.test.ts index 44e61f6a7a..255a8260a2 100644 --- a/packages/ui-server/tests/storage-collection.test.ts +++ b/packages/ui-server/tests/storage-collection.test.ts @@ -69,13 +69,15 @@ test("revocation during a real scan never publishes its result", async () => { test("bounded process cancellation reaps the real child", async () => { const { storageProcess } = await import("../src/storage/process"); - const { readFileSync, existsSync } = await import("node:fs"); + const { existsSync } = await import("node:fs"); + const { readPositivePid } = await import("../../../tests/helpers/atomic-file"); const f = fixture(), pidFile = join(f.app, "pid"), controller = new AbortController(); - const pending = storageProcess([process.execPath, "--config=/dev/null", "--no-env-file", "-e", `await Bun.write(${JSON.stringify(pidFile)},String(process.pid));setInterval(()=>{},1000);`], { signal: controller.signal }); + const pending = storageProcess([process.execPath, "--config=/dev/null", "--no-env-file", "-e", `const fs=require("node:fs");fs.writeFileSync(${JSON.stringify(pidFile + ".tmp")},String(process.pid));fs.renameSync(${JSON.stringify(pidFile + ".tmp")},${JSON.stringify(pidFile)});setInterval(()=>{},1000);`], { signal: controller.signal }); try { for (let i = 0; i < 200 && !existsSync(pidFile); i++) await new Promise(done => setTimeout(done, 5)); expect(existsSync(pidFile)).toBe(true); - const pid = Number(readFileSync(pidFile, "utf8")); + // PID 0 would make the reap check below fail falsely: process.kill(0, 0) succeeds. + const pid = readPositivePid(pidFile, "STORAGE_CHILD_PID_PUBLISHED"); controller.abort(); await expect(pending).rejects.toThrow("cancelled"); expect(() => process.kill(pid, 0), "STORAGE_CANCEL_REAPS_CHILD").toThrow(); diff --git a/scripts/native-proof/hosted-app-child.ts b/scripts/native-proof/hosted-app-child.ts index 941f0ae94f..2a4915b2e0 100644 --- a/scripts/native-proof/hosted-app-child.ts +++ b/scripts/native-proof/hosted-app-child.ts @@ -1,4 +1,4 @@ -import { appendFileSync, readFileSync, writeFileSync, statSync } from "node:fs"; +import { appendFileSync, readFileSync, renameSync, writeFileSync, statSync } from "node:fs"; import { join } from "node:path"; const [source, dir, brain, socket, selectedBackend = "claude"] = process.argv.slice(2); @@ -284,11 +284,13 @@ try { app.wsHost.failureReplay.begin = async (...args: any[]) => { const answer = await replayBegin(...args), finish = answer.finish.bind(answer); answer.finish = async (...values: any[]) => { const start = performance.now(); event("failure_replay_finish_start"); try { return await finish(...values); } finally { event("failure_replay_finish_end", { elapsedMs: performance.now() - start }); } }; return answer; }; const principal = createPrincipal(app.db, { authMethod: "password", label: "Odysseus admission", ttlSeconds: 3600 }); server = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: app.fetch, websocket: app.websocket }); - writeFileSync(join(dir!, "ready.json"), JSON.stringify({ + // Published by rename: the parent polls for ready.json and then parses it. + writeFileSync(join(dir!, "ready.json.tmp"), JSON.stringify({ rootWarnings: observability.logs.find({severity:"WARN"}).filter((log:any)=>String(log.body).includes("runs as root")).map((log:any)=>String(log.body)), port: server.port, egressPort: egressOrigin.port, principalId: principal.id, pid: process.pid, secret: SECRET, dbBytes: statSync(dbPath).size, status: app.activity?.runtime?.snapshot?.() })); + renameSync(join(dir!, "ready.json.tmp"), join(dir!, "ready.json")); event("ready", { port: server.port }); let closing = false; process.on("SIGTERM", async () => { diff --git a/scripts/native-proof/reference-integration-child.ts b/scripts/native-proof/reference-integration-child.ts index fce933cf66..ffd32a51d8 100644 --- a/scripts/native-proof/reference-integration-child.ts +++ b/scripts/native-proof/reference-integration-child.ts @@ -5,7 +5,7 @@ * launcher, native manager, reference pool, journal and hygiene review are the * production ones. Only the model is scripted, offline. */ -import { appendFileSync, statSync, writeFileSync } from "node:fs"; +import { appendFileSync, renameSync, statSync, writeFileSync } from "node:fs"; import { createHash } from "node:crypto"; import { join } from "node:path"; import { INTEGRATION_STEPS, stepKey, type IntegrationState, type IntegrationStep } from "./reference-integration-steps.js"; @@ -156,8 +156,10 @@ try { }); const owner = createPrincipal(app.db, { authMethod: "password", label: "Odysseus", ttlSeconds: 3600 }); server = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: app.fetch, websocket: app.websocket }); - writeFileSync(join(dir, "ready.json"), JSON.stringify({ port: server.port, principalId: owner.id, secret: SECRET, pid: process.pid, + // Published by rename: the parent polls for ready.json and then parses it. + writeFileSync(join(dir, "ready.json.tmp"), JSON.stringify({ port: server.port, principalId: owner.id, secret: SECRET, pid: process.pid, dbBytes: statSync(join(dir, "ui.db")).size, referenceTools: Boolean(app.wsHost.referenceTools), status: app.activity?.runtime?.snapshot?.() })); + renameSync(join(dir, "ready.json.tmp"), join(dir, "ready.json")); event("ready", { port: server.port }); let closing = false; process.on("SIGTERM", async () => { diff --git a/tests/integration-command.test.ts b/tests/integration-command.test.ts index c91c342996..c28bb7e6bb 100644 --- a/tests/integration-command.test.ts +++ b/tests/integration-command.test.ts @@ -96,7 +96,7 @@ else fi`); chmodSync(shim, 0o755); const gh = join(bin, "gh"), actual = { sha: synthetic, tree, parents: [base, head] }; writeFileSync(gh, `#!${process.execPath} - import {readFileSync,writeFileSync} from "node:fs"; + import {readFileSync,renameSync,writeFileSync} from "node:fs"; import {GitReservationStore,reservationTransition} from ${JSON.stringify(library)}; const args=process.argv.slice(2), file=${JSON.stringify(apiState)}, s=JSON.parse(readFileSync(file,"utf8")); const candidate=${JSON.stringify(candidate)}, actual=${JSON.stringify(actual)}, root=${JSON.stringify(root)}, remote=${JSON.stringify(remote)}; @@ -121,7 +121,7 @@ fi`); chmodSync(shim, 0o755); else if(args[0]==="api") { const path=args.find(x=>x.startsWith("repos/"))??args[1]; if(s.mode==="confirm-held"&&s.requested&&path.includes("actions/workflows/ci.yml/runs")){ - writeFileSync(${JSON.stringify(join(dir, "held"))},JSON.stringify({pid:process.pid,start:readFileSync("/proc/self/stat","utf8").split(") ").at(-1).split(" ")[19]})); + writeFileSync(${JSON.stringify(join(dir, "held.tmp"))},JSON.stringify({pid:process.pid,start:readFileSync("/proc/self/stat","utf8").split(") ").at(-1).split(" ")[19]}));renameSync(${JSON.stringify(join(dir, "held.tmp"))},${JSON.stringify(join(dir, "held"))}); await new Promise(()=>setInterval(()=>{},1000)); } if(args.includes("--include")){console.log("HTTP/2.0 200 OK\\nDate: "+new Date(s.now).toUTCString()+"\\n\\n{}");writeFileSync(file,JSON.stringify(s));process.exit(0);} diff --git a/tests/test-invocation-workers.test.ts b/tests/test-invocation-workers.test.ts index a5cc2fa7ab..643cc5e6f6 100644 --- a/tests/test-invocation-workers.test.ts +++ b/tests/test-invocation-workers.test.ts @@ -9,7 +9,7 @@ test("two native private workers attest actual independent builds and reject sib const reports = join(root, "tmp/reports"), shared = join(root, "tmp/shared"); mkdirSync(shared, { recursive: true }); const files = ["tests/odysseus.test.ts", "tests/penelope.test.ts"]; for (const [index, file] of files.entries()) write(file, `import {test,expect} from "bun:test"; -import {readFileSync,writeFileSync,existsSync} from "node:fs"; +import {readFileSync,renameSync,writeFileSync,existsSync} from "node:fs"; import {join} from "node:path"; import {invocationBuild} from "../scripts/test-invocation"; import {runtimePackageBuild} from "../packages/ui-react/tests/fixtures/runtime-package-build"; @@ -18,7 +18,7 @@ test("independent prepared worker ${index}",async()=>{ const root=process.cwd(),shared=${JSON.stringify(shared)}; const receipt=invocationBuild(root,["ithaca","troy"]);expect(receipt,"PRIVATE_WORKER_ACTUAL_SUCCESSFUL_AUTHORITY").toBeDefined(); const own={authority:process.env.BRAIN_TEST_BUILD_AUTHORITY,nonce:process.env.BRAIN_TEST_INVOCATION_NONCE,lease:receipt.lease,build:receipt.build.pid}; -writeFileSync(join(shared,"${index}.json"),JSON.stringify(own)); +writeFileSync(join(shared,"${index}.json.tmp"),JSON.stringify(own));renameSync(join(shared,"${index}.json.tmp"),join(shared,"${index}.json")); await runtimePackageBuild(root,["ithaca"],runtimeHookPhases("private-worker-${index}")); const end=Date.now()+10000;while(!existsSync(join(shared,"${1-index}.json"))&&Date.now() worker.turnTemp!.root, allowanceBytes: allowance, scratch: WORKER_SCRATCH, exclude: [], keep: [WORKER_SCRATCH], linkedText: () => "[Report](/tmp/report.md)" }; From cbfb142a33d01922636509ae8a10c1606aafa86d Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 3 Nov 2026 09:52:48 +0000 Subject: [PATCH 3/3] test(core): publish the MCP cancellation marker atomically The cancel fixture wrote call-aborted with Bun.write, which creates the file before writing it, while the test polls for the file and then checks its exact content. Found by the #3435 audit re-run. Refs #3435 Co-Authored-By: Claude Opus 5.5 --- packages/core/tests/module-mcp-tools.test.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/packages/core/tests/module-mcp-tools.test.ts b/packages/core/tests/module-mcp-tools.test.ts index 9baaee0251..bf46dcd801 100644 --- a/packages/core/tests/module-mcp-tools.test.ts +++ b/packages/core/tests/module-mcp-tools.test.ts @@ -40,7 +40,10 @@ function fixtures(specs: Fixture[]): string { const run = mode === "throws" ? 'throw new Error("fixture operation failed");' : mode === "cancel" ? ` await Bun.write(ctx.root + "/call-started", "started"); await new Promise((resolve) => ctx.signal.addEventListener("abort", resolve, { once: true })); - await Bun.write(ctx.root + "/call-aborted", "aborted"); + // Published by rename: the test polls for call-aborted and then reads it. + const fs = await import("node:fs"); + fs.writeFileSync(ctx.root + "/call-aborted.tmp", "aborted"); + fs.renameSync(ctx.root + "/call-aborted.tmp", ctx.root + "/call-aborted"); return ${result};` : `return ${result};`; writeFileSync(join(dir, `${local}.ts`), mode === "import-failure" ? 'throw new Error("fixture import failed");' : ` import { z } from "zod";