Skip to content

engine: fix incremental dependency data loss - #322

Merged
bpowers merged 3 commits into
mainfrom
compiler-fixes
Feb 25, 2026
Merged

bpowers merged 3 commits into
mainfrom
compiler-fixes

Conversation

@bpowers

@bpowers bpowers commented Feb 25, 2026 •

Copy link
Copy Markdown
Owner

Summary

This PR fixes five high-priority compiler/sync correctness bugs in batch 1:

What changed

  • symbolic.rs

    • Replaced decl.off as u32 with checked conversion (u32::try_from) in symbolize_module_decl.
    • Added regression test for overflowing usize offsets to ensure symbolization rejects narrowing.
  • db.rs

    • model_causal_edges: normalize module-ref sources in both explicit and implicit module edge insertion paths.
    • source_variable_from_datamodel and update_source_variable: preserve Module.compat instead of resetting to Compat::default().
    • compile_implicit_var_fragment:
      • added leading-dot stripping and composite module·output dependency handling
      • builds module stubs/module_refs/submodel metadata for composite module deps
      • collects graphical-function tables from dependency source variables (matching compile_var_fragment behavior)
  • db_tests.rs

    • Added regressions for each bug path:
      • inter-module causal-edge normalization
      • module visibility preservation (fresh + incremental sync)
      • implicit compile path with SMTH1(module.output, ...)
      • implicit compile path requiring dep lookup tables (SMTH1(LOOKUP(table_var, ...), ...))

Verification

Ran targeted regressions and nearby sanity tests:

  • compiler::symbolic::tests::test_module_decl_offset_overflow_is_rejected
  • db::db_tests::test_model_causal_edges_normalizes_inter_module_output_refs
  • db::db_tests::test_sync_preserves_module_visibility_from_datamodel
  • db::db_tests::test_incremental_sync_updates_module_visibility
  • db::db_tests::test_incremental_compile_smooth_over_module_output
  • db::db_tests::test_incremental_compile_implicit_lookup_dep_tables
  • db::db_tests::test_implicit_module_offsets_in_flattened_map
  • db::db_tests::test_sparse_per_element_gfs_preserve_table_indices
  • db::db_tests::test_incremental_vs_monolithic_output
  • cargo fmt --check

All pre-commit checks passed during commit.

Fixes #291
Fixes #293
Fixes #301
Fixes #304
Fixes #320

This hardens several silent correctness failures in incremental compilation and
salsa sync. Module-to-module causal edges now normalize module output refs,
implicit fragment compilation now resolves composite module dependencies and
collects lookup tables from dependency variables, and module compat visibility
is preserved during both initial and incremental sync.

It also removes a silent narrowing cast in symbolic module declaration
symbolization by rejecting offsets that do not fit in u32. New regression tests
cover each bug path so these failures cannot silently regress again.

@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: 0df6d09b6d

ℹ️ 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".

