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.
package/dist/core/dsl.js CHANGED
@@ -1,4 +1,5 @@
1
- import { retainFrom, retainCounted, publishProof, withPublicRule, retainStepProof, publishStepProof, retainLiveProof, publishLiveProof } from "./proof-output.js";
1
+ import { retainFrom, retainCounted, retainAggregate, publishProof, withPublicRule, retainStepProof, publishStepProof, retainLiveProof, publishLiveProof } from "./proof-output.js";
2
+ import { searchAggregate } from "./aggregate-search.js";
2
3
  import { searchNow as countedSearchNow } from "./wall.js";
3
4
  // Typed builders for machines, decisions and loops: names are declared once and come back as typed values, so a
4
5
  // misspelled name, a law that reads a request, or a step that sets an undeclared variable is a TypeScript error, and
@@ -29,10 +30,10 @@ import { proveCountedCandidateSeeds } from "./counted-candidate-seeds.js";
29
30
  import { stepSeedFamilies, tryStepSeed } from "./step-seeds.js";
30
31
  import { bindSourceMachine, inheritSource, isSourceBound, translationVerdict } from "./source-check.js";
31
32
  import { env as knobs } from "./solver.js";
32
- 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";
33
34
  import { allowed, keysOf, requestEnv, watch, watchWork } from "./watch.js";
34
35
  import { ghostOf, proveSome, skolemOf, someHolds, substVars, substVarsE, witnessSupport } from "./exists.js";
35
- 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";
36
37
  import { certLoop, clock, counted, factsFor, fullRate, grow, pastWall, proveLaw, proveLaws, proveLiveness, proveSetFast, proveStepLaws, usualProof, withModelRounds, withWall } from "../kernel/prove.js";
37
38
  import { WallExpired, checkWall, checkBudget, checkWorkEndpoint, searchWall, withBudget, inBudget, BudgetExpired } from "./wall.js";
38
39
  import { completeWorkProfile } from "./work-profile.js";
