Lake: shorten the reference critical section for build-store lookups

Aperta
#16,955 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
54/100
Tipo di issue
Bug
Chiarezza
Specificata chiaramente
Stato di attività
Attiva

Direzione di ricerca

Read src/lake/Lake/Util/StoreInsts.lean, especially the three StateRefT' fetch? instances for DTreeMap, RBArray, and NameMap. Change those lookups to read a map snapshot with getThe, then perform the lookup on that snapshot; leave the StateT instances and write operations as they are. Check the mixed-access stress test and benchmark described in the issue, confirming reads, inserts, and missing-key behavior remain correct.

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

Descrizione

In a parallel build, Lake walks transitive imports to assemble each module’s setup. A lookup of an already memoized facet runs through the shared build store. The three reference-backed stores in Lake.Util.StoreInsts currently implement fetch? by taking the map out of the ref, looking up the key, and putting the map back. On a shared ref, another reader or writer spins until the map is put back. Store instances · Reference operations

Read a persistent map snapshot with getThe, then perform the same lookup on that snapshot. The ref read takes ownership of the current root long enough to retain a reference. Once the root is back in the ref, the reader can finish its search while another task accesses the store. Reference counting keeps the captured root and all reachable values live. A writer that encounters a shared root uses the map’s normal copy-on-write path. Each read sees the map at the instant it took the snapshot. The existing compound miss, create, and publish sequence still consists of individual operations.

fetch? k := return (← getThe (Std.DTreeMap κ β cmp)).get? k

Apply the same change to the RBArray and NameMap instances for StateRefT'. The StateT instances and all write operations retain their existing definitions.

Measurements

The following medians are per call to mkModuleSetup on the official Linux Lean 4.36.0 release. Eight workers concurrently set up a module using a shared store pre-populated with 6,690 ready build jobs. The comparison changed the shared-reference lookup on the warm facet path. Each row has 96 measured calls per setting after warm-up.

Project and module Facet lookups per call Lookup under reference lock Lookup on retained snapshot
PhysLean, Physlib.Mathematics.SpecialFunctions.PhysHermite 6,801 54.65 ms 21.19 ms
VCVio, LatticeCrypto.Ring.Core 4,737 37.71 ms 14.35 ms
VCVio, LatticeCrypto.DiscreteGaussian 7,048 55.90 ms 21.44 ms

Across eight module samples, medians fell by 23.4–37.9 ms in this read-heavy workload. The reconstructed import artifacts matched the original setup data for all eight modules after normalizing dependency paths. A fully concurrent warm walk increases contention compared with a build where some workers are waiting for compiler children. Concurrent writers can also allocate extra tree paths while readers retain older snapshots.

A mixed-access stress test exercised all three store instances with 16 workers and 131,071 initial entries. It verified that inserts remained visible, existing keys retained their values, and missing keys stayed absent. Three runs with 15 readers and one writer on the simpler DTreeMap Nat had median times of 4.42 s for the release and 4.98 s for the candidate SDK. In a within-binary comparison of the two ref access methods, the snapshot path ranged from 17% faster to 10% slower over three pairs. With 12 readers and four writers, the RBArray median rose from 8.78 s to 9.52 s. Cheap key comparisons and concurrent insertion can limit or reverse the gain observed while assembling real module setups.

Cold project builds

I also paired the official Linux release with an official-recipe Stage2 SDK containing this change and compact module setup JSON. Each project was built once per setting in the same worktree, with 16 physical CPUs allocated to the build, a warm dependency tree, and Lean compiler children using -j2.

Project Compiled modules Release wall time With both changes Lake process CPU
VCVio 1,334 427.18 s 412.74 s 110.46 → 79.62 CPU-s
PhysLean 781 592.29 s 582.57 s 58.75 → 41.59 CPU-s

All seven artifact types matched byte for byte for all 2,115 compiled modules. These whole-build figures measure the two changes together. The rebuilt SDK's Lean shared library has a different binary fingerprint, and compiler-child CPU also varied across the pairs. The per-module measurements above isolate the store change.

Reproduce on stock Lean 4.36.0

Run the following Bash block on Linux with Elan and the official leanprover/lean4:v4.36.0 toolchain. It compiles a standalone benchmark that runs the two read implementations against the same persistent map and asserts the lookup results. Use the median of the three elapsed-nanosecond values for each mode. The last columns report process peak RSS from Linux procfs.

set -euo pipefail
sdk=$(lean +leanprover/lean4:v4.36.0 --print-prefix)
test "$("$sdk/bin/lean" --githash)" = 611c117bfaf7b7ae1cfcf246ce6fba31e8f509e9
work=$(mktemp -d "${TMPDIR:-/tmp}/lake-repro.XXXXXXXX")
trap 'find "$work" -depth -delete' EXIT
cd "$work"
unset LEAN_PATH LEAN_SRC_PATH LEAN_SYSROOT
cat > Store.lean <<'LEAN'
import Lake

