Skip to content

ltm: discovery-mode correctness fixes from deep review - #705

Merged
bpowers merged 10 commits into
mainfrom
ltm-review-fixes
Jun 4, 2026
Merged

bpowers merged 10 commits into
mainfrom
ltm-review-fixes

Conversation

@bpowers

@bpowers bpowers commented Jun 4, 2026

Copy link
Copy Markdown
Owner

A multi-agent deep review of the LTM implementation against the four papers empirically validated the scoring core (paper Tables 1-3, chain-rule and aggregation invariance, isolated-loop +/-1, Bass inflection crossing all reproduce exactly) and found the residual risk concentrated in discovery mode. This PR lands the documentation honesty fixes plus three discovery-mode fixes, each implemented TDD-first and passed through an independent adversarial review loop (two of the three needed a fix round after review caught real gaps).

Commits

Verification

Every commit passed the full pre-commit suite (Rust fmt/clippy/tests, TS lint/build/tsc/tests, pysimlin), and the full suite was re-run on the rebased result. The ignored C-LEARN LTM tests (clearn_pinned_climate_loop_is_scored, clearn_ltm_discovery_compiles, clearn_with_ltm_simulates_model_vars_identically, discovery_clearn_matches_vm_wasm) were run explicitly in release mode for both behavior-changing commits. Independent reviewers verified the discriminating power of the new regression tests by stub-reverting the fixes and watching them fail.

Related issues: GH #696, #698, #699, #700, #701, #679, #495.

@claude

claude Bot commented Jun 4, 2026

Copy link
Copy Markdown

Review

No qualifying findings.

I traced the four behavior-changing arms end-to-end:

The new regression tests drive the production paths (analyze_model_multi_output_loop_polarity_reinforcing, analyze_model_module_to_module_exit_port_polarity_reinforcing, discovery_recovers_cross_agg_loops_matches_exhaustive, exhaustive_module_loop_polarity_reclassified_from_runtime, exhaustive_never_active_loop_keeps_structural_polarity, the budget-clip + no-agg-unaffected discovery tests). The cross-mode score fingerprint comparison in discovery_recovers_cross_agg_loops_matches_exhaustive (rounded |score| to 1e-9) is the strongest discriminator and pins the new behavior to exhaustive ground truth.

Overall correctness verdict: correct.

@bpowers

bpowers commented Jun 4, 2026

Copy link
Copy Markdown
Owner Author

@codex review

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

ℹ️ 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/ltm_finding.rs Outdated
Comment on lines +1962 to +1971
let instances: HashSet<&Ident<Canonical>> = causal_graph
.variables()
.iter()
.filter_map(|(name, var)| match var {
Variable::Module { model_name, .. } if model_name.as_str() == sub_model_name => {
Some(name)
}
_ => None,
})
.collect();

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 Use project-wide output-port set for module pathways

When the same sub-model is instantiated in another model that reads an additional output port, this parent-only scan no longer matches the emission path: db::ltm::find_model_output_ports builds the sub-model's $⁚ltm⁚path⁚{entry}⁚{idx} ordering from reads across all project models. If that other port sorts before the port used by the current loop, recompute_module_input_edge_series will look up the wrong pathway index and can reintroduce the wrong-signed module edge the override is meant to fix. Please derive this set from the same project-wide source/order as emission, or carry the emitted ordering into discovery.

Useful? React with 👍 / 👎.

