gdp-wired 0.24.0 → 0.26.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 (52) hide show
  1. package/README.md +14 -9
  2. package/dist/core/accel.d.ts +44 -0
  3. package/dist/core/accel.js +955 -0
  4. package/dist/core/bmc.d.ts +8 -0
  5. package/dist/core/bmc.js +263 -97
  6. package/dist/core/cycles.d.ts +2 -3
  7. package/dist/core/cycles.js +409 -174
  8. package/dist/core/cyclic.d.ts +4 -1
  9. package/dist/core/cyclic.js +86 -64
  10. package/dist/core/data.d.ts +9 -1
  11. package/dist/core/data.js +872 -168
  12. package/dist/core/discover.js +2 -3
  13. package/dist/core/dsl.d.ts +3 -2
  14. package/dist/core/dsl.js +21 -18
  15. package/dist/core/exists.js +7 -14
  16. package/dist/core/extract-check.d.ts +3 -2
  17. package/dist/core/extract-check.js +137 -50
  18. package/dist/core/extract-print.d.ts +1 -0
  19. package/dist/core/extract-print.js +26 -3
  20. package/dist/core/extract-read.d.ts +85 -4
  21. package/dist/core/extract-read.js +295 -34
  22. package/dist/core/extract-shapes.d.ts +14 -0
  23. package/dist/core/extract-shapes.js +608 -78
  24. package/dist/core/extract-xstate.d.ts +5 -1
  25. package/dist/core/extract-xstate.js +618 -184
  26. package/dist/core/extract.js +73 -27
  27. package/dist/core/infer.d.ts +1 -0
  28. package/dist/core/infer.js +364 -40
  29. package/dist/core/machine.d.ts +6 -0
  30. package/dist/core/machine.js +35 -3
  31. package/dist/core/nonterm.d.ts +9 -2
  32. package/dist/core/nonterm.js +173 -9
  33. package/dist/core/q.d.ts +1 -0
  34. package/dist/core/q.js +2 -2
  35. package/dist/core/relation.d.ts +1 -0
  36. package/dist/core/relation.js +95 -39
  37. package/dist/core/solver.d.ts +12 -0
  38. package/dist/core/solver.js +76 -30
  39. package/dist/core/transfer.js +23 -14
  40. package/dist/core/translate.d.ts +1 -1
  41. package/dist/core/translate.js +22 -49
  42. package/dist/core/xstate.d.ts +6 -1
  43. package/dist/core/xstate.js +336 -55
  44. package/dist/kernel/cdcl.d.ts +5 -0
  45. package/dist/kernel/cdcl.js +44 -8
  46. package/dist/kernel/prove.d.ts +6 -1
  47. package/dist/kernel/prove.js +101 -85
  48. package/dist/kernel/reader.d.ts +1 -0
  49. package/dist/kernel/reader.js +4 -3
  50. package/dist/kernel/simplex.d.ts +1 -1
  51. package/dist/kernel/simplex.js +13 -1
  52. package/package.json +3 -2
@@ -13,20 +13,25 @@
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";
25
- import { proveRule, proveSteps } from "./dsl.js";
27
+ import { all, any, atMost, divisorsIn, evalC, get, interpret, machineTerms, modName, n, not, plus, same, seeded, times, withArithmetic, x } from "./machine.js";
28
+ import { proveRule, proveSteps, verdictOf } from "./dsl.js";
26
29
  import { allowed, watch } from "./watch.js";
27
- import { clock, counted, grow, proveLaw, proveLaws, proveStepLaws, usedHyps, withDeadline } from "../kernel/prove.js";
30
+ import { clock, counted, grow, proveLaw, proveLaws, proveStepLaws, usedHyps, withDeadline, withTrees } from "../kernel/prove.js";
28
31
  import { obligations, substC } from "../kernel/kernel.js";
29
- import { work } from "./solver.js";
32
+ import { env, gcd, work } from "./solver.js";
33
+ import { bgcd } from "./q.js";
34
+ import { REFUTED, growCdcl } from "../kernel/cdcl.js";
30
35
  const KEY = 'key$found', AT = '@', K = '#', SOME = 'k$found';
31
36
  // The counted clock's rates, units a millisecond: about the slowest tenth of what Modal's 1-vCPU containers do in each
32
37
  // phase (`runs/modal/infer/after2`, GDP_INFER_TRACE=1: requests tried 85 a ms, rows 13,093, forms evaluated 11,240, the
@@ -38,19 +43,35 @@ const KEY = 'key$found', AT = '@', K = '#', SOME = 'k$found';
38
43
  export const inferRates = { tries: 100, rows: 10_000, evals: 10_000, watched: 100, work: 40 };
39
44
  export const inferRuns = 16_000;
40
45
  // GDP_INFER_TRACE=1: each phase's wall time beside what it counted, to stderr (the calibration's numbers).
41
- const inferTrace = !!globalThis.process?.env?.GDP_INFER_TRACE;
46
+ const inferTrace = !!env.GDP_INFER_TRACE;
42
47
  // The join (below, after the candidates): GDP_JOIN=0 turns it off, for comparing. Its share of what is left of the
43
48
  // search's budget; each kernel search's budget (counted, or wall time where timed), a request's 150 ms; the steps a walk
44
49
  // from a joined state takes; pairs of values as directions up to 10 values; a bound raised twice at most, then dropped;
45
50
  // equalities of at most 4 values, coefficients up to 1,000; at most 24 candidates beside the hull, 40 tried; yes/nos in
46
51
  // 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
52
  // at a time.
48
- const joinOn = globalThis.process?.env?.GDP_JOIN !== '0';
53
+ const joinOn = env.GDP_JOIN !== '0';
49
54
  const joinShare = 0.6, joinQueryMs = 8000, joinRequestMs = 150, joinWalk = 8, joinPairs = 10, joinRaises = 2, joinSparse = 4, joinCoef = 1000;
50
55
  const joinExtras = 24, joinTries = 40, joinBits = 7, joinKeys = 128, joinAttempts = 6, joinAdd = 2;
51
- const seeded = (seed) => { let s = seed; return k => { s = (s * 1103515245 + 12345) % 2 ** 31; return Math.floor(s / 2 ** 31 * k); }; };
56
+ // 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
57
+ // CDCL search first, at a quarter of the goal's budget).
58
+ // GDP_JOIN_NEVERS=0: each control state no run reached a form of its own, as before (else one form for all of them,
59
+ // until it is first broken).
60
+ const joinNevers = env.GDP_JOIN_NEVERS !== '0';
61
+ const joinNeversBreaks = 1;
62
+ const joinCore = env.GDP_JOIN_CORE !== '0';
63
+ // Cubes blocked where no candidate rules a counterexample out (GDP_JOIN_CUBES=0: none): at most 48 in all, each tried 8
64
+ // times, its predecessors blocked first 3 deep, each query's budget 2 s (counted, or wall time where timed).
65
+ const joinCubes = env.GDP_JOIN_CUBES !== '0';
66
+ const joinCubeMax = 48, joinCubeTries = 8, joinCubeDepth = 3, joinCubeMs = 2000;
67
+ // Once a cube is in the set, the join has 0.3 of what is left of its time (the search below the rest).
68
+ const joinCubeWindow = 0.3;
69
+ // GDP_JOIN_PRIME=0: each control state no state reached a form of its own, every value read.
70
+ const joinPrime = env.GDP_JOIN_PRIME !== '0';
71
+ // GDP_JOIN_DOWN=0: a blocked cube kept as its refutation's core cuts it (no literal dropped); joinDownQueries, the
72
+ // queries a cube's generalization may ask.
73
+ const joinDown = env.GDP_JOIN_DOWN !== '0', joinDownQueries = 24;
52
74
  const isRule = (t) => typeof t.kindsOfState === 'function';
53
- const gcd = (a, b) => (b === 0 ? Math.abs(a) : gcd(b, a % b));
54
75
  // The constants a machine's expressions hold, and the factors it multiplies by.
55
76
  function constantsOf(m, laws) {
56
77
  const out = new Set();
@@ -226,7 +247,7 @@ function comparisons(m, laws, atoms, coords) {
226
247
  return [...found.values()];
227
248
  }
228
249
  export function inferLaws(target, laws, stepLaws = [], opts = {}) {
229
- return quietly(() => withDeadline(performance.now() + (opts.ms ?? 20000), () => inferLawsSearch(target, laws, stepLaws, opts)));
250
+ return quietly(() => withDeadline(clock() + (opts.ms ?? 20000), () => inferLawsSearch(target, laws, stepLaws, opts)));
230
251
  }
231
252
  function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
232
253
  const t0 = performance.now(), ms = opts.ms ?? 20000, wallUntil = t0 + ms, rule = isRule(target) ? target : undefined;
@@ -274,7 +295,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
274
295
  if (searchRule)
275
296
  return stepLaws.length ? proveSteps(searchRule, ls, stepLaws, { search: false }) : proveRule(searchRule, ls, { search: false });
276
297
  const out = stepLaws.length ? proveStepLaws(mm, ls, stepLaws) : proveLaws(mm, ls);
277
- return { proven: out.proven, checked: out.checked, ...(out.failed ? { goal: out.failed.goal, stuck: out.failed.stuck, ...(out.failed.witness ? { witness: out.failed.witness } : {}), ...(out.failed.why ? { why: out.failed.why } : {}) } : {}) };
298
+ return verdictOf(out);
278
299
  };
279
300
  const stats = (samples, candidates, alive) => ({ samples, candidates, alive, proofs, ms: Math.round(performance.now() - t0), stopped: stop() });
280
301
  const first = opts.first ?? prove(laws);
