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 {
5 avg,
6 count,
7 groupBy,
8 max,
9 median,
10 min,
11 mode,
12 sum,
13} from '../../src/operators/groupBy.js'
14import { output } from '../../src/operators/index.js'
15import { serializeValue } from '../../src/utils.js'
16
17describe(`Operators`, () => {
18 describe(`GroupBy operation`, () => {
19 test(`with no aggregate`, () => {
20 const graph = new D2()
21 const input = graph.newInput<{
22 category: string
23 amount: number
24 }>()
25 let latestMessage: any = null
26
27 input.pipe(
28 groupBy((data) => ({ category: data.category })),
29 output((message) => {
30 latestMessage = message
31 }),
32 )
33
34 graph.finalize()
35
36 // Initial data
37 input.sendData(
38 new MultiSet([
39 [{ category: `A`, amount: 10 }, 1],
40 [{ category: `A`, amount: 20 }, 1],
41 [{ category: `B`, amount: 30 }, 1],
42 ]),
43 )
44 graph.run()
45
46 // Verify we have the latest message
47 expect(latestMessage).not.toBeNull()
48
49 const result = latestMessage.getInner()
50
51 const expectedResult = [
52 [
53 [
54 serializeValue({ category: `A` }),
55 {
56 category: `A`,
57 },
58 ],
59 1,
60 ],
61 [
62 [
63 serializeValue({ category: `B` }),
64 {
65 category: `B`,
66 },
67 ],
68 1,
69 ],
70 ]
71
72 expect(result).toEqual(expectedResult)
73 })
74
75 test(`with single sum aggregate`, () => {
76 const graph = new D2()
77 const input = graph.newInput<{
78 category: string
79 amount: number
80 }>()
81 let latestMessage: any = null
82
83 input.pipe(
84 groupBy((data) => ({ category: data.category }), {
85 total: sum((data) => data.amount),
86 }),
87 output((message) => {
88 latestMessage = message
89 }),
90 )
91
92 graph.finalize()
93
94 // Initial data
95 input.sendData(
96 new MultiSet([
97 [{ category: `A`, amount: 10 }, 1],
98 [{ category: `A`, amount: 20 }, 1],
99 [{ category: `B`, amount: 30 }, 1],
100 ]),
101 )
102 graph.run()
103
104 // Verify we have the latest message
105 expect(latestMessage).not.toBeNull()
106
107 const result = latestMessage.getInner()
108
109 const expectedResult = [
110 [
111 [
112 serializeValue({ category: `A` }),
113 {
114 total: 30,
115 category: `A`,
116 },
117 ],
118 1,
119 ],
120 [
121 [
122 serializeValue({ category: `B` }),
123 {
124 total: 30,
125 category: `B`,
126 },
127 ],
128 1,
129 ],
130 ]
131
132 expect(result).toEqual(expectedResult)
133 })
134
135 test(`does not reserve an aggregate name for its original group key`, () => {
136 const graph = new D2()
137 const input = graph.newInput<{ category: string }>()
138 let latestMessage: MultiSet<unknown> | undefined
139
140 input.pipe(
141 groupBy((data) => ({ category: data.category }), {
142 __original_key__: count(),
143 }),
144 output((message) => {
145 latestMessage = message
146 }),
147 )
148 graph.finalize()
149 input.sendData(
150 new MultiSet([
151 [{ category: `A` }, 1],
152 [{ category: `A` }, 1],
153 ]),
154 )
155 graph.run()
156
157 expect(latestMessage?.getInner()).toEqual([
158 [
159 [
160 serializeValue({ category: `A` }),
161 { category: `A`, __original_key__: 2 },
162 ],
163 1,
164 ],
165 ])
166 })
167
168 test(`with sum and count aggregates`, () => {
169 const graph = new D2()
170 const input = graph.newInput<{
171 category: string
172 region: string
173 amount: number
174 }>()
175 let latestMessage: any = null
176 const messages: Array<MultiSet<any>> = []
177
178 input.pipe(
179 groupBy(
180 (data) => ({
181 category: data.category,
182 region: data.region,
183 }),
184 {
185 total: sum((data) => data.amount),
186 count: count(),
187 },
188 ),
189 output((message) => {
190 latestMessage = message
191 messages.push(message)
192 }),
193 )
194
195 graph.finalize()
196
197 // Initial data
198 input.sendData(
199 new MultiSet([
200 [{ category: `A`, region: `East`, amount: 10 }, 1],
201 [{ category: `A`, region: `East`, amount: 20 }, 1],
202 [{ category: `A`, region: `West`, amount: 30 }, 1],
203 [{ category: `B`, region: `East`, amount: 40 }, 1],
204 ]),
205 )
206 graph.run()
207
208 // Verify we have the latest message
209 expect(latestMessage).not.toBeNull()
210
211 const expectedResult = [
212 [
213 [
214 serializeValue({ category: `A`, region: `East` }),
215 {
216 total: 30,
217 count: 2,
218 category: `A`,
219 region: `East`,
220 },
221 ],
222 1,
223 ],
224 [
225 [
226 serializeValue({ category: `A`, region: `West` }),
227 {
228 total: 30,
229 count: 1,
230 category: `A`,
231 region: `West`,
232 },
233 ],
234 1,
235 ],
236 [
237 [
238 serializeValue({ category: `B`, region: `East` }),
239 {
240 total: 40,
241 count: 1,
242 category: `B`,
243 region: `East`,
244 },
245 ],
246 1,
247 ],
248 ]
249
250 expect(latestMessage.getInner()).toEqual(expectedResult)
251
252 // --- Add a new record ---
253 input.sendData(
254 new MultiSet([
255 [{ category: `A`, region: `East`, amount: 15 }, 1],
256 [{ category: `B`, region: `West`, amount: 25 }, 1],
257 ]),
258 )
259
260 graph.run()
261
262 const expectedAddResult = [
263 [
264 [
265 serializeValue({ category: `A`, region: `East` }),
266 {
267 category: `A`,
268 region: `East`,
269 total: 30,
270 count: 2,
271 },
272 ],
273 -1,
274 ],
275 [
276 [
277 serializeValue({ category: `A`, region: `East` }),
278 {
279 category: `A`,
280 region: `East`,
281 total: 45,
282 count: 3,
283 },
284 ],
285 1,
286 ],
287 [
288 [
289 serializeValue({ category: `B`, region: `West` }),
290 {
291 category: `B`,
292 region: `West`,
293 total: 25,
294 count: 1,
295 },
296 ],
297 1,
298 ],
299 ]
300
301 expect(latestMessage.getInner()).toEqual(expectedAddResult)
302
303 // --- Delete a record ---
304 input.sendData(
305 new MultiSet([
306 [{ category: `A`, region: `East`, amount: 20 }, -1], // Remove one of the A/East records
307 ]),
308 )
309 graph.run()
310
311 const expectedDeleteResult = [
312 [
313 [
314 serializeValue({ category: `A`, region: `East` }),
315 {
316 category: `A`,
317 region: `East`,
318 total: 45,
319 count: 3,
320 },
321 ],
322 -1,
323 ],
324 [
325 [
326 serializeValue({ category: `A`, region: `East` }),
327 {
328 category: `A`,
329 region: `East`,
330 total: 25,
331 count: 2,
332 },
333 ],
334 1,
335 ],
336 ]
337
338 expect(latestMessage.getInner()).toEqual(expectedDeleteResult)
339 })
340
341 test(`with count (only not-null values)`, () => {
342 const graph = new D2()
343 const input = graph.newInput<{
344 category: string
345 amount: number | null
346 }>()
347 let latestMessage: any = null
348 const messages: Array<MultiSet<any>> = []
349
350 input.pipe(
351 groupBy(
352 (data) => ({
353 category: data.category,
354 }),
355 {
356 countNotNull: count((data) => data.amount),
357 count: count(),
358 },
359 ),
360 output((message) => {
361 latestMessage = message
362 messages.push(message)
363 }),
364 )
365
366 graph.finalize()
367
368 // Initial data
369 input.sendData(
370 new MultiSet([
371 [{ category: `A`, amount: 10 }, 1],
372 [{ category: `B`, amount: 10 }, 1],
373 [{ category: `A`, amount: null }, 1],
374 [{ category: `B`, amount: null }, 1],
375 ]),
376 )
377
378 graph.run()
379
380 // Verify we have the latest message
381 expect(latestMessage).not.toBeNull()
382
383 const expectedResult = [
384 [
385 [
386 serializeValue({ category: `A` }),
387 {
388 category: `A`,
389 countNotNull: 1,
390 count: 2,
391 },
392 ],
393 1,
394 ],
395 [
396 [
397 serializeValue({ category: `B` }),
398 {
399 category: `B`,
400 countNotNull: 1,
401 count: 2,
402 },
403 ],
404 1,
405 ],
406 ]
407
408 expect(latestMessage.getInner()).toEqual(expectedResult)
409 })
410
411 test(`with avg and count aggregates`, () => {
412 const graph = new D2()
413 const input = graph.newInput<{
414 category: string
415 amount: number
416 }>()
417 let latestMessage: any = null
418 const messages: Array<MultiSet<any>> = []
419
420 input.pipe(
421 groupBy((data) => ({ category: data.category }), {
422 average: avg((data) => data.amount),
423 count: count(),
424 }),
425 output((message) => {
426 latestMessage = message
427 messages.push(message)
428 }),
429 )
430
431 graph.finalize()
432
433 // Initial data
434 input.sendData(
435 new MultiSet([
436 [{ category: `A`, amount: 10 }, 1],
437 [{ category: `A`, amount: 20 }, 1],
438 [{ category: `B`, amount: 30 }, 1],
439 ]),
440 )
441 graph.run()
442
443 // Verify we have the latest message
444 expect(latestMessage).not.toBeNull()
445
446 const expectedResult = [
447 [
448 [
449 serializeValue({ category: `A` }),
450 {
451 category: `A`,
452 average: 15,
453 count: 2,
454 },
455 ],
456 1,
457 ],
458 [
459 [
460 serializeValue({ category: `B` }),
461 {
462 category: `B`,
463 average: 30,
464 count: 1,
465 },
466 ],
467 1,
468 ],
469 ]
470
471 expect(latestMessage.getInner()).toEqual(expectedResult)
472
473 // --- Add a new record ---
474 input.sendData(
475 new MultiSet([
476 [{ category: `A`, amount: 30 }, 1],
477 [{ category: `C`, amount: 50 }, 1],
478 ]),
479 )
480 graph.run()
481
482 const expectedAddResult = [
483 [
484 [
485 serializeValue({ category: `A` }),
486 {
487 category: `A`,
488 average: 15,
489 count: 2,
490 },
491 ],
492 -1,
493 ],
494 [
495 [
496 serializeValue({ category: `A` }),
497 {
498 category: `A`,
499 average: 20,
500 count: 3,
501 },
502 ],
503 1,
504 ],
505 [
506 [
507 serializeValue({ category: `C` }),
508 {
509 category: `C`,
510 average: 50,
511 count: 1,
512 },
513 ],
514 1,
515 ],
516 ]
517
518 expect(latestMessage.getInner()).toEqual(expectedAddResult)
519
520 // --- Delete a record ---
521 input.sendData(
522 new MultiSet([
523 [{ category: `A`, amount: 10 }, -1], // Remove the first A record
524 ]),
525 )
526 graph.run()
527
528 const expectedDeleteResult = [
529 [
530 [
531 serializeValue({ category: `A` }),
532 {
533 category: `A`,
534 average: 20,
535 count: 3,
536 },
537 ],
538 -1,
539 ],
540 [
541 [
542 serializeValue({ category: `A` }),
543 {
544 category: `A`,
545 average: 25,
546 count: 2,
547 },
548 ],
549 1,
550 ],
551 ]
552
553 expect(latestMessage.getInner()).toEqual(expectedDeleteResult)
554 })
555
556 test(`with min and max aggregates`, () => {
557 const graph = new D2()
558 const input = graph.newInput<{
559 category: string
560 amount: number
561 date: Date
562 }>()
563 let latestMessage: any = null
564
565 input.pipe(
566 groupBy((data) => ({ category: data.category }), {
567 minimum: min((data) => data.amount),
568 maximum: max((data) => data.amount),
569 min_date: min((data) => data.date),
570 max_date: max((data) => data.date),
571 }),
572 output((message) => {
573 latestMessage = message
574 }),
575 )
576
577 graph.finalize()
578
579 // Initial data
580 input.sendData(
581 new MultiSet([
582 [{ category: `A`, amount: 10, date: new Date(`2025/12/13`) }, 1],
583 [{ category: `A`, amount: 20, date: new Date(`2025/12/15`) }, 1],
584 [{ category: `A`, amount: 5, date: new Date(`2025/12/12`) }, 1],
585 [{ category: `B`, amount: 30, date: new Date(`2025/12/12`) }, 1],
586 [{ category: `B`, amount: 15, date: new Date(`2025/12/13`) }, 1],
587 ]),
588 )
589
590 // Run the graph to process all messages
591 graph.run()
592
593 expect(latestMessage).not.toBeNull()
594
595 const expectedResult = [
596 [
597 [
598 serializeValue({ category: `A` }),
599 {
600 category: `A`,
601 minimum: 5,
602 maximum: 20,
603 min_date: new Date(`2025/12/12`),
604 max_date: new Date(`2025/12/15`),
605 },
606 ],
607 1,
608 ],
609 [
610 [
611 serializeValue({ category: `B` }),
612 {
613 category: `B`,
614 minimum: 15,
615 maximum: 30,
616 min_date: new Date(`2025/12/12`),
617 max_date: new Date(`2025/12/13`),
618 },
619 ],
620 1,
621 ],
622 ]
623
624 expect(latestMessage.getInner()).toEqual(expectedResult)
625 })
626
627 // These are readable replay witnesses. The generated groupBy law lives in
628 // incrementalization-law.property.test.ts.
629 test(`min and max reduce keep 0, 0n, and empty string as extremes`, () => {
630 const minNum = min<number>()
631 const maxNum = max<number>()
632 const minStr = min<string>()
633 const minBig = min<bigint>()
634 const maxBig = max<bigint>()
635
636 if (
637 !(`reduce` in minNum) ||
638 !(`reduce` in maxNum) ||
639 !(`reduce` in minStr) ||
640 !(`reduce` in minBig) ||
641 !(`reduce` in maxBig)
642 ) {
643 throw new Error(`Expected direct min/max aggregates`)
644 }
645
646 expect(
647 minNum.reduce([
648 [undefined, 1],
649 [5, 1],
650 [0, 1],
651 ]),
652 ).toBe(0)
653 expect(
654 minNum.reduce([
655 [0, 1],
656 [3, 1],
657 ]),
658 ).toBe(0)
659 expect(
660 maxNum.reduce([
661 [undefined, 1],
662 [-2, 1],
663 [0, 1],
664 [-1, 1],
665 ]),
666 ).toBe(0)
667 expect(
668 maxNum.reduce([
669 [0, 1],
670 [-1, 1],
671 ]),
672 ).toBe(0)
673 expect(
674 minStr.reduce([
675 [`b`, 1],
676 [``, 1],
677 ]),
678 ).toBe(``)
679 expect(
680 minStr.reduce([
681 [``, 1],
682 [`a`, 1],
683 ]),
684 ).toBe(``)
685 expect(
686 minBig.reduce([
687 [5n, 1],
688 [0n, 1],
689 ]),
690 ).toBe(0n)
691 expect(
692 maxBig.reduce([
693 [-2n, 1],
694 [0n, 1],
695 ]),
696 ).toBe(0n)
697 })
698
699 test(`with min and max aggregates including a zero amount`, () => {
700 const graph = new D2()
701 const input = graph.newInput<{
702 category: string
703 amount: number
704 }>()
705 let latestMessage: any = null
706
707 input.pipe(
708 groupBy((data) => ({ category: data.category }), {
709 minimum: min((data) => data.amount),
710 maximum: max((data) => data.amount),
711 }),
712 output((message) => {
713 latestMessage = message
714 }),
715 )
716
717 graph.finalize()
718
719 input.sendData(
720 new MultiSet([
721 [{ category: `A`, amount: 10 }, 1],
722 [{ category: `A`, amount: 0 }, 1],
723 [{ category: `A`, amount: 7 }, 1],
724 ]),
725 )
726 graph.run()
727
728 expect(latestMessage.getInner()).toEqual([
729 [
730 [
731 serializeValue({ category: `A` }),
732 {
733 category: `A`,
734 minimum: 0,
735 maximum: 10,
736 },
737 ],
738 1,
739 ],
740 ])
741 })
742
743 test(`with median and mode aggregates`, () => {
744 const graph = new D2()
745 const input = graph.newInput<{
746 category: string
747 amount: number
748 }>()
749 let latestMessage: any = null
750
751 input.pipe(
752 groupBy((data) => ({ category: data.category }), {
753 middle: median((data) => data.amount),
754 mostFrequent: mode((data) => data.amount),
755 }),
756 output((message) => {
757 latestMessage = message
758 }),
759 )
760
761 graph.finalize()
762
763 // Initial data with pattern designed to test median and mode
764 input.sendData(
765 new MultiSet([
766 // Category A: [10, 20, 20, 30, 50]
767 // Median: 20, Mode: 20
768 [{ category: `A`, amount: 10 }, 1],
769 [{ category: `A`, amount: 20 }, 2], // Added twice to test mode
770 [{ category: `A`, amount: 30 }, 1],
771 [{ category: `A`, amount: 50 }, 1],
772
773 // Category B: [5, 10, 15, 20]
774 // Median: 12.5 (average of 10 and 15), Mode: 5, 10, 15, 20 (all appear once)
775 [{ category: `B`, amount: 5 }, 1],
776 [{ category: `B`, amount: 10 }, 1],
777 [{ category: `B`, amount: 15 }, 1],
778 [{ category: `B`, amount: 20 }, 1],
779 ]),
780 )
781
782 // Run the graph to process all messages
783 graph.run()
784
785 expect(latestMessage).not.toBeNull()
786
787 const expectedResult = [
788 [
789 [
790 serializeValue({ category: `A` }),
791 {
792 category: `A`,
793 middle: 20,
794 mostFrequent: 20,
795 },
796 ],
797 1,
798 ],
799 [
800 [
801 serializeValue({ category: `B` }),
802 {
803 category: `B`,
804 middle: 12.5,
805 mostFrequent: 5, // First encountered value with highest frequency (all values appear once)
806 },
807 ],
808 1,
809 ],
810 ]
811
812 expect(latestMessage.getInner()).toEqual(expectedResult)
813 })
814
815 test(`complete group removal with sum aggregate`, () => {
816 const graph = new D2()
817 const input = graph.newInput<{
818 category: string
819 amount: number
820 }>()
821 let latestMessage: any = null
822
823 input.pipe(
824 groupBy((data) => ({ category: data.category }), {
825 total: sum((data) => data.amount),
826 }),
827 output((message) => {
828 latestMessage = message
829 }),
830 )
831
832 graph.finalize()
833
834 // Initial data
835 input.sendData(
836 new MultiSet([
837 [{ category: `A`, amount: 10 }, 1],
838 [{ category: `A`, amount: 20 }, 1],
839 [{ category: `B`, amount: 30 }, 1],
840 [{ category: `C`, amount: 40 }, 1],
841 ]),
842 )
843 graph.run()
844
845 // Verify initial state
846 expect(latestMessage).not.toBeNull()
847 let result = latestMessage.getInner()
848 expect(result).toHaveLength(3) // Should have 3 groups
849
850 // Find the group for category A
851 const categoryAGroup = result.find(
852 ([key]: any) => key[0] === serializeValue({ category: `A` }),
853 )
854 expect(categoryAGroup).toBeDefined()
855 expect(categoryAGroup[0][1].total).toBe(30) // Sum of 10 + 20
856
857 // Now remove ALL records from category A
858 input.sendData(
859 new MultiSet([
860 [{ category: `A`, amount: 10 }, -1],
861 [{ category: `A`, amount: 20 }, -1],
862 ]),
863 )
864 graph.run()
865
866 // After removing all A records, the group should be completely removed
867 // NOT return a group with total: 0
868 result = latestMessage.getInner()
869
870 // The result should contain the removal of the old group
871 // but NOT the creation of a new group with total: 0
872 const expectedResult = [
873 [
874 [
875 serializeValue({ category: `A` }),
876 {
877 category: `A`,
878 total: 30,
879 },
880 ],
881 -1, // This should be removed
882 ],
883 ]
884
885 expect(result).toEqual(expectedResult)
886
887 // Verify no new group with total: 0 was created by checking that
888 // we don't have any positive weight entries for category A
889 const positiveCategoryAEntries = result.filter(
890 ([key, , weight]: any) =>
891 key[0] === serializeValue({ category: `A` }) && weight > 0,
892 )
893 expect(positiveCategoryAEntries).toHaveLength(0)
894 })
895
896 test(`complete group removal with multiple aggregates`, () => {
897 const graph = new D2()
898 const input = graph.newInput<{
899 category: string
900 region: string
901 amount: number
902 }>()
903 let latestMessage: any = null
904
905 input.pipe(
906 groupBy(
907 (data) => ({
908 category: data.category,
909 region: data.region,
910 }),
911 {
912 total: sum((data) => data.amount),
913 count: count(),
914 average: avg((data) => data.amount),
915 },
916 ),
917 output((message) => {
918 latestMessage = message
919 }),
920 )
921
922 graph.finalize()
923
924 // Initial data
925 input.sendData(
926 new MultiSet([
927 [{ category: `A`, region: `East`, amount: 10 }, 1],
928 [{ category: `A`, region: `East`, amount: 20 }, 1],
929 [{ category: `A`, region: `West`, amount: 30 }, 1],
930 [{ category: `B`, region: `East`, amount: 40 }, 1],
931 ]),
932 )
933 graph.run()
934
935 // Verify initial state
936 expect(latestMessage).not.toBeNull()
937 let result = latestMessage.getInner()
938 expect(result).toHaveLength(3) // Should have 3 groups
939
940 // Find the group for category A, region East
941 const categoryAEastGroup = result.find(
942 ([key]: any) =>
943 key[0] === serializeValue({ category: `A`, region: `East` }),
944 )
945 expect(categoryAEastGroup).toBeDefined()
946 expect(categoryAEastGroup[0][1]).toEqual({
947 category: `A`,
948 region: `East`,
949 total: 30, // 10 + 20
950 count: 2,
951 average: 15, // 30 / 2
952 })
953
954 // Now remove ALL records from category A, region East
955 input.sendData(
956 new MultiSet([
957 [{ category: `A`, region: `East`, amount: 10 }, -1],
958 [{ category: `A`, region: `East`, amount: 20 }, -1],
959 ]),
960 )
961 graph.run()
962
963 // After removing all A/East records, that group should be completely removed
964 // NOT return a group with total: 0, count: 0, average: 0 (or NaN)
965 result = latestMessage.getInner()
966
967 // The result should contain the removal of the old group
968 const expectedResult = [
969 [
970 [
971 serializeValue({ category: `A`, region: `East` }),
972 {
973 category: `A`,
974 region: `East`,
975 total: 30,
976 count: 2,
977 average: 15,
978 },
979 ],
980 -1, // This should be removed
981 ],
982 ]
983
984 expect(result).toEqual(expectedResult)
985
986 // Verify no new group with zero/empty values was created
987 const positiveCategoryAEastEntries = result.filter(
988 ([key, , weight]: any) =>
989 key[0] === serializeValue({ category: `A`, region: `East` }) &&
990 weight > 0,
991 )
992 expect(positiveCategoryAEastEntries).toHaveLength(0)
993 })
994
995 test(`group removal and re-addition with sum aggregate`, () => {
996 const graph = new D2()
997 const input = graph.newInput<{
998 category: string
999 amount: number
1000 }>()
1001 let latestMessage: any = null
1002
1003 input.pipe(
1004 groupBy((data) => ({ category: data.category }), {
1005 total: sum((data) => data.amount),
1006 }),
1007 output((message) => {
1008 latestMessage = message
1009 }),
1010 )
1011
1012 graph.finalize()
1013
1014 // Step 1: Initial data
1015 input.sendData(
1016 new MultiSet([
1017 [{ category: `A`, amount: 10 }, 1],
1018 [{ category: `A`, amount: 20 }, 1],
1019 [{ category: `B`, amount: 30 }, 1],
1020 ]),
1021 )
1022 graph.run()
1023
1024 // Verify initial state
1025 expect(latestMessage).not.toBeNull()
1026 let result = latestMessage.getInner()
1027 expect(result).toHaveLength(2) // Should have 2 groups
1028
1029 // Find the group for category A
1030 const categoryAGroup = result.find(
1031 ([key]: any) => key[0] === serializeValue({ category: `A` }),
1032 )
1033 expect(categoryAGroup).toBeDefined()
1034 expect(categoryAGroup[0][1].total).toBe(30) // Sum of 10 + 20
1035
1036 // Step 2: Remove ALL records from category A
1037 input.sendData(
1038 new MultiSet([
1039 [{ category: `A`, amount: 10 }, -1],
1040 [{ category: `A`, amount: 20 }, -1],
1041 ]),
1042 )
1043 graph.run()
1044
1045 // Verify group A is completely removed
1046 result = latestMessage.getInner()
1047 const expectedRemovalResult = [
1048 [
1049 [
1050 serializeValue({ category: `A` }),
1051 {
1052 category: `A`,
1053 total: 30,
1054 },
1055 ],
1056 -1, // Group should be removed
1057 ],
1058 ]
1059 expect(result).toEqual(expectedRemovalResult)
1060
1061 // Step 3: Re-add records to category A with different values
1062 input.sendData(
1063 new MultiSet([
1064 [{ category: `A`, amount: 50 }, 1],
1065 [{ category: `A`, amount: 25 }, 1],
1066 ]),
1067 )
1068 graph.run()
1069
1070 // Verify group A is recreated with correct new aggregate values
1071 result = latestMessage.getInner()
1072 const expectedReAdditionResult = [
1073 [
1074 [
1075 serializeValue({ category: `A` }),
1076 {
1077 category: `A`,
1078 total: 75, // 50 + 25 (new values, not the old 30)
1079 },
1080 ],
1081 1, // New group should be added
1082 ],
1083 ]
1084 expect(result).toEqual(expectedReAdditionResult)
1085
1086 // Step 4: Verify no lingering effects by adding more data
1087 input.sendData(new MultiSet([[{ category: `A`, amount: 15 }, 1]]))
1088 graph.run()
1089
1090 // Verify aggregate is updated correctly from the new baseline
1091 result = latestMessage.getInner()
1092 const expectedUpdateResult = [
1093 [
1094 [
1095 serializeValue({ category: `A` }),
1096 {
1097 category: `A`,
1098 total: 75, // Previous total
1099 },
1100 ],
1101 -1, // Remove old state
1102 ],
1103 [
1104 [
1105 serializeValue({ category: `A` }),
1106 {
1107 category: `A`,
1108 total: 90, // 75 + 15
1109 },
1110 ],
1111 1, // Add new state
1112 ],
1113 ]
1114 expect(result).toEqual(expectedUpdateResult)
1115 })
1116
1117 test(`group removal and re-addition with multiple aggregates`, () => {
1118 const graph = new D2()
1119 const input = graph.newInput<{
1120 category: string
1121 region: string
1122 amount: number
1123 }>()
1124 let latestMessage: any = null
1125
1126 input.pipe(
1127 groupBy(
1128 (data) => ({
1129 category: data.category,
1130 region: data.region,
1131 }),
1132 {
1133 total: sum((data) => data.amount),
1134 count: count(),
1135 average: avg((data) => data.amount),
1136 minimum: min((data) => data.amount),
1137 maximum: max((data) => data.amount),
1138 },
1139 ),
1140 output((message) => {
1141 latestMessage = message
1142 }),
1143 )
1144
1145 graph.finalize()
1146
1147 // Step 1: Initial data
1148 input.sendData(
1149 new MultiSet([
1150 [{ category: `A`, region: `East`, amount: 10 }, 1],
1151 [{ category: `A`, region: `East`, amount: 20 }, 1],
1152 [{ category: `A`, region: `East`, amount: 30 }, 1],
1153 [{ category: `B`, region: `West`, amount: 100 }, 1],
1154 ]),
1155 )
1156 graph.run()
1157
1158 // Verify initial state
1159 expect(latestMessage).not.toBeNull()
1160 let result = latestMessage.getInner()
1161 expect(result).toHaveLength(2) // Should have 2 groups
1162
1163 // Find the group for category A, region East
1164 const categoryAEastGroup = result.find(
1165 ([key]: any) =>
1166 key[0] === serializeValue({ category: `A`, region: `East` }),
1167 )
1168 expect(categoryAEastGroup).toBeDefined()
1169 expect(categoryAEastGroup[0][1]).toEqual({
1170 category: `A`,
1171 region: `East`,
1172 total: 60, // 10 + 20 + 30
1173 count: 3,
1174 average: 20, // 60 / 3
1175 minimum: 10,
1176 maximum: 30,
1177 })
1178
1179 // Step 2: Remove ALL records from category A, region East
1180 input.sendData(
1181 new MultiSet([
1182 [{ category: `A`, region: `East`, amount: 10 }, -1],
1183 [{ category: `A`, region: `East`, amount: 20 }, -1],
1184 [{ category: `A`, region: `East`, amount: 30 }, -1],
1185 ]),
1186 )
1187 graph.run()
1188
1189 // Verify group is completely removed
1190 result = latestMessage.getInner()
1191 const expectedRemovalResult = [
1192 [
1193 [
1194 serializeValue({ category: `A`, region: `East` }),
1195 {
1196 category: `A`,
1197 region: `East`,
1198 total: 60,
1199 count: 3,
1200 average: 20,
1201 minimum: 10,
1202 maximum: 30,
1203 },
1204 ],
1205 -1, // Group should be removed
1206 ],
1207 ]
1208 expect(result).toEqual(expectedRemovalResult)
1209
1210 // Step 3: Re-add records to category A, region East with completely different values
1211 input.sendData(
1212 new MultiSet([
1213 [{ category: `A`, region: `East`, amount: 5 }, 1],
1214 [{ category: `A`, region: `East`, amount: 15 }, 1],
1215 [{ category: `A`, region: `East`, amount: 40 }, 1],
1216 [{ category: `A`, region: `East`, amount: 40 }, 1], // Duplicate to test aggregates properly
1217 ]),
1218 )
1219 graph.run()
1220
1221 // Verify group is recreated with correct new aggregate values
1222 result = latestMessage.getInner()
1223 const expectedReAdditionResult = [
1224 [
1225 [
1226 serializeValue({ category: `A`, region: `East` }),
1227 {
1228 category: `A`,
1229 region: `East`,
1230 total: 100, // 5 + 15 + 40 + 40 (completely new calculation)
1231 count: 4,
1232 average: 25, // 100 / 4
1233 minimum: 5, // New minimum
1234 maximum: 40, // New maximum
1235 },
1236 ],
1237 1, // New group should be added
1238 ],
1239 ]
1240 expect(result).toEqual(expectedReAdditionResult)
1241
1242 // Step 4: Remove some records and verify aggregates update correctly
1243 input.sendData(
1244 new MultiSet([
1245 [{ category: `A`, region: `East`, amount: 40 }, -1], // Remove one of the 40s
1246 ]),
1247 )
1248 graph.run()
1249
1250 // Verify aggregates are updated correctly from the new baseline
1251 result = latestMessage.getInner()
1252 const expectedPartialRemovalResult = [
1253 [
1254 [
1255 serializeValue({ category: `A`, region: `East` }),
1256 {
1257 category: `A`,
1258 region: `East`,
1259 total: 100,
1260 count: 4,
1261 average: 25,
1262 minimum: 5,
1263 maximum: 40,
1264 },
1265 ],
1266 -1, // Remove old state
1267 ],
1268 [
1269 [
1270 serializeValue({ category: `A`, region: `East` }),
1271 {
1272 category: `A`,
1273 region: `East`,
1274 total: 60, // 5 + 15 + 40 (one 40 removed)
1275 count: 3,
1276 average: 20, // 60 / 3
1277 minimum: 5, // Still 5
1278 maximum: 40, // Still 40 (one remains)
1279 },
1280 ],
1281 1, // Add new state
1282 ],
1283 ]
1284 expect(result).toEqual(expectedPartialRemovalResult)
1285 })
1286 })
1287})