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 get isEmpty(): boolean {
72 return this.#multiplicities.size === 0 && this.#topK.size === 0
73 }
74
75 /**
76 * Process an element update (insert or delete based on multiplicity change).
77 * Returns the changes to the topK window.
78 */
79 processElement(key: K, value: T, multiplicity: number): TopKChanges<[K, T]> {
80 const { oldMultiplicity, newMultiplicity } = this.#updateMultiplicity(
81 key,
82 multiplicity,
83 )
84
85 if (oldMultiplicity <= 0 && newMultiplicity > 0) {
86 // The value was invisible but should now be visible
87 return this.#topK.insert([key, value])
88 } else if (oldMultiplicity > 0 && newMultiplicity <= 0) {
89 // The value was visible but should now be invisible
90 return this.#topK.delete([key, value])
91 }
92 // The value was invisible and remains invisible,
93 // or was visible and remains visible - no topK change
94 return { moveIn: null, moveOut: null }
95 }
96
97 /**
98 * Move the topK window. Only works with TopKArray implementation.
99 */
100 move(options: { offset?: number; limit?: number }): TopKMoveChanges<[K, T]> {
101 if (!(this.#topK instanceof TopKArray)) {
102 throw new Error(
103 `Cannot move B+-tree implementation of TopK with fractional index`,
104 )
105 }
106 return this.#topK.move(options)
107 }
108
109 #updateMultiplicity(
110 key: K,
111 multiplicity: number,
112 ): { oldMultiplicity: number; newMultiplicity: number } {
113 if (multiplicity === 0) {
114 const current = this.#multiplicities.get(key) ?? 0
115 return { oldMultiplicity: current, newMultiplicity: current }
116 }
117
118 const oldMultiplicity = this.#multiplicities.get(key) ?? 0
119 const newMultiplicity = oldMultiplicity + multiplicity
120 if (newMultiplicity === 0) {
121 this.#multiplicities.delete(key)
122 } else {
123 this.#multiplicities.set(key, newMultiplicity)
124 }
125 return { oldMultiplicity, newMultiplicity }
126 }
127}
128
129/**
130 * Handles a moveIn change by adding it to the result array.
131 */
132export function handleMoveIn<K extends string | number, T>(
133 moveIn: IndexedValue<[K, T]> | null,
134 result: Array<[[K, IndexedValue<T>], number]>,
135): void {
136 if (moveIn) {
137 const [[key, value], index] = moveIn
138 result.push([[key, [value, index]], 1])
139 }
140}
141
142/**
143 * Handles a moveOut change by adding it to the result array.
144 */
145export function handleMoveOut<K extends string | number, T>(
146 moveOut: IndexedValue<[K, T]> | null,
147 result: Array<[[K, IndexedValue<T>], number]>,
148): void {
149 if (moveOut) {
150 const [[key, value], index] = moveOut
151 result.push([[key, [value, index]], -1])
152 }
153}