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

indexes.ts

531 lines17.3 KB

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>
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 }
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 }
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 #consolidatedMultiplicity: Map<TKey, number> = new Map() // sum of multiplicities per key
163 /**
164 * When true, the producer guarantees that a value's string or number
165 * prefix determines the value: two values under one key with an equal
166 * prefix are equal, so they merge without a structural hash.
167 */
168 #prefixIdentity: boolean
169​
170 constructor(options?: { prefixIdentity?: boolean }) {
171 this.#inner = new Map()
172 this.#prefixIdentity = options?.prefixIdentity ?? false
173 }
174​
175 /**
176 * Create an Index from multiple MultiSet messages.
177 * @param messages - Array of MultiSet messages to build the index from.
178 * @returns A new Index containing all the data from the messages.
179 */
180 static fromMultiSets<K, V>(messages: Array<MultiSet<[K, V]>>): Index<K, V> {
181 const index = new Index<K, V>()
182​
183 for (const message of messages) {
184 for (const [item, multiplicity] of message.getInner()) {
185 const [key, value] = item
186 index.addValue(key, [value, multiplicity])
187 }
188 }
189​
190 return index
191 }
192​
193 /**
194 * This method returns a string representation of the index.
195 * @param indent - Whether to indent the string representation.
196 * @returns A string representation of the index.
197 */
198 toString(indent = false): string {
199 return `Index(${JSON.stringify(
200 [...this.entries()],
201 undefined,
202 indent ? 2 : undefined,
203 )})`
204 }
205​
206 /**
207 * The size of the index.
208 */
209 get size(): number {
210 return this.#inner.size
211 }
212​
213 /**
214 * This method checks if the index has a given key.
215 * @param key - The key to check.
216 * @returns True if the index has the key, false otherwise.
217 */
218 has(key: TKey): boolean {
219 return this.#inner.has(key)
220 }
221​
222 /**
223 * Check if a key has presence (non-zero consolidated multiplicity).
224 * @param key - The key to check.
225 * @returns True if the key has non-zero consolidated multiplicity, false otherwise.
226 */
227 hasPresence(key: TKey): boolean {
228 return (this.#consolidatedMultiplicity.get(key) || 0) !== 0
229 }
230​
231 /**
232 * Get the consolidated multiplicity (sum of multiplicities) for a key.
233 * @param key - The key to get the consolidated multiplicity for.
234 * @returns The consolidated multiplicity for the key.
235 */
236 getConsolidatedMultiplicity(key: TKey): number {
237 return this.#consolidatedMultiplicity.get(key) || 0
238 }
239​
240 /**
241 * Get all keys that have presence (non-zero consolidated multiplicity).
242 * @returns An iterator of keys with non-zero consolidated multiplicity.
243 */
244 getPresenceKeys(): Iterable<TKey> {
245 return this.#consolidatedMultiplicity.keys()
246 }
247​
248 /**
249 * This method returns all values for a given key.
250 * @param key - The key to get the values for.
251 * @returns An array of value tuples [value, multiplicity].
252 */
253 get(key: TKey): Array<[TValue, number]> {
254 return [...this.getIterator(key)]
255 }
256​
257 /**
258 * This method returns an iterator over all values for a given key.
259 * @param key - The key to get the values for.
260 * @returns An iterator of value tuples [value, multiplicity].
261 */
262 *getIterator(key: TKey): Iterable<[TValue, number]> {
263 const mapOrSingleValue = this.#inner.get(key)
264 if (isSingleValue(mapOrSingleValue)) {
265 yield mapOrSingleValue
266 } else if (mapOrSingleValue === undefined) {
267 return
268 } else if (mapOrSingleValue instanceof ValueMap) {
269 // Direct ValueMap - all values have NO_PREFIX
270 for (const valueTuple of mapOrSingleValue.values()) {
271 yield valueTuple
272 }
273 } else {
274 // PrefixMap - iterate through all prefixes
275 for (const singleValueOrValueMap of mapOrSingleValue.values()) {
276 if (isSingleValue(singleValueOrValueMap)) {
277 yield singleValueOrValueMap
278 } else {
279 for (const valueTuple of singleValueOrValueMap.values()) {
280 yield valueTuple
281 }
282 }
283 }
284 }
285 }
286​
287 /**
288 * This returns an iterator that iterates over all key-value pairs.
289 * @returns An iterable of all key-value pairs (and their multiplicities) in the index.
290 */
291 *entries(): Iterable<[TKey, [TValue, number]]> {
292 for (const key of this.#inner.keys()) {
293 for (const valueTuple of this.getIterator(key)) {
294 yield [key, valueTuple]
295 }
296 }
297 }
298​
299 /**
300 * This method only iterates over the keys and not over the values.
301 * Hence, it is more efficient than the `#entries` method.
302 * It returns an iterator that you can use if you need to iterate over the values for a given key.
303 * @returns An iterator of all *keys* in the index and their corresponding value iterator.
304 */
305 *entriesIterators(): Iterable<[TKey, Iterable<[TValue, number]>]> {
306 for (const key of this.#inner.keys()) {
307 yield [key, this.getIterator(key)]
308 }
309 }
310​
311 /**
312 * This method adds a value to the index.
313 * @param key - The key to add the value to.
314 * @param valueTuple - The value tuple [value, multiplicity] to add to the index.
315 */
316 addValue(key: TKey, valueTuple: SingleValue<TValue>) {
317 const [value, multiplicity] = valueTuple
318 // If the multiplicity is 0, do nothing
319 if (multiplicity === 0) return
320​
321 // Update consolidated multiplicity tracking
322 const newConsolidatedMultiplicity =
323 (this.#consolidatedMultiplicity.get(key) || 0) + multiplicity
324 if (newConsolidatedMultiplicity === 0) {
325 this.#consolidatedMultiplicity.delete(key)
326 } else {
327 this.#consolidatedMultiplicity.set(key, newConsolidatedMultiplicity)
328 }
329​
330 const mapOrSingleValue = this.#inner.get(key)
331​
332 if (mapOrSingleValue === undefined) {
333 // First value for this key
334 this.#inner.set(key, valueTuple)
335 return
336 }
337​
338 if (isSingleValue(mapOrSingleValue)) {
339 // Handle transition from single value to map
340 this.#handleSingleValueTransition(
341 key,
342 mapOrSingleValue,
343 value,
344 multiplicity,
345 )
346 return
347 }
348​
349 if (mapOrSingleValue instanceof ValueMap) {
350 // Handle existing ValueMap
351 const prefix = getPrefix<TValue, TPrefix>(value)
352 if (prefix !== NO_PREFIX) {
353 // Convert ValueMap to PrefixMap since we have a prefixed value
354 const prefixMap = new PrefixMap<TValue, TPrefix>()
355 prefixMap.set(NO_PREFIX, mapOrSingleValue)
356 prefixMap.set(prefix, valueTuple)
357 this.#inner.set(key, prefixMap)
358 } else {
359 // Add to existing ValueMap
360 const isEmpty = mapOrSingleValue.addValue(value, multiplicity)
361 if (isEmpty) {
362 this.#inner.delete(key)
363 }
364 }
365 } else {
366 // Handle existing PrefixMap
367 const isEmpty = mapOrSingleValue.addValue(
368 value,
369 multiplicity,
370 this.#prefixIdentity,
371 )
372 if (isEmpty) {
373 this.#inner.delete(key)
374 }
375 }
376 }
377​
378 /**
379 * Handle the transition from a single value to either a ValueMap or PrefixMap
380 */
381 #handleSingleValueTransition(
382 key: TKey,
383 currentSingleValue: SingleValue<TValue>,
384 newValue: TValue,
385 multiplicity: number,
386 ) {
387 const [currentValue, currentMultiplicity] = currentSingleValue
388​
389 // Check for exact same value (reference equality)
390 if (currentValue === newValue) {
391 const newMultiplicity = currentMultiplicity + multiplicity
392 if (newMultiplicity === 0) {
393 this.#inner.delete(key)
394 } else {
395 this.#inner.set(key, [newValue, newMultiplicity])
396 }
397 return
398 }
399​
400 // Get prefixes for both values
401 const newPrefix = getPrefix<TValue, TPrefix>(newValue)
402 const currentPrefix = getPrefix<TValue, TPrefix>(currentValue)
403​
404 // Check if they're the same value by prefix/suffix comparison
405 if (
406 isSamePrefix(currentPrefix, newPrefix) &&
407 ((this.#prefixIdentity && newPrefix !== NO_PREFIX) ||
408 hash(currentValue) === hash(newValue))
409 ) {
410 const newMultiplicity = currentMultiplicity + multiplicity
411 if (newMultiplicity === 0) {
412 this.#inner.delete(key)
413 } else {
414 this.#inner.set(key, [newValue, newMultiplicity])
415 }
416 return
417 }
418​
419 // Different values - choose appropriate map type
420 if (currentPrefix === NO_PREFIX && newPrefix === NO_PREFIX) {
421 // Both have NO_PREFIX, use ValueMap directly
422 const valueMap = new ValueMap<TValue>()
423 valueMap.set(hash(currentValue), currentSingleValue)
424 valueMap.set(hash(newValue), [newValue, multiplicity])
425 this.#inner.set(key, valueMap)
426 } else {
427 // At least one has a prefix, use PrefixMap
428 const prefixMap = new PrefixMap<TValue, TPrefix>()
429​
430 if (isSamePrefix(currentPrefix, newPrefix)) {
431 // Same prefix, different suffixes - need ValueMap within PrefixMap
432 const valueMap = new ValueMap<TValue>()
433 valueMap.set(hash(currentValue), currentSingleValue)
434 valueMap.set(hash(newValue), [newValue, multiplicity])
435 prefixMap.set(currentPrefix, valueMap)
436 } else {
437 // Different prefixes - store as separate single values
438 prefixMap.set(currentPrefix, currentSingleValue)
439 prefixMap.set(newPrefix, [newValue, multiplicity])
440 }
441​
442 this.#inner.set(key, prefixMap)
443 }
444 }
445​
446 /**
447 * This method appends another index to the current index.
448 * @param other - The index to append to the current index.
449 */
450 append(other: Index<TKey, TValue>): void {
451 for (const [key, value] of other.entries()) {
452 this.addValue(key, value)
453 }
454 }
455​
456 /**
457 * This method joins two indexes.
458 * @param other - The index to join with the current index.
459 * @returns A multiset of the joined values.
460 */
461 join<TValue2>(
462 other: Index<TKey, TValue2>,
463 ): MultiSet<[TKey, [TValue, TValue2]]> {
464 const result: Array<[[TKey, [TValue, TValue2]], number]> = []
465 // We want to iterate over the smaller of the two indexes to reduce the
466 // number of operations we need to do.
467 if (this.size <= other.size) {
468 for (const [key, valueIt] of this.entriesIterators()) {
469 if (!other.has(key)) continue
470 const otherValues = other.get(key)
471 for (const [val1, mul1] of valueIt) {
472 for (const [val2, mul2] of otherValues) {
473 if (mul1 !== 0 && mul2 !== 0) {
474 result.push([[key, [val1, val2]], mul1 * mul2])
475 }
476 }
477 }
478 }
479 } else {
480 for (const [key, otherValueIt] of other.entriesIterators()) {
481 if (!this.has(key)) continue
482 const values = this.get(key)
483 for (const [val2, mul2] of otherValueIt) {
484 for (const [val1, mul1] of values) {
485 if (mul1 !== 0 && mul2 !== 0) {
486 result.push([[key, [val1, val2]], mul1 * mul2])
487 }
488 }
489 }
490 }
491 }
492​
493 return new MultiSet(result)
494 }
496​
497/**
498 * This function extracts the prefix from a value.
499 * @param value - The value to extract the prefix from.
500 * @returns The prefix and the suffix.
501 */
502// Prefixes are Map keys, so they compare as a Map does: NaN equals NaN.
503function isSamePrefix(a: unknown, b: unknown): boolean {
504 return a === b || (Number.isNaN(a) && Number.isNaN(b))
506​
507function getPrefix<TValue, TPrefix>(value: TValue): TPrefix | NO_PREFIX {
508 // If the value is an array and the first element is a string or number, then the
509 // first element is the prefix. This is used to distinguish between values without
510 // the need for hashing unless there are multiple values for the same prefix.
511 if (
512 Array.isArray(value) &&
513 (typeof value[0] === `string` ||
514 typeof value[0] === `number` ||
515 typeof value[0] === `bigint`)
516 ) {
517 return value[0] as TPrefix
518 }
519 return NO_PREFIX
521​
522/**
523 * This function checks if a value is a single value.
524 * @param value - The value to check.
525 * @returns True if the value is a single value, false otherwise.
526 */
527function isSingleValue<TValue>(
528 value: SingleValue<TValue> | unknown,
529): value is SingleValue<TValue> {
530 return Array.isArray(value)