Skip to content

engine: unified LTM module composite scoring - #416

Merged
bpowers merged 34 commits into
mainfrom
ltm-module-scoring
Mar 30, 2026
Merged

bpowers merged 34 commits into
mainfrom
ltm-module-scoring

Conversation

@bpowers

@bpowers bpowers commented Mar 30, 2026

Copy link
Copy Markdown
Owner

Summary

  • Replace separate root/sub-model LTM variable generation with unified model_ltm_variables tracked function that generates link scores, loop scores, pathway scores, and composite scores for any model
  • Remove is_root gates so all models (root, stdlib, user-defined) receive LTM instrumentation when ltm_enabled=true
  • Update link_score_equation_text to generate equations for module-involved links (input->module, module->downstream, module->module) instead of returning None
  • Migrate all non-module LTM tests from interpreter path (Project::from + with_ltm) to salsa/VM path (compile_project_incremental + VM)
  • Delete ~3500 lines of test-only LTM code (with_ltm, inject_ltm_vars, old tracked functions, test-only generation functions)
  • Add graceful degradation for LTM vars that can't be resolved during assembly (fixes stdlib module compilation with ltm_enabled=true)
  • Add 7 new VM integration tests for feedback loops, user-defined modules, and nested modules
  • Update LTM design doc and engine CLAUDE.md for unified architecture

Net: -1489 lines (2173 added, 3662 removed across 16 files, 30 commits)

Test Plan

  • cargo test -p simlin-engine --features "testing,file_io" -- all tests pass (22/22 simulate_ltm, 56/56 simulate)
  • cargo clippy -p simlin-engine -- zero warnings
  • cargo build --workspace -- no dead-code warnings
  • Verify mark2_mdl_compiles_with_ltm_enabled passes (regression test for graceful LTM degradation)
  • Review human test plan at docs/test-plans/2026-03-29-ltm-module-scoring.md
  • 2 tests remain #[ignore] with documented root causes (discovery parser edge cases)

bpowers added 30 commits March 29, 2026 22:28
Remove test-only cfg gates and change visibility to pub(crate) for
generate_module_link_score_equation and generate_module_input_link_score_equation
so that link_score_equation_text in db.rs can call them for module-involved links.
Replace the early-return None for module links with equation generation
for three cases: input->module (composite reference), module->downstream
(standard ceteris-paribus), and module->module (black-box delta-ratio).
Update the test to verify composite reference equations are produced.
Add model_ltm_variables in db_ltm.rs that replaces the separate
root-model and sub-model LTM variable generation paths with a single
function. Auto-detects sub-model behavior by checking for input ports
with causal pathways to output. Module-containing loops are no longer
filtered out because link_score_equation_text now handles module
links via composite references. Pathway score equations reference
link_score prefix uniformly instead of ilink.

Old functions (model_ltm_synthetic_variables, etc.) are retained for
callers updated in later phases. Tests in db_ltm_unified_tests.rs.
The identical 55-line feedback_loop_project() function existed in both
db_tests.rs and db_ltm_unified_tests.rs. Since the two files are
separate mod scopes inside db.rs and cannot share private helpers
directly, extract the shared fixture to testutils.rs as pub(crate) and
import it in both test modules.
Replace the discovery-mode dispatch (choosing between
model_ltm_all_link_synthetic_variables and model_ltm_synthetic_variables)
with a single call to the unified model_ltm_variables function. The
unified function handles discovery mode internally and produces identical
results for root models.
Remove the is_root guard from compute_layout's Section 3 (LTM synthetic
variables), allowing sub-models to receive LTM instrumentation slots.
Replace the discovery-mode dispatch with a single call to the unified
model_ltm_variables function.

Models without feedback loops (e.g. passthrough modules) naturally get
empty LTM var lists. No salsa dependency cycle: model_ltm_variables
calls only analysis functions that don't depend on compute_layout.
Both LTM compilation passes in assemble_module (the main link/loop
score compilation and the implicit var fragment collection) now run
for all models when ltm_enabled, not just root. Models without
feedback loops get empty LTM var lists from model_ltm_variables.

