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 *
8 * A small adjacency list is the model. Kahn's algorithm independently decides
9 * whether the root-reachable graph is acyclic. Acyclic sharing is unfolded into
10 * equal fresh trees and must hash the same; a reachable cycle must reject on
11 * every attempt, while an unreachable cycle is irrelevant. Named witnesses
12 * keep rare topology classes present even when random generation misses them.
13 */
14
15// Kahn's algorithm checks the reachable graph without using the hasher's
16// recursive active-path algorithm. Unreachable cycles do not affect the root.
17function isAcyclic(edges: Array<Array<number>>): boolean {
18 const reachable = new Set([0])
19 for (const node of reachable) {
20 for (const target of edges[node]!) reachable.add(target)
21 }
22 const incoming = new Map([...reachable].map((node) => [node, 0]))
23 for (const node of reachable) {
24 for (const target of edges[node]!) {
25 incoming.set(target, incoming.get(target)! + 1)
26 }
27 }
28 const ready = [...reachable].filter((node) => incoming.get(node) === 0)
29 for (const node of ready) {
30 for (const target of edges[node]!) {
31 const remaining = incoming.get(target)! - 1
32 incoming.set(target, remaining)
33 if (remaining === 0) ready.push(target)
34 }
35 }
36 return ready.length === reachable.size
37}
38
39const graphArbitrary = fc
40 .array(fc.array(fc.nat({ max: 5 }), { maxLength: 3 }), {
41 minLength: 1,
42 maxLength: 6,
43 })
44 .map((edges) =>
45 edges.map((targets) => targets.map((target) => target % edges.length)),
46 )
47
48function expectGraphHash(
49 edges: Array<Array<number>>,
50 hashValue: (value: unknown) => number = hash,
51): void {
52 const nodes = edges.map((_, value) => ({
53 value,
54 children: [] as Array<unknown>,
55 }))
56 edges.forEach((targets, index) => {
57 nodes[index]!.children = targets.map((target) => nodes[target])
58 })
59 if (!isAcyclic(edges)) {
60 for (let attempt = 0; attempt < 2; attempt++) {
61 expect(() => hashValue(nodes[0])).toThrow(
62 `Cannot hash cyclic structural values`,
63 )
64 }
65 return
66 }
67 // Unfold sharing into equal but distinct subtrees. Hash identity must
68 // depend on values, not whether the graph reused an object reference.
69 const unfold = (node: number): unknown => ({
70 value: node,
71 children: edges[node]!.map(unfold),
72 })
73 expect(hashValue(nodes[0])).toBe(hashValue(unfold(0)))
74}
75
76// Named semantic cells run on every campaign; random frequency is not evidence
77// that disconnected cycles, repeated references, or duplicate edges were reached.
78const graphWitnesses: Array<{
79 name: string
80 edges: Array<Array<number>>
81 acyclic: boolean
82}> = [
83 { name: `isolated root`, edges: [[]], acyclic: true },
84 { name: `root self-cycle`, edges: [[0]], acyclic: false },
85 { name: `reachable mutual cycle`, edges: [[1], [0]], acyclic: false },
86 { name: `unreachable self-cycle`, edges: [[], [1]], acyclic: true },
87 {
88 name: `shared acyclic diamond`,
89 edges: [[1, 2], [3], [3], []],
90 acyclic: true,
91 },
92 { name: `duplicate acyclic edges`, edges: [[1, 1], []], acyclic: true },
93 { name: `duplicate cyclic edges`, edges: [[1, 1], [0]], acyclic: false },
94]
95
96describe(`structural hash graph boundary`, () => {
97 it.each([
98 `object`,
99 `array`,
100 `map-key`,
101 `map-value`,
102 `set`,
103 `symbol`,
104 ] as const)(`rejects a cycle through %s on every attempt`, (kind) => {
105 const record: Record<PropertyKey, unknown> = {}
106 const array: Array<unknown> = []
107 const map = new Map<unknown, unknown>()
108 const set = new Set<unknown>()
109 const input =
110 kind === `array`
111 ? array
112 : kind.startsWith(`map`)
113 ? map
114 : kind === `set`
115 ? set
116 : record
117 if (kind === `object`) record.self = input
118 if (kind === `symbol`) record[Symbol(`self`)] = input
119 if (kind === `array`) array.push(input)
120 if (kind === `map-key`) map.set(input, 1)
121 if (kind === `map-value`) map.set(1, input)
122 if (kind === `set`) set.add(input)
123 for (let attempt = 0; attempt < 2; attempt++) {
124 expect(() => hash(input)).toThrow(`Cannot hash cyclic structural values`)
125 }
126 })
127
128 it.each(graphWitnesses)(`matches the $name witness`, ({ edges, acyclic }) => {
129 // These expected categories are specified independently of Kahn's result.
130 expect(isAcyclic(edges)).toBe(acyclic)
131 expectGraphHash(edges)
132 })
133
134 for (const seed of [1657019, undefined]) {
135 it(`matches reachable graph cycles and shared DAGs (${seed ?? `random`})`, () => {
136 fc.assert(
137 fc.property(graphArbitrary, (edges) => {
138 expectGraphHash(edges)
139 }),
140 { numRuns: 300, ...(seed === undefined ? {} : { seed }) },
141 )
142 })
143 }
144
145 it(`rejects cycle acceptance while accepting its acyclic near-neighbor`, () => {
146 expect(() => expectGraphHash([[1], [0]], () => 0)).toThrow()
147 expectGraphHash([[1], []], () => 0)
148 expectGraphHash([[1], [0]])
149 expectGraphHash([[1], []])
150 })
151
152 it(`rejects false cycle rejection for unreachable cycles and shared DAGs`, () => {
153 const rejectAll = (): number => {
154 throw new TypeError(`Cannot hash cyclic structural values`)
155 }
156 for (const edges of [
157 [[], [1]],
158 [[1, 2], [3], [3], []],
159 [[1, 1], []],
160 ]) {
161 expect(() => expectGraphHash(edges, rejectAll)).toThrow(
162 `Cannot hash cyclic structural values`,
163 )
164 expectGraphHash(edges)
165 }
166 expectGraphHash([[0]], rejectAll)
167 })
168
169 it(`rejects unequal hashes of a shared DAG and its unfolding`, () => {
170 let calls = 0
171 expect(() =>
172 expectGraphHash([[1, 2], [3], [3], []], () => ++calls),
173 ).toThrow()
174 expect(calls).toBe(2)
175 expectGraphHash([[1, 2], [3], [3], []])
176 })
177
178 it(`leaves completed siblings uncached after a cycle rejects the root`, () => {
179 let reads = 0
180 const sibling = {
181 get value() {
182 return ++reads
183 },
184 }
185 const root: Record<string, unknown> = { a: sibling }
186 root.z = root
187 expect(() => hash(root)).toThrow(`Cannot hash cyclic structural values`)
188 expect(() => hash(root)).toThrow(`Cannot hash cyclic structural values`)
189 expect(reads).toBe(2)
190 delete root.z
191 expect(hash(root)).toBe(hash({ a: { value: 3 } }))
192 expect(reads).toBe(3)
193 })
194})