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

topKState.ts

143 lines4.8 KB

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
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 = this.#multiplicities.get(key) ?? 0
88 const newMultiplicity = oldMultiplicity + multiplicity
89 if (multiplicity !== 0) {
90 if (newMultiplicity === 0) this.#multiplicities.delete(key)
91 else this.#multiplicities.set(key, newMultiplicity)
92 }
93​
94 if (oldMultiplicity <= 0 && newMultiplicity > 0) {
95 // The value was invisible but should now be visible
96 return this.#topK.insert([key, value])
97 } else if (oldMultiplicity > 0 && newMultiplicity <= 0) {
98 // The value was visible but should now be invisible
99 return this.#topK.delete([key, value])
100 }
101 // The value was invisible and remains invisible,
102 // or was visible and remains visible - no topK change
103 return { moveIn: null, moveOut: null }
104 }
105​
106 /**
107 * Move the topK window. Only works with TopKArray implementation.
108 */
109 move(options: { offset?: number; limit?: number }): TopKMoveChanges<[K, T]> {
110 if (!(this.#topK instanceof TopKArray)) {
111 throw new Error(
112 `Cannot move B+-tree implementation of TopK with fractional index`,
113 )
114 }
115 return this.#topK.move(options)
116 }
118​
119/**
120 * Handles a moveIn change by adding it to the result array.
121 */
122export function handleMoveIn<K extends string | number, T>(
123 moveIn: IndexedValue<[K, T]> | null,
124 result: Array<[[K, IndexedValue<T>], number]>,
125): void {
126 if (moveIn) {
127 const [[key, value], index] = moveIn
128 result.push([[key, [value, index]], 1])
129 }
131​
132/**
133 * Handles a moveOut change by adding it to the result array.
134 */
135export function handleMoveOut<K extends string | number, T>(
136 moveOut: IndexedValue<[K, T]> | null,
137 result: Array<[[K, IndexedValue<T>], number]>,
138): void {
139 if (moveOut) {
140 const [[key, value], index] = moveOut
141 result.push([[key, [value, index]], -1])
142 }