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

hash-session-replay.test.ts

115 lines4.2 KB

1import { describe, expect, it } from 'vitest'
2import { fc } from '@fast-check/vitest'
3import { captureHashSession } from './hash-session'
4import type { HashSession } from './hash-session'
5​
6type Encounter = `symbol-a` | `symbol-b` | `function` | `register-opaque`
7const encounters: Array<Encounter> = [
8 `symbol-a`,
9 `symbol-b`,
10 `function`,
11 `register-opaque`,
13​
14function runEncounterScript(
15 session: HashSession,
16 script: ReadonlyArray<Encounter>,
17): Array<number> {
18 // Same descriptions do not collapse distinct symbols. The IDs and action
19 // order below are the replay representation; JSON of runtime handles is not.
20 const symbols = { 'symbol-a': Symbol(`same`), 'symbol-b': Symbol(`same`) }
21 const callable = () => 1
22 const opaque: { self?: object } = {}
23 opaque.self = opaque
24 const observed: Array<number> = []
25 for (const action of script) {
26 if (action === `register-opaque`) session.registerOpaqueHash(opaque)
27 else
28 observed.push(
29 session.hash(action === `function` ? callable : symbols[action]),
30 )
31 }
32 const value = { symbol: symbols[`symbol-a`], callable, opaque }
33 const clone = { symbol: symbols[`symbol-a`], callable, opaque }
34 const result = session.hash(value)
35 expect(session.hash(clone)).toBe(result)
36 observed.push(result, session.hash(symbols[`symbol-b`]))
37 return observed
39​
40function expectSessionLaws(session: HashSession): void {
41 expect(session.hash({ a: [1, 2] })).toBe(session.hash({ a: [1, 2] }))
42 expect(session.hash(-0)).toBe(session.hash(0))
43 const cycle: { next?: object } = {}
44 cycle.next = cycle
45 expect(() => session.hash(cycle)).toThrow(
46 `Cannot hash cyclic structural values`,
47 )
49​
50describe(`hash initialization and encounter replay`, () => {
51 it(`replays native module draws and an explicit reference encounter history`, async () => {
52 const nativeRandom = Math.random
53 const first = await captureHashSession()
54 expect(Math.random).toBe(nativeRandom)
55 expect(first.tape.length).toBeGreaterThan(0)
56 const script: Array<Encounter> = [
57 `symbol-b`,
58 `function`,
59 `register-opaque`,
60 `symbol-a`,
61 ]
62 const observed = runEncounterScript(first, script)
63 const replay = await captureHashSession(first.tape)
64 expect(Math.random).toBe(nativeRandom)
65 expect(replay.environment).toEqual(first.environment)
66 expect(runEncounterScript(replay, script)).toEqual(observed)
67 })
68​
69 it(`preserves equality and cycle laws across bounded initialization tapes`, async () => {
70 const captured = await captureHashSession()
71 for (const offset of [0.125, 0.375, 0.625]) {
72 // Do not require the numeric digest to agree across different tapes.
73 const tape = captured.tape.map((_, index) => (offset + index / 64) % 1)
74 expectSessionLaws(await captureHashSession(tape))
75 }
76 })
77​
78 it(`replays bounded encounter permutations without changing their order`, async () => {
79 const captured = await captureHashSession()
80 await fc.assert(
81 fc.asyncProperty(
82 fc.shuffledSubarray(encounters, {
83 minLength: encounters.length,
84 maxLength: encounters.length,
85 }),
86 async (script) => {
87 const first = await captureHashSession(captured.tape)
88 const observed = runEncounterScript(first, script)
89 const replay = await captureHashSession(captured.tape)
90 expect(runEncounterScript(replay, script)).toEqual(observed)
91 },
92 ),
93 { seed: 205205, numRuns: 12 },
94 )
95 })
96​
97 it(`rejects incomplete and excessive tapes and restores randomness on import failure`, async () => {
98 const nativeRandom = Math.random
99 const captured = await captureHashSession()
100 await expect(captureHashSession(captured.tape.slice(1))).rejects.toThrow(
101 `Hash replay tape exhausted`,
102 )
103 expect(Math.random).toBe(nativeRandom)
104 await expect(captureHashSession([...captured.tape, 0.5])).rejects.toThrow(
105 `Unused hash replay draws`,
106 )
107 expect(Math.random).toBe(nativeRandom)
108 const error = new Error(`import rejected`)
109 await expect(
110 captureHashSession(undefined, () => Promise.reject(error)),
111 ).rejects.toBe(error)
112 expect(Math.random).toBe(nativeRandom)
113 expectSessionLaws(await captureHashSession(captured.tape))
114 })
115})