@@ -576,6 +597,10 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
576
597
  const atText = (g) => `${nameOf(g.atom)} is ${shownValue(g.atom, g.value)}`;
577
598
  if (f.never)
578
599
  return `never ${f.never.map(atText).join(' and ')}`;
600
+ if (f.nevers)
601
+ return `never ${f.nevers.map(c => c.map(atText).join(' and ')).join('; nor ')}`;
602
+ if (f.cube)
603
+ 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
604
  if (f.also)
580
605
  return `${f.also.map(atText).join(' and ')} → ${textOf({ ...f, also: undefined })}`;
581
606
  if (f.unreachable)
@@ -605,6 +630,10 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
605
630
  };
606
631
  if (f.never)
607
632
  return any(...f.never.map(g => notAt(g.atom, g.value)));
633
+ if (f.nevers)
634
+ return all(...f.nevers.map(c => any(...c.map(g => notAt(g.atom, g.value)))));
635
+ if (f.cube)
636
+ 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
637
  if (f.also)
609
638
  return any(...f.also.map(g => notAt(g.atom, g.value)), condOf({ ...f, also: undefined }));
610
639
  if (f.unreachable)
@@ -629,7 +658,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
629
658
  };
630
659
  // The builder call, for a rule whose atoms are its own variables (naturals, or integers alone).
631
660
  const sourceOf = (f, text) => {
632
- if (!rule || f.when || f.mod || f.also || f.never)
661
+ if (!rule || f.when || f.mod || f.also || f.never || f.nevers || f.cube)
633
662
  return undefined;
634
663
  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
664
  const ints = f.coef.filter(([i]) => atoms[i].int).length;
@@ -677,6 +706,10 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
677
706
  const vs = valuesOf(env);
678
707
  if (f.never)
679
708
  return f.never.some(g => vs[g.atom] !== g.value);
709
+ if (f.nevers)
710
+ return f.nevers.every(c => c.some(g => vs[g.atom] !== g.value));
711
+ if (f.cube)
712
+ 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
713
  if (f.also?.some(g => vs[g.atom] !== g.value))
681
714
  return true;
682
715
  if (f.unreachable)
@@ -918,32 +951,33 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
918
951
  const locsReached = jChoice ? new Set(valsS[jChoice.atom]).size : 1;
919
952
  const keyModes = [...(jChoice ? [jChoice] : []), ...(bits.length && bits.length <= joinBits && locsReached * 2 ** bits.length <= joinKeys ? bits : [])];
920
953
  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))
954
+ // The directions over some values: each value up and down, pairs of them where there are few, and the rule's own
955
+ // comparisons over the state (a guard, the query's condition), each both ways.
956
+ const directions = (cs) => {
957
+ const out = [];
958
+ for (const i of cs)
959
+ out.push([[i, 1]], [[i, -1]]);
960
+ if (cs.length <= joinPairs)
961
+ for (const [a2, i] of cs.entries())
962
+ for (const j of cs.slice(a2 + 1))
963
+ for (const [c1, c2] of [[1, 1], [1, -1], [-1, 1], [-1, -1]])
964
+ out.push([[i, c1], [j, c2]]);
965
+ const known = new Set(out.map(t => JSON.stringify(t)));
966
+ for (const t of comparisons(m, laws, atoms, cs))
933
967
  for (const u of [t, t.map(([i, c]) => [i, -c])]) {
934
968
  const k2 = JSON.stringify(u);
935
- if (!known.has(k2) && dirs.length < 2 * CN + 4 * joinPairs * joinPairs + 64) {
969
+ if (!known.has(k2) && out.length < 2 * cs.length + 4 * joinPairs * joinPairs + 64) {
936
970
  known.add(k2);
937
- dirs.push(u);
971
+ out.push(u);
938
972
  }
939
973
  }
940
- }
974
+ return out;
975
+ };
976
+ const dirs = directions(coords);
941
977
  // Widening with thresholds: a bound a counterexample breaks rises to the next of the rule's constants (their sums and
942
978
  // products the first time, the constants alone after), and past that it is dropped.
943
979
  const fine = bounds, coarse = [...new Set([0, ...consts.flatMap(k => [k, -k])])].sort((p2, q2) => p2 - q2);
944
980
  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
