gdp-wired 0.24.0 → 0.25.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.
@@ -12,6 +12,7 @@ export type InferOptions = {
12
12
  first?: Verdict;
13
13
  progress?: (phase: string, info: Record<string, number | string>) => void;
14
14
  existentials?: boolean;
15
+ minimize?: boolean;
15
16
  remainders?: boolean;
16
17
  };
17
18
  export type Found = {
@@ -13,20 +13,24 @@
13
13
  // - the join: per control state (the choice, loc, and a few yes/nos), the samples' affine hull (its equalities, exact)
14
14
  // and each direction's largest value (each value up and down, pairs where there are few, the rule's own comparisons);
15
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
16
+ // then the forms a counterexample breaks, as IC3's relative induction, then all), each asked first of the CDCL
17
+ // search for a model alone (a refutation's core: the forms it read), a counterexample the whole set allows joined in
18
+ // (the hull grows to hold it, a bound rises to the next of the rule's constants, then goes), one to a caller's law
19
+ // ruled out by a candidate or, where none does, by a cube blocked as IC3 blocks one (its control state and the
20
+ // bounds that keep the samples out, the literals its refutation's core read, its predecessors blocked first); every
21
+ // goal of the cone proven, the cone is the answer
19
22
  // - the kernel (where the join proves nothing, as it was): the laws with the candidates chosen so far, proven one law
20
23
  // at a time; when a goal is stuck at a step, its witness is a counterexample to induction, so the candidate that
21
24
  // 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
22
25
  // is the answer, after each chosen candidate the proof doesn't need is taken out again
23
26
  import { quietly } from "./cyclic.js";
24
- import { any, atMost, divisorsIn, evalC, get, interpret, machineTerms, modName, n, not, plus, same, times, withArithmetic, x } from "./machine.js";
27
+ import { all, any, atMost, divisorsIn, evalC, get, interpret, machineTerms, modName, n, not, plus, same, times, withArithmetic, x } from "./machine.js";
25
28
  import { proveRule, proveSteps } from "./dsl.js";
26
29
  import { allowed, watch } from "./watch.js";
27
30
  import { clock, counted, grow, proveLaw, proveLaws, proveStepLaws, usedHyps, withDeadline } from "../kernel/prove.js";
28
31
  import { obligations, substC } from "../kernel/kernel.js";
29
32
  import { work } from "./solver.js";
33
+ import { REFUTED, growCdcl } from "../kernel/cdcl.js";
30
34
  const KEY = 'key$found', AT = '@', K = '#', SOME = 'k$found';
31
35
  // The counted clock's rates, units a millisecond: about the slowest tenth of what Modal's 1-vCPU containers do in each
32
36
  // phase (`runs/modal/infer/after2`, GDP_INFER_TRACE=1: requests tried 85 a ms, rows 13,093, forms evaluated 11,240, the
@@ -48,6 +52,19 @@ const inferTrace = !!globalThis.process?.env?.GDP_INFER_TRACE;
48
52
  const joinOn = globalThis.process?.env?.GDP_JOIN !== '0';
49
53
  const joinShare = 0.6, joinQueryMs = 8000, joinRequestMs = 150, joinWalk = 8, joinPairs = 10, joinRaises = 2, joinSparse = 4, joinCoef = 1000;
50
54
  const joinExtras = 24, joinTries = 40, joinBits = 7, joinKeys = 128, joinAttempts = 6, joinAdd = 2;
55
+ // GDP_JOIN_CORE=0: the join's goals by the prover's trees alone, as before (else a model, or a refutation's core, of the
56
+ // CDCL search first, at a quarter of the goal's budget).
57
+ // GDP_JOIN_NEVERS=0: each control state no run reached a form of its own, as before (else one form for all of them,
58
+ // until it is first broken).
59
+ const joinNevers = globalThis.process?.env?.GDP_JOIN_NEVERS !== '0';
60
+ const joinNeversBreaks = 1;
61
+ const joinCore = globalThis.process?.env?.GDP_JOIN_CORE !== '0';
62
+ // Cubes blocked where no candidate rules a counterexample out (GDP_JOIN_CUBES=0: none): at most 48 in all, each tried 8
63
+ // times, its predecessors blocked first 3 deep, each query's budget 2 s (counted, or wall time where timed).
64
+ const joinCubes = globalThis.process?.env?.GDP_JOIN_CUBES !== '0';
65
+ const joinCubeMax = 48, joinCubeTries = 8, joinCubeDepth = 3, joinCubeMs = 2000;
66
+ // Once a cube is in the set, the join has 0.3 of what is left of its time (the search below the rest).
67
+ const joinCubeWindow = 0.3;
51
68
  const seeded = (seed) => { let s = seed; return k => { s = (s * 1103515245 + 12345) % 2 ** 31; return Math.floor(s / 2 ** 31 * k); }; };
52
69
  const isRule = (t) => typeof t.kindsOfState === 'function';
53
70
  const gcd = (a, b) => (b === 0 ? Math.abs(a) : gcd(b, a % b));
@@ -576,6 +593,10 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
576
593
  const atText = (g) => `${nameOf(g.atom)} is ${shownValue(g.atom, g.value)}`;
577
594
  if (f.never)
578
595
  return `never ${f.never.map(atText).join(' and ')}`;
596
+ if (f.nevers)
597
+ return `never ${f.nevers.map(c => c.map(atText).join(' and ')).join('; nor ')}`;
598
+ if (f.cube)
599
+ return `never ${f.cube.map(l => ('at' in l ? atText(l.at) : (({ l: a, r: b }) => `${a} <= ${b}`)(sides({ coef: l.lin.coef, d: l.lin.d, cells: false, size: 0 })))).join(' and ')}`;
579
600
  if (f.also)
580
601
  return `${f.also.map(atText).join(' and ')} → ${textOf({ ...f, also: undefined })}`;
581
602
  if (f.unreachable)
@@ -605,6 +626,10 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
605
626
  };