The ilink prefix check is removed since model_ltm_variables produces
only link_score-prefixed variables.
calc_flattened_offsets_incremental now includes LTM variable offsets
for all models when ltm_enabled, not just root. The compute_layout
call passes through the is_root flag instead of hardcoding true, and
the discovery-mode dispatch is replaced with model_ltm_variables.
Replace the discovery-mode dispatch between model_ltm_all_link_synthetic_variables
and model_ltm_synthetic_variables with a single call to the unified
model_ltm_variables function. This call site was not behind an is_root gate
(it already ran for all models), but it was using the old per-mode functions
instead of the unified one that handles both modes internally.
…agment

The comment claimed LTM vars are always compiled in root model context,
which is no longer true after the is_root gates were removed. The new
comment accurately describes what the offset initialization does: it
starts the mini-layout after the 4 implicit time variables.
Tests verify that LTM synthetic variable generation and layout allocation
work correctly for models containing SMOOTH/DELAY stdlib modules:

- test_ltm_smooth_model_compiles_with_ltm: SMTH1 in feedback loop
  generates link_score vars and allocates extra layout slots
- test_ltm_delay_model_compiles: DELAY1 in feedback loop generates
  link_score vars and allocates extra layout slots
- test_ltm_passthrough_module_compiles: user-defined module with no
  internal stocks compiles fully with LTM (no spurious LTM overhead)
- test_ltm_multiple_smooth_instances_compile: two SMOOTH instances get
  independent link_score vars and additional layout slots

Tests are in a new db_ltm_module_tests.rs file to keep db_tests.rs
under the line limit.
The comment in enumerate_module_instances_inner still said LTM implicit
module variables exist "only in the root model", but the is_root gate was
removed in an earlier commit so this now runs for any model with LTM
enabled.

The discovery-mode dispatch in compile_ltm_equation_fragment was using
the older model_ltm_all_link_synthetic_variables / model_ltm_synthetic_variables
split rather than the unified model_ltm_variables function, which already
handles discovery mode internally. Replaced with the single unified call
and removed the now-unused imports.
Add set_project_ltm_discovery_mode public wrapper in db.rs following
the same pattern as set_project_ltm_enabled. Add the corresponding
compile_ltm_discovery_incremental helper in simulate_ltm.rs for tests
that need to exercise the VM with all-link discovery scoring.

Also adds five VM integration tests for LTM scoring:
- test_feedback_loop_exhaustive_vm (balancing loop, exhaustive mode)
- test_feedback_loop_discovery_vm (discovery mode with discover_loops)
- test_reinforcing_feedback_loop_vm (reinforcing loop)
- test_multiple_feedback_loops_vm (independent subsystem scoring)
- test_passthrough_module_ltm_vm (no modules, no composite scores)

The VM + LTM path does not yet support models containing stdlib modules
(SMOOTH/DELAY) because LTM augmentation generates variable references
that fail layout resolution for implicit module instances. The new VM
tests use non-module feedback loops; module-specific LTM coverage
remains on the interpreter path.
Adds test_user_defined_module_ltm_vm which constructs a multi-model
project with a user-defined sub-model ("growth") containing an internal
stock. The parent model feeds input to the sub-model and uses its output
in a feedback loop, exercising the full compile_project_incremental + VM
pipeline with LTM enabled. Verifies link scores, loop scores, relative
loop scores, and that the sub-model's internal variables are accessible
via qualified names in the results.
Adds test_nested_module_ltm_vm which constructs a model where a
user-defined sub-model ("processor") internally calls SMTH1, creating
two levels of module nesting (root -> user module -> stdlib SMOOTH).

