gdp-wired 0.22.0 → 0.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/README.md +27 -2
  2. package/dist/core/bmc.d.ts +49 -0
  3. package/dist/core/bmc.js +509 -0
  4. package/dist/core/check.d.ts +1 -1
  5. package/dist/core/check.js +19 -6
  6. package/dist/core/cycles.d.ts +38 -0
  7. package/dist/core/cycles.js +531 -43
  8. package/dist/core/data.d.ts +25 -1
  9. package/dist/core/data.js +984 -215
  10. package/dist/core/discover.js +8 -3
  11. package/dist/core/dsl.d.ts +17 -3
  12. package/dist/core/dsl.js +81 -15
  13. package/dist/core/extract-check.d.ts +77 -0
  14. package/dist/core/extract-check.js +785 -0
  15. package/dist/core/extract-ir.d.ts +139 -0
  16. package/dist/core/extract-ir.js +198 -0
  17. package/dist/core/extract-print.d.ts +30 -0
  18. package/dist/core/extract-print.js +426 -0
  19. package/dist/core/extract-read.d.ts +298 -0
  20. package/dist/core/extract-read.js +1298 -0
  21. package/dist/core/extract-shapes.d.ts +13 -0
  22. package/dist/core/extract-shapes.js +993 -0
  23. package/dist/core/extract-xstate.d.ts +34 -0
  24. package/dist/core/extract-xstate.js +320 -0
  25. package/dist/core/extract.d.ts +31 -0
  26. package/dist/core/extract.js +249 -0
  27. package/dist/core/infer.js +518 -5
  28. package/dist/core/kind.d.ts +30 -0
  29. package/dist/core/kind.js +81 -0
  30. package/dist/core/nonterm.d.ts +34 -0
  31. package/dist/core/nonterm.js +610 -0
  32. package/dist/core/q.d.ts +17 -0
  33. package/dist/core/q.js +52 -0
  34. package/dist/core/rationals.d.ts +112 -0
  35. package/dist/core/rationals.js +281 -0
  36. package/dist/core/relation.d.ts +28 -0
  37. package/dist/core/relation.js +483 -0
  38. package/dist/core/solver.d.ts +5 -2
  39. package/dist/core/solver.js +65 -20
  40. package/dist/core/transfer.d.ts +3 -3
  41. package/dist/core/transfer.js +69 -42
  42. package/dist/core/xstate.d.ts +6 -0
  43. package/dist/core/xstate.js +70 -12
  44. package/dist/kernel/cdcl.d.ts +13 -0
  45. package/dist/kernel/cdcl.js +307 -236
  46. package/dist/kernel/kernel.d.ts +106 -0
  47. package/dist/kernel/kernel.js +342 -0
  48. package/dist/kernel/prove.js +14 -3
  49. package/dist/kernel/qprove.d.ts +18 -0
  50. package/dist/kernel/qprove.js +157 -0
  51. package/dist/kernel/reader.d.ts +14 -0
  52. package/dist/kernel/reader.js +102 -14
  53. package/dist/kernel/simplex.d.ts +4 -0
  54. package/dist/kernel/simplex.js +38 -11
  55. package/dist/lean-kernel/emit.d.ts +46 -1
  56. package/dist/lean-kernel/emit.js +125 -16
  57. package/dist/lean-kernel/library.js +4 -1
  58. package/dist/lean-kernel/qlean.d.ts +26 -0
  59. package/dist/lean-kernel/qlean.js +105 -0
  60. package/package.json +16 -3
package/README.md CHANGED
@@ -68,7 +68,16 @@ All of these are proven automatically, and each proof is also a Lean theorem:
68
68
  - **XState machines** (`gdp-wired/xstate`): `fromXState(machine, {guards, actions})` builds the chart an XState v5
69
69
  machine runs as, with each guard and action it names given again in gdp-wired's terms, and `conforms(chart, machine,
