gdp-wired 0.51.0 → 0.53.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/README.md +2 -2
  2. package/dist/core/accel-refute.d.ts +53 -0
  3. package/dist/core/accel-refute.js +997 -0
  4. package/dist/core/aggregate-kinds.d.ts +10 -0
  5. package/dist/core/aggregate-kinds.js +44 -0
  6. package/dist/core/aggregate-search.d.ts +9 -0
  7. package/dist/core/aggregate-search.js +74 -0
  8. package/dist/core/aggregate-weighted/candidates.d.ts +18 -0
  9. package/dist/core/aggregate-weighted/candidates.js +128 -0
  10. package/dist/core/aggregate-weighted/search.d.ts +17 -0
  11. package/dist/core/aggregate-weighted/search.js +68 -0
  12. package/dist/core/cli.d.ts +2 -0
  13. package/dist/core/cli.js +8 -1
  14. package/dist/core/cycles.d.ts +2 -0
  15. package/dist/core/cycles.js +12 -9
  16. package/dist/core/dsl.d.ts +7 -1
  17. package/dist/core/dsl.js +158 -26
  18. package/dist/core/filtered-sum-candidates.d.ts +17 -0
  19. package/dist/core/filtered-sum-candidates.js +77 -0
  20. package/dist/core/live-support.d.ts +5 -0
  21. package/dist/core/live-support.js +148 -0
  22. package/dist/core/live.js +194 -37
  23. package/dist/core/lockstep.d.ts +5 -0
  24. package/dist/core/lockstep.js +23 -0
  25. package/dist/core/ordered-pair-seeds.d.ts +2 -0
  26. package/dist/core/ordered-pair-seeds.js +109 -0
  27. package/dist/core/proof-output.d.ts +49 -2
  28. package/dist/core/proof-output.js +44 -0
  29. package/dist/core/search-termination.d.ts +4 -0
  30. package/dist/core/search-termination.js +1 -1
  31. package/dist/core/source-check.d.ts +4 -1
  32. package/dist/core/source-check.js +5 -2
  33. package/dist/core/sparse-kind-proof.d.ts +7 -0
  34. package/dist/core/sparse-kind-proof.js +49 -0
  35. package/dist/core/step-seeds.d.ts +46 -0
  36. package/dist/core/step-seeds.js +316 -0
  37. package/dist/kernel/finite-sum.d.ts +31 -0
  38. package/dist/kernel/finite-sum.js +74 -0
  39. package/dist/kernel/ghost-write.d.ts +117 -0
  40. package/dist/kernel/ghost-write.js +89 -0
  41. package/dist/lean-kernel/Cert.lean +222 -0
  42. package/dist/lean-kernel/Count.lean +1568 -0
  43. package/dist/lean-kernel/Ghost.lean +373 -0
  44. package/dist/lean-kernel/GhostMap.lean +426 -0
  45. package/dist/lean-kernel/Kernel.lean +2881 -0
  46. package/dist/lean-kernel/Live.lean +1168 -0
  47. package/dist/lean-kernel/Progress.lean +543 -0
  48. package/dist/lean-kernel/Sets.lean +1975 -0
  49. package/dist/lean-kernel/StepLaw.lean +128 -0
  50. package/dist/lean-kernel/Steps.lean +477 -0
  51. package/dist/lean-kernel/Sums.lean +916 -0
  52. package/dist/lean-kernel/emit.d.ts +15 -0
  53. package/dist/lean-kernel/emit.js +47 -6
  54. package/dist/lean-kernel/finite-sum-export.d.ts +3 -0
  55. package/dist/lean-kernel/finite-sum-export.js +163 -0
  56. package/dist/lean-kernel/ghost-write-export.d.ts +3 -0
  57. package/dist/lean-kernel/ghost-write-export.js +81 -0
  58. package/dist/lean-kernel/lean-aggregate/FiniteFold.lean +44 -0
  59. package/dist/lean-kernel/lean-aggregate/GroupedTransport.lean +308 -0
  60. package/dist/lean-kernel/lean-aggregate/aggregate.d.ts +13 -0
  61. package/dist/lean-kernel/lean-aggregate/aggregate.js +68 -0
  62. package/dist/lean-kernel/lean-aggregate/assets.d.ts +5 -0
  63. package/dist/lean-kernel/lean-aggregate/assets.js +7 -0
  64. package/dist/lean-kernel/lean-aggregate/audit.d.ts +3 -0
  65. package/dist/lean-kernel/lean-aggregate/audit.js +13 -0
  66. package/dist/lean-kernel/lean-aggregate/exact.d.ts +15 -0
  67. package/dist/lean-kernel/lean-aggregate/exact.js +51 -0
  68. package/dist/lean-kernel/lean-aggregate/index.d.ts +19 -0
  69. package/dist/lean-kernel/lean-aggregate/index.js +52 -0
  70. package/dist/lean-kernel/lean-aggregate/point-fold.d.ts +27 -0
  71. package/dist/lean-kernel/lean-aggregate/point-fold.js +79 -0
  72. package/dist/lean-kernel/lean-aggregate/replay-fold.d.ts +2 -0
  73. package/dist/lean-kernel/lean-aggregate/replay-fold.js +163 -0
  74. package/dist/lean-kernel/lean-aggregate/source.d.ts +2 -0
  75. package/dist/lean-kernel/lean-aggregate/source.js +141 -0
  76. package/dist/lean-kernel/lean-aggregate/weighted-flags.d.ts +2 -0
  77. package/dist/lean-kernel/lean-aggregate/weighted-flags.js +26 -0
  78. package/dist/lean-kernel/lean-aggregate/weighted-replay.d.ts +7 -0
  79. package/dist/lean-kernel/lean-aggregate/weighted-replay.js +53 -0
  80. package/dist/lean-kernel/lean-aggregate/weighted-seeded.d.ts +30 -0
  81. package/dist/lean-kernel/lean-aggregate/weighted-seeded.js +64 -0
  82. package/dist/lean-kernel/lean-aggregate/weighted.d.ts +18 -0
  83. package/dist/lean-kernel/lean-aggregate/weighted.js +115 -0
  84. package/dist/lean-kernel/lean-aggregate/worker.d.ts +10 -0
  85. package/dist/lean-kernel/lean-aggregate/worker.js +46 -0
  86. package/dist/lean-kernel/library.js +3 -0
  87. package/dist/lean-kernel/lift-simulation/shape.js +5 -5
  88. package/docs/lean-aggregate.md +29 -0
  89. package/package.json +6 -1