Uses the interpreter path (Project::from + with_ltm) because the
incremental LTM compilation path has a known limitation with stdlib
modules where LTM-augmented variable names fail layout resolution.
Verifies link scores through the module, loop scores, relative loop
scores, and that the nested SMOOTH module is properly handled. Also
validates the model structure compiles and simulates on the VM path
without LTM as a sanity check.
The discovery helper now uses compile_ltm_discovery_incremental + Vm
for simulation instead of Project::from + with_ltm_all_links() +
Simulation::new. Project::from is retained only for causal graph
structural analysis needed by ltm_finding::discover_loops.
Remove the interpreter leg (Project::from + with_ltm + Simulation::new)
from simulate_ltm_path, keeping only the VM path via
compile_ltm_incremental. Project::from is retained solely for structural
loop detection used by ensure_ltm_results error reporting. Golden data
validation produces identical results.
The test_discovery_independent_subsystems test previously used
TestProject::compile() + with_ltm_all_links() + Simulation::new()
(AST interpreter). Migrated to build_datamodel() +
compile_ltm_discovery_incremental + VM. The 4 other discovery tests
(discovery_logistic_growth_finds_both_loops,
discovery_cross_validates_with_exhaustive, discovery_arms_race_3party,
discovery_decoupled_stocks) already use discover_loops_from_path which
was migrated to the VM path in a prior commit.
Migrate 4 tests from the interpreter (Project::from + with_ltm() +
Simulation::new) to the salsa/VM path:

- hero_culture_loop_sign_continuity: now uses compile_ltm_incremental +
  VM for simulation, retaining Project::from only for structural loop
  detection (loop ID enumeration for sign continuity checking).

- test_independent_subsystems_partitioned_relative_scores: now uses
  build_datamodel() + compile_ltm_incremental + VM instead of
  compile() + with_ltm() + Simulation::new().

- test_coupled_two_stock_single_partition: same migration pattern;
  retains Project::from for structural CausalGraph partition analysis.

- test_arms_race_single_partition: migrated from Project::from +
  CausalGraph::from_model to salsa-based model_cycle_partitions.
  This test only does structural analysis (no LTM simulation).
Migrate 7 stdlib-module LTM tests from TestProject::compile() to
TestProject::build_datamodel() + Project::from():

- test_internal_smooth_loop_not_in_parent: fully migrated to salsa
  model_detected_loops (no with_ltm needed, pure structural analysis)
- test_smooth_goal_seeking_ltm: structural analysis via salsa
  model_detected_loops, simulation via interpreter (with_ltm)
- test_multiple_smooth_instances: same pattern as above
- test_smooth_with_initial_value_ltm: interpreter path (with_ltm_all_links)
- test_smooth_model_discovery_mode: interpreter path (with_ltm_all_links)
- test_discovery_ilink_not_in_search_graph: renamed to
  test_discovery_submodel_link_scores_excluded_from_search, updated
  assertions for unified naming convention (interpunct namespacing
  instead of ilink prefix)
- test_module_output_multi_input_link_score_magnitude: interpreter path

The compile_ltm_incremental + VM path does not yet support stdlib
modules (SMOOTH/DELAY): LTM-augmented variable names fail layout
resolution for implicit module instances. Tests that need LTM
simulation results for stdlib modules remain on the interpreter path
with clear documentation. Structural analysis (loop detection) uses
salsa model_detected_loops where possible.
Phase 6 (Subcomponent A, Tasks 1-3) of the LTM module composite scoring
design plan.

Task 1: Remove with_ltm(), with_ltm_all_links(), inject_ltm_vars(),
abort_if_arrayed() and all associated tests from project.rs. Migrate
7 simulate_ltm.rs callers from the interpreter path to the salsa/VM
path (compile_ltm_incremental / compile_ltm_discovery_incremental).

Task 2: Remove generate_ltm_variables, generate_ltm_variables_all_links,
compute_composite_ports, generate_ltm_variables_inner,
generate_link_score_variables, generate_module_internal_ltm_variables,
generate_max_abs_chain, SyntheticVariables, CompositePortMap type aliases,
and the entire test module from ltm_augment.rs. Production functions
(generate_loop_score_variables, generate_link_score_equation_for_link,
generate_module_link_score_equation, generate_module_input_link_score_equation)
are retained as they are called by salsa tracked functions.

