`importModules` / `withImportModules` leaks `CompactedRegion`s when a later import fails

Open
#16,911 0 comments 0 reactions 0 assignees View on GitHub

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

bug
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, commit fd149e00cbdb00df937d9f64b8ed477252d32c68.)
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
  1. 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 ()
  1. compile and link with LeakSanitizer (using Homebrew LLVM clang on macOS arm64; standard clang -fsanitize=leak on 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
  1. 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:


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

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from leanprover/lean4

All issues in leanprover/lean4

Similar issues

More Backend & API Design issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.