package/dist/core/dsl.js CHANGED
@@ -1,4 +1,5 @@
1
- import { retainFrom, retainCounted, publishProof, withPublicRule } 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
@@ -23,16 +24,20 @@ export { fixedInt, FixedWord, fixedFailure, fixedSelect } from "./fixed-integers
23
24
  import { binder, copyVariable, encodeBinders, generatedVariable, guardReserved, internalName, plainDeclaration, variable } from "./dsl-binders.js";
24
25
  import { candidates, cone, searchCounted } from "./counts.js";
25
26
  import { proveCandidateSeeds } from "./candidate-seeds.js";
27
+ import { orderedPairSeed } from "./ordered-pair-seeds.js";
28
+ import { tryLockstepScalars } from "./lockstep.js";
26
29
  import { proveCountedCandidateSeeds } from "./counted-candidate-seeds.js";
27
- import { bindSourceMachine, inheritSource, translationVerdict } from "./source-check.js";
30
+ import { stepSeedFamilies, tryStepSeed } from "./step-seeds.js";
31
+ import { bindSourceMachine, inheritSource, isSourceBound, translationVerdict } from "./source-check.js";
28
32
  import { env as knobs } from "./solver.js";
29
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";
30
34
  import { allowed, keysOf, requestEnv, watch, watchWork } from "./watch.js";
31
35
  import { ghostOf, proveSome, skolemOf, someHolds, substVars, substVarsE, witnessSupport } from "./exists.js";
32
36
  import { check, mapArities, checkRecur, foldObligations, ghostedMachine, loopObligations, someOfGhostsOk, substC, sumMachine } from "../kernel/kernel.js";
33
37
  import { certLoop, clock, counted, factsFor, fullRate, grow, pastWall, proveLaw, proveLaws, proveLiveness, proveSetFast, proveStepLaws, usualProof, withModelRounds, withWall } from "../kernel/prove.js";
34
- import { WallExpired, checkWall, checkBudget, checkWorkEndpoint, searchWall, withBudget, BudgetExpired } from "./wall.js";
38
+ import { WallExpired, checkWall, checkBudget, checkWorkEndpoint, searchWall, withBudget, inBudget, BudgetExpired } from "./wall.js";
35
39
  import { completeWorkProfile } from "./work-profile.js";
40
+ import { stepWorkProfile } from "./step-work.js";
36
41
  import { workLedger } from "./work-admission.js";
37
42
  import { withStageAllowance, withStageDeadline, withStageWall, withStageWork, remainingStageWork } from "./dsl-deadline.js";
38
43
  import { completedSearch, searchContext, stoppedSearch } from "./search-termination.js";
