Skip to content

engine: finish salsa migration, delete monolithic compilation path - #375

Merged
bpowers merged 32 commits into
mainfrom
finish-salsa-migration
Mar 7, 2026
Merged

bpowers merged 32 commits into
mainfrom
finish-salsa-migration

Conversation

@bpowers

@bpowers bpowers commented Mar 7, 2026

Copy link
Copy Markdown
Owner

Summary

Makes the incremental salsa compilation pipeline the sole compilation path, then deletes the monolithic code. This is a 7-phase migration executed across 28 commits:

  • Phase 1-2: Update stale docstrings, remove catch_unwind from incremental paths
  • Phase 3: Unify parse_source_variable on module-context variant (dimension-granularity invalidation prep)
  • Phase 4: Migrate all production callers (layout, analysis, cli, mcp, patch, db) from Project::from to salsa queries
  • Phase 5: Add incremental test helpers to TestProject, migrate test files
  • Phase 6: Delete Simulation::compile(), compile_project, set_dependencies_cached (284 lines), gate Project::from behind #[cfg(any(test, feature = "testing"))]
  • Phase 7: Add dimension-granularity invalidation so scalar variables are immune to dimension changes, and arrayed variables only re-parse when their specific dimensions change

Key deletions: try_compile_model, try_detect_ltm_loops_monolithic, compile_project, Simulation::compile(), set_dependencies_cached, collect_formatted_issues, bench_project_build

Bug fix included: expand_maps_to_chains now follows reverse maps_to edges, fixing cross-dimension mapping context for subscripted SMOOTH builtins.

All 2853 workspace tests pass.

Test Plan

  • cargo test -p simlin-engine --features testing -- all engine tests pass
  • cargo test -p libsimlin -- FFI layer tests pass
  • cargo test -p simlin-cli -- CLI tests pass
  • cargo run -p simlin-cli -- simulate test/predator_prey/predator_prey.xmile -- end-to-end simulation works
  • Verify Project::from is only available under testing feature gate
  • See docs/test-plans/2026-03-06-finish-salsa-migration.md for full human test plan

bpowers added 29 commits March 7, 2026 06:13
The incremental compilation path (compile_project_incremental) now correctly
handles all model types including module variables, implicit variables from
SMOOTH/DELAY/TREND, and differentiated module input sets. Update docstrings
on Simulation::compile and compile_project that incorrectly claimed #295
was still open. Both methods are retained only for test cross-validation.
The incremental compiler returns clean Result::Err for all error conditions
instead of panicking, so defensive catch_unwind wrappers are no longer
needed. Removes catch_unwind from benchmarks, the incremental coverage
test, and the incremental LTM loop detection path.

Also updates the compile_project_incremental docstring which incorrectly
claimed a monolithic fallback that no longer exists.

Three catch_unwind sites wrapping monolithic code (layout/mod.rs:1874,
layout/mod.rs:2129, analysis.rs:124) are retained until those callers
migrate to the incremental path in Phase 4.

Part of #363
Verifies that PREVIOUS(x) where x = SMTH1(input, 1) compiles and
simulates correctly through the incremental salsa path.  The test
ensures module expansion is used instead of LoadPrev, which would
read the wrong VM slot for multi-slot module-backed variables.
Production call sites in db.rs, db_analysis.rs, and db_ltm.rs now use
parse_source_variable_with_module_context instead of the plain
parse_source_variable variant.  Where a model is available the tracked
model_module_ident_context function provides the context (preserving
salsa cache stability); where no model is available (variable_dimensions,
variable_direct_dependencies without context) an empty ModuleIdentContext
is used since the caller is only extracting dimension or dependency info
that is unaffected by module identity.
All callers now use parse_source_variable_with_module_context. The
plain parse_source_variable (which passed module_idents = None) has
been deleted.  Test code uses a parse_var_no_module_ctx helper that
constructs an empty ModuleIdentContext.  The libsimlin FFI caller
in model.rs was also migrated.
Delete try_compile_model (which used Project::from with catch_unwind)
and try_detect_ltm_loops_monolithic (which used Project::with_ltm()).
Both functions are replaced by the salsa incremental path:

