gdp-wired 0.21.0 → 0.22.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.
@@ -0,0 +1,543 @@
1
+ // Untrusted, like prove.ts: a second search for a goal's tree, CDCL over the goal's atoms with the kernel's reading as
2
+ // the theory. Its refutation is a resolution DAG of refuted cases, unfolded into a kernel tree at the end, so the
3
+ // certificate is the kernel's as it is (kernel.ts's check); nothing here is trusted.
4
+ //
5
+ // The trail is a path (kernel.ts's Path). After unit propagation over the learned clauses (and bound propagation: an
6
+ // open atom its variables' single-variable bounds decide), the rows the kernel reads at the trail (reader.ts, which
7
+ // reads them again only where the trail changed what they read) are given to an incremental simplex (simplex.ts),
8
+ // and an infeasible one's rows are refuted exactly (core/solver.ts). Refuted, the refutation's core is the decisions
9
+ // the rows it reads need (reader.ts's reasons: a conjunction false needs one false part, a disjunction's last open part
10
+ // needs the others false, a term's value the decisions its choices took), and the leaf is that core with the
11
+ // derivation: a clause of decisions that can't all hold. Conflict analysis resolves the leaf with the clauses that propagated its latest literals down to the
12
+ // first unique implication point, learns the result, jumps back to where it is unit and asserts the flipped literal.
13
+ // Not refuted, the next decision is the open atom (growPlain's candidates at the trail) of highest activity (VSIDS),
14
+ // its last value first (phase saving); Luby restarts. A conflict at level 0 resolves to the empty clause.
15
+ //
16
+ // The DAG unfolds into a tree: a resolution on an atom the path leaves open is a split on it, its two parents the two
17
+ // sides; one the path decides follows the parent that agrees; a leaf's derivation is found again among the rows at
18
+ // its tree path (a longer path than its clause's), and where a row isn't there, the rows at the tree path are solved
19
+ // afresh.
20
+ import { refuteFast, solve, work } from "../core/solver.js";
21
+ import { checkRefutation } from "../core/check.js";
22
+ import { atomOf, canon, canonFlip, isCell, isMonomial, leafConstraints } from "./kernel.js";
23
+ import { clock, nearOf, openAt, openCells, rowsAt, unitAtoms } from "./prove.js";
24
+ import { Reader, namesOf } from "./reader.js";
25
+ import { Simplex } from "./simplex.js";
26
+ // A derivation's own inputs: the rows it reads, in order, and the steps renumbered to them.
27
+ function localize(rows, steps) {
28
+ const inputs = [], at = new Map();
29
+ const out = steps.map(st => {
30
+ if (st.kind !== 'input')
31
+ return st;
32
+ let j = at.get(st.index);
33
+ if (j === undefined) {
34
+ j = inputs.length;
35
+ at.set(st.index, j);
36
+ inputs.push(rows[st.index].lin);
37
+ }
38
+ return { ...st, index: j };
39
+ });
40
+ return { inputs, steps: out };
41
+ }
42
+ // GDP_CDCL_LP=0: each node solved by elimination alone (no simplex); GDP_CDCL_FILL (8): the simplex's tableau begun
43
+ // again past this many entries a row the node reads (research/step's comparisons).
44
+ const env = globalThis.process?.env ?? {};
45
+ const lpFill = Number(env.GDP_CDCL_FILL ?? 8), useLp = env.GDP_CDCL_LP !== '0', verify = env.GDP_CDCL_VERIFY === '1';
46
+ // Counters research/step reads (times only while `on`).
47
+ export const cdclStats = { on: false, runs: 0, proven: 0, conflicts: 0, decisions: 0, solveMs: 0, rowsMs: 0, coreMs: 0, unfoldMs: 0, leaves: 0, resolved: 0, coreSize: 0, pathSize: 0, lpMisses: 0, resolved2: 0, unfoldWhy: '', orderMs: 0, boundMs: 0, openMisses: 0, lpMs: 0, lpUnknown: 0, fmCalls: 0, pivots: 0, lpRebuilds: 0, lpRows: 0, lpNnz: 0, lpVars: 0, lpLoad: 0, nodes: 0, boundRounds: 0 };
48
+ export function growCdcl(goal, root, budget, opts = {}) {
49
+ const until = budget.until ?? Infinity, st = cdclStats, timing = st.on;
50
+ const t = (f, add) => { if (!timing)
51
+ return f(); const t0 = performance.now(); try {
52
+ return f();
53
+ }
54
+ finally {
55
+ add(performance.now() - t0);
56
+ } };
57
+ st.runs++;
58
+ const vars = new Map(), trail = [], levels = [];
59
+ let sx = useLp ? new Simplex() : undefined;
60
+ const nodes = [], clauses = [], occ = new Map();
61
+ let inc = 1;
62
+ // An atom as a variable: the stored form is the one whose canonical text is the variable's name (the smaller).
63
+ const ensure = (lin) => {
64
+ const a = canon(lin), b = canonFlip(lin), flip = b < a, key = flip ? b : a;
65
+ if (!vars.has(key)) {
66
+ const stored = flip ? atomOf(lin, false).lin : lin;
67
+ vars.set(key, { lin: stored, terms: Object.entries(stored).filter(([x0]) => x0 !== '1'), level: -1, at: -1, act: 0, phase: !flip });
68
+ }
69
+ return key;
70
+ };
71
+ // The root's own decisions are level 0, with no reason: they stay in every clause (the tree starts below them).
72
+ const rootNames = new Set(), stamps = [];
73
+ let stampN = 0;
74
+ for (const [key, a] of root) {
75
+ const name = ensure(a.lin), x = vars.get(name), val = name === key ? a.holds : !a.holds;
76
+ x.val = val;
77
+ x.level = 0;
78
+ x.at = trail.length;
79
+ stamps[x.at] = ++stampN;
80
+ trail.push(name);
81
+ rootNames.add(name);
82
+ }
83
+ const reader = new Reader(goal, {
84
+ get: name => vars.get(name), stamp: at => stamps[at], size: () => trail.length,
85
+ lin: at => { const name = trail[at], x = vars.get(name); return { name, lin: x.lin, holds: x.val }; },
86
+ });
87
+ const last = goal.hyps.length - 1, near = nearOf(goal);
88
+ const decidedLin = (lin) => vars.get(canon(lin))?.val !== undefined || vars.get(canonFlip(lin))?.val !== undefined;
89
+ const fixed = trail.length;
90
+ const level = () => levels.length;
91
+ const pathOf = () => new Map(trail.map(name => { const x = vars.get(name); return [name, { lin: x.lin, holds: x.val }]; }));
92
+ const assign = (name, val, reason) => {
93
+ const x = vars.get(name);
94
+ x.val = val;
95
+ x.level = level();
96
+ x.at = trail.length;
97
+ x.phase = val;
98
+ stamps[x.at] = ++stampN;
99
+ if (reason === undefined)
100
+ delete x.reason;
101
+ else
102
+ x.reason = reason;
103
+ trail.push(name);
104
+ };
105
+ const undoTo = (l) => {
106
+ const keep = levels[l] ?? trail.length;
107
+ while (trail.length > Math.max(keep, fixed)) {
108
+ const x = vars.get(trail.pop());
109
+ delete x.val;
110
+ x.level = -1;
111
+ delete x.reason;
112
+ }
113
+ levels.length = l;
114
+ };
115
+ const addClause = (lits, node) => {
116
+ clauses.push({ lits, node });
117
+ const i = clauses.length - 1;
118
+ for (const [name, pos] of lits) {
119
+ const key = `${name}=${pos}`;
120
+ let xs = occ.get(key);
121
+ if (!xs)
122
+ occ.set(key, (xs = []));
123
+ xs.push(i);
124
+ }
125
+ return i;
126
+ };
127
+ let qhead = 0;
128
+ // Unit propagation: a clause whose literals all hold is a conflict (its index); all but one, the last is flipped.
129
+ const propagate = () => {
130
+ while (qhead < trail.length) {
131
+ const name = trail[qhead++], x = vars.get(name);
132
+ for (const ci of occ.get(`${name}=${x.val}`) ?? []) {
133
+ const c = clauses[ci];
134
+ let open, nOpen = 0, dead = false;
135
+ for (const [w, p] of c.lits) {
136
+ const y = vars.get(w);
137
+ if (y.val === undefined) {
138
+ nOpen++;
139
+ open = w;
140
+ if (nOpen > 1)
141
+ break;
142
+ }
143
+ else if (y.val !== p) {
144
+ dead = true;
145
+ break;
146
+ }
147
+ }
148
+ if (dead || nOpen > 1)
149
+ continue;
150
+ if (nOpen === 0)
151
+ return ci;
152
+ assign(open, !c.lits.get(open), ci);
153
+ }
154
+ }
155
+ return undefined;
156
+ };
157
+ const bump = (lits) => {
158
+ for (const name of lits.keys()) {
159
+ const x = vars.get(name);
160
+ x.act += inc;
161
+ if (x.act > 1e100) {
162
+ for (const y of vars.values())
163
+ y.act *= 1e-100;
164
+ inc *= 1e-100;
165
+ }
166
+ }
167
+ inc /= 0.95;
168
+ };
169
+ const resolveOn = (c, name) => {
170
+ const x = vars.get(name), r = clauses[x.reason];
171
+ if (r.node < 0)
172
+ materialize(x.reason);
173
+ const lits = new Map(c.lits);
174
+ lits.delete(name);
175
+ for (const [w, p] of r.lits)
176
+ if (w !== name)
177
+ lits.set(w, p);
178
+ nodes.push({ res: c.lits.get(name) ? [c.node, r.node] : [r.node, c.node], on: x.lin });
179
+ st.resolved++;
180
+ return { lits, node: nodes.length - 1 };
181
+ };
182
+ // A leaf: the decisions of a reason (the root's are every leaf's, below which the tree starts: not literals of its
183
+ // clause) and a derivation over the rows it reads.
184
+ const leafNode = (w, inputs, steps, extra) => {
185
+ nodes.push({ inputs, steps });
186
+ st.leaves++;
187
+ const lits = new Map();
188
+ for (const name of w)
189
+ if (!rootNames.has(name))
190
+ lits.set(name, vars.get(name).val);
191
+ if (extra)
192
+ lits.set(extra[0], extra[1]);
193
+ st.coreSize += lits.size;
194
+ return { lits, node: nodes.length - 1 };
195
+ };
196
+ // A theory conflict at the trail: the leaf at its core, the reasons of the rows its derivation reads.
197
+ const leafAt = (rows, steps) => t(() => {
198
+ const w = new Set();
199
+ for (const s of steps)
200
+ if (s.kind === 'input')
201
+ for (const name of rows[s.index].w)
202
+ w.add(name);
203
+ st.pathSize += trail.length - fixed;
204
+ const local = localize(rows, steps);
205
+ return leafNode(w, local.inputs, local.steps);
206
+ }, ms => { st.coreMs += ms; });
207
+ // Bound propagation's reasons, made when conflict analysis reads them: the atom's bounds (single-variable rows at the
208
+ // trail then) and its other side refute each other, a leaf at the bounds' reasons with that side decided.
209
+ const pending = new Map();
210
+ const materialize = (ci) => t(() => {
211
+ const b = pending.get(ci), x = vars.get(b.name), c = clauses[ci];
212
+ pending.delete(ci);
213
+ const local = [...b.used.map(lin => ({ lin, label: '' })), { lin: atomOf(x.lin, !b.val).lin, label: '' }];
214
+ const s = solve(local);
215
+ if (s.kind !== 'refuted')
216
+ throw new Error('a bound propagation its bounds do not refute');
217
+ const loc = localize(local, s.steps), made = leafNode(b.w, loc.inputs, loc.steps, [b.name, !b.val]);
218
+ c.lits = made.lits;
219
+ c.node = made.node;
220
+ }, ms => { st.coreMs += ms; });
221
+ const luby = (i) => { let n = 1; while ((1 << n) - 1 < i + 1)
222
+ n++; return (1 << n) - 1 === i + 1 ? 1 << (n - 1) : luby(i + 1 - (1 << (n - 1))); };
223
+ let restartAt = 32, nRestart = 0, sinceRestart = 0;
224
+ const stuck = (kind, why, extra = {}) => ({ stuck: kind, path: pathOf(), why, ...extra });
225
+ for (;;) {
226
+ if (++budget.nodes > 200_000 || clock() > until)
227
+ return stuck('unknown', budget.nodes > 200_000 ? 'nodes' : 'time');
228
+ let conflict;
229
+ const ci = propagate();
230
+ if (ci !== undefined)
231
+ conflict = clauses[ci];
232
+ else {
233
+ reader.begin();
234
+ st.nodes++;
235
+ const rowsR = t(() => reader.rows(), ms => { st.rowsMs += ms; });
236
+ const full = rowsR;
237
+ if (verify) {
238
+ const mine = new Set(rowsR.map(r => canon(r.lin))), theirs = new Set(leafConstraints(goal, pathOf()).map(r => canon(r.lin)));
239
+ if (mine.size !== theirs.size || [...mine].some(x => !theirs.has(x)))
240
+ throw new Error(`reader.ts's rows differ from kernel.ts's at a node of ${goal.name}`);
241
+ }
242
+ work.n += 1 + full.length;
243
+ // (the elimination below reads term columns' rows only once the trail has an atom about one, as growPlain does)
244
+ let columns = false;
245
+ for (let i = 0; i < trail.length && !columns; i++)
246
+ for (const key in vars.get(trail[i]).lin)
247
+ if (key.startsWith('⟦')) {
248
+ columns = true;
249
+ break;
250
+ }
251
+ const idx = columns ? undefined : full.flatMap((r, i) => (namesOf(r.lin).some(key => key.startsWith('⟦')) ? [] : [i]));
252
+ const rows = idx ? idx.map(i => full[i]) : full, at = (i) => (!idx ? i : i < rows.length ? idx[i] : full.length + i - rows.length);
253
+ // The candidates, in growPlain's order: the units, the conclusion's open atoms, the hypotheses' near it, the
254
+ // rest, pairs of cells.
255
+ const cands = t(() => {
256
+ const out = [...unitAtoms(goal)];
257
+ if (last >= 0)
258
+ reader.open(last, out);
259
+ for (let i = 0; i < last; i++)
260
+ if (near[i])
261
+ reader.open(i, out);
262
+ for (let i = 0; i < last; i++)
263
+ if (!near[i])
264
+ reader.open(i, out);
265
+ if (rows.some(r => namesOf(r.lin).some(isCell)))
266
+ for (const x of openCells(rows, pathOf()))
267
+ out.push(x);
268
+ const seen = new Set();
269
+ return out.filter(lin => !seen.has(lin) && (seen.add(lin), namesOf(lin).length > 0) && !decidedLin(lin));
270
+ }, ms => { st.orderMs += ms; });
271
+ const open = cands.length > 0;
272
+ // Bound propagation: an open atom its variables' bounds (the single-variable rows) decide.
273
+ const tb = timing ? performance.now() : 0;
274
+ if (open) {
275
+ const lo = new Map(), hi = new Map();
276
+ full.forEach((r, i) => {
277
+ const ks = namesOf(r.lin);
278
+ if (ks.length !== 1)
279
+ return;
280
+ const x0 = ks[0], c = r.lin[x0], k0 = r.lin['1'] ?? 0;
281
+ if (c > 0) {
282
+ const b = Math.floor(-k0 / c);
283
+ if (b < (hi.get(x0)?.[0] ?? Infinity))
284
+ hi.set(x0, [b, i]);
285
+ }
286
+ else if (c < 0) {
287
+ const b = Math.ceil(k0 / -c);
288
+ if (b > (lo.get(x0)?.[0] ?? -Infinity))
289
+ lo.set(x0, [b, i]);
290
+ }
291
+ });
292
+ let forced = 0;
293
+ for (const lin of cands) {
294
+ const name = ensure(lin), x = vars.get(name);
295
+ if (x.val !== undefined || namesOf(x.lin).some(key => key.startsWith('⟦')))
296
+ continue; // (a term column's rows read differently once its choice is decided)
297
+ const side = (val) => {
298
+ let sum = x.lin['1'] ?? 0;
299
+ const used = [];
300
+ for (const [x0, c] of x.terms) {
301
+ const b = (c > 0) === val ? hi.get(x0) : lo.get(x0);
302
+ if (!b)
303
+ return undefined;
304
+ sum += c * b[0];
305
+ used.push(b[1]);
306
+ }
307
+ return (val ? sum <= 0 : sum >= 1) ? used : undefined;
308
+ };
309
+ for (const val of [true, false]) {
310
+ const used = side(val);
311
+ if (!used)
312
+ continue;
313
+ const w = new Set();
314
+ for (const i of used)
315
+ for (const n of rowsR[i].w)
316
+ w.add(n);
317
+ clauses.push({ lits: new Map([[name, !val]]), node: -1 });
318
+ pending.set(clauses.length - 1, { w, used: used.map(i => full[i].lin), name, val });
319
+ assign(name, val, clauses.length - 1);
320
+ forced++;
321
+ break;
322
+ }
323
+ }
324
+ if (timing)
325
+ st.boundMs += performance.now() - tb;
326
+ if (forced) {
327
+ st.boundRounds++;
328
+ continue;
329
+ }
330
+ }
331
+ let steps;
332
+ let verdict;
333
+ t(() => {
334
+ // The simplex first (warm from the node before): a conflict's rows, refuted exactly, are the leaf. With a case
335
+ // still open, a node it finds feasible is split; with none, the exact elimination below decides it (integers).
336
+ if (sx) {
337
+ const t0 = timing ? performance.now() : 0;
338
+ // (a tableau that has gathered many more forms than a node reads is begun again: every pivot updates them all)
339
+ if (sx.size > 4 * full.length + 500 || sx.nnz > lpFill * full.length) {
340
+ sx = new Simplex();
341
+ st.lpRebuilds++;
342
+ }
343
+ const p0 = sx.pivots;
344
+ let lp = sx.load(full);
345
+ if (lp.kind === 'sat')
346
+ lp = sx.check();
347
+ if (timing) {
348
+ st.lpMs += performance.now() - t0;
349
+ st.pivots += sx.pivots - p0;
350
+ st.lpRows = sx.size;
351
+ st.lpNnz = sx.nnz;
352
+ st.lpVars = sx.vars;
353
+ st.lpLoad = full.length;
354
+ if (lp.kind === 'unknown')
355
+ st.lpUnknown++;
356
+ }
357
+ if (lp.kind === 'conflict') {
358
+ const support = lp.rows.sort((x, y) => x - y), out = solve(support.map(i => full[i]));
359
+ if (out.kind === 'refuted')
360
+ steps = out.steps.map(s => (s.kind === 'input' ? { ...s, index: support[s.index] } : s));
361
+ else
362
+ st.lpMisses++;
363
+ }
364
+ if (steps || (open && lp.kind === 'sat'))
365
+ return;
366
+ }
367
+ st.fmCalls++;
368
+ if (open && rows.length > 60) {
369
+ const fast = refuteFast(rows);
370
+ if (fast?.kind === 'refuted')
371
+ steps = fast.steps.map(s => (s.kind === 'input' ? { ...s, index: at(s.index) } : s));
372
+ }
373
+ if (!steps) {
374
+ verdict = open && rows.length > 60 ? solve(rows, 2 * rows.length) : solve(rows);
375
+ if (verdict.kind === 'refuted')
376
+ steps = verdict.steps.map(s => (s.kind === 'input' ? { ...s, index: at(s.index) } : s));
377
+ }
378
+ if (!steps && open && !columns && full.length > rows.length) {
379
+ const fast = refuteFast(full);
380
+ if (fast?.kind === 'refuted')
381
+ steps = fast.steps;
382
+ }
383
+ }, ms => { st.solveMs += ms; });
384
+ if (steps)
385
+ conflict = leafAt(rowsR, steps);
386
+ else {
387
+ // A decision: the open atom of highest activity (the first candidate among equals).
388
+ let pick, best = -1;
389
+ for (const lin of cands) {
390
+ const name = ensure(lin), x = vars.get(name);
391
+ if (x.val === undefined && x.act > best) {
392
+ best = x.act;
393
+ pick = name;
394
+ }
395
+ }
396
+ if (!pick && verdict?.kind === 'unknown') {
397
+ for (const [x0, value] of Object.entries(verdict.point ?? {})) {
398
+ if (Math.abs(value - Math.round(value)) < 1e-9 || isMonomial(x0))
399
+ continue;
400
+ const c = Math.floor(value), lin = c === 0 ? { [x0]: 1 } : { [x0]: 1, 1: -c };
401
+ if (!decidedLin(lin)) {
402
+ pick = ensure(lin);
403
+ break;
404
+ }
405
+ }
406
+ }
407
+ // Nothing open by this reading: the kernel's own reading of the trail (prove.ts's) has the last word.
408
+ if (!pick) {
409
+ const p = pathOf(), more = openAt(goal, p, rowsAt(goal, p)).find(lin => Object.keys(lin).some(key => key !== '1') && !decidedLin(lin));
410
+ if (more) {
411
+ st.openMisses++;
412
+ pick = ensure(more);
413
+ }
414
+ }
415
+ if (!pick)
416
+ return verdict?.kind === 'sat' ? stuck('sat', 'a model', { witness: verdict.witness }) : stuck('unknown', 'no split');
417
+ levels.push(trail.length);
418
+ st.decisions++;
419
+ assign(pick, vars.get(pick).phase);
420
+ continue;
421
+ }
422
+ }
423
+ // Conflict analysis.
424
+ st.conflicts++;
425
+ sinceRestart++;
426
+ let c = conflict;
427
+ for (;;) {
428
+ if (!c.lits.size) {
429
+ const tree = t(() => unfold(goal, nodes, c.node, root, opts.maxLeaves ?? 20_000, until), ms => { st.unfoldMs += ms; });
430
+ if (!tree)
431
+ return stuck('unknown', 'unfold');
432
+ st.proven++;
433
+ return { tree, nodes: budget.nodes };
434
+ }
435
+ const top = Math.max(...[...c.lits.keys()].map(name => vars.get(name).level));
436
+ if (top < level()) {
437
+ undoTo(top);
438
+ qhead = trail.length;
439
+ }
440
+ const here = [...c.lits.keys()].filter(name => vars.get(name).level === top);
441
+ if (top === 0) {
442
+ c = resolveOn(c, here.reduce((a, b) => (vars.get(a).at > vars.get(b).at ? a : b)));
443
+ continue;
444
+ }
445
+ if (here.length === 1)
446
+ break;
447
+ const latest = here.reduce((a, b) => (vars.get(a).at > vars.get(b).at ? a : b));
448
+ if (vars.get(latest).reason === undefined)
449
+ break;
450
+ c = resolveOn(c, latest);
451
+ }
452
+ const top = Math.max(...[...c.lits.keys()].map(name => vars.get(name).level));
453
+ const here = [...c.lits.keys()].filter(name => vars.get(name).level === top);
454
+ bump(c.lits);
455
+ const learned = addClause(c.lits, c.node);
456
+ if (here.length !== 1) {
457
+ undoTo(Math.max(0, top - 1));
458
+ qhead = Math.min(qhead, trail.length);
459
+ continue;
460
+ }
461
+ const uip = here[0];
462
+ undoTo(Math.max(0, ...[...c.lits.keys()].filter(name => name !== uip).map(name => vars.get(name).level)));
463
+ qhead = trail.length;
464
+ assign(uip, !c.lits.get(uip), learned);
465
+ if (sinceRestart >= restartAt) {
466
+ sinceRestart = 0;
467
+ restartAt = 32 * luby(++nRestart);
468
+ undoTo(0);
469
+ qhead = Math.min(qhead, trail.length);
470
+ }
471
+ }
472
+ }
473
+ // The DAG as a kernel tree below `root`, walked depth first with a reader of its own (the tree's path is a stack, as
474
+ // the search's trail is): each leaf's derivation found again among the rows at its tree path, in kernel.ts's order (the
475
+ // tree's leaves index those), else those rows refuted afresh. GDP_CDCL_VERIFY=1 compares each leaf's rows with
476
+ // kernel.ts's (kernel/cdcl.test.ts).
477
+ function unfold(goal, nodes, top, root, maxLeaves, until) {
478
+ const stack = [], on = new Map(), stamps = [];
479
+ let stampN = 0, leaves = 0;
480
+ const push = (name, lin, holds) => { on.set(name, { val: holds, at: stack.length }); stamps[stack.length] = ++stampN; stack.push({ name, lin, holds }); };
481
+ const pop = () => { on.delete(stack.pop().name); };
482
+ for (const [key, a] of root)
483
+ push(key, a.lin, a.holds);
484
+ const reader = new Reader(goal, { get: name => on.get(name), stamp: at => stamps[at], size: () => stack.length, lin: at => stack[at] });
485
+ const go = (i) => {
486
+ const n = nodes[i];
487
+ if ('res' in n) {
488
+ const key = canon(n.on), d = on.get(key);
489
+ if (d)
490
+ return go(d.val ? n.res[0] : n.res[1]);
491
+ push(key, n.on, true);
492
+ const yes = go(n.res[0]);
493
+ pop();
494
+ if (!yes)
495
+ return undefined;
496
+ push(key, n.on, false);
497
+ const no = go(n.res[1]);
498
+ pop();
499
+ return no && { split: n.on, yes, no };
500
+ }
501
+ if (++leaves > maxLeaves || clock() > until) {
502
+ cdclStats.unfoldWhy = leaves > maxLeaves ? 'leaves' : 'time';
503
+ return undefined;
504
+ }
505
+ reader.begin();
506
+ const rows = reader.leafRows();
507
+ if (verify) {
508
+ const path = new Map(stack.map(x => [x.name, { lin: x.lin, holds: x.holds }])), kr = leafConstraints(goal, path);
509
+ if (kr.length !== rows.length || kr.some((r, j) => canon(r.lin) !== canon(rows[j].lin))) {
510
+ const j = kr.findIndex((r, j2) => canon(r.lin) !== canon(rows[j2]?.lin ?? {}));
511
+ throw new Error(`reader.ts's rows differ from kernel.ts's at a leaf of ${goal.name}: ${kr.length} vs ${rows.length}, at ${j}: ${JSON.stringify(kr[j])} vs ${JSON.stringify(rows[j]?.lin)}; next ${JSON.stringify(kr.slice(j + 1, j + 3).map(r => r.lin))} vs ${JSON.stringify(rows.slice(j + 1, j + 3).map(r => r.lin))}`);
512
+ }
513
+ }
514
+ const at = new Map();
515
+ rows.forEach((r, j) => { const key = canon(r.lin); if (!at.has(key))
516
+ at.set(key, j); });
517
+ const steps = [];
518
+ for (const s of n.steps) {
519
+ if (s.kind !== 'input') {
520
+ steps.push(s);
521
+ continue;
522
+ }
523
+ const j = at.get(canon(n.inputs[s.index]));
524
+ if (j === undefined)
525
+ break;
526
+ steps.push({ ...s, index: j });
527
+ }
528
+ if (steps.length === n.steps.length && checkRefutation(rows, steps))
529
+ return { leaf: steps };
530
+ // (a row a longer path reads otherwise: a hypothesis false outright there, a choice decided)
531
+ cdclStats.resolved2++;
532
+ work.n += 1 + rows.length;
533
+ const fast = rows.length > 60 ? refuteFast(rows) : undefined;
534
+ if (fast?.kind === 'refuted')
535
+ return { leaf: fast.steps };
536
+ const out = solve(rows);
537
+ if (out.kind === 'refuted')
538
+ return { leaf: out.steps };
539
+ cdclStats.unfoldWhy = 'refute';
540
+ return undefined;
541
+ };
542
+ return go(top);
543
+ }
@@ -1,8 +1,13 @@
1
1
  import type { C, E, Law, Machine } from '../core/machine.js';
