gdp-wired 0.30.1 → 0.31.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.
@@ -33,9 +33,9 @@
33
33
  // is the answer, after each chosen candidate the proof doesn't need is taken out again
34
34
  import { quietly } from "./cyclic.js";
35
35
  import { all, any, atMost, divisorsIn, evalC, evalE, get, interpret, machineTerms, modName, n, not, plus, same, seeded, times, withArithmetic, x } from "./machine.js";
36
- import { proveRule, proveSteps, verdictOf } from "./dsl.js";
37
- import { allowed, watch } from "./watch.js";
38
- import { clock, counted, grow, lawInstances, proveLaw, proveLaws, proveStepLaws, stepLawInstances, usedHyps, withDeadline, withTrees } from "../kernel/prove.js";
36
+ import { bool, proveRule, proveSteps, verdictOf } from "./dsl.js";
37
+ import { allowed, keysOf, linKey, watch } from "./watch.js";
38
+ import { clock, counted, grow, keyValue, lawInstances, proveLaw, proveLaws, proveStepLaws, stepLawInstances, usedHyps, withDeadline, withModels, withTrees } from "../kernel/prove.js";
39
39
  import { assumed, obligations, plainOf, stepLawObligations, substC } from "../kernel/kernel.js";
40
40
  import { env, gcd, work } from "./solver.js";
41
41
  import { bgcd } from "./q.js";
@@ -43,7 +43,7 @@ import { showC, showE } from "./exists.js";
43
43
  import { REFUTED, growCdcl } from "../kernel/cdcl.js";
44
44
  // a value outside a guard's (or a control value's) values
45
45
  const off = (g, v) => v < g.value || v > (g.hi ?? g.value);
46
- const KEY = 'key$found', KEY2 = 'key2$found', AT = '@', K = '#', K2 = '##', SOME = 'k$found';
46
+ const KEY = 'key$found', KEY2 = 'key2$found', AT = '@', K = '#', SOME = 'k$found';
47
47
  // The counted clock's rates, units a millisecond: about the slowest tenth of what Modal's 1-vCPU containers do in each
48
48
  // phase (`runs/modal/infer/after2`, GDP_INFER_TRACE=1: requests tried 85 a ms, rows 13,093, forms evaluated 11,240, the
49
49
  // kernel's work 37; laws watched 198 by a fit), so a counted budget runs out no later than a timed one would there.
@@ -156,34 +156,17 @@ function constantsOf(m, laws) {
156
156
  laws.forEach(l => c(l.holds));
157
157
  return [...out].filter(k => Number.isSafeInteger(k) && Math.abs(k) <= 1e6);
158
158
  }
