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

hash-work.test.ts

170 lines5.4 KB

1import { Temporal } from 'temporal-polyfill'
2import { describe, expect, it, vi } from 'vitest'
3import { equalHashValues, hash, registerOpaqueHash } from '../src/hashing/hash'
4​
5function countTraversalAllocations(run: () => void): number {
6 let allocations = 0
7 for (const name of [`Map`, `Set`, `WeakMap`] as const) {
8 vi.stubGlobal(
9 name,
10 new Proxy(globalThis[name], {
11 construct(target, args) {
12 allocations++
13 return Reflect.construct(target, args)
14 },
15 }),
16 )
17 }
18 try {
19 run()
20 } finally {
21 vi.unstubAllGlobals()
22 }
23 return allocations
25​
26describe(`hash traversal work`, () => {
27 it.each([`object`, `array`] as const)(
28 `does not let a rejected %s traversal subsidize its own retry`,
29 (kind) => {
30 const left = Array.from({ length: 500_001 }, () => 0)
31 const right = Array.from({ length: 500_001 }, () => 0)
32 const root = kind === `object` ? { left, right } : [left, right]
33 // Either child fits, but this fresh root exceeds the combined work cap.
34 // Keeping the completed left child's cache after failure lets retry pass.
35 for (let attempt = 0; attempt < 2; attempt++) {
36 expect(() => hash(root)).toThrow(
37 `Value is too complex to hash safely: structural work`,
38 )
39 }
40 },
41 )
42​
43 it(`does not allocate traversal collections for primitive and cached inputs`, () => {
44 const cached = { id: 1, title: `cached` }
45 hash(cached)
46 const inputs = [null, undefined, false, 0, 1n, `row`, Symbol(`key`), cached]
47 expect(
48 countTraversalAllocations(() => {
49 for (const input of inputs) hash(input)
50 }),
51 ).toBe(0)
52 })
53​
54 it(`measures traversal collections for fresh structural inputs`, () => {
55 expect(countTraversalAllocations(() => hash({ id: 1 }))).toBeGreaterThan(0)
56 })
57​
58 it(`uses identity for registered handles without traversing mutable internals`, () => {
59 const first: Record<string, unknown> = {}
60 const second: Record<string, unknown> = {}
61 for (const value of [first, second]) {
62 value.self = value
63 Object.defineProperty(value, `state`, {
64 enumerable: true,
65 get() {
66 throw new Error(`must not read handle state`)
67 },
68 })
69 registerOpaqueHash(value)
70 }
71 const before = hash({ handle: first })
72 first.changed = true
73 expect(hash({ handle: first })).toBe(before)
74 expect(hash({ handle: second })).not.toBe(before)
75 expect(
76 countTraversalAllocations(() => {
77 hash(first)
78 hash(second)
79 }),
80 ).toBe(0)
81 })
82​
83 it(`visits each shared acyclic subtree once`, () => {
84 let reads = 0
85 let root: object = { value: 1 }
86 for (let depth = 0; depth < 200; depth++) {
87 const child = root
88 root = {
89 get left() {
90 reads++
91 return child
92 },
93 get right() {
94 reads++
95 return child
96 },
97 }
98 }
99 const result = hash(root)
100 expect(reads).toBe(400)
101 expect(hash(root)).toBe(result)
102 expect(reads).toBe(400)
103 })
104​
105 it(`bounds value visits without publishing partial structural caches`, () => {
106 let reads = 0
107 const shared = {}
108 const root = {
109 a: {
110 get value() {
111 reads++
112 return 1
113 },
114 },
115 // Repeated references must still count as work, even when their hashes
116 // are cached; no expanded tree is needed to reach the bound.
117 z: Array.from({ length: 1_000_001 }, () => shared),
118 }
119 for (let attempt = 1; attempt <= 2; attempt++) {
120 expect(() => hash(root)).toThrow(
121 `Value is too complex to hash safely: structural work`,
122 )
123 expect(reads).toBe(attempt)
124 }
125 expect(hash({ value: 1 })).toBe(hash({ value: 1 }))
126 })
127​
128 it(`copies a shared Map's entries once per compared pair, not per revisit`, () => {
129 const shared = new Map(Array.from({ length: 50 }, (_, i) => [i, i]))
130 const copy = new Map(shared)
131 const entries = vi.spyOn(Map.prototype, `entries`)
132 try {
133 expect(
134 equalHashValues(Array(100).fill(shared), Array(100).fill(copy)),
135 ).toBe(true)
136 // One copy for each side of the single distinct pair.
137 expect(entries).toHaveBeenCalledTimes(2)
138 } finally {
139 entries.mockRestore()
140 }
141 })
142​
143 // Each visited value costs one unit of work. Each header value of an array
144 // (its length) or a regular expression (source, flags, and lastIndex) also
145 // costs one unit. Date, binary, and Temporal header values cost nothing.
146 // Each case names the largest input that fits under the cap.
147 const zeros = (n: number) => Array.from({ length: n }, () => 0)
148 it.each<[string, (n: number) => unknown, number]>([
149 [`a flat array`, zeros, 999_999],
150 [`an object`, (n) => ({ ...zeros(n) }), 1_000_000],
151 [`nested one-element arrays`, (n) => zeros(n).map(() => [0]), 333_333],
152 [`an array with a regular expression`, (n) => [/x/g, ...zeros(n)], 999_995],
153 [`an array with a date`, (n) => [new Date(0), ...zeros(n)], 999_998],
154 [
155 `an array with binary data`,
156 (n) => [new Uint8Array(100), ...zeros(n)],
157 999_998,
158 ],
159 [
160 `an array with a Temporal value`,
161 (n) => [Temporal.PlainDate.from(`2024-01-15`), ...zeros(n)],
162 999_998,
163 ],
164 ])(`counts the structural work of %s exactly`, (_name, build, largest) => {
165 expect(() => hash(build(largest))).not.toThrow()
166 expect(() => hash(build(largest + 1))).toThrow(
167 `Value is too complex to hash safely: structural work`,
168 )
169 })
170})