gdp-wired 0.48.0 → 0.49.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 (295) hide show
  1. package/README.md +2 -2
  2. package/dist/core/bmc.js +10 -7
  3. package/dist/core/check.js +7 -2
  4. package/dist/core/count-attempt-work.d.ts +29 -0
  5. package/dist/core/count-attempt-work.js +96 -0
  6. package/dist/core/count-boolean-partition.d.ts +5 -0
  7. package/dist/core/count-boolean-partition.js +47 -0
  8. package/dist/core/count-bounded-quotient.d.ts +2 -0
  9. package/dist/core/count-bounded-quotient.js +13 -0
  10. package/dist/core/count-case-compose.d.ts +20 -0
  11. package/dist/core/count-case-compose.js +289 -0
  12. package/dist/core/count-cases.js +3 -2
  13. package/dist/core/count-cert-rename.d.ts +10 -0
  14. package/dist/core/count-cert-rename.js +69 -0
  15. package/dist/core/count-cert-transport.d.ts +10 -2
  16. package/dist/core/count-cert-transport.js +60 -9
  17. package/dist/core/count-certificate-minimize.d.ts +57 -0
  18. package/dist/core/count-certificate-minimize.js +263 -0
  19. package/dist/core/count-closed-family.d.ts +32 -0
  20. package/dist/core/count-closed-family.js +143 -0
  21. package/dist/core/count-closing-budget.d.ts +10 -0
  22. package/dist/core/count-closing-budget.js +49 -0
  23. package/dist/core/count-closing-needs.d.ts +5 -0
  24. package/dist/core/count-closing-needs.js +9 -0
  25. package/dist/core/count-component-budget.d.ts +5 -0
  26. package/dist/core/count-component-budget.js +9 -0
  27. package/dist/core/count-copy-shape.d.ts +11 -0
  28. package/dist/core/count-copy-shape.js +40 -0
  29. package/dist/core/count-disjoint-funding.d.ts +75 -0
  30. package/dist/core/count-disjoint-funding.js +284 -0
  31. package/dist/core/count-emitter-frame-pool.d.ts +23 -0
  32. package/dist/core/count-emitter-frame-pool.js +87 -0
  33. package/dist/core/count-final-step.d.ts +5 -0
  34. package/dist/core/count-final-step.js +20 -0
  35. package/dist/core/count-fixed-frame.d.ts +4 -0
  36. package/dist/core/count-fixed-frame.js +30 -0
  37. package/dist/core/count-frames.d.ts +25 -0
  38. package/dist/core/count-frames.js +118 -0
  39. package/dist/core/count-frozen-guard.d.ts +2 -0
  40. package/dist/core/count-frozen-guard.js +31 -0
  41. package/dist/core/count-generation-phase.d.ts +7 -0
  42. package/dist/core/count-generation-phase.js +33 -0
  43. package/dist/core/count-guard-composition.d.ts +12 -0
  44. package/dist/core/count-guard-composition.js +48 -0
  45. package/dist/core/count-guard-context.d.ts +11 -0
  46. package/dist/core/count-guard-context.js +50 -0
  47. package/dist/core/count-guard-facts.d.ts +50 -0
  48. package/dist/core/count-guard-facts.js +97 -0
  49. package/dist/core/count-guard-proposals.d.ts +7 -0
  50. package/dist/core/count-guard-proposals.js +106 -0
  51. package/dist/core/count-guard-shape.d.ts +18 -0
  52. package/dist/core/count-guard-shape.js +100 -0
  53. package/dist/core/count-guard-tree.d.ts +17 -0
  54. package/dist/core/count-guard-tree.js +125 -0
  55. package/dist/core/count-leader-facts.d.ts +10 -0
  56. package/dist/core/count-leader-facts.js +52 -0
  57. package/dist/core/count-leader.d.ts +10 -0
  58. package/dist/core/count-leader.js +331 -0
  59. package/dist/core/count-lemma-transport.d.ts +8 -0
  60. package/dist/core/count-lemma-transport.js +47 -0
  61. package/dist/core/count-lifted-budget.d.ts +54 -0
  62. package/dist/core/count-lifted-budget.js +97 -0
  63. package/dist/core/count-lifted-copy.d.ts +3 -0
  64. package/dist/core/count-lifted-copy.js +166 -0
  65. package/dist/core/count-lifted-increment.d.ts +3 -0
  66. package/dist/core/count-lifted-increment.js +146 -0
  67. package/dist/core/count-lifted-load.d.ts +5 -0
  68. package/dist/core/count-lifted-load.js +179 -0
  69. package/dist/core/count-lifted-prerequisite.d.ts +14 -0
  70. package/dist/core/count-lifted-prerequisite.js +53 -0
  71. package/dist/core/count-lifted-replacement.d.ts +3 -0
  72. package/dist/core/count-lifted-replacement.js +540 -0
  73. package/dist/core/count-lifted-shape.d.ts +63 -0
  74. package/dist/core/count-lifted-shape.js +115 -0
  75. package/dist/core/count-lifted-strategy.d.ts +7 -0
  76. package/dist/core/count-lifted-strategy.js +226 -0
  77. package/dist/core/count-lifted-transports.d.ts +32 -0
  78. package/dist/core/count-lifted-transports.js +293 -0
  79. package/dist/core/count-load-shape.d.ts +17 -0
  80. package/dist/core/count-load-shape.js +67 -0
  81. package/dist/core/count-minimal-view.d.ts +26 -0
  82. package/dist/core/count-minimal-view.js +46 -0
  83. package/dist/core/count-operation-observation.d.ts +9 -0
  84. package/dist/core/count-operation-observation.js +22 -0
  85. package/dist/core/count-operation-order.d.ts +5 -0
  86. package/dist/core/count-operation-order.js +4 -0
  87. package/dist/core/count-phase.d.ts +9 -0
  88. package/dist/core/count-phase.js +127 -0
  89. package/dist/core/count-premise-search.d.ts +9 -0
  90. package/dist/core/count-premise-search.js +41 -0
  91. package/dist/core/count-premise-view.d.ts +19 -0
  92. package/dist/core/count-premise-view.js +220 -0
  93. package/dist/core/count-prerequisite-components.d.ts +67 -0
  94. package/dist/core/count-prerequisite-components.js +239 -0
  95. package/dist/core/count-prerequisite-memory.d.ts +24 -0
  96. package/dist/core/count-prerequisite-memory.js +37 -0
  97. package/dist/core/count-prerequisite-plan.d.ts +12 -0
  98. package/dist/core/count-prerequisite-plan.js +88 -0
  99. package/dist/core/count-primitive-budget.d.ts +1 -0
  100. package/dist/core/count-primitive-budget.js +8 -0
  101. package/dist/core/count-project-free.d.ts +3 -0
  102. package/dist/core/count-project-free.js +24 -0
  103. package/dist/core/count-project-witness.d.ts +4 -0
  104. package/dist/core/count-project-witness.js +48 -0
  105. package/dist/core/count-proof-rescope.d.ts +14 -0
  106. package/dist/core/count-proof-rescope.js +71 -0
  107. package/dist/core/count-proof-scope.d.ts +68 -0
  108. package/dist/core/count-proof-scope.js +333 -0
  109. package/dist/core/count-prune-owned-root.d.ts +5 -0
  110. package/dist/core/count-prune-owned-root.js +27 -0
  111. package/dist/core/count-query-context.d.ts +3 -0
  112. package/dist/core/count-query-context.js +7 -0
  113. package/dist/core/count-query.d.ts +15 -0
  114. package/dist/core/count-query.js +59 -0
  115. package/dist/core/count-quorum-leaf.d.ts +9 -0
  116. package/dist/core/count-quorum-leaf.js +38 -0
  117. package/dist/core/count-reachability-budget.d.ts +1 -0
  118. package/dist/core/count-reachability-budget.js +7 -0
  119. package/dist/core/count-reachability-reconcile.d.ts +11 -0
  120. package/dist/core/count-reachability-reconcile.js +19 -0
  121. package/dist/core/count-reachability.d.ts +50 -0
  122. package/dist/core/count-reachability.js +351 -0
  123. package/dist/core/count-rebase-path.d.ts +9 -0
  124. package/dist/core/count-rebase-path.js +68 -0
  125. package/dist/core/count-recipe-context.d.ts +45 -0
  126. package/dist/core/count-recipe-context.js +71 -0
  127. package/dist/core/count-recipe-controller.d.ts +115 -0
  128. package/dist/core/count-recipe-controller.js +417 -0
  129. package/dist/core/count-recipe-graph.d.ts +36 -0
  130. package/dist/core/count-recipe-graph.js +211 -0
  131. package/dist/core/count-recovery/conditional-check-cache.js +3 -2
  132. package/dist/core/count-recovery/conditional-cuts.js +5 -4
  133. package/dist/core/count-recovery/conditional-proof.d.ts +37 -3
  134. package/dist/core/count-recovery/conditional-proof.js +72 -30
  135. package/dist/core/count-recovery/derivability-closure.js +2 -1
  136. package/dist/core/count-recovery/guard-cases.js +2 -1
  137. package/dist/core/count-recovery/reframe-tree.d.ts +2 -0
  138. package/dist/core/count-recovery/reframe-tree.js +24 -0
  139. package/dist/core/count-recovery/replay-linear-skeleton.d.ts +2 -0
  140. package/dist/core/count-recovery/replay-linear-skeleton.js +28 -0
  141. package/dist/core/count-recovery/row-cases.js +2 -1
  142. package/dist/core/count-rejection-budget.d.ts +8 -0
  143. package/dist/core/count-rejection-budget.js +15 -0
  144. package/dist/core/count-replacement.d.ts +5 -0
  145. package/dist/core/count-replacement.js +129 -0
  146. package/dist/core/count-replay-diagnostic.d.ts +21 -0
  147. package/dist/core/count-replay-diagnostic.js +49 -0
  148. package/dist/core/count-replay-skeleton.d.ts +4 -0
  149. package/dist/core/count-replay-skeleton.js +28 -0
  150. package/dist/core/count-rescope-funding.d.ts +3 -0
  151. package/dist/core/count-rescope-funding.js +17 -0
  152. package/dist/core/count-restrictions.d.ts +11 -0
  153. package/dist/core/count-restrictions.js +31 -0
  154. package/dist/core/count-retry-budget.d.ts +67 -0
  155. package/dist/core/count-retry-budget.js +114 -0
  156. package/dist/core/count-retry-round.d.ts +24 -0
  157. package/dist/core/count-retry-round.js +44 -0
  158. package/dist/core/count-row-agreement.d.ts +35 -0
  159. package/dist/core/count-row-agreement.js +270 -0
  160. package/dist/core/count-row-aliases.d.ts +3 -0
  161. package/dist/core/count-row-aliases.js +59 -0
  162. package/dist/core/count-row-composition.d.ts +6 -0
  163. package/dist/core/count-row-composition.js +55 -0
  164. package/dist/core/count-row-copy-linear.d.ts +4 -0
  165. package/dist/core/count-row-copy-linear.js +83 -0
  166. package/dist/core/count-row-copy.d.ts +4 -0
  167. package/dist/core/count-row-copy.js +94 -0
  168. package/dist/core/count-row-policy.d.ts +3 -0
  169. package/dist/core/count-row-policy.js +56 -0
  170. package/dist/core/count-row-reindex.d.ts +11 -0
  171. package/dist/core/count-row-reindex.js +126 -0
  172. package/dist/core/count-row-support.d.ts +9 -0
  173. package/dist/core/count-row-support.js +42 -0
  174. package/dist/core/count-row-symmetry.d.ts +7 -0
  175. package/dist/core/count-row-symmetry.js +100 -0
  176. package/dist/core/count-scope-hyps.d.ts +2 -0
  177. package/dist/core/count-scope-hyps.js +163 -0
  178. package/dist/core/count-scope-row-reuse.d.ts +3 -0
  179. package/dist/core/count-scope-row-reuse.js +92 -0
  180. package/dist/core/count-search-allowance.d.ts +1 -0
  181. package/dist/core/count-search-allowance.js +17 -0
  182. package/dist/core/count-stabilize-tree.d.ts +9 -0
  183. package/dist/core/count-stabilize-tree.js +35 -0
  184. package/dist/core/count-stage-trace.d.ts +8 -0
  185. package/dist/core/count-stage-trace.js +45 -0
  186. package/dist/core/count-strategies.d.ts +16 -0
  187. package/dist/core/count-strategies.js +155 -0
  188. package/dist/core/count-strategy-premises.d.ts +5 -0
  189. package/dist/core/count-strategy-premises.js +14 -0
  190. package/dist/core/count-strategy.d.ts +41 -0
  191. package/dist/core/count-strategy.js +76 -0
  192. package/dist/core/count-support.js +3 -2
  193. package/dist/core/count-tier-budget.d.ts +14 -0
  194. package/dist/core/count-tier-budget.js +64 -0
  195. package/dist/core/count-unwritten-prefix.d.ts +24 -0
  196. package/dist/core/count-unwritten-prefix.js +97 -0
  197. package/dist/core/count-write-shape.d.ts +15 -0
  198. package/dist/core/count-write-shape.js +73 -0
  199. package/dist/core/counts.d.ts +37 -13
  200. package/dist/core/counts.js +990 -127
  201. package/dist/core/cycles.js +5 -4
  202. package/dist/core/cyclic.js +11 -10
  203. package/dist/core/data.js +16 -15
  204. package/dist/core/dsl-deadline.d.ts +3 -0
  205. package/dist/core/dsl-deadline.js +27 -0
  206. package/dist/core/dsl.d.ts +9 -0
  207. package/dist/core/dsl.js +156 -51
  208. package/dist/core/evaluation-admission.d.ts +1 -0
  209. package/dist/core/evaluation-admission.js +3 -0
  210. package/dist/core/exists.d.ts +6 -1
  211. package/dist/core/exists.js +51 -9
  212. package/dist/core/field-laws.d.ts +3 -1
  213. package/dist/core/field-laws.js +140 -2
  214. package/dist/core/finite-houdini.d.ts +6 -0
  215. package/dist/core/finite-houdini.js +63 -21
  216. package/dist/core/finite-tiny.js +95 -67
  217. package/dist/core/fixtures/count-completion/paxos-decision.json +1 -0
  218. package/dist/core/fresh.js +5 -1
  219. package/dist/core/infer.js +45 -30
  220. package/dist/core/kind.js +2 -1
  221. package/dist/core/lemma-cuts.js +11 -10
  222. package/dist/core/linear-admission.d.ts +14 -0
  223. package/dist/core/linear-admission.js +151 -0
  224. package/dist/core/machine.d.ts +5 -2
  225. package/dist/core/machine.js +105 -31
  226. package/dist/core/meter.d.ts +22 -0
  227. package/dist/core/meter.js +34 -0
  228. package/dist/core/nonterm.js +4 -3
  229. package/dist/core/prover-row-budget.d.ts +3 -0
  230. package/dist/core/prover-row-budget.js +106 -0
  231. package/dist/core/quorum-laws.d.ts +21 -1
  232. package/dist/core/quorum-laws.js +27 -3
  233. package/dist/core/rationals.js +3 -2
  234. package/dist/core/rejection-discovery.d.ts +34 -0
  235. package/dist/core/rejection-discovery.js +36 -0
  236. package/dist/core/rejection-stage.d.ts +39 -0
  237. package/dist/core/rejection-stage.js +205 -0
  238. package/dist/core/request-quotient.d.ts +8 -0
  239. package/dist/core/request-quotient.js +299 -0
  240. package/dist/core/row-agreement-shape.d.ts +15 -0
  241. package/dist/core/row-agreement-shape.js +68 -0
  242. package/dist/core/runtime-wall.d.ts +2 -0
  243. package/dist/core/search-policy.d.ts +15 -0
  244. package/dist/core/search-policy.js +68 -0
  245. package/dist/core/solver.d.ts +1 -1
  246. package/dist/core/solver.js +40 -6
  247. package/dist/core/step-work.d.ts +12 -0
  248. package/dist/core/step-work.js +14 -0
  249. package/dist/core/strategy-premises.d.ts +8 -0
  250. package/dist/core/strategy-premises.js +64 -0
  251. package/dist/core/system.js +4 -3
  252. package/dist/core/table-admission.d.ts +1 -0
  253. package/dist/core/table-admission.js +3 -0
  254. package/dist/core/trace-clock.d.ts +3 -0
  255. package/dist/core/trace-clock.js +16 -0
  256. package/dist/core/transfer.js +3 -2
  257. package/dist/core/translate.js +16 -3
  258. package/dist/core/wall.d.ts +6 -1
  259. package/dist/core/wall.js +23 -9
  260. package/dist/core/watch.d.ts +1 -1
  261. package/dist/core/watch.js +13 -4
  262. package/dist/core/work-admission.d.ts +164 -0
  263. package/dist/core/work-admission.js +418 -0
  264. package/dist/core/work-amount.d.ts +21 -0
  265. package/dist/core/work-amount.js +80 -0
  266. package/dist/core/work-collections.d.ts +11 -0
  267. package/dist/core/work-collections.js +198 -0
  268. package/dist/core/work-kinds.d.ts +11 -0
  269. package/dist/core/work-kinds.js +9 -0
  270. package/dist/core/work-meter.d.ts +8 -0
  271. package/dist/core/work-meter.js +83 -0
  272. package/dist/core/work-observe.d.ts +12 -0
  273. package/dist/core/work-observe.js +39 -0
  274. package/dist/core/work-profile.d.ts +10 -0
  275. package/dist/core/work-profile.js +21 -0
  276. package/dist/core/work-refusal.d.ts +1 -0
  277. package/dist/core/work-refusal.js +6 -0
  278. package/dist/interchange/format.js +2 -0
  279. package/dist/kernel/cdcl.js +93 -40
  280. package/dist/kernel/epr.js +23 -8
  281. package/dist/kernel/kernel.d.ts +47 -1
  282. package/dist/kernel/kernel.js +417 -68
  283. package/dist/kernel/prove.d.ts +49 -3
  284. package/dist/kernel/prove.js +468 -122
  285. package/dist/kernel/prover-rows.d.ts +1 -0
  286. package/dist/kernel/prover-rows.js +12 -1
  287. package/dist/kernel/reader.d.ts +1 -1
  288. package/dist/kernel/reader.js +57 -12
  289. package/dist/kernel/simplex.js +9 -2
  290. package/dist/lean-kernel/emit.d.ts +9 -1
  291. package/dist/lean-kernel/emit.js +144 -22
  292. package/dist/lean-kernel/legacy-family-library.d.ts +1 -0
  293. package/dist/lean-kernel/legacy-family-library.js +5 -0
  294. package/dist/lean-kernel/library.js +3 -3
  295. package/package.json +1 -1
