gdp-wired 0.23.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 (40) hide show
  1. package/README.md +12 -2
  2. package/dist/core/bmc.d.ts +13 -2
  3. package/dist/core/bmc.js +390 -18
  4. package/dist/core/cycles.d.ts +23 -0
  5. package/dist/core/cycles.js +104 -54
  6. package/dist/core/data.d.ts +9 -0
  7. package/dist/core/data.js +352 -121
  8. package/dist/core/discover.js +8 -3
  9. package/dist/core/dsl.d.ts +7 -2
  10. package/dist/core/dsl.js +47 -9
  11. package/dist/core/extract-check.d.ts +77 -0
  12. package/dist/core/extract-check.js +785 -0
  13. package/dist/core/extract-ir.d.ts +139 -0
  14. package/dist/core/extract-ir.js +198 -0
  15. package/dist/core/extract-print.d.ts +30 -0
  16. package/dist/core/extract-print.js +426 -0
  17. package/dist/core/extract-read.d.ts +298 -0
  18. package/dist/core/extract-read.js +1298 -0
  19. package/dist/core/extract-shapes.d.ts +13 -0
  20. package/dist/core/extract-shapes.js +993 -0
  21. package/dist/core/extract-xstate.d.ts +34 -0
  22. package/dist/core/extract-xstate.js +320 -0
  23. package/dist/core/extract.d.ts +31 -0
  24. package/dist/core/extract.js +249 -0
  25. package/dist/core/kind.d.ts +30 -0
  26. package/dist/core/kind.js +81 -0
  27. package/dist/core/relation.js +7 -4
  28. package/dist/core/xstate.d.ts +6 -0
  29. package/dist/core/xstate.js +70 -12
  30. package/dist/kernel/cdcl.d.ts +10 -0
  31. package/dist/kernel/cdcl.js +291 -241
  32. package/dist/kernel/kernel.d.ts +15 -0
  33. package/dist/kernel/kernel.js +32 -0
  34. package/dist/kernel/prove.js +14 -3
  35. package/dist/kernel/reader.d.ts +14 -0
  36. package/dist/kernel/reader.js +102 -14
  37. package/dist/lean-kernel/emit.d.ts +28 -1
  38. package/dist/lean-kernel/emit.js +56 -15
  39. package/dist/lean-kernel/library.js +2 -1
  40. package/package.json +12 -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`),
@@ -455,7 +464,8 @@ The npm package is built from `core/`, `kernel/` and `lean-kernel/` alone; nothi
455
464
  ## Running
456
465
 
457
466
  The npm package is the library: the builders (`gdp-wired`), the runtimes (`gdp-wired/machine`), composition
458
- (`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
459
469
  inference (`gdp-wired/infer`), the
460
470
  Lean export (`gdp-wired/lean`), the kernel (`gdp-wired/kernel`), the prover (`gdp-wired/prove`), the derivation checker