2
- import { type Goal, type Instances, type Liveness, type Path, type StepLaw, type Tree } from './kernel.js';
2
+ import { type Lin } from '../core/solver.js';
3
+ import type { Cyclic } from './cyclic.js';
4
+ import { type Goal, type Instances, type Liveness, type Loop, type Path, type StepLaw, type Tree, leafConstraintsReusing } from './kernel.js';
3
5
  export declare const pairedKeys: {
4
6
  skip: boolean;
5
7
  };
8
+ export declare function openCells(rows: {
9
+ lin: Lin;
10
+ }[], path: Path): Lin[];
6
11
  export declare const profile: {
7
12
  on: boolean;
8
13
  goals: {
@@ -47,7 +52,13 @@ export declare function grow(goal: Goal, path?: Path, budget?: {
47
52
  until?: number;
48
53
  units?: boolean;
49
54
  }): Outcome;
55
+ export declare function rowsAt(goal: Goal, path: Path): ReturnType<typeof leafConstraintsReusing>;
50
56
  export declare function widen(part: Goal, whole: Goal, tree: Tree, opaque?: Record<string, E>, pp?: Path, wp?: Path): Tree | undefined;
57
+ export declare function nearOf(goal: Goal): boolean[];
58
+ export declare const unitAtoms: (goal: Goal) => Lin[];
59
+ export declare function openAt(goal: Goal, path: Path, rows: {
60
+ lin: Lin;
61
+ }[]): Lin[];
51
62
  export declare const minimal: {
52
63
  on: boolean;
53
64
  };
@@ -109,6 +120,7 @@ export declare function proveStepLaws(given0: Machine, given: Law[], stepLaws: S
109
120
  machine?: Machine;
110
121
  stepLaws?: StepLaw[];
111
122
  proof?: StepProof;
123
+ uncovered?: string[];
112
124
  };
113
125
  export declare function proveProgress(m: Machine, laws: Law[], p: {
114
126
  name: string;
@@ -118,10 +130,17 @@ export declare function proveProgress(m: Machine, laws: Law[], p: {
118
130
  }): Report & {
119
131
  instances?: Instances;
120
132
  trees?: Record<string, Tree>;
133
+ uncovered?: string;
121
134
  };
122
135
  export declare function proveLiveness(m: Machine, laws: Law[], l: Liveness): Report & {
123
136
  steps?: ReturnType<typeof proveStepLaws>;
137
+ uncovered?: string[];
124
138
  };
139
+ export declare function certLoop(l: Loop, laws: Law[], rank: E | E[], trees: Record<string, Tree>, usualMs?: number): {
140
+ checked: boolean;
141
+ proof?: Cyclic;
142
+ why: string;
143
+ } | undefined;
125
144
  export declare const countLeaves: (t: Tree) => number;
126
145
  export declare function concretize(goal: Goal, bound?: number): Record<string, number> | undefined;
127
146
  export declare function factsFor(m: Machine, goal: Goal): C[];