gdp-wired 0.38.0 → 0.40.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/dist/core/dsl.js CHANGED
@@ -16,11 +16,12 @@
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 { searchCounted } from "./counts.js";
19
+ import { env as knobs } from "./solver.js";
19
20
  import { argsKey, machineTerms, carriedView, compileFunction, divName, divisor, divisorsIn, evalC, evalE, interpret, isArithmetic, loadJs, modName, numbersOf, pairedArgs, seeded, withArithmetic } from "./machine.js";
20
21
  import { allowed, keysOf, requestEnv, watch, watchWork } from "./watch.js";
21
- import { someHolds, substVars, substVarsE } from "./exists.js";
22
+ import { ghostOf, proveSome, someHolds, substVars, substVarsE } from "./exists.js";
22
23
  import { check, checkRecur, foldObligations, loopObligations, substC, sumMachine } from "../kernel/kernel.js";
23
- import { certLoop, clock, counted, factsFor, fullRate, grow, proveLaws, proveLiveness, proveSetFast, proveStepLaws, usualProof, withDeadline, withWall } from "../kernel/prove.js";
24
+ import { certLoop, clock, counted, factsFor, fullRate, grow, proveLaw, proveLaws, proveLiveness, proveSetFast, proveStepLaws, usualProof, withDeadline, withWall } from "../kernel/prove.js";
24
25
  import { certCyclic, certOn, crossCyclic, cyclicOn, foldNodes, proveCyclic, quietly, recurNodes, translatedProof, uncovered } from "./cyclic.js";
25
26
  import { discover } from "./discover.js";
26
27
  import { inferLaws } from "./infer.js";
@@ -3049,9 +3050,24 @@ function searchedUntil(r, laws, stepLaws, v, opts, until) {
3049
3050
  return { proven: true, checked: true, found: { laws: fresh, ...(lemmas ? { lemmas } : {}) }, assumes: reachableBy(fresh) };
3050
3051
  }
3051
3052
  }
3052
- const ms = until - clock() - tail;
3053
+ let ms = until - clock() - tail;
3053
3054
  if (ms < 500)
3054
3055
  return v;
3056
+ // (a law with "there exists" about no key: its ghost chosen with the engine's cubes kept, within half of it)
3057
+ if (!stepLaws.length && laws.some(l => l.some?.length) && laws.every(l => !l.some?.length || !l.forall)) {
3058
+ let c;
3059
+ try {
3060
+ c = withWall(performance.now() + ms / 2, () => withDeadline(clock() + ms / 2, () => someCone(rule, laws, ms / 2)));
3061
+ }
3062
+ catch (e) {
3063
+ if (knobs.GDP_EXISTS_LOG === '1')
3064
+ console.error(`exists: cone failed: ${String(e.stack ?? e).slice(0, 600)}`);
3065
+ }
3066
+ if (c)
3067
+ return { ...c, found: { ...c.found, ...(lemmas ? { lemmas } : {}) } };
3068
+ if ((ms = until - clock() - tail) < 500)
3069
+ return v;
3070
+ }
3055
3071
  // (the search's own wall ends where the tail begins: the last bounded runs keep it)
3056
3072
  const tailAt = () => performance.now() + Math.max(0, until - tail - clock());
3057
3073
  const inf = withWall(tailAt(), () => inferLaws(rule, [...fresh.map(f => f.law), ...laws], stepLaws, { ms, ...(rule === r && !fresh.length ? { first: v } : {}) }));
@@ -3077,6 +3093,51 @@ function searchedUntil(r, laws, stepLaws, v, opts, until) {
3077
3093
  void _stats;
3078
3094
  return { ...verdict, found: { laws: [...fresh, ...found], ...(lemmas ? { lemmas } : {}) }, ...withAssumes([...fresh, ...found]) };
3079
3095
  }
