gdp-wired 0.30.0 → 0.31.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -83,11 +83,21 @@ All of these are proven automatically, and each proof is also a Lean theorem:
83
83
  and string-literal unions, values that may be null, records, Map and Record keyed state, arrays as lists, Dates as
84
84
  their time, branches and early returns, throws as refusals, `Date.now()` as an input) and what it refuses, each with
85
85
  the place and the reason, are in `core/extract.ts`.
86
+ - **Effect services** (`gdp-wired/effect`, `effect` 3.x or 4.x): `extractEffect(code, {entry, effect})` reads a service
87
+ whose make effect creates Refs (Ref, SynchronizedRef, SubscriptionRef, 4.x's TxRef) and returns an object of methods
88
+ (`Effect.fn` bodies, arrows returning an effect), with typed failures as its refusals and `Clock.currentTimeMillis` as
89
+ an input; the rule is checked by running the service on Effect's runtime (`Effect.runSyncExit`, the clock fixed at
90
+ each request's time), every Ref, result and failure compared. `conforms(rule, service)` runs a rule written by hand
91
+ beside a running service (Effect's own Semaphore, a store), and `fromSchema(schema)` is a Schema's kind
92
+ (`examples/effect.ts`; what is read and refused, with what Effect projects write, in `research/effect/README.md`).
86
93
  - **What nobody stated, looked for when the prover alone stops**: where `proveRule` or `proveSteps` doesn't prove the laws
87
94
  and no run breaks them, it looks for lemmas about the rule's recurrences and lists (`discover`), lemmas about the
88
95
  functions it knows by their facts (`cycleLemmas`, each proven by a cyclic proof) and then invariants (`inferLaws`),
89
96
  within 10 s (`{search: {ms}}`; `{search: false}`, the prover alone); the verdict's `found` holds what
90
- proved them, as laws and lemmas with the source to paste.
97
+ proved them, as laws and lemmas with the source to paste. Each invariant found holds in the states reachable from the
98
+ start, so a proof that needs one holds there and the verdict says so (`assumes: {states: 'reachable', laws}`). Code that
99
+ steps the rule from states it is handed proves with `{from: 'any'}`: every step law then holds from every state the
100
+ laws allow, reachable or not, and the search never adds an invariant.
91
101
  - **Invariants nobody wrote** (`gdp-wired/infer`): `inferLaws(rule, laws)` proves a law that holds but isn't inductive
92
102
  alone, with the laws it finds (bounds, sums and differences over the state, the same where a flag or a choice holds
93
103
  one value, remainders of a value or of a sum or difference of two, x mod 2 = 0 for a counter stepping by 2, and laws
@@ -470,7 +480,7 @@ The npm package is built from `core/`, `kernel/` and `lean-kernel/` alone; nothi
470
480
 
471
481
  The npm package is the library: the builders (`gdp-wired`), the runtimes (`gdp-wired/machine`), composition
472
482
  (`gdp-wired/compose`), XState machines as charts (`gdp-wired/xstate`), rules read from the code (`gdp-wired/extract`, with
473
- `typescript` installed), lemmas nobody stated (`gdp-wired/discover`), invariant
483
+ `typescript` installed), Effect services (`gdp-wired/effect`, with `typescript` and `effect`), lemmas nobody stated (`gdp-wired/discover`), invariant
474
484
  inference (`gdp-wired/infer`), the
475
485
  Lean export (`gdp-wired/lean`), the kernel (`gdp-wired/kernel`), the prover (`gdp-wired/prove`), the derivation checker
476
486
  and solver (`gdp-wired/check`, `gdp-wired/solver`). Everything else here (examples, comparisons, the Lean twin, the GPU
@@ -1,4 +1,4 @@
1
- import { type Kind, type Rule, type TermLike, type Verdict, Choice, Cond, Term } from './dsl.js';
1
+ import { type Kind, type ProveOptions, type Rule, type TermLike, type Verdict, Choice, Cond, Term } from './dsl.js';
2
2
  import { type Law } from './machine.js';
3
3
  import type { StepLaw } from '../kernel/kernel.js';
4
4
  export type StateNode = {
@@ -78,7 +78,7 @@ export declare class Chart<P extends Obj = {}, I extends Obj = {}, X extends Obj
78
78
  law(name: string, f: (env: After<P & X>) => Cond): Law;
79
79
  stepLaw(name: string, then: (before: Env<P, I, X>, after: After<X>) => Cond, when?: (before: Env<P, I, X>) => Cond): StepLaw;
80
80
  chartLaws(): Law[];
81
- prove(laws?: Law[], stepLaws?: StepLaw[]): Verdict;
81
+ prove(laws?: Law[], stepLaws?: StepLaw[], opts?: ProveOptions): Verdict;
82
82
  check(opts?: {
83
83
  params?: Obj;
84
84
  bound?: number;
@@ -201,7 +201,7 @@ export class Chart {
201
201
  const { rule: r, regions } = this.build();
202
202
  return regions.flatMap(reg => [...reg.compounds].filter(([c, { history }]) => history && c).map(([c]) => r.law(`${reg.name === 'state' ? '' : `${reg.name}.`}${c} remembers one of its own states`, (env) => any(...reg.leaves.filter(l => l.startsWith(`${c}.`)).map(l => env[`${reg.field}.last.${c}`].is(l))))));
203
203
  }
204
- prove(laws = [], stepLaws = []) { const given = [...this.chartLaws(), ...laws]; return stepLaws.length ? proveSteps(this.rule, given, stepLaws) : proveRule(this.rule, given); }
204
+ prove(laws = [], stepLaws = [], opts = {}) { const given = [...this.chartLaws(), ...laws]; return stepLaws.length ? proveSteps(this.rule, given, stepLaws, opts) : proveRule(this.rule, given, opts); }
205
205
  // --- the checks a chart's author expects -------------------------------------------------------------------------
206
206
  // reached: each state, with the first run from the start that reaches it (a breadth-first walk of the compiled rule
207
207
  // over every event and small payloads, `bound` the largest natural tried, under `params`), or `unreachable` where the
@@ -149,14 +149,15 @@ export declare function translatedProof(key: () => string, build: (reused: boole
149
149
  why?: string;
150
150
  };
151
151
  export declare const routeOf: () => string;
152
- export declare const translateMs: (usualMs?: number) => number;
152
+ export declare const translateMs: (usualMs?: number, floor?: number) => number;
153
+ export declare const stepCertFloor: () => number;
153
154
  export declare function crossCyclic(kind: string, name: string, usual: boolean, run0: (() => CyclicVerdict) | undefined, usualMs?: number, translated?: Translated): void;
154
155
  export declare const certMode: () => boolean;
155
156
  export declare const certOn: () => boolean;
156
157
  export declare const certSearch: () => boolean;
157
158
  export declare const certMs: () => number;
158
159
  export declare const uncovered: (kind: string, name: string, why: string) => void;
159
- export declare function certCyclic(kind: string, name: string, translated: Translated | undefined, run0: (() => CyclicVerdict) | undefined, usualMs?: number): {
160
+ export declare function certCyclic(kind: string, name: string, translated: Translated | undefined, run0: (() => CyclicVerdict) | undefined, usualMs?: number, floor?: number): {
160
161
  checked: boolean;
161
162
  proof?: Cyclic;
162
163
  why: string;
@@ -1376,11 +1376,18 @@ const none = () => ({ proven: false, checked: false, node: '', goal: 'no instanc
1376
1376
  // translated) searched, within `until` where it is given; with why the translation wasn't proven.
1377
1377
  // A translation within the certificate's budget (GDP_CERT_MS) or four times the usual proof's time, whichever is longer
1378
1378
  // (`translateMs`): one that will fail is cut there, not at its goals' own bounds.
1379
- export const translateMs = (usualMs = 0) => Math.max(certMs(), 4 * usualMs);
1380
- function cyclicOf(translated, run, st, until, usualMs) {
1379
+ // `floor`: the least a translation is given (a step law's certificate passes its own, stepCertFloor).
1380
+ export const translateMs = (usualMs = 0, floor = certMs()) => Math.max(floor, 4 * usualMs);
1381
+ // A step law's: four times its usual proof's time, at least a quarter second (GDP_CERT_STEP_MS). Its usual trees are
1382
+ // the certificate where the translation isn't made, checked by kernel.ts as every certificate is, so a translation that
1383
+ // will fail costs at most that. (With GDP_CERT_MS's 10 s as the floor, from 0.19.0, every step law whose translation
1384
+ // fails waited it out, and twice from 0.20.0, together and then alone: a statechart's 19 step laws, proven in 0.35 s,
1385
+ // took 55 s to certify, every one of the failed laws' certificates its usual trees in the end.)
1386
+ export const stepCertFloor = () => Number(env.GDP_CERT_STEP_MS ?? 250);
1387
+ function cyclicOf(translated, run, st, until, usualMs, floor) {
1381
1388
  let how = 'searched', why;
1382
1389
  if (translated) {
1383
- const r = withDeadline(clock() + translateMs(usualMs), () => translated(st));
1390
+ const r = withDeadline(clock() + translateMs(usualMs, floor), () => translated(st));
1384
1391
  if (r.verdict?.proven && r.verdict.checked)
1385
1392
  return { out: r.verdict, how: 'translated' };
1386
1393
  how = 'fallback';
@@ -1429,11 +1436,11 @@ export const certMs = () => Number(env.GDP_CERT_MS ?? 10_000);
1429
1436
  // A proof of a kind no cyclic instance covers, or whose cyclic proof wasn't made, counted (`cyclic: {..., uncovered:
1430
1437
  // true, why}`): its certificate the usual trees.
1431
1438
  export const uncovered = (kind, name, why) => cycLog({ kind, name, uncovered: true, why });
1432
- export function certCyclic(kind, name, translated, run0, usualMs) {
1439
+ export function certCyclic(kind, name, translated, run0, usualMs, floor) {
1433
1440
  for (const key of Object.keys(cyclicProf))
1434
1441
  delete cyclicProf[key];
1435
1442
  const st = tstats(), t0 = performance.now(), until = clock() + certMs();
1436
- const { out, how, why } = cyclicOf(translated, (translated && !certSearch() ? undefined : run0) ?? none, st, until, usualMs);
1443
+ const { out, how, why } = cyclicOf(translated, (translated && !certSearch() ? undefined : run0) ?? none, st, until, usualMs, floor);
1437
1444
  const checked = out.proven && out.checked;
1438
1445
  cycLog({ kind, name, cert: true, usual: true, cyclic: checked, ms: Math.round(performance.now() - t0), ...(usualMs === undefined ? {} : { usualMs: Math.round(usualMs) }), route: how, ...(how !== 'searched' ? st : {}), ...(why ? { fellBack: why } : {}), ...profLine() });
1439
1446
  const late = clock() > until ? ` within ${certMs()} ms` : '';
@@ -191,6 +191,11 @@ export declare class Val {
191
191
  ne(b: Val): Bool;
192
192
  }
193
193
  export declare const wrap: (s: Sort, x: X) => Nat | Bool | Val | Integer;
194
+ export declare const whenOf: (y: Y) => {
195
+ c: Y;
196
+ a: Y;
197
+ b: Y;
198
+ } | undefined;
194
199
  export declare function when<T extends Nat | Val | Bool | Integer | number>(c: Bool, a: T, b: T): T extends number ? Nat : T;
195
200
  export declare const dataNamed: (name: string) => Data;
196
201
  export declare const fieldSort: (f: {
package/dist/core/data.js CHANGED
@@ -152,6 +152,15 @@ export class Val {
152
152
  // A value of a sort from its term.
153
153
  export const wrap = (s, x) => (s === 'nat' ? new Nat(x) : s === 'bool' ? new Bool({ op: 'holds', x }) : s === 'int' ? new Integer(x) : new Val(s, x));
154
154
  const xOf = (s, v) => (s === 'nat' ? natX(v) : s === 'bool' ? { op: 'bool', c: v.y } : s === 'int' ? intX(v) : v.x);
155
+ // `when`'s shape on Bool, read back: its condition and its two sides.
156
+ export const whenOf = (y) => {
157
+ if (y.op !== 'or' || y.xs.length !== 2)
158
+ return undefined;
159
+ const [p, q] = y.xs;
160
+ if (p.op !== 'and' || q.op !== 'and' || p.xs.length !== 2 || q.xs.length !== 2 || q.xs[0].op !== 'not')
161
+ return undefined;
162
+ return JSON.stringify(q.xs[0].x) === JSON.stringify(p.xs[0]) ? { c: p.xs[0], a: p.xs[1], b: q.xs[1] } : undefined;
163
+ };
155
164
  export function when(c, a, b) {
156
165
  if (a instanceof Bool)
157
166
  return new Bool({ op: 'or', xs: [{ op: 'and', xs: [c.y, a.y] }, { op: 'and', xs: [{ op: 'not', x: c.y }, b.y] }] });
@@ -435,7 +444,10 @@ function recursion(fn) {
435
444
  return { decreases: got[0], ring: names };
436
445
  }
437
446
  export const terminationMs = { ms: 10_000 };
438
- const measurable = (s) => s === 'nat' || s instanceof Data;
447
+ // (an integer's size is its value where it is positive, 0 below: Lean's Int.toNat; a measure that reads one is read in
448
+ // the integers, its value the same, compare/chc-adt's naturals written as Int)
449
+ const measurable = (s) => s === 'nat' || s === 'int' || s instanceof Data;
450
+ const sized = (s) => s === 'nat' || s instanceof Data;
439
451
  function measureOf(name, ps, m) {
440
452
  if (!m.length)
441
453
  throw new Error(`${name}: an empty measure`);
@@ -446,7 +458,7 @@ function measureOf(name, ps, m) {
446
458
  }
447
459
  export const showMeasure = (f, m) => {
448
460
  const comp = (c) => {
449
- const parts = c.coef.flatMap((k, i) => (k ? [`${k < 0 ? '−' : ''}${Math.abs(k) === 1 ? '' : `${Math.abs(k)}·`}${f.params[i].sort === 'nat' ? f.params[i].name : `size(${f.params[i].name})`}`] : []));
461
+ const parts = c.coef.flatMap((k, i) => (k ? [`${k < 0 ? '−' : ''}${Math.abs(k) === 1 ? '' : `${Math.abs(k)}·`}${f.params[i].sort === 'nat' ? f.params[i].name : f.params[i].sort === 'int' ? `toNat(${f.params[i].name})` : `size(${f.params[i].name})`}`] : []));
450
462
  const t = [...parts, ...(c.fold ? [`${c.fold.fn}(${f.params[c.fold.of].name})`] : []), ...(c.c ? [String(c.c)] : [])].join(' + ').replace(/\+ −/g, '− ');
451
463
  return t || '0';
452
464
  };
@@ -455,6 +467,8 @@ export const showMeasure = (f, m) => {
455
467
  // A component at arguments, as a term (its negative part subtracted, truncated as the encoding reads it).
456
468
  const sizeX = (s, a) => (s === 'nat' ? a : { op: 'size', data: s.name, of: a });
457
469
  export function measureX(f, c, args) {
470
+ if (readsInt(f, c))
471
+ return measureI(f, c, args);
458
472
  const pos = [], neg = [];
459
473
  c.coef.forEach((k, i) => { if (!k)
460
474
  return; const t = sizeX(f.params[i].sort, args[i]); (k > 0 ? pos : neg).push(Math.abs(k) === 1 ? t : { op: 'mul', k: Math.abs(k), a: t }); });
@@ -467,7 +481,30 @@ export function measureX(f, c, args) {
467
481
  const sum = (ts) => (ts.length ? ts.reduce((a, b) => ({ op: 'add', a, b })) : { op: 'nat', value: 0 });
468
482
  return neg.length ? { op: 'sub', a: sum(pos), b: sum(neg) } : sum(pos);
469
483
  }
470
- const lexY = (as, bs) => (as.length === 1 ? { op: '<', a: as[0], b: bs[0] } : { op: 'or', xs: [{ op: '<', a: as[0], b: bs[0] }, { op: 'and', xs: [{ op: '=', a: as[0], b: bs[0] }, lexY(as.slice(1), bs.slice(1))] }] });
484
+ // A component that reads an integer, in the integers: max(0, Σ coef·toNat(x) + c), each natural and size made an integer.
485
+ const readsInt = (f, c) => c.coef.some((k, i) => k && f.params[i].sort === 'int');
486
+ const iZero = { op: 'int', value: 0 }, iMax0 = (a) => ({ op: 'if', c: { op: 'i<=', a: iZero, b: a }, then: a, else: iZero });
487
+ function measureI(f, c, args) {
488
+ const terms = [];
489
+ c.coef.forEach((k, i) => {
490
+ if (!k)
491
+ return;
492
+ const q = f.params[i].sort, t = q === 'int' ? iMax0(args[i]) : { op: 'ofnat', a: sizeX(q, args[i]) };
493
+ terms.push(k === 1 ? t : { op: 'imul', k, a: t });
494
+ });
495
+ if (c.fold)
496
+ terms.push({ op: 'ofnat', a: { op: 'call', fn: c.fold.fn, args: [args[c.fold.of]] } });
497
+ if (c.c)
498
+ terms.push({ op: 'int', value: c.c });
499
+ return iMax0(terms.reduce((a, b) => ({ op: 'iadd', a, b })));
500
+ }
501
+ // (where either side's component is in the integers, both are, and compared there)
502
+ const lexY = (as, bs, ints = []) => {
503
+ const [a, b] = ints[0] ? [as[0], bs[0]].map(x => (isIntX(x) ? x : { op: 'ofnat', a: x })) : [as[0], bs[0]];
504
+ const lt = { op: ints[0] ? 'i<' : '<', a, b };
505
+ return as.length === 1 ? lt : { op: 'or', xs: [lt, { op: 'and', xs: [{ op: '=', a, b }, lexY(as.slice(1), bs.slice(1), ints.slice(1))] }] };
506
+ };
507
+ const isIntX = (x) => x.op === 'if' && x.else.op === 'int';
471
508
  // The measures of a ring, each padded to the longest with components 0 (Data.lean's `lexLt` compares tuples of one length).
472
509
  const padded = (ring, ms) => {
473
510
  const w = Math.max(...ms.map(m => m.comps.length));
@@ -490,9 +527,18 @@ function sitesOf(fn, names) {
490
527
  goX(y.b, w);
491
528
  return;
492
529
  case 'and':
493
- case 'or':
530
+ case 'or': {
531
+ // a condition's choice (`when` on Bool: (c ∧ a) ∨ (¬c ∧ b)) is an if: each side on its path
532
+ const c = whenOf(y);
533
+ if (c) {
534
+ goY(c.c, w);
535
+ goY(c.a, { ...w, wrap: z => w.wrap({ op: 'or', xs: [{ op: 'not', x: c.c }, z] }) });
536
+ goY(c.b, { ...w, wrap: z => w.wrap({ op: 'or', xs: [c.c, z] }) });
537
+ return;
538
+ }
494
539
  y.xs.forEach(z => goY(z, w));
495
540
  return;
541
+ }
496
542
  case 'not':
497
543
  goY(y.x, w);
498
544
  return;
@@ -598,12 +644,13 @@ const ownArgs = (f) => f.params.map(q => ({ op: 'var', name: `${f.name}.${q.name
598
644
  // among its caller's.
599
645
  function obligation(ring, ms, s, i) {
600
646
  const fn = ring[s.from], to = ring[s.to];
601
- const holds = shapedBy(s)(s.wrap(lexY(ms[s.to].comps.map(c => measureX(to, c, s.args)), ms[s.from].comps.map(c => measureX(fn, c, ownArgs(fn))))));
647
+ const ints = ms[s.to].comps.map((c, j) => readsInt(to, c) || readsInt(fn, ms[s.from].comps[j]));
648
+ const holds = shapedBy(s)(s.wrap(lexY(ms[s.to].comps.map(c => measureX(to, c, s.args)), ms[s.from].comps.map(c => measureX(fn, c, ownArgs(fn))), ints)));
602
649
  const name = ring.length === 1 ? `${fn.name}'s call ${i + 1} lowers ${showMeasure(fn, ms[0])}` : `${fn.name}'s call ${i + 1}, of ${to.name}, lowers ${showMeasure(to, ms[s.to])} below ${showMeasure(fn, ms[s.from])}`;
603
650
  return { name, vars: s.vars.filter(v => !s.shape.has(v.name)), holds, params: [...new Set(paramsIn(holds))] };
604
651
  }
605
652
  let tracing;
606
- const featOf = (f, vs) => f.params.map((p, i) => (p.sort === 'nat' ? vs[i] : p.sort instanceof Data ? sizeOf(p.sort, vs[i]) : 0));
653
+ const featOf = (f, vs) => f.params.map((p, i) => sizeOfValue(p.sort, vs[i]));
607
654
  function runEdges(ring) {
608
655
  const rand = rng(17), edges = new Map();
609
656
  const tables = new Map();
@@ -634,7 +681,7 @@ const lowers = (ms, e) => {
634
681
  }
635
682
  return false;
636
683
  };
637
- const sizeOfValue = (s, v) => (s === 'nat' ? v : s instanceof Data ? sizeOf(s, v) : 0);
684
+ const sizeOfValue = (s, v) => (s === 'nat' ? v : s === 'int' ? Math.max(0, v) : s instanceof Data ? sizeOf(s, v) : 0);
638
685
  function sizeBounds(t, sort, vars, envs, coef = 1) {
639
686
  const ms = vars.flatMap((v, i) => (measurable(v.sort) ? [i] : [])), at = [];
640
687
  for (const s of envs) {
@@ -679,18 +726,18 @@ function sizeLaws(l, ring) {
679
726
  walk(l.holds, o => { if (o.op === 'call' && !ring.includes(o.fn) && !seen.has(o.fn)) {
680
727
  seen.add(o.fn);
681
728
  const g = fnOf(o.fn);
682
- if (measurable(g.ret))
729
+ if (sized(g.ret))
683
730
  helpers.push(g);
684
731
  } });
685
732
  const out = [];
686
733
  const nat = (n) => ({ op: 'nat', value: n }), add = (a, b) => (b.op === 'nat' && b.value === 0 ? a : { op: 'add', a, b });
687
734
  for (const g of helpers.slice(0, 4)) {
688
735
  const vars = g.params.map((q, i) => ({ name: `${q.name}${i}`, sort: q.sort }));
689
- if (!vars.some(v => measurable(v.sort)))
736
+ if (!vars.some(v => sized(v.sort)))
690
737
  continue;
691
738
  const call = { op: 'call', fn: g.name, args: vars.map(v => ({ op: 'var', name: v.name })) }, envs = samples(vars, [], 160, 23);
692
739
  const twice = g.ret === 'nat' && vars.length === 1 && vars[0].sort === 'nat' ? upperBounds(sizeBounds(call, g.ret, vars, envs, 2), 1).filter(b => b.lo !== b.hi) : [];
693
- for (const b of [...upperBounds(sizeBounds(call, g.ret, vars, envs)), ...twice]) {
740
+ for (const b of [...upperBounds(sizeBounds(call, g.ret, vars, envs)), ...twice].filter(b => b.of.every(i => sized(vars[i].sort)))) {
694
741
  const lhs0 = b.coef === 1 ? sizeX(g.ret, call) : { op: 'mul', k: b.coef, a: sizeX(g.ret, call) };
695
742
  const sum = b.of.map(i => sizeX(vars[i].sort, { op: 'var', name: vars[i].name })).reduce((a, c) => ({ op: 'add', a, b: c }));
696
743
  const lhs = add(lhs0, nat(Math.max(0, -b.hi))), rhs = add(sum, nat(Math.max(0, b.hi)));
@@ -1848,6 +1895,15 @@ function schemes(p, l) {
1848
1895
  go(t.else, env, [...guard, { op: 'not', x: c }], through);
1849
1896
  return;
1850
1897
  }
1898
+ // (and a condition's choice on Bool, as termination reads it: core/data.ts's whenOf)
1899
+ const w = m && x.op === 'or' ? whenOf(x) : undefined;
1900
+ if (w) {
1901
+ const c = encY(p, w.c, env);
1902
+ go(w.c, env, guard, through);
1903
+ go(w.a, env, [...guard, c], through);
1904
+ go(w.b, env, [...guard, { op: 'not', x: c }], through);
1905
+ return;
1906
+ }
1851
1907
  if (t.op === 'call' && t.fn === f.name) {
1852
1908
  const subst = {};
1853
1909
  let ok = true;
@@ -313,6 +313,7 @@ function houdiniList(r, part, cands, params) {
313
313
  // is proven first, then each dropped in turn while the laws stay proven without it.
314
314
  // `first`: the laws' verdict on r alone, when the caller has it.
315
315
  export function discover(r, laws, stepLaws = [], first) {
316
+ r = r.withSumsOf(laws, stepLaws);
316
317
  return quietly(() => discoverSearch(r, laws, stepLaws, first ?? proveSteps(r, laws, stepLaws, { search: false })));
317
318
  }
318
319
  function discoverSearch(r, laws, stepLaws, first) {
@@ -618,6 +618,7 @@ export declare class Rule<P extends Obj = {}, I extends Obj = {}, S extends Obj
618
618
  private lawOf;
619
619
  private someOf;
620
620
  private divides;
621
+ withSumsOf(...xs: unknown[]): this;
621
622
  dividesBy(...ks: number[]): this;
622
623
  withDivisors(...ks: number[]): this;
623
624
  private kinds?;
@@ -679,6 +680,7 @@ export declare class Rule<P extends Obj = {}, I extends Obj = {}, S extends Obj
679
680
  [k in keyof P]: Raw;
680
681
  }): Record<string, Record<string, number>>;
681
682
  kindsOfState(): [string, Kind<unknown>][];
683
+ kindsOfCells(): [string, Kind<unknown>][];
682
684
  randomParams(rand: Rand, bound: number): Record<string, number>;
683
685
  private paramValues;
684
686
  randomInput(rand: Rand, bound: number, ps?: Record<string, number>): Request;
@@ -839,6 +841,11 @@ export type Verdict = {
839
841
  found?: Found;
840
842
  witnesses?: Record<string, string>;
841
843
  k?: number;
844
+ assumes?: Assumes;
845
+ };
846
+ export type Assumes = {
847
+ states: 'reachable';
848
+ laws: string[];
842
849
  };
843
850
  export type Found = {
844
851
  laws?: {
@@ -858,6 +865,7 @@ export type ProveOptions = {
858
865
  ms?: number;
859
866
  cycles?: boolean;
860
867
  };
868
+ from?: 'reachable' | 'any';
861
869
  };
862
870
  export declare class Unproven extends Error {
863
871
  readonly verdict: Verdict;
package/dist/core/dsl.js CHANGED
@@ -16,7 +16,7 @@
16
16
  // A step returns its updates as one object: every right-hand side reads the state before the step, as the kernel and
17
17
  // both runtimes do.
18
18
  import { argsKey, machineTerms, carriedView, compileFunction, divName, divisor, divisorsIn, evalC, evalE, interpret, isArithmetic, loadJs, modName, numbersOf, pairedArgs, seeded, withArithmetic } from "./machine.js";
19
- import { allowed, keysOf, requestEnv, watch } from "./watch.js";
19
+ import { allowed, keysOf, requestEnv, watch, watchWork } from "./watch.js";
20
20
  import { someHolds, substVars, substVarsE } from "./exists.js";
21
21
  import { check, checkRecur, foldObligations, loopObligations, substC, sumMachine } from "../kernel/kernel.js";
22
22
  import { certLoop, clock, counted, factsFor, fullRate, grow, proveLaws, proveLiveness, proveStepLaws, usualProof, withDeadline } from "../kernel/prove.js";
@@ -1900,10 +1900,14 @@ export class Rule {
1900
1900
  divides(x) {
1901
1901
  if (this.spec.arith)
1902
1902
  divisorsIn([x], this.spec.arith);
1903
- for (const n of Object.keys(sumsIn([x]) ?? {}))
1904
- (this.spec.sumsRead ??= new Set()).add(n);
1905
1903
  return x;
1906
1904
  }
1905
+ // The same rule declaring every sum over a map's keys these read (laws, step laws, a liveness, a decision's goal), as
1906
+ // each prover entry takes it; this rule itself unchanged. The rule where they read none it doesn't already declare.
1907
+ withSumsOf(...xs) {
1908
+ const had = this.spec.sumsRead ?? new Set(), names = Object.keys(sumsIn(xs) ?? {}).filter(n => !had.has(n));
1909
+ return names.length ? this.with({ sumsRead: new Set([...had, ...names]) }) : this;
1910
+ }
1907
1911
  // Divide by these too (inferLaws' candidates): the machine declares div$k and mod$k for each.
1908
1912
  dividesBy(...ks) { for (const k of ks)
1909
1913
  (this.spec.arith ??= new Set()).add(divisor(k, 'dividesBy')); return this; }
@@ -2011,7 +2015,7 @@ export class Rule {
2011
2015
  const listed = lists.flatMap(l => l.equationsAt(uniqueTerms([l.len, l.len.minus(1), ...keysRead([...hyps, t], l.maps)])).map(c => c.c));
2012
2016
  const goal = this.divides({ name, hyps: [...listed, ...hyps, { op: 'not', x: t }] });
2013
2017
  const facts = this.spec.fns?.length || this.spec.facts?.length || this.spec.arith?.size ? factsFor(this.machine, goal) : [];
2014
- const d = { name, rule: this, given: hyps, then: t, goal: { name, hyps: [...facts, ...goal.hyps] } };
2018
+ const d = { name, rule: this.withSumsOf(goal), given: hyps, then: t, goal: { name, hyps: [...facts, ...goal.hyps] } };
2015
2019
  if ([...(Array.isArray(g) ? g : [g]).map(c => c.c), t].some(quantifiedIn)) {
2016
2020
  const conds = (e) => { const own = given(e); return { given$: all(...(Array.isArray(own) ? own : [own])), then$: then(e) }; };
2017
2021
  const r = (this.spec.step ? this : this.step(() => ({}))).flags(conds);
@@ -2267,6 +2271,9 @@ export class Rule {
2267
2271
  // interpreter evaluates (core/watch.ts's verdicts, over the same keys). A law that says something other than its
2268
2272
  // callback, or a step that writes something other than it means, is reported with the state it shows at.
2269
2273
  crossCheck(laws, stepLaws = [], opts = {}) {
2274
+ const summed = this.withSumsOf(laws, stepLaws);
2275
+ if (summed !== this)
2276
+ return summed.crossCheck(laws, stepLaws, opts);
2270
2277
  const s = this.spec, m = this.machine, run = interpret(m), bound = opts.bound ?? 4, rand = opts.rand ?? seeded(7);
2271
2278
  let checked = 0;
2272
2279
  const at = (what, params, st, input) => `${what}: params ${JSON.stringify(params)}, state ${JSON.stringify(this.decode(st))}${input ? `, request ${JSON.stringify(numbersOf(input))}` : ''}`;
@@ -2355,6 +2362,9 @@ export class Rule {
2355
2362
  Object.assign(written, k.store(n, updates[n]));
2356
2363
  } });
2357
2364
  for (const n of Object.keys(st.scalars)) {
2365
+ // (a sum over a map's keys: no callback writes it; the runtimes keep it exact, kernel.ts's sumMachine)
2366
+ if (m.sums && n in m.sums)
2367
+ continue;
2358
2368
  const u = written[n], got = next.scalars[n], want = u === undefined ? st.scalars[n] : valOf(u);
2359
2369
  if (want === undefined)
2360
2370
  continue;
@@ -2502,6 +2512,8 @@ export class Rule {
2502
2512
  }
2503
2513
  // The state's variables declared with a kind (a yes/no, a choice, an integer...), with their kinds.
2504
2514
  kindsOfState() { return this.spec.kinded ?? []; }
2515
+ // (the maps of a kind, and the kind of their cells)
2516
+ kindsOfCells() { return this.spec.cells ?? []; }
2505
2517
  // Random params and inputs that meet their kinds (not the user's `pre` or `assume`, which a caller checks).
2506
2518
  randomParams(rand, bound) { return this.withSkolems('params', Object.assign({}, ...this.spec.params.map(([n, k]) => k.random(n, rand, bound)))); }
2507
2519
  // The params' values by their kinds, as constants (what a fold that reads them is computed with).
@@ -2723,6 +2735,10 @@ const withKinds = (r, laws) => [...r.kindLaws().filter(k => !laws.some(l => l.na
2723
2735
  // it is found on any machine. (A stop at 150 ms of wall time left a false law to the kernel whenever the first run alone
2724
2736
  // took that long, a pause on a loaded container: core/pairs.test.ts's two groups, whose 944-hypothesis step goal then ran
2725
2737
  // out its 944 s, in 7 of 130 runs of the suite's pairs job on Modal.)
2738
+ // The tuples a law is read at count too (core/watch.ts's watchWork), at most `perTrial` for each trial a budget has: a law
2739
+ // about five keys read at every tuple of a run's keys, at every step of 2,400 deeper trials, is half an hour of a 600 s
2740
+ // search (sharded KV's); the runs that refute the pilot's broken variants read at most 2.2M of a budget's 6M.
2741
+ const perTrial = 10_000;
2726
2742
  const refuteBudget = { trials: 60, depth: 6, bound: 3 };
2727
2743
  // A request as a run's trace shows it: each map it carries as an object of its cells.
2728
2744
  const shownRequest = (input) => Object.fromEntries(Object.entries(input).map(([n, x]) => [n, typeof x === 'number' ? x : Object.fromEntries(x)]));
@@ -2767,8 +2783,9 @@ function refuteByRuns(r, laws, stepLaws = [], budget = refuteBudget) {
2767
2783
  let alone;
2768
2784
  const factsHold = (params) => (alone ??= facts.filter(f => !readsParams(f)).every(f => holds(f, params)))
2769
2785
  && facts.filter(readsParams).every(f => holds(f, params));
2786
+ const cap = watchWork.n + perTrial * budget.trials;
2770
2787
  try {
2771
- for (let trial = 0; trial < budget.trials; trial++) {
2788
+ for (let trial = 0; trial < budget.trials && watchWork.n <= cap; trial++) {
2772
2789
  // (`mixed`: the trials in turn at bounds 1 to 4, every fourth near)
2773
2790
  const bound = budget.mixed ? 1 + trial % 4 : budget.bound, guided = guides, near = budget.mixed && trial % 4 ? undefined : budget.near;
2774
2791
  const params = r.randomParams(rand, bound);
@@ -2786,7 +2803,7 @@ function refuteByRuns(r, laws, stepLaws = [], budget = refuteBudget) {
2786
2803
  for (const { w, on } of watching)
2787
2804
  if (!('then' in w) && !on.start(st))
2788
2805
  return broken(w, '@start', st);
2789
- for (let d = 0, tries = 0; d < budget.depth && tries < 40; tries++) {
2806
+ for (let d = 0, tries = 0; d < budget.depth && tries < 40 && watchWork.n <= cap; tries++) {
2790
2807
  const input = r.randomInput(rand, bound, params);
2791
2808
  if (near)
2792
2809
  for (const x of m.inputs)
@@ -2815,7 +2832,7 @@ function refuteByRuns(r, laws, stepLaws = [], budget = refuteBudget) {
2815
2832
  // variable of a kind is drawn as its kind draws (33 yes/nos drawn from 0..7 almost never make a lawful state).
2816
2833
  const steps1 = stepLaws.filter(sl => (sl.steps ?? 1) === 1), given = withKinds(r, laws);
2817
2834
  const wide = Object.keys(m.state).length + m.inputs.length >= 32, lawsHere = wide ? given : [], kinded = wide ? r.kindsOfState() : [];
2818
- for (let trial = 0; budget.states !== false && !m.history && (steps1.length || lawsHere.length) && trial < budget.trials * 4; trial++) {
2835
+ for (let trial = 0; budget.states !== false && !m.history && (steps1.length || lawsHere.length) && trial < budget.trials * 4 && watchWork.n <= cap; trial++) {
2819
2836
  const params = r.randomParams(rand, bound);
2820
2837
  if (m.pre && !evalC(m.pre, params, { scalars: {}, maps: {} }, m) || !factsHold(params))
2821
2838
  continue;
@@ -2850,6 +2867,7 @@ const refutedVerdict = (out) => ({ proven: false, checked: false, goal: out.goal
2850
2867
  const noting = (r, ...xs) => { const ks = divisorsIn(xs); if (ks.size)
2851
2868
  r.dividesBy(...ks); return r; };
2852
2869
  export function proveRule(r, laws, opts = {}) {
2870
+ r = r.withSumsOf(laws);
2853
2871
  noting(r, laws);
2854
2872
  const refuted = refuteByRuns(r, laws);
2855
2873
  // A state the laws allow whose step breaks one, with no run to it (a wide rule's: what the kernel's step goal would end
@@ -2862,6 +2880,7 @@ export function proveRule(r, laws, opts = {}) {
2862
2880
  return searched(r, laws, [], v, opts);
2863
2881
  }
2864
2882
  export function proveSteps(r, laws, stepLaws, opts = {}) {
2883
+ r = r.withSumsOf(laws, stepLaws);
2865
2884
  noting(r, laws, stepLaws);
2866
2885
  const refuted = refuteByRuns(r, laws, stepLaws);
2867
2886
  // (a step law broken from a state the laws allow, with no run to it: the laws may need an invariant there, or the run
@@ -2901,7 +2920,8 @@ function stepGhosts(m, stepLaws) {
2901
2920
  // recurrences or carried lists (the rule made again with them), then invariants over what it then is. The verdict is the
2902
2921
  // prover's on the laws with what was found; when nothing is found, the prover's own (with why).
2903
2922
  function searched(r, laws, stepLaws, v, opts) {
2904
- if ((v.proven && v.checked) || opts.search === false || v.run || v.stuck === 'sat' && !/@step|@\d+ steps/.test(v.goal ?? ''))
2923
+ const any = opts.from === 'any';
2924
+ if ((v.proven && v.checked) || opts.search === false || v.run || v.stuck === 'sat' && (any || !/@step|@\d+ steps/.test(v.goal ?? '')))
2905
2925
  return v;
2906
2926
  // The deeper runs; then runs over small values (keys that meet, small params), whose requests meet their
2907
2927
  // assumption's equalities and clocks, or near the counterexample the verdict ends at.
@@ -2928,11 +2948,11 @@ function searched(r, laws, stepLaws, v, opts) {
2928
2948
  return refutedBy(shallow);
2929
2949
  // k-induction (core/kind.ts): the plain laws as one, over k = 2, 3, ... steps in a row, the rule's kinds assumed;
2930
2950
  // within a twentieth of the budget (at most 500 ms, counted so too).
2931
- if (!stepLaws.length && laws.every(l => !l.forall && !l.keys?.length && !l.some?.length)) {
2951
+ if (!any && !stepLaws.length && laws.every(l => !l.forall && !l.keys?.length && !l.some?.length)) {
2932
2952
  const ms = Math.min(500, total / 20), kinds = withKinds(r, []).filter(k => !laws.some(l => l.name === k.name));
2933
2953
  const kd = counted(fullRate, () => proveKInduction(r.machine, kinds, conjunction(laws), { ms }), true);
2934
2954
  if (kd.proven && kd.checked)
2935
- return { proven: true, checked: true, k: kd.k };
2955
+ return { proven: true, checked: true, k: kd.k, assumes: { states: 'reachable', laws: [] } };
2936
2956
  }
2937
2957
  let rule = r, lemmas;
2938
2958
  const { fns, lists } = r.parts;
@@ -2952,6 +2972,9 @@ function searched(r, laws, stepLaws, v, opts) {
2952
2972
  }
2953
2973
  // Laws about the ids a counter hands out (core/fresh.ts), within a tenth of what is left: the laws with them, then
2954
2974
  // the invariant search with them given.
2975
+ // (each found invariant proven from init: none where the step laws hold from any state)
2976
+ if (any)
2977
+ return { ...v, why: [v.why, 'no invariant searched for: {from: \'any\'}'].filter(Boolean).join('; ') };
2955
2978
  let fresh = [];
2956
2979
  if (Object.keys(rule.machine.maps ?? {}).length && until - clock() - tail > 1000) {
2957
2980
  const fm = rule.machine, share = (until - clock() - tail) / 10;
@@ -2959,7 +2982,7 @@ function searched(r, laws, stepLaws, v, opts) {
2959
2982
  if (fresh.length) {
2960
2983
  const given = [...withKinds(rule, laws), ...fresh.map(f => f.law)], out = withDeadline(clock() + share, () => (stepLaws.length ? proveStepLaws(fm, given, stepLaws) : proveLaws(fm, given)));
2961
2984
  if (out.proven && out.checked)
2962
- return { proven: true, checked: true, found: { laws: fresh, ...(lemmas ? { lemmas } : {}) } };
2985
+ return { proven: true, checked: true, found: { laws: fresh, ...(lemmas ? { lemmas } : {}) }, assumes: reachableBy(fresh) };
2963
2986
  }
2964
2987
  }
2965
2988
  const ms = until - clock() - tail;
@@ -2975,7 +2998,7 @@ function searched(r, laws, stepLaws, v, opts) {
2975
2998
  if (inf2.proven && inf2.checked) {
2976
2999
  const { found, stats: _s2, ...verdict } = inf2;
2977
3000
  void _s2;
2978
- return { ...verdict, found: { laws: [...fresh, ...found], ...(lemmas ? { lemmas } : {}) } };
3001
+ return { ...verdict, found: { laws: [...fresh, ...found], ...(lemmas ? { lemmas } : {}) }, ...withAssumes([...fresh, ...found]) };
2979
3002
  }
2980
3003
  }
2981
3004
  // (a step law's ghost: at most 10 s of it, as its goals cost more than the laws')
@@ -2986,9 +3009,13 @@ function searched(r, laws, stepLaws, v, opts) {
2986
3009
  }
2987
3010
  const { found, stats: _stats, ...verdict } = inf;
2988
3011
  void _stats;
2989
- return { ...verdict, found: { laws: [...fresh, ...found], ...(lemmas ? { lemmas } : {}) } };
3012
+ return { ...verdict, found: { laws: [...fresh, ...found], ...(lemmas ? { lemmas } : {}) }, ...withAssumes([...fresh, ...found]) };
2990
3013
  }
3014
+ // What a verdict proven with these found laws rests on: the states reachable from init (each found law is proven so).
3015
+ const reachableBy = (found) => ({ states: 'reachable', laws: found.map(f => f.text) });
3016
+ const withAssumes = (found) => (found.length ? { assumes: reachableBy(found) } : {});
2991
3017
  export function proveLeadsTo(r, laws, l, opts = {}) {
3018
+ r = r.withSumsOf(laws, l);
2992
3019
  noting(r, laws, l);
2993
3020
  if (laws.some(law => law.some?.length))
2994
3021
  throw new Error(`${r.machine.name}: a law with "there exists" goes to proveRule or proveSteps; a liveness takes plain laws (the ones its proof printed, Verdict.witnesses)`);
@@ -3019,8 +3046,9 @@ export function proveLeadsTo(r, laws, l, opts = {}) {
3019
3046
  f = g2;
3020
3047
  }
3021
3048
  }
3049
+ const helpers = [...fresh, ...(f.laws ?? []).map((law, i) => ({ law, text: f.found?.laws[i] ?? law.name }))];
3022
3050
  return { proven: f.proven, checked: f.checked, ...(f.goal ? { goal: f.goal, stuck: f.stuck } : {}), ...(f.witness ? { witness: f.witness } : {}), ...(f.why ? { why: f.why } : {}),
3023
- ...(f.found ? { found: { rank: f.found.rank, ...(f.laws?.length || fresh.length ? { laws: [...fresh, ...(f.laws ?? []).map((law, i) => ({ law, text: f.found.laws[i] ?? law.name }))] } : {}) } } : {}) };
3051
+ ...(f.found ? { found: { rank: f.found.rank, ...(helpers.length ? { laws: helpers } : {}) } } : {}), ...(f.proven ? withAssumes(helpers) : {}) };
3024
3052
  }
3025
3053
  const out = proveLiveness(r.machine, withKinds(r, laws), l);
3026
3054
  return verdictOf(out);
@@ -0,0 +1,47 @@
1
+ import type { Kind, Rule } from './dsl.js';
2
+ import { type Rand } from './machine.js';
3
+ import { type ExtractOptions, type Extraction } from './extract.js';
4
+ type Mod = Record<string, any>;
5
+ export type EffectOptions = ExtractOptions & {
6
+ effect: Mod;
7
+ modules?: Record<string, unknown>;
8
+ };
9
+ export type Runner = {
10
+ run: (eff: unknown, now?: number) => unknown;
11
+ exit: (eff: unknown, now: number) => {
12
+ ok: true;
13
+ value: unknown;
14
+ } | {
15
+ ok: false;
16
+ error: string;
17
+ };
18
+ get: (mod: string, ref: unknown) => unknown;
19
+ set: (mod: string, ref: unknown, v: unknown) => unknown;
20
+ };
21
+ export declare function runner(E: Mod): Runner;
22
+ export declare function extractEffect(code: string, opts: EffectOptions): Extraction;
23
+ export type Service<S> = {
24
+ effect: Mod;
25
+ make: (params: Record<string, unknown>) => unknown;
26
+ request: (service: S, input: Record<string, unknown>, params: Record<string, unknown>) => unknown;
27
+ observe?: (service: S, result: any, input: Record<string, unknown>) => unknown;
28
+ view?: (state: Record<string, unknown>, input: Record<string, unknown>) => Record<string, unknown>;
29
+ now?: string;
30
+ };
31
+ export declare function conforms<S>(r: Rule, svc: Service<S>, opts: {
32
+ draw: (rand: Rand) => Record<string, unknown>;
33
+ params?: (rand: Rand) => Record<string, unknown>;
34
+ runs?: number;
35
+ depth?: number;
36
+ seed?: number;
37
+ }): {
38
+ checked: number;
39
+ failure?: string;
40
+ };
41
+ export declare function fromSchema(schema: {
42
+ ast: unknown;
43
+ fields?: Record<string, {
44
+ ast: unknown;
45
+ }>;
46
+ }): Kind<any>;
47
+ export {};