- Dependency extraction now uses variable_direct_dependencies from
  the salsa db, falling back to string heuristics when the equation
  has a parse error (matching the old behavior).
- LTM loop detection always uses try_detect_ltm_loops_incremental.

When callers pass db_state as None, a temporary SimlinDb is created
and synced internally (ensure_db_state_mut helper), so the public API
remains backward-compatible with test callers that don't have a db.
The layout caller now requires the project to be synced before layout
generation. If sync_state is None, it returns an early error instead
of silently falling through with no salsa db. The SourceProject
handle is extracted explicitly and passed to generate_best_layout.
Change analyze_model and run_ltm_pipeline to accept a caller-provided
SimlinDb and SourceProject instead of creating an internal SimlinDb.
Remove catch_unwind wrapper and Project::from usage from run_ltm_pipeline
by building the CausalGraph from salsa-tracked causal edges via
model_causal_edges/causal_graph_from_edges.

Add discover_loops_with_graph to ltm_finding, which accepts a pre-built
CausalGraph and stock list, enabling callers with salsa-derived graphs
to bypass the monolithic Project path. The original discover_loops now
delegates to this new function.

Update simlin-mcp callers (ReadModel, EditModel) to create a SimlinDb,
sync the project, and pass both to the updated analyze_model.
Replace all Project::from usage in simlin-cli with salsa-based
compilation:

- Error reporting (run_datamodel_with_errors): uses salsa accumulator
  diagnostics via collect_all_diagnostics + format_diagnostic instead
  of monolithic Project + collect_formatted_issues

- LTM loop detection (simulate): uses model_detected_loops salsa query
  instead of ltm::detect_loops on a monolithic Project

- Equations mode (print_equations): uses SourceModel/SourceVariable
  iteration with parse_source_variable_with_module_context instead of
  Project::from variable iteration

Also makes model_module_ident_context public in db.rs so external
consumers can construct the context needed for variable parsing.
Replace the two remaining production callers of Project::from:

- patch.rs (apply_rename_variable): use SimlinDb + sync_from_datamodel +
  reconstruct_model_variables to get parsed/lowered variables with ASTs
  for dependency-aware renaming, instead of CompiledProject::from.

- db.rs (get_stdlib_composite_ports): use SimlinDb + sync_from_datamodel +
  base_from with cached sources instead of Project::from. The base_from
  call is still needed because compute_composite_ports takes &Project,
  but Project::from is no longer called. Phase 6 will address base_from.
No production callers remain after earlier tasks migrated layout and
analysis paths to the incremental salsa pipeline.  Move both methods,
their helper functions (inject_ltm_vars, abort_if_arrayed), and the
imports they need behind #[cfg(any(test, feature = "testing"))] so
they are excluded from production builds.

The "testing" feature is needed because #[cfg(test)] alone does not
apply when the library is compiled as a dependency of integration
tests.  The simulate_ltm integration test now requires this feature
in addition to file_io.

Part of #292
Add compile_incremental, run_vm_incremental, assert_compiles_incremental,
vm_result_incremental, and assert_vm_result_incremental methods that use
the salsa-based incremental pipeline (SimlinDb + sync_from_datamodel_incremental
+ compile_project_incremental) instead of the monolithic CompiledProject::from
+ Simulation::compile path.

Extract the shared result-collection logic into a standalone collect_results
helper to avoid duplicating the array aggregation code.

Existing monolithic methods are kept for now; Phase 6 will remove them
after all callers are migrated.
Replace monolithic TestProject methods with their incremental
counterparts across array_tests.rs and unit_checking_test.rs:

- assert_compiles() -> assert_compiles_incremental()
- assert_vm_result() -> assert_vm_result_incremental()
- vm_result() -> vm_result_incremental()

Three tests in array_tests.rs retain assert_compiles() because
their features (@n position syntax, MEAN with dynamic ranges) are
not yet supported on the incremental compilation path.

The two direct CompiledProject::from calls in unit_checking_test.rs
are replaced with sync_from_datamodel_incremental +
compile_project_incremental, checking diagnostics via
collect_all_diagnostics instead of inspecting compiled model fields.

