gdp-wired 0.51.0 → 0.52.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/README.md +2 -2
  2. package/dist/core/accel-refute.d.ts +53 -0
  3. package/dist/core/accel-refute.js +997 -0
  4. package/dist/core/cli.d.ts +2 -0
  5. package/dist/core/cli.js +8 -1
  6. package/dist/core/cycles.d.ts +2 -0
  7. package/dist/core/cycles.js +12 -9
  8. package/dist/core/dsl.d.ts +7 -1
  9. package/dist/core/dsl.js +147 -26
  10. package/dist/core/live-support.d.ts +5 -0
  11. package/dist/core/live-support.js +148 -0
  12. package/dist/core/live.js +194 -37
  13. package/dist/core/lockstep.d.ts +5 -0
  14. package/dist/core/lockstep.js +23 -0
  15. package/dist/core/ordered-pair-seeds.d.ts +2 -0
  16. package/dist/core/ordered-pair-seeds.js +109 -0
  17. package/dist/core/proof-output.d.ts +38 -1
  18. package/dist/core/proof-output.js +38 -0
  19. package/dist/core/search-termination.d.ts +4 -0
  20. package/dist/core/search-termination.js +1 -1
  21. package/dist/core/source-check.d.ts +4 -1
  22. package/dist/core/source-check.js +5 -2
  23. package/dist/core/sparse-kind-proof.d.ts +7 -0
  24. package/dist/core/sparse-kind-proof.js +49 -0
  25. package/dist/core/step-seeds.d.ts +46 -0
  26. package/dist/core/step-seeds.js +316 -0
  27. package/dist/lean-kernel/Cert.lean +222 -0
  28. package/dist/lean-kernel/Count.lean +1568 -0
  29. package/dist/lean-kernel/Ghost.lean +373 -0
  30. package/dist/lean-kernel/GhostMap.lean +426 -0
  31. package/dist/lean-kernel/Kernel.lean +2881 -0
  32. package/dist/lean-kernel/Live.lean +1168 -0
  33. package/dist/lean-kernel/Progress.lean +543 -0
  34. package/dist/lean-kernel/Sets.lean +1975 -0
  35. package/dist/lean-kernel/StepLaw.lean +128 -0
  36. package/dist/lean-kernel/Steps.lean +477 -0
  37. package/dist/lean-kernel/Sums.lean +916 -0
  38. package/dist/lean-kernel/emit.d.ts +4 -0
  39. package/dist/lean-kernel/emit.js +23 -4
  40. package/dist/lean-kernel/lean-aggregate/FiniteFold.lean +44 -0
  41. package/dist/lean-kernel/lean-aggregate/GroupedTransport.lean +308 -0
  42. package/dist/lean-kernel/lean-aggregate/aggregate.d.ts +13 -0
  43. package/dist/lean-kernel/lean-aggregate/aggregate.js +68 -0
  44. package/dist/lean-kernel/lean-aggregate/assets.d.ts +5 -0
  45. package/dist/lean-kernel/lean-aggregate/assets.js +7 -0
  46. package/dist/lean-kernel/lean-aggregate/audit.d.ts +3 -0
  47. package/dist/lean-kernel/lean-aggregate/audit.js +13 -0
  48. package/dist/lean-kernel/lean-aggregate/exact.d.ts +15 -0
  49. package/dist/lean-kernel/lean-aggregate/exact.js +51 -0
  50. package/dist/lean-kernel/lean-aggregate/index.d.ts +19 -0
  51. package/dist/lean-kernel/lean-aggregate/index.js +52 -0
  52. package/dist/lean-kernel/lean-aggregate/point-fold.d.ts +27 -0
  53. package/dist/lean-kernel/lean-aggregate/point-fold.js +79 -0
  54. package/dist/lean-kernel/lean-aggregate/replay-fold.d.ts +2 -0
  55. package/dist/lean-kernel/lean-aggregate/replay-fold.js +163 -0
  56. package/dist/lean-kernel/lean-aggregate/source.d.ts +2 -0
  57. package/dist/lean-kernel/lean-aggregate/source.js +141 -0
  58. package/dist/lean-kernel/lean-aggregate/weighted-flags.d.ts +2 -0
  59. package/dist/lean-kernel/lean-aggregate/weighted-flags.js +26 -0
  60. package/dist/lean-kernel/lean-aggregate/weighted-replay.d.ts +7 -0
  61. package/dist/lean-kernel/lean-aggregate/weighted-replay.js +53 -0
  62. package/dist/lean-kernel/lean-aggregate/weighted-seeded.d.ts +30 -0
  63. package/dist/lean-kernel/lean-aggregate/weighted-seeded.js +64 -0
  64. package/dist/lean-kernel/lean-aggregate/weighted.d.ts +18 -0
  65. package/dist/lean-kernel/lean-aggregate/weighted.js +115 -0
  66. package/dist/lean-kernel/lean-aggregate/worker.d.ts +10 -0
  67. package/dist/lean-kernel/lean-aggregate/worker.js +46 -0
  68. package/docs/lean-aggregate.md +29 -0
  69. package/package.json +6 -1
@@ -2,6 +2,8 @@
2
2
  // the private observations must downgrade a source proof, not turn it into a DSL proof.
3
3
  const sourceMarker = Symbol.for('gdp-wired.source-proof.v1');
