gdp-wired 0.48.0 → 0.50.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 (361) hide show
  1. package/README.md +6 -2
  2. package/dist/core/bmc.js +10 -7
  3. package/dist/core/candidate-seeds.d.ts +25 -0
  4. package/dist/core/candidate-seeds.js +90 -0
  5. package/dist/core/check.js +7 -2
  6. package/dist/core/cli.js +3 -0
  7. package/dist/core/count-attempt-work.d.ts +29 -0
  8. package/dist/core/count-attempt-work.js +96 -0
  9. package/dist/core/count-boolean-partition.d.ts +5 -0
  10. package/dist/core/count-boolean-partition.js +47 -0
  11. package/dist/core/count-bounded-quotient.d.ts +2 -0
  12. package/dist/core/count-bounded-quotient.js +13 -0
  13. package/dist/core/count-case-compose.d.ts +20 -0
  14. package/dist/core/count-case-compose.js +289 -0
  15. package/dist/core/count-cases.js +3 -2
  16. package/dist/core/count-cert-rename.d.ts +10 -0
  17. package/dist/core/count-cert-rename.js +69 -0
  18. package/dist/core/count-cert-transport.d.ts +10 -2
  19. package/dist/core/count-cert-transport.js +60 -9
  20. package/dist/core/count-certificate-minimize.d.ts +57 -0
  21. package/dist/core/count-certificate-minimize.js +263 -0
  22. package/dist/core/count-closed-family.d.ts +32 -0
  23. package/dist/core/count-closed-family.js +143 -0
  24. package/dist/core/count-closing-budget.d.ts +10 -0
  25. package/dist/core/count-closing-budget.js +49 -0
  26. package/dist/core/count-closing-needs.d.ts +5 -0
  27. package/dist/core/count-closing-needs.js +9 -0
  28. package/dist/core/count-component-budget.d.ts +5 -0
  29. package/dist/core/count-component-budget.js +9 -0
  30. package/dist/core/count-copy-shape.d.ts +11 -0
  31. package/dist/core/count-copy-shape.js +40 -0
  32. package/dist/core/count-disjoint-funding.d.ts +75 -0
  33. package/dist/core/count-disjoint-funding.js +284 -0
  34. package/dist/core/count-emitter-frame-pool.d.ts +23 -0
  35. package/dist/core/count-emitter-frame-pool.js +87 -0
  36. package/dist/core/count-final-step.d.ts +5 -0
  37. package/dist/core/count-final-step.js +20 -0
  38. package/dist/core/count-fixed-frame.d.ts +4 -0
  39. package/dist/core/count-fixed-frame.js +30 -0
  40. package/dist/core/count-frames.d.ts +25 -0
  41. package/dist/core/count-frames.js +118 -0
  42. package/dist/core/count-frozen-guard.d.ts +2 -0
  43. package/dist/core/count-frozen-guard.js +31 -0
  44. package/dist/core/count-generation-phase.d.ts +7 -0
  45. package/dist/core/count-generation-phase.js +33 -0
  46. package/dist/core/count-guard-composition.d.ts +12 -0
  47. package/dist/core/count-guard-composition.js +48 -0
  48. package/dist/core/count-guard-context.d.ts +11 -0
  49. package/dist/core/count-guard-context.js +50 -0
  50. package/dist/core/count-guard-facts.d.ts +50 -0
  51. package/dist/core/count-guard-facts.js +97 -0
  52. package/dist/core/count-guard-proposals.d.ts +7 -0
  53. package/dist/core/count-guard-proposals.js +106 -0
  54. package/dist/core/count-guard-shape.d.ts +18 -0
  55. package/dist/core/count-guard-shape.js +100 -0
  56. package/dist/core/count-guard-tree.d.ts +17 -0
  57. package/dist/core/count-guard-tree.js +125 -0
  58. package/dist/core/count-leader-facts.d.ts +10 -0
  59. package/dist/core/count-leader-facts.js +52 -0
  60. package/dist/core/count-leader.d.ts +10 -0
  61. package/dist/core/count-leader.js +331 -0
  62. package/dist/core/count-lemma-transport.d.ts +8 -0
  63. package/dist/core/count-lemma-transport.js +47 -0
  64. package/dist/core/count-lifted-budget.d.ts +54 -0
  65. package/dist/core/count-lifted-budget.js +97 -0
  66. package/dist/core/count-lifted-copy.d.ts +3 -0
  67. package/dist/core/count-lifted-copy.js +166 -0
  68. package/dist/core/count-lifted-increment.d.ts +3 -0
  69. package/dist/core/count-lifted-increment.js +146 -0
  70. package/dist/core/count-lifted-load.d.ts +5 -0
  71. package/dist/core/count-lifted-load.js +179 -0
  72. package/dist/core/count-lifted-prerequisite.d.ts +14 -0
  73. package/dist/core/count-lifted-prerequisite.js +53 -0
  74. package/dist/core/count-lifted-replacement.d.ts +3 -0
  75. package/dist/core/count-lifted-replacement.js +540 -0
  76. package/dist/core/count-lifted-shape.d.ts +63 -0
  77. package/dist/core/count-lifted-shape.js +115 -0
  78. package/dist/core/count-lifted-strategy.d.ts +7 -0
  79. package/dist/core/count-lifted-strategy.js +226 -0
  80. package/dist/core/count-lifted-transports.d.ts +32 -0
  81. package/dist/core/count-lifted-transports.js +293 -0
  82. package/dist/core/count-load-shape.d.ts +17 -0
  83. package/dist/core/count-load-shape.js +67 -0
  84. package/dist/core/count-minimal-view.d.ts +26 -0
  85. package/dist/core/count-minimal-view.js +46 -0
  86. package/dist/core/count-operation-observation.d.ts +9 -0
  87. package/dist/core/count-operation-observation.js +22 -0
  88. package/dist/core/count-operation-order.d.ts +5 -0
  89. package/dist/core/count-operation-order.js +4 -0
  90. package/dist/core/count-phase.d.ts +9 -0
  91. package/dist/core/count-phase.js +127 -0
  92. package/dist/core/count-premise-search.d.ts +9 -0
  93. package/dist/core/count-premise-search.js +41 -0
  94. package/dist/core/count-premise-view.d.ts +19 -0
  95. package/dist/core/count-premise-view.js +220 -0
  96. package/dist/core/count-prerequisite-components.d.ts +67 -0
  97. package/dist/core/count-prerequisite-components.js +239 -0
  98. package/dist/core/count-prerequisite-memory.d.ts +24 -0
  99. package/dist/core/count-prerequisite-memory.js +37 -0
  100. package/dist/core/count-prerequisite-plan.d.ts +12 -0
  101. package/dist/core/count-prerequisite-plan.js +88 -0
  102. package/dist/core/count-primitive-budget.d.ts +1 -0
  103. package/dist/core/count-primitive-budget.js +8 -0
  104. package/dist/core/count-project-free.d.ts +3 -0
  105. package/dist/core/count-project-free.js +24 -0
  106. package/dist/core/count-project-witness.d.ts +4 -0
  107. package/dist/core/count-project-witness.js +48 -0
  108. package/dist/core/count-proof-rescope.d.ts +14 -0
  109. package/dist/core/count-proof-rescope.js +71 -0
  110. package/dist/core/count-proof-scope.d.ts +68 -0
  111. package/dist/core/count-proof-scope.js +333 -0
  112. package/dist/core/count-prune-owned-root.d.ts +5 -0
  113. package/dist/core/count-prune-owned-root.js +27 -0
  114. package/dist/core/count-query-context.d.ts +3 -0
  115. package/dist/core/count-query-context.js +7 -0
  116. package/dist/core/count-query.d.ts +15 -0
  117. package/dist/core/count-query.js +59 -0
  118. package/dist/core/count-quorum-leaf.d.ts +9 -0
  119. package/dist/core/count-quorum-leaf.js +38 -0
  120. package/dist/core/count-reachability-budget.d.ts +1 -0
  121. package/dist/core/count-reachability-budget.js +7 -0
  122. package/dist/core/count-reachability-reconcile.d.ts +11 -0
  123. package/dist/core/count-reachability-reconcile.js +19 -0
  124. package/dist/core/count-reachability.d.ts +50 -0
  125. package/dist/core/count-reachability.js +351 -0
  126. package/dist/core/count-rebase-path.d.ts +9 -0
  127. package/dist/core/count-rebase-path.js +68 -0
  128. package/dist/core/count-recipe-context.d.ts +45 -0
  129. package/dist/core/count-recipe-context.js +71 -0
  130. package/dist/core/count-recipe-controller.d.ts +115 -0
  131. package/dist/core/count-recipe-controller.js +417 -0
  132. package/dist/core/count-recipe-graph.d.ts +36 -0
  133. package/dist/core/count-recipe-graph.js +211 -0
  134. package/dist/core/count-recovery/conditional-check-cache.js +3 -2
  135. package/dist/core/count-recovery/conditional-cuts.js +5 -4
  136. package/dist/core/count-recovery/conditional-proof.d.ts +37 -3
  137. package/dist/core/count-recovery/conditional-proof.js +72 -30
  138. package/dist/core/count-recovery/derivability-closure.js +2 -1
  139. package/dist/core/count-recovery/guard-cases.js +2 -1
  140. package/dist/core/count-recovery/reframe-tree.d.ts +2 -0
  141. package/dist/core/count-recovery/reframe-tree.js +24 -0
  142. package/dist/core/count-recovery/replay-linear-skeleton.d.ts +2 -0
  143. package/dist/core/count-recovery/replay-linear-skeleton.js +28 -0
  144. package/dist/core/count-recovery/row-cases.js +2 -1
  145. package/dist/core/count-rejection-budget.d.ts +8 -0
  146. package/dist/core/count-rejection-budget.js +15 -0
  147. package/dist/core/count-replacement.d.ts +5 -0
  148. package/dist/core/count-replacement.js +129 -0
  149. package/dist/core/count-replay-diagnostic.d.ts +21 -0
  150. package/dist/core/count-replay-diagnostic.js +49 -0
  151. package/dist/core/count-replay-skeleton.d.ts +4 -0
  152. package/dist/core/count-replay-skeleton.js +28 -0
  153. package/dist/core/count-rescope-funding.d.ts +3 -0
  154. package/dist/core/count-rescope-funding.js +17 -0
  155. package/dist/core/count-restrictions.d.ts +11 -0
  156. package/dist/core/count-restrictions.js +31 -0
  157. package/dist/core/count-retry-budget.d.ts +67 -0
  158. package/dist/core/count-retry-budget.js +114 -0
  159. package/dist/core/count-retry-round.d.ts +24 -0
  160. package/dist/core/count-retry-round.js +44 -0
  161. package/dist/core/count-row-agreement.d.ts +35 -0
  162. package/dist/core/count-row-agreement.js +270 -0
  163. package/dist/core/count-row-aliases.d.ts +3 -0
  164. package/dist/core/count-row-aliases.js +59 -0
  165. package/dist/core/count-row-composition.d.ts +6 -0
  166. package/dist/core/count-row-composition.js +55 -0
  167. package/dist/core/count-row-copy-linear.d.ts +4 -0
  168. package/dist/core/count-row-copy-linear.js +83 -0
  169. package/dist/core/count-row-copy.d.ts +4 -0
  170. package/dist/core/count-row-copy.js +94 -0
  171. package/dist/core/count-row-policy.d.ts +3 -0
  172. package/dist/core/count-row-policy.js +56 -0
  173. package/dist/core/count-row-reindex.d.ts +11 -0
  174. package/dist/core/count-row-reindex.js +126 -0
  175. package/dist/core/count-row-support.d.ts +9 -0
  176. package/dist/core/count-row-support.js +42 -0
  177. package/dist/core/count-row-symmetry.d.ts +7 -0
  178. package/dist/core/count-row-symmetry.js +100 -0
  179. package/dist/core/count-scope-hyps.d.ts +2 -0
  180. package/dist/core/count-scope-hyps.js +163 -0
  181. package/dist/core/count-scope-row-reuse.d.ts +3 -0
  182. package/dist/core/count-scope-row-reuse.js +92 -0
  183. package/dist/core/count-search-allowance.d.ts +1 -0
  184. package/dist/core/count-search-allowance.js +17 -0
  185. package/dist/core/count-stabilize-tree.d.ts +9 -0
  186. package/dist/core/count-stabilize-tree.js +35 -0
  187. package/dist/core/count-stage-trace.d.ts +8 -0
  188. package/dist/core/count-stage-trace.js +45 -0
  189. package/dist/core/count-strategies.d.ts +16 -0
  190. package/dist/core/count-strategies.js +155 -0
  191. package/dist/core/count-strategy-premises.d.ts +5 -0
  192. package/dist/core/count-strategy-premises.js +14 -0
  193. package/dist/core/count-strategy.d.ts +41 -0
  194. package/dist/core/count-strategy.js +76 -0
  195. package/dist/core/count-support.d.ts +1 -0
  196. package/dist/core/count-support.js +26 -4
  197. package/dist/core/count-tier-budget.d.ts +14 -0
  198. package/dist/core/count-tier-budget.js +64 -0
  199. package/dist/core/count-unwritten-prefix.d.ts +24 -0
  200. package/dist/core/count-unwritten-prefix.js +97 -0
  201. package/dist/core/count-write-shape.d.ts +15 -0
  202. package/dist/core/count-write-shape.js +73 -0
  203. package/dist/core/counted-candidate-seeds.d.ts +12 -0
  204. package/dist/core/counted-candidate-seeds.js +31 -0
  205. package/dist/core/counts.d.ts +37 -13
  206. package/dist/core/counts.js +999 -129
  207. package/dist/core/cycles.js +5 -4
  208. package/dist/core/cyclic.js +11 -10
  209. package/dist/core/data.js +16 -15
  210. package/dist/core/dsl-deadline.d.ts +3 -0
  211. package/dist/core/dsl-deadline.js +27 -0
  212. package/dist/core/dsl.d.ts +32 -2
  213. package/dist/core/dsl.js +202 -64
  214. package/dist/core/evaluation-admission.d.ts +1 -0
  215. package/dist/core/evaluation-admission.js +3 -0
  216. package/dist/core/exists.d.ts +6 -1
  217. package/dist/core/exists.js +53 -10
  218. package/dist/core/field-laws.d.ts +3 -1
  219. package/dist/core/field-laws.js +159 -3
  220. package/dist/core/finite-houdini.d.ts +6 -0
  221. package/dist/core/finite-houdini.js +63 -21
  222. package/dist/core/finite-tiny.js +95 -67
  223. package/dist/core/fixtures/count-completion/paxos-decision.json +1 -0
  224. package/dist/core/fresh.js +5 -1
  225. package/dist/core/infer.js +49 -33
  226. package/dist/core/kind.js +2 -1
  227. package/dist/core/lemma-cuts.js +11 -10
  228. package/dist/core/lift-cli.d.ts +11 -0
  229. package/dist/core/lift-cli.js +113 -0
  230. package/dist/core/linear-admission.d.ts +14 -0
  231. package/dist/core/linear-admission.js +151 -0
  232. package/dist/core/machine.d.ts +5 -2
  233. package/dist/core/machine.js +105 -31
  234. package/dist/core/meter.d.ts +22 -0
  235. package/dist/core/meter.js +34 -0
  236. package/dist/core/nonterm.js +4 -3
  237. package/dist/core/proof-output.d.ts +53 -0
  238. package/dist/core/proof-output.js +38 -0
  239. package/dist/core/prover-row-budget.d.ts +3 -0
  240. package/dist/core/prover-row-budget.js +106 -0
  241. package/dist/core/quorum-laws.d.ts +21 -1
  242. package/dist/core/quorum-laws.js +80 -17
  243. package/dist/core/rationals.js +3 -2
  244. package/dist/core/rejection-discovery.d.ts +34 -0
  245. package/dist/core/rejection-discovery.js +36 -0
  246. package/dist/core/rejection-stage.d.ts +39 -0
  247. package/dist/core/rejection-stage.js +205 -0
  248. package/dist/core/request-quotient.d.ts +8 -0
  249. package/dist/core/request-quotient.js +299 -0
  250. package/dist/core/row-agreement-shape.d.ts +15 -0
  251. package/dist/core/row-agreement-shape.js +68 -0
  252. package/dist/core/runtime-wall.d.ts +2 -0
  253. package/dist/core/search-policy.d.ts +15 -0
  254. package/dist/core/search-policy.js +68 -0
  255. package/dist/core/solver.d.ts +1 -1
  256. package/dist/core/solver.js +40 -6
  257. package/dist/core/step-work.d.ts +12 -0
  258. package/dist/core/step-work.js +14 -0
  259. package/dist/core/strategy-premises.d.ts +8 -0
  260. package/dist/core/strategy-premises.js +64 -0
  261. package/dist/core/system.js +4 -3
  262. package/dist/core/table-admission.d.ts +1 -0
  263. package/dist/core/table-admission.js +3 -0
  264. package/dist/core/trace-clock.d.ts +3 -0
  265. package/dist/core/trace-clock.js +16 -0
  266. package/dist/core/transfer.js +3 -2
  267. package/dist/core/translate.js +16 -3
  268. package/dist/core/wall.d.ts +6 -1
  269. package/dist/core/wall.js +23 -9
  270. package/dist/core/watch.d.ts +1 -1
  271. package/dist/core/watch.js +13 -4
  272. package/dist/core/work-admission.d.ts +164 -0
  273. package/dist/core/work-admission.js +418 -0
  274. package/dist/core/work-amount.d.ts +21 -0
  275. package/dist/core/work-amount.js +80 -0
  276. package/dist/core/work-collections.d.ts +11 -0
  277. package/dist/core/work-collections.js +198 -0
  278. package/dist/core/work-kinds.d.ts +11 -0
  279. package/dist/core/work-kinds.js +9 -0
  280. package/dist/core/work-meter.d.ts +8 -0
  281. package/dist/core/work-meter.js +83 -0
  282. package/dist/core/work-observe.d.ts +12 -0
  283. package/dist/core/work-observe.js +39 -0
  284. package/dist/core/work-profile.d.ts +10 -0
  285. package/dist/core/work-profile.js +21 -0
  286. package/dist/core/work-refusal.d.ts +1 -0
  287. package/dist/core/work-refusal.js +6 -0
  288. package/dist/interchange/format.js +2 -0
  289. package/dist/kernel/cdcl.js +93 -40
  290. package/dist/kernel/epr.js +23 -8
  291. package/dist/kernel/function-instances.d.ts +45 -0
  292. package/dist/kernel/function-instances.js +460 -0
  293. package/dist/kernel/kernel.d.ts +47 -1
  294. package/dist/kernel/kernel.js +417 -68
  295. package/dist/kernel/prove.d.ts +61 -6
  296. package/dist/kernel/prove.js +625 -205
  297. package/dist/kernel/prover-rows.d.ts +1 -0
  298. package/dist/kernel/prover-rows.js +12 -1
  299. package/dist/kernel/reader.d.ts +1 -1
  300. package/dist/kernel/reader.js +57 -12
  301. package/dist/kernel/simplex.js +9 -2
  302. package/dist/lean-kernel/axiom-audit.d.ts +11 -0
  303. package/dist/lean-kernel/axiom-audit.js +50 -0
  304. package/dist/lean-kernel/emit.d.ts +34 -3
  305. package/dist/lean-kernel/emit.js +215 -28
  306. package/dist/lean-kernel/legacy-family-library.d.ts +1 -0
  307. package/dist/lean-kernel/legacy-family-library.js +5 -0
  308. package/dist/lean-kernel/legacy-family-order.d.ts +1 -0
  309. package/dist/lean-kernel/legacy-family-order.js +26 -0
  310. package/dist/lean-kernel/library.js +25 -3
  311. package/dist/lean-kernel/lift/counted-source-data.d.ts +7 -0
  312. package/dist/lean-kernel/lift/counted-source-data.js +78 -0
  313. package/dist/lean-kernel/lift/index.d.ts +82 -0
  314. package/dist/lean-kernel/lift/index.js +116 -0
  315. package/dist/lean-kernel/lift/project.d.ts +4 -0
  316. package/dist/lean-kernel/lift/project.js +15 -0
  317. package/dist/lean-kernel/lift/proof-capture.d.ts +104 -0
  318. package/dist/lean-kernel/lift/proof-capture.js +216 -0
  319. package/dist/lean-kernel/lift/proof-codec.d.ts +28 -0
  320. package/dist/lean-kernel/lift/proof-codec.js +299 -0
  321. package/dist/lean-kernel/lift/proof-counted-source.d.ts +16 -0
  322. package/dist/lean-kernel/lift/proof-counted-source.js +68 -0
  323. package/dist/lean-kernel/lift/proof-frontier.d.ts +19 -0
  324. package/dist/lean-kernel/lift/proof-frontier.js +153 -0
  325. package/dist/lean-kernel/lift/proof-graph.d.ts +17 -0
  326. package/dist/lean-kernel/lift/proof-graph.js +130 -0
  327. package/dist/lean-kernel/lift/proof-parts.d.ts +29 -0
  328. package/dist/lean-kernel/lift/proof-parts.js +131 -0
  329. package/dist/lean-kernel/lift/proof-prelude.d.ts +2 -0
  330. package/dist/lean-kernel/lift/proof-prelude.js +38 -0
  331. package/dist/lean-kernel/lift/proof-witness.d.ts +30 -0
  332. package/dist/lean-kernel/lift/proof-witness.js +283 -0
  333. package/dist/lean-kernel/lift/shape.d.ts +5 -0
  334. package/dist/lean-kernel/lift/shape.js +57 -0
  335. package/dist/lean-kernel/lift/source-projection.d.ts +16 -0
  336. package/dist/lean-kernel/lift/source-projection.js +81 -0
  337. package/dist/lean-kernel/lift/source.d.ts +23 -0
  338. package/dist/lean-kernel/lift/source.js +111 -0
  339. package/dist/lean-kernel/lift/witness-alpha.d.ts +9 -0
  340. package/dist/lean-kernel/lift/witness-alpha.js +31 -0
  341. package/dist/lean-kernel/lift-legacy.d.ts +58 -0
  342. package/dist/lean-kernel/lift-legacy.js +84 -0
  343. package/dist/lean-kernel/lift-names.d.ts +22 -0
  344. package/dist/lean-kernel/lift-names.js +36 -0
  345. package/dist/lean-kernel/lift-simulation/index.d.ts +29 -0
  346. package/dist/lean-kernel/lift-simulation/index.js +352 -0
  347. package/dist/lean-kernel/lift-simulation/shape.d.ts +41 -0
  348. package/dist/lean-kernel/lift-simulation/shape.js +173 -0
  349. package/dist/lean-kernel/lift-special/index.d.ts +36 -0
  350. package/dist/lean-kernel/lift-special/index.js +241 -0
  351. package/dist/lean-kernel/lift-special/structural.d.ts +25 -0
  352. package/dist/lean-kernel/lift-special/structural.js +126 -0
  353. package/dist/lean-kernel/lift-typed/index.d.ts +35 -0
  354. package/dist/lean-kernel/lift-typed/index.js +256 -0
  355. package/dist/lean-kernel/lift-typed/roles.d.ts +17 -0
  356. package/dist/lean-kernel/lift-typed/roles.js +170 -0
  357. package/dist/lean-kernel/lift-typed/shape.d.ts +1 -0
  358. package/dist/lean-kernel/lift-typed/shape.js +12 -0
  359. package/dist/lean-kernel/lift.d.ts +30 -0
  360. package/dist/lean-kernel/lift.js +97 -0
  361. package/package.json +5 -1
