gdp-wired 0.25.0 → 0.27.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 (52) hide show
  1. package/README.md +14 -9
  2. package/dist/core/accel.d.ts +20 -1
  3. package/dist/core/accel.js +797 -220
  4. package/dist/core/bmc.d.ts +12 -1
  5. package/dist/core/bmc.js +275 -106
  6. package/dist/core/cycles.d.ts +2 -3
  7. package/dist/core/cycles.js +35 -131
  8. package/dist/core/cyclic.d.ts +4 -1
  9. package/dist/core/cyclic.js +103 -74
  10. package/dist/core/data.d.ts +1 -1
  11. package/dist/core/data.js +89 -118
  12. package/dist/core/discover.js +65 -27
  13. package/dist/core/dsl.d.ts +3 -2
  14. package/dist/core/dsl.js +29 -25
  15. package/dist/core/exists.js +7 -14
  16. package/dist/core/extract-check.d.ts +55 -4
  17. package/dist/core/extract-check.js +248 -122
  18. package/dist/core/extract-print.d.ts +1 -0
  19. package/dist/core/extract-print.js +26 -3
  20. package/dist/core/extract-read.d.ts +98 -4
  21. package/dist/core/extract-read.js +306 -43
  22. package/dist/core/extract-shapes.d.ts +14 -0
  23. package/dist/core/extract-shapes.js +609 -79
  24. package/dist/core/extract-xstate.d.ts +5 -1
  25. package/dist/core/extract-xstate.js +618 -184
  26. package/dist/core/extract.d.ts +1 -0
  27. package/dist/core/extract.js +81 -30
  28. package/dist/core/infer.d.ts +1 -0
  29. package/dist/core/infer.js +126 -64
  30. package/dist/core/machine.d.ts +6 -0
  31. package/dist/core/machine.js +35 -4
  32. package/dist/core/nonterm.d.ts +5 -1
  33. package/dist/core/nonterm.js +133 -45
  34. package/dist/core/q.d.ts +1 -0
  35. package/dist/core/q.js +2 -2
  36. package/dist/core/relation.d.ts +1 -0
  37. package/dist/core/relation.js +20 -36
  38. package/dist/core/solver.d.ts +33 -0
  39. package/dist/core/solver.js +84 -30
  40. package/dist/core/transfer.js +22 -13
  41. package/dist/core/translate.d.ts +1 -1
  42. package/dist/core/translate.js +88 -65
  43. package/dist/core/xstate.d.ts +6 -1
  44. package/dist/core/xstate.js +336 -55
  45. package/dist/kernel/cdcl.js +212 -79
  46. package/dist/kernel/prove.d.ts +36 -5
  47. package/dist/kernel/prove.js +212 -104
  48. package/dist/kernel/reader.d.ts +75 -5
  49. package/dist/kernel/reader.js +533 -76
  50. package/dist/kernel/simplex.d.ts +27 -2
  51. package/dist/kernel/simplex.js +160 -14
  52. package/package.json +3 -2
@@ -1,4 +1,15 @@
1
- import { add, k, refuteFast, scale, solve, sub, v, work } from "../core/solver.js";
1
+ // An untrusted prover for the kernel: grows a split tree until every leaf's constraints are refuted by solve(), splitting
2
+ // on whatever atom the hypotheses leave open (an if's condition, a min's or ∸'s comparison, a disjunction's atoms, two
3
+ // reads of one map at keys not yet known equal or apart). Its trees go to kernel.check; nothing it says is trusted.
4
+ // What keeps it fast (research/perf/prover-bench.ts and prover-stress.ts measure each):
5
+ // - the conclusion's atoms are split first: a case it never reads is often one no refutation needs;
6
+ // - a node with a case still to split asks only "refuted or not": its Farkas rows first (solver.ts refuteFast), then
7
+ // a bounded elimination; the full one, which a satisfiable system needs to the last variable, only at the leaves;
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
+ // - a hypothesis' rows and open atoms, and every term inside them, are reused from an earlier path that decided the
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";
12
+ import { add, costs, env, k, refuteFast, scale, solve, sub, v, work } from "../core/solver.js";
2
13
  import { checkRefutation } from "../core/check.js";
3
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";
4
15
  import { proveSome, someLaws } from "../core/exists.js";
