From 8308b7ae2c30144fba4955ede2da447dc301412f Mon Sep 17 00:00:00 2001 From: AlonM <39011515+alonbase@users.noreply.github.com> Date: Thu, 26 Nov 2026 15:11:30 +0200 Subject: [PATCH] perf: reduce memory of the LeanExport reader This PR reduces the memory that `leanchecker --from-export`, `lake check --from-export` and `lake comparator` use to read an export, by storing its names, levels and expressions in arrays instead of hash maps. `LeanExport.Basic` numbers each kind densely and in order. The new `IdTable` in `LeanExport.Parse` keeps that dense prefix in an `Array` and puts any index that does not extend it into a `Std.HashMap`, so indices in any order, with gaps or beyond 2^64 are accepted with the same results and error messages as before. On an export of `Lean` (823,583,439 bytes), the sampled peak anonymous memory of `leanchecker --from-export` goes from 1364 MiB to 784 MiB. Exports whose indices do not extend the dense prefix keep their previous memory use and took about 4-9 % more CPU time to parse in our measurements. Co-Authored-By: Claude Opus 5.5 --- src/LeanExport/Parse.lean | 44 +++++++- tests/elab/leanExportParseIndexOrder.lean | 132 ++++++++++++++++++++++ 2 files changed, 170 insertions(+), 6 deletions(-) create mode 100644 tests/elab/leanExportParseIndexOrder.lean diff --git a/src/LeanExport/Parse.lean b/src/LeanExport/Parse.lean index 2432cfc41d..efc2b4e531 100644 --- a/src/LeanExport/Parse.lean +++ b/src/LeanExport/Parse.lean @@ -34,11 +34,43 @@ namespace Parse open Std.Internal.Parsec Std.Internal.Parsec.String Lean +/-- +The objects of one kind bound so far, by export index. `LeanExport.Basic` numbers each kind densely +and in order, so those objects live in an `Array`, without a hash map entry per object. An index +that does not extend that dense prefix (a sparse or out-of-order export) goes to the `HashMap` +instead, so indices in any order and with gaps are accepted. + +Invariant: every key of `sparse` is at least `dense.size`. An index only enters `sparse` when it is +neither bound nor equal to `dense.size`, and `dense` only grows by an index that is not in `sparse`, +so it never grows past a key of `sparse`. +-/ +structure IdTable (α : Type) where + dense : Array α := #[] + sparse : Std.HashMap Nat α := {} + +namespace IdTable + +@[inline] +def get? (t : IdTable α) (i : Nat) : Option α := + if h : i < t.dense.size then some t.dense[i] else t.sparse[i]? + +@[inline] +def contains (t : IdTable α) (i : Nat) : Bool := + i < t.dense.size || t.sparse.contains i + +/-- Binds `i`, which must not be bound yet. -/ +@[inline] +def insert (t : IdTable α) (i : Nat) (x : α) : IdTable α := + match t with + | ⟨dense, sparse⟩ => if i == dense.size then ⟨dense.push x, sparse⟩ else ⟨dense, sparse.insert i x⟩ + +end IdTable + structure State where stream : IO.FS.Stream - nameMap : Std.HashMap Nat Lean.Name := { (0, .anonymous) } - levelMap : Std.HashMap Nat Lean.Level := { (0, .zero) } - exprMap : Std.HashMap Nat Lean.Expr := {} + nameMap : IdTable Lean.Name := { dense := #[.anonymous] } + levelMap : IdTable Lean.Level := { dense := #[.zero] } + exprMap : IdTable Lean.Expr := {} recursorRuleMap : Std.HashMap Nat Lean.RecursorRule := {} constMap : Std.HashMap Lean.Name Lean.ConstantInfo := {} constOrder : Array Lean.Name := #[] @@ -54,7 +86,7 @@ def fail (msg : String) : M α := @[inline] def getName (nidx : Nat) : M Lean.Name := do - let some n := (← get).nameMap[nidx]? | fail s!"Name not found {nidx}" + let some n := (← get).nameMap.get? nidx | fail s!"Name not found {nidx}" return n @[inline] @@ -65,7 +97,7 @@ def addName (nidx : Nat) (n : Lean.Name) : M Unit := do @[inline] def getLevel (uidx : Nat) : M Lean.Level := do - let some l := (← get).levelMap[uidx]? | fail s!"Level not found {uidx}" + let some l := (← get).levelMap.get? uidx | fail s!"Level not found {uidx}" return l @[inline] @@ -76,7 +108,7 @@ def addLevel (uidx : Nat) (l : Lean.Level) : M Unit := do @[inline] def getExpr (eidx : Nat) : M Lean.Expr := do - let some e := (← get).exprMap[eidx]? | fail s!"Expr not found {eidx}" + let some e := (← get).exprMap.get? eidx | fail s!"Expr not found {eidx}" return e @[inline] diff --git a/tests/elab/leanExportParseIndexOrder.lean b/tests/elab/leanExportParseIndexOrder.lean new file mode 100644 index 0000000000..e0932aa65f --- /dev/null +++ b/tests/elab/leanExportParseIndexOrder.lean @@ -0,0 +1,132 @@ +import LeanExport.Parse + +/-! +Tests that the `LeanExport` NDJSON reader accepts the indices of names, levels and expressions in +any order, with gaps and beyond 2^64, not only the dense in-order numbering `LeanExport` writes, +and that the errors for indices bound twice or used unbound do not depend on where the index falls +relative to the dense prefix the reader stores in an array. +-/ + +def parse (lines : List String) : IO Unit := do + let input := String.intercalate "\n" ("{}" :: lines) ++ "\n" + let buf ← IO.mkRef { data := input.toUTF8 : IO.FS.Stream.Buffer } + let env ← LeanExport.parseStream (.ofBuffer buf) + for n in env.constOrder do + IO.println s!"{n} : {env.constMap[n]!.type}" + +def ax (name type : Nat) : String := + s!"\{\"axiom\":\{\"name\":{name},\"levelParams\":[],\"type\":{type},\"isUnsafe\":false}}" + +-- In order (what `LeanExport` writes) + +/-- info: a : Type -/ +#guard_msgs in +#eval parse [ + "{\"in\":1,\"str\":{\"pre\":0,\"str\":\"a\"}}", + "{\"il\":1,\"succ\":0}", + "{\"ie\":0,\"sort\":1}", + ax 1 0] + +-- Out of order and with gaps: names, levels and expressions + +/-- +info: b.a : Type.{1} +c : Type.{1} -> Type.{1} +-/ +#guard_msgs in +#eval parse [ + "{\"in\":7,\"str\":{\"pre\":0,\"str\":\"b\"}}", + "{\"in\":3,\"str\":{\"pre\":7,\"str\":\"a\"}}", + "{\"in\":1,\"str\":{\"pre\":0,\"str\":\"c\"}}", + "{\"il\":5,\"succ\":0}", + "{\"il\":2,\"succ\":5}", + "{\"ie\":9,\"sort\":2}", + "{\"ie\":4,\"forallE\":{\"name\":0,\"type\":9,\"body\":9,\"binderInfo\":\"default\"}}", + ax 3 9, + ax 1 4] + +-- The dense prefix catches up with an index bound ahead of it, and reading continues past it + +/-- +info: a : Type +b : Type -> Type +-/ +#guard_msgs in +#eval parse [ + "{\"in\":2,\"str\":{\"pre\":0,\"str\":\"b\"}}", + "{\"in\":1,\"str\":{\"pre\":0,\"str\":\"a\"}}", + "{\"il\":1,\"succ\":0}", + "{\"ie\":1,\"sort\":1}", + "{\"ie\":0,\"sort\":1}", + "{\"ie\":2,\"forallE\":{\"name\":0,\"type\":0,\"body\":1,\"binderInfo\":\"default\"}}", + ax 1 0, + ax 2 2] + +-- Indices far beyond any dense prefix, next to the small indices they agree with modulo 2^64 + +/-- +info: a : Type +b : Prop +-/ +#guard_msgs in +#eval parse [ + "{\"in\":1,\"str\":{\"pre\":0,\"str\":\"a\"}}", + "{\"in\":18446744073709551617,\"str\":{\"pre\":0,\"str\":\"b\"}}", + "{\"il\":1,\"succ\":0}", + "{\"ie\":0,\"sort\":1}", + "{\"ie\":18446744073709551616,\"sort\":0}", + ax 1 0, + "{\"axiom\":{\"name\":18446744073709551617,\"levelParams\":[],\"type\":18446744073709551616,\"isUnsafe\":false}}"] + +-- Bound twice: ahead of the dense prefix, and at the index the dense prefix has caught up to + +/-- error: Expr index 5 bound twice -/ +#guard_msgs in +#eval parse [ + "{\"ie\":5,\"sort\":0}", + "{\"ie\":5,\"sort\":0}"] + +/-- error: Expr index 2 bound twice -/ +#guard_msgs in +#eval parse [ + "{\"ie\":2,\"sort\":0}", + "{\"ie\":0,\"sort\":0}", + "{\"ie\":1,\"sort\":0}", + "{\"ie\":2,\"sort\":0}"] + +/-- error: Name index 3 bound twice -/ +#guard_msgs in +#eval parse [ + "{\"in\":3,\"str\":{\"pre\":0,\"str\":\"a\"}}", + "{\"in\":1,\"str\":{\"pre\":0,\"str\":\"b\"}}", + "{\"in\":2,\"str\":{\"pre\":0,\"str\":\"c\"}}", + "{\"in\":3,\"str\":{\"pre\":0,\"str\":\"d\"}}"] + +/-- error: Level index 2 bound twice -/ +#guard_msgs in +#eval parse [ + "{\"il\":2,\"succ\":0}", + "{\"il\":1,\"succ\":0}", + "{\"il\":2,\"succ\":1}"] + +-- Used before it is bound, inside and beyond the dense prefix + +/-- error: Expr not found 1 -/ +#guard_msgs in +#eval parse [ + "{\"ie\":0,\"sort\":0}", + "{\"ie\":2,\"forallE\":{\"name\":0,\"type\":0,\"body\":1,\"binderInfo\":\"default\"}}"] + +/-- error: Expr not found 7 -/ +#guard_msgs in +#eval parse [ + "{\"ie\":3,\"sort\":0}", + "{\"ie\":0,\"forallE\":{\"name\":0,\"type\":3,\"body\":7,\"binderInfo\":\"default\"}}"] + +/-- error: Name not found 2 -/ +#guard_msgs in +#eval parse ["{\"in\":1,\"str\":{\"pre\":2,\"str\":\"a\"}}"] + +/-- error: Level not found 3 -/ +#guard_msgs in +#eval parse ["{\"il\":1,\"succ\":3}"] -- 2.43.0