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

oracle-reach.ts

71 lines2.5 KB

1import { readOracleRunConfig } from './oracle-config.js'
2​
3/**
4 * Declared reach for a generated-history property.
5 *
6 * A law is enforced only in the states that generated histories reach. A
7 * property can pass any number of runs and still check nothing in the state
8 * its law is about, because the grammar, the driver, or the run budget never
9 * produces that state. Counting passing runs does not show reach.
10 *
11 * A property declares the states its laws depend on. Its driver calls
12 * `reach(state)` when a history enters one. After the property ran,
13 * `assertReached()` fails for every declared state that fewer than `minimum`
14 * histories entered. A history counts once per state, however often it
15 * enters it.
16 *
17 * A replay of one seed or path checks one history, not reach, so the check
18 * does nothing then.
19 */
20export function createOracleReach<TState extends string>(
21 property: string,
22 states: ReadonlyArray<TState>,
23 {
24 minimum = 1,
25 replaying: replayOverride,
26 }: { minimum?: number; replaying?: boolean } = {},
27) {
28 const counts = new Map<TState, number>(states.map((state) => [state, 0]))
29 let current = new Set<TState>()
30 // Other packages use their own replay prefixes. An explicit campaign choice
31 // must not inherit an unrelated DB replay selector from the environment.
32 const replaying =
33 replayOverride ??
34 (() => {
35 const { replaySeed, replayPath } = readOracleRunConfig()
36 return replaySeed !== undefined || replayPath !== undefined
37 })()
38 return {
39 /** Starts one generated history. */
40 beginHistory(): void {
41 current = new Set()
42 },
43 /** The current history entered a declared state. */
44 reach(state: TState): void {
45 if (!counts.has(state)) {
46 throw new Error(`${property}: undeclared reach state ${state}`)
47 }
48 if (current.has(state)) return
49 current.add(state)
50 counts.set(state, counts.get(state)! + 1)
51 },
52 /** How many histories entered each declared state. */
53 counts(): ReadonlyMap<TState, number> {
54 return counts
55 },
56 /** Fails for each declared state that too few histories entered. */
57 assertReached(): void {
58 if (replaying) return
59 const missed = [...counts]
60 .filter(([, count]) => count < minimum)
61 .map(([state, count]) => `${state} (${count})`)
62 if (missed.length > 0) {
63 throw new Error(
64 `${property}: generated histories reached these states fewer than ` +
65 `${minimum} times, so their laws were not enforced there: ` +
66 missed.join(`, `),
67 )
68 }
69 },
70 }