@@ -11,6 +11,14 @@
11
11
  import { cpair, evalC, evalE, walkOnce } from "../core/machine.js";
12
12
  import { add, costs, env, k, refuteFast, scale, solve, sub, v, work } from "../core/solver.js";
13
13
  import { checkRefutation } from "../core/check.js";
14
+ import { fullWork as rawFullWork } from "../core/work-meter.js";
15
+ import { stepWork, stepWorkProfile } from "../core/step-work.js";
16
+ import { completeWorkProfile } from "../core/work-profile.js";
17
+ import { projectedSearchWork, proxySearchState } from "../core/search-policy.js";
18
+ import { BudgetExpired, admittedWork, startWork, workLedger } from "../core/work-admission.js";
19
+ import { workDivide, workFromNumber, workMultiply, workToNumber } from "../core/work-amount.js";
20
+ export { BudgetExpired } from "../core/work-admission.js";
21
+ import { traceNow, withTraceWorkScope } from "../core/trace-clock.js";
14
22
  import { allowNode, allowTranslated, certCyclic, certOn, certSearch, stepCertFloor, translateMs, closingInsts, crossCyclic, cyclicOn, cycLog, hasQuantified, loopNodes, machineNodes, proveCyclic, reqTS, searchedStepNodes, skMachine, timedKind, withWitness, translatedProof, uncovered, uncoveredWhy } from "../core/cyclic.js";
15
23
  import { proveSome, someLaws } from "../core/exists.js";
16
24
  import { REFUTED, growCdcl } from "./cdcl.js";
@@ -21,6 +29,8 @@ import { proverRows } from "./prover-rows.js";
21
29
  import { assumed, atomOf, boundOf, canon, canonFlip, cellParts, columnTerm, decided, factorsOf, isCell, isMonomial, stepZone, check, checkLaws, checkStepLaws, historyMachine, plainOf, substC, substE, leafConstraints, leafConstraintsReusing, reusing, linear, livenessHelpful, livenessParts, strongly, loopMachine, obligations, plainKey, progressObligations, stepLawObligations, trueC, truth, unreachable, witnessesOf, withProducts } from "./kernel.js";
22
30
  // The atoms the path leaves open, in evaluation order: deciding any of them makes progress.
23
31
  function openE(e, path, out) {
32
+ if (completeWorkProfile.enabled)
33
+ checkWorkEndpoint('open expression');
24
34
  switch (e.op) {
25
35
  case 'var':
26
36
  case 'const': return;
@@ -51,6 +61,8 @@ function openE(e, path, out) {
51
61
  }
52
62
  }
53
63
  function openC(c, path, out) {
64
+ if (completeWorkProfile.enabled)
65
+ checkWorkEndpoint('open condition');
54
66
  if (truth(c, path) !== undefined)
55
67
  return;
56
68
  if (c.op === 'flag' || c.op === 'all')
@@ -79,6 +91,8 @@ function openC(c, path, out) {
79
91
  // conjunction of settled parts / a linear comparison. A disjunction is settled only once one disjunct is left open and
80
92
  // that one is settled: facts from its last disjunct are not all its content while a case inside it is still open.
81
93
  function openH(c, path, out, positive = true) {
94
+ if (completeWorkProfile.enabled)
95
+ checkWorkEndpoint('open hypothesis');
82
96
  if (c.op === 'not')
83
97
  return openH(c.x, path, out, !positive);
84
98
  if ((c.op === 'and' && positive) || (c.op === 'or' && !positive))
@@ -179,6 +193,8 @@ function openCells(rows, path) {
179
193
  const dec = (lin) => path.get(canon(lin))?.holds ?? (path.has(canonFlip(lin)) ? !path.get(canonFlip(lin)).holds : undefined);
180
194
  for (let i = 0; i < names.length; i++)
181
195
  for (let j = i + 1; j < names.length; j++) {
196
+ if (completeWorkProfile.enabled)
197
+ checkWorkEndpoint('open cell pair');
182
198
  if (cs[i].map !== cs[j].map)
183
199
  continue;
184
200
  if (cs[i].keys || cs[j].keys) {
@@ -259,17 +275,17 @@ export function parseKey(text) {
259
275
  // the time in the solver and in building rows. Off unless `profile.on`; the counters cost nothing then.
260
276
  export const profile = { on: false, goals: [], solves: 0, solveMs: 0, rowsMs: 0, nodes: 0 };
261
277
  const timed = (f, add) => { if (!profile.on)
262
- return f(); const t = performance.now(); try {
278
+ return f(); const t = traceNow(); try {
263
279
  return f();
264
280
  }
265
281
  finally {
266
- add(performance.now() - t);
282
+ add(traceNow() - t);
267
283
  } };
268
284
  export const solveKinds = {};
269
285
  const solveP = (rows, maxRows) => {
270
286
  if (!profile.on)
271
287
  return solve(rows, maxRows);
272
- const t = performance.now(), out = solve(rows, maxRows), ms = performance.now() - t;
288
+ const t = traceNow(), out = solve(rows, maxRows), ms = traceNow() - t;
273
289
  profile.solves++;
274
290
  profile.solveMs += ms;
275
291
  const s = (solveKinds[out.kind] ??= { n: 0, ms: 0, rows: 0 });
@@ -293,28 +309,54 @@ export const cellProducts = { on: false };
293
309
  let deadline = Infinity, deadlineEpr = 0;
294
310
  // EPR has its own work counter. Debit it from a counted deadline, not from clock(): the protocol engine already
295
311
  // accounts for EPR in its own clock. A scope's anchor charges all its queries, including nested and failed ones.
296
- const eprTimeSince = (start) => rate ? (eprMeter.n - start) / rate : 0;
312
+ const searchRate = () => proxySearchState()?.rate ?? rate;
313
+ const eprTimeSince = (start) => searchRate() ? (eprMeter.n - start) / searchRate() : 0;
297
314
  // The clock every budget here reads (grow's `until`, withDeadline's; core/cyclic.ts's and core/data.ts's searches): wall
298
315
  // time, or within `counted` the work the prover has done (the solver's rows read and made, each node's rows), `perMs`
299
316
  // units a millisecond, so that what a search's budget lets it try, and so its verdict, doesn't depend on the machine's
300
317
  // speed. A counted search inside another reads the outer's clock.
301
318
  // With `full`, the clock reads the cost model below in place of work.n.
302
319
  let rate = 0, meter = () => work.n;
303
- export const clock = () => (rate ? meter() / rate : performance.now());
320
+ export const clock = () => {
321
+ const proxy = proxySearchState();
322
+ if (proxy)
323
+ return proxy.rate ? (proxy.model ? projectedSearchWork() : work.n) / proxy.rate : projectedSearchWork() / fullRate;
324
+ return completeWorkProfile.enabled ? workToNumber(workDivide(admittedWork(), workFromNumber(fullRate))) : stepWorkProfile.enabled ? fullWork() / fullRate : (rate ? meter() / rate : performance.now());
325
+ };
304
326
  export function counted(perMs, f, full = false) {
305
- if (rate)
306
- return f();
307
- const outer = deadline;
308
- rate = perMs;
309
- deadline = Infinity;
310
- meter = full ? fullWork : () => work.n;
311
- try {
312
- return f();
313
- }
314
- finally {
315
- rate = 0;
316
- deadline = outer;
317
- }
327
+ return withTraceWorkScope(() => {
328
+ const proxy = proxySearchState();
329
+ if (proxy) {
330
+ if (proxy.rate)
331
+ return f();
332
+ const outer = proxy.deadline, outerEpr = proxy.deadlineEpr, model = proxy.model;
333
+ proxy.rate = perMs;
334
+ proxy.model = full;
335
+ proxy.deadline = Infinity;
336
+ try {
337
+ return f();
338
+ }
339
+ finally {
340
+ proxy.rate = 0;
341
+ proxy.model = model;
342
+ proxy.deadline = outer;
343
+ proxy.deadlineEpr = outerEpr;
344
+ }
345
+ }
346
+ if (rate || completeWorkProfile.enabled)
347
+ return f();
348
+ const outer = deadline;
349
+ rate = perMs;
350
+ deadline = Infinity;
351
+ meter = full ? fullWork : () => work.n;
352
+ try {
353
+ return f();
354
+ }
355
+ finally {
356
+ rate = 0;
357
+ deadline = outer;
358
+ }
359
+ });
318
360
  }
319
361
  // The cost model: what a query does, by kind (core/solver.ts's costs), each weighed to the milliseconds a Modal 2-vCPU
320
362
  // container takes for it, `fullRate` units a millisecond at the median query: elimination's pairs and the float
@@ -324,30 +366,186 @@ export function counted(perMs, f, full = false) {
324
366
  // the solver and each node read, which the incremental search reads whole no more: on 7,027 root queries of 20 ms or
325
367
  // more (research/query/fit.py on runs/query/cal2: the 332 step goals, CHC sat and unsat, ITS, the false step goals and
326
368
  // the real-world corpus), work.n did 28 to 377 units a ms (p10, p90), the model 120 to 401.
327
- const model = [['fm', 2.33], ['fcells', 0.0123], ['plainRows', 7.93], ['values', 0.672], ['copies', 0.735], ['edges', 0.0435],
328
- ['scan', 0.0765], ['pivotRows', 0.599], ['unitRows', 15.6], ['unfoldRows', 0.735], ['goalNodes', 0.492], ['translateRows', 7.93]];
329
369
  export const fullRate = 250;
330
- export const fullWork = () => { let n = 0; for (const [k, w] of model)
331
- n += w * costs[k]; return n; };
370
+ export const fullWork = () => stepWork() + rawFullWork();
371
+ // Only heuristic readers use this. fullWork and every admission stay authoritative.
372
+ export const searchWork = () => proxySearchState() ? projectedSearchWork() : fullWork();
373
+ // Explicit synchronous work scopes. The default paths do not enter one yet:
374
+ // count/plain migrations and legacy deadline-reset semantics are separate steps.
375
+ let budgetUnitsEnd;
376
+ let admissionRefusedAt;
377
+ export const inBudget = () => completeWorkProfile.enabled ? workLedger.inBudget() : budgetUnitsEnd !== undefined;
378
+ export const inWorkScope = () => inBudget() || rate !== 0 || stepWorkProfile.enabled;
379
+ // Search endpoints follow the active clock; legacy real walls remain separate.
380
+ export const searchNow = () => inWorkScope() ? clock() : performance.now();
381
+ export const budgetEnd = () => {
382
+ if (proxySearchState())
383
+ return Infinity;
384
+ if (!completeWorkProfile.enabled)
385
+ return (budgetUnitsEnd ?? Infinity) / fullRate;
386
+ const end = workLedger.endpoint();
387
+ return end === null ? Infinity : workToNumber(workDivide(end, workFromNumber(fullRate)));
388
+ };
389
+ // Hard-stop checkpoints must not turn a local search deadline into a whole-run stop.
390
+ export function checkWorkEndpoint(phase) {
391
+ if (completeWorkProfile.enabled) {
392
+ workLedger.check(phase);
393
+ return;
394
+ }
395
+ if (budgetUnitsEnd !== undefined && (admissionRefusedAt === budgetUnitsEnd || fullWork() > budgetUnitsEnd))
396
+ throw new BudgetExpired(phase);
397
+ }
398
+ // Pre-step admission for new native primitive counters. No credit is minted and
399
+ // no local deadline is promoted to whole-search cancellation.
400
+ export function checkWorkAdmission(units, phase) {
401
+ if (!Number.isFinite(units) || units < 0)
402
+ throw new RangeError('work charge must be finite and nonnegative');
403
+ if (completeWorkProfile.enabled) {
404
+ workLedger.checkAmount(workFromNumber(units), phase);
405
+ return;
406
+ }
407
+ if (budgetUnitsEnd !== undefined && (admissionRefusedAt === budgetUnitsEnd || fullWork() + units > budgetUnitsEnd)) {
408
+ admissionRefusedAt = budgetUnitsEnd;
409
+ throw new BudgetExpired(phase);
410
+ }
411
+ }
412
+ export function remainingWork() {
413
+ if (completeWorkProfile.enabled) {
414
+ const left = workLedger.available();
415
+ return left === null ? Infinity : workToNumber(left);
416
+ }
417
+ return budgetUnitsEnd === undefined ? Infinity : admissionRefusedAt === budgetUnitsEnd ? 0 : Math.max(0, budgetUnitsEnd - fullWork());
418
+ }
419
+ export function checkBudget(phase) {
420
+ if (completeWorkProfile.enabled) {
421
+ workLedger.check(phase);
422
+ return;
423
+ }
424
+ if (budgetUnitsEnd !== undefined && (admissionRefusedAt === budgetUnitsEnd || fullWork() > budgetUnitsEnd
425
+ || completeWorkProfile.enabled && clock() > withinDeadline(budgetEnd())))
426
+ throw new BudgetExpired(phase);
427
+ }
428
+ export function withBudget(units, f) {
429
+ if (completeWorkProfile.enabled) {
430
+ const grant = typeof units === 'number' ? workFromNumber(units) : units;
431
+ // Opening a real quota must not introduce a heuristic counted region.
432
+ if (proxySearchState())
433
+ return withTraceWorkScope(() => workLedger.withBudget(grant, () => {
434
+ checkBudget('entry');
435
+ const result = f();
436
+ checkBudget('completion');
437
+ return result;
438
+ }));
439
+ return counted(fullRate, () => workLedger.withBudget(grant, () => {
440
+ checkBudget('entry');
441
+ const result = f();
442
+ checkBudget('completion');
443
+ return result;
444
+ }), true);
445
+ }
446
+ if (typeof units !== 'number')
447
+ throw new Error('exact work budgets require the full-work profile');
448
+ if (!Number.isFinite(units) || units < 0)
449
+ throw new RangeError('work budget must be finite and nonnegative');
450
+ // Never silently interpret units using a legacy work.n/count-rate island.
451
+ if (rate && meter !== fullWork)
452
+ throw new Error('work budget requires the outer full-work clock');
453
+ return counted(fullRate, () => {
454
+ checkWorkEndpoint('inherited admission');
455
+ const previous = budgetUnitsEnd, previousRefused = admissionRefusedAt;
456
+ budgetUnitsEnd = Math.min(previous ?? Infinity, workCap, fullWork() + units);
457
+ try {
458
+ return withWork(budgetUnitsEnd, () => withDeadline(budgetEnd(), () => {
459
+ checkBudget('entry');
460
+ const result = f();
461
+ // The final checker is inside the allowance, not free completion work.
462
+ checkBudget('completion');
463
+ return result;
464
+ }));
465
+ }
466
+ finally {
467
+ // A refusal at a shared endpoint remains visible after an inner scope;
468
+ // a genuinely smaller child allowance cannot poison a larger parent.
469
+ admissionRefusedAt = admissionRefusedAt === budgetUnitsEnd && previous === budgetUnitsEnd ? previous : previousRefused;
470
+ budgetUnitsEnd = previous;
471
+ }
472
+ }, true);
473
+ }
332
474
  // A goal's own budget where its caller gives none, outside a counted search: the cost model's work, groundRate units a
333
475
  // millisecond of the budget (below fullRate: the queries of 10 s or more did 163 to 271 units a ms at their median, by
334
476
  // group of the run above, so a long goal's budget takes about the wall time it had), so a goal left unknown is left so
335
477
  // on any machine; a deadline it is grown within stays.
336
478
  const groundRate = 180;
337
479
  let workCap = Infinity;
338
- export const withWork = (cap, f) => { const outer = workCap; workCap = Math.min(outer, cap); try {
339
- return f();
480
+ export const withWork = (cap, f) => {
481
+ if (completeWorkProfile.enabled) {
482
+ if (cap === Infinity)
483
+ return f();
484
+ return workLedger.withEndpoint('work-cap', typeof cap === 'number' ? workFromNumber(cap) : cap, f);
485
+ }
486
+ if (typeof cap !== 'number')
487
+ throw new Error('exact work caps require the full-work profile');
488
+ const outer = workCap;
489
+ workCap = Math.min(outer, cap);
490
+ try {
491
+ return f();
492
+ }
493
+ finally {
494
+ workCap = outer;
495
+ }
496
+ };
497
+ // Internal search caps are proxy state only; explicit withWork remains native.
498
+ const searchWorkCap = () => proxySearchState()?.workCap ?? workCap;
499
+ export function withSearchWork(cap, f) {
500
+ const proxy = proxySearchState();
501
+ if (!proxy)
502
+ return withWork(cap, f);
503
+ const outer = proxy.workCap;
504
+ proxy.workCap = Math.min(outer, cap);
505
+ try {
506
+ return f();
507
+ }
508
+ finally {
509
+ proxy.workCap = outer;
510
+ }
340
511
  }
341
- finally {
342
- workCap = outer;
343
- } };
344
512
  // Past a budget's end on the clock, or past the work a goal's own budget allows.
345
513
  // A wall-clock end beside the clock's (withWall: the search's own end, core/dsl.ts): work the counted clock doesn't count
346
514
  // (the EPR path's propositional search, a node's propagation, building a large goal's rows) stops there too, and past it
347
515
  // every goal is left unknown, whatever its own budget. Untrusted: it only stops a search.
348
516
  let wallEnd = Infinity;
349
- export const pastWall = () => wallEnd !== Infinity && performance.now() > wallEnd;
350
- export function withWall(end, f) {
517
+ // Capture the producer's clock domain before nested counted() changes it.
518
+ export const wallDeadline = (end, domain) => ({ end, domain: domain ?? (inWorkScope() || proxySearchState()?.rate ? 'counted' : 'real') });
519
+ // A legacy counted clock is not an opt-in work-only cancellation policy.
520
+ // Preserve its inherited real wall; only explicit work scopes/profiles elide it.
521
+ const workOnlyWall = () => inBudget() || stepWorkProfile.enabled;
522
+ export const pastWall = () => {
523
+ checkWorkEndpoint('prover boundary');
524
+ const proxy = proxySearchState();
525
+ if (proxy)
526
+ return clock() > withinDeadline(Infinity) || (!workOnlyWall() && proxy.wallEnd !== Infinity && performance.now() > proxy.wallEnd);
527
+ return (inWorkScope() && clock() > withinDeadline(budgetEnd()))
528
+ || (!workOnlyWall() && wallEnd !== Infinity && performance.now() > wallEnd);
529
+ };
530
+ export function withWall(limit, f) {
531
+ const proxy = proxySearchState();
532
+ // Untagged legacy endpoints retain their old policy. Search producers tag
533
+ // their domain explicitly, so counted milliseconds never become real time.
534
+ const { end, domain } = typeof limit === 'number' ? wallDeadline(limit, workOnlyWall() || proxy?.rate ? 'counted' : 'real') : limit;
535
+ if (domain === 'counted')
536
+ return withDeadline(Math.min(budgetEnd(), end), f);
537
+ if (workOnlyWall())
538
+ return f();
539
+ if (proxy) {
540
+ const outer = proxy.wallEnd;
541
+ proxy.wallEnd = Math.min(outer, end);
542
+ try {
543
+ return f();
544
+ }
545
+ finally {
546
+ proxy.wallEnd = outer;
547
+ }
548
+ }
351
549
  const outer = wallEnd;
352
550
  wallEnd = Math.min(outer, end);
353
551
  try {
@@ -359,12 +557,46 @@ export function withWall(end, f) {
359
557
  }
360
558
  // Past the wall or the deadline in force: a goal grown now is left unknown at once.
361
559
  const ranOut = () => pastWall() || withinDeadline(Infinity) <= clock();
362
- // (the wall's end in force, Infinity where none: a search inside that stops itself there)
363
- export const wallAt = () => wallEnd;
364
- export const late = (until) => clock() > until || (workCap !== Infinity && fullWork() > workCap) || pastWall();
560
+ // Active-clock endpoint; inherited real walls are checked separately by pastWall.
561
+ export const wallAt = () => {
562
+ const proxy = proxySearchState();
563
+ if (proxy)
564
+ return workOnlyWall() || proxy.rate ? withinDeadline(Infinity) : proxy.wallEnd;
565
+ return inWorkScope() ? withinDeadline(budgetEnd()) : wallEnd;
566
+ };
567
+ export const late = (until) => {
568
+ checkWorkEndpoint('prover poll');
569
+ const proxy = proxySearchState();
570
+ if (proxy)
571
+ return clock() > until || (proxy.workCap !== Infinity && searchWork() > proxy.workCap) || pastWall();
572
+ return clock() > until || (workCap !== Infinity && fullWork() > workCap) || pastWall();
573
+ };
365
574
  // A budget's end, within the deadline (a translation's own bound, core/cyclic.ts's, kept by the export's GDP_CERT_MS).
366
- export const withinDeadline = (until) => Math.min(until, deadline - eprTimeSince(deadlineEpr));
575
+ export const withinDeadline = (until) => {
576
+ const proxy = proxySearchState();
577
+ if (proxy)
578
+ return Math.min(until, proxy.deadline - eprTimeSince(proxy.deadlineEpr));
579
+ return completeWorkProfile.enabled ? Math.min(until, budgetEnd()) : Math.min(until, deadline - eprTimeSince(deadlineEpr));
580
+ };
367
581
  export function withDeadline(until, f) {
582
+ const proxy = proxySearchState();
583
+ if (proxy) {
584
+ const outer = proxy.deadline, outerEpr = proxy.deadlineEpr;
585
+ proxy.deadline = withinDeadline(until);
586
+ proxy.deadlineEpr = eprMeter.n;
587
+ try {
588
+ return f();
589
+ }
590
+ finally {
591
+ proxy.deadline = outer;
592
+ proxy.deadlineEpr = outerEpr;
593
+ }
594
+ }
595
+ if (completeWorkProfile.enabled) {
596
+ if (until === Infinity)
597
+ return f();
598
+ return workLedger.withEndpoint('deadline', workMultiply(workFromNumber(until), workFromNumber(fullRate)), f);
599
+ }
368
600
  const outer = deadline, outerEpr = deadlineEpr;
369
601
  deadline = withinDeadline(until);
370
602
  deadlineEpr = eprMeter.n;
@@ -376,6 +608,9 @@ export function withDeadline(until, f) {
376
608
  deadlineEpr = outerEpr;
377
609
  }
378
610
  }
611
+ // Full-accounting closing snapshots keep absolute endpoints and the legacy
612
+ // clock anchors as data. This observer never rebases deadlines or resets fuel.
613
+ export const snapshotProofClock = () => ({ rate, deadline, deadlineEpr, budgetUnitsEnd, admissionRefusedAt, workCap, wallEnd });
379
614
  // `units: false`: the goal's own order, no units first (a caller after a model, not a proof: a run guided by the
380
615
  // prover's witnesses, say, whose models units would steer).
381
616
  export function grow(goal, path = new Map(), budget) {
@@ -383,8 +618,8 @@ export function grow(goal, path = new Map(), budget) {
383
618
  return { stuck: 'unknown', path, why: outOfBudget(goal, 'time', path.size) };
384
619
  if (!budget) {
385
620
  const ms = Math.max(20_000, 1_000 * goal.hyps.length);
386
- if (!rate)
387
- return withWork(fullWork() + groundRate * ms, () => grow(goal, path, { nodes: 0 }));
621
+ if (!searchRate())
622
+ return withSearchWork(searchWork() + groundRate * ms, () => grow(goal, path, { nodes: 0 }));
388
623
  budget = { nodes: 0, until: clock() + ms };
389
624
  }
390
625
  const end = withinDeadline(budget.until ?? Infinity);
@@ -403,8 +638,8 @@ export function grow(goal, path = new Map(), budget) {
403
638
  proveDump(goal);
404
639
  }
405
640
  if (proveTrace && !path.size && !budget.nodes) {
406
- const t = performance.now(), out = growRoot(goal, path, budget);
407
- console.error(`[grow] ${goal.name}: ${goal.hyps.length} hyps, ${budget.nodes} nodes, ${Math.round(performance.now() - t)} ms, ${'tree' in out ? 'proven' : `${out.stuck}${out.why ? ` (${out.why})` : ''}`}`);
641
+ const t = traceNow(), out = growRoot(goal, path, budget);
642
+ console.error(`[grow] ${goal.name}: ${goal.hyps.length} hyps, ${budget.nodes} nodes, ${Math.round(traceNow() - t)} ms, ${'tree' in out ? 'proven' : `${out.stuck}${out.why ? ` (${out.why})` : ''}`}`);
408
643
  return out;
409
644
  }
410
645
  // (a root goal grown before within `withTrees`: its tree again; a tree is the kernel's to check wherever it goes)
@@ -446,11 +681,11 @@ export function withTrees(f) {
446
681
  // its wall time and counted work, its outcome, and how many queries it is inside.
447
682
  export const queryHook = { depth: 0 };
448
683
  export function logged(kind, goal, f) {
449
- const t0 = performance.now(), w0 = work.n;
684
+ const t0 = traceNow(), w0 = work.n;
450
685
  queryHook.depth++;
451
686
  try {
452
687
  const out = f();
453
- queryHook.on?.({ kind, goal, ms: performance.now() - t0, work: work.n - w0, out, depth: queryHook.depth - 1 });
688
+ queryHook.on?.({ kind, goal, ms: traceNow() - t0, work: work.n - w0, out, depth: queryHook.depth - 1 });
454
689
  return out;
455
690
  }
456
691
  finally {
@@ -465,9 +700,9 @@ function growKept(goal, path, budget) {
465
700
  function growKept0(goal, path, budget) {
466
701
  if (!profile.on || path.size || budget.nodes)
467
702
  return growRoot(goal, path, budget);
468
- const t = performance.now(), s0 = profile.solves, m0 = profile.solveMs, r0 = profile.rowsMs, n0 = profile.nodes;
703
+ const t = traceNow(), s0 = profile.solves, m0 = profile.solveMs, r0 = profile.rowsMs, n0 = profile.nodes;
469
704
  const out = growRoot(goal, path, budget);
470
- profile.goals.push({ name: goal.name, ms: performance.now() - t, nodes: profile.nodes - n0, solves: profile.solves - s0, solveMs: profile.solveMs - m0, rowsMs: profile.rowsMs - r0, proven: 'tree' in out });
705
+ profile.goals.push({ name: goal.name, ms: traceNow() - t, nodes: profile.nodes - n0, solves: profile.solves - s0, solveMs: profile.solveMs - m0, rowsMs: profile.rowsMs - r0, proven: 'tree' in out });
471
706
  return out;
472
707
  }
473
708
  // The share of a root goal's budget the CDCL search gets (GDP_CDCL_SHARE; 0 turns it off), and the quick search's nodes
@@ -511,11 +746,11 @@ function eprFirst(goal, budget, whole = true, stop = () => pastWall() || pastEpr
511
746
  if (d.sat)
512
747
  return { stuck: 'sat', witness: d.witness, diagram: d.diagram, path: new Map(), why: 'a model' };
513
748
  const last = goal.hyps.length - 1, core = d.core.includes(last) ? d.core : [...d.core, last], part = { name: goal.name, hyps: core.map(i => goal.hyps[i]) };
514
- const now = clock(), end = withinDeadline(budget.until ?? Infinity), w = fullWork();
749
+ const now = clock(), end = withinDeadline(budget.until ?? Infinity), w = searchWork();
515
750
  eprScope.busy = true;
516
751
  try {
517
752
  const share = whole ? 0.5 : 1;
518
- const out = withWork(workCap === Infinity ? Infinity : w + share * (workCap - w), () => grow(part, new Map(), { nodes: 0, until: end === Infinity ? end : now + share * (end - now) }));
753
+ const out = withSearchWork(searchWorkCap() === Infinity ? Infinity : w + share * (searchWorkCap() - w), () => grow(part, new Map(), { nodes: 0, until: end === Infinity ? end : now + share * (end - now) }));
519
754
  if (!('tree' in out)) {
520
755
  eprLast.refuted = true;
521
756
  return undefined;
@@ -604,8 +839,8 @@ export const wideFor = (goal) => !wideBusy && goal.hyps.length >= wideAt && term
604
839
  // (`keep`: a part's tree kept as the part's, with the part and its hypotheses' indices in the whole as its core, not
605
840
  // widened: settle's, whose final proof is made over the instances its proofs read)
606
841
  export function growWide(goal, budget, ask = (g, until) => grow(g, new Map(), { nodes: 0, until }), keep = false) {
607
- const hyps = goal.hyps, last = hyps.length - 1, broken = brokenOf(goal), now = clock(), w = fullWork();
608
- const end = withinDeadline(budget.until ?? Infinity), span = wideShare * (end - now), room = wideShare * (workCap - w), until = now + span;
842
+ const hyps = goal.hyps, last = hyps.length - 1, broken = brokenOf(goal), now = clock(), w = searchWork();
843
+ const end = withinDeadline(budget.until ?? Infinity), span = wideShare * (end - now), room = wideShare * (searchWorkCap() - w), until = now + span;
609
844
  const part = new Set([last]), near = new Set(cellsIn(hyps[last])), cells = new Map();
610
845
  const cellsAt = (i) => { let c = cells.get(i); if (!c)
611
846
  cells.set(i, (c = cellsIn(hyps[i]))); return c; };
@@ -619,24 +854,24 @@ export function growWide(goal, budget, ask = (g, until) => grow(g, new Map(), {
619
854
  // (a part's own budget: what the whole's search spends on as many nodes, four times over (a node of the part reads
620
855
  // that much less), at least a sixteenth of the share: a part that a small budget doesn't settle leaves the goal)
621
856
  const ids = [...part].sort((a, b) => a - b), g = { name: goal.name, hyps: ids.map(i => hyps[i]) }, f = Math.max(1 / 16, Math.min(1, 4 * part.size / hyps.length));
622
- const t0 = performance.now(), at = clock();
857
+ const t0 = traceNow(), at = clock();
623
858
  wideScope.judge = w => !broken(w, ids, true).length;
624
859
  let out;
625
860
  try {
626
- out = withWork(Math.min(w + room, fullWork() + f * room), () => ask(g, Math.min(until, at + f * span)));
861
+ out = withSearchWork(Math.min(w + room, searchWork() + f * room), () => ask(g, Math.min(until, at + f * span)));
627
862
  }
628
863
  finally {
629
864
  wideScope.judge = undefined;
630
865
  }
631
866
  wideHook.on?.(g, out);
632
867
  if (wideTrace)
633
- console.error(`[wide] ${goal.name.slice(0, 40)}: part ${g.hyps.length} of ${hyps.length}, ${'tree' in out ? 'tree' : out.stuck} in ${Math.round(performance.now() - t0)} ms${'tree' in out ? '' : ` ${out.why?.slice(0, 50) ?? ''}`}`);
868
+ console.error(`[wide] ${goal.name.slice(0, 40)}: part ${g.hyps.length} of ${hyps.length}, ${'tree' in out ? 'tree' : out.stuck} in ${Math.round(traceNow() - t0)} ms${'tree' in out ? '' : ` ${out.why?.slice(0, 50) ?? ''}`}`);
634
869
  if ('tree' in out && keep) {
635
870
  wideStats.trees++;
636
871
  return { tree: out.tree, nodes: out.nodes, part: g, core: ids };
637
872
  }
638
873
  if ('tree' in out) {
639
- const tree = withWork(w + room, () => withDeadline(until, () => widen(g, goal, out.tree)));
874
+ const tree = withSearchWork(w + room, () => withDeadline(until, () => widen(g, goal, out.tree)));
640
875
  if (tree)
641
876
  wideStats.trees++;
642
877
  return tree && { tree, nodes: out.nodes };
@@ -720,8 +955,8 @@ function growRoot(goal, path, budget) {
720
955
  }
721
956
  if (root) {
722
957
  if (cdcl) {
723
- const now = clock(), end = withinDeadline(budget.until ?? Infinity), w = fullWork();
724
- const out = withWork(workCap === Infinity ? Infinity : w + cdclShare * (workCap - w), () => growCdcl(goal, path, { nodes: 0, until: end === Infinity ? end : now + cdclShare * (end - now) }));
958
+ const now = clock(), end = withinDeadline(budget.until ?? Infinity), w = searchWork();
959
+ const out = withSearchWork(searchWorkCap() === Infinity ? Infinity : w + cdclShare * (searchWorkCap() - w), () => growCdcl(goal, path, { nodes: 0, until: end === Infinity ? end : now + cdclShare * (end - now) }));
725
960
  // (with `realModels.on`, a model whose products don't multiply out is no model: the CDCL search reads a product as
726
961
  // a name of its own, where the plain search below multiplies rows; a goal whose products only its cases bring,
727
962
  // core/nonterm.ts's x' := x·y)
@@ -755,9 +990,14 @@ function growPlain(goal, path, budget) {
755
990
  const full = timed(() => rowsAt(goal, path), ms => { profile.rowsMs += ms; });
756
991
  work.n += 1 + full.length;
757
992
  costs.plainNodes++;
758
- costs.plainRows += full.length;
993
+ if (!completeWorkProfile.enabled)
994
+ costs.plainRows += full.length;
759
995
  const columns = [...path.values()].some(a => Object.keys(a.lin).some(key => key.startsWith('⟦')));
760
- const idx = full.flatMap((r, i) => (columns || !Object.keys(r.lin).some(key => key.startsWith('⟦')) ? [i] : []));
996
+ const idx = full.flatMap((r, i) => {
997
+ if (completeWorkProfile.enabled)
998
+ startWork('plainRows', 1, 'plain row processing');
999
+ return columns || !Object.keys(r.lin).some(key => key.startsWith('⟦')) ? [i] : [];
1000
+ });
761
1001
  const rows = idx.map(i => full[i]), at = (i) => (i < rows.length ? idx[i] : full.length + i - rows.length);
762
1002
  const leafOf = (steps0, products0, squares0) => {
763
1003
  const { steps, products, squares } = products0 || squares0 ? trimmed(rows.length, steps0, products0 ?? [], squares0 ?? []) : { steps: steps0, products: undefined, squares: undefined };
@@ -1069,6 +1309,18 @@ export function rowsAt(goal, path) {
1069
1309
  }
1070
1310
  return rows;
1071
1311
  }
1312
+ // Untrusted capture may reuse an existing proposal without forcing a cache
1313
+ // miss to materialize another table. Same lookup as rowsAt; no cache mutation,
1314
+ // metering, checking, or authority to accept a certificate.
1315
+ export function cachedRowsAt(goal, path) {
1316
+ const byPath = rowsSeen.get(goal);
1317
+ if (!byPath)
1318
+ return undefined;
1319
+ let id = '';
1320
+ for (const [key, a] of path)
1321
+ id += `${a.holds ? '+' : '-'}${key}|`;
1322
+ return byPath.get(id);
1323
+ }
1072
1324
  function lift(goal, tree, from, to) {
1073
1325
  const own = to.size; // the decision's row: the last of `from`'s path rows, below every later split's
1074
1326
  const reads = (t) => ('leaf' in t ? t.leaf.some(st => st.kind === 'input' && st.index === own) || (t.products ?? []).some(([i, j]) => i === own || j === own) : reads(t.yes) || reads(t.no));
@@ -1201,9 +1453,10 @@ const nearSeen = new WeakMap();
1201
1453
  // (the names a term reads, its shared parts walked once: a witness read at each of its uses is one object)
1202
1454
  const namesOf = (t) => {
1203
1455
  const out = new Set();
1204
- walkOnce(t, o => { costs.goalNodes++; for (const [key, v] of Object.entries(o))
1456
+ walkOnce(t, o => { if (!completeWorkProfile.enabled)
1457
+ costs.goalNodes++; for (const [key, v] of Object.entries(o))
1205
1458
  if ((key === 'name' || key === 'map') && typeof v === 'string')
1206
- out.add(v); });
1459
+ out.add(v); }, completeWorkProfile.enabled ? () => startWork('goalNodes', 1, 'goal name traversal') : undefined);
1207
1460
  return out;
1208
1461
  };
1209
1462
  export function nearOf(goal) {
@@ -1230,9 +1483,12 @@ function unitsOf(goal) {
1230
1483
  // Forced by the root's rows without a solver: a row the atom is (or is the negation of), or the bounds the rows give
1231
1484
  // single variables (x <= c, x >= c) deciding it whichever way its variables go.
1232
1485
  const root = new Map(), rows = leafConstraints(goal, root), seen = new Set(), given = new Set();
1233
- costs.unitRows += rows.length;
1486
+ if (!completeWorkProfile.enabled)
1487
+ costs.unitRows += rows.length;
1234
1488
  const lo = new Map(), hi = new Map();
1235
1489
  for (const r of rows) {
1490
+ if (completeWorkProfile.enabled)
1491
+ startWork('unitRows', 1, 'unit row processing');
1236
1492
  given.add(canon(r.lin));
1237
1493
  const vs = Object.keys(r.lin).filter(key => key !== '1');
1238
1494
  if (vs.length !== 1)
@@ -1361,7 +1617,8 @@ function growFocused(goal, path, focus, budget, near = focus) {
1361
1617
  // (each node reads its whole leaf, counted as growPlain counts a node's rows)
1362
1618
  const leaf = leafConstraints(goal, path);
1363
1619
  work.n += 1 + leaf.length;
1364
- costs.plainRows += leaf.length;
1620
+ if (!completeWorkProfile.enabled)
1621
+ costs.plainRows += leaf.length;
1365
1622
  const verdict = solveNear(leaf, [...near, ...[...path.values()].slice(-1).map(a => a.lin)]);
1366
1623
  if (verdict.kind === 'refuted')
1367
1624
  return { tree: { leaf: verdict.steps }, nodes: budget.nodes };
@@ -1383,10 +1640,13 @@ function growFocused(goal, path, focus, budget, near = focus) {
1383
1640
  // read (a param every step reads) joins no rows: through it every step is near every other.
1384
1641
  function solveNear(rows, seeds) {
1385
1642
  const uses = new Map();
1386
- for (const r of rows)
1643
+ for (const r of rows) {
1644
+ if (completeWorkProfile.enabled)
1645
+ startWork('plainRows', 1, 'focused row processing');
1387
1646
  for (const key in r.lin)
1388
1647
  if (key !== '1')
1389
1648
  uses.set(key, (uses.get(key) ?? 0) + 1);
1649
+ }
1390
1650
  const hub = (key) => (uses.get(key) ?? 0) > Math.max(16, rows.length / 8);
1391
1651
  const reach = new Set(seeds.flatMap(l => Object.keys(l).filter(key => key !== '1')));
1392
1652
  for (let hop = 0; hop < 2; hop++) {
@@ -1769,8 +2029,8 @@ export function modelInstances(m, laws, inst, goal, w, most = 64, sorted = false
1769
2029
  export const modelShare = 3;
1770
2030
  // (GDP_MODELS_TRACE=1: each model round, its goal and the tuples a model adds, on stderr)
1771
2031
  const modelsTrace = !!env.GDP_MODELS_TRACE, modelFloor = Number(env.GDP_MODEL_FLOOR ?? 1_000);
1772
- const costNow = () => (rate ? clock() : fullWork() / groundRate);
1773
- const within = (ms, f) => (rate ? withDeadline(clock() + ms, f) : withWork(fullWork() + groundRate * ms, f));
2032
+ const costNow = () => (searchRate() ? clock() : searchWork() / groundRate);
2033
+ const within = (ms, f) => (searchRate() ? withDeadline(clock() + ms, f) : withSearchWork(searchWork() + groundRate * ms, f));
1774
2034
  export function withModels(m, laws, inst, goalOf, ask, modelOf, settled) {
1775
2035
  return withPatterns(m, laws, () => modelsLoop(m, laws, inst, goalOf, ask, modelOf, settled));
1776
2036
  }
@@ -2345,8 +2605,8 @@ export const decideLawHook = {};
2345
2605
  export function decideLaw(m, laws, i, rounds = modelRounds) {
2346
2606
  if (!decideLawHook.on)
2347
2607
  return decideLaw0(m, laws, i, rounds);
2348
- const t0 = performance.now(), out = decideLaw0(m, laws, i, rounds);
2349
- decideLawHook.on(m, laws, i, out, performance.now() - t0);
2608
+ const t0 = traceNow(), out = decideLaw0(m, laws, i, rounds);
2609
+ decideLawHook.on(m, laws, i, out, traceNow() - t0);
2350
2610
  return out;
2351
2611
  }
2352
2612
  // (why decideLaw last answered nothing: `refuted`, the abstraction refuted a goal whose core's proof didn't finish, a
@@ -2360,7 +2620,7 @@ function decideLaw0(m, laws, i, rounds) {
2360
2620
  return withPatterns(m, laws, () => {
2361
2621
  if (!eprScope.patterns)
2362
2622
  return undefined;
2363
- const out = settled(m, laws, i, rounds, false);
2623
+ const out = settled(m, laws, i, rounds, false, 'decision');
2364
2624
  // (a proof's support: the laws its goals' proofs read)
2365
2625
  return !out ? undefined : 'proofs' in out ? { proven: true, uses: [...new Set(Object.values(out.proofs).flatMap(p => [...p.uses.keys()]))] } : out.stuck === 'sat' ? { proven: false, goal: out.goal, stuck: 'sat', witness: out.witness, ...(out.diagram ? { diagram: out.diagram } : {}) } : undefined;
2366
2626
  });
@@ -2368,21 +2628,59 @@ function decideLaw0(m, laws, i, rounds) {
2368
2628
  // (GDP_MEMO_CAP: how many machines' decisions are kept, 4 by default; the hits and misses counted for the engine's trace)
2369
2629
  const memoCap = Number(env.GDP_MEMO_CAP ?? 4);
2370
2630
  export const memoHits = { n: 0, miss: 0, setKey: '', setJson: '' };
2631
+ export const memoReuseStats = { hitChecks: 0, hitCheckFailures: 0, coldRetries: 0, proofRetries: 0, modelRetries: 0, seedRetries: 0, modelHits: 0, modelsIgnored: 0, discardedSeeds: 0, wholeRetries: 0, decisionHits: 0, lawHits: 0, setHits: 0 };
2371
2632
  export const machineKey = (m) => { const s = JSON.stringify(m); let h = 0; for (let i = 0; i < s.length; i++)
2372
2633
  h = (h * 31 + s.charCodeAt(i)) | 0; return `${s.length}:${h}`; };
2373
2634
  const memos = new Map(), machineText = new WeakMap(), lawText = new WeakMap();
2635
+ // Alpha hits are untrusted hints: non-exact proofs are checked locally; non-exact models go cold.
2374
2636
  // (texts up to a renaming of fresh names, x$12: a rule's machine and kinds' laws are made again with
2375
2637
  // fresh binders, so the same machine had another text each time and no decision was found again; GDP_MEMO_ALPHA=0 off)
2376
2638
  const alpha = env.GDP_MEMO_ALPHA !== '0';
2377
2639
  const alphaText = (s) => { if (!alpha)
2378
2640
  return s; const to = new Map(); return s.replace(/([A-Za-z_?]+)\$(\d+)/g, (w, p) => { let r = to.get(w); if (!r)
2379
2641
  to.set(w, (r = `${p}$_${to.size}`)); return r; }); };
2380
- const textOfLaw = (l) => { let t = lawText.get(l.holds); if (t === undefined)
2381
- lawText.set(l.holds, (t = alphaText(JSON.stringify([l.holds, l.forall ?? null, l.keys ?? null])))); return t; };
2642
+ const textsOfLaw = (l) => { let t = lawText.get(l); if (!t) {
2643
+ const exact = JSON.stringify([l.holds, l.forall ?? null, l.keys ?? null]);
2644
+ lawText.set(l, (t = { exact, text: alphaText(exact) }));
2645
+ } return t; };
2646
+ const textOfLaw = (l) => textsOfLaw(l).text;
2647
+ const textsOfMachine = (m) => { let t = machineText.get(m); if (!t) {
2648
+ const exact = JSON.stringify(m);
2649
+ machineText.set(m, (t = { exact, text: alphaText(exact) }));
2650
+ } return t; };
2651
+ // Exact query context belongs to each entry, not to a shared alpha-keyed machine slot.
2652
+ const memoContext = (m, laws) => ({ machine: textsOfMachine(m).exact, laws: new Map(laws.map(l => [l.name, textsOfLaw(l).exact])) });
2653
+ const memoAttempt = () => ({ cold: new Set(), reused: new Set(), fresh: new Map() });
2654
+ function exactMemoContext(context, m, laws) {
2655
+ return context.machine === textsOfMachine(m).exact && laws.every(l => context.laws.get(l.name) === textsOfLaw(l).exact);
2656
+ }
2657
+ function discardMemo(memo, name, attempt, reason = 'proof') {
2658
+ memo.proven.delete(name);
2659
+ memo.models.delete(name);
2660
+ if (!attempt.cold.has(name)) {
2661
+ attempt.cold.add(name);
2662
+ memoReuseStats.coldRetries++;
2663
+ memoReuseStats[`${reason}Retries`]++;
2664
+ }
2665
+ }
2666
+ function checkMemoLaw(m, laws, i, cached) {
2667
+ const proofs = {}, byName = new Map(laws.map(l => [l.name, l]));
2668
+ // Widen usually makes fresh leaves, but its grow fallback may return a cached tree.
2669
+ // New tree objects drop every goal-local WeakMap annotation before source extraction.
2670
+ const currentTree = (t) => 'leaf' in t ? { ...t } : { ...t, yes: currentTree(t.yes), no: currentTree(t.no) };
2671
+ for (const g of obligations(m, laws, { [laws[i].name]: cached.inst }, i)) {
2672
+ const p = cached.proofs[g.name], widened = p && widen(p.part, g, p.tree);
2673
+ const tree = widened && currentTree(widened);
2674
+ if (!tree || !check(g, tree))
2675
+ return undefined;
2676
+ // Read current row sources, never the cached support/tuple metadata.
2677
+ const src = sourcesOf(m, laws, cached.inst, g, usedHyps(g, tree));
2678
+ proofs[g.name] = { part: g, tree, uses: new Map((src ? [...src.keys()] : laws.map(l => l.name)).map(n => [n, textOfLaw(byName.get(n))])), ...(src ? { tuples: src } : {}) };
2679
+ }
2680
+ return { text: textOfLaw(laws[i]), context: memoContext(m, laws), inst: cached.inst, proofs };
2681
+ }
2382
2682
  function memoOf(m) {
2383
- let key = machineText.get(m);
2384
- if (key === undefined)
2385
- machineText.set(m, (key = alphaText(JSON.stringify(m))));
2683
+ const key = textsOfMachine(m).text;
2386
2684
  let memo = memos.get(key);
2387
2685
  if (!memo) {
2388
2686
  if (memos.size >= memoCap)
@@ -2394,24 +2692,56 @@ function memoOf(m) {
2394
2692
  const stands = (p, byName) => [...p.uses].every(([n, t]) => { const l = byName.get(n); return !!l && textOfLaw(l) === t; });
2395
2693
  // Law i settled, from what was kept where it still stands (a proof whose support is in the set, a model of a set holding
2396
2694
  // this one): else its goals settled again, those whose proofs stand kept.
2397
- function settled(m, laws, i, rounds, usual) {
2695
+ function settled(m, laws, i, rounds, usual, consumer = 'decision', attempt = memoAttempt()) {
2398
2696
  const law = laws[i], memo = memoOf(m), byName = new Map(laws.map(l => [l.name, l])), text = textOfLaw(law);
2399
- const was = memo.proven.get(law.name), prev = was?.text === text ? was : undefined;
2697
+ if (attempt.fresh.has(law.name))
2698
+ return attempt.fresh.get(law.name);
2699
+ const was = !attempt.cold.has(law.name) ? memo.proven.get(law.name) : undefined;
2700
+ let prev = was?.text === text ? was : undefined;
2701
+ const exact = prev && exactMemoContext(prev.context, m, laws);
2400
2702
  if (prev && Object.values(prev.proofs).every(p => stands(p, byName))) {
2401
- memoHits.n++;
2402
- return prev;
2703
+ let valid = exact ? prev : undefined;
2704
+ if (!exact) {
2705
+ memoReuseStats.hitChecks++;
2706
+ valid = checkMemoLaw(m, laws, i, prev);
2707
+ }
2708
+ if (valid) {
2709
+ memoHits.n++;
2710
+ memoReuseStats[`${consumer}Hits`]++;
2711
+ attempt.reused.add(law.name);
2712
+ return valid;
2713
+ }
2714
+ memoReuseStats.hitCheckFailures++;
2715
+ discardMemo(memo, law.name, attempt);
2716
+ prev = undefined;
2717
+ }
2718
+ else if (prev && !exact) {
2719
+ // A partial renamed proof is not a verdict: stale instances/kept goals must not end this attempt.
2720
+ memoReuseStats.discardedSeeds++;
2721
+ discardMemo(memo, law.name, attempt, 'seed');
2722
+ prev = undefined;
2403
2723
  }
2404
2724
  memoHits.miss++;
2405
- const mo = rounds === modelRounds ? memo.models.get(law.name) : undefined;
2406
- if (mo && (!strict(usual) || mo.strict) && mo.text === text && laws.every(l => mo.set.get(l.name) === textOfLaw(l)))
2407
- return mo.model;
2725
+ const mo = !attempt.cold.has(law.name) && rounds === modelRounds ? memo.models.get(law.name) : undefined;
2726
+ if (mo && (!strict(usual) || mo.strict) && mo.text === text && laws.every(l => mo.set.get(l.name) === textOfLaw(l))) {
2727
+ if (exactMemoContext(mo.context, m, laws)) {
2728
+ memoReuseStats.modelHits++;
2729
+ return mo.model;
2730
+ }
2731
+ // A renamed negative is only a hint. Do not let it bypass the one native cold attempt.
2732
+ memoReuseStats.modelsIgnored++;
2733
+ discardMemo(memo, law.name, attempt, 'model');
2734
+ prev = undefined;
2735
+ }
2408
2736
  const out = settle(m, laws, i, rounds, usual, prev);
2409
2737
  const cap = (x) => { if (x.size >= 4096)
2410
2738
  x.clear(); return x; };
2411
2739
  if (out && 'proofs' in out)
2412
2740
  cap(memo.proven).set(law.name, out);
2413
2741
  else if (out?.stuck === 'sat' && rounds === modelRounds)
2414
- cap(memo.models).set(law.name, { text, model: out, strict: strict(usual), set: new Map(laws.map(l => [l.name, textOfLaw(l)])) });
2742
+ cap(memo.models).set(law.name, { text, context: memoContext(m, laws), model: out, strict: strict(usual), set: new Map(laws.map(l => [l.name, textOfLaw(l)])) });
2743
+ if (attempt.cold.has(law.name))
2744
+ attempt.fresh.set(law.name, out);
2415
2745
  return out;
2416
2746
  }
2417
2747
  // The fast path's machines: no history, sums or "there exists" (their goals are other machines' or need witnesses).
@@ -2532,7 +2862,7 @@ function settle(m, laws, i, rounds, usual, prev) {
2532
2862
  break;
2533
2863
  }
2534
2864
  if (!more)
2535
- return { text: textOfLaw(law), inst, proofs };
2865
+ return { text: textOfLaw(law), context: memoContext(m, laws), inst, proofs };
2536
2866
  inst = more;
2537
2867
  }
2538
2868
  }
@@ -2559,39 +2889,51 @@ export function proveSetFast(m, laws) {
2559
2889
  if (!fastShape(m, laws))
2560
2890
  return someLaws(laws) && fastShape(m, laws.map(l => ({ name: l.name, holds: l.holds }))) ? proveSome(m, laws, { whole: proveSetFast }) : proveLaws(m, laws);
2561
2891
  return withPatterns(m, laws, () => pointed(laws, () => {
2562
- const at = [];
2563
- for (let i = 0; i < laws.length; i++) {
2564
- const out = settled(m, laws, i, modelRounds, true);
2565
- if (!('proofs' in out))
2566
- return { proven: false, nodes: 0, leaves: 0, checked: false, failed: { goal: out.goal, stuck: out.stuck, ...(out.witness ? { witness: out.witness } : {}), ...(out.why ? { why: out.why } : {}), ...(out.diagram ? { diagram: out.diagram } : {}) } };
2567
- at.push(out);
2568
- }
2569
- const instances = {}, trees = {}, byName = new Map(laws.map(l => [l.name, l]));
2570
- let nodes = 0, leaves = 0;
2571
- for (const [i, law] of laws.entries()) {
2572
- // (each law about keys at the tuples the proofs read; all of them where a proof's sources weren't read)
2573
- const s = at[i], ps = Object.values(s.proofs), all = ps.some(p => !p.tuples);
2574
- const inst = all ? s.inst : Object.fromEntries(Object.entries(s.inst).map(([n, ks]) => {
2575
- const l = byName.get(n), k = l ? widthOf(l) : 1;
2576
- return [n, !l ? ks : ks.filter((_, j) => ps.some(p => p.tuples.get(n)?.has(JSON.stringify(ks.slice(j - (j % k), j - (j % k) + k)))))];
2577
- }));
2578
- instances[law.name] = inst;
2579
- for (const g of obligations(m, laws, { [law.name]: inst }, i)) {
2580
- const p = s.proofs[g.name];
2581
- let tree = p && widen(p.part, g, p.tree);
2582
- if (!tree) {
2583
- const o = grow(g);
2584
- if (!('tree' in o))
2585
- return stuckAt(g, o, nodes, leaves);
2586
- tree = o.tree;
2587
- nodes += o.nodes;
2892
+ const attempt = memoAttempt();
2893
+ const run = () => {
2894
+ const at = [];
2895
+ for (let i = 0; i < laws.length; i++) {
2896
+ const out = settled(m, laws, i, modelRounds, true, 'set', attempt);
2897
+ if (!('proofs' in out))
2898
+ return { proven: false, nodes: 0, leaves: 0, checked: false, failed: { goal: out.goal, stuck: out.stuck, ...(out.witness ? { witness: out.witness } : {}), ...(out.why ? { why: out.why } : {}), ...(out.diagram ? { diagram: out.diagram } : {}) } };
2899
+ at.push(out);
2900
+ }
2901
+ const instances = {}, trees = {}, byName = new Map(laws.map(l => [l.name, l]));
2902
+ let nodes = 0, leaves = 0;
2903
+ for (const [i, law] of laws.entries()) {
2904
+ // (each law about keys at the tuples the proofs read; all of them where a proof's sources weren't read)
2905
+ const s = at[i], ps = Object.values(s.proofs), all = ps.some(p => !p.tuples);
2906
+ const inst = all ? s.inst : Object.fromEntries(Object.entries(s.inst).map(([n, ks]) => {
2907
+ const l = byName.get(n), k = l ? widthOf(l) : 1;
2908
+ return [n, !l ? ks : ks.filter((_, j) => ps.some(p => p.tuples.get(n)?.has(JSON.stringify(ks.slice(j - (j % k), j - (j % k) + k)))))];
2909
+ }));
2910
+ instances[law.name] = inst;
2911
+ for (const g of obligations(m, laws, { [law.name]: inst }, i)) {
2912
+ const p = s.proofs[g.name];
2913
+ let tree = p && widen(p.part, g, p.tree);
2914
+ if (!tree) {
2915
+ const o = grow(g);
2916
+ if (!('tree' in o))
2917
+ return stuckAt(g, o, nodes, leaves);
2918
+ tree = o.tree;
2919
+ nodes += o.nodes;
2920
+ }
2921
+ trees[g.name] = tree;
2922
+ leaves += countLeaves(tree);
2588
2923
  }
2589
- trees[g.name] = tree;
2590
- leaves += countLeaves(tree);
2591
2924
  }
2925
+ const proof = { instances, trees };
2926
+ return { proven: true, nodes, leaves, checked: checkLaws(m, laws, proof), proof };
2927
+ };
2928
+ const out = run(), retry = [...attempt.reused].filter(name => !attempt.cold.has(name));
2929
+ if ((!out.proven || !out.checked) && retry.length) {
2930
+ memoReuseStats.wholeRetries++;
2931
+ const memo = memoOf(m);
2932
+ for (const name of retry)
2933
+ discardMemo(memo, name, attempt);
2934
+ return run();
2592
2935
  }
2593
- const proof = { instances, trees };
2594
- return { proven: true, nodes, leaves, checked: checkLaws(m, laws, proof), proof };
2936
+ return out;
2595
2937
  }));
2596
2938
  }
2597
2939
  export function proveLaw(m, laws, i) {
@@ -2604,7 +2946,7 @@ export function proveLaw(m, laws, i) {
2604
2946
  // proof, which widens and checks; wo's "a leader has the voting quorum's votes" from its 40-law set, 0.45 s there
2605
2947
  // against 25 s to unknown here)
2606
2948
  return withPatterns(m, laws, () => {
2607
- const out = eprScope.patterns && fastShape(m, laws) ? settled(m, laws, i, modelRounds, false) : undefined;
2949
+ const out = eprScope.patterns && fastShape(m, laws) ? settled(m, laws, i, modelRounds, false, 'law') : undefined;
2608
2950
  if (out && 'proofs' in out)
2609
2951
  return { proven: true };
2610
2952
  if (out?.stuck === 'sat')
@@ -2631,7 +2973,7 @@ function proveOne(m, laws, i) {
2631
2973
  const memo = memoOf(m);
2632
2974
  if (memo.proven.size >= 4096)
2633
2975
  memo.proven.clear();
2634
- memo.proven.set(law.name, { text: textOfLaw(law), inst: at, proofs });
2976
+ memo.proven.set(law.name, { text: textOfLaw(law), context: memoContext(m, laws), inst: at, proofs });
2635
2977
  };
2636
2978
  const few = triggered(pm, laws, inst, i2 => obligations(m, laws, { [law.name]: i2 }, i), law.forall ? [`${law.forall}#`] : []);
2637
2979
  if (!sameInstances(few, inst)) {
@@ -2698,7 +3040,8 @@ export const withStrict = (f) => { const o = strictOn; strictOn = true; try {
2698
3040
  finally {
2699
3041
  strictOn = o;
2700
3042
  } };
2701
- // (by machine and by the law set's names: one machine is asked with many sets)
3043
+ // By immutable machine and ordered, exact law context, including all binding metadata.
3044
+ export const sortMemoStats = { hits: 0, misses: 0 };
2702
3045
  const sortsMemo = new WeakMap();
2703
3046
  const sortPlacesOn = env.GDP_SORT_PLACES !== '0';
2704
3047
  function sortsOf(m, laws) {
@@ -2839,13 +3182,16 @@ function instanceSortGuard(m, laws) {
2839
3182
  let byLaws = sortsMemo.get(m);
2840
3183
  if (!byLaws)
2841
3184
  sortsMemo.set(m, (byLaws = new Map()));
2842
- const lk = laws.map(l => l.name).join('\u0001');
3185
+ const lk = JSON.stringify(laws.map(l => [l.name, textsOfLaw(l).exact]));
2843
3186
  let s = byLaws.get(lk);
2844
3187
  if (!s) {
3188
+ sortMemoStats.misses++;
2845
3189
  if (byLaws.size >= 64)
2846
3190
  byLaws.clear();
2847
3191
  byLaws.set(lk, (s = sortsOf(m, laws)));
2848
3192
  }
3193
+ else
3194
+ sortMemoStats.hits++;
2849
3195
  const S = s;
2850
3196
  const keysOf = (n) => {
2851
3197
  if (n.startsWith('?')) {
@@ -2932,12 +3278,12 @@ function proveLawsAsGiven(m, laws, defer) {
2932
3278
  const modes = cyclicOn() || certOn(), hist = modes && m.history ? historyMachine(m) : undefined, mc = hist ? hist.machine : m;
2933
3279
  const why = modes ? (sumsWhy(m) ?? uncoveredWhy(mc, laws)) : undefined, cert = certOn() && !why;
2934
3280
  usualCheck.on = !cert && !defer;
2935
- const t0 = performance.now(), out = fast ?? (() => { try {
3281
+ const t0 = traceNow(), out = fast ?? (() => { try {
2936
3282
  return proveThinned(m, laws, { ...instances });
2937
3283
  }
2938
3284
  finally {
2939
3285
  usualCheck.on = true;
2940
- } })(), usualMs = performance.now() - t0;
3286
+ } })(), usualMs = traceNow() - t0;
2941
3287
  if (out.proof)
2942
3288
  usualProof.last = { m, laws, proof: out.proof };
2943
3289
  const inst = out.proof?.instances ?? instances;
@@ -3088,7 +3434,7 @@ export function stepLawInstances(m, laws) {
3088
3434
  function proveStepLawsAsGiven(m, laws, stepLaws, base, ready = () => { }) {
3089
3435
  if (!base.proof)
3090
3436
  return { proven: false, nodes: base.nodes, leaves: base.leaves, checked: false };
3091
- const t0 = performance.now();
3437
+ const t0 = traceNow();
3092
3438
  const plain = plainOf(m);
3093
3439
  // Each step law its own instances, from its own goal: the keys the step and the laws read, and its own (a k-step
3094
3440
  // law's later frames read keys no other step law has); where positions shift or a law is about several keys, the
@@ -3105,7 +3451,7 @@ function proveStepLawsAsGiven(m, laws, stepLaws, base, ready = () => { }) {
3105
3451
  const ownMs = {};
3106
3452
  for (const sl of stepLaws)
3107
3453
  for (const goal of stepLawObligations(m, laws, perStep[sl.name] ?? instances, sl)) {
3108
- const g0 = performance.now();
3454
+ const g0 = traceNow();
3109
3455
  const full = perStep[sl.name] ?? instances, few = triggered(plain, laws, full, inst => stepLawObligations(m, laws, inst, sl), [sl.forall, ...(sl.keys ?? [])].flatMap(k => (k ? [k] : [])));
3110
3456
  let out = sameInstances(few, full) ? grow(goal) : grow(stepLawObligations(m, laws, few, sl).find(g => g.name === goal.name) ?? goal);
3111
3457
  if ('tree' in out && !sameInstances(few, full))
@@ -3139,12 +3485,12 @@ function proveStepLawsAsGiven(m, laws, stepLaws, base, ready = () => { }) {
3139
3485
  trees[goal.name] = out.tree;
3140
3486
  nodes += out.nodes;
3141
3487
  leaves += countLeaves(out.tree);
3142
- ownMs[sl.name] = (ownMs[sl.name] ?? 0) + performance.now() - g0;
3488
+ ownMs[sl.name] = (ownMs[sl.name] ?? 0) + traceNow() - g0;
3143
3489
  }
3144
3490
  // (every step law proven: the laws' certificate, or their check, as proveLaws makes it; its time not the step laws')
3145
- const r0 = performance.now();
3491
+ const r0 = traceNow();
3146
3492
  ready();
3147
- const usual0 = t0 + performance.now() - r0;
3493
+ const usual0 = t0 + traceNow() - r0;
3148
3494
  const proof = { laws: base.proof, instances, ...(Object.keys(perStep).length ? { perStep } : {}), trees };
3149
3495
  // Step laws of a machine the cyclic instances cover (one step, or several over no map) are translated with the laws
3150
3496
  // (core/cyclic.ts); the rest are counted as no instance's.
@@ -3164,7 +3510,7 @@ function proveStepLawsAsGiven(m, laws, stepLaws, base, ready = () => { }) {
3164
3510
  if (!why && one.length && out.checked) {
3165
3511
  const all = one.map(sl => { const inst = perStep[sl.name] ?? instances, goal = stepLawObligations(m, laws, inst, sl)[0]; return { sl, inst, goal, tree: trees[goal.name] }; });
3166
3512
  const translatedOf = (steps) => (st) => translatedProof(() => JSON.stringify(['steps', plain, laws, base.proof.instances, steps.map(x => [x.sl, x.inst])]), reused => timedKind('instance', 0, () => machineNodes(plain, laws, base.proof.instances, { trees: base.proof.trees, steps, lawsMade: reused }, st)), st, () => JSON.stringify(['machine', plain, laws, base.proof.instances]));
3167
- const usualMs = performance.now() - usual0;
3513
+ const usualMs = traceNow() - usual0;
3168
3514
  if (cyclicOn())
3169
3515
  crossCyclic('step law', m.name, true, undefined, usualMs, translatedOf(all));
3170
3516
  // (where the step laws' proof together isn't made, each step law's alone: one the translation misses leaves the
@@ -3195,7 +3541,7 @@ function proveStepLawsAsGiven(m, laws, stepLaws, base, ready = () => { }) {
3195
3541
  const b = machineNodes(plain, laws, base.proof.instances);
3196
3542
  return proveCyclic(b.facts, [...b.specs, ...searchedStepNodes(plain, laws, rest.map(sl => ({ law: sl, instances: perStep[sl.name] ?? instances })), b.facts, b.specs)]);
3197
3543
  };
3198
- const c = certCyclic('step law', m.name, undefined, searchedSteps, performance.now() - usual0);
3544
+ const c = certCyclic('step law', m.name, undefined, searchedSteps, traceNow() - usual0);
3199
3545
  for (const sl of c.checked ? [] : rest)
3200
3546
  miss(sl, `${restWhy(sl)}: ${c.why}`);
3201
3547
  }
@@ -3207,7 +3553,7 @@ function proveStepLawsAsGiven(m, laws, stepLaws, base, ready = () => { }) {
3207
3553
  // Progress (kernel.ts's progressObligations): the laws proven first, then each goal, the every-key laws assumed at every
3208
3554
  // key the goals read a map at.
3209
3555
  export function proveProgress(m, laws, p) {
3210
- const t0 = performance.now(), base = proveLaws(m, laws);
3556
+ const t0 = traceNow(), base = proveLaws(m, laws);
3211
3557
  if (!base.proven || !base.checked)
3212
3558
  return { proven: false, nodes: base.nodes, leaves: base.leaves, ...(base.failed ? { failed: base.failed } : {}), checked: false };
3213
3559
  const ls = base.laws ?? laws;
@@ -3250,7 +3596,7 @@ export function proveProgress(m, laws, p) {
3250
3596
  });
3251
3597
  return found?.out ?? last;
3252
3598
  };
3253
- const c = certCyclic('progress', m.name, translated, certSearch() ? allowed : undefined, performance.now() - t0);
3599
+ const c = certCyclic('progress', m.name, translated, certSearch() ? allowed : undefined, traceNow() - t0);
3254
3600
  if (!c.checked) {
3255
3601
  const why = `a request allowed: ${c.why}`;
3256
3602
  uncovered('progress', m.name, why);