Concurrent `Job.bindM` callbacks race on `BuildStore` in `fetchOrCreate`, launching duplicate concurrent builds of shared plugin modules

Aperta
#16,874 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 1 giorno

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
4/5
Tempo stimato
3-5 giorni
Idoneità per principianti
35/100
Tipo di issue
Bug
Chiarezza
Abbastanza chiara
Stato di attività
Attiva
Ambito
build-system

Direzione di ricerca

Start with src/lake/Lake/Util/Store.lean and src/lake/Lake/Build/Index.lean to trace fetchOrCreate, then read src/lake/Lake/Build/Target/Fetch.lean and src/lake/Lake/Build/Job/Monad.lean for the concurrent callers. Reproduce with two concurrent fetches of the same memoized facet and inspect the build output for duplicate compiler launches. Done means concurrent requests share one in-flight build; add a deterministic regression test.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

Summary

On Lean and Lake v4.36.0 (611c117bfaf7b7ae1cfcf246ce6fba31e8f509e9), when many modules in a library declare the same shared plugin (plugins = ["<PluginLib>:shared"]), Lake can launch two concurrent lean compiler processes for the exact same plugin module, reading the same source file and writing to the same .olean / .setup.json / .c output paths while Lake still exits with code 0.

The root cause is that PartialBuildKey.fetchInCoreAux (Target/Fetch.lean:65) uses Job.bindM with the default sync := false, dispatching concurrent callbacks that share the same IO.Ref BuildStore (Job/Monad.lean:245,250), while recBuildWithIndex → fetchOrCreate (Index.lean:48, Util/Store.lean:47-55) performs an unsynchronized check-create-insert (fetch? → create → store) across an await boundary (Library.lean:141).

Observed Evidence on Lean 4.36.0

During a single lake build ArkLib on frozen ArkLib (2934c834177ee4de50b9df5ce58509a8529fbf88, 1,252 owned modules, LEAN_NUM_THREADS=8, Lean -j2) using an official-recipe Stage 2 Lean 4.36.0 build (611c117bfaf7b7ae1cfcf246ce6fba31e8f509e9):

  • The lakefile.toml defines a single ArkLibLintPlugin library, referenced by ArkLib via plugins = ["ArkLibLintPlugin:shared"] (the only other reference is in the unrequested ArkLibTest library).
  • The single Lake root process (PID 51393) spawned 1,253 physical lean processes for 1,252 unique owned modules.
  • ArkLibLintPlugin was compiled twice concurrently:
Field Attempt 1 Attempt 2
PID 51522 51525
Launch delta 0 ms +4.895 ms
Execution overlap 453.018 ms 453.018 ms
Process CPU (user + sys) 496.335 ms 528.342 ms
Source SHA-256 3e0a92ef47b5b608199f130701842a8f9e4b7fb8902a9be50bd0a38c9a3d33c6 identical
Setup path .lake/build/ir/ArkLibLintPlugin.setup.json identical

Lake exited with status 0 despite both processes concurrently writing to the same shared output paths.

Source-Level Root Cause (611c117bfaf7b7ae1cfcf246ce6fba31e8f509e9)

  1. Every consumer module fetches the shared plugin via PartialBuildKey.fetchInCoreAux.
    • Module.recFetchPreSetup (src/lake/Lake/Build/Module.lean:650) calls mod.plugins.fetchIn mod.pkg "module plugins" for each module in the library.
    • For .facet target shortFacet (e.g. ArkLibLintPlugin:shared), PartialBuildKey.fetchInCoreAux (src/lake/Lake/Build/Target/Fetch.lean:54-67) resolves the target job (Job.pure for a lean_lib config target from Index.lean:38) and then calls:
      let job ← (job.cast h).bindM (kind := cfg.outKind) fun data =>
        fetch (.facet target kind data facet)
      
  2. Job.bindM runs the fetch callback asynchronously on the shared IO.Ref BuildStore.
    • Job.bindM (src/lake/Lake/Build/Job/Monad.lean:240-256) defaults to sync := false and passes the shared store reference into BaseIO.bindTask:
      BaseIO.bindTask task (prio := prio) (sync := sync) fun
        | .ok a sa => do
          ...
          match (← withLoggedIO (f a) |>.toFn fetch pkg? stack store ctx {sa with trace}) with
      
    • Consequently, multiple consumer modules' plugin fetches execute fetch (.facet <ArkLibLintPlugin> lean_lib data lean_lib.shared) concurrently on separate worker threads against the same BuildStore.
  3. fetchOrCreate has no synchronization or in-flight placeholder across create.
    • recBuildWithIndex (src/lake/Lake/Build/Index.lean:46-48) memoizes facets via fetchOrCreate key recFetch.
    • fetchOrCreate (src/lake/Lake/Util/Store.lean:47-55) performs an unsynchronized check-then-act sequence:
      @[inline] public def fetchOrCreate
        [Monad m] (key : κ) [MonadStore1Of key α m] (create : m α)
      : m α := do
        if let some val ← fetch? key then
          return val
        else
          let val ← create
          store key val
          return val
      
    • For LeanLib.sharedFacetConfig (src/lake/Lake/Build/Library.lean:139-168), recBuildShared awaits self.modules.fetch at line 141 and mod.transImports.fetch at line 150 before recBuildShared returns and store key val inserts the shared facet job into BuildStore.
    • Any second async bindM worker that reaches fetch? key during this wide window also observes none, enters LeanLib.recBuildShared, and recursively calls fetchOrCreate for the plugin module's native/elaboration facets (elabArts, Module.lean:1248) concurrently, spawning a duplicate lean compilation on the same output files.

Expected Behavior and Suggested Fix

Lake should guarantee that a memoized BuildKey is created at most once per build, even when fetch is invoked from concurrent Job.bindM callbacks:

  1. Root fix (atomic memoization in BuildStore / fetchOrCreate): Guard BuildStore lookup/insertion (e.g., via a mutex or an in-flight IO.Promise/placeholder entry keyed by BuildKey) so concurrent fetchOrCreate callers for the same key share the in-flight job instead of running create twice.
  2. Targeted mitigation in Target/Fetch.lean:65: For already-resolved target jobs (such as Job.pure config targets), avoid unnecessarily hopping onto an async worker thread via bindM (sync := false) before calling fetch (.facet ...). (Note: any other Job.bindM caller invoking fetch still requires fix #1 for general soundness.)

Reproducibility Note

Because the race requires two Job.bindM callbacks to overlap inside fetchOrCreate before the first store completes, small low-concurrency projects (e.g. 8 consumers at LEAN_NUM_THREADS=2) rarely hit the window in a single run, whereas larger libraries with many consumers sharing a :shared plugin at higher LEAN_NUM_THREADS (e.g. ArkLib at LEAN_NUM_THREADS=8) trigger it cleanly. A deterministic unit test can directly invoke two concurrent Job.bindM (sync := false) tasks calling fetch on the same memoized facet whose fetchFn yields/awaits before returning.

Lingua principale
Lean
Stelle
10.3k
Fork
1.1k
Merge medio
16h 45m
PR unite (30g)
361

Preparare l'ambiente

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di leanprover/lean4

Tutte le issue di leanprover/lean4

Issue simili

Altre issue su Build System

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.