Open History to see the last commit
1import { expect } from 'vitest'
2import { MultiSet } from '../src/multiset.js'
3
4// Enable detailed logging of test results when LOG_RESULTS is set
5const LOG_RESULTS =
6 process.env.LOG_RESULTS === `true` || process.env.LOG_RESULTS === `1`
7
8/**
9 * Materialize a result set from weighted deltas
10 * Takes an array of weighted deltas and consolidates them into a final result set
11 */
12export function materializeResults<T>(
13 weightedDeltas: Array<[T, number]>,
14): Map<string, T> {
15 const multiSet = new MultiSet(weightedDeltas)
16 const consolidated = multiSet.consolidate()
17 const result = new Map<string, T>()
18
19 for (const [item, multiplicity] of consolidated.getInner()) {
20 if (multiplicity > 0) {
21 // Use JSON.stringify for content-based key comparison
22 const key = JSON.stringify(item)
23 result.set(key, item)
24 }
25 }
26
27 return result
28}
29
30/**
31 * Materialize a keyed result set from weighted deltas
32 * Takes an array of keyed weighted deltas and consolidates them per key
33 */
34export function materializeKeyedResults<K, V>(
35 weightedDeltas: Array<[[K, V], number]>,
36): Map<K, V> {
37 const result = new Map<K, Map<string, { value: V; multiplicity: number }>>()
38
39 // Group weighted deltas by key first
40 for (const [[key, value], multiplicity] of weightedDeltas) {
41 if (!result.has(key)) {
42 result.set(key, new Map())
43 }
44
45 const valueMap = result.get(key)!
46 const valueKey = JSON.stringify(value)
47 const existing = valueMap.get(valueKey)
48 const newMultiplicity = (existing?.multiplicity ?? 0) + multiplicity
49
50 if (newMultiplicity === 0) {
51 valueMap.delete(valueKey)
52 } else {
53 valueMap.set(valueKey, { value, multiplicity: newMultiplicity })
54 }
55 }
56
57 // Extract final values per key
58 const finalResult = new Map<K, V>()
59 for (const [key, valueMap] of result.entries()) {
60 // Filter to only positive multiplicities
61 const positiveValues = Array.from(valueMap.values()).filter(
62 (entry) => entry.multiplicity > 0,
63 )
64
65 if (positiveValues.length === 1) {
66 finalResult.set(key, positiveValues[0]!.value)
67 } else if (positiveValues.length > 1) {
68 throw new Error(
69 `Key ${key} has multiple final values: ${positiveValues.map((v) => JSON.stringify(v.value)).join(`, `)}`,
70 )
71 }
72 // If no positive values, key was completely removed
73 }
74
75 return finalResult
76}
77
78/**
79 * Convert a Map back to a sorted array for comparison
80 */
81export function mapToSortedArray<T>(
82 map: Map<string, T>,
83 compare?: (a: T, b: T) => number,
84): Array<T> {
85 const compareFn =
86 compare ??
87 ((a: T, b: T) => {
88 // Sort by JSON string representation for consistent ordering
89 return JSON.stringify(a).localeCompare(JSON.stringify(b))
90 })
91 return Array.from(map.values()).sort(compareFn)
92}
93
94/**
95 * Create expected result set as a Map
96 */
97export function createExpectedResults<T>(items: Array<T>): Map<string, T> {
98 const map = new Map<string, T>()
99 for (const item of items) {
100 const key = JSON.stringify(item)
101 map.set(key, item)
102 }
103 return map
104}
105
106/**
107 * Test observation of flattened weighted deltas and their materialized result.
108 * Each [row, weight] entry contributes one to deltaCount, regardless of weight.
109 * Both trackers receive D2 MultiSet messages and flatten their entries.
110 * They omit message boundaries: an empty message contributes no delta.
111 */
112export interface TestResult<T> {
113 weightedDeltas: Array<[T, number]>
114 deltaCount: number
115 materializedResults: Map<string, T>
116 sortedResults: Array<T>
117}
118
119export interface KeyedTestResult<K, V> {
120 weightedDeltas: Array<[[K, V], number]>
121 deltaCount: number
122 materializedResults: Map<K, V>
123 sortedResults: Array<[K, V]>
124}
125
126export class MessageTracker<T> {
127 private weightedDeltas: Array<[T, number]> = []
128
129 addMessage(message: MultiSet<T>) {
130 this.weightedDeltas.push(...message.getInner())
131 }
132
133 getResult(compare?: (a: T, b: T) => number): TestResult<T> {
134 const materializedResults = materializeResults(this.weightedDeltas)
135 const sortedResults = mapToSortedArray(materializedResults, compare)
136
137 return {
138 weightedDeltas: this.weightedDeltas,
139 deltaCount: this.weightedDeltas.length,
140 materializedResults,
141 sortedResults,
142 }
143 }
144
145 reset() {
146 this.weightedDeltas = []
147 }
148}
149
150export class KeyedMessageTracker<K, V> {
151 private weightedDeltas: Array<[[K, V], number]> = []
152
153 addMessage(message: MultiSet<[K, V]>) {
154 this.weightedDeltas.push(...message.getInner())
155 }
156
157 getResult(): KeyedTestResult<K, V> {
158 const materializedResults = materializeKeyedResults(this.weightedDeltas)
159 const sortedResults = Array.from(materializedResults.entries()).sort(
160 (a, b) => {
161 // Sort by key for consistent ordering
162 return JSON.stringify(a[0]).localeCompare(JSON.stringify(b[0]))
163 },
164 )
165
166 return {
167 weightedDeltas: this.weightedDeltas,
168 deltaCount: this.weightedDeltas.length,
169 materializedResults,
170 sortedResults,
171 }
172 }
173
174 reset() {
175 this.weightedDeltas = []
176 }
177}
178
179/**
180 * Assert that results match expected, with weighted delta count logging
181 */
182export function assertResults<T>(
183 testName: string,
184 actual: TestResult<T>,
185 expected: Array<T>,
186 maxExpectedDeltas?: number,
187) {
188 const expectedMap = createExpectedResults(expected)
189 const expectedSorted = mapToSortedArray(expectedMap)
190
191 if (LOG_RESULTS) {
192 console.log(
193 `${testName}: ${actual.deltaCount} weighted deltas, ${actual.sortedResults.length} final results`,
194 )
195 console.log(` Weighted deltas:`, actual.weightedDeltas)
196 console.log(` Final results:`, actual.sortedResults)
197 }
198
199 // Check that materialized results match expected
200 expect(actual.sortedResults).toEqual(expectedSorted)
201
202 // Check weighted delta count constraints if provided
203 if (maxExpectedDeltas !== undefined) {
204 expect(actual.deltaCount).toBeLessThanOrEqual(maxExpectedDeltas)
205 }
206
207 // Log for debugging - use more reasonable threshold
208 // For empty results, allow up to 2 weighted deltas (typical for removal operations)
209 // For non-empty results, allow up to 3x the expected count
210 const reasonableThreshold = expected.length === 0 ? 2 : expected.length * 3
211 if (actual.deltaCount > reasonableThreshold) {
212 console.warn(
213 `⚠️ ${testName}: High weighted delta count (${actual.deltaCount} weighted deltas for ${expected.length} expected results)`,
214 )
215 }
216}
217
218/**
219 * Assert that keyed results match expected, with weighted delta count logging
220 */
221export function assertKeyedResults<K, V>(
222 testName: string,
223 actual: KeyedTestResult<K, V>,
224 expected: Array<[K, V]>,
225 maxExpectedDeltas?: number,
226) {
227 const expectedSorted = expected.sort((a, b) => {
228 return JSON.stringify(a[0]).localeCompare(JSON.stringify(b[0]))
229 })
230
231 if (LOG_RESULTS) {
232 console.log(
233 `${testName}: ${actual.deltaCount} weighted deltas, ${actual.sortedResults.length} final results per key`,
234 )
235 console.log(` Weighted deltas:`, actual.weightedDeltas)
236 console.log(` Final results:`, actual.sortedResults)
237 }
238
239 // Check that materialized results match expected
240 expect(actual.sortedResults).toEqual(expectedSorted)
241
242 // Check weighted delta count constraints if provided
243 if (maxExpectedDeltas !== undefined) {
244 expect(actual.deltaCount).toBeLessThanOrEqual(maxExpectedDeltas)
245 }
246
247 // Log for debugging - use more reasonable threshold
248 // Account for scenarios where weighted deltas cancel out due to object identity
249 // Allow up to 4x the expected count to accommodate remove/add pairs
250 const reasonableThreshold = Math.max(expected.length * 4, 2)
251 if (actual.deltaCount > reasonableThreshold) {
252 console.warn(
253 `⚠️ ${testName}: High weighted delta count (${actual.deltaCount} weighted deltas for ${expected.length} expected key-value pairs)`,
254 )
255 }
256
257 // Log key insights
258 const affectedKeys = new Set(
259 actual.weightedDeltas.map(([[key, _value], _mult]) => key),
260 )
261 if (LOG_RESULTS) {
262 console.log(
263 `${testName}: ✅ ${affectedKeys.size} keys affected, ${actual.sortedResults.length} final keys`,
264 )
265 }
266}
267
268/**
269 * Extract unique keys from weighted deltas to verify incremental behavior
270 */
271export function extractDeltaKeys<K, V>(
272 weightedDeltas: Array<[[K, V], number]>,
273): Set<K> {
274 const keys = new Set<K>()
275 for (const [[key, _value], _multiplicity] of weightedDeltas) {
276 keys.add(key)
277 }
278 return keys
279}
280
281/**
282 * Assert that only specific keys appear in weighted deltas (for incremental processing verification)
283 */
284export function assertOnlyKeysAffected<K, V>(
285 testName: string,
286 weightedDeltas: Array<[[K, V], number]>,
287 expectedKeys: Array<K>,
288) {
289 const actualKeys = extractDeltaKeys(weightedDeltas)
290 const expectedKeySet = new Set(expectedKeys)
291
292 // Check that all actual keys are expected
293 Array.from(actualKeys).forEach((key) => {
294 if (!expectedKeySet.has(key)) {
295 throw new Error(`${testName}: Unexpected key ${key} in weighted deltas`)
296 }
297 })
298
299 if (LOG_RESULTS) {
300 console.log(
301 `${testName}: ✅ Only expected keys affected: ${Array.from(actualKeys).join(`, `)}`,
302 )
303 }
304}
305
306export const compareFractionalIndex = (
307 r1: [unknown, [unknown, string]],
308 r2: [unknown, [unknown, string]],
309) => {
310 const [_key1, [_value1, index1]] = r1
311 const [_key2, [_value2, index2]] = r2
312 return index1 < index2 ? -1 : index1 > index2 ? 1 : 0
313}