gdp-wired 0.22.0 → 0.23.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.
@@ -10,15 +10,22 @@
10
10
  // or …), and where a cell holds one value
11
11
  // - Houdini on the runs' neighbors: a reached state moved a little that every candidate alive and every law allows,
12
12
  // stepped; a candidate its step breaks is in no inductive set of them, so it is dropped
13
- // - the kernel: the laws with the candidates chosen so far, proven one law at a time; when a goal is stuck at a step,
14
- // its witness is a counterexample to induction, so the candidate that rules it out (and the most of those seen) is
15
- // added; a chosen candidate that nothing supports, or that makes a proof slow, is dropped; the set proven as a whole
13
+ // - the join: per control state (the choice, loc, and a few yes/nos), the samples' affine hull (its equalities, exact)
14
+ // and each direction's largest value (each value up and down, pairs where there are few, the rule's own comparisons);
15
+ // Houdini on the cone of the caller's laws: each goal proven with as little of that set assumed as will do (none,
16
+ // then the forms a counterexample breaks, as IC3's relative induction, then all), a counterexample the whole set
17
+ // allows joined in (the hull grows to hold it, a bound rises to the next of the rule's constants, then goes), one to a
18
+ // caller's law ruled out by a candidate; every goal of the cone proven, the cone is the answer
19
+ // - the kernel (where the join proves nothing, as it was): the laws with the candidates chosen so far, proven one law
20
+ // at a time; when a goal is stuck at a step, its witness is a counterexample to induction, so the candidate that
21
+ // rules it out (and the most of those seen) is added; a chosen candidate that nothing supports, or that makes a proof slow, is dropped; the set proven as a whole
16
22
  // is the answer, after each chosen candidate the proof doesn't need is taken out again
17
23
  import { quietly } from "./cyclic.js";
18
24
  import { any, atMost, divisorsIn, evalC, get, interpret, machineTerms, modName, n, not, plus, same, times, withArithmetic, x } from "./machine.js";
19
25
  import { proveRule, proveSteps } from "./dsl.js";
20
26
  import { allowed, watch } from "./watch.js";
21
- import { proveLaw, proveLaws, proveStepLaws, withDeadline } from "../kernel/prove.js";
27
+ import { clock, counted, grow, proveLaw, proveLaws, proveStepLaws, usedHyps, withDeadline } from "../kernel/prove.js";
28
+ import { obligations, substC } from "../kernel/kernel.js";
22
29
  import { work } from "./solver.js";
23
30
  const KEY = 'key$found', AT = '@', K = '#', SOME = 'k$found';
24
31
  // The counted clock's rates, units a millisecond: about the slowest tenth of what Modal's 1-vCPU containers do in each
@@ -32,6 +39,15 @@ export const inferRates = { tries: 100, rows: 10_000, evals: 10_000, watched: 10
32
39
  export const inferRuns = 16_000;
33
40
  // GDP_INFER_TRACE=1: each phase's wall time beside what it counted, to stderr (the calibration's numbers).
34
41
  const inferTrace = !!globalThis.process?.env?.GDP_INFER_TRACE;
42
+ // The join (below, after the candidates): GDP_JOIN=0 turns it off, for comparing. Its share of what is left of the
43
+ // search's budget; each kernel search's budget (counted, or wall time where timed), a request's 150 ms; the steps a walk
44
+ // from a joined state takes; pairs of values as directions up to 10 values; a bound raised twice at most, then dropped;
45
+ // equalities of at most 4 values, coefficients up to 1,000; at most 24 candidates beside the hull, 40 tried; yes/nos in
46
+ // the control state up to 7, and 128 of its values; a goal tried with 6 parts of the set before all of it, 2 forms added
47
+ // at a time.
48
+ const joinOn = globalThis.process?.env?.GDP_JOIN !== '0';
49
+ const joinShare = 0.6, joinQueryMs = 8000, joinRequestMs = 150, joinWalk = 8, joinPairs = 10, joinRaises = 2, joinSparse = 4, joinCoef = 1000;
50
+ const joinExtras = 24, joinTries = 40, joinBits = 7, joinKeys = 128, joinAttempts = 6, joinAdd = 2;
35
51
  const seeded = (seed) => { let s = seed; return k => { s = (s * 1103515245 + 12345) % 2 ** 31; return Math.floor(s / 2 ** 31 * k); }; };
36
52
  const isRule = (t) => typeof t.kindsOfState === 'function';
37
53
  const gcd = (a, b) => (b === 0 ? Math.abs(a) : gcd(b, a % b));
@@ -119,6 +135,96 @@ const keyValue = (cell, w) => {
119
135
  }
120
136
  return value;
121
137
  };
