gdp-wired 0.32.0 → 0.33.1

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.
@@ -1,4 +1,4 @@
1
- import type { C, E, Law, Machine } from '../core/machine.js';
1
+ import type { C, E, Law, Machine, MapUpdate } from '../core/machine.js';
2
2
  import { type Constraint, type Lin, type Step } from '../core/solver.js';
3
3
  export declare function unreachable(value: never): never;
4
4
  export type Tree = {
@@ -287,4 +287,48 @@ export declare function checkQMachine(m: QMachine, laws: QLaw[], trees: Record<s
287
287
  start: Tree;
288
288
  step: Tree;
289
289
  }>): boolean;
290
+ export type Count = {
291
+ v: string;
292
+ key: string;
293
+ below: E;
294
+ body: E;
295
+ };
296
+ export type CountInst = {
297
+ wit: string;
298
+ below: E;
299
+ terms: [number, string][];
300
+ unit: number;
301
+ };
302
+ export type CountedGoal = {
303
+ name: string;
304
+ hyps: C[];
305
+ counts: Count[];
306
+ };
307
+ export declare function countHyp(cs: Count[], i: CountInst): C | undefined;
308
+ export declare function countHyps(cs: Count[], is: CountInst[]): C[] | undefined;
309
+ export declare const witFresh: (hyps: C[], cs: Count[], is: CountInst[], w: string) => boolean;
310
+ export declare function countedOk(hyps: C[], cs: Count[], is: CountInst[]): boolean;
311
+ export declare function checkCounted(g: CountedGoal, cert: {
312
+ insts: CountInst[];
313
+ tree: Tree;
314
+ }): boolean;
315
+ export declare function countedGoal(g: CountedGoal, insts: CountInst[]): Goal | undefined;
316
+ export type GhostMap = {
317
+ start: number;
318
+ write: MapUpdate;
319
+ };
320
+ export type Ghosted = {
321
+ orig: Machine;
322
+ vars: Record<string, {
323
+ start: E;
324
+ step: E;
325
+ }>;
326
+ maps: Record<string, GhostMap>;
327
+ };
328
+ export declare function ghostedMachine(g: Ghosted): Machine;
329
+ export declare function ghostedOk(g: Ghosted): boolean;
330
+ export declare const checkGhostedLaws: (g: Ghosted, laws: Law[], proof: {
331
+ instances: Record<string, Instances>;
332
+ trees: Record<string, Tree>;
333
+ }) => boolean;
290
334
  export {};
