Skip to content

perf: build library suggestion indexes with one parallel traversal - #15391

Merged
kim-em merged 5 commits into
leanprover:masterfrom
marcelolynch:library-suggestions-fast-index
Oct 3, 2026
Merged

kim-em merged 5 commits into
leanprover:masterfrom
marcelolynch:library-suggestions-fast-index

Conversation

@marcelolynch

@marcelolynch marcelolynch commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

This PR makes the first library suggestion query in a process much faster. Since #15159 the symbol frequency map and the Sine Qua Non trigger index are computed on first use. The first grind +suggestions, simp? +suggestions or try? in a file took 12 s with import Lean and several minutes with import Mathlib. Both indexes now come from one traversal of the imported theorem statements. The traversal runs in parallel tasks and classifies the arguments of each application head once per head and arity. The results are identical to the previous traversal on every theorem of Lean core and of Mathlib. Concurrent first queries share one computation, and a cancelled query stops at once.

Closes #15392.

Measured on an Apple M5 Pro (18 threads). Lean-only numbers are medians of 10 interleaved runs of the timing files in #15392; the master and rc1 columns use v4.35.0-rc1 and a local stage1 build of master, the PR column a local stage1 build with this change. Mathlib numbers use Mathlib at v4.35.0-rc3 with local stage1 builds of v4.35.0-rc3 without and with this change.

first use v4.35.0-rc1 (indexes stored in oleans) master (v4.35.0-rc2 and later) this PR
symbolFrequencyMap, cold, import Lean (216k constants, 41k theorems) 5.5 ms 6.2 s 0.49 s
sineQuaNonTheorems, cold, import Lean 30 ms 6.1 s 0.09 s
first grind +suggestions in a file with import Lean 0.11 s 12.1 s 0.63 s
second grind +suggestions in the same file 0.07 s 0.08 s 0.08 s
symbolFrequencyMap, cold, import Mathlib (792k constants, 304k theorems) – 157–159 s 8–9 s
sineQuaNonTheorems, cold, import Mathlib – 173 s 1.5 s
CPU and max RSS of that Mathlib process – 327 s, 17.3 GB 76 s, 7.6 GB
MathlibTest/LibrarySuggestions/sineQuaNon.lean 15 s (Mathlib CI) 341 s 14–16 s
MathlibTest/symbolFrequency.lean 10 s (Mathlib CI) 159 s 12.5–12.8 s

rc1 did the same work at build time: about 9–11 s of CPU over a core stage1 build and about 215 s over a full Mathlib build, plus 6.3 MB of core oleans (0.36%) and about 49 MB of Mathlib oleans.

Implementation:

  • foldRelevantConstants visits an application spine at once. For each head and number of arguments, it computes an ArgKind per parameter from the binders of the head's type. It skips instance-implicit arguments and proofs (parameter type in Prop). It visits arguments whose parameter type is never a proposition without isProof, and isProof decides the rest.
  • Binder domains, forall bodies, and the heads and bodies of applications, lambdas and lets that are not proofs also skip isProof, because they cannot be proofs.
  • Expr.relevantConstantsOfEach caches the kinds per head constant across all statements of a batch. getFunInfo shares its results for constants between threads through one IO.Ref, on which parallel callers spin, so the traversal computes the kinds itself.
  • importedRelevantConstants computes the relevant constants of every imported theorem in one task per hardware thread and caches the array. symbolFrequencyMap and prepareTriggers are folds over it.
  • The three caches are SharedCaches. Concurrent first callers wait for one computation. The cache does not keep a failed or interrupted computation, and the waiting callers then compute the value themselves. A cancelled caller stops waiting at once and leaves the computation running.
  • The tasks get no cancellation token, because every Core.checkSystem would read it and concurrent reads of one IO.Ref spin. relevantConstantsOfEach checks the token every 64 statements instead.
  • prepareTriggers sorts the theorems of each trigger by tolerance and keeps the previous order among equal tolerances.
  • A statement whose traversal throws contributes no constants. This case occurs in a module file that imports Mathlib: some public equation lemmas mention private auxiliary proofs whose module part is not loaded, and every library suggestion query failed there with an unknown constant error.

Test changes: tests/elab/symbolFrequency_foldRelevantConsts.lean gets cases for heads whose type exposes fewer binders than the application has arguments, heads whose type unfolds to a function type, local heads with instance-implicit binders, the batched traversal, a statement whose traversal fails, and cancellation. The new tests/elab/library_suggestions_shared_cache.lean checks that concurrent callers share one computation, that callers compute the value again after a failed or interrupted computation, that a cancelled caller returns while the computation continues, and that concurrent first uses of symbolFrequencyMap get one map. tests/elab/library_suggestions_lazy.lean also checks the new cache.

