gdp-wired 0.53.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.
@@ -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?: {
package/dist/core/dsl.js CHANGED
@@ -30,10 +30,10 @@ import { proveCountedCandidateSeeds } from "./counted-candidate-seeds.js";
30
30
  import { stepSeedFamilies, tryStepSeed } from "./step-seeds.js";
31
31
  import { bindSourceMachine, inheritSource, isSourceBound, translationVerdict } from "./source-check.js";
32
32
  import { env as knobs } from "./solver.js";
33
- import { argsKey, bindDirect, directOf, machineTerms, part, tuple, carriedView, compileFunction, divName, divisor, divisorsIn, evalC, evalE, fnCall, hasFinite, interpret, isArithmetic, loadJs, modName, numbersOf, pairedArgs, seeded, sourceFreeFn, withArithmetic } from "./machine.js";
33
+ import { argsKey, bindDirect, directOf, machineTerms, part, tuple, carriedView, compileFunction, divName, divisor, divisorsIn, evalC, evalE, exactMapSum, fnCall, hasFinite, interpret, isArithmetic, loadJs, modName, numbersOf, pairedArgs, seeded, sourceFreeFn, withArithmetic } from "./machine.js";
34
34
  import { allowed, keysOf, requestEnv, watch, watchWork } from "./watch.js";
35
35
  import { ghostOf, proveSome, skolemOf, someHolds, substVars, substVarsE, witnessSupport } from "./exists.js";
36
- import { check, mapArities, checkRecur, foldObligations, ghostedMachine, loopObligations, someOfGhostsOk, substC, sumMachine } from "../kernel/kernel.js";
36
+ import { check, mapArities, checkRecur, foldObligations, ghostedMachine, loopObligations, sideGoals, someOfGhostsOk, substC, sumMachine } from "../kernel/kernel.js";
37
37
  import { certLoop, clock, counted, factsFor, fullRate, grow, pastWall, proveLaw, proveLaws, proveLiveness, proveSetFast, proveStepLaws, usualProof, withModelRounds, withWall } from "../kernel/prove.js";
38
38
  import { WallExpired, checkWall, checkBudget, checkWorkEndpoint, searchWall, withBudget, inBudget, BudgetExpired } from "./wall.js";
39
39
  import { completeWorkProfile } from "./work-profile.js";
@@ -1939,7 +1939,7 @@ export class Rule {
1939
1939
  const m = this.machine;
1940
1940
  if (m.history)
1941
1941
  return undefined;
1942
- const have = new Set(Object.keys(m.sums ?? {})), more = new Set(this.spec.sumsRead ?? []), arity = mapArities(m);
1942
+ const have = new Set(Object.keys(m.sums ?? {})), more = new Set(this.spec.sumsRead ?? []), arity = mapArities(m), kinds = this.kindLaws();
1943
1943
  for (const [map, init] of Object.entries(m.maps ?? {})) {
1944
1944
  // (a map keyed by tuples has no sum read at one key: a sum's term reads its maps at the key alone)
1945
1945
  if (init !== 0 || !m.step.maps?.[map] || (m.inputMaps ?? []).includes(map) || (arity[map] ?? 1) > 1)
@@ -1948,7 +1948,10 @@ export class Rule {
1948
1948
  if (have.has(name))
1949
1949
  continue;
1950
1950
  try {
1951
- sumMachine({ ...m, sums: { ...m.sums, ...sumsIn([], [name]) } });
1951
+ const cand = { ...m, sums: { ...m.sums, ...sumsIn([], [name]) } };
1952
+ const { goals } = sumMachine(cand, undefined, kinds);
1953
+ if (goals.length && refusedSumCover(cand, kinds))
1954
+ continue;
1952
1955
  more.add(name);
1953
1956
  }
1954
1957
  catch { /* a sum the kernel takes no cover of */ }
@@ -2708,9 +2711,14 @@ export class Rule {
2708
2711
  Object.assign(written, k.store(n, updates[n]));
2709
2712
  } });
2710
2713
  for (const n of Object.keys(st.scalars)) {
2711
- // (a sum over a map's keys: no callback writes it; the runtimes keep it exact, kernel.ts's sumMachine)
2712
- if (m.sums && n in m.sums)
2714
+ // (a sum over a map's keys: no callback writes it; verify the runtime kept it equal to the exact map sum)
2715
+ if (m.sums && n in m.sums) {
2716
+ count();
2717
+ const want = exactMapSum(m, n, m.sums[n], next), got = next.scalars[n];
2718
+ if (want !== got)
2719
+ return `the step keeps sum ${n} = ${got}, but the exact map sum is ${want}`;
2713
2720
  continue;
2721
+ }
2714
2722
  const u = written[n], got = next.scalars[n], want = u === undefined ? st.scalars[n] : valOf(u);
2715
2723
  if (want === undefined)
2716
2724
  continue;
@@ -3280,11 +3288,89 @@ function guidesOf(m) {
3280
3288
  } }];
3281
3289
  });
3282
3290
  }
