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

shared-driver-fairness-oracle.test.ts

555 lines17.2 KB

1/**
2 * Node campaign for the shared-driver K=1 contract documented in
3 * `shared-driver-fairness-oracle.ts`. Fixed histories prove neutral reach and a
4 * persist storm; generated legal histories vary both lane sizes, mutation
5 * width, and tail order. Public rows and logical completion checkpoints are
6 * checked independently of production scheduling, and an executable
7 * named persist-first FIFO wrong answer proves the checker rejects the original
8 * fault. Grammar controls reconstruct that witness, exercise the bounded
9 * marginals, reject a nearby invalid storm, and ablate tail-order variation.
10 * The identical generated property runs in retained fixed-seed and seedless
11 * random lanes. Supplying both TANSTACK_DB_DRIVER_FAIRNESS_SEED and
12 * TANSTACK_DB_DRIVER_FAIRNESS_PATH replaces those lanes with one checked
13 * seed+shrink-path replay. An axis-removal calibration proves that removing
14 * tail-order variation loses hydrate-before-later-persist histories.
15 */
16import { mkdtempSync, rmSync } from 'node:fs'
17import { tmpdir } from 'node:os'
18import { join } from 'node:path'
19import fc from 'fast-check'
20import { describe, expect, it } from 'vitest'
21import {
22 SHARED_DRIVER_FAIRNESS_BOUND,
23 createPersistFirstFaultObservation,
24 findSharedDriverFairnessViolation,
25 observeSharedDriverFairness,
26} from './shared-driver-fairness-oracle'
27import { createWASQLiteTestDatabase } from './helpers/wa-sqlite-test-db'
28import type {
29 SharedDriverFairnessObservation,
30 SharedDriverFairnessOptions,
31 SharedDriverFairnessScenario,
32 SharedDriverFairnessWork,
33} from './shared-driver-fairness-oracle'
34​
35const FIXED_SEED = 165_905
36const GENERATED_RUNS = 12
37const HYDRATE_COUNT_RANGE = { min: 2, max: 7 } as const
38const PERSIST_COUNT_RANGE = { min: 3, max: 7 } as const
39const MUTATIONS_PER_PERSIST_RANGE = { min: 1, max: 3 } as const
40​
41type FairnessReplayEnvironment = Record<string, string | undefined>
42​
43type FairnessReplayConfig = {
44 seed: number
45 path: string
47​
48type FairnessPropertyMode = {
49 label: `fixed-seed` | `seedless-random` | `checked-replay`
50 seed?: number
51 path?: string
53​
54function readFairnessReplayConfig(
55 environment: FairnessReplayEnvironment = process.env,
56): FairnessReplayConfig | undefined {
57 const seedText = environment.TANSTACK_DB_DRIVER_FAIRNESS_SEED
58 const path = environment.TANSTACK_DB_DRIVER_FAIRNESS_PATH
59 if (seedText === undefined && path === undefined) return undefined
60 if (seedText === undefined || path === undefined) {
61 throw new Error(
62 `TANSTACK_DB_DRIVER_FAIRNESS_SEED and TANSTACK_DB_DRIVER_FAIRNESS_PATH must be supplied together`,
63 )
64 }
65​
66 const seed = Number(seedText)
67 if (seedText.trim() === `` || !Number.isSafeInteger(seed)) {
68 throw new Error(`TANSTACK_DB_DRIVER_FAIRNESS_SEED must be an integer`)
69 }
70 if (!/^\d+(?::\d+)*$/.test(path)) {
71 throw new Error(
72 `TANSTACK_DB_DRIVER_FAIRNESS_PATH must contain colon-separated nonnegative integers`,
73 )
74 }
75 return { seed, path }
77​
78function createFairnessPropertyModes(
79 replay: FairnessReplayConfig | undefined,
80): ReadonlyArray<FairnessPropertyMode> {
81 if (replay) {
82 return [{ label: `checked-replay`, ...replay }]
83 }
84 return [
85 { label: `fixed-seed`, seed: FIXED_SEED },
86 { label: `seedless-random` },
87 ]
89​
90function readFairnessCalibration(
91 environment: FairnessReplayEnvironment = process.env,
92): SharedDriverFairnessOptions {
93 const fault = environment.TANSTACK_DB_DRIVER_FAIRNESS_CALIBRATION
94 if (fault === undefined) return {}
95 if (fault !== `persist-first-fifo`) {
96 throw new Error(
97 `TANSTACK_DB_DRIVER_FAIRNESS_CALIBRATION must be persist-first-fifo`,
98 )
99 }
100 return { schedulingFault: fault }
102​
103const fairnessPropertyModes = createFairnessPropertyModes(
104 readFairnessReplayConfig(),
106const fairnessCalibration = readFairnessCalibration()
107​
108type WorkKind = SharedDriverFairnessWork[`kind`]
109​
110type GeneratedFairnessHistory = {
111 hydrateCount: number
112 persistCount: number
113 mutationsPerPersist: number
114 orderedKinds: ReadonlyArray<WorkKind>
115 replayHistory: string
117​
118type GeneratedTailEntry = {
119 kind: WorkKind
120 token: string
122​
123function createScenario(
124 id: string,
125 orderedKinds: ReadonlyArray<WorkKind>,
126 mutationsPerPersist = 1,
127): SharedDriverFairnessScenario {
128 let hydrateIndex = 0
129 let persistIndex = 0
130 return {
131 id,
132 work: orderedKinds.map((kind) => {
133 if (kind === `persist`) {
134 const index = persistIndex++
135 return {
136 kind,
137 id: `persist-${index}`,
138 mutationsPerPersist,
139 }
140 }
141 const index = hydrateIndex++
142 return {
143 kind,
144 id: `hydrate-${index}`,
145 seededRows: [
146 { id: `row-${index}-0`, value: index * 10 },
147 { id: `row-${index}-1`, value: index * 10 + 1 },
148 ],
149 }
150 }),
151 }
153​
154function expectedHydratedCollections(scenario: SharedDriverFairnessScenario) {
155 return scenario.work.flatMap((work) =>
156 work.kind === `hydrate`
157 ? [
158 {
159 collectionId: `${scenario.id}-${work.id}`,
160 rows: work.seededRows.map((row) => ({ ...row })),
161 },
162 ]
163 : [],
164 )
166​
167async function withNodeScenario(
168 scenario: SharedDriverFairnessScenario,
169 assertion: (
170 observation: SharedDriverFairnessObservation,
171 ) => void | Promise<void>,
172 options: SharedDriverFairnessOptions = {},
173): Promise<void> {
174 const directory = mkdtempSync(join(tmpdir(), `db-driver-fairness-`))
175 let primaryFailure: unknown
176 try {
177 const observation = await observeSharedDriverFairness(
178 () =>
179 createWASQLiteTestDatabase({
180 filename: join(directory, `state.sqlite`),
181 }),
182 scenario,
183 options,
184 )
185 await assertion(observation)
186 } catch (error) {
187 primaryFailure = error
188 }
189​
190 let nodeCleanupFailure: unknown
191 try {
192 rmSync(directory, { recursive: true, force: true })
193 } catch (error) {
194 nodeCleanupFailure = error
195 }
196​
197 if (primaryFailure !== undefined) {
198 if (nodeCleanupFailure !== undefined) {
199 const primaryMessage =
200 primaryFailure instanceof Error
201 ? primaryFailure.message
202 : String(primaryFailure)
203 const cleanupMessage =
204 nodeCleanupFailure instanceof Error
205 ? nodeCleanupFailure.message
206 : String(nodeCleanupFailure)
207 throw new Error(
208 `${primaryMessage}; node cleanup diagnostics: ${cleanupMessage}`,
209 )
210 }
211 throw primaryFailure
212 }
213 if (nodeCleanupFailure !== undefined) throw nodeCleanupFailure
215​
216function expectObservationReach(
217 observation: SharedDriverFairnessObservation,
218): void {
219 const expectedHydrates = expectedHydratedCollections(observation.scenario)
220 expect(observation.admittedHydrateIds).toEqual(
221 expectedHydrates.map(({ collectionId }) => collectionId),
222 )
223 expect(observation.hydrationCompletions).toHaveLength(expectedHydrates.length)
224 // Actual rows come from the public Collection after preload. The expected
225 // rows above are derived independently from the generated seed history.
226 expect(observation.hydratedCollections).toEqual(expectedHydrates)
228​
229function expectFairObservation(
230 observation: SharedDriverFairnessObservation,
231): void {
232 expectObservationReach(observation)
233 const violation = findSharedDriverFairnessViolation(
234 observation,
235 SHARED_DRIVER_FAIRNESS_BOUND,
236 )
237 if (violation) {
238 throw new Error(
239 `shared-driver fairness mismatch at ${violation.checkpoint.collectionId}: ` +
240 `${violation.checkpoint.completedPersistIds.length} persists completed ` +
241 `(maximum ${violation.expectedMaximumCompletedPersists}), ` +
242 `${violation.checkpoint.pendingPersistCount} remained pending ` +
243 `(minimum ${violation.expectedMinimumPendingPersists}); ` +
244 `permitted completed ids: ${JSON.stringify(violation.permittedCompletedPersistIds)}; ` +
245 `cleanup diagnostics: ${JSON.stringify(observation.cleanupFailures)}`,
246 )
247 }
248 expect(observation.cleanupFailures).toEqual([])
250​
251function buildGeneratedHistory(
252 hydrateCount: number,
253 persistCount: number,
254 mutationsPerPersist: number,
255 generatedTail: ReadonlyArray<GeneratedTailEntry>,
256): GeneratedFairnessHistory {
257 return {
258 hydrateCount,
259 persistCount,
260 mutationsPerPersist,
261 orderedKinds: [
262 `persist` as const,
263 ...generatedTail.map(({ kind }) => kind),
264 ],
265 replayHistory: `p0,${generatedTail.map(({ token }) => token).join(`,`)}`,
266 }
268​
269function createGeneratedHistoryArbitrary(
270 tailOrderAxis: `varied` | `removed`,
271): fc.Arbitrary<GeneratedFairnessHistory> {
272 return fc
273 .record({
274 hydrateCount: fc.integer(HYDRATE_COUNT_RANGE),
275 persistCount: fc.integer(PERSIST_COUNT_RANGE),
276 mutationsPerPersist: fc.integer(MUTATIONS_PER_PERSIST_RANGE),
277 })
278 .chain(({ hydrateCount, persistCount, mutationsPerPersist }) => {
279 const tail = [
280 ...Array.from({ length: persistCount - 1 }, (_, index) => ({
281 kind: `persist` as const,
282 token: `p${index + 1}`,
283 })),
284 ...Array.from({ length: hydrateCount }, (_, index) => ({
285 kind: `hydrate` as const,
286 token: `h${index}`,
287 })),
288 ]
289 const orderedTail =
290 tailOrderAxis === `varied`
291 ? fc.shuffledSubarray(tail, {
292 minLength: tail.length,
293 maxLength: tail.length,
294 })
295 : fc.constant(tail)
296 return orderedTail.map((generatedTail) =>
297 buildGeneratedHistory(
298 hydrateCount,
299 persistCount,
300 mutationsPerPersist,
301 generatedTail,
302 ),
303 )
304 })
306​
307function reachesHydrateBeforeLaterPersist(
308 history: GeneratedFairnessHistory,
309): boolean {
310 let hydrateSeen = false
311 for (const kind of history.orderedKinds.slice(1)) {
312 if (kind === `hydrate`) hydrateSeen = true
313 if (kind === `persist` && hydrateSeen) return true
314 }
315 return false
317​
318const generatedHistoryArbitrary = createGeneratedHistoryArbitrary(`varied`)
319const tailOrderAblatedArbitrary = createGeneratedHistoryArbitrary(`removed`)
320let generatedPropertyExecutions = 0
321​
322const generatedFairnessProperty = fc.asyncProperty(
323 generatedHistoryArbitrary,
324 async ({
325 hydrateCount,
326 persistCount,
327 mutationsPerPersist,
328 orderedKinds,
329 replayHistory,
330 }) => {
331 generatedPropertyExecutions++
332 const observationId =
333 `generated-h${hydrateCount}-p${persistCount}-m${mutationsPerPersist}-` +
334 replayHistory.replaceAll(`,`, `-`)
335 await withNodeScenario(
336 createScenario(observationId, orderedKinds, mutationsPerPersist),
337 expectFairObservation,
338 fairnessCalibration,
339 )
340 },
342​
343describe(`shared BrowserWASQLiteDriver fairness oracle`, () => {
344 it(`selects fixed and seedless lanes by default and only replay when requested`, () => {
345 expect(createFairnessPropertyModes(readFairnessReplayConfig({}))).toEqual([
346 { label: `fixed-seed`, seed: FIXED_SEED },
347 { label: `seedless-random` },
348 ])
349 expect(
350 createFairnessPropertyModes(
351 readFairnessReplayConfig({
352 TANSTACK_DB_DRIVER_FAIRNESS_SEED: `42`,
353 TANSTACK_DB_DRIVER_FAIRNESS_PATH: `0:1`,
354 }),
355 ),
356 ).toEqual([{ label: `checked-replay`, seed: 42, path: `0:1` }])
357 expect(readFairnessCalibration({})).toEqual({})
358 expect(
359 readFairnessCalibration({
360 TANSTACK_DB_DRIVER_FAIRNESS_CALIBRATION: `persist-first-fifo`,
361 }),
362 ).toEqual({ schedulingFault: `persist-first-fifo` })
363 })
364​
365 it.each([
366 {
367 name: `seed without path`,
368 environment: { TANSTACK_DB_DRIVER_FAIRNESS_SEED: `42` },
369 message: `must be supplied together`,
370 },
371 {
372 name: `path without seed`,
373 environment: { TANSTACK_DB_DRIVER_FAIRNESS_PATH: `0` },
374 message: `must be supplied together`,
375 },
376 {
377 name: `non-integer seed`,
378 environment: {
379 TANSTACK_DB_DRIVER_FAIRNESS_SEED: `4.2`,
380 TANSTACK_DB_DRIVER_FAIRNESS_PATH: `0`,
381 },
382 message: `must be an integer`,
383 },
384 {
385 name: `invalid shrink path`,
386 environment: {
387 TANSTACK_DB_DRIVER_FAIRNESS_SEED: `42`,
388 TANSTACK_DB_DRIVER_FAIRNESS_PATH: `0:-1`,
389 },
390 message: `colon-separated nonnegative integers`,
391 },
392 ])(`rejects incomplete or invalid replay coordinates: $name`, (probe) => {
393 expect(() => readFairnessReplayConfig(probe.environment)).toThrow(
394 probe.message,
395 )
396 })
397​
398 it(`reconstructs the known persist-first witness, covers range marginals, and rejects a nearby invalid storm`, async () => {
399 const knownWitness = buildGeneratedHistory(2, 4, 1, [
400 { kind: `persist`, token: `p1` },
401 { kind: `persist`, token: `p2` },
402 { kind: `persist`, token: `p3` },
403 { kind: `hydrate`, token: `h0` },
404 { kind: `hydrate`, token: `h1` },
405 ])
406 expect(knownWitness).toEqual({
407 hydrateCount: 2,
408 persistCount: 4,
409 mutationsPerPersist: 1,
410 orderedKinds: [
411 `persist`,
412 `persist`,
413 `persist`,
414 `persist`,
415 `hydrate`,
416 `hydrate`,
417 ],
418 replayHistory: `p0,p1,p2,p3,h0,h1`,
419 })
420​
421 const marginalHistories = [
422 buildGeneratedHistory(2, 3, 1, [
423 { kind: `persist`, token: `p1` },
424 { kind: `persist`, token: `p2` },
425 { kind: `hydrate`, token: `h0` },
426 { kind: `hydrate`, token: `h1` },
427 ]),
428 buildGeneratedHistory(7, 7, 3, [
429 ...Array.from({ length: 6 }, (_, index) => ({
430 kind: `persist` as const,
431 token: `p${index + 1}`,
432 })),
433 ...Array.from({ length: 7 }, (_, index) => ({
434 kind: `hydrate` as const,
435 token: `h${index}`,
436 })),
437 ]),
438 ]
439 expect(
440 marginalHistories.map((history) => [
441 history.hydrateCount,
442 history.persistCount,
443 history.mutationsPerPersist,
444 ]),
445 ).toEqual([
446 [2, 3, 1],
447 [7, 7, 3],
448 ])
449​
450 await expect(
451 withNodeScenario(
452 createScenario(`invalid-storm-boundary`, [
453 `hydrate`,
454 `persist`,
455 `hydrate`,
456 ]),
457 expectFairObservation,
458 ),
459 ).rejects.toThrow(`must begin with its already-running persist`)
460 })
461​
462 it(`reaches cold hydration and preserves independently seeded public rows without queued persists`, async () => {
463 await withNodeScenario(
464 createScenario(`neutral-reach`, [`hydrate`, `hydrate`, `hydrate`]),
465 (observation) => {
466 expectFairObservation(observation)
467 expect(
468 observation.rawDequeues.some((entry) =>
469 entry.sql.startsWith(
470 `SELECT key, value, metadata, row_version FROM`,
471 ),
472 ),
473 ).toBe(true)
474 },
475 )
476 })
477​
478 it(`completes a pending cold hydrate before an unrelated persist backlog drains`, async () => {
479 await withNodeScenario(
480 createScenario(
481 `fixed-persist-storm`,
482 [`persist`, `persist`, `persist`, `hydrate`, `hydrate`],
483 2,
484 ),
485 expectFairObservation,
486 )
487 })
488​
489 it.each(fairnessPropertyModes)(
490 `bounds persist completions for generated ordered cold-hydrate/persist histories in $label mode`,
491 async (mode) => {
492 const executionsBefore = generatedPropertyExecutions
493 await fc.assert(generatedFairnessProperty, {
494 numRuns: GENERATED_RUNS,
495 verbose: 2,
496 ...(mode.seed === undefined ? {} : { seed: mode.seed }),
497 ...(mode.path === undefined ? {} : { path: mode.path }),
498 })
499 expect(generatedPropertyExecutions).toBeGreaterThan(executionsBefore)
500 },
501 )
502​
503 it(`proves tail-order ablation removes a hydrate-before-later-persist history`, () => {
504 const sampleOptions = { seed: FIXED_SEED, numRuns: GENERATED_RUNS }
505 const completeGrammar = fc.sample(generatedHistoryArbitrary, sampleOptions)
506 const tailOrderAblatedGrammar = fc.sample(
507 tailOrderAblatedArbitrary,
508 sampleOptions,
509 )
510​
511 expect(completeGrammar.some(reachesHydrateBeforeLaterPersist)).toBe(true)
512 expect(tailOrderAblatedGrammar.some(reachesHydrateBeforeLaterPersist)).toBe(
513 false,
514 )
515 })
516​
517 it(`rejects the named persist-first FIFO wrong answer through the real package path`, async () => {
518 await withNodeScenario(
519 createScenario(
520 `persist-first-fixture-fault`,
521 [`persist`, `persist`, `persist`, `persist`, `hydrate`, `hydrate`],
522 1,
523 ),
524 (observation) => {
525 expectObservationReach(observation)
526 const violation = findSharedDriverFairnessViolation(observation)
527 if (!violation) {
528 throw new Error(
529 `persist-first scheduling mutant escaped the fairness checker; ` +
530 `cleanup diagnostics: ${JSON.stringify(observation.cleanupFailures)}`,
531 )
532 }
533 expect(violation.checkpoint.completedPersistIds).toHaveLength(4)
534 expect(violation.checkpoint.pendingPersistCount).toBe(0)
535 expect(observation.cleanupFailures).toEqual([])
536 },
537 { schedulingFault: `persist-first-fifo` },
538 )
539 })
540​
541 it(`calibrates the checker against a synthetic persist-first observation`, () => {
542 const scenario = createScenario(
543 `persist-first-checker-calibration`,
544 [`persist`, `persist`, `persist`, `persist`, `hydrate`, `hydrate`],
545 1,
546 )
547 const fault = createPersistFirstFaultObservation(scenario)
548​
549 expect(findSharedDriverFairnessViolation(fault)).toMatchObject({
550 checkpoint: fault.hydrationCompletions[0],
551 expectedMaximumCompletedPersists: 1,
552 expectedMinimumPendingPersists: 3,
553 })
554 })
555})