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 } from './topKArray.js'
12import type { DifferenceStreamReader } from '../graph.js'
13import type { IStreamBuilder, PipedOperator } from '../types.js'
14
15export interface TopKWithFractionalIndexOptions {
16 limit?: number
17 offset?: number
18 setSizeCallback?: SetSizeCallback
19 setWindowFn?: (
20 windowFn: (options: { offset?: number; limit?: number }) => void,
21 ) => void
22}
23
24/**
25 * Receives the window size. Given a predicate that holds for a prefix of the
26 * window order, the getter counts only the leading values that satisfy it.
27 */
28export type SetSizeCallback = (
29 getSize: (counts?: (value: unknown) => boolean) => number,
30) => void
31
32/**
33 * Operator for fractional indexed topK operations
34 * This operator maintains fractional indices for sorted elements
35 * and only updates indices when elements move position
36 */
37export class TopKWithFractionalIndexOperator<
38 K extends string | number,
39 T,
40> extends UnaryOperator<[K, T], [K, IndexedValue<T>]> {
41 #state: TopKState<K, T>
42
43 constructor(
44 id: number,
45 inputA: DifferenceStreamReader<[K, T]>,
46 output: DifferenceStreamWriter<[K, IndexedValue<T>]>,
47 comparator: (a: T, b: T) => number,
48 options: TopKWithFractionalIndexOptions,
49 ) {
50 super(id, inputA, output)
51 const limit = options.limit ?? Infinity
52 const offset = options.offset ?? 0
53 this.#state = new TopKState(
54 new TopKArray(offset, limit, createKeyedComparator(comparator)),
55 )
56 options.setSizeCallback?.((counts) =>
57 counts ? this.#state.countLeadingInWindow(counts) : this.#state.size,
58 )
59 options.setWindowFn?.(this.moveTopK.bind(this))
60 }
61
62 /**
63 * Moves the topK window based on the provided offset and limit.
64 * Any changes to the topK are sent to the output.
65 */
66 moveTopK({ offset, limit }: { offset?: number; limit?: number }) {
67 const result: Array<[[K, IndexedValue<T>], number]> = []
68 const diff = this.#state.move({ offset, limit })
69
70 diff.moveIns.forEach((moveIn) => handleMoveIn(moveIn, result))
71 diff.moveOuts.forEach((moveOut) => handleMoveOut(moveOut, result))
72
73 if (diff.changes) {
74 // There are changes to the topK
75 // it could be that moveIns and moveOuts are empty
76 // because the collection is lazy, so we will run the graph again to load the data
77 this.output.sendData(new MultiSet(result))
78 }
79 }
80
81 run(): void {
82 const result: Array<[[K, IndexedValue<T>], number]> = []
83 for (const [[key, value], multiplicity] of topKBatch(
84 this.inputMessages(),
85 )) {
86 this.processElement(key, value, multiplicity, result)
87 }
88
89 if (result.length > 0) {
90 this.output.sendData(new MultiSet(result))
91 }
92 }
93
94 processElement(
95 key: K,
96 value: T,
97 multiplicity: number,
98 result: Array<[[K, IndexedValue<T>], number]>,
99 ): void {
100 const changes = this.#state.processElement(key, value, multiplicity)
101 handleMoveIn(changes.moveIn, result)
102 handleMoveOut(changes.moveOut, result)
103 }
104}
105
106/**
107 * Limits the number of results based on a comparator, with optional offset.
108 * Uses fractional indexing to minimize the number of changes when elements move positions.
109 * Each element is assigned a fractional index that is lexicographically sortable.
110 * When elements move, only the indices of the moved elements are updated, not all elements.
111 *
112 * @param comparator - A function that compares two elements
113 * @param options - An optional object containing limit and offset properties
114 * @returns A piped operator that orders the elements and limits the number of results
115 */
116export function topKWithFractionalIndex<KType extends string | number, T>(
117 comparator: (a: T, b: T) => number,
118 options?: TopKWithFractionalIndexOptions,
119): PipedOperator<[KType, T], [KType, IndexedValue<T>]> {
120 const opts = options || {}
121
122 return (
123 stream: IStreamBuilder<[KType, T]>,
124 ): IStreamBuilder<[KType, IndexedValue<T>]> => {
125 const output = new StreamBuilder<[KType, IndexedValue<T>]>(
126 stream.graph,
127 new DifferenceStreamWriter<[KType, IndexedValue<T>]>(),
128 )
129 const operator = new TopKWithFractionalIndexOperator<KType, T>(
130 stream.graph.getNextOperatorId(),
131 stream.connectReader(),
132 output.writer,
133 comparator,
134 opts,
135 )
136 stream.graph.addOperator(operator)
137 return output
138 }
139}