Skip to content

engine: incremental compilation followup fixes - #300

Merged
bpowers merged 7 commits into
mainfrom
incremental-compilation-followup
Feb 24, 2026
Merged

bpowers merged 7 commits into
mainfrom
incremental-compilation-followup

Conversation

@bpowers

@bpowers bpowers commented Feb 23, 2026 •

Copy link
Copy Markdown
Owner

Summary

Incremental compilation correctness fixes, plus two issues identified during code review:

  • Incremental compilation fixes: error handling now surfaces real compile failures instead of generic messages; array table placeholders preserved for sparse per-element graphical functions; implicit MODULE variables get correct sub-model slot sizes in flattened offset calculation
  • Module refs consistency: strip module ident prefix from implicit var module_refs, matching all other construction sites
  • TOCTOU race fix (libsimlin: sync_state TOCTOU race in simlin_project_add_model #303): simlin_project_add_model used .take() on sync_state and dropped the db lock before restoring it, allowing concurrent simlin_sim_new to see None and fail. Now uses .clone() and holds the db lock through the restore, matching the libsimlin: sync_state TOCTOU race in apply_project_patch_internal #297 fix in patch.rs
  • Memory leak fix (Box::leak in build_submodel_metadata causes unbounded memory growth #302): build_submodel_metadata used Box::leak to create stub variable references, leaking memory on every recompilation. Replaced with bumpalo::Bump arena allocation scoped to each compilation function, so stubs are freed when compilation completes

Fixes #302
Fixes #303

Test plan

  • cargo test -p simlin-engine -- 2139 tests
  • cargo test --features file_io --test simulate -- 32 integration tests
  • cargo test -p libsimlin -- 151 tests including new concurrency regression test
  • Full pre-commit hooks (clippy, fmt, WASM build, TS lint/build/test, pysimlin)

…currency

Three sets of fixes building on the salsa incremental compilation framework:

1. Concurrency fixes in patch.rs (Issues 296-298): Combined two separate
   project lock acquisitions into one atomic snapshot for the TOCTOU race on
   unit warnings. On the accept path, restore db to original state before
   releasing the db lock so no concurrent reader sees staged state, then
   re-acquire all three locks in documented order (project -> db -> sync_state)
   for atomic commit.

2. Implicit variable support: Added model_implicit_var_info tracked function,
   compile_implicit_var_fragment helper, extended compute_layout and
   assemble_module to handle variables generated by SMOOTH/DELAY/TREND builtins.

3. Module variable support: Added model_module_map tracked function,
   build_submodel_metadata helper, compile_var_fragment now uses real
   module_models and builds sub-model metadata for module-type variables.

Also adds incremental_compilation_covers_all_models integration test (ignored
for now) that identifies 16 remaining models that fail incrementally (stdlib
models not in SourceProject, implicit MODULE variables not recognized, composite
dependency names not resolved in mini-context).
Fix 16 remaining incremental compilation failures across stdlib
models, module variables, and lookup/array operations. The
incremental path now produces identical bytecode for all 75 test
models.

Key changes:
- Add stdlib models to SourceProject in both sync paths
- Extend ImplicitVarDeps/Meta with is_module and model_name fields
- Fix model_dependency_graph to classify implicit modules correctly
- Extend model_module_map to include implicit MODULE variables
- Handle composite dep names (middle-dot separated) in compilation
- Strip module ident prefix from ModuleReference.dst for bare names
- Build Variable::Module directly for module-type source vars
- Filter module inputs from sub-model runlists
- Guard against None AST in stock non-initial compilation phase
- Extract lookup tables from source vars for dependency stubs
- Build minimal ModelStage0 for array dimension resolution
- Remove monolithic compilation fallback in libsimlin
- Enable incremental_compilation_covers_all_models test
@bpowers
bpowers force-pushed the incremental-compilation-followup branch from ecfdfdc to 225169e Compare February 23, 2026 21:48
@claude

claude Bot commented Feb 23, 2026

Copy link
Copy Markdown

Code Review for PR #300: engine: incremental compilation followup fixes

Findings

[P2] compile_implicit_var_fragment does not strip module ident prefix from module_refs input set

File: src/simlin-engine/src/db.rs:4140-4143

In compile_implicit_var_fragment, the module_refs input set for implicit MODULE variables is built using raw canonicalize(&mr.dst) without stripping the module ident prefix:

let input_set: BTreeSet<Ident<Canonical>> = dm_module
    .references
    .iter()
    .map(|mr| Ident::new(canonicalize(&mr.dst).as_ref()))
    .collect();

Every other code path that builds module_refs strips the module variable name prefix from dst before inserting into the input set — for example, explicit modules in compile_var_fragment (line 3587-3594), implicit modules referenced by parent variables (line 3481-3490), and enumerate_module_instances_inner (line 4742-4752). Without stripping, the input set will contain prefixed names like $⁚smooth⁚0⁚smth1·input instead of bare sub-model variable names like input. When the bytecode compiler builds CallModule declarations, it resolves input offsets against the sub-model's metadata, which uses bare names — so the lookup would fail to match, potentially producing incorrect module input wiring for SMOOTH/DELAY/TREND builtins in the incremental compilation path. The existing test incremental_compilation_covers_all_models only checks that compilation succeeds (not output correctness), so this mismatch would not be caught.


[P3] calc_flattened_offsets_incremental does not recurse into implicit MODULE variables

File: src/simlin-engine/src/db.rs:4867-4879

The new block that adds implicit variables to the flattened offset map treats all implicit vars uniformly with info.size (hardcoded to 1 in model_implicit_var_info). For explicit MODULE variables, the function recurses into the sub-model (lines 4809-4829) to compute the actual slot count and produce per-sub-variable flattened offsets. For implicit MODULE variables (generated by SMOOTH/DELAY builtins), it inserts a single entry with size 1 and does not recurse. This means implicit module sub-model variables won't appear in the output offset map, and any implicit variables sorted after an implicit module in the name order will have incorrect offsets. Since implicit variable names are internal identifiers not typically queried by users, this only affects debugging/introspection of builtin internals — it does not affect simulation correctness because the VM uses compute_layout (which handles implicit modules correctly) for its memory layout.


Overall Correctness

The patch is mostly correct — the concurrency fix in patch.rs (atomically snapshotting warning baseline + datamodel), the dependency normalization in model_dependency_graph, the stdlib model injection, and the extensive new module/implicit-variable support in the incremental compilation path are sound. The new test coverage for incremental compilation across all test models is valuable. The P2 finding (missing prefix stripping in compile_implicit_var_fragment) is the most actionable issue and could produce incorrect simulation results for models using SMOOTH/DELAY/TREND builtins when compiled via the incremental path.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ecfdfdc169

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/libsimlin/src/simulation.rs Outdated
Comment on lines +69 to +71
Err(err) => {
eprintln!("incremental compilation failed: {err}");
None

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Propagate incremental compile errors in sim creation

When incremental compilation returns Err, this branch logs to stderr and returns None instead of preserving the error, which later leads simlin_sim_new to build a simulation with vm=None and vm_error=None. In that state callers get a generic "simulation has not been initialised" error on first run, and no out_error from construction, so real compile failures (or transient states like concurrent sync updates) are silently downgraded to an opaque runtime failure.

Useful? React with 👍 / 👎.

@claude

claude Bot commented Feb 23, 2026

Copy link
Copy Markdown

Code Review: PR #300 — engine: incremental compilation followup fixes

Finding 1: [P1] calc_flattened_offsets_incremental uses hardcoded info.size (always 1) for implicit module variables

File: src/simlin-engine/src/db.rs, lines 4867–4879

model_implicit_var_info always sets size: 1 for every implicit variable (line 843). For non-module implicit vars this is correct, but for module-type implicit vars (created by SMOOTH, DELAY builtins), the actual size should be the sub-model's n_slots. compute_layout (lines 2847–2856) correctly handles this by checking info.is_module and calling compute_layout(db, *sm, project, false).n_slots, but calc_flattened_offsets_incremental at line 4876 blindly uses info.size. Since the resulting offsets feed into CompiledSimulation's name-to-offset map, any variable positioned after an implicit module in the layout will have an incorrect offset, causing simlin_sim_get_value_by_name to return wrong values for models that use SMOOTH/DELAY/TREND builtins with implicit sub-modules.


Finding 2: [P2] compile_implicit_var_fragment does not strip module ident prefix from module_refs dst

File: src/simlin-engine/src/db.rs, lines 4140–4143

In compile_implicit_var_fragment, the input_set for module_refs is built as:

.map(|mr| Ident::new(canonicalize(&mr.dst).as_ref()))

This includes the full prefixed dst (e.g. $⁚x⁚0⁚init·output). Every other place in this PR that builds module_refs—compile_var_fragment (line 3591–3594), enumerate_module_instances_inner (line 4774–4777), and the implicit_module_refs block (line 3532–3535)—strips the module ident prefix via dst_canonical.strip_prefix(&input_prefix). The mismatch means the CallModule bytecodes emitted for implicit module variables will reference a module key with prefixed input names, while compiled_modules is keyed with stripped names. This would cause module instance lookup failure at assembly time for models with implicit module variables.


Overall Correctness Verdict

Not correct. Finding 1 is a concrete offset computation bug that produces wrong name-to-offset mappings for models with implicit module variables. Finding 2 is an inconsistency in module_refs construction that will cause assembly failures for implicit module variables. Both findings affect models using SMOOTH, DELAY, or TREND builtins (which generate implicit module sub-models). The existing test incremental_compilation_covers_all_models only checks that compilation succeeds, not that offsets or runtime behavior are correct, so these bugs may not be caught by the current test suite.

…d implicit module offsets

Three correctness fixes for the salsa-based incremental compilation path:

1. Preserve compile failure details in simlin_sim_new: when incremental
   compilation fails, the error was silently dropped, causing callers to
   see only a generic "not initialised" message.  Now the actual compile
   error is stored in vm_error and surfaced when the simulation is run.

2. Preserve array table placeholders for sparse per-element GFs: the
   extract_tables_from_source_var helper used filter_map which dropped
   elements without graphical functions, shifting table indices for later
   elements.  Now uses map with empty placeholder tables matching the
   behavior of variable.rs build_tables.

3. Compute real sizes for implicit MODULE variables in flattened offset
   calculation: implicit MODULE vars (from DELAY/SMOOTH expansion) were
   recorded with size 1, but they occupy their sub-model's full slot
   count.  Now calc_flattened_offsets_incremental recurses into sub-models
   for implicit modules, mirroring the existing explicit module handling.
@claude

claude Bot commented Feb 23, 2026

Copy link
Copy Markdown

Code Review: PR #300 — engine: incremental compilation followup fixes

Findings


[P2] module_refs input_set not prefix-stripped in compile_implicit_var_fragment

File: src/simlin-engine/src/db.rs, lines 4145–4149

In compile_implicit_var_fragment, the module_refs input_set for implicit module variables is built without stripping the module ident prefix from dst:

let input_set: BTreeSet<Ident<Canonical>> = dm_module
    .references
    .iter()
    .map(|mr| Ident::new(canonicalize(&mr.dst).as_ref()))
    .collect();

Every other location that builds a module_refs input_set strips the module ident prefix from dst using filter_map + strip_prefix — see lines 3486–3495 (compile_var_fragment implicit modules), lines 3375–3380 (explicit module deps), lines 4747–4758 (enumerate_module_instances_inner implicit modules). This means the ModuleKey produced here will contain prefixed input names (e.g. $⁚x⁚0⁚smooth·input) instead of bare sub-model names (e.g. input), which is inconsistent with the keys generated by enumerate_module_instances_inner for the same modules. If the bytecode compiler uses these keys to match compiled module instances, the mismatch could cause incorrect module selection or compilation failure for models that exercise implicit module inputs. Whether this triggers depends on the specific implicit module reference format, but it's the only site in the file that doesn't strip the prefix.


[P2] Box::leak in build_submodel_metadata is an unbounded memory leak

File: src/simlin-engine/src/db.rs, line 3007

build_submodel_metadata uses Box::leak with a comment claiming it's acceptable because "these are cached by salsa and only created once per variable." However, build_submodel_metadata is a plain function (not #[salsa::tracked]), and its primary caller compile_implicit_var_fragment is also explicitly non-tracked. Each invocation leaks fresh Variable stubs that are never freed. In a long-running editor session with many edit cycles, each recompilation leaks O(M) stubs (where M is the number of sub-model variables across all module references). While each individual stub is small, this grows without bound over the lifetime of the process.


Overall Correctness Verdict

Mostly correct. The PR makes substantial and well-structured progress on incremental compilation support for implicit variables, modules, and dependency normalization. The test coverage is thorough and the architectural approach is sound. The two issues above are real but unlikely to be blocking — the prefix-stripping inconsistency may not manifest in current test models, and the memory leak is slow-growing. Existing code and tests should not break from this patch.

@bpowers

bpowers commented Feb 23, 2026

Copy link
Copy Markdown
Owner Author

Code Review: PR #300 -- engine: incremental compilation followup fixes

Reviewed the 2 commits on this branch (225169e6, 792ab247) against main.

Changes Summary

  1. simulation.rs: Removes the silent swallow of incremental compilation errors. Previously, when compile_project_incremental failed, the error was printed to stderr and (None, None, None) was returned, meaning the caller got a sim handle with no VM and no error -- leading to a generic "not been initialised" message at runtime. Now the Result is propagated directly, so vm_error captures the real compilation failure.

  2. db.rs (extract_tables_from_source_var): Fixes a table-index misalignment bug. For arrayed variables with sparse per-element graphical functions, filter_map would skip elements without a GF, causing later elements to get the wrong lookup table. Changed to map with empty Table { data: vec![] } placeholders, preserving 1:1 alignment between element offsets and table indices.

  3. db.rs (calc_flattened_offsets_incremental): Implicit MODULE variables (from SMOOTH/DELAY/TREND builtin expansion) now recursively compute their sub-model slot count instead of using the fixed info.size (which was 1). Without this, all variables laid out after an implicit module would have incorrect offsets.

  4. SKILL.md: Updates the /address-feedback-local skill to use the new codex CLI syntax and simplifies the Claude review step.

  5. Tests: Three well-targeted tests covering the three bug fixes above.

Findings

No actionable findings. The changes are well-scoped bug fixes with matching tests. Specifically:

  • The error propagation fix in simulation.rs is correct: vm_error is checked in both simlin_sim_run_to and simlin_sim_run_to_end, so the real error now surfaces properly.
  • The filter_map -> map + placeholder fix in extract_tables_from_source_var is the right approach for maintaining table index alignment, and matches the pattern used by variable.rs build_tables.
  • The implicit module offset calculation correctly mirrors the recursive pattern already used for explicit module variables earlier in the same function.
  • The sub_size: usize = sub_offsets.iter().map(|(_, (_, size))| size).sum() computation is correct because calc_flattened_offsets_incremental produces contiguous, non-overlapping offsets starting from 0, so the sum of sizes equals the total slot count.

Overall Correctness Verdict

Looks correct. Three real bugs fixed, each with a targeted test. The logic in the fixes mirrors existing patterns for explicit variables and is consistent with the monolithic compilation path.

@bpowers

bpowers commented Feb 23, 2026

Copy link
Copy Markdown
Owner Author

Review cycle summary

After two review iterations, this PR addresses three correctness bugs in the salsa-based incremental compilation path:

Error propagation: When incremental compilation failed, the actual error was silently dropped and callers received only a generic "not initialised" message. The real compile error is now preserved and surfaced at runtime, making it possible for users to diagnose model issues through the incremental path.

Table index alignment: Arrayed variables with sparse per-element graphical functions had their table indices shifted when elements without GFs were dropped via filter_map. Empty placeholder tables are now inserted to maintain alignment, matching the existing behavior in variable.rs build_tables.

Implicit module offset calculation: Implicit MODULE variables generated by SMOOTH/DELAY/TREND builtins were recorded with a fixed size of 1 slot, but they actually occupy their sub-model's full slot count. The flattened offset calculation now recurses into sub-models for implicit modules, mirroring the existing handling for explicit modules. Without this fix, all variables laid out after an implicit module had incorrect offsets in the results map.

Each fix includes a targeted test. A separate issue (#301) was filed to track a related edge case in implicit var dep resolution for composite module outputs.

compile_implicit_var_fragment was building the module_refs input_set
using raw canonicalize(dst) without stripping the module ident prefix.
Every other code path that builds module_refs (compile_var_fragment,
enumerate_module_instances_inner, and the implicit module block in
compile_var_fragment) correctly strips the "module_name·" prefix to
produce bare sub-model variable names like "input" rather than
prefixed names like "$⁚smooth⁚0⁚smth1·input".

While this field is not currently read by the VM compilation path
(only the interpreter), fixing it prevents a latent bug and keeps
all module_refs construction sites consistent.
@bpowers

bpowers commented Feb 23, 2026

Copy link
Copy Markdown
Owner Author

@codex review

1 similar comment
@bpowers

bpowers commented Feb 23, 2026

Copy link
Copy Markdown
Owner Author

@codex review

@claude

claude Bot commented Feb 23, 2026

Copy link
Copy Markdown

Code Review: PR #300 — engine: incremental compilation followup fixes

Summary

This PR extends the salsa-based incremental compilation path to handle implicit variables (from SMOOTH/DELAY/TREND builtins), module-type variables, stdlib models, and several concurrency/correctness fixes. It removes the monolithic compilation fallback, asserting that incremental compilation now covers all models. The changes span ~1850 lines of additions across db.rs, patch.rs, simulation.rs, compiler/mod.rs, and variable.rs, plus comprehensive tests.

Analysis

Concurrency fix in patch.rs: The change to atomically snapshot the warning baseline and datamodel under a single lock acquisition is a clear correctness improvement. The two-phase commit (restore original state before releasing db lock, then re-acquire all three locks in documented order for the final commit) maintains the project -> db -> sync_state lock ordering invariant correctly.

Monolithic fallback removal in simulation.rs: The fallback is replaced with direct error propagation from the incremental path. This is backed by the new incremental_compilation_covers_all_models integration test that verifies every test model compiles via the incremental path.

Module handling in dependency graph and runlists: Modules are correctly moved from the flows phase to the stocks phase (!i.is_stock && !i.is_module for flows, i.is_stock || i.is_module for stocks), matching the monolithic compiler's behavior in model.rs lines 984, 1028, 1150, 1182.

Module input prefix stripping in enumerate_module_instances_inner: The old code passed raw module_refs dst values (e.g., "hares·food") as module input names. The new code strips the module variable prefix to get bare sub-model variable names (e.g., "food"), matching resolve_module_input's behavior in the monolithic path. This is necessary for the new is_module_input filtering in assemble_module to correctly identify which variables are externally provided.

Stdlib models: Both sync_from_datamodel and sync_from_datamodel_incremental now add stdlib models consistently, with the incremental path correctly reusing previous salsa handles when available.

Dependency normalization: The normalize_dep closure in model_dependency_graph correctly handles composite module output references (stripping leading middle-dot and truncating at the first middle-dot) so that dependency names resolve to module variable names rather than qualified output names.

compile_implicit_var_fragment: This new ~500-line function mirrors compile_var_fragment for implicit variables. The mini-Module compilation pattern (always placing expressions in runlist_flows and reading from compiled_flows) is consistent with the existing pattern in compile_var_fragment. Phase selection (initial/flow/stock) is correctly determined by the surrounding conditionals, not by the mini-Module's internal runlist assignments.

compiler/mod.rs fix: The unwrap() on ast.as_ref() for stocks with None AST is replaced with a proper EmptyEquation error. Defensive improvement.

Findings

No bugs found that meet the flagging criteria. The changes consistently mirror the monolithic compiler's behavior, lock ordering is maintained, and the test coverage is thorough (new tests for error preservation, sparse per-element GFs, implicit module offsets, and all-model incremental compilation coverage).

One observation (not a bug): build_submodel_metadata uses Box::leak to satisfy lifetime constraints. The comment states these are "cached by salsa and only created once per variable," but build_submodel_metadata itself is not a salsa-tracked function — it's called from tracked functions. Each re-computation of the parent tracked function will leak new boxes. In practice this is bounded (proportional to sub-model variable count × input changes) and acceptable for a desktop simulation tool, but the comment slightly overstates the caching guarantee.

Verdict

Overall correctness: Correct. The patch should not break existing code or tests, and is free of blocking bugs. The incremental compilation path now consistently handles all variable types (explicit, implicit, module, stock, aux) with proper dependency normalization, module input filtering, and stdlib model resolution.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ff598e1e8b

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines 64 to +69
} else {
None
Err(engine::Error {
kind: engine::ErrorKind::Simulation,
code: engine::ErrorCode::NotSimulatable,
details: Some("incremental compilation: no sync state available".to_string()),
})

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Keep monolithic fallback when sync state is temporarily absent

Returning NotSimulatable when sync_state is None introduces transient failures for valid projects under concurrent mutation: simlin_project_add_model currently does sync_state.lock().unwrap().take() and only restores it after rebuilding, so simlin_sim_new can now fail in that window even though the model can still be compiled from the project snapshot. The previous fallback to monolithic compilation masked this expected temporary None state, so this change creates a user-visible regression in multi-threaded callers.

Useful? React with 👍 / 👎.

Comment thread src/simlin-engine/src/db.rs Outdated
// Build a stub variable with correct dimensions for the sub-model context
let dims = variable_dimensions(db, *svar, project);
let stub = build_stub_variable(db, svar, &var_ident, dims);
let stub: &'a crate::variable::Variable = Box::leak(Box::new(stub));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Avoid leaking submodel stubs during fragment compilation

This Box::leak permanently allocates one stub per submodel variable every time build_submodel_metadata runs, and that helper is called from fragment compilation paths that can be re-executed across incremental edits. In a long-lived process (server/editor session), repeated compiles will accumulate unreclaimed allocations, so memory usage grows over time instead of staying bounded by the current model graph.

Useful? React with 👍 / 👎.

@bpowers

bpowers commented Feb 23, 2026

Copy link
Copy Markdown
Owner Author

Review cycle summary

After three review iterations (two prior + one in this cycle), this PR addresses four correctness issues in the salsa-based incremental compilation path, each with targeted tests.

The latest iteration fixed a latent inconsistency in compile_implicit_var_fragment where implicit module module_refs input sets were built without stripping the module ident prefix from dst. While this field is not currently consumed by the VM compilation path (only the interpreter), every other code site that builds module_refs performs the stripping, and the mismatch would become a real bug if the field were used in the future. The fix brings all module_refs construction sites into consistency.

Two additional concerns raised by reviewers were tracked as separate issues rather than addressed in-PR: a Box::leak memory growth pattern in build_submodel_metadata (#302), and a brief sync_state race window during simlin_project_add_model (#303). Both are pre-existing design concerns that warrant their own targeted fixes.

@codecov

codecov Bot commented Feb 23, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 90.45752% with 73 lines in your changes missing coverage. Please review.
✅ Project coverage is 79.18%. Comparing base (645893e) to head (45f0983).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
src/simlin-engine/src/db.rs 92.32% 54 Missing ⚠️
src/simlin-engine/tests/simulate.rs 58.53% 17 Missing ⚠️
src/libsimlin/src/simulation.rs 60.00% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #300      +/-   ##
==========================================
+ Coverage   78.44%   79.18%   +0.73%     
==========================================
  Files         121      121              
  Lines       29656    30375     +719     
==========================================
+ Hits        23265    24052     +787     
+ Misses       6391     6323      -68     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

simlin_project_add_model used .take() on sync_state and dropped the
db lock before restoring it. Between drop(db) and the restore,
concurrent simlin_sim_new readers could observe sync_state = None and
get spurious NotSimulatable errors.

Fix: use .clone() instead of .take() and hold the db lock until after
sync_state is restored, matching the pattern already used in patch.rs
for issue #297.
…adata

build_submodel_metadata used Box::leak to create &'a Variable references
for sub-model stubs, leaking memory on every compilation. The comment
claiming salsa caching made this acceptable was inaccurate -- this is a
plain function, not a salsa-tracked query.

Replace with bumpalo::Bump arena allocation. Each caller
(compile_var_fragment and compile_implicit_var_fragment) creates a
function-scoped arena that outlives all metadata references, so stubs
are properly freed when compilation completes.
@bpowers

bpowers commented Feb 24, 2026

Copy link
Copy Markdown
Owner Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 45f0983f12

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +4060 to +4064
if let Some(dep_source_var) = source_vars.get(dep_name.as_str()) {
let dep_dims = variable_dimensions(db, *dep_source_var, project);
let dep_size = variable_size(db, *dep_source_var, project);
let dep_var = build_stub_variable(db, dep_source_var, &dep_ident, dep_dims);
dep_variables.push((dep_ident, dep_var, dep_size));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Normalize implicit dependency names before metadata lookup

This implicit-fragment dependency path only checks source_vars.get(dep_name) / implicit_info.contains_key(dep_name) and never handles composite module-output refs (e.g. module·output) or leading-dot refs. Builtin expansion can generate implicit helper vars with those deps (for complex stdlib arguments), so the required module metadata/module refs are never added here, and later offset resolution for that dependency can fail during incremental compilation. The explicit-fragment path added special handling for this case, but the implicit path does not.

Useful? React with 👍 / 👎.

Comment on lines +4126 to +4130
let gf_tables = lowered.tables();
if !gf_tables.is_empty() {
let table_results: crate::Result<Vec<crate::compiler::Table>> = gf_tables
.iter()
.map(|t| crate::compiler::Table::new(&implicit_name, t))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Include dependency lookup tables for implicit fragments

The implicit-fragment compiler only builds tables from lowered.tables() and does not copy graphical-function tables from dependencies (unlike the explicit-fragment path). If an implicit helper var contains LOOKUP(dep, x) (which happens when stdlib-call arguments are lowered into helper vars), dep's table is missing from the mini-module and fragment compilation can fail, breaking incremental compilation for those builtin-expression models.

Useful? React with 👍 / 👎.

@claude

claude Bot commented Feb 24, 2026

Copy link
Copy Markdown

Code Review

I performed a thorough review of this PR covering: the TOCTOU race fix in patch.rs and project.rs, the fallback removal in simulation.rs, the bumpalo arena-based memory leak fix, the incremental compilation enhancements in db.rs (implicit module variables, stdlib registration, module maps, dependency normalization, layout/offset computation, fragment compilation), and the new tests.

Findings

No bugs found. The changes are consistent and correct:

  • TOCTOU fixes: The project.rs change (.clone() instead of .take(), holding db lock through sync_state restore) correctly prevents the window where sync_state is None. The patch.rs refactoring correctly restores the db to original state before dropping the db lock, then re-acquires all three locks in documented order (project -> db -> sync_state) for an atomic commit. Between the lock release and re-acquisition, concurrent readers see consistent original state.

  • Module refs stripping: The dst prefix stripping (module_name·sub_var → sub_var) is applied consistently in compile_var_fragment, compile_implicit_var_fragment, enumerate_module_instances_inner, and model_module_map, matching the monolithic compiler's resolve_module_input behavior.

  • Module runlist handling: Modules are correctly excluded from runlist_flows (line 1200: !i.is_stock && !i.is_module) and included in runlist_stocks (line 1213: i.is_stock || i.is_module). With implicit modules now correctly marked is_module: true, they move from the flows phase to the stocks phase, matching monolithic behavior.

  • Implicit module slot sizes: compute_layout, calc_flattened_offsets_incremental, and the compile_implicit_var_fragment function all correctly resolve implicit MODULE variables to their sub-model's full n_slots count rather than defaulting to size 1.

  • Arena allocation: The bumpalo::Bump arena replaces Box::leak in build_submodel_metadata. The arena outlives all references into it within each compilation function, and the compiled output (VarFragmentResult) contains only owned types, so the arena can be safely dropped after compilation.

  • Dependency normalization: The normalize_dep closure correctly strips leading middle-dot (U+00B7, XMILE parent refs) and truncates composite module output references at the first middle-dot, producing bare dependency names for the graph.

Overall Correctness Verdict

Correct. The patch is free of bugs and blocking issues. The TOCTOU, memory leak, and incremental compilation fixes are all sound, the lock ordering is maintained, and the new test coverage (concurrency regression test, compile error preservation test, sparse GF test, implicit module offset test, integration test across all models) validates the changes.

@bpowers

bpowers commented Feb 24, 2026

Copy link
Copy Markdown
Owner Author

Review cycle summary

Both automated reviewers (Claude and Codex) reviewed the two new commits added in this cycle:

Claude's review found no bugs across the full PR. Codex raised two theoretical concerns about compile_implicit_var_fragment missing dependency name normalization (P1) and dependency table collection (P2) relative to the explicit path. Both are real completeness gaps but don't manifest in any current test model -- implicit variables from DELAY/SMOOTH/PREVIOUS/TREND builtins don't generate module-output refs or LOOKUP dependencies. P1 was already tracked as #301; P2 was filed as #304.

@bpowers
bpowers merged commit eb45f4a into main Feb 24, 2026
13 checks passed
@bpowers
bpowers deleted the incremental-compilation-followup branch February 24, 2026 01:05
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

libsimlin: sync_state TOCTOU race in simlin_project_add_model Box::leak in build_submodel_metadata causes unbounded memory growth

1 participant