gdp-wired 0.26.0 → 0.28.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 (44) hide show
  1. package/dist/core/accel.d.ts +24 -0
  2. package/dist/core/accel.js +557 -207
  3. package/dist/core/bmc.d.ts +4 -1
  4. package/dist/core/bmc.js +18 -15
  5. package/dist/core/cycles.d.ts +2 -0
  6. package/dist/core/cycles.js +1 -1
  7. package/dist/core/cyclic.js +17 -10
  8. package/dist/core/data.d.ts +1 -0
  9. package/dist/core/data.js +73 -18
  10. package/dist/core/discover.js +64 -25
  11. package/dist/core/dsl.js +108 -18
  12. package/dist/core/extract-check.d.ts +52 -2
  13. package/dist/core/extract-check.js +155 -104
  14. package/dist/core/extract-read.d.ts +25 -0
  15. package/dist/core/extract-read.js +55 -14
  16. package/dist/core/extract-shapes.js +94 -18
  17. package/dist/core/extract-xstate.js +16 -3
  18. package/dist/core/extract.d.ts +1 -0
  19. package/dist/core/extract.js +16 -8
  20. package/dist/core/fresh.d.ts +9 -0
  21. package/dist/core/fresh.js +91 -0
  22. package/dist/core/infer.d.ts +1 -0
  23. package/dist/core/infer.js +64 -46
  24. package/dist/core/live.d.ts +15 -0
  25. package/dist/core/live.js +317 -0
  26. package/dist/core/machine.js +0 -1
  27. package/dist/core/nonterm.d.ts +3 -1
  28. package/dist/core/nonterm.js +103 -25
  29. package/dist/core/solver.d.ts +21 -0
  30. package/dist/core/solver.js +8 -0
  31. package/dist/core/translate.js +69 -19
  32. package/dist/kernel/cdcl.js +212 -78
  33. package/dist/kernel/kernel.d.ts +17 -1
  34. package/dist/kernel/kernel.js +158 -2
  35. package/dist/kernel/prove.d.ts +30 -4
  36. package/dist/kernel/prove.js +119 -25
  37. package/dist/kernel/reader.d.ts +74 -5
  38. package/dist/kernel/reader.js +531 -75
  39. package/dist/kernel/simplex.d.ts +26 -1
  40. package/dist/kernel/simplex.js +148 -14
  41. package/dist/lean-kernel/emit.d.ts +15 -3
  42. package/dist/lean-kernel/emit.js +144 -12
  43. package/dist/lean-kernel/library.js +1 -1
  44. package/package.json +2 -2
@@ -16,9 +16,10 @@
16
16
  // then the forms a counterexample breaks, as IC3's relative induction, then all), each asked first of the CDCL
17
17
  // search for a model alone (a refutation's core: the forms it read), a counterexample the whole set allows joined in
18
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
+ // ruled out by a candidate or by a cube blocked as IC3 blocks one (its control state, the rule's own comparisons
20
+ // true there and the bounds that keep the samples out, the literals its refutation's core read, its predecessors
21
+ // blocked first), the cube first where no sample is at its control state; every goal of the cone proven, the cone
22
+ // is the answer
22
23
  // - the kernel (where the join proves nothing, as it was): the laws with the candidates chosen so far, proven one law
23
24
  // at a time; when a goal is stuck at a step, its witness is a counterexample to induction, so the candidate that
24
25
  // 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
@@ -60,17 +61,21 @@ const joinExtras = 24, joinTries = 40, joinBits = 7, joinKeys = 128, joinAttempt
60
61
  const joinNevers = env.GDP_JOIN_NEVERS !== '0';
61
62
  const joinNeversBreaks = 1;
62
63
  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).
64
+ // Cubes blocked for a counterexample to a caller's law (GDP_JOIN_CUBES=0: none), before any candidate is tried where
65
+ // no sample holds its control state, else where none rules it out: at most 48 in all, each tried 8 times, its
66
+ // predecessors blocked first 8 deep, each query's budget 2 s (counted, or wall time where timed).
65
67
  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;
68
+ const joinCubeMax = 48, joinCubeTries = 8, joinCubeDepth = 8, joinCubeMs = 2000;
69
+ // GDP_JOIN_ATOMS=0: a cube's literals at a point its control values and the samples' bounds alone (else the rule's own
70
+ // comparisons true there too).
71
+ const joinAtoms = env.GDP_JOIN_ATOMS !== '0';
69
72
  // GDP_JOIN_PRIME=0: each control state no state reached a form of its own, every value read.
70
73
  const joinPrime = env.GDP_JOIN_PRIME !== '0';
