Repository navigation
engine: LTM review hardening and module link-score correctness (#675) - #684
Conversation
Findings from a deep review of the LTM implementation against the four
papers (scoring math validated empirically and found faithful; these are
the actionable gaps the review surfaced):
1. Dense-SCC OOM guard. MAX_LTM_SCC_NODES bounds node count but circuit
count is super-exponential in SCC density: a near-complete 14-node
digraph holds ~119M elementary circuits and uncapped Johnson allocates
tens of GB while passing both 50-node gates. Every production Johnson
run now carries MAX_LTM_CIRCUITS (100k); exhausting it marks the result
truncated, which the shared model_ltm_mode gate treats like an oversized
SCC (flip to discovery + Warning). A pin whose element expansion blows
the budget becomes an invalid pin. The truncation check in
model_ltm_variables runs before the empty-circuits branch, which would
otherwise read a truncated result as "no loops to score".
2. Module input reconstruction. reconstruct_single_variable lowered
explicit module variables through lower_variable with an empty
scope.models map, so resolve_module_input dropped every input and the
reconstructed Variable::Module carried inputs: []. The LTM module link
formulas match the edge source against those inputs, so every
input-to-user-module link score silently fell through to a bare-module
delta-ratio whose fragment cannot compile (score stubbed to 0) in BOTH
modes. Explicit modules now take the same direct-construction path as
implicit ones. Discovery mode additionally hardcoded the output port
name ("output") for user modules; the new model_module_output_ports
query scans the model's dependency sets for module-qualified references
instead, so non-stdlib port names resolve.
3. Polarity value-sign rules. The Mul both-operands-dependent arm composed
derivative signs, which the product rule does not justify: logistic
growth pop*(1-pop/K) was labeled a definite Negative (confidence 1.0)
while its true partial flips sign at K/2. Both-sides Mul/Div now
propagate only when derivative signs agree (Mul) / oppose (Div) AND both
operands are positive-by-convention (bare variable refs or positive
constants -- compound factors like 1-pop/K stay Unknown). One-sided Div
now consults the independent operand's provable value sign (-5/y is
Positive, x/-5 is Negative; both were labeled with the opposite sign
before), keeping the conventional positive-value assumption only for
non-constant operands, documented as a labeling convention.
The design doc is updated for these changes plus stale-claim corrections
from the same review: loop dedup is by canonical rotation (not sorted node
set, fixed in #308); the expansion-cap "effectively exhaustive" claim is
scoped to components where the cap does not bind (it binds at K8 density);
the GH #528 broadcast-agg degradation is fail-loud (compile failure +
Warning), not silent; the black-box module formula is documented as a gain
rather than a true link score; and the pin sibling-cycle limitation is
recorded.
The black-box module link formula computed `Δto/Δfrom` -- the GAIN dz/dx (a sensitivity), not an LTM link score. A link score is `|Δ_x(z)/Δ(z)| · sign(Δ_x(z)/Δ(x))`, normalized by the TARGET's change. The two differ by the `|Δx/Δz|` weighting that makes link scores chain multiplicatively into loop scores: an isolated feedback loop's raw loop score is exactly ±1 regardless of the gains around it (papers' Appendix B), an invariant the gain formula breaks (the loop score scales with the product of the gains). This replaces the gain everywhere a module link is scored. module_link_score_equation is now the single source of truth for a module-involved link's equation, shared verbatim by the (from, to)-keyed link_score_equation_text and the per-shape link_score_equation_text_shaped so the two twins can never drift. Three cases, each preferring a faithful link score and only falling back to the magnitude-1 signed black_box_unit_transfer_equation (SIGN(Δto)·SIGN(Δfrom)) when nothing better exists: - module->module: reference the target module's composite for the fed input port (the macro treatment, ref 6) -- the wiring from the source module's output to the target's input port is an identity, so the loop product equals the fully-expanded model's. The edge source is the normalized module node, but the target's ModuleInput::src is the module-qualified from-output, so the match is by normalize_module_ref(src), not raw equality (the prior code's raw match always missed for a module source). - module->variable: a real ceteris-paribus partial is available (the target's equation references module-output), so use it -- the exact link score. The prior gain arm WAS reachable and fired for every module->downstream edge; a single-input downstream that should score 1 scored the gain instead. - variable->module and the passthrough residual: the signed unit transfer against a READABLE scalar output ref (module-port), never the bare module name. For a single-input black box z=F(x) the unit transfer is exact (all of dz is attributable to x); for stateful/multi-input boxes it is the perfect-mixing-spirit approximation: polarity exact, magnitude approximated as 1. Ground-truth findings while implementing: 1. The pre-fix module->module fragment referenced the BARE module names (delta-mod_b/delta-mod_a), which are not scalar-readable, so an isolated loop through a passthrough-module chain scored 0 (the variable->module composite reference into a passthrough -- which has no composite -- also resolved to a constant 0). This fix upgrades those dead links. 2. Composites resolve in discovery mode. The pre-fix code gated composite references to exhaustive mode on a now-stale "cross-module refs don't resolve in discovery" assumption; since GH #548 build_submodel_metadata lays out a sub-model's composite vars in the parent's flattened offset map whenever ltm_enabled (both modes). An empirical probe showed a SMOOTH composite resolving to a nonzero value in a discovery run, so discovery now uses the same composite reference exhaustive mode does -- the divergent discovery-only gain branch is deleted. module_composite_ports reads the sub-model's actual model_ltm_variables output to decide whether a port has a composite, rather than guessing from the module's stock count. Tests: an isolated single-stock loop routed through a two-passthrough- module chain (including a module->module link) now has raw loop score exactly +1 at gains 1.0/2.0/0.5 (was 0 -- the links were dead). The multi-input module link-score magnitude test now passes and is un-ignored (module->variable is a real ceteris-paribus partial, ~0.5, not the gain), so it runs under pre-commit/CI rather than only on demand. C-LEARN exhaustive + pinned end-to-end and the LTM-on-wasm discovery parity suites stay green. Refs #675.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: cb2a774c39
ℹ️ 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".
| let port = ports | ||
| .first() | ||
| .cloned() |
There was a problem hiding this comment.
Avoid scoring against an arbitrary module output
For stockless/passthrough modules with more than one parent-visible output, this fallback always scores the input→module link against the first sorted port, regardless of which output is actually used by the loop. For example, if a module exposes both pos = input and neg = -input and the feedback path reads m.pos, model_module_output_ports can still return neg first, causing the unit-transfer sign for input→m to be computed from the wrong output. Since the causal edge has been collapsed to the module node, this should avoid choosing an arbitrary port or carry enough port context to select the output participating in the edge.
Useful? React with 👍 / 👎.
Code ReviewAfter a deep review of the two commits (the LTM hardening pass and the module link-score scoring fix), I did not find any blocking issues. The changes are well-tested, well-documented, and address real correctness gaps with sound reasoning:
The Overall correctness verdictCorrect. The patch closes the four identified gaps without breaking existing behavior. The test coverage (production-budget OOM gate, isolated-loop ±1 invariant across module→module, passthrough port-name fidelity, discovery-mode composite parity, logistic growth polarity, signed numerator/denominator Div) is exhaustive for the surface it touches, and the previously- |
A loop through a multi-output passthrough module was scored against the wrong output port. The `input -> module` link score's unit-transfer fallback picked `ports.first()` -- the alphabetically-first parent-read output -- regardless of which output the loop actually traverses. For a passthrough exposing `pos = input*0.02` and `neg = -input` whose feedback loop reads only `m.pos` (and a side variable reads `m.neg`, forcing `neg` into the output-port set), the `input->m` score was computed against `neg`, whose sign opposes `pos`, flipping the whole loop's polarity (raw score -1 instead of +1). See PR #684 review r3344948690. Composites alone cannot fix this: the composite max-abs-selects across ALL of the module's pathways, and a single-dependency link score is just `(dz)/|dz| = SIGN(dz)`, so the `0.02` coefficient cancels and BOTH `pos` and `neg` score magnitude exactly 1. The composite's `if ABS(path0) >= ABS(path1)` selection is therefore comparing 1 against 1 -- a structural magnitude-1 TIE that `>=` resolves to the first index, `path0`, which is `neg`, exactly the wrong port. Because the candidates always tie, max-abs can never recover the right port here; it just returns whichever pathway is enumerated first. The fix instead selects, per loop link, the pathway the loop actually traverses. Three parts: * Passthrough modules now emit real pathway/composite vars. The stock-free early return in `model_ltm_variables` fired before computing input-port pathways; it now fires only when the model has neither stocks nor input-port pathways, so a passthrough (whose internals are a pure aux chain LTM scores exactly) gets instrumented while a stock-free root model -- no parent reading `module.var`, hence no output ports -- still emits nothing. * `find_model_output_ports` sorts its result (closes GH #680). The merge order of the HashSet it returned was process-nondeterministic; the sub-model's pathway-index assignment and the parent's recomputation must agree on it, so the sort is a prerequisite for index-for-index identity. Both sites now derive the output-port set through one shared `sub_model_output_ports` helper (stdlib-prefixed name -> `["output"]`, else `find_model_output_ports`), so the stdlib `output` convention and the user-model port scan are byte-identical by construction -- the pathway indices the alias references cross-module cannot skew apart. * In exhaustive mode the loop-score equation overrides each `x -> m` module link with a per-exit-port pathway selection. The exit port is read off the next loop link `m -> y` (the unique real `m.port` `y` reads, or `y`'s matching ModuleInput.src when `y` is itself a module); the entry port is `m`'s ModuleInput whose normalized src is `x`. The parent recomputes the sub-model's pathway map with the same salsa-cached inputs the sub-model's own emission uses, so the recomputed pathway indices match the emitted `$:ltm:path:{entry}:{idx}` vars. The override is an alias var `$:ltm:link_score:{x}->{m}:via:{exit}` (single matching pathway ref, a max-abs selection over several, or `"0"` when none connect entry to exit). The alias reads SUB-model pathway vars, which the parent evaluates when it runs module `m` -- before its appended link-score fragments -- exactly as the existing composite reference resolves at the current step (verified by an end-to-end simulation assertion). `Loop.links` is NOT rewritten (loop IDs derive from the link sequence and the FFI's id->score correspondence depends on it); the override is threaded into the loop-score equation builder as a `(loop_id, link_index)` side-table. The base arbitrary-port unit-transfer fallback remains, but now fires only for a genuinely pathway-less module (output independent of input), whose link score is moot. Discovery mode is untouched (no loop-score vars to override; the base composite is the paper-faithful per-edge approximation). Residual gap: pinned loops pass an empty override map, so a pin traversing a multi-output module still uses the arbitrary-port base fallback.
Review summaryReviewed the PR end-to-end. The changes are internally consistent and well-motivated:
End-to-end correctness is empirically pinned by the new I found no actionable bugs introduced by this PR worth flagging. Overall correctness verdictCorrect. No findings. |
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
find_model_output_ports already sorts its output-port set before returning (landed in PR #684), replacing an unordered HashSet drain whose process- random iteration order leaked into pathway enumeration, magnitude-tie winner selection, and the $⁚ltm⁚path⁚{port}⁚{idx} synthetic-var indices -- making salsa cache values byte-unstable across processes for multi-output modules with tied pathway scores. That fix shipped without the regression test the issue called for. Add a test that pins the sorted contract through the sub_model_output_ports wrapper (which delegates straight to find_model_output_ports for a non- stdlib model): a main model reads three internal ports of a multi-output sub-model in reverse-alphabetical order, and the returned set must be canonical-name-sorted regardless of read, declaration, or hash order. The function is pub(super) within the ltm module, so the test exercises it via the crate-visible wrapper rather than constructing a tied-pathway-score fixture (which would be disproportionate for pinning the sort itself). Addresses GH #680.
Two commits from a deep review of the LTM implementation against the four papers (seven-agent audit: scoring math validated empirically across eight invariants; these commits close the actionable gaps it surfaced).
Commit 1: harden LTM circuit budgets, module links, and polarity rules
MAX_LTM_SCC_NODESbounds node count, but elementary-circuit count is super-exponential in SCC density: a near-complete 14-node digraph holds ~119M circuits and OOMs uncapped Johnson (~26 GB measured) while passing both 50-node gates. Every production Johnson run now carriesMAX_LTM_CIRCUITS(100k); exhausting it flips the model to discovery via the sharedmodel_ltm_modegate with a Warning, and an over-budget pinned-loop expansion becomes an invalid pin. End-to-end pinned by a production-budget test (the dense model now resolves in 0.08s).reconstruct_single_variablelowered explicit module variables against an emptyscope.models, so every input failed resolution and the reconstructedVariable::Modulecarriedinputs: []— silently zeroing input→user-module link scores in both modes. Explicit modules now take the same direct-construction path as implicit ones, and discovery mode resolves the module's real output port via the newmodel_module_output_portsdependency scan instead of a hardcodedoutput.pop*(1-pop/K)was labeled a definite Negative (confidence 1.0) while its true partial flips sign at K/2. Both-sides Mul/Div now propagate only when derivative signs agree (Mul) / oppose (Div) AND both operands are positive-by-convention (bare refs or positive constants — compound factors like1-pop/Kstay Unknown). One-sided Div consults provable value signs (-5/yis Positive,x/-5is Negative; both were labeled backwards), keeping the conventional positive-value assumption only for non-constant operands, documented as a labeling convention.Commit 2: score module link scores as link scores, not the gain dz/dx (#675)
The black-box module formula computed the gain Δto/Δfrom, which lacks the target-change normalization that makes link scores chain into loop scores — and ground-truth probing showed the pre-fix module paths were worse than biased: passthrough-module links referenced composites that do not exist (a cross-module read of an absent LTM var compiles cleanly and reads 0, see #683), and module→module links referenced unreadable bare module names. Now: module→module and variable→module links reference the target module's composite wherever the sub-model exposes one (both modes; the discovery-mode divergence was stale post-#548 and is deleted), module→variable links use a real ceteris-paribus partial, and the residual no-composite case uses a magnitude-1 signed unit-transfer (exact for single-input stateless modules) instead of the gain.
Verified by an adversarial review pass: an isolated loop through a module→module chain scores exactly ±1 at any gain (the papers' Appendix B invariant, violated by the gain formula), and a SMOOTH-routed loop's score is byte-identical to the fully-expanded explicit-stock model's, with the module-internal drain loops correctly suppressed.
Testing
Full pre-commit gauntlet on both commits (Rust fmt/clippy/tests, TS, pysimlin, wasm), all LTM integration suites, and the ignored C-LEARN/WRLD3 release-mode tests (exhaustive identity vs Ref.vdf, pinned climate loop, wasm discovery parity).
Issues: closes #675; review findings filed as #673, #674, #676, #677, #678, #679, #680, #681, #683.