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.
@@ -69,6 +69,7 @@ export type Machine = {
69
69
  pre?: C;
70
70
  assume?: C;
71
71
  history?: History;
72
+ sums?: Record<string, Sum>;
72
73
  fns?: Record<string, Fn>;
73
74
  facts?: Law[];
74
75
  };
@@ -120,6 +121,10 @@ export type History = {
120
121
  after: E;
121
122
  };
122
123
  };
124
+ export type Sum = {
125
+ key: string;
126
+ term: E;
127
+ };
123
128
  export type MapUpdate = {
124
129
  key: E;
125
130
  value: E;
@@ -5,7 +5,7 @@
5
5
  // Arithmetic is linear: +, −, × by a constant, min, max, if. Maps are naturals indexed by naturals, every cell starting
6
6
  // at the same value; a law about a map holds for every key x, and is proven at one arbitrary x (with the law assumed at
7
7
  // every other key the step reads).
8
- import { boundOf, crossFree, historyMachine, keyTerm, plainKey, scope } from "../kernel/kernel.js";
8
+ import { boundOf, crossFree, historyMachine, keyTerm, plainKey, scope, sumRuntime } from "../kernel/kernel.js";
9
9
  import { add, env, eq, k, le, lt, nat, scale, show, solve, sub, v } from "./solver.js";
10
10
  export const seeded = (seed) => { let x = seed; return k => { x = (x * 1103515245 + 12345) % 2 ** 31; return Math.floor(x / 2 ** 31 * k); }; };
11
11
  // Every object in a term, the term first.
@@ -321,9 +321,9 @@ function writeEvery(w, env, st, m) {
321
321
  // The machine a runtime steps (with a history, kernel.ts's plain machine), its queries, and the inputs a request carries.
322
322
  function runnable(m) {
323
323
  const h = m.history;
324
+ const plain = h ? historyMachine(m).machine : sumRuntime(m);
324
325
  if (!h)
325
- scope(m);
326
- const plain = h ? historyMachine(m).machine : m;
326
+ scope(plain);
327
327
  const queries = h ? Object.keys(h.queries) : [];
328
328
  return { h, plain, queries, carried: m.inputs.filter(i => !queries.includes(i)) };
329
329
  }
@@ -1,6 +1,19 @@
1
- import { type Lin } from '../core/solver.js';
1
+ import { type Lin, type Step } from '../core/solver.js';
2
2
  import { type Goal, type Path } from './kernel.js';
3
3
  import { type Outcome } from './prove.js';
4
+ type DagNode = {
5
+ inputs: Lin[];
6
+ steps: Step[];
7
+ src?: number[];
8
+ lits?: [Lin, boolean][];
9
+ } | {
10
+ res: [number, number];
11
+ on: Lin;
12
+ };
13
+ export type Dag = {
14
+ nodes: DagNode[];
15
+ top: number;
16
+ };
4
17
  export declare const cdclStats: {
5
18
  on: boolean;
6
19
  runs: number;
@@ -36,6 +49,7 @@ export declare const cdclStats: {
36
49
  export declare const REFUTED = "refuted, not unfolded";
37
50
  export type Refuted = Outcome & {
38
51
  core?: number[];
52
+ dag?: Dag;
39
53
  };
40
54
  export declare function growCdcl(goal: Goal, root: Path, budget: {
41
55
  nodes: number;
@@ -45,14 +59,17 @@ export declare function growCdcl(goal: Goal, root: Path, budget: {
45
59
  model?: boolean;
46
60
  wall?: number;
47
61
  core?: boolean;
62
+ dag?: boolean;
48
63
  }): Outcome;
49
64
  export declare function cdclSession(goal: Goal, root: Path, opts?: {
50
65
  maxLeaves?: number;
51
66
  model?: boolean;
52
67
  core?: boolean;
68
+ dag?: boolean;
53
69
  }): {
54
70
  run: (b: {
55
71
  nodes: number;
56
72
  until?: number;
57
73
  }, w?: number, assume?: Lin) => Outcome;
58
74
  };
75
+ export {};
@@ -25,7 +25,7 @@ import { Reader, namesOf } from "./reader.js";
25
25
  import { Simplex } from "./simplex.js";
26
26
  // A derivation's own inputs: the rows it reads, in order, and the steps renumbered to them.
27
27
  function localize(rows, steps) {
28
- const inputs = [], at = new Map();
28
+ const inputs = [], at = new Map(), from = [];
29
29
  const out = steps.map(st => {
30
30
  if (st.kind !== 'input')
31
31
  return st;
@@ -34,10 +34,11 @@ function localize(rows, steps) {
34
34
  j = inputs.length;
35
35
  at.set(st.index, j);
36
36
  inputs.push(rows[st.index].lin);
37
+ from.push(st.index);
37
38
  }
38
39
  return { ...st, index: j };
39
40
  });
40
- return { inputs, steps: out };
41
+ return { inputs, steps: out, from };
41
42
  }
42
43
  // An atom's variable: the smaller of its canonical text and its flip's (remembered per form).
43
44
  const keyMemo = new WeakMap();
@@ -84,7 +85,7 @@ export function cdclSession(goal, root, opts = {}) {
84
85
  let sx = useLp ? new Simplex() : undefined;
85
86
  const nodes = [], clauses = [], occ = new Map();
86
87
  // (with opts.core: each leaf's hypotheses, by node; the hypothesis each row at this node came from)
87
- const leafHyps = new Map(), wantCore = !!(opts.core && opts.model);
88
+ const leafHyps = new Map(), wantCore = !!(opts.core && opts.model), wantDag = !!(opts.dag && opts.model);
88
89
  const hypsOf = (rs) => {
89
90
  return reader.hypsOf(rs);
90
91
  };
@@ -263,8 +264,8 @@ export function cdclSession(goal, root, opts = {}) {
263
264
  };
264
265
  // A leaf: the decisions of a reason (the root's are every leaf's, below which the tree starts: not literals of its
265
266
  // clause) and a derivation over the rows it reads.
266
- const leafNode = (w, inputs, steps, extra, hyps) => {
267
- nodes.push({ inputs, steps });
267
+ const leafNode = (w, inputs, steps, extra, hyps, src) => {
268
+ nodes.push(src ? { inputs, steps, src } : { inputs, steps });
268
269
  if (hyps)
269
270
  leafHyps.set(nodes.length - 1, hyps);
270
271
  st.leaves++;
@@ -274,6 +275,8 @@ export function cdclSession(goal, root, opts = {}) {
274
275
  lits.set(name, vars.get(name).val);
275
276
  if (extra)
276
277
  lits.set(extra[0], extra[1]);
278
+ if (src)
279
+ nodes.at(-1).lits = [...lits].map(([name, val]) => [vars.get(name).lin, val]);
277
280
  st.coreSize += lits.size;
278
281
  return { lits, node: nodes.length - 1 };
279
282
  };
@@ -286,7 +289,7 @@ export function cdclSession(goal, root, opts = {}) {
286
289
  w.add(name);
287
290
  st.pathSize += trail.length - fixed;
288
291
  const local = localize(rows, steps);
289
- return leafNode(w, local.inputs, local.steps, undefined, wantCore ? hypsOf(steps.flatMap(s => (s.kind === 'input' ? [rows[s.index]] : []))) : undefined);
292
+ return leafNode(w, local.inputs, local.steps, undefined, wantCore ? hypsOf(steps.flatMap(s => (s.kind === 'input' ? [rows[s.index]] : []))) : undefined, wantDag ? local.from.map(i => reader.srcOf(rows[i]) ?? -1) : undefined);
290
293
  }, ms => { st.coreMs += ms; });
291
294
  // Bound propagation's reasons, made when conflict analysis reads them: the atom's bounds (single-variable rows at the
292
295
  // trail then) and its other side refute each other, a leaf at the bounds' reasons with that side decided.
@@ -298,7 +301,7 @@ export function cdclSession(goal, root, opts = {}) {
298
301
  const s = solve(local);
299
302
  if (s.kind !== 'refuted')
300
303
  throw new Error('a bound propagation its bounds do not refute');
301
- const loc = localize(local, s.steps), made = leafNode(b.w, loc.inputs, loc.steps, [b.name, !b.val], b.hyps);
304
+ const loc = localize(local, s.steps), made = leafNode(b.w, loc.inputs, loc.steps, [b.name, !b.val], b.hyps, b.src && loc.from.map(i => b.src[i] ?? -1));
302
305
  c.lits = made.lits;
303
306
  c.node = made.node;
304
307
  }, ms => { st.coreMs += ms; });
@@ -497,7 +500,7 @@ export function cdclSession(goal, root, opts = {}) {
497
500
  for (const n of rowsR[i].w)
498
501
  w.add(n);
499
502
  clauses.push({ lits: new Map([[name, !val]]), node: -1 });
500
- pending.set(clauses.length - 1, { w, used: used.map(i => full[i].lin), name, val, ...(wantCore ? { hyps: hypsOf(used.map(i => rowsR[i])) } : {}) });
503
+ pending.set(clauses.length - 1, { w, used: used.map(i => full[i].lin), name, val, ...(wantCore ? { hyps: hypsOf(used.map(i => rowsR[i])) } : {}), ...(wantDag ? { src: used.map(i => reader.srcOf(rowsR[i]) ?? -1) } : {}) });
501
504
  assign(name, val, clauses.length - 1);
502
505
  forced++;
503
506
  break;
@@ -630,6 +633,8 @@ export function cdclSession(goal, root, opts = {}) {
630
633
  for (;;) {
631
634
  if (!c.lits.size) {
632
635
  if (opts.model) {
636
+ if (wantDag)
637
+ return { stuck: 'unknown', path: new Map(), why: REFUTED, dag: { nodes, top: c.node } };
633
638
  if (!wantCore)
634
639
  return { stuck: 'unknown', path: new Map(), why: REFUTED };
635
640
  // the hypotheses the leaves below the empty clause read (a clause never made into a node, a bound's not yet
@@ -73,6 +73,18 @@ export declare function historyMachine(m: Machine): {
73
73
  machine: Machine;
74
74
  goals: Goal[];
75
75
  };
76
+ export declare const sumParts: (s: string) => {
77
+ flag: string;
78
+ x: string;
79
+ };
80
+ export declare function sumCovers(m: Machine): Record<string, E[]>;
81
+ export declare function sumMachine(m: Machine, given?: Record<string, E[]>): {
82
+ machine: Machine;
83
+ goals: Goal[];
84
+ };
85
+ export declare function sumRuntime(m: Machine): Machine;
86
+ export declare const plainOf: (m: Machine) => Machine;
87
+ export declare const sideGoals: (m: Machine) => Goal[];
76
88
  export declare function obligations(m: Machine, laws: Law[], instances?: Record<string, Instances>, only?: number): Goal[];
77
89
  export declare function checkLaws(m: Machine, laws: Law[], proof: {
78
90
  instances: Record<string, Instances>;
@@ -116,7 +128,7 @@ export declare const coverGoal: (r: {
116
128
  }) => Goal;
117
129
  export declare function caseGoals(l: Loop, r: Pick<Recur, 'set' | 'wit'>, cases: Pick<RecurCases['cases'][number], 'pins' | 'cond'>[]): Goal[];
118
130
  export declare function checkRecurCases(l: Loop, r: RecurCases): boolean;
119
- export declare function progressObligations(m: Machine, laws: Law[], instances: Instances, p: {
131
+ export declare function progressObligations(m0: Machine, laws: Law[], instances: Instances, p: {
120
132
  name: string;
121
133
  when: C;
122
134
  then: C;
@@ -133,7 +145,11 @@ export type Liveness = {
133
145
  rank: E | E[];
134
146
  request?: Record<string, E>;
135
147
  helpful?: Helpful[];
148
+ fairness?: 'weak' | 'strong';
149
+ levels?: number[];
136
150
  };
151
+ export declare const strongly: (l: Liveness) => boolean;
152
+ export declare const livenessLevels: (l: Liveness) => number[];
137
153
  export declare const trueC: C, falseC: C;
138
154
  export declare const livenessRanks: (l: Liveness) => E[];
139
155
  export declare const livenessHelpful: (l: Liveness) => {
@@ -1027,11 +1027,170 @@ export function historyMachine(m) {
1027
1027
  }
1028
1028
  return { machine, goals };
1029
1029
  }
1030
+ // --- sums over a map's keys (Sums.lean) ---------------------------------------------------------------------------
1031
+ // A machine with sums as a plain one, as Sums.lean's SumMachine.plain builds it: each sum S a state variable from 0, after
1032
+ // each step (S + new) ∸ old, where old and new are the term's values at the cover keys (each key once: a key equal to an
1033
+ // earlier one adds 0) before and after the step; conjoined to the assumption, old ≤ S and a quantified flag that holds
1034
+ // at every key k: the term at k and at the cover keys, each once, is at most S. Sound because every sum is exact in every
1035
+ // reachable state (Sums.lean's sum_holds): the term starts 0 at every key, a step changes it at the cover keys alone
1036
+ // (a map it reads written at one key: that key; written at every key: the keys its value compares the bound key with,
1037
+ // each other key kept, the cover goals returned), so the facts hold of every request there (sum_allowed). The cover keys
1038
+ // read no flag (a quantified flag reads none; Lean inlines the rest, here nothing to inline).
1039
+ const ZERO = { op: 'const', value: 0 };
1040
+ const TRUE_C = { op: '<=', a: ZERO, b: ZERO };
1041
+ // Sums.lean's dTermE: G at each listed key, a key equal to an earlier one read as 0.
1042
+ const dTerm = (G, cs) => (cs.length ? { op: 'add', a: G(cs[0]), b: dTerm(t => ({ op: 'if', c: { op: '=', a: t, b: cs[0] }, then: ZERO, else: G(t) }), cs.slice(1)) } : ZERO);
1043
+ // A term over the maps at the key alone (Sums.lean's gOkE): no variable but in a map's key, and that key the variable.
1044
+ const sumTermOk = (e, key) => {
1045
+ switch (e.op) {
1046
+ case 'var': return false;
1047
+ case 'const': return true;
1048
+ case 'get': return e.key.op === 'var' && e.key.name === key;
1049
+ case 'mul': return sumTermOk(e.a, key);
1050
+ case 'if': return sumCondOk(e.c, key) && sumTermOk(e.then, key) && sumTermOk(e.else, key);
1051
+ case 'add':
1052
+ case 'sub':
1053
+ case 'min':
1054
+ case 'max':
1055
+ case 'prod': return sumTermOk(e.a, key) && sumTermOk(e.b, key);
1056
+ default: return unreachable(e);
1057
+ }
1058
+ };
1059
+ const sumCondOk = (c, key) => c.op === 'flag' || c.op === 'all' ? false : c.op === 'not' ? sumCondOk(c.x, key)
1060
+ : c.op === 'and' || c.op === 'or' ? c.xs.every(y => sumCondOk(y, key)) : sumTermOk(c.a, key) && sumTermOk(c.b, key);
1061
+ // The names a sum's parts go by: its quantified flag, the cover goals' key.
1062
+ export const sumParts = (s) => ({ flag: `cells$${s}`, x: `x$${s}` });
1063
+ // The keys a write at every key compares its bound key with (k = t, t not reading k): where else it keeps every cell.
1064
+ function comparedKeys(t, key, out) {
1065
+ if (t.op === '=' && t.a.op === 'var' && t.a.name === key && !readsKey(t.b, key))
1066
+ out.set(JSON.stringify(t.b), t.b);
1067
+ else if (t.op === '=' && t.b.op === 'var' && t.b.name === key && !readsKey(t.a, key))
1068
+ out.set(JSON.stringify(t.a), t.a);
1069
+ for (const x of Object.values(t))
1070
+ if (x && typeof x === 'object')
1071
+ (Array.isArray(x) ? x : [x]).forEach(y => comparedKeys(y, key, out));
1072
+ }
1073
+ // Each sum's cover keys, in the order of the maps its term reads (first read first).
1074
+ export function sumCovers(m) {
1075
+ return Object.fromEntries(Object.entries(m.sums ?? {}).map(([s, sum]) => {
1076
+ const out = new Map();
1077
+ for (const map of [...new Set([...JSON.stringify(sum.term).matchAll(/"op":"get","map":"([^"]+)"/g)].map(x2 => x2[1]))]) {
1078
+ const w = m.step.maps?.[map];
1079
+ if (!w)
1080
+ continue;
1081
+ if ('each' in w)
1082
+ comparedKeys(w.value, w.each, out);
1083
+ else
1084
+ out.set(JSON.stringify(w.key), w.key);
1085
+ }
1086
+ return [s, [...out.values()]];
1087
+ }));
1088
+ }
1089
+ // `given`: each sum's cover keys (core/conformance.ts's tampered twins), else sumCovers'.
1090
+ export function sumMachine(m, given) {
1091
+ const sums = Object.entries(m.sums ?? {});
1092
+ if (!sums.length)
1093
+ return { machine: m, goals: [] };
1094
+ if (m.history)
1095
+ throw new Error(`${m.name}: sums over a map's keys go on a machine without a history`);
1096
+ const covers = given ?? sumCovers(m), flags = m.step.flags ?? {};
1097
+ // (substitutions that leave each flag as it is: Lean reads a flag as its variable in the step's view)
1098
+ const same = Object.fromEntries(Object.keys(flags).map(f => [f, { op: 'flag', name: f }]));
1099
+ // (a sum may be declared in the state, at 0, which no step sets: a state variable the plain machine moves)
1100
+ for (const [s] of sums)
1101
+ if (s in m.state && JSON.stringify(m.state[s]) !== JSON.stringify(ZERO) || s in (m.step.state ?? {}))
1102
+ throw new Error(`${m.name}: the sum ${s} starts at 0 and no step sets it`);
1103
+ // (every name the machine has, as the Lean twin numbers them: a flag f's variable ?f, a quantified flag's witnesses,
1104
+ // the keys writes at every key and quantified flags bind)
1105
+ const names = [...m.params, ...m.inputs, ...Object.keys(m.state).filter(n => !(n in m.sums)), ...Object.keys(m.maps ?? {}), ...(m.inputMaps ?? []), ...Object.keys(m.fns ?? {}),
1106
+ ...Object.keys(flags), ...Object.keys(flags).map(f => `?${f}`), ...Object.entries(flags).flatMap(([f, c]) => (c.op === 'all' ? [...witnessesOf(f, c), ...boundOf(c)] : [])),
1107
+ ...Object.values(m.step.maps ?? {}).flatMap(w => ('each' in w ? [w.each] : []))];
1108
+ const steps = {}, qflags = {}, facts = [], goals = [];
1109
+ for (const [s, sum] of sums) {
1110
+ const { term, key } = sum, { flag, x } = sumParts(s), cs = covers[s];
1111
+ const read = [...new Set([...JSON.stringify(term).matchAll(/"op":"get","map":"([^"]+)"/g)].map(x2 => x2[1]))];
1112
+ const bad = (why) => { throw new Error(`${m.name}: the sum ${s}: ${why}`); };
1113
+ for (const name of [s, key, flag, x]) {
1114
+ plainName(m.name, name);
1115
+ if (names.includes(name) || name in (m.sums ?? {}) && name !== s)
1116
+ bad(`${name} is already a name of the machine`);
1117
+ }
1118
+ if (new Set([s, key, flag, x, `?${flag}`, `w?${flag}`]).size !== 6 || names.includes(`?${flag}`) || names.includes(`w?${flag}`))
1119
+ bad('its names collide');
1120
+ if (!natural(term) || !sumTermOk(term, key))
1121
+ bad(`its term reads the maps at ${key} alone, and no other name`);
1122
+ for (const map of read) {
1123
+ if ((m.inputMaps ?? []).includes(map) || (m.fns ?? {})[map] || !(map in (m.maps ?? {})))
1124
+ bad(`${map} is not a map of the machine's state`);
1125
+ }
1126
+ // 0 where every map holds its start value (Sums.lean's startVal: the term with each read its map's start).
1127
+ const atStart = substE(term, { vars: {}, maps: Object.fromEntries(read.map(map => [map, () => ({ op: 'const', value: m.maps[map] })])), flags: same });
1128
+ if (natE(atStart, {}) !== 0n)
1129
+ bad('its term is not 0 at the start');
1130
+ for (const c of cs)
1131
+ if (JSON.stringify(c).includes('"op":"flag"') || readsKey(c, key) || readsKey(c, x))
1132
+ bad('a key a step writes it at reads a flag');
1133
+ // (Sums.lean's sumOk1: a map the term reads written at one key has that key among the cover keys)
1134
+ for (const map of read) {
1135
+ const w = m.step.maps?.[map];
1136
+ if (w && !('each' in w) && !cs.some(c => JSON.stringify(c) === JSON.stringify(w.key)))
1137
+ bad(`the key ${map} is written at is no cover key`);
1138
+ }
1139
+ const here = (t) => substE(term, { vars: { [key]: t }, maps: {}, flags: same });
1140
+ // A map read after the step, over the step's view (Sums.lean's postRd).
1141
+ const post = (map) => (k2) => {
1142
+ const w = m.step.maps?.[map];
1143
+ if (!w)
1144
+ return { op: 'get', map, key: k2 };
1145
+ if ('each' in w)
1146
+ return substE(w.value, { vars: { [w.each]: k2 }, maps: {}, flags: same });
1147
+ return { op: 'if', c: { op: '=', a: k2, b: w.key }, then: w.value, else: { op: 'get', map, key: k2 } };
1148
+ };
1149
+ const after = (t) => substE(term, { vars: { [key]: t }, maps: Object.fromEntries(read.map(map => [map, post(map)])), flags: same });
1150
+ const S = { op: 'var', name: s };
1151
+ steps[s] = { op: 'sub', a: { op: 'add', a: S, b: dTerm(after, cs) }, b: dTerm(here, cs) };
1152
+ qflags[flag] = { op: 'all', key, c: { op: '<=', a: dTerm(here, [{ op: 'var', name: key }, ...cs]), b: S } };
1153
+ facts.push({ op: 'and', xs: [{ op: '<=', a: dTerm(here, cs), b: S }, { op: 'flag', name: flag }] });
1154
+ // A map it reads written at every key: at a key none of the cover keys is, the write keeps the cell. Built as
1155
+ // Sums.lean's sumCoverGoal builds it (each write at every key in the machine's order, its flags inlined as Lean
1156
+ // inlines them: a flag f read as (if f's condition then 1 else 0) = 1), so the Lean export reads these goals as they are.
1157
+ const lean = { vars: {}, maps: {}, flags: Object.fromEntries(Object.entries(flagsOf(m)).map(([f, c]) => [f, flags[f].op === 'all' ? c
1158
+ : { op: '=', a: { op: 'if', c, then: { op: 'const', value: 1 }, else: ZERO }, b: { op: 'const', value: 1 } }])) };
1159
+ for (const [map, w] of Object.entries(m.step.maps ?? {})) {
1160
+ if (!('each' in w) || !read.includes(map))
1161
+ continue;
1162
+ const X = { op: 'var', name: x };
1163
+ goals.push({ name: `${s} @cover ${map}`, hyps: [substC(m.assume ?? TRUE_C, lean), ...cs.map((c) => ({ op: 'not', x: { op: '=', a: X, b: c } })),
1164
+ { op: 'not', x: { op: '=', a: substE(substE(w.value, lean), { vars: { [w.each]: X }, maps: {}, flags: {} }), b: { op: 'get', map, key: X } } }] });
1165
+ }
1166
+ }
1167
+ // (Sums.lean's sumsC: each sum's facts, then the rest, ending in 0 ≤ 0)
1168
+ const assumed = facts.reduceRight((acc, f) => ({ op: 'and', xs: [f, acc] }), TRUE_C);
1169
+ const machine = {
1170
+ ...m, sums: undefined,
1171
+ state: { ...m.state, ...Object.fromEntries(sums.map(([s]) => [s, ZERO])) },
1172
+ step: { ...m.step, flags: { ...flags, ...qflags }, state: { ...m.step.state, ...steps } },
1173
+ assume: { op: 'and', xs: [m.assume ?? TRUE_C, assumed] },
1174
+ };
1175
+ return { machine, goals };
1176
+ }
1177
+ // The machine the runtimes step: each sum a state variable kept exact by its step, the rule's own assumption.
1178
+ export function sumRuntime(m) {
1179
+ if (!m.sums || !Object.keys(m.sums).length)
1180
+ return m;
1181
+ const { machine } = sumMachine(m);
1182
+ const flags = Object.fromEntries(Object.entries(machine.step.flags ?? {}).filter(([f]) => !Object.keys(m.sums).some(s => sumParts(s).flag === f)));
1183
+ return { ...machine, step: { ...machine.step, flags }, assume: m.assume };
1184
+ }
1185
+ // The plain machine any claim is proven of: with a history kernel.ts's historyMachine's, with sums sumMachine's.
1186
+ export const plainOf = (m) => (m.history ? historyMachine(m).machine : m.sums && Object.keys(m.sums).length ? sumMachine(m).machine : m);
1187
+ // The goals beside a plain machine's own: a history's record goals, the sums' cover goals.
1188
+ export const sideGoals = (m) => (m.history ? historyMachine(m).goals : m.sums && Object.keys(m.sums).length ? sumMachine(m).goals : []);
1030
1189
  // `only`: the goals of that law alone (the prover's instance search asks for one law's at a time).
1031
1190
  export function obligations(m, laws, instances = {}, only) {
1032
- if (m.history) {
1033
- const { machine, goals } = historyMachine(m);
1034
- return [...obligations(machine, laws, instances, only), ...(only === undefined ? goals : [])];
1191
+ if (m.history || (m.sums && Object.keys(m.sums).length)) {
1192
+ const goals = sideGoals(m);
1193
+ return [...obligations(plainOf(m), laws, instances, only), ...(only === undefined ? goals : [])];
1035
1194
  }
1036
1195
  scope(m, laws);
1037
1196
  const ok = [...Object.values(m.state), ...Object.values(m.step.state ?? {}), ...Object.values(m.step.maps ?? {}).flatMap(w => ('each' in w ? [w.value] : [w.key, w.value]))].every(natural)
@@ -1330,7 +1489,10 @@ export function checkRecurCases(l, r) {
1330
1489
  // request (a term per input over the state and params) and proving it allowed (the machine's assumption holds of it)
1331
1490
  // and that the step it causes makes `then` hold. `then` reads the state before the step by plain names and after it by
1332
1491
  // primed names (s', and M'[k] as a read of the map named M'). The laws assumed must be proven inductive on their own.
1333
- export function progressObligations(m, laws, instances, p) {
1492
+ // A machine with sums: the request is allowed by the rule's own assumption (the facts its plain machine assumes besides
1493
+ // hold of every request where the sums are exact: Sums.lean's sum_allowed).
1494
+ export function progressObligations(m0, laws, instances, p) {
1495
+ const m = plainOf(m0), own = m0.sums && Object.keys(m0.sums).length ? m0.assume : m.assume;
1334
1496
  if (!m.inputs.every(i => i in p.request) || !Object.values(p.request).every(natural) || mentions(p.when, m.inputs))
1335
1497
  throw new Error('outside the kernel');
1336
1498
  for (const e of Object.values(p.request))
@@ -1344,10 +1506,12 @@ export function progressObligations(m, laws, instances, p) {
1344
1506
  const asked = holds(reading(before, p.request), closing(m, instances));
1345
1507
  const caused = step(asked, updateOf(m));
1346
1508
  return [
1347
- ...(m.assume ? [goal(`${p.name}: the request is allowed`, asked, substC(inlineFlags(m, m.assume), req))] : []),
1509
+ ...(own ? [goal(`${p.name}: the request is allowed`, asked, substC(inlineFlags(m, own), req))] : []),
1348
1510
  goal(`${p.name}: the step it causes`, caused, across(caused, p.then, Object.keys(m.state), Object.keys(m.maps ?? {}), { inputs: p.request, flags })),
1349
1511
  ];
1350
1512
  }
1513
+ export const strongly = (l) => l.fairness === 'strong';
1514
+ export const livenessLevels = (l) => l.levels ?? livenessHelpful(l).map((_, i) => i);
1351
1515
  const zero = { op: 'const', value: 0 };
1352
1516
  export const trueC = { op: '<=', a: zero, b: zero }, falseC = { op: '<', a: zero, b: zero };
1353
1517
  const and2 = (a, b) => ({ op: 'and', xs: [a, b] }), or2 = (a, b) => ({ op: 'or', xs: [a, b] });
@@ -1364,7 +1528,7 @@ export const livenessHelpful = (l) => {
1364
1528
  };
1365
1529
  export function livenessParts(m, l) {
1366
1530
  // A machine with a history as its plain machine (its sums are state, its queries inputs no request names).
1367
- const plain = m.history ? historyMachine(m).machine : m;
1531
+ const plain = plainOf(m);
1368
1532
  const queries = Object.keys(m.history?.queries ?? {}), client = plain.inputs.filter(i => !queries.includes(i));
1369
1533
  const ranks = livenessRanks(l), helpful = livenessHelpful(l);
1370
1534
  if (!ranks.length || !helpful.length)
@@ -1383,6 +1547,18 @@ export function livenessParts(m, l) {
1383
1547
  const after = { vars: Object.fromEntries(Object.keys(plain.state).map(n => [n, { op: 'var', name: `${n}'` }])), maps: Object.fromEntries(Object.keys(plain.maps ?? {}).map(map => [map, (key) => ({ op: 'get', map: `${map}'`, key })])), flags: {} };
1384
1548
  const prime = (c) => substC(c, after), ranks2 = ranks.map(r => substE(r, after)), to2 = prime(l.to);
1385
1549
  const pending = and2(l.from, { op: 'not', x: l.to }), lower = lexLt(ranks2, ranks), regions = helpful.map(h => h.when);
1550
+ if (strongly(l)) {
1551
+ // (Live.lean's liveStaySC and liveHelpThenS: the regions of a higher level, in order)
1552
+ const levels = livenessLevels(l);
1553
+ if (levels.length !== helpful.length || !levels.every(n => Number.isInteger(n) && n >= 0))
1554
+ throw new Error(`liveness ${l.name}: a level, a natural, per helpful request`);
1555
+ return {
1556
+ stay: { name: `${l.name}: each step stays or gets there, the rank never rising`, when: pending, then: and2(or2(prime(l.from), to2), or2(to2, or2(lower, eqs(ranks2, ranks)))) },
1557
+ cover: { name: `${l.name}: some helpful request applies`, when: pending, then: anyOf(regions) },
1558
+ helps: helpful.map((h, i) => ({ name: `${l.name}: helpful request ${i + 1}`, when: and2(pending, and2(h.when, named(Object.entries(h.request)))),
1559
+ then: or2(to2, or2(lower, anyOf(regions.filter((_, j) => levels[i] < levels[j]).map(prime)))) })),
1560
+ };
1561
+ }
1386
1562
  return {
1387
1563
  stay: { name: `${l.name}: each step stays or gets there, the rank kept only with its region`, when: pending,
1388
1564
  then: and2(or2(prime(l.from), to2), or2(to2, or2(lower, and2(eqs(ranks2, ranks), keep(regions, prime))))) },
@@ -1391,7 +1567,7 @@ export function livenessParts(m, l) {
1391
1567
  };
1392
1568
  }
1393
1569
  export function stepLawObligations(machine, laws, instances, sl) {
1394
- const m = machine.history ? historyMachine(machine).machine : machine;
1570
+ const m = plainOf(machine);
1395
1571
  scope(m, laws);
1396
1572
  const k = sl.steps ?? 1;
1397
1573
  // Past 64 the cost is the bound (proving grows about as k³: 64 steps in about 5 s on Modal; Lean checks 32 in about 14 s, 64 in about 47 s).
@@ -1442,7 +1618,7 @@ export function stepLawObligations(machine, laws, instances, sl) {
1442
1618
  const lawsOnly = (inst) => Object.fromEntries(Object.entries(inst).filter(([n]) => !n.startsWith('?')));
1443
1619
  export function checkStepLaws(m, laws, stepLaws, proof) {
1444
1620
  return checkLaws(m, laws, proof.laws) && stepLaws.every(sl => {
1445
- const inst = proof.perStep?.[sl.name] ?? proof.instances, plain = m.history ? historyMachine(m).machine : m;
1621
+ const inst = proof.perStep?.[sl.name] ?? proof.instances, plain = plainOf(m);
1446
1622
  const zone = stepZone(plain, sl.steps ?? 1);
1447
1623
  return [...assumed(laws, inst), ...assumed(plain.facts ?? [], inst), ...closing(plain, lawsOnly(inst))].every(c => !mentions(c, zone))
1448
1624
  && stepLawObligations(m, laws, inst, sl).every(g => proof.trees[g.name] !== undefined && check(g, proof.trees[g.name]));
@@ -1455,7 +1631,7 @@ export const stepZone = (m, k) => [
1455
1631
  ...Array.from({ length: k - 1 }, (_, i) => Object.keys(m.state).map(n => stateName(n, i + 1))).flat(),
1456
1632
  ];
1457
1633
  export function kInductionSteps(machine, kl) {
1458
- const m = machine.history ? historyMachine(machine).machine : machine, L = kl.law, k = kl.k;
1634
+ const m = plainOf(machine), L = kl.law, k = kl.k;
1459
1635
  if (L.forall || L.keys?.length || L.some?.length || L.ex)
1460
1636
  throw new Error(`k-induction of ${L.name}: a law with no key`);
1461
1637
  if (!Number.isInteger(k) || k < 1 || k > 64)
@@ -1477,11 +1653,11 @@ export function kInductionSteps(machine, kl) {
1477
1653
  ];
1478
1654
  }
1479
1655
  export const kInductionStart = (machine, kl, instances) => {
1480
- const m = machine.history ? historyMachine(machine).machine : machine;
1656
+ const m = plainOf(machine);
1481
1657
  return obligations(m, [kl.law], { [kl.law.name]: instances })[0];
1482
1658
  };
1483
1659
  export function checkKInduction(m, laws, kl, proof) {
1484
- const steps = kInductionSteps(m, kl), plain = m.history ? historyMachine(m).machine : m;
1660
+ const steps = kInductionSteps(m, kl), plain = plainOf(m);
1485
1661
  scope(plain, [...laws, kl.law]);
1486
1662
  const start = kInductionStart(m, kl, proof.perStep?.[`${kl.law.name} @start`] ?? proof.instances);
1487
1663
  return proof.trees[start.name] !== undefined && check(start, proof.trees[start.name]) && checkStepLaws(m, laws, steps, proof);
@@ -124,6 +124,7 @@ export declare function proveLaw(m: Machine, laws: Law[], i: number): {
124
124
  stuck: string;
125
125
  witness?: Record<string, number>;
126
126
  };
127
+ export declare function lawInstances(m: Machine, laws: Law[], i: number): Instances;
127
128
  export declare const usualCheck: {
128
129
  on: boolean;
129
130
  };
@@ -153,6 +154,7 @@ export declare function proveStepLaws(given0: Machine, given: Law[], stepLaws: S
153
154
  proof?: StepProof;
154
155
  uncovered?: string[];
155
156
  };
157
+ export declare function stepLawInstances(m: Machine, laws: Law[]): (sl: StepLaw) => Instances;
156
158
  export declare function proveProgress(m: Machine, laws: Law[], p: {
157
159
  name: string;
158
160
  when: C;
@@ -163,9 +165,11 @@ export declare function proveProgress(m: Machine, laws: Law[], p: {
163
165
  trees?: Record<string, Tree>;
164
166
  uncovered?: string;
165
167
  };
166
- export declare function proveLiveness(m: Machine, laws: Law[], l: Liveness): Report & {
168
+ export declare function chooseLevels(m: Machine, laws: Law[], l: Liveness): number[] | undefined;
169
+ export declare function proveLiveness(m: Machine, laws: Law[], given: Liveness): Report & {
167
170
  steps?: ReturnType<typeof proveStepLaws>;
168
171
  uncovered?: string[];
172
+ levels?: number[];
169
173
  };
170
174
  export declare function certLoop(l: Loop, laws: Law[], rank: E | E[], trees: Record<string, Tree>, usualMs?: number): {
171
175
  checked: boolean;