gdp-wired 0.45.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 (120) 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 +423 -31
  7. package/dist/core/calendar.d.ts +29 -0
  8. package/dist/core/calendar.js +82 -0
  9. package/dist/core/cli.d.ts +3 -0
  10. package/dist/core/cli.js +204 -38
  11. package/dist/core/compose.js +3 -1
  12. package/dist/core/counts.d.ts +4 -1
  13. package/dist/core/counts.js +314 -85
  14. package/dist/core/cycles.js +8 -1
  15. package/dist/core/cyclic.d.ts +1 -0
  16. package/dist/core/cyclic.js +13 -7
  17. package/dist/core/data-synth.d.ts +3 -0
  18. package/dist/core/data-synth.js +252 -0
  19. package/dist/core/data.d.ts +2 -1
  20. package/dist/core/data.js +223 -24
  21. package/dist/core/discover.js +3 -1
  22. package/dist/core/draft.d.ts +19 -0
  23. package/dist/core/draft.js +53 -0
  24. package/dist/core/dsl.d.ts +37 -3
  25. package/dist/core/dsl.js +167 -26
  26. package/dist/core/effect.d.ts +1 -4
  27. package/dist/core/effect.js +1 -15
  28. package/dist/core/exists.d.ts +1 -0
  29. package/dist/core/exists.js +191 -16
  30. package/dist/core/extract-c.d.ts +2 -0
  31. package/dist/core/extract-c.js +169 -22
  32. package/dist/core/extract-check.d.ts +1 -0
  33. package/dist/core/extract-check.js +66 -0
  34. package/dist/core/extract-go-check.d.ts +1 -1
  35. package/dist/core/extract-go-check.js +2 -1
  36. package/dist/core/extract-go.d.ts +1 -0
  37. package/dist/core/extract-go.js +38 -4
  38. package/dist/core/extract-ir.d.ts +1 -0
  39. package/dist/core/extract-ir.js +15 -0
  40. package/dist/core/extract-jvm.d.ts +1 -1
  41. package/dist/core/extract-jvm.js +2 -0
  42. package/dist/core/extract-orm.d.ts +12 -0
  43. package/dist/core/extract-orm.js +244 -0
  44. package/dist/core/extract-print.js +20 -1
  45. package/dist/core/extract-py.d.ts +1 -0
  46. package/dist/core/extract-py.js +1 -1
  47. package/dist/core/extract-read.d.ts +17 -0
  48. package/dist/core/extract-read.js +5 -5
  49. package/dist/core/extract-rs.js +5 -1
  50. package/dist/core/extract-shapes.js +2 -0
  51. package/dist/core/extract-sol.d.ts +10 -1
  52. package/dist/core/extract-sol.js +70 -22
  53. package/dist/core/extract-step.d.ts +151 -1
  54. package/dist/core/extract-step.js +1232 -60
  55. package/dist/core/extract-swift.js +6 -2
  56. package/dist/core/extract.d.ts +8 -0
  57. package/dist/core/extract.js +61 -5
  58. package/dist/core/fiber-run.d.ts +5 -0
  59. package/dist/core/fiber-run.js +18 -0
  60. package/dist/core/infer.d.ts +4 -1
  61. package/dist/core/infer.js +918 -217
  62. package/dist/core/jvm/JavaReader.java +23 -6
  63. package/dist/core/jvm/Jvm.java +3 -0
  64. package/dist/core/jvm/KtReader.java +6 -5
  65. package/dist/core/laws.d.ts +10 -3
  66. package/dist/core/laws.js +193 -14
  67. package/dist/core/machine.d.ts +15 -1
  68. package/dist/core/machine.js +187 -15
  69. package/dist/core/nonterm.js +14 -1
  70. package/dist/core/orm/harness.js +61 -0
  71. package/dist/core/orm-fixtures/schema.prisma +5 -0
  72. package/dist/core/py/harness.py +183 -10
  73. package/dist/core/py/reader.py +234 -40
  74. package/dist/core/reader-fixtures/README.md +28 -0
  75. package/dist/core/reader-fixtures/c-693042.cpp +8 -0
  76. package/dist/core/reader-fixtures/go-685506.go +14 -0
  77. package/dist/core/reader-fixtures/jvm-724362.kt +8 -0
  78. package/dist/core/reader-fixtures/jvm-737430.kt +7 -0
  79. package/dist/core/reader-fixtures/jvm-765282.kt +3 -0
  80. package/dist/core/reader-fixtures/swift-735726.swift +15 -0
  81. package/dist/core/reader-fixtures/swift-735990.swift +15 -0
  82. package/dist/core/reader-fixtures/swift-739158.swift +4 -0
  83. package/dist/core/reader-fixtures/swift-744834.swift +15 -0
  84. package/dist/core/reader-fixtures/swift-746946.swift +31 -0
  85. package/dist/core/reader-fixtures/typescript-673062.ts.txt +2 -0
  86. package/dist/core/relation.d.ts +1 -1
  87. package/dist/core/relation.js +29 -2
  88. package/dist/core/relational.js +4 -2
  89. package/dist/core/rs/src/main.rs +8 -2
  90. package/dist/core/sample-cache.d.ts +8 -0
  91. package/dist/core/sample-cache.js +46 -0
  92. package/dist/core/security.d.ts +38 -0
  93. package/dist/core/security.js +88 -0
  94. package/dist/core/sol/harness.py +57 -4
  95. package/dist/core/sol-concrete.d.ts +23 -0
  96. package/dist/core/sol-concrete.js +195 -0
  97. package/dist/core/solver.js +3 -1
  98. package/dist/core/swift/Sources/gdp-swiftreader/main.swift +50 -7
  99. package/dist/core/system.js +1 -1
  100. package/dist/core/transfer.js +22 -9
  101. package/dist/core/translate.js +39 -10
  102. package/dist/core/watch.js +50 -5
  103. package/dist/interchange/format.js +11 -1
  104. package/dist/kernel/cdcl.d.ts +5 -0
  105. package/dist/kernel/cdcl.js +56 -9
  106. package/dist/kernel/epr.js +108 -26
  107. package/dist/kernel/kernel.d.ts +29 -1
  108. package/dist/kernel/kernel.js +325 -62
  109. package/dist/kernel/model-sequence.d.ts +3 -0
  110. package/dist/kernel/model-sequence.js +34 -0
  111. package/dist/kernel/prove.d.ts +10 -3
  112. package/dist/kernel/prove.js +332 -71
  113. package/dist/kernel/reader.d.ts +3 -0
  114. package/dist/kernel/reader.js +101 -14
  115. package/dist/kernel/share.d.ts +1 -0
  116. package/dist/kernel/share.js +27 -0
  117. package/dist/lean-kernel/emit.js +30 -37
  118. package/dist/lean-kernel/lean-terms.js +5 -0
  119. package/dist/lean-kernel/library.js +10 -10
  120. package/package.json +6 -1