606
627
  if (f.never)
607
628
  return any(...f.never.map(g => notAt(g.atom, g.value)));
629
+ if (f.nevers)
630
+ return all(...f.nevers.map(c => any(...c.map(g => notAt(g.atom, g.value)))));
631
+ if (f.cube)
632
+ return not(all(...f.cube.map(l => ('at' in l ? same(part(atoms[l.at.atom], atoms[l.at.atom].parts[0][0]), n(l.at.value)) : condOf({ coef: l.lin.coef, d: l.lin.d, cells: false, size: 0 })))));
608
633
  if (f.also)
609
634
  return any(...f.also.map(g => notAt(g.atom, g.value)), condOf({ ...f, also: undefined }));
610
635
  if (f.unreachable)
@@ -629,7 +654,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
629
654
  };
630
655
  // The builder call, for a rule whose atoms are its own variables (naturals, or integers alone).
631
656
  const sourceOf = (f, text) => {
632
- if (!rule || f.when || f.mod || f.also || f.never)
657
+ if (!rule || f.when || f.mod || f.also || f.never || f.nevers || f.cube)
633
658
  return undefined;
634
659
  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] : [])])];
635
660
  const ints = f.coef.filter(([i]) => atoms[i].int).length;
@@ -677,6 +702,10 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
677
702
  const vs = valuesOf(env);
678
703
  if (f.never)
679
704
  return f.never.some(g => vs[g.atom] !== g.value);
705
+ if (f.nevers)
706
+ return f.nevers.every(c => c.some(g => vs[g.atom] !== g.value));
707
+ if (f.cube)
708
+ return !f.cube.every(l => ('at' in l ? vs[l.at.atom] === l.at.value : l.lin.coef.reduce((acc, [i, c]) => acc + c * vs[i], 0) <= l.lin.d));
680
709
  if (f.also?.some(g => vs[g.atom] !== g.value))
681
710
  return true;
682
711
  if (f.unreachable)
@@ -918,26 +947,29 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
918
947
  const locsReached = jChoice ? new Set(valsS[jChoice.atom]).size : 1;
919
948
  const keyModes = [...(jChoice ? [jChoice] : []), ...(bits.length && bits.length <= joinBits && locsReached * 2 ** bits.length <= joinKeys ? bits : [])];
920
949
  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))
950
+ // The directions over some values: each value up and down, pairs of them where there are few, and the rule's own
951
+ // comparisons over the state (a guard, the query's condition), each both ways.
952
+ const directions = (cs) => {
953
+ const out = [];
954
+ for (const i of cs)
955
+ out.push([[i, 1]], [[i, -1]]);
956
+ if (cs.length <= joinPairs)
957
+ for (const [a2, i] of cs.entries())
958
+ for (const j of cs.slice(a2 + 1))
959
+ for (const [c1, c2] of [[1, 1], [1, -1], [-1, 1], [-1, -1]])
960
+ out.push([[i, c1], [j, c2]]);
961
+ const known = new Set(out.map(t => JSON.stringify(t)));
962
+ for (const t of comparisons(m, laws, atoms, cs))
933
963
  for (const u of [t, t.map(([i, c]) => [i, -c])]) {
934
964
  const k2 = JSON.stringify(u);
935
- if (!known.has(k2) && dirs.length < 2 * CN + 4 * joinPairs * joinPairs + 64) {
965
+ if (!known.has(k2) && out.length < 2 * cs.length + 4 * joinPairs * joinPairs + 64) {
936
966
  known.add(k2);
937
- dirs.push(u);
967
+ out.push(u);
938
968
  }
939
969
  }
940
- }
970
+ return out;
971
+ };
972
+ const dirs = directions(coords);
941
973
  // Widening with thresholds: a bound a counterexample breaks rises to the next of the rule's constants (their sums and
