gdp-wired 0.39.0 → 0.40.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,5 +1,9 @@
1
1
  import { type C, type E, type Law, type Machine } from './machine.js';
2
2
  import { type CountCert, type CountInst, type Instances, type MapRead } from '../kernel/kernel.js';
3
+ export declare const cprof: Record<string, number>;
4
+ export declare const countsDump: {
5
+ on?: (goal: object) => void;
6
+ };
3
7
  export declare function guardLaws(m: Machine): {
4
8
  counts: Machine['counts'];
5
9
  laws: Law[];
@@ -9,6 +13,8 @@ export declare function certFor(goal: {
9
13
  }, decls: {
10
14
  map: string;
11
15
  below: E;
16
+ j: string;
17
+ body: E;
12
18
  }[]): {
13
19
  reads: MapRead[];
14
20
  insts: CountInst[];
@@ -1,12 +1,23 @@
1
1
  import { assumed, checkCountedLaws, countedObligations, mcGoal, substC } from "../kernel/kernel.js";
2
- import { clock, grow } from "../kernel/prove.js";
3
- import { REFUTED, growCdcl } from "../kernel/cdcl.js";
2
+ import { clock, grow, modelInstances, widen } from "../kernel/prove.js";
3
+ import { REFUTED, cdclStats, growCdcl } from "../kernel/cdcl.js";
4
4
  import { inferLaws } from "./infer.js";
5
5
  import { holdsAt, small } from "./exists.js";
6
6
  import { env } from "./solver.js";
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
+ // profiles: each step goal left unknown or with a model past GDP_COUNTS_DUMP_MIN (300) hypotheses, the first GDP_COUNTS_DUMP_N (3))
9
+ export const cprof = {};
10
+ export const countsDump = {};
11
+ const ptime = (k, f) => { const t = performance.now(); try {
12
+ return f();
13
+ }
14
+ finally {
15
+ cprof[k] = (cprof[k] ?? 0) + performance.now() - t;
16
+ } };
17
+ let dumped = 0;
7
18
  const v = (name) => ({ op: 'var', name }), k = (value) => ({ op: 'const', value });
8
19
  const json = (t) => JSON.stringify(t);
9
- const knob = { pairs: env.GDP_K_PAIRS === '1', rounds: Number(env.GDP_K_ROUNDS ?? 2), cap: Number(env.GDP_K_CAP ?? 24), ts: env.GDP_K_TS !== '0', keyed: env.GDP_K_KEYED !== '0', flagTs: env.GDP_K_FLAGTS !== '0', shrink: Number(env.GDP_K_SHRINK ?? 150) };
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' };
10
21
  const one = k(1), zero = k(0);
11
22
  // Every term t with `get(map, t)` in t0.
12
23
  function reads(t0, map, out = new Map()) {
@@ -32,11 +43,35 @@ export function guardLaws(m) {
32
43
  x = substC(x, fsub); return x; };
33
44
  const guards = m.assume ? atoms(m.assume).filter(a => a.op === '<' || a.op === '<=') : [];
34
45
  const isCount = (mp) => !!m.counts?.[mp];
46
+ const when = (name, h, cmp) => ({ name, forall: 'a$c', holds: { op: 'or', xs: [{ op: 'not', x: h }, cmp] } });
47
+ // A stored set: a write at every key that copies a request's counted set (its value reads the count's body at the key)
48
+ // keeps what the guard asked of it. Its state count, below the same bound, in place of the request's in each guard
49
+ // comparison, is proposed under each member of the set and each scalar literal the flags read (started = 1); and that
50
+ // comparison is a guard the quantified flags below read too (a leader whose votes cover the stored set).
51
+ const all = { ...m.counts }, more = [];
52
+ const lits = [...new Map(Object.values(flags).flatMap(f => (f.op === 'all' ? [] : atoms(f))).filter(a => a.op === '=' && a.a.op === 'var' && a.a.name in m.state && a.b.op === 'const').map(a => [json(a), a])).values()];
53
+ for (const [mp, w] of Object.entries(m.step.maps ?? {})) {
54
+ if (!('each' in w))
55
+ continue;
56
+ for (const [c, d] of Object.entries(m.counts ?? {})) {
57
+ if (d.body.op !== 'if' || !json(w.value).includes(json(substC(d.body.c, { vars: { [d.key]: v(w.each) }, maps: {}, flags: {} }))))
58
+ continue;
59
+ const name = `${c}$${mp}`, key = `${name}$k`, member = (x) => ({ op: '=', a: { op: 'get', map: mp, key: v(x) }, b: one }), mine = member('a$c');
60
+ all[name] = counts[name] = { j: `${name}$x`, key, below: d.below, body: { op: 'if', c: member(key), then: one, else: zero } };
61
+ for (const g of guards)
62
+ if (reads(g, x => x === c).size) {
63
+ const g2 = substC(g, { vars: {}, maps: { [c]: () => ({ op: 'get', map: name, key: v('a$c') }) }, flags: {} });
64
+ more.push(g2);
65
+ for (const [i, h] of [mine, ...lits].entries())
66
+ laws.push(when(`${name} keeps ${c}'s bound ${i}`, h, g2));
67
+ }
68
+ }
69
+ }
35
70
  for (const [mp, w] of Object.entries(m.step.maps ?? {})) {
36
71
  if ('each' in w || w.key.op !== 'var' || !m.inputs.includes(w.key.name))
37
72
  continue;
38
73
  const t = w.key.name, written = inline({ op: '<=', a: one, b: w.value });
39
- const law = (name, cmp) => ({ name, forall: 'a$c', holds: { op: 'or', xs: [{ op: 'not', x: { op: '<=', a: one, b: { op: 'get', map: mp, key: v('a$c') } } }, cmp] } });
74
+ const law = (name, cmp) => when(name, { op: '<=', a: one, b: { op: 'get', map: mp, key: v('a$c') } }, cmp);
40
75
  // A comparison with a state count at the written key.
41
76
  for (const g of guards)
42
77
  for (const [, [c, key]] of reads(g, isCount)) {
@@ -53,7 +88,7 @@ export function guardLaws(m) {
53
88
  const [h, r] = q.c.xs[0].op === 'not' ? [q.c.xs[0].x, q.c.xs[1]] : [q.c.xs[1].op === 'not' ? q.c.xs[1].x : undefined, q.c.xs[0]];
54
89
  if (!h || !r)
55
90
  continue;
56
- for (const [c, d] of Object.entries(m.counts ?? {})) {
91
+ for (const [c, d] of Object.entries(all)) {
57
92
  // the set: the count's body is the flag's hypothesis at its key
58
93
  const body = d.body.op === 'if' ? d.body.c : undefined;
59
94
  if (!body || json(substC(body, { vars: { [d.key]: v(q.key) }, maps: {}, flags: {} })) !== json(h))
@@ -62,7 +97,7 @@ export function guardLaws(m) {
62
97
  continue;
63
98
  const name = `${c}$${mp}`, j = `${name}$x`, key = `${name}$k`;
64
99
  counts[name] = { j, key, below: d.below, body: { op: 'if', c: substC(r, { vars: { [q.key]: v(key), [t]: v(j) }, maps: {}, flags: {} }), then: one, else: zero } };
65
- for (const g of guards)
100
+ for (const g of [...guards, ...more])
66
101
  if (reads(g, x => x === c).size)
67
102
  laws.push(law(`${mp} keeps ${c}'s bound through ${name}`, substC(g, { vars: {}, maps: { [c]: () => ({ op: 'get', map: name, key: v('a$c') }) }, flags: {} })));
68
103
  }
@@ -85,7 +120,10 @@ export function certFor(goal, decls) {
85
120
  for (const [mp, t] of [...rs])
86
121
  if (mp.endsWith('#') && byMap.has(mp.slice(0, -1)) && !rs.some(([m2, t2]) => m2 === mp.slice(0, -1) && json(t2) === json(t)))
87
122
  rs.push([mp.slice(0, -1), t]);
88
- const named = rs.slice(0, 6).map(([mp, t], i) => [`r$${i}`, mp, t]);
123
+ // (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); };
125
+ 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]);
89
127
  const bound = (r) => json(byMap.get(r[1]).below);
90
128
  const insts = [], wits = [];
91
129
  const add = (terms, unit, below) => { const w = `w$${insts.length}`; wits.push(w); insts.push({ wit: w, below, terms, unit }); };
@@ -180,12 +218,20 @@ export function matched(names, body, cells, cap = knob.cap) {
180
218
  return [...out.values()].slice(0, cap);
181
219
  }
182
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) {
183
229
  const until = clock() + ms, g = guardLaws(m0), m = { ...m0, counts: { ...m0.counts, ...g.counts } };
184
230
  // The small instances: each param 2 and 3 (where the precondition allows), inputs and sets below 3.
185
231
  const insts = [2, 3].map(x => Object.fromEntries(m.params.map(p => [p, x])));
186
232
  const states = insts.map(p => {
187
233
  try {
188
- return { p, sts: small(m, p, 3) };
234
+ return { p, sts: ptime('small', () => small(m, p, 3, 3000, 300_000, knob.walks)) };
189
235
  }
190
236
  catch {
191
237
  return { p, sts: [] };
@@ -199,116 +245,291 @@ export function searchCounted(m0, caller, ms = 60_000) {
199
245
  if (!caller.every(trueAll))
200
246
  return { proven: false, laws: caller, m, why: clock() < until ? 'a law fails on the small instances' : 'time' };
201
247
  // (the engine's minimal ∀ cubes on its own small instances and data filter, core/infer.ts's: the supports no guard reads)
202
- const t1 = clock(), cubes = inferLaws(m0, caller, [], { cubes: 2, ms: Math.min(15_000, ms / 4), first: { proven: false, checked: false } }).found.map(f => f.law);
248
+ const t1 = clock(), rows = states.flatMap(({ p, sts }) => sts.map(st => ({ params: p, st })));
249
+ const cubes = 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));
250
+ if (env.GDP_COUNTS_TRACE)
251
+ console.error(`counts: small ${states.map(({ sts }) => sts.length).join('/')}; declared ${Object.keys(g.counts ?? {}).join(', ')}`);
203
252
  if (env.GDP_COUNTS_TRACE)
204
253
  console.error(`counts: cubes ${cubes.length} in ${Math.round(clock() - t1)} ms: ${cubes.map(l => l.name).join('; ')}`);
205
- let set = [...caller, ...[...kinds, ...g.laws, ...cubes].filter(trueAll)];
254
+ let set = [...caller, ...ptime('filter', () => [...kinds, ...g.laws, ...cubes].filter(trueAll))];
206
255
  if (env.GDP_COUNTS_TRACE)
207
- console.error(`counts: candidates ${set.map(l => l.name).join('; ')}`);
208
- for (let round = 0; clock() < until; round++) {
209
- // (the law's own names and the request's values that key a map: an action's value keys none)
210
- 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]))];
211
- const keyed = m.inputs.filter(i => keys0.some(key => mentions(key, i)));
212
- const terms = (l) => [...(l.forall ? [v(`${l.forall}#`)] : []), ...(l.keys ?? []).map(v), ...(knob.keyed ? keyed : m.inputs).map(v)];
213
- const instances = {}, certs = {}, failed = new Set();
214
- for (const law of set) {
215
- if (clock() > until)
216
- return { proven: false, laws: set, m, why: 'time' };
217
- const ts = terms(law);
218
- // (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
219
- // the witnesses, by the goal's reads below)
220
- const inst = () => {
221
- const out = {};
222
- for (const l of set) {
223
- if (l.keys?.length === 1 && knob.pairs)
224
- out[l.name] = ts.flatMap(x => ts.flatMap(y => (json(x) === json(y) ? [] : [x, y])));
225
- else if (!l.keys?.length && l.forall && knob.ts)
226
- out[l.name] = [...ts];
227
- }
228
- for (const [f, q] of Object.entries(m.step.flags ?? {}))
229
- if (q.op === 'all' && !q.keys?.length)
230
- out[`?${f}`] = knob.flagTs ? ts : m.inputs.map(v);
231
- return out;
232
- };
233
- // (more instances where the goal's reads meet a law's: each keyed law and quantified flag, matched; at most twice)
234
- const more = (at, hyps) => {
235
- const cells = [...ground(hyps).values()];
236
- let grew = false;
237
- const add = (name, ts2) => {
238
- const have = new Set(), cur = at[name] ?? [], n = ts2[0]?.length ?? 1;
239
- for (let i = 0; i + n <= cur.length; i += n)
240
- have.add(json(cur.slice(i, i + n)));
241
- for (const t of ts2)
242
- if (!have.has(json(t))) {
243
- have.add(json(t));
244
- at[name] = [...(at[name] ?? []), ...t];
245
- grew = true;
246
- }
247
- };
248
- for (const l of set)
249
- if (l.forall)
250
- add(l.name, matched([l.forall, ...(l.keys ?? [])], l.holds, cells));
251
- for (const [f, q] of Object.entries(m.step.flags ?? {}))
252
- if (q.op === 'all' && !q.keys?.length)
253
- add(`?${f}`, matched([q.key], q.c, cells));
254
- return grew;
256
+ console.error(`counts: candidates at ${Math.round(clock() - t1)} ms: ${set.map(l => l.name).join('; ')}`);
257
+ // (the law's own names and the request's values that key a map: an action's value keys none)
258
+ 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]))];
259
+ const keyed = m.inputs.filter(i => keys0.some(key => mentions(key, i)));
260
+ const terms = (l) => [...(l.forall ? [v(`${l.forall}#`)] : []), ...(l.keys ?? []).map(v), ...(knob.keyed ? keyed : m.inputs).map(v)];
261
+ let counted = true, stuck = '';
262
+ // One law's goals and their certificates, the laws `ls` assumed (a subsequence of the set): pass 0 with no instances of
263
+ // the lemma, pass 1 with the cells' (one set of witnesses a law); a tree each within `ms`.
264
+ const attempt = (law, ls, pass, ms) => {
265
+ const ts = terms(law);
266
+ // (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
267
+ // the witnesses, by the goal's reads below)
268
+ const inst = {};
269
+ for (const l of ls) {
270
+ if (l.keys?.length === 1 && knob.pairs)
271
+ inst[l.name] = ts.flatMap(x => ts.flatMap(y => (json(x) === json(y) ? [] : [x, y])));
272
+ else if (!l.keys?.length && l.forall && knob.ts)
273
+ inst[l.name] = [...ts];
274
+ }
275
+ for (const [f, q] of Object.entries(m.step.flags ?? {}))
276
+ if (q.op === 'all' && !q.keys?.length)
277
+ inst[`?${f}`] = knob.flagTs ? ts : m.inputs.map(v);
278
+ // (more instances where the goal's reads meet a law's: each keyed law and quantified flag, matched; at most twice)
279
+ // (the cells the goals' conclusions read first: a law's instances at the conclusion's own keys come before the cap)
280
+ const more = (at, hyps, concl) => {
281
+ const cells = [...ground(hyps, knob.first ? ground(concl) : new Map()).values()];
282
+ let grew = false;
283
+ const add = (name, ts2) => {
284
+ const have = new Set(), cur = at[name] ?? [], n = ts2[0]?.length ?? 1;
285
+ for (let i = 0; i + n <= cur.length; i += n)
286
+ have.add(json(cur.slice(i, i + n)));
287
+ for (const t of ts2)
288
+ if (!have.has(json(t))) {
289
+ have.add(json(t));
290
+ at[name] = [...(at[name] ?? []), ...t];
291
+ grew = true;
292
+ }
255
293
  };
256
- // The goals' certificates: first with no instances of the lemma, then with the cells' (one set of witnesses a law).
257
- let ok = true;
258
- for (const pass of [0, 1]) {
259
- instances[law.name] = inst();
260
- ok = true;
261
- let built = [];
262
- for (let r = 0; r <= knob.rounds; r++) {
263
- built = countedObligations(m, set, instances, set.indexOf(law)).map(({ goal, decls }) => {
264
- const c = pass ? certFor(goal, decls) : { reads: [], insts: [] };
265
- return { goal, c, gg: mcGoal(goal.hyps, decls, c) };
266
- });
267
- if (r === knob.rounds || !more(instances[law.name], built.map(b => b.gg?.hyps ?? b.goal.hyps)))
294
+ for (const l of ls)
295
+ if (l.forall)
296
+ add(l.name, matched([l.forall, ...(l.keys ?? [])], l.holds, cells));
297
+ for (const [f, q] of Object.entries(m.step.flags ?? {}))
298
+ if (q.op === 'all' && !q.keys?.length)
299
+ add(`?${f}`, matched([q.key], q.c, cells));
300
+ return grew;
301
+ };
302
+ const obligations = (at) => ptime('encode', () => countedObligations(m, ls, { [law.name]: at }, ls.indexOf(law)));
303
+ let built = [];
304
+ let at = inst;
305
+ for (let r = 0; r <= knob.rounds; r++) {
306
+ built = obligations(at).map(({ goal, decls }) => {
307
+ const c = pass ? certFor(goal, decls) : { reads: [], insts: [] };
308
+ return { goal, decls, c, gg: ptime('encode', () => mcGoal(goal.hyps, decls, c)) };
309
+ });
310
+ 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)))))
311
+ break;
312
+ }
313
+ // The step goal decided first by the CDCL search for a model (its phases the simplex's point: a model is met where the
314
+ // tree search would split on), within 2·ms (5 s at most):
315
+ // - refuted, past `shrink` hypotheses: the law's instances cut to those its core reads, the goals grown with them;
316
+ // - a model: the instances it asks for (kernel/prove.ts's modelInstances, MBQI: a law or quantified flag broken at a
317
+ // tuple of the goal's own keys), the goals made again with them, `mbqi` rounds at most; none asked, the goal has a
318
+ // model and is given up at once (no tree to grow);
319
+ // - unknown: the goals grown as they are.
320
+ // (a long attempt, the hard stage's or Houdini's, three times the rounds; past them, the goal is unknown, not a model)
321
+ let esc = 0, round = 0;
322
+ const rounds = ms >= 5_000 ? 3 * knob.mbqi : knob.mbqi;
323
+ again: for (;;) {
324
+ // (a refutation's core, where the step goal was decided refuted and not cut: its hypotheses, grown on their own first)
325
+ let part;
326
+ for (;; round++) {
327
+ const step = built.at(-1);
328
+ if (!step?.gg || step.gg.hyps.length < knob.decide)
329
+ break;
330
+ 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 }));
331
+ if (!('tree' in q) && q.why === REFUTED && q.core) {
332
+ if (step.gg.hyps.length <= knob.shrink) {
333
+ const last = step.gg.hyps.length - 1, keep = q.core.includes(last) ? q.core : [...q.core, last];
334
+ if (knob.part)
335
+ part = { gg: step.gg, core: { name: step.gg.name, hyps: keep.map(h => step.gg.hyps[h]) } };
268
336
  break;
337
+ }
338
+ const used = new Set(q.core.map(h => json(step.gg.hyps[h]))), cut = {};
339
+ for (const [name, ts2] of Object.entries(at)) {
340
+ const l = ls.find(x => x.name === name), n = l ? 1 + (l.keys?.length ?? 0) : 0;
341
+ 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();
342
+ }
343
+ at = cut;
344
+ built = obligations(at).map(({ goal, decls }, j) => ({ goal, decls, c: built[j].c, gg: mcGoal(goal.hyps, decls, built[j].c) }));
345
+ break;
269
346
  }
270
- // (a step goal past a few hundred hypotheses: the CDCL search's refutation first, its core naming the law instances
271
- // it read; the law's instances cut to those, and its goals grown with them, the certificate's reads kept)
272
- const step = built.at(-1);
273
- if (step?.gg && step.gg.hyps.length > knob.shrink) {
274
- const q = growCdcl(step.gg, new Map(), { nodes: 0, until: Math.min(until, clock() + 5_000) }, { model: true, core: true });
275
- if (!('tree' in q) && q.why === REFUTED && q.core) {
276
- const used = new Set(q.core.map(h => json(step.gg.hyps[h]))), at = instances[law.name], cut = {};
277
- for (const [name, ts2] of Object.entries(at)) {
278
- const l = set.find(x => x.name === name), n = l ? 1 + (l.keys?.length ?? 0) : 0;
279
- 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();
280
- }
281
- instances[law.name] = cut;
282
- built = countedObligations(m, set, instances, set.indexOf(law)).map(({ goal, decls }, j) => ({ goal, c: built[j].c, gg: mcGoal(goal.hyps, decls, built[j].c) }));
347
+ if ('tree' in q || q.stuck !== 'sat' || !q.witness)
348
+ break;
349
+ if (round >= rounds) {
350
+ stuck = 'unknown';
351
+ return undefined;
352
+ }
353
+ let asked = round < rounds ? ptime('mbqi', () => modelInstances(m, ls, at, step.gg, q.witness)) : undefined;
354
+ // (no instance asked: the blanket ones next, in turn, before the model is taken as one: the goals' reads matched,
355
+ // then the every-key laws at the law's own names and the request's values)
356
+ for (; !asked && esc < 2; esc++) {
357
+ const at2 = Object.fromEntries(Object.entries(at).map(([n, t]) => [n, [...t]]));
358
+ 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))))
359
+ : 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)))
360
+ return false; at2[l.name] = [...had, t]; return true; }).length).some(n => n > 0);
361
+ if (grew)
362
+ asked = at2;
363
+ }
364
+ if (!asked) {
365
+ stuck = 'sat';
366
+ if (countsDump.on && pass && ls.length >= Number(env.GDP_COUNTS_DUMP_LS ?? 0) && dumped < Number(env.GDP_COUNTS_DUMP_N ?? 3)) {
367
+ dumped++;
368
+ 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 });
283
369
  }