71
74
  // GDP_JOIN_DOWN=0: a blocked cube kept as its refutation's core cuts it (no literal dropped); joinDownQueries, the
72
75
  // queries a cube's generalization may ask.
73
76
  const joinDown = env.GDP_JOIN_DOWN !== '0', joinDownQueries = 24;
77
+ // GDP_INFER_HALVES=0: a cell form chosen without its equality's other half (below).
78
+ const inferHalves = env.GDP_INFER_HALVES !== '0';
74
79
  const isRule = (t) => typeof t.kindsOfState === 'function';
75
80
  // The constants a machine's expressions hold, and the factors it multiplies by.
76
81
  function constantsOf(m, laws) {
@@ -156,9 +161,6 @@ const keyValue = (cell, w) => {
156
161
  }
157
162
  return value;
158
163
  };
159
- // The linear comparisons a machine's conditions make over the state alone (its assumption, its step's conditions and the
160
- // laws), as coefficients over the atoms given (an integer atom's two parts with opposite coefficients): the directions
161
- // a bound of the join may take beside the atoms' own.
162
164
  function comparisons(m, laws, atoms, coords) {
163
165
  const lin = (e, k, out) => {
164
166
  if (e.op === 'const') {
@@ -232,13 +234,15 @@ function comparisons(m, laws, atoms, coords) {
232
234
  if (neg)
233
235
  l.delete(neg[0]);
234
236
  }
237
+ const k0 = l.get('1') ?? 0;
235
238
  l.delete('1');
236
- if ([...l.values()].some(v => v !== 0) || coef.length < 2)
239
+ if ([...l.values()].some(v => v !== 0) || !coef.length)
237
240
  return;
238
241
  const g = coef.reduce((acc, [, cc]) => gcd(acc, cc), 0), t = coef.map(([i, cc]) => [i, cc / g]);
239
- if (t[0][1] < 0)
240
- t.forEach(p => { p[1] = -p[1]; });
241
- found.set(JSON.stringify(t), t);
242
+ const d = Math.floor((c.op === '<' ? -k0 - 1 : -k0) / g), u = t.map(([i, cc]) => [i, -cc]);
243
+ for (const r of [{ coef: t, d }, { coef: u, d: -d - 1 }, ...(c.op === '=' ? [{ coef: u, d: -d }, { coef: t, d: d - 1 }] : [])])
244
+ if (Number.isSafeInteger(r.d))
245
+ found.set(JSON.stringify(r), r);
242
246
  };
243
247
  if (m.assume)
244
248
  visitC(m.assume);
@@ -944,7 +948,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
944
948
  const pool0 = pool.slice(), ctis0 = ctis.length;
945
949
  if (joinOn && !mapNames.length && NS)
946
950
  try {
947
- const jT0 = performance.now(), jUntil = Math.min(until, now() + (until - now()) * joinShare);
951
+ const jT0 = performance.now(), jUntil = Math.min(until, now() + (until - now()) * (opts.join ?? joinShare));
948
952
  // The control state: the choice (loc) and, where they are few, the yes/nos (a program counter in bits), each of its
949
953
  // values reached a part of its own.
950
954
  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);
@@ -963,14 +967,15 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
963
967
  for (const [c1, c2] of [[1, 1], [1, -1], [-1, 1], [-1, -1]])
964
968
  out.push([[i, c1], [j, c2]]);
965
969
  const known = new Set(out.map(t => JSON.stringify(t)));
966
- for (const t of comparisons(m, laws, atoms, cs))
967
- for (const u of [t, t.map(([i, c]) => [i, -c])]) {
968
- const k2 = JSON.stringify(u);
969
- if (!known.has(k2) && out.length < 2 * cs.length + 4 * joinPairs * joinPairs + 64) {
970
- known.add(k2);
971
- out.push(u);
970
+ for (const { coef } of comparisons(m, laws, atoms, cs))
971
+ if (coef.length > 1)
972
+ for (const u of coef[0][1] > 0 ? [coef, coef.map(([i, c]) => [i, -c])] : []) {
973
+ const k2 = JSON.stringify(u);
974
+ if (!known.has(k2) && out.length < 2 * cs.length + 4 * joinPairs * joinPairs + 64) {
975
+ known.add(k2);
976
+ out.push(u);
977
+ }
972
978
  }
973
- }
974
979
  return out;
975
980
  };
976
981
  const dirs = directions(coords);
@@ -1230,10 +1235,17 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1230
1235
  return { scalars: sc, maps: {} };
1231
1236
  };
1232
1237
  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).
