From e65644cdaca2cb0a8d6495c510acb9ff6a97d0d0 Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 12 Nov 2026 00:25:55 -0600 Subject: [PATCH 1/2] experimental: dual-run a test file under Node.js and its executable A compiled program should answer the way Node.js answers for the same input. Nothing checked that for tests outside the repository: a runner could compile a test file and run it, but no one compared the two runs. `@scriptc/experimental/dual-run` exports `dualRun(entry, options)`, which builds `entry` through the `scriptc` command and its executable cache, runs it under Node.js and as the binary, and returns `{ node, native, equal, diff }`. The runs are compared after the normalization the differential harness documents: durations take a placeholder, stack frames, the "N lines matching cause stack trace" fold and the inspect property block are dropped, and stderr is compared only when both runs exit 0. A difference is returned as readable text naming the test it breaks and the line it starts at. The API is Node.js tooling (it spawns the compiler), so vitest and jest call it while a scriptc-built program cannot, and it is opt-in. `@scriptc/experimental/dual-run/reporter` is a node:test reporter for `node --test`. It compares every file Node ran, prints one line per file, shows the first difference in a diff, reports the failing tests Node reported, gives a line to a file Node could not load, and reports a file whose Node output differs between two runs as flaky rather than blaming the binary. It sets the exit code to 1 on a difference; a build the compiler refuses is reported with its diagnostics and also fails the run. The command is found through SCRIPTC_BIN, the nearest node_modules/.bin from the working directory upward, or PATH. Both lanes run with TZ=UTC and LANG=C; the Node lane uses --experimental-transform-types and --disallow-code-generation-from-strings, so enums run and code generation is refused as a compiled program refuses it. Node's warnings about the transform flag and about a .ts file in a package without "type": "module" are turned off: they carry content the binary never prints, the process id included, so even two Node runs of the same file would differ. test: tests/harness/dual-run.test.ts covers a passing file, a failing assertion, a typeless package's warning, a program whose stdout differs, a file the compiler refuses and the reporter over all four (plus a file Node's loader rejects). Both flavors build the fixtures as a user does, without sanitizers. The suite's cost is recorded in scripts/ci-test-costs.json. docs: a Dual-Run Testing page with a captured report, the comparison rules and the API, a section in the experimental package README, and the page title and migration baseline entries. --- docs/content/docs/dual-run.mdx | 95 ++++++ docs/content/docs/meta.json | 1 + docs/src/lib/page-titles.ts | 1 + docs/test/fixtures/migration-baseline.json | 26 ++ packages/experimental/README.md | 20 ++ packages/experimental/dual-run-core.js | 310 +++++++++++++++++++ packages/experimental/dual-run.d.ts | 58 ++++ packages/experimental/dual-run.js | 51 +++ packages/experimental/dual-run/reporter.d.ts | 12 + packages/experimental/dual-run/reporter.js | 178 +++++++++++ packages/experimental/package.json | 13 + scripts/ci-test-costs.json | 2 + tests/fixtures/dual-run/diverges.test.mts | 11 + tests/fixtures/dual-run/failing.test.mts | 10 + tests/fixtures/dual-run/load-failure.mts | 15 + tests/fixtures/dual-run/passing.test.mts | 12 + tests/fixtures/dual-run/refused.ts | 4 + tests/fixtures/dual-run/typeless.test.ts | 9 + tests/harness/dual-run.test.ts | 136 ++++++++ 19 files changed, 964 insertions(+) create mode 100644 docs/content/docs/dual-run.mdx create mode 100644 packages/experimental/dual-run-core.js create mode 100644 packages/experimental/dual-run.d.ts create mode 100644 packages/experimental/dual-run.js create mode 100644 packages/experimental/dual-run/reporter.d.ts create mode 100644 packages/experimental/dual-run/reporter.js create mode 100644 tests/fixtures/dual-run/diverges.test.mts create mode 100644 tests/fixtures/dual-run/failing.test.mts create mode 100644 tests/fixtures/dual-run/load-failure.mts create mode 100644 tests/fixtures/dual-run/passing.test.mts create mode 100644 tests/fixtures/dual-run/refused.ts create mode 100644 tests/fixtures/dual-run/typeless.test.ts create mode 100644 tests/harness/dual-run.test.ts diff --git a/docs/content/docs/dual-run.mdx b/docs/content/docs/dual-run.mdx new file mode 100644 index 0000000000..54e4f9aeeb --- /dev/null +++ b/docs/content/docs/dual-run.mdx @@ -0,0 +1,95 @@ +--- +title: "Dual-Run Testing" +--- + +Compiled tests should report what the same tests report under Node.js. Dual-run testing runs each test file both ways, once under Node.js and once as the executable scriptc builds, compares the two runs, and fails when they differ. It is opt-in: it runs only when you add the reporter or call the program API. Run it in CI, where a divergence fails the change that introduced it rather than waiting for a user to notice it. + +Add both packages as development dependencies: + +```console +$ npm install --save-dev scriptc @scriptc/experimental +``` + +Dual-run builds through the `scriptc` command and its executable cache, so the second run of an unchanged file reuses the executable it built the first time. It uses the command named by `SCRIPTC_BIN` when that is set, otherwise the nearest `node_modules/.bin/scriptc` from the working directory upward, otherwise `scriptc` on `PATH`. + +## Run a suite with the reporter + +Pass the reporter to the Node.js test runner in place of its own. For every test file the runner finds, the reporter builds the file, runs the binary, and compares the two runs. It prints one line per file, shaped like this run on a suite of four files, one of which fails an assertion, one whose report differs, and one whose Node.js output varies between runs: + +```console +$ node --test --test-reporter=@scriptc/experimental/dual-run/reporter --test-reporter-destination=stdout +✖ test/format.test.ts (1 passed, 1 failed) + ✖ formats thousands: Expected values to be strictly equal: (line 8) +✔ test/parse.test.ts (2 passed) +✖ test/point.test.ts "reports a thrown point": native stdout differs at line 15 +@@ stdout line 15 + + test at test/point.test.ts:12:1 + ✖ reports a thrown point (Xms) + - Point { x: 1, y: 2 } + + [object Object] + +ℹ test/watch.test.ts: the Node run differs between two runs (flaky), not compared +``` + +- A `✔` line means every test in the file behaves the same in both runs. +- A `✖` line that names a test and shows a diff means the compiled binary's output differs from Node.js, and the diff starts at the line where it does. +- A `✖` line with test counts means Node.js reported a failed test in the file. The failing tests and their messages follow, so the report explains the exit code on its own. +- A `✖` line without counts is a file Node.js itself could not run, for example because its TypeScript loader rejects the file's syntax; the failure Node.js reported follows, and the file is still compared. +- An `ℹ` line marks a file whose output differed between two Node.js runs. The reporter does not blame the binary for that, and the comparison does not fail the run. + +The runner's exit code is nonzero when a file's reports differ or when a test fails. Files that fail to build are reported with the compiler's diagnostics and also fail the run. + +The report does not repeat the test files' own output. Program output appears in a diff when the two runs differ; for the full Node.js report, run the file with `node` directly. + +## Compare one file from a test runner + +Vitest and jest run JavaScript on Node.js, so scriptc cannot compile them, but they can call the program API. `dualRun` runs one file twice and returns both runs: + +```ts:tests/dual-run.test.ts +import { expect, test } from "vitest"; +import { dualRun } from "@scriptc/experimental/dual-run"; + +test("compiled serialization matches Node.js", async () => { + const result = await dualRun("test/serialize.test.ts"); + expect(result.diff).toBe(""); + expect(result.equal).toBe(true); +}); +``` + +A failing comparison keeps the first difference in `result.diff`, so `expect(result.diff).toBe("")` prints it in the test failure report. When the file does not compile, `dualRun` rejects with a `DualRunBuildError` whose `stderr` holds the compiler's diagnostics. + +## What is compared + +Both runs render a Node.js spec report, and the two reports are compared as text, together with the program's output and exit code. The differences that are inherent to the two lanes are normalized before the comparison: + +- a duration in a test result line or in the suite summary takes a placeholder, because the runners measure different times; +- stack frames, the `N lines matching cause stack trace` fold and the property block that follows them are dropped, because they name runner-internal code and objects; +- stderr is compared only when both runs exit 0, because an uncaught error's report format differs between the two (stdout, the report and the exit code are still compared). + +Everything else must match: test names, pass, fail, skip and todo results, assertion messages, the failing-tests section, and the program's own stdout and stderr. + +Both lanes run with `TZ=UTC` and `LANG=C`, so dates and collation do not depend on the machine. The Node.js lane also runs with `--experimental-transform-types`, which a compiled program does not need, and with `--disallow-code-generation-from-strings`, the same refusal compiled programs apply to `eval` and `Function`. Node's warnings about the transform flag and about a `.ts` file in a package that does not set `"type": "module"` are turned off, because they carry content the binary never prints, the process id included. + +## API + +
+
dualRun(entry, options?)
+
Runs entry under Node.js and as its compiled executable and returns a promise of {`{ node, native, equal, diff }`}. Each run has stdout, stderr and exitCode (null when a signal ended it). equal is true when the runs match after the normalization above, and diff is the first difference as readable text, "" when there is none. Rejects with a DualRunBuildError when the program does not compile.
+
options.args
+
Arguments passed to both runs.
+
options.stdin
+
A string or Uint8Array written to both runs' standard input, which is closed afterwards.
+
options.env
+
Variables added to both runs' environment. An entry set to undefined removes the variable.
+
options.cwd
+
Working directory of both runs and of the build. Defaults to the current working directory.
+
options.timeoutMs
+
Bound on each run, in milliseconds. Defaults to 120000.
+
new DualRunBuildError()
+
The build's entry, cli, stderr and exitCode, and the same text in message.
+
+ +## Limits + +Dual-run builds native executables, so a suite that runs as WebAssembly under `scriptc run` is not covered, and a compiled program cannot import either module: they spawn processes, so they run under Node.js only. A program whose own Node.js run varies is reported as flaky and not compared, so a suite that depends on timing or on the network needs those inputs deterministic before dual-run can say anything about it. The comparison is also blind to a difference that the normalization removes, such as a duration or a stack frame, and to stderr of a run that exits nonzero. diff --git a/docs/content/docs/meta.json b/docs/content/docs/meta.json index b84c6f1843..040cb2d243 100644 --- a/docs/content/docs/meta.json +++ b/docs/content/docs/meta.json @@ -13,6 +13,7 @@ "threads", "contracts", "experimental", + "dual-run", "native-objects", "---Reference---", "cli", diff --git a/docs/src/lib/page-titles.ts b/docs/src/lib/page-titles.ts index bc7d416e3c..4d2fd20758 100644 --- a/docs/src/lib/page-titles.ts +++ b/docs/src/lib/page-titles.ts @@ -10,6 +10,7 @@ export const PAGE_TITLES: Record = { threads: "Sharing Data Between Workers", contracts: "Contract Types", experimental: "Experimental APIs", + "dual-run": "Dual-Run Testing", wasm: "WebAssembly Modules", platforms: "Platform Support", compatibility: "Node.js 24 Compatibility", diff --git a/docs/test/fixtures/migration-baseline.json b/docs/test/fixtures/migration-baseline.json index 385c3ad784..5b671041a1 100644 --- a/docs/test/fixtures/migration-baseline.json +++ b/docs/test/fixtures/migration-baseline.json @@ -335,6 +335,32 @@ } ] }, + { + "href": "/docs/dual-run", + "title": "Dual-Run Testing", + "headings": [ + { + "text": "Run a suite with the reporter", + "id": "run-a-suite-with-the-reporter" + }, + { + "text": "Compare one file from a test runner", + "id": "compare-one-file-from-a-test-runner" + }, + { + "text": "What is compared", + "id": "what-is-compared" + }, + { + "text": "API", + "id": "api" + }, + { + "text": "Limits", + "id": "limits" + } + ] + }, { "legacy": "/wasm", "href": "/docs/wasm", diff --git a/packages/experimental/README.md b/packages/experimental/README.md index 1e7b05f303..ff3f33ca67 100644 --- a/packages/experimental/README.md +++ b/packages/experimental/README.md @@ -175,3 +175,23 @@ NODE_OPTIONS=--disallow-code-generation-from-strings node --require @scriptc/exp ``` The hook prints a warning to stderr when the flag is missing, or when the running Node.js version differs from the release the refusal data describes. +## Dual-run testing + +`@scriptc/experimental/dual-run` runs a test file twice, once under Node.js and once as the executable scriptc builds, and compares the runs: test names, pass and fail results, assertion messages, program output and the exit code, with durations and stack frames normalized away. It is Node.js tooling, so a scriptc-built program cannot call it, and a compiled program never needs to. + +```ts +import { dualRun } from "@scriptc/experimental/dual-run"; + +const result = await dualRun("test/format.test.ts"); +if (!result.equal) throw new Error(result.diff); +``` + +`dualRun(entry, { args, stdin, env, cwd, timeoutMs })` returns `{ node, native, equal, diff }`, where each run has `stdout`, `stderr` and `exitCode`. A program that does not compile rejects with a `DualRunBuildError` whose `stderr` holds the diagnostics. + +The `@scriptc/experimental/dual-run/reporter` subpath is a Node.js test reporter that does the same for every file `node --test` runs: + +```console +$ node --test --test-reporter=@scriptc/experimental/dual-run/reporter --test-reporter-destination=stdout +``` + +It prints one line per file, shows a diff when the two runs differ, reports a file whose Node.js output itself varies as flaky, and fails the run on a difference. Both forms build through the `scriptc` command and its executable cache, found from `SCRIPTC_BIN`, `node_modules/.bin` or `PATH`. See [dual-run testing](https://scriptc.dev/docs/dual-run). diff --git a/packages/experimental/dual-run-core.js b/packages/experimental/dual-run-core.js new file mode 100644 index 0000000000..28550a3851 --- /dev/null +++ b/packages/experimental/dual-run-core.js @@ -0,0 +1,310 @@ +// The dual-run engine: one program run twice, under Node.js and as the +// compiled binary, and the two runs compared. @scriptc/experimental's +// `dualRun` and the `dual-run/reporter` module are thin layers over it; the +// module itself is not reachable through the package's exports. + +import { spawn } from "node:child_process"; +import { existsSync, statSync } from "node:fs"; +import { delimiter, dirname, isAbsolute, join, resolve } from "node:path"; + +/** Node runs the oracle with these flags: TypeScript's transform-only + * features (enums, namespaces) need --experimental-transform-types, the + * code-generation flag makes `eval` and `Function` throw the way a compiled + * program always does, and the warning the transform flag prints is + * silenced so both lanes have the same stderr. A .ts file in a package + * without "type": "module" also warns about its module type, with the + * process id in the warning, which neither lane should be compared on. */ +const NODE_ORACLE_FLAGS = [ + "--experimental-transform-types", + "--disable-warning=ExperimentalWarning", + "--disable-warning=MODULE_TYPELESS_PACKAGE_JSON", + "--disallow-code-generation-from-strings", +]; + +/** Both lanes run with this environment: a fixed time zone and locale keep + * dates and collation out of the diff, as the repository's differential + * harness does. */ +const BASE_ENV = { TZ: "UTC", LANG: "C" }; + +/** The documented normalization, identical to tests/harness/node-test-normalize.ts: + * Node's spec reporter embeds real durations in every line, and the stack + * frames, the "N lines matching cause stack trace" fold and the inspect + * property block are runner-internal output the compiled runtime omits. + * Everything else must match byte-exactly. */ +function normalizeNodeTestOutput(stdout) { + const out = []; + let inPropBlock = false; + for (const line of stdout.split("\n")) { + if (inPropBlock) { + if (/^\s*\}\s*$/.test(line)) inPropBlock = false; + continue; + } + if (/^\s+\.\.\. \d+ lines? matching cause stack trace \.\.\.$/.test(line)) continue; + if (/^\s+at /.test(line)) { + if (line.trimEnd().endsWith("{")) inPropBlock = true; + continue; + } + out.push( + line + .replace(/\(\d+(?:\.\d+)?ms\)/g, "(Xms)") + .replace(/^ℹ duration_ms .*$/, "ℹ duration_ms X"), + ); + } + return out.join("\n"); +} + +/** Thrown when the CLI cannot build a program: its diagnostics are the + * build's own stderr, kept whole so a runner can print them. */ +export class DualRunBuildError extends Error { + constructor(entry, cli, stderr, exitCode) { + super( + `scriptc could not build ${entry}\n${stderr.trim()}` + + (exitCode === null ? "" : `\n(build exited with code ${exitCode})`), + ); + this.name = "DualRunBuildError"; + this.entry = entry; + this.cli = cli; + this.stderr = stderr; + this.exitCode = exitCode; + } +} + +/** The CLI as a command line: a JavaScript file runs under this Node, a + * Windows .cmd shim needs a shell, anything else runs as it is. */ +function commandFor(bin) { + if (/\.(?:js|mjs|cjs)$/.test(bin)) + return { command: process.execPath, prefix: [bin], shell: false }; + if (process.platform === "win32" && /\.(?:cmd|bat)$/.test(bin)) + return { command: bin, prefix: [], shell: true }; + return { command: bin, prefix: [], shell: false }; +} + +/** The `scriptc` CLI: SCRIPTC_BIN when set, else the nearest + * node_modules/.bin/scriptc from cwd upward, else PATH. */ +function resolveScriptcBin({ cwd = process.cwd(), env = process.env } = {}) { + if (env.SCRIPTC_BIN) { + const bin = isAbsolute(env.SCRIPTC_BIN) ? env.SCRIPTC_BIN : resolve(cwd, env.SCRIPTC_BIN); + if (existsSync(bin)) return bin; + throw new Error(`scriptc: SCRIPTC_BIN names ${bin}, which does not exist`); + } + const names = + process.platform === "win32" ? ["scriptc.cmd", "scriptc.exe", "scriptc"] : ["scriptc"]; + for (let dir = resolve(cwd); ; dir = dirname(dir)) { + for (const name of names) { + const bin = join(dir, "node_modules", ".bin", name); + if (existsSync(bin)) return bin; + } + if (dirname(dir) === dir) break; + } + for (const dir of (env.PATH ?? "").split(delimiter)) { + if (dir === "") continue; + for (const name of names) { + const bin = join(dir, name); + if (existsSync(bin)) return bin; + } + } + throw new Error( + "scriptc: no scriptc executable found: install the scriptc package in this project, put it on PATH, or set SCRIPTC_BIN", + ); +} + +/** The merged environment both lanes run with. The fixed variables win over + * the caller's, since a diff that depends on the machine's locale or time + * zone would not be about the program. */ +function laneEnv(env) { + const merged = { ...process.env, ...env, ...BASE_ENV }; + for (const key of Object.keys(merged)) if (merged[key] === undefined) delete merged[key]; + return merged; +} + +/** Runs a command to completion, capturing both streams. A spawn failure or + * timeout rejects; a nonzero exit code does not. */ +function runCommand(command, args, { cwd, env, stdin, timeoutMs = 120_000, shell = false }) { + return new Promise((resolveRun, reject) => { + const child = spawn(command, args, { + cwd, + env, + shell, + stdio: [stdin === undefined ? "ignore" : "pipe", "pipe", "pipe"], + }); + const out = []; + const err = []; + let timedOut = false; + const timer = setTimeout(() => { + timedOut = true; + child.kill("SIGKILL"); + }, timeoutMs); + child.stdout.on("data", (chunk) => out.push(chunk)); + child.stderr.on("data", (chunk) => err.push(chunk)); + child.on("error", (error) => { + clearTimeout(timer); + reject(error); + }); + if (stdin !== undefined) { + child.stdin.on("error", () => {}); // A program may exit before reading. + child.stdin.end(stdin); + } + child.on("close", (code, signal) => { + clearTimeout(timer); + if (timedOut) { + reject(new Error(`${command} did not finish within ${timeoutMs}ms`)); + return; + } + resolveRun({ + stdout: Buffer.concat(out).toString("utf8"), + stderr: Buffer.concat(err).toString("utf8"), + exitCode: code === null ? null : code, + signal: signal ?? null, + }); + }); + }); +} + +/** Builds one program through the `scriptc` CLI, whose executable cache + * makes a repeated build a cache hit. The CLI prints the artifact path as + * the last line of stdout. */ +async function buildExecutable(entry, { cwd, env, timeoutMs } = {}) { + const bin = resolveScriptcBin({ cwd, env }); + const { command, prefix, shell } = commandFor(bin); + const absoluteEntry = resolve(cwd ?? process.cwd(), entry); + if (!existsSync(absoluteEntry)) throw new Error(`scriptc: ${absoluteEntry} does not exist`); + const build = await runCommand(command, [...prefix, "build", absoluteEntry], { + cwd, + env, + timeoutMs, + shell, + }); + if (build.exitCode !== 0) { + throw new DualRunBuildError(absoluteEntry, bin, build.stderr, build.exitCode); + } + const path = build.stdout.trim().split("\n").at(-1) ?? ""; + if (path === "" || !existsSync(path) || !statSync(path).isFile()) { + throw new Error(`scriptc: the build of ${absoluteEntry} did not print an artifact path`); + } + return { binaryPath: path, cli: bin }; +} + +/** One program under Node.js alone, in the oracle lane's environment: the + * reporter runs it a second time to tell a flaky program from a divergent + * one. */ +export function runNodeLane(entry, { args = [], stdin, env = {}, cwd, timeoutMs = 120_000 } = {}) { + const laneCwd = resolve(cwd ?? process.cwd()); + return runCommand(process.execPath, [...NODE_ORACLE_FLAGS, resolve(laneCwd, entry), ...args], { + cwd: laneCwd, + env: laneEnv(env), + stdin, + timeoutMs, + }); +} + +/** Both lanes for one program: Node.js runs the entry with the oracle + * flags, the binary runs as it was built. */ +export async function runLanes( + entry, + { args = [], stdin, env = {}, cwd, timeoutMs = 120_000 } = {}, +) { + const laneCwd = resolve(cwd ?? process.cwd()); + const absoluteEntry = resolve(laneCwd, entry); + const mergedEnv = laneEnv(env); + const { binaryPath } = await buildExecutable(absoluteEntry, { + cwd: laneCwd, + env: mergedEnv, + timeoutMs, + }); + const [node, native] = await Promise.all([ + runCommand(process.execPath, [...NODE_ORACLE_FLAGS, absoluteEntry, ...args], { + cwd: laneCwd, + env: mergedEnv, + stdin, + timeoutMs, + }), + runCommand(binaryPath, args, { cwd: laneCwd, env: mergedEnv, stdin, timeoutMs }), + ]); + return { node, native, binaryPath, entry: absoluteEntry, cwd: laneCwd }; +} + +/** How the two runs differ, or null when they agree. stdout is compared + * after the node:test normalization; stderr only when both runs exited 0, + * because a nonzero run's stderr carries the uncaught-throw report, whose + * format is a documented divergence (tests/harness/differential.test.ts + * states the same rule). */ +export function compareLanes(node, native) { + const differences = []; + if (node.exitCode !== native.exitCode) { + differences.push({ + stream: "exit code", + node: `${node.exitCode}`, + native: `${native.exitCode}`, + }); + } + const nodeOut = normalizeNodeTestOutput(node.stdout); + const nativeOut = normalizeNodeTestOutput(native.stdout); + if (nodeOut !== nativeOut) + differences.push({ stream: "stdout", node: nodeOut, native: nativeOut }); + if (node.exitCode === 0 && native.exitCode === 0) { + const nodeErr = normalizeNodeTestOutput(node.stderr); + const nativeErr = normalizeNodeTestOutput(native.stderr); + if (nodeErr !== nativeErr) + differences.push({ stream: "stderr", node: nodeErr, native: nativeErr }); + } + return differences.length === 0 ? null : differences; +} + +/** The first line index (0-based) where two texts differ, or -1. */ +function firstDifference(a, b) { + const al = a.split("\n"); + const bl = b.split("\n"); + for (let i = 0; i < Math.max(al.length, bl.length); i++) if (al[i] !== bl[i]) return i; + return -1; +} + +/** The test line a differing report line belongs to: the nearest preceding + * " " line, so a diff names the test it broke. */ +function testNameAt(text, lineIndex) { + const lines = text.split("\n"); + const result = /^\s*(?:✔|✖|▶|⚠)\s+(.*?)(?:\s+\((?:X|\d*\.?\d+)ms\))?(?:\s+#.*)?\s*$/; + for (let i = Math.min(lineIndex, lines.length - 1); i >= 0; i--) { + const match = result.exec(lines[i]); + if (match && match[1] !== "") return match[1]; + } + return null; +} + +const DIFF_CONTEXT = 3; +const DIFF_MAX_LINES = 40; + +/** A compact line diff: the differing line with a few lines of context on + * each side, marked - for Node and + for the binary. */ +function formatDiff(stream, node, native) { + const line = firstDifference(node, native); + if (line < 0) return ""; + const al = node.split("\n"); + const bl = native.split("\n"); + const start = Math.max(0, line - DIFF_CONTEXT); + const end = Math.min(Math.max(al.length, bl.length), line + DIFF_CONTEXT + 1); + const out = [`@@ ${stream} line ${line + 1}`]; + for (let i = start; i < end; i++) { + if (al[i] === bl[i]) { + out.push(` ${al[i] ?? ""}`); + continue; + } + out.push(` - ${al[i] ?? ""}`); + out.push(` + ${bl[i] ?? ""}`); + } + if (end < Math.max(al.length, bl.length)) + out.push(` … ${Math.max(al.length, bl.length) - end} more lines`); + if (out.length > DIFF_MAX_LINES) out.length = DIFF_MAX_LINES; + return out.join("\n"); +} + +/** One readable sentence and diff for the first difference. `name` is the + * compared program as the caller wants it shown. */ +export function describeDifferences(name, differences) { + const first = differences[0]; + if (first.stream === "exit code") + return `${name}: native exit code ${first.native}, node ${first.node}`; + const where = firstDifference(first.node, first.native) + 1; + const test = testNameAt(first.node, where - 1); + const heading = `${name}${test === null ? "" : ` ${JSON.stringify(test)}`}: native ${first.stream} differs at line ${where}`; + return `${heading}\n${formatDiff(first.stream, first.node, first.native)}`; +} diff --git a/packages/experimental/dual-run.d.ts b/packages/experimental/dual-run.d.ts new file mode 100644 index 0000000000..4d338baea8 --- /dev/null +++ b/packages/experimental/dual-run.d.ts @@ -0,0 +1,58 @@ +/** One program's run in one lane. `exitCode` is null when a signal ended + * the process. */ +export interface DualRunLane { + stdout: string; + stderr: string; + exitCode: number | null; +} + +export interface DualRunOptions { + /** Arguments passed to both lanes. */ + args?: readonly string[]; + /** Written to both lanes' standard input, which is closed afterwards. */ + stdin?: string | Uint8Array; + /** Added to both lanes' environment. The environment always sets TZ=UTC + * and LANG=C. An entry left undefined removes the variable. */ + env?: Record; + /** Working directory of both lanes and of the build. Defaults to + * process.cwd(). */ + cwd?: string; + /** Bound on each lane's run, in milliseconds. Defaults to 120000. */ + timeoutMs?: number; +} + +export interface DualRunResult { + node: DualRunLane; + native: DualRunLane; + /** Whether the runs agree after the documented node:test normalization: + * durations are replaced by a placeholder on both sides, stack frames, + * the "N lines matching cause stack trace" fold and the inspect property + * block are dropped, stderr is compared only when both runs exit 0, and + * everything else matches byte-exactly. */ + equal: boolean; + /** A readable diff of the first difference, "" when `equal`. */ + diff: string; +} + +/** A build that did not produce an executable: the CLI's diagnostics are in + * `stderr`. */ +export declare class DualRunBuildError extends Error { + readonly name: "DualRunBuildError"; + /** The program's absolute path. */ + readonly entry: string; + /** The `scriptc` executable the build ran. */ + readonly cli: string; + /** The build's stderr, whole. */ + readonly stderr: string; + /** The build's exit code, null when a signal ended it. */ + readonly exitCode: number | null; +} + +/** Runs `entry` once under Node.js and once as the executable scriptc + * builds from it, and compares the two runs: test names, pass/fail results, + * assertion messages, program output and the exit code. The build goes + * through the scriptc CLI and its executable cache, and the CLI is found + * through SCRIPTC_BIN, the nearest node_modules/.bin/scriptc from `cwd` + * upward, or PATH. Rejects with a DualRunBuildError when the program does + * not compile. */ +export declare function dualRun(entry: string, options?: DualRunOptions): Promise; diff --git a/packages/experimental/dual-run.js b/packages/experimental/dual-run.js new file mode 100644 index 0000000000..0917490d57 --- /dev/null +++ b/packages/experimental/dual-run.js @@ -0,0 +1,51 @@ +// @scriptc/experimental/dual-run — the program API. +// +// `dualRun` runs a program twice, once under Node.js and once as the +// executable scriptc builds from it, and compares the two runs: test names, +// pass/fail results, assertion messages, program output and the exit code, +// with the durations and stack frames both sides render differently +// normalized away. It is Node.js tooling (it spawns the compiler and the +// binary), so a scriptc-built program cannot call it; a test runner such as +// vitest or jest, which scriptc cannot compile, can. + +import { compareLanes, describeDifferences, runLanes } from "./dual-run-core.js"; + +/** + * Runs `entry` under Node.js and as its compiled executable, and compares + * the runs. + * + * @param {string} entry The program, relative to `cwd`. + * @param {{ + * args?: readonly string[], + * stdin?: string | Uint8Array, + * env?: Record, + * cwd?: string, + * timeoutMs?: number, + * }} [options] + * `args` are passed to both lanes, `stdin` is written to both, and `env` + * is added to both lanes' environment (which always has TZ=UTC and + * LANG=C). `cwd` is the working directory of both lanes and of the + * build; `timeoutMs` bounds each lane's run. + * @returns {Promise<{ + * node: { stdout: string, stderr: string, exitCode: number | null }, + * native: { stdout: string, stderr: string, exitCode: number | null }, + * equal: boolean, + * diff: string, + * }>} + * The two runs, `equal` when they agree, and a readable diff when they + * do not (`diff` is "" when `equal`). Rejects with a `DualRunBuildError` + * when the program does not compile, whose `stderr` holds the + * diagnostics. + */ +export async function dualRun(entry, options = {}) { + const { node, native } = await runLanes(entry, options); + const differences = compareLanes(node, native); + return { + node, + native, + equal: differences === null, + diff: differences === null ? "" : describeDifferences(entry, differences), + }; +} + +export { DualRunBuildError } from "./dual-run-core.js"; diff --git a/packages/experimental/dual-run/reporter.d.ts b/packages/experimental/dual-run/reporter.d.ts new file mode 100644 index 0000000000..f28e8693e7 --- /dev/null +++ b/packages/experimental/dual-run/reporter.d.ts @@ -0,0 +1,12 @@ +import type { TestEvent } from "node:test/reporters"; + +/** A node:test reporter that, for every file Node ran, builds the file with + * scriptc, runs the binary and compares its spec report, program output and + * exit code with a plain `node ` run, using the documented node:test + * normalization. A difference is reported against the test it breaks and + * sets the exit code to 1; a file whose Node output differs between two + * runs is reported as flaky instead. Use it with + * `--test-reporter=@scriptc/experimental/dual-run/reporter`. */ +export default function reporter( + source: AsyncGenerator, +): AsyncGenerator; diff --git a/packages/experimental/dual-run/reporter.js b/packages/experimental/dual-run/reporter.js new file mode 100644 index 0000000000..7d5089a9f5 --- /dev/null +++ b/packages/experimental/dual-run/reporter.js @@ -0,0 +1,178 @@ +// @scriptc/experimental/dual-run/reporter — a node:test reporter that runs +// every test file a second way. +// +// node --test --test-reporter=@scriptc/experimental/dual-run/reporter \ +// --test-reporter-destination=stdout +// +// Node runs the files as usual; for each file the reporter builds it with +// scriptc, runs the binary, and compares the binary's spec report, program +// output and exit code with a plain `node ` run of the same file, +// using the documented node:test normalization (durations, stack frames and +// the inspect property block are runner-internal and differ by design). A +// difference is reported against the test it breaks and fails the run. A +// file whose Node output itself differs between two runs is reported as +// flaky instead: the Node run, not the program, is what varies. +// +// The report is one line per file, plus the failing tests' messages and, +// on a difference, a diff. Node's own results come from the event stream +// (name, counts and message per test), so a test that fails in both lanes +// is reported as the test failure it is. + +import { relative } from "node:path"; +import { + DualRunBuildError, + compareLanes, + describeDifferences, + runLanes, + runNodeLane, +} from "../dual-run-core.js"; + +/** How many files are compared at once. Node runs its files concurrently, + * and each comparison is one cached build plus two short runs. */ +const CONCURRENCY = 4; + +/** The report stream is whatever Node was told to use; the reporter only + * yields text. */ +export default async function* reporter(source) { + const cwd = process.cwd(); + /** What Node reported about each file, keyed by its absolute path. */ + const files = new Map(); + const pending = []; + const state = { diverged: false }; + + const stateFor = (file) => { + let fileState = files.get(file); + if (fileState === undefined) + files.set(file, (fileState = { summary: null, failures: [], queued: false })); + return fileState; + }; + + /** Starts the comparison of one file, once; the entry is unknown before + * Node reports the file done. */ + function queue(file) { + const fileState = stateFor(file); + if (fileState.queued) return; + fileState.queued = true; + pending.push(compareFile(file, fileState, cwd, state)); + } + + for await (const event of source) { + const data = event.data; + if (event.type === "test:fail") { + // A suite reports its children's failure again as its own; the leaf + // test is the one with the message. + if (typeof data?.file !== "string" || data.details?.type === "suite") continue; + stateFor(data.file).failures.push(data); + continue; + } + if (event.type !== "test:summary") continue; + const file = data?.file; + // The run's own summary has no file; every file's has one. + if (typeof file !== "string") continue; + stateFor(file).summary = data; + queue(file); + // Yield results that are already in, so a long run reports as it goes. + while (pending.length > 0 && pending[0].settled) yield (await pending.shift().promise) + "\n"; + } + // A file Node could not load is reported as one failed test, without a + // summary of its own; it still ran, so it is compared like the rest. + for (const file of files.keys()) queue(file); + for (const entry of pending) yield (await entry.promise) + "\n"; + if (state.diverged) process.exitCode = 1; +} + +/** A comparison started for one file, with a flag its result can be checked + * against without blocking the event loop. */ +function compareFile(file, fileState, cwd, state) { + const shown = relative(cwd, file) || file; + const entry = { settled: false }; + entry.promise = withSlot(async () => { + try { + return await compareOne(file, shown, fileState, cwd, state); + } catch (error) { + state.diverged = true; + return `✖ ${shown}: ${error instanceof Error ? error.message : String(error)}`; + } + }).finally(() => { + entry.settled = true; + }); + return entry; +} + +/** A counting semaphore around the comparisons. */ +let active = 0; +const waiting = []; +async function withSlot(fn) { + while (active >= CONCURRENCY) await new Promise((resume) => waiting.push(resume)); + active++; + try { + return await fn(); + } finally { + active--; + waiting.shift()?.(); + } +} + +async function compareOne(file, shown, fileState, cwd, state) { + let first; + try { + first = await runLanes(file, { cwd }); + } catch (error) { + state.diverged = true; + if (error instanceof DualRunBuildError) + return `✖ ${shown}: scriptc could not build this file\n${indent(error.stderr)}`; + throw error; + } + const differences = compareLanes(first.node, first.native); + if (differences === null) return nodeResult(shown, fileState.summary, fileState.failures); + // The Node lane may be the side that varies: run it once more and compare + // the two Node runs before blaming the binary. + const again = await runNodeLane(file, { cwd }); + if (compareLanes(first.node, again) !== null) + return `ℹ ${shown}: the Node run differs between two runs (flaky), not compared`; + state.diverged = true; + return `✖ ${describeDifferences(shown, differences)}`; +} + +/** What Node's own run of the file reported: a line per file and a line per + * failed test, so a test that fails in both lanes is not hidden behind a + * passing comparison. A file Node could not load has failed tests but no + * summary of its own, so its line carries no counts. */ +function nodeResult(shown, summary, failures) { + const counts = summary?.counts ?? {}; + const parts = [`${counts.passed ?? 0} passed`]; + if (counts.failed) parts.push(`${counts.failed} failed`); + if (counts.skipped) parts.push(`${counts.skipped} skipped`); + if (counts.todo) parts.push(`${counts.todo} todo`); + const countsText = summary === null ? "" : ` (${parts.join(", ")})`; + const head = `${summary?.success ? "✔" : "✖"} ${shown}${countsText}`; + if (failures.length === 0) return head; + const lines = failures.map((failure) => { + const message = firstLine(failure.details?.error?.message); + const where = failure.line === undefined ? "" : ` (line ${failure.line})`; + return ` ✖ ${failure.name}: ${message}${where}`; + }); + return [head, ...lines].join("\n"); +} + +/** The part of an error message that fits on a report line: the message's + * first non-empty line, which names the failure ("Expected values to be + * strictly deep-equal:", say); the details below it are Node's own diff. */ +function firstLine(message) { + if (typeof message !== "string") return "failed"; + const text = + message + .split("\n") + .map((line) => line.trim()) + .find((line) => line !== "") ?? ""; + if (text === "") return "failed"; + return text.length > 200 ? `${text.slice(0, 197)}...` : text; +} + +function indent(text) { + return text + .trimEnd() + .split("\n") + .map((line) => ` ${line}`) + .join("\n"); +} diff --git a/packages/experimental/package.json b/packages/experimental/package.json index 0adfc73e9f..4d10043c34 100644 --- a/packages/experimental/package.json +++ b/packages/experimental/package.json @@ -17,6 +17,14 @@ "types": "./index.d.ts", "default": "./index.js" }, + "./dual-run": { + "types": "./dual-run.d.ts", + "default": "./dual-run.js" + }, + "./dual-run/reporter": { + "types": "./dual-run/reporter.d.ts", + "default": "./dual-run/reporter.js" + }, "./register": { "types": "./register.d.ts", "default": "./register.js" @@ -26,6 +34,11 @@ "files": [ "index.js", "index.d.ts", + "dual-run.js", + "dual-run.d.ts", + "dual-run-core.js", + "dual-run/reporter.js", + "dual-run/reporter.d.ts", "register.js", "register.d.ts", "refusals.json", diff --git a/scripts/ci-test-costs.json b/scripts/ci-test-costs.json index 8f93494bb9..ca47188513 100644 --- a/scripts/ci-test-costs.json +++ b/scripts/ci-test-costs.json @@ -651,6 +651,7 @@ "tests/harness/decl-boundary.test.ts": 128069, "tests/harness/dgram.test.ts": 5714, "tests/harness/diagnostics.test.ts": 97554, + "tests/harness/dual-run.test.ts": 9000, "tests/harness/dyncheck.test.ts": 64478, "tests/harness/error-accessor-reflection.test.ts": 2615, "tests/harness/error-cache-sweep.test.ts": 2947, @@ -1446,6 +1447,7 @@ "tests/harness/decl-boundary.test.ts": 582885, "tests/harness/dgram.test.ts": 17971, "tests/harness/diagnostics.test.ts": 82530, + "tests/harness/dual-run.test.ts": 13900, "tests/harness/dyncheck.test.ts": 142435, "tests/harness/error-accessor-reflection.test.ts": 3504, "tests/harness/errors.test.ts": 261554, diff --git a/tests/fixtures/dual-run/diverges.test.mts b/tests/fixtures/dual-run/diverges.test.mts new file mode 100644 index 0000000000..f9d91c85d7 --- /dev/null +++ b/tests/fixtures/dual-run/diverges.test.mts @@ -0,0 +1,11 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; + +// The executable path is the one value the two lanes cannot share: Node +// prints its own path, the binary prints its own. The comparison stops at +// the first line. +console.log(process.execPath); + +test("adds", () => { + assert.equal(1 + 1, 2); +}); diff --git a/tests/fixtures/dual-run/failing.test.mts b/tests/fixtures/dual-run/failing.test.mts new file mode 100644 index 0000000000..2e1f87e18b --- /dev/null +++ b/tests/fixtures/dual-run/failing.test.mts @@ -0,0 +1,10 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; + +test("passes", () => { + assert.equal(2 * 3, 6); +}); + +test("fails", () => { + assert.deepEqual({ a: 1 }, { a: 2 }); +}); diff --git a/tests/fixtures/dual-run/load-failure.mts b/tests/fixtures/dual-run/load-failure.mts new file mode 100644 index 0000000000..f6aeea51c1 --- /dev/null +++ b/tests/fixtures/dual-run/load-failure.mts @@ -0,0 +1,15 @@ +import { test } from "node:test"; + +// Node's test runner loads TypeScript by erasing types, so this file fails +// to load under `node --test`: an enum is not erasable. The oracle flags +// (--experimental-transform-types) and the compiler both accept it, so the +// reporter has a Node-side failure without a per-file summary to report, +// and still names the file and the failure. +enum Direction { + Up = "up", + Down = "down", +} + +test("moves one way", () => { + if (Direction.Up !== "up") throw new Error("bad enum"); +}); diff --git a/tests/fixtures/dual-run/passing.test.mts b/tests/fixtures/dual-run/passing.test.mts new file mode 100644 index 0000000000..82a2e1ff42 --- /dev/null +++ b/tests/fixtures/dual-run/passing.test.mts @@ -0,0 +1,12 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; + +console.log("passing fixture"); + +test("adds", () => { + assert.equal(1 + 1, 2); +}); + +test("concatenates", () => { + assert.equal("a" + "b", "ab"); +}); diff --git a/tests/fixtures/dual-run/refused.ts b/tests/fixtures/dual-run/refused.ts new file mode 100644 index 0000000000..2fd69825b2 --- /dev/null +++ b/tests/fixtures/dual-run/refused.ts @@ -0,0 +1,4 @@ +// WeakRef has no scriptc lowering yet: the build refuses with SC2020, which +// the program API reports as a DualRunBuildError. +const reference = new WeakRef({ value: 1 }); +console.log(reference.deref()?.value); diff --git a/tests/fixtures/dual-run/typeless.test.ts b/tests/fixtures/dual-run/typeless.test.ts new file mode 100644 index 0000000000..112740ace8 --- /dev/null +++ b/tests/fixtures/dual-run/typeless.test.ts @@ -0,0 +1,9 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; + +// A .ts file in a package that does not set "type": "module" makes Node warn +// about the module type, and the warning carries the process id, so two Node +// runs of this file never match. The lanes have to agree on what they see. +test("adds", () => { + assert.equal(2 + 2, 4); +}); diff --git a/tests/harness/dual-run.test.ts b/tests/harness/dual-run.test.ts new file mode 100644 index 0000000000..2997ff6c26 --- /dev/null +++ b/tests/harness/dual-run.test.ts @@ -0,0 +1,136 @@ +/* @scriptc/experimental/dual-run, end to end: the program API compares a + * node:test program under Node.js and as its compiled executable, and the + * reporter does the same for every file `node --test` ran. + * + * The fixtures are four small programs: one passes, one fails an + * assertion, one prints process.execPath (the one value the lanes cannot + * share), and one uses a type the compiler refuses. Every build goes + * through the scriptc CLI and its executable cache, with SCRIPTC_BIN + * pointing at the workspace's CLI entry (the published package ships a + * native binary instead). Both flavors build the fixtures the way a user + * does, without the sanitizer, so the suite costs about the same in each; + * the runtime these programs use runs sanitized in + * tests/harness/node-test.test.ts. */ +import { spawn } from "node:child_process"; +import { join } from "node:path"; +import { describe, expect, test } from "vitest"; +import { DualRunBuildError, dualRun } from "@scriptc/experimental/dual-run"; + +const repoRoot = join(import.meta.dirname, "../.."); +const fixturesDir = join(repoRoot, "tests/fixtures/dual-run"); +const cli = join(repoRoot, "packages/cli/dist/main.js"); +const reporter = join(repoRoot, "packages/experimental/dual-run/reporter.js"); + +/** The CLI's environment: the workspace entry replaces the installed + * `scriptc` binary, and the test cache the vitest config chose applies. */ +function cliEnv(env: NodeJS.ProcessEnv = {}): NodeJS.ProcessEnv { + return { ...process.env, SCRIPTC_BIN: cli, ...env }; +} + +describe("dualRun", () => { + test("a passing program matches its binary", async () => { + const result = await dualRun(join(fixturesDir, "passing.test.mts"), { + cwd: repoRoot, + env: cliEnv(), + }); + expect(result.equal).toBe(true); + expect(result.diff).toBe(""); + expect(result.node.exitCode).toBe(0); + expect(result.native.exitCode).toBe(0); + expect(result.native.stdout).toContain("✔ adds"); + }, 180_000); + + test("a failing assertion is part of the comparison", async () => { + const result = await dualRun(join(fixturesDir, "failing.test.mts"), { + cwd: repoRoot, + env: cliEnv(), + }); + expect(result.equal).toBe(true); + expect(result.node.exitCode).toBe(1); + expect(result.native.exitCode).toBe(1); + expect(result.native.stdout).toContain("ℹ fail 1"); + }, 180_000); + + test("Node's module-type warning is not a difference", async () => { + const result = await dualRun(join(fixturesDir, "typeless.test.ts"), { + cwd: repoRoot, + env: cliEnv(), + }); + expect(result.equal).toBe(true); + // The warning names the process, so it could never match the binary. + expect(result.node.stderr).toBe(""); + }, 180_000); + + test("a divergence is reported at the line it starts", async () => { + const result = await dualRun(join(fixturesDir, "diverges.test.mts"), { + cwd: repoRoot, + env: cliEnv(), + }); + expect(result.equal).toBe(false); + expect(result.diff).toContain("native stdout differs at line 1"); + // The executable paths themselves, one on each side of the diff. + expect(result.diff).toContain(` - ${process.execPath}`); + expect(result.diff).toContain(" + "); + }, 180_000); + + test("a program the compiler refuses rejects with the diagnostics", async () => { + const entry = join(fixturesDir, "refused.ts"); + const error = (await dualRun(entry, { cwd: repoRoot, env: cliEnv() }).then( + () => null, + (e: unknown) => e, + )) as DualRunBuildError | null; + expect(error).toBeInstanceOf(DualRunBuildError); + expect(error!.entry).toBe(entry); + expect(error!.stderr).toContain("SC2020"); + }, 180_000); +}); + +describe("dual-run reporter", () => { + test("reports every file Node ran", async () => { + const files = [ + "passing.test.mts", + "failing.test.mts", + "diverges.test.mts", + "load-failure.mts", + ].map((name) => join(fixturesDir, name)); + const run = await new Promise<{ stdout: string; stderr: string; exitCode: number }>( + (resolve, reject) => { + const child = spawn( + process.execPath, + ["--test", `--test-reporter=${reporter}`, "--test-reporter-destination=stdout", ...files], + { cwd: repoRoot, env: cliEnv(), stdio: ["ignore", "pipe", "pipe"] }, + ); + const out: Buffer[] = []; + const err: Buffer[] = []; + child.stdout.on("data", (c: Buffer) => out.push(c)); + child.stderr.on("data", (c: Buffer) => err.push(c)); + child.on("close", (code, signal) => { + if (signal) { + reject(new Error(`reporter run died to ${signal}\n${Buffer.concat(err)}`)); + return; + } + resolve({ + stdout: Buffer.concat(out).toString("utf8"), + stderr: Buffer.concat(err).toString("utf8"), + exitCode: code ?? 0, + }); + }); + }, + ); + const lines = run.stdout.split("\n"); + const lineFor = (name: string) => + lines.find((line) => line.includes(`tests/fixtures/dual-run/${name}`)); + expect(lineFor("passing.test.mts")).toMatch(/^✔ .*\(2 passed\)$/); + // The comparison agrees, and the test failure Node reported is still + // part of the report. + expect(lineFor("failing.test.mts")).toMatch(/^✖ .*\(1 passed, 1 failed\)$/); + expect(run.stdout).toContain("✖ fails: Expected values to be strictly deep-equal:"); + expect(lineFor("diverges.test.mts")).toMatch(/^✖ .*native stdout differs at line 1/); + // A file Node itself could not load still gets a line, with the failure + // Node reported for it; the comparison found the two lanes equal. + expect(lineFor("load-failure.mts")).toMatch(/^✖ .*load-failure\.mts$/); + expect(run.stdout).toMatch(/ ✖ .*load-failure\.mts: test failed \(line 1\)/); + expect(run.stderr).toBe(""); + expect(run.exitCode).toBe(1); + }, 180_000); +}); From c4e63e280bde2d19f0fb759ef13f6e30b5cc5552 Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 12 Nov 2026 00:53:26 -0600 Subject: [PATCH 2/2] Answer the review --- docs/content/docs/dual-run.mdx | 4 +- packages/experimental/dual-run-core.js | 10 +++ packages/experimental/dual-run.d.ts | 4 +- packages/experimental/dual-run/reporter.js | 15 +++- scripts/ci-test-costs.json | 4 +- .../dual-run/dual-run-in-test.test.mts | 14 +++ tests/fixtures/dual-run/helper-failure.mjs | 11 +++ .../fixtures/dual-run/imports-helper.test.mts | 4 + tests/harness/dual-run.test.ts | 85 +++++++++++++------ 9 files changed, 119 insertions(+), 32 deletions(-) create mode 100644 tests/fixtures/dual-run/dual-run-in-test.test.mts create mode 100644 tests/fixtures/dual-run/helper-failure.mjs create mode 100644 tests/fixtures/dual-run/imports-helper.test.mts diff --git a/docs/content/docs/dual-run.mdx b/docs/content/docs/dual-run.mdx index 54e4f9aeeb..ed11002a2d 100644 --- a/docs/content/docs/dual-run.mdx +++ b/docs/content/docs/dual-run.mdx @@ -34,7 +34,7 @@ $ node --test --test-reporter=@scriptc/experimental/dual-run/reporter --test-rep - A `✔` line means every test in the file behaves the same in both runs. - A `✖` line that names a test and shows a diff means the compiled binary's output differs from Node.js, and the diff starts at the line where it does. -- A `✖` line with test counts means Node.js reported a failed test in the file. The failing tests and their messages follow, so the report explains the exit code on its own. +- A `✖` line with test counts means Node.js reported a failed test in the file. The failing tests and their messages follow, so the report explains the exit code on its own. A test declared in a module the file imports counts toward the file Node.js ran, so its failure appears on that file's line and the imported module is not compared as a file of its own. - A `✖` line without counts is a file Node.js itself could not run, for example because its TypeScript loader rejects the file's syntax; the failure Node.js reported follows, and the file is still compared. - An `ℹ` line marks a file whose output differed between two Node.js runs. The reporter does not blame the binary for that, and the comparison does not fail the run. @@ -69,7 +69,7 @@ Both runs render a Node.js spec report, and the two reports are compared as text Everything else must match: test names, pass, fail, skip and todo results, assertion messages, the failing-tests section, and the program's own stdout and stderr. -Both lanes run with `TZ=UTC` and `LANG=C`, so dates and collation do not depend on the machine. The Node.js lane also runs with `--experimental-transform-types`, which a compiled program does not need, and with `--disallow-code-generation-from-strings`, the same refusal compiled programs apply to `eval` and `Function`. Node's warnings about the transform flag and about a `.ts` file in a package that does not set `"type": "module"` are turned off, because they carry content the binary never prints, the process id included. +Both lanes run with `TZ=UTC` and `LANG=C`, so dates and collation do not depend on the machine. They also run without `NODE_TEST_CONTEXT`, which `node --test` sets for each test file it starts and which would make the Node.js lane answer with binary test events instead of the spec report. The Node.js lane also runs with `--experimental-transform-types`, which a compiled program does not need, and with `--disallow-code-generation-from-strings`, the same refusal compiled programs apply to `eval` and `Function`. Node's warnings about the transform flag and about a `.ts` file in a package that does not set `"type": "module"` are turned off, because they carry content the binary never prints, the process id included. ## API diff --git a/packages/experimental/dual-run-core.js b/packages/experimental/dual-run-core.js index 28550a3851..c8b21b6324 100644 --- a/packages/experimental/dual-run-core.js +++ b/packages/experimental/dual-run-core.js @@ -108,11 +108,21 @@ function resolveScriptcBin({ cwd = process.cwd(), env = process.env } = {}) { ); } +/** Variables that would make a lane behave as a node:test child rather than + * as a plain `node ` run. Node's test runner sets NODE_TEST_CONTEXT for + * every test file it starts, and node:test then writes binary test events + * instead of the spec report; a compiled program never does that, so a lane + * that inherited the variable would differ for reasons the program does not + * control. `dualRun` is often called from inside a test, so both lanes drop + * it even when the caller names it. */ +const LANE_ENV_DROPPED = ["NODE_TEST_CONTEXT"]; + /** The merged environment both lanes run with. The fixed variables win over * the caller's, since a diff that depends on the machine's locale or time * zone would not be about the program. */ function laneEnv(env) { const merged = { ...process.env, ...env, ...BASE_ENV }; + for (const key of LANE_ENV_DROPPED) delete merged[key]; for (const key of Object.keys(merged)) if (merged[key] === undefined) delete merged[key]; return merged; } diff --git a/packages/experimental/dual-run.d.ts b/packages/experimental/dual-run.d.ts index 4d338baea8..581c9b4d00 100644 --- a/packages/experimental/dual-run.d.ts +++ b/packages/experimental/dual-run.d.ts @@ -12,7 +12,9 @@ export interface DualRunOptions { /** Written to both lanes' standard input, which is closed afterwards. */ stdin?: string | Uint8Array; /** Added to both lanes' environment. The environment always sets TZ=UTC - * and LANG=C. An entry left undefined removes the variable. */ + * and LANG=C, and never carries NODE_TEST_CONTEXT, which would make a + * node:test program write binary test events instead of its report. An + * entry left undefined removes the variable. */ env?: Record; /** Working directory of both lanes and of the build. Defaults to * process.cwd(). */ diff --git a/packages/experimental/dual-run/reporter.js b/packages/experimental/dual-run/reporter.js index 7d5089a9f5..b00167defc 100644 --- a/packages/experimental/dual-run/reporter.js +++ b/packages/experimental/dual-run/reporter.js @@ -31,6 +31,15 @@ import { * and each comparison is one cached build plus two short runs. */ const CONCURRENCY = 4; +/** The file Node ran that a result belongs to. A test declared in a module + * the entry imports reports that module as `file`, with `entryFile` naming + * the file Node started; keying by the entry keeps one line per file Node + * ran and keeps the failure with the file that ran it. A file Node could not + * load reports no `entryFile`, and its own path is the entry. */ +function entryFileOf(data) { + return typeof data.entryFile === "string" ? data.entryFile : data.file; +} + /** The report stream is whatever Node was told to use; the reporter only * yields text. */ export default async function* reporter(source) { @@ -62,13 +71,13 @@ export default async function* reporter(source) { // A suite reports its children's failure again as its own; the leaf // test is the one with the message. if (typeof data?.file !== "string" || data.details?.type === "suite") continue; - stateFor(data.file).failures.push(data); + stateFor(entryFileOf(data)).failures.push(data); continue; } if (event.type !== "test:summary") continue; - const file = data?.file; // The run's own summary has no file; every file's has one. - if (typeof file !== "string") continue; + if (typeof data?.file !== "string") continue; + const file = entryFileOf(data); stateFor(file).summary = data; queue(file); // Yield results that are already in, so a long run reports as it goes. diff --git a/scripts/ci-test-costs.json b/scripts/ci-test-costs.json index ca47188513..a45d8b8deb 100644 --- a/scripts/ci-test-costs.json +++ b/scripts/ci-test-costs.json @@ -651,7 +651,7 @@ "tests/harness/decl-boundary.test.ts": 128069, "tests/harness/dgram.test.ts": 5714, "tests/harness/diagnostics.test.ts": 97554, - "tests/harness/dual-run.test.ts": 9000, + "tests/harness/dual-run.test.ts": 13400, "tests/harness/dyncheck.test.ts": 64478, "tests/harness/error-accessor-reflection.test.ts": 2615, "tests/harness/error-cache-sweep.test.ts": 2947, @@ -1447,7 +1447,7 @@ "tests/harness/decl-boundary.test.ts": 582885, "tests/harness/dgram.test.ts": 17971, "tests/harness/diagnostics.test.ts": 82530, - "tests/harness/dual-run.test.ts": 13900, + "tests/harness/dual-run.test.ts": 18400, "tests/harness/dyncheck.test.ts": 142435, "tests/harness/error-accessor-reflection.test.ts": 3504, "tests/harness/errors.test.ts": 261554, diff --git a/tests/fixtures/dual-run/dual-run-in-test.test.mts b/tests/fixtures/dual-run/dual-run-in-test.test.mts new file mode 100644 index 0000000000..02766ce6fa --- /dev/null +++ b/tests/fixtures/dual-run/dual-run-in-test.test.mts @@ -0,0 +1,14 @@ +import { test } from "node:test"; +import { fileURLToPath } from "node:url"; +import { dualRun } from "@scriptc/experimental/dual-run"; + +// A node:test file that compares another file from inside the runner. The +// process the runner starts carries NODE_TEST_CONTEXT, which must not reach +// either lane: node:test would answer with binary test events instead of the +// spec report, and a compiled program never does that. +test("dualRun inside the runner compares the file", async () => { + const result = await dualRun(fileURLToPath(new URL("./passing.test.mts", import.meta.url)), { + cwd: process.cwd(), + }); + if (!result.equal) throw new Error(result.diff); +}); diff --git a/tests/fixtures/dual-run/helper-failure.mjs b/tests/fixtures/dual-run/helper-failure.mjs new file mode 100644 index 0000000000..363c44c344 --- /dev/null +++ b/tests/fixtures/dual-run/helper-failure.mjs @@ -0,0 +1,11 @@ +import { test } from "node:test"; + +// Declared in a module the entry imports. Node reports the failure with the +// module as `file` and the file it ran as `entryFile`, so the reporter must +// keep the failure on the entry's line instead of comparing this module as +// a file of its own. +test("helper fails", () => { + throw new Error("from the helper"); +}); + +test("helper passes", () => {}); diff --git a/tests/fixtures/dual-run/imports-helper.test.mts b/tests/fixtures/dual-run/imports-helper.test.mts new file mode 100644 index 0000000000..5000d1ab48 --- /dev/null +++ b/tests/fixtures/dual-run/imports-helper.test.mts @@ -0,0 +1,4 @@ +import { test } from "node:test"; +import "./helper-failure.mjs"; + +test("entry passes", () => {}); diff --git a/tests/harness/dual-run.test.ts b/tests/harness/dual-run.test.ts index 2997ff6c26..4613f79a5f 100644 --- a/tests/harness/dual-run.test.ts +++ b/tests/harness/dual-run.test.ts @@ -27,6 +27,39 @@ function cliEnv(env: NodeJS.ProcessEnv = {}): NodeJS.ProcessEnv { return { ...process.env, SCRIPTC_BIN: cli, ...env }; } +/** Runs files through `node --test`, optionally with the dual-run reporter, + * the way a CI job would, and returns what it printed and its exit code. */ +function runNodeTest( + files: string[], + { withReporter }: { withReporter: boolean }, +): Promise<{ stdout: string; stderr: string; exitCode: number }> { + const args = withReporter + ? ["--test", `--test-reporter=${reporter}`, "--test-reporter-destination=stdout", ...files] + : ["--test", ...files]; + return new Promise((resolve, reject) => { + const child = spawn(process.execPath, args, { + cwd: repoRoot, + env: cliEnv(), + stdio: ["ignore", "pipe", "pipe"], + }); + const out: Buffer[] = []; + const err: Buffer[] = []; + child.stdout.on("data", (c: Buffer) => out.push(c)); + child.stderr.on("data", (c: Buffer) => err.push(c)); + child.on("close", (code, signal) => { + if (signal) { + reject(new Error(`node --test died to ${signal}\n${Buffer.concat(err)}`)); + return; + } + resolve({ + stdout: Buffer.concat(out).toString("utf8"), + stderr: Buffer.concat(err).toString("utf8"), + exitCode: code ?? 0, + }); + }); + }); +} + describe("dualRun", () => { test("a passing program matches its binary", async () => { const result = await dualRun(join(fixturesDir, "passing.test.mts"), { @@ -83,6 +116,19 @@ describe("dualRun", () => { expect(error!.entry).toBe(entry); expect(error!.stderr).toContain("SC2020"); }, 180_000); + + test("a call from inside a node:test run compares the file", async () => { + // The runner starts its test files with NODE_TEST_CONTEXT set, where + // node:test answers with binary test events instead of the spec report; + // the lanes must not inherit it, or every call made from a test would + // report a divergence that is not the program's. + const run = await runNodeTest([join(fixturesDir, "dual-run-in-test.test.mts")], { + withReporter: false, + }); + expect(run.stderr).toBe(""); + expect(run.stdout).toContain("✔ dualRun inside the runner compares the file"); + expect(run.exitCode).toBe(0); + }, 180_000); }); describe("dual-run reporter", () => { @@ -93,30 +139,7 @@ describe("dual-run reporter", () => { "diverges.test.mts", "load-failure.mts", ].map((name) => join(fixturesDir, name)); - const run = await new Promise<{ stdout: string; stderr: string; exitCode: number }>( - (resolve, reject) => { - const child = spawn( - process.execPath, - ["--test", `--test-reporter=${reporter}`, "--test-reporter-destination=stdout", ...files], - { cwd: repoRoot, env: cliEnv(), stdio: ["ignore", "pipe", "pipe"] }, - ); - const out: Buffer[] = []; - const err: Buffer[] = []; - child.stdout.on("data", (c: Buffer) => out.push(c)); - child.stderr.on("data", (c: Buffer) => err.push(c)); - child.on("close", (code, signal) => { - if (signal) { - reject(new Error(`reporter run died to ${signal}\n${Buffer.concat(err)}`)); - return; - } - resolve({ - stdout: Buffer.concat(out).toString("utf8"), - stderr: Buffer.concat(err).toString("utf8"), - exitCode: code ?? 0, - }); - }); - }, - ); + const run = await runNodeTest(files, { withReporter: true }); const lines = run.stdout.split("\n"); const lineFor = (name: string) => lines.find((line) => line.includes(`tests/fixtures/dual-run/${name}`)); @@ -133,4 +156,18 @@ describe("dual-run reporter", () => { expect(run.stderr).toBe(""); expect(run.exitCode).toBe(1); }, 180_000); + + test("a failure declared in an imported module stays on the entry's line", async () => { + const entry = join(fixturesDir, "imports-helper.test.mts"); + const run = await runNodeTest([entry], { withReporter: true }); + // Node counts the imported module's tests in the entry it ran, and its + // failure names the module as the declaring file; the report keeps one + // line for the entry and does not compare the module as a file of its + // own. + expect(run.stdout).toMatch(/^✖ .*imports-helper\.test\.mts \(2 passed, 1 failed\)$/m); + expect(run.stdout).toContain("✖ helper fails: from the helper"); + expect(run.stdout).not.toContain("helper-failure.mjs"); + expect(run.stderr).toBe(""); + expect(run.exitCode).toBe(1); + }, 180_000); });