370
+ if (env.GDP_COUNTS_TRACE === '2')
371
+ 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`);
372
+ return undefined;
284
373
  }
285
- for (const { goal, c, gg } of built) {
286
- const o = gg && grow(gg, new Map(), { nodes: 0, until: Math.min(until, clock() + 10_000) });
287
- if (!o || !('tree' in o)) {
288
- ok = false;
289
- if (env.GDP_COUNTS_TRACE && pass)
290
- 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(' ')})`);
291
- break;
374
+ at = asked;
375
+ built = obligations(at).map(({ goal, decls }) => {
376
+ const c = pass ? certFor(goal, decls) : { reads: [], insts: [] };
377
+ return { goal, decls, c, gg: mcGoal(goal.hyps, decls, c) };
378
+ });
379
+ }
380
+ // (whether a goal reads a count: if none does, pass 1's goals are pass 0's)
381
+ if (!pass)
382
+ counted = built.some(b => certFor(b.goal, b.decls).reads.length);
383
+ const certs = {};
384
+ for (const { goal, c, gg } of built) {
385
+ const t0 = clock(), viaPart = gg && part?.gg === gg ? ptime('part', () => {
386
+ 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;
387
+ return w ? { tree: w, nodes: 0 } : undefined;
388
+ }) : undefined;
389
+ const o = viaPart ?? (gg && ptime(`grow${(gg.hyps.length > 300 ? '>300' : '')}`, () => grow(gg, new Map(), { nodes: 0, until: Math.min(until, clock() + ms) })));
390
+ 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)) {
391
+ dumped++;
392
+ countsDump.on({ law: law.name, goal: goal.name, ls: ls.map(l => l.name), stuck: o.stuck, hyps: gg.hyps });
393
+ }
394
+ if (env.GDP_COUNTS_TRACE === '2')
395
+ 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`);
396
+ // (the tree search's model of the step goal: the instances it asks for, as the CDCL search's, and the goals again)
397
+ if (gg && o && !('tree' in o) && o.stuck === 'sat' && o.witness && gg === built.at(-1).gg && round < rounds) {
398
+ const asked = ptime('mbqi', () => modelInstances(m, ls, at, gg, o.witness));
399
+ if (asked) {
400
+ at = asked;
401
+ round++;
402
+ 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) }; });
403
+ continue again;
292
404
  }
293
- certs[goal.name] = { reads: c.reads, insts: c.insts, tree: o.tree };
294
405
  }
295
- if (ok)
406
+ if (!o || !('tree' in o)) {
407
+ stuck = gg ? o.stuck ?? '' : '';
408
+ if (env.GDP_COUNTS_TRACE && pass === 1 && ls.length === set.length)
409
+ 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(' ')})`);
410
+ return undefined;
411
+ }
412
+ certs[goal.name] = { reads: c.reads, insts: c.insts, tree: o.tree };
413
+ }
414
+ return { instances: at, certs };
415
+ }
416
+ };
417
+ // The laws kept: each proven from the laws kept before it and itself (IC3's relative induction, its cone), tried again
418
+ // as more are kept, each goal briefly; their proofs stand whatever else the set holds. Then, in turn, each law whose
419
+ // goal ran out of time there (no model: a pigeonhole's goal over a large cone) with a full goal's time, the brief
420
+ // round again after each kept. With every caller kept, the kept laws are the proof; else Houdini over the whole set,
421
+ // the kept laws' proofs reused.
422
+ // (a law about no key is assumed in every goal, so with one in the set nothing is kept)
423
+ const kept = new Map(), cone = (l) => kept.has(l.name), tried = new Map(), late = new Map(), hard = new Map();
424
+ const keep = (law, pr) => { if (pr)
425
+ kept.set(law.name, pr);
426
+ else
427
+ late.set(law.name, stuck); return !!pr; };
428
+ // (the maps a law reads, a count's through its body)
429
+ 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) : [])]));
430
+ const near = (law) => { const ms0 = mapsOf(law); return set.filter(l => l === law || (cone(l) && [...mapsOf(l)].some(q => ms0.has(q)))); };
431
+ // (the kept laws by the maps they share, a hop at a time from the law's own, the fewest keys first, until `most`)
432
+ const hops = (law, most) => {
433
+ const seen = new Set(mapsOf(law)), out = new Set([law]);
434
+ for (let grew = true; grew && out.size < most;) {
435
+ grew = false;
436
+ 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));
437
+ for (const l of layer) {
438
+ if (out.size >= most)
296
439
  break;
440
+ out.add(l);
441
+ grew = true;
297
442
  }
