Skip to content

LTM hardening: close out the top tracked gaps from epic #488 - #668

Merged
bpowers merged 15 commits into
mainfrom
ltm-gaps
Jun 2, 2026
Merged

bpowers merged 15 commits into
mainfrom
ltm-gaps

Conversation

@bpowers

@bpowers bpowers commented Jun 2, 2026

Copy link
Copy Markdown
Owner

Closes out the highest-priority gaps from the LTM tracking epic #488, one reviewed commit per gap. Every fix was implemented TDD-first by a dedicated agent and adversarially reviewed by a separate one (red-test verification against the parent commit, full pre-commit suite on every commit); review findings were folded back in as follow-up commits.

Correctness fixes (silent wrong results)

Diagnostics and UX

Determinism and ranking

Capability and robustness

Housekeeping

Related issue activity from this effort

bpowers added 14 commits June 1, 2026 17:49
The LTM ceteris-paribus partial-equation builders
(build_partial_equation_shaped / _with_live_ref and
subscript_idents_at_element) silently fell back to the lowercased input
text when Expr0::new returned Err or Ok(None). With no PREVIOUS() wrapping
applied, that "partial" is identical to the target's full equation, so the
link-score numerator (partial - PREVIOUS(target)) equals the denominator
(target - PREVIOUS(target)) and the score magnitude collapses to a constant
|Δz/Δz| = 1. Worse, that wrong equation compiles cleanly, so
model_ltm_fragment_diagnostics (which only catches *compile* failures) never
sees it -- a hidden attribution error rather than an explicit failure
(GH #311).

The fix makes the builders return a structured PartialEquationError carrying
the original equation text, and threads it through every link-score
generator (generate_link_score_equation_for_link, the aux-to-aux /
stock-to-flow / arrayed-per-element generators, and the agg-half emitters).
The db-bearing callers (link_score_equation_text,
link_score_equation_text_shaped, and the scalar->arrayed / agg->target
emitters in db/ltm) convert the error into a Warning naming the variable and
the offending equation text, and skip emitting that link-score variable --
the established "loud failure" pattern (cf.
emit_unscoreable_disjoint_edge_warning). Chose option (a) loud-skip over a
semantics-preserving fallback because any silent degradation here (even a
safe-zero partial) remains hidden, which is exactly the property the issue
calls out as dangerous.

The legitimate "parsed fine, no other deps to wrap" case (a constant, or the
live source alone) is unchanged: it still returns Ok with the re-printed
text, distinguishing it from the parse-failure path the bug blurred. The
parse failure is effectively unreachable through the production salsa path
(the equation text is always a print_eqn re-print, and an empty equation is
rejected as an EmptyEquation Error upstream before LTM augmentation runs), so
this is defense-in-depth for the unanticipated case -- which is why the
silent semantics-changing fallback was so hazardous. Builder-level failure is
tested directly (build_partial_equation_shaped_parse_error_is_err /
_empty_equation_is_err / _no_deps_to_wrap_is_ok,
subscript_idents_at_element_parse_error_is_err), the generator chain
end-to-end (generate_link_score_equation_for_link_empty_target_is_err /
_normal_target_is_ok), the db warning message contract
(test_ltm_partial_equation_warning_message_contract), and the actual salsa
accumulation through a db-bearing emitter
(test_ltm_partial_equation_warning_accumulates_via_salsa, which drives the
real .accumulate(db) path the six call sites share since the error-producing
production route is unreachable). The test module is split into the sibling
ltm_augment_tests.rs to keep ltm_augment.rs under the per-file line cap.
The 2023 Loops-That-Matter flow-to-stock link-score formula assumes Euler
integration: its numerator `PREVIOUS(flow) - PREVIOUS(PREVIOUS(flow))` aligns
to the causal interval that drove the stock change from t-1 to t only under the
Euler update `stock(t) = stock(t-1) + dt * flow(t-1)`. RK2/RK4 sub-step the
stock update, so that alignment breaks and the link scores become
mathematically meaningless. Non-Euler integration is genuinely honored at
runtime (the VM and wasm backends each have distinct RK2/RK4 stepping loops),
so before this change enabling LTM on an RK-integrated model produced
plausible-looking but wrong scores with nothing to flag it -- a
silent-correctness hazard. GH #486.

Because the wrong scores actually run (RK4 is honored, not parsed-and-ignored),
Error severity is the correct verdict, as the issue requested. The check fires
only when LTM is requested and the model has stocks (a stock-free model
produces no flow-to-stock scores), and the effective integration method is
resolved the same way assemble_simulation picks its Specs: a model's own
model_sim_specs override wins, else the project sim_specs.

The guard is enforced at two surfaces because the diagnostics path and the
sim-compile path are separate. model_ltm_variables accumulates an Error
diagnostic, so it reaches collect_all_diagnostics consumers (libsimlin
get_errors / patch validation, MCP and pysimlin analyze) via
model_all_diagnostics -> model_ltm_fragment_diagnostics, exactly the way the
auto-flip warning does. assemble_module additionally returns a hard Err so
compile_project_incremental (which simlin_sim_new and the wasm backend use, and
which does NOT read the diagnostic accumulator) fails cleanly with a readable
message naming the offending method and pointing the user to switch to Euler or
disable LTM, rather than building a sim that silently emits wrong scores. A
non-LTM run of the same model is unaffected -- both surfaces are gated on
ltm_enabled.

The existing mark2_mdl_compiles_with_ltm_enabled test asserted exactly the
silently-wrong behavior this fix removes (mark2.mdl declares RK4); it is
repurposed to assert the RK4 model is now cleanly rejected with the
Euler-assumption error and still compiles with LTM disabled.
When LTM auto-flips from exhaustive loop enumeration to discovery mode
(the model's causal-graph SCC exceeds MAX_LTM_SCC_NODES), the engine
accumulates a Warning -- but that warning, plus every other LTM-gated
diagnostic (synthetic-fragment compile failures, the GH #311 partial-
equation warnings, the GH #486 non-Euler Error), was unreachable through
simlin_project_get_errors. simlin_sim_new resets the salsa ltm_enabled
input to false right after compile (to avoid leaking it into patch
validation), so get_errors re-ran diagnostic collection with LTM
synthesis gated off by the `if project.ltm_enabled(db)` branch in
model_all_diagnostics. The whole LTM diagnostic pipeline was skipped and
the warnings were invisible (GH #466).

Fix per option 4 of the issue: latch a set-once `ltm_requested`
AtomicBool on SimlinProject the first time any simulation is created with
enable_ltm=true, and have simlin_project_get_errors transiently re-enable
ltm_enabled (via the existing pub(crate) LtmEnabledGuard) for the
duration of diagnostic collection iff that latch is set. This scopes the
LTM diagnostic cost to callers who asked for LTM at least once -- a
project that never requested LTM skips the toggle and pays no LTM
synthesis cost -- and adds no new FFI surface, the smallest change that
makes ALL LTM diagnostics from the most recent LTM-enabled compile
reachable.

Why option 4 over the alternatives: investigation confirmed all four
concerns the issue raised. (a) SimlinProject is the right home: an
AtomicBool is Sync and set-once-monotone, no mutex needed. (b) No
interleave with concurrent sim creation: the transient enable happens
under the db lock, the same lock simlin_sim_new holds for its own LTM
flag dance, so the two serialize and a partial LTM state is never
observed; LtmEnabledGuard restores the flag unconditionally on drop, even
on panic. (c) Salsa re-hits the memoized LTM synthesis after a
false->true toggle: measured a re-collection at ~2x faster than the cold
first compute on a 51-node-SCC fixture (revalidate, not recompute), so
get_errors stays cheap. (d) pysimlin's project.get_errors() routes
straight through simlin_project_get_errors and model.simulate(
enable_ltm=True) routes through simlin_sim_new(enable_ltm=true), so the
binding inherits the fix end to end with no pysimlin-side plumbing.

The existing engine test test_ltm_disabled_does_not_surface_auto_flip_
warning is renamed to test_ltm_disabled_gate_suppresses_auto_flip_warning
and its docstring rewritten to make explicit that it now pins the gate's
"off by default" half -- the mechanism the FFI fix relies on -- so the
original intent (never pay LTM cost when nobody asked for LTM) stays
machine-checkable, while the user-facing reachability is covered by the
new FFI and pysimlin tests.

Tests: libsimlin tests/errors.rs gains test_get_errors_surfaces_ltm_auto_
flip_warning_after_ltm_sim, test_get_errors_no_ltm_diagnostics_when_ltm_
never_requested, and test_get_errors_ltm_warning_survives_subsequent_non_
ltm_sim; pysimlin tests/test_ltm_mode_and_links.py gains the
TestLtmDiagnosticsThroughGetErrors class.
The GH #486 non-Euler rejection resolved the integration method per-model
(each model's `model_sim_specs` override else project specs) and applied it
per-module in `assemble_module` and per-model in `model_ltm_variables`. That
is the wrong granularity: a `CompiledSimulation` has exactly one
`Specs.method`, which `assemble_simulation` takes from the MAIN (root) model's
override else the project specs -- a submodel's own `model_sim_specs` is never
consulted by the VM.

The per-model resolution was wrong in both directions, each reachable from
real input (XMILE import populates per-model sim_specs):

- False negative (the silent #486 hazard): a stock-free main overriding to
  RK4 instantiates a submodel that holds the stock+flow feedback loop and has
  no override. The VM integrates everything under the main-governed RK4 and
  the submodel's flow-to-stock link score is produced and run -- yet the guard
  missed it because the submodel's method fell back to the project's Euler.
- False positive: a submodel overriding to RK4 under a Euler main. The VM runs
  Euler (main governs) and the scores are valid -- yet the compile failed.

Resolve the effective method once, exactly as `assemble_simulation` builds its
`Specs` (root override else project specs), and reject only when the assembled
sim actually produces flow-to-stock scores -- i.e. some instantiated model
(root or a transitively-instantiated submodule, per `enumerate_module_instances`)
has stocks. Unused model definitions are never instantiated, so their specs and
stocks are irrelevant. Checking the instantiated set against the single
main-governed method covers both directions.

The check now lives once in `assemble_simulation` and rides its `Err`, so it
reaches `simlin_sim_new`, `simlin_project_get_errors` (the `vm_error` channel
in `gather_error_details_with_db`, which compiles "main"), and the wasm
backend (`WasmGenError::Unsupported`). The per-model accumulator emission in
`model_ltm_variables` is removed: `model_all_diagnostics` has no main-model
context, so it cannot carry this main-governed diagnostic correctly, and the
per-model emission also duplicated the error once per instantiated model in the
`collect_all_diagnostics` path. Removing it fixes both the wrong-model
attribution and the duplication the review flagged.

References GH #486.
GH #466 follow-up. The original GH #466 fix latched an `ltm_requested`
flag on `SimlinProject` and had `simlin_project_get_errors` transiently
re-enable the salsa `ltm_enabled` input -- including the compile that
feeds the `vm_error` channel -- so the LTM diagnostic pipeline became
reachable. After the GH #486 follow-up (b443797) removed the per-model
non-Euler accumulator diagnostic, the non-Euler rejection rides ONLY the
`assemble_simulation` hard `Err`. Compiling with LTM enabled in
`get_errors` therefore landed that `Err` in `vm_error`, so a model that
uses RK4 and simulates fine without LTM -- after a single default
`pysimlin model.run()` (which tries `enable_ltm=True`, fails, and degrades
gracefully) -- reported the non-Euler rejection as a project error. The
natural "load RK4 model -> run() -> check()" workflow flagged a fine model
as broken purely from run history.

Part 1: LTM is an analysis overlay, not part of a project's intrinsic
compilability. `simlin_project_get_errors` now computes the compile/VM
channel with LTM OFF (as pre-#466), and uses the latched transient
re-enable ONLY to harvest the additional LTM diagnostics via
`collect_all_diagnostics`. Those diagnostics (auto-flip-to-discovery
advisory, synthetic-fragment compile failures, the GH #311 partial-
equation warnings) accumulate through `model_all_diagnostics` ->
`model_ltm_variables` independent of whether the LTM-enabled assembly
would succeed, so they still surface for a model whose LTM assembly is
rejected (verified: an RK4 auto-flip model still emits the advisory).
Salsa memoizes both flag states, so the off-then-on pass is the cheap
revalidation case.

Part 2: severity through the FFI. `SimlinErrorDetail` gained a `severity`
field (`SimlinErrorSeverity { Error, Warning }`), threaded from the engine
`Diagnostic.severity` (the `vm_error`/compile-failure detail defaults to
`Error`). simlin.h is regenerated. pysimlin's `ErrorDetail`/`check()` and
the TS engine's `readErrorDetail`/`check()` map it, so the LTM auto-flip
advisory presents as a warning rather than claiming the model is broken.
Breaking the C struct is fine in this monorepo (no external FFI users);
the wasm32 struct grows 28 -> 32 bytes (the trailing pad already reserved
it), and the engine's struct-offset/size test is updated accordingly.

References GH #466.
compute_rel_loop_scores and compute_rel_loop_scores_per_element normalize
each loop's relative score against a per-cycle-partition denominator: the
sum of |loop_score_j| over the loops sharing that partition (or
(partition, slot) bucket) at each step. The sum was taken with a raw
.abs(), so a single loop whose loop_score was NaN at a step turned the
whole partition's denominator into NaN. The SAFEDIV-0 guard (denom == 0.0)
does not fire on NaN (NaN == 0.0 is false), so every loop in that partition
got num / NaN == NaN -- one bad loop poisoned every sibling's relative
score. The two streaming FFI helpers (compute_partition_denominator and
compute_partition_denominator_for_element) shared the structure and had to
stay bit-identical to the full-sweep helpers, so they had the same bug.

The fix routes every partition-sum summand through a new denom_summand
helper that excludes NaN (treats it as a non-contributing 0) while keeping
+/-Inf. The two semantics are chosen deliberately:

- NaN: a NaN loop_score means that one loop's score is undefined at that
  step -- not signal. Excluding it lets healthy siblings normalize against
  the healthy denominator, and the bad loop's own numerator stays NaN so
  its own relative score stays NaN (the honest per-loop "undefined here"
  signal). This matches the discovery path's philosophy, where
  ltm_finding::SearchGraph::from_edges coerces a NaN link score to a
  non-contributing 0 -- so the two LTM paths now agree on NaN handling.

- Inf: a raw loop score legitimately diverges at a dominance inflection
  (the link-score denominators go to zero there), so an Inf summand is real
  signal that the loop dominates. It is kept in the sum, which sends the
  dominated siblings to 0 (finite/Inf) and the dominant loop to NaN
  (Inf/Inf) -- the same inflection-point behavior the removed synthetic
  SAFEDIV equation produced. Filtering Inf (via is_finite) would instead
  hide the dominance and hand the dominant loop an out-of-range Inf
  relative score, so only NaN is filtered.

The earlier "non-finite values propagate through IEEE-754, matching the
removed SAFEDIV equation" rustdoc framed the propagation as intentional; it
only meant the post-simulation refactor preserved the removed synthetic
equation's semantics bug-for-bug. The removed SAFEDIV never promised
NaN-resilience either. The rustdoc on both functions (and the streaming
helpers) is updated to describe the chosen NaN/Inf semantics.

The proptest equivalence generators are finite-only, so they never
exercised the NaN path and did not pin the old semantics; the two reference
oracles are still updated to re-derive the same NaN-exclusion rule inline
(independently of denom_summand) so they stay correct if a future generator
introduces non-finite samples.

GH #542
assign_loop_ids derived a loop's r/b/u id from a single sort key -- the
deduped, sorted SET of variables in the cycle. Two distinct directed
cycles over the same node set (multidigraph siblings a->b->c->a and
a->c->b->a, retained as separate loops since the GH #308/#494 canonical
edge-sequence dedup) collapse to the same set key, so the stable-sort
fallback preserved whatever order Johnson's enumerator (and ultimately
HashMap iteration in IndexedGraph::from_edges) emitted them in. That
order is deterministic within a process but per-process-randomized
across processes, because Rust's DefaultHasher reseeds each process. So
the same model could assign r3 to the forward sibling in one run and to
the reverse sibling in the next, flapping the loop ids that persisted UI
state, loop pinning (SetLoopName/LoopMetadata), and deterministic tests
key on.

Extend the sort key with a secondary tiebreaker: the canonical cyclic
rotation of the loop's directed edge sequence (canonical_rotation over
each link.from). This is the exact key the find_loops_with_limit dedup
already guarantees is unique per loop -- raw link.from, not the stripped
variable name, so it also distinguishes per-element cross-element loops
on arrayed models. Siblings differ on it, so it fully orders any tied
group and makes id assignment a pure function of loop content.

The PRIMARY key (deduped variable set) is unchanged and stays the
leading tuple component, so a model whose loops all have distinct
variable sets -- the common single-direction case -- keeps its existing
numbering bit-for-bit and no ids churn. The discovery path's twin
assign_loop_ids in ltm_finding.rs carried the same set-only key and the
same latent sibling-tie hazard (its FoundLoop list arrives in score then
DFS order, which ties when two siblings share a score); it gets the same
tiebreaker. The element-level/tiered builders and model_detected_loops
route through graph::assign_loop_ids, so they inherit the fix; pinned
loops use declaration-index pin{n} ids and were never affected.

Tests: a structural-path order-independence test feeds the K3
multidigraph sibling pair to assign_loop_ids in several input orders and
asserts each directed cycle keeps the same id (verified red against the
set-only key); a focused test pins the rule (the lex-smaller canonical
edge sequence gets the lower id index); a discovery-path twin; and an
end-to-end arms-race fixture through model_detected_loops.

GH #497
rank_and_filter previously sorted, truncated to MAX_LOOPS, and re-sorted
discovered loops by raw avg_abs_score -- an ABSOLUTE magnitude. LTM
importance is partition-relative: a loop matters in proportion to its
contribution within its OWN cycle partition (the relative loop score,
ref 4.4). Raw-magnitude ranking biased the selection toward whichever
partition had the largest-magnitude scores, so a non-dominant loop in a
high-activity partition outranked (and could displace from the cap) a
partition-dominant loop in a low-activity partition. The truncate ran
BEFORE the partition-aware MIN_CONTRIBUTION filter, so a loop dominant in
a small partition but globally below rank 200 was dropped before the
partition scope ever saw it.

New pipeline: compute per-partition per-timestep totals over ALL
discovered loops -> apply the partition-aware MIN_CONTRIBUTION retention
filter (peak semantics, unchanged) BEFORE any global cap -> rank by the
partition-relative key -> truncate to MAX_LOOPS -> assign IDs (the
assigner is order-independent, commit 1539329) -> final caller-facing
order is the relative-importance ranking.

Ranking key (mean vs peak): the retention filter keeps its PEAK relative
contribution -- "did this loop ever matter?" The ranking key is the MEAN
magnitude of the relative loop score over the steps where the loop is
active -- "how important overall?" The mean is the literature's
loop-inclusion measure ("average magnitude of the relative loop score
across the simulation period"; docs/reference 13.3). Active-step (delayed)
averaging skips steps where the partition total is 0 (no loop active) or
the loop's own score is NaN, rather than counting them as 0 -- counting an
inactive step as 0 would penalize a sharply-but-briefly dominant loop
(exactly the loop the peak retention filter exists to keep). A loop with
no active steps gets NaN and sorts last, never displacing a real loop.

NaN/Inf handling mirrors ltm_post.rs::denom_summand (commit 58a5667, GH
#542) so the two LTM paths agree: a NaN score contributes nothing to a
partition total and that step drops out of the loop's own mean; an Inf
score stays in the partition total (a real dominance-inflection signal),
so the loop's own Inf/Inf=NaN step drops out and dominated siblings see a
finite/Inf=0 contribution. Loops with no parent-level partition (a pure
module-internal loop) map to the None partition key and group with their
peers like any other key.

Tie-breaking for equal relative keys is content-based -- the canonical
edge-sequence sort key from commit 1539329 -- never input order, so the
retained set, assigned IDs, and final ordering are invariant under input
permutation.

FoundLoop.avg_abs_score is retained: no consumer ranks on it (analysis.rs
reads the Vec order and per-step scores; libsimlin/pysimlin/MCP surface
that order), but integration tests assert it is finite/positive. The
caller-facing ORDERING changes by design.

GH #543, GH #310
CausalGraph::enumerate_module_pathways enumerated every internal
input->output simple path with a depth cap but no cap on the path COUNT.
Simple-path count is exponential in graph size: a module body shaped as a
chain of N diamonds has 2^N short paths that never trip the depth cap.
Each pathway mints one $⁚ltm⁚path⁚{input}⁚{idx} synthetic variable and
folds into the input port's composite link score, so the pathway count is
model-controlled and unbounded -- an adversarial or accidentally-dense
module body could mint exponentially many synthetic vars and OOM (GH #649).

The fix bounds the WORK, not just the result: the DFS stops emitting once
the per-port completed-path budget is reached AND aborts once a per-call
expansion allowance is exhausted. The expansion allowance is budget *
max_depth -- exactly the worst-case descent count to complete `budget`
paths in a dead-end-free graph (the tightest such case is `budget`
prefix-disjoint chains of length max_depth), so a legitimate enumeration
is never starved by the work cap while an exponential dead-end frontier
(subgraphs with no path to the output) still aborts in O(budget *
max_depth) expansions rather than 2^N. A dedicated test pins the
non-starving boundary at budget == path-count.

Truncation is deterministic: the DFS sorts each node's neighbor list
before walking, so the kept pathway prefix is a function of the graph's
node identities alone, reproducible across runs and processes regardless
of how the adjacency vector was constructed. The composite max-abs fold is
commutative, so a truncated port's composite degrades to the max over the
kept prefix -- never a panic or a silent zero. A CompilationDiagnostic
Warning names the module and clipped input port(s), and a robust
pathways_truncated flag rides out on LtmVariablesResult (mirroring the
#515 agg_recovery_truncated plumbing). enrich_with_module_stocks degrades
a truncated port to its existing "all module-internal stocks" fallback
rather than collecting stocks from only the kept prefix, so no stock is
silently lost.

Budget value: MAX_MODULE_PATHWAYS = 8192. This is defense-in-depth against
exponential blowup, not a tight performance cap, so it is set comfortably
above the legitimate in-repo corpus maximum. Measured on
covid19-us-homer: the SSTATS macro module produces 303 pathways through
its busiest input port via the production composite path, and the covid19
root model's enrich_with_module_stocks enumeration peaks at 6744 simple
pathways from one node. 8192 clears both with headroom while still
tripping long before a true blowup (a 14-diamond chain already exceeds
it). Verified SSTATS does not truncate at the production budget. The
test-only ModulePathwayBudgetGuard (the AggLoopBudgetGuard pattern) lets
the tests trip the budget with tiny fixtures.
Sim.get_links() returned only each link's RAW LTM link-score series. The
raw score divides by the change in the link's TARGET variable, so links
into near-constant variables (parameters, equilibria) produce
astronomically large scores -- ranking links by |average raw score| to
find "the most important links" surfaces these numerically degenerate
links instead of meaningful ones (the GH #652 observation: top links at
6.4e22 / 1.1e16 between near-constant policy variables). Raw link scores
are not comparable across different targets.

This adds the relative link score: for each target, normalize a link's
score by the per-timestep sum of |score| over all of that target's
scored inputs (LTM ref 13.3/13.12; Schoenberg 2020 section 4). The
result is in [-1, 1] and IS comparable across the model -- the fraction
of the target's change attributable to that input.

The computation lands in the shared, backend-agnostic core:
engine::ltm_post::compute_rel_link_scores (a pure function, unit-tested)
is called by libsimlin's analyze_links_core via attach_relative_scores,
so BOTH the VM path (simlin_analyze_get_links) and the wasm path
(simlin_analyze_links_from_wasm_results) get it through the one core the
wasm-LTM work funneled them through -- they cannot diverge (AC5.1). It
runs over the final, post-synthetic-collapse link set so the per-target
denominator matches the links the caller receives.

Sign convention: signed, kept in [-1, 1] (the literature's [0, 1]
phrasing is about magnitude), consistent with rel_loop_score keeping
polarity -- the sign tells a reader whether the input pushes the target
up or down. NaN/Inf semantics reuse the established denom_summand rules
(GH #542): a NaN summand is excluded from the per-target sum so one
undefined input does not poison its siblings; Inf is retained (a
diverging input dominates, sending finite siblings to 0 and itself to
NaN via Inf/Inf); a 0 denominator yields 0 (SAFEDIV-0).

Denominator scope is the scored inputs only. In discovery mode every
causal edge is scored, so the denominator is the complete input set and
the relative score is exactly "fraction of the target's change
attributable to this input". In exhaustive mode only in-loop edges carry
score series, so a target with some inputs outside loops normalizes over
just the scored subset -- a slight overstatement of each link's share,
documented as a caveat on the function rather than papered over with
invented zero series.

FFI: SimlinLink grows two additive fields (relative_score /
relative_score_len), populated exactly when the raw score is. The links
payload is a C struct, not a protobuf, so this is a pure ABI-additive
change (28 bytes on wasm32); simlin_sizeof_link and the @simlin/engine
LINK_SIZE/readLinks offsets track it. get_links is on-demand analysis,
not a hot path, so doubling the series payload is acceptable (the issue
accepts series).

pysimlin Link gains relative_score (numpy series) and
average_relative_score(); average_score()/max_score() docstrings now
WARN that raw scores are not comparable across targets and point at the
relative score for ranking. The TS @simlin/engine Link gains relativeScore
through the same readLinks/convertLinks plumbing.

GH #652
The dynamic-subscript arm of `walk_expr_as_view` (the path a wrapping
array reducer like `SUM(arr[i])` takes) walked each index expression
with `walk_expr(...).unwrap().unwrap()`, so a recoverable lowering Err in
an index expression became a process-killing panic.

A valid arrayed model under LTM hits this: the GH #525 reference
classifier marks a partially-iterated subscript (`pop[region,young]`
inside `row_sum[region]`) as `DynamicIndex`, the ceteris-paribus partial
wraps it as `PREVIOUS(SUM(pop[region,young]))`, and inside the SUM
reducer's view-index walk that inner `PREVIOUS` survives helper
rewriting as a non-variable expression and lowers to the clean
`NotSimulatable` the `BuiltinFn::Previous` arm emits. The double-unwrap
turned that typed Err into a panic at the index walk, defeating the LTM
assemble path's `Err(_) => None` graceful-stub handler
(`db/ltm/compile.rs`'s `module.compile()` match) -- whose whole design
depends on the error propagating so the un-compilable synthetic fragment
is dropped and the variable stubs to a constant 0.

Convert the two index-walk sites (and audit the sibling double-unwraps:
`SafeDiv`'s optional third arg and `EvalModule`'s input args, both of
which walk user-derived expressions that can carry the same recoverable
failure) to propagate the Result via `?`. The Option unwrap stays a hard
unwrap: an index/operand that lowered to no value-producing opcode is a
genuine compiler invariant violation (only `EvalModule` or a
non-iteration `TempArray`), never reachable from a real subscript index.

This fixes the CRASH, not GH #525's mis-classification root cause. With
the fix the model compiles and simulates, with the offending link score
gracefully stubbed to 0 plus the existing fragment-failure Warning -- the
graceful-degradation contract a new test now pins (the repo lacked one).
The constant-0/Warning assertions are marked as pinning the current
DEGRADED #525 behavior that #525's future classifier fix will improve.
A plain apply-to-all equation that nests PREVIOUS around a bare arrayed
name -- `p2bare[region] = PREVIOUS(PREVIOUS(pop))` with `pop[region]`
arrayed -- failed to compile (NotSimulatable). The inner `PREVIOUS(pop)`
is an expression argument, so `make_temp_arg` in builtins_visitor.rs
captured it into a synthesized helper aux whose equation was
`Equation::Scalar("previous(pop, 0)")` -- a bare arrayed name in a scalar
equation is ill-typed, so the helper fragment failed and the whole model
was rejected. The explicitly subscripted form and a single (non-nested)
bare PREVIOUS both compiled; only the nested-bare form failed (GH #541).

Fix (the issue's option (b), generalized): in A2A context, when the
captured PREVIOUS/INIT argument carries a bare variable reference,
`make_temp_arg` now synthesizes an *arrayed* helper -- an
`Equation::ApplyToAll` over the active apply-to-all dimensions holding the
un-substituted argument -- and returns a per-element subscript reference
`helper[<element>]` instead of the bare helper name. The bare arrayed name
keeps its array shape, and dimension matching (including transposed and
multi-dimensional contexts) is delegated to the existing apply-to-all
lowering, which matches by dimension name rather than position. This is
chosen over synthesizing one arrayed helper text per call (option (a)'s
literal form) because the visitor has no variable->dimensions map -- the
per-variable parse path withholds the model name set for salsa
incrementality -- so it cannot know whether a bare name is arrayed; an
arrayed helper broadcasts a scalar reference cleanly too, making the
conservative "treat any surviving bare reference as possibly-arrayed"
choice correct in every case. A bare arrayed name in a *scalar* equation
(no active subscript) keeps the scalar-helper path and still errors
cleanly, as it should.

The arrayed helper carries no per-element name suffix, so every element
of the enclosing apply-to-all produces the identical helper;
`instantiate_implicit_modules` deduplicates them to one. Supporting an
arrayed implicit helper end-to-end also required teaching the layout the
helper's real size: `model_implicit_var_info` now records each implicit
helper's dimensions/element-count (it was hardcoded scalar), the
implicit-var compiler sizes its own mini-layout slot from that count
(a wrong size spilled per-element writes into neighboring variables'
slots), and the dependency-stub builders (both the source-var and
implicit-var paths) give an arrayed-helper dependency a dummy
`ApplyToAll` AST so a `helper[<elem>]` reference resolves instead of being
rejected as a subscript on a scalar.

The prior characterization tripwire is flipped into a positive regression
test asserting per-element equivalence with the subscripted form, plus
multi-dimensional and transposed-context variants. The LTM flow-to-stock
generator-side workaround (commit 8853e8d) is retained with a note that
this engine-level fix now supersedes it: it is pinned by dedicated tests
and re-baselining every arrayed flow-to-stock link score's equation text
would be a broad change with no behavioral benefit. GH #541.
Reviewer-identified accuracy fixes accumulated during the LTM-hardening
session; no behavior change beyond un-ignoring a now-tractable test.

- ltm_discovery_large_models: the discovery rewrite (081e984) made World3
  discovery tractable and GH #540 is closed, so the module docs / FIXMEs
  no longer describe pre-fix intractability (390s/22GB). Un-ignore
  world3_discovery_single_timestep: measured ~0.6s end to end on a debug
  build (discovery itself ~20ms), comfortably within the per-test budget.
  Replaced the leaked-worker/RSS-ceiling timeout machinery (which existed
  solely to bound a runaway) with a direct call plus a generous wall-clock
  regression guard, and refreshed the sibling-test docs.
- ltm_post: softened the GH #542 rustdoc. The NaN loop's own relative
  score stays NaN only while a healthy sibling keeps the denominator
  non-zero; when the NaN loop is the partition's sole contributor (or all
  members are NaN at a step) the denominator collapses to 0.0 and the
  SAFEDIV-0 guard yields 0.0 (the lone-pin degeneracy path).
- ltm_finding: documented in rank_and_filter that relative-importance
  means are taken over each loop's own active-step set, so a loop dominant
  in a briefly-active partition ties one dominant in an always-active
  partition by design.
- simulate_ltm_wasm: fixed the stale rationale for excluding Loop.id from
  the parity identity key. Ids are now content-determined (canonical
  edge-sequence tiebreak, 1539329) with partition-relative ranking, but
  the assigned counter is still a whole-set property, so the exclusion
  conclusion stands.
- ltm_finding: cold-path assign_loop_ids now uses sort_by_cached_key
  matching the graph.rs twin instead of recomputing the allocating key per
  comparison.
- ltm/graph: scoped the work-bound no-starvation guarantee to
  dead-end-free graphs and documented that a mixed graph can exhaust the
  allowance and return fewer (down to zero) paths, correctly flagged as
  truncated with a Warning (safe degradation).
Commit 1736f9a (GH #541) made `make_temp_arg` synthesize an arrayed
`Equation::ApplyToAll` helper whenever an A2A `PREVIOUS`/`INIT` argument
carried a bare variable reference, skipping the per-element
`substitute_dimension_refs` translation. That regressed C-LEARN
compilation -- including the plain non-LTM compile -- which went unnoticed
because every C-LEARN test is `#[ignore]`d and the pre-commit hook runs
none.

C-LEARN's dominant idiom is an A2A `INITIAL` whose argument subscripts
other arrays by dimensions that MAP to the active dimension
(`FF change start year[COP] = INITIAL(IF THEN ELSE(...,
ff_change_start_year_aggregated[Aggregated Regions], ...))`, where
`Aggregated Regions` maps to `COP`). The arrayed helper held that body
un-substituted, so the foreign `[Aggregated Regions]` subscript stayed a
dimension name ill-typed in an `ApplyToAll` over `COP`, the helper
fragment failed to compile (`BadDimensionName`), and the assemble path
silently dropped it, surfacing as `NotSimulatable`.

Three fixes, narrowing the arrayed path to exactly the shape that needs
it and correcting two latent name-resolution bugs it exposed:

1. Dispatch (`builtins_visitor.rs`): the arrayed-helper path now fires
   only when the argument has a bare variable reference AND NO subscript
   at all. The sole shape that genuinely needs it is a bare arrayed name
   (`PREVIOUS(PREVIOUS(pop))`); any subscripted argument -- active-dim,
   mapped-dim, or literal-element -- keeps the proven pre-#541 per-element
   scalar-helper path, which translates each subscript to a concrete
   element. This also stops the path from corrupting LTM link-score
   numerators: a bare arrayed name inside an array reducer
   (`PREVIOUS(SUM(arr))`) is collapsed to a scalar by the reducer, so
   `arg_has_bare_var_ref` no longer descends into `SUM`/`MEAN`/`MIN`/
   `MAX`/`STDDEV`/`RANK`/`SIZE`; wrapping `SUM(arr)` in an `ApplyToAll`
   broadcast a scalar reduce across the active dims and made the LTM run
   diverge from plain on C-LEARN's HFC variables.

2. `variable::get_dimensions` now matches dimension names CANONICALLY
   rather than by raw `==`. The arrayed helper's `Equation::ApplyToAll`
   dims come from `print_eqn` (canonical, `hfc_type`) and must resolve
   against a dimension declared with original casing (`HFC type` ->
   `HFC_type`); raw equality rejected it as `BadDimensionName`. A
   dimension's identity is its canonical name (the dims map is keyed by
   it), and importer equations already match exactly, so this is a strict
   superset.

3. `model_implicit_var_info`'s arrayed-helper size computation matches
   the helper's canonical dim names against the project dims canonically
   too; a raw miss fell back to size 1 and corrupted the layout.

Adds regression tests (the C-LEARN mapped-dimension INITIAL idiom via an
MDL-imported fixture, a capitalized-dimension arrayed helper, and the
bare-name-inside-reducer scalar-helper contract) plus the previously
missing coverage gap. All three `#[ignore]`d C-LEARN tests
(`compiles_and_runs_clearn_structural`, `clearn_ltm_discovery_compiles`,
`clearn_with_ltm_simulates_model_vars_identically`) verified passing in
debug. GH #541.

@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: 206f8b932d

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

// and hold the *un-substituted* argument so bare arrayed names stay
// arrayed and a subscripted reference (`arr[Dim]`) broadcasts over
// the helper's own dimensions instead of being frozen to one element.
let id = format!("$⁚{}⁚{}⁚arg0", self.variable_name, self.n);

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 Preserve per-slot helper identity

When this branch runs from the Ast::Arrayed per-element path, each slot gets a fresh BuiltinVisitor with self.n starting at 0, so omitting the active element from the helper id makes distinct slot equations collide. For example, two arrayed slots like PREVIOUS(PREVIOUS(a)) and PREVIOUS(PREVIOUS(b)) both synthesize $⁚x⁚0⁚arg0; the later dedup_vars_by_ident(all_vars) in the arrayed branch keeps only one helper, and both slots then read the same captured source, silently corrupting valid per-element arrayed equations.

Useful? React with 👍 / 👎.

@claude

claude Bot commented Jun 2, 2026

Copy link
Copy Markdown

Code Review (claude-opus-4-7)

Reviewed the 14 commits / ~14.5k lines of diff focused on the eight gap closures called out in the PR description. The work is unusually disciplined: each fix has dedicated regression tests, the FFI ABI growth is pinned by cross-language size checks, and the WHY-vs-WHAT comments make the rationale auditable.

What was verified end-to-end

Minor observations (not blockers)

  • validateStructSizes (analysis.ts:307-324) checks loop/link/ptr but not errorDetailSize. The size is pinned by the integration test (integration.test.ts:528), so coverage exists at test time, but production code wouldn't catch a future ABI drift on SimlinErrorDetail. Pre-existing pattern — not introduced here.
  • ltm_requested (simulation.rs:79-83) latches true BEFORE compilation succeeds. If enable_ltm=true is passed but compile fails for an unrelated reason, the latch is still set and subsequent get_errors calls pay the LTM diagnostic re-enable cost. Probably intentional (the caller did request LTM), but a "set-on-success" alternative would avoid the cost in that edge case.
  • compute_rel_link_scores (ltm_post.rs:259-312) zero-pads a numerator shorter than step_count via series.get(t).copied().unwrap_or(0.0). The doc says "never happens in production"; this is a silent pad rather than an assertion, which could mask a future invariant break. Consider debug_assert_eq!(series.len(), step_count) so a regression surfaces in tests.

Overall correctness verdict

Correct. I did not identify any blocking bugs across the eight categories I audited. The fixes target real silent-wrong-result hazards (#311, #486, #542, #525) with loud-failure replacements and tests that pin the new contract; the determinism (#497) and ranking (#543/#310) fixes are content-keyed rather than enumeration-order-dependent; the pathway budget (#649) has both work and result caps with deterministic truncation. The PR is ready to land.

GH #541's arrayed-helper path (`make_temp_arg` synthesizing an
`Equation::ApplyToAll` helper for a bare arrayed `PREVIOUS`/`INIT`
argument) named that helper without an element suffix: `$⁚{var}⁚{n}⁚arg0`.
That is correct for the `Ast::ApplyToAll` per-element expansion -- every
slot walks the SAME cloned body, so all N helpers are byte-identical and
`dedup_vars_by_ident` collapses them to one. But the `Ast::Arrayed`
per-element expansion walks a DIFFERENT equation per slot through a fresh
`BuiltinVisitor` (so `n` restarts at 0 and `variable_name` is shared), so
two slots whose equations differ both synthesized `$⁚{var}⁚0⁚arg0` with
DIFFERENT `ApplyToAll` bodies. `dedup_vars_by_ident` kept the first
occurrence -- its "identical by construction" claim held only for the
ApplyToAll path -- so a later slot silently read an earlier slot's helper:
wrong values on a valid model, no error (PR #668, codex r3341582353).
Example: `x[e1] = PREVIOUS(PREVIOUS(a))`, `x[e2] = PREVIOUS(PREVIOUS(b))`
with `a`, `b` distinct scalars made `x[e2]` track `a`. Pre-#541 scalar
helpers carried the element suffix (`...⁚arg0⁚{elem}`), preserving per-slot
identity; the suffix-less arrayed helper broke that invariant for the
Arrayed path.

Two fixes:

1. Per-slot identity: a new `per_element_equation` flag on
   `BuiltinVisitor`, set ONLY by the `Ast::Arrayed` per-element expansion
   (NOT by its `default_expr` visitor, which uses `::new`, has no active
   subscript, and never reaches the arrayed-helper branch). When set, the
   arrayed helper appends the slot's element suffix, exactly like the
   scalar helpers, so distinct slots get distinct helpers. The
   `Ast::ApplyToAll` path is unchanged (suffix-less shared helper +
   dedup), where the identical-by-construction guarantee genuinely holds.
   Cost: N arrayed helpers for an N-slot variable using this construct --
   correct beats compact; the downstream plumbing
   (`model_implicit_var_info` dims/size, dep stubs, layout) keys on the
   recorded dims and handles a suffixed `ApplyToAll` helper unchanged.

2. Hardening: `dedup_vars_by_ident` now compares colliding entries and
   returns a loud `Generic` error on a same-ident-DIFFERENT-content
   collision instead of silently keeping the first. This converts any
   future regression of this class from silent corruption into a clean
   compile failure -- the lesson from this corruption being invisible.

Adds TDD regression tests: the per-slot collision repro
(`PREVIOUS(PREVIOUS(a))`/`(b)` distinct scalars -- RED at HEAD), the bare
arrayed variant matching the subscripted form per slot, the same-body
no-regression pin, the INIT twin, and a `dedup_vars_by_ident`
conflicting-collision unit test. All three `#[ignore]`d C-LEARN tests
verified passing in debug. GH #541, PR #668.
@bpowers

bpowers commented Jun 2, 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 2, 2026

Copy link
Copy Markdown

Code review

This PR closes a substantial portion of the LTM tracking epic (#488) and contains tightly-scoped, well-documented fixes for correctness, determinism, diagnostics, and robustness. The TDD-first commits, the extensive doc-comments explaining why each invariant holds, and the new test coverage (per-NaN handling, partition-relative ranking, sibling-cycle id determinism, module-pathway budget, GH 486 RK4 gating, GH 466 latch survival, wasm/VM parity for relative scores) are exemplary.

I did a careful read of the highest-risk areas:

  • compute_rel_link_scores (src/simlin-engine/src/ltm_post.rs): per-target denominator construction is order-deterministic (BTreeMap iteration + stable index push), the ? short-circuit on unscored links is sound, NaN/Inf semantics are documented and consistent with denom_summand, and the wasm/VM parity test (links_from_wasm_match_vm) covers the new column.
  • rank_and_filter + rank_truncate_and_id (src/simlin-engine/src/ltm_finding.rs): the filter-before-truncate order (GH 310) is correct, the relative-importance key is computed over the full discovered set (so partition totals reflect the whole partition), and cmp_relative_importance sinks NaN deterministically.
  • dedup_vars_by_ident (src/simlin-engine/src/builtins_visitor.rs): the byte-identical-vs-conflict distinction is the right invariant for the suffix-less-helper vs per-element-arrayed distinction, and the loud Generic error on a conflicting same-id collision is the correct response (rather than silent keep-first).
  • GH 486 non-Euler guard in assemble_simulation: the method is resolved once against the main-model-governed Specs.method (not per-submodel), and the any_stocks check covers root-or-transitively-instantiated stocks. The accompanying decision to not compute vm_error with LTM on in simlin_project_get_errors (so RK4 + LTM does not masquerade as a project error) is well-explained and tested (test_get_errors_rk4_ltm_compile_failure_is_not_a_project_error).
  • ltm_requested latch + LtmEnabledGuard transient re-enable (src/libsimlin/src/project.rs, src/libsimlin/src/lib.rs): correctly serialized against simlin_sim_new's flag dance via the db lock; the Acquire/Release atomic + db lock combo is conservative but correct.
  • get_dimensions canonical match (src/simlin-engine/src/variable.rs): only applied where it's needed (matching against datamodel::Dimension which keeps original casing); the parallel callsites in var_fragment.rs/fragment_compile.rs use crate::dimensions::Dimension whose name() already returns canonical, so raw == remains correct there.
  • module_pathway_budget (src/simlin-engine/src/ltm/graph.rs): the budget * max_depth work bound's no-starvation property for dead-end-free graphs is explained and pinned by a property test; the truncation-aware enrich_with_module_stocks falls back to "all internal stocks" rather than silently dropping stocks (the conservative direction).
  • loop_id_sort_key secondary key (src/simlin-engine/src/ltm/graph.rs + src/simlin-engine/src/ltm_finding.rs): mirrored on both id-assignment sites; single-direction loops keep bit-identical numbering because the primary set-based key already totally orders them.
  • codegen.rs ? propagation: every fixed unwrap is the right call (a PREVIOUS-of-non-var inside a View subscript index lowers to NotSimulatable, which the LTM assemble path's Err(_) => None handler reads as a graceful stub), and the new test covers the array-view twin.

I did not find a discrete, actionable bug that meets the flagging threshold. All the patterns I dug into (float-summation order, NaN/Inf semantics in denominators, salsa input flip ordering, ident-collision handling, dim-name canonicalization, FFI ownership of the new relative_score array, salsa accumulator emission on the partial-equation error path) check out against their accompanying invariants and tests.

Overall correctness verdict: CORRECT

The patch is large but each commit is tightly scoped, well-tested (including red-test verification against the parent commit per the PR description), and the documentation in code is unusually thorough -- the kind that makes the why of each invariant auditable. The remaining open items (GH 525 mis-scoring root cause, GH 528 strict-prefix broadcast, the mapped-dim sliced-reducer hoist carve-out) are explicitly carried in comments and the epic's followups rather than papered over.

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-augment: parse fallback can silently break ceteris-paribus logic

1 participant