gdp-wired 0.44.0 → 0.46.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.
Files changed (133) hide show
  1. package/README.md +58 -7
  2. package/dist/core/bitsets.d.ts +2 -0
  3. package/dist/core/bitsets.js +23 -0
  4. package/dist/core/bmc.js +6 -2
  5. package/dist/core/c/reader.d.ts +9 -1
  6. package/dist/core/c/reader.js +445 -38
  7. package/dist/core/calendar.d.ts +29 -0
  8. package/dist/core/calendar.js +82 -0
  9. package/dist/core/check.js +3 -2
  10. package/dist/core/cli.d.ts +4 -0
  11. package/dist/core/cli.js +335 -39
  12. package/dist/core/compose.js +3 -1
  13. package/dist/core/counts.d.ts +5 -2
  14. package/dist/core/counts.js +335 -88
  15. package/dist/core/cycles.js +8 -1
  16. package/dist/core/cyclic.d.ts +1 -0
  17. package/dist/core/cyclic.js +13 -7
  18. package/dist/core/data-synth.d.ts +3 -0
  19. package/dist/core/data-synth.js +252 -0
  20. package/dist/core/data.d.ts +8 -2
  21. package/dist/core/data.js +1113 -172
  22. package/dist/core/discover.js +3 -1
  23. package/dist/core/draft.d.ts +19 -0
  24. package/dist/core/draft.js +53 -0
  25. package/dist/core/dsl.d.ts +39 -3
  26. package/dist/core/dsl.js +250 -31
  27. package/dist/core/effect-prims.js +2 -2
  28. package/dist/core/effect.d.ts +1 -4
  29. package/dist/core/effect.js +1 -15
  30. package/dist/core/ex/reader.exs +17 -1
  31. package/dist/core/exists.d.ts +16 -1
  32. package/dist/core/exists.js +447 -50
  33. package/dist/core/extract-c.d.ts +2 -0
  34. package/dist/core/extract-c.js +185 -31
  35. package/dist/core/extract-check.d.ts +7 -0
  36. package/dist/core/extract-check.js +115 -3
  37. package/dist/core/extract-ex.js +3 -3
  38. package/dist/core/extract-go-check.d.ts +1 -1
  39. package/dist/core/extract-go-check.js +21 -13
  40. package/dist/core/extract-go.d.ts +1 -0
  41. package/dist/core/extract-go.js +58 -9
  42. package/dist/core/extract-ir.d.ts +1 -0
  43. package/dist/core/extract-ir.js +15 -0
  44. package/dist/core/extract-jvm.d.ts +1 -1
  45. package/dist/core/extract-jvm.js +65 -14
  46. package/dist/core/extract-orm.d.ts +12 -0
  47. package/dist/core/extract-orm.js +244 -0
  48. package/dist/core/extract-print.js +23 -1
  49. package/dist/core/extract-py.d.ts +1 -0
  50. package/dist/core/extract-py.js +4 -4
  51. package/dist/core/extract-rb.js +3 -3
  52. package/dist/core/extract-read.d.ts +25 -0
  53. package/dist/core/extract-read.js +60 -5
  54. package/dist/core/extract-rs.js +22 -20
  55. package/dist/core/extract-shapes.js +22 -0
  56. package/dist/core/extract-sol.d.ts +10 -1
  57. package/dist/core/extract-sol.js +89 -30
  58. package/dist/core/extract-step.d.ts +201 -4
  59. package/dist/core/extract-step.js +1514 -111
  60. package/dist/core/extract-swift.js +24 -13
  61. package/dist/core/extract.d.ts +9 -0
  62. package/dist/core/extract.js +88 -7
  63. package/dist/core/fiber-run.d.ts +5 -0
  64. package/dist/core/fiber-run.js +18 -0
  65. package/dist/core/fresh.d.ts +2 -2
  66. package/dist/core/fresh.js +7 -3
  67. package/dist/core/go/reader.go +7 -1
  68. package/dist/core/infer.d.ts +4 -1
  69. package/dist/core/infer.js +1020 -246
  70. package/dist/core/jvm/JavaReader.java +33 -8
  71. package/dist/core/jvm/Jvm.java +20 -1
  72. package/dist/core/jvm/KtReader.java +59 -6
  73. package/dist/core/laws.d.ts +10 -3
  74. package/dist/core/laws.js +193 -14
  75. package/dist/core/machine.d.ts +16 -3
  76. package/dist/core/machine.js +212 -28
  77. package/dist/core/nonterm.js +14 -1
  78. package/dist/core/orm/harness.js +61 -0
  79. package/dist/core/orm-fixtures/schema.prisma +5 -0
  80. package/dist/core/py/harness.py +260 -21
  81. package/dist/core/py/reader.py +278 -39
  82. package/dist/core/rb/reader.rb +52 -5
  83. package/dist/core/reader-fixtures/README.md +28 -0
  84. package/dist/core/reader-fixtures/c-693042.cpp +8 -0
  85. package/dist/core/reader-fixtures/go-685506.go +14 -0
  86. package/dist/core/reader-fixtures/jvm-724362.kt +8 -0
  87. package/dist/core/reader-fixtures/jvm-737430.kt +7 -0
  88. package/dist/core/reader-fixtures/jvm-765282.kt +3 -0
  89. package/dist/core/reader-fixtures/swift-735726.swift +15 -0
  90. package/dist/core/reader-fixtures/swift-735990.swift +15 -0
  91. package/dist/core/reader-fixtures/swift-739158.swift +4 -0
  92. package/dist/core/reader-fixtures/swift-744834.swift +15 -0
  93. package/dist/core/reader-fixtures/swift-746946.swift +31 -0
  94. package/dist/core/reader-fixtures/typescript-673062.ts.txt +2 -0
  95. package/dist/core/relation.d.ts +1 -1
  96. package/dist/core/relation.js +29 -2
  97. package/dist/core/relational.js +4 -2
  98. package/dist/core/rs/src/main.rs +18 -2
  99. package/dist/core/sample-cache.d.ts +8 -0
  100. package/dist/core/sample-cache.js +46 -0
  101. package/dist/core/security.d.ts +38 -0
  102. package/dist/core/security.js +88 -0
  103. package/dist/core/sol/harness.py +63 -7
  104. package/dist/core/sol-concrete.d.ts +23 -0
  105. package/dist/core/sol-concrete.js +195 -0
  106. package/dist/core/solver.js +8 -5
  107. package/dist/core/swift/Sources/gdp-swiftreader/main.swift +50 -7
  108. package/dist/core/system.d.ts +62 -1
  109. package/dist/core/system.js +263 -4
  110. package/dist/core/transfer.js +39 -9
  111. package/dist/core/translate.js +39 -10
  112. package/dist/core/watch.js +51 -6
  113. package/dist/interchange/check.js +10 -10
  114. package/dist/interchange/format.d.ts +4 -0
  115. package/dist/interchange/format.js +24 -6
  116. package/dist/kernel/cdcl.d.ts +5 -0
  117. package/dist/kernel/cdcl.js +88 -10
  118. package/dist/kernel/epr.js +141 -29
  119. package/dist/kernel/kernel.d.ts +31 -1
  120. package/dist/kernel/kernel.js +391 -101
  121. package/dist/kernel/model-sequence.d.ts +3 -0
  122. package/dist/kernel/model-sequence.js +34 -0
  123. package/dist/kernel/prove.d.ts +30 -1
  124. package/dist/kernel/prove.js +481 -71
  125. package/dist/kernel/reader.d.ts +3 -0
  126. package/dist/kernel/reader.js +101 -14
  127. package/dist/kernel/share.d.ts +1 -0
  128. package/dist/kernel/share.js +27 -0
  129. package/dist/lean-kernel/emit.d.ts +9 -3
  130. package/dist/lean-kernel/emit.js +200 -66
  131. package/dist/lean-kernel/lean-terms.js +5 -0
  132. package/dist/lean-kernel/library.js +10 -10
  133. package/package.json +7 -2
@@ -32,11 +32,13 @@
32
32
  // rules it out (and the most of those seen) is added; a chosen candidate that nothing supports, or that makes a proof slow, is dropped; the set proven as a whole
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
- import { all, any, atMost, carriedView, compileC, compileE, loadJs, divisorsIn, evalC, evalE, get, interpret, machineTerms, fnValue, modName, n, not, plus, same, searchSeeded, times, walk, withArithmetic, x } from "./machine.js";
35
+ import { bitIntersection, bitIntersects } from "./bitsets.js";
36
+ import { samplePredicates, sampleStateText } from "./sample-cache.js";
37
+ import { all, any, atMost, carriedView, compileC, compileE, cpair, fastStep, divisorsIn, evalC, evalE, get, interpret, machineTerms, fnValue, modName, n, not, partsOf as tupleOf, plus, same, seeded, times, walk, withArithmetic, x } from "./machine.js";
36
38
  import { bool, proveRule, proveSteps, verdictOf } from "./dsl.js";
37
39
  import { allowed, keysOf, linKey, watch } from "./watch.js";
38
40
  import { clock, counted, fullWork, decideLaw, decideNote, machineKey, memoHits, withStrict, fullRate, grow, keyValue, lawInstances, proveLaw, proveLaws, proveSetFast, proveStepLaws, stepLawInstances, usedHyps, withDeadline, withModels, withTrees, withWall, withWork } from "../kernel/prove.js";
39
- import { assumed, obligations, plainOf, stepLawObligations, substC } from "../kernel/kernel.js";
41
+ import { assumed, eachParts, obligations, plainOf, stepLawObligations, substC, tuple, tupleParts } from "../kernel/kernel.js";
40
42
  import { env, gcd, work } from "./solver.js";
41
43
  import { bgcd } from "./q.js";
42
44
  import { showC, showE } from "./exists.js";
@@ -93,7 +95,7 @@ const joinDown = env.GDP_JOIN_DOWN !== '0', joinDownQueries = 24;
93
95
  const inferHalves = env.GDP_INFER_HALVES !== '0';
94
96
  const isRule = (t) => typeof t.kindsOfState === 'function';
95
97
  // The constants a machine's expressions hold, and the factors it multiplies by.
