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