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

incrementalization-law.ts

499 lines14.2 KB

1import { fc } from '@fast-check/vitest'
2import { D2 } from '../src/d2.js'
3import { MultiSet } from '../src/multiset.js'
4import { output } from '../src/operators/output.js'
5import type { IStreamBuilder } from '../src/types.js'
6import type { Arbitrary } from 'fast-check'
7​
8/**
9 * # How does the checker judge an incremental operator?
10 *
11 * A relation is a set of values with signed integer weights. A positive weight
12 * adds copies. A negative weight removes copies. For a query `Q`, a change from
13 * state `x` to state `y` must emit the weighted difference `Q(y) - Q(x)`.
14 *
15 * The caller supplies two independent parts:
16 *
17 * 1. `build` constructs the production D2 graph.
18 * 2. `evaluate` computes the complete expected relation from plain data.
19 *
20 * The checker applies each logical batch in two ways. The atomic run delivers
21 * the batch in one graph step. The split run delivers the same change as legal
22 * one-row steps. After each logical batch, both runs must satisfy three laws:
23 *
24 * 1. The emitted delta equals the difference between full recomputations.
25 * 2. The retained output equals the new full recomputation.
26 * 3. Atomic and split delivery end with the same retained output.
27 *
28 * Split delivery does not invent invalid intermediate input states. It orders
29 * unit changes so weights stay nonnegative. A caller can also declare a unique
30 * row key so a replacement retracts the occupied row before it inserts a new
31 * row with the same key.
32 */
33​
34export type Weighted<T> = Array<[T, number]>
35​
36type StateEntry<T> = { value: T; weight: number }
37type State<T> = Map<string, StateEntry<T>>
38​
39export interface LawValuePolicy<T> {
40 identity: (value: T) => string
41 clone: (value: T) => T
43​
44/**
45 * Policy for JSON-shaped law values whose JSON encoding is the contract's
46 * relation identity. Callers with NaN, infinities, undefined, symbols, or an
47 * identity that ignores object-property order must provide a different policy.
48 */
49export function jsonLawValuePolicy<T>(): LawValuePolicy<T> {
50 return {
51 identity: (value) => `${typeof value}:${JSON.stringify(value)}`,
52 clone: (value) => structuredClone(value),
53 }
55​
56export interface SplitDeliveryDomain<T> {
57 /**
58 * Identifies a slot that may contain at most one distinct relation value.
59 * Omit this for ordinary Z-set inputs where several values may share a key.
60 */
61 uniqueKey?: (value: T) => string
63​
64export interface IncrementalizationReach {
65 atomicCheckpoints: number
66 atomicDeliveries: number
67 splitCheckpoints: number
68 splitDeliveries: number
70​
71export function weightedStateArbitrary<T>(
72 value: Arbitrary<T>,
73 options: { maxLength?: number; maxWeight?: number } = {},
74): Arbitrary<Weighted<T>> {
75 return fc.array(
76 fc.tuple(value, fc.integer({ min: 1, max: options.maxWeight ?? 2 })),
77 { maxLength: options.maxLength ?? 8 },
78 )
80​
81export interface UnaryIncrementalizationLaw<Input, Output> {
82 name: string
83 initial: Weighted<Input>
84 batches: Array<Weighted<Input>>
85 inputPolicy: LawValuePolicy<Input>
86 outputPolicy: LawValuePolicy<Output>
87 splitDomain?: SplitDeliveryDomain<Input>
88 build: (input: IStreamBuilder<Input>) => IStreamBuilder<Output>
89 evaluate: (input: Weighted<Input>) => Weighted<Output>
91​
92export interface BinaryIncrementalizationLaw<Left, Right, Output> {
93 name: string
94 initialLeft: Weighted<Left>
95 initialRight: Weighted<Right>
96 batches: Array<{ left: Weighted<Left>; right: Weighted<Right> }>
97 leftPolicy: LawValuePolicy<Left>
98 rightPolicy: LawValuePolicy<Right>
99 outputPolicy: LawValuePolicy<Output>
100 leftSplitDomain?: SplitDeliveryDomain<Left>
101 rightSplitDomain?: SplitDeliveryDomain<Right>
102 build: (
103 left: IStreamBuilder<Left>,
104 right: IStreamBuilder<Right>,
105 ) => IStreamBuilder<Output>
106 evaluate: (left: Weighted<Left>, right: Weighted<Right>) => Weighted<Output>
108​
109function addBatch<T>(
110 state: State<T>,
111 batch: Weighted<T>,
112 law: string,
113 policy: LawValuePolicy<T>,
114): void {
115 const consolidated: State<T> = new Map()
116 for (const [value, delta] of batch) {
117 if (!Number.isInteger(delta)) {
118 throw new Error(`${law}: weights must be integers`)
119 }
120 const key = policy.identity(value)
121 const weight = (consolidated.get(key)?.weight ?? 0) + delta
122 if (weight === 0) consolidated.delete(key)
123 else consolidated.set(key, { value, weight })
124 }
125​
126 for (const [key, { value, weight }] of consolidated) {
127 const nextWeight = (state.get(key)?.weight ?? 0) + weight
128 if (nextWeight < 0) {
129 throw new Error(`${law}: generated an illegal negative input state`)
130 }
131 if (nextWeight === 0) state.delete(key)
132 else state.set(key, { value: policy.clone(value), weight: nextWeight })
133 }
135​
136function addOutput<T>(
137 state: State<T>,
138 batch: Weighted<T>,
139 policy: LawValuePolicy<T>,
140): void {
141 for (const [value, delta] of batch) {
142 const key = policy.identity(value)
143 const nextWeight = (state.get(key)?.weight ?? 0) + delta
144 if (nextWeight === 0) state.delete(key)
145 else state.set(key, { value: policy.clone(value), weight: nextWeight })
146 }
148​
149function fromWeighted<T>(
150 values: Weighted<T>,
151 policy: LawValuePolicy<T>,
152): State<T> {
153 const state: State<T> = new Map()
154 addOutput(state, values, policy)
155 return state
157​
158function asWeighted<T>(state: State<T>): Weighted<T> {
159 return [...state.values()].map(({ value, weight }) => [value, weight])
161​
162function normalized<T>(state: State<T>): Array<[string, number]> {
163 return [...state.entries()]
164 .map(([key, { weight }]) => [key, weight] as [string, number])
165 .sort(([left], [right]) => left.localeCompare(right))
167​
168function difference<T>(
169 before: Weighted<T>,
170 after: Weighted<T>,
171 policy: LawValuePolicy<T>,
172): State<T> {
173 const result = fromWeighted(after, policy)
174 addOutput(
175 result,
176 before.map(([value, weight]) => [value, -weight]),
177 policy,
178 )
179 return result
181​
182export function weightedDifference<T>(
183 before: Weighted<T>,
184 after: Weighted<T>,
185 policy: LawValuePolicy<T>,
186 cancellationValue?: T,
187): Weighted<T> {
188 const result = asWeighted(difference(before, after, policy))
189 if (cancellationValue !== undefined) {
190 result.push([cancellationValue, -1], [cancellationValue, 1])
191 }
192 return result
194​
195export function weightedTransitions<T>(
196 states: Array<Weighted<T>>,
197 policy: LawValuePolicy<T>,
198 cancellationValue?: T,
199): Array<Weighted<T>> {
200 return states
201 .slice(1)
202 .map((next, index) =>
203 weightedDifference(states[index]!, next, policy, cancellationValue),
204 )
206​
207function assertEqual<T>(
208 law: string,
209 checkpoint: number,
210 kind: string,
211 actual: State<T>,
212 expected: State<T>,
213): void {
214 const actualRows = normalized(actual)
215 const expectedRows = normalized(expected)
216 if (JSON.stringify(actualRows) !== JSON.stringify(expectedRows)) {
217 throw new Error(
218 `${law}: ${kind} diverged at checkpoint ${checkpoint}\n` +
219 `expected ${JSON.stringify(expectedRows)}\n` +
220 `actual ${JSON.stringify(actualRows)}`,
221 )
222 }
224​
225function validUnitPartitions<T>(
226 state: State<T>,
227 batch: Weighted<T>,
228 law: string,
229 policy: LawValuePolicy<T>,
230 domain: SplitDeliveryDomain<T> | undefined,
231): Array<Weighted<T>> {
232 let validation = new Map(
233 [...state].map(([key, { value, weight }]) => [
234 key,
235 { value: policy.clone(value), weight },
236 ]),
237 )
238​
239 const assertDomain = (candidate: State<T>): void => {
240 if (!domain?.uniqueKey) return
241 const occupied = new Set<string>()
242 for (const { value, weight } of candidate.values()) {
243 if (weight <= 0) continue
244 const key = domain.uniqueKey(value)
245 if (occupied.has(key)) {
246 throw new Error(
247 `${law}: split delivery violates unique input key ${key}`,
248 )
249 }
250 occupied.add(key)
251 }
252 }
253​
254 assertDomain(validation)
255 const pending = batch.map(
256 ([value, weight]) => [policy.clone(value), weight] as [T, number],
257 )
258 const deliveries: Array<Weighted<T>> = []
259​
260 while (pending.length > 0) {
261 let selected = -1
262 let nextValidation: State<T> | undefined
263 for (let index = 0; index < pending.length; index++) {
264 const candidate = new Map(
265 [...validation].map(([key, { value, weight }]) => [
266 key,
267 { value: policy.clone(value), weight },
268 ]),
269 )
270 try {
271 addBatch(candidate, [pending[index]!], law, policy)
272 assertDomain(candidate)
273 selected = index
274 nextValidation = candidate
275 break
276 } catch (error) {
277 if (
278 error instanceof Error &&
279 (error.message.includes(
280 `generated an illegal negative input state`,
281 ) ||
282 error.message.includes(`split delivery violates unique input key`))
283 ) {
284 // This unit is not a legal prefix. Another unit may make it legal.
285 continue
286 }
287 throw error
288 }
289 }
290 if (selected < 0 || !nextValidation) {
291 throw new Error(
292 `${law}: batch has no unit ordering with legal split-delivery prefixes`,
293 )
294 }
295 const [delivery] = pending.splice(selected, 1)
296 deliveries.push([delivery!])
297 validation = nextValidation
298 }
299​
300 return deliveries
302​
303interface RunResult<T> {
304 output: State<T>
305 checkpoints: number
306 deliveries: number
308​
309function runUnary<Input, Output>(
310 law: UnaryIncrementalizationLaw<Input, Output>,
311 partition: boolean,
312): RunResult<Output> {
313 const graph = new D2()
314 const input = graph.newInput<Input>()
315 const emitted: Weighted<Output> = []
316 law
317 .build(input)
318 .pipe(output((message) => emitted.push(...message.getInner())))
319 graph.finalize()
320​
321 const inputState: State<Input> = new Map()
322 const outputState: State<Output> = new Map()
323 let deliveriesCount = 0
324 const logicalBatches = [law.initial, ...law.batches]
325 logicalBatches.forEach((batch, checkpoint) => {
326 const before = law.evaluate(asWeighted(inputState))
327 const deliveries = partition
328 ? validUnitPartitions(
329 inputState,
330 batch,
331 law.name,
332 law.inputPolicy,
333 law.splitDomain,
334 )
335 : [batch]
336 addBatch(inputState, batch, law.name, law.inputPolicy)
337 const after = law.evaluate(asWeighted(inputState))
338 const expectedDelta = difference(before, after, law.outputPolicy)
339 emitted.length = 0
340​
341 for (const delivery of deliveries) {
342 input.sendData(new MultiSet(delivery))
343 graph.run()
344 deliveriesCount++
345 }
346​
347 const actualDelta = fromWeighted(emitted, law.outputPolicy)
348 assertEqual(
349 law.name,
350 checkpoint,
351 `output delta`,
352 actualDelta,
353 expectedDelta,
354 )
355 addOutput(outputState, emitted, law.outputPolicy)
356 assertEqual(
357 law.name,
358 checkpoint,
359 `materialized output`,
360 outputState,
361 fromWeighted(after, law.outputPolicy),
362 )
363 })
364 return {
365 output: outputState,
366 checkpoints: logicalBatches.length,
367 deliveries: deliveriesCount,
368 }
370​
371export function assertUnaryIncrementalization<Input, Output>(
372 law: UnaryIncrementalizationLaw<Input, Output>,
373): IncrementalizationReach {
374 const atomic = runUnary(law, false)
375 const split = runUnary(law, true)
376 assertEqual(
377 law.name,
378 law.batches.length,
379 `partitioned output`,
380 split.output,
381 atomic.output,
382 )
383 return {
384 atomicCheckpoints: atomic.checkpoints,
385 atomicDeliveries: atomic.deliveries,
386 splitCheckpoints: split.checkpoints,
387 splitDeliveries: split.deliveries,
388 }
390​
391function runBinary<Left, Right, Output>(
392 law: BinaryIncrementalizationLaw<Left, Right, Output>,
393 partition: boolean,
394): RunResult<Output> {
395 const graph = new D2()
396 const left = graph.newInput<Left>()
397 const right = graph.newInput<Right>()
398 const emitted: Weighted<Output> = []
399 law
400 .build(left, right)
401 .pipe(output((message) => emitted.push(...message.getInner())))
402 graph.finalize()
403​
404 const leftState: State<Left> = new Map()
405 const rightState: State<Right> = new Map()
406 const outputState: State<Output> = new Map()
407 let deliveriesCount = 0
408 const logicalBatches = [
409 { left: law.initialLeft, right: law.initialRight },
410 ...law.batches,
411 ]
412​
413 logicalBatches.forEach((batch, checkpoint) => {
414 const before = law.evaluate(asWeighted(leftState), asWeighted(rightState))
415 const leftDeliveries = partition
416 ? validUnitPartitions(
417 leftState,
418 batch.left,
419 law.name,
420 law.leftPolicy,
421 law.leftSplitDomain,
422 )
423 : [batch.left]
424 const rightDeliveries = partition
425 ? validUnitPartitions(
426 rightState,
427 batch.right,
428 law.name,
429 law.rightPolicy,
430 law.rightSplitDomain,
431 )
432 : [batch.right]
433 addBatch(leftState, batch.left, law.name, law.leftPolicy)
434 addBatch(rightState, batch.right, law.name, law.rightPolicy)
435 const after = law.evaluate(asWeighted(leftState), asWeighted(rightState))
436 const expectedDelta = difference(before, after, law.outputPolicy)
437 emitted.length = 0
438​
439 if (partition) {
440 for (const delivery of leftDeliveries) {
441 left.sendData(new MultiSet(delivery))
442 graph.run()
443 deliveriesCount++
444 }
445 for (const delivery of rightDeliveries) {
446 right.sendData(new MultiSet(delivery))
447 graph.run()
448 deliveriesCount++
449 }
450 } else {
451 left.sendData(new MultiSet(batch.left))
452 right.sendData(new MultiSet(batch.right))
453 graph.run()
454 deliveriesCount++
455 }
456​
457 const actualDelta = fromWeighted(emitted, law.outputPolicy)
458 assertEqual(
459 law.name,
460 checkpoint,
461 `output delta`,
462 actualDelta,
463 expectedDelta,
464 )
465 addOutput(outputState, emitted, law.outputPolicy)
466 assertEqual(
467 law.name,
468 checkpoint,
469 `materialized output`,
470 outputState,
471 fromWeighted(after, law.outputPolicy),
472 )
473 })
474 return {
475 output: outputState,
476 checkpoints: logicalBatches.length,
477 deliveries: deliveriesCount,
478 }
480​
481export function assertBinaryIncrementalization<Left, Right, Output>(
482 law: BinaryIncrementalizationLaw<Left, Right, Output>,
483): IncrementalizationReach {
484 const atomic = runBinary(law, false)
485 const split = runBinary(law, true)
486 assertEqual(
487 law.name,
488 law.batches.length,
489 `partitioned output`,
490 split.output,
491 atomic.output,
492 )
493 return {
494 atomicCheckpoints: atomic.checkpoints,
495 atomicDeliveries: atomic.deliveries,
496 splitCheckpoints: split.checkpoints,
497 splitDeliveries: split.deliveries,
498 }