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

check-oracle-run-counts.mjs

488 lines16.0 KB

1#!/usr/bin/env node
2/**
3 * Reports oracle run budgets that a branch lowered or removed.
4 *
5 * A generated property checks more histories with a larger budget. Lowering
6 * one can make a failing property pass without any change that a lint rule can
7 * see, because the new count is still a valid count. Removing one drops its
8 * histories altogether. This check compares each oracle file's budgets with
9 * their versions at the merge-base and reports every budget that went down,
10 * and every budget that no tracked oracle file has any more. Either can be a
11 * deliberate choice, so the report is a tripwire for the reviewer, not a
12 * failure: CI prints it as a warning, and the agent hooks return it at the
13 * end of a turn.
14 *
15 * A budget is keyed by its registered property where the code names one
16 * (`oraclePropertyOptions(n, 'p')`, `oracleRandomParameters(n, _, 'p')`, or
17 * `{ property: 'p', defaultRuns: n }`), and otherwise by its fixed seed
18 * (`{ seed: s, numRuns: oracleRuns(n) }`). A key or count is a literal, a
19 * constant in the same file, or a constant that the file imports. An import
20 * follows relative re-exports (`export { x } from`, `export * from`), so a
21 * constant defined in a support module is tracked where the oracle uses it.
22 *
23 * An oracle file's budgets are its own and those in the test modules that it
24 * imports or re-exports, transitively, other than oracle files, which are
25 * checked as themselves. So a campaign that moves into a support module keeps
26 * its tracking. A budget that leaves one oracle file and appears in another,
27 * where it was not at base, has moved, and its new count is compared. A key
28 * that is in no tracked oracle file at head is reported as removed: the
29 * maintainer decided on 2026-10-27 that a removal is reported like a lowered
30 * budget, and that a move into an imported support module is not a removal.
31 * A fixed seed is not unique, so a key that another oracle file already had at
32 * base counts as present there, and is neither removed nor compared.
33 *
34 * An oracle file is a file whose name contains `oracle`, in TypeScript or
35 * JavaScript. It is checked when it changed, or when a module that it imports
36 * (directly or through re-exports) changed. Untracked files count as changed.
37 *
38 * node scripts/check-oracle-run-counts.mjs [--format=text|github]
39 */
40import { execFileSync } from 'node:child_process'
41import { existsSync, readFileSync } from 'node:fs'
42import { basename, join, posix } from 'node:path'
43import { fileURLToPath, pathToFileURL } from 'node:url'
44import { parseArgs } from 'node:util'
45import tsParser from '@typescript-eslint/parser'
46​
47const root = fileURLToPath(new URL(`../`, import.meta.url))
48​
49function git(cwd, ...args) {
50 // Pipe stderr so that a failed attempt in `mergeBase` prints nothing. An
51 // oracle file can exceed the default 1 MiB output buffer.
52 return execFileSync(`git`, args, {
53 cwd,
54 encoding: `utf8`,
55 maxBuffer: 1024 * 1024 * 1024,
56 stdio: [`ignore`, `pipe`, `pipe`],
57 }).trim()
59​
60/**
61 * The commit where this branch left main. Without one, the branch's own
62 * history cannot be found, so this fails instead of comparing too little.
63 */
64export function mergeBase(repo = root) {
65 for (const branch of [`origin/main`, `main`]) {
66 try {
67 return git(repo, `merge-base`, `HEAD`, branch)
68 } catch {
69 // Try the next branch.
70 }
71 }
72 throw new Error(
73 `Cannot find origin/main or main to compare this branch against. Run \`git fetch origin main\`.`,
74 )
76​
77/**
78 * Reads files at the base commit or in the working tree, and parses each once.
79 * A file that does not exist at a revision reads as undefined. Any other
80 * failure to read a file throws, so a budget is never compared with a file
81 * that only seemed to be missing.
82 */
83class SourceReader {
84 #repo
85 #base
86 #baseFiles
87 #texts = new Map()
88 #asts = new Map()
89​
90 constructor(repo, base) {
91 this.#repo = repo
92 this.#base = base
93 }
94​
95 /** Every file at the base commit. */
96 baseFiles() {
97 this.#baseFiles ??= new Set(
98 git(this.#repo, `ls-tree`, `-r`, `--name-only`, this.#base)
99 .split(`\n`)
100 .filter(Boolean),
101 )
102 return this.#baseFiles
103 }
104​
105 text(file, revision) {
106 const key = `${revision}\0${file}`
107 if (!this.#texts.has(key)) {
108 let text
109 if (revision === `head`) {
110 const path = join(this.#repo, file)
111 text = existsSync(path) ? readFileSync(path, `utf8`) : undefined
112 } else if (this.baseFiles().has(file)) {
113 text = git(this.#repo, `show`, `${this.#base}:${file}`)
114 }
115 this.#texts.set(key, text)
116 }
117 return this.#texts.get(key)
118 }
119​
120 ast(file, revision) {
121 const key = `${revision}\0${file}`
122 if (!this.#asts.has(key)) {
123 const text = this.text(file, revision)
124 this.#asts.set(
125 key,
126 text === undefined
127 ? undefined
128 : tsParser.parse(text, {
129 range: true,
130 loc: true,
131 jsx: /\.[jt]sx$/.test(file),
132 }),
133 )
134 }
135 return this.#asts.get(key)
136 }
138​
139function walk(node, visit) {
140 if (node === null || typeof node !== `object`) return
141 if (typeof node.type === `string`) visit(node)
142 for (const [key, child] of Object.entries(node)) {
143 if (key === `parent`) continue
144 if (Array.isArray(child)) child.forEach((item) => walk(item, visit))
145 else if (child && typeof child.type === `string`) walk(child, visit)
146 }
148​
149/** The repository path of a relative module, or undefined for a missing one. */
150function resolveModule(fromFile, source, reader, revision) {
151 if (!source.startsWith(`.`)) return undefined
152 const target = posix.normalize(posix.join(posix.dirname(fromFile), source))
153 const stem = target.replace(/\.(m?js|jsx|tsx?)$/, ``)
154 return [
155 `${stem}.ts`,
156 `${stem}.tsx`,
157 `${stem}.js`,
158 `${stem}.mjs`,
159 `${stem}.jsx`,
160 `${stem}/index.ts`,
161 `${stem}/index.js`,
162 ].find((candidate) => reader.text(candidate, revision) !== undefined)
164​
165function nameOf(node) {
166 return node.name ?? node.value
168​
169/**
170 * The number or string that an expression is: a literal, a constant that the
171 * file declares or imports, or `oracleRuns` of one of those.
172 */
173function valueOf(node, file, reader, revision, depth) {
174 if (node === null || node === undefined || depth > 25) return undefined
175 if (
176 node.type === `Literal` &&
177 (typeof node.value === `number` || typeof node.value === `string`)
178 ) {
179 return node.value
180 }
181 if (node.type === `TemplateLiteral` && node.expressions.length === 0) {
182 return node.quasis[0].value.cooked
183 }
184 if (node.type === `Identifier`) {
185 return nameValue(node.name, file, reader, revision, depth + 1)
186 }
187 if (
188 node.type === `CallExpression` &&
189 node.callee.type === `Identifier` &&
190 node.callee.name === `oracleRuns`
191 ) {
192 return valueOf(node.arguments[0], file, reader, revision, depth + 1)
193 }
194 return undefined
196​
197/** The value of a name in a file: an import, or a constant that the file declares. */
198function nameValue(name, file, reader, revision, depth) {
199 const ast = reader.ast(file, revision)
200 if (ast === undefined || depth > 25) return undefined
201 for (const statement of ast.body) {
202 if (statement.type !== `ImportDeclaration`) continue
203 for (const specifier of statement.specifiers) {
204 if (specifier.local.name !== name) continue
205 const target = resolveModule(
206 file,
207 statement.source.value,
208 reader,
209 revision,
210 )
211 if (target === undefined || specifier.type !== `ImportSpecifier`)
212 return undefined
213 return exportValue(
214 target,
215 nameOf(specifier.imported),
216 reader,
217 revision,
218 depth + 1,
219 )
220 }
221 }
222 let found
223 walk(ast, (node) => {
224 if (
225 found !== undefined ||
226 node.type !== `VariableDeclaration` ||
227 node.kind !== `const`
228 )
229 return
230 for (const declarator of node.declarations) {
231 if (declarator.id.type === `Identifier` && declarator.id.name === name) {
232 found = {
233 value: valueOf(declarator.init, file, reader, revision, depth + 1),
234 }
235 return
236 }
237 }
238 })
239 return found?.value
241​
242/** The value of an export of a module, following its re-exports. */
243function exportValue(file, name, reader, revision, depth) {
244 const ast = reader.ast(file, revision)
245 if (ast === undefined || depth > 25) return undefined
246 for (const statement of ast.body) {
247 if (statement.type !== `ExportNamedDeclaration`) continue
248 if (statement.declaration?.type === `VariableDeclaration`) {
249 for (const declarator of statement.declaration.declarations) {
250 if (
251 declarator.id.type === `Identifier` &&
252 declarator.id.name === name
253 ) {
254 return valueOf(declarator.init, file, reader, revision, depth + 1)
255 }
256 }
257 }
258 for (const specifier of statement.specifiers) {
259 if (nameOf(specifier.exported) !== name) continue
260 const local = nameOf(specifier.local)
261 if (statement.source === null) {
262 return nameValue(local, file, reader, revision, depth + 1)
263 }
264 const target = resolveModule(
265 file,
266 statement.source.value,
267 reader,
268 revision,
269 )
270 return target === undefined
271 ? undefined
272 : exportValue(target, local, reader, revision, depth + 1)
273 }
274 }
275 for (const statement of ast.body) {
276 if (
277 statement.type !== `ExportAllDeclaration` ||
278 statement.exported !== null
279 )
280 continue
281 const target = resolveModule(file, statement.source.value, reader, revision)
282 const value =
283 target === undefined
284 ? undefined
285 : exportValue(target, name, reader, revision, depth + 1)
286 if (value !== undefined) return value
287 }
288 return undefined
290​
291function propertyValue(object, name, file, reader, revision) {
292 const property = object.properties.find(
293 (candidate) =>
294 candidate.type === `Property` &&
295 !candidate.computed &&
296 nameOf(candidate.key) === name,
297 )
298 return property === undefined
299 ? undefined
300 : valueOf(property.value, file, reader, revision, 0)
302​
303/** Every keyed run budget in one file at one revision. */
304function runBudgets(file, revision, reader) {
305 const ast = reader.ast(file, revision)
306 const budgets = new Map()
307 if (ast === undefined) return budgets
308 const record = (key, value) => {
309 if (key !== undefined && value !== undefined) budgets.set(key, value)
310 }
311 const value = (node) => valueOf(node, file, reader, revision, 0)
312 walk(ast, (node) => {
313 if (node.type === `CallExpression` && node.callee.type === `Identifier`) {
314 const [first, second, third] = node.arguments
315 if (node.callee.name === `oraclePropertyOptions`) {
316 const property = value(second)
317 if (typeof property === `string`)
318 record(`property ${property}`, value(first))
319 }
320 if (node.callee.name === `oracleRandomParameters`) {
321 const property = value(third)
322 if (typeof property === `string`)
323 record(`property ${property}`, value(first))
324 }
325 }
326 if (node.type === `ObjectExpression`) {
327 const property = propertyValue(node, `property`, file, reader, revision)
328 if (typeof property === `string`) {
329 record(
330 `property ${property}`,
331 propertyValue(node, `defaultRuns`, file, reader, revision),
332 )
333 }
334 const seed = propertyValue(node, `seed`, file, reader, revision)
335 if (typeof seed === `number`) {
336 record(
337 `fixed seed ${seed}`,
338 propertyValue(node, `numRuns`, file, reader, revision),
339 )
340 }
341 }
342 })
343 return budgets
345​
346/** The repository files that a file imports or re-exports, transitively. */
347function dependencies(file, reader, revision) {
348 const found = new Set()
349 const pending = [file]
350 while (pending.length > 0) {
351 const current = pending.pop()
352 const ast = reader.ast(current, revision)
353 if (ast === undefined) continue
354 for (const statement of ast.body) {
355 if (
356 (statement.type === `ImportDeclaration` ||
357 statement.type === `ExportAllDeclaration` ||
358 statement.type === `ExportNamedDeclaration`) &&
359 statement.source
360 ) {
361 const target = resolveModule(
362 current,
363 statement.source.value,
364 reader,
365 revision,
366 )
367 if (target !== undefined && !found.has(target)) {
368 found.add(target)
369 pending.push(target)
370 }
371 }
372 }
373 }
374 return found
376​
377/** Whether a file is an oracle file, by the oracle naming rule. */
378export function isOracleFile(file) {
379 return /oracle.*\.(tsx?|m?js|jsx)$/.test(basename(file))
381​
382/**
383 * The budgets that an oracle file uses at a revision: its own, and those in
384 * the non-oracle modules that it reaches. Its own budget wins a shared key.
385 */
386function scopeBudgets(file, revision, reader) {
387 const budgets = new Map()
388 for (const module of dependencies(file, reader, revision)) {
389 if (isOracleFile(module)) continue
390 for (const [key, value] of runBudgets(module, revision, reader))
391 budgets.set(key, value)
392 }
393 for (const [key, value] of runBudgets(file, revision, reader))
394 budgets.set(key, value)
395 return budgets
397​
398/**
399 * Every keyed run budget that the branch lowered or removed, by the oracle
400 * file that used it at base. A removed budget has no `now`. The head side is
401 * the working tree of `repo`, and the base side is the commit `base`.
402 */
403export function loweredRunBudgetsBetween(repo, base) {
404 const reader = new SourceReader(repo, base)
405 const changed = new Set(
406 [
407 git(repo, `diff`, `--name-only`, base),
408 git(repo, `ls-files`, `--others`, `--exclude-standard`),
409 ]
410 .flatMap((output) => output.split(`\n`))
411 .filter(Boolean),
412 )
413 const oracles = [
414 ...new Set(
415 [...reader.baseFiles(), ...changed].filter((file) => isOracleFile(file)),
416 ),
417 ]
418 const scopes = { base: new Map(), head: new Map() }
419 const scope = (file, revision) => {
420 if (!scopes[revision].has(file))
421 scopes[revision].set(file, scopeBudgets(file, revision, reader))
422 return scopes[revision].get(file)
423 }
424 const atHead = oracles.filter(
425 (file) => reader.text(file, `head`) !== undefined,
426 )
427 const lowered = []
428 for (const file of oracles) {
429 if (reader.text(file, `base`) === undefined) continue
430 const affected = [file, ...dependencies(file, reader, `head`)].some(
431 (candidate) => changed.has(candidate),
432 )
433 if (!affected) continue
434 for (const [key, was] of scope(file, `base`)) {
435 let now = scope(file, `head`).get(key)
436 if (now === undefined) {
437 const holders = atHead.filter(
438 (other) => other !== file && scope(other, `head`).has(key),
439 )
440 if (holders.length === 0) {
441 lowered.push({ file, key, was })
442 continue
443 }
444 // A key that another file already had at base is that file's own.
445 const movedTo = holders.filter(
446 (other) => !scope(other, `base`).has(key),
447 )
448 if (movedTo.length !== 1) continue
449 now = scope(movedTo[0], `head`).get(key)
450 }
451 if (now < was) lowered.push({ file, key, was, now })
452 }
453 }
454 return lowered
456​
457/** Every keyed run budget that the branch lowered or removed, in this repository. */
458export function loweredRunBudgets() {
459 return loweredRunBudgetsBetween(root, mergeBase())
461​
462export function describeLoweredRunBudget({ key, was, now }) {
463 return now === undefined
464 ? `${key}: run budget removed (was ${was})`
465 : `${key}: run budget lowered from ${was} to ${now}`
467​
468// Importing this module, as the lint script does, must not run the report.
469if (
470 process.argv[1] !== undefined &&
471 import.meta.url === pathToFileURL(process.argv[1]).href
472) {
473 const { values: options } = parseArgs({
474 options: { format: { type: `string`, default: `text` } },
475 })
476 const lowered = loweredRunBudgets()
477 for (const budget of lowered) {
478 const message = describeLoweredRunBudget(budget)
479 if (options.format === `github`) {
480 console.log(
481 `::warning file=${budget.file},title=${budget.now === undefined ? `Removed` : `Lowered`} oracle run budget::${message}`,
482 )
483 } else {
484 console.log(`${budget.file}: ${message}`)
485 }
486 }
487 process.exitCode = lowered.length > 0 && options.format === `text` ? 1 : 0