gdp-wired 0.28.0 → 0.29.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.
@@ -14,7 +14,7 @@ import { checkRefutation } from "../core/check.js";
14
14
  import { allowNode, allowTranslated, certCyclic, certOn, certSearch, closingInsts, crossCyclic, cyclicOn, cycLog, hasQuantified, loopNodes, machineNodes, proveCyclic, reqTS, searchedStepNodes, skMachine, timedKind, withWitness, translatedProof, uncovered, uncoveredWhy } from "../core/cyclic.js";
15
15
  import { proveSome, someLaws } from "../core/exists.js";
16
16
  import { growCdcl } from "./cdcl.js";
17
- import { assumed, atomOf, boundOf, canon, canonFlip, columnTerm, decided, factorsOf, isCell, isMonomial, stepZone, check, checkLaws, checkStepLaws, historyMachine, substC, substE, leafConstraints, leafConstraintsReusing, reusing, linear, livenessHelpful, livenessParts, loopMachine, obligations, plainKey, progressObligations, stepLawObligations, trueC, truth, unreachable, witnessesOf, withProducts } from "./kernel.js";
17
+ import { assumed, atomOf, boundOf, canon, canonFlip, columnTerm, decided, factorsOf, isCell, isMonomial, stepZone, check, checkLaws, checkStepLaws, historyMachine, plainOf, substC, substE, leafConstraints, leafConstraintsReusing, reusing, linear, livenessHelpful, livenessParts, strongly, loopMachine, obligations, plainKey, progressObligations, stepLawObligations, trueC, truth, unreachable, witnessesOf, withProducts } from "./kernel.js";
18
18
  // The atoms the path leaves open, in evaluation order: deciding any of them makes progress.
19
19
  function openE(e, path, out) {
20
20
  switch (e.op) {
@@ -428,7 +428,10 @@ function growRoot(goal, path, budget) {
428
428
  }
429
429
  return growPlain(goal, path, budget);
430
430
  }
431
- export const realModels = { on: false };
431
+ // A CDCL model whose products don't multiply out is no model (GDP_REAL_MODELS=0: taken as one, as before): its
432
+ // monomials are names of their own there, so x' = (t − last)·rate may read 0 with rate = 1 and t − last = 1, where
433
+ // the plain search multiplies the factors' rows (x/time/rate's refill, a rank-0 step goal).
434
+ export const realModels = { on: env.GDP_REAL_MODELS !== '0' };
432
435
  const fakeProducts = (w) => !!w && Object.keys(w).some(key => isMonomial(key) && (w[key] ?? 0) !== factorsOf(key).reduce((acc, f) => acc * (w[f] ?? 0), 1));
433
436
  function growPlain(goal, path, budget) {
434
437
  if (budget.cap !== undefined && budget.nodes >= budget.cap)
@@ -520,6 +523,33 @@ function growPlain(goal, path, budget) {
520
523
  }
521
524
  }
522
525
  }
526
+ // Past forty rows, every pair is too many: each monomial x·y's factors' bounds (rows of x alone, of y alone)
527
+ // multiplied pairwise, McCormick's envelope of the product (interval·blockedUntil >= blockedUntil from interval >= 1
528
+ // and blockedUntil >= 0), each pair once, at most 300.
529
+ if (!split && monomials && rows.length > 40) {
530
+ const alone = new Map();
531
+ rows.forEach((r, i) => { const ks = Object.keys(r.lin).filter(key => key !== '1'); if (ks.length === 1 && !isMonomial(ks[0]))
532
+ alone.set(ks[0], [...(alone.get(ks[0]) ?? []), i]); });
533
+ const seenP = new Set(), pairs = [];
534
+ for (const m of new Set(rows.flatMap(r => Object.keys(r.lin).filter(isMonomial)))) {
535
+ const fs = factorsOf(m);
536
+ if (fs.length !== 2)
537
+ continue;
538
+ for (const i of alone.get(fs[0]) ?? [])
539
+ for (const j of alone.get(fs[1]) ?? []) {
540
+ const key2 = i < j ? `${i},${j}` : `${j},${i}`;
541
+ if (!seenP.has(key2) && pairs.length < 300) {
542
+ seenP.add(key2);
543
+ pairs.push(i < j ? [i, j] : [j, i]);
544
+ }
545
+ }
546
+ }
547
+ if (pairs.length) {
548
+ const mc = solve(withProducts(rows, pairs));
549
+ if (mc.kind === 'refuted')
550
+ return { tree: leafOf(mc.steps, pairs), nodes: budget.nodes };
551
+ }
552
+ }
523
553
  if (!split && monomials && rows.length <= 40) {
524
554
  // Only rows about the factors (no other map cells), each pair once: elimination over hundreds of products blows up.
525
555
  const factorSet = new Set(rows.flatMap(r => Object.keys(r.lin).filter(isMonomial).flatMap(factorsOf)));
@@ -1154,11 +1184,30 @@ const withReads = (laws, inst, keys, focus) => ({ ...inst, ...Object.fromEntries
1154
1184
  out.set(JSON.stringify(had.slice(i, i + n)), had.slice(i, i + n));
1155
1185
  for (const tuple of related(keys, focus, n))
1156
1186
  out.set(JSON.stringify(tuple), tuple);
1187
+ for (const tuple of matched(l, keys))
1188
+ out.set(JSON.stringify(tuple), tuple);
1157
1189
  return [l.name, [...out.values()].flat()];
1158
1190
  }
1159
1191
  const seen = new Set(had.map(e => JSON.stringify(e)));
1160
1192
  return [l.name, [...had, ...keys.filter(e => { const id = JSON.stringify(e); return seen.has(id) ? false : (seen.add(id), true); })]];
1161
1193
  })) });
