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: 4 additions & 1 deletion packages/core/tests/module-mcp-tools.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down
4 changes: 3 additions & 1 deletion packages/ui-sdk/tests/worker-turn-temp.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 });
Expand Down
2 changes: 1 addition & 1 deletion packages/ui-server/tests/boot-probe-deadline.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down
3 changes: 2 additions & 1 deletion packages/ui-server/tests/fixtures/inbox-dispatch-host.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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); });
5 changes: 3 additions & 2 deletions packages/ui-server/tests/fixtures/storage-notify-process.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand All @@ -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();
3 changes: 2 additions & 1 deletion packages/ui-server/tests/helpers/native-suite-timeout.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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, `
Expand Down
8 changes: 5 additions & 3 deletions packages/ui-server/tests/storage-collection.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
6 changes: 4 additions & 2 deletions scripts/native-proof/hosted-app-child.ts
Original file line number Diff line number Diff line change
@@ -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);
Expand Down Expand Up @@ -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 () => {
Expand Down
6 changes: 4 additions & 2 deletions scripts/native-proof/reference-integration-child.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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 () => {
Expand Down
10 changes: 7 additions & 3 deletions tests/ci-runner.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 }); });
Expand Down Expand Up @@ -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;
}
});
Expand Down
37 changes: 37 additions & 0 deletions tests/helpers/atomic-file.ts
Original file line number Diff line number Diff line change
@@ -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 `<path>.tmp`, then rename it onto `<path>`. */
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;
}
3 changes: 2 additions & 1 deletion tests/helpers/planning-control-fixture.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand All @@ -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") {
Expand Down
4 changes: 2 additions & 2 deletions tests/integration-command.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)};
Expand All @@ -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);}
Expand Down
3 changes: 3 additions & 0 deletions tests/planning-observer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 => {
Expand Down
4 changes: 2 additions & 2 deletions tests/test-invocation-workers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -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()<end)await Bun.sleep(10);
const sibling=JSON.parse(readFileSync(join(shared,"${1-index}.json"),"utf8"));expect(sibling.nonce).not.toBe(own.nonce);expect(sibling.lease.ino).not.toBe(own.lease.ino);
Expand Down
5 changes: 3 additions & 2 deletions tests/turn-temp-backends.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,10 @@ test("both turn_temp registrations report real private usage, keep linked bytes
mkdirSync(brain);
const allowance = 8 * 1024 * 1024;
const worker = launchAgentWorker({ brainPath: brain, env: {}, sandbox: prepareWorkerSandbox(brain, {}), turnTempBytes: allowance,
command: [process.execPath, "-e", `import {writeFileSync} from 'node:fs';
command: [process.execPath, "-e", `import {renameSync,writeFileSync} from 'node:fs';
writeFileSync('/tmp/large.bin',new Uint8Array(${Math.ceil(allowance * .81)}));
writeFileSync('/tmp/report.md','Odysseus returns.');
// Published by rename: the test polls for report.md and then reads it.
writeFileSync('/tmp/report.md.tmp','Odysseus returns.');renameSync('/tmp/report.md.tmp','/tmp/report.md');
await Bun.stdin.text();`] });
const access: TurnTempAccess = { root: () => worker.turnTemp!.root, allowanceBytes: allowance,
scratch: WORKER_SCRATCH, exclude: [], keep: [WORKER_SCRATCH], linkedText: () => "[Report](/tmp/report.md)" };
Expand Down
Loading