Open History to see the last commit
1import { describe, expect, it } from 'vitest'
2import { fc, test as fcTest } from '@fast-check/vitest'
3import { HashReplayError, captureHashSession } from './hash-session'
4import type { HashSession } from './hash-session'
5
6const nativeSession = await captureHashSession()
7const { hash } = nativeSession
8
9/**
10 * The hash is a deterministic fingerprint of its declared value domain.
11 *
12 * Independent constructors build equivalent values with different allocation,
13 * property order, container order, and normalized numeric representations.
14 * They must agree. Deliberately different type/value pairs must disagree only
15 * where the contract promises separation; a sampled 32-bit collision alone is
16 * not a defect. `HashSession` records environment and calls so a failure can be
17 * replayed without turning random frequency into a semantic claim.
18 *
19 * Graph reachability, mixed carriers, failed traversal, and retry atomicity are
20 * separate owners. Keeping them separate makes this file's flat-value model
21 * small enough to inspect.
22 */
23
24// Arbitraries for generating test values
25const arbitraryPrimitive = fc.oneof(
26 fc.string(),
27 fc.integer(),
28 fc.double({ noNaN: true }),
29 fc.boolean(),
30 fc.constant(null),
31 fc.constant(undefined),
32)
33
34const arbitraryDate = fc.date({ noInvalidDate: true })
35
36const arbitraryUint8Array = fc.uint8Array({ minLength: 0, maxLength: 128 })
37
38const arbitrarySimpleObject = fc.dictionary(fc.string(), fc.integer(), {
39 maxKeys: 5,
40})
41
42const arbitrarySimpleArray = fc.array(fc.integer(), { maxLength: 10 })
43
44type HashValue = (value: unknown) => number
45
46function expectDistinctHashes(
47 law: string,
48 input: unknown,
49 left: unknown,
50 right: unknown,
51 session: HashSession = nativeSession,
52): void {
53 // Callers supply JSON-safe descriptors (arrays, entries, finite timestamps),
54 // detached before either driver input is exposed to the hasher.
55 const originalInput: unknown = JSON.parse(JSON.stringify(input))
56 const observed: Array<number> = []
57 try {
58 observed.push(session.hash(left), session.hash(right))
59 expect(observed[0]).not.toBe(observed[1])
60 } catch (cause) {
61 throw new HashReplayError(
62 {
63 law,
64 input: originalInput,
65 observed,
66 tape: session.tape,
67 environment: session.environment,
68 },
69 cause,
70 )
71 }
72}
73
74// This is the original sampled array/object distinction. A collision is not a
75// product defect.
76function expectArrayObjectDistinct(
77 arr: Array<number>,
78 session: HashSession = nativeSession,
79): void {
80 const obj: Record<string, number> = {}
81 arr.forEach((value, index) => {
82 obj[String(index)] = value
83 })
84 expectDistinctHashes(`array-object`, arr, arr, obj, session)
85}
86
87function expectBooleanNullDistinct(
88 value: boolean,
89 session: HashSession = nativeSession,
90): void {
91 expectDistinctHashes(`boolean-null`, value, value, null, session)
92}
93
94function expectEqualHashes(
95 value: unknown,
96 equivalent: unknown,
97 hashValue: HashValue = hash,
98): void {
99 expect(hashValue(value)).toBe(hashValue(equivalent))
100}
101
102// Prefixing preserves arbitrary string content while excluding integer-index
103// keys. Unique keys and at least two entries make reversal consequential.
104const arbitraryNonIndexEntries = fc.uniqueArray(
105 fc.tuple(
106 fc.string().map((key) => `key:${key}`),
107 fc.integer(),
108 ),
109 { minLength: 2, maxLength: 5, selector: ([key]) => key },
110)
111
112function expectPermutedHashes(
113 entries: Array<[string, number]>,
114 hashValue: HashValue = hash,
115): void {
116 const original = Object.fromEntries(entries)
117 const reversed = Object.fromEntries([...entries].reverse())
118 expect(Object.keys(original)).not.toEqual(Object.keys(reversed))
119 expect(original).toEqual(reversed)
120 expectEqualHashes(original, reversed, hashValue)
121}
122
123// The generated values supply the same numeric entries to each pair. Only the
124// container kind may distinguish Set/Map from the corresponding plain object.
125const typeMarkerValues = fc.uniqueArray(fc.integer(), {
126 minLength: 1,
127 maxLength: 5,
128})
129
130const typeMarkerReplaySeed = process.env.TANSTACK_DB_IVM_HASH_TYPE_SEED
131const typeMarkerReplayPath = process.env.TANSTACK_DB_IVM_HASH_TYPE_PATH
132const typeMarkerCampaigns =
133 typeMarkerReplaySeed === undefined && typeMarkerReplayPath === undefined
134 ? [
135 { name: `1659001`, seed: 1659001 },
136 { name: `random`, seed: undefined },
137 ]
138 : [
139 {
140 name: `replay`,
141 seed:
142 typeMarkerReplaySeed === undefined
143 ? undefined
144 : Number(typeMarkerReplaySeed),
145 },
146 ]
147
148describe(`hash property-based tests`, () => {
149 describe(`determinism`, () => {
150 fcTest.prop([arbitraryPrimitive])(
151 `hash is deterministic for primitives`,
152 (value) => {
153 const first = hash(value)
154 const second = hash(value)
155 expect(first).toBe(second)
156 },
157 )
158
159 fcTest.prop([arbitrarySimpleObject])(
160 `hash is deterministic for objects`,
161 (obj) => {
162 const first = hash(obj)
163 const second = hash(obj)
164 expect(first).toBe(second)
165 },
166 )
167
168 fcTest.prop([arbitrarySimpleArray])(
169 `hash is deterministic for arrays`,
170 (arr) => {
171 const first = hash(arr)
172 const second = hash(arr)
173 expect(first).toBe(second)
174 },
175 )
176
177 fcTest.prop([arbitraryDate])(`hash is deterministic for dates`, (date) => {
178 const first = hash(date)
179 const second = hash(date)
180 expect(first).toBe(second)
181 })
182
183 fcTest.prop([arbitraryUint8Array])(
184 `hash is deterministic for Uint8Arrays`,
185 (arr) => {
186 const first = hash(arr)
187 const second = hash(arr)
188 expect(first).toBe(second)
189 },
190 )
191 })
192
193 describe(`structural equality`, () => {
194 fcTest.prop([arbitrarySimpleObject])(
195 `cloned objects have same hash`,
196 (obj) => {
197 const clone = { ...obj }
198 expect(hash(clone)).toBe(hash(obj))
199 },
200 )
201
202 fcTest.prop([arbitrarySimpleArray])(
203 `cloned arrays have same hash`,
204 (arr) => {
205 const clone = [...arr]
206 expect(hash(clone)).toBe(hash(arr))
207 },
208 )
209
210 fcTest.prop([arbitraryDate])(
211 `dates with same time have same hash`,
212 (date) => {
213 const clone = new Date(date.getTime())
214 expect(hash(clone)).toBe(hash(date))
215 },
216 )
217
218 fcTest.prop([arbitraryUint8Array])(
219 `Uint8Arrays with same content have same hash`,
220 (arr) => {
221 const clone = new Uint8Array(arr)
222 expect(hash(clone)).toBe(hash(arr))
223 },
224 )
225
226 fcTest.prop([
227 fc.array(fc.tuple(fc.string(), fc.integer()), { maxLength: 5 }),
228 ])(`Maps with same entries have same hash`, (entries) => {
229 const map1 = new Map(entries)
230 const map2 = new Map(entries)
231 expect(hash(map1)).toBe(hash(map2))
232 })
233
234 fcTest.prop([fc.array(fc.integer(), { maxLength: 10 })])(
235 `Sets with same values have same hash`,
236 (arr) => {
237 const set1 = new Set(arr)
238 const set2 = new Set(arr)
239 expect(hash(set1)).toBe(hash(set2))
240 },
241 )
242 })
243
244 describe(`property order independence`, () => {
245 fcTest.prop([
246 fc.uniqueArray(
247 fc.string().filter((s) => s !== `` && s !== `__proto__`),
248 { minLength: 2, maxLength: 2 },
249 ),
250 fc.integer(),
251 fc.integer(),
252 ])(
253 `objects with same properties in different order have same hash`,
254 ([key1, key2], val1, val2) => {
255 expect(key1).not.toBe(key2)
256 const obj1 = { [key1!]: val1, [key2!]: val2 }
257 const obj2 = { [key2!]: val2, [key1!]: val1 }
258 expect(hash(obj1)).toBe(hash(obj2))
259 },
260 )
261
262 fcTest.prop([
263 fc.dictionary(
264 fc.string().filter((s) => s !== `__proto__`),
265 fc.integer(),
266 { minKeys: 2, maxKeys: 5 },
267 ),
268 ])(`object hash is independent of property insertion order`, (obj) => {
269 const keys = Object.keys(obj)
270 const reversedKeys = [...keys].reverse()
271
272 // Create new object with reversed key order
273 const reversed: Record<string, number> = {}
274 for (const key of reversedKeys) {
275 reversed[key] = obj[key]!
276 }
277
278 expect(hash(reversed)).toBe(hash(obj))
279 })
280
281 for (const seed of [1657021, undefined]) {
282 it(`preserves hashes after an observed non-index key permutation (${seed ?? `random`})`, () => {
283 fc.assert(
284 fc.property(arbitraryNonIndexEntries, (entries) => {
285 expectPermutedHashes(entries)
286 }),
287 { numRuns: 100, ...(seed === undefined ? {} : { seed }) },
288 )
289 })
290 }
291 })
292
293 describe(`number normalization`, () => {
294 fcTest.prop([fc.constant(0)])(`0 and -0 have the same hash`, () => {
295 expect(hash(0)).toBe(hash(-0))
296 })
297
298 fcTest.prop([fc.constant(NaN)])(`NaN has consistent hash`, () => {
299 const first = hash(NaN)
300 const second = hash(NaN)
301 expect(first).toBe(second)
302 })
303
304 fcTest.prop([fc.integer()])(`integers hash consistently`, (n) => {
305 expect(hash(n)).toBe(hash(n))
306 })
307
308 fcTest.prop([fc.double({ noNaN: true, noDefaultInfinity: true })])(
309 `doubles hash consistently`,
310 (n) => {
311 expect(hash(n)).toBe(hash(n))
312 },
313 )
314 })
315
316 // These are sampled discrimination controls, not universal injectivity laws.
317 // A finite hash can collide; a collision needs diagnosis, not a stronger API claim.
318 describe(`sampled type distinction controls`, () => {
319 fcTest.prop([fc.array(fc.integer(), { minLength: 1, maxLength: 5 })])(
320 `array and object with same indices have different hashes`,
321 (arr) => {
322 expectArrayObjectDistinct(arr)
323 },
324 )
325
326 fcTest.prop([fc.integer()])(
327 `number and string representation have different hashes`,
328 (n) => {
329 expectDistinctHashes(`number-string`, n, n, String(n))
330 },
331 )
332
333 fcTest.prop([fc.boolean()])(
334 `boolean and its string representation have different hashes`,
335 (b) => {
336 expectDistinctHashes(`boolean-string`, b, b, String(b))
337 },
338 )
339
340 fcTest.prop([fc.date({ noInvalidDate: true })])(
341 `date and its timestamp have different hashes`,
342 (date) => {
343 expectDistinctHashes(
344 `date-timestamp`,
345 date.getTime(),
346 date,
347 date.getTime(),
348 )
349 },
350 )
351
352 fcTest.prop([fc.array(fc.integer(), { minLength: 1, maxLength: 5 })])(
353 `array and Set with same values have different hashes`,
354 (arr) => {
355 const set = new Set(arr)
356 expectDistinctHashes(`array-set`, arr, arr, set)
357 },
358 )
359
360 // These sampled hash distinctions do not claim collision freedom.
361 for (const carrier of [`Set`, `Map`] as const) {
362 const property = fc.property(typeMarkerValues, (values) => {
363 if (carrier === `Set`) {
364 expectDistinctHashes(
365 `set-object`,
366 values,
367 new Set(values),
368 Object.fromEntries(values.map((value, index) => [index, value])),
369 )
370 } else {
371 const entries = values.map((value) => [String(value), value] as const)
372 expectDistinctHashes(
373 `map-object`,
374 entries,
375 new Map(entries),
376 Object.fromEntries(entries.map((entry, index) => [index, entry])),
377 )
378 }
379 })
380 for (const { name, seed } of typeMarkerCampaigns) {
381 it(`${carrier} differs from an object with matching entries (${name})`, () => {
382 if (
383 typeMarkerReplayPath !== undefined &&
384 typeMarkerReplaySeed === undefined
385 )
386 throw new Error(`TANSTACK_DB_IVM_HASH_TYPE_PATH requires a seed`)
387 if (
388 typeMarkerReplaySeed !== undefined &&
389 (typeMarkerReplaySeed.trim() === `` ||
390 typeof seed !== `number` ||
391 !Number.isSafeInteger(seed) ||
392 seed < -2147483648 ||
393 seed > 2147483647)
394 )
395 throw new Error(
396 `TANSTACK_DB_IVM_HASH_TYPE_SEED must be a 32-bit integer`,
397 )
398 fc.assert(property, {
399 numRuns: 100,
400 ...(seed === undefined ? {} : { seed }),
401 ...(typeMarkerReplayPath === undefined
402 ? {}
403 : { path: typeMarkerReplayPath }),
404 })
405 })
406 }
407 }
408 })
409
410 describe(`nested structures`, () => {
411 fcTest.prop([
412 fc.array(fc.array(fc.integer(), { maxLength: 3 }), { maxLength: 3 }),
413 ])(`nested arrays hash consistently`, (nested) => {
414 const clone = nested.map((inner) => [...inner])
415 expect(hash(clone)).toBe(hash(nested))
416 })
417
418 fcTest.prop([
419 fc.dictionary(
420 fc.string(),
421 fc.dictionary(fc.string(), fc.integer(), { maxKeys: 3 }),
422 { maxKeys: 3 },
423 ),
424 ])(`nested objects hash consistently`, (nested) => {
425 const clone = Object.fromEntries(
426 Object.entries(nested).map(([k, v]) => [k, { ...v }]),
427 )
428 expect(hash(clone)).toBe(hash(nested))
429 })
430 })
431
432 describe(`hash produces numbers`, () => {
433 fcTest.prop([arbitraryPrimitive])(
434 `hash returns a number for primitives`,
435 (value) => {
436 expect(typeof hash(value)).toBe(`number`)
437 expect(Number.isFinite(hash(value))).toBe(true)
438 },
439 )
440
441 fcTest.prop([arbitrarySimpleObject])(
442 `hash returns a number for objects`,
443 (obj) => {
444 expect(typeof hash(obj)).toBe(`number`)
445 expect(Number.isFinite(hash(obj))).toBe(true)
446 },
447 )
448
449 fcTest.prop([arbitrarySimpleArray])(
450 `hash returns a number for arrays`,
451 (arr) => {
452 expect(typeof hash(arr)).toBe(`number`)
453 expect(Number.isFinite(hash(arr))).toBe(true)
454 },
455 )
456 })
457
458 describe(`reconstructed primitive equality`, () => {
459 fcTest.prop([fc.integer()])(
460 `integer decimal round trips preserve hashes`,
461 (value) => {
462 const equivalent = Number(String(value))
463 expect(equivalent).toBe(value)
464 expectEqualHashes(value, equivalent)
465 },
466 )
467
468 fcTest.prop([fc.string()])(
469 `reconstructed strings preserve hashes`,
470 (value) => {
471 const equivalent = value.split(``).join(``)
472 expect(equivalent).toBe(value)
473 expectEqualHashes(value, equivalent)
474 },
475 )
476 })
477
478 describe(`sampled extension distinction controls`, () => {
479 fcTest.prop([
480 fc.array(fc.integer(), { minLength: 1, maxLength: 10 }),
481 fc.integer(),
482 ])(`arrays with extra element have different hashes`, (arr, extra) => {
483 const extended = [...arr, extra]
484 expectDistinctHashes(`array-extension`, { arr, extra }, arr, extended)
485 })
486
487 fcTest.prop([
488 fc.dictionary(fc.string(), fc.integer(), { minKeys: 1, maxKeys: 5 }),
489 fc.string(),
490 fc.integer(),
491 ])(
492 `objects with extra property have different hashes`,
493 (obj, newKey, newValue) => {
494 // Keep arbitrary key content, but construct a fresh key rather than
495 // silently pass when it already exists (including on the prototype).
496 while (newKey in obj) newKey += `\0`
497 const extended = { ...obj, [newKey]: newValue }
498 expect(Object.keys(extended)).toHaveLength(Object.keys(obj).length + 1)
499 expectDistinctHashes(
500 `object-extension`,
501 { entries: Object.entries(obj), newKey, newValue },
502 obj,
503 extended,
504 )
505 },
506 )
507 })
508
509 describe(`law checker calibration`, () => {
510 it(`replays an actual sampled-law collision with its native failure cause`, async () => {
511 // A legal but deliberately colliding initialization environment. Its
512 // count comes from native capture, not a copied list of marker constants.
513 const collisionSession = await captureHashSession(
514 nativeSession.tape.map(() => 0),
515 )
516 const property = fc.property(fc.boolean(), (value) =>
517 expectBooleanNullDistinct(value, collisionSession),
518 )
519 const failed = fc.check(property, { seed: 205205, numRuns: 1 })
520 expect(failed.failed).toBe(true)
521 expect(failed.numShrinks).toBeGreaterThan(0)
522 expect(failed.counterexample).toEqual([false])
523 expect(failed.counterexamplePath).toBe(`0:0`)
524 expect(failed.errorInstance).toBeInstanceOf(HashReplayError)
525 if (
526 !(failed.errorInstance instanceof HashReplayError) ||
527 failed.counterexamplePath === null
528 ) {
529 throw new Error(`Missing sampled-law replay evidence`)
530 }
531 const failure = failed.errorInstance
532 expect(failure.cause).toMatchObject({ name: `AssertionError` })
533 expect(failure.replay.law).toBe(`boolean-null`)
534 expect(failure.replay.input).toEqual(failed.counterexample[0])
535 expect(failure.replay.observed[0]).toBe(failure.replay.observed[1])
536 const replaySession = await captureHashSession(failure.replay.tape)
537 const replay = fc.check(
538 fc.property(fc.boolean(), (value) =>
539 expectBooleanNullDistinct(value, replaySession),
540 ),
541 {
542 seed: failed.seed,
543 path: failed.counterexamplePath,
544 numRuns: 1,
545 endOnFailure: true,
546 },
547 )
548 expect(replay.failed).toBe(true)
549 expect(replay.counterexample).toEqual(failed.counterexample)
550 expect(replay.errorInstance).toBeInstanceOf(HashReplayError)
551 if (!(replay.errorInstance instanceof HashReplayError))
552 throw new Error(`Missing replay error`)
553 expect(replay.errorInstance.replay).toEqual(failure.replay)
554 expect(replay.errorInstance.cause).toMatchObject({
555 name: `AssertionError`,
556 })
557 let reported: unknown
558 try {
559 fc.assert(property, {
560 seed: failed.seed,
561 path: failed.counterexamplePath,
562 numRuns: 1,
563 endOnFailure: true,
564 errorWithCause: true,
565 })
566 } catch (cause) {
567 reported = cause
568 }
569 expect(reported).toBeInstanceOf(Error)
570 if (!(reported instanceof Error))
571 throw new Error(`Missing native fast-check report`)
572 expect(reported.message).toContain(`seed: ${failed.seed}`)
573 expect(reported.message).toContain(`path:`)
574 expect(reported.cause).toBeInstanceOf(HashReplayError)
575 // The same original consumer remains a valid sampled control under its
576 // native initialization; it is not weakened to accommodate the collision.
577 expectBooleanNullDistinct(false)
578 })
579
580 it.each([0, 42, ``, `reconstructed`])(
581 `rejects inconsistent equal-value hashes for %j`,
582 (value) => {
583 let calls = 0
584 expect(() => expectEqualHashes(value, value, () => ++calls)).toThrow()
585 expect(calls).toBe(2)
586 expectEqualHashes(value, value)
587 },
588 )
589
590 it(`rejects an insertion-order-sensitive result but accepts equal structures`, () => {
591 const entries: Array<[string, number]> = [
592 [`key:left`, 1],
593 [`key:right`, 2],
594 ]
595 expect(() =>
596 expectPermutedHashes(entries, (value) =>
597 Object.keys(value as object)[0] === `key:left` ? 1 : 2,
598 ),
599 ).toThrow()
600 expectPermutedHashes(entries)
601 // The reach guard must also reject a nominal reversal of index keys.
602 expect(() =>
603 expectPermutedHashes([
604 [`0`, 1],
605 [`1`, 2],
606 ]),
607 ).toThrow()
608 })
609
610 it(`shrinks and replays an injected equality-law failure`, () => {
611 const property = fc.property(arbitraryNonIndexEntries, (entries) => {
612 let calls = 0
613 expectPermutedHashes(entries, () => ++calls)
614 })
615 const failed = fc.check(property, { seed: 1657021, numRuns: 100 })
616 expect(failed.failed).toBe(true)
617 expect(failed.counterexample).not.toBeNull()
618 expect(failed.numShrinks).toBeGreaterThan(0)
619 if (failed.counterexamplePath === null) {
620 throw new Error(`Expected a counterexample path for replay`)
621 }
622 const replayed = fc.check(property, {
623 seed: failed.seed,
624 path: failed.counterexamplePath,
625 numRuns: 100,
626 endOnFailure: true,
627 })
628 expect(replayed.failed).toBe(true)
629 expect(replayed.counterexample).toEqual(failed.counterexample)
630 })
631 })
632})