981
  const normal = (e) => { let g2 = 0n; for (const x2 of e)
948
982
  g2 = bgcd(g2, x2); if (g2 > 1n)
949
983
  for (let k = 0; k < e.length; k++)
@@ -988,25 +1022,27 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
988
1022
  const combos = keyModes.reduce((acc, mo) => acc.flatMap(c => mo.values.map(v => [...c, v])), [[]]);
989
1023
  for (let j = 0; j < NS; j++)
990
1024
  join(keyOf(valsS.map(col => col[j])), valsS.map(col => col[j]), false);
1025
+ let neversBroken = 0;
991
1026
  const formsNow = () => {
992
1027
  const out = [], seenT = new Set();
993
1028
  const push = (f) => { const t = textOf(f); if (!seenT.has(t) && !names.has(t)) {
994
1029
  seenT.add(t);
995
1030
  out.push(f);
996
1031
  } };
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]));
1032
+ // (a choice's value no state reached: one form, whatever the yes/nos; the control states no state reached, one form
1033
+ // for all, where there are several: each alone needs the others to be inductive, a goal each where one does)
1034
+ const reachedFirst = new Set([...groups.keys()].map(k2 => k2.split(',')[0])), nev = [];
999
1035
  for (const combo of combos) {
1000
1036
  if (combo.length > 1 && !reachedFirst.has(String(combo[0]))) {
1001
1037
  if (combo.slice(1).every(v => v === 0))
1002
- push({ coef: [], d: 0, cells: false, unreachable: { atom: keyAtoms[0], value: combo[0] }, size: 1 });
1038
+ nev.push([{ atom: keyAtoms[0], value: combo[0] }]);
1003
1039
  continue;
1004
1040
  }
1005
1041
  const ats = combo.map((value, k) => ({ atom: keyAtoms[k], value })), grp = groups.get(combo.join(','));
1006
1042
  const guard = ats.length ? { guard: ats[0], ...(ats.length > 1 ? { also: ats.slice(1) } : {}) } : {};
1007
1043
  if (!grp) {
1008
1044
  if (ats.length)
1009
- push({ coef: [], d: 0, cells: false, ...(ats.length > 1 ? { never: ats } : { unreachable: ats[0] }), size: 1 });
1045
+ nev.push(ats);
1010
1046
  continue;
1011
1047
  }
1012
1048
  for (const e of grp.eqs) {
@@ -1033,8 +1069,38 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1033
1069
  push({ coef: t, d: hi, cells: false, ...guard, size: 0 });
1034
1070
  });
1035
1071
  }
1072
+ // (once broken, each its own form from then on, so that a state joined in changes only the forms that
1073
+ // read its own control state, not every proof that read them all)
1074
+ if (nev.length > 1 && joinNevers && neversBroken < joinNeversBreaks)
1075
+ push({ coef: [], d: 0, cells: false, nevers: nev, size: 1 });
1076
+ else
1077
+ for (const ats of joinPrime ? primes(nev) : nev)
1078
+ push({ coef: [], d: 0, cells: false, ...(ats.length > 1 ? { never: ats } : { unreachable: ats[0] }), size: 1 });
1036
1079
  return out;
1037
1080
  };
1081
+ // The control states no state reached, as fewer and smaller cubes (a program counter in bits: Spacer's clauses there
1082
+ // read two or three of its bits): each cube's values dropped one at a time, the yes/nos first, while it holds at no
1083
+ // control state reached, then the cubes another cube's values include left out. Together they say what the cubes
1084
+ // of every value say (the control state is one reached), but a goal reads fewer of them, and each of them less.
1085
+ const primes = (nev) => {
1086
+ const reachedKeys = [...groups.keys()].map(k2 => k2.split(',').map(Number));
1087
+ const holdsAtSome = (c) => reachedKeys.some(vs => c.every(a => vs[keyAtoms.indexOf(a.atom)] === a.value));
1088
+ const out = [];
1089
+ for (const ats of nev) {
1090
+ let c = ats;
1091
+ for (const a of [...ats.slice(1), ats[0]]) {
1092
+ if (c.length <= 1)
1093
+ break;
1094
+ const fewer = c.filter(b2 => b2 !== a);
1095
+ if (!holdsAtSome(fewer))
1096
+ c = fewer;
1097
+ }
1098
+ out.push(c);
1099
+ }
1100
+ const key2 = (c) => c.map(a => `${a.atom}=${a.value}`).sort().join('&');
1101
+ const uniq = [...new Map(out.map(c => [key2(c), c])).values()].sort((a, b) => a.length - b.length);
1102
+ return uniq.filter((c, i) => !uniq.slice(0, i).some(d => d.every(a => c.some(b2 => b2.atom === a.atom && b2.value === a.value))));
1103
+ };
1038
1104
  let rounds = 0, why = '', set = [];
1039
1105
  const params0 = {};
1040
1106
  // Beside the hull, forms of the candidates' that rule out a counterexample to the caller's laws (a state the set
