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

indexes.ts

510 lines16.7 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 */
62 addValue(value: TValue, multiplicity: number): boolean {
63 if (multiplicity === 0) return this.size === 0
64​
65 const prefix = getPrefix<TValue, TPrefix>(value)
66 const valueMapOrSingleValue = this.get(prefix)
67​
68 if (isSingleValue(valueMapOrSingleValue)) {
69 const [currentValue, currentMultiplicity] = valueMapOrSingleValue
70 const currentPrefix = getPrefix<TValue, TPrefix>(currentValue)
71​
72 if (!isSamePrefix(currentPrefix, prefix)) {
73 throw new Error(`Mismatching prefixes, this should never happen`)
74 }
75​
76 if (currentValue === value || hash(currentValue) === hash(value)) {
77 // Same value, update multiplicity
78 const newMultiplicity = currentMultiplicity + multiplicity
79 if (newMultiplicity === 0) {
80 this.delete(prefix)
81 } else {
82 this.set(prefix, [value, newMultiplicity])
83 }
84 } else {
85 // Different suffixes, need to create ValueMap
86 const valueMap = new ValueMap<TValue>()
87 valueMap.set(hash(currentValue), valueMapOrSingleValue)
88 valueMap.set(hash(value), [value, multiplicity])
89 this.set(prefix, valueMap)
90 }
91 } else if (valueMapOrSingleValue === undefined) {
92 // No existing value for this prefix
93 this.set(prefix, [value, multiplicity])
94 } else {
95 // Existing ValueMap
96 const isEmpty = valueMapOrSingleValue.addValue(value, multiplicity)
97 if (isEmpty) {
98 this.delete(prefix)
99 }
100 }
101​
102 return this.size === 0
103 }
105​
106// Third level map type for the index, stores single values or value maps against a hash.
107class ValueMap<TValue> extends Map<Hash, [TValue, number]> {
108 /**
109 * Add a value to the ValueMap. Returns true if the map becomes empty after the operation.
110 * @param value - The full value to store
111 * @param multiplicity - The multiplicity to add
112 * @param hashKey - Optional hash key to use instead of hashing the full value (used when in PrefixMap context)
113 */
114 addValue(value: TValue, multiplicity: number): boolean {
115 if (multiplicity === 0) return this.size === 0
116​
117 const key = hash(value)
118 const currentValue = this.get(key)
119​
120 if (currentValue) {
121 const [, currentMultiplicity] = currentValue
122 const newMultiplicity = currentMultiplicity + multiplicity
123 if (newMultiplicity === 0) {
124 this.delete(key)
125 } else {
126 this.set(key, [value, newMultiplicity])
127 }
128 } else {
129 this.set(key, [value, multiplicity])
130 }
131​
132 return this.size === 0
133 }
135​
136/**
137 * A map from a difference collection trace's keys -> (value, multiplicities) that changed.
138 * Used in operations like join and reduce where the operation needs to
139 * exploit the key-value structure of the data to run efficiently.
140 */
141export class Index<TKey, TValue, TPrefix = any> {
142 /*
143 * This index maintains a nested map of keys -> (value, multiplicities), where:
144 * - initially the values are stored against the key as a single value tuple
145 * - when a key gets additional values, the values are stored against the key in a
146 * prefix map
147 * - the prefix is extract where possible from values that are structured as
148 * [rowPrimaryKey, rowValue], as they are in the Tanstack DB query pipeline.
149 * - only when there are multiple values for a given prefix do we fall back to a
150 * hash to identify identical values, storing them in a third level value map.
151 */
152 #inner: IndexMap<TKey, TValue, TPrefix>
153 #consolidatedMultiplicity: Map<TKey, number> = new Map() // sum of multiplicities per key
154​
155 constructor() {
156 this.#inner = new Map()
157 }
158​
159 /**
160 * Create an Index from multiple MultiSet messages.
161 * @param messages - Array of MultiSet messages to build the index from.
162 * @returns A new Index containing all the data from the messages.
163 */
164 static fromMultiSets<K, V>(messages: Array<MultiSet<[K, V]>>): Index<K, V> {
165 const index = new Index<K, V>()
166​
167 for (const message of messages) {
168 for (const [item, multiplicity] of message.getInner()) {
169 const [key, value] = item
170 index.addValue(key, [value, multiplicity])
171 }
172 }
173​
174 return index
175 }
176​
177 /**
178 * This method returns a string representation of the index.
179 * @param indent - Whether to indent the string representation.
180 * @returns A string representation of the index.
181 */
182 toString(indent = false): string {
183 return `Index(${JSON.stringify(
184 [...this.entries()],
185 undefined,
186 indent ? 2 : undefined,
187 )})`
188 }
189​
190 /**
191 * The size of the index.
192 */
193 get size(): number {
194 return this.#inner.size
195 }
196​
197 /**
198 * This method checks if the index has a given key.
199 * @param key - The key to check.
200 * @returns True if the index has the key, false otherwise.
201 */
202 has(key: TKey): boolean {
203 return this.#inner.has(key)
204 }
205​
206 /**
207 * Check if a key has presence (non-zero consolidated multiplicity).
208 * @param key - The key to check.
209 * @returns True if the key has non-zero consolidated multiplicity, false otherwise.
210 */
211 hasPresence(key: TKey): boolean {
212 return (this.#consolidatedMultiplicity.get(key) || 0) !== 0
213 }
214​
215 /**
216 * Get the consolidated multiplicity (sum of multiplicities) for a key.
217 * @param key - The key to get the consolidated multiplicity for.
218 * @returns The consolidated multiplicity for the key.
219 */
220 getConsolidatedMultiplicity(key: TKey): number {
221 return this.#consolidatedMultiplicity.get(key) || 0
222 }
223​
224 /**
225 * Get all keys that have presence (non-zero consolidated multiplicity).
226 * @returns An iterator of keys with non-zero consolidated multiplicity.
227 */
228 getPresenceKeys(): Iterable<TKey> {
229 return this.#consolidatedMultiplicity.keys()
230 }
231​
232 /**
233 * This method returns all values for a given key.
234 * @param key - The key to get the values for.
235 * @returns An array of value tuples [value, multiplicity].
236 */
237 get(key: TKey): Array<[TValue, number]> {
238 return [...this.getIterator(key)]
239 }
240​
241 /**
242 * This method returns an iterator over all values for a given key.
243 * @param key - The key to get the values for.
244 * @returns An iterator of value tuples [value, multiplicity].
245 */
246 *getIterator(key: TKey): Iterable<[TValue, number]> {
247 const mapOrSingleValue = this.#inner.get(key)
248 if (isSingleValue(mapOrSingleValue)) {
249 yield mapOrSingleValue
250 } else if (mapOrSingleValue === undefined) {
251 return
252 } else if (mapOrSingleValue instanceof ValueMap) {
253 // Direct ValueMap - all values have NO_PREFIX
254 for (const valueTuple of mapOrSingleValue.values()) {
255 yield valueTuple
256 }
257 } else {
258 // PrefixMap - iterate through all prefixes
259 for (const singleValueOrValueMap of mapOrSingleValue.values()) {
260 if (isSingleValue(singleValueOrValueMap)) {
261 yield singleValueOrValueMap
262 } else {
263 for (const valueTuple of singleValueOrValueMap.values()) {
264 yield valueTuple
265 }
266 }
267 }
268 }
269 }
270​
271 /**
272 * This returns an iterator that iterates over all key-value pairs.
273 * @returns An iterable of all key-value pairs (and their multiplicities) in the index.
274 */
275 *entries(): Iterable<[TKey, [TValue, number]]> {
276 for (const key of this.#inner.keys()) {
277 for (const valueTuple of this.getIterator(key)) {
278 yield [key, valueTuple]
279 }
280 }
281 }
282​
283 /**
284 * This method only iterates over the keys and not over the values.
285 * Hence, it is more efficient than the `#entries` method.
286 * It returns an iterator that you can use if you need to iterate over the values for a given key.
287 * @returns An iterator of all *keys* in the index and their corresponding value iterator.
288 */
289 *entriesIterators(): Iterable<[TKey, Iterable<[TValue, number]>]> {
290 for (const key of this.#inner.keys()) {
291 yield [key, this.getIterator(key)]
292 }
293 }
294​
295 /**
296 * This method adds a value to the index.
297 * @param key - The key to add the value to.
298 * @param valueTuple - The value tuple [value, multiplicity] to add to the index.
299 */
300 addValue(key: TKey, valueTuple: SingleValue<TValue>) {
301 const [value, multiplicity] = valueTuple
302 // If the multiplicity is 0, do nothing
303 if (multiplicity === 0) return
304​
305 // Update consolidated multiplicity tracking
306 const newConsolidatedMultiplicity =
307 (this.#consolidatedMultiplicity.get(key) || 0) + multiplicity
308 if (newConsolidatedMultiplicity === 0) {
309 this.#consolidatedMultiplicity.delete(key)
310 } else {
311 this.#consolidatedMultiplicity.set(key, newConsolidatedMultiplicity)
312 }
313​
314 const mapOrSingleValue = this.#inner.get(key)
315​
316 if (mapOrSingleValue === undefined) {
317 // First value for this key
318 this.#inner.set(key, valueTuple)
319 return
320 }
321​
322 if (isSingleValue(mapOrSingleValue)) {
323 // Handle transition from single value to map
324 this.#handleSingleValueTransition(
325 key,
326 mapOrSingleValue,
327 value,
328 multiplicity,
329 )
330 return
331 }
332​
333 if (mapOrSingleValue instanceof ValueMap) {
334 // Handle existing ValueMap
335 const prefix = getPrefix<TValue, TPrefix>(value)
336 if (prefix !== NO_PREFIX) {
337 // Convert ValueMap to PrefixMap since we have a prefixed value
338 const prefixMap = new PrefixMap<TValue, TPrefix>()
339 prefixMap.set(NO_PREFIX, mapOrSingleValue)
340 prefixMap.set(prefix, valueTuple)
341 this.#inner.set(key, prefixMap)
342 } else {
343 // Add to existing ValueMap
344 const isEmpty = mapOrSingleValue.addValue(value, multiplicity)
345 if (isEmpty) {
346 this.#inner.delete(key)
347 }
348 }
349 } else {
350 // Handle existing PrefixMap
351 const isEmpty = mapOrSingleValue.addValue(value, multiplicity)
352 if (isEmpty) {
353 this.#inner.delete(key)
354 }
355 }
356 }
357​
358 /**
359 * Handle the transition from a single value to either a ValueMap or PrefixMap
360 */
361 #handleSingleValueTransition(
362 key: TKey,
363 currentSingleValue: SingleValue<TValue>,
364 newValue: TValue,
365 multiplicity: number,
366 ) {
367 const [currentValue, currentMultiplicity] = currentSingleValue
368​
369 // Check for exact same value (reference equality)
370 if (currentValue === newValue) {
371 const newMultiplicity = currentMultiplicity + multiplicity
372 if (newMultiplicity === 0) {
373 this.#inner.delete(key)
374 } else {
375 this.#inner.set(key, [newValue, newMultiplicity])
376 }
377 return
378 }
379​
380 // Get prefixes for both values
381 const newPrefix = getPrefix<TValue, TPrefix>(newValue)
382 const currentPrefix = getPrefix<TValue, TPrefix>(currentValue)
383​
384 // Check if they're the same value by prefix/suffix comparison
385 if (
386 isSamePrefix(currentPrefix, newPrefix) &&
387 (currentValue === newValue || hash(currentValue) === hash(newValue))
388 ) {
389 const newMultiplicity = currentMultiplicity + multiplicity
390 if (newMultiplicity === 0) {
391 this.#inner.delete(key)
392 } else {
393 this.#inner.set(key, [newValue, newMultiplicity])
394 }
395 return
396 }
397​
398 // Different values - choose appropriate map type
399 if (currentPrefix === NO_PREFIX && newPrefix === NO_PREFIX) {
400 // Both have NO_PREFIX, use ValueMap directly
401 const valueMap = new ValueMap<TValue>()
402 valueMap.set(hash(currentValue), currentSingleValue)
403 valueMap.set(hash(newValue), [newValue, multiplicity])
404 this.#inner.set(key, valueMap)
405 } else {
406 // At least one has a prefix, use PrefixMap
407 const prefixMap = new PrefixMap<TValue, TPrefix>()
408​
409 if (isSamePrefix(currentPrefix, newPrefix)) {
410 // Same prefix, different suffixes - need ValueMap within PrefixMap
411 const valueMap = new ValueMap<TValue>()
412 valueMap.set(hash(currentValue), currentSingleValue)
413 valueMap.set(hash(newValue), [newValue, multiplicity])
414 prefixMap.set(currentPrefix, valueMap)
415 } else {
416 // Different prefixes - store as separate single values
417 prefixMap.set(currentPrefix, currentSingleValue)
418 prefixMap.set(newPrefix, [newValue, multiplicity])
419 }
420​
421 this.#inner.set(key, prefixMap)
422 }
423 }
424​
425 /**
426 * This method appends another index to the current index.
427 * @param other - The index to append to the current index.
428 */
429 append(other: Index<TKey, TValue>): void {
430 for (const [key, value] of other.entries()) {
431 this.addValue(key, value)
432 }
433 }
434​
435 /**
436 * This method joins two indexes.
437 * @param other - The index to join with the current index.
438 * @returns A multiset of the joined values.
439 */
440 join<TValue2>(
441 other: Index<TKey, TValue2>,
442 ): MultiSet<[TKey, [TValue, TValue2]]> {
443 const result: Array<[[TKey, [TValue, TValue2]], number]> = []
444 // We want to iterate over the smaller of the two indexes to reduce the
445 // number of operations we need to do.
446 if (this.size <= other.size) {
447 for (const [key, valueIt] of this.entriesIterators()) {
448 if (!other.has(key)) continue
449 const otherValues = other.get(key)
450 for (const [val1, mul1] of valueIt) {
451 for (const [val2, mul2] of otherValues) {
452 if (mul1 !== 0 && mul2 !== 0) {
453 result.push([[key, [val1, val2]], mul1 * mul2])
454 }
455 }
456 }
457 }
458 } else {
459 for (const [key, otherValueIt] of other.entriesIterators()) {
460 if (!this.has(key)) continue
461 const values = this.get(key)
462 for (const [val2, mul2] of otherValueIt) {
463 for (const [val1, mul1] of values) {
464 if (mul1 !== 0 && mul2 !== 0) {
465 result.push([[key, [val1, val2]], mul1 * mul2])
466 }
467 }
468 }
469 }
470 }
471​
472 return new MultiSet(result)
473 }
475​
476/**
477 * This function extracts the prefix from a value.
478 * @param value - The value to extract the prefix from.
479 * @returns The prefix and the suffix.
480 */
481// Prefixes are Map keys, so they compare as a Map does: NaN equals NaN.
482function isSamePrefix(a: unknown, b: unknown): boolean {
483 return a === b || (Number.isNaN(a) && Number.isNaN(b))
485​
486function getPrefix<TValue, TPrefix>(value: TValue): TPrefix | NO_PREFIX {
487 // If the value is an array and the first element is a string or number, then the
488 // first element is the prefix. This is used to distinguish between values without
489 // the need for hashing unless there are multiple values for the same prefix.
490 if (
491 Array.isArray(value) &&
492 (typeof value[0] === `string` ||
493 typeof value[0] === `number` ||
494 typeof value[0] === `bigint`)
495 ) {
496 return value[0] as TPrefix
497 }
498 return NO_PREFIX
500​
501/**
502 * This function checks if a value is a single value.
503 * @param value - The value to check.
504 * @returns True if the value is a single value, false otherwise.
505 */
506function isSingleValue<TValue>(
507 value: SingleValue<TValue> | unknown,
508): value is SingleValue<TValue> {
509 return Array.isArray(value)