pi-mono/packages/codemode/test/deterministic.test.ts
Armin Ronacher 18b142f2fe fix(codemode,durable,coding-agent): start() runs in one remote session; review fixes
- RemoteCodemodeSandbox ran start() step by step, saving the whole heap after
  every step (and failing on a WeakRef). Sandboxes now open a run with its
  lifetime (session or saved), and a start() run is one session on the remote,
  as on main.
- start()'s tests run on the worker, inline, and remote sandboxes again, with
  main's cases for globals numbered with tools and rejections carrying their
  properties; a test checks a remote start() takes no steps.
- start()'s fingerprint names the run's actual CPU budget (none, a number, or
  remote), not "default" for every sandbox.
- start()'s call records carry the module; the dropped calls are computed once.
- Durable skips a namespace named like a built-in global or a global's
  namespace (models) as a module, instead of failing every script; pi-codemode
  exports CODEMODE_RESERVED_NAMES from /declarations for it.
- Docs: CodemodeHostCall.id, durable's call keys and schema, the CHANGELOGs
  (start()'s jsName, the un-awaited calls rule, /remote, strict mode and UTC in
  the coding agent), the README on dropped calls and remote start() runs, and
  the coding agent's Bun caveat, which no longer holds (checked on Bun 1.4.4:
  a long sort or split stops at the deadline).
2026-11-30 19:15:05 +01:00

332 lines
14 KiB
TypeScript

