gdp-wired 0.36.0 → 0.37.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,12 +1,9 @@
1
- import { type C, type E, type Law, type Machine, type State } from './machine.js';
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
- type Env = Record<string, number>;
4
3
  export declare function guardLaws(m: Machine): {
5
4
  counts: Machine['counts'];
6
5
  laws: Law[];
7
6
  };
8
- export declare function pairLaws(m: Machine): Law[];
9
- export declare function small(m: Machine, p: Env, b: number, cap?: number): State[];
10
7
  export declare function certFor(goal: {
11
8
  hyps: C[];
12
9
  }, decls: {
@@ -17,6 +14,7 @@ export declare function certFor(goal: {
17
14
  insts: CountInst[];
18
15
  wits: string[];
19
16
  };
17
+ export declare function matched(names: string[], body: C, cells: [string, E][], cap?: number): E[][];
20
18
  export type Counted = {
21
19
  proven: boolean;
22
20
  laws: Law[];
@@ -28,4 +26,3 @@ export type Counted = {
28
26
  why?: string;
29
27
  };
30
28
  export declare function searchCounted(m0: Machine, caller: Law[], ms?: number): Counted;
31
- export {};
@@ -1,21 +1,12 @@
1
- // The search for a machine with counts (Machine.counts; the kernel's countedObligations and checkCountedLaws, Lean's
2
- // CountMachine.lean): untrusted. It proposes laws that read counts of the state, filters every candidate on the small
3
- // instances' reachable states, and keeps the largest set the kernel accepts (Houdini), each goal's certificate built
4
- // here: the count cells the goal reads, Count.lean's instances over pairs of them, and the laws and quantified flags at
5
- // the instances' witnesses.
6
- // - The guard's shape: a step writes P[t] where a quantified flag says every member of a set the request counts
7
- // satisfies R(member, t), and the assumption compares that count with a bound (2·|Q| > size, |Q| ≥ n − t, …). Then
8
- // a state count c_R(x) = |{k < bound: R(k, x)}| is declared, and P[a] ⇒ the same comparison with c_R[a] for |Q| is
9
- // proposed: what every majority, quorum or threshold protocol keeps of its decisions.
10
- // - A guard comparing a state count at the written key (2·voters[n] > size, Leader[n] := 1): P[a] ⇒ that comparison
11
- // at a.
12
- // - Each map's cells at most what the small instances reach.
13
- import { carriedView, evalC, interpret } from "./machine.js";
14
- import { checkCountedLaws, countedObligations, mcGoal, substC } from "../kernel/kernel.js";
1
+ import { assumed, checkCountedLaws, countedObligations, mcGoal, substC } from "../kernel/kernel.js";
15
2
  import { clock, grow } from "../kernel/prove.js";
3
+ import { REFUTED, growCdcl } from "../kernel/cdcl.js";
4
+ import { inferLaws } from "./infer.js";
5
+ import { holdsAt, small } from "./exists.js";
16
6
  import { env } from "./solver.js";
17
7
  const v = (name) => ({ op: 'var', name }), k = (value) => ({ op: 'const', value });
18
8
  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) };
19
10
  const one = k(1), zero = k(0);
20
11
  // Every term t with `get(map, t)` in t0.
21
12
  function reads(t0, map, out = new Map()) {
@@ -79,69 +70,6 @@ export function guardLaws(m) {
79
70
  }
80
71
  return { counts, laws };
81
72
  }
82
- // --- relations over pairs: one value per first key, and one relation inside another ---------------------------------
83
- // A map written at x·N + y (a relation, x's row) is a candidate for "at most one y in a row", and each two such maps for
84
- // "one holds where the other does", at the same pair or the swapped one; the small instances keep the true ones.
85
- export function pairLaws(m) {
86
- const widths = new Map();
87
- for (const [mp, w] of Object.entries(m.step.maps ?? {}))
88
- if (!('each' in w) && w.key.op === 'add' && w.key.a.op === 'mul' && w.key.a.a.op === 'var' && w.key.b.op === 'var')
89
- widths.set(mp, w.key.a.k);
90
- const at = (mp, x, y, n) => ({ op: 'get', map: mp, key: { op: 'add', a: { op: 'mul', k: n, a: v(x) }, b: v(y) } });
91
- const has = (e) => ({ op: '<=', a: one, b: e }), lt = (x, n) => ({ op: '<', a: v(x), b: k(n) });
92
- const out = [];
93
- for (const [mp, n] of widths)
94
- out.push({ name: `${mp}: one per row`, forall: 'p$c', keys: ['q$c', 'r$c'], holds: { op: 'or', xs: [{ op: 'not', x: { op: 'and', xs: [lt('q$c', n), lt('r$c', n), has(at(mp, 'p$c', 'q$c', n)), has(at(mp, 'p$c', 'r$c', n))] } }, { op: '=', a: v('q$c'), b: v('r$c') }] } });
95
- for (const [a, n] of widths)
96
- for (const [b, n2] of widths)
97
- if (a !== b && n === n2)
98
- for (const swap of [false, true])
99
- out.push({ name: `${a} inside ${b}${swap ? ', swapped' : ''}`, forall: 'p$c', keys: ['q$c'], holds: { op: 'or', xs: [{ op: 'not', x: { op: 'and', xs: [lt('q$c', n), lt('p$c', n), has(at(a, 'p$c', 'q$c', n))] } }, has(swap ? at(b, 'q$c', 'p$c', n) : at(b, 'p$c', 'q$c', n))] } });
100
- // (and over one key: where one map's cell is set, another's is)
101
- const singles = Object.entries(m.step.maps ?? {}).filter(([, w]) => !('each' in w) && w.key.op === 'var').map(([mp]) => mp);
102
- for (const a of singles)
103
- for (const b of singles)
104
- if (a !== b)
105
- out.push({ name: `${a} inside ${b}`, forall: 'p$c', holds: { op: 'or', xs: [{ op: 'not', x: has({ op: 'get', map: a, key: v('p$c') }) }, has({ op: 'get', map: b, key: v('p$c') })] } });
106
- return out;
107
- }
108
- // --- the small instances --------------------------------------------------------------------------------------------------
109
- // Every state reached from the start with the params at `p`, each input below `b`, each carried map a subset of 0 .. b − 1.
110
- export function small(m, p, b, cap = 3000) {
111
- const run = interpret(m), start = run.init(p);
112
- 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])));
113
- let reqs = [{}];
114
- for (const i of m.inputs)
115
- reqs = reqs.flatMap(r => Array.from({ length: b }, (_, x) => ({ ...r, [i]: x })));
116
- for (const c of m.inputMaps ?? [])
117
- reqs = reqs.flatMap(r => subsets.map(s => ({ ...r, [c]: s })));
118
- const seen = new Map([[json(start), start]]), queue = [start];
119
- while (queue.length && seen.size < cap) {
120
- const st = queue.shift();
121
- for (const r of reqs) {
122
- let next;
123
- try {
124
- next = run.step(p, st, r);
125
- }
126
- catch {
127
- continue;
128
- }
129
- const key = json([next.scalars, Object.entries(next.maps).map(([n, cs]) => [n, [...cs].filter(([, x]) => x).sort((a, c) => a[0] - c[0])])]);
130
- if (!seen.has(key)) {
131
- seen.set(key, next);
132
- queue.push(next);
133
- }
134
- }
135
- }
136
- return [...seen.values()];
137
- }
138
- // A law at a state, its counts the state's, at every key below b.
139
- function holdsAt(m, law, p, st, b) {
140
- const empty = Object.fromEntries((m.inputMaps ?? []).map(c => [c, new Map()]));
141
- const view = carriedView(m, st, empty, undefined, p), keys = [law.forall, ...(law.keys ?? [])].filter((x) => !!x);
142
- const go = (env, ks) => (ks.length ? Array.from({ length: b }, (_, x) => x).every(x => go({ ...env, [ks[0]]: x }, ks.slice(1))) : evalC(law.holds, { ...env, ...st.scalars }, view, m));
143
- return go({ ...p }, keys);
144
- }
145
73
  // --- a goal's certificate -------------------------------------------------------------------------------------------------
