gdp-wired 0.41.1 → 0.43.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.
@@ -1,8 +1,8 @@
1
- import { assumed, checkCountedLaws, countedObligations, mcGoal, substC } from "../kernel/kernel.js";
2
- import { clock, grow, modelInstances, widen } from "../kernel/prove.js";
1
+ import { assumed, checkCountedLaws, countedObligations, mcGoal, scope, substC } from "../kernel/kernel.js";
2
+ import { clock, counted, fullRate, grow, modelInstances, wallAt, widen, withWall } from "../kernel/prove.js";
3
3
  import { REFUTED, cdclStats, growCdcl } from "../kernel/cdcl.js";
4
4
  import { inferLaws } from "./infer.js";
5
- import { holdsAt, small } from "./exists.js";
5
+ import { smallOf, trueSmall } from "./exists.js";
6
6
  import { env } from "./solver.js";
7
7
  // (GDP_COUNTS_PROF: where a counted search's time goes, by phase, on stderr at the end; `countsDump.on`, set by research's
8
8
  // profiles: each step goal left unknown or with a model past GDP_COUNTS_DUMP_MIN (300) hypotheses, the first GDP_COUNTS_DUMP_N (3))
@@ -17,7 +17,6 @@ finally {
17
17
  let dumped = 0;
18
18
  const v = (name) => ({ op: 'var', name }), k = (value) => ({ op: 'const', value });
19
19
  const json = (t) => JSON.stringify(t);
20
- const knob = { pairs: env.GDP_K_PAIRS === '1', rounds: Number(env.GDP_K_ROUNDS ?? 0), cap: Number(env.GDP_K_CAP ?? 24), ts: env.GDP_K_TS === '1', keyed: env.GDP_K_KEYED !== '0', flagTs: env.GDP_K_FLAGTS !== '0', shrink: Number(env.GDP_K_SHRINK ?? 150), walks: Number(env.GDP_K_WALKS ?? 100_000), alone: Number(env.GDP_K_ALONE ?? 300), hops: Number(env.GDP_K_HOPS ?? 16), first: env.GDP_K_FIRST !== '0', decide: Number(env.GDP_K_DECIDE ?? 0), mbqi: Number(env.GDP_K_MBQI ?? 12), once: env.GDP_K_ONCE !== '0', reads: Number(env.GDP_K_READS ?? 6), memo: env.GDP_K_MEMO !== '0', part: env.GDP_K_PART !== '0', rows: env.GDP_K_ROWS !== '0', widen: env.GDP_K_WIDEN !== '0' };
21
20
  const one = k(1), zero = k(0);
22
21
  // Every term t with `get(map, t)` in t0.
23
22
  function reads(t0, map, out = new Map()) {
@@ -121,9 +120,9 @@ export function certFor(goal, decls) {
121
120
  if (mp.endsWith('#') && byMap.has(mp.slice(0, -1)) && !rs.some(([m2, t2]) => m2 === mp.slice(0, -1) && json(t2) === json(t)))
122
121
  rs.push([mp.slice(0, -1), t]);
123
122
  // (a count whose bound and body don't read its key is one number at every key: read once, at its first-ranked key)
124
- const once = new Set(), keyless = (mp) => { const d = byMap.get(mp); return knob.once && !mentions([d.below, d.body], d.j); };
123
+ const once = new Set(), keyless = (mp) => { const d = byMap.get(mp); return !mentions([d.below, d.body], d.j); };
125
124
  const rs1 = rs.filter(([mp]) => !keyless(mp) || (!once.has(mp) && !!once.add(mp)));
126
- const named = rs1.slice(0, knob.reads).map(([mp, t], i) => [`r$${i}`, mp, t]);
125
+ const named = rs1.map(([mp, t], i) => [`r$${i}`, mp, t]);
127
126
  const bound = (r) => json(byMap.get(r[1]).below);
128
127
  const insts = [], wits = [];
129
128
  const add = (terms, unit, below) => { const w = `w$${insts.length}`; wits.push(w); insts.push({ wit: w, below, terms, unit }); };
@@ -145,105 +144,30 @@ export function certFor(goal, decls) {
145
144
  add([[1, a[0]], [1, c[0]]], -1, byMap.get(a[1]).below);
146
145
  return { reads: named, insts: insts.slice(0, 10), wits: wits.slice(0, 10) };
147
146
  }
148
- // --- instances by the goal's own reads (E-matching, as an SMT solver instantiates a quantifier) ------------------------
149
- // A law over keys (and a quantified flag) is assumed at the tuples where its map reads meet the cells the goal reads: each
150
- // read of the law, its key a pattern over the law's names, matched against a cell read in the goal (a count's body at a
151
- // witness included), the tuples one read or two cover; the goal regrown with them, twice at most.
152
- const ground = (t0, out = new Map()) => {
153
- const go = (x) => {
154
- if (!x || typeof x !== 'object')
155
- return;
156
- const o = x;
157
- if (o.op === 'all')
158
- return;
159
- if (o.op === 'get')
160
- out.set(json([o.map, o.key]), [o.map, o.key]);
161
- for (const y of Object.values(o))
162
- go(y);
163
- };
164
- go(t0);
165
- return out;
166
- };
167
- // (a name a pattern reads twice, as x·N + x, matched by a cell whose two places differ: bound to each, `alt`, so the law
168
- // is assumed where the goal's cases make them equal)
169
- function bindKey(p, g, names, b, alt) {
170
- if (p.op === 'var' && names.includes(p.name)) {
171
- const x = b[p.name];
172
- if (!x) {
173
- b[p.name] = g;
174
- return true;
175
- }
176
- if (json(x) === json(g))
177
- return true;
178
- if (!alt || alt[p.name])
179
- return false;
180
- alt[p.name] = g;
147
+ // --- the candidates --------------------------------------------------------------------------------------------------
148
+ // One list from the machine's shapes, each kept only if true on every small state: each map's cells at most what the
149
+ // small instances reach; the guards' count comparisons (guardLaws, `guarded`); one key a row; the engine's minimal ∀
150
+ // cubes of at most two literals (core/infer.ts's `cubes`, read off these small states, within a quarter of the search's
151
+ // budget `ms`, 15 s at most), its template `shapes` (the caller's laws, or an ∃ law's frame), each guard `u < param` loosened where a caller reads u with no param bound.
152
+ export function candidates(src, m, caller, shapes, guarded, ms, until) {
153
+ const states = ptime('small', () => smallOf(m));
154
+ // (a law of the state only: one the kernel's scope refuses, reading an input or a count of the request (a guard's
155
+ // comparison with a second request count), has no value at a state, and is not proposed)
156
+ const ofState = (l) => { try {
157
+ scope(m, [l]);
181
158
  return true;
182
159
  }
183
- if (p.op !== g.op)
160
+ catch {
184
161
  return false;
185
- const q = g;
186
- switch (p.op) {
187
- case 'add':
188
- case 'sub':
189
- case 'min':
190
- case 'max':
191
- case 'prod': return bindKey(p.a, q.a, names, b, alt) && bindKey(p.b, q.b, names, b, alt);
192
- case 'mul': return p.k === q.k && bindKey(p.a, q.a, names, b, alt);
193
- case 'var':
194
- case 'const':
195
- case 'get':
196
- case 'if': return json(p) === json(g);
197
- }
198
- }
199
- export function matched(names, body, cells, cap = knob.cap) {
200
- const pats = [...reads(body, () => true).values()].filter(([, key]) => names.some(nm => mentions(key, nm)));
201
- const per = pats.map(([mp, key]) => cells.filter(c => c[0] === mp).flatMap(([, g]) => { const b = {}, alt = {}; return bindKey(key, g, names, b, alt) ? [b, ...Object.entries(alt).map(([nm, t]) => ({ ...b, [nm]: t }))] : []; }));
202
- const out = new Map();
203
- const put = (b) => { if (names.every(nm => b[nm])) {
204
- const t = names.map(nm => b[nm]);
205
- out.set(json(t), t);
206
162
  } };
207
- for (const [i, bs] of per.entries())
208
- for (const b of bs) {
209
- put(b);
210
- for (const c of per.slice(i + 1).flat()) {
211
- if (out.size >= cap)
212
- break;
213
- const m2 = { ...b };
214
- if (Object.entries(c).every(([nm, t]) => !m2[nm] || json(m2[nm]) === json(t)))
215
- put(Object.assign(m2, c));
216
- }
217
- }
218
- return [...out.values()].slice(0, cap);
219
- }
220
- export function searchCounted(m0, caller, ms = 60_000) {
221
- if (!env.GDP_COUNTS_PROF)
222
- return searchCounted0(m0, caller, ms);
223
- cdclStats.on = true;
224
- const t = performance.now(), out = searchCounted0(m0, caller, ms);
225
- console.error(`counts: prof total ${Math.round(performance.now() - t)} ms; ${Object.entries(cprof).map(([k2, x]) => `${k2} ${Math.round(x)}`).join(', ')}; cdcl runs ${cdclStats.runs} conflicts ${cdclStats.conflicts} decisions ${cdclStats.decisions} solveMs ${Math.round(cdclStats.solveMs)} rowsMs ${Math.round(cdclStats.rowsMs)} coreMs ${Math.round(cdclStats.coreMs)} unfoldMs ${Math.round(cdclStats.unfoldMs)} lpMs ${Math.round(cdclStats.lpMs)} boundMs ${Math.round(cdclStats.boundMs)} orderMs ${Math.round(cdclStats.orderMs)}`);
226
- return out;
227
- }
228
- function searchCounted0(m0, caller, ms = 60_000) {
229
- const until = clock() + ms, g = guardLaws(m0), m = { ...m0, counts: { ...m0.counts, ...g.counts } };
230
- // The small instances: each param 2 and 3 (where the precondition allows), inputs and sets below 3.
231
- const insts = [2, 3].map(x => Object.fromEntries(m.params.map(p => [p, x])));
232
- const states = insts.map(p => {
233
- try {
234
- return { p, sts: ptime('small', () => small(m, p, 3, 3000, 300_000, knob.walks)) };
235
- }
236
- catch {
237
- return { p, sts: [] };
238
- }
239
- });
163
+ const trueAll = (l) => clock() < until && ofState(l) && trueSmall(m, [l]);
240
164
  const kinds = Object.keys(m.maps ?? {}).map(mp => {
241
165
  const most = Math.max(0, ...states.flatMap(({ sts }) => sts.flatMap(st => [...(st.maps[mp]?.values() ?? [])])));
242
166
  return { name: `${mp} at most ${most}`, forall: 'a$c', holds: { op: '<=', a: { op: 'get', map: mp, key: v('a$c') }, b: k(most) } };
243
167
  });
244
168
  // (a relation written at a composed key N·a + b under a quantified flag that its row a (or column b) holds no cell:
245
- // at most one b a row (one a a column), K2's support the engine's cubes of two keys can't state, three keys read:
246
- // one decision a node where a decision needs the node undecided; a map a caller reads)
169
+ // at most one b a row (one a a column), three keys read, which the engine's cubes of two keys can't state: one
170
+ // decision a node where a decision needs the node undecided; a map a caller reads)
247
171
  const rowLaws = Object.entries(m.step.maps ?? {}).flatMap(([mp, w]) => {
248
172
  const key = 'each' in w ? undefined : w.key;
249
173
  if (key?.op !== 'add' || key.a.op !== 'mul' || key.a.a.op !== 'var' || key.b.op !== 'var' || !caller.some(l => reads(l.holds, x => x === mp).size))
@@ -256,12 +180,9 @@ function searchCounted0(m0, caller, ms = 60_000) {
256
180
  holds: { op: 'or', xs: [{ op: 'not', x: { op: 'and', xs: [...[a, x, y].map((z) => ({ op: '<', a: z, b: k(n) })), cell(x), cell(y)] } }, { op: '=', a: x, b: y }] } };
257
181
  });
258
182
  });
259
- const trueAll = (l) => clock() < until && states.every(({ p, sts }) => sts.every(st => holdsAt(m, l, p, st, 4)));
260
- if (!caller.every(trueAll))
261
- return { proven: false, laws: caller, m, why: clock() < until ? 'a law fails on the small instances' : 'time' };
262
- // (the engine's minimal ∀ cubes on its own small instances and data filter, core/infer.ts's: the supports no guard reads)
263
183
  const t1 = clock(), rows = states.flatMap(({ p, sts }) => sts.map(st => ({ params: p, st })));
264
- const cubes0 = ptime('cubes', () => inferLaws(m0, caller, [], { cubes: 2, ms: Math.min(15_000, ms / 4), first: { proven: false, checked: false }, rows }).found.map(f => f.law));
184
+ // (the cubes' budget counted, their wall stop the search's own: a slow machine finds the same cubes, later)
185
+ const cubes0 = ptime('cubes', () => inferLaws(src, shapes, [], { cubes: 2, ms: Math.min(15_000, ms / 4), wall: wallAt(), first: { proven: false, checked: false }, rows }).found.map(f => f.law));
265
186
  // (a cube's guard `u < param` dropped where u sits at a map's place that a caller reads with no param bound, the
266
187
  // decided value below N and not below size, if the small instances still hold it: the engine's template reads every
267
188
  // key of a composed map as one sort)
@@ -281,286 +202,234 @@ function searchCounted0(m0, caller, ms = 60_000) {
281
202
  const w = { ...c, name: name === c.name ? `${c.name} (any ${shown.join(', ')})` : name, holds: { op: 'or', xs: c.holds.xs.map(d => (d.op === 'not' ? { op: 'not', x: { op: 'and', xs: conjs(d.x).filter(keep) } } : d)) } };
282
203
  return trueAll(w) ? w : c;
283
204
  };
284
- const cubes = knob.widen ? cubes0.map(loosened) : cubes0;
205
+ const cubes = cubes0.map(loosened);
285
206
  if (env.GDP_COUNTS_TRACE)
286
- console.error(`counts: small ${states.map(({ sts }) => sts.length).join('/')}; declared ${Object.keys(g.counts ?? {}).join(', ')}`);
207
+ console.error(`counts: small ${states.map(({ sts }) => sts.length).join('/')}; cubes ${cubes.length} in ${Math.round(clock() - t1)} ms: ${cubes.map(l => l.name).join('; ')}`);
208
+ // (a candidate whose every conjunct a law before it states, its keys named apart by place, is not proposed again: a
209
+ // cell's maximum its kind's law states, a cube a guard's)
210
+ const said = new Set(), parts = (l) => {
211
+ const ks = [l.forall, ...(l.keys ?? [])].filter((x) => !!x), named = substC(l.holds, { vars: Object.fromEntries(ks.map((x, i) => [x, v(`$${i}`)])), maps: {}, flags: {} });
212
+ return (named.op === 'and' ? named.xs : [named]).map(json);
213
+ };
214
+ for (const l of caller)
215
+ for (const q of parts(l))
216
+ said.add(q);
217
+ const out = ptime('filter', () => [...kinds, ...guarded, ...rowLaws, ...cubes].filter(l => { const ps = parts(l); if (ps.every(q => said.has(q)) || !trueAll(l))
218
+ return false; for (const q of ps)
219
+ said.add(q); return true; }));
287
220
  if (env.GDP_COUNTS_TRACE)
288
- console.error(`counts: cubes ${cubes.length} in ${Math.round(clock() - t1)} ms: ${cubes.map(l => l.name).join('; ')}`);
289
- let set = [...caller, ...ptime('filter', () => [...kinds, ...g.laws, ...(knob.rows ? rowLaws : []), ...cubes].filter(trueAll))];
221
+ console.error(`counts: ${kinds.length + guarded.length + rowLaws.length + cubes.length - out.length} candidates said before or false on the small instances`);
222
+ return out;
223
+ }
224
+ export function cone(m, set, attempt, until) {
225
+ const kept = new Map(), inCone = (l) => kept.has(l.name), tried = new Map(), times = new Map(), asked = new Set();
226
+ const stopAt = until - (until - clock()) / 3, brief = (stopAt - clock()) / Math.max(1, set.length);
227
+ // (the maps a law reads, a count's through its body)
228
+ const mapsOf = (l) => new Set([...reads(l.holds, () => true).values()].flatMap(([mp]) => [mp, ...(m.counts?.[mp] ? [...reads(m.counts[mp].body, () => true).values()].map(([q]) => q) : [])]));
229
+ const near = (law) => { const ms0 = mapsOf(law); return set.filter(l => l === law || (inCone(l) && [...mapsOf(l)].some(q => ms0.has(q)))); };
230
+ const tier = (t) => {
231
+ let any = false;
232
+ for (let grew = true; grew && clock() < stopAt;) {
233
+ grew = false;
234
+ for (const law of set) {
235
+ const id = `${t} ${law.name}`;
236
+ if (kept.has(law.name) || tried.get(id) === kept.size || (t === 0 && tried.has(id)) || (t === 2 && (times.get(law.name) ?? 0) >= 2) || clock() > stopAt)
237
+ continue;
238
+ tried.set(id, kept.size);
239
+ if (t === 2)
240
+ times.set(law.name, (times.get(law.name) ?? 0) + 1);
241
+ const ls = t === 0 ? [law] : t === 1 ? near(law) : set.filter(l => l === law || inCone(l));
242
+ // (a tier whose goal is a nearer tier's, tried at this cone already, is skipped; and the same law over the same
243
+ // laws, asked before in any tier: its goals are those again)
244
+ if ((t === 1 && ls.length === 1) || (t === 2 && tried.get(`1 ${law.name}`) === kept.size && near(law).length === ls.length))
245
+ continue;
246
+ const same = `${law.name}\n${ls.map(l => l.name).join('\n')}`;
247
+ if (asked.has(same))
248
+ continue;
249
+ asked.add(same);
250
+ const r = attempt(law, ls, brief);
251
+ if ('proof' in r) {
252
+ kept.set(law.name, r.proof);
253
+ grew = any = true;
254
+ if (env.GDP_COUNTS_TRACE === '3')
255
+ console.error(`counts: keep ${law.name.slice(0, 50)} tier ${t}`);
256
+ }
257
+ }
258
+ if (t === 2)
259
+ break;
260
+ }
261
+ return any;
262
+ };
263
+ tier(0);
264
+ do
265
+ tier(1);
266
+ while (tier(2) && clock() < stopAt);
267
+ return kept;
268
+ }
269
+ // On the counted clock (kernel/prove.ts's `counted`, the cost model's work at fullRate a millisecond), as the engine's
270
+ // search is: what a budget lets it try, and so its verdict, is the same on a slow or shared machine as on a fast one; the
271
+ // wall a stop only at twice the budget.
272
+ export function searchCounted(m0, caller, ms = 60_000) {
273
+ const run = () => withWall(performance.now() + 2 * ms, () => counted(fullRate, () => searchCounted0(m0, caller, ms), true));
274
+ if (!env.GDP_COUNTS_PROF)
275
+ return run();
276
+ cdclStats.on = true;
277
+ const t = performance.now(), out = run();
278
+ console.error(`counts: prof total ${Math.round(performance.now() - t)} ms; ${Object.entries(cprof).map(([k2, x]) => `${k2} ${Math.round(x)}`).join(', ')}; cdcl runs ${cdclStats.runs} conflicts ${cdclStats.conflicts} decisions ${cdclStats.decisions} solveMs ${Math.round(cdclStats.solveMs)} rowsMs ${Math.round(cdclStats.rowsMs)} coreMs ${Math.round(cdclStats.coreMs)} unfoldMs ${Math.round(cdclStats.unfoldMs)} lpMs ${Math.round(cdclStats.lpMs)} boundMs ${Math.round(cdclStats.boundMs)} orderMs ${Math.round(cdclStats.orderMs)}`);
279
+ return out;
280
+ }
281
+ function searchCounted0(m0, caller, ms = 60_000) {
282
+ const until = clock() + ms, g = guardLaws(m0), m = { ...m0, counts: { ...m0.counts, ...g.counts } };
283
+ if (!caller.every(l => clock() < until && trueSmall(m, [l])))
284
+ return { proven: false, laws: caller, m, why: clock() < until ? 'a law fails on the small instances' : 'time' };
285
+ const t1 = clock();
286
+ let set = [...caller, ...candidates(m0, m, caller, caller, g.laws, ms, until)];
290
287
  if (env.GDP_COUNTS_TRACE)
291
288
  console.error(`counts: candidates at ${Math.round(clock() - t1)} ms: ${set.map(l => l.name).join('; ')}`);
292
289
  // (the law's own names and the request's values that key a map: an action's value keys none)
293
290
  const keys0 = [...[...reads([m.step, m.assume ?? null], () => true).values()].map(([, key]) => key), ...Object.values(m.step.maps ?? {}).flatMap(w => ('each' in w ? [] : [w.key]))];
294
- const keyed = m.inputs.filter(i => keys0.some(key => mentions(key, i)));
295
- const terms = (l) => [...(l.forall ? [v(`${l.forall}#`)] : []), ...(l.keys ?? []).map(v), ...(knob.keyed ? keyed : m.inputs).map(v)];
296
- let counted = true, stuck = '';
291
+ const keyed = m.inputs.filter(i => keys0.some(key => mentions(key, i))).map(v);
292
+ const terms = (l) => [...(l.forall ? [v(`${l.forall}#`)] : []), ...(l.keys ?? []).map(v), ...keyed];
293
+ let counted = true;
294
+ const none = { reads: [], insts: [] };
297
295
  // One law's goals and their certificates, the laws `ls` assumed (a subsequence of the set): pass 0 with no instances of
298
- // the lemma, pass 1 with the cells' (one set of witnesses a law); a tree each within `ms`.
296
+ // the lemma, pass 1 with the cells' (one set of witnesses a law); a tree each within `ms`. The instances: the
297
+ // quantified flags at the law's own terms, then what the goals' models ask.
298
+ // A law's last model (a counterexample to its induction, CTI) is kept: tried again over more laws (the cone's next
299
+ // tier, Houdini's round), the model is first read against them as the attempt reads a model (modelInstances: a law
300
+ // broken at a tuple of the goal's keys); none broken, it is still a model, and the law is refuted again without a
301
+ // solve. (Not where a law added reads a count: its goal's count instances aren't read here.)
302
+ const models = new Map(), isCount = (mp) => !!m.counts?.[mp];
299
303
  const attempt = (law, ls, pass, ms) => {
300
- const ts = terms(law);
301
- // (the laws over one key at pairs of the law's own names and the request's, every-key laws at those; the rest, and
302
- // the witnesses, by the goal's reads below)
303
- const inst = {};
304
- for (const l of ls) {
305
- if (l.keys?.length === 1 && knob.pairs)
306
- inst[l.name] = ts.flatMap(x => ts.flatMap(y => (json(x) === json(y) ? [] : [x, y])));
307
- else if (!l.keys?.length && l.forall && knob.ts)
308
- inst[l.name] = [...ts];
309
- }
310
- for (const [f, q] of Object.entries(m.step.flags ?? {}))
311
- if (q.op === 'all' && !q.keys?.length)
312
- inst[`?${f}`] = knob.flagTs ? ts : m.inputs.map(v);
313
- // (more instances where the goal's reads meet a law's: each keyed law and quantified flag, matched; at most twice)
314
- // (the cells the goals' conclusions read first: a law's instances at the conclusion's own keys come before the cap)
315
- const more = (at, hyps, concl) => {
316
- const cells = [...ground(hyps, knob.first ? ground(concl) : new Map()).values()];
317
- let grew = false;
318
- const add = (name, ts2) => {
319
- const have = new Set(), cur = at[name] ?? [], n = ts2[0]?.length ?? 1;
320
- for (let i = 0; i + n <= cur.length; i += n)
321
- have.add(json(cur.slice(i, i + n)));
322
- for (const t of ts2)
323
- if (!have.has(json(t))) {
324
- have.add(json(t));
325
- at[name] = [...(at[name] ?? []), ...t];
326
- grew = true;
327
- }
328
- };
329
- for (const l of ls)
330
- if (l.forall)
331
- add(l.name, matched([l.forall, ...(l.keys ?? [])], l.holds, cells));
332
- for (const [f, q] of Object.entries(m.step.flags ?? {}))
333
- if (q.op === 'all' && !q.keys?.length)
334
- add(`?${f}`, matched([q.key], q.c, cells));
335
- return grew;
336
- };
337
- const obligations = (at) => ptime('encode', () => countedObligations(m, ls, { [law.name]: at }, ls.indexOf(law)));
338
- let built = [];
339
- let at = inst;
340
- for (let r = 0; r <= knob.rounds; r++) {
341
- built = obligations(at).map(({ goal, decls }) => {
342
- const c = pass ? certFor(goal, decls) : { reads: [], insts: [] };
343
- return { goal, decls, c, gg: ptime('encode', () => mcGoal(goal.hyps, decls, c)) };
344
- });
345
- if (r === knob.rounds || !ptime('match', () => more(at, built.map(b => b.gg?.hyps ?? b.goal.hyps), built.map(b => b.goal.hyps.at(-1)))))
346
- break;
304
+ const ts = terms(law), id = `${pass} ${law.name}`, cti = models.get(id);
305
+ if (cti && !ls.some(l => !cti.ls.has(l.name) && reads(l.holds, isCount).size)) {
306
+ const at0 = Object.fromEntries(Object.entries(cti.at).filter(([n]) => n.startsWith('?') || ls.some(l => l.name === n)));
307
+ if (!ptime('mbqi', () => modelInstances(m, ls, at0, cti.gg, cti.w)))
308
+ return { stuck: 'sat' };
347
309
  }
310
+ const refuted = (gg, w) => { models.set(id, { gg, w, at, ls: new Set(ls.map(l => l.name)) }); return { stuck: 'sat' }; };
311
+ let at = Object.fromEntries(Object.entries(m.step.flags ?? {}).flatMap(([f, q]) => (q.op === 'all' && !q.keys?.length ? [[`?${f}`, ts]] : [])));
312
+ const obligations = (i) => ptime('encode', () => countedObligations(m, ls, { [law.name]: i }, ls.indexOf(law)));
313
+ const build = () => obligations(at).map(({ goal, decls }) => { const c = pass ? certFor(goal, decls) : none; return { goal, decls, c, gg: ptime('encode', () => mcGoal(goal.hyps, decls, c)) }; });
314
+ let built = build();
315
+ const t0 = clock(), more = () => clock() - t0 <= Math.max(ms, 1_000);
348
316
  // The step goal decided first by the CDCL search for a model (its phases the simplex's point: a model is met where the
349
317
  // tree search would split on), within 2·ms (5 s at most):
350
- // - refuted, past `shrink` hypotheses: the law's instances cut to those its core reads, the goals grown with them;
318
+ // - refuted: the law's instances cut to those its core reads, and the core's hypotheses grown on their own first,
319
+ // the tree widened to the goal;
351
320
  // - a model: the instances it asks for (kernel/prove.ts's modelInstances, MBQI: a law or quantified flag broken at a
352
- // tuple of the goal's own keys), the goals made again with them, `mbqi` rounds at most; none asked, the goal has a
353
- // model and is given up at once (no tree to grow);
321
+ // tuple of the goal's own keys), the goals made again with them; none asked, the goal has a model and is given
322
+ // up at once (no tree to grow); the rounds within the attempt's time (a second at least, as the kernel's
323
+ // withModels gives its later rounds), past which the goal is unknown;
354
324
  // - unknown: the goals grown as they are.
355
- // (a long attempt, the hard stage's or Houdini's, three times the rounds; past them, the goal is unknown, not a model)
356
- let esc = 0, round = 0;
357
- const rounds = ms >= 5_000 ? 3 * knob.mbqi : knob.mbqi;
358
- again: for (;;) {
359
- // (a refutation's core, where the step goal was decided refuted and not cut: its hypotheses, grown on their own first)
325
+ for (;;) {
360
326
  let part;
361
- for (;; round++) {
327
+ for (;;) {
362
328
  const step = built.at(-1);
363
- if (!step?.gg || step.gg.hyps.length < knob.decide)
329
+ if (!step?.gg)
364
330
  break;
365
331
  const q = ptime('decide', () => growCdcl(step.gg, new Map(), { nodes: 0, until: Math.min(until, clock() + Math.min(2 * ms, 5_000)) }, { model: true, core: true }));
366
332
  if (!('tree' in q) && q.why === REFUTED && q.core) {
367
- if (step.gg.hyps.length <= knob.shrink) {
368
- const last = step.gg.hyps.length - 1, keep = q.core.includes(last) ? q.core : [...q.core, last];
369
- if (knob.part)
370
- part = { gg: step.gg, core: { name: step.gg.name, hyps: keep.map(h => step.gg.hyps[h]) } };
371
- break;
372
- }
373
- const used = new Set(q.core.map(h => json(step.gg.hyps[h]))), cut = {};
333
+ const gg = step.gg, last = gg.hyps.length - 1, used = new Set(q.core.map(h => json(gg.hyps[h]))), cut = {};
374
334
  for (const [name, ts2] of Object.entries(at)) {
375
335
  const l = ls.find(x => x.name === name), n = l ? 1 + (l.keys?.length ?? 0) : 0;
376
336
  cut[name] = !l ? ts2 : Array.from({ length: ts2.length / n }, (_, t) => ts2.slice(t * n, t * n + n)).filter(t => used.has(json(assumed([l], { [name]: t })[0]))).flat();
377
337
  }
378
338
  at = cut;
379
339
  built = obligations(at).map(({ goal, decls }, j) => ({ goal, decls, c: built[j].c, gg: mcGoal(goal.hyps, decls, built[j].c) }));
340
+ part = { gg: built.at(-1).gg, core: { name: gg.name, hyps: (q.core.includes(last) ? q.core : [...q.core, last]).map(h => gg.hyps[h]) } };
380
341
  break;
381
342
  }
382
343
  if ('tree' in q || q.stuck !== 'sat' || !q.witness)
383
344
  break;
384
- if (round >= rounds) {
385
- stuck = 'unknown';
386
- return undefined;
387
- }
388
- let asked = round < rounds ? ptime('mbqi', () => modelInstances(m, ls, at, step.gg, q.witness)) : undefined;
389
- // (no instance asked: the blanket ones next, in turn, before the model is taken as one: the goals' reads matched,
390
- // then the every-key laws at the law's own names and the request's values)
391
- for (; !asked && esc < 2; esc++) {
392
- const at2 = Object.fromEntries(Object.entries(at).map(([n, t]) => [n, [...t]]));
393
- const grew = esc === 0 ? ptime('match', () => more(at2, built.map(b => b.gg?.hyps ?? b.goal.hyps), built.map(b => b.goal.hyps.at(-1))))
394
- : ls.filter(l => !l.keys?.length && l.forall).map(l => ts.filter(t => { const had = at2[l.name] ?? []; if (had.some(x => json(x) === json(t)))
395
- return false; at2[l.name] = [...had, t]; return true; }).length).some(n => n > 0);
396
- if (grew)
397
- asked = at2;
398
- }
345
+ if (!more())
346
+ return { stuck: 'unknown' };
347
+ const asked = ptime('mbqi', () => modelInstances(m, ls, at, step.gg, q.witness));
399
348
  if (!asked) {
400
- stuck = 'sat';
401
- if (countsDump.on && pass && ls.length >= Number(env.GDP_COUNTS_DUMP_LS ?? 0) && dumped < Number(env.GDP_COUNTS_DUMP_N ?? 3)) {
349
+ if (countsDump.on && pass && dumped < Number(env.GDP_COUNTS_DUMP_N ?? 3)) {
402
350
  dumped++;
403
351
  countsDump.on({ law: law.name, goal: step.goal.name, ls: ls.map(l => l.name), stuck: 'sat', witness: q.witness, reads: step.c.reads, insts: step.c.insts, hyps: step.gg.hyps });
404
352
  }
405
- if (env.GDP_COUNTS_TRACE === '2')
406
- console.error(`counts: ${ls.length === 1 ? 'alone' : `kept${ls.length}`} ${pass} ${step.goal.name}: sat by its model, round ${round}, ${step.gg.hyps.length} hyps`);
407
- return undefined;
353
+ return refuted(step.gg, q.witness);
408
354
  }
409
355
  at = asked;
410
- built = obligations(at).map(({ goal, decls }) => {
411
- const c = pass ? certFor(goal, decls) : { reads: [], insts: [] };
412
- return { goal, decls, c, gg: mcGoal(goal.hyps, decls, c) };
413
- });
356
+ built = build();
414
357
  }
415
358
  // (whether a goal reads a count: if none does, pass 1's goals are pass 0's)
416
359
  if (!pass)
417
360
  counted = built.some(b => certFor(b.goal, b.decls).reads.length);
418
361
  const certs = {};
362
+ let again = false;
419
363
  for (const { goal, c, gg } of built) {
420
364
  const t0 = clock(), viaPart = gg && part?.gg === gg ? ptime('part', () => {
421
365
  const o1 = grow(part.core, new Map(), { nodes: 0, until: Math.min(until, clock() + Math.max(ms, 2_000)) }), w = 'tree' in o1 ? widen(part.core, gg, o1.tree) : undefined;
422
366
  return w ? { tree: w, nodes: 0 } : undefined;
423
367
  }) : undefined;
424
368
  const o = viaPart ?? (gg && ptime(`grow${(gg.hyps.length > 300 ? '>300' : '')}`, () => grow(gg, new Map(), { nodes: 0, until: Math.min(until, clock() + ms) })));
425
- if (countsDump.on && gg && o && !('tree' in o) && gg.hyps.length > Number(env.GDP_COUNTS_DUMP_MIN ?? 300) && ls.length >= Number(env.GDP_COUNTS_DUMP_LS ?? 0) && dumped < Number(env.GDP_COUNTS_DUMP_N ?? 3)) {
369
+ if (countsDump.on && gg && o && !('tree' in o) && gg.hyps.length > Number(env.GDP_COUNTS_DUMP_MIN ?? 300) && dumped < Number(env.GDP_COUNTS_DUMP_N ?? 3)) {
426
370
  dumped++;
427
371
  countsDump.on({ law: law.name, goal: goal.name, ls: ls.map(l => l.name), stuck: o.stuck, hyps: gg.hyps });
428
372
  }
429
373
  if (env.GDP_COUNTS_TRACE === '2')
430
- console.error(`counts: ${ls.length === 1 ? 'alone' : ls.length < set.length ? `kept${ls.length}` : 'all'} ${pass} ${goal.name}: ${o && 'tree' in o ? 'proven' : gg ? o.stuck : 'no read'} ${gg?.hyps.length ?? 0} hyps ${Math.round(clock() - t0)} ms`);
374
+ console.error(`counts: ${ls.length === 1 ? 'alone' : `with ${ls.length}`} ${pass} ${goal.name}: ${o && 'tree' in o ? 'proven' : gg ? o.stuck : 'no read'} ${gg?.hyps.length ?? 0} hyps ${Math.round(clock() - t0)} ms`);
431
375
  // (the tree search's model of the step goal: the instances it asks for, as the CDCL search's, and the goals again)
432
- if (gg && o && !('tree' in o) && o.stuck === 'sat' && o.witness && gg === built.at(-1).gg && round < rounds) {
376
+ if (gg && o && !('tree' in o) && o.stuck === 'sat' && o.witness && gg === built.at(-1).gg && more()) {
433
377
  const asked = ptime('mbqi', () => modelInstances(m, ls, at, gg, o.witness));
434
378
  if (asked) {
435
379
  at = asked;
436
- round++;
437
- built = obligations(at).map(({ goal: g2, decls }) => { const c2 = pass ? certFor(g2, decls) : { reads: [], insts: [] }; return { goal: g2, decls, c: c2, gg: mcGoal(g2.hyps, decls, c2) }; });
438
- continue again;
380
+ built = build();
381
+ again = true;
382
+ break;
439
383
  }
440
384
  }
441
- if (!o || !('tree' in o)) {
442
- stuck = gg ? o.stuck ?? '' : '';
443
- if (env.GDP_COUNTS_TRACE && pass === 1 && ls.length === set.length)
444
- console.error(`counts: ${goal.name}: ${gg ? json(o).slice(0, 300) : 'a read of no count'} (reads ${c.reads.map(r => `${r[1]}[${json(r[2])}]`).join(' ')})`);
445
- return undefined;
446
- }
385
+ if (gg && o && !('tree' in o) && o.stuck === 'sat' && o.witness && gg === built.at(-1).gg)
386
+ return refuted(gg, o.witness);
387
+ if (!o || !('tree' in o))
388
+ return { stuck: gg ? o.stuck ?? '' : '' };
447
389
  certs[goal.name] = { reads: c.reads, insts: c.insts, tree: o.tree };
448
390
  }
449
- return { instances: at, certs };
391
+ if (!again)
392
+ return { proof: { instances: at, certs } };
450
393
  }
451
394
  };
452
- // The laws kept: each proven from the laws kept before it and itself (IC3's relative induction, its cone), tried again
453
- // as more are kept, each goal briefly; their proofs stand whatever else the set holds. Then, in turn, each law whose
454
- // goal ran out of time there (no model: a pigeonhole's goal over a large cone) with a full goal's time, the brief
455
- // round again after each kept. With every caller kept, the kept laws are the proof; else Houdini over the whole set,
456
- // the kept laws' proofs reused.
457
- // (a law about no key is assumed in every goal, so with one in the set nothing is kept)
458
- const kept = new Map(), cone = (l) => kept.has(l.name), tried = new Map(), late = new Map(), hard = new Map();
459
- const keep = (law, pr) => { if (pr)
460
- kept.set(law.name, pr);
461
- else
462
- late.set(law.name, stuck); return !!pr; };
463
- // (the maps a law reads, a count's through its body)
464
- const mapsOf = (l) => new Set([...reads(l.holds, () => true).values()].flatMap(([mp]) => [mp, ...(m.counts?.[mp] ? [...reads(m.counts[mp].body, () => true).values()].map(([q]) => q) : [])]));
465
- const near = (law) => { const ms0 = mapsOf(law); return set.filter(l => l === law || (cone(l) && [...mapsOf(l)].some(q => ms0.has(q)))); };
466
- // (the kept laws by the maps they share, a hop at a time from the law's own, the fewest keys first, until `most`)
467
- const hops = (law, most) => {
468
- const seen = new Set(mapsOf(law)), out = new Set([law]);
469
- for (let grew = true; grew && out.size < most;) {
470
- grew = false;
471
- const layer = set.filter(l => cone(l) && !out.has(l) && [...mapsOf(l)].some(q => seen.has(q))).sort((a, b) => (a.keys?.length ?? 0) - (b.keys?.length ?? 0));
472
- for (const l of layer) {
473
- if (out.size >= most)
474
- break;
475
- out.add(l);
476
- grew = true;
477
- }
478
- for (const l of layer)
479
- if (out.has(l))
480
- for (const q of mapsOf(l))
481
- seen.add(q);
482
- }
483
- return set.filter(l => out.has(l));
395
+ const traced = (law, ls, pass, ms) => {
396
+ const t0 = clock(), r = attempt(law, ls, pass, ms);
397
+ if (env.GDP_COUNTS_TRACE === '3')
398
+ console.error(`counts: try ${law.name.slice(0, 50)} | ls ${ls.length} pass ${pass} ms ${ms} took ${Math.round(clock() - t0)} -> ${'proof' in r ? 'kept' : r.stuck}`);
399
+ return r;
484
400
  };
485
- // (in tiers, each to its fixpoint before the next: the law alone, once; with the kept laws that read one of its maps;
486
- // with every kept law, a larger goal, the nearer tier again after each kept)
487
- // (the whole cone's goal at most twice a law here: the hard stage below takes the rest)
488
- const times = new Map(), askedLs = new Set();
489
- const tier = (t) => {
490
- let any = false;
491
- for (let grew = true; grew && clock() < stopAt;) {
492
- grew = false;
493
- for (const law of set) {
494
- const id = `${t} ${law.name}`;
495
- if (kept.has(law.name) || tried.get(id) === kept.size || (t === 0 && tried.has(id)) || (t === 2 && (times.get(law.name) ?? 0) >= 2) || clock() > stopAt)
496
- continue;
497
- tried.set(id, kept.size);
498
- if (t === 2)
499
- times.set(law.name, (times.get(law.name) ?? 0) + 1);
500
- const ls = t === 0 ? [law] : t === 1 ? near(law) : set.filter(l => l === law || cone(l));
501
- // (a tier whose goal is a nearer tier's, tried at this cone already, is skipped)
502
- if ((t === 1 && ls.length === 1) || (t === 2 && tried.get(`1 ${law.name}`) === kept.size && near(law).length === ls.length))
503
- continue;
504
- // (the same law over the same laws, asked before in any tier, failed then: its goals are those again)
505
- const same = `${law.name}\n${ls.map(l => l.name).join('\n')}`;
506
- if (knob.memo && askedLs.has(same))
507
- continue;
508
- askedLs.add(same);
509
- if (keep(law, attempt(law, ls, 1, knob.alone)))
510
- grew = any = true;
511
- }
512
- if (t === 2)
513
- break;
514
- }
515
- return any;
516
- };
517
- // (the sweeps stop with a third of what is left after the candidates, which the hard stage keeps)
518
- let stopAt = until - (until - clock()) / 3;
519
- const sweep = () => { tier(0); do
520
- tier(1);
521
- while (tier(2) && clock() < stopAt); };
522
- // (the callers first, then the laws that read a count, a pigeonhole's; each again once more laws are kept)
523
- const readsCount = (l) => reads(l.holds, mp => !!m.counts?.[mp]).size > 0;
524
- const order = [...set.filter(l => caller.includes(l)), ...set.filter(l => !caller.includes(l) && readsCount(l)), ...set.filter(l => !caller.includes(l) && !readsCount(l))];
525
- if (set.every(l => l.forall))
526
- for (sweep(), stopAt = until; clock() < until;) {
527
- const next = order.find(l => !kept.has(l.name) && hard.get(l.name) !== kept.size && late.get(l.name) === 'unknown');
528
- if (!next)
529
- break;
530
- hard.set(next.name, kept.size);
531
- // (the kept laws a few hops from the law's maps first, a smaller goal, then every kept law)
532
- const few = hops(next, knob.hops), all = set.filter(l => l === next || cone(l));
533
- if (keep(next, (few.length < all.length ? attempt(next, few, 1, 10_000) : undefined) ?? attempt(next, all, 1, 10_000)))
534
- sweep();
535
- }
401
+ // The cone (a law about no key is assumed in every goal, so with one in the set nothing is kept); with every caller
402
+ // kept, the kept laws are the proof; else Houdini over the whole set, the kept laws' proofs reused.
403
+ const kept = set.every(l => l.forall) ? cone(m, set, (law, ls, ms2) => traced(law, ls, 1, ms2), until) : new Map();
536
404
  if (env.GDP_COUNTS_TRACE)
537
405
  console.error(`counts: kept ${kept.size} of ${set.length} in ${Math.round(clock() - t1)} ms`);
538
406
  const finish = (ls, proof) => (ptime('kernel', () => checkCountedLaws(m, ls, proof)) ? { proven: true, laws: ls, m, proof } : { proven: false, laws: ls, m, why: 'the kernel refused the set' });
539
407
  const keptProof = () => ({ instances: Object.fromEntries([...kept].map(([n, pr]) => [n, pr.instances])), certs: Object.assign({}, ...[...kept.values()].map(pr => pr.certs)) });
540
- if (caller.every(cone))
541
- return finish(set.filter(cone), keptProof());
408
+ if (caller.every(l => kept.has(l.name)))
409
+ return finish(set.filter(l => kept.has(l.name)), keptProof());
410
+ // (each law not kept an even share of what is left a round)
542
411
  for (let round = 0; clock() < until; round++) {
543
- const { instances, certs } = keptProof(), failed = new Set();
412
+ const { instances, certs } = keptProof(), failed = new Set(), share = (until - clock()) / Math.max(1, set.filter(l => !kept.has(l.name)).length);
544
413
  // (the callers last, so they meet every support kept so far)
545
414
  for (const law of [...set.filter(l => !caller.includes(l)), ...set.filter(l => caller.includes(l))]) {
546
415
  if (clock() > until)
547
416
  return { proven: false, laws: set, m, why: 'time' };
548
417
  if (kept.has(law.name))
549
418
  continue;
550
- const pr = attempt(law, set, 0, 10_000) ?? (counted ? attempt(law, set, 1, 10_000) : undefined);
551
- if (!pr) {
419
+ let r = traced(law, set, 0, share);
420
+ if (!('proof' in r) && counted)
421
+ r = traced(law, set, 1, share);
422
+ if (!('proof' in r)) {
552
423
  failed.add(law.name);
553
424
  continue;
554
425
  }
555
- instances[law.name] = pr.instances;
556
- Object.assign(certs, pr.certs);
426
+ instances[law.name] = r.proof.instances;
427
+ Object.assign(certs, r.proof.certs);
557
428
  }
558
429
  if (env.GDP_COUNTS_TRACE)
559
430
  console.error(`counts: round ${round}: ${set.length} laws, ${kept.size} kept, failed ${[...failed].join('; ').slice(0, 600)}`);
560
431
  if (!failed.size)
561
432
  return finish(set, { instances, certs });
562
- if (caller.some(l => failed.has(l.name)) && set.length === caller.length)
563
- return { proven: false, laws: set, m, why: `not proven: ${[...failed].join(', ')}` };
564
433
  const next = set.filter(l => !failed.has(l.name) || caller.includes(l));
565
434
  // (only callers fail: drop nothing more, give up)
566
435
  if (next.length === set.length)