@@ -1096,11 +1162,25 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1096
1162
  const stepWith = (name, form, ctx) => {
1097
1163
  const ctxLaws = [...ctx, ...(form ? [form] : [])].map(lawFor), ls = [...given, ...ctxLaws], mm = forLaws(ctxLaws).m;
1098
1164
  const idx = form ? ls.length - 1 : ls.findIndex(l => l.name === name);
1099
- const g = obligations(mm, ls, {}, idx)[1];
1165
+ const g = obligations(mm, ls, {}, idx)[1], base0 = g.hyps.length - 1 - ls.length, used = [];
1166
+ // First a model alone of the CDCL search (no tree unfolded): refuted, the hypotheses its leaves read are those
1167
+ // a tree would (the set's proof is the kernel's below, as before); a model is the counterexample; else the prover.
1168
+ if (joinCore) {
1169
+ const quick = budgeted(joinQueryMs / 4, until2 => growCdcl(g, new Map(), { nodes: 0, until: until2 }, { model: true, core: true }));
1170
+ if (!('tree' in quick) && quick.why === REFUTED && quick.core) {
1171
+ for (const h of quick.core) {
1172
+ const k = h - base0;
1173
+ if (k >= given.length && k < ls.length && k !== idx)
1174
+ used.push(ls[k].name);
1175
+ }
1176
+ return { used };
1177
+ }
1178
+ if (!('tree' in quick) && quick.stuck === 'sat' && quick.witness)
1179
+ return { stuck: 'sat', witness: quick.witness };
1180
+ }
1100
1181
  const out = budgeted(joinQueryMs, until2 => grow(g, new Map(), { nodes: 0, until: until2 }));
1101
1182
  if (!('tree' in out))
1102
1183
  return { stuck: out.stuck, witness: out.stuck === 'sat' ? out.witness : undefined };
1103
- const base0 = g.hyps.length - 1 - ls.length, used = [];
1104
1184
  for (const h of usedHyps(g, out.tree)) {
1105
1185
  const k = h - base0;
1106
1186
  if (k >= given.length && k < ls.length && k !== idx)
@@ -1109,11 +1189,241 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1109
1189
  return { used };
1110
1190
  };
1111
1191
  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: {} } });