461
471
  and solver (`gdp-wired/check`, `gdp-wired/solver`). Everything else here (examples, comparisons, the Lean twin, the GPU
@@ -1,4 +1,4 @@
1
- import { type C, type Law, type Machine, type Request } from './machine.js';
1
+ import { type C, type E, type Law, type Machine, type Request } from './machine.js';
2
2
  export type BoundedRun = {
3
3
  law: string;
4
4
  depth: number;
@@ -14,7 +14,7 @@ export type BmcOptions = {
14
14
  progress?: (depth: number, outcome: 'refuted' | 'sat' | 'unknown', ms: number) => void;
15
15
  };
16
16
  export declare function bmcFits(m: Machine, laws: Law[]): boolean;
17
- export declare const bmcRate = 200;
17
+ export declare const bmcRate = 250;
18
18
  export declare function bmcGoal(m: Machine, laws: Law[], k: number): {
19
19
  name: string;
20
20
  hyps: C[];
@@ -23,6 +23,12 @@ export declare function fixed(hyps: C[]): {
23
23
  hyps: C[];
24
24
  fixed: Record<string, number>;
25
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>;
26
32
  export declare function runOf(m: Machine, w: Record<string, number>, k: number): {
27
33
  params: Record<string, number>;
28
34
  trace: Request[];
@@ -35,4 +41,9 @@ export declare function replay(m: Machine, laws: Law[], run: {
35
41
  steps: number;
36
42
  witness: Record<string, number>;
37
43
  } | undefined;
44
+ export declare function forcedRun(m: Machine, laws: Law[], opts: {
45
+ steps: number;
46
+ wall: number;
47
+ guesses?: number;
48
+ }): BoundedRun | undefined;
38
49
  export declare function findBoundedRun(m: Machine, laws: Law[], opts: BmcOptions): BoundedRun | undefined;
package/dist/core/bmc.js CHANGED
@@ -8,14 +8,25 @@
8
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
9
  // runs out.
10
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
+ //
11
22
  // The budget is read off prove.ts's clock inside `counted` (the kernel's work, bmcRate units a millisecond), so the
12
23
  // search is the same on any machine; a wall-clock stop beside it (`wall`) is for callers under a wall-clock limit.
13
- import { evalC, interpret, isArithmetic, numbersOf } from "./machine.js";
14
- import { stepLawObligations, substC } from "../kernel/kernel.js";
24
+ import { evalC, evalE, interpret, isArithmetic, loadJs, numbersOf } from "./machine.js";
25
+ import { stepLawObligations, substC, substE } from "../kernel/kernel.js";
15
26
  import { clock, counted } from "../kernel/prove.js";
16
- import { REFUTED, growCdcl } from "../kernel/cdcl.js";
27
+ import { REFUTED, cdclSession, growCdcl } from "../kernel/cdcl.js";
17
28
  import { allowed } from "./watch.js";
18
- import { simpC } from "./nonterm.js";
29
+ import { simpC, simpE } from "./nonterm.js";
19
30
  // Machines whose runs the goals describe as they are: scalars only (no maps, history or carried maps), no quantified
20
31
  // flag, no function but division by a constant (whose facts fix its value); laws plain (no key, no "there exists").
21
32
  export function bmcFits(m, laws) {
@@ -30,10 +41,16 @@ export function bmcFits(m, laws) {
30
41
  return laws.every(l => !l.forall && !l.some?.length);
31
42
  }
32
43
  // The counted clock's rate here, units of the kernel's work a millisecond: the median of what Modal's 2-vCPU containers
33
- // did on the k-step goals of CHC-COMP's unsat LIA-Lin tasks (runs/unsat/bmc-only1: 1,462 depths past 200 ms, from 0 to
34
- // 340 units a ms at the 90th percentile, 190 at the median). The CDCL search counts its rows, which a goal of many atoms
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
35
47
  // and few rows a node keeps low, so a caller under a wall-clock limit gives a wall stop too.
36
- export const bmcRate = 200;
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';
37
54
  // The goal of depth k: a run of k steps from the start whose last state breaks a law.
38
55
  export function bmcGoal(m, laws, k) {
39
56
  const start = { op: 'and', xs: Object.entries(m.state).map(([n, e]) => ({ op: '=', a: { op: 'var', name: n }, b: e })) };
@@ -46,10 +63,10 @@ export function bmcGoal(m, laws, k) {
46
63
  // The goal with its constants put in: each name a hypothesis fixes (n = c, at the top) replaced by its value and the
47
64
  // terms folded (core/nonterm.ts's simpC), until none is left; the names fixed, with their values (a model's part), or
48
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;
49
69
  export function fixed(hyps) {
50
- const top = (c) => (c.op === 'and' ? c.xs.flatMap(top) : [c]);
51
- 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);
52
- const isTrue = (c) => c.op === '<=' && c.a.op === 'const' && c.b.op === 'const' && c.a.value <= c.b.value;
53
70
  const values = {};
54
71
  let cs = hyps.flatMap(top);
55
72
  for (;;) {
@@ -70,6 +87,128 @@ export function fixed(hyps) {
70
87
  cs = cs.filter(c => !isTrue(c));
71
88
  }
72
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
+ }
73
212
  // The run a model names: the params, the first request by plain names, the j-th (j >= 2) as input@j.
74
213
  export function runOf(m, w, k) {
75
214
  const at = (n) => Math.max(0, Math.round(w[n] ?? 0));
@@ -102,14 +241,235 @@ export function replay(m, laws, run) {
102
241
  throw e;
103
242
  }
104
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
+ }
105
438
  export function findBoundedRun(m, laws, opts) {
106
439
  if (!laws.length || !bmcFits(m, laws))
107
440
  return undefined;
108
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;
109
447
  return counted(bmcRate, () => {
110
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;
111
450
  for (let k = opts.from ?? 1; k <= last && clock() < until && !(opts.wall !== undefined && performance.now() > opts.wall); k++) {
112
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
+ }
113
473
  let goal;
114
474
  try {
115
475
  goal = bmcGoal(m, laws, k);
@@ -122,15 +482,27 @@ export function findBoundedRun(m, laws, opts) {
122
482
  opts.progress?.(k, 'refuted', Math.round(clock() - t0));
123
483
  continue;
124
484
  }
125
- const out = growCdcl({ name: goal.name, hyps: f.hyps }, new Map(), { nodes: 0, until }, { model: true, ...(opts.wall !== undefined ? { wall: opts.wall } : {}) });
126
- const refuted = !('tree' in out) && out.why === REFUTED;
127
- opts.progress?.(k, refuted ? 'refuted' : 'tree' in out ? 'refuted' : out.stuck, Math.round(clock() - t0));
128
- if (refuted || 'tree' in out)
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')
129
504
  continue;
130
- if (out.stuck !== 'sat' || !out.witness)
131
- return undefined;
132
- const run = runOf(m, { ...out.witness, ...f.fixed }, k), broken = replay(m, laws, run);
133
- return broken ? { law: broken.law, witness: broken.witness, depth: broken.steps, params: run.params, trace: run.trace.slice(0, broken.steps) } : undefined;
505
+ return typeof got === 'string' ? undefined : got;
134
506
  }
135
507
  return undefined;
136
508
  });
@@ -2,6 +2,8 @@ import type { C, E, Law, Machine, Request } from './machine.js';
2
2
  import type { Liveness, Loop, Tree } from '../kernel/kernel.js';
3
3
  import { type Cyclic, type Fact } from '../kernel/cyclic.js';
4
4
  import { type NodeSpec } from './cyclic.js';
5
+ import { type Lin } from './solver.js';
6
+ import { type Relation } from './relation.js';
5
7
  import type { StepLaw } from '../kernel/kernel.js';
6
8
  export type Claim = {
7
9
  name: string;
@@ -48,6 +50,21 @@ export declare function ranksOfRuns(vars: string[], points: Env[], edges: {
48
50
  }[];
49
51
  left: number;
50
52
  };
53
+ export declare function ranksOfCalls(nodes: string[][], points: {
54
+ node: number;
55
+ env: Env;
56
+ }[], edges: {
57
+ from: number;
58
+ to: number;
59
+ s: Env;
60
+ t: Env;
61
+ }[], ms?: number): {
62
+ comps: {
63
+ coef: Record<string, number>;
64
+ c: number;
65
+ }[][];
66
+ left: number;
67
+ };
51
68
  export declare function claimInstances(facts: Fact[], claim: Claim, depth?: number): NodeSpec['insts'];
52
69
  export declare function findCycles(facts: Fact[], claims: Claim[], opts?: CycleOptions): CycleVerdict;
53
70
  export declare function rankOfRelation(l: Loop, laws: Law[], until: number): {
@@ -57,6 +74,12 @@ export declare function rankOfRelation(l: Loop, laws: Law[], until: number): {
57
74
  } | {
58
75
  why: string;
59
76
  };
77
+ export declare function rankOfPaths(name: string, rel: Relation, until: number): {
78
+ forms: Lin[][];
79
+ values: number[];
80
+ } | {
81
+ why: string;
82
+ };
60
83
  export declare function rankWithInvariants(l: Loop, laws: Law[], until: number): {
61
84
  rank: E[];
62
85
  text: string;