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 */
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 (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 }
104}
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 }
134}
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
154 constructor() {
155 this.#inner = new Map()
156 }
157
158 /**
159 * This method returns a string representation of the index.
160 * @param indent - Whether to indent the string representation.
161 * @returns A string representation of the index.
162 */
163 toString(indent = false): string {
164 return `Index(${JSON.stringify(
165 [...this.entries()],
166 undefined,
167 indent ? 2 : undefined
168 )})`
169 }
170
171 /**
172 * The size of the index.
173 */
174 get size(): number {
175 return this.#inner.size
176 }
177
178 /**
179 * This method checks if the index has a given key.
180 * @param key - The key to check.
181 * @returns True if the index has the key, false otherwise.
182 */
183 has(key: TKey): boolean {
184 return this.#inner.has(key)
185 }
186
187 /**
188 * This method returns all values for a given key.
189 * @param key - The key to get the values for.
190 * @returns An array of value tuples [value, multiplicity].
191 */
192 get(key: TKey): Array<[TValue, number]> {
193 return [...this.getIterator(key)]
194 }
195
196 /**
197 * This method returns an iterator over all values for a given key.
198 * @param key - The key to get the values for.
199 * @returns An iterator of value tuples [value, multiplicity].
200 */
201 *getIterator(key: TKey): Iterable<[TValue, number]> {
202 const mapOrSingleValue = this.#inner.get(key)
203 if (isSingleValue(mapOrSingleValue)) {
204 yield mapOrSingleValue
205 } else if (mapOrSingleValue === undefined) {
206 return
207 } else if (mapOrSingleValue instanceof ValueMap) {
208 // Direct ValueMap - all values have NO_PREFIX
209 for (const valueTuple of mapOrSingleValue.values()) {
210 yield valueTuple
211 }
212 } else {
213 // PrefixMap - iterate through all prefixes
214 for (const singleValueOrValueMap of mapOrSingleValue.values()) {
215 if (isSingleValue(singleValueOrValueMap)) {
216 yield singleValueOrValueMap
217 } else {
218 for (const valueTuple of singleValueOrValueMap.values()) {
219 yield valueTuple
220 }
221 }
222 }
223 }
224 }
225
226 /**
227 * This returns an iterator that iterates over all key-value pairs.
228 * @returns An iterable of all key-value pairs (and their multiplicities) in the index.
229 */
230 *entries(): Iterable<[TKey, [TValue, number]]> {
231 for (const key of this.#inner.keys()) {
232 for (const valueTuple of this.getIterator(key)) {
233 yield [key, valueTuple]
234 }
235 }
236 }
237
238 /**
239 * This method only iterates over the keys and not over the values.
240 * Hence, it is more efficient than the `#entries` method.
241 * It returns an iterator that you can use if you need to iterate over the values for a given key.
242 * @returns An iterator of all *keys* in the index and their corresponding value iterator.
243 */
244 *entriesIterators(): Iterable<[TKey, Iterable<[TValue, number]>]> {
245 for (const key of this.#inner.keys()) {
246 yield [key, this.getIterator(key)]
247 }
248 }
249
250 /**
251 * This method adds a value to the index.
252 * @param key - The key to add the value to.
253 * @param valueTuple - The value tuple [value, multiplicity] to add to the index.
254 */
255 addValue(key: TKey, valueTuple: SingleValue<TValue>) {
256 const [value, multiplicity] = valueTuple
257 // If the multiplicity is 0, do nothing
258 if (multiplicity === 0) return
259
260 const mapOrSingleValue = this.#inner.get(key)
261
262 if (mapOrSingleValue === undefined) {
263 // First value for this key
264 this.#inner.set(key, valueTuple)
265 return
266 }
267
268 if (isSingleValue(mapOrSingleValue)) {
269 // Handle transition from single value to map
270 this.#handleSingleValueTransition(
271 key,
272 mapOrSingleValue,
273 value,
274 multiplicity
275 )
276 return
277 }
278
279 if (mapOrSingleValue instanceof ValueMap) {
280 // Handle existing ValueMap
281 const prefix = getPrefix<TValue, TPrefix>(value)
282 if (prefix !== NO_PREFIX) {
283 // Convert ValueMap to PrefixMap since we have a prefixed value
284 const prefixMap = new PrefixMap<TValue, TPrefix>()
285 prefixMap.set(NO_PREFIX, mapOrSingleValue)
286 prefixMap.set(prefix, valueTuple)
287 this.#inner.set(key, prefixMap)
288 } else {
289 // Add to existing ValueMap
290 const isEmpty = mapOrSingleValue.addValue(value, multiplicity)
291 if (isEmpty) {
292 this.#inner.delete(key)
293 }
294 }
295 } else {
296 // Handle existing PrefixMap
297 const isEmpty = mapOrSingleValue.addValue(value, multiplicity)
298 if (isEmpty) {
299 this.#inner.delete(key)
300 }
301 }
302 }
303
304 /**
305 * Handle the transition from a single value to either a ValueMap or PrefixMap
306 */
307 #handleSingleValueTransition(
308 key: TKey,
309 currentSingleValue: SingleValue<TValue>,
310 newValue: TValue,
311 multiplicity: number
312 ) {
313 const [currentValue, currentMultiplicity] = currentSingleValue
314
315 // Check for exact same value (reference equality)
316 if (currentValue === newValue) {
317 const newMultiplicity = currentMultiplicity + multiplicity
318 if (newMultiplicity === 0) {
319 this.#inner.delete(key)
320 } else {
321 this.#inner.set(key, [newValue, newMultiplicity])
322 }
323 return
324 }
325
326 // Get prefixes for both values
327 const newPrefix = getPrefix<TValue, TPrefix>(newValue)
328 const currentPrefix = getPrefix<TValue, TPrefix>(currentValue)
329
330 // Check if they're the same value by prefix/suffix comparison
331 if (
332 currentPrefix === newPrefix &&
333 (currentValue === newValue || hash(currentValue) === hash(newValue))
334 ) {
335 const newMultiplicity = currentMultiplicity + multiplicity
336 if (newMultiplicity === 0) {
337 this.#inner.delete(key)
338 } else {
339 this.#inner.set(key, [newValue, newMultiplicity])
340 }
341 return
342 }
343
344 // Different values - choose appropriate map type
345 if (currentPrefix === NO_PREFIX && newPrefix === NO_PREFIX) {
346 // Both have NO_PREFIX, use ValueMap directly
347 const valueMap = new ValueMap<TValue>()
348 valueMap.set(hash(currentValue), currentSingleValue)
349 valueMap.set(hash(newValue), [newValue, multiplicity])
350 this.#inner.set(key, valueMap)
351 } else {
352 // At least one has a prefix, use PrefixMap
353 const prefixMap = new PrefixMap<TValue, TPrefix>()
354
355 if (currentPrefix === newPrefix) {
356 // Same prefix, different suffixes - need ValueMap within PrefixMap
357 const valueMap = new ValueMap<TValue>()
358 valueMap.set(hash(currentValue), currentSingleValue)
359 valueMap.set(hash(newValue), [newValue, multiplicity])
360 prefixMap.set(currentPrefix, valueMap)
361 } else {
362 // Different prefixes - store as separate single values
363 prefixMap.set(currentPrefix, currentSingleValue)
364 prefixMap.set(newPrefix, [newValue, multiplicity])
365 }
366
367 this.#inner.set(key, prefixMap)
368 }
369 }
370
371 /**
372 * This method appends another index to the current index.
373 * @param other - The index to append to the current index.
374 */
375 append(other: Index<TKey, TValue>): void {
376 for (const [key, value] of other.entries()) {
377 this.addValue(key, value)
378 }
379 }
380
381 /**
382 * This method joins two indexes.
383 * @param other - The index to join with the current index.
384 * @returns A multiset of the joined values.
385 */
386 join<TValue2>(
387 other: Index<TKey, TValue2>
388 ): MultiSet<[TKey, [TValue, TValue2]]> {
389 const result: Array<[[TKey, [TValue, TValue2]], number]> = []
390 // We want to iterate over the smaller of the two indexes to reduce the
391 // number of operations we need to do.
392 if (this.size <= other.size) {
393 for (const [key, valueIt] of this.entriesIterators()) {
394 if (!other.has(key)) continue
395 const otherValues = other.get(key)
396 for (const [val1, mul1] of valueIt) {
397 for (const [val2, mul2] of otherValues) {
398 if (mul1 !== 0 && mul2 !== 0) {
399 result.push([[key, [val1, val2]], mul1 * mul2])
400 }
401 }
402 }
403 }
404 } else {
405 for (const [key, otherValueIt] of other.entriesIterators()) {
406 if (!this.has(key)) continue
407 const values = this.get(key)
408 for (const [val2, mul2] of otherValueIt) {
409 for (const [val1, mul1] of values) {
410 if (mul1 !== 0 && mul2 !== 0) {
411 result.push([[key, [val1, val2]], mul1 * mul2])
412 }
413 }
414 }
415 }
416 }
417
418 return new MultiSet(result)
419 }
420}
421
422/**
423 * This function extracts the prefix from a value.
424 * @param value - The value to extract the prefix from.
425 * @returns The prefix and the suffix.
426 */
427function getPrefix<TValue, TPrefix>(value: TValue): TPrefix | NO_PREFIX {
428 // If the value is an array and the first element is a string or number, then the
429 // first element is the prefix. This is used to distinguish between values without
430 // the need for hashing unless there are multiple values for the same prefix.
431 if (
432 Array.isArray(value) &&
433 (typeof value[0] === `string` ||
434 typeof value[0] === `number` ||
435 typeof value[0] === `bigint`)
436 ) {
437 return value[0] as TPrefix
438 }
439 return NO_PREFIX
440}
441
442/**
443 * This function checks if a value is a single value.
444 * @param value - The value to check.
445 * @returns True if the value is a single value, false otherwise.
446 */
447function isSingleValue<TValue>(
448 value: SingleValue<TValue> | unknown
449): value is SingleValue<TValue> {
450 return Array.isArray(value)
451}