gdp-wired 0.30.0 → 0.31.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.
@@ -8,10 +8,10 @@
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
- import { allowNode, allowTranslated, certCyclic, certOn, certSearch, closingInsts, crossCyclic, cyclicOn, cycLog, hasQuantified, loopNodes, machineNodes, proveCyclic, reqTS, searchedStepNodes, skMachine, timedKind, withWitness, translatedProof, uncovered, uncoveredWhy } from "../core/cyclic.js";
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";
15
15
  import { proveSome, someLaws } from "../core/exists.js";
16
16
  import { growCdcl } from "./cdcl.js";
17
17
  import { assumed, atomOf, boundOf, canon, canonFlip, columnTerm, decided, factorsOf, isCell, isMonomial, stepZone, check, checkLaws, checkStepLaws, historyMachine, plainOf, substC, substE, leafConstraints, leafConstraintsReusing, reusing, linear, livenessHelpful, livenessParts, strongly, loopMachine, obligations, plainKey, progressObligations, stepLawObligations, trueC, truth, unreachable, witnessesOf, withProducts } from "./kernel.js";
@@ -1165,48 +1165,220 @@ function keysInlined(m, keys) {
1165
1165
  return [...new Map(keys.map(e => substE(e, { vars: {}, maps: {}, flags })).map(e => [JSON.stringify(e), e])).values()];
1166
1166
  }
1167
1167
  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); });
