Skip to content

engine: LTM review hardening and module link-score correctness (#675) - #684

Merged
bpowers merged 3 commits into
mainfrom
ltm-review-hardening
Jun 3, 2026
Merged

bpowers merged 3 commits into
mainfrom
ltm-review-hardening

Conversation

@bpowers

@bpowers bpowers commented Jun 2, 2026

Copy link
Copy Markdown
Owner

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

  • Dense-SCC OOM guard. MAX_LTM_SCC_NODES bounds 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 carries MAX_LTM_CIRCUITS (100k); exhausting it flips the model to discovery via the shared model_ltm_mode gate 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).
  • Module input reconstruction. reconstruct_single_variable lowered explicit module variables against an empty scope.models, so every input failed resolution and the reconstructed Variable::Module carried inputs: [] — 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 new model_module_output_ports dependency scan instead of a hardcoded output.
  • Polarity value-sign rules. The Mul both-operands arm composed derivative signs, which the product rule does not justify: logistic 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 like 1-pop/K stay Unknown). One-sided Div consults provable value signs (-5/y is Positive, x/-5 is Negative; both were labeled backwards), keeping the conventional positive-value assumption only for non-constant operands, documented as a labeling convention.
  • Design-doc corrections from the same review: canonical-rotation dedup (not sorted node set), expansion-cap exhaustiveness claim scoped to where the cap does not bind, ltm: agg→target link score over-subscripts an arrayed synthetic agg in the broadcast case (agg[D1] feeding to[D1,D2]) #528 is fail-loud, black-box formula caveat, pin sibling-cycle limitation.

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.

bpowers added 2 commits June 2, 2026 14:30
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.

@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: 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".

Comment on lines +578 to +580
let port = ports
.first()
.cloned()

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 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 👍 / 👎.

@claude

claude Bot commented Jun 2, 2026

Copy link
Copy Markdown

Code Review

After 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:

  • MAX_LTM_CIRCUITS budget: truncation propagates correctly through LoopCircuitsResult → TieredCircuitsResult → model_ltm_mode and model_ltm_variables. The order of the truncation check before the slow_path_largest_scc check in model_ltm_variables (db/ltm/mod.rs:1203) is critical to avoid silent disagreement with the mode gate, and is correctly documented.
  • module_link_score_equation consolidation: the shared helper between link_score_equation_text and link_score_equation_text_shaped is bit-identical, and the composite_ref_for_port correctly resolves through both edges.dynamic_modules (implicit/stdlib) and model.variables (user-defined explicit). The normalize_module_ref(&i.src) == from_ident match on the module→module arm correctly handles the source-qualified ModuleInput::src.
  • Signed unit-transfer fallback: SIGN(Δto) * SIGN(Δfrom) preserves the Appendix B isolated-loop ±1 invariant, byte-pinned by module_to_module_isolated_loop_raw_score_is_one across three gain values.
  • Mul/Div polarity rules: the new operand_positive_by_convention predicate correctly distinguishes bare variable references (positive-by-convention) from compound expressions like (1 - pop/K) whose value sign itself flips. Both-sides Mul requiring agreeing derivative signs AND positive-by-convention operands matches the product rule's true sign condition; Div mirroring with opposing signs matches the quotient rule. The value_sign helper correctly handles provably-negative constants (-5/y → Positive, x/-5 → Negative) and the test test_polarity_div_denominator_value_sign_guards_numerator_polarity covers the positive-constant variable case too.
  • reconstruct_single_variable fix: dispatching Variable::Module to reconstruct_implicit_variable (which uses build_module_inputs directly from the datamodel references) correctly bypasses the lower_variable path whose empty scope.models was dropping every module input.

The model_module_output_ports implicit-vars loop only iterating dt_deps (not initial_deps) mirrors the pre-existing db::ltm::loops::find_model_output_ports pattern, so it's a documented intentional reuse, not a regression.

Overall correctness verdict

Correct. 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-#[ignore]d test_module_output_multi_input_link_score_magnitude is now passing.

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.
@claude

claude Bot commented Jun 3, 2026

Copy link
Copy Markdown

Review summary

Reviewed the PR end-to-end. The changes are internally consistent and well-motivated:

  • Circuit budget (MAX_LTM_CIRCUITS = 100_000): correctly threaded through model_loop_circuits, model_loop_circuits_tiered, model_detected_loops, pinned-loop expansion, and model_ltm_mode. The new if tiered.truncated arm in model_ltm_variables precedes the empty-fast-and-slow-path check, avoiding the trap where truncation would be read as "no loops".
  • Module link score consolidation (module_link_score_equation): the single helper shared by link_score_equation_text and link_score_equation_text_shaped eliminates the prior twins drift hazard. The composite/ceteris-paribus/unit-transfer fallback ordering is sound; the variable → module arm's inputs.iter().find(|i| i.src == from_ident) exact-equality matches the parsed references. The module → module arm correctly uses normalize_module_ref because to's input src carries the qualified from·output.
  • Per-exit-port overrides (compute_module_link_overrides): the lexical sort relationship of ⁚viaacc⁚{exit}⁚{idx} < ⁚via⁚{exit} is correct (after via, a U+0061 < ⁚ U+205A), so the accumulator helpers evaluate before the alias. The pathway recomputation reuses the same salsa-cached sub_model_output_ports + model_causal_edges the sub-model's own emission uses, so pathway indices match index-for-index. The find_model_output_ports deterministic sort (GH ltm: multi-output-port module pathway/composite ordering is process-nondeterministic (unordered output-port set) #680) is a hard prerequisite and is in place.
  • Reconstruct fix in reconstruct_single_variable: explicit module instances now flow through reconstruct_implicit_variable, populating Variable::Module { inputs } so the link-score generators can match i.src == from_ident rather than silently falling through with inputs: [].
  • Polarity rules: the Mul both-sides arm now requires operand_positive_by_convention on both factors and matching derivative signs; the Div arm uses value_sign to handle provably-negative constants (-5/y Positive, x/-5 Negative). The quotient-rule both-sides case correctly requires opposing derivative signs.

End-to-end correctness is empirically pinned by the new module_to_module_isolated_loop_raw_score_is_one (Appendix B invariant across gains 0.5/1.0/2.0) and multi_output_passthrough_loop_raw_score_is_one (the reviewer's pos/neg counterexample).

I found no actionable bugs introduced by this PR worth flagging.

Overall correctness verdict

Correct. No findings.

@bpowers
bpowers merged commit af6436c into main Jun 3, 2026
12 of 13 checks passed
@bpowers
bpowers deleted the ltm-review-hardening branch June 3, 2026 02:19
bpowers added a commit that referenced this pull request Jun 4, 2026
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
bpowers added a commit that referenced this pull request Jun 10, 2026
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.
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.

ltm: black-box module link formula is a gain (dz/dx), not a link score

1 participant