Open History to see the last commit
1import { describe, expect, it } from 'vitest'
2import { fc } from '@fast-check/vitest'
3import { hash } from '../src/hashing/hash'
4
5/**
6 * Structural hash follows the reachable value graph, not object identity.
7 * This is the established structural-value contract recorded in the oracle
8 * coverage map: equal acyclic values have equal hashes, reachable cycles
9 * reject, and a failed traversal publishes no reusable sibling hashes.
10 *
11 * A small adjacency list is the model. Kahn's algorithm independently decides
12 * whether the root-reachable graph is acyclic. Acyclic sharing is unfolded into
13 * equal fresh trees and must hash the same; a reachable cycle must reject on
14 * every attempt, while an unreachable cycle is irrelevant. Named witnesses
15 * keep rare topology classes present even when random generation misses them.
16 * The generated topology claim is limited to plain objects with numeric
17 * labels and array edges, at most six nodes and three edges per node. Fixed
18 * cases also cover cycle rejection through other containers. This file does
19 * not establish collision freedom or complexity limits.
20 */
21
22const fixedSeed = 1657019
23const replaySeedText = process.env.TANSTACK_DB_IVM_HASH_GRAPH_SEED
24const replayPath = process.env.TANSTACK_DB_IVM_HASH_GRAPH_PATH
25const replaySeed =
26 replaySeedText === undefined ? undefined : Number(replaySeedText)
27if (
28 replaySeedText !== undefined &&
29 (replaySeedText.trim() === `` || !Number.isSafeInteger(replaySeed))
30) {
31 throw new Error(`TANSTACK_DB_IVM_HASH_GRAPH_SEED must be an integer`)
32}
33if (replayPath !== undefined && replaySeed === undefined) {
34 throw new Error(
35 `TANSTACK_DB_IVM_HASH_GRAPH_PATH requires TANSTACK_DB_IVM_HASH_GRAPH_SEED`,
36 )
37}
38const campaigns =
39 replaySeed === undefined
40 ? [
41 { name: `fixed`, seed: fixedSeed, path: undefined },
42 { name: `random`, seed: undefined, path: undefined },
43 ]
44 : [{ name: `replay`, seed: replaySeed, path: replayPath }]
45
46// This adjacency list exists only in the model; production receives a rooted
47// JavaScript value. Kahn's algorithm checks reachability without using the
48// hasher's recursive active-path algorithm. Unreachable cycles do not affect
49// the root. The checkpoint is each hash() return or throw.
50function isAcyclic(edges: Array<Array<number>>): boolean {
51 const reachable = new Set([0])
52 for (const node of reachable) {
53 for (const target of edges[node]!) reachable.add(target)
54 }
55 const incoming = new Map([...reachable].map((node) => [node, 0]))
56 for (const node of reachable) {
57 for (const target of edges[node]!) {
58 incoming.set(target, incoming.get(target)! + 1)
59 }
60 }
61 const ready = [...reachable].filter((node) => incoming.get(node) === 0)
62 for (const node of ready) {
63 for (const target of edges[node]!) {
64 const remaining = incoming.get(target)! - 1
65 incoming.set(target, remaining)
66 if (remaining === 0) ready.push(target)
67 }
68 }
69 return ready.length === reachable.size
70}
71
72// Grammar: one root and up to five other nodes; each node has zero to three
73// ordered edges. Target reduction keeps every edge in range while retaining
74// self, backward, duplicate, and disconnected-edge cases. An empty graph or
75// an out-of-range target is outside this grammar. Restricting to one node
76// loses diamonds and disconnected cycles; one edge per node loses branching
77// and duplicates; forward-only targets lose reachable cycles.
78const graphArbitrary = fc
79 .array(fc.array(fc.nat({ max: 5 }), { maxLength: 3 }), {
80 minLength: 1,
81 maxLength: 6,
82 })
83 .map((edges) =>
84 edges.map((targets) => targets.map((target) => target % edges.length)),
85 )
86
87function expectGraphHash(
88 edges: Array<Array<number>>,
89 hashValue: (value: unknown) => number = hash,
90): void {
91 const nodes = edges.map((_, value) => ({
92 value,
93 children: [] as Array<unknown>,
94 }))
95 edges.forEach((targets, index) => {
96 nodes[index]!.children = targets.map((target) => nodes[target])
97 })
98 if (!isAcyclic(edges)) {
99 for (let attempt = 0; attempt < 2; attempt++) {
100 expect(() => hashValue(nodes[0])).toThrow(
101 `Cannot hash cyclic structural values`,
102 )
103 }
104 return
105 }
106 // Unfold sharing into equal but distinct subtrees. Hash identity must
107 // depend on values, not whether the graph reused an object reference.
108 const unfold = (node: number): unknown => ({
109 value: node,
110 children: edges[node]!.map(unfold),
111 })
112 expect(hashValue(nodes[0])).toBe(hashValue(unfold(0)))
113}
114
115// Named semantic cells run on every campaign; random frequency is not evidence
116// that disconnected cycles, repeated references, or duplicate edges were reached.
117const graphWitnesses: Array<{
118 name: string
119 edges: Array<Array<number>>
120 acyclic: boolean
121}> = [
122 { name: `isolated root`, edges: [[]], acyclic: true },
123 { name: `root self-cycle`, edges: [[0]], acyclic: false },
124 { name: `reachable mutual cycle`, edges: [[1], [0]], acyclic: false },
125 { name: `unreachable self-cycle`, edges: [[], [1]], acyclic: true },
126 {
127 name: `shared acyclic diamond`,
128 edges: [[1, 2], [3], [3], []],
129 acyclic: true,
130 },
131 { name: `duplicate acyclic edges`, edges: [[1, 1], []], acyclic: true },
132 { name: `duplicate cyclic edges`, edges: [[1, 1], [0]], acyclic: false },
133 {
134 name: `maximum node and edge bounds`,
135 edges: [[1, 2, 5], [3], [3], [4], [5], []],
136 acyclic: true,
137 },
138]
139
140describe(`structural hash graph boundary`, () => {
141 it.each([
142 `object`,
143 `array`,
144 `map-key`,
145 `map-value`,
146 `set`,
147 `symbol`,
148 ] as const)(`rejects a cycle through %s on every attempt`, (kind) => {
149 const record: Record<PropertyKey, unknown> = {}
150 const array: Array<unknown> = []
151 const map = new Map<unknown, unknown>()
152 const set = new Set<unknown>()
153 const input =
154 kind === `array`
155 ? array
156 : kind.startsWith(`map`)
157 ? map
158 : kind === `set`
159 ? set
160 : record
161 if (kind === `object`) record.self = input
162 if (kind === `symbol`) record[Symbol(`self`)] = input
163 if (kind === `array`) array.push(input)
164 if (kind === `map-key`) map.set(input, 1)
165 if (kind === `map-value`) map.set(1, input)
166 if (kind === `set`) set.add(input)
167 for (let attempt = 0; attempt < 2; attempt++) {
168 expect(() => hash(input)).toThrow(`Cannot hash cyclic structural values`)
169 }
170 })
171
172 it.each(graphWitnesses)(`matches the $name witness`, ({ edges, acyclic }) => {
173 // These expected categories are specified independently of Kahn's result.
174 expect(isAcyclic(edges)).toBe(acyclic)
175 expectGraphHash(edges)
176 })
177
178 for (const campaign of campaigns) {
179 it(`matches reachable graph cycles and shared DAGs (${campaign.name})`, () => {
180 fc.assert(
181 fc.property(graphArbitrary, (edges) => {
182 expectGraphHash(edges)
183 }),
184 {
185 numRuns: 300,
186 ...(campaign.seed === undefined ? {} : { seed: campaign.seed }),
187 ...(campaign.path === undefined ? {} : { path: campaign.path }),
188 },
189 )
190 })
191 }
192
193 it(`rejects cycle acceptance while accepting its acyclic near-neighbor`, () => {
194 expect(() => expectGraphHash([[1], [0]], () => 0)).toThrow()
195 expectGraphHash([[1], []], () => 0)
196 expectGraphHash([[1], [0]])
197 expectGraphHash([[1], []])
198 })
199
200 it(`replays a cycle-acceptance mismatch at the same checkpoint`, () => {
201 const property = fc.property(fc.integer({ min: 1, max: 3 }), (length) => {
202 const edges = Array.from({ length: length + 1 }, (_, node) => [
203 node === length ? 0 : node + 1,
204 ])
205 expectGraphHash(edges)
206 expectGraphHash(edges, () => 0)
207 })
208 const failed = fc.check(property, { seed: fixedSeed, numRuns: 1 })
209 expect(failed.failed).toBe(true)
210 expect(failed.errorInstance).toMatchObject({ name: `AssertionError` })
211 if (failed.counterexamplePath === null) {
212 throw new Error(`Missing graph replay path`)
213 }
214 const replay = fc.check(property, {
215 seed: failed.seed,
216 path: failed.counterexamplePath,
217 endOnFailure: true,
218 })
219 expect(replay.counterexample).toEqual(failed.counterexample)
220 expect(replay.errorInstance).toMatchObject({ name: `AssertionError` })
221 })
222
223 it(`rejects false cycle rejection for unreachable cycles and shared DAGs`, () => {
224 const rejectAll = (): number => {
225 throw new TypeError(`Cannot hash cyclic structural values`)
226 }
227 for (const edges of [
228 [[], [1]],
229 [[1, 2], [3], [3], []],
230 [[1, 1], []],
231 ]) {
232 expect(() => expectGraphHash(edges, rejectAll)).toThrow(
233 `Cannot hash cyclic structural values`,
234 )
235 expectGraphHash(edges)
236 }
237 expectGraphHash([[0]], rejectAll)
238 })
239
240 it(`rejects unequal hashes of a shared DAG and its unfolding`, () => {
241 let calls = 0
242 expect(() =>
243 expectGraphHash([[1, 2], [3], [3], []], () => ++calls),
244 ).toThrow()
245 expect(calls).toBe(2)
246 expectGraphHash([[1, 2], [3], [3], []])
247 })
248
249 it(`leaves completed siblings uncached after a cycle rejects the root`, () => {
250 let reads = 0
251 const sibling = {
252 get value() {
253 return ++reads
254 },
255 }
256 const root: Record<string, unknown> = { a: sibling }
257 root.z = root
258 expect(() => hash(root)).toThrow(`Cannot hash cyclic structural values`)
259 expect(() => hash(root)).toThrow(`Cannot hash cyclic structural values`)
260 expect(reads).toBe(2)
261 delete root.z
262 expect(hash(root)).toBe(hash({ a: { value: 3 } }))
263 expect(reads).toBe(3)
264 })
265})