1168
+ // The keys some goals read a map at, and at each map, in one walk.
1169
+ function mapReads(goals) {
1170
+ const all = new Map(), out = new Map();
1171
+ const { inC } = eachRead(e => { const id = JSON.stringify(e.key); all.set(id, e.key); if (!out.has(e.map))
1172
+ out.set(e.map, new Map()); out.get(e.map).set(id, e.key); });
1171
1173
  for (const g of goals)
1172
1174
  g.hyps.forEach(inC);
1173
- return [...out.values()];
1175
+ return { keys: [...all.values()], byMap: new Map([...out].map(([mp, ks]) => [mp, [...ks.values()]])) };
1176
+ }
1177
+ // A cell's key as the kernel names it (kernel.ts keyOf): `name:coef` parts joined by ',', '1' the constant; its value
1178
+ // where the names have these (a name left out is 0, as a model leaves it).
1179
+ export const keyValue = (cell, w) => {
1180
+ const inner = cell.slice(cell.indexOf('[') + 1, -1);
1181
+ if (inner.includes('['))
1182
+ return undefined;
1183
+ let value = 0;
1184
+ for (const part of inner.split(',').filter(Boolean)) {
1185
+ const at = part.lastIndexOf(':'), name = part.slice(0, at), coef = Number(part.slice(at + 1));
1186
+ if (name === '1')
1187
+ value += coef;
1188
+ else if (name in w)
1189
+ value += coef * w[name];
1190
+ else if (name.includes('['))
1191
+ return undefined;
1192
+ }
1193
+ return value;
1194
+ };
1195
+ // Instances a model asks for (model-based instantiation, as SMT solvers' MBQI and Ivy's EPR checks read a model): a
1196
+ // model of a goal whose laws about keys (and quantified flags) were assumed at some tuples only can break one at a tuple
1197
+ // 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
1198
+ // EPR-like goal has), the laws hold everywhere in a real one. Here: the model read as a state (its cells at the values
1199
+ // of their keys, a function read as a map), each law and each quantified flag the model sets evaluated at every tuple of
1200
+ // the values the goal's keys take, and each tuple where one fails added, as the goal's terms with those values, to its
1201
+ // instances. None found: the model is one on every tuple of the goal's keys. Untrusted: it chooses instances only.
1202
+ export const modelRounds = 4;
1203
+ export function modelInstances(m, laws, inst, goal, w, most = 64) {
1204
+ const pm = plainOf(m), qs = Object.entries(pm.step.flags ?? {}).filter((e) => e[1].op === 'all' && w[`?${e[0]}`] === 1);
1205
+ const keyed = laws.filter(l => l.forall);
1206
+ if (!keyed.length && !qs.length)
1207
+ return undefined;
1208
+ const fns = Object.keys(pm.fns ?? {}), mm = { ...pm, fns: undefined, maps: { ...(pm.maps ?? {}), ...Object.fromEntries(fns.map(f => [f, 0])) } };
1209
+ const maps = Object.fromEntries(Object.keys(mm.maps).map(mp => [mp, new Map()]));
1210
+ for (const [cell, value] of Object.entries(w)) {
1211
+ const br = cell.indexOf('[');
1212
+ if (br < 0 || !cell.endsWith(']') || !maps[cell.slice(0, br)])
1213
+ continue;
1214
+ const key = keyValue(cell, w);
1215
+ if (key !== undefined)
1216
+ maps[cell.slice(0, br)].set(key, value);
1217
+ }
1218
+ const st = { scalars: {}, maps }, read = (at) => new Proxy({ ...w, ...at }, { get: (t, p) => t[p] ?? 0 });
1219
+ const ev = (f) => { try {
1220
+ return f();
1221
+ }
1222
+ catch {
1223
+ return undefined;
1224
+ } };
1225
+ const valueOf = (e) => { try {
1226
+ return evalE(e, read({}), st, mm);
1227
+ }
1228
+ catch {
1229
+ return undefined;
1230
+ } };
1231
+ // Each bound key over its own sort as the model fills it: the terms its body's map reads bind matched against the
1232
+ // 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
1233
+ // function's), every key of the goal.
1234
+ const keys = mapReads([goal]).keys, all = new Map();
1235
+ for (const e of keys) {
1236
+ const v2 = valueOf(e);
1237
+ if (v2 !== undefined && !all.has(v2))
1238
+ all.set(v2, e);
1239
+ }
1240
+ if (!all.size)
1241
+ return undefined;
1242
+ const sortsOf = (body, names) => sortTerms(body, names, fns, () => keys).map(ts => {
1243
+ const p = new Map();
1244
+ for (const e of ts ?? []) {
1245
+ const v2 = valueOf(e);
1246
+ if (v2 !== undefined && !p.has(v2))
1247
+ p.set(v2, e);
1248
+ }
1249
+ return p.size ? p : all;
1250
+ });
1251
+ const out = { ...inst };
1252
+ let added = 0, evals = 0;
1253
+ const each = (id, names, body) => {
1254
+ const have = new Set(), had = out[id] ?? [], n = names.length, sorts = sortsOf(body, names);
1255
+ // (a law at one key assumed at a term of every value its sort takes already: nothing to add)
1256
+ if (n === 1) {
1257
+ const covered = new Set(had.map(valueOf));
1258
+ if ([...sorts[0].keys()].every(v2 => covered.has(v2)))
1259
+ return;
1260
+ }
1261
+ for (let t = 0; t + n <= had.length; t += n)
1262
+ have.add(JSON.stringify(had.slice(t, t + n)));
1263
+ const go = (i, at, terms) => {
1264
+ if (added >= most || evals > 20_000)
1265
+ return;
1266
+ if (i === n) {
1267
+ evals++;
1268
+ if (ev(() => evalC(body, read(at), st, mm)) !== false)
1269
+ return;
1270
+ const id2 = JSON.stringify(terms);
1271
+ if (have.has(id2))
1272
+ return;
1273
+ have.add(id2);
1274
+ out[id] = [...(out[id] ?? []), ...terms];
1275
+ added++;
1276
+ return;
1277
+ }
1278
+ for (const [v2, e] of sorts[i])
1279
+ go(i + 1, { ...at, [names[i]]: v2 }, [...terms, e]);
1280
+ };
1281
+ go(0, {}, []);
1282
+ };
1283
+ for (const l of keyed)
1284
+ each(l.name, [l.forall, ...(l.keys ?? [])], l.holds);
1285
+ for (const [f, q] of qs)
1286
+ each(`?${f}`, boundOf(q), q.c);
1287
+ return added ? out : undefined;
1288
+ }
1289
+ // A goal (or a law's goals) asked at some instances, and again at those its model asks for (modelInstances), up to
1290
+ // modelRounds times. `ask` is the caller's own question; `modelOf` reads a model from its answer, `settled` says it is
1291
+ // one (a proof, a model: not out of budget). The later rounds together get modelShare times the cost model's work the
1292
+ // 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,
1293
+ // not the goal's usual budget again; a later round left unsettled gives back the first round's answer, so the verdict is
1294
+ // never one the model's tuples made worse. Untrusted.
1295
+ export const modelShare = 3;
1296
+ const costNow = () => (rate ? clock() : fullWork() / groundRate);
1297
+ const within = (ms, f) => (rate ? withDeadline(clock() + ms, f) : withWork(fullWork() + groundRate * ms, f));
1298
+ export function withModels(m, laws, inst, goalOf, ask, modelOf, settled) {
1299
+ let at = inst, first, cap = 0;
1300
+ for (let round = 0;; round++) {
1301
+ const c0 = costNow(), result = round ? within(Math.max(0, cap), () => ask(goalOf(at))) : ask(goalOf(at));
1302
+ if (round)
1303
+ cap -= costNow() - c0;
1304
+ else
1305
+ cap = Math.max(1_000, modelShare * (costNow() - c0));
1306
+ if (round && !settled(result))
1307
+ return first;
1308
+ first ??= { result, inst: at };
1309
+ const mw = modelOf(result), more = mw && round < modelRounds && cap > 0 ? modelInstances(m, laws, at, mw.goal, mw.w) : undefined;
1310
+ if (!more)
1311
+ return { result, inst: at };
1312
+ at = more;
1313
+ }
1174
1314
  }
