gdp-wired 0.27.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.
@@ -1,7 +1,7 @@
1
1
  import { atMost, n, not, pointWrite } from "../core/machine.js";
2
2
  import { add, k, scale, sub } from "../core/solver.js";
3
- import { boundOf, check, checkRecur, recurGoal, canon, factorsOf, isCell, isMonomial, columnTerm, stateName, termColumn, historyMachine, foldObligations, kInductionStart, kInductionSteps, leafConstraints, loopLiveness, loopMachine, linear, livenessHelpful, livenessParts, livenessRanks, loopObligations, trueC, obligations, progressObligations, stepLawObligations, substC, witnessesOf, withProducts } from "../kernel/kernel.js";
4
- import { grow, minimal, proveBuilt, proveLaws, proveStepLaws, withDeadline } from "../kernel/prove.js";
3
+ import { boundOf, caseGoals, check, checkRecur, checkRecurCases, coverGoal, recurGoal, canon, decided, factorsOf, isCell, isMonomial, columnTerm, stateName, termColumn, truth, historyMachine, sumMachine, sumCovers, sumParts, foldObligations, kInductionStart, kInductionSteps, leafConstraints, loopLiveness, loopMachine, linear, livenessHelpful, livenessParts, livenessLevels, livenessRanks, strongly, loopObligations, trueC, obligations, progressObligations, stepLawObligations, substC, witnessesOf, withProducts } from "../kernel/kernel.js";
4
+ import { chooseLevels, grow, minimal, proveBuilt, proveLaws, proveStepLaws, withDeadline } from "../kernel/prove.js";
5
5
  import { refinement, refinementSides } from "../core/compose.js";
6
6
  import { leanSurface, leanTerms } from "./lean-terms.js";
7
7
  import { descentGoal, mainGoal, premiseGoal } from "../kernel/cyclic.js";
@@ -50,7 +50,81 @@ export function leaves(t, path, visit) {
50
50
  leaves(t.yes, new Map(path).set(id, { lin: t.split, holds: true }), visit);
51
51
  leaves(t.no, new Map(path).set(id, { lin: t.split, holds: false }), visit);
52
52
  }