1192
+ // --- cubes: a point the samples leave out, as literals -------------------------------------------------------------
1193
+ const ctrl = modes.filter(mo => (mo.choice || mo.bool) && !atoms[mo.atom].cell && !atoms[mo.atom].param).map(mo => mo.atom);
1194
+ // (the rule's own comparisons first, then each value, then pairs: of two directions that leave out as many samples
1195
+ // the first is taken, so a bound the runs' depth sets, i0 <= 1 where they went 1 deep, gives way to the relation
1196
+ // that holds at every depth, i0 <= i1)
1197
+ 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);
1198
+ const D = [...D0.slice(own), ...D0.slice(0, own)];
1199
+ const dot = (t, v) => { let s2 = 0; for (const [i, c] of t)
1200
+ s2 += c * v[i]; return s2; };
1201
+ const litHolds = (l, v) => ('at' in l ? v[l.at.atom] === l.at.value : dot(l.lin.coef, v) <= l.lin.d);
1202
+ const inCube = (c, v) => c.every(l => litHolds(l, v));
1203
+ const vecKey = (v) => Array.from(v).join(',');
1204
+ const S = rowsS.map(r => valuesOf(r)), sampled = new Set(S.map(vecKey));
1205
+ let initVec;
1206
+ try {
1207
+ if (!m.params.length)
1208
+ initVec = valuesOf(pointOf({}, run.init({})).scalar);
1209
+ }
1210
+ catch {
1211
+ initVec = undefined;
1212
+ }
1213
+ if (initVec && !sampled.has(vecKey(initVec))) {
1214
+ S.push(initVec);
1215
+ sampled.add(vecKey(initVec));
1216
+ }
1217
+ const addSample = (v) => { const k2 = vecKey(v); if (!sampled.has(k2)) {
1218
+ sampled.add(k2);
1219
+ S.push(v);
1220
+ } };
1221
+ // a state from a point's values: an integer's two naturals normalized (the kernel's model may leave both above 0)
1222
+ const stateAt = (w) => {
1223
+ const sc = Object.fromEntries(scalars.map(v => [v, w[v] ?? 0]));
1224
+ for (const a of atoms)
1225
+ if (a.int && !a.param && !a.cell) {
1226
+ const [p, q] = [a.parts[0][0], a.parts[1][0]], v = (sc[p] ?? 0) - (sc[q] ?? 0);
1227
+ sc[p] = Math.max(0, v);
1228
+ sc[q] = Math.max(0, -v);
1229
+ }
1230
+ return { scalars: sc, maps: {} };
1231
+ };
1232
+ const vecOf = (st) => valuesOf(pointOf({}, st).scalar);
1233
+ // The cube of a point the samples leave out: its control literals, then the direction that leaves out the most
1234
+ // samples still in, its bound as weak as leaves them out, until none is in (undefined: none leaves out the rest).
1235
+ const cubeOf = (v) => {
1236
+ const lits = ctrl.map(i => ({ at: { atom: i, value: v[i] } }));
1237
+ let alive = S.filter(s2 => inCube(lits, s2));
1238
+ while (alive.length) {
1239
+ let best = -1, bestN = 0;
1240
+ for (let q = 0; q < D.length; q++) {
1241
+ const tv = dot(D[q], v);
1242
+ let cnt = 0;
1243
+ for (const s2 of alive)
1244
+ if (dot(D[q], s2) > tv)
1245
+ cnt++;
1246
+ if (cnt > bestN)
1247
+ (bestN = cnt, best = q);
1248
+ }
1249
+ if (best < 0)
1250
+ return undefined;
1251
+ const t = D[best], tv = dot(t, v);
1252
+ let d = Infinity;
1253
+ for (const s2 of alive) {
1254
+ const w2 = dot(t, s2);
1255
+ if (w2 > tv && w2 - 1 < d)
1256
+ d = w2 - 1;
1257
+ }
1258
+ lits.push({ lin: { coef: t, d } });
1259
+ alive = alive.filter(s2 => dot(t, s2) <= d);
1260
+ }
1261
+ return lits;
1262
+ };
1263
+ // A literal true at v and false at u (a control value first, then the direction u is furthest past v in), its
1264
+ // bound v's own (a bound just short of u would creep up one reached state at a time).
1265
+ const apart = (v, u) => {
1266
+ for (const i of ctrl)
1267
+ if (v[i] !== u[i])
1268
+ return { at: { atom: i, value: v[i] } };
1269
+ let best, gap = 0;
1270
+ for (const t of D) {
1271
+ const g2 = (dot(t, u) - dot(t, v)) / t.reduce((acc, [, c]) => acc + Math.abs(c), 0);
1272
+ if (g2 > gap)
1273
+ (gap = g2, best = { lin: { coef: t, d: dot(t, v) } });
1274
+ }
1275
+ return best;
1276
+ };
1277
+ // Literals put back from `from` until no sample is in the cube (false where a sample can't be left out).
1278
+ const outOfSamples = (c, from) => {
1279
+ for (let alive = S.filter(s2 => inCube(c, s2)); alive.length;) {
1280
+ let best, bestN = 0;
1281
+ for (const l of from) {
1282
+ if (c.includes(l))
1283
+ continue;
1284
+ let cnt = 0;
1285
+ for (const s2 of alive)
1286
+ if (!litHolds(l, s2))
1287
+ cnt++;
1288
+ if (cnt > bestN)
1289
+ (bestN = cnt, best = l);
1290
+ }
1291
+ if (!best)
1292
+ return false;
1293
+ c.push(best);
1294
+ alive = alive.filter(s2 => litHolds(best, s2));
1295
+ }
1296
+ return true;
1297
+ };
1298
+ const formOf = (c) => ({ coef: [], d: 0, cells: false, cube: c, size: 1 });
1299
+ const witnessStep = (w) => {
1300
+ const pre = stateAt(w), input = Object.fromEntries(m.inputs.map(i => [i, w[i] ?? 0]));
1301
+ try {
1302
+ return { pre, post: run.step({}, pre, input) };
1303
+ }
1304
+ catch {
1305
+ return { pre };
1306
+ }
1307
+ };
1308
+ // Is the cube's negation inductive relative to these laws (the caller's and the kinds' beside)? Its literals after
1309
+ // the step are hypotheses of their own, so the refutation's core names those it read.
1310
+ const queryWith = (c, frame) => {
1311
+ const f = formOf(c), ls = [...given, ...frame, lawFor(f)], mm = forLaws(ls).m;
1312
+ const g = obligations(mm, ls, {}, ls.length - 1)[1], last = g.hyps.at(-1);
1313
+ 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;
1314
+ const tails = inner ?? [last], hyps = [...g.hyps.slice(0, -1), ...tails], base = hyps.length - tails.length;
1315
+ const out = budgeted(joinCubeMs, until2 => growCdcl({ name: 'a cube', hyps }, new Map(), { nodes: 0, until: until2 }, { model: true, core: true }));
1316
+ if ('tree' in out)
1317
+ return { ok: true, core: new Set(c.map((_, j) => j)) };
1318
+ if (out.why === REFUTED)
1319
+ 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)) };
1320
+ if (out.stuck === 'sat' && out.witness)
1321
+ return { ok: false, ...witnessStep(out.witness) };
1322
+ return undefined;
1323
+ };
1324
+ // A counterexample to a caller's law no candidate rules out: its cube (its control state and the bounds that keep
1325
+ // the samples out), blocked relative to the set (the set assumed before the step, and the cube's own negation, as
1326
+ // IC3's relative induction), its literals after the step those the refutation read (its core), the samples and the
1327
+ // start kept out. A predecessor the set allows into the cube: its own cube blocked first (a few deep), else the
1328
+ // cube made smaller to leave the predecessor's successor out. Each cube blocked is a form of the set (a
1329
+ // disjunction: never all its literals), which the join keeps or drops as any other.
1330
+ let cubed = 0, cubeWhy = '', cubeUntil = Infinity;
1331
+ // IC3's generalization of a cube blocked (Bradley's down, literal dropping as Een, Mishchenko and Brayton's): the
1332
+ // literals taken out a part at a time (half of them, then quarters, ..., then one by one), a part kept out where the
1333
+ // cube without it still leaves the start and the samples out and is still blocked relative to the same laws (the
1334
+ // refutation's core then cutting it further); within joinDownQueries queries. A cube's core reads most of its
1335
+ // literals where the step's terms are a chain of ifs (research/dag: a refutation's core is nearly its whole path), so
1336
+ // the core alone leaves a cube of every control value; Spacer's clauses on these tasks read two to four.
1337
+ const down = (c, frame) => {
1338
+ let cur = c, queries = 0;
1339
+ for (let part = Math.ceil(cur.length / 2); part >= 1 && queries < joinDownQueries && now() < jUntil && !stop(); part = part === 1 ? 0 : Math.ceil(part / 2)) {
1340
+ for (let i = 0; i < cur.length && cur.length > 1 && queries < joinDownQueries && now() < jUntil && !stop();) {
1341
+ const cand = [...cur.slice(0, i), ...cur.slice(i + part)];
1342
+ if (!cand.length || (initVec && inCube(cand, initVec)) || S.some(s2 => inCube(cand, s2))) {
1343
+ i += part;
1344
+ continue;
1345
+ }
1346
+ queries++;
1347
+ const r = queryWith(cand, frame);
1348
+ if (!r?.ok) {
1349
+ i += part;
1350
+ continue;
1351
+ }
1352
+ const cut = cand.filter((_, j) => r.core.has(j));
1353
+ cur = cut.length && !(initVec && inCube(cut, initVec)) && !S.some(s2 => inCube(cut, s2)) ? cut : cand;
1354
+ }
1355
+ }
1356
+ return cur;
1357
+ };
1358
+ const blockCube = (v, depth, within) => {
1359
+ let c = cubeOf(v);
1360
+ const made = [];
1361
+ if (!c)
1362
+ cubeWhy = sampled.has(vecKey(v)) ? 'a sample' : 'inside';
1363
+ // (relative to as little of the set as will do, as the join's goals are: the forms that rule out each
1364
+ // predecessor found, doubling, then the whole set)
1365
+ let ctx = [];
1366
+ for (let tries = 0; c && tries < joinCubeTries && now() < jUntil && !stop(); tries++) {
1367
+ const r = queryWith(c, [...ctx, ...made].map(lawFor).filter(l => l.name !== textOf(formOf(c))));
1368
+ if (!r) {
1369
+ cubeWhy = 'unknown';
1370
+ break;
1371
+ }
1372
+ if (r.ok) {
1373
+ const c2 = c.filter((_, j) => r.core.has(j));
1374
+ if (initVec && inCube(c2, initVec)) {
1375
+ const l = c.find(l2 => !litHolds(l2, initVec));
1376
+ if (l)
1377
+ c2.push(l);
1378
+ }
1379
+ const c3 = outOfSamples(c2, c) ? c2 : c;
1380
+ made.push(formOf(joinDown ? down(c3, [...ctx, ...made].map(lawFor).filter(l => l.name !== textOf(formOf(c3)))) : c3));
1381
+ break;
1382
+ }
1383
+ if (!r.post) {
1384
+ cubeWhy = 'no step';
1385
+ break;
1386
+ }
1387
+ const pv = vecOf(r.pre), qv = vecOf(r.post);
1388
+ const ruling = within.filter(f => !ctx.includes(f) && !holdsRow(f, { ...r.pre.scalars }));
1389
+ if (ruling.length) {
1390
+ ctx = [...ctx, ...ruling.slice(0, Math.max(joinAdd, ctx.length))];
1391
+ tries--;
1392
+ continue;
1393
+ }
1394
+ if (!inCube(c, qv)) {
1395
+ cubeWhy = 'outside';
1396
+ break;
1397
+ }
1398
+ const sub = depth > 0 && !sampled.has(vecKey(pv)) ? blockCube(pv, depth - 1, [...within, ...made]) : [];
1399
+ if (sub.length) {
1400
+ made.push(...sub);
1401
+ continue;
1402
+ }
1403
+ // (a predecessor the runs reached: its successor is reached too, a sample now)
1404
+ if (sampled.has(vecKey(pv)))
1405
+ addSample(qv);
1406
+ const l = apart(v, qv);
1407
+ if (!l) {
1408
+ cubeWhy = 'reached';
1409
+ break;
1410
+ }
1411
+ c = [...c, l];
1412
+ cubeWhy = 'tries';
1413
+ }
1414
+ return made;
1415
+ };
1112
1416
  for (;;) {
1113
1417
  if (now() > jUntil || stop()) {
1114
1418
  why = 'time';
1115
1419
  break;
1116
1420
  }
1421
+ // (once a cube is in the set, the join has a part of what is left, the search below the rest: the cubes are
1422
+ // for counterexamples no candidate rules out, which the search below rules out its own way)
1423
+ if (now() > cubeUntil) {
1424
+ why = 'cubes';
1425
+ break;
1426
+ }
1117
1427
  rounds++;
1118
1428
  set = [...formsNow(), ...extras].filter(f => !blocked.has(textOf(f)));
1119
1429
  const byText = new Map(set.map(f => [textOf(f), f]));
@@ -1145,7 +1455,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1145
1455
  // counterexample the whole set allows is one to learn from.
1146
1456
  const todoForm = callers.has(todo) ? undefined : byText.get(todo);
1147
1457
  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);