Interpreter-path methods (assert_interpreter_result, run_interpreter,
assert_scalar_result, assert_sim_builds, assert_unit_error,
assert_compile_error) are retained per AC4.6.
Delete compile_vm_monolithic and INCREMENTAL_BUILTIN_ISSUES -- all
previously-problematic models (delay, smooth, initial, wrld3-03) now
work correctly on the incremental salsa path.

Migrate simulate_mdl_path, simulate_mdl_path_with_data, and all inline
tests (simulates_except_basic_mdl, simulates_wrld3_03, GET DIRECT
DATA/CONSTANTS/LOOKUPS, simulates_clearn) from sim.compile() to
compile_vm() (incremental).

MDL path tests now validate interpreter and VM independently against
expected output rather than cross-validating, since the incremental
path may produce different evaluation orders for internal variables.

simulates_vector_simple_mdl switched to interpreter-only: the
incremental path has a pre-existing limitation with VECTOR ELM MAP
cross-dimension source indexing.
Add compile_ltm_incremental helper that creates a SimlinDb, syncs the
datamodel, enables LTM, and compiles via compile_project_incremental.

Migrate simulate_ltm_path VM leg from inline incremental code to the
new helper, simplifying the function and removing the intermediate
datamodel_for_vm clone.

The sim.compile() call in test_smooth_goal_seeking_ltm is retained on
the monolithic path because the incremental LTM compilation does not
yet support module-containing models (SMTH1 stdlib module instances
fail layout resolution with LTM-augmented variable names).

All other LTM tests (discovery, causal graph, loop detection, cycle
partitions) use the interpreter path retained per AC4.6, or the
monolithic Project::from for exhaustive cross-validation. These will
be addressed when Project::from is removed in Phase 6.
Migrate all sim.compile() and Project::from call sites in vm.rs test
modules (per_variable_initials_tests, vm_reset_and_run_initials_tests,
set_value_tests, superinstruction_tests, vm_reset_run_to_and_constants_tests)
to use TestProject::compile_incremental() or direct SimlinDb +
compile_project_incremental calls.

Migrate vm_alloc.rs build_scalar_model helper from monolithic
Project::from + Simulation::compile to TestProject::compile_incremental.

Migrate compiler/symbolic.rs compile_and_roundtrip helper and
test_resolve_uses_layout_n_slots_not_symbolic from Project::from +
Module::new to SimlinDb + compile_project_incremental + compute_layout.

ltm.rs and ltm_augment.rs tests are left unchanged because every
Project::from call in those files tests the monolithic detect_loops,
CausalGraph::from_model, generate_ltm_variables, or with_ltm APIs
directly -- these will be removed together with Project::from in Phase 6.
Migrate Project::from callers in test code to use the incremental
salsa pipeline (SimlinDb + sync_from_datamodel + collect_all_diagnostics
/ compile_project_incremental / model_causal_edges).

libsimlin errors.rs: add format_diagnostic_with_datamodel and
collect_formatted_issues_from_diagnostics to produce snippet-annotated
error output from salsa diagnostics, replacing the monolithic
collect_formatted_issues path in tests.

roundtrip.rs: use sync_from_datamodel to verify models parse and
compile without blocking errors.

model.rs: replace get_incoming_links (monolithic ModelStage1 API) with
model_causal_edges (salsa tracked function) for dependency verification.

db_diagnostic_tests.rs: remove old-path cross-validation comparison,
verify expected error codes directly from accumulator diagnostics.

db_fragment_cache_tests.rs: replace Project::from error checking with
collect_all_diagnostics.

Retained Project::from callers: project.rs tests (testing with_ltm
which requires monolithic Project, deferred to Phase 6), vdf.rs tests
(VDF APIs take &Project, deferred to Phase 6), interpreter paths
(retained per AC4.6).
Delete Simulation::compile() and compile_project from interpreter.rs,
bench_project_build from benches/compiler.rs, and set_dependencies_cached
from model.rs (Phase 6, Tasks 1-2 of the salsa migration).