146
74
  // The count cells the goal reads (each before the step with its post name's twin), instances over pairs of them with one
147
75
  // bound (a count that doesn't drop, +1 and −1; two that meet, +1, +1 and −1), each with a fresh witness; and the laws and
@@ -179,6 +107,78 @@ export function certFor(goal, decls) {
179
107
  add([[1, a[0]], [1, c[0]]], -1, byMap.get(a[1]).below);
180
108
  return { reads: named, insts: insts.slice(0, 10), wits: wits.slice(0, 10) };
181
109
  }
110
+ // --- instances by the goal's own reads (E-matching, as an SMT solver instantiates a quantifier) ------------------------
111
+ // A law over keys (and a quantified flag) is assumed at the tuples where its map reads meet the cells the goal reads: each
112
+ // 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
113
+ // witness included), the tuples one read or two cover; the goal regrown with them, twice at most.
114
+ const ground = (t0, out = new Map()) => {
115
+ const go = (x) => {
116
+ if (!x || typeof x !== 'object')
117
+ return;
118
+ const o = x;
119
+ if (o.op === 'all')
120
+ return;
121
+ if (o.op === 'get')
122
+ out.set(json([o.map, o.key]), [o.map, o.key]);
123
+ for (const y of Object.values(o))
124
+ go(y);
125
+ };
126
+ go(t0);
127
+ return out;
128
+ };
129
+ // (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
130
+ // is assumed where the goal's cases make them equal)
131
+ function bindKey(p, g, names, b, alt) {
132
+ if (p.op === 'var' && names.includes(p.name)) {
133
+ const x = b[p.name];
134
+ if (!x) {
135
+ b[p.name] = g;
136
+ return true;
137
+ }
138
+ if (json(x) === json(g))
139
+ return true;
140
+ if (!alt || alt[p.name])
141
+ return false;
142
+ alt[p.name] = g;
143
+ return true;
144
+ }
145
+ if (p.op !== g.op)
146
+ return false;
147
+ const q = g;
148
+ switch (p.op) {
149
+ case 'add':
150
+ case 'sub':
151
+ case 'min':
152
+ case 'max':
153
+ case 'prod': return bindKey(p.a, q.a, names, b, alt) && bindKey(p.b, q.b, names, b, alt);
154
+ case 'mul': return p.k === q.k && bindKey(p.a, q.a, names, b, alt);
155
+ case 'var':
156
+ case 'const':
157
+ case 'get':
158
+ case 'if': return json(p) === json(g);
159
+ }
160
+ }
161
+ export function matched(names, body, cells, cap = knob.cap) {
162
+ const pats = [...reads(body, () => true).values()].filter(([, key]) => names.some(nm => mentions(key, nm)));
163
+ 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 }))] : []; }));
164
+ const out = new Map();
165
+ const put = (b) => { if (names.every(nm => b[nm])) {
166
+ const t = names.map(nm => b[nm]);
167
+ out.set(json(t), t);
168
+ } };
169
+ for (const [i, bs] of per.entries())
170
+ for (const b of bs) {
171
+ put(b);
172
+ for (const c of per.slice(i + 1).flat()) {
173
+ if (out.size >= cap)
174
+ break;
175
+ const m2 = { ...b };
176
+ if (Object.entries(c).every(([nm, t]) => !m2[nm] || json(m2[nm]) === json(t)))
177
+ put(Object.assign(m2, c));
178
+ }
179
+ }
180
+ return [...out.values()].slice(0, cap);
181
+ }
182
182
  export function searchCounted(m0, caller, ms = 60_000) {
183
183
  const until = clock() + ms, g = guardLaws(m0), m = { ...m0, counts: { ...m0.counts, ...g.counts } };
184
184
  // The small instances: each param 2 and 3 (where the precondition allows), inputs and sets below 3.
@@ -195,43 +195,94 @@ export function searchCounted(m0, caller, ms = 60_000) {
195
195
  const most = Math.max(0, ...states.flatMap(({ sts }) => sts.flatMap(st => [...(st.maps[mp]?.values() ?? [])])));
196
196
  return { name: `${mp} at most ${most}`, forall: 'a$c', holds: { op: '<=', a: { op: 'get', map: mp, key: v('a$c') }, b: k(most) } };
197
197
  });