@@ -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, fastStep, divisorsIn, evalC, evalE, get, interpret, machineTerms, fnValue, modName, n, not, plus, same, seeded, 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;
@@ -214,7 +465,7 @@ function keySorts(m, laws, pairing, fine = false) {
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
470
  if (!pairing?.n || fine)
220
471
  return undefined;
@@ -244,7 +495,37 @@ function keySorts(m, laws, pairing, fine = false) {
244
495
  if (v && typeof v === 'object')
245
496
  (Array.isArray(v) ? v : [v]).forEach(y => { if (y && typeof y === 'object' && 'op' in y)
246
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
+ };
247
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
+ }
248
529
  if (t.op === 'get') {
249
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)
250
531
  const carried = (m.inputMaps ?? []).includes(t.map);
@@ -313,6 +594,16 @@ function keySorts(m, laws, pairing, fine = false) {
313
594
  kids(t, y => walk(y, name));
314
595
  };
315
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
+ }
316
607
  for (const [mp, w] of Object.entries(m.step.maps ?? {})) {
317
608
  if ('each' in w)
318
609
  walk(w.value, v => (v === w.each ? `M:${mp}` : rule(v)));
@@ -345,6 +636,7 @@ function keySorts(m, laws, pairing, fine = false) {
345
636
  // (a map of keys of k parts read at a write at every key's own key is no plain read)
346
637
  for (const mp of arity.keys())
347
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; };
348
640
  return {
349
641
  find,
350
642
  sortOf: (l, v) => find(`L:${l.name}:${v}`),
@@ -369,9 +661,11 @@ function keySorts(m, laws, pairing, fine = false) {
369
661
  },
370
662
  // (a guard that reads the state or params beside the keys: a domain that moves)
371
663
  moving: (g, bound) => [...JSON.stringify(g).matchAll(/"name":"([^"]+)"/g)].some(q => !bound.includes(q[1])),
372
- 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)),
373
667
  // (a key of k parts at these key terms)
374
- 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,
375
669
  compose: (a, b) => { const k = plus(times(pairing.n, a), b); return pairing.c ? plus(k, n(pairing.c)) : k; },
376
670
  plainMaps: (sort) => [...plainRead].filter(mp => find(`M:${mp}`) === sort),
377
671
  valuesAt: (st, sort) => {
@@ -387,6 +681,11 @@ function keySorts(m, laws, pairing, fine = false) {
387
681
  ks.add((k - pairing.c) % pairing.n);
388
682
  }
389
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
+ }
390
689
  if (ar && pairing?.n && k >= pairing.c)
391
690
  for (let i = ar - 1, r = k - pairing.c; i >= 0; i--, r = Math.floor(r / pairing.n))
392
691
  if (find(`${mp}:${i}`) === sort)
@@ -471,7 +770,9 @@ function preimages(m, laws, stepLaws, atoms, coords) {
471
770
  case 'min':
472
771
  case 'max': return uniq([...linE(e.a, post), ...linE(e.b, post)]);
473
772
  case 'if': return uniq([...linE(e.then, post), ...linE(e.else, post)]);
474
- case 'prod': return [];
773
+ case 'prod':
774
+ case 'tup':
775
+ case 'proj': return [];
475
776
  case 'get': {
476
777
  const name = e.map.endsWith("'") && maps.has(e.map.slice(0, -1)) ? e.map.slice(0, -1) : e.map;
477
778
  if (!maps.has(name))
@@ -715,7 +1016,9 @@ function comparisons(m, laws, atoms, coords, more = []) {
715
1016
  return [...found.values()];
716
1017
  }
717
1018
  export function inferLaws(target, laws, stepLaws = [], opts = {}) {
718
- 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))));
719
1022
  }
720
1023
  function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
721
1024
  // (GDP_INFER_TRACE=2: each phase's progress too, to stderr)
@@ -813,8 +1116,11 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
813
1116
  trace('start');
814
1117
  // Counted: `runs` requests tried at least, and on until as many states as the samples hold were offered (a trial offers
815
1118
  // its start at least), the trials at most `runs` or that many. Timed: `runsMs` of wall time.
816
- 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));
817
- const moreRuns = (trial) => (runsTimed ? performance.now() < runsUntil : trial < Math.max(cap, least) && (used.tries < least || offered < cap) && !stop());
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());
818
1124
  let trials = 0;
819
1125
  // (an assumption with "there exists", a value the request brings, may admit no request at a small bound, a multiple
820
1126
  // of 5 but 0, say: a trial whose steps moved nothing doubles the bound at once)
@@ -842,7 +1148,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
842
1148
  }
843
1149
  else {
844
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)
845
- params = randomParams(trial % 20 === 1 ? 0 : trial % 2 ? bound : 2 ** rand(11));
1151
+ params = randomParams(trial % 20 === 1 ? 0 : relStep ? Math.min(bound, 4) : trial % 2 ? bound : 2 ** rand(11));
846
1152
  if (m.pre && !evalC(m.pre, params, { scalars: {}, maps: {} }, m))
847
1153
  continue;