🤖 Generated with Claude Code

Build the relevant constants of every imported theorem once, in parallel tasks, and derive both
the symbol frequency map and the Sine Qua Non trigger map from them. The traversal visits each
application spine once and computes the instance-implicit mask of its head directly, cached per
head constant. `getFunInfo` on each partial application rarely hit its cache, and `getFunInfo` on
constants goes through `realizeValue`, whose shared `IO.Ref` parallel tasks spin on.

On Mathlib (304262 theorems) the cold symbol frequency map drops from about 150-200s to 10s and
the cold trigger index from about 165s to 2s, with identical results.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@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 Sep 28, 2026
@marcelolynch
marcelolynch force-pushed the library-suggestions-fast-index branch 2 times, most recently from 10b8da6 to 288b6a0 Compare September 28, 2026 22:05
Marcelo Lynch and others added 2 commits September 28, 2026 19:29
…levant constants

`foldRelevantConstants` decides for each application head, once per head and arity, which parameters are instance-implicit, which are propositions (their arguments are proofs), and which are never propositions. It calls `isProof` only for arguments whose parameter type may or may not be a proposition, for `let` values, and for the root. Binder domains, forall bodies, and the heads and bodies of non-proof applications, lambdas, and lets are never proofs, so they skip the check too. The results are identical on every theorem of Lean core and of Mathlib.

A statement whose traversal fails, for example because it refers to a private auxiliary proof of a module whose private part is not imported, contributes no constants instead of failing the whole index.

Add traversal test cases for heads whose type exposes fewer binders than the application has arguments, heads whose type unfolds to a function type, local heads with instance-implicit binders, and the batched traversal.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
The imported relevant constants, the symbol frequency map and the Sine Qua Non trigger map are now `SharedCache`s: concurrent first uses wait for one computation instead of each starting their own set of parallel tasks. A failed or interrupted computation is not cached, and the callers that were waiting for it compute the value themselves. A cancelled caller stops waiting at once, through `CancelToken.onSet`, and leaves the computation running.

Each parallel task now passes its whole chunk to `relevantConstantsOfEach`, so the per-head parameter kinds are computed once per task instead of once per 4096 statements. `relevantConstantsOfEach` takes the cancellation token and checks it every 64 statements, so cancellation takes effect within milliseconds instead of up to a batch of 4096 statements.

The trigger buckets are updated in place with `alter`, and the unreachable re-throw of interrupts and runtime exceptions is removed (`Core.tryCatch` already re-throws them).

Add tests for the shared cache (one computation for concurrent callers, retry after a failed or interrupted computation, prompt return of a cancelled waiter, one map object for concurrent first uses of `symbolFrequencyMap`), for statements whose traversal fails, and for cancellation of `relevantConstantsOfEach`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
kim-em added 2 commits October 2, 2026 06:57
This PR makes library suggestion indexing respect the configured worker pool and prevents cancellable cache waiters from blocking queued work.

Race completion and cancellation into a promise and wait with IO.wait, which permits queued tasks to run while a pool worker is blocked. Keep the existing index chunks and run the shared-cache regression tests with one pool worker.
@kim-em kim-em added the changelog-tactics User facing tactics label Oct 2, 2026
@marcelolynch
marcelolynch marked this pull request as ready for review October 2, 2026 13:21
@kim-em
kim-em added this pull request to the merge queue Oct 3, 2026
Merged via the queue into leanprover:master with commit 193c358 Oct 3, 2026
26 checks passed
Kha pushed a commit that referenced this pull request Oct 6, 2026
…15391)

This PR makes the first library suggestion query in a process much
faster. Since #15159 the symbol frequency map and the Sine Qua Non
trigger index are computed on first use. The first `grind +suggestions`,
`simp? +suggestions` or `try?` in a file took 12 s with `import Lean`
and several minutes with `import Mathlib`. Both indexes now come from
one traversal of the imported theorem statements. The traversal runs in
parallel tasks and classifies the arguments of each application head
once per head and arity. The results are identical to the previous
traversal on every theorem of Lean core and of Mathlib. Concurrent first
queries share one computation, and a cancelled query stops at once.

Closes #15392.