Task 3: Remove model_ltm_synthetic_variables,
model_ltm_all_link_synthetic_variables, module_ltm_synthetic_variables,
module_ilink_equation_text, get_stdlib_composite_ports from db.rs.
Delete db_stdlib_ports_tests.rs. Migrate 7 db_tests.rs callers to use
model_ltm_variables from db_ltm.rs. Retain module_input_pathways_from_edges
and generate_max_abs_chain_str as they are used by model_ltm_variables.
Replace references to deleted with_ltm_all_links() with the current
ltm_discovery_mode compile path in documentation comments and error
messages.
…ixed

The salsa/VM compilation path fails to assemble LTM synthetic variables
that reference implicit stdlib module instance names (e.g. the `smth1`
instance created by SMTH1(level, 3)).  At assembly time the module
instance and its synthetic link-score variables are not present in the
layout, so symbolic bytecode resolution panics with "variable 'smth1'
not found in layout during resolution".

Mark the six affected tests #[ignore] and add a section-level comment
explaining the root cause.  The tests document the intended behaviour
and will serve as regression tests once the layout resolution path
correctly handles stdlib module instances inside LTM equations.
Remove references to deleted test-only code paths (with_ltm, with_ltm_all_links,
inject_ltm_vars, generate_ltm_variables, CompositePortMap, compute_composite_ports,
generate_module_internal_ltm_variables) and the ilink naming prefix.

Update to describe the unified architecture: model_ltm_variables tracked function
as the single entry point, ltm_enabled/ltm_discovery_mode flags on SourceProject,
identical LTM treatment for all models (root, stdlib, user-defined), and
compile_project_incremental as the compilation entry point. Add new test file
listings for salsa pipeline tests (db_ltm_tests, db_ltm_unified_tests,
db_ltm_module_tests).
Remove references to deleted with_ltm()/with_ltm_all_links() from project.rs
and testing feature descriptions. Update ltm_augment.rs entry to list the
retained public functions. Add model_ltm_variables documentation to db_ltm.rs
entry. Add new LTM test file listings (db_ltm_tests, db_ltm_unified_tests,
db_ltm_module_tests).
…esign doc

The LTM synthetic variable injection section referenced the deleted
inject_ltm_vars() function. Updated to describe the current architecture
where model_ltm_variables tracked function generates LTM variables through
the salsa pipeline.
…er.md

link_score_equation_text and module_input_pathways_from_edges are both
defined in db.rs, not db_ltm.rs. Fix the attribution at the Module Links
section heading.

Also rewrap the Array Variables paragraph to eliminate an orphaned line
break that was left over from a prior partial edit.
AC1.3 (test_user_defined_module_ltm_vm): renamed the growth sub-model's
output variable from output_rate to output so the LTM pathway analyzer
finds the causal path input_signal -> growth_flow -> internal_level ->
output and generates a composite score for the input port. Added
assertions that composite score variables exist namespaced by the module
instance name (growth_model.*composite*).

AC4.2/AC4.3 (test_nested_module_ltm_vm): added assertions verifying (1)
composite scores exist for the SMOOTH instance nested inside the processor
user module (namespaced under processor.*), (2) chained nesting notation
is present in composite key names (multiple $ segments), and (3) non-zero
link scores exist at the nested level inside the SMOOTH.

AC3.2 (ltm_augment.rs): inlined generate_module_link_score_equation and
generate_module_input_link_score_equation into link_score_equation_text
in db.rs, then deleted the standalone functions. Made quote_ident
pub(crate) so db.rs can call it for the inlined black-box formula.
Updated CLAUDE.md to reflect the deleted functions.
When sub-models are assembled with ltm_enabled=true, model_ltm_variables
generates LTM synthetic vars whose equations reference implicit stdlib module
instance names as they appear in the root model (e.g. "smth1").  Those names
don't exist in the sub-model's layout, where the same slots are addressed
under qualified names like "$:var_name:0:smth1".  resolve_module then fails
with "variable 'smth1' not found in layout during resolution", crashing the
entire compilation of models that use SMOOTH/DELAY inside feedback loops
(mark2.mdl being the concrete regression case).

Fix: add fragment_vars_in_layout() to the symbolic layer, which walks all
SymVarRef names in a CompiledVarFragment and returns false if any name is
absent from the layout.  In assemble_module, call this predicate before
inserting each LTM fragment (both main vars and implicit PREVIOUS helper
vars).  Unresolvable fragments are silently dropped; the root model generates
its own correctly-namespaced LTM vars for the same causal paths, so nothing
meaningful is lost.