96
- function constantsOf(m, laws) {
98
+ export function constantsOf(m, laws) {
97
99
  const out = new Set();
98
100
  const e = (t) => {
99
101
  switch (t.op) {
@@ -110,9 +112,13 @@ function constantsOf(m, laws) {
110
112
  case 'min':
111
113
  case 'max':
112
114
  case 'prod':
115
+ case 'tup':
113
116
  e(t.a);
114
117
  e(t.b);
115
118
  break;
119
+ case 'proj':
120
+ e(t.a);
121
+ break; // the selector is not an arithmetic constant
116
122
  case 'if':
117
123
  c(t.c);
118
124
  e(t.then);
@@ -159,11 +165,256 @@ function constantsOf(m, laws) {
159
165
  laws.forEach(l => c(l.holds));
160
166
  return [...out].filter(k => Number.isSafeInteger(k) && Math.abs(k) <= 1e6);
161
167
  }
168
+ // (a view's keys that are terms of the others (`defs`): its laws read the terms in their place, and quantify the rest)
169
+ const defsOf = (v) => ({ vars: Object.fromEntries(v.vars.flatMap((k, i) => (v.defs?.[i] ? [[k, v.defs[i]]] : []))), maps: {}, flags: {} });
162
170
  // A key's linear form over the names `ok` admits, into `out` (`1` the constant); false where it is none.
163
171
  const conj = (c) => (c.op === 'and' ? c.xs.flatMap(conj) : [c]);
164
172
  // A few values: at most four, none past 8: a mode's, and a view's cell reads each of them as a literal (as it does any
165
173
  // three: a program counter's four phases are a mode, and were no literal of a view)
166
174
  const few = (vals) => vals.length <= 4 && vals.every(x => x <= 8);
175
+ // A step of a rule of relations for the samples (untrusted: they only suggest candidates): each write at every tuple
176
+ // of a relation evaluated, compiled, at every tuple of parts below a bound past every value the state, params and
177
+ // request hold (the interpreter's breakpoints at every part make a step of a four-place relation thousands of
178
+ // interpreted evaluations); the rest of the step the interpreter's. Its first steps are checked against the
179
+ // interpreter's, and one that differs, or a domain past `most` tuples, leaves the interpreter's.
180
+ export function domainStep(m, most = 20_000) {
181
+ // (every write at every key, a relation's at its tuples and a plain map's at its keys, n 1; a write at one key as itself)
182
+ const tupled = (mp) => (m.relations?.[mp]?.length ?? 0) > 1;
183
+ if (!Object.entries(m.step.maps ?? {}).some(([mp, w]) => 'each' in w && tupled(mp)) || m.history || m.leasts || m.inputMaps?.length || m.counts || m.fns)
184
+ return undefined;
185
+ // (a write at every key of a map keyed by tuples that names no relation: the interpreter's)
186
+ if (Object.entries(m.step.maps ?? {}).some(([mp, w]) => 'each' in w && !tupled(mp) && JSON.stringify(w).includes('"op":"proj"')))
187
+ return undefined;
188
+ const rels = Object.entries(m.step.maps ?? {}).flatMap(([mp, w]) => ('each' in w ? [{ mp, n: tupled(mp) ? m.relations[mp].length : 1, w }] : []));
189
+ const keyed = Object.entries(m.step.maps ?? {}).flatMap(([mp, w]) => ('each' in w ? [] : [{ mp, key: compileE(w.key, m), value: compileE(w.value, m) }]));
190
+ const scalarsNext = Object.entries(m.step.state ?? {}).map(([v, e]) => [v, compileE(e, m)]);
191
+ const run = interpret(m);
192
+ const each = rels.map(r => { const t = eachParts(r.w, r.n); return { ...r, names: t.names, value: t.value, f: compileE(t.value, m) }; });
193
+ const mentions = (t, names) => { let hit = false; walk(t, o => { if (o.op === 'var' && names.has(String(o.name)))
194
+ hit = true; }); return hit; };
195
+ const merge = (a, b) => { const o = new Map(a); for (const [k, v] of b) {
196
+ if (o.has(k) && o.get(k) !== v)
197
+ return undefined;
198
+ o.set(k, v);
199
+ } return o; };
200
+ const pinInfo = new Map(each.map(r => [r, { names: new Set(r.names), own: JSON.stringify(tuple(r.names.map((nm) => ({ op: 'var', name: nm })))), ground: new WeakMap(), owns: new WeakMap() }]));
201
+ const pinEs = new WeakMap(), pinCs = new WeakMap();
202
+ const pinsOf = (r, env, st) => {
203
+ const info = pinInfo.get(r), { names, own } = info;
204
+ const ground = (t) => { let b = info.ground.get(t); if (b === undefined) {
205
+ b = !mentions(t, names);
206
+ info.ground.set(t, b);
207
+ } return b; };
208
+ const evE = (e) => { let f = pinEs.get(e); if (!f) {
209
+ f = compileE(e, m);
210
+ pinEs.set(e, f);
211
+ } return f(env, st); };
212
+ const evC = (c) => { let f = pinCs.get(c); if (!f) {
213
+ f = compileC(c, m);
214
+ pinCs.set(c, f);
215
+ } return f(env, st); };
216
+ const any = [new Map()];
217
+ const isOwn = (e) => { let b = info.owns.get(e); if (b === undefined) {
218
+ b = e.op === 'get' && e.map === r.mp && JSON.stringify(e.key) === own;
219
+ info.owns.set(e, b);
220
+ } return b; };
221
+ const c2 = (c) => {
222
+ if (c.op === 'flag')
223
+ return env[`?${c.name}`] === 1 ? any : 'no';
224
+ if (c.op === 'and') {
225
+ let acc = [new Map()];
226
+ for (const y of c.xs) {
227
+ const p2 = c2(y);
228
+ if (p2 === 'no')
229
+ return 'no';
230
+ acc = acc.flatMap(a => p2.flatMap(b => { const o = merge(a, b); return o ? [o] : []; }));
231
+ if (!acc.length)
232
+ return 'no';
233
+ if (acc.length > 256)
234
+ return any;
235
+ }
236
+ return acc;
237
+ }
238
+ if (c.op === 'or') {
239
+ const out = [];
240
+ for (const y of c.xs) {
241
+ const p2 = c2(y);
242
+ if (p2 !== 'no')
243
+ out.push(...p2);
244
+ }
245
+ return out.length ? (out.some(q => !q.size) ? any : out) : 'no';
246
+ }
247
+ if (c.op === 'not')
248
+ return ground(c.x) ? (evC(c.x) ? 'no' : any) : any;
249
+ if (c.op === 'all')
250
+ return ground(c) ? (evC(c) ? any : 'no') : any;
251
+ if (c.op === '<' || c.op === '<=' || c.op === '=') {
252
+ if (ground(c))
253
+ return evC(c) ? any : 'no';
254
+ // (the own cell at the tuple: 0 here, so own ≥ 1 is false and own = 0, own ≤ 0 true)
255
+ if (isOwn(c.b) && ground(c.a))
256
+ return compare(c.op, evE(c.a), 0) ? any : 'no';
257
+ if (isOwn(c.a) && ground(c.b))
258
+ return compare(c.op, 0, evE(c.b)) ? any : 'no';
259
+ if (c.op === '=')
260
+ for (const [a, b] of [[c.a, c.b], [c.b, c.a]])
261
+ if (a.op === 'var' && names.has(a.name) && ground(b))
262
+ return [new Map([[r.names.indexOf(a.name), evE(b)]])];
263
+ }
264
+ return any;
265
+ };
266
+ const and2 = (a, b) => { if (a === 'no' || b === 'no')
267
+ return 'no'; const o = a.flatMap(x2 => b.flatMap(y => { const q = merge(x2, y); return q ? [q] : []; })); return !o.length ? 'no' : o.length > 256 ? any : o; };
268
+ const or2 = (a, b) => (a === 'no' ? b : b === 'no' ? a : [...a, ...b].some(q => !q.size) ? any : [...a, ...b]);
269
+ const e2 = (e) => {
270
+ if (e.op === 'const')
271
+ return e.value ? any : 'no';
272
+ if (isOwn(e))
273
+ return 'no';
274
+ if (e.op === 'if')
275
+ return ground(e.c) ? e2(evC(e.c) ? e.then : e.else) : or2(and2(c2(e.c), e2(e.then)), and2(c2({ op: 'not', x: e.c }), e2(e.else)));
276
+ return ground(e) ? (evE(e) ? any : 'no') : any;
277
+ };
278
+ return e2(r.value);
279
+ };
280
+ const compare = (op, a, b) => (op === '<' ? a < b : op === '<=' ? a <= b : a === b);
281
+ // (a condition at every key read at the keys below the bound and one past it: past every value the state, request and
282
+ // the rule's own constants hold, no read moves and no comparison turns; the interpreter's breakpoints otherwise)
283
+ const constTop = Math.max(0, ...[...JSON.stringify([m.step, m.assume ?? null]).matchAll(/"value":(\d+)/g)].map(q => Number(q[1])));
284
+ const domC = (c) => {
285
+ if (c.op === 'all' && !c.keys?.length) {
286
+ const body = domC(c.c), k = c.key;
287
+ return (env, st, D) => { const was = env[k]; try {
288
+ for (let i = 0; i <= Math.max(D, constTop + 2); i++) {
289
+ env[k] = i;
290
+ if (!body(env, st, D))
291
+ return false;
292
+ }
293
+ return true;
294
+ }
295
+ finally {
296
+ if (was === undefined)
297
+ delete env[k];
298
+ else
299
+ env[k] = was;
300
+ } };
301
+ }
302
+ if (c.op === 'and') {
303
+ const xs = c.xs.map(domC);
304
+ return (env, st, D) => xs.every(x2 => x2(env, st, D));
305
+ }
306
+ if (c.op === 'or') {
307
+ const xs = c.xs.map(domC);
308
+ return (env, st, D) => xs.some(x2 => x2(env, st, D));
309
+ }
310
+ if (c.op === 'not') {
311
+ const y = domC(c.x);
312
+ return (env, st, D) => !y(env, st, D);
313
+ }
314
+ const f = JSON.stringify(c).includes('"op":"all"') ? (env, st) => evalC(c, env, st, m) : compileC(c, m);
315
+ return (env, st) => f(env, st);
316
+ };
317
+ const flags = Object.entries(m.step.flags ?? {}).map(([name, c]) => [name, domC(c)]), assume = m.assume ? domC(m.assume) : undefined;
318
+ let checks = 6, off = false;
319
+ const sameCells = (a, b) => b !== undefined && a.size === b.size && [...a].every(([k, v]) => b.has(k) && b.get(k) === v);
320
+ const sameFields = (a, b) => Object.keys(a).length === Object.keys(b).length && Object.entries(a).every(([k, v]) => Object.hasOwn(b, k) && b[k] === v);
321
+ const same2 = (a, b) => JSON.stringify([a.scalars, Object.entries(a.maps).map(([k, c]) => [k, [...c].sort((p, q) => p[0] - q[0])])]) === JSON.stringify([b.scalars, Object.entries(b.maps).map(([k, c]) => [k, [...c].sort((p, q) => p[0] - q[0])])]);
322
+ const slow = (params, st, input) => (allowed(m, run, params, st, input) ? run.step(params, st, input) : undefined);
323
+ return (params, st, input) => {
324
+ if (off)
325
+ return slow(params, st, input);
326
+ let top = 0;
327
+ for (const v of [...Object.values(params), ...Object.values(st.scalars), ...Object.values(input)])
328
+ if (typeof v === 'number' && v > top)
329
+ top = v;
330
+ for (const [mp, cells] of Object.entries(st.maps))
331
+ for (const k of cells.keys()) {
332
+ if (tupled(mp)) {
333
+ for (const d of tupleOf(k, m.relations[mp].length))
334
+ if (d > top)
335
+ top = d;
336
+ }
337
+ else if (k > top)
338
+ top = k;
339
+ }
340
+ const D = top + 2;
341
+ if (each.some(r => D ** r.n > most))
342
+ return slow(params, st, input);
343
+ // (as the interpreter's step: the flags in turn, the assumption, then every value read off the state before it)
344
+ const env = { ...params };
345
+ for (const i of m.inputs)
346
+ if (typeof input[i] === 'number')
347
+ env[i] = input[i];
348
+ for (const [name, c] of flags)
349
+ env[`?${name}`] = c(env, st, D) ? 1 : 0;
350
+ if (assume && !assume(env, st, D))
351
+ return undefined;
352
+ // Samples are immutable: bulk writes replace their map, and point writes
353
+ // copy only a changed map. Never clone a map just before replacing it.
354
+ const next = { scalars: { ...st.scalars }, maps: { ...st.maps } };
355
+ for (const [v, f] of scalarsNext)
356
+ next.scalars[v] = f(env, st);
357
+ const sets = keyed.map(w => [w.mp, w.key(env, st), w.value(env, st)]);
358
+ const defaults = { ...st.defaults };
359
+ for (const r of each) {
360
+ const far = r.names.map(() => D + 1);
361
+ r.names.forEach((nm, i) => (env[nm] = far[i]));
362
+ const fallback = r.f(env, st), cells = new Map(), at = (xs) => { r.names.forEach((nm, i) => (env[nm] = xs[i])); const v = r.f(env, st); if (v !== fallback)
363
+ cells.set(xs.slice(0, -1).reduceRight((b, a) => cpair(a, b), xs.at(-1)), v); };
364
+ // (the tuples it holds and those its pins allow, where its cells are 0 by default; else every tuple below D)
365
+ const pins = fallback === 0 && !st.defaults?.[r.mp] && !m.maps?.[r.mp] ? pinsOf(r, env, st) : undefined;
366
+ if (r.n === 1)
367
+ for (const k of st.maps[r.mp]?.keys() ?? [])
368
+ if (k >= D)
369
+ at([k]);
370
+ const each2 = (fixed) => { const xs = r.names.map((_, i) => fixed.get(i) ?? 0), free = r.names.map((_, i) => i).filter(i => !fixed.has(i)); for (;;) {
371
+ at(xs);
372
+ let j = free.length - 1;
373
+ while (j >= 0 && ++xs[free[j]] === D)
374
+ xs[free[j--]] = 0;
375
+ if (j < 0)
376
+ break;
377
+ } };
378
+ if (pins) {
379
+ for (const k of st.maps[r.mp]?.keys() ?? [])
380
+ at(tupleOf(k, r.n));
381
+ if (pins !== 'no')
382
+ for (const p2 of pins)
383
+ each2(p2);
384
+ }
385
+ else
386
+ each2(new Map());
387
+ next.maps[r.mp] = sameCells(cells, st.maps[r.mp]) ? st.maps[r.mp] : cells;
388
+ defaults[r.mp] = fallback;
389
+ }
390
+ for (const [mp, k, v] of sets) {
391
+ const old = st.maps[mp];
392
+ if (!old.has(k) || old.get(k) !== v) {
393
+ const cells = new Map(old);
394
+ cells.set(k, v);
395
+ next.maps[mp] = cells;
396
+ }
397
+ }
398
+ const out = { ...next, defaults };
399
+ if (checks > 0) {
400
+ checks--;
401
+ let want;
402
+ try {
403
+ want = run.step(params, st, input);
404
+ }
405
+ catch {
406
+ want = undefined;
407
+ }
408
+ if (!want || !same2(want, out)) {
409
+ off = true;
410
+ return slow(params, st, input);
411
+ }
412
+ }
413
+ // Keep the reference cross-check above even for a no-op. Reusing the state
414
+ // also reuses its canonical key, without changing any sampled transition.
415
+ return st.defaults !== undefined && sameFields(defaults, st.defaults) && sameFields(next.scalars, st.scalars) && Object.entries(next.maps).every(([mp, cells]) => cells === st.maps[mp]) ? st : out;
416
+ };
417
+ }
167
418
  function pairingOf(m) {
168
419
  const inputs = new Set(m.inputs), input = (v) => inputs.has(v);
169
420
  let found;
@@ -208,15 +459,15 @@ function pairingOf(m) {
208
459
  // 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
209
460
  // keys are named apart (`L:law:key`). What a view of a law needs of it: its keys' sorts, the composed keys its reads
210
461
  // 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.
211
- function keySorts(m, laws, pairing) {
462
+ function keySorts(m, laws, pairing, fine = false) {
212
463
  const parent = new Map();
213
464
  const find = (a) => { const p2 = parent.get(a); if (p2 === undefined || p2 === a)
214
465
  return a; const r = find(p2); parent.set(a, r); return r; };
215
466
  const union = (a, b) => { const ra = find(a), rb = find(b); if (ra !== rb)
216
467
  parent.set(ra, rb); };
217
- const composed = new Set(), plainRead = new Set();
468
+ const composed = new Set(), plainRead = new Set(), tupled = new Set();
218
469
  const split = (key, name) => {
219
- if (!pairing?.n)
470
+ if (!pairing?.n || fine)
220
471
  return undefined;
221
472
  const lin = new Map();
222
473
  if (!linKey(key, () => true, 1, lin))
@@ -228,7 +479,8 @@ function keySorts(m, laws, pairing) {
228
479
  const a = hi && name(hi[0]), b = lo && name(lo[0]);
229
480
  return a && b ? [a, b] : undefined;
230
481
  };
231
- // (a key of three or more parts, N²·a + N·b + c: its parts, each a place of its own, `${k}:${i}`)
482
+ // (a key of three or more parts, N²·a + N·b + c: its parts, each a place of its own, `${k}:${i}`; `fine`, the engine's:
483
+ // of two parts too, so a map's row and column are sorts of their own unless a key read in both unites them)
232
484
  const arity = new Map();
233
485
  const parts = (key, name) => {
234
486
  if (!pairing?.n)
@@ -237,13 +489,43 @@ function keySorts(m, laws, pairing) {
237
489
  if (!linKey(key, () => true, 1, lin) || (lin.get('1') ?? 0) !== pairing.c)
238
490
  return undefined;
239
491
  const vs = [...lin].filter(([v, c]) => v !== '1' && c).sort((a, b) => b[1] - a[1]), ns = vs.map(([v]) => name(v));
240
- return vs.length >= 3 && vs.every(([, c], i) => c === pairing.n ** (vs.length - 1 - i)) && ns.every(Boolean) ? ns : undefined;
492
+ return vs.length >= (fine ? 2 : 3) && vs.every(([, c], i) => c === pairing.n ** (vs.length - 1 - i)) && ns.every(Boolean) ? ns : undefined;
241
493
  };
242
494
  const kids = (t, f) => { for (const v of Object.values(t))
243
495
  if (v && typeof v === 'object')
244
496
  (Array.isArray(v) ? v : [v]).forEach(y => { if (y && typeof y === 'object' && 'op' in y)
245
497
  f(y); }); };
498
+ // (a tuple key's part: a name, or the i-th part of a write at every key's own key, proj 0 ∘ proj 1ⁱ or proj 1ⁱ of it)
499
+ const partName = (e, name) => {
500
+ if (e.op === 'var')
501
+ return name(e.name);
502
+ let j = 0, y = e.op === 'proj' && e.k === 0 ? e.a : e;
503
+ while (y.op === 'proj' && y.k === 1) {
504
+ j++;
505
+ y = y.a;
506
+ }
507
+ const own = y !== e && y.op === 'var' ? name(y.name) : undefined;
508
+ return own?.startsWith('M:') && tupled.has(own.slice(2)) ? `${own.slice(2)}:${j}` : undefined;
509
+ };
246
510
  const walk = (t, name) => {
511
+ // (a map keyed by tuples: each part a place of its own, `${map}:${i}`, compared part by part, never by arithmetic)
512
+ if (t.op === 'get' && t.key.op === 'tup' && t.map in (m.maps ?? {})) {
513
+ const ps = tupleParts(t.key);
514
+ arity.set(t.map, ps.length);
515
+ tupled.add(t.map);
516
+ ps.forEach((q, i) => { const nm = partName(q, name); if (nm)
517
+ union(nm, `${t.map}:${i}`);
518
+ else
519
+ walk(q, name); });
520
+ return;
521
+ }
522
+ if (t.op === '=' && t.a.op !== 'tup' && t.b.op !== 'tup') {
523
+ const a = partName(t.a, name), b = partName(t.b, name);
524
+ if (a && b && (t.a.op !== 'var' || t.b.op !== 'var')) {
525
+ union(a, b);
526
+ return;
527
+ }
528
+ }
247
529
  if (t.op === 'get') {
248
530
  // (a carried map's key has its cells' sort, as a map's: the quorum a request brings, read where the stored one is)
249
531
  const carried = (m.inputMaps ?? []).includes(t.map);
@@ -294,6 +576,13 @@ function keySorts(m, laws, pairing) {
294
576
  union(a, b);
295
577
  return;
296
578
  }
579
+ // (`fine`: a key compared with a cell, as a value it holds (Table[a·N + k] = v + 1), is of the cells' values' sort)
580
+ if (fine && t.op === '=')
581
+ for (const [c, e] of [[t.a, t.b], [t.b, t.a]]) {
582
+ const vr = e.op === 'var' ? e : e.op === 'add' && e.a.op === 'var' && e.b.op === 'const' ? e.a : undefined;
583
+ if (c.op === 'get' && c.map in (m.maps ?? {}) && vr && name(vr.name))
584
+ union(name(vr.name), `V:${c.map}`);
585
+ }
297
586
  // (a write at every key of k parts at one: z = N²·n + N·k + v)
298
587
  if (t.op === '=' && t.a.op === 'var' && name(t.a.name)?.startsWith('M:')) {
299
588
  const mp = name(t.a.name).slice(2), ps = parts(t.b, name);
@@ -305,6 +594,16 @@ function keySorts(m, laws, pairing) {
305
594
  kids(t, y => walk(y, name));
306
595
  };
307
596
  const inputs = new Set(m.inputs), rule = (v) => (inputs.has(v) ? v : undefined);
597
+ // (the relations' place sorts, where the rule names them: Machine.relations, a hint read first)
598
+ for (const [mp, srts] of Object.entries(m.relations ?? {})) {
599
+ if (srts.length > 1) {
600
+ arity.set(mp, srts.length);
601
+ tupled.add(mp);
602
+ srts.forEach((q, i) => union(`${mp}:${i}`, `R:${q}`));
603
+ }
604
+ else if (srts.length === 1)
605
+ union(`M:${mp}`, `R:${srts[0]}`);
606
+ }
308
607
  for (const [mp, w] of Object.entries(m.step.maps ?? {})) {
309
608
  if ('each' in w)
310
609
  walk(w.value, v => (v === w.each ? `M:${mp}` : rule(v)));
@@ -312,6 +611,15 @@ function keySorts(m, laws, pairing) {
312
611
  walk({ op: 'get', map: mp, key: w.key }, rule);
313
612
  walk(w.value, rule);
314
613
  }
614
+ // (`fine`: a value written to a cell, an input or one past it, of the cells' values' sort)
615
+ if (fine) {
616
+ const leaves = (e) => (e.op === 'if' ? [...leaves(e.then), ...leaves(e.else)] : [e]);
617
+ for (const l of leaves(w.value)) {
618
+ const vr = l.op === 'var' ? l : l.op === 'add' && l.a.op === 'var' && l.b.op === 'const' ? l.a : undefined;
619
+ if (vr && rule(vr.name))
620
+ union(vr.name, `V:${mp}`);
621
+ }
622
+ }
315
623
  }
316
624
  for (const e of Object.values(m.step.state ?? {}))
317
625
  walk(e, rule);
@@ -328,6 +636,7 @@ function keySorts(m, laws, pairing) {
328
636
  // (a map of keys of k parts read at a write at every key's own key is no plain read)
329
637
  for (const mp of arity.keys())
330
638
  plainRead.delete(mp);
639
+ const composeAll = (ts) => { const k = ts.reduce((acc, t) => plus(times(pairing.n, acc), t)); return pairing.c ? plus(k, n(pairing.c)) : k; };
331
640
  return {
332
641
  find,
333
642
  sortOf: (l, v) => find(`L:${l.name}:${v}`),
@@ -352,9 +661,11 @@ function keySorts(m, laws, pairing) {
352
661
  },
353
662
  // (a guard that reads the state or params beside the keys: a domain that moves)
354
663
  moving: (g, bound) => [...JSON.stringify(g).matchAll(/"name":"([^"]+)"/g)].some(q => !bound.includes(q[1])),
355
- composedMaps: [...composed], plainRead: [...plainRead], arity,
664
+ composedMaps: [...composed], plainRead: [...plainRead], arity, tupled,
665
+ // (a map's key at these parts: a tuple where the map is keyed by tuples, else the radix's)
666
+ keyOf: (mp, ts) => (tupled.has(mp) ? tuple(ts) : composeAll(ts)),
356
667
  // (a key of k parts at these key terms)
357
- composeAll: (ts) => { const k = ts.reduce((acc, t) => plus(times(pairing.n, acc), t)); return pairing.c ? plus(k, n(pairing.c)) : k; },
668
+ composeAll,
358
669
  compose: (a, b) => { const k = plus(times(pairing.n, a), b); return pairing.c ? plus(k, n(pairing.c)) : k; },
359
670
  plainMaps: (sort) => [...plainRead].filter(mp => find(`M:${mp}`) === sort),
360
671
  valuesAt: (st, sort) => {
@@ -370,6 +681,11 @@ function keySorts(m, laws, pairing) {
370
681
  ks.add((k - pairing.c) % pairing.n);
371
682
  }
372
683
  const ar = arity.get(mp);
684
+ if (ar && tupled.has(mp)) {
685
+ tupleOf(k, ar).forEach((d, i) => { if (find(`${mp}:${i}`) === sort)
686
+ ks.add(d); });
687
+ continue;
688
+ }
373
689
  if (ar && pairing?.n && k >= pairing.c)
374
690
  for (let i = ar - 1, r = k - pairing.c; i >= 0; i--, r = Math.floor(r / pairing.n))
375
691
  if (find(`${mp}:${i}`) === sort)
@@ -454,7 +770,9 @@ function preimages(m, laws, stepLaws, atoms, coords) {
454
770
  case 'min':
455
771
  case 'max': return uniq([...linE(e.a, post), ...linE(e.b, post)]);
456
772
  case 'if': return uniq([...linE(e.then, post), ...linE(e.else, post)]);
457
- case 'prod': return [];
773
+ case 'prod':
774
+ case 'tup':
775
+ case 'proj': return [];
458
776
  case 'get': {
459
777
  const name = e.map.endsWith("'") && maps.has(e.map.slice(0, -1)) ? e.map.slice(0, -1) : e.map;
460
778
  if (!maps.has(name))
@@ -698,7 +1016,9 @@ function comparisons(m, laws, atoms, coords, more = []) {
698
1016
  return [...found.values()];
699
1017
  }
700
1018
  export function inferLaws(target, laws, stepLaws = [], opts = {}) {
701
- return quietly(() => withDeadline(clock() + (opts.wall === undefined ? opts.ms ?? 20000 : Math.max(0, opts.wall - performance.now())), () => inferLawsSearch(target, laws, stepLaws, opts)));
1019
+ // Repeated rounds and minimization can ask the same root goal again. Keep only
1020
+ // completed trees for this search, keyed by exact hypotheses and prover modes.
1021
+ return withTrees(() => quietly(() => withDeadline(clock() + (opts.wall === undefined ? opts.ms ?? 20000 : Math.max(0, opts.wall - performance.now())), () => inferLawsSearch(target, laws, stepLaws, opts))));
702
1022
  }
703
1023
  function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
704
1024
  // (GDP_INFER_TRACE=2: each phase's progress too, to stderr)
@@ -767,25 +1087,40 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
767
1087
  if ((first.proven && first.checked) || first.run)
768
1088
  return { ...first, found: [], stats: stats(0, 0, 0) };
769
1089
  // --- runs ------------------------------------------------------------------------------------------------------------
770
- const run = interpret(m), rand = searchSeeded(17), kinds = rule ? rule.kindsOfState() : [];
1090
+ const run = interpret(m), rand = seeded(17), kinds = rule ? rule.kindsOfState() : [];
771
1091
  const given = rule ? [...rule.kindLaws().filter(k => !laws.some(l => l.name === k.name)), ...laws] : laws;
772
1092
  const randomParams = (bound, r = rand) => (rule ? rule.randomParams(r, bound) : Object.fromEntries(m.params.map(p => [p, r(bound + 1)])));
773
1093
  const randomInput = (params, bound, r = rand) => (rule ? rule.randomInput(r, bound, params)
774
1094
  : { ...Object.fromEntries(m.inputs.map(i => [i, r(bound + 1)])), ...Object.fromEntries((m.inputMaps ?? []).map(i => [i, new Map()])) });
775
- const samples = [], cap = 3000;
776
- const keep = (s) => { if (samples.length < cap)
777
- samples.push(s);
778
- else if (rand(4) === 0)
779
- samples[rand(cap)] = s; };
1095
+ // (each state once: a machine with no requests walks one path, and its copies pushed out the caller's states (opts.seen))
1096
+ const samples = [], cap = 3000, keys = [], held = new Set();
1097
+ const mapsText = (st) => JSON.stringify(Object.values(st.maps).map(c => [...c]));
1098
+ let offered = 0;
1099
+ // (how many states offered held each value of each state variable: `rare`, below)
1100
+ const stateVars = Object.keys(m.state), seenAt = stateVars.map(() => new Map()), withMaps = Object.keys(m.maps ?? {}).length > 0;
1101
+ const keep = (s) => {
1102
+ offered++;
1103
+ stateVars.forEach((v, i) => { const x2 = s.st.scalars[v] ?? 0; seenAt[i].set(x2, (seenAt[i].get(x2) ?? 0) + 1); });
1104
+ const k = JSON.stringify([s.params, s.st.scalars, s.st.defaults ?? 0]) + mapsText(s.st), i = held.has(k) ? -1 : samples.length < cap ? samples.length : rand(4) === 0 ? rand(cap) : -1;
1105
+ if (i < 0)
1106
+ return;
1107
+ if (i < samples.length)
1108
+ held.delete(keys[i]);
1109
+ samples[i] = s;
1110
+ keys[i] = k;
1111
+ held.add(k);
1112
+ };
780
1113
  for (const st of opts.seen ?? [])
781
1114
  if (!m.params.length)
782
1115
  keep({ params: {}, st });
783
1116
  trace('start');
784
- const mapsText = (st) => JSON.stringify(Object.values(st.maps).map(c => [...c]));
785
- // Counted: `runs` requests tried at least, and on until the samples are full (a trial keeps its start at least, so as
786
- // many trials as they hold fill them), the trials at most `runs` or that many. Timed: `runsMs` of wall time.
787
- const runsTimed = timed || opts.runsMs !== undefined, runsUntil = Math.min(wallUntil, performance.now() + (opts.runsMs ?? 500)), least = opts.runs ?? Math.min(inferRuns, Math.max(2000, 4 * ms));
788
- const moreRuns = (trial) => (runsTimed ? performance.now() < runsUntil : trial < Math.max(cap, least) && (used.tries < least || samples.length < cap) && !stop());
1117
+ // Counted: `runs` requests tried at least, and on until as many states as the samples hold were offered (a trial offers
1118
+ // its start at least), the trials at most `runs` or that many. Timed: `runsMs` of wall time.
1119
+ // (a rule of relations: its steps by domainStep, its params small: a relation's tuples grow as a power of them; its
1120
+ // runs the least, the engine's small instance its samples)
1121
+ const relStep = domainStep(m);
1122
+ const runsTimed = timed || opts.runsMs !== undefined, runsUntil = Math.min(wallUntil, performance.now() + (opts.runsMs ?? 500)), least = opts.runs ?? (relStep ? 2000 : Math.min(inferRuns, Math.max(2000, 4 * ms)));
1123
+ const moreRuns = (trial) => (runsTimed ? performance.now() < runsUntil : trial < (relStep ? 400 : Math.max(cap, least)) && (used.tries < least || offered < cap) && !stop());
789
1124
  let trials = 0;
790
1125
  // (an assumption with "there exists", a value the request brings, may admit no request at a small bound, a multiple
791
1126
  // of 5 but 0, say: a trial whose steps moved nothing doubles the bound at once)
@@ -793,26 +1128,54 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
793
1128
  for (let trial = 0, bound = 2, stuck = false; moreRuns(trial); trial++, bound = trial % 20 === 0 || stuck ? (bound >= 1024 ? 2 : bound * 2) : bound) {
794
1129
  stuck = false;
795
1130
  trials++;
796
- const params = randomParams(bound);
797
- if (m.pre && !evalC(m.pre, params, { scalars: {}, maps: {} }, m))
798
- continue;
799
- let st;
800
- try {
801
- st = run.init(params);
1131
+ // (a rule with maps: one trial in four goes on from a sample, of 64 drawn, holding the value of a state variable the
1132
+ // fewest states offered held, its requests at the smallest bound. The hull's bounds come from the states past the
1133
+ // usual, which runs from the start seldom reach (a ticket lock's service at 2 in 2 to 9 of 3,000 samples, the join
1134
+ // then dropping the forms they left too tight one at a time), and a key or two at a time step on from them. On rules
1135
+ // of scalars alone, CHC's and ITS's programs, measured, it cost more than it found: s_split_22 29 -> 7 of 40 seeds)
1136
+ const rare = withMaps && trial % 4 === 3 && stateVars.length > 0 && samples.length >= 64;
1137
+ let params, st;
1138
+ if (rare) {
1139
+ const v = rand(stateVars.length), seen = (q) => seenAt[v].get(q.st.scalars[stateVars[v]] ?? 0) ?? 0;
1140
+ let q0 = samples[rand(samples.length)];
1141
+ for (let q = 1; q < 64; q++) {
1142
+ const o = samples[rand(samples.length)];
1143
+ if (seen(o) < seen(q0))
1144
+ q0 = o;
1145
+ }
1146
+ ;
1147
+ ({ params, st } = q0);
802
1148
  }
803
- catch {
804
- continue;
1149
+ else {
1150
+ // (params at a bound of their own every other trial, at 0 one in twenty: a small budget with large costs, all-0 params)
1151
+ params = randomParams(trial % 20 === 1 ? 0 : relStep ? Math.min(bound, 4) : trial % 2 ? bound : 2 ** rand(11));
1152
+ if (m.pre && !evalC(m.pre, params, { scalars: {}, maps: {} }, m))
1153
+ continue;
1154
+ try {
1155
+ st = run.init(params);
1156
+ }
1157
+ catch {
1158
+ continue;
1159
+ }
1160
+ keep({ params, st });
805
1161
  }
806
- keep({ params, st });
807
1162
  let took = 0;
808
1163
  for (let d = 0, tries = 0; d < 40 && tries < 200; tries++) {
809
1164
  used.tries++;
810
- const input = randomInput(params, bound);
1165
+ const input = randomInput(params, rare ? 2 : bound);
811
1166
  let next;
812
1167
  try {
813
- if (!allowed(m, run, params, st, input))
814
- continue;
815
- next = run.step(params, st, input);
1168
+ if (relStep) {
1169
+ const n2 = relStep(params, st, input);
1170
+ if (!n2)
1171
+ continue;
1172
+ next = n2;
1173
+ }
1174
+ else {
1175
+ if (!allowed(m, run, params, st, input))
1176
+ continue;
1177
+ next = run.step(params, st, input);
1178
+ }
816
1179
  }
817
1180
  catch {
818
1181
  break;
@@ -850,7 +1213,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
850
1213
  {
851
1214
  const named = (n) => stateSet.has(n) || m.params.includes(n);
852
1215
  const okE = (e) => e.op === 'const' || (e.op === 'var' ? named(e.name) : e.op === 'mul' ? okE(e.a) : e.op === 'if' ? okC(e.c) && okE(e.then) && okE(e.else)
853
- : e.op === 'get' ? !!m.fns?.[e.map] && okE(e.key) : okE(e.a) && okE(e.b));
1216
+ : e.op === 'get' ? !!m.fns?.[e.map] && okE(e.key) : e.op === 'tup' || e.op === 'proj' ? false : okE(e.a) && okE(e.b));
854
1217
  const okC = (c) => (c.op === 'and' || c.op === 'or' ? c.xs.every(okC) : c.op === 'not' ? okC(c.x) : c.op === '<' || c.op === '<=' || c.op === '=' ? okE(c.a) && okE(c.b) : false);
855
1218
  const seenT = new Set();
856
1219
  const visitE = (e) => {
@@ -875,7 +1238,8 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
875
1238
  visitE(e.key);
876
1239
  else {
877
1240
  visitE(e.a);
878
- visitE(e.b);
1241
+ if ('b' in e)
1242
+ visitE(e.b);
879
1243
  }
880
1244
  };
881
1245
  const visitC = (c) => { if (c.op === 'and' || c.op === 'or')
@@ -1020,9 +1384,11 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1020
1384
  s += c * vals[i][j]; return s; };
1021
1385
  const keyNots = plain.filter(i => !atoms[i].param && !atoms[i].int && !atoms[i].term);
1022
1386
  // The guards: the choices first, then yes/nos, then small naturals, at most eight; each shape's largest value per
1023
- // guard in one pass over (at most 1,500 of) the rows. Building candidates takes at most a quarter of the time.
1387
+ // guard in one pass over (at most 3,000 of) the rows: with each state kept once a stride skips states, not copies, and a
1388
+ // guard's bound past a skipped one is no law (break_safe's i1 + 1 <= i0 → 27 <= i0). Building candidates takes at most
1389
+ // a quarter of the time.
1024
1390
  const guards = [...modes].sort((p, q) => Number(!!q.choice) - Number(!!p.choice) || Number(!!q.bool) - Number(!!p.bool)).slice(0, 8);
1025
- const strideS = Math.max(1, Math.ceil(NS / 1500)), strideK = Math.max(1, Math.ceil(NK / 1500));
1391
+ const strideS = Math.max(1, Math.ceil(NS / 3000)), strideK = Math.max(1, Math.ceil(NK / 3000));
1026
1392
  const buildUntil = opts.cubes ? 0 : Math.min(until, now() + (until - now()) / 4);
1027
1393
  for (const [n_, { coef, cells }] of shapes.entries()) {
1028
1394
  if (forms.length > maxCandidates || (n_ % 256 === 0 && (now() > buildUntil || stop())))
@@ -1076,16 +1442,17 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1076
1442
  // seldom meets a bound between two times: until[k] + E <= now, reached at the instant its lease ends).
1077
1443
  if (w < 0 || !Number.isFinite(written))
1078
1444
  continue;
1079
- const wr = { atom: w, value: 1, hi: Infinity }, near = (dv) => (dv < 0 ? [0] : [dv, ...bounds.filter(b => b > dv).slice(0, 1)]);
1445
+ // (only where it bounds lower than the guard's own form, which a shape of three has none of)
1446
+ const wr = { atom: w, value: 1, hi: Infinity }, near = (dv) => (dv < 0 ? [0] : [dv, ...bounds.filter(b => b > dv).slice(0, 1)]), alone = (v) => (coef.length > 2 ? Infinity : v);
1080
1447
  if (written < d)
1081
1448
  for (const dv of near(written))
1082
1449
  if (dv < d)
1083
1450
  forms.push({ coef, d: dv, cells, guard: wr, size: sizeOf(coef) + 55 });
1084
1451
  here.forEach((mode, g) => { for (const [value, dv] of mostW[g])
1085
- if (mode.values.includes(value) && dv < Math.min(written, most[g].get(value)))
1452
+ if (mode.values.includes(value) && dv < Math.min(written, alone(most[g].get(value))))
1086
1453
  for (const e of near(dv))
1087
1454
  forms.push({ coef, d: e, cells, guard: { atom: mode.atom, value }, also: [wr], size: sizeOf(coef) + 65 }); });
1088
- keyNots.forEach((s, g) => { if (Number.isFinite(awayW[g]) && awayW[g] < Math.min(written, away[g]))
1455
+ keyNots.forEach((s, g) => { if (Number.isFinite(awayW[g]) && awayW[g] < Math.min(written, alone(away[g])))
1089
1456
  for (const e of near(awayW[g]))
1090
1457
  forms.push({ coef, d: e, cells, guard: { keyNot: s }, also: [wr], size: sizeOf(coef) + 70 }); });
1091
1458
  }
@@ -1181,7 +1548,9 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1181
1548
  return only.values.filter(v => c * v <= f.d);
1182
1549
  };
1183
1550
  // (a form about every key says so first)
1184
- const viewText = (v, t) => v.vars.reduce((acc, k2, i) => acc.replaceAll(k2, v.names[i]), t);
1551
+ const viewText = (v, t) => v.vars.reduce((acc, k2, i) => acc.replaceAll(k2, v.names[i]), t).replace(/free\d+\$enum/g, '_');
1552
+ // (the free parts a view's form reads, keys of its law beside the view's)
1553
+ const freeOf = (f, v) => (v.proj ? [...new Set(atomsIn(f).flatMap(i => (atoms[i].place !== undefined ? v.proj[atoms[i].place]?.free ?? [] : [])))] : []);
1185
1554
  const textOf = (f) => {
1186
1555
  if (f.cells)
1187
1556
  return `every k: ${textIn(f)}`;
@@ -1326,13 +1695,34 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1326
1695
  // --- evaluating a form ---------------------------------------------------------------------------------------------
1327
1696
  // (each row's atom values read once, however many forms are evaluated there: rows are never changed once made)
1328
1697
  const valuesAt = new WeakMap();
1698
+ const atomsByField = new Map();
1699
+ let indexedAtoms = 0;
1329
1700
  const valuesOf = (env) => {
1330
1701
  let vs = valuesAt.get(env);
1331
1702
  if (!vs) {
1332
- const n2 = atoms.length;
1333
- vs = new Float64Array(n2);
1334
- for (let i = 0; i < n2; i++)
1335
- vs[i] = valueOf(atoms[i], env);
1703
+ // Before any view columns exist the original dense scan is cheaper.
1704
+ if (atoms.length === A) {
1705
+ vs = new Float64Array(A);
1706
+ for (let i = 0; i < A; i++)
1707
+ vs[i] = valueOf(atoms[i], env);
1708
+ valuesAt.set(env, vs);
1709
+ return vs;
1710
+ }
1711
+ // Views add atoms incrementally. Most belong to other views and read
1712
+ // absent fields (zero); visit only this row's fields, preserving indices.
1713
+ for (; indexedAtoms < atoms.length; indexedAtoms++) {
1714
+ const a = atoms[indexedAtoms];
1715
+ for (const [p, sign] of a.parts) {
1716
+ const field = a.cell ? AT + p : p;
1717
+ if (!atomsByField.has(field))
1718
+ atomsByField.set(field, []);
1719
+ atomsByField.get(field).push([indexedAtoms, sign]);
1720
+ }
1721
+ }
1722
+ vs = new Float64Array(atoms.length);
1723
+ for (const [field, value] of Object.entries(env))
1724
+ for (const [i, sign] of atomsByField.get(field) ?? [])
1725
+ vs[i] = vs[i] + sign * value;
1336
1726
  valuesAt.set(env, vs);
1337
1727
  }
1338
1728
  return vs;
@@ -1458,15 +1848,22 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1458
1848
  return out;
1459
1849
  };
1460
1850
  // --- Houdini on the runs' neighbors ----------------------------------------------------------------------------------
1461
- let alive = forms.slice().sort((p, q) => p.size - q.size).slice(0, maxCandidates);
1851
+ // (a map keyed by tuples is read at its tuples only: a form about every key reads it at one key, which no law can)
1852
+ const tupleMaps = new Set(Object.entries(m.relations ?? {}).filter(([, srt]) => srt.length > 1).map(([mp]) => mp));
1853
+ walk([m.step, m.assume ?? null, ...laws.map(l => l.holds)], o => { if (o.op === 'get' && o.key?.op === 'tup')
1854
+ tupleMaps.add(String(o.map)); });
1855
+ const plainKeyed = (f) => f.view !== undefined || !atomsIn(f).some(i => atoms[i].cell && tupleMaps.has(atoms[i].parts[0][0]));
1856
+ let alive = forms.filter(plainKeyed).sort((p, q) => p.size - q.size).slice(0, maxCandidates);
1462
1857
  const ctis = [];
1463
1858
  // (a law about keys is evaluated at every tuple of the state's keys, as watch does: counted as that many evaluations)
1464
1859
  const lawful = (params, st) => {
1860
+ const k = keysOf(4, st).length, cost = given.reduce((s, l) => s + (l.forall ? k ** (1 + (l.keys?.length ?? 0)) : 0), 0);
1861
+ // (a state whose laws' tuples cost more than a million evaluations is no sample: one such check took sharded_kv's whole
1862
+ // budget, five keys at 40 values)
1863
+ if (cost > 1e6)
1864
+ return false;
1465
1865
  used.watched += given.length;
1466
- const k = keysOf(4, st).length;
1467
- for (const l of given)
1468
- if (l.forall)
1469
- used.evals += k ** (1 + (l.keys?.length ?? 0));
1866
+ used.evals += cost;
1470
1867
  try {
1471
1868
  return given.every(l => watch(m, run, l, params, 4).start(st));
1472
1869
  }
@@ -1474,7 +1871,9 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1474
1871
  return false;
1475
1872
  }
1476
1873
  };
1477
- const houdiniUntil = opts.cubes ? 0 : Math.min(until, now() + Math.max(500, (until - now()) / 4));
1874
+ // (none on a rule of relations: its moves change a cell at a tuple's code, and its laws are read at every tuple of the
1875
+ // codes a state holds, a power of them; the engine's small instance is where its samples are)
1876
+ const houdiniUntil = opts.cubes || relStep ? 0 : Math.min(until, now() + Math.max(500, (until - now()) / 4));
1478
1877
  for (let quiet = 0; samples.length && now() < houdiniUntil && !stop() && quiet < 3;) {
1479
1878
  const killed = new Set();
1480
1879
  for (let tries = 0; tries < 400 && now() < houdiniUntil && !stop(); tries++) {
@@ -1527,7 +1926,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1527
1926
  // (about two keys: where the frame holds of them)
1528
1927
  const v = f.view !== undefined ? views[f.view] : undefined;
1529
1928
  if (!l)
1530
- 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) } : {}) }));
1929
+ lawOf.set(f, (l = { name: textOf(f), holds: v ? substC(any(not(v.frame), condOf(f)), defsOf(v)) : condOf(f), ...(f.cells ? { forall: KEY } : v ? { forall: v.vars[0], keys: [...v.vars.slice(1).filter((_, i) => !v.defs?.[i + 1]), ...freeOf(f, v)] } : {}), ...(f.cong ? { some: someOf(f) } : {}) }));
1531
1930
  return l;
1532
1931
  };
1533
1932
  const names = new Set(given.map(l => l.name));
@@ -1563,7 +1962,8 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1563
1962
  // eight values most unusual at it are read (furthest past the samples in its guard, then the rarest there).
1564
1963
  const choiceMode = modes.find(mo => mo.choice && !atoms[mo.atom].cell);
1565
1964
  const condAtoms = plain.filter(i => !atoms[i].param && i !== choiceMode?.atom);
1566
- const fromCti = (p) => {
1965
+ const fromCti = (p) => fromCti0(p).filter(plainKeyed);
1966
+ const fromCti0 = (p) => {
1567
1967
  const end = Math.min(until, now() + Math.max(300, (until - now()) / 8));
1568
1968
  const sc = p.scalar, pv = (coef) => { let v = 0; for (const [i, c] of coef)
1569
1969
  v += c * valueOf(atoms[i], sc); return v; };
@@ -1660,7 +2060,9 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1660
2060
  const pool0 = pool.slice(), ctis0 = ctis.length;
1661
2061
  if (joinOn && NS)
1662
2062
  try {
1663
- const jT0 = performance.now(), jUntil = Math.min(until, now() + (until - now()) * (opts.join ?? joinShare));
2063
+ // (a rule of relations: no round of the join, whose hulls and bounds state no law of a relation's tuples; the engine's)
2064
+ const noJoin = opts.join === 0 || !!Object.keys(m.relations ?? {}).length;
2065
+ const jT0 = performance.now(), jUntil = Math.min(until, now() + (until - now()) * (noJoin ? 0 : opts.join ?? joinShare));
1664
2066
  // The control state: the choice (loc) and, where they are few, the yes/nos (a program counter in bits), each of its
1665
2067
  // values reached a part of its own.
1666
2068
  const jChoice = modes.find(mo => mo.choice && !atoms[mo.atom].cell), bits = modes.filter(mo => mo.bool && !atoms[mo.atom].cell && !atoms[mo.atom].param);
@@ -1716,6 +2118,22 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1716
2118
  }
1717
2119
  return rows;
1718
2120
  };
2121
+ // (a relation projected: each state's tuples decoded once)
2122
+ const tuplesOf = new WeakMap();
2123
+ const projected = (st, pj, want) => {
2124
+ let by = tuplesOf.get(st);
2125
+ if (!by)
2126
+ tuplesOf.set(st, (by = new Map()));
2127
+ let ts = by.get(pj.mp);
2128
+ if (!ts) {
2129
+ ts = [];
2130
+ for (const [k, c] of st.maps[pj.mp] ?? [])
2131
+ if (c >= 1)
2132
+ ts.push(tupleOf(k, pj.n));
2133
+ by.set(pj.mp, ts);
2134
+ }
2135
+ return ts.some(t => want.every((w, i) => w < 0 || t[i] === w)) ? 1 : 0;
2136
+ };
1719
2137
  const addView = (v, mapsAt, valuesOf2, per, extra = [], product = false) => {
1720
2138
  const vi = views.length, va = [];
1721
2139
  // (`extra`: values of its keys that are atoms too, a key or a function of one: e ≤ Ep[a], idn(x) < idn(y))
@@ -1729,7 +2147,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1729
2147
  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 });
1730
2148
  }
1731
2149
  });
1732
- const compiled = { frame: compileC(v.frame, m), places: v.places.map(p => compileE(p, m)), extra: extra.map(t => compileE(t.term, m)),
2150
+ const compiled = { defs: (v.defs ?? []).map(d => (d ? compileE(d, m) : undefined)), frame: compileC(v.frame, m), places: v.places.map((p, i) => (v.proj?.[i] ? () => 0 : compileE(p, m))), extra: extra.map(t => compileE(t.term, m)),
1733
2151
  xs: extra.map((_, j) => `$x${vi}:${j}`), qs: mapsAt.map((mps, place) => mps.map(mp => `${AT}${AT}${mp}${AT}${vi}:${place}`)) };
1734
2152
  const rowsOf = (params, st, full = false) => {
1735
2153
  // (`per` values a key; the engine's views (`product`) at most per^keys rows a state, 64 at least, the fewer-valued
@@ -1763,11 +2181,33 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1763
2181
  catch {
1764
2182
  row[compiled.xs[j]] = 0;
1765
2183
  } });
1766
- mapsAt.forEach((mps, place) => { const key = compiled.places[place](env, st); mps.forEach((mp, h) => { const q = compiled.qs[place][h]; row[q] = cellOf(st, mp, key); cells.push([q, mp, key]); }); });
2184
+ mapsAt.forEach((mps, place) => {
2185
+ const pj = v.proj?.[place];
2186
+ if (pj) {
2187
+ const q = compiled.qs[place][0], val = projected(st, pj, pj.at.map(k => (k < 0 ? -1 : env[v.vars[k]])));
2188
+ row[q] = val;
2189
+ if (!val)
2190
+ cells.push([q, pj.mp, -1]);
2191
+ return;
2192
+ }
2193
+ const key = compiled.places[place](env, st);
2194
+ mps.forEach((mp, h) => { const q = compiled.qs[place][h]; row[q] = cellOf(st, mp, key); cells.push([q, mp, key]); });
2195
+ });
1767
2196
  used.erows++;
1768
2197
  out.push(mark(withTerms(row, st), st, cells));
1769
2198
  return;
1770
2199
  }
2200
+ const def = compiled.defs[i];
2201
+ if (def) {
2202
+ try {
2203
+ env[v.vars[i]] = def(env, st);
2204
+ }
2205
+ catch {
2206
+ return;
2207
+ }
2208
+ go(i + 1, env);
2209
+ return;
2210
+ }
1771
2211
  for (const k2 of cand[i]) {
1772
2212
  env[v.vars[i]] = k2;
1773
2213
  go(i + 1, env);
@@ -1776,7 +2216,8 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1776
2216
  go(0, { ...params, ...st.scalars });
1777
2217
  return out;
1778
2218
  };
1779
- views.push({ ...v, atoms: va, rows: distinctRows(rowsOf), rowsOf });
2219
+ // (an engine view's rows are read off the small states where it is enumerated, not kept here)
2220
+ views.push({ ...v, atoms: va, rows: product ? [] : distinctRows(rowsOf), rowsOf });
1780
2221
  };
1781
2222
  // The pairs: where the rule composes two keys into one (Link[N·a + b] beside Known[a], Known[b]), the cells at two
1782
2223
  // 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
@@ -1785,14 +2226,16 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1785
2226
  // 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).
1786
2227
  const callerLaws = [...laws, ...stepLaws.map(sl => ({ name: sl.name, holds: sl.then, ...(sl.forall ? { forall: sl.forall } : {}), ...(sl.keys ? { keys: sl.keys } : {}) }))];
1787
2228
  const sorts = mapNames.length ? keySorts(m, callerLaws, pairing) : undefined;
1788
- if (pairing) {
2229
+ // (the maps keyed by tuples are read at their tuples, in the engine's views alone)
2230
+ const flat = mapNames.filter(mp => !sorts?.tupled.has(mp));
2231
+ if (pairing && flat.length) {
1789
2232
  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)];
1790
2233
  // (by sort, where the rule composes: a row's maps at x, a column's at y, the composed maps at the composed key)
1791
2234
  const sorted = P.n && sorts ? [sorts.plainMaps(sorts.find('hi')), sorts.plainMaps(sorts.find('lo')), sorts.composedMaps] : undefined;
1792
2235
  const held = (st) => {
1793
2236
  const ks = new Set();
1794
- for (const c of Object.values(st.maps))
1795
- for (const k of c.keys()) {
2237
+ for (const mp of flat)
2238
+ for (const k of st.maps[mp]?.keys() ?? []) {
1796
2239
  ks.add(k);
1797
2240
  if (P.n && k >= P.c) {
1798
2241
  ks.add(Math.floor((k - P.c) / P.n));
@@ -1802,7 +2245,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1802
2245
  const xs = [...ks, ks.size ? Math.max(...ks) + 1 : 0];
1803
2246
  return [xs, xs];
1804
2247
  };
1805
- 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);
2248
+ 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(() => flat), held, 24);
1806
2249
  }
1807
2250
  // A view of each caller's law about several keys that the pairs don't hold (three keys: two holders of a lock and
1808
2251
  // the lock; two keys of one sort where the pairs relate two sorts): its keys, each of the sort its reads give it
@@ -2272,7 +2715,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
2272
2715
  s2 += c * v[i]; return s2; };
2273
2716
  const litHolds = (l, v) => ('at' in l ? v[l.at.atom] === l.at.value : dot(l.lin.coef, v) <= l.lin.d);
2274
2717
  const inCube = (c, v) => c.every(l => litHolds(l, v));
2275
- const vecKey = (v) => Array.from(v).join(',');
2718
+ const vecKey = (v) => v instanceof Float64Array ? v.join(',') : Array.from(v).join(',');
2276
2719
  const S = rowsS.map(r => valuesOf(r)), sampled = new Set(S.map(vecKey));
2277
2720
  let initVec;
2278
2721
  try {
@@ -2613,8 +3056,96 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
2613
3056
  m.fns[k] = fn;
2614
3057
  }
2615
3058
  };
3059
+ // (a rule of relations: its small instance, rows and pool bounded, so a large one ends unknown within its memory)
3060
+ const rel = !!Object.keys(m.relations ?? {}).length;
3061
+ let freeCount = 0, grown = () => 0;
3062
+ const popcount = (w) => { w -= (w >>> 1) & 0x55555555; w = (w & 0x33333333) + ((w >>> 2) & 0x33333333); return (((w + (w >>> 4)) & 0x0f0f0f0f) * 0x01010101) >>> 24; };
3063
+ // Semantic dependencies include maps hidden in expressions and derived view keys.
3064
+ const relationalSupport = rel && new Set(Object.values(m.relations ?? {}).flat()).size > 1;
3065
+ const imagePlaces = new Map();
3066
+ for (const [mp, w] of Object.entries(m.step.maps ?? {})) {
3067
+ const width = m.relations?.[mp]?.length;
3068
+ if (!width)
3069
+ continue;
3070
+ const mark = (i, e) => { if (e.op !== 'get')
3071
+ return; if (!imagePlaces.has(mp))
3072
+ imagePlaces.set(mp, new Map()); const at = imagePlaces.get(mp); if (!at.has(i))
3073
+ at.set(i, new Set()); at.get(i).add(e.map); };
3074
+ if ('each' in w) {
3075
+ const p = eachParts(w, width);
3076
+ walk(p.value, o => { const c = o; if (c.op === '=')
3077
+ for (const [a, b] of [[c.a, c.b], [c.b, c.a]])
3078
+ if (a.op === 'var' && p.names.includes(a.name))
3079
+ mark(p.names.indexOf(a.name), b); });
3080
+ }
3081
+ else
3082
+ tupleParts(w.key).forEach((e, i) => mark(i, e));
3083
+ }
3084
+ const bridges = new WeakMap();
3085
+ const dependencies = new WeakMap();
3086
+ const semanticMaps = (f) => {
3087
+ let ms = dependencies.get(f);
3088
+ if (!ms) {
3089
+ const names = new Set();
3090
+ walk(lawFor(f).holds, o => { if (o.op === 'get')
3091
+ names.add(String(o.map)); });
3092
+ ms = [...names].sort();
3093
+ dependencies.set(f, ms);
3094
+ }
3095
+ return ms;
3096
+ };
3097
+ const controlOf = (f) => atomsIn(f).filter(i => atoms[i].place === undefined && !atoms[i].cell && !atoms[i].term && !atoms[i].param).map(i => `${atoms[i].name}:${JSON.stringify(f.cube.filter(l => atomsIn(formOf([l])).includes(i)))}`).sort().join();
3098
+ const familyOf = (f) => {
3099
+ return `${semanticMaps(f).join()}|${controlOf(f)}|${bridges.get(f)?.premise ?? ''}|${views[f.view].defs ? views[f.view].vars.length : 0}`;
3100
+ };
3101
+ const bitWrite = (mp, e) => e.op === 'if' ? bitWrite(mp, e.then) && bitWrite(mp, e.else) : e.op === 'get' ? e.map === mp : e.op === 'const' && (e.value === 0 || e.value === 1);
3102
+ const bitMaps = new Set(Object.entries(m.step.maps ?? {}).filter(([mp, w]) => !m.relations?.[mp] && bitWrite(mp, w.value)).map(([mp]) => mp));
3103
+ const readySupport = (f) => !views[f.view].defs && f.cube.some(l => 'lin' in l && l.lin.d === -1 && l.lin.coef.length === 1 && l.lin.coef[0][1] === -1 && bitMaps.has(atoms[l.lin.coef[0][0]].parts[0]?.[0].split(AT)[2] ?? ''));
3104
+ const fieldSupport = (f) => !views[f.view].defs && f.cube.some(l => {
3105
+ if (!('at' in l) || l.at.value !== 0)
3106
+ return false;
3107
+ const t = atoms[l.at.atom].term, v = views[f.view], sorts = viewSorts.get(f.view);
3108
+ if (t?.op !== 'if' || t.c.op !== '=')
3109
+ return false;
3110
+ return [[t.c.a, t.c.b], [t.c.b, t.c.a]].some(([a, b]) => a.op === 'get' && a.key.op === 'var' && b.op === 'var' && sorts[v.vars.indexOf(a.key.name)] === sorts[v.vars.indexOf(b.name)]);
3111
+ }) && atomsIn(f).some(i => m.relations?.[atoms[i].parts[0]?.[0].split(AT)[2] ?? '']);
3112
+ // Basic setup/range support first, then connected implications. Derived
3113
+ // copies must not crowd the simpler facts out of the fixed-size frontier.
3114
+ const supportOrder = (f) => {
3115
+ if (controlOf(f))
3116
+ return views[f.view].defs ? 1 : 0;
3117
+ if (readySupport(f) || f.cube.some(l => atomsIn(formOf([l])).some(i => atoms[i].name.includes(' in range'))))
3118
+ return 0;
3119
+ if (fieldSupport(f) || views[f.view].defs && f.cube.length === 1 && views[f.view].vars.length <= 2)
3120
+ return 1;
3121
+ const bridge = bridges.get(f);
3122
+ return bridge ? bridge.observed || f.cube.length === 3 ? 1 : 2 : 3;
3123
+ };
3124
+ const diagonalCost = (f) => atomsIn(f).filter(i => { const t = atoms[i].term; if (t?.op !== 'if' || t.c.op !== '=')
3125
+ return false; return [[t.c.a, t.c.b], [t.c.b, t.c.a]].some(([a, b]) => a.op === 'get' && a.key.op === 'var' && b.op === 'var' && a.key.name === b.name); }).length;
3126
+ const diverse = (fs) => {
3127
+ const groups = new Map();
3128
+ for (const f of [...fs].sort((a, b) => supportOrder(a) - supportOrder(b) || a.cube.length - b.cube.length || (readySupport(a) && readySupport(b) ? diagonalCost(a) - diagonalCost(b) : 0) || (bridges.get(a)?.cost ?? 0) - (bridges.get(b)?.cost ?? 0) || Number(!!views[a.view].defs) - Number(!!views[b.view].defs) || (controlOf(a) || readySupport(a) ? views[a.view].vars.length - views[b.view].vars.length : views[b.view].vars.length - views[a.view].vars.length))) {
3129
+ const k = familyOf(f);
3130
+ if (!groups.has(k))
3131
+ groups.set(k, []);
3132
+ groups.get(k).push(f);
3133
+ }
3134
+ const out = [], kinds = [...groups.values()].sort((a, b) => supportOrder(a[0]) - supportOrder(b[0]));
3135
+ for (let i = 0; i < 3; i++)
3136
+ for (const fs of kinds)
3137
+ if (fs[i] && supportOrder(fs[i]) < 3)
3138
+ out.push(fs[i]);
3139
+ out.sort((a, b) => supportOrder(a) - supportOrder(b));
3140
+ const chosen = new Set(out);
3141
+ for (let i = 0; out.length < fs.length; i++)
3142
+ for (const fs of kinds)
3143
+ if (fs[i] && !chosen.has(fs[i]))
3144
+ out.push(fs[i]);
3145
+ return out;
3146
+ };
2616
3147
  const enumerated = () => {
2617
- const ks = sorts, comp = ks.composedMaps.length && pairing?.n ? [ks.find('hi'), ks.find('lo')] : undefined;
3148
+ const ks = keySorts(m, callerLaws, pairing, true), comp = ks.composedMaps.length && pairing?.n ? [ks.find('hi'), ks.find('lo')] : undefined;
2618
3149
  const multi = [...ks.arity].map(([mp, k]) => ({ mp, slots: Array.from({ length: k }, (_, i) => ks.find(`${mp}:${i}`)) }));
2619
3150
  const ss = [...new Set([...ks.plainRead.map(mp => ks.find(`M:${mp}`)), ...(comp ?? []), ...multi.flatMap(q => q.slots)])];
2620
3151
  // (a map's values of a key's sort, and the sorts an order compares: e < Ep[a] makes Ep's values epochs, ordered)
@@ -2628,8 +3159,10 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
2628
3159
  if (less)
2629
3160
  ord.add(vf(b));
2630
3161
  } };
3162
+ // (on a rule of relations a key below a param is bounded, not ordered: its sort's size is the param's, below)
3163
+ const bounded = (e) => !!Object.keys(m.relations ?? {}).length && e.op === 'var' && m.params.includes(e.name);
2631
3164
  walk([m.step, m.assume], o => { const c = o; if (c.op === '<' || c.op === '<=' || c.op === '=')
2632
- relate(node(c.a), node(c.b), c.op !== '='); });
3165
+ relate(node(c.a), node(c.b), c.op !== '=' && !bounded(c.a) && !bounded(c.b)); });
2633
3166
  // (a param that bounds a sort's keys, k < p, is that sort's size in the small instance; a param a key equals, a write
2634
3167
  // at every key at it (k = first) or a read at it, is an element of that sort, which pins it against renaming)
2635
3168
  const bounding = new Map(), elementOf = new Map();
@@ -2653,7 +3186,10 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
2653
3186
  // (a function of a key whose values are a composed map's rows: Pending[idn(x)·N + y])
2654
3187
  const fnHi = Object.keys(m.fns ?? {}).filter(f => comp && ss.includes(ks.find(`F:${f}`)) && vf(`V:${f}`) === vf(comp[0]));
2655
3188
  const placesOf = (s) => (comp ? comp.filter(c => c === s).length + fnHi.filter(f => ks.find(`F:${f}`) === s).length : 0);
2656
- const width = ss.map(s => Math.min(3, Math.max(ordered(s) ? 2 : 0, ks.plainMaps(s).length ? 1 : 0, placesOf(s) + (placesOf(s) >= 2 ? 1 : 0), ...multi.map(q => q.slots.filter(c => c === s).length), ...callerLaws.map(l => [l.forall, ...(l.keys ?? [])].filter(b => b && ks.sortOf(l, b) === s).length))));
3189
+ // (a two-part map whose row is a function's value: the function's argument and the column, places of their sorts)
3190
+ const fnRows = Object.keys(m.fns ?? {}).flatMap(f => multi.filter(q => q.slots.length === 2 && ss.includes(ks.find(`F:${f}`)) && vf(`V:${f}`) === vf(q.slots[0])).map(q => ({ f, q })));
3191
+ const rowPlaces = (s) => fnRows.filter(({ f }) => ks.find(`F:${f}`) === s).length + fnRows.filter(({ q }) => q.slots[1] === s).length;
3192
+ const width = ss.map(s => Math.min(3, Math.max(ordered(s) ? 2 : 0, ks.plainMaps(s).length ? 1 : 0, placesOf(s) + (placesOf(s) >= 2 ? 1 : 0), ...multi.map(q => { const c = q.slots.filter(c2 => c2 === s).length; return c + (c >= 2 ? 1 : 0); }), rowPlaces(s) + (rowPlaces(s) >= 2 ? 1 : 0), ...callerLaws.map(l => [l.forall, ...(l.keys ?? [])].filter(b => b && ks.sortOf(l, b) === s).length))));
2657
3193
  // (a key's own bounds and domain: a caller's law's guards on one key of the sort, k < 64, k < size)
2658
3194
  const bounds = new Map();
2659
3195
  for (const l of callerLaws) {
@@ -2664,6 +3200,15 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
2664
3200
  bounds.set(s, [...(bounds.get(s) ?? []), substC(g, { vars: { [one[0]]: x(KEY) }, maps: {}, flags: {} })]);
2665
3201
  }
2666
3202
  }
3203
+ if (relationalSupport && m.assume) {
3204
+ const conjuncts = (c) => c.op === 'and' ? c.xs.flatMap(conjuncts) : [c];
3205
+ for (const c of conjuncts(m.assume))
3206
+ if ((c.op === '<' || c.op === '<=') && c.a.op === 'var' && m.inputs.includes(c.a.name) && c.b.op === 'var' && m.params.includes(c.b.name)) {
3207
+ const s = ks.find(c.a.name), g = substC(c, { vars: { [c.a.name]: x(KEY) }, maps: {}, flags: {} });
3208
+ if (!(bounds.get(s) ?? []).some(h => JSON.stringify(h) === JSON.stringify(g)))
3209
+ bounds.set(s, [...(bounds.get(s) ?? []), g]);
3210
+ }
3211
+ }
2667
3212
  opts.progress?.('join template', { sorts: ss.map((s, i) => `${s}:${width[i]}`).join(' '), multi: multi.map(q => `${q.mp}:${q.slots.join(',')}`).join(' ') });
2668
3213
  // The small instance (BRAB's, DuoAI's simulation made complete): each key sort its first 2 to 3 elements (its width),
2669
3214
  // an ordered one 0..3, a function's values over its argument's, params small, each input over its sort's elements
@@ -2674,7 +3219,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
2674
3219
  // (`visit`: each new state as the BFS finds it, which ends the BFS by answering false: the filter reads as it goes)
2675
3220
  const instance = (grow, share, rnd, cap = 2_000_000, visit) => {
2676
3221
  let halt = false;
2677
- const base = share === undefined, most = base ? 20_000 : cap, combosMax = base ? 2048 : 16_384, reqs = [];
3222
+ const base = share === undefined, most = base ? (rel ? 8_000 : 20_000) : cap, combosMax = base ? 2048 : 16_384, reqs = [];
2678
3223
  const size = (q) => Math.max(2, Math.min(3, width[ss.indexOf(q)] ?? 2)) + grow(q), keyDom = (q) => Array.from({ length: ordered(q) ? 4 + grow(q) : size(q) }, (_, i) => i);
2679
3224
  const fnDom = (q) => Object.keys(m.fns ?? {}).filter(f => vf(`V:${f}`) === vf(q) && ss.includes(ks.find(`F:${f}`))).flatMap(f => keyDom(ks.find(`F:${f}`)).map(k => { try {
2680
3225
  return fnValue(m.fns[f], k);
@@ -2715,7 +3260,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
2715
3260
  layout.set(mp, [ks.find(`M:${mp}`)]);
2716
3261
  else if (ks.composedMaps.includes(mp) && pairing?.n)
2717
3262
  layout.set(mp, [ks.find('hi'), ks.find('lo')]);
2718
- else if (ar && pairing?.n)
3263
+ else if (ar && (pairing?.n || ks.tupled.has(mp)))
2719
3264
  layout.set(mp, Array.from({ length: ar }, (_, i) => ks.find(`${mp}:${i}`)));
2720
3265
  }
2721
3266
  const stored = new Set(m.inputs.filter(i => JSON.stringify(m.step.state ?? {}).includes(`"name":"${i}"`)).map(i => ks.find(i)));
@@ -2737,6 +3282,10 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
2737
3282
  const pm = ren.get(lay[0]);
2738
3283
  return pm && k < pm.length ? pm[k] : k;
2739
3284
  }
3285
+ if (ks.tupled.has(mp)) {
3286
+ const ds = tupleOf(k, lay.length).map((d, i) => { const pm = ren.get(lay[i]); return pm && d < pm.length ? pm[d] : d; });
3287
+ return ds.slice(0, -1).reduceRight((b, a) => cpair(a, b), ds.at(-1));
3288
+ }
2740
3289
  if (k < pairing.c)
2741
3290
  return k;
2742
3291
  const digits = [];
@@ -2744,21 +3293,29 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
2744
3293
  digits.unshift(i === lay.length - 1 ? r : r % pairing.n);
2745
3294
  return pairing.c + digits.reduce((acc, d, i) => { const pm = ren.get(lay[i]); return acc * pairing.n + (pm && d < pm.length ? pm[d] : d); }, 0);
2746
3295
  };
2747
- const textAt = (q, ren) => JSON.stringify([q.params, q.st.scalars, Object.entries(q.st.maps).map(([mp, cells]) => { const d = q.st.defaults?.[mp] ?? m.maps?.[mp] ?? 0; return [...cells].filter(([, v]) => v !== d).map(([k, v]) => [renKey(mp, k, ren), v]).sort((a, b) => a[0] - b[0]); }), q.st.defaults ?? null]);
3296
+ const textAt = (q, ren) => !ren.size ? sampleStateText(q.params, q.st, m.maps ?? {}) : JSON.stringify([q.params, q.st.scalars, Object.entries(q.st.maps).map(([mp, cells]) => { const d = q.st.defaults?.[mp] ?? m.maps?.[mp] ?? 0; return [...cells].filter(([, v]) => v !== d).map(([k, v]) => [renKey(mp, k, ren), v]).sort((a, b) => a[0] - b[0]); }), q.st.defaults ?? null]);
2748
3297
  // (the state's own text first, its renamings' only for a text not seen)
2749
- const canon = new Map();
3298
+ const canon = new Map(), stateKeys = new WeakMap(), cacheStates = !Object.values(m.step.maps ?? {}).some(w => 'each' in w);
2750
3299
  const keyOf3 = (q) => {
3300
+ // Memoize point-write samples only; bulk writes can reconstruct defaults. Params are fixed here.
3301
+ const was = cacheStates ? stateKeys.get(q.st) : undefined;
3302
+ if (was?.params === q.params)
3303
+ return was.key;
2751
3304
  const own = textAt(q, new Map());
2752
3305
  let best = canon.get(own);
2753
3306
  if (best === undefined) {
2754
3307
  best = own;
2755
3308
  for (const ren of rens) {
3309
+ if (!ren.size)
3310
+ continue;
2756
3311
  const t = textAt(q, ren);
2757
3312
  if (t < best)
2758
3313
  best = t;
2759
3314
  }
2760
3315
  canon.set(own, best);
2761
3316
  }
3317
+ if (cacheStates)
3318
+ stateKeys.set(q.st, { params: q.params, key: best });
2762
3319
  return best;
2763
3320
  };
2764
3321
  // (the step compiled once: core/machine.ts's JavaScript, its assumption refusing a request as `allowed` does)
@@ -2766,7 +3323,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
2766
3323
  // few others that keep its facts on the sort's keys (its values reversed, and each turned by one), each run as its
2767
3324
  // own machine; their states' rows read under their table. One table alone is a fact of it, not of the rule: ring's
2768
3325
  // ids, every node past another one's below it)
2769
- const tables = [{ m, run, js: m.history || m.counts ? undefined : loadJs(m), fns: {} }];
3326
+ const tables = [{ m, run, js: fastStep(m) ?? relStep, fns: {} }];
2770
3327
  for (const [f, fn] of Object.entries(m.fns ?? {})) {
2771
3328
  const arg = ks.find(`F:${f}`);
2772
3329
  if (fn.call || fn.recur || (fn.arity ?? 1) !== 1 || !ss.includes(arg) || m.history || m.counts)
@@ -2786,13 +3343,13 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
2786
3343
  return false;
2787
3344
  } }); });
2788
3345
  if (keeps && tables.length < 4)
2789
- tables.push({ m: m2, run: interpret(m2), js: loadJs(m2), fns: { [f]: fn2 } });
3346
+ tables.push({ m: m2, run: interpret(m2), js: fastStep(m2), fns: { [f]: fn2 } });
2790
3347
  }
2791
3348
  }
2792
3349
  const stepIn = (tb, params, st, input) => {
2793
3350
  try {
2794
3351
  if (tb.js)
2795
- return tb.js.step(params, tb.js.fork(st), input);
3352
+ return tb.js(params, st, input);
2796
3353
  return allowed(tb.m, tb.run, params, st, input) ? tb.run.step(params, st, input) : undefined;
2797
3354
  }
2798
3355
  catch {
@@ -2933,7 +3490,27 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
2933
3490
  return { small, others, bfs, cut, params: pvs.size, ms: Math.round(vnow() - t3) };
2934
3491
  };
2935
3492
  {
2936
- const r0 = instance(() => 0, undefined, rand), own = [...r0.small, ...r0.others], most = new Map();
3493
+ let r0 = instance(() => 0, undefined, rand);
3494
+ // (a relation no state of the small instance holds a tuple of (a start its states never reach: three nodes can't
3495
+ // all be linked in pairs): the instance one element larger in one sort, the first that fills every relation)
3496
+ const none = (r) => Object.entries(m.relations ?? {}).some(([mp, srts]) => srts.length > 1 && ![...r.small, ...r.others].some(q => [...(q.st.maps[mp]?.values() ?? [])].some(c => c >= 1)));
3497
+ // (the sort with the most places in the relations first)
3498
+ const placesOf2 = (q) => [...ks.arity.keys()].filter(mp => ks.tupled.has(mp)).reduce((k, mp) => k + Array.from({ length: ks.arity.get(mp) }, (_, i) => ks.find(`${mp}:${i}`)).filter(t => t === q).length, 0);
3499
+ if (none(r0))
3500
+ for (const s1 of [...ss].sort((a, b) => placesOf2(b) - placesOf2(a))) {
3501
+ if (stop())
3502
+ break;
3503
+ const g1 = (q) => (q === s1 ? 1 : 0), req = smallReq.length;
3504
+ const r1 = instance(g1, undefined, rand);
3505
+ if (!none(r1)) {
3506
+ smallReq.splice(0, req);
3507
+ r0 = r1;
3508
+ grown = g1;
3509
+ break;
3510
+ }
3511
+ smallReq.length = req;
3512
+ }
3513
+ const own = [...r0.small, ...r0.others], most = new Map();
2937
3514
  samples.unshift(...r0.small);
2938
3515
  for (const q of own)
2939
3516
  for (const [mp, cs] of Object.entries(q.st.maps))
@@ -2943,165 +3520,317 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
2943
3520
  // more values, so the literals the cubes are made of are the instance's own)
2944
3521
  smallAll = [...(opts.rows ?? []).filter(q => Object.entries(q.st.maps).every(([mp, cs]) => [...cs.values()].every(c => c <= Math.max(1, most.get(mp) ?? 1)))), ...own];
2945
3522
  }
3523
+ // (a map read at a key of one sort whose values are keys of another, offset by a constant (Src[p] = n + 1): its
3524
+ // value at a key, less the offset, a key of the values' sort)
3525
+ const derived = Object.entries(m.step.maps ?? {}).flatMap(([mp, w]) => {
3526
+ if (!ks.plainRead.includes(mp) || !(mp in (m.maps ?? {})))
3527
+ return [];
3528
+ const key = ks.find(`M:${mp}`), sort = ks.find(`V:${mp}`);
3529
+ if (!ss.includes(key) || !ss.includes(sort) || key === sort)
3530
+ return [];
3531
+ const leaves = (e) => (e.op === 'if' ? [...leaves(e.then), ...leaves(e.else)] : [e]);
3532
+ const offs = new Set(leaves(w.value).flatMap(l => (l.op === 'get' && l.map === mp ? [] : l.op === 'var' ? [0] : l.op === 'add' && l.a.op === 'var' && l.b.op === 'const' ? [l.b.value] : l.op === 'const' && l.value === 0 ? [] : [-1])));
3533
+ if (offs.size !== 1 || offs.has(-1))
3534
+ return [];
3535
+ const c = [...offs][0];
3536
+ return [{ mp, key, sort, at: (k) => (c ? { op: 'sub', a: get(mp, k), b: n(c) } : get(mp, k)) }];
3537
+ });
2946
3538
  const out = [];
2947
3539
  for (const counts of width.reduce((acc, w) => acc.flatMap(c => Array.from({ length: w + 1 }, (_, k) => [...c, k])), [[]])) {
2948
- const keys = ss.flatMap((s, i) => Array.from({ length: counts[i] }, () => s)), vars = keys.map((_, i) => `key${i + 1}$enum`);
2949
- if (!keys.length || keys.length > 5 || stop())
3540
+ const keys0 = ss.flatMap((s, i) => Array.from({ length: counts[i] }, () => s)), vars0 = keys0.map((_, i) => `key${i + 1}$enum`);
3541
+ // (on a rule of relations three keys at most, a map's value as a fourth: the cubes over its tuples read no more)
3542
+ if (!keys0.length || keys0.length > (Object.keys(m.relations ?? {}).length ? 3 : 5) || stop())
2950
3543
  continue;
2951
- const places = [], mapsAt = [], covers = [];
2952
- keys.forEach((s, i) => { if (ks.plainMaps(s).length) {
2953
- places.push(x(vars[i]));
2954
- mapsAt.push(ks.plainMaps(s));
2955
- covers.push([i]);
2956
- } });
2957
- if (comp)
2958
- keys.forEach((a, i) => keys.forEach((b, j) => { if (a === comp[0] && b === comp[1]) {
2959
- places.push(ks.compose(x(vars[i]), x(vars[j])));
2960
- mapsAt.push(ks.composedMaps);
2961
- covers.push(i === j ? [i] : [i, j]);
2962
- } }));
2963
- for (const q of multi)
2964
- for (const t of q.slots.reduce((acc, s) => acc.flatMap(p => keys.flatMap((k2, j) => (k2 === s ? [[...p, j]] : []))), [[]])) {
2965
- places.push(ks.composeAll(t.map(j => x(vars[j]))));
2966
- mapsAt.push([q.mp]);
2967
- covers.push([...new Set(t)]);
3544
+ const tries = [{}, ...derived.flatMap(d => keys0.flatMap((s, i) => (s === d.key && keys0.filter(t => t === s).length === 1 && multi.some(q => ks.tupled.has(q.mp) && q.slots.includes(d.sort)) ? [{ der: { mp: d.mp, src: i, sort: d.sort, term: d.at(x(vars0[i])) } }] : [])))];
3545
+ for (let ti = 0; ti < tries.length && !stop(); ti++) {
3546
+ const { only, der } = tries[ti], inView = (mp) => !only || !ks.tupled.has(mp) || only.has(mp);
3547
+ const keys = der ? [...keys0, `D:${der.mp}`] : keys0, vars = der ? [...vars0, `der${ti}$enum`] : vars0, slot = der ? [...keys0, der.sort] : keys0;
3548
+ const places = [], mapsAt = [], covers = [], pats = [], proj = [];
3549
+ keys.forEach((s, i) => { if (ks.plainMaps(s).length) {
3550
+ places.push(x(vars[i]));
3551
+ mapsAt.push(ks.plainMaps(s));
3552
+ covers.push([i]);
3553
+ } });
3554
+ if (comp)
3555
+ keys.forEach((a, i) => keys.forEach((b, j) => { if (a === comp[0] && b === comp[1]) {
3556
+ places.push(ks.compose(x(vars[i]), x(vars[j])));
3557
+ mapsAt.push(ks.composedMaps);
3558
+ covers.push(i === j ? [i] : [i, j]);
3559
+ } }));
3560
+ for (const q of multi)
3561
+ if (inView(q.mp))
3562
+ for (const t of q.slots.reduce((acc, s) => acc.flatMap(p => slot.flatMap((k2, j) => (k2 === s ? [[...p, j]] : []))), [[]])) {
3563
+ pats[places.length] = t;
3564
+ places.push(ks.keyOf(q.mp, t.map(j => x(vars[j]))));
3565
+ mapsAt.push([q.mp]);
3566
+ covers.push([...new Set(t)]);
3567
+ }
3568
+ // (a relation's tuple with the view's keys at some of its parts, each once, the others free: P(x, _, y, _), the
3569
+ // relation projected on the parts the view reads)
3570
+ // (a map's value as a key there or not: Pend(q, c, _) beside T(Src(q), c, Src(q)))
3571
+ const place1 = (acc, s, i) => acc.flatMap(p => q2.slots.flatMap((s2, pos) => (s2 === s && p[pos] === -1 ? [p.map((y, k) => (k === pos ? i : y))] : [])));
3572
+ let q2;
3573
+ for (const q of multi)
3574
+ if (inView(q.mp) && ks.tupled.has(q.mp) && m.relations?.[q.mp] && keys0.length < q.slots.length)
3575
+ for (const t of (q2 = q, ((base) => (der ? [...base, ...place1(base, der.sort, keys0.length)] : base))(keys0.reduce((acc, s, i) => place1(acc, s, i), [q.slots.map(() => -1)])))) {
3576
+ if (!t.includes(-1))
3577
+ continue;
3578
+ const free = t.flatMap(k => (k < 0 ? [`free${++freeCount}$enum`] : [])), fr = [...free];
3579
+ pats[places.length] = t;
3580
+ proj[places.length] = { mp: q.mp, n: t.length, at: t, free };
3581
+ places.push(tuple(t.map(k => x(k < 0 ? fr.shift() : vars[k]))));
3582
+ mapsAt.push([q.mp]);
3583
+ covers.push([...new Set(t.filter(k => k >= 0))]);
3584
+ }
3585
+ for (const f of fnHi)
3586
+ keys.forEach((a, i) => keys.forEach((b, j) => { if (a === ks.find(`F:${f}`) && b === comp[1]) {
3587
+ places.push(ks.compose(get(f, x(vars[i])), x(vars[j])));
3588
+ mapsAt.push(ks.composedMaps);
3589
+ covers.push(i === j ? [i] : [i, j]);
3590
+ } }));
3591
+ // (and a two-part map's row a function of a key, as a composed map's: Pending[idn(x)·N + y])
3592
+ for (const { f, q } of fnRows)
3593
+ keys.forEach((a, i) => keys.forEach((b, j) => { if (a === ks.find(`F:${f}`) && b === q.slots[1]) {
3594
+ places.push(ks.composeAll([get(f, x(vars[i])), x(vars[j])]));
3595
+ mapsAt.push([q.mp]);
3596
+ covers.push(i === j ? [i] : [i, j]);
3597
+ } }));
3598
+ const names = [...['x', 'y', 'z', 'w', 'u'].slice(0, keys0.length), ...(der ? [`${der.mp}(${'xyzwu'[der.src]})`] : [])], fns = Object.keys(m.fns ?? {}).filter(f => ordered(`V:${f}`) && ss.includes(ks.find(`F:${f}`)));
3599
+ const extra = [...keys.flatMap((q, i) => (ordered(q) ? [{ name: names[i], term: x(vars[i]) }] : [])), ...fns.flatMap(f => keys.flatMap((q, i) => (q === ks.find(`F:${f}`) ? [{ name: `${f}(${names[i]})`, term: get(f, x(vars[i])) }] : [])))];
3600
+ // (on a rule of relations, a map's value at a key that is a key of a sort the view holds, beside each such key: is
3601
+ // it that key (Link(x) = x, Src(q) = y), a 0 or a 1)
3602
+ if (Object.keys(m.relations ?? {}).length)
3603
+ keys0.forEach((s0, i) => { for (const mp of ks.plainMaps(s0)) {
3604
+ const sv = ks.find(`V:${mp}`);
3605
+ if (sv !== s0 && !ss.includes(sv))
3606
+ continue;
3607
+ slot.forEach((s1, j) => { if (s1 === sv && (j !== keys0.length || der?.src !== i || der?.mp !== mp))
3608
+ extra.push({ name: `${mp}(${names[i]})=${names[j]}`, term: { op: 'if', c: same(get(mp, x(vars[i])), x(vars[j])), then: n(1), else: n(0) }, eq: [...new Set([i, j, ...(j === keys0.length && der ? [der.src] : [])])] }); });
3609
+ } });
3610
+ if (relationalSupport)
3611
+ keys0.forEach((s, i) => {
3612
+ for (const mp of ks.plainMaps(s)) {
3613
+ const sv = ks.find(`V:${mp}`), gs = bounds.get(sv);
3614
+ if (gs?.length)
3615
+ extra.push({ name: `${mp}(${names[i]}) in range`, term: { op: 'if', c: substC(all(...gs), { vars: { [KEY]: get(mp, x(vars[i])) }, maps: {}, flags: {} }), then: n(1), else: n(0) }, eq: [i] });
3616
+ }
3617
+ });
3618
+ let frame = all(...keys.flatMap((s, i) => [...(((comp && s === comp[1]) || multi.some(q => !ks.tupled.has(q.mp) && q.slots.slice(1).includes(s))) && !bounds.has(s) ? [atMost(x(vars[i]), n(pairing.n - 1))] : []), ...[...new Set((bounds.get(s) ?? []).map(g => JSON.stringify(substC(g, { vars: { [KEY]: x(vars[i]) }, maps: {}, flags: {} }))))].map(t => JSON.parse(t)), ...keys.slice(0, i).flatMap((t, j) => (t === s ? [not(same(x(vars[j]), x(vars[i])))] : []))]));
3619
+ // (a view with more than 48 places of tuple maps has more than 96 literals of its tuples alone: split at once)
3620
+ const tm0 = [...new Set(mapsAt.flat().filter(mp => ks.tupled.has(mp)))];
3621
+ if (!only && tm0.length > 1 && mapsAt.filter(mps => mps.some(mp => ks.tupled.has(mp))).length > 48) {
3622
+ tries.push(...tm0.map(mp => ({ only: new Set([mp]), der })), ...(tm0.length > 2 ? tm0.flatMap((a, i) => tm0.slice(i + 1).map(b => ({ only: new Set([a, b]), der }))) : []));
3623
+ continue;
2968
3624
  }
2969
- for (const f of fnHi)
2970
- keys.forEach((a, i) => keys.forEach((b, j) => { if (a === ks.find(`F:${f}`) && b === comp[1]) {
2971
- places.push(ks.compose(get(f, x(vars[i])), x(vars[j])));
2972
- mapsAt.push(ks.composedMaps);
2973
- covers.push(i === j ? [i] : [i, j]);
2974
- } }));
2975
- const names = ['x', 'y', 'z', 'w', 'u'].slice(0, keys.length), fns = Object.keys(m.fns ?? {}).filter(f => ordered(`V:${f}`) && ss.includes(ks.find(`F:${f}`)));
2976
- const extra = [...keys.flatMap((q, i) => (ordered(q) ? [{ name: names[i], term: x(vars[i]) }] : [])), ...fns.flatMap(f => keys.flatMap((q, i) => (q === ks.find(`F:${f}`) ? [{ name: `${f}(${names[i]})`, term: get(f, x(vars[i])) }] : [])))];
2977
- const frame = all(...keys.flatMap((s, i) => [...(comp && s === comp[1] && !bounds.has(s) ? [atMost(x(vars[i]), n(pairing.n - 1))] : []), ...[...new Set((bounds.get(s) ?? []).map(g => JSON.stringify(substC(g, { vars: { [KEY]: x(vars[i]) }, maps: {}, flags: {} }))))].map(t => JSON.parse(t)), ...keys.slice(0, i).flatMap((t, j) => (t === s ? [not(same(x(vars[j]), x(vars[i])))] : []))]));
2978
- const vi = views.length;
2979
- addView({ vars, names, places, covers, frame, need: keys.length, printable: false }, mapsAt, st => keys.map(s => ks.valuesAt(st, s)), Math.max(2, Math.floor(64 ** (1 / keys.length))), extra, true);
2980
- // (the rows: every small state's, distinct, at most 20,000; the view's own rows stop at its first states, the shallow
2981
- // ones, so a deep state's (a leader's) would be left out)
2982
- viewSorts.set(vi, keys);
2983
- const v = views[vi], R = [], seenRows = new Set();
2984
- for (const q of smallAll.length ? smallAll : []) {
2985
- if (R.length >= 20_000)
2986
- break;
2987
- for (const row of withTable(q.params, () => v.rowsOf(q.params, q.st))) {
2988
- const r = valuesOf(row), k2 = vecKey(r);
2989
- if (!seenRows.has(k2)) {
2990
- seenRows.add(k2);
2991
- R.push(r);
3625
+ if (der) {
3626
+ covers.forEach(c => { if (c.includes(keys0.length) && !c.includes(der.src))
3627
+ c.push(der.src); });
3628
+ frame = all(frame, ...keys0.flatMap((s, i) => (s === der.sort ? [not(same(x(vars[keys0.length]), x(vars0[i])))] : [])));
3629
+ }
3630
+ const vi = views.length;
3631
+ addView({ vars, names, places, covers, frame, need: keys.length, printable: false, ...(proj.length ? { proj } : {}), ...(der ? { defs: [...vars0.map(() => undefined), der.term] } : {}) }, mapsAt, st => keys.map(s => ks.valuesAt(st, s)), Math.max(2, Math.floor(64 ** (1 / keys.length))), extra, true);
3632
+ // (the rows: every small state's, distinct, at most 20,000; the view's own rows stop at its first states, the shallow
3633
+ // ones, so a deep state's (a leader's) would be left out)
3634
+ viewSorts.set(vi, keys);
3635
+ const v = views[vi], R = [], seenRows = new Set();
3636
+ // Deduplicate by the atoms this view's literals can read, not by the
3637
+ // growing zero-filled columns of every previously enumerated view.
3638
+ const rowAtoms = [...v.atoms, ...modes.filter(mo => !atoms[mo.atom].cell && !atoms[mo.atom].param).map(mo => mo.atom)];
3639
+ for (const q of smallAll.length ? smallAll : []) {
3640
+ if (R.length >= (rel ? 8_000 : 20_000))
3641
+ break;
3642
+ for (const row of withTable(q.params, () => v.rowsOf(q.params, q.st))) {
3643
+ const r = valuesOf(row), k2 = relationalSupport ? rowAtoms.map(i => r[i]).join(',') : vecKey(r);
3644
+ if (!seenRows.has(k2)) {
3645
+ seenRows.add(k2);
3646
+ R.push(r);
3647
+ }
2992
3648
  }
2993
3649
  }
2994
- }
2995
- if (!R.length)
2996
- R.push(...v.rows.slice(0, 3000).map(valuesOf));
2997
- try {
2998
- if (!m.params.length)
2999
- R.push(...v.rowsOf({}, run.init({})).map(valuesOf));
3000
- }
3001
- catch { /* (the samples hold the start) */ }
3002
- // (each literal with the rows it is true at, as bits; `id` its atoms, `name` its text under a renaming of the keys)
3003
- const W = Math.ceil(R.length / 32), lits = [];
3004
- const where = (i) => { const pl = atoms[i].place; return pl === undefined ? [] : covers[pl]; };
3005
- // (an extra atom's key, and its function where it is one)
3006
- const keyOf2 = (i) => { const t = atoms[i].term; return t?.op === 'var' ? v.vars.indexOf(t.name) : t?.op === 'get' && t.key.op === 'var' ? v.vars.indexOf(t.key.name) : -1; };
3007
- const fnOf = (i) => { const t = atoms[i].term; return t?.op === 'get' ? t.map : undefined; };
3008
- const term = (i, ren) => (atoms[i].place !== undefined ? `${atoms[i].parts[0][0].split(AT)[2]}[${where(i).map(k => ren[k]).join()}]` : keyOf2(i) >= 0 ? `${fnOf(i) ?? ''}#${ren[keyOf2(i)]}` : `s${i}`);
3009
- const reads = (i) => (keyOf2(i) >= 0 ? [keyOf2(i)] : where(i));
3010
- const add = (lit, id, name, rd, holds, before) => {
3011
- const bits = new Uint32Array(W);
3012
- R.forEach((r, k) => { if (holds(r))
3013
- bits[k >> 5] |= 1 << (k & 31); });
3014
- lits.push({ lit, id, name, reads: rd, bits, ...(before ? { before } : {}), state: ('at' in lit ? [lit.at.atom] : lit.lin.coef.map(([a]) => a)).some(a => atoms[a].place !== undefined || (!atoms[a].term && !atoms[a].param)) });
3015
- };
3016
- const valued = (i) => atoms[i].place !== undefined && !!valueSort(atoms[i].parts[0][0].split(AT)[2]);
3017
- for (const i of [...v.atoms.filter(j => !atoms[j].int && !atoms[j].term), ...modes.filter(mo => !atoms[mo.atom].cell && !atoms[mo.atom].param).map(mo => mo.atom)]) {
3018
- const vals = [...new Set(R.map(r => r[i]))].sort((a, b) => a - b);
3019
- // (a value of a key's sort: 0 alone, an order literal below)
3020
- for (const value of valued(i) ? vals.filter(q => q === 0) : vals.length <= 3 || few(vals) ? vals : []) {
3021
- const top = value > 0 && value === vals.at(-1);
3022
- add(top ? { lin: { coef: [[i, -1]], d: -value } } : { at: { atom: i, value } }, `${i}`, ren => `${term(i, ren)}=${value}`, reads(i), r => (top ? r[i] >= value : r[i] === value));
3650
+ if (!R.length)
3651
+ R.push(...distinctRows(v.rowsOf).slice(0, 3000).map(valuesOf));
3652
+ try {
3653
+ if (!m.params.length)
3654
+ R.push(...v.rowsOf({}, run.init({})).map(valuesOf));
3023
3655
  }
3024
- }
3025
- // (an ordered sort's keys and values compared: t ≤ u and u < t, of a key and a value or two values)
3026
- const ts = v.atoms.filter(i => keyOf2(i) >= 0 || valued(i));
3027
- const sortOf2 = (i) => vf(fnOf(i) ? `V:${fnOf(i)}` : keyOf2(i) >= 0 ? keys[keyOf2(i)] : valueSort(atoms[i].parts[0][0].split(AT)[2]));
3028
- for (const [a2, i] of ts.entries())
3029
- for (const j of ts.slice(a2 + 1)) {
3030
- if (sortOf2(i) !== sortOf2(j))
3031
- continue;
3032
- // (two keys of one sort are distinct: one before the other)
3033
- const keysOnly = !fnOf(i) && !fnOf(j) && atoms[i].place === undefined && atoms[j].place === undefined;
3034
- for (const [p, q] of [[i, j], [j, i]])
3035
- for (const d of keysOnly ? [-1] : [0, -1])
3036
- add({ lin: { coef: [[p, 1], [q, -1]], d } }, `${i}~${j}`, ren => `${term(p, ren)}<=${d}+${term(q, ren)}`, [...reads(p), ...reads(q)], r => r[p] - r[q] <= d, keysOnly ? [keyOf2(p), keyOf2(q)] : undefined);
3656
+ catch { /* (the samples hold the start) */ }
3657
+ // (each literal with the rows it is true at, as bits; `id` its atoms, `name` its text under a renaming of the keys)
3658
+ const W = Math.ceil(R.length / 32), lits = [];
3659
+ const where = (i) => { const pl = atoms[i].place; return pl === undefined ? [] : covers[pl]; };
3660
+ // (an extra atom's key, and its function where it is one)
3661
+ const keyOf2 = (i) => { const t = atoms[i].term; return t?.op === 'var' ? v.vars.indexOf(t.name) : t?.op === 'get' && t.key.op === 'var' ? v.vars.indexOf(t.key.name) : -1; };
3662
+ const fnOf = (i) => { const t = atoms[i].term; return t?.op === 'get' ? t.map : undefined; };
3663
+ // (a tuple's place by its parts, the free ones _: T(x, y, x) and T(x, x, y) are two)
3664
+ const termTexts = new Map();
3665
+ const term = (i, ren) => {
3666
+ const key = `${i}:${ren.join(',')}`, old = termTexts.get(key);
3667
+ if (old !== undefined)
3668
+ return old;
3669
+ const a = atoms[i], value = a.place !== undefined ? `${a.parts[0][0].split(AT)[2]}[${(pats[a.place] ?? where(i)).map(k => (k < 0 ? '_' : ren[k])).join()}]` : keyOf2(i) >= 0 ? `${fnOf(i) ?? ''}#${ren[keyOf2(i)]}` : a.term ? JSON.stringify(a.term, (k, v) => { const j = k === 'name' ? vars.indexOf(v) : -1; return j >= 0 ? vars[ren[j]] : v; }) : `s${i}`;
3670
+ termTexts.set(key, value);
3671
+ return value;
3672
+ };
3673
+ const eqAt = new Map(extra.flatMap((t, j) => (t.eq ? [[v.atoms[j], t.eq]] : [])));
3674
+ const reads = (i) => eqAt.get(i) ?? (keyOf2(i) >= 0 ? [keyOf2(i)] : where(i));
3675
+ const add = (lit, id, name, rd, holds, before) => {
3676
+ const bits = new Uint32Array(W);
3677
+ R.forEach((r, k) => { if (holds(r))
3678
+ bits[k >> 5] |= 1 << (k & 31); });
3679
+ lits.push({ lit, id, name, reads: rd, bits, ...(before ? { before } : {}), state: ('at' in lit ? [lit.at.atom] : lit.lin.coef.map(([a]) => a)).some(a => atoms[a].place !== undefined || eqAt.has(a) || (!atoms[a].term && !atoms[a].param)) });
3680
+ };
3681
+ const valued = (i) => atoms[i].place !== undefined && !!valueSort(atoms[i].parts[0][0].split(AT)[2]);
3682
+ for (const i of [...v.atoms.filter(j => !atoms[j].int && (!atoms[j].term || eqAt.has(j))), ...modes.filter(mo => !atoms[mo.atom].cell && !atoms[mo.atom].param).map(mo => mo.atom)]) {
3683
+ // (a relation's tuple: in it or not, whether or not the rows take both: "never in it" is a cube of one literal)
3684
+ const rel = atoms[i].place !== undefined && ks.tupled.has(atoms[i].parts[0][0].split(AT)[2]) && !!m.relations?.[atoms[i].parts[0][0].split(AT)[2]];
3685
+ const vals = rel || eqAt.has(i) ? [0, 1] : [...new Set(R.map(r => r[i]))].sort((a, b) => a - b);
3686
+ // (a value of a key's sort: 0 alone, an order literal below)
3687
+ // (a projected place: only that it holds)
3688
+ for (const value of atoms[i].place !== undefined && proj[atoms[i].place] ? [1] : valued(i) ? vals.filter(q => q === 0) : vals.length <= 3 || few(vals) ? vals : []) {
3689
+ const top = value > 0 && value === vals.at(-1);
3690
+ add(top ? { lin: { coef: [[i, -1]], d: -value } } : { at: { atom: i, value } }, `${i}`, ren => `${term(i, ren)}=${value}`, reads(i), r => (top ? r[i] >= value : r[i] === value));
3691
+ }
3037
3692
  }
3038
- used.rows += R.length * lits.length;
3039
- opts.progress?.('join view', { keys: keys.join(), places: places.length, lits: lits.length, rows: R.length, names: lits.map(l => l.name(keys.map((_, i) => i))).join(' ').slice(0, 900) });
3040
- if (lits.length > 96)
3041
- continue;
3042
- const empty = (b) => b.every(w => w === 0), and = (a, b) => a.map((w, k) => w & b[k]);
3043
- const none = (ls) => empty(ls.slice(1).reduce((b, l) => and(b, lits[l].bits), lits[ls[0]].bits));
3044
- // (a renaming of a sort's keys moves each literal to the place its keys go to)
3045
- const perms = keys.reduce((acc, s) => acc.flatMap(p => keys.flatMap((t, j) => (t === s && !p.includes(j) ? [[...p, j]] : []))), [[]]);
3046
- const canon = (ls) => perms.map(ren => ls.map(l => lits[l].name(ren)).sort().join('&')).sort()[0];
3047
- const seen = new Set(), found = [];
3048
- const dfs = (from, chosen, size, bits, most = 400) => {
3049
- for (let j = from; j < lits.length && found.length < most; j++) {
3050
- if (chosen.some(c => lits[c].id === lits[j].id))
3051
- continue;
3052
- const now2 = [...chosen, j], b = bits ? and(bits, lits[j].bits) : lits[j].bits;
3053
- if (now2.length < size) {
3054
- if (!empty(b))
3055
- dfs(j + 1, now2, size, b, most);
3056
- continue;
3693
+ // (an ordered sort's keys and values compared: t ≤ u and u < t, of a key and a value or two values)
3694
+ const ts = v.atoms.filter(i => keyOf2(i) >= 0 || valued(i));
3695
+ const sortOf2 = (i) => vf(fnOf(i) ? `V:${fnOf(i)}` : keyOf2(i) >= 0 ? keys[keyOf2(i)] : valueSort(atoms[i].parts[0][0].split(AT)[2]));
3696
+ for (const [a2, i] of ts.entries())
3697
+ for (const j of ts.slice(a2 + 1)) {
3698
+ if (sortOf2(i) !== sortOf2(j) || (relationalSupport && !ordered(sortOf2(i))))
3699
+ continue;
3700
+ // (two keys of one sort are distinct: one before the other)
3701
+ const keysOnly = !fnOf(i) && !fnOf(j) && atoms[i].place === undefined && atoms[j].place === undefined;
3702
+ for (const [p, q] of [[i, j], [j, i]])
3703
+ for (const d of keysOnly ? [-1] : [0, -1])
3704
+ add({ lin: { coef: [[p, 1], [q, -1]], d } }, `${i}~${j}`, ren => `${term(p, ren)}<=${d}+${term(q, ren)}`, [...reads(p), ...reads(q)], r => r[p] - r[q] <= d, keysOnly ? [keyOf2(p), keyOf2(q)] : undefined);
3057
3705
  }
3058
- if (!empty(b) || now2.some((_, k) => now2.length > 1 && none(now2.filter((__, q) => q !== k))))
3059
- continue;
3060
- // (a cube reading no state (keys and functions alone) is a fact of the functions' tables, or false: none)
3061
- if (contradicts(now2.map(l => lits[l].lit)) || !now2.some(l => lits[l].state) || oneSided(now2.map(l => lits[l].lit), vi))
3062
- continue;
3063
- const read = new Set(now2.flatMap(l => lits[l].reads)), k2 = canon(now2);
3064
- if (read.size === keys.length && !seen.has(k2)) {
3065
- seen.add(k2);
3066
- found.push(now2);
3706
+ used.rows += R.length * lits.length;
3707
+ // (a literal true at every row is in no minimal cube, and one true at none is a cube alone: the others count)
3708
+ const ones = (b) => { let c = 0; for (const w of b)
3709
+ c += popcount(w); return c; }, informative = lits.filter(l => { const c = ones(l.bits); return c > 0 && c < R.length; });
3710
+ opts.progress?.('join view', { keys: keys.join(), ...(only ? { only: [...only].join() } : {}), places: places.length, lits: lits.length, informative: informative.length, rows: R.length, names: lits.map(l => l.name(keys.map((_, i) => i))).join(' ').slice(0, 900) });
3711
+ if (informative.length > 96) {
3712
+ const tm = [...new Set(mapsAt.flat().filter(mp => ks.tupled.has(mp)))];
3713
+ if (!only && tm.length > 1)
3714
+ tries.push(...tm.map(mp => ({ only: new Set([mp]), der })), ...(tm.length > 2 ? tm.flatMap((a, i) => tm.slice(i + 1).map(b => ({ only: new Set([a, b]), der }))) : []));
3715
+ continue;
3716
+ }
3717
+ const empty = (b) => !bitIntersects([b]), and = bitIntersection;
3718
+ const none = (ls) => !bitIntersects(ls.map(l => lits[l].bits));
3719
+ // (a renaming of a sort's keys moves each literal to the place its keys go to)
3720
+ const perms = keys.reduce((acc, s) => acc.flatMap(p => keys.flatMap((t, j) => (t === s && !p.includes(j) ? [[...p, j]] : []))), [[]]);
3721
+ const canon = (ls) => perms.map(ren => ls.map(l => lits[l].name(ren)).sort().join('&')).sort()[0];
3722
+ const seen = new Set(), found = [];
3723
+ const dfs = (from, chosen, size, bits, most = 400) => {
3724
+ for (let j = from; j < lits.length && found.length < most; j++) {
3725
+ if (chosen.some(c => lits[c].id === lits[j].id))
3726
+ continue;
3727
+ const now2 = [...chosen, j], next = lits[j].bits;
3728
+ // A leaf only asks whether any row holds the cube. Stop at its first witness,
3729
+ // without materializing a bitmap (also for each minimality check).
3730
+ if (now2.length < size) {
3731
+ const b = bits ? and(bits, next) : next;
3732
+ if (!empty(b))
3733
+ dfs(j + 1, now2, size, b, most);
3734
+ continue;
3735
+ }
3736
+ if (bitIntersects(bits ? [bits, next] : [next]) || now2.some((_, k) => now2.length > 1 && none(now2.filter((__, q) => q !== k))))
3737
+ continue;
3738
+ // (a cube reading no state (keys and functions alone) is a fact of the functions' tables, or false: none)
3739
+ if (contradicts(now2.map(l => lits[l].lit)) || !now2.some(l => lits[l].state) || oneSided(now2.map(l => lits[l].lit), vi))
3740
+ continue;
3741
+ const read = new Set(now2.flatMap(l => lits[l].reads)), k2 = canon(now2);
3742
+ if (der && read.has(der.src))
3743
+ read.add(keys0.length);
3744
+ if (read.size === keys.length && !seen.has(k2)) {
3745
+ seen.add(k2);
3746
+ found.push(now2);
3747
+ }
3748
+ }
3749
+ };
3750
+ // (four literals where a view's literals are few: a ring's order of three keys with what holds there)
3751
+ const all0 = lits.map(l => l.lit);
3752
+ // Small samples may make a premise empty without making it impossible. Retain
3753
+ // cross-relation implications as alternatives to that stronger empty law.
3754
+ if (relationalSupport) {
3755
+ const mapAt = (j) => { const is = atomsIn(formOf([lits[j].lit])); return is.length === 1 && atoms[is[0]].place !== undefined ? atoms[is[0]].parts[0][0].split(AT)[2] : undefined; };
3756
+ const pos = lits.flatMap((l, j) => 'lin' in l.lit && l.lit.lin.d === -1 && l.lit.lin.coef.length === 1 && l.lit.lin.coef[0][1] === -1 && mapAt(j) ? [j] : []);
3757
+ const neg = lits.flatMap((l, j) => 'at' in l.lit && l.lit.at.value === 0 && m.relations?.[mapAt(j) ?? ''] ? [j] : []);
3758
+ const controls = lits.flatMap((l, j) => atomsIn(formOf([l.lit])).some(i => atoms[i].place === undefined && !atoms[i].cell && !atoms[i].term && !atoms[i].param) ? [j] : []);
3759
+ const keep = (js, p) => {
3760
+ if (new Set(js.flatMap(j => lits[j].reads)).size !== keys.length || !none(js) || contradicts(js.map(j => lits[j].lit)))
3761
+ return;
3762
+ const f = formOf(js.map(j => lits[j].lit), vi);
3763
+ const posAtom = atomsIn(formOf([lits[p].lit]))[0], pattern = pats[atoms[posAtom].place] ?? [];
3764
+ const repeated = js.reduce((sum, j) => { const a = atomsIn(formOf([lits[j].lit]))[0], ps = (pats[atoms[a].place] ?? []).filter(k => k >= 0); return sum + ps.length - new Set(ps).size; }, 0);
3765
+ const excess = keys0.filter((_, k) => !lits[p].reads.includes(k)).length;
3766
+ const missingImage = der ? js.filter(j => j !== p && !lits[j].reads.includes(keys0.length)).length : 0;
3767
+ let wrongRole = 0;
3768
+ if (der)
3769
+ for (const j of js.filter(j => j !== p)) {
3770
+ const a = atomsIn(formOf([lits[j].lit]))[0], pat = pats[atoms[a].place] ?? [];
3771
+ for (const [pos, maps] of imagePlaces.get(mapAt(j) ?? '') ?? [])
3772
+ if (maps.has(der.mp))
3773
+ wrongRole += pat[pos] === keys0.length ? -1 : 1;
3774
+ }
3775
+ bridges.set(f, { observed: !empty(lits[p].bits), premise: `${mapAt(p)}:${js.length}`, cost: excess * 100 + wrongRole * 20 + missingImage * 10 + (pattern.includes(keys0.length) ? 5 : 0) + repeated * 2 + keys0.length });
3776
+ out.push(f);
3777
+ };
3778
+ for (const p of pos) {
3779
+ for (const c of controls)
3780
+ keep([p, c], p);
3781
+ for (const a of neg)
3782
+ if (mapAt(a) !== mapAt(p) && lits[a].reads.some(k => lits[p].reads.includes(k))) {
3783
+ keep([p, a], p);
3784
+ if (der && (opts.cubes ?? 3) >= 3)
3785
+ for (const b of neg)
3786
+ if (b > a && mapAt(b) !== mapAt(a) && mapAt(b) !== mapAt(p))
3787
+ keep([p, a, b], p);
3788
+ }
3067
3789
  }
3068
3790
  }
3069
- };
3070
- // (four literals where a view's literals are few: a ring's order of three keys with what holds there)
3071
- for (let size = 1; size <= (lits.length <= 40 ? 4 : 3); size++)
3072
- dfs(0, [], size);
3073
- // (where they are more: the four-literal cubes with a chain of three keys of one sort, a < b < c (betweenness, and a
3074
- // cycle's turns of it), the two order literals and any two others, 200 at most; and the doubled patterns below)
3075
- if (lits.length > 40) {
3076
- const at = found.length;
3077
- lits.forEach((a, i) => lits.forEach((b, j) => { if (a.before && b.before && a.before[1] === b.before[0] && a.before[0] !== b.before[1] && found.length < at + 200) {
3078
- const ab = and(a.bits, b.bits);
3079
- if (!empty(ab))
3080
- dfs(0, [i, j], 4, ab, at + 200);
3081
- } }));
3082
- // (and "two of a pattern are one", DuoAI's: a two-literal pattern some row has, beside its image under a renaming of
3083
- // the view's keys within their sorts (Transfer[z, x] and Ep[x] < z, twice: two live transfers), 200 at most)
3084
- const byName = new Map(lits.map((l, i) => [l.name(keys.map((_, k) => k)), i])), at2 = found.length;
3085
- for (const ren of perms.filter(r => r.some((k, i) => k !== i)))
3086
- for (let i = 0; i < lits.length && found.length < at2 + 200; i++)
3087
- for (let j = i + 1; j < lits.length && found.length < at2 + 200; j++) {
3088
- const i2 = byName.get(lits[i].name(ren)), j2 = byName.get(lits[j].name(ren));
3089
- if (i2 === undefined || j2 === undefined || new Set([i, j, i2, j2]).size < 4 || lits[i].id === lits[j].id || empty(and(lits[i].bits, lits[j].bits)))
3090
- continue;
3091
- const ls2 = [i, j, i2, j2], b2 = ls2.slice(1).reduce((b, l) => and(b, lits[l].bits), lits[i].bits);
3092
- if (!empty(b2) || ls2.some((_, k) => none(ls2.filter((__, q) => q !== k))) || contradicts(ls2.map(l => lits[l].lit)) || oneSided(ls2.map(l => lits[l].lit), vi))
3093
- continue;
3094
- const read = new Set(ls2.flatMap(l => lits[l].reads)), k2 = canon(ls2);
3095
- if (read.size === keys.length && !seen.has(k2)) {
3096
- seen.add(k2);
3097
- found.push(ls2);
3791
+ dfs(0, [], 1);
3792
+ const found1 = found.map(ls => ls.map(l => lits[l].lit));
3793
+ found.length = 0;
3794
+ lits.splice(0, lits.length, ...informative);
3795
+ // Cube-only callers discard wider cubes at the API boundary. Do not build
3796
+ // or data-filter them first: use the requested width during enumeration.
3797
+ const requestedWidth = opts.cubes || Infinity;
3798
+ for (let size = 2; size <= Math.min(requestedWidth, lits.length <= 40 ? 4 : 3); size++)
3799
+ dfs(0, [], size);
3800
+ // (where they are more: the four-literal cubes with a chain of three keys of one sort, a < b < c (betweenness, and a
3801
+ // cycle's turns of it), the two order literals and any two others, 200 at most; and the doubled patterns below)
3802
+ if (lits.length > 40 && requestedWidth >= 4) {
3803
+ const at = found.length;
3804
+ lits.forEach((a, i) => lits.forEach((b, j) => { if (a.before && b.before && a.before[1] === b.before[0] && a.before[0] !== b.before[1] && found.length < at + 200) {
3805
+ const ab = and(a.bits, b.bits);
3806
+ if (!empty(ab))
3807
+ dfs(0, [i, j], 4, ab, at + 200);
3808
+ } }));
3809
+ // (and "two of a pattern are one", DuoAI's: a two-literal pattern some row has, beside its image under a renaming of
3810
+ // the view's keys within their sorts (Transfer[z, x] and Ep[x] < z, twice: two live transfers), 200 at most)
3811
+ const byName = new Map(lits.map((l, i) => [l.name(keys.map((_, k) => k)), i])), at2 = found.length;
3812
+ for (const ren of perms.filter(r => r.some((k, i) => k !== i)))
3813
+ for (let i = 0; i < lits.length && found.length < at2 + 200; i++)
3814
+ for (let j = i + 1; j < lits.length && found.length < at2 + 200; j++) {
3815
+ const i2 = byName.get(lits[i].name(ren)), j2 = byName.get(lits[j].name(ren));
3816
+ if (i2 === undefined || j2 === undefined || new Set([i, j, i2, j2]).size < 4 || lits[i].id === lits[j].id || empty(and(lits[i].bits, lits[j].bits)))
3817
+ continue;
3818
+ const ls2 = [i, j, i2, j2];
3819
+ if (!none(ls2) || ls2.some((_, k) => none(ls2.filter((__, q) => q !== k))) || contradicts(ls2.map(l => lits[l].lit)) || oneSided(ls2.map(l => lits[l].lit), vi))
3820
+ continue;
3821
+ const read = new Set(ls2.flatMap(l => lits[l].reads)), k2 = canon(ls2);
3822
+ if (read.size === keys.length && !seen.has(k2)) {
3823
+ seen.add(k2);
3824
+ found.push(ls2);
3825
+ }
3098
3826
  }
3099
- }
3827
+ }
3828
+ known.set(vi, { R, lits: all0 });
3829
+ out.push(...[...found1, ...found.map(ls => ls.map(l => lits[l].lit))].map(c => formOf(c, vi)));
3100
3830
  }
3101
- known.set(vi, { R, lits: lits.map(l => l.lit) });
3102
- out.push(...found.map(ls => formOf(ls.map(l => lits[l].lit), vi)));
3103
3831
  }
3104
- const made0 = out.filter((f, i) => !set.some(g => textOf(g) === textOf(f)) && out.findIndex(g => textOf(g) === textOf(f)) === i);
3832
+ const seenText = new Set(), made1 = out.filter(f => { const t = textOf(f); return !set.some(g => textOf(g) === t) && !seenText.has(t) && !!seenText.add(t); });
3833
+ const made0 = rel && made1.length > 600 ? (relationalSupport ? diverse(made1) : [...made1].sort((a, b) => a.cube.length - b.cube.length)).slice(0, 600) : made1;
3105
3834
  return env.GDP_POOL !== '0' ? dataFilter(made0) : made0;
3106
3835
  // The pool's data filter (DuoAI's junk killed by data before any solver call; research/protocols/engine/DESIGN.md,
3107
3836
  // gen/pool): each cube asked at every reachable state of larger instances, one more element of every sort and then
@@ -3117,7 +3846,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
3117
3846
  const t5 = vnow(), share = Math.min(Number(env.GDP_POOL_MS ?? 30_000), (eUntil - t5) / 3);
3118
3847
  const quiet = Number(env.GDP_POOL_QUIET ?? 150), least5 = Number(env.GDP_POOL_LEAST ?? 0), most5 = Number(env.GDP_POOL_STATES ?? 1_000);
3119
3848
  const litAt = (l, r) => ('at' in l ? valueOf(atoms[l.at.atom], r) === l.at.value : l.lin.coef.reduce((s2, [i, c]) => s2 + c * valueOf(atoms[i], r), 0) <= l.lin.d);
3120
- const plans = [() => 1, ...(ss.length > 1 ? ss.map(s2 => (q) => (q === s2 ? 1 : 0)) : [])];
3849
+ const plans = [q => grown(q) + 1, ...(ss.length > 1 ? ss.map(s2 => (q) => grown(q) + (q === s2 ? 1 : 0)) : [])];
3121
3850
  let live = pool, states = 0;
3122
3851
  for (const [k, grow] of plans.entries()) {
3123
3852
  if (!live.length || stop())
@@ -3125,8 +3854,11 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
3125
3854
  const killed = new Set(), byView = new Map();
3126
3855
  for (const f of live)
3127
3856
  byView.set(f.view, [...(byView.get(f.view) ?? []), f]);
3857
+ // Each literal is shared by many cubes. Read it once per row, lazily, retaining
3858
+ // the original cube/row order and the exact near-miss counts before a kill.
3859
+ const tables = new Map([...byView].map(([vi, fs]) => [vi, samplePredicates(fs.map(f => f.cube), l => JSON.stringify(l), litAt)]));
3128
3860
  let read = 0, still = 0, lastKill = 0;
3129
- const r = instance(grow, share, searchSeeded(29 + k), most5, q => {
3861
+ const r = instance(grow, share, seeded(29 + k), most5, q => {
3130
3862
  if (read >= most5 || (read >= (k ? 0 : least5) && still >= quiet) || stop())
3131
3863
  return false;
3132
3864
  states++;
@@ -3137,12 +3869,16 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
3137
3869
  if (!alive.length)
3138
3870
  continue;
3139
3871
  const rows = withTable(q.params, () => views[vi].rowsOf(q.params, q.st, true));
3140
- for (const f of alive) {
3872
+ const table = tables.get(vi), holds = table.on(rows);
3873
+ for (let fi = 0; fi < fs.length; fi++) {
3874
+ const f = fs[fi];
3875
+ if (killed.has(f))
3876
+ continue;
3141
3877
  let near = 0;
3142
- for (const row of rows) {
3878
+ for (let ri = 0; ri < rows.length; ri++) {
3143
3879
  let off = 0;
3144
- for (const l of f.cube)
3145
- if (!litAt(l, row) && ++off > 1)
3880
+ for (const l of table.groups[fi])
3881
+ if (!holds(l, ri) && ++off > 1)
3146
3882
  break;
3147
3883
  if (off === 0) {
3148
3884
  killed.add(f);
@@ -3199,7 +3935,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
3199
3935
  // (a sums pass's reserve where one follows: 10 s, or a quarter of what is left where less is)
3200
3936
  const v0 = views.length, reserve = rule?.withMapSums() ? Math.min(10_000, (eUntil - vnow()) / 4) : 0;
3201
3937
  const implied = (f) => {
3202
- const v = views[f.view], sk = { vars: Object.fromEntries(v.vars.map(k => [k, x(`${k}#`)])), maps: {}, flags: {} }, hyps = [substC(v.frame, sk), not(substC(condOf(f), sk))];
3938
+ const v = views[f.view], sk = { vars: Object.fromEntries([...v.vars.filter((_, i) => !v.defs?.[i]), ...freeOf(f, v)].map(k => [k, x(`${k}#`)])), maps: {}, flags: {} }, hyps = [substC(substC(v.frame, defsOf(v)), sk), not(substC(substC(condOf(f), defsOf(v)), sk))];
3203
3939
  for (const l of given) {
3204
3940
  const b = [l.forall, ...(l.keys ?? [])].filter((q) => !!q);
3205
3941
  if (v.vars.length ** b.length > 64)
@@ -3223,7 +3959,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
3223
3959
  // (in turn by the maps a cube reads, those reading the caller's first: one of each kind before a second of any; in
3224
3960
  // a kind, the fewer literals first (DuoAI's minimal clauses), then the cube over more distinct keys (the law its
3225
3961
  // diagonal case is a case of))
3226
- const mapsOfCube = (f) => [...new Set(f.cube.flatMap(l => atomsIn(formOf([l])).map(i => atoms[i].parts[0][0].split(AT)[2] ?? '')))].sort().join();
3962
+ const mapsOfCube = (f) => relationalSupport ? familyOf(f) : [...new Set(f.cube.flatMap(l => atomsIn(formOf([l])).map(i => atoms[i].parts[0][0].split(AT)[2] ?? '')))].sort().join();
3227
3963
  const byMaps = new Map();
3228
3964
  const width2 = (f) => views[f.view].vars.length;
3229
3965
  for (const f of [...made].sort((a, b) => near(a) - near(b) || a.cube.length - b.cube.length || width2(b) - width2(a))) {
@@ -3237,14 +3973,17 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
3237
3973
  if (fs[i])
3238
3974
  turns.push(fs[i]);
3239
3975
  // (every cube of at most two literals first, DuoAI's minimal clauses, the turns' order kept within each part)
3240
- turns.sort((a, b) => Math.min(a.cube.length, 3) - Math.min(b.cube.length, 3));
3976
+ if (relationalSupport)
3977
+ turns.splice(0, turns.length, ...diverse(made));
3978
+ else
3979
+ turns.sort((a, b) => Math.min(a.cube.length, 3) - Math.min(b.cube.length, 3));
3241
3980
  // (round 0 the minimal cubes, at most 24, or the whole enumeration where it is 16 or fewer; the rest by relevance to
3242
3981
  // the counterexamples, IC3's order)
3243
3982
  const whole = made.length <= 16;
3244
3983
  for (const f of turns) {
3245
- if (cubes.length >= 24 || stop())
3984
+ if (cubes.length >= (relationalSupport ? 96 : 24) || stop())
3246
3985
  break;
3247
- if ((whole || f.cube.length <= 2) && !names.has(textOf(f)) && !implied(f))
3986
+ if ((whole || f.cube.length <= (relationalSupport ? 3 : 2)) && !names.has(textOf(f)) && !implied(f))
3248
3987
  cubes.push(f);
3249
3988
  }
3250
3989
  opts.progress?.('join enumerated', { views: views.length - v0, cubes: cubes.length, ms: Math.round(vnow()) });
@@ -3280,7 +4019,10 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
3280
4019
  if (vnow() > eUntil)
3281
4020
  return false;
3282
4021
  try {
3283
- post = run.step(params, st, requestOf(w));
4022
+ const next = relStep ? relStep(params, st, requestOf(w)) : run.step(params, st, requestOf(w));
4023
+ if (!next)
4024
+ return false;
4025
+ post = next;
3284
4026
  stepNamed(st, post);
3285
4027
  }
3286
4028
  catch {
@@ -3391,6 +4133,8 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
3391
4133
  if (v.vars.length !== 1 || stop())
3392
4134
  continue;
3393
4135
  const keyed = (l) => atomsIn(formOf([l])).some(i => atoms[i].place !== undefined || !!atoms[i].term);
4136
+ if (k.lits.some(l => atomsIn(formOf([l])).some(i => atoms[i].place !== undefined && !!v.proj?.[atoms[i].place])))
4137
+ continue;
3394
4138
  const As = [[], ...k.lits.filter(l => !keyed(l)).map(l => [l])], Bs0 = k.lits.filter(keyed);
3395
4139
  const off = (l) => !('at' in l) || l.at.value !== 0;
3396
4140
  const Bs = [...Bs0.map(l => [l]), ...Bs0.flatMap((l, i) => Bs0.slice(i + 1).map(l2 => [l, l2]))].filter(b => !contradicts(b) && b.some(off));
@@ -3539,13 +4283,17 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
3539
4283
  const nm = (i) => atoms[i].name.replace(tok, (_, c) => letters[ren[letters.indexOf(c)]]);
3540
4284
  return 'at' in l ? { sum: nm(l.at.atom), d: 0, at: l.at.value } : { sum: l.lin.coef.map(([i, c]) => `${c}*${nm(i)}`).sort().join('+'), d: l.lin.d };
3541
4285
  });
4286
+ // (a projected place's free part, _, matches any key there: P[x, x, y, y] in it entails P[x, _, y, _] in it)
4287
+ const pat = new Map(), same3 = (a, b) => a === b || (a.includes('_') && (pat.get(a) ?? (pat.set(a, new RegExp(`^${a.replace(/[.*+?^${}()|[\]\\]/g, '\\$&').replace(/_/g, '(?:[xyzwu]|\\w+\\([xyzwu]\\))')}$`)), pat.get(a))).test(b));
3542
4288
  const entails = (b, a) => (a.at !== undefined ? b.at !== undefined && b.sum === a.sum && b.at === a.at
3543
- : b.at !== undefined ? a.sum === `-1*${b.sum}` && -b.at <= a.d : b.sum === a.sum && b.d <= a.d);
4289
+ : b.at !== undefined ? same3(a.sum, `-1*${b.sum}`) && -b.at <= a.d : same3(a.sum, b.sum) && b.d <= a.d);
3544
4290
  const sortsOf = (f) => viewSorts.get(f.view) ?? [];
3545
4291
  const maps2 = (sa, sb) => sa.reduce((acc, s2) => acc.flatMap(r => sb.flatMap((t2, j) => (t2 === s2 && !r.includes(j) ? [[...r, j]] : []))), [[]]);
3546
4292
  const own = new Map(pool.map(f => [f, litsOf(f, sortsOf(f).map((_, i) => i))]));
3547
- const implies = (a, b) => a !== b && maps2(sortsOf(a), sortsOf(b)).some(ren => { const la = litsOf(a, ren), lb = own.get(b); return la.every(x2 => lb.some(y2 => entails(y2, x2))); });
3548
- const order = [...pool].sort((p2, q2) => p2.cube.length - q2.cube.length || sortsOf(p2).length - sortsOf(q2).length);
4293
+ const implies = (a, b) => a !== b && (!relationalSupport || familyOf(a) === familyOf(b)) && maps2(sortsOf(a), sortsOf(b)).some(ren => { const la = litsOf(a, ren), lb = own.get(b); return la.every(x2 => lb.some(y2 => entails(y2, x2))); });
4294
+ // (ties: the cube with more free parts first, the weaker one, so the particular ones it implies go)
4295
+ const frees = (f) => f.cube.reduce((k, l) => k + atomsIn(formOf([l])).filter(i => atoms[i].name.includes('_')).length, 0);
4296
+ const order = [...pool].sort((p2, q2) => p2.cube.length - q2.cube.length || sortsOf(p2).length - sortsOf(q2).length || frees(q2) - frees(p2));
3549
4297
  const kept = [], by = new Map();
3550
4298
  for (const b of order)
3551
4299
  if (!kept.some(a => implies(a, b)))
@@ -3747,18 +4495,24 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
3747
4495
  // (DuoAI's: the Houdini fixpoint of the relevant candidates, once, with 40% of the engine's time left: the set, the pending cubes and every cube a
3748
4496
  // counterexample ranked in its top eight, a cube the fast proof fails at dropped (the usual proof where it fails at
3749
4497
  // a cube the rounds proved), until the whole proves or the time is out)
3750
- if (!houdinied && !enumProof && vnow() > eUntil - 0.4 * (eUntil - engineStart)) {
3751
- houdinied = true;
4498
+ // (on a rule of relations also at once, over round 0's cubes: each cube's own goal there runs to the EPR path's cap
4499
+ // on a relation of four places, where the set's proof reads them together)
4500
+ const early = round === 0 && !!Object.keys(m.relations ?? {}).length && !relationalSupport;
4501
+ if (!enumProof && (early || (!houdinied && vnow() > eUntil - 0.4 * (eUntil - engineStart)))) {
4502
+ if (!early)
4503
+ houdinied = true;
3752
4504
  let hs = [...new Map([...cubes, ...pending, ...pool].filter(g => !dead.has(textOf(g)) && !atStart(g)).map(g => [textOf(g), g])).values()];
3753
4505
  for (let k = 0; k < 200 && hs.length && vnow() < eUntil && !stop(); k++) {
3754
4506
  const t2 = vnow(), hl = [...laws, ...hs.map(lawFor), ...(ghost ? [ghost.some] : [])];
3755
- let v = within(t0 + ms, () => prove(hl, true));
4507
+ // (the early one each proof within a quarter of what is left of the engine's: the rounds after it keep theirs)
4508
+ const hEnd = early ? Math.min(t0 + ms, vnow() + (eUntil - vnow()) / 4) : t0 + ms;
4509
+ let v = within(hEnd, () => prove(hl, true));
3756
4510
  const at0 = String(v.goal ?? ''), g0 = v.proven && v.checked ? undefined : hs.find(c => at0.startsWith(`${textOf(c)} @`));
3757
4511
  // (or at a law the caller gave, a kind's: no cube to blame, so the usual proof's verdict)
3758
4512
  if (!(v.proven && v.checked) && (g0 ? at0.endsWith('@step') && stands.has(lawFor(g0).name) : true))
3759
- v = within(t0 + ms, () => prove(hl));
4513
+ v = within(hEnd, () => prove(hl));
3760
4514
  const at = String(v.goal ?? ''), g = v.proven && v.checked ? undefined : hs.find(c => at.startsWith(`${textOf(c)} @`));
3761
- opts.progress?.('join houdini', { cubes: hs.length, proven: v.proven && v.checked ? 1 : 0, ms: Math.round(vnow() - t2), at: at.slice(0, 100) });
4515
+ opts.progress?.('join houdini', { cubes: hs.length, proven: v.proven && v.checked ? 1 : 0, ms: Math.round(vnow() - t2), at: at.slice(0, 100), ...(g ? {} : { stuck: String(v.stuck ?? ''), why: String(v.why ?? '').slice(0, 160) }) });
3762
4516
  if (v.proven && v.checked) {
3763
4517
  why = 'inductive';
3764
4518
  cone = hs;
@@ -3792,7 +4546,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
3792
4546
  for (let it = 0; it < 6; it++) {
3793
4547
  const cs = cubes.filter(c => !out2.has(c)), ls2 = it ? [...given, ...cs.map(lawFor), ...(ghost ? [ghost.plain] : [])] : lsAll, mm2 = it ? withGhost(forLaws(ls2).m) : mmRound;
3794
4548
  const byName = new Map(cs.map(c => [textOf(c), c])), at3 = new Map(cs.map((c, i) => [c, given.length + i])), need = new Set(), todo = [];
3795
- const ask = (i) => (vnow() > kUntil() || stop() ? undefined : within(Math.min(kUntil(), vnow() + joinQueryMs / 8), () => decideLaw(mm2, ls2, i)));
4549
+ const ask = (i) => (vnow() > kUntil() || stop() ? undefined : within(Math.min(kUntil(), vnow() + (i < given.length ? joinQueryMs : joinQueryMs / 8)), () => decideLaw(mm2, ls2, i)));
3796
4550
  const add = (us) => { for (const u of us)
3797
4551
  if (!need.has(u)) {
3798
4552
  need.add(u);
@@ -3823,6 +4577,8 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
3823
4577
  }
3824
4578
  if (failed) {
3825
4579
  out2.add(failed);
4580
+ if (relationalSupport)
4581
+ real.add(failed);
3826
4582
  opts.progress?.('join cone', { round, it, failed: textOf(failed).slice(0, 100), need: need.size, ms: Math.round(vnow() - t1) });
3827
4583
  continue;
3828
4584
  }
@@ -3840,7 +4596,11 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
3840
4596
  }
3841
4597
  if (!g)
3842
4598
  return false;
4599
+ // The nominal-relation frontier drops its failed cone candidates.
4600
+ // Other engines may need them again after learning arithmetic support.
3843
4601
  out2.add(g);
4602
+ if (relationalSupport)
4603
+ real.add(g);
3844
4604
  }
3845
4605
  return false;
3846
4606
  };
@@ -3858,6 +4618,8 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
3858
4618
  over = true;
3859
4619
  return;
3860
4620
  }
4621
+ if (relationalSupport && real.size)
4622
+ break;
3861
4623
  }
3862
4624
  if (f)
3863
4625
  held = true;
@@ -3885,12 +4647,13 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
3885
4647
  stand(ls[idx].name);
3886
4648
  continue;
3887
4649
  }
3888
- let isReal = !!dl && (f && dl.goal.endsWith('@start') ? badAtStart(f, dl.witness) : realCti(dl.witness, f, others)), wit = dl?.witness;
4650
+ const hint = !dl ? decideNote.hint : undefined;
4651
+ let isReal = !!dl && (f && dl.goal.endsWith('@start') ? badAtStart(f, dl.witness) : realCti(dl.witness, f, others)), wit = dl?.witness ?? hint?.witness;
3889
4652
  if (f && isReal && dl.goal.endsWith('@start'))
3890
4653
  startReal.add(f);
3891
4654
  // (a cube the EPR path ran out of time on: unsure at once, kept as optimistic Houdini keeps it; the CDCL search
3892
4655
  // after it would be no quicker)
3893
- if (!dl && !(f && outOfTime)) {
4656
+ if (!dl && !hint && !(f && outOfTime)) {
3894
4657
  const inst = mapNames.length ? lawInstances(mm, ls, idx) : undefined, g = obligations(mm, ls, inst ? { [ls[idx].name]: inst } : {}, idx)[1];
3895
4658
  // (the engine's wall too: a counted budget alone runs on past it, wo's 6 s)
3896
4659
  // (its share on the wall too: a counted budget of 2 s ran 8.8 s on wo's 3-key cubes)
@@ -3992,6 +4755,8 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
3992
4755
  }
3993
4756
  }
3994
4757
  opts.progress?.('join enumerated', { round, cubes: cubes.length, real: real.size, unsure: unsure.size, caller: caller ? 1 : 0, diagrams: blocked2.length, ms: Math.round(vnow()) });
4758
+ if (unsure.size)
4759
+ opts.progress?.('join unsure', { round, cubes: [...unsure].map(textOf).join(' | ') });
3995
4760
  // (optimistic Houdini: an unsure cube holds at every small state and every step from one (they are its rows), so
3996
4761
  // it stays; the set's proof decides, a cube it fails at dropped and the rounds go on)
3997
4762
  // (IC3's push: the pending cubes asked together, each with the set and every other pending one assumed (one frame),
@@ -4135,7 +4900,8 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
4135
4900
  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) };
4136
4901
  }
4137
4902
  for (;;) {
4138
- if (now() > jUntil || stop()) {
4903
+ // (`join` 0: no round, the engine's alone)
4904
+ if (now() > jUntil || noJoin || stop()) {
4139
4905
  why = 'time';
4140
4906
  break;
4141
4907
  }
@@ -4396,7 +5162,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
4396
5162
  pool = pool0;
4397
5163
  ctis.length = ctis0;
4398
5164
  chosen = [];
4399
- opts.progress?.('join failed', { why: String(e.message).slice(0, 120) });
5165
+ opts.progress?.('join failed', { why: String(e.stack).slice(0, 1500) });
4400
5166
  }
4401
5167
  // The search proves one law at a time (proveLaw), each with every law assumed, and keeps what it proved while laws
4402
5168
  // are only added (more laws assumed keep a proof a proof); dropping one forgets it all. Once every law is proven so,
@@ -4451,6 +5217,14 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
4451
5217
  if (!last.goal)
4452
5218
  break;
4453
5219
  const name = goalName(last.goal), stuckOn = chosen.find(f => lawFor(f).name === name);
5220
+ // (the join's control states no state reached, one law for all, unproven with every law of the set assumed (their
5221
+ // instances shared among more laws: a model none of the join's proofs met): each its own law, as the join has them
5222
+ // once one is broken)
5223
+ if (stuckOn?.nevers && !last.run) {
5224
+ chosen = chosen.flatMap(f => (f === stuckOn ? f.nevers.map(c => ({ ...f, nevers: undefined, ...(c.length > 1 ? { never: c } : { unreachable: c[0] }) })) : [f]));
5225
+ forget();
5226
+ continue;
5227
+ }
4454
5228
  if (last.run) {
4455
5229
  // A real run breaks it: a candidate is false (dropped); a law of the caller's is false (the answer).
4456
5230
  if (!stuckOn)