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

replay-observation-oracle.test.js

250 lines9.1 KB

1/**
2 * A completed-history count is output data, not a generated-property budget.
3 * The maintainer's 2026-10-28 decision permits the typed OracleReplayWitness
4 * record in its shared writer only when every value use serializes that record.
5 * AGENTS.md still requires one-run unpinned property options to be reported.
6 * A type annotation cannot excuse an options alias, escape, mutation or second
7 * use. The initializer must be a plain data record with witness fields; custom
8 * serialization hooks can receive the record without a binding reference.
9 * This boundary owns only that distinction, not all no-disabled syntax.
10 *
11 * The finite source grammar varies location, annotation, value use, type-only
12 * queries, JSON bindings and record spelling. Its intent model knows whether
13 * the authored program is exclusively
14 * recording a witness; it never parses source or invokes the rule. ESLint's
15 * real TypeScript parser and no-disabled rule supply the report observation.
16 * The comparison runs after linting and retains every report, including parser
17 * errors. There is no random sampling, filesystem fixture or external process.
18 * Global JSON.stringify is the supported serializer; its unmodified standard
19 * behavior is a trusted premise. Global monkeypatches are outside this law.
20 * Other serializers,
21 * destructuring and intermodule flow are deliberately outside the allowance.
22 */
23import assert from 'node:assert/strict'
24import tsParser from '@typescript-eslint/parser'
25import { Linter } from 'eslint'
26import { afterAll, test } from 'vitest'
27import { declareOracle } from '../../packages/db/tests/oracle-declaration.js'
28import { createOracleReach } from '../../packages/db/tests/oracle-reach.js'
29import noDisabled from './rules/no-disabled.js'
30​
31const writer = '/repo/packages/db/tests/oracle-replay-witness.ts'
32const flows = [
33 'serialize',
34 'budget',
35 'both',
36 'alias',
37 'escape',
38 'reassign',
39 'shadow-json',
40 'read-field',
41 'replacer',
42 'export',
43 'runtime-typeof',
45const jsonBindings = [
46 'builtin',
47 'type-alias',
48 'interface',
49 'import-type',
50 'import-type-specifier',
51 'ambient-value',
52 'outer-value-inner-type',
54const programs = []
55for (const location of ['writer', 'lookalike'])
56 for (const annotation of ['witness', 'other', 'none'])
57 for (const flow of flows)
58 for (const name of ['record', 'serializedProof'])
59 for (const typeQuery of ['none', 'direct', 'qualified', 'before'])
60 for (const jsonBinding of jsonBindings) {
61 // An export inside a function is illegal TypeScript. Other axes
62 // remain independent; the grammar never relies on parser recovery.
63 if (flow === 'export' && jsonBinding === 'outer-value-inner-type')
64 continue
65 programs.push({
66 location,
67 annotation,
68 flow,
69 name,
70 typeQuery,
71 jsonBinding,
72 initializer: 'plain',
73 })
74 }
75// Custom hooks challenge the otherwise admissible recording programs. Crossing
76// them with already rejected uses would hide whether this new guard runs.
77for (const program of [...programs])
78 if (
79 program.location === 'writer' &&
80 program.annotation === 'witness' &&
81 program.flow === 'serialize' &&
82 !['ambient-value', 'outer-value-inner-type'].includes(program.jsonBinding)
83 )
84 for (const initializer of [
85 'spread',
86 'method',
87 'accessor',
88 'prototype',
89 'computed',
90 ])
91 programs.push({ ...program, initializer })
92​
93// Only a dedicated recording program emits a count observation. Every other
94// authored program has an unpinned literal count whose enforcement must remain.
95function expectedReports(program) {
96 return program.location === 'writer' &&
97 program.annotation === 'witness' &&
98 program.flow === 'serialize' &&
99 program.jsonBinding !== 'ambient-value' &&
100 program.jsonBinding !== 'outer-value-inner-type' &&
101 program.initializer === 'plain'
102 ? []
103 : ['singleRun']
105​
106function source(program) {
107 const { name, annotation, flow } = program
108 const type =
109 annotation === 'none'
110 ? ''
111 : `: ${annotation === 'witness' ? 'OracleReplayWitness' : 'OtherRecord'}`
112 const hook =
113 'toJSON(this: OracleReplayWitness) { fc.assert(property, this); return null }'
114 const custom =
115 program.initializer === 'spread'
116 ? '...budgetHook,'
117 : program.initializer === 'prototype'
118 ? '__proto__: budgetHook,'
119 : program.initializer === 'method'
120 ? `${hook},`
121 : program.initializer === 'accessor'
122 ? 'get toJSON() { return function() { fc.assert(property, this); return null } },'
123 : program.initializer === 'computed'
124 ? '["toJSON"]() { fc.assert(property, this); return null },'
125 : ''
126 const record = `const budgetHook = { ${hook} };\n${flow === 'export' ? 'export ' : ''}${flow === 'reassign' ? 'let' : 'const'} ${name}${type} = { ${custom} numRuns: 1, failed: false }`
127 const serialize = `appendFileSync(channel, JSON.stringify(${name}));`
128 const use =
129 flow === 'serialize' || flow === 'export'
130 ? `${serialize}\n${serialize}`
131 : flow === 'budget'
132 ? `fc.assert(property, ${name})`
133 : flow === 'both'
134 ? `${serialize}\nfc.assert(property, ${name})`
135 : flow === 'alias'
136 ? `const options = ${name}; fc.assert(property, options)`
137 : flow === 'escape'
138 ? `send(${name})`
139 : flow === 'reassign'
140 ? `${name} = replacement; ${serialize}`
141 : flow === 'shadow-json'
142 ? serialize
143 : flow === 'replacer'
144 ? `JSON.stringify(${name}, (_key, value) => { fc.assert(property, value); return value })`
145 : flow === 'runtime-typeof'
146 ? `${serialize}\ntypeof ${name}`
147 : `${serialize}\nfc.assert(property, { numRuns: ${name}.numRuns })`
148 const query =
149 program.typeQuery === 'none'
150 ? ''
151 : `type Snapshot = typeof ${name}${program.typeQuery === 'qualified' ? '.numRuns' : ''};`
152 const body = `${record};\n${program.typeQuery === 'before' ? query : ''}\n${use};\n${program.typeQuery === 'before' ? '' : query}`
153 const rendered =
154 flow === 'shadow-json' ? `function encode(JSON) { ${body} }` : body
155 if (program.jsonBinding === 'outer-value-inner-type')
156 return `function outer(JSON) { { type JSON = { marker: true }; ${rendered} } }`
157 const prefix =
158 program.jsonBinding === 'type-alias'
159 ? 'type JSON = { marker: true };'
160 : program.jsonBinding === 'interface'
161 ? 'interface JSON { marker: true };'
162 : program.jsonBinding === 'import-type'
163 ? 'import type JSON from "types";'
164 : program.jsonBinding === 'import-type-specifier'
165 ? 'import { type JSON } from "types";'
166 : program.jsonBinding === 'ambient-value'
167 ? 'declare const JSON: unknown;'
168 : ''
169 return `${prefix}\n${rendered}`
171​
172// This driver asks the actual rule for all reports, rather than classifying its
173// AST ourselves. Binding spelling must not change the observation.
174function reports(program) {
175 return new Linter({ cwd: '/repo' })
176 .verify(
177 source(program),
178 [
179 {
180 files: ['**/*.ts'],
181 languageOptions: {
182 parser: tsParser,
183 parserOptions: { ecmaVersion: 'latest', sourceType: 'module' },
184 },
185 plugins: { oracle: { rules: { 'no-disabled': noDisabled } } },
186 rules: { 'oracle/no-disabled': 'error' },
187 },
188 ],
189 {
190 filename:
191 program.location === 'writer'
192 ? writer
193 : '/repo/packages/db/tests/witness-output.ts',
194 },
195 )
196 .map((report) => report.messageId ?? `parse:${report.message}`)
198​
199function checkReports(program, observed) {
200 assert.deepEqual(observed, expectedReports(program), JSON.stringify(program))
202​
203const stateOf = ({
204 location,
205 annotation,
206 flow,
207 typeQuery,
208 jsonBinding,
209 initializer,
210}) =>
211 `${location}/${annotation}/${flow}/${typeQuery}/${jsonBinding}/${initializer}`
212const states = [...new Set(programs.map(stateOf))]
213const reach = createOracleReach('lint.replay-observation', states, {
214 replaying: false,
215})
216let campaignEntered = false
217afterAll(() => {
218 // Calibrations can be selected independently. Once any source comparison
219 // starts, the finite campaign still owes every declared reach state.
220 if (campaignEntered) reach.assertReached()
221})
222declareOracle({
223 check: [checkReports],
224 model: [expectedReports],
225 grammar: [programs],
226})
227​
228test.each(programs)(
229 'separates replay observations from budgets %j',
230 (program) => {
231 campaignEntered = true
232 reach.beginHistory()
233 const observed = reports(program)
234 reach.reach(stateOf(program))
235 checkReports(program, observed)
236 },
238​
239test.each(['missing-report', 'spurious-report'])(
240 'rejects wrong report observation %s',
241 (fault) => {
242 const program = programs.find(
243 (candidate) =>
244 (expectedReports(candidate).length === 0) ===
245 (fault === 'spurious-report'),
246 )
247 const wrong = expectedReports(program).length === 0 ? ['singleRun'] : []
248 assert.throws(() => checkReports(program, wrong))
249 },