Repository navigation
engine: enable LTM always-on via auto-flip + post-sim rel_loop_score - #461
Conversation
7dd299e to
577dbce
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 577dbce230
ℹ️ 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".
| } else { | ||
| }; | ||
|
|
||
| let ltm = engine::db::model_ltm_variables(&*db_locked, synced_model.source, sync.project); |
There was a problem hiding this comment.
Derive loop partitions from simulation snapshot
simlin_analyze_get_relative_loop_score now recomputes loop_partitions from the current project DB state (model_ltm_variables) instead of using the model snapshot that produced sim_ref.state.results. If the project is patched after creating/running a simulation (an explicitly supported snapshot-isolation workflow in src/libsimlin/tests/incremental.rs), this mixes old loop_score series with new partition membership and can silently return wrong relative scores or DoesNotExist for previously valid loop IDs.
Useful? React with 👍 / 👎.
| return; | ||
| }; | ||
|
|
||
| let scored = engine::ltm_post::compute_rel_loop_scores(results, <m.loop_partitions); |
There was a problem hiding this comment.
Avoid recomputing all relative scores per API call
This call computes relative scores for every loop on each single-loop request, then discards all but one series. Higher-level callers iterate this API per loop (for example, _populate_loop_behavior in src/pysimlin/simlin/run.py), so total cost becomes quadratic in loop count (O(num_loops^2 * steps)) instead of the previous per-loop linear read from precomputed data, which can significantly slow LTM analysis on models with many loops.
Useful? React with 👍 / 👎.
Code review[P2]
|
ReviewOverall the patch looks correct and the design trade-offs (cap removal, post-sim normalization, auto-flip on largest SCC, cached Findings[P3] [P3] VerdictCorrect. No blocking issues — the two P3 items above are worth considering but neither gates the merge. |
|
Reviewed the full diff (engine, libsimlin FFI, layout, tests, docs). Traced the two auto-flip gates (element-level SCC in No P0/P1/P2/P3 findings. The changes are well-covered by the 45 integration tests in overall correctness: correct |
Adds set_max_ltm_circuits/default_max_ltm_circuits public fns backed by an atomic so diagnostic harnesses can sweep the LTM circuit budget without rebuilding the documented MAX_LTM_CIRCUITS constant. The default-budget enumeration wrappers (find_loops, find_circuit_node_lists, find_indexed_circuits) now read from the atomic; find_loops_with_limit and friends are unchanged. Also adds examples/ltm_full_bench.rs, a full-pipeline harness that drives parse -> sync -> ltm_enabled -> causal_edges -> element_edges -> loop_circuits -> ltm_variables -> compile on a chosen model and cap, emitting VmPeak/VmHWM/VmRSS snapshots at each stage so we can locate which stage first exceeds available memory as the cap is lifted. The harness aborts when VmPeak crosses LTM_BENCH_ABORT_MIB (default 15 GiB) so a runaway does not take down the whole box. Neither change touches production behaviour: the default cap is unchanged and the override exists solely for diagnostic sweeps.
… diagnosis Adds opt-in telemetry (LTM_BENCH_TRACE=1) to generate_loop_score_variables so the cap-lift diagnostic harness can observe loop_score and rel_loop_score equation-text growth in-flight. Every 10_000 loops the function logs: pass name, loops emitted so far, partition index/size (pass 2 only), cumulative loop_score bytes, cumulative rel_loop_score bytes, and /proc/self/status VmRSS in MiB. This lets us slope-fit each curve against loops-emitted and confirm whether rel_loop_score grows quadratically in partition size (O(P^2)) as predicted in the options doc. When the env var is unset the added cost is a pair of u64 adds plus a single bool check per iteration; no formatting or syscalls run on the hot path. The RSS reader gracefully degrades to None off Linux and on wasm targets so the function is still safe to call there.
Switches the LTM_BENCH_TRACE cadence from every-10_000 to powers of two up to 8192 plus every 10_000 thereafter. On WRLD3 the predicted rel_loop_score equation grows to O(P^2) bytes per loop with a single ~1.86M-loop partition, which means the process can OOM before the 10_000th iteration; the exponential early sample guarantees we still capture the scaling curve when that happens.
New ltm_post module with compute_rel_loop_scores plus unit tests and a
SAFEDIV-equivalence proptest. The implementation will replace the
compile-time emission of $⁚ltm⁚rel_loop_score⁚{id} synthetic variables,
which was O(P²) text per cycle partition and dominated the downstream
LTM pipeline on dense models (see the 2026-04-18 cap-lift diagnosis).
At this step the function is unused; the follow-up commits remove the
compile-time generator and point the two known read sites at the new
computation.
When a user enables exhaustive LTM analysis on a model whose element-level causal graph contains an SCC larger than MAX_LTM_SCC_NODES (currently 50), model_ltm_variables now silently downgrades to discovery mode before paying the circuit-enumeration and equation-emission cost. At WRLD3 scale the 166-node SCC produces ~1.86M elementary circuits, which allocate ~17 GB in build_element_level_loops and would project to ~140 TB of rel_loop_score equation text downstream. See docs/design-plans/2026-04-18-ltm-cap-lift- diagnosis.md for the measurements that motivated the threshold. The SCC check runs on the element-level causal graph (the same graph Johnson's algorithm walks), via the salsa-cached model_element_causal_edges, so repeated calls are cheap. When the auto-flip fires, a CompilationDiagnostic at Warning severity is accumulated so callers can surface the fallback; the user-requested `ltm_discovery_mode` path bypasses the check.
Replace divergence #2 to describe the SCC-size auto-flip in model_ltm_variables. Previously the section said the two LTM modes were strictly separate with no automatic switching; auto-flip to discovery above MAX_LTM_SCC_NODES introduces a bounded form of switching that is worth calling out for anyone tracing why exhaustive analysis silently produced no loop_score vars on a large model.
Exhaustive LTM used to synthesize one $:ltm:rel_loop_score:{id} aux per
loop with an equation that divided loop_score by the sum of absolute
scores over the loop's cycle partition. For partitions containing P
loops, that's P equations each summing over P denominators -- O(P^2)
equation text. WRLD3's 1.86M-loop partition projected to ~140 TB of
generated text during augmentation (see
docs/design-plans/2026-04-18-ltm-cap-lift-diagnosis.md).
This change computes rel_loop_score in Rust after simulation instead:
- LtmVariablesResult gains a loop_partitions field mapping each loop id
to its cycle-partition key. generate_loop_score_variables still emits
the one absolute loop_score aux per loop; the compile-time
rel_loop_score emitter is removed.
- ltm_post::compute_rel_loop_scores walks the loop_score timeseries
row-major over the Results buffer, grouping loops by the cached
partition key and normalizing against the sum of abs(loop_score) in
each partition. SAFEDIV-0 semantics are preserved (zero denom -> 0).
- Consumers that used to read $:ltm:rel_loop_score:{id} from VM offsets
now call compute_rel_loop_scores after simulation: layout metadata
(try_detect_ltm_loops_incremental) and the libsimlin FFI
(simlin_analyze_get_relative_loop_score). simulate_ltm integration
tests and the LTM bench were updated analogously.
- A proptest in ltm_post asserts the new computation agrees with the
inlined reference SAFEDIV formula to 1e-10 across small random loop
sets and partition assignments, so the post-sim path is a drop-in
substitute for the removed equations.
The goldenfile test/logistic_growth_ltm/ltm_results.tsv is preserved
bit-for-bit: simulates_population_ltm still loads the TSV and compares
against the post-sim output.
Reflect Option B of the LTM cap-lift plan in the LTM design doc and the engine module map: - docs/design/ltm--loops-that-matter.md: call out ltm_post.rs in the module table, update the exhaustive/discovery mode and partition descriptions, drop rel_loop_score from the Naming Convention table, rewrite the Synthetic Variable Approach and Trade-offs sections so they account for the post-sim path, and expand the "relative loop score formula" divergence-from-papers bullet to cover both the SAFEDIV-0 choice and the post-sim timing. The auto-flip bullet also picks up the fact that the O(P^2) blow-up was specific to the removed emitter. - src/simlin-engine/CLAUDE.md: list ltm_post.rs, and update the db_ltm.rs and ltm_augment.rs entries so the description of what model_ltm_variables emits matches reality after the emitter move.
model_ltm_variables accumulates a Warning diagnostic when it auto-flips from exhaustive to discovery mode, but model_all_diagnostics never invoked it, so the warning was invisible to collect_all_diagnostics -- the path both libsimlin and simlin-mcp use to surface diagnostics to end users. Drive model_ltm_variables from model_all_diagnostics when ltm_enabled is set, so salsa's accumulator propagates the warning to the collector. Two new tests guard the invariant: the surfacing test asserts the warning reaches collect_model_diagnostics on an auto-flipped 51-node SCC model, and the negative test asserts LTM-disabled projects do not emit LTM diagnostics (so callers who never asked for LTM pay no synthesis cost).
Four new tests guard previously-unchecked behaviour along the cap-lift
boundary:
* test_auto_flip_keys_on_largest_scc_not_total_nodes -- two disjoint
40-node cycles (80 nodes total) must stay on the exhaustive path;
a regression that accidentally summed SCC sizes would crush any
real model with multiple independent feedback subsystems.
* test_user_discovery_mode_does_not_emit_auto_flip_warning --
discovery-by-user-choice and discovery-by-auto-flip look identical
in output shape; the warning must fire only for the latter or the
diagnostic becomes noise.
* test_auto_flip_uses_element_level_scc_for_arrayed_models -- a
60-element A2A stock-flow loop has element-level SCC of 2, not
variable-level 2. The gate must key on the element graph (which it
does); this test pins the invariant so a future refactor that swaps
in the variable-level graph would be caught.
* nan_loop_score_propagates_without_panic -- documents and pins the
documented IEEE-754 propagation contract for post-sim
compute_rel_loop_scores; the removed compile-time SAFEDIV equation
did the same, but only arithmetic on NaN, never asserting.
Helper build_two_disjoint_sccs_project constructs two prefixed cycles
(a_* and b_*) parameterized by per-cycle size.
Captures the end-to-end validation of commits c11f485/aff5c56f (auto-flip) and 2647501/4959706c (post-sim rel_loop_score), including the WRLD3 bench numbers at cap=100k/2M/usize::MAX, the semantic cross- check summary for the 45-test simulate_ltm suite, and sign-off for task #7 (cap raise). Documents the one non-trivial finding surfaced during the review -- the auto-flip warning was accumulated but not surfaced through collect_all_diagnostics -- and the inline fix + test coverage added to close it.
Add a regression test that pins the uncapped element-level enumeration count for wrld3-03 to 1,863,803 circuits -- the value measured by the 2026-04-18 adversarial cap-lift validation. The test runs before the MAX_LTM_CIRCUITS cap is removed so the count stands as a contract: any future refactor that silently reintroduces a cap (or corrupts Johnson's dedup) will flip this test red. Uses find_indexed_circuits_with_limit so the test exercises the same compact-index path the salsa pipeline uses in production. Ident-expanded find_circuit_node_lists_with_limit would allocate ~1.8 GB of strings just to count circuits, which is wasteful for a pure regression check.
The element-level auto-flip gate in `model_ltm_variables`
(`MAX_LTM_SCC_NODES = 50`) is now the real backstop for the LTM
pipeline: oversized SCCs flip to discovery mode rather than
materializing per-element loop scores. That makes the legacy
`MAX_LTM_CIRCUITS = 100_000` cap on pure enumeration vestigial. The
cap's only remaining effect was to silently truncate the circuit
list ingested by `model_loop_circuits`, `model_detected_loops`, and
`model_element_loop_circuits`, which in turn masked WRLD3's true
1,863,803 elementary circuits behind a 100,000-entry cache -- useless
for diagnostics, and an obstacle to the stress harness in
`examples/ltm_full_bench.rs` that needs the raw graph structure.
This commit removes the constant plus all supporting surface:
`RUNTIME_LTM_CIRCUIT_BUDGET`, `set_max_ltm_circuits`,
`default_max_ltm_circuits`, and the three default-budget enumeration
wrappers (`find_loops`, `find_circuit_node_lists`,
`find_indexed_circuits`). `TruncatedByBudget` and the
`_with_limit` variants remain as the general form so future stress
tests can still measure truncation behaviour on demand. All three
salsa call sites in `db_analysis.rs`, plus `detect_loops` and
`ltm_full_bench.rs`, now pass `usize::MAX` as the enumeration budget;
in practice the budget can never be exhausted (Johnson's enumerates
each circuit exactly once), so the `.expect(...)` message documents
why the `TruncatedByBudget` branch is unreachable rather than
silently swallowing it.
Adversarial validation (2026-04-18 run, recorded in
`tests/wrld3_ltm_panic.rs::wrld3_element_level_enumeration_is_uncapped`
and repeated with the full bench):
- wrld3-03.mdl: 1,863,803 circuits, 467 MiB VmPeak, 1.6 s wall,
compile_ok=true, 483 link_score synth vars emitted (loop_score /
path / composite skipped by auto-flip as expected for a 166-node
SCC).
- arrayed_population.stmx: 6 circuits, 10.5 MiB peak, compile_ok.
- cross_element.stmx: 12 circuits, 10.5 MiB peak, compile_ok.
The full-pipeline bench also gained XMILE (.stmx / .xmile) support so
these non-Vensim regression models can be profiled without a separate
driver script.
The cap-lift diagnosis, options, and validation design plans now each carry a "Resolution" section pointing at the branch (`ltm-perf-enable-always`), the two landed options (auto-flip at `MAX_LTM_SCC_NODES = 50` and post-sim `rel_loop_score`), and the `MAX_LTM_CIRCUITS` removal. The 2026-04-17 mem-reduction doc is left intact because its reference to the 100,000 cap is an accurate description of the state at that time and the prose makes the temporal framing clear. Tech-debt item #25 ("LTM Element-Level Loop Enumeration Runs at Wrong Granularity") previously called out `MAX_LTM_CIRCUITS = 100_000` as the gate that pure-A2A multiplication would hit first. With the cap retired, `MAX_LTM_SCC_NODES = 50` is now the first gate; the item's description and review date are updated to reflect that without changing scope (the variable-level enumeration refactor is still the right follow-up).
Three review-driven fixes to the cap-lift branch: 1. model_detected_loops now gates on MAX_LTM_SCC_NODES just like model_ltm_variables. Layout feedback-loop metadata, the simlin_analyze_get_loops FFI, and simlin-cli --ltm all call this function directly; before this change they would still enumerate ~1.86M loops and allocate ~17 GB of Loop/Link state on WRLD3-scale models even though model_ltm_variables had already auto-flipped. Returning empty matches the honest answer -- listing 1.86M loops is useless to those consumers, and the discovery path via analyze_model is what they should use for dense-graph models. 2. Add a MAX_LTM_TOTAL_CIRCUITS = 10_000 backstop inside model_ltm_variables. The largest-SCC gate misses pathological shapes where a small variable-level SCC is expanded across a large dimension: a pure A2A population[Region] -> births[Region] -> population[Region] cycle with a big dimension has max_scc_size == 2 but one element-level circuit per element, each of which still becomes a ~9 KB Loop struct in build_element_level_loops. When the total circuit count exceeds the backstop, flip to discovery and emit the same Assembly Warning as the SCC gate. 3. compute_rel_loop_scores now builds its partition-group index in a BTreeMap rather than a HashMap. Float summation inside a partition is not associative, so hash-randomized iteration across runs would otherwise allow bit-for-bit drift in the rel_loop_score denominator on the same input -- invisible to the existing tests (1e-10 proptest tolerance, 0.05 integration tolerance) but observable to diffing consumers and undesirable in a salsa-cached pipeline. The in-test reference implementation mirrors the BTreeMap to keep the proptest equivalence honest. Tests: two new tests in db_ltm_unified_tests cover the total-circuit backstop (discovery-shape output + Warning diagnostic) on a 10_001-element A2A model. Two new tests in db_analysis cover the model_detected_loops gate at the 51/49 threshold boundary. All 3079 engine unit tests, 45 simulate_ltm integration tests, and both wrld3_ltm_panic tests pass. Follow-ups filed as separate issues rather than fixed inline: - #463 LTM scalar FFI element-0 collapse for A2A arrayed loops (pre-existing, not a regression introduced by this branch) - #464 LTM_BENCH_TRACE should be cfg-gated rather than env-gated - #465 wrld3 uncapped enumeration test should skip under debug_assertions
Four review-driven corrections to the iteration-1 fixes: 1. model_detected_loops: replace the largest-SCC gate with a circuit- budget gate (MAX_LTM_TOTAL_CIRCUITS). Codex correctly noted that the SCC-size gate was too aggressive -- a sparse 75-node ring has exactly one elementary loop and enumerating it is trivial, but the iteration-1 gate suppressed it unconditionally. The budget-based gate measures actual circuit count (Johnson's bails via TruncatedByBudget as soon as the (K+1)th circuit would be recorded), so sparse long rings pass through while dense graphs like WRLD3 still truncate to empty. Tests updated: the 51-node ring test removed, new tests cover a 75-node sparse ring (returns 1 loop) and a budget=0 truncation signal through the CausalGraph API. 2. simlin_analyze_get_relative_loop_score: snapshot loop_partitions on SimState at simlin_sim_new time rather than re-querying the salsa db at score-read time. Addresses two prior-review concerns at once: (P1) if the project is patched between sim_new and the FFI call, the score computation would silently use the *new* partition mapping against the *old* results buffer, producing wrong normalization or DoesNotExist for loops that were legitimately scored; (P2) the FFI held db_locked + sync_state while acquiring state.lock(), inverting the lock order the rest of libsimlin uses. Reading from the SimState snapshot eliminates both -- the FFI now only takes state.lock(), and the scores stay consistent with the VM's era. 3. Improve DoesNotExist messages in the relative-score FFI to distinguish "LTM was off or auto-flipped" from "unknown loop id in an LTM exhaustive run". The former is the expected outcome when auto-flip fires on arrayed models where model_detected_loops still reports structural loops; the message now tells FFI callers to check the engine warnings rather than wonder why the loop id they just got from simlin_analyze_get_loops has no score. 4. Add a symmetric surfacing test for the total-circuit backstop warning (parallel to the existing SCC-gate test). Verifies the Warning reaches collect_model_diagnostics (the FFI surface), not just the direct salsa accumulator. Catches a future regression where model_all_diagnostics stops driving LTM synthesis. 5. Drop the redundant !is_discovery_user guard on the SCC gate: max_scc_size is 0 on the user-discovery branch, so the comparison is self-consistent without the extra check. Test sweep: 3079 engine unit tests, 45 simulate_ltm integration, 20 libsimlin tests, both wrld3_ltm_panic tests. All green.
19bbced to
5c1daf6
Compare
PR reviewNo findings. I checked the hot spots:
Overall correctness: correct. The O(P²) equation-text blowup is cleanly eliminated; the snapshot pattern correctly binds post-sim normalization to the VM's compilation era; and the diagnostic visibility fix ( |
PR #461 reviewI walked the full diff carefully: the auto-flip gate in No findings. overall correctnesscorrect |
…cores Three corrections to iteration-2 from review: 1. model_detected_loops: switch from find_loops_with_limit to a new find_loops_if_under_limit API that gates on the *post-dedup* distinct-circuit count, not on raw Johnson emissions. Codex correctly noted that find_loops_with_limit's budget is charged on every raw DFS emission (proved by the existing johnson_budget_charges_duplicate_raw_cycles test), so dense multidigraphs where the same node-set is rediscovered many times could trip MAX_LTM_TOTAL_CIRCUITS even when the *actual* Loop-struct materialization cost (which the gate is trying to bound) is well under the threshold. find_loops_if_under_limit runs enumeration to completion -- the cheap phase, `Vec<u32>` paths -- and only materializes Loop structs when the deduped count is within budget. The new unit test in ltm::tests constructs K4 (11 distinct circuits, many raw emissions) and shows the two APIs diverging at budget=11: find_loops_with_limit(11) trips, find_loops_if_under_limit(11) succeeds. Refactored out a shared materialize_loops_from_indexed so both paths emit identical Loop structs and assign the same deterministic IDs. 2. SimState: memoize the full compute_rel_loop_scores map on first FFI read, invalidate when results are replaced. pysimlin's `_populate_loop_behavior` and the LoopDominanceAnalyzer example both iterate every loop id and call get_relative_loop_score per loop, which with the uncached path was O(P^2 * S) across a full iteration (P full recomputes, each O(P * S)). The cache collapses this to a single O(P * S) traversal. Invalidation hooks at the two write sites for state.results (simlin_sim_run_to_end and simlin_sim_reset). 3. db_analysis doc: update the MAX_LTM_TOTAL_CIRCUITS reference on find_loops_if_under_limit to explain the raw-vs-deduped semantic split so a future reader does not reintroduce the regression. Test sweep: 3080 engine unit tests, 7 ltm_post tests, 45 simulate_ltm integration, 20 libsimlin tests, both wrld3_ltm_panic tests; all green.
…count Two fixes from iter-11 review: 1. Rewrite test_compute_metadata_preserves_structural_loops_when_ltm_auto_flips to actually exercise the iter-10 code path it claims to guard (claude iter-11 P2). The previous version built a 60-element pure-A2A model and asserted feedback_loops was non-empty, but that shape doesn't trip any auto-flip gate (largest_scc_size = 2, estimate_emitted_loop_count = 1), so loop_partitions came back populated and the iter-10 "return None on empty partitions" guard never evaluated true -- test passed against both pre- and post-iter-10 code. New version sets ltm_discovery_mode = true explicitly, which produces the same empty-loop_partitions shape auto-flip would, and asserts both that feedback_loops surfaces the structural loop AND that importance_series is empty (the post-iter-10 contract). 2. estimate_emitted_loop_count now matches build_element_level_loops on the degenerate repeated-variable-names case where the unique stripped cycle has length < 2 (claude iter-11 P3). A group whose stripped signature is something like [pop, pop] means the variable graph has a direct pop -> pop self-edge (rare in real SD models but structurally possible). `build_element_level_loops` gates Loop emission on `unique_cycle.len() >= 2`, so it emits zero Loops for this shape; the estimator now mirrors that check by counting only when the first-repeat prefix is >= 2 names long, preventing spurious over-counts on degenerate inputs. Codex iter-11 P2 (auto-flip warning unreachable through simlin_project_get_errors) deferred to follow-up issue #466. The self-contained error message in simlin_analyze_get_relative_loop_score is the primary UX mitigation for the unreachability; surfacing the warning through the separate project.get_errors workflow requires a larger architectural change (sim-side diagnostic capture or always-on model_ltm_variables in model_all_diagnostics) that is out of scope for this PR's cap-lift focus. Test sweep: 3084 engine unit tests, 45 simulate_ltm, 20 libsimlin, 33 layout, both wrld3_ltm_panic tests. All green.
Review: LTM always-on via auto-flip + post-sim rel_loop_scoreThorough pass over the production diff (ltm_post.rs, ltm.rs, db_ltm.rs, db.rs, db_analysis.rs, layout/mod.rs, ltm_augment.rs, libsimlin lib.rs/simulation.rs/analysis.rs). Tests cover the adversarial cases I would have wanted (auto-flip triggered by SCC size, auto-flip triggered by emitted-loop estimate, user-discovery suppression of auto-flip, pure-A2A collapse, truncation fallback to persisted metadata, rel_score proptest to 1e-10 against a reference implementation). Observations (no P0/P1)
Things I verified and have no concern with
Overall correctness: correctI did not find any blocking issues. The auto-flip gates are well-coordinated, the post-sim rel_score path is a strict improvement over the O(P²) emitted-equation approach, and the cache invalidation covers every mutation path in the current FFI. The P2/P3 items above are comment/doc suggestions, not code changes. |
Codex iter-12 P2: `compute_rel_loop_scores` is new code in this PR and only reads `row[offset]` (element 0) for every loop, so arrayed A2A loops that previously had per-element `rel_loop_score` synthetic variables lost per-element normalization in the post-sim path. The FFI and layout consumers it serves were already element-0-only pre-PR (verified by reading the old libsimlin analysis.rs), so no existing public behaviour regresses. But the function is the canonical replacement for the retired synthetic variables, and users who want per-element data (diagram UI reading per-element importance, a future FFI that exposes arrayed loop analysis, or pysimlin callers reading dimension-aware series) need a production path that reproduces the pre-PR per-element math. This commit adds `compute_rel_loop_scores_per_element(results, loop_partitions, n_slots_by_loop) -> HashMap<String, Vec<f64>>` to `ltm_post.rs`. The function mirrors the pre-PR compile-time SAFEDIV-per-partition-per-element equation exactly: - For each partition group, `max_slots` = the largest slot count among the loops in the group. Scalar loops treat `slots == 1` and broadcast their single value across every element slot, matching the compile-time emitter's broadcast semantics. - The denominator at element `k` is `sum_j |loop_score_j[k_j]|` where `k_j = k` for arrayed loops and `k_j = 0` for scalar. - Output is a flat `Vec<f64>` per loop id of length `step_count * max_slots`, row-major with step varying slowest. Scalar-only groups trivially stride 1 and produce output identical to `compute_rel_loop_scores`. The existing scalar `compute_rel_loop_scores` is retained so the libsimlin FFI (which deliberately returns a scalar series to match pre-PR semantics) and layout feedback-metadata (which consumes a single series per loop for importance ranking) don't need to change. New consumers that want per-element semantics call the new function directly. The `compute_rel_loop_scores_per_element` helper that was previously a test-only local in `tests/simulate_ltm.rs` (the workaround referenced by claude iter-1's A2A concern) is now a thin alias that forwards to the production version -- no logic change to the three existing arrayed integration tests (`test_a2a_pure_dimension_loop_scores`, `test_arrayed_population_ltm_exhaustive`, and their siblings), but they now pin the production code rather than a parallel implementation. Test sweep: 3084 engine unit tests, 45 simulate_ltm, 20 libsimlin, 33 layout, both wrld3_ltm_panic tests. All green.
Codex iter-13 P1: the pre-enumeration largest-SCC gate (MAX_LTM_SCC_NODES = 50) was too blunt. A sparse model like stock -> aux_1 -> ... -> aux_49 -> flow -> stock has one elementary loop but a 51-node SCC; the old heuristic mistook length for density and forced the model into discovery mode even though exhaustive LTM would emit just one loop_score cheaply. This commit drops MAX_LTM_SCC_NODES entirely. WRLD3-scale dense feedback is still caught, but now via the MAX_LTM_TOTAL_CIRCUITS post-collapse emit-count gate backed by the MAX_LTM_ENUMERATION_CAP streaming cutoff: - Dense SCCs (WRLD3's 166-node SCC, 1.86M circuits) trip the streaming cap inside model_element_loop_circuits, returning LoopCircuitsResult.truncated = true, which model_ltm_variables routes into the same auto-flip handler as an over-budget emit count. - Sparse large SCCs (51-node ring) enumerate cheaply (1 circuit, microseconds), report estimate_emitted_loop_count = 1, and stay exhaustive so the user gets per-loop scoring on the single real loop. Tests renamed and retargeted to use the disjoint-cycles trigger (build_n_disjoint_cycles_project) instead of build_chain_scc_project, except for test_model_ltm_variables_stays_exhaustive_on_sparse_large_scc which deliberately retains the 51-node-chain shape to pin the "sparse large SCC stays exhaustive" contract that replaces the old "stays exhaustive below SCC threshold" semantic. The CausalGraph's largest_scc_size() helper is kept as a public structural-analysis API (still used by examples/ltm_mem_bench.rs) but no longer gates LTM. Claude iter-13 P2: add two new unit tests for the production compute_rel_loop_scores_per_element that had previously only been exercised through the simulate_ltm integration suite: 1. per_element_with_all_scalar_matches_scalar_variant: pins the docstring's "scalar-only groups trivially stride 1 and produce output identical to compute_rel_loop_scores" claim with both missing-entry and explicit slot=1 inputs. 2. per_element_broadcasts_scalar_loops_in_mixed_partition: hand-computed per-element denominators for a mixed partition (one arrayed 3-slot loop + one scalar loop) to pin the broadcast semantic against the pre-PR compile-time emitter's behaviour. Codex iter-13 P2 about model_detected_loops truncation visibility through simlin_cli::simulate() is covered by the self-contained error message in simlin_analyze_get_relative_loop_score and is tracked in follow-up issue #466 alongside the related simlin_project_get_errors gap. Both are documented as "LTM warnings not reachable through the current diagnostic FFI workflow" deferred to a separate FFI-layer change. Test sweep: 3086 engine unit tests (+2 new), 45 simulate_ltm, 20 libsimlin, 33 layout, both wrld3_ltm_panic tests. All green.
ReviewOverall the patch is well-structured: the move of [P3] Duplicated
|
Codex iter-14 P2: `compute_rel_loop_scores_per_element` previously walked `k` from 0 to the partition's `max_slots` and indexed every non-scalar loop as `row[off + k]`. Partition membership is based on stock SCCs, so a single partition can legitimately contain arrayed loops with different arities -- a Region loop of size 2 and a Region x Age loop of size 2*3 = 6, for example. Once k >= the shorter loop's slot count, `row[off + k]` would read past the loop's own buffer into adjacent columns and mix in unrelated variable data. This commit factors the element-index resolution into a local `elem_index(i)` helper that returns `None` for loops whose slot_count exceeds k, and both the denominator sum and the numerator write use `filter_map` / `let Some(_) = ... else continue` to drop those loops cleanly. A new unit test `per_element_mixed_arity_drops_short_loop_beyond_its_length` pins the contract with a 2-slot + 4-slot partition in shape (1, 2, 3, 4, 10, 20, 30, 40) where the 2-slot loop's elements 2 and 3 must come back as default 0.0 (loop has no slot at that element, not a misaligned read from the 4-slot loop's buffer). Claude iter-14 P2: fix the duplicate `## Why 10_000` rustdoc section on `MAX_LTM_TOTAL_CIRCUITS` introduced in iter-13. The iter-13 edit added a new paragraph but left the original section in place, producing two identical h2s back-to-back with slightly different memory figures (~90 MB in one, ~130 MB in the other). Kept the more detailed figure (~130 MB, accounting for both Loop struct allocation AND loop_score equation text). Codex iter-14 P1 about `collect_all_diagnostics` forcing LTM synthesis is misfounded -- the call is gated by `if project.ltm_enabled(db)`, which is false in all production callers (MCP read_model, MCP edit_model, libsimlin simlin_project_get_errors, and simlin-cli simulate -- the last collects diagnostics BEFORE set_project_ltm_enabled(true)). The only transient path where `ltm_enabled = true` during diagnostic collection is inside `simlin_sim_new` itself, and there `model_ltm_variables` has already been computed by `compile_project_incremental`, so the salsa cache serves the diagnostic-time call without re-running enumeration. No unexpected-cost regression. Test sweep: 3087 engine unit tests (+1 new), 45 simulate_ltm, 20 libsimlin, 33 layout, both wrld3_ltm_panic tests. All green.
Code review — PR #461
|
…rcuit count Codex iter-15 P1: the streaming distinct-circuit cap (MAX_LTM_ENUMERATION_CAP = 1_000_000) bounds how many circuits the indexed enumeration emits but not how much memory they consume. Each circuit is a Vec<u32> whose length equals the loop's node count, so peak state is O(sum(len(circuit_i))) rather than O(circuit_count). A pathological pure-A2A model with a 1000-node feedback loop replicated across 900k elements stays under the 1M-circuit cap yet accumulates ~900M u32 indices (~3.5 GiB before Vec overhead), which blows WASM's 4 GiB budget long before the circuit-count cutoff triggers. This commit adds a companion node-count cap, MAX_LTM_ENUMERATION_NODES = 10_000_000 (~40 MiB of indexed-path storage), threaded through the same Johnson's DFS as the distinct-count cutoff: - JohnsonState gains `node_limit` and `total_nodes_emitted`. Each successful circuit push bumps the running total and checks both caps (distinct-count and node-count), returning TruncatedByBudgetInternal on the first overrun. - enumerate_circuits_in_scc and enumerate_indexed_circuits_ex accept both limits; per-SCC budgeting subtracts the already-accumulated counts so a two-SCC model trips at the sum boundary rather than per-SCC. - find_indexed_circuits_streaming_distinct gains a node_limit parameter; model_element_loop_circuits passes both constants in. - The diagnostic callers (examples/ltm_mem_bench.rs) continue to use usize::MAX for both limits since they want raw graph measurement. For the 10k-loops-of-length-1000 materialization scenario codex also called out: enumeration now trips on 10M node indices before reaching the materialization step, so the downstream build_element_level_loops cliff is avoided via the enumeration cap rather than needing a separate link-count gate. Realistic SD models (WRLD3's 87M nodes trip the distinct-count cap at 1M circuits first, at ~47M nodes via streaming) are unchanged. New unit test `streaming_node_limit_trips_on_long_loops` verifies the cutoff fires at the cumulative boundary (two 3-node rings with node_limit = 4 trips; with node_limit = 6 both admit). The test uses distinct_limit = usize::MAX to isolate the node-count cutoff from the pre-existing distinct-count cutoff. Test sweep: 3088 engine unit tests (+1 new), 45 simulate_ltm, 20 libsimlin, 33 layout, both wrld3_ltm_panic tests. All green.
ReviewInvestigated the cap-lift architecture end-to-end: FindingsNothing rises to [P2] or above. Two [P3] observations: [P3] [P3] Auto-flip to discovery silently drops Overall correctness: correct.Test coverage is unusually thorough for the surface area changed: proptest against an inlined reference implementation, explicit NaN propagation, SAFEDIV-0, mixed-arity partitions, disjoint-SCC denominators, and a WRLD3 panic regression test. The BTreeMap-over-HashMap choice for partition iteration ( |
Iteration-16 reviews flagged three concerns with the earlier single-cap gate around element-level feedback-loop enumeration: 1. MAX_LTM_ENUMERATION_NODES (10M) was tight enough that a WRLD3-shape model could hit the node cap before the distinct count cap. Raise it to 100M (~400 MB indexed-path storage); the distinct cap now fires first on realistic inputs and the node cap remains the backstop for pathological long-loop shapes. Update the ltm.rs rustdoc to state which cap is primary on WRLD3 so future readers do not have to re-derive it. 2. Structural consumers (layout metadata, simlin_analyze_get_loops, simlin-cli --ltm) were sharing the MAX_LTM_TOTAL_CIRCUITS = 10_000 budget with LTM variable synthesis. Structural consumers do not pay the equation-text cost and can tolerate more loops. Add MAX_LTM_DETECTED_LOOPS = 100_000 and route model_detected_loops through a new CausalGraph::find_loops_if_under_limit_ex(max_loops, max_nodes) that accepts both caps; the LTM synthesis path still uses the stricter 10k cap. At ~9 KB per materialized Loop struct, 100k loops cost ~900 MB of transient state, still inside WASM's 4 GiB ceiling but shy of WRLD3 scale. 3. The auto-flip diagnostic in db_ltm only named the distinct-circuit cap; it should name both streaming caps because either can fire first. Same for the FFI error in libsimlin -- list all three threshold constants so callers looking up the error can find them. Delete the tests/layout.rs regression test for the detected.truncated -> compute_metadata fallback branch. The original test built MAX_LTM_TOTAL_CIRCUITS + 1 = 10_001 disjoint cycles to force truncation; with the cap at 100_000 it would need 100_001+ cycles (300k+ variables) to reproduce, and a denser construction hits Johnson's DFS raw-cycle explosion well before the dedup sees the distinct count. The sibling fallback branch on simulation failure is still covered by test_ltm_fallback_on_sim_error in layout_tests.rs, and the truncation branch itself runs in production against WRLD3-scale models. Tracked as GitHub issue #467.
|
Took a full pass at this. The core design — auto-flip gate + post-sim One finding: [P3] Overall correctness: correct. The only issue I found is the stale docstring above. |
…nostics Iteration-17 reviews flagged four concerns with the earlier cap-split patch: 1. FFI simlin_analyze_get_relative_loop_score materialized compute_rel_loop_scores for every loop on first lookup. On exhaustive models near MAX_LTM_TOTAL_CIRCUITS that cache is loop_count * step_count * 8 bytes -- about 800 MB at 10k loops and 10k saved steps, which re-introduces the large memory spike the removal of rel_loop_score synthetic variables was meant to avoid. Replace the full-map cache with per-cycle-partition denominator caching: peak memory is now bounded by num_partitions * step_count, while the per-loop iteration pattern (pysimlin _populate_loop_behavior, diagram UI, MCP) still amortizes denominator work across loops in the same partition. Introduces ltm_post::compute_partition_denominator and compute_rel_loop_score_for_id primitives with bit-parity tests against compute_rel_loop_scores. 2. model_all_diagnostics only accumulated the LTM auto-flip / total-circuit warnings when project.ltm_enabled was currently true, but simlin_sim_new toggles that flag back to false after compilation to avoid leaking LTM synthesis into later patch validation. After the reset, salsa re-runs the accumulator without LTM and the warning is dropped, so simlin_project_get_errors reported nothing even though the sim had already auto-flipped to discovery. Capture the LTM-specific diagnostics on SimlinProject::pending_ltm_diagnostics at sim_new time and replay them through the get_errors path. Cleared by simlin_project_apply_patch since the patched model may no longer trip the same threshold. Adds FFI integration test test_auto_flip_warning_surfaces_via_get_errors_after_sim_new. Non-LTM users who never requested LTM still see no LTM warnings (the existing test_ltm_disabled_does_not_surface_auto_flip_warning gating). 3. Several rustdoc and inline comments in db_analysis.rs still cited MAX_LTM_TOTAL_CIRCUITS after iteration-16 split the structural cap from the LTM-synthesis cap, and the "~40 MB" indexed-path budget estimate lagged behind the 10x raise to 100M nodes (~400 MB). Update the rustdoc on model_detected_loops and DetectedLoopsResult to name MAX_LTM_DETECTED_LOOPS and MAX_LTM_ENUMERATION_NODES, correct the numeric estimates, and fix two stale MAX_LTM_TOTAL_CIRCUITS references in test assertion messages. 4. ltm_full_bench reported circuits=0 whenever model_element_loop_circuits returned truncated = true because the streaming cap deliberately leaves the circuits vec empty -- exactly the shape the benchmark was meant to diagnose. Emit an explicit truncated=true marker in the detail line so the profiling output matches reality on dense models. Also adds find_loops_if_under_limit_ex_gates_on_node_cap unit test covering the node-cap branch of the new two-cap API.
ReviewRead through the engine changes ( Findings[P3]
|
…g slot Iteration-18 reviews raised three concerns, all addressed here: 1. Codex P3: compute_partition_denominator iterated loop_partitions in HashMap order, so the float sum it produced could drift bit-for-bit between runs on the same input. The existing full-pass helper compute_rel_loop_scores already sorts loop IDs before summing for exactly this reason. The libsimlin FFI single-loop path delegates to the streamed primitive, so partitions with mixed-magnitude loop_score values could return a slightly different relative-score series than the full-pass path. Sort the IDs before collecting offsets in compute_partition_denominator; add a bit-parity regression test that mixes 1e16 and O(1) values across three non-lex-ordered loop IDs to pin the determinism contract against future refactors. 2. Codex P2: append_captured_diagnostics deduped only on the formatted message text. Today that is safe because format_diagnostic_with_datamodel prefixes Assembly warnings with the model name, but defensive coding against a future formatter change is cheap: switch the dedup key to (model_name, message) using the Diagnostic's structural model field so multi-model dedup stays correct regardless of the formatter. Add regression tests covering both (a) repeated simlin_sim_new(enable_ltm=true) on the same project producing exactly one warning in get_errors output (overwrite, not accumulate), and (b) a multi-model project where the dense model's warning surfaces even when the current sim is for the sparse model. 3. Claude #1: simlin_sim_new only assigned pending_ltm_diagnostics when the captured diagnostic set was non-empty, so a sparse sim_new after a dense one would leave the stale dense warning in the slot. Always overwrite on enable_ltm=true (including to an empty vector) so the slot reflects the most recent LTM-enabled compile. Additional hygiene from Claude #5/#8: - Document the lock ordering (acquire pending_ltm_diagnostics after db/sync_state/datamodel) on the SimState field to keep future callers from inverting it. - Consolidate the two back-to-back comment blocks in simlin_analyze_get_relative_loop_score into a single coherent preamble covering partition resolution, cache lifecycle, and the reborrow rationale.
ReviewI reviewed the substantive code changes in
Minor (P3, optional)
Overall correctnessCorrect. No P0/P1/P2 issues found. Test coverage (proptest bit-parity, adversarial corner tests, WRLD3 panic regression, golden TSV preservation) is well-aligned with the changes. |
Iteration-19 reviews raised two concerns, both addressed here: 1. Codex P2: layout's try_detect_ltm_loops_incremental still used the full-pass compute_rel_loop_scores, materializing the entire loop_count * step_count matrix and cloning each series into its FeedbackLoop. At exhaustive-mode models near MAX_LTM_TOTAL_CIRCUITS that is hundreds of MB of transient state on top of the already-sizeable VM results buffer. Switch to the same per-partition streaming the libsimlin FFI uses (compute_partition_denominator + compute_rel_loop_score_for_id) so peak extra memory during layout generation drops to O(num_partitions * step_count + 1 * step_count). The layout tests pass unchanged (32/32), pinning that the per-loop output is bit-identical to the prior implementation. 2. Claude #1: the iter-18 bit-parity test per_id_rel_loop_score_bit_parity_with_mixed_magnitudes did not actually guard against removing the sort in compute_partition_denominator. Widely-spaced magnitudes (1e16, -1e16, 1.0) round bit-identically regardless of summation order because the small value is absorbed at the large exponent, so the test passed even with the sort commented out. Replace with a stronger test: - 7 loops with [0.1, 0.2, ..., 0.7] magnitudes so any two orderings differ by at least one ULP, - 16 fresh RandomState::new() seeds per trial so iteration orders reliably differ (verified empirically at ~93% catch rate with 8 trials; 16 trials push it past 99%). Rename the test to *_denominator_is_order_independent so future readers understand what property it pins. The test passes in the corrected code and reliably fails when the sort is removed.
ReviewI reviewed this PR focusing on the post-simulation
FindingsNone at P0/P1/P2/P3 that an author would fix. Things I initially flagged and then cleared:
Overall correctnessCorrect. The PR is unusually well-commented — the key design decisions (post-sim normalization, partition snapshot at |
|
Completed iterative review cycle with High-level improvements layered on top of the original auto-flip + post-sim cap-lift work:
Tracked as tech debt for future follow-up: dedicated integration coverage for the |
## Summary First step to re-landing the work from reverted PR #461, this time with a safety rail that would have caught the failure mode before merge. - Rebase of the 16 commits that were in place at the [2dbce50 checkpoint](2dbce50) (the user-reviewed state of the original PR: simple `MAX_LTM_SCC_NODES = 50` auto-flip gate + post-sim `compute_rel_loop_scores`, no layered iterations). - New commit caps `cargo test --workspace` wall-clock at 180s in both `scripts/pre-commit` and `.github/workflows/ci.yaml`, with `timeout(1)` from coreutils (no new dep). `cargo tarpaulin` gets a matching 2700s outer cap. - Docs update: `docs/dev/rust.md` grows a "Test time budgets" section; `CLAUDE.md` and `docs/dev/commands.md` point at it. ## What went wrong on PR #461 PR #461 was clean through the 16 commits in this branch. Over the ~19 commits of subsequent review feedback the clean `MAX_LTM_SCC_NODES = 50` gate was removed and replaced with four interacting knobs (`MAX_LTM_DETECTED_LOOPS`, `MAX_LTM_TOTAL_CIRCUITS`, `MAX_LTM_ENUMERATION_CAP`, `MAX_LTM_ENUMERATION_NODES`). The new `MAX_LTM_TOTAL_CIRCUITS = 10_000` gate is only testable by *enumerating past it*, so the added tests built fixtures with 10,001 disjoint 3-cycles (~30k variables) and ran them through full compilation -- one of them three times in a loop to exercise dedup. That single test binary reported `finished in 2652.16s` (44 minutes). The ubuntu-latest build job hit GitHub's 60-minute per-job cap. Code Coverage (tarpaulin) failed with "Timed out waiting for test response" at 8 minutes. Nothing in pre-commit or CI noticed until GitHub's job limit fired. This PR fixes that blind spot first, so subsequent iterations on the LTM cap-lift work happen with a backstop in place. ## Measured CI baseline (post-revert main, last 3 runs) | Step | ubuntu-latest | macos-latest | |---|---|---| | `cargo test --workspace` Test step | 58-60s | 39-49s | | `cargo tarpaulin --out Xml` | -- | 1387-1466s (23-24 min) | 180s is ~3x the cargo-test baseline. Local dev machines run the suite in ~25s, so ~7x headroom there. ## Design guidance added `docs/dev/rust.md` documents the anti-pattern directly: do not test a production threshold gate by constructing a fixture large enough to trip it. Expose a test-only override and use a tiny fixture. Expensive tests that genuinely need a real-world case (e.g. compiling WRLD3) should be `#[ignore]`'d with the opt-in command documented next to them. ## Test plan - [ ] Local `./scripts/pre-commit` passes (verified on this branch with the new timeout in place). - [ ] CI Test step completes well under 180s on ubuntu-latest and macos-latest. - [ ] CI Coverage step completes well under 2700s. - [ ] Timeout exit messaging surfaces correctly when tripped (spot-check: `timeout --kill-after=30 1 cargo test` should fail with a clear message pointing at `docs/dev/rust.md`). ## Follow-ups (not this PR) - The `wrld3_element_level_enumeration_is_uncapped` test in `src/simlin-engine/tests/wrld3_ltm_panic.rs` takes ~29s at this checkpoint. That is under the cap but worth gating behind `#[ignore]` per a later iteration-1 review comment. I am leaving it as-is in this PR to keep the diff narrow; it can be addressed in the next iteration on top of the safety rail. - The feedback-loop refinements from iterations 17-35 of PR #461 -- structural/synthesis cap split, FFI cache, pending_ltm_diagnostics capture, BTreeMap-deterministic summation, per-element `compute_rel_loop_scores`, etc. -- should be evaluated on their individual merits against this checkpoint, not bundled. Each should land in its own small PR so we can see which ones are load-bearing and which were premature.
PR #461 moved rel_loop_score normalization to post-simulation in ltm_post.rs, where the helpers re-sorted loop ids lexicographically (b1, b10, b2, ...) to pin determinism over the prior HashMap's hash-randomized iteration. That order is bit-level different from the removed compile-time emitter, which accumulated the partition-sum denominator in the loops' emission order; because IEEE-754 addition is non-associative the lex sort perturbs every dense-partition denominator at the ULP, so any consumer diffing timeseries across engine versions sees spurious diffs. Switch LtmVariablesResult.loop_partitions from HashMap to IndexMap (the issue's preferred approach) so its iteration order is the loops' emission order, and have the post-sim consumers walk map order instead of sorting. indexmap (already in the tree via salsa, which also supplies its salsa::Update impl) is added as a direct simlin-engine dependency and re-exported as engine::indexmap so libsimlin and the integration tests thread the IndexMap through without their own dependency. Emission order is the content-derived order assign_loop_ids produces (it sorts on the canonical edge-sequence rotation, not on HashMap enumeration -- ltm::graph::loop_id_sort_key), so it is deterministic across salsa cache invalidations and across processes; IndexMap's order-insensitive PartialEq (used for salsa cache equality) therefore never causes spurious invalidation while the iteration order stays fixed. A sibling change (#487) had already made loop_partitions per-slot (Vec<Option<usize>>); only the map container changes here. reclassify_loops_from_results and the FFI debug-assert only do per-id lookups, so they are order-agnostic; the libsimlin streaming-denominator path (ensure_denom_for_element) iterated the map directly, so it now sums in emission order too, matching the engine's full-sweep helper. GH #468.
Summary
MAX_LTM_CIRCUITS = 100_000safety cap and replace it with a principled structural gate:MAX_LTM_SCC_NODES = 50triggers auto-flip to discovery mode when any element-level SCC exceeds the threshold, with a Warning diagnostic surfaced throughmodel_all_diagnostics.rel_loop_scorefrom compile-time synthetic equations to post-simulation computation (ltm_post::compute_rel_loop_scores). Eliminates the O(P^2) equation-text blowup that previously projected to ~140 TB on WRLD3.Why
Simlin's WASM target has a 4 GiB linear-memory ceiling. Running LTM on WRLD3 with the previous pipeline needed on the order of 15-60+ GiB of intermediate state:
build_element_level_loopsmaterialized 1.86M Loop structs (mean 47 Link entries each) for ~17 GiB by itself.rel_loop_scoreequation text was O(P^2) per partition — 75 MB per equation times 1.86M equations ~= 140 TB projected.The 100k circuit cap hid this by returning empty on budget exhaustion, so raising it exposed the downstream cliffs. See
docs/design-plans/2026-04-18-ltm-cap-lift-diagnosis.mdfor the measured trace anddocs/design-plans/2026-04-18-ltm-cap-lift-options.mdfor the design rationale.How
src/simlin-engine/src/db_ltm.rs): compute the largest element-level SCC before callingbuild_element_level_loops. If it exceedsMAX_LTM_SCC_NODES = 50, take theis_discoverybranch internally and emit a Warning through theCompilationDiagnosticaccumulator. The paper's prescribed two-tier strategy; Simlin had both modes but no automatic switch.src/simlin-engine/src/ltm_post.rs):compute_rel_loop_scores(results, loop_partitions)normalizesloop_scoretimeseries against the sum-of-absolutes per partition.LtmVariablesResult::loop_partitionscaches the loop-to-partition mapping. Two consumers migrated:libsimlin::simlin_analyze_get_relative_loop_scoreFFI andlayout/mod.rsfeedback-loop metadata.src/simlin-engine/src/ltm.rs):MAX_LTM_CIRCUITS,RUNTIME_LTM_CIRCUIT_BUDGET,set_max_ltm_circuits,default_max_ltm_circuits,current_ltm_circuit_budget, and the three default-budget wrappers deleted.TruncatedByBudgetand*_with_limitkept as the general form.model_all_diagnosticsdid not invokemodel_ltm_variables, so the auto-flip Warning was invisible to FFI callers. Fixed with a gated call + regression test.compute_rel_loop_scores.Test plan
cargo test -p simlin-engine --release-- 3045 engine tests passcargo test --release --features file_io --test simulate_ltm-- 45/45 including bit-for-bit preservation of thetest/logistic_growth_ltm/ltm_results.tsvgolden TSVcargo test --release --features file_io --test wrld3_ltm_panic-- both tests pass in 1.63s total (was SIGKILL/OOM pre-fix)pnpm build+pnpm test-- green via pre-commit hook on every commitarrayed_population.stmx(6 circuits, SCC small) stays exhaustive, 3.8ms / 10.5 MiBcross_element.stmx(12 circuits, SCC small) stays exhaustive, 5.0ms / 10.5 MiB