198
- const trueAll = (l) => states.every(({ p, sts }) => sts.every(st => holdsAt(m, l, p, st, 4)));
198
+ const trueAll = (l) => clock() < until && states.every(({ p, sts }) => sts.every(st => holdsAt(m, l, p, st, 4)));
199
199
  if (!caller.every(trueAll))
200
- return { proven: false, laws: caller, m, why: 'a law fails on the small instances' };
201
- let set = [...caller, ...[...kinds, ...pairLaws(m), ...g.laws].filter(trueAll)];
200
+ return { proven: false, laws: caller, m, why: clock() < until ? 'a law fails on the small instances' : 'time' };
201
+ // (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);
203
+ if (env.GDP_COUNTS_TRACE)
204
+ 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)];
202
206
  if (env.GDP_COUNTS_TRACE)
203
207
  console.error(`counts: candidates ${set.map(l => l.name).join('; ')}`);
204
208
  for (let round = 0; clock() < until; round++) {
205
- const terms = (l) => [...(l.forall ? [v(`${l.forall}#`)] : []), ...(l.keys ?? []).map(v), ...m.inputs.map(v)];
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)];
206
213
  const instances = {}, certs = {}, failed = new Set();
207
214
  for (const law of set) {
208
215
  if (clock() > until)
209
216
  return { proven: false, laws: set, m, why: 'time' };
210
217
  const ts = terms(law);
211
- const inst = (wits) => {
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 = () => {
212
221
  const out = {};
213
222
  for (const l of set) {
214
- if (l.keys?.length === 1)
223
+ if (l.keys?.length === 1 && knob.pairs)
215
224
  out[l.name] = ts.flatMap(x => ts.flatMap(y => (json(x) === json(y) ? [] : [x, y])));
216
- else if (l.keys?.length === 2)
217
- out[l.name] = ts.flatMap(x => ts.flatMap(y => ts.flatMap(z => (json(y) === json(z) ? [] : [x, y, z]))));
218
- else if (l.forall)
219
- out[l.name] = [...ts, ...wits.map(v)];
225
+ else if (!l.keys?.length && l.forall && knob.ts)
226
+ out[l.name] = [...ts];
220
227
  }
221
228
  for (const [f, q] of Object.entries(m.step.flags ?? {}))
222
229
  if (q.op === 'all' && !q.keys?.length)
223
- out[`?${f}`] = [...wits.map(v), ...m.inputs.map(v)];
230
+ out[`?${f}`] = knob.flagTs ? ts : m.inputs.map(v);
224
231
  return out;
225
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;
255
+ };
226
256
  // The goals' certificates: first with no instances of the lemma, then with the cells' (one set of witnesses a law).
227
257
  let ok = true;
228
258
  for (const pass of [0, 1]) {
229
- const wits0 = pass ? Array.from({ length: 10 }, (_, i) => `w$${i}`) : [];
230
- instances[law.name] = inst(wits0);
259
+ instances[law.name] = inst();
231
260
  ok = true;
232
- for (const { goal, decls } of countedObligations(m, set, instances, set.indexOf(law))) {
233
- const c = pass ? certFor(goal, decls) : { reads: [], insts: [] };
234
- const gg = mcGoal(goal.hyps, decls, c);
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)))
268
+ break;
269
+ }
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) }));
283
+ }
284
+ }
285
+ for (const { goal, c, gg } of built) {
235
286
  const o = gg && grow(gg, new Map(), { nodes: 0, until: Math.min(until, clock() + 10_000) });
236
287
  if (!o || !('tree' in o)) {
237
288
  ok = false;
@@ -6,6 +6,8 @@ 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[];
10
+ export declare function holdsAt(m: Machine, law: Law, p: Env, st: State, b: number): boolean;
9
11
  export declare function someHolds(body: C, vars: string[], env: Env, st: State, m: Machine): {
10
12
  holds: boolean;
11
13
  witness?: Env;
@@ -14,9 +14,10 @@
14
14
  // value before, shifts of it, the request's values and the state before; each is chosen to satisfy P at every
15
15
  // counterexample so far, per case of the step (the conditions its updates split on: the request's clause, say).
16
16
  // A law under a `forall` key takes witness terms only (a ghost per key would be a map).
17
- import { evalC, evalE, n as k, walk, x as v } from "./machine.js";
18
- import { clock, proveLaw, proveLaws, withinDeadline } from "../kernel/prove.js";
17
+ import { carriedView, evalC, evalE, interpret, n as k, walk, x as v } from "./machine.js";
18
+ import { clock, proveLaw, proveLaws, withDeadline, withinDeadline } from "../kernel/prove.js";
19
19
  import { env } from "./solver.js";
20
+ import { ghostedMachine, ghostedOk, substC } from "../kernel/kernel.js";
20
21
  const add = (a, b) => (a.op === 'const' && a.value === 0 ? b : b.op === 'const' && b.value === 0 ? a : { op: 'add', a, b });
21
22
  const sum = (es) => es.reduce((acc, e) => add(acc, e), k(0));
22
23
  const sub = (a, b) => (b.op === 'const' && b.value === 0 ? a : { op: 'sub', a, b });
@@ -152,6 +153,54 @@ function solved(atoms, g) {
152
153
  }
153
154
  return out;
154
155
  }
156
+ const atomsOf2 = (c) => (c.op === 'and' || c.op === 'or' ? c.xs.flatMap(atomsOf2) : c.op === 'not' ? atomsOf2(c.x) : [c]);
157
+ // --- the small instances (core/counts.ts's filter and the ghost maps' below) --------------------------------------------------------------------------------------------------
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) {
161
+ const run = interpret(m), start = run.init(p);
162
+ 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
+ // (an input the assumption keeps below a few values, an action's, over all of them; the rest below b)
164
+ const below = (i) => Math.max(b, ...(m.assume ? atomsOf2(m.assume) : []).flatMap(c => (c.op === '<' && c.a.op === 'var' && c.a.name === i && c.b.op === 'const' && c.b.value <= 8 ? [c.b.value] : [])));
165
+ let reqs = [{}];
166
+ for (const i of m.inputs)
167
+ reqs = reqs.flatMap(r => Array.from({ length: below(i) }, (_, x) => ({ ...r, [i]: x })));
168
+ for (const c of m.inputMaps ?? [])
169
+ reqs = reqs.flatMap(r => subsets.map(s => ({ ...r, [c]: s })));
170
+ const seen = new Map([[key(start), start]]), queue = [start];
171
+ while (queue.length && seen.size < cap && work > 0) {
172
+ const st = queue.shift();
173
+ for (const r of reqs) {
174
+ if (--work < 0)
175
+ break;
176
+ let next;
177
+ try {
178
+ next = run.step(p, st, r);
179
+ }
180
+ catch {
181
+ continue;
182
+ }
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])])]);
184
+ if (!seen.has(id)) {
185
+ seen.set(id, next);
186
+ queue.push(next);
187
+ }
188
+ }
189
+ }
190
+ return [...seen.values()];
191
+ }
192
+ // A law at a state, its counts the state's, at every key below b.
193
+ // (a state's view once: a law is read at every state, and every law at each)
194
+ const views = new WeakMap();
195
+ export function holdsAt(m, law, p, st, b) {
196
+ const empty = Object.fromEntries((m.inputMaps ?? []).map(c => [c, new Map()]));
197
+ let view = views.get(st);
198
+ if (!view)
199
+ views.set(st, (view = carriedView(m, st, empty, undefined, p)));
200
+ const keys = [law.forall, ...(law.keys ?? [])].filter((x) => !!x);
201
+ const go = (env, ks) => (ks.length ? Array.from({ length: b }, (_, x) => x).every(x => go({ ...env, [ks[0]]: x }, ks.slice(1))) : evalC(law.holds, { ...env, ...st.scalars }, view, m));
202
+ return go({ ...p }, keys);
203
+ }
155
204
  // --- evaluating ∃ on a state ----------------------------------------------------------------------------------------
