`importModules` / `withImportModules` leaks `CompactedRegion`s when a later import fails
Maintainers usually reply within 1 day
Nobody has claimed this yet.
Assessment
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Newbie friendliness
- 47/100
- Issue type
- Bug
- Clarity
- Clearly specified
- Activity status
- Active
- Domain
- backend
Research direction
Start with readModuleDataPartsOfMod, readIRPartsOfMod, importModules, and withImportModules in src/Lean/Environment.lean, then trace how ImportState owns regions across failures. Use the standalone reproducer and LeakSanitizer commands in the issue to compare the leak case with ok and missing-first. Done means failed imports release regions without leaving caller state pointing into freed regions; extension references with loadExts := true also need consideration.
Written by the indexing model from the issue text.
Description
Prerequisites
- Check that your issue is not already filed: https://github.com/leanprover/lean4/issues
- Reduce the issue to a minimal, self-contained, reproducible test case. Avoid dependencies to Mathlib or Batteries.
- Test your test case against the latest nightly release. (Also reproduced on
4.38.0-nightly-2026-11-30, commitfd149e00cbdb00df937d9f64b8ed477252d32c68.)
Description
when Lean.importModules or Lean.withImportModules reads one or more valid .olean/.ir dependencies and then throws on a later missing or invalid import, the CompactedRegions it already acquired during importModulesCore are leaked.
importModules throws before it returns an Environment, so withImportModules never reaches its finally env.freeRegions, and the caller doesnt have an Environment handle it can use to free those regions either. in a long-lived process that retries imports after user edits, the memory grows with each failed import.
Steps to Reproduce
- save this standalone
Repro.lean(no external dependencies,loadExts := false, no plugins):
import Lean
open Lean
unsafe def main (args : List String) : IO Unit := do
initSearchPath (← findSysroot)
let (imports, n) := match args with
| ["ok", k] => (#[{ module := `Init.Prelude }], k.toNat!)
| ["missing-first", k] => (#[{ module := `DoesNotExist }, { module := `Init.Prelude }], k.toNat!)
| ["leak", k] => (#[{ module := `Init.Prelude }, { module := `DoesNotExist }], k.toNat!)
| _ => (#[{ module := `Init.Prelude }, { module := `DoesNotExist }], 3)
for _ in [0:n] do
try
withImportModules imports {} fun _env => pure ()
catch _ =>
pure ()
- compile and link with LeakSanitizer (using Homebrew LLVM
clangon macOS arm64; standardclang -fsanitize=leakon Linux):
PREFIX=$(lean --print-prefix)
lean -c Repro.c Repro.lean
/opt/homebrew/opt/llvm/bin/clang -fsanitize=leak -O1 Repro.c \
-I "$PREFIX/include" \
-L "$PREFIX/lib/lean" -Wl,-rpath,"$PREFIX/lib/lean" \
-lleanshared -lInit_shared -o repro
- run the control and failing cases:
ASAN_OPTIONS=detect_leaks=1 ./repro ok 3
ASAN_OPTIONS=detect_leaks=1 ./repro missing-first 3
ASAN_OPTIONS=detect_leaks=1 ./repro leak 2
ASAN_OPTIONS=detect_leaks=1 ./repro leak 5
Expected behavior
the CompactedRegions acquired during a failed importModules / withImportModules attempt should be freed on the error path if an Environment hasnt been constructed and returned yet. there should be 0 lean_compacted_region_read leaks, like in the ok and missing-first cases.
Actual behavior
when an attempt reads Init.Prelude and then fails on DoesNotExist, the compacted regions are leaked. the amount reported grows when i increase the number of attempts. the number of regions LSan reports varies between runs. with normal settings, leak 2 reported between 2 and 5 regions and leak 5 reported between 5 and 20 across six runs. when i disabled stack scanning, those cases consistently reported 5 and 20 regions, so it looks like stack roots can affect the count. leak 1 still reported 0 though, and i havent established why or whether the final iteration’s regions remain reachable at exit. the table is an example from a run:
| Command | LSan Summary | lean_compacted_region_read leaks |
|---|---|---|
./repro ok 3 |
336 B in 16 allocs | 0 (one-time startup static init only) |
./repro missing-first 3 |
336 B in 16 allocs | 0 (one-time startup static init only) |
./repro leak 2 |
5,245,696 B in 21 allocs | 5,245,360 B (5 regions) |
./repro leak 5 |
20,981,776 B in 36 allocs | 20,981,440 B (20 regions) |
sample LSan stack trace:
Direct leak of 1045720 byte(s) in 1 object(s) allocated from:
#0 malloc (libclang_rt.lsan_osx_dynamic.dylib)
#1 lean_compacted_region_read (libleanshared.dylib)
#2 l___private_Lean_Environment_0__Lean_readModuleDataPartsOfMod (libleanshared.dylib)
#3 ...Lean_importModulesCore_go_spec__0 (libleanshared.dylib)
...
#14 l_Lean_importModules (libleanshared.dylib)
#15 l_Lean_withImportModules___redArg (libleanshared.dylib)
Versions
- Lean:
Lean (version 4.36.0, arm64-apple-darwin24.6.0, commit 611c117bfaf7b7ae1cfcf246ce6fba31e8f509e9, Release) - OS: macOS 26.5.2 (25F84), arm64
- LSan compiler: Homebrew clang 22.1.7
Additional Information
the relevant code i found in src/Lean/Environment.lean at commit 611c117b:
readModuleDataPartsOfMod(L2443-L2456) andreadIRPartsOfMod(L2458-L2470) acquireCompactedRegions viaCompactedRegion.read.importModules(L2815-L2819) runsimportModulesCoreinStateRefT ImportState IObeforefinalizeImport. ifimportModulesCorethrows, theImportStateis discarded without freeing the accumulated regions.withImportModules(L2827-L2830) only guardsact envwithfinally env.freeRegions.
i tested a local fix in my 4.36.0-based SDK that tracks each CompactedRegion acquired during the current import attempt and frees them in reverse order if the import fails before publication. for importModulesCore, it also keeps the previous ImportState separate until the traversal succeeds, so a failed traversal doesnt leave the caller's state pointing into freed regions.
it stops rolling regions back before they can be made persistent or exposed to extension code with loadExts := true, since extensions may retain references even if they later throw. it also frees newly allocated or mapped buffers in lean_compacted_region_read if reading fails before a CompactedRegion is returned.
with this change, leak 2 and leak 5 produced no LSan report in my local SDK test, and subsequent retries succeeded. my full SDK patch also has embedding-specific ownership changes, so im not saying its good for upstream.
- Dominant language
- Lean
- Stars
- 10.5k
- Forks
- 1.2k
- Avg merge
- 19h 36m
- Merged PRs (30d)
- 323
Getting set up
- No Dockerfile or Docker Compose file
- Has a pull request template
- Read the contributing guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
More from leanprover/lean4
-
P-medium
Difficulty 2/5 1-3 hours Newbie friendliness 68/100
leanprover/lean4#16958 ·
Maintainers usually reply within 1 day
-
Difficulty 2/5 1-3 hours Newbie friendliness 82/100
leanprover/lean4#16897 ·
Maintainers usually reply within 1 day
-
bug
Difficulty 2/5 1-3 hours Newbie friendliness 78/100
leanprover/lean4#16892 ·
Maintainers usually reply within 1 day
-
Difficulty 1/5 1-3 hours Newbie friendliness 86/100
leanprover/lean4#16886 · 1 comment ·
Maintainers usually reply within 1 day
-
bug
Difficulty 1/5 Under an hour Newbie friendliness 78/100
leanprover/lean4#16820 ·
Maintainers usually reply within 1 day
All issues in leanprover/lean4
Similar issues
-
Difficulty 1/5 Under an hour Newbie friendliness 72/100
superfly/contextwindow#18 ·
-
Difficulty 2/5 1-3 hours Newbie friendliness 76/100
Maintainers usually reply within 1 day
-
Difficulty 2/5 1-3 hours Newbie friendliness 83/100
Lincoln-cn/JAiRouter#1452 ·
Maintainers usually reply within 1 day
-
accepted
Difficulty 2/5 1-3 hours Newbie friendliness 68/100
future-agi/future-agi#6351 ·
Maintainers usually reply within 1 day
-
Difficulty 2/5 1-3 hours Newbie friendliness 68/100
Maintainers usually reply within 1 day