848
1154
  try {
@@ -859,9 +1165,17 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
859
1165
  const input = randomInput(params, rare ? 2 : bound);
860
1166
  let next;
861
1167
  try {
862
- if (!allowed(m, run, params, st, input))
863
- continue;
864
- 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
+ }
865
1179
  }
866
1180
  catch {
867
1181
  break;
@@ -899,7 +1213,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
899
1213
  {
900
1214
  const named = (n) => stateSet.has(n) || m.params.includes(n);
901
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)
902
- : 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));
903
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);
904
1218
  const seenT = new Set();
905
1219
  const visitE = (e) => {
@@ -924,7 +1238,8 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
924
1238
  visitE(e.key);
925
1239
  else {
926
1240
  visitE(e.a);
927
- visitE(e.b);
1241
+ if ('b' in e)
1242
+ visitE(e.b);
928
1243
  }
929
1244
  };
930
1245
  const visitC = (c) => { if (c.op === 'and' || c.op === 'or')
@@ -1233,7 +1548,9 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1233
1548
  return only.values.filter(v => c * v <= f.d);
1234
1549
  };
1235
1550
  // (a form about every key says so first)
1236
- 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 ?? [] : [])))] : []);
1237
1554
  const textOf = (f) => {
1238
1555
  if (f.cells)
1239
1556
  return `every k: ${textIn(f)}`;
@@ -1378,13 +1695,34 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1378
1695
  // --- evaluating a form ---------------------------------------------------------------------------------------------
1379
1696
  // (each row's atom values read once, however many forms are evaluated there: rows are never changed once made)
1380
1697
  const valuesAt = new WeakMap();
1698
+ const atomsByField = new Map();
1699
+ let indexedAtoms = 0;
1381
1700
  const valuesOf = (env) => {
1382
1701
  let vs = valuesAt.get(env);
1383
1702
  if (!vs) {
1384
- const n2 = atoms.length;
1385
- vs = new Float64Array(n2);
1386
- for (let i = 0; i < n2; i++)
1387
- 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;
1388
1726
  valuesAt.set(env, vs);
1389
1727
  }
1390
1728
  return vs;
@@ -1510,7 +1848,12 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1510
1848
  return out;
1511
1849
  };
1512
1850
  // --- Houdini on the runs' neighbors ----------------------------------------------------------------------------------
1513
- 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);
1514
1857
  const ctis = [];
1515
1858
  // (a law about keys is evaluated at every tuple of the state's keys, as watch does: counted as that many evaluations)
1516
1859
  const lawful = (params, st) => {
@@ -1528,7 +1871,9 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1528
1871
  return false;
1529
1872
  }
1530
1873
  };
1531
- 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));
1532
1877
  for (let quiet = 0; samples.length && now() < houdiniUntil && !stop() && quiet < 3;) {
1533
1878
  const killed = new Set();
1534
1879
  for (let tries = 0; tries < 400 && now() < houdiniUntil && !stop(); tries++) {
@@ -1581,7 +1926,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1581
1926
  // (about two keys: where the frame holds of them)
1582
1927
  const v = f.view !== undefined ? views[f.view] : undefined;
1583
1928
  if (!l)
1584
- 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) } : {}) }));
1585
1930
  return l;
1586
1931
  };
1587
1932
  const names = new Set(given.map(l => l.name));
@@ -1617,7 +1962,8 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1617
1962
  // eight values most unusual at it are read (furthest past the samples in its guard, then the rarest there).
1618
1963
  const choiceMode = modes.find(mo => mo.choice && !atoms[mo.atom].cell);
1619
1964
  const condAtoms = plain.filter(i => !atoms[i].param && i !== choiceMode?.atom);
1620
- const fromCti = (p) => {
1965
+ const fromCti = (p) => fromCti0(p).filter(plainKeyed);
1966
+ const fromCti0 = (p) => {
1621
1967
  const end = Math.min(until, now() + Math.max(300, (until - now()) / 8));
1622
1968
  const sc = p.scalar, pv = (coef) => { let v = 0; for (const [i, c] of coef)
1623
1969
  v += c * valueOf(atoms[i], sc); return v; };
@@ -1714,7 +2060,9 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1714
2060
  const pool0 = pool.slice(), ctis0 = ctis.length;
1715
2061
  if (joinOn && NS)
1716
2062
  try {
1717
- 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));
1718
2066
  // The control state: the choice (loc) and, where they are few, the yes/nos (a program counter in bits), each of its
1719
2067
  // values reached a part of its own.
1720
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);
@@ -1770,6 +2118,22 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1770
2118
  }
1771
2119
  return rows;
1772
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
+ };
1773
2137
  const addView = (v, mapsAt, valuesOf2, per, extra = [], product = false) => {
1774
2138
  const vi = views.length, va = [];
1775
2139
  // (`extra`: values of its keys that are atoms too, a key or a function of one: e ≤ Ep[a], idn(x) < idn(y))
@@ -1783,7 +2147,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1783
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 });
1784
2148
  }
1785
2149
  });
1786
- 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)),
1787
2151
  xs: extra.map((_, j) => `$x${vi}:${j}`), qs: mapsAt.map((mps, place) => mps.map(mp => `${AT}${AT}${mp}${AT}${vi}:${place}`)) };
1788
2152
  const rowsOf = (params, st, full = false) => {
1789
2153
  // (`per` values a key; the engine's views (`product`) at most per^keys rows a state, 64 at least, the fewer-valued
@@ -1817,11 +2181,33 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1817
2181
  catch {
1818
2182
  row[compiled.xs[j]] = 0;
1819
2183
  } });
1820
- 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
+ });
1821
2196
  used.erows++;
1822
2197
  out.push(mark(withTerms(row, st), st, cells));
1823
2198
  return;
1824
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
+ }
1825
2211
  for (const k2 of cand[i]) {
1826
2212
  env[v.vars[i]] = k2;
1827
2213
  go(i + 1, env);
@@ -1830,7 +2216,8 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1830
2216
  go(0, { ...params, ...st.scalars });
1831
2217
  return out;
1832
2218
  };