156
205
  // Whether ∃ vars. P holds where env and st give every other value, with a witness: exact when the bound values are one
157
206
  // natural or one integer read linearly (P's truth changes only next to the values its atoms solve for, so those, their
@@ -359,14 +408,75 @@ function planOf(m, law) {
359
408
  groups.forEach((g, i) => { terms[i] = [g.map(n => w.terms[n] ?? k(0))]; });
360
409
  if (w?.ghost)
361
410
  groups.forEach((g, i) => { starts[i] = [g.map(n => w.ghost[n]?.start ?? k(0))]; steps[i] = [g.map(n => w.ghost[n]?.step ?? v(n))]; });
362
- return { law, groups, terms, starts, steps, pick: w?.ghost ? { mode: 'ghost', start: groups.map(() => 0), cases: new Map() } : { mode: 'term', at: groups.map(() => 0) }, seen: { term: [], start: [], step: new Map() }, given };
411
+ return { law, groups, terms, starts, steps, maps: [], pick: w?.ghost ? { mode: 'ghost', start: groups.map(() => 0), cases: new Map() } : { mode: 'term', at: groups.map(() => 0) }, seen: { term: [], start: [], step: new Map() }, given };
363
412
  }
413
+ function mapGhostsOf(m, law, taken) {
414
+ const x = law.some[0], names = [law.forall, ...(law.keys ?? [])];
415
+ const xs = law.holds.op === 'or' ? law.holds.xs : [law.holds], P = xs.filter(d => namesOf(d).includes(x)), rest = xs.filter(d => !namesOf(d).includes(x));
416
+ const guards = rest.flatMap(d => (d.op === 'not' ? (d.x.op === 'and' ? d.x.xs : [d.x]) : [])).filter(c => !readsMaps(c));
417
+ if (law.some.length !== 1 || x.endsWith('$neg') || !P.length)
418
+ return [];
419
+ const out = [];
420
+ for (const [mp, w] of Object.entries(m.step.maps ?? {})) {
421
+ if ('each' in w)
422
+ continue;
423
+ const kv = namesOf(w.key);
424
+ if (!kv.length || !kv.every(n => m.inputs.includes(n)) || kv.length > names.length)
425
+ continue;
426
+ const set = substC({ op: '<=', a: k(1), b: w.value }, { vars: {}, maps: { [mp]: () => k(0) }, flags: Object.fromEntries(Object.keys(m.step.flags ?? {}).map(f => [f, { op: 'flag', name: f }])) });
427
+ // (each write key's input at a different one of the law's keys)
428
+ const injections = kv.reduce((acc) => acc.flatMap(a => names.filter(n => !a.includes(n)).map(n => [...a, n])), [[]]);
429
+ // (a value an action selects, compared with constants alone, is no witness)
430
+ const keyed = new Set();
431
+ walk([m.step, m.assume ?? null], o => { if (o.op === 'get')
432
+ for (const n of namesOf(o.key))
433
+ keyed.add(n); });
434
+ for (const w2 of Object.values(m.step.maps ?? {}))
435
+ if (!('each' in w2))
436
+ for (const n of namesOf(w2.key))
437
+ keyed.add(n);
438
+ const action = (i) => !keyed.has(i);
439
+ for (const inj of injections)
440
+ for (const val of m.inputs.filter(i => !kv.includes(i) && !action(i))) {
441
+ let name = `${mp}$w`;
442
+ for (let j = 2; taken.has(name); j++)
443
+ name = `${mp}$w${j}`;
444
+ const at = substVarsE(w.key, Object.fromEntries(kv.map((n, j) => [n, v(inj[j])]))), atW = { op: 'get', map: name, key: at };
445
+ const Pw = substVars(P.length === 1 ? P[0] : { op: 'or', xs: P }, { [x]: atW }), has = { op: '<=', a: k(1), b: { op: 'get', map: mp, key: at } };
446
+ out.push({ name, write: { key: w.key, value: { op: 'if', c: set, then: v(val), else: { op: 'get', map: name, key: w.key } } }, at,
447
+ holds: substVars(law.holds, { [x]: atW }),
448
+ inv: { name: `${law.name}: ${name} where ${mp} is set`, forall: law.forall, ...(law.keys ? { keys: law.keys } : {}), holds: { op: 'or', xs: [{ op: 'not', x: { op: 'and', xs: [...guards, has] } }, Pw] } } });
449
+ }
450
+ }
451
+ return out;
452
+ }
453
+ const takenOf = (m) => new Set([...Object.keys(m.maps ?? {}), ...(m.inputMaps ?? []), ...Object.keys(m.fns ?? {})]);
454
+ const firstPicks = new Map();
455
+ // The machine with a ghost map (kernel.ts's ghostedMachine of Ghosted, whose ghostedOk it must pass).
456
+ const withMap = (m, g) => {
457
+ const o = { orig: m, vars: {}, maps: { [g.name]: { start: 0, write: g.write } } };
458
+ if (!ghostedOk(o))
459
+ throw new Error(`${g.name}: not a ghost of ${m.name}`);
460
+ return ghostedMachine(o);
461
+ };
364
462
  // The machine with every ghost the plans have chosen, and each law as the kernel proves it.