@@ -1938,7 +1939,7 @@ export class Rule {
1938
1939
  const m = this.machine;
1939
1940
  if (m.history)
1940
1941
  return undefined;
1941
- 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();
1942
1943
  for (const [map, init] of Object.entries(m.maps ?? {})) {
1943
1944
  // (a map keyed by tuples has no sum read at one key: a sum's term reads its maps at the key alone)
1944
1945
  if (init !== 0 || !m.step.maps?.[map] || (m.inputMaps ?? []).includes(map) || (arity[map] ?? 1) > 1)
@@ -1947,7 +1948,10 @@ export class Rule {
1947
1948
  if (have.has(name))
1948
1949
  continue;
1949
1950
  try {
1950
- 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;
1951
1955
  more.add(name);
1952
1956
  }
1953
1957
  catch { /* a sum the kernel takes no cover of */ }
@@ -2707,9 +2711,14 @@ export class Rule {
2707
2711
  Object.assign(written, k.store(n, updates[n]));
2708
2712
  } });
2709
2713
  for (const n of Object.keys(st.scalars)) {
2710
- // (a sum over a map's keys: no callback writes it; the runtimes keep it exact, kernel.ts's sumMachine)
2711
- 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}`;
2712
2720
  continue;
2721
+ }
2713
2722
  const u = written[n], got = next.scalars[n], want = u === undefined ? st.scalars[n] : valOf(u);
2714
2723
  if (want === undefined)
2715
2724
  continue;
@@ -3279,11 +3288,89 @@ function guidesOf(m) {
3279
3288
  } }];
3280
3289
  });
3281
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
+ }
3282
3369
  // Model-only negative evidence for inference: never a source-law verdict.
3283
- export function refuteModelByRuns(r, laws, stepLaws = []) {
3284
- return refuteByRuns(r, laws, stepLaws);
3370
+ export function refuteModelByRuns(r, laws, stepLaws = [], original = r) {
3371
+ return refuteByRuns(r, laws, stepLaws, refuteBudget, original);
3285
3372
  }
3286
- function refuteByRuns(r, laws, stepLaws = [], budget = refuteBudget) {
3373
+ function refuteByRuns(r, laws, stepLaws = [], budget = refuteBudget, original = r) {
3287
3374
  const m = r.machine;
3288
3375
  const run = interpret(m), rand = seeded(budget.seed ?? 13), bound = budget.bound, shown = shownRequest, guides = budget.mixed ? guidesOf(m) : [];
3289
3376
  // (Division by a constant is a function too, its facts Euclid's, which its JavaScript meets: not checked.)
@@ -3330,8 +3417,10 @@ function refuteByRuns(r, laws, stepLaws = [], budget = refuteBudget) {
3330
3417
  // The witness: the params, the state the breaking step starts from (or the start) and its request's own values.
3331
3418
  const broken = (w, at, before, input) => ({ goal: `${w.name} ${at}`, witness: { ...params, ...before.scalars, ...(input ? numbersOf(input) : {}) }, run: { params, trace: trace.map(shown) } });
3332
3419
  for (const { w, on } of watching)
3333
- if (!('then' in w) && !on.start(st))
3334
- 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
+ }
3335
3424
  for (let d = 0, tries = 0; d < budget.depth && tries < 40 && watchWork.n <= cap && !late(); tries++) {
3336
3425
  const input = r.randomInput(rand, bound, params);
3337
3426
  if (near)
@@ -3350,11 +3439,28 @@ function refuteByRuns(r, laws, stepLaws = [], budget = refuteBudget) {
3350
3439
  if (!allowed(m, run, params, st, input))
3351
3440
  continue;
3352
3441
  d++;
3353
- 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
+ }
3354
3453
  trace.push(input);
3454
+ let unconfirmed = false;
3355
3455
  for (const { w, on } of watching)
3356
- if (!on.step(st, input, next))
3357
- 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;
3358
3464
  st = next;
3359
3465
  }
3360
3466
  }
@@ -3373,12 +3479,37 @@ function refuteByRuns(r, laws, stepLaws = [], budget = refuteBudget) {
3373
3479
  for (const [n, k] of kinded)
3374
3480
  Object.assign(scalars, k.random(n, rand, bound));
3375
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
+ }
3376
3496
  if (!given.every(l => watch(m, run, l, params, bound).start(st)))
3377
3497
  continue;
3378
3498
  const input = r.randomInput(rand, bound, params);
3379
3499
  if (!allowed(m, run, params, st, input))
3380
3500
  continue;
3381
- 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) });
3382
3513
  for (const sl of steps1)
3383
3514
  if (!watch(m, run, sl, params, bound).step(st, input, next))
3384
3515
  return { goal: `${sl.name} @step law`, witness: witness() };
@@ -3492,13 +3623,19 @@ function proveRuleWall(r, laws, opts, captureMachine) {
3492
3623
  return retainFrom(translationVerdict(r, laws, result), [result]);
3493
3624
  }
3494
3625
  function proveRuleIn(r, laws, opts, captureMachine) {
3626
+ const originalRule = r;
3495
3627
  r = r.withSumsOf(laws, opts.candidateSeeds?.laws ?? []);
3496
3628
  noting(r, laws);
3497
3629
  if (opts.candidateSeeds) {
3498
3630
  if (opts.search === false || opts.from === 'any')
3499
3631
  throw Error('candidate seeds require reachable-state search');
3500
3632
  const machine = r.machine, extraCounts = opts.candidateSeeds.counts ?? {};
3501
- 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) {
3502
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]);
3503
3640
  if (Object.keys(extraCounts).some(n => reserved.has(n)))
3504
3641
  throw Error('candidate count declaration must not override the source');
@@ -3518,13 +3655,16 @@ function proveRuleIn(r, laws, opts, captureMachine) {
3518
3655
  return retainFrom(verdictOf(seeded.closure), [seeded.closure], { kind: 'inference', original: machine, laws });
3519
3656
  }
3520
3657
  }
3521
- const refuted = refuteByRuns(r, laws);
3658
+ const refuted = refuteByRuns(r, laws, [], refuteBudget, originalRule);
3522
3659
  checkWorkEndpoint('refutation result');
3523
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
3524
3661
  // at), is a counterexample to induction: the laws may still hold, so the search goes on from it, as from the kernel's.
3525
3662
  // (A step law broken so is refused, proveSteps below: it holds from every state the laws allow, reached or not.)
3526
3663
  if (refuted?.run)
3527
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 };
3528
3668
  // A narrowly matched candidate gets a bounded attempt before unrestricted
3529
3669
  // inference. A failed helper proof is not a verdict about the caller's law.
3530
3670
  const search = typeof opts.search === 'object' ? opts.search : undefined;
@@ -3560,7 +3700,16 @@ function proveRuleIn(r, laws, opts, captureMachine) {
3560
3700
  }
3561
3701
  }
3562
3702
  if (refuted)
3563
- return searched(r, laws, [], refutedVerdict(refuted), opts);
3703
+ return searched(r, laws, [], refutedVerdict(refuted), opts, originalRule);
3704
+ if (r === originalRule && !opts.candidateSeeds && opts.from !== 'any' && opts.search !== false &&
3705
+ !completeWorkProfile.enabled && !(typeof opts.search === 'object' && opts.search.work !== undefined) && laws.length === 1) {
3706
+ const ms = typeof opts.search === 'object' ? opts.search.ms ?? 60_000 : 60_000;
3707
+ // Rule.machine can allocate fresh write binders on each access. Check and
3708
+ // retain the same public snapshot, not a later alpha-renamed copy.
3709
+ const aggregate = searchAggregate(captureMachine, laws[0], () => withKinds(r, laws).slice(0, -1), ms);
3710
+ if (aggregate)
3711
+ return retainAggregate({ proven: true, checked: true }, captureMachine, laws[0], aggregate.certificate, aggregate.kinds);
3712
+ }
3564
3713
  // A rule with counts: its goals are the counted ones (core/counts.ts searches them; the kernel checks the set).
3565
3714
  if (r.machine.counts && Object.keys(r.machine.counts).length) {
3566
3715
  const c = searchCounted(r.machine, withKinds(r, laws), typeof opts.search === 'object' ? opts.search.ms ?? 60_000 : 60_000);
@@ -3585,7 +3734,7 @@ function proveRuleIn(r, laws, opts, captureMachine) {
3585
3734
  : { proven: false, checked: false, stuck: 'unknown' };
3586
3735
  if (out)
3587
3736
  retainFrom(v, [out]);
3588
- return searched(r, laws, [], v, opts);
3737
+ return searched(r, laws, [], v, opts, originalRule);
3589
3738
  }
3590
3739
  export function proveSteps(r, laws, stepLaws, opts = {}) {
3591
3740
  return watchdogVerdict(opts.watchdogMs, () => workVerdict(opts, plan => proveStepsWall(r, laws, stepLaws, plan)));
@@ -3611,15 +3760,19 @@ function proveStepsWall(r, laws, stepLaws, opts) {
3611
3760
  return publishStepProof(translated, verdict);
3612
3761
  }
3613
3762
  function proveStepsIn(r, laws, stepLaws, opts) {
3763
+ const originalRule = r;
3614
3764
  r = r.withSumsOf(laws, stepLaws);
3615
3765
  noting(r, laws, stepLaws);
3616
- const refuted = refuteByRuns(r, laws, stepLaws);
3766
+ const refuted = refuteByRuns(r, laws, stepLaws, refuteBudget, originalRule);
3617
3767
  checkWorkEndpoint('refutation result');
3618
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
3619
3769
  // be further than these runs go; the search goes on from it, as from the kernel's)
3620
3770
  if (refuted?.run)
3621
3771
  return refutedVerdict(refuted);
3622
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 };
3623
3776
  // A bounded search for reachable-state supports. Keep from-any proofs,
3624
3777
  // explicit work accounting and real counterexample preflight unchanged.
3625
3778
  const sl = stepLaws.length === 1 ? stepLaws[0] : undefined;
@@ -3658,7 +3811,7 @@ function proveStepsIn(r, laws, stepLaws, opts) {
3658
3811
  if (strengthened)
3659
3812
  return strengthened;
3660
3813
  }
3661
- return searched(r, laws, stepLaws, v, fallback);
3814
+ return searched(r, laws, stepLaws, v, fallback, originalRule);
3662
3815
  }
3663
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
3664
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
@@ -3688,7 +3841,10 @@ function stepGhosts(m, stepLaws) {
3688
3841
  // The search, where the prover alone didn't prove the laws and nothing refuted them: the lemmas first where the rule has
3689
3842
  // recurrences or carried lists (the rule made again with them), then invariants over what it then is. The verdict is the
3690
3843
  // prover's on the laws with what was found; when nothing is found, the prover's own (with why).
3691
- 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;
3692
3848
  try {
3693
3849
  return searchedIn(r, laws, stepLaws, v, opts);
3694
3850
  }
@@ -3703,8 +3859,12 @@ function searched(r, laws, stepLaws, v, opts) {
3703
3859
  throw e;
3704
3860
  return stoppedSearch(v, e.termination);
3705
3861
  }
3862
+ finally {
3863
+ searchOriginalRule = prev;
3864
+ }
3706
3865
  }
3707
3866
  function searchedIn(r, laws, stepLaws, v, opts) {
3867
+ const original = searchOriginalRule ?? r;
3708
3868
  const any = opts.from === 'any';
3709
3869
  if ((v.proven && v.checked) || opts.search === false || v.run || v.acceleratedRun?.checked || v.stuck === 'sat' && (any || !/@step|@\d+ steps/.test(v.goal ?? '')))
3710
3870
  return v;
@@ -3714,7 +3874,7 @@ function searchedIn(r, laws, stepLaws, v, opts) {
3714
3874
  const explicitWork = typeof opts.search === 'object' ? opts.search.work : undefined;
3715
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;
3716
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 } : {}) }]) {
3717
- const deeper = refuteByRuns(r, laws, stepLaws, { ...b, until: runsUntil });
3877
+ const deeper = refuteByRuns(r, laws, stepLaws, { ...b, until: runsUntil }, original);
3718
3878
  if (deeper?.run)
3719
3879
  return refutedVerdict(deeper);
3720
3880
  }
@@ -3723,7 +3883,7 @@ function searchedIn(r, laws, stepLaws, v, opts) {
3723
3883
  const m0 = r.machine, clocked = stepLaws.length > 0 || [...divisorsIn(laws.map(l => l.holds))].some(k => k >= 3600);
3724
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))] : [];
3725
3885
  if (pool.length) {
3726
- 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);
3727
3887
  if (deeper?.run)
3728
3888
  return refutedVerdict(deeper);
3729
3889
  }
@@ -4012,6 +4172,9 @@ function proveLeadsToIn(r, laws, l, opts, allowRing) {
4012
4172
  noting(r, laws, l);
4013
4173
  if (laws.some(law => law.some?.length))
4014
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 };
4015
4178
  if (Array.isArray(l.rank) && !l.rank.length) {
4016
4179
  const ms = opts.ms ?? 10_000, until = clock() + ms;
4017
4180
  const draws = { params: (rand, bound) => r.randomParams(rand, bound), input: (rand, bound, ps) => r.randomInput(rand, bound, ps) };
@@ -4074,6 +4237,8 @@ export function refuteLeadsTo(r, laws, l, opts = {}) {
4074
4237
  return undefined;
4075
4238
  const k = keyed(r, l).withSumsOf(laws, l);
4076
4239
  noting(k, laws, l);
4240
+ if (refusedSumCover(k.machine, withKinds(k, laws)))
4241
+ return undefined;
4077
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);
4078
4243
  }
4079
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
@@ -0,0 +1,17 @@
1
+ import { type C, type Counted, type E, type Law, type Machine } from './machine.js';
2
+ export type FilteredCounterProposal = {
3
+ map: string;
4
+ key: string;
5
+ reset: C;
6
+ bound: E;
7
+ offset: number;
8
+ fields: {
9
+ field: string;
10
+ value: number;
11
+ guard: C;
12
+ count: string;
13
+ }[];
14
+ counts: Record<string, Counted>;
15
+ laws: Law[];
16
+ };
17
+ export declare function proposeFilteredCounters(m: Machine, caller: Law): FilteredCounterProposal[];
@@ -0,0 +1,77 @@
1
+ // Untrusted, intentionally small syntax recognizers. Their products are
2
+ // candidates for existing checked induction, never extra source facts.
3
+ import { get, n, x, plus, same } from "./machine.js";
4
+ import { substC } from "../kernel/kernel.js";
5
+ const equal = (a, b) => JSON.stringify(a) === JSON.stringify(b);
6
+ const atoms = (c) => !c ? [] : c.op === 'and' ? c.xs.flatMap(atoms) : [c];
7
+ const subKey = (c, name, term) => substC(c, { vars: { [name]: term }, maps: {}, flags: {} });
8
+ const rootReset = (u, start) => u.op === 'if' && equal(u.then, start) ? u : undefined;
9
+ const increase = (u, field) => u.op === 'if' && equal(u.else, x(field)) && equal(u.then, plus(x(field), n(1))) ? u.c : undefined;
10
+ const guardIncludes = (full, sub) => atoms(sub).every(p => atoms(full).some(q => equal(p, q)));
11
+ const onlyVariable = (e, name) => e.op === 'var' && e.name === name;
12
+ export function proposeFilteredCounters(m, caller) {
13
+ if (m.history || Object.keys(m.counts ?? {}).length || Object.keys(m.sums ?? {}).length || caller.forall || caller.keys?.length)
14
+ return [];
15
+ const src = JSON.stringify([m, caller]), uses = JSON.stringify(caller.holds);
16
+ let stem = 'agg$';
17
+ while (src.includes(stem))
18
+ stem += 'a';
19
+ const out = [];
20
+ for (const [map, wr] of Object.entries(m.step.maps ?? {})) {
21
+ // Cover singleton point writes and broadcast-reset-plus-point writes. A
22
+ // spatial guard is not accepted as a scalar guard; it is first specialized.
23
+ if (!('each' in wr) || m.maps?.[map] === undefined)
24
+ continue;
25
+ const init = n(m.maps[map]);
26
+ const outer = rootReset(wr.value, init), first = outer?.else;
27
+ if (!outer || first?.op !== 'if')
28
+ continue;
29
+ const keyAtom = atoms(first.c).find(c => c.op === '=' && onlyVariable(c.a, wr.each) && c.b.op === 'var' && m.inputs.includes(c.b.name));
30
+ if (keyAtom?.op !== '=' || keyAtom.b.op !== 'var')
31
+ continue;
32
+ const key = keyAtom.b.name;
33
+ const below = atoms(m.assume).find(c => (c.op === '<=' || c.op === '<') && onlyVariable(c.a, key) && c.b.op === 'var' && m.params.includes(c.b.name));
34
+ if (!below || (below.op !== '<=' && below.op !== '<'))
35
+ continue;
36
+ const lower = atoms(m.assume).filter(c => c.op === '<=' && c.a.op === 'const' && onlyVariable(c.b, key)).map(c => c.op === '<=' && c.a.op === 'const' ? c.a.value : 0);
37
+ const offset = Math.max(0, ...lower);
38
+ const bound0 = below.op === '<=' ? plus(below.b, n(1)) : below.b;
39
+ const bound = below.op === '<=' && offset === 1 ? below.b : offset ? { op: 'sub', a: bound0, b: n(offset) } : bound0;
40
+ const options = [];
41
+ let walk = first;
42
+ for (let i = 0; i < 8 && walk.op === 'if'; i++, walk = walk.else) {
43
+ const value = walk.then;
44
+ const parts = atoms(walk.c);
45
+ if (!parts.some(p => equal(p, keyAtom)) || value.op !== 'const' || equal(value, init))
46
+ break;
47
+ const [one, ...more] = parts.filter(p => !equal(p, keyAtom));
48
+ if (!one)
49
+ break;
50
+ options.push({ value: value.value, guard: more.length ? { op: 'and', xs: [one, ...more] } : one });
51
+ }
52
+ if (!equal(walk, get(map, x(wr.each))) || !options.length)
53
+ continue;
54
+ const counters = Object.entries(m.step.state ?? {}).flatMap(([field, u]) => {
55
+ if (!uses.includes(`"name":${JSON.stringify(field)}`) || !equal(m.state[field], n(0)))
56
+ return [];
57
+ const reset = rootReset(u, n(0)), guard = reset && increase(reset.else, field);
58
+ return reset && guard && equal(reset.c, outer.c) ? [{ field, guard }] : [];
59
+ });
60
+ const fields = counters.flatMap(({ field, guard }) => {
61
+ // Prefer the first branch whose guard is covered by the increment. Later
62
+ // alternatives are fallback writes in the source's own branch order.
63
+ const opt = options.find(o => guardIncludes(guard, o.guard));
64
+ return opt ? [{ field, guard, value: opt.value, count: `${stem}${out.length}$${field}` }] : [];
65
+ });
66
+ if (!fields.length || new Set(fields.map(f => f.value)).size !== fields.length)
67
+ continue;
68
+ const binder = `${stem}member`, arg = `${stem}argument`, coord = offset ? plus(x(binder), n(offset)) : x(binder);
69
+ const counts = Object.fromEntries(fields.map(f => [f.count, { j: arg, key: binder, below: bound, body: { op: 'if', c: same(get(map, coord), n(f.value)), then: n(1), else: n(0) } }]));
70
+ const laws = fields.map(f => ({ name: `${stem}${f.field} equals its filtered count`, holds: same(x(f.field), get(f.count, n(0))) }));
71
+ // Emit a disjoint-capacity candidate, not a theorem about an assumed tally.
72
+ if (fields.length > 1)
73
+ laws.push({ name: `${stem}disjoint filtered capacity`, holds: { op: '<=', a: fields.map(f => x(f.field)).reduce(plus), b: bound } });
74
+ out.push({ map, key, reset: subKey(outer.c, wr.each, x(key)), bound, offset, fields, counts, laws });
75
+ }
76
+ return out;
77
+ }
@@ -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>;