942
974
  // products the first time, the constants alone after), and past that it is dropped.
943
975
  const fine = bounds, coarse = [...new Set([0, ...consts.flatMap(k => [k, -k])])].sort((p2, q2) => p2 - q2);
@@ -988,25 +1020,27 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
988
1020
  const combos = keyModes.reduce((acc, mo) => acc.flatMap(c => mo.values.map(v => [...c, v])), [[]]);
989
1021
  for (let j = 0; j < NS; j++)
990
1022
  join(keyOf(valsS.map(col => col[j])), valsS.map(col => col[j]), false);
1023
+ let neversBroken = 0;
991
1024
  const formsNow = () => {
992
1025
  const out = [], seenT = new Set();
993
1026
  const push = (f) => { const t = textOf(f); if (!seenT.has(t) && !names.has(t)) {
994
1027
  seenT.add(t);
995
1028
  out.push(f);
996
1029
  } };
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]));
1030
+ // (a choice's value no state reached: one form, whatever the yes/nos; the control states no state reached, one form
1031
+ // for all, where there are several: each alone needs the others to be inductive, a goal each where one does)
1032
+ const reachedFirst = new Set([...groups.keys()].map(k2 => k2.split(',')[0])), nev = [];
999
1033
  for (const combo of combos) {
1000
1034
  if (combo.length > 1 && !reachedFirst.has(String(combo[0]))) {
1001
1035
  if (combo.slice(1).every(v => v === 0))
1002
- push({ coef: [], d: 0, cells: false, unreachable: { atom: keyAtoms[0], value: combo[0] }, size: 1 });
1036
+ nev.push([{ atom: keyAtoms[0], value: combo[0] }]);
1003
1037
  continue;
1004
1038
  }
1005
1039
  const ats = combo.map((value, k) => ({ atom: keyAtoms[k], value })), grp = groups.get(combo.join(','));
1006
1040
  const guard = ats.length ? { guard: ats[0], ...(ats.length > 1 ? { also: ats.slice(1) } : {}) } : {};
1007
1041
  if (!grp) {
1008
1042
  if (ats.length)
1009
- push({ coef: [], d: 0, cells: false, ...(ats.length > 1 ? { never: ats } : { unreachable: ats[0] }), size: 1 });
1043
+ nev.push(ats);
1010
1044
  continue;
1011
1045
  }
1012
1046
  for (const e of grp.eqs) {
@@ -1033,6 +1067,13 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1033
1067
  push({ coef: t, d: hi, cells: false, ...guard, size: 0 });
1034
1068
  });
1035
1069
  }
1070
+ // (once broken, each its own form from then on, so that a state joined in changes only the forms that
1071
+ // read its own control state, not every proof that read them all)
1072
+ if (nev.length > 1 && joinNevers && neversBroken < joinNeversBreaks)
1073
+ push({ coef: [], d: 0, cells: false, nevers: nev, size: 1 });
1074
+ else
1075
+ for (const ats of nev)
1076
+ push({ coef: [], d: 0, cells: false, ...(ats.length > 1 ? { never: ats } : { unreachable: ats[0] }), size: 1 });
1036
1077
  return out;
1037
1078
  };
1038
1079
  let rounds = 0, why = '', set = [];
@@ -1096,11 +1137,25 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1096
1137
  const stepWith = (name, form, ctx) => {
1097
1138
  const ctxLaws = [...ctx, ...(form ? [form] : [])].map(lawFor), ls = [...given, ...ctxLaws], mm = forLaws(ctxLaws).m;
1098
1139
  const idx = form ? ls.length - 1 : ls.findIndex(l => l.name === name);
1099
- const g = obligations(mm, ls, {}, idx)[1];
1140
+ const g = obligations(mm, ls, {}, idx)[1], base0 = g.hyps.length - 1 - ls.length, used = [];
1141
+ // First a model alone of the CDCL search (no tree unfolded): refuted, the hypotheses its leaves read are those
1142
+ // a tree would (the set's proof is the kernel's below, as before); a model is the counterexample; else the prover.
1143
+ if (joinCore) {
1144
+ const quick = budgeted(joinQueryMs / 4, until2 => growCdcl(g, new Map(), { nodes: 0, until: until2 }, { model: true, core: true }));
1145
+ if (!('tree' in quick) && quick.why === REFUTED && quick.core) {
1146
+ for (const h of quick.core) {
1147
+ const k = h - base0;
1148
+ if (k >= given.length && k < ls.length && k !== idx)
1149
+ used.push(ls[k].name);
1150
+ }
1151
+ return { used };
1152
+ }
1153
+ if (!('tree' in quick) && quick.stuck === 'sat' && quick.witness)
1154
+ return { stuck: 'sat', witness: quick.witness };
1155
+ }
1100
1156
  const out = budgeted(joinQueryMs, until2 => grow(g, new Map(), { nodes: 0, until: until2 }));
1101
1157
  if (!('tree' in out))
1102
1158
  return { stuck: out.stuck, witness: out.stuck === 'sat' ? out.witness : undefined };
1103
- const base0 = g.hyps.length - 1 - ls.length, used = [];
1104
1159
  for (const h of usedHyps(g, out.tree)) {
1105
1160
  const k = h - base0;
1106
1161
  if (k >= given.length && k < ls.length && k !== idx)
@@ -1109,11 +1164,213 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1109
1164
  return { used };
1110
1165
  };
1111
1166
  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: {} } });
