gdp-wired 0.30.1 → 0.31.1

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.
@@ -8,7 +8,7 @@
8
8
  // - a refutation of a split's yes side that never reads the split refutes its parent (lift), and the no side is skipped;
9
9
  // - a hypothesis' rows and open atoms, and every term inside them, are reused from an earlier path that decided the
10
10
  // same atoms they read (kernel.ts's reusing), so a new decision reads again only what it touches.
11
- import { walkOnce } from "../core/machine.js";
11
+ import { evalC, evalE, walkOnce } from "../core/machine.js";
12
12
  import { add, costs, env, k, refuteFast, scale, solve, sub, v, work } from "../core/solver.js";
13
13
  import { checkRefutation } from "../core/check.js";
14
14
  import { allowNode, allowTranslated, certCyclic, certOn, certSearch, stepCertFloor, translateMs, closingInsts, crossCyclic, cyclicOn, cycLog, hasQuantified, loopNodes, machineNodes, proveCyclic, reqTS, searchedStepNodes, skMachine, timedKind, withWitness, translatedProof, uncovered, uncoveredWhy } from "../core/cyclic.js";
@@ -97,15 +97,22 @@ function openH(c, path, out, positive = true) {
97
97
  export const pairedKeys = { skip: false };
98
98
  // (each cell's map and key, and each pair's difference both ways, made once: the pairs are quadratic in the names, and
99
99
  // the same forms at every node keep what is remembered per form)
100
+ // (by the first cell, then the second: no key text made per lookup, the search's nodes ask for every pair again)
100
101
  const cellKeys = new Map(), cellPairs = new Map();
102
+ let cellPairsN = 0;
101
103
  export const cellPair = (a, b) => {
102
- const pk = `${a}\u0000${b}`;
103
- let pair = cellPairs.get(pk);
104
+ let row = cellPairs.get(a);
105
+ if (!row)
106
+ cellPairs.set(a, (row = new Map()));
107
+ let pair = row.get(b);
104
108
  if (!pair) {
105
- if (cellPairs.size > 200_000)
109
+ if (++cellPairsN > 200_000) {
106
110
  cellPairs.clear();
111
+ cellPairsN = 1;
112
+ cellPairs.set(a, (row = new Map()));
113
+ }
107
114
  const d = sub(cellKey(a).key, cellKey(b).key);
108
- cellPairs.set(pk, (pair = { d, neg: scale(d, -1) }));
115
+ row.set(b, (pair = { d, neg: scale(d, -1) }));
109
116
  }
110
117
  return pair;
111
118
  };
@@ -1165,48 +1172,220 @@ function keysInlined(m, keys) {
1165
1172
  return [...new Map(keys.map(e => substE(e, { vars: {}, maps: {}, flags })).map(e => [JSON.stringify(e), e])).values()];
1166
1173
  }
1167
1174
  const shifts = (m) => Object.values(m.step.maps ?? {}).some(w => 'each' in w && !plainKey(w.value, w.each));
1168
- // The keys some goals read a map at.
1169
- function mapKeys(goals) {
1170
- const out = new Map(), { inC } = eachRead(e => { out.set(JSON.stringify(e.key), e.key); });
1175
+ // The keys some goals read a map at, and at each map, in one walk.
1176
+ function mapReads(goals) {
1177
+ const all = new Map(), out = new Map();
1178
+ const { inC } = eachRead(e => { const id = JSON.stringify(e.key); all.set(id, e.key); if (!out.has(e.map))
1179
+ out.set(e.map, new Map()); out.get(e.map).set(id, e.key); });
1171
1180
  for (const g of goals)
1172
1181
  g.hyps.forEach(inC);
1173
- return [...out.values()];
1182
+ return { keys: [...all.values()], byMap: new Map([...out].map(([mp, ks]) => [mp, [...ks.values()]])) };
1183
+ }
1184
+ // A cell's key as the kernel names it (kernel.ts keyOf): `name:coef` parts joined by ',', '1' the constant; its value
1185
+ // where the names have these (a name left out is 0, as a model leaves it).
1186
+ export const keyValue = (cell, w) => {
1187
+ const inner = cell.slice(cell.indexOf('[') + 1, -1);
1188
+ if (inner.includes('['))
1189
+ return undefined;
1190
+ let value = 0;
1191
+ for (const part of inner.split(',').filter(Boolean)) {
1192
+ const at = part.lastIndexOf(':'), name = part.slice(0, at), coef = Number(part.slice(at + 1));
1193
+ if (name === '1')
1194
+ value += coef;
1195
+ else if (name in w)
1196
+ value += coef * w[name];
1197
+ else if (name.includes('['))
1198
+ return undefined;
1199
+ }
1200
+ return value;
1201
+ };
1202
+ // Instances a model asks for (model-based instantiation, as SMT solvers' MBQI and Ivy's EPR checks read a model): a
1203
+ // model of a goal whose laws about keys (and quantified flags) were assumed at some tuples only can break one at a tuple
1204
+ // of the goal's own keys it was never assumed at. That model is no counterexample: on the goal's keys (all the keys an
1205
+ // EPR-like goal has), the laws hold everywhere in a real one. Here: the model read as a state (its cells at the values
1206
+ // of their keys, a function read as a map), each law and each quantified flag the model sets evaluated at every tuple of
1207
+ // the values the goal's keys take, and each tuple where one fails added, as the goal's terms with those values, to its
1208
+ // instances. None found: the model is one on every tuple of the goal's keys. Untrusted: it chooses instances only.
1209
+ export const modelRounds = 4;
1210
+ export function modelInstances(m, laws, inst, goal, w, most = 64) {
1211
+ const pm = plainOf(m), qs = Object.entries(pm.step.flags ?? {}).filter((e) => e[1].op === 'all' && w[`?${e[0]}`] === 1);
1212
+ const keyed = laws.filter(l => l.forall);
1213
+ if (!keyed.length && !qs.length)
1214
+ return undefined;
1215
+ const fns = Object.keys(pm.fns ?? {}), mm = { ...pm, fns: undefined, maps: { ...(pm.maps ?? {}), ...Object.fromEntries(fns.map(f => [f, 0])) } };
1216
+ const maps = Object.fromEntries(Object.keys(mm.maps).map(mp => [mp, new Map()]));
1217
+ for (const [cell, value] of Object.entries(w)) {
1218
+ const br = cell.indexOf('[');
1219
+ if (br < 0 || !cell.endsWith(']') || !maps[cell.slice(0, br)])
1220
+ continue;
1221
+ const key = keyValue(cell, w);
1222
+ if (key !== undefined)
1223
+ maps[cell.slice(0, br)].set(key, value);
1224
+ }
1225
+ const st = { scalars: {}, maps }, read = (at) => new Proxy({ ...w, ...at }, { get: (t, p) => t[p] ?? 0 });
1226
+ const ev = (f) => { try {
1227
+ return f();
1228
+ }
1229
+ catch {
1230
+ return undefined;
1231
+ } };
1232
+ const valueOf = (e) => { try {
1233
+ return evalE(e, read({}), st, mm);
1234
+ }
1235
+ catch {
1236
+ return undefined;
1237
+ } };
1238
+ // Each bound key over its own sort as the model fills it: the terms its body's map reads bind matched against the
1239
+ // goal's keys (M[x·N + y] against M[a·N + b] binds x to a), one term a value; a key no read binds (or only a
1240
+ // function's), every key of the goal.
1241
+ const keys = mapReads([goal]).keys, all = new Map();
1242
+ for (const e of keys) {
1243
+ const v2 = valueOf(e);
1244
+ if (v2 !== undefined && !all.has(v2))
1245
+ all.set(v2, e);
1246
+ }
1247
+ if (!all.size)
1248
+ return undefined;
1249
+ const sortsOf = (body, names) => sortTerms(body, names, fns, () => keys).map(ts => {
1250
+ const p = new Map();
1251
+ for (const e of ts ?? []) {
1252
+ const v2 = valueOf(e);
1253
+ if (v2 !== undefined && !p.has(v2))
1254
+ p.set(v2, e);
1255
+ }
1256
+ return p.size ? p : all;
1257
+ });
1258
+ const out = { ...inst };
1259
+ let added = 0, evals = 0;
1260
+ const each = (id, names, body) => {
1261
+ const have = new Set(), had = out[id] ?? [], n = names.length, sorts = sortsOf(body, names);
1262
+ // (a law at one key assumed at a term of every value its sort takes already: nothing to add)
1263
+ if (n === 1) {
1264
+ const covered = new Set(had.map(valueOf));
1265
+ if ([...sorts[0].keys()].every(v2 => covered.has(v2)))
1266
+ return;
1267
+ }
1268
+ for (let t = 0; t + n <= had.length; t += n)
1269
+ have.add(JSON.stringify(had.slice(t, t + n)));
1270
+ const go = (i, at, terms) => {
1271
+ if (added >= most || evals > 20_000)
1272
+ return;
1273
+ if (i === n) {
1274
+ evals++;
1275
+ if (ev(() => evalC(body, read(at), st, mm)) !== false)
1276
+ return;
1277
+ const id2 = JSON.stringify(terms);
1278
+ if (have.has(id2))
1279
+ return;
1280
+ have.add(id2);
1281
+ out[id] = [...(out[id] ?? []), ...terms];
1282
+ added++;
1283
+ return;
1284
+ }
1285
+ for (const [v2, e] of sorts[i])
1286
+ go(i + 1, { ...at, [names[i]]: v2 }, [...terms, e]);
1287
+ };
1288
+ go(0, {}, []);
1289
+ };
1290
+ for (const l of keyed)
1291
+ each(l.name, [l.forall, ...(l.keys ?? [])], l.holds);
1292
+ for (const [f, q] of qs)
1293
+ each(`?${f}`, boundOf(q), q.c);
1294
+ return added ? out : undefined;
1295
+ }
1296
+ // A goal (or a law's goals) asked at some instances, and again at those its model asks for (modelInstances), up to
1297
+ // modelRounds times. `ask` is the caller's own question; `modelOf` reads a model from its answer, `settled` says it is
1298
+ // one (a proof, a model: not out of budget). The later rounds together get modelShare times the cost model's work the
1299
+ // first took (at least a second of it), so a model's tuples that make the goal one the prover can't finish cost that,
1300
+ // not the goal's usual budget again; a later round left unsettled gives back the first round's answer, so the verdict is
1301
+ // never one the model's tuples made worse. Untrusted.
1302
+ export const modelShare = 3;
1303
+ const costNow = () => (rate ? clock() : fullWork() / groundRate);
1304
+ const within = (ms, f) => (rate ? withDeadline(clock() + ms, f) : withWork(fullWork() + groundRate * ms, f));
1305
+ export function withModels(m, laws, inst, goalOf, ask, modelOf, settled) {
1306
+ let at = inst, first, cap = 0;
1307
+ for (let round = 0;; round++) {
1308
+ const c0 = costNow(), result = round ? within(Math.max(0, cap), () => ask(goalOf(at))) : ask(goalOf(at));
1309
+ if (round)
1310
+ cap -= costNow() - c0;
1311
+ else
1312
+ cap = Math.max(1_000, modelShare * (costNow() - c0));
1313
+ if (round && !settled(result))
1314
+ return first;
1315
+ first ??= { result, inst: at };
1316
+ const mw = modelOf(result), more = mw && round < modelRounds && cap > 0 ? modelInstances(m, laws, at, mw.goal, mw.w) : undefined;
1317
+ if (!more)
1318
+ return { result, inst: at };
1319
+ at = more;
1320
+ }
1174
1321
  }
1175
1322
  // Instances with each every-key law also at these keys. A law about two keys or more goes at tuples that relate the
1176
1323
  // goal's own keys (`focus`: the skolems of the law it proves, or a step law's keys) to each other and to the keys that
1177
1324
  // read none of them: at the i-th place, a key that reads the i-th focus alone (the first, past the focus there is), and
1178
1325
  // at most one place a key that reads no focus.
1179
- const withReads = (laws, inst, keys, focus) => ({ ...inst, ...Object.fromEntries(laws.filter(l => l.forall).map(l => {
1326
+ const withReads = (laws, inst, keys, focus, byMap, fns = []) => ({ ...inst, ...Object.fromEntries(laws.filter(l => l.forall).map(l => {
1180
1327
  const had = inst[l.name] ?? [];
1181
1328
  if (l.keys?.length) {
1182
- const n = l.keys.length + 1, out = new Map();
1329
+ const n = l.keys.length + 1, out = new Map(), sorted = byMap ? keySorted(l, byMap, fns) : undefined;
1183
1330
  for (let i = 0; i + n <= had.length; i += n)
1184
1331
  out.set(JSON.stringify(had.slice(i, i + n)), had.slice(i, i + n));
1185
- for (const tuple of related(keys, focus, n))
1186
- out.set(JSON.stringify(tuple), tuple);
1187
- for (const tuple of matched(l, keys))
1188
- out.set(JSON.stringify(tuple), tuple);
1332
+ for (const tuple of [...related(keys, focus, n), ...matched(l, keys)])
1333
+ if (!sorted || sorted(tuple))
1334
+ out.set(JSON.stringify(tuple), tuple);
1189
1335
  return [l.name, [...out.values()].flat()];
1190
1336
  }
1191
1337
  const seen = new Set(had.map(e => JSON.stringify(e)));
1192
1338
  return [l.name, [...had, ...keys.filter(e => { const id = JSON.stringify(e); return seen.has(id) ? false : (seen.add(id), true); })]];
1193
1339
  })) });
1340
+ // A tuple of the key's sort: each of a law's keys read at a map (M[x], M[x·N + y]) takes only the terms its read matches
1341
+ // against the keys the goals read that map at (the key's sort, as the goal holds it: Link[c1·N + s] against
1342
+ // Link[a·N + b] gives c1 a and s b); a key no read binds, or a read no goal key matches, takes any. A function's
1343
+ // argument is no sort (a function is read at any key). Untrusted: it chooses instances only.
1344
+ function keySorted(l, byMap, fns) {
1345
+ const allowed = sortTerms(l.holds, [l.forall, ...(l.keys ?? [])], fns, mp => byMap.get(mp) ?? []).map(ts => ts && new Set(ts.map(t => JSON.stringify(t))));
1346
+ return tuple => tuple.every((t, i) => !allowed[i] || allowed[i].has(JSON.stringify(t)));
1347
+ }
1348
+ // The terms `body`'s reads (not a function's) bind each of `vars` to, matched against the keys `at` gives their map.
1349
+ function sortTerms(body, vars, fns, at) {
1350
+ const out = vars.map(() => undefined);
1351
+ eachRead(e => {
1352
+ if (fns.includes(e.map) || !vars.some(x => JSON.stringify(e.key).includes(`"name":${JSON.stringify(x)}`)))
1353
+ return;
1354
+ for (const t of at(e.map)) {
1355
+ const b = matchMany(e.key, t, vars);
1356
+ if (b)
1357
+ vars.forEach((x, i) => { if (x in b)
1358
+ (out[i] ??= []).push(b[x]); });
1359
+ }
1360
+ }).inC(body);
1361
+ return out;
1362
+ }
1194
1363
  // 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
1364
  // that makes that key one the goals read (Link[a·N + b] gives (a, b)), as a fact about several keys is matched
1196
1365
  // (withFacts). A key of one bound name alone matches every key, so it binds no tuple here.
1366
+ // Where no one key names every bound name (a relation read at two pairs, Link[c1·N + s] and Link[c2·N + s]), two reads'
1367
+ // matches together bind them, as a fact's do (withFacts): at a name both bind, each one's value in turn.
1197
1368
  const matched = (l, keys) => {
1198
1369
  const vars = [l.forall, ...(l.keys ?? [])], names = (e) => vars.filter(x => JSON.stringify(e).includes(`"name":${JSON.stringify(x)}`));
1199
1370
  const pats = new Map();
1200
- eachRead(e => { if (names(e.key).length === vars.length)
1371
+ eachRead(e => { const ns = names(e.key); if (ns.length === vars.length || ns.length > 1)
1201
1372
  pats.set(JSON.stringify(e.key), e.key); }).inC(l.holds);
1202
- const out = [];
1373
+ const partial = [];
1203
1374
  for (const p of pats.values())
1204
1375
  for (const key of keys) {
1205
1376
  const b = matchMany(p, key, vars);
1206
- if (b && vars.every(x => x in b))
1207
- out.push(vars.map(x => b[x]));
1377
+ if (b)
1378
+ partial.push(b);
1208
1379
  }
1209
- return out;
1380
+ const whole = (b) => vars.every(x => x in b), out = partial.filter(whole);
1381
+ for (let i = 0; i < partial.length; i++)
1382
+ for (let j = i + 1; j < partial.length; j++) {
1383
+ const a = partial[i], b = partial[j];
1384
+ if (whole(a) || whole(b) || !vars.every(x => x in a || x in b))
1385
+ continue;
1386
+ out.push({ ...b, ...a }, { ...a, ...b });
1387
+ }
1388
+ return out.map(b => vars.map(x => b[x]));
1210
1389
  };
1211
1390
  // The n-tuples of the keys that relate the focus (withReads).
1212
1391
  const related = (keys, focus, n) => {
@@ -1344,8 +1523,8 @@ function instancesFor(m, laws, build, opts = {}) {
1344
1523
  if (m.facts?.length)
1345
1524
  inst = withFacts(m, inst, fnKeys(m, build(inst)));
1346
1525
  if (reads) {
1347
- const keys = mapKeys(build(inst));
1348
- inst = union(withReads(laws, inst, keys, opts.focus ?? []), flagInstances(m, keys, opts.focus), m);
1526
+ const { keys, byMap } = mapReads(build(inst));
1527
+ inst = union(withReads(laws, inst, keys, opts.focus ?? [], byMap, Object.keys(m.fns ?? {})), flagInstances(m, keys, opts.focus), m);
1349
1528
  }
1350
1529
  }
1351
1530
  return inst;
@@ -1554,23 +1733,54 @@ export function proveLaws(m, laws) {
1554
1733
  }
1555
1734
  // One law's two goals, every law assumed (core/infer.ts adds laws one at a time and reproves only what isn't proven
1556
1735
  // yet); not a proof of the set, which proveLaws gives. Laws with some key go through proveLaws.
1736
+ // Decisions at the simplex's point (kernel/cdcl.ts's phaseAtPoint, as its model search decides) in the goals of a law set
1737
+ // with a law about several keys, on the proof path (proveLaw, proveThinned): those goals' first rounds are often models
1738
+ // a tuple short (withModels asks again at the model's tuples), and the search deciding by its saved phases wanders before
1739
+ // it finds one (toy consensus's safety law: 108 s and 181k nodes for a model the point finds in 663; research/protocols/
1740
+ // COST.md). Untrusted: the order of the cases only.
1741
+ export const atPoint = { on: false };
1742
+ const pointed = (laws, f) => {
1743
+ if (atPoint.on || !laws.some(l => l.keys?.length))
1744
+ return f();
1745
+ atPoint.on = true;
1746
+ try {
1747
+ return f();
1748
+ }
1749
+ finally {
1750
+ atPoint.on = false;
1751
+ }
1752
+ };
1557
1753
  export function proveLaw(m, laws, i) {
1558
- const law = laws[i];
1559
1754
  if (laws.some(l => someKeys(l.holds).length) || someLaws(laws)) {
1560
1755
  const r = proveLaws(m, laws);
1561
1756
  return r.proven ? { proven: true } : { proven: false, goal: r.failed.goal, stuck: r.failed.stuck, ...(r.failed.witness ? { witness: r.failed.witness } : {}) };
1562
1757
  }
1563
- const pm = plainOf(m), inst = lawInstances(m, laws, i);
1758
+ return pointed(laws, () => proveOne(m, laws, i));
1759
+ }
1760
+ function proveOne(m, laws, i) {
1761
+ const law = laws[i], pm = plainOf(m), inst = lawInstances(m, laws, i);
1564
1762
  const few = triggered(pm, laws, inst, i2 => obligations(m, laws, { [law.name]: i2 }, i), law.forall ? [`${law.forall}#`] : []);
1565
1763
  if (!sameInstances(few, inst) && obligations(m, laws, { [law.name]: few }, i).every(goal => 'tree' in grow(goal)))
1566
1764
  return { proven: true };
1567
- for (const goal of obligations(m, laws, { [law.name]: inst }, i)) {
1765
+ // (a model breaking a law at a tuple of the goal's keys: those added, the law asked again)
1766
+ const { result: a } = withModels(m, laws, inst, i2 => obligations(m, laws, { [law.name]: i2 }, i), growAll, grownModel, grownSettled);
1767
+ return a.out ? { proven: false, goal: a.goal.name, stuck: a.out.stuck, ...(a.out.witness ? { witness: a.out.witness } : {}) } : { proven: true };
1768
+ }
1769
+ function growAll(gs) {
1770
+ const done = {};
1771
+ let n = 0, lv = 0;
1772
+ for (const goal of gs) {
1568
1773
  const out = grow(goal);
1569
1774
  if (!('tree' in out))
1570
- return { proven: false, goal: goal.name, stuck: out.stuck, ...(out.witness ? { witness: out.witness } : {}) };
1775
+ return { done, n, lv, goal, out };
1776
+ done[goal.name] = out.tree;
1777
+ n += out.nodes;
1778
+ lv += countLeaves(out.tree);
1571
1779
  }
1572
- return { proven: true };
1780
+ return { done, n, lv };
1573
1781
  }
1782
+ const grownModel = (x) => (x.out?.stuck === 'sat' && x.out.witness ? { goal: x.goal, w: x.out.witness } : undefined);
1783
+ const grownSettled = (x) => !x.out || x.out.stuck === 'sat';
1574
1784
  // The instances law i's goals are read at (proveLaw's; core/infer.ts's join asks one goal at a time).
1575
1785
  export function lawInstances(m, laws, i) {
1576
1786
  // (a machine with sums: its plain machine's instances, as proveLawsAsGiven's)
@@ -1659,31 +1869,27 @@ export const usualProof = {};
1659
1869
  // A machine with sums has no cyclic twin yet: its certificate is the usual trees, checked with its cover goals.
1660
1870
  const sumsWhy = (m) => (m.sums && Object.keys(m.sums).length ? 'a sum over a map\'s keys (Sums.lean checks the usual trees)' : undefined);
1661
1871
  function proveThinned(m, laws, instances) {
1872
+ return pointed(laws, () => thinned(m, laws, instances));
1873
+ }
1874
+ function thinned(m, laws, instances) {
1662
1875
  const trees = {}, fulls = { ...instances };
1663
1876
  let nodes = 0, leaves = 0;
1664
1877
  for (const [i, law] of laws.entries()) {
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}#`] : []);
1878
+ const full = instances[law.name];
1879
+ const few = triggered(plainOf(m), laws, full, inst => obligations(m, laws, { ...instances, [law.name]: inst }, i), law.forall ? [`${law.forall}#`] : []);
1880
+ // (thinned instances first, then the full ones; each asked again at the tuples its models ask for)
1666
1881
  for (const inst of sameInstances(few, full) ? [full] : [few, full]) {
1667
- instances[law.name] = inst;
1668
- const done = {};
1669
- let failed, n = 0, lv = 0;
1670
- for (const goal of obligations(m, laws, instances, i)) {
1671
- const out = grow(goal);
1672
- if (!('tree' in out)) {
1673
- failed = { goal: goal.name, stuck: out.stuck, ...(out.witness ? { witness: out.witness } : {}), ...(out.why ? { why: out.why } : {}) };
1674
- break;
1675
- }
1676
- done[goal.name] = out.tree;
1677
- n += out.nodes;
1678
- lv += countLeaves(out.tree);
1679
- }
1680
- if (failed && inst !== full)
1882
+ const { result: a, inst: at } = withModels(m, laws, inst, i2 => obligations(m, laws, { ...instances, [law.name]: i2 }, i), growAll, grownModel, grownSettled);
1883
+ instances[law.name] = at;
1884
+ if (inst === full)
1885
+ fulls[law.name] = at;
1886
+ if (a.out && inst !== full)
1681
1887
  continue;
1682
- if (failed)
1683
- return { proven: false, nodes, leaves, failed, checked: false };
1684
- Object.assign(trees, done);
1685
- nodes += n;
1686
- leaves += lv;
1888
+ if (a.out)
1889
+ return stuckAt(a.goal, a.out, nodes, leaves);
1890
+ Object.assign(trees, a.done);
1891
+ nodes += a.n;
1892
+ leaves += a.lv;
1687
1893
  break;
1688
1894
  }
1689
1895
  }
@@ -141,6 +141,7 @@ export declare function smachineToLean(id: string, given: Machine, laws: Law[],
141
141
  what: string;
142
142
  m: Machine;
143
143
  covers?: Record<string, E[]>;
144
+ coverLaws?: Law[];
144
145
  expect: boolean;
145
146
  }[];
146
147
  coverTrees?: Record<string, Tree>;
@@ -1191,7 +1191,7 @@ theorem ${id}_orig_laws : ∀ ρ M, SReach ${id}_ghosted.orig ρ M → ∀ e ∈
1191
1191
  })]));
1192
1192
  const allowGoals = [...allowed.values()].flatMap(a => (a ? [a.out.goal] : []));
1193
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 `))) : [];
1194
+ const covers = sm ? Object.keys(sm.sums).map(s2 => sumMachine(sm, undefined, laws).goals.filter(g => g.name.startsWith(`${s2} @cover `))) : [];
1195
1195
  const named = machineNames(m, laws, allSteps, stepLaws, { ...opts, ...(hm ? { record: hm.history.record } : {}) });
1196
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
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))])];
@@ -1247,18 +1247,25 @@ def ${id}_machine : SMachine := ${id}_sums.plain`;
1247
1247
  return `(⟨${lit(base)},
1248
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
1249
  };
1250
+ // The laws a twin's cover goals read: each the entry of its name, with its law and further keys as the twin has them.
1251
+ const coverLit = (ls) => list(ls.map(l => {
1252
+ const j = laws.findIndex(l2 => l2.name === l.name);
1253
+ if (j < 0)
1254
+ throw new Error(`${id}: no law ${l.name}`);
1255
+ return JSON.stringify(l) === JSON.stringify(laws[j]) ? `${id}_e${j}` : `{${id}_e${j} with law := ⟨${c(l.holds)}, ${l.forall ? `some ${ix(l.forall)}` : 'none'}⟩, keys2 := ${list((l.keys ?? []).map(k2 => String(ix(k2))))}}`;
1256
+ }));
1250
1257
  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}`);
1258
+ example : (checkSums ${tamperLit(t)} ${t.coverLaws ? coverLit(t.coverLaws) : `${id}_proof`} ${id}_covers && checkSMachine ${tamperLit(t)}.plain ${id}_proof) = ${t.expect} := by ${checkBy}`);
1252
1259
  return `
1253
1260
  def ${id}_covers : List (List (List VDef × Tree)) := ${list(trees)}
1254
- theorem ${id}_scheck : checkSums ${id}_sums ${id}_covers = true := by ${checkBy}
1261
+ theorem ${id}_scheck : checkSums ${id}_sums ${id}_proof ${id}_covers = true := by ${checkBy}
1255
1262
  /-- Each sum's variable is, in every state the machine reaches, the sum over every key of its term there. -/
1256
1263
  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
1264
+ sum_holds ${id}_sums ${id}_check ${id}_scheck
1258
1265
  /-- There the machine allows a request exactly when the rule's own assumption does. -/
1259
1266
  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
1267
  = 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)
1268
+ sum_allowed ${id}_sums ${id}_check ${id}_scheck
1262
1269
  ${Object.entries(sm.sums).map(([s2, sum], j) => `/-- ${s2}: the sum over every key of its term (Sums.lean's IsSum). -/
1263
1270
  theorem ${id}_sum${j} : ∀ ρ M, SReach ${id}_machine ρ M → IsSum (gAt (${e(sum.term)}) M) (ρ ${ix(s2)}) :=
1264
1271
  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')}` : ''}`;