1833
- 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 });
1834
2221
  };
1835
2222
  // The pairs: where the rule composes two keys into one (Link[N·a + b] beside Known[a], Known[b]), the cells at two
1836
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
@@ -1839,14 +2226,16 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1839
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).
1840
2227
  const callerLaws = [...laws, ...stepLaws.map(sl => ({ name: sl.name, holds: sl.then, ...(sl.forall ? { forall: sl.forall } : {}), ...(sl.keys ? { keys: sl.keys } : {}) }))];
1841
2228
  const sorts = mapNames.length ? keySorts(m, callerLaws, pairing) : undefined;
1842
- 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) {
1843
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)];
1844
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)
1845
2234
  const sorted = P.n && sorts ? [sorts.plainMaps(sorts.find('hi')), sorts.plainMaps(sorts.find('lo')), sorts.composedMaps] : undefined;
1846
2235
  const held = (st) => {
1847
2236
  const ks = new Set();
1848
- for (const c of Object.values(st.maps))
1849
- for (const k of c.keys()) {
2237
+ for (const mp of flat)
2238
+ for (const k of st.maps[mp]?.keys() ?? []) {
1850
2239
  ks.add(k);
1851
2240
  if (P.n && k >= P.c) {
1852
2241
  ks.add(Math.floor((k - P.c) / P.n));
@@ -1856,7 +2245,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1856
2245
  const xs = [...ks, ks.size ? Math.max(...ks) + 1 : 0];
1857
2246
  return [xs, xs];
1858
2247
  };
1859
- 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);
1860
2249
  }
1861
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
1862
2251
  // the lock; two keys of one sort where the pairs relate two sorts): its keys, each of the sort its reads give it
@@ -2326,7 +2715,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
2326
2715
  s2 += c * v[i]; return s2; };
2327
2716
  const litHolds = (l, v) => ('at' in l ? v[l.at.atom] === l.at.value : dot(l.lin.coef, v) <= l.lin.d);
2328
2717
  const inCube = (c, v) => c.every(l => litHolds(l, v));
2329
- const vecKey = (v) => Array.from(v).join(',');
2718
+ const vecKey = (v) => v instanceof Float64Array ? v.join(',') : Array.from(v).join(',');
2330
2719
  const S = rowsS.map(r => valuesOf(r)), sampled = new Set(S.map(vecKey));
2331
2720
  let initVec;
2332
2721
  try {
@@ -2667,6 +3056,94 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
2667
3056
  m.fns[k] = fn;
2668
3057
  }
2669
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
+ };
2670
3147
  const enumerated = () => {
2671
3148
  const ks = keySorts(m, callerLaws, pairing, true), comp = ks.composedMaps.length && pairing?.n ? [ks.find('hi'), ks.find('lo')] : undefined;
2672
3149
  const multi = [...ks.arity].map(([mp, k]) => ({ mp, slots: Array.from({ length: k }, (_, i) => ks.find(`${mp}:${i}`)) }));
@@ -2682,8 +3159,10 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
2682
3159
  if (less)
2683
3160
  ord.add(vf(b));
2684
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);
2685
3164
  walk([m.step, m.assume], o => { const c = o; if (c.op === '<' || c.op === '<=' || c.op === '=')
2686
- 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)); });
2687
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
2688
3167
  // at every key at it (k = first) or a read at it, is an element of that sort, which pins it against renaming)
2689
3168
  const bounding = new Map(), elementOf = new Map();
@@ -2721,6 +3200,15 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
2721
3200
  bounds.set(s, [...(bounds.get(s) ?? []), substC(g, { vars: { [one[0]]: x(KEY) }, maps: {}, flags: {} })]);
2722
3201
  }
2723
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
+ }
2724
3212
  opts.progress?.('join template', { sorts: ss.map((s, i) => `${s}:${width[i]}`).join(' '), multi: multi.map(q => `${q.mp}:${q.slots.join(',')}`).join(' ') });
2725
3213
  // The small instance (BRAB's, DuoAI's simulation made complete): each key sort its first 2 to 3 elements (its width),
2726
3214
  // an ordered one 0..3, a function's values over its argument's, params small, each input over its sort's elements
@@ -2731,7 +3219,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
2731
3219
  // (`visit`: each new state as the BFS finds it, which ends the BFS by answering false: the filter reads as it goes)
2732
3220
  const instance = (grow, share, rnd, cap = 2_000_000, visit) => {
2733
3221
  let halt = false;
2734
- 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 = [];
2735
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);
2736
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 {
2737
3225
  return fnValue(m.fns[f], k);
@@ -2772,7 +3260,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
2772
3260
  layout.set(mp, [ks.find(`M:${mp}`)]);
2773
3261
  else if (ks.composedMaps.includes(mp) && pairing?.n)
2774
3262
  layout.set(mp, [ks.find('hi'), ks.find('lo')]);
2775
- else if (ar && pairing?.n)
3263
+ else if (ar && (pairing?.n || ks.tupled.has(mp)))
2776
3264
  layout.set(mp, Array.from({ length: ar }, (_, i) => ks.find(`${mp}:${i}`)));
2777
3265
  }
2778
3266
  const stored = new Set(m.inputs.filter(i => JSON.stringify(m.step.state ?? {}).includes(`"name":"${i}"`)).map(i => ks.find(i)));
@@ -2794,6 +3282,10 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
2794
3282
  const pm = ren.get(lay[0]);
2795
3283
  return pm && k < pm.length ? pm[k] : k;
2796
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
+ }
2797
3289
  if (k < pairing.c)
2798
3290
  return k;
2799
3291
  const digits = [];
@@ -2801,21 +3293,29 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
2801
3293
  digits.unshift(i === lay.length - 1 ? r : r % pairing.n);
2802
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);
2803
3295
  };
2804
- 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]);
2805
3297
  // (the state's own text first, its renamings' only for a text not seen)
2806
- const canon = new Map();
3298
+ const canon = new Map(), stateKeys = new WeakMap(), cacheStates = !Object.values(m.step.maps ?? {}).some(w => 'each' in w);
2807
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;
2808
3304
  const own = textAt(q, new Map());
2809
3305
  let best = canon.get(own);
2810
3306
  if (best === undefined) {
2811
3307
  best = own;
2812
3308
  for (const ren of rens) {
3309
+ if (!ren.size)
3310
+ continue;
2813
3311
  const t = textAt(q, ren);
2814
3312
  if (t < best)
2815
3313
  best = t;
2816
3314
  }
2817
3315
  canon.set(own, best);
2818
3316
  }
3317
+ if (cacheStates)
3318
+ stateKeys.set(q.st, { params: q.params, key: best });
2819
3319
  return best;
2820
3320
  };
2821
3321
  // (the step compiled once: core/machine.ts's JavaScript, its assumption refusing a request as `allowed` does)
@@ -2823,7 +3323,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
2823
3323
  // few others that keep its facts on the sort's keys (its values reversed, and each turned by one), each run as its
2824
3324
  // own machine; their states' rows read under their table. One table alone is a fact of it, not of the rule: ring's
2825
3325
  // ids, every node past another one's below it)
2826
- const tables = [{ m, run, js: fastStep(m), fns: {} }];
3326
+ const tables = [{ m, run, js: fastStep(m) ?? relStep, fns: {} }];
2827
3327
  for (const [f, fn] of Object.entries(m.fns ?? {})) {
2828
3328
  const arg = ks.find(`F:${f}`);
2829
3329
  if (fn.call || fn.recur || (fn.arity ?? 1) !== 1 || !ss.includes(arg) || m.history || m.counts)
@@ -2990,7 +3490,27 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
2990
3490
  return { small, others, bfs, cut, params: pvs.size, ms: Math.round(vnow() - t3) };
2991
3491
  };
2992
3492
  {
2993
- 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();
2994
3514
  samples.unshift(...r0.small);
2995
3515
  for (const q of own)
2996
3516
  for (const [mp, cs] of Object.entries(q.st.maps))
@@ -3000,172 +3520,317 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
3000
3520
  // more values, so the literals the cubes are made of are the instance's own)
3001
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];
3002
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
+ });
3003
3538
  const out = [];
3004
3539
  for (const counts of width.reduce((acc, w) => acc.flatMap(c => Array.from({ length: w + 1 }, (_, k) => [...c, k])), [[]])) {
3005
- const keys = ss.flatMap((s, i) => Array.from({ length: counts[i] }, () => s)), vars = keys.map((_, i) => `key${i + 1}$enum`);
3006
- 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())
3007
3543
  continue;
3008
- const places = [], mapsAt = [], covers = [];
3009
- keys.forEach((s, i) => { if (ks.plainMaps(s).length) {
3010
- places.push(x(vars[i]));
3011
- mapsAt.push(ks.plainMaps(s));
3012
- covers.push([i]);
3013
- } });
3014
- if (comp)
3015
- keys.forEach((a, i) => keys.forEach((b, j) => { if (a === comp[0] && b === comp[1]) {
3016
- places.push(ks.compose(x(vars[i]), x(vars[j])));
3017
- mapsAt.push(ks.composedMaps);
3018
- covers.push(i === j ? [i] : [i, j]);
3019
- } }));
3020
- for (const q of multi)
3021
- for (const t of q.slots.reduce((acc, s) => acc.flatMap(p => keys.flatMap((k2, j) => (k2 === s ? [[...p, j]] : []))), [[]])) {
3022
- places.push(ks.composeAll(t.map(j => x(vars[j]))));
3023
- mapsAt.push([q.mp]);
3024
- 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;
3025
3624
  }
3026
- for (const f of fnHi)
3027
- keys.forEach((a, i) => keys.forEach((b, j) => { if (a === ks.find(`F:${f}`) && b === comp[1]) {
3028
- places.push(ks.compose(get(f, x(vars[i])), x(vars[j])));
3029
- mapsAt.push(ks.composedMaps);
3030
- covers.push(i === j ? [i] : [i, j]);
3031
- } }));
3032
- // (and a two-part map's row a function of a key, as a composed map's: Pending[idn(x)·N + y])
3033
- for (const { f, q } of fnRows)
3034
- keys.forEach((a, i) => keys.forEach((b, j) => { if (a === ks.find(`F:${f}`) && b === q.slots[1]) {
3035
- places.push(ks.composeAll([get(f, x(vars[i])), x(vars[j])]));
3036
- mapsAt.push([q.mp]);
3037
- covers.push(i === j ? [i] : [i, j]);
3038
- } }));
3039
- 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}`)));
3040
- 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])) }] : [])))];
3041
- const frame = all(...keys.flatMap((s, i) => [...(((comp && s === comp[1]) || multi.some(q => 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])))] : []))]));
3042
- const vi = views.length;
3043
- 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);
3044
- // (the rows: every small state's, distinct, at most 20,000; the view's own rows stop at its first states, the shallow
3045
- // ones, so a deep state's (a leader's) would be left out)
3046
- viewSorts.set(vi, keys);
3047
- const v = views[vi], R = [], seenRows = new Set();
3048
- for (const q of smallAll.length ? smallAll : []) {
3049
- if (R.length >= 20_000)
3050
- break;
3051
- for (const row of withTable(q.params, () => v.rowsOf(q.params, q.st))) {
3052
- const r = valuesOf(row), k2 = vecKey(r);
3053
- if (!seenRows.has(k2)) {
3054
- seenRows.add(k2);
3055
- 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
+ }
3056
3648
  }
3057
3649
  }
3058
- }
3059
- if (!R.length)
3060
- R.push(...v.rows.slice(0, 3000).map(valuesOf));
3061
- try {
3062
- if (!m.params.length)
3063
- R.push(...v.rowsOf({}, run.init({})).map(valuesOf));
3064
- }
3065
- catch { /* (the samples hold the start) */ }
3066
- // (each literal with the rows it is true at, as bits; `id` its atoms, `name` its text under a renaming of the keys)
3067
- const W = Math.ceil(R.length / 32), lits = [];
3068
- const where = (i) => { const pl = atoms[i].place; return pl === undefined ? [] : covers[pl]; };
3069
- // (an extra atom's key, and its function where it is one)
3070
- 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; };
3071
- const fnOf = (i) => { const t = atoms[i].term; return t?.op === 'get' ? t.map : undefined; };
3072
- 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}`);
3073
- const reads = (i) => (keyOf2(i) >= 0 ? [keyOf2(i)] : where(i));
3074
- const add = (lit, id, name, rd, holds, before) => {
3075
- const bits = new Uint32Array(W);
3076
- R.forEach((r, k) => { if (holds(r))
3077
- bits[k >> 5] |= 1 << (k & 31); });
3078
- 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)) });
3079
- };
3080
- const valued = (i) => atoms[i].place !== undefined && !!valueSort(atoms[i].parts[0][0].split(AT)[2]);
3081
- 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)]) {
3082
- const vals = [...new Set(R.map(r => r[i]))].sort((a, b) => a - b);
3083
- // (a value of a key's sort: 0 alone, an order literal below)
3084
- for (const value of valued(i) ? vals.filter(q => q === 0) : vals.length <= 3 || few(vals) ? vals : []) {
3085
- const top = value > 0 && value === vals.at(-1);
3086
- 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));
3087
3655
  }
3088
- }
3089
- // (an ordered sort's keys and values compared: t ≤ u and u < t, of a key and a value or two values)
3090
- const ts = v.atoms.filter(i => keyOf2(i) >= 0 || valued(i));
3091
- const sortOf2 = (i) => vf(fnOf(i) ? `V:${fnOf(i)}` : keyOf2(i) >= 0 ? keys[keyOf2(i)] : valueSort(atoms[i].parts[0][0].split(AT)[2]));
3092
- for (const [a2, i] of ts.entries())
3093
- for (const j of ts.slice(a2 + 1)) {
3094
- if (sortOf2(i) !== sortOf2(j))
3095
- continue;
3096
- // (two keys of one sort are distinct: one before the other)
3097
- const keysOnly = !fnOf(i) && !fnOf(j) && atoms[i].place === undefined && atoms[j].place === undefined;
3098
- for (const [p, q] of [[i, j], [j, i]])
3099
- for (const d of keysOnly ? [-1] : [0, -1])
3100
- 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
+ }
3101
3692
  }
3102
- used.rows += R.length * lits.length;
3103
- 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) });
3104
- if (lits.length > 96)
3105
- continue;
3106
- const empty = (b) => b.every(w => w === 0), and = (a, b) => a.map((w, k) => w & b[k]);
3107
- const none = (ls) => empty(ls.slice(1).reduce((b, l) => and(b, lits[l].bits), lits[ls[0]].bits));
3108
- // (a renaming of a sort's keys moves each literal to the place its keys go to)
3109
- const perms = keys.reduce((acc, s) => acc.flatMap(p => keys.flatMap((t, j) => (t === s && !p.includes(j) ? [[...p, j]] : []))), [[]]);
3110
- const canon = (ls) => perms.map(ren => ls.map(l => lits[l].name(ren)).sort().join('&')).sort()[0];
3111
- const seen = new Set(), found = [];
3112
- const dfs = (from, chosen, size, bits, most = 400) => {
3113
- for (let j = from; j < lits.length && found.length < most; j++) {
3114
- if (chosen.some(c => lits[c].id === lits[j].id))
3115
- continue;
3116
- const now2 = [...chosen, j], b = bits ? and(bits, lits[j].bits) : lits[j].bits;
3117
- if (now2.length < size) {
3118
- if (!empty(b))
3119
- dfs(j + 1, now2, size, b, most);
3120
- 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);
3121
3705
  }
3122
- if (!empty(b) || now2.some((_, k) => now2.length > 1 && none(now2.filter((__, q) => q !== k))))
3123
- continue;
3124
- // (a cube reading no state (keys and functions alone) is a fact of the functions' tables, or false: none)
3125
- if (contradicts(now2.map(l => lits[l].lit)) || !now2.some(l => lits[l].state) || oneSided(now2.map(l => lits[l].lit), vi))
3126
- continue;
3127
- const read = new Set(now2.flatMap(l => lits[l].reads)), k2 = canon(now2);
3128
- if (read.size === keys.length && !seen.has(k2)) {
3129
- seen.add(k2);
3130
- 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
+ }
3131
3789
  }
3132
3790
  }
3133
- };
3134
- // (four literals where a view's literals are few: a ring's order of three keys with what holds there)
3135
- for (let size = 1; size <= (lits.length <= 40 ? 4 : 3); size++)
3136
- dfs(0, [], size);
3137
- // (where they are more: the four-literal cubes with a chain of three keys of one sort, a < b < c (betweenness, and a
3138
- // cycle's turns of it), the two order literals and any two others, 200 at most; and the doubled patterns below)
3139
- if (lits.length > 40) {
3140
- const at = found.length;
3141
- 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) {
3142
- const ab = and(a.bits, b.bits);
3143
- if (!empty(ab))
3144
- dfs(0, [i, j], 4, ab, at + 200);
3145
- } }));
3146
- // (and "two of a pattern are one", DuoAI's: a two-literal pattern some row has, beside its image under a renaming of
3147
- // the view's keys within their sorts (Transfer[z, x] and Ep[x] < z, twice: two live transfers), 200 at most)
3148
- const byName = new Map(lits.map((l, i) => [l.name(keys.map((_, k) => k)), i])), at2 = found.length;
3149
- for (const ren of perms.filter(r => r.some((k, i) => k !== i)))
3150
- for (let i = 0; i < lits.length && found.length < at2 + 200; i++)
3151
- for (let j = i + 1; j < lits.length && found.length < at2 + 200; j++) {
3152
- const i2 = byName.get(lits[i].name(ren)), j2 = byName.get(lits[j].name(ren));
3153
- 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)))
3154
- continue;
3155
- const ls2 = [i, j, i2, j2], b2 = ls2.slice(1).reduce((b, l) => and(b, lits[l].bits), lits[i].bits);
3156
- 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))
3157
- continue;
3158
- const read = new Set(ls2.flatMap(l => lits[l].reads)), k2 = canon(ls2);
3159
- if (read.size === keys.length && !seen.has(k2)) {
3160
- seen.add(k2);
3161
- 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
+ }
3162
3826
  }