138
+ // The linear comparisons a machine's conditions make over the state alone (its assumption, its step's conditions and the
139
+ // laws), as coefficients over the atoms given (an integer atom's two parts with opposite coefficients): the directions
140
+ // a bound of the join may take beside the atoms' own.
141
+ function comparisons(m, laws, atoms, coords) {
142
+ const lin = (e, k, out) => {
143
+ if (e.op === 'const') {
144
+ out.set('1', (out.get('1') ?? 0) + k * e.value);
145
+ return true;
146
+ }
147
+ if (e.op === 'var') {
148
+ out.set(e.name, (out.get(e.name) ?? 0) + k);
149
+ return true;
150
+ }
151
+ if (e.op === 'add')
152
+ return lin(e.a, k, out) && lin(e.b, k, out);
153
+ return e.op === 'mul' && lin(e.a, k * e.k, out);
154
+ };
155
+ // A request's value that some step puts in a state variable as it is (a clause's head argument, say) stands for that
156
+ // variable: a comparison over the request then reads as one over the state it makes.
157
+ const inputTo = new Map();
158
+ const leaves = (e, to) => { if (e.op === 'var') {
159
+ if (m.inputs.includes(e.name) && !inputTo.has(e.name))
160
+ inputTo.set(e.name, to);
161
+ }
162
+ else if (e.op === 'if') {
163
+ leaves(e.then, to);
164
+ leaves(e.else, to);
165
+ } };
166
+ for (const [v, e] of Object.entries(m.step.state ?? {}))
167
+ leaves(e.op === 'sub' ? e.a : e, v);
168
+ const found = new Map();
169
+ const visitE = (e) => {
170
+ if (e.op === 'if') {
171
+ visitC(e.c);
172
+ visitE(e.then);
173
+ visitE(e.else);
174
+ }
175
+ else if (e.op === 'add' || e.op === 'sub' || e.op === 'min' || e.op === 'max' || e.op === 'prod') {
176
+ visitE(e.a);
177
+ visitE(e.b);
178
+ }
179
+ else if (e.op === 'mul')
180
+ visitE(e.a);
181
+ };
182
+ const visitC = (c) => {
183
+ if (c.op === 'and' || c.op === 'or') {
184
+ c.xs.forEach(visitC);
185
+ return;
186
+ }
187
+ if (c.op === 'not') {
188
+ visitC(c.x);
189
+ return;
190
+ }
191
+ if (c.op !== '<' && c.op !== '<=' && c.op !== '=')
192
+ return;
193
+ visitE(c.a);
194
+ visitE(c.b);
195
+ const l0 = new Map();
196
+ if (!lin(c.a, 1, l0) || !lin(c.b, -1, l0))
197
+ return;
198
+ const l = new Map();
199
+ for (const [v, k] of l0) {
200
+ const w = inputTo.get(v) ?? v;
201
+ l.set(w, (l.get(w) ?? 0) + k);
202
+ }
203
+ const coef = [];
204
+ for (const i of coords) {
205
+ const a = atoms[i], [pos, neg] = a.parts, cp = l.get(pos[0]) ?? 0;
206
+ if (neg && (l.get(neg[0]) ?? 0) !== -cp)
207
+ return;
208
+ if (cp)
209
+ coef.push([i, cp]);
210
+ l.delete(pos[0]);
211
+ if (neg)
212
+ l.delete(neg[0]);
213
+ }
214
+ l.delete('1');
215
+ if ([...l.values()].some(v => v !== 0) || coef.length < 2)
216
+ return;
217
+ const g = coef.reduce((acc, [, cc]) => gcd(acc, cc), 0), t = coef.map(([i, cc]) => [i, cc / g]);
218
+ if (t[0][1] < 0)
219
+ t.forEach(p => { p[1] = -p[1]; });
220
+ found.set(JSON.stringify(t), t);
221
+ };
222
+ if (m.assume)
223
+ visitC(m.assume);
224
+ Object.values(m.step.state ?? {}).forEach(visitE);
225
+ laws.forEach(l => visitC(l.holds));
226
+ return [...found.values()];
227
+ }
122
228
  export function inferLaws(target, laws, stepLaws = [], opts = {}) {
123
229
  return quietly(() => withDeadline(performance.now() + (opts.ms ?? 20000), () => inferLawsSearch(target, laws, stepLaws, opts)));
124
230
  }
@@ -467,6 +573,11 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
467
573
  return only.values.filter(v => c * v <= f.d);
468
574
  };