1175
1315
  // Instances with each every-key law also at these keys. A law about two keys or more goes at tuples that relate the
1176
1316
  // 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
1317
  // 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
1318
  // 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 => {
1319
+ const withReads = (laws, inst, keys, focus, byMap, fns = []) => ({ ...inst, ...Object.fromEntries(laws.filter(l => l.forall).map(l => {
1180
1320
  const had = inst[l.name] ?? [];
1181
1321
  if (l.keys?.length) {
1182
- const n = l.keys.length + 1, out = new Map();
1322
+ const n = l.keys.length + 1, out = new Map(), sorted = byMap ? keySorted(l, byMap, fns) : undefined;
1183
1323
  for (let i = 0; i + n <= had.length; i += n)
1184
1324
  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);
1325
+ for (const tuple of [...related(keys, focus, n), ...matched(l, keys)])
1326
+ if (!sorted || sorted(tuple))
1327
+ out.set(JSON.stringify(tuple), tuple);
1189
1328
  return [l.name, [...out.values()].flat()];
1190
1329
  }
1191
1330
  const seen = new Set(had.map(e => JSON.stringify(e)));
1192
1331
  return [l.name, [...had, ...keys.filter(e => { const id = JSON.stringify(e); return seen.has(id) ? false : (seen.add(id), true); })]];
1193
1332
  })) });
1333
+ // 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
1334
+ // against the keys the goals read that map at (the key's sort, as the goal holds it: Link[c1·N + s] against
1335
+ // 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
1336
+ // argument is no sort (a function is read at any key). Untrusted: it chooses instances only.
1337
+ function keySorted(l, byMap, fns) {
1338
+ 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))));
1339
+ return tuple => tuple.every((t, i) => !allowed[i] || allowed[i].has(JSON.stringify(t)));
1340
+ }
1341
+ // The terms `body`'s reads (not a function's) bind each of `vars` to, matched against the keys `at` gives their map.
1342
+ function sortTerms(body, vars, fns, at) {
1343
+ const out = vars.map(() => undefined);
1344
+ eachRead(e => {
1345
+ if (fns.includes(e.map) || !vars.some(x => JSON.stringify(e.key).includes(`"name":${JSON.stringify(x)}`)))
1346
+ return;
1347
+ for (const t of at(e.map)) {
1348
+ const b = matchMany(e.key, t, vars);
1349
+ if (b)
1350
+ vars.forEach((x, i) => { if (x in b)
1351
+ (out[i] ??= []).push(b[x]); });
1352
+ }
1353
+ }).inC(body);
1354
+ return out;
1355
+ }
1194
1356
  // 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
1357
  // that makes that key one the goals read (Link[a·N + b] gives (a, b)), as a fact about several keys is matched