bpowers added a commit that referenced this pull request Jun 4, 2026
The discovery-mode per-exit-port pathway recompute (GH #698) reconstructed a
sub-model's output-port set by scanning only the analyzed model's variables.
Emission (db::ltm::find_model_output_ports) derives it from reads across ALL
project models, and the sub-model emits its $.ltm.path.{port}.{idx} vars
against that project-wide sorted set. So when the same sub-model is also
instantiated in another project model (or nested in another sub-model) that
reads an additional output port sorting BEFORE the port the loop traverses,
every pathway index shifts and the recompute read the wrong pathway var --
re-introducing the wrong-signed module edge the GH #698 fix was meant to
eliminate.

Fix by identity-by-construction: discover_loops_with_graph now takes a
SubModelOutputPorts map (sub-model canonical name -> emitted sorted port set).
analyze_model builds it via the new public build_sub_model_output_ports, which
calls the SAME db::ltm::sub_model_output_ports decision emission uses (one per
project model, including the stdlib output-convention short-circuit), so the
recompute enumerates pathway indices against the identical set the sub-model
emitted against regardless of which project model the loop lives in. The
db-less discover_loops(&Results, &Project) convenience path (tests only)
reconstructs the same project-wide-union + stdlib-output semantics in
project_sub_model_output_ports rather than scanning the analyzed model alone.
The shared ltm_discovery_inputs test harness threads the map (and now uses the
module-enriched element graph) so the wasm/VM parity and large-model harnesses
mirror production exactly.

This replaces the parent-scoped discovery_sub_model_output_ports (removed).
causal_graph_from_element_edges_with_modules is now pub so the harness mirrors
the production graph.

Reference: #705 (comment)
GH #698
@bpowers

bpowers commented Jun 4, 2026

Copy link
Copy Markdown
Owner Author

@codex review

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

ℹ️ 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/ltm_finding.rs Outdated
Comment on lines +2087 to +2093
let entry_port = inputs.iter().find_map(|inp| {
if normalize_module_ref(&inp.src) == link.from {
Some(inp.dst.clone())
} else {
None
}
})?;

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 choosing an arbitrary module input port

When the same upstream variable feeds more than one input port on a module, this find_map silently picks the first matching input and recomputes the loop edge from that port's pathway series. Because the collapsed causal edge is only x -> m, a model with x wired to both m.a and m.b can select the wrong pathway (or miss the active one) and report the wrong loop score/polarity; this should treat multiple matching inputs as ambiguous and fall back to the composite score, like the exit-port helper does for multi-output readers.

Useful? React with 👍 / 👎.

bpowers added 8 commits June 3, 2026 21:52
A multi-agent deep review of the LTM implementation against the four
papers empirically validated the scoring core (paper Tables 1-3, chain
rule and aggregation invariance, isolated-loop +/-1, Bass inflection
crossing all reproduce exactly), but found three places where our
documentation overstates or omits behavior:

- The discovery-mode zero-edge-exclusion comments claimed per-step
  exclusion "loses no loop that ever matters". That is only true for
  loops simultaneously active at a sampled step: a baton-passing loop
  whose links are active at disjoint times is invisible to discovery at
  every step (GH #699, demonstrated by the decoupled_stocks fixture).
  Two test comments also still attributed discovery behavior to the
  removed best_score pruning, one misattributing the actual root cause.

- The design doc's Discovery Mode step 4 claimed discovered loops flow
  through build_element_level_loops; discovery has its own path and
  never runs recover_cross_agg_loops, so cross-element reducer loops
  are silently dropped (GH #696). The multi-output module asymmetry is
  also elevated from "approximation" to what it empirically is: a
  possible polarity inversion (GH #698).

- Design-doc divergence 6 documented the 1-DT flow-to-stock numerator
  shift but not the time_step factor, which is load-bearing (without it
  every flow-to-stock score is 1/dt too large, compounding per stock in
  a loop); the papers hide this by using dt=1 in every worked example.
Git hooks live in the repository's common git dir, shared by every
linked worktree, but dev-init.sh computed the symlink target from the
current checkout's REPO_ROOT. Running dev-init inside a temporary
worktree (which Claude Code agent worktrees do as a matter of course)
therefore re-pointed the shared hook at the worktree's copy of
scripts/pre-commit; once the worktree was removed the symlink dangled
and git silently skipped pre-commit for every subsequent commit in the
main checkout. This bit a real session: a commit on main bypassed
fmt/clippy/tests with no warning.

Resolve the target against the common dir's parent (the main checkout)
instead, and guard on the target existing so a bare or unusual layout
degrades to a no-op rather than installing a broken link. Verified by
running dev-init from a throwaway linked worktree: the shared hook now
stays pointed at the main checkout and survives worktree removal.

Closes #700.
In discovery mode a feedback loop traversing a multi-output module could
get the WRONG polarity (inverted sign) relative to exhaustive mode. The
input->module link score there was the module composite, which max-abs-
selects across ALL output-port pathways; single-dependency pathways all
normalize to magnitude exactly 1, so the composite's tie-break picked an
arbitrary (first-enumerated) port -- possibly one whose sign opposes the
pathway the loop actually reads, flipping the loop's reported polarity.

Exhaustive mode already fixes this with a per-exit-port pathway-selection
override on the loop-score equation (PR #684). Discovery emits no loop-score
equations, so it had nothing to override. This applies the same selection
during the post-simulation score recompute (path -> FoundLoop): for a loop
edge x->m whose next edge m->y identifies the exit port, the edge's score
series is recomputed by max-abs-selecting over the sub-model's per-pathway
scores (m.$.ltm.path.{entry}.{idx}) that end at that port, instead of
reading the composite. Pathway indices are recovered from the module's
sub-graph via the same enumerate_pathways_to_outputs machinery and the same
sorted output-port set the sub-model emitted against (including the stdlib
output-convention short-circuit), so they match the emitted pathway vars
index-for-index -- the same parity guarantee exhaustive relies on. The DFS
still uses the composite for edge ordering and zero-exclusion, so no loop is
lost; the recompute falls back to the composite for single-output / pathless
/ indeterminate-port edges, so SMOOTH/DELAY and pathless modules are
unaffected.

The recompute needs module sub-graphs + the variable map on the discovery
CausalGraph. The PRODUCTION discovery path (analyze_model) builds that graph
from element-level edges via causal_graph_from_element_edges, which hardcodes
both empty -- so the recompute silently never fired there. analyze_model now
uses causal_graph_from_element_edges_with_modules, which enriches the
element-level graph with the shared model_variables_and_module_graphs pair.
That builder (and CausalGraph::from_model, the discover_loops convenience
path) builds a sub-graph for EVERY referenced sub-model, not only stockful
DynamicModules: a stockless passthrough emits pathway vars (PR #684) but
otherwise has no sub-graph to consult. The now-redundant
classify_module_for_ltm stock gate (and its ModuleLtmRole enum) is removed.
reconstruct_model_variables reconstructs a module instance through
reconstruct_implicit_variable so its ModuleInputs survive (the generic
parse+lower path drops them against an empty scope.models), letting the
recompute read a module's entry/exit ports -- the same fix
reconstruct_single_variable already applied for the exhaustive override.

Design choice: a post-discovery recompute (approach (a)) rather than emitting
per-exit-port via-alias link-score vars in discovery mode (approach (b)). The
recompute is self-contained in ltm_finding.rs, needs no new synthetic vars,
and reuses the existing max_abs_score_series helper; the parity-critical
pathway-index derivation reuses CausalGraph::enumerate_pathways_to_outputs.

Regression coverage: cross-mode polarity agreement in
tests/simulate_ltm.rs (discover_loops convenience path) plus two
analyze_model end-to-end tests (production path) for the aux-reader and
module->module exit-port arms.

GH #698
Discovery mode silently dropped every cross-element feedback loop that
traverses a hoisted reducer's synthetic $:ltm:agg:{n} node more than once
(pop[a] -> agg -> pop[b] -> agg -> pop[a]). Such a loop is non-elementary
in the element graph, and the strongest-path DFS's `visiting` set forbids
revisiting any node -- including the agg -- so the search could never
construct it. Exhaustive mode reconstructs these by stitching the single-agg
"petals" together via recover_cross_agg_loops; discovery never ran any
recovery. The bite was worst exactly where it matters: a reducer-in-feedback
model over a large dimension trips MAX_LTM_SCC_NODES, auto-flips to discovery,
and loses precisely the loops that matter there, with no signal.

Fix with approach (a) from GH #696: post-discovery petal stitching that
reuses the SAME combinatorial core exhaustive uses, rather than relaxing the
DFS's elementary-cycle invariant. The petal priority / pairwise-disjoint-
internal-node rule / MAX_AGG_PETALS / cyclic_orderings enumeration / loop-count
budget are extracted from recover_cross_agg_loops into a mode-agnostic
stitch_cross_agg_petals (generic over the node representation: &str circuit
nodes for exhaustive, owned Ident for discovery) plus a shared collect_agg_petals
extractor. recover_cross_agg_loops now calls them, so its behavior is unchanged
(the four-petal cyclic-orderings test still passes bit-for-bit). Discovery
treats each discovered single-agg path as a petal, stitches the disjoint subsets,
appends the stitched element-level sequences back into all_paths (deduped by
canonical rotation), and lets them flow through the identical FoundLoop
construction / score-product / trim / dedup / rank pipeline -- so a stitched
loop is scored exactly as any discovered loop (its edge multiset is the union
of its petals' disjoint edges, hence the per-step product of the petals' link
scores). This is the principled choice: it keeps the DFS's invariants intact,
mirrors the exhaustive design exactly, and guarantees discovery recovers the
same loop set exhaustive does (cross-validated by value, not just count).

Recovery is post-simulation, so there is no salsa diagnostic accumulator to
emit the truncation Warning exhaustive uses; DiscoveryResult gains an
agg_recovery_truncated flag (the analogue of LtmVariablesResult's), threaded
through analysis::ModelAnalysis.

The multi-agg subtlety is handled identically to exhaustive: a petal is a
circuit touching exactly one agg once, so a discovered path through two
distinct aggs is already a complete loop, not a petal.

GH #696.
The test helper claimed to use "the same wiring analyze_model uses",
but it builds its graph with the bare causal_graph_from_element_edges
constructor while production analyze_model uses the _with_modules
enriching variant. The distinction is exactly the kind that masked the
GH #698 production no-op, so the docstring should not invite a future
reader to rely on it; the production wiring is covered end-to-end by
the cross-validation test in tests/simulate_ltm.rs.
model_detected_loops is a pre-simulation salsa query, so it can only report a
loop's structural polarity. Pervasively for module-heavy models the static
polarity of a variable->module / module->variable black-box link is Unknown, so
a loop through a module boundary is labelled Undetermined even when its
simulated loop score is single-signed at every active step (GH #679).
Reclassifying from runtime scores is therefore a post-simulation concern.

This adds db::analysis::reclassify_loops_from_results, the canonical in-engine
primitive: it reads each loop's $:ltm:loop_score:{id} slot(s) from a Results and
applies LoopPolarity::from_runtime_scores to overwrite the polarity and
polarity_confidence, keeping the loop id stable (the FFI id->score
correspondence and salsa caching depend on a loop detected as u1 keeping the id
u1 even when its runtime polarity is Reinforcing). A loop whose score is never
active keeps its structural polarity.

Scope is deliberately narrow and the framing is honest about what does NOT
change behavior:

- The helper has NO production caller yet. The libsimlin/WASM/TS
  simlin_analyze_get_loops surface takes only a SimlinModel (no Results in
  hand), is intentionally structural-only, and folds Mostly* to R/B and drops
  confidence at the C ABI boundary. Surfacing runtime polarity there is the FFI
  work tracked under GH #495; this change does NOT unblock that on the
  exhaustive path (the coalescing/confidence-drop happens regardless of how the
  polarity was computed). The helper exists so a future sim-bearing Rust
  consumer has one correct place to call.
- pysimlin Run.loops already reclassified via its own Python
  from_runtime_scores mirror; that behavior predates this commit. A regression
  test now pins the exhaustive module-boundary case there.
- The engine analyze_model / MCP surface is discovery-based and already
  reclassifies through the FoundLoop path.

The three reclassification sites use DIFFERENT A2A input constructions (the
Rust helper concatenates all element slots; pysimlin reads slot 0; discovery
uses one strongest-path scalar per FoundLoop), so the docs and docstrings
deliberately do not claim they "match exactly" -- they agree on scalar loops
and the shared from_runtime_scores semantics, and diverge only in how an A2A
loop's element slots are reduced. The structural-vs-runtime polarity
match-blocks in model_detected_loops are factored through a shared
detected_polarity_from_ltm mapper.

C-LEARN runs in discovery mode, so the change has nil impact there.

GH #679
The discovery-mode per-exit-port pathway recompute (GH #698) reconstructed a
sub-model's output-port set by scanning only the analyzed model's variables.
Emission (db::ltm::find_model_output_ports) derives it from reads across ALL
project models, and the sub-model emits its $.ltm.path.{port}.{idx} vars
against that project-wide sorted set. So when the same sub-model is also
instantiated in another project model (or nested in another sub-model) that
reads an additional output port sorting BEFORE the port the loop traverses,
every pathway index shifts and the recompute read the wrong pathway var --
re-introducing the wrong-signed module edge the GH #698 fix was meant to
eliminate.

Fix by identity-by-construction: discover_loops_with_graph now takes a
SubModelOutputPorts map (sub-model canonical name -> emitted sorted port set).
analyze_model builds it via the new public build_sub_model_output_ports, which
calls the SAME db::ltm::sub_model_output_ports decision emission uses (one per
project model, including the stdlib output-convention short-circuit), so the
recompute enumerates pathway indices against the identical set the sub-model
emitted against regardless of which project model the loop lives in. The
db-less discover_loops(&Results, &Project) convenience path (tests only)
reconstructs the same project-wide-union + stdlib-output semantics in
project_sub_model_output_ports rather than scanning the analyzed model alone.
The shared ltm_discovery_inputs test harness threads the map (and now uses the
module-enriched element graph) so the wasm/VM parity and large-model harnesses
mirror production exactly.

This replaces the parent-scoped discovery_sub_model_output_ports (removed).
causal_graph_from_element_edges_with_modules is now pub so the harness mirrors
the production graph.

Reference: #705 (comment)
GH #698
When one parent variable x is wired to MORE THAN ONE input port of module m
(x -> m.a AND x -> m.b), the causal edges collapse to a single x -> m edge, so
the per-exit-port pathway recompute (GH #698) had no unambiguous entry port.
Both the discovery recompute (recompute_module_input_edge_series) and the
exhaustive twin (compute_module_link_overrides) resolved the entry port with a
find_map that silently picked the FIRST matching ModuleInput, then recomputed
the loop edge from that port's pathway -- which can be the wrong port (or miss
the active one), reporting a wrong-signed loop score/polarity.

Treat multiple matching ModuleInputs as ambiguous and decline (return
None/continue), leaving the base composite link score (the documented
pre-existing first-matched-port approximation) in place -- exactly mirroring
the multi-match -> ambiguous semantics the exit-port helpers
(discovery_module_exit_port / module_exit_port_for_reader) already use. Both
sides had the identical bug, so both are fixed for parity.

The regression fixture wires a stock to two input ports of a sub-model whose
loop-exit output (late = 0 - a) has the opposite sign of the base composite's
tie-broken pathway (early = a, +1); before the fix the first-match recompute
flipped the loop to balancing, now it follows the base composite (reinforcing)
in both modes.

Reference: #705 (comment)
GH #698
@bpowers
bpowers force-pushed the ltm-review-fixes branch from d78e05e to 4d20dec Compare June 4, 2026 04:54
@bpowers

bpowers commented Jun 4, 2026

Copy link
Copy Markdown
Owner Author

@codex review

@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: 4d20dec63b

ℹ️ 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/ltm_finding.rs Outdated
Comment on lines +2123 to +2128
Variable::Module { inputs: y_in, .. } => y_in.iter().find_map(|inp| {
if normalize_module_ref(&inp.src) == *module_name {
inp.src
.as_str()
.split_once('\u{00B7}')
.map(|(_, port)| Ident::new(port))

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 Treat ambiguous module-to-module exits as fallback

When the next reader y is also a module and has multiple inputs sourced from the same module instance (for example m.pos -> y.a and m.neg -> y.b), the collapsed loop edge is just m -> y, so it does not identify a unique exit port. This new discovery recompute currently takes the first matching input via find_map, which can select the wrong output pathway and flip or zero the recomputed x -> m score; it should mirror discovery_module_exit_port and return None on multiple matches so the base composite is left in place.

Useful? React with 👍 / 👎.

@claude

claude Bot commented Jun 4, 2026

Copy link
Copy Markdown

Review

I reviewed the PR's code-changing files (scripts/dev-init.sh, src/simlin-engine/src/db/analysis.rs, src/simlin-engine/src/db/ltm/{loops.rs,mod.rs}, src/simlin-engine/src/ltm/{graph.rs,types.rs}, src/simlin-engine/src/ltm_finding.rs, src/simlin-engine/src/analysis.rs, src/pysimlin/tests/test_ltm_polarity.py) and the new integration tests.

Findings: none I'd ask the author to fix.

Notes on what I checked:

  • GH ltm: discovery mode can report the wrong loop polarity (sign error) through a multi-output module #698 entry-port disambiguation (recompute_module_input_edge_series in ltm_finding.rs ~L2096-L2107 and the exhaustive twin compute_module_link_overrides in db/ltm/mod.rs ~L470-L482): both now decline on multi-port entries instead of silently picking the first match, with mirrored semantics. The fixture in analyze_model_ambiguous_entry_port_falls_back_to_composite cross-checks both modes agree.
  • GH ltm: discovery mode can report the wrong loop polarity (sign error) through a multi-output module #698 exit-port resolution for module->module hops (recompute_module_input_edge_series ~L2123-L2133): uses find_map (first-match) like the exhaustive twin in db/ltm/mod.rs ~L498-L508, so the asymmetric ambiguity handling between Module y_var and Var y_var is preserved consistently across both modes (pre-existing pattern, not a new regression).
  • Project-wide output-port set (build_sub_model_output_ports in analysis.rs and project_sub_model_output_ports in ltm_finding.rs): both derive port sets via the same db::ltm::sub_model_output_ports decision / project-wide-union + stdlib output short-circuit. The db-less convenience path's reconstruction matches emission for the common cases (a flow/aux's main equation, and stocks' init_ast since var.ast() returns it for Variable::Stock). A flow's init_ast reading a module output is theoretically missed, but this is an edge case unlikely to matter.
  • Cross-agg petal stitching (stitch_cross_agg_petals / collect_agg_petals in db/ltm/loops.rs): the generic extraction preserves the priority sort, disjoint-subset enumeration, MAX_AGG_PETALS cap, and global-budget logic of the original. The petal sort comparator changed from (internal.len(), nodes.join("\u{0}")) to (internal.len(), nodes Vec<T> lex), which yields equivalent orderings for the inputs the test suite covers (test pinned bit-for-bit per PR description). Dedup of stitched paths against existing all_paths via canonical_rotation of node names is consistent with the integer-id dedup already in place because IndexedSearch::build is a bijection between names and ids.
  • reconstruct_model_variables (db/analysis.rs ~L2548-L2577): module variables now go through reconstruct_implicit_variable to preserve inputs, mirroring reconstruct_single_variable. The early continue skips the implicit_vars extraction for modules, which is fine because parsing a module variable doesn't generate SMOOTH/DELAY-style implicit vars.
  • reclassify_loops_from_results (db/analysis.rs ~L1948-L1989): the per-slot bounds check (if off < results.step_size) silently drops out-of-bounds slots, which is defensive in practice; loop ids are preserved across reclassification as documented.
  • dev-init.sh: resolves the symlink target against dirname(git rev-parse --git-common-dir) (the main checkout) and guards on the target existing. Behavior is correct for both main and linked-worktree invocations.

Overall correctness

Correct.

The per-exit-port pathway recompute (GH #698) reads the loop's exit port off
the next link m -> y. The module-to-module exit arm -- where y is itself a
module fed by m's output -- resolved that port with a find_map that silently
picked the FIRST of y's inputs sourced from m. When y reads MORE THAN ONE
distinct output port of m (m.early -> y.p AND m.late -> y.q), the collapsed
m -> y edge has no unique exit port, so first-match could select the wrong
output pathway and recompute the x -> m edge against it, flipping or zeroing
the loop's score/polarity. This is the third symmetric instance of the
multi-match family (after the entry port and the project-wide output set).

Count distinct matching ports and decline (None -> base composite fallback)
when two DISTINCT ports match, mirroring the multi-match -> ambiguous
semantics the non-module exit helper (module_exit_port_for_reader /
discovery_module_exit_port) and the entry-port resolution already use. Two of
y's inputs naming the SAME m.port are NOT ambiguous (a unique distinct port).
Both the discovery recompute (recompute_module_input_edge_series) and the
exhaustive twin (compute_module_link_overrides) had the identical bug, so both
are fixed for parity.

The regression fixture wires a consumer module to two opposite-signed output
ports of an upstream producer module inside a feedback loop, ordered so
first-match would pick the (-) port; before the fix the recompute flipped the
loop to balancing, now it follows the base composite (reinforcing) in both
modes.

Reference: #705 (comment)
GH #698
@bpowers

bpowers commented Jun 4, 2026

Copy link
Copy Markdown
Owner Author

@codex review

@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: 0672537aae

ℹ️ 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/ltm_finding.rs Outdated
Comment on lines +2104 to +2106
let mut matching = inputs
.iter()
.filter(|inp| normalize_module_ref(&inp.src) == link.from);

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 Normalize element names before matching module ports

When discovery runs on an element-level graph, an arrayed source edge is named like s[NYC] -> m, while the module input wiring still stores the base source s; this exact comparison therefore makes recompute_module_input_edge_series return None for arrayed loops through a multi-output module. In that case discovery falls back to the module composite score across all outputs, so the same wrong-exit-port polarity bug this override is meant to fix still occurs for loops such as s[e] -> m -> growth[e] -> s[e]. The exhaustive override strips subscripts before this match, and the discovery path needs the same normalization for element-level names.

Useful? React with 👍 / 👎.

@claude

claude Bot commented Jun 4, 2026

Copy link
Copy Markdown

Code Review

[P2] Discovery's per-exit-port recompute does not strip element subscripts, unlike the exhaustive twin

File: src/simlin-engine/src/ltm_finding.rs (lines 2100-2122)

recompute_module_input_edge_series looks up the entry port via normalize_module_ref(&inp.src) == link.from and the exit reader via causal_graph.variables().get(&next.to), both without stripping element subscripts. In contrast, the exhaustive twin compute_module_link_overrides (src/simlin-engine/src/db/ltm/mod.rs:438-485) consistently applies strip_subscript(link.from.as_str()), strip_subscript(next.from.as_str()), and strip_subscript(next.to.as_str()) before the same lookups. The element-level graph emits subscripted source nodes for arrayed sources feeding modules (e.g. pop[a] -> m, see emit_edges_for_reference in src/simlin-engine/src/db/analysis.rs:236-278), and Variable::Module.inputs[*].src is bare (pop), so the equality check fails and the recompute silently falls back to the (potentially wrong-signed) composite. Same for an arrayed reader on the exit side: variables is keyed by bare names, so get(&next.to) returns None when next.to is y[a]. The current regression tests use only scalar stocks/auxes through modules, so this asymmetry is not exercised; an arrayed source-or-reader through a multi-output module would reproduce the original GH 698 polarity-inversion in discovery mode while exhaustive correctly applies the override. The fix is to strip_subscript (and Ident::new the result) before the three lookups, mirroring the exhaustive path.

Overall correctness verdict: correct (with the above caveat)

The patch is internally consistent and the core fixes (per-exit-port recompute, cross-agg petal-stitching extraction, project-wide port-set threading, ambiguous entry/exit fallback, dev-init hook resolution) look right and are well-covered by regression tests against the exhaustive sibling. The arrayed-source/reader-through-module asymmetry above is the only meaningful correctness gap I see, and it does not regress against the pre-PR baseline (discovery's pre-PR behavior was the composite fallback on every module edge), so it is a missed optimization rather than a new bug. The rest of the changes -- documentation, test coverage, the new reclassify_loops_from_results primitive (no production caller yet), pysimlin pin, and the example/test plumbing -- all look correct.

Discovery runs on the element-level graph, so an arrayed loop's non-module
nodes carry element subscripts (s[nyc] -> m -> growth[nyc]).
recompute_module_input_edge_series matched the entry port with an exact
`normalize_module_ref(inp.src) == link.from` and looked the exit reader up in
the bare-keyed variables() map -- both fail on the subscripted forms, so the
recompute declined for EVERY arrayed module loop and the wrong-exit-port
composite bug the override exists to fix re-occurred. Strip the subscript via
the canonical crate::ltm::strip_subscript on link.from (entry match),
link.to/next.from (module node + sequentiality guard), and next.to (exit
reader lookup) before each name comparison, preserving the prior ambiguity
semantics (two distinct ports -> decline; same port twice -> unique). This
mirrors the exhaustive twin compute_module_link_overrides, which already
strips link.from/link.to/next.from/next.to (db/ltm/mod.rs).

The end-to-end arrayed manifestation is currently masked by an upstream gap:
a scalar module output feeding an arrayed reader (growth[Region] = m.pos)
emits a single scalar constant-0 link score rather than per-element
m->growth[e] scores, so the loop product is 0 and discovery drops the loop
before the recompute runs. That gap is tracked separately as GH #716. This
change is therefore latent defense that restores name-handling parity with
the exhaustive override; it is covered by a unit-level red-green test
(recompute_strips_element_subscripts_before_port_match) that drives the
matching code directly with a real compiled module project's graph/results
and a hand-built subscripted links chain (fails returning None before, passes
returning the pos-pathway series after), plus a documentation test
(analyze_model_arrayed_module_loop_blocked_by_scalar_output_gap) pinning the
current masked end-to-end state so closing #716 is a deliberate change.

The `ltm_finding.rs` test module moved to a sibling `ltm_finding_tests.rs`
(mounted via `#[cfg(test)] #[path]`) to keep the production file under the
per-file line cap.

Reference: #705 (comment)
GH #698
@bpowers

bpowers commented Jun 4, 2026

Copy link
Copy Markdown
Owner Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🎉

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

@claude

claude Bot commented Jun 4, 2026

Copy link
Copy Markdown

Review Summary

I reviewed this PR carefully against its three discovery-mode correctness claims (per-exit-port recompute, cross-agg loop recovery, runtime polarity reclassification) plus the dev-init hook fix. The implementation is careful, the comments are thorough, and the regression tests are strong (including the discriminating power checks).

I did not identify any blocking correctness bugs introduced by this change. A few minor observations below for the author's awareness, but none rise to the level of needing a fix.

Observations (non-blocking)

src/simlin-engine/src/ltm_finding.rs — performance of recompute_module_input_edge_series
This is called for every link of every discovered loop, and each call may invoke enumerate_pathways_to_outputs_with_truncation on the module's sub-graph. For a discovery pass over a model with many loops crossing many module instances, the same sub-model pathway enumeration is recomputed redundantly. The exhaustive-mode twin (compute_module_link_overrides) faces a similar pattern but emits aliases once. If this surfaces as a hot spot on large models, a HashMap<(sub_model, entry_port), &pathways> keyed cache reusable across loops would help. Not a correctness issue.

src/simlin-engine/src/ltm_finding.rs:894-905 — convenience path divergence from emission
project_sub_model_output_ports applies a port.starts_with('$') filter that the salsa-side find_model_output_ports does not have. In practice the salsa side runs pre-LTM-emission (no $⁚ltm⁚… references in the user model's deps), so the produced port sets match — but the comment claims project-wide-emission identity which is slightly overstated; the safety comes from temporal ordering, not from byte-identical scanning logic.

src/simlin-engine/src/db/analysis.rs:1944 — reclassify_loops_from_results slot guard
The if off < results.step_size per-slot guard silently drops out-of-range slots rather than asserting. If loop_partitions[id].len() and the emitted loop_score series ever desynced, the reclassification would proceed against a partial sample set rather than fail loudly. This shouldn't happen in practice but a debug_assert! would catch a future regression.

src/simlin-engine/src/ltm/graph.rs:233-244 — sub-graph build cost
Now builds a recursive sub-graph for every referenced module (including stockless passthroughs that have no pathways), as the PR description notes. The wasted work for genuinely pathless modules is real (each one walks the full sub-model edge set) though almost certainly negligible vs. compile/sim cost. Worth tracking if it ever appears in a profile.

Overall correctness verdict

Correct — the change is implemented as documented; existing tests pass; the new regression tests are well-discriminated against stub-reverts of each fix; the dev-init hook fix correctly resolves through --git-common-dir.

@bpowers
bpowers merged commit 26a641e into main Jun 4, 2026
3 checks passed
@bpowers
bpowers deleted the ltm-review-fixes branch June 4, 2026 13:30
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