1194
+ // A law about several keys where its body reads a map at a key naming every one of them (Link[x·N + y]): the tuple
1195
+ // that makes that key one the goals read (Link[a·N + b] gives (a, b)), as a fact about several keys is matched
1196
+ // (withFacts). A key of one bound name alone matches every key, so it binds no tuple here.
1197
+ const matched = (l, keys) => {
1198
+ const vars = [l.forall, ...(l.keys ?? [])], names = (e) => vars.filter(x => JSON.stringify(e).includes(`"name":${JSON.stringify(x)}`));
1199
+ const pats = new Map();
1200
+ eachRead(e => { if (names(e.key).length === vars.length)
1201
+ pats.set(JSON.stringify(e.key), e.key); }).inC(l.holds);
1202
+ const out = [];
1203
+ for (const p of pats.values())
1204
+ for (const key of keys) {
1205
+ const b = matchMany(p, key, vars);
1206
+ if (b && vars.every(x => x in b))
1207
+ out.push(vars.map(x => b[x]));
1208
+ }
1209
+ return out;
1210
+ };
1162
1211
  // The n-tuples of the keys that relate the focus (withReads).
1163
1212
  const related = (keys, focus, n) => {
1164
1213
  const reads = (e, x) => x !== undefined && JSON.stringify(e).includes(`"name":${JSON.stringify(x)}`);
@@ -1511,12 +1560,8 @@ export function proveLaw(m, laws, i) {
1511
1560
  const r = proveLaws(m, laws);
1512
1561
  return r.proven ? { proven: true } : { proven: false, goal: r.failed.goal, stuck: r.failed.stuck, ...(r.failed.witness ? { witness: r.failed.witness } : {}) };
1513
1562
  }
1514
- const keys = [...readKeys(m, laws), ...witnesses(m)];
1515
- const inst = instancesFor(m, laws, inst => obligations(m, laws, { [law.name]: inst }, i), {
1516
- seed: [...keys, ...(law.forall ? [{ op: 'var', name: `${law.forall}#` }] : []), ...(law.keys ?? []).map((name) => ({ op: 'var', name }))],
1517
- focus: [...(law.forall ? [`${law.forall}#`] : []), ...(law.keys ?? [])],
1518
- });
1519
- const few = triggered(m, laws, inst, i2 => obligations(m, laws, { [law.name]: i2 }, i), law.forall ? [`${law.forall}#`] : []);
1563
+ const pm = plainOf(m), inst = lawInstances(m, laws, i);
1564
+ const few = triggered(pm, laws, inst, i2 => obligations(m, laws, { [law.name]: i2 }, i), law.forall ? [`${law.forall}#`] : []);
1520
1565
  if (!sameInstances(few, inst) && obligations(m, laws, { [law.name]: few }, i).every(goal => 'tree' in grow(goal)))
1521
1566
  return { proven: true };
1522
1567
  for (const goal of obligations(m, laws, { [law.name]: inst }, i)) {
@@ -1526,11 +1571,25 @@ export function proveLaw(m, laws, i) {
1526
1571
  }
1527
1572
  return { proven: true };
1528
1573
  }
1529
- function proveLawsAsGiven(m, laws) {
1574
+ // The instances law i's goals are read at (proveLaw's; core/infer.ts's join asks one goal at a time).
1575
+ export function lawInstances(m, laws, i) {
1576
+ // (a machine with sums: its plain machine's instances, as proveLawsAsGiven's)
1577
+ const law = laws[i], pm = plainOf(m), keys = [...readKeys(pm, laws), ...witnesses(pm)];
1578
+ return instancesFor(pm, laws, inst => obligations(m, laws, { [law.name]: inst }, i), {
1579
+ seed: [...keys, ...(law.forall ? [{ op: 'var', name: `${law.forall}#` }] : []), ...(law.keys ?? []).map((name) => ({ op: 'var', name }))],
1580
+ focus: [...(law.forall ? [`${law.forall}#`] : []), ...(law.keys ?? [])],
1581
+ });
1582
+ }
1583
+ // `defer`: the usual trees now, their certificate and check given to it as `finish`, which proveStepLaws runs once every
1584
+ // step law is proven too: a verdict that fails needs neither (TigerBeetle's laws spent 50 s of 67 on the laws' certificate
1585
+ // and check before a step law failed). Deferred, a certificate not made leaves the check to checkStepLaws, which reads
1586
+ // these trees again.
1587
+ function proveLawsAsGiven(m, laws, defer) {
1530
1588
  // Each law's two goals (start and step) get their own instances, seeded with its own keys.
1531
- const keys = [...readKeys(m, laws), ...witnesses(m)], instances = {};
1589
+ // (a machine with sums: its instances are its plain machine's, whose flags hold each sum's facts at every key)
1590
+ const pm = plainOf(m), keys = [...readKeys(pm, laws), ...witnesses(pm)], instances = {};
1532
1591
  laws.forEach((law, i) => {
1533
- instances[law.name] = instancesFor(m, laws, inst => obligations(m, laws, { ...instances, [law.name]: inst }, i), {
1592
+ instances[law.name] = instancesFor(pm, laws, inst => obligations(m, laws, { ...instances, [law.name]: inst }, i), {
1534
1593
  seed: [...keys, ...(law.forall ? [{ op: 'var', name: `${law.forall}#` }] : []), ...(law.keys ?? []).map((name) => ({ op: 'var', name }))],
1535
1594
  focus: [...(law.forall ? [`${law.forall}#`] : []), ...(law.keys ?? [])],
1536
1595
  });
@@ -1541,8 +1600,8 @@ function proveLawsAsGiven(m, laws) {
1541
1600
  // among them, do nothing more than before)
1542
1601
  // A machine with a history: its laws are its plain machine's (historyMachine; the record goals leaf goals beside them).
1543
1602
  const modes = cyclicOn() || certOn(), hist = modes && m.history ? historyMachine(m) : undefined, mc = hist ? hist.machine : m;
1544
- const why = modes ? uncoveredWhy(mc, laws) : undefined, cert = certOn() && !why;
1545
- usualCheck.on = !cert;
1603
+ const why = modes ? (sumsWhy(m) ?? uncoveredWhy(mc, laws)) : undefined, cert = certOn() && !why;
1604
+ usualCheck.on = !cert && !defer;
1546
1605
  const t0 = performance.now(), out = (() => { try {
1547
1606
  return proveThinned(m, laws, { ...instances });
1548
1607
  }
@@ -1554,31 +1613,42 @@ function proveLawsAsGiven(m, laws) {
1554
1613
  const inst = out.proof?.instances ?? instances;
1555
1614
  const searched = () => { const { facts, specs } = machineNodes(mc, laws, inst); return proveCyclic(facts, specs); };
1556
1615
  const translated = out.proof ? ((st) => translatedProof(() => JSON.stringify(['machine', mc, laws, inst]), () => timedKind('instance', 0, () => machineNodes(mc, laws, inst, out.proof, st)), st)) : undefined;
1557
- if (cyclicOn()) {
1558
- const usual = out.proven && out.checked;
1559
- // (a history: its plain machine's cyclic proof, and its record goals as the leaf goals they are; a machine with flags
1560
- // that hold at every key the usual route doesn't prove: not searched, as before 0.19.0, a search there costs seconds)
1561
- const records = !hist || hist.goals.every(g => { const tr = out.proof?.trees[g.name] ?? (() => { const o = grow(g); return 'tree' in o ? o.tree : undefined; })(); return tr !== undefined && check(g, tr); });
1562
- const recordFails = () => ({ proven: false, checked: false, node: m.name, goal: 'a record goal', stuck: 'not proven' });
1563
- if (!why && (usual || !hasQuantified(mc)))
1564
- crossCyclic('machine', m.name, usual, records ? searched : recordFails, usualMs, records ? translated : undefined);
1565
- else
1566
- cycLog({ kind: 'machine', name: m.name, usual, uncovered: true, why: why ?? 'a flag at every key the usual route does not prove' });
1567
- }
1568
- if (cert && out.proven && out.proof) {
1569
- const c = certCyclic('machine', m.name, translated, searched, usualMs);
1570
- if (c.checked) {
1571
- // (a history's record goals checked as they are: leaf goals)
1572
- out.checked = !hist || hist.goals.every(g => out.proof.trees[g.name] !== undefined && check(g, out.proof.trees[g.name]));
1573
- Object.assign(out.proof, { cyclic: c.proof });
1574
- }
1575
- else {
1616
+ // The certificate (or, where none is made, the check), now or where the caller defers it.
1617
+ const finish = () => {
1618
+ if (defer && !cert && cyclicOn() && out.proven && out.proof)
1576
1619
  out.checked = checkLaws(m, laws, out.proof);
1577
- uncovered('machine', m.name, c.why);
1620
+ if (cyclicOn()) {
1621
+ const usual = out.proven && out.checked;
1622
+ // (a history: its plain machine's cyclic proof, and its record goals as the leaf goals they are; a machine with flags
1623
+ // that hold at every key the usual route doesn't prove: not searched, as before 0.19.0, a search there costs seconds)
1624
+ const records = !hist || hist.goals.every(g => { const tr = out.proof?.trees[g.name] ?? (() => { const o = grow(g); return 'tree' in o ? o.tree : undefined; })(); return tr !== undefined && check(g, tr); });
1625
+ const recordFails = () => ({ proven: false, checked: false, node: m.name, goal: 'a record goal', stuck: 'not proven' });
1626
+ if (!why && (usual || !hasQuantified(mc)))
1627
+ crossCyclic('machine', m.name, usual, records ? searched : recordFails, usualMs, records ? translated : undefined);
1628
+ else
1629
+ cycLog({ kind: 'machine', name: m.name, usual, uncovered: true, why: why ?? 'a flag at every key the usual route does not prove' });
1578
1630
  }
1579
- }
1580
- else if (certOn() && why && out.proven)
1581
- cycLog({ kind: 'machine', name: m.name, cert: true, uncovered: true, why });
1631
+ if (cert && out.proven && out.proof) {
1632
+ const c = certCyclic('machine', m.name, translated, searched, usualMs);
1633
+ if (c.checked) {
1634
+ // (a history's record goals checked as they are: leaf goals)
1635
+ out.checked = !hist || hist.goals.every(g => out.proof.trees[g.name] !== undefined && check(g, out.proof.trees[g.name]));
1636
+ Object.assign(out.proof, { cyclic: c.proof });
1637
+ }
1638
+ else {
1639
+ // (deferred: the step laws' certificate translates these trees too, and where it isn't made checkStepLaws checks them)
1640
+ if (!defer)
1641
+ out.checked = checkLaws(m, laws, out.proof);
1642
+ uncovered('machine', m.name, c.why);
1643
+ }
1644
+ }
1645
+ else if (certOn() && why && out.proven)
1646
+ cycLog({ kind: 'machine', name: m.name, cert: true, uncovered: true, why });
1647
+ };
1648
+ if (defer)
1649
+ defer(finish);
1650
+ else
1651
+ finish();
1582
1652
  return out;
1583
1653
  }
1584
1654
  // Whether the usual proof's trees are checked (off while GDP_CERT=cyclic makes the certificate a cyclic proof).
@@ -1586,11 +1656,13 @@ export const usualCheck = { on: true };
1586
1656
  // The last machine proof made (core/dsl.ts's recurrences read their machine's, to translate it: core/cyclic.ts).
1587
1657
  export const usualProof = {};
1588
1658
  // Each law with its instances thinned (`triggered`) where that proves it, else with all of them.
1659
+ // A machine with sums has no cyclic twin yet: its certificate is the usual trees, checked with its cover goals.
1660
+ const sumsWhy = (m) => (m.sums && Object.keys(m.sums).length ? 'a sum over a map\'s keys (Sums.lean checks the usual trees)' : undefined);
1589
1661
  function proveThinned(m, laws, instances) {
1590
1662
  const trees = {}, fulls = { ...instances };
1591
1663
  let nodes = 0, leaves = 0;
1592
1664
  for (const [i, law] of laws.entries()) {
1593
- const full = instances[law.name], few = triggered(m, laws, full, inst => obligations(m, laws, { ...instances, [law.name]: inst }, i), law.forall ? [`${law.forall}#`] : []);
1665
+ const full = instances[law.name], few = triggered(plainOf(m), laws, full, inst => obligations(m, laws, { ...instances, [law.name]: inst }, i), law.forall ? [`${law.forall}#`] : []);
1594
1666
  for (const inst of sameInstances(few, full) ? [full] : [few, full]) {
1595
1667
  instances[law.name] = inst;
1596
1668
  const done = {};
@@ -1650,7 +1722,11 @@ function proveWith(m, laws, instances) {
1650
1722
  return { proven: true, nodes, leaves, checked: !usualCheck.on || checkLaws(m, laws, proof), proof };
1651
1723
  }
1652
1724
  export function proveStepLaws(given0, given, stepLaws) {
1653
- const base = proveLaws(given0, given);
1725
+ // (plain laws: their certificate and check made only once the step laws are proven too, `ready` below; where it isn't
1726
+ // made, checkStepLaws reads their trees again)
1727
+ let finish;
1728
+ const base = !someLaws(given) && !given.some(l => someKeys(l.holds).length) ? proveLawsAsGiven(given0, given, f => { finish = f; }) : proveLaws(given0, given);
1729
+ const ready = () => { const f = finish; finish = undefined; f?.(); };
1654
1730
  if (!base.proven || !base.proof)
1655
1731
  return { proven: false, nodes: base.nodes, leaves: base.leaves, ...(base.failed ? { failed: base.failed } : {}), checked: false };
1656
1732
  const laws = base.laws ?? given;
@@ -1658,32 +1734,40 @@ export function proveStepLaws(given0, given, stepLaws) {
1658
1734
  const m = base.machine ?? given0, mx = base.machine ? { machine: base.machine } : {};
1659
1735
  if (stepLaws.some(sl => someKeys(sl.then).length)) {
1660
1736
  // Each step law's witnesses on its own (a step law assumes no other), the request and the state after among them.
1661
- const plain = m.history ? historyMachine(m).machine : m, after = Object.keys(plain.state).map(n => `${n}'`);
1662
- const out = chooseWitnesses(stepLaws, sl => sl.then, sl => [...(sl.forall ? [sl.forall] : []), ...plain.inputs, ...after], plain, sls => sls.every(sl => { const r = proveStepLawsAsGiven(m, laws, [sl], base); return r.proven && r.checked; }), (sl, then) => ({ ...sl, then }));
1737
+ const plain = plainOf(m), after = Object.keys(plain.state).map(n => `${n}'`);
1738
+ const out = chooseWitnesses(stepLaws, sl => sl.then, sl => [...(sl.forall ? [sl.forall] : []), ...plain.inputs, ...after], plain, sls => sls.every(sl => { const r = proveStepLawsAsGiven(m, laws, [sl], base, ready); return r.proven && r.checked; }), (sl, then) => ({ ...sl, then }));
1663
1739
  if ('stuck' in out)
1664
1740
  return { proven: false, nodes: base.nodes, leaves: base.leaves, failed: { goal: 'witnesses', stuck: out.stuck }, checked: false };
1665
- return { ...proveStepLawsAsGiven(m, laws, out.items, base), ...(base.laws ? { laws } : {}), ...mx, stepLaws: out.items };
1741
+ return { ...proveStepLawsAsGiven(m, laws, out.items, base, ready), ...(base.laws ? { laws } : {}), ...mx, stepLaws: out.items };
1666
1742
  }
1667
- return { ...proveStepLawsAsGiven(m, laws, stepLaws, base), ...(base.laws ? { laws } : {}), ...mx };
1743
+ return { ...proveStepLawsAsGiven(m, laws, stepLaws, base, ready), ...(base.laws ? { laws } : {}), ...mx };
1668
1744
  }
1669
- function proveStepLawsAsGiven(m, laws, stepLaws, base) {
1745
+ // The keys a step law reads its maps at, and its own.
1746
+ const ownKeys = (plain, sl) => [...keysInlined(plain, [sl.then, ...(sl.when === undefined ? [] : Array.isArray(sl.when) ? sl.when : [sl.when])].flatMap(readKeysC)),
1747
+ ...[sl.forall, ...(sl.keys ?? [])].flatMap(key => (key ? [{ op: 'var', name: key }] : []))];
1748
+ // Each step law's instances (proveStepLaws'; core/infer.ts's join asks one goal at a time).
1749
+ export function stepLawInstances(m, laws) {
1750
+ const plain = plainOf(m);
1751
+ const shared = [...readKeys(plain, laws), ...witnesses(plain)], named = [...laws, ...(plain.facts ?? [])], reads = shifts(plain) || laws.some(l => l.keys?.length) || pairFlags(plain);
1752
+ const own = (sl) => ownKeys(plain, sl);
1753
+ return sl => {
1754
+ const zone = stepZone(plain, sl.steps ?? 1), keep = (inst) => avoiding(inst, zone, named, plain);
1755
+ return keep(instancesFor(plain, laws, inst => stepLawObligations(m, laws, keep(inst), sl), { seed: [...shared, ...own(sl)], focus: [sl.forall, ...(sl.keys ?? [])].flatMap(k => (k ? [k] : [])), reads }));
1756
+ };
1757
+ }
1758
+ function proveStepLawsAsGiven(m, laws, stepLaws, base, ready = () => { }) {
1670
1759
  if (!base.proof)
1671
1760
  return { proven: false, nodes: base.nodes, leaves: base.leaves, checked: false };
1672
1761
  const t0 = performance.now();
1673
- const plain = m.history ? historyMachine(m).machine : m;
1762
+ const plain = plainOf(m);
1674
1763
  // Each step law its own instances, from its own goal: the keys the step and the laws read, and its own (a k-step
1675
1764
  // law's later frames read keys no other step law has); where positions shift or a law is about several keys, the
1676
1765
  // keys its goal reads a map at too. A frame's hypotheses read no name the run introduces later (kernel.ts's
1677
1766
  // stepZone), so a k-step law drops the keys that read one; but a flag that holds at every key holds at a later step's
1678
1767
  // key too: where these instances don't prove it, each flag at its own witness at every step is tried (keptAcross).
1679
- const shared = [...readKeys(plain, laws), ...witnesses(plain)], named = [...laws, ...(plain.facts ?? [])], reads = shifts(plain) || laws.some(l => l.keys?.length) || pairFlags(plain);
1680
- const own = (sl) => [...keysInlined(plain, [sl.then, ...(sl.when === undefined ? [] : Array.isArray(sl.when) ? sl.when : [sl.when])].flatMap(readKeysC)),
1681
- ...[sl.forall, ...(sl.keys ?? [])].flatMap(key => (key ? [{ op: 'var', name: key }] : []))];
1682
- const perStep = {};
1683
- for (const sl of stepLaws) {
1684
- const zone = stepZone(plain, sl.steps ?? 1), keep = (inst) => avoiding(inst, zone, named, plain);
1685
- perStep[sl.name] = keep(instancesFor(plain, laws, inst => stepLawObligations(m, laws, keep(inst), sl), { seed: [...shared, ...own(sl)], focus: [sl.forall, ...(sl.keys ?? [])].flatMap(k => (k ? [k] : [])), reads }));
1686
- }
1768
+ const perStep = {}, at = stepLawInstances(m, laws);
1769
+ for (const sl of stepLaws)
1770
+ perStep[sl.name] = at(sl);
1687
1771
  const instances = perStep[stepLaws[0]?.name ?? ''] ?? {};
1688
1772
  const trees = {};
1689
1773
  let nodes = base.nodes, leaves = base.leaves;
@@ -1697,7 +1781,7 @@ function proveStepLawsAsGiven(m, laws, stepLaws, base) {
1697
1781
  out = grow(goal);
1698
1782
  // A k-step law that reads a condition kept across its steps: each flag at its own witnesses, at every step.
1699
1783
  if (!('tree' in out))
1700
- for (const kept of keptAcross(plain, laws, perStep[sl.name] ?? instances, own(sl), sl.steps ?? 1)) {
1784
+ for (const kept of keptAcross(plain, laws, perStep[sl.name] ?? instances, ownKeys(plain, sl), sl.steps ?? 1)) {
1701
1785
  const again = grow(stepLawObligations(m, laws, kept, sl)[0]);
1702
1786
  if ('tree' in again) {
1703
1787
  out = again;
@@ -1723,12 +1807,16 @@ function proveStepLawsAsGiven(m, laws, stepLaws, base) {
1723
1807
  nodes += out.nodes;
1724
1808
  leaves += countLeaves(out.tree);
1725
1809
  }
1810
+ // (every step law proven: the laws' certificate, or their check, as proveLaws makes it; its time not the step laws')
1811
+ const r0 = performance.now();
1812
+ ready();
1813
+ const usual0 = t0 + performance.now() - r0;
1726
1814
  const proof = { laws: base.proof, instances, ...(Object.keys(perStep).length ? { perStep } : {}), trees };
1727
1815
  // Step laws of a machine the cyclic instances cover (one step, or several over no map) are translated with the laws
1728
1816
  // (core/cyclic.ts); the rest are counted as no instance's.
1729
1817
  // (a machine with a history: its plain machine's; a flag at every key through its sk machine; k-step laws over a map
1730
1818
  // searched, where GDP_CERT_SEARCH=1; where no cyclic proof is made the usual trees, checked above, stay the certificate)
1731
- const modes = cyclicOn() || certOn(), why = modes ? uncoveredWhy(plain, laws) : undefined, one = stepLaws;
1819
+ const modes = cyclicOn() || certOn(), why = modes ? (sumsWhy(m) ?? uncoveredWhy(plain, laws)) : undefined, one = stepLaws;
1732
1820
  // Where the cyclic certificate is made below (GDP_CERT, not the cross-check; the laws' certificate checked), the usual
1733
1821
  // trees are its input, as a machine's laws' are: checkStepLaws (the laws' usual trees again, then the step laws') runs
1734
1822
  // only where no certificate is made.
@@ -1742,7 +1830,7 @@ function proveStepLawsAsGiven(m, laws, stepLaws, base) {
1742
1830
  if (!why && one.length && out.checked) {
1743
1831
  const all = one.map(sl => { const inst = perStep[sl.name] ?? instances, goal = stepLawObligations(m, laws, inst, sl)[0]; return { sl, inst, goal, tree: trees[goal.name] }; });
1744
1832
  const translatedOf = (steps) => (st) => translatedProof(() => JSON.stringify(['steps', plain, laws, base.proof.instances, steps.map(x => [x.sl, x.inst])]), reused => timedKind('instance', 0, () => machineNodes(plain, laws, base.proof.instances, { trees: base.proof.trees, steps, lawsMade: reused }, st)), st, () => JSON.stringify(['machine', plain, laws, base.proof.instances]));
1745
- const usualMs = performance.now() - t0;
1833
+ const usualMs = performance.now() - usual0;
1746
1834
  if (cyclicOn())
1747
1835
  crossCyclic('step law', m.name, true, undefined, usualMs, translatedOf(all));
1748
1836
  // (where the step laws' proof together isn't made, each step law's alone: one the translation misses leaves the
@@ -1766,7 +1854,7 @@ function proveStepLawsAsGiven(m, laws, stepLaws, base) {
1766
1854
  const b = machineNodes(plain, laws, base.proof.instances);
1767
1855
  return proveCyclic(b.facts, [...b.specs, ...searchedStepNodes(plain, laws, rest.map(sl => ({ law: sl, instances: perStep[sl.name] ?? instances })), b.facts, b.specs)]);
1768
1856
  };
1769
- const c = certCyclic('step law', m.name, undefined, searchedSteps, performance.now() - t0);
1857
+ const c = certCyclic('step law', m.name, undefined, searchedSteps, performance.now() - usual0);
1770
1858
  for (const sl of c.checked ? [] : rest)
1771
1859
  miss(sl, `${restWhy(sl)}: ${c.why}`);
1772
1860
  }
@@ -1782,7 +1870,7 @@ export function proveProgress(m, laws, p) {
1782
1870
  if (!base.proven || !base.checked)
1783
1871
  return { proven: false, nodes: base.nodes, leaves: base.leaves, ...(base.failed ? { failed: base.failed } : {}), checked: false };
1784
1872
  const ls = base.laws ?? laws;
1785
- const instances = instancesFor(m, ls, inst => progressObligations(m, ls, inst, p));
1873
+ const instances = instancesFor(plainOf(m), ls, inst => progressObligations(m, ls, inst, p));
1786
1874
  const trees = {};
1787
1875
  let nodes = base.nodes, leaves = base.leaves;
1788
1876
  for (const goal of progressObligations(m, ls, instances, p)) {
@@ -1798,7 +1886,7 @@ export function proveProgress(m, laws, p) {
1798
1886
  // then the allowed goal translated, core/cyclic.ts's allowTranslated, its last node BridgeRules.lean's cycAOk: from
1799
1887
  // every reachable state, every request meeting the region and its terms is allowed; where GDP_CERT_SEARCH=1 and that
1800
1888
  // isn't proven, allowNode searched with the witnesses withWitness finds)
1801
- const alone = JSON.stringify(p.then) === JSON.stringify(trueC) && !m.history && !m.inputMaps?.length && m.assume !== undefined;
1889
+ const alone = JSON.stringify(p.then) === JSON.stringify(trueC) && !m.history && !sumsWhy(m) && !m.inputMaps?.length && m.assume !== undefined;
1802
1890
  if (certOn() && alone && checked && base.proof) {
1803
1891
  const lp = base.proof, q = hasQuantified(m), goal = progressObligations(m, ls, instances, p)[0];
1804
1892
  const translated = (st) => translatedProof(() => JSON.stringify(['allowed', m, ls, lp.instances, instances, p]), reused => {
@@ -1847,18 +1935,67 @@ export function proveProgress(m, laws, p) {
1847
1935
  // liveness is covered exactly where every part has its cyclic certificate (`cyclic: {kind: 'liveness', ...}`), and
1848
1936
  // uncovered, with the part's why, where one is on the usual rule.
1849
1937
  // (`uncovered`, where the certificate is on: why each part is on the usual rule; none, the liveness is covered)
1850
- export function proveLiveness(m, laws, l) {
1938
+ // Under strong fairness, where no levels are given: each helpful request's goal tried handing over to no region and to
1939
+ // each other one alone (levels 0 but its own and that one's), then levels from the hand-overs that end at a request
1940
+ // reaching `to` or lowering the rank (each level above the one it hands over from: no cycle). Undefined where none.
1941
+ export function chooseLevels(m, laws, l) {
1942
+ // (help i at level 0 hands over to j alone at level 1, or to none: every level 0)
1943
+ const n = livenessHelpful(l).length, at = (j) => Array.from({ length: n }, (_, x) => (x === j ? 1 : 0));
1944
+ const proves = (i, j) => { const r = proveStepLaws(m, laws, [livenessParts(m, { ...l, levels: at(j) }).helps[i]]); return r.proven && r.checked; };
1945
+ const dist = Array.from({ length: n }, (_, i) => (proves(i) ? 0 : undefined));
1946
+ if (dist.every(d => d === 0))
1947
+ return dist.map(() => 0);
1948
+ const edges = Array.from({ length: n }, (_, i) => (dist[i] === 0 ? [] : Array.from({ length: n }, (_, j) => j).filter(j => j !== i && proves(i, j))));
1949
+ for (let round = 0; round < n; round++)
1950
+ for (let i = 0; i < n; i++)
1951
+ if (dist[i] === undefined) {
1952
+ const ds = edges[i].flatMap(j => (dist[j] === undefined ? [] : [dist[j]]));
1953
+ if (ds.length)
1954
+ dist[i] = Math.min(...ds) + 1;
1955
+ }
1956
+ if (dist.some(d => d === undefined))
1957
+ return undefined;
1958
+ const top = Math.max(...dist);
1959
+ return dist.map(d => top - d);
1960
+ }
1961
+ export function proveLiveness(m, laws, given) {
1962
+ // (strong fairness: the levels the helpful requests hand over by, where they aren't given)
1963
+ const lv = strongly(given) && !given.levels && livenessHelpful(given).length > 1 ? chooseLevels(m, laws, given) : undefined;
1964
+ const l = lv ? { ...given, levels: lv } : given;
1851
1965
  const { stay, cover, helps } = livenessParts(m, l);
1852
1966
  const a = proveStepLaws(m, laws, [stay, cover, ...helps]);
1853
1967
  if (!a.proven || !a.checked)
1854
1968
  return { proven: false, nodes: a.nodes, leaves: a.leaves, ...(a.failed ? { failed: a.failed } : {}), checked: false };
1855
- const plain = m.history ? historyMachine(m).machine : m;
1969
+ const plain = plainOf(m);
1856
1970
  let nodes = a.nodes, leaves = a.leaves;
1857
1971
  const left = [...(a.uncovered ?? []).map(why => `a step law: ${why}`)];
1858
1972
  for (const [i, h] of livenessHelpful(l).entries()) {
1859
- if (m.history || plain.inputMaps?.length || !plain.assume || !plain.inputs.every(inp => inp in h.request))
1973
+ // (a machine with sums: allowed by the rule's own assumption, its plain machine's facts given; Sums.lean)
1974
+ const own = sumsWhy(m) ? m.assume : plain.assume;
1975
+ // Under strong fairness the claim reads each helpful request allowed in its region (Live.lean's sleads_sf_soundA):
1976
+ // proven always, the inputs it leaves free given witness terms.
1977
+ if (strongly(l)) {
1978
+ if (m.history || plain.inputMaps?.length)
1979
+ return { proven: false, nodes, leaves, failed: { goal: `${l.name}: helpful request ${i + 1} is allowed`, stuck: 'a history or carried maps: no request allowed shown under strong fairness' }, checked: false };
1980
+ if (!own)
1981
+ continue;
1982
+ const w = withWitness(plain, h.request, wit => {
1983
+ if (!plain.inputs.every(inp => inp in h.request || wit.some(([x2]) => x2 === inp)))
1984
+ return undefined;
1985
+ const b = proveProgress(sumsWhy(m) ? m : plain, laws, { name: `${l.name}: helpful request ${i + 1} is allowed`, when: { op: 'and', xs: [l.from, { op: 'not', x: l.to }, h.when] }, then: trueC, request: { ...h.request, ...Object.fromEntries(wit) } });
1986
+ return b.proven && b.checked ? b : undefined;
1987
+ });
1988
+ if (!w)
1989
+ return { proven: false, nodes, leaves, failed: { goal: `${l.name}: helpful request ${i + 1} is allowed`, stuck: 'no request with its terms the assumption allows' }, checked: false };
1990
+ nodes += w.out.nodes;
1991
+ leaves += w.out.leaves;
1992
+ if (w.out.uncovered)
1993
+ left.push(`helpful request ${i + 1} allowed: ${w.out.uncovered}`);
1994
+ continue;
1995
+ }
1996
+ if (m.history || plain.inputMaps?.length || !own || !plain.inputs.every(inp => inp in h.request))
1860
1997
  continue;
1861
- const b = proveProgress(plain, laws, { name: `${l.name}: helpful request ${i + 1} is allowed`, when: { op: 'and', xs: [l.from, { op: 'not', x: l.to }, h.when] }, then: trueC, request: h.request });
1998
+ const b = proveProgress(sumsWhy(m) ? m : plain, laws, { name: `${l.name}: helpful request ${i + 1} is allowed`, when: { op: 'and', xs: [l.from, { op: 'not', x: l.to }, h.when] }, then: trueC, request: h.request });
1862
1999
  nodes += b.nodes;
1863
2000
  leaves += b.leaves;
1864
2001
  if (!b.proven || !b.checked)
@@ -1874,7 +2011,7 @@ export function proveLiveness(m, laws, l) {
1874
2011
  }
1875
2012
  else if (cyclicOn())
1876
2013
  uncovered('liveness', m.name, 'a claim about runs that never end');
1877
- return { proven: true, checked: true, nodes, leaves, steps: a, ...(certOn() ? { uncovered: left } : {}) };
2014
+ return { proven: true, checked: true, nodes, leaves, steps: a, ...(certOn() ? { uncovered: left } : {}), ...(lv ? { levels: lv } : {}) };
1878
2015
  }
1879
2016
  // A loop's halting (kernel.ts's loopObligations: its machine's laws, and its liveness's step laws, `while` failing later
1880
2017
  // from anywhere, every request helpful), its usual trees given: translated to one cyclic proof as proveStepLaws
@@ -50,6 +50,7 @@ export declare class Reader {
50
50
  private node;
51
51
  private natRows;
52
52
  private atomRows;
53
+ private leafAtomRows;
53
54
  private ls;
54
55
  private ts;
55
56
  private fs;
@@ -122,6 +123,7 @@ export declare class Reader {
122
123
  private hypsIn;
123
124
  private src;
124
125
  hypsOf(rows: Row[]): number[];
126
+ srcOf(r: Row): number | undefined;
125
127
  private inSeg;
126
128
  private cached;
127
129
  private termKeys;
@@ -68,6 +68,7 @@ export class Reader {
68
68
  node = 0;
69
69
  natRows = new Map();
70
70
  atomRows = new Map();
71
+ leafAtomRows = new WeakMap();
71
72
  ls = new Map();
72
73
  ts = new Map();
73
74
  fs = [];
@@ -611,10 +612,10 @@ export class Reader {
611
612
  const s = this.trail.stamp(i);
612
613
  let r = this.trailStamps[i] === s ? this.trailRows[i] : undefined;
613
614
  if (!r) {
614
- const a = this.trail.lin(i), key = `${a.name}=${a.holds}`;
615
- r = this.atomRows.get(key);
616
- if (!r)
617
- this.atomRows.set(key, (r = { lin: atomOf(a.lin, a.holds).lin, w: new Set([a.name]), label: '' }));
615
+ // (by the atom's own form, not its name: kernel.ts reads the names in a form's own order, which two forms of
616
+ // one atom may not share, and the names' order is the order of the rows past the facts)
617
+ const a = this.trail.lin(i), own = this.leafAtomRows.get(a.lin) ?? this.leafAtomRows.set(a.lin, []).get(a.lin), k = a.holds ? 1 : 0;
618
+ r = own[k] ?? (own[k] = { lin: atomOf(a.lin, a.holds).lin, w: new Set([a.name]), label: '' });
618
619
  this.trailRows[i] = r;
619
620
  this.trailStamps[i] = s;
620
621
  }
@@ -702,6 +703,8 @@ export class Reader {
702
703
  if (i !== undefined)
703
704
  out.add(i);
704
705
  } return [...out]; }
706
+ // The hypothesis a live row came from (undefined for the trail's atoms, the naturals and the term columns' rows).
707
+ srcOf(r) { return this.src.get(r); }
705
708
  inSeg = new Map();
706
709
  cached = new Map();
707
710
  termKeys = [];
@@ -137,6 +137,18 @@ export declare function smachineToLean(id: string, given: Machine, laws: Law[],
137
137
  };
138
138
  noFacts?: boolean;
139
139
  kind?: KindLean;
140
+ sumTampers?: {
141
+ what: string;
142
+ m: Machine;
143
+ covers?: Record<string, E[]>;
144
+ expect: boolean;
145
+ }[];
146
+ coverTrees?: Record<string, Tree>;
147
+ liveTampers?: {
148
+ what: string;
149
+ l: Liveness;
150
+ expect: boolean;
151
+ }[];
140
152
  }): string;
141
153
  export declare const seedStepProof: (m: Machine, laws: Law[], stepLaws: StepLaw[], r: ReturnType<typeof proveStepLaws>) => void;
142
154
  export declare const cyclicCerts: () => boolean;