/** * The prefix runner: runs a set of `@tanstack/oracles` files on one version * of a bench library, either exploring (a campaign at a seed, with the run * multiplier) or replaying one found failure, and reads the result. * * The decisions are pure functions with laws in * `tests/oracle/prefix-run.oracle.property.test.ts`; `runOracles` is the wiring * (scratch folder, a vitest process, its reporter), with its integration run in * `tests/oracle/prefix-runner.oracle.property.test.ts`. */ import { createHash } from 'node:crypto' import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, symlinkSync, writeFileSync, } from 'node:fs' import { createRequire } from 'node:module' import { basename, dirname, join } from 'node:path' import { runCapture } from '../proc.ts' import type { Exploration, Failure, Replay, ReplayResult } from './score.ts' /** Every property explores this many times its declared runs. */ export const RUNS_MULTIPLIER = 50 // ---------- the scratch folder ---------- export interface LayoutPlan { /** Real folders, created in the scratch folder. */ dirs: Array /** Entries linked to the same path in the tree. */ links: Array /** Oracle files copied in. */ copies: Array } /** * The scratch folder for one tree: the folders on each oracle file's path are * real, the oracle files are copied, and every other entry of those folders * (and of the root) links to the tree, so no write lands inside it. * `listDir(dir)` names the tree's entries in `dir` (`` for the root). */ export function layoutPlan( oracleFiles: ReadonlyArray, listDir: (dir: string) => ReadonlyArray, ): LayoutPlan { const copies = [...new Set(oracleFiles)].sort() const dirs = new Set([``]) for (const f of copies) { const parts = f.split(`/`) for (let i = 1; i < parts.length; i++) dirs.add(parts.slice(0, i).join(`/`)) } const taken = new Set([...dirs, ...copies]) const links: Array = [] for (const d of dirs) for (const name of listDir(d)) { const p = d ? `${d}/${name}` : name if (!taken.has(p)) links.push(p) } return { dirs: [...dirs].filter(Boolean).sort(), links: links.sort(), copies } } // ---------- run records ---------- export interface ErrorRecord { name: string message: string expected?: string actual?: string cause?: ErrorRecord } export interface TestRecord { /** The full test name: ` > `. */ test: string state: `passed` | `failed` | `skipped` | `pending` errors: Array } export interface RunRecord { /** The time limit stopped the run. */ timedOut: boolean /** vitest ended without a report, and no time limit stopped it. */ crashed: boolean /** Test files that failed to load, and errors outside any test. */ loadErrors: Array tests: Array } const VIOLATION = `OracleViolation` const violationOf = (e: ErrorRecord): ErrorRecord | undefined => e.name === VIOLATION ? e : e.cause?.name === VIOLATION ? e.cause : undefined /** The reason a run couldn't run, or undefined when its result stands. */ function couldNotRun(r: RunRecord): string | undefined { if (r.timedOut) return `time limit` if (r.loadErrors.length) return `load failed: ${r.loadErrors.join(`; `)}` for (const t of r.tests) if (t.state === `failed` && !t.errors.some((e) => violationOf(e))) return `${t.test}: ${t.errors.map((e) => e.name).join(`, `) || `failed with no error`}` return undefined } const line = (text: string, prefix: string) => text .split(`\n`) .find((l) => l.startsWith(prefix)) ?.slice(prefix.length) const REPLAY = /^Replay: ORACLE_SEED=(-?\d+) ORACLE_PATH=(\S+) ORACLE_PROPERTY='[^']*' ORACLE_UNIT='([^']*)'/m /** The replay a failed campaign prints, or a rerun of the test by name. */ function replayOf(test: string, e: ErrorRecord, property: string): Replay { const m = REPLAY.exec(e.message) return m ? { property, unit: m[3]!, seed: Number(m[1]), path: m[2]! } : { property, unit: test.slice(property.length + ` > `.length) } } /** What an exploration found: its distinct law violations, or why it couldn't run. */ export function exploration(r: RunRecord): Exploration { const why = couldNotRun(r) if (why !== undefined) return { couldNotRun: why } const found = new Map() for (const t of r.tests) for (const e of t.errors) { const v = violationOf(e) if (!v) continue const property = v.message.split(` violated at checkpoint `)[0]! const history = line(v.message, `History: `) ?? `` // A failure found by several tests is one failure; any of their replays reruns it. found.set(JSON.stringify([property, history]), { property, history, expected: v.expected ?? ``, actual: v.actual ?? ``, replay: replayOf(t.test, e, property), }) } return { failures: [...found.values()] } } /** A replay's result: its selected test failed with a law violation, or passed. */ export function replayResult(r: RunRecord): ReplayResult { const why = couldNotRun(r) if (why !== undefined) return { couldNotRun: why } const ran = r.tests.filter( (t) => t.state === `passed` || t.state === `failed`, ) if (!ran.length) return { couldNotRun: `the replay selected no test` } return ran.some((t) => t.state === `failed`) ? `fail` : `pass` } // ---------- the environment ---------- export function exploreEnv(seed: number): { env: Record } { return { env: { ORACLE_SEED: String(seed), ORACLE_RUNS_MULTIPLIER: String(RUNS_MULTIPLIER), }, } } /** A replay: the framework's selection when the failure has a seed and path, and its test by name. */ export function replayEnv(r: Replay): { env: Record test: string } { return { env: r.seed === undefined ? {} : { ORACLE_SEED: String(r.seed), ORACLE_PATH: r.path!, ORACLE_PROPERTY: r.property, ORACLE_UNIT: r.unit, }, test: `${r.property} > ${r.unit}`, } } // ---------- the cache ---------- /** * The run-record cache's key of a job: the oracle files and their contents, * the runner's settings, the snapshot build its trees were made from (the * snapshot's seal, new with each build), the version of the job's tree (its * folder's name: a commit, or the snapshot) and what the job runs (its environment, which * holds the run multiplier, and its selected test). Never its id, which only * names it within one command. */ export function cacheKey( job: OracleJob, files: ReadonlyArray, settings: { timeoutSec: number }, snapshot: string, ): string { // The set of files: each path once, in path order. const byPath = new Map(files) const sorted = [...byPath.keys()] .sort() .map((path) => [path, byPath.get(path)]) return createHash(`sha256`) .update( JSON.stringify([ sorted, settings, snapshot, basename(job.tree), job.env, job.test, ]), ) .digest(`hex`) } /** A run stopped by the time limit, or whose vitest crashed, is not kept: a later run may finish. */ export const cacheable = (r: RunRecord): boolean => !r.timedOut && !r.crashed // ---------- the wiring ---------- const require = createRequire(import.meta.url) const packageDir = (name: string) => dirname(require.resolve(`${name}/package.json`)) const escape = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, `\\$&`) /** vitest's name filter for ` > `: it joins suite and test names with a space. */ const testPattern = (test: string) => { const [property, ...unit] = test.split(` > `) return `^${escape(property!)}(?: | > )${escape(unit.join(` > `))}$` } /** One run of the oracle files: a version, its environment, and a test to run alone (a replay). */ export interface OracleJob { id: string tree: string env: Record test?: string } export interface RunOraclesOptions { jobs: ReadonlyArray /** The oracle files' root, and the files under it, by repo-relative path. */ oracleRoot: string oracleFiles: ReadonlyArray /** Seconds one test may run. */ timeoutSec: number /** Where scratch folders go. */ scratchRoot: string } const TIMED_OUT = /Test timed out in \d+ms/ type ErrorLike = { name?: unknown message?: unknown expected?: unknown actual?: unknown cause?: ErrorLike } const fields = (e: ErrorLike) => ({ name: String(e.name ?? `Error`), message: String(e.message ?? ``), ...(e.expected === undefined ? {} : { expected: String(e.expected) }), ...(e.actual === undefined ? {} : { actual: String(e.actual) }), }) /** An error and its cause: a campaign's violation is the cause of fast-check's error. */ const errorRecord = (e: ErrorLike): ErrorRecord => ({ ...fields(e), ...(e.cause ? { cause: fields(e.cause) } : {}), }) /** A test module as the batch's reporter writes it: plain data from vitest's test modules. */ export interface ModuleData { moduleId: string project: string errors: ReadonlyArray<{ message?: unknown }> tests: ReadonlyArray<{ fullName: string state: string errors?: ReadonlyArray }> } /** Each job's record (by project name) from the batch's test modules. */ export function recordOf( modules: ReadonlyArray, unhandled: ReadonlyArray<{ message?: unknown }>, ): Record> { const byProject: Record> = {} const of = (name: string) => (byProject[name] ??= { tests: [], loadErrors: [] }) for (const m of modules) { const p = of(m.project) for (const e of m.errors) p.loadErrors.push(`${m.moduleId}: ${String(e.message)}`) for (const t of m.tests) p.tests.push({ test: t.fullName, state: t.state as TestRecord[`state`], errors: (t.errors ?? []).map(errorRecord), }) } // An error outside any test belongs to no one job: every job that ran couldn't run. for (const e of unhandled) for (const p of Object.values(byProject)) p.loadErrors.push(`unhandled: ${String(e.message)}`) return byProject } // The batch's vitest config. Its reporter writes the test modules as plain data when the run ends, so a batch stopped // at its limit has no records file. `config` holds the projects; `out`, the records file. const configText = ( projects: unknown, out: string, ) => `import { writeFileSync } from 'node:fs' const err = (e) => e && { name: e.name, message: e.message, expected: e.expected, actual: e.actual, cause: err(e.cause) } export default { test: { projects: ${JSON.stringify(projects)}, reporters: [{ onTestRunEnd: (modules, unhandled) => writeFileSync(${JSON.stringify(out)}, JSON.stringify({ modules: modules.map((m) => ({ moduleId: m.moduleId, project: m.project.name, errors: m.errors().map((e) => ({ message: e.message })), tests: [...m.children.allTests()].map((t) => ({ fullName: t.fullName, state: t.result().state, errors: (t.result().errors ?? []).map(err) })), })), unhandled: unhandled.map((e) => ({ message: e.message })), })), }], }, } ` /** * Runs every job in one vitest process of its own, one project per job, each * in its own scratch folder (see `layoutPlan`), and returns each job's run * record. At the batch's limit its whole process group is stopped. */ export async function runOracles( o: RunOraclesOptions, ): Promise> { mkdirSync(o.scratchRoot, { recursive: true }) const batch = mkdtempSync(join(o.scratchRoot, `batch-`)) try { const projects = o.jobs.map((job, i) => { const dir = join(batch, String(i)) const plan = layoutPlan(o.oracleFiles, (d) => existsSync(join(job.tree, d)) ? readdirSync(join(job.tree, d)) : [], ) // The job's folder, then the real folders on the oracle files' paths (sorted: each parent first). for (const d of [``, ...plan.dirs]) mkdirSync(join(dir, d)) for (const l of plan.links) symlinkSync(join(job.tree, l), join(dir, l)) for (const c of plan.copies) copyFileSync(join(o.oracleRoot, c), join(dir, c)) return { resolve: { alias: { '@tanstack/oracles': packageDir(`@tanstack/oracles`), 'fast-check': packageDir(`fast-check`), }, }, test: { name: job.id, root: dir, include: plan.copies, env: job.env, testTimeout: o.timeoutSec * 1000, ...(job.test ? { testNamePattern: testPattern(job.test) } : {}), }, } }) const config = join(batch, `vitest.config.mjs`) const out = join(batch, `records.json`) writeFileSync(config, configText(projects, out)) // The whole batch may take each job's limit and one more; past that, every job without a record timed out. // vitest keeps its results cache in its working directory: the batch's folder, so nothing lands where the command runs. const ran = await runCapture( process.execPath, [join(packageDir(`vitest`), `vitest.mjs`), `run`, `--config`, config], { cwd: batch, timeoutMs: o.timeoutSec * 1000 * (o.jobs.length + 1), }, ) const data = existsSync(out) ? (JSON.parse(readFileSync(out, `utf8`)) as { modules: Array unhandled: Array<{ message?: unknown }> }) : undefined const records = data ? recordOf(data.modules, data.unhandled) : {} return new Map( o.jobs.map((job) => { const r = records[job.id] const timedOut = r ? r.tests.some((t) => t.errors.some((e) => TIMED_OUT.test(e.message))) : ran.timedOut return [ job.id, { timedOut, crashed: !r && !timedOut, loadErrors: r ? r.loadErrors : timedOut ? [] : [ `no record: vitest ended without one for this job (exit ${ran.code})`, ], tests: r ? r.tests : [], }, ] }), ) } finally { rmSync(batch, { recursive: true }) } }