1238
+ // The cube of a point the samples leave out: its control literals and the rule's own comparisons true there (where
1239
+ // no sample is, a location the runs never reached, a cube of its control values alone isn't blocked: its
1240
+ // predecessors take it back to the samples; the comparisons are what a predecessor's guards say, as Spacer's
1241
+ // projections read them), then the direction that leaves out the most samples still in, its bound as weak as
1242
+ // leaves them out, until none is in (undefined: none leaves out the rest).
1243
+ const ruleLits = joinAtoms ? comparisons(m, laws, atoms, lc).map(lin => ({ lin })) : [];
1235
1244
  const cubeOf = (v) => {
1236
1245
  const lits = ctrl.map(i => ({ at: { atom: i, value: v[i] } }));
1246
+ for (const l of ruleLits)
1247
+ if (litHolds(l, v))
1248
+ lits.push(l);
1237
1249
  let alive = S.filter(s2 => inCube(lits, s2));
1238
1250
  while (alive.length) {
1239
1251
  let best = -1, bestN = 0;
@@ -1308,7 +1320,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1308
1320
  // Is the cube's negation inductive relative to these laws (the caller's and the kinds' beside)? Its literals after
1309
1321
  // the step are hypotheses of their own, so the refutation's core names those it read.
1310
1322
  const queryWith = (c, frame) => {
1311
- const f = formOf(c), ls = [...given, ...frame, lawFor(f)], mm = forLaws(ls).m;
1323
+ const f = formOf(c), own = lawFor(f), names2 = new Set([own.name]), ls = [...given, ...frame.filter(l => !names2.has(l.name) && !!names2.add(l.name)), own], mm = forLaws(ls).m;
1312
1324
  const g = obligations(mm, ls, {}, ls.length - 1)[1], last = g.hyps.at(-1);
1313
1325
  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
1326
  const tails = inner ?? [last], hyps = [...g.hyps.slice(0, -1), ...tails], base = hyps.length - tails.length;
@@ -1321,13 +1333,13 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1321
1333
  return { ok: false, ...witnessStep(out.witness) };
1322
1334
  return undefined;
1323
1335
  };
1324
- // A counterexample to a caller's law no candidate rules out: its cube (its control state and the bounds that keep
1336
+ // A counterexample to a caller's law: its cube (its control state, the rule's comparisons and the bounds that keep
1325
1337
  // the samples out), blocked relative to the set (the set assumed before the step, and the cube's own negation, as
1326
1338
  // IC3's relative induction), its literals after the step those the refutation read (its core), the samples and the
1327
1339
  // start kept out. A predecessor the set allows into the cube: its own cube blocked first (a few deep), else the
1328
1340
  // cube made smaller to leave the predecessor's successor out. Each cube blocked is a form of the set (a
1329
1341
  // disjunction: never all its literals), which the join keeps or drops as any other.
1330
- let cubed = 0, cubeWhy = '', cubeUntil = Infinity;
1342
+ let cubed = 0, cubeWhy = '';
1331
1343
  // IC3's generalization of a cube blocked (Bradley's down, literal dropping as Een, Mishchenko and Brayton's): the
1332
1344
  // literals taken out a part at a time (half of them, then quarters, ..., then one by one), a part kept out where the
1333
1345
  // cube without it still leaves the start and the samples out and is still blocked relative to the same laws (the
@@ -1418,12 +1430,6 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1418
1430
  why = 'time';
1419
1431
  break;
1420
1432
  }
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
- }
1427
1433
  rounds++;
1428
1434
  set = [...formsNow(), ...extras].filter(f => !blocked.has(textOf(f)));
1429
1435
  const byText = new Map(set.map(f => [textOf(f), f]));
@@ -1522,9 +1528,22 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1522
1528
  }
