Skip to content

perf: memoize the control information of do sequences - #16557

Merged
sgraf812 merged 16 commits into
masterfrom
sg/do-control-info-cache
Nov 19, 2026
Merged

sgraf812 merged 16 commits into
masterfrom
sg/do-control-info-cache

Conversation

@sgraf812

@sgraf812 sgraf812 commented Nov 18, 2026 •

Copy link
Copy Markdown
Member

This PR makes the elaboration time of long else if chains in do blocks linear in the number of branches, and it reduces the elaboration time of deeply nested if and for elements.

Every if, match, for, try and repeat element infers the ControlInfo of its sub-blocks before it elaborates them, so a block nested n levels deep visited its innermost elements n times. The do elaboration context now holds a ControlInfoCache that maps every visited doSeq node, compared by pointer, to its ControlInfo, and the do elaborators pass it to inferControlInfoSeq and inferControlInfoElem. Both functions take the cache as an optional argument, so control information handlers that call them stay valid. The map is an opaque ControlInfoMap implemented by a PtrMap. It keeps every visited node alive until the elaboration of its do block ends, so a pointer identifies one node also across postponement; on an 800-branch else if chain the peak memory grows by less than 1 MiB. 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.

An else if chain of 800 branches over 4 let mut variables drops from 9.57G to 3.69G instructions. In tests/elab/do_scaling.lean, the else if chain, nested if and nested for now scale linearly.

🤖 Generated with Claude Code

sgraf812 and others added 10 commits November 18, 2026 09:13
`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.
@sgraf812 sgraf812 added the changelog-language Language features and metaprograms label Nov 18, 2026
@sgraf812

Copy link
Copy Markdown
Member Author

!bench

@leanprover-radar

leanprover-radar commented Nov 18, 2026 •

Copy link
Copy Markdown

Benchmark results for dd23129 against c59550c are in. No significant results found. @sgraf812

  • ✅ build//instructions: -717.2M (-0.01%)

New metrics (10✅, 11🟥)

  • ✅ elab/big_match_lits//cycles: -144.4M (-0.13%)
  • ✅ elab/big_match_lits//instructions: -173.2M (-0.07%)
  • 🟥 elab/big_match_lits//maxrss: +1MiB (+0.05%)
  • ✅ elab/big_match_lits//task-clock: -25ms (-0.13%)
  • ✅ elab/big_match_lits//wall-clock: -21ms (-0.11%)
  • ✅ elab/do_nested_match_bind//cycles: -5.4M (-0.14%)
  • 🟥 elab/do_nested_match_bind//instructions: +880.1k (+0.01%)
  • 🟥 elab/do_nested_match_bind//maxrss: +5MiB (+0.25%)
  • ✅ elab/do_nested_match_bind//task-clock: -2ms (-0.31%)
  • 🟥 elab/do_nested_match_bind//wall-clock: +0s (+0.05%)
  • 🟥 elab/structural_eqdef_simp_proj//cycles: +441.0M (+1.38%)
  • 🟥 elab/structural_eqdef_simp_proj//instructions: +3.8M (+0.00%)
  • 🟥 elab/structural_eqdef_simp_proj//maxrss: +6MiB (+1.07%)
  • 🟥 elab/structural_eqdef_simp_proj//task-clock: +84ms (+1.43%)
  • 🟥 elab/structural_eqdef_simp_proj//wall-clock: +75ms (+1.66%)
  • 🟥 vcgen/IfsJP/20/kernel//wall-clock: +3ms (+0.34%)
  • ✅ vcgen/IfsJP/20/vcgen//wall-clock: -8ms (-9.72%)
  • ✅ vcgen/IfsJP/30/kernel//wall-clock: -6ms (-0.51%)
  • ✅ vcgen/IfsJP/30/vcgen//wall-clock: -2ms (-1.52%)
  • 🟥 vcgen/IfsJP/40/kernel//wall-clock: +7ms (+0.40%)
  • and 1 more

Medium changes (1✅)

  • ✅ build/module/Init.Grind.Ring.Kronecker//instructions: -1.4G (-3.15%)

Small changes (31✅, 11🟥)

  • ✅ compiled/nat_repr//task-clock: -75ms (-5.93%)
  • ✅ compiled/nat_repr//wall-clock: -75ms (-5.89%)
  • 🟥 elab/lift_lets_spine//instructions: +8.6M (+0.14%)
  • and 39 hidden

@github-actions github-actions Bot added the toolchain-available A toolchain is available for this PR, at leanprover/lean4-pr-releases:pr-release-NNNN label Nov 18, 2026
Base automatically changed from sg/do-elab-benches to master November 18, 2026 14:03
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
sgraf812 marked this pull request as ready for review November 19, 2026 09:34
@sgraf812
sgraf812 added this pull request to the merge queue Nov 19, 2026
Merged via the queue into master with commit 0c0183e Nov 19, 2026
19 checks passed
@sgraf812
sgraf812 deleted the sg/do-control-info-cache branch November 19, 2026 11:50
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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

changelog-language Language features and metaprograms toolchain-available A toolchain is available for this PR, at leanprover/lean4-pr-releases:pr-release-NNNN

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants