gdp-wired 0.23.0 → 0.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +12 -2
  2. package/dist/core/bmc.d.ts +13 -2
  3. package/dist/core/bmc.js +390 -18
  4. package/dist/core/cycles.d.ts +23 -0
  5. package/dist/core/cycles.js +104 -54
  6. package/dist/core/data.d.ts +9 -0
  7. package/dist/core/data.js +352 -121
  8. package/dist/core/discover.js +8 -3
  9. package/dist/core/dsl.d.ts +7 -2
  10. package/dist/core/dsl.js +47 -9
  11. package/dist/core/extract-check.d.ts +77 -0
  12. package/dist/core/extract-check.js +785 -0
  13. package/dist/core/extract-ir.d.ts +139 -0
  14. package/dist/core/extract-ir.js +198 -0
  15. package/dist/core/extract-print.d.ts +30 -0
  16. package/dist/core/extract-print.js +426 -0
  17. package/dist/core/extract-read.d.ts +298 -0
  18. package/dist/core/extract-read.js +1298 -0
  19. package/dist/core/extract-shapes.d.ts +13 -0
  20. package/dist/core/extract-shapes.js +993 -0
  21. package/dist/core/extract-xstate.d.ts +34 -0
  22. package/dist/core/extract-xstate.js +320 -0
  23. package/dist/core/extract.d.ts +31 -0
  24. package/dist/core/extract.js +249 -0
  25. package/dist/core/kind.d.ts +30 -0
  26. package/dist/core/kind.js +81 -0
  27. package/dist/core/relation.js +7 -4
  28. package/dist/core/xstate.d.ts +6 -0
  29. package/dist/core/xstate.js +70 -12
  30. package/dist/kernel/cdcl.d.ts +10 -0
  31. package/dist/kernel/cdcl.js +291 -241
  32. package/dist/kernel/kernel.d.ts +15 -0
  33. package/dist/kernel/kernel.js +32 -0
  34. package/dist/kernel/prove.js +14 -3
  35. package/dist/kernel/reader.d.ts +14 -0
  36. package/dist/kernel/reader.js +102 -14
  37. package/dist/lean-kernel/emit.d.ts +28 -1
  38. package/dist/lean-kernel/emit.js +56 -15
  39. package/dist/lean-kernel/library.js +2 -1
  40. package/package.json +12 -3
@@ -2,8 +2,8 @@ import { compileFunction, evalC as evalMC, evalE as evalME, fnValue, interpret,
2
2
  import { check, livenessHelpful, livenessParts, loopLiveness, loopMachine, loopObligations, substC, substE } from "../kernel/kernel.js";
3
3
  import { checkCyclic, factsAvoid, lexLt } from "../kernel/cyclic.js";
4
4
  import { proveCyclic } from "./cyclic.js";
5
- import { solve } from "./solver.js";
6
- import { grow, proveLaws, proveLiveness, proveStepLaws, withDeadline } from "../kernel/prove.js";
5
+ import { solve, work } from "./solver.js";
6
+ import { clock, grow, proveLaws, proveLiveness, proveStepLaws, withDeadline } from "../kernel/prove.js";
7
7
  import { inferLaws } from "./infer.js";
8
8
  import { generators, houdini, relationOf } from "./relation.js";
9
9
  // --- terms ----------------------------------------------------------------------------------------------------------
@@ -402,7 +402,7 @@ function lp(must, pool, until, scale = 1, signs = [true, false], whole = false)
402
402
  const b = x.startsWith('b:') ? (wide ? bound * scale : bound) : bound;
403
403
  rows.push({ [x]: 1, 1: -b }, natural ? { [x]: -1 } : { [x]: -1, 1: -b });
404
404
  }
405
- for (let round = 0; round < 40 && performance.now() < until; round++) {
405
+ for (let round = 0; round < 40 && clock() < until; round++) {
406
406
  const out = solve(rows.map(lin => ({ lin, label: '' })), 4000);
407
407
  if (out.kind !== 'sat')
408
408
  break;
@@ -443,7 +443,9 @@ const qlt = (a, b) => a.n * b.d < b.n * a.d;
443
443
  function simplex(T, basis, cost, open, until) {
444
444
  const cols = cost.length;
445
445
  for (let it = 0; it < 5000; it++) {
446
- if (performance.now() > until)
446
+ // (each pivot counted as work, as the solver's rows are: a counted search's clock runs while it solves)
447
+ work.n += 1 + ((T.length * cols) >> 6);
448
+ if (clock() > until)
447
449
  return false;
448
450
  let enter = -1;
449
451
  for (let j = 0; j < cols && enter < 0; j++) {
@@ -563,7 +565,7 @@ function exactLp(must, pool, until, whole = false) {
563
565
  if (x !== '1')
564
566
  m = Math.max(m, Math.abs(l[x])); return m; };
565
567
  const sizes = pool.map(size), half = sizes.reduce((a, b) => Math.max(a, b), 0) / 2, small = whole ? pool : pool.filter((_, i) => sizes[i] <= half), rows = [...must];
566
- for (let round = 0; round < 40 && performance.now() < until; round++) {
568
+ for (let round = 0; round < 40 && clock() < until; round++) {
567
569
  const w = exactSolve(rows, until);
568
570
  if (!w)
569
571
  return undefined;
@@ -598,13 +600,13 @@ function lexRanks(idx, nodes, samples, edges, name, until, onEdges = false, weak
598
600
  let left = [...new Map(edges.map(e => { const l = delta(e); return [id(l), l]; })).values()];
599
601
  let keep = [...new Map(weak.map(e => { const l = delta(e); return [id(l), l]; })).values()].filter(l => !left.some(x => id(x) === id(l)));
600
602
  const comps = [];
601
- while (left.length && comps.length < 4 && performance.now() < until) {
603
+ while (left.length && comps.length < 4 && clock() < until) {
602
604
  let sum = {};
603
605
  const strict = (l) => valueAt(l, sum) < 0;
604
606
  // One try per pattern of signs (which unknowns an edge raises and lowers): edges alike drop alike, mostly.
605
607
  const tried = new Set(), sign = (l) => id(Object.keys(l).filter(x => x !== '1').sort().map(x => `${x}${Math.sign(l[x])}`));
606
608
  for (const l of left) {
607
- if (strict(l) || performance.now() > until || tried.has(sign(l)) || tried.size > 40)
609
+ if (strict(l) || clock() > until || tried.has(sign(l)) || tried.size > 40)
608
610
  continue;
609
611
  tried.add(sign(l));
610
612
  const w = lp([plus(l, { 1: 1 })], [...left, ...keep, ...points], until, scale);
@@ -628,11 +630,20 @@ function lexRanks(idx, nodes, samples, edges, name, until, onEdges = false, weak
628
630
  }
629
631
  const gcd = (a, b) => (b === 0 ? a : gcd(b, a % b));
630
632
  // The same over named naturals and the edges of runs alone (core/data.ts: a recursive function's calls, each from its
631
- // parameters' sizes to its arguments'): each component's coefficient per variable and its constant.
633
+ // parameters' sizes to its arguments'): each component's coefficient per variable and its constant. Several nodes (a
634
+ // ring of functions calling each other, each its own names; `nodes`), each its own coefficients and constant per
635
+ // component (a rank per location: (size(x), 1) at one function, (size(x), 0) at the one it calls with x). Its budget,
636
+ // `ms`, is read on the shared clock (kernel/prove.ts's `clock`): counted work inside a counted search, its pivots counted
637
+ // as the solver's rows are, so a counted search's verdict doesn't depend on the machine's speed.
632
638
  export function ranksOfRuns(vars, points, edges, ms = 1000) {
633
- const node = { name: 'runs', hyps: [], concl: yes, vars, level: 0, given: true };
634
- const { comps, left } = lexRanks([0], [node], [points.map(env => ({ env, calls: new Set() }))], edges.map(e => ({ from: 0, to: 0, s: e.s, t: e.t })), shared, performance.now() + ms);
635
- return { comps: comps.map(c => ({ coef: Object.fromEntries(vars.map((x, j) => [x, c[shared(0, j)] ?? 0])), c: c[shared(0, 'b')] ?? 0 })), left };
639
+ const r = ranksOfCalls([vars], points.map(env => ({ node: 0, env })), edges.map(e => ({ from: 0, to: 0, s: e.s, t: e.t })), ms);
640
+ return { comps: r.comps.map(c => c[0]), left: r.left };
641
+ }
642
+ export function ranksOfCalls(nodes, points, edges, ms = 1000) {
643
+ const ns = nodes.map((vars, i) => ({ name: `runs ${i}`, hyps: [], concl: yes, vars, level: 0, given: true }));
644
+ const name = nodes.length === 1 ? shared : own(ns), idx = nodes.map((_, i) => i);
645
+ const { comps, left } = lexRanks(idx, ns, nodes.map((_, i) => points.filter(p => p.node === i).map(p => ({ env: p.env, calls: new Set() }))), edges, name, clock() + ms);
646
+ return { comps: comps.map(c => ns.map((nd, n) => ({ coef: Object.fromEntries(nd.vars.map((x, j) => [x, c[name(n, j)] ?? 0])), c: c[name(n, 'b')] ?? 0 }))), left };
636
647
  }
637
648
  const compE = (c, n, node, name) => unfeat(linE(Object.fromEntries(node.vars.map((x, j) => [x, c[name(n, j)] ?? 0])), c[name(n, 'b')] ?? 0));
638
649
  // Ranks of degree 2: a product of two of a node's variables (a square too) a further variable of the LP, its value at
@@ -882,7 +893,7 @@ export function claimInstances(facts, claim, depth = 2) {
882
893
  return instancesFor(facts, { eqs, arity, values: {}, memo: new Map(), fuel: 0, depth: 0 }, nodeOf(claim, 0, true), depth).insts;
883
894
  }
884
895
  export function findCycles(facts, claims, opts = {}) {
885
- const t0 = performance.now(), until = t0 + (opts.ms ?? 10_000), depth = opts.depth ?? 1;
896
+ const t0 = clock(), until = t0 + (opts.ms ?? 10_000), depth = opts.depth ?? 1;
886
897
  const { eqs, arity } = equations(facts);
887
898
  const cx = { eqs, arity, values: opts.values ?? {}, memo: new Map(), fuel: 20_000, depth: 0 };
888
899
  const big = Math.max(0, ...constsOf([facts.map(f => f.holds), claims]).filter(c => c <= 1000));
@@ -901,7 +912,7 @@ export function findCycles(facts, claims, opts = {}) {
901
912
  console.error(`[cycles] ${sp.name}: rank (${sp.rank.map(showE).join(', ')}), ${sp.insts.length} instances, uses ${sp.uses.map(u => `${u.node}@{${Object.entries(u.subst).map(([x, t]) => `${x} := ${showE(t)}`).join(', ')}}`).join(' ')}`);
902
913
  const out = withDeadline(until, () => proveCyclic(facts, b.specs));
903
914
  if (trace)
904
- console.error(`[cycles] ${out.proven ? 'proven' : `${out.node}: ${out.goal} ${out.stuck}`} at ${Math.round(performance.now() - t0)} ms`);
915
+ console.error(`[cycles] ${out.proven ? 'proven' : `${out.node}: ${out.goal} ${out.stuck}`} at ${Math.round(clock() - t0)} ms`);
905
916
  if (!out.proven) {
906
917
  const at = nodes.find(n => n.name === out.node) ?? nodes[0];
907
918
  return { failed: at, verdict: { proven: false, checked: false, goal: out.goal, stuck: out.stuck } };
@@ -913,7 +924,7 @@ export function findCycles(facts, claims, opts = {}) {
913
924
  // dropped in turn where the rest are proven without it (only what the claims need is kept).
914
925
  const attempt = (start, depth, quad) => {
915
926
  let nodes = start, done;
916
- for (let round = 0; round <= start.length && nodes.length && performance.now() < until && !done; round++) {
927
+ for (let round = 0; round <= start.length && nodes.length && clock() < until && !done; round++) {
917
928
  const t = once(nodes, depth, quad);
918
929
  if ('proven' in t) {
919
930
  done = t.proven;
@@ -924,11 +935,11 @@ export function findCycles(facts, claims, opts = {}) {
924
935
  nodes = nodes.filter(n => n !== t.failed);
925
936
  }
926
937
  if (!done)
927
- return { proven: false, checked: false, why: performance.now() >= until ? 'out of time' : 'every candidate dropped' };
938
+ return { proven: false, checked: false, why: clock() >= until ? 'out of time' : 'every candidate dropped' };
928
939
  if (opts.houdini)
929
940
  return done;
930
941
  for (const c of nodes.filter(n => !n.given)) {
931
- if (performance.now() >= until)
942
+ if (clock() >= until)
932
943
  break;
933
944
  const rest = nodes.filter(n => n !== c), t = once(rest, depth, quad);
934
945
  if ('proven' in t && t.proven.checked)
@@ -951,7 +962,7 @@ export function findCycles(facts, claims, opts = {}) {
951
962
  ];
952
963
  const tried = new Set();
953
964
  for (const [d, t, quad] of tries) {
954
- if (performance.now() >= until)
965
+ if (clock() >= until)
955
966
  break;
956
967
  const nodes = t();
957
968
  if (tried.has(id([d, nodes.map(n => n.name), quad])))
@@ -1018,12 +1029,21 @@ const locations = (rel) => {
1018
1029
  }
1019
1030
  return { values, fromOf, toOf, names, at: live.map(s => [...s].sort()) };
1020
1031
  };
1032
+ // A rank from a relation made elsewhere (core/data.ts: a ring of functions' calls, a location per function, each
1033
+ // call's argument sizes bounded from its parameters' and fields'): per location, each component's linear form over the
1034
+ // names (no regions: those read an atom, not a form).
1035
+ export function rankOfPaths(name, rel, until) {
1036
+ const r = relationRank({ name }, rel, until);
1037
+ if (!('rank' in r))
1038
+ return r;
1039
+ return r.forms ? { forms: r.forms, values: locations(rel).values } : { why: 'a rank by regions' };
1040
+ }
1021
1041
  function relationRank(l, rel, until, extra = []) {
1022
1042
  const { values, fromOf, toOf, names, at } = locations(rel);
1023
1043
  const every = [...new Set(at.flat())].sort();
1024
1044
  const gpaths = [];
1025
1045
  for (const [i, p] of rel.paths.entries()) {
1026
- if (performance.now() > until)
1046
+ if (clock() > until)
1027
1047
  return { why: 'out of time on the relation' };
1028
1048
  const rows = [...p.rows, ...(extra[fromOf(i)] ?? [])];
1029
1049
  const ns = [...new Set([...rows.flatMap(r => Object.keys(r)), ...Object.values(p.post).flatMap(r => Object.keys(r)), ...every])].filter(x => x !== '1').sort();
@@ -1091,7 +1111,7 @@ function relationRank(l, rel, until, extra = []) {
1091
1111
  const must = [];
1092
1112
  let w;
1093
1113
  for (const p of left) {
1094
- if (performance.now() > until)
1114
+ if (clock() > until)
1095
1115
  break;
1096
1116
  if (w && sat(w, strict.get(p)))
1097
1117
  continue;
@@ -1114,17 +1134,17 @@ function relationRank(l, rel, until, extra = []) {
1114
1134
  const ranked = (paths, tag0, until) => {
1115
1135
  let left = paths;
1116
1136
  const mine = [], sizes = [];
1117
- while (left.length && mine.length < 8 && performance.now() < until) {
1137
+ while (left.length && mine.length < 8 && clock() < until) {
1118
1138
  const tag = `${tag0}${mine.length}.`;
1119
1139
  // depth 1 first, all at once then one path after another; then deeper
1120
1140
  const order = [1, 2, 3].flatMap(depth => [false, true].flatMap(greedy => [false, true].map((own) => [{ depth, own, tag }, greedy])));
1121
1141
  let found;
1122
1142
  for (const [tp, greedy] of order) {
1123
- if (found || performance.now() > until)
1143
+ if (found || clock() > until)
1124
1144
  break;
1125
- const t1 = performance.now(), b = block(tp, left, greedy, until);
1145
+ const t1 = clock(), b = block(tp, left, greedy, until);
1126
1146
  if (trace)
1127
- console.error(`[cycles] ${l.name}: block ${tag} depth ${tp.depth}${tp.own ? ' own' : ''}${greedy ? ' greedy' : ''}: ${b ? b.strict.length : 'none'} of ${left.length} paths, ${Math.round(performance.now() - t1)} ms`);
1147
+ console.error(`[cycles] ${l.name}: block ${tag} depth ${tp.depth}${tp.own ? ' own' : ''}${greedy ? ' greedy' : ''}: ${b ? b.strict.length : 'none'} of ${left.length} paths, ${Math.round(clock() - t1)} ms`);
1128
1148
  if (b && b.strict.length)
1129
1149
  found = { ...b, tp };
1130
1150
  }
@@ -1145,7 +1165,7 @@ function relationRank(l, rel, until, extra = []) {
1145
1165
  left = left.filter(p => !strict.includes(p));
1146
1166
  }
1147
1167
  if (left.length)
1148
- return { why: performance.now() >= until ? 'out of time on the relation' : 'past 8 components' };
1168
+ return { why: clock() >= until ? 'out of time on the relation' : 'past 8 components' };
1149
1169
  return { parts: mine, sizes };
1150
1170
  };
1151
1171
  // Regions: a component with no rank, its locations split by an atom its paths read (q < p: min(p, q); y ≥ 2: a
@@ -1168,7 +1188,7 @@ function relationRank(l, rel, until, extra = []) {
1168
1188
  atoms.sort((a, b) => Object.keys(b).length - Object.keys(a).length);
1169
1189
  const locs = values.flatMap((_, n) => (comp[n] === c ? [n] : []));
1170
1190
  for (const [ai, a] of atoms.slice(0, 8).entries()) {
1171
- if (performance.now() > until)
1191
+ if (clock() > until)
1172
1192
  return undefined;
1173
1193
  const base = nodeLoc.length, node = (n, yes) => base + 2 * locs.indexOf(n) + (yes ? 0 : 1);
1174
1194
  for (const n of locs)
@@ -1193,12 +1213,14 @@ function relationRank(l, rel, until, extra = []) {
1193
1213
  return undefined;
1194
1214
  };
1195
1215
  const parts = []; // per component of the locations: its parts, each a term per location
1216
+ const lins = []; // the same as forms, where no regions were needed
1196
1217
  const sizes = [];
1197
1218
  for (const c of [...new Set(comp)].sort((a, b) => a - b)) {
1198
1219
  // (half the time left for the component as it is: the regions have the rest)
1199
- const inner = gpaths.filter(p => comp[p.from] === c && comp[p.to] === c), out = ranked(inner, `${c}.`, performance.now() + (until - performance.now()) / 2);
1220
+ const inner = gpaths.filter(p => comp[p.from] === c && comp[p.to] === c), out = ranked(inner, `${c}.`, clock() + (until - clock()) / 2);
1200
1221
  if ('parts' in out) {
1201
1222
  parts[c] = out.parts.map(fs => values.map((_, n) => termOf(rel, fs[n])));
1223
+ lins[c] = out.parts;
1202
1224
  sizes.push(...out.sizes);
1203
1225
  continue;
1204
1226
  }
@@ -1206,6 +1228,7 @@ function relationRank(l, rel, until, extra = []) {
1206
1228
  if (!r)
1207
1229
  return out;
1208
1230
  parts[c] = r.parts;
1231
+ lins[c] = undefined;
1209
1232
  sizes.push(...r.sizes);
1210
1233
  }
1211
1234
  // per location, its component's parts in order (0 past them), the heights first where paths join components
@@ -1221,7 +1244,10 @@ function relationRank(l, rel, until, extra = []) {
1221
1244
  });
1222
1245
  if (!rank.length)
1223
1246
  rank.push(k(0));
1224
- return { rank, text: `(${rank.map(showE).join(', ')})`, blocks: sizes };
1247
+ const linear = [...new Set(comp)].every(c => lins[c] || !parts[c]);
1248
+ const forms = linear ? [...(gpaths.some(p => comp[p.from] !== comp[p.to]) ? [values.map((_, n) => konstL(heightOf(comp[n])))] : []),
1249
+ ...Array.from({ length: width }, (_, j) => values.map((_, n) => lins[comp[n]]?.[j]?.[n] ?? {}))] : undefined;
1250
+ return { rank, text: `(${rank.map(showE).join(', ')})`, blocks: sizes, ...(forms ? { forms } : {}) };
1225
1251
  }
1226
1252
  // Invariants first, so a rank may assume them: atoms per location (each name's bounds at the constants the paths
1227
1253
  // read, and the paths' own atoms over the state and params), those false at a start dropped (the loop's starts, run
@@ -1315,11 +1341,11 @@ export function rankWithInvariants(l, laws, until) {
1315
1341
  return [...best.values(), ...rest];
1316
1342
  };
1317
1343
  let H = [], found = { why: 'no invariant' };
1318
- const t1 = performance.now();
1344
+ const t1 = clock();
1319
1345
  for (const [i, cands] of [bounds, withAtoms].entries()) {
1320
- if (performance.now() > until)
1346
+ if (clock() > until)
1321
1347
  break;
1322
- const closed = houdini(rel, atStarts(cands), locOf, i ? until : performance.now() + (until - performance.now()) / 2);
1348
+ const closed = houdini(rel, atStarts(cands), locOf, i ? until : clock() + (until - clock()) / 2);
1323
1349
  if (!closed || !closed.some(h => h.length))
1324
1350
  continue;
1325
1351
  H = closed.map(tightest);
@@ -1331,7 +1357,7 @@ export function rankWithInvariants(l, laws, until) {
1331
1357
  if (!('rank' in found))
1332
1358
  return found;
1333
1359
  // fewer: a location's atoms at once, then one atom at a time, within ten times the first search's time
1334
- const stop = Math.min(until, performance.now() + Math.max(500, 10 * (performance.now() - t1)));
1360
+ const stop = Math.min(until, clock() + Math.max(500, 10 * (clock() - t1)));
1335
1361
  const without = (drop) => {
1336
1362
  const fewer = houdini(rel, H.map((g, n) => g.filter(h => !drop(n, h))), locOf, stop);
1337
1363
  if (!fewer || fewer.flat().length === H.flat().length)
@@ -1345,14 +1371,14 @@ export function rankWithInvariants(l, laws, until) {
1345
1371
  return false;
1346
1372
  };
1347
1373
  for (const n of H.keys()) {
1348
- if (performance.now() > stop)
1374
+ if (clock() > stop)
1349
1375
  break;
1350
1376
  if (H[n].length)
1351
1377
  without(m => m === n);
1352
1378
  }
1353
1379
  for (const [n, hs] of H.map((h, n) => [n, [...h]]))
1354
1380
  for (const h of hs) {
1355
- if (performance.now() > stop)
1381
+ if (clock() > stop)
1356
1382
  break;
1357
1383
  if (H[n].includes(h))
1358
1384
  without((m, g) => m === n && g === h);
@@ -1374,13 +1400,13 @@ const goalsProven = (goals) => {
1374
1400
  // turn that stays in the loop an edge; then the kernel's halting goals, with invariants inferLaws finds for them where
1375
1401
  // the rank needs one.
1376
1402
  export function findRank(l, laws = [], opts = {}) {
1377
- const t0 = performance.now(), until = t0 + (opts.ms ?? 10_000), rand = seeded(23);
1403
+ const t0 = clock(), until = t0 + (opts.ms ?? 10_000), rand = seeded(23);
1378
1404
  const cx = { eqs: new Map(), arity: new Map(), values: {}, memo: new Map(), fuel: Infinity, depth: 0 };
1379
1405
  const state = Object.keys(l.state), names = [...state, ...l.params].sort();
1380
1406
  const node = { name: l.name, hyps: [], concl: yes, vars: names, level: 0, given: true };
1381
1407
  const points = new Map(), edges = new Map();
1382
1408
  for (const bound of [2, 4, 8, 16, 32])
1383
- for (let trial = 0; trial < 40 && performance.now() < t0 + 1000; trial++) {
1409
+ for (let trial = 0; trial < 40 && clock() < t0 + 1000; trial++) {
1384
1410
  const ps = Object.fromEntries(l.params.map(p => [p, rand(bound + 1)]));
1385
1411
  if (l.pre && evC(cx, l.pre, ps) !== true)
1386
1412
  continue;
@@ -1429,7 +1455,7 @@ export function findRank(l, laws = [], opts = {}) {
1429
1455
  const quadratic = (ps, until) => {
1430
1456
  const out = [];
1431
1457
  for (const p of ps) {
1432
- if (performance.now() > until)
1458
+ if (clock() > until)
1433
1459
  break;
1434
1460
  const d = withProducts([node], samples, [...edges.values()], [p]), r = lexRanks([0], d.nodes, d.samples, d.edges, shared, until);
1435
1461
  if (!r.comps.length || r.left)
@@ -1467,10 +1493,10 @@ export function findRank(l, laws = [], opts = {}) {
1467
1493
  catch (e) {
1468
1494
  return { why: `the relation's search threw: ${e.message.slice(0, 120)}` };
1469
1495
  } };
1470
- const relT0 = performance.now(), rel = safely(() => rankOfRelation(l, laws, performance.now() + (until - performance.now()) / 2));
1496
+ const relT0 = clock(), rel = safely(() => rankOfRelation(l, laws, clock() + (until - clock()) / 2));
1471
1497
  let relWhy = 'rank' in rel ? `the kernel refused ${rel.text}` : rel.why;
1472
1498
  if (trace)
1473
- console.error(`[cycles] ${l.name}: the relation's rank ${'rank' in rel ? rel.text : rel.why} (from ${Math.round(relT0 - t0)} ms to ${Math.round(performance.now() - t0)} ms)`);
1499
+ console.error(`[cycles] ${l.name}: the relation's rank ${'rank' in rel ? rel.text : rel.why} (from ${Math.round(relT0 - t0)} ms to ${Math.round(clock() - t0)} ms)`);
1474
1500
  if ('rank' in rel) {
1475
1501
  const verdict = withDeadline(until, () => goalsProven(loopObligations(l, laws, rel.rank)));
1476
1502
  if ('trees' in verdict)
@@ -1485,7 +1511,7 @@ export function findRank(l, laws = [], opts = {}) {
1485
1511
  return done(won.rank, won.verdict.trees);
1486
1512
  if (!('rank' in rel)) {
1487
1513
  // invariants first: the relation's rank where they hold, with as few of them as it needs
1488
- const inv = safely(() => rankWithInvariants(l, laws, performance.now() + (until - performance.now()) / 2));
1514
+ const inv = safely(() => rankWithInvariants(l, laws, clock() + (until - clock()) / 2));
1489
1515
  if (trace)
1490
1516
  console.error(`[cycles] ${l.name}: the relation's rank with invariants ${'rank' in inv ? `${inv.text} with ${inv.texts.join('; ')}` : inv.why}`);
1491
1517
  if ('rank' in inv) {
@@ -1506,7 +1532,7 @@ export function findRank(l, laws = [], opts = {}) {
1506
1532
  const base = tried[0];
1507
1533
  if (base && !('trees' in base.verdict)) {
1508
1534
  const rank = base.rank, m = loopMachine(l), { stay, cover, helps } = livenessParts(m, loopLiveness(l, rank));
1509
- const ms = (until - performance.now()) * (rest.length ? 0.5 : 1);
1535
+ const ms = (until - clock()) * (rest.length ? 0.5 : 1);
1510
1536
  if (ms > 300) {
1511
1537
  const inf = inferLaws(m, laws, [stay, cover, ...helps], { ms });
1512
1538
  const kept = inf.found.filter(f => !f.law.forall && !f.law.keys?.length), more = kept.map(f => f.law);
@@ -1518,7 +1544,7 @@ export function findRank(l, laws = [], opts = {}) {
1518
1544
  }
1519
1545
  }
1520
1546
  // (the products the loop doesn't read within a quarter of its time: a search that fails tries each of them)
1521
- tried = quadratic(rest, Math.min(until, performance.now() + (opts.ms ?? 10_000) / 4));
1547
+ tried = quadratic(rest, Math.min(until, clock() + (opts.ms ?? 10_000) / 4));
1522
1548
  const late = tried.find(t => 'trees' in t.verdict);
1523
1549
  if (late && 'trees' in late.verdict)
1524
1550
  return done(late.rank, late.verdict.trees);
@@ -1528,7 +1554,7 @@ export function findRank(l, laws = [], opts = {}) {
1528
1554
  return { proven: false, checked: false, rank: base.rank, found: { rank: text, laws: [] }, goal: first.goal, stuck: first.stuck, ...(first.witness ? { witness: first.witness } : {}), why: `rank ${text} from the runs; no invariant found that it needs; the relation: ${relWhy}` };
1529
1555
  }
1530
1556
  export function findLeadsTo(m, laws, l, sample, opts = {}) {
1531
- const t0 = performance.now(), until = t0 + (opts.ms ?? 10_000), rand = seeded(29), run = interpret(m);
1557
+ const t0 = clock(), until = t0 + (opts.ms ?? 10_000), rand = seeded(29), run = interpret(m);
1532
1558
  const names = [...Object.keys(m.state), ...m.params].sort(), helpful = livenessHelpful(l);
1533
1559
  const node = { name: l.name, hyps: [], concl: yes, vars: names, level: 0, given: true };
1534
1560
  const env = (ps, st) => ({ ...ps, ...st.scalars });
@@ -1541,7 +1567,7 @@ export function findLeadsTo(m, laws, l, sample, opts = {}) {
1541
1567
  const pending = (ps, st) => holds(l.from, ps, st) === true && holds(l.to, ps, st) === false;
1542
1568
  const points = new Map(), strong = new Map(), weak = new Map();
1543
1569
  for (const bound of [2, 4, 8, 16])
1544
- for (let trial = 0; trial < 20 && performance.now() < t0 + 1000; trial++) {
1570
+ for (let trial = 0; trial < 20 && clock() < t0 + 1000; trial++) {
1545
1571
  let ps;
1546
1572
  try {
1547
1573
  ps = sample.params(rand, bound);
@@ -1584,15 +1610,36 @@ export function findLeadsTo(m, laws, l, sample, opts = {}) {
1584
1610
  st = next;
1585
1611
  }
1586
1612
  }
1613
+ // The trivial ranks first, where the runs allow them: the constant 0 (every helpful step in its region reaches `to` at
1614
+ // once: none sampled stays pending, which leaves the fit below nothing to fit), then each state variable alone (every
1615
+ // helpful step sampled that stays pending lowers it, and no other raises it), up to four of them. Rank 0 may take half
1616
+ // of what is left, each variable a quarter.
1617
+ const zero = { op: 'const', value: 0 }, tried = new Map();
1618
+ const keeps = (x) => [...weak.values()].every(e => e.t[x] <= e.s[x]), lowers = (x) => [...strong.values()].every(e => e.t[x] < e.s[x]);
1619
+ const trivial = [...(strong.size ? [] : [[zero]]), ...Object.keys(m.state).filter(x => keeps(x) && lowers(x)).slice(0, 4).map(name => [{ op: 'var', name }])];
1620
+ const rankText = (rank) => `(${rank.map(showE).join(', ')})`;
1621
+ for (const [i, rank] of trivial.entries()) {
1622
+ const ms = until - performance.now();
1623
+ if (ms < 200)
1624
+ break;
1625
+ const v = withDeadline(performance.now() + ms * (i === 0 && !strong.size ? 0.5 : 0.25), () => proveLiveness(m, laws, { ...l, rank }));
1626
+ if (v.proven && v.checked)
1627
+ return { proven: true, checked: true, rank, laws: [], found: { rank: rankText(rank), laws: [] } };
1628
+ tried.set(id(rank), v);
1629
+ }
1587
1630
  const samples = [[...points.values()].map(env => ({ env, calls: new Set() }))];
1588
1631
  const { comps, left } = lexRanks([0], [node], samples, [...strong.values()], shared, until, false, [...weak.values()]);
1589
- if (!comps.length || left)
1590
- return { proven: false, checked: false, why: `no linear rank, in order, that ${strong.size} helpful steps sampled lower and ${weak.size} others keep` };
1591
- const rank = comps.map(c => compE(c, 0, node, shared)), text = `(${rank.map(showE).join(', ')})`, lv = { ...l, rank };
1592
- const first = withDeadline(until, () => proveLiveness(m, laws, lv));
1632
+ const noRank = `no linear rank, in order, that ${strong.size} helpful steps sampled lower and ${weak.size} others keep`;
1633
+ const fitted = comps.length && !left ? comps.map(c => compE(c, 0, node, shared)) : undefined;
1634
+ // Past the fit, the invariants a rank needs: the fitted one's, or else rank 0's where the runs allow it.
1635
+ const rank = fitted ?? (strong.size ? undefined : [zero]);
1636
+ if (!rank)
1637
+ return { proven: false, checked: false, why: noRank };
1638
+ const text = rankText(rank), lv = { ...l, rank };
1639
+ const first = tried.get(id(rank)) ?? withDeadline(until, () => proveLiveness(m, laws, lv));
1593
1640
  if (first.proven && first.checked)
1594
1641
  return { proven: true, checked: true, rank, laws: [], found: { rank: text, laws: [] } };
1595
- const ms = until - performance.now();
1642
+ const ms = until - clock();
1596
1643
  if (ms > 300) {
1597
1644
  const { stay, cover, helps } = livenessParts(m, lv), inf = inferLaws(m, laws, [stay, cover, ...helps], { ms });
1598
1645
  const kept = inf.found.filter(f => !f.law.forall && !f.law.keys?.length), more = kept.map(f => f.law);
@@ -1602,10 +1649,13 @@ export function findLeadsTo(m, laws, l, sample, opts = {}) {
1602
1649
  return { proven: true, checked: true, rank, laws: more, found: { rank: text, laws: kept.map(f => f.text) } };
1603
1650
  }
1604
1651
  }
1605
- return { proven: false, checked: false, rank, found: { rank: text, laws: [] }, ...(first.failed ? { goal: first.failed.goal, stuck: first.failed.stuck, ...(first.failed.witness ? { witness: first.failed.witness } : {}) } : {}), why: `rank ${text} from the runs; the kernel's goals not proven with it` };
1652
+ const failed = first.failed ? { goal: first.failed.goal, stuck: first.failed.stuck, ...(first.failed.witness ? { witness: first.failed.witness } : {}) } : {};
1653
+ if (!fitted)
1654
+ return { proven: false, checked: false, ...failed, why: `${noRank}; rank ${text}, which the runs allow, not proven, nor with the invariants found` };
1655
+ return { proven: false, checked: false, rank, found: { rank: text, laws: [] }, ...failed, why: `rank ${text} from the runs; the kernel's goals not proven with it` };
1606
1656
  }
1607
1657
  export function cycleLemmas(m, laws, stepLaws = [], opts = {}) {
1608
- const until = performance.now() + (opts.ms ?? 10_000);
1658
+ const until = clock() + (opts.ms ?? 10_000);
1609
1659
  const fns = Object.entries(m.fns ?? {}).filter(([, f]) => !f.recur && (f.arity ?? 1) === 1);
1610
1660
  const fns2 = Object.entries(m.fns ?? {}).filter(([, f]) => !f.recur && f.arity === 2 && f.call);
1611
1661
  if ((!fns.length && !fns2.length) || !m.facts?.length)
@@ -1698,16 +1748,16 @@ export function cycleLemmas(m, laws, stepLaws = [], opts = {}) {
1698
1748
  const unique = [...new Map(claims.map(c => [c.name, c])).values()], two = (c) => m.fns?.[readsOf(c.concl)[0]?.map ?? '']?.arity === 2;
1699
1749
  const proofs = new Map();
1700
1750
  for (const c of unique.filter(two)) {
1701
- if (performance.now() >= until)
1751
+ if (clock() >= until)
1702
1752
  break;
1703
- const o = findCycles(facts, [c], { ms: Math.min(1000, (until - performance.now()) * 0.1), values, houdini: true, generalize: false });
1753
+ const o = findCycles(facts, [c], { ms: Math.min(1000, (until - clock()) * 0.1), values, houdini: true, generalize: false });
1704
1754
  if (o.proven && o.checked && o.proof)
1705
1755
  proofs.set(c.name, o.proof);
1706
1756
  }
1707
1757
  const ones = unique.filter(c => !two(c));
1708
1758
  if (!ones.length && !proofs.size)
1709
1759
  return { proven: false, checked: false, found: [], why: unique.length ? 'no lemma proven' : 'no lemma fits the values' };
1710
- const out = ones.length ? findCycles(facts, ones, { ms: Math.max(0, until - performance.now()) * 0.6, values, houdini: true, generalize: false }) : { proven: true, checked: true, kept: [] };
1760
+ const out = ones.length ? findCycles(facts, ones, { ms: Math.max(0, until - clock()) * 0.6, values, houdini: true, generalize: false }) : { proven: true, checked: true, kept: [] };
1711
1761
  if ((!out.proven || !out.checked || !out.kept?.length) && !proofs.size)
1712
1762
  return { proven: false, checked: false, found: [], why: out.why ?? 'no lemma proven' };
1713
1763
  const kept = [...(out.proven && out.checked ? out.kept ?? [] : []), ...proofs.keys()];
@@ -1732,7 +1782,7 @@ export function cycleLemmas(m, laws, stepLaws = [], opts = {}) {
1732
1782
  if (!best.ok)
1733
1783
  return { proven: false, checked: false, found: [], why: `lemmas proven (${found.map(f => f.text).join('; ')}), the laws not with them` };
1734
1784
  for (const f of [...found]) {
1735
- if (performance.now() >= until)
1785
+ if (clock() >= until)
1736
1786
  break;
1737
1787
  const rest = found.filter(g => g !== f), again = proveWith(rest);
1738
1788
  if (again.ok)
@@ -258,6 +258,7 @@ export type Termination = {
258
258
  proof?: CyclicVerdict;
259
259
  scheme?: string;
260
260
  lemmas: string[];
261
+ lemmaLaws?: DataLaw[];
261
262
  }[];
262
263
  ms: number;
263
264
  };
@@ -266,6 +267,13 @@ export declare const terminationMs: {
266
267
  };
267
268
  export declare const showMeasure: (f: Pick<Fn, "params">, m: Measure) => string;
268
269
  export declare function measureX(f: Pick<Fn, 'params'>, c: Measure['comps'][number], args: X[]): X;
270
+ export declare function checkMeasures(fns: Fn[], ms: Measure[], budget?: number): {
271
+ proven: true;
272
+ obligations: Termination['obligations'][];
273
+ } | {
274
+ proven: false;
275
+ why: string;
276
+ };
269
277
  export type DataLaw = {
270
278
  name: string;
271
279
  vars: {
@@ -383,6 +391,7 @@ export type Options = {
383
391
  seed?: number;
384
392
  patience?: number;
385
393
  transfer?: boolean;
394
+ lemmasFirst?: boolean;
386
395
  };
387
396
  export declare function refute(l: DataLaw, n?: number, seed?: number): Record<string, string> | undefined;
388
397
  type SchemeUse = {