gdp-wired 0.34.0 → 0.36.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.
@@ -0,0 +1,31 @@
1
+ import { type C, type E, type Law, type Machine, type State } from './machine.js';
2
+ import { type CountCert, type CountInst, type Instances, type MapRead } from '../kernel/kernel.js';
3
+ type Env = Record<string, number>;
4
+ export declare function guardLaws(m: Machine): {
5
+ counts: Machine['counts'];
6
+ laws: Law[];
7
+ };
8
+ export declare function pairLaws(m: Machine): Law[];
9
+ export declare function small(m: Machine, p: Env, b: number, cap?: number): State[];
10
+ export declare function certFor(goal: {
11
+ hyps: C[];
12
+ }, decls: {
13
+ map: string;
14
+ below: E;
15
+ }[]): {
16
+ reads: MapRead[];
17
+ insts: CountInst[];
18
+ wits: string[];
19
+ };
20
+ export type Counted = {
21
+ proven: boolean;
22
+ laws: Law[];
23
+ m: Machine;
24
+ proof?: {
25
+ instances: Record<string, Instances>;
26
+ certs: Record<string, CountCert>;
27
+ };
28
+ why?: string;
29
+ };
30
+ export declare function searchCounted(m0: Machine, caller: Law[], ms?: number): Counted;
31
+ export {};
@@ -0,0 +1,264 @@
1
+ // The search for a machine with counts (Machine.counts; the kernel's countedObligations and checkCountedLaws, Lean's
2
+ // CountMachine.lean): untrusted. It proposes laws that read counts of the state, filters every candidate on the small
3
+ // instances' reachable states, and keeps the largest set the kernel accepts (Houdini), each goal's certificate built
4
+ // here: the count cells the goal reads, Count.lean's instances over pairs of them, and the laws and quantified flags at
5
+ // the instances' witnesses.
6
+ // - The guard's shape: a step writes P[t] where a quantified flag says every member of a set the request counts
7
+ // satisfies R(member, t), and the assumption compares that count with a bound (2·|Q| > size, |Q| ≥ n − t, …). Then
8
+ // a state count c_R(x) = |{k < bound: R(k, x)}| is declared, and P[a] ⇒ the same comparison with c_R[a] for |Q| is
9
+ // proposed: what every majority, quorum or threshold protocol keeps of its decisions.
10
+ // - A guard comparing a state count at the written key (2·voters[n] > size, Leader[n] := 1): P[a] ⇒ that comparison
11
+ // at a.
12
+ // - Each map's cells at most what the small instances reach.
13
+ import { carriedView, evalC, interpret } from "./machine.js";
14
+ import { checkCountedLaws, countedObligations, mcGoal, substC } from "../kernel/kernel.js";
15
+ import { clock, grow } from "../kernel/prove.js";
16
+ import { env } from "./solver.js";
17
+ const v = (name) => ({ op: 'var', name }), k = (value) => ({ op: 'const', value });
18
+ const json = (t) => JSON.stringify(t);
19
+ const one = k(1), zero = k(0);
20
+ // Every term t with `get(map, t)` in t0.
21
+ function reads(t0, map, out = new Map()) {
22
+ const go = (x) => {
23
+ if (!x || typeof x !== 'object')
24
+ return;
25
+ const o = x;
26
+ if (o.op === 'get' && map(o.map))
27
+ out.set(json([o.map, o.key]), [o.map, o.key]);
28
+ for (const y of Object.values(o))
29
+ go(y);
30
+ };
31
+ go(t0);
32
+ return out;
33
+ }
34
+ const mentions = (t, name) => json(t).includes(`"name":${json(name)}`);
35
+ const atoms = (c) => (c.op === 'and' || c.op === 'or' ? c.xs.flatMap(atoms) : c.op === 'not' ? atoms(c.x) : [c]);
36
+ // --- candidates from the guard's shape -----------------------------------------------------------------------------------
37
+ export function guardLaws(m) {
38
+ const counts = {}, laws = [];
39
+ const flags = m.step.flags ?? {}, fsub = { vars: {}, maps: {}, flags: Object.fromEntries(Object.entries(flags).map(([f, fc]) => [f, fc.op === 'all' ? { op: '=', a: v(`?${f}`), b: one } : fc])) };
40
+ const inline = (c) => { let x = c; for (let i = 0; i < 4 && json(x).includes('"op":"flag"'); i++)
41
+ x = substC(x, fsub); return x; };
42
+ const guards = m.assume ? atoms(m.assume).filter(a => a.op === '<' || a.op === '<=') : [];
43
+ const isCount = (mp) => !!m.counts?.[mp];
44
+ for (const [mp, w] of Object.entries(m.step.maps ?? {})) {
45
+ if ('each' in w || w.key.op !== 'var' || !m.inputs.includes(w.key.name))
46
+ continue;
47
+ const t = w.key.name, written = inline({ op: '<=', a: one, b: w.value });
48
+ const law = (name, cmp) => ({ name, forall: 'a$c', holds: { op: 'or', xs: [{ op: 'not', x: { op: '<=', a: one, b: { op: 'get', map: mp, key: v('a$c') } } }, cmp] } });
49
+ // A comparison with a state count at the written key.
50
+ for (const g of guards)
51
+ for (const [, [c, key]] of reads(g, isCount)) {
52
+ if (json(key) !== json(v(t)) || mentions(m.counts[c].body, t))
53
+ continue;
54
+ if (m.inputs.some(i => i !== t && mentions(g, i)))
55
+ continue;
56
+ laws.push(law(`${mp} keeps ${c}'s bound`, substC(g, { vars: { [t]: v('a$c') }, maps: {}, flags: {} })));
57
+ }
58
+ // A quantified flag the write reads: every member of a counted set satisfies R(member, t).
59
+ for (const [f, q] of Object.entries(flags)) {
60
+ if (q.op !== 'all' || q.keys?.length || !mentions(written, `?${f}`) || q.c.op !== 'or' || q.c.xs.length !== 2)
61
+ continue;
62
+ const [h, r] = q.c.xs[0].op === 'not' ? [q.c.xs[0].x, q.c.xs[1]] : [q.c.xs[1].op === 'not' ? q.c.xs[1].x : undefined, q.c.xs[0]];
63
+ if (!h || !r)
64
+ continue;
65
+ for (const [c, d] of Object.entries(m.counts ?? {})) {
66
+ // the set: the count's body is the flag's hypothesis at its key
67
+ const body = d.body.op === 'if' ? d.body.c : undefined;
68
+ if (!body || json(substC(body, { vars: { [d.key]: v(q.key) }, maps: {}, flags: {} })) !== json(h))
69
+ continue;
70
+ if (m.inputs.some(i => i !== t && mentions(r, i)))
71
+ continue;
72
+ const name = `${c}$${mp}`, j = `${name}$x`, key = `${name}$k`;
73
+ counts[name] = { j, key, below: d.below, body: { op: 'if', c: substC(r, { vars: { [q.key]: v(key), [t]: v(j) }, maps: {}, flags: {} }), then: one, else: zero } };
74
+ for (const g of guards)
75
+ if (reads(g, x => x === c).size)
76
+ laws.push(law(`${mp} keeps ${c}'s bound through ${name}`, substC(g, { vars: {}, maps: { [c]: () => ({ op: 'get', map: name, key: v('a$c') }) }, flags: {} })));
77
+ }
78
+ }
79
+ }
80
+ return { counts, laws };
81
+ }
82
+ // --- relations over pairs: one value per first key, and one relation inside another ---------------------------------
83
+ // A map written at x·N + y (a relation, x's row) is a candidate for "at most one y in a row", and each two such maps for
84
+ // "one holds where the other does", at the same pair or the swapped one; the small instances keep the true ones.
85
+ export function pairLaws(m) {
86
+ const widths = new Map();
87
+ for (const [mp, w] of Object.entries(m.step.maps ?? {}))
88
+ if (!('each' in w) && w.key.op === 'add' && w.key.a.op === 'mul' && w.key.a.a.op === 'var' && w.key.b.op === 'var')
89
+ widths.set(mp, w.key.a.k);
90
+ const at = (mp, x, y, n) => ({ op: 'get', map: mp, key: { op: 'add', a: { op: 'mul', k: n, a: v(x) }, b: v(y) } });
91
+ const has = (e) => ({ op: '<=', a: one, b: e }), lt = (x, n) => ({ op: '<', a: v(x), b: k(n) });
92
+ const out = [];
93
+ for (const [mp, n] of widths)
94
+ out.push({ name: `${mp}: one per row`, forall: 'p$c', keys: ['q$c', 'r$c'], holds: { op: 'or', xs: [{ op: 'not', x: { op: 'and', xs: [lt('q$c', n), lt('r$c', n), has(at(mp, 'p$c', 'q$c', n)), has(at(mp, 'p$c', 'r$c', n))] } }, { op: '=', a: v('q$c'), b: v('r$c') }] } });
95
+ for (const [a, n] of widths)
96
+ for (const [b, n2] of widths)
97
+ if (a !== b && n === n2)
98
+ for (const swap of [false, true])
99
+ out.push({ name: `${a} inside ${b}${swap ? ', swapped' : ''}`, forall: 'p$c', keys: ['q$c'], holds: { op: 'or', xs: [{ op: 'not', x: { op: 'and', xs: [lt('q$c', n), lt('p$c', n), has(at(a, 'p$c', 'q$c', n))] } }, has(swap ? at(b, 'q$c', 'p$c', n) : at(b, 'p$c', 'q$c', n))] } });
100
+ // (and over one key: where one map's cell is set, another's is)
101
+ const singles = Object.entries(m.step.maps ?? {}).filter(([, w]) => !('each' in w) && w.key.op === 'var').map(([mp]) => mp);
102
+ for (const a of singles)
103
+ for (const b of singles)
104
+ if (a !== b)
105
+ out.push({ name: `${a} inside ${b}`, forall: 'p$c', holds: { op: 'or', xs: [{ op: 'not', x: has({ op: 'get', map: a, key: v('p$c') }) }, has({ op: 'get', map: b, key: v('p$c') })] } });
106
+ return out;
107
+ }
108
+ // --- the small instances --------------------------------------------------------------------------------------------------
109
+ // Every state reached from the start with the params at `p`, each input below `b`, each carried map a subset of 0 .. b − 1.
110
+ export function small(m, p, b, cap = 3000) {
111
+ const run = interpret(m), start = run.init(p);
112
+ 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])));
113
+ let reqs = [{}];
114
+ for (const i of m.inputs)
115
+ reqs = reqs.flatMap(r => Array.from({ length: b }, (_, x) => ({ ...r, [i]: x })));
116
+ for (const c of m.inputMaps ?? [])
117
+ reqs = reqs.flatMap(r => subsets.map(s => ({ ...r, [c]: s })));
118
+ const seen = new Map([[json(start), start]]), queue = [start];
119
+ while (queue.length && seen.size < cap) {
120
+ const st = queue.shift();
121
+ for (const r of reqs) {
122
+ let next;
123
+ try {
124
+ next = run.step(p, st, r);
125
+ }
126
+ catch {
127
+ continue;
128
+ }
129
+ const key = json([next.scalars, Object.entries(next.maps).map(([n, cs]) => [n, [...cs].filter(([, x]) => x).sort((a, c) => a[0] - c[0])])]);
130
+ if (!seen.has(key)) {
131
+ seen.set(key, next);
132
+ queue.push(next);
133
+ }
134
+ }
135
+ }
136
+ return [...seen.values()];
137
+ }
138
+ // A law at a state, its counts the state's, at every key below b.
139
+ function holdsAt(m, law, p, st, b) {
140
+ const empty = Object.fromEntries((m.inputMaps ?? []).map(c => [c, new Map()]));
141
+ const view = carriedView(m, st, empty, undefined, p), keys = [law.forall, ...(law.keys ?? [])].filter((x) => !!x);
142
+ const go = (env, ks) => (ks.length ? Array.from({ length: b }, (_, x) => x).every(x => go({ ...env, [ks[0]]: x }, ks.slice(1))) : evalC(law.holds, { ...env, ...st.scalars }, view, m));
143
+ return go({ ...p }, keys);
144
+ }
145
+ // --- a goal's certificate -------------------------------------------------------------------------------------------------
146
+ // The count cells the goal reads (each before the step with its post name's twin), instances over pairs of them with one
147
+ // bound (a count that doesn't drop, +1 and −1; two that meet, +1, +1 and −1), each with a fresh witness; and the laws and
148
+ // quantified flags at the witnesses (returned, for the goal's law's instances).
149
+ export function certFor(goal, decls) {
150
+ const byMap = new Map(decls.map(d => [d.map, d])), last = goal.hyps.at(-1);
151
+ // (the conclusion's reads first, then those at a constant or the law's own names, then the rest)
152
+ const own = (t) => t.op === 'const' || (t.op === 'var' && json(last).includes(`"name":${json(t.name)}`));
153
+ const all0 = [...reads(goal.hyps, mp => byMap.has(mp)).values()], inLast = [...reads(last, mp => byMap.has(mp)).keys()];
154
+ const rank = ([mp, t]) => (inLast.includes(json([mp, t])) ? 0 : own(t) ? 1 : 2);
155
+ const rs = all0.sort((x, y) => rank(x) - rank(y));
156
+ // (each read after the step beside its twin before it, when the goal declares both)
157
+ for (const [mp, t] of [...rs])
158
+ if (mp.endsWith('#') && byMap.has(mp.slice(0, -1)) && !rs.some(([m2, t2]) => m2 === mp.slice(0, -1) && json(t2) === json(t)))
159
+ rs.push([mp.slice(0, -1), t]);
160
+ const named = rs.slice(0, 6).map(([mp, t], i) => [`r$${i}`, mp, t]);
161
+ const bound = (r) => json(byMap.get(r[1]).below);
162
+ const insts = [], wits = [];
163
+ const add = (terms, unit, below) => { const w = `w$${insts.length}`; wits.push(w); insts.push({ wit: w, below, terms, unit }); };
164
+ // first: a count after the step at least each other one (it doesn't drop; what the step adds); then two counts before it
165
+ // that meet, the first of the pair one the conclusion or the law's own names read; then the rest at most another
166
+ const post = (r) => r[1].endsWith('#'), ranked = (r) => rank([r[1], r[2]]) <= 1;
167
+ for (const c of named)
168
+ if (post(c))
169
+ for (const a of named)
170
+ if (a !== c && !post(a) && bound(a) === bound(c))
171
+ add([[1, a[0]], [-1, c[0]]], 0, byMap.get(c[1]).below);
172
+ for (const [i, a] of named.entries())
173
+ for (const [j, c] of named.entries())
174
+ if (i < j && (ranked(a) || ranked(c)) && bound(a) === bound(c) && !post(a) && !post(c))
175
+ add([[1, a[0]], [1, c[0]]], -1, byMap.get(a[1]).below);
176
+ for (const [i, a] of named.entries())
177
+ for (const [j, c] of named.entries())
178
+ if (i < j && !(ranked(a) || ranked(c)) && bound(a) === bound(c) && !post(a) && !post(c))
179
+ add([[1, a[0]], [1, c[0]]], -1, byMap.get(a[1]).below);
180
+ return { reads: named, insts: insts.slice(0, 10), wits: wits.slice(0, 10) };
181
+ }
182
+ export function searchCounted(m0, caller, ms = 60_000) {
183
+ const until = clock() + ms, g = guardLaws(m0), m = { ...m0, counts: { ...m0.counts, ...g.counts } };
184
+ // The small instances: each param 2 and 3 (where the precondition allows), inputs and sets below 3.
185
+ const insts = [2, 3].map(x => Object.fromEntries(m.params.map(p => [p, x])));
186
+ const states = insts.map(p => {
187
+ try {
188
+ return { p, sts: small(m, p, 3) };
189
+ }
190
+ catch {
191
+ return { p, sts: [] };
192
+ }
193
+ });
194
+ const kinds = Object.keys(m.maps ?? {}).map(mp => {
195
+ const most = Math.max(0, ...states.flatMap(({ sts }) => sts.flatMap(st => [...(st.maps[mp]?.values() ?? [])])));
196
+ return { name: `${mp} at most ${most}`, forall: 'a$c', holds: { op: '<=', a: { op: 'get', map: mp, key: v('a$c') }, b: k(most) } };
197
+ });
198
+ const trueAll = (l) => states.every(({ p, sts }) => sts.every(st => holdsAt(m, l, p, st, 4)));
199
+ if (!caller.every(trueAll))
200
+ return { proven: false, laws: caller, m, why: 'a law fails on the small instances' };
201
+ let set = [...caller, ...[...kinds, ...pairLaws(m), ...g.laws].filter(trueAll)];
202
+ if (env.GDP_COUNTS_TRACE)
203
+ console.error(`counts: candidates ${set.map(l => l.name).join('; ')}`);
204
+ for (let round = 0; clock() < until; round++) {
205
+ const terms = (l) => [...(l.forall ? [v(`${l.forall}#`)] : []), ...(l.keys ?? []).map(v), ...m.inputs.map(v)];
206
+ const instances = {}, certs = {}, failed = new Set();
207
+ for (const law of set) {
208
+ if (clock() > until)
209
+ return { proven: false, laws: set, m, why: 'time' };
210
+ const ts = terms(law);
211
+ const inst = (wits) => {
212
+ const out = {};
213
+ for (const l of set) {
214
+ if (l.keys?.length === 1)
215
+ out[l.name] = ts.flatMap(x => ts.flatMap(y => (json(x) === json(y) ? [] : [x, y])));
216
+ else if (l.keys?.length === 2)
217
+ out[l.name] = ts.flatMap(x => ts.flatMap(y => ts.flatMap(z => (json(y) === json(z) ? [] : [x, y, z]))));
218
+ else if (l.forall)
219
+ out[l.name] = [...ts, ...wits.map(v)];
220
+ }
221
+ for (const [f, q] of Object.entries(m.step.flags ?? {}))
222
+ if (q.op === 'all' && !q.keys?.length)
223
+ out[`?${f}`] = [...wits.map(v), ...m.inputs.map(v)];
224
+ return out;
225
+ };
226
+ // The goals' certificates: first with no instances of the lemma, then with the cells' (one set of witnesses a law).
227
+ let ok = true;
228
+ for (const pass of [0, 1]) {
229
+ const wits0 = pass ? Array.from({ length: 10 }, (_, i) => `w$${i}`) : [];
230
+ instances[law.name] = inst(wits0);
231
+ ok = true;
232
+ for (const { goal, decls } of countedObligations(m, set, instances, set.indexOf(law))) {
233
+ const c = pass ? certFor(goal, decls) : { reads: [], insts: [] };
234
+ const gg = mcGoal(goal.hyps, decls, c);
235
+ const o = gg && grow(gg, new Map(), { nodes: 0, until: Math.min(until, clock() + 10_000) });
236
+ if (!o || !('tree' in o)) {
237
+ ok = false;
238
+ if (env.GDP_COUNTS_TRACE && pass)
239
+ console.error(`counts: ${goal.name}: ${gg ? json(o).slice(0, 300) : 'a read of no count'} (reads ${c.reads.map(r => `${r[1]}[${json(r[2])}]`).join(' ')})`);
240
+ break;
241
+ }
242
+ certs[goal.name] = { reads: c.reads, insts: c.insts, tree: o.tree };
243
+ }
244
+ if (ok)
245
+ break;
246
+ }
247
+ if (!ok)
248
+ failed.add(law.name);
249
+ }
250
+ if (!failed.size) {
251
+ const proof = { instances, certs };
252
+ return checkCountedLaws(m, set, proof) ? { proven: true, laws: set, m, proof } : { proven: false, laws: set, m, why: 'the kernel refused the set' };
253
+ }
254
+ if (caller.some(l => failed.has(l.name)) && set.length === caller.length)
255
+ return { proven: false, laws: set, m, why: `not proven: ${[...failed].join(', ')}` };
256
+ const next = set.filter(l => !failed.has(l.name) || caller.includes(l));
257
+ if (next.length === set.length) {
258
+ // only callers fail: drop nothing more, give up
259
+ return { proven: false, laws: set, m, why: `not proven: ${[...failed].join(', ')}` };
260
+ }
261
+ set = next;
262
+ }
263
+ return { proven: false, laws: set, m, why: 'time' };
264
+ }
@@ -528,6 +528,10 @@ type Spec = {
528
528
  nodes?: [string, Kind<unknown>, string[], Record<string, NodeFold<unknown, string>>][];
529
529
  kinded?: [string, Kind<unknown>][];
530
530
  carried?: string[];
531
+ counts?: [string, (env: never) => {
532
+ below: TermLike;
533
+ body: (x: Term, k: Term) => Cond | TermLike;
534
+ }][];
531
535
  seqs?: string[];
532
536
  seqTables?: string[];
533
537
  lists2?: [string, Kind<unknown>, Record<string, ListFold<unknown>>, Record<string, ListLemma>][];
@@ -601,6 +605,12 @@ export declare class Rule<P extends Obj = {}, I extends Obj = {}, S extends Obj
601
605
  carries<const N extends string>(...names: N[]): Rule<P, I & {
602
606
  [k in N]: MapRef;
603
607
  }, S, M, F, R, Su, Q>;
608
+ counts<T extends Record<string, (env: P & I & S & M) => {
609
+ below: TermLike;
610
+ body: (x: Term, k: Term) => Cond | TermLike;
611
+ }>>(cs: T): Rule<P, I & {
612
+ [k in keyof T]: MapRef;
613
+ }, S, M, F, R, Su, Q>;
604
614
  carriesSeq<const N extends string>(...names: N[]): Rule<P, I & {
605
615
  [k in N]: SeqRef;
606
616
  }, S, M, F, R, Su, Q>;
package/dist/core/dsl.js CHANGED
@@ -15,6 +15,7 @@
15
15
  //
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
+ import { searchCounted } from "./counts.js";
18
19
  import { argsKey, machineTerms, carriedView, compileFunction, divName, divisor, divisorsIn, evalC, evalE, interpret, isArithmetic, loadJs, modName, numbersOf, pairedArgs, seeded, withArithmetic } from "./machine.js";
19
20
  import { allowed, keysOf, requestEnv, watch, watchWork } from "./watch.js";
20
21
  import { someHolds, substVars, substVarsE } from "./exists.js";
@@ -1811,6 +1812,12 @@ export class Rule {
1811
1812
  facts(f) { return this.with({ facts: [...(this.spec.facts ?? []), f] }); }
1812
1813
  // Maps each request carries whole (a set of names, say: cells 0 or 1), every cell past them 0; read like any map.
1813
1814
  carries(...names) { return this.with({ carried: [...(this.spec.carried ?? []), ...names] }); }
1815
+ // Counts (Machine.counts): `.counts({votes: env => ({below: env.size, body: (x, k) => env.Vote.at(k).eq(x.plus(1))})})`;
1816
+ // each a map no step writes, at x the number of keys k below the bound where the body holds (or its sum), read by the
1817
+ // flags, the assumption and the step at the request's view, and by a law at the state.
1818
+ counts(cs) {
1819
+ return this.with({ counts: [...(this.spec.counts ?? []), ...Object.entries(cs)] });
1820
+ }
1814
1821
  // Sequences each request carries (SeqRef): `.carriesSeq('Path')`, then `Path.at(i)`, `Path.len`, `A.prefixOf(B)`; the
1815
1822
  // request gives each as an array of naturals.
1816
1823
  carriesSeq(...names) {
@@ -2097,6 +2104,8 @@ export class Rule {
2097
2104
  out[n] = k.value(n);
2098
2105
  for (const n of this.spec.carried ?? [])
2099
2106
  out[n] = new MapRef(n, 0);
2107
+ for (const [n] of this.spec.counts ?? [])
2108
+ out[n] = new MapRef(n, 0);
2100
2109
  for (const n of this.spec.seqs ?? []) {
2101
2110
  delete out[`${n}_len`];
2102
2111
  out[n] = new SeqRef(new MapRef(n, 0), v(`${n}_len`));
@@ -2274,6 +2283,10 @@ export class Rule {
2274
2283
  state: Object.fromEntries(s.state.map(([n, init]) => [n, typeof init === 'number' ? termOf(init) : termOf(init(pEnv))])),
2275
2284
  ...(s.maps.length ? { maps: Object.fromEntries(s.maps) } : {}),
2276
2285
  ...(s.carried?.length ? { inputMaps: s.carried } : {}),
2286
+ ...(s.counts?.length ? { counts: Object.fromEntries(s.counts.map(([n, f]) => {
2287
+ const c = f(env), j = `${n}$x`, key = `${n}$k`, b = c.body(v(j), v(key));
2288
+ return [n, { j, key, below: termOf(c.below), body: b instanceof Cond ? { op: 'if', c: b.c, then: { op: 'const', value: 1 }, else: { op: 'const', value: 0 } } : termOf(b) }];
2289
+ })) } : {}),
2277
2290
  step: { ...(Object.keys(flags).length ? { flags } : {}), ...(Object.keys(state).length ? { state } : {}), ...(Object.keys(maps).length ? { maps } : {}) },
2278
2291
  ...(pre.length ? { pre: pre.length === 1 ? pre[0] : { op: 'and', xs: pre } } : {}),
2279
2292
  ...(assume.length ? { assume: assume.length === 1 ? assume[0] : { op: 'and', xs: assume } } : {}),
@@ -2361,7 +2374,7 @@ export class Rule {
2361
2374
  }
2362
2375
  // One step: the flags, the updates and the step laws, each against what the interpreter computed.
2363
2376
  crossStep(params, st, input, next, stepLaws, bound, count) {
2364
- const s = this.spec, m = this.machine, run = interpret(m), seen = carriedView(m, st, input), req = requestEnv(m, run, params, st, input);
2377
+ const s = this.spec, m = this.machine, run = interpret(m), seen = carriedView(m, st, input, undefined, params), req = requestEnv(m, run, params, st, input);
2365
2378
  const keys = keysOf(bound, seen, next), vars = { ...params, ...st.scalars, ...req };
2366
2379
  const sc = { vars, maps: Object.fromEntries(Object.entries(seen.maps).map(([n, cells]) => [n, { cells, dflt: seen.defaults?.[n] ?? m.maps?.[n] ?? 0 }])), keys: exactKeys(keys, vars, seen, next), flags: {} };
2367
2380
  // Flags: every callback in order, each name's last definition winning, until the values settle (a name defined
@@ -2914,6 +2927,11 @@ export function proveRule(r, laws, opts = {}) {
2914
2927
  // (A step law broken so is refused, proveSteps below: it holds from every state the laws allow, reached or not.)
2915
2928
  if (refuted)
2916
2929
  return refuted.run ? refutedVerdict(refuted) : searched(r, laws, [], refutedVerdict(refuted), opts);
2930
+ // A rule with counts: its goals are the counted ones (core/counts.ts searches them; the kernel checks the set).
2931
+ if (r.machine.counts && Object.keys(r.machine.counts).length) {
2932
+ const c = searchCounted(r.machine, withKinds(r, laws), typeof opts.search === 'object' ? opts.search.ms ?? 60_000 : 60_000);
2933
+ return { proven: c.proven, checked: c.proven, ...(c.why ? { why: c.why } : {}), found: { laws: c.laws.map(l => ({ text: l.name })) } };
2934
+ }
2917
2935
  const out = (opts.fast ? proveSetFast : proveLaws)(r.machine, withKinds(r, laws));
2918
2936
  const v = { ...verdictOf(out), ...(out.witnesses && out.proven ? { witnesses: out.witnesses } : {}) };
2919
2937
  return searched(r, laws, [], v, opts);
@@ -70,6 +70,7 @@ export declare const kindOfVar: (v: Var, sorts: Sorts, at?: string) => Kind<unkn
70
70
  export declare function ruleSnap(r: Rule, m: Model, st: State, sorts: Sorts): Snap;
71
71
  export declare function ruleState(base: State, s: Snap, m: Model, sorts: Sorts): State;
72
72
  export declare function constantsOf(m: Model): number[];
73
+ export declare function stringsOf(m: Model): string[];
73
74
  export declare function draw(sort: Var['sort'], sorts: Sorts, name: string, rand: Rand, near: number[], bound: number, strs: string[]): Raw;
74
75
  export type CheckOptions = {
75
76
  runs?: number;
@@ -334,11 +334,18 @@ const cellKind = (d, sorts) => record({ has: bool, ...Object.fromEntries(d.field
334
334
  const BIG = [Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER - 1, 2 ** 31, 2 ** 32];
335
335
  export function constantsOf(m) {
336
336
  const out = new Set([0, 1]);
337
- walk([m.writes, m.mapWrites, m.refuse, m.pre, m.init], o => { if (o.op === 'const' && typeof o.v === 'number')
337
+ walk([m.writes, m.mapWrites, m.refuse, m.pre, m.init, m.folds ?? []], o => { if (o.op === 'const' && typeof o.v === 'number')
338
338
  out.add(o.v); if (typeof o.k === 'number')
339
339
  out.add(o.k); });
340
340
  return [...out];
341
341
  }
342
+ // The strings drawn: a few, and the literals the rule compares with.
343
+ export function stringsOf(m) {
344
+ const out = new Set(['a', 'b', 'c', '']);
345
+ walk([m.writes, m.mapWrites, m.refuse, m.folds ?? []], o => { if (o.op === 'slit' && typeof o.value === 'string')
346
+ out.add(o.value); });
347
+ return [...out];
348
+ }
342
349
  export function draw(sort, sorts, name, rand, near, bound, strs) {
343
350
  switch (sort.k) {
344
351
  case 'bool': return rand(2) === 1;
@@ -447,7 +454,7 @@ export function drive(m, r, sorts, code, opts = {}) {
447
454
  const isClass = m.shape === 'class';
448
455
  const interp = r.interpreter(), gen = r.compiled(), machine = r.machine;
449
456
  const ev = { runs: 0, requests: 0, fromStates: 0, probes: { conditions: 0, witnesses: 0, steps: 0 }, refusedBoth: 0, outside: 0, edge: 0, compiledAgreed: 0, coverage: { arms: 0, hit: 0, missed: [] }, ms: 0 };
450
- const consts = constantsOf(m), strs = ['a', 'b', 'c', ''];
457
+ const consts = constantsOf(m), strs = stringsOf(m);
451
458
  const paramKinds = m.params.map(v => [v, kindOfVar(v, sorts)]), inputKinds = m.inputs.map(v => [v, kindOfVar(v, sorts)]);
452
459
  const fail = (what) => { ev.mismatch = what; return finish(); };
453
460
  const finish = () => {
@@ -475,6 +482,9 @@ export function drive(m, r, sorts, code, opts = {}) {
475
482
  const x = draw(v.sort, sorts, v.name, rand, near, bound, [...strs, ...keys]);
476
483
  inputs[v.name] = code.input ? code.input(v, x, rand) : opts.given?.[v.name] === 'nat' && typeof x === 'number' ? Math.abs(x) : x;
477
484
  }
485
+ // (a list the request carries: up to 4 items, mostly, each field drawn by its sort)
486
+ for (const q of m.seqs ?? [])
487
+ inputs[q.name] = Array.from({ length: rand(4) === 0 ? rand(bound + 1) : rand(5) }, () => Object.fromEntries(q.fields.map(f => [f.name, draw(f.sort, sorts, `${q.name}.${f.name}`, rand, near, bound, strs)])));
478
488
  return { e, inputs };
479
489
  };
480
490
  const ruleInputs = (inputs, e) => {
@@ -498,6 +508,8 @@ export function drive(m, r, sorts, code, opts = {}) {
498
508
  // through `next`), else the difference.
499
509
  const step = (params, ps, side, st, inputs, e, next, where) => {
500
510
  const args = code.args(inputs, e), raw = ruleInputs(inputs, e);
511
+ if (m.folds)
512
+ carry(m, raw, inputs, side.snap, params, r.decode(st));
501
513
  const nowVar = m.inputs.find(v => v.note?.startsWith('Date.now()'));
502
514
  if (nowVar)
503
515
  code.setNow(inputs[nowVar.name]);
@@ -756,8 +768,9 @@ export function drive(m, r, sorts, code, opts = {}) {
756
768
  if (diff)
757
769
  return fail(diff);
758
770
  }
759
- // Steps from the prover's counterexamples: each condition of the step, refuted as "never holds".
760
- if (opts.probes !== false) {
771
+ // Steps from the prover's counterexamples: each condition of the step, refuted as "never holds". (Not where the
772
+ // rule carries folds: their equations, quantified over every pass, make each probe slow, and a witness's lists empty.)
773
+ if (opts.probes !== false && !m.folds?.length) {
761
774
  const conds = conditionsOf(m);
762
775
  for (const [i, c] of conds.entries()) {
763
776
  ev.probes.conditions++;
@@ -889,11 +902,35 @@ export function condAt(c, env) {
889
902
  }
890
903
  import { yes as yesC, no as noC, when as whenDsl } from "./dsl.js";
891
904
  const whenInt = (c, a, b) => whenDsl(c, a, b);
905
+ // The lists a request carries, and each fold's running values as its passes compute them over the items (from the
906
+ // state before the step, the request and the params): what the rule assumes every request carries.
907
+ // (dec: the rule's state before the step, decoded: a list of the state at the rule's own places)
908
+ function carry(m, raw, inputs, st, params, dec) {
909
+ const lists = {};
910
+ for (const q of m.seqs ?? []) {
911
+ lists[q.name] = (inputs[q.name] ?? []);
912
+ raw[q.name] = lists[q.name];
913
+ raw[`${q.name}_len`] = lists[q.name].length;
914
+ }
915
+ const dflt = (map, field) => { const f = m.maps.find(d => d.name === map)?.fields.find(x => x.name === field); return field === 'has' || f?.sort.k === 'bool' ? false : f?.sort.k === 'choice' ? f.sort.values[0] : 0; };
916
+ const cell = (map, key, field) => (lists[map] ? lists[map][key][field] : dec[map]?.[String(key)]?.[field] ?? dflt(map, field));
917
+ for (const d of m.folds ?? []) {
918
+ // (the passes: a carried list's length, or one past a list of the state's last place)
919
+ const env = { ...params, ...st.leaves, ...raw }, runs = [];
920
+ const n = d.state ? Math.max(-1, ...Object.entries(dec[d.list] ?? {}).filter(([, c]) => c.has).map(([k]) => Number(k))) + 1 : (lists[d.list] ?? []).length;
921
+ const at = (t, i) => evalTerm(t.e, i === undefined ? env : { ...env, [I.PASS]: i }, cell);
922
+ runs.push(Object.fromEntries(d.fields.map(f => [f.name, at(d.init[f.name])])));
923
+ lists[d.run] = runs;
924
+ for (let i = 0; i < n; i++)
925
+ runs.push(Object.fromEntries(d.fields.map(f => [f.name, at(d.step[f.name], i)])));
926
+ raw[d.run] = runs;
927
+ }
928
+ }
892
929
  // A term at concrete values (a constant field over the params, a start, the precondition; with `cell`, a state's
893
930
  // map cells and list items too).
894
931
  export function evalTerm(t, env, cell) {
895
932
  const at = (map, k, field) => (cell ?? (() => { throw new Error('a map cell at the start'); }))(map, key(k), field);
896
- const key = (k) => (k.op === 'num' ? n(k.e) : k.op === 'svar' ? env[k.name] : k.op === 'slit' ? k.value : b(k.c) ? key(k.a) : key(k.b));
933
+ const key = (k) => (k.op === 'num' ? n(k.e) : k.op === 'svar' ? env[k.name] : k.op === 'slit' ? k.value : k.op === 'cell' ? at(k.map, k.key, k.field) : b(k.c) ? key(k.a) : key(k.b));
897
934
  const n = (e) => {
898
935
  switch (e.op) {
899
936
  case 'var': return env[e.name];
@@ -911,7 +948,7 @@ export function evalTerm(t, env, cell) {
911
948
  case 'cell': return at(e.map, e.key, e.field);
912
949
  }
913
950
  };
914
- const l = (x) => (x.op === 'var' ? env[x.name] : x.op === 'lit' ? x.value : x.op === 'ite' ? (b(x.c) ? l(x.a) : l(x.b)) : (() => { throw new Error('a map cell'); })());
951
+ const l = (x) => (x.op === 'var' ? env[x.name] : x.op === 'lit' ? x.value : x.op === 'ite' ? (b(x.c) ? l(x.a) : l(x.b)) : at(x.map, x.key, x.field));
915
952
  const b = (x) => {
916
953
  switch (x.op) {
917
954
  case 'const': return x.v;
@@ -104,7 +104,13 @@ export type K = {
104
104
  c: B;
105
105
  a: K;
106
106
  b: K;
107
+ } | {
108
+ op: 'cell';
109
+ map: string;
110
+ key: K;
111
+ field: string;
107
112
  };
113
+ export declare const PASS = "i$";
108
114
  export declare const keyOf: (x: object) => string;
109
115
  export declare const same: (a: object, b: object) => boolean;
110
116
  export declare const num: (v: number) => N;
@@ -1,3 +1,5 @@
1
+ // The pass a fold's step is at: a bound name in its terms (cells of carried lists at i$ and i$ + 1).
2
+ export const PASS = 'i$';
1
3
  // Structural keys (memoized: the same object is compared many times while paths merge).
2
4
  const keys = new WeakMap();
3
5
  export const keyOf = (x) => {
@@ -242,8 +242,32 @@ export function sortsOf(m, given = {}) {
242
242
  if (d.fields[0].sort.k === 'num')
243
243
  sorts.set(`${d.name}.$item`, given[`${d.name}.$item`] ?? 'nat');
244
244
  }
245
+ // A carried list's length and a fold's pass are naturals; an item's numbers integers (any the request carries), a
246
+ // fold's running ones naturals until its start or a step may be below 0.
247
+ for (const q of m.seqs ?? []) {
248
+ sorts.set(`${q.name}_len`, 'nat');
249
+ for (const f of q.fields)
250
+ if (f.sort.k === 'num')
251
+ sorts.set(`${q.name}.${f.name}`, given[`${q.name}.${f.name}`] ?? 'int');
252
+ }
253
+ for (const d of m.folds ?? []) {
254
+ sorts.set(`${d.run}_len`, 'nat');
255
+ for (const f of d.fields)
256
+ if (f.sort.k === 'num')
257
+ sorts.set(`${d.run}.${f.name}`, 'nat');
258
+ }
259
+ if (m.folds?.length)
260
+ sorts.set(I.PASS, 'nat');
245
261
  for (let changed = true; changed;) {
246
262
  changed = false;
263
+ for (const d of m.folds ?? [])
264
+ for (const f of d.fields) {
265
+ const n = `${d.run}.${f.name}`, a = d.init[f.name], b = d.step[f.name];
266
+ if (f.sort.k === 'num' && sorts.get(n) === 'nat' && ((a.s === 'num' && !natOK(a.e, ctx0())) || (b.s === 'num' && !natOK(b.e, ctx0())))) {
267
+ sorts.set(n, 'int');
268
+ changed = true;
269
+ }
270
+ }
247
271
  for (const v of nums(m.state)) {
248
272
  if (sorts.get(v.name) === 'int' || given[v.name])
249
273
  continue;
@@ -391,8 +415,8 @@ export function pb(c, P, ctx) {
391
415
  case 'is': return `${pl(c.l, P, ctx)}.is(${q(c.value)})`;
392
416
  case 'leq': return `${pl(c.a, P, ctx)}.eq(${pl(c.b, P, ctx)})`;
393
417
  case 'keq': {
394
- const s = (k) => (k.op === 'svar' ? k.name : k.op === 'slit' ? q(k.value) : pk(k, P, ctx));
395
- return c.a.op === 'svar' ? `${c.a.name}.eq(${s(c.b)})` : c.b.op === 'svar' ? `${c.b.name}.eq(${s(c.a)})` : `${pk(c.a, P, ctx)}.eq(${pk(c.b, P, ctx)})`;
418
+ const s = (k) => (k.op === 'svar' || k.op === 'cell' ? pstr(k, P, ctx) : k.op === 'slit' ? q(k.value) : pk(k, P, ctx));
419
+ return c.a.op === 'svar' || c.a.op === 'cell' ? `${pstr(c.a, P, ctx)}.eq(${s(c.b)})` : c.b.op === 'svar' || c.b.op === 'cell' ? `${pstr(c.b, P, ctx)}.eq(${s(c.a)})` : `${pk(c.a, P, ctx)}.eq(${pk(c.b, P, ctx)})`;
396
420
  }
397
421
  case 'cell': return cellText(c, P, ctx);
398
422
  }
@@ -428,6 +452,7 @@ export function pk(k, P, ctx) {
428
452
  throw new Refusal(P.m.file, 'a map key that may be negative (a rule\'s map is keyed by naturals)');
429
453
  return pn(k.e, P, ctx, 'nat');
430
454
  case 'svar': return `${k.name}.id`;
455
+ case 'cell': return `${cellText(k, P, ctx)}.id`;
431
456
  case 'slit': return `intern(${q(k.value)})`;
432
457
  case 'kite': return `when(${pb(k.c, P, ctx)}, ${pk(k.a, P, ctx)}, ${pk(k.b, P, ctx)})`;
433
458
  }
@@ -445,6 +470,8 @@ export function pterm(t, P, ctx, target) {
445
470
  function pstr(k, P, ctx, top = false) {
446
471
  if (k.op === 'svar')
447
472
  return k.name;
473
+ if (k.op === 'cell')
474
+ return cellText(k, P, ctx);
448
475
  if (k.op === 'slit') {
449
476
  if (top)
450
477
  return q(k.value);
@@ -48,6 +48,7 @@ export type MapDecl = {
48
48
  untyped?: boolean;
49
49
  len?: number;
50
50
  ordered?: true;
51
+ carried?: true;
51
52
  };
52
53
  export type LeastRead = {
53
54
  name: string;
@@ -194,6 +195,17 @@ export type Model = {
194
195
  imports?: string[];
195
196
  kind?: string;
196
197
  leasts?: LeastRead[];
198
+ seqs?: MapDecl[];
199
+ folds?: Fold[];
200
+ };
201
+ export type Fold = {
202
+ list: string;
203
+ run: string;
204
+ fields: Var[];
205
+ init: Record<string, Term>;
206
+ step: Record<string, Term>;
207
+ len: N;
208
+ state?: true;
197
209
  };
198
210
  type V = {
199
211
  t: 'num';