gdp-wired 0.54.2 → 0.55.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.
package/README.md CHANGED
@@ -167,7 +167,10 @@ the annotation declared in your code), `@gdp_law("...")` in Python, `@gdp_law ".
167
167
  (`counts[user]`, `user in counts`, `cache["rl:" + user]`), `forall k in m: ...`, a choice by its value (`mode ==
168
168
  "closed"`). Anything else is refused with why, never dropped. Modelling choices a rule needs (`failures = "kept"` for
169
169
  laws about when it raises, a store's attributes, an untyped result) go in a `gdp.toml` beside the code (or `[tool.gdp]`
170
- in pyproject.toml, `"gdp"` in package.json), per rule under `[rules.<name>]`. The exit code is 1 when a stated law is
170
+ in pyproject.toml, `"gdp"` in package.json), per rule under `[rules.<name>]`. When an individual stated invariant or step
171
+ law ends `unknown` (neither proven nor refuted) in default reachable-state `check`, it is retried jointly with the other
172
+ laws stated on the same rule within the time its own budget has left, crediting only that law and only if the kernel checks
173
+ the whole joint family (never changing a proven or refuted verdict). The exit code is 1 when a stated law is
171
174
  broken, 2 when one couldn't be checked: `uses: monotykamary/gdp-wired@main` with `paths:` runs it in CI.
172
175
 
173
176
  Laws about two runs read the same way: `diagnosis never reaches status, result` (two runs differing only in the
@@ -250,7 +253,9 @@ All of these are proven automatically, and each proof is also a Lean theorem:
250
253
  and no run breaks them, it looks for lemmas about the rule's recurrences and lists (`discover`), lemmas about the
251
254
  functions it knows by their facts (`cycleLemmas`, each proven by a cyclic proof) and then invariants (`inferLaws`),
252
255
  under a configurable search allowance (`{search: {ms: 10000}}` by default; `{search: false}`, the prover alone);
253
- the verdict's `found` holds what proved them, as laws and lemmas with the source to paste.
256
+ the verdict's `found` holds what proved them, as laws and lemmas with the source to paste. Callers who pass several
257
+ laws on the same rule (`proveRule(rule, [law1, law2])` or `proveSteps(rule, laws, [step1, step2])`) already get joint
258
+ proof — the search and kernel check all of them together as one family, rather than proving one law at a time.
254
259
  [Explicit counted work and stop causes](docs/search-budgets.md) separate the search allowance from an optional
255
260
  real-time safety watchdog; legacy `ms` is not a promise of machine-independent completion. Each invariant found holds in the states reachable from the
256
261
  start, so a proof that needs one holds there and the verdict says so (`assumes: {states: 'reachable', laws}`). Code that
@@ -1,8 +1,9 @@
1
1
  import type { Law, Machine } from './machine.js';
2
2
  import { type FiniteSumCertificate } from '../kernel/finite-sum.js';
3
3
  import { type GhostWriteCertificate } from '../kernel/ghost-write.js';
4
+ import type { GroupedSumCertificate } from '../kernel/grouped-sum.js';
4
5
  import { type AggregateKinds } from './aggregate-kinds.js';
5
- export type AggregateCertificate = FiniteSumCertificate | GhostWriteCertificate;
6
+ export type AggregateCertificate = FiniteSumCertificate | GhostWriteCertificate | GroupedSumCertificate;
6
7
  export declare function searchAggregate(m: Machine, law: Law, getKinds: () => Law[], ms: number): {
7
8
  certificate: AggregateCertificate;
8
9
  kinds?: AggregateKinds;
@@ -1,6 +1,7 @@
1
1
  import { searchWall } from "./wall.js";
2
2
  import { proposeFilteredCounters } from "./filtered-sum-candidates.js";
3
3
  import { weightedSearch } from "./aggregate-weighted/search.js";
4
+ import { hasGroupedSumShape, searchGroupedSum } from "./grouped-sum-search.js";
4
5
  import { checkFiniteSum, finiteSumTheory, sumLocalGoal } from "../kernel/finite-sum.js";
5
6
  import { checkGhostWrite } from "../kernel/ghost-write.js";
6
7
  import { clock, grow, pastWall, withWall } from "../kernel/prove.js";
@@ -64,9 +65,20 @@ function proposeAggregate(m, law, ms) {
64
65
  return undefined;
65
66
  });
66
67
  }
67
- if (!maps.some(write => 'each' in write) || !maps.some(write => !('each' in write)))
68
+ const canWeight = maps.some(write => 'each' in write) && maps.some(write => !('each' in write));
69
+ const until = clock() + ms;
70
+ if (hasGroupedSumShape(m, law)) {
71
+ const groupBudget = canWeight ? Math.min(5_000, Math.floor(ms / 3)) : Math.min(10_000, ms);
72
+ const grouped = searchGroupedSum(m, law, groupBudget);
73
+ if (grouped)
74
+ return grouped;
75
+ }
76
+ if (!canWeight)
77
+ return;
78
+ const remaining = until - clock();
79
+ if (!(remaining > 0))
68
80
  return;
69
- const p = weightedSearch(m, law, ms);
81
+ const p = weightedSearch(m, law, remaining);
70
82
  if (!p)
71
83
  return;
72
84
  const cert = { kind: 'ghost-write', recipe: p.recipe, projection: { omitMap: p.recipe.ghostMap }, target: p.machine, laws: p.laws, pointLaw: p.pointLaw, proof: p.proof };
package/dist/core/cli.js CHANGED
@@ -680,11 +680,12 @@ function* checkPipeline(t, o) {
680
680
  // (from any state, the laws about states as one inductive set: the largest the stated ones make, each law the
681
681
  // kernel's step breaks taken out in turn (Houdini), the others proven together; one taken out is judged alone)
682
682
  const inductive = from && x.rule && !sys ? houdini(x, stated.filter(m => twice(m).length === 1 && kindOf(m) === 'law'), o.ms, ctx, o.work, o.watchdogMs) : undefined;
683
+ const siblings = !from && !sys ? stated.filter(m => twice(m).length === 1) : undefined;
683
684
  const outsOf = [];
684
685
  for (const i of order) {
685
686
  const l = stated[i];
686
687
  outsOf[i] = twice(l).length > 1 ? { name: l.name, expr: l.expr, where: l.where, verdict: 'not read', why: `a law of this name is stated twice (${twice(l).join(', ')}): a law is known by its name`, ms: 0 }
687
- : sys ? proveInEnv(x, l, o.ms, proven, { ...ctx, sys, entry: name }) : prove(x, l, o.ms, proven, { ...ctx, entry: name, ...(from ? { from, inductive, together: stated.filter(m => twice(m).length === 1 && kindOf(m) === 'law' && inductive.has(m.name)) } : {}) });
688
+ : sys ? proveInEnv(x, l, o.ms, proven, { ...ctx, sys, entry: name }) : prove(x, l, o.ms, proven, { ...ctx, entry: name, ...(from ? { from, inductive, together: stated.filter(m => twice(m).length === 1 && kindOf(m) === 'law' && inductive.has(m.name)) } : siblings ? { siblings } : {}) });
688
689
  }
689
690
  r.laws = outsOf;
690
691
  if (o.security) {
@@ -754,12 +755,15 @@ function houdini(x, ls, ms, opts, work, watchdogMs) {
754
755
  // an interchange document whose meta holds them.
755
756
  // The rule a law is proven on: the extraction's, declaring the divisors the law reads that the code doesn't (x // k,
756
757
  // x % k: floor division and remainder by a constant, known by their facts), its machine made again with them.
758
+ function divisorsOf(expr) {
759
+ return [...new Set([...expr.matchAll(/(?:\/\/|%)\s*(\d+)/g)].map(m => Number(m[1])).filter(k => k >= 1))].sort((a, b) => a - b);
760
+ }
757
761
  function ruleFor(x, expr) {
758
762
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
759
763
  const r = x.rule;
760
764
  if (!r)
761
765
  return x;
762
- const ks = [...expr.matchAll(/(?:\/\/|%)\s*(\d+)/g)].map(m => Number(m[1])).filter(k => k >= 1);
766
+ const ks = divisorsOf(expr);
763
767
  return ks.length ? { ...x, rule: r.withDivisors(...ks) } : x;
764
768
  }
765
769
  function prove(x0, l, ms, proven, ctx, work = ctx?.work) {
@@ -857,6 +861,72 @@ function prove(x0, l, ms, proven, ctx, work = ctx?.work) {
857
861
  verdict = 'unknown';
858
862
  if (v.translation === 'error')
859
863
  verdict = 'not read';
864
+ let jointCertInvs;
865
+ // Fallback only: when an ordinary reachable-state law ends unknown (neither proven nor refuted), retry it jointly
866
+ // with the other laws stated on the same rule within the time left in this law's own budget. Credit only this law,
867
+ // and only if the kernel checks the whole joint family (including this law).
868
+ if (verdict === 'unknown' && b && !ctx?.from && work === undefined && !v.proven && !v.run
869
+ && !(v.stopped && v.termination?.kind === 'wall-deadline')
870
+ && v.translation !== 'unchecked' && v.translation !== 'error' && (ctx?.siblings?.length ?? 0) > 1) {
871
+ const budgetCap = ctx.watchdogMs !== undefined ? Math.min(ms, ctx.watchdogMs) : ms;
872
+ const remaining = Math.floor(budgetCap - (cliNow() - t0));
873
+ if (remaining >= 1) {
874
+ const targetDivs = divisorsOf(l.expr).join(',');
875
+ const jointInvs = [...inv];
876
+ const jointSteps = [];
877
+ const addedStated = new Set();
878
+ let siblingCount = 0;
879
+ let targetInJoint = false;
880
+ for (const m of ctx.siblings) {
881
+ if (m.name === l.name) {
882
+ if (b.kind === 'law')
883
+ jointInvs.push(b.law);
884
+ else
885
+ jointSteps.push(b.law);
886
+ addedStated.add(m.name);
887
+ targetInJoint = true;
888
+ continue;
889
+ }
890
+ if (isLeadsTo(m.expr) || isTwoRuns(m.expr) || divisorsOf(m.expr).join(',') !== targetDivs)
891
+ continue;
892
+ let sb;
893
+ try {
894
+ sb = buildLaw(x, m, ctx);
895
+ }
896
+ catch {
897
+ continue;
898
+ }
899
+ if (sb.kind === 'law')
900
+ jointInvs.push(sb.law);
901
+ else
902
+ jointSteps.push(sb.law);
903
+ addedStated.add(m.name);
904
+ siblingCount++;
905
+ }
906
+ if (b.kind === 'step') {
907
+ for (const p of proven)
908
+ if (!addedStated.has(p.name))
909
+ jointInvs.push(p);
910
+ }
911
+ if (targetInJoint && siblingCount >= 1) {
912
+ const jointOpts = { search: { ms: remaining }, ...(!syncControl || ctx.watchdogMs !== undefined ? { watchdogMs: remaining } : {}) };
913
+ try {
914
+ const jv = jointSteps.length
915
+ ? proveSteps(x.rule, jointInvs, jointSteps, jointOpts)
916
+ : proveRule(x.rule, jointInvs, jointOpts);
917
+ if (jv.proven && jv.checked && jv.translation !== 'unchecked' && jv.translation !== 'error') {
918
+ v = jv;
919
+ verdict = 'proven';
920
+ jointCertInvs = jointInvs;
921
+ }
922
+ }
923
+ catch (e) {
924
+ if (e && typeof e === 'object' && e.name === 'Refusal')
925
+ throw e;
926
+ }
927
+ }
928
+ }
929
+ }
860
930
  if (ctx?.from && v.proven && v.assumes)
861
931
  v.why = `proven only in states a run from the start reaches (from = "any" asks for every state the laws allow): it needs ${v.assumes.laws.join('; ') || 'k-induction'}`;
862
932
  // (a run the front end replays on the code: broken only where the code runs it so)
@@ -879,7 +949,8 @@ function prove(x0, l, ms, proven, ctx, work = ctx?.work) {
879
949
  const more = v.found?.laws?.map(f => f.law) ?? [];
880
950
  const meta = { producer: 'gdp-wired check', file: ctx.file, ...(ctx.entry ? { entry: ctx.entry } : {}), law: l.name, expr: l.expr, ...(l.where ? { where: l.where } : {}), cites };
881
951
  const doc = v.k ? undefined : two ? certify(two.rule, [...v.given ?? [], ...more, ...two.laws], two.stepLaws, meta)
882
- : b.kind === 'law' ? certify(x.rule, [...inv, ...more, b.law], [], meta) : certify(x.rule, [...inv, ...proven, ...more], [b.law], meta);
952
+ : jointCertInvs ? certify(x.rule, [...jointCertInvs, ...more], b.kind === 'step' ? [b.law] : [], meta)
953
+ : b.kind === 'law' ? certify(x.rule, [...inv, ...more, b.law], [], meta) : certify(x.rule, [...inv, ...proven, ...more], [b.law], meta);
883
954
  if (doc) {
884
955
  fs.mkdirSync(ctx.cert, { recursive: true });
885
956
  cert = path.join(ctx.cert, `${[ctx.entry ?? path.basename(ctx.file), l.name].join('.').replace(/[^\w.-]+/g, '-')}.json`);
@@ -0,0 +1,4 @@
1
+ import { type Law, type Machine } from './machine.js';
2
+ import { type GroupedSumCertificate } from '../kernel/grouped-sum.js';
3
+ export declare const hasGroupedSumShape: (source: Machine, law: Law) => boolean;
4
+ export declare function searchGroupedSum(source: Machine, law: Law, ms: number): GroupedSumCertificate | undefined;
@@ -0,0 +1,327 @@
1
+ // Untrusted grouped-sum candidate synthesis and proving.
2
+ // Recognizes row-grouped covering laws of the shape:
3
+ // ∀ k. G(k) ⇒ w(k) ≤ Tot[grp(k)] (and companion scalar clauses ∀ k. G'(k) ⇒ w'(k) ≤ X)
4
+ // synthesizes fresh observer + parameterized sum helpers, proves the plain SMachine family,
5
+ // and accepts ONLY certificates verified by the trusted checker `checkGroupedSum`.
6
+ import { atMost, get, n, not, plus, same, x } from "./machine.js";
7
+ import { checkGroupedSum, groupedSumTheory } from "../kernel/grouped-sum.js";
8
+ import { substC, substE } from "../kernel/kernel.js";
9
+ import { clock, grow, pastWall, proveLaws, withDeadline } from "../kernel/prove.js";
10
+ import { growCdcl } from "../kernel/cdcl.js";
11
+ const ZERO = n(0);
12
+ const ONE = n(1);
13
+ const text = (v) => JSON.stringify(v);
14
+ function clauses(c, neg, most) {
15
+ switch (c.op) {
16
+ case 'not': return clauses(c.x, !neg, most);
17
+ case 'and':
18
+ case 'or': {
19
+ const parts = c.xs.map(y => clauses(y, neg, most));
20
+ if (parts.some(p => !p))
21
+ return undefined;
22
+ if ((c.op === 'and') !== neg) {
23
+ const out = parts.flat();
24
+ return out.length > most ? undefined : out;
25
+ }
26
+ let out = [[]];
27
+ for (const p of parts) {
28
+ out = out.flatMap(a => p.map(b => [...a, ...b]));
29
+ if (out.length > most)
30
+ return undefined;
31
+ }
32
+ return out;
33
+ }
34
+ case '<':
35
+ case '<=':
36
+ case '=': return [[{ c, neg }]];
37
+ case 'flag':
38
+ case 'all': return undefined;
39
+ }
40
+ }
41
+ function reads(t, key, r = { vars: new Set(), maps: new Set(), keyed: true, shaped: true }) {
42
+ switch (t.op) {
43
+ case 'var':
44
+ r.vars.add(t.name);
45
+ break;
46
+ case 'const': break;
47
+ case 'get':
48
+ r.maps.add(t.map);
49
+ if (!(t.key.op === 'var' && t.key.name === key)) {
50
+ r.keyed = false;
51
+ reads(t.key, key, r);
52
+ }
53
+ break;
54
+ case 'mul':
55
+ reads(t.a, key, r);
56
+ break;
57
+ case 'add':
58
+ case 'sub':
59
+ case 'min':
60
+ case 'max':
61
+ case 'prod':
62
+ reads(t.a, key, r);
63
+ reads(t.b, key, r);
64
+ break;
65
+ case 'if':
66
+ reads(t.c, key, r);
67
+ reads(t.then, key, r);
68
+ reads(t.else, key, r);
69
+ break;
70
+ case 'tup':
71
+ case 'proj':
72
+ r.shaped = false;
73
+ break;
74
+ case '<':
75
+ case '<=':
76
+ case '=':
77
+ reads(t.a, key, r);
78
+ reads(t.b, key, r);
79
+ break;
80
+ case 'and':
81
+ case 'or':
82
+ for (const y of t.xs)
83
+ reads(y, key, r);
84
+ break;
85
+ case 'not':
86
+ reads(t.x, key, r);
87
+ break;
88
+ case 'flag':
89
+ case 'all':
90
+ r.shaped = false;
91
+ break;
92
+ }
93
+ return r;
94
+ }
95
+ function atMostLit(l) {
96
+ const c = l.c;
97
+ if (c.op === '<=' && !l.neg)
98
+ return { lo: c.a, hi: c.b };
99
+ if (c.op === '<' && l.neg)
100
+ return { lo: c.b, hi: c.a };
101
+ if (c.op === '<' && !l.neg && c.a.op === 'const')
102
+ return { lo: n(c.a.value + 1), hi: c.b };
103
+ if (c.op === '<=' && l.neg && c.b.op === 'const')
104
+ return { lo: n(c.b.value + 1), hi: c.a };
105
+ if (c.op === '=' && l.neg) {
106
+ if (c.a.op === 'const' && c.a.value === 0)
107
+ return { lo: ONE, hi: c.b };
108
+ if (c.b.op === 'const' && c.b.value === 0)
109
+ return { lo: ONE, hi: c.a };
110
+ }
111
+ return undefined;
112
+ }
113
+ const litC = (l) => (l.neg ? not(l.c) : l.c);
114
+ const notLit = (l) => (l.neg ? l.c : not(l.c));
115
+ function parseGroupedShapes(m, law) {
116
+ const key = law.forall;
117
+ if (!key || law.keys?.length || law.some?.length || law.ex || law.finite !== undefined || law.witness)
118
+ return;
119
+ if (m.history || m.primitiveFailure || Object.keys(m.counts ?? {}).length
120
+ || Object.keys(m.sums ?? {}).length || Object.keys(m.leasts ?? {}).length || !m.maps)
121
+ return;
122
+ const cs = clauses(law.holds, false, 16);
123
+ if (!cs)
124
+ return;
125
+ const stateMap = (name) => Object.hasOwn(m.maps, name) && !(m.inputMaps ?? []).includes(name) && !Object.hasOwn(m.fns ?? {}, name);
126
+ const scalarVar = (name) => Object.hasOwn(m.state, name);
127
+ const cellTerm = (t) => {
128
+ const r = reads(t, key);
129
+ return r.shaped && r.keyed && r.maps.size > 0 && r.vars.size === 0 && [...r.maps].every(stateMap);
130
+ };
131
+ const freeTerm = (t) => {
132
+ const r = reads(t, key);
133
+ return r.shaped && !r.vars.has(key) && r.maps.size === 0;
134
+ };
135
+ const scalarTotal = (t) => freeTerm(t) && [...reads(t, key).vars].some(scalarVar);
136
+ const groupedTotal = (t) => t.op === 'get' && stateMap(t.map) && cellTerm(t.key) ? { totMap: t.map, group: t.key } : undefined;
137
+ const grouped = [];
138
+ const scalar = [];
139
+ for (const clause of cs) {
140
+ const guards = [], unless = [];
141
+ let grpMatch;
142
+ let weight, scalTot;
143
+ let ok = true;
144
+ for (const l of clause) {
145
+ if (cellTerm(l.c)) {
146
+ guards.push(notLit(l));
147
+ continue;
148
+ }
149
+ const le = atMostLit(l);
150
+ if (le) {
151
+ const gt = groupedTotal(le.hi);
152
+ if (gt && !grpMatch && !scalTot && (cellTerm(le.lo) || (le.lo.op === 'const' && le.lo.value === 1))) {
153
+ grpMatch = gt;
154
+ weight = le.lo;
155
+ continue;
156
+ }
157
+ if (scalarTotal(le.hi) && !grpMatch && !weight && !scalTot && cellTerm(le.lo)) {
158
+ weight = le.lo;
159
+ scalTot = le.hi;
160
+ continue;
161
+ }
162
+ if (scalarTotal(le.hi) && !grpMatch && le.lo.op === 'const' && le.lo.value === 1 && (!weight || text(weight) === text(ONE))) {
163
+ weight = ONE;
164
+ scalTot = scalTot ? plus(scalTot, le.hi) : le.hi;
165
+ continue;
166
+ }
167
+ }
168
+ if (freeTerm(l.c)) {
169
+ unless.push(litC(l));
170
+ continue;
171
+ }
172
+ ok = false;
173
+ break;
174
+ }
175
+ if (!ok || !weight)
176
+ continue;
177
+ if (weight.op === 'const' && !guards.length)
178
+ continue;
179
+ if (grpMatch)
180
+ grouped.push({ kind: 'grouped', totMap: grpMatch.totMap, group: grpMatch.group, weight, guards, unless });
181
+ else if (scalTot)
182
+ scalar.push({ kind: 'scalar', total: scalTot, weight, guards, unless });
183
+ }
184
+ if (!grouped.length)
185
+ return;
186
+ return { key, grouped, scalar };
187
+ }
188
+ const andAll = (xs) => (xs.length === 1 ? xs[0] : { op: 'and', xs });
189
+ function tryProveVariant(source, law, observer, group, sums, laws, until) {
190
+ if (clock() >= until || pastWall())
191
+ return;
192
+ const dummy = {
193
+ kind: 'grouped-sum',
194
+ observer,
195
+ group,
196
+ sums,
197
+ laws,
198
+ proof: { instances: {}, trees: {} },
199
+ };
200
+ let theory;
201
+ try {
202
+ theory = groupedSumTheory(source, law, dummy);
203
+ }
204
+ catch {
205
+ return;
206
+ }
207
+ if (!theory)
208
+ return;
209
+ const sideTrees = Object.create(null);
210
+ for (const g of theory.initGoals) {
211
+ if (clock() >= until || pastWall())
212
+ return;
213
+ const res = grow(g, new Map(), { nodes: 0, until: Math.min(until, clock() + 500) });
214
+ if (!('tree' in res))
215
+ return;
216
+ sideTrees[g.name] = res.tree;
217
+ }
218
+ const out = withDeadline(until, () => proveLaws(theory.plain, laws));
219
+ if (!out.proven || !out.checked || !out.proof || pastWall())
220
+ return;
221
+ for (const g of theory.coverGoals) {
222
+ if (clock() >= until || pastWall())
223
+ return;
224
+ const quick = grow(g, new Map(), { nodes: 0, until: Math.min(until, clock() + 500) });
225
+ const got = 'tree' in quick ? quick : growCdcl(g, new Map(), { nodes: 0, until });
226
+ if (!('tree' in got))
227
+ return;
228
+ sideTrees[g.name] = got.tree;
229
+ }
230
+ const cert = {
231
+ kind: 'grouped-sum',
232
+ observer,
233
+ group,
234
+ sums,
235
+ laws,
236
+ proof: { instances: out.proof.instances, trees: { ...out.proof.trees, ...sideTrees } },
237
+ };
238
+ return checkGroupedSum(source, law, cert) ? cert : undefined;
239
+ }
240
+ export const hasGroupedSumShape = (source, law) => parseGroupedShapes(source, law) !== undefined;
241
+ export function searchGroupedSum(source, law, ms) {
242
+ if (!Number.isFinite(ms) || ms <= 0)
243
+ return;
244
+ const parsed = parseGroupedShapes(source, law);
245
+ if (!parsed)
246
+ return;
247
+ const { key, grouped, scalar } = parsed;
248
+ const until = clock() + ms;
249
+ // Fresh prefix avoiding every identifier already present in source or law.
250
+ const occupied = text([source, law]);
251
+ let prefix = 'gs$';
252
+ while (occupied.includes(prefix))
253
+ prefix += 'a';
254
+ const observer = `${prefix}obs`;
255
+ // Try each distinct group key expression found in the law (usually one).
256
+ const distinctGroups = [...new Map(grouped.map(g => [text(g.group), g.group])).values()];
257
+ for (const group of distinctGroups) {
258
+ if (clock() >= until || pastWall())
259
+ return;
260
+ const matchingGrouped = grouped.filter(g => text(g.group) === text(group));
261
+ const sums = Object.create(null);
262
+ const boundSpecs = [];
263
+ const zeroHelpers = [];
264
+ const seenSum = new Map();
265
+ const seenZero = new Set();
266
+ let sumIdx = 0;
267
+ const addSum = (isGrouped, guards, weight, target, unless) => {
268
+ const kName = `${prefix}k${sumIdx}`;
269
+ const subKey = { vars: { [key]: x(kName) }, maps: {}, flags: {} };
270
+ const gConds = [
271
+ ...guards.map(g => substC(g, subKey)),
272
+ ...(isGrouped ? [same(substE(group, subKey), x(observer))] : []),
273
+ ];
274
+ const wAtK = substE(weight, subKey);
275
+ const term = gConds.length ? { op: 'if', c: andAll(gConds), then: wAtK, else: ZERO } : wAtK;
276
+ const params = isGrouped ? [observer] : [];
277
+ // Deduplicate sums modulo key-binder renaming.
278
+ const sig = text({ params, term: substE(term, { vars: { [kName]: x(key) }, maps: {}, flags: {} }) });
279
+ let sName = seenSum.get(sig);
280
+ if (!sName) {
281
+ sName = `${prefix}s${sumIdx++}`;
282
+ seenSum.set(sig, sName);
283
+ sums[sName] = { key: kName, term, params };
284
+ }
285
+ boundSpecs.push({ name: `${prefix}bound_${boundSpecs.length}`, sumVar: sName, target, unless });
286
+ // Canonical inactive-cell-zero companion law for weighted sums over a 0-initialized map.
287
+ if (weight.op === 'get' && source.maps?.[weight.map] === 0 && guards.length) {
288
+ const holds = { op: 'or', xs: [andAll(guards), same(weight, ZERO)] };
289
+ const zSig = text(holds);
290
+ if (!seenZero.has(zSig)) {
291
+ seenZero.add(zSig);
292
+ zeroHelpers.push({ name: `${prefix}zero_${zeroHelpers.length}`, forall: key, holds });
293
+ }
294
+ }
295
+ };
296
+ for (const sc of scalar)
297
+ addSum(false, sc.guards, sc.weight, sc.total, sc.unless);
298
+ for (const gc of matchingGrouped)
299
+ addSum(true, gc.guards, gc.weight, get(gc.totMap, x(observer)), gc.unless);
300
+ const guardTarget = {
301
+ name: law.name,
302
+ forall: key,
303
+ holds: { op: 'or', xs: [not(same(group, x(observer))), law.holds] },
304
+ };
305
+ const makeBounds = (op) => boundSpecs.map(b => {
306
+ const cmp = op === '<=' ? atMost(x(b.sumVar), b.target) : same(x(b.sumVar), b.target);
307
+ return { name: b.name, holds: b.unless.length ? { op: 'or', xs: [...b.unless, cmp] } : cmp };
308
+ });
309
+ // Variant 0: minimal inequality family (e.g. NATS row 7).
310
+ // Variant 1: inequality family + inactive-cell-zero companions (e.g. DuckDB row 16).
311
+ // Variant 2: exact equality family + inactive-cell-zero companions.
312
+ const variants = [
313
+ [...makeBounds('<='), guardTarget],
314
+ ...(zeroHelpers.length ? [[...zeroHelpers, ...makeBounds('<='), guardTarget]] : []),
315
+ [...zeroHelpers, ...makeBounds('='), guardTarget],
316
+ ];
317
+ const sliceMs = Math.max(1000, Math.floor((until - clock()) / variants.length));
318
+ for (const laws of variants) {
319
+ if (clock() >= until || pastWall())
320
+ return;
321
+ const cert = tryProveVariant(source, law, observer, group, sums, laws, Math.min(until, clock() + sliceMs));
322
+ if (cert)
323
+ return cert;
324
+ }
325
+ }
326
+ return undefined;
327
+ }
@@ -0,0 +1,40 @@
1
+ import { type E, type Law, type Machine } from '../core/machine.js';
2
+ import { type Goal, type Instances, type Tree } from './kernel.js';
3
+ export type GroupedSumDecl = {
4
+ key: string;
5
+ term: E;
6
+ params: string[];
7
+ covers?: E[];
8
+ };
9
+ export type GroupedSumCertificate = {
10
+ kind: 'grouped-sum';
11
+ observer: string;
12
+ group: E;
13
+ sums: Record<string, GroupedSumDecl>;
14
+ laws: Law[];
15
+ proof: {
16
+ instances: Record<string, Instances>;
17
+ trees: Record<string, Tree>;
18
+ };
19
+ };
20
+ export declare function defaultGroupedCovers(m: Machine, term: E): E[];
21
+ export type CheckedGroupedSumDecl = {
22
+ name: string;
23
+ key: string;
24
+ params: string[];
25
+ term: E;
26
+ covers: E[];
27
+ flag: string;
28
+ x: string;
29
+ read: string[];
30
+ };
31
+ export declare function groupedSumTheory(source: Machine, law: Law, cert: GroupedSumCertificate): {
32
+ plain: Machine;
33
+ observer: string;
34
+ group: E;
35
+ decls: CheckedGroupedSumDecl[];
36
+ initGoals: Goal[];
37
+ coverGoals: Goal[];
38
+ guardIndex: number;
39
+ } | undefined;
40
+ export declare function checkGroupedSum(source: Machine, law: Law, cert: GroupedSumCertificate): boolean;