Repository navigation
engine: incremental compilation followup fixes - #300
Conversation
…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
ecfdfdc to
225169e
Compare
Code Review for PR #300: engine: incremental compilation followup fixesFindings[P2]
|
There was a problem hiding this comment.
💡 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".
| Err(err) => { | ||
| eprintln!("incremental compilation failed: {err}"); | ||
| None |
There was a problem hiding this comment.
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 👍 / 👎.
Code Review: PR #300 — engine: incremental compilation followup fixesFinding 1: [P1]
|
…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.
Code Review: PR #300 — engine: incremental compilation followup fixesFindings[P2]
|
Code Review: PR #300 -- engine: incremental compilation followup fixesReviewed the 2 commits on this branch ( Changes Summary
FindingsNo actionable findings. The changes are well-scoped bug fixes with matching tests. Specifically:
Overall Correctness VerdictLooks 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. |
Review cycle summaryAfter 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 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.
|
@codex review |
1 similar comment
|
@codex review |
Code Review: PR #300 — engine: incremental compilation followup fixesSummaryThis 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 AnalysisConcurrency fix in Monolithic fallback removal in Module handling in dependency graph and runlists: Modules are correctly moved from the flows phase to the stocks phase ( Module input prefix stripping in Stdlib models: Both Dependency normalization: The
FindingsNo 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): VerdictOverall 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. |
There was a problem hiding this comment.
💡 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".
| } else { | ||
| None | ||
| Err(engine::Error { | ||
| kind: engine::ErrorKind::Simulation, | ||
| code: engine::ErrorCode::NotSimulatable, | ||
| details: Some("incremental compilation: no sync state available".to_string()), | ||
| }) |
There was a problem hiding this comment.
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 👍 / 👎.
| // 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)); |
There was a problem hiding this comment.
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 👍 / 👎.
Review cycle summaryAfter 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 Two additional concerns raised by reviewers were tracked as separate issues rather than addressed in-PR: a |
Codecov Report❌ Patch coverage is
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. 🚀 New features to boost your workflow:
|
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.
|
@codex review |
There was a problem hiding this comment.
💡 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".
| 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)); |
There was a problem hiding this comment.
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 👍 / 👎.
| 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)) |
There was a problem hiding this comment.
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 👍 / 👎.
Code ReviewI performed a thorough review of this PR covering: the TOCTOU race fix in FindingsNo bugs found. The changes are consistent and correct:
Overall Correctness VerdictCorrect. 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. |
Review cycle summaryBoth 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 |
Summary
Incremental compilation correctness fixes, plus two issues identified during code review:
simlin_project_add_modelused.take()onsync_stateand dropped the db lock before restoring it, allowing concurrentsimlin_sim_newto seeNoneand 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 inpatch.rsbuild_submodel_metadatausedBox::leakto create stub variable references, leaking memory on every recompilation. Replaced withbumpalo::Bumparena allocation scoped to each compilation function, so stubs are freed when compilation completesFixes #302
Fixes #303
Test plan
cargo test -p simlin-engine-- 2139 testscargo test --features file_io --test simulate-- 32 integration testscargo test -p libsimlin-- 151 tests including new concurrency regression test