3163
- }
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)));
3164
3830
  }
3165
- known.set(vi, { R, lits: lits.map(l => l.lit) });
3166
- out.push(...found.map(ls => formOf(ls.map(l => lits[l].lit), vi)));
3167
3831
  }
3168
- 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;
3169
3834
  return env.GDP_POOL !== '0' ? dataFilter(made0) : made0;
3170
3835
  // The pool's data filter (DuoAI's junk killed by data before any solver call; research/protocols/engine/DESIGN.md,
3171
3836
  // gen/pool): each cube asked at every reachable state of larger instances, one more element of every sort and then
@@ -3181,7 +3846,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
3181
3846
  const t5 = vnow(), share = Math.min(Number(env.GDP_POOL_MS ?? 30_000), (eUntil - t5) / 3);
3182
3847
  const quiet = Number(env.GDP_POOL_QUIET ?? 150), least5 = Number(env.GDP_POOL_LEAST ?? 0), most5 = Number(env.GDP_POOL_STATES ?? 1_000);
3183
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);
3184
- 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)) : [])];
3185
3850
  let live = pool, states = 0;
3186
3851
  for (const [k, grow] of plans.entries()) {
3187
3852
  if (!live.length || stop())
@@ -3189,6 +3854,9 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
3189
3854
  const killed = new Set(), byView = new Map();
3190
3855
  for (const f of live)
3191
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)]));
3192
3860
  let read = 0, still = 0, lastKill = 0;
3193
3861
  const r = instance(grow, share, seeded(29 + k), most5, q => {
3194
3862
  if (read >= most5 || (read >= (k ? 0 : least5) && still >= quiet) || stop())
@@ -3201,12 +3869,16 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
3201
3869
  if (!alive.length)
3202
3870
  continue;
3203
3871
  const rows = withTable(q.params, () => views[vi].rowsOf(q.params, q.st, true));
3204
- 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;
3205
3877
  let near = 0;
3206
- for (const row of rows) {
3878
+ for (let ri = 0; ri < rows.length; ri++) {
3207
3879
  let off = 0;
3208
- for (const l of f.cube)
3209
- if (!litAt(l, row) && ++off > 1)
3880
+ for (const l of table.groups[fi])
3881
+ if (!holds(l, ri) && ++off > 1)
3210
3882
  break;
3211
3883
  if (off === 0) {
3212
3884
  killed.add(f);
@@ -3263,7 +3935,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
3263
3935
  // (a sums pass's reserve where one follows: 10 s, or a quarter of what is left where less is)
3264
3936
  const v0 = views.length, reserve = rule?.withMapSums() ? Math.min(10_000, (eUntil - vnow()) / 4) : 0;
3265
3937
  const implied = (f) => {
3266
- 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))];
3267
3939
  for (const l of given) {
3268
3940
  const b = [l.forall, ...(l.keys ?? [])].filter((q) => !!q);
3269
3941
  if (v.vars.length ** b.length > 64)
@@ -3287,7 +3959,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
3287
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
3288
3960
  // a kind, the fewer literals first (DuoAI's minimal clauses), then the cube over more distinct keys (the law its
3289
3961
  // diagonal case is a case of))
3290
- 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();
3291
3963
  const byMaps = new Map();
3292
3964
  const width2 = (f) => views[f.view].vars.length;
3293
3965
  for (const f of [...made].sort((a, b) => near(a) - near(b) || a.cube.length - b.cube.length || width2(b) - width2(a))) {
@@ -3301,14 +3973,17 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
3301
3973
  if (fs[i])
3302
3974
  turns.push(fs[i]);
3303
3975
  // (every cube of at most two literals first, DuoAI's minimal clauses, the turns' order kept within each part)
3304
- 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));
3305
3980
  // (round 0 the minimal cubes, at most 24, or the whole enumeration where it is 16 or fewer; the rest by relevance to
3306
3981
  // the counterexamples, IC3's order)
3307
3982
  const whole = made.length <= 16;
3308
3983
  for (const f of turns) {
3309
- if (cubes.length >= 24 || stop())
3984
+ if (cubes.length >= (relationalSupport ? 96 : 24) || stop())
3310
3985
  break;
3311
- 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))
3312
3987
  cubes.push(f);
3313
3988
  }
3314
3989
  opts.progress?.('join enumerated', { views: views.length - v0, cubes: cubes.length, ms: Math.round(vnow()) });
@@ -3344,7 +4019,10 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
3344
4019
  if (vnow() > eUntil)
3345
4020
  return false;
3346
4021
  try {
3347
- 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;
3348
4026
  stepNamed(st, post);
3349
4027
  }
3350
4028
  catch {
@@ -3455,6 +4133,8 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
3455
4133
  if (v.vars.length !== 1 || stop())
3456
4134
  continue;
3457
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;
3458
4138
  const As = [[], ...k.lits.filter(l => !keyed(l)).map(l => [l])], Bs0 = k.lits.filter(keyed);
3459
4139
  const off = (l) => !('at' in l) || l.at.value !== 0;
3460
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));
@@ -3603,13 +4283,17 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
3603
4283
  const nm = (i) => atoms[i].name.replace(tok, (_, c) => letters[ren[letters.indexOf(c)]]);
3604
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 };
3605
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));
3606
4288
  const entails = (b, a) => (a.at !== undefined ? b.at !== undefined && b.sum === a.sum && b.at === a.at
3607
- : 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);
3608
4290
  const sortsOf = (f) => viewSorts.get(f.view) ?? [];
