gdp-wired 0.25.0 → 0.27.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 (52) hide show
  1. package/README.md +14 -9
  2. package/dist/core/accel.d.ts +20 -1
  3. package/dist/core/accel.js +797 -220
  4. package/dist/core/bmc.d.ts +12 -1
  5. package/dist/core/bmc.js +275 -106
  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 +103 -74
  10. package/dist/core/data.d.ts +1 -1
  11. package/dist/core/data.js +89 -118
  12. package/dist/core/discover.js +65 -27
  13. package/dist/core/dsl.d.ts +3 -2
  14. package/dist/core/dsl.js +29 -25
  15. package/dist/core/exists.js +7 -14
  16. package/dist/core/extract-check.d.ts +55 -4
  17. package/dist/core/extract-check.js +248 -122
  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 +98 -4
  21. package/dist/core/extract-read.js +306 -43
  22. package/dist/core/extract-shapes.d.ts +14 -0
  23. package/dist/core/extract-shapes.js +609 -79
  24. package/dist/core/extract-xstate.d.ts +5 -1
  25. package/dist/core/extract-xstate.js +618 -184
  26. package/dist/core/extract.d.ts +1 -0
  27. package/dist/core/extract.js +81 -30
  28. package/dist/core/infer.d.ts +1 -0
  29. package/dist/core/infer.js +126 -64
  30. package/dist/core/machine.d.ts +6 -0
  31. package/dist/core/machine.js +35 -4
  32. package/dist/core/nonterm.d.ts +5 -1
  33. package/dist/core/nonterm.js +133 -45
  34. package/dist/core/q.d.ts +1 -0
  35. package/dist/core/q.js +2 -2
  36. package/dist/core/relation.d.ts +1 -0
  37. package/dist/core/relation.js +20 -36
  38. package/dist/core/solver.d.ts +33 -0
  39. package/dist/core/solver.js +84 -30
  40. package/dist/core/transfer.js +22 -13
  41. package/dist/core/translate.d.ts +1 -1
  42. package/dist/core/translate.js +88 -65
  43. package/dist/core/xstate.d.ts +6 -1
  44. package/dist/core/xstate.js +336 -55
  45. package/dist/kernel/cdcl.js +212 -79
  46. package/dist/kernel/prove.d.ts +36 -5
  47. package/dist/kernel/prove.js +212 -104
  48. package/dist/kernel/reader.d.ts +75 -5
  49. package/dist/kernel/reader.js +533 -76
  50. package/dist/kernel/simplex.d.ts +27 -2
  51. package/dist/kernel/simplex.js +160 -14
  52. package/package.json +3 -2
@@ -25,6 +25,7 @@ export type Extraction = {
25
25
  notes: string[];
26
26
  };
27
27
  export declare function extract(code: string, opts: ExtractOptions): Extraction;
28
+ export declare function fromModel(model: Model, file: string, domains: Record<string, 'nat' | 'int'> | undefined, notes: string[], run: (rule: Rule, sorts: Sorts) => Evidence): Extraction;
28
29
  export declare const toSource: (x: Extraction) => string;
29
30
  export type { Evidence, Model, Term };
30
31
  export { Refusal };