469
575
  const textOf = (f) => {
576
+ const atText = (g) => `${nameOf(g.atom)} is ${shownValue(g.atom, g.value)}`;
577
+ if (f.never)
578
+ return `never ${f.never.map(atText).join(' and ')}`;
579
+ if (f.also)
580
+ return `${f.also.map(atText).join(' and ')} → ${textOf({ ...f, also: undefined })}`;
470
581
  if (f.unreachable)
471
582
  return `${nameOf(f.unreachable.atom)} is never ${shownValue(f.unreachable.atom, f.unreachable.value)}`;
472
583
  if (f.cong)
@@ -492,6 +603,10 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
492
603
  const e = part(atoms[i], atoms[i].parts[0][0]), mo = modeOf(i), lastValue = mo?.bool ? 1 : mo?.choice ? mo.choice.length - 1 : undefined;
493
604
  return value === 0 ? atMost(n(1), e) : value === lastValue ? atMost(e, n(value - 1)) : not(same(e, n(value)));
494
605
  };
606
+ if (f.never)
607
+ return any(...f.never.map(g => notAt(g.atom, g.value)));
608
+ if (f.also)
609
+ return any(...f.also.map(g => notAt(g.atom, g.value)), condOf({ ...f, also: undefined }));
495
610
  if (f.unreachable)
496
611
  return notAt(f.unreachable.atom, f.unreachable.value);
497
612
  if (f.mod) {
@@ -514,7 +629,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
514
629
  };
515
630
  // The builder call, for a rule whose atoms are its own variables (naturals, or integers alone).