1523
1529
  if (outside || breaks(params, post)) {
1524
1530
  // the caller's law broken from a state the set allows: a candidate false there and at every state reached, the
1525
- // one false at the most such states (then the smallest), or one made from it (fromCti)
1531
+ // one false at the most such states (then the smallest), or one made from it (fromCti); else its cube blocked,
1532
+ // as IC3 blocks one. Where no sample holds its control state (the samples say nothing of it) the cube comes first.
1526
1533
  negs.push(pre);
1527
1534
  ctis.push(pre);
1535
+ const pv = valuesOf(pre.scalar), alone = !S.some(s2 => ctrl.every(i => s2[i] === pv[i]));
1536
+ const cube = () => {
1537
+ if (outside || !joinCubes || !initVec || cubed >= joinCubeMax)
1538
+ return false;
1539
+ const made = blockCube(pv, joinCubeDepth, set), fresh = made.filter((f, i) => !set.some(g2 => textOf(g2) === textOf(f)) && made.findIndex(g2 => textOf(g2) === textOf(f)) === i);
1540
+ opts.progress?.('join', { round: rounds, set: set.length, cubes: made.map(f => textOf(f).slice(0, 100)).join('; ') || `none: ${cubeWhy}` });
1541
+ cubed += fresh.length;
1542
+ extras.push(...fresh);
1543
+ return fresh.length > 0;
1544
+ };
1545
+ if (alone && cube())
1546
+ continue;
1528
1547
  const pick = (fs) => { let bestF, score = -Infinity; for (const f of fs) {
1529
1548
  if (f.cells || f.cong || extras.includes(f) || blocked.has(textOf(f)) || holdsAt(f, pre) || !reached.every(p2 => holdsAt(f, p2)))
1530
1549
  continue;
@@ -1542,17 +1561,8 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1542
1561
  if (next)
1543
1562
  tried++;
1544
1563
  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
- }
1564
+ if (!next && !alone && cube())
1565
+ continue;
1556
1566
  if (!next) {
1557
1567
  why = 'target';
1558
1568
  break;
@@ -1656,6 +1666,8 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1656
1666
  forget();
1657
1667
  return whole;
1658
1668
  };
1669
+ // A cell form's mirror, −Σ ≤ −d beside Σ ≤ d under the same guard (its text).
1670
+ const mirrorText = (f) => (!f.cells || f.mod || f.cong || f.never || f.nevers || f.cube || f.unreachable || f.also || !f.coef.length ? undefined : textOf({ ...f, coef: f.coef.map(([i, c]) => [i, -c]), d: -f.d }));
1659
1671
  for (let iter = 0; iter < 300 && now() < until && !stop(); iter++) {
1660
1672
  const began = now(), wall = performance.now();
1661
1673
  // (each law proven alone, then the set as a whole: the same goals, grown once)
@@ -1691,8 +1703,14 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1691
1703
  next = best(p);
1692
1704
  opts.progress?.('cti', { forms: made.length, ms: Math.round(performance.now() - t) });
1693
1705
  }
1706
+ // (a cell form chosen with its mirror where that is alive: the equality both halves state at every key, neither
1707
+ // inductive without the other, as the real-world corpus's Timelock and blnk need; on CHC's scalar forms, measured,
1708
+ // it cost s_split tasks, so cell forms only)
1694
1709
  if (next) {
1695
1710
  chosen.push(next);
1711
+ const mt = inferHalves ? mirrorText(next) : undefined, mirror = mt && pool.find(g => !chosen.includes(g) && textOf(g) === mt);
1712
+ if (mirror)
1713
+ chosen.push(mirror);
1696
1714
  continue;
1697
1715
  }
1698
1716
  // Stuck with no counterexample on a goal not a candidate's: the last candidate made it harder, so it goes.
@@ -0,0 +1,15 @@
1
+ import { type Law, type Machine, type Rand, type Request } from './machine.js';
2
+ import { type Liveness } from '../kernel/kernel.js';
3
+ import { type LeadsVerdict } from './cycles.js';
4
+ import { inferLaws } from './infer.js';
5
+ type Env = Record<string, number>;
6
+ export type Draws = {
7
+ params: (rand: Rand, bound: number) => Env;
8
+ input: (rand: Rand, bound: number, ps: Env) => Request;
9
+ state?: (rand: Rand, bound: number) => Env;
10
+ rule?: Parameters<typeof inferLaws>[0];
11
+ };
12
+ export declare function leadsByTerms(m: Machine, laws: Law[], l: Liveness, draws: Draws, opts?: {
13
+ ms?: number;
14
+ }): LeadsVerdict;
15
+ export {};
@@ -0,0 +1,317 @@
1
+ // "From leads to to" with no rank stated, where the rank fitted to the runs (core/cycles.ts's findLeadsTo) is not the
2
+ // one: a rank made of the rule's own terms, chosen by the steps it must lower. Its components are drawn from
3
+ // - the control: a variable its kind bounds (a chart's state, a status, a flag), ranked by the steps between its
4
+ // values (each strongly connected set of values one level, the levels in the order the steps go);
5
+ // - the distances the rule compares: for each comparison a < b or a <= b of its guards, its steps, the law and the
6
+ // helpful requests (the request's own inputs replaced by what it sends), over the state, the params and the cells
7
+ // they read, the distance until it changes (b ∸ a, a + 1 ∸ b and the like): a counter up to a limit, a clock up to a
8
+ // deadline, a timestamp's distance from the time;
9
+ // - a state variable alone, and the constant 0.
10
+ // The steps are taken from runs from the start and from random states the laws allow, where `from` holds and `to`
11
+ // doesn't (the kernel's goals are about every such state, reached or not): a helpful request's in its region must
12
+ // lower the rank, and so must any other that leaves a region it was in; the rest must not raise it. Components are
13
+ // chosen in order, each one no step raises that lowers the most of those left. The rank is then the kernel's
14
+ // (proveLiveness), with the invariants inferLaws finds where its goals need some. Nothing new is trusted.
15
+ import { evalC, evalE, interpret, seeded, walk } from "./machine.js";
16
+ import { livenessHelpful, livenessParts, substE } from "../kernel/kernel.js";
17
+ import { clock, proveLiveness, withDeadline } from "../kernel/prove.js";
18
+ import { allowed, watch } from "./watch.js";
19
+ import { showE } from "./cycles.js";
20
+ import { inferLaws } from "./infer.js";
21
+ const id = (t) => JSON.stringify(t);
22
+ const k = (value) => ({ op: 'const', value }), v = (name) => ({ op: 'var', name });
23
+ const sub = (a, b) => ({ op: 'sub', a, b }), plus1 = (a) => ({ op: 'add', a, b: k(1) });
24
+ // The comparisons a condition or term makes, each side a term.
25
+ function comparisons(t) {
26
+ const out = [];
27
+ walk(t, o => { if ((o.op === '<' || o.op === '<=' || o.op === '=') && typeof o.a === 'object' && typeof o.b === 'object')
28
+ out.push([o.a, o.b]); });
29
+ // (a side that decides a flag or a quantifier is no term of the state)
30
+ return out.filter(p => { let plain = true; walk(p, o => { if (o.op === 'flag' || o.op === 'all')
31
+ plain = false; }); return plain; });
32
+ }
33
+ const reads = (e, names) => { let hit = false; walk(e, o => { if (o.op === 'var' && names.includes(o.name))
34
+ hit = true; }); return hit; };
35
+ const constant = (e) => { let c = true; walk(e, o => { if (o.op === 'var' || o.op === 'get')
36
+ c = false; }); return c; };
37
+ // The candidate components that don't depend on the steps: the distances, each variable alone.
38
+ function distances(m, l) {
39
+ const helpful = livenessHelpful(l), atoms = [...comparisons([m.step, m.assume, l.from, l.to, helpful.map(h => h.when)])];
40
+ // a guard as the helpful request meets it: its inputs replaced by the terms it sends
41
+ for (const h of helpful) {
42
+ const s = { vars: h.request, maps: {}, flags: {} };
43
+ for (const [a, b] of comparisons([m.step, m.assume]))
44
+ atoms.push([substE(a, s), substE(b, s)]);
45
+ }
46
+ const out = new Map();
47
+ const add = (e) => { if (!constant(e) && !reads(e, m.inputs))
48
+ out.set(id(e), e); };
49
+ for (const [a, b] of atoms) {
50
+ if (reads(a, m.inputs) || reads(b, m.inputs) || constant(a) && constant(b))
51
+ continue;
52
+ for (const e of [sub(b, a), sub(a, b), sub(plus1(a), b), sub(plus1(b), a)])
53
+ add(e);
54
+ }
55
+ for (const x of Object.keys(m.state))
56
+ add(v(x));
57
+ return [...out.values()];
58
+ }
59
+ // A variable's values ranked by the steps between them: each strongly connected set one level, a level above every one
60
+ // a step goes to from it (Tarjan's components, then the longest path down).
61
+ function controlRank(x, steps) {
62
+ const graph = new Map();
63
+ const node = (a) => graph.get(a) ?? (graph.set(a, new Set()), graph.get(a));
64
+ for (const st of steps) {
65
+ const a = st.s.scalars[x], b = st.t.scalars[x];
66
+ node(b);
67
+ if (a !== b)
68
+ node(a).add(b);
69
+ }
70
+ if (graph.size < 2)
71
+ return undefined;
72
+ const index = new Map(), low = new Map(), comp = new Map(), stack = [];
73
+ let n = 0, c = 0;
74
+ const visit = (a) => {
75
+ index.set(a, n);
76
+ low.set(a, n++);
77
+ stack.push(a);
78
+ for (const b of graph.get(a)) {
79
+ if (!index.has(b)) {
80
+ visit(b);
81
+ low.set(a, Math.min(low.get(a), low.get(b)));
82
+ }
83
+ else if (!comp.has(b))
84
+ low.set(a, Math.min(low.get(a), index.get(b)));
85
+ }
86
+ if (low.get(a) === index.get(a)) {
87
+ let b;
88
+ do {
89
+ b = stack.pop();
90
+ comp.set(b, c);
91
+ } while (b !== a);
92
+ c++;
93
+ }
94
+ };
95
+ for (const a of graph.keys())
96
+ if (!index.has(a))
97
+ visit(a);
98
+ const level = new Map();
99
+ // (Tarjan numbers a component after every one it reaches: so in that order each level is known before it is needed)
100
+ const members = Array.from({ length: c }, (_, i) => [...graph.keys()].filter(a => comp.get(a) === i));
101
+ for (const ms of members) {
102
+ let lv = 0;
103
+ for (const a of ms)
104
+ for (const b of graph.get(a))
105
+ if (comp.get(b) !== comp.get(a))
106
+ lv = Math.max(lv, level.get(comp.get(b)) + 1);
107
+ level.set(comp.get(ms[0]), lv);
108
+ }
109
+ const values = [...graph.keys()].sort((p, q) => p - q).map(a => [a, level.get(comp.get(a))]);
110
+ if (values.every(([, lv]) => lv === 0))
111
+ return undefined;
112
+ return values.slice(0, -1).reduceRight((rest, [a, lv]) => ({ op: 'if', c: { op: '=', a: v(x), b: k(a) }, then: k(lv), else: rest }), k(values.at(-1)[1]));
113
+ }
114
+ // The variables a kind law bounds by a small constant (x < c, x <= c).
115
+ const bounded = (m, laws) => {
116
+ const out = new Set();
117
+ for (const law of laws)
118
+ if (!law.forall)
119
+ walk(law.holds, o => {
120
+ const a = o.a, b = o.b;
121
+ if ((o.op === '<' || o.op === '<=') && a?.op === 'var' && a.name in m.state && b?.op === 'const' && b.value <= 32)
122
+ out.add(a.name);
123
+ });
124
+ return [...out];
125
+ };
126
+ export function leadsByTerms(m, laws, l, draws, opts = {}) {
127
+ const t0 = clock(), until = t0 + (opts.ms ?? 10_000), rand = seeded(31), run = interpret(m), helpful = livenessHelpful(l);
128
+ const env = (ps, st) => ({ ...ps, ...st.scalars });
129
+ const holds = (c, ps, st) => { try {
130
+ return evalC(c, env(ps, st), st, m);
131
+ }
132
+ catch {
133
+ return undefined;
134
+ } };
135
+ const pending = (ps, st) => holds(l.from, ps, st) === true && holds(l.to, ps, st) === false;
136
+ const regions = (ps, st) => helpful.map(h => holds(h.when, ps, st) === true);
137
+ const steps = [];
138
+ // One step from a pending state: a helpful request in its region (its named inputs at the state, the rest drawn), or
139
+ // any request; kept where it stays pending.
140
+ const take = (ps, st, bound, h) => {
141
+ for (let tries = 0; tries < 20; tries++) {
142
+ try {
143
+ const input = draws.input(rand, bound, ps);
144
+ if (h !== undefined)
145
+ for (const [x, t] of Object.entries(helpful[h].request))
146
+ input[x] = evalE(t, env(ps, st), st, m);
147
+ if (!allowed(m, run, ps, st, input))
148
+ continue;
149
+ const next = run.step(ps, st, input);
150
+ if (pending(ps, st) && pending(ps, next)) {
151
+ const was = regions(ps, st), now = regions(ps, next);
152
+ steps.push({ ps, s: st, t: next, lower: h !== undefined || was.some((r, i) => r && !now[i]) });
153
+ }
154
+ return next;
155
+ }
156
+ catch { /* refused: another */ }
157
+ }
158
+ return undefined;
159
+ };
160
+ const pick = (ps, st) => { const rs = regions(ps, st).flatMap((r, i) => (r ? [i] : [])); return rs.length && rand(2) ? rs[rand(rs.length)] : undefined; };
161
+ const sampleUntil = t0 + Math.min(1500, (until - t0) / 8);
162
+ // runs from the start
163
+ for (const bound of [2, 4, 8])
164
+ for (let trial = 0; trial < 20 && clock() < sampleUntil; trial++) {
165
+ let ps, st;
166
+ try {
167
+ ps = draws.params(rand, bound);
168
+ if (m.pre && !evalC(m.pre, ps, { scalars: {}, maps: {} }, m))
169
+ continue;
170
+ st = run.init(ps);
171
+ }
172
+ catch {
173
+ continue;
174
+ }
175
+ for (let turn = 0; turn < 80 && st; turn++)
176
+ st = pending(ps, st) ? take(ps, st, bound, pick(ps, st)) : take(ps, st, bound);
177
+ }
178
+ // random states the laws allow
179
+ if (!m.history)
180
+ for (let trial = 0, found = 0; trial < 4000 && found < 300 && clock() < sampleUntil; trial++) {
181
+ const bound = 4;
182
+ let ps;
183
+ try {
184
+ ps = draws.params(rand, bound);
185
+ if (m.pre && !evalC(m.pre, ps, { scalars: {}, maps: {} }, m))
186
+ continue;
187
+ }
188
+ catch {
189
+ continue;
190
+ }
191
+ const scalars = { ...Object.fromEntries(Object.keys(m.state).map(n => [n, rand(8)])), ...(draws.state?.(rand, bound) ?? {}) };
192
+ const st = { scalars, maps: Object.fromEntries(Object.keys(m.maps ?? {}).map(n => [n, new Map(Array.from({ length: rand(3) }, () => [rand(bound + 1), rand(bound + 1)]))])) };
193
+ try {
194
+ if (!pending(ps, st) || !laws.every(law => watch(m, run, law, ps, bound).start(st)))
195
+ continue;
196
+ }
197
+ catch {
198
+ continue;
199
+ }
200
+ found++;
201
+ take(ps, st, bound, pick(ps, st));
202
+ }
203
+ // A goal's counterexample as a step (the kernel names a cell by its map and its key's linear form, `M[d:1,1:2]`): the
204
+ // state, params and request it gives (0 where it gives none), stepped by the interpreter. The step a goal fails at
205
+ // is one the rank must allow; so the ranks are chosen again with it, a few rounds.
206
+ const fromWitness = (w, goal) => {
207
+ const ps = Object.fromEntries(m.params.map(p => [p, w[p] ?? 0])), maps = Object.fromEntries(Object.keys(m.maps ?? {}).map(n => [n, new Map()]));
208
+ for (const [name, x] of Object.entries(w)) {
209
+ const at = name.indexOf('[');
210
+ if (at < 0 || !name.endsWith(']') || !maps[name.slice(0, at)])
211
+ continue;
212
+ let key = 0;
213
+ for (const part of name.slice(at + 1, -1).split(',')) {
214
+ const c = part.lastIndexOf(':'), n = part.slice(0, c);
215
+ key += Number(part.slice(c + 1)) * (n === '1' ? 1 : w[n] ?? 0);
216
+ }
217
+ if (Number.isInteger(key) && key >= 0)
218
+ maps[name.slice(0, at)].set(key, x);
219
+ }
220
+ const st = { scalars: Object.fromEntries(Object.keys(m.state).map(x => [x, w[x] ?? 0])), maps };
221
+ const input = Object.fromEntries(m.inputs.map(i => [i, w[i] ?? 0]));
222
+ try {
223
+ if (!pending(ps, st) || !allowed(m, run, ps, st, input))
224
+ return false;
225
+ const next = run.step(ps, st, input);
226
+ if (!pending(ps, next))
227
+ return false;
228
+ const was = regions(ps, st), now = regions(ps, next), h = /helpful request (\d+)/.exec(goal);
229
+ steps.push({ ps, s: st, t: next, lower: !!h || was.some((r, i) => r && !now[i]) });
230
+ return true;
231
+ }
232
+ catch {
233
+ return false;
234
+ }
235
+ };
236
+ if (!steps.length)
237
+ return { proven: false, checked: false, why: 'no step sampled from a state where it is pending' };
238
+ // The components, then the ranks: each component the one no step raises that lowers the most steps left to lower.
239
+ const value = (e, ps, st) => { try {
240
+ return evalE(e, env(ps, st), st, m);
241
+ }
242
+ catch {
243
+ return NaN;
244
+ } };
245
+ const fixed = distances(m, l), text = (rank) => `(${rank.map(showE).join(', ')})`, tried = new Set();
246
+ let last, best;
247
+ for (let round = 0; round < 6 && until - clock() > 200; round++) {
248
+ const cands = [...bounded(m, laws).map(x => controlRank(x, steps)).filter((e) => !!e), ...fixed];
249
+ const vals = cands.map(e => steps.map(st => [value(e, st.ps, st.s), value(e, st.ps, st.t)]));
250
+ const build = (banned) => {
251
+ let left = steps.map((_, i) => i);
252
+ const rank = [];
253
+ for (let turn = 0; turn < 3 && left.some(i => steps[i].lower); turn++) {
254
+ let pick = -1, most = 0;
255
+ for (let c = 0; c < cands.length; c++) {
256
+ if (banned.has(c) || rank.includes(c))
257
+ continue;
258
+ const vs = vals[c];
259
+ if (!left.every(i => vs[i][1] <= vs[i][0]))
260
+ continue;
261
+ const n = left.filter(i => steps[i].lower && vs[i][1] < vs[i][0]).length;
262
+ if (n > most)
263
+ (pick = c, most = n);
264
+ }
265
+ if (pick < 0)
266
+ return undefined;
267
+ rank.push(pick);
268
+ left = left.filter(i => !(vals[pick][i][1] < vals[pick][i][0]));
269
+ }
270
+ return left.some(i => steps[i].lower) ? undefined : (rank.length ? rank.map(c => cands[c]) : [k(0)]);
271
+ };
272
+ // the first rank, then those without its first component
273
+ const ranks = [], first = build(new Set());
274
+ if (first)
275
+ ranks.push(first);
276
+ for (let c = 0; c < cands.length && ranks.length < 3 && first; c++) {
277
+ if (id(cands[c]) !== id(first[0]))
278
+ continue;
279
+ const r = build(new Set([c]));
280
+ if (r && !ranks.some(x => id(x) === id(r)))
281
+ ranks.push(r);
282
+ }
283
+ const fresh = ranks.filter(r => !tried.has(id(r)));
284
+ if (!fresh.length)
285
+ break;
286
+ let learnt = false;
287
+ for (const rank of fresh) {
288
+ const ms = until - clock();
289
+ if (ms < 200)
290
+ break;
291
+ tried.add(id(rank));
292
+ best ??= rank;
293
+ last = withDeadline(clock() + ms / 3, () => proveLiveness(m, laws, { ...l, rank }));
294
+ if (last.proven && last.checked)
295
+ return { proven: true, checked: true, rank, laws: [], found: { rank: text(rank), laws: [] } };
296
+ if (last.failed?.witness && fromWitness(last.failed.witness, last.failed.goal))
297
+ learnt = true;
298
+ }
299
+ if (!learnt)
300
+ break;
301
+ }
302
+ if (!best)
303
+ return { proven: false, checked: false, why: `no rank of the rule's terms that the ${steps.length} steps sampled allow` };
304
+ // the first rank with the invariants its goals need
305
+ const rank = best, lv = { ...l, rank }, ms = until - clock();
306
+ if (ms > 300) {
307
+ const { stay, cover, helps } = livenessParts(m, lv), inf = inferLaws(draws.rule ?? m, laws, [stay, cover, ...helps], { ms });
308
+ const kept = inf.found.filter(f => !f.law.forall && !f.law.keys?.length), more = kept.map(f => f.law);
309
+ if (inf.proven && more.length) {
310
+ const again = withDeadline(until + 5000, () => proveLiveness(m, [...laws, ...more], lv));
311
+ if (again.proven && again.checked)
312
+ return { proven: true, checked: true, rank, laws: more, found: { rank: text(rank), laws: kept.map(f => f.text) } };
313
+ }
314
+ }
315
+ const failed = last?.failed ? { goal: last.failed.goal, stuck: last.failed.stuck, ...(last.failed.witness ? { witness: last.failed.witness } : {}) } : {};
316
+ return { proven: false, checked: false, rank, found: { rank: text(rank), laws: [] }, ...failed, why: `rank ${text(rank)} of the rule's terms, from ${steps.length} steps sampled; the kernel's goals not proven with it` };
317
+ }
@@ -2,7 +2,6 @@
2
2
  // - interpret / compileJs: the runtime, as an interpreter and as generated JavaScript
3
3
  // - prove: each law by induction (holds at the start, one step preserves it), with every case decided by solver.ts
4
4
  // - search: real counterexample traces from the start, by bounded enumeration of short request sequences
5
- // - strengthen (invariant.ts): candidate invariants dropped until the rest are inductive (Houdini)
6
5
  // Arithmetic is linear: +, −, × by a constant, min, max, if. Maps are naturals indexed by naturals, every cell starting
7
6
  // at the same value; a law about a map holds for every key x, and is proven at one arbitrary x (with the law assumed at
8
7
  // every other key the step reads).
@@ -1,5 +1,5 @@
1
1
  import { type C, type E } from './machine.js';
2
- import { type Loop, type Recur } from '../kernel/kernel.js';
2
+ import { type Loop, type Recur, type RecurCases } from '../kernel/kernel.js';
3
3
  export type NeverEndsOptions = {
4
4
  ms?: number;
5
5
  seed?: number;
@@ -8,11 +8,13 @@ export type NeverEndsOptions = {
8
8
  counted?: number;
9
9
  accel?: number;
10
10
  extend?: number;
11
+ cases?: boolean;
11
12
  };
12
13
  export type NeverEndsVerdict = {
13
14
  proven: boolean;
14
15
  checked: boolean;
15
16
  recur?: Recur;
17
+ cases?: RecurCases;
16
18
  by?: 'lasso' | 'policy lasso' | 'recurrent set' | 'accelerated';
17
19
  why?: string;
18
20
  lasso?: {