The incremental compilation path (compile_project_incremental) is now
the sole production compilation entry point. Simulation::new and
run_to_end are retained as the AST interpreter reference spec.

set_dependencies and all_deps are retained because Project::base_from
still needs cross-model transitive dependency resolution that the salsa
model_dependency_graph does not replicate for module-containing models.
These will be removed when base_from is deleted in a later task.

TestProject::run_vm() now uses compile_incremental instead of the
deleted Simulation::compile(). The compiler_vector test for scalar
context rejection of array-producing builtins is updated to match the
incremental path's error format. The VM cross-check in
test_smooth_goal_seeking_ltm is removed with a TODO, since the
incremental LTM path does not yet handle module-containing models.
Gate `From<datamodel::Project> for Project`, `run_default_model_checks`,
and `ModelStage1::check_units` with `#[cfg(any(test, feature = "testing"))]`
so no production code can use the monolithic construction path.

`Project::base_from` remains available as pub(crate) because
`get_stdlib_composite_ports` in db.rs needs it in production (inside
OnceLock). The `From` impl delegates to `base_from` and is only needed
by the AST interpreter cross-validation tests.

Test helper methods in test_common.rs that depend on `Project::from`
(compile, build_sim, run_interpreter, etc.) are likewise gated.
The `compiler_vector` and `simulate` integration tests now require the
`testing` feature.
Delete collect_formatted_issues, format_project_error, and
format_model_error from libsimlin/errors.rs -- all three had zero
remaining callers after the CLI and tests migrated to the
collect_all_diagnostics path.

Update comments on ModelStage1.errors, ModelStage1.unit_warnings,
and Project.errors that incorrectly referenced
collect_formatted_issues as the reason for retention. The actual
reason these fields are retained is that Module::new (interpreter
path), test helpers, and get_stdlib_composite_ports still read them.

Variable-level errors/unit_errors fields are NOT removed: they are
populated during parsing and consumed by the production salsa
pipeline (compile_var_fragment in db.rs, db_ltm.rs), not just the
monolithic path as the plan assumed.
Update docstrings and comments that referenced the deleted monolithic
compilation path (Simulation::compile, compile_project) or described
the salsa path as an alternative to the monolithic path. The
monolithic path is now test-only (gated behind cfg(test/testing)),
so comments should reflect the current state rather than the old
dual-path architecture.
Add variable_relevant_dimensions tracked function that extracts
dimension names from a variable's SourceEquation without reading the
project-level dimension list. For scalar variables this produces an
empty set, completely decoupling them from dimension changes.

Add expand_maps_to_chains helper that transitively follows maps_to
and mappings links so that arrayed variables depending on A (which
maps_to B) also include B in their relevant set.

Modify parse_source_variable_impl to filter project dimensions
through the relevant set before passing them to the parse pipeline.
Scalar variables now pass an empty dimensions slice (no dependency on
project.dimensions at all), while arrayed variables only depend on
their own dimensions and transitive mapping targets.
Four tests verify AC8 dimension-granularity invalidation behavior:
- Scalar variable immune to dimension changes (pointer-equal cache hit)
- Arrayed variable with different dimension produces value-equal result
  and value-equal compiled fragment (early cutoff prevents downstream
  invalidation)
- Arrayed variable with same dimension is re-parsed (pointer differs)
- maps_to chain triggers re-parse when mapped-to dimension changes

Tests placed in a new db_dimension_invalidation_tests.rs file to keep
db_tests.rs under the 6000-line project lint threshold.
Reflect contract changes from the finish-salsa-migration branch:

- engine: document testing feature, cfg-gated Project::from and
  check_units, dimension-granularity invalidation
  (variable_relevant_dimensions), sole parse entry point
  (parse_source_variable_with_module_context), analyze_model signature
  change requiring SimlinDb + SourceProject, new
  db_dimension_invalidation_tests
- libsimlin: collect_formatted_issues replaced by
  collect_formatted_issues_from_diagnostics, layout requires synced
  project