import { afterEach, beforeEach, describe, expect, it } from "vitest";
import {
type CodemodeHostCall,
type CodemodeRun,
type CodemodeRunOptions,
CodemodeSandbox,
type CodemodeSandboxBase,
type CodemodeSandboxBaseOptions,
InlineCodemodeSandbox,
RemoteCodemodeSandbox,
} from "../src/index.ts";
import { inProcessRemote } from "./remote-support.ts";
/**
* `start()` runs a script deterministically with the caller answering its calls, so a durable host can replay it
* after a restart. Every test runs on each sandbox: a worker thread, the calling thread, and a remote served in process
* that structured-clones every message, as Workers RPC would.
*/
const STARTED_AT = Date.UTC(2026, 0, 15, 10, 0, 0);
const BACKENDS: Record<string, (options: CodemodeSandboxBaseOptions) => CodemodeSandboxBase> = {
worker: (options) => new CodemodeSandbox(options),
inline: (options) => new InlineCodemodeSandbox(options),
remote: (options) => {
const { remote } = inProcessRemote({ maxInterruptBudget: 1e8 });
return new RemoteCodemodeSandbox({ ...options, remote: () => remote });
},
};
/** What each sandbox's fingerprint names as its engine, and as the fuel of a run whose options set none. */
const ENGINES: Record<string, string> = {
worker: "djs [0-9a-f]{8}",
inline: "djs [0-9a-f]{8}",
remote: "djs \\(remote\\)",
};
const FUELS: Record<string, string> = { worker: "none", inline: "\\d+", remote: "remote" };
let backend = "worker";
let sandbox: CodemodeSandboxBase;
const sandboxes: CodemodeSandboxBase[] = [];
function newSandbox(options: CodemodeSandboxBaseOptions = {}): CodemodeSandboxBase {
const created = BACKENDS[backend]!(options);
sandboxes.push(created);
return created;
}
/**
* Start `code` with tools `echo` and `wait`. Every call but `wait` is answered at once with its argument, as result
* number 1, 2, ... with the clock at `STARTED_AT + 1000 * seq`; `wait` is left for the test to answer. `events` has
* `started <fingerprint>`, `call <id>`, and `idle <seq>` in order. `on`: the sandbox, by default one of 64 MiB.
*/
function start(code: string, options: Partial<CodemodeRunOptions> = {}, on = sandbox) {
const calls: CodemodeHostCall[] = [];
const idles: [seq: number, issued: number][] = [];
const events: string[] = [];
let seq = 0;
const run: CodemodeRun = on.start(code, {
startedAt: STARTED_AT,
seed: 1,
tools: [{ name: "echo" }, { name: "wait" }],
timeoutMs: 20_000,
...options,
onStarted: (fingerprint) => events.push(`started ${fingerprint}`),
onCall: (call) => {
calls.push(call);
events.push(`call ${call.id}`);
if (call.name === "wait") return;
queueMicrotask(() => {
seq++;
run.deliver(seq, STARTED_AT + 1000 * seq, call.id, { ok: true, value: call.args });
});
},
onIdle: (seq, issued) => {
idles.push([seq, issued]);
events.push(`idle ${seq}`);
},
});
return { run, calls, idles, events };
}
const savedTimezone = process.env.TZ;
afterEach(async () => {
if (savedTimezone === undefined) delete process.env.TZ;
else process.env.TZ = savedTimezone;
await Promise.all(sandboxes.splice(0).map((created) => created.close()));
});
describe.each(Object.keys(BACKENDS))("start() on the %s sandbox", (name) => {
beforeEach(() => {
backend = name;
sandbox = newSandbox({ memoryLimitBytes: 64 * 1024 * 1024 });
});
it("makes the same calls and output for the same start, seed, and results, in UTC", async () => {
const code = `
const values = [Date.now(), performance.now(), Math.random(), Math.random(), new Date().toISOString()];
const first = await tools.echo(values);
text(JSON.stringify([Date.now(), performance.now(), Math.random()]));
return await tools.echo(first.concat(Math.random()));
`;
const one = start(code);
const two = start(code);
const [a, b] = await Promise.all([one.run.result, two.run.result]);
// Call durations are wall-clock time; everything else is the same.
const timeless = (result: typeof a) => ({
...result,
calls: result.calls.map(({ name, status }) => ({ name, status })),
});
expect(timeless(a)).toEqual(timeless(b));
expect(one.calls).toEqual(two.calls);
// The clock: startedAt, then the time of the result being processed; performance.now() counts from startedAt.
const [now, elapsed, random] = one.calls[0]!.args as number[];
expect([now, elapsed]).toEqual([STARTED_AT, 0]);
expect((one.calls[0]!.args as unknown[])[4]).toBe("2026-01-15T10:00:00.000Z");
const printed = JSON.parse(a.ok ? (a.output[0] as { text: string }).text : "[]") as number[];
expect(printed.slice(0, 2)).toEqual([STARTED_AT + 1000, 1000]);
// Pinned: a change here changes what replayed scripts see, so it must change the fingerprint too.
expect(random).toBe(PINNED_FIRST_RANDOM);
// The seed decides the random values, not the start time.
const later = start(code, { startedAt: STARTED_AT + 5000 });
const reseeded = start(code, { seed: 2 });
await Promise.all([later.run.result, reseeded.run.result]);
expect((later.calls[0]!.args as number[])[2]).toBe(random);
expect((reseeded.calls[0]!.args as number[])[2]).not.toBe(random);
// Seed 0 has its own values, not seed 1's; the run is in UTC whatever the host's timezone, and a WeakRef
// never loses its target.
process.env.TZ = "Asia/Kolkata";
const zero = start(
"return [Math.random(), Math.random(), new Date(0).getHours(), typeof new WeakRef({}).deref()]",
{ seed: 0 },
);
expect(await zero.run.result).toMatchObject({ ok: true, value: [...PINNED_SEED_ZERO, 0, "object"] });
});
it("applies results in seq order, whatever order they are delivered in, on a clock that never goes back", async () => {
const recorded = start(`const before = Date.now();
const order = [];
const wait = (name) => tools.wait(name).then(() => order.push([name, Date.now()]));
await Promise.all([wait("a"), wait("b")]);
return [before, order];`);
await waitFor(() => recorded.calls.length === 2 && recorded.idles.length === 1);
const [a, b] = recorded.calls;
// b is result 1 and a result 2, but a arrives first. b's clock is behind the run's start, as a resumed host's
// may be: the clock stays.
recorded.run.deliver(2, STARTED_AT + 2000, a!.id, { ok: true, value: null });
expect(() => recorded.run.deliver(1, Number.NaN, b!.id, { ok: true, value: null })).toThrow(
"not a finite number",
);
recorded.run.deliver(1, STARTED_AT - 2000, b!.id, { ok: true, value: null });
expect(await recorded.run.result).toMatchObject({
ok: true,
value: [
STARTED_AT,
[
["b", STARTED_AT],
["a", STARTED_AT + 2000],
],
],
});
// No idle after the last result: the script finished in that drain, and the host stopped the VM.
expect(recorded.idles).toEqual([
[0, 2],
[1, 2],
]);
});
it("reports the fingerprint before any call, the calls issued after each result, and the result it ended in", async () => {
const recorded = start("await tools.echo(1); await Promise.all([tools.echo(2), tools.echo(3)]);");
expect(await recorded.run.result).toMatchObject({ ok: true, during: { seq: 3, issued: 3 } });
const [fingerprint, ...events] = recorded.events;
expect(fingerprint).toMatch(new RegExp(`^started ${ENGINES[backend]}, heap 67108864, fuel ${FUELS[backend]}$`));
expect(events.slice(0, 2)).toEqual(["call 1", "idle 0"]);
expect(recorded.idles).toEqual([
[0, 1],
[1, 3],
[2, 3],
]);
const same = start("return 1");
const other = start("return 1", {}, newSandbox({ memoryLimitBytes: 32 * 1024 * 1024 }));
const thrown = start("await tools.echo(1); return await tools.echo(2).then(() => { throw 1; })");
expect(await same.run.result).toMatchObject({ ok: true, during: { seq: 0, issued: 0 } });
await other.run.result;
expect(await thrown.run.result).toMatchObject({ ok: false, during: { seq: 2, issued: 2 } });
expect(same.events[0]).toBe(fingerprint);
expect(other.events[0]).not.toBe(fingerprint);
expect(await sandbox.execute("return 1")).not.toHaveProperty("during");
});
it("checks what deliver() and start() get, leaving the call waiting", async () => {
const recorded = start("await Promise.all([tools.wait(1), tools.wait(2)])");
await waitFor(() => recorded.calls.length === 2);
const { run } = recorded;
expect(() => run.deliver(1, STARTED_AT, 99, { ok: true, value: null })).toThrow("Call 99 is not waiting");
expect(() => run.deliver(1, STARTED_AT, 1, { ok: true, value: 1n })).toThrow();
expect(() => run.deliver(1, STARTED_AT, 1, { ok: false, message: "x", properties: { big: 1n } })).toThrow();
for (const properties of [null, [1]] as unknown as Record<string, unknown>[]) {
expect(() => run.deliver(1, STARTED_AT, 1, { ok: false, message: "x", properties })).toThrow("not an object");
}
run.deliver(1, STARTED_AT, 1, { ok: true, value: null });
expect(() => run.deliver(1, STARTED_AT, 2, { ok: true, value: null })).toThrow("used once");
expect(() => run.deliver(0, STARTED_AT, 2, { ok: true, value: null })).toThrow("used once");
expect(run.finished).toBe(false);
run.deliver(2, STARTED_AT, 2, { ok: true, value: null });
expect(await run.result).toMatchObject({ ok: true });
expect(run.finished).toBe(true);
expect(() =>
sandbox.start("", {
startedAt: STARTED_AT,
seed: 1,
tools: [{ name: "a-b" }, { name: "a_b" }],
onCall: () => {},
}),
).toThrow("script names must be unique");
});
it("ends with an error the script cannot catch when the caller aborts", async () => {
const controller = new AbortController();
const recorded = start(
`try { await tools.wait(1); } catch { text("caught"); }
text("after");`,
{ signal: controller.signal },
);
await waitFor(() => recorded.calls.length === 1);
controller.abort(new Error("diverged"));
const result = await recorded.run.result;
expect(result).toMatchObject({ ok: false, error: { kind: "aborted", message: "diverged" }, output: [] });
expect(() => recorded.run.deliver(1, STARTED_AT, 1, { ok: true, value: null })).not.toThrow();
});
it("numbers calls to globals with tools, and answers errors as rejections carrying their properties", async () => {
// `search` is answered at once with its arguments; `wait` by the test.
const recorded = start(
`const found = await search("x", 2);
try { await tools.wait("fail"); } catch (e) { text([e instanceof Error, e.name, e.message, e.structuredOutput]); }
return found;`,
{ globals: [{ name: "search", spread: true }] },
);
await waitFor(() => recorded.calls.length === 2);
expect(recorded.calls).toMatchObject([
{ id: 1, target: "global", name: "search", args: ["x", 2] },
{ id: 2, target: "tool", name: "wait", args: "fail" },
]);
recorded.run.deliver(2, STARTED_AT, 2, {
ok: false,
message: "no",
properties: { structuredOutput: { code: 7 }, name: "Ignored", message: "ignored" },
});
const result = await recorded.run.result;
expect(result).toMatchObject({
ok: true,
value: ["x", 2],
output: [{ type: "text", text: '[true,"Error","no",{"code":7}]' }],
});
// Calls to globals count as issued calls too.
expect(recorded.idles.slice(0, 2)).toEqual([
[0, 1],
[1, 2],
]);
expect(result.calls).toMatchObject([{ name: "wait", status: "error" }]);
});
it("numbers the calls it hands out 1, 2, ..., whatever the output and store calls in between", async () => {
const recorded = start(`text("a"); await tools.echo(1); store("k", 1); text(load("k")); await tools.echo(2);
console.log("b"); return await tools.echo(3);`);
expect(await recorded.run.result).toMatchObject({ ok: true, value: 3, during: { seq: 3, issued: 3 } });
expect(recorded.calls.map((call) => call.id)).toEqual([1, 2, 3]);
});
it("reports the calls the script made in its last step without awaiting them, never handing them out", async () => {
const recorded = start(`await tools.echo(1); tools.wait("left"); tools.echo(2); return "done";`);
const result = await recorded.run.result;
expect(result).toMatchObject({ ok: true, value: "done", during: { seq: 1, issued: 3 } });
expect(recorded.calls.map((call) => call.id)).toEqual([1]);
expect(recorded.run.dropped).toMatchObject([
{ id: 2, name: "wait", args: "left" },
{ id: 3, name: "echo", args: 2 },
]);
expect(result.calls.map(({ name, status }) => [name, status])).toEqual([
["echo", "ok"],
["wait", "cancelled"],
["echo", "cancelled"],
]);
});
it("reaches the tools of its modules by import, and ends a missing tool's error with its hint", async () => {
const imported = start(`import { echo } from "@mcp/github";\nreturn await echo("x");`, {
tools: [],
modules: [{ specifier: "@mcp/github", tools: [{ name: "echo" }] }],
});
expect(await imported.run.result).toMatchObject({ ok: true, value: "x" });
expect(imported.calls).toMatchObject([{ id: 1, target: "tool", name: "echo", module: "@mcp/github" }]);
const missing = start("return tools.ech;", { missingToolHint: "searchTools(query) finds tools." });
const result = await missing.run.result;
expect(result.ok ? "" : result.error.message).toMatch(
/tools\.ech does not exist\..*searchTools\(query\) finds tools\./,
);
});
});
describe("start() on a remote", () => {
it("runs in one session, never saved step by step, so a WeakRef is fine", async () => {
const { remote, steps } = inProcessRemote({ maxInterruptBudget: 1e8 });
backend = "remote";
const created = new RemoteCodemodeSandbox({ remote: () => remote });
sandboxes.push(created);
const recorded = start(
"const ref = new WeakRef({}); await tools.echo(1); return typeof ref.deref();",
{},
created,
);
expect(await recorded.run.result).toMatchObject({ ok: true, value: "object" });
expect(steps.count).toBe(0);
});
});
async function waitFor(check: () => boolean): Promise<void> {
const deadline = Date.now() + 5000;
while (!check()) {
if (Date.now() > deadline) throw new Error("Condition was not reached");
await new Promise((resolve) => setTimeout(resolve, 5));
}
}
/** The first two `Math.random()` values with seed 0. */
const PINNED_SEED_ZERO = [0.05279087335850807, 0.3311202810018534];
/** The first `Math.random()` with seed 1. */
const PINNED_FIRST_RANDOM = 0.28083505005035936;