Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

run-budget-oracle.property.test.js

637 lines22.5 KB

1/**
2 * Law (L5): every run budget that an oracle property uses is tracked by
3 * scripts/check-oracle-run-counts.mjs, wherever it is written. A budget is the
4 * numRuns of a fixed-seed campaign, or the run count of a registered property.
5 * When the branch lowers a budget, or removes it from every tracked oracle
6 * file, the script reports it, so the change is visible to the reviewer.
7 *
8 * A budget belongs to the oracle file that uses it: its own campaigns, and the
9 * campaigns and constants in the test modules that it imports or re-exports.
10 * Moving a budget between those places keeps it tracked. So does moving it to
11 * another tracked oracle file. A budget is removed when its key is in no
12 * tracked oracle file at head: it was deleted, or moved into an ordinary test
13 * file that no oracle file imports.
14 *
15 * Authority: AGENTS.md "Lint feedback while you work" names a lowered budget
16 * as a shortcut that the oracle pass hides, and the run-count script is the
17 * tripwire for it. docs/contributing/oracle-rubric.md ORC-007 requires the same
18 * property, generators, and budget in each campaign. The removal rule is the
19 * maintainer's decision of 2026-10-27: a key present in a tracked oracle file
20 * at base and in no tracked oracle file at head is reported as removed, and a
21 * move into an imported support module is not a removal. The script's header
22 * states the key and value forms that it reads.
23 *
24 * Limits. The grammar builds one oracle file, up to two support modules, an
25 * ordinary test file, and a second oracle file, with at most three budgets. A
26 * key is unique to its budget, except that a fixed seed can be shared with an
27 * unrelated campaign in the second oracle file. Then the removal law treats
28 * the seed as still present, and the model follows it. Star re-exports are not
29 * generated. A count may be wrapped in oracleRuns. The model judges the
30 * reported budget, its base value, and its head value or removal; it does not
31 * predict the wording of a line.
32 *
33 * Structure:
34 * 1. The grammar draws budgets: their form, the places their count and key
35 * are written, where the campaign is at base, and where it is at head.
36 * 2. The model predicts the lowered and removed budgets from those draws.
37 * 3. The driver writes both versions into a temporary git repository and runs
38 * the script's command-line report there, with a copy of the script under
39 * test. A crashed script is a failure, not an empty report.
40 * 4. The comparison checks that the report equals the prediction.
41 */
42import { execFile } from 'node:child_process'
43import {
44 mkdtempSync,
45 mkdirSync,
46 readFileSync,
47 rmSync,
48 symlinkSync,
49 writeFileSync,
50} from 'node:fs'
51import { tmpdir } from 'node:os'
52import { join } from 'node:path'
53import { fileURLToPath } from 'node:url'
54import { promisify } from 'node:util'
55import fc from 'fast-check'
56import { afterAll, beforeAll, describe, expect, it } from 'vitest'
57import { declareOracle } from '../packages/db/tests/oracle-declaration.js'
58import {
59 oraclePropertyOptions,
60 oracleRuns,
61} from '../packages/db/tests/oracle-config.js'
62import { createOracleReach } from '../packages/db/tests/oracle-reach.js'
63​
64declareOracle({
65 model: [predictReport],
66 check: [compareReport],
67 grammar: [programArbitrary],
68})
69​
70const PROPERTY = `scripts.run-budget`
71const FIXED_SEED = 2234
72const BASE_RUNS = 20
73const repoRoot = fileURLToPath(new URL(`../`, import.meta.url))
74const OTHER_ORACLE = `tests/other-oracle.test.ts`
75const ORDINARY = `tests/ordinary.test.ts`
76// A base oracle file above the default 1 MiB child-process buffer. Reading it
77// at the base commit must not be mistaken for a missing file.
78const LARGE_PADDING = 1_100_000
79​
80// -- 1. Grammar ---------------------------------------------------------------
81//
82// A budget's count is written inline, in support module A, or in A and passed
83// on by support module B's re-export. Its key is inline or imported from A. A
84// change edits the count where it is defined, or writes a literal at the call.
85// The campaign itself is in the oracle file or in A at base (`callAt`). At
86// head it stays, moves between the oracle file and A, moves to the ordinary
87// file or the second oracle file, or is deleted (`fate`). The oracle file and
88// A are `.ts` or `.js`; an import names A with or without the `.js` suffix.
89​
90const budgetSkeleton = fc.record({
91 form: fc.constantFrom(`property`, `seed`),
92 source: fc.constantFrom(`inline`, `imported`, `reexported`),
93 keySource: fc.constantFrom(`inline`, `imported`),
94 wrapped: fc.boolean(),
95 base: fc.nat({ max: 398 }).map((n) => n + 2),
96 // Lowering, and editing the definition, are the cases that the law is about,
97 // so the grammar draws them more often.
98 change: fc.oneof(
99 { weight: 3, arbitrary: fc.constant(`lower`) },
100 { weight: 1, arbitrary: fc.constant(`raise`) },
101 { weight: 1, arbitrary: fc.constant(`keep`) },
102 ),
103 delta: fc.nat({ max: 50 }).map((n) => n + 1),
104 editAt: fc.oneof(
105 { weight: 3, arbitrary: fc.constant(`definition`) },
106 { weight: 1, arbitrary: fc.constant(`call`) },
107 ),
108 callAt: fc.oneof(
109 { weight: 2, arbitrary: fc.constant(`oracle`) },
110 { weight: 1, arbitrary: fc.constant(`support`) },
111 ),
112 fate: fc.oneof(
113 { weight: 4, arbitrary: fc.constant(`stay`) },
114 { weight: 1, arbitrary: fc.constant(`swap`) },
115 { weight: 2, arbitrary: fc.constant(`remove`) },
116 { weight: 2, arbitrary: fc.constant(`ordinary`) },
117 { weight: 2, arbitrary: fc.constant(`other-oracle`) },
118 ),
119 sharedSeed: fc.boolean(),
120})
121​
122const fileForms = fc.record({
123 oracleExtension: fc.oneof(
124 { weight: 2, arbitrary: fc.constant(`ts`) },
125 { weight: 1, arbitrary: fc.constant(`js`) },
126 ),
127 supportExtension: fc.oneof(
128 { weight: 2, arbitrary: fc.constant(`ts`) },
129 { weight: 1, arbitrary: fc.constant(`js`) },
130 ),
131 jsSpecifier: fc.boolean(),
132 large: fc.oneof(
133 { weight: 2, arbitrary: fc.constant(false) },
134 { weight: 1, arbitrary: fc.constant(true) },
135 ),
136 // The second oracle file exists at base, or is new and untracked at head.
137 otherNew: fc.boolean(),
138})
139​
140/** Feature gates: which count sources a campaign may draw. */
141const ALL = [`inline`, `imported`, `reexported`]
142​
143function programArbitrary(sources, supportOnly = false) {
144 return fc
145 .record({
146 budgets: fc.array(budgetSkeleton, { minLength: 1, maxLength: 3 }),
147 files: fileForms,
148 })
149 .map(({ budgets, files }) => ({
150 files: resolveFiles(files),
151 budgets: budgets.map((budget, index) =>
152 resolveBudget(
153 supportOnly ? supportOnlyBudget(budget) : budget,
154 index,
155 sources,
156 files,
157 ),
158 ),
159 }))
161​
162/**
163 * A budget whose only edit lives in a support module: its count is imported
164 * or re-exported, its campaign stays in the oracle file, and the edit is at
165 * the count's definition, so the oracle file stays the same.
166 */
167function supportOnlyBudget(skeleton) {
168 return {
169 ...skeleton,
170 source: skeleton.source === `inline` ? `reexported` : skeleton.source,
171 editAt: `definition`,
172 callAt: `oracle`,
173 fate: `stay`,
174 }
176​
177function resolveFiles(files) {
178 return {
179 ...files,
180 oracle: `tests/case-oracle.test.${files.oracleExtension}`,
181 support: `tests/support-a.${files.supportExtension}`,
182 reexport: `tests/support-b.ts`,
183 }
185​
186/**
187 * A budget with its index, its values before and after the change, and the
188 * places the grammar drew, restricted to the allowed count sources.
189 */
190function resolveBudget(skeleton, index, sources, files) {
191 const source = sources.includes(skeleton.source) ? skeleton.source : `inline`
192 const headValue =
193 skeleton.change === `lower`
194 ? Math.max(1, skeleton.base - skeleton.delta)
195 : skeleton.change === `raise`
196 ? skeleton.base + skeleton.delta
197 : skeleton.base
198 return {
199 index,
200 form: skeleton.form,
201 source,
202 keySource: skeleton.keySource,
203 wrapped: skeleton.wrapped,
204 before: skeleton.base,
205 after: headValue,
206 changed: headValue !== skeleton.base,
207 // An inline count is always written at the call, so it changes there.
208 // An imported count changes at its definition, or as a literal at the call.
209 changedAt: source === `inline` ? `call` : skeleton.editAt,
210 callAt: skeleton.callAt,
211 fate: skeleton.fate,
212 // A shared seed is an unrelated campaign in the second oracle file, at
213 // base and at head. The budget's own campaign never moves there, and the
214 // file is not new: a campaign that appears with the key at head is a move.
215 sharedSeed:
216 skeleton.form === `seed` &&
217 skeleton.sharedSeed &&
218 skeleton.fate !== `other-oracle` &&
219 !files.otherNew,
220 key:
221 skeleton.form === `property`
222 ? `property budget.${skeleton.keySource === `imported` ? `q` : `p`}${index}`
223 : `fixed seed ${1000 + index}`,
224 }
226​
227// -- 2. Model -----------------------------------------------------------------
228//
229// The model reads the draws, not the files. Every budget starts in the oracle
230// file's scope: its campaign is in the oracle file or in a module that the
231// oracle file imports. A budget that is deleted, or moved into the ordinary
232// file, leaves every tracked oracle file, so it is reported as removed, unless
233// its fixed seed is still written in the second oracle file. A budget that
234// stays, moves between the oracle file and its support module, or moves to the
235// second oracle file is still tracked, and it is reported when its count went
236// down. Each line names the oracle file that used the budget at base.
237​
238/** The reported budgets, as sorted `file|key|before|after-or-removed` strings. */
239function predictReport(program) {
240 const lines = []
241 for (const budget of program.budgets) {
242 const leaves = budget.fate === `remove` || budget.fate === `ordinary`
243 if (leaves) {
244 if (!budget.sharedSeed) {
245 lines.push(
246 `${program.files.oracle}|${budget.key}|${budget.before}|removed`,
247 )
248 }
249 } else if (budget.after < budget.before) {
250 lines.push(
251 `${program.files.oracle}|${budget.key}|${budget.before}|${budget.after}`,
252 )
253 }
254 }
255 return lines.sort()
257​
258// -- 3. Driver ----------------------------------------------------------------
259//
260// The driver renders every file at base and at head, commits the base files,
261// and writes the head files into the working tree, as an edit leaves them. A
262// second oracle file that is new at head stays untracked. It runs the script's
263// command-line report with a copy of the script under test, and reads the
264// report lines back into the model's form.
265​
266/** Where a budget's campaign is at a revision, or undefined when it is gone. */
267function campaignFile(program, budget, revision) {
268 const { files } = program
269 const atBase = budget.callAt === `oracle` ? files.oracle : files.support
270 if (revision === `base`) return atBase
271 switch (budget.fate) {
272 case `stay`:
273 return atBase
274 case `swap`:
275 return atBase === files.oracle ? files.support : files.oracle
276 case `ordinary`:
277 return ORDINARY
278 case `other-oracle`:
279 return OTHER_ORACLE
280 default:
281 return undefined
282 }
284​
285/** A module's source text, collected as imports, then body lines. */
286class ModuleText {
287 #imports = new Map()
288 #lines = []
289​
290 import(specifier, name) {
291 if (!this.#imports.has(specifier)) this.#imports.set(specifier, new Set())
292 this.#imports.get(specifier).add(name)
293 }
294​
295 line(text) {
296 this.#lines.push(text)
297 }
298​
299 render(padding = 0) {
300 const imports = [...this.#imports].map(
301 ([specifier, names]) =>
302 `import { ${[...names].join(`, `)} } from '${specifier}'`,
303 )
304 const pad = padding > 0 ? [`// ${`x`.repeat(padding)}`] : []
305 return `${[...imports, ...this.#lines, ...pad].join(`\n`)}\n`
306 }
308​
309/** The base or head text of every file in a program. */
310function renderFiles(program, revision) {
311 const { files } = program
312 const isHead = revision === `head`
313 const supportSpecifier = files.jsSpecifier ? `./support-a.js` : `./support-a`
314 const modules = new Map(
315 [files.oracle, files.support, files.reexport, ORDINARY].map((file) => [
316 file,
317 new ModuleText(),
318 ]),
319 )
320 const otherPresent = !files.otherNew || isHead
321 if (otherPresent) modules.set(OTHER_ORACLE, new ModuleText())
322 const support = modules.get(files.support)
323 const reexported = []
324​
325 for (const budget of program.budgets) {
326 const i = budget.index
327 const host = campaignFile(program, budget, revision)
328 const count = isHead ? budget.after : budget.before
329 const seed = 1000 + i
330 // The definition of an imported key and count lives in support module A.
331 if (budget.keySource === `imported`) {
332 support.line(
333 budget.form === `property`
334 ? `export const PROP_${i} = 'budget.q${i}'`
335 : `export const SEED_${i} = ${seed}`,
336 )
337 }
338 const literalAtCall =
339 budget.source === `inline` ||
340 (isHead && budget.changed && budget.changedAt === `call`)
341 if (!literalAtCall) {
342 const defined =
343 isHead && budget.changed && budget.changedAt === `definition`
344 ? budget.after
345 : budget.before
346 support.line(`export const RUNS_${i} = ${defined}`)
347 if (budget.source === `reexported`) reexported.push(`RUNS_${i}`)
348 }
349 // An unrelated campaign in the second oracle file that shares the seed.
350 if (budget.sharedSeed) {
351 modules
352 .get(OTHER_ORACLE)
353 .line(
354 `fc.assert(fc.property(fc.integer(), () => undefined), { numRuns: 7, seed: ${seed} })`,
355 )
356 }
357 if (host === undefined) continue
358 const hostText = modules.get(host)
359 const inSupport = host === files.support
360 const fromHost = (file) =>
361 file === files.support ? supportSpecifier : `./support-b`
362 // A campaign in A reads A's own constants; elsewhere it imports them.
363 const use = (name, file) => {
364 if (!inSupport) hostText.import(fromHost(file), name)
365 return name
366 }
367 const countText = literalAtCall
368 ? `${count}`
369 : budget.source === `reexported` && !inSupport
370 ? use(`RUNS_${i}`, files.reexport)
371 : use(`RUNS_${i}`, files.support)
372 const runs = budget.wrapped ? `oracleRuns(${countText})` : countText
373 const keyText =
374 budget.keySource === `imported`
375 ? use(
376 budget.form === `property` ? `PROP_${i}` : `SEED_${i}`,
377 files.support,
378 )
379 : budget.form === `property`
380 ? `'budget.p${i}'`
381 : `${seed}`
382 const call =
383 budget.form === `property`
384 ? `export const opts${i} = oraclePropertyOptions(${runs}, ${keyText})`
385 : `export function campaign${i}() { fc.assert(fc.property(fc.integer(), () => undefined), { numRuns: ${runs}, seed: ${keyText} }) }`
386 hostText.line(call)
387 // The oracle file uses a campaign in A by importing it.
388 if (inSupport) {
389 modules
390 .get(files.oracle)
391 .import(
392 supportSpecifier,
393 budget.form === `property` ? `opts${i}` : `campaign${i}`,
394 )
395 }
396 }
397 if (reexported.length > 0) {
398 modules
399 .get(files.reexport)
400 .line(`export { ${reexported.join(`, `)} } from '${supportSpecifier}'`)
401 }
402 const rendered = new Map()
403 for (const [file, text] of modules) {
404 rendered.set(
405 file,
406 text.render(file === files.oracle && files.large ? LARGE_PADDING : 0),
407 )
408 }
409 return rendered
411​
412let work
413let scriptText
414​
415beforeAll(() => {
416 // Each run has its own directory, so concurrent runs cannot remove each
417 // other's repositories.
418 work = mkdtempSync(join(tmpdir(), `run-budget-oracle-`))
419 // A mutant is run from a copy: RUN_BUDGET_SCRIPT names the copy under test.
420 scriptText = readFileSync(
421 process.env.RUN_BUDGET_SCRIPT ??
422 join(repoRoot, `scripts`, `check-oracle-run-counts.mjs`),
423 `utf8`,
424 )
425})
426​
427afterAll(() => {
428 rmSync(work, { recursive: true, force: true })
429})
430​
431// Child processes run asynchronously so a long campaign never blocks the
432// test worker's event loop.
433const run = promisify(execFile)
434​
435const loweredLine = /^(.+?): (.+): run budget lowered from (\d+) to (\d+)$/
436const removedLine = /^(.+?): (.+): run budget removed \(was (\d+)\)$/
437​
438/**
439 * The script's report as model lines. The script exits 0 with no output when
440 * it reports nothing, and 1 with one line per budget when it reports. Any
441 * other outcome, including a crash, which also exits 1, fails the driver.
442 */
443function reportLines({ code, stdout, stderr }) {
444 if (stderr !== `` || (code !== 0 && code !== 1)) {
445 throw new Error(`script failed (exit ${code}):\n${stderr}`)
446 }
447 const lines = stdout.split(`\n`).filter(Boolean)
448 if ((code === 1) !== lines.length > 0) {
449 throw new Error(`exit ${code} does not match report:\n${stdout}`)
450 }
451 return lines
452 .map((line) => {
453 const lowered = loweredLine.exec(line)
454 if (lowered !== null) {
455 const [, file, key, was, now] = lowered
456 return `${file}|${key}|${was}|${now}`
457 }
458 const removed = removedLine.exec(line)
459 if (removed !== null) {
460 const [, file, key, was] = removed
461 return `${file}|${key}|${was}|removed`
462 }
463 throw new Error(`unexpected report line: ${line}`)
464 })
465 .sort()
467​
468/**
469 * Runs the script in a fresh repository whose base commit holds the base files
470 * and whose working tree holds the head files. Returns the reported budgets.
471 */
472async function reportOf(program) {
473 const directory = mkdtempSync(join(work, `r`))
474 const git = (...args) =>
475 run(
476 `git`,
477 [
478 `-c`,
479 `user.name=oracle`,
480 `-c`,
481 `user.email=oracle@example.invalid`,
482 ...args,
483 ],
484 { cwd: directory, encoding: `utf8` },
485 )
486 const write = (files) => {
487 for (const [file, text] of files) {
488 mkdirSync(join(directory, file, `..`), { recursive: true })
489 writeFileSync(join(directory, file), text)
490 }
491 }
492 try {
493 await git(`init`, `-q`, `-b`, `main`)
494 mkdirSync(join(directory, `scripts`))
495 writeFileSync(
496 join(directory, `scripts`, `check-oracle-run-counts.mjs`),
497 scriptText,
498 )
499 write(renderFiles(program, `base`))
500 await git(`add`, `-A`)
501 await git(`commit`, `-q`, `-m`, `base`)
502 // The dependencies are linked after the commit, so they are not tracked.
503 symlinkSync(join(repoRoot, `node_modules`), join(directory, `node_modules`))
504 write(renderFiles(program, `head`))
505 const result = await run(
506 process.execPath,
507 [`scripts/check-oracle-run-counts.mjs`, `--format=text`],
508 { cwd: directory, encoding: `utf8`, maxBuffer: 64 * 1024 * 1024 },
509 ).then(
510 ({ stdout, stderr }) => ({ code: 0, stdout, stderr }),
511 (error) => {
512 if (typeof error.code !== `number`) throw error
513 return { code: error.code, stdout: error.stdout, stderr: error.stderr }
514 },
515 )
516 return reportLines(result)
517 } finally {
518 rmSync(directory, { recursive: true, force: true })
519 }
521​
522// -- 4. Comparison ------------------------------------------------------------
523​
524/** The script's report equals the model's prediction, as sorted lists. */
525function compareReport(actual, expected) {
526 expect(actual).toEqual(expected)
528​
529// -- 5. Reach -----------------------------------------------------------------
530//
531// The states that the laws above depend on. A state counts once per history.
532​
533const STATES = [
534 `imported-count`,
535 `re-exported-count`,
536 `imported-key`,
537 `support-only-change`,
538 `oracle-and-support-change`,
539 `lowered-budget`,
540 `campaign-in-support`,
541 `moved-into-support`,
542 `removed-budget`,
543 `moved-to-ordinary`,
544 `moved-to-oracle`,
545 `moved-to-untracked-oracle`,
546 `shared-seed-kept`,
547 `large-base-file`,
548 `js-oracle`,
549 `js-support`,
551const reach = createOracleReach(PROPERTY, STATES, { minimum: 1 })
552​
553/** Marks the states that the program enters. */
554function recordStates(program) {
555 reach.beginHistory()
556 const states = new Set()
557 const { files } = program
558 for (const budget of program.budgets) {
559 if (budget.source === `imported`) states.add(`imported-count`)
560 if (budget.source === `reexported`) states.add(`re-exported-count`)
561 if (budget.keySource === `imported`) states.add(`imported-key`)
562 if (budget.after < budget.before) states.add(`lowered-budget`)
563 if (budget.callAt === `support`) states.add(`campaign-in-support`)
564 if (budget.callAt === `oracle` && budget.fate === `swap`) {
565 states.add(`moved-into-support`)
566 }
567 if (budget.fate === `remove`) states.add(`removed-budget`)
568 if (budget.fate === `ordinary`) states.add(`moved-to-ordinary`)
569 if (budget.fate === `other-oracle`) {
570 states.add(
571 files.otherNew ? `moved-to-untracked-oracle` : `moved-to-oracle`,
572 )
573 }
574 if (
575 budget.sharedSeed &&
576 (budget.fate === `remove` || budget.fate === `ordinary`)
577 ) {
578 states.add(`shared-seed-kept`)
579 }
580 }
581 const atCall = program.budgets.some(
582 (budget) => budget.changed && budget.changedAt === `call`,
583 )
584 const atDefinition = program.budgets.some(
585 (budget) => budget.changed && budget.changedAt === `definition`,
586 )
587 if (atDefinition && !atCall) states.add(`support-only-change`)
588 if (atDefinition && atCall) states.add(`oracle-and-support-change`)
589 if (files.large) states.add(`large-base-file`)
590 if (files.oracleExtension === `js`) states.add(`js-oracle`)
591 if (files.supportExtension === `js`) states.add(`js-support`)
592 for (const state of states) reach.reach(state)
594​
595// Each campaign has its own fixed seed, so the four campaigns do not draw the
596// same programs. The fixed options are written where the campaign is named, so
597// the run-count script tracks each budget.
598function campaign(name, sources, fixed, supportOnly = false) {
599 const arbitrary = programArbitrary(sources, supportOnly)
600 const predicate = async (program) => {
601 recordStates(program)
602 compareReport(await reportOf(program), predictReport(program))
603 }
604 it(`${name}: fixed-seed campaign`, async () => {
605 await fc.assert(fc.asyncProperty(arbitrary, predicate), fixed)
606 }, 900_000)
607 it(`${name}: random-seed campaign`, async () => {
608 await fc.assert(
609 fc.asyncProperty(arbitrary, predicate),
610 oraclePropertyOptions(BASE_RUNS, PROPERTY),
611 )
612 }, 900_000)
614​
615describe(`run budgets that the run-count script tracks`, () => {
616 campaign(`inline and imported counts`, [`inline`, `imported`], {
617 seed: FIXED_SEED,
618 numRuns: oracleRuns(BASE_RUNS),
619 })
620 campaign(`re-exported counts`, [`reexported`], {
621 seed: 2235,
622 numRuns: oracleRuns(BASE_RUNS),
623 })
624 campaign(`every source`, ALL, { seed: 2236, numRuns: oracleRuns(BASE_RUNS) })
625 campaign(
626 `support-only edits`,
627 [`imported`, `reexported`],
628 { seed: 2237, numRuns: oracleRuns(BASE_RUNS) },
629 true,
630 )
631 // Every declared state must be entered by the campaigns above.
632 afterAll(() => {
633 if (process.env.TANSTACK_DB_ORACLE_REACH_REPORT)
634 console.log(`REACH`, JSON.stringify([...reach.counts()]))
635 reach.assertReached()
636 })
637})