gdp-wired 0.31.0 → 0.32.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.
Files changed (73) hide show
  1. package/README.md +82 -6
  2. package/dist/core/c/reader.d.ts +86 -0
  3. package/dist/core/c/reader.js +860 -0
  4. package/dist/core/cli.d.ts +66 -0
  5. package/dist/core/cli.js +582 -0
  6. package/dist/core/dsl.d.ts +4 -2
  7. package/dist/core/dsl.js +22 -12
  8. package/dist/core/effect.d.ts +6 -4
  9. package/dist/core/effect.js +48 -10
  10. package/dist/core/ex/harness.exs +177 -0
  11. package/dist/core/ex/json.exs +46 -0
  12. package/dist/core/ex/reader.exs +462 -0
  13. package/dist/core/exists.d.ts +3 -0
  14. package/dist/core/exists.js +3 -1
  15. package/dist/core/extract-c.d.ts +35 -0
  16. package/dist/core/extract-c.js +424 -0
  17. package/dist/core/extract-check.js +27 -6
  18. package/dist/core/extract-ex.d.ts +16 -0
  19. package/dist/core/extract-ex.js +33 -0
  20. package/dist/core/extract-go-check.d.ts +28 -0
  21. package/dist/core/extract-go-check.js +639 -0
  22. package/dist/core/extract-go.d.ts +231 -0
  23. package/dist/core/extract-go.js +1166 -0
  24. package/dist/core/extract-jvm.d.ts +23 -0
  25. package/dist/core/extract-jvm.js +220 -0
  26. package/dist/core/extract-print.js +17 -7
  27. package/dist/core/extract-py.d.ts +15 -0
  28. package/dist/core/extract-py.js +31 -0
  29. package/dist/core/extract-rb.d.ts +17 -0
  30. package/dist/core/extract-rb.js +31 -0
  31. package/dist/core/extract-read.d.ts +20 -0
  32. package/dist/core/extract-read.js +46 -6
  33. package/dist/core/extract-rs.d.ts +12 -0
  34. package/dist/core/extract-rs.js +306 -0
  35. package/dist/core/extract-shapes.d.ts +2 -0
  36. package/dist/core/extract-shapes.js +6 -5
  37. package/dist/core/extract-step.d.ts +806 -0
  38. package/dist/core/extract-step.js +4141 -0
  39. package/dist/core/extract-swift.d.ts +27 -0
  40. package/dist/core/extract-swift.js +484 -0
  41. package/dist/core/extract-xstate.d.ts +10 -3
  42. package/dist/core/extract-xstate.js +50 -4
  43. package/dist/core/extract.d.ts +22 -3
  44. package/dist/core/extract.js +107 -18
  45. package/dist/core/go/go.mod +3 -0
  46. package/dist/core/go/reader.go +901 -0
  47. package/dist/core/infer.js +1770 -52
  48. package/dist/core/jvm/Harness.java +361 -0
  49. package/dist/core/jvm/JavaReader.java +825 -0
  50. package/dist/core/jvm/Jvm.java +332 -0
  51. package/dist/core/jvm/KtReader.java +960 -0
  52. package/dist/core/jvm/Rt.java +10 -0
  53. package/dist/core/laws.d.ts +66 -0
  54. package/dist/core/laws.js +522 -0
  55. package/dist/core/py/harness.py +328 -0
  56. package/dist/core/py/reader.py +447 -0
  57. package/dist/core/rb/harness.rb +233 -0
  58. package/dist/core/rb/reader.rb +375 -0
  59. package/dist/core/rs/Cargo.lock +108 -0
  60. package/dist/core/rs/Cargo.toml +14 -0
  61. package/dist/core/rs/src/main.rs +681 -0
  62. package/dist/core/swift/Harness.swift +124 -0
  63. package/dist/core/swift/Main.swift +34 -0
  64. package/dist/core/swift/Package.swift +13 -0
  65. package/dist/core/swift/Sources/gdp-swiftreader/main.swift +1341 -0
  66. package/dist/kernel/cdcl.js +43 -18
  67. package/dist/kernel/epr.d.ts +35 -0
  68. package/dist/kernel/epr.js +1676 -0
  69. package/dist/kernel/prove.d.ts +44 -0
  70. package/dist/kernel/prove.js +668 -54
  71. package/dist/lean-kernel/emit.d.ts +1 -0
  72. package/dist/lean-kernel/emit.js +21 -4
  73. package/package.json +53 -6
@@ -14,6 +14,7 @@ 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";
15
15
  import { proveSome, someLaws } from "../core/exists.js";
16
16
  import { growCdcl } from "./cdcl.js";
17
+ import { decide, patternsOf } from "./epr.js";
17
18
  import { assumed, atomOf, boundOf, canon, canonFlip, columnTerm, decided, factorsOf, isCell, isMonomial, stepZone, check, checkLaws, checkStepLaws, historyMachine, plainOf, substC, substE, leafConstraints, leafConstraintsReusing, reusing, linear, livenessHelpful, livenessParts, strongly, loopMachine, obligations, plainKey, progressObligations, stepLawObligations, trueC, truth, unreachable, witnessesOf, withProducts } from "./kernel.js";
18
19
  // The atoms the path leaves open, in evaluation order: deciding any of them makes progress.