- cli: all compilation uses incremental salsa path exclusively
- mcp: analyze_model callers provide SimlinDb + SourceProject
expand_maps_to_chains now follows reverse dimension mappings in addition
to forward ones. When a variable like s6[DimB] uses SMTH1(input_3[DimA],
...), the DimensionsContext built for its parse must include DimA (which
maps to DimB), not just DimB. Without DimA in context, the per-element
implicit variable expansion in builtins_visitor cannot perform the cross-
dimension substitution and stores an unresolved dimension reference
(input_3[dima]) that then fails lower_ast with DimensionInScalarContext,
ultimately surfacing as EmptyEquation in the compiler.
The `errors` and `unit_errors` fields on Variable::Stock/Var/Module, the
methods that read them (equation_errors, unit_errors, push_error,
push_unit_error), and the ModelStage1 helpers (get_variable_errors,
get_unit_errors) are from the monolithic compilation path. The salsa
incremental path emits all diagnostics via CompilationDiagnostic
accumulators instead.

Add doc comments pointing new callers toward db::collect_model_diagnostics
so the intended migration direction is clear without triggering compiler
deprecation warnings throughout the codebase.
@claude

claude Bot commented Mar 7, 2026

Copy link
Copy Markdown

Code Review

[P2] LTM flags never reset in analysis.rs::run_ltm_pipeline

File: src/simlin-engine/src/analysis.rs, lines ~133-134 (new code)

run_ltm_pipeline sets ltm_enabled and ltm_discovery_mode to true on the caller-provided db but never resets them. The old code created its own SimlinDb inside the function so flags were naturally scoped; now that db is passed from the caller, these flags leak. Compare with layout/mod.rs::try_detect_ltm_loops_incremental which correctly resets ltm_enabled to false after compilation. Current callers (MCP tools, tests) create fresh dbs per call so this doesn't cause issues today, but any future caller that reuses a db after analyze_model will get LTM-augmented compilations unexpectedly. Additionally, if compile_project_incremental or subsequent .ok()? calls cause an early return, the flags remain set with no cleanup path.


Overall correctness: The patch is correct for current usage. The LTM flag leak is a real defect in the API contract but does not affect any existing callers since they all create fresh SimlinDb instances. All other changes (monolithic path removal, dimension-granularity invalidation, expand_maps_to_chains, test migration) are structurally sound and well-tested (2853 tests passing). The catch_unwind removal is intentional and appropriate given the migration to Result-based error handling.

@claude

claude Bot commented Mar 7, 2026

Copy link
Copy Markdown

Code Review

Findings

[P2] Missing canonicalization in run_ltm_pipeline model lookup

File: src/simlin-engine/src/analysis.rs:137

At line 137, source_project.models(db).get(&actual_name) looks up the model by its display name (e.g., Main), but source_project.models() is keyed by canonical name (e.g., main). The parallel code in layout/mod.rs:2018-2019 correctly canonicalizes before lookup: let canonical_name = crate::canonicalize(&actual_name_owned). When the display name differs from the canonical name, this causes source_model to be None, silently skipping the entire CausalGraph construction and discover_loops_with_graph call -- the function returns None, and analyze_model gracefully degrades to empty loop fields. The compilation at line 131 still succeeds because compile_project_incremental internally canonicalizes.


[P2] LTM flags not reset in run_ltm_pipeline

File: src/simlin-engine/src/analysis.rs:127-128

run_ltm_pipeline sets ltm_enabled and ltm_discovery_mode to true on the caller-provided source_project at lines 127-128 but never resets them before returning. The analogous code in layout/mod.rs:2028,2036 properly resets set_ltm_enabled(db).to(false) after compilation. Since analyze_model takes a mutable SimlinDb from the caller, the db is left with LTM flags enabled. Current callers all create temporary dbs so this is not immediately broken, but the old code created a local db inside catch_unwind and never leaked state to the caller. If a future caller reuses the db after analyze_model, subsequent compilations would include LTM synthetic variables.


Overall Correctness

The patch is correct for the vast majority of cases -- existing tests pass, the monolithic path is cleanly gated behind cfg(test), and the incremental migration is thorough. The two findings above are edge-case issues (non-canonical model names, db reuse after analysis) that do not affect the primary compilation or simulation paths, but would be worth addressing.