365
- function built(m, plans, cases) {
463
+ function built(m0, plans, cases) {
464
+ let m = m0;
465
+ const invs = [];
466
+ for (const p of plans)
467
+ if (p.pick.mode === 'map') {
468
+ const g = p.maps[p.pick.at];
469
+ m = withMap(m, g);
470
+ invs.push(g.inv);
471
+ }
366
472
  const state = { ...m.state }, step = { ...m.step.state }, ghosts = [];
367
473
  const laws = plans.map(p => {
368
474
  const { law } = p, ex = { vars: law.some, body: law.holds };
369
475
  const plain = { name: law.name, holds: law.holds, ...(law.forall ? { forall: law.forall } : {}), ...(law.keys ? { keys: law.keys } : {}), stated: law.stated ?? law.holds };
476
+ if (p.pick.mode === 'map') {
477
+ const g = p.maps[p.pick.at];
478
+ return { ...plain, holds: g.holds, ex: { ...ex, map: { name: g.name, at: g.at } } };
479
+ }
370
480
  if (p.pick.mode === 'term') {
371
481
  const pick = p.pick.at, sub = {};
372
482
  p.groups.forEach((g, i) => g.forEach((n, j) => { sub[n] = p.terms[i][pick[i]][j]; }));
@@ -381,7 +491,7 @@ function built(m, plans, cases) {
381
491
  }));
382
492
  return { ...plain, ex: { ...ex, ghost: true } };
383
493
  });
384
- return { machine: { ...m, state, step: { ...m.step, state: step } }, laws, ghosts };
494
+ return { machine: { ...m, state, step: { ...m.step, state: step } }, laws, ghosts, invs };
385
495
  }