298
- if (!ok)
299
- failed.add(law.name);
443
+ for (const l of layer)
444
+ if (out.has(l))
445
+ for (const q of mapsOf(l))
446
+ seen.add(q);
447
+ }
448
+ return set.filter(l => out.has(l));
449
+ };
450
+ // (in tiers, each to its fixpoint before the next: the law alone, once; with the kept laws that read one of its maps;
451
+ // with every kept law, a larger goal, the nearer tier again after each kept)
452
+ // (the whole cone's goal at most twice a law here: the hard stage below takes the rest)
453
+ const times = new Map(), askedLs = new Set();
454
+ const tier = (t) => {
455
+ let any = false;
456
+ for (let grew = true; grew && clock() < stopAt;) {
457
+ grew = false;
458
+ for (const law of set) {
459
+ const id = `${t} ${law.name}`;
460
+ 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)
461
+ continue;
462
+ tried.set(id, kept.size);
463
+ if (t === 2)
464
+ times.set(law.name, (times.get(law.name) ?? 0) + 1);
465
+ const ls = t === 0 ? [law] : t === 1 ? near(law) : set.filter(l => l === law || cone(l));
466
+ // (a tier whose goal is a nearer tier's, tried at this cone already, is skipped)
467
+ if ((t === 1 && ls.length === 1) || (t === 2 && tried.get(`1 ${law.name}`) === kept.size && near(law).length === ls.length))
468
+ continue;
469
+ // (the same law over the same laws, asked before in any tier, failed then: its goals are those again)
470
+ const same = `${law.name}\n${ls.map(l => l.name).join('\n')}`;
471
+ if (knob.memo && askedLs.has(same))
472
+ continue;
473
+ askedLs.add(same);
474
+ if (keep(law, attempt(law, ls, 1, knob.alone)))
475
+ grew = any = true;
476
+ }
477
+ if (t === 2)
478
+ break;
300
479
  }
301
- if (!failed.size) {
302
- const proof = { instances, certs };
303
- return checkCountedLaws(m, set, proof) ? { proven: true, laws: set, m, proof } : { proven: false, laws: set, m, why: 'the kernel refused the set' };
480
+ return any;
481
+ };
482
+ // (the sweeps stop with a third of what is left after the candidates, which the hard stage keeps)
483
+ let stopAt = until - (until - clock()) / 3;
484
+ const sweep = () => { tier(0); do
485
+ tier(1);
486
+ while (tier(2) && clock() < stopAt); };
487
+ // (the callers first, then the laws that read a count, a pigeonhole's; each again once more laws are kept)
488
+ const readsCount = (l) => reads(l.holds, mp => !!m.counts?.[mp]).size > 0;
489
+ const order = [...set.filter(l => caller.includes(l)), ...set.filter(l => !caller.includes(l) && readsCount(l)), ...set.filter(l => !caller.includes(l) && !readsCount(l))];
490
+ if (set.every(l => l.forall))
491
+ for (sweep(), stopAt = until; clock() < until;) {
492
+ const next = order.find(l => !kept.has(l.name) && hard.get(l.name) !== kept.size && late.get(l.name) === 'unknown');
493
+ if (!next)
494
+ break;
495
+ hard.set(next.name, kept.size);
496
+ // (the kept laws a few hops from the law's maps first, a smaller goal, then every kept law)
497
+ const few = hops(next, knob.hops), all = set.filter(l => l === next || cone(l));
498
+ if (keep(next, (few.length < all.length ? attempt(next, few, 1, 10_000) : undefined) ?? attempt(next, all, 1, 10_000)))
499
+ sweep();
304
500
  }