@@ -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) {
@@ -46,10 +55,16 @@ export function extract(code, opts) {
46
55
  return { ok: false, refusals: [{ where: e.where, what: e.what }], notes };
47
56
  throw e;
48
57
  }
58
+ return fromModel(model, file, opts.domains, notes, (rule, sorts) => check(code, file, model, rule, sorts, { ...opts.check, ...(opts.files ? { files: opts.files } : {}), ...(opts.domains ? { given: opts.domains } : {}) }));
59
+ }
60
+ // A model read by a front end (this file's TypeScript, or core/extract-go.ts's Go) printed as the rule, built, and
61
+ // checked against the code by the front end's own check: what both front ends share.
62
+ export function fromModel(model, file, domains, notes, run) {
49
63
  let source, body, sorts;
50
64
  try {
51
- const s = sortsOf(model, opts.domains);
65
+ const s = sortsOf(model, domains);
52
66
  sorts = s.sorts;
67
+ datesInRange(model, sorts);
53
68
  notes.push(...model.notes, ...s.notes);
54
69
  body = builderOf(model, sorts);
55
70
  source = moduleOf(model, body, file);
@@ -69,11 +84,39 @@ export function extract(code, opts) {
69
84
  }
70
85
  if (invariants.length)
71
86
  source = `${source}\n// What every state of the code is: a law about every state is about the code's with these beside it.\nexport const ${identOf(model)}Invariants = [${invariantsOf(model, sorts).map(x => x.replace(/^r\./, `${identOf(model)}Rule.`)).join(', ')}]\n`;
72
- const evidence = check(code, file, model, rule, sorts, { ...opts.check, ...(opts.files ? { files: opts.files } : {}), ...(opts.domains ? { given: opts.domains } : {}) });
87
+ const evidence = run(rule, sorts);
73
88
  if (evidence.mismatch)
74
89
  return { ok: false, source, model, sorts, evidence, refusals: [{ where: file, what: `the rule and the code differ: ${evidence.mismatch}` }], notes };
75
90
  return { ok: true, rule, ...(invariants.length ? { invariants } : {}), source, model, sorts, evidence, refusals: [], notes };
76
91
  }
92
+ // 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
93
+ // set one there (as it refuses a sum past 2^53), and a start there: its claim stops at the Date's range.
94
+ const DATE_MAX = 8_640_000_000_000_000;
95
+ function datesInRange(m, sorts) {
96
+ 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))));
97
+ const dated = m.state.filter(v => v.sort.k === 'num' && v.sort.date);
98
+ const over = [];
99
+ for (const v of dated) {
100
+ const w = m.writes[v.name];
101
+ if (w?.s === 'num')
102
+ over.push(out(w.e, v.name));
103
+ }
104
+ for (const d of m.maps)
105
+ for (const f of d.fields)
106
+ if (f.sort.k === 'num' && f.sort.date) {
107
+ const w = m.mapWrites[d.name];
108
+ const t = w?.vals[f.name];
109
+ if (t?.s === 'num')
110
+ over.push(I.and(w.has, out(t.e, `${d.name}.${f.name}`)));
111
+ }
112
+ if (over.length)
113
+ m.refuse = I.or(m.refuse, ...over);
114
+ const starts = dated.filter(v => m.init[v.name]?.s === 'num').map(v => I.not(out(m.init[v.name].e, v.name)));
115
+ if (starts.length)
116
+ m.pre = I.and(m.pre, ...starts);
117
+ if (over.length || starts.length)
118
+ 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)');
119
+ }
77
120
  // The module a user keeps: the rule, with what it was read from and how it was checked.
78
121
  export const toSource = (x) => x.source ?? '';
79
122
  // The source is the rule: it is evaluated with the builders, so what is checked is what is printed.
@@ -88,7 +131,8 @@ function evaluate(body) {
88
131
  function invariantsOf(m, sorts) {
89
132
  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
133
  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(', ')}))))`);
134
+ return [...(m.laws ?? []), ...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(', ')}))))`),
135
+ ...(m.lists ?? []).map(d => `r.law(${JSON.stringify(`${d.name}: nothing past its end`)}, ({${d.name}}) => ${d.name}.within())`)];
92
136
  }