53
- export function encode(ex, tamper = false, dropStep = true, globalVars, globalMaps, slim = false) {
53
+ // The choices Lean's linear forms look up in the table (Kernel.lean's linear and truth): at each leaf, walking what the
54
+ // leaf's hinted rows make Lean read (a hypothesis's facts, a term column's rows), every ∸, min, max or if the path
55
+ // leaves open, and only an if's branch the path takes. Undefined where a leaf has a row of no hint (Lean then reads every
56
+ // hypothesis's rows, and every term column's).
57
+ function reachedChoices(goal, leafList) {
58
+ const out = new Set();
59
+ for (const { leaf, path, base } of leafList) {
60
+ const n0 = base.length, seen = new Set();
61
+ const walkE = (e) => {
62
+ if (seen.has(e))
63
+ return;
64
+ seen.add(e);
65
+ switch (e.op) {
66
+ case 'var':
67
+ case 'const': return;
68
+ case 'mul': return walkE(e.a);
69
+ case 'get': return walkE(e.key);
70
+ case 'add':
71
+ case 'prod':
72
+ walkE(e.a);
73
+ walkE(e.b);
74
+ return;
75
+ case 'sub':
76
+ case 'min':
77
+ case 'max':
78
+ walkE(e.a);
79
+ walkE(e.b);
80
+ if (linear(e.a, path) && linear(e.b, path) && !decided(e, path))
81
+ out.add(termColumn(e));
82
+ return;
83
+ case 'if': {
84
+ walkC(e.c);
85
+ const t = truth(e.c, path);
86
+ if (t === undefined)
87
+ out.add(termColumn(e));
88
+ else
89
+ walkE(t ? e.then : e.else);
90
+ }
91
+ }
92
+ };
93
+ const walkC = (c) => {
94
+ if (seen.has(c))
95
+ return;
96
+ seen.add(c);
97
+ if (c.op === 'not')
98
+ walkC(c.x);
99
+ else if (c.op === 'and' || c.op === 'or')
100
+ c.xs.forEach(walkC);
101
+ else if (c.op === 'all')
102
+ walkC(c.c);
103
+ else if (c.op !== 'flag') {
104
+ walkE(c.a);
105
+ walkE(c.b);
106
+ }
107
+ };
108
+ for (const i of new Set([...leaf.leaf.flatMap(st => (st.kind === 'input' && st.index < n0 ? [st.index] : [])), ...(leaf.products ?? []).flat().filter(i => i < n0)])) {
109
+ const src = base[i].src;
110
+ if (!src)
111
+ return undefined;
112
+ if ('fact' in src)
113
+ walkC(goal.hyps[src.fact]);
114
+ else if ('term' in src) {
115
+ const t = columnTerm(src.term);
116
+ out.add(src.term);
117
+ walkE(t);
118
+ if (t.op === 'if') {
119
+ walkE(t.then);
120
+ walkE(t.else);
121
+ }
122
+ } // (Lean's termRowsAt reads an if's two branches)
123
+ }
124
+ }
125
+ return out;
126
+ }
127
+ export function encode(ex, tamper = false, dropStep = true, globalVars, globalMaps, slim = false, reach = false) {
54
128
  const { goal, tree } = ex;
55
129
  // `slim`: the table only has the columns Lean reads. Each row a leaf uses has a hint (where Lean looks for it first),
56
130
  // and Lean computes only the hinted hypotheses' linear forms (Kernel.lean's srcRows), so the columns are the
@@ -129,8 +203,15 @@ export function encode(ex, tamper = false, dropStep = true, globalVars, globalMa
129
203
  else if (typeof val === 'object' && val !== null)
130
204
  choices(val);
131
205
  };
132
- readHyps.forEach(choices);
133
- readTerms.forEach(choices);
206
+ // (`reach`: only the choices Lean's linear forms look up, where they can be found)
207
+ const reachedCols = reach && !slim ? reachedChoices(goal, leafList) : undefined;
208
+ if (reachedCols)
209
+ for (const name of reachedCols)
210
+ terms.add(name);
211
+ else {
212
+ readHyps.forEach(choices);
213
+ readTerms.forEach(choices);
214
+ }
134
215
  const readSubterms = [...readHyps, ...readTerms.map((t) => ({ op: '<=', a: t, b: t }))].flatMap(subterms).filter(e => e.op === 'prod' || e.op === 'get');
135
216
  for (const { leaf, path, base } of leafList) {
136
217
  const n0 = base.length;
@@ -351,9 +432,9 @@ export function loopToLean(id, l, laws, rank, tamper) {
351
432
  export function neverEndsToLean(id, l, r, tampered = []) {
352
433
  if (!checkRecur(l, r))
353
434
  throw new Error(`${id}: the certificate does not check`);
354
- const { vars, loop, recur } = recurLean(id, l, r);
435
+ const { vars, loop, recur, defs } = recurLean(id, l, r);
355
436
  return `-- ${l.name}: a run that never ends (variables ${vars.map((v2, j) => `${j} ${v2}`).join(', ')})
356
- def ${id}_loop : Loop := ${loop}
437
+ ${defs ? `${defs}\n` : ''}def ${id}_loop : Loop := ${loop}
357
438
  def ${id}_recur : Recur := ${recur(r)}
358
439
  /-- ${l.name} never ends: for some params meeting its precondition, a run of turns from the start goes on forever. -/
359
440
  theorem ${id}_never_ends : NeverEnds ${id}_loop :=
@@ -362,22 +443,73 @@ theorem ${id}_never_ends : NeverEnds ${id}_loop :=
362
443
  def ${id}_tampered${j} : Recur := ${recur(t.recur)}
363
444
  example : checkRecur ${id}_loop ${id}_tampered${j} = false := by ${checkBy}`).join('')}`;
364
445
  }
446
+ // A loop with a run that never ends, its set closed by cases (NonTerm.lean's never_ends_of_cases): the cover's and each
447
+ // case's table and tree, read against the goals Lean builds (the pins substituted, the constants folded).
448
+ export function neverEndsCasesToLean(id, l, r) {
449
+ if (!checkRecurCases(l, r))
450
+ throw new Error(`${id}: the certificate does not check`);
451
+ const { vars, loop, recur, defs } = recurCasesLean(id, l);
452
+ return `-- ${l.name}: a run that never ends, closed by ${r.cases.length} cases (variables ${vars.map((v2, j) => `${j} ${v2}`).join(', ')})
453
+ ${defs ? `${defs}\n` : ''}def ${id}_loop : Loop := ${loop}
454
+ def ${id}_recur : RecurCases := ${recur(r)}
455
+ /-- ${l.name} never ends: for some params meeting its precondition, a run of turns from the start goes on forever. -/
456
+ theorem ${id}_never_ends : NeverEnds ${id}_loop :=
457
+ never_ends_of_cases ${id}_loop ${id}_recur (by ${checkBy})`;
458
+ }
459
+ // A certificate by cases as NonTerm.lean's RecurCases (each tree written against the goal it refutes, else none).
460
+ export function recurCasesLean(id, l) {
461
+ const { vars, loop, defs } = recurLean(id, l, undefined);
462
+ const { e, c } = leanTerms(vars, [], id);
463
+ const ix = (name) => { const j = vars.indexOf(name); if (j < 0)
464
+ throw new Error(`${id}: no variable for ${name}`); return j; };
465
+ const vals = (o) => list(Object.entries(o).map(([name, v2]) => `(${ix(name)}, ${v2})`));
466
+ const cert = (goal, tree) => {
467
+ let fits = false;
468
+ try {
469
+ fits = check(goal, tree);
470
+ }
471
+ catch {
472
+ fits = false;
473
+ }
474
+ const coded = fits ? encode({ name: `${id}: ${goal.name}`, goal, tree }, false, true, vars, [], false, true) : { tab: '[]', tree: '.leafAt [] [] [] []' };
475
+ return `(${coded.tab}, [], ${coded.tree})`;
476
+ };
477
+ const recur = (r) => `⟨${list(vars.map((_, j) => String(j)))},
478
+ ${vals(r.start)},
479
+ ${list(r.stem.map(vals))},
480
+ ${c(r.set)},
481
+ ${list(Object.entries(r.wit).map(([name, t]) => `(${ix(name)}, ${e(t)})`))},
482
+ ${cert(coverGoal(r), r.cover)},
483
+ ${list(r.cases.map((k2, j) => `(${list(k2.pins.map(([n2, x]) => `(${ix(n2)}, ${x})`))}, ${c(k2.cond)}, ${cert(goals(r)[j], k2.tree)})`))}⟩`;
484
+ const made = new WeakMap(), goals = (r) => { let g = made.get(r); if (!g)
485
+ made.set(r, (g = caseGoals(l, r, r.cases))); return g; };
486
+ return { vars, loop, recur, defs };
487
+ }
365
488
  // The loop and a certificate as NonTerm.lean's Loop and Recur (the domain every variable; a certificate whose tree
366
489
  // doesn't refute its own goal carries `fallback`'s table and tree, which refutes `fallback`'s). lean-kernel/conformance.ts prints its cases with it.
490
+ // (a loop's start and body past 128 variables as definitions of 128 each, appended: Lean elaborates a list literal of
491
+ // deep terms one level deeper per entry, and pgarch's 690 body terms, each 228 rules deep, pass its recursion limit)
367
492
  export function recurLean(id, l, fallback) {
368
493
  const vars = [...l.params, ...l.inputs, ...Object.keys(l.state)];
369
494
  const { e, c } = leanTerms(vars, [], id);
370
495
  const ix = (name) => { const j = vars.indexOf(name); if (j < 0)
371
496
  throw new Error(`${id}: no variable for ${name}`); return j; };
497
+ const defs = [];
498
+ const pieces = (what, xs) => {
499
+ if (xs.length <= 128)
500
+ return list(xs);
501
+ const names = Array.from({ length: Math.ceil(xs.length / 128) }, (_, k) => { defs.push(`def ${id}_${what}${k} : List (Nat × E) := ${list(xs.slice(k * 128, k * 128 + 128))}`); return `${id}_${what}${k}`; });
502
+ return `(${names.join(' ++ ')})`;
503
+ };
372
504
  const loop = `⟨${list(l.inputs.map(name => String(ix(name))))},
373
- ${list(Object.entries(l.state).map(([name, e2]) => `(${ix(name)}, ${e(e2)})`))},
374
- ${list(Object.entries(l.body).map(([name, e2]) => `(${ix(name)}, ${e(e2)})`))},
505
+ ${pieces('init', Object.entries(l.state).map(([name, e2]) => `(${ix(name)}, ${e(e2)})`))},
506
+ ${pieces('body', Object.entries(l.body).map(([name, e2]) => `(${ix(name)}, ${e(e2)})`))},
375
507
  ${c(l.while)},
376
508
  ${l.pre ? c(l.pre) : TRUE},
377
509
  ${l.assume ? c(l.assume) : TRUE}⟩`;
378
510
  const vals = (o) => list(Object.entries(o).map(([name, v]) => `(${ix(name)}, ${v})`));
379
511
  const recur = (rr) => {
380
- const enc = (g) => encode({ name: `${id}: ${l.name} never ends`, goal: recurGoal(l, g), tree: g.tree }, false, true, vars, []);
512
+ const enc = (g) => encode({ name: `${id}: ${l.name} never ends`, goal: recurGoal(l, g), tree: g.tree }, false, true, vars, [], false, true);
381
513
  // The tree is written against the goal it refutes: the certificate's own where kernel.ts's check accepts it there,
382
514
  // else `fallback`'s (which must check), and Lean reads it against the goal it builds from `rr` either way. So every
383
515
  // number written is one kernel.ts's check replayed: integers, every cut dividing its row.
@@ -388,7 +520,7 @@ export function recurLean(id, l, fallback) {
388
520
  return false;
389
521
  } };
390
522
  // (neither refuting its goal, as a forged certificate's: a leaf with no step, the tree that refutes nothing)
391
- const by = fits(rr) ? rr : fits(fallback) ? fallback : undefined;
523
+ const by = fits(rr) ? rr : fallback && fits(fallback) ? fallback : undefined;
392
524
  const coded = by ? enc(by) : { tab: '[]', tree: '.leafAt [] [] [] []' };
393
525
  return `⟨${list(vars.map((_, j) => String(j)))},
394
526
  ${vals(rr.start)},
@@ -397,7 +529,7 @@ export function recurLean(id, l, fallback) {
397
529
  ${list(Object.entries(rr.wit).map(([name, t]) => `(${ix(name)}, ${e(t)})`))},
398
530
  (${coded.tab}, [], ${coded.tree})⟩`;
399
531
  };
400
- return { vars, loop, recur };
532
+ return { vars, loop, recur, defs: defs.join('\n') };
401
533
  }
402
534
  // Folds through Kern.fold_sound: Lean builds the leaf and node goals; the trees are the kernel's.
403
535
  export function foldToLean(id, f, laws, extra = '') {
@@ -816,7 +948,10 @@ function machineNames(m, laws, allSteps, stepLaws, opts) {
816
948
  export function smachineToLean(id, given, laws, opts = {}) {
817
949
  const hm = given.history ? { ...given, history: { ...given.history, prune: undefined } } : undefined;
818
950
  const hplain = hm ? historyMachine(hm) : undefined, stepLaws = opts.stepLaws ?? [], rf = opts.refined, gv = opts.ghosts ?? [];
819
- const m = hplain ? hplain.machine : given;
951
+ // A machine with sums goes as its plain machine too (kernel.ts's sumMachine), built in Lean (Sums.lean's
952
+ // SumMachine.plain) from the rule without them and the sums.
953
+ const sm = !hm && given.sums && Object.keys(given.sums).length ? given : undefined;
954
+ const m = hplain ? hplain.machine : sm ? sumMachine(sm).machine : given;
820
955
  const claims = [];
821
956
  const claimSteps = () => claims.flatMap(cl => cl.steps);
822
957
  // A step law's SKStep literal: its whens, then, the names its later requests and states are read by, its proof.
@@ -885,22 +1020,68 @@ theorem ${id}_refines : ∀ ρ M, SReach ${id}_refined.impl ρ M → ∃ ρc Mc
885
1020
  } });
886
1021
  // Liveness (Live.lean's sleads_sound): its step laws (stay, cover, one per helpful request), and where each helpful
887
1022
  // request is proven allowed in its region, the same under weak fairness (sleads_wf_sound).
888
- for (const [j, l] of (opts.liveness ?? []).entries()) {
1023
+ for (const [j, l0] of (opts.liveness ?? []).entries()) {
1024
+ // (strong fairness: the levels the helpful requests hand over by, chosen as proveLiveness chooses them)
1025
+ const l = strongly(l0) && !l0.levels && livenessHelpful(l0).length > 1 ? { ...l0, levels: chooseLevels(sm ?? m, laws, l0) ?? livenessLevels(l0) } : l0;
889
1026
  const { stay, cover, helps } = livenessParts(m, l), helpful = livenessHelpful(l), lid = `${id}_live${j}`;
890
1027
  const allows = helps.map((hs, i) => ({ when: hs.when, request: helpful[i].request }));
1028
+ if (strongly(l)) {
1029
+ claims.push({ steps: [stay, cover, ...helps], allows, render: h => {
1030
+ const al = allows.map(h.allow);
1031
+ if (!al.every(a => a !== undefined))
1032
+ throw new Error(`${id}: ${l.name}: under strong fairness each helpful request is shown allowed in its region`);
1033
+ const own = sm ? `${id}_sums.s.f.m.assume` : `${id}_machine.f.m.assume`;
1034
+ return `-- Liveness under strong fairness: ${l.name}
1035
+ def ${lid} : Live := ${liveLit(l, { e, c }, ix, list(Object.keys(m.state).map(s2 => `(${ix(s2)}, ${ix(`${s2}'`)})`)), list(Object.keys(m.maps ?? {}).map(mp => `(${mx(mp)}, ${mx(`${mp}'`)})`)))}
1036
+ def ${lid}_lv : List Nat := ${list(livenessLevels(l).map(String))}
1037
+ def ${lid}_sp : SProof := ${h.sproof(stay)}
1038
+ def ${lid}_cp : SProof := ${h.sproof(cover)}
1039
+ def ${lid}_hp : List SProof := ${list(helps.map(h.sproof))}
1040
+ def ${lid}_ap : List (List (Nat × E) × SProof × List E) := ${list(al)}
1041
+ theorem ${lid}_ok : sliveOk ${id}_machine ${lid} = true := by ${checkBy}
1042
+ theorem ${lid}_stay : checkSKStep ${id}_machine ${id}_proof (sliveStep ${lid} ${lid}.pend (liveStaySC ${lid}) ${lid}_sp) = true := by ${checkBy}
1043
+ theorem ${lid}_cover : checkSKStep ${id}_machine ${id}_proof (sliveStep ${lid} ${lid}.pend (liveCoverC ${lid}) ${lid}_cp) = true := by ${checkBy}
1044
+ theorem ${lid}_helps : sliveHelpsOkS ${id}_machine ${id}_proof ${lid} ${lid}_lv ${lid}_hp = true := by ${checkBy}
1045
+ theorem ${lid}_allows : sliveAllowsOkA ${id}_machine ${id}_proof ${lid} ${lid}_ap ${own} = true := by ${checkBy}
1046
+ /-- ${l.name}, under strong fairness: along every run that takes each helpful request in its region infinitely often
1047
+ wherever, infinitely often, it is allowed there, \`from\` is followed by \`to\`. -/
1048
+ theorem ${lid}_holds (run : SRun ${id}_machine)
1049
+ (fair : ∀ h ∈ ${lid}.helps, (∀ n, ∃ m, n ≤ m ∧ evalC (run.st m).1 (run.st m).2 h.1 = true ∧ ∃ ι κ, (∀ p ∈ h.2, ι p.1 = evalE (run.st m).1 (run.st m).2 p.2)
1050
+ ∧ evalC (sView ${id}_machine (run.st m).1 (run.st m).2 ι κ).1 (sView ${id}_machine (run.st m).1 (run.st m).2 ι κ).2 ${own} = true) →
1051
+ ∀ n, ∃ m, n ≤ m ∧ evalC (run.st m).1 (run.st m).2 h.1 = true ∧ ∀ p ∈ h.2, (run.req m).1 p.1 = evalE (run.st m).1 (run.st m).2 p.2) :
1052
+ ∀ n, evalC (run.st n).1 (run.st n).2 ${lid}.from_ = true → ∃ m, n ≤ m ∧ evalC (run.st m).1 (run.st m).2 ${lid}.to = true :=
1053
+ sleads_sf_soundA ${id}_machine ${id}_proof ${lid} ${lid}_lv _ _ _ _ _ ${id}_check ${lid}_ok ${lid}_stay ${lid}_cover ${lid}_helps ${lid}_allows run fair${j === 0 ? (opts.liveTampers ?? []).map(t => {
1054
+ const L = `(${liveLit(t.l, { e, c }, ix, list(Object.keys(m.state).map(s2 => `(${ix(s2)}, ${ix(`${s2}'`)})`)), list(Object.keys(m.maps ?? {}).map(mp => `(${mx(mp)}, ${mx(`${mp}'`)})`)))} : Live)`;
1055
+ const steps = strongly(t.l) ? `checkSKStep ${id}_machine ${id}_proof (sliveStep ${L} ${L}.pend (liveStaySC ${L}) ${lid}_sp)
1056
+ && checkSKStep ${id}_machine ${id}_proof (sliveStep ${L} ${L}.pend (liveCoverC ${L}) ${lid}_cp) && sliveHelpsOkS ${id}_machine ${id}_proof ${L} ${list(livenessLevels(t.l).map(String))} ${lid}_hp`
1057
+ : `checkSKStep ${id}_machine ${id}_proof (sliveStep ${L} ${L}.pend (liveStayC ${L}) ${lid}_sp)
1058
+ && checkSKStep ${id}_machine ${id}_proof (sliveStep ${L} ${L}.pend (liveCoverC ${L}) ${lid}_cp) && sliveHelpsOk ${id}_machine ${id}_proof ${L} ${lid}_hp`;
1059
+ return `\n-- TAMPERED: ${t.what}. Lean computes the check to ${t.expect}, kernel.ts's answer.\nexample : (${steps}) = ${t.expect} := by ${checkBy}`;
1060
+ }).join('') : ''}`;
1061
+ } });
1062
+ continue;
1063
+ }
891
1064
  claims.push({ steps: [stay, cover, ...helps], allows, render: h => {
892
1065
  const al = allows.map(h.allow);
893
1066
  const wf = al.every(a => a !== undefined) ? `
894
1067
  def ${lid}_ap : List (List (Nat × E) × SProof × List E) := ${list(al)}
895
- theorem ${lid}_allows : sliveAllowsOk ${id}_machine ${id}_proof ${lid} ${lid}_ap = true := by ${checkBy}
1068
+ theorem ${lid}_allows : ${sm ? `sliveAllowsOkA ${id}_machine ${id}_proof ${lid} ${lid}_ap ${id}_sums.s.f.m.assume` : `sliveAllowsOk ${id}_machine ${id}_proof ${lid} ${lid}_ap`} = true := by ${checkBy}
896
1069
  /-- ${l.name}, under weak fairness: along every run that takes each helpful request whenever, from some point on, it
897
1070
  stays allowed, \`from\` is followed by \`to\`. -/
898
1071
  theorem ${lid}_holds_wf (run : SRun ${id}_machine)
899
1072
  (fair : ∀ h ∈ ${lid}.helps, ∀ n, (∀ m, n ≤ m → ∃ ι κ, (∀ p ∈ h.2, ι p.1 = evalE (run.st m).1 (run.st m).2 p.2)
900
- ∧ evalC (sView ${id}_machine (run.st m).1 (run.st m).2 ι κ).1 (sView ${id}_machine (run.st m).1 (run.st m).2 ι κ).2 ${id}_machine.f.m.assume = true) →
1073
+ ∧ evalC (sView ${id}_machine (run.st m).1 (run.st m).2 ι κ).1 (sView ${id}_machine (run.st m).1 (run.st m).2 ι κ).2 ${sm ? `${id}_sums.s` : `${id}_machine`}.f.m.assume = true) →
901
1074
  ∃ m, n ≤ m ∧ ∀ p ∈ h.2, (run.req m).1 p.1 = evalE (run.st m).1 (run.st m).2 p.2) :
902
1075
  ∀ n, evalC (run.st n).1 (run.st n).2 ${lid}.from_ = true → ∃ m, n ≤ m ∧ evalC (run.st m).1 (run.st m).2 ${lid}.to = true :=
903
- sleads_wf_sound ${id}_machine ${id}_proof ${lid} _ _ _ _ ${id}_check ${lid}_ok ${lid}_stay ${lid}_cover ${lid}_helps ${lid}_allows run fair` : '';
1076
+ ${sm ? `sleads_wf_soundA ${id}_machine ${id}_proof ${lid} _ _ _ _ _ ${id}_check ${lid}_ok ${lid}_stay ${lid}_cover ${lid}_helps ${lid}_allows run fair` : `sleads_wf_sound ${id}_machine ${id}_proof ${lid} _ _ _ _ ${id}_check ${lid}_ok ${lid}_stay ${lid}_cover ${lid}_helps ${lid}_allows run fair`}${sm ? `
1077
+ /-- ${l.name}, for the rule with its sums under weak fairness of its own assumption: along every run of requests the
1078
+ rule allows, each helpful request taken whenever, from some point on, the rule allows it. -/
1079
+ theorem ${lid}_sums_wf (run : SumRun ${id}_sums)
1080
+ (fair : ∀ h ∈ ${lid}.helps, ∀ n, (∀ m, n ≤ m → ∃ ι κ, (∀ p ∈ h.2, ι p.1 = evalE (run.st m).1 (run.st m).2 p.2)
1081
+ ∧ evalC (sView ${id}_machine (run.st m).1 (run.st m).2 ι κ).1 (sView ${id}_machine (run.st m).1 (run.st m).2 ι κ).2 ${id}_sums.s.f.m.assume = true) →
1082
+ ∃ m, n ≤ m ∧ ∀ p ∈ h.2, (run.req m).1 p.1 = evalE (run.st m).1 (run.st m).2 p.2) :
1083
+ ∀ n, evalC (run.st n).1 (run.st n).2 ${lid}.from_ = true → ∃ m, n ≤ m ∧ evalC (run.st m).1 (run.st m).2 ${lid}.to = true :=
1084
+ sumleads_wf_sound ${id}_sums ${id}_covers ${id}_proof ${lid} _ _ _ _ ${id}_scheck ${id}_check ${lid}_ok ${lid}_stay ${lid}_cover ${lid}_helps ${lid}_allows run fair` : ''}` : '';
904
1085
  return `-- Liveness: ${l.name}
905
1086
  def ${lid} : Live := ${liveLit(l, { e, c }, ix, list(Object.keys(m.state).map(s2 => `(${ix(s2)}, ${ix(`${s2}'`)})`)), list(Object.keys(m.maps ?? {}).map(mp => `(${mx(mp)}, ${mx(`${mp}'`)})`)))}
906
1087
  def ${lid}_sp : SProof := ${h.sproof(stay)}
@@ -1001,7 +1182,7 @@ theorem ${id}_orig_laws : ∀ ρ M, SReach ${id}_ghosted.orig ρ M → ∀ e ∈
1001
1182
  ...Array.from({ length: Math.floor(qi.length / n) }, (_, t) => ({ op: 'or', xs: [eqC({ op: 'var', name: `?${f}` }, zero1(0)), at(qi.slice(t * n, (t + 1) * n))] })),
1002
1183
  { op: 'or', xs: [eqC({ op: 'var', name: `?${f}` }, zero1(1)), { op: 'not', x: at(qwits(f).map((name) => ({ op: 'var', name }))) }] }];
