Skip to content

Box::leak in build_submodel_metadata causes unbounded memory growth #302

Closed

Description

@bpowers

Problem

build_submodel_metadata in src/simlin-engine/src/db.rs (line 3007) uses Box::leak(Box::new(stub)) to create &'a Variable references for sub-model variable stubs. This leaks memory on every call and is never reclaimed.

let stub: &'a crate::variable::Variable = Box::leak(Box::new(stub));

The comment in the surrounding code suggests salsa caching limits invocations, but build_submodel_metadata is a plain function -- not a #[salsa::tracked] function -- so salsa does not cache or deduplicate its calls. Its callers (compile_implicit_var_fragment, compile_var_fragment) are also non-tracked. Each recompilation leaks O(M) Variable stubs where M is the number of sub-model variables.

Individual stubs are small, but in a long-running editor session with frequent recompilation (e.g., the user typing equations), this grows without bound.

Why It Matters

  • Correctness: Unbounded memory growth in a long-running process (the editor) will eventually degrade performance or exhaust memory.
  • Developer experience: The Box::leak pattern here is surprising and misleading -- the comment's claim about salsa caching is inaccurate for a non-tracked function.

Component(s) Affected

  • src/simlin-engine/src/db.rs -- build_submodel_metadata function (around line 3007)

Possible Approaches

  1. Arena allocation: Use a typed arena (e.g., typed_arena::Arena or bumpalo) scoped to the compilation unit, so all stubs are freed together when compilation completes.
  2. Salsa interning: Make the stub variables salsa-interned or tracked values so they participate in salsa's lifecycle management.
  3. Refactor VariableMetadata: Change VariableMetadata to own its Variable (or use Arc<Variable>) instead of requiring a borrowed reference with lifetime 'a, eliminating the need for leaked references.

Context

Identified during PR #300 code review.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions