gdp-wired 0.39.0 → 0.41.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', rows: env.GDP_K_ROWS !== '0', widen: env.GDP_K_WIDEN !== '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: [] };
@@ -195,120 +241,330 @@ export function searchCounted(m0, caller, ms = 60_000) {
195
241
  const most = Math.max(0, ...states.flatMap(({ sts }) => sts.flatMap(st => [...(st.maps[mp]?.values() ?? [])])));
196
242
  return { name: `${mp} at most ${most}`, forall: 'a$c', holds: { op: '<=', a: { op: 'get', map: mp, key: v('a$c') }, b: k(most) } };
197
243
  });
244
+ // (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)
247
+ const rowLaws = Object.entries(m.step.maps ?? {}).flatMap(([mp, w]) => {
248
+ const key = 'each' in w ? undefined : w.key;
249
+ 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))
250
+ return [];
251
+ const n = key.a.k, row = key.a.a, col0 = key.b, cellAt = (p, q) => ({ op: 'get', map: mp, key: { op: 'add', a: { op: 'mul', k: n, a: p }, b: q } });
252
+ const empty = (col) => Object.values(m.step.flags ?? {}).some(q => q.op === 'all' && !q.keys?.length && json(q.c).includes(json(col ? cellAt(v(q.key), col0) : cellAt(row, v(q.key)))));
253
+ return [false, true].filter(empty).map((col) => {
254
+ const [a, x, y] = [v('a$c'), v('x$c'), v('y$c')], cell = (z) => ({ op: '<=', a: one, b: col ? cellAt(z, a) : cellAt(a, z) });
255
+ return { name: `${mp}: one ${col ? 'first key a second' : 'second key a first'}`, forall: 'a$c', keys: ['x$c', 'y$c'],
256
+ 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
+ });
258
+ });
198
259
  const trueAll = (l) => clock() < until && states.every(({ p, sts }) => sts.every(st => holdsAt(m, l, p, st, 4)));
199
260
  if (!caller.every(trueAll))
200
261
  return { proven: false, laws: caller, m, why: clock() < until ? 'a law fails on the small instances' : 'time' };
201
262
  // (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);
263
+ 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));
265
+ // (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
+ // decided value below N and not below size, if the small instances still hold it: the engine's template reads every
267
+ // key of a composed map as one sort)
268
+ const placesOf = (key) => (key.op === 'var' ? [key.name] : key.op === 'add' && key.a.op === 'mul' && key.a.a.op === 'var' && key.b.op === 'var' ? [key.a.a.name, key.b.name] : undefined);
269
+ const conjs = (c) => (c.op === 'and' ? c.xs.flatMap(conjs) : [c]);
270
+ const guardsOf = (l) => (l.holds.op === 'or' ? l.holds.xs.flatMap(d => (d.op === 'not' ? conjs(d.x) : [])) : []);
271
+ const bounded = (gs, u) => gs.some(c => c.op === '<' && c.a.op === 'var' && c.a.name === u && c.b.op === 'var' && m.params.includes(c.b.name));
272
+ const loose = new Set(caller.filter(l => guardsOf(l).length).flatMap(l => [...reads(l.holds, mp => mp in (m.maps ?? {})).values()].flatMap(([mp, key]) => (placesOf(key) ?? []).flatMap((u, i) => (bounded(guardsOf(l), u) ? [] : [`${mp}:${i}`])))));
273
+ const loosened = (c) => {
274
+ const drop = new Set([...reads(c.holds, () => true).values()].flatMap(([mp, key]) => (placesOf(key) ?? []).filter((u, i) => loose.has(`${mp}:${i}`))));
275
+ const keep = (x) => !(x.op === '<' && x.a.op === 'var' && drop.has(x.a.name) && x.b.op === 'var' && m.params.includes(x.b.name));
276
+ if (!drop.size || c.holds.op !== 'or' || !guardsOf(c).some(x => !keep(x)))
277
+ return c;
278
+ // (the engine names the law's keys x, y, z in order)
279
+ const shown = [c.forall, ...(c.keys ?? [])].flatMap((u, i) => (u && drop.has(u) ? ['xyzw'[i] ?? u] : []));
280
+ const name = shown.reduce((t, x) => t.replace(new RegExp(`\\b${x} < (${m.params.join('|')}) ∧ `, 'g'), ''), c.name);
281
+ 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
+ return trueAll(w) ? w : c;
283
+ };
284
+ const cubes = knob.widen ? cubes0.map(loosened) : cubes0;
285
+ if (env.GDP_COUNTS_TRACE)
286
+ console.error(`counts: small ${states.map(({ sts }) => sts.length).join('/')}; declared ${Object.keys(g.counts ?? {}).join(', ')}`);
203
287
  if (env.GDP_COUNTS_TRACE)