386
496
  // A state's values for every name, 0 for a name it doesn't give (as the prover reads a model).
387
497
  const total = (w) => new Proxy(w, { get: (t, n) => (typeof n === 'string' ? (t[n] ?? 0) : undefined) });
@@ -474,15 +584,71 @@ export function proveSome(m, laws, opts = {}) {
474
584
  const current = () => {
475
585
  const b = built(m, [...plans.values()], cases);
476
586
  const out = laws.map((l, i) => (plans.has(i) ? b.laws[[...plans.keys()].indexOf(i)] : l));
477
- return { machine: b.machine, laws: out, ghosts: b.ghosts };
587
+ return { machine: b.machine, laws: [...out, ...b.invs], ghosts: b.ghosts };
478
588
  };
479
589
  const rounds = opts.rounds ?? 24;
590
+ // (a law about every key with no witness term: the next ghost map past `from` that keeps its law and the ghost's own
591
+ // on every state of the small instances, each param 2 and 3)
592
+ const smallOk = (mm, ls) => [2, 3].every(x => { const ps = Object.fromEntries(m.params.map(q => [q, x])); return small(mm, ps, 2, 1500, 100_000).every(st => ls.every(l => holdsAt(mm, l, ps, st, 2))); });
593
+ const toMap = (p, from) => {
594
+ if (from < 0)
595
+ p.maps = mapGhostsOf(m, p.law, takenOf(m));
596
+ const others = [...plans.values()].filter(q => q !== p && q.pick.mode === 'map');
597
+ for (let j = from + 1; j < p.maps.length; j++) {
598
+ const g = p.maps[j];
599
+ try {
600
+ const mm = withMap(others.reduce((acc, q) => withMap(acc, q.maps[q.pick.at]), m), g);
601
+ const ok = smallOk(mm, [g.inv, { ...p.law, holds: g.holds, some: undefined }]);
602
+ if (log)
603
+ console.error(`exists: map ${g.name} at ${showE(g.at)} := ${showE(g.write.value)}: ${ok ? 'kept' : 'false on the small instances'}`);
604
+ if (ok) {
605
+ p.pick = { mode: 'map', at: j };
606
+ return true;
607
+ }
608
+ }
609
+ catch (e) {
610
+ if (log)
611
+ console.error(`exists: map ${g.name}: ${String(e).slice(0, 120)}`);
612
+ }
613
+ }
614
+ return false;
615
+ };
480
616
  const log = env.GDP_EXISTS_LOG === '1';
481
617
  // Each law's witness until its goals are proven with every law assumed (choose); then the whole set, and where a
482
618
  // later choice broke a law proven before (a witness term is a hypothesis of every law), that law's again.
483
619
  const choose = (i, p, pass, first) => {
620
+ // (a law about every key over maps, one value bound: its first witness term one the small instances keep, else a
621
+ // ghost map at once; none of either, no witness)
622
+ if (p.law.forall && !p.given && p.groups.length === 1 && p.groups[0].length === 1 && mapsRead(p.law) && p.pick.mode === 'term' && !first) {
623
+ // (the first pick a machine's law got, again: a search asks the same law with each candidate set)
624
+ const id = key([m.step, m.assume ?? null, m.maps ?? null, p.law.holds]), had = firstPicks.get(id);
625
+ if (had?.mode === 'map') {
626
+ p.maps = mapGhostsOf(m, p.law, takenOf(m));
627
+ p.pick = { ...had };
628
+ }
629
+ else if (had)
630
+ p.pick = { mode: 'term', at: [...had.at] };
631
+ }
632
+ if (p.law.forall && !p.given && p.groups.length === 1 && p.groups[0].length === 1 && mapsRead(p.law) && p.pick.mode === 'term' && !first && !firstPicks.has(key([m.step, m.assume ?? null, m.maps ?? null, p.law.holds]))) {
633
+ const x = p.groups[0][0], at = p.terms[0].findIndex(t => { try {
634
+ return smallOk(m, [{ ...p.law, holds: substVars(p.law.holds, { [x]: t[0] }), some: undefined }]);
635
+ }
636
+ catch {
637
+ return false;
638
+ } });
639
+ if (log)
640
+ console.error(`exists: first term on the small instances: ${at < 0 ? 'none' : describe({ ...p, pick: { mode: 'term', at: [at] } }, cases)}`);
641
+ if (at >= 0)
642
+ p.pick = { mode: 'term', at: [at] };
643
+ else if (!toMap(p, -1))
644
+ return { proven: false, nodes: 0, leaves: 0, checked: false, failed: { goal: `${p.law.name} @step`, stuck: 'unknown', why: `no witness for "${p.law.name}" holds on the small instances` } };
645
+ const pk = p.pick;
646
+ firstPicks.set(key([m.step, m.assume ?? null, m.maps ?? null, p.law.holds]), pk.mode === 'map' ? { mode: 'map', at: pk.at } : { mode: 'term', at: [...pk.at] });
647
+ }
484
648
  for (let round = 0;; round++) {
485
- const now = current(), t0 = performance.now(), r = round === 0 && first ? { proven: false, ...first } : proveLaw(now.machine, now.laws, i);
649
+ const now = current(), t0 = performance.now(), r = round === 0 && first ? { proven: false, ...first }
650
+ // (a ghost map's goals within 2 s: a search asks them with every candidate set, and one without its supports can take minutes)
651
+ : p.pick.mode === 'map' ? withDeadline(clock() + 2_000, () => proveLaw(now.machine, now.laws, i)) : proveLaw(now.machine, now.laws, i);
486
652
  if (log)
487
653
  console.error(`exists: pass ${pass} round ${round} "${p.law.name}" ${p.pick.mode} ${describe(p, cases).slice(0, 160)}: ${r.proven ? 'proven' : `${r.goal} ${r.stuck}`} (${Math.round(performance.now() - t0)} ms)`);
488
654
  if (r.proven)
@@ -500,6 +666,8 @@ export function proveSome(m, laws, opts = {}) {
500
666
  p.pick = { mode: 'ghost', start: p.groups.map(() => 0), cases: new Map() };
501
667
  continue;
502
668
  }
669
+ if (p.law.forall && !p.given && p.pick.mode !== 'ghost' && toMap(p, p.pick.mode === 'map' ? p.pick.at : -1))
670
+ continue;
503
671
  return fail(r.stuck);
504
672
  }
505
673
  const w = r.witness, atStart = r.goal.endsWith('@start'), blind = mapsRead(p.law);
@@ -529,8 +697,15 @@ export function proveSome(m, laws, opts = {}) {
529
697
  p.pick = { mode: 'ghost', start: p.groups.map(() => 0), cases: new Map() };
530
698
  continue;
531
699
  }
700
+ if (p.law.forall && !p.given && toMap(p, -1))
701
+ continue;
532
702
  return fail(`no witness term found for "${p.law.name}" (${r.goal}): name one (exists(kind, f, witness))`);
533
703
  }
704
+ if (p.pick.mode === 'map') {
705
+ if (toMap(p, p.pick.at))
706
+ continue;
707
+ return fail(`no ghost map found for "${p.law.name}" (${r.goal})`);
708
+ }
534
709
  if (atStart) {
535
710
  p.seen.start.push(after);
536
711
  const old = p.pick.start;
@@ -598,6 +773,10 @@ function describe(p, cases) {
598
773
  const at = p.pick.at;
599
774
  return p.groups.map((g, i) => `${name(g)} = ${show(p.terms[i][at[i]])}`).join(', ');
600
775
  }
776
+ if (p.pick.mode === 'map') {
777
+ const g = p.maps[p.pick.at];
778
+ return `${name(p.groups[0])} = ${g.name}[${showE(g.at)}], ${g.name}[${showE(g.write.key)}] := ${showE(g.write.value)}`;
779
+ }
601
780
  const { start, cases: cs } = p.pick;
602
781
  return p.groups.map((g, i) => `${name(g)} starts at ${show(p.starts[i][start[i]])}; after a step ${[...cs.entries()].filter(([c]) => c >= 0).map(([c, at]) => `${show(p.steps[i][at[i]])} where ${showC(cases[c])}`).join(', ')}${cs.size > (cs.has(-1) ? 1 : 0) ? ', else ' : ''}${show(p.steps[i][cs.get(-1)?.[i] ?? 0])}`).join('; ');
603
782
  }
@@ -15,6 +15,7 @@ export type InferOptions = {
15
15
  minimize?: boolean;
16
16
  remainders?: boolean;
17
17
  join?: number;
18
+ cubes?: number;
18
19
  };
19
20
  export type Found = {
20
21
  law: Law;
@@ -760,7 +760,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
760
760
  return verdictOf(out);
761
761
  };
762
762
  const stats = (samples, candidates, alive) => ({ samples, candidates, alive, proofs, ms: Math.round(performance.now() - t0), stopped: stop() });
763
- const first = opts.first ?? prove(laws);
763
+ const first = opts.first ?? (opts.cubes ? { proven: false, checked: false } : prove(laws));
764
764
  if ((first.proven && first.checked) || first.run)
765
765
  return { ...first, found: [], stats: stats(0, 0, 0) };
766
766
  // --- runs ------------------------------------------------------------------------------------------------------------
@@ -1018,7 +1018,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1018
1018
  // guard in one pass over (at most 1,500 of) the rows. Building candidates takes at most a quarter of the time.
1019
1019
  const guards = [...modes].sort((p, q) => Number(!!q.choice) - Number(!!p.choice) || Number(!!q.bool) - Number(!!p.bool)).slice(0, 8);
1020
1020
  const strideS = Math.max(1, Math.ceil(NS / 1500)), strideK = Math.max(1, Math.ceil(NK / 1500));
1021
- const buildUntil = Math.min(until, now() + (until - now()) / 4);
1021
+ const buildUntil = opts.cubes ? 0 : Math.min(until, now() + (until - now()) / 4);
1022
1022
  for (const [n_, { coef, cells }] of shapes.entries()) {
1023
1023
  if (forms.length > maxCandidates || (n_ % 256 === 0 && (now() > buildUntil || stop())))
1024
1024
  break;
@@ -1436,7 +1436,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1436
1436
  return false;
1437
1437
  }
1438
1438
  };
