Open History to see the last commit
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 * The shared fixture holds the first `BEGIN IMMEDIATE` while cold `preload()`
16 * calls queue. This file supplies BetterSQLite; the receiving witness in
17 * `../e2e/shared-driver-fairness-oracle.opfs.spec.ts` uses the same fixture with a
18 * Chromium OPFSCoopSyncVFS worker after release. It checks rows and K=1 cuts.
19 * Generated failures record the original and reduced histories with their
20 * violated laws and checkpoints; the report says whether shrinking retained
21 * that violation. The full logical persist completion order checks lane FIFO.
22 */
23import { mkdtempSync, rmSync } from 'node:fs'
24import { tmpdir } from 'node:os'
25import { join } from 'node:path'
26import fc from 'fast-check'
27import { describe, expect, it } from 'vitest'
28import {
29 SHARED_DRIVER_FAIRNESS_BOUND,
30 createPersistFirstFaultObservation,
31 findSharedDriverFairnessViolation,
32 observeSharedDriverFairness,
33} from './shared-driver-fairness-oracle'
34import { createWASQLiteTestDatabase } from './helpers/wa-sqlite-test-db'
35import type {
36 SharedDriverFairnessObservation,
37 SharedDriverFairnessOptions,
38 SharedDriverFairnessScenario,
39 SharedDriverFairnessWork,
40} from './shared-driver-fairness-oracle'
41
42const FIXED_SEED = 165_905
43const GENERATED_RUNS = 12
44const HYDRATE_COUNT_RANGE = { min: 2, max: 7 } as const
45const PERSIST_COUNT_RANGE = { min: 3, max: 7 } as const
46const MUTATIONS_PER_PERSIST_RANGE = { min: 1, max: 3 } as const
47
48type FairnessReplayEnvironment = Record<string, string | undefined>
49
50type FairnessReplayConfig = {
51 seed: number
52 path: string
53}
54
55type FairnessPropertyMode = {
56 label: `fixed-seed` | `seedless-random` | `checked-replay`
57 seed?: number
58 path?: string
59}
60
61class FairnessOracleFailure extends Error {
62 constructor(
63 readonly law: string,
64 readonly checkpoint: string,
65 cause: unknown,
66 ) {
67 super(cause instanceof Error ? cause.message : String(cause), { cause })
68 }
69}
70
71function checkAt(law: string, checkpoint: string, assertion: () => void): void {
72 try {
73 assertion()
74 } catch (error) {
75 throw new FairnessOracleFailure(law, checkpoint, error)
76 }
77}
78
79function readFairnessReplayConfig(
80 environment: FairnessReplayEnvironment = process.env,
81): FairnessReplayConfig | undefined {
82 const seedText = environment.TANSTACK_DB_DRIVER_FAIRNESS_SEED
83 const path = environment.TANSTACK_DB_DRIVER_FAIRNESS_PATH
84 if (seedText === undefined && path === undefined) return undefined
85 if (seedText === undefined || path === undefined) {
86 throw new Error(
87 `TANSTACK_DB_DRIVER_FAIRNESS_SEED and TANSTACK_DB_DRIVER_FAIRNESS_PATH must be supplied together`,
88 )
89 }
90
91 const seed = Number(seedText)
92 if (seedText.trim() === `` || !Number.isSafeInteger(seed)) {
93 throw new Error(`TANSTACK_DB_DRIVER_FAIRNESS_SEED must be an integer`)
94 }
95 if (!/^\d+(?::\d+)*$/.test(path)) {
96 throw new Error(
97 `TANSTACK_DB_DRIVER_FAIRNESS_PATH must contain colon-separated nonnegative integers`,
98 )
99 }
100 return { seed, path }
101}
102
103function createFairnessPropertyModes(
104 replay: FairnessReplayConfig | undefined,
105): ReadonlyArray<FairnessPropertyMode> {
106 if (replay) {
107 return [{ label: `checked-replay`, ...replay }]
108 }
109 return [
110 { label: `fixed-seed`, seed: FIXED_SEED },
111 { label: `seedless-random` },
112 ]
113}
114
115function readFairnessCalibration(
116 environment: FairnessReplayEnvironment = process.env,
117): SharedDriverFairnessOptions {
118 const fault = environment.TANSTACK_DB_DRIVER_FAIRNESS_CALIBRATION
119 if (fault === undefined) return {}
120 if (fault !== `persist-first-fifo`) {
121 throw new Error(
122 `TANSTACK_DB_DRIVER_FAIRNESS_CALIBRATION must be persist-first-fifo`,
123 )
124 }
125 return { schedulingFault: fault }
126}
127
128const fairnessPropertyModes = createFairnessPropertyModes(
129 readFairnessReplayConfig(),
130)
131const fairnessCalibration = readFairnessCalibration()
132
133type WorkKind = SharedDriverFairnessWork[`kind`]
134
135type GeneratedFairnessHistory = {
136 hydrateCount: number
137 persistCount: number
138 mutationsPerPersist: number
139 orderedKinds: ReadonlyArray<WorkKind>
140 replayHistory: string
141}
142
143type GeneratedTailEntry = {
144 kind: WorkKind
145 token: string
146}
147
148function createScenario(
149 id: string,
150 orderedKinds: ReadonlyArray<WorkKind>,
151 mutationsPerPersist = 1,
152): SharedDriverFairnessScenario {
153 let hydrateIndex = 0
154 let persistIndex = 0
155 return {
156 id,
157 work: orderedKinds.map((kind) => {
158 if (kind === `persist`) {
159 const index = persistIndex++
160 return {
161 kind,
162 id: `persist-${index}`,
163 mutationsPerPersist,
164 }
165 }
166 const index = hydrateIndex++
167 return {
168 kind,
169 id: `hydrate-${index}`,
170 seededRows: [
171 { id: `row-${index}-0`, value: index * 10 },
172 { id: `row-${index}-1`, value: index * 10 + 1 },
173 ],
174 }
175 }),
176 }
177}
178
179function expectedHydratedCollections(scenario: SharedDriverFairnessScenario) {
180 return scenario.work.flatMap((work) =>
181 work.kind === `hydrate`
182 ? [
183 {
184 collectionId: `${scenario.id}-${work.id}`,
185 rows: work.seededRows.map((row) => ({ ...row })),
186 },
187 ]
188 : [],
189 )
190}
191
192async function withNodeScenario(
193 scenario: SharedDriverFairnessScenario,
194 assertion: (
195 observation: SharedDriverFairnessObservation,
196 ) => void | Promise<void>,
197 options: SharedDriverFairnessOptions = {},
198): Promise<void> {
199 const directory = mkdtempSync(join(tmpdir(), `db-driver-fairness-`))
200 let primaryFailure: unknown
201 try {
202 const observation = await observeSharedDriverFairness(
203 () =>
204 createWASQLiteTestDatabase({
205 filename: join(directory, `state.sqlite`),
206 }),
207 scenario,
208 options,
209 )
210 await assertion(observation)
211 } catch (error) {
212 primaryFailure = error
213 }
214
215 let nodeCleanupFailure: unknown
216 try {
217 rmSync(directory, { recursive: true, force: true })
218 } catch (error) {
219 nodeCleanupFailure = error
220 }
221
222 if (primaryFailure !== undefined) {
223 if (nodeCleanupFailure !== undefined) {
224 throw new AggregateError(
225 [primaryFailure, nodeCleanupFailure],
226 `primary: ${String(primaryFailure)}; node cleanup diagnostics: ${String(nodeCleanupFailure)}`,
227 { cause: primaryFailure },
228 )
229 }
230 throw primaryFailure
231 }
232 if (nodeCleanupFailure !== undefined) throw nodeCleanupFailure
233}
234
235function expectObservationReach(
236 observation: SharedDriverFairnessObservation,
237): void {
238 const expectedHydrates = expectedHydratedCollections(observation.scenario)
239 checkAt(`hydrate admission IDs`, `after all preload requests`, () =>
240 expect(observation.admittedHydrateIds).toEqual(
241 expectedHydrates.map(({ collectionId }) => collectionId),
242 ),
243 )
244 checkAt(`hydrate completion count`, `after all preloads`, () =>
245 expect(observation.hydrationCompletions).toHaveLength(
246 expectedHydrates.length,
247 ),
248 )
249 // Actual rows come from the public Collection after preload. The expected
250 // rows above are derived independently from the generated seed history.
251 checkAt(`hydrated public rows`, `after all preloads`, () =>
252 expect(observation.hydratedCollections).toEqual(expectedHydrates),
253 )
254}
255
256function expectFairObservation(
257 observation: SharedDriverFairnessObservation,
258): void {
259 expectObservationReach(observation)
260 const expectedPersistIds = observation.scenario.work
261 .filter((work) => work.kind === `persist`)
262 .map((work) => `${observation.scenario.id}-${work.id}`)
263 checkAt(`persist FIFO completion order`, `after all work settled`, () =>
264 expect(
265 observation.logicalCompletionOrder
266 .filter((entry) => entry.startsWith(`persist:`))
267 .map((entry) => entry.slice(`persist:`.length)),
268 ).toEqual(expectedPersistIds),
269 )
270 const violation = findSharedDriverFairnessViolation(
271 observation,
272 SHARED_DRIVER_FAIRNESS_BOUND,
273 )
274 if (violation) {
275 const checkpointIndex = observation.hydrationCompletions.indexOf(
276 violation.checkpoint,
277 )
278 const violatedLaws: Array<string> = []
279 if (violation.checkpoint.collectionId !== violation.expectedCollectionId) {
280 violatedLaws.push(`hydrate FIFO identity`)
281 }
282 if (
283 violation.checkpoint.completedPersistIds.length >
284 violation.expectedMaximumCompletedPersists
285 ) {
286 violatedLaws.push(`K=1 completed-persist bound`)
287 }
288 if (
289 violation.checkpoint.pendingPersistCount <
290 violation.expectedMinimumPendingPersists
291 ) {
292 violatedLaws.push(`K=1 pending-persist backlog`)
293 }
294 if (violation.unexpectedCompletedPersistIds.length > 0) {
295 violatedLaws.push(`completed persist outside permitted prefix`)
296 }
297 throw new FairnessOracleFailure(
298 violatedLaws.join(`; `),
299 `hydrate completion ${checkpointIndex}`,
300 new Error(
301 `shared-driver fairness mismatch at ${violation.checkpoint.collectionId}: ` +
302 `${violation.checkpoint.completedPersistIds.length} persists completed ` +
303 `(maximum ${violation.expectedMaximumCompletedPersists}), ` +
304 `${violation.checkpoint.pendingPersistCount} remained pending ` +
305 `(minimum ${violation.expectedMinimumPendingPersists}); ` +
306 `permitted completed ids: ${JSON.stringify(violation.permittedCompletedPersistIds)}; ` +
307 `cleanup diagnostics: ${JSON.stringify(observation.cleanupFailures)}`,
308 ),
309 )
310 }
311 checkAt(`driver cleanup`, `after observation`, () =>
312 expect(observation.cleanupFailures).toEqual([]),
313 )
314}
315
316function buildGeneratedHistory(
317 hydrateCount: number,
318 persistCount: number,
319 mutationsPerPersist: number,
320 generatedTail: ReadonlyArray<GeneratedTailEntry>,
321): GeneratedFairnessHistory {
322 return {
323 hydrateCount,
324 persistCount,
325 mutationsPerPersist,
326 orderedKinds: [
327 `persist` as const,
328 ...generatedTail.map(({ kind }) => kind),
329 ],
330 replayHistory: `p0,${generatedTail.map(({ token }) => token).join(`,`)}`,
331 }
332}
333
334function createGeneratedHistoryArbitrary(
335 tailOrderAxis: `varied` | `removed`,
336): fc.Arbitrary<GeneratedFairnessHistory> {
337 return fc
338 .record({
339 hydrateCount: fc.integer(HYDRATE_COUNT_RANGE),
340 persistCount: fc.integer(PERSIST_COUNT_RANGE),
341 mutationsPerPersist: fc.integer(MUTATIONS_PER_PERSIST_RANGE),
342 })
343 .chain(({ hydrateCount, persistCount, mutationsPerPersist }) => {
344 const tail = [
345 ...Array.from({ length: persistCount - 1 }, (_, index) => ({
346 kind: `persist` as const,
347 token: `p${index + 1}`,
348 })),
349 ...Array.from({ length: hydrateCount }, (_, index) => ({
350 kind: `hydrate` as const,
351 token: `h${index}`,
352 })),
353 ]
354 const orderedTail =
355 tailOrderAxis === `varied`
356 ? fc.shuffledSubarray(tail, {
357 minLength: tail.length,
358 maxLength: tail.length,
359 })
360 : fc.constant(tail)
361 return orderedTail.map((generatedTail) =>
362 buildGeneratedHistory(
363 hydrateCount,
364 persistCount,
365 mutationsPerPersist,
366 generatedTail,
367 ),
368 )
369 })
370}
371
372function reachesHydrateBeforeLaterPersist(
373 history: GeneratedFairnessHistory,
374): boolean {
375 let hydrateSeen = false
376 for (const kind of history.orderedKinds.slice(1)) {
377 if (kind === `hydrate`) hydrateSeen = true
378 if (kind === `persist` && hydrateSeen) return true
379 }
380 return false
381}
382
383const generatedHistoryArbitrary = createGeneratedHistoryArbitrary(`varied`)
384const tailOrderAblatedArbitrary = createGeneratedHistoryArbitrary(`removed`)
385let generatedPropertyExecutions = 0
386type GeneratedFailureRecord = {
387 law: string
388 checkpoint: string
389 history: string
390 message: string
391}
392const generatedFailureRecords: Array<GeneratedFailureRecord> = []
393
394function recordGeneratedFailure(error: unknown, history: string): void {
395 const primary = error instanceof AggregateError ? error.cause : error
396 generatedFailureRecords.push({
397 law:
398 primary instanceof FairnessOracleFailure
399 ? primary.law
400 : `unclassified driver or setup failure`,
401 checkpoint:
402 primary instanceof FairnessOracleFailure
403 ? primary.checkpoint
404 : `before classified refinement check`,
405 history,
406 message: error instanceof Error ? error.message : String(error),
407 })
408}
409
410const generatedFairnessProperty = fc.asyncProperty(
411 generatedHistoryArbitrary,
412 async ({
413 hydrateCount,
414 persistCount,
415 mutationsPerPersist,
416 orderedKinds,
417 replayHistory,
418 }) => {
419 generatedPropertyExecutions++
420 const observationId =
421 `generated-h${hydrateCount}-p${persistCount}-m${mutationsPerPersist}-` +
422 replayHistory.replaceAll(`,`, `-`)
423 try {
424 await withNodeScenario(
425 createScenario(observationId, orderedKinds, mutationsPerPersist),
426 expectFairObservation,
427 fairnessCalibration,
428 )
429 } catch (error) {
430 recordGeneratedFailure(error, replayHistory)
431 throw error
432 }
433 },
434)
435
436describe(`shared BrowserWASQLiteDriver fairness oracle`, () => {
437 it(`selects fixed and seedless lanes by default and only replay when requested`, () => {
438 expect(createFairnessPropertyModes(readFairnessReplayConfig({}))).toEqual([
439 { label: `fixed-seed`, seed: FIXED_SEED },
440 { label: `seedless-random` },
441 ])
442 expect(
443 createFairnessPropertyModes(
444 readFairnessReplayConfig({
445 TANSTACK_DB_DRIVER_FAIRNESS_SEED: `42`,
446 TANSTACK_DB_DRIVER_FAIRNESS_PATH: `0:1`,
447 }),
448 ),
449 ).toEqual([{ label: `checked-replay`, seed: 42, path: `0:1` }])
450 expect(readFairnessCalibration({})).toEqual({})
451 expect(
452 readFairnessCalibration({
453 TANSTACK_DB_DRIVER_FAIRNESS_CALIBRATION: `persist-first-fifo`,
454 }),
455 ).toEqual({ schedulingFault: `persist-first-fifo` })
456 })
457
458 it.each([
459 {
460 name: `seed without path`,
461 environment: { TANSTACK_DB_DRIVER_FAIRNESS_SEED: `42` },
462 message: `must be supplied together`,
463 },
464 {
465 name: `path without seed`,
466 environment: { TANSTACK_DB_DRIVER_FAIRNESS_PATH: `0` },
467 message: `must be supplied together`,
468 },
469 {
470 name: `non-integer seed`,
471 environment: {
472 TANSTACK_DB_DRIVER_FAIRNESS_SEED: `4.2`,
473 TANSTACK_DB_DRIVER_FAIRNESS_PATH: `0`,
474 },
475 message: `must be an integer`,
476 },
477 {
478 name: `invalid shrink path`,
479 environment: {
480 TANSTACK_DB_DRIVER_FAIRNESS_SEED: `42`,
481 TANSTACK_DB_DRIVER_FAIRNESS_PATH: `0:-1`,
482 },
483 message: `colon-separated nonnegative integers`,
484 },
485 ])(`rejects incomplete or invalid replay coordinates: $name`, (probe) => {
486 expect(() => readFairnessReplayConfig(probe.environment)).toThrow(
487 probe.message,
488 )
489 })
490
491 it(`reconstructs the known persist-first witness, covers range marginals, and rejects a nearby invalid storm`, async () => {
492 const knownWitness = buildGeneratedHistory(2, 4, 1, [
493 { kind: `persist`, token: `p1` },
494 { kind: `persist`, token: `p2` },
495 { kind: `persist`, token: `p3` },
496 { kind: `hydrate`, token: `h0` },
497 { kind: `hydrate`, token: `h1` },
498 ])
499 expect(knownWitness).toEqual({
500 hydrateCount: 2,
501 persistCount: 4,
502 mutationsPerPersist: 1,
503 orderedKinds: [
504 `persist`,
505 `persist`,
506 `persist`,
507 `persist`,
508 `hydrate`,
509 `hydrate`,
510 ],
511 replayHistory: `p0,p1,p2,p3,h0,h1`,
512 })
513
514 // Fixing hydrate count at two loses later completion checkpoints. Fixing
515 // persist count at three loses larger backlogs. Fixing mutation width at
516 // one loses multi-row work inside one logical persist.
517 const marginalHistories = [
518 buildGeneratedHistory(2, 3, 1, [
519 { kind: `persist`, token: `p1` },
520 { kind: `persist`, token: `p2` },
521 { kind: `hydrate`, token: `h0` },
522 { kind: `hydrate`, token: `h1` },
523 ]),
524 buildGeneratedHistory(7, 7, 3, [
525 ...Array.from({ length: 6 }, (_, index) => ({
526 kind: `persist` as const,
527 token: `p${index + 1}`,
528 })),
529 ...Array.from({ length: 7 }, (_, index) => ({
530 kind: `hydrate` as const,
531 token: `h${index}`,
532 })),
533 ]),
534 ]
535 expect(
536 marginalHistories.map((history) => [
537 history.hydrateCount,
538 history.persistCount,
539 history.mutationsPerPersist,
540 ]),
541 ).toEqual([
542 [2, 3, 1],
543 [7, 7, 3],
544 ])
545
546 await expect(
547 withNodeScenario(
548 createScenario(`invalid-storm-boundary`, [
549 `hydrate`,
550 `persist`,
551 `hydrate`,
552 ]),
553 expectFairObservation,
554 ),
555 ).rejects.toThrow(`must begin with its already-running persist`)
556 })
557
558 it(`reaches cold hydration and preserves independently seeded public rows without queued persists`, async () => {
559 await withNodeScenario(
560 createScenario(`neutral-reach`, [`hydrate`, `hydrate`, `hydrate`]),
561 (observation) => {
562 expectFairObservation(observation)
563 expect(
564 observation.rawDequeues.some((entry) =>
565 entry.sql.startsWith(
566 `SELECT key, value, metadata, row_version FROM`,
567 ),
568 ),
569 ).toBe(true)
570 },
571 )
572 })
573
574 it(`completes a pending cold hydrate before an unrelated persist backlog drains and distinguishes K=1 from K=2`, async () => {
575 const scenario = createScenario(
576 `fixed-persist-storm`,
577 [`persist`, `persist`, `persist`, `hydrate`, `hydrate`],
578 2,
579 )
580 await withNodeScenario(scenario, (observation) => {
581 expectFairObservation(observation)
582
583 // A K=2 scheduler could finish the third persist before the second
584 // hydrate. K=1 must leave it pending at that logical checkpoint.
585 const secondHydrate = observation.hydrationCompletions[1]!
586 expect(secondHydrate.pendingPersistCount).toBeGreaterThan(0)
587 const completedPersistIds = scenario.work
588 .filter((work) => work.kind === `persist`)
589 .map((work) => `${scenario.id}-${work.id}`)
590 expect(observation.hydrationCompletions[0]?.completedPersistIds).toEqual(
591 completedPersistIds.slice(0, 1),
592 )
593 const k2WrongAnswer = {
594 ...observation,
595 logicalCompletionOrder: [
596 `persist:${completedPersistIds[0]}`,
597 `hydrate:${observation.hydrationCompletions[0]!.collectionId}`,
598 `persist:${completedPersistIds[1]}`,
599 `persist:${completedPersistIds[2]}`,
600 `hydrate:${secondHydrate.collectionId}`,
601 ],
602 hydrationCompletions: [
603 observation.hydrationCompletions[0]!,
604 {
605 ...secondHydrate,
606 completionOrdinal: 4,
607 completedPersistIds,
608 pendingPersistCount: 0,
609 },
610 ],
611 }
612 expect(findSharedDriverFairnessViolation(k2WrongAnswer)).toMatchObject({
613 checkpoint: k2WrongAnswer.hydrationCompletions[1],
614 expectedMaximumCompletedPersists: 2,
615 expectedMinimumPendingPersists: 1,
616 })
617 expect(
618 findSharedDriverFairnessViolation(k2WrongAnswer, 2),
619 ).toBeUndefined()
620
621 const swappedPersistOrder = observation.logicalCompletionOrder.map(
622 (entry) => {
623 if (entry === `persist:${completedPersistIds[1]}`) {
624 return `persist:${completedPersistIds[2]}`
625 }
626 if (entry === `persist:${completedPersistIds[2]}`) {
627 return `persist:${completedPersistIds[1]}`
628 }
629 return entry
630 },
631 )
632 let orderFailure: unknown
633 try {
634 expectFairObservation({
635 ...observation,
636 logicalCompletionOrder: swappedPersistOrder,
637 })
638 } catch (error) {
639 orderFailure = error
640 }
641 expect(orderFailure).toMatchObject({
642 law: `persist FIFO completion order`,
643 checkpoint: `after all work settled`,
644 })
645 })
646 })
647
648 it.each(fairnessPropertyModes)(
649 `bounds persist completions for generated ordered cold-hydrate/persist histories in $label mode`,
650 async (mode) => {
651 const executionsBefore = generatedPropertyExecutions
652 const failuresBefore = generatedFailureRecords.length
653 const result = await fc.check(generatedFairnessProperty, {
654 numRuns: GENERATED_RUNS,
655 verbose: 2,
656 ...(mode.seed === undefined ? {} : { seed: mode.seed }),
657 ...(mode.path === undefined ? {} : { path: mode.path }),
658 })
659 if (result.failed) {
660 const failures = generatedFailureRecords.slice(failuresBefore)
661 const original = failures[0]
662 const reduced = failures.at(-1)
663 const sameViolation =
664 original !== undefined &&
665 reduced !== undefined &&
666 original.law !== `unclassified driver or setup failure` &&
667 original.law === reduced.law &&
668 original.checkpoint === reduced.checkpoint
669 const reductionOutcome =
670 result.numShrinks === 0
671 ? `no reduction`
672 : sameViolation
673 ? `same law and checkpoint`
674 : `different failure or unreached checkpoint`
675 throw new Error(
676 `shared-driver fairness property failed in ${mode.label} mode; ` +
677 `seed=${result.seed}, shrink path=${result.counterexamplePath ?? `none`}; ` +
678 `original=${JSON.stringify(original ?? null)}; ` +
679 `reduced=${JSON.stringify(reduced ?? null)}; ` +
680 `reduction outcome=${reductionOutcome}`,
681 { cause: result.errorInstance },
682 )
683 }
684 expect(generatedPropertyExecutions).toBeGreaterThan(executionsBefore)
685 },
686 // Each campaign runs 12 SQLite histories; parallel CI adds I/O contention.
687 // The fairness law above measures logical completions, not elapsed time.
688 30_000,
689 )
690
691 it(`proves tail-order ablation removes a hydrate-before-later-persist history`, () => {
692 const sampleOptions = { seed: FIXED_SEED, numRuns: GENERATED_RUNS }
693 const completeGrammar = fc.sample(generatedHistoryArbitrary, sampleOptions)
694 const tailOrderAblatedGrammar = fc.sample(
695 tailOrderAblatedArbitrary,
696 sampleOptions,
697 )
698
699 expect(completeGrammar.some(reachesHydrateBeforeLaterPersist)).toBe(true)
700 expect(tailOrderAblatedGrammar.some(reachesHydrateBeforeLaterPersist)).toBe(
701 false,
702 )
703 })
704
705 it(`rejects the named persist-first FIFO wrong answer through the real package path`, async () => {
706 await withNodeScenario(
707 createScenario(
708 `persist-first-fixture-fault`,
709 [`persist`, `persist`, `persist`, `persist`, `hydrate`, `hydrate`],
710 1,
711 ),
712 (observation) => {
713 expectObservationReach(observation)
714 const violation = findSharedDriverFairnessViolation(observation)
715 if (!violation) {
716 throw new Error(
717 `persist-first scheduling mutant escaped the fairness checker; ` +
718 `cleanup diagnostics: ${JSON.stringify(observation.cleanupFailures)}`,
719 )
720 }
721 expect(violation.checkpoint.completedPersistIds).toHaveLength(4)
722 expect(violation.checkpoint.pendingPersistCount).toBe(0)
723 expect(observation.cleanupFailures).toEqual([])
724 },
725 { schedulingFault: `persist-first-fifo` },
726 )
727 })
728
729 it(`calibrates the checker against a synthetic persist-first observation`, () => {
730 const scenario = createScenario(
731 `persist-first-checker-calibration`,
732 [`persist`, `persist`, `persist`, `persist`, `hydrate`, `hydrate`],
733 1,
734 )
735 const fault = createPersistFirstFaultObservation(scenario)
736
737 expect(findSharedDriverFairnessViolation(fault)).toMatchObject({
738 checkpoint: fault.hydrationCompletions[0],
739 expectedMaximumCompletedPersists: 1,
740 expectedMinimumPendingPersists: 3,
741 })
742 })
743})