@@ -50,13 +50,16 @@ export const canonFlip = (lin) => {
50
50
  export const atomOf = (lin, holds) => ({ lin: holds ? lin : add(k(1), scale(lin, -1)), label: '' });
51
51
  // Is lin <= 0 decided by the path? A constant atom decides itself.
52
52
  // Over the integers lin <= 0 fails exactly when 1 - lin <= 0 holds, so either atom decides the other.
53
+ // A form with a coefficient past a safe integer decides nothing: it may be a rounded difference, and its flip is
54
+ // rounded again (1 - (2^53 + 1) reads as the safe 1 - 2^53), so an atom about another form would decide it.
53
55
  function decide(lin, path) {
54
56
  let constant = true;
55
- for (const key in lin)
56
- if (key !== '1') {
57
+ for (const key in lin) {
58
+ if (!Number.isSafeInteger(lin[key]))
59
+ return undefined;
60
+ if (key !== '1')
57
61
  constant = false;
58
- break;
59
- }
62
+ }
60
63
  if (constant)
61
64
  return (lin['1'] ?? 0) <= 0;
62
65
  const direct = look(path, canon(lin));
@@ -124,14 +127,21 @@ export function linear(e, path) {
124
127
  memo.set(e, out);
125
128
  return out;
126
129
  }
130
+ // A form with a coefficient past a safe integer is no form: its float may be rounded, and every part is read through
131
+ // here, so no rounding inside a term goes unseen (core/check.ts refuses such rows too).
127
132
  function linearOf(e, path) {
133
+ const out = linearOp(e, path);
134
+ return out && safe(out) ? out : undefined;
135
+ }
136
+ const safe = (lin) => Object.values(lin).every(c => Number.isSafeInteger(c));
137
+ function linearOp(e, path) {
128
138
  switch (e.op) {
129
139
  case 'var': return e.name === '1' || /[*[\],:⟦]/.test(e.name) ? undefined : v(e.name); // those characters build cells, monomials and term columns
130
140
  case 'const': return k(e.value);
131
141
  case 'mul': {
132
142
  const a = linear(e.a, path);
133
- return a && scale(a, e.k);
134
- }
143
+ return a && Number.isSafeInteger(e.k) ? scale(a, e.k) : undefined;
144
+ } // (10 · 0.1 is a float 1)
135
145
  case 'prod': {
136
146
  const a = linear(e.a, path), b = linear(e.b, path);
137
147
  return a && b && times(a, b);
@@ -231,16 +241,23 @@ export function termRows(name, path) {
231
241
  // product is of its branch). Forgetting how monomials relate (x*x to x, say, or two monomials over cells the path
232
242
  // proves equal) only weakens what a leaf may use, so it stays sound; distributing is what proves spend <= m·count over
233
243
  // a node from the same law at its children.
244
+ // Every coefficient, product and partial sum a safe integer, else no product: a rounded product is past 2^53, but a
245
+ // monomial's other products could bring its sum back under it (and a square's form is the prover's, any float).
234
246
  function times(a, b) {
235
- const out = [];
247
+ const out = {};
236
248
  for (const [p, cp] of Object.entries(a))
237
249
  for (const [q, cq] of Object.entries(b)) {
238
250
  if (p.includes('⟦') || q.includes('⟦'))
239
251
  return undefined;
240
- const fs = [...(p === '1' ? [] : factorsOf(p)), ...(q === '1' ? [] : factorsOf(q))].sort();
241
- out.push({ [fs.length ? fs.join('*') : '1']: cp * cq });
252
+ const fs = [...(p === '1' ? [] : factorsOf(p)), ...(q === '1' ? [] : factorsOf(q))].sort(), key = fs.length ? fs.join('*') : '1', c = (out[key] ?? 0) + cp * cq;
253
+ if (!(Number.isSafeInteger(cp) && Number.isSafeInteger(cq) && Number.isSafeInteger(cp * cq) && Number.isSafeInteger(c)))
254
+ return undefined;
255
+ out[key] = c;
242
256
  }
243
- return add(...out);
257
+ for (const key in out)
258
+ if (out[key] === 0)
259
+ delete out[key];
260
+ return out;
244
261
  }
245
262
  // A name's factors: split at each '*' outside a cell's brackets (a cell's key may itself read a monomial).
246
263
  const factorMemo = new Map();
@@ -291,7 +308,10 @@ function comparisonOf(c, path) {
291
308
  const a = linear(c.a, path), b = linear(c.b, path);
292
309
  if (!a || !b)
293
310
  return undefined;
311
+ // A rounded difference gives no fact: one past 2^53 is refused as a row, but plus 1 it may be safe again.
294
312
  const ab = sub(a, b), ba = sub(b, a);
313
+ if (!safe(ab))
314
+ return undefined;
295
315
  if (c.op === '<=')
296
316
  return { when: [ab], unless: [[add(ba, k(1))]] };
297
317
  if (c.op === '<')
@@ -770,9 +790,10 @@ function inScope(what, ts, vars, maps = [], flags = []) {
770
790
  }
771
791
  }
772
792
  // A name the kernel's linear forms would read as something else: '1' is the constant, and '*', '[', ']', ',' and ':'
773
- // build monomials and cells. Such a name could never be proven about; refused instead, with its name.
774
- const plainName = (what, name) => { if (name === '1' || /[*[\],:]/.test(name))
775
- throw new Error(`${what}: the name ${name} is reserved (1, or * [ ] , :)`); };
793
+ // build monomials and cells; '#' marks the fresh name a law is proven at (k#, its key's), which a name of the machine or
794
+ // another key of the law would capture. Such a name could never be proven about; refused instead, with its name.
795
+ const plainName = (what, name) => { if (name === '1' || /[*[\],:#]/.test(name))
796
+ throw new Error(`${what}: the name ${name} is reserved (1, or * [ ] , : #)`); };
776
797
  const distinct = (what, names) => { const seen = new Set(); for (const name of names) {
777
798
  if (seen.has(name))
778
799
  throw new Error(`${what} declares ${name} twice`);
@@ -849,8 +870,11 @@ export function scope(m, laws = []) {
849
870
  for (const law of [...laws, ...facts]) {
850
871
  const what = facts.includes(law) ? `fact ${law.name}` : `law ${law.name}`;
851
872
  for (const key of [law.forall, ...(law.keys ?? [])])
852
- if (key && [...names, ...maps, ...carried, ...fns].includes(key))
853
- throw new Error(`${what}'s key ${key} is already a name of ${m.name}`);
873
+ if (key) {
874
+ plainName(what, key);
875
+ if ([...names, ...maps, ...carried, ...fns].includes(key))
876
+ throw new Error(`${what}'s key ${key} is already a name of ${m.name}`);
877
+ }
854
878
  if (law.keys?.length && (!law.forall || new Set([law.forall, ...law.keys]).size !== law.keys.length + 1))
855
879
  throw new Error(`${what}: further keys come with a first, each a different name`);
856
880
  if (law.name.startsWith('?'))
@@ -1341,18 +1365,21 @@ const isFC = (c) => c.op === '<' && c.a.op === 'const' && c.b.op === 'const' ? c
1341
1365
  const kE = (value) => ({ op: 'const', value });
1342
1366
  // Lean's folds, on kernel.ts's terms: an and of several (Lean: each and of two, nested to the right) is false if one is,
1343
1367
  // else the rest that aren't true, and so for or; read through the Lean text, the two give the same terms.
1344
- const foldMul = (k0, a) => (k0 === 0 ? kE(0) : k0 === 1 ? a : a.op === 'const' ? kE(k0 * a.value) : { op: 'mul', k: k0, a });
1368
+ // A constant folded past a safe integer is left unfolded (`kF`): its float may be rounded (2 + (2^53 - 1) is 2^53), and
1369
+ // the term unfolded has its value exactly, which the kernel's linear forms then refuse (Lean's Nat folds it exactly).
1370
+ const kF = (value, e) => (Number.isSafeInteger(value) ? kE(value) : e);
1371
+ const foldMul = (k0, a) => (k0 === 0 ? kE(0) : k0 === 1 ? a : a.op === 'const' ? kF(k0 * a.value, { op: 'mul', k: k0, a }) : { op: 'mul', k: k0, a });
1345
1372
  function foldTerm(e, f, fc) {
1346
1373
  switch (e.op) {
1347
1374
  case 'var':
1348
1375
  case 'const': return e;
1349
1376
  case 'add': {
1350
1377
  const a = f(e.a), b = f(e.b);
1351
- return a.op === 'const' && a.value === 0 ? b : b.op === 'const' && b.value === 0 ? a : a.op === 'const' && b.op === 'const' ? kE(a.value + b.value) : { op: 'add', a, b };
1378
+ return a.op === 'const' && a.value === 0 ? b : b.op === 'const' && b.value === 0 ? a : a.op === 'const' && b.op === 'const' ? kF(a.value + b.value, { op: 'add', a, b }) : { op: 'add', a, b };
1352
1379
  }
1353
1380
  case 'sub': {
1354
1381
  const a = f(e.a), b = f(e.b);
1355
- return b.op === 'const' && b.value === 0 ? a : a.op === 'const' && b.op === 'const' ? kE(Math.max(0, a.value - b.value)) : { op: 'sub', a, b };
1382
+ return b.op === 'const' && b.value === 0 ? a : a.op === 'const' && b.op === 'const' ? kF(Math.max(0, a.value - b.value), { op: 'sub', a, b }) : { op: 'sub', a, b };
1356
1383
  }
1357
1384
  case 'mul': return foldMul(e.k, f(e.a));
1358
1385
  case 'min':
@@ -1919,3 +1946,105 @@ export function checkQMachine(m, laws, trees) {
1919
1946
  return !!t && !qOccurs(law.holds, m.inputs) && checkQTree(goals.start, t.start) && checkQTree(goals.step, t.step);
1920
1947
  });
1921
1948
  }
1949
+ // Lean's beqE: equal by structure (every field, keys in order).
1950
+ const stable = (t) => JSON.stringify(t, (_, x) => (x && typeof x === 'object' && !Array.isArray(x) ? Object.fromEntries(Object.keys(x).sort().map(key => [key, x[key]])) : x));
1951
+ const sameE = (a, b) => stable(a) === stable(b);
1952
+ // findCount: the first count with the variable.
1953
+ const findCount = (cs, v) => cs.find(c => c.v === v);
1954
+ // resolve: each term's count, if every term names one whose bound is the instance's.
1955
+ function resolve(cs, B, ts) {
1956
+ const out = [];
1957
+ for (const [z, v] of ts) {
1958
+ const c = findCount(cs, v);
1959
+ if (!c || !sameE(c.below, B))
1960
+ return undefined;
1961
+ out.push([z, c]);
1962
+ }
1963
+ return out;
1964
+ }
1965
+ // sumE: a sum, right-nested from 0. posP, negP: Int.toNat z and Int.toNat (−z).
1966
+ const sumE = (es) => es.reduceRight((acc, e) => ({ op: 'add', a: e, b: acc }), { op: 'const', value: 0 });
1967
+ const posP = (z) => Math.max(z, 0), negP = (z) => Math.max(-z, 0);
1968
+ // side: each count read by rd times its coefficient's part, then the unit's part times `one`.
1969
+ const side = (part, rd, one, u, rs) => ({ op: 'add', a: sumE(rs.map(([z, c]) => ({ op: 'mul', k: part(z), a: rd(c) }))), b: { op: 'mul', k: part(u), a: one } });
1970
+ // atCount: the count's variable; atWit: its body at the witness (substE [(key, var w)] body).
1971
+ const atCount = (c) => ({ op: 'var', name: c.v });
1972
+ const atWit = (w) => (c) => substE(c.body, { vars: { [c.key]: { op: 'var', name: w } }, maps: {}, flags: {} });
1973
+ // countHyp: the instance's hypothesis (and/or binary, as Lean's .and/.or).
1974
+ export function countHyp(cs, i) {
1975
+ const rs = resolve(cs, i.below, i.terms);
1976
+ if (!rs)
1977
+ return undefined;
1978
+ const one = { op: 'const', value: 1 }, w = atWit(i.wit);
1979
+ return { op: 'or', xs: [
1980
+ { op: '<=', a: side(posP, atCount, i.below, i.unit, rs), b: side(negP, atCount, i.below, i.unit, rs) },
1981
+ { op: 'and', xs: [{ op: '<', a: { op: 'var', name: i.wit }, b: i.below }, { op: '<', a: side(negP, w, one, i.unit, rs), b: side(posP, w, one, i.unit, rs) }] }
1982
+ ] };
1983
+ }
1984
+ // countHyps: every instance's, in order, or none if one isn't built.
1985
+ export function countHyps(cs, is) {
1986
+ const out = [];
1987
+ for (const i of is) {
1988
+ const h = countHyp(cs, i);
1989
+ if (!h)
1990
+ return undefined;
1991
+ out.push(h);
1992
+ }
1993
+ return out;
1994
+ }
1995
+ // witFresh: no hypothesis reads w, no count names it or reads it (in its bound or body), no instance's bound reads it.
1996
+ const readsVar = (t, w) => reads(t).vars.has(w);
1997
+ export const witFresh = (hyps, cs, is, w) => hyps.every(h => !readsVar(h, w)) && cs.every(c => c.v !== w && !readsVar(c.below, w) && !readsVar(c.body, w)) && is.every(j => !readsVar(j.below, w));
1998
+ // countedOk: the witnesses distinct (cDistinct), each fresh.
1999
+ export function countedOk(hyps, cs, is) {
2000
+ const ws = is.map(i => i.wit);
2001
+ return new Set(ws).size === ws.length && is.every(i => witFresh(hyps, cs, is, i.wit));
2002
+ }
2003
+ // checkCounted, and TypeScript's own condition on the certificate, an input from outside: every witness a name (Lean's
2004
+ // is a variable; a number 5 would pass `reads` yet be read as the variable "5") and every coefficient a safe integer
2005
+ // (Lean's are Int).
2006
+ const typed = (is) => is.every(i => typeof i.wit === 'string' && Number.isSafeInteger(i.unit) && i.terms.every(([z]) => Number.isSafeInteger(z)));
2007
+ export function checkCounted(g, cert) {
2008
+ if (!(countedOk(g.hyps, g.counts, cert.insts) && typed(cert.insts)))
2009
+ return false;
2010
+ const goal = countedGoal(g, cert.insts);
2011
+ return goal !== undefined && check(goal, cert.tree);
2012
+ }
2013
+ // The goal a certificate's tree refutes: the goal's hypotheses, then the instances' (also what the search and the
2014
+ // exporter read), or none.
2015
+ export function countedGoal(g, insts) {
2016
+ const hs = countHyps(g.counts, insts);
2017
+ return hs && { name: g.name, hyps: [...g.hyps, ...hs] };
2018
+ }
2019
+ // SGhostedM.full: the original with each ghost's start and step after its own (Lean: lists appended; here records, whose
2020
+ // names smghostOk keeps apart from the original's).
2021
+ export function ghostedMachine(g) {
2022
+ const o = g.orig, gv = Object.entries(g.vars), gm = Object.entries(g.maps);
2023
+ return { ...o,
2024
+ state: { ...o.state, ...Object.fromEntries(gv.map(([name, x]) => [name, x.start])) },
2025
+ maps: { ...o.maps, ...Object.fromEntries(gm.map(([name, x]) => [name, x.start])) },
2026
+ step: { ...o.step,
2027
+ state: { ...o.step.state, ...Object.fromEntries(gv.map(([name, x]) => [name, x.step])) },
2028
+ maps: { ...o.step.maps, ...Object.fromEntries(gm.map(([name, x]) => [name, x.write])) } } };
2029
+ }
2030
+ // smghostOk: the original takes no history and no sums (Lean's SGhostedM is over SMachine); the ghost variables are none of
2031
+ // its variables (extVars: inputs, quantified flags and their witnesses; the state; the plain flags; the keys its writes
2032
+ // and quantified flags bind); the ghost maps none of its maps (origMaps: started, written, carried); and none of its
2033
+ // parts reads a ghost (pre, assume, flags, the start, the step, the writes, the facts; a flag f reads Lean's ?f). Lean's
2034
+ // distinct ghosts and ghost writes of ghost maps only hold here by construction (record keys; a ghost map's write is its
2035
+ // own).
2036
+ export function ghostedOk(g) {
2037
+ const o = g.orig, vs = Object.keys(g.vars), ms = Object.keys(g.maps);
2038
+ const fl = Object.entries(o.step.flags ?? {}), ws = Object.values(o.step.maps ?? {});
2039
+ const quant = fl.filter((e) => e[1].op === 'all');
2040
+ const varNames = [...o.inputs, ...quant.flatMap(([f, q]) => [`?${f}`, ...witnessesOf(f, q)]), ...Object.keys(o.state), ...Object.keys(o.step.state ?? {}),
2041
+ ...fl.map(([f]) => `?${f}`), ...ws.flatMap(w => ('each' in w ? [w.each] : [])), ...quant.flatMap(([, q]) => boundOf(q))];
2042
+ const mapNames = [...Object.keys(o.maps ?? {}), ...Object.keys(o.step.maps ?? {}), ...(o.inputMaps ?? [])];
2043
+ const parts = [o.pre ?? trueC, o.assume ?? trueC, ...fl.map(([, c]) => c), ...Object.values(o.state), ...Object.values(o.step.state ?? {}),
2044
+ ...ws.flatMap(w => ('each' in w ? [w.value] : [w.key, w.value])), ...(o.facts ?? []).map(l => l.holds)];
2045
+ const apart = (t) => { const r = reads(t); return vs.every(v => !r.vars.has(v) && !(v.startsWith('?') && r.flags.has(v.slice(1)))) && ms.every(mp => !r.maps.has(mp)); };
2046
+ return !o.history && !o.sums && vs.every(v => !varNames.includes(v)) && ms.every(mp => !mapNames.includes(mp)) && parts.every(apart);
2047
+ }
2048
+ // The laws of a ghosted machine, checked: the ghosts as smghostOk says, and the laws of the ghosted machine as checkLaws
2049
+ // says (Lean: smghostOk and checkSMachine of SGhostedM.full).
2050
+ export const checkGhostedLaws = (g, laws, proof) => ghostedOk(g) && checkLaws(ghostedMachine(g), laws, proof);
@@ -53,6 +53,7 @@ export declare const clock: () => number;
53
53
  export declare function counted<T>(perMs: number, f: () => T, full?: boolean): T;
54
54
  export declare const fullRate = 250;
55
55
  export declare const fullWork: () => number;
56
+ export declare const withWork: <T>(cap: number, f: () => T) => T;
56
57
  export declare const pastWall: () => boolean;
57
58
  export declare function withWall<T>(end: number, f: () => T): T;
58
59
  export declare const late: (until: number) => boolean;
@@ -14,7 +14,7 @@ import { checkRefutation } from "../core/check.js";
14
14
  import { allowNode, allowTranslated, certCyclic, certOn, certSearch, stepCertFloor, translateMs, closingInsts, crossCyclic, cyclicOn, cycLog, hasQuantified, loopNodes, machineNodes, proveCyclic, reqTS, searchedStepNodes, skMachine, timedKind, withWitness, translatedProof, uncovered, uncoveredWhy } from "../core/cyclic.js";
15
15
  import { proveSome, someLaws } from "../core/exists.js";
16
16
  import { growCdcl } from "./cdcl.js";
17
- import { decide, patternsOf } from "./epr.js";
17
+ import { decide, pastEprCap, patternsOf } from "./epr.js";
18
18
  import { assumed, atomOf, boundOf, canon, canonFlip, columnTerm, decided, factorsOf, isCell, isMonomial, stepZone, check, checkLaws, checkStepLaws, historyMachine, plainOf, substC, substE, leafConstraints, leafConstraintsReusing, reusing, linear, livenessHelpful, livenessParts, strongly, loopMachine, obligations, plainKey, progressObligations, stepLawObligations, trueC, truth, unreachable, witnessesOf, withProducts } from "./kernel.js";
19
19
  // The atoms the path leaves open, in evaluation order: deciding any of them makes progress.
20
20
  function openE(e, path, out) {
@@ -283,7 +283,7 @@ export const fullWork = () => { let n = 0; for (const [k, w] of model)
283
283
  // on any machine; a deadline it is grown within stays.
284
284
  const groundRate = 180;
285
285
  let workCap = Infinity;
286
- const withWork = (cap, f) => { const outer = workCap; workCap = Math.min(outer, cap); try {
286
+ export const withWork = (cap, f) => { const outer = workCap; workCap = Math.min(outer, cap); try {
287
287
  return f();
288
288
  }
289
289
  finally {
@@ -437,7 +437,7 @@ const withPatterns = (m, laws, f) => {
437
437
  // (`refuted`: the last decision refuted the goal and its core's proof didn't finish: a model from fewer instances, asked
438
438
  // before, is then no answer, as the abstraction refutes it at these)
439
439
  const eprLast = { refuted: false };
440
- function eprFirst(goal, budget, whole = true, late = pastWall) {
440
+ function eprFirst(goal, budget, whole = true, late = () => pastWall() || pastEprCap()) {
441
441
  eprLast.refuted = false;
442
442
  const d = decide(goal, eprScope.patterns, { exact: true, late });
443
443
  if ('unknown' in d)
@@ -2056,7 +2056,7 @@ function settle(m, laws, i, rounds, usual, prev) {
2056
2056
  let last;
2057
2057
  for (let round = 0;; round++) {
2058
2058
  let more;
2059
- const late = round > rounds ? () => pastWall() || clock() > end : pastWall;
2059
+ const late = round > rounds ? () => pastWall() || pastEprCap() || clock() > end : () => pastWall() || pastEprCap();
2060
2060
  for (const g of obligations(m, laws, { [law.name]: inst }, i)) {
2061
2061
  if (proofs[g.name])
2062
2062
  continue;
@@ -1,6 +1,6 @@
1
1
  import type { C, E, Law, Machine, Recurrence } from '../core/machine.js';
2
2
  import { type Lin, type Step } from '../core/solver.js';
3
- import { type Fold, type Goal, type Instances, type KInduction, type Liveness, type Loop, type Path, type Recur, type RecurCases, type StepLaw, type Tree } from '../kernel/kernel.js';
3
+ import { type CountedGoal, type CountInst, type Ghosted, type Fold, type Goal, type Instances, type KInduction, type Liveness, type Loop, type Path, type Recur, type RecurCases, type StepLaw, type Tree } from '../kernel/kernel.js';
4
4
  import { proveStepLaws } from '../kernel/prove.js';
5
5
  import { type Cyclic } from '../kernel/cyclic.js';
6
6
  import { leanLibrary } from './library.js';
@@ -27,6 +27,13 @@ export declare function encode(ex: Exported, tamper?: boolean, dropStep?: boolea
27
27
  e: (t: E) => string;
28
28
  };
29
29
  export declare function goalToLean(ex: Exported, i: number, tamper?: boolean, dropStep?: boolean): string;
30
+ export declare function countedToLean(id: string, g: CountedGoal, cert: {
31
+ insts: CountInst[];
32
+ tree: Tree;
33
+ }, tampered?: {
34
+ what: string;
35
+ insts: CountInst[];
36
+ }[]): string;
30
37
  export declare function machineToLean(id: string, m: Machine, laws: Law[], corollary?: string): string;
31
38
  export declare const TRUE = ".le (.const 0) (.const 0)";
32
39
  export declare const grown: (g: Goal) => Tree;
@@ -112,7 +119,7 @@ export declare function smachineToLean(id: string, given: Machine, laws: Law[],
112
119
  simp?: string[];
113
120
  free?: string[];
114
121
  ghosts?: string[];
115
- after?: (ix: (name: string) => number) => string;
122
+ after?: (ix: (name: string) => number, mx: (name: string) => number, lit: (m: Machine) => string) => string;
116
123
  historyTampers?: {
117
124
  what: string;
118
125
  relations: {
@@ -121,6 +128,13 @@ export declare function smachineToLean(id: string, given: Machine, laws: Law[],
121
128
  }[];
122
129
  withRecordTrees: boolean;
123
130
  }[];
131
+ ghosted?: Ghosted;
132
+ forallSome?: {
133
+ law: string;
134
+ map: string;
135
+ at: E;
136
+ as: string;
137
+ }[];
124
138
  refined?: {
125
139
  impl: Machine;
126
140
  spec: Machine;
@@ -1,6 +1,6 @@
1
1
  import { atMost, n, not, pointWrite } from "../core/machine.js";
2
2
  import { add, k, scale, sub } from "../core/solver.js";
3
- import { boundOf, caseGoals, check, checkRecur, checkRecurCases, coverGoal, recurGoal, canon, decided, factorsOf, isCell, isMonomial, columnTerm, stateName, termColumn, truth, historyMachine, sumMachine, sumCovers, sumParts, foldObligations, kInductionStart, kInductionSteps, leafConstraints, loopLiveness, loopMachine, linear, livenessHelpful, livenessParts, livenessLevels, livenessRanks, strongly, loopObligations, trueC, obligations, progressObligations, stepLawObligations, substC, witnessesOf, withProducts } from "../kernel/kernel.js";
3
+ import { countedGoal, countHyps, boundOf, caseGoals, check, checkRecur, checkRecurCases, coverGoal, recurGoal, canon, decided, factorsOf, isCell, isMonomial, columnTerm, stateName, termColumn, truth, historyMachine, sumMachine, sumCovers, sumParts, foldObligations, kInductionStart, kInductionSteps, leafConstraints, loopLiveness, loopMachine, linear, livenessHelpful, livenessParts, livenessLevels, livenessRanks, strongly, loopObligations, trueC, obligations, progressObligations, stepLawObligations, substC, witnessesOf, withProducts } from "../kernel/kernel.js";
4
4
  import { chooseLevels, clock, grow, minimal, proveBuilt, proveLaws, proveSetFast, proveStepLaws, withDeadline } from "../kernel/prove.js";
5
5
  import { refinement, refinementSides } from "../core/compose.js";
6
6
  import { leanSurface, leanTerms } from "./lean-terms.js";
@@ -371,6 +371,37 @@ ${body}
371
371
  theorem ${name} : ∀ env maps, ¬ ∀ c ∈ ${name}_goal.hyps, evalC env maps c = true :=
372
372
  sound ${name}_goal ${name}_tree (by ${checkBy})`;
373
373
  }
374
+ // A counted goal (Count.lean's checkCounted, kernel.ts's twin): its hypotheses and counts, the certificate's instances,
375
+ // and the tree encoded against the goal with the instances' hypotheses after the goal's (kernel.ts's countedGoal). Lean
376
+ // builds those hypotheses itself (countHyps); the example states that they are the ones kernel.ts built. `tampered`:
377
+ // certificates Lean computes to false, as kernel.ts refuses them.
378
+ const varsOfE = (t) => [...JSON.stringify(t).matchAll(/"op":"var","name":"([^"]+)"/g)].map(m => m[1]);
379
+ const mapsOf = (t) => [...JSON.stringify(t).matchAll(/"op":"get","map":"([^"]+)"/g)].map(m => m[1]);
380
+ export function countedToLean(id, g, cert, tampered = []) {
381
+ const goal = countedGoal(g, cert.insts);
382
+ if (!goal)
383
+ throw new Error(`${id}: an instance names no count of the goal, or a count of another bound`);
384
+ const vars = [...new Set([...goal.hyps.flatMap(varsOf), ...g.counts.flatMap(cn => [cn.v, cn.key, ...varsOfE(cn.below), ...varsOfE(cn.body)]),
385
+ ...[...cert.insts, ...tampered.flatMap(t => t.insts)].flatMap(i => [i.wit, ...varsOfE(i.below)])])];
386
+ const maps = [...new Set([...goal.hyps, ...g.counts.flatMap(cn => [cn.below, cn.body])].flatMap(mapsOf))];
387
+ const enc = encode({ name: id, goal, tree: cert.tree }, false, true, vars, maps), { e, c } = enc;
388
+ const ix = (name) => vars.indexOf(name);
389
+ const instsLit = (is) => list(is.map(i => `⟨${ix(i.wit)}, ${e(i.below)}, ${list(i.terms.map(([z, v2]) => `(${int(z)}, ${ix(v2)})`))}, ${int(i.unit)}⟩`));
390
+ return `-- ${g.name} (variables ${vars.map((v2, j) => `${j} ${v2}`).join(', ')}; maps ${maps.map((m2, j) => `${j} ${m2}`).join(', ')})
391
+ def ${id}_goal : CGoal := ⟨${list(g.hyps.map(c))},
392
+ ${list(g.counts.map(cn => `⟨${ix(cn.v)}, ${ix(cn.key)}, ${e(cn.below)}, ${e(cn.body)}⟩`))}⟩
393
+ def ${id}_insts : List CInst := ${instsLit(cert.insts)}
394
+ def ${id}_tab : List VDef := ${enc.tab}
395
+ def ${id}_tree : Tree :=
396
+ ${enc.tree}
397
+ -- The instances' hypotheses Lean builds are the ones kernel.ts built.
398
+ example : countHyps ${id}_goal.counts ${id}_insts = some ${list(countHyps(g.counts, cert.insts).map(c))} := by ${checkBy}
399
+ /-- ${g.name}: no naturals and maps where each count is its sum satisfy the hypotheses. -/
400
+ theorem ${id} : ∀ ρ M, (∀ cn ∈ ${id}_goal.counts, cn.Holds ρ M) → ¬ ∀ h ∈ ${id}_goal.hyps, evalC ρ M h = true :=
401
+ counted_sound ${id}_goal ${id}_insts ${id}_tab ${id}_tree (by ${checkBy})${tampered.map(t => `
402
+ -- TAMPERED: ${t.what}. Lean computes the check to false, as kernel.ts refuses it.
403
+ example : checkCounted ${id}_goal ${instsLit(t.insts)} ${id}_tab ${id}_tree = false := by ${checkBy}`).join('')}`;
404
+ }
374
405
  // Whole machines through Kern.machine_sound: Lean builds the goals from the machine; the trees are the kernel's.
375
406
  export function machineToLean(id, m, laws, corollary) {
376
407
  if (m.maps && Object.keys(m.maps).length)
@@ -1111,6 +1142,32 @@ example : (checkSMachine ${id}_tampered ${id}_proof && sliveOk ${id}_tampered ${
1111
1142
  && checkSKStep ${id}_tampered ${id}_proof (sliveStep ${id}_live0 ${id}_live0.pend (liveStayC ${id}_live0) ${id}_live0_sp)
1112
1143
  && checkSKStep ${id}_tampered ${id}_proof (sliveStep ${id}_live0 ${id}_live0.pend (liveCoverC ${id}_live0) ${id}_live0_cp)
1113
1144
  && sliveHelpsOk ${id}_tampered ${id}_proof ${id}_live0 ${id}_live0_hp) = false := by ${checkBy}` : ''}` });
1145
+ // Ghost maps (GhostMap.lean): the laws that read no ghost hold of the original; every law, of the original with some
1146
+ // ghost values and maps (Skolem functions of the keys); and each law read ∀∃.
1147
+ const gm = opts.ghosted;
1148
+ if (gm)
1149
+ claims.push({ steps: [], allows: [], render: () => {
1150
+ const memOf = (j) => (j === 0 ? 'List.mem_cons_self' : `List.mem_cons_of_mem _ (${memOf(j - 1)})`);
1151
+ return `-- The laws that read no ghost hold of the original.
1152
+ theorem ${id}_orig_laws : ∀ ρ M, SReach ${id}_gm.orig ρ M → ∀ e ∈ ${id}_proof, avoids ${id}_gm.vars e.law.holds = true → avoidsMaps ${id}_gm.maps e.law.holds = true → e.Holds ρ M :=
1153
+ smghost_laws ${id}_gm ${id}_gmOk ${id}_proof ${id}_check
1154
+ -- Every law, at every reachable state of the original: some ghost values and ghost maps where it holds.
1155
+ theorem ${id}_skolem : ∀ ρ M, SReach ${id}_gm.orig ρ M → ∃ ρg Mg, Agree ${id}_gm.vars ρg ρ ∧ (∀ mp, mp ∉ ${id}_gm.maps → Mg mp = M mp) ∧ ∀ e ∈ ${id}_proof, e.Holds ρg Mg :=
1156
+ some_of_ghostmap ${id}_gm ${id}_gmOk ${id}_proof ${id}_check${(opts.forallSome ?? []).map((fs, j) => {
1157
+ const li = laws.findIndex(l => l.name === fs.law), law = laws[li];
1158
+ if (!law?.forall || law.keys?.length)
1159
+ throw new Error(`${id}: ${fs.law}: read ∀∃, a law about one key`);
1160
+ const read = substC(law.holds, { vars: {}, maps: { [fs.map]: () => ({ op: 'var', name: fs.as }) }, flags: {} });
1161
+ return `
1162
+ /-- ${law.name}, read ∀∃: for every ${law.forall}, some ${fs.as} (${fs.map} at ${law.forall}, a Skolem function the step keeps) where it holds; no ghost read. -/
1163
+ theorem ${id}_some${j} : ∀ ρ M, SReach ${id}_gm.orig ρ M → ∀ v, ∃ val, evalC (upd (upd ρ ${ix(law.forall)} v) ${ix(fs.as)} val) M
1164
+ (${c(read)}) = true := by
1165
+ have h := forall_some_of_ghostmap ${id}_gm ${id}_gmOk ${id}_proof ${id}_check ${id}_e${li} (${memOf(li)}) ${ix(law.forall)} rfl rfl ${mx(fs.map)} ${ix(fs.as)} (${e(fs.at)})
1166
+ (by ${checkBy}) (by ${checkBy}) (by ${checkBy}) (by ${checkBy})
1167
+ have hr : substRC [] (rdW ${mx(fs.map)} ${ix(fs.as)}) ${id}_e${li}.law.holds = ${c(read)} := by ${checkBy}
1168
+ rw [hr] at h; exact h`;
1169
+ }).join('')}`;
1170
+ } });
1114
1171
  // Ghosts (Ghost.lean's sghost_laws): the laws that read no ghost hold of the machine without its ghosts.
1115
1172
  if (gv.length)
1116
1173
  claims.push({ steps: [], allows: [], render: () => `-- The laws that read no ghost hold of the machine without its ghosts.
@@ -1333,7 +1390,13 @@ ${rf ? `def ${id}_refined : SRefined := ⟨${lit(rf.impl)},
1333
1390
  ${lit(rf.spec)},
1334
1391
  ${list(Object.entries(rf.wit).map(([inp, t]) => `(${ix(`b_${inp}`)}, ${e(t)})`))},
1335
1392
  ${c(rf.stutter)}⟩
1336
- def ${id}_machine : SMachine := ${id}_refined.full` : gv.length ? `def ${id}_ghosted : SGhosted := ⟨${lit(orig)},
1393
+ def ${id}_machine : SMachine := ${id}_refined.full` : gm ? `def ${id}_gm : SGhostedM := ⟨${lit(gm.orig)},
1394
+ ${list(Object.entries(gm.vars).map(([v2, x2]) => `(${ix(v2)}, ${e(x2.start)}, ${e(x2.step)})`))},
1395
+ ${list(Object.entries(gm.maps).map(([mp, x2]) => `(${mx(mp)}, ${x2.start})`))},
1396
+ ${list(Object.entries(gm.maps).flatMap(([mp, x2]) => ('each' in x2.write ? [] : [`(${mx(mp)}, ${e(x2.write.key)}, ${e(x2.write.value)})`])))},
1397
+ ${list(Object.entries(gm.maps).flatMap(([mp, x2]) => ('each' in x2.write ? [`(${mx(mp)}, ${ix(x2.write.each)}, ${e(x2.write.value)})`] : [])))}⟩
1398
+ def ${id}_machine : SMachine := ${id}_gm.full
1399
+ theorem ${id}_gmOk : smghostOk ${id}_gm = true := by ${checkBy}` : gv.length ? `def ${id}_ghosted : SGhosted := ⟨${lit(orig)},
1337
1400
  ${list(gv.map(v2 => `(${ix(v2)}, ${e(m.state[v2])}, ${e(m.step.state?.[v2] ?? { op: 'var', name: v2 })})`))}⟩
1338
1401
  def ${id}_machine : SMachine := ${id}_ghosted.full
1339
1402
  theorem ${id}_ghostOk : sghostOk ${id}_ghosted = true := by ${checkBy}` : hm ? `def ${id}_hist : HMachine := ${hlit(hm.history.relations ?? [])}
@@ -1347,7 +1410,7 @@ theorem ${id}_laws : ∀ ρ M, SReach ${id}_machine ρ M → ∀ e ∈ ${id}_pro
1347
1410
  ${hm ? histBlock() : readable(id, laws, vars, mapNames, { binders: '(ρ : Nat → Nat) (μ : Nat → Nat → Nat)', hyp: `SReach ${id}_machine ρ μ`, call: `${id}_laws ρ μ h`, lit: c, eLit: e })}${sm ? sumsBlock() : ''}${opts.noFacts ? '' : factsProof(id, m, mapNames, vars, opts.simp)}${opts.tamper ? `
1348
1411
  -- TAMPERED: ${opts.tamper.what}. Lean computes the check to false.
1349
1412
  def ${id}_tampered : SMachine := ${lit(opts.tamper.machine)}
1350
- example : checkSMachine ${id}_tampered ${id}_proof = false := by ${checkBy}` : ''}${records.length ? `\n\n${records.join('\n\n')}` : ''}${opts.after ? `\n\n${opts.after(ix)}` : ''}`;
1413
+ example : checkSMachine ${id}_tampered ${id}_proof = false := by ${checkBy}` : ''}${records.length ? `\n\n${records.join('\n\n')}` : ''}${opts.after ? `\n\n${opts.after(ix, mx, lit)}` : ''}`;
1351
1414
  }
1352
1415
  // --- the cyclic certificate's export (GDP_CERT=cyclic) -------------------------------------------------------------
1353
1416
  // By default, or with GDP_CERT=cyclic (core/cyclic.ts's certOn: a covered proof's certificate is its cyclic proof; or toLean's
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gdp-wired",
3
- "version": "0.32.0",
3
+ "version": "0.33.1",
4
4
  "description": "An automatic prover for stateful rules (budgets, caps, windows, workflows, policies): laws proven with no proof to write, checked again in Lean, counterexamples found on the GPU, the rule shipped as code",
5
5
  "keywords": [
6
6
  "verification",
@@ -148,6 +148,10 @@
148
148
  "types": "./dist/core/laws.d.ts",
149
149
  "default": "./dist/core/laws.js"
150
150
  },
151
+ "./relational": {
152
+ "types": "./dist/core/relational.d.ts",
153
+ "default": "./dist/core/relational.js"
154
+ },
151
155
  "./package.json": "./package.json"
152
156
  },
153
157
  "bin": {
@@ -181,7 +185,7 @@
181
185
  "prepublishOnly": "bun scripts/build.ts",
182
186
  "smoke": "sh scripts/smoke.sh",
183
187
  "bar": "bun gates/bar.ts",
184
- "test": "bun scripts/gen-lean-library.ts --check && cd core && bun test exports.test.ts cli.test.ts solver.test.ts dsl.test.ts sums.test.ts arith.test.ts conformance.test.ts compose.test.ts quantifiers.test.ts functions.test.ts keyterms.test.ts lists.test.ts liveness.test.ts sizes.test.ts values.test.ts rationals.test.ts builders.test.ts gdp.test.ts datatypes.test.ts lemmas.test.ts discover.test.ts infer.test.ts cyclic.test.ts cycles.test.ts nonterm.test.ts data.test.ts hypothesis.test.ts seqs.test.ts abstract.test.ts search.test.ts invoices.test.ts folds.test.ts trees.test.ts pairs.test.ts chart.test.ts xstate.test.ts extract.test.ts effect.test.ts && cd ../kernel && bun test tamper.test.ts refusals.test.ts steplaw.test.ts sets.test.ts cdcl.test.ts && cd ../examples && bun test examples.test.ts && cd .. && bun examples/readme.ts && bun examples/guide.ts && bun examples/composition.ts && bun examples/sets.ts && bun examples/quantifiers.ts && bun examples/functions.ts && bun examples/datatypes.ts && bun examples/lemmas.ts && bun examples/discover.ts && bun examples/invoices.ts && bun examples/folds.ts && bun examples/trees.ts && bun examples/pairs.ts && bun examples/groups.ts && bun examples/charts.ts && bun examples/xstate.ts && bun examples/effect.ts && bun examples/infer.ts && bun examples/arith.ts && bun examples/cyclic.ts && bun examples/cycles.ts && bun examples/data.ts && bun examples/abstract.ts && bun test compare/tip/translate.test.ts && bun examples/scopes.ts && bun examples/lists.ts && bun examples/sizes.ts && bun examples/liveness.ts && bun examples/sums.ts && bun examples/nonterm.ts && bun examples/rationals.ts && bun examples/budget.ts && bun examples/gdp.ts && bun examples/steps.ts && bun examples/jev-fabric/run.ts"
188
+ "test": "bun scripts/gen-lean-library.ts --check && cd core && bun test exports.test.ts cli.test.ts solver.test.ts dsl.test.ts sums.test.ts arith.test.ts conformance.test.ts compose.test.ts relational.test.ts quantifiers.test.ts functions.test.ts keyterms.test.ts lists.test.ts liveness.test.ts sizes.test.ts values.test.ts rationals.test.ts builders.test.ts gdp.test.ts datatypes.test.ts lemmas.test.ts discover.test.ts infer.test.ts cyclic.test.ts cycles.test.ts nonterm.test.ts data.test.ts hypothesis.test.ts seqs.test.ts abstract.test.ts search.test.ts invoices.test.ts folds.test.ts trees.test.ts pairs.test.ts chart.test.ts xstate.test.ts extract.test.ts effect.test.ts && cd ../kernel && bun test tamper.test.ts refusals.test.ts steplaw.test.ts sets.test.ts cdcl.test.ts && cd ../examples && bun test examples.test.ts && cd .. && bun examples/readme.ts && bun examples/guide.ts && bun examples/composition.ts && bun examples/sets.ts && bun examples/quantifiers.ts && bun examples/functions.ts && bun examples/datatypes.ts && bun examples/lemmas.ts && bun examples/discover.ts && bun examples/invoices.ts && bun examples/folds.ts && bun examples/trees.ts && bun examples/pairs.ts && bun examples/groups.ts && bun examples/charts.ts && bun examples/xstate.ts && bun examples/effect.ts && bun examples/infer.ts && bun examples/arith.ts && bun examples/cyclic.ts && bun examples/cycles.ts && bun examples/data.ts && bun examples/abstract.ts && bun test compare/tip/translate.test.ts && bun examples/scopes.ts && bun examples/lists.ts && bun examples/sizes.ts && bun examples/liveness.ts && bun examples/sums.ts && bun examples/nonterm.ts && bun examples/rationals.ts && bun examples/budget.ts && bun examples/gdp.ts && bun examples/steps.ts && bun examples/jev-fabric/run.ts"
185
189
  },
186
190
  "devDependencies": {
187
191
  "@gdp-ts/core": "0.1.0",