gdp-wired 0.30.1 → 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,6 +83,13 @@ 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`),
@@ -473,7 +480,7 @@ The npm package is built from `core/`, `kernel/` and `lean-kernel/` alone; nothi
473
480
 
474
481
  The npm package is the library: the builders (`gdp-wired`), the runtimes (`gdp-wired/machine`), composition
475
482
  (`gdp-wired/compose`), XState machines as charts (`gdp-wired/xstate`), rules read from the code (`gdp-wired/extract`, with
476
- `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
477
484
  inference (`gdp-wired/infer`), the
478
485
  Lean export (`gdp-wired/lean`), the kernel (`gdp-wired/kernel`), the prover (`gdp-wired/prove`), the derivation checker
479
486
  and solver (`gdp-wired/check`, `gdp-wired/solver`). Everything else here (examples, comparisons, the Lean twin, the GPU
@@ -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;
@@ -680,6 +680,7 @@ export declare class Rule<P extends Obj = {}, I extends Obj = {}, S extends Obj
680
680
  [k in keyof P]: Raw;
681
681
  }): Record<string, Record<string, number>>;
682
682
  kindsOfState(): [string, Kind<unknown>][];
683
+ kindsOfCells(): [string, Kind<unknown>][];
683
684
  randomParams(rand: Rand, bound: number): Record<string, number>;
684
685
  private paramValues;
685
686
  randomInput(rand: Rand, bound: number, ps?: Record<string, number>): Request;
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";
@@ -2512,6 +2512,8 @@ export class Rule {
2512
2512
  }
2513
2513
  // The state's variables declared with a kind (a yes/no, a choice, an integer...), with their kinds.
2514
2514
  kindsOfState() { return this.spec.kinded ?? []; }
2515
+ // (the maps of a kind, and the kind of their cells)
2516
+ kindsOfCells() { return this.spec.cells ?? []; }
2515
2517
  // Random params and inputs that meet their kinds (not the user's `pre` or `assume`, which a caller checks).
2516
2518
  randomParams(rand, bound) { return this.withSkolems('params', Object.assign({}, ...this.spec.params.map(([n, k]) => k.random(n, rand, bound)))); }
2517
2519
  // The params' values by their kinds, as constants (what a fold that reads them is computed with).
@@ -2733,6 +2735,10 @@ const withKinds = (r, laws) => [...r.kindLaws().filter(k => !laws.some(l => l.na
2733
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
2734
2736
  // took that long, a pause on a loaded container: core/pairs.test.ts's two groups, whose 944-hypothesis step goal then ran
2735
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;
2736
2742
  const refuteBudget = { trials: 60, depth: 6, bound: 3 };
2737
2743
  // A request as a run's trace shows it: each map it carries as an object of its cells.
2738
2744
  const shownRequest = (input) => Object.fromEntries(Object.entries(input).map(([n, x]) => [n, typeof x === 'number' ? x : Object.fromEntries(x)]));
@@ -2777,8 +2783,9 @@ function refuteByRuns(r, laws, stepLaws = [], budget = refuteBudget) {
2777
2783
  let alone;
2778
2784
  const factsHold = (params) => (alone ??= facts.filter(f => !readsParams(f)).every(f => holds(f, params)))
2779
2785
  && facts.filter(readsParams).every(f => holds(f, params));
2786
+ const cap = watchWork.n + perTrial * budget.trials;
2780
2787
  try {
2781
- for (let trial = 0; trial < budget.trials; trial++) {
2788
+ for (let trial = 0; trial < budget.trials && watchWork.n <= cap; trial++) {
2782
2789
  // (`mixed`: the trials in turn at bounds 1 to 4, every fourth near)
2783
2790
  const bound = budget.mixed ? 1 + trial % 4 : budget.bound, guided = guides, near = budget.mixed && trial % 4 ? undefined : budget.near;
2784
2791
  const params = r.randomParams(rand, bound);
@@ -2796,7 +2803,7 @@ function refuteByRuns(r, laws, stepLaws = [], budget = refuteBudget) {
2796
2803
  for (const { w, on } of watching)
2797
2804
  if (!('then' in w) && !on.start(st))
2798
2805
  return broken(w, '@start', st);
2799
- 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++) {
2800
2807
  const input = r.randomInput(rand, bound, params);
2801
2808
  if (near)
2802
2809
  for (const x of m.inputs)
@@ -2825,7 +2832,7 @@ function refuteByRuns(r, laws, stepLaws = [], budget = refuteBudget) {
2825
2832
  // variable of a kind is drawn as its kind draws (33 yes/nos drawn from 0..7 almost never make a lawful state).
2826
2833
  const steps1 = stepLaws.filter(sl => (sl.steps ?? 1) === 1), given = withKinds(r, laws);
2827
2834
  const wide = Object.keys(m.state).length + m.inputs.length >= 32, lawsHere = wide ? given : [], kinded = wide ? r.kindsOfState() : [];
2828
- 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++) {
2829
2836
  const params = r.randomParams(rand, bound);
2830
2837
  if (m.pre && !evalC(m.pre, params, { scalars: {}, maps: {} }, m) || !factsHold(params))
2831
2838
  continue;
@@ -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 {};