3096
+ // A law with "there exists" about no key, which the join can't take as its goal: its witness core/exists.ts's ghostOf;
3097
+ // the engine's minimal ∀ cubes of two literals (core/infer.ts's `cubes`, its template two keys at the bound value's
3098
+ // places, framed by the law's conjuncts that read the value and no map), each kept where it is proven from the kept ones
3099
+ // and itself (IC3's relative induction, its cone), again while more are kept; then the laws with those kept. (A law about
3100
+ // every key goes the usual way: its ghost maps' goals ran past the search's wall here, firewall's, and won nothing.)
3101
+ function someCone(r, laws0, ms) {
3102
+ const until = clock() + ms, m = r.machine, yes = { op: '<=', a: { op: 'const', value: 0 }, b: { op: 'const', value: 0 } };
3103
+ const laws = laws0.map(l => (l.some?.length && !l.forall && !l.witness ? { ...l, witness: ghostOf(m, l) } : l));
3104
+ if (laws.some(l => l.some?.length && !l.forall && !l.witness))
3105
+ return undefined;
3106
+ const named = (d, l) => l.some.some(x => JSON.stringify(d).includes(`"name":${JSON.stringify(x)}`));
3107
+ const shape = (l) => (l.some?.length ? shapeOf(l) : l);
3108
+ // (two keys at the bound value's places, the law's conjuncts that read the value and no map their frame)
3109
+ function shapeOf(l) {
3110
+ const x = l.some[0], at = (c, k) => substVars(c, { [x]: { op: 'var', name: k } }), ks = ['k$some', 'k2$some'];
3111
+ const cs = l.holds.op === 'and' ? l.holds.xs : [l.holds], frame = cs.filter(c => named(c, l) && !JSON.stringify(c).includes('"op":"get"')), rest = cs.filter(c => !frame.includes(c));
3112
+ return { name: l.name, forall: ks[0], keys: [ks[1]], holds: { op: 'or', xs: [{ op: 'not', x: { op: 'and', xs: ks.flatMap(k => frame.map(c => at(c, k))) } }, ...ks.flatMap(k => rest.map(c => at(c, k))), yes] } };
3113
+ }
3114
+ const cubes = [...withKinds(r, []), ...inferLaws(r, laws.map(shape), [], { cubes: 2, ms: Math.min(10_000, ms / 3), first: { proven: false, checked: false } }).found.map(f => f.law)];
3115
+ const kept = [], tried = new Map();
3116
+ for (let grew = true; grew && clock() < until;) {
3117
+ grew = false;
3118
+ for (const c of cubes) {
3119
+ if (kept.includes(c) || tried.get(c.name) === kept.length || clock() > until)
3120
+ continue;
3121
+ tried.set(c.name, kept.length);
3122
+ // (a cube the kernel refuses to state, one past its key rules, is never kept)
3123
+ let ok = false;
3124
+ try {
3125
+ ok = withDeadline(Math.min(until, clock() + 1000), () => proveLaw(m, [...kept, c], kept.length)).proven;
3126
+ }
3127
+ catch { /* not kept */ }
3128
+ if (ok) {
3129
+ kept.push(c);
3130
+ grew = true;
3131
+ }
3132
+ }
3133
+ }
3134
+ if (knobs.GDP_EXISTS_LOG === '1')
3135
+ console.error(`exists: cone ${kept.length} of ${cubes.length} kept: ${kept.map(l => l.name).join('; ').slice(0, 2000)}`);
3136
+ if (clock() > until)
3137
+ return undefined;
3138
+ const v = verdictOf(proveSome(m, [...laws, ...kept.filter(c => !laws.some(l => l.name === c.name))]));
3139
+ return v.proven && v.checked ? { ...v, found: { laws: kept.map(l => ({ law: l, text: l.name })) }, ...withAssumes(kept.map(l => ({ text: l.name }))) } : undefined;
3140
+ }
3080
3141
  // What a verdict proven with these found laws rests on: the states reachable from init (each found law is proven so).
3081
3142
  const reachableBy = (found) => ({ states: 'reachable', laws: found.map(f => f.text) });
3082
3143
  const withAssumes = (found) => (found.length ? { assumes: reachableBy(found) } : {});
@@ -6,7 +6,8 @@ export declare const namesOf: (t: E | C) => string[];
6
6
  export declare function groupsOf(vars: string[]): Group[];
7
7
  export declare function substVarsE(e: E, s: Record<string, E>): E;
8
8
  export declare function substVars(c: C, s: Record<string, E>): C;
9
- export declare function small(m: Machine, p: Env, b: number, cap?: number, work?: number): State[];
9
+ export declare function small(m: Machine, p: Env, b: number, cap?: number, work?: number, walks?: number): State[];
10
+ export declare function ghostOf(m: Machine, law: Law): SomeWitness | undefined;
10
11
  export declare function holdsAt(m: Machine, law: Law, p: Env, st: State, b: number): boolean;
