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

incrementalization-law-oracle.ts

507 lines14.4 KB

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