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

hash.property.test.ts

669 lines21.3 KB

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