93
137
  function evaluateLaws(r, xs) {
94
138
  if (!xs.length)
@@ -101,9 +145,9 @@ function moduleOf(m, body, file) {
101
145
  const used = NAMES.filter(n => new RegExp(`(^|[^.\\w$])${n}\\(|(^|[^.\\w$])${n}\\b(?!\\s*:)`).test(body.replace(/'[^']*'/g, "''")) || (n === 'rule'));
102
146
  const ident = identOf(m);
103
147
  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'}).`,
148
+ `// Extracted by gdp-wired/extract from ${file} (${m.entry}, ${m.factory ? 'a factory of an object of functions' : m.shape === 'class' ? (/\.go$/.test(file) ? 'a struct and its methods' : 'a class') : m.shape === 'reducer' ? 'a step function' : 'functions over one record'}).`,
105
149
  `// Checked against the code it was read from; read again with extract() after the code changes.`,
106
- `import {${[...new Set([...used, ...(m.maps.length ? ['all', 'any', 'forall'] : [])])].sort((a, b) => a.localeCompare(b)).join(', ')}} from 'gdp-wired'`,
150
+ `import {${[...new Set([...used, ...(m.maps.length ? ['all', 'any', 'forall'] : []), ...['all', 'any', 'forall'].filter(n => (m.laws ?? []).some(l => l.includes(`${n}(`)))])].sort((a, b) => a.localeCompare(b)).join(', ')}} from 'gdp-wired'`,
107
151
  '',
108
152
  `export const ${ident}Rule = ${body}`,
109
153
  '',
@@ -139,6 +183,8 @@ function builderOf(m, sorts) {
139
183
  lines.push(` .state({${m.state.map(v => `${v.name}: ${start(v)}`).join(', ')}})`);
140
184
  if (m.maps.length)
141
185
  lines.push(` .maps({${m.maps.map((d) => `${d.name}: ${mapKind(d, sorts)}.from(${mapEmpty(d)})`).join(', ')}})`);
186
+ if (m.lists?.length)
187
+ lines.push(` .items({${m.lists.map(d => `${d.name}: ${kindOf(d.fields[0], sorts, `${d.name}.$item`)}`).join(', ')}})`);
142
188
  const envOf = (...xs) => {
143
189
  const vars = new Set(), maps = new Set();
144
190
  for (const x of xs)
@@ -172,9 +218,19 @@ function builderOf(m, sorts) {
172
218
  const vals = d.fields.map(f => `${f.name}: ${pterm(w.vals[f.name], P, { m, sorts, atoms: [w.has] }, `${n}.${f.name}`)}`);
173
219
  outs.push([n, `${n}.set(${pk(w.key, P, ctx())}, {has: ${pb(w.has, P, ctx())}, ${vals.join(', ')}})`]);
174
220
  }
221
+ // A list's write: its apply over the operations by cases (each under its condition).
222
+ const lw = Object.entries(m.listWrites ?? {});
223
+ for (const [n, ops] of lw) {
224
+ const one = (o) => {
225
+ const at = { m, sorts, atoms: [o.when] }, when = pb(o.when, P, ctx());
226
+ 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})`;
227
+ };
228
+ outs.push([`...${n}`, `${n}.apply(${ops.map(one).join(', ')})`]);
229
+ }
175
230
  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(', ')}}`;
231
+ const lterms = lw.flatMap(([, ops]) => ops.flatMap(o => [o.when, ...(o.op === 'pop' ? [] : [o.x.e]), ...(o.op === 'set' ? [o.i] : [])]));
232
+ 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)]);
233
+ const ret = `{${outs.map(([n, x]) => (n.startsWith('...') ? `...${x}` : `${n}: ${x}`)).join(', ')}}`;
178
234
  lines.push(defs.length ? ` .step((${env}) => {\n${defs.map(d => ` ${d}`).join('\n')}\n return ${ret}\n })` : ` .step((${env}) => (${ret}))`);
179
235
  return lines.join('\n');
180
236
  }
@@ -227,13 +283,8 @@ function hoist(m, P, roots) {
227
283
  if (!isBool(node)) {
228
284
  const ctx = { m, sorts: P.sorts, atoms: [] }, free = natOK(node, ctx);
229
285
  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);
286
+ walk(node, o => { if (o.op === 'cell')
287
+ cells.push(`${o.map}.${o.field}`); });
237
288
  const hasInt = [...I.varsOf(node).vars].some(n => P.sorts.get(n) === 'int') || cells.some(c => P.sorts.get(c) === 'int');
238
289
  if (!free && !hasInt)
239
290
  continue;
@@ -14,6 +14,7 @@ export type InferOptions = {
14
14
  existentials?: boolean;
15
15
  minimize?: boolean;
16
16
  remainders?: boolean;
17
+ join?: number;
17
18
  };
18
19
  export type Found = {
19
20
  law: Law;
@@ -16,20 +16,22 @@
16
16
  // then the forms a counterexample breaks, as IC3's relative induction, then all), each asked first of the CDCL
17
17
  // search for a model alone (a refutation's core: the forms it read), a counterexample the whole set allows joined in
18
18
  // (the hull grows to hold it, a bound rises to the next of the rule's constants, then goes), one to a caller's law
19
- // ruled out by a candidate or, where none does, by a cube blocked as IC3 blocks one (its control state and the
20
- // bounds that keep the samples out, the literals its refutation's core read, its predecessors blocked first); every
21
- // goal of the cone proven, the cone is the answer
19
+ // ruled out by a candidate or by a cube blocked as IC3 blocks one (its control state, the rule's own comparisons
20
+ // true there and the bounds that keep the samples out, the literals its refutation's core read, its predecessors
21
+ // blocked first), the cube first where no sample is at its control state; every goal of the cone proven, the cone
22
+ // is the answer
22
23
  // - the kernel (where the join proves nothing, as it was): the laws with the candidates chosen so far, proven one law
23
24
  // at a time; when a goal is stuck at a step, its witness is a counterexample to induction, so the candidate that
24
25
  // 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
26
  // is the answer, after each chosen candidate the proof doesn't need is taken out again
26
27
  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";
28
+ import { all, any, atMost, divisorsIn, evalC, get, interpret, machineTerms, modName, n, not, plus, same, seeded, times, withArithmetic, x } from "./machine.js";
29
+ import { proveRule, proveSteps, verdictOf } from "./dsl.js";
29
30
  import { allowed, watch } from "./watch.js";
30
- import { clock, counted, grow, proveLaw, proveLaws, proveStepLaws, usedHyps, withDeadline } from "../kernel/prove.js";
31
+ import { clock, counted, grow, proveLaw, proveLaws, proveStepLaws, usedHyps, withDeadline, withTrees } from "../kernel/prove.js";
31
32
  import { obligations, substC } from "../kernel/kernel.js";
32
- import { work } from "./solver.js";
33
+ import { env, gcd, work } from "./solver.js";
34
+ import { bgcd } from "./q.js";
33
35
  import { REFUTED, growCdcl } from "../kernel/cdcl.js";
34
36
  const KEY = 'key$found', AT = '@', K = '#', SOME = 'k$found';
35
37
  // The counted clock's rates, units a millisecond: about the slowest tenth of what Modal's 1-vCPU containers do in each
@@ -42,32 +44,37 @@ const KEY = 'key$found', AT = '@', K = '#', SOME = 'k$found';
42
44
  export const inferRates = { tries: 100, rows: 10_000, evals: 10_000, watched: 100, work: 40 };
43
45
  export const inferRuns = 16_000;
44
46
  // 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;
47
+ const inferTrace = !!env.GDP_INFER_TRACE;
46
48
  // The join (below, after the candidates): GDP_JOIN=0 turns it off, for comparing. Its share of what is left of the
47
49
  // search's budget; each kernel search's budget (counted, or wall time where timed), a request's 150 ms; the steps a walk
48
50
  // from a joined state takes; pairs of values as directions up to 10 values; a bound raised twice at most, then dropped;
49
51
  // equalities of at most 4 values, coefficients up to 1,000; at most 24 candidates beside the hull, 40 tried; yes/nos in
50
52
  // 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
53
  // at a time.
52
- const joinOn = globalThis.process?.env?.GDP_JOIN !== '0';
54
+ const joinOn = env.GDP_JOIN !== '0';
53
55
  const joinShare = 0.6, joinQueryMs = 8000, joinRequestMs = 150, joinWalk = 8, joinPairs = 10, joinRaises = 2, joinSparse = 4, joinCoef = 1000;
54
56
  const joinExtras = 24, joinTries = 40, joinBits = 7, joinKeys = 128, joinAttempts = 6, joinAdd = 2;
55
57
  // 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
58
  // CDCL search first, at a quarter of the goal's budget).
57
59
  // 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
60
  // until it is first broken).
59
- const joinNevers = globalThis.process?.env?.GDP_JOIN_NEVERS !== '0';
61
+ const joinNevers = env.GDP_JOIN_NEVERS !== '0';
60
62
  const joinNeversBreaks = 1;
61
- const joinCore = globalThis.process?.env?.GDP_JOIN_CORE !== '0';
62
- // Cubes blocked where no candidate rules a counterexample out (GDP_JOIN_CUBES=0: none): at most 48 in all, each tried 8
63
- // 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 joinCubeMax = 48, joinCubeTries = 8, joinCubeDepth = 3, joinCubeMs = 2000;
66
- // 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
- 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); }; };
63
+ const joinCore = env.GDP_JOIN_CORE !== '0';
64
+ // Cubes blocked for a counterexample to a caller's law (GDP_JOIN_CUBES=0: none), before any candidate is tried where
65
+ // no sample holds its control state, else where none rules it out: at most 48 in all, each tried 8 times, its
66
+ // predecessors blocked first 8 deep, each query's budget 2 s (counted, or wall time where timed).
67
+ const joinCubes = env.GDP_JOIN_CUBES !== '0';
68
+ const joinCubeMax = 48, joinCubeTries = 8, joinCubeDepth = 8, joinCubeMs = 2000;
69
+ // GDP_JOIN_ATOMS=0: a cube's literals at a point its control values and the samples' bounds alone (else the rule's own
70
+ // comparisons true there too).
71
+ const joinAtoms = env.GDP_JOIN_ATOMS !== '0';
72
+ // GDP_JOIN_PRIME=0: each control state no state reached a form of its own, every value read.
73
+ const joinPrime = env.GDP_JOIN_PRIME !== '0';
74
+ // GDP_JOIN_DOWN=0: a blocked cube kept as its refutation's core cuts it (no literal dropped); joinDownQueries, the
75
+ // queries a cube's generalization may ask.
76
+ const joinDown = env.GDP_JOIN_DOWN !== '0', joinDownQueries = 24;
69
77
  const isRule = (t) => typeof t.kindsOfState === 'function';
70
- const gcd = (a, b) => (b === 0 ? Math.abs(a) : gcd(b, a % b));
71
78
  // The constants a machine's expressions hold, and the factors it multiplies by.
72
79
  function constantsOf(m, laws) {
73
80
  const out = new Set();
@@ -152,9 +159,6 @@ const keyValue = (cell, w) => {
152
159
  }
153
160
  return value;
154
161
  };
155
- // The linear comparisons a machine's conditions make over the state alone (its assumption, its step's conditions and the
156
- // laws), as coefficients over the atoms given (an integer atom's two parts with opposite coefficients): the directions
157
- // a bound of the join may take beside the atoms' own.
158
162
  function comparisons(m, laws, atoms, coords) {
159
163
  const lin = (e, k, out) => {
160
164
  if (e.op === 'const') {
@@ -228,13 +232,15 @@ function comparisons(m, laws, atoms, coords) {
228
232
  if (neg)
229
233
  l.delete(neg[0]);
230
234
  }
235
+ const k0 = l.get('1') ?? 0;
231
236
  l.delete('1');
232
- if ([...l.values()].some(v => v !== 0) || coef.length < 2)
237
+ if ([...l.values()].some(v => v !== 0) || !coef.length)
233
238
  return;
234
239
  const g = coef.reduce((acc, [, cc]) => gcd(acc, cc), 0), t = coef.map(([i, cc]) => [i, cc / g]);
235
- if (t[0][1] < 0)
236
- t.forEach(p => { p[1] = -p[1]; });
237
- found.set(JSON.stringify(t), t);
240
+ const d = Math.floor((c.op === '<' ? -k0 - 1 : -k0) / g), u = t.map(([i, cc]) => [i, -cc]);
241
+ for (const r of [{ coef: t, d }, { coef: u, d: -d - 1 }, ...(c.op === '=' ? [{ coef: u, d: -d }, { coef: t, d: d - 1 }] : [])])
242
+ if (Number.isSafeInteger(r.d))
243
+ found.set(JSON.stringify(r), r);
238
244
  };
239
245
  if (m.assume)
240
246
  visitC(m.assume);
@@ -243,7 +249,7 @@ function comparisons(m, laws, atoms, coords) {
243
249
  return [...found.values()];
244
250
  }
245
251
  export function inferLaws(target, laws, stepLaws = [], opts = {}) {
246
- return quietly(() => withDeadline(performance.now() + (opts.ms ?? 20000), () => inferLawsSearch(target, laws, stepLaws, opts)));
252
+ return quietly(() => withDeadline(clock() + (opts.ms ?? 20000), () => inferLawsSearch(target, laws, stepLaws, opts)));
247
253
  }
248
254
  function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
249
255
  const t0 = performance.now(), ms = opts.ms ?? 20000, wallUntil = t0 + ms, rule = isRule(target) ? target : undefined;
@@ -291,7 +297,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
291
297
  if (searchRule)
292
298
  return stepLaws.length ? proveSteps(searchRule, ls, stepLaws, { search: false }) : proveRule(searchRule, ls, { search: false });
293
299
  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 } : {}) } : {}) };