204
288
  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)];
289
+ let set = [...caller, ...ptime('filter', () => [...kinds, ...g.laws, ...(knob.rows ? rowLaws : []), ...cubes].filter(trueAll))];
206
290
  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;
291
+ console.error(`counts: candidates at ${Math.round(clock() - t1)} ms: ${set.map(l => l.name).join('; ')}`);
292
+ // (the law's own names and the request's values that key a map: an action's value keys none)
293
+ 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 = '';
297
+ // 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`.
299
+ 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
+ }
255
328
  };
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)))
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;
347
+ }
348
+ // 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
+ // 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;
351
+ // - 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);
354
+ // - 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)
360
+ let part;
361
+ for (;; round++) {
362
+ const step = built.at(-1);
363
+ if (!step?.gg || step.gg.hyps.length < knob.decide)
364
+ break;
365
+ 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
+ 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]) } };
268
371
  break;
372
+ }
373
+ const used = new Set(q.core.map(h => json(step.gg.hyps[h]))), cut = {};
374
+ for (const [name, ts2] of Object.entries(at)) {
375
+ const l = ls.find(x => x.name === name), n = l ? 1 + (l.keys?.length ?? 0) : 0;
376
+ 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
+ }
378
+ at = cut;
379
+ built = obligations(at).map(({ goal, decls }, j) => ({ goal, decls, c: built[j].c, gg: mcGoal(goal.hyps, decls, built[j].c) }));
380
+ break;
269
381
  }
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) }));
382
+ if ('tree' in q || q.stuck !== 'sat' || !q.witness)
383
+ 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
+ }
399
+ 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)) {
402
+ dumped++;
403
+ 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
404
  }
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;
284
408
  }
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;
409
+ 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
+ });
414
+ }
415
+ // (whether a goal reads a count: if none does, pass 1's goals are pass 0's)
416
+ if (!pass)
417
+ counted = built.some(b => certFor(b.goal, b.decls).reads.length);
418
+ const certs = {};
419
+ for (const { goal, c, gg } of built) {
420
+ const t0 = clock(), viaPart = gg && part?.gg === gg ? ptime('part', () => {
421
+ 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
+ return w ? { tree: w, nodes: 0 } : undefined;
423
+ }) : undefined;
424
+ 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)) {
426
+ dumped++;
427
+ countsDump.on({ law: law.name, goal: goal.name, ls: ls.map(l => l.name), stuck: o.stuck, hyps: gg.hyps });
428
+ }
429
+ 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`);
431
+ // (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) {
433
+ const asked = ptime('mbqi', () => modelInstances(m, ls, at, gg, o.witness));
434
+ if (asked) {
435
+ 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;
292
439
  }
293
- certs[goal.name] = { reads: c.reads, insts: c.insts, tree: o.tree };
294
440
  }
295
- if (ok)
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
+ }
447
+ certs[goal.name] = { reads: c.reads, insts: c.insts, tree: o.tree };
448
+ }
449
+ return { instances: at, certs };
450
+ }
451
+ };
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)
296
474
  break;
475
+ out.add(l);
476
+ grew = true;
297
477
  }
298
- if (!ok)
299
- failed.add(law.name);
478
+ for (const l of layer)
479
+ if (out.has(l))
480
+ for (const q of mapsOf(l))
481
+ seen.add(q);
300
482
  }
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' };
483
+ return set.filter(l => out.has(l));
484
+ };
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();
304
535
  }
536
+ if (env.GDP_COUNTS_TRACE)
537
+ console.error(`counts: kept ${kept.size} of ${set.length} in ${Math.round(clock() - t1)} ms`);
538
+ 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
+ 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());
542
+ for (let round = 0; clock() < until; round++) {
543
+ const { instances, certs } = keptProof(), failed = new Set();
544
+ // (the callers last, so they meet every support kept so far)
545
+ for (const law of [...set.filter(l => !caller.includes(l)), ...set.filter(l => caller.includes(l))]) {
546
+ if (clock() > until)
547
+ return { proven: false, laws: set, m, why: 'time' };
548
+ if (kept.has(law.name))
549
+ continue;
550
+ const pr = attempt(law, set, 0, 10_000) ?? (counted ? attempt(law, set, 1, 10_000) : undefined);
551
+ if (!pr) {
552
+ failed.add(law.name);
553
+ continue;
554
+ }
555
+ instances[law.name] = pr.instances;
556
+ Object.assign(certs, pr.certs);
557
+ }
558
+ if (env.GDP_COUNTS_TRACE)
559
+ console.error(`counts: round ${round}: ${set.length} laws, ${kept.size} kept, failed ${[...failed].join('; ').slice(0, 600)}`);
560
+ if (!failed.size)
561
+ return finish(set, { instances, certs });
305
562
  if (caller.some(l => failed.has(l.name)) && set.length === caller.length)
306
563
  return { proven: false, laws: set, m, why: `not proven: ${[...failed].join(', ')}` };
307
564
  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
565
+ // (only callers fail: drop nothing more, give up)
566
+ if (next.length === set.length)
310
567
  return { proven: false, laws: set, m, why: `not proven: ${[...failed].join(', ')}` };
311
- }
312
568
  set = next;
313
569
  }
314
570
  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
@@ -823,7 +823,7 @@ export function extractSolidity(at, opts = {}) {
823
823
  // (the check's probes: the branches' conditions, each a state and request the prover finds; a revert's condition
824
824
  // holds at no step the rule takes, and a contract's rule is large)
825
825
  const havoc = Object.fromEntries(meta.fields.filter(f => meta.nested.includes(f.name)).map(f => [f.name, f.t.val.k === 'bool' ? 'bool' : 'int']));
826
- const o = { ...opts, methods, strict: true, onError: 'discard', entry: meta.contract, check: { probes: 'writes', ...opts.check }, answers: { ...havoc, ...opts.answers } };
826
+ const o = { ...opts, methods, share: opts.share ?? true, strict: true, onError: 'discard', entry: meta.contract, check: { probes: 'writes', ...opts.check }, answers: { ...havoc, ...opts.answers } };
827
827
  // extractStep's run, the width's param fixed for the check's own draws (2^52: the proof is for every width)
828
828
  const notes = [];
829
829
  let read;
@@ -195,6 +195,7 @@ export type StepOptions = {
195
195
  domains?: Record<string, 'nat' | 'int'>;
196
196
  defaults?: string[];
197
197
  fields?: Record<string, null | boolean | number | string>;
198
+ share?: boolean;
198
199
  check?: {
199
200
  runs?: number;
200
201
  depth?: number;
@@ -586,6 +587,7 @@ export declare class Stepper {
586
587
  intTy(t: SType): IntTy | undefined;
587
588
  typed(v: Var, t: SType | IntTy, role: Var['role'], sel?: I.B): void;
588
589
  sel: B;
590
+ shared: Map<string, [V, PArg]>;
589
591
  clock(at: {
590
592
  p: string;
591
593
  }, p: Path): [V, Path];
@@ -240,6 +240,8 @@ export class Stepper {
240
240
  this.refusals.push(I.and(sel, I.cmp('<', x, I.num(0))));
241
241
  }
242
242
  sel = I.T;
243
+ // (StepOptions.share: each shared input by its type and place, made at its first method)
244
+ shared = new Map();
243
245
  // The clock: one input a step.
244
246
  clock(at, p) {
245
247
  // (read again in the step: the same time, as the check's clock gives it; the step taken to run within one tick)
@@ -4766,8 +4768,24 @@ function readOnce(mod, opts, g) {
4766
4768
  refuse(fn, `${fn.name}: a method that takes self by value (it consumes the object)`);
4767
4769
  if (fn.generic)
4768
4770
  refuse(fn, `${fn.name}: a generic method`);
4771
+ const kth = new Map();
4769
4772
  for (const pa of fn.params.filter(x => !x.self && !x.star)) {
4770
- const [v, a] = g.input(`${names.length > 1 ? `${fn.name}_` : ''}${pa.name}`, pa.t, fn, p);
4773
+ const s = opts.share && names.length > 1 ? g.scalar(pa.t) : undefined, ty = JSON.stringify(pa.t), k = kth.get(ty) ?? 0;
4774
+ kth.set(ty, k + 1);
4775
+ // (shared: named by the argument where every method names its k-th of the type alike, else by the type and k)
4776
+ const at = s && chosen.map(f => f.params.filter(x => !x.self && !x.star && JSON.stringify(x.t) === ty)[k]?.name).filter(Boolean);
4777
+ const it = pa.t;
4778
+ const nm = at ? (at.every(x => x === pa.name) ? pa.name : `${it.k === 'int' ? `${it.signed ? '' : 'u'}int${it.bits || ''}` : it.k}_${k}`) : `${names.length > 1 ? `${fn.name}_` : ''}${pa.name}`;
4779
+ const had = at ? g.shared.get(`${ty} ${k}`) : undefined;
4780
+ if (had && had[1].k === 'in') {
4781
+ g.typed(g.vars.get(had[1].name), pa.t, 'input');
4782
+ args.push(had[0]);
4783
+ pargs.push([pa.name, had[1]]);
4784
+ continue;
4785
+ }
4786
+ const [v, a] = g.input(nm, pa.t, fn, p);
4787
+ if (at)
4788
+ g.shared.set(`${ty} ${k}`, [v, a]);
4771
4789
  args.push(v);
4772
4790
  pargs.push([pa.name, a]);
4773
4791
  }
@@ -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.41.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",