501
+ if (env.GDP_COUNTS_TRACE)
502
+ console.error(`counts: kept ${kept.size} of ${set.length} in ${Math.round(clock() - t1)} ms`);
503
+ 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' });
504
+ const keptProof = () => ({ instances: Object.fromEntries([...kept].map(([n, pr]) => [n, pr.instances])), certs: Object.assign({}, ...[...kept.values()].map(pr => pr.certs)) });
505
+ if (caller.every(cone))
506
+ return finish(set.filter(cone), keptProof());
507
+ for (let round = 0; clock() < until; round++) {
508
+ const { instances, certs } = keptProof(), failed = new Set();
509
+ // (the callers last, so they meet every support kept so far)
510
+ for (const law of [...set.filter(l => !caller.includes(l)), ...set.filter(l => caller.includes(l))]) {
511
+ if (clock() > until)
512
+ return { proven: false, laws: set, m, why: 'time' };
513
+ if (kept.has(law.name))
514
+ continue;
515
+ const pr = attempt(law, set, 0, 10_000) ?? (counted ? attempt(law, set, 1, 10_000) : undefined);
516
+ if (!pr) {
517
+ failed.add(law.name);
518
+ continue;
519
+ }
520
+ instances[law.name] = pr.instances;
521
+ Object.assign(certs, pr.certs);
522
+ }
523
+ if (env.GDP_COUNTS_TRACE)
524
+ console.error(`counts: round ${round}: ${set.length} laws, ${kept.size} kept, failed ${[...failed].join('; ').slice(0, 600)}`);
525
+ if (!failed.size)
526
+ return finish(set, { instances, certs });
305
527
  if (caller.some(l => failed.has(l.name)) && set.length === caller.length)
306
528
  return { proven: false, laws: set, m, why: `not proven: ${[...failed].join(', ')}` };
307
529
  const next = set.filter(l => !failed.has(l.name) || caller.includes(l));
308
- if (next.length === set.length) {
309
- // only callers fail: drop nothing more, give up
530
+ // (only callers fail: drop nothing more, give up)
531
+ if (next.length === set.length)
310
532
  return { proven: false, laws: set, m, why: `not proven: ${[...failed].join(', ')}` };
311
- }
312
533
  set = next;
313
534
  }
