Open History to see the last commit
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, TopK } 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
27}
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 /**
65 * Creates a new TopK data structure for a group.
66 * Can be overridden in subclasses to use different implementations (e.g., B+ tree).
67 */
68 protected createTopK(
69 offset: number,
70 limit: number,
71 comparator: (a: [K, T], b: [K, T]) => number,
72 ): TopK<[K, T]> {
73 return new TopKArray(offset, limit, comparator)
74 }
75
76 #getTotalSize(): number {
77 let size = 0
78 for (const state of this.#groupStates.values()) {
79 size += state.size
80 }
81 return size
82 }
83
84 #getOrCreateGroupState(groupKey: unknown): TopKState<K, T> {
85 let state = this.#groupStates.get(groupKey)
86 if (!state) {
87 const topK = this.createTopK(this.#offset, this.#limit, this.#comparator)
88 state = new TopKState(topK)
89 this.#groupStates.set(groupKey, state)
90 }
91 return state
92 }
93
94 #cleanupGroupIfEmpty(groupKey: unknown, state: TopKState<K, T>): void {
95 if (state.isEmpty) {
96 this.#groupStates.delete(groupKey)
97 }
98 }
99
100 /**
101 * Moves the topK window for all groups based on the provided offset and limit.
102 * Any changes to the topK are sent to the output.
103 */
104 #moveTopK({ offset, limit }: { offset?: number; limit?: number }): void {
105 if (offset !== undefined) {
106 this.#offset = offset
107 }
108 if (limit !== undefined) {
109 this.#limit = limit
110 }
111
112 const result: Array<[[K, IndexedValue<T>], number]> = []
113 let hasChanges = false
114
115 for (const state of this.#groupStates.values()) {
116 const diff = state.move({ offset: this.#offset, limit: this.#limit }) // TODO: think we should just pass offset and limit
117
118 diff.moveIns.forEach((moveIn) => handleMoveIn(moveIn, result))
119 diff.moveOuts.forEach((moveOut) => handleMoveOut(moveOut, result))
120
121 if (diff.changes) {
122 hasChanges = true
123 }
124 }
125
126 if (hasChanges) {
127 this.output.sendData(new MultiSet(result))
128 }
129 }
130
131 run(): void {
132 const result: Array<[[K, IndexedValue<T>], number]> = []
133 for (const [[key, value], multiplicity] of topKBatch(
134 this.inputMessages(),
135 )) {
136 this.#processElement(key, value, multiplicity, result)
137 }
138
139 if (result.length > 0) {
140 this.output.sendData(new MultiSet(result))
141 }
142 }
143
144 #processElement(
145 key: K,
146 value: T,
147 multiplicity: number,
148 result: Array<[[K, IndexedValue<T>], number]>,
149 ): void {
150 const groupKey = this.#groupKeyFn(key, value)
151 const state = this.#getOrCreateGroupState(groupKey)
152
153 const changes = state.processElement(key, value, multiplicity)
154 handleMoveIn(changes.moveIn, result)
155 handleMoveOut(changes.moveOut, result)
156
157 // Cleanup empty groups to prevent memory leaks
158 this.#cleanupGroupIfEmpty(groupKey, state)
159 }
160}
161
162/**
163 * Limits the number of results per group based on a comparator, with optional offset.
164 * Uses fractional indexing to minimize the number of changes when elements move positions.
165 * Each element is assigned a fractional index that is lexicographically sortable.
166 * When elements move, only the indices of the moved elements are updated, not all elements.
167 *
168 * This operator groups elements by the provided groupKeyFn and applies the limit/offset
169 * independently to each group.
170 *
171 * @param comparator - A function that compares two elements for ordering
172 * @param options - Configuration including groupKeyFn, limit, and offset
173 * @returns A piped operator that orders elements per group and limits results per group
174 */
175export function groupedTopKWithFractionalIndex<K extends string | number, T>(
176 comparator: (a: T, b: T) => number,
177 options: GroupedTopKWithFractionalIndexOptions<K, T>,
178): PipedOperator<[K, T], [K, IndexedValue<T>]> {
179 return (
180 stream: IStreamBuilder<[K, T]>,
181 ): IStreamBuilder<[K, IndexedValue<T>]> => {
182 const output = new StreamBuilder<[K, IndexedValue<T>]>(
183 stream.graph,
184 new DifferenceStreamWriter<[K, IndexedValue<T>]>(),
185 )
186 const operator = new GroupedTopKWithFractionalIndexOperator<K, T>(
187 stream.graph.getNextOperatorId(),
188 stream.connectReader(),
189 output.writer,
190 comparator,
191 options,
192 )
193 stream.graph.addOperator(operator)
194 return output
195 }
196}