Repository navigation
engine: consolidate compilation onto salsa incremental path - #360
Conversation
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 2fd982d563
ℹ️ 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".
| engine::db::set_project_ltm_enabled(&mut db, source_project, enable_ltm); | ||
| engine::db::compile_project_incremental(&db, source_project, &model_ref.model_name) |
There was a problem hiding this comment.
Reset project LTM flag after creating a simulation
simlin_sim_new mutates the shared SourceProject by setting ltm_enabled and then returns without restoring prior state. Because other FFI paths (simlin_project_is_simulatable and simlin_project_get_errors) call compile_project_incremental without setting this flag, a caller that creates one LTM simulation can cause later non-LTM checks to compile in LTM mode and surface incorrect NotSimulatable/diagnostic results.
Useful? React with 👍 / 👎.
| source_project.set_ltm_enabled(db).to(true); | ||
| let compiled_sim = | ||
| crate::db::compile_project_incremental(db, source_project, &actual_name_owned).ok()?; | ||
| let mut vm = crate::vm::Vm::new(compiled_sim).ok()?; |
There was a problem hiding this comment.
Always clear temporary LTM mode on layout failures
The incremental layout path enables ltm_enabled and then uses fallible ? calls before the later reset to false. If compilation/simulation fails (or panics and is caught), the function exits early and leaves the shared project stuck in LTM mode, which then contaminates subsequent non-LTM compile/error queries that reuse the same DB state.
Useful? React with 👍 / 👎.
Completed brainstorming session. Design includes: - PREVIOUS/INIT conversion from stdlib modules to VM builtins - LTM parallel compilation path (compile_ltm_var_fragment) - Error accumulator consolidation (sole error source) - engine::Project removal from apply_patch - SimlinDb threading to all internal callers - Old monolithic bytecode compilation path deletion - 6 implementation phases
Six-phase implementation plan for consolidating the salsa incremental compiler as the sole production compilation path. Phases cover: PREVIOUS/INIT as builtin opcodes, LTM parallel compilation, error accumulator consolidation, apply_patch migration, internal caller threading, and monolithic path deletion. Includes test requirements mapping all acceptance criteria to automated tests or human verification.
Add two new BuiltinFn enum variants for PREVIOUS(x) and INIT(x), replacing what were previously stdlib dynamic module implementations. Update all exhaustive match arms across the codebase: name(), try_map(), for_each_expr_ref(), walk_builtin_expr(), and every AST lowering pass, compiler context, codegen, interpreter, patch, units_check, and units_infer module. The is_builtin_fn() registration is deferred to Task 3, when the visitor, codegen, and VM form a complete pipeline. Without that pipeline, registering in is_builtin_fn() would intercept previous/init calls before module expansion, breaking LTM equations.
Add two new Opcode variants:
- LoadPrev { off }: pushes curr[module_off + off] onto the stack,
semantically distinct from LoadVar for dependency tracking but
identical VM behavior during the dt-phase.
- LoadInitial { off }: will push from initial-value buffer at t=0;
currently unreachable until the buffer is wired in Task 5.
Both have stack_effect (0, 1) matching LoadVar.
Add corresponding SymbolicOpcode variants (SymLoadPrev, SymLoadInitial)
with symbolize/resolve mappings following the same pattern as
LoadVar/SymLoadVar.
Add Previous/Init handling to builtins_visitor, expr1 resolution, compiler codegen, interpreter eval, and VM dispatch. Both functions currently continue to use stdlib module expansion because: - PREVIOUS: LoadPrev reads from curr[] which holds CURRENT values for non-stock variables during the Flows phase (evaluation ordering issue) - INIT: the stdlib module's internal stock pulls the variable into the Initials runlist; without it, aux-only models have empty Initials and the initial_values snapshot is all zeros The opcodes and BuiltinFn variants are scaffolding for future activation when the evaluation model is updated. The interpreter captures an initial_values snapshot after the Initials phase, and the VM stores a parallel initial_values buffer populated in run_initials().
The LoadPrev opcode now reads from a dedicated prev_values buffer instead of curr[]. Both the interpreter and VM snapshot curr[] after stocks but before the time advance each timestep, and seed prev_values from the post-initials state at t=0. The codegen handles Expr::ModuleInput inside BuiltinFn::Previous by falling back to LoadModuleInput, and unexpected arg types by evaluating the expression normally. PREVIOUS still routes through module expansion in builtins_visitor because promoting it to a builtin changes the model's dependency graph, which breaks LTM link-score evaluation ordering. The scaffolding is ready for activation once the evaluation model supports it.
Phase 1 scaffolding verification: test that PREVIOUS and INIT work correctly through the module-expansion path, with interpreter-vs-VM parity checks. Tests cover: - PREVIOUS(stock): interpreter/VM produce identical lagged values - INIT(aux): interpreter/VM agree on frozen t=0 value - PREVIOUS(flow): same lag behavior for flow variables - MODEL_NAMES status: documents that "previous" and "init" remain in stdlib MODEL_NAMES (activation deferred due to LTM dependency graph ordering)
… input These two boolean fields on the SourceProject salsa input control the LTM (Loops That Matter) subsystem. ltm_enabled gates compute_layout slot allocation and assemble_module compilation of LTM synthetic variables. ltm_discovery_mode selects between scoring only edges in detected loops vs all causal edges. Both default to false so existing behavior is unchanged.
After the existing explicit + implicit variable sections, compute_layout now allocates slots for LTM synthetic variables as a third section. This is gated on project.ltm_enabled(db) so there is zero overhead when LTM is disabled. When the model has no feedback loops the LTM variable list is empty and no slots are allocated. Discovery mode selects the broader all-link variable set via ltm_discovery_mode.
Implement compile_ltm_var_fragment and model_ltm_implicit_var_info as salsa tracked functions for per-equation LTM compilation. This enables incremental recompilation of link scores, loop scores, and relative loop scores independently of the main variable compilation pipeline. Key additions: - parse_ltm_equation: creates transient aux variables and runs them through BuiltinVisitor for PREVIOUS module expansion - model_ltm_implicit_var_info: tracked function collecting metadata about implicit PREVIOUS modules created by LTM equations - compile_ltm_var_fragment: tracked function keyed on LtmLinkId for link score compilation - compile_ltm_equation_fragment: shared implementation for any LTM equation (link/loop/relative scores) - compile_ltm_implicit_var_fragment: compiles PREVIOUS stdlib module instances referenced by LTM link score equations - compute_layout Section 3b: slot allocation for LTM implicit modules - assemble_module Pass 3: assembly of LTM variable fragments and their implicit module fragments into the final bytecode The LTM compilation code is extracted into db_ltm.rs to keep db.rs under the 6000-line threshold.
Replace the monolithic with_ltm() + compile_simulation fallback in simlin_sim_new with the salsa-based incremental pipeline. Both LTM and non-LTM paths now use compile_project_incremental; the only difference is the ltm_enabled flag on SourceProject. This required three supporting fixes in the incremental compilation pipeline: 1. Guard LTM sections in compute_layout and assemble_module with is_root to prevent salsa dependency cycles when stdlib models are compiled (compute_layout -> model_ltm_implicit_var_info -> compute_layout for stdlib "previous" model). 2. In compile_ltm_implicit_var_fragment, add ALL LTM implicit module refs to module_models (not just the current one), because PREVIOUS modules chain: instance N reads instance N-1's output via a middot submodel reference. 3. Enumerate LTM implicit module instances in enumerate_module_instances_inner and include LTM variable offsets in calc_flattened_offsets_incremental, so the VM can find compiled modules and the FFI can look up loop score variables by offset.
Phase 2, Task 6: five new tests in db_tests.rs verifying that the incremental compilation pipeline handles LTM correctly: - AC1.4: no-loop model has zero LTM overhead (identical slot counts) - AC1.5: disabling LTM after enabling produces identical output - AC1.1: LTM synthetic variables appear in compiled output with correct offsets and produce non-zero loop scores at runtime - AC1.6: discovery mode compiles successfully with per-link scores Also adds a no_loop_project() helper for testing models without feedback loops.
Add DiagnosticSeverity enum (Error/Warning) to Diagnostic struct and Assembly(String) variant to DiagnosticError. Update all existing Diagnostic creation sites to include severity: equation and model errors use Error, unit errors use Warning. Update format_diagnostic in libsimlin to handle the Assembly variant and update test Diagnostic structs with the new severity field.
Instead of silently returning None when a variable has equation errors or table construction failures, accumulate each error as a CompilationDiagnostic before bailing out. This makes error codes like BadTable, EmptyEquation, and MismatchedDimensions accessible through the salsa accumulator path (AC2.2, AC2.3, AC2.4). The function still returns None so assemble_module detects the failure, but the specific error details are now recorded in the accumulator.
…ble_simulation Add try_accumulate_diagnostic helper that safely pushes diagnostics into the salsa accumulator when a tracked context is active, catching the panic when called outside tracked functions (e.g. from compile_project_incremental). All Err return paths in assemble_module and assemble_simulation now push Assembly-variant diagnostics: circular dependencies, missing fragments, concatenation failures, resolve_module failures, missing model references, and module enumeration failures.
New salsa tracked function that performs unit inference and checking independently of the old Project compilation path. Builds temporary ModelStage0/ModelStage1 representations from salsa-cached parsed variables for all project models (needed for cross-module unit constraints), then runs the same infer+check pipeline as run_default_model_checks. Unit errors are accumulated as Warning severity diagnostics. model_all_diagnostics now calls check_model_units instead of reading unit_errors from parsed variables (which were empty in the pure salsa path since the old path populated them during Project::from).
model_all_diagnostics now calls compile_var_fragment for each variable in addition to check_model_units. This surfaces compilation-level errors (BadTable, MismatchedDimensions, etc.) through the salsa accumulator without needing to invoke compile_project_incremental or assemble_simulation. The previous explicit equation-error loop is replaced by compile_var_fragment calls, which are a superset: they first check parse errors (accumulating them) and then proceed with compilation to catch additional error types. compile_var_fragment is called with is_root: true and empty module_input_names for diagnostic collection, ensuring implicit vars (time, dt) are available and preventing false-positive errors for variables that reference them.
Add tests verifying each acceptance criterion for Phase 3: - AC2.1: Parity between old struct-field error collection and new salsa accumulator. Both paths produce the same error codes for a project with syntax errors and empty equations. - AC2.2: BadTable error from mismatched x/y table lengths surfaces as the specific BadTable error code through the accumulator. - AC2.3: EmptyEquation error for a stock with no equation surfaces through the accumulator with Error severity. - AC2.4: MismatchedDimensions error for array variables with incompatible named dimensions surfaces through the accumulator. This required adding a lowered-variable error check in compile_var_fragment -- after lower_variable runs, dimension mismatch errors are now accumulated before returning None. - AC2.5: Unit inference warnings are accumulated with Warning severity, not blocking Error severity. - AC2.7: VM bytecode validation errors (BadSimSpecs from Vm::new) are detectable after compile_project_incremental succeeds. Assembly-level errors (CircularDependency) are accumulated via model_dependency_graph and surfaced through collect_all_diagnostics. Tests are in a new db_diagnostic_tests.rs file to keep db_tests.rs under the 6000-line project lint threshold.
…roject The SimlinProject struct now stores a datamodel::Project (lightweight data) instead of engine::Project (compiled model state). All query functions (get_errors, is_simulatable, get_links, get_loops, get_latex_equation, get_incoming_links, get_dependencies) now go through the salsa incremental compilation path exclusively. Key changes: - SimlinProject.project field replaced by SimlinProject.datamodel - model.rs: rewrote get_incoming_links, get_links, get_latex_equation, get_dependencies to use salsa tracked functions - analysis.rs: rewrote get_loops to use model_detected_loops (with polarity and deterministic r1/b1/u1 IDs), get_links to use model_causal_edges - patch.rs: rewrote error collection to use collect_all_diagnostics and compile_project_incremental instead of engine::Project - engine: extracted causal graph analysis into db_analysis.rs to keep db.rs under the 6000-line threshold - engine: added model_detected_loops for polarity-aware loop detection matching LTM augmentation IDs - engine: replaced catch_unwind in try_accumulate_diagnostic with a thread-local tracked-context flag, fixing WASM panic (catch_unwind does not work with panic=abort in release builds) - ast: added Ast<Expr0> trait impl and latex_eqn_expr0 for rendering parsed equations without full compilation
Add four tests covering the AC2 acceptance criteria for the patch error checking migration to the incremental compilation path: - AC2.1 syntax error: patch with "3 * )" is rejected with a parse error code and model state is unchanged - AC2.1 circular dependency: patch creating a->b->a cycle is rejected with CircularDependency/NotSimulatable and model is unchanged - AC2.1 valid patch: accepted patch produces correct simulation results through the incremental pipeline (stock integration) - AC2.6 source assertion: patch.rs must not contain any reference to compile_simulation, ensuring the monolithic path stays eliminated Also fix a stale doc comment in patch.rs that still referenced engine::Project instead of datamodel::Project.
Replace the monolithic Project::from + with_ltm_all_links() + Simulation::new compilation path in run_ltm_pipeline with the incremental salsa path (SimlinDb + sync_from_datamodel + compile_project_incremental). LTM discovery mode is enabled on the salsa SourceProject so that link score synthetic variables cover all causal edges. A plain Project::from (without with_ltm_all_links) is still built for discover_loops, which needs the compiled model graph for CausalGraph structural analysis. The resolve_loop_name and to_loop_summary helpers now take &datamodel::Project directly instead of going through engine::Project.datamodel, removing a needless coupling. The analyze_model public API signature is unchanged -- callers (MCP tools, tests) continue to pass &datamodel::Project as before.
Add an optional db_state parameter (SimlinDb + SourceProject) through the layout function call chain so that LTM loop detection can use the incremental salsa compilation path when a database is available. The new try_detect_ltm_loops_incremental function uses model_detected_loops for loop discovery, enables LTM via the salsa setter, compiles incrementally, simulates, and extracts loop scores -- all without building the monolithic Project::from + with_ltm pipeline. The monolithic path is preserved as a fallback when no db is provided. The libsimlin FFI caller (simlin_project_diagram_sync) passes the persistent sync state's SourceProject through to the layout engine. MCP tools and tests pass None since they lack a persistent db.
Replace the monolithic compilation pipeline (Project::from + Simulation::new + sim.compile + Vm::new) with the salsa incremental path (SimlinDb + sync_from_datamodel_incremental + compile_project_incremental + Vm::new). Both the normal and LTM simulation paths now go through run_incremental(). The monolithic Project::from is still used for loop detection (ltm::detect_loops) and error reporting (collect_formatted_issues), which walk the engine::Project struct fields directly.
The CLI no longer calls with_ltm() -- it was migrated to the incremental path. Update the deprecation doc comment to list only the layout monolithic fallback as the remaining production caller.
Replace sim.compile() (monolithic) with compile_project_incremental in simulate_ltm_path. The interpreter leg using project.with_ltm() is retained for cross-validation. The original datamodel is cloned before with_ltm() consumes the project, then synced into a fresh SimlinDb with ltm_enabled=true. test_smooth_goal_seeking_ltm keeps the monolithic path because the incremental LTM compilation does not yet support models containing stdlib module instances (SMOOTH); a comment documents this. Fix a bug in assemble_module where rfind for the LTM link score prefix separator searched the full variable name including the portion after the arrow, causing a slice bounds panic when the "to" name contained separator characters (e.g. module instance names like "$:smoothed_level:0:smth1"). Also migrate remaining monolithic sim.compile() calls in the simulation and array_ops benchmarks to the incremental path.
Replace monolithic Simulation::new + compile() with the salsa-based compile_project_incremental path in compiler.rs benchmarks, and remove monolithic baseline groups from incremental benchmarks. The array_ops.rs changes are whitespace-only (cargo fmt removed blank lines). is_simulatable now uses catch_unwind around the incremental path because some models (C-LEARN) panic rather than returning a clean error.
All VM compilation legs in simulate_path now use a compile_vm helper that prefers the salsa-backed incremental path (compile_project_incremental) for non-module models. Models with explicit or implicit modules (SMOOTH, DELAY, INIT, etc.) fall back to the monolithic Simulation::compile() path because the incremental path does not yet correctly propagate module input values during simulation. The simulates_wrld3_03 and incremental_compilation_covers_all_models tests are also updated to use the same pattern.
Replace the monolithic fallback in compile_vm() with the salsa-backed incremental compilation path for all test models, including those with module variables (explicit and implicit via SMOOTH/DELAY/TREND/etc.). Three bugs in the incremental path prevented module-containing models from producing correct simulation results: 1. assemble_module excluded module input variables from initials and flows runlists. Module inputs need LoadModuleInput->AssignCurr bytecodes in these phases to copy parent-provided values into sub-model slots. Now only excluded from the stocks runlist. 2. model_dependency_graph_impl excluded module variables from the flows runlist. The monolithic path puts modules in both flows (for EvalModule) and stocks (for stock updates). Fixed the flows predicate to include modules. 3. model_dependency_graph_impl did not filter stock dependencies from module dt_deps. Composite references like "submodel·stock_var" must be filtered because stocks break the dependency chain in the dt phase. Without filtering, spurious cycles caused incorrect topological orderings (e.g., lynxes before hares). Added stock-kind check matching the monolithic module_deps behavior.
Remove compile_project from the crate's public re-exports since no external callers exist. Delete Project::from_with_salsa_sync and its test (the old apply_patch bridge is no longer needed). Mark both Simulation::compile() and compile_project() as test-only with doc comments noting the module-input propagation bug that prevents full removal. Delete 8 cross-validation tests in db_tests that compared monolithic vs incremental compilation paths, and refactor 2 implicit-lookup tests to use fresh incremental compiles as reference instead of the monolithic oracle. Migrate the nonexistent-model error test to use the incremental path.
Mark Simulation::compile() and compile_project() as deprecated with explicit references to GitHub #295 (module input propagation bug). Add deprecation doc comments to ModelStage1.errors, .unit_warnings, and Project.errors noting that these fields are superseded by salsa accumulators but retained for the monolithic path.
Mark Simulation::compile() and compile_project() as deprecated with explicit references to GitHub #295 (module input propagation bug). These functions are retained only because the incremental path does not yet correctly propagate module input values during VM simulation.
…lidation tests Add doc comments to Simulation::compile() and compile_project() marking them as test-only, with notes that the incremental path (in db.rs) is the production entry point. The monolithic path is retained because the incremental path does not yet propagate module input values correctly. Delete compile_project_f64_matches_simulation_compile and compile_as_matches_compile_project cross-validation tests (redundant now that simulate.rs tests exercise both paths). Migrate the nonexistent-model error test to the incremental compile path.
Replace the module-detection-based compile_vm routing (which used the monolithic sim.compile() for all models with modules) with the incremental salsa-backed compile_project_incremental path as the default for all tests. Five bug fixes in db.rs make the incremental path handle modules correctly: 1. topo_sort_str: filter the output to only include variables from the input set, preventing dependency traversal from pulling in stocks that should not be in the flows runlist. 2. model_dependency_graph_impl flows runlist: include stock-typed module inputs (matching the monolithic path's `instantiation.contains(id) || !var.is_stock()` filter) so that LoadModuleInput -> AssignCurr opcodes propagate parent values. 3. compile_var_fragment: generate flow_bytecodes for stock-typed module inputs (not just non-stocks) so the flows phase has bytecodes to execute for these variables. 4. model_dependency_graph_impl dt_deps: filter out composite module references to stocks (e.g., "submodel.stock_var") to prevent spurious dependency cycles. 5. assemble_module runlist filtering: allow module input variables through initials and flows phases (only exclude from stocks), matching the monolithic path's instantiation-based filtering. A few models with subscripted SMOOTH/DELAY builtins and WRLD3 still use the monolithic path as a fallback due to pre-existing incremental path limitations with array builtin compilation.
…idation tests Remove compile_project from the crate's public re-exports in lib.rs since all external callers (libsimlin, simlin-cli) use compile_project_incremental. Internal uses via crate::interpreter::compile_project still work. Delete Project::from_with_salsa_sync and its test -- the old apply_patch bridge between monolithic and salsa is no longer needed after Phase 4 rewrote apply_patch to use the incremental path. Delete 6 cross-validation tests in db_tests.rs that compared monolithic vs incremental compilation output: - test_incremental_bytecode_equivalence - test_incremental_vs_monolithic_output - test_assemble_simulation_stock_flow (and stock_flow_project helper) - test_incremental_teacup_constant_detection - test_incremental_teacup_simulation - test_ac4_3_full_bytecode_equivalence_stock_flow_lookup Refactor 2 implicit-lookup tests to use a fresh incremental compile as the reference instead of the monolithic oracle: - test_incremental_compile_implicit_lookup_dep_tables - test_incremental_compile_implicit_lookup_dep_tables_after_equation_update
Reflect the 6-phase salsa consolidation changes across CLAUDE.md files and architecture.md: - engine CLAUDE.md: new "Incremental compilation (salsa)" section documenting db.rs, db_analysis.rs, db_ltm.rs, db_diagnostic_tests.rs; updated builtins (PREVIOUS/INIT), bytecode (LoadPrev/LoadInitial), VM (snapshot buffers), interpreter (deprecated), project.rs (with_ltm deprecated), analysis.rs (uses incremental path) - libsimlin CLAUDE.md: SimlinProject now wraps datamodel::Project (not engine::Project); simulation uses unified incremental pipeline for both LTM and non-LTM; error collection via salsa accumulators; new test files (tests_incremental.rs, tests_patch.rs) - architecture.md: primary compilation path is compile_project_incremental; interpreter deprecated; PREVIOUS/INIT intrinsic opcodes - interpreter.rs: improve deprecation doc-comments with GitHub #295 refs
Human test plan covering all 6 phases of the salsa consolidation implementation. Documents automated test coverage for 30 acceptance criteria, manual verification steps for 4 design decisions, and known gaps deferred by design (LoadPrev/LoadInitial activation).
2fd982d to
cc55ac9
Compare
Code Review: engine: consolidate compilation onto salsa incremental pathFindings[P1]
|
Address code review feedback: - Fix ltm_enabled leak: use and_then chains instead of ? returns in try_detect_ltm_loops_incremental so set_ltm_enabled(false) always runs - Canonicalize model name before SourceProject lookup in layout metadata - Add compute_link_polarities to return per-link polarity from causal graph analysis, fixing hardcoded Unknown polarity in analyze_get_links - Fix stale doc comment referencing non-existent set_tracked_context_flag Fix pre-existing simulation regression: PREVIOUS(SELF, expr) where expr depends on another variable (e.g. IF switch=1 THEN 1 ELSE 0) produced wrong initial values. The initials runlist was missing transitive deps of implicit intermediate variables created by the builtins_visitor for complex PREVIOUS arguments. The module's stock was initialized before its dependency was evaluated, reading uninitialized zeros. Also fix pre-existing compilation errors: Ast::Arrayed pattern field count mismatch, missing imports in interpreter tests, and stale field name in libsimlin project.rs.
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## main #360 +/- ##
==========================================
- Coverage 79.16% 78.75% -0.42%
==========================================
Files 137 139 +2
Lines 35221 36480 +1259
==========================================
+ Hits 27883 28729 +846
- Misses 7338 7751 +413 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
Code Review[P2] Panic-safety:
|
simlin_sim_new sets ltm_enabled=true on the shared SourceProject for LTM simulations but never resets it. Subsequent operations sharing the same SourceProject (e.g. patch validation) would compile in stale LTM mode, potentially causing spurious failures or different error behavior. Reset the flag immediately after compilation.
Code Review: engine: consolidate compilation onto salsa incremental pathThis is a large, well-structured PR that migrates LTM analysis, error reporting, and the CLI/layout callers onto the salsa incremental compilation path. The design doc, acceptance criteria, and test coverage are thorough. One bug found. Findings[P2]
|
… leak Two fixes from review feedback: 1. patch.rs: Hold the datamodel lock for the entire apply_project_patch_internal operation. Previously, the datamodel lock was released between validation and commit, allowing a concurrent patcher to snapshot a stale datamodel and overwrite the first writer's committed changes (lost update). 2. layout/mod.rs: Split try_detect_ltm_loops_incremental into separate catch_unwind scopes so that set_ltm_enabled(false) always executes even if compilation panics inside the catch_unwind boundary.
The comment claimed the flag was managed by model_all_diagnostics, but it is never set to true. Assembly errors propagate via Result::Err from compile_project_incremental. Update the comment to accurately describe the current state and purpose as scaffolding.
Code ReviewThis is a large, well-structured PR that consolidates the compilation pipeline onto the salsa incremental path across 6 phases. Findings[P3] Potential duplicate project-level diagnostics in multi-model projects
Overall Correctness VerdictCorrect. The patch should not break existing code or tests. The concurrency simplification in |
Code ReviewSummaryThis is a large-scale refactoring PR that consolidates the compilation pipeline from a monolithic
FindingsNo blocking issues found. Notes
Overall Correctness VerdictCorrect. The patch does not introduce bugs that would break existing code or tests. Lock ordering is consistent, error handling is preserved, and the incremental compilation path correctly mirrors the behavior of the monolithic path. The PREVIOUS/INIT opcode scaffolding is properly guarded and documented as deferred work. |
Review cycle summaryFour review iterations (Codex gpt-5.3-codex + Claude) identified and addressed the following improvements: Iteration 1 fixed pre-existing issues uncovered by the consolidation: a Iteration 2 addressed an Iteration 3 fixed two concurrency issues: (1) a lost-update window in Iteration 4 fixed a misleading doc comment on Deferred items tracked as GitHub issues: PREVIOUS/INIT opcode activation (#362), incremental compiler panics on C-LEARN (#363). |
module_deps() filtered stock inputs during the initial phase, dropping the dependency edge from modules (SMOOTH3, DELAY, etc.) to their stock inputs. This meant the topological sort treated them as independent, and their relative init order depended on HashMap iteration. When the module happened to be initialized before its stock input, the module read 0 instead of the stock's actual initial value. The fix removes the is_stock filter in the initial branch of module_deps -- during initialization, stock values ARE needed by modules that depend on them. Also replaces HashSet with BTreeSet in build_runlist's initials path so that the topo sort input is deterministic, preventing similar ordering bugs from being hidden by non-determinism.
The HashSet non-determinism in build_runlist acts as free fuzzing of init ordering among independent variables. It is what caught the missing stock dependency bug in the first place -- a deterministic order would have silently hidden the bug if it happened to be a "lucky" ordering. The real fix is the dependency graph correction (removing the is_stock filter in module_deps for initials), not making the ordering deterministic.
Code ReviewThis is a large, well-structured consolidation of the compilation pipeline onto the salsa incremental path. I reviewed the core engine changes (db.rs, db_analysis.rs, db_ltm.rs, vm.rs, bytecode.rs, codegen.rs, builtins_visitor.rs, interpreter.rs), the FFI layer changes (patch.rs, simulation.rs, model.rs, layout.rs, lib.rs, project.rs), and the threading/locking model across all mutexes. Findings[P3]
The catch-all What I verified (no issues found)
Overall CorrectnessCorrect. The patch is free of blocking bugs. The one finding is a latent issue in currently-dead scaffolding code. Existing tests should not break, and the incremental compilation pipeline is correctly structured. |
Summary
LoadPrev/LoadInitialopcodes,BuiltinFn::Previous/Initvariants,prev_values/initial_valuessnapshot buffers in VM, and module expansion for PREVIOUS/INIT intrinsics.ltm_enabled/ltm_discovery_modeflags onSourceProject, generate synthetic LTM variables through the incremental pipeline.DiagnosticErrorwithAssemblyvariant and severity levels, accumulate specific error codes incompile_var_fragment,assemble_module, andassemble_simulationvia the salsaCompilationDiagnosticaccumulator.engine::Projectwithdatamodel::ProjectinSimlinProject, addSimlinDbandPersistentSyncStatefor incremental compilation, verifyapply_patchuses the accumulator-based error path.SimlinDbthrough layout and analysis modules, migratesimlin-clito the incremental path, deprecatewith_ltm()/with_ltm_all_links().simulate.rs,simulate_ltm.rs, and benchmarks to incremental VM path, removecompile_projectfrom public API, add deprecation docs referencing GitHub engine: models with modules or SMOOTH/DELAY skip incremental compile #295 for remaining monolithic callers.Known deferred items
LoadPrev/LoadInitialopcode activation deferred -- PREVIOUS/INIT still use module expansion. Scaffolding exists inbytecode.rsandvm.rs.compile_project()andSimulation::compile()retained as test-only; cannot be fully deleted until engine: models with modules or SMOOTH/DELAY skip incremental compile #295 is resolved.Test plan
cargo test -p simlin-engine --features file_io(all 40+ models pass)cargo test -p simlin --lib(all FFI tests pass)docs/test-plans/2026-02-26-salsa-consolidation.md