refactor!: simplify runtime tools and remove replay engines (#572)

* fix(hopper): report unavailable procedure body coverage

* refactor!: simplify runtime tools and remove replay engines

Keep direct inspection, capture, and comparison tools. Bind handlers to named contracts and let agents compose experiments with commands and local fixture servers.

BREAKING CHANGE: Remove controlled replay, Node characterization, finite replay-machine, managed runtime planning, and redundant string-tracing tools. Retire process replay, shims, reactive scenarios, custom checkpoints, and active browser replay and origin-scope inputs.
This commit is contained in:
morluto
2026-10-05 21:15:04 +08:00
committed by GitHub
parent c6d3bdf597
commit e07b81649e
258 changed files with 1193 additions and 22444 deletions
@@ -3,6 +3,7 @@ import { promisify } from "node:util";
import { describe, expect, it } from "vitest";
import { z } from "zod";
import { OFFICIAL_TOOL_CONTRACTS } from "../../../../src/contracts/toolContracts.js";
const execute = promisify(execFile);
const bridgePath = new URL(
@@ -21,12 +22,42 @@ const probeResultSchema = z.strictObject({
}),
current_document: z.literal("fixture"),
current_address: z.literal("0x401000"),
containing_procedure: z.strictObject({
query_address: z.literal("0x401000"),
found: z.literal(true),
procedure: z.strictObject({
address: z.literal("0x401000"),
name: z.literal("fixture-procedure"),
classification: z.null(),
body: z.strictObject({
available: z.literal(false),
reason: z.string(),
}),
}),
}),
procedure_info: z.strictObject({
name: z.literal("fixture-procedure"),
entrypoint: z.literal("0x401000"),
basicblock_count: z.literal(1),
length: z.number(),
signature: z.literal("int fixture-procedure()"),
locals: z.array(z.unknown()),
classification: z.null(),
body: z.strictObject({
available: z.literal(false),
reason: z.string(),
}),
}),
strings: z.strictObject({ "0x401234": z.literal("fixture string") }),
procedure_references: z.strictObject({
procedure: z.strictObject({
address: z.literal("0x401000"),
name: z.literal("fixture-procedure"),
classification: z.null(),
body: z.strictObject({
available: z.literal(false),
reason: z.string(),
}),
}),
direction: z.literal("outgoing"),
reference_kinds_available: z.literal(false),
@@ -117,6 +148,19 @@ describe("Hopper API facade", () => {
},
);
const result = probeResultSchema.parse(JSON.parse(stdout));
for (const [name, value] of [
["resolve_containing_procedure", result.containing_procedure],
["procedure_references", result.procedure_references],
["procedure_info", result.procedure_info],
] as const) {
const contract = OFFICIAL_TOOL_CONTRACTS.find(
(candidate) => candidate.name === name,
);
if (contract === undefined) throw new Error(`missing ${name} contract`);
const parsed = contract.outputSchema.shape.result.safeParse(value);
if (!parsed.success) throw new Error(`${name}: ${parsed.error.message}`);
expect(parsed.success, name).toBe(true);
}
expect(result.provider_faults.map((reply) => reply.error.message)).toEqual([
"TypeError: Hopper bridge operation failed",
"ValueError: Hopper bridge operation failed",
@@ -168,12 +212,45 @@ describe("Hopper API facade", () => {
address: "0x401000",
name: "fixture-procedure",
classification: null,
body: {
available: false,
reason:
"Hopper's public Python API does not expose complete function body ranges",
},
},
direction: "outgoing",
reference_kinds_available: false,
unresolved_calls: [],
references: [],
});
expect(result.containing_procedure).toEqual({
query_address: "0x401000",
found: true,
procedure: {
address: "0x401000",
name: "fixture-procedure",
classification: null,
body: {
available: false,
reason:
"Hopper's public Python API does not expose complete function body ranges",
},
},
});
expect(result.procedure_info).toEqual({
name: "fixture-procedure",
entrypoint: "0x401000",
basicblock_count: 1,
length: 4,
signature: "int fixture-procedure()",
locals: [],
classification: null,
body: {
available: false,
reason:
"Hopper's public Python API does not expose complete function body ranges",
},
});
expect(stdout).not.toContain("supersecret");
expect(result.analysis_guard.message).toContain(
"requires completed Hopper background analysis",
@@ -1,435 +0,0 @@
import { readFile, realpath, rm, stat } from "node:fs/promises";
import { join, resolve } from "node:path";
import { describe, expect, it, vi } from "vitest";
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
import { runControlledReplay } from "../../../../src/application/JavaScriptReplayService.js";
import type {
JavaScriptReplayConfiguration,
JavaScriptReplayHost,
JavaScriptReplayRunner,
} from "../../../../src/application/JavaScriptReplayPlanning.js";
import {
controlledReplayInputSchema,
controlledReplayOutputSchema,
} from "../../../../src/domain/javascriptReplay.js";
const root = resolve("tests/fixtures/replay");
const configuration: JavaScriptReplayConfiguration = {
nodePath: process.execPath,
bubblewrapPath: process.execPath,
systemdRunPath: process.execPath,
systemctlPath: process.execPath,
shellPath: process.execPath,
};
const host: JavaScriptReplayHost = {
readSource: async (path, maximumBytes) => {
const canonicalPath = await realpath(path);
const bytes = await readFile(canonicalPath);
if (bytes.byteLength > maximumBytes) throw new RangeError("fixture limit");
return { canonicalPath, bytes };
},
identifyExecutable: async (path) => ({
path,
version: "fixture-1",
sha256: "1".repeat(64),
}),
identifyWorker: async () => ({
path: "/fixture/worker.js",
version: "fixture-worker-1",
sha256: "2".repeat(64),
}),
identifyRuntimeClosure: async (path) => [
{
sourcePath: path,
destinationPath: "/runtime/node",
sha256: "1".repeat(64),
},
],
seccompDigest: () => "3".repeat(64),
probe: async () => undefined,
};
const input = (
mode: "plan" | "execute",
path = resolve(root, "parser.mjs"),
) => ({
mode,
left: {
modules: [
{
alias: "parser",
path,
format: "esm" as const,
role: "module" as const,
dependencies: {},
},
],
entry_alias: "parser",
entry_export: "default",
},
cases: [{ case_id: "heading", arguments: ["# Title"] }],
});
const completedRunner = (): JavaScriptReplayRunner => ({
execute: async (prepared) => ({
plan_digest: prepared.publicPlan.plan_digest,
outcomes: [
{
case_id: "heading",
outcome: "return",
value: { type: "heading", text: "Title" },
input_sha256: prepared.publicPlan.cases[0]?.sha256 ?? "0".repeat(64),
output_sha256: "2".repeat(64),
truncated: false,
},
],
stderr: "",
termination: "completed",
cleanup: { state: "complete", residual_resources: [] },
limitations: ["fixture runner"],
reproducer: null,
}),
});
describe("controlled JavaScript replay planning", () => {
it("requires an exact digest for execution and keeps plan input separate", () => {
expect(
controlledReplayInputSchema.safeParse({
...input("execute"),
plan_digest: "0".repeat(64),
}).success,
).toBe(true);
expect(
controlledReplayInputSchema.safeParse({
...input("execute"),
}).success,
).toBe(false);
expect(
controlledReplayInputSchema.safeParse({
...input("plan"),
plan_digest: "0".repeat(64),
}).success,
).toBe(false);
expect(
controlledReplayInputSchema.safeParse({
...input("plan"),
}).success,
).toBe(true);
expect(
controlledReplayInputSchema.safeParse({
...input("execute"),
plan_digest: "0".repeat(64),
reproducer_export: {
path: "/tmp/reproducer",
},
}).success,
).toBe(true);
});
it("rejects relative module paths", () => {
expect(
controlledReplayInputSchema.safeParse({
...input("plan", "relative/parser.mjs"),
}).success,
).toBe(false);
});
it("accepts caller replay budgets above former tool-side ceilings", () => {
expect(
controlledReplayInputSchema.safeParse({
...input("plan"),
generator: { preset: "parser-boundaries", seed: 1, count: 65 },
limits: {
wall_time_ms: 60_000,
memory_bytes: 1024 * 1024 * 1024,
tasks: 64,
cpu_quota_percent: 200,
tmpfs_bytes: 128 * 1024 * 1024,
module_bytes: 32 * 1024 * 1024,
input_bytes: 2 * 1024 * 1024,
protocol_bytes: 128 * 1024 * 1024,
output_bytes: 8 * 1024 * 1024,
stderr_bytes: 512 * 1024,
result_depth: 128,
result_nodes: 200_000,
},
}).success,
).toBe(true);
});
it("rejects oversized aggregate cases before probing or reading", async () => {
const probe = vi.fn(host.probe);
const readSource = vi.fn(host.readSource);
const result = await runControlledReplay(
{
configuration: () => configuration,
host: { ...host, probe, readSource },
runner: completedRunner(),
},
{
...input("plan"),
cases: [{ case_id: "large", arguments: ["too large"] }],
limits: { input_bytes: 1 },
},
);
expect(result.ok).toBe(false);
expect(probe).not.toHaveBeenCalled();
expect(readSource).not.toHaveBeenCalled();
});
it("returns a deterministic plan without admitting application code", async () => {
const execute = vi.fn(completedRunner().execute);
const first = await runControlledReplay(
{
configuration: () => configuration,
host,
runner: { execute },
},
input("plan"),
);
const second = await runControlledReplay(
{
configuration: () => configuration,
host,
runner: { execute },
},
input("plan"),
);
expect(first).toEqual(second);
expect(execute).not.toHaveBeenCalled();
expect(first.ok && first.value).toMatchObject({
phase: "plan",
plan: { network: "none", filesystem: { host_writes: false } },
evidence: null,
});
if (!first.ok) throw first.error;
const output = controlledReplayOutputSchema.parse(first.value);
expect(
controlledReplayOutputSchema.safeParse({ ...output, plan: null }).success,
).toBe(false);
expect(
controlledReplayOutputSchema.safeParse({ ...output, phase: "execute" })
.success,
).toBe(false);
});
it("rejects a stale digest before worker admission", async () => {
const execute = vi.fn(completedRunner().execute);
const result = await runControlledReplay(
{
configuration: () => configuration,
host,
runner: { execute },
},
{ ...input("execute"), plan_digest: "0".repeat(64) },
);
expect(result.ok).toBe(false);
expect(!result.ok && result.error._tag).toBe("ReplayPlanStaleError");
expect(execute).not.toHaveBeenCalled();
});
});
describe("controlled JavaScript replay configuration snapshots", () => {
it("uses one configuration snapshot for the complete planning operation", async () => {
let reads = 0;
const configuredReplay = (): JavaScriptReplayConfiguration => {
reads += 1;
return configuration;
};
const result = await runControlledReplay(
{
configuration: configuredReplay,
host,
runner: completedRunner(),
},
input("plan"),
);
expect([result.ok, reads]).toEqual([true, 1]);
});
});
describe("controlled JavaScript replay evidence and plan identity", () => {
it("plans and executes without grants after matching the content-bound plan", async () => {
const dependencies = {
configuration: () => configuration,
host,
runner: completedRunner(),
};
const planned = await runControlledReplay(dependencies, input("plan"));
if (
!planned.ok ||
typeof planned.value !== "object" ||
planned.value === null ||
Array.isArray(planned.value)
)
throw new Error("missing fixture plan");
const plan = planned.value.plan;
if (
typeof plan !== "object" ||
plan === null ||
Array.isArray(plan) ||
typeof plan.plan_digest !== "string"
)
throw new Error("missing fixture digest");
const executed = await runControlledReplay(dependencies, {
...input("execute"),
plan_digest: plan.plan_digest,
});
expect(executed.ok && executed.value).toMatchObject({
phase: "execute",
plan: null,
evidence: {
provider: { id: "rea-javascript-replay" },
authority: "controlled-replay",
confidence: "observed",
environment: { isolation: "container" },
},
});
if (!executed.ok) throw executed.error;
const output = controlledReplayOutputSchema.parse(executed.value);
expect(output.source_evidence).toHaveLength(1);
expect(output.source_evidence[0]?.confidence).toBe("observed");
expect(output.evidence?.evidence_links).toEqual([
output.source_evidence[0]?.evidence_id,
]);
expect(
controlledReplayOutputSchema.safeParse({
...output,
source_evidence: [],
}).success,
).toBe(false);
});
it("changes the commitment when selected module bytes change", async () => {
const dependencies = {
configuration: () => configuration,
host,
runner: completedRunner(),
};
const left = await runControlledReplay(dependencies, input("plan"));
const right = await runControlledReplay(
dependencies,
input("plan", resolve(root, "parser-v2.mjs")),
);
expect(left.ok && right.ok && left.value).not.toEqual(
right.ok && right.value,
);
});
});
describe("controlled JavaScript replay cancellation and export", () => {
it("projects an observed cancelled termination through the shared error algebra", async () => {
const execute = vi.fn<JavaScriptReplayRunner["execute"]>(
async (prepared) => ({
plan_digest: prepared.publicPlan.plan_digest,
outcomes: [
{
case_id: "heading",
outcome: "cancelled",
input_sha256:
prepared.publicPlan.cases[0]?.sha256 ?? "0".repeat(64),
output_sha256: null,
truncated: false,
},
],
stderr: "",
termination: "cancelled",
cleanup: { state: "complete", residual_resources: [] },
limitations: ["fixture cancellation"],
reproducer: null,
}),
);
const dependencies = {
configuration: () => configuration,
host,
runner: { execute },
};
const planned = await runControlledReplay(dependencies, input("plan"));
if (!planned.ok) throw planned.error;
const plan = controlledReplayOutputSchema.parse(planned.value).plan;
if (plan === null) throw new Error("missing cancellation plan");
const controller = new AbortController();
const result = await runControlledReplay(
dependencies,
{
...input("execute"),
plan_digest: plan.plan_digest,
},
{ signal: controller.signal },
);
expect(result.ok).toBe(false);
expect(!result.ok && result.error._tag).toBe("AnalysisCancelledError");
expect(execute).toHaveBeenCalledWith(
expect.any(Object),
configuration,
controller.signal,
);
});
it("does not admit a worker after cancellation during planning", async () => {
const controller = new AbortController();
const execute = vi.fn(completedRunner().execute);
const result = await runControlledReplay(
{
configuration: () => configuration,
host: {
...host,
probe: async () => {
controller.abort();
},
},
runner: { execute },
},
{ ...input("execute"), plan_digest: "0".repeat(64) },
{ signal: controller.signal },
);
expect(result.ok).toBe(false);
expect(!result.ok && result.error._tag).toBe("AnalysisCancelledError");
expect(execute).not.toHaveBeenCalled();
});
it("exports an owner-only source-free reproducer after cleanup", async () => {
const directory = await createTestTempDirectory("rea-reproducer-test-");
const path = join(directory, "reproducer.json");
const dependencies = {
configuration: () => configuration,
host,
runner: completedRunner(),
};
const export_ = {
path,
include_sources: false,
};
try {
const planned = await runControlledReplay(dependencies, {
...input("plan"),
reproducer_export: export_,
});
if (!planned.ok) throw new Error("missing export plan");
const plan = controlledReplayOutputSchema.parse(planned.value).plan;
if (plan === null) throw new Error("missing export plan");
const executed = await runControlledReplay(dependencies, {
...input("execute"),
reproducer_export: export_,
plan_digest: plan.plan_digest,
});
expect(executed.ok && executed.value).toMatchObject({
evidence: {
normalized_result: {
reproducer: { state: "written", path },
},
},
});
const metadata = await stat(path);
expect(metadata.mode & 0o777).toBe(0o600);
expect(JSON.parse(await readFile(path, "utf8"))).toMatchObject({
sources: null,
});
} finally {
await rm(directory, { recursive: true, force: true });
}
});
});
@@ -1,644 +0,0 @@
import { execFile, spawn } from "node:child_process";
import { readFile, writeFile } from "node:fs/promises";
import { join, resolve } from "node:path";
import { pathToFileURL } from "node:url";
import { promisify } from "node:util";
import { describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
import type { WorkerModule } from "../../../../src/replay/JavaScriptReplayWorkerTypes.js";
const fixture = async (name: string): Promise<string> =>
readFile(resolve("tests/fixtures/replay", name), "utf8");
const runWorker = async (request: unknown) =>
new Promise<{ code: number | null; stdout: string; stderr: string }>(
(resolvePromise, reject) => {
const child = spawn(
process.execPath,
[
"--experimental-vm-modules",
resolve("dist/replay/JavaScriptReplayWorker.js"),
],
{ stdio: ["pipe", "pipe", "pipe"] },
);
let stdout = "";
let stderr = "";
child.stdout.on("data", (chunk: Buffer) => {
stdout += chunk.toString("utf8");
});
child.stderr.on("data", (chunk: Buffer) => {
stderr += chunk.toString("utf8");
});
child.once("error", reject);
child.once("close", (code) => resolvePromise({ code, stdout, stderr }));
child.stdin.end(JSON.stringify(request));
},
);
const request = async (
name: string,
format: "esm" | "commonjs-factory",
entryExport: string,
arguments_: readonly unknown[],
) => ({
left: {
modules: [
{
alias: "entry",
format,
dependencies: {},
source: await fixture(name),
},
],
entryAlias: "entry",
entryExport,
},
cases: [
{
caseId: "case",
arguments: arguments_,
inputSha256: "a".repeat(64),
},
],
determinism: {
clockIso: "2000-01-01T00:00:00.000Z",
randomSeed: 7,
},
limits: { resultDepth: 16, resultNodes: 10_000, exceptionBytes: 4096 },
});
it("uses the caller's full output budget for exception text", async () => {
const message = "x".repeat(70_000);
const workerRequest = await request("exception.mjs", "esm", "default", [
message,
]);
workerRequest.limits.exceptionBytes = 80_000;
const result = await runWorker(workerRequest);
expect(result.code).toBe(0);
const response = JSON.parse(result.stdout) as {
readonly left: readonly {
readonly exception: { readonly message: string };
}[];
};
expect(response.left[0]?.exception.message).toBe(`fixture:${message}`);
});
describe("disposable JavaScript replay worker", () => {
it("rejects malformed runtime-hop requests before loading modules", async () => {
const result = await runWorker({
left: { modules: "not-an-array", entryAlias: "entry", entryExport: "x" },
cases: [],
determinism: { clockIso: "2000-01-01T00:00:00.000Z", randomSeed: 7 },
limits: { resultDepth: 16, resultNodes: 10_000, exceptionBytes: 4096 },
});
expect(result.code).toBe(70);
expect(result.stdout).toBe("");
expect(result.stderr).toContain("Invalid replay worker modules");
});
it("runs an ESM parser with projected plain data", async () => {
const result = await runWorker(
await request("parser.mjs", "esm", "default", ["# Title"]),
);
expect(result.code).toBe(0);
expect(JSON.parse(result.stdout)).toMatchObject({
left: [
{
outcome: "return",
value: { type: "heading", text: "Title" },
},
],
});
});
it("supports extracted Rspack factories and helper-defined exports", async () => {
const result = await runWorker(
await request("clipboard.factory.txt", "commonjs-factory", "normalize", [
"a\r\nb",
]),
);
expect(result.code).toBe(0);
expect(JSON.parse(result.stdout)).toMatchObject({
left: [
{
outcome: "return",
value: { text: "a\nb", bytes: 4 },
},
],
});
});
it("runs the source-owned sanitizer fixture", async () => {
const result = await runWorker(
await request("sanitizer.factory.txt", "commonjs-factory", "sanitize", [
"<script>alert(1)</script><b onclick=bad>ok</b>",
]),
);
expect(JSON.parse(result.stdout)).toMatchObject({
left: [{ outcome: "return", value: "<b>ok</b>" }],
});
});
it("denies dynamic imports and undeclared requires", async () => {
const dynamic = await runWorker(
await request("dynamic-import.mjs", "esm", "default", []),
);
expect(JSON.parse(dynamic.stdout)).toMatchObject({
left: [
{
outcome: "denied",
exception: {
message: "Dynamic import is unavailable in controlled replay",
},
},
],
});
const undeclared = await runWorker(
await request(
"undeclared-require.factory.txt",
"commonjs-factory",
"default",
[],
),
);
expect(JSON.parse(undeclared.stdout)).toMatchObject({
left: [
{
outcome: "denied",
exception: { message: "Undeclared require: node:fs" },
},
],
});
});
it("retains exceptions as observations", async () => {
const result = await runWorker(
await request("exception.mjs", "esm", "default", ["value"]),
);
expect(result.code).toBe(0);
expect(JSON.parse(result.stdout)).toMatchObject({
left: [
{
outcome: "exception",
exception: { name: "TypeError", message: "fixture:value" },
},
],
});
});
it("rejects Proxy results without invoking descriptor traps", async () => {
const result = await runWorker(
await request("proxy-result.mjs", "esm", "default", []),
);
expect(result.code).toBe(0);
expect(JSON.parse(result.stdout)).toMatchObject({
left: [
{
outcome: "serialization_error",
exception: {
name: "TypeError",
message: "Proxy replay results are unavailable",
},
},
],
});
expect(result.stderr).not.toContain("proxy trap must not run");
});
it("does not expose ambient process, require, network, buffers, or timers", async () => {
const result = await runWorker(
await request("side-effect-attempt.mjs", "esm", "default", []),
);
expect(result.code).toBe(0);
expect(JSON.parse(result.stdout)).toMatchObject({
left: [
{
outcome: "return",
value: {
process: "undefined",
require: "undefined",
fetch: "undefined",
buffer: "undefined",
timer: "undefined",
},
},
],
});
});
});
describe("ESM imports of CommonJS replay factories", () => {
it.each([false, true])(
"matches native Node default import when __esModule is %s",
async (marked) => {
const directory = await createTestTempDirectory("rea-replay-interop-");
const source = `module.exports={default:'named-default',answer:42,__esModule:${String(marked)}};`;
const path = join(directory, "dependency.cjs");
await writeFile(path, source, "utf8");
const { stdout } = await promisify(execFile)(
process.execPath,
[
"--input-type=module",
"-e",
"const {default:value}=await import(process.argv[1]); console.log(JSON.stringify({kind:typeof value,property:value.default,answer:value.answer}));",
pathToFileURL(path).href,
],
{ timeout: 5000 },
);
const expected: unknown = JSON.parse(stdout);
expect(expected).toEqual({
kind: "object",
property: "named-default",
answer: 42,
});
const workerRequest = await request("parser.mjs", "esm", "default", []);
workerRequest.left.modules = [
{
alias: "entry",
format: "esm",
dependencies: { "./dependency": "dependency" },
source:
"import value from './dependency'; export default function(){ return {kind:typeof value,property:value.default,answer:value.answer}; }",
},
{
alias: "dependency",
format: "commonjs-factory",
dependencies: {},
source: `function(module){ ${source} }`,
},
];
const result = await runWorker(workerRequest);
expect(result.code).toBe(0);
expect(JSON.parse(result.stdout)).toMatchObject({
left: [{ outcome: "return", value: expected }],
});
},
);
it.each([false, true])(
"preserves Rspack require.n behavior when __esModule is %s",
async (marked) => {
const workerRequest = await request(
"clipboard.factory.txt",
"commonjs-factory",
"default",
[],
);
workerRequest.left.modules = [
{
alias: "entry",
format: "commonjs-factory",
dependencies: { "./dependency": "dependency" },
source:
"function(module,exports,require){ const normalized=require.n(require('./dependency'))(); module.exports.default=()=>typeof normalized; }",
},
{
alias: "dependency",
format: "commonjs-factory",
dependencies: {},
source: `function(module){ module.exports={default:'named-default',answer:42,__esModule:${String(marked)}}; }`,
},
];
const result = await runWorker(workerRequest);
expect(JSON.parse(result.stdout)).toMatchObject({
left: [{ outcome: "return", value: marked ? "string" : "object" }],
});
},
);
it("preserves direct factory default-export selection", async () => {
const workerRequest = await request(
"clipboard.factory.txt",
"commonjs-factory",
"default",
[],
);
workerRequest.left.modules[0] = {
alias: "entry",
format: "commonjs-factory",
dependencies: {},
source: "function(module){ module.exports={default:()=>42}; }",
};
const result = await runWorker(workerRequest);
expect(JSON.parse(result.stdout)).toMatchObject({
left: [{ outcome: "return", value: 42 }],
});
});
});
describe("replay ESM graph linking", () => {
const esmModule = (
alias: string,
source: string,
dependencies: Record<string, string> = {},
): WorkerModule => ({ alias, source, dependencies, format: "esm" });
it.each([
{
name: "two-module cycle",
value: 8,
modules: [
esmModule(
"entry",
"import { value } from './dep'; export default function(){ return value(); } export function base(){ return 7; }",
{ "./dep": "dep" },
),
esmModule(
"dep",
"import { base } from './entry'; export function value(){ return base()+1; }",
{ "./entry": "entry" },
),
],
},
{
name: "three-module cycle",
value: 8,
modules: [
esmModule(
"entry",
"import { value } from './dep'; export default function(){ return value(); } export function base(){ return 7; }",
{ "./dep": "dep" },
),
esmModule(
"dep",
"import { value as next } from './third'; export function value(){ return next(); }",
{ "./third": "third" },
),
esmModule(
"third",
"import { base } from './entry'; export function value(){ return base()+1; }",
{ "./entry": "entry" },
),
],
},
{
name: "acyclic evaluation order",
value: 8,
modules: [
esmModule(
"entry",
"import { value } from './dep'; const answer=value+1; export default function(){ return answer; }",
{ "./dep": "dep" },
),
esmModule("dep", "export const value=7;"),
],
},
{
name: "diamond single initialization",
value: [1, 1],
modules: [
esmModule(
"entry",
"import { a } from './a'; import { b } from './b'; export default function(){ return [a,b]; }",
{ "./a": "a", "./b": "b" },
),
esmModule(
"a",
"import { value } from './shared'; export const a=value;",
{
"./shared": "shared",
},
),
esmModule(
"b",
"import { value } from './shared'; export const b=value;",
{
"./shared": "shared",
},
),
esmModule(
"shared",
"globalThis.initializations=(globalThis.initializations??0)+1; export const value=globalThis.initializations;",
),
],
},
{
name: "mixed CommonJS factory",
value: 8,
modules: [
esmModule(
"entry",
"import value from './dep'; export default function(){ return value.answer; }",
{ "./dep": "dep" },
),
{
alias: "dep",
source: "function(module) { module.exports={answer:8}; }",
dependencies: {},
format: "commonjs-factory" as const,
},
],
},
])("links $name before evaluation", async ({ modules, value }) => {
const workerRequest = await request("parser.mjs", "esm", "default", []);
workerRequest.left.modules = modules;
const result = await runWorker(workerRequest);
expect(result.code).toBe(0);
expect(JSON.parse(result.stdout)).toMatchObject({
left: [{ outcome: "return", value }],
});
});
it("still denies undeclared static imports", async () => {
const workerRequest = await request("parser.mjs", "esm", "default", []);
workerRequest.left.modules = [
esmModule(
"entry",
"import './undeclared'; export default function(){ return 1; }",
),
];
const result = await runWorker(workerRequest);
expect(JSON.parse(result.stdout)).toMatchObject({
left: [
{
outcome: "denied",
exception: { message: "Undeclared import: ./undeclared" },
},
],
});
});
});
describe("deterministic replay Date compatibility", () => {
it.each([
["new Date(2020, 0, 2).getFullYear()", 2020],
["new Date(2020, 0, 2, 3, 4, 5, 6).getMilliseconds()", 6],
["typeof Date()", "string"],
["Date() === new Date().toString()", true],
["new Date().toISOString()", "2000-01-01T00:00:00.000Z"],
["Date.now()", 946684800000],
["new Date(0).getTime()", 0],
[
"new Date('2020-01-02T00:00:00Z').toISOString()",
"2020-01-02T00:00:00.000Z",
],
["new Date() instanceof Date", true],
[
"(() => { class ChildDate extends Date {} const date = new ChildDate(2020, 0, 2); return [date instanceof ChildDate, date instanceof Date, date.getFullYear(), date.constructor === ChildDate]; })()",
[true, true, 2020, true],
],
["Date.UTC(2020, 0, 2)", 1577923200000],
])("preserves %s", async (expression, expected) => {
const workerRequest = await request("parser.mjs", "esm", "default", []);
workerRequest.left.modules[0] = {
alias: "entry",
format: "esm",
dependencies: {},
source: `export default function () { return ${expression}; }`,
};
const result = await runWorker(workerRequest);
expect(result.code).toBe(0);
expect(JSON.parse(result.stdout)).toMatchObject({
left: [{ outcome: "return", value: expected }],
});
});
});
it("rejects results the JSON projection cannot represent faithfully", async () => {
const workerRequest = await request("parser.mjs", "esm", "default", []);
workerRequest.left.modules[0] = {
alias: "entry",
format: "esm",
dependencies: {},
source: "export default function () { return { a: 1, [Symbol('s')]: 2 }; }",
};
const result = await runWorker(workerRequest);
expect(JSON.parse(result.stdout)).toMatchObject({
left: [
{
outcome: "serialization_error",
exception: {
message: "Symbol-keyed replay results are unavailable",
},
},
],
});
});
it("keeps an own __proto__ property instead of mutating the output", async () => {
const workerRequest = await request("parser.mjs", "esm", "default", []);
workerRequest.left.modules[0] = {
alias: "entry",
format: "esm",
dependencies: {},
source: `export default function () {
const value = {};
Object.defineProperty(value, "__proto__", {
value: { injected: true },
enumerable: true,
});
return value;
}`,
};
const result = await runWorker(workerRequest);
expect(JSON.parse(result.stdout)).toMatchObject({
left: [
{
outcome: "return",
value: { __proto__: { injected: true } },
},
],
});
});
describe("replay determinism and builtin identity", () => {
const evaluate = async (
expression: string,
randomSeed: number,
): Promise<unknown> => {
const workerRequest = await request("parser.mjs", "esm", "default", []);
workerRequest.determinism.randomSeed = randomSeed;
workerRequest.left.modules[0] = {
alias: "entry",
format: "esm",
dependencies: {},
source: `export default function () { return ${expression}; }`,
};
const result = await runWorker(workerRequest);
expect(result.code).toBe(0);
return JSON.parse(result.stdout).left[0];
};
it("varies Math.random across draws when seeded with zero", async () => {
const outcome = (await evaluate(
"[Math.random(), Math.random(), Math.random()]",
0,
)) as { outcome: string; value?: number[] };
expect(outcome.outcome).toBe("return");
expect(new Set(outcome.value).size).toBe(3);
});
it("produces an identical stream for the same seed", async () => {
const first = await evaluate("[Math.random(), Math.random()]", 5);
const second = await evaluate("[Math.random(), Math.random()]", 5);
expect(first).toEqual(second);
});
it("presents Date with real builtin identity", async () => {
expect(await evaluate("[Date.name, Date.length]", 3)).toMatchObject({
outcome: "return",
value: ["Date", 7],
});
});
it("presents Math with real descriptors and unaffected members", async () => {
// Object identity is realm-specific inside the vm, so the meaningful checks
// are the descriptor and the untouched members.
const outcome = (await evaluate(
"[Object.getOwnPropertyDescriptor(Math, 'random').configurable, Object.getOwnPropertyDescriptor(Math, 'random').writable, Math.max(1, 2), Math.floor(1.7), Math.PI > 3]",
3,
)) as { outcome: string; value?: unknown[] };
expect(outcome).toMatchObject({
outcome: "return",
value: [true, true, 2, 1, true],
});
});
});
describe("replay array projection", () => {
it.each([
["Array(3)", [null, null, null]],
[
"(() => { const value = Array(3); value[1] = 42; return value; })()",
[null, 42, null],
],
["[1, null, 3]", [1, null, 3]],
["[]", []],
])("preserves JSON array positions for %s", async (expression, expected) => {
const workerRequest = await request("parser.mjs", "esm", "default", []);
workerRequest.left.modules[0] = {
alias: "entry",
format: "esm",
dependencies: {},
source: `export default function () { return ${expression}; }`,
};
const result = await runWorker(workerRequest);
expect(result.code).toBe(0);
expect(JSON.parse(result.stdout)).toMatchObject({
left: [{ outcome: "return", value: expected }],
});
});
it("accounts for holes in the existing result node budget", async () => {
const workerRequest = await request("parser.mjs", "esm", "default", []);
workerRequest.left.modules[0] = {
alias: "entry",
format: "esm",
dependencies: {},
source: "export default function () { return Array(4); }",
};
workerRequest.limits.resultNodes = 3;
const result = await runWorker(workerRequest);
expect(JSON.parse(result.stdout)).toMatchObject({
left: [
{
outcome: "serialization_error",
exception: { message: "Replay result projection limit exceeded" },
},
],
});
});
});