gdp-wired 0.25.0 → 0.26.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 (50) hide show
  1. package/README.md +14 -9
  2. package/dist/core/accel.d.ts +1 -1
  3. package/dist/core/accel.js +336 -101
  4. package/dist/core/bmc.d.ts +8 -0
  5. package/dist/core/bmc.js +263 -97
  6. package/dist/core/cycles.d.ts +2 -3
  7. package/dist/core/cycles.js +35 -131
  8. package/dist/core/cyclic.d.ts +4 -1
  9. package/dist/core/cyclic.js +86 -64
  10. package/dist/core/data.d.ts +1 -1
  11. package/dist/core/data.js +89 -118
  12. package/dist/core/discover.js +2 -3
  13. package/dist/core/dsl.d.ts +3 -2
  14. package/dist/core/dsl.js +21 -18
  15. package/dist/core/exists.js +7 -14
  16. package/dist/core/extract-check.d.ts +3 -2
  17. package/dist/core/extract-check.js +137 -50
  18. package/dist/core/extract-print.d.ts +1 -0
  19. package/dist/core/extract-print.js +26 -3
  20. package/dist/core/extract-read.d.ts +85 -4
  21. package/dist/core/extract-read.js +295 -34
  22. package/dist/core/extract-shapes.d.ts +14 -0
  23. package/dist/core/extract-shapes.js +608 -78
  24. package/dist/core/extract-xstate.d.ts +5 -1
  25. package/dist/core/extract-xstate.js +618 -184
  26. package/dist/core/extract.js +73 -27
  27. package/dist/core/infer.js +72 -18
  28. package/dist/core/machine.d.ts +6 -0
  29. package/dist/core/machine.js +35 -3
  30. package/dist/core/nonterm.d.ts +5 -1
  31. package/dist/core/nonterm.js +109 -41
  32. package/dist/core/q.d.ts +1 -0
  33. package/dist/core/q.js +2 -2
  34. package/dist/core/relation.d.ts +1 -0
  35. package/dist/core/relation.js +20 -36
  36. package/dist/core/solver.d.ts +12 -0
  37. package/dist/core/solver.js +76 -30
  38. package/dist/core/transfer.js +22 -13
  39. package/dist/core/translate.d.ts +1 -1
  40. package/dist/core/translate.js +22 -49
  41. package/dist/core/xstate.d.ts +6 -1
  42. package/dist/core/xstate.js +336 -55
  43. package/dist/kernel/cdcl.js +1 -2
  44. package/dist/kernel/prove.d.ts +6 -1
  45. package/dist/kernel/prove.js +96 -82
  46. package/dist/kernel/reader.d.ts +1 -0
  47. package/dist/kernel/reader.js +4 -3
  48. package/dist/kernel/simplex.d.ts +1 -1
  49. package/dist/kernel/simplex.js +13 -1
  50. package/package.json +3 -2
@@ -1,6 +1,7 @@
1
1
  // Rules read from the code that ships (`gdp-wired/extract`): `extract(code, {entry})` reads a TypeScript or JavaScript
2
- // step function (a reducer `(state, action) => state`, `useReducer`'s, functions over one record) or a class whose
3
- // methods write its fields (a rate limiter's `tryRemove(n)`, a wallet's `debit(x)`), and returns the rule that steps the
2
+ // step function (a reducer `(state, action) => state`, `useReducer`'s, functions over one record), a class whose
3
+ // methods write its fields (a rate limiter's `tryRemove(n)`, a wallet's `debit(x)`), with the classes it extends, or
4
+ // the object of functions a factory returns (its state what they close over), and returns the rule that steps the
4
5
  // same way, as a builder value and as the source that makes it (`toSource`), for a user to read and keep:
5
6
  //
6
7
  // const x = extract(readFileSync('bucket.ts', 'utf8'), {file: 'bucket.ts', entry: 'TokenBucket'})
@@ -10,26 +11,34 @@
10
11
  //
11
12
  // The extractor is untrusted. The rule is checked against the original code by running both (core/extract-check.ts):
12
13
  // requests from the start, steps from drawn states, and steps from the prover's counterexamples, every state, map cell,
13
- // result and refusal compared, and the code's branches counted. Any difference refuses the extraction with the
14
+ // list, result and refusal compared, and the code's branches counted. Any difference refuses the extraction with the
14
15
  // difference; nothing is adopted that the check didn't run. What the subset doesn't read is refused where it is, with
15
16
  // the reason, never approximated. XState machines go through `fromXState` (core/xstate.ts), their guards and actions
16
- // read the same way (`extractXState`).
17
+ // read the same way (`extractXState`, a machine or a function that makes one, its actors, timers and eventless
18
+ // transitions included).
17
19
  //
18
20
  // The subset: numbers (integers: a literal that isn't one is refused; division only as Math.floor or Math.ceil of
19
- // x / k for a constant k; % by a constant of a natural), booleans, string-literal unions, records and nested records
20
- // (spreads, shorthand), Map and Record state keyed by numbers or strings (get, set, has, delete, [k], ?? a default),
21
- // conditionals, ternaries, && || ?? (their right side's effects on its own path), early returns, switch on a tag
22
- // (fall-through, default), Math.min, Math.max, Math.abs, Date.now() (an input; once a step), throws (the rule's
23
- // refusals: its assumption, or its precondition for a constructor), helper functions and methods of the same file
24
- // (inlined), getters. Refused: loops, arrays, strings beyond keys and literals, floats, async, try/catch, writes to the
25
- // state a reducer is given, a throw after a method wrote a field, two keys of one map written in one step, a map
26
- // replaced whole, a reference into a map held across a set, aliasing that depends on the path, other modules' code.
21
+ // x / k for a constant k, a fraction being a binary float the code rounds; % by a constant of a natural), booleans,
22
+ // string-literal unions, strings (set, compared, truthy where not empty), null and undefined where a value may be
23
+ // missing, records and nested records (spreads, shorthand), Map and Record state keyed by numbers or strings (get,
24
+ // set, has, delete, [k], ?? a default; a Map given to a constructor starts empty), arrays of numbers, booleans and
25
+ // string unions as lists (length, [i], push, pop, [i] = x within the array, [...xs], [...xs, x]), Dates as their time
26
+ // (new Date(), getTime(), setTime() where the Date is held), conditionals, ternaries, && || ?? (their right side's
27
+ // effects on its own path), early returns, switch on a tag (fall-through, default), Math.min, Math.max, Math.abs,
28
+ // Boolean(x), Date.now() (an input; once a step), throws (the rule's refusals: its assumption, or its precondition
29
+ // for a constructor), helper functions and methods of the same files (inlined), getters, single inheritance (each
30
+ // member resolved statically: this.m() the nearest the object has, super.m() the nearest above the class it is in),
31
+ // results kept (a value, a record of values, a value that may be missing). Refused: loops, strings beyond keys and
32
+ // literals, floats, async, try/catch, writes to the state a reducer is given, a throw after a method wrote a field, two
33
+ // keys of one map or two writes of one list in one step, a map or a list replaced whole, a reference into a map held
34
+ // across a set, one object (an array, a Map, a Date) in two places, aliasing that depends on the path, mixins, other
35
+ // modules' code.
27
36
  import * as dsl from "./dsl.js";
28
- import { compileFunction } from "./machine.js";
37
+ import { compileFunction, walk } from "./machine.js";
29
38
  import * as I from "./extract-ir.js";
30
39
  import { Refusal } from "./extract-read.js";
31
- import { isSlice, readClass, readFunctions, readSlice } from "./extract-shapes.js";
32
- import { kindOf, mapEmpty, mapKind, natOK, pb, pk, pterm, sortsOf } from "./extract-print.js";
40
+ import { isFactory, isSlice, readClass, readFactory, readFunctions, readSlice } from "./extract-shapes.js";
41
+ import { kindOf, mapEmpty, mapKind, natOK, pb, pidx, pk, pterm, sortsOf } from "./extract-print.js";
33
42
  import { check } from "./extract-check.js";