300
+ return verdictOf(out);
295
301
  };
296
302
  const stats = (samples, candidates, alive) => ({ samples, candidates, alive, proofs, ms: Math.round(performance.now() - t0), stopped: stop() });
297
303
  const first = opts.first ?? prove(laws);
@@ -940,7 +946,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
940
946
  const pool0 = pool.slice(), ctis0 = ctis.length;
941
947
  if (joinOn && !mapNames.length && NS)
942
948
  try {
943
- const jT0 = performance.now(), jUntil = Math.min(until, now() + (until - now()) * joinShare);
949
+ const jT0 = performance.now(), jUntil = Math.min(until, now() + (until - now()) * (opts.join ?? joinShare));
944
950
  // The control state: the choice (loc) and, where they are few, the yes/nos (a program counter in bits), each of its
945
951
  // values reached a part of its own.
946
952
  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);
@@ -959,14 +965,15 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
959
965
  for (const [c1, c2] of [[1, 1], [1, -1], [-1, 1], [-1, -1]])
960
966
  out.push([[i, c1], [j, c2]]);
961
967
  const known = new Set(out.map(t => JSON.stringify(t)));
962
- for (const t of comparisons(m, laws, atoms, cs))
963
- for (const u of [t, t.map(([i, c]) => [i, -c])]) {
964
- const k2 = JSON.stringify(u);
965
- if (!known.has(k2) && out.length < 2 * cs.length + 4 * joinPairs * joinPairs + 64) {
966
- known.add(k2);
967
- out.push(u);
968
+ for (const { coef } of comparisons(m, laws, atoms, cs))
969
+ if (coef.length > 1)
970
+ for (const u of coef[0][1] > 0 ? [coef, coef.map(([i, c]) => [i, -c])] : []) {
971
+ const k2 = JSON.stringify(u);
972
+ if (!known.has(k2) && out.length < 2 * cs.length + 4 * joinPairs * joinPairs + 64) {
973
+ known.add(k2);
974
+ out.push(u);
975
+ }
968
976
  }
969
- }
970
977
  return out;
971
978
  };
