From 9865b62cb18ce067259868b1fed8a917e4d8efbf Mon Sep 17 00:00:00 2001 From: Kyle Mathews Date: Tue, 1 Dec 2026 21:32:16 -0700 Subject: [PATCH 01/51] fix(oracle-gaps): every read is a daemon input Rebased onto main (bbd961d6, #314's SQLite evidence store). The 43 commits of the branch are squashed into this one commit. The pre-rebase history is kept at fix/daemon-every-read 6bc03d4b. - Drops the JSONL evidence store, its ORACLE_GAPS_TEST_STRING_LIMIT knob, the storeLimit field and its constructed history, and the store-join and store-read mutants. #314's SQLite store replaces them. - storedInputs reads main's storedUnits. - The drawn fields inputRead, keepStamp, inputSteps, childWrite and childEnvironment are appended after main's faults. Fixed histories that main added take their neutral values. history-fingerprint.json and constructed-order.json gain only appended lines. - pr.yml keeps main's changes gating; the fixed-seed and random shards are 5, the determinism shards are 8. Co-authored-by: Isaac --- .changeset/gap-cli-daemon-every-read.md | 11 + .github/workflows/pr.yml | 18 +- README.md | 82 ++-- .../oracles/oracle-gaps/capture-setup.mjs | 143 +++---- packages/oracles/oracle-gaps/check.mjs | 298 +++++++++++++- packages/oracles/oracle-gaps/child-writes.mjs | 19 + .../oracle-gaps/constructed-order.json | 15 +- packages/oracles/oracle-gaps/daemon.mjs | 27 +- .../oracle-gaps/gap-report-model-oracle.mjs | 385 +++++++++++++++++- .../gap-report-oracle.property.test.mjs | 325 ++++++++++++++- ...gap-report-static-oracle.property.test.mjs | 29 +- .../oracle-gaps/history-fingerprint.json | 14 +- packages/oracles/oracle-gaps/inputs.mjs | 236 +++++++++++ packages/oracles/scripts/e2e-shards.mjs | 41 ++ packages/oracles/scripts/pr-shards.mjs | 39 ++ 15 files changed, 1512 insertions(+), 170 deletions(-) create mode 100644 .changeset/gap-cli-daemon-every-read.md create mode 100644 packages/oracles/oracle-gaps/child-writes.mjs create mode 100644 packages/oracles/oracle-gaps/inputs.mjs diff --git a/.changeset/gap-cli-daemon-every-read.md b/.changeset/gap-cli-daemon-every-read.md new file mode 100644 index 00000000..0bb98f78 --- /dev/null +++ b/.changeset/gap-cli-daemon-every-read.md @@ -0,0 +1,11 @@ +--- +'@tanstack/oracles': patch +--- + +A check through `--daemon` now treats every read as an input of the runs that made it, so after any of these changes it reports what a cold run reports. Before, the daemon reused a run that read the old input. The new inputs are a file that a test reads through `fs` outside the package or under `node_modules`, or through `createReadStream`; a directory that a test lists (`readdir`, `opendir`, and their sync and `fs/promises` forms), by its entries; an environment variable that a test reads (or the set of variable names, when a test lists them); and a file or variable that Vitest, Vite, or the config reads in the CLI's process, while it loads or in a hook of any plugin, Vite's own included, such as the `tsconfig.json` that Vite's esbuild plugin reads or a sidecar file that a plugin writes into the code it transforms. + +The daemon now runs each check in the environment of the CLI that asked for it. A check from another environment, or after a file that Vitest, the config, or a plugin read or wrote has changed, starts a new daemon. Because Vitest and Vite read every environment variable while they start, any change to the environment runs every unit again, as a cold run does. + +Each check now hashes every file input from its content, so an edit that keeps a file's size and modification time, as `cp -p`, `rsync -t`, or `touch -r` leave it, is no longer missed. + +A file that a test, or a Node process it started at any depth, wrote before the test read it is the test's own output and no input, so a test whose child writes a temporary file is reused on an unchanged check. diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index 345e10c8..dfa4da58 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -149,7 +149,7 @@ jobs: env: SHARD: ${{ matrix.shard }} test-oracle-gaps-end-to-end: - name: Gap report end-to-end oracle (fixed seed, ${{ matrix.shard }}/4) + name: Gap report end-to-end oracle (fixed seed, ${{ matrix.shard }}/5) # Gated: runs when gaps changed (scripts/classify-changes.sh). needs: changes if: needs.changes.outputs.gaps == 'true' @@ -157,7 +157,7 @@ jobs: strategy: fail-fast: false matrix: - shard: [1, 2, 3, 4] + shard: [1, 2, 3, 4, 5] steps: - name: Checkout uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 @@ -165,7 +165,7 @@ jobs: persist-credentials: false - name: Setup Tools uses: tanstack/config/.github/setup@e4b48f16568324f76f467aa4c2aac2f05db632c3 - # The end-to-end oracle's fixed-seed units, in four shards. Its random + # The end-to-end oracle's fixed-seed units, in five shards. Its random # units and determinism units run in their own jobs, and its # calibrations run locally. - run: pnpm exec vitest --run --config oracle-gaps/vitest.config.mjs gap-report-oracle -t "$(node scripts/pr-shards.mjs pattern oracle-gaps-fixed-seed "$SHARD")" @@ -173,7 +173,7 @@ jobs: env: SHARD: ${{ matrix.shard }} test-oracle-gaps-random: - name: Gap report end-to-end oracle (random seed, ${{ matrix.shard }}/4) + name: Gap report end-to-end oracle (random seed, ${{ matrix.shard }}/5) # Gated: runs when gaps changed (scripts/classify-changes.sh). needs: changes if: needs.changes.outputs.gaps == 'true' @@ -184,7 +184,7 @@ jobs: strategy: fail-fast: false matrix: - shard: [1, 2, 3, 4] + shard: [1, 2, 3, 4, 5] steps: - name: Checkout uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 @@ -192,7 +192,7 @@ jobs: persist-credentials: false - name: Setup Tools uses: tanstack/config/.github/setup@e4b48f16568324f76f467aa4c2aac2f05db632c3 - # The end-to-end oracle's random units, in four weighted shards. Each run + # The end-to-end oracle's random units, in five weighted shards (the fifth holds the daemon-input units). Each run # draws a fresh campaign seed (the ORACLE_SEED line in the log). A failing # unit prints its Replay line and its history, cut at 2,000 characters # (#81), and does not shrink (GAP_E2E_SHRINKS=0; the maintainer's decision @@ -208,7 +208,7 @@ jobs: SHARD: ${{ matrix.shard }} GAP_E2E_SHRINKS: 0 test-oracle-gaps-determinism: - name: Gap report end-to-end oracle (determinism, ${{ matrix.shard }}/7) + name: Gap report end-to-end oracle (determinism, ${{ matrix.shard }}/8) # Gated: runs when gaps changed (scripts/classify-changes.sh). needs: changes if: needs.changes.outputs.gaps == 'true' @@ -218,7 +218,7 @@ jobs: strategy: fail-fast: false matrix: - shard: [1, 2, 3, 4, 5, 6, 7] + shard: [1, 2, 3, 4, 5, 6, 7, 8] steps: - name: Checkout uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 @@ -226,7 +226,7 @@ jobs: persist-credentials: false - name: Setup Tools uses: tanstack/config/.github/setup@e4b48f16568324f76f467aa4c2aac2f05db632c3 - # The end-to-end oracle's determinism units, in seven shards, the witness + # The end-to-end oracle's determinism units, in eight shards (the eighth holds the daemon-input units), the witness # module's two halves among them (the maintainer's decision "#90 job # stays blocking", 2026-11-16). Each unit runs a history twice and # compares the results and fixed lines; heartbeats are checked for shape. diff --git a/README.md b/README.md index f2b164b3..11f35185 100644 --- a/README.md +++ b/README.md @@ -243,39 +243,55 @@ runs cold` and runs the check in its own process, which reports what the run's output directory, and serves the next check. On Windows, which has no process groups, the run is not supervised. - A check through the daemon reuses a run while its inputs are unchanged: - the modules the run loaded, and the files in the package that its tests - read through `fs` (`readFileSync`, `readFile`, `existsSync`, `statSync`, - and `fs/promises` `readFile` and `stat`), each by the content that the - run read. A run that an edit overlapped, because a file changed after the - run read it, is not reused. A directory that a test stats or tests for is - an input as a directory, not by its content. - - Two kinds of input are not tracked yet. A Vite plugin whose output depends - on anything but a module's text, such as a sidecar file that it reads, can - make the daemon serve a run that read the plugin's old output. And the - daemon's environment is fixed when it starts, so an environment variable - that a later check sets does not reach the daemon's runs. After such a - change, run the check cold (without `--daemon`), or stop the daemon with - `oracle-gaps --stop-daemon --package `. The maintainer decided on - 2026-11-13 that the daemon tracks both and restarts when they change; a - later release does that. - - These reads are no input, so an edit to the file alone does not rerun the - tests that read it: a read outside the package or under `node_modules`; a - read from a worker thread or child process that the test starts; and a - read through any `fs` or `fs/promises` function other than the six above, - or through one of those six given a file descriptor. That catch-all - includes, for example, `readdir`, `opendir`, `glob`, `globSync`, - `createReadStream`, `realpath`, `lstat`, `access`, `open`, `read`, - `readSync`, `readv`, `fstat`, `fstatSync`, `copyFile`, `copyFileSync`, `cp`, - `cpSync`, `openAsBlob`, `statfs`, `readlink`, the callback `stat`, - `exists`, `watch`, and `watchFile`, and the `fs/promises` `readdir`, - `opendir`, `glob`, `lstat`, `realpath`, `readlink`, `access`, `open`, - `copyFile`, `cp`, `statfs`, and `watch`. Run the check cold (without - `--daemon`) after an edit to a file read that way. A later release records - all of them except `watch` and `watchFile`, which wait for future changes - and stay no input (maintainer decision, 2026-11-13, with `watchFile` in the + A check through the daemon reuses a run while its inputs are unchanged. + Every read is an input (maintainer decision, 2026-11-16): the modules the + run loaded; the files its tests read through `fs` on any path, inside the + package or outside it, `node_modules` included (`readFileSync`, + `readFile`, `createReadStream`, `existsSync`, `statSync`, and + `fs/promises` `readFile` and `stat`), each by the content that the run + read; the directories its tests list (`readdir`, `readdirSync`, `opendir`, + `opendirSync`, and `fs/promises` `readdir` and `opendir`), each by its + entries' names and kinds; the environment variables its tests read, by + value, or all of them when a test lists them; and what Vitest, Vite, and + the config read in the CLI's process, while Vitest loads and the contexts + warm, and in each hook of every plugin, Vite's own (such as the + `tsconfig.json` that its esbuild plugin reads) and the config's alike. A + file that a reader wrote earlier in the check, before it read it or tested + whether it exists, is its own output and no input (maintainer decision, + 2026-11-17). For a test, that includes a file that a Node process it + started wrote, at any depth: each such process preloads the runner's + write log through `NODE_OPTIONS` (maintainer decision, 2026-11-19). A + child started with an environment that drops `NODE_OPTIONS`, or a writer + that is not Node, is not seen, so its file stays an input. A file the + session wrote that is edited by hand afterwards is seen. Each check hashes + every file input from its content, so an edit that keeps a file's size and + modification time (`cp -p`, `rsync -t`, `touch -r`) is seen. A run that an + edit overlapped, because a file changed after the run read it, is not + reused. A directory that a test stats or tests for is an input as a + directory, not by its content. + + The daemon runs every check in the environment that the CLI asking for it + has. While a context warms, Vitest and Vite read every environment + variable by value, so a check from an environment that differs in any + variable, even one no test reads (`OLDPWD`, `SHLVL`, a terminal's session + id), starts a new daemon and runs every unit again, as a cold run does. + So does a check after a file that Vitest, the config, or a plugin read or + wrote has changed. + + These reads are no input yet, so an edit to the file alone does not rerun + the tests that read it: a read from a worker thread or child process that + the test starts (#143); a read through a file descriptor, after `open`, + `openSync`, or the `fs/promises` `open` (#141); a link's target, or the + rest of the stat family, `lstat`, `readlink`, `realpath`, `access`, the + callback `stat`, and `exists` (#142); `glob`, `globSync`, `copyFile`, + `copyFileSync`, `cp`, `cpSync`, `openAsBlob`, `statfs`, and the + `fs/promises` `glob`, `copyFile`, `cp`, and `statfs` (#152); the + module-level reads of a test file whose tests are all skipped (#153); and + the earlier content of a file that a test appends to, partly writes, or + fails to write, then reads (#154). Run the check cold (without `--daemon`) + after an edit to a file read that way. A later release records all of + them except `watch` and `watchFile`, which wait for future changes and + stay no input (maintainer decision, 2026-11-13, with `watchFile` in the family of `watch`). - `packages/eslint-plugin-oracles` (`@tanstack/eslint-plugin-oracles`): the diff --git a/packages/oracles/oracle-gaps/capture-setup.mjs b/packages/oracles/oracle-gaps/capture-setup.mjs index 72e61ff8..9d2a4ecc 100644 --- a/packages/oracles/oracle-gaps/capture-setup.mjs +++ b/packages/oracles/oracle-gaps/capture-setup.mjs @@ -24,12 +24,14 @@ // In a mutant run, fast-check stops a property at its first failure instead // of shrinking it: a kill needs one failing history, not the smallest one. import { createHash } from 'node:crypto' -import fs, { appendFileSync, readFileSync } from 'node:fs' +import { appendFileSync, readFileSync } from 'node:fs' import { createRequire, syncBuiltinESMExports } from 'node:module' -import { dirname, isAbsolute, join, resolve as resolvePath } from 'node:path' -import { fileURLToPath } from 'node:url' +import { dirname, isAbsolute, join } from 'node:path' +import { fileURLToPath, pathToFileURL } from 'node:url' +import { threadId } from 'node:worker_threads' import { afterAll, beforeEach, chai, expect, inject, vi } from 'vitest' -import { posix, writeWhole } from './paths.mjs' +import { inputHash, keepProperties, watchReads } from './inputs.mjs' +import { writeWhole } from './paths.mjs' const run = inject(`oracleGaps`) ?? @@ -68,14 +70,7 @@ const realUse = real.use // A wrapper keeps every own property of the function it wraps, such as // `util.promisify.custom`, so `util.promisify(setTimeout)` still resolves -// with its value under the capture (law 3: a test that passes alone passes -// under the CLI). -function keepProperties(from, to) { - for (const key of Reflect.ownKeys(from)) - if (key !== `prototype`) - Object.defineProperty(to, key, Object.getOwnPropertyDescriptor(from, key)) - return to -} +// with its value under the capture (inputs.mjs, keepProperties). // The timers that code in this worker has pending, counted where they are // made, each with when it is next due: Node's resource list does not @@ -274,70 +269,62 @@ function appendClosingRow(row) { writeWhole(`${hold}.${marker}`, ``) appendFileSync(state.capture, row.slice(half)) } -// The files this copy reads through fs inside the package: by a sync, a -// promise, or a callback read, or a check of whether a file exists or what -// it is. The daemon stores the run under them as it does the modules the -// copy evaluated (the closing row's `loaded`), so an edit of only such a -// file runs it again, as a cold run sees the edit (law 9). Reads under -// node_modules and of the runner's own files are left out. Each path keeps -// its hash from the copy's first read of it, taken as the runner hashes an -// input (check.mjs, fileHashes), so the run is stored under the text it -// read and not under an edit that lands later in the run (review of #55, -// F1). +// What this copy reads: each file through fs, on any path, node_modules +// included, by a sync, a promise, or a callback read, or a check of whether +// a file exists or what it is; and each environment variable, or the set of +// names when the copy lists them (inputs.mjs). Every read is a daemon input +// (maintainer decision, 2026-11-16): the daemon stores the run under them as +// it does the modules the copy evaluated (the closing row's `loaded`), so an +// edit of only such an input runs it again, as a cold run sees the edit +// (law 9). A file keeps its hash from the copy's first read of it, so the +// run is stored under the text it read and not under an edit that lands +// later in the run (review of #55, F1). A variable's hash is the runner's, +// from the environment it gives the check (check.mjs, servedHash). A file +// that the copy, or a process it started at any depth, wrote before the copy +// read it is its own output, no input, whether the copy reads its text or +// tests whether it exists (`stat:`). globalThis.__oracleGapsReads = new Map() -if (!globalThis.__oracleGapsReading) { - globalThis.__oracleGapsReading = true - // A read's key follows the gap CLI's path rule (paths.mjs, copied beside - // this file with it). The file system gets the native path. - const root = `${posix(process.cwd()).replace(/\/+$/, ``)}/` - const { readFileSync: readNow, statSync: statNow } = fs - const hashNow = (path) => { - try { - return statNow(path).isFile() - ? createHash(`sha1`).update(readNow(path)).digest(`hex`) - : `not a file` - } catch { - return `missing` - } - } - const record = (target) => { - let path - try { - if (target instanceof URL) path = fileURLToPath(target) - else if (typeof target === `string`) path = resolvePath(target) - else if (Buffer.isBuffer(target)) path = resolvePath(target.toString()) - } catch { - return - } - if (path === undefined) return - const key = posix(path) - const reads = globalThis.__oracleGapsReads - if ( - key.startsWith(root) && - !key.includes(`/node_modules/`) && - !key.includes(`/.oracle-gaps`) && - !reads.has(key) - ) - reads.set(key, hashNow(path)) +const wrote = new Set() +// The child processes' writes: every Node process a test starts preloads +// child-writes.mjs, which each of its own children inherits through +// NODE_OPTIONS, and appends the key of each file it writes to this copy's +// log, in the session directory beside this file. +// The session directory, from this file's path. Not `new URL(, +// import.meta.url)`: a client-transform environment (jsdom) rewrites that +// form to a URL of Vite's dev server. +const home = dirname(fileURLToPath(import.meta.url)) +const childLog = join( + home, + `child-writes-${process.pid}-${threadId}-${(globalThis.__oracleGapsCopies = (globalThis.__oracleGapsCopies ?? 0) + 1)}.log`, +) +let childRead = 0 +/** Whether the copy or a process it started wrote the file `key` names. */ +function ownOutput(key) { + const file = key.replace(/^stat:/, `fs:`) + if (wrote.has(file)) return true + let text + try { + text = globalThis.__oracleGapsOriginalFs.readFileSync(childLog, `utf8`) + } catch { + return false } - // A wrapper keeps the function's own properties (its name and length, - // which code that dispatches on arity reads), so a test that passes alone - // passes under the capture (law 3; review of #55). - for (const [owner, names] of [ - [fs, [`readFileSync`, `readFile`, `existsSync`, `statSync`]], - [fs.promises, [`readFile`, `stat`]], - ]) - for (const name of names) { - const original = owner[name] - owner[name] = keepProperties(original, function (target, ...rest) { - record(target) - return original.call(this, target, ...rest) - }) - } - // An ES module's `import { readFileSync } from 'node:fs'` (and from - // 'node:fs/promises') reads these from now on. - syncBuiltinESMExports() + for (const line of text.slice(childRead).split(`\n`)) + if (line !== ``) wrote.add(line) + childRead = text.length + return wrote.has(file) +} +watchReads((key, write) => { + const reads = globalThis.__oracleGapsReads + if (write) wrote.add(key) + else if (!reads.has(key) && !wrote.has(key) && !ownOutput(key)) + reads.set(key, key.startsWith(`env:`) ? null : inputHash(key)) +}) +if (!globalThis.__oracleGapsChildren) { + globalThis.__oracleGapsChildren = true + process.env.NODE_OPTIONS = + `${process.env.NODE_OPTIONS ?? ``} --import=${pathToFileURL(join(home, `child-writes.mjs`)).href}`.trim() } +process.env.ORACLE_GAPS_CHILD_WRITES = childLog // A test's own writes to the process's stdout and stderr (a debugging // `process.stdout.write`) go to the run's test-output.log, beside its // capture, not to the CLI's streams, whose every line is a line of the @@ -1167,13 +1154,9 @@ afterAll(() => { // The hash of each file the copy read, from its first read, under its own // key (`fs:`): a test's read of a file is another input than the // module that its context serves from that file, which can differ from - // the file's text (fourth review of #55, F-A2). - const readAt = Object.fromEntries( - [...globalThis.__oracleGapsReads].map(([path, hash]) => [ - `fs:${path}`, - hash, - ]), - ) + // the file's text (fourth review of #55, F-A2). A variable it read has no + // hash here (`env:`, null). + const readAt = Object.fromEntries(globalThis.__oracleGapsReads) appendClosingRow( `${JSON.stringify({ file: thisFile, closed: true, at: realNow(), loaded, readAt, ...(skippedCopy ? { skipped: true } : {}) })}\n`, ) diff --git a/packages/oracles/oracle-gaps/check.mjs b/packages/oracles/oracle-gaps/check.mjs index da4c39a3..b97ef020 100644 --- a/packages/oracles/oracle-gaps/check.mjs +++ b/packages/oracles/oracle-gaps/check.mjs @@ -9,16 +9,21 @@ // units, the ownership, and the options. A cold run computes every unit. The // daemon keeps each unit in its evidence store with the hash of every module // the run imported, as Vitest reports them, and of what was served for each -// instrumented or patched source; a stored unit is reused only while every -// one of those hashes is unchanged. So a check through the daemon reports -// what a cold run reports (the CLI oracle's law 9). Not covered: a file a -// test reads through `fs`, an environment variable other than the seed, and -// a new file that changes how an unchanged import resolves. +// instrumented or patched source, and of every other read the run made: a +// file its tests read through `fs` on any path, a variable they read, and +// what the config and its plugins read in this process (inputs.mjs; every +// read is a daemon input, maintainer decision, 2026-11-16). A stored unit is +// reused only while every one of those hashes is unchanged. So a check +// through the daemon reports what a cold run reports (the CLI oracle's law +// 9). Not covered: a read through another fs API than those inputs.mjs +// watches, one from a worker thread or a child process that a test starts, +// and a new file that changes how an unchanged import resolves. // // A unit's identity also carries the global inputs: this CLI's own files, // the harness, the Vite config and the files it loads, the package's // manifest and the lockfile, the Node version, and the options that change a // run (the seed, the test timeout, and bail). +import { AsyncLocalStorage } from 'node:async_hooks' import { spawn, spawnSync } from 'node:child_process' import { createHash } from 'node:crypto' import { @@ -76,6 +81,7 @@ import { specifierOf, } from './paths.mjs' import { stateDirOf } from './evidence.mjs' +import { envHash, inputHash, watchReads } from './inputs.mjs' import { baselineOf, blockedOr, @@ -155,6 +161,8 @@ const ownFiles = [ `stream.mjs`, `authored.mjs`, `capture-setup.mjs`, + `inputs.mjs`, + `child-writes.mjs`, `paths.mjs`, `evidence.mjs`, `daemon.mjs`, @@ -208,10 +216,55 @@ class KeepOrder { } } -/** Hashes of files by content, memoized by size and modification time. */ +/** + * Every plugin of a resolved config, Vite's and Vitest's own as well as the + * config's, with each hook run under `reading` (openSession), so what a hook + * reads is a session input: the tsconfig.json that Vite's esbuild plugin + * reads is an input as a sidecar of the config's own plugin is (review of + * #133, F1). A `load` or `transform` hook names the module it serves. The + * runner's own plugin is left as it is. A plugin is wrapped once; a hook is + * a function or an object with a `handler`, as Vite takes it. + */ +const hooked = new WeakSet() +function pluginHooks(plugins, reading) { + for (const option of plugins) { + if (option.name === `oracle-gaps-schemata` || hooked.has(option)) continue + hooked.add(option) + hookPlugin(option, reading) + } +} +function hookPlugin(option, reading) { + for (const [name, hook] of Object.entries(option)) { + const handler = typeof hook === `function` ? hook : hook?.handler + if (typeof handler !== `function`) continue + const at = { load: 0, transform: 1 }[name] + const watched = function (...args) { + const id = at === undefined ? undefined : args[at] + return reading.run( + { + hook: true, + module: + typeof id === `string` + ? `fs:${posix(id.split(`?`)[0])}` + : undefined, + }, + () => handler.apply(this, args), + ) + } + option[name] = + typeof hook === `function` ? watched : { ...hook, handler: watched } + } +} + +/** + * Hashes of files by content, memoized by size and modification time for + * one check (`forget`, which each check calls first): an edit between two + * checks that keeps a file's size and modification time, as `cp -p` leaves + * it, is still seen (D10; the TLA model's weakened-stamp run). + */ function fileHashes() { const memo = new Map() - return (path) => { + const hashOf = (path) => { let stat try { stat = statSync(path) @@ -234,6 +287,8 @@ function fileHashes() { memo.set(path, { stamp, hash }) return hash } + hashOf.forget = () => memo.clear() + return hashOf } /** The lockfile that pins the package's dependencies, if any. */ @@ -434,11 +489,77 @@ export async function openSession(pkg, pause = async () => {}) { `the TypeScript this CLI depends on (${ts.version}) has no compiler API`, `Reinstall @tanstack/oracles, which depends on TypeScript 5.`, ) + // What Vitest, the config, and the config's own plugins read in this + // process (`reading`): every plugin input is a daemon input (maintainer + // decision, 2026-11-16, "All of them"). What Vitest and Vite read while + // Vitest loads and while a context warms (`warmReads`, some hundred files + // and variables) is a global input of every unit (globalKey). What a hook + // of the config's own plugins reads (`hookReads`, pluginHooks), at any + // time, is an input of every unit that settles after it, with its hash + // from that read (settleIn). A daemon whose session read a file that has + // changed since is replaced (inputsChanged, daemon.mjs), since a plugin or + // a module may keep what it read. A load or transform hook's read of the + // module it serves is that module's own text, the module's input already. + // A file that the session wrote earlier in the check before it read it, + // such as the config Vite bundles into a temporary file, is the session's + // own output (maintainer decision, 2026-11-17, "Own writes aren't + // inputs": the same process, earlier in the check). Each check starts + // with no write (`wrote`), and a file the session wrote must still hold + // what it wrote at the next check (`written`, inputsChanged), since a + // hand edit of it is no write of the session. So is a variable that the + // CLI set (ORACLE_GAPS_STATE, which names each check's output), which a + // copy may read too. A read that comes after its warm ended, from work the + // warm left behind, is a hook's read, so the global inputs stay those of + // the warm itself. + const warmReads = new Map() + const hookReads = new Map() + // The hook reads in the order they came (`hookLog`), kept once in the + // store per session (`hook-log:`): a unit names the part of the log + // that came before it settled (`hooks::`), which is an input while + // every read in that part holds its hash, so no unit carries the reads + // themselves (about 3,000 on TanStack DB's suite; review of #133). + const hookLogId = sha1(`${process.pid}:${Date.now()}:${Math.random()}`) + const hookLog = [] + // How much of the hook log the store holds (see check). + let hookLogStored = 0 + // Per check: how far each session's log still holds (logHolds). + const holds = new Map() + const wrote = new Set() + const written = new Map() + const reading = new AsyncLocalStorage() + watchReads((key, write) => { + const at = reading.getStore() + if (write && key.startsWith(`env:`)) wrote.add(key) + const reads = at?.hook || at?.done ? hookReads : warmReads + if (at === undefined || at.discovery || key === at.module || reads.has(key)) + return + if (write) wrote.add(key) + else if (!wrote.has(key)) { + const hash = key.startsWith(`env:`) + ? reads === hookReads + ? envHash(key.slice(4)) + : null + : inputHash(key) + reads.set(key, hash) + if (reads === hookReads) hookLog.push([key, hash]) + } + }) + // Runs `work` as a warm under `reading`. + const warming = async (work) => { + const at = {} + try { + return await reading.run(at, work) + } finally { + at.done = true + } + } + globalThis.__oracleGapsPluginHooks = (plugins) => + pluginHooks(plugins, reading) const requireTarget = createRequire(join(pkg, `package.json`)) let createVitest try { - ;({ createVitest } = await import( - pathToFileURL(requireTarget.resolve(`vitest/node`)).href + ;({ createVitest } = await warming( + () => import(pathToFileURL(requireTarget.resolve(`vitest/node`)).href), )) } catch (error) { throw new Refusal( @@ -479,7 +600,11 @@ export async function openSession(pkg, pause = async () => {}) { writeFileSync(join(home, `host`), hostname()) const harness = join(home, `capture-setup.mjs`) copyFileSync(join(here, `capture-setup.mjs`), harness) - // The harness imports the path rule beside it (capture-setup.mjs). + // The harness imports the input rule and the path rule beside it, and + // preloads the child-write log into the processes a test starts + // (capture-setup.mjs). + copyFileSync(join(here, `inputs.mjs`), join(home, `inputs.mjs`)) + copyFileSync(join(here, `child-writes.mjs`), join(home, `child-writes.mjs`)) copyFileSync(join(here, `paths.mjs`), join(home, `paths.mjs`)) // One wrapper config per context, over the package's own config (a path // relative to the package, or undefined for none). Each serves its own @@ -523,6 +648,11 @@ export default async (env) => { plugins: [{ name: 'oracle-gaps-schemata', enforce: 'pre', + // Every resolved plugin's hooks read their inputs under the runner's + // watch (check.mjs, pluginHooks). + configResolved(resolved) { + globalThis.__oracleGapsPluginHooks(resolved.plugins) + }, // A workspace dependency loads from its one-file bundle // (workspaceBundles). A copy of a test file is not resolved here, so // Vite keeps the absolute path that Vitest imports it by, and \`load\` @@ -584,11 +714,58 @@ export default async (env) => { // module by the text that its context serves. const servedHash = (path, index) => { if (path.startsWith(`fs:`)) return hashOf(path.slice(3)) + // A variable by its value in the environment this check runs under, and + // a directory by its listing now. + if (path.startsWith(`env:`)) return envHash(path.slice(4)) + if (path.startsWith(`hooks:`)) { + const [, id, n] = path.split(`:`) + return logHolds(id, Number(n)) >= Number(n) ? `held` : `changed` + } + if (path.startsWith(`shared:`)) return sharedHolds(path, index) + if (/^(dir|dirs|stat):/.test(path)) return inputHash(path) const text = globalThis.__oracleGapsServe[index]?.get(path) ?? globalThis.__oracleGapsSchemata.get(path) return text === undefined ? hashOf(path) : sha1(text) } + // The inputs that many units read alike, a variable or a file under + // node_modules, are stored once per distinct set (`shared:`, a row + // of the store) and named by each unit that read them (sharedInputs), so + // a unit keeps only the inputs that are its own (review of #133, M + // "Optimize #133 before merging"). A set holds while each of its inputs + // holds its hash, judged once per check and context. + const shared = new Map() + const sharedHolds = (path, index) => { + const key = `${path}:${index}` + if (!shared.has(key)) { + const inputs = currentStore?.get(path)?.variants[0]?.inputs + shared.set( + key, + inputs?.every(([input, hash]) => servedHash(input, index) === hash) + ? `held` + : `changed`, + ) + } + return shared.get(key) + } + // How much of a session's hook log, from its start, still holds its + // hashes in this check: a unit that names `hooks::` is unchanged + // while the first n reads hold. Another session's log is read from the + // store; the current one's grows while the check runs, so the count + // extends as later units ask. + let currentStore + const logHolds = (id, n) => { + const log = + id === hookLogId + ? hookLog + : (currentStore?.get(`hook-log:${id}`)?.variants[0]?.inputs ?? []) + const held = holds.get(id) ?? { count: 0, broken: false } + holds.set(id, held) + while (!held.broken && held.count < Math.min(n, log.length)) + if (servedHash(log[held.count][0]) === log[held.count][1]) held.count += 1 + else held.broken = true + return held.count + } // A context transformed a module (its wrapper's transform hook): the hash // of what it then serves. globalThis.__oracleGapsTransformed = (index, path) => @@ -726,7 +903,12 @@ export default async (env) => { await new Promise((resolve) => service.on(`exit`, resolve)) throw new Error(`The service was stopped`) } - async function warmContext(settings, index) { + // A context warms under `reading` (see warmReads): what its config, Vite, + // and Vitest read while it warms is a global input. + function warmContext(settings, index) { + return warming(() => warmIn(settings, index)) + } + async function warmIn(settings, index) { await fromConfig(index, settings.config, warmProbe()) writeWrapper(index, settings.config) // A context that fails to open gives its listener allowance back: one @@ -751,6 +933,10 @@ export default async (env) => { teardownTimeout: settings.testTimeout, typecheck: { enabled: false }, coverage: { enabled: false }, + // The runner orders the files itself (KeepOrder), so Vitest's + // results cache, which it reads when a context warms and writes + // after each run, would only be an input that every run changes. + cache: false, // Vitest 5 caches transformed modules on disk by default, keyed by // the file, not by what this runner's plugin serves for it, so a // patched or instrumented source could come back as an earlier text. @@ -778,6 +964,17 @@ export default async (env) => { throw error }), ) + // Vitest's discovery of the test files lists the package's directories. + // Each check discovers them again, outside any warm (specsOf), so what a + // listing found is never stale: those listings are no global input. The + // `--out` directories that runs create beside the tests would otherwise + // change every unit's identity at every check. + for (const project of context.projects ?? []) { + const globFiles = project.globFiles + if (typeof globFiles === `function`) + project.globFiles = (...args) => + reading.run({ discovery: true }, () => globFiles.apply(project, args)) + } // Vitest 3 calls this step `init`; Vitest 4 renamed it `standalone`. await fromConfig( index, @@ -1597,7 +1794,25 @@ export default async (env) => { return environments } - async function check( + // A check, after which each file the session wrote is known by its text. + async function check(...args) { + try { + return await checkIn(...args) + } finally { + for (const key of wrote) + if (key.startsWith(`fs:`)) written.set(key, inputHash(key)) + // The session's hook log, for units that later sessions look up, once + // it has grown: a put marks the store to be written again, whole. + if (hookLog.length > hookLogStored) { + args[1]?.put(`hook-log:${hookLogId}`, { + inputs: [...hookLog], + unit: null, + }) + hookLogStored = hookLog.length + } + } + } + async function checkIn( options, store, log = console.error, @@ -1612,6 +1827,13 @@ export default async (env) => { if (gone()) throw new Error(`the check's caller has gone`) } stopIfGone() + // Each check hashes every input from its text (fileHashes), and starts + // with no write of its own. + hashOf.forget() + wrote.clear() + holds.clear() + shared.clear() + currentStore = store const authored = options.mutants ? loadAuthored(options.mutants) : [] seedVariable = `${options.envPrefix}_SEED` if (options.hangLimit > options.mutantLimit) @@ -1736,6 +1958,9 @@ export default async (env) => { ] .sort() .map((file) => [file, hashOf(file)]), + // What Vitest, Vite, and the config read while Vitest loaded and the + // contexts warmed (warmReads), each by its value now. + [...warmReads.keys()].sort().map((key) => [key, servedHash(key)]), process.version, options.seed ?? null, settings, @@ -1800,11 +2025,20 @@ export default async (env) => { // its context's transform of it, or else its hash at the start, or now. // A path that changed while the run ran is invalidated, and the run is // not stored (undefined); nor is a run with no known input. - function settleIn(context, started, paths, readAt = {}) { + function settleIn(context, started, runPaths, runReadAt = {}) { const index = indexOf.get(context) const served = servedBy(index) const loads = globalThis.__oracleGapsLoads[index] - let stable = paths.length > 0 + let stable = runPaths.length > 0 + // What the config's plugins have read so far, each with its hash from + // its read: the run may have read through any of it (see hookReads). + // A variable that the CLI set (`wrote`) is its own output, which a + // copy may read too (the harness's fallback read of ORACLE_GAPS_STATE). + const hooks = `hooks:${hookLogId}:${hookLog.length}` + const paths = [...new Set([...runPaths, hooks])].filter( + (path) => !(path.startsWith(`env:`) && wrote.has(path)), + ) + const readAt = { [hooks]: `held`, ...runReadAt } const inputs = paths.map((path) => { const now = servedHash(path, index) const hash = @@ -1821,12 +2055,32 @@ export default async (env) => { }) return stable ? inputs : undefined } - const remember = (id, unit, inputs) => { + // A unit is stored without the hashes of what its copy read (`readAt`), + // which only its settling used: the stored inputs hold them. + const remember = (id, { readAt, ...unit }, inputs) => { if (!inputs) return - const entry = { inputs, unit } + const entry = { inputs: sharedInputs(inputs), unit } hook?.stored(entry) store.put(id, entry) } + // A unit's inputs with those that many units read alike (see + // sharedHolds) moved into one stored set, which the unit names. + const sharedInputs = (inputs) => { + const common = [] + const own = [] + for (const input of inputs) + (input[0].startsWith(`env:`) || input[0].includes(`/node_modules/`) + ? common + : own + ).push(input) + if (common.length < 2) return inputs + // In one order, so the copies of a file, which read the same modules + // in different orders, name one set. + common.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)) + const path = `shared:${sha1(JSON.stringify(common))}` + if (!store.get(path)) store.put(path, { inputs: common, unit: null }) + return [...own, [path, `held`]] + } // A batch run in a slot's context, with the inputs to store each item // under: the modules its file's unmutated run read, and those its copy // loaded beyond them, as a mutated branch can import a module. @@ -2809,7 +3063,17 @@ export default async (env) => { removeHome() } - return { check, close } + /** + * Whether a file the session read (warmReads, hookReads) or wrote + * (written) holds other text now: a + * daemon then serves no more checks, since a plugin or a module may keep + * what it read (daemon.mjs). + */ + const inputsChanged = () => + [...warmReads, ...hookReads, ...written].some( + ([key, hash]) => !key.startsWith(`env:`) && inputHash(key) !== hash, + ) + return { check, close, inputsChanged } } /** diff --git a/packages/oracles/oracle-gaps/child-writes.mjs b/packages/oracles/oracle-gaps/child-writes.mjs new file mode 100644 index 00000000..7a2fce60 --- /dev/null +++ b/packages/oracles/oracle-gaps/child-writes.mjs @@ -0,0 +1,19 @@ +// What a test's own child processes write, at any depth. The harness +// (capture-setup.mjs) preloads this file into every Node process that a test +// starts (`--import` in NODE_OPTIONS, which each child passes on to its own +// children) and names a log per copy (ORACLE_GAPS_CHILD_WRITES). Each file +// that such a process writes goes into the log as its input key, before the +// write, so the copy knows that a later read of it reads its own process +// tree's output, which is no input (maintainer decisions "Own writes aren't +// inputs", 2026-11-17, and "Optimize #133 before merging", 2026-11-19). +// The log is written through a file descriptor, which no wrapper watches. +import { openSync, writeSync } from 'node:fs' +import { watchReads } from './inputs.mjs' + +const log = process.env.ORACLE_GAPS_CHILD_WRITES +if (log) { + const fd = openSync(log, `a`) + watchReads((key, write) => { + if (write && key.startsWith(`fs:`)) writeSync(fd, `${key}\n`) + }) +} diff --git a/packages/oracles/oracle-gaps/constructed-order.json b/packages/oracles/oracle-gaps/constructed-order.json index 2f83f51a..9b28adf4 100644 --- a/packages/oracles/oracle-gaps/constructed-order.json +++ b/packages/oracles/oracle-gaps/constructed-order.json @@ -108,6 +108,19 @@ "a stop after the run's ending is written, while its exit is held", "an internal error after the run's ending is answered", "a supervisor killed while its child, with no process left, awaits its answer", - "an internal error after the run's ending is written, before the supervisor has it" + "an internal error after the run's ending is written, before the supervisor has it", + "an edit to a file in the package that keeps its size and modification time", + "an edit to a file outside the package that a test reads", + "an edit to a file under node_modules that a test reads", + "an edit to an environment variable that a test reads", + "an edit to a file the config's plugin reads when the config resolves", + "an edit to a file the config's plugin reads when it transforms a test", + "an edit to a directory listing that a test reads", + "an edit to a directory a test reads through opendir", + "an edit to a file a test reads through a stream", + "an edit to the tsconfig that Vite's own plugin reads", + "an edit to a directory the config lists when it loads", + "a hand edit of a file the config's plugin writes", + "a test that reads a file its child process wrote, rechecked through the daemon" ] } diff --git a/packages/oracles/oracle-gaps/daemon.mjs b/packages/oracles/oracle-gaps/daemon.mjs index 28ebbd3b..5859656f 100644 --- a/packages/oracles/oracle-gaps/daemon.mjs +++ b/packages/oracles/oracle-gaps/daemon.mjs @@ -234,7 +234,12 @@ export async function requestDaemon(pkg, argv, code) { let reply const sent = Date.now() try { - reply = await send(pkg, { argv, cwd: process.cwd(), code }, true) + // The CLI's environment, which the daemon must run the check under. + reply = await send( + pkg, + { argv, cwd: process.cwd(), code, env: process.env }, + true, + ) held += Date.now() - sent // A daemon that stopped answering: the CLI checks cold (R39) and leaves // it; the daemon drops the check once it sees the CLI gone. @@ -367,7 +372,13 @@ async function takeLock(lock, socket) { } } +// An environment as one value: its names and values, in name order. +const envKey = (env) => JSON.stringify(Object.entries(env ?? {}).sort()) + async function serve(pkg) { + // The environment this daemon runs its checks under, which the CLI that + // started it gave it, taken before the session sets anything in it. + const ownEnv = envKey(process.env) mkdirSync(stateDirOf(pkg), { recursive: true }) const lock = join(stateDirOf(pkg), `daemon.lock`) const socket = socketOf(pkg) @@ -476,8 +487,18 @@ async function serve(pkg) { // A daemon whose code changed, or that a CLI of other code asks (a // second install), declines this check and closes after the // requests already queued, each of which hears `closing`; the CLI - // then starts a daemon of its own code. - if (codeIdentity() !== code || message.code !== code) { + // then starts a daemon of its own code. So does a daemon asked from + // another environment than its own, or whose session read a file + // that changed since (check.mjs, inputsChanged): every read is a + // daemon input (maintainer decision, 2026-11-16), and a module or a + // plugin may keep what it read, so the CLI starts a daemon in its own + // environment, which reads them again. + if ( + codeIdentity() !== code || + message.code !== code || + envKey(message.env) !== ownEnv || + session.inputsChanged() + ) { closing = true queue = queue.then(() => shutdown(connection, { restart: true })) return diff --git a/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs b/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs index 8add7dd9..e3f41e80 100644 --- a/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs +++ b/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs @@ -13,10 +13,11 @@ import { rmSync, symlinkSync, unlinkSync, + utimesSync, writeFileSync, } from 'node:fs' import { createRequire } from 'node:module' -import { dirname, join } from 'node:path' +import { dirname, join, posix as posixPath } from 'node:path' import { fileURLToPath } from 'node:url' import fc from 'fast-check' @@ -532,6 +533,11 @@ const earlierEdits = edits.filter((edit) => !laterEdits.includes(edit)) const faults = [`corruptStore`] // A history's no faults, one value, as `NO_LATER_STEPS`. const NO_FAULTS = Object.freeze([]) +// The edit of the gate input that file b's verdict reads (`inputRead`), +// which flips it between `open` and `shut`. It is drawn in its own field +// (`inputSteps`), after `laterSteps`, so the fields before it draw as they +// did (the generator rule: new draws go last). +const inputEdits = [`inputGate`] // A history's no later edits, one value, so `histories` can take it back // (fc.constant takes back only its own reference). const NO_LATER_STEPS = Object.freeze([]) @@ -544,6 +550,12 @@ const laterStepsOf = (history) => history.witness === false && history.steps != null ? [...(history.laterSteps ?? []), ...(history.faults ?? [])] : [] +// The input edits a history takes after its later edits, by the same rule. +const NO_INPUT_STEPS = Object.freeze([]) +const inputStepsOf = (history) => + history.witness === false && history.steps != null + ? (history.inputSteps ?? []) + : [] // The steps that act on the daemon and change no file. const daemonEvents = new Set([ `restart`, @@ -1170,6 +1182,94 @@ const drawn = fc.record({ }), }, ), + // Every read is a daemon input (maintainer decision, 2026-11-16, "All of + // them"): a file a test reads through fs on any path, node_modules + // included; an environment variable a test reads; and what the config's + // own plugin reads. File b's verdicts also wait on one such gate input, + // which the `inputGate` edit flips between `open` and `shut` (law 9). The + // gate is a JSON file that the test reads with a sync read: in the + // package's tests (`inside`), beside the package and outside it + // (`outside`), or in a package under its node_modules (`module`); or the + // variable GAP_INPUT_GATE (`env`); or a file the config's own plugin + // reads, once when the config resolves (`pluginConfig`) or each time it + // transforms a test file (`pluginTransform`), and writes into the test's + // text; or the listing of a directory of the package's tests, which holds + // one empty file named `open` or `shut`, read by `readdirSync` + // (`listing`) or by `opendirSync` (`opendir`): the edit renames that file, + // so no file's text changes; or the package's gate file read through a + // stream (`stream`, createReadStream); or an input of Vite's own plugins, + // the package's tsconfig.json, whose useDefineForClassFields decides + // whether a declared class field is an own property (`tsconfig`); or a + // listing that the config makes when it loads and gives to the tests + // through `define` (`configListing`); or a file that the config's plugin + // writes when the config resolves, which the edit then changes by hand + // (`pluginWrite`: a cold run's plugin writes it again, so the cold result + // does not change, and the daemon must not read the hand edit). These fields change what a history runs, so + // they are drawn (maintainer decision, 2026-11-16, "Randomness wins"), and + // last. + inputRead: fc.constantFrom( + `none`, + `none`, + `none`, + `inside`, + `outside`, + `module`, + `env`, + `pluginConfig`, + `pluginTransform`, + `listing`, + `opendir`, + `stream`, + `tsconfig`, + `configListing`, + `pluginWrite`, + ), + // Each write of a gate file keeps its size (`open` and `shut` have one + // length) and gets back one fixed modification time, as `cp -p`, `rsync + // -t`, or `touch -r` leave a file: a cache keyed by size and time cannot + // tell the two texts apart (D10; the TLA model's weakened-stamp run). + keepStamp: fc.constantFrom(false, false, false, true), + // The input edits, which follow a history's steps and later edits. + inputSteps: fc.oneof( + { weight: 3, arbitrary: fc.constant(NO_INPUT_STEPS) }, + { + weight: 1, + arbitrary: fc.array(fc.constantFrom(...inputEdits), { + minLength: 1, + maxLength: 2, + }), + }, + ), + // Whether file b, as it loads, reads a file that its test's own child + // process wrote: a node child starts a node grandchild, which writes the + // file in a new temporary directory and prints the directory, and file b + // reads the file and removes the directory. A file that the test's own + // process tree wrote earlier in the check is its own output, no input + // (maintainer decisions "Own writes aren't inputs", 2026-11-17, and + // "Optimize #133 before merging", 2026-11-19), so an unchanged recheck + // through the daemon reuses file b's runs although the directory differs + // in every run. It changes what a history runs, so it is drawn (randomness + // wins, 2026-11-16), and last. + childWrite: fc.constantFrom( + false, + false, + false, + false, + false, + false, + false, + true, + ), + // The Vite environment that file b runs in when it reads what its child + // process wrote (`childWrite`): the config's (`node`), or one that + // transforms its modules for the client (`client`), as a jsdom + // environment does. The client transform rewrites `new URL(, + // import.meta.url)` to a URL of the dev server, in the harness that runs in + // the file's environment too, so the harness's own path to the child + // preload must not take that form (TanStack DB's jsdom suite). Only file b + // takes it, and only where it reads no gate input or data, whose paths + // take that form in the file's own text. + childEnvironment: fc.constantFrom(`node`, `node`, `node`, `client`), }) // The edit sequence over the witness module, the one list of steps that a @@ -1327,14 +1427,21 @@ const histories = drawn.map( ? { ...taken, faults: NO_FAULTS } : taken const later = (steps ?? []).filter((step) => laterEdits.includes(step)) + // An input edit in `steps` moves to `inputSteps` in the same way. + const inputs = (steps ?? []).filter((step) => inputEdits.includes(step)) const remaining = (steps ?? []).filter( - (step) => !laterEdits.includes(step) && !faults.includes(step), + (step) => + !laterEdits.includes(step) && + !faults.includes(step) && + !inputEdits.includes(step), ) - if (later.length === 0 && struck.length === 0) return faulted + if (later.length === 0 && struck.length === 0 && inputs.length === 0) + return faulted return { ...faulted, steps: remaining.length > 0 ? remaining : null, ...(later.length > 0 ? { laterSteps: later } : {}), + ...(inputs.length > 0 ? { inputSteps: inputs } : {}), } }, ) @@ -3499,7 +3606,11 @@ function resolveHistory(history) { template: history.template, fault: history.fault, stability: history.stability, - steps: [...(history.steps ?? []), ...laterStepsOf(history)], + steps: [ + ...(history.steps ?? []), + ...laterStepsOf(history), + ...inputStepsOf(history), + ], pauseEngages: history.pauseEngages !== false, warmReplaced: history.warmReplaced === true, replyHeld: history.replyHeld === true, @@ -3511,6 +3622,23 @@ function resolveHistory(history) { spinThrows: history.spinThrows === true, slowStart: history.slowStart ?? false, shortWait: history.shortWait === true, + childWrite: history.childWrite === true, + childEnvironment: + history.childWrite === true && + (history.inputRead ?? `none`) === `none` && + (history.fsRead ?? `none`) === `none` + ? (history.childEnvironment ?? `node`) + : `node`, + // The gate input that file b's verdicts also wait on (`inputRead`), and + // whether each write of a gate file keeps its size and modification time + // (`keepStamp`). + // A plugin's gate needs a config to hold the plugin: with none, file b + // reads no gate. + inputRead: + configGated(history) && configOf(history).configPath === undefined + ? `none` + : (history.inputRead ?? `none`), + keepStamp: history.keepStamp === true, // Whether a step edits file b's helper during a check (`midrun`): then // file a loads the helper and holds the test that edits it. midrun: [...(history.steps ?? []), ...laterStepsOf(history)].includes( @@ -5596,6 +5724,125 @@ const dataReads = { ], } +// The gate input of file b's verdicts (`inputRead`): the variable that +// `env` reads, and the file each other kind reads. A gate file holds +// `open` or `shut`, two words of one length, so an edit keeps its size. +const INPUT_GATE_VAR = `GAP_INPUT_GATE` +const gateText = (open) => + `${JSON.stringify({ gate: open ? `open` : `shut` })}\n` +// The modification time, in seconds, that every write of a gate file gets +// back under `keepStamp`. +const GATE_STAMP = 1_700_000_000 +// A fixture path under the directory beside the package (`outsideOf`), +// which is outside it; writeFixture places it there. +const BESIDE = `/` +/** The directory beside the package `dir` that holds its outside files. */ +const outsideOf = (dir) => `${dir}.outside` +const gateFiles = { + inside: `tests/gate.json`, + stream: `tests/gate.json`, + outside: `${BESIDE}gate.json`, + module: `node_modules/gap-gate/gate.json`, + pluginConfig: `tests/plugin-gate.json`, + pluginTransform: `tests/plugin-gate.json`, +} +/** Whether the gate input is one that the config's own plugin reads. */ +const pluginGated = (history) => + history.inputRead === `pluginConfig` || + history.inputRead === `pluginTransform` +/** Whether the gate lives in the config (a plugin, or the config's own listing). */ +const configGated = (history) => + pluginGated(history) || + history.inputRead === `configListing` || + history.inputRead === `pluginWrite` +// Whether a test's verdict waits on the gate input. +const inputGated = (plan, file, t) => + plan.inputRead !== `none` && + file === `b` && + t.judges && + t.judgeBy === `verdict` +// How file b reads its gate input, by each kind (`inputRead`). The outside +// file lies in the directory beside the package, named by the package's +// own directory with `.outside` after it. The plugin kinds read the text +// that the config's plugin wrote in place of `__GAP_INPUT_GATE__`. +const readGateFile = (path) => + `const readInput = async () => ({ open: JSON.parse(readGate(${path}, 'utf8')).gate === 'open' })` +const inputReads = { + inside: [ + `import { readFileSync as readGate } from 'node:fs'`, + readGateFile(`new URL('./gate.json', import.meta.url)`), + ], + outside: [ + `import { readFileSync as readGate } from 'node:fs'`, + `import { fileURLToPath as gatePackage } from 'node:url'`, + readGateFile( + `gatePackage(new URL('..', import.meta.url)).replace(/[\\\\/]+$/, '') + '.outside/gate.json'`, + ), + ], + module: [ + `import { readFileSync as readGate } from 'node:fs'`, + readGateFile( + `new URL('../node_modules/gap-gate/gate.json', import.meta.url)`, + ), + ], + env: [ + `const readInput = async () => ({ open: process.env.${INPUT_GATE_VAR} !== 'shut' })`, + ], + pluginConfig: [ + `const readInput = async () => ({ open: __GAP_INPUT_GATE__ === 'open' })`, + ], + pluginTransform: [ + `const readInput = async () => ({ open: __GAP_INPUT_GATE__ === 'open' })`, + ], + tsconfig: [ + `class GateBase {}`, + `class GateField extends GateBase { field!: number }`, + `const readInput = async () => ({ open: Object.hasOwn(new GateField(), 'field') })`, + ], + configListing: [ + `const readInput = async () => ({ open: __GAP_INPUT_GATE__ === 'open' })`, + ], + pluginWrite: [ + `import { readFileSync as readGate } from 'node:fs'`, + readGateFile(`new URL('./gen.json', import.meta.url)`), + ], + stream: [ + `import { createReadStream as streamGate } from 'node:fs'`, + `const readInput = async () => { const chunks: Array = []; for await (const chunk of streamGate(new URL('./gate.json', import.meta.url))) chunks.push(chunk as Buffer); return { open: JSON.parse(Buffer.concat(chunks).toString('utf8')).gate === 'open' } }`, + ], + listing: [ + `import { readdirSync as listGate } from 'node:fs'`, + `const readInput = async () => ({ open: listGate(new URL('./gate-dir/', import.meta.url)).includes('open') })`, + ], + opendir: [ + `import { opendirSync as openGate } from 'node:fs'`, + `const readInput = async () => { const dir = openGate(new URL('./gate-dir/', import.meta.url)); const names: Array = []; for (let entry = dir.readSync(); entry; entry = dir.readSync()) names.push(entry.name); dir.closeSync(); return { open: names.includes('open') } }`, + ], +} +// File b's read of a file that its test's child process tree wrote +// (`childWrite`): the grandchild writes `child.txt` in a new directory under +// the OS temporary directory and prints the directory, which the child +// passes on; file b tests that the file exists, which is a read of it by +// existence and kind (G42's stat family), checks its text, and removes the +// directory. +const CHILD_WRITE = `const fs = require('node:fs'), os = require('node:os'), path = require('node:path'); const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gap-child-')); fs.writeFileSync(path.join(dir, 'child.txt'), 'written'); process.stdout.write(dir)` +const CHILD_START = `process.stdout.write(require('node:child_process').execFileSync(process.execPath, ['-e', ${JSON.stringify(CHILD_WRITE)}], { encoding: 'utf8' }))` +const childWriteRead = [ + `import { execFileSync as runChild } from 'node:child_process'`, + `import { existsSync as childExists, readFileSync as readChild, rmSync as removeChild } from 'node:fs'`, + `import { join as joinChild } from 'node:path'`, + `const childDir = runChild(process.execPath, ['-e', ${JSON.stringify(CHILD_START)}], { encoding: 'utf8' })`, + `if (!childExists(joinChild(childDir, 'child.txt'))) throw new Error('the child process wrote no file')`, + `const childText = readChild(joinChild(childDir, 'child.txt'), 'utf8')`, + `removeChild(childDir, { recursive: true, force: true })`, + `if (childText !== 'written') throw new Error('the child process wrote another text')`, +] +/** The variables a check of `state` runs with: the gate's, under `env`. */ +const inputEnv = (plan, state) => + plan.inputRead === `env` + ? { [INPUT_GATE_VAR]: state.inputOpen ? `open` : `shut` } + : {} + function oracleTestFile(plan, file) { const sites = sitesOf(plan) const entries = [ @@ -5645,6 +5892,9 @@ function oracleTestFile(plan, file) { const out = [ // A per-file environment, which Vitest reads from the file's text. ...(plan.pragma && file === `a` ? [`// @vitest-environment marked`] : []), + ...(plan.childEnvironment === `client` && file === `b` + ? [`// @vitest-environment client-marked`] + : []), `import { ${holdsFailingLaw(plan, file) && plan.failingLawHook !== `none` ? `${plan.failingLawHook}, ` : ``}${plan.tests.some((t) => t.file === file && t.cleanupThrows) ? `afterEach, ` : ``}describe, expect, test${plan.tests.some((t) => t.file === file && (t.spies || t.timed === `spiedclock`)) ? `, vi` : ``} } from 'vitest'`, ...(plan.tests.some((t) => t.file === file && t.shrinks) ? [`import fc from 'fast-check'`] @@ -5698,6 +5948,10 @@ function oracleTestFile(plan, file) { `import * as sut from '../src/sut'`, ...(file === `b` ? [`import { strict } from './strict'`] : []), ...(file === `b` && plan.fsRead !== `none` ? dataReads[plan.fsRead] : []), + ...(file === `b` && plan.inputRead !== `none` + ? inputReads[plan.inputRead] + : []), + ...(file === `b` && plan.childWrite ? childWriteRead : []), ...stubs, // State that tests of this file share (the `w_shared` witness). `const shared = { value: 0 }`, @@ -5875,7 +6129,7 @@ function oracleTestFile(plan, file) { // A lazy gate is imported only where the output differs, so // the unmutated run never loads it. It is open before any // edit, so the model need not read it. - ` if (${when} && JSON.stringify(${out}) !== ${JSON.stringify(expected)}${lazyGated(plan, file, t) ? ` && (await import('./lazy')).open` : ``}${fsGated(plan, file, t) ? ` && (await readData()).open` : ``}) {`, + ` if (${when} && JSON.stringify(${out}) !== ${JSON.stringify(expected)}${lazyGated(plan, file, t) ? ` && (await import('./lazy')).open` : ``}${fsGated(plan, file, t) ? ` && (await readData()).open` : ``}${inputGated(plan, file, t) ? ` && (await readInput()).open` : ``}) {`, ` g.__oracleVerdict?.({ property: 'fixture-${file}', law: '${t.law}', checkpoint: 'trace' })`, ` throw new Error('violation')`, ` }`, @@ -5893,7 +6147,7 @@ function oracleTestFile(plan, file) { : []), t.asProp ? ` fcTest.prop([fcv.integer({ min: 0, max: 10 })], { numRuns: 20, seed: 1 })('${testName(t, index)}', async (n) => {` - : ` test('${testName(t, index)}', ${(t.hangs && !t.flaky) || t.slow || t.ioWait || t.timed || lazyGated(plan, file, t) || fsGated(plan, file, t) ? `async ` : ``}() => {`, + : ` test('${testName(t, index)}', ${(t.hangs && !t.flaky) || t.slow || t.ioWait || t.timed || lazyGated(plan, file, t) || fsGated(plan, file, t) || inputGated(plan, file, t) ? `async ` : ``}() => {`, ...partsOf(t).flatMap(campaign), ` })`, `})`, @@ -6161,6 +6415,8 @@ const initialState = (plan) => ({ lazyOpen: true, // What `tests/data.json` holds: whether file b's data gate is open. dataOpen: true, + // Whether file b's gate input reads `open` (`inputRead`). + inputOpen: true, // How many mid-run edits have landed (`midrun`). midruns: 0, seed: 1, @@ -6191,17 +6447,49 @@ const PRE_PLUGIN = `{ name: 'gap-pre-rewrite', enforce: 'pre', transform(code, i // memory, so only the runner's own \`load\` can answer for it (review of #103). const LOAD_PLUGIN = `{ name: 'gap-own-load', load(id) { const path = id.split('?')[0]; return path.endsWith('.test.ts') ? readFileSync(path, 'utf8') : undefined } }` +// The config's own plugin that reads the gate file (`inputRead` +// `pluginConfig` or `pluginTransform`) and writes its word in place of +// `__GAP_INPUT_GATE__` in each test file it transforms. It finds the file +// from the config's own location (`gatePath`), not from a root, which a +// config's test root moves. `pluginConfig` reads it once, when the config +// resolves; `pluginTransform` reads it in each transform. +const GATE_READ = `JSON.parse(readGate(gatePath, 'utf8')).gate` +const gatePlugin = (plan) => + plan.inputRead === `pluginWrite` + ? `{ name: 'gap-input-gate', configResolved() { writeGate(gatePath, '{"gate":"open"}\\n') } }` + : `(() => { let gate; return { name: 'gap-input-gate', configResolved() { ${plan.inputRead === `pluginConfig` ? `gate = ${GATE_READ}` : ``} }, transform(code, id) { return id.split('?')[0].endsWith('.test.ts') ? code.replaceAll('__GAP_INPUT_GATE__', JSON.stringify(${plan.inputRead === `pluginConfig` ? `gate` : GATE_READ})) : undefined } } })()` +// The gate file's path from a config at `configPath` (in the package, or in +// its parent, where the package is the directory `pkg`). +const gateFromConfig = (configPath, target = `tests/plugin-gate.json`) => + posixPath.relative( + posixPath.dirname(posixPath.join(`/pkg`, configPath)), + `/pkg/${target}`, + ) +// The file or directory the config reads or writes, by gate kind. +const configTargets = { + configListing: `tests/gate-dir`, + pluginWrite: `tests/gen.json`, +} + /** * The text of the package's config, in its syntax (`configOf`), with the * fault, the top-level await, or the `require` calls the plan holds. `test` * is the config's `test` object. */ -function configText(plan, test) { +function configText(plan, test, configPath = plan.configPath) { const commonjs = plan.configSyntax === `cjs` const plugins = [ ...(plan.prePlugin ? [PRE_PLUGIN] : []), ...(plan.loadPlugin ? [LOAD_PLUGIN] : []), + ...(pluginGated(plan) || plan.inputRead === `pluginWrite` + ? [gatePlugin(plan)] + : []), ] + // The config's listing of the gate directory, given to the tests. + const define = + plan.inputRead === `configListing` + ? `, define: { __GAP_INPUT_GATE__: JSON.stringify(listGate(gatePath).includes('open') ? 'open' : 'shut') }` + : `` const config = `defineConfig(${ { object: ``, function: `() => (`, async: `async () => (`, promise: `` }[ plan.config @@ -6210,7 +6498,7 @@ function configText(plan, test) { plan.fault === `projects` ? `{ projects: [{ test: { name: 'unit', ...${test} } }] }` : test - }${plugins.length > 0 ? `, plugins: [${plugins.join(`, `)}]` : ``} }${plan.config === `object` || plan.config === `promise` ? `` : `)`})` + }${plugins.length > 0 ? `, plugins: [${plugins.join(`, `)}]` : ``}${define} }${plan.config === `object` || plan.config === `promise` ? `` : `)`})` // A promise of the config, a null default, or a config cut off mid-object. const body = plan.fault === `configNull` @@ -6229,6 +6517,17 @@ function configText(plan, test) { : [`import { fileURLToPath } from 'node:url'`]), // Only a config in ES module syntax has the load plugin (`loadPluginOf`). ...(plan.loadPlugin ? [`import { readFileSync } from 'node:fs'`] : []), + ...(configGated(plan) + ? commonjs + ? [ + `const { readFileSync: readGate, readdirSync: listGate, writeFileSync: writeGate } = require('node:fs')`, + `const gatePath = require('node:path').join(__dirname, '${gateFromConfig(configPath, configTargets[plan.inputRead])}')`, + ] + : [ + `import { readFileSync as readGate, readdirSync as listGate, writeFileSync as writeGate } from 'node:fs'`, + `const gatePath = new URL('${gateFromConfig(configPath, configTargets[plan.inputRead])}', import.meta.url)`, + ] + : []), ...(plan.fault === `configThrows` ? [`throw new Error('the fixture config broke')`] : []), @@ -6422,6 +6721,7 @@ function fixtureFiles(plan, state = initialState(plan)) { [altConfigPath(plan)]: configText( plan, test.replace(`'tests/**/*.test.ts'`, `'tests/a.test.ts'`), + altConfigPath(plan), ), } : {}), @@ -6445,6 +6745,30 @@ function fixtureFiles(plan, state = initialState(plan)) { ...(plan.fsRead !== `none` ? { 'tests/data.json': `${JSON.stringify({ open: state.dataOpen })}\n` } : {}), + // The gate file, which under `keepStamp` gets back one modification + // time each time it is written. + // The gate directory of a listing, which holds one empty file, named + // by the gate's word. + ...([`listing`, `opendir`, `configListing`].includes(plan.inputRead) + ? { [`tests/gate-dir/${state.inputOpen ? `open` : `shut`}`]: `` } + : {}), + // The package's tsconfig.json, read by Vite's own esbuild plugin. + ...(plan.inputRead === `tsconfig` + ? { + 'tsconfig.json': `${JSON.stringify({ compilerOptions: { target: `ES2022`, useDefineForClassFields: state.inputOpen } })}\n`, + } + : {}), + // The file the config's plugin writes, as a hand edit leaves it. + ...(plan.inputRead === `pluginWrite` + ? { 'tests/gen.json': gateText(state.inputOpen) } + : {}), + ...(gateFiles[plan.inputRead] === undefined + ? {} + : { + [gateFiles[plan.inputRead]]: plan.keepStamp + ? { text: gateText(state.inputOpen), mtime: GATE_STAMP } + : gateText(state.inputOpen), + }), // A workspace dependency with module state, linked through node_modules. 'deps/state-dep/package.json': manifest({ name: `state-dep`, @@ -6552,6 +6876,24 @@ function fixtureFiles(plan, state = initialState(plan)) { ].join(`\n`), } : {}), + // The client-transform environment that file b names when it reads what + // its child process wrote (`childEnvironment`). + ...(plan.childEnvironment === `client` + ? { + [`${testRoot.environments ?? `node_modules`}/vitest-environment-client-marked/package.json`]: `${JSON.stringify({ name: `vitest-environment-client-marked`, type: `module`, exports: `./index.js` })}\n`, + [`${testRoot.environments ?? `node_modules`}/vitest-environment-client-marked/index.js`]: + [ + `export default {`, + ` name: 'client-marked',`, + ` viteEnvironment: 'client',`, + ` setup() {`, + ` return { teardown() {} }`, + ` },`, + `}`, + ``, + ].join(`\n`), + } + : {}), // A copy that a check which died left behind (the runner names its // copies `.oracle-gaps---`). It is no test file: a check // that took it for one would refuse the run. @@ -6567,6 +6909,14 @@ function fixtureFiles(plan, state = initialState(plan)) { } for (const file of oracleFilesOf(plan)) files[`tests/${file}.test.ts`] = oracleTestFile(plan, file) + // The hand edit of the file the plugin writes also changes file b's own + // text, so the daemon runs b again and reads the edited file. + if ( + plan.inputRead === `pluginWrite` && + files[`tests/b.test.ts`] !== undefined + ) + files[`tests/b.test.ts`] += + `// the plugin's file was edited to ${state.inputOpen ? `open` : `shut`}\n` // Each mid-run edit changes file a's own text too (a count of them), so // the daemon runs file a's tests again in the check the edit lands in, // instead of reusing their evidence: the marker sits in the daemon's @@ -6637,6 +6987,11 @@ function removePath(path) { // The paths each fixture directory holds, so a state that lacks a file of // the state before it removes that file. const written = new Map() +// Where a fixture path lies: in the package, or beside it (`BESIDE`). +const placeOf = (dir, path) => + path.startsWith(BESIDE) + ? join(outsideOf(dir), path.slice(BESIDE.length)) + : join(dir, path) function writeFixture(dir, files) { for (const sub of [ `src`, @@ -6650,14 +7005,17 @@ function writeFixture(dir, files) { if (!existsSync(join(dir, `node_modules/state-dep`))) symlinkSync(`../deps/state-dep`, join(dir, `node_modules/state-dep`), `dir`) for (const path of written.get(dir) ?? []) - if (!(path in files)) removePath(join(dir, path)) - for (const [path, text] of Object.entries(files)) { - const at = join(dir, path) + if (!(path in files)) removePath(placeOf(dir, path)) + for (const [path, value] of Object.entries(files)) { + const at = placeOf(dir, path) mkdirSync(dirname(at), { recursive: true }) + // A file may name the modification time it gets back (`keepStamp`). + const text = typeof value?.text === `string` ? value.text : value // An unchanged file keeps its modification time, as in a real package. if (typeof text === `string`) { if (!existsSync(at) || readFileSync(at, `utf8`) !== text) writeFileSync(at, text) + if (value.mtime !== undefined) utimesSync(at, value.mtime, value.mtime) } else if (linkTarget(at) !== text.link) { // A link that a later state points elsewhere is replaced. removePath(at) @@ -6734,6 +7092,7 @@ function applyEdit(state, edit) { : { ...state, strict: !state.strict, midruns: state.midruns + 1 } if (edit === `lazy`) return { ...state, lazyOpen: !state.lazyOpen } if (edit === `fsData`) return { ...state, dataOpen: !state.dataOpen } + if (edit === `inputGate`) return { ...state, inputOpen: !state.inputOpen } if (edit === `seed`) return { ...state, seed: state.seed === 1 ? 2 : 1 } if (edit === `config`) return { ...state, altConfig: !state.altConfig } // A seed no other step uses, so the check has fresh work to be killed in. @@ -6992,6 +7351,10 @@ export { NO_LATER_STEPS, NO_FAULTS, faults, + NO_INPUT_STEPS, + inputEdits, + inputEnv, + outsideOf, MIDRUN_EDITORS, captureWitness, outsideRepository, diff --git a/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs b/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs index 71c87f27..605a2867 100644 --- a/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs +++ b/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs @@ -494,8 +494,12 @@ * the check it overlaps must report, for each mutant, what a cold run of * the state before or after the edit reports, and the runner must store no * run under a text it did not read (see the limits). An edit can change a - * file that a test reads through `fs` (`fsData`). Law 9's edits do not - * include an environment variable other than the seed, a new file that changes how an + * file that a test reads through `fs` (`fsData`), and the gate input that + * file b's verdict reads (`inputGate`): a file in the package, outside it, + * or under node_modules, the variable GAP_INPUT_GATE, or a file the config's + * own plugin reads, since every read is a daemon input (maintainer decision, + * 2026-11-16). Law 9's edits do not include another environment variable + * than the seed and the gate's, a new file that changes how an * unchanged import resolves, a change to the Vite config or the installed * packages, or checks at once other than the two that start the daemon. * The harness keeps every global a copy defines configurable, by wrapping @@ -663,6 +667,9 @@ import { FULL_LIMIT_MS, NO_LATER_STEPS, NO_STOPS, + NO_INPUT_STEPS, + inputEnv, + outsideOf, } from './gap-report-model-oracle.mjs' const here = dirname(fileURLToPath(import.meta.url)) @@ -2793,8 +2800,15 @@ async function incremental(dir, plan, cli, copy, observe, states) { if (!reportText.includes(RUN_LINE)) throw new Error(`the cli edit no longer finds the summary's run line`) const cold = new Map() + // A state is its files, its seed, its CLI, and the variables it sets. const fingerprint = (files, state, other = false) => - JSON.stringify([files, state.seed, state.cliEdited, other]) + JSON.stringify([ + files, + state.seed, + state.cliEdited, + other, + inputEnv(plan, state), + ]) cold.set(fingerprint(fixtureFiles(plan), initialState(plan)), cli) // A cold result without the run identity, which every edit changes, so // that two states compare by what they report. @@ -2874,11 +2888,15 @@ async function incremental(dir, plan, cli, copy, observe, states) { ...configArgs(plan), // After the `config` edit, `--config` names the second config. ...(state.altConfig ? { config: altConfigPath(plan) } : {}), - // A warm daemon's check under a 3 s bound (`shortWait`): one that works + // The gate variable of this state, when file b's verdicts read one, and + // a warm daemon's check under a 3 s bound (`shortWait`): one that works // longer tells its CLI so, by its beats. - ...(plan.shortWait && step !== `start` - ? { env: { ORACLE_GAPS_TEST_WAIT_MS: `3000` } } - : {}), + env: { + ...inputEnv(plan, state), + ...(plan.shortWait && step !== `start` + ? { ORACLE_GAPS_TEST_WAIT_MS: `3000` } + : {}), + }, } // The first check may be two at once, which must reach one daemon, and // so are the two after a crash. @@ -3118,6 +3136,13 @@ async function incremental(dir, plan, cli, copy, observe, states) { states.add( `an unchanged check through the daemon computed nothing while a test read a source through fs`, ) + // File b read a file that its test's child process tree wrote, in a + // new temporary directory each run: the file is the tree's own output, + // so the unchanged recheck reused b's runs (`childWrite`). + if (plan.childWrite) + states.add( + `an unchanged check through the daemon computed nothing while a test read what its child process wrote`, + ) } // A daemon check after an edit that computed fewer runs cut off by their // call budget than the cold run of the same state reused such a run, so @@ -3158,6 +3183,17 @@ async function incremental(dir, plan, cli, copy, observe, states) { // The other install's summary reads otherwise by construction, so its // check is no edit, and the next edit is compared with the state before. if (step === `otherInstall`) return + // A hand edit of a file the config's plugin writes leaves the cold result + // as it was (the cold run's plugin writes the file again); the check + // through the daemon is judged against it all the same. + if ( + step === `inputGate` && + plan.inputRead === `pluginWrite` && + daemon.reported + ) + states.add( + `a hand edit of a file the config's plugin writes was checked through the daemon`, + ) // An edit that changes the cold result is one a stale cache could miss. if (step !== `start` && result(previous) !== result(coldRun)) { states.add(`edit ${step} changed the cold result`) @@ -3166,6 +3202,23 @@ async function incremental(dir, plan, cli, copy, observe, states) { states.add( `an edit to data read through ${plan.fsRead} changed the cold result`, ) + // An edit of only the gate input that file b's verdicts read, by each + // kind, and one that kept the gate file's size and modification time. + if (step === `inputGate`) { + states.add( + `an edit to the ${plan.inputRead} gate input changed the cold result`, + ) + // Only a gate file keeps its stamp; a listing's edit renames a file. + if ( + plan.keepStamp && + ![`env`, `listing`, `opendir`, `tsconfig`, `configListing`].includes( + plan.inputRead, + ) + ) + states.add( + `an edit that kept a file's size and modification time changed the cold result`, + ) + } // The daemon's previous check stored runs of file b's copies that read // the data and spun (`spinData`), a file that b's unmutated run never // reads: the runner must store each such run under the inputs it read @@ -3525,7 +3578,12 @@ async function incremental(dir, plan, cli, copy, observe, states) { let warm if (!mid) { const [warmRun] = await runClisAtOnce(dir, files, [ - { ...how, daemon: true, outName: `out-warm`, env }, + { + ...how, + daemon: true, + outName: `out-warm`, + env: { ...how.env, ...env }, + }, ]) observe( `retention:warm`, @@ -3542,7 +3600,9 @@ async function incremental(dir, plan, cli, copy, observe, states) { writeFileSync(armMark, ``) } let finished = false - const running = runClisAtOnce(dir, files, [{ ...how, daemon: true, env }]) + const running = runClisAtOnce(dir, files, [ + { ...how, daemon: true, env: { ...how.env, ...env } }, + ]) running.then(() => { finished = true }) @@ -3742,15 +3802,18 @@ async function driver(plan, observe) { psMissing: plan.psMissing, cli: plan.cliPath === `spaced` ? copy : here, ...configArgs(plan), + env: { + ...inputEnv(plan, initialState(plan)), + ...(plan.rejectBatch > 0 + ? { ORACLE_GAPS_TEST_REJECT_BATCH: String(plan.rejectBatch) } + : {}), + }, // A rejected batch ends through the internal error's ending, the one ending a history reaches that // names its log, so its output directory's name holds a line break where the platform allows one // (not on win32): its error line and done line must escape it (the register's C entry "The // internal-error line"). ...(plan.rejectBatch > 0 - ? { - env: { ORACLE_GAPS_TEST_REJECT_BATCH: String(plan.rejectBatch) }, - outBreak: process.platform !== `win32`, - } + ? { outBreak: process.platform !== `win32` } : {}), foreign: plan.foreign, } @@ -4836,6 +4899,7 @@ async function driver(plan, observe) { } finally { if (copy) rmSync(copy, { recursive: true, force: true }) removePath(`${dir}.link`) + rmSync(outsideOf(dir), { recursive: true, force: true }) written.delete(dir) dropHook(dir) try { @@ -6910,6 +6974,20 @@ const incrementalStates = [ `the daemon ran from a path with a space and #`, `of two checks held in the daemon at once, one computed and the other reused`, ] +// The kinds of gate input that file b's verdicts may read (`inputRead`). +const inputKinds = [ + `inside`, + `outside`, + `module`, + `env`, + `pluginConfig`, + `pluginTransform`, + `listing`, + `opendir`, + `stream`, + `tsconfig`, + `configListing`, +] // Law 9's states that a constructed history of their own reaches, not the // edit sequence: the mid-run edit, and an edit to data a test reads through // fs, by each read. @@ -6927,6 +7005,15 @@ const ownedIncrementalStates = [ `an edit to data read through promise changed the cold result`, `an edit to data read through callback changed the cold result`, `an edit to data read through statDir changed the cold result`, + // Every read is a daemon input (maintainer decision, 2026-11-16): an edit + // of only the gate input that file b's verdicts read, by each kind, and an + // edit that kept the gate file's size and modification time (D10). + ...inputKinds.map( + (kind) => `an edit to the ${kind} gate input changed the cold result`, + ), + `a hand edit of a file the config's plugin writes was checked through the daemon`, + `edit inputGate changed the cold result`, + `an edit that kept a file's size and modification time changed the cold result`, ] // The static states (probe structure and ownership through the reference // tree) are gap-report-static-oracle's: it reaches each in every campaign, @@ -7203,6 +7290,7 @@ const required = [ `a check through the daemon worked past its CLI's bound`, `a slow daemon start was served by the daemon`, `a check abandoned while a context warmed in place of a cut one wrote nothing more`, + `an unchanged check through the daemon computed nothing while a test read what its child process wrote`, ] // The faults the CLI analyzes anyway: a package's TypeScript is no input. const analyzedFaults = [`noTypescript`, `apiLessTypescript`] @@ -7348,6 +7436,9 @@ const separate = [ `a check through the daemon worked past its CLI's bound`, `a slow daemon start was served by the daemon`, `a check abandoned while a context warmed in place of a cut one wrote nothing more`, + // Each has its own constructed history (#179; own writes of the test's + // process tree). + `an unchanged check through the daemon computed nothing while a test read what its child process wrote`, ] // A stop by SIGTERM exists only where Node can deliver it: on win32 kill is // TerminateProcess, so there the stop law is judged by SIGINT (the test stop @@ -7771,6 +7862,11 @@ oracleProperty({ shortWait: false, absentObjects: [], optionalChains: [], + inputRead: `none`, + keepStamp: false, + inputSteps: NO_INPUT_STEPS, + childWrite: false, + childEnvironment: `node`, failingLaw: `none`, failingLawAt: `end`, failingLawCalls: `none`, @@ -7985,6 +8081,11 @@ oracleProperty({ failingLawCalls: 'none', failingLawHook: 'none', failingLawSpins: false, + inputRead: `none`, + keepStamp: false, + inputSteps: NO_INPUT_STEPS, + childWrite: false, + childEnvironment: `node`, }, }, { @@ -8150,6 +8251,11 @@ oracleProperty({ failingLawCalls: 'none', failingLawHook: 'none', failingLawSpins: false, + inputRead: `none`, + keepStamp: false, + inputSteps: NO_INPUT_STEPS, + childWrite: false, + childEnvironment: `node`, }, }, { @@ -8342,6 +8448,11 @@ oracleProperty({ failingLawCalls: 'none', failingLawHook: 'none', failingLawSpins: false, + inputRead: `none`, + keepStamp: false, + inputSteps: NO_INPUT_STEPS, + childWrite: false, + childEnvironment: `node`, }, }, ], @@ -8363,6 +8474,12 @@ oracleProperty({ spinData: false, wholeFile: `none`, fault: `none`, + // No gate input: its states are the daemon-input histories', and the + // witness module's own runs are the costliest of the campaign (the + // Windows job of this one history; review of #133, F6). + inputRead: `none`, + keepStamp: false, + inputSteps: NO_INPUT_STEPS, authored: { stmt: 0, kind: `apply` }, stability: `insertGuard`, steps: null, @@ -11311,6 +11428,188 @@ oracleProperty({ ], }), }, + // Every read is a daemon input (maintainer decision, 2026-11-16, "All + // of them"). File b's verdict also waits on one gate input, and the + // one edit flips only that input from `open` to `shut`: the cold run + // then reports b's mutant as a survivor, and the daemon must not + // reuse a kill that read the open gate (law 9). A second check with + // nothing changed then computes nothing (the `unchanged reuse` law), so + // a daemon that never reuses, which equals a cold run trivially, fails + // too. One history per kind of input, appended last, so the histories + // before them keep their seeds' samples. + ...[ + // A file in the package that the test reads, written back with its + // size and modification time, as `cp -p` leaves it: the daemon must + // see the new text all the same (D10). + [ + `an edit to a file in the package that keeps its size and modification time`, + `inside`, + true, + ], + [ + `an edit to a file outside the package that a test reads`, + `outside`, + false, + ], + [ + `an edit to a file under node_modules that a test reads`, + `module`, + false, + ], + [`an edit to an environment variable that a test reads`, `env`, false], + [ + `an edit to a file the config's plugin reads when the config resolves`, + `pluginConfig`, + false, + ], + // Written back with its size and modification time, too. + [ + `an edit to a file the config's plugin reads when it transforms a test`, + `pluginTransform`, + true, + ], + // A directory's listing, by readdirSync and by opendirSync: the edit + // renames the one file in it. + [`an edit to a directory listing that a test reads`, `listing`, false], + [ + `an edit to a directory a test reads through opendir`, + `opendir`, + false, + ], + // The package's gate file read through a stream, written back with + // its size and modification time. + [`an edit to a file a test reads through a stream`, `stream`, true], + // An input of Vite's own esbuild plugin (review of #133, F1). + [ + `an edit to the tsconfig that Vite's own plugin reads`, + `tsconfig`, + false, + ], + // A listing that the config makes when it loads (review of #133, F2). + [ + `an edit to a directory the config lists when it loads`, + `configListing`, + false, + ], + // A hand edit of a file that the config's plugin writes (review of + // #133, F3): the cold run's plugin writes it again, so the cold + // result does not change. + [ + `a hand edit of a file the config's plugin writes`, + `pluginWrite`, + false, + ], + ].map(([name, inputRead, keepStamp]) => ({ + name, + enters: [ + ...(inputRead === `pluginWrite` + ? [ + `a hand edit of a file the config's plugin writes was checked through the daemon`, + ] + : [ + `edit inputGate changed the cold result`, + `an edit to the ${inputRead} gate input changed the cold result`, + ]), + `an unchanged check through the daemon computed nothing`, + ...(keepStamp + ? [ + `an edit that kept a file's size and modification time changed the cold result`, + ] + : []), + ], + build: (generated) => ({ + ...generated, + functions: [[{ kind: `push`, quote: `'` }]], + containers: [], + overloads: [], + owners: [`b`], + library: [], + libraryOwners: [], + runes: [], + derived: null, + dotGen: false, + dataOwners: [], + exportOwners: [], + importer: `none`, + wholeFile: `none`, + template: false, + tests: [{ ...judging(`b`, `fixed seed`, 1), fn: 0 }], + witness: false, + authored: null, + secondAuthored: false, + fault: `none`, + stability: `none`, + ordinary: false, + native: `none`, + boot: false, + cliPath: `plain`, + concurrentStart: false, + lazyGate: false, + fsRead: `none`, + prePlugin: false, + // A config the plugin can sit in, which Vitest discovers. + configPlace: `discovered`, + inputRead, + keepStamp, + laterSteps: NO_LATER_STEPS, + inputSteps: NO_INPUT_STEPS, + steps: [`inputGate`, `recheck`], + }), + })), + { + // A file that the test's own child process tree wrote earlier in the + // check is no input of the test (maintainer decisions "Own writes + // aren't inputs", 2026-11-17, and "Optimize #133 before merging", + // 2026-11-19): file b reads, as it loads, a file that a node + // grandchild of its test wrote in a new temporary directory, so the + // unchanged recheck through the daemon must reuse b's runs although + // the file's path differs in every run (`unchanged reuse`). + name: `a test that reads a file its child process wrote, rechecked through the daemon`, + enters: [ + `an unchanged check through the daemon computed nothing`, + `an unchanged check through the daemon computed nothing while a test read what its child process wrote`, + ], + build: (generated) => ({ + ...generated, + functions: [[{ kind: `push`, quote: `'` }]], + containers: [], + overloads: [], + owners: [`b`], + library: [], + libraryOwners: [], + runes: [], + derived: null, + dotGen: false, + dataOwners: [], + exportOwners: [], + importer: `none`, + wholeFile: `none`, + template: false, + tests: [{ ...judging(`b`, `fixed seed`, 1), fn: 0 }], + witness: false, + authored: null, + secondAuthored: false, + fault: `none`, + stability: `none`, + ordinary: false, + native: `none`, + boot: false, + cliPath: `plain`, + concurrentStart: false, + lazyGate: false, + fsRead: `none`, + prePlugin: false, + inputRead: `none`, + keepStamp: false, + laterSteps: NO_LATER_STEPS, + inputSteps: NO_INPUT_STEPS, + steps: [`recheck`], + childWrite: true, + // In an environment that transforms file b for the client, as a + // jsdom environment does (`childEnvironment`). + childEnvironment: `client`, + }), + }, ]), }, resolve: resolveHistory, diff --git a/packages/oracles/oracle-gaps/gap-report-static-oracle.property.test.mjs b/packages/oracles/oracle-gaps/gap-report-static-oracle.property.test.mjs index b3ea365d..fb374686 100644 --- a/packages/oracles/oracle-gaps/gap-report-static-oracle.property.test.mjs +++ b/packages/oracles/oracle-gaps/gap-report-static-oracle.property.test.mjs @@ -133,6 +133,7 @@ import { refusalBreach, resolveHistory, removePath, + outsideOf, sourceArgument, caseless, writeFixture, @@ -255,6 +256,7 @@ function defaultOutputsOf(dir, sources) { same: [outs[0] === outs[1], outs[0] === outs[2], outs[1] === outs[2]], } } finally { + rmSync(outsideOf(other), { recursive: true, force: true }) rmSync(other, { recursive: true, force: true }) } } @@ -1003,6 +1005,7 @@ async function driver(plan, observe) { } finally { written.delete(dir) removePath(`${dir}.link`) + rmSync(outsideOf(dir), { recursive: true, force: true }) rmSync(scratch, { recursive: true, force: true }) } } @@ -1272,29 +1275,41 @@ const corruptArguments = (change) => (trace) => { const value = { ...trace[index].value, ...change(trace[index].value) } return trace.map((o, i) => (i === index ? { ...o, value } : o)) } +// Each calibration names the history it corrupts (the framework's history +// binding), so it runs that one history instead of searching the campaign's +// histories for one its corruption applies to: a refusal's corruption needs a +// refused run, which the search found only after a dozen other histories, +// and the draws that #133's appended fields shift made that search longer +// (review of #133, F6). The bound histories reach what each corruption needs: +// a refusal, Svelte runes, owned mutants, a stability rerun, a derived class. const calibrations = [ { name: `a refusal prints a stack trace, as a crash does`, + history: { constructed: `bad arguments: noPackage` }, law: `report-shaped ending`, corrupt: corruptArguments(() => ({ stackFrames: true })), }, { name: `a refusal exits 1, as a crash does`, + history: { constructed: `bad arguments: noPackage` }, law: `report-shaped ending`, corrupt: corruptArguments(() => ({ exit: 1 })), }, { name: `a refusal gives no fix`, + history: { constructed: `bad arguments: noPackage` }, law: `report-shaped ending`, corrupt: corruptArguments(() => ({ fix: undefined, cause: undefined })), }, { name: `a refusal ends without its done line`, + history: { constructed: `bad arguments: noPackage` }, law: `report-shaped ending`, corrupt: corruptArguments(() => ({ done: undefined })), }, { name: `a refusal's fix offers a way around it`, + history: { constructed: `bad arguments: noPackage` }, law: `report-shaped ending`, corrupt: corruptArguments((v) => ({ fix: `${v.fix} Or mark the mutant equivalent.`, @@ -1302,11 +1317,13 @@ const calibrations = [ }, { name: `a refusal names another cause`, + history: { constructed: `bad arguments: noPackage` }, law: `report-shaped ending`, corrupt: corruptArguments(() => ({ cause: `something went wrong` })), }, { name: `a rune is moved from its place`, + history: { constructed: `every static state` }, law: `rune placement`, corrupt: corrupt(`static`, (v) => { if (!v.runes?.includes(`= $`)) return false @@ -1315,11 +1332,13 @@ const calibrations = [ }, { name: `a mutant is dropped`, + history: { constructed: `every static state` }, law: `enumeration`, corrupt: corrupt(`static`, (v) => void v.mutants.shift()), }, { name: `production code is marked as probe code`, + history: { constructed: `every static state` }, law: `probe-only code`, corrupt: corrupt(`static`, (v) => { const m = v.mutants.find((x) => !x.probe) @@ -1329,6 +1348,7 @@ const calibrations = [ }, { name: `an owned mutant is reported unowned`, + history: { constructed: `every static state` }, law: `ownership`, corrupt: corrupt(`static`, (v) => { const m = v.mutants.find((x) => !x.probe && x.owned) @@ -1338,6 +1358,7 @@ const calibrations = [ }, { name: `a derived class's super call is made conditional`, + history: { constructed: `a plain-parameter derived class` }, law: `super unconditional`, corrupt: corrupt(`derived`, (v) => { const run = v.mutants[0]?.runs[0] @@ -1349,6 +1370,7 @@ const calibrations = [ }, { name: `the instrumented derived class differs with no mutant active`, + history: { constructed: `a plain-parameter derived class` }, law: `no-mutant behavior`, corrupt: corrupt(`derived`, (v) => { v.instrumented[0] = { error: `Must call super constructor` } @@ -1356,6 +1378,7 @@ const calibrations = [ }, { name: `a key drops its statement`, + history: { constructed: `every static state` }, law: `keys`, corrupt: corrupt(`static`, (v) => { v.mutants[0].key = v.mutants[0].key.slice( @@ -1366,6 +1389,7 @@ const calibrations = [ }, { name: `an edit moves a key`, + history: { constructed: `every static state` }, law: `key stability`, corrupt: (trace) => { const before = trace.find((o) => o.checkpoint === `static`)?.value @@ -1849,7 +1873,10 @@ oracleProperty({ driver, check, calibrations, - timeout: 120_000, + // A loud wall-clock backstop, not a budget (M-6): about twice the + // generated units' measured cost on CI (85 to 121 s), so a unit is never + // cut off by load before its verdict (review of #133, F6; #144). + timeout: 240_000, }) // ## Mutant anchors stay inside their declaration diff --git a/packages/oracles/oracle-gaps/history-fingerprint.json b/packages/oracles/oracle-gaps/history-fingerprint.json index d5d43394..09c196fc 100644 --- a/packages/oracles/oracle-gaps/history-fingerprint.json +++ b/packages/oracles/oracle-gaps/history-fingerprint.json @@ -86,7 +86,12 @@ ["failingLawCalls", "3f853c3b6c6b89b5"], ["failingLawHook", "4417bd05ca78a981"], ["failingLawSpins", "a52fc926e1e1704b"], - ["faults", "484207f844e32250"] + ["faults", "484207f844e32250"], + ["inputRead", "edba1fe5f65d4573"], + ["keepStamp", "8f39ed756b8c1587"], + ["inputSteps", "0c3b8c28396b30de"], + ["childWrite", "dfc2c2d5f3dec106"], + ["childEnvironment", "39e7d4a78e66adab"] ], "histories": [ ["functions", "66c0e9c56951c377"], @@ -175,6 +180,11 @@ ["failingLawCalls", "3f853c3b6c6b89b5"], ["failingLawHook", "4417bd05ca78a981"], ["failingLawSpins", "a52fc926e1e1704b"], - ["faults", "484207f844e32250"] + ["faults", "484207f844e32250"], + ["inputRead", "edba1fe5f65d4573"], + ["keepStamp", "8f39ed756b8c1587"], + ["inputSteps", "0c3b8c28396b30de"], + ["childWrite", "dfc2c2d5f3dec106"], + ["childEnvironment", "39e7d4a78e66adab"] ] } diff --git a/packages/oracles/oracle-gaps/inputs.mjs b/packages/oracles/oracle-gaps/inputs.mjs new file mode 100644 index 00000000..42f06b5b --- /dev/null +++ b/packages/oracles/oracle-gaps/inputs.mjs @@ -0,0 +1,236 @@ +// What a run reads, as the daemon keys it. Every read is a daemon input +// (maintainer decision, 2026-11-16, "All of them"): a file read through fs +// on any path, node_modules included, an environment variable, and what +// the config's own plugins read. So when one changes between two checks, +// the next check through the daemon reports what a cold run reports (the +// CLI oracle's law 9). +// +// An input's key is `fs:` for a file, hashed by its text (or as +// `not a file`, or `missing`), `dir:` for a directory's listing, +// hashed by its entries' names and kinds, or `dirs:` for a recursive +// one, `stat:` for a test of whether a path exists and what it is, +// hashed by that, `env:` for a variable, hashed by its value, or `env:*` for the +// set of names, which code reads when it lists the environment. The harness (capture-setup.mjs) watches a test's reads in +// its worker, and the session (check.mjs) watches what the config and its +// plugins read in the CLI's process. Both files are copied beside the +// harness with this one. +import { createHash } from 'node:crypto' +import fs from 'node:fs' +import { syncBuiltinESMExports } from 'node:module' +import { basename, dirname, join, resolve } from 'node:path' +import { fileURLToPath } from 'node:url' +import { posix } from './paths.mjs' + +// The calls that read a file (a stream's too, by the whole file). Each is +// taken once per process, before a wrapper replaces it, so hashing a file is +// not itself a read. +const reads = [ + [fs, [`readFileSync`, `readFile`, `createReadStream`]], + [fs.promises, [`readFile`]], +] +// The calls that test whether a file exists and what it is: an input by its +// existence and kind (G42's stat family), not by its text, so that Vite's +// resolution, which stats each module it imports, does not make every +// module's text an input of every run. +const stats = [ + [fs, [`existsSync`, `statSync`]], + [fs.promises, [`stat`]], +] +// The calls that list a directory. +const listings = [ + [fs, [`readdirSync`, `readdir`, `opendirSync`, `opendir`]], + [fs.promises, [`readdir`, `opendir`]], +] +// The calls that write a file's text. A file that a reader wrote before it +// reads it holds the reader's own output, which follows from the reader's +// other inputs, so that read is no input: a test's temporary file, or the +// config that Vite bundles into a temporary file and then imports. +const writes = [ + [fs, [`writeFileSync`, `writeFile`, `appendFileSync`, `appendFile`]], + [fs.promises, [`writeFile`, `appendFile`]], +] +const original = (globalThis.__oracleGapsOriginalFs ??= { + readFileSync: fs.readFileSync, + statSync: fs.statSync, + readdirSync: fs.readdirSync, + realpathSync: fs.realpathSync.native, +}) +const sha1 = (data) => createHash(`sha1`).update(data).digest(`hex`) + +/** + * A file's input hash now, never from a cache: the hash of its text, or + * `not a file` (a test can stat a directory, whose input is that a + * directory is there), or `missing`. + */ +export function fileHash(path) { + try { + return original.statSync(path).isFile() + ? sha1(original.readFileSync(path)) + : `not a file` + } catch { + return `missing` + } +} + +/** + * A directory's input hash now: that of its entries' names and kinds, every + * level's for a recursive listing, or `not a directory`, or `missing`. + */ +function listingHash(path, recursive) { + try { + return sha1( + original + .readdirSync(path, { withFileTypes: true, recursive }) + // The runner's own entries (its session directory) are no input. + .filter( + (entry) => + !isRunnerFile(`${posix(entry.parentPath ?? path)}/${entry.name}/`), + ) + .map( + (entry) => + `${posix(entry.parentPath ?? path)}/${entry.name}\0${entry.isDirectory() ? `d` : entry.isSymbolicLink() ? `l` : `f`}`, + ) + .sort() + .join(`\0`), + ) + } catch (error) { + return error?.code === `ENOTDIR` ? `not a directory` : `missing` + } +} + +/** A file's or a directory's input hash now, by its key. */ +export const inputHash = (key) => + key.startsWith(`fs:`) + ? fileHash(key.slice(3)) + : key.startsWith(`stat:`) + ? kindOf(key.slice(5)) + : key.startsWith(`dirs:`) + ? listingHash(key.slice(5), true) + : listingHash(key.slice(4), false) + +/** A path's existence and kind now. */ +function kindOf(path) { + try { + const stat = original.statSync(path) + return stat.isFile() ? `file` : stat.isDirectory() ? `directory` : `other` + } catch { + return `missing` + } +} + +/** A variable's input hash under `env`, or for `*`, that of its names. */ +export const envHash = ( + name, + env = globalThis.__oracleGapsEnv ?? process.env, +) => + sha1( + name === `*` + ? Object.keys(env).sort().join(`\0`) + : `${env[name] === undefined ? `unset` : `=${env[name]}`}`, + ) + +// The runner's own files: a session directory (`.oracle-gaps-/`, which +// holds this file) and the copies of test files +// (`.oracle-gaps---`). A user's path that only contains +// `.oracle-gaps` is an input like any other. +const isRunnerFile = (path) => /\/\.oracle-gaps-\d+[-/]/.test(path) + +/** + * A wrapper keeps every own property of the function it wraps (its name + * and length, which code that dispatches on arity reads, or + * `util.promisify.custom`), so a test that passes alone passes under the + * capture (law 3; review of #55). + */ +export function keepProperties(from, to) { + for (const key of Reflect.ownKeys(from)) + if (key !== `prototype`) + Object.defineProperty(to, key, Object.getOwnPropertyDescriptor(from, key)) + return to +} + +/** + * Watches this process's reads from now on: each read calls `record(key)` + * with the input's key, and each write of a file or a variable + * `record(key, true)`, the + * `record` of the latest call. The wrappers are + * installed once per process. A file's path is the path rule's (paths.mjs), + * and the runner's own files are left out. An ES module's + * `import { readFileSync } from 'node:fs'` reads the wrappers too. + */ +export function watchReads(record) { + globalThis.__oracleGapsRecord = record + if (globalThis.__oracleGapsWatching) return + globalThis.__oracleGapsWatching = true + record = (key, write) => globalThis.__oracleGapsRecord(key, write) + const watched = (target, kind, options) => { + const write = kind === `write` + let path + try { + if (target instanceof URL) path = resolve(fileURLToPath(target)) + else if (typeof target === `string`) path = resolve(target) + else if (Buffer.isBuffer(target)) path = resolve(target.toString()) + } catch { + return + } + if (path === undefined || isRunnerFile(posix(path))) return + const prefix = + kind === `stat` + ? `stat` + : kind !== `list` + ? `fs` + : options?.recursive + ? `dirs` + : `dir` + record(`${prefix}:${posix(path)}`, write) + // A written file is also known by its directory's real path, which a + // later read through a link, or an import by its real URL, names. + if (write) + try { + record( + `fs:${posix(join(original.realpathSync(dirname(path)), basename(path)))}`, + write, + ) + } catch { + // No directory to write in: the write fails as it would. + } + } + for (const [calls, kind] of [ + [reads, `read`], + [stats, `stat`], + [listings, `list`], + [writes, `write`], + ]) + for (const [owner, names] of calls) + for (const name of names) { + const call = owner[name] + owner[name] = keepProperties(call, function (target, ...rest) { + watched(target, kind, rest[0]) + return call.call(this, target, ...rest) + }) + } + syncBuiltinESMExports() + // A variable read by name, a test of whether it is set, and a listing of + // the names, which reads the set of names. + // The environment itself, which hashing reads without being watched. + globalThis.__oracleGapsEnv = process.env + process.env = new Proxy(process.env, { + get(env, name) { + if (typeof name === `string`) record(`env:${name}`) + return Reflect.get(env, name) + }, + has(env, name) { + if (typeof name === `string`) record(`env:${name}`) + return Reflect.has(env, name) + }, + ownKeys(env) { + record(`env:*`) + return Reflect.ownKeys(env) + }, + // A write goes to the environment itself, which keeps its own rules + // (a value is a string). A variable the reader set is its own output. + set(env, name, value) { + if (typeof name === `string`) record(`env:${name}`, true) + return Reflect.set(env, name, value) + }, + }) +} diff --git a/packages/oracles/scripts/e2e-shards.mjs b/packages/oracles/scripts/e2e-shards.mjs index 2cd10740..9fba527a 100644 --- a/packages/oracles/scripts/e2e-shards.mjs +++ b/packages/oracles/scripts/e2e-shards.mjs @@ -118,6 +118,47 @@ export const shards = { `fixed seed 20261105: an edit to data a test reads through fs (statDir)`, `random seed: an edit to data a test reads through fs (statDir)`, `determinism: constructed history: an edit to data a test reads through fs (statDir)`, + // The daemon-input histories (law 9, every read is a daemon input): about + // 25 s each on the Arca pool, fixed seed. + `fixed seed 20261105: an edit to a file in the package that keeps its size and modification time`, + `random seed: an edit to a file in the package that keeps its size and modification time`, + `determinism: constructed history: an edit to a file in the package that keeps its size and modification time`, + `fixed seed 20261105: an edit to a file outside the package that a test reads`, + `random seed: an edit to a file outside the package that a test reads`, + `determinism: constructed history: an edit to a file outside the package that a test reads`, + `fixed seed 20261105: an edit to a file under node_modules that a test reads`, + `random seed: an edit to a file under node_modules that a test reads`, + `determinism: constructed history: an edit to a file under node_modules that a test reads`, + `fixed seed 20261105: an edit to an environment variable that a test reads`, + `random seed: an edit to an environment variable that a test reads`, + `determinism: constructed history: an edit to an environment variable that a test reads`, + `fixed seed 20261105: an edit to a file the config's plugin reads when the config resolves`, + `random seed: an edit to a file the config's plugin reads when the config resolves`, + `determinism: constructed history: an edit to a file the config's plugin reads when the config resolves`, + `fixed seed 20261105: an edit to a file the config's plugin reads when it transforms a test`, + `random seed: an edit to a file the config's plugin reads when it transforms a test`, + `determinism: constructed history: an edit to a file the config's plugin reads when it transforms a test`, + `fixed seed 20261105: an edit to a directory listing that a test reads`, + `random seed: an edit to a directory listing that a test reads`, + `determinism: constructed history: an edit to a directory listing that a test reads`, + `fixed seed 20261105: an edit to a directory a test reads through opendir`, + `random seed: an edit to a directory a test reads through opendir`, + `determinism: constructed history: an edit to a directory a test reads through opendir`, + `fixed seed 20261105: an edit to a file a test reads through a stream`, + `random seed: an edit to a file a test reads through a stream`, + `determinism: constructed history: an edit to a file a test reads through a stream`, + "fixed seed 20261105: an edit to the tsconfig that Vite's own plugin reads", + "random seed: an edit to the tsconfig that Vite's own plugin reads", + "determinism: constructed history: an edit to the tsconfig that Vite's own plugin reads", + 'fixed seed 20261105: an edit to a directory the config lists when it loads', + 'random seed: an edit to a directory the config lists when it loads', + 'determinism: constructed history: an edit to a directory the config lists when it loads', + "fixed seed 20261105: a hand edit of a file the config's plugin writes", + "random seed: a hand edit of a file the config's plugin writes", + "determinism: constructed history: a hand edit of a file the config's plugin writes", + 'fixed seed 20261105: a test that reads a file its child process wrote, rechecked through the daemon', + 'random seed: a test that reads a file its child process wrote, rechecked through the daemon', + 'determinism: constructed history: a test that reads a file its child process wrote, rechecked through the daemon', // Added with the CLI's parent-config discovery (not yet measured). `fixed seed 20261105: a package whose parent directory has its config`, `random seed: test.projects in a parent's config`, diff --git a/packages/oracles/scripts/pr-shards.mjs b/packages/oracles/scripts/pr-shards.mjs index 4ae92192..0832c6b3 100644 --- a/packages/oracles/scripts/pr-shards.mjs +++ b/packages/oracles/scripts/pr-shards.mjs @@ -27,6 +27,24 @@ import { tmpdir } from 'node:os' import { dirname, join } from 'node:path' import { fileURLToPath } from 'node:url' +// The constructed histories of the edits of each kind of daemon input +// (gap-report-oracle.property.test.mjs). +const daemonInputUnits = [ + 'an edit to a file in the package that keeps its size and modification time', + 'an edit to a file outside the package that a test reads', + 'an edit to a file under node_modules that a test reads', + 'an edit to an environment variable that a test reads', + "an edit to a file the config's plugin reads when the config resolves", + "an edit to a file the config's plugin reads when it transforms a test", + 'an edit to a directory listing that a test reads', + 'an edit to a directory a test reads through opendir', + 'an edit to a file a test reads through a stream', + "an edit to the tsconfig that Vite's own plugin reads", + 'an edit to a directory the config lists when it loads', + "a hand edit of a file the config's plugin writes", + // A file the test's child process wrote (own writes of the process tree). + 'a test that reads a file its child process wrote, rechecked through the daemon', +] const escape = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, `\\$&`) const anyOf = (names) => `(?:${names.map(escape).join(`|`)})` const rest = Symbol(`rest`) @@ -391,6 +409,10 @@ export const partitions = { ]), // The rest: 401 s of weight, and any unit added later. 4: rest, + // The edits of a daemon input that every read makes one (maintainer + // decision, 2026-11-16, "Every read is a daemon input"), one unit per + // kind of input: 73 s on the CI runner. + 5: anyOf(daemonInputUnits), }, }, // The end-to-end gap oracle's random units, which every pull request runs @@ -498,6 +520,8 @@ export const partitions = { ]), // The rest: 560 s of weight, and any unit added later. 4: rest, + // The daemon-input units (see the fixed-seed partition). + 5: anyOf(daemonInputUnits), }, }, // The end-to-end gap oracle's determinism units, which every pull request @@ -628,6 +652,8 @@ export const partitions = { ]), // The rest: 471 s of weight, and any unit added later. 7: rest, + // The daemon-input units (see the fixed-seed partition). + 8: anyOf(daemonInputUnits.map((name) => `constructed history: ${name}`)), }, }, 'oracle-gaps-static-windows': { @@ -885,6 +911,10 @@ export const partitions = { 'two runs on one output directory', 'a stream log that cannot be written', 'a start refuses an empty claim', + daemonInputUnits[0], + daemonInputUnits[1], + daemonInputUnits[9], + daemonInputUnits[12], ]), 7: anyOf([ 'a daemon pause that cannot engage', @@ -927,6 +957,10 @@ export const partitions = { 'a stop with the default output directory', 'a daemon check with the default output directory', 'a daemon check with the default output directory, unsupervised', + daemonInputUnits[2], + daemonInputUnits[3], + daemonInputUnits[10], + daemonInputUnits[11], ]), 9: anyOf([ 'a lazy module loaded before a hang in the same batch', @@ -945,6 +979,11 @@ export const partitions = { 'a stop before the CLI starts', 'a stop by SIGTERM as the CLI starts', 'a start refuses a dangling claim', + daemonInputUnits[4], + daemonInputUnits[5], + daemonInputUnits[6], + daemonInputUnits[7], + daemonInputUnits[8], 'a stop before the CLI starts, after a stopped check', 'a run after a killed CLI', ]), From 8c770da920c2ea13dbfbe05c0f3bfffd261fdcdf Mon Sep 17 00:00:00 2001 From: Kyle Mathews Date: Tue, 1 Dec 2026 22:02:17 -0700 Subject: [PATCH 02/51] test(oracle-gaps): daemon inputs read by stat, append, child process and require, oracle first (WIP, not pushed) Seven constructed histories for the reads that the review of #133 found unkeyed (133-1, 133-2, 133-3, 133-6). On the rebased commit they fail, as they should on production they were written against: - `stat`, `statAsync`, `statCallback`: a test reads the gate's size through statSync, fs/promises stat, and the callback stat (RED: incremental equals cold after inputGate). - `append`, `flagAppend`: a test appends to the gate, then reads it (RED). - `childRead`: a node child process reads the gate (RED). - `required`: a JSON gate loaded with createRequire. It passes on the rebased commit: the file read is recorded. The production changes that follow the oracle, in this same commit: - inputs.mjs: `stat:` (existsSync) stays kind-only. The statSync, stat and fs/promises stat calls key `statx:` by the file's size, times, identity, and mode. A directory is keyed by its kind alone. - inputs.mjs and capture-setup.mjs: an append reads the text it adds to before it writes, so that text is an input unless the copy wrote it first. - child-writes.mjs and capture-setup.mjs: child processes log their reads with the hash taken at read time (`R`) and their writes (`W`), and the copy folds the log in order. - check.mjs: the same append rule on the CLI side; a write marks the file written even after a read in the same check. State: the seven histories are still RED on fixed and random seeds, with "unchanged reuse" at the recheck (the daemon computes runs that owe none). Not pushed. See /tmp/gap-pr/pr133-eval-ledger.md. Co-authored-by: Isaac --- .../oracles/oracle-gaps/capture-setup.mjs | 48 +++-- packages/oracles/oracle-gaps/check.mjs | 13 +- packages/oracles/oracle-gaps/child-writes.mjs | 26 ++- .../oracle-gaps/constructed-order.json | 9 +- .../oracle-gaps/gap-report-model-oracle.mjs | 61 ++++++- .../gap-report-oracle.property.test.mjs | 165 +++++++++++------- .../oracle-gaps/history-fingerprint.json | 4 +- packages/oracles/oracle-gaps/inputs.mjs | 84 +++++++-- packages/oracles/scripts/e2e-shards.mjs | 21 +++ packages/oracles/scripts/pr-shards.mjs | 14 ++ 10 files changed, 340 insertions(+), 105 deletions(-) diff --git a/packages/oracles/oracle-gaps/capture-setup.mjs b/packages/oracles/oracle-gaps/capture-setup.mjs index 9d2a4ecc..d6285a9a 100644 --- a/packages/oracles/oracle-gaps/capture-setup.mjs +++ b/packages/oracles/oracle-gaps/capture-setup.mjs @@ -298,26 +298,50 @@ const childLog = join( `child-writes-${process.pid}-${threadId}-${(globalThis.__oracleGapsCopies = (globalThis.__oracleGapsCopies ?? 0) + 1)}.log`, ) let childRead = 0 -/** Whether the copy or a process it started wrote the file `key` names. */ -function ownOutput(key) { - const file = key.replace(/^stat:/, `fs:`) - if (wrote.has(file)) return true +/** + * Folds the log lines that the copy's process tree wrote since the last fold, + * in the order they were written (child-writes.mjs). A child's read of a file + * that the tree had not written is an input of the copy, with the hash the + * child took at that read; a child's write makes the file the tree's own + * output. A line still being written waits for the next fold (133-2). + */ +function foldChildren() { let text try { text = globalThis.__oracleGapsOriginalFs.readFileSync(childLog, `utf8`) } catch { - return false + return + } + const end = text.lastIndexOf(`\n`) + if (end < childRead) return + const reads = globalThis.__oracleGapsReads + for (const line of text.slice(childRead, end).split(`\n`)) { + if (line === ``) continue + const [op, key, hash] = JSON.parse(line) + if (op === `W`) wrote.add(key) + else if (!wrote.has(key) && !reads.has(key)) reads.set(key, hash) } - for (const line of text.slice(childRead).split(`\n`)) - if (line !== ``) wrote.add(line) - childRead = text.length - return wrote.has(file) + childRead = end + 1 +} +/** + * Whether the copy or a process it started wrote the file that `key` names: + * a stat of a file is a read of the file (`stat:` and `statx:`). + */ +function ownOutput(key) { + foldChildren() + return wrote.has(key.replace(/^(stat|statx):/, `fs:`)) } watchReads((key, write) => { const reads = globalThis.__oracleGapsReads - if (write) wrote.add(key) - else if (!reads.has(key) && !wrote.has(key) && !ownOutput(key)) + // A read, or the read that an append makes of the text it adds to (133-3), + // is an input unless the copy or its process tree wrote the file first. + if (write !== true && !reads.has(key) && !wrote.has(key) && !ownOutput(key)) reads.set(key, key.startsWith(`env:`) ? null : inputHash(key)) + if (write) { + // The child reads before this write come first, so they are inputs. + foldChildren() + wrote.add(key) + } }) if (!globalThis.__oracleGapsChildren) { globalThis.__oracleGapsChildren = true @@ -1156,6 +1180,8 @@ afterAll(() => { // module that its context serves from that file, which can differ from // the file's text (fourth review of #55, F-A2). A variable it read has no // hash here (`env:`, null). + // The child processes' reads after the copy's last own read or write. + foldChildren() const readAt = Object.fromEntries(globalThis.__oracleGapsReads) appendClosingRow( `${JSON.stringify({ file: thisFile, closed: true, at: realNow(), loaded, readAt, ...(skippedCopy ? { skipped: true } : {}) })}\n`, diff --git a/packages/oracles/oracle-gaps/check.mjs b/packages/oracles/oracle-gaps/check.mjs index b97ef020..17b70e35 100644 --- a/packages/oracles/oracle-gaps/check.mjs +++ b/packages/oracles/oracle-gaps/check.mjs @@ -531,10 +531,10 @@ export async function openSession(pkg, pause = async () => {}) { const at = reading.getStore() if (write && key.startsWith(`env:`)) wrote.add(key) const reads = at?.hook || at?.done ? hookReads : warmReads - if (at === undefined || at.discovery || key === at.module || reads.has(key)) - return - if (write) wrote.add(key) - else if (!wrote.has(key)) { + if (at === undefined || at.discovery || key === at.module) return + // A read, or the read that an append makes of the text it adds to + // (133-3), is an input unless the session wrote the file first. + if (write !== true && !wrote.has(key) && !reads.has(key)) { const hash = key.startsWith(`env:`) ? reads === hookReads ? envHash(key.slice(4)) @@ -543,6 +543,9 @@ export async function openSession(pkg, pause = async () => {}) { reads.set(key, hash) if (reads === hookReads) hookLog.push([key, hash]) } + // A write is the session's, even when the file was read before it in + // this check: it must still hold its text at the next check (`written`). + if (write) wrote.add(key) }) // Runs `work` as a warm under `reading`. const warming = async (work) => { @@ -722,7 +725,7 @@ export default async (env) => { return logHolds(id, Number(n)) >= Number(n) ? `held` : `changed` } if (path.startsWith(`shared:`)) return sharedHolds(path, index) - if (/^(dir|dirs|stat):/.test(path)) return inputHash(path) + if (/^(dir|dirs|stat|statx):/.test(path)) return inputHash(path) const text = globalThis.__oracleGapsServe[index]?.get(path) ?? globalThis.__oracleGapsSchemata.get(path) diff --git a/packages/oracles/oracle-gaps/child-writes.mjs b/packages/oracles/oracle-gaps/child-writes.mjs index 7a2fce60..9321c4de 100644 --- a/packages/oracles/oracle-gaps/child-writes.mjs +++ b/packages/oracles/oracle-gaps/child-writes.mjs @@ -1,19 +1,29 @@ -// What a test's own child processes write, at any depth. The harness +// What a test's own child processes read and write, at any depth. The harness // (capture-setup.mjs) preloads this file into every Node process that a test // starts (`--import` in NODE_OPTIONS, which each child passes on to its own -// children) and names a log per copy (ORACLE_GAPS_CHILD_WRITES). Each file -// that such a process writes goes into the log as its input key, before the -// write, so the copy knows that a later read of it reads its own process -// tree's output, which is no input (maintainer decisions "Own writes aren't -// inputs", 2026-11-17, and "Optimize #133 before merging", 2026-11-19). +// children) and names a log per copy (ORACLE_GAPS_CHILD_WRITES). Each line is +// a JSON array, written as the process makes the call: +// ["R", key, hash] a read of the input `key`, hashed now, before the read; +// ["W", key] a write of the file `key`, which makes it the tree's own +// output, so a later read of it is no input. +// An append reads the text it adds to, then writes (`R` and then `W`), so the +// text is an input and the file is still the tree's output after the write. +// The copy folds the log in order (capture-setup.mjs, foldChildren): a read +// the tree had not written is an input of the test, whichever process made +// it (maintainer decisions "Own writes aren't inputs", 2026-11-17, "Optimize +// #133 before merging", 2026-11-19; review of #133, F-2). An environment +// variable is the CLI's to watch: the whole environment restarts the daemon. // The log is written through a file descriptor, which no wrapper watches. import { openSync, writeSync } from 'node:fs' -import { watchReads } from './inputs.mjs' +import { inputHash, watchReads } from './inputs.mjs' const log = process.env.ORACLE_GAPS_CHILD_WRITES if (log) { const fd = openSync(log, `a`) + const put = (line) => writeSync(fd, `${JSON.stringify(line)}\n`) watchReads((key, write) => { - if (write && key.startsWith(`fs:`)) writeSync(fd, `${key}\n`) + if (key.startsWith(`env:`)) return + if (write !== true) put([`R`, key, inputHash(key)]) + if (write) put([`W`, key]) }) } diff --git a/packages/oracles/oracle-gaps/constructed-order.json b/packages/oracles/oracle-gaps/constructed-order.json index 9b28adf4..df6d8e8e 100644 --- a/packages/oracles/oracle-gaps/constructed-order.json +++ b/packages/oracles/oracle-gaps/constructed-order.json @@ -121,6 +121,13 @@ "an edit to the tsconfig that Vite's own plugin reads", "an edit to a directory the config lists when it loads", "a hand edit of a file the config's plugin writes", - "a test that reads a file its child process wrote, rechecked through the daemon" + "a test that reads a file its child process wrote, rechecked through the daemon", + "an edit to a file the test stats for its size, by statSync", + "an edit to a file the test stats for its size, by fs/promises stat", + "an edit to a file the test stats for its size, by the callback stat", + "an edit to a file a test appends to, then reads", + "an edit to a file a test appends to with flag a, then reads", + "an edit to a file a test requires as JSON", + "an edit to a file that a test child process reads" ] } diff --git a/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs b/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs index e3f41e80..aff37b3b 100644 --- a/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs +++ b/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs @@ -1223,6 +1223,13 @@ const drawn = fc.record({ `tsconfig`, `configListing`, `pluginWrite`, + `stat`, + `statAsync`, + `statCallback`, + `append`, + `flagAppend`, + `required`, + `childRead`, ), // Each write of a gate file keeps its size (`open` and `shut` have one // length) and gets back one fixed modification time, as `cp -p`, `rsync @@ -5733,6 +5740,16 @@ const gateText = (open) => // The modification time, in seconds, that every write of a gate file gets // back under `keepStamp`. const GATE_STAMP = 1_700_000_000 +// The kinds that read the gate file's size and not its text (`stat`, the +// promise and callback forms of `stat`): their `shut` text is longer than +// `open`, so the size tells the two apart, and an edit changes the size. The +// size of `open` is the reader's constant. +const SIZE_GATES = [`stat`, `statAsync`, `statCallback`] +const OPEN_SIZE = gateText(true).length +const gateTextFor = (kind, open) => + SIZE_GATES.includes(kind) && !open + ? `${JSON.stringify({ gate: `shut`, pad: `....` })}\n` + : gateText(open) // A fixture path under the directory beside the package (`outsideOf`), // which is outside it; writeFixture places it there. const BESIDE = `/` @@ -5745,6 +5762,13 @@ const gateFiles = { module: `node_modules/gap-gate/gate.json`, pluginConfig: `tests/plugin-gate.json`, pluginTransform: `tests/plugin-gate.json`, + stat: `tests/gate.json`, + statAsync: `tests/gate.json`, + statCallback: `tests/gate.json`, + append: `tests/gate.json`, + flagAppend: `tests/gate.json`, + required: `tests/gate.json`, + childRead: `tests/gate.json`, } /** Whether the gate input is one that the config's own plugin reads. */ const pluginGated = (history) => @@ -5818,6 +5842,36 @@ const inputReads = { `import { opendirSync as openGate } from 'node:fs'`, `const readInput = async () => { const dir = openGate(new URL('./gate-dir/', import.meta.url)); const names: Array = []; for (let entry = dir.readSync(); entry; entry = dir.readSync()) names.push(entry.name); dir.closeSync(); return { open: names.includes('open') } }`, ], + stat: [ + `import { statSync as statGate } from 'node:fs'`, + `const readInput = async () => ({ open: statGate(new URL('./gate.json', import.meta.url)).size === ${OPEN_SIZE} })`, + ], + statAsync: [ + `import { stat as statGateAsync } from 'node:fs/promises'`, + `const readInput = async () => ({ open: (await statGateAsync(new URL('./gate.json', import.meta.url))).size === ${OPEN_SIZE} })`, + ], + statCallback: [ + `import { stat as statGateCallback } from 'node:fs'`, + `const readInput = () => new Promise((resolve, reject) => statGateCallback(new URL('./gate.json', import.meta.url), (error, stats) => (error ? reject(error) : resolve({ open: stats.size === ${OPEN_SIZE} }))))`, + ], + append: [ + `import { appendFileSync as appendGate, readFileSync as readGate } from 'node:fs'`, + `const readInput = async () => { const url = new URL('./gate.json', import.meta.url); appendGate(url, ''); return { open: JSON.parse(readGate(url, 'utf8')).gate === 'open' } }`, + ], + flagAppend: [ + `import { writeFileSync as writeGate, readFileSync as readGate } from 'node:fs'`, + `const readInput = async () => { const url = new URL('./gate.json', import.meta.url); writeGate(url, '', { flag: 'a' }); return { open: JSON.parse(readGate(url, 'utf8')).gate === 'open' } }`, + ], + required: [ + `import { createRequire as requireFrom } from 'node:module'`, + `import { fileURLToPath as gatePath } from 'node:url'`, + `const readInput = async () => { const path = gatePath(new URL('./gate.json', import.meta.url)); const req = requireFrom(import.meta.url); delete req.cache[path]; return { open: req(path).gate === 'open' } }`, + ], + childRead: [ + `import { execFileSync as runGateChild } from 'node:child_process'`, + `import { fileURLToPath as gatePath } from 'node:url'`, + `const readInput = async () => ({ open: JSON.parse(runGateChild(process.execPath, ['-e', "process.stdout.write(require('node:fs').readFileSync(process.argv[1], 'utf8'))", gatePath(new URL('./gate.json', import.meta.url))], { encoding: 'utf8' })).gate === 'open' })`, + ], } // File b's read of a file that its test's child process tree wrote // (`childWrite`): the grandchild writes `child.txt` in a new directory under @@ -6766,8 +6820,11 @@ function fixtureFiles(plan, state = initialState(plan)) { ? {} : { [gateFiles[plan.inputRead]]: plan.keepStamp - ? { text: gateText(state.inputOpen), mtime: GATE_STAMP } - : gateText(state.inputOpen), + ? { + text: gateTextFor(plan.inputRead, state.inputOpen), + mtime: GATE_STAMP, + } + : gateTextFor(plan.inputRead, state.inputOpen), }), // A workspace dependency with module state, linked through node_modules. 'deps/state-dep/package.json': manifest({ diff --git a/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs b/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs index 605a2867..221b57c4 100644 --- a/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs +++ b/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs @@ -3211,9 +3211,16 @@ async function incremental(dir, plan, cli, copy, observe, states) { // Only a gate file keeps its stamp; a listing's edit renames a file. if ( plan.keepStamp && - ![`env`, `listing`, `opendir`, `tsconfig`, `configListing`].includes( - plan.inputRead, - ) + ![ + `env`, + `listing`, + `opendir`, + `tsconfig`, + `configListing`, + `stat`, + `statAsync`, + `statCallback`, + ].includes(plan.inputRead) ) states.add( `an edit that kept a file's size and modification time changed the cold result`, @@ -6987,6 +6994,13 @@ const inputKinds = [ `stream`, `tsconfig`, `configListing`, + `stat`, + `statAsync`, + `statCallback`, + `append`, + `flagAppend`, + `required`, + `childRead`, ] // Law 9's states that a constructed history of their own reaches, not the // edit sequence: the mid-run edit, and an edit to data a test reads through @@ -7634,6 +7648,64 @@ const witnessEditSequence = (witness) => (generated) => ({ steps: witnessSteps, }) +const gateKindHistory = ([name, inputRead, keepStamp]) => ({ + name, + enters: [ + ...(inputRead === `pluginWrite` + ? [ + `a hand edit of a file the config's plugin writes was checked through the daemon`, + ] + : [ + `edit inputGate changed the cold result`, + `an edit to the ${inputRead} gate input changed the cold result`, + ]), + `an unchanged check through the daemon computed nothing`, + ...(keepStamp + ? [ + `an edit that kept a file's size and modification time changed the cold result`, + ] + : []), + ], + build: (generated) => ({ + ...generated, + functions: [[{ kind: `push`, quote: `'` }]], + containers: [], + overloads: [], + owners: [`b`], + library: [], + libraryOwners: [], + runes: [], + derived: null, + dotGen: false, + dataOwners: [], + exportOwners: [], + importer: `none`, + wholeFile: `none`, + template: false, + tests: [{ ...judging(`b`, `fixed seed`, 1), fn: 0 }], + witness: false, + authored: null, + secondAuthored: false, + fault: `none`, + stability: `none`, + ordinary: false, + native: `none`, + boot: false, + cliPath: `plain`, + concurrentStart: false, + lazyGate: false, + fsRead: `none`, + prePlugin: false, + // A config the plugin can sit in, which Vitest discovers. + configPlace: `discovered`, + inputRead, + keepStamp, + laterSteps: NO_LATER_STEPS, + inputSteps: NO_INPUT_STEPS, + steps: [`inputGate`, `recheck`], + }), +}) + oracleProperty({ id: `oracle-gaps.report`, law: { @@ -11499,63 +11571,7 @@ oracleProperty({ `pluginWrite`, false, ], - ].map(([name, inputRead, keepStamp]) => ({ - name, - enters: [ - ...(inputRead === `pluginWrite` - ? [ - `a hand edit of a file the config's plugin writes was checked through the daemon`, - ] - : [ - `edit inputGate changed the cold result`, - `an edit to the ${inputRead} gate input changed the cold result`, - ]), - `an unchanged check through the daemon computed nothing`, - ...(keepStamp - ? [ - `an edit that kept a file's size and modification time changed the cold result`, - ] - : []), - ], - build: (generated) => ({ - ...generated, - functions: [[{ kind: `push`, quote: `'` }]], - containers: [], - overloads: [], - owners: [`b`], - library: [], - libraryOwners: [], - runes: [], - derived: null, - dotGen: false, - dataOwners: [], - exportOwners: [], - importer: `none`, - wholeFile: `none`, - template: false, - tests: [{ ...judging(`b`, `fixed seed`, 1), fn: 0 }], - witness: false, - authored: null, - secondAuthored: false, - fault: `none`, - stability: `none`, - ordinary: false, - native: `none`, - boot: false, - cliPath: `plain`, - concurrentStart: false, - lazyGate: false, - fsRead: `none`, - prePlugin: false, - // A config the plugin can sit in, which Vitest discovers. - configPlace: `discovered`, - inputRead, - keepStamp, - laterSteps: NO_LATER_STEPS, - inputSteps: NO_INPUT_STEPS, - steps: [`inputGate`, `recheck`], - }), - })), + ].map(gateKindHistory), { // A file that the test's own child process tree wrote earlier in the // check is no input of the test (maintainer decisions "Own writes @@ -11610,6 +11626,35 @@ oracleProperty({ childEnvironment: `client`, }), }, + ...[ + [ + `an edit to a file the test stats for its size, by statSync`, + `stat`, + false, + ], + [ + `an edit to a file the test stats for its size, by fs/promises stat`, + `statAsync`, + false, + ], + [ + `an edit to a file the test stats for its size, by the callback stat`, + `statCallback`, + false, + ], + [`an edit to a file a test appends to, then reads`, `append`, false], + [ + `an edit to a file a test appends to with flag a, then reads`, + `flagAppend`, + false, + ], + [`an edit to a file a test requires as JSON`, `required`, false], + [ + `an edit to a file that a test child process reads`, + `childRead`, + false, + ], + ].map(gateKindHistory), ]), }, resolve: resolveHistory, diff --git a/packages/oracles/oracle-gaps/history-fingerprint.json b/packages/oracles/oracle-gaps/history-fingerprint.json index 09c196fc..9cb48899 100644 --- a/packages/oracles/oracle-gaps/history-fingerprint.json +++ b/packages/oracles/oracle-gaps/history-fingerprint.json @@ -87,7 +87,7 @@ ["failingLawHook", "4417bd05ca78a981"], ["failingLawSpins", "a52fc926e1e1704b"], ["faults", "484207f844e32250"], - ["inputRead", "edba1fe5f65d4573"], + ["inputRead", "e60f722316d29505"], ["keepStamp", "8f39ed756b8c1587"], ["inputSteps", "0c3b8c28396b30de"], ["childWrite", "dfc2c2d5f3dec106"], @@ -181,7 +181,7 @@ ["failingLawHook", "4417bd05ca78a981"], ["failingLawSpins", "a52fc926e1e1704b"], ["faults", "484207f844e32250"], - ["inputRead", "edba1fe5f65d4573"], + ["inputRead", "e60f722316d29505"], ["keepStamp", "8f39ed756b8c1587"], ["inputSteps", "0c3b8c28396b30de"], ["childWrite", "dfc2c2d5f3dec106"], diff --git a/packages/oracles/oracle-gaps/inputs.mjs b/packages/oracles/oracle-gaps/inputs.mjs index 42f06b5b..1e3b93ba 100644 --- a/packages/oracles/oracle-gaps/inputs.mjs +++ b/packages/oracles/oracle-gaps/inputs.mjs @@ -9,7 +9,9 @@ // `not a file`, or `missing`), `dir:` for a directory's listing, // hashed by its entries' names and kinds, or `dirs:` for a recursive // one, `stat:` for a test of whether a path exists and what it is, -// hashed by that, `env:` for a variable, hashed by its value, or `env:*` for the +// hashed by that, `statx:` for a path's metadata (its size, times, +// identity, mode and kind, a directory's by its kind alone), `env:` +// for a variable, hashed by its value, or `env:*` for the // set of names, which code reads when it lists the environment. The harness (capture-setup.mjs) watches a test's reads in // its worker, and the session (check.mjs) watches what the config and its // plugins read in the CLI's process. Both files are copied beside the @@ -31,9 +33,13 @@ const reads = [ // The calls that test whether a file exists and what it is: an input by its // existence and kind (G42's stat family), not by its text, so that Vite's // resolution, which stats each module it imports, does not make every -// module's text an input of every run. -const stats = [ - [fs, [`existsSync`, `statSync`]], +// module's text an input of every run. `existsSync` tells nothing more. +const stats = [[fs, [`existsSync`]]] +// The calls that read a path's metadata: a stat's size or times change with +// the text, so the result is an input by all of them (`statx:`), not by kind +// alone (133-1). The callback form of `stat` is one too (133-6). +const metadata = [ + [fs, [`statSync`, `stat`]], [fs.promises, [`stat`]], ] // The calls that list a directory. @@ -104,9 +110,11 @@ export const inputHash = (key) => ? fileHash(key.slice(3)) : key.startsWith(`stat:`) ? kindOf(key.slice(5)) - : key.startsWith(`dirs:`) - ? listingHash(key.slice(5), true) - : listingHash(key.slice(4), false) + : key.startsWith(`statx:`) + ? metadataHash(key.slice(6)) + : key.startsWith(`dirs:`) + ? listingHash(key.slice(5), true) + : listingHash(key.slice(4), false) /** A path's existence and kind now. */ function kindOf(path) { @@ -118,6 +126,35 @@ function kindOf(path) { } } +/** + * A path's metadata now: a file's size, times, identity, and mode, so that an + * edit that keeps the size, or a hand edit that keeps the time, is still a + * change (133-1). A directory's is its kind alone: its times move with every + * entry the runner itself writes beside the tests, and its entries are an + * input where a test lists them. + */ +function metadataHash(path) { + try { + const stat = original.statSync(path) + return stat.isFile() + ? sha1( + [ + stat.size, + stat.mtimeMs, + stat.ctimeMs, + stat.ino, + stat.mode, + `file`, + ].join(`\0`), + ) + : stat.isDirectory() + ? `directory` + : `other` + } catch { + return `missing` + } +} + /** A variable's input hash under `env`, or for `*`, that of its names. */ export const envHash = ( name, @@ -162,8 +199,20 @@ export function watchReads(record) { if (globalThis.__oracleGapsWatching) return globalThis.__oracleGapsWatching = true record = (key, write) => globalThis.__oracleGapsRecord(key, write) - const watched = (target, kind, options) => { + const watched = (target, kind, args, name) => { const write = kind === `write` + // A listing's options come first, a write's after its data. + const options = kind === `list` ? args[0] : args[1] + // An append reads the text it adds to before it writes, so that text is + // an input unless the copy wrote it first (133-3). An append is a call + // named `append...`, or a write with the flag `a`. + const appends = + write && + (/append/i.test(name) || + (typeof options === `object` && + options !== null && + String(options.flag ?? ``).startsWith(`a`))) + const mark = appends ? `append` : write let path try { if (target instanceof URL) path = resolve(fileURLToPath(target)) @@ -176,19 +225,21 @@ export function watchReads(record) { const prefix = kind === `stat` ? `stat` - : kind !== `list` - ? `fs` - : options?.recursive - ? `dirs` - : `dir` - record(`${prefix}:${posix(path)}`, write) + : kind === `statx` + ? `statx` + : kind !== `list` + ? `fs` + : options?.recursive + ? `dirs` + : `dir` + record(`${prefix}:${posix(path)}`, mark) // A written file is also known by its directory's real path, which a // later read through a link, or an import by its real URL, names. if (write) try { record( `fs:${posix(join(original.realpathSync(dirname(path)), basename(path)))}`, - write, + mark, ) } catch { // No directory to write in: the write fails as it would. @@ -197,6 +248,7 @@ export function watchReads(record) { for (const [calls, kind] of [ [reads, `read`], [stats, `stat`], + [metadata, `statx`], [listings, `list`], [writes, `write`], ]) @@ -204,7 +256,7 @@ export function watchReads(record) { for (const name of names) { const call = owner[name] owner[name] = keepProperties(call, function (target, ...rest) { - watched(target, kind, rest[0]) + watched(target, kind, rest, name) return call.call(this, target, ...rest) }) } diff --git a/packages/oracles/scripts/e2e-shards.mjs b/packages/oracles/scripts/e2e-shards.mjs index 9fba527a..b3b57af0 100644 --- a/packages/oracles/scripts/e2e-shards.mjs +++ b/packages/oracles/scripts/e2e-shards.mjs @@ -159,6 +159,27 @@ export const shards = { 'fixed seed 20261105: a test that reads a file its child process wrote, rechecked through the daemon', 'random seed: a test that reads a file its child process wrote, rechecked through the daemon', 'determinism: constructed history: a test that reads a file its child process wrote, rechecked through the daemon', + 'fixed seed 20261105: an edit to a file the test stats for its size, by statSync', + 'random seed: an edit to a file the test stats for its size, by statSync', + 'determinism: constructed history: an edit to a file the test stats for its size, by statSync', + 'fixed seed 20261105: an edit to a file the test stats for its size, by fs/promises stat', + 'random seed: an edit to a file the test stats for its size, by fs/promises stat', + 'determinism: constructed history: an edit to a file the test stats for its size, by fs/promises stat', + 'fixed seed 20261105: an edit to a file the test stats for its size, by the callback stat', + 'random seed: an edit to a file the test stats for its size, by the callback stat', + 'determinism: constructed history: an edit to a file the test stats for its size, by the callback stat', + 'fixed seed 20261105: an edit to a file a test appends to, then reads', + 'random seed: an edit to a file a test appends to, then reads', + 'determinism: constructed history: an edit to a file a test appends to, then reads', + 'fixed seed 20261105: an edit to a file a test appends to with flag a, then reads', + 'random seed: an edit to a file a test appends to with flag a, then reads', + 'determinism: constructed history: an edit to a file a test appends to with flag a, then reads', + 'fixed seed 20261105: an edit to a file a test requires as JSON', + 'random seed: an edit to a file a test requires as JSON', + 'determinism: constructed history: an edit to a file a test requires as JSON', + 'fixed seed 20261105: an edit to a file that a test child process reads', + 'random seed: an edit to a file that a test child process reads', + 'determinism: constructed history: an edit to a file that a test child process reads', // Added with the CLI's parent-config discovery (not yet measured). `fixed seed 20261105: a package whose parent directory has its config`, `random seed: test.projects in a parent's config`, diff --git a/packages/oracles/scripts/pr-shards.mjs b/packages/oracles/scripts/pr-shards.mjs index 0832c6b3..d0d86693 100644 --- a/packages/oracles/scripts/pr-shards.mjs +++ b/packages/oracles/scripts/pr-shards.mjs @@ -44,6 +44,13 @@ const daemonInputUnits = [ "a hand edit of a file the config's plugin writes", // A file the test's child process wrote (own writes of the process tree). 'a test that reads a file its child process wrote, rechecked through the daemon', + 'an edit to a file the test stats for its size, by statSync', + 'an edit to a file the test stats for its size, by fs/promises stat', + 'an edit to a file the test stats for its size, by the callback stat', + 'an edit to a file a test appends to, then reads', + 'an edit to a file a test appends to with flag a, then reads', + 'an edit to a file a test requires as JSON', + 'an edit to a file that a test child process reads', ] const escape = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, `\\$&`) const anyOf = (names) => `(?:${names.map(escape).join(`|`)})` @@ -917,6 +924,13 @@ export const partitions = { daemonInputUnits[12], ]), 7: anyOf([ + daemonInputUnits[13], + daemonInputUnits[14], + daemonInputUnits[15], + daemonInputUnits[16], + daemonInputUnits[17], + daemonInputUnits[18], + daemonInputUnits[19], 'a daemon pause that cannot engage', 'an edit to data a test reads through fs (statDir)', 'an edit to data a test reads through fs (promise)', From 150d04721a69faa335d63bfc319ccd72b99dc35c Mon Sep 17 00:00:00 2001 From: Kyle Mathews Date: Tue, 1 Dec 2026 22:48:37 -0700 Subject: [PATCH 03/51] fix(oracle-gaps): an append to the run's own capture or log reads nothing first The copy's first write of test-output.log is an append, and an append reads the text it adds to first (133-3). The runner creates that log and its capture rows for this run, so the pre-read recorded the log as missing, then the log grew while the run settled, and settleIn never stored the unit. A check of an unchanged state recomputed three runs that owed none (law 9, unchanged reuse). Rule: an append to the run's own capture rows or test-output.log reads nothing first; a plain read of either file is still an input. RED before: the seven repaired histories failed at unchanged reuse. GREEN after: the seven and the seven existing gate-input histories (inside, outside, module, env, listing, stream, tsconfig) pass, 42 tests. Co-authored-by: Isaac --- .../oracles/oracle-gaps/capture-setup.mjs | 26 +++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/packages/oracles/oracle-gaps/capture-setup.mjs b/packages/oracles/oracle-gaps/capture-setup.mjs index d6285a9a..fd1a8406 100644 --- a/packages/oracles/oracle-gaps/capture-setup.mjs +++ b/packages/oracles/oracle-gaps/capture-setup.mjs @@ -331,11 +331,33 @@ function ownOutput(key) { foldChildren() return wrote.has(key.replace(/^(stat|statx):/, `fs:`)) } +// Rule: an append to the run's own capture rows or test-output.log reads +// nothing first, since the runner created that file for this run, so its +// text is the run's own output and not an input. The reuse miss of #133: the +// log's first pre-read was recorded as missing, the log grew while the run +// settled, so the unit was never stored. A plain read of either file is +// still an input. +const posixOf = (path) => + process.platform === `win32` ? path.replaceAll(`\\`, `/`) : path +function isRunnerOwnAppend(key, write) { + if (write !== `append` || !state.capture || key.startsWith(`env:`)) + return false + const own = [state.capture, join(dirname(state.capture), `test-output.log`)] + const path = key.slice(key.indexOf(`:`) + 1) + return own.some((file) => path === posixOf(file)) +} watchReads((key, write) => { const reads = globalThis.__oracleGapsReads // A read, or the read that an append makes of the text it adds to (133-3), - // is an input unless the copy or its process tree wrote the file first. - if (write !== true && !reads.has(key) && !wrote.has(key) && !ownOutput(key)) + // is an input unless the copy or its process tree wrote the file first, or + // the append is the runner's own (isRunnerOwnAppend). + if ( + write !== true && + !isRunnerOwnAppend(key, write) && + !reads.has(key) && + !wrote.has(key) && + !ownOutput(key) + ) reads.set(key, key.startsWith(`env:`) ? null : inputHash(key)) if (write) { // The child reads before this write come first, so they are inputs. From 0d8474d897e17930216b2776c575497a5e5c209e Mon Sep 17 00:00:00 2001 From: Kyle Mathews Date: Tue, 1 Dec 2026 23:16:23 -0700 Subject: [PATCH 04/51] test(oracle-gaps): a constructed history kills the runner's own-append exemption File a's test writes to the process's streams, so its copy appends to the run's test-output.log. A recheck of the unchanged state reuses both files' runs, since that append is no input (isRunnerOwnAppend). Without the exemption the log grows while the run settles, the runs are never stored, and the recheck computes them again. The state is declared and entered; the mutant is killed on the fixed seed and the random seed. Co-authored-by: Isaac --- .../oracle-gaps/constructed-order.json | 3 +- .../gap-report-oracle.property.test.mjs | 65 +++++++++++++++++++ packages/oracles/scripts/e2e-shards.mjs | 3 + packages/oracles/scripts/pr-shards.mjs | 2 + 4 files changed, 72 insertions(+), 1 deletion(-) diff --git a/packages/oracles/oracle-gaps/constructed-order.json b/packages/oracles/oracle-gaps/constructed-order.json index c57b535e..36ed13cd 100644 --- a/packages/oracles/oracle-gaps/constructed-order.json +++ b/packages/oracles/oracle-gaps/constructed-order.json @@ -136,6 +136,7 @@ "an edit to a file a test appends to, then reads", "an edit to a file a test appends to with flag a, then reads", "an edit to a file a test requires as JSON", - "an edit to a file that a test child process reads" + "an edit to a file that a test child process reads", + "a test that writes to the console, rechecked through the daemon" ] } diff --git a/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs b/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs index 5c39ddf5..d231a489 100644 --- a/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs +++ b/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs @@ -3232,6 +3232,13 @@ async function incremental(dir, plan, cli, copy, observe, states) { states.add( `an unchanged check through the daemon computed nothing while a test read what its child process wrote`, ) + // File a's test wrote to the process's streams, so its copy appended to + // the run's own test-output.log, which the run creates (capture-setup.mjs, + // isRunnerOwnAppend): the unchanged recheck reused a's runs. + if (plan.consoleOutput) + states.add( + `an unchanged check through the daemon computed nothing while a test wrote to the console`, + ) } // A daemon check after an edit that computed fewer runs cut off by their // call budget than the cold run of the same state reused such a run, so @@ -7896,6 +7903,7 @@ const required = [ `a slow daemon start was served by the daemon`, `a check abandoned while a context warmed in place of a cut one wrote nothing more`, `an unchanged check through the daemon computed nothing while a test read what its child process wrote`, + `an unchanged check through the daemon computed nothing while a test wrote to the console`, ] // The faults the CLI analyzes anyway: a package's TypeScript is no input. const analyzedFaults = [`noTypescript`, `apiLessTypescript`] @@ -8045,6 +8053,8 @@ const separate = [ // Each has its own constructed history (#179; own writes of the test's // process tree). `an unchanged check through the daemon computed nothing while a test read what its child process wrote`, + // Its own constructed history (a test that writes to the console). + `an unchanged check through the daemon computed nothing while a test wrote to the console`, ] // A stop by SIGTERM exists only where Node can deliver it: on win32 kill is // TerminateProcess, so there the stop law is judged by SIGINT (the test stop @@ -12320,6 +12330,61 @@ oracleProperty({ false, ], ].map(gateKindHistory), + { + // File a's test writes to the process's streams (`consoleOutput`), so + // its copy appends to the run's own test-output.log, which the run + // creates. That append is no input (capture-setup.mjs, isRunnerOwnAppend), + // so the unchanged recheck through the daemon reuses both files' runs. + // With the exemption removed, the log grows while the run settles, + // the runs are never stored, and the recheck computes them again. + name: `a test that writes to the console, rechecked through the daemon`, + enters: [ + `an unchanged check through the daemon computed nothing`, + `an unchanged check through the daemon computed nothing while a test wrote to the console`, + ], + build: (generated) => ({ + ...generated, + functions: [[{ kind: `push`, quote: `'` }]], + containers: [], + overloads: [], + owners: [`a`, `b`], + library: [], + libraryOwners: [], + runes: [], + derived: null, + dotGen: false, + dataOwners: [], + exportOwners: [], + importer: `none`, + wholeFile: `none`, + template: false, + tests: [ + { ...judging(`a`, `fixed seed`, 1), fn: 0 }, + { ...judging(`b`, `fixed seed`, 1), fn: 0 }, + ], + witness: false, + authored: null, + secondAuthored: false, + fault: `none`, + stability: `none`, + ordinary: false, + native: `none`, + boot: false, + cliPath: `plain`, + concurrentStart: false, + lazyGate: false, + fsRead: `none`, + prePlugin: false, + inputRead: `none`, + keepStamp: false, + laterSteps: NO_LATER_STEPS, + inputSteps: NO_INPUT_STEPS, + steps: [`recheck`], + childWrite: false, + childEnvironment: `node`, + consoleOutput: true, + }), + }, ]), }, resolve: resolveHistory, diff --git a/packages/oracles/scripts/e2e-shards.mjs b/packages/oracles/scripts/e2e-shards.mjs index 8f45bee6..c8a4f38a 100644 --- a/packages/oracles/scripts/e2e-shards.mjs +++ b/packages/oracles/scripts/e2e-shards.mjs @@ -180,6 +180,9 @@ export const shards = { 'fixed seed 20261105: an edit to a file that a test child process reads', 'random seed: an edit to a file that a test child process reads', 'determinism: constructed history: an edit to a file that a test child process reads', + 'fixed seed 20261105: a test that writes to the console, rechecked through the daemon', + 'random seed: a test that writes to the console, rechecked through the daemon', + 'determinism: constructed history: a test that writes to the console, rechecked through the daemon', // Added with the CLI's parent-config discovery (not yet measured). `fixed seed 20261105: a package whose parent directory has its config`, `random seed: test.projects in a parent's config`, diff --git a/packages/oracles/scripts/pr-shards.mjs b/packages/oracles/scripts/pr-shards.mjs index fefacedd..6615128c 100644 --- a/packages/oracles/scripts/pr-shards.mjs +++ b/packages/oracles/scripts/pr-shards.mjs @@ -51,6 +51,7 @@ const daemonInputUnits = [ 'an edit to a file a test appends to with flag a, then reads', 'an edit to a file a test requires as JSON', 'an edit to a file that a test child process reads', + 'a test that writes to the console, rechecked through the daemon', ] const escape = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, `\\$&`) const anyOf = (names) => `(?:${names.map(escape).join(`|`)})` @@ -934,6 +935,7 @@ export const partitions = { daemonInputUnits[17], daemonInputUnits[18], daemonInputUnits[19], + 'a test that writes to the console, rechecked through the daemon', 'a daemon pause that cannot engage', 'an edit to data a test reads through fs (statDir)', 'an edit to data a test reads through fs (promise)', From f7a95db27e29140b29d4dcf31f461da4ddb7cdc6 Mon Sep 17 00:00:00 2001 From: Kyle Mathews Date: Tue, 1 Dec 2026 23:28:19 -0700 Subject: [PATCH 05/51] fix(oracle-gaps): a worker thread's reads are inputs A worker starts with the NODE_OPTIONS its process had at start, so a preload set later never reaches it, and a test's worker read was no input. The copy now patches worker_threads.Worker in its realm to give each worker the child-writes preload (in execArgv; an eval worker requires it first), so the worker's reads and writes go to the same log the child processes use. The threadRead gate kind reads the gate in a worker, RED without the patch and GREEN with it. A child process started with an environment that drops NODE_OPTIONS is still not watched (#143). The runner's own capture and test-output.log are no input for an append (README daemon section). Co-authored-by: Isaac --- README.md | 14 +++++-- .../oracles/oracle-gaps/capture-setup.mjs | 40 +++++++++++++++++++ packages/oracles/oracle-gaps/check.mjs | 5 ++- .../oracle-gaps/constructed-order.json | 3 +- .../oracle-gaps/gap-report-model-oracle.mjs | 9 +++++ .../gap-report-oracle.property.test.mjs | 9 +++++ .../oracle-gaps/history-fingerprint.json | 4 +- packages/oracles/scripts/e2e-shards.mjs | 3 ++ packages/oracles/scripts/pr-shards.mjs | 2 + 9 files changed, 80 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 11f35185..52a44e4c 100644 --- a/README.md +++ b/README.md @@ -278,17 +278,23 @@ runs cold` and runs the check in its own process, which reports what the So does a check after a file that Vitest, the config, or a plugin read or wrote has changed. + The harness gives each worker thread and each child process that a test + starts its preload, so their reads are inputs too. A child process that + the test starts with an environment that drops `NODE_OPTIONS` is not + watched (#143). A file that the runner created for the run (its capture + rows and its `test-output.log`) is the runner's output: an append to one + of them reads nothing first, and a plain read of either is still an input. + These reads are no input yet, so an edit to the file alone does not rerun - the tests that read it: a read from a worker thread or child process that - the test starts (#143); a read through a file descriptor, after `open`, + the tests that read it: a read through a file descriptor, after `open`, `openSync`, or the `fs/promises` `open` (#141); a link's target, or the rest of the stat family, `lstat`, `readlink`, `realpath`, `access`, the callback `stat`, and `exists` (#142); `glob`, `globSync`, `copyFile`, `copyFileSync`, `cp`, `cpSync`, `openAsBlob`, `statfs`, and the `fs/promises` `glob`, `copyFile`, `cp`, and `statfs` (#152); the module-level reads of a test file whose tests are all skipped (#153); and - the earlier content of a file that a test appends to, partly writes, or - fails to write, then reads (#154). Run the check cold (without `--daemon`) + the earlier content of a file that a test partly writes or fails to write, + then reads. Run the check cold (without `--daemon`) after an edit to a file read that way. A later release records all of them except `watch` and `watchFile`, which wait for future changes and stay no input (maintainer decision, 2026-11-13, with `watchFile` in the diff --git a/packages/oracles/oracle-gaps/capture-setup.mjs b/packages/oracles/oracle-gaps/capture-setup.mjs index fd1a8406..95286612 100644 --- a/packages/oracles/oracle-gaps/capture-setup.mjs +++ b/packages/oracles/oracle-gaps/capture-setup.mjs @@ -371,6 +371,46 @@ if (!globalThis.__oracleGapsChildren) { `${process.env.NODE_OPTIONS ?? ``} --import=${pathToFileURL(join(home, `child-writes.mjs`)).href}`.trim() } process.env.ORACLE_GAPS_CHILD_WRITES = childLog +// Worker threads (#143): a worker starts with the NODE_OPTIONS its process +// had at start, not later ones, so the copy's preload (child-writes.mjs) is +// given to each worker in its execArgv, as each child process gets it. The +// class is replaced in this realm only, and the builtin's ESM exports are +// synced, so a test's `import { Worker }` gets the wrapper. A worker whose +// `env` is an object gets the log's name too. +if (!globalThis.__oracleGapsWorkers) { + globalThis.__oracleGapsWorkers = true + const threads = createRequire(import.meta.url)(`node:worker_threads`) + const Base = threads.Worker + const preload = pathToFileURL(join(home, `child-writes.mjs`)).href + class Watched extends Base { + constructor(file, options = {}) { + const env = + options.env && typeof options.env === `object` + ? { + ...options.env, + ORACLE_GAPS_CHILD_WRITES: process.env.ORACLE_GAPS_CHILD_WRITES, + } + : options.env + // An eval worker ignores `--import` in its execArgv, so its code first + // requires the preload (a synchronous require of this ES module). + const code = + options.eval && typeof file === `string` + ? `require(${JSON.stringify(join(home, `child-writes.mjs`))});\n${file}` + : file + super(code, { + ...options, + env, + execArgv: [ + ...(options.execArgv ?? process.execArgv), + `--import`, + preload, + ], + }) + } + } + threads.Worker = Watched + syncBuiltinESMExports() +} // A test's own writes to the process's stdout and stderr (a debugging // `process.stdout.write`) go to the run's test-output.log, beside its // capture, not to the CLI's streams, whose every line is a line of the diff --git a/packages/oracles/oracle-gaps/check.mjs b/packages/oracles/oracle-gaps/check.mjs index e88fac40..c660d409 100644 --- a/packages/oracles/oracle-gaps/check.mjs +++ b/packages/oracles/oracle-gaps/check.mjs @@ -20,8 +20,9 @@ // reused only while every one of those hashes is unchanged. So a check // through the daemon reports what a cold run reports (the CLI oracle's law // 9). Not covered: a read through another fs API than those inputs.mjs -// watches, one from a worker thread or a child process that a test starts, -// and a new file that changes how an unchanged import resolves. +// watches, a read from a child process that a test starts with an environment +// that drops NODE_OPTIONS (#143), and a new file that changes how an unchanged +// import resolves. A worker thread a test starts is covered (capture-setup.mjs). // // A unit's identity also carries the global inputs: this CLI's own files, // the harness, the Vite config and the files it loads, the package's diff --git a/packages/oracles/oracle-gaps/constructed-order.json b/packages/oracles/oracle-gaps/constructed-order.json index 36ed13cd..c6933b81 100644 --- a/packages/oracles/oracle-gaps/constructed-order.json +++ b/packages/oracles/oracle-gaps/constructed-order.json @@ -137,6 +137,7 @@ "an edit to a file a test appends to with flag a, then reads", "an edit to a file a test requires as JSON", "an edit to a file that a test child process reads", - "a test that writes to the console, rechecked through the daemon" + "a test that writes to the console, rechecked through the daemon", + "an edit to a file a test reads inside a worker thread" ] } diff --git a/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs b/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs index b2493b92..4d76b861 100644 --- a/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs +++ b/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs @@ -1253,6 +1253,7 @@ const drawn = fc.record({ `flagAppend`, `required`, `childRead`, + `threadRead`, ), // Each write of a gate file keeps its size (`open` and `shut` have one // length) and gets back one fixed modification time, as `cp -p`, `rsync @@ -5868,6 +5869,7 @@ const gateFiles = { flagAppend: `tests/gate.json`, required: `tests/gate.json`, childRead: `tests/gate.json`, + threadRead: `tests/gate.json`, } /** Whether the gate input is one that the config's own plugin reads. */ const pluginGated = (history) => @@ -5971,6 +5973,13 @@ const inputReads = { `import { fileURLToPath as gatePath } from 'node:url'`, `const readInput = async () => ({ open: JSON.parse(runGateChild(process.execPath, ['-e', "process.stdout.write(require('node:fs').readFileSync(process.argv[1], 'utf8'))", gatePath(new URL('./gate.json', import.meta.url))], { encoding: 'utf8' })).gate === 'open' })`, ], + // File b reads the gate in a worker thread, which runs the same code and + // reports back through a message (worker_threads, #143). + threadRead: [ + `import { Worker as GateWorker } from 'node:worker_threads'`, + `import { fileURLToPath as gatePath } from 'node:url'`, + `const readInput = () => new Promise((resolve, reject) => { const worker = new GateWorker("const fs = require('node:fs'); const { parentPort, workerData } = require('node:worker_threads'); parentPort.postMessage(JSON.parse(fs.readFileSync(workerData, 'utf8')).gate === 'open')", { eval: true, workerData: gatePath(new URL('./gate.json', import.meta.url)) }); worker.once('message', (open) => resolve({ open: open === true })); worker.once('error', reject) })`, + ], } // File b's read of a file that its test's child process tree wrote // (`childWrite`): the grandchild writes `child.txt` in a new directory under diff --git a/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs b/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs index d231a489..373a127e 100644 --- a/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs +++ b/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs @@ -7585,6 +7585,7 @@ const inputKinds = [ `flagAppend`, `required`, `childRead`, + `threadRead`, ] // Law 9's states that a constructed history of their own reaches, not the // edit sequence: the mid-run edit, and an edit to data a test reads through @@ -12385,6 +12386,14 @@ oracleProperty({ consoleOutput: true, }), }, + // File b reads the gate in a worker thread (worker_threads, #143): the + // harness gives each worker its preload (capture-setup.mjs), so the + // worker's read is an input and the edit changes the cold result. + gateKindHistory([ + `an edit to a file a test reads inside a worker thread`, + `threadRead`, + false, + ]), ]), }, resolve: resolveHistory, diff --git a/packages/oracles/oracle-gaps/history-fingerprint.json b/packages/oracles/oracle-gaps/history-fingerprint.json index ad9c5ebe..63513fad 100644 --- a/packages/oracles/oracle-gaps/history-fingerprint.json +++ b/packages/oracles/oracle-gaps/history-fingerprint.json @@ -89,7 +89,7 @@ ["faults", "484207f844e32250"], ["diffBase", "12e714e66d263986"], ["authoredSpan", "3259189ca6a54cd5"], - ["inputRead", "ae6b3a303b146ee0"], + ["inputRead", "241a2a8be84773fe"], ["keepStamp", "6e084c1e8b33f13d"], ["inputSteps", "c47bf09530d81851"], ["childWrite", "96cd063b1067f34b"], @@ -185,7 +185,7 @@ ["faults", "484207f844e32250"], ["diffBase", "12e714e66d263986"], ["authoredSpan", "3259189ca6a54cd5"], - ["inputRead", "ae6b3a303b146ee0"], + ["inputRead", "241a2a8be84773fe"], ["keepStamp", "6e084c1e8b33f13d"], ["inputSteps", "c47bf09530d81851"], ["childWrite", "96cd063b1067f34b"], diff --git a/packages/oracles/scripts/e2e-shards.mjs b/packages/oracles/scripts/e2e-shards.mjs index c8a4f38a..64a48628 100644 --- a/packages/oracles/scripts/e2e-shards.mjs +++ b/packages/oracles/scripts/e2e-shards.mjs @@ -183,6 +183,9 @@ export const shards = { 'fixed seed 20261105: a test that writes to the console, rechecked through the daemon', 'random seed: a test that writes to the console, rechecked through the daemon', 'determinism: constructed history: a test that writes to the console, rechecked through the daemon', + 'fixed seed 20261105: an edit to a file a test reads inside a worker thread', + 'random seed: an edit to a file a test reads inside a worker thread', + 'determinism: constructed history: an edit to a file a test reads inside a worker thread', // Added with the CLI's parent-config discovery (not yet measured). `fixed seed 20261105: a package whose parent directory has its config`, `random seed: test.projects in a parent's config`, diff --git a/packages/oracles/scripts/pr-shards.mjs b/packages/oracles/scripts/pr-shards.mjs index 6615128c..f9153980 100644 --- a/packages/oracles/scripts/pr-shards.mjs +++ b/packages/oracles/scripts/pr-shards.mjs @@ -52,6 +52,7 @@ const daemonInputUnits = [ 'an edit to a file a test requires as JSON', 'an edit to a file that a test child process reads', 'a test that writes to the console, rechecked through the daemon', + 'an edit to a file a test reads inside a worker thread', ] const escape = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, `\\$&`) const anyOf = (names) => `(?:${names.map(escape).join(`|`)})` @@ -936,6 +937,7 @@ export const partitions = { daemonInputUnits[18], daemonInputUnits[19], 'a test that writes to the console, rechecked through the daemon', + 'an edit to a file a test reads inside a worker thread', 'a daemon pause that cannot engage', 'an edit to data a test reads through fs (statDir)', 'an edit to data a test reads through fs (promise)', From dce21b36443f285dc1cf1efb386b526fa2c4da7a Mon Sep 17 00:00:00 2001 From: Kyle Mathews Date: Wed, 2 Dec 2026 07:43:04 -0700 Subject: [PATCH 06/51] fix(oracle-gaps): a require's package.json main and type are inputs Node reads the package.json that decides a require's main and type itself, so the fs wrapper never saw it: editing a sub's main changed the module the daemon kept. The copy wraps Module._resolveFilename (a private Node API) and records the package.json files each resolution consults, up to the first that exists, and the resolved file's scope. requireMain and requireType gate kinds: RED without the wrapper (4 of 6 fail at incremental equals cold), GREEN with it (6 of 6). The wrapper throws at setup if Node no longer has Module._resolveFilename (check.mjs header). Co-authored-by: Isaac --- README.md | 6 ++- .../oracles/oracle-gaps/capture-setup.mjs | 43 +++++++++++++++++++ packages/oracles/oracle-gaps/check.mjs | 9 ++++ .../oracle-gaps/constructed-order.json | 4 +- .../oracle-gaps/gap-report-model-oracle.mjs | 33 ++++++++++++-- .../gap-report-oracle.property.test.mjs | 17 ++++++++ .../oracle-gaps/history-fingerprint.json | 4 +- packages/oracles/scripts/e2e-shards.mjs | 6 +++ packages/oracles/scripts/pr-shards.mjs | 4 ++ 9 files changed, 119 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 52a44e4c..6d044a12 100644 --- a/README.md +++ b/README.md @@ -279,7 +279,11 @@ runs cold` and runs the check in its own process, which reports what the wrote has changed. The harness gives each worker thread and each child process that a test - starts its preload, so their reads are inputs too. A child process that + starts its preload, so their reads are inputs too. A `require` in a test + consults the `package.json` files that decide a package's `main` and + `type`; Node reads them itself, so the harness records them through a + wrapper on `Module._resolveFilename`, a private Node API (check.mjs says + what changes if a Node version alters it). A child process that the test starts with an environment that drops `NODE_OPTIONS` is not watched (#143). A file that the runner created for the run (its capture rows and its `test-output.log`) is the runner's output: an append to one diff --git a/packages/oracles/oracle-gaps/capture-setup.mjs b/packages/oracles/oracle-gaps/capture-setup.mjs index 95286612..9e2dd4ed 100644 --- a/packages/oracles/oracle-gaps/capture-setup.mjs +++ b/packages/oracles/oracle-gaps/capture-setup.mjs @@ -371,6 +371,49 @@ if (!globalThis.__oracleGapsChildren) { `${process.env.NODE_OPTIONS ?? ``} --import=${pathToFileURL(join(home, `child-writes.mjs`)).href}`.trim() } process.env.ORACLE_GAPS_CHILD_WRITES = childLog +// Node resolves a require without fs: the package.json files that decide a +// request's main (its directory's) and type (the resolved file's package +// scope) are read by Node itself, so the fs wrapper never sees them (probed: +// editing a sub's main changed the module, and no fs read showed it). This +// wraps Module._resolveFilename, Node's private resolver, in this realm. Each +// resolution records the package.json files it consults, from the request's +// candidate and from the resolved file's directory, up to the first that +// exists (a missing one is recorded too), as inputs. The check (check.mjs, +// the header) says what the oracle shows if a Node version renames it. +const { Module } = createRequire(import.meta.url)(`node:module`) +if (typeof Module?._resolveFilename !== `function`) + throw new Error( + `oracle-gaps: this Node has no Module._resolveFilename, so a require's package.json inputs cannot be recorded (capture-setup.mjs)`, + ) +const resolveFilename = Module._resolveFilename +// The package.json keys from `dir` upward, through the first that exists. +function scopeKeysOf(dir) { + const keys = [] + for (let at = dir; ; at = dirname(at)) { + const key = `fs:${posixOf(join(at, `package.json`))}` + keys.push(key) + if (inputHash(key) !== `missing` || dirname(at) === at) break + } + return keys +} +function recordScope(dir) { + const reads = globalThis.__oracleGapsReads + for (const key of scopeKeysOf(dir)) + if (!reads.has(key) && !wrote.has(key) && !ownOutput(key)) + reads.set(key, inputHash(key)) +} +Module._resolveFilename = function (request, parent, ...rest) { + const from = parent?.filename + const relative = + typeof request === `string` && + from !== undefined && + (request.startsWith(`.`) || isAbsolute(request)) + if (relative) recordScope(join(dirname(from), request)) + const result = resolveFilename.call(this, request, parent, ...rest) + if (typeof result === `string` && isAbsolute(result)) + recordScope(dirname(result)) + return result +} // Worker threads (#143): a worker starts with the NODE_OPTIONS its process // had at start, not later ones, so the copy's preload (child-writes.mjs) is // given to each worker in its execArgv, as each child process gets it. The diff --git a/packages/oracles/oracle-gaps/check.mjs b/packages/oracles/oracle-gaps/check.mjs index c660d409..89b7e2ea 100644 --- a/packages/oracles/oracle-gaps/check.mjs +++ b/packages/oracles/oracle-gaps/check.mjs @@ -23,6 +23,15 @@ // watches, a read from a child process that a test starts with an environment // that drops NODE_OPTIONS (#143), and a new file that changes how an unchanged // import resolves. A worker thread a test starts is covered (capture-setup.mjs). +// Node's own reads of the package.json files that a require consults (main, +// type) are covered by a wrapper on Module._resolveFilename in the copy +// (capture-setup.mjs). That is a private Node API, not a documented one: if a +// Node version renames it, capture-setup.mjs throws at setup, so the copy and +// the check fail loudly rather than run unwrapped; if Node changes its +// behaviour so that the wrapper is bypassed, the package.json histories +// (`an edit to the package.json main that a test requires`, and `type`) show it +// as a daemon result that differs from the cold one (law 9, incremental equals +// cold, RED on the unwrapped copy). // // A unit's identity also carries the global inputs: this CLI's own files, // the harness, the Vite config and the files it loads, the package's diff --git a/packages/oracles/oracle-gaps/constructed-order.json b/packages/oracles/oracle-gaps/constructed-order.json index c6933b81..94dbf3df 100644 --- a/packages/oracles/oracle-gaps/constructed-order.json +++ b/packages/oracles/oracle-gaps/constructed-order.json @@ -138,6 +138,8 @@ "an edit to a file a test requires as JSON", "an edit to a file that a test child process reads", "a test that writes to the console, rechecked through the daemon", - "an edit to a file a test reads inside a worker thread" + "an edit to a file a test reads inside a worker thread", + "an edit to the package.json main that a test requires", + "an edit to the package.json type that a test requires" ] } diff --git a/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs b/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs index 4d76b861..c8087ae5 100644 --- a/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs +++ b/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs @@ -1254,6 +1254,8 @@ const drawn = fc.record({ `required`, `childRead`, `threadRead`, + `requireMain`, + `requireType`, ), // Each write of a gate file keeps its size (`open` and `shut` have one // length) and gets back one fixed modification time, as `cp -p`, `rsync @@ -5847,9 +5849,13 @@ const GATE_STAMP = 1_700_000_000 const SIZE_GATES = [`stat`, `statAsync`, `statCallback`] const OPEN_SIZE = gateText(true).length const gateTextFor = (kind, open) => - SIZE_GATES.includes(kind) && !open - ? `${JSON.stringify({ gate: `shut`, pad: `....` })}\n` - : gateText(open) + kind === `requireMain` + ? `${JSON.stringify({ main: open ? `open.js` : `shut.js` })}\n` + : kind === `requireType` + ? `${JSON.stringify({ type: open ? `commonjs` : `module` })}\n` + : SIZE_GATES.includes(kind) && !open + ? `${JSON.stringify({ gate: `shut`, pad: `....` })}\n` + : gateText(open) // A fixture path under the directory beside the package (`outsideOf`), // which is outside it; writeFixture places it there. const BESIDE = `/` @@ -5870,6 +5876,8 @@ const gateFiles = { required: `tests/gate.json`, childRead: `tests/gate.json`, threadRead: `tests/gate.json`, + requireMain: `tests/sub/package.json`, + requireType: `tests/sub/package.json`, } /** Whether the gate input is one that the config's own plugin reads. */ const pluginGated = (history) => @@ -5975,6 +5983,14 @@ const inputReads = { ], // File b reads the gate in a worker thread, which runs the same code and // reports back through a message (worker_threads, #143). + requireMain: [ + `import { createRequire as requireFrom } from 'node:module'`, + `const readInput = async () => { const req = requireFrom(import.meta.url); const path = req.resolve('./sub'); delete req.cache[path]; return { open: req(path).open === true } }`, + ], + requireType: [ + `import { createRequire as requireFrom } from 'node:module'`, + `const readInput = async () => { const req = requireFrom(import.meta.url); const path = req.resolve('./sub'); delete req.cache[path]; return { open: req(path).open === true } }`, + ], threadRead: [ `import { Worker as GateWorker } from 'node:worker_threads'`, `import { fileURLToPath as gatePath } from 'node:url'`, @@ -6957,6 +6973,17 @@ function fixtureFiles(plan, state = initialState(plan)) { ...(plan.inputRead === `pluginWrite` ? { 'tests/gen.json': gateText(state.inputOpen) } : {}), + // A package that the test requires: its main picks one of two files + // (requireMain), or its type decides how a CommonJS file loads (requireType). + ...(plan.inputRead === `requireMain` + ? { + 'tests/sub/open.js': `module.exports = { open: true }\n`, + 'tests/sub/shut.js': `module.exports = { open: false }\n`, + } + : {}), + ...(plan.inputRead === `requireType` + ? { 'tests/sub/index.js': `module.exports = { open: true }\n` } + : {}), ...(gateFiles[plan.inputRead] === undefined ? {} : { diff --git a/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs b/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs index 373a127e..fa84c459 100644 --- a/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs +++ b/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs @@ -7586,6 +7586,8 @@ const inputKinds = [ `required`, `childRead`, `threadRead`, + `requireMain`, + `requireType`, ] // Law 9's states that a constructed history of their own reaches, not the // edit sequence: the mid-run edit, and an edit to data a test reads through @@ -12394,6 +12396,21 @@ oracleProperty({ `threadRead`, false, ]), + // File b requires a package: its main picks the file it loads, and the + // edit changes only that package.json. Node reads the main itself, so + // only the resolver wrapper (capture-setup.mjs) records the edit. + gateKindHistory([ + `an edit to the package.json main that a test requires`, + `requireMain`, + false, + ]), + // The same package's type: a CommonJS file loads as a module after the + // edit, and the test's require then fails to see its export. + gateKindHistory([ + `an edit to the package.json type that a test requires`, + `requireType`, + false, + ]), ]), }, resolve: resolveHistory, diff --git a/packages/oracles/oracle-gaps/history-fingerprint.json b/packages/oracles/oracle-gaps/history-fingerprint.json index 63513fad..41b8b8b9 100644 --- a/packages/oracles/oracle-gaps/history-fingerprint.json +++ b/packages/oracles/oracle-gaps/history-fingerprint.json @@ -89,7 +89,7 @@ ["faults", "484207f844e32250"], ["diffBase", "12e714e66d263986"], ["authoredSpan", "3259189ca6a54cd5"], - ["inputRead", "241a2a8be84773fe"], + ["inputRead", "447de24d5daef092"], ["keepStamp", "6e084c1e8b33f13d"], ["inputSteps", "c47bf09530d81851"], ["childWrite", "96cd063b1067f34b"], @@ -185,7 +185,7 @@ ["faults", "484207f844e32250"], ["diffBase", "12e714e66d263986"], ["authoredSpan", "3259189ca6a54cd5"], - ["inputRead", "241a2a8be84773fe"], + ["inputRead", "447de24d5daef092"], ["keepStamp", "6e084c1e8b33f13d"], ["inputSteps", "c47bf09530d81851"], ["childWrite", "96cd063b1067f34b"], diff --git a/packages/oracles/scripts/e2e-shards.mjs b/packages/oracles/scripts/e2e-shards.mjs index 64a48628..12f30517 100644 --- a/packages/oracles/scripts/e2e-shards.mjs +++ b/packages/oracles/scripts/e2e-shards.mjs @@ -186,6 +186,12 @@ export const shards = { 'fixed seed 20261105: an edit to a file a test reads inside a worker thread', 'random seed: an edit to a file a test reads inside a worker thread', 'determinism: constructed history: an edit to a file a test reads inside a worker thread', + 'fixed seed 20261105: an edit to the package.json main that a test requires', + 'random seed: an edit to the package.json main that a test requires', + 'determinism: constructed history: an edit to the package.json main that a test requires', + 'fixed seed 20261105: an edit to the package.json type that a test requires', + 'random seed: an edit to the package.json type that a test requires', + 'determinism: constructed history: an edit to the package.json type that a test requires', // Added with the CLI's parent-config discovery (not yet measured). `fixed seed 20261105: a package whose parent directory has its config`, `random seed: test.projects in a parent's config`, diff --git a/packages/oracles/scripts/pr-shards.mjs b/packages/oracles/scripts/pr-shards.mjs index f9153980..e4f1bb06 100644 --- a/packages/oracles/scripts/pr-shards.mjs +++ b/packages/oracles/scripts/pr-shards.mjs @@ -53,6 +53,8 @@ const daemonInputUnits = [ 'an edit to a file that a test child process reads', 'a test that writes to the console, rechecked through the daemon', 'an edit to a file a test reads inside a worker thread', + 'an edit to the package.json main that a test requires', + 'an edit to the package.json type that a test requires', ] const escape = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, `\\$&`) const anyOf = (names) => `(?:${names.map(escape).join(`|`)})` @@ -938,6 +940,8 @@ export const partitions = { daemonInputUnits[19], 'a test that writes to the console, rechecked through the daemon', 'an edit to a file a test reads inside a worker thread', + 'an edit to the package.json main that a test requires', + 'an edit to the package.json type that a test requires', 'a daemon pause that cannot engage', 'an edit to data a test reads through fs (statDir)', 'an edit to data a test reads through fs (promise)', From 38655e62eba74b55fe7f3b3e74ded818c8baf397 Mon Sep 17 00:00:00 2001 From: Kyle Mathews Date: Wed, 2 Dec 2026 08:03:27 -0700 Subject: [PATCH 07/51] perf(oracle-gaps): a child fold reads only what the tree wrote since the last The copy folded its child process log by reading the whole file at every fold (review of #133, 133-15). It now reads from the last fold's byte offset, so a fold costs what was written since. The offset is in bytes, which also fixes a character/byte mismatch in the old index. Co-authored-by: Isaac --- .../oracles/oracle-gaps/capture-setup.mjs | 28 +++++++++++++++---- 1 file changed, 23 insertions(+), 5 deletions(-) diff --git a/packages/oracles/oracle-gaps/capture-setup.mjs b/packages/oracles/oracle-gaps/capture-setup.mjs index 9e2dd4ed..d6d02c61 100644 --- a/packages/oracles/oracle-gaps/capture-setup.mjs +++ b/packages/oracles/oracle-gaps/capture-setup.mjs @@ -24,7 +24,14 @@ // In a mutant run, fast-check stops a property at its first failure instead // of shrinking it: a kill needs one failing history, not the smallest one. import { createHash } from 'node:crypto' -import { appendFileSync, readFileSync } from 'node:fs' +import { + appendFileSync, + closeSync, + fstatSync, + openSync, + readFileSync, + readSync, +} from 'node:fs' import { createRequire, syncBuiltinESMExports } from 'node:module' import { dirname, isAbsolute, join } from 'node:path' import { fileURLToPath, pathToFileURL } from 'node:url' @@ -306,22 +313,33 @@ let childRead = 0 * output. A line still being written waits for the next fold (133-2). */ function foldChildren() { + // Only the bytes after the last fold (`childRead`), so a check's folds cost + // what the tree wrote since the last one, not the whole log (review of #133, + // 133-15). let text + let fd try { - text = globalThis.__oracleGapsOriginalFs.readFileSync(childLog, `utf8`) + fd = openSync(childLog, `r`) + const size = fstatSync(fd).size + if (size <= childRead) return + const chunk = Buffer.alloc(size - childRead) + readSync(fd, chunk, 0, chunk.length, childRead) + text = chunk.toString(`utf8`) } catch { return + } finally { + if (fd !== undefined) closeSync(fd) } const end = text.lastIndexOf(`\n`) - if (end < childRead) return + if (end < 0) return const reads = globalThis.__oracleGapsReads - for (const line of text.slice(childRead, end).split(`\n`)) { + for (const line of text.slice(0, end).split(`\n`)) { if (line === ``) continue const [op, key, hash] = JSON.parse(line) if (op === `W`) wrote.add(key) else if (!wrote.has(key) && !reads.has(key)) reads.set(key, hash) } - childRead = end + 1 + childRead += Buffer.byteLength(text.slice(0, end + 1)) } /** * Whether the copy or a process it started wrote the file that `key` names: From f2a09af7411d4c78676c507583f4bfda3c60935b Mon Sep 17 00:00:00 2001 From: Kyle Mathews Date: Wed, 2 Dec 2026 08:29:50 -0700 Subject: [PATCH 08/51] fix(oracle-gaps): repair the CodeRabbit findings that hold on the head Probe-backed (RED before, GREEN after; probes in /tmp/gap-pr/cr): - A file is hashed in chunks, so a file past readFileSync's limit keeps its edits instead of hashing as missing (CR-10). - A failed write marks nothing. A write that keeps its bytes (append, and the flag r+) reads them first. A write marks the file once it has succeeded (CR-12, CR-21). - A path keeps its spelling, so `..` after a symbolic link is resolved by the kernel, not collapsed first (CR-22). - A child's log write that fails leaves .lost and the child keeps its result; the copy does not store that run (CR-19). - A worker started by a worker is watched, at any depth, and an eval worker keeps its 'use strict' prologue (CR-24, CR-25). One patch serves the test realm and every preloaded process (patchWorkerThreads). - The CLI sends its environment only to a daemon socket this user owns (CR-6). Code, not yet RED-witnessed by an oracle history: - A child's reads fold before a read tests the tree's writes (CR-16, CR-26). - The CLI side: a write is hashed when it succeeds, not at the check's end (CR-14); a stat of an own write is no input (CR-3); the global key uses the warm reads' hashes (CR-4); a write clears the hook-log holds (CR-18). - Generator: an unchanged recheck does not set the fixture's time (CR-20); a client environment is not used with a raw-import check (CR-8). - Listing hashes fall back to Dirent.path on Node 20.1 to 20.11 (CR-11). Docs: the changeset and the README name the reads that stay untracked, and that a directory's stat is by kind (CR-1, CR-13). Open, not in this commit: CR-2 (a frozen plugin's hook; a design decision), CR-17 (warm reads of a switched config), CR-18 (a unit's own writes into a listed path), CR-23 (a stream's bytes before it opens). See the ledger. Co-authored-by: Isaac --- .changeset/gap-cli-daemon-every-read.md | 8 +- README.md | 22 ++- .../oracles/oracle-gaps/capture-setup.mjs | 66 +++---- packages/oracles/oracle-gaps/check.mjs | 81 +++++--- packages/oracles/oracle-gaps/child-writes.mjs | 41 +++- packages/oracles/oracle-gaps/daemon.mjs | 32 +++- .../oracle-gaps/gap-report-model-oracle.mjs | 20 +- packages/oracles/oracle-gaps/inputs.mjs | 175 +++++++++++++++--- 8 files changed, 334 insertions(+), 111 deletions(-) diff --git a/.changeset/gap-cli-daemon-every-read.md b/.changeset/gap-cli-daemon-every-read.md index 0bb98f78..0caf912c 100644 --- a/.changeset/gap-cli-daemon-every-read.md +++ b/.changeset/gap-cli-daemon-every-read.md @@ -6,6 +6,10 @@ A check through `--daemon` now treats every read as an input of the runs that ma The daemon now runs each check in the environment of the CLI that asked for it. A check from another environment, or after a file that Vitest, the config, or a plugin read or wrote has changed, starts a new daemon. Because Vitest and Vite read every environment variable while they start, any change to the environment runs every unit again, as a cold run does. -Each check now hashes every file input from its content, so an edit that keeps a file's size and modification time, as `cp -p`, `rsync -t`, or `touch -r` leave it, is no longer missed. +Each check now hashes every file input from its content, so an edit that keeps a file's size and modification time, as `cp -p`, `rsync -t`, or `touch -r` leave it, is no longer missed. A test that stats a file by its size or times has that metadata as an input too, while a directory's stat is an input by its kind alone. -A file that a test, or a Node process it started at any depth, wrote before the test read it is the test's own output and no input, so a test whose child writes a temporary file is reused on an unchanged check. +A file that a test, or a Node process or worker thread it started at any depth, wrote before the test read it is the test's own output and no input, so a test whose child writes a temporary file is reused on an unchanged check. + +Not every read is tracked yet. These stay untracked, and the README lists them: a read through a file descriptor, a link's target, the other stat calls, `glob`, `copyFile` and `cp`; a directory's own metadata; a child process started with an environment that drops `NODE_OPTIONS`, and a writer that is not Node. Run the check cold after an edit to one of them. Vitest's own discovery listings are left out on purpose. + +The CLI sends its environment to its daemon's socket only when this user owns that socket, so another user's listener in the shared temporary directory cannot receive it. diff --git a/README.md b/README.md index 6d044a12..b90c6b28 100644 --- a/README.md +++ b/README.md @@ -247,9 +247,13 @@ runs cold` and runs the check in its own process, which reports what the Every read is an input (maintainer decision, 2026-11-16): the modules the run loaded; the files its tests read through `fs` on any path, inside the package or outside it, `node_modules` included (`readFileSync`, - `readFile`, `createReadStream`, `existsSync`, `statSync`, and - `fs/promises` `readFile` and `stat`), each by the content that the run - read; the directories its tests list (`readdir`, `readdirSync`, `opendir`, + `readFile`, `createReadStream`, and `fs/promises` `readFile`), each by the + content that the run read; the files its tests stat, by their existence + and kind (`existsSync`), or by their size, times, identity, and mode + (`statSync`, `stat` with or without a callback, and `fs/promises` `stat`), + where a directory's stat is an input by its kind alone, so a directory's + own size or times are not (a limit, CR-13); the directories its tests list + (`readdir`, `readdirSync`, `opendir`, `opendirSync`, and `fs/promises` `readdir` and `opendir`), each by its entries' names and kinds; the environment variables its tests read, by value, or all of them when a test lists them; and what Vitest, Vite, and @@ -270,6 +274,11 @@ runs cold` and runs the check in its own process, which reports what the reused. A directory that a test stats or tests for is an input as a directory, not by its content. + The CLI sends its environment with each request, so it sends it only to a + daemon socket that this user owns; a socket another user made in the + shared temporary directory is refused, and no request goes to it. On + Windows, a named pipe has no owner check here. + The daemon runs every check in the environment that the CLI asking for it has. While a context warms, Vitest and Vite read every environment variable by value, so a check from an environment that differs in any @@ -279,7 +288,8 @@ runs cold` and runs the check in its own process, which reports what the wrote has changed. The harness gives each worker thread and each child process that a test - starts its preload, so their reads are inputs too. A `require` in a test + starts its preload, at any depth (a worker started by a worker included), + so their reads are inputs too. A `require` in a test consults the `package.json` files that decide a package's `main` and `type`; Node reads them itself, so the harness records them through a wrapper on `Module._resolveFilename`, a private Node API (check.mjs says @@ -292,8 +302,8 @@ runs cold` and runs the check in its own process, which reports what the These reads are no input yet, so an edit to the file alone does not rerun the tests that read it: a read through a file descriptor, after `open`, `openSync`, or the `fs/promises` `open` (#141); a link's target, or the - rest of the stat family, `lstat`, `readlink`, `realpath`, `access`, the - callback `stat`, and `exists` (#142); `glob`, `globSync`, `copyFile`, + rest of the stat family, `lstat`, `readlink`, `realpath`, `access`, and + `exists` (#142); `glob`, `globSync`, `copyFile`, `copyFileSync`, `cp`, `cpSync`, `openAsBlob`, `statfs`, and the `fs/promises` `glob`, `copyFile`, `cp`, and `statfs` (#152); the module-level reads of a test file whose tests are all skipped (#153); and diff --git a/packages/oracles/oracle-gaps/capture-setup.mjs b/packages/oracles/oracle-gaps/capture-setup.mjs index d6d02c61..bf7ed262 100644 --- a/packages/oracles/oracle-gaps/capture-setup.mjs +++ b/packages/oracles/oracle-gaps/capture-setup.mjs @@ -27,6 +27,7 @@ import { createHash } from 'node:crypto' import { appendFileSync, closeSync, + existsSync, fstatSync, openSync, readFileSync, @@ -37,7 +38,12 @@ import { dirname, isAbsolute, join } from 'node:path' import { fileURLToPath, pathToFileURL } from 'node:url' import { threadId } from 'node:worker_threads' import { afterAll, beforeEach, chai, expect, inject, vi } from 'vitest' -import { inputHash, keepProperties, watchReads } from './inputs.mjs' +import { + inputHash, + keepProperties, + patchWorkerThreads, + watchReads, +} from './inputs.mjs' import { writeWhole } from './paths.mjs' const run = @@ -365,10 +371,15 @@ function isRunnerOwnAppend(key, write) { return own.some((file) => path === posixOf(file)) } watchReads((key, write) => { + // The child reads that came before this event fold first, so each is + // judged, in its order, before this read tests the tree's writes and the + // reads (CR-16: a child's earlier hash must not be overwritten here). + foldChildren() const reads = globalThis.__oracleGapsReads - // A read, or the read that an append makes of the text it adds to (133-3), - // is an input unless the copy or its process tree wrote the file first, or - // the append is the runner's own (isRunnerOwnAppend). + // A read, or the read that a write which keeps its bytes makes before the + // write (`append`, 133-3, CR-21), is an input unless the copy or its process + // tree wrote the file first, or the append is the runner's own + // (isRunnerOwnAppend). A write marks the file once it has succeeded (`true`). if ( write !== true && !isRunnerOwnAppend(key, write) && @@ -377,11 +388,7 @@ watchReads((key, write) => { !ownOutput(key) ) reads.set(key, key.startsWith(`env:`) ? null : inputHash(key)) - if (write) { - // The child reads before this write come first, so they are inputs. - foldChildren() - wrote.add(key) - } + if (write === true) wrote.add(key) }) if (!globalThis.__oracleGapsChildren) { globalThis.__oracleGapsChildren = true @@ -415,6 +422,8 @@ function scopeKeysOf(dir) { return keys } function recordScope(dir) { + // The child reads that came first fold before these reads are tested (CR-26). + foldChildren() const reads = globalThis.__oracleGapsReads for (const key of scopeKeysOf(dir)) if (!reads.has(key) && !wrote.has(key) && !ownOutput(key)) @@ -440,37 +449,9 @@ Module._resolveFilename = function (request, parent, ...rest) { // `env` is an object gets the log's name too. if (!globalThis.__oracleGapsWorkers) { globalThis.__oracleGapsWorkers = true - const threads = createRequire(import.meta.url)(`node:worker_threads`) - const Base = threads.Worker - const preload = pathToFileURL(join(home, `child-writes.mjs`)).href - class Watched extends Base { - constructor(file, options = {}) { - const env = - options.env && typeof options.env === `object` - ? { - ...options.env, - ORACLE_GAPS_CHILD_WRITES: process.env.ORACLE_GAPS_CHILD_WRITES, - } - : options.env - // An eval worker ignores `--import` in its execArgv, so its code first - // requires the preload (a synchronous require of this ES module). - const code = - options.eval && typeof file === `string` - ? `require(${JSON.stringify(join(home, `child-writes.mjs`))});\n${file}` - : file - super(code, { - ...options, - env, - execArgv: [ - ...(options.execArgv ?? process.execArgv), - `--import`, - preload, - ], - }) - } - } - threads.Worker = Watched - syncBuiltinESMExports() + // The patch (inputs.mjs) is the same one each preloaded process applies, so + // a worker started from a worker is covered too (CR-25). + patchWorkerThreads(join(home, `child-writes.mjs`)) } // A test's own writes to the process's stdout and stderr (a debugging // `process.stdout.write`) go to the run's test-output.log, beside its @@ -1306,7 +1287,10 @@ afterAll(() => { // The child processes' reads after the copy's last own read or write. foldChildren() const readAt = Object.fromEntries(globalThis.__oracleGapsReads) + // A child process that lost a line of its log (child-writes.mjs) left the + // marker, so the run's reads are not all here (CR-19). + const childLost = existsSync(`${childLog}.lost`) appendClosingRow( - `${JSON.stringify({ file: thisFile, closed: true, at: realNow(), loaded, readAt, ...(skippedCopy ? { skipped: true } : {}) })}\n`, + `${JSON.stringify({ file: thisFile, closed: true, at: realNow(), loaded, readAt, childLost, ...(skippedCopy ? { skipped: true } : {}) })}\n`, ) }) diff --git a/packages/oracles/oracle-gaps/check.mjs b/packages/oracles/oracle-gaps/check.mjs index 89b7e2ea..63da347f 100644 --- a/packages/oracles/oracle-gaps/check.mjs +++ b/packages/oracles/oracle-gaps/check.mjs @@ -96,7 +96,7 @@ import { specifierOf, } from './paths.mjs' import { stateDirOf } from './evidence.mjs' -import { envHash, inputHash, watchReads } from './inputs.mjs' +import { envHash, fileSha1, inputHash, watchReads } from './inputs.mjs' import { baselineOf, blockedOr, @@ -294,7 +294,7 @@ function fileHashes() { if (known?.stamp === stamp) return known.hash let hash try { - hash = sha1(readFileSync(path)) + hash = fileSha1(path) } catch { // Removed between the stat and the read. return `missing` @@ -544,12 +544,16 @@ export async function openSession(pkg, pause = async () => {}) { const reading = new AsyncLocalStorage() watchReads((key, write) => { const at = reading.getStore() - if (write && key.startsWith(`env:`)) wrote.add(key) + if (write === true && key.startsWith(`env:`)) wrote.add(key) const reads = at?.hook || at?.done ? hookReads : warmReads if (at === undefined || at.discovery || key === at.module) return - // A read, or the read that an append makes of the text it adds to - // (133-3), is an input unless the session wrote the file first. - if (write !== true && !wrote.has(key) && !reads.has(key)) { + // A stat of a file the session wrote is no input either, as a copy's stat + // of its own output is not (capture-setup.mjs, ownOutput; CR-3). + const ownWrite = + wrote.has(key) || wrote.has(key.replace(/^(stat|statx):/, `fs:`)) + // A read, or the read that a write which keeps its bytes makes before it + // (133-3, CR-21), is an input unless the session wrote the file first. + if (write !== true && !ownWrite && !reads.has(key)) { const hash = key.startsWith(`env:`) ? reads === hookReads ? envHash(key.slice(4)) @@ -558,9 +562,18 @@ export async function openSession(pkg, pause = async () => {}) { reads.set(key, hash) if (reads === hookReads) hookLog.push([key, hash]) } - // A write is the session's, even when the file was read before it in - // this check: it must still hold its text at the next check (`written`). - if (write) wrote.add(key) + if (write === true) { + // A write is the session's, once it has succeeded: the file must still + // hold the text it wrote at the next check, so its hash is taken now, + // not at the check's end, where a hand edit made in between would be + // stored as the session's own text (`written`; CR-14). + wrote.add(key) + if (key.startsWith(`fs:`)) written.set(key, inputHash(key)) + // A listed path that this write changed is no longer held by the hook + // log's prefixes, which a later unit would otherwise still judge held + // (CR-18). + holds.clear() + } }) // Runs `work` as a warm under `reading`. const warming = async (work) => { @@ -1306,6 +1319,9 @@ export default async (env) => { rows, inputs: importsOf(file, modules, closing), readAt: closing.readAt, + // A child process's log lost lines, so its reads are not all here + // (child-writes.mjs): the run is not stored (CR-19). + childLost: closing.childLost === true, } } @@ -1323,6 +1339,7 @@ export default async (env) => { seconds, inputs: importsOf(file, modules, closing), readAt: closing.readAt, + childLost: closing.childLost === true, } } @@ -1627,6 +1644,7 @@ export default async (env) => { rows: own.map((row) => [row.key, row]), inputs: importsOf(item.file, [], closings.get(copies[i])), readAt: closings.get(copies[i])?.readAt, + childLost: closings.get(copies[i])?.childLost === true, } }), timedOutAt: current, @@ -1691,6 +1709,7 @@ export default async (env) => { .map((row) => [map(row.key), { ...row, key: map(row.key) }]), inputs: importsOf(item.file, modules, closings.get(copy)), readAt: closings.get(copy)?.readAt, + childLost: closings.get(copy)?.childLost === true, } }), } @@ -1817,8 +1836,6 @@ export default async (env) => { try { return await checkIn(...args) } finally { - for (const key of wrote) - if (key.startsWith(`fs:`)) written.set(key, inputHash(key)) // The session's hook log, for units that later sessions look up, once // it has grown: a put marks the store to be written again, whole. if (hookLog.length > hookLogStored) { @@ -1977,8 +1994,16 @@ export default async (env) => { .sort() .map((file) => [file, hashOf(file)]), // What Vitest, Vite, and the config read while Vitest loaded and the - // contexts warmed (warmReads), each by its value now. - [...warmReads.keys()].sort().map((key) => [key, servedHash(key)]), + // contexts warmed (warmReads), each by its value at that read: the + // contexts were warmed on that text, so a file edited since is keyed + // by what the run used, and the next check, which finds the file + // changed, computes it again (CR-4). A variable is read now. + [...warmReads] + .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)) + .map(([key, hash]) => [ + key, + key.startsWith(`env:`) ? servedHash(key) : hash, + ]), process.version, options.seed ?? null, settings, @@ -2115,17 +2140,20 @@ export default async (env) => { options.seed ?? null, ) const inputs = items.map(({ file }, k) => - settleIn( - context, - started, - [ - ...new Set([ - ...(fileInputs.get(file) ?? []), - ...(batch.units[k]?.inputs ?? []), - ]), - ], - batch.units[k]?.readAt, - ), + // A unit whose child log lost lines is not stored (CR-19). + batch.units[k]?.childLost + ? undefined + : settleIn( + context, + started, + [ + ...new Set([ + ...(fileInputs.get(file) ?? []), + ...(batch.units[k]?.inputs ?? []), + ]), + ], + batch.units[k]?.readAt, + ), ) return { ...batch, inputs } } @@ -2168,7 +2196,10 @@ export default async (env) => { if (!result.timedOut && spec.startsWith(`unmutated:`)) fileInputs.set(file, result.inputs) if (paths) { - const inputs = settleIn(context, started, paths, result.readAt) + // A run whose child log lost lines is not stored (CR-19). + const inputs = result.childLost + ? undefined + : settleIn(context, started, paths, result.readAt) if (keep) remember(id, result, inputs) } return result diff --git a/packages/oracles/oracle-gaps/child-writes.mjs b/packages/oracles/oracle-gaps/child-writes.mjs index 9321c4de..1070f068 100644 --- a/packages/oracles/oracle-gaps/child-writes.mjs +++ b/packages/oracles/oracle-gaps/child-writes.mjs @@ -14,16 +14,47 @@ // #133 before merging", 2026-11-19; review of #133, F-2). An environment // variable is the CLI's to watch: the whole environment restarts the daemon. // The log is written through a file descriptor, which no wrapper watches. -import { openSync, writeSync } from 'node:fs' -import { inputHash, watchReads } from './inputs.mjs' +import { openSync, writeFileSync, writeSync } from 'node:fs' +import { fileURLToPath } from 'node:url' +import { inputHash, patchWorkerThreads, watchReads } from './inputs.mjs' const log = process.env.ORACLE_GAPS_CHILD_WRITES if (log) { - const fd = openSync(log, `a`) - const put = (line) => writeSync(fd, `${JSON.stringify(line)}\n`) + // The log is telemetry: a failed write (a full disk, a log that cannot be + // opened) must not change the child's own result (CR-19). The child then + // goes on unlogged, and leaves `.lost`, which the copy reads, so the + // run that it belongs to is not stored as complete. + let fd + let lost = false + const lose = () => { + lost = true + try { + writeFileSync(`${log}.lost`, ``) + } catch { + // The marker cannot be written either; nothing more to do. + } + } + try { + fd = openSync(log, `a`) + } catch { + lose() + } + const put = (line) => { + if (lost) return + try { + writeSync(fd, `${JSON.stringify(line)}\n`) + } catch { + lose() + } + } watchReads((key, write) => { if (key.startsWith(`env:`)) return if (write !== true) put([`R`, key, inputHash(key)]) - if (write) put([`W`, key]) + // A write is logged once it has succeeded (inputs.mjs), so a failed one + // makes nothing the tree's own (CR-12). + if (write === true) put([`W`, key]) }) + // A worker started by this process, or by a worker, gets the preload too + // (CR-25). + patchWorkerThreads(fileURLToPath(import.meta.url)) } diff --git a/packages/oracles/oracle-gaps/daemon.mjs b/packages/oracles/oracle-gaps/daemon.mjs index 5859656f..ede69f3d 100644 --- a/packages/oracles/oracle-gaps/daemon.mjs +++ b/packages/oracles/oracle-gaps/daemon.mjs @@ -34,6 +34,7 @@ import { randomUUID } from 'node:crypto' import { existsSync, linkSync, + lstatSync, mkdirSync, openSync, readFileSync, @@ -130,6 +131,22 @@ async function pauseAt(point) { * reaches it. The bound changes the run's path, never its outcome: the CLI * then checks cold (v21.2 R39, I15). */ +/** + * Whether a daemon's endpoint is one this user may send to: a Unix socket + * that this user owns (CR-6). Absent, it is ours to start a daemon at, so the + * connect reports that. A named pipe (Windows) has no owner check here, which + * the README lists as a limit. + */ +function endpointIsOurs(endpoint) { + if (process.platform === `win32`) return true + try { + const stat = lstatSync(endpoint) + return stat.isSocket() && stat.uid === process.getuid() + } catch { + return true + } +} + function send(pkg, message, bounded = false) { return new Promise((settle, reject) => { // Test-only (ORACLE_GAPS_TEST_WAIT_MARK, a path): the bound is a pause @@ -141,7 +158,20 @@ function send(pkg, message, bounded = false) { settle(value) } const fail = reject - const socket = connect(socketOf(pkg)) + // The request carries this CLI's environment, so it goes only to a socket + // this user made (CR-6). On a shared host another user can listen on the + // path first, in the shared temporary directory, so an endpoint that is + // not ours is refused, and no byte of the request is written to it. + const endpoint = socketOf(pkg) + if (!endpointIsOurs(endpoint)) { + reject( + new Error( + `the daemon's socket ${endpoint} is not a socket this user owns, so the check does not send its environment to it; remove that path and check again`, + ), + ) + return + } + const socket = connect(endpoint) let reply = `` socket.on(`connect`, () => socket.write(`${JSON.stringify(message)}\n`)) if (bounded) { diff --git a/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs b/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs index c8087ae5..e16a0dc6 100644 --- a/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs +++ b/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs @@ -11,6 +11,7 @@ import { readFileSync, readlinkSync, rmSync, + statSync, symlinkSync, unlinkSync, utimesSync, @@ -3700,10 +3701,14 @@ function resolveHistory(history) { slowStart: history.slowStart ?? false, shortWait: history.shortWait === true, childWrite: history.childWrite === true, + // A client environment rewrites `new URL(..., import.meta.url)` to the dev + // server's URL, so file b's raw-import check (rawImport) cannot read the + // module there: such a history runs its file b in node (CR-8). childEnvironment: history.childWrite === true && (history.inputRead ?? `none`) === `none` && - (history.fsRead ?? `none`) === `none` + (history.fsRead ?? `none`) === `none` && + !(history.tests ?? []).some((t) => t.file === `b` && t.rawImport) ? (history.childEnvironment ?? `node`) : `node`, // The gate input that file b's verdicts also wait on (`inputRead`), and @@ -7238,9 +7243,16 @@ function writeFixture(dir, files) { const text = typeof value?.text === `string` ? value.text : value // An unchanged file keeps its modification time, as in a real package. if (typeof text === `string`) { - if (!existsSync(at) || readFileSync(at, `utf8`) !== text) - writeFileSync(at, text) - if (value.mtime !== undefined) utimesSync(at, value.mtime, value.mtime) + const changed = !existsSync(at) || readFileSync(at, `utf8`) !== text + if (changed) writeFileSync(at, text) + // The stamp is set after a content write, or where the time differs: a + // utimes call always advances the ctime, which a stat input reads, so an + // unchanged recheck must not make one (CR-20). + if ( + value.mtime !== undefined && + (changed || Math.floor(statSync(at).mtimeMs / 1000) !== value.mtime) + ) + utimesSync(at, value.mtime, value.mtime) } else if (linkTarget(at) !== text.link) { // A link that a later state points elsewhere is replaced. removePath(at) diff --git a/packages/oracles/oracle-gaps/inputs.mjs b/packages/oracles/oracle-gaps/inputs.mjs index 1e3b93ba..81adbe0d 100644 --- a/packages/oracles/oracle-gaps/inputs.mjs +++ b/packages/oracles/oracle-gaps/inputs.mjs @@ -18,9 +18,9 @@ // harness with this one. import { createHash } from 'node:crypto' import fs from 'node:fs' -import { syncBuiltinESMExports } from 'node:module' -import { basename, dirname, join, resolve } from 'node:path' -import { fileURLToPath } from 'node:url' +import { createRequire, syncBuiltinESMExports } from 'node:module' +import { basename, dirname, isAbsolute, join } from 'node:path' +import { fileURLToPath, pathToFileURL } from 'node:url' import { posix } from './paths.mjs' // The calls that read a file (a stream's too, by the whole file). Each is @@ -63,6 +63,28 @@ const original = (globalThis.__oracleGapsOriginalFs ??= { }) const sha1 = (data) => createHash(`sha1`).update(data).digest(`hex`) +/** + * The SHA-1 of a file's bytes, read in chunks: a whole-file read fails for a + * regular file past about 2 GiB (ERR_FS_FILE_TOO_LARGE), and such a file's + * edits must still be seen (CR-10). Equal to `sha1(readFileSync(path))` for + * any file that a whole read can take. + */ +export function fileSha1(path) { + const hash = createHash(`sha1`) + const fd = fs.openSync(path, `r`) + try { + const chunk = Buffer.allocUnsafe(1 << 20) + for (;;) { + const count = fs.readSync(fd, chunk, 0, chunk.length, null) + if (count === 0) break + hash.update(chunk.subarray(0, count)) + } + } finally { + fs.closeSync(fd) + } + return hash.digest(`hex`) +} + /** * A file's input hash now, never from a cache: the hash of its text, or * `not a file` (a test can stat a directory, whose input is that a @@ -70,14 +92,17 @@ const sha1 = (data) => createHash(`sha1`).update(data).digest(`hex`) */ export function fileHash(path) { try { - return original.statSync(path).isFile() - ? sha1(original.readFileSync(path)) - : `not a file` + return original.statSync(path).isFile() ? fileSha1(path) : `not a file` } catch { return `missing` } } +// The directory that holds an entry of a listing: `parentPath` where Node has +// it (20.12 and later, 21.4 and later), else `path`, which Node 20.1 to 20.11 +// gave as the parent (CR-11), else the listing's root. +const parentOf = (entry, root) => entry.parentPath ?? entry.path ?? root + /** * A directory's input hash now: that of its entries' names and kinds, every * level's for a recursive listing, or `not a directory`, or `missing`. @@ -90,11 +115,11 @@ function listingHash(path, recursive) { // The runner's own entries (its session directory) are no input. .filter( (entry) => - !isRunnerFile(`${posix(entry.parentPath ?? path)}/${entry.name}/`), + !isRunnerFile(`${posix(parentOf(entry, path))}/${entry.name}/`), ) .map( (entry) => - `${posix(entry.parentPath ?? path)}/${entry.name}\0${entry.isDirectory() ? `d` : entry.isSymbolicLink() ? `l` : `f`}`, + `${posix(parentOf(entry, path))}/${entry.name}\0${entry.isDirectory() ? `d` : entry.isSymbolicLink() ? `l` : `f`}`, ) .sort() .join(`\0`), @@ -166,6 +191,11 @@ export const envHash = ( : `${env[name] === undefined ? `unset` : `=${env[name]}`}`, ) +// A path as it was given, made absolute against the working directory but +// with its `..` components kept (CR-22). +const spelledAbsolute = (path) => + isAbsolute(path) ? path : `${process.cwd()}/${path}` + // The runner's own files: a session directory (`.oracle-gaps-/`, which // holds this file) and the copies of test files // (`.oracle-gaps---`). A user's path that only contains @@ -199,29 +229,38 @@ export function watchReads(record) { if (globalThis.__oracleGapsWatching) return globalThis.__oracleGapsWatching = true record = (key, write) => globalThis.__oracleGapsRecord(key, write) + // Records what a call reads before it runs, and returns the mark that + // records what a write makes the tree's own once the write has succeeded + // (undefined for a call that writes nothing). A failed write marks nothing + // (CR-12), so a read after it is an input. const watched = (target, kind, args, name) => { const write = kind === `write` // A listing's options come first, a write's after its data. const options = kind === `list` ? args[0] : args[1] - // An append reads the text it adds to before it writes, so that text is - // an input unless the copy wrote it first (133-3). An append is a call - // named `append...`, or a write with the flag `a`. - const appends = + // A write that keeps the bytes it does not overwrite reads them first: + // an append (a call named `append...`, or the flag `a`), and a + // read-write open without truncation (the flag `r+`, CR-21). Its read is + // an input unless the copy wrote the file first (133-3), so it records + // `append` (a read) before the call, and `true` (the write) after it. + const flag = + typeof options === `object` && options !== null + ? String(options.flag ?? `w`) + : `w` + const keeps = write && - (/append/i.test(name) || - (typeof options === `object` && - options !== null && - String(options.flag ?? ``).startsWith(`a`))) - const mark = appends ? `append` : write + (/append/i.test(name) || flag.startsWith(`a`) || flag.startsWith(`r`)) let path try { - if (target instanceof URL) path = resolve(fileURLToPath(target)) - else if (typeof target === `string`) path = resolve(target) - else if (Buffer.isBuffer(target)) path = resolve(target.toString()) + // A path keeps the spelling it was given: the kernel resolves `..` + // after a symbolic link, which `resolve` would collapse first (CR-22). + if (target instanceof URL) path = fileURLToPath(target) + else if (typeof target === `string`) path = spelledAbsolute(target) + else if (Buffer.isBuffer(target)) + path = spelledAbsolute(target.toString()) } catch { - return + return undefined } - if (path === undefined || isRunnerFile(posix(path))) return + if (path === undefined || isRunnerFile(posix(path))) return undefined const prefix = kind === `stat` ? `stat` @@ -232,18 +271,25 @@ export function watchReads(record) { : options?.recursive ? `dirs` : `dir` - record(`${prefix}:${posix(path)}`, mark) + const keys = [`${prefix}:${posix(path)}`] // A written file is also known by its directory's real path, which a // later read through a link, or an import by its real URL, names. if (write) try { - record( + keys.push( `fs:${posix(join(original.realpathSync(dirname(path)), basename(path)))}`, - mark, ) } catch { // No directory to write in: the write fails as it would. } + if (!write) { + for (const key of keys) record(key, false) + return undefined + } + if (keeps) for (const key of keys) record(key, `append`) + return () => { + for (const key of keys) record(key, true) + } } for (const [calls, kind] of [ [reads, `read`], @@ -256,8 +302,26 @@ export function watchReads(record) { for (const name of names) { const call = owner[name] owner[name] = keepProperties(call, function (target, ...rest) { - watched(target, kind, rest, name) - return call.call(this, target, ...rest) + const mark = watched(target, kind, rest, name) + if (mark === undefined) return call.call(this, target, ...rest) + // The mark follows the write's success: a callback without an + // error, a promise's resolution, or the sync return. + if (typeof rest.at(-1) === `function`) { + const done = rest.pop() + rest.push(function (error, ...values) { + if (!error) mark() + return done.call(this, error, ...values) + }) + return call.call(this, target, ...rest) + } + const result = call.call(this, target, ...rest) + if (result && typeof result.then === `function`) + return result.then((value) => { + mark() + return value + }) + mark() + return result }) } syncBuiltinESMExports() @@ -286,3 +350,60 @@ export function watchReads(record) { }, }) } + +// The code of an eval worker with the preload first (CR-24). The preload goes +// after the directive prologue (`'use strict'`), which must stay the first +// statements of the code, or the worker's strictness changes. +const preloadedCode = (code, preload) => { + // Leading space and comments, then `'use strict'` statements, each ended by + // `;` or a line end (so `'use strict'.length` is not a directive). + const prologue = + /^(?:\s|\/\/[^\n]*\n|\/\*[\s\S]*?\*\/)*(?:(['"])use strict\1(?:[ \t]*;|[ \t]*(?=\n))\s*)*/.exec( + code, + )[0] + return `${prologue};require(${JSON.stringify(preload)});\n${code.slice(prologue.length)}` +} + +/** + * Gives every Worker that this realm starts the child-writes preload, so a + * worker's reads and writes reach the log of its process tree (#143). A + * worker takes the `--import` in its execArgv, and an eval worker ignores it, + * so its code first requires the preload (`preloadedCode`). A worker whose + * `env` is an object gets the log's name too. Applied in the test's realm by + * capture-setup.mjs, and in every preloaded process by child-writes.mjs, so a + * worker started from a worker is covered at any depth (CR-25). + */ +export function patchWorkerThreads(preload) { + if (globalThis.__oracleGapsWorkerPatch) return + globalThis.__oracleGapsWorkerPatch = true + const threads = createRequire(import.meta.url)(`node:worker_threads`) + const Base = threads.Worker + const href = pathToFileURL(preload).href + class Watched extends Base { + constructor(file, options = {}) { + const env = + options.env && typeof options.env === `object` + ? { + ...options.env, + ORACLE_GAPS_CHILD_WRITES: process.env.ORACLE_GAPS_CHILD_WRITES, + } + : options.env + super( + options.eval && typeof file === `string` + ? preloadedCode(file, preload) + : file, + { + ...options, + env, + execArgv: [ + ...(options.execArgv ?? process.execArgv), + `--import`, + href, + ], + }, + ) + } + } + threads.Worker = Watched + syncBuiltinESMExports() +} From 0c1c6839fb2cf695733e94f5be67979f5b15292b Mon Sep 17 00:00:00 2001 From: Kyle Mathews Date: Wed, 2 Dec 2026 08:58:31 -0700 Subject: [PATCH 09/51] fix(oracle-gaps): a file the session wrote and then removed is no change The session records each file it writes by its text at the write (CR-14), so a file that Vite then deletes (the config it bundles into a temporary file, once loaded) read as changed at the next check, and the daemon restarted on every request. A file that is missing at the check's end is now stored as missing: its removal is the session's own, while an edit that keeps the file in place is still seen (the hand-edit history stays GREEN, 3 of 3). Co-authored-by: Isaac --- packages/oracles/oracle-gaps/check.mjs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/packages/oracles/oracle-gaps/check.mjs b/packages/oracles/oracle-gaps/check.mjs index 63da347f..35b6a795 100644 --- a/packages/oracles/oracle-gaps/check.mjs +++ b/packages/oracles/oracle-gaps/check.mjs @@ -1836,6 +1836,15 @@ export default async (env) => { try { return await checkIn(...args) } finally { + // A file the session wrote and then removed (Vite deletes the config it + // bundles into a temporary file once it has loaded it) is no longer the + // session's to keep: it is stored as missing, so the removal is not a + // change that restarts the daemon. An edit that keeps the file in place + // is still seen, since its hash stays the one taken when it was written + // (CR-14, and the regression that the write-time hash caused). + for (const key of wrote) + if (key.startsWith(`fs:`) && inputHash(key) === `missing`) + written.set(key, `missing`) // The session's hook log, for units that later sessions look up, once // it has grown: a put marks the store to be written again, whole. if (hookLog.length > hookLogStored) { From a7600bb0ef47bdb37a5db46c36da9d1694244617 Mon Sep 17 00:00:00 2001 From: Kyle Mathews Date: Wed, 2 Dec 2026 09:43:18 -0700 Subject: [PATCH 10/51] fix(oracle-gaps): a mid-run edit of a gate that a test reads lands in its check The mid-run history for a gate (`midrunGate`) never landed its edit: the edit's marker was in the daemon's session directory, and the check the edit overlaps restarts the daemon (file b's text counts its mid-run edits, which the session reads), which removed the directory and the marker. The marker is now one per package (`.oracle-gaps-midrun.txt`), runner-owned by the same rule as the other runner files (inputs.mjs isRunnerFile), so no run takes it as an input. The writer's guard reads the gate for a gate target (it read the helper before), a gate's drawn flag stays false for the helper and data histories (`midrunGate: false`, which keeps their draws), and the history fingerprint gains the new field at its end. The history `an edit to a gate that a test reads, during a check through the daemon` is GREEN (3 of 3). On the unrepaired production (the rule removed), it is killed by the witness guard law: the marker is stored as a run's input. Co-authored-by: Isaac --- .../oracle-gaps/constructed-order.json | 3 +- .../oracle-gaps/gap-report-model-oracle.mjs | 62 +++++++--- .../gap-report-oracle.property.test.mjs | 107 ++++++++++++++++-- .../oracle-gaps/history-fingerprint.json | 6 +- packages/oracles/oracle-gaps/inputs.mjs | 6 +- 5 files changed, 151 insertions(+), 33 deletions(-) diff --git a/packages/oracles/oracle-gaps/constructed-order.json b/packages/oracles/oracle-gaps/constructed-order.json index 94dbf3df..508be9fa 100644 --- a/packages/oracles/oracle-gaps/constructed-order.json +++ b/packages/oracles/oracle-gaps/constructed-order.json @@ -140,6 +140,7 @@ "a test that writes to the console, rechecked through the daemon", "an edit to a file a test reads inside a worker thread", "an edit to the package.json main that a test requires", - "an edit to the package.json type that a test requires" + "an edit to the package.json type that a test requires", + "an edit to a gate that a test reads, during a check through the daemon" ] } diff --git a/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs b/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs index e16a0dc6..4aabebff 100644 --- a/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs +++ b/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs @@ -1304,6 +1304,19 @@ const drawn = fc.record({ // takes it, and only where it reads no gate input or data, whose paths // take that form in the file's own text. childEnvironment: fc.constantFrom(`node`, `node`, `node`, `client`), + // Whether a mid-run edit (`midrun`, by file a's test) lands on the gate file + // that file b's verdict reads, not on the helper (`midrunTarget`, drawn + // earlier). Drawn last, so every field above draws as before. + midrunGate: fc.constantFrom( + false, + false, + false, + false, + false, + false, + false, + true, + ), }) // The edit sequence over the witness module, the one list of steps that a @@ -6352,7 +6365,7 @@ function oracleTestFile(plan, file) { `test('fixed seed 999', () => {})`, ) // The mid-run edit: the first run of this test after the driver marks an - // edit pending (`midrun.txt`, `pending:`) rewrites file b's + // edit pending (`.oracle-gaps-midrun.txt`, `pending:`) rewrites file b's // helper, or the data file, with that value and marks the edit done, so // every later run of it, in this check or another, changes nothing. It // calls nothing of the source under test, so no mutant reaches it. In @@ -6367,23 +6380,26 @@ function oracleTestFile(plan, file) { ...(file === `a` ? [` void strictAtLoad`] : [ - ` if (!(${plan.midrunTarget === `data` ? `(await readData()).open` : `strict`})) throw new Error('${MIDRUN_EDITORS[plan.midrunTarget].message}')`, + ` if (!(${plan.midrunTarget === `data` ? `(await readData()).open` : plan.midrunTarget === `gate` ? `(await readInput()).open` : `strict`})) throw new Error('${MIDRUN_EDITORS[plan.midrunTarget].message}')`, ]), - // The marker sits in the run's own session directory, beside the - // runner's harness (the worker's first setup file), which is no input - // of a run by design (check.mjs, ownHarness). So the marker's own edit - // does not decide whether the run is stored: only the helper's or the - // data's text does. A run with no harness, or no marker, edits nothing. + // The marker sits in the package, beside the daemon's session directory + // (the worker's first setup file is there), and it is runner-owned + // (inputs.mjs isRunnerFile), so the marker's own edit does not decide + // whether the run is stored: only the helper's or the data's text does. + // A run with no harness, or no marker, edits nothing. ` const harness = (globalThis as { __vitest_worker__?: { config?: { setupFiles?: Array } } }).__vitest_worker__?.config?.setupFiles?.[0]`, ` if (!harness) return`, - ` const marker = markerPath(markerDir(harness), 'midrun.txt')`, + ` const marker = markerPath(markerDir(markerDir(harness)), '.oracle-gaps-midrun.txt')`, ` let text = ''`, ` try { text = readMarker(marker, 'utf8') } catch { return }`, ` if (!text.startsWith('pending:')) return`, ` const value = text.slice('pending:'.length).trim()`, plan.midrunTarget === `data` ? ` writeEdit(new URL('./data.json', import.meta.url), \`{"open":\${value}}\\n\`)` - : ` writeEdit(new URL('./strict.ts', import.meta.url), \`export const strict = \${value}\\n\`)`, + : plan.midrunTarget === `gate` + ? // The gate file, as the gate kind writes it, open or shut. + ` writeEdit(new URL('./gate.json', import.meta.url), value === 'true' ? ${JSON.stringify(gateTextFor(plan.inputRead, true))} : ${JSON.stringify(gateTextFor(plan.inputRead, false))})` + : ` writeEdit(new URL('./strict.ts', import.meta.url), \`export const strict = \${value}\\n\`)`, ` writeEdit(marker, 'done\\n')`, `})`, ) @@ -6581,13 +6597,21 @@ const MIDRUN_EDITORS = { test: `edits the data during the check`, message: `the data this run read is closed`, }, + gate: { + test: `edits the gate during the check`, + message: `the gate this run read is shut`, + }, } /** What a mid-run edit changes: the data file only when file b reads one. */ const midrunTargetOf = (history) => - history.midrunTarget === `data` && (history.fsRead ?? `none`) !== `none` - ? `data` - : `helper` + // A gate file that the history's gate kind reads (`midrunGate`, a build-only + // flag: the drawn `midrunTarget` keeps its values, so main's draws stay). + history.midrunGate === true && gateFiles[history.inputRead] !== undefined + ? `gate` + : history.midrunTarget === `data` && (history.fsRead ?? `none`) !== `none` + ? `data` + : `helper` // Law 9's fixture state: the history, and what the edits outside it set. const initialState = (plan) => ({ @@ -7149,8 +7173,8 @@ function fixtureFiles(plan, state = initialState(plan)) { `// the plugin's file was edited to ${state.inputOpen ? `open` : `shut`}\n` // Each mid-run edit changes file a's own text too (a count of them), so // the daemon runs file a's tests again in the check the edit lands in, - // instead of reusing their evidence: the marker sits in the daemon's - // session directory, which is no input of a run. + // instead of reusing their evidence. The marker is runner-owned, so no run + // takes it as an input. if (plan.midrun) files[`tests/${plan.midrunBy}.test.ts`] += `// mid-run edits: ${state.midruns}\n` @@ -7324,9 +7348,11 @@ function applyEdit(state, edit) { // A mid-run edit leaves file b's helper as the helper edit does. if (edit === `helper`) return { ...state, strict: !state.strict } if (edit === `midrun`) - return midrunTargetOf(state.history) === `data` - ? { ...state, dataOpen: !state.dataOpen, midruns: state.midruns + 1 } - : { ...state, strict: !state.strict, midruns: state.midruns + 1 } + return midrunTargetOf(state.history) === `gate` + ? { ...state, inputOpen: !state.inputOpen, midruns: state.midruns + 1 } + : midrunTargetOf(state.history) === `data` + ? { ...state, dataOpen: !state.dataOpen, midruns: state.midruns + 1 } + : { ...state, strict: !state.strict, midruns: state.midruns + 1 } if (edit === `lazy`) return { ...state, lazyOpen: !state.lazyOpen } if (edit === `fsData`) return { ...state, dataOpen: !state.dataOpen } if (edit === `inputGate`) return { ...state, inputOpen: !state.inputOpen } @@ -7584,6 +7610,8 @@ function readSummary(summary) { export { drawn, + gateFiles, + gateTextFor, NO_STOPS, NO_LATER_STEPS, NO_FAULTS, diff --git a/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs b/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs index fa84c459..4c31559c 100644 --- a/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs +++ b/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs @@ -699,6 +699,8 @@ import { sourceArgument, outsideRepository, ENV_PREFIX, + gateFiles, + gateTextFor, MUTANT_LIMIT_MS, HEARTBEAT_MS, FULL_LIMIT_MS, @@ -3565,22 +3567,34 @@ async function incremental(dir, plan, cli, copy, observe, states) { // root, the tests' files live where `tests` links to). const target = fixturePathOf( plan, - plan.midrunTarget === `data` ? `tests/data.json` : `tests/strict.ts`, + plan.midrunTarget === `data` + ? `tests/data.json` + : plan.midrunTarget === `gate` + ? gateFiles[plan.inputRead] + : `tests/strict.ts`, ) const after = files[target] - const value = after.includes(`true`) - // The marker goes in the running daemon's session directory, where - // the test finds it beside the runner's harness. With no daemon - // running (a step before killed it), no edit lands. - const [daemonPid] = daemonsOf(dir) - const marker = - daemonPid && join(dir, `.oracle-gaps-${daemonPid}`, `midrun.txt`) - if (marker && existsSync(dirname(marker))) - writeFileSync(marker, `pending:${value}\n`) + const value = + plan.midrunTarget === `gate` + ? after === gateTextFor(plan.inputRead, true) + : after.includes(`true`) const before = { ...files, - [target]: after.replace(String(value), String(!value)), + [target]: + plan.midrunTarget === `gate` + ? gateTextFor(plan.inputRead, !value) + : after.replace(String(value), String(!value)), } + // The marker sits in the package, not in the daemon's session directory: + // the check that the edit overlaps restarts the daemon (file b's text + // counts its mid-run edits, which the session reads), and a restart + // removes the session directory. The name is one for the package, since + // the restarted daemon has another process id. It is runner-owned + // (inputs.mjs isRunnerFile), so no run takes it as an input. With no + // daemon running (a step before killed it), no edit lands. + const [daemonPid] = daemonsOf(dir) + const marker = daemonPid && join(dir, `.oracle-gaps-midrun.txt`) + if (marker) writeFileSync(marker, `pending:${value}\n`) const during = runCli(dir, before, { ...how, daemon: true }) const landed = marker && @@ -3600,7 +3614,7 @@ async function incremental(dir, plan, cli, copy, observe, states) { // a run under it would let the marker's edit, and not the helper's or // the data's, decide whether a run is stored. markerStored ||= storedInputs(dir).some((path) => - path.endsWith(`/midrun.txt`), + path.endsWith(`/.oracle-gaps-midrun.txt`), ) midrunChecks = { during, before: runCli(dir, before, how), landed } // The check the edit overlapped, through the daemon, and the cold run of @@ -7601,6 +7615,7 @@ const ownedIncrementalStates = [ `an unchanged check through the daemon computed nothing while a test read a source through fs`, `a capture row read while the worker wrote it`, `a run edited the data it had read, during a check through the daemon`, + `a run edited the gate it had read, during a check through the daemon`, `edit fsData changed the cold result`, `an edit to data read through sync changed the cold result`, `an edit to data read through promise changed the cold result`, @@ -8544,6 +8559,7 @@ oracleProperty({ inputSteps: NO_INPUT_STEPS, childWrite: false, childEnvironment: `node`, + midrunGate: false, failingLaw: `none`, failingLawAt: `end`, failingLawCalls: `none`, @@ -8767,6 +8783,7 @@ oracleProperty({ inputSteps: NO_INPUT_STEPS, childWrite: false, childEnvironment: `node`, + midrunGate: false, }, }, { @@ -8939,6 +8956,7 @@ oracleProperty({ inputSteps: NO_INPUT_STEPS, childWrite: false, childEnvironment: `node`, + midrunGate: false, }, }, { @@ -9138,6 +9156,7 @@ oracleProperty({ inputSteps: NO_INPUT_STEPS, childWrite: false, childEnvironment: `node`, + midrunGate: false, }, }, ], @@ -9975,6 +9994,7 @@ oracleProperty({ steps: [`midrun`], midrunBy: `b`, midrunTarget: `helper`, + midrunGate: false, fsRead: `none`, lazyGate: false, }), @@ -10030,6 +10050,7 @@ oracleProperty({ steps: [`midrun`], midrunBy: `b`, midrunTarget: `data`, + midrunGate: false, fsRead: `sync`, lazyGate: false, }), @@ -12302,6 +12323,7 @@ oracleProperty({ // In an environment that transforms file b for the client, as a // jsdom environment does (`childEnvironment`). childEnvironment: `client`, + midrunGate: false, }), }, ...[ @@ -12385,6 +12407,7 @@ oracleProperty({ steps: [`recheck`], childWrite: false, childEnvironment: `node`, + midrunGate: false, consoleOutput: true, }), }, @@ -12411,6 +12434,66 @@ oracleProperty({ `requireType`, false, ]), + { + // File b's test edits the gate that its own verdict reads, during a + // check through the daemon (`midrunGate`, I12 for the gate kinds). A run + // that read the old text and settled after the edit is not stored, so + // the check that follows equals a cold run of the state after the edit. + name: `an edit to a gate that a test reads, during a check through the daemon`, + enters: [ + `an edit landed during a check through the daemon`, + `edit midrun changed the cold result`, + `a run edited the gate it had read, during a check through the daemon`, + ], + build: (generated) => ({ + ...generated, + functions: [[{ kind: `push`, quote: `'` }]], + containers: [], + overloads: [], + owners: [`a`, `b`], + library: [], + libraryOwners: [], + runes: [], + derived: null, + dotGen: false, + dataOwners: [], + exportOwners: [], + importer: `none`, + wholeFile: `none`, + template: false, + tests: [ + { ...judging(`a`, `fixed seed`, 1), fn: 0 }, + { ...judging(`b`, `fixed seed`, 1), fn: 0 }, + ], + witness: false, + authored: null, + secondAuthored: false, + fault: `none`, + stability: `none`, + ordinary: false, + native: `none`, + boot: false, + cliPath: `plain`, + concurrentStart: false, + lazyGate: false, + fsRead: `none`, + prePlugin: false, + inputRead: `stat`, + keepStamp: false, + laterSteps: NO_LATER_STEPS, + inputSteps: NO_INPUT_STEPS, + steps: [`midrun`], + midrunBy: `b`, + midrunGate: true, + contexts: 1, + budget: `two`, + // The driver finds the daemon's session directory beside the package, so + // the package is not a sibling of the check's directory here. + siblingDir: false, + childWrite: false, + childEnvironment: `node`, + }), + }, ]), }, resolve: resolveHistory, diff --git a/packages/oracles/oracle-gaps/history-fingerprint.json b/packages/oracles/oracle-gaps/history-fingerprint.json index 41b8b8b9..199b385e 100644 --- a/packages/oracles/oracle-gaps/history-fingerprint.json +++ b/packages/oracles/oracle-gaps/history-fingerprint.json @@ -93,7 +93,8 @@ ["keepStamp", "6e084c1e8b33f13d"], ["inputSteps", "c47bf09530d81851"], ["childWrite", "96cd063b1067f34b"], - ["childEnvironment", "65a23ef9c722a68d"] + ["childEnvironment", "65a23ef9c722a68d"], + ["midrunGate", "3dbf515a001458e2"] ], "histories": [ ["functions", "66c0e9c56951c377"], @@ -189,6 +190,7 @@ ["keepStamp", "6e084c1e8b33f13d"], ["inputSteps", "c47bf09530d81851"], ["childWrite", "96cd063b1067f34b"], - ["childEnvironment", "65a23ef9c722a68d"] + ["childEnvironment", "65a23ef9c722a68d"], + ["midrunGate", "3dbf515a001458e2"] ] } diff --git a/packages/oracles/oracle-gaps/inputs.mjs b/packages/oracles/oracle-gaps/inputs.mjs index 81adbe0d..af132971 100644 --- a/packages/oracles/oracle-gaps/inputs.mjs +++ b/packages/oracles/oracle-gaps/inputs.mjs @@ -200,7 +200,11 @@ const spelledAbsolute = (path) => // holds this file) and the copies of test files // (`.oracle-gaps---`). A user's path that only contains // `.oracle-gaps` is an input like any other. -const isRunnerFile = (path) => /\/\.oracle-gaps-\d+[-/]/.test(path) +// The mid-run test marker (`.oracle-gaps-midrun.txt`, one per package) is +// the test harness's own file, so it is runner-owned too. +const isRunnerFile = (path) => + /\/\.oracle-gaps-\d+[-/]/.test(path) || + path.endsWith(`/.oracle-gaps-midrun.txt`) /** * A wrapper keeps every own property of the function it wraps (its name From ef8ea606b447d0ac140f41bd9d08a22544ada4bd Mon Sep 17 00:00:00 2001 From: Kyle Mathews Date: Wed, 2 Dec 2026 10:17:16 -0700 Subject: [PATCH 11/51] test(oracle-gaps): witnesses for the write, link, worker and log repairs Gate kinds for the CodeRabbit repairs that had only probe evidence (round 4): a failed exclusive create then a read (CR-12), an update open with no bytes then a read (CR-21), a path through a link and dot-dot (CR-22), a worker that a worker starts (CR-25), and a child whose write log cannot be opened, which keeps its result and whose run the copy does not store (CR-19; the history stops after the edit, since no unchanged reuse is owed for a run that is not stored). Each is RED on the pre-fix line as a mutant (incremental equals cold, or classification for the child-startup mutant), and GREEN on head. The four histories are appended to the registration order and to constructed-order.json; the inputRead fingerprint line is regenerated for the longer kind list. Co-authored-by: Isaac --- .../oracle-gaps/constructed-order.json | 7 ++- .../oracle-gaps/gap-report-model-oracle.mjs | 52 ++++++++++++++++++ .../gap-report-oracle.property.test.mjs | 54 +++++++++++++++++-- .../oracle-gaps/history-fingerprint.json | 4 +- 4 files changed, 111 insertions(+), 6 deletions(-) diff --git a/packages/oracles/oracle-gaps/constructed-order.json b/packages/oracles/oracle-gaps/constructed-order.json index 508be9fa..c78b32e1 100644 --- a/packages/oracles/oracle-gaps/constructed-order.json +++ b/packages/oracles/oracle-gaps/constructed-order.json @@ -141,6 +141,11 @@ "an edit to a file a test reads inside a worker thread", "an edit to the package.json main that a test requires", "an edit to the package.json type that a test requires", - "an edit to a gate that a test reads, during a check through the daemon" + "an edit to a gate that a test reads, during a check through the daemon", + "an edit to a file a test reads inside a worker started by a worker", + "an edit to a file a test tries to create exclusively, then reads", + "an edit to a file a test opens for update, then reads", + "an edit to a file that a child process reads when its own log fails", + "an edit to a file a test reads through a link and dot-dot" ] } diff --git a/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs b/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs index 4aabebff..21afd8f1 100644 --- a/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs +++ b/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs @@ -1257,6 +1257,11 @@ const drawn = fc.record({ `threadRead`, `requireMain`, `requireType`, + `wxExisting`, + `rplus`, + `threadNested`, + `childLost`, + `linkDotDot`, ), // Each write of a gate file keeps its size (`open` and `shut` have one // length) and gets back one fixed modification time, as `cp -p`, `rsync @@ -5851,6 +5856,9 @@ const dataReads = { ], } +// The code of the worker that a worker starts for `threadNested` (CR-25). +const NESTED_INNER = `const fs = require('node:fs'); const { parentPort, workerData } = require('node:worker_threads'); parentPort.postMessage(JSON.parse(fs.readFileSync(workerData, 'utf8')).gate === 'open')` +const NESTED_OUTER = `const { Worker } = require('node:worker_threads'); const { parentPort, workerData } = require('node:worker_threads'); const inner = new Worker(${JSON.stringify(NESTED_INNER)}, { eval: true, workerData }); inner.once('message', (open) => parentPort.postMessage(open === true)); inner.once('error', (error) => { throw error })` // The gate input of file b's verdicts (`inputRead`): the variable that // `env` reads, and the file each other kind reads. A gate file holds // `open` or `shut`, two words of one length, so an edit keeps its size. @@ -5896,6 +5904,11 @@ const gateFiles = { threadRead: `tests/gate.json`, requireMain: `tests/sub/package.json`, requireType: `tests/sub/package.json`, + wxExisting: `tests/gate.json`, + rplus: `tests/gate.json`, + threadNested: `tests/gate.json`, + childLost: `tests/gate.json`, + linkDotDot: `tests/a/gate.json`, } /** Whether the gate input is one that the config's own plugin reads. */ const pluginGated = (history) => @@ -6009,6 +6022,40 @@ const inputReads = { `import { createRequire as requireFrom } from 'node:module'`, `const readInput = async () => { const req = requireFrom(import.meta.url); const path = req.resolve('./sub'); delete req.cache[path]; return { open: req(path).open === true } }`, ], + // A failed exclusive create of the existing gate file (CR-12): the write + // throws EEXIST, the test catches it, and then reads the file. + wxExisting: [ + `import { writeFileSync as writeGate, readFileSync as readGate } from 'node:fs'`, + `const readInput = async () => { const url = new URL('./gate.json', import.meta.url); try { writeGate(url, '', { flag: 'wx' }) } catch { /* the file exists */ } return { open: JSON.parse(readGate(url, 'utf8')).gate === 'open' } }`, + ], + // An open for update without truncation writes no bytes here, and keeps + // the file's text, which the test then reads (CR-21). + rplus: [ + `import { writeFileSync as writeGate, readFileSync as readGate } from 'node:fs'`, + `const readInput = async () => { const url = new URL('./gate.json', import.meta.url); writeGate(url, '', { flag: 'r+' }); return { open: JSON.parse(readGate(url, 'utf8')).gate === 'open' } }`, + ], + // A worker that starts a worker, which reads the gate (CR-25). + threadNested: [ + `import { Worker as GateWorker } from 'node:worker_threads'`, + `import { fileURLToPath as gatePath } from 'node:url'`, + `const readInput = () => new Promise((resolve, reject) => { const outer = new GateWorker(${JSON.stringify(NESTED_OUTER)}, { eval: true, workerData: gatePath(new URL('./gate.json', import.meta.url)) }); outer.once('message', (open) => resolve({ open: open === true })); outer.once('error', reject) })`, + ], + // A child whose own write-log cannot be opened (a directory at its path): + // the child keeps its result, and the gate it read decides the verdict (CR-19). + childLost: [ + `import { execFileSync as runGateChild } from 'node:child_process'`, + `import { mkdirSync as makeLogDir, rmSync as removeLog } from 'node:fs'`, + `import { fileURLToPath as gatePath } from 'node:url'`, + `const readInput = async () => { const log = process.env.ORACLE_GAPS_CHILD_WRITES; if (log) { removeLog(log, { force: true }); makeLogDir(log) } return { open: JSON.parse(runGateChild(process.execPath, ['-e', "process.stdout.write(require('node:fs').readFileSync(process.argv[1], 'utf8'))", gatePath(new URL('./gate.json', import.meta.url))], { encoding: 'utf8' })).gate === 'open' } }`, + ], + // A path spelled through a symbolic link and `..` (CR-22): the kernel opens + // a/gate.json, while a lexical reading of the same spelling names gate.json. + // The path is a string, because a URL's `..` is resolved before the call. + linkDotDot: [ + `import { readFileSync as readGate } from 'node:fs'`, + `import { fileURLToPath as linkPath } from 'node:url'`, + `const readInput = async () => ({ open: JSON.parse(readGate(linkPath(new URL('.', import.meta.url)) + 'link/../gate.json', 'utf8')).gate === 'open' })`, + ], threadRead: [ `import { Worker as GateWorker } from 'node:worker_threads'`, `import { fileURLToPath as gatePath } from 'node:url'`, @@ -7013,6 +7060,11 @@ function fixtureFiles(plan, state = initialState(plan)) { ...(plan.inputRead === `requireType` ? { 'tests/sub/index.js': `module.exports = { open: true }\n` } : {}), + // The link, and the directory it names, are fixture state, so the run + // only reads through them (CR-22). + ...(plan.inputRead === `linkDotDot` + ? { 'tests/a/b/keep.txt': `kept\n`, 'tests/link': { link: 'a/b' } } + : {}), ...(gateFiles[plan.inputRead] === undefined ? {} : { diff --git a/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs b/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs index 4c31559c..1d16e9fb 100644 --- a/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs +++ b/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs @@ -7602,6 +7602,11 @@ const inputKinds = [ `threadRead`, `requireMain`, `requireType`, + `wxExisting`, + `rplus`, + `threadNested`, + `childLost`, + `linkDotDot`, ] // Law 9's states that a constructed history of their own reaches, not the // edit sequence: the mid-run edit, and an edit to data a test reads through @@ -8268,7 +8273,10 @@ const witnessEditSequence = (witness) => (generated) => ({ steps: witnessSteps, }) -const gateKindHistory = ([name, inputRead, keepStamp]) => ({ +// `reuses` is false for a kind whose run the copy must not store (a child whose +// log lost lines, CR-19): its check after the edit is no unchanged reuse, so the +// history stops after the edit, and enters no unchanged-reuse state. +const gateKindHistory = ([name, inputRead, keepStamp, reuses = true]) => ({ name, enters: [ ...(inputRead === `pluginWrite` @@ -8279,7 +8287,9 @@ const gateKindHistory = ([name, inputRead, keepStamp]) => ({ `edit inputGate changed the cold result`, `an edit to the ${inputRead} gate input changed the cold result`, ]), - `an unchanged check through the daemon computed nothing`, + ...(reuses + ? [`an unchanged check through the daemon computed nothing`] + : []), ...(keepStamp ? [ `an edit that kept a file's size and modification time changed the cold result`, @@ -8322,7 +8332,7 @@ const gateKindHistory = ([name, inputRead, keepStamp]) => ({ keepStamp, laterSteps: NO_LATER_STEPS, inputSteps: NO_INPUT_STEPS, - steps: [`inputGate`, `recheck`], + steps: reuses ? [`inputGate`, `recheck`] : [`inputGate`], }), }) @@ -12494,6 +12504,44 @@ oracleProperty({ childEnvironment: `node`, }), }, + // Appended after the last recorded constructed history (the order + // canary): the four gate kinds of the CodeRabbit repairs (CR-12, CR-19, + // CR-21, CR-25). + // A worker that a worker starts reads the file: the nested worker has + // the preload too (CR-25). + gateKindHistory([ + `an edit to a file a test reads inside a worker started by a worker`, + `threadNested`, + false, + ]), + // A failed exclusive create of the file, and then its read: the failed + // write makes nothing the tree's own (CR-12). + gateKindHistory([ + `an edit to a file a test tries to create exclusively, then reads`, + `wxExisting`, + false, + ]), + // A write with flag r+ and no bytes, then the read: the write keeps the + // file's text, so the text is an input (CR-21). + gateKindHistory([ + `an edit to a file a test opens for update, then reads`, + `rplus`, + false, + ]), + // A child process whose write log cannot be opened: it keeps its + // result, and the verdict follows the file it read (CR-19). + gateKindHistory([ + `an edit to a file that a child process reads when its own log fails`, + `childLost`, + false, + false, + ]), + // A path through a symbolic link and `..` (CR-22). + gateKindHistory([ + `an edit to a file a test reads through a link and dot-dot`, + `linkDotDot`, + false, + ]), ]), }, resolve: resolveHistory, diff --git a/packages/oracles/oracle-gaps/history-fingerprint.json b/packages/oracles/oracle-gaps/history-fingerprint.json index 199b385e..5359ff9c 100644 --- a/packages/oracles/oracle-gaps/history-fingerprint.json +++ b/packages/oracles/oracle-gaps/history-fingerprint.json @@ -89,7 +89,7 @@ ["faults", "484207f844e32250"], ["diffBase", "12e714e66d263986"], ["authoredSpan", "3259189ca6a54cd5"], - ["inputRead", "447de24d5daef092"], + ["inputRead", "ae1f93b14fffe88d"], ["keepStamp", "6e084c1e8b33f13d"], ["inputSteps", "c47bf09530d81851"], ["childWrite", "96cd063b1067f34b"], @@ -186,7 +186,7 @@ ["faults", "484207f844e32250"], ["diffBase", "12e714e66d263986"], ["authoredSpan", "3259189ca6a54cd5"], - ["inputRead", "447de24d5daef092"], + ["inputRead", "ae1f93b14fffe88d"], ["keepStamp", "6e084c1e8b33f13d"], ["inputSteps", "c47bf09530d81851"], ["childWrite", "96cd063b1067f34b"], From 3e3458d13de57cbef04c546b76607ad15aa5a26e Mon Sep 17 00:00:00 2001 From: Kyle Mathews Date: Wed, 2 Dec 2026 10:24:29 -0700 Subject: [PATCH 12/51] test(oracle-gaps): witnesses for the worker directive and the large-file hash A gate kind whose worker opens with 'use strict' (CR-24): its open is the gate only when its plain call sees no `this`, so a preload that puts a prefix ahead of the directive makes the worker sloppy. RED on the pre-fix preloadedCode (the require ahead of the code) by the classification law; GREEN on head. A unit test of fileHash on a 2.5 GiB sparse file (CR-10): the whole-file read that the pre-fix hash used fails with ERR_FS_FILE_TOO_LARGE, so the file hashed as missing. A constructed oracle history would need that file in every copy, so the witness is a plain test (tests/gap-inputs-large-file.test.ts, skipped on Windows, which has no sparse files here). RED on the whole-read mutant; GREEN on head. The chunked hash takes about 1.3 s here. The history name is appended to constructed-order.json, and the inputRead fingerprint line is regenerated for the longer kind list. Co-authored-by: Isaac --- .../oracle-gaps/constructed-order.json | 3 +- .../oracle-gaps/gap-report-model-oracle.mjs | 12 ++++ .../gap-report-oracle.property.test.mjs | 7 +++ .../oracle-gaps/history-fingerprint.json | 4 +- .../tests/gap-inputs-large-file.test.ts | 60 +++++++++++++++++++ 5 files changed, 83 insertions(+), 3 deletions(-) create mode 100644 packages/oracles/tests/gap-inputs-large-file.test.ts diff --git a/packages/oracles/oracle-gaps/constructed-order.json b/packages/oracles/oracle-gaps/constructed-order.json index c78b32e1..2c7e98f7 100644 --- a/packages/oracles/oracle-gaps/constructed-order.json +++ b/packages/oracles/oracle-gaps/constructed-order.json @@ -146,6 +146,7 @@ "an edit to a file a test tries to create exclusively, then reads", "an edit to a file a test opens for update, then reads", "an edit to a file that a child process reads when its own log fails", - "an edit to a file a test reads through a link and dot-dot" + "an edit to a file a test reads through a link and dot-dot", + "an edit to a file a test reads in a worker with strict mode" ] } diff --git a/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs b/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs index 21afd8f1..0f215bc0 100644 --- a/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs +++ b/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs @@ -1262,6 +1262,7 @@ const drawn = fc.record({ `threadNested`, `childLost`, `linkDotDot`, + `threadStrict`, ), // Each write of a gate file keeps its size (`open` and `shut` have one // length) and gets back one fixed modification time, as `cp -p`, `rsync @@ -5859,6 +5860,8 @@ const dataReads = { // The code of the worker that a worker starts for `threadNested` (CR-25). const NESTED_INNER = `const fs = require('node:fs'); const { parentPort, workerData } = require('node:worker_threads'); parentPort.postMessage(JSON.parse(fs.readFileSync(workerData, 'utf8')).gate === 'open')` const NESTED_OUTER = `const { Worker } = require('node:worker_threads'); const { parentPort, workerData } = require('node:worker_threads'); const inner = new Worker(${JSON.stringify(NESTED_INNER)}, { eval: true, workerData }); inner.once('message', (open) => parentPort.postMessage(open === true)); inner.once('error', (error) => { throw error })` +// The code of the worker for `threadStrict`. +const STRICT_WORKER = `'use strict'; const fs = require('node:fs'); const { parentPort, workerData } = require('node:worker_threads'); const plain = function () { return this }; parentPort.postMessage(plain() === undefined && JSON.parse(fs.readFileSync(workerData, 'utf8')).gate === 'open')` // The gate input of file b's verdicts (`inputRead`): the variable that // `env` reads, and the file each other kind reads. A gate file holds // `open` or `shut`, two words of one length, so an edit keeps its size. @@ -5909,6 +5912,7 @@ const gateFiles = { threadNested: `tests/gate.json`, childLost: `tests/gate.json`, linkDotDot: `tests/a/gate.json`, + threadStrict: `tests/gate.json`, } /** Whether the gate input is one that the config's own plugin reads. */ const pluginGated = (history) => @@ -6056,6 +6060,14 @@ const inputReads = { `import { fileURLToPath as linkPath } from 'node:url'`, `const readInput = async () => ({ open: JSON.parse(readGate(linkPath(new URL('.', import.meta.url)) + 'link/../gate.json', 'utf8')).gate === 'open' })`, ], + // A worker whose code opens with 'use strict': its open is the gate only + // when its plain call sees no `this`, which holds in strict mode alone + // (CR-24: a capture prefix ahead of the directive makes the worker sloppy). + threadStrict: [ + `import { Worker as GateWorker } from 'node:worker_threads'`, + `import { fileURLToPath as gatePath } from 'node:url'`, + `const readInput = () => new Promise((resolve, reject) => { const worker = new GateWorker(${JSON.stringify(STRICT_WORKER)}, { eval: true, workerData: gatePath(new URL('./gate.json', import.meta.url)) }); worker.once('message', (open) => resolve({ open: open === true })); worker.once('error', reject) })`, + ], threadRead: [ `import { Worker as GateWorker } from 'node:worker_threads'`, `import { fileURLToPath as gatePath } from 'node:url'`, diff --git a/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs b/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs index 1d16e9fb..983ef989 100644 --- a/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs +++ b/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs @@ -7607,6 +7607,7 @@ const inputKinds = [ `threadNested`, `childLost`, `linkDotDot`, + `threadStrict`, ] // Law 9's states that a constructed history of their own reaches, not the // edit sequence: the mid-run edit, and an edit to data a test reads through @@ -12542,6 +12543,12 @@ oracleProperty({ `linkDotDot`, false, ]), + // A worker whose 'use strict' directive must stay first (CR-24). + gateKindHistory([ + `an edit to a file a test reads in a worker with strict mode`, + `threadStrict`, + false, + ]), ]), }, resolve: resolveHistory, diff --git a/packages/oracles/oracle-gaps/history-fingerprint.json b/packages/oracles/oracle-gaps/history-fingerprint.json index 5359ff9c..f20bf3c5 100644 --- a/packages/oracles/oracle-gaps/history-fingerprint.json +++ b/packages/oracles/oracle-gaps/history-fingerprint.json @@ -89,7 +89,7 @@ ["faults", "484207f844e32250"], ["diffBase", "12e714e66d263986"], ["authoredSpan", "3259189ca6a54cd5"], - ["inputRead", "ae1f93b14fffe88d"], + ["inputRead", "bf3383770ee32a9d"], ["keepStamp", "6e084c1e8b33f13d"], ["inputSteps", "c47bf09530d81851"], ["childWrite", "96cd063b1067f34b"], @@ -186,7 +186,7 @@ ["faults", "484207f844e32250"], ["diffBase", "12e714e66d263986"], ["authoredSpan", "3259189ca6a54cd5"], - ["inputRead", "ae1f93b14fffe88d"], + ["inputRead", "bf3383770ee32a9d"], ["keepStamp", "6e084c1e8b33f13d"], ["inputSteps", "c47bf09530d81851"], ["childWrite", "96cd063b1067f34b"], diff --git a/packages/oracles/tests/gap-inputs-large-file.test.ts b/packages/oracles/tests/gap-inputs-large-file.test.ts new file mode 100644 index 00000000..3eff22c0 --- /dev/null +++ b/packages/oracles/tests/gap-inputs-large-file.test.ts @@ -0,0 +1,60 @@ +import { + closeSync, + mkdtempSync, + openSync, + rmSync, + truncateSync, + writeFileSync, + writeSync, +} from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { describe, expect, test } from 'vitest' +import { fileHash } from '../oracle-gaps/inputs.mjs' + +// A file's input hash is its text's SHA-1 (inputs.mjs). A whole-file read +// cannot take a regular file past about 2 GiB (ERR_FS_FILE_TOO_LARGE), so a +// larger file hashed as missing, and its edits were not seen (CR-10). The hash +// reads the file in chunks instead. The file here is sparse, so it is cheap to +// make and to read; sparse files are not made on Windows, so the test is +// skipped there. +const LIMIT = 2 * 1024 ** 3 + 512 * 1024 ** 2 + +describe(`the input hash of a file past a whole read's limit`, () => { + test.skipIf(process.platform === `win32`)( + `hashes a 2.5 GiB file and sees an edit at its end`, + () => { + const dir = mkdtempSync(join(tmpdir(), `gap-large-`)) + try { + const big = join(dir, `big.bin`) + writeFileSync(big, ``) + truncateSync(big, LIMIT) + const before = fileHash(big) + expect(before).toMatch(/^[0-9a-f]{40}$/) + const fd = openSync(big, `r+`) + try { + writeSync(fd, Buffer.from([1]), 0, 1, LIMIT - 1) + } finally { + closeSync(fd) + } + expect(fileHash(big)).toMatch(/^[0-9a-f]{40}$/) + expect(fileHash(big)).not.toBe(before) + } finally { + rmSync(dir, { recursive: true, force: true }) + } + }, + 60_000, + ) + + test(`hashes a small file as its text`, () => { + const dir = mkdtempSync(join(tmpdir(), `gap-small-`)) + try { + const small = join(dir, `small.txt`) + writeFileSync(small, `text\n`) + // SHA-1 of `text\n`, the same as a whole read's hash. + expect(fileHash(small)).toBe('aa785adca3fcdfe1884ae840e13c6d294a2414e8') + } finally { + rmSync(dir, { recursive: true, force: true }) + } + }) +}) From b3b00f25b24bc7bc975a489dd44c0850c85280d6 Mon Sep 17 00:00:00 2001 From: Kyle Mathews Date: Wed, 2 Dec 2026 10:38:42 -0700 Subject: [PATCH 13/51] test(oracle-gaps): a config plugin's scratch file is no input (CR-3) A config plugin writes a scratch file beside the config, tests it, and removes it at each resolve. The history is GREEN on head (3 of 3) and the fingerprint canary passes. Its RED is not yet witnessed: the pre-fix line (ownWrite without the stat-to-write mapping) survives, because a restart that reuses stored evidence is not observable in the oracle (133-10). Co-authored-by: Isaac --- .../oracle-gaps/constructed-order.json | 3 +- .../oracle-gaps/gap-report-model-oracle.mjs | 14 +++++ .../gap-report-oracle.property.test.mjs | 55 +++++++++++++++++++ .../oracle-gaps/history-fingerprint.json | 6 +- 4 files changed, 75 insertions(+), 3 deletions(-) diff --git a/packages/oracles/oracle-gaps/constructed-order.json b/packages/oracles/oracle-gaps/constructed-order.json index 2c7e98f7..eec78ae2 100644 --- a/packages/oracles/oracle-gaps/constructed-order.json +++ b/packages/oracles/oracle-gaps/constructed-order.json @@ -147,6 +147,7 @@ "an edit to a file a test opens for update, then reads", "an edit to a file that a child process reads when its own log fails", "an edit to a file a test reads through a link and dot-dot", - "an edit to a file a test reads in a worker with strict mode" + "an edit to a file a test reads in a worker with strict mode", + "an unchanged check through the daemon while a config's plugin writes, stats and removes a scratch file" ] } diff --git a/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs b/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs index 0f215bc0..891a8e2e 100644 --- a/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs +++ b/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs @@ -1323,6 +1323,9 @@ const drawn = fc.record({ false, true, ), + // Drawn last (CR-3): a config plugin that writes a scratch file beside the + // config, tests it, and removes it at each resolve (`scratchPlugin`). + scratchPlugin: fc.constantFrom(false, false, false, false, true), }) // The edit sequence over the witness module, the one list of steps that a @@ -3771,6 +3774,7 @@ function resolveHistory(history) { matcherOwns: history.matcherOwns ?? `none`, config: history.config ?? `object`, prePlugin: history.prePlugin === true, + scratchPlugin: history.scratchPlugin === true, tornRows: history.tornRows === true, ...configOf(history), configEnv: history.configEnv === true, @@ -6713,6 +6717,10 @@ const PRE_PLUGIN = `{ name: 'gap-pre-rewrite', enforce: 'pre', transform(code, i // memory, so only the runner's own \`load\` can answer for it (review of #103). const LOAD_PLUGIN = `{ name: 'gap-own-load', load(id) { const path = id.split('?')[0]; return path.endsWith('.test.ts') ? readFileSync(path, 'utf8') : undefined } }` +// The config's own plugin that writes a scratch file beside the config, tests +// whether it exists, and removes it, at each resolve (`scratchPlugin`). The +// stat of the session's own write is no input (check.mjs, ownWrite; CR-3). +const SCRATCH_PLUGIN = `{ name: 'gap-scratch', configResolved() { const path = new URL('./gap-scratch.txt', import.meta.url); writeScratch(path, 'scratch\\n'); if (scratchExists(path)) removeScratch(path) } }` // The config's own plugin that reads the gate file (`inputRead` // `pluginConfig` or `pluginTransform`) and writes its word in place of // `__GAP_INPUT_GATE__` in each test file it transforms. It finds the file @@ -6746,6 +6754,7 @@ function configText(plan, test, configPath = plan.configPath) { const commonjs = plan.configSyntax === `cjs` const plugins = [ ...(plan.prePlugin ? [PRE_PLUGIN] : []), + ...(plan.scratchPlugin ? [SCRATCH_PLUGIN] : []), ...(plan.loadPlugin ? [LOAD_PLUGIN] : []), ...(pluginGated(plan) || plan.inputRead === `pluginWrite` ? [gatePlugin(plan)] @@ -6783,6 +6792,11 @@ function configText(plan, test, configPath = plan.configPath) { : [`import { fileURLToPath } from 'node:url'`]), // Only a config in ES module syntax has the load plugin (`loadPluginOf`). ...(plan.loadPlugin ? [`import { readFileSync } from 'node:fs'`] : []), + ...(plan.scratchPlugin && !commonjs + ? [ + `import { writeFileSync as writeScratch, existsSync as scratchExists, unlinkSync as removeScratch } from 'node:fs'`, + ] + : []), ...(configGated(plan) ? commonjs ? [ diff --git a/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs b/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs index 983ef989..59de0503 100644 --- a/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs +++ b/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs @@ -8528,6 +8528,7 @@ oracleProperty({ configRequire: false, contexts: 4, steps: null, + scratchPlugin: false, dataOwners: ['b', 'a'], exportOwners: ['b', 'b', 'b', 'b', 'a', 'none'], importer: 'a', @@ -8571,6 +8572,7 @@ oracleProperty({ childWrite: false, childEnvironment: `node`, midrunGate: false, + scratchPlugin: false, failingLaw: `none`, failingLawAt: `end`, failingLawCalls: `none`, @@ -8795,6 +8797,7 @@ oracleProperty({ childWrite: false, childEnvironment: `node`, midrunGate: false, + scratchPlugin: false, }, }, { @@ -8968,6 +8971,7 @@ oracleProperty({ childWrite: false, childEnvironment: `node`, midrunGate: false, + scratchPlugin: false, }, }, { @@ -9168,6 +9172,7 @@ oracleProperty({ childWrite: false, childEnvironment: `node`, midrunGate: false, + scratchPlugin: false, }, }, ], @@ -12549,6 +12554,56 @@ oracleProperty({ `threadStrict`, false, ]), + { + // A config plugin that writes a scratch file beside the config, tests + // whether it exists, and removes it at each resolve: the stat of the + // session's own write is no input, so the unchanged check reuses every + // run and does not restart the daemon (check.mjs, ownWrite; CR-3). + name: `an unchanged check through the daemon while a config's plugin writes, stats and removes a scratch file`, + enters: [`an unchanged check through the daemon computed nothing`], + build: (generated) => ({ + ...generated, + functions: [ + [{ kind: `push`, quote: `'` }], + [{ kind: `push`, quote: `'` }], + ], + containers: [], + overloads: [], + owners: [`a`, `b`], + library: [], + libraryOwners: [], + runes: [], + derived: null, + dotGen: false, + dataOwners: [], + exportOwners: [], + importer: `none`, + wholeFile: `none`, + template: false, + tests: [ + { ...judging(`a`, `fixed seed`, 1), fn: 0 }, + { ...judging(`b`, `fixed seed`, 1), fn: 1 }, + ], + witness: false, + authored: null, + secondAuthored: false, + fault: `none`, + stability: `none`, + ordinary: false, + native: `none`, + boot: false, + budget: `two`, + cliPath: `plain`, + concurrentStart: false, + contexts: 1, + laterSteps: NO_LATER_STEPS, + steps: [`recheck`], + scratchPlugin: true, + configPlace: `discovered`, + configFile: `vite.config.mjs`, + config: `object`, + }), + }, ]), }, resolve: resolveHistory, diff --git a/packages/oracles/oracle-gaps/history-fingerprint.json b/packages/oracles/oracle-gaps/history-fingerprint.json index f20bf3c5..1c75c5c0 100644 --- a/packages/oracles/oracle-gaps/history-fingerprint.json +++ b/packages/oracles/oracle-gaps/history-fingerprint.json @@ -94,7 +94,8 @@ ["inputSteps", "c47bf09530d81851"], ["childWrite", "96cd063b1067f34b"], ["childEnvironment", "65a23ef9c722a68d"], - ["midrunGate", "3dbf515a001458e2"] + ["midrunGate", "3dbf515a001458e2"], + ["scratchPlugin", "5e372e55093ca141"] ], "histories": [ ["functions", "66c0e9c56951c377"], @@ -191,6 +192,7 @@ ["inputSteps", "c47bf09530d81851"], ["childWrite", "96cd063b1067f34b"], ["childEnvironment", "65a23ef9c722a68d"], - ["midrunGate", "3dbf515a001458e2"] + ["midrunGate", "3dbf515a001458e2"], + ["scratchPlugin", "5e372e55093ca141"] ] } From 2d1ec512d6cb60b2572c9f3e7b9b3d2eca06171f Mon Sep 17 00:00:00 2001 From: Kyle Mathews Date: Wed, 2 Dec 2026 10:46:54 -0700 Subject: [PATCH 14/51] fix(oracle-gaps): a frozen plugin hook is checked cold and stores no unit (CR-2) A config plugin whose object is frozen cannot take the runner's hook wrapper, so the assignment threw and the CLI refused the config. Now the hook is not wrapped, the check computes every unit as a cold run does and stores none, and its stream note names the plugin (R39, R13/G34: the daemon is a cache over the cold result). Law 9 gains the agreed sentence. RED: the no-guard mutant fails the history 2 of 3 (law config at cli). GREEN: 3 of 3 (fixed seed, random seed, reach). Regression: 15 of 15 for the pre-plugin, plugin-write, and config-refusal histories. Co-authored-by: Isaac --- packages/oracles/oracle-gaps/check.mjs | 47 ++++++++--- .../oracle-gaps/constructed-order.json | 3 +- .../oracle-gaps/gap-report-model-oracle.mjs | 6 ++ .../gap-report-oracle.property.test.mjs | 81 ++++++++++++++++++- .../oracle-gaps/history-fingerprint.json | 6 +- 5 files changed, 129 insertions(+), 14 deletions(-) diff --git a/packages/oracles/oracle-gaps/check.mjs b/packages/oracles/oracle-gaps/check.mjs index 35b6a795..fba7e912 100644 --- a/packages/oracles/oracle-gaps/check.mjs +++ b/packages/oracles/oracle-gaps/check.mjs @@ -241,14 +241,14 @@ class KeepOrder { * a function or an object with a `handler`, as Vite takes it. */ const hooked = new WeakSet() -function pluginHooks(plugins, reading) { +function pluginHooks(plugins, reading, unrecorded) { for (const option of plugins) { if (option.name === `oracle-gaps-schemata` || hooked.has(option)) continue hooked.add(option) - hookPlugin(option, reading) + hookPlugin(option, reading, unrecorded) } } -function hookPlugin(option, reading) { +function hookPlugin(option, reading, unrecorded) { for (const [name, hook] of Object.entries(option)) { const handler = typeof hook === `function` ? hook : hook?.handler if (typeof handler !== `function`) continue @@ -266,8 +266,16 @@ function hookPlugin(option, reading) { () => handler.apply(this, args), ) } - option[name] = - typeof hook === `function` ? watched : { ...hook, handler: watched } + // A frozen plugin object cannot take the wrapper: its assignment throws + // in this module's strict code. Its hooks are not recorded, so the check + // stores no unit of them, and names the plugin (CR-2). + try { + option[name] = + typeof hook === `function` ? watched : { ...hook, handler: watched } + } catch { + unrecorded.add(String(option.name)) + return + } } } @@ -584,8 +592,12 @@ export async function openSession(pkg, pause = async () => {}) { at.done = true } } + // The plugins whose hooks could not be recorded (hookPlugin). While any is + // here, the session keeps no unit: each check computes every unit, as a cold + // run does, and names each plugin on its stream (CR-2). + const unrecorded = new Set() globalThis.__oracleGapsPluginHooks = (plugins) => - pluginHooks(plugins, reading) + pluginHooks(plugins, reading, unrecorded) const requireTarget = createRequire(join(pkg, `package.json`)) let createVitest try { @@ -1833,9 +1845,26 @@ export default async (env) => { // A check, after which each file the session wrote is known by its text. async function check(...args) { + const store = args[1] + const log = args[2] ?? console.error + const unstored = () => unrecorded.size > 0 + const kept = { + get: (id) => (unstored() ? undefined : store.get(id)), + put: (id, entry) => { + if (!unstored()) store.put(id, entry) + }, + flush: () => store.flush?.(), + } try { - return await checkIn(...args) + return await checkIn(args[0], kept, ...args.slice(2)) } finally { + for (const name of unrecorded) + log( + streamLine( + `note`, + `plugin ${escapeControls(name)} has a frozen hook object: this check runs cold and stores no unit of it`, + ), + ) // A file the session wrote and then removed (Vite deletes the config it // bundles into a temporary file once it has loaded it) is no longer the // session's to keep: it is stored as missing, so the removal is not a @@ -1847,8 +1876,8 @@ export default async (env) => { written.set(key, `missing`) // The session's hook log, for units that later sessions look up, once // it has grown: a put marks the store to be written again, whole. - if (hookLog.length > hookLogStored) { - args[1]?.put(`hook-log:${hookLogId}`, { + if (hookLog.length > hookLogStored && !unstored()) { + store.put(`hook-log:${hookLogId}`, { inputs: [...hookLog], unit: null, }) diff --git a/packages/oracles/oracle-gaps/constructed-order.json b/packages/oracles/oracle-gaps/constructed-order.json index eec78ae2..640f07ac 100644 --- a/packages/oracles/oracle-gaps/constructed-order.json +++ b/packages/oracles/oracle-gaps/constructed-order.json @@ -148,6 +148,7 @@ "an edit to a file that a child process reads when its own log fails", "an edit to a file a test reads through a link and dot-dot", "an edit to a file a test reads in a worker with strict mode", - "an unchanged check through the daemon while a config's plugin writes, stats and removes a scratch file" + "an unchanged check through the daemon while a config's plugin writes, stats and removes a scratch file", + "a check through the daemon of a config whose plugin object is frozen" ] } diff --git a/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs b/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs index 891a8e2e..ce852b54 100644 --- a/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs +++ b/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs @@ -1326,6 +1326,8 @@ const drawn = fc.record({ // Drawn last (CR-3): a config plugin that writes a scratch file beside the // config, tests it, and removes it at each resolve (`scratchPlugin`). scratchPlugin: fc.constantFrom(false, false, false, false, true), + // Drawn last (CR-2): the config's plugin object is frozen, so the runner cannot wrap its hooks (`frozenPlugin`). + frozenPlugin: fc.constantFrom(false, false, false, false, true), }) // The edit sequence over the witness module, the one list of steps that a @@ -3775,6 +3777,7 @@ function resolveHistory(history) { config: history.config ?? `object`, prePlugin: history.prePlugin === true, scratchPlugin: history.scratchPlugin === true, + frozenPlugin: history.frozenPlugin === true, tornRows: history.tornRows === true, ...configOf(history), configEnv: history.configEnv === true, @@ -6720,6 +6723,8 @@ const LOAD_PLUGIN = `{ name: 'gap-own-load', load(id) { const path = id.split('? // The config's own plugin that writes a scratch file beside the config, tests // whether it exists, and removes it, at each resolve (`scratchPlugin`). The // stat of the session's own write is no input (check.mjs, ownWrite; CR-3). +// The config's own plugin, frozen (`frozenPlugin`): a runner's wrapper cannot be assigned to its hooks (CR-2). +const FROZEN_PLUGIN = `{ name: 'gap-frozen', transform(code) { return undefined } }` const SCRATCH_PLUGIN = `{ name: 'gap-scratch', configResolved() { const path = new URL('./gap-scratch.txt', import.meta.url); writeScratch(path, 'scratch\\n'); if (scratchExists(path)) removeScratch(path) } }` // The config's own plugin that reads the gate file (`inputRead` // `pluginConfig` or `pluginTransform`) and writes its word in place of @@ -6755,6 +6760,7 @@ function configText(plan, test, configPath = plan.configPath) { const plugins = [ ...(plan.prePlugin ? [PRE_PLUGIN] : []), ...(plan.scratchPlugin ? [SCRATCH_PLUGIN] : []), + ...(plan.frozenPlugin ? [`Object.freeze(${FROZEN_PLUGIN})`] : []), ...(plan.loadPlugin ? [LOAD_PLUGIN] : []), ...(pluginGated(plan) || plan.inputRead === `pluginWrite` ? [gatePlugin(plan)] diff --git a/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs b/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs index 59de0503..f1f100aa 100644 --- a/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs +++ b/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs @@ -234,7 +234,10 @@ * state reports: the same exit status and refusal cause, the same run * identity, results, and summary. Only how the result was produced may * differ: durations, the options that name the output directory and the - * daemon, and the counts of reused and computed evidence. The edits change + * daemon, and the counts of reused and computed evidence. A check through + * the daemon whose plugin hook cannot be recorded (a frozen hook object) is + * computed as a cold run computes it and stores no unit of it; its stream + * note names the plugin. The edits change * a test, a source statement, the source's line numbers, an owns list, * the authored mutant, a helper module that one oracle file imports, a * module that a test imports only where its output differs, the @@ -2297,6 +2300,10 @@ function namedScratch(text, names) { // check runs cold instead (R39: a cold fallback names its cause). const coldFallbackNote = /^oracle-gaps: note the package's daemon sent nothing for \d+ s; this check runs cold/ +// The note a CLI writes for a plugin whose hook object is frozen, so that its +// hooks cannot be recorded: the check runs cold and stores no unit (CR-2). +const frozenPluginNote = + /^oracle-gaps: note plugin gap-frozen has a frozen hook object: this check runs cold and stores no unit of it$/ // A run's own output directory, `out`, named `` in each // spelling the stack may use, wherever it is a whole path: not followed by @@ -3054,7 +3061,9 @@ async function incremental(dir, plan, cli, copy, observe, states) { // after the daemon's earlier check of the same state, whose evidence is // stored before it replies. So one of the two computes and the other // reuses, whichever order the daemon took them in. - const reuseOwed = plan.tests.every((t) => !t.flaky) + // A plugin whose hook cannot be recorded stores no unit, so its rechecks + // reuse nothing and compute as a cold run does (law 9, CR-2). + const reuseOwed = plan.tests.every((t) => !t.flaky) && !plan.frozenPlugin unchangedComputed = step === `recheck` && reuseOwed ? computedRuns(daemon) : undefined const laterComputed = @@ -3183,6 +3192,16 @@ async function incremental(dir, plan, cli, copy, observe, states) { [daemon, ...others].every((run) => run.refusal !== undefined) ) states.add(`two checks at once on a session that cannot open`) + // A frozen plugin object (CR-2): the check named the plugin, and the store + // holds no unit of it (stored units are the session's, storedUnits). + if ( + plan.frozenPlugin && + daemon.stream.notes.some((note) => frozenPluginNote.test(note)) && + storedUnits(stateDirOf(realpathSync(dir))).length === 0 + ) + states.add( + `a check through the daemon with a frozen plugin object named it and stored no unit`, + ) if (plan.fault === `brokenVitest` && daemon.refusal !== undefined) states.add(`a session failure larger than a socket buffer`) const after = { @@ -7924,6 +7943,7 @@ const required = [ `an edit to data that only a copy spun alone read changed the cold result`, `a slow warm-up was served by the daemon`, `a check through the daemon worked past its CLI's bound`, + `a check through the daemon with a frozen plugin object named it and stored no unit`, `a slow daemon start was served by the daemon`, `a check abandoned while a context warmed in place of a cut one wrote nothing more`, `an unchanged check through the daemon computed nothing while a test read what its child process wrote`, @@ -8072,6 +8092,7 @@ const separate = [ `an edit to data that only a copy spun alone read changed the cold result`, `a slow warm-up was served by the daemon`, `a check through the daemon worked past its CLI's bound`, + `a check through the daemon with a frozen plugin object named it and stored no unit`, `a slow daemon start was served by the daemon`, `a check abandoned while a context warmed in place of a cut one wrote nothing more`, // Each has its own constructed history (#179; own writes of the test's @@ -8529,6 +8550,7 @@ oracleProperty({ contexts: 4, steps: null, scratchPlugin: false, + frozenPlugin: false, dataOwners: ['b', 'a'], exportOwners: ['b', 'b', 'b', 'b', 'a', 'none'], importer: 'a', @@ -8573,6 +8595,7 @@ oracleProperty({ childEnvironment: `node`, midrunGate: false, scratchPlugin: false, + frozenPlugin: false, failingLaw: `none`, failingLawAt: `end`, failingLawCalls: `none`, @@ -8798,6 +8821,7 @@ oracleProperty({ childEnvironment: `node`, midrunGate: false, scratchPlugin: false, + frozenPlugin: false, }, }, { @@ -8972,6 +8996,7 @@ oracleProperty({ childEnvironment: `node`, midrunGate: false, scratchPlugin: false, + frozenPlugin: false, }, }, { @@ -9173,6 +9198,7 @@ oracleProperty({ childEnvironment: `node`, midrunGate: false, scratchPlugin: false, + frozenPlugin: false, }, }, ], @@ -12604,6 +12630,57 @@ oracleProperty({ config: `object`, }), }, + { + // A config whose plugin object is frozen: its hooks cannot take the runner's + // wrapper, so the check names the plugin and stores no unit of it, and + // computes each unit as a cold run does (CR-2). + name: `a check through the daemon of a config whose plugin object is frozen`, + enters: [ + `a check through the daemon with a frozen plugin object named it and stored no unit`, + ], + build: (generated) => ({ + ...generated, + functions: [ + [{ kind: `push`, quote: `'` }], + [{ kind: `push`, quote: `'` }], + ], + containers: [], + overloads: [], + owners: [`a`, `b`], + library: [], + libraryOwners: [], + runes: [], + derived: null, + dotGen: false, + dataOwners: [], + exportOwners: [], + importer: `none`, + wholeFile: `none`, + template: false, + tests: [ + { ...judging(`a`, `fixed seed`, 1), fn: 0 }, + { ...judging(`b`, `fixed seed`, 1), fn: 1 }, + ], + witness: false, + authored: null, + secondAuthored: false, + fault: `none`, + stability: `none`, + ordinary: false, + native: `none`, + boot: false, + budget: `two`, + cliPath: `plain`, + concurrentStart: false, + contexts: 1, + laterSteps: NO_LATER_STEPS, + steps: [`recheck`], + frozenPlugin: true, + configPlace: `discovered`, + configFile: `vite.config.mjs`, + config: `object`, + }), + }, ]), }, resolve: resolveHistory, diff --git a/packages/oracles/oracle-gaps/history-fingerprint.json b/packages/oracles/oracle-gaps/history-fingerprint.json index 1c75c5c0..f29b95da 100644 --- a/packages/oracles/oracle-gaps/history-fingerprint.json +++ b/packages/oracles/oracle-gaps/history-fingerprint.json @@ -95,7 +95,8 @@ ["childWrite", "96cd063b1067f34b"], ["childEnvironment", "65a23ef9c722a68d"], ["midrunGate", "3dbf515a001458e2"], - ["scratchPlugin", "5e372e55093ca141"] + ["scratchPlugin", "5e372e55093ca141"], + ["frozenPlugin", "71622bf0995bc427"] ], "histories": [ ["functions", "66c0e9c56951c377"], @@ -193,6 +194,7 @@ ["childWrite", "96cd063b1067f34b"], ["childEnvironment", "65a23ef9c722a68d"], ["midrunGate", "3dbf515a001458e2"], - ["scratchPlugin", "5e372e55093ca141"] + ["scratchPlugin", "5e372e55093ca141"], + ["frozenPlugin", "71622bf0995bc427"] ] } From 36e95797d8795cc8dc954040a307c35a3d794aae Mon Sep 17 00:00:00 2001 From: Kyle Mathews Date: Wed, 2 Dec 2026 11:19:34 -0700 Subject: [PATCH 15/51] fix(oracle-gaps): a constructed history takes no drawn frozen plugin (S-2) withDeclaration spread the generated base into every constructed history, so a base that drew frozenPlugin: true handed a frozen plugin (which stores no unit, CR-2) to a history that must enter an unchanged check through the daemon that computed nothing. The fixed-seed tsconfig history failed on that seed. A construction now takes the neutral value unless it names the field (the CR-2 history names it itself). Co-authored-by: Isaac --- .../oracles/oracle-gaps/gap-report-oracle.property.test.mjs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs b/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs index f1f100aa..549d9752 100644 --- a/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs +++ b/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs @@ -8226,6 +8226,10 @@ const withDeclaration = (constructed) => failingLawCalls: `none`, failingLawHook: `none`, failingLawSpins: false, + // A frozen plugin stores no unit (CR-2), so a construction that does + // not name it cannot reach a state of reuse: it runs with a plugin + // that can be wrapped. The CR-2 history names it itself. + frozenPlugin: false, declaration: index % 2 === 0 ? `wrapper` : `oracleProperty`, ownerless: false, owners: [`a`, ...generated.owners.slice(1)], From f973aa7160991b04541c44ea32ed5c5bd94dd12a Mon Sep 17 00:00:00 2001 From: Kyle Mathews Date: Wed, 2 Dec 2026 12:10:36 -0700 Subject: [PATCH 16/51] fix(oracle-gaps): a daemon check writes only what its state changed The driver wrote every fixture file back to its state text before each daemon check, so a file that a config plugin had written since the previous check (a pluginWrite gate) was edited again by the harness: a second edit that the history never declared. A daemon check now writes only the files whose state text changed since the previous check (writeFixture's base). A start, a restart or crash step, and a cold run still write every file. The restart rule (G34, model restartOwed) is judged on consecutive daemon checks that both reported: a changed environment, CLI code, or plugin gate file owes a new daemon, and nothing else does. A mid-run edit's check and the check after it are not judged (law 9's limit). Co-authored-by: Isaac --- .../oracle-gaps/gap-report-model-oracle.mjs | 39 ++++- .../gap-report-oracle.property.test.mjs | 155 +++++++++++++++++- 2 files changed, 188 insertions(+), 6 deletions(-) diff --git a/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs b/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs index ce852b54..2756e238 100644 --- a/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs +++ b/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs @@ -6105,6 +6105,34 @@ const inputEnv = (plan, state) => ? { [INPUT_GATE_VAR]: state.inputOpen ? `open` : `shut` } : {} +// The gate kinds whose file the config's plugins, Vite, or the config read in +// the CLI process, so the session holds them as its inputs (check.mjs, +// `reading`; pluginWrite is the session's own write, which a hand edit changes). +export const PLUGIN_INPUT_READS = new Set([ + `pluginConfig`, + `pluginTransform`, + `tsconfig`, + `configListing`, + `pluginWrite`, +]) + +// The restart rule (G34, the daemon restarts when a tracked environment or +// plugin input changes; daemon.mjs `envKey(message.env) !== ownEnv` and +// `codeIdentity() !== code`, check.mjs `inputsChanged`). A check through the +// daemon is served by the daemon that its previous check was served by unless +// one of these changed since that check: the environment its CLI sent, the +// CLI's code (`cliCode`: the copy, its edited copy, or another install), or +// the gate file of a plugin input (`inputOpen`, for a plugin gate kind). The +// e2e oracle judges each pair of consecutive daemon checks that both reported +// (check.pid) against this rule; a refused check's session is not judged +// (law 9's limit). +const envOf = (env) => JSON.stringify(Object.entries(env ?? {}).sort()) +export const restartOwed = (plan, check, previous) => + envOf(check.env) !== envOf(previous.env) || + check.cliCode !== previous.cliCode || + (PLUGIN_INPUT_READS.has(plan.inputRead) && + check.inputOpen !== previous.inputOpen) + function oracleTestFile(plan, file) { const sites = sitesOf(plan) const entries = [ @@ -7330,7 +7358,15 @@ const placeOf = (dir, path) => path.startsWith(BESIDE) ? join(outsideOf(dir), path.slice(BESIDE.length)) : join(dir, path) -function writeFixture(dir, files) { +// The state text a file had at the previous daemon check (`base`, a files map), +// or undefined where every file is written (a start, a restart or crash step, +// a cold run). A daemon check writes only the files whose state text changed +// since that check (R1): a file that a plugin wrote since then keeps the +// plugin's output, and the harness does not re-apply the hand edit over it as +// if the history had edited the file again. Nothing else changes: the removal +// of a file the state lacks, and the stamp of a file that is written. +const sameState = (a, b) => JSON.stringify(a) === JSON.stringify(b) +function writeFixture(dir, files, base) { for (const sub of [ `src`, `tests`, @@ -7345,6 +7381,7 @@ function writeFixture(dir, files) { for (const path of written.get(dir) ?? []) if (!(path in files)) removePath(placeOf(dir, path)) for (const [path, value] of Object.entries(files)) { + if (base !== undefined && sameState(base[path], value)) continue const at = placeOf(dir, path) mkdirSync(dirname(at), { recursive: true }) // A file may name the modification time it gets back (`keepStamp`). diff --git a/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs b/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs index 549d9752..4291ab5e 100644 --- a/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs +++ b/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs @@ -291,6 +291,15 @@ * hold released by the daemon's count of accepted requests, so its reach * names a measured overlap, not two processes' timing. A completed check * through the daemon names its own report in its done line. + * The daemon that serves a check is the one that served the check before + * it, unless an environment variable, the CLI's code, or a plugin gate + * file changed in between (the restart rule, G34: model restartOwed). The + * law judges that only on pairs of consecutive daemon checks that both + * reported. Limit: a check that was refused before its session ran is not + * judged, so a plugin gate's restart after a refused start (which a + * session of pluginWrite opens) is outside this law. A mid-run edit restarts + * the daemon of the check it overlaps, so that check and the one after it + * are not judged against the rule (the mid-run family judges the edit). * 10. **The runner runs the package as Vitest does.** From any install path * (one with a space and `#` included), for any spelling of `--source` * (`./`, a redundant segment, an absolute path through a symbolic link @@ -712,6 +721,8 @@ import { NO_INPUT_STEPS, inputEnv, outsideOf, + PLUGIN_INPUT_READS, + restartOwed, } from './gap-report-model-oracle.mjs' const here = dirname(fileURLToPath(import.meta.url)) @@ -982,7 +993,7 @@ function beforeLastLine(stderr, foreign) { } function runCli(dir, files, how = {}) { - writeFixture(dir, files) + writeFixture(dir, files, how.fixtureBase) const before = new Set(filesUnder(dir)) const { args, out: outBase } = cliArgs(dir, files, how) // Each call has its own output directory: its retention lines are then its own, even when a @@ -2210,7 +2221,7 @@ const byRole = (a, b) => { * starts, so a driver can watch the directory its own call writes. */ async function runClisAtOnce(dir, files, hows, outs = []) { - writeFixture(dir, files) + writeFixture(dir, files, hows[0]?.fixtureBase) return Promise.all( hows.map(async (how) => { const { args, out: outBase } = cliArgs(dir, files, how) @@ -2296,6 +2307,19 @@ function namedScratch(text, names) { ) } +// The steps after which a check's daemon is a new process by the step's own +// act (a start, a kill, a stop), so its pid is not judged against the last +// one (the restart observable, G34). Every other step's pid is judged. +const RESTART_NOT_JUDGED = new Set([ + `start`, + `restart`, + `crash`, + `crashAtOnce`, + `reboot`, + `reusedPid`, + `stopAtOnce`, + `dieMidCheck`, +]) // The note a CLI writes when its daemon sent nothing within its bound and the // check runs cold instead (R39: a cold fallback names its cause). const coldFallbackNote = @@ -2942,6 +2966,20 @@ async function incremental(dir, plan, cli, copy, observe, states) { // How many runs the daemon computed in a check of a state that nothing // changed, where it owes none (undefined elsewhere). let unchangedComputed + // The daemon check before this one, and the pid and inputs that served it + // (the restart observable, G34): undefined after a start or a kill. A pid + // is recorded as its ordinal among the daemons this history met (the first + // is 1), so the trace repeats between runs, where process ids do not. + // The files and step of the previous check (R1: writeFixture writes only what changed). + let lastFiles + let lastStep + let lastDaemon + const daemonOrdinals = new Map() + const ordinalOf = (pid) => { + if (!daemonOrdinals.has(pid)) + daemonOrdinals.set(pid, daemonOrdinals.size + 1) + return daemonOrdinals.get(pid) + } // The check through the daemon during which a mid-run edit landed, and a // cold run of the state before the edit (the `midrun` step). let midrunChecks @@ -2973,8 +3011,19 @@ async function incremental(dir, plan, cli, copy, observe, states) { : reportText, ) const files = fixtureFiles(resolveHistory(state.history), state) + // R1 (the driver's rule, writeFixture): a daemon check writes only the files + // whose state text changed since the previous check. A start, a restart or + // crash step, and a check after one write every file (fixtureBase undefined). + const previousStep = lastStep + const fixtureBase = + RESTART_NOT_JUDGED.has(step) || RESTART_NOT_JUDGED.has(previousStep) + ? undefined + : lastFiles + lastFiles = files + lastStep = step const key = fingerprint(files, state, step === `otherInstall`) const how = { + fixtureBase, seed: state.seed, outMode: plan.outMode, unsupervised: plan.unsupervised, @@ -3048,7 +3097,8 @@ async function incremental(dir, plan, cli, copy, observe, states) { Number(readFileSync(overlapMark, `utf8`)) >= 2 if (overlapMark) rmSync(dirname(overlapMark), { recursive: true, force: true }) - if (!cold.has(key)) cold.set(key, runCli(dir, files, how)) + if (!cold.has(key)) + cold.set(key, runCli(dir, files, { ...how, fixtureBase: undefined })) const coldRun = cold.get(key) if (plan.outMode === `default`) states.add(`a daemon check with the default output directory`) @@ -3068,6 +3118,46 @@ async function incremental(dir, plan, cli, copy, observe, states) { step === `recheck` && reuseOwed ? computedRuns(daemon) : undefined const laterComputed = twice && reuseOwed ? computedRuns(others[0]) : undefined + // The restart observable (G34): the pid that ran this check (check.pid), + // against the pid of the daemon's previous check. A start or a kill has no + // previous daemon to compare with, since its pid changes by its own act. + const cliCode = + step === `otherInstall` ? `other` : state.cliEdited ? `edited` : `copy` + // A mid-run edit restarts the daemon of the check it overlaps (midrun), and the + // check after it is not judged against the one before: the mid-run family + // judges that restart (law 9's limit). + const priorDaemon = + RESTART_NOT_JUDGED.has(step) || + step === `midrun` || + previousStep === `midrun` + ? undefined + : lastDaemon + lastDaemon = + daemon.checkPid === undefined + ? undefined + : { + pid: ordinalOf(daemon.checkPid), + env: how.env, + cliCode, + inputOpen: state.inputOpen, + reported: daemon.reported === true, + } + const restart = + daemon.checkPid === undefined + ? undefined + : { + step, + pid: ordinalOf(daemon.checkPid), + previousPid: priorDaemon?.pid, + env: how.env, + previousEnv: priorDaemon?.env, + cliCode, + previousCode: priorDaemon?.cliCode, + inputOpen: state.inputOpen, + previousInputOpen: priorDaemon?.inputOpen, + reported: daemon.reported === true, + previousReported: priorDaemon?.reported, + } for (const [i, run] of [daemon, ...others].entries()) { // A daemon's call: the daemon the driver killed during it, if any, or // the one that held its check until the CLI fell back, wrote the lines @@ -3093,6 +3183,7 @@ async function incremental(dir, plan, cli, copy, observe, states) { step: i === 0 ? step : `${step} (a second check at once)`, markerStored, unchangedComputed: i === 0 ? unchangedComputed : laterComputed, + restart: i === 0 ? restart : undefined, midrun: i === 0 && step === `midrun` && midrunChecks ? { @@ -3202,6 +3293,17 @@ async function incremental(dir, plan, cli, copy, observe, states) { states.add( `a check through the daemon with a frozen plugin object named it and stored no unit`, ) + // A daemon restart on a changed plugin input (G34): the check whose plugin + // gate file changed was served by a new daemon. + if ( + restart?.previousPid !== undefined && + restart.reported && + restart.previousReported && + restart.pid !== restart.previousPid && + PLUGIN_INPUT_READS.has(plan.inputRead) && + restart.inputOpen !== restart.previousInputOpen + ) + states.add(`a daemon restart on a changed plugin input`) if (plan.fault === `brokenVitest` && daemon.refusal !== undefined) states.add(`a session failure larger than a socket buffer`) const after = { @@ -3628,14 +3730,22 @@ async function incremental(dir, plan, cli, copy, observe, states) { `a run edited the ${plan.midrunTarget} it had read, during a check through the daemon`, ) } - const next = runCli(dir, files, { ...how, daemon: true }) + const next = runCli(dir, files, { + ...how, + daemon: true, + fixtureBase: before, + }) // The marker is out of a run's inputs by design; a runner that stored // a run under it would let the marker's edit, and not the helper's or // the data's, decide whether a run is stored. markerStored ||= storedInputs(dir).some((path) => path.endsWith(`/.oracle-gaps-midrun.txt`), ) - midrunChecks = { during, before: runCli(dir, before, how), landed } + midrunChecks = { + during, + before: runCli(dir, before, { ...how, fixtureBase: undefined }), + landed, + } // The check the edit overlapped, through the daemon, and the cold run of // the state before the edit: each call's lines are judged as any call's. for (const run of [during, midrunChecks.before]) @@ -5285,6 +5395,35 @@ function incrementalCheck(observations, expected, plan) { }, ) } + // The restart observable (G34): the pid of a check's daemon changes exactly + // where the restart rule owes a restart (model: restartOwed). A surviving + // restart and a missing one both fail, and so does a restart at an + // unchanged recheck. + if ( + value.restart?.previousPid !== undefined && + value.restart.reported && + value.restart.previousReported + ) { + const { restart: r } = value + const owed = restartOwed( + plan, + { env: r.env, cliCode: r.cliCode, inputOpen: r.inputOpen }, + { + env: r.previousEnv, + cliCode: r.previousCode, + inputOpen: r.previousInputOpen, + }, + ) + const restarted = r.pid !== r.previousPid + if (restarted !== owed) + return violation( + `incremental`, + owed + ? `the check through the daemon at ${step} kept the daemon that served its previous check (pid ${r.pid}), though a tracked input changed` + : `the check through the daemon at ${step} was served by a new daemon (pid ${r.previousPid} to ${r.pid}), though no tracked input changed`, + `restart iff a tracked input changed`, + ) + } if (value.unchangedComputed > 0) return violation( `incremental`, @@ -7655,6 +7794,7 @@ const ownedIncrementalStates = [ `a hand edit of a file the config's plugin writes was checked through the daemon`, `edit inputGate changed the cold result`, `an edit that kept a file's size and modification time changed the cold result`, + `a daemon restart on a changed plugin input`, ] // The static states (probe structure and ownership through the reference // tree) are gap-report-static-oracle's: it reaches each in every campaign, @@ -8321,6 +8461,11 @@ const gateKindHistory = ([name, inputRead, keepStamp, reuses = true]) => ({ `an edit that kept a file's size and modification time changed the cold result`, ] : []), + // A plugin input that the session holds restarts the daemon: the check + // after its edit is served by a new daemon (G34, the restart observable). + ...(PLUGIN_INPUT_READS.has(inputRead) + ? [`a daemon restart on a changed plugin input`] + : []), ], build: (generated) => ({ ...generated, From 7166a038bac0b3e8465a49a8bbdbdf5be6adda4f Mon Sep 17 00:00:00 2001 From: Kyle Mathews Date: Wed, 2 Dec 2026 12:16:35 -0700 Subject: [PATCH 17/51] test(oracle-gaps): the restart rule's calibrations kill a kept and a new daemon Two calibrations for the restart observable (G34, law 9's restart rule). One corrupts a check that a changed plugin input owes a new daemon, and that kept its daemon, so the trace says the daemon was kept; the other corrupts an unchanged recheck that kept its daemon into one a new process served. Both must fail the restart law (checked on its named history). Calibration evidence, not run on the head as a separate claim: the CR-3 RED (the pre-fix ownWrite line) fails the scratch-plugin history at recheck with a new daemon (pid 1 to 2), and passes once restored. A hostile mutant (the daemon's restart ignores the environment) fails the environment history at inputGate on both fixed and random seeds. Co-authored-by: Isaac --- .../gap-report-oracle.property.test.mjs | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs b/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs index 4291ab5e..140754df 100644 --- a/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs +++ b/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs @@ -7132,6 +7132,53 @@ calibrations.push( // holds only when the edit landed (fourth review of #55, F-C1): with no // edit, that check reads one state, so a mutant of file b that it reports // as neither cold run does, killed for survived, is a violation. +// The restart observable (G34, law 9's restart rule): a check that a changed +// plugin input owes a new daemon, and that kept its daemon, is named; and a +// check at an unchanged recheck that a new daemon served is named. +calibrations.push({ + name: `the check that a changed plugin input reached kept the daemon of the check before it`, + law: `restart iff a tracked input changed`, + history: { + constructed: `an edit to a file the config's plugin reads when the config resolves`, + }, + corrupt: (trace) => { + const index = trace.findIndex( + (o) => + o.checkpoint === `incremental` && + o.value.restart?.previousPid !== undefined && + o.value.restart.reported && + o.value.restart.previousReported && + o.value.restart.pid !== o.value.restart.previousPid, + ) + if (index < 0) return undefined + const value = structuredClone(trace[index].value) + value.restart.pid = value.restart.previousPid + return trace.map((o, i) => (i === index ? { ...o, value } : o)) + }, +}) + +calibrations.push({ + name: `the unchanged recheck that a new daemon served is named`, + law: `restart iff a tracked input changed`, + history: { + constructed: `an unchanged check through the daemon while a config's plugin writes, stats and removes a scratch file`, + }, + corrupt: (trace) => { + const index = trace.findIndex( + (o) => + o.checkpoint === `incremental` && + o.value.step === `recheck` && + o.value.restart?.previousPid !== undefined && + o.value.restart.reported && + o.value.restart.previousReported, + ) + if (index < 0) return undefined + const value = structuredClone(trace[index].value) + value.restart.pid = value.restart.previousPid + 1000 + return trace.map((o, i) => (i === index ? { ...o, value } : o)) + }, +}) + calibrations.push({ name: `the check a mid-run edit did not reach flips a mutant of the editing file`, law: `incremental equals cold`, From 241ee5a699047a6630937d6d5c27e81959284714 Mon Sep 17 00:00:00 2001 From: Kyle Mathews Date: Wed, 2 Dec 2026 13:01:07 -0700 Subject: [PATCH 18/51] fix(oracle-gaps): a frozen plugin's state reads an unreadable store as undecided The frozen-plugin state (CR-2) read the evidence store, which the corruptStore step overwrites, and threw. After the merge of main (#99, #314) the store is corrupted in more histories, so the state now reads it through storedNoneReadable: an unreadable store decides no state. Co-authored-by: Isaac --- .../oracle-gaps/gap-report-oracle.property.test.mjs | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs b/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs index 9aa26175..9b09a1c3 100644 --- a/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs +++ b/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs @@ -2935,6 +2935,16 @@ const waitGone = async (pid) => { * The paths that the package's daemon stored any run under, from its * evidence store (evidence.mjs), or none when it has stored nothing. */ +// Whether the package's store holds no unit. A store that cannot be read (the +// corruptStore step overwrites it) decides no state: false, not a guess. +function storedNoneReadable(dir) { + try { + return storedUnits(stateDirOf(realpathSync(dir))).length === 0 + } catch { + return false + } +} + function storedInputs(dir) { return storedUnits(stateDirOf(realpathSync(dir))).flatMap((row) => row.variants.flatMap((variant) => variant.inputs.map(([path]) => path)), @@ -3337,7 +3347,7 @@ async function incremental(dir, plan, cli, copy, observe, states) { if ( plan.frozenPlugin && daemon.stream.notes.some((note) => frozenPluginNote.test(note)) && - storedUnits(stateDirOf(realpathSync(dir))).length === 0 + storedNoneReadable(dir) ) states.add( `a check through the daemon with a frozen plugin object named it and stored no unit`, From 6d7abf6fb9b8316d8e82ac9bb1a7e8b385caf295 Mon Sep 17 00:00:00 2001 From: Kyle Mathews Date: Wed, 2 Dec 2026 13:18:38 -0700 Subject: [PATCH 19/51] fix(oracle-gaps): a unit a daemon check does not store names its moved input A unit whose input moved during its run is not stored, and an unchanged recheck then recomputes it. Nothing said which unit, or which input. The daemon's check now writes one line per such unit to daemon.log: the unit's file, spec and select, and each input's key with its hash at read and at check end, or that the unit read no input. A cold run writes none. Results and the stream are unchanged. Co-authored-by: Isaac --- packages/oracles/oracle-gaps/check.mjs | 42 ++++++++++++++++++++++--- packages/oracles/oracle-gaps/daemon.mjs | 2 ++ 2 files changed, 39 insertions(+), 5 deletions(-) diff --git a/packages/oracles/oracle-gaps/check.mjs b/packages/oracles/oracle-gaps/check.mjs index 9d33a70c..1aacd3bd 100644 --- a/packages/oracles/oracle-gaps/check.mjs +++ b/packages/oracles/oracle-gaps/check.mjs @@ -2064,6 +2064,9 @@ export default async (env) => { log = console.error, progress = () => {}, gone = () => false, + // The daemon's diagnostic line (its log, daemon.log): a unit a check did + // not store, and why. Undefined for a cold run, which writes none. + diag = undefined, ) { // A check whose caller has gone (a daemon's CLI that checked cold) stops // before it writes more into its --out: here, at each phase's end, and @@ -2281,12 +2284,14 @@ export default async (env) => { // a file's from the copy's first read of it (`readAt`), a module's from // its context's transform of it, or else its hash at the start, or now. // A path that changed while the run ran is invalidated, and the run is - // not stored (undefined); nor is a run with no known input. - function settleIn(context, started, runPaths, runReadAt = {}) { + // not stored (undefined); nor is a run with no known input. `label` names + // the unit in the diagnostic line (`diag`) of a run that is not stored. + function settleIn(context, started, runPaths, runReadAt = {}, label) { const index = indexOf.get(context) const served = servedBy(index) const loads = globalThis.__oracleGapsLoads[index] let stable = runPaths.length > 0 + const moved = [] // What the config's plugins have read so far, each with its hash from // its read: the run may have read through any of it (see hookReads). // A variable that the CLI set (`wrote`) is its own output, which a @@ -2306,12 +2311,28 @@ export default async (env) => { context.invalidateFile(posix(path)) loads?.delete(path) } - if (hash !== now) stable = false + if (hash !== now) { + stable = false + moved.push( + `${path} read at ${hash.slice(0, 12)}, at check end ${now.slice(0, 12)}`, + ) + } served.set(path, now) return [path, hash] }) + if (!stable && label !== undefined && diag !== undefined) + diag( + `oracle-gaps: note unit ${label} is not stored: ${ + moved.length > 0 + ? `an input moved during its run: ${moved.join(`; `)}` + : `it read no input` + }`, + ) return stable ? inputs : undefined } + // The name a diagnostic line gives a unit: its file, spec and select. + const labelOf = (file, spec, select) => + `${relativeWithin(pkg, file) ?? posix(file)} spec ${spec} select ${JSON.stringify(select ?? null)}` // A copy cut by a clock or by its call count: its own run's timeout, or // Vitest's own limit ("Test timed out"), which the copy outlived. Such a // copy is never charged, and it ends the mutant's copies (the outcome rule, @@ -2366,7 +2387,7 @@ export default async (env) => { items, options.seed ?? null, ) - const inputs = items.map(({ file }, k) => + const inputs = items.map(({ file, spec, select }, k) => // A unit whose child log lost lines is not stored (CR-19). batch.units[k]?.childLost ? undefined @@ -2380,6 +2401,9 @@ export default async (env) => { ]), ], batch.units[k]?.readAt, + batch.units[k] && !batch.units[k].skipped + ? labelOf(file, spec, select) + : undefined, ), ) return { ...batch, inputs } @@ -2425,7 +2449,15 @@ export default async (env) => { // A run whose child log lost lines is not stored (CR-19). const inputs = result.childLost ? undefined - : settleIn(context, started, paths, result.readAt) + : settleIn( + context, + started, + paths, + result.readAt, + keep && !result.skipped + ? labelOf(file, spec, runOptions.select) + : undefined, + ) if (keep) remember(id, result, inputs) } return result diff --git a/packages/oracles/oracle-gaps/daemon.mjs b/packages/oracles/oracle-gaps/daemon.mjs index df07426d..d4ff4686 100644 --- a/packages/oracles/oracle-gaps/daemon.mjs +++ b/packages/oracles/oracle-gaps/daemon.mjs @@ -569,6 +569,8 @@ async function serve(pkg) { (line) => stderr.push(`${line}\n`), beat, () => connection.destroyed, + // The daemon's log (daemon.log): a unit not stored, and why. + (line) => console.error(line), ) // The store is a cache: a flush that fails (a full disk) loses // nothing the check reported, so the reply stands, and the units From 3b32dc7bae6737512dd50af45d198d0c867d7b3b Mon Sep 17 00:00:00 2001 From: Kyle Mathews Date: Wed, 2 Dec 2026 14:17:16 -0700 Subject: [PATCH 20/51] fix(oracle-gaps): a file a run's own tree made is its output, not an input An unchanged recheck through the daemon recomputed five units of TanStack DB's packages/db (the unrepaired branch stored 554 of 559). Each read a path that the run itself then made or changed, so the end state moved and the run was not stored: - a test that checks for a file, then its child process makes it (a tsx compile cache, pid-named, left behind): absent when read, present after; - a test that copies a fixture into a directory it makes (copyFileSync was not a write), its child reads the copy, the test removes the directory; - a test that lists a directory it makes, then writes a report into it. Each path is now the run's own output, so no input (law 9's "own outputs are not inputs"): a path its tree created or copied that it read absent, and a directory the run made entries in. A path the run read present and then changed is still an input that moved, so its run is not stored (a file the test rewrites with different content each run). Vitest's own results cache is the runner's output. Limit, stated in check.mjs and the e2e law: a later run that finds a leftover of an earlier run at such a path reuses the stored run, so a test whose outcome depends on that leftover is not hermetic. Three constructed histories (ownOutput: created, copied, listed) are RED on the unrepaired branch (both seeds, "computed 2 runs that were not cut off") and GREEN after. Hostile mutant (the owned check off): created fails on both seeds. The results and the stream are the same shape. Co-authored-by: Isaac --- .../oracles/oracle-gaps/capture-setup.mjs | 7 +- packages/oracles/oracle-gaps/check.mjs | 44 +++++++++- .../oracle-gaps/constructed-order.json | 5 +- .../oracle-gaps/gap-report-model-oracle.mjs | 61 +++++++++++++ .../gap-report-oracle.property.test.mjs | 88 +++++++++++++++++++ .../oracle-gaps/history-fingerprint.json | 2 + packages/oracles/oracle-gaps/inputs.mjs | 26 +++++- packages/oracles/scripts/e2e-shards.mjs | 9 ++ packages/oracles/scripts/pr-shards.mjs | 3 + 9 files changed, 239 insertions(+), 6 deletions(-) diff --git a/packages/oracles/oracle-gaps/capture-setup.mjs b/packages/oracles/oracle-gaps/capture-setup.mjs index 77101a73..cee0db75 100644 --- a/packages/oracles/oracle-gaps/capture-setup.mjs +++ b/packages/oracles/oracle-gaps/capture-setup.mjs @@ -1402,10 +1402,15 @@ afterAll(() => { // The child processes' reads after the copy's last own read or write. foldChildren() const readAt = Object.fromEntries(globalThis.__oracleGapsReads) + // The files the copy or its process tree wrote or copied (`own`): the run's + // own output, which no input of the run is (check.mjs, settleIn). + const own = [...wrote] + .filter((key) => key.startsWith(`fs:`)) + .map((key) => key.slice(`fs:`.length)) // A child process that lost a line of its log (child-writes.mjs) left the // marker, so the run's reads are not all here (CR-19). const childLost = existsSync(`${childLog}.lost`) appendClosingRow( - `${JSON.stringify({ file: thisFile, closed: true, at: realNow(), loaded, readAt, childLost, ...(skippedCopy ? { skipped: true } : {}) })}\n`, + `${JSON.stringify({ file: thisFile, closed: true, at: realNow(), loaded, readAt, own, childLost, ...(skippedCopy ? { skipped: true } : {}) })}\n`, ) }) diff --git a/packages/oracles/oracle-gaps/check.mjs b/packages/oracles/oracle-gaps/check.mjs index 1aacd3bd..539a0d7e 100644 --- a/packages/oracles/oracle-gaps/check.mjs +++ b/packages/oracles/oracle-gaps/check.mjs @@ -23,6 +23,15 @@ // watches, a read from a child process that a test starts with an environment // that drops NODE_OPTIONS (#143), and a new file that changes how an unchanged // import resolves. A worker thread a test starts is covered (capture-setup.mjs). +// Own output (law 9, round 13, 2026-12-02, pending the maintainer's acceptance +// of this limit): a path that the run's own process tree created or copied, +// which the run read as absent, is no input, and neither is a directory the +// run made entries in (inputs.mjs, capture-setup.mjs, settleIn). A path the run +// read present and then changed is an input that moved, so its run is not +// stored. Limit: a later run that finds a leftover of an earlier run at such a +// path reuses the stored run as if the path were absent or unlisted, so a test +// whose outcome depends on that leftover is not hermetic, and not covered. +// Vitest's own results cache is the runner's output (inputs.mjs isRunnerFile). // Node's own reads of the package.json files that a require consults (main, // type) are covered by a wrapper on Module._resolveFilename in the copy // (capture-setup.mjs). That is a private Node API, not a documented one: if a @@ -1413,6 +1422,7 @@ export default async (env) => { rows, inputs: importsOf(file, modules, closing), readAt: closing.readAt, + own: closing.own, // A child process's log lost lines, so its reads are not all here // (child-writes.mjs): the run is not stored (CR-19). childLost: closing.childLost === true, @@ -1446,6 +1456,7 @@ export default async (env) => { seconds, inputs: importsOf(file, modules, closing), readAt: closing.readAt, + own: closing.own, childLost: closing.childLost === true, } } @@ -1816,6 +1827,7 @@ export default async (env) => { rows: own.map((row) => [row.key, row]), inputs: importsOf(item.file, [], closings.get(copies[i])), readAt: closings.get(copies[i])?.readAt, + own: closings.get(copies[i])?.own, childLost: closings.get(copies[i])?.childLost === true, } }), @@ -1891,6 +1903,7 @@ export default async (env) => { .map((row) => [map(row.key), { ...row, key: map(row.key) }]), inputs: importsOf(item.file, modules, closings.get(copy)), readAt: closings.get(copy)?.readAt, + own: closings.get(copy)?.own, childLost: closings.get(copy)?.childLost === true, } }), @@ -2286,10 +2299,35 @@ export default async (env) => { // A path that changed while the run ran is invalidated, and the run is // not stored (undefined); nor is a run with no known input. `label` names // the unit in the diagnostic line (`diag`) of a run that is not stored. - function settleIn(context, started, runPaths, runReadAt = {}, label) { + // `own` is the run's own output (capture-setup.mjs): a path its tree + // created or copied is no input when the run read it absent, and so is a + // directory it made entries in (law 9, own outputs are not inputs). A path + // present when read, which the run then changed, is still an input. + function settleIn( + context, + started, + given, + runReadAt = {}, + label, + own = [], + ) { const index = indexOf.get(context) const served = servedBy(index) const loads = globalThis.__oracleGapsLoads[index] + const owned = (path) => + own.some((root) => path === root || path.startsWith(`${root}/`)) + const runPaths = given.filter((key) => { + const path = key.slice(key.indexOf(`:`) + 1) + const absent = (runReadAt[key] ?? started.get(key)) === `missing` + if (/^(fs|stat|statx|dir|dirs):/.test(key) && absent && owned(path)) + return false + if ( + /^(dir|dirs):/.test(key) && + own.some((root) => root.startsWith(`${path}/`)) + ) + return false + return true + }) let stable = runPaths.length > 0 const moved = [] // What the config's plugins have read so far, each with its hash from @@ -2348,7 +2386,7 @@ export default async (env) => { // decision (M, 2026-11-23; I8, I12). A count or state cut is stored. // A unit is stored without the hashes of what its copy read (`readAt`), // which only its settling used: the stored inputs hold them. - const remember = (id, { readAt, ...unit }, inputs) => { + const remember = (id, { readAt, own, ...unit }, inputs) => { if (!inputs) return const entry = { inputs: sharedInputs(inputs), unit } hook?.stored(entry) @@ -2404,6 +2442,7 @@ export default async (env) => { batch.units[k] && !batch.units[k].skipped ? labelOf(file, spec, select) : undefined, + batch.units[k]?.own, ), ) return { ...batch, inputs } @@ -2457,6 +2496,7 @@ export default async (env) => { keep && !result.skipped ? labelOf(file, spec, runOptions.select) : undefined, + result.own, ) if (keep) remember(id, result, inputs) } diff --git a/packages/oracles/oracle-gaps/constructed-order.json b/packages/oracles/oracle-gaps/constructed-order.json index 80611275..6a1d7389 100644 --- a/packages/oracles/oracle-gaps/constructed-order.json +++ b/packages/oracles/oracle-gaps/constructed-order.json @@ -194,6 +194,9 @@ "an edit to a file a test reads through a link and dot-dot", "an edit to a file a test reads in a worker with strict mode", "an unchanged check through the daemon while a config's plugin writes, stats and removes a scratch file", - "a check through the daemon of a config whose plugin object is frozen" + "a check through the daemon of a config whose plugin object is frozen", + "an unchanged check through the daemon while a test made the files it reads: a file its child process makes after the test checks for it", + "an unchanged check through the daemon while a test made the files it reads: a copy its child process reads, in a directory it removes", + "an unchanged check through the daemon while a test made the files it reads: a directory it lists before it writes a file into it" ] } diff --git a/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs b/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs index e9a49d77..bb245ee6 100644 --- a/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs +++ b/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs @@ -1536,6 +1536,21 @@ const drawn = fc.record({ scratchPlugin: fc.constantFrom(false, false, false, false, true), // Drawn last (CR-2): the config's plugin object is frozen, so the runner cannot wrap its hooks (`frozenPlugin`). frozenPlugin: fc.constantFrom(false, false, false, false, true), + // File b's own output (OWN_OUTPUT_READS): drawn last, so the draws above keep + // their values for every seed. Most histories run without it. + ownOutput: fc.constantFrom( + `none`, + `none`, + `none`, + `none`, + `none`, + `none`, + `none`, + `none`, + `created`, + `copied`, + `listed`, + ), }) // The edit sequence over the witness module, the one list of steps that a @@ -3995,6 +4010,7 @@ function resolveHistory(history) { slowStart: history.slowStart ?? false, shortWait: history.shortWait === true, childWrite: history.childWrite === true, + ownOutput: history.ownOutput ?? `none`, // A client environment rewrites `new URL(..., import.meta.url)` to the dev // server's URL, so file b's raw-import check (rawImport) cannot read the // module there: such a history runs its file b in node (CR-8). @@ -6886,6 +6902,48 @@ const childWriteRead = [ `removeChild(childDir, { recursive: true, force: true })`, `if (childText !== 'written') throw new Error('the child process wrote another text')`, ] +// File b's own output (`ownOutput`), made in the run and read by it, which +// the run must not record as an input: `created` (the test checks for a file, +// its child process makes it, and the test reads and removes it), `copied` +// (the test copies a file into a new directory, its child process reads the +// copy, and the test removes the directory), and `listed` (the test lists a +// new directory, writes a file into it, and lists it again). Each is a +// read of a path that the run itself changes before the check ends. +const OWN_OUTPUT_READS = { + created: [ + `import { execFileSync as ownRun } from 'node:child_process'`, + `import { mkdtempSync as ownMake, readFileSync as ownRead, rmSync as ownRemove, writeFileSync as ownWrite } from 'node:fs'`, + `import { tmpdir as ownTmp } from 'node:os'`, + `import { join as ownJoin } from 'node:path'`, + `const ownDirectory = ownMake(ownJoin(ownTmp(), 'gap-own-'))`, + `const ownFile = ownJoin(ownDirectory, 'made.txt')`, + `ownRun(process.execPath, ['-e', ${JSON.stringify(`const fs = require('node:fs'); let found = true; try { fs.readFileSync(process.argv[1]) } catch { found = false } if (!found) fs.writeFileSync(process.argv[1], 'made')`)}, ownFile])`, + `if (ownRead(ownFile, 'utf8') !== 'made') throw new Error('the child made another text')`, + ], + copied: [ + `import { execFileSync as ownRun } from 'node:child_process'`, + `import { copyFileSync as ownCopy, mkdtempSync as ownMake, rmSync as ownRemove } from 'node:fs'`, + `import { tmpdir as ownTmp } from 'node:os'`, + `import { fileURLToPath as ownPath } from 'node:url'`, + `import { join as ownJoin } from 'node:path'`, + `const ownCopyDirectory = ownMake(ownJoin(ownTmp(), 'gap-copy-'))`, + `const ownCopied = ownJoin(ownCopyDirectory, 'strict.ts')`, + `ownCopy(ownPath(new URL('./strict.ts', import.meta.url)), ownCopied)`, + `const ownText = ownRun(process.execPath, ['-e', ${JSON.stringify(`process.stdout.write(require('node:fs').readFileSync(process.argv[1], 'utf8').slice(0, 12))`)}, ownCopied], { encoding: 'utf8' })`, + `if (ownText.length === 0) throw new Error('the child read no copy')`, + `ownRemove(ownCopyDirectory, { recursive: true, force: true })`, + ], + listed: [ + `import { mkdtempSync as ownMake, readdirSync as ownList, rmSync as ownRemove, writeFileSync as ownWrite } from 'node:fs'`, + `import { tmpdir as ownTmp } from 'node:os'`, + `import { join as ownJoin } from 'node:path'`, + `const ownListDirectory = ownMake(ownJoin(ownTmp(), 'gap-list-'))`, + `if (ownList(ownListDirectory).length !== 0) throw new Error('the new directory held entries')`, + `ownWrite(ownJoin(ownListDirectory, 'report.json'), '{}')`, + `if (ownList(ownListDirectory).length !== 1) throw new Error('the directory did not hold the report')`, + `ownRemove(ownListDirectory, { recursive: true, force: true })`, + ], +} /** The variables a check of `state` runs with: the gate's, under `env`. */ const inputEnv = (plan, state) => plan.inputRead === `env` @@ -7046,6 +7104,9 @@ function oracleTestFile(plan, file) { ? inputReads[plan.inputRead] : []), ...(file === `b` && plan.childWrite ? childWriteRead : []), + ...(file === `b` && plan.ownOutput !== `none` + ? OWN_OUTPUT_READS[plan.ownOutput] + : []), ...stubs, // State that tests of this file share (the `w_shared` witness). `const shared = { value: 0 }`, diff --git a/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs b/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs index 9b09a1c3..19bb15a8 100644 --- a/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs +++ b/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs @@ -546,6 +546,16 @@ * than the seed and the gate's, a new file that changes how an * unchanged import resolves, a change to the Vite config or the installed * packages, or checks at once other than the two that start the daemon. + * Own output (law 9, round 13, 2026-12-02; the maintainer has not yet accepted + * this limit): a file a run's own process tree creates or copies, which the run + * reads as absent, and a directory the run makes entries in, are the run's own + * output, no input of it (the constructed histories `ownOutput`: a test whose + * child makes the file it checks for, a copy its child reads, a listing before a + * write). A file the run reads present and then changes is an input that moved, + * so its run is not stored (a file the test rewrites with different content each + * run). The limit: a later run that finds a leftover of an earlier run at such a + * path reuses the stored run as if the path were absent or unlisted, so a test + * whose outcome depends on its own leftover is not hermetic, and is not covered. * The harness keeps every global a copy defines configurable, by wrapping * `Object.defineProperty`, `Object.defineProperties`, and * `Reflect.defineProperty`, so that each copy in the shared realm starts @@ -554,6 +564,7 @@ * under the report, which law 3's capture clause does not cover * (maintainer decision, 2026-11-08; such a test belongs outside the * owns-declaring files). The daemon count after a stop is read from the process list. Two + * owns-declaring files). The daemon count after a stop is read from the process list. Two * daemon defects have no observation here: a stale lock removed without * the atomic claim (two daemons serve until the loser sees its lock taken, * within 2 s), and a stop that releases the lock before it closes the @@ -3414,6 +3425,13 @@ async function incremental(dir, plan, cli, copy, observe, states) { states.add( `an unchanged check through the daemon computed nothing while a test read what its child process wrote`, ) + // File b made the files it reads during its run (`ownOutput`): the + // unchanged recheck reused b's runs, although each read was of the run's + // own output (check.mjs, settleIn; the own-output rule of law 9). + if (plan.ownOutput !== `none`) + states.add( + `an unchanged check through the daemon computed nothing while a test made the files it reads`, + ) // File a's test wrote to the process's streams, so its copy appended to // the run's own test-output.log, which the run creates (capture-setup.mjs, // isRunnerOwnAppend): the unchanged recheck reused a's runs. @@ -8864,6 +8882,7 @@ const required = [ `a slow daemon start was served by the daemon`, `a check abandoned while a context warmed in place of a cut one wrote nothing more`, `an unchanged check through the daemon computed nothing while a test read what its child process wrote`, + `an unchanged check through the daemon computed nothing while a test made the files it reads`, `an unchanged check through the daemon computed nothing while a test wrote to the console`, ] // The faults the CLI analyzes anyway: a package's TypeScript is no input. @@ -9046,6 +9065,7 @@ const separate = [ // Each has its own constructed history (#179; own writes of the test's // process tree). `an unchanged check through the daemon computed nothing while a test read what its child process wrote`, + `an unchanged check through the daemon computed nothing while a test made the files it reads`, // Its own constructed history (a test that writes to the console). `an unchanged check through the daemon computed nothing while a test wrote to the console`, ] @@ -9213,6 +9233,7 @@ const withDeclaration = (constructed) => midrunGate: false, scratchPlugin: false, frozenPlugin: false, + ownOutput: `none`, ...item.build({ ...generated, // The end-to-end dimensions a generated base may draw: a construction @@ -9233,6 +9254,7 @@ const withDeclaration = (constructed) => // not name it cannot reach a state of reuse: it runs with a plugin // that can be wrapped. The CR-2 history names it itself. frozenPlugin: false, + ownOutput: `none`, declaration: index % 2 === 0 ? `wrapper` : `oracleProperty`, ownerless: false, owners: [`a`, ...generated.owners.slice(1)], @@ -9637,6 +9659,7 @@ oracleProperty({ steps: null, scratchPlugin: false, frozenPlugin: false, + ownOutput: `none`, dataOwners: ['b', 'a'], exportOwners: ['b', 'b', 'b', 'b', 'a', 'none'], importer: 'a', @@ -9687,6 +9710,7 @@ oracleProperty({ midrunGate: false, scratchPlugin: false, frozenPlugin: false, + ownOutput: `none`, failingLaw: `none`, failingLawAt: `end`, failingLawCalls: `none`, @@ -9931,6 +9955,7 @@ oracleProperty({ midrunGate: false, scratchPlugin: false, frozenPlugin: false, + ownOutput: `none`, }, }, { @@ -10119,6 +10144,7 @@ oracleProperty({ midrunGate: false, scratchPlugin: false, frozenPlugin: false, + ownOutput: `none`, }, }, { @@ -10339,6 +10365,7 @@ oracleProperty({ midrunGate: false, scratchPlugin: false, frozenPlugin: false, + ownOutput: `none`, }, }, ], @@ -16333,11 +16360,72 @@ oracleProperty({ laterSteps: NO_LATER_STEPS, steps: [`recheck`], frozenPlugin: true, + ownOutput: `none`, configPlace: `discovered`, configFile: `vite.config.mjs`, config: `object`, }), }, + ...[ + // The three shapes of a test's own output (ownOutput, the model): the + // test reads a file its child process makes, a copy its child reads, or + // a directory it writes into. Each unchanged recheck must reuse every run + // (law 9, own outputs are not inputs; check.mjs settleIn). + [ + `created`, + `a file its child process makes after the test checks for it`, + ], + [`copied`, `a copy its child process reads, in a directory it removes`], + [`listed`, `a directory it lists before it writes a file into it`], + ].map(([ownOutput, shape]) => ({ + name: `an unchanged check through the daemon while a test made the files it reads: ${shape}`, + enters: [ + `an unchanged check through the daemon computed nothing while a test made the files it reads`, + ], + build: (generated) => ({ + ...generated, + functions: [ + [{ kind: `push`, quote: `'` }], + [{ kind: `push`, quote: `'` }], + ], + containers: [], + overloads: [], + owners: [`a`, `b`], + library: [], + libraryOwners: [], + runes: [], + derived: null, + dotGen: false, + dataOwners: [], + exportOwners: [], + importer: `none`, + wholeFile: `none`, + template: false, + tests: [ + { ...judging(`a`, `fixed seed`, 1), fn: 0 }, + { ...judging(`b`, `fixed seed`, 1), fn: 1 }, + ], + witness: false, + authored: null, + secondAuthored: false, + fault: `none`, + stability: `none`, + ordinary: false, + native: `none`, + boot: false, + budget: `two`, + cliPath: `plain`, + concurrentStart: false, + contexts: 1, + laterSteps: NO_LATER_STEPS, + steps: [`recheck`], + childWrite: false, + ownOutput, + configPlace: `discovered`, + configFile: `vite.config.mjs`, + config: `object`, + }), + })), ]), }, resolve: resolveHistory, diff --git a/packages/oracles/oracle-gaps/history-fingerprint.json b/packages/oracles/oracle-gaps/history-fingerprint.json index 57772c0b..0628bf5f 100644 --- a/packages/oracles/oracle-gaps/history-fingerprint.json +++ b/packages/oracles/oracle-gaps/history-fingerprint.json @@ -101,6 +101,7 @@ ["midrunGate", "713ce34a4c29b9ea"], ["scratchPlugin", "8ef451bcd3642b7a"], ["frozenPlugin", "3c89007373c202b5"], + ["ownOutput", "d9403784a36412a8"], ["tests.pendingIo", "02f66613e9490d15"] ], "histories": [ @@ -205,6 +206,7 @@ ["midrunGate", "713ce34a4c29b9ea"], ["scratchPlugin", "8ef451bcd3642b7a"], ["frozenPlugin", "3c89007373c202b5"], + ["ownOutput", "d9403784a36412a8"], ["tests.pendingIo", "02f66613e9490d15"] ] } diff --git a/packages/oracles/oracle-gaps/inputs.mjs b/packages/oracles/oracle-gaps/inputs.mjs index af132971..f377d416 100644 --- a/packages/oracles/oracle-gaps/inputs.mjs +++ b/packages/oracles/oracle-gaps/inputs.mjs @@ -55,6 +55,14 @@ const writes = [ [fs, [`writeFileSync`, `writeFile`, `appendFileSync`, `appendFile`]], [fs.promises, [`writeFile`, `appendFile`]], ] +// The calls that copy a file or a tree from their first path to their second. +// The source is read, and the destination is the tree's own output once the +// copy succeeds, as a write's is (`copied`, below). A test that copies a +// fixture into a directory it makes, then has its child read it, is no input. +const copies = [ + [fs, [`copyFileSync`, `cpSync`]], + [fs.promises, [`copyFile`, `cp`]], +] const original = (globalThis.__oracleGapsOriginalFs ??= { readFileSync: fs.readFileSync, statSync: fs.statSync, @@ -202,9 +210,13 @@ const spelledAbsolute = (path) => // `.oracle-gaps` is an input like any other. // The mid-run test marker (`.oracle-gaps-midrun.txt`, one per package) is // the test harness's own file, so it is runner-owned too. +// The runner's own files, which no test reads as an input: its copies, the +// marker of a mid-run check, and Vitest's results cache (rewritten by every +// run of Vitest, with the run's timings, so no run finds the same text). const isRunnerFile = (path) => /\/\.oracle-gaps-\d+[-/]/.test(path) || - path.endsWith(`/.oracle-gaps-midrun.txt`) + path.endsWith(`/.oracle-gaps-midrun.txt`) || + /\/node_modules\/\.vite\/vitest\//.test(path) /** * A wrapper keeps every own property of the function it wraps (its name @@ -295,18 +307,28 @@ export function watchReads(record) { for (const key of keys) record(key, true) } } + // A copy reads its source (the first path) and writes its destination (the + // second), which is marked once the copy has succeeded. + const copied = (source, destination, name) => { + watched(source, `read`, [], name) + return watched(destination, `write`, [], name) + } for (const [calls, kind] of [ [reads, `read`], [stats, `stat`], [metadata, `statx`], [listings, `list`], [writes, `write`], + [copies, `copy`], ]) for (const [owner, names] of calls) for (const name of names) { const call = owner[name] owner[name] = keepProperties(call, function (target, ...rest) { - const mark = watched(target, kind, rest, name) + const mark = + kind === `copy` + ? copied(target, rest[0], name) + : watched(target, kind, rest, name) if (mark === undefined) return call.call(this, target, ...rest) // The mark follows the write's success: a callback without an // error, a promise's resolution, or the sync return. diff --git a/packages/oracles/scripts/e2e-shards.mjs b/packages/oracles/scripts/e2e-shards.mjs index 40832b5d..5cfc3f3e 100644 --- a/packages/oracles/scripts/e2e-shards.mjs +++ b/packages/oracles/scripts/e2e-shards.mjs @@ -256,6 +256,9 @@ export const shards = { `fixed seed 20261105: a failing owner under its parent's config`, `random seed: a package whose parent directory has its config`, `determinism: constructed history: test.projects in a parent's config`, + `fixed seed 20261105: an unchanged check through the daemon while a test made the files it reads: a file its child process makes after the test checks for it`, + `random seed: an unchanged check through the daemon while a test made the files it reads: a file its child process makes after the test checks for it`, + `determinism: constructed history: an unchanged check through the daemon while a test made the files it reads: a file its child process makes after the test checks for it`, ], // 522 s in the measured run, about 221 s idle. 'e2e-3': [ @@ -452,6 +455,9 @@ export const shards = { `fixed seed 20261105: a flaky owner's loop calls under the call budget`, `random seed: a flaky owner's loop calls under the call budget`, `determinism: constructed history: a flaky owner's loop calls under the call budget`, + `fixed seed 20261105: an unchanged check through the daemon while a test made the files it reads: a copy its child process reads, in a directory it removes`, + `random seed: an unchanged check through the daemon while a test made the files it reads: a copy its child process reads, in a directory it removes`, + `determinism: constructed history: an unchanged check through the daemon while a test made the files it reads: a copy its child process reads, in a directory it removes`, ], // 522 s in the measured run, about 221 s idle. 'e2e-5': [ @@ -764,6 +770,9 @@ export const shards = { `random seed: an unregistered soft verdict before a later calibration spin survives the cut`, `determinism: constructed history: a verdict after a clocked count cut's budget throw does not kill`, `determinism: constructed history: an unregistered soft verdict before a later calibration spin survives the cut`, + `fixed seed 20261105: an unchanged check through the daemon while a test made the files it reads: a directory it lists before it writes a file into it`, + `random seed: an unchanged check through the daemon while a test made the files it reads: a directory it lists before it writes a file into it`, + `determinism: constructed history: an unchanged check through the daemon while a test made the files it reads: a directory it lists before it writes a file into it`, ], } diff --git a/packages/oracles/scripts/pr-shards.mjs b/packages/oracles/scripts/pr-shards.mjs index e03773b6..a7a63358 100644 --- a/packages/oracles/scripts/pr-shards.mjs +++ b/packages/oracles/scripts/pr-shards.mjs @@ -102,6 +102,9 @@ const unmeasuredHistories = [ 'an edit to a file a test reads in a worker with strict mode', "an unchanged check through the daemon while a config's plugin writes, stats and removes a scratch file", 'a check through the daemon of a config whose plugin object is frozen', + 'an unchanged check through the daemon while a test made the files it reads: a file its child process makes after the test checks for it', + 'an unchanged check through the daemon while a test made the files it reads: a copy its child process reads, in a directory it removes', + 'an unchanged check through the daemon while a test made the files it reads: a directory it lists before it writes a file into it', ] const unmeasuredPrefix = { 'oracle-gaps-determinism': 'constructed history: ', From f2709e550179fbfb1b51d2b009610d2e740a81b3 Mon Sep 17 00:00:00 2001 From: Kyle Mathews Date: Wed, 2 Dec 2026 13:30:06 -0700 Subject: [PATCH 21/51] test(oracle-gaps): the restart law's mid-run scoping is accepted 2026-12-02 Law 9 now states that the mid-run scoping of the restart rule is accepted 2026-12-02 (coordinator): a mid-run edit restarts the daemon of the check it overlaps, so that check and the one after it are not judged against the rule; the mid-run family judges the edit instead. Text only. Co-authored-by: Isaac --- .../oracle-gaps/gap-report-oracle.property.test.mjs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs b/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs index 19bb15a8..f5d7641f 100644 --- a/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs +++ b/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs @@ -293,9 +293,10 @@ * law judges that only on pairs of consecutive daemon checks that both * reported. Limit: a check that was refused before its session ran is not * judged, so a plugin gate's restart after a refused start (which a - * session of pluginWrite opens) is outside this law. A mid-run edit restarts - * the daemon of the check it overlaps, so that check and the one after it - * are not judged against the rule (the mid-run family judges the edit). + * session of pluginWrite opens) is outside this law. The mid-run scoping is + * accepted 2026-12-02 (coordinator): a mid-run edit restarts the daemon of + * the check it overlaps, so that check and the one after it are not judged + * against the rule; the mid-run family judges the edit instead. * 10. **The runner runs the package as Vitest does.** From any install path * (one with a space and `#` included), for any spelling of `--source` * (`./`, a redundant segment, an absolute path through a symbolic link From d3aa405bf66b53f8b7ab753ec99833d6f002fba1 Mon Sep 17 00:00:00 2001 From: Kyle Mathews Date: Wed, 2 Dec 2026 14:12:04 -0700 Subject: [PATCH 22/51] fix(oracle-gaps): a Vite resolution stat of a test file is a kind read, so an edit keeps the daemon Vite's own plugins stat a path only to learn whether it is a file, as the stat family of inputs.mjs already says. A metadata read by one of them was an input by size and time, so editing a test file restarted the daemon with no tracked input changed (CI restart law, unit "a daemon check with the default output directory, unsupervised", seed 1087925067). Their stats are now kind reads; a config plugin's metadata read is still an input by its metadata. Co-authored-by: Isaac --- packages/oracles/oracle-gaps/check.mjs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/packages/oracles/oracle-gaps/check.mjs b/packages/oracles/oracle-gaps/check.mjs index 539a0d7e..20a9b770 100644 --- a/packages/oracles/oracle-gaps/check.mjs +++ b/packages/oracles/oracle-gaps/check.mjs @@ -314,6 +314,10 @@ function hookPlugin(option, reading, unrecorded) { typeof id === `string` ? `fs:${posix(id.split(`?`)[0])}` : undefined, + // Vite's own plugins stat a path to learn only whether it is a file + // (resolution, as inputs.mjs's stat family says), so their metadata + // reads are kind reads: an edit of the file keeps its kind. + kindOnly: option.name.startsWith(`vite:`), }, () => handler.apply(this, args), ) @@ -602,8 +606,12 @@ export async function openSession(pkg, pause = async () => {}) { const wrote = new Set() const written = new Map() const reading = new AsyncLocalStorage() - watchReads((key, write) => { + watchReads((read, write) => { const at = reading.getStore() + const key = + at?.kindOnly && read.startsWith(`statx:`) + ? `stat:${read.slice(`statx:`.length)}` + : read if (write === true && key.startsWith(`env:`)) wrote.add(key) const reads = at?.hook || at?.done ? hookReads : warmReads if (at === undefined || at.discovery || key === at.module) return From fc60b5401ab975a8d6347da010d6d37b8531145e Mon Sep 17 00:00:00 2001 From: Kyle Mathews Date: Wed, 2 Dec 2026 14:12:09 -0700 Subject: [PATCH 23/51] fix(oracle-gaps): the scratch-plugin config fixture is valid in a CommonJS config The scratch plugin was emitted for CommonJS configs with its ESM helpers and import.meta.url, so the config threw at resolve and the run refused before its config was named. The CommonJS form takes its helpers from require and its path from __dirname, as the CommonJS gate path does. Co-authored-by: Isaac --- .../oracle-gaps/gap-report-model-oracle.mjs | 20 ++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs b/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs index bb245ee6..5f5b143f 100644 --- a/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs +++ b/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs @@ -7724,6 +7724,10 @@ const LOAD_PLUGIN = `{ name: 'gap-own-load', load(id) { const path = id.split('? // The config's own plugin, frozen (`frozenPlugin`): a runner's wrapper cannot be assigned to its hooks (CR-2). const FROZEN_PLUGIN = `{ name: 'gap-frozen', transform(code) { return undefined } }` const SCRATCH_PLUGIN = `{ name: 'gap-scratch', configResolved() { const path = new URL('./gap-scratch.txt', import.meta.url); writeScratch(path, 'scratch\\n'); if (scratchExists(path)) removeScratch(path) } }` +// The same plugin in a CommonJS config, which has no `import.meta`: its file is +// named by `__dirname`, as the CommonJS gate path is (a config that wrote the +// ESM form threw at resolve and refused, the run naming no config). +const SCRATCH_PLUGIN_CJS = `{ name: 'gap-scratch', configResolved() { const path = require('node:url').pathToFileURL(require('node:path').join(__dirname, 'gap-scratch.txt')); writeScratch(path, 'scratch\\n'); if (scratchExists(path)) removeScratch(path) } }` // The config's own plugin that reads the gate file (`inputRead` // `pluginConfig` or `pluginTransform`) and writes its word in place of // `__GAP_INPUT_GATE__` in each test file it transforms. It finds the file @@ -7757,7 +7761,9 @@ function configText(plan, test, configPath = plan.configPath) { const commonjs = plan.configSyntax === `cjs` const plugins = [ ...(plan.prePlugin ? [PRE_PLUGIN] : []), - ...(plan.scratchPlugin ? [SCRATCH_PLUGIN] : []), + ...(plan.scratchPlugin + ? [commonjs ? SCRATCH_PLUGIN_CJS : SCRATCH_PLUGIN] + : []), ...(plan.frozenPlugin ? [`Object.freeze(${FROZEN_PLUGIN})`] : []), ...(plan.loadPlugin ? [LOAD_PLUGIN] : []), ...(pluginGated(plan) || plan.inputRead === `pluginWrite` @@ -7796,10 +7802,14 @@ function configText(plan, test, configPath = plan.configPath) { : [`import { fileURLToPath } from 'node:url'`]), // Only a config in ES module syntax has the load plugin (`loadPluginOf`). ...(plan.loadPlugin ? [`import { readFileSync } from 'node:fs'`] : []), - ...(plan.scratchPlugin && !commonjs - ? [ - `import { writeFileSync as writeScratch, existsSync as scratchExists, unlinkSync as removeScratch } from 'node:fs'`, - ] + ...(plan.scratchPlugin + ? commonjs + ? [ + `const { writeFileSync: writeScratch, existsSync: scratchExists, unlinkSync: removeScratch } = require('node:fs')`, + ] + : [ + `import { writeFileSync as writeScratch, existsSync as scratchExists, unlinkSync as removeScratch } from 'node:fs'`, + ] : []), ...(configGated(plan) ? commonjs From 0be60309bd2c5ec5d148c18bf4e5e285f1f83770 Mon Sep 17 00:00:00 2001 From: Kyle Mathews Date: Wed, 2 Dec 2026 14:45:14 -0700 Subject: [PATCH 24/51] fix(oracle-gaps): Vitest's results caches are the runner's output, not inputs On TanStack DB's packages/db, one unmutated unit (oracle-replay) ran a nested Vitest, which rewrites its results cache each run with the run's timings. The cache was a read of the test's tree before the write, so the unit was not stored and every unchanged recheck computed it again. The runner's own files (isRunnerFile) now also leave out Vitest's results caches, both node_modules/.vite/vitest and node_modules/.vitest-cache. No constructed history reproduces this shape yet (a child that rewrites a file under node_modules/.vitest-cache passes on both the unrepaired and the fixed head), so this rule is covered only by the measured DB run; the constructed history is an open item. Co-authored-by: Isaac --- packages/oracles/oracle-gaps/inputs.mjs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/packages/oracles/oracle-gaps/inputs.mjs b/packages/oracles/oracle-gaps/inputs.mjs index f377d416..2f343ea3 100644 --- a/packages/oracles/oracle-gaps/inputs.mjs +++ b/packages/oracles/oracle-gaps/inputs.mjs @@ -211,12 +211,14 @@ const spelledAbsolute = (path) => // The mid-run test marker (`.oracle-gaps-midrun.txt`, one per package) is // the test harness's own file, so it is runner-owned too. // The runner's own files, which no test reads as an input: its copies, the -// marker of a mid-run check, and Vitest's results cache (rewritten by every -// run of Vitest, with the run's timings, so no run finds the same text). +// marker of a mid-run check, and Vitest's results caches (`.vite/vitest` and +// `.vitest-cache`, rewritten by every run of Vitest with the run's timings, so +// no run finds the same text; a nested run of Vitest writes them too). const isRunnerFile = (path) => /\/\.oracle-gaps-\d+[-/]/.test(path) || path.endsWith(`/.oracle-gaps-midrun.txt`) || - /\/node_modules\/\.vite\/vitest\//.test(path) + /\/node_modules\/\.vite\/vitest\//.test(path) || + /\/node_modules\/\.vitest-cache\//.test(path) /** * A wrapper keeps every own property of the function it wraps (its name From cd44ff9ce386141f6c5e9b69f5237cfe7924ed1a Mon Sep 17 00:00:00 2001 From: Kyle Mathews Date: Wed, 2 Dec 2026 14:49:36 -0700 Subject: [PATCH 25/51] fix(oracle-gaps): a check records a daemon pid only where the restart law judges it; reach is recorded sorted Determinism 14/14 (CI run 46958617422) found two histories whose two runs recorded different traces: - "a declaration fault: configNull": the restart observation of a refused check carried the daemon's pid, which depends on when the previous daemon exits. The restart law judges a pair only when both checks reported, so the observation now follows the same rule: a check whose pair is not judged records no restart value. The law also rejects a recorded pid that no pair judges (RED on the unchanged driver: "recorded its daemon's pid" at start in all three units). - "an edit sequence over the witness module, the first half": the reach states were the same in both runs but inserted in another order (observation 59). Reach is a set, read as one by the framework, so it is recorded sorted. GREEN: configNull (fixed, random, determinism) and the edit-first-half determinism unit pass; restart calibrations and the restart-related units (parent-directory config, default output directory) pass. Co-authored-by: Isaac --- .../gap-report-oracle.property.test.mjs | 33 +++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) diff --git a/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs b/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs index f5d7641f..c1ffceb3 100644 --- a/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs +++ b/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs @@ -3226,6 +3226,15 @@ async function incremental(dir, plan, cli, copy, observe, states) { reported: daemon.reported === true, previousReported: priorDaemon?.reported, } + // The restart observation is recorded only where the restart law judges + // it: this check and its predecessor both reported. A refused check's + // daemon pid depends on when the previous daemon exits, so recording it + // makes the trace nondeterministic (law 9's determinism; S-3(a)). + const restartJudged = + restart !== undefined && + restart.previousPid !== undefined && + restart.reported && + restart.previousReported for (const [i, run] of [daemon, ...others].entries()) { // A daemon's call: the daemon the driver killed during it, if any, or // the one that held its check until the CLI fell back, wrote the lines @@ -3251,7 +3260,7 @@ async function incremental(dir, plan, cli, copy, observe, states) { step: i === 0 ? step : `${step} (a second check at once)`, markerStored, unchangedComputed: i === 0 ? unchangedComputed : laterComputed, - restart: i === 0 ? restart : undefined, + restart: i === 0 && restartJudged ? restart : undefined, midrun: i === 0 && step === `midrun` && midrunChecks ? { @@ -5891,7 +5900,12 @@ async function driver(plan, observe) { observe, states, ) - for (const state of states) observe(`reach`, state) + // Reach is a set (the glossary's `reach`; the framework reads it as one), + // so its order carries no law. The insertion order of two states followed + // the daemon's timing: the two runs of one history recorded the same + // states in another order (CI 46958617422, observation 59, "reused + // evidence" and "edit helper changed the cold result"). Record them sorted. + for (const state of [...states].sort()) observe(`reach`, state) } finally { if (copy) rmSync(copy, { recursive: true, force: true }) rmSync(`${dir}.samples`, { recursive: true, force: true }) @@ -5980,6 +5994,21 @@ function incrementalCheck(observations, expected, plan) { // where the restart rule owes a restart (model: restartOwed). A surviving // restart and a missing one both fail, and so does a restart at an // unchanged recheck. + // A recorded pid that no pair of reported checks judges is a timing value: + // the trace must not carry it (the driver records it only where judged). + if ( + value.restart !== undefined && + !( + value.restart.previousPid !== undefined && + value.restart.reported && + value.restart.previousReported + ) + ) + return violation( + `incremental`, + `the check through the daemon at ${step} recorded its daemon's pid, though it or its predecessor did not report: no law judges that pid, and it depends on timing`, + `restart iff a tracked input changed`, + ) if ( value.restart?.previousPid !== undefined && value.restart.reported && From 843b13419dc0083aed61cbc8327c79901eba75c4 Mon Sep 17 00:00:00 2001 From: Kyle Mathews Date: Wed, 2 Dec 2026 14:51:06 -0700 Subject: [PATCH 26/51] fix(oracle-gaps): narrow the Vitest cache exclusion to the metadata file it read The results-cache exclusion of the previous commit (every file under node_modules/.vitest-cache) made the random-seed history "an edit during a check through the daemon" fail to reach its state "an edit landed during a check through the daemon". The DB unit read only node_modules/.vitest-cache/ _metadata.json, so the exclusion now names that file. The `.vite/vitest` exclusion is unchanged. Co-authored-by: Isaac --- packages/oracles/oracle-gaps/inputs.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/oracles/oracle-gaps/inputs.mjs b/packages/oracles/oracle-gaps/inputs.mjs index 2f343ea3..acfb3fb7 100644 --- a/packages/oracles/oracle-gaps/inputs.mjs +++ b/packages/oracles/oracle-gaps/inputs.mjs @@ -218,7 +218,7 @@ const isRunnerFile = (path) => /\/\.oracle-gaps-\d+[-/]/.test(path) || path.endsWith(`/.oracle-gaps-midrun.txt`) || /\/node_modules\/\.vite\/vitest\//.test(path) || - /\/node_modules\/\.vitest-cache\//.test(path) + /\/node_modules\/\.vitest-cache\/_metadata\.json$/.test(path) /** * A wrapper keeps every own property of the function it wraps (its name From 326a73e18673cf84ae89c221e6c902a788abb0b1 Mon Sep 17 00:00:00 2001 From: Kyle Mathews Date: Wed, 2 Dec 2026 15:25:40 -0700 Subject: [PATCH 27/51] fix(oracle-gaps): a directory a run makes is its own output, from the call's return On TanStack DB's packages/db, the oracle-replay unit stats a temporary directory that its own nested run made (mkdtemp), then removes it. mkdir and mkdtemp were not writes to the watcher, so the stat read the directory as an input that moved when the test removed it, and the unit was not stored: the unchanged recheck computed it again. mkdirSync and mkdtempSync (and fs/promises mkdir and mkdtemp) now mark the path they make, the returned path for mkdtemp, once the call has succeeded. A read of it after that is no input, as a write's is. The listed history gains a stat of the directory the test made before it removes it: RED on the previous head (two seeds, "computed 2 runs that were not cut off"), GREEN here. Co-authored-by: Isaac --- .../oracle-gaps/gap-report-model-oracle.mjs | 3 ++- packages/oracles/oracle-gaps/inputs.mjs | 27 +++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs b/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs index 5f5b143f..8d19f803 100644 --- a/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs +++ b/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs @@ -6934,13 +6934,14 @@ const OWN_OUTPUT_READS = { `ownRemove(ownCopyDirectory, { recursive: true, force: true })`, ], listed: [ - `import { mkdtempSync as ownMake, readdirSync as ownList, rmSync as ownRemove, writeFileSync as ownWrite } from 'node:fs'`, + `import { existsSync as ownExists, mkdtempSync as ownMake, readdirSync as ownList, rmSync as ownRemove, writeFileSync as ownWrite } from 'node:fs'`, `import { tmpdir as ownTmp } from 'node:os'`, `import { join as ownJoin } from 'node:path'`, `const ownListDirectory = ownMake(ownJoin(ownTmp(), 'gap-list-'))`, `if (ownList(ownListDirectory).length !== 0) throw new Error('the new directory held entries')`, `ownWrite(ownJoin(ownListDirectory, 'report.json'), '{}')`, `if (ownList(ownListDirectory).length !== 1) throw new Error('the directory did not hold the report')`, + `if (!ownExists(ownListDirectory)) throw new Error('the directory the test made was gone')`, `ownRemove(ownListDirectory, { recursive: true, force: true })`, ], } diff --git a/packages/oracles/oracle-gaps/inputs.mjs b/packages/oracles/oracle-gaps/inputs.mjs index acfb3fb7..021bc463 100644 --- a/packages/oracles/oracle-gaps/inputs.mjs +++ b/packages/oracles/oracle-gaps/inputs.mjs @@ -63,6 +63,13 @@ const copies = [ [fs, [`copyFileSync`, `cpSync`]], [fs.promises, [`copyFile`, `cp`]], ] +// The calls that make a directory: its path (mkdir) or the one it returns +// (mkdtemp) is the run's own output from the call's success, so a read of it +// after that is no input (a test's temporary directory, removed at the end). +const makes = [ + [fs, [`mkdirSync`, `mkdtempSync`]], + [fs.promises, [`mkdir`, `mkdtemp`]], +] const original = (globalThis.__oracleGapsOriginalFs ??= { readFileSync: fs.readFileSync, statSync: fs.statSync, @@ -352,6 +359,26 @@ export function watchReads(record) { return result }) } + for (const [owner, names] of makes) + for (const name of names) { + const call = owner[name] + const returned = name.startsWith(`mkdtemp`) + const made = (path) => { + if (path === undefined) return + const mark = watched(path, `write`, [], name) + if (mark !== undefined) mark() + } + owner[name] = keepProperties(call, function (target, ...rest) { + const result = call.call(this, target, ...rest) + if (result && typeof result.then === `function`) + return result.then((value) => { + made(returned ? value : target) + return value + }) + made(returned ? result : target) + return result + }) + } syncBuiltinESMExports() // A variable read by name, a test of whether it is set, and a listing of // the names, which reads the set of names. From c11836a35945375872bab70ab499545f26e3899e Mon Sep 17 00:00:00 2001 From: Kyle Mathews Date: Wed, 2 Dec 2026 15:26:32 -0700 Subject: [PATCH 28/51] fix(oracle-gaps): the reset step's daemon is a new process by its own act, so its pid is not judged The restart law judged the pid of the check after a resetBeforeRead step against the pid before it: the step stops the daemon before it reads the request, so the check is served by a new daemon by the step's own act. The exemption set held dieMidCheck, the other paused-check step, but not this one. CI on fc60b540 (run 46973588851) failed "a daemon pause that cannot engage" and "a reset check after its warm daemon was replaced" on this law. RED on cd44ff9c (unchanged): "the check through the daemon at resetBeforeRead was served by a new daemon (pid 2 to 3)" in the daemon pause unit (fixed seed). GREEN: the daemon pause unit passes (fixed, random, determinism). Still failing and not in this commit: the reset unit at corruptStore (pid 2 to 3), see the ledger's Round 14. Co-authored-by: Isaac --- packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs b/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs index c1ffceb3..d61fe8db 100644 --- a/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs +++ b/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs @@ -2339,6 +2339,7 @@ const RESTART_NOT_JUDGED = new Set([ `reusedPid`, `stopAtOnce`, `dieMidCheck`, + `resetBeforeRead`, ]) // The note a CLI writes when its daemon sent nothing within its bound and the // check runs cold instead (R39: a cold fallback names its cause). From db16e3678e52e41599ae022264d70376df192321 Mon Sep 17 00:00:00 2001 From: Kyle Mathews Date: Wed, 2 Dec 2026 16:03:57 -0700 Subject: [PATCH 29/51] fix(oracle-gaps): the restart law judges no pair across a daemon the protocol replaced The restart law judged the pid of every check against the check before it. Its daemon is replaced by design in several protocol events, so those pairs are not input changes: a check held past the CLI's bound (the CLI falls back cold and the driver stops or abandons the daemon), a daemon that stopped answering, a slow start, and a check after a step that ended its daemon after the check ran (dieMidCheck, resetBeforeRead, stopAtOnce, midrun). The law now judges a pair only when both reported, the earlier check's step does not end its daemon, neither check fell back to a cold run, and the pair's pids are defined (model: restartJudged). The driver records a restart only where restartJudged judges it, and the law rejects a recorded pid that no pair judges. RESTART_NOT_JUDGED moves into the model. A start is no end: the daemon it makes serves the next check, so the pair after a start is still judged. corruptStore (fixed seed reset unit): the pid change was the CLI's protocol, not the store. resetBeforeRead's kill ended the daemon after its check; the CLI started a fresh one for corruptStore, and the store overwrite did not end it (daemon trace: no exit, no uncaught error during the step). RED on cherry-picked head (before this commit): 10 of 14 units in the daemon-family set failed on the restart law. GREEN after: 13 of 14 pass (random reset included). Still failing: fixed seed brokenVitest at inputGate, a separate question (its session never tracks the plugin gate file). Restart calibrations and scratch, default-output and pluginConfig units: GREEN. Co-authored-by: Isaac --- .../oracle-gaps/gap-report-model-oracle.mjs | 45 +++++++++ .../gap-report-oracle.property.test.mjs | 98 ++++++++++--------- 2 files changed, 99 insertions(+), 44 deletions(-) diff --git a/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs b/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs index 8d19f803..5e45ed16 100644 --- a/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs +++ b/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs @@ -6979,6 +6979,51 @@ export const restartOwed = (plan, check, previous) => (PLUGIN_INPUT_READS.has(plan.inputRead) && check.inputOpen !== previous.inputOpen) +// The steps after which a check's daemon is a new process by the step's own +// act (a start, a kill, a stop, a reset, a mid-run edit): the restart law +// does not judge that check's pid. Every other step's pid is judged. +export const RESTART_NOT_JUDGED = new Set([ + `start`, + `restart`, + `crash`, + `crashAtOnce`, + `reboot`, + `reusedPid`, + `stopAtOnce`, + `dieMidCheck`, + `resetBeforeRead`, +]) +// The steps that end the daemon which ran their check, after the check ran (a +// kill or a stop of the held or reset daemon, a mid-run edit's restart): the +// pair that starts after one of them is not judged. +const ENDS_DAEMON_AFTER = new Set([ + `dieMidCheck`, + `resetBeforeRead`, + `stopAtOnce`, + `midrun`, +]) +/** + * Whether the restart law judges the pid of `check` against the pid of the + * check before it (`previous`, undefined when none has a pid). The law's rule + * (law 9): it judges a pair of consecutive daemon checks only when both + * reported, neither check's step ends or replaces its daemon by its own act + * (RESTART_NOT_JUDGED, ENDS_DAEMON_AFTER), and the CLI's daemon protocol did + * not replace the daemon between them: neither check fell back to a cold run + * (`fellBack`: its daemon held it past the CLI's bound, or sent nothing, so + * the CLI started a fresh daemon or ran cold; a start past the bound is one + * such check). A start is no end: the daemon it makes serves the next check. + */ +export const restartJudged = (step, previousStep, check, previous) => + previous !== undefined && + previous.pid !== undefined && + !RESTART_NOT_JUDGED.has(step) && + step !== `midrun` && + !ENDS_DAEMON_AFTER.has(previousStep) && + check.reported && + previous.reported && + !check.fellBack && + !previous.fellBack + function oracleTestFile(plan, file) { const sites = sitesOf(plan) const entries = [ diff --git a/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs b/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs index d61fe8db..f692bd83 100644 --- a/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs +++ b/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs @@ -1,3 +1,4 @@ +import { appendFileSync as __appendFileSync } from 'node:fs' /** * # What does the gap report owe the oracle author? * @@ -290,9 +291,14 @@ * The daemon that serves a check is the one that served the check before * it, unless an environment variable, the CLI's code, or a plugin gate * file changed in between (the restart rule, G34: model restartOwed). The - * law judges that only on pairs of consecutive daemon checks that both - * reported. Limit: a check that was refused before its session ran is not - * judged, so a plugin gate's restart after a refused start (which a + * law judges a pair of consecutive daemon checks only when both reported, + * neither check's step ends its daemon by its own act (a stop, kill or + * reset after the check, a start, a restart, a crash, a mid-run edit), and + * the CLI's daemon protocol did not replace the daemon between them: no + * cold fallback in either check (a start past the bound, a daemon that + * stopped answering, a held reply, a daemon that sent nothing; model + * restartJudged). Limit: a check that was refused before its session ran + * is not judged, so a plugin gate's restart after a refused start (which a * session of pluginWrite opens) is outside this law. The mid-run scoping is * accepted 2026-12-02 (coordinator): a mid-run edit restarts the daemon of * the check it overlaps, so that check and the one after it are not judged @@ -731,6 +737,8 @@ import { inputEnv, outsideOf, PLUGIN_INPUT_READS, + RESTART_NOT_JUDGED, + restartJudged, restartOwed, } from './gap-report-model-oracle.mjs' @@ -2327,20 +2335,6 @@ function namedScratch(text, names) { ) } -// The steps after which a check's daemon is a new process by the step's own -// act (a start, a kill, a stop), so its pid is not judged against the last -// one (the restart observable, G34). Every other step's pid is judged. -const RESTART_NOT_JUDGED = new Set([ - `start`, - `restart`, - `crash`, - `crashAtOnce`, - `reboot`, - `reusedPid`, - `stopAtOnce`, - `dieMidCheck`, - `resetBeforeRead`, -]) // The note a CLI writes when its daemon sent nothing within its bound and the // check runs cold instead (R39: a cold fallback names its cause). const coldFallbackNote = @@ -3195,12 +3189,12 @@ async function incremental(dir, plan, cli, copy, observe, states) { // A mid-run edit restarts the daemon of the check it overlaps (midrun), and the // check after it is not judged against the one before: the mid-run family // judges that restart (law 9's limit). - const priorDaemon = - RESTART_NOT_JUDGED.has(step) || - step === `midrun` || - previousStep === `midrun` - ? undefined - : lastDaemon + const priorDaemon = lastDaemon + // Whether the CLI's protocol ran this check cold, after its daemon held it + // or sent nothing (heldPhase, slowOpen, a cold fallback, R39). + const fellBack = + daemon.held === true || + daemon.stream.notes.some((note) => coldFallbackNote.test(note)) lastDaemon = daemon.checkPid === undefined ? undefined @@ -3210,12 +3204,15 @@ async function incremental(dir, plan, cli, copy, observe, states) { cliCode, inputOpen: state.inputOpen, reported: daemon.reported === true, + fellBack, + step, } const restart = daemon.checkPid === undefined ? undefined : { step, + previousStep, pid: ordinalOf(daemon.checkPid), previousPid: priorDaemon?.pid, env: how.env, @@ -3226,16 +3223,25 @@ async function incremental(dir, plan, cli, copy, observe, states) { previousInputOpen: priorDaemon?.inputOpen, reported: daemon.reported === true, previousReported: priorDaemon?.reported, + fellBack, + previousFellBack: priorDaemon?.fellBack, } // The restart observation is recorded only where the restart law judges - // it: this check and its predecessor both reported. A refused check's - // daemon pid depends on when the previous daemon exits, so recording it - // makes the trace nondeterministic (law 9's determinism; S-3(a)). - const restartJudged = + // it (model: restartJudged): a refused check's daemon pid depends on when + // the previous daemon exits, and a held check's on the CLI's fallback, so + // recording either would make the trace nondeterministic (law 9; S-3(a)). + __appendFileSync( + '/tmp/gap-pr/bv-trace.log', + `CHECK step=${step} prev=${previousStep} fault=${plan.fault} checkPid=${daemon.checkPid} reported=${daemon.reported} held=${daemon.held} refusal=${daemon.refusal !== undefined} exit=${daemon.exit} prevPid=${lastDaemon?.pid} notes=${JSON.stringify(daemon.stream?.notes?.slice(0, 2)?.map((n) => String(n).slice(0, 70)))} inputOpen=${state.inputOpen} steps=${plan.steps?.join(',')}\n`, + ) + const judged = restart !== undefined && - restart.previousPid !== undefined && - restart.reported && - restart.previousReported + restartJudged( + step, + previousStep, + { reported: restart.reported, fellBack }, + priorDaemon, + ) for (const [i, run] of [daemon, ...others].entries()) { // A daemon's call: the daemon the driver killed during it, if any, or // the one that held its check until the CLI fell back, wrote the lines @@ -3261,7 +3267,7 @@ async function incremental(dir, plan, cli, copy, observe, states) { step: i === 0 ? step : `${step} (a second check at once)`, markerStored, unchangedComputed: i === 0 ? unchangedComputed : laterComputed, - restart: i === 0 && restartJudged ? restart : undefined, + restart: i === 0 && judged ? restart : undefined, midrun: i === 0 && step === `midrun` && midrunChecks ? { @@ -3377,9 +3383,7 @@ async function incremental(dir, plan, cli, copy, observe, states) { // A daemon restart on a changed plugin input (G34): the check whose plugin // gate file changed was served by a new daemon. if ( - restart?.previousPid !== undefined && - restart.reported && - restart.previousReported && + judged && restart.pid !== restart.previousPid && PLUGIN_INPUT_READS.has(plan.inputRead) && restart.inputOpen !== restart.previousInputOpen @@ -5999,22 +6003,28 @@ function incrementalCheck(observations, expected, plan) { // the trace must not carry it (the driver records it only where judged). if ( value.restart !== undefined && - !( - value.restart.previousPid !== undefined && - value.restart.reported && - value.restart.previousReported + !restartJudged( + value.restart.step, + value.restart.previousStep, + { + reported: value.restart.reported, + fellBack: value.restart.fellBack, + }, + value.restart.previousPid === undefined + ? undefined + : { + pid: value.restart.previousPid, + reported: value.restart.previousReported, + fellBack: value.restart.previousFellBack, + }, ) ) return violation( `incremental`, - `the check through the daemon at ${step} recorded its daemon's pid, though it or its predecessor did not report: no law judges that pid, and it depends on timing`, + `the check through the daemon at ${step} recorded its daemon's pid, though no pair judges it (a fault, a held or cold-fallback check, or a check that did not report): the pid depends on timing`, `restart iff a tracked input changed`, ) - if ( - value.restart?.previousPid !== undefined && - value.restart.reported && - value.restart.previousReported - ) { + if (value.restart !== undefined) { const { restart: r } = value const owed = restartOwed( plan, From 92933b6a588de1261e14cd33ee88489536a88ddd Mon Sep 17 00:00:00 2001 From: Kyle Mathews Date: Wed, 2 Dec 2026 19:14:33 -0700 Subject: [PATCH 30/51] docs(oracle-gaps): the own-output rule is accepted, with its limit (2026-12-02, maintainer) Law 9's text, the check header, and the README's daemon section record the maintainer's decision of 2026-12-02: a path the run's own process tree created or copied, which it read as absent, is no input; a directory the run added entries to is no input; mkdir and mkdtemp count as writes. The limit: a later run that finds a leftover of an earlier run at such a path reuses the stored run, so a test whose outcome depends on that leftover is not hermetic. Co-authored-by: Isaac --- README.md | 7 ++++++ packages/oracles/oracle-gaps/check.mjs | 17 +++++++------- .../gap-report-oracle.property.test.mjs | 22 ++++++++++--------- 3 files changed, 28 insertions(+), 18 deletions(-) diff --git a/README.md b/README.md index 2d9e6673..6fb5af28 100644 --- a/README.md +++ b/README.md @@ -297,6 +297,13 @@ runs cold` and runs the check in its own process, which reports what the reused. A directory that a test stats or tests for is an input as a directory, not by its content. + A path that a run's own process tree created or copied, which the run read + as absent, is no input, and a directory the run added entries to is no input; + mkdir and mkdtemp count as writes (accepted 2026-12-02, maintainer). Limit, + accepted 2026-12-02 (maintainer): a later run that finds a leftover of an + earlier run at such a path reuses the stored run, so a test whose outcome + depends on that leftover is not hermetic. + The CLI sends its environment with each request, so it sends it only to a daemon socket that this user owns; a socket another user made in the shared temporary directory is refused, and no request goes to it. On diff --git a/packages/oracles/oracle-gaps/check.mjs b/packages/oracles/oracle-gaps/check.mjs index 20a9b770..61494be4 100644 --- a/packages/oracles/oracle-gaps/check.mjs +++ b/packages/oracles/oracle-gaps/check.mjs @@ -23,14 +23,15 @@ // watches, a read from a child process that a test starts with an environment // that drops NODE_OPTIONS (#143), and a new file that changes how an unchanged // import resolves. A worker thread a test starts is covered (capture-setup.mjs). -// Own output (law 9, round 13, 2026-12-02, pending the maintainer's acceptance -// of this limit): a path that the run's own process tree created or copied, -// which the run read as absent, is no input, and neither is a directory the -// run made entries in (inputs.mjs, capture-setup.mjs, settleIn). A path the run -// read present and then changed is an input that moved, so its run is not -// stored. Limit: a later run that finds a leftover of an earlier run at such a -// path reuses the stored run as if the path were absent or unlisted, so a test -// whose outcome depends on that leftover is not hermetic, and not covered. +// Own output (law 9, round 13, accepted 2026-12-02 (maintainer)): a path that +// the run's own process tree created or copied, which the run read as absent, +// is not an input, and a directory the run added entries to is not an input; +// mkdir and mkdtemp count as writes (inputs.mjs, capture-setup.mjs, settleIn). +// A path the run read present and then changed is an input that moved, so its +// run is not stored. Limit, accepted 2026-12-02 (maintainer): a later run that +// finds a leftover of an earlier run at such a path reuses the stored run as if +// the path were absent or unlisted, so a test whose outcome depends on that +// leftover is not hermetic, and not covered. // Vitest's own results cache is the runner's output (inputs.mjs isRunnerFile). // Node's own reads of the package.json files that a require consults (main, // type) are covered by a wrapper on Module._resolveFilename in the copy diff --git a/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs b/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs index f692bd83..a6bf5d9b 100644 --- a/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs +++ b/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs @@ -553,16 +553,18 @@ import { appendFileSync as __appendFileSync } from 'node:fs' * than the seed and the gate's, a new file that changes how an * unchanged import resolves, a change to the Vite config or the installed * packages, or checks at once other than the two that start the daemon. - * Own output (law 9, round 13, 2026-12-02; the maintainer has not yet accepted - * this limit): a file a run's own process tree creates or copies, which the run - * reads as absent, and a directory the run makes entries in, are the run's own - * output, no input of it (the constructed histories `ownOutput`: a test whose - * child makes the file it checks for, a copy its child reads, a listing before a - * write). A file the run reads present and then changes is an input that moved, - * so its run is not stored (a file the test rewrites with different content each - * run). The limit: a later run that finds a leftover of an earlier run at such a - * path reuses the stored run as if the path were absent or unlisted, so a test - * whose outcome depends on its own leftover is not hermetic, and is not covered. + * Own output (law 9, round 13, 2026-12-02; accepted 2026-12-02 (maintainer)): + * a file a run's own process tree creates or copies, which the run reads as + * absent, and a directory the run makes entries in, are the run's own output, + * no input of it (the constructed histories `ownOutput`: a test whose child + * makes the file it checks for, a copy its child reads, a listing before a + * write). mkdir and mkdtemp count as writes. A file the run reads present and + * then changes is an input that moved, so its run is not stored (a file the + * test rewrites with different content each run). The limit, accepted + * 2026-12-02 (maintainer): a later run that finds a leftover of an earlier run + * at such a path reuses the stored run as if the path were absent or unlisted, + * so a test whose outcome depends on its own leftover is not hermetic, and is + * not covered. * The harness keeps every global a copy defines configurable, by wrapping * `Object.defineProperty`, `Object.defineProperties`, and * `Reflect.defineProperty`, so that each copy in the shared realm starts From b65773b614d896bfde8dce1e2129a18c5c0eac6b Mon Sep 17 00:00:00 2001 From: Kyle Mathews Date: Wed, 2 Dec 2026 20:50:01 -0700 Subject: [PATCH 31/51] fix(oracle-gaps): a pluginWrite gate's warm leaves the file open, so a hand edit it wrote back restarts nothing The restart rule owed a restart at a hand edit of a pluginWrite gate file whenever the edit's state differed from the previous check's state. But the config's plugin writes that file as open at every warm of the session, so a daemon that warmed in the previous check had left it open. The daemon's session compares the file's text with what it wrote (check.mjs, written, inputsChanged), so an edit to open is no change of the session's input, and the kept daemon equals a cold run. The driver now records the gate text a check leaves (open where its daemon warmed), and law 9 states the rule. Co-authored-by: Isaac --- .../oracle-gaps/gap-report-model-oracle.mjs | 6 +++++ .../gap-report-oracle.property.test.mjs | 25 ++++++++++++++++--- 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs b/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs index 5e45ed16..138fb490 100644 --- a/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs +++ b/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs @@ -6972,6 +6972,12 @@ export const PLUGIN_INPUT_READS = new Set([ // e2e oracle judges each pair of consecutive daemon checks that both reported // (check.pid) against this rule; a refused check's session is not judged // (law 9's limit). +// For `pluginWrite` the gate file is the file the config's plugin writes at each +// warm of the session (as `open`), so the `inputOpen` of a previous check is the +// text that check left: `open` where its daemon warmed, else the hand edit's +// state (the driver records it so). The daemon's session (check.mjs, `written`, +// inputsChanged) compares the file's text with what it wrote, so a hand edit +// that the next warm wrote back is no change of the session's input. const envOf = (env) => JSON.stringify(Object.entries(env ?? {}).sort()) export const restartOwed = (plan, check, previous) => envOf(check.env) !== envOf(previous.env) || diff --git a/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs b/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs index a6bf5d9b..21544eb3 100644 --- a/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs +++ b/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs @@ -290,8 +290,14 @@ import { appendFileSync as __appendFileSync } from 'node:fs' * through the daemon names its own report in its done line. * The daemon that serves a check is the one that served the check before * it, unless an environment variable, the CLI's code, or a plugin gate - * file changed in between (the restart rule, G34: model restartOwed). The - * law judges a pair of consecutive daemon checks only when both reported, + * file changed in between (the restart rule, G34: model restartOwed). A + * pluginWrite gate file is the file the config's plugin writes as `open` at + * each warm of the session, so a check whose daemon warmed leaves it open, + * and a hand edit that the next warm wrote back (or one that sets it to the + * text it already holds) changes no tracked input: the daemon is kept, and + * its check equals a cold run's (round 17, 2026-12-02; the probe in + * check.mjs `inputsChanged` shows the session holds the rewritten text). + * The law judges a pair of consecutive daemon checks only when both reported, * neither check's step ends its daemon by its own act (a stop, kill or * reset after the check, a start, a restart, a crash, a mid-run edit), and * the CLI's daemon protocol did not replace the daemon between them: no @@ -3197,6 +3203,19 @@ async function incremental(dir, plan, cli, copy, observe, states) { const fellBack = daemon.held === true || daemon.stream.notes.some((note) => coldFallbackNote.test(note)) + // The gate text that this check leaves for the next one (`inputOpen`). A + // pluginWrite gate is a file the config's plugin writes in configResolved, + // as `open` (gatePlugin), at every warm of the session: a daemon that + // warmed in this check (a start, or a new process id) leaves the file open, + // whatever the hand edit made, so the next check compares with `open`, not + // with the hand edit's state (law 9; the restart rule's pluginWrite limit). + // Any other check leaves the text the hand edit made. + const warmedHere = + daemon.checkPid !== undefined && + (priorDaemon === undefined || + ordinalOf(daemon.checkPid) !== priorDaemon.pid) + const leftOpen = + plan.inputRead === `pluginWrite` && warmedHere ? true : state.inputOpen lastDaemon = daemon.checkPid === undefined ? undefined @@ -3204,7 +3223,7 @@ async function incremental(dir, plan, cli, copy, observe, states) { pid: ordinalOf(daemon.checkPid), env: how.env, cliCode, - inputOpen: state.inputOpen, + inputOpen: leftOpen, reported: daemon.reported === true, fellBack, step, From a10189e64b95f28fff8e862d919f1c1287a613b1 Mon Sep 17 00:00:00 2001 From: Kyle Mathews Date: Wed, 2 Dec 2026 20:52:28 -0700 Subject: [PATCH 32/51] fix(oracle-gaps): a child's stat or listing of a path its tree wrote is own output A child process's read was judged against the write log under its raw key, so a child's existsSync (stat:) or listing (dir:) of a directory it had just made was recorded as an input. The run then removed the directory, the input moved, and the unit was not stored. foldChildren and ownOutput now share ownKeyOf, which maps stat, statx, dir, and dirs to the path's write key. Law 9's own-output sentence now matches the code (accepted 2026-12-02, maintainer): a path the run's tree wrote, created or copied before the read, is no input, whatever the read saw. Constructed history ownOutput childStat: a child makes a directory, checks it, and passes its name back; the test checks it (present) and removes it. - RED on 92933b6a: 2 of 2 fail (fixed and random seed). - GREEN with this change: 3 of 3 (fixed, random, determinism). - Hostile mutant (fold after judgment: no foldChildren at the read or in ownOutput): 2 of 2 fail. - Family run (own-output, mid-run, child, gate and plugin filters), 129 tests: 124 pass, 5 fail, all pre-existing on 92933b6a (same failures, checked): two mid-run calibrations ("a mid-run edit did not reach flips a mutant of the editing file", "... reached reports another file's mutant as neither cold run did"; logs /tmp/gap-pr/db2-midrun-head.log); two plugin hand-edit histories ("a hand edit of a file the config's plugin writes", fixed and random seed; logs /tmp/gap-pr/db2-plugin-head.log); and the random-seed "a file its child process makes after the test checks for it" at seed -1547090748 path 0:5 (replays /tmp/gap-pr/db2-rp-head-child.log). - Shards: e2e 5 shards exact, pr 7 partitions exact (the new names added). - tsc --noEmit and eslint on changed files: pass. The fingerprint canary's recorded ownOutput hash moves to 7fec7ca2c6124a4a (approved 2026-12-02 by the maintainer). Co-authored-by: Isaac --- README.md | 13 +++++----- .../oracles/oracle-gaps/capture-setup.mjs | 11 ++++++-- packages/oracles/oracle-gaps/check.mjs | 16 ++++++------ .../oracle-gaps/gap-report-model-oracle.mjs | 17 +++++++++++- .../gap-report-oracle.property.test.mjs | 26 +++++++++++-------- .../oracle-gaps/history-fingerprint.json | 4 +-- packages/oracles/scripts/e2e-shards.mjs | 3 +++ packages/oracles/scripts/pr-shards.mjs | 1 + 8 files changed, 61 insertions(+), 30 deletions(-) diff --git a/README.md b/README.md index 6fb5af28..ab97f1f6 100644 --- a/README.md +++ b/README.md @@ -297,12 +297,13 @@ runs cold` and runs the check in its own process, which reports what the reused. A directory that a test stats or tests for is an input as a directory, not by its content. - A path that a run's own process tree created or copied, which the run read - as absent, is no input, and a directory the run added entries to is no input; - mkdir and mkdtemp count as writes (accepted 2026-12-02, maintainer). Limit, - accepted 2026-12-02 (maintainer): a later run that finds a leftover of an - earlier run at such a path reuses the stored run, so a test whose outcome - depends on that leftover is not hermetic. + A path that a run's own process tree wrote, created or copied before the + read, is no input, and a directory the run added entries to is no input; + mkdir and mkdtemp count as writes (accepted 2026-12-02, maintainer). A path + the run read present and then changed, which the tree did not write first, + is an input that moved. Limit, accepted 2026-12-02 (maintainer): a later run + that finds a leftover of an earlier run at such a path reuses the stored run, + so a test whose outcome depends on that leftover is not hermetic. The CLI sends its environment with each request, so it sends it only to a daemon socket that this user owns; a socket another user made in the diff --git a/packages/oracles/oracle-gaps/capture-setup.mjs b/packages/oracles/oracle-gaps/capture-setup.mjs index cee0db75..841254ad 100644 --- a/packages/oracles/oracle-gaps/capture-setup.mjs +++ b/packages/oracles/oracle-gaps/capture-setup.mjs @@ -311,7 +311,9 @@ function foldChildren() { if (line === ``) continue const [op, key, hash] = JSON.parse(line) if (op === `W`) wrote.add(key) - else if (!wrote.has(key) && !reads.has(key)) reads.set(key, hash) + // A child's stat or listing of a path the tree wrote before it is the + // tree's own output too: its key names the file, as ownOutput maps it. + else if (!wrote.has(ownKeyOf(key)) && !reads.has(key)) reads.set(key, hash) } childRead += Buffer.byteLength(text.slice(0, end + 1)) } @@ -321,7 +323,12 @@ function foldChildren() { */ function ownOutput(key) { foldChildren() - return wrote.has(key.replace(/^(stat|statx):/, `fs:`)) + return wrote.has(ownKeyOf(key)) +} +// The write log's key for a read's key: a stat, metadata, or listing of a path +// names the path, which the log keys as `fs:` (the tree's writes and makes). +function ownKeyOf(key) { + return key.replace(/^(stat|statx|dirs?):/, `fs:`) } // Rule: an append to the run's own capture rows or test-output.log reads // nothing first, since the runner created that file for this run, so its diff --git a/packages/oracles/oracle-gaps/check.mjs b/packages/oracles/oracle-gaps/check.mjs index 61494be4..85f67323 100644 --- a/packages/oracles/oracle-gaps/check.mjs +++ b/packages/oracles/oracle-gaps/check.mjs @@ -24,14 +24,14 @@ // that drops NODE_OPTIONS (#143), and a new file that changes how an unchanged // import resolves. A worker thread a test starts is covered (capture-setup.mjs). // Own output (law 9, round 13, accepted 2026-12-02 (maintainer)): a path that -// the run's own process tree created or copied, which the run read as absent, -// is not an input, and a directory the run added entries to is not an input; -// mkdir and mkdtemp count as writes (inputs.mjs, capture-setup.mjs, settleIn). -// A path the run read present and then changed is an input that moved, so its -// run is not stored. Limit, accepted 2026-12-02 (maintainer): a later run that -// finds a leftover of an earlier run at such a path reuses the stored run as if -// the path were absent or unlisted, so a test whose outcome depends on that -// leftover is not hermetic, and not covered. +// the run's own process tree wrote, created or copied before the read, is not +// an input, and a directory the run added entries to is not an input; mkdir +// and mkdtemp count as writes (inputs.mjs, capture-setup.mjs, settleIn). A path +// the run read present and then changed, which the tree did not write first, is +// an input that moved, so its run is not stored. Limit, accepted 2026-12-02 +// (maintainer): a later run that finds a leftover of an earlier run at such a +// path reuses the stored run, so a test whose outcome depends on that leftover +// is not hermetic, and not covered. // Vitest's own results cache is the runner's output (inputs.mjs isRunnerFile). // Node's own reads of the package.json files that a require consults (main, // type) are covered by a wrapper on Module._resolveFilename in the copy diff --git a/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs b/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs index 138fb490..177874b1 100644 --- a/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs +++ b/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs @@ -1537,7 +1537,8 @@ const drawn = fc.record({ // Drawn last (CR-2): the config's plugin object is frozen, so the runner cannot wrap its hooks (`frozenPlugin`). frozenPlugin: fc.constantFrom(false, false, false, false, true), // File b's own output (OWN_OUTPUT_READS): drawn last, so the draws above keep - // their values for every seed. Most histories run without it. + // their values for every seed. Most histories run without it. The arbitrary + // takes every shape, so a constructed history of one can shrink. ownOutput: fc.constantFrom( `none`, `none`, @@ -1550,6 +1551,7 @@ const drawn = fc.record({ `created`, `copied`, `listed`, + `childStat`, ), }) @@ -6909,6 +6911,7 @@ const childWriteRead = [ // copy, and the test removes the directory), and `listed` (the test lists a // new directory, writes a file into it, and lists it again). Each is a // read of a path that the run itself changes before the check ends. +const CHILD_OWN_STAT = `const fs = require('node:fs'), os = require('node:os'), path = require('node:path'); const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gap-own-stat-')); if (!fs.existsSync(dir)) throw new Error('the child saw no directory it made'); process.stdout.write(dir)` const OWN_OUTPUT_READS = { created: [ `import { execFileSync as ownRun } from 'node:child_process'`, @@ -6944,6 +6947,18 @@ const OWN_OUTPUT_READS = { `if (!ownExists(ownListDirectory)) throw new Error('the directory the test made was gone')`, `ownRemove(ownListDirectory, { recursive: true, force: true })`, ], + // The child process makes the directory and checks it (existsSync, a stat in + // the child) and passes its name back; the test then checks it too (present, + // made by its tree before the check) and removes it. Both reads are of the + // tree's own output, which the run must not record (check.mjs, foldChildren + // and ownOutput): recorded, the directory's removal would move an input. + childStat: [ + `import { execFileSync as ownRun } from 'node:child_process'`, + `import { existsSync as ownExists, rmSync as ownRemove } from 'node:fs'`, + `const ownStatDirectory = ownRun(process.execPath, ['-e', ${JSON.stringify(CHILD_OWN_STAT)}], { encoding: 'utf8' })`, + `if (!ownExists(ownStatDirectory)) throw new Error('the test saw no directory its child made')`, + `ownRemove(ownStatDirectory, { recursive: true, force: true })`, + ], } /** The variables a check of `state` runs with: the gate's, under `env`. */ const inputEnv = (plan, state) => diff --git a/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs b/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs index 21544eb3..6c955ceb 100644 --- a/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs +++ b/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs @@ -560,17 +560,17 @@ import { appendFileSync as __appendFileSync } from 'node:fs' * unchanged import resolves, a change to the Vite config or the installed * packages, or checks at once other than the two that start the daemon. * Own output (law 9, round 13, 2026-12-02; accepted 2026-12-02 (maintainer)): - * a file a run's own process tree creates or copies, which the run reads as - * absent, and a directory the run makes entries in, are the run's own output, - * no input of it (the constructed histories `ownOutput`: a test whose child - * makes the file it checks for, a copy its child reads, a listing before a - * write). mkdir and mkdtemp count as writes. A file the run reads present and - * then changes is an input that moved, so its run is not stored (a file the - * test rewrites with different content each run). The limit, accepted - * 2026-12-02 (maintainer): a later run that finds a leftover of an earlier run - * at such a path reuses the stored run as if the path were absent or unlisted, - * so a test whose outcome depends on its own leftover is not hermetic, and is - * not covered. + * a path the run's own process tree wrote, created or copied before the read, + * is not an input, and a directory the run added entries to is not an input; + * mkdir and mkdtemp count as writes (the constructed histories `ownOutput`: a + * test whose child makes the file it checks for, a copy its child reads, a + * listing before a write, a directory its child makes, checks, and removes). A + * path the run reads present and then changes, which the tree did not write + * first, is an input that moved, so its run is not stored (a file the test + * rewrites with different content each run). The limit, accepted 2026-12-02 + * (maintainer): a later run that finds a leftover of an earlier run at such a + * path reuses the stored run, so a test whose outcome depends on its own + * leftover is not hermetic, and is not covered. * The harness keeps every global a copy defines configurable, by wrapping * `Object.defineProperty`, `Object.defineProperties`, and * `Reflect.defineProperty`, so that each copy in the shared realm starts @@ -16439,6 +16439,10 @@ oracleProperty({ ], [`copied`, `a copy its child process reads, in a directory it removes`], [`listed`, `a directory it lists before it writes a file into it`], + [ + `childStat`, + `a directory its child process makes, checks for, and removes`, + ], ].map(([ownOutput, shape]) => ({ name: `an unchanged check through the daemon while a test made the files it reads: ${shape}`, enters: [ diff --git a/packages/oracles/oracle-gaps/history-fingerprint.json b/packages/oracles/oracle-gaps/history-fingerprint.json index 0628bf5f..d60481c0 100644 --- a/packages/oracles/oracle-gaps/history-fingerprint.json +++ b/packages/oracles/oracle-gaps/history-fingerprint.json @@ -101,7 +101,7 @@ ["midrunGate", "713ce34a4c29b9ea"], ["scratchPlugin", "8ef451bcd3642b7a"], ["frozenPlugin", "3c89007373c202b5"], - ["ownOutput", "d9403784a36412a8"], + ["ownOutput", "7fec7ca2c6124a4a"], ["tests.pendingIo", "02f66613e9490d15"] ], "histories": [ @@ -206,7 +206,7 @@ ["midrunGate", "713ce34a4c29b9ea"], ["scratchPlugin", "8ef451bcd3642b7a"], ["frozenPlugin", "3c89007373c202b5"], - ["ownOutput", "d9403784a36412a8"], + ["ownOutput", "7fec7ca2c6124a4a"], ["tests.pendingIo", "02f66613e9490d15"] ] } diff --git a/packages/oracles/scripts/e2e-shards.mjs b/packages/oracles/scripts/e2e-shards.mjs index 5cfc3f3e..b2e9fa8d 100644 --- a/packages/oracles/scripts/e2e-shards.mjs +++ b/packages/oracles/scripts/e2e-shards.mjs @@ -773,6 +773,9 @@ export const shards = { `fixed seed 20261105: an unchanged check through the daemon while a test made the files it reads: a directory it lists before it writes a file into it`, `random seed: an unchanged check through the daemon while a test made the files it reads: a directory it lists before it writes a file into it`, `determinism: constructed history: an unchanged check through the daemon while a test made the files it reads: a directory it lists before it writes a file into it`, + `fixed seed 20261105: an unchanged check through the daemon while a test made the files it reads: a directory its child process makes, checks for, and removes`, + `random seed: an unchanged check through the daemon while a test made the files it reads: a directory its child process makes, checks for, and removes`, + `determinism: constructed history: an unchanged check through the daemon while a test made the files it reads: a directory its child process makes, checks for, and removes`, ], } diff --git a/packages/oracles/scripts/pr-shards.mjs b/packages/oracles/scripts/pr-shards.mjs index a7a63358..72efee46 100644 --- a/packages/oracles/scripts/pr-shards.mjs +++ b/packages/oracles/scripts/pr-shards.mjs @@ -105,6 +105,7 @@ const unmeasuredHistories = [ 'an unchanged check through the daemon while a test made the files it reads: a file its child process makes after the test checks for it', 'an unchanged check through the daemon while a test made the files it reads: a copy its child process reads, in a directory it removes', 'an unchanged check through the daemon while a test made the files it reads: a directory it lists before it writes a file into it', + 'an unchanged check through the daemon while a test made the files it reads: a directory its child process makes, checks for, and removes', ] const unmeasuredPrefix = { 'oracle-gaps-determinism': 'constructed history: ', From 6f8c47c636782c641fc7a959b67569f13c0caf13 Mon Sep 17 00:00:00 2001 From: Kyle Mathews Date: Thu, 3 Dec 2026 08:25:07 -0700 Subject: [PATCH 33/51] fix(oracle-gaps): a check that edits no gate starts on the text the last warm left A pluginWrite gate's warm rewrites the file as open. The restart record used the model state, so a recheck after a hand edit that the warm had written back compared `shut` with the previous check's `open` and owed a restart the daemon (correctly) did not take. A check now starts on the text on disk: the edit's state where the step edits the gate, else the text the previous check left. Co-authored-by: Isaac --- .../gap-report-oracle.property.test.mjs | 23 +++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs b/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs index 6d492b5b..9ad5548c 100644 --- a/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs +++ b/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs @@ -3060,6 +3060,10 @@ async function incremental(dir, plan, cli, copy, observe, states) { let lastFiles let lastStep let lastDaemon + // The gate text the last check wrote (`gateSeen`), and the text on disk after + // it (`gateOnDisk`): a pluginWrite warm rewrites the file as open (law 9). + let gateSeen = true + let gateOnDisk = true const daemonOrdinals = new Map() const ordinalOf = (pid) => { if (!daemonOrdinals.has(pid)) @@ -3226,8 +3230,23 @@ async function incremental(dir, plan, cli, copy, observe, states) { daemon.checkPid !== undefined && (priorDaemon === undefined || ordinalOf(daemon.checkPid) !== priorDaemon.pid) + // The text the check starts on: a step that edits the gate (its state + // differs from the state the last check wrote) starts on the edit's state; + // any other step starts on the text the previous check left on disk, which + // a warm of the plugin rewrote as `open` (the restart law compares it). + const writesGate = state.inputOpen !== gateSeen + const startOpen = + plan.inputRead === `pluginWrite` && !writesGate + ? gateOnDisk + : state.inputOpen const leftOpen = - plan.inputRead === `pluginWrite` && warmedHere ? true : state.inputOpen + plan.inputRead === `pluginWrite` + ? warmedHere + ? true + : startOpen + : state.inputOpen + gateSeen = state.inputOpen + gateOnDisk = leftOpen lastDaemon = daemon.checkPid === undefined ? undefined @@ -3252,7 +3271,7 @@ async function incremental(dir, plan, cli, copy, observe, states) { previousEnv: priorDaemon?.env, cliCode, previousCode: priorDaemon?.cliCode, - inputOpen: state.inputOpen, + inputOpen: startOpen, previousInputOpen: priorDaemon?.inputOpen, reported: daemon.reported === true, previousReported: priorDaemon?.reported, From 17940ca916936bdf5ba3881507384c89488e3ada Mon Sep 17 00:00:00 2001 From: Kyle Mathews Date: Thu, 3 Dec 2026 08:27:38 -0700 Subject: [PATCH 34/51] test(oracle-gaps): the restart trace writes no file, so the tree holds no path of this machine The CHECK trace appended to /tmp/gap-pr/bv-trace.log on every check, which fails on any machine without that directory. A local probe can re-add it. Co-authored-by: Isaac --- .../oracles/oracle-gaps/gap-report-oracle.property.test.mjs | 5 ----- 1 file changed, 5 deletions(-) diff --git a/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs b/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs index 9ad5548c..9410db09 100644 --- a/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs +++ b/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs @@ -1,4 +1,3 @@ -import { appendFileSync as __appendFileSync } from 'node:fs' /** * # What does the gap report owe the oracle author? * @@ -3282,10 +3281,6 @@ async function incremental(dir, plan, cli, copy, observe, states) { // it (model: restartJudged): a refused check's daemon pid depends on when // the previous daemon exits, and a held check's on the CLI's fallback, so // recording either would make the trace nondeterministic (law 9; S-3(a)). - __appendFileSync( - '/tmp/gap-pr/bv-trace.log', - `CHECK step=${step} prev=${previousStep} fault=${plan.fault} checkPid=${daemon.checkPid} reported=${daemon.reported} held=${daemon.held} refusal=${daemon.refusal !== undefined} exit=${daemon.exit} prevPid=${lastDaemon?.pid} notes=${JSON.stringify(daemon.stream?.notes?.slice(0, 2)?.map((n) => String(n).slice(0, 70)))} inputOpen=${state.inputOpen} steps=${plan.steps?.join(',')}\n`, - ) const judged = restart !== undefined && restartJudged( From f594771ff03d9b32c845057926a3fb77c4801c29 Mon Sep 17 00:00:00 2001 From: Kyle Mathews Date: Thu, 3 Dec 2026 08:46:13 -0700 Subject: [PATCH 35/51] test(bug-search): restore main's non-null assertions that the merge commit's lint fix removed The merge commit f6c31809 brought main's bug-search tests into the branch as staged files, and the pre-commit hook's `eslint --fix` ran over them in a worktree where @tanstack/oracles was not built, so the typed lint read the framework's types as `any`, judged three non-null assertions unnecessary and removed them. `pnpm --filter bug-search typecheck` then failed on CI (TS2345: 'BugH | undefined', 'string | undefined') while main passes. The two files are main's again, byte for byte; with the package built, the same hook keeps them. Co-authored-by: Isaac --- .../tests/oracle/bench-snapshot.oracle.property.test.ts | 2 +- .../tests/oracle/prefix-score.oracle.property.test.ts | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/bug-search/tests/oracle/bench-snapshot.oracle.property.test.ts b/packages/bug-search/tests/oracle/bench-snapshot.oracle.property.test.ts index 1c252147..8cfd8818 100644 --- a/packages/bug-search/tests/oracle/bench-snapshot.oracle.property.test.ts +++ b/packages/bug-search/tests/oracle/bench-snapshot.oracle.property.test.ts @@ -761,7 +761,7 @@ oracleProperty({ ? got.error === null : expected.seal ? got.error !== null && got.error.includes(`${NAME}: the seal of`) - : namesLimit(got.error, expected.failing, expected.limit), + : namesLimit(got.error, expected.failing!, expected.limit!), } return ( differs(`outcome`, `setup`, actual, { diff --git a/packages/bug-search/tests/oracle/prefix-score.oracle.property.test.ts b/packages/bug-search/tests/oracle/prefix-score.oracle.property.test.ts index ff4d7694..0e66525b 100644 --- a/packages/bug-search/tests/oracle/prefix-score.oracle.property.test.ts +++ b/packages/bug-search/tests/oracle/prefix-score.oracle.property.test.ts @@ -982,7 +982,7 @@ oracleProperty({ law: `caught`, history: { constructed: `more flips than the judge sees` }, corrupt: (trace, plan) => { - const every = flipsOf(plan.bugs[0]).map((k, i) => ({ + const every = flipsOf(plan.bugs[0]!).map((k, i) => ({ bug: `B0`, key: k, ...valuesOf(i), @@ -998,7 +998,7 @@ oracleProperty({ law: `caught`, history: { constructed: `more flips than the judge sees` }, corrupt: (trace, plan) => { - const six = flipsOf(plan.bugs[0]) + const six = flipsOf(plan.bugs[0]!) .slice(0, 6) .map((k, i) => ({ bug: `B0`, key: k, ...valuesOf(i) })) return trace.map((o) => From 361d9d553b4d2e4dbcef0bdea837829690839c48 Mon Sep 17 00:00:00 2001 From: Kyle Mathews Date: Thu, 3 Dec 2026 09:11:22 -0700 Subject: [PATCH 36/51] fix(oracle-gaps): a leading directive keeps the eval worker strict, and a numeric open flag that keeps bytes reads first - CR-24: the preload of an eval worker went after 'use strict' only; a 'custom' directive before it let the preload turn strict mode off. The prologue match now takes every leading string-literal statement. - CR-21: a numeric open flag without O_TRUNC (fs.constants.O_RDWR) was stringified, so it never recorded the pre-read that the string flag r+ records. The write now reads the prior text when the flag keeps bytes. - CR-1: the changeset's opening sentence claimed every read is tracked; it now claims each tracked read and points to the listed untracked reads. Witnesses: tests/gap-eval-worker-prologue.test.ts (RED 'custom' directive false with the old pattern, GREEN true) and tests/gap-inputs-numeric-flag.test.ts (RED 'append' missing with the numeric branch off, GREEN with it). Targeted histories: append, rplus, wxExisting and the worker-thread family pass (30 and 15 of their units). Co-authored-by: Isaac --- .changeset/gap-cli-daemon-every-read.md | 2 +- packages/oracles/oracle-gaps/inputs.mjs | 17 ++++--- .../tests/gap-eval-worker-prologue.test.ts | 34 +++++++++++++ .../tests/gap-inputs-numeric-flag.test.ts | 49 +++++++++++++++++++ 4 files changed, 95 insertions(+), 7 deletions(-) create mode 100644 packages/oracles/tests/gap-eval-worker-prologue.test.ts create mode 100644 packages/oracles/tests/gap-inputs-numeric-flag.test.ts diff --git a/.changeset/gap-cli-daemon-every-read.md b/.changeset/gap-cli-daemon-every-read.md index 0caf912c..1f33e998 100644 --- a/.changeset/gap-cli-daemon-every-read.md +++ b/.changeset/gap-cli-daemon-every-read.md @@ -2,7 +2,7 @@ '@tanstack/oracles': patch --- -A check through `--daemon` now treats every read as an input of the runs that made it, so after any of these changes it reports what a cold run reports. Before, the daemon reused a run that read the old input. The new inputs are a file that a test reads through `fs` outside the package or under `node_modules`, or through `createReadStream`; a directory that a test lists (`readdir`, `opendir`, and their sync and `fs/promises` forms), by its entries; an environment variable that a test reads (or the set of variable names, when a test lists them); and a file or variable that Vitest, Vite, or the config reads in the CLI's process, while it loads or in a hook of any plugin, Vite's own included, such as the `tsconfig.json` that Vite's esbuild plugin reads or a sidecar file that a plugin writes into the code it transforms. +A check through `--daemon` now treats each tracked read as an input of the runs that made it, so after any change to a tracked input it reports what a cold run reports. Reads that stay untracked are listed below. Before, the daemon reused a run that read the old input. The new inputs are a file that a test reads through `fs` outside the package or under `node_modules`, or through `createReadStream`; a directory that a test lists (`readdir`, `opendir`, and their sync and `fs/promises` forms), by its entries; an environment variable that a test reads (or the set of variable names, when a test lists them); and a file or variable that Vitest, Vite, or the config reads in the CLI's process, while it loads or in a hook of any plugin, Vite's own included, such as the `tsconfig.json` that Vite's esbuild plugin reads or a sidecar file that a plugin writes into the code it transforms. The daemon now runs each check in the environment of the CLI that asked for it. A check from another environment, or after a file that Vitest, the config, or a plugin read or wrote has changed, starts a new daemon. Because Vitest and Vite read every environment variable while they start, any change to the environment runs every unit again, as a cold run does. diff --git a/packages/oracles/oracle-gaps/inputs.mjs b/packages/oracles/oracle-gaps/inputs.mjs index 021bc463..f35e3aff 100644 --- a/packages/oracles/oracle-gaps/inputs.mjs +++ b/packages/oracles/oracle-gaps/inputs.mjs @@ -264,16 +264,20 @@ export function watchReads(record) { const options = kind === `list` ? args[0] : args[1] // A write that keeps the bytes it does not overwrite reads them first: // an append (a call named `append...`, or the flag `a`), and a - // read-write open without truncation (the flag `r+`, CR-21). Its read is + // read-write open without truncation (the flag `r+`, CR-21; a numeric + // flag without O_TRUNC, such as fs.constants.O_RDWR, CR-21). Its read is // an input unless the copy wrote the file first (133-3), so it records // `append` (a read) before the call, and `true` (the write) after it. const flag = typeof options === `object` && options !== null - ? String(options.flag ?? `w`) + ? (options.flag ?? `w`) : `w` const keeps = write && - (/append/i.test(name) || flag.startsWith(`a`) || flag.startsWith(`r`)) + (/append/i.test(name) || + (typeof flag === `number` + ? (flag & fs.constants.O_TRUNC) === 0 + : /^[ar]/.test(String(flag)))) let path try { // A path keeps the spelling it was given: the kernel resolves `..` @@ -407,13 +411,14 @@ export function watchReads(record) { } // The code of an eval worker with the preload first (CR-24). The preload goes -// after the directive prologue (`'use strict'`), which must stay the first +// after the directive prologue (every leading string-literal statement, such +// as `'use strict'`, and `'custom'` before it), which must stay the first // statements of the code, or the worker's strictness changes. const preloadedCode = (code, preload) => { - // Leading space and comments, then `'use strict'` statements, each ended by + // Leading space and comments, then string-literal statements, each ended by // `;` or a line end (so `'use strict'.length` is not a directive). const prologue = - /^(?:\s|\/\/[^\n]*\n|\/\*[\s\S]*?\*\/)*(?:(['"])use strict\1(?:[ \t]*;|[ \t]*(?=\n))\s*)*/.exec( + /^(?:\s|\/\/[^\n]*\n|\/\*[\s\S]*?\*\/)*(?:(['"])(?:[^'"\\\n]|\\.)*\1(?:[ \t]*;|[ \t]*(?=\n))\s*)*/.exec( code, )[0] return `${prologue};require(${JSON.stringify(preload)});\n${code.slice(prologue.length)}` diff --git a/packages/oracles/tests/gap-eval-worker-prologue.test.ts b/packages/oracles/tests/gap-eval-worker-prologue.test.ts new file mode 100644 index 00000000..8204afd2 --- /dev/null +++ b/packages/oracles/tests/gap-eval-worker-prologue.test.ts @@ -0,0 +1,34 @@ +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { createRequire } from 'node:module' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { describe, expect, test } from 'vitest' +import { patchWorkerThreads } from '../oracle-gaps/inputs.mjs' + +// An eval worker's code gets the child-writes preload ahead of it. The preload +// must go after the whole directive prologue: a `'custom'` directive before +// `'use strict'` must not let the preload turn strict mode off (CR-24). +const require = createRequire(import.meta.url) + +describe(`the preload of an eval worker`, () => { + test(`keeps every leading directive first, so the worker stays strict`, async () => { + const dir = mkdtempSync(join(tmpdir(), `gap-prologue-`)) + try { + const preload = join(dir, `preload.mjs`) + writeFileSync(preload, `// an empty preload\n`) + patchWorkerThreads(preload) + const { Worker } = require(`node:worker_threads`) + const probe = `require('node:worker_threads').parentPort.postMessage((function () { return this === undefined })())` + const run = (code: string) => + new Promise((resolve, reject) => { + const worker = new Worker(code, { eval: true }) + worker.on(`message`, resolve) + worker.on(`error`, reject) + }) + expect(await run(`'use strict'; ${probe}`)).toBe(true) + expect(await run(`'custom'; 'use strict'; ${probe}`)).toBe(true) + } finally { + rmSync(dir, { recursive: true, force: true }) + } + }) +}) diff --git a/packages/oracles/tests/gap-inputs-numeric-flag.test.ts b/packages/oracles/tests/gap-inputs-numeric-flag.test.ts new file mode 100644 index 00000000..d767fbfc --- /dev/null +++ b/packages/oracles/tests/gap-inputs-numeric-flag.test.ts @@ -0,0 +1,49 @@ +import { execFileSync } from 'node:child_process' +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { describe, expect, test } from 'vitest' + +// A write with a numeric open flag that keeps the bytes it does not overwrite +// (fs.constants.O_RDWR, no O_TRUNC) is a read-write open, as the string flag +// `r+` is: the write must record a read of the prior text before it, or a +// later read of the file misses the bytes the write kept (CR-21). A flag with +// O_TRUNC replaces the file, so it records no such read. The watcher is +// installed in a child process, so this test's own fs calls are not wrapped. +const script = ` +import { mkdtempSync, writeFileSync, constants } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +const { watchReads } = await import(process.argv[2]) +const seen = [] +watchReads((key, write) => seen.push(write ?? 'read')) +const dir = mkdtempSync(join(tmpdir(), 'numeric-flag-')) +const fixture = join(dir, 'fixture.txt') +writeFileSync(fixture, 'AB') +seen.length = 0 +writeFileSync(fixture, 'X', { flag: constants.O_RDWR }) +const keeps = seen.slice() +seen.length = 0 +writeFileSync(fixture, 'Y', { flag: constants.O_WRONLY | constants.O_TRUNC }) +console.log(JSON.stringify({ keeps, replaces: seen.slice() })) +` + +describe(`a write with a numeric open flag`, () => { + test(`reads the prior text only when the flag keeps the bytes it does not write`, () => { + const dir = mkdtempSync(join(tmpdir(), `gap-numeric-flag-`)) + try { + const file = join(dir, `run.mjs`) + writeFileSync(file, script) + const inputs = new URL(`../oracle-gaps/inputs.mjs`, import.meta.url).href + const out = execFileSync(process.execPath, [file, inputs], { + encoding: `utf8`, + }) + const { keeps, replaces } = JSON.parse(out.trim().split(`\n`).pop()!) + expect(keeps[0]).toBe(`append`) + expect(keeps.at(-1)).toBe(true) + expect(replaces).not.toContain(`append`) + } finally { + rmSync(dir, { recursive: true, force: true }) + } + }) +}) From 13c20e9d402633283e69f91aa6f87817dbbd7474 Mon Sep 17 00:00:00 2001 From: Kyle Mathews Date: Thu, 3 Dec 2026 09:36:50 -0700 Subject: [PATCH 37/51] test(oracle-gaps): the numeric-flag unit opens with flag combinations Node maps from r+ and w The Windows unit suite failed on 361d9d55 with EINVAL from the bare numeric flag writes in tests/gap-inputs-numeric-flag.test.ts. The keep case now uses O_RDWR | O_CREAT (the open r+ maps to on an existing file) and the replace case O_WRONLY | O_CREAT | O_TRUNC (the open w maps to). The law is unchanged: a numeric flag without O_TRUNC records the pre-read. RED: with the numeric branch of inputs.mjs disabled, the unit fails (expected true to be 'append'); GREEN on the restored code. Co-authored-by: Isaac --- .../tests/gap-inputs-numeric-flag.test.ts | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/packages/oracles/tests/gap-inputs-numeric-flag.test.ts b/packages/oracles/tests/gap-inputs-numeric-flag.test.ts index d767fbfc..84229f5c 100644 --- a/packages/oracles/tests/gap-inputs-numeric-flag.test.ts +++ b/packages/oracles/tests/gap-inputs-numeric-flag.test.ts @@ -5,11 +5,14 @@ import { join } from 'node:path' import { describe, expect, test } from 'vitest' // A write with a numeric open flag that keeps the bytes it does not overwrite -// (fs.constants.O_RDWR, no O_TRUNC) is a read-write open, as the string flag -// `r+` is: the write must record a read of the prior text before it, or a -// later read of the file misses the bytes the write kept (CR-21). A flag with -// O_TRUNC replaces the file, so it records no such read. The watcher is -// installed in a child process, so this test's own fs calls are not wrapped. +// (fs.constants.O_RDWR | O_CREAT, no O_TRUNC) is a read-write open, as the +// string flag `r+` is: the write must record a read of the prior text before +// it, or a later read of the file misses the bytes the write kept (CR-21). A +// flag with O_TRUNC replaces the file, so it records no such read. The flags +// are the combinations Node's string flags map to (`r+`, `w`), so the test does +// not depend on how libuv maps a bare numeric flag on each platform (the +// Windows unit suite failed with EINVAL on one of the bare forms). The watcher +// is installed in a child process, so this test's own fs calls are not wrapped. const script = ` import { mkdtempSync, writeFileSync, constants } from 'node:fs' import { tmpdir } from 'node:os' @@ -21,10 +24,10 @@ const dir = mkdtempSync(join(tmpdir(), 'numeric-flag-')) const fixture = join(dir, 'fixture.txt') writeFileSync(fixture, 'AB') seen.length = 0 -writeFileSync(fixture, 'X', { flag: constants.O_RDWR }) +writeFileSync(fixture, 'X', { flag: constants.O_RDWR | constants.O_CREAT }) const keeps = seen.slice() seen.length = 0 -writeFileSync(fixture, 'Y', { flag: constants.O_WRONLY | constants.O_TRUNC }) +writeFileSync(fixture, 'Y', { flag: constants.O_WRONLY | constants.O_CREAT | constants.O_TRUNC }) console.log(JSON.stringify({ keeps, replaces: seen.slice() })) ` From aaadc840bb06f0e9ae92c53acfce33d839ab9ba7 Mon Sep 17 00:00:00 2001 From: Kyle Mathews Date: Thu, 3 Dec 2026 10:14:36 -0700 Subject: [PATCH 38/51] test(oracle-gaps): the held-check violation names the refusal its CLI exited with The cold-fallback law's held-check message gave only the exit code, so the CI failures of the held-check family (a check abandoned while a context warms, and a check whose daemon stops answering: the CLI exited 2 where the cold run exited 0) could not name the refusal. The message now carries the run's refusal (or its first stderr line). The law is unchanged. This is diagnostic only: the family does not reproduce locally or on Arca (3 of 3 runs of each history under parallel load, and the fixed-seed shard 5 on a 4-core pinned run, all GREEN). Co-authored-by: Isaac --- .../oracles/oracle-gaps/gap-report-oracle.property.test.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs b/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs index 9410db09..8b5d9687 100644 --- a/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs +++ b/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs @@ -6155,7 +6155,7 @@ function incrementalCheck(observations, expected, plan) { if (daemon.held && daemon.exit !== cold.exit) return violation( `incremental`, - `after ${step}, the daemon held the check and the CLI did not fall back to a cold check: it exited ${daemon.exit}${daemon.exit > 128 ? ` when the driver's backstop stopped it` : ``}, and the cold run exited ${cold.exit}`, + `after ${step}, the daemon held the check and the CLI did not fall back to a cold check: it exited ${daemon.exit}${daemon.exit > 128 ? ` when the driver's backstop stopped it` : ``} (${daemon.refusal ?? daemon.stderr ?? `no refusal`}), and the cold run exited ${cold.exit}`, `cold fallback`, ) if (daemon.rewritten.length > 0) From 100e19e781c143560450b80ba3ada005878fe0bf Mon Sep 17 00:00:00 2001 From: Kyle Mathews Date: Thu, 3 Dec 2026 11:39:44 -0700 Subject: [PATCH 39/51] test(oracle-gaps): a check at once records the environment its CLI sent, so a daemon it started restarts for the next check The two checks at once of "an edit sequence through the daemon" start the daemon with ORACLE_GAPS_TEST_HOLD_OVERLAP. The daemon keeps the environment of the CLI that started it (daemon.mjs, ownEnv), so the helper check, sent without that variable, was served by a new daemon. The law's model recorded the plan's environment for those checks instead, so it judged no restart owed. The model now records the environment the CLIs sent (the hold's for checks at once), and law 9's text says why a daemon restarts. RED: the unrepaired model fails the history at helper, "served by a new daemon (pid 1 to 2), though no tracked input changed". GREEN: the history passes. Mutant: daemon.mjs without the environment check keeps the daemon, and the history fails, "kept the daemon that served its previous check (pid 1), though a tracked input changed". Co-authored-by: Isaac --- .../gap-report-oracle.property.test.mjs | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs b/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs index 8b5d9687..539e9f2d 100644 --- a/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs +++ b/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs @@ -289,7 +289,12 @@ * through the daemon names its own report in its done line. * The daemon that serves a check is the one that served the check before * it, unless an environment variable, the CLI's code, or a plugin gate - * file changed in between (the restart rule, G34: model restartOwed). A + * file changed in between (the restart rule, G34: model restartOwed). The + * environment is the one each CLI sent, and a daemon keeps the environment + * of the CLI that started it: two checks at once that start it with the + * test-only hold variable (ORACLE_GAPS_TEST_HOLD_OVERLAP), so a check from + * a CLI without it restarts the daemon (daemon.mjs, envKey of the request + * against the daemon's own). A * pluginWrite gate file is the file the config's plugin writes as `open` at * each warm of the session, so a check whose daemon warmed leaves it open, * and a hand edit that the next warm wrote back (or one that sets it to the @@ -3166,6 +3171,10 @@ async function incremental(dir, plan, cli, copy, observe, states) { const hold = overlapMark ? { env: { ORACLE_GAPS_TEST_HOLD_OVERLAP: overlapMark } } : {} + // The environment each of the checks at once sends: the hold's, which + // replaces the plan's (`...hold` above). The daemon they start keeps it, so + // the next check from another environment restarts the daemon (law 9). + const sentEnv = twice ? (hold.env ?? how.env) : how.env const [daemon, ...others] = twice ? ( await runClisAtOnce(dir, files, [ @@ -3251,7 +3260,7 @@ async function incremental(dir, plan, cli, copy, observe, states) { ? undefined : { pid: ordinalOf(daemon.checkPid), - env: how.env, + env: sentEnv, cliCode, inputOpen: leftOpen, reported: daemon.reported === true, @@ -3266,7 +3275,7 @@ async function incremental(dir, plan, cli, copy, observe, states) { previousStep, pid: ordinalOf(daemon.checkPid), previousPid: priorDaemon?.pid, - env: how.env, + env: sentEnv, previousEnv: priorDaemon?.env, cliCode, previousCode: priorDaemon?.cliCode, From 3a3d54b158d60ddec32e9eccebbdd2a74aa21435 Mon Sep 17 00:00:00 2001 From: Kyle Mathews Date: Thu, 3 Dec 2026 11:41:19 -0700 Subject: [PATCH 40/51] fix(oracle-gaps): a Vitest that fails to load names where it resolved, and whether that is a real path The held histories' CI failure says the package's Vitest failed to load ("Cannot find package '@vitest/utils' imported from .../node_modules/vitest/ dist/node.js") on the fallback's cold check, and that path is not a real path. The refusal now also names the resolved path, whether it is the real path, NODE_OPTIONS, and the process's execArgv, so the next CI failure of this family shows which layout the fallback had. No behaviour changes otherwise; the mechanism is not yet reproduced locally or on CI. Co-authored-by: Isaac --- packages/oracles/oracle-gaps/check.mjs | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/packages/oracles/oracle-gaps/check.mjs b/packages/oracles/oracle-gaps/check.mjs index 85f67323..b72559cc 100644 --- a/packages/oracles/oracle-gaps/check.mjs +++ b/packages/oracles/oracle-gaps/check.mjs @@ -661,13 +661,24 @@ export async function openSession(pkg, pause = async () => {}) { pluginHooks(plugins, reading, unrecorded) const requireTarget = createRequire(join(pkg, `package.json`)) let createVitest + let resolved try { + resolved = requireTarget.resolve(`vitest/node`) ;({ createVitest } = await warming( - () => import(pathToFileURL(requireTarget.resolve(`vitest/node`)).href), + () => import(pathToFileURL(resolved).href), )) } catch (error) { + // Where Vitest resolved and whether that is a real path (a symbolic link's + // target is what ESM imports from), named so a failure on another machine + // says which layout it had (the CI failure of the held histories). + const layout = + resolved === undefined + ? `resolved nothing` + : realPathOf(resolved) === posix(resolved) + ? `resolved ${resolved}, a real path` + : `resolved ${resolved}, not its real path ${realPathOf(resolved)}` throw new Refusal( - `the package's Vitest failed to load: ${error?.message ?? error}`, + `the package's Vitest failed to load: ${error?.message ?? error} (${layout}; NODE_OPTIONS ${JSON.stringify(process.env.NODE_OPTIONS ?? null)}; execArgv ${JSON.stringify(process.execArgv)})`, `Install a working Vitest in the package, so that vitest/node loads from it.`, ) } From d1df42abe8937a118c3e84d3dcbfe93e85357377 Mon Sep 17 00:00:00 2001 From: Kyle Mathews Date: Thu, 3 Dec 2026 12:02:22 -0700 Subject: [PATCH 41/51] test(oracle-gaps): a classification violation names a crash's error, and a restart records the hold mark by its order A crash's violation now carries the error its first failing test threw, so the next Windows failure of a crashed mutant names the crash. A restart's recorded environment names the hold's mark by the order it first appeared in the history, not by its fresh directory's path, so two runs of one history record the same trace (the determinism law). Co-authored-by: Isaac --- .../gap-report-oracle.property.test.mjs | 42 +++++++++++++++++-- 1 file changed, 39 insertions(+), 3 deletions(-) diff --git a/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs b/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs index 539e9f2d..e07720a4 100644 --- a/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs +++ b/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs @@ -2872,6 +2872,9 @@ function readRunIn(dir, out, status, stderr, cli, stdout, derived) { laws: r.laws, // The cut that ended a timeout (classify.mjs `outcomeOf`). cause: r.outcome === `timeout` ? r.detail : undefined, + // The error that a crash's first failing test threw (classify.mjs + // `outcomeOf`), so a classification violation names the crash. + crash: r.outcome === `crashed` ? r.detail : undefined, // The built-in law of a kill that a cut by count or state decided // (bounded work or no progress), null for a behavioral law. builtIn: @@ -3053,6 +3056,26 @@ async function incremental(dir, plan, cli, copy, observe, states) { markDirs.push(marks) return marks } + // The hold's mark is a fresh directory in every run, so a restart's recorded + // environment names it by the order it first appeared in this history, which + // is the same in each run of it (the determinism law). Its path is not an + // observation. + const holdMarks = new Map() + const markOrdinal = (path) => { + if (!holdMarks.has(path)) holdMarks.set(path, holdMarks.size + 1) + return holdMarks.get(path) + } + const recordedEnv = (env) => + env === undefined + ? undefined + : Object.fromEntries( + Object.entries(env).map(([name, value]) => [ + name, + name === `ORACLE_GAPS_TEST_HOLD_OVERLAP` + ? `hold mark ${markOrdinal(value)}` + : value, + ]), + ) // How many runs the daemon computed in a check of a state that nothing // changed, where it owes none (undefined elsewhere). let unchangedComputed @@ -3275,8 +3298,8 @@ async function incremental(dir, plan, cli, copy, observe, states) { previousStep, pid: ordinalOf(daemon.checkPid), previousPid: priorDaemon?.pid, - env: sentEnv, - previousEnv: priorDaemon?.env, + env: recordedEnv(sentEnv), + previousEnv: recordedEnv(priorDaemon?.env), cliCode, previousCode: priorDaemon?.cliCode, inputOpen: startOpen, @@ -6595,7 +6618,7 @@ function check(plan, observations, expected) { if (kind !== owed.kind) return violation( `cli`, - `${site(got)}: ${kind}, owed ${owed.kind}`, + `${site(got)}: ${kind}, owed ${owed.kind}${got.crash === undefined ? `` : `; the crash threw ${JSON.stringify(got.crash)}`}`, owed.kind === `unowned` || kind === `unowned` ? `ownership` : `classification`, @@ -7610,6 +7633,19 @@ const calibrations = [ }, ), }, + { + // The violation names the error of the crash it reports (its `crash`). + name: `a kill is reported as a crash, and names the error`, + law: `classification`, + difference: `the crash threw "calibration error"`, + corrupt: firstWhere( + (m) => !m.probe && m.outcome === `killed`, + (m) => { + m.outcome = `crashed` + m.crash = `calibration error` + }, + ), + }, { name: `an owned mutant is reported as unowned`, law: `ownership`, From e91c0d6b0d37c1d9bcd61e873586cf8ad735908b Mon Sep 17 00:00:00 2001 From: Kyle Mathews Date: Thu, 3 Dec 2026 12:12:51 -0700 Subject: [PATCH 42/51] fix(oracle-gaps): a Vitest load refusal names its layout on its first line The held check's refusal is read from the CLI's first refused line, so the layout that 3a3d54b1 added after the error text was lost whenever the error text had a line break: CI's held histories (fixed seed 4/9, 7/9, 8/9, 9/9, random 13/13) named the error and nothing of the layout. The layout now comes before the text, and the text's line breaks are flattened. Co-authored-by: Isaac --- packages/oracles/oracle-gaps/check.mjs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/packages/oracles/oracle-gaps/check.mjs b/packages/oracles/oracle-gaps/check.mjs index b72559cc..87d552ae 100644 --- a/packages/oracles/oracle-gaps/check.mjs +++ b/packages/oracles/oracle-gaps/check.mjs @@ -677,8 +677,11 @@ export async function openSession(pkg, pause = async () => {}) { : realPathOf(resolved) === posix(resolved) ? `resolved ${resolved}, a real path` : `resolved ${resolved}, not its real path ${realPathOf(resolved)}` + // The layout comes before the error's text, and the text's line breaks are + // flattened: the refusal's first line is the one a driver reads (the CI + // failure of the held histories, 3a3d54b1 showed no layout at all). throw new Refusal( - `the package's Vitest failed to load: ${error?.message ?? error} (${layout}; NODE_OPTIONS ${JSON.stringify(process.env.NODE_OPTIONS ?? null)}; execArgv ${JSON.stringify(process.execArgv)})`, + `the package's Vitest failed to load (${layout}; NODE_OPTIONS ${JSON.stringify(process.env.NODE_OPTIONS ?? null)}; execArgv ${JSON.stringify(process.execArgv)}): ${String(error?.message ?? error).replaceAll(`\n`, ` / `)}`, `Install a working Vitest in the package, so that vitest/node loads from it.`, ) } From 6a0d1a1dfd42860de0c142a32da43edf54b1f7c5 Mon Sep 17 00:00:00 2001 From: Kyle Mathews Date: Thu, 3 Dec 2026 12:43:52 -0700 Subject: [PATCH 43/51] test(oracle-gaps): the kill-reported-as-crash calibration is in an e2e shard Co-authored-by: Isaac --- packages/oracles/scripts/e2e-shards.mjs | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/oracles/scripts/e2e-shards.mjs b/packages/oracles/scripts/e2e-shards.mjs index f058ff77..e84d302e 100644 --- a/packages/oracles/scripts/e2e-shards.mjs +++ b/packages/oracles/scripts/e2e-shards.mjs @@ -242,6 +242,7 @@ export const shards = { `random seed: a config fault in a run that owns nothing`, `random seed: a declaration fault: apiLessTypescript`, `calibration: a crash is reported as a kill`, + `calibration: a kill is reported as a crash, and names the error`, `calibration: a daemon is left after --stop-daemon`, `calibration: a refused run is reported as complete`, `determinism: constructed history: a .cjs config that calls require`, From 5db6b8ed4cddcefdef0f13d2236c0b5fcb26136e Mon Sep 17 00:00:00 2001 From: Kyle Mathews Date: Thu, 3 Dec 2026 13:06:47 -0700 Subject: [PATCH 44/51] fix(oracle-gaps): the daemon's log names each restart, each declined request, and each kept check's inputs Co-authored-by: Isaac --- packages/oracles/oracle-gaps/check.mjs | 24 +++++-- packages/oracles/oracle-gaps/daemon.mjs | 87 +++++++++++++++++++++---- 2 files changed, 94 insertions(+), 17 deletions(-) diff --git a/packages/oracles/oracle-gaps/check.mjs b/packages/oracles/oracle-gaps/check.mjs index 87d552ae..4cadf38c 100644 --- a/packages/oracles/oracle-gaps/check.mjs +++ b/packages/oracles/oracle-gaps/check.mjs @@ -3540,11 +3540,25 @@ export default async (env) => { * daemon then serves no more checks, since a plugin or a module may keep * what it read (daemon.mjs). */ - const inputsChanged = () => - [...warmReads, ...hookReads, ...written].some( - ([key, hash]) => !key.startsWith(`env:`) && inputHash(key) !== hash, - ) - return { check, close, inputsChanged } + // The keys whose text changed since the session read or wrote them (the + // restart reason names them, daemon.mjs `restartReason`). + // The session's input state now: how many tracked inputs it compares, which + // changed (their keys), and each gate input's stored and current hash (a key + // that names a gate, for the daemon's log). + const inputState = () => { + const changed = [] + const gates = [] + let compared = 0 + for (const [key, hash] of [...warmReads, ...hookReads, ...written]) { + if (key.startsWith(`env:`)) continue + compared += 1 + const now = inputHash(key) + if (now !== hash) changed.push(key) + if (key.includes(`gate`)) gates.push({ key, stored: hash, now }) + } + return { compared, changed, gates } + } + return { check, close, inputState } } /** diff --git a/packages/oracles/oracle-gaps/daemon.mjs b/packages/oracles/oracle-gaps/daemon.mjs index d4ff4686..31beb3ee 100644 --- a/packages/oracles/oracle-gaps/daemon.mjs +++ b/packages/oracles/oracle-gaps/daemon.mjs @@ -32,6 +32,7 @@ import { spawn } from 'node:child_process' import { randomUUID } from 'node:crypto' import { + appendFileSync, existsSync, linkSync, lstatSync, @@ -176,9 +177,14 @@ function send(pkg, message, bounded = false) { socket.on(`connect`, () => socket.write(`${JSON.stringify(message)}\n`)) if (bounded) { socket.setTimeout(WAIT_MS) - socket.on(`timeout`, () => - mark === undefined ? done({ silent: true }) : writeMark(mark, ``), - ) + socket.on(`timeout`, () => { + if (mark !== undefined) return writeMark(mark, ``) + logNote( + pkg, + `the CLI gave up waiting: ${WAIT_MS} ms with no beat or reply from the daemon; this check runs cold`, + ) + done({ silent: true }) + }) } socket.on(`data`, (chunk) => { reply += chunk @@ -416,6 +422,40 @@ async function takeLock(lock, socket) { // An environment as one value: its names and values, in name order. const envKey = (env) => JSON.stringify(Object.entries(env ?? {}).sort()) +// A line of daemon.log (the daemon's and the CLI's own notes, never a stream): +// each names its time, so a stretch can be measured from the log. +export const logNote = (pkg, text) => { + try { + appendFileSync( + join(stateDirOf(pkg), `daemon.log`), + `${new Date().toISOString()} oracle-gaps: pid ${process.pid}: ${text}\n`, + ) + } catch { + // A note that cannot be written loses nothing a check reports. + } +} + +// Why a request restarts this daemon, in the order the request handler has +// always tested it (the first reason only), or undefined when none holds. An +// input's changed keys are named, since a restart reason is a diagnosis. +// It returns { why, inputs }: `inputs` is the session's input state (check.mjs +// inputState) when the tracked inputs were compared, else undefined. +function restartReason(message, code, ownEnv, session, codeIdentity) { + if (codeIdentity() !== code) return { why: `the code of this copy changed` } + if (message.code !== code) return { why: `the request is of other code` } + if (envKey(message.env) !== ownEnv) + return { why: `the request's environment differs from the daemon's` } + const inputs = session.inputState() + if (inputs.changed.length > 0) { + const shown = inputs.changed.slice(0, 8).join(`, `) + return { + why: `a tracked input changed: ${shown}${inputs.changed.length > 8 ? ` and ${inputs.changed.length - 8} more` : ``}`, + inputs, + } + } + return { why: undefined, inputs } +} + async function serve(pkg) { // The environment this daemon runs its checks under, which the CLI that // started it gave it, taken before the session sets anything in it. @@ -506,7 +546,10 @@ async function serve(pkg) { if (!request.includes(`\n`)) return const message = JSON.parse(request) // A closing daemon serves nothing more; the caller waits for the next. - if (closing) return reply(connection, { closing: true }) + if (closing) { + logNote(pkg, `declined a request: the daemon is closing`) + return reply(connection, { closing: true }) + } if (message.stop) { closing = true queue = queue.then(() => shutdown(connection)) @@ -514,17 +557,23 @@ async function serve(pkg) { } waiting.add(connection) overlap?.accepted() + const arrived = Date.now() queue = queue.then(async () => { clearTimeout(idle) // A request queued before the session failed hears why. - if (failure) + if (failure) { + logNote(pkg, `declined a request: the session failed to open`) return reply(connection, { code, stdout: ``, stderr: ``, failed: sent(failure), }) - if (closing) return reply(connection, { closing: true }) + } + if (closing) { + logNote(pkg, `declined a request: the daemon is closing`) + return reply(connection, { closing: true }) + } // A daemon whose code changed, or that a CLI of other code asks (a // second install), declines this check and closes after the // requests already queued, each of which hears `closing`; the CLI @@ -534,18 +583,28 @@ async function serve(pkg) { // daemon input (maintainer decision, 2026-11-16), and a module or a // plugin may keep what it read, so the CLI starts a daemon in its own // environment, which reads them again. - if ( - codeIdentity() !== code || - message.code !== code || - envKey(message.env) !== ownEnv || - session.inputsChanged() - ) { + const decided = restartReason( + message, + code, + ownEnv, + session, + codeIdentity, + ) + if (decided.why !== undefined) { + logNote(pkg, `replaced by a new daemon: ${decided.why}`) closing = true queue = queue.then(() => shutdown(connection, { restart: true })) return } + // The decision that kept this daemon, with what it compared: the tracked + // inputs' count and any gate input's stored and current hash. + logNote( + pkg, + `kept for a check: compared ${decided.inputs.compared} tracked inputs, none changed; gates ${JSON.stringify(decided.inputs.gates)}`, + ) // The test-only hold before a check runs (`pauseAt`). await pauseAt(`daemon-check`) + const checkStarted = Date.now() const stderr = [] let stdout = `` let failed @@ -586,6 +645,10 @@ async function serve(pkg) { } catch (error) { failed = sent(error) } + logNote( + pkg, + `served a check${failed === undefined ? `` : ` that failed`}: ${checkStarted - arrived} ms queued (the session's open included), ${Date.now() - checkStarted} ms checking`, + ) await reply(connection, { code, stdout, From a7e17a4a100ee7dbd1887a20510e1690e330f372 Mon Sep 17 00:00:00 2001 From: Kyle Mathews Date: Thu, 3 Dec 2026 13:21:41 -0700 Subject: [PATCH 45/51] test(oracle-gaps): a restart violation names each daemon's real pid, so a failure maps to its daemon log The driver numbers daemons by ordinal (pid 15). The violation now also gives the process ids, which the daemon's log lines carry. Law-neutral: the restart rule and the recorded trace are unchanged. Co-authored-by: Isaac --- .../oracle-gaps/gap-report-oracle.property.test.mjs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs b/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs index e07720a4..d26bc3ed 100644 --- a/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs +++ b/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs @@ -3095,6 +3095,9 @@ async function incremental(dir, plan, cli, copy, observe, states) { const ordinalOf = (pid) => { if (!daemonOrdinals.has(pid)) daemonOrdinals.set(pid, daemonOrdinals.size + 1) + // DIAGNOSTIC (test-only, to revert): ordinal -> real pid, for violation text. + globalThis.__oracleRealPids ??= new Map() + globalThis.__oracleRealPids.set(daemonOrdinals.get(pid), pid) return daemonOrdinals.get(pid) } // The check through the daemon during which a mid-run edit landed, and a @@ -6140,8 +6143,8 @@ function incrementalCheck(observations, expected, plan) { return violation( `incremental`, owed - ? `the check through the daemon at ${step} kept the daemon that served its previous check (pid ${r.pid}), though a tracked input changed` - : `the check through the daemon at ${step} was served by a new daemon (pid ${r.previousPid} to ${r.pid}), though no tracked input changed`, + ? `the check through the daemon at ${step} kept the daemon that served its previous check (pid ${r.pid}, real ${globalThis.__oracleRealPids?.get(r.pid)} from ${globalThis.__oracleRealPids?.get(r.previousPid)}), though a tracked input changed` + : `the check through the daemon at ${step} was served by a new daemon (pid ${r.previousPid} to ${r.pid}, real ${globalThis.__oracleRealPids?.get(r.previousPid)} to ${globalThis.__oracleRealPids?.get(r.pid)}), though no tracked input changed`, `restart iff a tracked input changed`, ) } From 31b5b0b052caf31debcfcfba6c6ba769a4846a0d Mon Sep 17 00:00:00 2001 From: Kyle Mathews Date: Thu, 3 Dec 2026 14:24:48 -0700 Subject: [PATCH 46/51] fix(oracle-gaps): a package reached through a symbolic link is imported by its real path A require resolves a package to its link, not its target, in Node's preserve-symlinks mode, and an ESM import of the link does not find the dependencies that sit beside the target (pnpm links each package from node_modules/.pnpm): CI's held-check refusal, "Cannot find package '@vitest/utils'", on 5db6b8ed (fixed seed 7/9). The Vitest import and the esbuild imports (the linked-package scan, configParses) now import the real path (moduleUrlOf), which the default resolver gives too. Reproduced with a pnpm-style fixture under NODE_PRESERVE_SYMLINKS=1: the mutant with the link path fails with the CI text, the fix loads in both modes. CI's refusal does not name the environment variable, so the CI cause is not confirmed; the refusal now names NODE_PRESERVE_SYMLINKS as well. Co-authored-by: Isaac --- packages/oracles/oracle-gaps/check.mjs | 24 ++++++++++++++++-------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/packages/oracles/oracle-gaps/check.mjs b/packages/oracles/oracle-gaps/check.mjs index 4cadf38c..30882283 100644 --- a/packages/oracles/oracle-gaps/check.mjs +++ b/packages/oracles/oracle-gaps/check.mjs @@ -108,6 +108,18 @@ import { } from './paths.mjs' import { stateDirOf } from './evidence.mjs' import { envHash, fileSha1, inputHash, watchReads } from './inputs.mjs' + +/** + * The URL a resolved module is imported from: its real path. Under Node's + * preserve-symlinks mode (NODE_PRESERVE_SYMLINKS=1, or --preserve-symlinks) a + * require resolves a package to its link, not its target, and an ESM import of + * the link does not find the dependencies that sit beside the target (pnpm + * links each package from node_modules/.pnpm): "Cannot find package + * '@vitest/utils'". The target is what Node imports by default, so the real + * path loads the same module in either mode. + */ +export const moduleUrlOf = (resolved) => + pathToFileURL(realpathSync.native(resolved)).href import { baselineOf, blockedOr, @@ -428,9 +440,7 @@ export async function workspaceBundles(pkg) { const requireVite = createRequire( createRequire(join(pkg, `package.json`)).resolve(`vite`), ) - const esbuild = await import( - pathToFileURL(requireVite.resolve(`esbuild`)).href - ) + const esbuild = await import(moduleUrlOf(requireVite.resolve(`esbuild`))) // A package's one ESM entry: its `exports` for `.`, under `import`, else // `node` or `default`. A package with no `exports`, or one that also // exports a subpath (other than its manifest), has none. @@ -664,9 +674,7 @@ export async function openSession(pkg, pause = async () => {}) { let resolved try { resolved = requireTarget.resolve(`vitest/node`) - ;({ createVitest } = await warming( - () => import(pathToFileURL(resolved).href), - )) + ;({ createVitest } = await warming(() => import(moduleUrlOf(resolved)))) } catch (error) { // Where Vitest resolved and whether that is a real path (a symbolic link's // target is what ESM imports from), named so a failure on another machine @@ -681,7 +689,7 @@ export async function openSession(pkg, pause = async () => {}) { // flattened: the refusal's first line is the one a driver reads (the CI // failure of the held histories, 3a3d54b1 showed no layout at all). throw new Refusal( - `the package's Vitest failed to load (${layout}; NODE_OPTIONS ${JSON.stringify(process.env.NODE_OPTIONS ?? null)}; execArgv ${JSON.stringify(process.execArgv)}): ${String(error?.message ?? error).replaceAll(`\n`, ` / `)}`, + `the package's Vitest failed to load (${layout}; NODE_OPTIONS ${JSON.stringify(process.env.NODE_OPTIONS ?? null)}; NODE_PRESERVE_SYMLINKS ${JSON.stringify(process.env.NODE_PRESERVE_SYMLINKS ?? null)}; execArgv ${JSON.stringify(process.execArgv)}): ${String(error?.message ?? error).replaceAll(`\n`, ` / `)}`, `Install a working Vitest in the package, so that vitest/node loads from it.`, ) } @@ -984,7 +992,7 @@ export default async (env) => { const requireVite = createRequire( createRequire(requireTarget.resolve(`vitest/node`)).resolve(`vite`), ) - esbuild = await import(pathToFileURL(requireVite.resolve(`esbuild`)).href) + esbuild = await import(moduleUrlOf(requireVite.resolve(`esbuild`))) } catch { return } From f1b8e82b8fd8be690e7f4f3b3012235db6ab18b3 Mon Sep 17 00:00:00 2001 From: Kyle Mathews Date: Thu, 3 Dec 2026 14:25:18 -0700 Subject: [PATCH 47/51] fix(oracle-gaps): the daemon's log names each shutdown, lock transition and exit; a cleanState's lock loss is not judged The daemon's log now names why each daemon shuts down (idle, a stop request, a replacement, a failed session, a lock another daemon holds or a read error), its process exit, and its lock transitions (taken, found held, moved stale). Law-neutral: the restart decision is evaluated in the old order. The restart law judges a pair of daemon checks by their pids. The cleanState step removes the state directory, daemon.lock included, so the daemon that served the check before it leaves at its next lock watch (2 s) and is replaced at the following check, as the protocol does (daemon.mjs `watch`). The law says the state goes while the daemon may still run, so neither the cleanState check nor the check after it is judged (model LOCK_LOST_AT, law 9's paragraph, accepted by the coordinator 2026-12-03). Limit: a watch tick after two or more checks would still be a replacement the law does not judge. The restart violation names each daemon's real pid as well as its ordinal. Co-authored-by: Isaac --- packages/oracles/oracle-gaps/daemon.mjs | 49 ++++++++++++++++--- .../oracle-gaps/gap-report-model-oracle.mjs | 11 +++++ .../gap-report-oracle.property.test.mjs | 11 +++++ 3 files changed, 63 insertions(+), 8 deletions(-) diff --git a/packages/oracles/oracle-gaps/daemon.mjs b/packages/oracles/oracle-gaps/daemon.mjs index 31beb3ee..ce54ca76 100644 --- a/packages/oracles/oracle-gaps/daemon.mjs +++ b/packages/oracles/oracle-gaps/daemon.mjs @@ -386,14 +386,27 @@ const listening = (socket) => * Takes the package's lock, or returns false when a live daemon holds it. */ async function takeLock(lock, socket) { + // Test-visible lock transitions (daemon.log): who holds the lock, never its token. + const note = (text) => { + try { + appendFileSync( + join(dirname(lock), `daemon.log`), + `${new Date().toISOString()} oracle-gaps: pid ${process.pid}: lock ${text}\n`, + ) + } catch {} + } + const holderOf = (text) => + text === undefined ? `absent` : `held by pid ${text.split(':')[0]}` for (;;) { try { writeFileSync(lock, token, { flag: `wx` }) + note(`taken`) return true } catch (error) { if (error.code !== `EEXIST`) throw error } const seen = readText(lock) + note(`found ${holderOf(seen)}`) for (let waited = 0; waited < GRACE_MS; waited += 100) { if (await listening(socket)) return false await sleep(100) @@ -408,6 +421,7 @@ async function takeLock(lock, socket) { } catch { continue } + note(`moved the stale lock ${holderOf(readText(claim))}`) if (readText(claim) !== seen) try { linkSync(claim, lock) @@ -464,6 +478,8 @@ async function serve(pkg) { const lock = join(stateDirOf(pkg), `daemon.lock`) const socket = socketOf(pkg) if (!(await takeLock(lock, socket))) process.exit(0) + // Test-visible (daemon.log): the process's exit, after any shutdown line. + process.on(`exit`, (code) => logNote(pkg, `process exit ${code}`)) // A dead daemon's socket; this daemon holds the lock. removeSocket(socket) let closing = false @@ -492,13 +508,13 @@ async function serve(pkg) { }) // Stops serving: the requests already queued run first, each hearing // `closing`, then the daemon shuts down. - const close = () => { + const close = (why = `closed`) => { closing = true - queue = queue.then(() => shutdown()) + queue = queue.then(() => shutdown(undefined, { exitCode: 0 }, why)) } const closeAfter = (ms) => { clearTimeout(idle) - idle = setTimeout(close, ms) + idle = setTimeout(() => close(`idle for ${ms} ms`), ms) } // Resolves once the reply has left this process, so a daemon that exits // next cannot cut it short; a reply longer than the socket's buffer is @@ -552,7 +568,9 @@ async function serve(pkg) { } if (message.stop) { closing = true - queue = queue.then(() => shutdown(connection)) + queue = queue.then(() => + shutdown(connection, undefined, `stopped by a request`), + ) return } waiting.add(connection) @@ -593,7 +611,9 @@ async function serve(pkg) { if (decided.why !== undefined) { logNote(pkg, `replaced by a new daemon: ${decided.why}`) closing = true - queue = queue.then(() => shutdown(connection, { restart: true })) + queue = queue.then(() => + shutdown(connection, { restart: true }, `replaced`), + ) return } // The decision that kept this daemon, with what it compared: the tracked @@ -669,9 +689,10 @@ async function serve(pkg) { // it unlinks the socket path, and a daemon that lost its lock may find the // path taken by the successor that holds the lock now, whose socket it // would remove. - async function shutdown(connection, value = { exitCode: 0 }) { + async function shutdown(connection, value = { exitCode: 0 }, why = `closed`) { closing = true clearInterval(watch) + logNote(pkg, `shutting down: ${why}`) await session?.close() // A store that cannot write its last check (a full disk) is no reason to // keep the lock: the next daemon starts cold. @@ -708,15 +729,27 @@ async function serve(pkg) { // one rather than hearing this error again. failure = error writeFileSync(errorFileOf(pkg), JSON.stringify(sent(error))) + logNote(pkg, `the session failed to open: ${error?.message ?? error}`) opened() - close() + close(`the session failed to open`) return } rmSync(errorFileOf(pkg), { force: true }) opened() // A daemon whose lock another daemon took serves no more. watch = setInterval(() => { - if (!closing && readText(lock) !== token) close() + if (closing) return + let now + let errno + try { + now = readFileSync(lock, `utf8`) + } catch (error) { + errno = error.code + } + if (now !== token) + close( + `the lock names another daemon (${now === undefined ? `read error ${errno}` : `held by pid ${now.split(`:`)[0]}`})`, + ) }, 2000) closeAfter(idleMs) } diff --git a/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs b/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs index 9d1165cc..f779fd7e 100644 --- a/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs +++ b/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs @@ -7055,10 +7055,21 @@ const ENDS_DAEMON_AFTER = new Set([ * the CLI started a fresh daemon or ran cold; a start past the bound is one * such check). A start is no end: the daemon it makes serves the next check. */ +// The steps that remove the daemon's lock with the state directory +// (cleanState). The daemon's lock watch runs every 2 s, so the daemon that +// served the check before the removal, or the one after it, may leave at its +// next watch tick and be replaced by a new daemon at the following check. The +// protocol does this (daemon.mjs `watch`: "the lock names another daemon"), +// and the law says the state goes while the daemon may still run; so neither +// the step's own check nor the check after it is judged. Not judged means no +// pid is recorded for them (the restart observation, law 9). +export const LOCK_LOST_AT = new Set([`cleanState`]) export const restartJudged = (step, previousStep, check, previous) => previous !== undefined && previous.pid !== undefined && !RESTART_NOT_JUDGED.has(step) && + !LOCK_LOST_AT.has(step) && + !LOCK_LOST_AT.has(previousStep) && step !== `midrun` && !ENDS_DAEMON_AFTER.has(previousStep) && check.reported && diff --git a/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs b/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs index d26bc3ed..3b169064 100644 --- a/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs +++ b/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs @@ -313,6 +313,16 @@ * accepted 2026-12-02 (coordinator): a mid-run edit restarts the daemon of * the check it overlaps, so that check and the one after it are not judged * against the rule; the mid-run family judges the edit instead. + * The cleanState step removes the state directory, daemon.lock included. The + * daemon's lock watch runs every 2 s, so the daemon that served the check + * before the removal may leave at its next watch tick and be replaced at the + * following check (daemon.mjs `watch`). The protocol does this, and the law + * says the daemon's state goes while the daemon may still run. So neither the + * cleanState check nor the check after it is judged (model LOCK_LOST_AT, + * accepted by the coordinator, 2026-12-03). Limit: a watch tick after two or + * more checks would still be a replacement the law does not judge; the + * exemption is bounded by the durations of the checks between the removal + * and the next tick. * 10. **The runner runs the package as Vitest does.** From any install path * (one with a space and `#` included), for any spelling of `--source` * (`./`, a redundant segment, an absolute path through a symbolic link @@ -751,6 +761,7 @@ import { outsideOf, PLUGIN_INPUT_READS, RESTART_NOT_JUDGED, + LOCK_LOST_AT, restartJudged, restartOwed, } from './gap-report-model-oracle.mjs' From 2928a6ab45efe0fe9d5095a1bb2fa9913df46b15 Mon Sep 17 00:00:00 2001 From: Kyle Mathews Date: Thu, 3 Dec 2026 14:25:35 -0700 Subject: [PATCH 48/51] fix(oracle-gaps): on win32 the gate of a linkDotDot read is the file its lexical `..` opens The linkDotDot history reads `link/../gate.json` through a symbolic link to a/b. A POSIX kernel resolves `..` after the link, so the read opens tests/a/gate.json (CR-22). win32 resolves `..` lexically before it follows the link, so the same spelling opens tests/gate.json, which the fixture did not write. CI's Windows run (5db6b8ed, fixed seed 20261105, "a failing owner under its parent's config") failed with ENOENT on tests\gate.json: the mutant's copy crashed where the cold run's read had judged it. The model now names, per platform, the file the read opens (gateFiles.linkDotDot), so the fixture writes that file and the read sees the gate text the state holds. POSIX is unchanged. Co-authored-by: Isaac --- packages/oracles/oracle-gaps/gap-report-model-oracle.mjs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs b/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs index f779fd7e..34dad6c2 100644 --- a/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs +++ b/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs @@ -6744,7 +6744,12 @@ const gateFiles = { rplus: `tests/gate.json`, threadNested: `tests/gate.json`, childLost: `tests/gate.json`, - linkDotDot: `tests/a/gate.json`, + // The file the read of `link/../gate.json` opens. A kernel resolves `..` after + // a symbolic link (POSIX: a/gate.json, CR-22). win32 resolves `..` lexically + // before the link is followed, so the same spelling opens tests/gate.json + // (CI's Windows ENOENT on tests\gate.json, 5db6b8ed fixed seed 20261105). + linkDotDot: + process.platform === `win32` ? `tests/gate.json` : `tests/a/gate.json`, threadStrict: `tests/gate.json`, } /** Whether the gate input is one that the config's own plugin reads. */ From e209f632b75cfdda868cf0c9efb8b4d1728c845a Mon Sep 17 00:00:00 2001 From: Kyle Mathews Date: Thu, 3 Dec 2026 14:34:36 -0700 Subject: [PATCH 49/51] fix(oracle-gaps): a transform-time gate change owes a restart only after a check that ran a unit The restart rule owed a daemon restart for every change of a pluginTransform gate. A transform-time read is a unit's input, though: the plugin's transform runs where a unit computes, and the session records the gate only then. The rule now owes a restart for a pluginTransform change only after a check that ran a unit (the previous check's `ran`). Config-time gate kinds (pluginConfig, tsconfig, configListing, pluginWrite) owe a restart on every change. Limit: a check that ran a unit for other files only is judged the same way. Law 9's paragraph carries the reason. Seed 42735391 no longer fails at the restart checkpoint; its replay then stops at a constructed history's reach check (a warm daemon's connection reset), which is not decided here. Co-authored-by: Isaac --- .../oracle-gaps/gap-report-model-oracle.mjs | 19 ++++++++++++++++++- .../gap-report-oracle.property.test.mjs | 12 ++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs b/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs index 34dad6c2..09c2b4f2 100644 --- a/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs +++ b/packages/oracles/oracle-gaps/gap-report-model-oracle.mjs @@ -7020,10 +7020,27 @@ export const PLUGIN_INPUT_READS = new Set([ // inputsChanged) compares the file's text with what it wrote, so a hand edit // that the next warm wrote back is no change of the session's input. const envOf = (env) => JSON.stringify(Object.entries(env ?? {}).sort()) +// The gate kinds the session reads at config time (its open and each warm-up), +// so the session holds them as inputs from the start of a daemon's session. +export const CONFIG_GATE_READS = new Set([ + `pluginConfig`, + `tsconfig`, + `configListing`, + `pluginWrite`, +]) +// A transform-time read (pluginTransform) is a unit's input, not a session +// read: the plugin's transform runs where a unit computes, and the session +// records the gate only then. So a gate change owes a restart only after a +// check that ran a unit (`ran`: the previous check's computed units), where the +// transform could have read the gate in the session (law 9's limit: a check +// that ran a unit for other files only is judged the same). export const restartOwed = (plan, check, previous) => envOf(check.env) !== envOf(previous.env) || check.cliCode !== previous.cliCode || - (PLUGIN_INPUT_READS.has(plan.inputRead) && + (CONFIG_GATE_READS.has(plan.inputRead) && + check.inputOpen !== previous.inputOpen) || + (plan.inputRead === `pluginTransform` && + previous.ran > 0 && check.inputOpen !== previous.inputOpen) // The steps after which a check's daemon is a new process by the step's own diff --git a/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs b/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs index 3b169064..2eb51b0f 100644 --- a/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs +++ b/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs @@ -323,6 +323,13 @@ * more checks would still be a replacement the law does not judge; the * exemption is bounded by the durations of the checks between the removal * and the next tick. + * A transform-time gate read (pluginTransform) is a unit input, not a + * session read: a plugin's transform runs where a unit computes, so a gate + * change owes a restart only after a check that ran a unit (model + * restartOwed, CONFIG_GATE_READS and `ran`; decision 2026-12-03). The + * config-time gate kinds (pluginConfig, tsconfig, configListing, + * pluginWrite) owe the restart on every change. Limit: a check that ran a + * unit for other files only is judged the same way. * 10. **The runner runs the package as Vitest does.** From any install path * (one with a space and `#` included), for any spelling of `--source` * (`./`, a redundant segment, an absolute path through a symbolic link @@ -3299,6 +3306,9 @@ async function incremental(dir, plan, cli, copy, observe, states) { pid: ordinalOf(daemon.checkPid), env: sentEnv, cliCode, + // The units this check computed: a transform-time gate read is a + // session input only where a unit ran (restartOwed). + ran: computedRuns(daemon), inputOpen: leftOpen, reported: daemon.reported === true, fellBack, @@ -3322,6 +3332,7 @@ async function incremental(dir, plan, cli, copy, observe, states) { previousReported: priorDaemon?.reported, fellBack, previousFellBack: priorDaemon?.fellBack, + previousRan: priorDaemon?.ran, } // The restart observation is recorded only where the restart law judges // it (model: restartJudged): a refused check's daemon pid depends on when @@ -6147,6 +6158,7 @@ function incrementalCheck(observations, expected, plan) { env: r.previousEnv, cliCode: r.previousCode, inputOpen: r.previousInputOpen, + ran: r.previousRan, }, ) const restarted = r.pid !== r.previousPid From 44cb62a684eae4c57f9db624f4b91d5c21c4358b Mon Sep 17 00:00:00 2001 From: Kyle Mathews Date: Thu, 3 Dec 2026 15:01:37 -0700 Subject: [PATCH 50/51] fix(oracle-gaps): the reset step awaits its warm daemon's served mark The daemon writes its served mark after its reply, and the reply resolves once the CLI's socket closes, so the CLI can exit before the mark exists. The reset step sampled the mark at once, read no warm pid, and entered no "a warm daemon's connection was reset" state on seed 42735391 although the paused daemon was the warm one. The step now awaits the mark, up to 10 s. Co-authored-by: Isaac --- .../oracle-gaps/gap-report-oracle.property.test.mjs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs b/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs index 2eb51b0f..6d7cb912 100644 --- a/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs +++ b/packages/oracles/oracle-gaps/gap-report-oracle.property.test.mjs @@ -4041,6 +4041,15 @@ async function incremental(dir, plan, cli, copy, observe, states) { cold: false, }), ) + // The daemon writes its served mark after its reply, and the reply + // resolves once the CLI's socket closes, so the CLI may exit before the + // mark exists: the mark is awaited, not sampled (diag, 2026-12-03). + for ( + let waited = 0; + pidOf(servedMark) === undefined && waited < 10_000; + waited += 20 + ) + await new Promise((r) => setTimeout(r, 20)) warm = pidOf(servedMark) // The warm daemon is stopped before the pause is armed: an armed daemon // holds the stop's own connection unread, so the stop would never end. From 551472f505709575609f3ce15a4e95ba54c4611e Mon Sep 17 00:00:00 2001 From: Kyle Mathews Date: Thu, 3 Dec 2026 15:04:38 -0700 Subject: [PATCH 51/51] test(oracle-gaps): the evidence store's two size tests get a 60 s timeout Both tests flush around 6 MB of units with WAL checkpoints. The Windows runner's disk ran the first past the 5 s default (CI on 2928a6ab, "Test timed out in 5000ms" at the size law). The laws are unchanged. Co-authored-by: Isaac --- packages/oracles/tests/oracle-gaps-evidence-store.test.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/oracles/tests/oracle-gaps-evidence-store.test.ts b/packages/oracles/tests/oracle-gaps-evidence-store.test.ts index 8b9afac6..fb3297a7 100644 --- a/packages/oracles/tests/oracle-gaps-evidence-store.test.ts +++ b/packages/oracles/tests/oracle-gaps-evidence-store.test.ts @@ -203,8 +203,9 @@ describe.each(backends)(`evidence store (%s) size`, (name, open) => { // Four versions of half a megabyte, with room for the backend's framing; // the eight replaced versions must not have stayed in the store. expect(storeBytes(dir)).toBeLessThan(6 * half) - }) + }, 60_000) // 60 s: the Windows runner's disk runs these flushes past the 5 s default + // 60 s: the Windows runner's disk runs these flushes past the 5 s default. test(`the pages of pruned units go back to the file system`, async () => { const dir = scratch() let clock = 1_000_000 @@ -230,7 +231,7 @@ describe.each(backends)(`evidence store (%s) size`, (name, open) => { // The store holds one small unit: the pruned units' pages are not kept // for later use, they leave the file (review of #314, F2). expect(storeBytes(dir)).toBeLessThan(4 * page) - }) + }, 60_000) }) describe.each(backends)(`evidence store (%s) pruning`, (name, open) => {