1003
1184
  })];
1004
- const last = { op: 'not', x: sInline(m.assume ?? trueC) }, zkeys = carriedKeys([...base, last]);
1185
+ const last = { op: 'not', x: sInline((sm ? sm.assume : m.assume) ?? trueC) }, zkeys = carriedKeys([...base, last]);
1005
1186
  return { name: 'allowed', hyps: [...base, ...(m.inputMaps ?? []).flatMap(mp => zkeys.map(t => eqC({ op: 'get', map: mp, key: t }, zero1(0)))), last], zkeys };
1006
1187
  };
1007
1188
  const allowed = new Map(claims.flatMap(cl => cl.allows).map(a => [a, withWitness(m, a.request, wit => {
@@ -1009,8 +1190,11 @@ theorem ${id}_orig_laws : ∀ ρ M, SReach ${id}_ghosted.orig ρ M → ∀ e ∈
1009
1190
  return r2.proven ? r2 : undefined;
1010
1191
  })]));
1011
1192
  const allowGoals = [...allowed.values()].flatMap(a => (a ? [a.out.goal] : []));
1193
+ // Each sum's cover goals (kernel.ts builds them as Sums.lean's sumCoverGoal does), per sum in order.
1194
+ const covers = sm ? Object.keys(sm.sums).map(s2 => sumMachine(sm).goals.filter(g => g.name.startsWith(`${s2} @cover `))) : [];
1012
1195
  const named = machineNames(m, laws, allSteps, stepLaws, { ...opts, ...(hm ? { record: hm.history.record } : {}) });