11
12
  export declare function someHolds(body: C, vars: string[], env: Env, st: State, m: Machine): {
12
13
  holds: boolean;
@@ -156,8 +156,11 @@ function solved(atoms, g) {
156
156
  const atomsOf2 = (c) => (c.op === 'and' || c.op === 'or' ? c.xs.flatMap(atomsOf2) : c.op === 'not' ? atomsOf2(c.x) : [c]);
157
157
  // --- the small instances (core/counts.ts's filter and the ghost maps' below) --------------------------------------------------------------------------------------------------
158
158
  // Every state reached from the start with the params at `p`, each input below `b`, each carried map a subset of 0 .. b − 1.
159
- // (at most `cap` states, and `work` steps tried: a wide request space ends the BFS early, its states still reachable)
160
- export function small(m, p, b, cap = 3000, work = 300_000) {
159
+ // (at most `cap` states, and `work` steps tried: a wide request space ends the BFS early, its states still reachable;
160
+ // then, with `walks` steps more, random walks past it, each step a change of a kind (the variables it writes) chosen
161
+ // alike among those a few requests make: an action the BFS's levels never reach, a leader past a majority's votes, is
162
+ // taken as often as any other)
163
+ export function small(m, p, b, cap = 3000, work = 300_000, walks = 0) {
161
164
  const run = interpret(m), start = run.init(p);
162
165
  const subsets = Array.from({ length: 1 << b }, (_, s) => new Map(Array.from({ length: b }, (_, i) => i).filter(i => (s >> i) & 1).map(i => [i, 1])));
163
166
  // (an input the assumption keeps below a few values, an action's, over all of them; the rest below b)
@@ -167,7 +170,8 @@ export function small(m, p, b, cap = 3000, work = 300_000) {
167
170
  reqs = reqs.flatMap(r => Array.from({ length: below(i) }, (_, x) => ({ ...r, [i]: x })));
168
171
  for (const c of m.inputMaps ?? [])
169
172
  reqs = reqs.flatMap(r => subsets.map(s => ({ ...r, [c]: s })));
170
- const seen = new Map([[key(start), start]]), queue = [start];
173
+ const idOf = (s) => key([s.scalars, Object.entries(s.maps).map(([n, cs]) => [n, [...cs].filter(([, x]) => x).sort((a, c) => a[0] - c[0])])]);
174
+ const seen = new Map([[idOf(start), start]]), queue = [start];
171
175
  while (queue.length && seen.size < cap && work > 0) {
172
176
  const st = queue.shift();
173
177
  for (const r of reqs) {
@@ -180,15 +184,75 @@ export function small(m, p, b, cap = 3000, work = 300_000) {
180
184
  catch {
181
185
  continue;
182
186
  }
183
- const id = key([next.scalars, Object.entries(next.maps).map(([n, cs]) => [n, [...cs].filter(([, x]) => x).sort((a, c) => a[0] - c[0])])]);
187
+ const id = idOf(next);
184
188
  if (!seen.has(id)) {
185
189
  seen.set(id, next);
186
190
  queue.push(next);
187
191
  }
188
192
  }
189
193
  }
194
+ if (!queue.length)
195
+ return [...seen.values()];
196
+ const cell = (s, n, x) => s.maps[n]?.get(x) ?? s.defaults?.[n] ?? 0;
197
+ const kindOf = (a, c) => [...Object.keys(c.scalars).filter(n => a.scalars[n] !== c.scalars[n]),
198
+ ...Object.keys(c.maps).filter(n => a.defaults?.[n] !== c.defaults?.[n] || [...a.maps[n]?.keys() ?? [], ...c.maps[n].keys()].some(x => cell(a, n, x) !== cell(c, n, x)))].join();
199
+ let seed = 7;
200
+ const rnd = (n) => { seed = (seed * 48271) % 2147483647; return seed % n; };
201
+ for (let t = 0; walks > 0 && seen.size < 2 * cap; t++) {
202
+ let st = t % 2 ? start : [...seen.values()][rnd(seen.size)];
203
+ for (let d = 0; d < 40 && walks > 0; d++) {
204
+ const by = new Map();
205
+ for (let i = 0; i < 48; i++, walks--) {
206
+ let next;
207
+ try {
208
+ next = run.step(p, st, reqs[rnd(reqs.length)]);
209
+ }
210
+ catch {
211
+ continue;
212
+ }
213
+ const kd = kindOf(st, next);
214
+ if (kd)
215
+ by.set(kd, [...by.get(kd) ?? [], next]);
216
+ }
217
+ if (!by.size)
218
+ break;
219
+ const ks = [...by.values()], at = ks[rnd(ks.length)];
220
+ st = at[rnd(at.length)];
221
+ const id = idOf(st);
222
+ if (!seen.has(id))
223
+ seen.set(id, st);
224
+ }
225
+ }
190
226
  return [...seen.values()];
191
227
  }
228
+ // A ghost for a law about no key with one value ∃x. P over maps (PCorrect's "some process not done, or its y is 1"): x a
229
+ // state variable that starts at 0 or a param (or one less) and after each step keeps its value while P still holds there
230
+ // after the step, else moves to a term the step reads a map at (the process before the one that stepped); the first
231
+ // whose P holds at every state of the small instances (each param 2 and 3), given as the law's witness, or none.
232
+ export function ghostOf(m, law) {
233
+ const x = law.some?.[0];
234
+ if (!x || law.forall || law.some.length !== 1 || x.endsWith('$neg') || !readsMaps(law.holds) || x in m.state)
235
+ return undefined;
236
+ const after = { vars: Object.fromEntries(Object.keys(m.state).map(n => [n, m.step.state?.[n] ?? v(n)])), flags: {},
237
+ maps: Object.fromEntries(Object.entries(m.step.maps ?? {}).map(([mp, w]) => [mp, (at) => ('each' in w ? substVarsE(w.value, { [w.each]: at }) : { op: 'if', c: { op: '=', a: at, b: w.key }, then: w.value, else: { op: 'get', map: mp, key: at } })])) };
238
+ const keep = substC(law.holds, after), ts = new Map(m.inputs.map(i => [key(v(i)), v(i)]));
239
+ walk([m.step, m.assume ?? null], o => { if (o.op === 'get' && namesOf(o.key).some(n => m.inputs.includes(n)))
240
+ ts.set(key(o.key), o.key); });
241
+ const starts = [k(0), ...m.params.flatMap(q => [v(q), sub(v(q), k(1))])];
242
+ for (const t of ts.values())
243
+ for (const start of starts) {
244
+ const step = { op: 'if', c: keep, then: v(x), else: t }, gm = { ...m, state: { ...m.state, [x]: start }, step: { ...m.step, state: { ...m.step.state, [x]: step } } };
245
+ const ok = [2, 3].every(q => { const ps = Object.fromEntries(m.params.map(p => [p, q])); try {
246
+ return small(gm, ps, 3, 3000, 100_000).every(st => holdsAt(gm, { ...law, some: undefined }, ps, st, 3));
247
+ }
248
+ catch {
249
+ return false;
250
+ } });
251
+ if (ok)
252
+ return { ghost: { [x]: { start, step } } };
253
+ }
254
+ return undefined;
255
+ }
192
256
  // A law at a state, its counts the state's, at every key below b.
193
257
  // (a state's view once: a law is read at every state, and every law at each)
194
258
  const views = new WeakMap();
@@ -159,6 +159,10 @@ type Try = {
159
159
  hs: Handler[];
160
160
  to: [Path, number, Kind][];
161
161
  ws: B[];
162
+ depth: number;
163
+ };
164
+ export type StoreVal = 'int' | 'float' | string[] | {
165
+ json: Record<string, string | string[]>;
162
166
  };
163
167
  export type StoreDecl = {
164
168
  get?: string[];
@@ -168,6 +172,16 @@ export type StoreDecl = {
168
172
  value?: 'int' | 'float' | 'str';
169
173
  attrs?: Record<string, null | boolean | number | string>;
170
174
  async?: Record<string, boolean>;
175
+ values?: Record<string, StoreVal>;
176
+ apart?: boolean;
177
+ nothrow?: boolean;
178
+ };
179
+ type JField = {
180
+ name: string;
181
+ opt?: boolean;
182
+ choice?: boolean;
183
+ vals?: string[];
184
+ out?: boolean;
171
185
  };
172
186
  export type StepOptions = {
173
187
  entry?: string | string[];
@@ -179,6 +193,8 @@ export type StepOptions = {
179
193
  failures?: 'refuse' | 'kept';
180
194
  onError?: 'refuse' | 'discard';
181
195
  domains?: Record<string, 'nat' | 'int'>;
196
+ defaults?: string[];
197
+ fields?: Record<string, null | boolean | number | string>;
182
198
  check?: {
183
199
  runs?: number;
184
200
  depth?: number;
@@ -244,6 +260,7 @@ type V = {
244
260
  patch?: Patch;
245
261
  ret?: SType;
246
262
  recv?: V;
263
+ nothrow?: boolean;
247
264
  } | {
248
265
  t: 'fn';
249
266
  id: string;
@@ -263,6 +280,10 @@ type V = {
263
280
  t: 'sattr';
264
281
  store: string;
265
282
  path: string;
283
+ } | {
284
+ t: 'val';
285
+ ty: string;
286
+ f: Map<string, V>;
266
287
  } | {
267
288
  t: 'tuple';
268
289
  xs: V[];
@@ -410,6 +431,8 @@ export type Leaf = {
410
431
  store?: string;
411
432
  tpl?: string;
412
433
  ordered?: boolean;
434
+ json?: JField[];
435
+ choice?: boolean;
413
436
  };
414
437
  export type PArg = {
415
438
  k: 'in';
@@ -427,6 +450,7 @@ export type PArg = {
427
450
  f: [string, PArg][];
428
451
  } | {
429
452
  k: 'inert';
453
+ dict?: boolean;
430
454
  } | {
431
455
  k: 'store';
432
456
  name: string;
@@ -533,11 +557,14 @@ export declare class Stepper {
533
557
  tpl: string;
534
558
  id: string;
535
559
  decl: MapDecl;
560
+ json?: JField[];
561
+ choice?: boolean;
536
562
  }>;
537
563
  readonly leasts: LeastRead[];
538
564
  frames: string[];
539
565
  fieldNames: Set<string>;
540
566
  readonly frozen: Set<string>;
567
+ readonly atDefault: Set<V>;
541
568
  readonly ints: Map<string, IntTy>;
542
569
  readonly paramsOut: B[];
543
570
  now?: Var;
@@ -579,6 +606,7 @@ export declare class Stepper {
579
606
  raise(p: Path, c: B, w: B, [t, i]: [Try, number], k: Kind, at: {
580
607
  p: string;
581
608
  }): void;
609
+ readonly frameLocals: Map<string, V>[];
582
610
  tryStmt(s: SS, p: Path): Flow;
583
611
  listOf(v: V, p: Path, at: SX, carried?: boolean): {
584
612
  id: string;
@@ -722,6 +750,19 @@ export declare class Stepper {
722
750
  callsOn(r: SRec, fields: string[]): string[];
723
751
  storeDecl(store: string): StoreDecl;
724
752
  storeCall(store: string, m: string, args: V[], kw: [string, V][], at: SX, p: Path, awaited: boolean): [V, Path];
753
+ readonly withBodies: {
754
+ body: SS[];
755
+ locals: Map<string, V>;
756
+ }[];
757
+ generatorCM(s: SS, p: Path): Flow | undefined;
758
+ valItem(m: Extract<V, {
759
+ t: 'val';
760
+ }>, k: V, x: SX, p: Path): [V, Path];
761
+ valCall(o: Extract<V, {
762
+ t: 'val';
763
+ }>, m: string, args: V[], kw: [string, V][], x: SX, p: Path): [V, Path];
764
+ json(q0: string, args: V[], kw: [string, V][], x: SX, p: Path): [V, Path];
765
+ valBin(op: string, a: V, b: V, x: SX, p: Path): V;
725
766
  calleeNames(x: SX): string[];
726
767
  match(list: string[] | undefined, names: string[]): string | undefined;
727
768
  skipped(names: string[]): boolean;
@@ -762,6 +803,7 @@ export declare class Stepper {
762
803
  floorDiv(a: N, k: number): N;
763
804
  compare(x: SX, p: Path): [V, Path];
764
805
  equal(a: V, b: V, at: SX, p: Path): B;
806
+ truth(x: SX, p: Path): [B, Path];
765
807
  boolOp(x: SX, p: Path): [V, Path];
766
808
  fstr(x: SX, p: Path): [V, Path];
767
809
  call(x: SX, p: Path, awaited: boolean): [V, Path];