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

incrementalization-law.property.test.ts

792 lines25.1 KB

1import { setImmediate } from 'node:timers/promises'
2import { fc } from '@fast-check/vitest'
3import { describe, expect, it } from 'vitest'
4import {
5 consolidate,
6 filter,
7 fullJoin,
8 groupBy,
9 groupByOperators,
10 groupedOrderByWithFractionalIndex,
11 innerJoin,
12 leftJoin,
13 map,
14 negate,
15 orderBy,
16 reduce,
17 rightJoin,
18 topK,
19} from '../src/operators/index.js'
20import {
21 assertBinaryIncrementalization,
22 assertUnaryIncrementalization,
23 jsonLawValuePolicy,
24 weightedDifference,
25 weightedStateArbitrary,
26 weightedTransitions,
27} from './incrementalization-law.js'
28import type { Weighted } from './incrementalization-law.js'
29​
30/**
31 * # Does incremental execution equal full recomputation?
32 *
33 * D2 operators keep state and emit only changes. A wrong delta can leave the
34 * final rows looking right after a later batch, so final-state examples are not
35 * enough. This suite compares every emitted delta and retained result with a
36 * direct recomputation from the complete logical input.
37 *
38 * The plain evaluators below define the expected relations for reductions,
39 * joins, groups, and ordered windows. They use arrays and Maps, not D2
40 * operators. The shared checker then delivers each generated logical change as
41 * one atomic batch and as legal one-row steps.
42 *
43 * The generated domain uses small JSON tuples with integer weights. Named
44 * cases force empty batches, duplicate weights, replacements, cancellation,
45 * presence changes, falsey group extrema, boundary ties, and a zero-width
46 * window. Fault controls prove that the checker rejects missing, sign-flipped,
47 * wrong-member, and truthiness-filtered aggregate output.
48 *
49 * Before this repair the groupBy branch observed only sums. Truthiness defects
50 * in `min` and `max` were therefore outside both its model and its assertions.
51 * The small direct reducer cases remain readable replay witnesses; this suite
52 * owns the generated incremental-versus-recompute law.
53 */
54​
55type Keyed = [number, number]
56type JoinOutput = [number, [number, number]]
57type OuterJoinOutput = [number, [number | null, number | null]]
58type GroupedOutput = [
59 string,
60 {
61 bucket: number
62 total: number
63 minimum: number | undefined
64 maximum: number | undefined
65 },
67​
68const FIXED_SEED = 1741
69type GeneratedCampaign = {
70 name: `fixed` | `random` | `replay`
71 seed: number | undefined
72 path: string | undefined
74​
75const replaySeedText = process.env.TANSTACK_DB_IVM_ORACLE_SEED
76const replaySeed =
77 replaySeedText === undefined ? undefined : Number(replaySeedText)
78const RUNS = Number(process.env.TANSTACK_DB_IVM_ORACLE_RUNS ?? 100)
79const REPLAY_PATH = process.env.TANSTACK_DB_IVM_ORACLE_PATH
80if (
81 replaySeedText !== undefined &&
82 (replaySeedText.trim() === `` || !Number.isSafeInteger(replaySeed))
83) {
84 throw new Error(`TANSTACK_DB_IVM_ORACLE_SEED must be an integer`)
86if (!Number.isSafeInteger(RUNS) || RUNS <= 0) {
87 throw new Error(`TANSTACK_DB_IVM_ORACLE_RUNS must be a positive integer`)
89if (REPLAY_PATH !== undefined && replaySeed === undefined) {
90 throw new Error(
91 `TANSTACK_DB_IVM_ORACLE_PATH requires TANSTACK_DB_IVM_ORACLE_SEED`,
92 )
94​
95const generatedCampaigns: Array<GeneratedCampaign> =
96 replaySeed === undefined
97 ? [
98 { name: `fixed`, seed: FIXED_SEED, path: undefined },
99 { name: `random`, seed: undefined, path: undefined },
100 ]
101 : [{ name: `replay`, seed: replaySeed, path: REPLAY_PATH }]
102​
103function campaignParameters(campaign: (typeof generatedCampaigns)[number]) {
104 return {
105 numRuns: RUNS,
106 ...(campaign.seed === undefined ? {} : { seed: campaign.seed }),
107 ...(campaign.path === undefined ? {} : { path: campaign.path }),
108 }
110​
111const CANCELLATION_ROW: Keyed = [99, 99]
112const keyedPolicy = jsonLawValuePolicy<Keyed>()
113const joinPolicy = jsonLawValuePolicy<JoinOutput>()
114const outerJoinPolicy = jsonLawValuePolicy<OuterJoinOutput>()
115const groupedPolicy = jsonLawValuePolicy<GroupedOutput>()
116const uniqueRowSplitDomain = {
117 uniqueKey: ([key]: Keyed) => String(key),
119​
120/**
121 * The model observes relation membership and multiplicity. Plain `orderBy`
122 * exposes selected members, not their sequence indices. Publication timing and
123 * SQL meaning are separate contracts.
124 *
125 * Normal runs pair a stable campaign with a new random seed. Replay variables
126 * instead select only the recorded seed and shrink path.
127 */
128​
129const weightedWorld = weightedStateArbitrary(
130 fc.tuple(fc.integer({ min: 0, max: 3 }), fc.integer({ min: -3, max: 3 })),
131 { maxLength: 8, maxWeight: 2 },
133​
134function state(values: Weighted<Keyed>): Map<string, [Keyed, number]> {
135 const result = new Map<string, [Keyed, number]>()
136 for (const [value, delta] of values) {
137 const key = JSON.stringify(value)
138 const weight = (result.get(key)?.[1] ?? 0) + delta
139 if (weight === 0) result.delete(key)
140 else result.set(key, [value, weight])
141 }
142 return result
144​
145function transitions(worlds: Array<Weighted<Keyed>>): Array<Weighted<Keyed>> {
146 return weightedTransitions(worlds, keyedPolicy, CANCELLATION_ROW)
148​
149function keyedIdentity(input: Weighted<Keyed>): Weighted<Keyed> {
150 return [...state(input).values()].map(([value, weight]) => [value, weight])
152​
153function summed(input: Weighted<Keyed>): Weighted<Keyed> {
154 const groups = new Map<number, number>()
155 for (const [[key, value], weight] of keyedIdentity(input)) {
156 groups.set(key, (groups.get(key) ?? 0) + value * weight)
157 }
158 return [...groups].map(([key, value]) => [[key, value], 1])
160​
161function joined(
162 left: Weighted<Keyed>,
163 right: Weighted<Keyed>,
164): Weighted<JoinOutput> {
165 const result: Weighted<JoinOutput> = []
166 for (const [[leftKey, leftValue], leftWeight] of keyedIdentity(left)) {
167 for (const [[rightKey, rightValue], rightWeight] of keyedIdentity(right)) {
168 if (leftKey === rightKey) {
169 result.push([
170 [leftKey, [leftValue, rightValue]],
171 leftWeight * rightWeight,
172 ])
173 }
174 }
175 }
176 return result
178​
179function fullJoined(
180 left: Weighted<Keyed>,
181 right: Weighted<Keyed>,
182): Weighted<OuterJoinOutput> {
183 const leftRows = keyedIdentity(left)
184 const rightRows = keyedIdentity(right)
185 const result: Weighted<OuterJoinOutput> = []
186 for (const [[leftKey, leftValue], leftWeight] of leftRows) {
187 const matches = rightRows.filter(([[rightKey]]) => rightKey === leftKey)
188 if (matches.length === 0) {
189 result.push([[leftKey, [leftValue, null]], leftWeight])
190 } else {
191 for (const [[, rightValue], rightWeight] of matches) {
192 result.push([
193 [leftKey, [leftValue, rightValue]],
194 leftWeight * rightWeight,
195 ])
196 }
197 }
198 }
199 for (const [[rightKey, rightValue], rightWeight] of rightRows) {
200 if (leftRows.every(([[leftKey]]) => leftKey !== rightKey)) {
201 result.push([[rightKey, [null, rightValue]], rightWeight])
202 }
203 }
204 return result
206​
207function leftJoined(
208 left: Weighted<Keyed>,
209 right: Weighted<Keyed>,
210): Weighted<OuterJoinOutput> {
211 return fullJoined(left, right).filter(
212 ([[, [leftValue]]]) => leftValue !== null,
213 )
215​
216function rightJoined(
217 left: Weighted<Keyed>,
218 right: Weighted<Keyed>,
219): Weighted<OuterJoinOutput> {
220 return fullJoined(left, right).filter(
221 ([[, [, rightValue]]]) => rightValue !== null,
222 )
224​
225function joinedSums(
226 left: Weighted<Keyed>,
227 right: Weighted<Keyed>,
228): Weighted<Keyed> {
229 const sums = new Map<number, number>()
230 for (const [[key, [leftValue, rightValue]], weight] of joined(left, right)) {
231 sums.set(key, (sums.get(key) ?? 0) + leftValue * rightValue * weight)
232 }
233 return [...sums].map(([key, value]) => [[key, value], 1])
235​
236/**
237 * Group extrema come from every retained defined value. Zero is a value, not
238 * absence. The model recomputes from plain weighted rows and shares no
239 * aggregate reducer with production.
240 */
241function groupedAggregates(input: Weighted<Keyed>): Weighted<GroupedOutput> {
242 const groups = new Map<
243 number,
244 { total: number; minimum: number; maximum: number }
245 >()
246 for (const [[key, value], weight] of keyedIdentity(input)) {
247 const bucket = key % 2
248 const current = groups.get(bucket)
249 groups.set(
250 bucket,
251 current === undefined
252 ? { total: value * weight, minimum: value, maximum: value }
253 : {
254 total: current.total + value * weight,
255 minimum: Math.min(current.minimum, value),
256 maximum: Math.max(current.maximum, value),
257 },
258 )
259 }
260 return [...groups].map(([bucket, aggregates]) => [
261 [JSON.stringify({ bucket }), { bucket, ...aggregates }],
262 1,
263 ])
265​
266function topTwo(input: Weighted<Keyed>): Weighted<Keyed> {
267 const groups = new Map<number, Array<[number, number]>>()
268 for (const [[key, value], weight] of keyedIdentity(input)) {
269 const values = groups.get(key) ?? []
270 values.push([value, weight])
271 groups.set(key, values)
272 }
273 return [...groups].flatMap(([key, values]) =>
274 values
275 .sort(([left], [right]) => left - right)
276 .slice(0, 2)
277 .map(([value, weight]) => [[key, value] as Keyed, weight] as const),
278 )
280​
281const orderedWorld = fc
282 .uniqueArray(
283 fc.tuple(fc.integer({ min: 0, max: 7 }), fc.integer({ min: -20, max: 20 })),
284 { maxLength: 8, selector: ([key]) => key },
285 )
286 .filter((rows) => new Set(rows.map(([, rank]) => rank)).size === rows.length)
287 .map((rows): Weighted<Keyed> => rows.map((row) => [row, 1]))
288​
289function firstThree(input: Weighted<Keyed>): Weighted<Keyed> {
290 return keyedIdentity(input)
291 .sort(([[leftKey, leftRank]], [[rightKey, rightRank]]) =>
292 leftRank === rightRank ? leftKey - rightKey : leftRank - rightRank,
293 )
294 .slice(0, 3)
296​
297function firstTwoPerParity(input: Weighted<Keyed>): Weighted<Keyed> {
298 const groups = new Map<number, Array<[Keyed, number]>>()
299 for (const [value, weight] of keyedIdentity(input)) {
300 const values = groups.get(value[0] % 2) ?? []
301 values.push([value, weight])
302 groups.set(value[0] % 2, values)
303 }
304 return [...groups.values()].flatMap((values) =>
305 values
306 .sort(([[leftKey, leftRank]], [[rightKey, rightRank]]) =>
307 leftRank === rightRank ? leftKey - rightKey : leftRank - rightRank,
308 )
309 .slice(0, 2),
310 )
312​
313describe(`DBSP incrementalization laws`, () => {
314 it.each(generatedCampaigns)(
315 `checks consolidate, reduce, and grouped top-K against full recomputation ($name campaign)`,
316 async (campaign) => {
317 await fc.assert(
318 fc.asyncProperty(
319 fc.array(weightedWorld, { minLength: 2, maxLength: 7 }),
320 async (worlds) => {
321 // Yield between complete histories so stress runs can report progress.
322 // Graph delivery and every observation within a history stay synchronous.
323 await setImmediate()
324 const batches = transitions(worlds)
325 assertUnaryIncrementalization({
326 name: `consolidate`,
327 initial: worlds[0]!,
328 batches,
329 inputPolicy: keyedPolicy,
330 outputPolicy: keyedPolicy,
331 build: (input) => input.pipe(consolidate()),
332 evaluate: keyedIdentity,
333 })
334 assertUnaryIncrementalization({
335 name: `reduce`,
336 initial: worlds[0]!,
337 batches,
338 inputPolicy: keyedPolicy,
339 outputPolicy: keyedPolicy,
340 build: (input) =>
341 input.pipe(
342 reduce((values) => {
343 if (values.length === 0) return []
344 return [
345 [
346 values.reduce(
347 (sum, [value, weight]) => sum + value * weight,
348 0,
349 ),
350 1,
351 ],
352 ]
353 }),
354 ),
355 evaluate: summed,
356 })
357 assertUnaryIncrementalization({
358 name: `groupBy reduction`,
359 initial: worlds[0]!,
360 batches,
361 inputPolicy: keyedPolicy,
362 outputPolicy: groupedPolicy,
363 build: (input) =>
364 input.pipe(
365 groupBy(([key]) => ({ bucket: key % 2 }), {
366 total: groupByOperators.sum(([, value]) => value),
367 minimum: groupByOperators.min(([, value]) => value),
368 maximum: groupByOperators.max(([, value]) => value),
369 }),
370 ),
371 evaluate: groupedAggregates,
372 })
373 assertUnaryIncrementalization({
374 name: `top-K`,
375 initial: worlds[0]!,
376 batches,
377 inputPolicy: keyedPolicy,
378 outputPolicy: keyedPolicy,
379 build: (input) =>
380 input.pipe(topK((left, right) => left - right, { limit: 2 })),
381 evaluate: topTwo,
382 })
383 },
384 ),
385 campaignParameters(campaign),
386 )
387 },
388 )
389​
390 it.each(generatedCampaigns)(
391 `checks simultaneous binary join deltas and split delivery ($name campaign)`,
392 async (campaign) => {
393 await fc.assert(
394 fc.asyncProperty(
395 fc.array(fc.tuple(weightedWorld, weightedWorld), {
396 minLength: 2,
397 maxLength: 7,
398 }),
399 async (generated) => {
400 await setImmediate()
401 const worlds = generated.map(([left, right]) => ({ left, right }))
402 const batches = worlds.slice(1).map((next, index) => ({
403 left: weightedDifference(
404 worlds[index]!.left,
405 next.left,
406 keyedPolicy,
407 CANCELLATION_ROW,
408 ),
409 right: weightedDifference(
410 worlds[index]!.right,
411 next.right,
412 keyedPolicy,
413 CANCELLATION_ROW,
414 ),
415 }))
416 assertBinaryIncrementalization({
417 name: `inner join`,
418 initialLeft: worlds[0]!.left,
419 initialRight: worlds[0]!.right,
420 batches,
421 leftPolicy: keyedPolicy,
422 rightPolicy: keyedPolicy,
423 outputPolicy: joinPolicy,
424 build: (left, right) => left.pipe(innerJoin(right)),
425 evaluate: joined,
426 })
427 assertBinaryIncrementalization({
428 name: `full outer join`,
429 initialLeft: worlds[0]!.left,
430 initialRight: worlds[0]!.right,
431 batches,
432 leftPolicy: keyedPolicy,
433 rightPolicy: keyedPolicy,
434 outputPolicy: outerJoinPolicy,
435 build: (left, right) => left.pipe(fullJoin(right)),
436 evaluate: fullJoined,
437 })
438 assertBinaryIncrementalization({
439 name: `left outer join`,
440 initialLeft: worlds[0]!.left,
441 initialRight: worlds[0]!.right,
442 batches,
443 leftPolicy: keyedPolicy,
444 rightPolicy: keyedPolicy,
445 outputPolicy: outerJoinPolicy,
446 build: (left, right) => left.pipe(leftJoin(right)),
447 evaluate: leftJoined,
448 })
449 assertBinaryIncrementalization({
450 name: `right outer join`,
451 initialLeft: worlds[0]!.left,
452 initialRight: worlds[0]!.right,
453 batches,
454 leftPolicy: keyedPolicy,
455 rightPolicy: keyedPolicy,
456 outputPolicy: outerJoinPolicy,
457 build: (left, right) => left.pipe(rightJoin(right)),
458 evaluate: rightJoined,
459 })
460 assertBinaryIncrementalization({
461 name: `join then grouped reduction`,
462 initialLeft: worlds[0]!.left,
463 initialRight: worlds[0]!.right,
464 batches,
465 leftPolicy: keyedPolicy,
466 rightPolicy: keyedPolicy,
467 outputPolicy: keyedPolicy,
468 build: (left, right) =>
469 left.pipe(
470 innerJoin(right),
471 map(([key, [leftValue, rightValue]]) => [
472 key,
473 leftValue * rightValue,
474 ]),
475 reduce((values) => {
476 if (values.length === 0) return []
477 return [
478 [
479 values.reduce(
480 (sum, [value, weight]) => sum + value * weight,
481 0,
482 ),
483 1,
484 ],
485 ]
486 }),
487 ),
488 evaluate: joinedSums,
489 })
490 },
491 ),
492 campaignParameters(campaign),
493 )
494 },
495 )
496​
497 it.each(generatedCampaigns)(
498 `checks global ordering and window membership ($name campaign)`,
499 async (campaign) => {
500 await fc.assert(
501 fc.asyncProperty(
502 fc.array(orderedWorld, { minLength: 2, maxLength: 7 }),
503 async (worlds) => {
504 await setImmediate()
505 assertUnaryIncrementalization({
506 name: `orderBy`,
507 initial: worlds[0]!,
508 batches: transitions(worlds),
509 inputPolicy: keyedPolicy,
510 outputPolicy: keyedPolicy,
511 splitDomain: uniqueRowSplitDomain,
512 build: (input) =>
513 input.pipe(orderBy((rank) => rank, { limit: 3 })),
514 evaluate: firstThree,
515 })
516 assertUnaryIncrementalization({
517 name: `grouped orderBy`,
518 initial: worlds[0]!,
519 batches: transitions(worlds),
520 inputPolicy: keyedPolicy,
521 outputPolicy: keyedPolicy,
522 splitDomain: uniqueRowSplitDomain,
523 build: (input) =>
524 input.pipe(
525 groupedOrderByWithFractionalIndex((rank) => rank, {
526 groupKeyFn: (key) => key % 2,
527 limit: 2,
528 }),
529 map(([key, [rank]]) => [key, rank] as Keyed),
530 ),
531 evaluate: firstTwoPerParity,
532 })
533 },
534 ),
535 campaignParameters(campaign),
536 )
537 },
538 )
539​
540 it(`replays empty, duplicate, replacement, cancellation, and presence-flip cells`, () => {
541 const unaryReach = assertUnaryIncrementalization({
542 name: `named unary cells`,
543 initial: [],
544 batches: [
545 [
546 [CANCELLATION_ROW, -1],
547 [CANCELLATION_ROW, 1],
548 ],
549 [[[0, 1], 2]],
550 [
551 [[0, 1], -2],
552 [[0, 2], 1],
553 ],
554 [[[0, 2], -1]],
555 ],
556 inputPolicy: keyedPolicy,
557 outputPolicy: keyedPolicy,
558 build: (input) => input.pipe(consolidate()),
559 evaluate: keyedIdentity,
560 })
561 expect(unaryReach).toEqual({
562 atomicCheckpoints: 5,
563 atomicDeliveries: 5,
564 splitCheckpoints: 5,
565 splitDeliveries: 6,
566 })
567​
568 const binaryReach = assertBinaryIncrementalization({
569 name: `named outer-join presence cells`,
570 initialLeft: [[[0, 1], 1]],
571 initialRight: [],
572 batches: [
573 { left: [], right: [[[0, 2], 1]] },
574 {
575 left: [[[0, 1], -1]],
576 right: [[[0, 2], -1]],
577 },
578 ],
579 leftPolicy: keyedPolicy,
580 rightPolicy: keyedPolicy,
581 outputPolicy: outerJoinPolicy,
582 build: (left, right) => left.pipe(fullJoin(right)),
583 evaluate: fullJoined,
584 })
585 expect(binaryReach).toEqual({
586 atomicCheckpoints: 3,
587 atomicDeliveries: 3,
588 splitCheckpoints: 3,
589 splitDeliveries: 4,
590 })
591​
592 const extremaReach = assertUnaryIncrementalization({
593 name: `grouped falsey extrema`,
594 initial: [
595 [[0, 5], 1],
596 [[2, 0], 1],
597 [[1, -2], 1],
598 [[3, 0], 1],
599 ],
600 batches: [],
601 inputPolicy: keyedPolicy,
602 outputPolicy: groupedPolicy,
603 splitDomain: uniqueRowSplitDomain,
604 build: (input) =>
605 input.pipe(
606 groupBy(([key]) => ({ bucket: key % 2 }), {
607 total: groupByOperators.sum(([, value]) => value),
608 minimum: groupByOperators.min(([, value]) => value),
609 maximum: groupByOperators.max(([, value]) => value),
610 }),
611 ),
612 evaluate: groupedAggregates,
613 })
614 expect(extremaReach).toEqual({
615 atomicCheckpoints: 1,
616 atomicDeliveries: 1,
617 splitCheckpoints: 1,
618 splitDeliveries: 4,
619 })
620​
621 assertUnaryIncrementalization({
622 name: `grouped-order boundary tie`,
623 initial: [
624 [[4, 1], 1],
625 [[2, 1], 1],
626 [[0, 1], 1],
627 ],
628 batches: [],
629 inputPolicy: keyedPolicy,
630 outputPolicy: keyedPolicy,
631 splitDomain: uniqueRowSplitDomain,
632 build: (input) =>
633 input.pipe(
634 groupedOrderByWithFractionalIndex((rank) => rank, {
635 groupKeyFn: (key) => key % 2,
636 limit: 2,
637 }),
638 map(([key, [rank]]) => [key, rank] as Keyed),
639 ),
640 evaluate: firstTwoPerParity,
641 })
642​
643 assertUnaryIncrementalization({
644 name: `grouped-order replacement uses legal split prefixes`,
645 initial: [[[6, 0], 1]],
646 // Deliberately put the insertion first. The split scheduler must retract
647 // the occupied unique row key before it can deliver the replacement.
648 batches: [
649 [
650 [[6, -1], 1],
651 [[6, 0], -1],
652 ],
653 ],
654 inputPolicy: keyedPolicy,
655 outputPolicy: keyedPolicy,
656 splitDomain: uniqueRowSplitDomain,
657 build: (input) =>
658 input.pipe(
659 groupedOrderByWithFractionalIndex((rank) => rank, {
660 groupKeyFn: (key) => key % 2,
661 limit: 2,
662 }),
663 map(([key, [rank]]) => [key, rank] as Keyed),
664 ),
665 evaluate: firstTwoPerParity,
666 })
667​
668 assertUnaryIncrementalization({
669 name: `zero-width order window`,
670 initial: [
671 [[0, 0], 1],
672 [[1, 1], 1],
673 ],
674 batches: [],
675 inputPolicy: keyedPolicy,
676 outputPolicy: keyedPolicy,
677 splitDomain: uniqueRowSplitDomain,
678 build: (input) => input.pipe(orderBy((rank) => rank, { limit: 0 })),
679 evaluate: () => [],
680 })
681 })
682​
683 it(`rejects omitted, sign-flipped, wrong-member, wrong-window, and truthiness-filtered output`, () => {
684 expect(() =>
685 assertUnaryIncrementalization({
686 name: `omitted output fault`,
687 initial: [[[0, 1], 1]],
688 batches: [],
689 inputPolicy: keyedPolicy,
690 outputPolicy: keyedPolicy,
691 build: (input) => input.pipe(filter(() => false)),
692 evaluate: keyedIdentity,
693 }),
694 ).toThrow(/output delta diverged/)
695 expect(() =>
696 assertUnaryIncrementalization({
697 name: `sign-flipped weight fault`,
698 initial: [[[0, 1], 1]],
699 batches: [],
700 inputPolicy: keyedPolicy,
701 outputPolicy: keyedPolicy,
702 build: (input) => input.pipe(negate()),
703 evaluate: keyedIdentity,
704 }),
705 ).toThrow(/output delta diverged/)
706 expect(() =>
707 assertUnaryIncrementalization({
708 name: `wrong member fault`,
709 initial: [[[0, 1], 1]],
710 batches: [],
711 inputPolicy: keyedPolicy,
712 outputPolicy: keyedPolicy,
713 build: (input) =>
714 input.pipe(map(([key, value]) => [key, value + 1] as Keyed)),
715 evaluate: keyedIdentity,
716 }),
717 ).toThrow(/output delta diverged/)
718 expect(() =>
719 assertUnaryIncrementalization({
720 name: `wrong window fault`,
721 initial: [
722 [[0, 0], 1],
723 [[1, 1], 1],
724 [[2, 2], 1],
725 [[3, 3], 1],
726 ],
727 batches: [],
728 inputPolicy: keyedPolicy,
729 outputPolicy: keyedPolicy,
730 build: (input) =>
731 input.pipe(
732 orderBy((rank) => rank, {
733 comparator: (left, right) => right - left,
734 limit: 3,
735 }),
736 ),
737 evaluate: firstThree,
738 }),
739 ).toThrow(/output delta diverged/)
740​
741 const truthinessMinimum = {
742 preMap: ([, value]: Keyed): number | undefined => value,
743 reduce: (values: Array<[number | undefined, number]>) => {
744 let minimum: number | undefined
745 for (const [value] of values) {
746 if (!minimum || (value !== undefined && value && value < minimum)) {
747 minimum = value
748 }
749 }
750 return minimum
751 },
752 postMap: (result: number | undefined) => result,
753 }
754 const truthinessMaximum = {
755 preMap: ([, value]: Keyed): number | undefined => value,
756 reduce: (values: Array<[number | undefined, number]>) => {
757 let maximum: number | undefined
758 for (const [value] of values) {
759 if (!maximum || (value !== undefined && value && value > maximum)) {
760 maximum = value
761 }
762 }
763 return maximum
764 },
765 postMap: (result: number | undefined) => result,
766 }
767 expect(() =>
768 assertUnaryIncrementalization({
769 name: `truthiness-filtered extrema fault`,
770 initial: [
771 [[0, 5], 1],
772 [[2, 0], 1],
773 [[1, -2], 1],
774 [[3, 0], 1],
775 ],
776 batches: [],
777 inputPolicy: keyedPolicy,
778 outputPolicy: groupedPolicy,
779 splitDomain: uniqueRowSplitDomain,
780 build: (input) =>
781 input.pipe(
782 groupBy(([key]) => ({ bucket: key % 2 }), {
783 total: groupByOperators.sum(([, value]) => value),
784 minimum: truthinessMinimum,
785 maximum: truthinessMaximum,
786 }),
787 ),
788 evaluate: groupedAggregates,
789 }),
790 ).toThrow(/output delta diverged/)
791 })
792})