@@ -84,43 +95,68 @@ function openH(c, path, out, positive = true) {
84
95
  // keys a pairing builds ((a + b)² + b, keys whose difference has monomials) are left uncompared: that encoding states
85
96
  // their congruence as facts, and comparing their keys only brings products into leaves its linear rows decide.
86
97
  export const pairedKeys = { skip: false };
87
- export function openCells(rows, path) {
88
- const names = [...new Set(rows.flatMap(r => Object.keys(r.lin)))].filter(isCell);
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
+ // the same forms at every node keep what is remembered per form)
100
+ const cellKeys = new Map(), cellPairs = new Map();
101
+ export const cellPair = (a, b) => {
102
+ const pk = `${a}\u0000${b}`;
103
+ let pair = cellPairs.get(pk);
104
+ if (!pair) {
105
+ if (cellPairs.size > 200_000)
106
+ cellPairs.clear();
107
+ const d = sub(cellKey(a).key, cellKey(b).key);
108
+ cellPairs.set(pk, (pair = { d, neg: scale(d, -1) }));
109
+ }
110
+ return pair;
111
+ };
112
+ const cellKey = (n) => { let c = cellKeys.get(n); if (!c) {
113
+ if (cellKeys.size > 100_000)
114
+ cellKeys.clear();
115
+ cellKeys.set(n, (c = { map: n.slice(0, n.indexOf('[')), key: parseKey(n.slice(n.indexOf('[') + 1, -1)) }));
116
+ } return c; };
117
+ function openCells(rows, path) {
118
+ const seen = new Set(), names = [];
119
+ for (const r of rows)
120
+ for (const n in r.lin)
121
+ if (!seen.has(n)) {
122
+ seen.add(n);
123
+ if (isCell(n))
124
+ names.push(n);
125
+ }
89
126
  const out = [];
90
- const keyText = (n) => n.slice(n.indexOf('[') + 1, -1);
91
- // (each name's map and key read once: the pairs are quadratic in the names)
92
- const maps = names.map(n => n.slice(0, n.indexOf('['))), keys = names.map(n => parse(keyText(n)));
127
+ const cs = names.map(cellKey);
128
+ const dec = (lin) => path.get(canon(lin))?.holds ?? (path.has(canonFlip(lin)) ? !path.get(canonFlip(lin)).holds : undefined);
93
129
  for (let i = 0; i < names.length; i++)
94
130
  for (let j = i + 1; j < names.length; j++) {
95
- if (maps[i] !== maps[j])
131
+ if (cs[i].map !== cs[j].map)
96
132
  continue;
97
- const d = sub(keys[i], keys[j]);
133
+ const pair = cellPair(names[i], names[j]), d = pair.d;
98
134
  if (pairedKeys.skip && Object.keys(d).some(isMonomial))
99
135
  continue;
100
- const dec = (lin) => path.get(canon(lin))?.holds ?? (path.has(canonFlip(lin)) ? !path.get(canonFlip(lin)).holds : undefined);
101
136
  // Two cells of a run's map (core/cyclic.ts: time u and key k at u + k·Ω) at keys k·Ω and k'·Ω: k = k' first, a
102
137
  // linear atom; the keys' own difference only where k = k' (its other side then refuted by (k − k')·Ω = 0, a product).
103
- const q0 = cellProducts.on ? quotient(d) : undefined;
138
+ const q0 = cellProducts.on ? ('q0' in pair ? pair.q0 : (pair.q0 = quotient(d))) : undefined;
104
139
  if (q0) {
105
- const qa = dec(q0), qb = dec(scale(q0, -1));
140
+ const q1 = (pair.q1 ??= scale(q0, -1));
141
+ const qa = dec(q0), qb = dec(q1);
106
142
  if (qa === undefined) {
107
143
  out.push(q0);
108
144
  continue;
109
145
  }
110
146
  if (qa === true && qb === undefined) {
111
- out.push(scale(q0, -1));
147
+ out.push(q1);
112
148
  continue;
113
149
  }
114
150
  if (!(qa && qb))
115
151
  continue;
116
152
  cellDiffs.set(canon(d), q0);
117
- cellDiffs.set(canon(scale(d, -1)), scale(q0, -1));
153
+ cellDiffs.set(canon(pair.neg), q1);
118
154
  }
119
- const a = dec(d), b = dec(scale(d, -1));
155
+ const a = dec(d), b = dec(pair.neg);
120
156
  if (a === undefined)
121
157
  out.push(d);
122
158
  else if (a === true && b === undefined)
123
- out.push(scale(d, -1));
159
+ out.push(pair.neg);
124
160
  }
125
161
  return out;
126
162
  }
@@ -142,7 +178,8 @@ const quotient = (d) => {
142
178
  };
143
179
  // The cells' key differences split at their quotient's equality, by canonical text: their quotient.
144
180
  const cellDiffs = new Map();
145
- function parse(text) {
181
+ // A key's canonical text read back as its linear form.
182
+ export function parseKey(text) {
146
183
  const out = {};
147
184
  let depth = 0, start = 0;
148
185
  for (let i = 0; i <= text.length; i++) {
@@ -188,12 +225,12 @@ const solveP = (rows, maxRows) => {
188
225
  // PROVE_DUMP: a hook research/perf/prof sets to read each root goal.
189
226
  export let proveDump;
190
227
  export const setProveDump = (f) => { proveDump = f; };
191
- const proveTrace = !!globalThis.process?.env?.PROVE_TRACE;
228
+ const proveTrace = !!env.PROVE_TRACE;
192
229
  // `why`, when the budget ran out: which limit, at what size, and what usually helps.
193
230
  // Set while core/cyclic.ts grows its goals.
194
231
  export const cellProducts = { on: false };
195
- // The budget: 200,000 nodes and, by default, a second per hypothesis (at least 20 seconds) per goal; past either the goal
196
- // is left `unknown`. A goal with many instances (a law about two keys at its pairs) has that many more rows per leaf.
232
+ // The budget: 200,000 nodes and, by default, a second per hypothesis (at least 20 seconds) per goal, on the counted
233
+ // clock inside `counted` and in the cost model's work outside it (`withWork`); past either the goal is left `unknown`. A goal with many instances (a law about two keys at its pairs) has that many more rows per leaf.
197
234
  // A deadline every goal grown inside `withDeadline` keeps, beside its own budget: a search that proves many things (core/
198
235
  // infer.ts, core/discover.ts, the search proveRule falls back on) bounds them all; a goal past it is left `unknown`.
199
236
  let deadline = Infinity;
@@ -201,14 +238,16 @@ let deadline = Infinity;
201
238
  // time, or within `counted` the work the prover has done (the solver's rows read and made, each node's rows), `perMs`
202
239
  // units a millisecond, so that what a search's budget lets it try, and so its verdict, doesn't depend on the machine's
203
240
  // speed. A counted search inside another reads the outer's clock.
204
- let rate = 0;
205
- export const clock = () => (rate ? work.n / rate : performance.now());
206
- export function counted(perMs, f) {
241
+ // With `full`, the clock reads the cost model below in place of work.n.
242
+ let rate = 0, meter = () => work.n;
243
+ export const clock = () => (rate ? meter() / rate : performance.now());
244
+ export function counted(perMs, f, full = false) {
207
245
  if (rate)
208
246
  return f();
209
247
  const outer = deadline;
210
248
  rate = perMs;
211
249
  deadline = Infinity;
250
+ meter = full ? fullWork : () => work.n;
212
251
  try {
213
252
  return f();
214
253
  }
@@ -217,6 +256,33 @@ export function counted(perMs, f) {
217
256
  deadline = outer;
218
257
  }
219
258
  }
259
+ // The cost model: what a query does, by kind (core/solver.ts's costs), each weighed to the milliseconds a Modal 2-vCPU
260
+ // container takes for it, `fullRate` units a millisecond at the median query: elimination's pairs and the float
261
+ // simplex's cells, the plain search's rows a node (kernel.ts's reading, whole at each node), the values reader.ts finds
262
+ // again, the live rows' copies it keeps and the read edges a change walks, the candidates scanned, the pivots' rows,
263
+ // the root's rows for units, the unfolding's rows a leaf, the goal's nodes where a query starts. work.n counts the rows
264
+ // the solver and each node read, which the incremental search reads whole no more: on 7,027 root queries of 20 ms or
265
+ // more (research/query/fit.py on runs/query/cal2: the 332 step goals, CHC sat and unsat, ITS, the false step goals and
266
+ // the real-world corpus), work.n did 28 to 377 units a ms (p10, p90), the model 120 to 401.
267
+ const model = [['fm', 2.33], ['fcells', 0.0123], ['plainRows', 7.93], ['values', 0.672], ['copies', 0.735], ['edges', 0.0435],
268
+ ['scan', 0.0765], ['pivotRows', 0.599], ['unitRows', 15.6], ['unfoldRows', 0.735], ['goalNodes', 0.492], ['translateRows', 7.93]];
269
+ export const fullRate = 250;
270
+ export const fullWork = () => { let n = 0; for (const [k, w] of model)
271
+ n += w * costs[k]; return n; };
272
+ // A goal's own budget where its caller gives none, outside a counted search: the cost model's work, groundRate units a
273
+ // millisecond of the budget (below fullRate: the queries of 10 s or more did 163 to 271 units a ms at their median, by
274
+ // group of the run above, so a long goal's budget takes about the wall time it had), so a goal left unknown is left so
275
+ // on any machine; a deadline it is grown within stays.
276
+ const groundRate = 180;
277
+ let workCap = Infinity;
278
+ const withWork = (cap, f) => { const outer = workCap; workCap = Math.min(outer, cap); try {
279
+ return f();
280
+ }
281
+ finally {
282
+ workCap = outer;
283
+ } };
284
+ // 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);
220
286
  // A budget's end, within the deadline (a translation's own bound, core/cyclic.ts's, kept by the export's GDP_CERT_MS).
221
287
  export const withinDeadline = (until) => Math.min(until, deadline);
222
288
  export function withDeadline(until, f) {
@@ -231,7 +297,13 @@ export function withDeadline(until, f) {
231
297
  }
232
298
  // `units: false`: the goal's own order, no units first (a caller after a model, not a proof: a run guided by the
233
299
  // prover's witnesses, say, whose models units would steer).
234
- export function grow(goal, path = new Map(), budget = { nodes: 0, until: clock() + Math.max(20_000, 1_000 * goal.hyps.length) }) {
300
+ export function grow(goal, path = new Map(), budget) {
301
+ if (!budget) {
302
+ const ms = Math.max(20_000, 1_000 * goal.hyps.length);
303
+ if (!rate)
304
+ return withWork(fullWork() + groundRate * ms, () => grow(goal, path, { nodes: 0 }));
305
+ budget = { nodes: 0, until: clock() + ms };
306
+ }
235
307
  if (deadline < (budget.until ?? Infinity))
236
308
  budget.until = deadline;
237
309
  if (budget.units === false && unitsNow) {
@@ -251,6 +323,59 @@ export function grow(goal, path = new Map(), budget = { nodes: 0, until: clock()
251
323
  console.error(`[grow] ${goal.name}: ${goal.hyps.length} hyps, ${budget.nodes} nodes, ${Math.round(performance.now() - t)} ms, ${'tree' in out ? 'proven' : `${out.stuck}${out.why ? ` (${out.why})` : ''}`}`);
252
324
  return out;
253
325
  }
326
+ // (a root goal grown before within `withTrees`: its tree again; a tree is the kernel's to check wherever it goes)
327
+ const key = treeCache.on && !path.size && !budget.nodes ? treeKey(goal) : undefined, had = key === undefined ? undefined : treeCache.trees.get(key);
328
+ if (had)
329
+ return { tree: had, nodes: 0 };
330
+ if (key !== undefined) {
331
+ const out = growKept(goal, path, budget);
332
+ if ('tree' in out)
333
+ treeCache.keep(key, out.tree);
334
+ return out;
335
+ }
336
+ return growKept(goal, path, budget);
337
+ }
338
+ // Trees of root goals kept by their hypotheses (and the search's modes) while `withTrees` runs: core/infer.ts proves each
339
+ // law of a set alone (proveLaw) and then the set as a whole (proveRule), the same goals twice. At most 2,000 trees, and
340
+ // goals of at most 4 MB written out.
341
+ const treeCache = { on: 0, trees: new Map(), keep(key, tree) { if (this.trees.size >= 2000)
342
+ this.trees.clear(); this.trees.set(key, tree); } };
343
+ const treeKey = (goal) => { const text = JSON.stringify(goal.hyps); return text.length > 4_000_000 ? undefined : `${cellProducts.on ? 1 : 0}${unitsNow ? 1 : 0}${text}`; };
344
+ // GDP_TREES=0: no tree kept (each goal grown every time it is asked).
345
+ const keepTrees = env.GDP_TREES !== '0';
346
+ export function withTrees(f) {
347
+ if (!keepTrees)
348
+ return f();
349
+ treeCache.on++;
350
+ try {
351
+ return f();
352
+ }
353
+ finally {
354
+ if (--treeCache.on === 0)
355
+ treeCache.trees.clear();
356
+ }
357
+ }
358
+ // Each root query as it ends, for research's logs (research/query/log.ts sets it; off otherwise): the kind, the goal,
359
+ // its wall time and counted work, its outcome, and how many queries it is inside.
360
+ export const queryHook = { depth: 0 };
361
+ export function logged(kind, goal, f) {
362
+ const t0 = performance.now(), w0 = work.n;
363
+ queryHook.depth++;
364
+ try {
365
+ const out = f();
366
+ queryHook.on?.({ kind, goal, ms: performance.now() - t0, work: work.n - w0, out, depth: queryHook.depth - 1 });
367
+ return out;
368
+ }
369
+ finally {
370
+ queryHook.depth--;
371
+ }
372
+ }
373
+ function growKept(goal, path, budget) {
374
+ if (queryHook.on && !path.size && !budget.nodes && !queryHook.depth)
375
+ return logged('grow', goal, () => growKept0(goal, path, budget));
376
+ return growKept0(goal, path, budget);
377
+ }
378
+ function growKept0(goal, path, budget) {
254
379
  if (!profile.on || path.size || budget.nodes)
255
380
  return growRoot(goal, path, budget);
256
381
  const t = performance.now(), s0 = profile.solves, m0 = profile.solveMs, r0 = profile.rowsMs, n0 = profile.nodes;
@@ -260,8 +385,7 @@ export function grow(goal, path = new Map(), budget = { nodes: 0, until: clock()
260
385
  }
261
386
  // 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
262
387
  // before it (GDP_QUICK_CAP; 64 where the CDCL search isn't tried, as before it): research/step's comparisons.
263
- const proveEnv = globalThis.process?.env ?? {};
264
- const cdclShare = Number(proveEnv.GDP_CDCL_SHARE ?? 0.75), quickCap = Number(proveEnv.GDP_QUICK_CAP ?? 16);
388
+ const cdclShare = Number(env.GDP_CDCL_SHARE ?? 0.75), quickCap = Number(env.GDP_QUICK_CAP ?? 16);
265
389
  function growRoot(goal, path, budget) {
266
390
  // Past a few cases, CDCL over the atoms (kernel/cdcl.ts), with most of the budget: a linear goal's refutation there
267
391
  // is a resolution of short clauses, which the tree search would find again in every case that reaches one. Unknown
@@ -286,9 +410,12 @@ function growRoot(goal, path, budget) {
286
410
  }
287
411
  if (root) {
288
412
  if (cdcl) {
289
- const now = clock(), end = withinDeadline(budget.until ?? Infinity);
290
- const out = growCdcl(goal, path, { nodes: 0, until: end === Infinity ? end : now + cdclShare * (end - now) });
291
- if ('tree' in out || out.stuck === 'sat')
413
+ const now = clock(), end = withinDeadline(budget.until ?? Infinity), w = fullWork();
414
+ const out = withWork(workCap === Infinity ? Infinity : w + cdclShare * (workCap - w), () => growCdcl(goal, path, { nodes: 0, until: end === Infinity ? end : now + cdclShare * (end - now) }));
415
+ // (with `realModels.on`, a model whose products don't multiply out is no model: the CDCL search reads a product as
416
+ // a name of its own, where the plain search below multiplies rows; a goal whose products only its cases bring,
417
+ // core/nonterm.ts's x' := x·y)
418
+ if ('tree' in out || (out.stuck === 'sat' && !(realModels.on && fakeProducts(out.witness))))
292
419
  return out;
293
420
  }
294
421
  const open = new Set(root.flatMap(r => Object.keys(r.lin)).filter(n => n.startsWith('⟦') && columnTerm(n)?.op === 'if')).size;
@@ -301,17 +428,21 @@ function growRoot(goal, path, budget) {
301
428
  }
302
429
  return growPlain(goal, path, budget);
303
430
  }
431
+ export const realModels = { on: false };
432
+ const fakeProducts = (w) => !!w && Object.keys(w).some(key => isMonomial(key) && (w[key] ?? 0) !== factorsOf(key).reduce((acc, f) => acc * (w[f] ?? 0), 1));
304
433
  function growPlain(goal, path, budget) {
305
434
  if (budget.cap !== undefined && budget.nodes >= budget.cap)
306
435
  return { stuck: 'unknown', path, why: 'cap' };
307
436
  if (profile.on)
308
437
  profile.nodes++;
309
- if (++budget.nodes > 200_000 || (budget.until !== undefined && clock() > budget.until))
438
+ if (++budget.nodes > 200_000 || late(budget.until ?? Infinity))
310
439
  return { stuck: 'unknown', path, why: outOfBudget(goal, budget.nodes > 200_000 ? 'nodes' : 'time', path.size) };
311
440
  // Rows that read a term column only once a cut has put one on the path; before, the rows a choice-free search uses
312
441
  // (what it saw before term columns), renumbered to the whole leaf's when a leaf is found.
313
442
  const full = timed(() => rowsAt(goal, path), ms => { profile.rowsMs += ms; });
314
443
  work.n += 1 + full.length;
444
+ costs.plainNodes++;
445
+ costs.plainRows += full.length;
315
446
  const columns = [...path.values()].some(a => Object.keys(a.lin).some(key => key.startsWith('⟦')));
316
447
  const idx = full.flatMap((r, i) => (columns || !Object.keys(r.lin).some(key => key.startsWith('⟦')) ? [i] : []));
317
448
  const rows = idx.map(i => full[i]), at = (i) => (i < rows.length ? idx[i] : full.length + i - rows.length);
@@ -718,12 +849,19 @@ export function widen(part, whole, tree, opaque = {}, pp = new Map(), wp = pp) {
718
849
  }
719
850
  // Whether each hypothesis reads only names the goal's conclusion (its last hypothesis) reads.
720
851
  const nearSeen = new WeakMap();
721
- const namesOf = (t) => (t === undefined ? [] : [...JSON.stringify(t).matchAll(/"(?:name|map)":"([^"]+)"/g)].map(m => m[1]));
852
+ // (the names a term reads, its shared parts walked once: a witness read at each of its uses is one object)
853
+ const namesOf = (t) => {
854
+ const out = new Set();
855
+ walkOnce(t, o => { costs.goalNodes++; for (const [key, v] of Object.entries(o))
856
+ if ((key === 'name' || key === 'map') && typeof v === 'string')
857
+ out.add(v); });
858
+ return out;
859
+ };
722
860
  export function nearOf(goal) {
723
861
  let out = nearSeen.get(goal);
724
862
  if (!out) {
725
863
  const theirs = new Set(namesOf(goal.hyps.at(-1)));
726
- nearSeen.set(goal, (out = goal.hyps.map(h => namesOf(h).every(n => theirs.has(n)))));
864
+ nearSeen.set(goal, (out = goal.hyps.map(h => [...namesOf(h)].every(n => theirs.has(n)))));
727
865
  }
728
866
  return out;
729
867
  }
@@ -731,7 +869,7 @@ export function nearOf(goal) {
731
869
  // `?f = 1` holds, `k < len` where it is given). Split at the top, its forced side refutes at once; split late, under
732
870
  // every other case, it is split again in each.
733
871
  // GDP_UNITS=0 leaves them in the goal's order (for comparing).
734
- const unitFirst = globalThis.process?.env?.GDP_UNITS !== '0';
872
+ const unitFirst = env.GDP_UNITS !== '0';
735
873
  let unitsNow = true;
736
874
  // The units growPlain splits first, where it does (kernel/cdcl.ts reads them too).
737
875
  export const unitAtoms = (goal) => (unitFirst && unitsNow ? unitsOf(goal) : []);
@@ -743,6 +881,7 @@ function unitsOf(goal) {
743
881
  // Forced by the root's rows without a solver: a row the atom is (or is the negation of), or the bounds the rows give
744
882
  // single variables (x <= c, x >= c) deciding it whichever way its variables go.
745
883
  const root = new Map(), rows = leafConstraints(goal, root), seen = new Set(), given = new Set();
884
+ costs.unitRows += rows.length;
746
885
  const lo = new Map(), hi = new Map();
747
886
  for (const r of rows) {
748
887
  given.add(canon(r.lin));
@@ -949,25 +1088,28 @@ function fractional(point, path) {
949
1088
  return undefined;
950
1089
  }
951
1090
  // The keys a proof assumes the every-key laws at: every key the step and the laws read, and the fresh key of the goal.
1091
+ // Each map read of a term (inE) or a condition (inC) given to f, outermost first, a quantified flag's body included.
1092
+ const eachRead = (f) => {
1093
+ const inE = (e) => { if (e.op === 'get') {
1094
+ f(e);
1095
+ inE(e.key);
1096
+ }
1097
+ else if (e.op === 'if')
1098
+ (inC(e.c), inE(e.then), inE(e.else));
1099
+ else if (e.op === 'mul')
1100
+ inE(e.a);
1101
+ else if ('a' in e)
1102
+ (inE(e.a), inE(e.b)); };
1103
+ const inC = (c) => (c.op === 'flag' ? undefined : c.op === 'all' ? inC(c.c) : c.op === 'not' ? inC(c.x) : c.op === 'and' || c.op === 'or' ? c.xs.forEach(inC) : (inE(c.a), inE(c.b)));
1104
+ return { inE, inC };
1105
+ };
952
1106
  // A key bound by a quantified flag or a write at every key isn't one: those reads are at every key already.
953
1107
  function readKeys(m, laws) {
954
1108
  const out = new Map();
955
1109
  const bound = new Set([...Object.values(m.step.flags ?? {}).flatMap(c => (c.op === 'all' ? boundOf(c) : [])), ...Object.values(m.step.maps ?? {}).flatMap(w => ('each' in w ? [w.each] : []))]);
956
1110
  const free = (e) => !JSON.stringify(e).match(/"name":"([^"]+)"/g)?.some(n => bound.has(n.slice(8, -1)));
957
- const inE = (e) => {
958
- if (e.op === 'get') {
959
- if (free(e.key))
960
- out.set(JSON.stringify(e.key), e.key);
961
- inE(e.key);
962
- }
963
- else if (e.op === 'if')
964
- (inC(e.c), inE(e.then), inE(e.else));
965
- else if (e.op === 'mul')
966
- inE(e.a);
967
- else if ('a' in e)
968
- (inE(e.a), inE(e.b));
969
- };
970
- const inC = (c) => (c.op === 'flag' ? undefined : c.op === 'all' ? inC(c.c) : c.op === 'not' ? inC(c.x) : c.op === 'and' || c.op === 'or' ? c.xs.forEach(inC) : (inE(c.a), inE(c.b)));
1111
+ const { inE, inC } = eachRead(e => { if (free(e.key))
1112
+ out.set(JSON.stringify(e.key), e.key); });
971
1113
  Object.values(m.step.state ?? {}).forEach(inE);
972
1114
  Object.values(m.step.flags ?? {}).forEach(inC);
973
1115
  for (const w of Object.values(m.step.maps ?? {})) {
@@ -995,20 +1137,7 @@ function keysInlined(m, keys) {
995
1137
  const shifts = (m) => Object.values(m.step.maps ?? {}).some(w => 'each' in w && !plainKey(w.value, w.each));
996
1138
  // The keys some goals read a map at.
997
1139
  function mapKeys(goals) {
998
- const out = new Map();
999
- const inE = (e) => {
1000
- if (e.op === 'get') {
1001
- out.set(JSON.stringify(e.key), e.key);
1002
- inE(e.key);
1003
- }
1004
- else if (e.op === 'if')
1005
- (inC(e.c), inE(e.then), inE(e.else));
1006
- else if (e.op === 'mul')
1007
- inE(e.a);
1008
- else if ('a' in e)
1009
- (inE(e.a), inE(e.b));
1010
- };
1011
- const inC = (c) => (c.op === 'flag' ? undefined : c.op === 'all' ? inC(c.c) : c.op === 'not' ? inC(c.x) : c.op === 'and' || c.op === 'or' ? c.xs.forEach(inC) : (inE(c.a), inE(c.b)));
1140
+ const out = new Map(), { inC } = eachRead(e => { out.set(JSON.stringify(e.key), e.key); });
1012
1141
  for (const g of goals)
1013
1142
  g.hyps.forEach(inC);
1014
1143
  return [...out.values()];
@@ -1053,21 +1182,8 @@ const related = (keys, focus, n) => {
1053
1182
  const tuples = (keys, n) => (n === 0 ? [] : n === 1 ? keys : keys.flatMap(a => { const rest = tuples(keys, n - 1); return Array.from({ length: rest.length / (n - 1) }, (_, t) => [a, ...rest.slice(t * (n - 1), (t + 1) * (n - 1))]).flat(); }));
1054
1183
  // The keys some goals read a function at.
1055
1184
  function fnKeys(m, goals) {
1056
- const fns = Object.keys(m.fns ?? {}), out = new Map();
1057
- const inE = (e) => {
1058
- if (e.op === 'get') {
1059
- if (fns.includes(e.map))
1060
- out.set(JSON.stringify(e.key), e.key);
1061
- inE(e.key);
1062
- }
1063
- else if (e.op === 'if')
1064
- (inC(e.c), inE(e.then), inE(e.else));
1065
- else if (e.op === 'mul')
1066
- inE(e.a);
1067
- else if ('a' in e)
1068
- (inE(e.a), inE(e.b));
1069
- };
1070
- const inC = (c) => (c.op === 'flag' ? undefined : c.op === 'all' ? inC(c.c) : c.op === 'not' ? inC(c.x) : c.op === 'and' || c.op === 'or' ? c.xs.forEach(inC) : (inE(c.a), inE(c.b)));
1185
+ const fns = Object.keys(m.fns ?? {}), out = new Map(), { inC } = eachRead(e => { if (fns.includes(e.map))
1186
+ out.set(JSON.stringify(e.key), e.key); });
1071
1187
  for (const g of goals)
1072
1188
  g.hyps.forEach(inC);
1073
1189
  return [...out.values()];
@@ -1194,24 +1310,13 @@ function instancesFor(m, laws, build, opts = {}) {
1194
1310
  // Untrusted: fewer instances still make a checked proof, and where they don't prove a goal the full set is tried.
1195
1311
  const triggers = (body, key) => {
1196
1312
  const out = [], mentions = (e) => JSON.stringify(e).includes(`"name":${JSON.stringify(key)}`);
1197
- const inE = (e) => { if (e.op === 'get') {
1198
- if (mentions(e.key))
1199
- out.push({ map: e.map, at: e.key });
1200
- inE(e.key);
1201
- }
1202
- else if (e.op === 'if')
1203
- (inC(e.c), inE(e.then), inE(e.else));
1204
- else if (e.op === 'mul')
1205
- inE(e.a);
1206
- else if ('a' in e)
1207
- (inE(e.a), inE(e.b)); };
1208
- const inC = (c) => (c.op === 'flag' ? undefined : c.op === 'all' ? inC(c.c) : c.op === 'not' ? inC(c.x) : c.op === 'and' || c.op === 'or' ? c.xs.forEach(inC) : (inE(c.a), inE(c.b)));
1209
- inC(body);
1313
+ eachRead(e => { if (mentions(e.key))
1314
+ out.push({ map: e.map, at: e.key }); }).inC(body);
1210
1315
  return out;
1211
1316
  };
1212
1317
  const substKey = (e, key, by) => JSON.parse(JSON.stringify(e).replaceAll(`{"op":"var","name":${JSON.stringify(key)}}`, JSON.stringify(by)));
1213
1318
  // GDP_TRIGGER=0 keeps every instance (for comparing).
1214
- const triggerOn = globalThis.process?.env?.GDP_TRIGGER !== '0';
1319
+ const triggerOn = env.GDP_TRIGGER !== '0';
1215
1320
  function triggered(m, laws, inst, build, focus = []) {
1216
1321
  if (!triggerOn)
1217
1322
  return inst;
@@ -1235,17 +1340,7 @@ function triggered(m, laws, inst, build, focus = []) {
1235
1340
  const out = Object.fromEntries(Object.entries(inst).map(([n, ks]) => [n, bodies.has(n) ? tuplesOf(n, ks).filter(kept).flat() : ks]));
1236
1341
  for (let round = 0; round < 8; round++) {
1237
1342
  const reads = new Set();
1238
- const inE = (e) => { if (e.op === 'get') {
1239
- reads.add(`${e.map}|${JSON.stringify(e.key)}`);
1240
- inE(e.key);
1241
- }
1242
- else if (e.op === 'if')
1243
- (inC(e.c), inE(e.then), inE(e.else));
1244
- else if (e.op === 'mul')
1245
- inE(e.a);
1246
- else if ('a' in e)
1247
- (inE(e.a), inE(e.b)); };
1248
- const inC = (c) => (c.op === 'flag' ? undefined : c.op === 'all' ? inC(c.c) : c.op === 'not' ? inC(c.x) : c.op === 'and' || c.op === 'or' ? c.xs.forEach(inC) : (inE(c.a), inE(c.b)));
1343
+ const { inC } = eachRead(e => { reads.add(`${e.map}|${JSON.stringify(e.key)}`); });
1249
1344
  for (const g of build(out))
1250
1345
  g.hyps.forEach(inC);
1251
1346
  let grew = false;
@@ -1269,8 +1364,19 @@ function triggered(m, laws, inst, build, focus = []) {
1269
1364
  // found that its leaves refute with, the proof grown again with those alone. The checked goal is then built from far
1270
1365
  // fewer hypotheses (a law about pairs of items with 900 instance hypotheses and 30 leaves using a few of them, say).
1271
1366
  export const minimal = { on: false };
1367
+ export const leafRowsOf = new WeakMap();
1272
1368
  // The hypotheses a tree's leaves read: each leaf's input rows, and the rows its products multiply.
1273
1369
  export function usedHyps(goal, tree, path = new Map(), out = new Set()) {
1370
+ const known = 'leaf' in tree && !tree.products && !tree.squares ? leafRowsOf.get(tree) : undefined;
1371
+ if (known && 'leaf' in tree) {
1372
+ for (const st of tree.leaf)
1373
+ if (st.kind === 'input') {
1374
+ const s = known.at.get(st.index)?.src;
1375
+ if (typeof s === 'number' && s >= 0)
1376
+ out.add(s);
1377
+ }
1378
+ return out;
1379
+ }
1274
1380
  if ('leaf' in tree) {
1275
1381
  const rows = rowsAt(goal, path), n = rows.length, sq = tree.squares?.length ?? 0;
1276
1382
  const mark = (i) => {
@@ -1518,7 +1624,7 @@ function proveThinned(m, laws, instances) {
1518
1624
  if (!('tree' in out) && laws.some(l => instances[l.name] !== fulls[l.name]))
1519
1625
  return proveWith(m, laws, fulls);
1520
1626
  if (!('tree' in out))
1521
- return { proven: false, nodes, leaves, failed: { goal: goal.name, stuck: out.stuck, ...(out.witness ? { witness: out.witness } : {}), ...(out.why ? { why: out.why } : {}) }, checked: false };
1627
+ return stuckAt(goal, out, nodes, leaves);
1522
1628
  trees[goal.name] = out.tree;
1523
1629
  nodes += out.nodes;
1524
1630
  leaves += countLeaves(out.tree);
@@ -1526,6 +1632,8 @@ function proveThinned(m, laws, instances) {
1526
1632
  const proof = { instances, trees };
1527
1633
  return { proven: true, nodes, leaves, checked: !usualCheck.on || checkLaws(m, laws, proof), proof };
1528
1634
  }
1635
+ // A goal left unproven, the search's report so far.
1636
+ const stuckAt = (goal, out, nodes, leaves) => ({ proven: false, nodes, leaves, failed: { goal: goal.name, stuck: out.stuck, ...(out.witness ? { witness: out.witness } : {}), ...(out.why ? { why: out.why } : {}) }, checked: false });
1529
1637
  // Every goal of the laws with these instances.
1530
1638
  function proveWith(m, laws, instances) {
1531
1639
  const trees = {};
@@ -1533,7 +1641,7 @@ function proveWith(m, laws, instances) {
1533
1641
  for (const goal of obligations(m, laws, instances)) {
1534
1642
  const out = grow(goal);
1535
1643
  if (!('tree' in out))
1536
- return { proven: false, nodes, leaves, failed: { goal: goal.name, stuck: out.stuck, ...(out.witness ? { witness: out.witness } : {}), ...(out.why ? { why: out.why } : {}) }, checked: false };
1644
+ return stuckAt(goal, out, nodes, leaves);
1537
1645
  trees[goal.name] = out.tree;
1538
1646
  nodes += out.nodes;
1539
1647
  leaves += countLeaves(out.tree);
@@ -1598,7 +1706,7 @@ function proveStepLawsAsGiven(m, laws, stepLaws, base) {
1598
1706
  }
1599
1707
  }
1600
1708
  if (!('tree' in out))
1601
- return { proven: false, nodes, leaves, failed: { goal: goal.name, stuck: out.stuck, ...(out.witness ? { witness: out.witness } : {}), ...(out.why ? { why: out.why } : {}) }, checked: false };
1709
+ return stuckAt(goal, out, nodes, leaves);
1602
1710
  if (minimal.on) {
1603
1711
  const had = perStep[sl.name] ?? instances, built = stepLawObligations(m, laws, had, sl).find(g => g.name === goal.name);
1604
1712
  if (built) {
@@ -1680,7 +1788,7 @@ export function proveProgress(m, laws, p) {
1680
1788
  for (const goal of progressObligations(m, ls, instances, p)) {
1681
1789
  const out = grow(goal);
1682
1790
  if (!('tree' in out))
1683
- return { proven: false, nodes, leaves, failed: { goal: goal.name, stuck: out.stuck, ...(out.witness ? { witness: out.witness } : {}), ...(out.why ? { why: out.why } : {}) }, checked: false };
1791
+ return stuckAt(goal, out, nodes, leaves);
1684
1792
  trees[goal.name] = out.tree;
1685
1793
  nodes += out.nodes;
1686
1794
  leaves += countLeaves(out.tree);
@@ -42,6 +42,8 @@ export type Row = {
42
42
  w: W;
43
43
  label: '';
44
44
  };
45
+ export declare function times(a: Lin, b: Lin): Lin | undefined;
46
+ export declare const keepClean: boolean;
45
47
  export declare class Reader {
46
48
  readonly goal: Goal;
47
49
  readonly trail: Trail;
@@ -56,17 +58,17 @@ export declare class Reader {
56
58
  begin(): void;
57
59
  private up;
58
60
  private byAtom;
61
+ private found;
62
+ private lastUp;
59
63
  private clean;
60
- private frame;
61
64
  private factKeys;
62
65
  private openKeys;
63
- private lastUp;
66
+ private finding;
64
67
  private read;
65
68
  private readAtom;
66
69
  private within;
67
70
  touch(name: string): void;
68
71
  private ok;
69
- private kept;
70
72
  private units;
71
73
  private unit;
72
74
  dec(lin: Lin): R & {
@@ -79,11 +81,79 @@ export declare class Reader {
79
81
  private truth0;
80
82
  private factsOf;
81
83
  facts(i: number): FV;
84
+ private factsFin;
85
+ private partsOf;
86
+ private ps;
87
+ private parts;
88
+ private part;
82
89
  termRows(name: string): Row[];
83
90
  private decided;
84
91
  rows(): Row[];
85
- leafRows(): Row[];
86
- open(i: number, out: Lin[]): void;
92
+ private forms;
93
+ private formIds;
94
+ private nameIds;
95
+ private nameText;
96
+ private nameKind;
97
+ private formSeen;
98
+ private formAt;
99
+ private nameSeen;
100
+ private termSeen;
101
+ private gen;
102
+ form(lin: Lin): {
103
+ id: number;
104
+ names: number[];
105
+ };
106
+ readsColumn(lin: Lin): boolean;
107
+ private trailRows;
108
+ private trailStamps;
109
+ private pairs;
110
+ leafRows(src?: (number | [string, string])[]): Row[];
111
+ live: Row[];
112
+ entered: number[];
113
+ left: number[];
114
+ private syncing;
115
+ private dirty;
116
+ private slot;
117
+ private copies;
118
+ private c12;
119
+ private cT;
120
+ private inTrail;
121
+ private inParts;
122
+ private hypsIn;
123
+ private src;
124
+ hypsOf(rows: Row[]): number[];
125
+ private inSeg;
126
+ private cached;
127
+ private termKeys;
128
+ private pairKeys;
129
+ private liveCells;
130
+ private inNat;
131
+ private syncN;
132
+ private markN;
133
+ private wasLive;
134
+ private changed;
135
+ slotOf(id: number): number;
136
+ hasCells(): boolean;
137
+ private cellsOn;
138
+ readonly cells: Map<string, Set<string>>;
139
+ cellsChanged: number;
140
+ sync(): void;
141
+ private trailRow;
142
+ private segRows;
143
+ private pair;
144
+ private mark;
145
+ private addCopy;
146
+ private removeCopy;
147
+ private countUp;
148
+ private countDown;
149
+ private nameOn;
150
+ private nameOff;
151
+ private segOn;
152
+ private segOff;
153
+ private pairKey;
154
+ private cellOn;
155
+ private cellOff;
156
+ openList(i: number): Lin[];
87
157
  private openE;
88
158
  private openC;
89
159
  private openH;