3291
+ // Check every sum's `@cover` side goals (emitted for any summed map written at every key): if any cover goal fails to
3292
+ // prove and kernel-check, refuse sum maintenance for this rule (`stuck: 'unknown'`) rather than running on an uncovered
3293
+ // finite-cover approximation.
3294
+ export function refusedSumCover(m, laws = []) {
3295
+ if (!m.sums || !Object.keys(m.sums).length)
3296
+ return undefined;
3297
+ const covers = sideGoals(m, laws).filter(g => g.name.includes(' @cover '));
3298
+ if (!covers.length)
3299
+ return undefined;
3300
+ for (const g of covers) {
3301
+ const out = grow(g);
3302
+ if (!('tree' in out) || !check(g, out.tree)) {
3303
+ const [sumName, mapName] = g.name.split(' @cover ');
3304
+ return {
3305
+ goal: g.name,
3306
+ why: `sum ${sumName ?? g.name} cannot be maintained across broadcast write to map ${mapName ?? 'unknown'} (outside its finite cover)`,
3307
+ };
3308
+ }
3309
+ }
3310
+ return undefined;
3311
+ }
3312
+ // Independently replay a candidate concrete refutation on the original rule (before `withSumsOf`), computing every map
3313
+ // sum directly from the state's maps and defaults rather than trusting `sumMachine`/`sumRuntime`. Returns true only when
3314
+ // the trace is legal on the original rule and actually violates the target law or step law.
3315
+ export function replayRefutation(originalRule, laws, stepLaws, params, trace, bound, target) {
3316
+ const ks = divisorsIn([...laws, ...stepLaws]);
3317
+ const orig = ks.size ? originalRule.withDivisors(...ks) : originalRule;
3318
+ const origMachine = orig.machine;
3319
+ if (origMachine.pre && !evalC(origMachine.pre, params, { scalars: {}, maps: {} }, origMachine))
3320
+ return false;
3321
+ const origRun = interpret(origMachine);
3322
+ const origSums = origMachine.sums ?? {};
3323
+ const lawSums = sumsIn([laws, stepLaws]) ?? {};
3324
+ const extraSums = Object.entries(lawSums).filter(([name]) => !Object.hasOwn(origSums, name));
3325
+ const viewOf = (st) => {
3326
+ for (const [name, sum] of Object.entries(origSums)) {
3327
+ if (st.scalars[name] !== exactMapSum(origMachine, name, sum, st))
3328
+ throw new RangeError(`stale sum ${name}`);
3329
+ }
3330
+ if (!extraSums.length)
3331
+ return st;
3332
+ const scalars = { ...st.scalars };
3333
+ for (const [name, sum] of extraSums)
3334
+ scalars[name] = exactMapSum(origMachine, name, sum, st);
3335
+ return { ...st, scalars };
3336
+ };
3337
+ const targets = target ? [target] : [...laws, ...stepLaws];
3338
+ const watchers = targets.map(w => ({ w, on: watch(origMachine, origRun, w, params, bound) }));
3339
+ try {
3340
+ let st = origRun.init(params);
3341
+ let view = viewOf(st);
3342
+ if (trace.length === 0)
3343
+ return watchers.some(({ w, on }) => !('then' in w) && !on.start(view));
3344
+ for (let i = 0; i < trace.length; i++) {
3345
+ const input = trace[i];
3346
+ if (!allowed(origMachine, origRun, params, st, input))
3347
+ return false;
3348
+ const next = origRun.step(params, st, input);
3349
+ const nextView = viewOf(next);
3350
+ let failed = false;
3351
+ for (const { on } of watchers)
3352
+ if (!on.step(view, input, nextView))
3353
+ failed = true;
3354
+ if (i === trace.length - 1)
3355
+ return failed;
3356
+ st = next;
3357
+ view = nextView;
3358
+ }
3359
+ return false;
3360
+ }
3361
+ catch (e) {
3362
+ if (e instanceof WallExpired || e instanceof WatchdogExpired)
3363
+ throw e;
3364
+ if (e instanceof BudgetExpired)
3365
+ checkWorkEndpoint(e.phase);
3366
+ return false;
3367
+ }
3368
+ }
3283
3369
  // Model-only negative evidence for inference: never a source-law verdict.
