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

topKWithFractionalIndex.ts

371 lines12.5 KB

1import { generateKeyBetween } from "fractional-indexing"
2import { DifferenceStreamWriter, UnaryOperator } from "../graph.js"
3import { StreamBuilder } from "../d2.js"
4import { MultiSet } from "../multiset.js"
5import { binarySearch, globalObjectIdGenerator } from "../utils.js"
6import type { DifferenceStreamReader } from "../graph.js"
7import type { IStreamBuilder, PipedOperator } from "../types.js"
8​
9export interface TopKWithFractionalIndexOptions {
10 limit?: number
11 offset?: number
12 setSizeCallback?: (getSize: () => number) => void
14​
15export type TopKChanges<V> = {
16 /** Indicates which element moves into the topK (if any) */
17 moveIn: IndexedValue<V> | null
18 /** Indicates which element moves out of the topK (if any) */
19 moveOut: IndexedValue<V> | null
21​
22/**
23 * A topK data structure that supports insertions and deletions
24 * and returns changes to the topK.
25 */
26export interface TopK<V> {
27 size: number
28 insert: (value: V) => TopKChanges<V>
29 delete: (value: V) => TopKChanges<V>
31​
32/**
33 * Implementation of a topK data structure.
34 * Uses a sorted array internally to store the values and keeps a topK window over that array.
35 * Inserts and deletes are O(n) operations because worst case an element is inserted/deleted
36 * at the start of the array which causes all the elements to shift to the right/left.
37 */
38class TopKArray<V> implements TopK<V> {
39 #sortedValues: Array<IndexedValue<V>> = []
40 #comparator: (a: V, b: V) => number
41 #topKStart: number
42 #topKEnd: number
43​
44 constructor(
45 offset: number,
46 limit: number,
47 comparator: (a: V, b: V) => number
48 ) {
49 this.#topKStart = offset
50 this.#topKEnd = offset + limit
51 this.#comparator = comparator
52 }
53​
54 get size(): number {
55 const offset = this.#topKStart
56 const limit = this.#topKEnd - this.#topKStart
57 const available = this.#sortedValues.length - offset
58 return Math.max(0, Math.min(limit, available))
59 }
60​
61 insert(value: V): TopKChanges<V> {
62 const result: TopKChanges<V> = { moveIn: null, moveOut: null }
63​
64 // Lookup insert position
65 const index = this.#findIndex(value)
66 // Generate fractional index based on the fractional indices of the elements before and after it
67 const indexBefore =
68 index === 0 ? null : getIndex(this.#sortedValues[index - 1]!)
69 const indexAfter =
70 index === this.#sortedValues.length
71 ? null
72 : getIndex(this.#sortedValues[index]!)
73 const fractionalIndex = generateKeyBetween(indexBefore, indexAfter)
74​
75 // Insert the value at the correct position
76 const val = indexedValue(value, fractionalIndex)
77 // Splice is O(n) where n = all elements in the collection (i.e. n >= k) !
78 this.#sortedValues.splice(index, 0, val)
79​
80 // Check if the topK changed
81 if (index < this.#topKEnd) {
82 // The inserted element is either before the top K or within the top K
83 // If it is before the top K then it moves the element that was right before the topK into the topK
84 // If it is within the top K then the inserted element moves into the top K
85 // In both cases the last element of the old top K now moves out of the top K
86 const moveInIndex = Math.max(index, this.#topKStart)
87 if (moveInIndex < this.#sortedValues.length) {
88 // We actually have a topK
89 // because in some cases there may not be enough elements in the array to reach the start of the topK
90 // e.g. [1, 2, 3] with K = 2 and offset = 3 does not have a topK
91 result.moveIn = this.#sortedValues[moveInIndex]!
92​
93 // We need to remove the element that falls out of the top K
94 // The element that falls out of the top K has shifted one to the right
95 // because of the element we inserted, so we find it at index topKEnd
96 if (this.#topKEnd < this.#sortedValues.length) {
97 result.moveOut = this.#sortedValues[this.#topKEnd]!
98 }
99 }
100 }
101​
102 return result
103 }
104​
105 /**
106 * Deletes a value that may or may not be in the topK.
107 * IMPORTANT: this assumes that the value is present in the collection
108 * if it's not the case it will remove the element
109 * that is on the position where the provided `value` would be.
110 */
111 delete(value: V): TopKChanges<V> {
112 const result: TopKChanges<V> = { moveIn: null, moveOut: null }
113​
114 // Lookup delete position
115 const index = this.#findIndex(value)
116 // Remove the value at that position
117 const [removedElem] = this.#sortedValues.splice(index, 1)
118​
119 // Check if the topK changed
120 if (index < this.#topKEnd) {
121 // The removed element is either before the top K or within the top K
122 // If it is before the top K then the first element of the topK moves out of the topK
123 // If it is within the top K then the removed element moves out of the topK
124 result.moveOut = removedElem!
125 if (index < this.#topKStart) {
126 // The removed element is before the topK
127 // so actually, the first element of the topK moves out of the topK
128 // and not the element that we removed
129 // The first element of the topK is now at index topKStart - 1
130 // since we removed an element before the topK
131 const moveOutIndex = this.#topKStart - 1
132 if (moveOutIndex < this.#sortedValues.length) {
133 result.moveOut = this.#sortedValues[moveOutIndex]!
134 } else {
135 // No value is moving out of the topK
136 // because there are no elements in the topK
137 result.moveOut = null
138 }
139 }
140​
141 // Since we removed an element that was before or in the topK
142 // the first element after the topK moved one position to the left
143 // and thus falls into the topK now
144 const moveInIndex = this.#topKEnd - 1
145 if (moveInIndex < this.#sortedValues.length) {
146 result.moveIn = this.#sortedValues[moveInIndex]!
147 }
148 }
149​
150 return result
151 }
152​
153 // TODO: see if there is a way to refactor the code for insert and delete in the topK above
154 // because they are very similar, one is shifting the topK window to the left and the other is shifting it to the right
155 // so i have the feeling there is a common pattern here and we can implement both cases using that pattern
156​
157 #findIndex(value: V): number {
158 return binarySearch(this.#sortedValues, indexedValue(value, ``), (a, b) =>
159 this.#comparator(getValue(a), getValue(b))
160 )
161 }
163​
164/**
165 * Operator for fractional indexed topK operations
166 * This operator maintains fractional indices for sorted elements
167 * and only updates indices when elements move position
168 */
169export class TopKWithFractionalIndexOperator<K, T> extends UnaryOperator<
170 [K, T],
171 [K, IndexedValue<T>]
172> {
173 #index: Map<K, number> = new Map() // maps keys to their multiplicity
174​
175 /**
176 * topK data structure that supports insertions and deletions
177 * and returns changes to the topK.
178 */
179 #topK: TopK<TaggedValue<K, T>>
180​
181 #limit: number
182​
183 constructor(
184 id: number,
185 inputA: DifferenceStreamReader<[K, T]>,
186 output: DifferenceStreamWriter<[K, IndexedValue<T>]>,
187 comparator: (a: T, b: T) => number,
188 options: TopKWithFractionalIndexOptions
189 ) {
190 super(id, inputA, output)
191 this.#limit = options.limit ?? Infinity
192 const offset = options.offset ?? 0
193 const compareTaggedValues = (
194 a: TaggedValue<K, T>,
195 b: TaggedValue<K, T>
196 ) => {
197 // First compare on the value
198 const valueComparison = comparator(getVal(a), getVal(b))
199 if (valueComparison !== 0) {
200 return valueComparison
201 }
202 // If the values are equal, compare on the tag (object identity)
203 const tieBreakerA = getTag(a)
204 const tieBreakerB = getTag(b)
205 return tieBreakerA - tieBreakerB
206 }
207 this.#topK = this.createTopK(offset, this.#limit, compareTaggedValues)
208 options.setSizeCallback?.(() => this.#topK.size)
209 }
210​
211 protected createTopK(
212 offset: number,
213 limit: number,
214 comparator: (a: TaggedValue<K, T>, b: TaggedValue<K, T>) => number
215 ): TopK<TaggedValue<K, T>> {
216 return new TopKArray(offset, limit, comparator)
217 }
218​
219 run(): void {
220 const result: Array<[[K, IndexedValue<T>], number]> = []
221 for (const message of this.inputMessages()) {
222 for (const [item, multiplicity] of message.getInner()) {
223 const [key, value] = item
224 this.processElement(key, value, multiplicity, result)
225 }
226 }
227​
228 if (result.length > 0) {
229 this.output.sendData(new MultiSet(result))
230 }
231 }
232​
233 processElement(
234 key: K,
235 value: T,
236 multiplicity: number,
237 result: Array<[[K, IndexedValue<T>], number]>
238 ): void {
239 const { oldMultiplicity, newMultiplicity } = this.addKey(key, multiplicity)
240​
241 let res: TopKChanges<TaggedValue<K, T>> = {
242 moveIn: null,
243 moveOut: null,
244 }
245 if (oldMultiplicity <= 0 && newMultiplicity > 0) {
246 // The value was invisible but should now be visible
247 // Need to insert it into the array of sorted values
248 const taggedValue = tagValue(key, value)
249 res = this.#topK.insert(taggedValue)
250 } else if (oldMultiplicity > 0 && newMultiplicity <= 0) {
251 // The value was visible but should now be invisible
252 // Need to remove it from the array of sorted values
253 const taggedValue = tagValue(key, value)
254 res = this.#topK.delete(taggedValue)
255 } else {
256 // The value was invisible and it remains invisible
257 // or it was visible and remains visible
258 // so it doesn't affect the topK
259 }
260​
261 if (res.moveIn) {
262 const index = getIndex(res.moveIn)
263 const taggedValue = getValue(res.moveIn)
264 const k = getKey(taggedValue)
265 const val = getVal(taggedValue)
266 result.push([[k, [val, index]], 1])
267 }
268​
269 if (res.moveOut) {
270 const index = getIndex(res.moveOut)
271 const taggedValue = getValue(res.moveOut)
272 const k = getKey(taggedValue)
273 const val = getVal(taggedValue)
274 result.push([[k, [val, index]], -1])
275 }
276​
277 return
278 }
279​
280 private getMultiplicity(key: K): number {
281 return this.#index.get(key) ?? 0
282 }
283​
284 private addKey(
285 key: K,
286 multiplicity: number
287 ): { oldMultiplicity: number; newMultiplicity: number } {
288 const oldMultiplicity = this.getMultiplicity(key)
289 const newMultiplicity = oldMultiplicity + multiplicity
290 if (newMultiplicity === 0) {
291 this.#index.delete(key)
292 } else {
293 this.#index.set(key, newMultiplicity)
294 }
295 return { oldMultiplicity, newMultiplicity }
296 }
298​
299/**
300 * Limits the number of results based on a comparator, with optional offset.
301 * Uses fractional indexing to minimize the number of changes when elements move positions.
302 * Each element is assigned a fractional index that is lexicographically sortable.
303 * When elements move, only the indices of the moved elements are updated, not all elements.
304 *
305 * @param comparator - A function that compares two elements
306 * @param options - An optional object containing limit and offset properties
307 * @returns A piped operator that orders the elements and limits the number of results
308 */
309export function topKWithFractionalIndex<KType, T>(
310 comparator: (a: T, b: T) => number,
311 options?: TopKWithFractionalIndexOptions
312): PipedOperator<[KType, T], [KType, IndexedValue<T>]> {
313 const opts = options || {}
314​
315 return (
316 stream: IStreamBuilder<[KType, T]>
317 ): IStreamBuilder<[KType, IndexedValue<T>]> => {
318 const output = new StreamBuilder<[KType, IndexedValue<T>]>(
319 stream.graph,
320 new DifferenceStreamWriter<[KType, IndexedValue<T>]>()
321 )
322 const operator = new TopKWithFractionalIndexOperator<KType, T>(
323 stream.graph.getNextOperatorId(),
324 stream.connectReader(),
325 output.writer,
326 comparator,
327 opts
328 )
329 stream.graph.addOperator(operator)
330 stream.graph.addStream(output.connectReader())
331 return output
332 }
334​
335// Abstraction for fractionally indexed values
336export type FractionalIndex = string
337export type IndexedValue<V> = [V, FractionalIndex]
338​
339export function indexedValue<V>(
340 value: V,
341 index: FractionalIndex
342): IndexedValue<V> {
343 return [value, index]
345​
346export function getValue<V>(indexedVal: IndexedValue<V>): V {
347 return indexedVal[0]
349​
350export function getIndex<V>(indexedVal: IndexedValue<V>): FractionalIndex {
351 return indexedVal[1]
353​
354export type Tag = number
355export type TaggedValue<K, V> = [K, V, Tag]
356​
357function tagValue<K, V>(key: K, value: V): TaggedValue<K, V> {
358 return [key, value, globalObjectIdGenerator.getId(key)]
360​
361function getKey<K, V>(tieBreakerTaggedValue: TaggedValue<K, V>): K {
362 return tieBreakerTaggedValue[0]
364​
365function getVal<K, V>(tieBreakerTaggedValue: TaggedValue<K, V>): V {
366 return tieBreakerTaggedValue[1]
368​
369function getTag<K, V>(tieBreakerTaggedValue: TaggedValue<K, V>): Tag {
370 return tieBreakerTaggedValue[2]