4
4
  const marked = (value) => Object.prototype.hasOwnProperty.call(value, sourceMarker);
5
+ // A model counterexample is not a native source replay.
6
+ export const isSourceBound = (rule, laws) => marked(rule) || laws.some(marked);
5
7
  const mark = (value, enumerable = false) => { if (!marked(value))
6
8
  Object.defineProperty(value, sourceMarker, { value: true, enumerable }); };
7
9
  const markRule = (value) => {
@@ -44,10 +46,11 @@ export function attachNativeLaw(rule, law, name, method, evaluate) {
44
46
  mark(law);
45
47
  nativeLaws.set(law, { rule: sources.get(rule)?.root ?? rule, name, method, evaluate });
46
48
  }
47
- export function translationVerdict(rule, laws, verdict) {
49
+ export function translationVerdict(rule, laws, input) {
48
50
  const source = sources.get(rule), bound = laws.map(l => nativeLaws.get(l)).filter(x => x !== undefined);
49
51
  if (!source && !bound.length && !marked(rule) && !laws.some(marked))
50
- return verdict;
52
+ return input;
53
+ const verdict = input.fairRing === undefined && input.acceleratedRun === undefined ? input : { ...input, fairRing: undefined, acceleratedRun: undefined };
51
54
  const journal = source?.journal;
52
55
  const unchecked = (why) => ({ ...verdict, proven: false, checked: false, kernelProven: verdict.proven && verdict.checked, translation: 'unchecked', why: `source translation unchecked: ${why}` });
53
56
  if (!journal?.enabled || !journal.complete)
@@ -0,0 +1,7 @@
1
+ import { type Law, type Machine } from './machine.js';
2
+ import { type Instances, type Tree } from '../kernel/kernel.js';
3
+ export declare function kindConjuncts(kinds: Law[], reserved: Law[]): Law[];
4
+ export declare function sparseKindProof(m: Machine, laws: Law[], until: number): {
5
+ instances: Record<string, Instances>;
6
+ trees: Record<string, Tree>;
7
+ } | undefined;
@@ -0,0 +1,49 @@
1
+ // Try a small instantiation of the ordinary family. Only the unchanged
2
+ // kernel's checkLaws can accept it. This is useful when numerous kind guards
3
+ // share a record but each output only needs the previous kind at its own key.
4
+ import { walkOnce } from "./machine.js";
5
+ import { checkLaws, obligations } from "../kernel/kernel.js";
6
+ import { grow } from "../kernel/prove.js";
7
+ // A conjunction of state laws at one arbitrary key holds exactly when all
8
+ // of its conjuncts hold at that same key. Preserve the binders and check the
9
+ // entire resulting family; this only removes branching between kind fields.
10
+ export function kindConjuncts(kinds, reserved) {
11
+ const names = new Set([...kinds, ...reserved].map(l => l.name));
12
+ const flatten = (c) => c.op === 'and' && c.xs.length ? c.xs.flatMap(flatten) : [c];
13
+ return kinds.flatMap(law => {
14
+ if (law.some?.length || law.finite || law.keys?.length)
15
+ return [law];
16
+ const parts = flatten(law.holds);
17
+ return parts.length === 1 ? [law] : parts.map((holds, i) => {
18
+ let name = `${law.name} [conjunct ${i + 1}]`;
19
+ while (names.has(name))
20
+ name += '_';
21
+ names.add(name);
22
+ return { ...law, name, holds };
23
+ });
24
+ });
25
+ }
26
+ export function sparseKindProof(m, laws, until) {
27
+ if (laws.some(l => l.keys?.length || l.some?.length || l.finite))
28
+ return undefined;
29
+ const instances = Object.fromEntries(laws.filter(l => l.forall).map(law => {
30
+ const reads = new Set(), key = { op: 'var', name: `${law.forall}#` };
31
+ walkOnce(law.holds, x => { const t = x; if (t.op === 'get')
32
+ reads.add(t.map); });
33
+ const addresses = [...reads].flatMap(map => {
34
+ const w = m.step.maps?.[map];
35
+ return w && 'key' in w ? [w.key] : [];
36
+ });
37
+ const terms = [...new Map([key, ...addresses].map(t => [JSON.stringify(t), t])).values()];
38
+ return [law.name, { [law.name]: terms }];
39
+ }));
40
+ const trees = Object.create(null);
41
+ for (const goal of obligations(m, laws, instances)) {
42
+ const got = grow(goal, new Map(), { nodes: 0, until });
43
+ if (!('tree' in got))
44
+ return undefined;
45
+ trees[goal.name] = got.tree;
46
+ }
47
+ const proof = { instances, trees };
48
+ return checkLaws(m, laws, proof) ? proof : undefined;
49
+ }
@@ -0,0 +1,46 @@
1
+ import { type Law, type Machine } from './machine.js';
2
+ import { type Instances, type StepLaw, type Tree } from '../kernel/kernel.js';
3
+ export declare function stepSeedFamilies(m: Machine, sl: StepLaw): Law[][];
4
+ export declare function tryStepSeed(m: Machine, laws: Law[], kinds: Law[], sl: StepLaw, seeds: Law[], sparse?: boolean): {
5
+ family: Law[];
6
+ checked: import("../kernel/prove.ts").Report & {
7
+ laws?: Law[];
8
+ machine?: Machine;
9
+ stepLaws?: StepLaw[];
10
+ proof?: {
11
+ laws: {
12
+ instances: Record<string, Instances>;
13
+ trees: Record<string, Tree>;
14
+ };
15
+ instances: Instances;
16
+ perStep?: Record<string, Instances>;
17
+ trees: Record<string, Tree>;
18
+ };
19
+ uncovered?: string[];
20
+ };
21
+ kindProof?: undefined;
22
+ } | {
23
+ family: Law[];
24
+ checked: import("../kernel/prove.ts").Report & {
25
+ laws?: Law[];
26
+ machine?: Machine;
27
+ stepLaws?: StepLaw[];
28
+ proof?: {
29
+ laws: {
30
+ instances: Record<string, Instances>;
31
+ trees: Record<string, Tree>;
32
+ };
33
+ instances: Instances;
34
+ perStep?: Record<string, Instances>;
35
+ trees: Record<string, Tree>;
36
+ };
37
+ uncovered?: string[];
38
+ };
39
+ kindProof: {
40
+ laws: Law[];
41
+ proof: {
42
+ instances: Record<string, Instances>;
43
+ trees: Record<string, Tree>;
44
+ };
45
+ };
46
+ } | undefined;
@@ -0,0 +1,316 @@
1
+ // Search-only proposals. The existing step checker proves all the proposed state
2
+ // invariants and the original step law, or this stage contributes nothing.
3
+ import { hasFinite } from "./machine.js";
4
+ import { checkWorkEndpoint } from "./wall.js";
5
+ import { checkStepLaws, obligations, stepLawObligations } from "../kernel/kernel.js";
6
+ import { grow, proveStepLaws } from "../kernel/prove.js";
7
+ import { kindConjuncts, sparseKindProof } from "./sparse-kind-proof.js";
8
+ const repr = (x) => JSON.stringify(x);
9
+ const same = (a, b) => repr(a) === repr(b);
10
+ const v = (name) => ({ op: 'var', name });
11
+ const n = (value) => ({ op: 'const', value });
12
+ const get = (map, key) => ({ op: 'get', map, key });
13
+ const eq = (a, b) => ({ op: '=', a, b });
14
+ const le = (a, b) => ({ op: '<=', a, b });
15
+ const neg = (x) => ({ op: 'not', x });
16
+ const imp = (a, b) => ({ op: 'or', xs: [neg(a), b] });
17
+ // Bound the syntax walk even on hand-built machines with shared subterms. Abort
18
+ // rather than interpreting a partial walk as evidence that no other write exists.
19
+ class TooWide extends Error {
20
+ }
21
+ function objects(t) {
22
+ const seen = new Set(), out = [], stack = [t];
23
+ while (stack.length) {
24
+ const x = stack.pop();
25
+ if (!x || typeof x !== 'object' || seen.has(x))
26
+ continue;
27
+ if ((seen.size & 255) === 0)
28
+ checkWorkEndpoint('step seed syntax');
29
+ if (seen.size >= 8192)
30
+ throw new TooWide();
31
+ seen.add(x);
32
+ if (!Array.isArray(x))
33
+ out.push(x);
34
+ const xs = Object.values(x);
35
+ for (let i = xs.length - 1; i >= 0; i--)
36
+ stack.push(xs[i]);
37
+ }
38
+ return out;
39
+ }
40
+ const nodes = (t, op) => objects(t).filter(x => x.op === op);
41
+ const values = (t, depth = 0) => {
42
+ if (depth > 16)
43
+ throw new TooWide();
44
+ return t.op === 'if' ? [...values(t.then, depth + 1), ...values(t.else, depth + 1)] : [t];
45
+ };
46
+ function flagClosure(m, t) {
47
+ const roots = [t], seen = new Set();
48
+ for (let i = 0; i < roots.length; i++)
49
+ for (const f of nodes(roots[i], 'flag')) {
50
+ const c = m.step.flags?.[f.name];
51
+ if (c && !seen.has(f.name)) {
52
+ seen.add(f.name);
53
+ roots.push(c);
54
+ }
55
+ if (roots.length > 64)
56
+ throw new TooWide();
57
+ }
58
+ return roots;
59
+ }
60
+ function conjuncts(m, c, active = new Set(), depth = 0) {
61
+ if (depth > 16)
62
+ throw new TooWide();
63
+ if (c.op === 'and')
64
+ return c.xs.flatMap(x => conjuncts(m, x, active, depth + 1));
65
+ if (c.op === 'flag' && !active.has(c.name) && m.step.flags?.[c.name])
66
+ return conjuncts(m, m.step.flags[c.name], new Set([...active, c.name]), depth + 1);
67
+ return [c];
68
+ }
69
+ function seed(holds, name, forall) {
70
+ return { name: `step seed: ${name}`, holds, ...(forall === undefined ? {} : { forall }) };
71
+ }
72
+ // Find the access guards for the exact fields the step law expects to stay
73
+ // unchanged (or only change in one direction). An old-state tag on one field
74
+ // can make a default-valued allocation guard on a sibling field impossible.
75
+ function compatible(m, sl) {
76
+ if (!sl.forall || sl.keys?.length || sl.then.op !== 'or' || !m.maps)
77
+ return [];
78
+ const ante = sl.then.xs.find(x => x.op === 'not')?.x, k = v(sl.forall);
79
+ if (!ante || nodes(ante, 'var').some(x => x.name !== k.name))
80
+ return [];
81
+ const getters = nodes(ante, 'get'), maps = [...new Set(getters.map(x => x.map))], old = maps[0];
82
+ if (!old || maps.length !== 1 || !(old in m.maps) || !getters.every(x => same(x.key, k)))
83
+ return [];
84
+ const changed = [...new Set(nodes(sl.then, 'get').filter(x => x.map.endsWith("'")).map(x => x.map.slice(0, -1)))];
85
+ const kept = new Map();
86
+ for (const name of changed) {
87
+ const w = m.step.maps?.[name];
88
+ if (!w)
89
+ continue;
90
+ // Try the negation of actual default tests, and likewise the complement of
91
+ // a negated Boolean test on a zero-default cell. Merely occurring in a guard
92
+ // does not make the proposal true; it just gives the prover a useful guess.
93
+ for (const o of objects(flagClosure(m, w.value))) {
94
+ if (o.op !== '=' && o.op !== 'not')
95
+ continue;
96
+ const inverted = o.op === 'not', c = (inverted ? o.x : o);
97
+ if (c.op !== '=')
98
+ continue;
99
+ const [a, b] = c.a.op === 'get' ? [c.a, c.b] : [c.b, c.a];
100
+ if (a.op !== 'get' || b.op !== 'const' || a.map === old || kept.has(a.map))
101
+ continue;
102
+ if (inverted ? !(m.maps[a.map] === 0 && b.value === 1) : m.maps[a.map] !== b.value)
103
+ continue;
104
+ const test = eq(get(a.map, k), b);
105
+ kept.set(a.map, inverted ? test : neg(test));
106
+ }
107
+ }
108
+ const dot = old.lastIndexOf('.'), prefix = dot === -1 ? undefined : old.slice(0, dot + 1);
109
+ const local = (x) => Number(prefix !== undefined && x.startsWith(prefix));
110
+ return [...kept].sort(([a], [b]) => local(b) - local(a)).slice(0, 4)
111
+ .map(([a, test]) => [seed(imp(ante, test), `${old} excludes the allocation test for ${a}`, k.name)]);
112
+ }
113
+ // Derive a cursor anchor from an actual equality guard and corresponding writes
114
+ // of both the old and successor cursor. Match copied values by exact expression,
115
+ // not by names or adjacency in the user's source.
116
+ function coherence(m, sl) {
117
+ const state = m.step.state, maps = m.step.maps, defaults = m.maps;
118
+ if (sl.forall || !maps || !state || !defaults || !sl.when)
119
+ return [];
120
+ const inputs = new Set(m.inputs), vars = Object.keys(state);
121
+ const used = new Set([...m.inputs, ...m.params, ...Object.keys(m.state), ...nodes(m, 'var').map(x => x.name)]);
122
+ const key = ['$', '$$', '$$$'].find(x => !used.has(x));
123
+ if (!key)
124
+ return [];
125
+ const k = v(key);
126
+ const mvs = Object.fromEntries(Object.entries(maps).map(([a, w]) => [a, values(w.value)]));
127
+ const svs = Object.fromEntries(Object.entries(state).map(([a, e]) => [a, values(e)]));
128
+ const gvars = new Set(nodes([sl.then, sl.when], 'var').map(x => x.name.replace(/'$/, '')));
129
+ const clocks = new Map();
130
+ for (const { a, b } of nodes(m.assume, '<=')) {
131
+ if (a.op !== 'var' || b.op !== 'var' || !inputs.has(b.name))
132
+ continue;
133
+ const e = state[a.name];
134
+ if (e?.op === 'max' && ((same(e.a, a) && same(e.b, b)) || (same(e.b, a) && same(e.a, b))))
135
+ clocks.set(b.name, a);
136
+ }
137
+ // Normalize a guard to the stored observation and clock. It is a proposal,
138
+ // not an equivalence asserted between the original and normalized guards.
139
+ function relation(c, acting) {
140
+ let clock = false;
141
+ function rewrite(x, depth = 0) {
142
+ if (depth > 32)
143
+ throw new TooWide();
144
+ if (!x || typeof x !== 'object')
145
+ return x;
146
+ if (Array.isArray(x))
147
+ return x.map(z => rewrite(z, depth + 1));
148
+ const a = x;
149
+ if (a.op === 'if') {
150
+ const e = a.else;
151
+ if (e.op === 'get' && same(e.key, acting))
152
+ return get(e.map, k);
153
+ }
154
+ if (a.op === 'var') {
155
+ const s = a.name;
156
+ if (s === acting.name)
157
+ return k;
158
+ if (clocks.has(s)) {
159
+ clock = true;
160
+ return clocks.get(s);
161
+ }
162
+ }
163
+ return Object.fromEntries(Object.entries(a).map(([k, z]) => [k, rewrite(z, depth + 1)]));
164
+ }
165
+ const f = rewrite(c);
166
+ if (nodes(f, 'var').some(x => x.name !== key && !vars.includes(x.name) && !m.params.includes(x.name)) ||
167
+ nodes(f, 'get').some(x => !(x.map in defaults) || !same(x.key, k)) ||
168
+ objects(f).some(x => x.op === 'if' || x.op === 'all' || x.op === 'flag'))
169
+ return;
170
+ return { f, clock };
171
+ }
172
+ for (const test of nodes(flagClosure(m, sl.when), '=')) {
173
+ const [cur, cell] = test.a.op === 'get' ? [test.b, test.a] : [test.a, test.b];
174
+ if (cur.op !== 'var' || cell.op !== 'get' || cell.key.op !== 'var' || !inputs.has(cell.key.name))
175
+ continue;
176
+ const act = cell.key, primary = cell.map;
177
+ const next = svs[cur.name]?.find(e => e.op === 'add' && same(e.a, cur) && same(e.b, n(1)));
178
+ if (!next || !mvs[primary]?.some(e => same(e, next)) || !mvs[primary].some(e => same(e, cur)))
179
+ continue;
180
+ const seen = new Set(), out = [];
181
+ const push = (f, label, keyed = true) => {
182
+ const j = repr(f);
183
+ if (seen.has(j))
184
+ return;
185
+ seen.add(j);
186
+ out.push(seed(f, `${label} [${out.length}]`, keyed ? key : undefined));
187
+ };
188
+ const match = eq(get(primary, k), cur);
189
+ const secondary = Object.keys(mvs).filter(x => x !== primary && mvs[x].some(e => same(e, cur)) && !mvs[x].some(e => same(e, next)));
190
+ push(le(get(primary, k), cur), `${primary} is at most the cursor`);
191
+ for (const x of secondary)
192
+ push(le(get(x, k), get(primary, k)), `${x} is at most ${primary}`);
193
+ const identity = new Set();
194
+ let copies = 0;
195
+ for (const s of vars.filter(x => gvars.has(x) && x !== cur.name))
196
+ for (const mp of Object.keys(mvs)) {
197
+ if (mp === primary || secondary.includes(mp))
198
+ continue;
199
+ const both = svs[s].filter(e => e.op !== 'const' && !same(e, v(s)) && mvs[mp].some(t => same(t, e)));
200
+ if (!both.length)
201
+ continue;
202
+ const now = both.find(e => e.op === 'var' && clocks.has(e.name));
203
+ if (now?.op === 'var')
204
+ push(le(v(s), clocks.get(now.name)), `${s} is not past the clock`, false);
205
+ push(imp(match, now ? le(v(s), get(mp, k)) : eq(get(mp, k), v(s))), `${mp} is current on a matched cursor`);
206
+ copies++;
207
+ if (both.some(e => same(e, act)))
208
+ identity.add(mp);
209
+ }
210
+ if (!copies)
211
+ continue;
212
+ const timeGoal = nodes(sl.then, 'var').some(x => clocks.has(x.name)), post = nodes(sl.then, 'var').some(x => x.name.endsWith("'"));
213
+ const readers = new Set(nodes(flagClosure(m, [sl.when, ...vars.filter(x => gvars.has(x)).map(x => state[x])]), 'get').map(x => x.map));
214
+ for (const [mp, wr] of Object.entries(maps)) {
215
+ if (!readers.has(mp) || mp === primary || secondary.includes(mp) || identity.has(mp))
216
+ continue;
217
+ const b = get(mp, k), def = defaults[mp];
218
+ if (def === undefined)
219
+ continue;
220
+ const arms = [];
221
+ const visit = (e, path) => {
222
+ if (path.length > 16 || arms.length > 6)
223
+ throw new TooWide();
224
+ if (e.op === 'if') {
225
+ visit(e.then, [...path, e.c]);
226
+ visit(e.else, [...path, neg(e.c)]);
227
+ }
228
+ else if (e.op === 'const' && e.value !== def)
229
+ arms.push({ tag: e.value, path });
230
+ };
231
+ visit(wr.value, []);
232
+ for (const { tag, path } of arms) {
233
+ const cs = flagClosure(m, path);
234
+ if (timeGoal) {
235
+ for (const c of nodes(cs, 'not').filter(x => x.x.op === 'and')) {
236
+ const r = relation(c, act);
237
+ if (r?.clock && nodes(r.f, 'get').some(x => identity.has(x.map)))
238
+ push(imp(neg(eq(b, n(def))), r.f), `${mp} retains its clock guard`);
239
+ }
240
+ }
241
+ else if (post) {
242
+ const top = path.flatMap(c => conjuncts(m, c));
243
+ for (const c of nodes(cs, '=')) {
244
+ const r = relation(c, act);
245
+ if (r?.f.op !== '=' || !nodes(r.f, 'get').some(x => identity.has(x.map)) || ![r.f.a, r.f.b].some(z => same(z, k)))
246
+ continue;
247
+ push(imp(eq(b, n(tag)), top.some(x => same(x, c)) ? r.f : neg(r.f)), `${mp} retains the identity test for ${tag}`);
248
+ }
249
+ }
250
+ }
251
+ }
252
+ if (out.length <= 16)
253
+ return [out];
254
+ }
255
+ return [];
256
+ }
257
+ export function stepSeedFamilies(m, sl) {
258
+ try {
259
+ if ((sl.steps ?? 1) !== 1 || m.history || m.sums || m.counts || !m.maps || m.primitiveFailure || m.inputMaps?.length ||
260
+ objects([m, sl]).some(x => x.finite !== undefined) || hasFinite(sl))
261
+ return [];
262
+ return sl.forall ? compatible(m, sl) : coherence(m, sl);
263
+ }
264
+ catch (error) {
265
+ if (error instanceof TooWide)
266
+ return [];
267
+ throw error;
268
+ }
269
+ }
270
+ // Only trust the resulting ordinary proof. Kind reminders can be omitted for
271
+ // an allocation-guard proposal: proving with fewer hypotheses is stronger and
272
+ // avoids instantiating unrelated record fields at all possible write keys.
273
+ function atKeyProof(m, family, sl) {
274
+ // Every supplied hypothesis is still required at initiation and preservation.
275
+ // Start with the observed key only; instantiation is a proof-search choice.
276
+ const [law] = family, key = sl.forall;
277
+ const inst = { [law.name]: [v(key)] }, inv = { [law.name]: { [law.name]: [v(`${key}#`)] } };
278
+ const lt = {}, st = {};
279
+ let count = 0;
280
+ for (const [goals, dst] of [[obligations(m, family, inv), lt], [stepLawObligations(m, family, inst, sl), st]]) {
281
+ for (const g of goals) {
282
+ const r = grow(g);
283
+ if (!('tree' in r))
284
+ return { proven: false, checked: false, nodes: count, leaves: 0, failed: { goal: g.name, stuck: r.stuck, why: r.why, witness: r.witness } };
285
+ count += r.nodes;
286
+ dst[g.name] = r.tree;
287
+ }
288
+ }
289
+ const proof = { laws: { instances: inv, trees: lt }, instances: inst, trees: st };
290
+ if (!checkStepLaws(m, family, [sl], proof))
291
+ return undefined;
292
+ return { proven: true, checked: true, proof, nodes: count, leaves: 0 };
293
+ }
294
+ export function tryStepSeed(m, laws, kinds, sl, seeds, sparse = true) {
295
+ const extraKinds = kinds.filter(k => !laws.some(l => l.name === k.name));
296
+ const given = [...extraKinds, ...laws];
297
+ if (!seeds.length || new Set(seeds.map(s => s.name)).size !== seeds.length || seeds.some(s => given.some(l => l.name === s.name)))
298
+ return undefined;
299
+ const atKey = !laws.length && seeds.length === 1 && sl.forall && seeds[0].forall === sl.forall && !m.facts?.length &&
300
+ !Object.values(m.step.flags ?? {}).some(c => c.op === 'all');
301
+ if (atKey && sparse) {
302
+ const checked = atKeyProof(m, seeds, sl);
303
+ if (!checked?.proof || !checked.proven || !checked.checked)
304
+ return undefined;
305
+ // Kind laws are independent obligations of the public call, not optional
306
+ // conclusions. Check them separately to keep the sparse step proof small.
307
+ if (!extraKinds.length)
308
+ return { family: seeds, checked };
309
+ const kindLaws = kindConjuncts(extraKinds, seeds), proof = sparseKindProof(m, kindLaws, Infinity);
310
+ return proof ? { family: seeds, checked, kindProof: { laws: kindLaws, proof } } : undefined;
311
+ }
312
+ const family = [...given, ...seeds], checked = proveStepLaws(m, family, [sl]);
313
+ if (!checked.proof || !checked.proven || !checked.checked || !checkStepLaws(m, family, [sl], checked.proof))
314
+ return undefined;
315
+ return { family, checked };
316
+ }
@@ -0,0 +1,222 @@
1
+ /-
2
+ Cert: the trusted core of gdp-wired, with its proofs. Lean 4.34.0, core only.
3
+
4
+ A row `Σ cᵢ·xᵢ + c ≤ 0` over the integers. A certificate is a list of steps that replays into rows: an input row, a
5
+ positive combination of two earlier rows, or a cut (an earlier row whose coefficients are all g times q, replaced by q
6
+ with a constant c such that g·c ≤ constant + g − 1). `check` accepts when the last row has only zero coefficients and a
7
+ positive constant. `sound`: if `check` accepts, no integer point satisfies every input row.
8
+
9
+ A row holds its nonzero coefficients alone (column, coefficient), in column order, so a step costs a row's nonzeros
10
+ rather than the table's width. Any list reads as a sum (`dot`); sorted lists stay sorted and cancel to [] under `addL`.
11
+
12
+ `run_preserves` is the induction rule a step machine's laws rest on: a property true at the start and preserved by
13
+ every step holds after every sequence of steps.
14
+ -/
15
+
16
+ namespace Cert
17
+
18
+ structure Row where
19
+ coefs : List (Nat × Int)
20
+ const : Int
21
+ deriving Repr
22
+
23
+ def dot : List (Nat × Int) → List Int → Int
24
+ | [], _ => 0
25
+ | p :: rest, x => p.2 * x.getD p.1 0 + dot rest x
26
+
27
+ def eval (r : Row) (x : List Int) : Int := dot r.coefs x + r.const
28
+
29
+ -- Two sorted lists merged, coefficients of one column added (a column that cancels dropped). The fuel only bounds the
30
+ -- recursion: out of it, the lists are put side by side, which reads the same.
31
+ def addF : Nat → List (Nat × Int) → List (Nat × Int) → List (Nat × Int)
32
+ | 0, a, b => a ++ b
33
+ | _ + 1, [], b => b
34
+ | _ + 1, a, [] => a
35
+ | n + 1, p :: as, q :: bs =>
36
+ if p.1 < q.1 then p :: addF n as (q :: bs)
37
+ else if q.1 < p.1 then q :: addF n (p :: as) bs
38
+ else if p.2 + q.2 = 0 then addF n as bs else (p.1, p.2 + q.2) :: addF n as bs
39
+
40
+ def addL (a b : List (Nat × Int)) : List (Nat × Int) := addF (a.length + b.length) a b
41
+
42
+ def scaleL (m : Int) (a : List (Nat × Int)) : List (Nat × Int) := if m = 0 then [] else a.map (fun p => (p.1, m * p.2))
43
+
44
+ def allZero : List (Nat × Int) → Bool
45
+ | [] => true
46
+ | p :: a => p.2 == 0 && allZero a
47
+
48
+ theorem dot_app (x : List Int) : ∀ (a b : List (Nat × Int)), dot (a ++ b) x = dot a x + dot b x
49
+ | [], b => by simp [dot]
50
+ | p :: a, b => by simp only [List.cons_append, dot, dot_app x a b]; omega
51
+
52
+ theorem dot_addF (x : List Int) : ∀ (n : Nat) (a b : List (Nat × Int)), dot (addF n a b) x = dot a x + dot b x
53
+ | 0, a, b => by simp only [addF, dot_app]
54
+ | _ + 1, [], b => by simp [addF, dot]
55
+ | _ + 1, _ :: _, [] => by simp [addF, dot]
56
+ | n + 1, p :: as, q :: bs => by
57
+ simp only [addF]
58
+ split
59
+ · simp only [dot, dot_addF x n as (q :: bs)]; omega
60
+ · split
61
+ · simp only [dot, dot_addF x n (p :: as) bs]; omega
62
+ · have hpq : p.1 = q.1 := by omega
63
+ split
64
+ · rename_i hz
65
+ simp only [dot, dot_addF x n as bs, hpq]
66
+ have : p.2 * x.getD q.1 0 + q.2 * x.getD q.1 0 = 0 := by rw [← Int.add_mul, hz, Int.zero_mul]
67
+ omega
68
+ · simp only [dot, dot_addF x n as bs, hpq, Int.add_mul]; omega
69
+
70
+ theorem dot_addL (a b : List (Nat × Int)) (x : List Int) : dot (addL a b) x = dot a x + dot b x := dot_addF x _ a b
71
+
72
+ theorem dot_map (m : Int) (x : List Int) : ∀ (a : List (Nat × Int)), dot (a.map (fun p => (p.1, m * p.2))) x = m * dot a x
73
+ | [] => by simp [dot]
74
+ | p :: a => by simp only [List.map_cons, dot, dot_map m x a, Int.mul_add, Int.mul_assoc]
75
+
76
+ theorem dot_scaleL (m : Int) (a : List (Nat × Int)) (x : List Int) : dot (scaleL m a) x = m * dot a x := by
77
+ unfold scaleL
78
+ split
79
+ · rename_i h; subst h; simp [dot]
80
+ · exact dot_map m x a
81
+
82
+ theorem dot_allZero : ∀ (a : List (Nat × Int)) (x : List Int), allZero a = true → dot a x = 0
83
+ | [], _, _ => rfl
84
+ | p :: a, x, h => by
85
+ simp only [allZero, Bool.and_eq_true, beq_iff_eq] at h
86
+ simp [dot, h.1, dot_allZero a x h.2]
87
+
88
+ inductive Step where
89
+ | input (i : Nat)
90
+ | combine (a b : Nat) (ma mb : Int)
91
+ | cut (of : Nat) (g : Int) (q : List (Nat × Int)) (c : Int)
92
+ deriving Repr
93
+
94
+ def combineRow (ma mb : Int) (A B : Row) : Row :=
95
+ ⟨addL (scaleL ma A.coefs) (scaleL mb B.coefs), ma * A.const + mb * B.const⟩
96
+
97
+ def cutOk (A : Row) (g : Int) (q : List (Nat × Int)) (c : Int) : Bool :=
98
+ decide (1 ≤ g) && decide (A.coefs = scaleL g q) && decide (g * c ≤ A.const + g - 1)
99
+
100
+ -- The rows so far kept newest first, with their number (step i's row is at n − 1 − i): a row is put on the front and
101
+ -- read where it is, never past a chain of appends.
102
+ def replay (inputs : List Row) : List Step → Nat → List Row → Option (List Row)
103
+ | [], _, rows => some rows
104
+ | .input i :: ss, n, rows =>
105
+ match inputs[i]? with
106
+ | some r => replay inputs ss (n + 1) (r :: rows)
107
+ | none => none
108
+ | .combine a b ma mb :: ss, n, rows =>
109
+ match rows[n - 1 - a]?, rows[n - 1 - b]? with
110
+ | some A, some B => if a < n ∧ b < n ∧ 0 < ma ∧ 0 < mb then replay inputs ss (n + 1) (combineRow ma mb A B :: rows) else none
111
+ | _, _ => none
112
+ | .cut o g q c :: ss, n, rows =>
113
+ match rows[n - 1 - o]? with
114
+ | some A => if o < n ∧ cutOk A g q c then replay inputs ss (n + 1) (⟨q, c⟩ :: rows) else none
115
+ | none => none
116
+
117
+ def check (inputs : List Row) (steps : List Step) : Bool :=
118
+ match replay inputs steps 0 [] with
119
+ | some rows =>
120
+ match rows.head? with
121
+ | some r => allZero r.coefs && decide (0 < r.const)
122
+ | none => false
123
+ | none => false
124
+
125
+ theorem cut_sound (g d c c' : Int) (hg : 1 ≤ g) (h : g * d + c ≤ 0) (hc : g * c' ≤ c + g - 1) : d + c' ≤ 0 := by
126
+ have hd : g * (d + c') = g * d + g * c' := Int.mul_add g d c'
127
+ refine Int.not_lt.mp (fun h1 => ?_)
128
+ have h2 : g * 1 ≤ g * (d + c') := Int.mul_le_mul_of_nonneg_left (by omega) (by omega)
129
+ omega
130
+
131
+ -- Every row a replay produces holds wherever the inputs and the rows so far hold.
132
+ theorem replay_holds (inputs : List Row) (x : List Int) (hx : ∀ r ∈ inputs, eval r x ≤ 0) :
133
+ ∀ (ss : List Step) (n : Nat) (rows out : List Row), (∀ r ∈ rows, eval r x ≤ 0) →
134
+ replay inputs ss n rows = some out → ∀ r ∈ out, eval r x ≤ 0 := by
135
+ intro ss
136
+ induction ss with
137
+ | nil =>
138
+ intro n rows out hrows h
139
+ simp only [replay, Option.some.injEq] at h
140
+ exact h ▸ hrows
141
+ | cons s ss ih =>
142
+ intro n rows out hrows h
143
+ cases s with
144
+ | input i =>
145
+ simp only [replay] at h
146
+ split at h
147
+ · rename_i r hr
148
+ refine ih _ _ out ?_ h
149
+ intro r' hr'
150
+ rcases List.mem_cons.mp hr' with hr' | hr'
151
+ · exact hr' ▸ hx r (List.mem_of_getElem? hr)
152
+ · exact hrows r' hr'
153
+ · exact absurd h (by simp)
154
+ | combine a b ma mb =>
155
+ simp only [replay] at h
156
+ split at h
157
+ · rename_i A B hA hB
158
+ split at h
159
+ · rename_i hm
160
+ refine ih _ _ out ?_ h
161
+ intro r' hr'
162
+ rcases List.mem_cons.mp hr' with hr' | hr'
163
+ · subst hr'
164
+ have eA := hrows A (List.mem_of_getElem? hA)
165
+ have eB := hrows B (List.mem_of_getElem? hB)
166
+ simp only [eval, combineRow, dot_addL, dot_scaleL] at eA eB ⊢
167
+ have h1 : ma * (dot A.coefs x + A.const) ≤ ma * 0 := Int.mul_le_mul_of_nonneg_left eA (by omega)
168
+ have h2 : mb * (dot B.coefs x + B.const) ≤ mb * 0 := Int.mul_le_mul_of_nonneg_left eB (by omega)
169
+ simp only [Int.mul_add, Int.mul_zero] at h1 h2
170
+ omega
171
+ · exact hrows r' hr'
172
+ · exact absurd h (by simp)
173
+ · exact absurd h (by simp)
174
+ | cut o g q c =>
175
+ simp only [replay] at h
176
+ split at h
177
+ · rename_i A hA
178
+ split at h
179
+ · rename_i hok
180
+ refine ih _ _ out ?_ h
181
+ intro r' hr'
182
+ rcases List.mem_cons.mp hr' with hr' | hr'
183
+ · subst hr'
184
+ simp only [cutOk, Bool.and_eq_true, decide_eq_true_eq] at hok
185
+ obtain ⟨_, ⟨hg, hq⟩, hc⟩ := hok
186
+ have eA := hrows A (List.mem_of_getElem? hA)
187
+ have hdot : dot A.coefs x = g * dot q x := by rw [hq, dot_scaleL]
188
+ simp only [eval, hdot] at eA
189
+ exact cut_sound g (dot q x) A.const c hg eA hc
190
+ · exact hrows r' hr'
191
+ · exact absurd h (by simp)
192
+ · exact absurd h (by simp)
193
+
194
+ /-- A certificate the checker accepts refutes its inputs: no integer point satisfies them all. -/
195
+ theorem sound (inputs : List Row) (steps : List Step) (h : check inputs steps = true) (x : List Int)
196
+ (hx : ∀ r ∈ inputs, eval r x ≤ 0) : False := by
197
+ simp only [check] at h
198
+ split at h
199
+ · rename_i rows hrows
200
+ split at h
201
+ · rename_i r hr
202
+ simp only [Bool.and_eq_true, decide_eq_true_eq] at h
203
+ have hall := replay_holds inputs x hx steps 0 [] rows (by simp) hrows
204
+ have hm : r ∈ rows := by
205
+ cases rows with
206
+ | nil => simp at hr
207
+ | cons a as => simp only [List.head?, Option.some.injEq] at hr; subst hr; exact List.mem_cons_self
208
+ have := hall r hm
209
+ simp only [eval, dot_allZero r.coefs x h.1] at this
210
+ omega
211
+ · exact absurd h (by simp)
212
+ · exact absurd h (by simp)
213
+
214
+ /-- The induction rule: what holds at the start and survives every step holds after any sequence of steps. -/
215
+ theorem run_preserves {S I : Type} (step : S → I → S) (P : S → Prop) (start : S)
216
+ (h0 : P start) (hs : ∀ s i, P s → P (step s i)) : ∀ (is : List I), P (is.foldl step start) := by
217
+ intro is
218
+ induction is generalizing start with
219
+ | nil => exact h0
220
+ | cons i is ih => exact ih (step start i) (hs start i h0)
221
+
222
+ end Cert