Open History to see the last commit
1import { fc } from '@fast-check/vitest'
2import { afterEach, expect, it } from 'vitest'
3import {
4 oracleRandomParameters,
5 oracleReplayTest,
6 readOracleRunConfig,
7} from '../../db/tests/oracle-config.js'
8import { declareOracle } from '../../db/tests/oracle-declaration.js'
9import { OpSQLiteDriver } from '../src/op-sqlite-driver'
10import { createOpSQLiteTestDatabase } from './helpers/op-sqlite-test-db'
11import {
12 activeCleanupFns,
13 createTempSqlitePath,
14 expectExactAliasRows,
15 queryInjectedResult,
16 readAliasOracleRuns,
17 runActiveCleanupFns,
18 statementResultAliasNames,
19 statementResultFieldNames,
20 withColumnarDriver,
21 writeResultFieldNames,
22} from './op-sqlite-driver-support'
23
24afterEach(runActiveCleanupFns)
25
26/**
27 * Law: SQLiteDriver.query returns the complete ordered object rows supplied by
28 * the database after exec/run writes. SQL aliases remain row data even when
29 * their names match envelope fields, including direct rows made only of write
30 * marker aliases. When OP-SQLite supplies object rows and raw columnar rows
31 * together, the already-decoded object rows are authoritative. Malformed or
32 * incomplete result carriers reject. A bare array whose first entry can be
33 * both a row and a statement envelope has no self-describing interpretation;
34 * its driver must declare `rows` or `statement-results` mode. The declared
35 * mode, rather than reserved field names, decides markerless `{ rows }`
36 * wrappers.
37 * Source: SQLiteDriver's public query contract and op-sqlite's documented
38 * required `QueryResult.rows`, execute `{ rows, columnNames }`, and executeAsync
39 * `{ rawRows, columnNames, rowsAffected }` envelopes.
40 * Domain: deterministic object-row wrappers and columnar rows, including
41 * empty, asymmetric/reordered multirow, legal reserved-looking SQL aliases,
42 * and malformed or conflicting envelopes.
43 * Reference/history grammar: `aliasQueryCase` builds two ordered object rows
44 * directly from unique legal aliases and distinct scalar values. Histories
45 * choose wrapper shape, explicit mode for ambiguous arrays, or columnar
46 * aliases, execute real writes or one SELECT, and then either return the exact
47 * rows or reject an invalid envelope; the reference never calls the production
48 * decoder.
49 * Path/checkpoint: OpSQLiteDriver over a real better-sqlite3 shim, observed
50 * when each query Promise settles. Exact row values, keys, order, and count are
51 * compared.
52 * Refinement evidence: query execution counts prove the SELECT reached the
53 * adapter. Named empty, reordered, duplicated, missing-key, and swapped-value
54 * wrong answers challenge the checker. Normal execution runs the same alias
55 * properties and budgets in retained fixed-seed and seedless-random lanes.
56 * TANSTACK_DB_ORACLE_SEED, TANSTACK_DB_ORACLE_PATH, and TANSTACK_DB_ORACLE_PROPERTY
57 * select one exact replay.
58 * Real-provider refinement: frozen receipts from the published 15.2.7 Native
59 * and Node sources, plus forward receipts from 18.2.1 Native, Node, and browser
60 * sources, prove the shim's accepted envelopes match provider output.
61 * The frozen receipts, envelope-decoding cases, transaction tests, and
62 * malformed-envelope tables are ordinary unit tests in op-sqlite-driver.test.ts;
63 * they compare with fixed values, so they are not part of this law's coverage.
64 * Known omissions: frozen provider values establish result-shape conformance,
65 * not native device/host execution. A real runtime campaign still owns JSI,
66 * worker, and platform delivery.
67 */
68
69type AliasOracleProperty =
70 | `op-sqlite.write-marker-aliases`
71 | `op-sqlite.result-carrier-equivalence`
72 | `op-sqlite.columnar-sql-aliases`
73type AliasOracleParameters = {
74 numRuns: number
75 seed?: number
76 path?: string
77}
78
79const FIXED_ALIAS_ORACLE_SEED = 165903
80
81const aliasOracleRuns = readAliasOracleRuns()
82// Replay coordinates come from the shared TANSTACK_DB_ORACLE_* variables.
83const aliasOracleReplay = readOracleRunConfig()
84
85/**
86 * Registers a property's two campaigns. The fixed campaign pins its seed and
87 * stands aside on every path replay. The random campaign runs in ordinary and
88 * seed-only runs, and as the replay of its property, where the shared helper
89 * returns the recorded path.
90 */
91function registerAliasOracle(
92 property: AliasOracleProperty,
93 title: string,
94 check: (parameters: AliasOracleParameters) => Promise<void>,
95): void {
96 const randomParameters = oracleRandomParameters(
97 aliasOracleRuns,
98 aliasOracleReplay,
99 property,
100 )
101 oracleReplayTest(it)(`${title} [fixed]`, () =>
102 check({ numRuns: aliasOracleRuns, seed: FIXED_ALIAS_ORACLE_SEED }),
103 )
104 oracleReplayTest(it, property)(`${title} [random]`, () =>
105 check(randomParameters),
106 )
107}
108
109const writeResultAliasesArbitrary = fc.uniqueArray(
110 fc.constantFrom(...writeResultFieldNames),
111 {
112 minLength: 1,
113 maxLength: writeResultFieldNames.length,
114 },
115)
116const statementResultAliasesArbitrary = fc.uniqueArray(
117 fc.constantFrom(...statementResultAliasNames),
118 {
119 minLength: 1,
120 maxLength: statementResultAliasNames.length,
121 },
122)
123
124function isLegalAliasSequence(
125 aliases: ReadonlyArray<string>,
126 allowedAliases: ReadonlyArray<string>,
127): boolean {
128 const allowed = new Set(allowedAliases)
129 return (
130 aliases.length >= 1 &&
131 aliases.length <= allowedAliases.length &&
132 new Set(aliases).size === aliases.length &&
133 aliases.every((alias) => allowed.has(alias))
134 )
135}
136
137function expectAliasGrammar<TAlias extends string>(
138 arbitrary: fc.Arbitrary<Array<TAlias>>,
139 allowedAliases: ReadonlyArray<TAlias>,
140): void {
141 // Singletons ablate every other alias. Full and reversed witnesses exercise
142 // both length boundaries and order without changing the legal domain.
143 const witnesses = [
144 ...allowedAliases.map((alias) => [alias]),
145 [...allowedAliases],
146 [...allowedAliases].reverse(),
147 ]
148 const observed = new Set<string>()
149
150 fc.assert(
151 fc.property(arbitrary, (aliases) => {
152 expect(isLegalAliasSequence(aliases, allowedAliases)).toBe(true)
153 observed.add(JSON.stringify(aliases))
154 }),
155 {
156 seed: FIXED_ALIAS_ORACLE_SEED,
157 numRuns: 50,
158 examples: witnesses.map((aliases) => [aliases]),
159 },
160 )
161
162 witnesses.forEach((aliases) => {
163 expect(observed).toContain(JSON.stringify(aliases))
164 })
165 expect(isLegalAliasSequence([], allowedAliases)).toBe(false)
166 expect(
167 isLegalAliasSequence(
168 [allowedAliases[0]!, allowedAliases[0]!],
169 allowedAliases,
170 ),
171 ).toBe(false)
172 expect(isLegalAliasSequence([`not-an-op-sqlite-alias`], allowedAliases)).toBe(
173 false,
174 )
175}
176
177it(`controls alias grammar reconstruction, ablation, range, and exclusion`, () => {
178 expectAliasGrammar(writeResultAliasesArbitrary, writeResultFieldNames)
179 expectAliasGrammar(statementResultAliasesArbitrary, statementResultAliasNames)
180})
181
182registerAliasOracle(
183 `op-sqlite.write-marker-aliases`,
184 `preserves generated single-row write-marker aliases in direct row arrays`,
185 async (parameters) => {
186 await fc.assert(
187 fc.asyncProperty(writeResultAliasesArbitrary, async (aliases) => {
188 const row = Object.fromEntries(
189 aliases.map((alias, index) => [alias, `${index}:${alias}`]),
190 )
191 const actual = await queryInjectedResult<Record<string, unknown>>([row])
192 expectExactAliasRows(actual, [row])
193 }),
194 {
195 ...parameters,
196 ...(parameters.path === undefined
197 ? { examples: [[[`rowsAffected`]], [[...writeResultFieldNames]]] }
198 : { endOnFailure: true }),
199 },
200 )
201 },
202)
203
204registerAliasOracle(
205 `op-sqlite.result-carrier-equivalence`,
206 `returns the same rows across equivalent documented result carriers`,
207 async (parameters) => {
208 await fc.assert(
209 fc.asyncProperty(statementResultAliasesArbitrary, async (aliases) => {
210 const { expected } = aliasQueryCase(aliases)
211 const rawRows = expected.map((row) =>
212 aliases.map((alias) => row[alias]),
213 )
214 const equivalentResults: ReadonlyArray<{
215 result: unknown
216 arrayResultMode?: `rows` | `statement-results`
217 }> = [
218 { result: expected, arrayResultMode: `rows` },
219 { result: { rows: expected } },
220 { result: { resultRows: expected } },
221 {
222 result: [{ rowsAffected: 0, rows: expected }],
223 arrayResultMode: `statement-results`,
224 },
225 {
226 result: {
227 rowsAffected: 0,
228 rows: expected,
229 columnNames: aliases,
230 },
231 },
232 { result: { rowsAffected: 0, rawRows, columnNames: aliases } },
233 {
234 result: {
235 rowsAffected: 0,
236 rows: expected,
237 rawRows,
238 columnNames: aliases,
239 },
240 },
241 { result: { results: [{ rows: expected }] } },
242 ]
243
244 for (const { result, arrayResultMode } of equivalentResults) {
245 const actual = await queryInjectedResult<Record<string, unknown>>(
246 result,
247 arrayResultMode,
248 )
249 expectExactAliasRows(actual, expected)
250 }
251 }),
252 {
253 ...parameters,
254 ...(parameters.path === undefined
255 ? {
256 examples: [
257 [[`rowsAffected`]],
258 [[`rows`, `rawRows`, `columnNames`, `ordinary_name`]],
259 ],
260 }
261 : { endOnFailure: true }),
262 },
263 )
264 },
265)
266
267function quoteIdentifier(identifier: string): string {
268 return `"${identifier.replaceAll(`"`, `""`)}"`
269}
270
271function aliasValue(
272 alias: string,
273 rowIndex: number,
274 columnIndex: number,
275): string {
276 return `${rowIndex === 0 ? `left` : `right`}:${columnIndex}:${alias}`
277}
278
279function aliasQueryCase(aliases: ReadonlyArray<string>): {
280 sql: string
281 params: Array<unknown>
282 expected: Array<Record<string, unknown>>
283} {
284 const rowValues = [0, 1].map((rowIndex) =>
285 aliases.map((alias, columnIndex) =>
286 aliasValue(alias, rowIndex, columnIndex),
287 ),
288 )
289 const selectList = aliases
290 .map((alias) => `? AS ${quoteIdentifier(alias)}`)
291 .join(`, `)
292 return {
293 sql: `SELECT ${selectList} UNION ALL SELECT ${selectList}`,
294 params: [...rowValues[0]!, ...rowValues[1]!],
295 expected: rowValues.map((values) =>
296 Object.fromEntries(aliases.map((alias, index) => [alias, values[index]])),
297 ),
298 }
299}
300
301it(`preserves every statement-result field name when used as a SQL alias`, async () => {
302 await withColumnarDriver(async ({ driver, queryExecutions }) => {
303 const aliases = statementResultFieldNames
304 const { sql, params, expected } = aliasQueryCase(aliases)
305
306 const actual = await driver.query<Record<string, unknown>>(sql, params)
307 expect(queryExecutions()).toBe(1)
308 expectExactAliasRows(actual, expected)
309 })
310})
311
312it(`preserves statement-result field names in direct row arrays`, async () => {
313 const dbPath = createTempSqlitePath()
314 const database = createOpSQLiteTestDatabase({
315 filename: dbPath,
316 resultShape: `rows-array`,
317 })
318 activeCleanupFns.push(() => Promise.resolve(database.close()))
319 const aliases = statementResultFieldNames
320 const { sql, params, expected } = aliasQueryCase(aliases)
321
322 expectExactAliasRows(
323 await new OpSQLiteDriver({ database }).query<Record<string, unknown>>(
324 sql,
325 params,
326 ),
327 expected,
328 )
329})
330
331registerAliasOracle(
332 `op-sqlite.columnar-sql-aliases`,
333 `preserves generated legal SQL aliases through v14 columnar rows`,
334 async (parameters) => {
335 await withColumnarDriver(async ({ driver, queryExecutions }) => {
336 await fc.assert(
337 fc.asyncProperty(statementResultAliasesArbitrary, async (aliases) => {
338 const executionsBefore = queryExecutions()
339 const { sql, params, expected } = aliasQueryCase(aliases)
340 let actual: ReadonlyArray<Record<string, unknown>>
341 try {
342 actual = await driver.query<Record<string, unknown>>(sql, params)
343 } catch (error) {
344 expect(queryExecutions()).toBe(executionsBefore + 1)
345 throw error
346 }
347 expect(queryExecutions()).toBe(executionsBefore + 1)
348 expectExactAliasRows(actual, expected)
349 }),
350 {
351 ...parameters,
352 ...(parameters.path === undefined
353 ? { examples: [[[...statementResultFieldNames]]] }
354 : { endOnFailure: true }),
355 },
356 )
357 })
358 },
359)
360
361// The reference rows for a SQL alias case come from the alias list alone: no
362// production decoder runs here. Each row maps every alias to its own scalar.
363declareOracle({
364 model: [aliasQueryCase],
365 grammar: [writeResultAliasesArbitrary, statementResultAliasesArbitrary],
366})
367
368const reservedAliasWrongAnswers = (() => {
369 const aliases = [`rows`, `rowsAffected`, `ordinary_name`]
370 const { expected } = aliasQueryCase(aliases)
371 const first = expected[0]!
372 const second = expected[1]!
373 return [
374 { name: `silently empty result`, actual: [] },
375 {
376 name: `missing reserved alias`,
377 actual: [
378 Object.fromEntries(
379 Object.entries(first).filter(([alias]) => alias !== `rowsAffected`),
380 ),
381 second,
382 ],
383 },
384 {
385 name: `swapped reserved values`,
386 actual: [
387 { ...first, rows: first.rowsAffected, rowsAffected: first.rows },
388 second,
389 ],
390 },
391 { name: `duplicated first row`, actual: [first, first] },
392 ]
393})()
394
395it.each(reservedAliasWrongAnswers)(
396 `reserved-alias checker rejects wrong answer: $name`,
397 ({ actual }) => {
398 const { expected } = aliasQueryCase([
399 `rows`,
400 `rowsAffected`,
401 `ordinary_name`,
402 ])
403 expect(() => expectExactAliasRows(actual, expected)).toThrow(
404 `op-sqlite reserved-alias exact-row law violated`,
405 )
406 },
407)
408
409it(`reserved-alias checker accepts the independent reference rows`, () => {
410 const { expected } = aliasQueryCase([`rows`, `rowsAffected`, `ordinary_name`])
411 expectExactAliasRows(expected, expected)
412})
413
414it(`reserved-alias checker shrinks and replays the same row-law violation`, () => {
415 const challenge = (aliases: ReadonlyArray<string>) => {
416 const { expected } = aliasQueryCase(aliases)
417 expectExactAliasRows([], expected)
418 }
419 const originalAliases = statementResultFieldNames
420 expect(() => challenge(originalAliases)).toThrow(
421 `op-sqlite reserved-alias exact-row law violated`,
422 )
423
424 const property = fc.property(
425 fc.uniqueArray(fc.constantFrom(...statementResultAliasNames), {
426 minLength: 1,
427 maxLength: statementResultAliasNames.length,
428 }),
429 challenge,
430 )
431 const original = fc.check(property, {
432 seed: 165903,
433 numRuns: 20,
434 })
435 expect(original.failed).toBe(true)
436 expect(original.error).toContain(
437 `op-sqlite reserved-alias exact-row law violated`,
438 )
439 if (original.counterexamplePath === null) {
440 throw new Error(`Missing reserved-alias calibration replay path`)
441 }
442 const reduced = fc.check(property, {
443 seed: original.seed,
444 path: original.counterexamplePath,
445 numRuns: 1,
446 endOnFailure: true,
447 })
448 expect(reduced.failed).toBe(true)
449 expect(reduced.error).toContain(
450 `op-sqlite reserved-alias exact-row law violated`,
451 )
452 expect(reduced.counterexample).toEqual(original.counterexample)
453 expect(reduced.counterexample?.[0].length).toBeLessThan(
454 originalAliases.length,
455 )
456})