159
- // A cell's key as the kernel names it (kernel.ts keyOf): `name:coef` parts joined by ',', '1' the constant.
160
- // (a name the model leaves out is 0, as the state's and the request's are read: a law's key it left free, say)
161
- const keyValue = (cell, w) => {
162
- const inner = cell.slice(cell.indexOf('[') + 1, -1);
163
- if (inner.includes('['))
164
- return undefined;
165
- let value = 0;
166
- for (const part of inner.split(',').filter(Boolean)) {
167
- const at = part.lastIndexOf(':'), name = part.slice(0, at), coef = Number(part.slice(at + 1));
168
- if (name === '1')
169
- value += coef;
170
- else if (name in w)
171
- value += coef * w[name];
172
- else if (name.includes('['))
173
- return undefined;
174
- }
175
- return value;
176
- };
159
+ // A key's linear form over the names `ok` admits, into `out` (`1` the constant); false where it is none.
160
+ const conj = (c) => (c.op === 'and' ? c.xs.flatMap(conj) : [c]);
177
161
  function pairingOf(m) {
178
- const inputs = new Set(m.inputs);
179
- const lin = (e, k, out) => (e.op === 'const' ? (out.set('1', (out.get('1') ?? 0) + k * e.value), true) : e.op === 'var' ? inputs.has(e.name) && (out.set(e.name, (out.get(e.name) ?? 0) + k), true) : e.op === 'add' ? lin(e.a, k, out) && lin(e.b, k, out) : e.op === 'mul' ? lin(e.a, k * e.k, out) : false);
162
+ const inputs = new Set(m.inputs), input = (v) => inputs.has(v);
180
163
  let found;
181
164
  const each = new Set(Object.values(m.step.maps ?? {}).flatMap(w => ('each' in w ? [w.each] : [])));
182
165
  const consider = (key) => {
183
166
  if (found)
184
167
  return;
185
168
  const l = new Map();
186
- if (!lin(key, 1, l))
169
+ if (!linKey(key, input, 1, l))
187
170
  return;
188
171
  const vs = [...l].filter(([v, c]) => v !== '1' && c);
189
172
  if (vs.length !== 2)
@@ -191,7 +174,7 @@ function pairingOf(m) {
191
174
  const [[a, ca], [b, cb]] = vs[0][1] >= vs[1][1] ? [vs[0], vs[1]] : [vs[1], vs[0]];
192
175
  if (cb !== 1 || ca < 2)
193
176
  return;
194
- const conj = (c) => (c.op === 'and' ? c.xs.flatMap(conj) : [c]), names = (c) => [...JSON.stringify(c).matchAll(/"name":"([^"]+)"/g)].map(q => q[1]);
177
+ const names = (c) => [...JSON.stringify(c).matchAll(/"name":"([^"]+)"/g)].map(q => q[1]);
195
178
  const own = m.assume ? conj(m.assume).filter(c => names(c).length && names(c).every(v => v === a || v === b)) : [];
196
179
  found = { n: ca, c: l.get('1') ?? 0, frame: substC({ op: 'and', xs: own }, { vars: { [a]: x(KEY), [b]: x(KEY2) }, maps: {}, flags: {} }) };
197
180
  };
@@ -214,6 +197,130 @@ function pairingOf(m) {
214
197
  visit([m.step, m.assume]);
215
198
  return found;
216
199
  }
200
+ // The key's sort, read off the rule and the caller's laws: a key read at a map's plain key is of that map's key sort;
201
+ // at a key the rule composes (N·a + b + c, pairingOf's), a is of the rows' sort and b of the columns'; a write at every
202
+ // key's key is of its map's, and two keys compared (k = src) are of one sort. Union-find over those places; a law's own
203
+ // keys are named apart (`L:law:key`). What a view of a law needs of it: its keys' sorts, the composed keys its reads
204
+ // name, its guards on its keys alone, the maps read at a plain key of a sort, and the keys a state holds of a sort.
205
+ function keySorts(m, laws, pairing) {
206
+ const parent = new Map();
207
+ const find = (a) => { const p2 = parent.get(a); if (p2 === undefined || p2 === a)
208
+ return a; const r = find(p2); parent.set(a, r); return r; };
209
+ const union = (a, b) => { const ra = find(a), rb = find(b); if (ra !== rb)
210
+ parent.set(ra, rb); };
211
+ const composed = new Set(), plainRead = new Set();
212
+ const split = (key, name) => {
213
+ if (!pairing?.n)
214
+ return undefined;
215
+ const lin = new Map();
216
+ if (!linKey(key, () => true, 1, lin))
217
+ return undefined;
218
+ const vs = [...lin].filter(([v, c]) => v !== '1' && c);
219
+ if (vs.length !== 2 || (lin.get('1') ?? 0) !== pairing.c)
220
+ return undefined;
221
+ const hi = vs.find(([, c]) => c === pairing.n), lo = vs.find(([, c]) => c === 1);
222
+ const a = hi && name(hi[0]), b = lo && name(lo[0]);
223
+ return a && b ? [a, b] : undefined;
224
+ };
225
+ const kids = (t, f) => { for (const v of Object.values(t))
226
+ if (v && typeof v === 'object')
227
+ (Array.isArray(v) ? v : [v]).forEach(y => { if (y && typeof y === 'object' && 'op' in y)
228
+ f(y); }); };
229
+ const walk = (t, name) => {
230
+ if (t.op === 'get') {
231
+ if (!(t.map in (m.maps ?? {}))) {
232
+ walk(t.key, name);
233
+ return;
234
+ }
235
+ const sp = split(t.key, name);
236
+ if (sp) {
237
+ composed.add(t.map);
238
+ union(sp[0], 'hi');
239
+ union(sp[1], 'lo');
240
+ return;
241
+ }
242
+ if (t.key.op === 'var' && name(t.key.name)) {
243
+ plainRead.add(t.map);
244
+ union(name(t.key.name), `M:${t.map}`);
245
+ return;
246
+ }
247
+ walk(t.key, name);
248
+ return;
249
+ }
250
+ if (t.op === 'all') {
251
+ const own = new Set([t.key, ...(t.keys ?? [])]);
252
+ walk(t.c, v => (own.has(v) ? `Q:${JSON.stringify(t).length}:${v}` : name(v)));
253
+ return;
254
+ }
255
+ if (t.op === '=' && t.a.op === 'var' && t.b.op === 'var') {
256
+ const a = name(t.a.name), b = name(t.b.name);
257
+ if (a && b)
258
+ union(a, b);
259
+ return;
260
+ }
261
+ kids(t, y => walk(y, name));
262
+ };
263
+ const inputs = new Set(m.inputs), rule = (v) => (inputs.has(v) ? v : undefined);
264
+ for (const [mp, w] of Object.entries(m.step.maps ?? {})) {
265
+ if ('each' in w)
266
+ walk(w.value, v => (v === w.each ? `M:${mp}` : rule(v)));
267
+ else {
268
+ walk({ op: 'get', map: mp, key: w.key }, rule);
269
+ walk(w.value, rule);
270
+ }
271
+ }
272
+ for (const e of Object.values(m.step.state ?? {}))
273
+ walk(e, rule);
274
+ for (const c of Object.values(m.step.flags ?? {}))
275
+ walk(c, rule);
276
+ if (m.assume)
277
+ walk(m.assume, rule);
278
+ const lawName = (l) => { const own = new Set([l.forall, ...(l.keys ?? [])]); return (v) => (own.has(v) ? `L:${l.name}:${v}` : undefined); };
279
+ for (const l of laws)
280
+ walk(l.holds, lawName(l));
281
+ return {
282
+ find,
283
+ sortOf: (l, v) => find(`L:${l.name}:${v}`),
284
+ shape: (l, bound) => {
285
+ const own = new Set(bound), composites = [], guards = [];
286
+ const see = (t) => {
287
+ if (t.op === 'get') {
288
+ const sp = split(t.key, v => (own.has(v) ? v : undefined));
289
+ if (sp && !composites.some(([a, b]) => a === sp[0] && b === sp[1]))
290
+ composites.push(sp);
291
+ }
292
+ kids(t, see);
293
+ };
294
+ see(l.holds);
295
+ // (the antecedent's conditions on the keys alone: k < 64, a ≠ b)
296
+ const onKeys = (c) => { const s2 = JSON.stringify(c); return !s2.includes('"op":"get"') && [...s2.matchAll(/"name":"([^"]+)"/g)].every(q => own.has(q[1])); };
297
+ if (l.holds.op === 'or')
298
+ for (const y of l.holds.xs)
299
+ if (y.op === 'not')
300
+ guards.push(...conj(y.x).filter(onKeys));
301
+ return { composites, guards };
302
+ },
303
+ composedMaps: [...composed],
304
+ compose: (a, b) => { const k = plus(times(pairing.n, a), b); return pairing.c ? plus(k, n(pairing.c)) : k; },
305
+ plainMaps: (sort) => [...plainRead].filter(mp => find(`M:${mp}`) === sort),
306
+ valuesAt: (st, sort) => {
307
+ const ks = new Set();
308
+ for (const [mp, cells] of Object.entries(st.maps))
309
+ for (const k of cells.keys()) {
310
+ if (plainRead.has(mp) && find(`M:${mp}`) === sort)
311
+ ks.add(k);
312
+ if (composed.has(mp) && pairing?.n && k >= pairing.c) {
313
+ if (find('hi') === sort)
314
+ ks.add(Math.floor((k - pairing.c) / pairing.n));
315
+ if (find('lo') === sort)
316
+ ks.add((k - pairing.c) % pairing.n);
317
+ }
318
+ }
319
+ const xs = [...ks].sort((a, b) => a - b);
320
+ return [...xs, xs.length ? xs.at(-1) + 1 : 0];
321
+ },
322
+ };
323
+ }
217
324
  // The products of two of `names` a machine's terms (its step, flags, assumption) and these conditions multiply, a
218
325
  // product of sums read as its monomials ((top + 2)·window: top·window), each pair of factors once, in order.
219
326
  function monomialsOf(m, cs, names) {
@@ -302,9 +409,9 @@ function preimages(m, laws, stepLaws, atoms, coords) {
302
409
  }
303
410
  };
304
411
  const flags = {};
412
+ // (a quantified flag as the goals read it, its 0/1 variable ?f: a flag after it may read it, 2PC's go1 reads noGo)
305
413
  for (const [f, c] of Object.entries(m.step.flags ?? {}))
306
- if (c.op !== 'all')
307
- flags[f] = substC(c, { vars: {}, maps: {}, flags });
414
+ flags[f] = c.op === 'all' ? { op: '=', a: x(`?${f}`), b: n(1) } : substC(c, { vars: {}, maps: {}, flags });
308
415
  const inline = (c) => substC(c, { vars: {}, maps: {}, flags });
309
416
  const atomsOfC = (c, post, out) => {
310
417
  if (c.op === 'and' || c.op === 'or') {
@@ -743,17 +850,26 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
743
850
  const valueOf = (a, env) => { let s = 0; for (const [p, sign] of a.parts)
744
851
  s += sign * (env[a.cell ? AT + p : p] ?? 0); return s; };
745
852
  // The pairs' rows (the join's, where the rule composes two keys into one), once the pair atoms are made.
746
- let pairRowsOf, pairing;
853
+ const views = [];
747
854
  const cellOf = (st, map, key) => st.maps[map]?.get(key) ?? st.defaults?.[map] ?? m.maps[map];
748
855
  // The scalar rows (one per state reached), and the cell rows (one per state and key a map holds, and one fresh key).
749
856
  const keysIn = (st) => { const ks = new Set(); for (const c of Object.values(st.maps))
750
857
  for (const k of c.keys())
751
858
  ks.add(k); return [...ks]; };
859
+ // A state read from a kernel model names some cells (`named`, map|key); the others it leaves free (any value), so a form
860
+ // is judged there only at rows whose cells it reads the model names (`unnamed`: a row's cells it doesn't), and no
861
+ // fresh key. Elsewhere every cell is the state's.
862
+ const named = new WeakMap(), unnamed = new WeakMap();
863
+ const mark = (row, st, cells) => { const nm = named.get(st); if (nm) {
864
+ const u = new Set(cells.filter(([, mp, k]) => !nm.has(`${mp}|${k}`)).map(([q]) => q));
865
+ if (u.size)
866
+ unnamed.set(row, u);
867
+ } return row; };
752
868
  const cellRows = (params, st) => {
753
869
  if (!mapNames.length)
754
870
  return [];
755
871
  const ks = keysIn(st), fresh = ks.length ? Math.max(...ks) + 1 : 0;
756
- return [...ks, fresh].map(k => withTerms({ ...params, ...st.scalars, [K]: k, ...Object.fromEntries(mapNames.map(mp => [AT + mp, cellOf(st, mp, k)])) }, st));
872
+ return [...ks, ...(named.has(st) ? [] : [fresh])].map(k => mark(withTerms({ ...params, ...st.scalars, [K]: k, ...Object.fromEntries(mapNames.map(mp => [AT + mp, cellOf(st, mp, k)])) }, st), st, mapNames.map(mp => [AT + mp, mp, k])));
757
873
  };
758
874
  const rowsS = samples.map(s => withTerms({ ...s.params, ...s.st.scalars }, s.st));
759
875
  const rowsK = [];
@@ -957,7 +1073,15 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
957
1073
  return only.values.filter(v => c * v <= f.d);
958
1074
  };
959
1075
  // (a form about every key says so first)
960
- const textOf = (f) => (f.cells ? `every k: ${textIn(f)}` : f.pairs ? `every x, y${pairing.frame.op === 'and' && !pairing.frame.xs.length ? '' : ` with ${showC(pairing.frame).replaceAll(KEY2, 'y').replaceAll(KEY, 'x')}`}: ${textIn(f)}` : textIn(f));
1076
+ const viewText = (v, t) => v.vars.reduce((acc, k2, i) => acc.replaceAll(k2, v.names[i]), t);
1077
+ const textOf = (f) => {
1078
+ if (f.cells)
1079
+ return `every k: ${textIn(f)}`;
1080
+ if (f.view === undefined)
1081
+ return textIn(f);
1082
+ const v = views[f.view];
1083
+ return `every ${v.names.join(', ')}${v.frame.op === 'and' && !v.frame.xs.length ? '' : ` with ${viewText(v, showC(v.frame))}`}: ${textIn(f)}`;
1084
+ };
961
1085
  const textIn = (f) => {
962
1086
  const atText = (g) => (g.hi === undefined ? `${nameOf(g.atom)} is ${shownValue(g.atom, g.value)}` : g.hi === Infinity ? `${g.value} <= ${nameOf(g.atom)}` : `${nameOf(g.atom)} in ${g.value}..${g.hi}`);
963
1087
  if (f.never)
@@ -982,9 +1106,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
982
1106
  // Each congruence its own witness's name (each may be a ghost of the machine).
983
1107
  const someNames = new Map(), someName = (f) => { let k = someNames.get(f); if (!k)
984
1108
  someNames.set(f, (k = `${SOME}${someNames.size}`)); return k; };
985
- const placeKey = (place) => { if (place < 2)
986
- return x(place === 0 ? KEY : KEY2); const k = plus(times(pairing.n, x(KEY)), x(KEY2)); return pairing.c ? plus(k, n(pairing.c)) : k; };
987
- const part = (a, p) => (a.term ?? (a.place !== undefined ? get(p.slice(2, p.lastIndexOf(AT)), placeKey(a.place)) : a.cell ? get(p, x(KEY)) : x(p)));
1109
+ const part = (a, p) => (a.term ?? (a.place !== undefined ? get(p.slice(2, p.lastIndexOf(AT)), views[a.view].places[a.place]) : a.cell ? get(p, x(KEY)) : x(p)));
988
1110
  const partsOf = (f, sign) => f.coef.flatMap(([i, c]) => atoms[i].parts.filter(([, s]) => s * c * sign > 0).map(([p]) => { const e = part(atoms[i], p); return Math.abs(c) === 1 ? e : times(Math.abs(c), e); }));
989
1111
  // Σ c·v ≤ d over naturals: the positive parts on the left, the negative ones and d on the right (an integer's
990
1112
  // negative part goes to the other side of its sign).
@@ -1034,12 +1156,18 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1034
1156
  const ints = f.coef.filter(([i]) => atoms[i].int).length;
1035
1157
  if (ints && ints !== f.coef.length)
1036
1158
  return undefined;
1037
- const ref = (i) => (atoms[i].cell ? `${atoms[i].parts[0][0]}.at(k)` : nameOf(i));
1038
- const val = (i) => { const mo = modeOf(i); return mo?.choice && !atoms[i].cell ? `${ref(i)}.index` : mo?.bool && !atoms[i].cell ? `${ref(i)}.n` : ref(i); };
1159
+ // (a view's cell: its map at x or at y; over two plain keys alone, as the frame is then x ≠ y)
1160
+ if (f.view !== undefined && !views[f.view].printable)
1161
+ return undefined;
1162
+ const mapOf = (i) => { const a = atoms[i], p = a.parts[0][0]; return a.place !== undefined ? p.slice(2, p.lastIndexOf(AT)) : p; };
1163
+ const ref = (i) => (atoms[i].place !== undefined ? `${mapOf(i)}.at(${atoms[i].place === 0 ? 'x' : 'y'})` : atoms[i].cell ? `${atoms[i].parts[0][0]}.at(k)` : nameOf(i));
1164
+ // (a cell of a map of yes/nos, at k or at x or y, reads as its 0/1 term too)
1165
+ const boolCell = (i) => (atoms[i].cell || atoms[i].place !== undefined) && rule.kindsOfCells().some(([mp, kd]) => mp === mapOf(i) && kd === bool);
1166
+ const val = (i) => { const mo = modeOf(i); return mo?.choice && !atoms[i].cell ? `${ref(i)}.index` : (mo?.bool && !atoms[i].cell) || boolCell(i) ? `${ref(i)}.n` : ref(i); };
1039
1167
  const cond = (i, value, hi) => { const mo = modeOf(i); if (hi !== undefined)
1040
1168
  return hi === Infinity ? `${ref(i)}.atLeast(${value})` : `${ref(i)}.atLeast(${value}).and(${ref(i)}.atMost(${hi}))`; return mo?.choice && !atoms[i].cell ? `${ref(i)}.is('${mo.choice[value]}')` : mo?.bool && !atoms[i].cell ? (value === 1 ? ref(i) : `${ref(i)}.not()`) : `${ref(i)}.eq(${value})`; };
1041
- const args = `({${[...new Set(used.map(i => (atoms[i].cell ? atoms[i].parts[0][0] : nameOf(i))))].join(', ')}})`;
1042
- const wrap = (body) => (f.cells ? `forall(k => ${body})` : body);
1169
+ const args = `({${[...new Set(used.map(i => (atoms[i].cell || atoms[i].place !== undefined ? mapOf(i) : nameOf(i))))].join(', ')}})`;
1170
+ const wrap = (body) => (f.cells ? `forall(k => ${body})` : f.view !== undefined ? `forall((x, y) => x.eq(y).not().implies(${body}))` : body);
1043
1171
  if (f.unreachable)
1044
1172
  return `r.law('${text}', ${args} => ${cond(f.unreachable.atom, f.unreachable.value, f.unreachable.hi)}.not())`;
1045
1173
  if (f.cong) {
@@ -1113,8 +1241,11 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1113
1241
  s += c * vs[i];
1114
1242
  return f.mod ? residue(s, f.mod.k) === f.mod.r : s <= f.d;
1115
1243
  };
1116
- const pointOf = (params, st) => ({ scalar: withTerms({ ...params, ...st.scalars }, st), cells: cellRows(params, st), ...(pairRowsOf ? { pairs: pairRowsOf(params, st) } : {}) });
1117
- const holdsAt = (f, p) => (f.pairs ? (p.pairs ?? []).every(r => holdsRow(f, r)) : f.cells ? p.cells.every(r => holdsRow(f, r)) : holdsRow(f, p.scalar));
1244
+ const pointOf = (params, st) => ({ scalar: withTerms({ ...params, ...st.scalars }, st), cells: cellRows(params, st), views: views.map(v => v.rowsOf(params, st)) });
1245
+ // (the atoms a form reads)
1246
+ const atomsIn = (f) => [...f.coef.map(([i]) => i), ...(f.guard && 'atom' in f.guard ? [f.guard.atom] : []), ...(f.also ?? []).map(a => a.atom), ...(f.never ?? []).map(a => a.atom), ...(f.unreachable ? [f.unreachable.atom] : []), ...(f.nevers ?? []).flat().map(a => a.atom), ...(f.cube ?? []).flatMap(l => ('at' in l ? [l.at.atom] : l.lin.coef.map(([i]) => i)))];
1247
+ const judged = (f, r) => { const u = unnamed.get(r); return !u || !atomsIn(f).some(i => atoms[i].parts.some(([q]) => u.has(atoms[i].cell ? AT + q : q))); };
1248
+ const holdsAt = (f, p) => (f.view !== undefined ? (p.views[f.view] ?? []).every(r => !judged(f, r) || holdsRow(f, r)) : f.cells ? p.cells.every(r => !judged(f, r) || holdsRow(f, r)) : holdsRow(f, p.scalar));
1118
1249
  // A kernel witness as a point: its scalars, and a cell row per key it reads a map at.
1119
1250
  const witnessPoint = (w) => {
1120
1251
  const scalar = Object.fromEntries([...scalars, ...m.params].map(v => [v, w[v] ?? 0]));
@@ -1131,7 +1262,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1131
1262
  row[AT + name.slice(0, br)] = value;
1132
1263
  byKey.set(key, row);
1133
1264
  }
1134
- return { scalar, cells: [...byKey.values()] };
1265
+ return { scalar, cells: [...byKey.values()], views: [] };
1135
1266
  };
1136
1267
  // A kernel witness's map cells, each at the key it names (the others at the map's constant).
1137
1268
  const mapsOf = (w) => {
@@ -1151,12 +1282,20 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1151
1282
  // --- Houdini on the runs' neighbors ----------------------------------------------------------------------------------
1152
1283
  let alive = forms.slice().sort((p, q) => p.size - q.size).slice(0, maxCandidates);
1153
1284
  const ctis = [];
1154
- const lawful = (params, st) => { used.watched += given.length; try {
1155
- return given.every(l => watch(m, run, l, params, 4).start(st));
1156
- }
1157
- catch {
1158
- return false;
1159
- } };
1285
+ // (a law about keys is evaluated at every tuple of the state's keys, as watch does: counted as that many evaluations)
1286
+ const lawful = (params, st) => {
1287
+ used.watched += given.length;
1288
+ const k = keysOf(4, st).length;
1289
+ for (const l of given)
1290
+ if (l.forall)
1291
+ used.evals += k ** (1 + (l.keys?.length ?? 0));
1292
+ try {
1293
+ return given.every(l => watch(m, run, l, params, 4).start(st));
1294
+ }
1295
+ catch {
1296
+ return false;
1297
+ }
1298
+ };
1160
1299
  const houdiniUntil = Math.min(until, now() + Math.max(500, (until - now()) / 4));
1161
1300
  for (let quiet = 0; samples.length && now() < houdiniUntil && !stop() && quiet < 3;) {
1162
1301
  const killed = new Set();
@@ -1208,8 +1347,9 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1208
1347
  const lawFor = (f) => {
1209
1348
  let l = lawOf.get(f);
1210
1349
  // (about two keys: where the frame holds of them)
1350
+ const v = f.view !== undefined ? views[f.view] : undefined;
1211
1351
  if (!l)
1212
- lawOf.set(f, (l = { name: textOf(f), holds: f.pairs ? any(not(pairing.frame), condOf(f)) : condOf(f), ...(f.cells ? { forall: KEY } : f.pairs ? { forall: KEY, keys: [KEY2] } : {}), ...(f.cong ? { some: someOf(f) } : {}) }));
1352
+ lawOf.set(f, (l = { name: textOf(f), holds: v ? any(not(v.frame), condOf(f)) : condOf(f), ...(f.cells ? { forall: KEY } : v ? { forall: v.vars[0], keys: v.vars.slice(1) } : {}), ...(f.cong ? { some: someOf(f) } : {}) }));
1213
1353
  return l;
1214
1354
  };
1215
1355
  const names = new Set(given.map(l => l.name));
@@ -1373,49 +1513,119 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1373
1513
  // The pairs: where the rule composes two keys into one (Link[N·a + b] beside Known[a], Known[b]), the cells at two
1374
1514
  // keys x and y and at N·x + y, a row per two keys a state holds (or the parts of a composed key it holds, or a fresh
1375
1515
  // one) that the frame (the assumption's of a and b) allows: their forms laws at every two keys.
1376
- pairing = mapNames.length ? pairingOf(m) : undefined;
1377
- const pairAtoms = [], rowsP = [];
1516
+ // Where no key is composed but a caller's law is about several keys (two counted approvals by distinct reviewers, two
1517
+ // holders of one lock), the same space over two distinct keys x ≠ y: the cells at x and at y (`n` 0, no third place).
1518
+ const pairing = mapNames.length ? pairingOf(m) ?? ([...laws, ...stepLaws].some(l => l.keys?.length) ? { n: 0, c: 0, frame: not(same(x(KEY), x(KEY2))) } : undefined) : undefined;
1378
1519
  const cellLevels = pairing ? levelsOf(cellAtoms.filter(i => !atoms[i].int), valsK) : [];
1379
- if (pairing) {
1380
- const P = pairing;
1381
- for (const i of cellAtoms)
1382
- for (const place of [0, 1, 2]) {
1383
- const a = atoms[i], keyText = place === 0 ? 'x' : place === 1 ? 'y' : `${P.n}·x + y${P.c ? ` + ${P.c}` : ''}`;
1384
- pairAtoms.push(atoms.length);
1385
- atoms.push({ name: `${a.parts[0][0]}[${keyText}]`, parts: a.parts.map(([q, sg]) => [`${AT}${AT}${q}${AT}${place}`, sg]), param: false, int: a.int, cell: false, place });
1520
+ // A view's atoms (each map at each place it is read at there) and rows: each assignment of its keys to keys a state
1521
+ // holds (by sort: the keys of the maps read at the key's place, the parts of composed keys there, and a fresh one;
1522
+ // per key at most `per`), the frame met, each map's cell at each of its places.
1523
+ const addView = (v, mapsAt, valuesOf2, per) => {
1524
+ const vi = views.length, va = [];
1525
+ mapsAt.forEach((mps, place) => {
1526
+ for (const i of cellAtoms) {
1527
+ const a = atoms[i];
1528
+ if (!mps.includes(a.parts[0][0]))
1529
+ continue;
1530
+ va.push(atoms.length);
1531
+ atoms.push({ name: `${a.parts[0][0]}[${viewText(v, showE(v.places[place]))}]`, parts: a.parts.map(([q, sg]) => [`${AT}${AT}${q}${AT}${vi}:${place}`, sg]), param: false, int: a.int, cell: false, place, view: vi });
1386
1532
  }
1387
- pairRowsOf = (params, st) => {
1388
- const ks = new Set();
1389
- for (const c of Object.values(st.maps))
1390
- for (const k of c.keys()) {
1391
- ks.add(k);
1392
- if (k >= P.c) {
1393
- ks.add(Math.floor((k - P.c) / P.n));
1394
- ks.add((k - P.c) % P.n);
1395
- }
1396
- }
1397
- const held = [...ks], fresh = held.length ? Math.max(...held) + 1 : 0, xs = [...held, fresh].slice(0, 24), out = [];
1398
- for (const kx of xs)
1399
- for (const ky of xs) {
1533
+ });
1534
+ const rowsOf = (params, st) => {
1535
+ const cand = valuesOf2(st).map(vs => (named.has(st) ? vs.slice(0, -1) : vs).slice(0, per)), out = [];
1536
+ const go = (i, env) => {
1537
+ if (i === v.vars.length) {
1400
1538
  try {
1401
- if (!evalC(P.frame, { ...params, ...st.scalars, [KEY]: kx, [KEY2]: ky }, st, m))
1402
- continue;
1539
+ if (!evalC(v.frame, env, st, m))
1540
+ return;
1403
1541
  }
1404
1542
  catch {
1405
- continue;
1543
+ return;
1406
1544
  }
1407
- const row = { ...params, ...st.scalars, [K]: kx, [K2]: ky };
1408
- for (const mp of mapNames)
1409
- for (const [place, key] of [[0, kx], [1, ky], [2, P.n * kx + ky + P.c]])
1410
- row[`${AT}${AT}${mp}${AT}${place}`] = cellOf(st, mp, key);
1411
- out.push(withTerms(row, st));
1545
+ const row = { ...params, ...st.scalars, [K]: env[v.vars[0]] }, cells = [];
1546
+ mapsAt.forEach((mps, place) => { const key = evalE(v.places[place], env, st, m); for (const mp of mps) {
1547
+ const q = `${AT}${AT}${mp}${AT}${vi}:${place}`;
1548
+ row[q] = cellOf(st, mp, key);
1549
+ cells.push([q, mp, key]);
1550
+ } });
1551
+ out.push(mark(withTerms(row, st), st, cells));
1552
+ return;
1412
1553
  }
1554
+ for (const k2 of cand[i])
1555
+ go(i + 1, { ...env, [v.vars[i]]: k2 });
1556
+ };
1557
+ go(0, { ...params, ...st.scalars });
1413
1558
  return out;
1414
1559
  };
1560
+ const rows = [];
1415
1561
  for (const s2 of samples) {
1416
- if (rowsP.length > 6000)
1562
+ if (rows.length > 6000)
1417
1563
  break;
1418
- rowsP.push(...pairRowsOf(s2.params, s2.st));
1564
+ rows.push(...rowsOf(s2.params, s2.st));
1565
+ }
1566
+ views.push({ ...v, atoms: va, rows, rowsOf });
1567
+ };
1568
+ // The pairs: where the rule composes two keys into one (Link[N·a + b] beside Known[a], Known[b]), the cells at two
1569
+ // keys x and y and at N·x + y, a row per two keys a state holds (or the parts of a composed key it holds, or a fresh
1570
+ // one) that the frame (the assumption's of a and b) allows: their forms laws at every two keys.
1571
+ // Where no key is composed but a caller's law is about several keys (two counted approvals by distinct reviewers, two
1572
+ // holders of one lock), the same space over two distinct keys x ≠ y: the cells at x and at y (`n` 0, no third place).
1573
+ const callerLaws = [...laws, ...stepLaws.map(sl => ({ name: sl.name, holds: sl.then, ...(sl.forall ? { forall: sl.forall } : {}), ...(sl.keys ? { keys: sl.keys } : {}) }))];
1574
+ const sorts = mapNames.length ? keySorts(m, callerLaws, pairing) : undefined;
1575
+ if (pairing) {
1576
+ const P = pairing, composed = plus(times(P.n, x(KEY)), x(KEY2)), places = P.n ? [x(KEY), x(KEY2), P.c ? plus(composed, n(P.c)) : composed] : [x(KEY), x(KEY2)];
1577
+ // (by sort, where the rule composes: a row's maps at x, a column's at y, the composed maps at the composed key)
1578
+ const sorted = P.n && sorts ? [sorts.plainMaps(sorts.find('hi')), sorts.plainMaps(sorts.find('lo')), sorts.composedMaps] : undefined;
1579
+ const held = (st) => {
1580
+ const ks = new Set();
1581
+ for (const c of Object.values(st.maps))
1582
+ for (const k of c.keys()) {
1583
+ ks.add(k);
1584
+ if (P.n && k >= P.c) {
1585
+ ks.add(Math.floor((k - P.c) / P.n));
1586
+ ks.add((k - P.c) % P.n);
1587
+ }
1588
+ }
1589
+ const xs = [...ks, ks.size ? Math.max(...ks) + 1 : 0];
1590
+ return [xs, xs];
1591
+ };
1592
+ addView({ vars: [KEY, KEY2], names: ['x', 'y'], places, covers: P.n ? [[0], [1], [0, 1]] : [[0], [1]], frame: P.frame, need: P.n ? 1 : 2, printable: !P.n }, sorted ?? places.map(() => mapNames), held, 24);
1593
+ }
1594
+ // A view of each caller's law about several keys that the pairs don't hold (three keys: two holders of a lock and
1595
+ // the lock; two keys of one sort where the pairs relate two sorts): its keys, each of the sort its reads give it
1596
+ // (keySorts: a sort is the places a key is read at, the rule's keys read alike as one), its places the composed keys
1597
+ // its reads name and each map read at a plain key of a key's sort, its frame its own guards on its keys and the keys
1598
+ // of one sort distinct.
1599
+ if (sorts) {
1600
+ const seen = new Set();
1601
+ for (const l of callerLaws) {
1602
+ const bound = l.forall ? [l.forall, ...(l.keys ?? [])] : [];
1603
+ if (bound.length < 2 || bound.length > 4)
1604
+ continue;
1605
+ const shape = sorts.shape(l, bound);
1606
+ // (two keys the pairs already relate: a row and a column of the composed key, or two plain keys)
1607
+ if (!shape || (bound.length === 2 && pairing && (!pairing.n || (shape.composites.length === 1 && sorts.sortOf(l, bound[0]) !== sorts.sortOf(l, bound[1])))))
1608
+ continue;
1609
+ const vars = bound.map((_, i) => (i ? `key${i + 1}$found` : KEY)), ren = Object.fromEntries(bound.map((b2, i) => [b2, x(vars[i])]));
1610
+ const places = [], mapsAt = [], covers = [];
1611
+ for (const [a2, b2] of shape.composites) {
1612
+ places.push(sorts.compose(ren[a2], ren[b2]));
1613
+ mapsAt.push(sorts.composedMaps);
1614
+ covers.push([bound.indexOf(a2), bound.indexOf(b2)]);
1615
+ }
1616
+ bound.forEach((b2, i) => { const mps = sorts.plainMaps(sorts.sortOf(l, b2)); if (mps.length) {
1617
+ places.push(x(vars[i]));
1618
+ mapsAt.push(mps);
1619
+ covers.push([i]);
1620
+ } });
1621
+ const sig = JSON.stringify([bound.map(b2 => sorts.sortOf(l, b2)), covers, mapsAt]);
1622
+ if (seen.has(sig) || !places.length)
1623
+ continue;
1624
+ seen.add(sig);
1625
+ const distinct = bound.flatMap((b2, i) => bound.slice(i + 1).flatMap((c2, j) => (sorts.sortOf(l, b2) === sorts.sortOf(l, c2) ? [not(same(x(vars[i]), x(vars[i + 1 + j])))] : [])));
1626
+ const frame = all(...shape.guards.map((g) => substC(g, { vars: ren, maps: {}, flags: {} })), ...distinct);
1627
+ const per = Math.max(2, Math.floor(64 ** (1 / bound.length)));
1628
+ addView({ vars, names: ['x', 'y', 'z', 'w'].slice(0, bound.length), places, covers, frame, need: bound.length, printable: false }, mapsAt, st => bound.map(b2 => sorts.valuesAt(st, sorts.sortOf(l, b2))), per);
1419
1629
  }
1420
1630
  }
1421
1631
  // The directions over some values: each value up and down, pairs of them where there are few, the rule's own
@@ -1458,11 +1668,11 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1458
1668
  // and directions, and per control state the hull and the bounds. A space's forms are laws of the state, or, of the
1459
1669
  // cells, laws at every key (those that read a cell; the others are the states' space's).
1460
1670
  const space = (kind) => {
1461
- const cells = kind === 'cells', pairs = kind === 'pairs';
1671
+ const cells = kind === 'cells', view = typeof kind === 'number' ? views[kind] : undefined;
1462
1672
  const ctl = keyModes.map(mo => ({ atom: mo.atom, cuts: mo.values.slice(0, -1), top: mo.values.at(-1) }));
1463
- const exactAtoms = new Set(keyModes.map(mo => mo.atom)), own = cells ? [...plain, ...cellAtoms] : pairs ? [...plain, ...pairAtoms] : plain;
1673
+ const exactAtoms = new Set(keyModes.map(mo => mo.atom)), own = cells ? [...plain, ...cellAtoms] : view ? [...plain, ...view.atoms] : plain;
1464
1674
  // (a pair's cells take their map's cells' levels)
1465
- const levelable = pairs ? cellLevels.flatMap(c => pairAtoms.filter(i => atoms[i].parts[0][0].slice(2, atoms[i].parts[0][0].lastIndexOf(AT)) === atoms[c.atom].parts[0][0]).map(i => ({ ...c, atom: i })))
1675
+ const levelable = view ? cellLevels.flatMap(c => view.atoms.filter(i => atoms[i].parts[0][0].slice(2, atoms[i].parts[0][0].lastIndexOf(AT)) === atoms[c.atom].parts[0][0]).map(i => ({ ...c, atom: i })))
1466
1676
  : levelsOf(own.filter(i => !exactAtoms.has(i) && !atoms[i].int && (!cells || atoms[i].cell)), cells ? valsK : valsS);
1467
1677
  const coords = own.filter(i => !exactAtoms.has(i)), CN = coords.length, dirs = directions(coords);
1468
1678
  const groups = new Map();
@@ -1511,10 +1721,10 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1511
1721
  // a control value by its level (as the keys hold it) as the values it stands for
1512
1722
  const atLevel = (a) => atOf(ctl[keyAtoms.indexOf(a.atom)], a.value);
1513
1723
  // a point's rows in this space
1514
- const vecs = (p) => (cells ? p.cells.map(valuesOf) : pairs ? (p.pairs ?? []).map(valuesOf) : [valuesOf(p.scalar)]);
1724
+ const vecs = (p) => (cells ? p.cells.map(valuesOf) : view ? (p.views[kind] ?? []).map(valuesOf) : [valuesOf(p.scalar)]);
1515
1725
  const add = (p, widen) => { for (const v of vecs(p))
1516
1726
  join(keyOf(v), v, widen); };
1517
- const rows = (cells ? rowsK : pairs ? rowsP : rowsS).map(valuesOf);
1727
+ const rows = (cells ? rowsK : view ? view.rows : rowsS).map(valuesOf);
1518
1728
  for (const v of rows)
1519
1729
  join(keyOf(v), v, false);
1520
1730
  opts.progress?.('join start', { space: kind, control: ctl.map(c => `${nameOf(c.atom)}:${c.cuts.join('/')}`).join(' '), groups: groups.size, dirs: dirs.length, coords: CN });
@@ -1543,8 +1753,13 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1543
1753
  };
1544
1754
  const forms = (push) => {
1545
1755
  // (of the cells: only what reads one)
1546
- const keep = (f) => { if (kind === 'state' || [...f.coef.map(([i]) => i), ...(f.guard && 'atom' in f.guard ? [f.guard.atom] : []), ...(f.also ?? []).map(a => a.atom), ...(f.never ?? []).map(a => a.atom), ...(f.unreachable ? [f.unreachable.atom] : []), ...(f.nevers ?? []).flat().map(a => a.atom)].some(i => (pairs ? atoms[i].place !== undefined : atoms[i].cell)))
1547
- push(pairs ? { ...f, pairs: true } : f); };
1756
+ // (over two plain keys, a form that reads one of them alone is the cells' form, which every key's instance covers)
1757
+ const keep = (f) => {
1758
+ const read = atomsIn(f);
1759
+ const covered = new Set(read.flatMap(i => (atoms[i].place !== undefined ? view.covers[atoms[i].place] : [])));
1760
+ if (kind === 'state' || (view ? covered.size >= view.need : read.some(i => atoms[i].cell)))
1761
+ push(view ? { ...f, view: kind } : f);
1762
+ };
1548
1763
  // (a choice's value no state reached: one form, whatever the yes/nos; the control states no state reached, one form
1549
1764
  // for all, where there are several: each alone needs the others to be inductive, a goal each where one does)
1550
1765
  const reachedFirst = new Set([...groups.keys()].map(k2 => k2.split(',')[0])), nev = [];
@@ -1675,7 +1890,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1675
1890
  };
1676
1891
  return { cells, add, forms, refine, deepen, coords, control: () => `${ctl.map(c => nameOf(c.atom)).join(' ')} (${scored.join(' ')})`, groups };
1677
1892
  };
1678
- const spaces = [space('state'), ...(mapNames.length && cellAtoms.length ? [space('cells')] : []), ...(rowsP.length ? [space('pairs')] : [])];
1893
+ const spaces = [space('state'), ...(mapNames.length && cellAtoms.length ? [space('cells')] : []), ...views.flatMap((v, i) => (v.rows.length ? [space(i)] : []))];
1679
1894
  const formsNow = () => {
1680
1895
  const out = [], seenT = new Set();
1681
1896
  const push = (f) => { const t = textOf(f); if (!seenT.has(t) && !names.has(t)) {
@@ -1768,29 +1983,44 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1768
1983
  const idx = form ? ls.length - 1 : ls.findIndex(l => l.name === name);
1769
1984
  // (a rule with maps: the laws about every key at the instances the prover would read them at)
1770
1985
  const inst = !mapNames.length ? {} : sl ? stepLawInstances(mm, ls)(sl) : lawInstances(mm, ls, idx);
1771
- const g = sl ? stepLawObligations(mm, ls, inst, sl)[0] : obligations(mm, ls, { [ls[idx].name]: inst }, idx)[1], lawAt = lawsFrom(mm, ls, !!sl, inst), used = [];
1772
- const read = (h) => { const k = lawAt.get(h); if (k !== undefined && k >= given.length && k !== idx && !used.includes(ls[k].name))
1773
- used.push(ls[k].name); };
1774
- // First a model alone of the CDCL search (no tree unfolded): refuted, the hypotheses its leaves read are those
1775
- // a tree would (the set's proof is the kernel's below, as before); a model is the counterexample; else the prover.
1776
- if (joinCore) {
1777
- const quick = budgeted(joinQueryMs / 4, until2 => growCdcl(g, new Map(), { nodes: 0, until: until2 }, { model: true, core: true }));
1778
- if (!('tree' in quick) && quick.why === REFUTED && quick.core) {
1779
- for (const h of quick.core)
1780
- read(h);
1781
- return { used };
1986
+ const goalOf = (i2) => [sl ? stepLawObligations(mm, ls, i2, sl)[0] : obligations(mm, ls, { [ls[idx].name]: i2 }, idx)[1]];
1987
+ // (a model that breaks a law or a flag at a tuple of the goal's keys it wasn't assumed at: the goal asked again with
1988
+ // those instances; kernel/prove.ts's withModels)
1989
+ const ask = ([g], at) => {
1990
+ const lawAt = lawsFrom(mm, ls, !!sl, at), used = [];
1991
+ const read = (h) => { const k = lawAt.get(h); if (k !== undefined && k >= given.length && k !== idx && !used.includes(ls[k].name))
1992
+ used.push(ls[k].name); };
1993
+ // First a model alone of the CDCL search (no tree unfolded): refuted, the hypotheses its leaves read are those
1994
+ // a tree would (the set's proof is the kernel's below, as before); a model is the counterexample; else the prover.
1995
+ if (joinCore) {
1996
+ const quick = budgeted(joinQueryMs / 4, until2 => growCdcl(g, new Map(), { nodes: 0, until: until2 }, { model: true, core: true }));
1997
+ if (!('tree' in quick) && quick.why === REFUTED && quick.core) {
1998
+ for (const h of quick.core)
1999
+ read(h);
2000
+ return { used, g: g };
2001
+ }
2002
+ if (!('tree' in quick) && quick.stuck === 'sat' && quick.witness)
2003
+ return { stuck: 'sat', witness: quick.witness, g: g };
1782
2004
  }
1783
- if (!('tree' in quick) && quick.stuck === 'sat' && quick.witness)
1784
- return { stuck: 'sat', witness: quick.witness };
1785
- }
1786
- const out = budgeted(joinQueryMs, until2 => grow(g, new Map(), { nodes: 0, until: until2 }));
1787
- if (!('tree' in out))
1788
- return { stuck: out.stuck, witness: out.stuck === 'sat' ? out.witness : undefined };
1789
- for (const h of usedHyps(g, out.tree))
1790
- read(h);
1791
- return { used };
2005
+ const out = budgeted(joinQueryMs, until2 => grow(g, new Map(), { nodes: 0, until: until2 }));
2006
+ if (!('tree' in out))
2007
+ return { stuck: out.stuck, witness: out.stuck === 'sat' ? out.witness : undefined, g: g };
2008
+ for (const h of usedHyps(g, out.tree))
2009
+ read(h);
2010
+ return { used, g: g };
2011
+ };
2012
+ let at = inst;
2013
+ const { result } = withModels(mm, ls, inst, i2 => (at = i2, goalOf(i2)), gs => ask(gs, at), x => (mapNames.length && x.stuck === 'sat' && x.witness ? { goal: x.g, w: x.witness } : undefined), x => !!x.used || x.stuck === 'sat');
2014
+ return result.used ? { used: result.used } : { stuck: result.stuck, witness: result.witness };
1792
2015
  };
1793
- const stateOf = (w) => ({ params: m.params.length ? Object.fromEntries(m.params.map(p => [p, w[p] ?? 0])) : params0, st: { scalars: Object.fromEntries(scalars.map(v => [v, w[v] ?? 0])), maps: mapsOf(w) } });
2016
+ const stateOf = (w) => {
2017
+ const st = { scalars: Object.fromEntries(scalars.map(v => [v, w[v] ?? 0])), maps: mapsOf(w) };
2018
+ named.set(st, new Set(Object.entries(st.maps).flatMap(([mp, cells]) => [...cells.keys()].map(k => `${mp}|${k}`))));
2019
+ return { params: m.params.length ? Object.fromEntries(m.params.map(p => [p, w[p] ?? 0])) : params0, st };
2020
+ };
2021
+ // (a step from a model's state names what it named and the cells the step wrote)
2022
+ const stepNamed = (st, next) => { const nm = named.get(st); if (nm)
2023
+ named.set(next, new Set([...nm, ...Object.entries(next.maps).flatMap(([mp, cells]) => [...cells].filter(([k, v]) => st.maps[mp]?.get(k) !== v).map(([k]) => `${mp}|${k}`))])); };
1794
2024
  // --- cubes: a point the samples leave out, as literals -------------------------------------------------------------
1795
2025
  const ctrl = modes.filter(mo => (mo.choice || mo.bool) && !atoms[mo.atom].cell && !atoms[mo.atom].param).map(mo => mo.atom);
1796
2026
  // (the rule's own comparisons first, then each value, then pairs: of two directions that leave out as many samples
@@ -1904,7 +2134,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1904
2134
  }
1905
2135
  return true;
1906
2136
  };
1907
- const formOf = (c) => ({ coef: [], d: 0, cells: false, cube: c, size: 1 });
2137
+ const formOf = (c, view) => ({ coef: [], d: 0, cells: false, cube: c, size: 1, ...(view !== undefined ? { view } : {}) });
1908
2138
  const witnessStep = (w) => {
1909
2139
  const pre = stateAt(w), input = Object.fromEntries(m.inputs.map(i => [i, w[i] ?? 0]));
1910
2140
  try {
@@ -1916,9 +2146,10 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1916
2146
  };
1917
2147
  // Is the cube's negation inductive relative to these laws (the caller's and the kinds' beside)? Its literals after
1918
2148
  // the step are hypotheses of their own, so the refutation's core names those it read.
1919
- const queryWith = (c, frame) => {
1920
- const f = formOf(c), own = lawFor(f), names2 = new Set([own.name]), ls = [...given, ...frame.filter(l => !names2.has(l.name) && !!names2.add(l.name)), own], mm = forLaws(ls).m;
1921
- const g = obligations(mm, ls, {}, ls.length - 1)[1], last = g.hyps.at(-1);
2149
+ const queryWith = (c, frame, view) => {
2150
+ const f = formOf(c, view), own = lawFor(f), names2 = new Set([own.name]), ls = [...given, ...frame.filter(l => !names2.has(l.name) && !!names2.add(l.name)), own], mm = forLaws(ls).m;
2151
+ // (a view's cube at the keys the prover would assume it and the rest at)
2152
+ const g = obligations(mm, ls, view !== undefined ? { [own.name]: lawInstances(mm, ls, ls.length - 1) } : {}, ls.length - 1)[1], last = g.hyps.at(-1);
1922
2153
  const inner = last.op === 'not' && last.x.op === 'not' && last.x.x.op === 'and' && last.x.x.xs.length === c.length ? last.x.x.xs : undefined;
1923
2154
  const tails = inner ?? [last], hyps = [...g.hyps.slice(0, -1), ...tails], base = hyps.length - tails.length;
1924
2155
  const out = budgeted(joinCubeMs, until2 => growCdcl({ name: 'a cube', hyps }, new Map(), { nodes: 0, until: until2 }, { model: true, core: true }));
@@ -1943,23 +2174,24 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1943
2174
  // refutation's core then cutting it further); within joinDownQueries queries. A cube's core reads most of its
1944
2175
  // literals where the step's terms are a chain of ifs (research/dag: a refutation's core is nearly its whole path), so
1945
2176
  // the core alone leaves a cube of every control value; Spacer's clauses on these tasks read two to four.
1946
- const down = (c, frame) => {
2177
+ const stateOut = (c) => !(initVec && inCube(c, initVec)) && !S.some(s2 => inCube(c, s2));
2178
+ const down = (c, frame, out = stateOut, view) => {
1947
2179
  let cur = c, queries = 0;
1948
2180
  for (let part = Math.ceil(cur.length / 2); part >= 1 && queries < joinDownQueries && now() < jUntil && !stop(); part = part === 1 ? 0 : Math.ceil(part / 2)) {
1949
2181
  for (let i = 0; i < cur.length && cur.length > 1 && queries < joinDownQueries && now() < jUntil && !stop();) {
1950
2182
  const cand = [...cur.slice(0, i), ...cur.slice(i + part)];
1951
- if (!cand.length || (initVec && inCube(cand, initVec)) || S.some(s2 => inCube(cand, s2))) {
2183
+ if (!cand.length || !out(cand)) {
1952
2184
  i += part;
1953
2185
  continue;
1954
2186
  }
1955
2187
  queries++;
1956
- const r = queryWith(cand, frame);
2188
+ const r = queryWith(cand, frame, view);
1957
2189
  if (!r?.ok) {
1958
2190
  i += part;
1959
2191
  continue;
1960
2192
  }
1961
2193
  const cut = cand.filter((_, j) => r.core.has(j));
1962
- cur = cut.length && !(initVec && inCube(cut, initVec)) && !S.some(s2 => inCube(cut, s2)) ? cut : cand;
2194
+ cur = cut.length && out(cut) ? cut : cand;
1963
2195
  }
1964
2196
  }
1965
2197
  return cur;
@@ -2022,6 +2254,62 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
2022
2254
  }
2023
2255
  return made;
2024
2256
  };
2257
+ // A view's cube (two holders, two tickets): a row of a counterexample no sample's row is, as literals over the view's
2258
+ // cells (each few-valued cell at its value, each equality between two cells of one map that holds there, then the
2259
+ // bounds that leave the samples' rows out), blocked as the state's cubes are (its negation proven relative to the
2260
+ // set, the literals it doesn't need taken out): a law at every tuple of the view's keys. The disjunctions a hull
2261
+ // can't say (two waiting threads' tickets differ) are such cubes.
2262
+ const viewSpaces = views.map(v => {
2263
+ const R = v.rows.slice(0, 3000).map(valuesOf), seen = new Set(R.map(vecKey)), mapOf = (i) => atoms[i].parts[0][0].slice(2, atoms[i].parts[0][0].lastIndexOf(AT));
2264
+ const own = v.atoms.filter(i => !atoms[i].int), few = own.filter(i => new Set(R.map(r => r[i])).size <= 3);
2265
+ const eqs = own.flatMap((i, a2) => own.slice(a2 + 1).filter(j => mapOf(i) === mapOf(j) && !few.includes(i)).flatMap(j => [{ lin: { coef: [[i, 1], [j, -1]], d: 0 } }, { lin: { coef: [[j, 1], [i, -1]], d: 0 } }]));
2266
+ const dirs = own.filter(i => !few.includes(i)).flatMap(i => [[[i, 1]], [[i, -1]]]);
2267
+ let starts = [];
2268
+ try {
2269
+ if (!m.params.length)
2270
+ starts = v.rowsOf({}, run.init({})).map(valuesOf);
2271
+ }
2272
+ catch {
2273
+ starts = [];
2274
+ }
2275
+ const out = (c) => !starts.some(x2 => inCube(c, x2)) && !R.some(x2 => inCube(c, x2));
2276
+ return { R, seen, few, eqs, dirs, out };
2277
+ });
2278
+ const viewCube = (p) => {
2279
+ for (const [vi, V] of viewSpaces.entries())
2280
+ for (const r of (p.views[vi] ?? []).slice(0, 8)) {
2281
+ const x2 = valuesOf(r);
2282
+ if (V.seen.has(vecKey(x2)))
2283
+ continue;
2284
+ const c = [...V.few.map(i => ({ at: { atom: i, value: x2[i] } })), ...V.eqs.filter(l => litHolds(l, x2))];
2285
+ for (let alive = V.R.filter(y => inCube(c, y)); alive.length;) {
2286
+ let best, bestN = 0;
2287
+ for (const t of V.dirs) {
2288
+ const tv = dot(t, x2);
2289
+ let cnt = 0;
2290
+ for (const y of alive)
2291
+ if (dot(t, y) > tv)
2292
+ cnt++;
2293
+ if (cnt > bestN)
2294
+ (bestN = cnt, best = t);
2295
+ }
2296
+ if (!best)
2297
+ break;
2298
+ const d = dot(best, x2);
2299
+ c.push({ lin: { coef: best, d } });
2300
+ alive = alive.filter(y => dot(best, y) <= d);
2301
+ }
2302
+ if (!V.out(c))
2303
+ continue;
2304
+ // (relative to the forms proven so far, as little of the set as will do; else the whole set, ungeneralized)
2305
+ const proven = set.filter(f => stood.has(textOf(f))).map(lawFor), r2 = queryWith(c, proven, vi);
2306
+ if (r2?.ok)
2307
+ return [formOf(joinDown ? down(c, proven, V.out, vi) : c, vi)];
2308
+ if (queryWith(c, set.map(lawFor), vi)?.ok)
2309
+ return [formOf(c, vi)];
2310
+ }
2311
+ return [];
2312
+ };
2025
2313
  // The control refined on demand (as CEGAR refines its predicates, here read off the rule): a counterexample to a
2026
2314
  // caller's law that the set allows and nothing rules out lies among the samples of its control state. A level of a
2027
2315
  // value the rule compares with a constant (the first, of the values the laws read first, whose levels keep the control
@@ -2070,9 +2358,23 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
2070
2358
  const rank = (f) => (inCone.has(textOf(f)) ? 0 : stood.has(textOf(f)) ? 1 : 2) * 1000 + f.coef.length * 10 + (f.never || f.nevers || f.also ? 1 : 0);
2071
2359
  const whole = set.filter(f => f !== todoForm);
2072
2360
  let ctx = [], witness, lastStuck = '', qms = 0, settled = false;
2361
+ // (before the whole set, the forms proven so far beside the context: a proof there is a proof with the whole set,
2362
+ // at a fraction of its hypotheses; a model there, the whole set asked as before)
2363
+ const provenFirst = () => { const ps = whole.filter(f => !ctx.includes(f) && stood.has(textOf(f))); return ps.length && ctx.length + ps.length < whole.length / 2 ? [...ctx, ...ps] : undefined; };
2073
2364
  for (let attempt = 0; attempt <= joinAttempts; attempt++) {
2074
- if (attempt === joinAttempts)
2365
+ if (attempt === joinAttempts && ctx !== whole) {
2366
+ const pf = provenFirst();
2367
+ if (pf) {
2368
+ const out = stepWith(todo, todoForm, pf);
2369
+ if ('used' in out) {
2370
+ stood.set(todo, out.used);
2371
+ opts.progress?.('join', { round: rounds, set: set.length, ms: qms, proven: todo.slice(0, 60), reads: out.used.length, ctx: pf.length, attempt });
2372
+ settled = true;
2373
+ break;
2374
+ }
2375
+ }
2075
2376
  ctx = whole;
2377
+ }
2076
2378
  const tq = performance.now(), out = stepWith(todo, todoForm, ctx);
2077
2379
  qms += Math.round(performance.now() - tq);
2078
2380
  if ('used' in out) {
@@ -2119,6 +2421,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
2119
2421
  let post;
2120
2422
  try {
2121
2423
  post = run.step(params, st, input);
2424
+ stepNamed(st, post);
2122
2425
  }
2123
2426
  catch {
2124
2427
  post = undefined;
@@ -2171,9 +2474,25 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
2171
2474
  }
2172
2475
  if (next)
2173
2476
  tried++;
2174
- opts.progress?.('join', { round: rounds, set: set.length, ms: qms, target: next ? textOf(next).slice(0, 60) : 'none', ...(next ? {} : { outside: outside ? 1 : 0 }) });
2477
+ opts.progress?.('join', { round: rounds, set: set.length, ms: qms, target: next ? textOf(next).slice(0, 60) : 'none', ...(next ? {} : { outside: outside ? 1 : 0, goal: todo.slice(0, 120) }) });
2175
2478
  if (!next && !alone && cube())
2176
2479
  continue;
2480
+ // (where the state's cube isn't blocked, a view's)
2481
+ if (!next && joinCubes && !outside && cubed < joinCubeMax && views.length) {
2482
+ const made = viewCube(pre).filter(f => !set.some(g2 => textOf(g2) === textOf(f)));
2483
+ opts.progress?.('join', { round: rounds, set: set.length, viewCubes: made.map(f => textOf(f).slice(0, 120)).join('; ') || 'none' });
2484
+ if (made.length) {
2485
+ cubed += made.length;
2486
+ extras.push(...made);
2487
+ continue;
2488
+ }
2489
+ }
2490
+ // (a found form nothing strengthens is dropped, as Houdini drops one: the cone finds its way round it or fails on
2491
+ // a caller's law)
2492
+ if (!next && !callers.has(todo)) {
2493
+ blocked.add(todo);
2494
+ continue;
2495
+ }
2177
2496
  if (!next) {
2178
2497
  why = 'target';
2179
2498
  break;