1167
+ // --- cubes: a point the samples leave out, as literals -------------------------------------------------------------
1168
+ const ctrl = modes.filter(mo => (mo.choice || mo.bool) && !atoms[mo.atom].cell && !atoms[mo.atom].param).map(mo => mo.atom);
1169
+ // (the rule's own comparisons first, then each value, then pairs: of two directions that leave out as many samples
1170
+ // the first is taken, so a bound the runs' depth sets, i0 <= 1 where they went 1 deep, gives way to the relation
1171
+ // that holds at every depth, i0 <= i1)
1172
+ const lc = plain.filter(i => !atoms[i].param && !ctrl.includes(i)), D0 = directions(lc), own = 2 * lc.length + (lc.length <= joinPairs ? 2 * lc.length * (lc.length - 1) : 0);
1173
+ const D = [...D0.slice(own), ...D0.slice(0, own)];
1174
+ const dot = (t, v) => { let s2 = 0; for (const [i, c] of t)
1175
+ s2 += c * v[i]; return s2; };
1176
+ const litHolds = (l, v) => ('at' in l ? v[l.at.atom] === l.at.value : dot(l.lin.coef, v) <= l.lin.d);
1177
+ const inCube = (c, v) => c.every(l => litHolds(l, v));
1178
+ const vecKey = (v) => Array.from(v).join(',');
1179
+ const S = rowsS.map(r => valuesOf(r)), sampled = new Set(S.map(vecKey));
1180
+ let initVec;
1181
+ try {
1182
+ if (!m.params.length)
1183
+ initVec = valuesOf(pointOf({}, run.init({})).scalar);
1184
+ }
1185
+ catch {
1186
+ initVec = undefined;
1187
+ }
1188
+ if (initVec && !sampled.has(vecKey(initVec))) {
1189
+ S.push(initVec);
1190
+ sampled.add(vecKey(initVec));
1191
+ }
1192
+ const addSample = (v) => { const k2 = vecKey(v); if (!sampled.has(k2)) {
1193
+ sampled.add(k2);
1194
+ S.push(v);
1195
+ } };
1196
+ // a state from a point's values: an integer's two naturals normalized (the kernel's model may leave both above 0)
1197
+ const stateAt = (w) => {
1198
+ const sc = Object.fromEntries(scalars.map(v => [v, w[v] ?? 0]));
1199
+ for (const a of atoms)
1200
+ if (a.int && !a.param && !a.cell) {
1201
+ const [p, q] = [a.parts[0][0], a.parts[1][0]], v = (sc[p] ?? 0) - (sc[q] ?? 0);
1202
+ sc[p] = Math.max(0, v);
1203
+ sc[q] = Math.max(0, -v);
1204
+ }
1205
+ return { scalars: sc, maps: {} };
1206
+ };
1207
+ const vecOf = (st) => valuesOf(pointOf({}, st).scalar);
1208
+ // The cube of a point the samples leave out: its control literals, then the direction that leaves out the most
1209
+ // samples still in, its bound as weak as leaves them out, until none is in (undefined: none leaves out the rest).
1210
+ const cubeOf = (v) => {
1211
+ const lits = ctrl.map(i => ({ at: { atom: i, value: v[i] } }));
1212
+ let alive = S.filter(s2 => inCube(lits, s2));
1213
+ while (alive.length) {
1214
+ let best = -1, bestN = 0;
1215
+ for (let q = 0; q < D.length; q++) {
1216
+ const tv = dot(D[q], v);
1217
+ let cnt = 0;
1218
+ for (const s2 of alive)
1219
+ if (dot(D[q], s2) > tv)
1220
+ cnt++;
1221
+ if (cnt > bestN)
1222
+ (bestN = cnt, best = q);
1223
+ }
1224
+ if (best < 0)
1225
+ return undefined;
1226
+ const t = D[best], tv = dot(t, v);
1227
+ let d = Infinity;
1228
+ for (const s2 of alive) {
1229
+ const w2 = dot(t, s2);
1230
+ if (w2 > tv && w2 - 1 < d)
1231
+ d = w2 - 1;
1232
+ }
1233
+ lits.push({ lin: { coef: t, d } });
1234
+ alive = alive.filter(s2 => dot(t, s2) <= d);
1235
+ }
1236
+ return lits;
1237
+ };
1238
+ // A literal true at v and false at u (a control value first, then the direction u is furthest past v in), its
1239
+ // bound v's own (a bound just short of u would creep up one reached state at a time).
1240
+ const apart = (v, u) => {
1241
+ for (const i of ctrl)
1242
+ if (v[i] !== u[i])
1243
+ return { at: { atom: i, value: v[i] } };
1244
+ let best, gap = 0;
1245
+ for (const t of D) {
1246
+ const g2 = (dot(t, u) - dot(t, v)) / t.reduce((acc, [, c]) => acc + Math.abs(c), 0);
1247
+ if (g2 > gap)
1248
+ (gap = g2, best = { lin: { coef: t, d: dot(t, v) } });
1249
+ }
1250
+ return best;
1251
+ };
1252
+ // Literals put back from `from` until no sample is in the cube (false where a sample can't be left out).
1253
+ const outOfSamples = (c, from) => {
1254
+ for (let alive = S.filter(s2 => inCube(c, s2)); alive.length;) {
1255
+ let best, bestN = 0;
1256
+ for (const l of from) {
1257
+ if (c.includes(l))
1258
+ continue;
1259
+ let cnt = 0;
1260
+ for (const s2 of alive)
1261
+ if (!litHolds(l, s2))
1262
+ cnt++;
1263
+ if (cnt > bestN)
1264
+ (bestN = cnt, best = l);
1265
+ }
1266
+ if (!best)
1267
+ return false;
1268
+ c.push(best);
1269
+ alive = alive.filter(s2 => litHolds(best, s2));
1270
+ }
1271
+ return true;
1272
+ };
1273
+ const formOf = (c) => ({ coef: [], d: 0, cells: false, cube: c, size: 1 });
1274
+ const witnessStep = (w) => {
1275
+ const pre = stateAt(w), input = Object.fromEntries(m.inputs.map(i => [i, w[i] ?? 0]));
1276
+ try {
1277
+ return { pre, post: run.step({}, pre, input) };
1278
+ }
1279
+ catch {
1280
+ return { pre };
1281
+ }
1282
+ };
1283
+ // Is the cube's negation inductive relative to these laws (the caller's and the kinds' beside)? Its literals after
1284
+ // the step are hypotheses of their own, so the refutation's core names those it read.
1285
+ const queryWith = (c, frame) => {
1286
+ const f = formOf(c), ls = [...given, ...frame, lawFor(f)], mm = forLaws(ls).m;
1287
+ const g = obligations(mm, ls, {}, ls.length - 1)[1], last = g.hyps.at(-1);
1288
+ const inner = last.op === 'not' && last.x.op === 'not' && last.x.x.op === 'and' && last.x.x.xs.length === c.length ? last.x.x.xs : undefined;
1289
+ const tails = inner ?? [last], hyps = [...g.hyps.slice(0, -1), ...tails], base = hyps.length - tails.length;
1290
+ const out = budgeted(joinCubeMs, until2 => growCdcl({ name: 'a cube', hyps }, new Map(), { nodes: 0, until: until2 }, { model: true, core: true }));
1291
+ if ('tree' in out)
1292
+ return { ok: true, core: new Set(c.map((_, j) => j)) };
1293
+ if (out.why === REFUTED)
1294
+ return { ok: true, core: inner && out.core ? new Set(out.core.filter(h => h >= base).map(h => h - base)) : new Set(c.map((_, j) => j)) };
1295
+ if (out.stuck === 'sat' && out.witness)
1296
+ return { ok: false, ...witnessStep(out.witness) };
1297
+ return undefined;
1298
+ };
1299
+ // A counterexample to a caller's law no candidate rules out: its cube (its control state and the bounds that keep
1300
+ // the samples out), blocked relative to the set (the set assumed before the step, and the cube's own negation, as
1301
+ // IC3's relative induction), its literals after the step those the refutation read (its core), the samples and the
1302
+ // start kept out. A predecessor the set allows into the cube: its own cube blocked first (a few deep), else the
1303
+ // cube made smaller to leave the predecessor's successor out. Each cube blocked is a form of the set (a
1304
+ // disjunction: never all its literals), which the join keeps or drops as any other.
1305
+ let cubed = 0, cubeWhy = '', cubeUntil = Infinity;
1306
+ const blockCube = (v, depth, within) => {
1307
+ let c = cubeOf(v);
1308
+ const made = [];
1309
+ if (!c)
1310
+ cubeWhy = sampled.has(vecKey(v)) ? 'a sample' : 'inside';
1311
+ // (relative to as little of the set as will do, as the join's goals are: the forms that rule out each
1312
+ // predecessor found, doubling, then the whole set)
1313
+ let ctx = [];
1314
+ for (let tries = 0; c && tries < joinCubeTries && now() < jUntil && !stop(); tries++) {
1315
+ const r = queryWith(c, [...ctx, ...made].map(lawFor).filter(l => l.name !== textOf(formOf(c))));
1316
+ if (!r) {
1317
+ cubeWhy = 'unknown';
1318
+ break;
1319
+ }
1320
+ if (r.ok) {
1321
+ const c2 = c.filter((_, j) => r.core.has(j));
1322
+ if (initVec && inCube(c2, initVec)) {
1323
+ const l = c.find(l2 => !litHolds(l2, initVec));
1324
+ if (l)
1325
+ c2.push(l);
1326
+ }
1327
+ made.push(formOf(outOfSamples(c2, c) ? c2 : c));
1328
+ break;
1329
+ }
1330
+ if (!r.post) {
1331
+ cubeWhy = 'no step';
1332
+ break;
1333
+ }
1334
+ const pv = vecOf(r.pre), qv = vecOf(r.post);
1335
+ const ruling = within.filter(f => !ctx.includes(f) && !holdsRow(f, { ...r.pre.scalars }));
1336
+ if (ruling.length) {
1337
+ ctx = [...ctx, ...ruling.slice(0, Math.max(joinAdd, ctx.length))];
1338
+ tries--;
1339
+ continue;
1340
+ }
1341
+ if (!inCube(c, qv)) {
1342
+ cubeWhy = 'outside';
1343
+ break;
1344
+ }
1345
+ const sub = depth > 0 && !sampled.has(vecKey(pv)) ? blockCube(pv, depth - 1, [...within, ...made]) : [];
1346
+ if (sub.length) {
1347
+ made.push(...sub);
1348
+ continue;
1349
+ }
1350
+ // (a predecessor the runs reached: its successor is reached too, a sample now)
1351
+ if (sampled.has(vecKey(pv)))
1352
+ addSample(qv);
1353
+ const l = apart(v, qv);
1354
+ if (!l) {
1355
+ cubeWhy = 'reached';
1356
+ break;
1357
+ }
1358
+ c = [...c, l];
1359
+ cubeWhy = 'tries';
1360
+ }
1361
+ return made;
1362
+ };
1112
1363
  for (;;) {
1113
1364
  if (now() > jUntil || stop()) {
1114
1365
  why = 'time';
1115
1366
  break;
1116
1367
  }
1368
+ // (once a cube is in the set, the join has a part of what is left, the search below the rest: the cubes are
1369
+ // for counterexamples no candidate rules out, which the search below rules out its own way)
1370
+ if (now() > cubeUntil) {
1371
+ why = 'cubes';
1372
+ break;
1373
+ }
1117
1374
  rounds++;
1118
1375
  set = [...formsNow(), ...extras].filter(f => !blocked.has(textOf(f)));
1119
1376
  const byText = new Map(set.map(f => [textOf(f), f]));
@@ -1145,7 +1402,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1145
1402
  // counterexample the whole set allows is one to learn from.
1146
1403
  const todoForm = callers.has(todo) ? undefined : byText.get(todo);
1147
1404
  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);
