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

reduce.test.ts

599 lines15.5 KB

1import { describe, expect, test } from 'vitest'
2import { D2 } from '../../src/d2.js'
3import { MultiSet } from '../../src/multiset.js'
4import { reduce } from '../../src/operators/reduce.js'
5import { output } from '../../src/operators/output.js'
6import {
7 KeyedMessageTracker,
8 assertKeyedResults,
9 assertOnlyKeysAffected,
10} from '../test-utils.js'
11​
12describe(`Operators`, () => {
13 describe(`Reduce operation`, () => {
14 test(`basic reduce operation`, () => {
15 const graph = new D2()
16 const input = graph.newInput<[string, number]>()
17 const tracker = new KeyedMessageTracker<string, number>()
18​
19 input.pipe(
20 reduce((vals) => {
21 let sum = 0
22 for (const [val, diff] of vals) {
23 sum += val * diff
24 }
25 return [[sum, 1]]
26 }),
27 output((message) => {
28 tracker.addMessage(message)
29 }),
30 )
31​
32 graph.finalize()
33​
34 input.sendData(
35 new MultiSet([
36 [[`a`, 1], 2],
37 [[`a`, 2], 1],
38 [[`a`, 3], 1],
39 [[`b`, 4], 1],
40 ]),
41 )
42 input.sendData(new MultiSet([[[`b`, 5], 1]]))
43 graph.run()
44​
45 const result = tracker.getResult()
46​
47 // Assert only keys 'a' and 'b' are affected
48 assertOnlyKeysAffected(`basic reduce operation`, result.weightedDeltas, [
49 `a`,
50 `b`,
51 ])
52​
53 // Assert the final materialized results are correct
54 assertKeyedResults(
55 `basic reduce operation`,
56 result,
57 [
58 [`a`, 7], // 1*2 + 2*1 + 3*1 = 7
59 [`b`, 9], // 4*1 + 5*1 = 9
60 ],
61 4, // Expected weighted delta count
62 )
63 })
64​
65 test(`reduce with negative multiplicities`, () => {
66 const graph = new D2()
67 const input = graph.newInput<[string, number]>()
68 const tracker = new KeyedMessageTracker<string, number>()
69​
70 input.pipe(
71 reduce((vals) => {
72 let sum = 0
73 for (const [val, diff] of vals) {
74 sum += val * diff
75 }
76 return [[sum, 1]]
77 }),
78 output((message) => {
79 tracker.addMessage(message)
80 }),
81 )
82​
83 graph.finalize()
84​
85 input.sendData(
86 new MultiSet([
87 [[`a`, 1], -1],
88 [[`a`, 2], 2],
89 [[`b`, 3], -2],
90 ]),
91 )
92 graph.run()
93​
94 const result = tracker.getResult()
95​
96 // Assert only keys 'a' and 'b' are affected
97 assertOnlyKeysAffected(
98 `reduce with negative multiplicities`,
99 result.weightedDeltas,
100 [`a`, `b`],
101 )
102​
103 // Assert the final materialized results are correct
104 assertKeyedResults(
105 `reduce with negative multiplicities`,
106 result,
107 [
108 [`a`, 3], // 1*(-1) + 2*2 = 3
109 [`b`, -6], // 3*(-2) = -6
110 ],
111 4, // Expected weighted delta count
112 )
113 })
114​
115 test(`multiple incremental updates to same key`, () => {
116 const graph = new D2()
117 const input = graph.newInput<[string, number]>()
118 const tracker = new KeyedMessageTracker<string, number>()
119​
120 input.pipe(
121 reduce((vals) => {
122 let sum = 0
123 for (const [val, diff] of vals) {
124 sum += val * diff
125 }
126 return [[sum, 1]]
127 }),
128 output((message) => {
129 tracker.addMessage(message)
130 }),
131 )
132​
133 graph.finalize()
134​
135 // First update: a=1, b=2
136 input.sendData(
137 new MultiSet([
138 [[`a`, 1], 1],
139 [[`b`, 2], 1],
140 ]),
141 )
142 graph.run()
143​
144 const firstResult = tracker.getResult()
145 assertOnlyKeysAffected(
146 `reduce first update`,
147 firstResult.weightedDeltas,
148 [`a`, `b`],
149 )
150 assertKeyedResults(
151 `reduce first update`,
152 firstResult,
153 [
154 [`a`, 1],
155 [`b`, 2],
156 ],
157 4, // Expected weighted delta count
158 )
159​
160 tracker.reset()
161​
162 // Second update: add more to a, modify b
163 input.sendData(
164 new MultiSet([
165 [[`a`, 3], 1],
166 [[`b`, 4], 1],
167 ]),
168 )
169 graph.run()
170​
171 const secondResult = tracker.getResult()
172 assertOnlyKeysAffected(
173 `reduce second update`,
174 secondResult.weightedDeltas,
175 [`a`, `b`],
176 )
177 assertKeyedResults(
178 `reduce second update`,
179 secondResult,
180 [
181 [`a`, 4], // 1+3
182 [`b`, 6], // 2+4
183 ],
184 6, // Expected weighted delta count (old removed, new added for both keys)
185 )
186​
187 tracker.reset()
188​
189 // Third update: remove some from a only
190 input.sendData(new MultiSet([[[`a`, 1], -1]]))
191 graph.run()
192​
193 const thirdResult = tracker.getResult()
194 // Only key 'a' should be affected, not 'b'
195 assertOnlyKeysAffected(
196 `reduce third update`,
197 thirdResult.weightedDeltas,
198 [`a`],
199 )
200 assertKeyedResults(
201 `reduce third update`,
202 thirdResult,
203 [
204 [`a`, 3], // 4-1=3
205 ],
206 3, // Expected weighted delta count (old removed, new added for key a)
207 )
208 })
209​
210 test(`updates that cancel out completely`, () => {
211 const graph = new D2()
212 const input = graph.newInput<[string, number]>()
213 const tracker = new KeyedMessageTracker<string, number>()
214​
215 input.pipe(
216 reduce((vals) => {
217 let sum = 0
218 for (const [val, diff] of vals) {
219 sum += val * diff
220 }
221 return [[sum, 1]]
222 }),
223 output((message) => {
224 tracker.addMessage(message)
225 }),
226 )
227​
228 graph.finalize()
229​
230 // First update: add values
231 input.sendData(
232 new MultiSet([
233 [[`a`, 5], 1],
234 [[`a`, 3], 1],
235 [[`b`, 10], 1],
236 ]),
237 )
238 graph.run()
239​
240 // Second update: cancel out all values for 'a'
241 input.sendData(
242 new MultiSet([
243 [[`a`, 5], -1],
244 [[`a`, 3], -1],
245 ]),
246 )
247 graph.run()
248​
249 const result = tracker.getResult()
250​
251 // Assert only keys 'a' and 'b' are affected
252 assertOnlyKeysAffected(
253 `updates that cancel out completely`,
254 result.weightedDeltas,
255 [`a`, `b`],
256 )
257​
258 // Assert the final materialized results are correct
259 assertKeyedResults(
260 `updates that cancel out completely`,
261 result,
262 [
263 [`a`, 0], // 5+3-5-3 = 0
264 [`b`, 10], // 10 (unchanged)
265 ],
266 6, // Expected weighted delta count
267 )
268 })
269​
270 test(`mixed positive and negative updates`, () => {
271 const graph = new D2()
272 const input = graph.newInput<[string, number]>()
273 const tracker = new KeyedMessageTracker<string, number>()
274​
275 input.pipe(
276 reduce((vals) => {
277 let sum = 0
278 for (const [val, diff] of vals) {
279 sum += val * diff
280 }
281 return [[sum, 1]]
282 }),
283 output((message) => {
284 tracker.addMessage(message)
285 }),
286 )
287​
288 graph.finalize()
289​
290 // First update: establish initial state
291 input.sendData(
292 new MultiSet([
293 [[`a`, 10], 1],
294 [[`a`, 5], 2],
295 [[`b`, 20], 1],
296 ]),
297 )
298 graph.run()
299​
300 // Second update: mix of adds and removes
301 input.sendData(
302 new MultiSet([
303 [[`a`, 10], -1], // Remove one 10
304 [[`a`, 2], 1], // Add a 2
305 [[`b`, 20], -1], // Remove the 20
306 [[`b`, 15], 1], // Add a 15
307 [[`c`, 100], 1], // Add new key
308 ]),
309 )
310 graph.run()
311​
312 const result = tracker.getResult()
313​
314 // Assert only keys 'a', 'b', and 'c' are affected
315 assertOnlyKeysAffected(
316 `mixed positive and negative updates`,
317 result.weightedDeltas,
318 [`a`, `b`, `c`],
319 )
320​
321 // Assert the final materialized results are correct
322 assertKeyedResults(
323 `mixed positive and negative updates`,
324 result,
325 [
326 [`a`, 12], // 10+5+5-10+2 = 12
327 [`b`, 15], // 20-20+15 = 15
328 [`c`, 100], // 100
329 ],
330 8, // Expected weighted delta count
331 )
332 })
333​
334 test(`complex aggregation with multiple updates`, () => {
335 const graph = new D2()
336 const input = graph.newInput<[string, { value: number; count: number }]>()
337 const tracker = new KeyedMessageTracker<
338 string,
339 { avg: number; total: number }
340 >()
341​
342 input.pipe(
343 reduce((vals) => {
344 let totalSum = 0
345 let totalCount = 0
346 for (const [val, diff] of vals) {
347 totalSum += val.value * val.count * diff
348 totalCount += val.count * diff
349 }
350 const avg = totalCount > 0 ? totalSum / totalCount : 0
351 return [[{ avg, total: totalSum }, 1]]
352 }),
353 output((message) => {
354 tracker.addMessage(message)
355 }),
356 )
357​
358 graph.finalize()
359​
360 // First batch: group 'a' has values
361 input.sendData(
362 new MultiSet([
363 [[`a`, { value: 10, count: 2 }], 1], // 2 values of 10
364 [[`a`, { value: 20, count: 1 }], 1], // 1 value of 20
365 ]),
366 )
367 graph.run()
368​
369 // Second batch: add more to 'a' and start 'b'
370 input.sendData(
371 new MultiSet([
372 [[`a`, { value: 30, count: 1 }], 1], // 1 value of 30
373 [[`b`, { value: 50, count: 3 }], 1], // 3 values of 50
374 ]),
375 )
376 graph.run()
377​
378 // Third batch: remove some from 'a'
379 input.sendData(
380 new MultiSet([
381 [[`a`, { value: 10, count: 2 }], -1], // Remove the 2 values of 10
382 ]),
383 )
384 graph.run()
385​
386 const result = tracker.getResult()
387​
388 // Assert only keys 'a' and 'b' are affected
389 assertOnlyKeysAffected(
390 `complex aggregation with multiple updates`,
391 result.weightedDeltas,
392 [`a`, `b`],
393 )
394​
395 // Assert the final materialized results are correct
396 assertKeyedResults(
397 `complex aggregation with multiple updates`,
398 result,
399 [
400 [`a`, { avg: 25, total: 50 }], // Final: (20*1+30*1)/(1+1) = 50/2 = 25
401 [`b`, { avg: 50, total: 150 }], // Final: 50*3 = 150
402 ],
403 6, // Expected weighted delta count
404 )
405 })
406​
407 test(`updates with zero-multiplicity results`, () => {
408 const graph = new D2()
409 const input = graph.newInput<[string, number]>()
410 const tracker = new KeyedMessageTracker<string, number>()
411​
412 input.pipe(
413 reduce((vals) => {
414 let sum = 0
415 for (const [val, diff] of vals) {
416 sum += val * diff
417 }
418 // Only return non-zero sums
419 return sum !== 0 ? [[sum, 1]] : []
420 }),
421 output((message) => {
422 tracker.addMessage(message)
423 }),
424 )
425​
426 graph.finalize()
427​
428 // First update: establish values
429 input.sendData(
430 new MultiSet([
431 [[`a`, 5], 1],
432 [[`a`, -3], 1],
433 [[`b`, 10], 1],
434 ]),
435 )
436 graph.run()
437​
438 // Second update: make 'a' sum to zero
439 input.sendData(new MultiSet([[[`a`, -2], 1]]))
440 graph.run()
441​
442 // Third update: add back to 'a'
443 input.sendData(new MultiSet([[[`a`, 7], 1]]))
444 graph.run()
445​
446 const result = tracker.getResult()
447​
448 // Assert only keys 'a' and 'b' are affected
449 assertOnlyKeysAffected(
450 `updates with zero-multiplicity results`,
451 result.weightedDeltas,
452 [`a`, `b`],
453 )
454​
455 // Assert the final materialized results are correct
456 assertKeyedResults(
457 `updates with zero-multiplicity results`,
458 result,
459 [
460 [`a`, 7], // Final: 5-3-2+7 = 7
461 [`b`, 10], // Final: 10 (unchanged)
462 ],
463 5, // Expected weighted delta count
464 )
465 })
466​
467 test(`reduce incremental updates - only affected keys produce weighted deltas`, () => {
468 const graph = new D2()
469 const input = graph.newInput<[string, number]>()
470 const tracker = new KeyedMessageTracker<string, number>()
471​
472 input.pipe(
473 reduce((vals) => {
474 let sum = 0
475 for (const [val, diff] of vals) {
476 sum += val * diff
477 }
478 return [[sum, 1]]
479 }),
480 output((message) => {
481 tracker.addMessage(message)
482 }),
483 )
484​
485 graph.finalize()
486​
487 // Initial data: establish state for keys 'x', 'y', 'z'
488 input.sendData(
489 new MultiSet([
490 [[`x`, 10], 1],
491 [[`x`, 20], 1],
492 [[`y`, 5], 1],
493 [[`y`, 15], 1],
494 [[`y`, 25], 1],
495 [[`z`, 100], 1],
496 ]),
497 )
498 graph.run()
499​
500 // Reset tracker to focus on incremental updates
501 tracker.reset()
502​
503 // Incremental update: only affect keys 'x' and 'z'
504 input.sendData(
505 new MultiSet([
506 [[`x`, 30], 1], // Add to 'x' (30 -> 60)
507 [[`z`, 100], -1], // Remove from 'z' (100 -> 0)
508 ]),
509 )
510 graph.run()
511​
512 const result = tracker.getResult()
513​
514 // Assert only keys 'x' and 'z' are affected (NOT 'y')
515 assertOnlyKeysAffected(
516 `reduce incremental updates`,
517 result.weightedDeltas,
518 [`x`, `z`],
519 )
520​
521 // Assert the final materialized results are correct
522 assertKeyedResults(
523 `reduce incremental updates`,
524 result,
525 [
526 [`x`, 60], // Sum increased from 30 to 60
527 [`z`, 0], // Sum decreased from 100 to 0
528 ],
529 4, // Expected weighted delta count: remove old 'x', add new 'x', remove old 'z', add new 'z'
530 )
531 })
532​
533 test(`reduce with object identity - may produce weighted deltas for identical content`, () => {
534 const graph = new D2()
535 const input = graph.newInput<[string, { id: number; value: number }]>()
536 const tracker = new KeyedMessageTracker<string, { result: number }>()
537​
538 input.pipe(
539 reduce((vals) => {
540 let sum = 0
541 for (const [val, diff] of vals) {
542 sum += val.value * diff
543 }
544 // Return a new object each time - but hash comparison handles this efficiently
545 return [[{ result: sum }, 1]]
546 }),
547 output((message) => {
548 tracker.addMessage(message)
549 }),
550 )
551​
552 graph.finalize()
553​
554 // Initial data: establish state for keys 'a', 'b', 'c'
555 input.sendData(
556 new MultiSet([
557 [[`a`, { id: 1, value: 10 }], 1],
558 [[`a`, { id: 2, value: 20 }], 1],
559 [[`b`, { id: 3, value: 100 }], 1],
560 [[`c`, { id: 4, value: 5 }], 1],
561 [[`c`, { id: 5, value: 15 }], 1],
562 ]),
563 )
564 graph.run()
565​
566 // Reset tracker to focus on incremental updates
567 tracker.reset()
568​
569 // Update that should NOT change the result value for key 'a'
570 input.sendData(
571 new MultiSet([
572 [[`a`, { id: 1, value: 10 }], -1], // Remove 10
573 [[`a`, { id: 6, value: 10 }], 1], // Add 10 (same value, different object)
574 [[`b`, { id: 3, value: 100 }], -1], // Remove from 'b' (100 -> 0)
575 ]),
576 )
577 graph.run()
578​
579 const result = tracker.getResult()
580​
581 // With object identity: 'a' produces weighted deltas even though content is identical
582 // This demonstrates the object identity issue, but keysTodo should still limit processing
583 const aDeltas = result.weightedDeltas.filter(
584 ([[key, _value], _mult]) => key === `a`,
585 )
586 expect(aDeltas.length).toBe(2) // Object identity causes 2 weighted deltas (remove + add)
587​
588 // But the weighted deltas cancel out due to identical content
589 assertKeyedResults(
590 `reduce with object identity`,
591 result,
592 [
593 [`b`, { result: 0 }], // Changed from 100 to 0
594 ],
595 4, // With object identity: 4 weighted deltas total (2 for 'a', 2 for 'b')
596 )
597 })
598 })
599})