70
70
  createActor)` drives XState's own actor and the compiled rule with the same random events, comparing every state and
71
- context; what a chart can't run the same way is refused when built, with the reason (`examples/xstate.ts`).
71
+ context; what a chart can't run the same way, and any key it doesn't read, is refused when built, with the reason
72
+ (`examples/xstate.ts`). A v4 machine's `cond` is read as its guard.
73
+ - **Rules read from the code** (`gdp-wired/extract`): `extract(code, {entry})` reads a reducer, `useReducer`'s, functions
74
+ over one record, or a class whose methods write its fields, and returns the rule that steps the same way, as a builder
75
+ value and as source to keep (`toSource`); `extractXState` reads an XState machine's guards and actions, named or
76
+ inline, for `fromXState`. The extractor is untrusted: each rule is run beside the code it was read from (requests
77
+ from the start, steps from drawn states and from the prover's counterexamples, every state, cell, result and refusal
78
+ compared, the code's branches counted), and a difference refuses it. Its subset (integers, booleans, string-literal
79
+ unions, records, Map and Record keyed state, branches and early returns, throws as refusals, `Date.now()` as an
80
+ input) and what it refuses, each with the place and the reason, are in `core/extract.ts`.
72
81
  - **What nobody stated, looked for when the prover alone stops**: where `proveRule` or `proveSteps` doesn't prove the laws
73
82
  and no run breaks them, it looks for lemmas about the rule's recurrences and lists (`discover`), lemmas about the
74
83
  functions it knows by their facts (`cycleLemmas`, each proven by a cyclic proof) and then invariants (`inferLaws`),
@@ -103,12 +112,27 @@ All of these are proven automatically, and each proof is also a Lean theorem:
103
112
  goal reads), and the lemma a stuck one needs (g(x, 0) = 2x through g(x, a) = a + 2x; a bound on another function);
104
113
  `proveLoop` with no rank finds it (two phases' (x, y)) and the invariants it needs; the kernel checks the cyclic
105
114
  proof (`examples/cycles.ts`).
115
+ - **Runs that never end**: `proveNeverEnds(loop)` proves some run of a loop goes on forever (pagination that accepts an
116
+ empty page, a retry with no cap): a closed recurrent set with the turn from each of its states given, a start and a
117
+ stem into it, checked by the kernel and again in Lean (`NonTerm.lean`'s `never_ends_of`; `examples/nonterm.ts`).
118
+ - **Rules over the rationals** (`gdp-wired/rationals`): `ratRule` with `rat` and `nonneg` params, inputs and state,
119
+ each value an exact rational (0.1 is 1/10, a third is 1/3: nothing scaled to cents or encoded as naturals), terms
120
+ linear (+, −, × and ÷ by a constant, min, max, when). Linear arithmetic over ℚ is decidable: a law is proven by
121
+ trees whose leaves are Farkas certificates with strict rows, or refuted by an exact run from the start. A fee split,
122
+ a rate limiter with fractional tokens and a ledger in decimals, and 12 laws true over one of ℕ and ℚ and false over
123
+ the other, each decided both ways (`examples/rationals.ts`); the proofs again in Lean (`Rationals.lean`'s
124
+ `Q.machine_sound`). Products of unknowns and transcendental functions stay outside.
106
125
  - **Recursive datatypes as values** (`gdp-wired/data`): lists, trees, rose trees and their forests, declared by their
107
126
  constructors; functions over them by structural recursion, or by any recursion whose termination is proven first (a
108
127
  merge of two lists, a quicksort: the measure found, (size xs, size ys) or a sum of sizes, and each call's decrease
109
128
  proven by the kernel before the function's equation is used; one that doesn't terminate is refused with the reason);
110
129
  `proveData` finds the induction (structural, mutual, or the function's own call graph ranked by its measure) and the
111
130
  lemmas, each proof checked in Lean against the `inductive` and the functions as declared (`examples/data.ts`).
131
+ An abstract sort (`opaque('Elem')`: values compared by equality alone, any other read refused) makes a law hold at
132
+ every element type, not only the naturals; `unknownFn('f', [Elem], List)` is any function between sorts (a law about
133
+ every f, every default, every callback); `closures(...)` is a datatype of functions with its `apply`, for fields that
134
+ hold functions (`examples/abstract.ts`; Lean's twin doesn't yet close two shapes of its export there: a datatype of
135
+ two constructors with fields, and two constructor values compared inside a disjunction).
112
136
  - **Records and variants**: inputs, state, results, map cells and list items made of named fields, or one of several
113
137
  cases each with fields of its own (a payment by card or in cash, a seat free, held or sold), every case covered
114
138
  (`examples/datatypes.ts`).
@@ -440,7 +464,8 @@ The npm package is built from `core/`, `kernel/` and `lean-kernel/` alone; nothi
440
464
  ## Running
441
465
 
442
466
  The npm package is the library: the builders (`gdp-wired`), the runtimes (`gdp-wired/machine`), composition
443
- (`gdp-wired/compose`), XState machines as charts (`gdp-wired/xstate`), lemmas nobody stated (`gdp-wired/discover`), invariant
467
+ (`gdp-wired/compose`), XState machines as charts (`gdp-wired/xstate`), rules read from the code (`gdp-wired/extract`, with
468
+ `typescript` installed), lemmas nobody stated (`gdp-wired/discover`), invariant
444
469
  inference (`gdp-wired/infer`), the
445
470
  Lean export (`gdp-wired/lean`), the kernel (`gdp-wired/kernel`), the prover (`gdp-wired/prove`), the derivation checker
446
471
  and solver (`gdp-wired/check`, `gdp-wired/solver`). Everything else here (examples, comparisons, the Lean twin, the GPU
@@ -0,0 +1,49 @@
1
+ import { type C, type E, type Law, type Machine, type Request } from './machine.js';
2
+ export type BoundedRun = {
3
+ law: string;
4
+ depth: number;
5
+ witness: Record<string, number>;
6
+ params: Record<string, number>;
7
+ trace: Request[];
8
+ };
9
+ export type BmcOptions = {
10
+ ms: number;
11
+ wall?: number;
12
+ from?: number;
13
+ depth?: number;
14
+ progress?: (depth: number, outcome: 'refuted' | 'sat' | 'unknown', ms: number) => void;
15
+ };
16
+ export declare function bmcFits(m: Machine, laws: Law[]): boolean;
17
+ export declare const bmcRate = 250;
18
+ export declare function bmcGoal(m: Machine, laws: Law[], k: number): {
19
+ name: string;
20
+ hyps: C[];
21
+ };
22
+ export declare function fixed(hyps: C[]): {
23
+ hyps: C[];
24
+ fixed: Record<string, number>;
25
+ } | undefined;
26
+ export declare function relax(hyps: C[]): C[] | undefined;
27
+ export declare function reduce(hyps: C[]): {
28
+ hyps: C[];
29
+ defs: [string, E][];
30
+ } | undefined;
31
+ export declare function putBack(m: Machine, w: Record<string, number>, defs: [string, E][]): Record<string, number>;
32
+ export declare function runOf(m: Machine, w: Record<string, number>, k: number): {
33
+ params: Record<string, number>;
34
+ trace: Request[];
35
+ };
36
+ export declare function replay(m: Machine, laws: Law[], run: {
37
+ params: Record<string, number>;
38
+ trace: Request[];
39
+ }): {
40
+ law: string;
41
+ steps: number;
42
+ witness: Record<string, number>;
43
+ } | undefined;
44
+ export declare function forcedRun(m: Machine, laws: Law[], opts: {
45
+ steps: number;
46
+ wall: number;
47
+ guesses?: number;
48
+ }): BoundedRun | undefined;
49
+ export declare function findBoundedRun(m: Machine, laws: Law[], opts: BmcOptions): BoundedRun | undefined;
@@ -0,0 +1,509 @@
1
+ // Bounded runs: a law broken by a run of k steps from the start, found by the prover's model search. Nothing here is
2
+ // trusted. The goal of depth k is the kernel's own k-step goal (kernel.ts's stepLawObligations, `steps: k`): its first
3
+ // `when` is the start (each state variable its start value over the params), its `then` the laws after the last step
4
+ // (primed names), refuted. Its constants are put in (`fixed`), and a model of it is asked of kernel/cdcl.ts's search
5
+ // over its atoms with the incremental simplex (`model`: a refutation isn't unfolded into a tree, and each decision's
6
+ // phase is the simplex's point's). The model names the params and each step's request; the run is then taken by the
7
+ // interpreter, each request checked against the rule's assumption, and kept only where it breaks a law. A goal refuted
8
+ // at depth k says no run of k steps breaks the laws; the depths grow until the budget, or 64 (the kernel's bound on k),
9
+ // runs out.
10
+ //
11
+ // Before the search each goal is made smaller, keeping its models (`reduce`): a name equal to another name or a constant
12
+ // replaced by it, and a definition (n = e) of a name nothing else reads dropped (the cone of influence: a state value no
13
+ // later step and no law reads, a request value only its own equation reads), each name put back into the model from
14
+ // its definition. And it is first asked relaxed (`relax`): an integer is a pair of naturals (n, n$neg) normalized where
15
+ // it is written (n = a ∸ b, n$neg = b ∸ a: one case of the kernel's per pair and step), and every read of a pair is of
16
+ // its difference (dsl.ts's Int: sums, comparisons, products by constants, remainders and quotients alike), so the pair
17
+ // written as any two naturals of difference a − b (n + b = a + n$neg) is the same integer to every later read. The
18
+ // relaxed goal has every model of the goal; a run it gives is taken by the interpreter, which normalizes, and where
19
+ // that run breaks no law (a read of a pair the relaxation doesn't keep), the goal itself is asked at that depth. A
20
+ // relaxed goal refuted is the goal refuted.
21
+ //
22
+ // The budget is read off prove.ts's clock inside `counted` (the kernel's work, bmcRate units a millisecond), so the
23
+ // search is the same on any machine; a wall-clock stop beside it (`wall`) is for callers under a wall-clock limit.
24
+ import { evalC, evalE, interpret, isArithmetic, loadJs, numbersOf } from "./machine.js";
25
+ import { stepLawObligations, substC, substE } from "../kernel/kernel.js";
26
+ import { clock, counted } from "../kernel/prove.js";
27
+ import { REFUTED, cdclSession, growCdcl } from "../kernel/cdcl.js";
28
+ import { allowed } from "./watch.js";
29
+ import { simpC, simpE } from "./nonterm.js";
30
+ // Machines whose runs the goals describe as they are: scalars only (no maps, history or carried maps), no quantified
31
+ // flag, no function but division by a constant (whose facts fix its value); laws plain (no key, no "there exists").
32
+ export function bmcFits(m, laws) {
33
+ if (Object.keys(m.maps ?? {}).length || m.history || m.inputMaps?.length)
34
+ return false;
35
+ if (Object.values(m.step.flags ?? {}).some(f => f.op === 'all'))
36
+ return false;
37
+ if (Object.keys(m.fns ?? {}).some(f => !isArithmetic(f)))
38
+ return false;
39
+ if (JSON.stringify([m.state, m.step, m.assume ?? null, laws.map(l => l.holds)]).includes('"op":"prod"'))
40
+ return false;
41
+ return laws.every(l => !l.forall && !l.some?.length);
42
+ }
43
+ // The counted clock's rate here, units of the kernel's work a millisecond: the median of what Modal's 2-vCPU containers
44
+ // did on the k-step goals of CHC-COMP's unsat LIA-Lin tasks, the stage alone (runs/bmc2/only-mine3: 1,215 depths past
45
+ // 200 ms, 252 units a ms at the median, 383 at the 90th percentile; 168 at the median before reader.ts kept its clean
46
+ // values and the goals were reduced, runs/bmc2/only-base1). The CDCL search counts its rows, which a goal of many atoms
47
+ // and few rows a node keeps low, so a caller under a wall-clock limit gives a wall stop too.
48
+ export const bmcRate = 250;
49
+ // A forced run's share of the budget, and its steps at most (a derivation checkDerivation replays step by step).
50
+ const forcedShare = 0.3, forcedSteps = 1_000_000;
51
+ // GDP_BMC_RELAX=0: no relaxed goal first; GDP_BMC_INC=0: each depth's goal a search of its own (for comparing).
52
+ const env = globalThis.process?.env ?? {};
53
+ const useRelax = env.GDP_BMC_RELAX !== '0', useInc = env.GDP_BMC_INC !== '0';
54
+ // The goal of depth k: a run of k steps from the start whose last state breaks a law.
55
+ export function bmcGoal(m, laws, k) {
56
+ const start = { op: 'and', xs: Object.entries(m.state).map(([n, e]) => ({ op: '=', a: { op: 'var', name: n }, b: e })) };
57
+ const after = { vars: Object.fromEntries(Object.keys(m.state).map(n => [n, { op: 'var', name: `${n}'` }])), maps: {}, flags: {} };
58
+ const then = substC({ op: 'and', xs: laws.map(l => l.holds) }, after);
59
+ // Renamed: prove.ts keeps CDCL off goals named `@k steps` (for the size of their proofs); a model is all wanted here.
60
+ const g = stepLawObligations(m, [], {}, { name: 'a bounded run', when: start, then, steps: k })[0];
61
+ return { name: `a bounded run of ${k}`, hyps: g.hyps };
62
+ }
63
+ // The goal with its constants put in: each name a hypothesis fixes (n = c, at the top) replaced by its value and the
64
+ // terms folded (core/nonterm.ts's simpC), until none is left; the names fixed, with their values (a model's part), or
65
+ // undefined where a hypothesis folds to false (no model).
66
+ const top = (c) => (c.op === 'and' ? c.xs.flatMap(top) : [c]);
67
+ const isFalse = (c) => (c.op === '<' || c.op === '<=') && c.a.op === 'const' && c.b.op === 'const' && (c.op === '<' ? c.a.value >= c.b.value : c.a.value > c.b.value);
68
+ const isTrue = (c) => c.op === '<=' && c.a.op === 'const' && c.b.op === 'const' && c.a.value <= c.b.value;
69
+ export function fixed(hyps) {
70
+ const values = {};
71
+ let cs = hyps.flatMap(top);
72
+ for (;;) {
73
+ const now = {};
74
+ for (const c of cs)
75
+ if (c.op === '=') {
76
+ const [v, k] = c.a.op === 'var' && c.b.op === 'const' ? [c.a.name, c.b.value] : c.b.op === 'var' && c.a.op === 'const' ? [c.b.name, c.a.value] : [];
77
+ if (v !== undefined && !(v in now)) {
78
+ now[v] = { op: 'const', value: k };
79
+ values[v] = k;
80
+ }
81
+ }
82
+ if (!Object.keys(now).length)
83
+ return { hyps: cs, fixed: values };
84
+ cs = cs.map(c => simpC(substC(c, { vars: now, maps: {}, flags: {} }))).flatMap(top);
85
+ if (cs.some(isFalse))
86
+ return undefined;
87
+ cs = cs.filter(c => !isTrue(c));
88
+ }
89
+ }
90
+ // Each name's occurrences in some terms (a goal's terms are trees as the kernel reads them).
91
+ const occurrences = (xs, out = new Map()) => {
92
+ const go = (x) => {
93
+ switch (x.op) {
94
+ case 'var':
95
+ out.set(x.name, (out.get(x.name) ?? 0) + 1);
96
+ return;
97
+ case 'const':
98
+ case 'flag': return;
99
+ case 'add':
100
+ case 'sub':
101
+ case 'min':
102
+ case 'max':
103
+ case 'prod':
104
+ case '<':
105
+ case '<=':
106
+ case '=':
107
+ go(x.a);
108
+ go(x.b);
109
+ return;
110
+ case 'mul':
111
+ go(x.a);
112
+ return;
113
+ case 'if':
114
+ go(x.c);
115
+ go(x.then);
116
+ go(x.else);
117
+ return;
118
+ case 'get':
119
+ go(x.key);
120
+ return;
121
+ case 'and':
122
+ case 'or':
123
+ x.xs.forEach(go);
124
+ return;
125
+ case 'not':
126
+ go(x.x);
127
+ return;
128
+ case 'all':
129
+ go(x.c);
130
+ return;
131
+ }
132
+ };
133
+ xs.forEach(go);
134
+ return out;
135
+ };
136
+ // The goal relaxed (above): each pair written normalized at a step (n = a ∸ b and n$neg = b ∸ a, its partner the name
137
+ // with $neg before the step's ~j) as one equation of differences.
138
+ const partnerOf = (n) => (n.includes('$neg') ? undefined : n.replace(/(~\d+)?$/, j => `$neg${j}`));
139
+ const alike = (a, b) => a === b || JSON.stringify(a) === JSON.stringify(b);
140
+ export function relax(hyps) {
141
+ const defs = new Map();
142
+ for (const h of hyps)
143
+ if (h.op === '=' && h.a.op === 'var' && h.b.op === 'sub')
144
+ defs.set(h.a.name, { h, e: h.b });
145
+ const gone = new Set(), out = [];
146
+ for (const [n, { h, e }] of defs) {
147
+ const p = partnerOf(n), d = p === undefined ? undefined : defs.get(p);
148
+ if (!d || !alike(e.a, d.e.b) || !alike(e.b, d.e.a))
149
+ continue;
150
+ gone.add(h);
151
+ gone.add(d.h);
152
+ out.push({ op: '=', a: { op: 'add', a: { op: 'var', name: n }, b: e.b }, b: { op: 'add', a: e.a, b: { op: 'var', name: p } } });
153
+ }
154
+ return out.length ? [...hyps.filter(h => !gone.has(h)), ...out] : undefined;
155
+ }
156
+ // The goal made smaller with its models kept (above): the hypotheses left, and the names taken out with their terms,
157
+ // in the order taken (a later one's term may read an earlier one's name, never the other way), or undefined where a
158
+ // hypothesis folds to false.
159
+ export function reduce(hyps) {
160
+ let cs = hyps;
161
+ const defs = [];
162
+ for (;;) {
163
+ const n = occurrences(cs), sub = {}, drop = new Set();
164
+ for (const h of cs) {
165
+ if (h.op !== '=')
166
+ continue;
167
+ for (const [a, e] of [[h.a, h.b], [h.b, h.a]]) {
168
+ if (a.op !== 'var' || a.name in sub || occurrences([e]).has(a.name))
169
+ continue;
170
+ const copy = (e.op === 'var' && !(e.name in sub)) || e.op === 'const';
171
+ if (n.get(a.name) !== 1 && !copy)
172
+ continue;
173
+ drop.add(h);
174
+ defs.push([a.name, e]);
175
+ if (copy)
176
+ sub[a.name] = e;
177
+ break;
178
+ }
179
+ }
180
+ if (!drop.size)
181
+ return { hyps: cs, defs };
182
+ // (a copy's name may be another's copy: each replaced by the end of its chain)
183
+ for (const n0 of Object.keys(sub)) {
184
+ let e = sub[n0];
185
+ for (let i = 0; e.op === 'var' && sub[e.name] && i < 64; i++)
186
+ e = sub[e.name];
187
+ sub[n0] = e;
188
+ }
189
+ const s = { vars: sub, maps: {}, flags: {} }, any = Object.keys(sub).length > 0;
190
+ cs = cs.filter(h => !drop.has(h)).map(h => (any ? simpC(substC(h, s)) : h)).flatMap(top);
191
+ if (cs.some(isFalse))
192
+ return undefined;
193
+ cs = cs.filter(c => !isTrue(c));
194
+ }
195
+ }
196
+ // A model's names taken out put back, the last taken first (each term read at the model, a name it doesn't give 0).
197
+ export function putBack(m, w, defs) {
198
+ const out = { ...w };
199
+ for (const [n, e] of [...defs].reverse()) {
200
+ for (const x of occurrences([e]).keys())
201
+ if (!(x in out))
202
+ out[x] = 0;
203
+ try {
204
+ out[n] = evalE(e, out, { scalars: {}, maps: {} }, m);
205
+ }
206
+ catch {
207
+ out[n] = 0;
208
+ }
209
+ }
210
+ return out;
211
+ }
212
+ // The run a model names: the params, the first request by plain names, the j-th (j >= 2) as input@j.
213
+ export function runOf(m, w, k) {
214
+ const at = (n) => Math.max(0, Math.round(w[n] ?? 0));
215
+ const params = Object.fromEntries(m.params.map(p => [p, at(p)]));
216
+ const trace = Array.from({ length: k }, (_, j) => Object.fromEntries(m.inputs.map(n => [n, at(j ? `${n}@${j + 1}` : n)])));
217
+ return { params, trace };
218
+ }
219
+ // The run taken by the interpreter, up to the first step that breaks a law: the law, the steps, and the witness (the
220
+ // params, the state the last step starts from and its request), or undefined (a request refused, or no law broken).
221
+ export function replay(m, laws, run) {
222
+ const it = interpret(m);
223
+ if (m.pre && !evalC(m.pre, run.params, { scalars: {}, maps: {} }, m))
224
+ return undefined;
225
+ try {
226
+ let st = it.init(run.params);
227
+ for (const [j, input] of run.trace.entries()) {
228
+ if (!allowed(m, it, run.params, st, input))
229
+ return undefined;
230
+ const before = st;
231
+ st = it.step(run.params, st, input);
232
+ const law = laws.find(l => !evalC(l.holds, { ...run.params }, st, m))?.name;
233
+ if (law !== undefined)
234
+ return { law, steps: j + 1, witness: { ...run.params, ...before.scalars, ...numbersOf(input) } };
235
+ }
236
+ return undefined;
237
+ }
238
+ catch (e) {
239
+ if (e instanceof RangeError)
240
+ return undefined;
241
+ throw e;
242
+ }
243
+ }
244
+ // A forced run: from the start, each step the one the rule allows (a machine without params whose requests choose among
245
+ // a few cases, each request value below a bound its assumption states, the others 0), taken by the compiled rule until a
246
+ // step breaks a law, the run reaches a state with no way on, or `steps` or `wall` runs out. A step is forced where one
247
+ // case moves the state and that case reads no other request value; at most `guesses` steps aren't (a start of free
248
+ // values taken as 0, two ways on taken by the first). A deterministic loop's long runs (CHC-COMP's s_split: 10,002
249
+ // steps; the k-step goals fold to false without a case past depth 64) are its runs; a machine whose steps read their
250
+ // requests stops within a few steps. The run, as a bounded run's.
251
+ export function forcedRun(m, laws, opts) {
252
+ if (m.params.length || !laws.length || !bmcFits(m, laws))
253
+ return undefined;
254
+ // Each input bounded by the assumption (a top-level i < c or i <= c, c at most 64): its values; the others free.
255
+ const bound = new Map();
256
+ for (const c of m.assume ? top(m.assume) : [])
257
+ if ((c.op === '<' || c.op === '<=') && c.a.op === 'var' && c.b.op === 'const' && m.inputs.includes(c.a.name))
258
+ bound.set(c.a.name, Math.min(bound.get(c.a.name) ?? Infinity, c.op === '<' ? c.b.value : c.b.value + 1));
259
+ const finite = m.inputs.filter(i => (bound.get(i) ?? Infinity) <= 64), free = m.inputs.filter(i => !finite.includes(i));
260
+ let choices = [{}];
261
+ for (const i of finite) {
262
+ const n = bound.get(i);
263
+ choices = choices.flatMap(ch => Array.from({ length: n }, (_, v) => ({ ...ch, [i]: v })));
264
+ if (choices.length > 256)
265
+ return undefined;
266
+ }
267
+ // Whether a case reads a free value: its assumption and updates with the case put in.
268
+ // (the step's flags put in first: each a condition of the step, read where the terms read it, and each over the flags
269
+ // before it, as kernel.ts's flagsOf reads them)
270
+ const inlined = {};
271
+ for (const [f, c] of Object.entries(m.step.flags ?? {}))
272
+ inlined[f] = substC(c, { vars: {}, maps: {}, flags: inlined });
273
+ const flags = { vars: {}, maps: {}, flags: inlined };
274
+ const assume = m.assume && substC(m.assume, flags);
275
+ const conds = assume ? [assume] : [], updates = Object.values(m.step.state ?? {}).map(e => substE(e, flags));
276
+ const reads = choices.map(ch => {
277
+ const s = { vars: Object.fromEntries(Object.entries(ch).map(([n, v]) => [n, { op: 'const', value: v }])), maps: {}, flags: {} };
278
+ const ns = occurrences([...conds.map(c => simpC(substC(c, s))), ...updates.map(e => simpE(substE(e, s)))]);
279
+ return free.some(i => ns.has(i));
280
+ });
281
+ // Each case's assumption's top-level equations of a state value and a constant (where a CHC clause's body is), read
282
+ // before the step is taken.
283
+ const at = choices.map(ch => {
284
+ const s = { vars: Object.fromEntries(Object.entries(ch).map(([n, v]) => [n, { op: 'const', value: v }])), maps: {}, flags: {} };
285
+ return (assume ? top(simpC(substC(assume, s))) : []).flatMap(c => (c.op === '=' && c.a.op === 'var' && c.a.name in m.state && c.b.op === 'const' ? [[c.a.name, c.b.value]] : []));
286
+ });
287
+ // The rule with its assumption as a value (bmc$ok: 1 where the request is allowed), so a refused request throws nothing.
288
+ const ok = 'bmc$ok';
289
+ if (ok in m.state)
290
+ return undefined;
291
+ let js;
292
+ try {
293
+ js = loadJs({ ...m, state: { ...m.state, [ok]: { op: 'const', value: 1 } }, step: { ...m.step, state: { ...m.step.state, [ok]: m.assume ? { op: 'if', c: m.assume, then: { op: 'const', value: 1 }, else: { op: 'const', value: 0 } } : { op: 'const', value: 1 } } }, assume: undefined });
294
+ }
295
+ catch {
296
+ return undefined;
297
+ }
298
+ const same = (a, b) => { for (const key in a.scalars)
299
+ if (key !== ok && a.scalars[key] !== b.scalars[key])
300
+ return false; return true; };
301
+ const take = (st, input) => { try {
302
+ const next = js.step({}, js.fork(st), input);
303
+ return next.scalars[ok] === 1 ? next : undefined;
304
+ }
305
+ catch (e) {
306
+ if (e instanceof RangeError)
307
+ return undefined;
308
+ throw e;
309
+ } };
310
+ const broken = (st) => laws.find(l => !evalC(l.holds, {}, st, m))?.name;
311
+ const requests = choices.map(ch => ({ ...Object.fromEntries(free.map(i => [i, 0])), ...ch }));
312
+ let st = js.init({}), guesses = opts.guesses ?? 2;
313
+ const trace = [];
314
+ for (let n = 0; n < opts.steps && (n % 256 || performance.now() < opts.wall); n++) {
315
+ let next, request, forced = true;
316
+ for (const [j, input] of requests.entries()) {
317
+ if (at[j].some(([n, v]) => st.scalars[n] !== v))
318
+ continue;
319
+ const a = take(st, input);
320
+ if (!a)
321
+ continue;
322
+ const law = broken(a);
323
+ if (law !== undefined) {
324
+ const { [ok]: _, ...before } = st.scalars;
325
+ return { law, depth: n + 1, witness: { ...before, ...numbersOf(input) }, params: {}, trace: [...trace, input] };
326
+ }
327
+ if (same(a, st))
328
+ continue;
329
+ if (reads[j])
330
+ forced = false;
331
+ if (!next) {
332
+ next = a;
333
+ request = input;
334
+ }
335
+ else if (!same(next, a))
336
+ forced = false;
337
+ }
338
+ if (!next || (!forced && --guesses < 0))
339
+ return undefined;
340
+ trace.push(request);
341
+ st = next;
342
+ }
343
+ return undefined;
344
+ }
345
+ // The deeper goals as one growing goal, for one CDCL search kept from depth to depth (kernel/cdcl.ts's cdclSession):
346
+ // each step's hypotheses written once, in names that stay (the state after step j as n~j, the j-th request as input@j),
347
+ // relaxed and folded as above (each name of the step a constant or another name fixes put in, never one of an earlier
348
+ // step's), and each depth's last state breaking a law a hypothesis of its own, `act@k >= 1 or <the law broken at ~k>`,
349
+ // assumed by act@k <= 0 at depth k and set aside (act@k >= 1) at depth k + 1. Every clause the search learns is then a
350
+ // consequence of the hypotheses it has, at every later depth too. For machines whose goals read no function and no
351
+ // flag (whose kernel goals carry no fact this one would lack); the others, and a relaxed model the interpreter refuses,
352
+ // are asked as before, depth by depth.
353
+ function unrolled(m, laws) {
354
+ const goal = { name: 'a bounded run', hyps: [] }, sub = {}, defs = [];
355
+ const v = (name) => ({ op: 'var', name }), K = (value) => ({ op: 'const', value });
356
+ const stateAt = (j) => Object.fromEntries(Object.keys(m.state).map(n => [n, j === 0 ? m.state[n] : v(`${n}~${j}`)]));
357
+ const put = (c) => simpC(substC(c, { vars: sub, maps: {}, flags: {} }));
358
+ let k = 0, dead = false;
359
+ const session = cdclSession(goal, new Map(), { model: true });
360
+ // The cone of influence: the state values the laws, the assumption or the precondition read, and those the updates of
361
+ // these read, again until no more; the others' terms are left out at every step (no hypothesis reads them, and the
362
+ // interpreter takes the run's own values).
363
+ const live = new Set(), names = (xs) => [...occurrences(xs).keys()].filter(n => n in m.state);
364
+ const todo = names([...laws.map(l => l.holds), ...(m.assume ? [m.assume] : []), ...(m.pre ? [m.pre] : [])]);
365
+ while (todo.length) {
366
+ const n = todo.pop();
367
+ if (live.has(n))
368
+ continue;
369
+ live.add(n);
370
+ todo.push(...names([m.step.state?.[n] ?? v(n)]));
371
+ }
372
+ // Step j's hypotheses: its request allowed, each state value its term; folded; undefined where they can't hold.
373
+ const step = (j) => {
374
+ const before = stateAt(j - 1), inputs = Object.fromEntries(m.inputs.map(i => [i, v(j === 1 ? i : `${i}@${j}`)]));
375
+ const at = { vars: { ...before, ...inputs }, maps: {}, flags: {} };
376
+ const own = new Set([...Object.values(inputs).map(e => e.name), ...Object.keys(m.state).map(n => `${n}~${j}`)]);
377
+ const raw = [...(j === 1 && m.pre ? [m.pre] : []), ...(m.assume ? [substC(m.assume, at)] : []), ...[...live].map((n) => ({ op: '=', a: v(`${n}~${j}`), b: substE(m.step.state?.[n] ?? v(n), at) }))];
378
+ let cs = (useRelax ? relax(raw) : undefined) ?? raw;
379
+ for (;;) {
380
+ cs = cs.map(put).flatMap(top);
381
+ if (cs.some(isFalse))
382
+ return undefined;
383
+ cs = cs.filter(c => !isTrue(c));
384
+ // (each round, every name of this step that an equation gives a constant or another name, put in at once)
385
+ const now = {}, used = new Set();
386
+ for (const c of cs) {
387
+ if (c.op !== '=')
388
+ continue;
389
+ const free = (x) => x.op === 'var' && own.has(x.name) && !(x.name in sub) && !(x.name in now);
390
+ const [n, e] = free(c.a) && (c.b.op === 'const' || (c.b.op === 'var' && c.b.name !== c.a.name && !(c.b.name in now))) ? [c.a.name, c.b] : free(c.b) && c.a.op === 'const' ? [c.b.name, c.a] : [];
391
+ if (n === undefined)
392
+ continue;
393
+ now[n] = e;
394
+ used.add(c);
395
+ }
396
+ if (!Object.keys(now).length)
397
+ return cs;
398
+ // (a name another of this round's names is: the end of the chain)
399
+ for (const n of Object.keys(now)) {
400
+ let e = now[n];
401
+ for (let i = 0; e.op === 'var' && now[e.name] && i < 64; i++)
402
+ e = now[e.name];
403
+ now[n] = e;
404
+ }
405
+ for (const [n, e] of Object.entries(now)) {
406
+ sub[n] = e;
407
+ defs.push([n, e]);
408
+ }
409
+ for (const x of Object.keys(sub)) {
410
+ const e = sub[x];
411
+ if (e.op === 'var' && e.name in now)
412
+ sub[x] = now[e.name];
413
+ }
414
+ cs = cs.filter(c => !used.has(c));
415
+ }
416
+ };
417
+ // The next depth: its hypotheses added, and asked; the query folded to false is refuted with no search.
418
+ const next = (b, wall) => {
419
+ k++;
420
+ if (dead)
421
+ return { k, out: 'impossible' };
422
+ const cs = step(k);
423
+ if (!cs) {
424
+ dead = true;
425
+ return { k, out: 'impossible' };
426
+ }
427
+ if (k > 1)
428
+ goal.hyps.push({ op: '<=', a: K(1), b: v(`act@${k - 1}`) });
429
+ goal.hyps.push(...cs);
430
+ const query = put(substC({ op: 'not', x: { op: 'and', xs: laws.map(l => l.holds) } }, { vars: stateAt(k), maps: {}, flags: {} }));
431
+ if (isFalse(query))
432
+ return { k, out: 'refuted' };
433
+ goal.hyps.push({ op: 'or', xs: [{ op: '<=', a: K(1), b: v(`act@${k}`) }, query] });
434
+ return { k, out: session.run(b, wall, { [`act@${k}`]: 1 }) };
435
+ };
436
+ return { next, defs };
437
+ }
438
+ export function findBoundedRun(m, laws, opts) {
439
+ if (!laws.length || !bmcFits(m, laws))
440
+ return undefined;
441
+ const last = Math.min(64, opts.depth ?? 64);
442
+ // A forced run first, within forcedShare of the budget (as wall time: it is the compiled rule's, not the kernel's).
443
+ const now = performance.now(), end = Math.min(opts.wall ?? Infinity, now + opts.ms);
444
+ const forced = forcedRun(m, laws, { steps: forcedSteps, wall: now + forcedShare * (end - now) });
445
+ if (forced)
446
+ return forced;
447
+ return counted(bmcRate, () => {
448
+ const until = clock() + opts.ms;
449
+ const inc = useInc && !(opts.from && opts.from > 1) && !Object.keys(m.fns ?? {}).length && !Object.keys(m.step.flags ?? {}).length ? unrolled(m, laws) : undefined;
450
+ for (let k = opts.from ?? 1; k <= last && clock() < until && !(opts.wall !== undefined && performance.now() > opts.wall); k++) {
451
+ const t0 = clock();
452
+ if (inc) {
453
+ const { out } = inc.next({ nodes: 0, until }, opts.wall);
454
+ if (out === 'impossible') {
455
+ opts.progress?.(k, 'refuted', Math.round(clock() - t0));
456
+ return undefined;
457
+ }
458
+ if (out === 'refuted' || 'tree' in out || out.why === REFUTED) {
459
+ opts.progress?.(k, 'refuted', Math.round(clock() - t0));
460
+ continue;
461
+ }
462
+ if (out.stuck !== 'sat' || !out.witness) {
463
+ opts.progress?.(k, 'unknown', Math.round(clock() - t0));
464
+ return undefined;
465
+ }
466
+ const run = runOf(m, putBack(m, out.witness, inc.defs), k), broken = replay(m, laws, run);
467
+ if (broken) {
468
+ opts.progress?.(k, 'sat', Math.round(clock() - t0));
469
+ return { law: broken.law, witness: broken.witness, depth: broken.steps, params: run.params, trace: run.trace.slice(0, broken.steps) };
470
+ }
471
+ // (a model the interpreter refuses: the goal itself asked at this depth, below)
472
+ }
473
+ let goal;
474
+ try {
475
+ goal = bmcGoal(m, laws, k);
476
+ }
477
+ catch {
478
+ return undefined;
479
+ }
480
+ const f = fixed(goal.hyps);
481
+ if (!f) {
482
+ opts.progress?.(k, 'refuted', Math.round(clock() - t0));
483
+ continue;
484
+ }
485
+ // The goal asked (relaxed or as it is), reduced: refuted, or a run that breaks a law, or neither (undefined).
486
+ const ask = (hyps) => {
487
+ const r = reduce(hyps);
488
+ if (!r)
489
+ return 'refuted';
490
+ const out = growCdcl({ name: goal.name, hyps: r.hyps }, new Map(), { nodes: 0, until }, { model: true, ...(opts.wall !== undefined ? { wall: opts.wall } : {}) });
491
+ if ('tree' in out || out.why === REFUTED)
492
+ return 'refuted';
493
+ if (out.stuck !== 'sat' || !out.witness)
494
+ return 'unknown';
495
+ const run = runOf(m, putBack(m, { ...out.witness, ...f.fixed }, r.defs), k), broken = replay(m, laws, run);
496
+ return broken ? { law: broken.law, witness: broken.witness, depth: broken.steps, params: run.params, trace: run.trace.slice(0, broken.steps) } : 'sat';
497
+ };
498
+ const relaxed = useRelax && !inc ? relax(f.hyps) : undefined;
499
+ let got = relaxed ? ask(relaxed) : 'sat';
500
+ if (got === 'sat')
501
+ got = ask(f.hyps);
502
+ opts.progress?.(k, typeof got === 'string' ? got : 'sat', Math.round(clock() - t0));
503
+ if (got === 'refuted')
504
+ continue;
505
+ return typeof got === 'string' ? undefined : got;
506
+ }
507
+ return undefined;
508
+ });
509
+ }
@@ -1,3 +1,3 @@
1
1
  import type { Constraint, Step } from './solver.js';
2
- export declare function checkRefutation(constraints: Constraint[], steps: Step[]): boolean;
2
+ export declare function checkRefutation(constraints: Constraint[], steps: Step[], integral?: boolean): boolean;
3
3
  export declare function checkWitness(constraints: Constraint[], witness: Record<string, number>): boolean;