@codecov

codecov Bot commented Mar 7, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 68.28087% with 131 lines in your changes missing coverage. Please review.
✅ Project coverage is 76.49%. Comparing base (3abe530) to head (3dbd0de).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
src/simlin-cli/src/main.rs 0.00% 88 Missing ⚠️
src/simlin-engine/src/test_common.rs 79.10% 14 Missing ⚠️
src/simlin-engine/src/db.rs 76.36% 13 Missing ⚠️
src/simlin-engine/src/ltm_finding.rs 28.57% 5 Missing ⚠️
src/libsimlin/src/layout.rs 60.00% 2 Missing ⚠️
src/simlin-engine/src/db_ltm.rs 0.00% 2 Missing ⚠️
src/simlin-engine/src/project.rs 93.75% 2 Missing ⚠️
src/simlin-engine/tests/layout.rs 90.47% 2 Missing ⚠️
src/libsimlin/src/errors.rs 95.00% 1 Missing ⚠️
src/simlin-engine/src/layout/mod.rs 97.72% 1 Missing ⚠️
... and 1 more
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #375      +/-   ##
==========================================
- Coverage   79.39%   76.49%   -2.91%     
==========================================
  Files         145      143       -2     
  Lines       37769    36163    -1606     
==========================================
- Hits        29986    27662    -2324     
- Misses       7783     8501     +718     

☔ 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.

@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: c7e3c9336e

ℹ️ 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/simlin-engine/src/analysis.rs Outdated
let results = vm.into_results();

// Build the CausalGraph from salsa-tracked causal edges.
let source_model = source_project.models(db).get(&actual_name).copied()?;

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 Canonicalize model key before lookup in run_ltm_pipeline

run_ltm_pipeline indexes source_project.models(db) with actual_name as-is, but the sync layer stores model keys in canonical form. When a project uses non-canonical casing (for example model name Main), this lookup returns None after simulation succeeds, so analyze_model degrades to empty loop results even though the model is valid. Canonicalize actual_name before the map lookup to avoid dropping loop analysis for mixed-case model names.

Useful? React with 👍 / 👎.

Three bugs found during code review:

1. analysis.rs: run_ltm_pipeline used the original (non-canonical) model
   name to query source_project.models(db), which is keyed by canonical
   names. Models named "Main" would silently produce empty loop results.
   Fix: canonicalize actual_name when building it.

2. analysis.rs: analyze_model enabled ltm_enabled and ltm_discovery_mode
   on the caller's salsa db but never restored them, leaving LTM
   discovery mode active for subsequent compilations. Fix: move flag
   management to analyze_model with guaranteed cleanup after
   run_ltm_pipeline returns.

3. cli/main.rs: print_equations iterated model_names (original names) but
   looked them up in models (canonical keys), causing misses for
   non-canonical model names. Fix: canonicalize before lookup.
@claude

claude Bot commented Mar 7, 2026

Copy link
Copy Markdown

Code Review

This is a large, well-structured migration that eliminates the monolithic compilation path in favor of the salsa incremental pipeline. The deletion of Simulation::compile(), compile_project, set_dependencies_cached, and related code is clean, and the test migration is thorough. The new dimension-granularity invalidation (variable_relevant_dimensions + expand_maps_to_chains) is a meaningful optimization. The catch_unwind removal is appropriate now that the salsa path is the sole production path.

Findings

[P3] build_uid_to_loop_name receives canonical name but get_model() does exact string match

src/simlin-engine/src/analysis.rs, lines 128-137.

In run_ltm_pipeline, actual_name is now the canonicalized model name (e.g. "main" from crate::canonicalize(&m.name).into_owned()), but build_uid_to_loop_name passes it to project.get_model() which does an exact string comparison against m.name. For models whose display name differs from the canonical form (e.g. "Main", "My Model"), get_model will return None and user-assigned loop names from loop_metadata will be silently lost. The old code passed the display name (m.name.clone()) so this is a regression. The impact is cosmetic — loops are still detected, just without their persisted names — but the fix is straightforward: either pass the display name to build_uid_to_loop_name, or make get_model use canonicalized comparison.