1013
- const vars = [...new Set([...named.vars, ...[...goalsL, ...goalsS, ...allowGoals, ...(hplain?.goals ?? []), ...(opts.kind ? [opts.kind.start.goal] : [])].flatMap(g => g.hyps.flatMap(varsOf))])];
1196
+ const sumNames = sm ? Object.entries(sm.sums).flatMap(([s2, sum]) => { const { flag, x } = sumParts(s2); return [s2, sum.key, `?${flag}`, `w?${flag}`, x]; }) : [];
1197
+ const vars = [...new Set([...named.vars, ...sumNames, ...[...goalsL, ...goalsS, ...allowGoals, ...(hplain?.goals ?? []), ...covers.flat(), ...(opts.kind ? [opts.kind.start.goal] : [])].flatMap(g => g.hyps.flatMap(varsOf))])];
1014
1198
  const mapNames = [...new Set([...named.maps, ...[...JSON.stringify([...goalsL, ...goalsS, ...allowGoals]).matchAll(/"op":"get","map":"([^"]+)"/g)].map(x2 => x2[1])])];
1015
1199
  const enc = (g, tree) => encode({ name: `${id}: ${g.name}`, goal: g, tree }, false, true, vars, mapNames);
1016
1200
  const { e, c } = leanTerms(vars, mapNames, id);
@@ -1040,6 +1224,45 @@ theorem ${id}_orig_laws : ∀ ρ M, SReach ${id}_ghosted.orig ρ M → ∀ e ∈
1040
1224
  ${list(rels.map(rel => { if (rel.holds.op !== '<=')
1041
1225
  throw new Error(`${id}: a relation is a <= b`); return `(${c(rel.when)}, ${e(rel.holds.a)}, ${e(rel.holds.b)})`; }))}⟩`;
1042
1226
  };
1227
+ // The sums: the rule without them (its state without their variables) and each sum (Sums.lean's SumDecl: the
1228
+ // variable, the term's key, the term, the cover keys, the quantified flag and its witness, the cover goals' key).
1229
+ const sumsDef = () => {
1230
+ const sums = Object.entries(sm.sums), cov = sumCovers(sm);
1231
+ const base = { ...sm, sums: undefined, state: Object.fromEntries(Object.entries(sm.state).filter(([n2]) => !(n2 in sm.sums))) };
1232
+ return `def ${id}_sums : SumMachine := ⟨${lit(base)},
1233
+ ${list(sums.map(([s2, sum]) => { const { flag, x } = sumParts(s2); return `⟨${ix(s2)}, ${ix(sum.key)}, ${e(sum.term)}, ${list(cov[s2].map(e))}, ${ix(`?${flag}`)}, ${ix(`w?${flag}`)}, ${ix(x)}⟩`; }))}⟩
1234
+ def ${id}_machine : SMachine := ${id}_sums.plain`;
1235
+ };
1236
+ // Each cover goal's tree, the sums' check, and what it gives: each sum exact, the rule's assumption the plain
1237
+ // machine's, the laws.
1238
+ const sumsBlock = () => {
1239
+ const trees = covers.map(gs => list(gs.map(g => {
1240
+ const t2 = opts.coverTrees?.[g.name] ?? (() => { const out = grow(g); if (!('tree' in out))
1241
+ throw new Error(`${id}: ${g.name} not proven`); return out.tree; })();
1242
+ const x2 = enc(g, t2);
1243
+ return `(${x2.tab}, ${x2.tree})`;
1244
+ })));
1245
+ const tamperLit = (t) => {
1246
+ const cov = t.covers ?? sumCovers(t.m), base = { ...t.m, sums: undefined, state: Object.fromEntries(Object.entries(t.m.state).filter(([n2]) => !(n2 in t.m.sums))) };
1247
+ return `(⟨${lit(base)},
1248
+ ${list(Object.entries(t.m.sums).map(([s2, sum]) => { const { flag, x } = sumParts(s2); return `⟨${ix(s2)}, ${ix(sum.key)}, ${e(sum.term)}, ${list(cov[s2].map(e))}, ${ix(`?${flag}`)}, ${ix(`w?${flag}`)}, ${ix(x)}⟩`; }))}⟩ : SumMachine)`;
1249
+ };
1250
+ const tampered = (opts.sumTampers ?? []).map(t => `-- TAMPERED: ${t.what}. Lean computes the check to ${t.expect}, kernel.ts's answer.
1251
+ example : (checkSums ${tamperLit(t)} ${id}_covers && checkSMachine ${tamperLit(t)}.plain ${id}_proof) = ${t.expect} := by ${checkBy}`);
1252
+ return `
1253
+ def ${id}_covers : List (List (List VDef × Tree)) := ${list(trees)}
1254
+ theorem ${id}_scheck : checkSums ${id}_sums ${id}_covers = true := by ${checkBy}
1255
+ /-- Each sum's variable is, in every state the machine reaches, the sum over every key of its term there. -/
1256
+ theorem ${id}_exact : ∀ ρ M, SReach ${id}_machine ρ M → ∀ d ∈ ${id}_sums.sums, IsSum (gAt d.g M) (ρ d.v) :=
1257
+ sum_holds ${id}_sums ${id}_scheck
1258
+ /-- There the machine allows a request exactly when the rule's own assumption does. -/
1259
+ theorem ${id}_own : ∀ ρ M, SReach ${id}_machine ρ M → ∀ ι κ, evalC (sView ${id}_machine ρ M ι κ).1 (sView ${id}_machine ρ M ι κ).2 ${id}_machine.f.m.assume
1260
+ = evalC (sView ${id}_machine ρ M ι κ).1 (sView ${id}_machine ρ M ι κ).2 ${id}_sums.s.f.m.assume :=
1261
+ sum_allowed ${id}_sums ${id}_scheck (sOk_of ${id}_check)
1262
+ ${Object.entries(sm.sums).map(([s2, sum], j) => `/-- ${s2}: the sum over every key of its term (Sums.lean's IsSum). -/
1263
+ theorem ${id}_sum${j} : ∀ ρ M, SReach ${id}_machine ρ M → IsSum (gAt (${e(sum.term)}) M) (ρ ${ix(s2)}) :=
1264
+ fun ρ M h => ${id}_exact ρ M h (${id}_sums.sums[${j}]'(by decide)) (List.getElem_mem (by decide))`).join('\n')}${tampered.length ? `\n${tampered.join('\n')}` : ''}`;
1265
+ };
1043
1266
  // Each relation's record goal and its tree, the history's check, and the laws over histories.
1044
1267
  const histBlock = () => {
1045
1268
  const records = hplain.goals.map(g => { const out = grow(g); if (!('tree' in out))
@@ -1107,14 +1330,14 @@ def ${id}_machine : SMachine := ${id}_refined.full` : gv.length ? `def ${id}_gho
1107
1330
  ${list(gv.map(v2 => `(${ix(v2)}, ${e(m.state[v2])}, ${e(m.step.state?.[v2] ?? { op: 'var', name: v2 })})`))}⟩
1108
1331
  def ${id}_machine : SMachine := ${id}_ghosted.full
1109
1332
  theorem ${id}_ghostOk : sghostOk ${id}_ghosted = true := by ${checkBy}` : hm ? `def ${id}_hist : HMachine := ${hlit(hm.history.relations ?? [])}
1110
- def ${id}_machine : SMachine := ${id}_hist.plain` : lp0 ? `def ${id}_loop : Loop := ${loopLit(lp0.loop)}
1333
+ def ${id}_machine : SMachine := ${id}_hist.plain` : sm ? sumsDef() : lp0 ? `def ${id}_loop : Loop := ${loopLit(lp0.loop)}
1111
1334
  def ${id}_machine : SMachine := ${id}_loop.machine` : `def ${id}_machine : SMachine := ${lit(m)}`}
1112
1335
  ${entries.join('\n')}
1113
1336
  def ${id}_proof : List SEntry := ${list(laws.map((_, j) => `${id}_e${j}`))}
1114
1337
  theorem ${id}_check : checkSMachine ${id}_machine ${id}_proof = true := by ${checkBy}
1115
1338
  theorem ${id}_laws : ∀ ρ M, SReach ${id}_machine ρ M → ∀ e ∈ ${id}_proof, e.Holds ρ M :=
1116
1339
  smachine_sound ${id}_machine ${id}_proof ${id}_check
1117
- ${hm ? histBlock() : readable(id, laws, vars, mapNames, { binders: '(ρ : Nat → Nat) (μ : Nat → Nat → Nat)', hyp: `SReach ${id}_machine ρ μ`, call: `${id}_laws ρ μ h`, lit: c, eLit: e })}${opts.noFacts ? '' : factsProof(id, m, mapNames, vars, opts.simp)}${opts.tamper ? `
1340
+ ${hm ? histBlock() : readable(id, laws, vars, mapNames, { binders: '(ρ : Nat → Nat) (μ : Nat → Nat → Nat)', hyp: `SReach ${id}_machine ρ μ`, call: `${id}_laws ρ μ h`, lit: c, eLit: e })}${sm ? sumsBlock() : ''}${opts.noFacts ? '' : factsProof(id, m, mapNames, vars, opts.simp)}${opts.tamper ? `
1118
1341
  -- TAMPERED: ${opts.tamper.what}. Lean computes the check to false.
1119
1342
  def ${id}_tampered : SMachine := ${lit(opts.tamper.machine)}
1120
1343
  example : checkSMachine ${id}_tampered ${id}_proof = false := by ${checkBy}` : ''}${records.length ? `\n\n${records.join('\n\n')}` : ''}${opts.after ? `\n\n${opts.after(ix)}` : ''}`;
@@ -1784,13 +2007,16 @@ function toLeanWith(items, opts) {
1784
2007
  const mopts = { stepLaws: item.stepLaws, ...(item.liveness?.length ? { liveness: item.liveness } : {}),
1785
2008
  ...(item.ghosts?.length ? { ghosts: item.ghosts } : {}), ...(item.lean?.simp ? { simp: item.lean.simp } : {}), ...(item.lean?.after ? { after: item.lean.after } : {}) };
1786
2009
  const defs = `${recurDefs(m)}${item.lean?.defs ? `${item.lean.defs}\n` : ''}`;
1787
- const cyc = certsOn ? cycMachineToLean(id, m, item.laws, mopts) : undefined;
2010
+ // (a machine with sums has no cyclic twin: the usual trees, Sums.lean)
2011
+ // (nor a liveness under strong fairness: Live.lean's sleads_sf_soundA reads the usual step laws)
2012
+ const sums = !!(m.sums && Object.keys(m.sums).length), sf = (item.liveness ?? []).some(strongly);
2013
+ const cyc = certsOn && !sums && !sf ? cycMachineToLean(id, m, item.laws, mopts) : undefined;
1788
2014
  if (cyc && 'text' in cyc)
1789
2015
  certReport.cyclic.push(item.id);
1790
2016
  else if (cyc)
1791
2017
  certReport.usual.push({ id: item.id, why: cyc.why });
1792
2018
  parts.push(`-- ${item.id}\n${defs}${cyc && 'text' in cyc ? cyc.text : smachineToLean(id, m, item.laws, mopts)}`);
1793
- theorems.push(`${id}_laws`, ...item.laws.flatMap((l, j) => (l.ex ? [`${id}.some${j}`] : [])), ...(m.history ? [`${id}_hlaws`] : []), ...(item.stepLaws ?? []).map((_, j) => `${id}_step${j}_holds`), ...(item.liveness ?? []).map((_, j) => `${id}_live${j}_holds`));
2019
+ theorems.push(`${id}_laws`, ...item.laws.flatMap((l, j) => (l.ex ? [`${id}.some${j}`] : [])), ...(m.history ? [`${id}_hlaws`] : []), ...(sums ? [`${id}_exact`, `${id}_own`] : []), ...(item.stepLaws ?? []).map((_, j) => `${id}_step${j}_holds`), ...(item.liveness ?? []).map((_, j) => `${id}_live${j}_holds`));
1794
2020
  if (item.lean?.after)
1795
2021
  theorems.push(...[...item.lean.after(() => 0).matchAll(/^theorem (\S+)/gm)].map(x2 => x2[1]));
1796
2022
  }
@@ -1822,7 +2048,7 @@ function toLeanWith(items, opts) {
1822
2048
  theorems.push(`${id}_halts`);
1823
2049
  }
1824
2050
  else if ('neverEnds' in item) {
1825
- parts.push(`-- ${item.id}\n${neverEndsToLean(id, item.neverEnds, item.recur, item.tampered ?? [])}`);
2051
+ parts.push(`-- ${item.id}\n${'cases' in item ? neverEndsCasesToLean(id, item.neverEnds, item.cases) : neverEndsToLean(id, item.neverEnds, item.recur, item.tampered ?? [])}`);
1826
2052
  theorems.push(`${id}_never_ends`);
1827
2053
  }
1828
2054
  else if ('cyclic' in item) {
@@ -1862,7 +2088,7 @@ function toLeanWith(items, opts) {
1862
2088
  }
1863
2089
  // The file the items need: Live.lean for a liveness or a loop, Sets.lean (which imports Steps.lean) for any machine.
1864
2090
  return `import History
1865
- ${items.some(item => 'neverEnds' in item) ? 'import NonTerm\n' : ''}${items.some(item => 'kInduction' in item) ? 'import KInd\n' : ''}${cycTexts ? 'import BridgeRules\n' : ''}${items.some(item => 'cyclic' in item) ? (items.some(item => 'cyclic' in item && (item.bridge || item.recur || item.fold)) ? 'import Bridge\n' : 'import Cyclic\n') : ''}${items.some(item => 'cyclic' in item && item.data) ? 'import Data\n' : ''}import ${items.some(item => 'refinement' in item) ? 'Refine' : items.some(item => 'machine' in item && (item.ghosts?.length || item.laws.some(l => l.some?.length))) ? 'Ghost' : items.some(item => ('machine' in item && item.liveness?.length) || 'loop' in item) ? 'Live' : items.some(item => 'machine' in item) ? 'Sets' : 'Steps'}
2091
+ ${items.some(item => 'machine' in item && item.machine.sums && Object.keys(item.machine.sums).length) ? 'import Sums\n' : ''}${items.some(item => 'neverEnds' in item) ? 'import NonTerm\n' : ''}${items.some(item => 'kInduction' in item) ? 'import KInd\n' : ''}${cycTexts ? 'import BridgeRules\n' : ''}${items.some(item => 'cyclic' in item) ? (items.some(item => 'cyclic' in item && (item.bridge || item.recur || item.fold)) ? 'import Bridge\n' : 'import Cyclic\n') : ''}${items.some(item => 'cyclic' in item && item.data) ? 'import Data\n' : ''}import ${items.some(item => 'refinement' in item) ? 'Refine' : items.some(item => 'machine' in item && (item.ghosts?.length || item.laws.some(l => l.some?.length))) ? 'Ghost' : items.some(item => ('machine' in item && item.liveness?.length) || 'loop' in item) ? 'Live' : items.some(item => 'machine' in item) ? 'Sets' : 'Steps'}
1866
2092
  open Kern Cert
1867
2093
  set_option maxRecDepth 100000
1868
2094
  set_option maxHeartbeats 0