Open History to see the last commit
1# Code weight: one type dispatch for hashing and equality
2
3Reviewed executable revision: `3b8412f4` (base `0122da80`, the fetched
4`origin/main` at review time). This record follows in a documentation-only
5commit. Work started on `8283f2e8`. `f4c390a6` merges `0122da80`, which does
6not change `packages/db-ivm`.
7
8- `c0182397` adds the hash identity oracle and the work-cap tests on unchanged
9 production code.
10- `d1fa5a9a` is the refactor.
11- `b7455952` extends the oracle after mutants on the refactor found three
12 grammar gaps.
13- `6073cb13` applies review fixes. It fixes one performance regression and
14 one behavior change, and it closes three more grammar gaps.
15- `33603a2f` compares type markers by object identity, after an external
16 review found that equality used random numbers as type identity.
17- `3b8412f4` runs every oracle law in a module copy whose type markers all
18 collide, generates any value as a Map key, and aims half of the mutations
19 at container nodes.
20
21Each version of the new tests also passes on the base code. The documentation
22commit that follows also adds comments to the oracle file, with no executable
23change.
24
25## Change
26
27`hashObject` and `equalHashValues` in `packages/db-ivm/src/hashing/hash.ts`
28each had a six-way type dispatch: Date, binary, Temporal, RegExp, and the
29Map/Set/array/object shapes. Each branch had its own hasher or its own
30comparison. One `objectParts(input)` function now returns a
31`[marker, header, body?]` view that both use. Each marker is a private object
32that holds a random hash number. Hashing writes the number, and equality
33compares the objects by identity.
34
35| Type | Header | Body |
36| --- | --- | --- |
37| Date | timestamp, or `invalid` | none |
38| binary (at most 128 bytes) | the bytes as one string | none |
39| Temporal | type tag, string form | none |
40| RegExp | source, flags, `lastIndex` | the RegExp |
41| Map | none | its entries |
42| Set | none | its values |
43| array | length | the array |
44| object | none | the object |
45
46Also removed:
47
48- the four per-type hashers (`hashDate`, `hashUint8Array`, `hashTemporal`,
49 `hashPlainObject`) and `structuralShape`.
50- the duplicate root and nested paths in `getCachedHash`.
51- the unreachable `typeof` `default:` warning in `updateHasher`. The switch
52 already covers all eight `typeof` results.
53
54`referenceValues` moved into `isReferenceHashedObject`, which both functions
55already call.
56
57The change is intended to preserve behavior. Hash values change because the
58binary header is now a string. Hash values were never stable: the markers are
59random for each process, and nothing persists them.
60
61| Entry | Revision | min | gzip | brotli |
62| --- | --- | ---: | ---: | ---: |
63| full `@tanstack/db` (db-ivm inlined) | `0122da80` | 378,307 | 106,762 | 90,361 |
64| | `3b8412f4` | 377,379 | 106,527 | 90,141 |
65| | Δ | −928 | −235 | −220 |
66| standalone `@tanstack/db-ivm` | `0122da80` | 34,374 | 10,570 | 9,513 |
67| | `3b8412f4` | 33,452 | 10,347 | 9,353 |
68| | Δ | −922 | −223 | −160 |
69
70All numbers come from an esbuild bundle of the public entry, minified.
71
72## What earlier versions changed, and what this change keeps
73
74The audit prototype (ledger IVM-01) and the first port of it changed the
75behaviors below. This change keeps each one as the base code had it:
76
771. **Work cap.** The prototype wrote every header value directly to the
78 hasher. Array lengths and RegExp fields then stopped counting toward
79 `MAX_STRUCTURAL_HASH_WORK`, so a 1,000,000-element array was accepted
80 instead of rejected. Now header values of a type that has a body go through
81 `updateHasher`, as before. Date, binary, and Temporal headers still cost
82 nothing.
832. **Pair memo.** The prototype entered the equality pair memo before it
84 compared headers. That allocated memo entries for every Date, binary, and
85 Temporal pair, and binary equality took 2.3 times as long. The first port
86 moved the whole memo after `objectParts`, which copies Map and Set entries.
87 Each revisit of a shared or cyclic Map then cost O(entries): 100 revisits
88 of one pair made 200 entry copies instead of 2. Now the lookup comes before
89 `objectParts`, and the insert comes after the markers and headers match,
90 only for types with a body. That is the base order.
913. **Arrays from another realm.** `instanceof Array` is false for an array
92 from another realm, so both versions give it the object marker. The base
93 equality also compared lengths with `Array.isArray`. The prototype dropped
94 that check. This change keeps it.
954. **Header comparison.** The first port compared headers with the `NaN`
96 rule, so a RegExp whose `lastIndex` is `NaN` equaled its copy. The base
97 code compared RegExp fields with `!==`. Headers now compare with `===`, and
98 the header of an invalid Date is `invalid`, so all invalid dates stay equal.
995. **Type identity.** The base code told types apart with `instanceof`. The
100 first port compared the random marker numbers, so two types whose numbers
101 collided compared equal, for example an empty Map and an empty Set. Map and
102 array then also gave different results in each argument order. Markers are
103 now objects, compared by identity.
104
105## Why a new owner
106
107Before this change, `equalHashValues` had no direct test. `topKBatch` uses it
108to cancel a retraction against its replacement, and only
109`tests/operators/topk-batch-contract.test.ts` reached it. The hash-values
110owner (`hash.property.test.ts`) checks pairwise hash laws on flat values. It
111has no model of equality, and it does not generate Temporal values, RegExp
112fields, holes, symbol keys, registered handles, `File`, or Map/Set order.
113
114The new owner,
115`packages/db-ivm/tests/hash-identity-oracle.property.test.ts`, checks both
116functions against one identity model.
117
118## Contract, path, and limits
119
120Authority: the method comments in `src/hashing/hash.ts`, and the behavior at
121`8283f2e8`.
122
1231. Primitives compare by value. `-0` equals `0`, `NaN` equals `NaN`, and a
124 bigint differs from the equal number. Symbols compare by identity.
1252. Functions, registered handles, `File` values, and binary values over 128
126 bytes compare by identity.
1273. Dates compare by timestamp. All invalid dates are equal.
1284. Binary values of at most 128 bytes compare by bytes. `Buffer` and
129 `Uint8Array` do not differ.
1305. Temporal values compare by type tag and string form.
1316. Regular expressions compare by source, flags, `lastIndex`, and enumerable
132 own properties. The fields compare with `===`, so a `NaN` `lastIndex` never
133 equals itself.
1347. Arrays compare by length and enumerable own properties. A hole differs from
135 `undefined`.
1368. Maps and Sets compare by entries or values in insertion order. Other
137 properties on a Map or Set do not count.
1389. Other objects compare by enumerable own string and symbol properties, in
139 any order. The prototype and non-enumerable properties do not count.
140
141The model is a canonical encoding of a value **spec**, which is plain data.
142It never reads a production object. The driver builds both sides of a pair as
143fresh objects from their specs. A seed varies property order, prototypes
144(`{}`, `Object.create(null)`, a class instance), hidden non-enumerable
145properties, `Buffer` or `Uint8Array`, extra Map/Set properties, `-0` for `0`,
146and sharing or copying of a repeated subtree. None of these changes the
147identity.
148
149Every law also runs in a second copy of the module, loaded with a
150`captureHashSession` tape whose initialization draws are all equal. Every
151random constant, including every type marker, then has the same number, in any
152declaration order. A pinned case checks that precondition. In that copy, only
153the sampled distinct-hash control is skipped.
154
155For each acyclic pair, the check asserts:
156
157- `equalHashValues` in both argument orders equals the model verdict.
158- Equal identities have equal hashes.
159- Distinct identities have distinct hashes. This is a sampled control, because
160 a 32-bit hash can collide.
161
162Cyclic values are chains of arrays, Map values, Sets, or plain objects with a
163back edge to an ancestor. For each one, the check asserts that
164`equalHashValues` accepts a second build of the same spec and rejects a build
165where one leaf holds a text that no pool value has. It also asserts that `hash` throws
166`Cannot hash cyclic structural values`. These verdicts come from
167construction, so the model needs no bisimulation rule.
168
169`hash-work.test.ts` pins seven work-cap boundaries. Each case names the
170largest input that fits, and the next size must throw. One more law counts Map
171entry copies: equality on 100 revisits of one shared Map pair copies entries
172twice, once for each side.
173
174Limits:
175
176- Arrays from another realm are outside the grammar. One pinned case holds
177 equality's length check. Hashing gives such an array the object marker, so
178 `[1, <hole>]` and `[1]` from another realm hash equal but compare unequal.
179 This mismatch is present on the base revision too.
180- Map and Set order sensitivity, and ignored Map/Set properties, are pinned
181 current behavior. No contract promises them.
182- Getters and proxies are outside the grammar.
183- A RegExp with a `NaN` `lastIndex` is outside the grammar. One pinned case
184 holds strict comparison. Hashing normalizes `NaN`, so that pair hashes equal
185 but compares unequal. This mismatch is present on the base revision too.
186- Cycles through a RegExp property, a Map key, or a symbol-keyed property are
187 outside the grammar. So are pairs that differ only in where a back edge
188 points, such as `a = [a]` against `b = [[b]]`. Those need a bisimulation
189 model.
190- `hash` and `equalHashValues` still list enumerable own keys in two ways
191 (`Object.keys` plus symbols, and `Reflect.ownKeys`). The oracle's hidden
192 non-enumerable properties catch drift between them: mutant N16 fails.
193- Real Temporal types print distinct formats. Only a polyfill-shaped value can
194 share text across types, so one pinned case holds the type tag.
195
196## Grammar controls and calibration
197
198Specs cover every kind in the contract, nested to a small depth. Map keys are
199any generated value. The model merges primitive keys and shared references
200that are equal under SameValueZero, as Map and Set do: the first position
201stays and the last value wins. A pair is either the same spec (30%) or the
202spec with one near-miss mutation. Half of the mutations target a container
203node, because leaves outnumber containers:
204
205| Mutation | Examples |
206| --- | --- |
207| header | a Date timestamp, one binary byte, an appended byte, a Temporal value, RegExp flags or `lastIndex` |
208| hole | an appended hole, a hole for a value, `undefined` for a hole |
209| order | reversed Map entries, Set values, or object keys (object order keeps the identity) |
210| property | a renamed object or Map key, a repeated primitive Map key, a changed symbol key, an added RegExp or array property |
211| retype | A Date becomes its timestamp. Binary becomes an array of its bytes. A Map becomes a Set or an array of entry pairs. A Set becomes an array. An array becomes an object. |
212| replace | a different primitive or reference id |
213| split | a shared child becomes two copies, one of them changed |
214
215- **Reconstruction:** 22 pinned pairs hold one rule each, in both module
216 copies. Six more pinned cases hold the Temporal tag, strict RegExp field
217 comparison, a shared child against two different copies, the cross-realm
218 length check, the colliding-marker precondition, and a `topKBatch`
219 Map-to-Set replacement with colliding markers. One case builds the same
220 shared/copied spec with 39 seed pairs.
221- **Ablation and exclusion:** the mutants below.
222- **Range:** the positive execution witness requires the fixed campaign
223 (seed `2026930`, 300 pairs) to reach all 20 value kinds and all eight
224 mutation classes, to give a `false` verdict for header, hole, retype,
225 replace, and split mutations, and to give only `true` for unmutated pairs.
226 It also requires Map keys that are numbers, symbols, references, and
227 containers, and at least one merged Map key.
228
229Each run executes a fixed campaign and a random campaign of 300 pairs for
230acyclic values, and the same for cyclic values.
231`TANSTACK_DB_IVM_HASH_IDENTITY_SEED` and `TANSTACK_DB_IVM_HASH_IDENTITY_PATH`
232select a direct replay.
233
234### Source mutants on unchanged production (`8283f2e8` sources)
235
236All rows use the tests at `3b8412f4`. The columns count failures:
237
238- **Identity oracle:** `hash-identity-oracle.property.test.ts` (34 cases).
239- **Work-cap pins:** the seven boundary cases in `hash-work.test.ts`.
240- **Pre-existing:** every other db-ivm test, with `hash-work.test.ts` at its
241 `origin/main` version (589 tests).
242
243| Mutant | Identity oracle | Work-cap pins | Pre-existing |
244| --- | --- | --- | --- |
245| W1: equality ignores RegExp `lastIndex` | assertion failure (3) | 0 | 3 |
246| W2: equality ignores array length | assertion failure (4) | 0 | 3 |
247| W3: equality ignores the container kind | assertion failure (9) | 0 | 3 |
248| W4: binary equality compares only lengths | assertion failure (3) | 0 | 3 |
249| W5: Temporal equality compares only tags | assertion failure (2) | 0 | 0 |
250| W6: registered handles compare structurally | assertion failure (3) | 0 | 3 |
251| W7: equality ignores symbol keys | assertion failure (3) | 0 | 3 |
252| W8: a Set hashes with the array marker | assertion failure (4) | 0 | 0 |
253| W9: hashing skips symbol keys | assertion failure (3) | 0 | 7 |
254| W10: hashing omits the array length | assertion failure (3) | 6 | 2 |
255| W11: invalid dates compare with `===` | assertion failure (3) | 0 | 0 |
256| W12: equality compares large binary values by content | assertion failure (1) | 0 | 3 |
257
258A first mutant for W11, "Date equality accepts a non-Date", survived every
259test. It is equivalent in this domain: the earlier `typeof` guard rejects a
260Date compared with a primitive, and no generated object has `getTime`.
261
262### Source mutants on the refactor (`3b8412f4`)
263
264| Mutant | Identity oracle | Work-cap pins | Pre-existing |
265| --- | --- | --- | --- |
266| N1: a Set uses the Map marker | assertion failure (6) | 0 | 0 |
267| N2: equality skips header values | assertion failure (7) | 0 | 15 |
268| N3: the binary header holds only the length | assertion failure (3) | 0 | 3 |
269| N4: header-only types compare equal before their headers | assertion failure (5) | 0 | 6 |
270| N5: header values skip the work counter (the prototype) | 0 | assertion failure (6) | 0 |
271| N6: hashing drops symbol keys | assertion failure (3) | 0 | 7 |
272| N7: a RegExp has no body | assertion failure (2) | 1 | 0 |
273| N8: a Map body holds only values | assertion failure (7) | 0 | 7 |
274| N9: the Temporal header drops the tag | assertion failure (1) | 0 | 0 |
275| N10: registered handles compare structurally | assertion failure (3) | 0 | 3 |
276| N11: the cross-realm length check is removed | assertion failure (1) | 0 | 0 |
277| N12: the revisit check keys on the left object only | assertion failure (3) | 0 | 0 |
278| N13: equality skips values under symbol keys | assertion failure (2) | 0 | 0 |
279| N14: headers compare with the `NaN` rule (the first port) | assertion failure (1) | 0 | 0 |
280| N15: the revisit lookup follows `objectParts` (the first port) | 0 | 0 | 0 |
281| N16: hashing counts non-enumerable string keys | assertion failure (4) | 6 | 0 |
282| N17: equality compares marker numbers (the first port) | assertion failure (9) | 0 | 0 |
283
284N15 changes only work, not identity. The entry-copy law in
285`hash-work.test.ts` rejects it with an assertion failure (1 case). The
286production code before `33603a2f`, which compared marker numbers, fails the
287same 9 oracle cases as N17, including both generated pair campaigns.
288
289History of the grammar gaps:
290
291- N1, N8, N9, and N11 survived the first oracle (`c0182397`). `b7455952` adds
292 Sets of generated values, a Map key rename, a Map-to-Set retype, and two
293 pinned cases.
294- N12, N13, N14, and N15 came from review of `b7455952`. `6073cb13` adds the
295 split mutation, mutations of values under symbol keys, the strict RegExp
296 pin, and the entry-copy law.
297- N17 came from an external review of `f4c390a6`. `33603a2f` added a pinned
298 collision at fixed draw positions. `3b8412f4` replaces it with the
299 colliding module copy, which does not depend on declaration order.
300
301Fourteen mutants pass every pre-existing db-ivm test: W5, W8, W11, N1, N5, N7,
302N9, N11, N12, N13, N14, N15, N16, and N17.
303
304## Performance
305
306`hash` runs for structural keys and unkeyed consolidation. `equalHashValues`
307runs only in `topKBatch`, for a key with more than one entry in one batch.
308
309Each timing process loads one implementation and runs every workload five
310times after two warm-up passes. Most workloads use 20,000 values. Processes
311alternate, and each ratio is the median of 15 processes of each
312implementation. The machine had a load average of 4.5 to 10 during the run.
313
314| Workload | A/A | A/B |
315| --- | ---: | ---: |
316| hash rows (6 fields with a Date and an array) | 1.011 | 1.017 |
317| hash join keys (`[number, string]`) | 1.068 | 1.129 |
318| hash binary (16 bytes) | 0.973 | 1.104 |
319| hash nested (objects, arrays, Map, Set) | 1.024 | 0.897 |
320| hash dates (one valid, one invalid) | 1.043 | 0.710 |
321| equality rows | 1.020 | 0.964 |
322| equality join keys | 1.045 | 1.388 |
323| equality binary | 1.021 | 1.300 |
324| equality nested | 0.984 | 0.989 |
325| equality with 2,000 revisits of one shared Map | 1.003 | 0.739 |
326
327Each ratio is new time over base time. The A/A control compares two copies of
328the base code. Its noise reached ±7% in this run and ±10% in earlier runs.
329
330- Hashing is neutral or faster, except binary values, which are about 10%
331 slower. The murmur stream writes two bytes for each string character, and
332 the base code wrote each byte once.
333- Equality on small distinct pairs is 1.3 to 1.4 times slower for join keys
334 and binary values. Each side now builds a parts tuple and a header array.
335 `equalHashValues` runs only in `topKBatch` for a key with more than one
336 entry in one batch, so this cost stays on a rare path.
337- Equality over a shared Map is faster than the base, and it copies entries
338 once for each distinct pair.
339
340The harness is not checked in. These timings predate `33603a2f`, which adds one
341property read for each hashed object and compares marker objects instead of
342numbers. They were not rerun for that change.
343
344## ORC-001 through ORC-012
345
346| Requirement | Result |
347| --- | --- |
348| ORC-001 | The oracle's opening comment states the nine identity rules, the three laws, the authority, and the limits above. |
349| ORC-002 | The model is a canonical encoding of plain-data specs. It does not import production helpers or read production objects. Cyclic verdicts come from construction. |
350| ORC-003 | The contract, model (`identity`, `canon`), grammar (`specArb`, `nearMiss`, `pairArb`, `cyclicArb`), driver (`realize`), and checks (`expectPair`, `expectCyclicPair`) are separate and visible in one file. |
351| ORC-004 | Reconstruction, ablation, range, and exclusion appear above. |
352| ORC-005 | The driver calls the production functions. The positive witness shows that the fixed campaign reaches every kind, every mutation class, and both verdicts. |
353| ORC-006 | The source mutants above have their outcome classes. One equivalent mutant is recorded with its reason. |
354| ORC-007 | Fixed and random campaigns share each property, grammar, check, and budget (300 runs). The replay variables select a direct replay. The properties do not use `fc.commands`. |
355| ORC-008 | The model is a stateless encoding, so this requirement does not apply. |
356| ORC-009 | The model does not use production's marker/header/body split. It encodes each contract rule directly on spec kinds. `ref` is production's reference leaf. The oracle declares two model-only kinds. `twice` is one child that the driver shares or copies. `back` is a back edge to an ancestor. |
357| ORC-010 | fast-check reports the seed, path, and shrunk pair. Assertion messages give the mutation class and both identities. |
358| ORC-011 | The Map/Set order rule, the cross-realm mismatch, and the `NaN` `lastIndex` mismatch are shared current behavior. The limits name them instead of hiding them. |
359| ORC-012 | This record ties the reviewed revisions, outcome classes, limits, and performance evidence to the coverage map. |
360
361## Verification
362
363On `3b8412f4`, the following passed:
364
365- `packages/db-ivm` Vitest: 42 files, 631 tests, no type errors.
366- `packages/db-ivm` `tsc --noEmit`: no errors.
367- `packages/db` Vitest, typecheck off: 193 files, 7,162 tests.
368- `pnpm test:oracles`: 49 `@tanstack/db` files with 2,845 tests, and 16
369 `@tanstack/query-db-collection` files with 454 tests and 1 todo.
370- `pnpm test:minified-db`: error names, index metadata, query rows, and live
371 updates.
372
373The environment was Node `v24.19.0` and Vitest `3.2.4` on Darwin arm64.
374
375## External review follow-up at `33603a2f` and `3b8412f4`
376
377The executable fix at `33603a2f` follows reviewed PR head `f4c390a6` and
378base `0122da80`. An external review found that the refactor used independent
37931-bit random hash numbers as equality type discriminators. Those numbers can
380collide even though the value types differ. With a fresh module and controlled
381`Math.random` draws, making only the Map and Set marker numbers equal made
382`equalHashValues(new Map(), new Set())` and its reverse return `true` on
383`f4c390a6`. Both returned `false` on the base. Making the Map and array numbers
384equal made Map-to-array return `true` and array-to-Map return `false` on the PR.
385Both directions returned `false` on the base. Each probe observed 19 draws.
386
387The new pinned oracle first failed on the unmodified PR at the Map/Set
388assertion (`expected true to be false`). Each type marker now carries its
389original random hash number in a distinct private object. Hashing writes that
390number. Equality compares the marker objects by identity. This keeps the
391shared type dispatch and its random hash values while separating equality
392from numeric marker collisions. The same controlled probes then returned
393`false` for both pairs in both argument orders. The oracle also checks that
394`topKBatch` retains one Map retraction and one Set addition for the same key.
395The full db-ivm suite passed 625 tests in 42 files. `tsc --noEmit -p
396packages/db-ivm/tsconfig.json`, Prettier, and `git diff --check` passed.
397
398The test checks equality type separation for empty Map/Set and Map/array pairs
399under forced collisions, plus the corresponding `topKBatch` output. Distinct
400marker objects cover the other supported carrier types by the same invariant.
401The test does not prove hash collision freedom or all live-query histories.
402`3b8412f4` closes both gaps. The pinned draw-position test is replaced by the
403colliding module copy, which runs every generated and pinned law with all type
404markers equal. Generated Map keys now include numbers, symbols, references,
405and containers, with SameValueZero merging in the model.
406
407Three other external suggestions remain optional. The `if (body)` test in the
408header loop is invariant, but runs at most three times for a RegExp and once
409for an array. Distinct object comparisons allocate two parts tuples. A
410Map/Set mismatch copied one entries iterator on both the PR and base, while a
411binary/Date mismatch newly calls `String.fromCharCode` once. A direct type
412short-circuit would duplicate the shared dispatch without an established hot
413path need. For a fresh 16-byte binary value, a deterministic counter observed
41456 `writeByte` calls on the PR and 40 on the base. The earlier review's 10%
415binary timing and 1.3–1.4× small-pair equality timing were not rerun for this
416fix. Reintroducing specialized binary hashing remains a conditional
417performance follow-up, not part of this correctness fix.