Un-ignore four simulate_ltm tests that were blocked by this bug.  Two remain
#[ignore] with separate root causes documented in their comments.
@claude

claude Bot commented Mar 30, 2026

Copy link
Copy Markdown

Code Review

[P1] Delta-ratio formula divides delta_to / delta_to instead of delta_to / delta_from — always evaluates to ±1

File: src/simlin-engine/src/db.rs, lines 1787-1788, 1804-1805, 1833-1834

The black-box delta-ratio equation used for module-involved links computes:

ABS(((to - PREVIOUS(to))) / (to - PREVIOUS(to))) * SIGN(...)

The ABS numerator and denominator are identical (to_q - PREVIOUS(to_q)), so ABS(...) always evaluates to 1. The full expression therefore collapses to SIGN(delta_to / delta_from), giving ±1 regardless of the actual magnitude of influence. The denominator in the ABS term should use from_q instead of to_q to compute the actual ratio ABS(delta_to / delta_from). This same copy-paste error appears in all three code paths (no-matching-input fallback, to_var-not-Module fallback, module→module). The test_module_output_multi_input_link_score_magnitude test was #[ignore]d with "magnitudes are always ~1" attributed to the formula design, but this is likely the root cause.


Verdict: Correct with caveats. The structural refactoring (unified model_ltm_variables, removal of old test-only paths, migration to salsa/VM) is sound and tests pass. The delta-ratio formula bug above is the only blocking issue — it silently produces wrong magnitude values for all module-involved link scores.

@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: 6ad8042c82