972
979
  const dirs = directions(coords);
@@ -974,8 +981,6 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
974
981
  // products the first time, the constants alone after), and past that it is dropped.
975
982
  const fine = bounds, coarse = [...new Set([0, ...consts.flatMap(k => [k, -k])])].sort((p2, q2) => p2 - q2);
976
983
  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
984
  const normal = (e) => { let g2 = 0n; for (const x2 of e)
980
985
  g2 = bgcd(g2, x2); if (g2 > 1n)
981
986
  for (let k = 0; k < e.length; k++)
@@ -1072,10 +1077,33 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1072
1077
  if (nev.length > 1 && joinNevers && neversBroken < joinNeversBreaks)
1073
1078
  push({ coef: [], d: 0, cells: false, nevers: nev, size: 1 });
1074
1079
  else
1075
- for (const ats of nev)
1080
+ for (const ats of joinPrime ? primes(nev) : nev)
1076
1081
  push({ coef: [], d: 0, cells: false, ...(ats.length > 1 ? { never: ats } : { unreachable: ats[0] }), size: 1 });
1077
1082
  return out;
1078
1083
  };
1084
+ // The control states no state reached, as fewer and smaller cubes (a program counter in bits: Spacer's clauses there
1085
+ // 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
1086
+ // control state reached, then the cubes another cube's values include left out. Together they say what the cubes
1087
+ // of every value say (the control state is one reached), but a goal reads fewer of them, and each of them less.
1088
+ const primes = (nev) => {
1089
+ const reachedKeys = [...groups.keys()].map(k2 => k2.split(',').map(Number));
1090
+ const holdsAtSome = (c) => reachedKeys.some(vs => c.every(a => vs[keyAtoms.indexOf(a.atom)] === a.value));
1091
+ const out = [];
1092
+ for (const ats of nev) {
1093
+ let c = ats;
1094
+ for (const a of [...ats.slice(1), ats[0]]) {
1095
+ if (c.length <= 1)
1096
+ break;
1097
+ const fewer = c.filter(b2 => b2 !== a);
1098
+ if (!holdsAtSome(fewer))
1099
+ c = fewer;
1100
+ }
1101
+ out.push(c);
1102
+ }
1103
+ const key2 = (c) => c.map(a => `${a.atom}=${a.value}`).sort().join('&');
1104
+ const uniq = [...new Map(out.map(c => [key2(c), c])).values()].sort((a, b) => a.length - b.length);
1105
+ 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))));
1106
+ };
1079
1107
  let rounds = 0, why = '', set = [];