@@ -44,10 +49,13 @@ import { certCyclic, certOn, crossCyclic, cyclicOn, foldNodes, proveCyclic, quie
44
49
  import { discover } from "./discover.js";
45
50
  import { inferLaws, inferRates } from "./infer.js";
46
51
  import { findBoundedRun } from "./bmc.js";
52
+ import { checkAcceleratedRun, findAcceleratedRefutation, formatAcceleratedSummary } from "./accel-refute.js";
53
+ export { checkAcceleratedRun, findAcceleratedRefutation, formatAcceleratedSummary };
47
54
  import { conjunction, proveKInduction } from "./kind.js";
48
55
  import { cycleLemmas, findLeadsTo, findRank } from "./cycles.js";
49
56
  import { findNeverEnds } from "./nonterm.js";
50
57
  import { findRing, leadsByTerms } from "./live.js";
58
+ import { leadsByWriteSupports } from "./live-support.js";
51
59
  import { freshLaws } from "./fresh.js";
52
60
  // --- terms and conditions -------------------------------------------------------------------------------------------
53
61
  const naturalConst = (v) => {
@@ -3457,17 +3465,17 @@ function watchdogVerdict(ms, run) {
3457
3465
  export function proveRule(r, laws, opts = {}) {
3458
3466
  return watchdogVerdict(opts.watchdogMs, () => withModelRounds(opts.modelRounds, () => withPublicRule(outermost => {
3459
3467
  const captureMachine = r.machine, hasCounts = !!Object.keys(captureMachine.counts ?? {}).length;
3460
- const result = workVerdict(opts, plan => withPublicSearchPolicy(hasCounts, () => proveRuleWall(r, laws, plan)));
3468
+ const result = workVerdict(opts, plan => withPublicSearchPolicy(hasCounts, () => proveRuleWall(r, laws, plan, captureMachine)));
3461
3469
  return outermost ? publishProof(result, captureMachine, laws) : result;
3462
3470
  })));
3463
3471
  }
3464
- function proveRuleWall(r, laws, opts) {
3472
+ function proveRuleWall(r, laws, opts, captureMachine) {
3465
3473
  const ms = typeof opts.search === 'object' ? opts.search.ms : undefined;
3466
3474
  const run = () => {
3467
3475
  let result;
3468
3476
  try {
3469
3477
  checkWall('rule preflight');
3470
- const out = result = proveRuleIn(r, laws, opts);
3478
+ const out = result = proveRuleIn(r, laws, opts, captureMachine);
3471
3479
  if (!completedSearch(out) && !(out.stopped && out.termination))
3472
3480
  checkWall('rule result');
3473
3481
  return out;
@@ -3484,7 +3492,8 @@ function proveRuleWall(r, laws, opts) {
3484
3492
  const result = ms === undefined ? run() : withWall(searchWall(ms), run);
3485
3493
  return retainFrom(translationVerdict(r, laws, result), [result]);
3486
3494
  }
3487
- function proveRuleIn(r, laws, opts) {
3495
+ function proveRuleIn(r, laws, opts, captureMachine) {
3496
+ const originalRule = r;
3488
3497
  r = r.withSumsOf(laws, opts.candidateSeeds?.laws ?? []);
3489
3498
  noting(r, laws);
3490
3499
  if (opts.candidateSeeds) {
@@ -3516,8 +3525,53 @@ function proveRuleIn(r, laws, opts) {
3516
3525
  // 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
3517
3526
  // at), is a counterexample to induction: the laws may still hold, so the search goes on from it, as from the kernel's.
3518
3527
  // (A step law broken so is refused, proveSteps below: it holds from every state the laws allow, reached or not.)
3528
+ if (refuted?.run)
3529
+ return refutedVerdict(refuted);
3530
+ // A narrowly matched candidate gets a bounded attempt before unrestricted
3531
+ // inference. A failed helper proof is not a verdict about the caller's law.
3532
+ const search = typeof opts.search === 'object' ? opts.search : undefined;
3533
+ const seedMs = search?.ms ?? 10_000;
3534
+ if (opts.search !== false && opts.from !== 'any' && !opts.candidateSeeds && laws.length === 1 &&
3535
+ !captureMachine.history && !Object.keys(captureMachine.sums ?? {}).length && !Object.keys(captureMachine.counts ?? {}).length &&
3536
+ !Object.keys(r.machine.sums ?? {}).length) {
3537
+ const law = laws[0];
3538
+ if (search?.work === undefined && !completeWorkProfile.enabled && seedMs > 0 && Number.isFinite(seedMs)) {
3539
+ const lockstep = tryLockstepScalars(captureMachine, law, withKinds(r, [law]).slice(0, -1), Math.min(seedMs / 2, 26_000));
3540
+ if (lockstep)
3541
+ return lockstep;
3542
+ }
3543
+ if (!Object.keys(captureMachine.fns ?? {}).length && law.forall && law.keys?.length === 1 &&
3544
+ (search?.work !== undefined || seedMs > 0 && Number.isFinite(seedMs))) {
3545
+ const start = countedSearchNow(), prove = () => {
3546
+ const seed = orderedPairSeed(captureMachine, law);
3547
+ if (!seed)
3548
+ return undefined;
3549
+ const out = proveLaws(captureMachine, withKinds(r, [seed, law]));
3550
+ if (!out.proven || !out.checked)
3551
+ return undefined;
3552
+ const found = [{ text: seed.name, law: seed }];
3553
+ return retainFrom({ ...verdictOf(out), found: { laws: found }, ...withAssumes(found) }, [out], { kind: 'inference', original: captureMachine, laws });
3554
+ };
3555
+ const out = search?.work === undefined
3556
+ ? withStageWall(start + seedMs * (2 / 3), prove, () => undefined)
3557
+ : withStageWork(remainingStageWork(search.work, 2), prove, () => undefined);
3558
+ if (out)
3559
+ return out;
3560
+ if (search?.work === undefined && search?.ms === undefined && !completeWorkProfile.enabled)
3561
+ opts = { ...opts, search: { ...search, ms: Math.max(0, seedMs - (countedSearchNow() - start)) } };
3562
+ }
3563
+ }
3519
3564
  if (refuted)
3520
- return refuted.run ? refutedVerdict(refuted) : searched(r, laws, [], refutedVerdict(refuted), opts);
3565
+ return searched(r, laws, [], refutedVerdict(refuted), opts);
3566
+ if (r === originalRule && !opts.candidateSeeds && opts.from !== 'any' && opts.search !== false &&
3567
+ !completeWorkProfile.enabled && !(typeof opts.search === 'object' && opts.search.work !== undefined) && laws.length === 1) {
3568
+ const ms = typeof opts.search === 'object' ? opts.search.ms ?? 60_000 : 60_000;
3569
+ // Rule.machine can allocate fresh write binders on each access. Check and
3570
+ // retain the same public snapshot, not a later alpha-renamed copy.
3571
+ const aggregate = searchAggregate(captureMachine, laws[0], () => withKinds(r, laws).slice(0, -1), ms);
3572
+ if (aggregate)
3573
+ return retainAggregate({ proven: true, checked: true }, captureMachine, laws[0], aggregate.certificate, aggregate.kinds);
3574
+ }
3521
3575
  // A rule with counts: its goals are the counted ones (core/counts.ts searches them; the kernel checks the set).
3522
3576
  if (r.machine.counts && Object.keys(r.machine.counts).length) {
3523
3577
  const c = searchCounted(r.machine, withKinds(r, laws), typeof opts.search === 'object' ? opts.search.ms ?? 60_000 : 60_000);
@@ -3564,7 +3618,8 @@ function proveStepsWall(r, laws, stepLaws, opts) {
3564
3618
  };
3565
3619
  const verdict = opts.from !== 'any' || ms === undefined ? run()
3566
3620
  : withWall(countedSearchNow() + ms, run);
3567
- return translationVerdict(r, [...laws, ...stepLaws], verdict);
3621
+ const translated = translationVerdict(r, [...laws, ...stepLaws], verdict);
3622
+ return publishStepProof(translated, verdict);
3568
3623
  }
3569
3624
  function proveStepsIn(r, laws, stepLaws, opts) {
3570
3625
  r = r.withSumsOf(laws, stepLaws);
@@ -3573,11 +3628,48 @@ function proveStepsIn(r, laws, stepLaws, opts) {
3573
3628
  checkWorkEndpoint('refutation result');
3574
3629
  // (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
3575
3630
  // be further than these runs go; the search goes on from it, as from the kernel's)
3576
- if (refuted)
3577
- return refuted.run ? refutedVerdict(refuted) : searched(r, laws, stepLaws, refutedVerdict(refuted), opts);
3578
- const out = proveStepLaws(r.machine, withKinds(r, laws), stepLaws);
3579
- const v = verdictOf(out);
3580
- return searched(r, laws, stepLaws, v, opts);
3631
+ if (refuted?.run)
3632
+ return refutedVerdict(refuted);
3633
+ const m = r.machine;
3634
+ // A bounded search for reachable-state supports. Keep from-any proofs,
3635
+ // explicit work accounting and real counterexample preflight unchanged.
3636
+ const sl = stepLaws.length === 1 ? stepLaws[0] : undefined;
3637
+ const search = typeof opts.search === 'object' ? opts.search : undefined;
3638
+ const ms = Math.min(55_000, (search?.ms ?? 10_000) * (11 / 12));
3639
+ let fallback = opts;
3640
+ const enabled = sl && opts.search !== false && opts.from !== 'any' &&
3641
+ search?.work === undefined && !inBudget() && !completeWorkProfile.enabled && ms > 0 && Number.isFinite(search?.ms ?? 10_000);
3642
+ const trySeeds = (law) => {
3643
+ const started = countedSearchNow();
3644
+ const seeded = withStageDeadline(clock() + ms, () => {
3645
+ for (const seeds of stepSeedFamilies(m, law).slice(0, law.forall ? 1 : 2)) {
3646
+ const found = quietly(() => tryStepSeed(m, laws, r.kindLaws(), law, seeds));
3647
+ if (found?.checked.proven && found.checked.checked && found.checked.proof)
3648
+ return { ...found, seeds };
3649
+ }
3650
+ return undefined;
3651
+ }, () => undefined);
3652
+ if (seeded) {
3653
+ const found = seeded.seeds.map(law => ({ law, text: law.name }));
3654
+ return retainStepProof({ ...verdictOf(seeded.checked), found: { laws: found }, ...withAssumes(found) }, { machine: m, family: seeded.family, step: law, report: seeded.checked, ...(seeded.kindProof ? { kindProof: seeded.kindProof } : {}) });
3655
+ }
3656
+ const elapsed = Math.max(0, countedSearchNow() - started);
3657
+ if (elapsed >= 1)
3658
+ fallback = { ...opts, search: { ...search, ms: Math.max(0, (search?.ms ?? 10_000) - elapsed) } };
3659
+ return undefined;
3660
+ };
3661
+ // For a one-row law the sparse attempt avoids the large default instance
3662
+ // set entirely. The other shapes only try seeding after a non-inductive step.
3663
+ const sparse = enabled && sl?.forall && !laws.length ? trySeeds(sl) : undefined;
3664
+ if (sparse)
3665
+ return sparse;
3666
+ const v = refuted ? refutedVerdict(refuted) : verdictOf(proveStepLaws(m, withKinds(r, laws), stepLaws));
3667
+ if (enabled && sl && !sl.forall && v.stuck === 'sat') {
3668
+ const strengthened = trySeeds(sl);
3669
+ if (strengthened)
3670
+ return strengthened;
3671
+ }
3672
+ return searched(r, laws, stepLaws, v, fallback);
3581
3673
  }
3582
3674
  // 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
3583
3675
  // 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
@@ -3625,7 +3717,7 @@ function searched(r, laws, stepLaws, v, opts) {
3625
3717
  }
3626
3718
  function searchedIn(r, laws, stepLaws, v, opts) {
3627
3719
  const any = opts.from === 'any';
3628
- if ((v.proven && v.checked) || opts.search === false || v.run || v.stuck === 'sat' && (any || !/@step|@\d+ steps/.test(v.goal ?? '')))
3720
+ if ((v.proven && v.checked) || opts.search === false || v.run || v.acceleratedRun?.checked || v.stuck === 'sat' && (any || !/@step|@\d+ steps/.test(v.goal ?? '')))
3629
3721
  return v;
3630
3722
  // The deeper runs; then runs over small values (keys that meet, small params), whose requests meet their
3631
3723
  // assumption's equalities and clocks, or near the counterexample the verdict ends at.
@@ -3652,7 +3744,7 @@ function searchedIn(r, laws, stepLaws, v, opts) {
3652
3744
  return searchedUntil(r, laws, stepLaws, v, opts, until);
3653
3745
  return withStageWall(countedSearchNow() + Math.max(0, until - clock()), () => {
3654
3746
  const out = searchedUntil(r, laws, stepLaws, v, opts, until);
3655
- if (!(out.proven && out.checked) && !out.run)
3747
+ if (!completedSearch(out))
3656
3748
  checkWall('search result');
3657
3749
  return out;
3658
3750
  }, () => stoppedSearch(v, { kind: 'work-exhausted', phase: 'search stage', scope: 'stage' }));
@@ -3692,6 +3784,22 @@ function searchedUntil(r, laws, stepLaws, v, opts, until) {
3692
3784
  if (kd?.proven && kd.checked)
3693
3785
  return { proven: true, checked: true, k: kd.k, assumes: { states: 'reachable', laws: [] } };
3694
3786
  }
3787
+ // A compressed repeat is untrusted until the unchanged kernel proves its
3788
+ // admitted affine steps and exact replay checks the original failed law.
3789
+ // Translated source requires its own native replay; a model repeat is not it.
3790
+ if (!any && !stepLaws.length && !isSourceBound(r, laws) && !stepWorkProfile.enabled && !inBudget() &&
3791
+ laws.every(l => !l.forall && !l.keys?.length && !l.some?.length) && total > 1_000) {
3792
+ const ms = Math.min(1_500, total / 12), machine = r.machine;
3793
+ const acc = counted(fullRate, () => withStageAllowance(ms, () => findAcceleratedRefutation(machine, laws, {
3794
+ ms,
3795
+ wall: performance.now() + ms,
3796
+ shownRequest,
3797
+ randomParams: (rand, bound) => r.randomParams(rand, bound),
3798
+ randomInput: (rand, bound, ps) => r.randomInput(rand, bound, ps),
3799
+ }), () => undefined), true);
3800
+ if (acc?.checked && checkAcceleratedRun(machine, laws, acc))
3801
+ return { proven: false, checked: false, goal: `${acc.law} @accelerated (${formatAcceleratedSummary(acc)})`, stuck: 'sat', witness: acc.witness, acceleratedRun: acc };
3802
+ }
3695
3803
  let rule = r, lemmas;
3696
3804
  const { fns, lists } = r.parts;
3697
3805
  if (lists.length || fns.some(([, d]) => recurOf(d))) {
@@ -3907,23 +4015,43 @@ const withAssumes = (found) => (found.length ? { assumes: reachableBy(found) } :
3907
4015
  // The rule a keyed liveness is proven on: the rule with its key as one more param (a natural), any other rule as it is.
3908
4016
  export const keyed = (r, l) => (l.forall ? r.params({ [l.forall]: nat }) : r);
3909
4017
  export function proveLeadsTo(r, laws, l, opts = {}) {
3910
- return translationVerdict(r, [...laws, l], proveLeadsToIn(r, laws, l, opts));
4018
+ const out = proveLeadsToIn(r, laws, l, opts, !isSourceBound(r, [...laws, l]));
4019
+ return publishLiveProof(translationVerdict(r, [...laws, l], out), out);
3911
4020
  }
3912
- function proveLeadsToIn(r, laws, l, opts) {
4021
+ function proveLeadsToIn(r, laws, l, opts, allowRing) {
3913
4022
  r = keyed(r, l).withSumsOf(laws, l);
3914
4023
  noting(r, laws, l);
3915
4024
  if (laws.some(law => law.some?.length))
3916
4025
  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)`);
3917
4026
  if (Array.isArray(l.rank) && !l.rank.length) {
3918
- const until = clock() + (opts.ms ?? 10_000), draws = { params: (rand, bound) => r.randomParams(rand, bound), input: (rand, bound, ps) => r.randomInput(rand, bound, ps) };
4027
+ const ms = opts.ms ?? 10_000, until = clock() + ms;
4028
+ const draws = { params: (rand, bound) => r.randomParams(rand, bound), input: (rand, bound, ps) => r.randomInput(rand, bound, ps) };
4029
+ const m = r.machine, ringMs = Math.min(15_000, ms / 4);
4030
+ // History queries can keep a helpful request disabled indefinitely. Search
4031
+ // for a checked ring within the normal grant; never use a model ring as a
4032
+ // counterexample for extracted source or with unverified function facts.
4033
+ if (m.history && allowRing && !completeWorkProfile.enabled && ringMs > 1000 && Number.isFinite(ms)) {
4034
+ const found = withStageDeadline(clock() + ringMs, () => findRing(m, withKinds(r, laws), l, draws, { ms: ringMs }), () => undefined);
4035
+ if (found?.verdict.refuted)
4036
+ return { proven: false, checked: false, goal: l.name, stuck: 'sat', fairRing: found.ring };
4037
+ }
3919
4038
  // (the laws about the keys a counter hands out or a high-water mark bounds, core/fresh.ts, within a twentieth: given
3920
4039
  // to both searches, each proven again with the rank)
3921
4040
  const share = (until - clock()) / 20, fresh = Object.keys(r.machine.maps ?? {}).length ? withStageDeadline(clock() + share, () => freshLaws(r.machine, r.kindLaws(), draws, { ms: share }), () => []) : [];
3922
4041
  laws = [...laws, ...fresh.map(x => x.law)];
3923
- let f = findLeadsTo(r.machine, withKinds(r, laws), l, { ...draws, rule: r }, { ms: until - clock() });
4042
+ const ds = { ...draws, rule: r, state: (rand, bound) => Object.assign({}, ...r.kindsOfState().map(([n, kd]) => kd.random(n, rand, bound))) };
4043
+ // Strong fairness admits upward helpful handoffs at a fixed rank. Give guard-distance ranks a bounded first
4044
+ // look: the affine fit can spend the entire grant without finding a truncated distance to a guard bound.
4045
+ const firstMs = Math.min(15_000, (until - clock()) / 4), base = withKinds(r, laws);
4046
+ const early = completeWorkProfile.enabled ? undefined : withStageDeadline(Math.min(until, clock() + firstMs), () => l.fairness === 'strong' ?
4047
+ (firstMs > 1000 ? leadsByTerms(r.machine, base, l, ds, { ms: firstMs }) : undefined) :
4048
+ leadsByWriteSupports(r.machine, base, l, firstMs), () => undefined);
4049
+ let f = early?.proven && early.checked ? early : until > clock() ?
4050
+ findLeadsTo(r.machine, base, l, { ...draws, rule: r }, { ms: until - clock() }) :
4051
+ { proven: false, checked: false, why: 'liveness search reached its deadline' };
3924
4052
  // Where the rank fitted to the runs isn't the one: a rank of the rule's own terms (core/live.ts), in the time left.
3925
4053
  if (!(f.proven && f.checked) && until - clock() > 500) {
3926
- const g = leadsByTerms(r.machine, withKinds(r, laws), l, { ...draws, rule: r, state: (rand, bound) => Object.assign({}, ...r.kindsOfState().map(([n, kd]) => kd.random(n, rand, bound))) }, { ms: until - clock() });
4054
+ const g = leadsByTerms(r.machine, withKinds(r, laws), l, ds, { ms: until - clock() });
3927
4055
  if (g.proven && g.checked)
3928
4056
  f = g;
3929
4057
  }
@@ -3942,17 +4070,21 @@ function proveLeadsToIn(r, laws, l, opts) {
3942
4070
  }
3943
4071
  }
3944
4072
  const helpers = [...fresh, ...(f.laws ?? []).map((law, i) => ({ law, text: f.found?.laws[i] ?? law.name }))];
3945
- return { proven: f.proven, checked: f.checked, ...(f.proven && f.rank ? { rank: f.rank } : {}), ...(f.goal ? { goal: f.goal, stuck: f.stuck } : {}), ...(f.witness ? { witness: f.witness } : {}), ...(f.why ? { why: f.why } : {}),
3946
- ...(f.found ? { found: { rank: f.found.rank, ...(helpers.length ? { laws: helpers } : {}) } } : {}), ...(f.proven ? withAssumes(helpers) : {}) };
4073
+ return retainLiveProof({ proven: f.proven, checked: f.checked, ...(f.proven && f.rank ? { rank: f.rank } : {}), ...(f.proven && f.levels ? { levels: f.levels } : {}), ...(f.goal ? { goal: f.goal, stuck: f.stuck } : {}), ...(f.witness ? { witness: f.witness } : {}), ...(f.why ? { why: f.why } : {}),
4074
+ ...(f.found ? { found: { rank: f.found.rank, ...(helpers.length ? { laws: helpers } : {}) } } : {}), ...(f.proven ? withAssumes(helpers) : {}) }, 'evidence' in f ? f.evidence : undefined);
3947
4075
  }
3948
- const out = proveLiveness(r.machine, withKinds(r, laws), l);
3949
- return verdictOf(out);
4076
+ const machine = r.machine, family = withKinds(r, laws), out = proveLiveness(machine, family, l);
4077
+ const liveness = out.levels ? { ...l, levels: out.levels } : l;
4078
+ return retainLiveProof({ ...verdictOf(out), ...(out.proven && out.checked && out.levels ? { levels: out.levels } : {}) }, { machine, laws: family, liveness, report: out });
3950
4079
  }
3951
4080
  // A leads-to refuted by a fair run that never gets there (core/live.ts's findRing, checked by refutedBy): a stem from
3952
4081
  // the start, then round a ring of sets each request of which the kernel proves allowed and into the next set, fair to
3953
4082
  // each helpful request (taken in the ring, or never allowed in a set). Undefined where none is found within `ms`.
3954
4083
  export function refuteLeadsTo(r, laws, l, opts = {}) {
3955
- const k = keyed(r, l);
4084
+ if (isSourceBound(r, [...laws, l]) || completeWorkProfile.enabled)
4085
+ return undefined;
4086
+ const k = keyed(r, l).withSumsOf(laws, l);
4087
+ noting(k, laws, l);
3956
4088
  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);
3957
4089
  }
3958
4090
  // `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
+ }
@@ -0,0 +1,5 @@
1
+ import { type Law, type Machine } from './machine.js';
2
+ import { type Liveness } from '../kernel/kernel.js';
3
+ import { type LeadsVerdict } from './cycles.js';
4
+ export declare function helpfulWriteSupports(m: Machine, l: Liveness): Law[];
5
+ export declare function leadsByWriteSupports(m: Machine, laws: Law[], l: Liveness, ms: number): LeadsVerdict | undefined;
@@ -0,0 +1,148 @@
1
+ // Candidate invariants for simple helpful steps. Everything in this file is search guidance: even a syntactically
2
+ // matched write may take a different branch or alias a watched key. Only proveLiveness may accept the proposals.
3
+ import { walk } from "./machine.js";
4
+ import { livenessHelpful, substE, trueC } from "../kernel/kernel.js";
5
+ import { clock, proveLiveness, proveProgress, withDeadline } from "../kernel/prove.js";
6
+ import { showC } from "./cycles.js";
7
+ const id = (x) => JSON.stringify(x);
8
+ const same = (a, b) => id(a) === id(b);
9
+ const v = (name) => ({ op: 'var', name }), k = (value) => ({ op: 'const', value });
10
+ const at = (map, key) => ({ op: 'get', map, key });
11
+ const eq = (a, b) => ({ op: '=', a, b }), le = (a, b) => ({ op: '<=', a, b });
12
+ const implies = (x, y) => ({ op: 'or', xs: [{ op: 'not', x }, y] });
13
+ const and = (x, y) => ({ op: 'and', xs: [x, y] });
14
+ const conjuncts = (x) => x.op === 'and' ? x.xs.flatMap(conjuncts) : [x];
15
+ const addends = (x) => x.op === 'add' ? [...addends(x.a), ...addends(x.b)] : [x];
16
+ const outcomes = (x) => x.op === 'if' ? [...outcomes(x.then), ...outcomes(x.else)] : [x];
17
+ const mentions = (t, f) => {
18
+ let hit = false;
19
+ walk(t, o => { if (f(o))
20
+ hit = true; });
21
+ return hit;
22
+ };
23
+ const reads = (t, names) => mentions(t, o => o.op === 'var' && names.includes(o.name));
24
+ export function helpfulWriteSupports(m, l) {
25
+ if (m.history || m.sums && Object.keys(m.sums).length || m.inputMaps?.length || livenessHelpful(l).length !== 1)
26
+ return [];
27
+ const request = livenessHelpful(l)[0].request, stored = Object.entries(m.step.maps ?? {});
28
+ if (!stored.length || stored.length > 32)
29
+ return [];
30
+ const updates = Object.entries(m.step.state ?? {}), found = new Map();
31
+ const add = (holds) => {
32
+ const key = id(holds);
33
+ if (found.size >= 8 || found.has(key))
34
+ return;
35
+ found.set(key, { name: `liveness write support ${found.size + 1}: ${showC(holds)}`, holds });
36
+ };
37
+ // A helpful request names a key past a max/frontier. Where a scalar is either retained or written from that
38
+ // same request key, compare its value with the written expression at the frontier. Ordinary freshness laws about
39
+ // cells beyond the frontier are separately supplied by freshLaws. No clock assumption is added to the machine.
40
+ for (const [mark, next] of updates)
41
+ if (next.op === 'max') {
42
+ const key = same(next.a, v(mark)) ? next.b : same(next.b, v(mark)) ? next.a : undefined;
43
+ if (key?.op !== 'var' || !request[key.name] || !reads(request[key.name], [mark]) ||
44
+ !stored.some(([, w]) => 'key' in w && same(w.key, key)))
45
+ continue;
46
+ for (const [x, e] of updates)
47
+ if (e.op === 'if' && same(e.else, v(x)) && reads(e.then, [key.name])) {
48
+ if (mentions(e.then, o => o.op === 'flag' || o.op === 'get') || reads(e.then, m.inputs.filter(y => y !== key.name)))
49
+ continue;
50
+ add(le(v(x), substE(e.then, { vars: { [key.name]: v(mark) }, maps: {}, flags: {} })));
51
+ }
52
+ }
53
+ // A fixed observer is pending when its row's tag equals a constant. Follow its write selector to sibling payloads
54
+ // at the same write key and simple bounds on those payloads. Each projection is only a proposed reachable law.
55
+ for (const trigger of conjuncts(l.from))
56
+ if (trigger.op === '=') {
57
+ const tag = trigger.a.op === 'get' && trigger.b.op === 'const' ? trigger.a :
58
+ trigger.b.op === 'get' && trigger.a.op === 'const' ? trigger.b : undefined;
59
+ if (!tag || reads(tag.key, [...m.inputs, ...Object.keys(m.state)]) || mentions(tag.key, o => o.op === 'get'))
60
+ continue;
61
+ const write = m.step.maps?.[tag.map];
62
+ if (!write || !('key' in write) || write.value.op !== 'if' || !same(write.value.else, at(tag.map, write.key)))
63
+ continue;
64
+ const guard = write.value.c, bounds = new Map(), expanded = new Set();
65
+ const scan = (x) => walk(x, o => {
66
+ if (o.op === 'flag' && typeof o.name === 'string' && !expanded.has(o.name)) {
67
+ expanded.add(o.name);
68
+ const f = m.step.flags?.[o.name];
69
+ if (f)
70
+ scan(f);
71
+ }
72
+ if (o.op === '<=' && o.b?.op === 'var' && o.a?.op === 'add' && !reads(o.b, m.inputs)) {
73
+ bounds.set(id(o), { a: o.a, b: o.b });
74
+ }
75
+ });
76
+ scan(guard);
77
+ for (const [field, w] of stored) {
78
+ if (field === tag.map || !('key' in w) || !same(w.key, write.key) || w.value.op !== 'if')
79
+ continue;
80
+ const cells = at(field, tag.key), init = m.maps?.[field], old = at(field, w.key);
81
+ if (!same(w.value.else, old) || id(w.value.c) !== id(guard)) {
82
+ // A Boolean payload can be encoded after the row update as `if (updated predicate) then 1 else 0`.
83
+ // Recognize a sibling only if that predicate reads its own old bit and the row's update selector.
84
+ const c = w.value.c;
85
+ if ((init === 0 || init === 1) && same(w.value.then, k(1)) && same(w.value.else, k(0)) &&
86
+ mentions(c, o => o.op === 'get' && same(o, old)) && mentions(c, o => id(o) === id(guard))) {
87
+ add(implies(trigger, eq(cells, k(init))));
88
+ }
89
+ continue;
90
+ }
91
+ const val = w.value.then, leaves = outcomes(val);
92
+ // A co-written small choice or bit; the pending state may preserve its initial value.
93
+ if (init !== undefined && leaves.every(x => x.op === 'const' && x.value <= 4) &&
94
+ leaves.some(x => same(x, k(init))))
95
+ add(implies(trigger, eq(cells, k(init))));
96
+ for (const { a, b } of bounds.values())
97
+ if (addends(a).some(x => same(val, x))) {
98
+ add(implies(trigger, le(cells, b)));
99
+ // A simultaneously accumulated value using the same amount may be capped by the same guard bound.
100
+ for (const [x, e] of updates)
101
+ if (!same(v(x), b) && mentions(e, o => o.op === 'add' && addends(o).some(t => same(t, val))))
102
+ add(le(v(x), b));
103
+ // With a parameter-or-request payload, zero in the watched cell may identify the zero parameter case.
104
+ if (leaves.some(x => x.op === 'var' && m.inputs.includes(x.name))) {
105
+ for (const x of leaves)
106
+ if (x.op === 'var' && m.params.includes(x.name))
107
+ add(implies(and(trigger, eq(cells, k(0))), eq(x, k(0))));
108
+ }
109
+ }
110
+ }
111
+ }
112
+ return [...found.values()];
113
+ }
114
+ // Proof proposal only. The ordinary prover checks initiation, simultaneous preservation, stay, coverage,
115
+ // all helpful branches and the original fairness obligations. A wrong projection costs at most this stage's grant.
116
+ export function leadsByWriteSupports(m, laws, l, ms) {
117
+ if (ms < 500 || l.fairness === 'strong')
118
+ return undefined;
119
+ const until = clock() + ms, rank = [k(0)], candidates = helpfulWriteSupports(m, l);
120
+ if (!candidates.length)
121
+ return undefined;
122
+ let alive = candidates.filter(c => !laws.some(law => law.name === c.name));
123
+ while (alive.length && clock() < until) {
124
+ const all = [...laws, ...alive];
125
+ const out = withDeadline(until, () => proveLiveness(m, all, { ...l, rank }));
126
+ if (out.proven && out.checked) {
127
+ // The legacy step proof with unnamed weak-help fields need not show enabledness. For this new route, require
128
+ // one checked completion in each pending state: fill the spare fields with constants (a proof witness, not a
129
+ // new assumption about the scheduler or what values all executions must send).
130
+ const h = livenessHelpful(l)[0];
131
+ let progress;
132
+ if (m.assume && m.inputs.some(i => !(i in h.request))) {
133
+ const request = Object.fromEntries(m.inputs.map(i => [i, h.request[i] ?? k(0)]));
134
+ const a = withDeadline(until, () => proveProgress(m, all, { name: `${l.name}: helpful completion is allowed`,
135
+ when: and(and(l.from, { op: 'not', x: l.to }), h.when), then: trueC, request }));
136
+ if (!a.proven || !a.checked)
137
+ return undefined;
138
+ progress = a;
139
+ }
140
+ return { proven: true, checked: true, rank, laws: alive, evidence: { machine: m, laws: all, liveness: { ...l, rank }, report: out, ...(progress ? { progress } : {}) }, found: { rank: '(0)', laws: alive.map(c => showC(c.holds)) } };
141
+ }
142
+ const drop = alive.findIndex(c => out.failed?.goal.startsWith(`${c.name} @`));
143
+ if (drop < 0)
144
+ return undefined;
145
+ alive = alive.filter((_, i) => i !== drop);
146
+ }
147
+ return undefined;
148
+ }