for mr in source_var.module_refs(db).iter() {
let canonical_src = canonicalize(&mr.src).into_owned();
edges.entry(canonical_src).or_default().insert(name.clone());
let normalized = normalize_module_ref_str(&canonical_src);

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 Keep parent-scope module sources when normalizing edges

Avoid passing every module reference source through normalize_module_ref_str here: XMILE parent-scope connectors like from=".area" canonicalize to ·area, and normalize_module_ref_str truncates at the first middot, producing an empty key (""). That drops the real dependency source in model_causal_edges (and similarly in the implicit-module branch), so causal graphs/loop analysis for models using parent-scope module references become incorrect.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Addressed in commits a5eba4f and 3fe542a: normalize_module_ref_str now strips the leading middot before truncating, and both module-ref loops filter out internal/output refs (where src starts with the module's own prefix) before calling normalization. Regression tests cover both the leading-middot case and the self-loop prevention.

@claude

claude Bot commented Feb 25, 2026

Copy link
Copy Markdown

Code Review

Changes Reviewed

  1. symbolic.rs: Replaced decl.off as u32 with checked u32::try_from in symbolize_module_decl to prevent silent truncation. Straightforward correctness fix with a well-gated test (cfg(target_pointer_width = "64")).

  2. db.rs – model_causal_edges: Added normalize_module_ref_str to both explicit and implicit module reference source paths. This correctly maps qualified references like a·output to just a in the causal graph, preventing phantom output nodes.

  3. db.rs – compat preservation: Changed datamodel::Variable::Module(_) => datamodel::Compat::default() to m.compat.clone() in both source_variable_from_datamodel and update_source_variable. Consistent with how Stock/Flow/Aux already preserve compat.

  4. db.rs – compile_implicit_var_fragment: New composite module·output dependency handling with leading-dot stripping, module stub construction, submodel metadata building, and lookup table extraction from dependency source variables. The deduplication in the metadata assembly loop (line 4266: if !mini_metadata.contains_key(dep_ident)) correctly prevents double-allocation if duplicate composite deps reference the same module.

  5. db_tests.rs: Six well-targeted regression tests covering each bug path.

Findings

No bugs found. The changes are logically correct and well-tested. Key correctness observations:

  • The normalize_module_ref_str function is only applied to module reference src fields in model_causal_edges, which contain either plain variable names (no middle dot → passthrough) or qualified module·output names (normalized to module name). Leading-middle-dot scope markers don't appear in stored module reference sources, so the truncation-to-empty-string edge case cannot arise in practice.
  • The deduplication guard at line 4266 in the metadata assembly loop prevents incorrect offset allocation if dep_variables contains duplicate module entries from processing multiple composite deps referencing the same module.
  • extra_module_refs (HashMap) and extra_submodels (Vec with HashMap-based downstream consumers) handle duplicates gracefully via overwrite semantics.
  • The module_refs.extend(extra_module_refs) at the end correctly merges module refs from the implicit variable's own structure with external composite module dependencies, without risk of key collision in normal models.

Verdict

Correct. The patch addresses all five described bugs with appropriate tests. Existing code and tests should not break.

@codecov

codecov Bot commented Feb 25, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 71.79487% with 33 lines in your changes missing coverage. Please review.
✅ Project coverage is 79.33%. Comparing base (6b96e0f) to head (3fe542a).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
src/simlin-engine/src/db.rs 71.05% 33 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #322      +/-   ##
==========================================
- Coverage   79.35%   79.33%   -0.02%     
==========================================
  Files         132      132              
  Lines       31487    31574      +87     
==========================================
+ Hits        24986    25050      +64     
- Misses       6501     6524      +23     

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

…ication

normalize_module_ref_str failed to strip leading middots (XMILE parent-scope
refs like .area canonicalize to middot-area), producing empty-string keys in
the causal graph.  Align with model_dependency_graph's normalize_dep by
stripping the leading middot before truncating at the module qualifier.

Extract build_module_inputs helper to deduplicate the module reference
filtering/mapping logic that appeared in compile_var_fragment and twice in
compile_implicit_var_fragment.  Change extra_submodels from Vec to HashMap
to naturally deduplicate when multiple deps reference the same module.
@claude

claude Bot commented Feb 25, 2026

Copy link
Copy Markdown

Code Review: PR #322 — engine: fix incremental dependency data loss

I reviewed the full diff across symbolic.rs, db.rs, and db_tests.rs, examining each of the five fixes and comparing new code paths against existing ones.

Summary

This PR addresses five correctness bugs with well-structured fixes and thorough regression tests. Each fix is narrowly scoped and consistent with the patterns already established in the codebase.

Findings

No blocking bugs found.

Detailed Notes

symbolize_module_decl checked conversion (symbolic.rs) — Clean fix replacing as u32 with u32::try_from. The test is correctly gated with #[cfg(target_pointer_width = "64")].

normalize_module_ref_str leading-middot stripping (db.rs:1319-1326) — The new two-step normalization (strip leading middot, then truncate at first remaining middot) correctly handles the ·area parent-scope ref case that previously produced an empty-string key. The before/after behavior change is exactly what the model_causal_edges callers need. Minor note: a bare · input would return "", but this can't arise from the canonical name pipeline.

Module Compat preservation (db.rs:2404-2408, 2517-2521) — Straightforward fix: Module(_) => Compat::default() → Module(m) => m.compat.clone(). Both source_variable_from_datamodel and update_source_variable are updated consistently.

build_module_inputs extraction (db.rs:2957-2981) — The extracted helper faithfully reproduces the original inline logic, including the model_name == "main" middot-stripping condition. It's used in both compile_var_fragment (refactored) and the new compile_implicit_var_fragment module handling. Note: the existing inline code in the dep loop of compile_var_fragment (around line 3427) was not refactored to use this helper — a minor inconsistency that could be cleaned up separately.

compile_implicit_var_fragment composite module deps (db.rs:4100-4358) — The core of the PR. The new loop correctly: (1) strips leading middots, (2) detects composite module·output deps, (3) constructs Module variables with resolved inputs, (4) registers extra module_refs and submodel metadata. The module_refs.extend(extra_module_refs) cannot produce key collisions because module_refs is keyed by the implicit var's own canonical name while extra_module_refs is keyed by dependency module names. The lookup table collection loop (lines 4303-4321) mirrors the identical pattern in compile_var_fragment (lines 3617-3635).

Test coverage — All five fix paths have targeted regression tests that validate both the happy path and the specific failure mode. The module-output smooth test and lookup-dep-tables test both run full simulations to verify end-to-end correctness.

Verdict

Correct. The patch is free of bugs and blocking issues. Existing code and tests will not break.

Module references in Stella-imported models can include output refs where
src starts with the module's own prefix (e.g. src="a.output" for module "a").
After normalization these collapse to the module name, creating false
self-loops (a -> a) in the causal graph and downstream loop analysis.

Filter these internal refs before normalizing, matching the existing
filtering in build_module_inputs.
@claude

claude Bot commented Feb 25, 2026

Copy link
Copy Markdown

Code Review

Reviewed the three changed files: symbolic.rs (overflow check), db.rs (normalization, compat preservation, implicit var module deps, table collection), and db_tests.rs (regression tests).

Analysis

symbolic.rs — overflow check: Clean replacement of decl.off as u32 with u32::try_from. Test correctly gated with #[cfg(target_pointer_width = "64")] since on 32-bit usize == u32 and overflow is impossible.

normalize_module_ref_str: Now strips a leading middot before truncating at the first remaining middot. Edge cases check out: "·area" → "area", "module·output" → "module", "·module·output" → "module", "simple" → "simple".

model_causal_edges: The self_prefix filter and normalize_module_ref_str call are applied consistently in both the explicit-variable path (SourceVariableKind::Module) and the implicit-variable path (datamodel::Variable::Module). This prevents false self-loops from Stella-style output refs and normalizes inter-module references correctly.

Compat preservation: Straightforward fix — m.compat.clone() instead of Compat::default() in both source_variable_from_datamodel and update_source_variable.

build_module_inputs extraction: Compared the old inline closure in compile_var_fragment with the new helper — logic is identical. The generic S1: AsRef<str>, S2: AsRef<str> signature correctly handles Cow<str> from canonicalize().

compile_implicit_var_fragment module dep handling: The new composite module·output dependency detection (splitting at middot, looking up in source_vars then implicit_info) correctly builds module stubs, module_refs, and submodel metadata. Duplicate-prevention for mini_metadata insertion at line 4267-4278 handles the case where multiple dep names reference the same module. The extra_module_refs HashMap naturally deduplicates by key, and the data is identical across duplicates (same model, same inputs).

Lookup table collection: The new loop at lines 4314-4332 matches the existing pattern in compile_var_fragment (lines 3628-3646), correctly skipping module-qualified names and collecting tables from explicit source variables.

Findings

No bugs found.

Verdict: Correct

The patch correctly addresses all five reported issues with consistent normalization, proper compat propagation, and complete module dependency handling in the implicit compilation path. All changes are covered by regression tests. Existing code and tests should not break.

@bpowers

bpowers commented Feb 25, 2026

Copy link
Copy Markdown
Owner Author

Review cycle summary

This PR went through 3 review iterations with both Codex and Claude reviewing each round.

Iteration 1 identified two classes of issues:

  • A correctness bug in normalize_module_ref_str that failed to strip leading middots from XMILE parent-scope refs (e.g. .area -> empty-string key in the causal graph), and
  • Code duplication in the module-input building logic (3 near-identical blocks across compile_var_fragment and compile_implicit_var_fragment).

Both were addressed by extracting a build_module_inputs helper, fixing the normalization function, changing extra_submodels from Vec to HashMap for natural deduplication, and adding a regression test for the leading-middot case.

Iteration 2 caught that the new normalization in model_causal_edges could produce false self-loops for Stella-imported models where module references include output refs (src starts with the module's own prefix). Fixed by adding self-prefix filtering before normalization in both the explicit and implicit module edge paths, with a targeted regression test.

Iteration 3 both reviewers confirmed no remaining actionable issues.

@bpowers
bpowers merged commit d667c5a into main Feb 25, 2026
13 of 14 checks passed
@bpowers
bpowers deleted the compiler-fixes branch February 25, 2026 15:11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant