Open History to see the last commit
1import { equalHashValues } from '../hashing/hash.js'
2import { TopKArray } from './topKArray.js'
3import type { MultiSet } from '../multiset.js'
4import type {
5 IndexedValue,
6 TopK,
7 TopKChanges,
8 TopKMoveChanges,
9} from './topKArray.js'
10
11/** Apply a keyed batch's retractions before additions. An outer join can emit
12 * a replacement in the opposite order; key multiplicity alone would hide it.
13 * Consolidate first so a transient value added and removed in this same turn
14 * cannot be mistaken for the final replacement. Use structural relation
15 * identity: map can allocate a fresh value for each side of a cancelling pair.
16 * No state survives the run.
17 */
18export function* topKBatch<K, T>(messages: Array<MultiSet<[K, T]>>) {
19 const keyed = new Map<K, Array<[[K, T], number]>>()
20 for (const message of messages) {
21 for (const [value, weight] of message.getInner()) {
22 const entries = keyed.get(value[0])
23 if (entries) entries.push([value, weight])
24 else keyed.set(value[0], [[value, weight]])
25 }
26 }
27 const batch: Array<[[K, T], number]> = []
28 for (const entries of keyed.values()) {
29 // Ordering distinct keys needs only the caller's comparator. In particular,
30 // do not traverse irrelevant payloads or merge keys on a hash collision.
31 if (entries.length === 1) {
32 batch.push(entries[0]!)
33 continue
34 }
35 // A per-key scan keeps normal two-version replacements cheap and permits
36 // cycles, at the cost of quadratic comparisons for long same-key histories.
37 const consolidated: Array<[[K, T], number]> = []
38 for (const [value, weight] of entries) {
39 const previous = consolidated.find(([candidate]) =>
40 equalHashValues(candidate[1], value[1]),
41 )
42 if (previous) previous[1] += weight
43 else consolidated.push([value, weight])
44 }
45 batch.push(...consolidated)
46 }
47 for (const entry of batch) if (entry[1] < 0) yield entry
48 for (const entry of batch) if (entry[1] > 0) yield entry
49}
50
51/**
52 * Helper class that manages the state for a single topK window.
53 * Encapsulates the multiplicity tracking and topK data structure,
54 * providing a clean interface for processing elements and moving the window.
55 *
56 * This class is used by both TopKWithFractionalIndexOperator (single instance)
57 * and GroupedTopKWithFractionalIndexOperator (one instance per group).
58 */
59export class TopKState<K extends string | number, T> {
60 #multiplicities: Map<K, number> = new Map()
61 #topK: TopK<[K, T]>
62
63 constructor(topK: TopK<[K, T]>) {
64 this.#topK = topK
65 }
66
67 get size(): number {
68 return this.#topK.size
69 }
70
71 countLeadingInWindow(predicate: (value: T) => boolean): number {
72 return (
73 this.#topK.countLeadingInWindow?.(([, value]) => predicate(value)) ??
74 this.#topK.size
75 )
76 }
77
78 get isEmpty(): boolean {
79 return this.#multiplicities.size === 0 && this.#topK.size === 0
80 }
81
82 /**
83 * Process an element update (insert or delete based on multiplicity change).
84 * Returns the changes to the topK window.
85 */
86 processElement(key: K, value: T, multiplicity: number): TopKChanges<[K, T]> {
87 const { oldMultiplicity, newMultiplicity } = this.#updateMultiplicity(
88 key,
89 multiplicity,
90 )
91
92 if (oldMultiplicity <= 0 && newMultiplicity > 0) {
93 // The value was invisible but should now be visible
94 return this.#topK.insert([key, value])
95 } else if (oldMultiplicity > 0 && newMultiplicity <= 0) {
96 // The value was visible but should now be invisible
97 return this.#topK.delete([key, value])
98 }
99 // The value was invisible and remains invisible,
100 // or was visible and remains visible - no topK change
101 return { moveIn: null, moveOut: null }
102 }
103
104 /**
105 * Move the topK window. Only works with TopKArray implementation.
106 */
107 move(options: { offset?: number; limit?: number }): TopKMoveChanges<[K, T]> {
108 if (!(this.#topK instanceof TopKArray)) {
109 throw new Error(
110 `Cannot move B+-tree implementation of TopK with fractional index`,
111 )
112 }
113 return this.#topK.move(options)
114 }
115
116 #updateMultiplicity(
117 key: K,
118 multiplicity: number,
119 ): { oldMultiplicity: number; newMultiplicity: number } {
120 if (multiplicity === 0) {
121 const current = this.#multiplicities.get(key) ?? 0
122 return { oldMultiplicity: current, newMultiplicity: current }
123 }
124
125 const oldMultiplicity = this.#multiplicities.get(key) ?? 0
126 const newMultiplicity = oldMultiplicity + multiplicity
127 if (newMultiplicity === 0) {
128 this.#multiplicities.delete(key)
129 } else {
130 this.#multiplicities.set(key, newMultiplicity)
131 }
132 return { oldMultiplicity, newMultiplicity }
133 }
134}
135
136/**
137 * Handles a moveIn change by adding it to the result array.
138 */
139export function handleMoveIn<K extends string | number, T>(
140 moveIn: IndexedValue<[K, T]> | null,
141 result: Array<[[K, IndexedValue<T>], number]>,
142): void {
143 if (moveIn) {
144 const [[key, value], index] = moveIn
145 result.push([[key, [value, index]], 1])
146 }
147}
148
149/**
150 * Handles a moveOut change by adding it to the result array.
151 */
152export function handleMoveOut<K extends string | number, T>(
153 moveOut: IndexedValue<[K, T]> | null,
154 result: Array<[[K, IndexedValue<T>], number]>,
155): void {
156 if (moveOut) {
157 const [[key, value], index] = moveOut
158 result.push([[key, [value, index]], -1])
159 }
160}