1458
+ 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
1459
  const whole = set.filter(f => f !== todoForm);
1150
1460
  let ctx = [], witness, lastStuck = '', qms = 0, settled = false;
1151
1461
  for (let attempt = 0; attempt <= joinAttempts; attempt++) {
@@ -1191,6 +1501,8 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1191
1501
  continue;
1192
1502
  }
1193
1503
  const w = witness, { params, st } = stateOf(w);
1504
+ if (todoForm?.nevers)
1505
+ neversBroken++;
1194
1506
  const input = Object.fromEntries(m.inputs.map(i => [i, w[i] ?? 0]));
1195
1507
  let post;
1196
1508
  try {
@@ -1230,6 +1542,17 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1230
1542
  if (next)
1231
1543
  tried++;
1232
1544
  opts.progress?.('join', { round: rounds, set: set.length, ms: qms, target: next ? textOf(next).slice(0, 60) : 'none' });
1545
+ if (!next && !outside && joinCubes && initVec && cubed < joinCubeMax && now() < jUntil) {
1546
+ const made = blockCube(valuesOf(pre.scalar), joinCubeDepth, set);
1547
+ opts.progress?.('join', { round: rounds, set: set.length, cubes: made.map(f => textOf(f).slice(0, 100)).join('; ') || `none: ${cubeWhy}` });
1548
+ if (made.length) {
1549
+ if (!cubed)
1550
+ cubeUntil = now() + (jUntil - now()) * joinCubeWindow;
1551
+ cubed += made.length;
1552
+ extras.push(...made);
1553
+ continue;
1554
+ }
1555
+ }
1233
1556
  if (!next) {
1234
1557
  why = 'target';
1235
1558
  break;
@@ -1335,7 +1658,8 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1335
1658
  };
1336
1659
  for (let iter = 0; iter < 300 && now() < until && !stop(); iter++) {
1337
1660
  const began = now(), wall = performance.now();
1338
- last = search([...given, ...chosen.map(lawFor)]);
1661
+ // (each law proven alone, then the set as a whole: the same goals, grown once)
1662
+ last = withTrees(() => search([...given, ...chosen.map(lawFor)]));
1339
1663
  const took = now() - began;
1340
1664
  opts.progress?.('proof', { chosen: chosen.length, goal: last.goal ?? '', stuck: last.stuck ?? '', ms: Math.round(performance.now() - wall), counted: Math.round(took) });
1341
1665
  if (last.proven && last.checked)
@@ -1400,7 +1724,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1400
1724
  return { ...last, found: [], stats: stats(samples.length, forms.length, alive.length) };
1401
1725
  }
1402
1726
  // Take out what the proof doesn't need, the last added first.
1403
- for (const f of [...chosen].reverse()) {
1727
+ for (const f of opts.minimize === false ? [] : [...chosen].reverse()) {
1404
1728
  if (now() > until || stop())
1405
1729
  break;
1406
1730
  const without = chosen.filter(g => g !== f), v = prove([...laws, ...without.map(lawFor)]);
@@ -1,4 +1,8 @@
1
1
  import { type Constraint, type Verdict } from './solver.js';
2
+ export type Rand = (k: number) => number;
3
+ export declare const seeded: (seed: number) => Rand;
4
+ export declare const walk: (t: unknown, f: (o: Record<string, unknown>) => void) => void;
5
+ export declare const walkOnce: (t: unknown, f: (o: object) => void) => void;
2
6
  export type E = {
3
7
  op: 'var';
4
8
  name: string;
@@ -192,6 +196,8 @@ export type Request = Record<string, number | ReadonlyMap<number, number>>;
192
196
  export declare const naturalIn: (v: unknown, what: string) => number;
193
197
  export declare function evalE(e: E, env: Env, st: State, m: Machine): number;
194
198
  export declare const fnValue: (fn: Fn, key: number) => number;
199
+ export declare const pairE: (a: E, b: E) => E;
200
+ export declare const argsKey: (args: E[]) => E;
195
201
  export declare function pairedArgs(key: E, n: number): E[] | undefined;
196
202
  export declare function evalC(c: C, env: Env, st: State, m: Machine): boolean;
197
203
  export declare function carriedView(m: Machine, st: State, input: Request, rename?: (map: string) => string): State;