3284
- export function refuteModelByRuns(r, laws, stepLaws = []) {
3285
- return refuteByRuns(r, laws, stepLaws);
3370
+ export function refuteModelByRuns(r, laws, stepLaws = [], original = r) {
3371
+ return refuteByRuns(r, laws, stepLaws, refuteBudget, original);
3286
3372
  }
3287
- function refuteByRuns(r, laws, stepLaws = [], budget = refuteBudget) {
3373
+ function refuteByRuns(r, laws, stepLaws = [], budget = refuteBudget, original = r) {
3288
3374
  const m = r.machine;
3289
3375
  const run = interpret(m), rand = seeded(budget.seed ?? 13), bound = budget.bound, shown = shownRequest, guides = budget.mixed ? guidesOf(m) : [];
3290
3376
  // (Division by a constant is a function too, its facts Euclid's, which its JavaScript meets: not checked.)
@@ -3331,8 +3417,10 @@ function refuteByRuns(r, laws, stepLaws = [], budget = refuteBudget) {
3331
3417
  // The witness: the params, the state the breaking step starts from (or the start) and its request's own values.
3332
3418
  const broken = (w, at, before, input) => ({ goal: `${w.name} ${at}`, witness: { ...params, ...before.scalars, ...(input ? numbersOf(input) : {}) }, run: { params, trace: trace.map(shown) } });
3333
3419
  for (const { w, on } of watching)
3334
- if (!('then' in w) && !on.start(st))
3335
- return broken(w, '@start', st);
3420
+ if (!('then' in w) && !on.start(st)) {
3421
+ if (replayRefutation(original, laws, stepLaws, params, [], bound, w))
3422
+ return broken(w, '@start', st);
3423
+ }
3336
3424
  for (let d = 0, tries = 0; d < budget.depth && tries < 40 && watchWork.n <= cap && !late(); tries++) {
3337
3425
  const input = r.randomInput(rand, bound, params);
3338
3426
  if (near)
@@ -3351,11 +3439,28 @@ function refuteByRuns(r, laws, stepLaws = [], budget = refuteBudget) {
3351
3439
  if (!allowed(m, run, params, st, input))
3352
3440
  continue;
3353
3441
  d++;
3354
- const next = run.step(params, st, input);
3442
+ let next;
3443
+ try {
3444
+ next = run.step(params, st, input);
3445
+ }
3446
+ catch (e) {
3447
+ if (e instanceof WallExpired || e instanceof WatchdogExpired)
3448
+ throw e;
3449
+ if (e instanceof BudgetExpired)
3450
+ checkWorkEndpoint(e.phase);
3451
+ break;
3452
+ }
3355
3453
  trace.push(input);
3454
+ let unconfirmed = false;
3356
3455
  for (const { w, on } of watching)
3357
- if (!on.step(st, input, next))
3358
- return broken(w, !('then' in w) ? '@step' : (w.steps ?? 1) > 1 ? `@${w.steps} steps` : '@step law', st, input);
3456
+ if (!on.step(st, input, next)) {
3457
+ if (replayRefutation(original, laws, stepLaws, params, trace, bound, w))
3458
+ return broken(w, !('then' in w) ? '@step' : (w.steps ?? 1) > 1 ? `@${w.steps} steps` : '@step law', st, input);
3459
+ unconfirmed = true;
3460
+ break;
3461
+ }
3462
+ if (unconfirmed)
3463
+ break;
3359
3464
  st = next;
3360
3465
  }
3361
3466
  }
@@ -3374,12 +3479,37 @@ function refuteByRuns(r, laws, stepLaws = [], budget = refuteBudget) {
3374
3479
  for (const [n, k] of kinded)
3375
3480
  Object.assign(scalars, k.random(n, rand, bound));
3376
3481
  const st = { scalars, maps: Object.fromEntries(Object.keys(m.maps ?? {}).map(n => [n, new Map(Array.from({ length: rand(3) }, () => [rand(bound + 1), rand(bound + 1)]))])) };
3482
+ if (m.sums) {
3483
+ let sumOk = true;
3484
+ for (const [name, sum] of Object.entries(m.sums)) {
3485
+ try {
3486
+ st.scalars[name] = exactMapSum(m, name, sum, st);
3487
+ }
3488
+ catch {
3489
+ sumOk = false;
3490
+ break;
3491
+ }
3492
+ }
3493
+ if (!sumOk)
3494
+ continue;
3495
+ }
3377
3496
  if (!given.every(l => watch(m, run, l, params, bound).start(st)))
3378
3497
  continue;
3379
3498
  const input = r.randomInput(rand, bound, params);
3380
3499
  if (!allowed(m, run, params, st, input))
3381
3500
  continue;
3382
- const next = run.step(params, st, input), witness = () => ({ ...params, ...st.scalars, ...numbersOf(input) });
3501
+ let next;
3502
+ try {
3503
+ next = run.step(params, st, input);
3504
+ }
3505
+ catch (e) {
3506
+ if (e instanceof WallExpired || e instanceof WatchdogExpired)
3507
+ throw e;
3508
+ if (e instanceof BudgetExpired)
3509
+ checkWorkEndpoint(e.phase);
3510
+ continue;
3511
+ }
3512
+ const witness = () => ({ ...params, ...st.scalars, ...numbersOf(input) });
3383
3513
  for (const sl of steps1)
3384
3514
  if (!watch(m, run, sl, params, bound).step(st, input, next))
3385
3515
  return { goal: `${sl.name} @step law`, witness: witness() };
@@ -3500,7 +3630,12 @@ function proveRuleIn(r, laws, opts, captureMachine) {
3500
3630
  if (opts.search === false || opts.from === 'any')
3501
3631
  throw Error('candidate seeds require reachable-state search');
3502
3632
  const machine = r.machine, extraCounts = opts.candidateSeeds.counts ?? {};
3503
- if (opts.candidateSeeds.kind === 'counted' || Object.keys(machine.counts ?? {}).length || Object.keys(extraCounts).length) {
3633
+ const isCounted = opts.candidateSeeds.kind === 'counted' || Object.keys(machine.counts ?? {}).length > 0 || Object.keys(extraCounts).length > 0;
3634
+ const seedCover = refusedSumCover(machine, withKinds(r, [...laws, ...opts.candidateSeeds.laws]));
3635
+ if (seedCover) {
3636
+ opts.candidateSeeds.report?.({ status: 'inconclusive', ...(isCounted ? { kind: 'counted' } : {}), kept: [], dropped: [], reason: seedCover.why });
3637
+ }
3638
+ else if (isCounted) {
3504
3639
  const reserved = new Set([...Object.keys(machine.maps ?? {}), ...Object.keys(machine.counts ?? {}), ...Object.keys(machine.state), ...Object.keys(machine.fns ?? {}), ...(machine.inputMaps ?? []), ...machine.params, ...machine.inputs]);
3505
3640
  if (Object.keys(extraCounts).some(n => reserved.has(n)))
3506
3641
  throw Error('candidate count declaration must not override the source');
@@ -3520,13 +3655,16 @@ function proveRuleIn(r, laws, opts, captureMachine) {
3520
3655
  return retainFrom(verdictOf(seeded.closure), [seeded.closure], { kind: 'inference', original: machine, laws });
3521
3656
  }
3522
3657
  }
3523
- const refuted = refuteByRuns(r, laws);
3658
+ const refuted = refuteByRuns(r, laws, [], refuteBudget, originalRule);
3524
3659
  checkWorkEndpoint('refutation result');
3525
3660
  // A state the laws allow whose step breaks one, with no run to it (a wide rule's: what the kernel's step goal would end
3526
3661
  // at), is a counterexample to induction: the laws may still hold, so the search goes on from it, as from the kernel's.
3527
3662
  // (A step law broken so is refused, proveSteps below: it holds from every state the laws allow, reached or not.)
3528
3663
  if (refuted?.run)
3529
3664
  return refutedVerdict(refuted);
3665
+ const coverRefusal = refusedSumCover(r.machine, withKinds(r, laws));
3666
+ if (coverRefusal)
3667
+ return { proven: false, checked: false, goal: coverRefusal.goal, stuck: 'unknown', why: coverRefusal.why };
3530
3668
  // A narrowly matched candidate gets a bounded attempt before unrestricted
3531
3669
  // inference. A failed helper proof is not a verdict about the caller's law.
3532
3670
  const search = typeof opts.search === 'object' ? opts.search : undefined;
@@ -3562,7 +3700,7 @@ function proveRuleIn(r, laws, opts, captureMachine) {
3562
3700
  }
3563
3701
  }
3564
3702
  if (refuted)
3565
- return searched(r, laws, [], refutedVerdict(refuted), opts);
3703
+ return searched(r, laws, [], refutedVerdict(refuted), opts, originalRule);
3566
3704
  if (r === originalRule && !opts.candidateSeeds && opts.from !== 'any' && opts.search !== false &&
3567
3705
  !completeWorkProfile.enabled && !(typeof opts.search === 'object' && opts.search.work !== undefined) && laws.length === 1) {
3568
3706
  const ms = typeof opts.search === 'object' ? opts.search.ms ?? 60_000 : 60_000;
@@ -3596,7 +3734,7 @@ function proveRuleIn(r, laws, opts, captureMachine) {
3596
3734
  : { proven: false, checked: false, stuck: 'unknown' };
3597
3735
  if (out)
3598
3736
  retainFrom(v, [out]);
3599
- return searched(r, laws, [], v, opts);
3737
+ return searched(r, laws, [], v, opts, originalRule);
3600
3738
  }
3601
3739
  export function proveSteps(r, laws, stepLaws, opts = {}) {
3602
3740
  return watchdogVerdict(opts.watchdogMs, () => workVerdict(opts, plan => proveStepsWall(r, laws, stepLaws, plan)));
@@ -3622,15 +3760,19 @@ function proveStepsWall(r, laws, stepLaws, opts) {
3622
3760
  return publishStepProof(translated, verdict);
3623
3761
  }
3624
3762
  function proveStepsIn(r, laws, stepLaws, opts) {
3763
+ const originalRule = r;
3625
3764
  r = r.withSumsOf(laws, stepLaws);
3626
3765
  noting(r, laws, stepLaws);
3627
- const refuted = refuteByRuns(r, laws, stepLaws);
3766
+ const refuted = refuteByRuns(r, laws, stepLaws, refuteBudget, originalRule);
3628
3767
  checkWorkEndpoint('refutation result');
3629
3768
  // (a step law broken from a state the laws allow, with no run to it: the laws may need an invariant there, or the run
3630
3769
  // be further than these runs go; the search goes on from it, as from the kernel's)
3631
3770
  if (refuted?.run)
3632
3771
  return refutedVerdict(refuted);
3633
3772
  const m = r.machine;
3773
+ const coverRefusal = refusedSumCover(m, withKinds(r, laws));
3774
+ if (coverRefusal)
3775
+ return { proven: false, checked: false, goal: coverRefusal.goal, stuck: 'unknown', why: coverRefusal.why };
3634
3776
  // A bounded search for reachable-state supports. Keep from-any proofs,
3635
3777
  // explicit work accounting and real counterexample preflight unchanged.
3636
3778
  const sl = stepLaws.length === 1 ? stepLaws[0] : undefined;
@@ -3669,7 +3811,7 @@ function proveStepsIn(r, laws, stepLaws, opts) {
3669
3811
  if (strengthened)
3670
3812
  return strengthened;
3671
3813
  }
3672
- return searched(r, laws, stepLaws, v, fallback);
3814
+ return searched(r, laws, stepLaws, v, fallback, originalRule);
3673
3815
  }
3674
3816
  // The one-step laws as laws the bounded runs read (core/bmc.ts takes laws alone): a ghost per step law, set once a step
3675
3817
  // it is about breaks it (`then` read with each primed name the step's update), and the law that it is never set. Only a
@@ -3699,7 +3841,10 @@ function stepGhosts(m, stepLaws) {
3699
3841
  // The search, where the prover alone didn't prove the laws and nothing refuted them: the lemmas first where the rule has
3700
3842
  // recurrences or carried lists (the rule made again with them), then invariants over what it then is. The verdict is the
3701
3843
  // prover's on the laws with what was found; when nothing is found, the prover's own (with why).
3702
- function searched(r, laws, stepLaws, v, opts) {
3844
+ let searchOriginalRule;
3845
+ function searched(r, laws, stepLaws, v, opts, original = r) {
3846
+ const prev = searchOriginalRule;
3847
+ searchOriginalRule = original;
3703
3848
  try {
3704
3849
  return searchedIn(r, laws, stepLaws, v, opts);
3705
3850
  }
@@ -3714,8 +3859,12 @@ function searched(r, laws, stepLaws, v, opts) {
3714
3859
  throw e;
3715
3860
  return stoppedSearch(v, e.termination);
3716
3861
  }
3862
+ finally {
3863
+ searchOriginalRule = prev;
3864
+ }
3717
3865
  }
3718
3866
  function searchedIn(r, laws, stepLaws, v, opts) {
3867
+ const original = searchOriginalRule ?? r;
3719
3868
  const any = opts.from === 'any';
3720
3869
  if ((v.proven && v.checked) || opts.search === false || v.run || v.acceleratedRun?.checked || v.stuck === 'sat' && (any || !/@step|@\d+ steps/.test(v.goal ?? '')))
3721
3870
  return v;
@@ -3725,7 +3874,7 @@ function searchedIn(r, laws, stepLaws, v, opts) {
3725
3874
  const explicitWork = typeof opts.search === 'object' ? opts.search.work : undefined;
3726
3875
  const ms = explicitWork === undefined ? (typeof opts.search === 'object' && opts.search.ms !== undefined ? opts.search.ms : 10_000) : Infinity, runsUntil = explicitWork === undefined ? countedSearchNow() + ms : Infinity;
3727
3876
  for (const b of [deeperBudget, { ...deeperBudget, bound: 1, seed: 31, states: false }, { ...deeperBudget, trials: 1200, seed: 41, states: false, mixed: true, ...(v.witness ? { near: v.witness } : {}) }]) {
3728
- const deeper = refuteByRuns(r, laws, stepLaws, { ...b, until: runsUntil });
3877
+ const deeper = refuteByRuns(r, laws, stepLaws, { ...b, until: runsUntil }, original);
3729
3878
  if (deeper?.run)
3730
3879
  return refutedVerdict(deeper);
3731
3880
  }
@@ -3734,7 +3883,7 @@ function searchedIn(r, laws, stepLaws, v, opts) {
3734
3883
  const m0 = r.machine, clocked = stepLaws.length > 0 || [...divisorsIn(laws.map(l => l.holds))].some(k => k >= 3600);
3735
3884
  const pool = clocked ? [...new Set(Object.entries(v.witness ?? {}).filter(([k, x]) => !m0.inputs.includes(k) && !m0.params.includes(k) && x > deeperBudget.bound).map(([, x]) => x))] : [];
3736
3885
  if (pool.length) {
3737
- const deeper = refuteByRuns(r, laws, stepLaws, { ...deeperBudget, trials: 300, seed: 43, states: false, mixed: true, near: v.witness, pool, until: runsUntil });
3886
+ const deeper = refuteByRuns(r, laws, stepLaws, { ...deeperBudget, trials: 300, seed: 43, states: false, mixed: true, near: v.witness, pool, until: runsUntil }, original);
3738
3887
  if (deeper?.run)
3739
3888
  return refutedVerdict(deeper);
3740
3889
  }
@@ -4023,6 +4172,9 @@ function proveLeadsToIn(r, laws, l, opts, allowRing) {
4023
4172
  noting(r, laws, l);
4024
4173
  if (laws.some(law => law.some?.length))
4025
4174
  throw new Error(`${r.machine.name}: a law with "there exists" goes to proveRule or proveSteps; a liveness takes plain laws (the ones its proof printed, Verdict.witnesses)`);
4175
+ const coverRefusal = refusedSumCover(r.machine, withKinds(r, laws));
4176
+ if (coverRefusal)
4177
+ return { proven: false, checked: false, goal: coverRefusal.goal, stuck: 'unknown', why: coverRefusal.why };
4026
4178
  if (Array.isArray(l.rank) && !l.rank.length) {
4027
4179
  const ms = opts.ms ?? 10_000, until = clock() + ms;
4028
4180
  const draws = { params: (rand, bound) => r.randomParams(rand, bound), input: (rand, bound, ps) => r.randomInput(rand, bound, ps) };
@@ -4085,6 +4237,8 @@ export function refuteLeadsTo(r, laws, l, opts = {}) {
4085
4237
  return undefined;
4086
4238
  const k = keyed(r, l).withSumsOf(laws, l);
4087
4239
  noting(k, laws, l);
4240
+ if (refusedSumCover(k.machine, withKinds(k, laws)))
4241
+ return undefined;
4088
4242
  return findRing(k.machine, withKinds(k, laws), l, { params: (rand, bound) => k.randomParams(rand, bound), input: (rand, bound, ps) => k.randomInput(rand, bound, ps) }, opts);
4089
4243
  }
4090
4244
  // `ms`: the budget (the prover's own per goal, 20 s or a second a hypothesis, where none is given), on the clock the
@@ -43,7 +43,7 @@ import { bitIntersection, bitIntersects } from "./bitsets.js";
43
43
  import { samplePredicates, sampleStateText } from "./sample-cache.js";
44
44
  import { sampleStep } from "./sample-step.js";
45
45
  import { all, any, atMost, carriedView, compileC, compileE, cpair, fastStep, divisorsIn, evalC, evalE, get, hasFinite, interpret, machineTerms, fnValue, modName, n, not, partsOf as tupleOf, plus, same, seeded, times, walk, withArithmetic, x } from "./machine.js";
46
- import { bool, refuteModelByRuns, verdictOf } from "./dsl.js";
46
+ import { bool, refuteModelByRuns, refusedSumCover, verdictOf } from "./dsl.js";
47
47
  import { allowed, keysOf, linKey, watch } from "./watch.js";
48
48
  import { BudgetExpired, checkBudget, clock, counted, fullWork, searchWork, decideLaw, decideNote, machineKey, memoHits, withBudget, withStrict, fullRate, grow, keyValue, lawInstances, proveLaw, proveLaws, proveSetFast, proveStepLaws, stepLawInstances, usedHyps, withDeadline, withModels, withTrees, withWall, withSearchWork } from "../kernel/prove.js";
49
49
  import { assumed, eachParts, obligations, plainOf, stepLawObligations, substC, tuple, tupleParts } from "../kernel/kernel.js";
@@ -1107,7 +1107,8 @@ function inferLawsSearchIn(target, laws, stepLaws, opts, observed) {
1107
1107
  // Divisor declarations are mutable rule metadata. Keep a private copy even
1108
1108
  // when withSumsOf would return the original rule: candidate search and returned
1109
1109
  // remainder laws must not add arithmetic facts to the caller's next proof.
1110
- const rule = isRule(target) ? target.withDivisors().withSumsOf(laws, stepLaws) : undefined;
1110
+ const baseRule = isRule(target) ? target.withDivisors() : undefined;
1111
+ const rule = baseRule?.withSumsOf(laws, stepLaws);
1111
1112
  // The clock the budgets read (counted milliseconds since the start, or wall time where `timed`), and the stop.
1112
1113
  const timed = !!opts.timed, w0 = work.n, used = { tries: 0, rows: 0, evals: 0, watched: 0, erows: 0, etries: 0 };
1113
1114
  const now = () => (timed ? countedSearchNow() - t0
@@ -1145,10 +1146,13 @@ function inferLawsSearchIn(target, laws, stepLaws, opts, observed) {
1145
1146
  cp = c;
1146
1147
  wp = work.n;
1147
1148
  };
1148
- if (rule) {
1149
+ if (baseRule) {
1149
1150
  const ks = divisorsIn([...laws, ...stepLaws]);
1150
- if (ks.size)
1151
- rule.dividesBy(...ks);
1151
+ if (ks.size) {
1152
+ baseRule.dividesBy(...ks);
1153
+ if (rule && rule !== baseRule)
1154
+ rule.dividesBy(...ks);
1155
+ }
1152
1156
  }
1153
1157
  const m = rule ? rule.machine : target;
1154
1158
  let proofs = 0;
@@ -1201,14 +1205,19 @@ function inferLawsSearchIn(target, laws, stepLaws, opts, observed) {
1201
1205
  };
1202
1206
  // The old public prover's first pass also sampled reachable counterexamples.
1203
1207
  // Keep that negative model evidence without invoking a source finalizer.
1204
- const refuted = !opts.first && !opts.cubes && rule ? refuteModelByRuns(rule, laws, stepLaws) : undefined;
1208
+ const refuted = !opts.first && !opts.cubes && rule ? refuteModelByRuns(rule, laws, stepLaws, baseRule) : undefined;
1209
+ const coverLaws = rule ? [...rule.kindLaws().filter(k => !laws.some(l => l.name === k.name)), ...laws] : laws;
1210
+ const coverRefusal = !refuted?.run ? refusedSumCover(m, coverLaws) : undefined;
1205
1211
  const first = opts.first ?? (refuted?.run ? { proven: false, checked: false, stuck: 'sat', ...refuted }
1206
- : opts.cubes ? { proven: false, checked: false } : prove(laws));
1212
+ : coverRefusal ? { proven: false, checked: false, goal: coverRefusal.goal, stuck: 'unknown', why: coverRefusal.why }
1213
+ : opts.cubes ? { proven: false, checked: false } : prove(laws));
1207
1214
  observed.context = () => searchContext(first);
1208
1215
  if ((first.proven && first.checked) || first.run) {
1209
1216
  const completed = observed.completed = retainFrom({ ...first, found: [], stats: completedStats(0, 0, 0) }, [first]);
1210
1217
  return retainFrom({ ...completed, stats: stats(0, 0, 0) }, [completed]);
1211
1218
  }
1219
+ if (coverRefusal)
1220
+ return { ...first, found: [], stats: stats(0, 0, 0) };
1212
1221
  // --- runs ------------------------------------------------------------------------------------------------------------
1213
1222
  const run = interpret(m), stepSample = sampleStep(m, run), rand = seeded(17), kinds = rule ? rule.kindsOfState() : [];
1214
1223
  const given = rule ? [...rule.kindLaws().filter(k => !laws.some(l => l.name === k.name)), ...laws] : laws;
@@ -284,6 +284,10 @@ export declare function pairedArgs(key: E, n: number): E[] | undefined;
284
284
  export declare function evalC(c: C, env: Env, st: State, m: Machine): boolean;
285
285
  export declare function compileE(e: E, m: Machine): (env: Env, st: State) => number;
286
286
  export declare function compileC(c: C, m: Machine): (env: Env, st: State) => boolean;
287
+ export declare function exactMapSum(m: Machine, name: string, sum: {
288
+ key: string;
289
+ term: E;
290
+ }, st: State): number;
287
291
  export declare function leastsIn(m: Machine, env: Env, st: State): Env;
288
292
  export declare function carriedView(m: Machine, st: State, input: Request, rename?: (map: string) => string, params?: Env, checkpoint?: () => void): State;
289
293
  export declare const numbersOf: (input: Request) => Record<string, number>;
@@ -777,6 +777,50 @@ function unchanged(t, map, env, st, m) {
777
777
  const zeroOne = () => [...(st.maps[map]?.values() ?? [])].every(x => x === 0 || x === 1) && (st.defaults?.[map] ?? m.maps[map]) <= 1;
778
778
  return v.op === 'if' && v.then.op === 'const' && v.then.value === 1 && v.else.op === 'const' && v.else.value === 0 && v.c.op === '<=' && v.c.a.op === 'const' && v.c.a.value === 1 && own(v.c.b) && zeroOne();
779
779
  }
780
+ // Exact value of a declared map sum directly from a state's maps and defaults (independent of sumRuntime's finite-cover
781
+ // delta). Throws RangeError when the sum's term is non-zero past the stored cells (an infinite sum over all naturals).
782
+ export function exactMapSum(m, name, sum, st) {
783
+ const read = mapsIn(sum.term);
784
+ for (const mp of read)
785
+ if (st.defaults?.[mp] === undefined && m.maps?.[mp] === undefined)
786
+ throw new RangeError(`${m.name}: map ${mp} is not declared on the machine`);
787
+ const dfltState = { scalars: {}, maps: Object.fromEntries(read.map(mp => [mp, new Map()])), ...(st.defaults ? { defaults: st.defaults } : {}) };
788
+ const d = evalE(sum.term, { [sum.key]: 0 }, dfltState, m);
789
+ if (d !== 0)
790
+ throw new RangeError(`${m.name}: the sum ${name} is infinite (its term is ${d} past the stored cells)`);
791
+ if (!read.length)
792
+ return 0;
793
+ let total = 0;
794
+ const env = { [sum.key]: 0 };
795
+ if (read.length === 1) {
796
+ const cells = st.maps[read[0]];
797
+ if (cells)
798
+ for (const key of cells.keys()) {
799
+ env[sum.key] = key;
800
+ total = exact(total + evalE(sum.term, env, st, m));
801
+ }
802
+ return total;
803
+ }
804
+ const keys = new Set();
805
+ for (const mp of read)
806
+ for (const key of st.maps[mp]?.keys() ?? [])
807
+ keys.add(key);
808
+ for (const key of keys) {
809
+ env[sum.key] = key;
810
+ total = exact(total + evalE(sum.term, env, st, m));
811
+ }
812
+ return total;
813
+ }
814
+ // Sums whose term reads at least one map written at every key (`each`): sumRuntime's finite-cover delta is only valid
815
+ // when the write's cover goal holds, so the runtimes recompute these sums directly from the post-step maps instead.
816
+ function recomputedSums(m) {
817
+ const out = new Set();
818
+ for (const [name, sum] of Object.entries(m.sums ?? {})) {
819
+ if (mapsIn(sum.term).some(mp => { const w = m.step.maps?.[mp]; return !!w && 'each' in w; }))
820
+ out.add(name);
821
+ }
822
+ return out;
823
+ }
780
824
  // The machine a runtime steps (with a history, kernel.ts's plain machine), its queries, and the inputs a request carries.
781
825
  function runnable(m) {
782
826
  const h = m.history;
@@ -870,7 +914,7 @@ export const numbersOf = (input) => Object.fromEntries(Object.entries(input).fil
870
914
  const refused = (m) => `${m.name}: the request fails the rule's assumption, so no proof covers the step it would take`;
871
915
  // The interpreter: persistent (a step leaves the state it was given as it was), so searches can branch from any state.
872
916
  export function interpret(m, checkpoint) {
873
- const { h, plain, carried } = runnable(m), arity = mapArities(plain);
917
+ const { h, plain, carried } = runnable(m), arity = mapArities(plain), recompute = recomputedSums(m);
874
918
  const args = (params, input) => {
875
919
  const env = {};
876
920
  for (const p of m.params)
@@ -948,7 +992,8 @@ export function interpret(m, checkpoint) {
948
992
  }
949
993
  const scalars = { ...st.scalars };
950
994
  for (const [name, e] of Object.entries(plain.step.state ?? {}))
951
- scalars[name] = evalE(e, env, st, plain);
995
+ if (!recompute.has(name))
996
+ scalars[name] = evalE(e, env, st, plain);
952
997
  const writes = Object.entries(plain.step.maps ?? {}).map(([name, w]) => [name, 'each' in w ? writeEvery(w, env, st, plain, arity[name] ?? 1, name) : { key: evalE(w.key, env, st, plain), value: evalE(w.value, env, st, plain) }]);
953
998
  const maps = Object.fromEntries(Object.entries(given.maps).map(([name, cells]) => [name, new Map(cells)]));
954
999
  const defaults = { ...given.defaults };
@@ -960,6 +1005,11 @@ export function interpret(m, checkpoint) {
960
1005
  else
961
1006
  maps[name].set(w.key, w.value);
962
1007
  const withDefaults = Object.keys(defaults).length ? { defaults } : {};
1008
+ if (recompute.size) {
1009
+ const post = { scalars, maps, ...withDefaults };
1010
+ for (const name of recompute)
1011
+ scalars[name] = exactMapSum(m, name, m.sums[name], post);
1012
+ }
963
1013
  if (!h)
964
1014
  return { scalars, maps, ...withDefaults };
965
1015
  const kept = evalC(h.keep, env, st, plain);
@@ -1030,7 +1080,7 @@ export function compileJs(m) { return compileJsMode(m, false); }
1030
1080
  // fastStep keeps the input state persistent. Its fork can wait until every
1031
1081
  // precondition and right-hand side has been evaluated, just before the writes.
1032
1082
  function compileJsMode(m, persistent, cells) {
1033
- const { h, plain, queries, carried } = runnable(m);
1083
+ const { h, plain, queries, carried } = runnable(m), recompute = recomputedSums(m);
1034
1084
  // (a condition or a write at every key over a tuple key: the interpreter decides those, part by part)
1035
1085
  const atEvery = [...Object.values(plain.step.flags ?? {}).filter(c => c.op === 'all' && c.finite === undefined), ...Object.values(plain.step.maps ?? {}).filter(w => 'each' in w)];
1036
1086
  const arity = mapArities(plain);
@@ -1157,14 +1207,56 @@ function compileJsMode(m, persistent, cells) {
1157
1207
  const better = l.by.map((b, i) => `by[${i}] !== bb[${i}] ? by[${i}] ${b.desc ? '>' : '<'} bb[${i}] : `).join('') + 'false';
1158
1208
  lines.push(`{ const ks = $keys(maps, ${JSON.stringify(ms)}), past = ks.pop(); let lk = past; if (${where}) throw new RangeError(${id(`${m.name}: ${name} has no least (its condition holds at every key past the cells)`)}); let bk, bb; for (lk of ks.sort((a, b) => a - b)) { if (!(${where})) continue; const by = [${by.join(', ')}]; if (bk === undefined || (${better})) { bk = lk; bb = by; } } env[${id(name)}] = bk ?? 0; env[${id(l.some)}] = bk === undefined ? 0 : 1; }`);
1159
1209
  }
1210
+ const sumEx = (e, keyVar) => {
1211
+ switch (e.op) {
1212
+ case 'const': return String(e.value);
1213
+ case 'add': return `$x(${sumEx(e.a, keyVar)} + ${sumEx(e.b, keyVar)})`;
1214
+ case 'sub': return `Math.max(0, ${sumEx(e.a, keyVar)} - ${sumEx(e.b, keyVar)})`;
1215
+ case 'mul': return `$x(${e.k} * ${sumEx(e.a, keyVar)})`;
1216
+ case 'prod': return `$x(${sumEx(e.a, keyVar)} * ${sumEx(e.b, keyVar)})`;
1217
+ case 'min': return `Math.min(${sumEx(e.a, keyVar)}, ${sumEx(e.b, keyVar)})`;
1218
+ case 'max': return `Math.max(${sumEx(e.a, keyVar)}, ${sumEx(e.b, keyVar)})`;
1219
+ case 'if': return `(${sumCx(e.c, keyVar)} ? ${sumEx(e.then, keyVar)} : ${sumEx(e.else, keyVar)})`;
1220
+ case 'get': return keyVar ? `(state.maps[${id(e.map)}].get(${keyVar}) ?? dft[${id(e.map)}] ?? ${plain.maps[e.map]})` : `(dft[${id(e.map)}] ?? ${plain.maps[e.map]})`;
1221
+ case 'var':
1222
+ case 'tup':
1223
+ case 'proj': throw new Error(`${m.name}: unexpected expression ${e.op} in sum term`);
1224
+ }
1225
+ };
1226
+ const sumCx = (c, keyVar) => {
1227
+ switch (c.op) {
1228
+ case '<': return `(${sumEx(c.a, keyVar)} < ${sumEx(c.b, keyVar)})`;
1229
+ case '<=': return `(${sumEx(c.a, keyVar)} <= ${sumEx(c.b, keyVar)})`;
1230
+ case '=': return `(${sumEx(c.a, keyVar)} === ${sumEx(c.b, keyVar)})`;
1231
+ case 'and': return c.xs.length ? `(${c.xs.map(y => sumCx(y, keyVar)).join(' && ')})` : 'true';
1232
+ case 'or': return c.xs.length ? `(${c.xs.map(y => sumCx(y, keyVar)).join(' || ')})` : 'false';
1233
+ case 'not': return `(!${sumCx(c.x, keyVar)})`;
1234
+ case 'flag':
1235
+ case 'all': throw new Error(`${m.name}: unexpected condition ${c.op} in sum term`);
1236
+ }
1237
+ };
1238
+ const stepScalars = Object.entries(plain.step.state ?? {}).filter(([name]) => !recompute.has(name));
1160
1239
  lines.push(...flags.map((name, i) => `const flag${i} = ${cx(plain.step.flags[name])};`),
1161
1240
  // The rule's own assumption, as `allowed` (core/watch.ts) reads it (a history's machine assumes more: its relations).
1162
- ...(m.assume ? [`if (!${cx(m.assume)}) throw new RangeError(${id(refused(m))});`] : []), ...(plain.primitiveFailure ? [`if (${cx(plain.primitiveFailure)}) { const e = new RangeError(${id(`${m.name}: fixed-width primitive failed`)}); e.name = "PrimitiveFailure"; throw e; }`] : []), `const scalars = {...s, ${Object.entries(plain.step.state ?? {}).map(([name, e]) => `${id(name)}: ${ex(e)}`).join(', ')}};`, ...[...sharedBreaks].map(([text, bk]) => `const ${bk} = ${breaksJs(JSON.parse(text))};`), ...writes.map(([name, w], i) => ('each' in w ? `const write${i} = ${every(w, sharedOf(name))};` : `const key${i} = ${ex(w.key)}, value${i} = ${ex(w.value)};`)));
1241
+ ...(m.assume ? [`if (!${cx(m.assume)}) throw new RangeError(${id(refused(m))});`] : []), ...(plain.primitiveFailure ? [`if (${cx(plain.primitiveFailure)}) { const e = new RangeError(${id(`${m.name}: fixed-width primitive failed`)}); e.name = "PrimitiveFailure"; throw e; }`] : []), `const scalars = {${['...s', ...stepScalars.map(([name, e]) => `${id(name)}: ${ex(e)}`)].join(', ')}};`, ...[...sharedBreaks].map(([text, bk]) => `const ${bk} = ${breaksJs(JSON.parse(text))};`), ...writes.map(([name, w], i) => ('each' in w ? `const write${i} = ${every(w, sharedOf(name))};` : `const key${i} = ${ex(w.key)}, value${i} = ${ex(w.value)};`)));
1163
1242
  if (h)
1164
1243
  lines.push(`const keep = ${cx(h.keep)};`);
1165
1244
  if (persistent)
1166
1245
  lines.push('state = fork(state);');
1167
1246
  lines.push(...writes.map(([name, w], i) => ('each' in w ? `state.maps[${id(name)}] = write${i}.cells; dft[${id(name)}] = write${i}.d;` : `state.maps[${id(name)}].set(key${i}, value${i});`)));
1247
+ for (const name of recompute) {
1248
+ const sum = m.sums[name], read = mapsIn(sum.term), dfltExpr = sumEx(sum.term), atKeyExpr = sumEx(sum.term, '$k');
1249
+ const errMsg = id(`${m.name}: the sum ${name} is infinite (its term is `);
1250
+ if (!read.length) {
1251
+ lines.push(`{ const $d = ${dfltExpr}; if ($d !== 0) throw new RangeError(${errMsg} + $d + " past the stored cells)"); scalars[${id(name)}] = 0; }`);
1252
+ }
1253
+ else if (read.length === 1) {
1254
+ lines.push(`{ const $d = ${dfltExpr}; if ($d !== 0) throw new RangeError(${errMsg} + $d + " past the stored cells)"); let $sum = 0; for (const $k of state.maps[${id(read[0])}].keys()) $sum = $x($sum + ${atKeyExpr}); scalars[${id(name)}] = $sum; }`);
1255
+ }
1256
+ else {
1257
+ lines.push(`{ const $d = ${dfltExpr}; if ($d !== 0) throw new RangeError(${errMsg} + $d + " past the stored cells)"); const $ks = new Set(); ${read.map(mp => `for (const $k of state.maps[${id(mp)}].keys()) $ks.add($k);`).join(' ')} let $sum = 0; for (const $k of $ks) $sum = $x($sum + ${atKeyExpr}); scalars[${id(name)}] = $sum; }`);
1258
+ }
1259
+ }
1168
1260
  if (h)
1169
1261
  lines.push(`if (keep) records.push({${h.record.map(f => `${id(f)}: env[${id(f)}]`).join(', ')}});`,
1170
1262
  // Drop the spent prefix now and then, not every step: amortized, each record is moved a bounded number of times.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gdp-wired",
3
- "version": "0.53.0",
3
+ "version": "0.53.1",
4
4
  "description": "An automatic prover for stateful rules (budgets, caps, windows, workflows, policies): laws proven with no proof to write, checked again in Lean, counterexamples found on the GPU, the rule shipped as code",
5
5
  "keywords": [
6
6
  "verification",