3609
4291
  const maps2 = (sa, sb) => sa.reduce((acc, s2) => acc.flatMap(r => sb.flatMap((t2, j) => (t2 === s2 && !r.includes(j) ? [[...r, j]] : []))), [[]]);
3610
4292
  const own = new Map(pool.map(f => [f, litsOf(f, sortsOf(f).map((_, i) => i))]));
3611
- 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))); });
3612
- 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));
3613
4297
  const kept = [], by = new Map();
3614
4298
  for (const b of order)
3615
4299
  if (!kept.some(a => implies(a, b)))
@@ -3811,18 +4495,24 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
3811
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
3812
4496
  // counterexample ranked in its top eight, a cube the fast proof fails at dropped (the usual proof where it fails at
3813
4497
  // a cube the rounds proved), until the whole proves or the time is out)
3814
- if (!houdinied && !enumProof && vnow() > eUntil - 0.4 * (eUntil - engineStart)) {
3815
- 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;
3816
4504
  let hs = [...new Map([...cubes, ...pending, ...pool].filter(g => !dead.has(textOf(g)) && !atStart(g)).map(g => [textOf(g), g])).values()];
3817
4505
  for (let k = 0; k < 200 && hs.length && vnow() < eUntil && !stop(); k++) {
3818
4506
  const t2 = vnow(), hl = [...laws, ...hs.map(lawFor), ...(ghost ? [ghost.some] : [])];
3819
- 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));
3820
4510
  const at0 = String(v.goal ?? ''), g0 = v.proven && v.checked ? undefined : hs.find(c => at0.startsWith(`${textOf(c)} @`));
3821
4511
  // (or at a law the caller gave, a kind's: no cube to blame, so the usual proof's verdict)
3822
4512
  if (!(v.proven && v.checked) && (g0 ? at0.endsWith('@step') && stands.has(lawFor(g0).name) : true))
3823
- v = within(t0 + ms, () => prove(hl));
4513
+ v = within(hEnd, () => prove(hl));
3824
4514
  const at = String(v.goal ?? ''), g = v.proven && v.checked ? undefined : hs.find(c => at.startsWith(`${textOf(c)} @`));
3825
- 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) }) });
3826
4516
  if (v.proven && v.checked) {
3827
4517
  why = 'inductive';
3828
4518
  cone = hs;
@@ -3856,7 +4546,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
3856
4546
  for (let it = 0; it < 6; it++) {
3857
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;
3858
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 = [];
3859
- 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)));
3860
4550
  const add = (us) => { for (const u of us)
3861
4551
  if (!need.has(u)) {
3862
4552
  need.add(u);
@@ -3887,6 +4577,8 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
3887
4577
  }
3888
4578
  if (failed) {
3889
4579
  out2.add(failed);
4580
+ if (relationalSupport)
4581
+ real.add(failed);
3890
4582
  opts.progress?.('join cone', { round, it, failed: textOf(failed).slice(0, 100), need: need.size, ms: Math.round(vnow() - t1) });
3891
4583
  continue;
3892
4584
  }
@@ -3904,7 +4596,11 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
3904
4596
  }
3905
4597
  if (!g)
3906
4598
  return false;
4599
+ // The nominal-relation frontier drops its failed cone candidates.
4600
+ // Other engines may need them again after learning arithmetic support.
3907
4601
  out2.add(g);
4602
+ if (relationalSupport)
4603
+ real.add(g);
3908
4604
  }
3909
4605
  return false;
3910
4606
  };
@@ -3922,6 +4618,8 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
3922
4618
  over = true;
3923
4619
  return;
3924
4620
  }
4621
+ if (relationalSupport && real.size)
4622
+ break;
3925
4623
  }
3926
4624
  if (f)
3927
4625
  held = true;
@@ -3949,12 +4647,13 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
3949
4647
  stand(ls[idx].name);
3950
4648
  continue;
3951
4649
  }
3952
- 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;
3953
4652
  if (f && isReal && dl.goal.endsWith('@start'))
3954
4653
  startReal.add(f);
3955
4654
  // (a cube the EPR path ran out of time on: unsure at once, kept as optimistic Houdini keeps it; the CDCL search
3956
4655
  // after it would be no quicker)
3957
- if (!dl && !(f && outOfTime)) {
4656
+ if (!dl && !hint && !(f && outOfTime)) {
3958
4657
  const inst = mapNames.length ? lawInstances(mm, ls, idx) : undefined, g = obligations(mm, ls, inst ? { [ls[idx].name]: inst } : {}, idx)[1];
3959
4658
  // (the engine's wall too: a counted budget alone runs on past it, wo's 6 s)
3960
4659
  // (its share on the wall too: a counted budget of 2 s ran 8.8 s on wo's 3-key cubes)
@@ -4056,6 +4755,8 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
4056
4755
  }
4057
4756
  }
4058
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(' | ') });
4059
4760
  // (optimistic Houdini: an unsure cube holds at every small state and every step from one (they are its rows), so
4060
4761
  // it stays; the set's proof decides, a cube it fails at dropped and the rounds go on)
4061
4762
  // (IC3's push: the pending cubes asked together, each with the set and every other pending one assumed (one frame),
@@ -4200,7 +4901,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
4200
4901
  }
4201
4902
  for (;;) {
4202
4903
  // (`join` 0: no round, the engine's alone)
4203
- if (now() > jUntil || opts.join === 0 || stop()) {
4904
+ if (now() > jUntil || noJoin || stop()) {
4204
4905
  why = 'time';
4205
4906
  break;
4206
4907
  }
@@ -4461,7 +5162,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
4461
5162
  pool = pool0;
4462
5163
  ctis.length = ctis0;
4463
5164
  chosen = [];
4464
- opts.progress?.('join failed', { why: String(e.message).slice(0, 120) });
5165
+ opts.progress?.('join failed', { why: String(e.stack).slice(0, 1500) });
4465
5166
  }
4466
5167
  // The search proves one law at a time (proveLaw), each with every law assumed, and keeps what it proved while laws
4467
5168
  // are only added (more laws assumed keep a proof a proof); dropping one forgets it all. Once every law is proven so,