1405
+ const rank = (f) => (inCone.has(textOf(f)) ? 0 : stood.has(textOf(f)) ? 1 : 2) * 1000 + f.coef.length * 10 + (f.never || f.nevers || f.also ? 1 : 0);
1149
1406
  const whole = set.filter(f => f !== todoForm);
1150
1407
  let ctx = [], witness, lastStuck = '', qms = 0, settled = false;
1151
1408
  for (let attempt = 0; attempt <= joinAttempts; attempt++) {
@@ -1191,6 +1448,8 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1191
1448
  continue;
1192
1449
  }
1193
1450
  const w = witness, { params, st } = stateOf(w);
1451
+ if (todoForm?.nevers)
1452
+ neversBroken++;
1194
1453
  const input = Object.fromEntries(m.inputs.map(i => [i, w[i] ?? 0]));
1195
1454
  let post;
1196
1455
  try {
@@ -1230,6 +1489,17 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1230
1489
  if (next)
1231
1490
  tried++;
1232
1491
  opts.progress?.('join', { round: rounds, set: set.length, ms: qms, target: next ? textOf(next).slice(0, 60) : 'none' });
1492
+ if (!next && !outside && joinCubes && initVec && cubed < joinCubeMax && now() < jUntil) {
1493
+ const made = blockCube(valuesOf(pre.scalar), joinCubeDepth, set);
1494
+ opts.progress?.('join', { round: rounds, set: set.length, cubes: made.map(f => textOf(f).slice(0, 100)).join('; ') || `none: ${cubeWhy}` });
1495
+ if (made.length) {
1496
+ if (!cubed)
1497
+ cubeUntil = now() + (jUntil - now()) * joinCubeWindow;
1498
+ cubed += made.length;
1499
+ extras.push(...made);
1500
+ continue;
1501
+ }
1502
+ }
1233
1503
  if (!next) {
1234
1504
  why = 'target';
1235
1505
  break;
@@ -1400,7 +1670,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1400
1670
  return { ...last, found: [], stats: stats(samples.length, forms.length, alive.length) };
1401
1671
  }
1402
1672
  // Take out what the proof doesn't need, the last added first.
1403
- for (const f of [...chosen].reverse()) {
1673
+ for (const f of opts.minimize === false ? [] : [...chosen].reverse()) {
1404
1674
  if (now() > until || stop())
1405
1675
  break;
1406
1676
  const without = chosen.filter(g => g !== f), v = prove([...laws, ...without.map(lawFor)]);
@@ -6,12 +6,13 @@ export type NeverEndsOptions = {
6
6
  maxTurns?: number;
7
7
  lassos?: boolean;
8
8
  counted?: number;
9
+ accel?: number;
9
10
  };
10
11
  export type NeverEndsVerdict = {
11
12
  proven: boolean;
12
13
  checked: boolean;
13
14
  recur?: Recur;
14
- by?: 'lasso' | 'policy lasso' | 'recurrent set';
15
+ by?: 'lasso' | 'policy lasso' | 'recurrent set' | 'accelerated';
15
16
  why?: string;
16
17
  lasso?: {
17
18
  params: Record<string, number>;
@@ -26,6 +27,8 @@ export type NeverEndsVerdict = {
26
27
  ms: number;
27
28
  lassoTried: number;
28
29
  goalSize: number;
30
+ accel: number;
31
+ accelClosed: number;
29
32
  };
30
33
  };
31
34
  export declare const simpE: (e: E) => E;
@@ -1,6 +1,8 @@
1
- import { checkRecur, recurGoal, substC, trueC } from "../kernel/kernel.js";
1
+ import { checkRecur, loopMachine, recurGoal, substC, trueC } from "../kernel/kernel.js";
2
2
  import { clock, counted, grow } from "../kernel/prove.js";
3
3
  import { work } from "./solver.js";
4
+ import { accelerated, stemsTo } from "./accel.js";
5
+ import { findBoundedRun } from "./bmc.js";
4
6
  const K = (value) => ({ op: 'const', value }), V = (name) => ({ op: 'var', name });
5
7
  const T = trueC, F = { op: '<', a: K(0), b: K(0) };
6
8
  const isT = (c) => c.op === '<=' && c.a.op === 'const' && c.b.op === 'const' && c.a.value <= c.b.value;
@@ -77,6 +79,10 @@ export function goalSize(x) {
77
79
  return n;
78
80
  }
79
81
  const GOAL_MAX = 300_000;
82
+ // An accelerated set's goal: the witness reads the location (and the set's parts only where the cycle comes back to one),
83
+ // so its ifs multiply the body's less, and such goals of millions of nodes have closed (TermComp's tqli: 720,729 nodes,
84
+ // proven in 22 s).
85
+ const ACCEL_GOAL_MAX = 5_000_000;
80
86
  // --- running the loop ---------------------------------------------------------------------------------------------------
81
87
  class Overflow extends Error {
82
88
  }
@@ -231,7 +237,7 @@ function search(l, opts) {
231
237
  const wall0 = performance.now(), now = clock, t0 = now(), until = t0 + (opts.ms ?? 10_000), maxTurns = opts.maxTurns ?? 400;
232
238
  let seed = opts.seed ?? 7;
233
239
  const rand = (k) => { seed = (seed * 1103515245 + 12345) % 2 ** 31; return Math.floor(seed / 2 ** 31 * k); };
234
- const stats = { runs: 0, turns: 0, policies: 0, rounds: 0, ms: 0, lassoTried: 0, goalSize: 0 };
240
+ const stats = { runs: 0, turns: 0, policies: 0, rounds: 0, ms: 0, lassoTried: 0, goalSize: 0, accel: 0, accelClosed: 0 };
235
241
  const done = (v) => ({ ...v, stats: { ...stats, ms: Math.round(performance.now() - wall0) } });
236
242
  const stateNames = Object.keys(l.state), kept = [...l.params, ...stateNames];
237
243
  const allObs = observables(kept), inObs = observables(l.inputs);
@@ -378,6 +384,96 @@ function search(l, opts) {
378
384
  }
379
385
  if (opts.lassos)
380
386
  return done({ proven: false, checked: false, why: `no lasso in ${stats.runs} runs` });
387
+ // 1b. Accelerated cycles (core/accel.ts): a set from a cycle of the relation, a stem into it, its closure proven.
388
+ if ((opts.accel ?? 0.4) > 0) {
389
+ const accelUntil = Math.min(until, now() + (until - now()) * (opts.accel ?? 0.4)), m = loopMachine(l);
390
+ try {
391
+ // (the random runs, the longest 20, for the cycles they take)
392
+ const ends = new Map();
393
+ for (const v of visits)
394
+ if (v.run && (ends.get(v.run)?.at ?? -1) < v.at)
395
+ ends.set(v.run, v);
396
+ const runs = [...ends.values()].sort((a, b) => b.at - a.at).slice(0, 20).map(v => ({ params: v.params, inputs: stemOf(v) }));
397
+ for (const a of accelerated(l, { now, until: accelUntil, runs, io: { start, turn } })) {
398
+ stats.accel++;
399
+ const goal = recurGoal(l, a);
400
+ stats.goalSize = Math.max(stats.goalSize, goalSize(goal.hyps));
401
+ if (goalSize(goal.hyps) > ACCEL_GOAL_MAX)
402
+ continue;
403
+ const inSet = cC(a.set);
404
+ // A stem into the set, cut where it first enters it (every turn allowed): from a state a random run reached (the
405
+ // shortest), else an accelerated run (cheap: tried before the closure, which is not tried for a set no stem
406
+ // reaches), else, once the set is closed, a bounded run (core/bmc.ts: the kernel's k-step goal's model, the set's
407
+ // complement as the law it breaks).
408
+ const cut = (t) => {
409
+ let st = start(t.params);
410
+ for (let j = 0; j <= t.stem.length; j++) {
411
+ if (inSet(st))
412
+ return { params: t.params, stem: t.stem.slice(0, j) };
413
+ if (j === t.stem.length)
414
+ return undefined;
415
+ const nx = turn(st, t.stem[j]);
416
+ if (!nx)
417
+ return undefined;
418
+ st = nx;
419
+ }
420
+ return undefined;
421
+ };
422
+ const stems = [], report = { exhausted: false };
423
+ let best;
424
+ for (const v of visits)
425
+ if ((!best || v.at < best.at) && inSet(v.st))
426
+ best = v;
427
+ if (best)
428
+ stems.push({ params: best.params, stem: stemOf(best) });
429
+ else {
430
+ // (a set's stem has time of its own, past the stage's if need be, within the search's)
431
+ let n = 0;
432
+ for (const t of stemsTo(l, a.targets, { start, turn }, { now, until: Math.min(until, now() + 1000), report })) {
433
+ const c = cut(t);
434
+ if (c) {
435
+ stems.push(c);
436
+ break;
437
+ }
438
+ if (++n >= 4)
439
+ break;
440
+ }
441
+ }
442
+ // (a set the accelerated runs' search, run to its end, doesn't reach is left: the time goes to sets a run reaches)
443
+ if (!stems.length && report.exhausted)
444
+ continue;
445
+ // (a set with a stem is likely: its closure may take most of what is left, past the stage's share; one without,
446
+ // the stage's share and at most 4 s)
447
+ const out = grow(goal, new Map(), { nodes: 0, until: stems.length ? Math.min(until, now() + Math.max(4000, (until - now()) * 0.6)) : Math.min(accelUntil, now() + 4000) });
448
+ if (!('tree' in out))
449
+ continue;
450
+ stats.accelClosed++;
451
+ if (!stems.length && now() < until) {
452
+ const left = Math.min(until - now(), 2000);
453
+ const run = findBoundedRun(m, [{ name: 'outside the set', holds: { op: 'not', x: a.set } }], { ms: left, depth: 24, ...(opts.counted ? {} : { wall: performance.now() + left }) });
454
+ const c = run && cut({ params: run.params, stem: run.trace.map(r => Object.fromEntries(l.inputs.map(n => [n, Number(r[n] ?? 0)]))) });
455
+ if (c)
456
+ stems.push(c);
457
+ }
458
+ for (const t of stems) {
459
+ const recur = { start: params(t.params), stem: asStem(t.stem), set: a.set, wit: a.wit, tree: out.tree };
460
+ let ok = false;
461
+ try {
462
+ ok = checkRecur(l, recur);
463
+ }
464
+ catch {
465
+ ok = false;
466
+ }
467
+ if (ok)
468
+ return done({ proven: true, checked: true, recur, by: 'accelerated' });
469
+ }
470
+ }
471
+ }
472
+ catch (e) {
473
+ if (!(e instanceof Overflow))
474
+ throw e;
475
+ }
476
+ }
381
477
  // 2. Policies from the states reached.
382
478
  const pools = inObs.map(o => {
383
479
  const terms = [iConst(0), iConst(1)];