516
631
  const sourceOf = (f, text) => {
517
- if (!rule || f.when || f.mod)
632
+ if (!rule || f.when || f.mod || f.also || f.never)
518
633
  return undefined;
519
634
  const used = [...new Set([...f.coef.map(([i]) => i), ...(f.guard ? ['keyNot' in f.guard ? f.guard.keyNot : f.guard.atom] : []), ...(f.unreachable ? [f.unreachable.atom] : [])])];
520
635
  const ints = f.coef.filter(([i]) => atoms[i].int).length;
@@ -560,6 +675,10 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
560
675
  const holdsRow = (f, env) => {
561
676
  used.evals++;
562
677
  const vs = valuesOf(env);
678
+ if (f.never)
679
+ return f.never.some(g => vs[g.atom] !== g.value);
680
+ if (f.also?.some(g => vs[g.atom] !== g.value))
681
+ return true;
563
682
  if (f.unreachable)
564
683
  return vs[f.unreachable.atom] !== f.unreachable.value;
565
684
  if (f.cong) {
@@ -782,6 +901,400 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
782
901
  // A stride may skip a sample that breaks a form: each is checked again at every sample in its guard.
783
902
  return out.sort((x, y) => x.size - y.size).slice(0, 2000).filter(f => inGuard.every(j => holdsRow(f, rowsS[j]))).slice(0, 400);
784
903
  };
904
+ // --- the join: an inductive invariant from the samples' hull (experiment: GDP_JOIN=1) -------------------------------------
905
+ // Per value of the choice (loc), the affine hull of the samples there (its equalities, exact) and the largest value of
906
+ // each direction (each value up and down, and pairs of them where there are few); the kernel's counterexample to the
907
+ // induction of them all, replayed, is a state they allow whose successor they don't: it is joined in (the hull grows to
908
+ // hold it, a bound rises to the next of the rule's constants, past three rises a bound is dropped), and so are the
909
+ // states short walks from it reach, until the kernel proves them inductive. The caller's laws are then proven with
910
+ // them assumed, and what their proofs read (and what those read, in turn) is the answer.
911
+ const pool0 = pool.slice(), ctis0 = ctis.length;
912
+ if (joinOn && !mapNames.length && NS)
913
+ try {
914
+ const jT0 = performance.now(), jUntil = Math.min(until, now() + (until - now()) * joinShare);
915
+ // The control state: the choice (loc) and, where they are few, the yes/nos (a program counter in bits), each of its
916
+ // values reached a part of its own.
917
+ const jChoice = modes.find(mo => mo.choice && !atoms[mo.atom].cell), bits = modes.filter(mo => mo.bool && !atoms[mo.atom].cell && !atoms[mo.atom].param);
918
+ const locsReached = jChoice ? new Set(valsS[jChoice.atom]).size : 1;
919
+ const keyModes = [...(jChoice ? [jChoice] : []), ...(bits.length && bits.length <= joinBits && locsReached * 2 ** bits.length <= joinKeys ? bits : [])];
920
+ const keyAtoms = keyModes.map(mo => mo.atom), coords = plain.filter(i => !keyAtoms.includes(i)), CN = coords.length;
921
+ const dirs = [];
922
+ for (const i of coords)
923
+ dirs.push([[i, 1]], [[i, -1]]);
924
+ if (CN <= joinPairs)
925
+ for (const [a2, i] of coords.entries())
926
+ for (const j of coords.slice(a2 + 1))
927
+ for (const [c1, c2] of [[1, 1], [1, -1], [-1, 1], [-1, -1]])
928
+ dirs.push([[i, c1], [j, c2]]);
929
+ // and the rule's own comparisons over the state (a guard, the query's condition): each as a direction, both ways
930
+ {
931
+ const known = new Set(dirs.map(t => JSON.stringify(t)));
932
+ for (const t of comparisons(m, laws, atoms, coords))
933
+ for (const u of [t, t.map(([i, c]) => [i, -c])]) {
934
+ const k2 = JSON.stringify(u);
935
+ if (!known.has(k2) && dirs.length < 2 * CN + 4 * joinPairs * joinPairs + 64) {
936
+ known.add(k2);
937
+ dirs.push(u);
938
+ }
939
+ }
940
+ }
941
+ // Widening with thresholds: a bound a counterexample breaks rises to the next of the rule's constants (their sums and
942
+ // products the first time, the constants alone after), and past that it is dropped.
943
+ const fine = bounds, coarse = [...new Set([0, ...consts.flatMap(k => [k, -k])])].sort((p2, q2) => p2 - q2);
944
+ const groups = new Map();
945
+ const bgcd = (a2, b2) => { a2 = a2 < 0n ? -a2 : a2; b2 = b2 < 0n ? -b2 : b2; while (b2)
946
+ [a2, b2] = [b2, a2 % b2]; return a2; };
947
+ const normal = (e) => { let g2 = 0n; for (const x2 of e)
948
+ g2 = bgcd(g2, x2); if (g2 > 1n)
949
+ for (let k = 0; k < e.length; k++)
950
+ e[k] /= g2; const lead = e.find(x2 => x2 !== 0n); if (lead !== undefined && lead < 0n)
951
+ for (let k = 0; k < e.length; k++)
952
+ e[k] = -e[k]; return e; };
953
+ const dirValue = (t, vs) => { let v = 0; for (const [i, c] of t)
954
+ v += c * vs[i]; return v; };
955
+ const residual = (e, vs) => { let r = e[CN]; for (let k = 0; k < CN; k++)
956
+ if (e[k])
957
+ r += e[k] * BigInt(vs[coords[k]]); return r; };
958
+ let joins = 0;
959
+ const join = (g, vs, widen) => {
960
+ let grp = groups.get(g);
961
+ if (!grp) {
962
+ grp = { eqs: coords.map((i, k) => { const e = Array.from({ length: CN + 1 }, () => 0n); e[k] = 1n; e[CN] = -BigInt(vs[i]); return e; }), hi: dirs.map(t => dirValue(t, vs)), raised: dirs.map(() => 0) };
963
+ groups.set(g, grp);
964
+ return;
965
+ }
966
+ const rs = grp.eqs.map(e => residual(e, vs)), nz = rs.flatMap((r, k) => (r !== 0n ? [k] : []));
967
+ if (nz.length) {
968
+ const piv = nz.reduce((p2, k) => (grp.eqs[k].filter(x2 => x2 !== 0n).length < grp.eqs[p2].filter(x2 => x2 !== 0n).length ? k : p2)), pe = grp.eqs[piv], pr = rs[piv];
969
+ for (const k of nz)
970
+ if (k !== piv)
971
+ grp.eqs[k] = normal(grp.eqs[k].map((x2, q2) => pr * x2 - rs[k] * pe[q2]));
972
+ grp.eqs.splice(piv, 1);
973
+ }
974
+ dirs.forEach((t, k) => {
975
+ const v = dirValue(t, vs);
976
+ if (v <= grp.hi[k])
977
+ return;
978
+ if (!widen) {
979
+ grp.hi[k] = v;
980
+ return;
981
+ }
982
+ const n2 = ++grp.raised[k], up = (n2 === 1 ? fine : coarse).find(b2 => b2 >= v);
983
+ grp.hi[k] = n2 > joinRaises || up === undefined ? Infinity : up;
984
+ });
985
+ joins++;
986
+ };
987
+ const keyOf = (vs) => keyAtoms.map(i => vs[i]).join(',');
988
+ const combos = keyModes.reduce((acc, mo) => acc.flatMap(c => mo.values.map(v => [...c, v])), [[]]);
989
+ for (let j = 0; j < NS; j++)
990
+ join(keyOf(valsS.map(col => col[j])), valsS.map(col => col[j]), false);
991
+ const formsNow = () => {
992
+ const out = [], seenT = new Set();
993
+ const push = (f) => { const t = textOf(f); if (!seenT.has(t) && !names.has(t)) {
994
+ seenT.add(t);
995
+ out.push(f);
996
+ } };
997
+ // (a choice's value no state reached: one form, whatever the yes/nos)
998
+ const reachedFirst = new Set([...groups.keys()].map(k2 => k2.split(',')[0]));
999
+ for (const combo of combos) {
1000
+ if (combo.length > 1 && !reachedFirst.has(String(combo[0]))) {
1001
+ if (combo.slice(1).every(v => v === 0))
1002
+ push({ coef: [], d: 0, cells: false, unreachable: { atom: keyAtoms[0], value: combo[0] }, size: 1 });
1003
+ continue;
1004
+ }
1005
+ const ats = combo.map((value, k) => ({ atom: keyAtoms[k], value })), grp = groups.get(combo.join(','));
1006
+ const guard = ats.length ? { guard: ats[0], ...(ats.length > 1 ? { also: ats.slice(1) } : {}) } : {};
1007
+ if (!grp) {
1008
+ if (ats.length)
1009
+ push({ coef: [], d: 0, cells: false, ...(ats.length > 1 ? { never: ats } : { unreachable: ats[0] }), size: 1 });
1010
+ continue;
1011
+ }
1012
+ for (const e of grp.eqs) {
1013
+ const coef = [];
1014
+ for (let k = 0; k < CN; k++)
1015
+ if (e[k])
1016
+ coef.push([coords[k], Number(e[k])]);
1017
+ const d = -Number(e[CN]);
1018
+ if (!coef.length || coef.length > joinSparse || coef.some(([, c]) => Math.abs(c) > joinCoef) || !Number.isSafeInteger(d))
1019
+ continue;
1020
+ push({ coef, d, cells: false, ...guard, size: 0 });
1021
+ push({ coef: coef.map(([i, c]) => [i, -c]), d: -d, cells: false, ...guard, size: 0 });
1022
+ }
1023
+ dirs.forEach((t, k) => {
1024
+ const hi = grp.hi[k];
1025
+ if (!Number.isFinite(hi))
1026
+ return;
1027
+ // constant on the hull (the equalities say it), or a yes/no's own range
1028
+ const neg = dirs.findIndex(u => u.length === t.length && u.every(([i, c], q2) => i === t[q2][0] && c === -t[q2][1]));
1029
+ if (neg >= 0 && grp.hi[neg] === -hi)
1030
+ return;
1031
+ if (t.length === 1 && modeOf(t[0][0])?.bool && (t[0][1] > 0 ? hi >= 1 : hi >= 0))
1032
+ return;
1033
+ push({ coef: t, d: hi, cells: false, ...guard, size: 0 });
1034
+ });
1035
+ }
1036
+ return out;
1037
+ };
1038
+ let rounds = 0, why = '', set = [];
1039
+ const params0 = {};
1040
+ // Beside the hull, forms of the candidates' that rule out a counterexample to the caller's laws (a state the set
1041
+ // allows whose successor breaks one): Houdini's, dropped when a counterexample's successor breaks them.
1042
+ const extras = [], negs = [], reached = [];
1043
+ let tried = 0;
1044
+ const breaks = (params, st) => laws.some(l => { try {
1045
+ return !evalC(l.holds, params, st, m);
1046
+ }
1047
+ catch {
1048
+ return true;
1049
+ } });
1050
+ // A request the rule allows at a state, found by the kernel (a model of the assumption there), some inputs fixed at
1051
+ // random first; the walks from a counterexample take these where random requests aren't allowed.
1052
+ const flagless = !Object.keys(m.step.flags ?? {}).length && !!m.assume;
1053
+ // A kernel search's budget: wall time where the search is timed, else counted in the kernel's work (inferRates.work
1054
+ // a millisecond), so that what it finds doesn't depend on the machine.
1055
+ const budgeted = (ms2, f) => (timed ? f(performance.now() + Math.max(200, Math.min(ms2, wallUntil - performance.now())))
1056
+ : counted(inferRates.work, () => f(clock() + ms2)));
1057
+ const requestAt = (params, st) => {
1058
+ const vars = {};
1059
+ for (const [v, val] of Object.entries({ ...params, ...st.scalars }))
1060
+ vars[v] = n(val);
1061
+ for (let tries = 0; tries < 2; tries++) {
1062
+ const fix = [];
1063
+ if (tries === 0)
1064
+ for (const i of m.inputs)
1065
+ if (rand(3) === 0)
1066
+ fix.push(same(x(i), n([0, 1, 2, ...Object.values(st.scalars)][rand(3 + scalars.length)])));
1067
+ const o = budgeted(joinRequestMs, until2 => grow({ name: 'a request', hyps: [substC(m.assume, { vars, maps: {}, flags: {} }), ...fix] }, new Map(), { nodes: 0, until: until2, units: false }));
1068
+ if (!('tree' in o) && o.stuck === 'sat' && o.witness)
1069
+ return Object.fromEntries(m.inputs.map(i => [i, o.witness[i] ?? 0]));
1070
+ }
1071
+ return undefined;
1072
+ };
1073
+ // Houdini on the cone of the caller's laws: each goal proven with the whole set assumed, beginning with the caller's
1074
+ // laws, then each form their trees read (usedHyps), breadth first; a proof stands while every form it read is still
1075
+ // in the set (the set only weakens). A goal's counterexample is a state the set allows: its successor is joined in
1076
+ // (or, breaking a caller's law, a candidate that rules the state out is added). Every goal of the cone proven, the
1077
+ // cone is inductive with the caller's laws, and it is the answer.
1078
+ const stood = new Map(), blocked = new Set(), callers = new Set(laws.map(l => l.name));
1079
+ let cone = [], dropped = 0;
1080
+ // A state reached from one the set allows: joined in, and every extra false there dropped.
1081
+ const reach = (p2) => {
1082
+ if (reached.length < 2000)
1083
+ reached.push(p2);
1084
+ const vs = valuesOf(p2.scalar);
1085
+ join(keyOf(vs), vs, true);
1086
+ for (let k = extras.length - 1; k >= 0; k--)
1087
+ if (!holdsAt(extras[k], p2)) {
1088
+ const f = extras[k];
1089
+ extras.splice(k, 1);
1090
+ pool = pool.filter(g2 => g2 !== f);
1091
+ dropped++;
1092
+ }
1093
+ };
1094
+ // A goal's step with these forms assumed (beside the caller's laws and the kinds'): its tree and the forms it read, or
1095
+ // the kernel's model.
1096
+ const stepWith = (name, form, ctx) => {
1097
+ const ctxLaws = [...ctx, ...(form ? [form] : [])].map(lawFor), ls = [...given, ...ctxLaws], mm = forLaws(ctxLaws).m;
1098
+ const idx = form ? ls.length - 1 : ls.findIndex(l => l.name === name);
1099
+ const g = obligations(mm, ls, {}, idx)[1];
1100
+ const out = budgeted(joinQueryMs, until2 => grow(g, new Map(), { nodes: 0, until: until2 }));
1101
+ if (!('tree' in out))
1102
+ return { stuck: out.stuck, witness: out.stuck === 'sat' ? out.witness : undefined };
1103
+ const base0 = g.hyps.length - 1 - ls.length, used = [];
1104
+ for (const h of usedHyps(g, out.tree)) {
1105
+ const k = h - base0;
1106
+ if (k >= given.length && k < ls.length && k !== idx)
1107
+ used.push(ls[k].name);
1108
+ }
1109
+ return { used };
1110
+ };
1111
+ const stateOf = (w) => ({ params: m.params.length ? Object.fromEntries(m.params.map(p => [p, w[p] ?? 0])) : params0, st: { scalars: Object.fromEntries(scalars.map(v => [v, w[v] ?? 0])), maps: {} } });
1112
+ for (;;) {
1113
+ if (now() > jUntil || stop()) {
1114
+ why = 'time';
1115
+ break;
1116
+ }
1117
+ rounds++;
1118
+ set = [...formsNow(), ...extras].filter(f => !blocked.has(textOf(f)));
1119
+ const byText = new Map(set.map(f => [textOf(f), f]));
1120
+ for (const [t, used] of stood)
1121
+ if (used.some(u => !byText.has(u)))
1122
+ stood.delete(t);
1123
+ const order = laws.map(l => l.name), inOrder = new Set(order);
1124
+ let todo;
1125
+ for (let q = 0; q < order.length; q++) {
1126
+ const used = stood.get(order[q]);
1127
+ if (!used) {
1128
+ todo = order[q];
1129
+ break;
1130
+ }
1131
+ for (const u of used)
1132
+ if (!inOrder.has(u)) {
1133
+ inOrder.add(u);
1134
+ order.push(u);
1135
+ }
1136
+ }
1137
+ if (todo === undefined) {
1138
+ why = 'inductive';
1139
+ cone = order.filter(t => !callers.has(t)).map(t => byText.get(t));
1140
+ break;
1141
+ }
1142
+ // The goal with as little of the set assumed as will do (relative induction, as IC3 has it): first none of it; a
1143
+ // counterexample the set rules out adds to what is assumed the forms that rule it out that the cone already has
1144
+ // (else those proven before, else the smallest), a few at a time; past a few tries, or stuck, the whole set. A
1145
+ // counterexample the whole set allows is one to learn from.
1146
+ const todoForm = callers.has(todo) ? undefined : byText.get(todo);
1147
+ const inCone = new Set(order);
1148
+ const rank = (f) => (inCone.has(textOf(f)) ? 0 : stood.has(textOf(f)) ? 1 : 2) * 1000 + f.coef.length * 10 + (f.never || f.also ? 1 : 0);
1149
+ const whole = set.filter(f => f !== todoForm);
1150
+ let ctx = [], witness, lastStuck = '', qms = 0, settled = false;
1151
+ for (let attempt = 0; attempt <= joinAttempts; attempt++) {
1152
+ if (attempt === joinAttempts)
1153
+ ctx = whole;
1154
+ const tq = performance.now(), out = stepWith(todo, todoForm, ctx);
1155
+ qms += Math.round(performance.now() - tq);
1156
+ if ('used' in out) {
1157
+ stood.set(todo, out.used);
1158
+ opts.progress?.('join', { round: rounds, set: set.length, ms: qms, proven: todo.slice(0, 60), reads: out.used.length, ctx: ctx.length, attempt });
1159
+ settled = true;
1160
+ break;
1161
+ }
1162
+ lastStuck = out.stuck;
1163
+ if (!out.witness) {
1164
+ if (ctx === whole)
1165
+ break;
1166
+ ctx = whole;
1167
+ attempt = joinAttempts - 1;
1168
+ continue;
1169
+ }
1170
+ const w = out.witness, { params: pp0, st: st0 } = stateOf(w), pre0 = pointOf(pp0, st0);
1171
+ if (ctx === whole) {
1172
+ witness = w;
1173
+ break;
1174
+ }
1175
+ const ruling = whole.filter(f => !ctx.includes(f) && !holdsAt(f, pre0)).sort((p2, q2) => rank(p2) - rank(q2));
1176
+ if (!ruling.length) {
1177
+ witness = w;
1178
+ break;
1179
+ }
1180
+ ctx = [...ctx, ...ruling.slice(0, joinAdd)];
1181
+ }
1182
+ if (settled)
1183
+ continue;
1184
+ if (!witness) {
1185
+ opts.progress?.('join', { round: rounds, set: set.length, ms: qms, result: lastStuck, goal: todo.slice(0, 60) });
1186
+ if (callers.has(todo)) {
1187
+ why = `stuck ${lastStuck}`;
1188
+ break;
1189
+ }
1190
+ blocked.add(todo);
1191
+ continue;
1192
+ }
1193
+ const w = witness, { params, st } = stateOf(w);
1194
+ const input = Object.fromEntries(m.inputs.map(i => [i, w[i] ?? 0]));
1195
+ let post;
1196
+ try {
1197
+ post = run.step(params, st, input);
1198
+ }
1199
+ catch {
1200
+ post = undefined;
1201
+ }
1202
+ const pre = pointOf(params, st);
1203
+ // A model the interpreter reads otherwise (a remainder's term the kernel left free, a value past what doubles hold):
1204
+ // for a form, its goal is set aside; for a caller's law, the state is still one to rule out.
1205
+ const outside = !post || set.some(f => !holdsAt(f, pre));
1206
+ if (outside && !callers.has(todo)) {
1207
+ blocked.add(todo);
1208
+ opts.progress?.('join', { round: rounds, set: set.length, ms: qms, result: 'outside', goal: todo.slice(0, 60) });
1209
+ continue;
1210
+ }
1211
+ if (outside || breaks(params, post)) {
1212
+ // the caller's law broken from a state the set allows: a candidate false there and at every state reached, the
1213
+ // one false at the most such states (then the smallest), or one made from it (fromCti)
1214
+ negs.push(pre);
1215
+ ctis.push(pre);
1216
+ const pick = (fs) => { let bestF, score = -Infinity; for (const f of fs) {
1217
+ if (f.cells || f.cong || extras.includes(f) || blocked.has(textOf(f)) || holdsAt(f, pre) || !reached.every(p2 => holdsAt(f, p2)))
1218
+ continue;
1219
+ const sc = negs.reduce((k2, c) => k2 + (holdsAt(f, c) ? 0 : 1), 0) * 1000 - f.size;
1220
+ if (sc > score)
1221
+ (bestF = f, score = sc);
1222
+ } return bestF; };
1223
+ const room = extras.length < joinExtras && tried < joinTries;
1224
+ let next = room ? pick(pool) : undefined;
1225
+ if (!next && room) {
1226
+ const made = fromCti(pre);
1227
+ pool.push(...made);
1228
+ next = pick(made);
1229
+ }
1230
+ if (next)
1231
+ tried++;
1232
+ opts.progress?.('join', { round: rounds, set: set.length, ms: qms, target: next ? textOf(next).slice(0, 60) : 'none' });
1233
+ if (!next) {
1234
+ why = 'target';
1235
+ break;
1236
+ }
1237
+ extras.push(next);
1238
+ continue;
1239
+ }
1240
+ const after = post, postP = pointOf(params, after);
1241
+ // (a model the interpreter reads otherwise, a quotient's term the kernel left free, say: nothing to join, and the
1242
+ // goal is set aside)
1243
+ if (!set.some(f => !holdsAt(f, postP))) {
1244
+ blocked.add(todo);
1245
+ opts.progress?.('join', { round: rounds, set: set.length, ms: qms, result: 'no violation', goal: todo.slice(0, 60) });
1246
+ continue;
1247
+ }
1248
+ const j0 = joins, d0 = dropped;
1249
+ reach(postP);
1250
+ // short walks from the state joined: every state they reach is a successor of one the invariant holds at
1251
+ let walked = 0;
1252
+ for (let t = 0, at = after, misses = 0; t < joinWalk && misses < 3; t++) {
1253
+ let inp = randomInput(params, 4), next;
1254
+ try {
1255
+ if (allowed(m, run, params, at, inp))
1256
+ next = run.step(params, at, inp);
1257
+ }
1258
+ catch {
1259
+ next = undefined;
1260
+ }
1261
+ if (!next && flagless) {
1262
+ inp = requestAt(params, at);
1263
+ try {
1264
+ if (inp)
1265
+ next = run.step(params, at, inp);
1266
+ }
1267
+ catch {
1268
+ next = undefined;
1269
+ }
1270
+ }
1271
+ if (!next) {
1272
+ misses++;
1273
+ continue;
1274
+ }
1275
+ if (breaks(params, next))
1276
+ break;
1277
+ reach(pointOf(params, next));
1278
+ at = next;
1279
+ walked++;
1280
+ }
1281
+ opts.progress?.('join', { round: rounds, set: set.length, ms: qms, goal: todo.slice(0, 60), joins: joins - j0, walked, dropped: dropped - d0 });
1282
+ }
1283
+ opts.progress?.('join end', { rounds, set: set.length, why, cone: cone.length, ms: Math.round(performance.now() - jT0) });
1284
+ // (unproven, the search below begins as it would have: the candidates and the counterexamples as they were)
1285
+ if (why === 'inductive')
1286
+ chosen = cone;
1287
+ else {
1288
+ pool = pool0;
1289
+ ctis.length = ctis0;
1290
+ }
1291
+ }
1292
+ catch (e) {
1293
+ pool = pool0;
1294
+ ctis.length = ctis0;
1295
+ chosen = [];
1296
+ opts.progress?.('join failed', { why: String(e.message).slice(0, 120) });
1297
+ }
785
1298
  // The search proves one law at a time (proveLaw), each with every law assumed, and keeps what it proved while laws
786
1299
  // are only added (more laws assumed keep a proof a proof); dropping one forgets it all. Once every law is proven so,
787
1300
  // the set is proven as a whole, by the rule's own prover: that verdict is the answer.
@@ -0,0 +1,34 @@
1
+ import type { C, E } from './machine.js';
2
+ import { type Loop, type Recur } from '../kernel/kernel.js';
3
+ export type NeverEndsOptions = {
4
+ ms?: number;
5
+ seed?: number;
6
+ maxTurns?: number;
7
+ lassos?: boolean;
8
+ counted?: number;
9
+ };
10
+ export type NeverEndsVerdict = {
11
+ proven: boolean;
12
+ checked: boolean;
13
+ recur?: Recur;
14
+ by?: 'lasso' | 'policy lasso' | 'recurrent set';
15
+ why?: string;
16
+ lasso?: {
17
+ params: Record<string, number>;
18
+ stem: Record<string, number>[];
19
+ cycle: Record<string, number>[];
20
+ };
21
+ stats: {
22
+ runs: number;
23
+ turns: number;
24
+ policies: number;
25
+ rounds: number;
26
+ ms: number;
27
+ lassoTried: number;
28
+ goalSize: number;
29
+ };
30
+ };
31
+ export declare const simpE: (e: E) => E;
32
+ export declare const simpC: (c: C) => C;
33
+ export declare function goalSize(x: unknown): number;
34
+ export declare function findNeverEnds(l: Loop, opts?: NeverEndsOptions): NeverEndsVerdict;