gdp-wired 0.52.0 → 0.53.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.
@@ -0,0 +1,10 @@
1
+ import { type Law, type Machine } from './machine.js';
2
+ import { type Instances, type Tree } from '../kernel/kernel.js';
3
+ export type AggregateKinds = {
4
+ laws: Law[];
5
+ proof: {
6
+ instances: Record<string, Instances>;
7
+ trees: Record<string, Tree>;
8
+ };
9
+ };
10
+ export declare function checkAggregateKinds(m: Machine, kinds: Law[], until: number): AggregateKinds | undefined;
@@ -0,0 +1,44 @@
1
+ // The aggregate law does not need any kind as a premise. Prove the kinds
2
+ // independently on the same source machine; ordinary checking is mandatory.
3
+ import { walkOnce } from "./machine.js";
4
+ import { checkLaws, obligations, own } from "../kernel/kernel.js";
5
+ import { clock, grow, pastWall } from "../kernel/prove.js";
6
+ import { growCdcl } from "../kernel/cdcl.js";
7
+ export function checkAggregateKinds(m, kinds, until) {
8
+ if (kinds.some(l => l.some?.length || l.keys?.length || l.finite !== undefined || l.ex))
9
+ return;
10
+ // A conjunction at any key holds iff each conjunct holds at that same key.
11
+ const parts = (c) => c.op === 'and' && c.xs.length ? c.xs.flatMap(parts) : [c];
12
+ const laws = kinds.flatMap(k => parts(k.holds).map((holds, i) => ({ ...k, name: `${k.name} [kind ${i + 1}]`, holds })));
13
+ const instances = Object.fromEntries(laws.filter(l => l.forall).map(l => {
14
+ const reads = new Set(), probe = { op: 'var', name: `${l.forall}#` };
15
+ walkOnce(l.holds, t => { const e = t; if (e.op === 'get')
16
+ reads.add(e.map); });
17
+ const addresses = [...reads].flatMap(map => {
18
+ const w = own(m.step.maps ?? {}, map);
19
+ return w && 'key' in w ? [w.key] : [];
20
+ });
21
+ const terms = [...new Map([probe, ...addresses].map(t => [JSON.stringify(t), t])).values()];
22
+ return [l.name, { [l.name]: terms }];
23
+ }));
24
+ let goals;
25
+ try {
26
+ goals = obligations(m, laws, instances);
27
+ }
28
+ catch {
29
+ if (pastWall())
30
+ return;
31
+ return;
32
+ }
33
+ const trees = Object.create(null);
34
+ for (const goal of goals) {
35
+ const quick = grow(goal, new Map(), { nodes: 0, until: Math.min(until, clock() + 75) });
36
+ const short = 'tree' in quick ? quick : growCdcl(goal, new Map(), { nodes: 0, until: Math.min(until, clock() + 3500) });
37
+ const got = 'tree' in short ? short : grow(goal, new Map(), { nodes: 0, until });
38
+ if (!('tree' in got))
39
+ return;
40
+ trees[goal.name] = got.tree;
41
+ }
42
+ const proof = { instances, trees };
43
+ return checkLaws(m, laws, proof) ? { laws, proof } : undefined;
44
+ }
@@ -0,0 +1,9 @@
1
+ import type { Law, Machine } from './machine.js';
2
+ import { type FiniteSumCertificate } from '../kernel/finite-sum.js';
3
+ import { type GhostWriteCertificate } from '../kernel/ghost-write.js';
4
+ import { type AggregateKinds } from './aggregate-kinds.js';
5
+ export type AggregateCertificate = FiniteSumCertificate | GhostWriteCertificate;
6
+ export declare function searchAggregate(m: Machine, law: Law, getKinds: () => Law[], ms: number): {
7
+ certificate: AggregateCertificate;
8
+ kinds?: AggregateKinds;
9
+ } | undefined;
@@ -0,0 +1,74 @@
1
+ import { searchWall } from "./wall.js";
2
+ import { proposeFilteredCounters } from "./filtered-sum-candidates.js";
3
+ import { weightedSearch } from "./aggregate-weighted/search.js";
4
+ import { checkFiniteSum, finiteSumTheory, sumLocalGoal } from "../kernel/finite-sum.js";
5
+ import { checkGhostWrite } from "../kernel/ghost-write.js";
6
+ import { clock, grow, pastWall, withWall } from "../kernel/prove.js";
7
+ import { checkAggregateKinds } from "./aggregate-kinds.js";
8
+ export function searchAggregate(m, law, getKinds, ms) {
9
+ // Reserve at least half the requested wall for ordinary proof/search.
10
+ const allowance = Math.min(30_000, ms / 2);
11
+ if (!(allowance > 0))
12
+ return;
13
+ return withWall(searchWall(allowance), () => {
14
+ const until = clock() + allowance;
15
+ const certificate = proposeAggregate(m, law, allowance);
16
+ if (!certificate || pastWall())
17
+ return undefined;
18
+ const kinds = getKinds();
19
+ if (!kinds.length)
20
+ return { certificate };
21
+ const checked = checkAggregateKinds(m, kinds, until);
22
+ return checked && !pastWall() ? { certificate, kinds: checked } : undefined;
23
+ });
24
+ }
25
+ function proposeAggregate(m, law, ms) {
26
+ if (ms <= 0 || m.history || m.primitiveFailure || Object.keys(m.sums ?? {}).length || Object.keys(m.counts ?? {}).length ||
27
+ Object.keys(m.fns ?? {}).length || m.facts?.length || m.inputMaps?.length || law.keys?.length || law.some?.length || law.ex)
28
+ return;
29
+ const maps = Object.values(m.step.maps ?? {});
30
+ if (!law.forall) {
31
+ if (maps.length !== 1 || !('each' in maps[0]))
32
+ return;
33
+ const allowance = Math.min(1_000, ms);
34
+ return withWall(searchWall(allowance), () => {
35
+ const until = clock() + allowance;
36
+ for (const p of proposeFilteredCounters(m, law)) {
37
+ if (p.bound.op !== 'var')
38
+ continue;
39
+ const layout = { map: p.map, bound: p.bound.name, key: p.key, offset: p.offset, fields: p.fields.map(({ field, value }) => ({ field, value })) };
40
+ // The public snapshot can lack automatically inferred sums or other
41
+ // features. Scope refusal is not a proof failure on the ordinary path.
42
+ let t;
43
+ try {
44
+ t = finiteSumTheory(m, law, layout);
45
+ }
46
+ catch {
47
+ if (pastWall())
48
+ return undefined;
49
+ continue;
50
+ }
51
+ if (!t)
52
+ continue;
53
+ const trees = Object.create(null);
54
+ for (const local of t.locals) {
55
+ const result = grow(sumLocalGoal(local), new Map(), { nodes: 0, until });
56
+ if (!('tree' in result))
57
+ break;
58
+ trees[local.name] = result.tree;
59
+ }
60
+ const cert = { kind: 'finite-sum', layout, trees };
61
+ if (checkFiniteSum(m, law, cert))
62
+ return cert;
63
+ }
64
+ return undefined;
65
+ });
66
+ }
67
+ if (!maps.some(write => 'each' in write) || !maps.some(write => !('each' in write)))
68
+ return;
69
+ const p = weightedSearch(m, law, ms);
70
+ if (!p)
71
+ return;
72
+ 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 };
73
+ return checkGhostWrite(m, law, cert) ? cert : undefined;
74
+ }
@@ -0,0 +1,18 @@
1
+ import { type E, type Law, type Machine } from '../machine.js';
2
+ export type WeightedRecipe = {
3
+ ghostMap: string;
4
+ point: E;
5
+ gates: [column: string, value: number][];
6
+ group: string;
7
+ weight: string;
8
+ observer: string;
9
+ };
10
+ export type WeightedCandidate = {
11
+ recipe: WeightedRecipe;
12
+ machine: Machine;
13
+ laws: Law[];
14
+ pointLaw: string;
15
+ agreementLaw: string;
16
+ sum: string;
17
+ };
18
+ export declare function weightedCandidates(m: Machine, law: Law): WeightedCandidate[];
@@ -0,0 +1,128 @@
1
+ // Untrusted recognition: derive a weighted-map recipe from a guarded subtraction.
2
+ // Acceptance and public-law transport belong to the caller’s trusted checker.
3
+ import { get, n, same, walkOnce, x } from "../machine.js";
4
+ import { ghostedMachine, ghostedOk, substC } from "../../kernel/kernel.js";
5
+ const text = (u) => JSON.stringify(u);
6
+ const eq = (a, b) => text(a) === text(b);
7
+ const flat = (op, c) => c.op === op ? c.xs.flatMap(t => flat(op, t)) : [c];
8
+ const zero = n(0);
9
+ const sameKey = (t, k) => eq(t, k);
10
+ const at = (t, nm) => t.op === 'var' && t.name === nm;
11
+ const isZero = (t, o) => t.op === 'const' && t.value === (o ?? 0);
12
+ const and = (xs) => ({ op: 'and', xs });
13
+ const ite = (c, then, otherwise) => ({ op: 'if', c, then, else: otherwise });
14
+ const noSub = { vars: {}, maps: {}, flags: {} };
15
+ const termReads = (t) => { const a = []; walkOnce(t, o => { const e = o; if (e.op === 'get')
16
+ a.push(e); }); return a; };
17
+ const points = (m, map) => { const w = m.step.maps?.[map]; return w && !('each' in w) ? w : undefined; };
18
+ const labels = (m, c, matching, negated = false) => {
19
+ const r = [];
20
+ const pattern = (node) => {
21
+ if (node.op !== '=')
22
+ return;
23
+ const t = node.a.op === 'get' ? node.a : node.b.op === 'get' ? node.b : undefined, v = t === node.a ? node.b : node.a;
24
+ if (t && v.op === 'const' && matching(t) && Object.hasOwn(m.maps ?? {}, t.map) && m.maps[t.map] !== v.value)
25
+ r.push([t.map, v.value]);
26
+ };
27
+ if (!negated)
28
+ walkOnce(c, o => pattern(o));
29
+ else
30
+ walkOnce(c, o => { const q = o; if (q.op === 'not')
31
+ pattern(q.x); });
32
+ return r;
33
+ };
34
+ export function weightedCandidates(m, law) {
35
+ if (!law.forall || law.keys?.length || law.some?.length || law.ex || law.finite !== undefined ||
36
+ m.history || m.primitiveFailure || m.sums || Object.keys(m.counts ?? {}).length || m.inputMaps?.length ||
37
+ Object.keys(m.fns ?? {}).length || m.facts?.length || Object.keys(m.leasts ?? {}).length)
38
+ return [];
39
+ const key = law.forall, ws = m.step.maps ?? {}, names = text([m, law]);
40
+ let prefix = 'weight$';
41
+ while (names.includes(prefix))
42
+ prefix += 'a';
43
+ const obs = `${prefix}observer`, binder = `${prefix}item`, wm = `${prefix}map`, sum = `${prefix}sum`, selected = x(obs);
44
+ // The lane’s canonical family uses its exact closed-flag view: each source
45
+ // flag is inlined in order, then bound over an unused fresh key. Do not
46
+ // substitute a different ghost assignment or rewrite any source writes.
47
+ const sumKey = `${prefix}index`, fresh = [obs, wm, sum, sumKey];
48
+ let stem = 'internal$';
49
+ while (text([m, law, fresh]).includes(stem))
50
+ stem += 'a';
51
+ const closed = Object.create(null), inlined = Object.create(null);
52
+ for (const [i, [name, condition]] of Object.entries(m.step.flags ?? {}).entries()) {
53
+ if (condition.op === 'all')
54
+ return [];
55
+ const c = substC(condition, { ...noSub, flags: inlined });
56
+ inlined[name] = c;
57
+ closed[name] = { op: 'all', key: `${stem}${i}`, c };
58
+ }
59
+ const o = { ...m, params: [...m.params, obs], step: { ...m.step, flags: closed } }, res = [];
60
+ for (const aMap of new Set(termReads(law.holds).filter(r => at(r.key, key)).map(r => r.map))) {
61
+ const wr = ws[aMap], u = wr && 'each' in wr && wr.value;
62
+ if (!u || u.op !== 'if' || !isZero(u.then))
63
+ continue;
64
+ const ix = wr.each, delta = u.else;
65
+ if (delta.op !== 'if' || !eq(delta.else, get(aMap, x(ix))) || delta.then.op !== 'sub')
66
+ continue;
67
+ const sub = delta.then;
68
+ if (sub.a.op !== 'add' || !eq(sub.a.a, get(aMap, x(ix))) || sub.b.op !== 'if' || !isZero(sub.b.else) || sub.b.then.op !== 'get')
69
+ continue;
70
+ const { map: weight, key: point } = sub.b.then, ww = points(m, weight);
71
+ if (!ww || !m.maps || m.maps[aMap] !== 0)
72
+ continue;
73
+ // Structural role match: the accumulator's addressed guard equates its
74
+ // own key to a foreign-key field of the same row as the removed weight.
75
+ const groups = new Set();
76
+ walkOnce(delta.c, node => {
77
+ const c = node;
78
+ if (c.op !== '=')
79
+ return;
80
+ for (const [k, t] of [[c.a, c.b], [c.b, c.a]]) {
81
+ if (at(k, ix) && t.op === 'get' && sameKey(t.key, point) && eq(points(m, t.map)?.key, ww.key))
82
+ groups.add(t.map);
83
+ }
84
+ });
85
+ if (groups.size !== 1)
86
+ continue;
87
+ const [group] = groups;
88
+ const aliases = point.op === 'if' ? [point.then, point.else] : [point];
89
+ const guards = flat('or', sub.b.c).flatMap(c => c.op === 'flag' && m.step.flags?.[c.name] ? [m.step.flags[c.name]] : []);
90
+ if (!guards.length)
91
+ continue;
92
+ const byGuard = guards.map(c => labels(m, c, r => aliases.some(k => eq(k, r.key)) && !!points(m, r.map)));
93
+ const gates = [...new Map(byGuard[0].filter(a => byGuard.every(xs => xs.some(b => eq(a, b)))).map(t => [text(t), t])).values()];
94
+ if (!gates.length || gates.length > 3 || !gates.some(([name]) => eq(points(m, name)?.key, point)))
95
+ continue;
96
+ const initGuards = flat('and', u.c), creating = initGuards.find(c => c.op === 'flag');
97
+ const aRef = initGuards.find(c => c.op === '=' && at(c.a, ix));
98
+ const absent = creating?.op === 'flag' && aRef?.op === '=' && m.step.flags?.[creating.name] ?
99
+ labels(m, m.step.flags[creating.name], r => eq(r.key, aRef.b) && !!ws[r.map] && 'each' in ws[r.map], true) : [];
100
+ const absence = absent.length === 1 ? absent[0] : undefined;
101
+ const post = (map, k) => {
102
+ const w = points(m, map);
103
+ if (!w)
104
+ throw Error('non-point in row');
105
+ if (eq(k, w.key))
106
+ return w.value;
107
+ return ite(same(k, w.key), w.value, get(map, k));
108
+ };
109
+ const contribution = (read) => ite(gates.reduceRight((tail, [g, v]) => and([same(read(g), n(v)), tail]), same(read(group), selected)), read(weight), zero);
110
+ // GhostWriteTransport.completePoint: the full post-row, including conditional
111
+ // aliasing against every column write; no read from the old ghost.
112
+ const value = contribution(name => post(name, point));
113
+ const ghost = { orig: o, vars: {}, maps: { [wm]: { start: 0, write: { key: point, value } } } };
114
+ if (!ghostedOk(ghost))
115
+ continue;
116
+ const instrumented = ghostedMachine(ghost);
117
+ const machine = { ...instrumented, state: { ...instrumented.state, [sum]: zero }, sums: { [sum]: { term: get(wm, x(sumKey)), key: sumKey } } };
118
+ const pointLaw = `${prefix}point contribution`, agreementLaw = `${prefix}accumulator equals weighted live sum`;
119
+ const laws = [
120
+ ...(absence ? [{ name: `${prefix}absent storage is zero`, holds: { op: 'or', xs: [same(get(absence[0], selected), n(absence[1])), same(get(aMap, selected), zero)] } }] : []),
121
+ { name: pointLaw, forall: binder, holds: same(get(wm, x(binder)), contribution(name => get(name, x(binder)))) },
122
+ { name: agreementLaw, holds: same(get(aMap, selected), x(sum)) },
123
+ { name: law.name, holds: substC(law.holds, { ...noSub, vars: { [key]: selected } }) },
124
+ ];
125
+ res.push({ recipe: { ghostMap: wm, point, gates, group: group, weight, observer: obs }, machine, laws, pointLaw, agreementLaw, sum });
126
+ }
127
+ return res;
128
+ }
@@ -0,0 +1,17 @@
1
+ import { type Law, type Machine } from '../machine.js';
2
+ import { type Instances, type Tree } from '../../kernel/kernel.js';
3
+ import { type WeightedRecipe } from './candidates.js';
4
+ export type WeightedProof = {
5
+ instances: Record<string, Instances>;
6
+ trees: Record<string, Tree>;
7
+ };
8
+ export type WeightedProposal = {
9
+ kind: 'weighted';
10
+ recipe: WeightedRecipe;
11
+ machine: Machine;
12
+ laws: Law[];
13
+ pointLaw: string;
14
+ proof: WeightedProof;
15
+ };
16
+ export type WeightedObserver = (event: Record<string, unknown>) => void;
17
+ export declare function weightedSearch(source: Machine, law: Law, ms: number, observe?: WeightedObserver): WeightedProposal | undefined;
@@ -0,0 +1,68 @@
1
+ import { n, x } from "../machine.js";
2
+ import { searchWall } from "../wall.js";
3
+ import { obligations, sumParts } from "../../kernel/kernel.js";
4
+ import { clock, grow, pastWall, withWall } from "../../kernel/prove.js";
5
+ import { growCdcl } from "../../kernel/cdcl.js";
6
+ import { weightedCandidates } from "./candidates.js";
7
+ // Every seed is an ordinary instance of a premise of the original obligation.
8
+ // The output is a proposal only, even after its instrumented family checks.
9
+ function proveSeeded(candidate, until, observe) {
10
+ const { machine, laws, recipe: { point }, pointLaw, agreementLaw, sum } = candidate;
11
+ const law = laws.find(l => l.name === pointLaw);
12
+ if (!law?.forall)
13
+ return;
14
+ const probe = x(`${law.forall}#`);
15
+ const touched = [point, ...(point.op === 'if' ? [point.then, point.else] : [])];
16
+ const sumFlag = `?${sumParts(sum).flag}`;
17
+ const closedInstances = Object.fromEntries(Object.entries(machine.step.flags ?? {})
18
+ .flatMap(([name, condition]) => condition.op === 'all' ? [[`?${name}`, [n(0)]]] : []));
19
+ const instances = Object.fromEntries(laws.map(l => [l.name, {
20
+ ...closedInstances,
21
+ [pointLaw]: l === law ? [...touched, probe] : [point],
22
+ [sumFlag]: l === law ? [probe] : [],
23
+ }]));
24
+ const trees = Object.create(null);
25
+ const goals = obligations(machine, laws, instances);
26
+ // Give the agreement obligation first refusal before the pointwise invariant.
27
+ const agreement = 2 * laws.findIndex(l => l.name === agreementLaw);
28
+ goals.unshift(...goals.splice(agreement, 2));
29
+ for (const goal of goals) {
30
+ if (clock() >= until || pastWall())
31
+ return;
32
+ const step = goal.name.endsWith(' @step');
33
+ const end = Math.min(until, clock() + (step ? 30_000 : 2_000));
34
+ const quick = grow(goal, new Map(), { nodes: 0, until: Math.min(end, clock() + (step ? 750 : 2_000)) });
35
+ const found = step && !('tree' in quick) && clock() < end && !pastWall()
36
+ ? growCdcl(goal, new Map(), { nodes: 0, until: Math.min(end, clock() + 28_000) }) : quick;
37
+ observe({ phase: 'goal', goal: goal.name, closed: 'tree' in found, remaining: Math.round(until - clock()),
38
+ ...('tree' in found ? {} : { stuck: found.stuck, why: found.why }) });
39
+ if (!('tree' in found))
40
+ return;
41
+ trees[goal.name] = found.tree;
42
+ }
43
+ // checkGhostWrite reconstructs this family from the source and checks it
44
+ // before production can accept it. Avoid doing the same full check twice.
45
+ return clock() < until && !pastWall() ? { instances, trees } : undefined;
46
+ }
47
+ export function weightedSearch(source, law, ms, observe = () => { }) {
48
+ if (!Number.isFinite(ms) || ms < 1000)
49
+ return;
50
+ const capped = Math.min(ms, 60_000), until = clock() + capped;
51
+ return withWall(searchWall(capped), () => {
52
+ try {
53
+ for (const candidate of weightedCandidates(source, law)) {
54
+ if (clock() >= until || pastWall())
55
+ break;
56
+ observe({ phase: 'candidate', recipe: candidate.recipe });
57
+ const proof = proveSeeded(candidate, until, observe);
58
+ if (proof)
59
+ return { kind: 'weighted', recipe: candidate.recipe, machine: candidate.machine,
60
+ laws: candidate.laws, pointLaw: candidate.pointLaw, proof };
61
+ }
62
+ }
63
+ catch (error) {
64
+ observe({ phase: 'error', error: String(error) });
65
+ }
66
+ return undefined;
67
+ });
68
+ }
@@ -1015,8 +1015,13 @@ type RunBudget = typeof refuteBudget & {
1015
1015
  states?: boolean;
1016
1016
  until?: number;
1017
1017
  };