1080
1108
  const params0 = {};
1081
1109
  // Beside the hull, forms of the candidates' that rule out a counterexample to the caller's laws (a state the set
@@ -1205,10 +1233,17 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1205
1233
  return { scalars: sc, maps: {} };
1206
1234
  };
1207
1235
  const vecOf = (st) => valuesOf(pointOf({}, st).scalar);
1208
- // The cube of a point the samples leave out: its control literals, then the direction that leaves out the most
1209
- // samples still in, its bound as weak as leaves them out, until none is in (undefined: none leaves out the rest).
1236
+ // The cube of a point the samples leave out: its control literals and the rule's own comparisons true there (where
1237
+ // no sample is, a location the runs never reached, a cube of its control values alone isn't blocked: its
1238
+ // predecessors take it back to the samples; the comparisons are what a predecessor's guards say, as Spacer's
1239
+ // projections read them), then the direction that leaves out the most samples still in, its bound as weak as
1240
+ // leaves them out, until none is in (undefined: none leaves out the rest).
1241
+ const ruleLits = joinAtoms ? comparisons(m, laws, atoms, lc).map(lin => ({ lin })) : [];
1210
1242
  const cubeOf = (v) => {
1211
1243
  const lits = ctrl.map(i => ({ at: { atom: i, value: v[i] } }));
1244
+ for (const l of ruleLits)
1245
+ if (litHolds(l, v))
1246
+ lits.push(l);
1212
1247
  let alive = S.filter(s2 => inCube(lits, s2));
1213
1248
  while (alive.length) {
1214
1249
  let best = -1, bestN = 0;
@@ -1283,7 +1318,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1283
1318
  // Is the cube's negation inductive relative to these laws (the caller's and the kinds' beside)? Its literals after
1284
1319
  // the step are hypotheses of their own, so the refutation's core names those it read.
1285
1320
  const queryWith = (c, frame) => {
1286
- const f = formOf(c), ls = [...given, ...frame, lawFor(f)], mm = forLaws(ls).m;
1321
+ const f = formOf(c), own = lawFor(f), names2 = new Set([own.name]), ls = [...given, ...frame.filter(l => !names2.has(l.name) && !!names2.add(l.name)), own], mm = forLaws(ls).m;
1287
1322
  const g = obligations(mm, ls, {}, ls.length - 1)[1], last = g.hyps.at(-1);
1288
1323
  const inner = last.op === 'not' && last.x.op === 'not' && last.x.x.op === 'and' && last.x.x.xs.length === c.length ? last.x.x.xs : undefined;
1289
1324
  const tails = inner ?? [last], hyps = [...g.hyps.slice(0, -1), ...tails], base = hyps.length - tails.length;
@@ -1296,13 +1331,40 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1296
1331
  return { ok: false, ...witnessStep(out.witness) };
1297
1332
  return undefined;
1298
1333
  };
1299
- // A counterexample to a caller's law no candidate rules out: its cube (its control state and the bounds that keep
1334
+ // A counterexample to a caller's law: its cube (its control state, the rule's comparisons and the bounds that keep
1300
1335
  // the samples out), blocked relative to the set (the set assumed before the step, and the cube's own negation, as
1301
1336
  // IC3's relative induction), its literals after the step those the refutation read (its core), the samples and the
1302
1337
  // start kept out. A predecessor the set allows into the cube: its own cube blocked first (a few deep), else the
1303
1338
  // cube made smaller to leave the predecessor's successor out. Each cube blocked is a form of the set (a
1304
1339
  // disjunction: never all its literals), which the join keeps or drops as any other.
1305
- let cubed = 0, cubeWhy = '', cubeUntil = Infinity;
1340
+ let cubed = 0, cubeWhy = '';
1341
+ // IC3's generalization of a cube blocked (Bradley's down, literal dropping as Een, Mishchenko and Brayton's): the
1342
+ // literals taken out a part at a time (half of them, then quarters, ..., then one by one), a part kept out where the
1343
+ // cube without it still leaves the start and the samples out and is still blocked relative to the same laws (the
1344
+ // refutation's core then cutting it further); within joinDownQueries queries. A cube's core reads most of its
1345
+ // literals where the step's terms are a chain of ifs (research/dag: a refutation's core is nearly its whole path), so
1346
+ // the core alone leaves a cube of every control value; Spacer's clauses on these tasks read two to four.
1347
+ const down = (c, frame) => {
1348
+ let cur = c, queries = 0;
1349
+ for (let part = Math.ceil(cur.length / 2); part >= 1 && queries < joinDownQueries && now() < jUntil && !stop(); part = part === 1 ? 0 : Math.ceil(part / 2)) {
1350
+ for (let i = 0; i < cur.length && cur.length > 1 && queries < joinDownQueries && now() < jUntil && !stop();) {
1351
+ const cand = [...cur.slice(0, i), ...cur.slice(i + part)];
1352
+ if (!cand.length || (initVec && inCube(cand, initVec)) || S.some(s2 => inCube(cand, s2))) {
1353
+ i += part;
1354
+ continue;
1355
+ }
1356
+ queries++;
1357
+ const r = queryWith(cand, frame);
1358
+ if (!r?.ok) {
1359
+ i += part;
1360
+ continue;
1361
+ }
1362
+ const cut = cand.filter((_, j) => r.core.has(j));
1363
+ cur = cut.length && !(initVec && inCube(cut, initVec)) && !S.some(s2 => inCube(cut, s2)) ? cut : cand;
1364
+ }
1365
+ }
1366
+ return cur;
1367
+ };
1306
1368
  const blockCube = (v, depth, within) => {
1307
1369
  let c = cubeOf(v);
1308
1370
  const made = [];
@@ -1324,7 +1386,8 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1324
1386
  if (l)
1325
1387
  c2.push(l);
1326
1388
  }
1327
- made.push(formOf(outOfSamples(c2, c) ? c2 : c));
1389
+ const c3 = outOfSamples(c2, c) ? c2 : c;
1390
+ made.push(formOf(joinDown ? down(c3, [...ctx, ...made].map(lawFor).filter(l => l.name !== textOf(formOf(c3)))) : c3));
1328
1391
  break;
1329
1392
  }
1330
1393
  if (!r.post) {
@@ -1365,12 +1428,6 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1365
1428
  why = 'time';
1366
1429
  break;
1367
1430
  }
1368
- // (once a cube is in the set, the join has a part of what is left, the search below the rest: the cubes are
1369
- // for counterexamples no candidate rules out, which the search below rules out its own way)
1370
- if (now() > cubeUntil) {
1371
- why = 'cubes';
1372
- break;
1373
- }
1374
1431
  rounds++;
1375
1432
  set = [...formsNow(), ...extras].filter(f => !blocked.has(textOf(f)));
1376
1433
  const byText = new Map(set.map(f => [textOf(f), f]));
@@ -1469,9 +1526,22 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1469
1526
  }
