Open History to see the last commit
1/**
2 * Distinct preserves one occurrence of every positively supported selected
3 * value, even when unequal values have the same digest. Authority: the unique
4 * combinations promised by docs/guides/live-queries.md, “Distinct”, and the
5 * DBSP accumulation law used by incrementalization-law-oracle.ts.
6 *
7 * This extends that owner's value/history domain. The model recomputes from
8 * plain records; hashing only discovers adversarial inputs for the driver.
9 * The bounded domain is immutable {id: string, value: integer} records. It
10 * exercises two unequal collision members and one noncolliding anchor. It
11 * does not specify representative choice for unequal unselected fields,
12 * ordering, readiness, or intermediate source-transaction publications.
13 */
14import { fc } from '@fast-check/vitest'
15import { declareOracle } from '../../db/tests/oracle-declaration.js'
16import type { Weighted } from './incrementalization-law-oracle.js'
17
18export type DistinctValue = { id: string; value: number }
19export type DistinctWorld = Array<number>
20export type DistinctHistory = Array<DistinctWorld>
21
22export const DISTINCT_REACH_STATES = [
23 `colliding values`,
24 `duplicate support`,
25 `partial removal`,
26 `last removal`,
27 `reinsertion`,
28] as const
29
30// Count input conditions after the driver checked their checkpoints. The two
31// collision members are labels 0 and 1; label 2 is an unequal anchor. No
32// production state supplies these premises.
33export function distinctReachStates(history: DistinctHistory) {
34 const reached = new Set<(typeof DISTINCT_REACH_STATES)[number]>()
35 const seen = new Set<number>()
36 let previous = [0, 0]
37 for (const world of history) {
38 const counts = [0, 1].map(
39 (label) => world.filter((x) => x === label).length,
40 )
41 if (counts.every((count) => count > 0)) reached.add(`colliding values`)
42 for (const label of [0, 1]) {
43 const count = counts[label]!
44 const before = previous[label]!
45 if (count > 1) reached.add(`duplicate support`)
46 if (before > count && count > 0) reached.add(`partial removal`)
47 if (before > 0 && count === 0 && counts[1 - label]! > 0)
48 reached.add(`last removal`)
49 if (before === 0 && count > 0 && seen.has(label))
50 reached.add(`reinsertion`)
51 if (count > 0) seen.add(label)
52 }
53 previous = counts
54 }
55 return reached
56}
57
58// Class numbers are model-only labels for fixture-defined unequal values.
59// World slots become unique source keys in the Collection receiving driver.
60// Repeated labels represent equal selections with independent source support.
61export const distinctHistory = fc
62 .tuple(
63 fc.boolean(),
64 fc.boolean(),
65 fc.integer({ min: 2, max: 4 }),
66 fc.array(fc.array(fc.integer({ min: 0, max: 2 }), { maxLength: 8 }), {
67 maxLength: 12,
68 }),
69 )
70 .map(([reverse, together, copies, tail]): DistinctHistory => {
71 const a = reverse ? 1 : 0
72 const b = reverse ? 0 : 1
73 return [
74 [],
75 ...(together ? [] : [[a]]),
76 [a, b, 2],
77 [...Array<number>(copies).fill(a), b, 2],
78 [a, b, 2],
79 [b, 2],
80 [a, b, 2],
81 [b, a, 2],
82 ...tail,
83 [],
84 [a, b, 2],
85 [],
86 ]
87 })
88
89// Birthday-search actual digests, with no hash replacement. The original
90// report's pair is tried first, then up to 500,000 records. Failure to find a
91// collision or a digest-distinct anchor is a setup error, never evidence that
92// production passed the law.
93export function distinctCollisionValues(
94 digest: (value: DistinctValue) => number,
95): Array<DistinctValue> {
96 const make = (value: number) => ({ id: `item-${value}`, value })
97 const withAnchor = (left: DistinctValue, right: DistinctValue) => {
98 const collisionHash = digest(left)
99 for (let value = -1; value >= -500_000; value--) {
100 const anchor = make(value)
101 if (digest(anchor) !== collisionHash) return [left, right, anchor]
102 }
103 throw new Error(`Distinct noncolliding anchor search exhausted`)
104 }
105 const reported = [make(51277), make(90754)]
106 if (digest(reported[0]!) === digest(reported[1]!))
107 return withAnchor(reported[0]!, reported[1]!)
108 const seen = new Map<number, number>()
109 for (let value = 0; value < 500_000; value++) {
110 const hash = digest(make(value))
111 const previous = seen.get(hash)
112 if (previous !== undefined) return withAnchor(make(previous), make(value))
113 seen.set(hash, value)
114 }
115 throw new Error(`Distinct collision fixture search exhausted`)
116}
117
118// Equality in this domain is equality of both named fields. Neither the
119// reference nor its comparison imports production hashing/equality semantics.
120export function distinctValueIdentity(value: DistinctValue): string {
121 return JSON.stringify([value.id, value.value])
122}
123
124export function recomputeDistinct(
125 input: Weighted<DistinctValue>,
126): Weighted<DistinctValue> {
127 const counts = new Map<string, { value: DistinctValue; count: number }>()
128 for (const [value, weight] of input) {
129 const identity = distinctValueIdentity(value)
130 const count = (counts.get(identity)?.count ?? 0) + weight
131 counts.set(identity, { value, count })
132 }
133 return [...counts.values()]
134 .filter(({ count }) => count > 0)
135 .map(({ value }) => [{ ...value }, 1])
136}
137
138// Preserve duplicate actual rows. Converting actual output to a Set would
139// silently accept duplicate output, just as checking size alone loses values.
140export function checkDistinctSnapshot(
141 actual: Array<DistinctValue>,
142 input: Weighted<DistinctValue>,
143 checkpoint: number,
144): void {
145 const expected = recomputeDistinct(input).map(([value]) =>
146 distinctValueIdentity(value),
147 )
148 const observed = actual.map(distinctValueIdentity)
149 if (JSON.stringify(observed.sort()) !== JSON.stringify(expected.sort()))
150 throw new Error(
151 `distinct snapshot diverged at checkpoint ${checkpoint}: ` +
152 `expected ${JSON.stringify(expected)}, actual ${JSON.stringify(observed)}`,
153 )
154}
155
156declareOracle({
157 model: [recomputeDistinct],
158 grammar: [distinctHistory],
159 check: [checkDistinctSnapshot],
160})
161
162/**
163 * Wider bucket histories separate selected identity from the emitted payload.
164 * The model's member numbers name fixture-defined unequal selections; variant
165 * is unselected data. No representative policy is promised. The full emitted
166 * relation must nevertheless contain one unit row per supported selection:
167 * a negative row must cancel the actual positive contribution (ARCHITECTURE.md,
168 * “Weighted relations and public keys”), not merely an equal selection.
169 * Removing duplicates also preserves a source payload: an emitted variant
170 * must have appeared in a positive input. This does not choose first/last or
171 * require a representative's source slot to remain live.
172 */
173export type DistinctBucketRow = { member: number; variant: number }
174export type DistinctBucketHistory = Array<Array<DistinctBucketRow>>
175export const distinctBucketHistory = fc
176 .tuple(
177 fc.shuffledSubarray([0, 1, 2, 3], { minLength: 4, maxLength: 4 }),
178 fc.integer({ min: 2, max: 4 }),
179 fc.array(
180 fc.array(
181 fc.record({
182 member: fc.integer({ min: 0, max: 4 }),
183 variant: fc.integer({ min: 0, max: 3 }),
184 }),
185 { maxLength: 8 },
186 ),
187 { maxLength: 12 },
188 ),
189 )
190 .map(([order, copies, tail]): DistinctBucketHistory => {
191 const [a, b, c, d] = order as [number, number, number, number]
192 const row = (member: number, variant = 0) => ({ member, variant })
193 return [
194 [],
195 [row(a), row(b)],
196 [
197 ...Array.from({ length: copies }, (_, variant) => row(a, variant)),
198 row(b),
199 ],
200 [row(a, 1), row(b)],
201 [row(b)],
202 [row(b), row(c)],
203 [row(b), row(c), row(d)],
204 [row(a), row(b), row(c), row(d)],
205 ...tail,
206 [],
207 [row(a, 2), row(b, 3)],
208 [],
209 ]
210 })
211
212export const DISTINCT_BUCKET_REACH_STATES = [
213 `unequal unselected payloads`,
214 `three colliding members`,
215 `later collision after removal`,
216 `empty after unequal payloads`,
217] as const
218
219export function distinctBucketReachStates(history: DistinctBucketHistory) {
220 const reached = new Set<(typeof DISTINCT_BUCKET_REACH_STATES)[number]>()
221 const seen = new Set<number>()
222 let removed = false
223 let unequal = false
224 let before = new Set<number>()
225 for (const world of history) {
226 const members = new Set(world.map((row) => row.member))
227 if (
228 [...members].some(
229 (member) =>
230 new Set(
231 world
232 .filter((row) => row.member === member)
233 .map((row) => row.variant),
234 ).size > 1,
235 )
236 ) {
237 reached.add(`unequal unselected payloads`)
238 unequal = true
239 }
240 if ([...members].filter((member) => member < 4).length >= 3)
241 reached.add(`three colliding members`)
242 if (
243 removed &&
244 [...members].some((member) => member < 4 && !seen.has(member))
245 )
246 reached.add(`later collision after removal`)
247 if (unequal && world.length === 0)
248 reached.add(`empty after unequal payloads`)
249 if ([...before].some((member) => !members.has(member))) removed = true
250 for (const member of members) seen.add(member)
251 before = members
252 }
253 return reached
254}
255
256// Final digests can collide without their nested object hashes colliding.
257// Search and verify the entire four-member premise rather than assuming that
258// a reported root collision composes. Hashing supplies stimuli, never truth.
259export function distinctCollisionFamily(
260 digest: (value: unknown) => number,
261): Array<unknown> {
262 const seen = new Map<number, DistinctValue>()
263 for (let value = 0; value < 1_000_000; value++) {
264 const next = { id: `family-${value}`, value }
265 const key = digest(next)
266 const previous = seen.get(key)
267 if (previous) {
268 const family = [
269 [previous, previous],
270 [previous, next],
271 [next, previous],
272 [next, next],
273 ]
274 const hashes = family.map(digest)
275 if (hashes.every((hash) => hash === hashes[0])) {
276 for (let n = -1; n > -100; n--) {
277 const anchor = [{ id: `anchor`, value: n }]
278 if (digest(anchor) !== hashes[0]) return [...family, anchor]
279 }
280 }
281 }
282 seen.set(key, next)
283 }
284 throw new Error(`Distinct four-member collision search exhausted`)
285}
286
287// Sum the raw full-row output, preserving negative residues and duplicate
288// representatives. The expected selections are recomputed solely from source
289// rows. Introduced rows are independent copies of positive source inputs;
290// they let this check reject fabricated payloads without selecting a preferred
291// representative. Keys must distinguish simultaneous outputs; their numerical
292// values and cross-rebuild stability are deliberately unspecified by this law.
293export function checkDistinctRepresentatives(
294 output: Weighted<[number, DistinctBucketRow]>,
295 input: Array<DistinctBucketRow>,
296 introduced: Array<DistinctBucketRow>,
297 checkpoint: string,
298): void {
299 const relation = new Map<
300 string,
301 { key: number; row: DistinctBucketRow; count: number }
302 >()
303 for (const [[key, row], weight] of output) {
304 const id = JSON.stringify([key, row])
305 relation.set(id, {
306 key,
307 row,
308 count: (relation.get(id)?.count ?? 0) + weight,
309 })
310 }
311 const rows = [...relation.values()].filter(({ count }) => count !== 0)
312 const expected = [...new Set(input.map(({ member }) => member))].sort()
313 const observed = rows.map(({ row }) => row.member).sort()
314 if (
315 rows.some(({ count }) => count !== 1) ||
316 rows.some(
317 ({ row }) =>
318 !introduced.some(
319 (source) =>
320 source.member === row.member && source.variant === row.variant,
321 ),
322 ) ||
323 new Set(rows.map(({ key }) => key)).size !== rows.length ||
324 JSON.stringify(observed) !== JSON.stringify(expected)
325 )
326 throw new Error(
327 `distinct representative contribution diverged at ${checkpoint}: ${JSON.stringify({ expected, rows })}`,
328 )
329}
330
331declareOracle({
332 grammar: [distinctBucketHistory],
333 check: [checkDistinctRepresentatives],
334})