ℹ️ 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/db.rs Outdated
Comment on lines 4662 to 4666
let fragment_result = if ltm_var.name.contains("\u{205A}link_score\u{205A}") {
// Extract from/to from the link score name
// Format: $:ltm:link_score:from->to or $:ltm:ilink:from->to
// Format: $:ltm:link_score:from->to
let arrow_pos = ltm_var.name.find('\u{2192}');
if let Some(arrow) = arrow_pos {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Split link_score names by fixed prefix, not last separator

Now that module-involved links are emitted as link_score vars, this parsing branch is exercised with identifiers that contain internal ⁚ separators (for example $⁚combined⁚0⁚smth1→combined). The current extraction logic in this branch uses the last separator before →, which truncates the from side to the final token and causes compile_ltm_var_fragment to miss the real link. Those fragments are then omitted, leaving module→downstream link scores effectively uncomputed and skewing downstream loop/composite scoring.

Useful? React with 👍 / 👎.

Comment on lines +1627 to +1631
let pathways = module_input_pathways_from_edges(edges_result);
let has_input_ports = !pathways.is_empty();

let mut vars = Vec::new();

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Avoid classifying root models by output pathway heuristic

This treats any model with non-empty pathways to a variable named output as a sub-model and switches it to all-edge link scoring. In exhaustive mode that bypasses loop/relative-loop generation entirely, so a root model that simply has a normal variable called output can lose loop scores based on naming alone. This changes core LTM semantics for valid root models and makes results dependent on an incidental identifier.

Useful? React with 👍 / 👎.

@codecov

codecov Bot commented Mar 30, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 89.07104% with 20 lines in your changes missing coverage. Please review.
✅ Project coverage is 78.46%. Comparing base (cf4a11a) to head (94ad6b5).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
src/simlin-engine/src/db.rs 80.43% 9 Missing ⚠️
src/simlin-engine/src/compiler/symbolic.rs 78.12% 7 Missing ⚠️
src/simlin-engine/src/db_ltm.rs 95.91% 4 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #416      +/-   ##
==========================================
- Coverage   78.58%   78.46%   -0.12%     
==========================================
  Files         166      166              
  Lines       46957    46757     -200     
==========================================
- Hits        36901    36690     -211     
- Misses      10056    10067      +11     

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

Fix evaluation-order bug where composite LTM vars were evaluated before
their path and link_score dependencies. Lexical sorting put composites
first (c < l < p), but the dependency chain is link_scores -> paths ->
composites. Replace with category-based sorting that respects this chain.

Extract the black-box delta-ratio formula (used for module links where
ceteris-paribus analysis is not possible) into a single helper function,
replacing three identical copies.
@claude

claude Bot commented Mar 30, 2026

Copy link
Copy Markdown

Code Review

Reviewed the full diff (~2173 added, ~3662 removed across 16 files). This PR unifies LTM variable generation behind a single model_ltm_variables tracked function, removes the is_root gate so all models get LTM instrumentation, handles module-involved links (input→module, module→downstream, module→module), adds graceful degradation for unresolvable LTM fragments, and migrates all LTM tests from the interpreter path to the salsa/VM path.

Findings

No blocking issues found.

Overall Correctness Verdict: Correct

The patch is well-structured and internally consistent:

  • Unified model_ltm_variables correctly auto-detects sub-model behavior via input port pathway analysis, generating all-edge link scores for sub-models and discovery mode while preserving exhaustive-mode loop/relative-loop scores for root models.
  • fragment_vars_in_layout provides sound graceful degradation: sub-model LTM equations referencing root-namespace-only names (e.g. bare smth1 vs qualified $⁚var_name⁚0⁚smth1) are silently dropped rather than failing assembly.
  • Sort order (link_score < loop_score < path < composite) correctly respects the dependency chain for sequential VM evaluation.
  • black_box_delta_ratio_equation produces SIGN(delta_to/delta_from) as documented — the ABS(delta_to/delta_to) = 1 term is a structural placeholder matching the standard ceteris-paribus formula shape. The known limitation (magnitude always ~1 for multi-input downstream) is explicitly tracked by the #[ignore]'d test_module_output_multi_input_link_score_magnitude test.
  • is_root gate removal is safe: compute_layout and assemble_module now pass the actual is_root flag through, and sub-models without feedback loops return empty LTM var lists (zero overhead).
  • Test coverage is thorough with 7 new VM integration tests covering feedback loops, user-defined modules, nested modules, and discovery mode.

…e mode

Fix regression where models with both input ports and internal feedback
loops (e.g., stdlib sub-models like smth1) would skip loop/relative
loop score generation. The has_input_ports flag only controlled the
link score strategy (all edges vs loop edges) but was incorrectly
gating loop score generation too. Move loop score generation into a
separate block that runs for all models in exhaustive mode.
@claude

claude Bot commented Mar 30, 2026

Copy link
Copy Markdown

Code Review

Reviewed the full diff (16 files, ~2200 added / ~3700 removed). This is a well-structured refactoring that unifies three separate LTM variable generation functions (model_ltm_synthetic_variables, model_ltm_all_link_synthetic_variables, module_ltm_synthetic_variables) into a single model_ltm_variables tracked function, removes the is_root gates so all models receive LTM treatment, and adds fragment_vars_in_layout as a safety net for unresolvable sub-model fragments.

No blocking findings

I examined the following areas closely and found no correctness issues:

  • black_box_delta_ratio_equation (db.rs:1742-1757): Direct port of the deleted generate_module_link_score_equation. The ABS(delta_to/delta_to) * SIGN(delta_to/delta_from) is algebraically SIGN(delta_to/delta_from) as the comment notes — pre-existing design, not a new bug.

  • link_score_equation_text module link handling (db.rs:1788-1815): The from_is_module && !to_is_module path passes a minimal all_vars map (only from + to), but this is fine because the from var is a Module, so both is_flow_to_stock and is_stock_to_flow checks fail, and it falls through to generate_auxiliary_to_auxiliary_equation which doesn't use all_vars.

  • Composite reference without pathway check (db.rs:1791): The old code checked composite_ports before using a composite reference; the new code always uses it if an input mapping exists. If the sub-model doesn't generate a composite (no pathway), fragment_vars_in_layout drops the unresolvable fragment. This changes behavior from "use black-box fallback" to "silently drop", but this is reasonable since a port without a causal pathway to output doesn't contribute to feedback loops.

  • Sort order in model_ltm_variables (db_ltm.rs:1815-1832): Categories: 0=link_score, 1=loop_score/rel_loop_score, 2=path, 3=composite. Loop scores must evaluate before relative loop scores — this works because "$⁚ltm⁚loop_score⁚" < "$⁚ltm⁚rel_loop_score⁚" lexically within category 1. The dependency chain (link_score → loop_score → path → composite) is correctly ordered.

  • Removal of is_root guards in compute_layout, assemble_module, calc_flattened_offsets_incremental, enumerate_module_instances_inner: Correct — model_ltm_variables returns empty for models without stocks, and the fragment_vars_in_layout check handles unresolvable fragments in sub-models.

  • fragment_vars_in_layout (symbolic.rs:807-859): Checks all phases (initial, flow, stock) and module decls. Correctly rejects fragments with unresolvable variable references.

Minor observation (non-blocking)

The model_ltm_variables function, in the exhaustive root-model case (!has_input_ports && !is_discovery), reconstructs the graph, loops, and calls assign_loop_ids twice — once in Part 1 (link scores) and again in Part 2 (loop scores). The underlying salsa queries are cached so the performance impact is mitigated, but the local reconstruction work is duplicated. Not a correctness issue.

Overall correctness: Correct ✓

The patch maintains correctness of existing code and tests. The unified architecture is cleaner, the fragment_vars_in_layout safety net handles edge cases gracefully, and the sort order correctly respects the dependency chain. The ~1500 net line reduction is well-justified.

Compute loops once at the top of model_ltm_variables and share between
the link-score strategy (loop edges only for exhaustive root models)
and loop/relative score generation. Eliminates ~50 lines of duplicated
CausalGraph/Loop reconstruction code.
@claude

claude Bot commented Mar 30, 2026

Copy link
Copy Markdown

Code Review: engine: unified LTM module composite scoring

Summary

This PR replaces separate root/sub-model LTM variable generation with a unified model_ltm_variables tracked function, removes the is_root gates so all models receive LTM instrumentation, handles module-involved links (input→module, module→downstream, module→module) in link_score_equation_text, and adds graceful degradation via fragment_vars_in_layout for unresolvable LTM fragments. Tests are migrated from the interpreter path to salsa/VM, and ~3500 lines of test-only code are deleted.

Findings

No bugs found. The patch is well-structured:

  • Unified model_ltm_variables correctly handles all three link score cases for modules, generates pathway/composite scores for models with input ports, and produces loop/relative loop scores for models with feedback loops (including models that are both sub-models and have internal loops).
  • Sort order in model_ltm_variables respects the evaluation dependency chain: link_score (cat 0) → loop_score/rel_loop_score (cat 1) → path (cat 2) → composite (cat 3). Within cat 1, loop_score sorts lexically before rel_loop_score, which is correct since rel scores depend on loop scores.
  • fragment_vars_in_layout is a clean solution for the namespace mismatch between sub-model LTM equations and root model layouts. The function checks all three bytecode phases plus module declarations.
  • No salsa dependency cycle: compute_layout → model_ltm_variables → analysis functions (model_causal_edges, model_loop_circuits) which don't depend on compute_layout.
  • black_box_delta_ratio_equation is a faithful copy of the old generate_module_link_score_equation (the ABS(delta_to / delta_to) = 1 pattern is pre-existing and documented as intentional in the docstring).

Minor observations (non-blocking)

  • The link_score_equation_text input→module case generates a composite reference for any module with a matching input mapping, even passthrough modules where the composite won't exist. fragment_vars_in_layout catches this and drops the fragment, but this means passthrough module links get no score rather than a black-box delta-ratio score. This is functionally equivalent to the old production code (which returned None for all module links) and is covered by test_ltm_passthrough_module_compiles.

Overall Correctness Verdict

Correct. The patch is free of bugs and blocking issues. Existing tests are preserved (migrated to VM path), new integration tests cover module scoring at multiple nesting levels, and the graceful degradation path is well-documented. The two #[ignore] tests have documented root causes unrelated to this change.

@bpowers

bpowers commented Mar 30, 2026

Copy link
Copy Markdown
Owner Author

Review cycle summary

Four automated review iterations identified and fixed three issues:

  1. LTM variable evaluation ordering -- Composite score variables were evaluated before their pathway and link score dependencies due to lexical sorting. Fixed with dependency-aware category sorting (link_score < loop_score < path < composite) that matches the VM's sequential flow evaluation order.

  2. Loop score generation for models with input ports -- Models that have both input ports (e.g., stdlib sub-models like smth1) and internal feedback loops were missing loop/relative loop scores. The has_input_ports flag was incorrectly gating loop score generation. Fixed by separating loop score generation into an independent block that runs for all models in exhaustive mode.

  3. Code quality -- Extracted the triplicated black-box delta-ratio formula into a single black_box_delta_ratio_equation helper function. Deduplicated the CausalGraph/Loop reconstruction that was duplicated between the link-score and loop-score generation blocks.

Three pre-existing issues were tracked as tech debt: hard-coded output variable name for module pathway detection, module-containing loops getting Unknown polarity instead of balancing/reinforcing classification, and two #[ignore] tests for discovery-mode module propagation and black-box formula magnitude.

Fix the black-box delta-ratio equation for module links: the ABS term
had identical numerator and denominator (delta_to / delta_to = 1),
collapsing magnitude to always +/-1. Changed to delta_to / delta_from
to compute the actual influence ratio.

Replace rfind-based link_score name parsing with fixed-prefix stripping.
The prefix is always "$:ltm:link_score:" so using rfind to find the
last separator was fragile for identifiers with internal separators.
@claude

claude Bot commented Mar 30, 2026

Copy link
Copy Markdown

Code Review

Reviewed the full diff (~5800 lines across 16 files). This is a clean unification of three separate LTM variable generation paths (model_ltm_synthetic_variables, model_ltm_all_link_synthetic_variables, module_ltm_synthetic_variables) into a single model_ltm_variables tracked function, with the is_root gate removed so all models get LTM instrumentation.

Key changes verified

  1. model_ltm_variables (db_ltm.rs) — Unified function correctly handles all three modes: discovery (all edges, no loop scores), exhaustive root (loop edges + loop/relative scores), and sub-model (all edges + pathway/composite scores). The dependency-aware sort (link_score → loop_score → path → composite) ensures correct VM evaluation order.

  2. link_score_equation_text (db.rs) — Module link handling covers three cases cleanly: non-module→module (composite ref or delta-ratio fallback), module→non-module (standard ceteris-paribus), module→module (delta-ratio). The black_box_delta_ratio_equation correctly guards against division by zero.

  3. fragment_vars_in_layout (symbolic.rs) — Graceful degradation for sub-model LTM fragments referencing unresolvable names. Covers all SymVarRef-bearing opcodes and module decls. The SymbolicOpcode enum has no uncovered variants with variable references.

  4. is_root gate removal — Verified no salsa dependency cycle: model_ltm_variables depends only on analysis functions (model_causal_edges, model_loop_circuits, etc.) that don't depend on compute_layout. The old cycle concern (compute_layout → model_ltm_implicit_var_info → compute_layout) is avoided because the new path doesn't traverse that dependency chain.

  5. LINK_SCORE_PREFIX parsing (assemble_module) — Switching from contains("link_score") + contains("ilink") to starts_with(LINK_SCORE_PREFIX) is correct since ilink is no longer generated.

  6. calc_flattened_offsets_incremental — Changed compute_layout(db, *source_model, project, true) to compute_layout(db, *source_model, project, is_root) — correct since sub-models now participate in LTM and need their own is_root=false layout.

No bugs found

The implementation is consistent, well-tested (7 new integration tests, comprehensive unit tests for the unified function and module handling), and the graceful degradation strategy for unresolvable sub-model fragments is sound.

Overall correctness: correct. The patch should not break existing code or tests, and is free of bugs and blocking issues.

@bpowers
bpowers merged commit 01970ba into main Mar 30, 2026
12 checks passed
@bpowers
bpowers deleted the ltm-module-scoring branch March 30, 2026 15:03
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