Repository navigation
perf: memoize the control information of do sequences - #16557
Merged
Merged
Conversation
`DoElemCont.mkBindUnlessPure` abstracts the bound variable in the continuation with `mkLambdaFVars`. The continuation refers to the rest of the block through assigned metavariables, and `mkLambdaFVars` follows these assignments without storing the result, so every bind traversed the whole rest of the block. Calling `instantiateMVars` first stores the instantiated values in the assignments. On 400 nested levels of `match (← do let a ← g i; pure a) with | .some r => pure r | none => (do …)`, the instruction count drops from 15.1G to 7.0G. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01D74FF3KTi9nZLQoDBeJNvL
This adds nine `elab_bench` files. Each one generates a `do` block of a size given by `TEST_BENCH` and elaborates it. Each file exercises one code path of the `do` elaborator: binds, join points, postponement, `try`, loops, branches and nested actions.
The benchmarks build their `do` blocks with syntax quotations and `mkIdent` and elaborate them with `elabCommand`, so the measurement contains no parsing of generated source.
`tests/elab/do_scaling.lean` elaborates 13 families of `do` blocks at sizes n, 2n and 4n and bounds the ratio of the heartbeat differences. The bound is 2.5 for the families of linear cost and slightly above the measured ratio for the others.
Every `if`, `match`, `for`, `try` and `repeat` element infers the `ControlInfo` of its sub-blocks, so a block nested `n` levels deep visited its innermost elements `n` times. A `ControlInfoCache` in the `do` elaboration context now stores the `ControlInfo` of every `doSeq` node by its address. `InferControlInfo.ofElem` also expands macros under `withRef` of the element, so that the quotations of the expansion take their source position from the element instead of from the enclosing element.
Member
Author
|
!bench |
|
Benchmark results for dd23129 against c59550c are in. No significant results found. @sgraf812
New metrics (10✅, 11🟥)
Medium changes (1✅)
Small changes (31✅, 11🟥)
|
The `Hashable` and `BEq` instances of `Lean.Ptr` are now safe, so `ControlInfoCache` can be a `Std.HashMap (Ptr DoSeq) ControlInfo`.
…an opaque type `ControlInfoMap` is an opaque type whose operations `empty`, `find?` and `insert` are implemented by a `PtrMap DoSeq ControlInfo`, so the instances of `Lean.Ptr` stay unsafe.
sgraf812
marked this pull request as ready for review
November 19, 2026 09:34
…cache # Conflicts: # tests/elab/do_scaling.lean
Rob23oba
pushed a commit
to leanprover/downstream-lean4
that referenced
this pull request
Nov 21, 2026
…Do.Context.controlInfoCache` (#271) Run [44844350878](https://github.com/leanprover/downstream-lean4/actions/runs/44844350878) on `nightly-2026-11-20`. This fixes the run's **new** breakage, `batteries` (critical), which took `aesop`, `mathlib4` and `cslib` down with it as skips. The rest of the red set is carried by PRs that are already open — `reference-manual` by #268, and `mathlib4` + `repl` by #270 (approved) — so **this PR's own CI stays red on `reference-manual`** until those merge. ## `batteries` — `Do.Context` gained a field, and `#do` builds one by hand [lean4#16557](leanprover/lean4#16557) ("perf: memoize the control information of `do` sequences", @sgraf812, in `nightly-2026-11-20`) added a field with no default to `Lean.Elab.Do.Context`: ```lean /-- The `ControlInfo` of the `doSeq` nodes of this `do` block inferred so far. -/ controlInfoCache : ControlInfoCache ``` The `downstream: update repo batteries` merge at the head of this run then brought in [batteries#1962](leanprover-community/batteries#1962) ("feat: `#do` command", @Rob23oba), whose `elabDoCommandCore` assembles a `Do.Context` itself rather than going through `Do.mkContext`. That file was written against batteries `main`, which still pins `v4.37.0-rc1`, so on the nightly it fails: ``` error: Batteries/Tactic/DoCommand.lean:213:15: Fields missing: `controlInfoCache` ``` `Batteries.Tactic.DoCommand` is reachable from the `Batteries` root module, so this is a critical-repo build failure, and `aesop`, `mathlib4` and `cslib` were all skipped behind it. ### The fix One field, a fresh cache, exactly what core's own `Do.mkContext` writes: ```lean controlInfoCache := ← ControlInfoCache.new ``` A `ControlInfoCache` memoizes the inferred `ControlInfo` of the `doSeq` nodes *within one `do` block*; `#do` elaborates one `doSeq` per invocation, so there is nothing to carry across calls and no reason to park a cache in `DoCommandExtensionState` next to the local context and the `mut` variables. Upstream batteries cannot see this yet: `nightly-testing` is on `nightly-2026-11-20` and carries the same unadapted file (byte-identical), and there is no batteries PR open that mentions `controlInfoCache` or lean4#16557 — so the same fix is wanted there. ### Verified * `batteries`: `lake build --wfail` (531 jobs), `lake test` (including the new `BatteriesTest.do_command`) and `lake lint`. * `aesop`: `lake build --wfail` and `lake test`, the two phases CI skipped (no lint driver). * `mathlib4`: `lake build Mathlib Archive Counterexamples Wanted cache --wfail` (18647 jobs), `lake test --iofail` (19211 jobs) and `lake lint`, with #270's `import-graph` fix applied locally, since `mathlib4` does not parse without it. `repl` was not rebuilt: it is noncritical, and the sites it failed at are #270's. `cslib` is left to `mathlib-nightly-testing` as before. <!-- downstream-watch: unattended --> Co-authored-by: downstream-lean4[bot] <downstream-lean4[bot]@users.noreply.github.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
This PR makes the elaboration time of long
else ifchains indoblocks linear in the number of branches, and it reduces the elaboration time of deeply nestedifandforelements.Every
if,match,for,tryandrepeatelement infers theControlInfoof its sub-blocks before it elaborates them, so a block nestednlevels deep visited its innermost elementsntimes. Thedoelaboration context now holds aControlInfoCachethat maps every visiteddoSeqnode, compared by pointer, to itsControlInfo, and thedoelaborators pass it toinferControlInfoSeqandinferControlInfoElem. Both functions take the cache as an optional argument, so control information handlers that call them stay valid. The map is an opaqueControlInfoMapimplemented by aPtrMap. It keeps every visited node alive until the elaboration of itsdoblock ends, so a pointer identifies one node also across postponement; on an 800-branchelse ifchain the peak memory grows by less than 1 MiB.InferControlInfo.ofElemalso expands macros underwithRefof the element, so that the quotations of the expansion take their source position from the element instead of from the enclosing element.An
else ifchain of 800 branches over 4let mutvariables drops from 9.57G to 3.69G instructions. Intests/elab/do_scaling.lean, theelse ifchain, nestedifand nestedfornow scale linearly.🤖 Generated with Claude Code