Overall Correctness

Correct. The patch is well-tested (2853 tests, plus new dimension-invalidation and analysis tests), all catch_unwind removals are intentional, and the migration from monolithic to incremental is consistent across CLI, MCP, libsimlin, and layout callers. The one finding above is a minor cosmetic regression that does not affect simulation correctness or existing tests.

Two bugs found in review iteration 2:

1. analysis.rs: after canonicalizing actual_name for salsa lookups,
   build_uid_to_loop_name and resolve_loop_name still need the original
   (non-canonical) model name for datamodel::Project::get_model(), which
   does exact name matching. Refactored run_ltm_pipeline to track both
   original_name and canonical_name separately.

2. layout/mod.rs: the heuristic dependency fallback
   (extract_equation_deps) ran whenever salsa dependency extraction
   returned empty deps, even for constant variables that genuinely have
   no dependencies. Now checks whether the equation actually parsed
   (AST exists) before deciding to fall back; constants with valid empty
   deps are no longer fed to the string heuristic.
@claude

claude Bot commented Mar 7, 2026

Copy link
Copy Markdown

Code Review: engine: finish salsa migration, delete monolithic compilation path

Summary

This is a large, well-structured migration PR (48 files, ~9500 lines of diff) that:

  1. Makes compile_project_incremental the sole production compilation path
  2. Deletes Simulation::compile(), compile_project, set_dependencies_cached, collect_formatted_issues, and the monolithic Project::from (gated behind #[cfg(any(test, feature = "testing"))])
  3. Removes catch_unwind wrappers from incremental paths (intentional — salsa queries shouldn't panic on well-formed inputs)
  4. Adds dimension-granularity invalidation so scalar variables aren't invalidated by dimension changes
  5. Fixes expand_maps_to_chains to follow reverse maps_to edges for cross-dimension SMOOTH/DELAY builtins

Detailed Analysis

Core migration (db.rs, interpreter.rs, project.rs): The removal of the monolithic path is clean. All callers are migrated: analysis.rs, layout/mod.rs, patch.rs, simlin-cli, simlin-mcp, and libsimlin. The parse_source_variable non-module-context variant is unified into parse_source_variable_with_module_context with empty context — this is semantically equivalent since module_idents.map_or(false, |set| set.contains(...)) returns false for both None and Some(empty_set).

Dimension invalidation (variable_relevant_dimensions, expand_maps_to_chains): The logic is correct. Scalar variables produce an empty dimension set (no salsa dependency on project.dimensions). Arrayed variables track only their referenced dimensions plus transitive maps_to chains in both directions. The worklist algorithm in expand_maps_to_chains properly handles forward, reverse, and transitive closure.

LTM flag management (analyze_model, try_detect_ltm_loops_incremental): Flags are set before the pipeline and reset afterward. Without catch_unwind, a panic would skip the reset — but this is an intentional design choice, and a panicking salsa query would leave the db in an unusable state regardless.

CLI print_equations rewrite: Correctly uses source_var.inflows(&db) / outflows(&db) instead of pattern-matching on Variable::Stock { inflows, outflows, .. }. The stdlib filter (model_name.starts_with("stdlib⁚")) is equivalent to the old model.implicit check since implicit was only set for stdlib models.

libsimlin changes: collect_formatted_issues (walking struct fields) is replaced by collect_formatted_issues_from_diagnostics (reading salsa accumulators). The new format_diagnostic_with_datamodel correctly enriches equation/unit errors with snippet context. The layout FFI now requires the project to be synced first (returning an error otherwise) rather than silently accepting a missing db_state.

Findings

No bugs found. The migration is thorough, all caller sites are updated consistently, and the test infrastructure properly validates both paths via differential tests.

Verdict

Overall correctness: Correct. The patch cleanly removes the monolithic compilation path, consistently migrates all callers to the incremental salsa pipeline, and adds proper test coverage for the new dimension invalidation behavior. The catch_unwind removal is an intentional and reasonable architectural decision for the salsa-based path.

@bpowers

bpowers commented Mar 7, 2026

Copy link
Copy Markdown
Owner Author

Review cycle summary

Three iterations of dual-reviewer feedback (Codex + Claude) identified and addressed several genuine issues in this salsa migration PR:

Iteration 1 fixed model name canonicalization mismatches: the CLI's print_equations and the analysis module's run_ltm_pipeline were using original model names to look up values in the salsa models map (which uses canonical/lowercase keys). Also moved LTM flag management into analyze_model so callers don't need to worry about cleanup. Added tests for non-canonical name lookups and LTM flag reset behavior.

Iteration 2 refined the layout dependency extraction fallback. The initial salsa-based dep extraction was too aggressive — it treated variables with broken equations (no AST) the same as genuine constants (empty deps). The fix checks parsed.variable.ast().is_none() to distinguish parse failures (fall back to string heuristics) from valid constants (trust empty deps). Added a test for constant variable dependency behavior.

Iteration 3 found no actionable issues. Codex flagged module-backed builtins (SMOOTH/DELAY) potentially losing deps in layout, but this was a false positive — dependency extraction runs at the pre-module-expansion AST level, so original input variable names are correctly preserved. Both reviewers confirmed clean in the same iteration.

@bpowers
bpowers merged commit 22978a5 into main Mar 7, 2026
10 checks passed
@bpowers
bpowers deleted the finish-salsa-migration branch March 7, 2026 22:24
@claude

claude Bot commented Mar 7, 2026

Copy link
Copy Markdown

Code Review: engine: finish salsa migration, delete monolithic compilation path

I've reviewed the full diff across all 40 changed files (2098 additions, 1947 deletions). This is a well-structured 7-phase migration that makes the incremental salsa compilation pipeline the sole production path and cleans up significant technical debt.

Summary of Changes Reviewed

  • Monolithic path removal: Simulation::compile(), compile_project, set_dependencies_cached, try_detect_ltm_loops_monolithic, with_ltm(), with_ltm_all_links() — all correctly deleted with production callers migrated to compile_project_incremental.
  • parse_source_variable unification: The non-module-context variant is removed; all call sites now use parse_source_variable_with_module_context. Verified that module_idents: None and module_idents: Some(&empty_set) are semantically equivalent in builtins_visitor.rs (line 192: is_some_and(|ids| ids.contains(ident)) returns false for both).
  • Dimension-granularity invalidation (variable_relevant_dimensions + expand_maps_to_chains): Scalar variables correctly produce an empty set (no dependency on project.dimensions). Arrayed variables correctly expand via both forward and reverse maps_to edges. The BFS in expand_maps_to_chains terminates correctly since expanded.insert() prevents revisiting.
  • catch_unwind removal: Correctly removed from incremental paths in layout. The old catch_unwind was a no-op under WASM's panic = "abort" anyway, and salsa queries don't panic on well-formed inputs.
  • Test migration: TestProject correctly gates assert_compiles() / build_sim() / etc. behind #[cfg(any(test, feature = "testing"))] while providing new compile_incremental() / run_vm_incremental() / assert_compiles_incremental() methods.
  • Layout metadata: compute_metadata now uses salsa dependency extraction with proper fallback to string heuristics when the parse fails (AST is None). The ensure_db_state_mut helper correctly manages the lifetime of a temporary db.
  • CLI: All paths correctly use sync_from_datamodel_incremental + compile_project_incremental.
  • Patch: apply_rename_variable correctly migrated from CompiledProject to reconstruct_model_variables via salsa.

Findings

No bugs found. The changes are internally consistent, the cfg gates are correctly applied, and the semantic equivalences hold across all migrated call sites. The new db_dimension_invalidation_tests.rs (350 lines) provides thorough coverage of the invalidation logic.

Overall Correctness Verdict

Correct. The patch cleanly removes the monolithic compilation path while preserving all existing behavior through the incremental salsa pipeline. All call sites are properly migrated, the dimension invalidation logic is sound, and no existing code or tests should break.

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.

1 participant