19
20
  function openE(e, path, out) {
@@ -97,15 +98,22 @@ function openH(c, path, out, positive = true) {
97
98
  export const pairedKeys = { skip: false };
98
99
  // (each cell's map and key, and each pair's difference both ways, made once: the pairs are quadratic in the names, and
99
100
  // the same forms at every node keep what is remembered per form)
101
+ // (by the first cell, then the second: no key text made per lookup, the search's nodes ask for every pair again)
100
102
  const cellKeys = new Map(), cellPairs = new Map();
103
+ let cellPairsN = 0;
101
104
  export const cellPair = (a, b) => {
102
- const pk = `${a}\u0000${b}`;
103
- let pair = cellPairs.get(pk);
105
+ let row = cellPairs.get(a);
106
+ if (!row)
107
+ cellPairs.set(a, (row = new Map()));
108
+ let pair = row.get(b);
104
109
  if (!pair) {
105
- if (cellPairs.size > 200_000)
110
+ if (++cellPairsN > 200_000) {
106
111
  cellPairs.clear();
112
+ cellPairsN = 1;
113
+ cellPairs.set(a, (row = new Map()));
114
+ }
107
115
  const d = sub(cellKey(a).key, cellKey(b).key);
108
- cellPairs.set(pk, (pair = { d, neg: scale(d, -1) }));
116
+ row.set(b, (pair = { d, neg: scale(d, -1) }));
109
117
  }
110
118
  return pair;
111
119
  };
@@ -282,7 +290,22 @@ finally {
282
290
  workCap = outer;
283
291
  } };
284
292
  // Past a budget's end on the clock, or past the work a goal's own budget allows.
285
- export const late = (until) => clock() > until || (workCap !== Infinity && fullWork() > workCap);
293
+ // A wall-clock end beside the clock's (withWall: the search's own end, core/dsl.ts): work the counted clock doesn't count
294
+ // (the EPR path's propositional search, a node's propagation, building a large goal's rows) stops there too, and past it
295
+ // every goal is left unknown, whatever its own budget. Untrusted: it only stops a search.
296
+ let wallEnd = Infinity;
297
+ export const pastWall = () => wallEnd !== Infinity && performance.now() > wallEnd;
298
+ export function withWall(end, f) {
299
+ const outer = wallEnd;
300
+ wallEnd = Math.min(outer, end);
301
+ try {
302
+ return f();
303
+ }
304
+ finally {
305
+ wallEnd = outer;
306
+ }
307
+ }
308
+ export const late = (until) => clock() > until || (workCap !== Infinity && fullWork() > workCap) || pastWall();
286
309
  // A budget's end, within the deadline (a translation's own bound, core/cyclic.ts's, kept by the export's GDP_CERT_MS).
287
310
  export const withinDeadline = (until) => Math.min(until, deadline);
288
311
  export function withDeadline(until, f) {
@@ -298,6 +321,8 @@ export function withDeadline(until, f) {
298
321
  // `units: false`: the goal's own order, no units first (a caller after a model, not a proof: a run guided by the
299
322
  // prover's witnesses, say, whose models units would steer).
300
323
  export function grow(goal, path = new Map(), budget) {
324
+ if (pastWall())
325
+ return { stuck: 'unknown', path, why: outOfBudget(goal, 'time', path.size) };
301
326
  if (!budget) {
302
327
  const ms = Math.max(20_000, 1_000 * goal.hyps.length);
303
328
  if (!rate)
@@ -386,12 +411,71 @@ function growKept0(goal, path, budget) {
386
411
  // The share of a root goal's budget the CDCL search gets (GDP_CDCL_SHARE; 0 turns it off), and the quick search's nodes
387
412
  // before it (GDP_QUICK_CAP; 64 where the CDCL search isn't tried, as before it): research/step's comparisons.
388
413
  const cdclShare = Number(env.GDP_CDCL_SHARE ?? 0.75), quickCap = Number(env.GDP_QUICK_CAP ?? 16);
414
+ // The EPR path (kernel/epr.ts): a root goal of a rule with a composed key, its hypotheses EPR-shaped (keys tuples of
415
+ // their parts, cells few-valued, no counter, sum or product), decided first by its abstraction. A model of the goal (the
416
+ // abstraction's, judged on every hypothesis by the interpreter) is the goal's model; a refutation's core (a few
417
+ // hypotheses) is proven by the usual search, within half the goal's budget, and widened to the whole goal (`widen`), whose
418
+ // tree the kernel checks as any; anything else, the usual search. Untrusted. GDP_EPR=0 turns it off.
419
+ const eprOn = env.GDP_EPR !== '0';
420
+ export const eprScope = {};
421
+ const withPatterns = (m, laws, f) => {
422
+ if (!eprOn || eprScope.patterns)
423
+ return f();
424
+ const p = patternsOf(plainOf(m), laws);
425
+ if (!Object.values(p).some(c => c.length > 1))
426
+ return f();
427
+ eprScope.patterns = p;
428
+ try {
429
+ return f();
430
+ }
431
+ finally {
432
+ eprScope.patterns = undefined;
433
+ }
434
+ };
435
+ // (`whole: false`: the core's tree alone, not widened to the goal, with the core (`part`); decideLaw's, whose caller's
436
+ // verdict rests on its own final proof: a refutation of some of a goal's hypotheses refutes the goal)
437
+ // (`refuted`: the last decision refuted the goal and its core's proof didn't finish: a model from fewer instances, asked
438
+ // before, is then no answer, as the abstraction refutes it at these)
439
+ const eprLast = { refuted: false };
440
+ function eprFirst(goal, budget, whole = true, late = pastWall) {
441
+ eprLast.refuted = false;
442
+ const d = decide(goal, eprScope.patterns, { exact: true, late });
443
+ if ('unknown' in d)
444
+ return undefined;
445
+ if (d.sat)
446
+ return { stuck: 'sat', witness: d.witness, diagram: d.diagram, path: new Map(), why: 'a model' };
447
+ const last = goal.hyps.length - 1, core = d.core.includes(last) ? d.core : [...d.core, last], part = { name: goal.name, hyps: core.map(i => goal.hyps[i]) };
448
+ const now = clock(), end = withinDeadline(budget.until ?? Infinity), w = fullWork();
449
+ eprScope.busy = true;
450
+ try {
451
+ const out = withWork(workCap === Infinity ? Infinity : w + 0.5 * (workCap - w), () => grow(part, new Map(), { nodes: 0, until: end === Infinity ? end : now + 0.5 * (end - now) }));
452
+ if (!('tree' in out)) {
453
+ eprLast.refuted = true;
454
+ return undefined;
455
+ }
456
+ if (!whole)
457
+ return { ...out, part, core };
458
+ const tree = widen(part, goal, out.tree);
459
+ return tree ? { tree, nodes: out.nodes } : undefined;
460
+ }
461
+ finally {
462
+ eprScope.busy = false;
463
+ }
464
+ }
389
465
  function growRoot(goal, path, budget) {
466
+ if (eprScope.patterns && !eprScope.busy && !path.size && !budget.nodes) {
467
+ const out = eprFirst(goal, budget);
468
+ if (out)
469
+ return out;
470
+ }
390
471
  // Past a few cases, CDCL over the atoms (kernel/cdcl.ts), with most of the budget: a linear goal's refutation there
391
472
  // is a resolution of short clauses, which the tree search would find again in every case that reaches one. Unknown
392
473
  // there, the plain search, the cuts and the plain search again have the rest. Not for a law over k steps in a row
393
474
  // (kernel.ts names its goals `@k steps`): the cuts make its tree a chain of one step's refutations, which the CDCL
394
475
  // search's tree, unfolded, repeats (research/step: four times the Lean text of examples/steps.ts). Nor for products.
476
+ // (past the wall, not even the root's rows: a large goal's take a second)
477
+ if (pastWall())
478
+ return { stuck: 'unknown', path, why: outOfBudget(goal, 'time', path.size) };
395
479
  const root = path.size === 0 && budget.nodes === 0 ? leafConstraints(goal, path) : undefined;
396
480
  const cdcl = !!root && cdclShare > 0 && !cellProducts.on && Number(/@(\d+) steps/.exec(goal.name)?.[1] ?? 1) <= 1 && !root.some(r => Object.keys(r.lin).some(isMonomial));
397
481
  // At the root: plainly first; where the cases multiply past a budget, through cuts. The plain budget halves with each
@@ -806,6 +890,8 @@ function lift(goal, tree, from, to) {
806
890
  // read as the term's linear form at the whole goal's path; a split the whole's path already decides is followed, not
807
891
  // made again.
808
892
  export function widen(part, whole, tree, opaque = {}, pp = new Map(), wp = pp) {
893
+ if (pastWall())
894
+ return undefined;
809
895
  const names = Object.keys(opaque);
810
896
  const rename = (lin) => {
811
897
  if (!names.length)
@@ -839,7 +925,10 @@ export function widen(part, whole, tree, opaque = {}, pp = new Map(), wp = pp) {
839
925
  const no = yes && widen(part, whole, tree.no, opaque, new Map(pp).set(id, { lin: tree.split, holds: false }), new Map(wp).set(wid, { lin: wl, holds: false }));
840
926
  return yes && no ? { split: wl, yes, no } : undefined;
841
927
  }
842
- const rp = rowsAt(part, pp), rw = rowsAt(whole, wp), at = new Map();
928
+ const rp = rowsAt(part, pp);
929
+ if (pastWall())
930
+ return undefined;
931
+ const rw = rowsAt(whole, wp), at = new Map();
843
932
  rw.forEach((r, i) => { const key = canon(r.lin); if (!at.has(key))
844
933
  at.set(key, i); });
845
934
  const map = (i) => { if (i >= rp.length)
@@ -995,6 +1084,8 @@ function withCuts(goal, path, budget) {
995
1084
  const chain = [];
996
1085
  let at = new Map(path);
997
1086
  for (const { n, e } of columns) {
1087
+ if (pastWall())
1088
+ return undefined;
998
1089
  if (e.op !== 'if')
999
1090
  continue;
1000
1091
  const a = linear(e.then, at), b = linear(e.else, at), focus = topAtoms(e.c, at);
@@ -1034,7 +1125,7 @@ function topAtoms(c, path) {
1034
1125
  }
1035
1126
  // A refutation that splits only on these atoms (a cut's failing side), within a small budget.
1036
1127
  function growFocused(goal, path, focus, budget, near = focus) {
1037
- if (++budget.nodes > 64)
1128
+ if (++budget.nodes > 64 || pastWall())
1038
1129
  return { stuck: 'unknown', path };
1039
1130
  const verdict = solveNear(leafConstraints(goal, path), [...near, ...[...path.values()].slice(-1).map(a => a.lin)]);
1040
1131
  if (verdict.kind === 'refuted')
@@ -1178,10 +1269,24 @@ function mapReads(goals) {
1178
1269
  // where the names have these (a name left out is 0, as a model leaves it).
1179
1270
  export const keyValue = (cell, w) => {
1180
1271
  const inner = cell.slice(cell.indexOf('[') + 1, -1);
1181
- if (inner.includes('['))
1182
- return undefined;
1272
+ // (its parts split at the commas outside brackets: a part may be a cell itself, Pending[idn[n:1]:64,n:1], valued as the
1273
+ // model values it)
1274
+ const parts = [];
1275
+ let depth = 0, from = 0;
1276
+ for (let i = 0; i < inner.length; i++) {
1277
+ const ch = inner[i];
1278
+ if (ch === '[')
1279
+ depth++;
1280
+ else if (ch === ']')
1281
+ depth--;
1282
+ else if (ch === ',' && depth === 0) {
1283
+ parts.push(inner.slice(from, i));
1284
+ from = i + 1;
1285
+ }
1286
+ }
1287
+ parts.push(inner.slice(from));
1183
1288
  let value = 0;
1184
- for (const part of inner.split(',').filter(Boolean)) {
1289
+ for (const part of parts.filter(Boolean)) {
1185
1290
  const at = part.lastIndexOf(':'), name = part.slice(0, at), coef = Number(part.slice(at + 1));
1186
1291
  if (name === '1')
1187
1292
  value += coef;
@@ -1205,7 +1310,8 @@ export function modelInstances(m, laws, inst, goal, w, most = 64) {
1205
1310
  const keyed = laws.filter(l => l.forall);
1206
1311
  if (!keyed.length && !qs.length)
1207
1312
  return undefined;
1208
- const fns = Object.keys(pm.fns ?? {}), mm = { ...pm, fns: undefined, maps: { ...(pm.maps ?? {}), ...Object.fromEntries(fns.map(f => [f, 0])) } };
1313
+ // (the maps a request carries read as maps too: a quantified flag over one, wo's ∀k. Q has k → Votes[src, k])
1314
+ const fns = Object.keys(pm.fns ?? {}), mm = { ...pm, fns: undefined, maps: { ...(pm.maps ?? {}), ...Object.fromEntries([...fns, ...(pm.inputMaps ?? [])].map(f => [f, 0])) } };
1209
1315
  const maps = Object.fromEntries(Object.keys(mm.maps).map(mp => [mp, new Map()]));
1210
1316
  for (const [cell, value] of Object.entries(w)) {
1211
1317
  const br = cell.indexOf('[');
@@ -1215,7 +1321,7 @@ export function modelInstances(m, laws, inst, goal, w, most = 64) {
1215
1321
  if (key !== undefined)
1216
1322
  maps[cell.slice(0, br)].set(key, value);
1217
1323
  }
1218
- const st = { scalars: {}, maps }, read = (at) => new Proxy({ ...w, ...at }, { get: (t, p) => t[p] ?? 0 });
1324
+ const st = { scalars: {}, maps }, read = (at) => new Proxy(at, { get: (t, p) => (p in t ? t[p] : w[p] ?? 0), has: (t, p) => p in t || p in w });
1219
1325
  const ev = (f) => { try {
1220
1326
  return f();
1221
1327
  }
@@ -1239,19 +1345,36 @@ export function modelInstances(m, laws, inst, goal, w, most = 64) {
1239
1345
  }
1240
1346
  if (!all.size)
1241
1347
  return undefined;
1242
- const sortsOf = (body, names) => sortTerms(body, names, fns, () => keys).map(ts => {
1348
+ // (each sort's witnesses first: an ∃ law's ghost, a quantified flag's witness, the terms a model most often breaks a
1349
+ // law at and no read's matching orders well)
1350
+ const witnessFirst = (p) => {
1351
+ const isW = (e) => /"name":"(some\$|w\?)/.test(JSON.stringify(e));
1352
+ return new Map([...[...p].filter(([, e]) => isW(e)), ...[...p].filter(([, e]) => !isW(e))]);
1353
+ };
1354
+ // (`atoms`: each sort over the goal's own names alone, its skolems, the request's inputs, witnesses and ghosts, the
1355
+ // elements an EPR model names: a composed term in a part's place is an instance at a key of the wrong sort)
1356
+ // (a key no read binds is a value, an epoch say, over the naturals: 0, their least, is one of its terms too, as Ivy's
1357
+ // ordered sorts have their zero; a law before the start, nothing above 0, is assumed there)
1358
+ const zero = { op: 'const', value: 0 };
1359
+ const sortsOf = (body, names, atoms) => sortTerms(body, names, fns, () => keys).map(ts => {
1243
1360
  const p = new Map();
1244
1361
  for (const e of ts ?? []) {
1245
1362
  const v2 = valueOf(e);
1246
- if (v2 !== undefined && !p.has(v2))
1363
+ if (v2 !== undefined && !p.has(v2) && (!atoms || e.op === 'var'))
1247
1364
  p.set(v2, e);
1248
1365
  }
1249
- return p.size ? p : all;
1366
+ const q = p.size ? p : atoms ? new Map([...all].filter(([, e]) => e.op === 'var')) : all, r = witnessFirst(q.size ? q : all);
1367
+ return ts || r.has(0) ? r : r.set(0, zero);
1250
1368
  });
1251
1369
  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);
1370
+ // (the 20,000 evaluations shared: each law and flag at most an even share of what is left, so the laws about five keys
1371
+ // first don't leave none to those after: sharded KV's "a key in transfer has no owner", broken at the goal's own keys)
1372
+ let added = 0, evals = 0, left = 0;
1373
+ const each = (id, names, body, atoms) => {
1374
+ if (pastWall())
1375
+ return;
1376
+ const until = evals + Math.max(256, Math.floor((20_000 - evals) / Math.max(1, left--)));
1377
+ const have = new Set(), had = out[id] ?? [], n = names.length, sorts = sortsOf(body, names, atoms);
1255
1378
  // (a law at one key assumed at a term of every value its sort takes already: nothing to add)
1256
1379
  if (n === 1) {
1257
1380
  const covered = new Set(had.map(valueOf));
@@ -1261,7 +1384,7 @@ export function modelInstances(m, laws, inst, goal, w, most = 64) {
1261
1384
  for (let t = 0; t + n <= had.length; t += n)
1262
1385
  have.add(JSON.stringify(had.slice(t, t + n)));
1263
1386
  const go = (i, at, terms) => {
1264
- if (added >= most || evals > 20_000)
1387
+ if (added >= most || evals > until || (evals % 512 === 0 && pastWall()))
1265
1388
  return;
1266
1389
  if (i === n) {
1267
1390
  evals++;
@@ -1280,10 +1403,17 @@ export function modelInstances(m, laws, inst, goal, w, most = 64) {
1280
1403
  };
1281
1404
  go(0, {}, []);
1282
1405
  };
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);
1406
+ // the goal's own names first; every key it reads where they show nothing
1407
+ for (const atoms of [true, false]) {
1408
+ if (atoms === false && added)
1409
+ break;
1410
+ evals = 0;
1411
+ left = keyed.length + qs.length;
1412
+ for (const l of keyed)
1413
+ each(l.name, [l.forall, ...(l.keys ?? [])], l.holds, atoms);
1414
+ for (const [f, q] of qs)
1415
+ each(`?${f}`, boundOf(q), q.c, atoms);
1416
+ }
1287
1417
  return added ? out : undefined;
1288
1418
  }
1289
1419
  // A goal (or a law's goals) asked at some instances, and again at those its model asks for (modelInstances), up to
@@ -1296,6 +1426,9 @@ export const modelShare = 3;
1296
1426
  const costNow = () => (rate ? clock() : fullWork() / groundRate);
1297
1427
  const within = (ms, f) => (rate ? withDeadline(clock() + ms, f) : withWork(fullWork() + groundRate * ms, f));
1298
1428
  export function withModels(m, laws, inst, goalOf, ask, modelOf, settled) {
1429
+ return withPatterns(m, laws, () => modelsLoop(m, laws, inst, goalOf, ask, modelOf, settled));
1430
+ }
1431
+ function modelsLoop(m, laws, inst, goalOf, ask, modelOf, settled) {
1299
1432
  let at = inst, first, cap = 0;
1300
1433
  for (let round = 0;; round++) {
1301
1434
  const c0 = costNow(), result = round ? within(Math.max(0, cap), () => ask(goalOf(at))) : ask(goalOf(at));
@@ -1305,6 +1438,8 @@ export function withModels(m, laws, inst, goalOf, ask, modelOf, settled) {
1305
1438
  cap = Math.max(1_000, modelShare * (costNow() - c0));
1306
1439
  if (round && !settled(result))
1307
1440
  return first;
1441
+ if (pastWall())
1442
+ return first ?? { result, inst: at };
1308
1443
  first ??= { result, inst: at };
1309
1444
  const mw = modelOf(result), more = mw && round < modelRounds && cap > 0 ? modelInstances(m, laws, at, mw.goal, mw.w) : undefined;
1310
1445
  if (!more)
@@ -1316,27 +1451,36 @@ export function withModels(m, laws, inst, goalOf, ask, modelOf, settled) {
1316
1451
  // 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
1317
1452
  // 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
1318
1453
  // at most one place a key that reads no focus.
1319
- const withReads = (laws, inst, keys, focus, byMap, fns = []) => ({ ...inst, ...Object.fromEntries(laws.filter(l => l.forall).map(l => {
1320
- const had = inst[l.name] ?? [];
1321
- if (l.keys?.length) {
1322
- const n = l.keys.length + 1, out = new Map(), sorted = byMap ? keySorted(l, byMap, fns) : undefined;
1323
- for (let i = 0; i + n <= had.length; i += n)
1324
- out.set(JSON.stringify(had.slice(i, i + n)), had.slice(i, i + n));
1325
- for (const tuple of [...related(keys, focus, n), ...matched(l, keys)])
1326
- if (!sorted || sorted(tuple))
1327
- out.set(JSON.stringify(tuple), tuple);
1328
- return [l.name, [...out.values()].flat()];
1329
- }
1330
- const seen = new Set(had.map(e => JSON.stringify(e)));
1331
- return [l.name, [...had, ...keys.filter(e => { const id = JSON.stringify(e); return seen.has(id) ? false : (seen.add(id), true); })]];
1332
- })) });
1454
+ // (a law about several keys at most relatedMost tuples each way, and with many such laws a share of relatedBudget: wo's
1455
+ // caller goal with 81 of them, 950 tuples each, held 34,881 hypotheses; the model's tuples add the rest)
1456
+ const withReads = (laws, inst, keys, focus, byMap, fns = []) => {
1457
+ const most = Math.min(relatedMost, Math.max(64, Math.floor(relatedBudget / Math.max(1, laws.filter(l => l.forall && l.keys?.length).length))));
1458
+ return { ...inst, ...Object.fromEntries(laws.filter(l => l.forall).map(l => {
1459
+ const had = inst[l.name] ?? [];
1460
+ if (l.keys?.length) {
1461
+ const n = l.keys.length + 1, out = new Map(), sorted = byMap ? keySorted(l, byMap, fns) : undefined;
1462
+ for (let i = 0; i + n <= had.length; i += n)
1463
+ out.set(JSON.stringify(had.slice(i, i + n)), had.slice(i, i + n));
1464
+ for (const tuple of [...related(keys, focus, n, sorted, most), ...matched(l, keys, most)])
1465
+ if (!sorted || sorted(tuple))
1466
+ out.set(JSON.stringify(tuple), tuple);
1467
+ return [l.name, [...out.values()].flat()];
1468
+ }
1469
+ const seen = new Set(had.map(e => JSON.stringify(e)));
1470
+ return [l.name, [...had, ...keys.filter(e => { const id = JSON.stringify(e); return seen.has(id) ? false : (seen.add(id), true); })]];
1471
+ })) };
1472
+ };
1333
1473
  // 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
1474
  // against the keys the goals read that map at (the key's sort, as the goal holds it: Link[c1·N + s] against
1335
1475
  // 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
1476
  // argument is no sort (a function is read at any key). Untrusted: it chooses instances only.
1477
+ // (per place too: `at(i, e)`, whether e is of the i-th key's sort, each key's text read once)
1337
1478
  function keySorted(l, byMap, fns) {
1338
1479
  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)));
1480
+ const text = new WeakMap(), id = (e) => { let t = text.get(e); if (t === undefined)
1481
+ text.set(e, (t = JSON.stringify(e))); return t; };
1482
+ const at = (i, e) => !allowed[i] || allowed[i].has(id(e));
1483
+ return Object.assign((tuple) => tuple.every((t, i) => at(i, t)), { at });
1340
1484
  }
1341
1485
  // The terms `body`'s reads (not a function's) bind each of `vars` to, matched against the keys `at` gives their map.
1342
1486
  function sortTerms(body, vars, fns, at) {
@@ -1358,7 +1502,10 @@ function sortTerms(body, vars, fns, at) {
1358
1502
  // (withFacts). A key of one bound name alone matches every key, so it binds no tuple here.
1359
1503
  // 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
1504
  // matches together bind them, as a fact's do (withFacts): at a name both bind, each one's value in turn.
1361
- const matched = (l, keys) => {
1505
+ // (at most relatedMost tuples a law, from each way: where a law about many keys has more, sharded KV's five keys at
1506
+ // 24,608 tuples each, 112,587 hypotheses before any search, the model's tuples, modelInstances, add those a proof misses)
1507
+ export const relatedMost = 512, relatedBudget = 8_192;
1508
+ const matched = (l, keys, most = relatedMost) => {
1362
1509
  const vars = [l.forall, ...(l.keys ?? [])], names = (e) => vars.filter(x => JSON.stringify(e).includes(`"name":${JSON.stringify(x)}`));
1363
1510
  const pats = new Map();
1364
1511
  eachRead(e => { const ns = names(e.key); if (ns.length === vars.length || ns.length > 1)
@@ -1370,30 +1517,40 @@ const matched = (l, keys) => {
1370
1517
  if (b)
1371
1518
  partial.push(b);
1372
1519
  }
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++) {
1520
+ const whole = (b) => vars.every(x => x in b), isWhole = partial.map(whole), out = partial.filter((_, i) => isWhole[i]);
1521
+ // (two partial matches together: at most `most` of them, as related's)
1522
+ for (let i = 0; i < partial.length && out.length < most; i++) {
1523
+ if (isWhole[i])
1524
+ continue;
1525
+ for (let j = i + 1; j < partial.length && out.length < most; j++) {
1376
1526
  const a = partial[i], b = partial[j];
1377
- if (whole(a) || whole(b) || !vars.every(x => x in a || x in b))
1527
+ if (isWhole[j] || !vars.every(x => x in a || x in b))
1378
1528
  continue;
1379
1529
  out.push({ ...b, ...a }, { ...a, ...b });
1380
1530
  }
1531
+ }
1381
1532
  return out.map(b => vars.map(x => b[x]));
1382
1533
  };
1383
- // The n-tuples of the keys that relate the focus (withReads).
1384
- const related = (keys, focus, n) => {
1534
+ // The n-tuples of the keys that relate the focus (withReads): those `keep` keeps, the first `most` of them in this order
1535
+ // (each place's own focus key before the rest).
1536
+ // (`keep` at each place, `keep.at`, as the tuple is made: a sort no key of keeps no tuple, and none is made of it)
1537
+ const related = (keys, focus, n, keep, most = Infinity) => {
1385
1538
  const reads = (e, x) => x !== undefined && JSON.stringify(e).includes(`"name":${JSON.stringify(x)}`);
1386
1539
  const own = (i) => { const f = focus[i] ?? focus[0]; return keys.filter(e => reads(e, f) && focus.every(g => g === f || !reads(e, g))); };
1387
- const R = keys.filter(e => !focus.some(f => reads(e, f))), out = [];
1540
+ const R0 = keys.filter(e => !focus.some(f => reads(e, f))), out = [];
1541
+ const owns = Array.from({ length: n }, (_, i) => own(i).filter(e => !keep || keep.at(i, e))), R = Array.from({ length: n }, (_, i) => R0.filter(e => !keep || keep.at(i, e)));
1542
+ let made = 0;
1388
1543
  const go = (i, tuple, rest) => {
1544
+ if (out.length >= most || (++made % 4096 === 0 && pastWall()))
1545
+ return;
1389
1546
  if (i === n) {
1390
1547
  out.push(tuple);
1391
1548
  return;
1392
1549
  }
1393
- for (const e of own(i))
1550
+ for (const e of owns[i])
1394
1551
  go(i + 1, [...tuple, e], rest);
1395
1552
  if (!rest)
1396
- for (const e of R)
1553
+ for (const e of R[i])
1397
1554
  go(i + 1, [...tuple, e], true);
1398
1555
  };
1399
1556
  go(0, [], false);
@@ -1455,8 +1612,36 @@ function matchMany(pattern, term, xs) {
1455
1612
  const pe = Object.entries(p), te = t;
1456
1613
  return pe.every(([k, val]) => k === 'op' || (typeof val === 'object' && val !== null ? (Array.isArray(val) ? Array.isArray(te[k]) && te[k].length === val.length && val.every((y, i) => go(y, te[k][i])) : go(val, te[k])) : val === te[k]));
1457
1614
  };
1458
- return go(pattern, term) ? bound : undefined;
1615
+ if (go(pattern, term))
1616
+ return bound;
1617
+ // (else as radix sums: a key written 64·(64·z + x) + w is 4096·n + 64·k + v's sort, each part bound to the part of
1618
+ // its coefficient)
1619
+ const p = radix(pattern), t = p && radix(term);
1620
+ if (!p || !t || p.length !== t.length || p.some(([, c], i) => c !== t[i][1]))
1621
+ return undefined;
1622
+ const out = {};
1623
+ for (const [i, [e]] of p.entries()) {
1624
+ const u = t[i][0];
1625
+ if (e.op === 'var' && xs.includes(e.name)) {
1626
+ if (e.name in out && JSON.stringify(out[e.name]) !== JSON.stringify(u))
1627
+ return undefined;
1628
+ out[e.name] = u;
1629
+ }
1630
+ else if (JSON.stringify(e) !== JSON.stringify(u))
1631
+ return undefined;
1632
+ }
1633
+ return out;
1459
1634
  }
1635
+ // A key as a radix sum Σ c·part, its parts by coefficient, highest first (distinct coefficients, no constant), else
1636
+ // undefined. A part is a name or a read of one (a function's).
1637
+ const radix = (e) => {
1638
+ const out = [];
1639
+ const go = (x, k) => x.op === 'add' ? go(x.a, k) && go(x.b, k) : x.op === 'mul' ? go(x.a, k * x.k) : x.op === 'var' || x.op === 'get' ? (out.push([x, k]), true) : false;
1640
+ if (!go(e, 1) || out.length < 2)
1641
+ return undefined;
1642
+ out.sort((a, b) => b[1] - a[1]);
1643
+ return out.every(([, c], i) => i === 0 || c !== out[i - 1][1]) ? out : undefined;
1644
+ };
1460
1645
  // The value of x that makes pattern the term, if one does (structurally).
1461
1646
  function match(pattern, term, x) {
1462
1647
  let bound;
@@ -1512,7 +1697,7 @@ function instancesFor(m, laws, build, opts = {}) {
1512
1697
  const seed = opts.seed && [...new Map(opts.seed.map(e => [JSON.stringify(e), e])).values()];
1513
1698
  let inst = opts.start ?? (seed ? { ...Object.fromEntries(laws.filter(l => l.forall).map(l => [l.name, l.keys?.length ? [] : seed])), ...flagInstances(m, seed, opts.focus) } : {});
1514
1699
  const reads = opts.reads ?? (!opts.seed || shifts(m) || laws.some(l => l.keys?.length) || pairFlags(m));
1515
- for (let round = 0; round < 2; round++) {
1700
+ for (let round = 0; round < 2 && !pastWall(); round++) {
1516
1701
  if (m.facts?.length)
1517
1702
  inst = withFacts(m, inst, fnKeys(m, build(inst)));
1518
1703
  if (reads) {
@@ -1559,7 +1744,7 @@ function triggered(m, laws, inst, build, focus = []) {
1559
1744
  const tuplesOf = (n, ks) => { const a = bodies.get(n).keys.length; return Array.from({ length: Math.floor(ks.length / a) }, (_, t) => ks.slice(t * a, (t + 1) * a)); };
1560
1745
  const kept = (tuple) => tuple.some(e => e.op === 'var' && focus.includes(e.name));
1561
1746
  const out = Object.fromEntries(Object.entries(inst).map(([n, ks]) => [n, bodies.has(n) ? tuplesOf(n, ks).filter(kept).flat() : ks]));
1562
- for (let round = 0; round < 8; round++) {
1747
+ for (let round = 0; round < 8 && !pastWall(); round++) {
1563
1748
  const reads = new Set();
1564
1749
  const { inC } = eachRead(e => { reads.add(`${e.map}|${JSON.stringify(e.key)}`); });
1565
1750
  for (const g of build(out))
@@ -1743,12 +1928,259 @@ const pointed = (laws, f) => {
1743
1928
  atPoint.on = false;
1744
1929
  }
1745
1930
  };
1931
+ // (a probe's hook: each decision with its machine, set, index and ms)
1932
+ export const decideLawHook = {};
1933
+ export function decideLaw(m, laws, i, rounds = modelRounds) {
1934
+ if (!decideLawHook.on)
1935
+ return decideLaw0(m, laws, i, rounds);
1936
+ const t0 = performance.now(), out = decideLaw0(m, laws, i, rounds);
1937
+ decideLawHook.on(m, laws, i, out, performance.now() - t0);
1938
+ return out;
1939
+ }
1940
+ // (why decideLaw last answered nothing: `refuted`, the abstraction refuted a goal whose core's proof didn't finish, a
1941
+ // goal the CDCL search after it would find no quicker)
1942
+ export const decideNote = { refuted: false };
1943
+ function decideLaw0(m, laws, i, rounds) {
1944
+ decideNote.refuted = false;
1945
+ if (!fastShape(m, laws))
1946
+ return undefined;
1947
+ return withPatterns(m, laws, () => {
1948
+ if (!eprScope.patterns)
1949
+ return undefined;
1950
+ const out = settled(m, laws, i, rounds, false);
1951
+ // (a proof's support: the laws its goals' proofs read)
1952
+ return !out ? undefined : 'proofs' in out ? { proven: true, uses: [...new Set(Object.values(out.proofs).flatMap(p => [...p.uses.keys()]))] } : out.stuck === 'sat' ? { proven: false, goal: out.goal, stuck: 'sat', witness: out.witness, ...(out.diagram ? { diagram: out.diagram } : {}) } : undefined;
1953
+ });
1954
+ }
1955
+ // (GDP_MEMO_CAP: how many machines' decisions are kept, 4 by default; the hits and misses counted for the engine's trace)
1956
+ const memoCap = Number(env.GDP_MEMO_CAP ?? 4);
1957
+ export const memoHits = { n: 0, miss: 0, setKey: '', setJson: '' };
1958
+ export const machineKey = (m) => { const s = JSON.stringify(m); let h = 0; for (let i = 0; i < s.length; i++)
1959
+ h = (h * 31 + s.charCodeAt(i)) | 0; return `${s.length}:${h}`; };
1960
+ const memos = new Map(), machineText = new WeakMap(), lawText = new WeakMap();
1961
+ // (texts up to a renaming of fresh names, x$12: a rule's machine and kinds' laws are made again with
1962
+ // fresh binders, so the same machine had another text each time and no decision was found again; GDP_MEMO_ALPHA=0 off)
1963
+ const alpha = env.GDP_MEMO_ALPHA !== '0';
1964
+ const alphaText = (s) => { if (!alpha)
1965
+ return s; const to = new Map(); return s.replace(/([A-Za-z_?]+)\$(\d+)/g, (w, p) => { let r = to.get(w); if (!r)
1966
+ to.set(w, (r = `${p}$_${to.size}`)); return r; }); };
1967
+ const textOfLaw = (l) => { let t = lawText.get(l.holds); if (t === undefined)
1968
+ lawText.set(l.holds, (t = alphaText(JSON.stringify([l.holds, l.forall ?? null, l.keys ?? null])))); return t; };
1969
+ function memoOf(m) {
1970
+ let key = machineText.get(m);
1971
+ if (key === undefined)
1972
+ machineText.set(m, (key = alphaText(JSON.stringify(m))));
1973
+ let memo = memos.get(key);
1974
+ if (!memo) {
1975
+ if (memos.size >= memoCap)
1976
+ memos.clear();
1977
+ memos.set(key, (memo = { proven: new Map(), models: new Map() }));
1978
+ }
1979
+ return memo;
1980
+ }
1981
+ const stands = (p, byName) => [...p.uses].every(([n, t]) => { const l = byName.get(n); return !!l && textOfLaw(l) === t; });
1982
+ // Law i settled, from what was kept where it still stands (a proof whose support is in the set, a model of a set holding
1983
+ // this one): else its goals settled again, those whose proofs stand kept.
1984
+ function settled(m, laws, i, rounds, usual) {
1985
+ const law = laws[i], memo = memoOf(m), byName = new Map(laws.map(l => [l.name, l])), text = textOfLaw(law);
1986
+ const was = memo.proven.get(law.name), prev = was?.text === text ? was : undefined;
1987
+ if (prev && Object.values(prev.proofs).every(p => stands(p, byName))) {
1988
+ memoHits.n++;
1989
+ return prev;
1990
+ }
1991
+ memoHits.miss++;
1992
+ const mo = rounds === modelRounds ? memo.models.get(law.name) : undefined;
1993
+ if (mo && mo.text === text && laws.every(l => mo.set.get(l.name) === textOfLaw(l)))
1994
+ return mo.model;
1995
+ const out = settle(m, laws, i, rounds, usual, prev);
1996
+ const cap = (x) => { if (x.size >= 4096)
1997
+ x.clear(); return x; };
1998
+ if (out && 'proofs' in out)
1999
+ cap(memo.proven).set(law.name, out);
2000
+ else if (out?.stuck === 'sat' && rounds === modelRounds)
2001
+ cap(memo.models).set(law.name, { text, model: out, set: new Map(laws.map(l => [l.name, textOfLaw(l)])) });
2002
+ return out;
2003
+ }
2004
+ // The fast path's machines: no history, sums or "there exists" (their goals are other machines' or need witnesses).
2005
+ const fastShape = (m, laws) => !m.history && !(m.sums && Object.keys(m.sums).length) && !someLaws(laws) && !laws.some(l => someKeys(l.holds).length);
2006
+ // How many hypotheses a law (or fact) is at these instances (kernel.ts's assumed), and its tuples' width.
2007
+ const widthOf = (l) => (l.keys?.length ? 1 + l.keys.length : 1);
2008
+ const countOf = (l, inst) => (l.forall ? Math.floor((inst[l.name]?.length ?? 0) / widthOf(l)) : 1);
2009
+ // The laws a step goal's hypotheses `used` are instances of, each with the tuples (by text) it is at. kernel.ts's
2010
+ // obligations lays a step goal out as: the facts at their instances, the precondition, the assumption, each law at its
2011
+ // instances in order, the quantified flags' closing, the conclusion. Each such hypothesis is checked against its law's
2012
+ // instance; one that isn't what the layout says leaves the sources unread (undefined). A start goal assumes no law.
2013
+ function sourcesOf(m, laws, inst, goal, used) {
2014
+ const out = new Map();
2015
+ if (goal.name.endsWith(' @start'))
2016
+ return out;
2017
+ let h = (m.facts ?? []).reduce((n, f) => n + countOf(f, inst), 0) + (m.pre ? 1 : 0) + (m.assume ? 1 : 0);
2018
+ const starts = laws.map(l => { const at = h; h += countOf(l, inst); return at; });
2019
+ for (const u of used) {
2020
+ if (!laws.length || u < starts[0] || u >= h)
2021
+ continue;
2022
+ let k = 0;
2023
+ while (k + 1 < laws.length && starts[k + 1] <= u)
2024
+ k++;
2025
+ const l = laws[k], t = u - starts[k], n = widthOf(l), tuple = l.forall ? (inst[l.name] ?? []).slice(t * n, (t + 1) * n) : [];
2026
+ const want = assumed([l], l.forall ? { [l.name]: tuple } : {})[0];
2027
+ if (!want || JSON.stringify(want) !== JSON.stringify(goal.hyps[u]))
2028
+ return undefined;
2029
+ if (!out.has(l.name))
2030
+ out.set(l.name, new Set());
2031
+ out.get(l.name).add(JSON.stringify(tuple));
2032
+ }
2033
+ return out;
2034
+ }
2035
+ // Law i's goals settled: each decided by the EPR path (a refutation's core proven), else (`usual`) by the usual search;
2036
+ // a model's broken tuples added (modelInstances) `rounds` times, and on while the caller's deadline allows (four times
2037
+ // as many at most: each round's model breaks a law at a tuple or two, sharded KV's caller goal from its enumerated cubes
2038
+ // is proven in its sixth), a goal proven in an earlier round not asked
2039
+ // again (the instances only grow). From `prev`, its instances (unless a law about keys is new since) and the proofs that
2040
+ // still stand. The proofs with their support, or the goal not proven (a model with its diagram, or unknown), or
2041
+ // undefined where the EPR path alone can't say (not `usual`).
2042
+ function settle(m, laws, i, rounds, usual, prev) {
2043
+ const law = laws[i], byName = new Map(laws.map(l => [l.name, l]));
2044
+ // (decideLaw's and the fast set proof's: each law's keys of its sort alone, `bySort`; proveLaw's and the join's as they
2045
+ // were. The fast set proof is checked over the tuples its proofs read, and the usual proof follows where it fails)
2046
+ let inst = prev && laws.every(l => !l.forall || l.name in prev.inst) ? prev.inst : bySort(m, laws, lawInstances(m, laws, i));
2047
+ // (GDP_DLTRIG=1: decideLaw's first instances only those a goal's reads trigger (proveOne's `triggered`), the model
2048
+ // rounds adding the instances a model breaks (MBQI's))
2049
+ if (!prev && !usual && env.GDP_DLTRIG === '1')
2050
+ inst = triggered(plainOf(m), laws, inst, i2 => obligations(m, laws, { [law.name]: i2 }, i), law.forall ? [`${law.forall}#`] : []);
2051
+ const proofs = Object.fromEntries(Object.entries(prev?.proofs ?? {}).filter(([, p]) => stands(p, byName)));
2052
+ const unknown = (g, why = 'past the search\'s end') => (usual ? { goal: g.name, stuck: 'unknown', why } : undefined);
2053
+ // (past the `rounds` model rounds, each round within the caller's deadline, its model the answer where the round can't
2054
+ // finish: a model of fewer instances is still one of the goal as it was asked)
2055
+ const end = withinDeadline(Infinity);
2056
+ let last;
2057
+ for (let round = 0;; round++) {
2058
+ let more;
2059
+ const late = round > rounds ? () => pastWall() || clock() > end : pastWall;
2060
+ for (const g of obligations(m, laws, { [law.name]: inst }, i)) {
2061
+ if (proofs[g.name])
2062
+ continue;
2063
+ if (late())
2064
+ return strict(usual) ? unknown(g) : last ?? unknown(g);
2065
+ let o = eprScope.patterns ? eprFirst(g, { nodes: 0, until: clock() + 4_000 }, false, late) : undefined;
2066
+ // (a refutation whose core's proof didn't finish: a model from fewer instances, which these refute, is no answer;
2067
+ // decideLaw's unknown, the usual search's next)
2068
+ if (!o && eprLast.refuted) {
2069
+ if (!usual) {
2070
+ decideNote.refuted = true;
2071
+ return undefined;
2072
+ }
2073
+ }
2074
+ else if (!o && (last || !usual))
2075
+ return strict(usual) ? undefined : last;
2076
+ // (the usual search, the EPR path not asked again)
2077
+ if (!o) {
2078
+ const busy = eprScope.busy;
2079
+ eprScope.busy = true;
2080
+ try {
2081
+ o = grow(g);
2082
+ }
2083
+ finally {
2084
+ eprScope.busy = busy;
2085
+ }
2086
+ }
2087
+ if ('tree' in o) {
2088
+ // (a proof whose hypotheses' sources aren't read: its support every law of the set)
2089
+ const src = sourcesOf(m, laws, inst, g, o.core ?? usedHyps(g, o.tree));
2090
+ proofs[g.name] = { part: o.part ?? g, tree: o.tree, uses: new Map((src ? [...src.keys()] : laws.map(l => l.name)).map(n => [n, textOfLaw(byName.get(n))])), ...(src ? { tuples: src } : {}) };
2091
+ continue;
2092
+ }
2093
+ if (o.stuck !== 'sat' || !o.witness)
2094
+ return strict(usual) ? unknown(g, o.why) : last ?? unknown(g, o.why);
2095
+ last = { goal: g.name, stuck: 'sat', witness: o.witness, ...(o.diagram ? { diagram: o.diagram } : {}), why: 'a model' };
2096
+ // (strict, decideLaw's: a model is returned only where confirmed, no assumed law broken at it over its own domain;
2097
+ // one that breaks only instances of another sort, or that the rounds or the wall cut off, is no answer)
2098
+ const capped = !(round < rounds || (round < 4 * rounds && end !== Infinity && clock() < end)), raw = capped ? undefined : modelInstances(m, laws, inst, g, o.witness);
2099
+ if (!capped && !raw)
2100
+ return last;
2101
+ more = raw && bySort(m, laws, raw);
2102
+ const count = (x) => Object.values(x).reduce((s2, ks) => s2 + ks.length, 0);
2103
+ if (strict(usual) && (capped || pastWall() || !more || count(more) <= count(inst)))
2104
+ return undefined;
2105
+ // (the model's only broken instances another sort's: the next round would find it again; decideLaw's no answer)
2106
+ if (more && count(more) <= count(inst))
2107
+ return usual ? last : undefined;
2108
+ if (!more || pastWall())
2109
+ return last;
2110
+ break;
2111
+ }
2112
+ if (!more)
2113
+ return { text: textOfLaw(law), inst, proofs };
2114
+ inst = more;
2115
+ }
2116
+ }
2117
+ // A set of laws proven as proveLaws proves it, for a search that drops a law the proof fails at and asks again (the
2118
+ // enumeration's set proof): each law's goals settled in order (kept from this call or decideLaw's where they stand), the
2119
+ // first law not proven returned with its goal's model; when every law is, the proof made once: each law's instances only
2120
+ // the tuples its proofs read, each proof widened to its goal there (else the goal grown), and the whole checked by
2121
+ // kernel.ts (checkLaws). Machines with a history, sums or "there exists": proveLaws. A search's trial proof: no cyclic
2122
+ // certificate is made.
2123
+ export function proveSetFast(m, laws) {
2124
+ if (env.GDP_MEMO_TRACE) {
2125
+ memoHits.setKey = machineKey(m);
2126
+ memoHits.setJson = JSON.stringify(m);
2127
+ }
2128
+ // (laws with "there exists": proveSome's witnesses, its whole set this fast proof over the ghosted machine)
2129
+ if (!fastShape(m, laws))
2130
+ return someLaws(laws) && fastShape(m, laws.map(l => ({ name: l.name, holds: l.holds }))) ? proveSome(m, laws, { whole: proveSetFast }) : proveLaws(m, laws);
2131
+ return withPatterns(m, laws, () => pointed(laws, () => {
2132
+ const at = [];
2133
+ for (let i = 0; i < laws.length; i++) {
2134
+ const out = settled(m, laws, i, modelRounds, true);
2135
+ if (!('proofs' in out))
2136
+ return { proven: false, nodes: 0, leaves: 0, checked: false, failed: { goal: out.goal, stuck: out.stuck, ...(out.witness ? { witness: out.witness } : {}), ...(out.why ? { why: out.why } : {}), ...(out.diagram ? { diagram: out.diagram } : {}) } };
2137
+ at.push(out);
2138
+ }
2139
+ const instances = {}, trees = {}, byName = new Map(laws.map(l => [l.name, l]));
2140
+ let nodes = 0, leaves = 0;
2141
+ for (const [i, law] of laws.entries()) {
2142
+ // (each law about keys at the tuples the proofs read; all of them where a proof's sources weren't read)
2143
+ const s = at[i], ps = Object.values(s.proofs), all = ps.some(p => !p.tuples);
2144
+ const inst = all ? s.inst : Object.fromEntries(Object.entries(s.inst).map(([n, ks]) => {
2145
+ const l = byName.get(n), k = l ? widthOf(l) : 1;
2146
+ return [n, !l ? ks : ks.filter((_, j) => ps.some(p => p.tuples.get(n)?.has(JSON.stringify(ks.slice(j - (j % k), j - (j % k) + k)))))];
2147
+ }));
2148
+ instances[law.name] = inst;
2149
+ for (const g of obligations(m, laws, { [law.name]: inst }, i)) {
2150
+ const p = s.proofs[g.name];
2151
+ let tree = p && widen(p.part, g, p.tree);
2152
+ if (!tree) {
2153
+ const o = grow(g);
2154
+ if (!('tree' in o))
2155
+ return stuckAt(g, o, nodes, leaves);
2156
+ tree = o.tree;
2157
+ nodes += o.nodes;
2158
+ }
2159
+ trees[g.name] = tree;
2160
+ leaves += countLeaves(tree);
2161
+ }
2162
+ }
2163
+ const proof = { instances, trees };
2164
+ return { proven: true, nodes, leaves, checked: checkLaws(m, laws, proof), proof };
2165
+ }));
2166
+ }
1746
2167
  export function proveLaw(m, laws, i) {
1747
2168
  if (laws.some(l => someKeys(l.holds).length) || someLaws(laws)) {
1748
2169
  const r = proveLaws(m, laws);
1749
2170
  return r.proven ? { proven: true } : { proven: false, goal: r.failed.goal, stuck: r.failed.stuck, ...(r.failed.witness ? { witness: r.failed.witness } : {}) };
1750
2171
  }
1751
- return pointed(laws, () => proveOne(m, laws, i));
2172
+ // (the thinned goals too by the EPR path where the rule's keys are composed: withModels' scope, entered here; first
2173
+ // the law settled by the EPR path as decideLaw settles it, kept where it stands: a caller's verdict rests on its final
2174
+ // proof, which widens and checks; wo's "a leader has the voting quorum's votes" from its 40-law set, 0.45 s there
2175
+ // against 25 s to unknown here)
2176
+ return withPatterns(m, laws, () => {
2177
+ const out = eprScope.patterns && fastShape(m, laws) ? settled(m, laws, i, modelRounds, false) : undefined;
2178
+ if (out && 'proofs' in out)
2179
+ return { proven: true };
2180
+ if (out?.stuck === 'sat')
2181
+ return { proven: false, goal: out.goal, stuck: 'sat', ...(out.witness ? { witness: out.witness } : {}), ...(out.diagram ? { diagram: out.diagram } : {}) };
2182
+ return pointed(laws, () => proveOne(m, laws, i));
2183
+ });
1752
2184
  }
1753
2185
  function proveOne(m, laws, i) {
1754
2186
  const law = laws[i], pm = plainOf(m), inst = lawInstances(m, laws, i);
@@ -1757,7 +2189,7 @@ function proveOne(m, laws, i) {
1757
2189
  return { proven: true };
1758
2190
  // (a model breaking a law at a tuple of the goal's keys: those added, the law asked again)
1759
2191
  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 };
2192
+ return a.out ? { proven: false, goal: a.goal.name, stuck: a.out.stuck, ...(a.out.witness ? { witness: a.out.witness } : {}), ...(a.out.diagram ? { diagram: a.out.diagram } : {}) } : { proven: true };
1761
2193
  }
1762
2194
  function growAll(gs) {
1763
2195
  const done = {};
@@ -1774,6 +2206,188 @@ function growAll(gs) {
1774
2206
  }
1775
2207
  const grownModel = (x) => (x.out?.stuck === 'sat' && x.out.witness ? { goal: x.goal, w: x.out.witness } : undefined);
1776
2208
  const grownSettled = (x) => !x.out || x.out.stuck === 'sat';
2209
+ // Each law's keys only at keys of their sort (Ivy's sorts; untrusted: an instance left out only weakens a goal, and a
2210
+ // set's proof is checked over its own instances). A sort is a class of a union-find over places: each part of a map's
2211
+ // key (by its pattern, `M:map:i`), a map's whole key where a law's key is the whole key (`K:map`), a function's
2212
+ // argument and value (`A:f`, `F:f`), and every name, a law's keys its own (`L:law:k`), a quantified flag's its own
2213
+ // (`Q:f:k`). Names one comparison relates are one sort; a part that is a function's value is that function's value's.
2214
+ // A key term whose sort is anchored (a map's part or key, a function's argument or value) and differs from the law key's
2215
+ // anchored sort is left out of the law's tuples there; a composed term is a whole key, of the map whose pattern its
2216
+ // factors are. GDP_SORTED=0 keeps every instance.
2217
+ const sortedOn = env.GDP_SORTED !== '0';
2218
+ // decideLaw's models confirmed only (GDP_STRICT=1; off by default: decentralized lock's rounds then lean on the proof
2219
+ // path where an unconfirmed model used to answer, 27-36 s against 13-17 s): a model is returned where no assumed law is
2220
+ // broken at it over its own domain, else nothing (research/protocols/engine/DESIGN.md, gen/ring)
2221
+ let strictOn = false;
2222
+ // (decideLaw's models are confirmed ones only, always: an unconfirmed one, at the deadline or past the model rounds, was
2223
+ // wrong against Z3 on 43 of wo's 143 top-down goals; GDP_STRICT=0 gives the old answer)
2224
+ const strict = (usual) => !usual && (strictOn || env.GDP_STRICT !== '0');
2225
+ // (strict models for a caller's own decisions: the engine's top-down phase, whose drops an unconfirmed model would make wrong)
2226
+ export const withStrict = (f) => { const o = strictOn; strictOn = true; try {
2227
+ return f();
2228
+ }
2229
+ finally {
2230
+ strictOn = o;
2231
+ } };
2232
+ // (by machine and by the law set's names: one machine is asked with many sets)
2233
+ const sortsMemo = new WeakMap();
2234
+ function sortsOf(m, laws) {
2235
+ const par = new Map(), find = (a) => { const q = par.get(a); if (q === undefined || q === a)
2236
+ return a; const r = find(q); par.set(a, r); return r; };
2237
+ const named = new Set(), union = (a, b) => { named.add(a); named.add(b); const ra = find(a), rb = find(b); if (ra !== rb)
2238
+ par.set(ra, rb); };
2239
+ const pats = patternsOf(m, laws), whole = new Map();
2240
+ const leaves = (e, k, out) => { if (e.op === 'add') {
2241
+ leaves(e.a, k, out);
2242
+ leaves(e.b, k, out);
2243
+ }
2244
+ else if (e.op === 'mul')
2245
+ leaves(e.a, k * e.k, out);
2246
+ else if (e.op !== 'const')
2247
+ out.push([e, k]); };
2248
+ const walkC = (c, name) => {
2249
+ const node = (e) => (e.op === 'var' ? name(e.name) : e.op === 'get' && m.fns?.[e.map] ? `F:${e.map}` : undefined);
2250
+ const visit = (o) => {
2251
+ if (!o || typeof o !== 'object')
2252
+ return;
2253
+ const x = o;
2254
+ if (x.op === 'get' && x.key) {
2255
+ if (m.fns?.[x.map]) {
2256
+ const n = node(x.key);
2257
+ if (n)
2258
+ union(n, `A:${x.map}`);
2259
+ }
2260
+ else {
2261
+ const ls = [];
2262
+ leaves(x.key, 1, ls);
2263
+ const pat = pats[x.map] ?? [1];
2264
+ if (pat.length > 1 && ls.length === 1 && ls[0][1] === 1) {
2265
+ const n = node(ls[0][0]);
2266
+ if (n)
2267
+ union(n, `K:${x.map}`);
2268
+ }
2269
+ else {
2270
+ if (pat.length > 1)
2271
+ whole.set(JSON.stringify(x.key), `K:${x.map}`);
2272
+ for (const [e, k] of ls) {
2273
+ const idx = pat.indexOf(k), n = node(e);
2274
+ if (n && idx >= 0)
2275
+ union(n, `M:${x.map}:${idx}`);
2276
+ }
2277
+ }
2278
+ }
2279
+ }
2280
+ if ((x.op === '<' || x.op === '<=' || x.op === '=') && x.a && x.b) {
2281
+ const la = [], lb = [];
2282
+ leaves(x.a, 1, la);
2283
+ leaves(x.b, 1, lb);
2284
+ if (la.length === 1 && lb.length === 1 && Math.abs(la[0][1]) === 1 && Math.abs(lb[0][1]) === 1) {
2285
+ const p = node(la[0][0]), q = node(lb[0][0]);
2286
+ if (p && q)
2287
+ union(p, q);
2288
+ }
2289
+ }
2290
+ for (const y of Object.values(o))
2291
+ visit(y);
2292
+ };
2293
+ visit(c);
2294
+ };
2295
+ const plain = (v) => `V:${v}`;
2296
+ walkC(m.step, plain);
2297
+ if (m.assume)
2298
+ walkC(m.assume, plain);
2299
+ if (m.pre)
2300
+ walkC(m.pre, plain);
2301
+ for (const [f, c] of Object.entries(m.step.flags ?? {}))
2302
+ if (c.op === 'all') {
2303
+ const bs = new Set(boundOf(c));
2304
+ walkC(c, v => (bs.has(v) ? `Q:${f}:${v}` : `V:${v}`));
2305
+ witnessesOf(f, c).forEach((w, j) => union(`V:${w}`, `Q:${f}:${boundOf(c)[j]}`));
2306
+ }
2307
+ // (a write at a key: the key read there; a write at every key, its binder the map's whole key)
2308
+ for (const [mp, w] of Object.entries(m.step.maps ?? {}))
2309
+ if (!('each' in w))
2310
+ walkC({ op: 'get', map: mp, key: w.key }, plain);
2311
+ for (const [mp, w] of Object.entries(m.step.maps ?? {}))
2312
+ if ('each' in w)
2313
+ union(`V:${w.each}`, (pats[mp] ?? [1]).length > 1 ? `K:${mp}` : `M:${mp}:0`);
2314
+ for (const l of laws) {
2315
+ const own = new Set([l.forall, ...(l.keys ?? [])].filter(Boolean));
2316
+ walkC(l.holds, v => (own.has(v) ? `L:${l.name}:${v}` : `V:${v}`));
2317
+ }
2318
+ // (two maps of one pattern whose parts are of the same sorts have their whole keys of one sort: wo's Votes, VoteMsg and
2319
+ // VoteRequestMsg, node × node, so a composed term read at one is an instance of a law about another's whole key)
2320
+ const multi = Object.keys(pats).filter(mp => pats[mp].length > 1);
2321
+ for (let grew = true; grew;) {
2322
+ grew = false;
2323
+ for (const a of multi)
2324
+ for (const b of multi)
2325
+ if (a < b && find(`K:${a}`) !== find(`K:${b}`) && pats[a].join() === pats[b].join() && pats[a].every((_, i) => named.has(`M:${a}:${i}`) && named.has(`M:${b}:${i}`) && find(`M:${a}:${i}`) === find(`M:${b}:${i}`))) {
2326
+ union(`K:${a}`, `K:${b}`);
2327
+ grew = true;
2328
+ }
2329
+ }
2330
+ const anchorOf = new Map();
2331
+ for (const a of par.keys())
2332
+ if (/^(M|K|A|F):/.test(a))
2333
+ anchorOf.set(find(a), true);
2334
+ for (const a of [...par.values()])
2335
+ if (/^(M|K|A|F):/.test(a))
2336
+ anchorOf.set(find(a), true);
2337
+ const of = (e) => {
2338
+ const w = whole.get(JSON.stringify(e));
2339
+ if (w)
2340
+ return w;
2341
+ const ls = [];
2342
+ leaves(e, 1, ls);
2343
+ // (a composed term, several parts or a part under a factor, is a whole key: of the map whose pattern its factors are,
2344
+ // never a part's sort)
2345
+ if (ls.length !== 1 || ls[0][1] !== 1) {
2346
+ const cs = ls.map(([, c]) => c).sort((a, b) => b - a).join(',');
2347
+ const mp = Object.keys(pats).find(k2 => pats[k2].length > 1 && [...pats[k2]].sort((a, b) => b - a).join(',') === cs);
2348
+ return mp ? `K:${mp}` : `K:?${cs}`;
2349
+ }
2350
+ const x = ls[0][0];
2351
+ return x.op === 'var' ? (x.name.endsWith('#') ? undefined : `V:${x.name}`) : x.op === 'get' && m.fns?.[x.map] ? `F:${x.map}` : undefined;
2352
+ };
2353
+ return { key: (law, k) => `L:${law}:${k}`, of, find, anchored: (a) => /^K:/.test(a) || !!anchorOf.get(find(a)) };
2354
+ }
2355
+ function bySort(m, laws, inst) {
2356
+ if (!sortedOn)
2357
+ return inst;
2358
+ let byLaws = sortsMemo.get(m);
2359
+ if (!byLaws)
2360
+ sortsMemo.set(m, (byLaws = new Map()));
2361
+ const lk = laws.map(l => l.name).join('\u0001');
2362
+ let s = byLaws.get(lk);
2363
+ if (!s) {
2364
+ if (byLaws.size >= 64)
2365
+ byLaws.clear();
2366
+ byLaws.set(lk, (s = sortsOf(m, laws)));
2367
+ }
2368
+ const S = s;
2369
+ const keysOf = (n) => {
2370
+ if (n.startsWith('?')) {
2371
+ const c = m.step.flags?.[n.slice(1)];
2372
+ return c?.op === 'all' ? boundOf(c).map(k => `Q:${n.slice(1)}:${k}`) : undefined;
2373
+ }
2374
+ const l = laws.find(x => x.name === n);
2375
+ return l?.forall ? [l.forall, ...(l.keys ?? [])].map(k => S.key(n, k)) : undefined;
2376
+ };
2377
+ return Object.fromEntries(Object.entries(inst).map(([n, ks]) => {
2378
+ const want = keysOf(n);
2379
+ if (!want || !ks.length)
2380
+ return [n, ks];
2381
+ const a = want.length, out = [];
2382
+ for (let t = 0; t + a <= ks.length; t += a) {
2383
+ const tuple = ks.slice(t, t + a);
2384
+ const ok = tuple.every((e, j) => { const se = S.of(e); return !se || !S.anchored(se) || !S.anchored(want[j]) || S.find(se) === S.find(want[j]); });
2385
+ if (ok)
2386
+ out.push(...tuple);
2387
+ }
2388
+ return [n, out];
2389
+ }));
2390
+ }
1777
2391
  // The instances law i's goals are read at (proveLaw's; core/infer.ts's join asks one goal at a time).
1778
2392
  export function lawInstances(m, laws, i) {
1779
2393
  // (a machine with sums: its plain machine's instances, as proveLawsAsGiven's)
@@ -1862,7 +2476,7 @@ export const usualProof = {};
1862
2476
  // A machine with sums has no cyclic twin yet: its certificate is the usual trees, checked with its cover goals.
1863
2477
  const sumsWhy = (m) => (m.sums && Object.keys(m.sums).length ? 'a sum over a map\'s keys (Sums.lean checks the usual trees)' : undefined);
1864
2478
  function proveThinned(m, laws, instances) {
1865
- return pointed(laws, () => thinned(m, laws, instances));
2479
+ return withPatterns(m, laws, () => pointed(laws, () => thinned(m, laws, instances)));
1866
2480
  }
1867
2481
  function thinned(m, laws, instances) {
1868
2482
  const trees = {}, fulls = { ...instances };