@@ -1,3 +1,4 @@
1
+ import { retainFamily, retainFrom } from "../core/proof-output.js";
1
2
  // An untrusted prover for the kernel: grows a split tree until every leaf's constraints are refuted by solve(), splitting
2
3
  // on whatever atom the hypotheses leave open (an if's condition, a min's or ∸'s comparison, a disjunction's atoms, two
3
4
  // reads of one map at keys not yet known equal or apart). Its trees go to kernel.check; nothing it says is trusted.
@@ -11,16 +12,27 @@
11
12
  import { cpair, evalC, evalE, walkOnce } from "../core/machine.js";
12
13
  import { add, costs, env, k, refuteFast, scale, solve, sub, v, work } from "../core/solver.js";
13
14
  import { checkRefutation } from "../core/check.js";
15
+ import { fullWork as rawFullWork } from "../core/work-meter.js";
16
+ import { stepWork, stepWorkProfile } from "../core/step-work.js";
17
+ import { completeWorkProfile } from "../core/work-profile.js";
18
+ import { projectedSearchWork, proxySearchState } from "../core/search-policy.js";
19
+ import { BudgetExpired, admittedWork, startWork, workLedger } from "../core/work-admission.js";
20
+ import { workDivide, workFromNumber, workMultiply, workToNumber } from "../core/work-amount.js";
21
+ export { BudgetExpired } from "../core/work-admission.js";
22
+ import { traceNow, withTraceWorkScope } from "../core/trace-clock.js";
14
23
  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
24
  import { proveSome, someLaws } from "../core/exists.js";
16
25
  import { REFUTED, growCdcl } from "./cdcl.js";
17
26
  import { decide, eprMeter, pastEprCap, patternsOf, withEprCap } from "./epr.js";
27
+ import { extendFunctionInstances, hasFunctionInstances } from "./function-instances.js";
18
28
  import { projected, tupleParts } from "./kernel.js";
19
29
  import { modelValueTerms } from "./model-values.js";
20
30
  import { proverRows } from "./prover-rows.js";
21
31
  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
32
  // The atoms the path leaves open, in evaluation order: deciding any of them makes progress.