314
535
  return { proven: false, laws: set, m, why: 'time' };
@@ -6,7 +6,7 @@ export declare const namesOf: (t: E | C) => string[];
6
6
  export declare function groupsOf(vars: string[]): Group[];
7
7
  export declare function substVarsE(e: E, s: Record<string, E>): E;
8
8
  export declare function substVars(c: C, s: Record<string, E>): C;
9
- export declare function small(m: Machine, p: Env, b: number, cap?: number, work?: number): State[];
9
+ export declare function small(m: Machine, p: Env, b: number, cap?: number, work?: number, walks?: number): State[];
10
10
  export declare function ghostOf(m: Machine, law: Law): SomeWitness | undefined;
11
11
  export declare function holdsAt(m: Machine, law: Law, p: Env, st: State, b: number): boolean;
12
12
  export declare function someHolds(body: C, vars: string[], env: Env, st: State, m: Machine): {
@@ -156,8 +156,11 @@ function solved(atoms, g) {
156
156
  const atomsOf2 = (c) => (c.op === 'and' || c.op === 'or' ? c.xs.flatMap(atomsOf2) : c.op === 'not' ? atomsOf2(c.x) : [c]);
157
157
  // --- the small instances (core/counts.ts's filter and the ghost maps' below) --------------------------------------------------------------------------------------------------
158
158
  // Every state reached from the start with the params at `p`, each input below `b`, each carried map a subset of 0 .. b − 1.
159
- // (at most `cap` states, and `work` steps tried: a wide request space ends the BFS early, its states still reachable)
160
- export function small(m, p, b, cap = 3000, work = 300_000) {
159
+ // (at most `cap` states, and `work` steps tried: a wide request space ends the BFS early, its states still reachable;
160
+ // then, with `walks` steps more, random walks past it, each step a change of a kind (the variables it writes) chosen
161
+ // alike among those a few requests make: an action the BFS's levels never reach, a leader past a majority's votes, is
162
+ // taken as often as any other)
163
+ export function small(m, p, b, cap = 3000, work = 300_000, walks = 0) {
161
164
  const run = interpret(m), start = run.init(p);
162
165
  const subsets = Array.from({ length: 1 << b }, (_, s) => new Map(Array.from({ length: b }, (_, i) => i).filter(i => (s >> i) & 1).map(i => [i, 1])));
163
166
  // (an input the assumption keeps below a few values, an action's, over all of them; the rest below b)
@@ -167,7 +170,8 @@ export function small(m, p, b, cap = 3000, work = 300_000) {
167
170
  reqs = reqs.flatMap(r => Array.from({ length: below(i) }, (_, x) => ({ ...r, [i]: x })));
168
171
  for (const c of m.inputMaps ?? [])
169
172
  reqs = reqs.flatMap(r => subsets.map(s => ({ ...r, [c]: s })));
170
- const seen = new Map([[key(start), start]]), queue = [start];
173
+ const idOf = (s) => key([s.scalars, Object.entries(s.maps).map(([n, cs]) => [n, [...cs].filter(([, x]) => x).sort((a, c) => a[0] - c[0])])]);
174
+ const seen = new Map([[idOf(start), start]]), queue = [start];
171
175
  while (queue.length && seen.size < cap && work > 0) {
172
176
  const st = queue.shift();
173
177
  for (const r of reqs) {
@@ -180,13 +184,45 @@ export function small(m, p, b, cap = 3000, work = 300_000) {
180
184
  catch {
181
185
  continue;
182
186
  }
183
- const id = key([next.scalars, Object.entries(next.maps).map(([n, cs]) => [n, [...cs].filter(([, x]) => x).sort((a, c) => a[0] - c[0])])]);
187
+ const id = idOf(next);
184
188
  if (!seen.has(id)) {
185
189
  seen.set(id, next);
186
190
  queue.push(next);
187
191
  }
188
192
  }
189
193
  }
194
+ if (!queue.length)
195
+ return [...seen.values()];
196
+ const cell = (s, n, x) => s.maps[n]?.get(x) ?? s.defaults?.[n] ?? 0;
197
+ const kindOf = (a, c) => [...Object.keys(c.scalars).filter(n => a.scalars[n] !== c.scalars[n]),
198
+ ...Object.keys(c.maps).filter(n => a.defaults?.[n] !== c.defaults?.[n] || [...a.maps[n]?.keys() ?? [], ...c.maps[n].keys()].some(x => cell(a, n, x) !== cell(c, n, x)))].join();
199
+ let seed = 7;
200
+ const rnd = (n) => { seed = (seed * 48271) % 2147483647; return seed % n; };
201
+ for (let t = 0; walks > 0 && seen.size < 2 * cap; t++) {
202
+ let st = t % 2 ? start : [...seen.values()][rnd(seen.size)];
203
+ for (let d = 0; d < 40 && walks > 0; d++) {
204
+ const by = new Map();
205
+ for (let i = 0; i < 48; i++, walks--) {
206
+ let next;
207
+ try {
208
+ next = run.step(p, st, reqs[rnd(reqs.length)]);
209
+ }
210
+ catch {
211
+ continue;
212
+ }
213
+ const kd = kindOf(st, next);
214
+ if (kd)
215
+ by.set(kd, [...by.get(kd) ?? [], next]);
216
+ }
217
+ if (!by.size)
218
+ break;
219
+ const ks = [...by.values()], at = ks[rnd(ks.length)];
220
+ st = at[rnd(at.length)];
221
+ const id = idOf(st);
222
+ if (!seen.has(id))
223
+ seen.set(id, st);
224
+ }
225
+ }
190
226
  return [...seen.values()];
191
227
  }
192
228
  // A ghost for a law about no key with one value ∃x. P over maps (PCorrect's "some process not done, or its y is 1"): x a
@@ -16,6 +16,10 @@ export type InferOptions = {
16
16
  remainders?: boolean;
17
17
  join?: number;
18
18
  cubes?: number;
19
+ rows?: {
20
+ params: Record<string, number>;
21
+ st: State;
22
+ }[];
19
23
  };
20
24
  export type Found = {
21
25
  law: Law;
@@ -2930,9 +2930,15 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
2930
2930
  return { small, others, bfs, cut, params: pvs.size, ms: Math.round(vnow() - t3) };
2931
2931
  };
2932
2932
  {
2933
- const r0 = instance(() => 0, undefined, rand);
2933
+ const r0 = instance(() => 0, undefined, rand), own = [...r0.small, ...r0.others], most = new Map();
2934
2934
  samples.unshift(...r0.small);
2935
- smallAll = [...r0.small, ...r0.others];
2935
+ for (const q of own)
2936
+ for (const [mp, cs] of Object.entries(q.st.maps))
2937
+ for (const c of cs.values())
2938
+ most.set(mp, Math.max(most.get(mp) ?? 0, c));
2939
+ // (the rows given, where their cells take values the small instance's do (a yes/no's 1 at least): more states, not
2940
+ // more values, so the literals the cubes are made of are the instance's own)
2941
+ smallAll = [...(opts.rows ?? []).filter(q => Object.entries(q.st.maps).every(([mp, cs]) => [...cs.values()].every(c => c <= Math.max(1, most.get(mp) ?? 1)))), ...own];
2936
2942
  }
2937
2943
  const out = [];
2938
2944
  for (const counts of width.reduce((acc, w) => acc.flatMap(c => Array.from({ length: w + 1 }, (_, k) => [...c, k])), [[]])) {
@@ -1311,7 +1311,7 @@ export function modelInstances(m, laws, inst, goal, w, most = 64) {
1311
1311
  if (!keyed.length && !qs.length)
1312
1312
  return undefined;
1313
1313
  // (the maps a request carries read as maps too: a quantified flag over one, wo's ∀k. Q has k → Votes[src, k])
1314
- const fns = Object.keys(pm.fns ?? {}), mm = { ...pm, fns: undefined, maps: { ...(pm.maps ?? {}), ...Object.fromEntries([...fns, ...(pm.inputMaps ?? [])].map(f => [f, 0])) } };
1314
+ const fns = Object.keys(pm.fns ?? {}), mm = { ...pm, fns: undefined, maps: { ...(pm.maps ?? {}), ...Object.fromEntries([...fns, ...(pm.inputMaps ?? []), ...Object.keys(pm.counts ?? {})].map(f => [f, 0])) } };
1315
1315
  const maps = Object.fromEntries(Object.keys(mm.maps).map(mp => [mp, new Map()]));
1316
1316
  for (const [cell, value] of Object.entries(w)) {
1317
1317
  const br = cell.indexOf('[');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gdp-wired",
3
- "version": "0.39.0",
3
+ "version": "0.40.0",
4
4
  "description": "An automatic prover for stateful rules (budgets, caps, windows, workflows, policies): laws proven with no proof to write, checked again in Lean, counterexamples found on the GPU, the rule shipped as code",
5
5
  "keywords": [
6
6
  "verification",