open Lake Lean

abbrev DT := Std.DTreeMap Nat (fun _ => Nat) compare
abbrev RB := RBArray Nat Nat compare
abbrev NM := NameMap Nat

def check (condition : Bool) (message : String) : IO Unit :=
  unless condition do throw (IO.userError message)

def mix {σ : Type} (label : String) (empty : σ)
    (get : Nat → StateRefT σ IO (Option Nat))
    (put : Nat → Nat → StateRefT σ IO Unit)
    (readers writers entries reads writes : Nat) : IO Unit := do
  let ref ← IO.mkRef empty
  for i in [:entries] do
    put i i ref
  let key (w i : Nat) := entries + w * writes + i
  let start ← IO.Promise.new (α := Unit)
  let writerTasks ← (List.range writers).mapM fun w => IO.asTask do
    IO.wait start.result!
    for i in [:writes] do
      put (key w i) (i + 1) ref
  let readerTasks ← (List.range readers).mapM fun r => IO.asTask do
    IO.wait start.result!
    let mut next := 0
    let mut index := r
    for i in [:reads] do
      index := (1664525 * index + 1013904223) % entries
      check ((← get index ref) == some index) "stable key changed"
      if writers > 0 && writes > 0 && i % 16 == 0 then
        let writer := r % writers
        if next > 0 then
          check ((← get (key writer (next - 1)) ref) == some next) "published key disappeared"
        if next < writes then
          if let some value ← get (key writer next) ref then
            check (value == next + 1) "published value is wrong"
            next := next + 1
      if i % 256 == 0 then
        check ((← get (entries + writers * writes) ref) == none) "missing key appeared"
  let begin ← IO.monoNanosNow
  start.resolve ()
  for task in writerTasks ++ readerTasks do
    IO.ofExcept (← IO.wait task)
  let done ← IO.monoNanosNow
  for w in [:writers] do
    for i in [:writes] do
      check ((← get (key w i) ref) == some (i + 1)) "writer lost an insertion"
  let proc ← IO.FS.readFile "/proc/self/status"
  let peak := (proc.splitOn "\n").find? (·.startsWith "VmHWM:")
  IO.println s!"{label}\t{readers}\t{writers}\t{entries}\t{reads}\t{writes}\t{done - begin}\t{peak.getD ""}"

def main (args : List String) : IO Unit := do
  let [mode, readers, writers, reads, writes] := args
    | throw (IO.userError "usage: store MODE READERS WRITERS READS WRITES")
  let parse (s : String) : IO Nat := match s.toNat? with
    | some n => pure n
    | none => throw (IO.userError s!"invalid count: {s}")
  let readers ← parse readers
  let writers ← parse writers
  let reads ← parse reads
  let writes ← parse writes
  let entries := 131071
  let putD (k v : Nat) : StateRefT DT IO Unit := Lake.MonadDStore.store (β := fun _ => Nat) k v
  match mode with
  | "locked" =>
    mix mode (∅ : DT) (fun k ref => ref.modifyGet fun t => (t.get? k, t))
      putD readers writers entries reads writes
  | "snapshot" =>
    mix mode (∅ : DT) (fun k ref => return (← ref.get).get? k)
      putD readers writers entries reads writes
  | "dtree" =>
    mix mode (∅ : DT) (fun k => Lake.MonadDStore.fetch? (β := fun _ => Nat) k)
      putD readers writers entries reads writes
  | "rbarray" =>
    mix mode (∅ : RB) (fun k => Lake.fetch? k)
      (fun k v => Lake.store k v) readers writers entries reads writes
  | "namemap" =>
    let key (i : Nat) := Name.num `entry i
    mix mode (∅ : NM) (fun k => Lake.fetch? (key k))
      (fun k v => Lake.store (key k) v) readers writers entries reads writes
  | _ => throw (IO.userError s!"unknown mode: {mode}")
LEAN

export LEAN_NUM_THREADS=8
"$sdk/bin/lean" -c Store.c Store.lean
"$sdk/bin/leanc" -O3 -o store Store.c -lLake_shared -lleanshared -lInit_shared \
  -Wl,-rpath,"$sdk/lib/lean"
for mode in locked snapshot snapshot locked locked snapshot; do
  ./store "$mode" 8 0 250000 0
done

(Confirmed still present on master at 3158840c in src/lake/Lake/Util/StoreInsts.lean:23,31,39.)

Lingua principale
Lean
Stelle
10.5k
Fork
1.2k
Merge medio
19h 36m
PR unite (30g)
323

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 Backend & API Design

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.