Open History to see the last commit
1/**
2 * # Optimized Index Data Structure
3 *
4 * Multi-level index that adapts storage strategy based on data patterns to minimize memory
5 * usage, eliminate wasteful lookups, and avoid hashing whenever possible.
6 *
7 * ## Storage Strategy
8 *
9 * **Single value**: `IndexMap['key'] → [value, multiplicity]` (no hashing needed)
10 *
11 * **Multiple unprefixed values**: Direct ValueMap (avoids NO_PREFIX lookup)
12 * ```
13 * IndexMap['key'] → ValueMap { hash(value1) → [value1, mult1], ... }
14 * ```
15 *
16 * **Values with prefixes**: PrefixMap uses prefix keys directly (no hashing)
17 * ```
18 * IndexMap['key'] → PrefixMap { 'prefix1' → [value1, mult1], NO_PREFIX → ValueMap{...} }
19 * ```
20 *
21 * **Multiple values per prefix**: ValueMap within PrefixMap (hash only suffixes)
22 * ```
23 * PrefixMap['prefix'] → ValueMap { hash(suffix1) → [full_value1, mult1], ... }
24 * ```
25 *
26 * ## Dynamic Evolution
27 *
28 * Structure automatically evolves as data is added:
29 * - Single → ValueMap (when both values unprefixed)
30 * - Single → PrefixMap (when at least one prefixed)
31 * - ValueMap → PrefixMap (adding prefixed value to unprefixed)
32 *
33 * Prefixes extracted from array values: `['prefix', 'suffix']` → prefix='prefix'
34 */
35
36import { MultiSet } from './multiset.js'
37import { hash } from './hashing/index.js'
38import type { Hash } from './hashing/index.js'
39
40// We use a symbol to represent the absence of a prefix, unprefixed values a stored
41// against this key.
42const NO_PREFIX = Symbol(`NO_PREFIX`)
43type NO_PREFIX = typeof NO_PREFIX
44
45// A single value is a tuple of the value and the multiplicity.
46type SingleValue<TValue> = [TValue, number]
47
48// Base map type for the index. Stores single values, prefix maps, or value maps against a key.
49type IndexMap<TKey, TValue, TPrefix> = Map<
50 TKey,
51 SingleValue<TValue> | PrefixMap<TValue, TPrefix> | ValueMap<TValue>
52>
53
54// Second level map type for the index, stores single values or value maps against a prefix.
55class PrefixMap<TValue, TPrefix> extends Map<
56 TPrefix | NO_PREFIX,
57 SingleValue<TValue> | ValueMap<TValue>
58> {
59 /**
60 * Add a value to the PrefixMap. Returns true if the map becomes empty after the operation.
61 * With `prefixIdentity`, values that share a prefix are the same value.
62 */
63 addValue(
64 value: TValue,
65 multiplicity: number,
66 prefixIdentity = false,
67 ): boolean {
68 if (multiplicity === 0) return this.size === 0
69
70 const prefix = getPrefix<TValue, TPrefix>(value)
71 const valueMapOrSingleValue = this.get(prefix)
72
73 if (isSingleValue(valueMapOrSingleValue)) {
74 const [currentValue, currentMultiplicity] = valueMapOrSingleValue
75 const currentPrefix = getPrefix<TValue, TPrefix>(currentValue)
76
77 if (!isSamePrefix(currentPrefix, prefix)) {
78 throw new Error(`Mismatching prefixes, this should never happen`)
79 }
80
81 if (
82 currentValue === value ||
83 (prefixIdentity && prefix !== NO_PREFIX) ||
84 hash(currentValue) === hash(value)
85 ) {
86 // Same value, update multiplicity
87 const newMultiplicity = currentMultiplicity + multiplicity
88 if (newMultiplicity === 0) {
89 this.delete(prefix)
90 } else {
91 this.set(prefix, [value, newMultiplicity])
92 }
93 } else {
94 // Different suffixes, need to create ValueMap
95 const valueMap = new ValueMap<TValue>()
96 valueMap.set(hash(currentValue), valueMapOrSingleValue)
97 valueMap.set(hash(value), [value, multiplicity])
98 this.set(prefix, valueMap)
99 }
100 } else if (valueMapOrSingleValue === undefined) {
101 // No existing value for this prefix
102 this.set(prefix, [value, multiplicity])
103 } else {
104 // Existing ValueMap
105 const isEmpty = valueMapOrSingleValue.addValue(value, multiplicity)
106 if (isEmpty) {
107 this.delete(prefix)
108 }
109 }
110
111 return this.size === 0
112 }
113}
114
115// Third level map type for the index, stores single values or value maps against a hash.
116class ValueMap<TValue> extends Map<Hash, [TValue, number]> {
117 /**
118 * Add a value to the ValueMap. Returns true if the map becomes empty after the operation.
119 * @param value - The full value to store
120 * @param multiplicity - The multiplicity to add
121 * @param hashKey - Optional hash key to use instead of hashing the full value (used when in PrefixMap context)
122 */
123 addValue(value: TValue, multiplicity: number): boolean {
124 if (multiplicity === 0) return this.size === 0
125
126 const key = hash(value)
127 const currentValue = this.get(key)
128
129 if (currentValue) {
130 const [, currentMultiplicity] = currentValue
131 const newMultiplicity = currentMultiplicity + multiplicity
132 if (newMultiplicity === 0) {
133 this.delete(key)
134 } else {
135 this.set(key, [value, newMultiplicity])
136 }
137 } else {
138 this.set(key, [value, multiplicity])
139 }
140
141 return this.size === 0
142 }
143}
144
145/**
146 * A map from a difference collection trace's keys -> (value, multiplicities) that changed.
147 * Used in operations like join and reduce where the operation needs to
148 * exploit the key-value structure of the data to run efficiently.
149 */
150export class Index<TKey, TValue, TPrefix = any> {
151 /*
152 * This index maintains a nested map of keys -> (value, multiplicities), where:
153 * - initially the values are stored against the key as a single value tuple
154 * - when a key gets additional values, the values are stored against the key in a
155 * prefix map
156 * - the prefix is extract where possible from values that are structured as
157 * [rowPrimaryKey, rowValue], as they are in the Tanstack DB query pipeline.
158 * - only when there are multiple values for a given prefix do we fall back to a
159 * hash to identify identical values, storing them in a third level value map.
160 */
161 #inner: IndexMap<TKey, TValue, TPrefix>
162 // Sum of multiplicities per key, for presence. Only joins read presence; a
163 // reduce index is built without it.
164 #consolidatedMultiplicity: Map<TKey, number> | undefined
165 /**
166 * When true, the producer guarantees that a value's string or number
167 * prefix determines the value: two values under one key with an equal
168 * prefix are equal, so they merge without a structural hash.
169 */
170 #prefixIdentity: boolean
171
172 constructor(options?: { prefixIdentity?: boolean; trackPresence?: boolean }) {
173 this.#inner = new Map()
174 if (options?.trackPresence ?? true)
175 this.#consolidatedMultiplicity = new Map()
176 this.#prefixIdentity = options?.prefixIdentity ?? false
177 }
178
179 /**
180 * Create an Index from multiple MultiSet messages.
181 * @param messages - Array of MultiSet messages to build the index from.
182 * @returns A new Index containing all the data from the messages.
183 */
184 static fromMultiSets<K, V>(messages: Array<MultiSet<[K, V]>>): Index<K, V> {
185 const index = new Index<K, V>()
186
187 for (const message of messages) {
188 for (const [item, multiplicity] of message.getInner()) {
189 const [key, value] = item
190 index.addValue(key, [value, multiplicity])
191 }
192 }
193
194 return index
195 }
196
197 /**
198 * This method returns a string representation of the index.
199 * @param indent - Whether to indent the string representation.
200 * @returns A string representation of the index.
201 */
202 toString(indent = false): string {
203 return `Index(${JSON.stringify(
204 [...this.entries()],
205 undefined,
206 indent ? 2 : undefined,
207 )})`
208 }
209
210 /**
211 * The size of the index.
212 */
213 get size(): number {
214 return this.#inner.size
215 }
216
217 #presence(): Map<TKey, number> {
218 if (this.#consolidatedMultiplicity === undefined)
219 throw new Error(`This Index does not track presence`)
220 return this.#consolidatedMultiplicity
221 }
222
223 /**
224 * This method checks if the index has a given key.
225 * @param key - The key to check.
226 * @returns True if the index has the key, false otherwise.
227 */
228 has(key: TKey): boolean {
229 return this.#inner.has(key)
230 }
231
232 /**
233 * Check if a key has presence (non-zero consolidated multiplicity).
234 * @param key - The key to check.
235 * @returns True if the key has non-zero consolidated multiplicity, false otherwise.
236 */
237 hasPresence(key: TKey): boolean {
238 return (this.#presence().get(key) || 0) !== 0
239 }
240
241 /**
242 * Get the consolidated multiplicity (sum of multiplicities) for a key.
243 * @param key - The key to get the consolidated multiplicity for.
244 * @returns The consolidated multiplicity for the key.
245 */
246 getConsolidatedMultiplicity(key: TKey): number {
247 return this.#presence().get(key) || 0
248 }
249
250 /**
251 * Get all keys that have presence (non-zero consolidated multiplicity).
252 * @returns An iterator of keys with non-zero consolidated multiplicity.
253 */
254 getPresenceKeys(): Iterable<TKey> {
255 return this.#presence().keys()
256 }
257
258 /**
259 * This method returns all values for a given key.
260 * @param key - The key to get the values for.
261 * @returns An array of value tuples [value, multiplicity].
262 */
263 get(key: TKey): Array<[TValue, number]> {
264 // Built directly, in getIterator's order: join and reduce call this for
265 // every changed key.
266 const mapOrSingleValue = this.#inner.get(key)
267 if (mapOrSingleValue === undefined) return []
268 if (isSingleValue(mapOrSingleValue)) return [mapOrSingleValue]
269 if (mapOrSingleValue instanceof ValueMap)
270 return [...mapOrSingleValue.values()]
271 const result: Array<[TValue, number]> = []
272 for (const singleValueOrValueMap of mapOrSingleValue.values()) {
273 if (isSingleValue(singleValueOrValueMap))
274 result.push(singleValueOrValueMap)
275 else
276 for (const valueTuple of singleValueOrValueMap.values())
277 result.push(valueTuple)
278 }
279 return result
280 }
281
282 /**
283 * This method returns an iterator over all values for a given key.
284 * @param key - The key to get the values for.
285 * @returns An iterator of value tuples [value, multiplicity].
286 */
287 *getIterator(key: TKey): Iterable<[TValue, number]> {
288 const mapOrSingleValue = this.#inner.get(key)
289 if (isSingleValue(mapOrSingleValue)) {
290 yield mapOrSingleValue
291 } else if (mapOrSingleValue === undefined) {
292 return
293 } else if (mapOrSingleValue instanceof ValueMap) {
294 // Direct ValueMap - all values have NO_PREFIX
295 for (const valueTuple of mapOrSingleValue.values()) {
296 yield valueTuple
297 }
298 } else {
299 // PrefixMap - iterate through all prefixes
300 for (const singleValueOrValueMap of mapOrSingleValue.values()) {
301 if (isSingleValue(singleValueOrValueMap)) {
302 yield singleValueOrValueMap
303 } else {
304 for (const valueTuple of singleValueOrValueMap.values()) {
305 yield valueTuple
306 }
307 }
308 }
309 }
310 }
311
312 /**
313 * This returns an iterator that iterates over all key-value pairs.
314 * @returns An iterable of all key-value pairs (and their multiplicities) in the index.
315 */
316 *entries(): Iterable<[TKey, [TValue, number]]> {
317 for (const key of this.#inner.keys()) {
318 for (const valueTuple of this.getIterator(key)) {
319 yield [key, valueTuple]
320 }
321 }
322 }
323
324 /**
325 * This method only iterates over the keys and not over the values.
326 * Hence, it is more efficient than the `#entries` method.
327 * It returns an iterator that you can use if you need to iterate over the values for a given key.
328 * @returns An iterator of all *keys* in the index and their corresponding value iterator.
329 */
330 *entriesIterators(): Iterable<[TKey, Iterable<[TValue, number]>]> {
331 for (const key of this.#inner.keys()) {
332 yield [key, this.getIterator(key)]
333 }
334 }
335
336 /**
337 * This method adds a value to the index.
338 * @param key - The key to add the value to.
339 * @param valueTuple - The value tuple [value, multiplicity] to add to the index.
340 */
341 addValue(key: TKey, valueTuple: SingleValue<TValue>) {
342 const [value, multiplicity] = valueTuple
343 // If the multiplicity is 0, do nothing
344 if (multiplicity === 0) return
345
346 // Update consolidated multiplicity tracking
347 const presence = this.#consolidatedMultiplicity
348 if (presence) {
349 const newConsolidatedMultiplicity =
350 (presence.get(key) || 0) + multiplicity
351 if (newConsolidatedMultiplicity === 0) {
352 presence.delete(key)
353 } else {
354 presence.set(key, newConsolidatedMultiplicity)
355 }
356 }
357
358 const mapOrSingleValue = this.#inner.get(key)
359
360 if (mapOrSingleValue === undefined) {
361 // First value for this key
362 this.#inner.set(key, valueTuple)
363 return
364 }
365
366 if (isSingleValue(mapOrSingleValue)) {
367 // Handle transition from single value to map
368 this.#handleSingleValueTransition(
369 key,
370 mapOrSingleValue,
371 value,
372 multiplicity,
373 )
374 return
375 }
376
377 if (mapOrSingleValue instanceof ValueMap) {
378 // Handle existing ValueMap
379 const prefix = getPrefix<TValue, TPrefix>(value)
380 if (prefix !== NO_PREFIX) {
381 // Convert ValueMap to PrefixMap since we have a prefixed value
382 const prefixMap = new PrefixMap<TValue, TPrefix>()
383 prefixMap.set(NO_PREFIX, mapOrSingleValue)
384 prefixMap.set(prefix, valueTuple)
385 this.#inner.set(key, prefixMap)
386 } else {
387 // Add to existing ValueMap
388 const isEmpty = mapOrSingleValue.addValue(value, multiplicity)
389 if (isEmpty) {
390 this.#inner.delete(key)
391 }
392 }
393 } else {
394 // Handle existing PrefixMap
395 const isEmpty = mapOrSingleValue.addValue(
396 value,
397 multiplicity,
398 this.#prefixIdentity,
399 )
400 if (isEmpty) {
401 this.#inner.delete(key)
402 }
403 }
404 }
405
406 /**
407 * Handle the transition from a single value to either a ValueMap or PrefixMap
408 */
409 #handleSingleValueTransition(
410 key: TKey,
411 currentSingleValue: SingleValue<TValue>,
412 newValue: TValue,
413 multiplicity: number,
414 ) {
415 const [currentValue, currentMultiplicity] = currentSingleValue
416
417 // Check for exact same value (reference equality)
418 if (currentValue === newValue) {
419 const newMultiplicity = currentMultiplicity + multiplicity
420 if (newMultiplicity === 0) {
421 this.#inner.delete(key)
422 } else {
423 this.#inner.set(key, [newValue, newMultiplicity])
424 }
425 return
426 }
427
428 // Get prefixes for both values
429 const newPrefix = getPrefix<TValue, TPrefix>(newValue)
430 const currentPrefix = getPrefix<TValue, TPrefix>(currentValue)
431
432 // Check if they're the same value by prefix/suffix comparison
433 if (
434 isSamePrefix(currentPrefix, newPrefix) &&
435 ((this.#prefixIdentity && newPrefix !== NO_PREFIX) ||
436 hash(currentValue) === hash(newValue))
437 ) {
438 const newMultiplicity = currentMultiplicity + multiplicity
439 if (newMultiplicity === 0) {
440 this.#inner.delete(key)
441 } else {
442 this.#inner.set(key, [newValue, newMultiplicity])
443 }
444 return
445 }
446
447 // Different values - choose appropriate map type
448 if (currentPrefix === NO_PREFIX && newPrefix === NO_PREFIX) {
449 // Both have NO_PREFIX, use ValueMap directly
450 const valueMap = new ValueMap<TValue>()
451 valueMap.set(hash(currentValue), currentSingleValue)
452 valueMap.set(hash(newValue), [newValue, multiplicity])
453 this.#inner.set(key, valueMap)
454 } else {
455 // At least one has a prefix, use PrefixMap
456 const prefixMap = new PrefixMap<TValue, TPrefix>()
457
458 if (isSamePrefix(currentPrefix, newPrefix)) {
459 // Same prefix, different suffixes - need ValueMap within PrefixMap
460 const valueMap = new ValueMap<TValue>()
461 valueMap.set(hash(currentValue), currentSingleValue)
462 valueMap.set(hash(newValue), [newValue, multiplicity])
463 prefixMap.set(currentPrefix, valueMap)
464 } else {
465 // Different prefixes - store as separate single values
466 prefixMap.set(currentPrefix, currentSingleValue)
467 prefixMap.set(newPrefix, [newValue, multiplicity])
468 }
469
470 this.#inner.set(key, prefixMap)
471 }
472 }
473
474 /**
475 * This method appends another index to the current index.
476 * @param other - The index to append to the current index.
477 */
478 append(other: Index<TKey, TValue>): void {
479 for (const [key, value] of other.entries()) {
480 this.addValue(key, value)
481 }
482 }
483
484 /**
485 * This method joins two indexes.
486 * @param other - The index to join with the current index.
487 * @returns A multiset of the joined values.
488 */
489 join<TValue2>(
490 other: Index<TKey, TValue2>,
491 ): MultiSet<[TKey, [TValue, TValue2]]> {
492 const result: Array<[[TKey, [TValue, TValue2]], number]> = []
493 // We want to iterate over the smaller of the two indexes to reduce the
494 // number of operations we need to do.
495 if (this.size <= other.size) {
496 for (const [key, valueIt] of this.entriesIterators()) {
497 if (!other.has(key)) continue
498 const otherValues = other.get(key)
499 for (const [val1, mul1] of valueIt) {
500 for (const [val2, mul2] of otherValues) {
501 if (mul1 !== 0 && mul2 !== 0) {
502 result.push([[key, [val1, val2]], mul1 * mul2])
503 }
504 }
505 }
506 }
507 } else {
508 for (const [key, otherValueIt] of other.entriesIterators()) {
509 if (!this.has(key)) continue
510 const values = this.get(key)
511 for (const [val2, mul2] of otherValueIt) {
512 for (const [val1, mul1] of values) {
513 if (mul1 !== 0 && mul2 !== 0) {
514 result.push([[key, [val1, val2]], mul1 * mul2])
515 }
516 }
517 }
518 }
519 }
520
521 return new MultiSet(result)
522 }
523}
524
525/**
526 * This function extracts the prefix from a value.
527 * @param value - The value to extract the prefix from.
528 * @returns The prefix and the suffix.
529 */
530// Prefixes are Map keys, so they compare as a Map does: NaN equals NaN.
531function isSamePrefix(a: unknown, b: unknown): boolean {
532 return a === b || (Number.isNaN(a) && Number.isNaN(b))
533}
534
535function getPrefix<TValue, TPrefix>(value: TValue): TPrefix | NO_PREFIX {
536 // If the value is an array and the first element is a string or number, then the
537 // first element is the prefix. This is used to distinguish between values without
538 // the need for hashing unless there are multiple values for the same prefix.
539 if (
540 Array.isArray(value) &&
541 (typeof value[0] === `string` ||
542 typeof value[0] === `number` ||
543 typeof value[0] === `bigint`)
544 ) {
545 return value[0] as TPrefix
546 }
547 return NO_PREFIX
548}
549
550/**
551 * This function checks if a value is a single value.
552 * @param value - The value to check.
553 * @returns True if the value is a single value, false otherwise.
554 */
555function isSingleValue<TValue>(
556 value: SingleValue<TValue> | unknown,
557): value is SingleValue<TValue> {
558 return Array.isArray(value)
559}