1196
1358
  // (withFacts). A key of one bound name alone matches every key, so it binds no tuple here.
1359
+ // 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'
1360
+ // matches together bind them, as a fact's do (withFacts): at a name both bind, each one's value in turn.
1197
1361
  const matched = (l, keys) => {
1198
1362
  const vars = [l.forall, ...(l.keys ?? [])], names = (e) => vars.filter(x => JSON.stringify(e).includes(`"name":${JSON.stringify(x)}`));
1199
1363
  const pats = new Map();
1200
- eachRead(e => { if (names(e.key).length === vars.length)
1364
+ eachRead(e => { const ns = names(e.key); if (ns.length === vars.length || ns.length > 1)
1201
1365
  pats.set(JSON.stringify(e.key), e.key); }).inC(l.holds);
1202
- const out = [];
1366
+ const partial = [];
1203
1367
  for (const p of pats.values())
1204
1368
  for (const key of keys) {
1205
1369
  const b = matchMany(p, key, vars);
1206
- if (b && vars.every(x => x in b))
1207
- out.push(vars.map(x => b[x]));
1370
+ if (b)
1371
+ partial.push(b);
1208
1372
  }
1209
- return out;
1373
+ const whole = (b) => vars.every(x => x in b), out = partial.filter(whole);
1374
+ for (let i = 0; i < partial.length; i++)
1375
+ for (let j = i + 1; j < partial.length; j++) {
1376
+ const a = partial[i], b = partial[j];
1377
+ if (whole(a) || whole(b) || !vars.every(x => x in a || x in b))
1378
+ continue;
1379
+ out.push({ ...b, ...a }, { ...a, ...b });
1380
+ }
1381
+ return out.map(b => vars.map(x => b[x]));
1210
1382
  };
1211
1383
  // The n-tuples of the keys that relate the focus (withReads).
1212
1384
  const related = (keys, focus, n) => {
@@ -1344,8 +1516,8 @@ function instancesFor(m, laws, build, opts = {}) {
1344
1516
  if (m.facts?.length)
1345
1517
  inst = withFacts(m, inst, fnKeys(m, build(inst)));
1346
1518
  if (reads) {
1347
- const keys = mapKeys(build(inst));
1348
- inst = union(withReads(laws, inst, keys, opts.focus ?? []), flagInstances(m, keys, opts.focus), m);
1519
+ const { keys, byMap } = mapReads(build(inst));
1520
+ inst = union(withReads(laws, inst, keys, opts.focus ?? [], byMap, Object.keys(m.fns ?? {})), flagInstances(m, keys, opts.focus), m);
1349
1521
  }
1350
1522
  }
1351
1523
  return inst;
@@ -1554,23 +1726,54 @@ export function proveLaws(m, laws) {
1554
1726
  }
1555
1727
  // 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
1728
  // yet); not a proof of the set, which proveLaws gives. Laws with some key go through proveLaws.
1729
+ // Decisions at the simplex's point (kernel/cdcl.ts's phaseAtPoint, as its model search decides) in the goals of a law set
1730
+ // with a law about several keys, on the proof path (proveLaw, proveThinned): those goals' first rounds are often models
1731
+ // a tuple short (withModels asks again at the model's tuples), and the search deciding by its saved phases wanders before
1732
+ // it finds one (toy consensus's safety law: 108 s and 181k nodes for a model the point finds in 663; research/protocols/
1733
+ // COST.md). Untrusted: the order of the cases only.
1734
+ export const atPoint = { on: false };
1735
+ const pointed = (laws, f) => {
1736
+ if (atPoint.on || !laws.some(l => l.keys?.length))
1737
+ return f();
1738
+ atPoint.on = true;
1739
+ try {
1740
+ return f();
1741
+ }
1742
+ finally {
1743
+ atPoint.on = false;
1744
+ }
1745
+ };
1557
1746
  export function proveLaw(m, laws, i) {
1558
- const law = laws[i];
1559
1747
  if (laws.some(l => someKeys(l.holds).length) || someLaws(laws)) {
1560
1748
  const r = proveLaws(m, laws);
1561
1749
  return r.proven ? { proven: true } : { proven: false, goal: r.failed.goal, stuck: r.failed.stuck, ...(r.failed.witness ? { witness: r.failed.witness } : {}) };
1562
1750
  }
1563
- const pm = plainOf(m), inst = lawInstances(m, laws, i);
1751
+ return pointed(laws, () => proveOne(m, laws, i));
1752
+ }
1753
+ function proveOne(m, laws, i) {
1754
+ const law = laws[i], pm = plainOf(m), inst = lawInstances(m, laws, i);
1564
1755
  const few = triggered(pm, laws, inst, i2 => obligations(m, laws, { [law.name]: i2 }, i), law.forall ? [`${law.forall}#`] : []);
1565
1756
  if (!sameInstances(few, inst) && obligations(m, laws, { [law.name]: few }, i).every(goal => 'tree' in grow(goal)))
1566
1757
  return { proven: true };
1567
- for (const goal of obligations(m, laws, { [law.name]: inst }, i)) {
1758
+ // (a model breaking a law at a tuple of the goal's keys: those added, the law asked again)
1759
+ const { result: a } = withModels(m, laws, inst, i2 => obligations(m, laws, { [law.name]: i2 }, i), growAll, grownModel, grownSettled);
1760
+ return a.out ? { proven: false, goal: a.goal.name, stuck: a.out.stuck, ...(a.out.witness ? { witness: a.out.witness } : {}) } : { proven: true };
1761
+ }
1762
+ function growAll(gs) {
1763
+ const done = {};
1764
+ let n = 0, lv = 0;
1765
+ for (const goal of gs) {
1568
1766
  const out = grow(goal);
1569
1767
  if (!('tree' in out))
1570
- return { proven: false, goal: goal.name, stuck: out.stuck, ...(out.witness ? { witness: out.witness } : {}) };
1768
+ return { done, n, lv, goal, out };
1769
+ done[goal.name] = out.tree;
1770
+ n += out.nodes;
1771
+ lv += countLeaves(out.tree);
1571
1772
  }
1572
- return { proven: true };
1773
+ return { done, n, lv };
1573
1774
  }
1775
+ const grownModel = (x) => (x.out?.stuck === 'sat' && x.out.witness ? { goal: x.goal, w: x.out.witness } : undefined);
1776
+ const grownSettled = (x) => !x.out || x.out.stuck === 'sat';
1574
1777
  // The instances law i's goals are read at (proveLaw's; core/infer.ts's join asks one goal at a time).
1575
1778
  export function lawInstances(m, laws, i) {
1576
1779
  // (a machine with sums: its plain machine's instances, as proveLawsAsGiven's)
@@ -1659,31 +1862,27 @@ export const usualProof = {};
1659
1862
  // A machine with sums has no cyclic twin yet: its certificate is the usual trees, checked with its cover goals.
1660
1863
  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
1864
  function proveThinned(m, laws, instances) {
1865
+ return pointed(laws, () => thinned(m, laws, instances));
1866
+ }
1867
+ function thinned(m, laws, instances) {
1662
1868
  const trees = {}, fulls = { ...instances };
1663
1869
  let nodes = 0, leaves = 0;
1664
1870
  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}#`] : []);
1871
+ const full = instances[law.name];
1872
+ const few = triggered(plainOf(m), laws, full, inst => obligations(m, laws, { ...instances, [law.name]: inst }, i), law.forall ? [`${law.forall}#`] : []);
1873
+ // (thinned instances first, then the full ones; each asked again at the tuples its models ask for)
1666
1874
  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)
1875
+ const { result: a, inst: at } = withModels(m, laws, inst, i2 => obligations(m, laws, { ...instances, [law.name]: i2 }, i), growAll, grownModel, grownSettled);
1876
+ instances[law.name] = at;
1877
+ if (inst === full)
1878
+ fulls[law.name] = at;
1879
+ if (a.out && inst !== full)
1681
1880
  continue;
1682
- if (failed)
1683
- return { proven: false, nodes, leaves, failed, checked: false };
1684
- Object.assign(trees, done);
1685
- nodes += n;
1686
- leaves += lv;
1881
+ if (a.out)
1882
+ return stuckAt(a.goal, a.out, nodes, leaves);
1883
+ Object.assign(trees, a.done);
1884
+ nodes += a.n;
1885
+ leaves += a.lv;
1687
1886
  break;
1688
1887
  }
1689
1888
  }
@@ -1771,8 +1970,11 @@ function proveStepLawsAsGiven(m, laws, stepLaws, base, ready = () => { }) {
1771
1970
  const instances = perStep[stepLaws[0]?.name ?? ''] ?? {};
1772
1971
  const trees = {};
1773
1972
  let nodes = base.nodes, leaves = base.leaves;
1973
+ // (each step law's own time, its share of the usual proof: what its certificate alone may take, stepCertFloor)
1974
+ const ownMs = {};
1774
1975
  for (const sl of stepLaws)
1775
1976
  for (const goal of stepLawObligations(m, laws, perStep[sl.name] ?? instances, sl)) {
1977
+ const g0 = performance.now();
1776
1978
  const full = perStep[sl.name] ?? instances, few = triggered(plain, laws, full, inst => stepLawObligations(m, laws, inst, sl), [sl.forall, ...(sl.keys ?? [])].flatMap(k => (k ? [k] : [])));
1777
1979
  let out = sameInstances(few, full) ? grow(goal) : grow(stepLawObligations(m, laws, few, sl).find(g => g.name === goal.name) ?? goal);
1778
1980
  if ('tree' in out && !sameInstances(few, full))
@@ -1806,6 +2008,7 @@ function proveStepLawsAsGiven(m, laws, stepLaws, base, ready = () => { }) {
1806
2008
  trees[goal.name] = out.tree;
1807
2009
  nodes += out.nodes;
1808
2010
  leaves += countLeaves(out.tree);
2011
+ ownMs[sl.name] = (ownMs[sl.name] ?? 0) + performance.now() - g0;
1809
2012
  }
1810
2013
  // (every step law proven: the laws' certificate, or their check, as proveLaws makes it; its time not the step laws')
1811
2014
  const r0 = performance.now();
@@ -1835,12 +2038,19 @@ function proveStepLawsAsGiven(m, laws, stepLaws, base, ready = () => { }) {
1835
2038
  crossCyclic('step law', m.name, true, undefined, usualMs, translatedOf(all));
1836
2039
  // (where the step laws' proof together isn't made, each step law's alone: one the translation misses leaves the
1837
2040
  // others theirs; and the usual trees, unchecked where the certificate was to be the verdict, are checked)
1838
- const together = certOn() ? certCyclic('step law', m.name, translatedOf(all), undefined, usualMs) : undefined;
2041
+ // (a certificate's translation is worth at most a few times the usual proof, which is an equally checked
2042
+ // certificate: the step laws together within translateMs of their usual time, then each alone within its share,
2043
+ // all of them within translateMs again; past that a step law's certificate is its usual trees)
2044
+ const floor = stepCertFloor(), owned = Object.values(ownMs).reduce((a, b) => a + b, 0);
2045
+ const together = certOn() ? certCyclic('step law', m.name, translatedOf(all), undefined, usualMs, floor) : undefined;
1839
2046
  if (together && !together.checked) {
1840
2047
  if (byCert)
1841
2048
  out.checked = checkStepLaws(m, laws, stepLaws, proof);
2049
+ const end = clock() + translateMs(usualMs, floor);
1842
2050
  for (const x of all) {
1843
- const c = all.length > 1 ? certCyclic('step law', m.name, translatedOf([x]), undefined, usualMs) : together;
2051
+ const share = owned > 0 ? usualMs * (ownMs[x.sl.name] ?? 0) / owned : usualMs / all.length;
2052
+ const c = all.length === 1 ? together : clock() < end ? withDeadline(end, () => certCyclic('step law', m.name, translatedOf([x]), undefined, share, floor))
2053
+ : { checked: false, why: `the step laws' certificates past ${Math.round(translateMs(usualMs, floor))} ms (their usual trees)` };
1844
2054
  if (!c.checked)
1845
2055
  miss(x.sl, c.why);
1846
2056
  }
@@ -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')}` : ''}`;