1018
- export declare function refuteModelByRuns(r: Parameters<typeof refuteByRuns>[0], laws: Law[], stepLaws?: StepLaw[]): ReturnType<typeof refuteByRuns>;
1019
- declare function refuteByRuns(r: Rule<Obj, Obj, Obj, Obj, Obj, Obj, Obj, Obj>, laws: Law[], stepLaws?: StepLaw[], budget?: RunBudget): {
1018
+ export declare function refusedSumCover(m: Machine, laws?: Law[]): {
1019
+ goal: string;
1020
+ why: string;
1021
+ } | undefined;
1022
+ export declare function replayRefutation(originalRule: Rule<Obj, Obj, Obj, Obj, Obj, Obj, Obj, Obj>, laws: Law[], stepLaws: StepLaw[], params: Record<string, number>, trace: Request[], bound: number, target?: Law | StepLaw): boolean;
1023
+ export declare function refuteModelByRuns(r: Parameters<typeof refuteByRuns>[0], laws: Law[], stepLaws?: StepLaw[], original?: Parameters<typeof refuteByRuns>[0]): ReturnType<typeof refuteByRuns>;
1024
+ declare function refuteByRuns(r: Rule<Obj, Obj, Obj, Obj, Obj, Obj, Obj, Obj>, laws: Law[], stepLaws?: StepLaw[], budget?: RunBudget, original?: Rule<Obj, Obj, Obj, Obj, Obj, Obj, Obj, Obj>): {
1020
1025
  goal: string;
1021
1026
  witness: Record<string, number>;
1022
1027
  run?: {