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

groupedTopKWithFractionalIndex.ts

185 lines5.9 KB

1import { DifferenceStreamWriter, UnaryOperator } from '../graph.js'
2import { StreamBuilder } from '../d2.js'
3import { MultiSet } from '../multiset.js'
4import {
5 TopKState,
6 handleMoveIn,
7 handleMoveOut,
8 topKBatch,
9} from './topKState.js'
10import { TopKArray, createKeyedComparator } from './topKArray.js'
11import type { IndexedValue } from './topKArray.js'
12import type { DifferenceStreamReader } from '../graph.js'
13import type { IStreamBuilder, PipedOperator } from '../types.js'
14​
15export interface GroupedTopKWithFractionalIndexOptions<K, T> {
16 limit?: number
17 offset?: number
18 setSizeCallback?: (getSize: () => number) => void
19 setWindowFn?: (
20 windowFn: (options: { offset?: number; limit?: number }) => void,
21 ) => void
22 /**
23 * Function to extract a group key from the element's key and value.
24 * Elements with the same group key will be sorted and limited together.
25 */
26 groupKeyFn: (key: K, value: T) => unknown
28​
29/**
30 * Operator for grouped fractional indexed topK operations.
31 * This operator maintains separate topK windows for each group,
32 * allowing per-group limits and ordering.
33 *
34 * The input is a keyed stream [K, T] and outputs [K, IndexedValue<T>].
35 * Elements are grouped by the groupKeyFn, and each group maintains
36 * its own sorted collection with independent limit/offset.
37 */
38export class GroupedTopKWithFractionalIndexOperator<
39 K extends string | number,
40 T,
41> extends UnaryOperator<[K, T], [K, IndexedValue<T>]> {
42 #groupStates: Map<unknown, TopKState<K, T>> = new Map()
43 #groupKeyFn: (key: K, value: T) => unknown
44 #comparator: (a: [K, T], b: [K, T]) => number
45 #offset: number
46 #limit: number
47​
48 constructor(
49 id: number,
50 inputA: DifferenceStreamReader<[K, T]>,
51 output: DifferenceStreamWriter<[K, IndexedValue<T>]>,
52 comparator: (a: T, b: T) => number,
53 options: GroupedTopKWithFractionalIndexOptions<K, T>,
54 ) {
55 super(id, inputA, output)
56 this.#groupKeyFn = options.groupKeyFn
57 this.#limit = options.limit ?? Infinity
58 this.#offset = options.offset ?? 0
59 this.#comparator = createKeyedComparator(comparator)
60 options.setSizeCallback?.(() => this.#getTotalSize())
61 options.setWindowFn?.(this.#moveTopK.bind(this))
62 }
63​
64 #getTotalSize(): number {
65 let size = 0
66 for (const state of this.#groupStates.values()) {
67 size += state.size
68 }
69 return size
70 }
71​
72 #getOrCreateGroupState(groupKey: unknown): TopKState<K, T> {
73 let state = this.#groupStates.get(groupKey)
74 if (!state) {
75 state = new TopKState(
76 new TopKArray(this.#offset, this.#limit, this.#comparator),
77 )
78 this.#groupStates.set(groupKey, state)
79 }
80 return state
81 }
82​
83 #cleanupGroupIfEmpty(groupKey: unknown, state: TopKState<K, T>): void {
84 if (state.isEmpty) {
85 this.#groupStates.delete(groupKey)
86 }
87 }
88​
89 /**
90 * Moves the topK window for all groups based on the provided offset and limit.
91 * Any changes to the topK are sent to the output.
92 */
93 #moveTopK({ offset, limit }: { offset?: number; limit?: number }): void {
94 if (offset !== undefined) {
95 this.#offset = offset
96 }
97 if (limit !== undefined) {
98 this.#limit = limit
99 }
100​
101 const result: Array<[[K, IndexedValue<T>], number]> = []
102 let hasChanges = false
103​
104 for (const state of this.#groupStates.values()) {
105 const diff = state.move({ offset: this.#offset, limit: this.#limit }) // TODO: think we should just pass offset and limit
106​
107 diff.moveIns.forEach((moveIn) => handleMoveIn(moveIn, result))
108 diff.moveOuts.forEach((moveOut) => handleMoveOut(moveOut, result))
109​
110 if (diff.changes) {
111 hasChanges = true
112 }
113 }
114​
115 if (hasChanges) {
116 this.output.sendData(new MultiSet(result))
117 }
118 }
119​
120 run(): void {
121 const result: Array<[[K, IndexedValue<T>], number]> = []
122 for (const [[key, value], multiplicity] of topKBatch(
123 this.inputMessages(),
124 )) {
125 this.#processElement(key, value, multiplicity, result)
126 }
127​
128 if (result.length > 0) {
129 this.output.sendData(new MultiSet(result))
130 }
131 }
132​
133 #processElement(
134 key: K,
135 value: T,
136 multiplicity: number,
137 result: Array<[[K, IndexedValue<T>], number]>,
138 ): void {
139 const groupKey = this.#groupKeyFn(key, value)
140 const state = this.#getOrCreateGroupState(groupKey)
141​
142 const changes = state.processElement(key, value, multiplicity)
143 handleMoveIn(changes.moveIn, result)
144 handleMoveOut(changes.moveOut, result)
145​
146 // Cleanup empty groups to prevent memory leaks
147 this.#cleanupGroupIfEmpty(groupKey, state)
148 }
150​
151/**
152 * Limits the number of results per group based on a comparator, with optional offset.
153 * Uses fractional indexing to minimize the number of changes when elements move positions.
154 * Each element is assigned a fractional index that is lexicographically sortable.
155 * When elements move, only the indices of the moved elements are updated, not all elements.
156 *
157 * This operator groups elements by the provided groupKeyFn and applies the limit/offset
158 * independently to each group.
159 *
160 * @param comparator - A function that compares two elements for ordering
161 * @param options - Configuration including groupKeyFn, limit, and offset
162 * @returns A piped operator that orders elements per group and limits results per group
163 */
164export function groupedTopKWithFractionalIndex<K extends string | number, T>(
165 comparator: (a: T, b: T) => number,
166 options: GroupedTopKWithFractionalIndexOptions<K, T>,
167): PipedOperator<[K, T], [K, IndexedValue<T>]> {
168 return (
169 stream: IStreamBuilder<[K, T]>,
170 ): IStreamBuilder<[K, IndexedValue<T>]> => {
171 const output = new StreamBuilder<[K, IndexedValue<T>]>(
172 stream.graph,
173 new DifferenceStreamWriter<[K, IndexedValue<T>]>(),
174 )
175 const operator = new GroupedTopKWithFractionalIndexOperator<K, T>(
176 stream.graph.getNextOperatorId(),
177 stream.connectReader(),
178 output.writer,
179 comparator,
180 options,
181 )
182 stream.graph.addOperator(operator)
183 return output
184 }