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

test-utils.ts

316 lines9.3 KB

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
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
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 text in code-unit order, a total order; collation can
89 // tie distinct strings.
90 const left = JSON.stringify(a)
91 const right = JSON.stringify(b)
92 return left < right ? -1 : left > right ? 1 : 0
93 })
94 return Array.from(map.values()).sort(compareFn)
96​
97/**
98 * Create expected result set as a Map
99 */
100export function createExpectedResults<T>(items: Array<T>): Map<string, T> {
101 const map = new Map<string, T>()
102 for (const item of items) {
103 const key = JSON.stringify(item)
104 map.set(key, item)
105 }
106 return map
108​
109/**
110 * Test observation of flattened weighted deltas and their materialized result.
111 * Each [row, weight] entry contributes one to deltaCount, regardless of weight.
112 * Both trackers receive D2 MultiSet messages and flatten their entries.
113 * They omit message boundaries: an empty message contributes no delta.
114 */
115export interface TestResult<T> {
116 weightedDeltas: Array<[T, number]>
117 deltaCount: number
118 materializedResults: Map<string, T>
119 sortedResults: Array<T>
121​
122export interface KeyedTestResult<K, V> {
123 weightedDeltas: Array<[[K, V], number]>
124 deltaCount: number
125 materializedResults: Map<K, V>
126 sortedResults: Array<[K, V]>
128​
129export class MessageTracker<T> {
130 private weightedDeltas: Array<[T, number]> = []
131​
132 addMessage(message: MultiSet<T>) {
133 this.weightedDeltas.push(...message.getInner())
134 }
135​
136 getResult(compare?: (a: T, b: T) => number): TestResult<T> {
137 const materializedResults = materializeResults(this.weightedDeltas)
138 const sortedResults = mapToSortedArray(materializedResults, compare)
139​
140 return {
141 weightedDeltas: this.weightedDeltas,
142 deltaCount: this.weightedDeltas.length,
143 materializedResults,
144 sortedResults,
145 }
146 }
147​
148 reset() {
149 this.weightedDeltas = []
150 }
152​
153export class KeyedMessageTracker<K, V> {
154 private weightedDeltas: Array<[[K, V], number]> = []
155​
156 addMessage(message: MultiSet<[K, V]>) {
157 this.weightedDeltas.push(...message.getInner())
158 }
159​
160 getResult(): KeyedTestResult<K, V> {
161 const materializedResults = materializeKeyedResults(this.weightedDeltas)
162 const sortedResults = Array.from(materializedResults.entries()).sort(
163 (a, b) => {
164 // Sort by key for consistent ordering
165 return JSON.stringify(a[0]).localeCompare(JSON.stringify(b[0]))
166 },
167 )
168​
169 return {
170 weightedDeltas: this.weightedDeltas,
171 deltaCount: this.weightedDeltas.length,
172 materializedResults,
173 sortedResults,
174 }
175 }
176​
177 reset() {
178 this.weightedDeltas = []
179 }
181​
182/**
183 * Assert that results match expected, with weighted delta count logging
184 */
185export function assertResults<T>(
186 testName: string,
187 actual: TestResult<T>,
188 expected: Array<T>,
189 maxExpectedDeltas?: number,
190) {
191 const expectedMap = createExpectedResults(expected)
192 const expectedSorted = mapToSortedArray(expectedMap)
193​
194 if (LOG_RESULTS) {
195 console.log(
196 `${testName}: ${actual.deltaCount} weighted deltas, ${actual.sortedResults.length} final results`,
197 )
198 console.log(` Weighted deltas:`, actual.weightedDeltas)
199 console.log(` Final results:`, actual.sortedResults)
200 }
201​
202 // Check that materialized results match expected
203 expect(actual.sortedResults).toEqual(expectedSorted)
204​
205 // Check weighted delta count constraints if provided
206 if (maxExpectedDeltas !== undefined) {
207 expect(actual.deltaCount).toBeLessThanOrEqual(maxExpectedDeltas)
208 }
209​
210 // Log for debugging - use more reasonable threshold
211 // For empty results, allow up to 2 weighted deltas (typical for removal operations)
212 // For non-empty results, allow up to 3x the expected count
213 const reasonableThreshold = expected.length === 0 ? 2 : expected.length * 3
214 if (actual.deltaCount > reasonableThreshold) {
215 console.warn(
216 `⚠️ ${testName}: High weighted delta count (${actual.deltaCount} weighted deltas for ${expected.length} expected results)`,
217 )
218 }
220​
221/**
222 * Assert that keyed results match expected, with weighted delta count logging
223 */
224export function assertKeyedResults<K, V>(
225 testName: string,
226 actual: KeyedTestResult<K, V>,
227 expected: Array<[K, V]>,
228 maxExpectedDeltas?: number,
229) {
230 const expectedSorted = expected.sort((a, b) => {
231 return JSON.stringify(a[0]).localeCompare(JSON.stringify(b[0]))
232 })
233​
234 if (LOG_RESULTS) {
235 console.log(
236 `${testName}: ${actual.deltaCount} weighted deltas, ${actual.sortedResults.length} final results per key`,
237 )
238 console.log(` Weighted deltas:`, actual.weightedDeltas)
239 console.log(` Final results:`, actual.sortedResults)
240 }
241​
242 // Check that materialized results match expected
243 expect(actual.sortedResults).toEqual(expectedSorted)
244​
245 // Check weighted delta count constraints if provided
246 if (maxExpectedDeltas !== undefined) {
247 expect(actual.deltaCount).toBeLessThanOrEqual(maxExpectedDeltas)
248 }
249​
250 // Log for debugging - use more reasonable threshold
251 // Account for scenarios where weighted deltas cancel out due to object identity
252 // Allow up to 4x the expected count to accommodate remove/add pairs
253 const reasonableThreshold = Math.max(expected.length * 4, 2)
254 if (actual.deltaCount > reasonableThreshold) {
255 console.warn(
256 `⚠️ ${testName}: High weighted delta count (${actual.deltaCount} weighted deltas for ${expected.length} expected key-value pairs)`,
257 )
258 }
259​
260 // Log key insights
261 const affectedKeys = new Set(
262 actual.weightedDeltas.map(([[key, _value], _mult]) => key),
263 )
264 if (LOG_RESULTS) {
265 console.log(
266 `${testName}: ✅ ${affectedKeys.size} keys affected, ${actual.sortedResults.length} final keys`,
267 )
268 }
270​
271/**
272 * Extract unique keys from weighted deltas to verify incremental behavior
273 */
274export function extractDeltaKeys<K, V>(
275 weightedDeltas: Array<[[K, V], number]>,
276): Set<K> {
277 const keys = new Set<K>()
278 for (const [[key, _value], _multiplicity] of weightedDeltas) {
279 keys.add(key)
280 }
281 return keys
283​
284/**
285 * Assert that only specific keys appear in weighted deltas (for incremental processing verification)
286 */
287export function assertOnlyKeysAffected<K, V>(
288 testName: string,
289 weightedDeltas: Array<[[K, V], number]>,
290 expectedKeys: Array<K>,
291) {
292 const actualKeys = extractDeltaKeys(weightedDeltas)
293 const expectedKeySet = new Set(expectedKeys)
294​
295 // Check that all actual keys are expected
296 Array.from(actualKeys).forEach((key) => {
297 if (!expectedKeySet.has(key)) {
298 throw new Error(`${testName}: Unexpected key ${key} in weighted deltas`)
299 }
300 })
301​
302 if (LOG_RESULTS) {
303 console.log(
304 `${testName}: ✅ Only expected keys affected: ${Array.from(actualKeys).join(`, `)}`,
305 )
306 }
308​
309export const compareFractionalIndex = (
310 r1: [unknown, [unknown, string]],
311 r2: [unknown, [unknown, string]],
312) => {
313 const [_key1, [_value1, index1]] = r1
314 const [_key2, [_value2, index2]] = r2
315 return index1 < index2 ? -1 : index1 > index2 ? 1 : 0