Measured on an Apple M5 Pro (18 threads). Lean-only numbers are medians
of 10 interleaved runs of the timing files in #15392; the master and rc1
columns use v4.35.0-rc1 and a local stage1 build of master, the PR
column a local stage1 build with this change. Mathlib numbers use
Mathlib at v4.35.0-rc3 with local stage1 builds of v4.35.0-rc3 without
and with this change.

| first use | v4.35.0-rc1 (indexes stored in oleans) | master
(v4.35.0-rc2 and later) | this PR |
|---|---|---|---|
| `symbolFrequencyMap`, cold, `import Lean` (216k constants, 41k
theorems) | 5.5 ms | 6.2 s | 0.49 s |
| `sineQuaNonTheorems`, cold, `import Lean` | 30 ms | 6.1 s | 0.09 s |
| first `grind +suggestions` in a file with `import Lean` | 0.11 s |
12.1 s | 0.63 s |
| second `grind +suggestions` in the same file | 0.07 s | 0.08 s | 0.08
s |
| `symbolFrequencyMap`, cold, `import Mathlib` (792k constants, 304k
theorems) | – | 157–159 s | 8–9 s |
| `sineQuaNonTheorems`, cold, `import Mathlib` | – | 173 s | 1.5 s |
| CPU and max RSS of that Mathlib process | – | 327 s, 17.3 GB | 76 s,
7.6 GB |
| `MathlibTest/LibrarySuggestions/sineQuaNon.lean` | 15 s (Mathlib CI) |
341 s | 14–16 s |
| `MathlibTest/symbolFrequency.lean` | 10 s (Mathlib CI) | 159 s |
12.5–12.8 s |

rc1 did the same work at build time: about 9–11 s of CPU over a core
stage1 build and about 215 s over a full Mathlib build, plus 6.3 MB of
core oleans (0.36%) and about 49 MB of Mathlib oleans.

Implementation:

* `foldRelevantConstants` visits an application spine at once. For each
head and number of arguments, it computes an `ArgKind` per parameter
from the binders of the head's type. It skips instance-implicit
arguments and proofs (parameter type in `Prop`). It visits arguments
whose parameter type is never a proposition without `isProof`, and
`isProof` decides the rest.
* Binder domains, forall bodies, and the heads and bodies of
applications, lambdas and lets that are not proofs also skip `isProof`,
because they cannot be proofs.
* `Expr.relevantConstantsOfEach` caches the kinds per head constant
across all statements of a batch. `getFunInfo` shares its results for
constants between threads through one `IO.Ref`, on which parallel
callers spin, so the traversal computes the kinds itself.
* `importedRelevantConstants` computes the relevant constants of every
imported theorem in one task per hardware thread and caches the array.
`symbolFrequencyMap` and `prepareTriggers` are folds over it.
* The three caches are `SharedCache`s. Concurrent first callers wait for
one computation. The cache does not keep a failed or interrupted
computation, and the waiting callers then compute the value themselves.
A cancelled caller stops waiting at once and leaves the computation
running.
* The tasks get no cancellation token, because every `Core.checkSystem`
would read it and concurrent reads of one `IO.Ref` spin.
`relevantConstantsOfEach` checks the token every 64 statements instead.
* `prepareTriggers` sorts the theorems of each trigger by tolerance and
keeps the previous order among equal tolerances.
* A statement whose traversal throws contributes no constants. This case
occurs in a `module` file that imports Mathlib: some public equation
lemmas mention private auxiliary proofs whose module part is not loaded,
and every library suggestion query failed there with an unknown constant
error.

Test changes: `tests/elab/symbolFrequency_foldRelevantConsts.lean` gets
cases for heads whose type exposes fewer binders than the application
has arguments, heads whose type unfolds to a function type, local heads
with instance-implicit binders, the batched traversal, a statement whose
traversal fails, and cancellation. The new
`tests/elab/library_suggestions_shared_cache.lean` checks that
concurrent callers share one computation, that callers compute the value
again after a failed or interrupted computation, that a cancelled caller
returns while the computation continues, and that concurrent first uses
of `symbolFrequencyMap` get one map.
`tests/elab/library_suggestions_lazy.lean` also checks the new cache.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Marcelo Lynch <[email protected]>
Co-authored-by: Kim Morrison <[email protected]>
(cherry picked from commit 193c358)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backport releases/v4.35.0 changelog-tactics User facing tactics 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.

first grind +suggestions / try? takes minutes with import Mathlib since v4.35.0-rc2 (#15159)

2 participants