23
33
  function openE(e, path, out) {
34
+ if (completeWorkProfile.enabled)
35
+ checkWorkEndpoint('open expression');
24
36
  switch (e.op) {
25
37
  case 'var':
26
38
  case 'const': return;
@@ -51,6 +63,8 @@ function openE(e, path, out) {
51
63
  }
52
64
  }
53
65
  function openC(c, path, out) {
66
+ if (completeWorkProfile.enabled)
67
+ checkWorkEndpoint('open condition');
54
68
  if (truth(c, path) !== undefined)
55
69
  return;
56
70
  if (c.op === 'flag' || c.op === 'all')
@@ -79,6 +93,8 @@ function openC(c, path, out) {
79
93
  // conjunction of settled parts / a linear comparison. A disjunction is settled only once one disjunct is left open and
80
94
  // that one is settled: facts from its last disjunct are not all its content while a case inside it is still open.
81
95
  function openH(c, path, out, positive = true) {
96
+ if (completeWorkProfile.enabled)
97
+ checkWorkEndpoint('open hypothesis');
82
98
  if (c.op === 'not')
83
99
  return openH(c.x, path, out, !positive);
84
100
  if ((c.op === 'and' && positive) || (c.op === 'or' && !positive))
@@ -179,6 +195,8 @@ function openCells(rows, path) {
179
195
  const dec = (lin) => path.get(canon(lin))?.holds ?? (path.has(canonFlip(lin)) ? !path.get(canonFlip(lin)).holds : undefined);
180
196
  for (let i = 0; i < names.length; i++)
181
197
  for (let j = i + 1; j < names.length; j++) {
198
+ if (completeWorkProfile.enabled)
199
+ checkWorkEndpoint('open cell pair');
182
200
  if (cs[i].map !== cs[j].map)
183
201
  continue;
184
202
  if (cs[i].keys || cs[j].keys) {
@@ -259,17 +277,17 @@ export function parseKey(text) {
259
277
  // the time in the solver and in building rows. Off unless `profile.on`; the counters cost nothing then.
260
278
  export const profile = { on: false, goals: [], solves: 0, solveMs: 0, rowsMs: 0, nodes: 0 };
261
279
  const timed = (f, add) => { if (!profile.on)
262
- return f(); const t = performance.now(); try {
280
+ return f(); const t = traceNow(); try {
263
281
  return f();
264
282
  }
265
283
  finally {
266
- add(performance.now() - t);
284
+ add(traceNow() - t);
267
285
  } };
268
286
  export const solveKinds = {};
269
287
  const solveP = (rows, maxRows) => {
270
288
  if (!profile.on)
271
289
  return solve(rows, maxRows);
272
- const t = performance.now(), out = solve(rows, maxRows), ms = performance.now() - t;
290
+ const t = traceNow(), out = solve(rows, maxRows), ms = traceNow() - t;
273
291
  profile.solves++;
274
292
  profile.solveMs += ms;
275
293
  const s = (solveKinds[out.kind] ??= { n: 0, ms: 0, rows: 0 });
@@ -293,28 +311,54 @@ export const cellProducts = { on: false };
293
311
  let deadline = Infinity, deadlineEpr = 0;
294
312
  // EPR has its own work counter. Debit it from a counted deadline, not from clock(): the protocol engine already
295
313
  // 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;
314
+ const searchRate = () => proxySearchState()?.rate ?? rate;
315
+ const eprTimeSince = (start) => searchRate() ? (eprMeter.n - start) / searchRate() : 0;
297
316
  // The clock every budget here reads (grow's `until`, withDeadline's; core/cyclic.ts's and core/data.ts's searches): wall
298
317
  // time, or within `counted` the work the prover has done (the solver's rows read and made, each node's rows), `perMs`
299
318
  // 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
319
  // speed. A counted search inside another reads the outer's clock.
301
320
  // With `full`, the clock reads the cost model below in place of work.n.
302
321
  let rate = 0, meter = () => work.n;
303
- export const clock = () => (rate ? meter() / rate : performance.now());
322
+ export const clock = () => {
323
+ const proxy = proxySearchState();
324
+ if (proxy)
325
+ return proxy.rate ? (proxy.model ? projectedSearchWork() : work.n) / proxy.rate : projectedSearchWork() / fullRate;
326
+ return completeWorkProfile.enabled ? workToNumber(workDivide(admittedWork(), workFromNumber(fullRate))) : stepWorkProfile.enabled ? fullWork() / fullRate : (rate ? meter() / rate : performance.now());
327
+ };
304
328
  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
- }
329
+ return withTraceWorkScope(() => {
330
+ const proxy = proxySearchState();
331
+ if (proxy) {
332
+ if (proxy.rate)
333
+ return f();
334
+ const outer = proxy.deadline, outerEpr = proxy.deadlineEpr, model = proxy.model;
335
+ proxy.rate = perMs;
336
+ proxy.model = full;
337
+ proxy.deadline = Infinity;
338
+ try {
339
+ return f();
340
+ }
341
+ finally {
342
+ proxy.rate = 0;
343
+ proxy.model = model;
344
+ proxy.deadline = outer;
345
+ proxy.deadlineEpr = outerEpr;
346
+ }
347
+ }
348
+ if (rate || completeWorkProfile.enabled)
349
+ return f();
350
+ const outer = deadline;
351
+ rate = perMs;
352
+ deadline = Infinity;
353
+ meter = full ? fullWork : () => work.n;
354
+ try {
355
+ return f();
356
+ }
357
+ finally {
358
+ rate = 0;
359
+ deadline = outer;
360
+ }
361
+ });
318
362
  }
319
363
  // The cost model: what a query does, by kind (core/solver.ts's costs), each weighed to the milliseconds a Modal 2-vCPU
320
364
  // container takes for it, `fullRate` units a millisecond at the median query: elimination's pairs and the float
@@ -324,30 +368,186 @@ export function counted(perMs, f, full = false) {
324
368
  // the solver and each node read, which the incremental search reads whole no more: on 7,027 root queries of 20 ms or
325
369
  // more (research/query/fit.py on runs/query/cal2: the 332 step goals, CHC sat and unsat, ITS, the false step goals and
326
370
  // 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
371
  export const fullRate = 250;
330
- export const fullWork = () => { let n = 0; for (const [k, w] of model)
331
- n += w * costs[k]; return n; };
372
+ export const fullWork = () => stepWork() + rawFullWork();
373
+ // Only heuristic readers use this. fullWork and every admission stay authoritative.
374
+ export const searchWork = () => proxySearchState() ? projectedSearchWork() : fullWork();
375
+ // Explicit synchronous work scopes. The default paths do not enter one yet:
376
+ // count/plain migrations and legacy deadline-reset semantics are separate steps.
377
+ let budgetUnitsEnd;
378
+ let admissionRefusedAt;
379
+ export const inBudget = () => completeWorkProfile.enabled ? workLedger.inBudget() : budgetUnitsEnd !== undefined;
380
+ export const inWorkScope = () => inBudget() || rate !== 0 || stepWorkProfile.enabled;
381
+ // Search endpoints follow the active clock; legacy real walls remain separate.
382
+ export const searchNow = () => inWorkScope() ? clock() : performance.now();
383
+ export const budgetEnd = () => {
384
+ if (proxySearchState())
385
+ return Infinity;
386
+ if (!completeWorkProfile.enabled)
387
+ return (budgetUnitsEnd ?? Infinity) / fullRate;
388
+ const end = workLedger.endpoint();
389
+ return end === null ? Infinity : workToNumber(workDivide(end, workFromNumber(fullRate)));
390
+ };
391
+ // Hard-stop checkpoints must not turn a local search deadline into a whole-run stop.
392
+ export function checkWorkEndpoint(phase) {
393
+ if (completeWorkProfile.enabled) {
394
+ workLedger.check(phase);
395
+ return;
396
+ }
397
+ if (budgetUnitsEnd !== undefined && (admissionRefusedAt === budgetUnitsEnd || fullWork() > budgetUnitsEnd))
398
+ throw new BudgetExpired(phase);
399
+ }
400
+ // Pre-step admission for new native primitive counters. No credit is minted and
401
+ // no local deadline is promoted to whole-search cancellation.
402
+ export function checkWorkAdmission(units, phase) {
403
+ if (!Number.isFinite(units) || units < 0)
404
+ throw new RangeError('work charge must be finite and nonnegative');
405
+ if (completeWorkProfile.enabled) {
406
+ workLedger.checkAmount(workFromNumber(units), phase);
407
+ return;
408
+ }
409
+ if (budgetUnitsEnd !== undefined && (admissionRefusedAt === budgetUnitsEnd || fullWork() + units > budgetUnitsEnd)) {
410
+ admissionRefusedAt = budgetUnitsEnd;
411
+ throw new BudgetExpired(phase);
412
+ }
413
+ }
414
+ export function remainingWork() {
415
+ if (completeWorkProfile.enabled) {
416
+ const left = workLedger.available();
417
+ return left === null ? Infinity : workToNumber(left);
418
+ }
419
+ return budgetUnitsEnd === undefined ? Infinity : admissionRefusedAt === budgetUnitsEnd ? 0 : Math.max(0, budgetUnitsEnd - fullWork());
420
+ }
421
+ export function checkBudget(phase) {
422
+ if (completeWorkProfile.enabled) {
423
+ workLedger.check(phase);
424
+ return;
425
+ }
426
+ if (budgetUnitsEnd !== undefined && (admissionRefusedAt === budgetUnitsEnd || fullWork() > budgetUnitsEnd
427
+ || completeWorkProfile.enabled && clock() > withinDeadline(budgetEnd())))
428
+ throw new BudgetExpired(phase);
429
+ }
430
+ export function withBudget(units, f) {
431
+ if (completeWorkProfile.enabled) {
432
+ const grant = typeof units === 'number' ? workFromNumber(units) : units;
433
+ // Opening a real quota must not introduce a heuristic counted region.
434
+ if (proxySearchState())
435
+ return withTraceWorkScope(() => workLedger.withBudget(grant, () => {
436
+ checkBudget('entry');
437
+ const result = f();
438
+ checkBudget('completion');
439
+ return result;
440
+ }));
441
+ return counted(fullRate, () => workLedger.withBudget(grant, () => {
442
+ checkBudget('entry');
443
+ const result = f();
444
+ checkBudget('completion');
445
+ return result;
446
+ }), true);
447
+ }
448
+ if (typeof units !== 'number')
449
+ throw new Error('exact work budgets require the full-work profile');
450
+ if (!Number.isFinite(units) || units < 0)
451
+ throw new RangeError('work budget must be finite and nonnegative');
452
+ // Never silently interpret units using a legacy work.n/count-rate island.
453
+ if (rate && meter !== fullWork)
454
+ throw new Error('work budget requires the outer full-work clock');
455
+ return counted(fullRate, () => {
456
+ checkWorkEndpoint('inherited admission');
457
+ const previous = budgetUnitsEnd, previousRefused = admissionRefusedAt;
458
+ budgetUnitsEnd = Math.min(previous ?? Infinity, workCap, fullWork() + units);
459
+ try {
460
+ return withWork(budgetUnitsEnd, () => withDeadline(budgetEnd(), () => {
461
+ checkBudget('entry');
462
+ const result = f();
463
+ // The final checker is inside the allowance, not free completion work.
464
+ checkBudget('completion');
465
+ return result;
466
+ }));
467
+ }
468
+ finally {
469
+ // A refusal at a shared endpoint remains visible after an inner scope;
470
+ // a genuinely smaller child allowance cannot poison a larger parent.
471
+ admissionRefusedAt = admissionRefusedAt === budgetUnitsEnd && previous === budgetUnitsEnd ? previous : previousRefused;
472
+ budgetUnitsEnd = previous;
473
+ }
474
+ }, true);
475
+ }
332
476
  // A goal's own budget where its caller gives none, outside a counted search: the cost model's work, groundRate units a
333
477
  // 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
478
  // 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
479
  // on any machine; a deadline it is grown within stays.
336
480
  const groundRate = 180;
337
481
  let workCap = Infinity;
338
- export const withWork = (cap, f) => { const outer = workCap; workCap = Math.min(outer, cap); try {
339
- return f();
482
+ export const withWork = (cap, f) => {
483
+ if (completeWorkProfile.enabled) {
484
+ if (cap === Infinity)
485
+ return f();
486
+ return workLedger.withEndpoint('work-cap', typeof cap === 'number' ? workFromNumber(cap) : cap, f);
487
+ }
488
+ if (typeof cap !== 'number')
489
+ throw new Error('exact work caps require the full-work profile');
490
+ const outer = workCap;
491
+ workCap = Math.min(outer, cap);
492
+ try {
493
+ return f();
494
+ }
495
+ finally {
496
+ workCap = outer;
497
+ }
498
+ };
499
+ // Internal search caps are proxy state only; explicit withWork remains native.
500
+ const searchWorkCap = () => proxySearchState()?.workCap ?? workCap;
501
+ export function withSearchWork(cap, f) {
502
+ const proxy = proxySearchState();
503
+ if (!proxy)
504
+ return withWork(cap, f);
505
+ const outer = proxy.workCap;
506
+ proxy.workCap = Math.min(outer, cap);
507
+ try {
508
+ return f();
509
+ }
510
+ finally {
511
+ proxy.workCap = outer;
512
+ }
340
513
  }
341
- finally {
342
- workCap = outer;
343
- } };
344
514
  // Past a budget's end on the clock, or past the work a goal's own budget allows.
345
515
  // 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
516
  // (the EPR path's propositional search, a node's propagation, building a large goal's rows) stops there too, and past it
347
517
  // every goal is left unknown, whatever its own budget. Untrusted: it only stops a search.
348
518
  let wallEnd = Infinity;
349
- export const pastWall = () => wallEnd !== Infinity && performance.now() > wallEnd;
350
- export function withWall(end, f) {
519
+ // Capture the producer's clock domain before nested counted() changes it.
520
+ export const wallDeadline = (end, domain) => ({ end, domain: domain ?? (inWorkScope() || proxySearchState()?.rate ? 'counted' : 'real') });
521
+ // A legacy counted clock is not an opt-in work-only cancellation policy.
522
+ // Preserve its inherited real wall; only explicit work scopes/profiles elide it.
523
+ const workOnlyWall = () => inBudget() || stepWorkProfile.enabled;
524
+ export const pastWall = () => {
525
+ checkWorkEndpoint('prover boundary');
526
+ const proxy = proxySearchState();
527
+ if (proxy)
528
+ return clock() > withinDeadline(Infinity) || (!workOnlyWall() && proxy.wallEnd !== Infinity && performance.now() > proxy.wallEnd);
529
+ return (inWorkScope() && clock() > withinDeadline(budgetEnd()))
530
+ || (!workOnlyWall() && wallEnd !== Infinity && performance.now() > wallEnd);
531
+ };
532
+ export function withWall(limit, f) {
533
+ const proxy = proxySearchState();
534
+ // Untagged legacy endpoints retain their old policy. Search producers tag
535
+ // their domain explicitly, so counted milliseconds never become real time.
536
+ const { end, domain } = typeof limit === 'number' ? wallDeadline(limit, workOnlyWall() || proxy?.rate ? 'counted' : 'real') : limit;
537
+ if (domain === 'counted')
538
+ return withDeadline(Math.min(budgetEnd(), end), f);
539
+ if (workOnlyWall())
540
+ return f();
541
+ if (proxy) {
542
+ const outer = proxy.wallEnd;
543
+ proxy.wallEnd = Math.min(outer, end);
544
+ try {
545
+ return f();
546
+ }
547
+ finally {
548
+ proxy.wallEnd = outer;
549
+ }
550
+ }
351
551
  const outer = wallEnd;
352
552
  wallEnd = Math.min(outer, end);
353
553
  try {
@@ -359,12 +559,46 @@ export function withWall(end, f) {
359
559
  }
360
560
  // Past the wall or the deadline in force: a goal grown now is left unknown at once.
361
561
  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();
562
+ // Active-clock endpoint; inherited real walls are checked separately by pastWall.
563
+ export const wallAt = () => {
564
+ const proxy = proxySearchState();
565
+ if (proxy)
566
+ return workOnlyWall() || proxy.rate ? withinDeadline(Infinity) : proxy.wallEnd;
567
+ return inWorkScope() ? withinDeadline(budgetEnd()) : wallEnd;
568
+ };
569
+ export const late = (until) => {
570
+ checkWorkEndpoint('prover poll');
571
+ const proxy = proxySearchState();
572
+ if (proxy)
573
+ return clock() > until || (proxy.workCap !== Infinity && searchWork() > proxy.workCap) || pastWall();
574
+ return clock() > until || (workCap !== Infinity && fullWork() > workCap) || pastWall();
575
+ };
365
576
  // 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));
577
+ export const withinDeadline = (until) => {
578
+ const proxy = proxySearchState();
579
+ if (proxy)
580
+ return Math.min(until, proxy.deadline - eprTimeSince(proxy.deadlineEpr));
581
+ return completeWorkProfile.enabled ? Math.min(until, budgetEnd()) : Math.min(until, deadline - eprTimeSince(deadlineEpr));
582
+ };
367
583
  export function withDeadline(until, f) {
584
+ const proxy = proxySearchState();
585
+ if (proxy) {
586
+ const outer = proxy.deadline, outerEpr = proxy.deadlineEpr;
587
+ proxy.deadline = withinDeadline(until);
588
+ proxy.deadlineEpr = eprMeter.n;
589
+ try {
590
+ return f();
591
+ }
592
+ finally {
593
+ proxy.deadline = outer;
594
+ proxy.deadlineEpr = outerEpr;
595
+ }
596
+ }
597
+ if (completeWorkProfile.enabled) {
598
+ if (until === Infinity)
599
+ return f();
600
+ return workLedger.withEndpoint('deadline', workMultiply(workFromNumber(until), workFromNumber(fullRate)), f);
601
+ }
368
602
  const outer = deadline, outerEpr = deadlineEpr;
369
603
  deadline = withinDeadline(until);
370
604
  deadlineEpr = eprMeter.n;
@@ -376,6 +610,9 @@ export function withDeadline(until, f) {
376
610
  deadlineEpr = outerEpr;
377
611
  }
378
612
  }
613
+ // Full-accounting closing snapshots keep absolute endpoints and the legacy
614
+ // clock anchors as data. This observer never rebases deadlines or resets fuel.
615
+ export const snapshotProofClock = () => ({ rate, deadline, deadlineEpr, budgetUnitsEnd, admissionRefusedAt, workCap, wallEnd });
379
616
  // `units: false`: the goal's own order, no units first (a caller after a model, not a proof: a run guided by the
380
617
  // prover's witnesses, say, whose models units would steer).
381
618
  export function grow(goal, path = new Map(), budget) {
@@ -383,8 +620,8 @@ export function grow(goal, path = new Map(), budget) {
383
620
  return { stuck: 'unknown', path, why: outOfBudget(goal, 'time', path.size) };
384
621
  if (!budget) {
385
622
  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 }));
623
+ if (!searchRate())
624
+ return withSearchWork(searchWork() + groundRate * ms, () => grow(goal, path, { nodes: 0 }));
388
625
  budget = { nodes: 0, until: clock() + ms };
389
626
  }
390
627
  const end = withinDeadline(budget.until ?? Infinity);
@@ -403,8 +640,8 @@ export function grow(goal, path = new Map(), budget) {
403
640
  proveDump(goal);
404
641
  }
405
642
  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})` : ''}`}`);
643
+ const t = traceNow(), out = growRoot(goal, path, budget);
644
+ 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
645
  return out;
409
646
  }
410
647
  // (a root goal grown before within `withTrees`: its tree again; a tree is the kernel's to check wherever it goes)
@@ -446,11 +683,11 @@ export function withTrees(f) {
446
683
  // its wall time and counted work, its outcome, and how many queries it is inside.
447
684
  export const queryHook = { depth: 0 };
448
685
  export function logged(kind, goal, f) {
449
- const t0 = performance.now(), w0 = work.n;
686
+ const t0 = traceNow(), w0 = work.n;
450
687
  queryHook.depth++;
451
688
  try {
452
689
  const out = f();
453
- queryHook.on?.({ kind, goal, ms: performance.now() - t0, work: work.n - w0, out, depth: queryHook.depth - 1 });
690
+ queryHook.on?.({ kind, goal, ms: traceNow() - t0, work: work.n - w0, out, depth: queryHook.depth - 1 });
454
691
  return out;
455
692
  }
456
693
  finally {
@@ -465,9 +702,9 @@ function growKept(goal, path, budget) {
465
702
  function growKept0(goal, path, budget) {
466
703
  if (!profile.on || path.size || budget.nodes)
467
704
  return growRoot(goal, path, budget);
468
- const t = performance.now(), s0 = profile.solves, m0 = profile.solveMs, r0 = profile.rowsMs, n0 = profile.nodes;
705
+ const t = traceNow(), s0 = profile.solves, m0 = profile.solveMs, r0 = profile.rowsMs, n0 = profile.nodes;
469
706
  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 });
707
+ 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
708
  return out;
472
709
  }
473
710
  // 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 +748,11 @@ function eprFirst(goal, budget, whole = true, stop = () => pastWall() || pastEpr
511
748
  if (d.sat)
512
749
  return { stuck: 'sat', witness: d.witness, diagram: d.diagram, path: new Map(), why: 'a model' };
513
750
  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();
751
+ const now = clock(), end = withinDeadline(budget.until ?? Infinity), w = searchWork();
515
752
  eprScope.busy = true;
516
753
  try {
517
754
  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) }));
755
+ 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
756
  if (!('tree' in out)) {
520
757
  eprLast.refuted = true;
521
758
  return undefined;
@@ -604,8 +841,8 @@ export const wideFor = (goal) => !wideBusy && goal.hyps.length >= wideAt && term
604
841
  // (`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
842
  // widened: settle's, whose final proof is made over the instances its proofs read)
606
843
  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;
844
+ const hyps = goal.hyps, last = hyps.length - 1, broken = brokenOf(goal), now = clock(), w = searchWork();
845
+ const end = withinDeadline(budget.until ?? Infinity), span = wideShare * (end - now), room = wideShare * (searchWorkCap() - w), until = now + span;
609
846
  const part = new Set([last]), near = new Set(cellsIn(hyps[last])), cells = new Map();
610
847
  const cellsAt = (i) => { let c = cells.get(i); if (!c)
611
848
  cells.set(i, (c = cellsIn(hyps[i]))); return c; };
@@ -619,24 +856,24 @@ export function growWide(goal, budget, ask = (g, until) => grow(g, new Map(), {
619
856
  // (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
857
  // that much less), at least a sixteenth of the share: a part that a small budget doesn't settle leaves the goal)
621
858
  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();
859
+ const t0 = traceNow(), at = clock();
623
860
  wideScope.judge = w => !broken(w, ids, true).length;
624
861
  let out;
625
862
  try {
626
- out = withWork(Math.min(w + room, fullWork() + f * room), () => ask(g, Math.min(until, at + f * span)));
863
+ out = withSearchWork(Math.min(w + room, searchWork() + f * room), () => ask(g, Math.min(until, at + f * span)));
627
864
  }
628
865
  finally {
629
866
  wideScope.judge = undefined;
630
867
  }
631
868
  wideHook.on?.(g, out);
632
869
  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) ?? ''}`}`);
870
+ 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
871
  if ('tree' in out && keep) {
635
872
  wideStats.trees++;
636
873
  return { tree: out.tree, nodes: out.nodes, part: g, core: ids };
637
874
  }
638
875
  if ('tree' in out) {
639
- const tree = withWork(w + room, () => withDeadline(until, () => widen(g, goal, out.tree)));
876
+ const tree = withSearchWork(w + room, () => withDeadline(until, () => widen(g, goal, out.tree)));
640
877
  if (tree)
641
878
  wideStats.trees++;
642
879
  return tree && { tree, nodes: out.nodes };
@@ -720,8 +957,8 @@ function growRoot(goal, path, budget) {
720
957
  }
721
958
  if (root) {
722
959
  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) }));
960
+ const now = clock(), end = withinDeadline(budget.until ?? Infinity), w = searchWork();
961
+ const out = withSearchWork(searchWorkCap() === Infinity ? Infinity : w + cdclShare * (searchWorkCap() - w), () => growCdcl(goal, path, { nodes: 0, until: end === Infinity ? end : now + cdclShare * (end - now) }));
725
962
  // (with `realModels.on`, a model whose products don't multiply out is no model: the CDCL search reads a product as
726
963
  // a name of its own, where the plain search below multiplies rows; a goal whose products only its cases bring,
727
964
  // core/nonterm.ts's x' := x·y)
@@ -755,9 +992,14 @@ function growPlain(goal, path, budget) {
755
992
  const full = timed(() => rowsAt(goal, path), ms => { profile.rowsMs += ms; });
756
993
  work.n += 1 + full.length;
757
994
  costs.plainNodes++;
758
- costs.plainRows += full.length;
995
+ if (!completeWorkProfile.enabled)
996
+ costs.plainRows += full.length;
759
997
  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] : []));
998
+ const idx = full.flatMap((r, i) => {
999
+ if (completeWorkProfile.enabled)
1000
+ startWork('plainRows', 1, 'plain row processing');
1001
+ return columns || !Object.keys(r.lin).some(key => key.startsWith('⟦')) ? [i] : [];
1002
+ });
761
1003
  const rows = idx.map(i => full[i]), at = (i) => (i < rows.length ? idx[i] : full.length + i - rows.length);
762
1004
  const leafOf = (steps0, products0, squares0) => {
763
1005
  const { steps, products, squares } = products0 || squares0 ? trimmed(rows.length, steps0, products0 ?? [], squares0 ?? []) : { steps: steps0, products: undefined, squares: undefined };
@@ -1069,6 +1311,18 @@ export function rowsAt(goal, path) {
1069
1311
  }
1070
1312
  return rows;
1071
1313
  }
1314
+ // Untrusted capture may reuse an existing proposal without forcing a cache
1315
+ // miss to materialize another table. Same lookup as rowsAt; no cache mutation,
1316
+ // metering, checking, or authority to accept a certificate.
1317
+ export function cachedRowsAt(goal, path) {
1318
+ const byPath = rowsSeen.get(goal);
1319
+ if (!byPath)
1320
+ return undefined;
1321
+ let id = '';
1322
+ for (const [key, a] of path)
1323
+ id += `${a.holds ? '+' : '-'}${key}|`;
1324
+ return byPath.get(id);
1325
+ }
1072
1326
  function lift(goal, tree, from, to) {
1073
1327
  const own = to.size; // the decision's row: the last of `from`'s path rows, below every later split's
1074
1328
  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 +1455,10 @@ const nearSeen = new WeakMap();
1201
1455
  // (the names a term reads, its shared parts walked once: a witness read at each of its uses is one object)
1202
1456
  const namesOf = (t) => {
1203
1457
  const out = new Set();
1204
- walkOnce(t, o => { costs.goalNodes++; for (const [key, v] of Object.entries(o))
1458
+ walkOnce(t, o => { if (!completeWorkProfile.enabled)
1459
+ costs.goalNodes++; for (const [key, v] of Object.entries(o))
1205
1460
  if ((key === 'name' || key === 'map') && typeof v === 'string')
1206
- out.add(v); });
1461
+ out.add(v); }, completeWorkProfile.enabled ? () => startWork('goalNodes', 1, 'goal name traversal') : undefined);
1207
1462
  return out;
1208
1463
  };
1209
1464
  export function nearOf(goal) {
@@ -1230,9 +1485,12 @@ function unitsOf(goal) {
1230
1485
  // 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
1486
  // single variables (x <= c, x >= c) deciding it whichever way its variables go.
1232
1487
  const root = new Map(), rows = leafConstraints(goal, root), seen = new Set(), given = new Set();
1233
- costs.unitRows += rows.length;
1488
+ if (!completeWorkProfile.enabled)
1489
+ costs.unitRows += rows.length;
1234
1490
  const lo = new Map(), hi = new Map();
1235
1491
  for (const r of rows) {
1492
+ if (completeWorkProfile.enabled)
1493
+ startWork('unitRows', 1, 'unit row processing');
1236
1494
  given.add(canon(r.lin));
1237
1495
  const vs = Object.keys(r.lin).filter(key => key !== '1');
1238
1496
  if (vs.length !== 1)
@@ -1361,7 +1619,8 @@ function growFocused(goal, path, focus, budget, near = focus) {
1361
1619
  // (each node reads its whole leaf, counted as growPlain counts a node's rows)
1362
1620
  const leaf = leafConstraints(goal, path);
1363
1621
  work.n += 1 + leaf.length;
1364
- costs.plainRows += leaf.length;
1622
+ if (!completeWorkProfile.enabled)
1623
+ costs.plainRows += leaf.length;
1365
1624
  const verdict = solveNear(leaf, [...near, ...[...path.values()].slice(-1).map(a => a.lin)]);
1366
1625
  if (verdict.kind === 'refuted')
1367
1626
  return { tree: { leaf: verdict.steps }, nodes: budget.nodes };
@@ -1383,10 +1642,13 @@ function growFocused(goal, path, focus, budget, near = focus) {
1383
1642
  // read (a param every step reads) joins no rows: through it every step is near every other.
1384
1643
  function solveNear(rows, seeds) {
1385
1644
  const uses = new Map();
1386
- for (const r of rows)
1645
+ for (const r of rows) {
1646
+ if (completeWorkProfile.enabled)
1647
+ startWork('plainRows', 1, 'focused row processing');
1387
1648
  for (const key in r.lin)
1388
1649
  if (key !== '1')
1389
1650
  uses.set(key, (uses.get(key) ?? 0) + 1);
1651
+ }
1390
1652
  const hub = (key) => (uses.get(key) ?? 0) > Math.max(16, rows.length / 8);
1391
1653
  const reach = new Set(seeds.flatMap(l => Object.keys(l).filter(key => key !== '1')));
1392
1654
  for (let hop = 0; hop < 2; hop++) {
@@ -1563,15 +1825,50 @@ export const keyValue = (cell, w) => {
1563
1825
  // the values the goal's keys take, and each tuple where one fails added, as the goal's terms with those values, to its
1564
1826
  // instances. None found: the model is one on every tuple of the goal's keys. Untrusted: it chooses instances only.
1565
1827
  export const modelRounds = 4;
1828
+ let scopedModelRounds;
1829
+ export function validateModelRounds(value) {
1830
+ if (value === 'progress' || typeof value === 'number' && Number.isSafeInteger(value) && value >= 0)
1831
+ return value;
1832
+ throw new RangeError('modelRounds must be a nonnegative safe integer or progress');
1833
+ }
1834
+ export function effectiveModelRounds() {
1835
+ if (scopedModelRounds !== undefined)
1836
+ return scopedModelRounds;
1837
+ const value = env.GDP_MODEL_ROUNDS;
1838
+ return value === undefined ? modelRounds : validateModelRounds(/^(0|[1-9][0-9]*)$/.test(value) ? Number(value) : value);
1839
+ }
1840
+ export function withModelRounds(value, f) {
1841
+ const policy = value === undefined ? effectiveModelRounds() : validateModelRounds(value), old = scopedModelRounds;
1842
+ scopedModelRounds = policy;
1843
+ try {
1844
+ return f();
1845
+ }
1846
+ finally {
1847
+ scopedModelRounds = old;
1848
+ }
1849
+ }
1566
1850
  // A condition as the disjuncts it is the or of (¬(a ∧ b) as ¬a, ¬b).
1567
1851
  // (GDP_MODEL_CUTS=0: every tuple evaluated whole, for comparing)
1568
1852
  const modelCuts = env.GDP_MODEL_CUTS !== '0';
1569
1853
  const disjuncts = (c) => (c.op === 'or' ? c.xs.flatMap(disjuncts) : c.op === 'not' && c.x.op === 'and' ? c.x.xs.flatMap(y => disjuncts({ op: 'not', x: y })) : c.op === 'not' && c.x.op === 'not' ? disjuncts(c.x.x) : [c]);
1570
- export function modelInstances(m, laws, inst, goal, w, most = 64, sorted = false) {
1854
+ export function modelInstances(m, laws, inst, goal, w, most = 64, sorted = false, confirmation) {
1855
+ if (confirmation) {
1856
+ confirmation.confirmed = false;
1857
+ confirmation.why = 'model domain not checked';
1858
+ }
1859
+ let incomplete, violated = false;
1860
+ const unfinished = (why) => { incomplete ??= why; };
1571
1861
  const pm = plainOf(m), qs = Object.entries(pm.step.flags ?? {}).filter((e) => e[1].op === 'all' && w[`?${e[0]}`] === 1);
1572
- const keyed = laws.filter(l => l.forall);
1573
- if (!keyed.length && !qs.length)
1862
+ // Start obligations assume facts, not the invariants being established.
1863
+ const keyed = [...(pm.facts ?? []), ...(goal.name.endsWith(' @start') ? [] : laws)].filter(l => l.forall);
1864
+ if (!keyed.length && !qs.length) {
1865
+ if (confirmation) {
1866
+ confirmation.confirmed = true;
1867
+ delete confirmation.why;
1868
+ }
1869
+ ;
1574
1870
  return undefined;
1871
+ }
1575
1872
  // (the maps a request carries read as maps too: a quantified flag over one, wo's ∀k. Q has k → Votes[src, k])
1576
1873
  const fns = Object.keys(pm.fns ?? {}), mm = { ...pm, fns: undefined, maps: { ...(pm.maps ?? {}), ...Object.fromEntries([...fns, ...(pm.inputMaps ?? []), ...Object.keys(pm.counts ?? {})].map(f => [f, 0])) } };
1577
1874
  const maps = Object.fromEntries(Object.keys(mm.maps).map(mp => [mp, new Map()]));
@@ -1582,6 +1879,8 @@ export function modelInstances(m, laws, inst, goal, w, most = 64, sorted = false
1582
1879
  const key = keyValue(cell, w);
1583
1880
  if (key !== undefined)
1584
1881
  maps[cell.slice(0, br)].set(key, value);
1882
+ else
1883
+ unfinished('model cell could not be decoded');
1585
1884
  }
1586
1885
  const st = { scalars: {}, maps }, read = (at) => new Proxy(at, { get: (t, p) => (p in t ? t[p] : w[p] ?? 0), has: (t, p) => p in t || p in w });
1587
1886
  // (a count's cell the model has not: its definition, its body summed over the model's cells below its bound, so a law
@@ -1589,6 +1888,8 @@ export function modelInstances(m, laws, inst, goal, w, most = 64, sorted = false
1589
1888
  for (const [c, d] of Object.entries(pm.counts ?? {})) {
1590
1889
  const had = maps[c], sum = (x) => {
1591
1890
  const e1 = read(d.base ? { [d.j]: Math.floor(x / d.base), [d.lo]: x % d.base } : { [d.j]: x }), n = Math.min(256, evalE(d.below, e1, st, mm));
1891
+ if (n === 256 && evalE(d.below, e1, st, mm) > n)
1892
+ unfinished('model count evaluation truncated');
1592
1893
  let t = 0;
1593
1894
  for (let k = 0; k < n; k++)
1594
1895
  t += evalE(d.body, read({ ...e1, [d.key]: k }), st, mm);
@@ -1603,12 +1904,23 @@ export function modelInstances(m, laws, inst, goal, w, most = 64, sorted = false
1603
1904
  return f();
1604
1905
  }
1605
1906
  catch {
1907
+ unfinished('model hypothesis evaluation incomplete');
1606
1908
  return undefined;
1607
1909
  } };
1910
+ if (confirmation)
1911
+ for (const h of goal.hyps) {
1912
+ if (pastWall()) {
1913
+ unfinished('model confirmation wall');
1914
+ break;
1915
+ }
1916
+ if (ev(() => evalC(h, read({}), st, mm)) === false)
1917
+ violated = true;
1918
+ }
1608
1919
  const valueOf = (e) => { try {
1609
1920
  return evalE(e, read({}), st, mm);
1610
1921
  }
1611
1922
  catch {
1923
+ unfinished('model term evaluation incomplete');
1612
1924
  return undefined;
1613
1925
  } };
1614
1926
  // Each bound key over its own sort as the model fills it: the terms its body's map reads bind matched against the
@@ -1622,8 +1934,11 @@ export function modelInstances(m, laws, inst, goal, w, most = 64, sorted = false
1622
1934
  if (v2 !== undefined && !all.has(v2))
1623
1935
  all.set(v2, e);
1624
1936
  }
1625
- if (!all.size)
1937
+ if (!all.size) {
1938
+ if (confirmation)
1939
+ confirmation.why = 'model has no evaluable key domain';
1626
1940
  return undefined;
1941
+ }
1627
1942
  // (each sort's witnesses first: an ∃ law's ghost, a quantified flag's witness, the terms a model most often breaks a
1628
1943
  // law at and no read's matching orders well)
1629
1944
  const witnessFirst = (p) => {
@@ -1652,8 +1967,10 @@ export function modelInstances(m, laws, inst, goal, w, most = 64, sorted = false
1652
1967
  // first don't leave none to those after: sharded KV's "a key in transfer has no owner", broken at the goal's own keys)
1653
1968
  let added = 0, evals = 0, left = 0, ineligible = false;
1654
1969
  const each = (id, names, body, atoms) => {
1655
- if (pastWall())
1970
+ if (pastWall()) {
1971
+ unfinished('model confirmation wall');
1656
1972
  return;
1973
+ }
1657
1974
  const until = evals + Math.max(256, Math.floor((20_000 - evals) / Math.max(1, left--)));
1658
1975
  const have = new Set(), had = out[id] ?? [], n = names.length, sorts = sortsOf(body, names, atoms);
1659
1976
  const keyNames = new Set();
@@ -1668,7 +1985,7 @@ export function modelInstances(m, laws, inst, goal, w, most = 64, sorted = false
1668
1985
  // Arithmetic-only naturals range over comparison boundaries, not map keys.
1669
1986
  // The model chooses constants; assumed/check still validate ordinary law instances.
1670
1987
  // (a law at one key assumed at a term of every value its sort takes already: nothing to add)
1671
- if (n === 1 && keyNames.has(names[0])) {
1988
+ if (!confirmation && n === 1 && keyNames.has(names[0])) {
1672
1989
  const covered = new Set(had.map(valueOf));
1673
1990
  if ([...sorts[0].keys()].every(v2 => covered.has(v2)))
1674
1991
  return;
@@ -1685,8 +2002,10 @@ export function modelInstances(m, laws, inst, goal, w, most = 64, sorted = false
1685
2002
  ready[names.reduce((a, x, j) => (t.includes(`"name":${JSON.stringify(x)}`) ? j + 1 : a), 0)].push(d);
1686
2003
  }
1687
2004
  const go = (i, at, terms) => {
1688
- if (added >= most || evals > until || (evals % 512 === 0 && pastWall()))
2005
+ if (added >= most || evals > until || (evals % 512 === 0 && pastWall())) {
2006
+ unfinished('model confirmation budget');
1689
2007
  return;
2008
+ }
1690
2009
  for (const d of ready[i]) {
1691
2010
  evals++;
1692
2011
  if (ev(() => evalC(d, read(at), st, mm)) === true)
@@ -1696,6 +2015,7 @@ export function modelInstances(m, laws, inst, goal, w, most = 64, sorted = false
1696
2015
  evals++;
1697
2016
  if (ev(() => evalC(body, read(at), st, mm)) !== false)
1698
2017
  return;
2018
+ violated = true;
1699
2019
  const id2 = JSON.stringify(terms);
1700
2020
  if (have.has(id2))
1701
2021
  return;
@@ -1757,44 +2077,62 @@ export function modelInstances(m, laws, inst, goal, w, most = 64, sorted = false
1757
2077
  for (const [f, q] of qs)
1758
2078
  each(`?${f}`, boundOf(q), q.c, atoms);
1759
2079
  }
1760
- // A rejected-only refinement is not evidence that the model satisfies every assumed law.
2080
+ // No new tuple is not confirmation: a cap, an evaluation failure, an already
2081
+ // assumed false instance, or a rejected tuple still leaves this model unconfirmed.
2082
+ if (confirmation) {
2083
+ confirmation.confirmed = !incomplete && !violated && !ineligible;
2084
+ if (confirmation.confirmed)
2085
+ delete confirmation.why;
2086
+ else
2087
+ confirmation.why = incomplete ?? (ineligible ? 'model violates an ineligible hypothesis instance' : 'model violates a hypothesis instance');
2088
+ }
1761
2089
  return added || ineligible ? out : undefined;
1762
2090
  }
1763
- // A goal (or a law's goals) asked at some instances, and again at those its model asks for (modelInstances), up to
1764
- // modelRounds times. `ask` is the caller's own question; `modelOf` reads a model from its answer, `settled` says it is
1765
- // one (a proof, a model: not out of budget). The later rounds together get modelShare times the cost model's work the
1766
- // first took (at least a second of it), so a model's tuples that make the goal one the prover can't finish cost that,
1767
- // not the goal's usual budget again; a later round left unsettled gives back the first round's answer, so the verdict is
1768
- // never one the model's tuples made worse. Untrusted.
2091
+ // A model of only the current instances is a proposal, never a deletion witness.
2092
+ // Refinement keeps the existing work share/round limits; failure to finish is
2093
+ // UNKNOWN, not the first SAT. Only a completed model-domain check admits SAT.
2094
+ // Untrusted: proof trees and instances still go through the unchanged checker.
1769
2095
  export const modelShare = 3;
1770
- // (GDP_MODELS_TRACE=1: each model round, its goal and the tuples a model adds, on stderr)
1771
2096
  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));
1774
- export function withModels(m, laws, inst, goalOf, ask, modelOf, settled) {
1775
- return withPatterns(m, laws, () => modelsLoop(m, laws, inst, goalOf, ask, modelOf, settled));
1776
- }
1777
- function modelsLoop(m, laws, inst, goalOf, ask, modelOf, settled) {
1778
- let at = inst, first, cap = 0;
2097
+ const costNow = () => (searchRate() ? clock() : searchWork() / groundRate);
2098
+ const within = (ms, f) => (searchRate() ? withDeadline(clock() + ms, f) : withSearchWork(searchWork() + groundRate * ms, f));
2099
+ export function withModels(m, laws, inst, goalOf, ask, modelOf, settled, unknown) {
2100
+ return withPatterns(m, laws, () => modelsLoop(m, laws, inst, goalOf, ask, modelOf, settled, unknown));
2101
+ }
2102
+ function modelsLoop(m, laws, inst, goalOf, ask, modelOf, settled, unknown) {
2103
+ let at = inst, cap = 0;
2104
+ const rounds = effectiveModelRounds();
2105
+ // Progress may use the caller's existing bounded allowance, never a new one.
2106
+ // Without an outer endpoint, retain the old finite local work share.
2107
+ const progressBudget = rounds === 'progress' && (inBudget() || Number.isFinite(wallAt()) || Number.isFinite(withinDeadline(Infinity)));
1779
2108
  for (let round = 0;; round++) {
1780
- const c0 = costNow(), result = round ? within(Math.max(0, cap), () => ask(goalOf(at))) : ask(goalOf(at));
2109
+ const c0 = costNow(), result = round && !progressBudget ? within(Math.max(0, cap), () => ask(goalOf(at))) : ask(goalOf(at));
1781
2110
  if (round)
1782
2111
  cap -= costNow() - c0;
1783
2112
  else
1784
2113
  cap = Math.max(modelFloor, modelShare * (costNow() - c0));
1785
- if (round && !settled(result)) {
1786
- if (modelsTrace)
1787
- console.error(`[models] round ${round} unsettled in ${Math.round(costNow() - c0)} cost`);
1788
- return first;
1789
- }
2114
+ const abandon = (why) => ({ result: unknown(result, `unconfirmed model: ${why}`), inst: at });
2115
+ if (!settled(result))
2116
+ return abandon('refinement unsettled');
2117
+ const mw = modelOf(result);
2118
+ if (!mw)
2119
+ return { result, inst: at };
1790
2120
  if (pastWall())
1791
- return first ?? { result, inst: at };
1792
- first ??= { result, inst: at };
1793
- const mw = modelOf(result), more = mw && round < modelRounds && cap > 0 ? modelInstances(m, laws, at, mw.goal, mw.w) : undefined;
2121
+ return abandon('wall reached');
2122
+ if (!progressBudget && cap <= 0)
2123
+ return abandon('work share exhausted');
2124
+ const confirmation = { confirmed: false };
2125
+ const more = modelInstances(m, laws, at, mw.goal, mw.w, undefined, false, confirmation);
1794
2126
  if (modelsTrace)
1795
- console.error(`[models] round ${round} ${mw ? `model at ${mw.goal.name} (${mw.goal.hyps.length} hyps)` : settled(result) ? 'settled' : 'unsettled'} ${Math.round(costNow() - c0)} cost, cap ${Math.round(cap)}; ${more ? `+${Object.entries(more).map(([n, ks]) => `${n.slice(0, 24)}:${ks.length - (at[n]?.length ?? 0)}`).filter(x => !x.endsWith(':0')).join(' ')}` : 'no more'}`);
1796
- if (!more)
2127
+ console.error(`[models] round ${round} ${mw.goal.name}: ${confirmation.confirmed ? 'confirmed' : confirmation.why}, cap ${Math.round(cap)}`);
2128
+ if (confirmation.confirmed)
1797
2129
  return { result, inst: at };
2130
+ if (pastWall())
2131
+ return abandon('wall reached');
2132
+ if (rounds !== 'progress' && round >= rounds)
2133
+ return abandon('round limit reached');
2134
+ if (!more || sameInstances(at, more))
2135
+ return abandon(confirmation.why ?? 'no eligible progress');
1798
2136
  at = more;
1799
2137
  }
1800
2138
  }
@@ -2092,7 +2430,7 @@ export function instancesFor(m, laws, build, opts = {}) {
2092
2430
  const reads = opts.reads ?? (!opts.seed || shifts(m) || laws.some(l => l.keys?.length) || pairFlags(m));
2093
2431
  for (let round = 0; round < 2 && !pastWall(); round++) {
2094
2432
  if (m.facts?.length)
2095
- inst = withFacts(m, inst, fnKeys(m, build(inst)));
2433
+ inst = hasFunctionInstances(m) ? extendFunctionInstances(m, inst, build(inst), (rest, prior, goals) => withFacts(rest, prior, fnKeys(rest, goals))) : withFacts(m, inst, fnKeys(m, build(inst)));
2096
2434
  if (reads) {
2097
2435
  const { keys, byMap } = mapReads(build(inst));
2098
2436
  inst = union(withReads(laws, inst, keys, opts.focus ?? [], byMap, Object.keys(m.fns ?? {})), flagInstances(m, keys, opts.focus), m);
@@ -2319,7 +2657,8 @@ export function proveLaws(m, laws) {
2319
2657
  const out = chooseWitnesses(laws, l => l.holds, l => (l.forall ? [l.forall] : []), m, ls => { const r = proveLawsAsGiven(m, ls); return r.proven && r.checked; }, (l, holds) => ({ ...l, holds, stated: l.stated ?? l.holds }));
2320
2658
  if ('stuck' in out)
2321
2659
  return { proven: false, nodes: 0, leaves: 0, failed: { goal: 'witnesses', stuck: out.stuck }, checked: false };
2322
- return { ...proveLawsAsGiven(m, out.items), laws: out.items };
2660
+ const result = proveLawsAsGiven(m, out.items);
2661
+ return retainFrom({ ...result, laws: out.items }, [result], { kind: 'some-key', originalLaws: laws, resolvedLaws: out.items });
2323
2662
  }
2324
2663
  // One law's two goals, every law assumed (core/infer.ts adds laws one at a time and reproves only what isn't proven
2325
2664
  // yet); not a proof of the set, which proveLaws gives. Laws with some key go through proveLaws.
@@ -2342,12 +2681,14 @@ const pointed = (laws, f) => {
2342
2681
  };
2343
2682
  // (a probe's hook: each decision with its machine, set, index and ms)
2344
2683
  export const decideLawHook = {};
2345
- export function decideLaw(m, laws, i, rounds = modelRounds) {
2346
- if (!decideLawHook.on)
2347
- 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);
2350
- return out;
2684
+ export function decideLaw(m, laws, i, rounds = effectiveModelRounds()) {
2685
+ return withModelRounds(rounds, () => {
2686
+ if (!decideLawHook.on)
2687
+ return decideLaw0(m, laws, i, rounds);
2688
+ const t0 = traceNow(), out = decideLaw0(m, laws, i, rounds);
2689
+ decideLawHook.on(m, laws, i, out, traceNow() - t0);
2690
+ return out;
2691
+ });
2351
2692
  }
2352
2693
  // (why decideLaw last answered nothing: `refuted`, the abstraction refuted a goal whose core's proof didn't finish, a
2353
2694
  // goal the CDCL search after it would find no quicker)
@@ -2360,7 +2701,7 @@ function decideLaw0(m, laws, i, rounds) {
2360
2701
  return withPatterns(m, laws, () => {
2361
2702
  if (!eprScope.patterns)
2362
2703
  return undefined;
2363
- const out = settled(m, laws, i, rounds, false);
2704
+ const out = settled(m, laws, i, rounds, false, 'decision');
2364
2705
  // (a proof's support: the laws its goals' proofs read)
2365
2706
  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
2707
  });
@@ -2368,21 +2709,59 @@ function decideLaw0(m, laws, i, rounds) {
2368
2709
  // (GDP_MEMO_CAP: how many machines' decisions are kept, 4 by default; the hits and misses counted for the engine's trace)
2369
2710
  const memoCap = Number(env.GDP_MEMO_CAP ?? 4);
2370
2711
  export const memoHits = { n: 0, miss: 0, setKey: '', setJson: '' };
2712
+ 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
2713
  export const machineKey = (m) => { const s = JSON.stringify(m); let h = 0; for (let i = 0; i < s.length; i++)
2372
2714
  h = (h * 31 + s.charCodeAt(i)) | 0; return `${s.length}:${h}`; };
2373
2715
  const memos = new Map(), machineText = new WeakMap(), lawText = new WeakMap();
2716
+ // Alpha hits are untrusted hints: non-exact proofs are checked locally; non-exact models go cold.
2374
2717
  // (texts up to a renaming of fresh names, x$12: a rule's machine and kinds' laws are made again with
2375
2718
  // fresh binders, so the same machine had another text each time and no decision was found again; GDP_MEMO_ALPHA=0 off)
2376
2719
  const alpha = env.GDP_MEMO_ALPHA !== '0';
2377
2720
  const alphaText = (s) => { if (!alpha)
2378
2721
  return s; const to = new Map(); return s.replace(/([A-Za-z_?]+)\$(\d+)/g, (w, p) => { let r = to.get(w); if (!r)
2379
2722
  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; };
2382
- function memoOf(m) {
2383
- let key = machineText.get(m);
2384
- if (key === undefined)
2385
- machineText.set(m, (key = alphaText(JSON.stringify(m))));
2723
+ const textsOfLaw = (l) => { let t = lawText.get(l); if (!t) {
2724
+ const exact = JSON.stringify([l.holds, l.forall ?? null, l.keys ?? null]);
2725
+ lawText.set(l, (t = { exact, text: alphaText(exact) }));
2726
+ } return t; };
2727
+ const textOfLaw = (l) => textsOfLaw(l).text;
2728
+ const textsOfMachine = (m) => { let t = machineText.get(m); if (!t) {
2729
+ const exact = JSON.stringify(m);
2730
+ machineText.set(m, (t = { exact, text: alphaText(exact) }));
2731
+ } return t; };
2732
+ // Exact query context belongs to each entry, not to a shared alpha-keyed machine slot.
2733
+ const memoContext = (m, laws) => ({ machine: textsOfMachine(m).exact, laws: new Map(laws.map(l => [l.name, textsOfLaw(l).exact])) });
2734
+ const memoAttempt = () => ({ cold: new Set(), reused: new Set(), fresh: new Map() });
2735
+ function exactMemoContext(context, m, laws) {
2736
+ return context.machine === textsOfMachine(m).exact && laws.every(l => context.laws.get(l.name) === textsOfLaw(l).exact);
2737
+ }
2738
+ function discardMemo(memo, name, attempt, reason = 'proof') {
2739
+ memo.proven.delete(name);
2740
+ memo.models.delete(name);
2741
+ if (!attempt.cold.has(name)) {
2742
+ attempt.cold.add(name);
2743
+ memoReuseStats.coldRetries++;
2744
+ memoReuseStats[`${reason}Retries`]++;
2745
+ }
2746
+ }
2747
+ function checkMemoLaw(m, laws, i, cached) {
2748
+ const proofs = {}, byName = new Map(laws.map(l => [l.name, l]));
2749
+ // Widen usually makes fresh leaves, but its grow fallback may return a cached tree.
2750
+ // New tree objects drop every goal-local WeakMap annotation before source extraction.
2751
+ const currentTree = (t) => 'leaf' in t ? { ...t } : { ...t, yes: currentTree(t.yes), no: currentTree(t.no) };
2752
+ for (const g of obligations(m, laws, { [laws[i].name]: cached.inst }, i)) {
2753
+ const p = cached.proofs[g.name], widened = p && widen(p.part, g, p.tree);
2754
+ const tree = widened && currentTree(widened);
2755
+ if (!tree || !check(g, tree))
2756
+ return undefined;
2757
+ // Read current row sources, never the cached support/tuple metadata.
2758
+ const src = sourcesOf(m, laws, cached.inst, g, usedHyps(g, tree));
2759
+ 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 } : {}) };
2760
+ }
2761
+ return { text: textOfLaw(laws[i]), context: memoContext(m, laws), inst: cached.inst, proofs };
2762
+ }
2763
+ function memoOf(m, rounds = effectiveModelRounds()) {
2764
+ const key = `${textsOfMachine(m).text}\0model-rounds:${rounds}`;
2386
2765
  let memo = memos.get(key);
2387
2766
  if (!memo) {
2388
2767
  if (memos.size >= memoCap)
@@ -2394,24 +2773,56 @@ function memoOf(m) {
2394
2773
  const stands = (p, byName) => [...p.uses].every(([n, t]) => { const l = byName.get(n); return !!l && textOfLaw(l) === t; });
2395
2774
  // 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
2775
  // this one): else its goals settled again, those whose proofs stand kept.
2397
- function settled(m, laws, i, rounds, usual) {
2398
- 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;
2776
+ function settled(m, laws, i, rounds, usual, consumer = 'decision', attempt = memoAttempt()) {
2777
+ const law = laws[i], memo = memoOf(m, rounds), byName = new Map(laws.map(l => [l.name, l])), text = textOfLaw(law);
2778
+ if (attempt.fresh.has(law.name))
2779
+ return attempt.fresh.get(law.name);
2780
+ const was = !attempt.cold.has(law.name) ? memo.proven.get(law.name) : undefined;
2781
+ let prev = was?.text === text ? was : undefined;
2782
+ const exact = prev && exactMemoContext(prev.context, m, laws);
2400
2783
  if (prev && Object.values(prev.proofs).every(p => stands(p, byName))) {
2401
- memoHits.n++;
2402
- return prev;
2784
+ let valid = exact ? prev : undefined;
2785
+ if (!exact) {
2786
+ memoReuseStats.hitChecks++;
2787
+ valid = checkMemoLaw(m, laws, i, prev);
2788
+ }
2789
+ if (valid) {
2790
+ memoHits.n++;
2791
+ memoReuseStats[`${consumer}Hits`]++;
2792
+ attempt.reused.add(law.name);
2793
+ return valid;
2794
+ }
2795
+ memoReuseStats.hitCheckFailures++;
2796
+ discardMemo(memo, law.name, attempt);
2797
+ prev = undefined;
2798
+ }
2799
+ else if (prev && !exact) {
2800
+ // A partial renamed proof is not a verdict: stale instances/kept goals must not end this attempt.
2801
+ memoReuseStats.discardedSeeds++;
2802
+ discardMemo(memo, law.name, attempt, 'seed');
2803
+ prev = undefined;
2403
2804
  }
2404
2805
  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;
2806
+ const mo = !attempt.cold.has(law.name) ? memo.models.get(law.name) : undefined;
2807
+ if (mo && (!strict(usual) || mo.strict) && mo.text === text && laws.every(l => mo.set.get(l.name) === textOfLaw(l))) {
2808
+ if (exactMemoContext(mo.context, m, laws)) {
2809
+ memoReuseStats.modelHits++;
2810
+ return mo.model;
2811
+ }
2812
+ // A renamed negative is only a hint. Do not let it bypass the one native cold attempt.
2813
+ memoReuseStats.modelsIgnored++;
2814
+ discardMemo(memo, law.name, attempt, 'model');
2815
+ prev = undefined;
2816
+ }
2408
2817
  const out = settle(m, laws, i, rounds, usual, prev);
2409
2818
  const cap = (x) => { if (x.size >= 4096)
2410
2819
  x.clear(); return x; };
2411
2820
  if (out && 'proofs' in out)
2412
2821
  cap(memo.proven).set(law.name, out);
2413
- 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)])) });
2822
+ else if (out?.stuck === 'sat')
2823
+ 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)])) });
2824
+ if (attempt.cold.has(law.name))
2825
+ attempt.fresh.set(law.name, out);
2415
2826
  return out;
2416
2827
  }
2417
2828
  // The fast path's machines: no history, sums or "there exists" (their goals are other machines' or need witnesses).
@@ -2464,18 +2875,16 @@ function settle(m, laws, i, rounds, usual, prev) {
2464
2875
  inst = triggered(plainOf(m), laws, inst, i2 => obligations(m, laws, { [law.name]: i2 }, i), law.forall ? [`${law.forall}#`] : []);
2465
2876
  const proofs = Object.fromEntries(Object.entries(prev?.proofs ?? {}).filter(([, p]) => stands(p, byName)));
2466
2877
  const unknown = (g, why = 'past the search\'s end') => (usual ? { goal: g.name, stuck: 'unknown', why } : undefined);
2467
- // (past the `rounds` model rounds, each round within the caller's deadline, its model the answer where the round can't
2468
- // finish: a model of fewer instances is still one of the goal as it was asked)
2878
+ // No model of fewer instances survives an unfinished refinement round.
2469
2879
  const end = withinDeadline(Infinity);
2470
- let last;
2471
2880
  for (let round = 0;; round++) {
2472
2881
  let more;
2473
- const late = round > rounds ? () => pastWall() || pastEprCap() || clock() > end : () => pastWall() || pastEprCap();
2882
+ const late = rounds !== 'progress' && round > rounds ? () => pastWall() || pastEprCap() || clock() > end : () => pastWall() || pastEprCap();
2474
2883
  for (const g of obligations(m, laws, { [law.name]: inst }, i)) {
2475
2884
  if (proofs[g.name])
2476
2885
  continue;
2477
2886
  if (late())
2478
- return strict(usual) ? unknown(g) : last ?? unknown(g);
2887
+ return unknown(g, 'unconfirmed model: search end reached');
2479
2888
  // (a wide goal decided over parts (growWide), each part by the EPR path: the abstraction of the whole is quadratic in
2480
2889
  // its cells, i4's engine set's step goal of 7,590 hypotheses ran 19M units past its caller's end and 10 GB)
2481
2890
  let o = !eprScope.patterns ? undefined : wideFor(g) && tupledScope() ? eprWide(g, late) ?? withEprCap(wideEprUnits, () => eprFirst(g, { nodes: 0, until: clock() + 4_000 }, false, late)) : eprFirst(g, { nodes: 0, until: clock() + 4_000 }, false, late);
@@ -2491,8 +2900,8 @@ function settle(m, laws, i, rounds, usual, prev) {
2491
2900
  return undefined;
2492
2901
  }
2493
2902
  }
2494
- else if (!o && (last || !usual))
2495
- return strict(usual) ? undefined : last;
2903
+ else if (!o && !usual)
2904
+ return undefined;
2496
2905
  // (the usual search, the EPR path not asked again)
2497
2906
  if (!o) {
2498
2907
  const busy = eprScope.busy;
@@ -2511,28 +2920,29 @@ function settle(m, laws, i, rounds, usual, prev) {
2511
2920
  continue;
2512
2921
  }
2513
2922
  if (o.stuck !== 'sat' || !o.witness)
2514
- return strict(usual) ? unknown(g, o.why) : last ?? unknown(g, o.why);
2515
- last = { goal: g.name, stuck: 'sat', witness: o.witness, ...(o.diagram ? { diagram: o.diagram } : {}), why: 'a model' };
2516
- // (strict, decideLaw's: a model is returned only where confirmed, no assumed law broken at it over its own domain;
2517
- // one that breaks only instances of another sort, or that the rounds or the wall cut off, is no answer)
2518
- const capped = !(round < rounds || (round < 4 * rounds && end !== Infinity && clock() < end)), raw = capped ? undefined : modelInstances(m, laws, inst, g, o.witness, undefined, true);
2519
- if (!capped && !raw)
2520
- return last;
2521
- more = raw && bySort(m, laws, raw);
2522
- const count = (x) => Object.values(x).reduce((s2, ks) => s2 + ks.length, 0);
2523
- if (strict(usual) && (capped || pastWall() || !more || count(more) <= count(inst))) {
2923
+ return unknown(g, o.why);
2924
+ const unconfirmed = (why) => {
2524
2925
  decideNote.hint = { goal: g.name, witness: o.witness };
2525
- return undefined;
2526
- }
2527
- // (the model's only broken instances another sort's: the next round would find it again; decideLaw's no answer)
2528
- if (more && count(more) <= count(inst))
2529
- return usual ? last : undefined;
2530
- if (!more || pastWall())
2531
- return last;
2926
+ return unknown(g, `unconfirmed model: ${why}`);
2927
+ };
2928
+ const capped = rounds !== 'progress' && !(round < rounds || (round < 4 * rounds && end !== Infinity && clock() < end));
2929
+ if (capped || pastWall())
2930
+ return unconfirmed(capped ? 'round limit reached' : 'wall reached');
2931
+ const confirmation = { confirmed: false };
2932
+ const raw = modelInstances(m, laws, inst, g, o.witness, undefined, true, confirmation);
2933
+ if (modelsTrace)
2934
+ console.error(`[models] settle round ${round} ${g.name}: ${confirmation.confirmed ? 'confirmed' : confirmation.why}`);
2935
+ if (confirmation.confirmed)
2936
+ return { goal: g.name, stuck: 'sat', witness: o.witness, ...(o.diagram ? { diagram: o.diagram } : {}), why: 'a confirmed model' };
2937
+ more = raw && bySort(m, laws, raw);
2938
+ if (pastWall())
2939
+ return unconfirmed('wall reached');
2940
+ if (!more || sameInstances(more, inst))
2941
+ return unconfirmed(confirmation.why ?? 'no eligible progress');
2532
2942
  break;
2533
2943
  }
2534
2944
  if (!more)
2535
- return { text: textOfLaw(law), inst, proofs };
2945
+ return { text: textOfLaw(law), context: memoContext(m, laws), inst, proofs };
2536
2946
  inst = more;
2537
2947
  }
2538
2948
  }
@@ -2559,52 +2969,64 @@ export function proveSetFast(m, laws) {
2559
2969
  if (!fastShape(m, laws))
2560
2970
  return someLaws(laws) && fastShape(m, laws.map(l => ({ name: l.name, holds: l.holds }))) ? proveSome(m, laws, { whole: proveSetFast }) : proveLaws(m, laws);
2561
2971
  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;
2972
+ const attempt = memoAttempt();
2973
+ const run = () => {
2974
+ const at = [];
2975
+ for (let i = 0; i < laws.length; i++) {
2976
+ const out = settled(m, laws, i, effectiveModelRounds(), true, 'set', attempt);
2977
+ if (!('proofs' in out))
2978
+ 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 } : {}) } };
2979
+ at.push(out);
2980
+ }
2981
+ const instances = {}, trees = {}, byName = new Map(laws.map(l => [l.name, l]));
2982
+ let nodes = 0, leaves = 0;
2983
+ for (const [i, law] of laws.entries()) {
2984
+ // (each law about keys at the tuples the proofs read; all of them where a proof's sources weren't read)
2985
+ const s = at[i], ps = Object.values(s.proofs), all = ps.some(p => !p.tuples);
2986
+ const inst = all ? s.inst : Object.fromEntries(Object.entries(s.inst).map(([n, ks]) => {
2987
+ const l = byName.get(n), k = l ? widthOf(l) : 1;
2988
+ 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)))))];
2989
+ }));
2990
+ instances[law.name] = inst;
2991
+ for (const g of obligations(m, laws, { [law.name]: inst }, i)) {
2992
+ const p = s.proofs[g.name];
2993
+ let tree = p && widen(p.part, g, p.tree);
2994
+ if (!tree) {
2995
+ const o = grow(g);
2996
+ if (!('tree' in o))
2997
+ return stuckAt(g, o, nodes, leaves);
2998
+ tree = o.tree;
2999
+ nodes += o.nodes;
3000
+ }
3001
+ trees[g.name] = tree;
3002
+ leaves += countLeaves(tree);
2588
3003
  }
2589
- trees[g.name] = tree;
2590
- leaves += countLeaves(tree);
2591
3004
  }
3005
+ const proof = { instances, trees };
3006
+ return retainFamily({ proven: true, nodes, leaves, checked: checkLaws(m, laws, proof), proof }, m, laws, proof);
3007
+ };
3008
+ const out = run(), retry = [...attempt.reused].filter(name => !attempt.cold.has(name));
3009
+ if ((!out.proven || !out.checked) && retry.length) {
3010
+ memoReuseStats.wholeRetries++;
3011
+ const memo = memoOf(m);
3012
+ for (const name of retry)
3013
+ discardMemo(memo, name, attempt);
3014
+ return run();
2592
3015
  }
2593
- const proof = { instances, trees };
2594
- return { proven: true, nodes, leaves, checked: checkLaws(m, laws, proof), proof };
3016
+ return out;
2595
3017
  }));
2596
3018
  }
2597
3019
  export function proveLaw(m, laws, i) {
2598
3020
  if (laws.some(l => someKeys(l.holds).length) || someLaws(laws)) {
2599
3021
  const r = proveLaws(m, laws);
2600
- return r.proven ? { proven: true } : { proven: false, goal: r.failed.goal, stuck: r.failed.stuck, ...(r.failed.witness ? { witness: r.failed.witness } : {}) };
3022
+ return r.proven ? { proven: true } : { proven: false, goal: r.failed.goal, stuck: r.failed.stuck, ...(r.failed.witness ? { witness: r.failed.witness } : {}), ...(r.failed.why ? { why: r.failed.why } : {}) };
2601
3023
  }
2602
3024
  // (the thinned goals too by the EPR path where the rule's keys are composed: withModels' scope, entered here; first
2603
3025
  // the law settled by the EPR path as decideLaw settles it, kept where it stands: a caller's verdict rests on its final
2604
3026
  // 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
3027
  // against 25 s to unknown here)
2606
3028
  return withPatterns(m, laws, () => {
2607
- const out = eprScope.patterns && fastShape(m, laws) ? settled(m, laws, i, modelRounds, false) : undefined;
3029
+ const out = eprScope.patterns && fastShape(m, laws) ? settled(m, laws, i, effectiveModelRounds(), false, 'law') : undefined;
2608
3030
  if (out && 'proofs' in out)
2609
3031
  return { proven: true };
2610
3032
  if (out?.stuck === 'sat')
@@ -2631,7 +3053,7 @@ function proveOne(m, laws, i) {
2631
3053
  const memo = memoOf(m);
2632
3054
  if (memo.proven.size >= 4096)
2633
3055
  memo.proven.clear();
2634
- memo.proven.set(law.name, { text: textOfLaw(law), inst: at, proofs });
3056
+ memo.proven.set(law.name, { text: textOfLaw(law), context: memoContext(m, laws), inst: at, proofs });
2635
3057
  };
2636
3058
  const few = triggered(pm, laws, inst, i2 => obligations(m, laws, { [law.name]: i2 }, i), law.forall ? [`${law.forall}#`] : []);
2637
3059
  if (!sameInstances(few, inst)) {
@@ -2655,10 +3077,10 @@ function proveOne(m, laws, i) {
2655
3077
  }
2656
3078
  }
2657
3079
  // (a model breaking a law at a tuple of the goal's keys: those added, the law asked again)
2658
- const { result: a, inst: at } = withModels(m, laws, inst, i2 => obligations(m, laws, { [law.name]: i2 }, i), growAll, grownModel, grownSettled);
3080
+ const { result: a, inst: at } = withModels(m, laws, inst, i2 => obligations(m, laws, { [law.name]: i2 }, i), growAll, grownModel, grownSettled, grownUnknown);
2659
3081
  if (!a.out)
2660
3082
  remember(at, a.done);
2661
- return a.out ? { proven: false, goal: a.goal.name, stuck: a.out.stuck, ...(a.out.witness ? { witness: a.out.witness } : {}), ...(a.out.diagram ? { diagram: a.out.diagram } : {}) } : { proven: true };
3083
+ return a.out ? { proven: false, goal: a.goal.name, stuck: a.out.stuck, ...(a.out.witness ? { witness: a.out.witness } : {}), ...(a.out.diagram ? { diagram: a.out.diagram } : {}), ...(a.out.why ? { why: a.out.why } : {}) } : { proven: true };
2662
3084
  }
2663
3085
  function growAll(gs) {
2664
3086
  const done = {};
@@ -2674,7 +3096,8 @@ function growAll(gs) {
2674
3096
  return { done, n, lv };
2675
3097
  }
2676
3098
  const grownModel = (x) => (x.out?.stuck === 'sat' && x.out.witness ? { goal: x.goal, w: x.out.witness } : undefined);
2677
- const grownSettled = (x) => !x.out || x.out.stuck === 'sat';
3099
+ const grownSettled = (x) => !x.out || (x.out.stuck === 'sat' && !!x.out.witness);
3100
+ const grownUnknown = (x, why) => ({ ...x, out: { stuck: 'unknown', path: x.out?.path ?? new Map(), why } });
2678
3101
  // Each law's keys only at keys of their sort (Ivy's sorts; untrusted: an instance left out only weakens a goal, and a
2679
3102
  // set's proof is checked over its own instances). A sort is a class of a union-find over places: each part of a map's
2680
3103
  // key (by its pattern, `M:map:i`), a map's whole key where a law's key is the whole key (`K:map`), a function's
@@ -2684,21 +3107,13 @@ const grownSettled = (x) => !x.out || x.out.stuck === 'sat';
2684
3107
  // anchored sort is left out of the law's tuples there; a composed term is a whole key, of the map whose pattern its
2685
3108
  // factors are. GDP_SORTED=0 keeps every instance.
2686
3109
  const sortedOn = env.GDP_SORTED !== '0';
2687
- // decideLaw's models confirmed only (GDP_STRICT=1; off by default: decentralized lock's rounds then lean on the proof
2688
- // path where an unconfirmed model used to answer, 27-36 s against 13-17 s): a model is returned where no assumed law is
2689
- // broken at it over its own domain, else nothing (research/protocols/engine/DESIGN.md, gen/ring)
2690
- let strictOn = false;
2691
- // (decideLaw's models are confirmed ones only, always: an unconfirmed one, at the deadline or past the model rounds, was
2692
- // wrong against Z3 on 43 of wo's 143 top-down goals; GDP_STRICT=0 gives the old answer)
2693
- const strict = (usual) => !usual && (strictOn || env.GDP_STRICT !== '0');
2694
- // (strict models for a caller's own decisions: the engine's top-down phase, whose drops an unconfirmed model would make wrong)
2695
- export const withStrict = (f) => { const o = strictOn; strictOn = true; try {
2696
- return f();
2697
- }
2698
- finally {
2699
- strictOn = o;
2700
- } };
2701
- // (by machine and by the law set's names: one machine is asked with many sets)
3110
+ // SAT admission is always strict, including the usual fallback and cached models.
3111
+ // GDP_STRICT=0 must not turn an unfinished refinement into a deletion witness.
3112
+ const strict = (_usual) => true;
3113
+ // Compatibility scope: all callers now have this conservative admission policy.
3114
+ export const withStrict = (f) => f();
3115
+ // By immutable machine and ordered, exact law context, including all binding metadata.
3116
+ export const sortMemoStats = { hits: 0, misses: 0 };
2702
3117
  const sortsMemo = new WeakMap();
2703
3118
  const sortPlacesOn = env.GDP_SORT_PLACES !== '0';
2704
3119
  function sortsOf(m, laws) {
@@ -2839,13 +3254,16 @@ function instanceSortGuard(m, laws) {
2839
3254
  let byLaws = sortsMemo.get(m);
2840
3255
  if (!byLaws)
2841
3256
  sortsMemo.set(m, (byLaws = new Map()));
2842
- const lk = laws.map(l => l.name).join('\u0001');
3257
+ const lk = JSON.stringify(laws.map(l => [l.name, textsOfLaw(l).exact]));
2843
3258
  let s = byLaws.get(lk);
2844
3259
  if (!s) {
3260
+ sortMemoStats.misses++;
2845
3261
  if (byLaws.size >= 64)
2846
3262
  byLaws.clear();
2847
3263
  byLaws.set(lk, (s = sortsOf(m, laws)));
2848
3264
  }
3265
+ else
3266
+ sortMemoStats.hits++;
2849
3267
  const S = s;
2850
3268
  const keysOf = (n) => {
2851
3269
  if (n.startsWith('?')) {
@@ -2932,12 +3350,12 @@ function proveLawsAsGiven(m, laws, defer) {
2932
3350
  const modes = cyclicOn() || certOn(), hist = modes && m.history ? historyMachine(m) : undefined, mc = hist ? hist.machine : m;
2933
3351
  const why = modes ? (sumsWhy(m) ?? uncoveredWhy(mc, laws)) : undefined, cert = certOn() && !why;
2934
3352
  usualCheck.on = !cert && !defer;
2935
- const t0 = performance.now(), out = fast ?? (() => { try {
3353
+ const t0 = traceNow(), out = fast ?? (() => { try {
2936
3354
  return proveThinned(m, laws, { ...instances });
2937
3355
  }
2938
3356
  finally {
2939
3357
  usualCheck.on = true;
2940
- } })(), usualMs = performance.now() - t0;
3358
+ } })(), usualMs = traceNow() - t0;
2941
3359
  if (out.proof)
2942
3360
  usualProof.last = { m, laws, proof: out.proof };
2943
3361
  const inst = out.proof?.instances ?? instances;
@@ -2979,6 +3397,8 @@ function proveLawsAsGiven(m, laws, defer) {
2979
3397
  defer(finish);
2980
3398
  else
2981
3399
  finish();
3400
+ if (!defer)
3401
+ retainFamily(out, m, laws, out.proof);
2982
3402
  return out;
2983
3403
  }
2984
3404
  // Whether the usual proof's trees are checked (off while GDP_CERT=cyclic makes the certificate a cyclic proof).
@@ -3001,7 +3421,7 @@ function thinned(m, laws, instances) {
3001
3421
  console.error(`[models] law ${law.name}: ${Object.values(full).reduce((a, ks) => a + ks.length, 0)} keys, ${Object.values(few).reduce((a, ks) => a + ks.length, 0)} triggered`);
3002
3422
  // (thinned instances first, then the full ones; each asked again at the tuples its models ask for)
3003
3423
  for (const inst of sameInstances(few, full) ? [full] : [few, full]) {
3004
- const { result: a, inst: at } = withModels(m, laws, inst, i2 => obligations(m, laws, { ...instances, [law.name]: i2 }, i), growAll, grownModel, grownSettled);
3424
+ const { result: a, inst: at } = withModels(m, laws, inst, i2 => obligations(m, laws, { ...instances, [law.name]: i2 }, i), growAll, grownModel, grownSettled, grownUnknown);
3005
3425
  instances[law.name] = at;
3006
3426
  if (inst === full)
3007
3427
  fulls[law.name] = at;
@@ -3088,7 +3508,7 @@ export function stepLawInstances(m, laws) {
3088
3508
  function proveStepLawsAsGiven(m, laws, stepLaws, base, ready = () => { }) {
3089
3509
  if (!base.proof)
3090
3510
  return { proven: false, nodes: base.nodes, leaves: base.leaves, checked: false };
3091
- const t0 = performance.now();
3511
+ const t0 = traceNow();
3092
3512
  const plain = plainOf(m);
3093
3513
  // 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
3514
  // law's later frames read keys no other step law has); where positions shift or a law is about several keys, the
@@ -3105,7 +3525,7 @@ function proveStepLawsAsGiven(m, laws, stepLaws, base, ready = () => { }) {
3105
3525
  const ownMs = {};
3106
3526
  for (const sl of stepLaws)
3107
3527
  for (const goal of stepLawObligations(m, laws, perStep[sl.name] ?? instances, sl)) {
3108
- const g0 = performance.now();
3528
+ const g0 = traceNow();
3109
3529
  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
3530
  let out = sameInstances(few, full) ? grow(goal) : grow(stepLawObligations(m, laws, few, sl).find(g => g.name === goal.name) ?? goal);
3111
3531
  if ('tree' in out && !sameInstances(few, full))
@@ -3139,12 +3559,12 @@ function proveStepLawsAsGiven(m, laws, stepLaws, base, ready = () => { }) {
3139
3559
  trees[goal.name] = out.tree;
3140
3560
  nodes += out.nodes;
3141
3561
  leaves += countLeaves(out.tree);
3142
- ownMs[sl.name] = (ownMs[sl.name] ?? 0) + performance.now() - g0;
3562
+ ownMs[sl.name] = (ownMs[sl.name] ?? 0) + traceNow() - g0;
3143
3563
  }
3144
3564
  // (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();
3565
+ const r0 = traceNow();
3146
3566
  ready();
3147
- const usual0 = t0 + performance.now() - r0;
3567
+ const usual0 = t0 + traceNow() - r0;
3148
3568
  const proof = { laws: base.proof, instances, ...(Object.keys(perStep).length ? { perStep } : {}), trees };
3149
3569
  // Step laws of a machine the cyclic instances cover (one step, or several over no map) are translated with the laws
3150
3570
  // (core/cyclic.ts); the rest are counted as no instance's.
@@ -3164,7 +3584,7 @@ function proveStepLawsAsGiven(m, laws, stepLaws, base, ready = () => { }) {
3164
3584
  if (!why && one.length && out.checked) {
3165
3585
  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
3586
  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;
3587
+ const usualMs = traceNow() - usual0;
3168
3588
  if (cyclicOn())
3169
3589
  crossCyclic('step law', m.name, true, undefined, usualMs, translatedOf(all));
3170
3590
  // (where the step laws' proof together isn't made, each step law's alone: one the translation misses leaves the
@@ -3195,7 +3615,7 @@ function proveStepLawsAsGiven(m, laws, stepLaws, base, ready = () => { }) {
3195
3615
  const b = machineNodes(plain, laws, base.proof.instances);
3196
3616
  return proveCyclic(b.facts, [...b.specs, ...searchedStepNodes(plain, laws, rest.map(sl => ({ law: sl, instances: perStep[sl.name] ?? instances })), b.facts, b.specs)]);
3197
3617
  };
3198
- const c = certCyclic('step law', m.name, undefined, searchedSteps, performance.now() - usual0);
3618
+ const c = certCyclic('step law', m.name, undefined, searchedSteps, traceNow() - usual0);
3199
3619
  for (const sl of c.checked ? [] : rest)
3200
3620
  miss(sl, `${restWhy(sl)}: ${c.why}`);
3201
3621
  }
@@ -3207,7 +3627,7 @@ function proveStepLawsAsGiven(m, laws, stepLaws, base, ready = () => { }) {
3207
3627
  // Progress (kernel.ts's progressObligations): the laws proven first, then each goal, the every-key laws assumed at every
3208
3628
  // key the goals read a map at.
3209
3629
  export function proveProgress(m, laws, p) {
3210
- const t0 = performance.now(), base = proveLaws(m, laws);
3630
+ const t0 = traceNow(), base = proveLaws(m, laws);
3211
3631
  if (!base.proven || !base.checked)
3212
3632
  return { proven: false, nodes: base.nodes, leaves: base.leaves, ...(base.failed ? { failed: base.failed } : {}), checked: false };
3213
3633
  const ls = base.laws ?? laws;
@@ -3250,7 +3670,7 @@ export function proveProgress(m, laws, p) {
3250
3670
  });
3251
3671
  return found?.out ?? last;
3252
3672
  };
3253
- const c = certCyclic('progress', m.name, translated, certSearch() ? allowed : undefined, performance.now() - t0);
3673
+ const c = certCyclic('progress', m.name, translated, certSearch() ? allowed : undefined, traceNow() - t0);
3254
3674
  if (!c.checked) {
3255
3675
  const why = `a request allowed: ${c.why}`;
3256
3676
  uncovered('progress', m.name, why);