34
43
  export function extract(code, opts) {
35
44
  const file = opts.file ?? 'input.ts', notes = [];
@@ -38,7 +47,7 @@ export function extract(code, opts) {
38
47
  const isClass = opts.shape ? opts.shape === 'class' : new RegExp(`\\bclass\\s+${opts.entry}\\b|\\b${opts.entry}\\s*=\\s*class\\b`).test(code);
39
48
  // The file sits in the working directory, so its imports (xstate, say) resolve as the project's do.
40
49
  const cwd = globalThis.process?.cwd?.() ?? '.', at = `${cwd}/${file}`;
41
- model = isClass ? readClass(code, at, opts) : isSlice(code, opts.entry) ? readSlice(code, at, opts) : readFunctions(code, at, opts);
50
+ model = isClass ? readClass(code, at, opts) : isSlice(code, opts.entry) ? readSlice(code, at, opts) : isFactory(code, file, opts.entry) ? readFactory(code, at, opts) : readFunctions(code, at, opts);
42
51
  model.file = file;
43
52
  }
44
53
  catch (e) {
@@ -50,6 +59,7 @@ export function extract(code, opts) {
50
59
  try {
51
60
  const s = sortsOf(model, opts.domains);
52
61
  sorts = s.sorts;
62
+ datesInRange(model, sorts);
53
63
  notes.push(...model.notes, ...s.notes);
54
64
  body = builderOf(model, sorts);
55
65
  source = moduleOf(model, body, file);
@@ -74,6 +84,34 @@ export function extract(code, opts) {
74
84
  return { ok: false, source, model, sorts, evidence, refusals: [{ where: file, what: `the rule and the code differ: ${evidence.mismatch}` }], notes };
75
85
  return { ok: true, rule, ...(invariants.length ? { invariants } : {}), source, model, sorts, evidence, refusals: [], notes };
76
86
  }
87
+ // A Date holds a time within ±8.64e15 ms; past it the code's Date is invalid (NaN). The rule refuses a step that would
88
+ // set one there (as it refuses a sum past 2^53), and a start there: its claim stops at the Date's range.
89
+ const DATE_MAX = 8_640_000_000_000_000;
90
+ function datesInRange(m, sorts) {
91
+ const out = (e, at) => (sorts.get(at) === 'nat' ? I.cmp('<', I.num(DATE_MAX), e) : I.or(I.cmp('<', I.num(DATE_MAX), e), I.cmp('<', e, I.num(-DATE_MAX))));
92
+ const dated = m.state.filter(v => v.sort.k === 'num' && v.sort.date);
93
+ const over = [];
94
+ for (const v of dated) {
95
+ const w = m.writes[v.name];
96
+ if (w?.s === 'num')
97
+ over.push(out(w.e, v.name));
98
+ }
99
+ for (const d of m.maps)
100
+ for (const f of d.fields)
101
+ if (f.sort.k === 'num' && f.sort.date) {
102
+ const w = m.mapWrites[d.name];
103
+ const t = w?.vals[f.name];
104
+ if (t?.s === 'num')
105
+ over.push(I.and(w.has, out(t.e, `${d.name}.${f.name}`)));
106
+ }
107
+ if (over.length)
108
+ m.refuse = I.or(m.refuse, ...over);
109
+ const starts = dated.filter(v => m.init[v.name]?.s === 'num').map(v => I.not(out(m.init[v.name].e, v.name)));
110
+ if (starts.length)
111
+ m.pre = I.and(m.pre, ...starts);
112
+ if (over.length || starts.length)
113
+ m.notes.push('a Date holds a time within ±8.64e15 ms: a step that would set one past it is refused (the code\'s Date would be invalid)');
114
+ }
77
115
  // The module a user keeps: the rule, with what it was read from and how it was checked.
78
116
  export const toSource = (x) => x.source ?? '';
79
117
  // The source is the rule: it is evaluated with the builders, so what is checked is what is printed.
@@ -88,7 +126,8 @@ function evaluate(body) {
88
126
  function invariantsOf(m, sorts) {
89
127
  const empty = (d, f) => (f.sort.k === 'num' ? `.eq(0)` : f.sort.k === 'bool' ? `.not()` : f.sort.k === 'choice' ? `.is(${JSON.stringify(f.sort.values[0])})` : `.eq('')`);
90
128
  void sorts;
91
- return m.maps.map(d => `r.law(${JSON.stringify(`${d.name}: a key it doesn't hold holds the defaults`)}, ({${d.name}}) => forall(k => any(${d.name}.at(k).has, all(${d.fields.map(f => `${d.name}.at(k).${f.name}${empty(d, f)}`).join(', ')}))))`);
129
+ return [...m.maps.map(d => `r.law(${JSON.stringify(`${d.name}: a key it doesn't hold holds the defaults`)}, ({${d.name}}) => forall(k => any(${d.name}.at(k).has, all(${d.fields.map(f => `${d.name}.at(k).${f.name}${empty(d, f)}`).join(', ')}))))`),
130
+ ...(m.lists ?? []).map(d => `r.law(${JSON.stringify(`${d.name}: nothing past its end`)}, ({${d.name}}) => ${d.name}.within())`)];
92
131
  }
93
132
  function evaluateLaws(r, xs) {
94
133
  if (!xs.length)
@@ -101,7 +140,7 @@ function moduleOf(m, body, file) {
101
140
  const used = NAMES.filter(n => new RegExp(`(^|[^.\\w$])${n}\\(|(^|[^.\\w$])${n}\\b(?!\\s*:)`).test(body.replace(/'[^']*'/g, "''")) || (n === 'rule'));
102
141
  const ident = identOf(m);
103
142
  return [
104
- `// Extracted by gdp-wired/extract from ${file} (${m.entry}, ${m.shape === 'class' ? 'a class' : m.shape === 'reducer' ? 'a step function' : 'functions over one record'}).`,
143
+ `// Extracted by gdp-wired/extract from ${file} (${m.entry}, ${m.factory ? 'a factory of an object of functions' : m.shape === 'class' ? 'a class' : m.shape === 'reducer' ? 'a step function' : 'functions over one record'}).`,
105
144
  `// Checked against the code it was read from; read again with extract() after the code changes.`,
106
145
  `import {${[...new Set([...used, ...(m.maps.length ? ['all', 'any', 'forall'] : [])])].sort((a, b) => a.localeCompare(b)).join(', ')}} from 'gdp-wired'`,
107
146
  '',
@@ -139,6 +178,8 @@ function builderOf(m, sorts) {
139
178
  lines.push(` .state({${m.state.map(v => `${v.name}: ${start(v)}`).join(', ')}})`);
140
179
  if (m.maps.length)
141
180
  lines.push(` .maps({${m.maps.map((d) => `${d.name}: ${mapKind(d, sorts)}.from(${mapEmpty(d)})`).join(', ')}})`);
181
+ if (m.lists?.length)
182
+ lines.push(` .items({${m.lists.map(d => `${d.name}: ${kindOf(d.fields[0], sorts, `${d.name}.$item`)}`).join(', ')}})`);
142
183
  const envOf = (...xs) => {
143
184
  const vars = new Set(), maps = new Set();
144
185
  for (const x of xs)
@@ -172,9 +213,19 @@ function builderOf(m, sorts) {
172
213
  const vals = d.fields.map(f => `${f.name}: ${pterm(w.vals[f.name], P, { m, sorts, atoms: [w.has] }, `${n}.${f.name}`)}`);
173
214
  outs.push([n, `${n}.set(${pk(w.key, P, ctx())}, {has: ${pb(w.has, P, ctx())}, ${vals.join(', ')}})`]);
174
215
  }
216
+ // A list's write: its apply over the operations by cases (each under its condition).
217
+ const lw = Object.entries(m.listWrites ?? {});
218
+ for (const [n, ops] of lw) {
219
+ const one = (o) => {
220
+ const at = { m, sorts, atoms: [o.when] }, when = pb(o.when, P, ctx());
221
+ return o.op === 'push' ? `${n}.push(${pterm(o.x, P, at, `${n}.$item`)}, ${when})` : o.op === 'pop' ? `${n}.pop(${when})` : `${n}.set(when(${when}, ${pidx(o.i, P, at)}, 0), ${pterm(o.x, P, at, `${n}.$item`)}, ${when})`;
222
+ };
223
+ outs.push([`...${n}`, `${n}.apply(${ops.map(one).join(', ')})`]);
224
+ }
175
225
  const all = [...defs, ...outs.map(([, x]) => x)].join('\n');
176
- const env = withChoices(envOf(...writes.map(([, t]) => t.e), ...mw.flatMap(([, w]) => [w.has, w.key, ...Object.values(w.vals).map(t => t.e)])), all, P, mw.map(([n]) => n));
177
- const ret = `{${outs.map(([n, x]) => `${n}: ${x}`).join(', ')}}`;
226
+ const lterms = lw.flatMap(([, ops]) => ops.flatMap(o => [o.when, ...(o.op === 'pop' ? [] : [o.x.e]), ...(o.op === 'set' ? [o.i] : [])]));
227
+ const env = withChoices(envOf(...writes.map(([, t]) => t.e), ...mw.flatMap(([, w]) => [w.has, w.key, ...Object.values(w.vals).map(t => t.e)]), ...lterms), all, P, [...mw.map(([n]) => n), ...lw.map(([n]) => n)]);
228
+ const ret = `{${outs.map(([n, x]) => (n.startsWith('...') ? `...${x}` : `${n}: ${x}`)).join(', ')}}`;
178
229
  lines.push(defs.length ? ` .step((${env}) => {\n${defs.map(d => ` ${d}`).join('\n')}\n return ${ret}\n })` : ` .step((${env}) => (${ret}))`);
179
230
  return lines.join('\n');
180
231
  }
@@ -227,13 +278,8 @@ function hoist(m, P, roots) {
227
278
  if (!isBool(node)) {
228
279
  const ctx = { m, sorts: P.sorts, atoms: [] }, free = natOK(node, ctx);
229
280
  const cells = [];
230
- const walk = (x) => { if (x && typeof x === 'object') {
231
- const o = x;
232
- if (o.op === 'cell')
233
- cells.push(`${o.map}.${o.field}`);
234
- Object.values(o).forEach(walk);
235
- } };
236
- walk(node);
281
+ walk(node, o => { if (o.op === 'cell')
282
+ cells.push(`${o.map}.${o.field}`); });
237
283
  const hasInt = [...I.varsOf(node).vars].some(n => P.sorts.get(n) === 'int') || cells.some(c => P.sorts.get(c) === 'int');
238
284
  if (!free && !hasInt)
239
285
  continue;
@@ -24,12 +24,13 @@
24
24
  // 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
25
25
  // is the answer, after each chosen candidate the proof doesn't need is taken out again
26
26
  import { quietly } from "./cyclic.js";
27
- import { all, any, atMost, divisorsIn, evalC, get, interpret, machineTerms, modName, n, not, plus, same, times, withArithmetic, x } from "./machine.js";
28
- import { proveRule, proveSteps } from "./dsl.js";
27
+ import { all, any, atMost, divisorsIn, evalC, get, interpret, machineTerms, modName, n, not, plus, same, seeded, times, withArithmetic, x } from "./machine.js";
28
+ import { proveRule, proveSteps, verdictOf } from "./dsl.js";
29
29
  import { allowed, watch } from "./watch.js";
30
- import { clock, counted, grow, proveLaw, proveLaws, proveStepLaws, usedHyps, withDeadline } from "../kernel/prove.js";
30
+ import { clock, counted, grow, proveLaw, proveLaws, proveStepLaws, usedHyps, withDeadline, withTrees } from "../kernel/prove.js";
31
31
  import { obligations, substC } from "../kernel/kernel.js";
32
- import { work } from "./solver.js";
32
+ import { env, gcd, work } from "./solver.js";
33
+ import { bgcd } from "./q.js";
33
34
  import { REFUTED, growCdcl } from "../kernel/cdcl.js";
34
35
  const KEY = 'key$found', AT = '@', K = '#', SOME = 'k$found';
35
36
  // The counted clock's rates, units a millisecond: about the slowest tenth of what Modal's 1-vCPU containers do in each
@@ -42,32 +43,35 @@ const KEY = 'key$found', AT = '@', K = '#', SOME = 'k$found';
42
43
  export const inferRates = { tries: 100, rows: 10_000, evals: 10_000, watched: 100, work: 40 };
43
44
  export const inferRuns = 16_000;
44
45
  // GDP_INFER_TRACE=1: each phase's wall time beside what it counted, to stderr (the calibration's numbers).
45
- const inferTrace = !!globalThis.process?.env?.GDP_INFER_TRACE;
46
+ const inferTrace = !!env.GDP_INFER_TRACE;
46
47
  // The join (below, after the candidates): GDP_JOIN=0 turns it off, for comparing. Its share of what is left of the
47
48
  // search's budget; each kernel search's budget (counted, or wall time where timed), a request's 150 ms; the steps a walk
48
49
  // from a joined state takes; pairs of values as directions up to 10 values; a bound raised twice at most, then dropped;
49
50
  // equalities of at most 4 values, coefficients up to 1,000; at most 24 candidates beside the hull, 40 tried; yes/nos in
50
51
  // the control state up to 7, and 128 of its values; a goal tried with 6 parts of the set before all of it, 2 forms added
51
52
  // at a time.
52
- const joinOn = globalThis.process?.env?.GDP_JOIN !== '0';
53
+ const joinOn = env.GDP_JOIN !== '0';
53
54
  const joinShare = 0.6, joinQueryMs = 8000, joinRequestMs = 150, joinWalk = 8, joinPairs = 10, joinRaises = 2, joinSparse = 4, joinCoef = 1000;
54
55
  const joinExtras = 24, joinTries = 40, joinBits = 7, joinKeys = 128, joinAttempts = 6, joinAdd = 2;
55
56
  // GDP_JOIN_CORE=0: the join's goals by the prover's trees alone, as before (else a model, or a refutation's core, of the
56
57
  // CDCL search first, at a quarter of the goal's budget).
57
58
  // GDP_JOIN_NEVERS=0: each control state no run reached a form of its own, as before (else one form for all of them,
58
59
  // until it is first broken).
59
- const joinNevers = globalThis.process?.env?.GDP_JOIN_NEVERS !== '0';
60
+ const joinNevers = env.GDP_JOIN_NEVERS !== '0';
60
61
  const joinNeversBreaks = 1;
61
- const joinCore = globalThis.process?.env?.GDP_JOIN_CORE !== '0';
62
+ const joinCore = env.GDP_JOIN_CORE !== '0';
62
63
  // Cubes blocked where no candidate rules a counterexample out (GDP_JOIN_CUBES=0: none): at most 48 in all, each tried 8
63
64
  // times, its predecessors blocked first 3 deep, each query's budget 2 s (counted, or wall time where timed).
64
- const joinCubes = globalThis.process?.env?.GDP_JOIN_CUBES !== '0';
65
+ const joinCubes = env.GDP_JOIN_CUBES !== '0';
65
66
  const joinCubeMax = 48, joinCubeTries = 8, joinCubeDepth = 3, joinCubeMs = 2000;
66
67
  // Once a cube is in the set, the join has 0.3 of what is left of its time (the search below the rest).
67
68
  const joinCubeWindow = 0.3;
68
- const seeded = (seed) => { let s = seed; return k => { s = (s * 1103515245 + 12345) % 2 ** 31; return Math.floor(s / 2 ** 31 * k); }; };
69
+ // GDP_JOIN_PRIME=0: each control state no state reached a form of its own, every value read.
70
+ const joinPrime = env.GDP_JOIN_PRIME !== '0';
71
+ // GDP_JOIN_DOWN=0: a blocked cube kept as its refutation's core cuts it (no literal dropped); joinDownQueries, the
72
+ // queries a cube's generalization may ask.
73
+ const joinDown = env.GDP_JOIN_DOWN !== '0', joinDownQueries = 24;
69
74
  const isRule = (t) => typeof t.kindsOfState === 'function';
70
- const gcd = (a, b) => (b === 0 ? Math.abs(a) : gcd(b, a % b));
71
75
  // The constants a machine's expressions hold, and the factors it multiplies by.
72
76
  function constantsOf(m, laws) {
73
77
  const out = new Set();
@@ -243,7 +247,7 @@ function comparisons(m, laws, atoms, coords) {
243
247
  return [...found.values()];
244
248
  }
245
249
  export function inferLaws(target, laws, stepLaws = [], opts = {}) {
246
- return quietly(() => withDeadline(performance.now() + (opts.ms ?? 20000), () => inferLawsSearch(target, laws, stepLaws, opts)));
250
+ return quietly(() => withDeadline(clock() + (opts.ms ?? 20000), () => inferLawsSearch(target, laws, stepLaws, opts)));
247
251
  }
248
252
  function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
249
253
  const t0 = performance.now(), ms = opts.ms ?? 20000, wallUntil = t0 + ms, rule = isRule(target) ? target : undefined;
@@ -291,7 +295,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
291
295
  if (searchRule)
292
296
  return stepLaws.length ? proveSteps(searchRule, ls, stepLaws, { search: false }) : proveRule(searchRule, ls, { search: false });
293
297
  const out = stepLaws.length ? proveStepLaws(mm, ls, stepLaws) : proveLaws(mm, ls);
294
- return { proven: out.proven, checked: out.checked, ...(out.failed ? { goal: out.failed.goal, stuck: out.failed.stuck, ...(out.failed.witness ? { witness: out.failed.witness } : {}), ...(out.failed.why ? { why: out.failed.why } : {}) } : {}) };
298
+ return verdictOf(out);
295
299
  };
296
300
  const stats = (samples, candidates, alive) => ({ samples, candidates, alive, proofs, ms: Math.round(performance.now() - t0), stopped: stop() });
297
301
  const first = opts.first ?? prove(laws);
@@ -974,8 +978,6 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
974
978
  // products the first time, the constants alone after), and past that it is dropped.
975
979
  const fine = bounds, coarse = [...new Set([0, ...consts.flatMap(k => [k, -k])])].sort((p2, q2) => p2 - q2);
976
980
  const groups = new Map();
977
- const bgcd = (a2, b2) => { a2 = a2 < 0n ? -a2 : a2; b2 = b2 < 0n ? -b2 : b2; while (b2)
978
- [a2, b2] = [b2, a2 % b2]; return a2; };
979
981
  const normal = (e) => { let g2 = 0n; for (const x2 of e)
980
982
  g2 = bgcd(g2, x2); if (g2 > 1n)
981
983
  for (let k = 0; k < e.length; k++)
@@ -1072,10 +1074,33 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1072
1074
  if (nev.length > 1 && joinNevers && neversBroken < joinNeversBreaks)
1073
1075
  push({ coef: [], d: 0, cells: false, nevers: nev, size: 1 });
1074
1076
  else
1075
- for (const ats of nev)
1077
+ for (const ats of joinPrime ? primes(nev) : nev)
1076
1078
  push({ coef: [], d: 0, cells: false, ...(ats.length > 1 ? { never: ats } : { unreachable: ats[0] }), size: 1 });
1077
1079
  return out;
1078
1080
  };
1081
+ // The control states no state reached, as fewer and smaller cubes (a program counter in bits: Spacer's clauses there
1082
+ // read two or three of its bits): each cube's values dropped one at a time, the yes/nos first, while it holds at no
1083
+ // control state reached, then the cubes another cube's values include left out. Together they say what the cubes
1084
+ // of every value say (the control state is one reached), but a goal reads fewer of them, and each of them less.
1085
+ const primes = (nev) => {
1086
+ const reachedKeys = [...groups.keys()].map(k2 => k2.split(',').map(Number));
1087
+ const holdsAtSome = (c) => reachedKeys.some(vs => c.every(a => vs[keyAtoms.indexOf(a.atom)] === a.value));
1088
+ const out = [];
1089
+ for (const ats of nev) {
1090
+ let c = ats;
1091
+ for (const a of [...ats.slice(1), ats[0]]) {
1092
+ if (c.length <= 1)
1093
+ break;
1094
+ const fewer = c.filter(b2 => b2 !== a);
1095
+ if (!holdsAtSome(fewer))
1096
+ c = fewer;
1097
+ }
1098
+ out.push(c);
1099
+ }
1100
+ const key2 = (c) => c.map(a => `${a.atom}=${a.value}`).sort().join('&');
1101
+ const uniq = [...new Map(out.map(c => [key2(c), c])).values()].sort((a, b) => a.length - b.length);
1102
+ return uniq.filter((c, i) => !uniq.slice(0, i).some(d => d.every(a => c.some(b2 => b2.atom === a.atom && b2.value === a.value))));
1103
+ };
1079
1104
  let rounds = 0, why = '', set = [];
1080
1105
  const params0 = {};
1081
1106
  // Beside the hull, forms of the candidates' that rule out a counterexample to the caller's laws (a state the set
@@ -1303,6 +1328,33 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1303
1328
  // cube made smaller to leave the predecessor's successor out. Each cube blocked is a form of the set (a
1304
1329
  // disjunction: never all its literals), which the join keeps or drops as any other.
1305
1330
  let cubed = 0, cubeWhy = '', cubeUntil = Infinity;
1331
+ // IC3's generalization of a cube blocked (Bradley's down, literal dropping as Een, Mishchenko and Brayton's): the
1332
+ // literals taken out a part at a time (half of them, then quarters, ..., then one by one), a part kept out where the
1333
+ // cube without it still leaves the start and the samples out and is still blocked relative to the same laws (the
1334
+ // refutation's core then cutting it further); within joinDownQueries queries. A cube's core reads most of its
1335
+ // literals where the step's terms are a chain of ifs (research/dag: a refutation's core is nearly its whole path), so
1336
+ // the core alone leaves a cube of every control value; Spacer's clauses on these tasks read two to four.
1337
+ const down = (c, frame) => {
1338
+ let cur = c, queries = 0;
1339
+ for (let part = Math.ceil(cur.length / 2); part >= 1 && queries < joinDownQueries && now() < jUntil && !stop(); part = part === 1 ? 0 : Math.ceil(part / 2)) {
1340
+ for (let i = 0; i < cur.length && cur.length > 1 && queries < joinDownQueries && now() < jUntil && !stop();) {
1341
+ const cand = [...cur.slice(0, i), ...cur.slice(i + part)];
1342
+ if (!cand.length || (initVec && inCube(cand, initVec)) || S.some(s2 => inCube(cand, s2))) {
1343
+ i += part;
1344
+ continue;
1345
+ }
1346
+ queries++;
1347
+ const r = queryWith(cand, frame);
1348
+ if (!r?.ok) {
1349
+ i += part;
1350
+ continue;
1351
+ }
1352
+ const cut = cand.filter((_, j) => r.core.has(j));
1353
+ cur = cut.length && !(initVec && inCube(cut, initVec)) && !S.some(s2 => inCube(cut, s2)) ? cut : cand;
1354
+ }
1355
+ }
1356
+ return cur;
1357
+ };
1306
1358
  const blockCube = (v, depth, within) => {
1307
1359
  let c = cubeOf(v);
1308
1360
  const made = [];
@@ -1324,7 +1376,8 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1324
1376
  if (l)
1325
1377
  c2.push(l);
1326
1378
  }
1327
- made.push(formOf(outOfSamples(c2, c) ? c2 : c));
1379
+ const c3 = outOfSamples(c2, c) ? c2 : c;
1380
+ made.push(formOf(joinDown ? down(c3, [...ctx, ...made].map(lawFor).filter(l => l.name !== textOf(formOf(c3)))) : c3));
1328
1381
  break;
1329
1382
  }
1330
1383
  if (!r.post) {
@@ -1605,7 +1658,8 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1605
1658
  };
1606
1659
  for (let iter = 0; iter < 300 && now() < until && !stop(); iter++) {
1607
1660
  const began = now(), wall = performance.now();
1608
- last = search([...given, ...chosen.map(lawFor)]);
1661
+ // (each law proven alone, then the set as a whole: the same goals, grown once)
1662
+ last = withTrees(() => search([...given, ...chosen.map(lawFor)]));
1609
1663
  const took = now() - began;
1610
1664
  opts.progress?.('proof', { chosen: chosen.length, goal: last.goal ?? '', stuck: last.stuck ?? '', ms: Math.round(performance.now() - wall), counted: Math.round(took) });
1611
1665
  if (last.proven && last.checked)
@@ -1,4 +1,8 @@
1
1
  import { type Constraint, type Verdict } from './solver.js';
2
+ export type Rand = (k: number) => number;
3
+ export declare const seeded: (seed: number) => Rand;
4
+ export declare const walk: (t: unknown, f: (o: Record<string, unknown>) => void) => void;
5
+ export declare const walkOnce: (t: unknown, f: (o: object) => void) => void;
2
6
  export type E = {
3
7
  op: 'var';
4
8
  name: string;
@@ -192,6 +196,8 @@ export type Request = Record<string, number | ReadonlyMap<number, number>>;
192
196
  export declare const naturalIn: (v: unknown, what: string) => number;
193
197
  export declare function evalE(e: E, env: Env, st: State, m: Machine): number;
194
198
  export declare const fnValue: (fn: Fn, key: number) => number;
199
+ export declare const pairE: (a: E, b: E) => E;
200
+ export declare const argsKey: (args: E[]) => E;
195
201
  export declare function pairedArgs(key: E, n: number): E[] | undefined;
196
202
  export declare function evalC(c: C, env: Env, st: State, m: Machine): boolean;
197
203
  export declare function carriedView(m: Machine, st: State, input: Request, rename?: (map: string) => string): State;
@@ -7,7 +7,36 @@
7
7
  // at the same value; a law about a map holds for every key x, and is proven at one arbitrary x (with the law assumed at
8
8
  // every other key the step reads).
9
9
  import { boundOf, crossFree, historyMachine, keyTerm, plainKey, scope } from "../kernel/kernel.js";
10
- import { add, eq, k, le, lt, nat, scale, show, solve, sub, v } from "./solver.js";
10
+ import { add, env, eq, k, le, lt, nat, scale, show, solve, sub, v } from "./solver.js";
11
+ export const seeded = (seed) => { let x = seed; return k => { x = (x * 1103515245 + 12345) % 2 ** 31; return Math.floor(x / 2 ** 31 * k); }; };
12
+ // Every object in a term, the term first.
13
+ export const walk = (t, f) => {
14
+ if (Array.isArray(t)) {
15
+ for (const x of t)
16
+ walk(x, f);
17
+ return;
18
+ }
19
+ if (!t || typeof t !== 'object')
20
+ return;
21
+ const o = t;
22
+ f(o);
23
+ for (const x of Object.values(o))
24
+ walk(x, f);
25
+ };
26
+ // Every object in a term once (arrays too), a part shared by several uses read at its first: a witness read at each of
27
+ // its uses in a goal is one object, and a walk of the goal written out would read it at each.
28
+ export const walkOnce = (t, f) => {
29
+ const seen = new Set();
30
+ const go = (x) => {
31
+ if (!x || typeof x !== 'object' || seen.has(x))
32
+ return;
33
+ seen.add(x);
34
+ f(x);
35
+ for (const y of Object.values(x))
36
+ go(y);
37
+ };
38
+ go(t);
39
+ };
11
40
  // A write at one key, for the parts that take no write at every key (the symbolic prover, the GPU synthesizers, the
12
41
  // hand-written shader, the first Lean export): they refuse one by name.
13
42
  export const pointWrite = (w, where) => { if ('each' in w)
@@ -227,7 +256,10 @@ const callOf = (fn) => {
227
256
  }
228
257
  return f;
229
258
  };
230
- // The n arguments a key pairs (left-nested, ((a, b), c)..., each pair (s)² + b with s = a + b), if it is their pairing.
259
+ // A key of several arguments: their pairing, left-nested, ((a, b), c)..., each pair (s)² + b with s = a + b.
260
+ export const pairE = (a, b) => { const s = plus(a, b); return plus(prod(s, s), b); };
261
+ export const argsKey = (args) => args.slice(1).reduce(pairE, args[0]);
262
+ // The n arguments a key pairs (argsKey's), if it is their pairing.
231
263
  const paired = new WeakMap();
232
264
  export function pairedArgs(key, n) {
233
265
  let byN = paired.get(key);
@@ -649,7 +681,7 @@ function symC(c, s, truth) {
649
681
  }
650
682
  }
651
683
  // PROVE_DEBUG=1 logs the case counts to stderr; read through globalThis so the module also loads where there is no process.
652
- const proveDebug = !!globalThis.process?.env?.PROVE_DEBUG;
684
+ const proveDebug = !!env.PROVE_DEBUG;
653
685
  const debug = (label, n) => { if (proveDebug)
654
686
  console.error(`[prove] ${label}: ${n} (${Math.round(performance.now())} ms)`); };
655
687
  // Drops the cases whose path is already impossible, so impossible branches don't multiply.
@@ -1,4 +1,4 @@
1
- import type { C, E } from './machine.js';
1
+ import { type C, type E } from './machine.js';
2
2
  import { type Loop, type Recur } from '../kernel/kernel.js';
3
3
  export type NeverEndsOptions = {
4
4
  ms?: number;
@@ -7,6 +7,7 @@ export type NeverEndsOptions = {
7
7
  lassos?: boolean;
8
8
  counted?: number;
9
9
  accel?: number;
10
+ extend?: number;
10
11
  };
11
12
  export type NeverEndsVerdict = {
12
13
  proven: boolean;
@@ -31,7 +32,10 @@ export type NeverEndsVerdict = {
31
32
  accelClosed: number;
32
33
  };
33
34
  };
35
+ export declare const isT: (c: C) => boolean;
36
+ export declare const isF: (c: C) => boolean;
34
37
  export declare const simpE: (e: E) => E;
35
38
  export declare const simpC: (c: C) => C;
36
39
  export declare function goalSize(x: unknown): number;
40
+ export declare const dagSize: (x: unknown) => number;
37
41
  export declare function findNeverEnds(l: Loop, opts?: NeverEndsOptions): NeverEndsVerdict;