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

shared-driver-fairness-oracle.test.ts

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