1439
- const houdiniUntil = Math.min(until, now() + Math.max(500, (until - now()) / 4));
1439
+ const houdiniUntil = opts.cubes ? 0 : Math.min(until, now() + Math.max(500, (until - now()) / 4));
1440
1440
  for (let quiet = 0; samples.length && now() < houdiniUntil && !stop() && quiet < 3;) {
1441
1441
  const killed = new Set();
1442
1442
  for (let tries = 0; tries < 400 && now() < houdiniUntil && !stop(); tries++) {
@@ -2173,7 +2173,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
2173
2173
  // (a step law's goal: its step from a state the set allows)
2174
2174
  const stepLawOf = new Map(stepLaws.map(sl => [sl.name, sl]));
2175
2175
  // (the engine runs after a join that finds nothing, on a rule whose scalars the runs held at few values: below)
2176
- let follows;
2176
+ let follows, cubesOut;
2177
2177
  const engineFollows = () => (follows ??= !!sorts && callerLaws.some(l => l.keys?.length) && atoms.every((a, i) => a.cell || a.param || !!a.term || a.view !== undefined || i >= valsS.length || new Set(valsS[i]).size <= 4));
2178
2178
  const stepWith = (name, form, ctx) => {
2179
2179
  const ctxLaws = [...ctx, ...(form ? [form] : [])].map(lawFor), ls = [...given, ...ctxLaws], mm = forLaws(ctxLaws).m, sl = form ? undefined : stepLawOf.get(name);
@@ -2728,10 +2728,10 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
2728
2728
  // few others that keep its facts on the sort's keys (its values reversed, and each turned by one), each run as its
2729
2729
  // own machine; their states' rows read under their table. One table alone is a fact of it, not of the rule: ring's
2730
2730
  // ids, every node past another one's below it)
2731
- const tables = [{ m, run, js: m.history ? undefined : loadJs(m), fns: {} }];
2731
+ const tables = [{ m, run, js: m.history || m.counts ? undefined : loadJs(m), fns: {} }];
2732
2732
  for (const [f, fn] of Object.entries(m.fns ?? {})) {
2733
2733
  const arg = ks.find(`F:${f}`);
2734
- if (fn.call || fn.recur || (fn.arity ?? 1) !== 1 || !ss.includes(arg) || m.history)
2734
+ if (fn.call || fn.recur || (fn.arity ?? 1) !== 1 || !ss.includes(arg) || m.history || m.counts)
2735
2735
  continue;
2736
2736
  const dom = keyDom(arg), vals = dom.map(k => { try {
2737
2737
  return fnValue(fn, k);
@@ -3170,6 +3170,10 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
3170
3170
  const near = (f) => (f.cube.some(l => atomsIn(formOf([l])).some(i => callerMaps.has(atoms[i].parts[0][0].split(AT)[2] ?? ''))) ? 0 : 1);
3171
3171
  // (the rounds over the data-filtered pool cut to its minimal cubes)
3172
3172
  const minPool = env.GDP_POOL !== '0' ? minimal(enumerated()) : { kept: enumerated(), by: new Map() }, made = minPool.kept;
3173
+ if (opts.cubes) {
3174
+ cubesOut = made;
3175
+ return;
3176
+ }
3173
3177
  const tEngine = vnow();
3174
3178
  let cubes = [];
3175
3179
  // (in turn by the maps a cube reads, those reading the caller's first: one of each kind before a second of any; in
@@ -4081,6 +4085,11 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
4081
4085
  });
4082
4086
  }
4083
4087
  };
4088
+ // (the cubes alone: the engine's enumeration on the small instance and the data filter, then out)
4089
+ if (opts.cubes) {
4090
+ engine();
4091
+ return { ...first, proven: false, found: (cubesOut ?? []).filter(f => f.cube.length <= opts.cubes).map(f => ({ law: lawFor(f), text: textOf(f) })), stats: stats(0, 0, 0) };
4092
+ }
4084
4093
  for (;;) {
4085
4094
  if (now() > jUntil || stop()) {
4086
4095
  why = 'time';
@@ -177,6 +177,10 @@ export type SomeProof = {
177
177
  body: C;
178
178
  sub?: Record<string, E>;
179
179
  ghost?: true;
180
+ map?: {
181
+ name: string;
182
+ at: E;
183
+ };
180
184
  };
181
185
  export { unreachable } from '../kernel/kernel.js';
182
186
  export declare const x: (name: string) => E;
@@ -12,7 +12,7 @@ import { someHolds } from "./exists.js";
12
12
  export const isStepLaw = (w) => 'then' in w;
13
13
  // A request's environment: the params, its inputs and queries, and the step's flags decided (as ?name).
14
14
  export function requestEnv(m, run, params, st, input) {
15
- const env = { ...params, ...numbersOf(input), ...run.queries(params, st, input) }, seen = carriedView(m, st, input);
15
+ const env = { ...params, ...numbersOf(input), ...run.queries(params, st, input) }, seen = carriedView(m, st, input, undefined, params);
16
16
  for (const [name, c] of Object.entries(m.step.flags ?? {}))
17
17
  env[`?${name}`] = evalC(c, env, seen, m) ? 1 : 0;
18
18
  return env;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gdp-wired",
3
- "version": "0.36.0",
3
+ "version": "0.37.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",