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

hash.property.test.ts

558 lines17.2 KB

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),
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 }
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)
86​
87function expectBooleanNullDistinct(
88 value: boolean,
89 session: HashSession = nativeSession,
90): void {
91 expectDistinctHashes(`boolean-null`, value, value, null, session)
93​
94function expectEqualHashes(
95 value: unknown,
96 equivalent: unknown,
97 hashValue: HashValue = hash,
98): void {
99 expect(hashValue(value)).toBe(hashValue(equivalent))
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 },
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)
122​
123describe(`hash property-based tests`, () => {
124 describe(`determinism`, () => {
125 fcTest.prop([arbitraryPrimitive])(
126 `hash is deterministic for primitives`,
127 (value) => {
128 const first = hash(value)
129 const second = hash(value)
130 expect(first).toBe(second)
131 },
132 )
133​
134 fcTest.prop([arbitrarySimpleObject])(
135 `hash is deterministic for objects`,
136 (obj) => {
137 const first = hash(obj)
138 const second = hash(obj)
139 expect(first).toBe(second)
140 },
141 )
142​
143 fcTest.prop([arbitrarySimpleArray])(
144 `hash is deterministic for arrays`,
145 (arr) => {
146 const first = hash(arr)
147 const second = hash(arr)
148 expect(first).toBe(second)
149 },
150 )
151​
152 fcTest.prop([arbitraryDate])(`hash is deterministic for dates`, (date) => {
153 const first = hash(date)
154 const second = hash(date)
155 expect(first).toBe(second)
156 })
157​
158 fcTest.prop([arbitraryUint8Array])(
159 `hash is deterministic for Uint8Arrays`,
160 (arr) => {
161 const first = hash(arr)
162 const second = hash(arr)
163 expect(first).toBe(second)
164 },
165 )
166 })
167​
168 describe(`structural equality`, () => {
169 fcTest.prop([arbitrarySimpleObject])(
170 `cloned objects have same hash`,
171 (obj) => {
172 const clone = { ...obj }
173 expect(hash(clone)).toBe(hash(obj))
174 },
175 )
176​
177 fcTest.prop([arbitrarySimpleArray])(
178 `cloned arrays have same hash`,
179 (arr) => {
180 const clone = [...arr]
181 expect(hash(clone)).toBe(hash(arr))
182 },
183 )
184​
185 fcTest.prop([arbitraryDate])(
186 `dates with same time have same hash`,
187 (date) => {
188 const clone = new Date(date.getTime())
189 expect(hash(clone)).toBe(hash(date))
190 },
191 )
192​
193 fcTest.prop([arbitraryUint8Array])(
194 `Uint8Arrays with same content have same hash`,
195 (arr) => {
196 const clone = new Uint8Array(arr)
197 expect(hash(clone)).toBe(hash(arr))
198 },
199 )
200​
201 fcTest.prop([
202 fc.array(fc.tuple(fc.string(), fc.integer()), { maxLength: 5 }),
203 ])(`Maps with same entries have same hash`, (entries) => {
204 const map1 = new Map(entries)
205 const map2 = new Map(entries)
206 expect(hash(map1)).toBe(hash(map2))
207 })
208​
209 fcTest.prop([fc.array(fc.integer(), { maxLength: 10 })])(
210 `Sets with same values have same hash`,
211 (arr) => {
212 const set1 = new Set(arr)
213 const set2 = new Set(arr)
214 expect(hash(set1)).toBe(hash(set2))
215 },
216 )
217 })
218​
219 describe(`property order independence`, () => {
220 fcTest.prop([
221 fc.uniqueArray(
222 fc.string().filter((s) => s !== `` && s !== `__proto__`),
223 { minLength: 2, maxLength: 2 },
224 ),
225 fc.integer(),
226 fc.integer(),
227 ])(
228 `objects with same properties in different order have same hash`,
229 ([key1, key2], val1, val2) => {
230 expect(key1).not.toBe(key2)
231 const obj1 = { [key1!]: val1, [key2!]: val2 }
232 const obj2 = { [key2!]: val2, [key1!]: val1 }
233 expect(hash(obj1)).toBe(hash(obj2))
234 },
235 )
236​
237 fcTest.prop([
238 fc.dictionary(
239 fc.string().filter((s) => s !== `__proto__`),
240 fc.integer(),
241 { minKeys: 2, maxKeys: 5 },
242 ),
243 ])(`object hash is independent of property insertion order`, (obj) => {
244 const keys = Object.keys(obj)
245 const reversedKeys = [...keys].reverse()
246​
247 // Create new object with reversed key order
248 const reversed: Record<string, number> = {}
249 for (const key of reversedKeys) {
250 reversed[key] = obj[key]!
251 }
252​
253 expect(hash(reversed)).toBe(hash(obj))
254 })
255​
256 for (const seed of [1657021, undefined]) {
257 it(`preserves hashes after an observed non-index key permutation (${seed ?? `random`})`, () => {
258 fc.assert(
259 fc.property(arbitraryNonIndexEntries, (entries) => {
260 expectPermutedHashes(entries)
261 }),
262 { numRuns: 100, ...(seed === undefined ? {} : { seed }) },
263 )
264 })
265 }
266 })
267​
268 describe(`number normalization`, () => {
269 fcTest.prop([fc.constant(0)])(`0 and -0 have the same hash`, () => {
270 expect(hash(0)).toBe(hash(-0))
271 })
272​
273 fcTest.prop([fc.constant(NaN)])(`NaN has consistent hash`, () => {
274 const first = hash(NaN)
275 const second = hash(NaN)
276 expect(first).toBe(second)
277 })
278​
279 fcTest.prop([fc.integer()])(`integers hash consistently`, (n) => {
280 expect(hash(n)).toBe(hash(n))
281 })
282​
283 fcTest.prop([fc.double({ noNaN: true, noDefaultInfinity: true })])(
284 `doubles hash consistently`,
285 (n) => {
286 expect(hash(n)).toBe(hash(n))
287 },
288 )
289 })
290​
291 // These are sampled discrimination controls, not universal injectivity laws.
292 // A finite hash can collide; a collision needs diagnosis, not a stronger API claim.
293 describe(`sampled type distinction controls`, () => {
294 fcTest.prop([fc.array(fc.integer(), { minLength: 1, maxLength: 5 })])(
295 `array and object with same indices have different hashes`,
296 (arr) => {
297 expectArrayObjectDistinct(arr)
298 },
299 )
300​
301 fcTest.prop([fc.integer()])(
302 `number and string representation have different hashes`,
303 (n) => {
304 expectDistinctHashes(`number-string`, n, n, String(n))
305 },
306 )
307​
308 fcTest.prop([fc.boolean()])(
309 `boolean and its string representation have different hashes`,
310 (b) => {
311 expectDistinctHashes(`boolean-string`, b, b, String(b))
312 },
313 )
314​
315 fcTest.prop([fc.date({ noInvalidDate: true })])(
316 `date and its timestamp have different hashes`,
317 (date) => {
318 expectDistinctHashes(
319 `date-timestamp`,
320 date.getTime(),
321 date,
322 date.getTime(),
323 )
324 },
325 )
326​
327 fcTest.prop([fc.array(fc.integer(), { minLength: 1, maxLength: 5 })])(
328 `array and Set with same values have different hashes`,
329 (arr) => {
330 const set = new Set(arr)
331 expectDistinctHashes(`array-set`, arr, arr, set)
332 },
333 )
334 })
335​
336 describe(`nested structures`, () => {
337 fcTest.prop([
338 fc.array(fc.array(fc.integer(), { maxLength: 3 }), { maxLength: 3 }),
339 ])(`nested arrays hash consistently`, (nested) => {
340 const clone = nested.map((inner) => [...inner])
341 expect(hash(clone)).toBe(hash(nested))
342 })
343​
344 fcTest.prop([
345 fc.dictionary(
346 fc.string(),
347 fc.dictionary(fc.string(), fc.integer(), { maxKeys: 3 }),
348 { maxKeys: 3 },
349 ),
350 ])(`nested objects hash consistently`, (nested) => {
351 const clone = Object.fromEntries(
352 Object.entries(nested).map(([k, v]) => [k, { ...v }]),
353 )
354 expect(hash(clone)).toBe(hash(nested))
355 })
356 })
357​
358 describe(`hash produces numbers`, () => {
359 fcTest.prop([arbitraryPrimitive])(
360 `hash returns a number for primitives`,
361 (value) => {
362 expect(typeof hash(value)).toBe(`number`)
363 expect(Number.isFinite(hash(value))).toBe(true)
364 },
365 )
366​
367 fcTest.prop([arbitrarySimpleObject])(
368 `hash returns a number for objects`,
369 (obj) => {
370 expect(typeof hash(obj)).toBe(`number`)
371 expect(Number.isFinite(hash(obj))).toBe(true)
372 },
373 )
374​
375 fcTest.prop([arbitrarySimpleArray])(
376 `hash returns a number for arrays`,
377 (arr) => {
378 expect(typeof hash(arr)).toBe(`number`)
379 expect(Number.isFinite(hash(arr))).toBe(true)
380 },
381 )
382 })
383​
384 describe(`reconstructed primitive equality`, () => {
385 fcTest.prop([fc.integer()])(
386 `integer decimal round trips preserve hashes`,
387 (value) => {
388 const equivalent = Number(String(value))
389 expect(equivalent).toBe(value)
390 expectEqualHashes(value, equivalent)
391 },
392 )
393​
394 fcTest.prop([fc.string()])(
395 `reconstructed strings preserve hashes`,
396 (value) => {
397 const equivalent = value.split(``).join(``)
398 expect(equivalent).toBe(value)
399 expectEqualHashes(value, equivalent)
400 },
401 )
402 })
403​
404 describe(`sampled extension distinction controls`, () => {
405 fcTest.prop([
406 fc.array(fc.integer(), { minLength: 1, maxLength: 10 }),
407 fc.integer(),
408 ])(`arrays with extra element have different hashes`, (arr, extra) => {
409 const extended = [...arr, extra]
410 expectDistinctHashes(`array-extension`, { arr, extra }, arr, extended)
411 })
412​
413 fcTest.prop([
414 fc.dictionary(fc.string(), fc.integer(), { minKeys: 1, maxKeys: 5 }),
415 fc.string(),
416 fc.integer(),
417 ])(
418 `objects with extra property have different hashes`,
419 (obj, newKey, newValue) => {
420 // Keep arbitrary key content, but construct a fresh key rather than
421 // silently pass when it already exists (including on the prototype).
422 while (newKey in obj) newKey += `\0`
423 const extended = { ...obj, [newKey]: newValue }
424 expect(Object.keys(extended)).toHaveLength(Object.keys(obj).length + 1)
425 expectDistinctHashes(
426 `object-extension`,
427 { entries: Object.entries(obj), newKey, newValue },
428 obj,
429 extended,
430 )
431 },
432 )
433 })
434​
435 describe(`law checker calibration`, () => {
436 it(`replays an actual sampled-law collision with its native failure cause`, async () => {
437 // A legal but deliberately colliding initialization environment. Its
438 // count comes from native capture, not a copied list of marker constants.
439 const collisionSession = await captureHashSession(
440 nativeSession.tape.map(() => 0),
441 )
442 const property = fc.property(fc.boolean(), (value) =>
443 expectBooleanNullDistinct(value, collisionSession),
444 )
445 const failed = fc.check(property, { seed: 205205, numRuns: 1 })
446 expect(failed.failed).toBe(true)
447 expect(failed.numShrinks).toBeGreaterThan(0)
448 expect(failed.counterexample).toEqual([false])
449 expect(failed.counterexamplePath).toBe(`0:0`)
450 expect(failed.errorInstance).toBeInstanceOf(HashReplayError)
451 if (
452 !(failed.errorInstance instanceof HashReplayError) ||
453 failed.counterexamplePath === null
454 ) {
455 throw new Error(`Missing sampled-law replay evidence`)
456 }
457 const failure = failed.errorInstance
458 expect(failure.cause).toMatchObject({ name: `AssertionError` })
459 expect(failure.replay.law).toBe(`boolean-null`)
460 expect(failure.replay.input).toEqual(failed.counterexample[0])
461 expect(failure.replay.observed[0]).toBe(failure.replay.observed[1])
462 const replaySession = await captureHashSession(failure.replay.tape)
463 const replay = fc.check(
464 fc.property(fc.boolean(), (value) =>
465 expectBooleanNullDistinct(value, replaySession),
466 ),
467 {
468 seed: failed.seed,
469 path: failed.counterexamplePath,
470 numRuns: 1,
471 endOnFailure: true,
472 },
473 )
474 expect(replay.failed).toBe(true)
475 expect(replay.counterexample).toEqual(failed.counterexample)
476 expect(replay.errorInstance).toBeInstanceOf(HashReplayError)
477 if (!(replay.errorInstance instanceof HashReplayError))
478 throw new Error(`Missing replay error`)
479 expect(replay.errorInstance.replay).toEqual(failure.replay)
480 expect(replay.errorInstance.cause).toMatchObject({
481 name: `AssertionError`,
482 })
483 let reported: unknown
484 try {
485 fc.assert(property, {
486 seed: failed.seed,
487 path: failed.counterexamplePath,
488 numRuns: 1,
489 endOnFailure: true,
490 errorWithCause: true,
491 })
492 } catch (cause) {
493 reported = cause
494 }
495 expect(reported).toBeInstanceOf(Error)
496 if (!(reported instanceof Error))
497 throw new Error(`Missing native fast-check report`)
498 expect(reported.message).toContain(`seed: ${failed.seed}`)
499 expect(reported.message).toContain(`path:`)
500 expect(reported.cause).toBeInstanceOf(HashReplayError)
501 // The same original consumer remains a valid sampled control under its
502 // native initialization; it is not weakened to accommodate the collision.
503 expectBooleanNullDistinct(false)
504 })
505​
506 it.each([0, 42, ``, `reconstructed`])(
507 `rejects inconsistent equal-value hashes for %j`,
508 (value) => {
509 let calls = 0
510 expect(() => expectEqualHashes(value, value, () => ++calls)).toThrow()
511 expect(calls).toBe(2)
512 expectEqualHashes(value, value)
513 },
514 )
515​
516 it(`rejects an insertion-order-sensitive result but accepts equal structures`, () => {
517 const entries: Array<[string, number]> = [
518 [`key:left`, 1],
519 [`key:right`, 2],
520 ]
521 expect(() =>
522 expectPermutedHashes(entries, (value) =>
523 Object.keys(value as object)[0] === `key:left` ? 1 : 2,
524 ),
525 ).toThrow()
526 expectPermutedHashes(entries)
527 // The reach guard must also reject a nominal reversal of index keys.
528 expect(() =>
529 expectPermutedHashes([
530 [`0`, 1],
531 [`1`, 2],
532 ]),
533 ).toThrow()
534 })
535​
536 it(`shrinks and replays an injected equality-law failure`, () => {
537 const property = fc.property(arbitraryNonIndexEntries, (entries) => {
538 let calls = 0
539 expectPermutedHashes(entries, () => ++calls)
540 })
541 const failed = fc.check(property, { seed: 1657021, numRuns: 100 })
542 expect(failed.failed).toBe(true)
543 expect(failed.counterexample).not.toBeNull()
544 expect(failed.numShrinks).toBeGreaterThan(0)
545 if (failed.counterexamplePath === null) {
546 throw new Error(`Expected a counterexample path for replay`)
547 }
548 const replayed = fc.check(property, {
549 seed: failed.seed,
550 path: failed.counterexamplePath,
551 numRuns: 100,
552 endOnFailure: true,
553 })
554 expect(replayed.failed).toBe(true)
555 expect(replayed.counterexample).toEqual(failed.counterexample)
556 })
557 })
558})