1470
1527
  if (outside || breaks(params, post)) {
1471
1528
  // the caller's law broken from a state the set allows: a candidate false there and at every state reached, the
1472
- // one false at the most such states (then the smallest), or one made from it (fromCti)
1529
+ // one false at the most such states (then the smallest), or one made from it (fromCti); else its cube blocked,
1530
+ // as IC3 blocks one. Where no sample holds its control state (the samples say nothing of it) the cube comes first.
1473
1531
  negs.push(pre);
1474
1532
  ctis.push(pre);
1533
+ const pv = valuesOf(pre.scalar), alone = !S.some(s2 => ctrl.every(i => s2[i] === pv[i]));
1534
+ const cube = () => {
1535
+ if (outside || !joinCubes || !initVec || cubed >= joinCubeMax)
1536
+ return false;
1537
+ const made = blockCube(pv, joinCubeDepth, set), fresh = made.filter((f, i) => !set.some(g2 => textOf(g2) === textOf(f)) && made.findIndex(g2 => textOf(g2) === textOf(f)) === i);
1538
+ opts.progress?.('join', { round: rounds, set: set.length, cubes: made.map(f => textOf(f).slice(0, 100)).join('; ') || `none: ${cubeWhy}` });
1539
+ cubed += fresh.length;
1540
+ extras.push(...fresh);
1541
+ return fresh.length > 0;
1542
+ };
1543
+ if (alone && cube())
1544
+ continue;
1475
1545
  const pick = (fs) => { let bestF, score = -Infinity; for (const f of fs) {
1476
1546
  if (f.cells || f.cong || extras.includes(f) || blocked.has(textOf(f)) || holdsAt(f, pre) || !reached.every(p2 => holdsAt(f, p2)))
1477
1547
  continue;
@@ -1489,17 +1559,8 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1489
1559
  if (next)
1490
1560
  tried++;
1491
1561
  opts.progress?.('join', { round: rounds, set: set.length, ms: qms, target: next ? textOf(next).slice(0, 60) : 'none' });
1492
- if (!next && !outside && joinCubes && initVec && cubed < joinCubeMax && now() < jUntil) {
1493
- const made = blockCube(valuesOf(pre.scalar), joinCubeDepth, set);
1494
- opts.progress?.('join', { round: rounds, set: set.length, cubes: made.map(f => textOf(f).slice(0, 100)).join('; ') || `none: ${cubeWhy}` });
1495
- if (made.length) {
1496
- if (!cubed)
1497
- cubeUntil = now() + (jUntil - now()) * joinCubeWindow;
1498
- cubed += made.length;
1499
- extras.push(...made);
1500
- continue;
1501
- }
1502
- }
1562
+ if (!next && !alone && cube())
1563
+ continue;
1503
1564
  if (!next) {
1504
1565
  why = 'target';
1505
1566
  break;
@@ -1605,7 +1666,8 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1605
1666
  };
1606
1667
  for (let iter = 0; iter < 300 && now() < until && !stop(); iter++) {
1607
1668
  const began = now(), wall = performance.now();
1608
- last = search([...given, ...chosen.map(lawFor)]);
1669
+ // (each law proven alone, then the set as a whole: the same goals, grown once)
1670
+ last = withTrees(() => search([...given, ...chosen.map(lawFor)]));
1609
1671
  const took = now() - began;
1610
1672
  opts.progress?.('proof', { chosen: chosen.length, goal: last.goal ?? '', stuck: last.stuck ?? '', ms: Math.round(performance.now() - wall), counted: Math.round(took) });
1611
1673
  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;