Skip to content

engine: enable LTM always-on via auto-flip + post-sim rel_loop_score - #461

Merged
bpowers merged 35 commits into
mainfrom
ltm-perf-enable-always
Apr 19, 2026
Merged

bpowers merged 35 commits into
mainfrom
ltm-perf-enable-always

Conversation

@bpowers

@bpowers bpowers commented Apr 19, 2026

Copy link
Copy Markdown
Owner

Summary

  • Remove the MAX_LTM_CIRCUITS = 100_000 safety cap and replace it with a principled structural gate: MAX_LTM_SCC_NODES = 50 triggers auto-flip to discovery mode when any element-level SCC exceeds the threshold, with a Warning diagnostic surfaced through model_all_diagnostics.
  • Move rel_loop_score from 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.
  • WRLD3 (1,863,803 elementary circuits, one 166-node SCC) now compiles with LTM enabled in ~1.6s at 467 MiB VmPeak, down from OOM/SIGKILL in >15 GiB.

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_loops materialized 1.86M Loop structs (mean 47 Link entries each) for ~17 GiB by itself.
  • rel_loop_score equation 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.md for the measured trace and docs/design-plans/2026-04-18-ltm-cap-lift-options.md for the design rationale.

How

  1. Auto-flip gate (src/simlin-engine/src/db_ltm.rs): compute the largest element-level SCC before calling build_element_level_loops. If it exceeds MAX_LTM_SCC_NODES = 50, take the is_discovery branch internally and emit a Warning through the CompilationDiagnostic accumulator. The paper's prescribed two-tier strategy; Simlin had both modes but no automatic switch.
  2. Post-sim rel_loop_score (src/simlin-engine/src/ltm_post.rs): compute_rel_loop_scores(results, loop_partitions) normalizes loop_score timeseries against the sum-of-absolutes per partition. LtmVariablesResult::loop_partitions caches the loop-to-partition mapping. Two consumers migrated: libsimlin::simlin_analyze_get_relative_loop_score FFI and layout/mod.rs feedback-loop metadata.
  3. Cap removal (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. TruncatedByBudget and *_with_limit kept as the general form.
  4. Diagnostic visibility fix: model_all_diagnostics did not invoke model_ltm_variables, so the auto-flip Warning was invisible to FFI callers. Fixed with a gated call + regression test.
  5. Corner tests (adversarial): disjoint-SCC keying (largest, not sum), user-discovery suppression (no double-warning), element-level SCC sizing for A2A loops, NaN propagation contract in compute_rel_loop_scores.

Test plan

  • cargo test -p simlin-engine --release -- 3045 engine tests pass
  • cargo test --release --features file_io --test simulate_ltm -- 45/45 including bit-for-bit preservation of the test/logistic_growth_ltm/ltm_results.tsv golden TSV
  • cargo 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 commit
  • pysimlin tests pass (pre-commit hook)
  • WRLD3 end-to-end at cap=100k / 2M / usize::MAX -- all three produce identical output (483 link scores, auto-flip fires), peak 467 MiB, wall ~1.6s
  • arrayed_population.stmx (6 circuits, SCC small) stays exhaustive, 3.8ms / 10.5 MiB
  • cross_element.stmx (12 circuits, SCC small) stays exhaustive, 5.0ms / 10.5 MiB

@bpowers
bpowers force-pushed the ltm-perf-enable-always branch from 7dd299e to 577dbce Compare April 19, 2026 14:01

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

Comment thread src/libsimlin/src/analysis.rs Outdated
} else {
};

let ltm = engine::db::model_ltm_variables(&*db_locked, synced_model.source, sync.project);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment thread src/libsimlin/src/analysis.rs Outdated
return;
};

let scored = engine::ltm_post::compute_rel_loop_scores(results, &ltm.loop_partitions);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

@claude

claude Bot commented Apr 19, 2026

Copy link
Copy Markdown

Code review

[P2] model_detected_loops is now unbounded with no SCC backstop on the layout + FFI paths

src/simlin-engine/src/db_analysis.rs:1079-1088

With MAX_LTM_CIRCUITS retired, model_detected_loops now calls find_loops_with_limit(usize::MAX).expect(...) and has no upstream gate analogous to the largest_scc_size() > MAX_LTM_SCC_NODES auto-flip added to model_ltm_variables in db_ltm.rs. This tracked function is invoked unconditionally by simlin_analyze_get_loops (src/libsimlin/src/analysis.rs:71) and by try_detect_ltm_loops_incremental (src/simlin-engine/src/layout/mod.rs:3827) — both production code paths, one reached from every FFI embedder (WASM/Go/C) and the other from diagram layout. On a WRLD3-shape input (166-node SCC, ~1.86M variable-level circuits) Johnson's algorithm enumerates every circuit and then materializes a fully polarity-analyzed Vec<Loop> whose Link storage alone runs to tens of millions of entries, comfortably exceeding the 4 GiB WASM budget that the validation doc targets. Previously the 100k cap short-circuited both call sites into an empty result; after this PR they will crash or OOM instead. The auto-flip only guards the compilation pipeline the ltm-cap-lift-validation.md doc exercised; model_detected_loops needs an equivalent SCC-size check (or a reintroduced bound with graceful empty fallback) before the same class of model hits the FFI/layout.

Overall correctness

Auto-flip + post-sim rel_loop_score is a sound structural fix for the O(P²) equation-text cliff and the build_element_level_loops memory cliff on the compilation path, and the compute_rel_loop_scores SAFEDIV-0 semantics + proptest coverage look correct. The gap is that the cap removal propagated beyond the paths the auto-flip guards: model_detected_loops is now unbounded on the FFI and layout entry points, so models that previously returned "no loops" will instead blow out memory. Address the model_detected_loops gating before landing; otherwise LGTM modulo that regression.

@claude

claude Bot commented Apr 19, 2026

Copy link
Copy Markdown

Review

Overall the patch looks correct and the design trade-offs (cap removal, post-sim normalization, auto-flip on largest SCC, cached loop_partitions) are well justified in the accompanying design plans and validated by tests. Lock order in the new simlin_analyze_get_relative_loop_score matches the existing db -> sync_state -> state discipline, so no deadlock risk. compute_rel_loop_scores is deterministic despite the HashMap<Option<usize>, Vec<usize>> iteration (each partition writes into disjoint indices; sums within a partition walk sorted indices), and SAFEDIV-0 semantics match the removed equation exactly.

Findings

[P3] simlin_analyze_get_rel_loop_score recomputes all loops per call — src/libsimlin/src/analysis.rs:405-468
The FFI now calls compute_rel_loop_scores(results, &loop_partitions) on every invocation and then does a HashMap::get(loop_id) lookup. Typical callers (diagram UI, MCP) query one loop at a time across many timesteps, so each call does O(S × P) work where only a single series is returned. Consider either (a) memoizing the full HashMap<String, Vec<f64>> on the SimlinSim until the next reset/step, or (b) adding a cheap single-loop path that sums only the owning partition. Not a correctness bug — flagging as a performance foot-gun for dense-partition models where P can reach the thousands.

[P3] model_detected_loops / model_loop_circuits now uncapped — src/simlin-engine/src/db_analysis.rs
Switching these to _with_limit(usize::MAX).expect(...) is consistent with moving the budget check to auto-flip, and the element-level SCC gate in model_ltm_variables keeps pathological LTM enumeration in check. But non-LTM callers of model_detected_loops / model_loop_circuits (analysis.rs, layout metadata) no longer have any guard. A synthetic model that's within the SCC threshold but has a combinatorial blow-up in cycle count (e.g., dense feedback without LTM enabled) would hang these paths. In practice user models don't look like that, and the design plan explicitly accepts this trade; noting so the trade-off is on the record for future triage.

Verdict

Correct. No blocking issues — the two P3 items above are worth considering but neither gates the merge.

@claude

claude Bot commented Apr 19, 2026

Copy link
Copy Markdown

Reviewed the full diff (engine, libsimlin FFI, layout, tests, docs).

Traced the two auto-flip gates (element-level SCC in model_ltm_variables, variable-level SCC in model_detected_loops), the post-sim compute_rel_loop_scores (BTreeMap keyed by partition for deterministic float-sum order, SAFEDIV semantics matching the reference formula via proptest to 1e-10), the model_all_diagnostics → model_ltm_variables wiring that surfaces auto-flip warnings through the salsa accumulator, the FFI change in simlin_analyze_get_relative_loop_score (lock db+sync_state, recompute partitions, then lock state for results), and the layout-path capture of loop_partitions before toggling set_ltm_enabled back to false.

No P0/P1/P2/P3 findings. The changes are well-covered by the 45 integration tests in simulate_ltm.rs, the wrld3 adversarial test asserting 1.86M circuits uncapped at the element level, positive/negative diagnostic-surfacing tests, and the per-element rel_loop_score helper.

overall correctness: correct

bpowers added 18 commits April 19, 2026 07:47
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.
@bpowers
bpowers force-pushed the ltm-perf-enable-always branch from 19bbced to 5c1daf6 Compare April 19, 2026 14:47
@claude

claude Bot commented Apr 19, 2026

Copy link
Copy Markdown

PR review

No findings.

I checked the hot spots:

  • ltm_post::compute_rel_loop_scores — BTreeMap for deterministic partition iteration is correctly justified and load-bearing (float-sum order under HashMap randomization would otherwise drift bit-for-bit between runs, invisible to the 1e-10 proptest tolerance). SAFEDIV-0 semantics, NaN propagation contract, and absent-offset omission all covered by unit + property tests.
  • Snapshot of loop_partitions at simlin_sim_new (libsimlin/src/simulation.rs:56-108) — correct lookup via engine::canonicalize(&model_ref.model_name) against the canonical-keyed sync.models. Capture happens before set_project_ltm_enabled(db, _, false) so a concurrent patch can't invalidate the mapping. Matching snapshot in layout/mod.rs:3850-3865.
  • Auto-flip gate (db_ltm.rs:2055+) — two-stage (largest SCC pre-enum + total-circuits post-enum) with explicit test_auto_flip_keys_on_largest_scc_not_total_nodes, test_auto_flip_on_total_circuits_above_threshold, and test_user_discovery_mode_does_not_emit_auto_flip_warning. Warning routed through model_all_diagnostics with a regression test for the previously-invisible-to-FFI path.
  • MAX_LTM_TOTAL_CIRCUITS = 10_000 cap on model_detected_loops (db_analysis.rs:1064-1106) — reduction from the prior 100K default is documented as intentional ('dense graphs like WRLD3 truncate and return empty so callers fall back to analyze_model's discovery-mode output') and matches the db_ltm.rs backstop so FFI/layout consumers stay consistent.
  • LTM_BENCH_TRACE instrumentation in ltm_augment::generate_loop_score_variables — deliberately preserved with justification comments. .is_ok() activating on any value (including =0) is a minor quirk, but given the explicit docstring (LTM_BENCH_TRACE=1) and opt-in framing, this is not worth changing.

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 (model_all_diagnostics -> model_ltm_variables) closes a real gap. Tests cover disjoint-SCC keying, user-discovery suppression, A2A SCC sizing, NaN propagation, and WRLD3 element-level enumeration uncapped — the failure modes I'd worry about are exactly the ones the new tests exercise.

@claude

claude Bot commented Apr 19, 2026

Copy link
Copy Markdown

PR #461 review

I walked the full diff carefully: the auto-flip gate in db_ltm::model_ltm_variables (element-SCC size + total-circuit backstop), the new post-sim ltm_post::compute_rel_loop_scores with SAFEDIV-0 semantics and BTreeMap-sorted determinism, the budgeted detect_loops/find_loops_with_limit plumbing (usize::MAX is safe since it's never exhausted on this path), the SimState::loop_partitions snapshot captured in simlin_sim_new before the LTM flag is reset, the layout incremental path that re-fetches partitions before flipping LTM back off, and the new unified tests covering the 51-node threshold, total-circuit gate, user-discovery path bypass, and element-level SCC keying for arrayed models. The warning emission via the CompilationDiagnostic accumulator correctly distinguishes the auto-flip vs user-discovery paths, and the rel-loop-score equality with the pre-PR synthetic-equation formula is covered by the proptest.

No findings.

overall correctness

correct

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

claude Bot commented Apr 19, 2026

Copy link
Copy Markdown

Review: LTM always-on via auto-flip + post-sim rel_loop_score

Thorough 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)

  • [P2] compute_rel_loop_scores BTreeMap grouping — src/simlin-engine/src/ltm_post.rs: using BTreeMap<Option<usize>, Vec<_>> to group partitions gives deterministic iteration order, which matters because downstream consumers may fingerprint or diff the resulting score map. Worth a one-line comment noting the ordering is load-bearing so a future refactor does not swap it for HashMap.

  • [P2] Invariant coupling between estimate_emitted_loop_count and build_element_level_loops — src/simlin-engine/src/db_ltm.rs: the estimator mirrors the collapse logic (pure-A2A→1, cross-element with has_repeated→1, mixed-leading-subscripts→1, otherwise group size). These two functions have to stay in lockstep or the auto-flip gate misfires. Consider a doc comment on each that points at the other, or — better — a small unit test that exercises each branch through both functions and asserts agreement.

  • [P3] largest_scc_size return semantics — src/simlin-engine/src/ltm.rs: returns 0 for the no-edge graph and ≤1 for acyclic graphs with self-edges. Call sites only use it as > MAX_LTM_SCC_NODES, so this is fine, but the semantics (SCC size as measured for loop-enumeration purposes, so singletons without self-edges are size 0) deserves a short rustdoc note.

  • [P3] Cache invalidation of cached_rel_scores — src/libsimlin/src/simulation.rs: invalidated on run_to_end, reset, set_value_by_offset. Those are the three paths that mutate state.results today. If a new mutation path is added (e.g. partial re-run, rewind), the cache will silently go stale. A debug_assert on results-pointer identity, or a comment on the cache field listing the invalidation sites, would make the coupling enforceable.

  • [P3] LTM_BENCH_TRACE telemetry — src/simlin-engine/src/ltm_augment.rs: the opt-in trace with read_rss_mib is Linux-only. A one-line comment to that effect near the cfg gate would save a future reader the confusion of seeing nothing on macOS/Windows.

Things I verified and have no concern with

  • model_detected_loops uses the variable-level cap (MAX_LTM_TOTAL_CIRCUITS) and model_element_loop_circuits uses the element-level enumeration cap (MAX_LTM_ENUMERATION_CAP) — correct separation.
  • loop_partitions snapshot in libsimlin is captured under the db lock alongside VM compilation, so it cannot race with a project edit.
  • The layout auto-flip fallback correctly treats detected.truncated as "no incremental result" and falls through to persisted loop_metadata.
  • LoopCircuitsResult::is_empty() returns true when truncated (the circuits Vec is empty), which is the intended signal to downstream consumers.
  • User-discovery mode short-circuits before the auto-flip warning is emitted, so users who opted into the expensive path do not get a spurious warning.

Overall correctness: correct

I 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.

bpowers added 2 commits April 19, 2026 10:51
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.
@claude

claude Bot commented Apr 19, 2026

Copy link
Copy Markdown

Review

Overall the patch is well-structured: the move of rel_loop_score from compile-time emission to post-simulation computation in ltm_post.rs is the right call, and the auto-flip gate design (post-collapse emit cap + streaming Johnson's cap) is well-motivated by the 2026-04-18 diagnosis. Found one documentation defect worth fixing before merge.

[P3] Duplicated ## Why 10_000 doc section on MAX_LTM_TOTAL_CIRCUITS

src/simlin-engine/src/ltm.rs lines 33–57: two consecutive ## Why 10_000 subsections appear in the doc comment for MAX_LTM_TOTAL_CIRCUITS, with overlapping and slightly inconsistent content (the first cites ~90 MB for 10_000 Loop structs, the second cites ~130 MB for 10_000 loops + loop_score equations). Readers rendering the rustdoc will see two identically-titled sections back-to-back. Collapse into a single section — the ~90 MB figure is the one consistent with the rest of the prose (which explicitly notes rel_loop_score was moved post-sim), and the ~4 KB/loop_score-equation figure can be folded into that same paragraph if worth keeping.

/// ## Why 10_000
///
/// The 2026-04-18 LTM cap-lift diagnosis
/// (`docs/design-plans/2026-04-18-ltm-cap-lift-diagnosis.md`) measured
/// two structural cliffs on WRLD3's 166-node SCC:
///
/// - Cliff A: `build_element_level_loops` allocates ~17 GB of
///   `Loop`/`Link` structs for 1.86M enumerated circuits.
/// - Cliff B: each `rel_loop_score` equation is 75,303,840 bytes
///   (~75.3 MB); full emission projects to ~140 TB of equation text
///   (mitigated separately by the move to post-sim
///   [`crate::ltm_post::compute_rel_loop_scores`]).
///
/// Cliff A remains the live constraint this gate addresses. At ~9 KB
/// per `Loop` struct plus ~4 KB per emitted `loop_score` equation,
/// 10_000 distinct Loops cost ~130 MB of intermediate state --
/// comfortable inside WASM's 4 GiB budget with room for the rest of
/// the compile pipeline. Every in-tree LTM test model is well under
/// this; only synthetic array-expansion pathology or models at the
/// scale of WRLD3 trip it.
pub const MAX_LTM_TOTAL_CIRCUITS: usize = 10_000;

Overall correctness

LGTM modulo the duplicated doc heading above. The post-sim compute_rel_loop_scores path (SAFEDIV-0 semantics, BTreeMap for deterministic iteration, proptest coverage) looks sound, and the caching on SimState::cached_rel_scores in simlin_analyze_get_relative_loop_score correctly invalidates with simulation state. The wrld3_element_level_enumeration_is_uncapped regression test anchors the intent well.

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

claude Bot commented Apr 19, 2026

Copy link
Copy Markdown

Code review — PR #461 engine: enable LTM always-on via auto-flip + post-sim rel_loop_score

Scope reviewed: full 4,259-add / 401-del diff across 23 files. Read in full: ltm.rs, db_ltm.rs, db_analysis.rs, ltm_post.rs, layout/mod.rs, libsimlin/src/{analysis,simulation,lib}.rs, plus design plans and all three test files.

Findings


[P2] simlin_analyze_get_relative_loop_score error message omits two of four "empty loop_partitions" cases — src/libsimlin/src/analysis.rs:459-468

The message branches on state.loop_partitions.is_empty() and explains it as "either LTM was not enabled [...] or the auto-flip threshold [was tripped]". But model_ltm_variables also returns empty loop_partitions when (a) edges_result.stocks.is_empty() (stockless model) and (b) project.ltm_discovery_mode(db) == true (user explicitly selected discovery). A caller who queries rel_loop_score on a stockless model or a discovery-mode run will see a message pointing them at the wrong root cause.

Low impact — users who ran discovery mode aren't expecting per-loop scores — but the message is user-facing diagnostic text and a mis-direction here will waste someone's time. Consider expanding to four cases or generalizing: "LTM did not materialize per-loop scores for this simulation (LTM disabled, discovery mode, stockless model, or auto-flipped past MAX_LTM_TOTAL_CIRCUITS / MAX_LTM_ENUMERATION_CAP)".


[P3] estimate_emitted_loop_count and build_element_level_loops are tightly coupled on collapse semantics; no compile-time guard catches drift — src/simlin-engine/src/db_ltm.rs:1769-1859 vs 1896-2149

The two functions must agree on the per-group emit count (pure-A2A → 1, cross-element → 1 gated on unique_cycle_len >= 2, scalar/mixed → group.len()). The doc comment on estimate_emitted_loop_count explicitly acknowledges the mirroring ("This function mirrors the exact collapse criteria of build_element_level_loops"). I worked through the branches side-by-side and they match today, including the subtle unique_cycle_len >= 2 gate on the repeated-name case.

Risk: a future change to the is_cross_element detector (e.g., loosening/tightening the leading-subscript comparison, or handling a new "partial-collapse" shape) will silently desync the gate. Since both functions walk the same grouping, a cheap debug_assert_eq!(estimate_emitted_loop_count(circuits), actual_emitted.len()) inside build_element_level_loops when both run on the same input would catch drift in tests without costing anything in release. Not required for this PR — raising it because the coupling is load-bearing for the backstop's soundness.


[P3] ltm::detect_loops has no remaining callers; dead public API — src/simlin-engine/src/ltm.rs:2048-2053

Grep across the repo only finds this function in docs and its own definition. The .expect("usize::MAX budget cannot be exhausted by Johnson's enumeration") is defensively sound, but if nothing calls it, the simpler fix is to delete it. (All real callers went through the db_analysis tracked functions per the 2026-03-30-remove-interpreter plan.) Per the root CLAUDE.md's "simple, general, testable" rule and the lack of serialized-to-disk concerns on internal Rust APIs, consider removing — either in this PR or a follow-up.


[P3] A2A loops lose per-element granularity at the FFI — src/libsimlin/src/analysis.rs:441

FFI path calls compute_rel_loop_scores (scalar — slot 0 only) even though compute_rel_loop_scores_per_element exists in ltm_post.rs. The doc comment on the latter acknowledges the FFI keeps scalar semantics to match pre-PR behavior, which is correct — pre-PR's compile-time rel_loop_score synthetic was A2A, but reading it through the scalar FFI offset also collapsed to slot 0. Flagging as a documentation-only observation so future readers know per-element data is already computable, just not surfaced. Not a blocker for this PR.


Things I verified and liked

  • cached_rel_scores invalidated in all three mutation paths (run_to_end, reset, set_value_by_offset). run_to correctly doesn't need invalidation because state.results is only populated by run_to_end (which consumes state.vm.take()), so the cached/uncached states stay in sync.
  • BTreeMap (not HashMap) used for partition grouping in compute_rel_loop_scores — correct choice given float-sum non-associativity and the justification in the rationale comment (lines 74-81).
  • SAFEDIV-0 semantics preserved (denom == 0.0 → 0.0, else division); NaN propagation test covers the "sum of NaN" path so regressions in IEEE-754 handling can't land silently.
  • model_detected_loops returning truncated: true with empty loops (rather than panicking / silently collapsing) preserves the "acyclic vs over-budget" distinction downstream consumers need — layout mod.rs:3838-3840 consumes this signal to trigger the persisted-metadata fallback exactly where expected.
  • The auto-flip gate's decision to key on post-collapse emit count (via estimate_emitted_loop_count) rather than raw circuit count correctly keeps pure-A2A large-dimension models (1 Loop struct after collapse) on the exhaustive path — the 2026-04-18 diagnosis doc walks through why the earlier largest-SCC heuristic was wrong for that shape.
  • WRLD3 regression has a dedicated wrld3_ltm_panic.rs test, the 3,045 engine tests + 45 simulate_ltm tests all pass per the validation doc, and the design was adversarially reviewed by a second team before merge.
  • MAX_LTM_ENUMERATION_CAP = 1_000_000 streaming cutoff inside Johnson's DFS (not post-materialization) is the right change — WRLD3's raw-emission blowup used to hold ~350 MB of Vec<Vec<u32>> state before dedup; the new path trips at ~9 MB per the ltm.rs:1243-1247 rationale.

Overall correctness

LGTM — no blocking findings. The P2 and P3 items above are minor diagnostic/cleanup polish. The core change set (replacing a hard 100K cap with a layered gate: streaming MAX_LTM_ENUMERATION_CAP cutoff during enumeration, post-collapse MAX_LTM_TOTAL_CIRCUITS gate on emit count, and post-sim rel_loop_score normalization replacing O(P²) equation-text emission) is correct and well-justified. Memory-cliff diagnosis in the design plan is specific, the test coverage targets both of the cliffs the diagnosis called out, and FFI consumers get a sensible fallback path (structural loops with empty importance series) instead of losing topology entirely when the model auto-flips.

Nothing else to raise. Ship it.

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

claude Bot commented Apr 19, 2026

Copy link
Copy Markdown

Review

Investigated the cap-lift architecture end-to-end: ltm_post::compute_rel_loop_scores and the per-element variant and their tests, the auto-flip gate in model_ltm_variables (circuits_result.truncated || estimated_loops > MAX_LTM_TOTAL_CIRCUITS), estimate_emitted_loop_count vs. build_element_level_loops (collapse rules match branch-for-branch — pure-A2A=1, cross-element via repeated names=1 iff unique_cycle_len >= 2, cross-element via mixed leading subscripts=1, scalar/mixed=group.len()), the streaming cutoffs in JohnsonState (> distinct_limit / > node_limit with per-SCC saturating_sub accounting), and the FFI cache plumbing in libsimlin/src/simulation.rs.

Findings

Nothing rises to [P2] or above. Two [P3] observations:

[P3] compute_rel_loop_scores scalar variant silently collapses A2A loops to slot 0. ltm_post.rs:106 reads row[off].abs() for the denominator sum, so an A2A partition's denominator is the first-element sum rather than a sum across all elements. This matches the pre-PR FFI return shape (documented at ltm_post.rs:131-138), but the layout consumer at layout/mod.rs now feeds this collapsed scalar into loop metadata where the pre-PR compile-time emitter would have produced per-element rel_loop_score variables. Given pre-PR layout also only read the scalar offset, this is behaviourally identical today — but a future caller that assumes "relative score" is per-element in layout metadata would be quietly wrong. A one-line doc pointer in layout/mod.rs back to compute_rel_loop_scores_per_element would prevent that drift.

[P3] Auto-flip to discovery silently drops rel_loop_score for callers. When estimated_loops > MAX_LTM_TOTAL_CIRCUITS, model_ltm_variables flips to discovery and loop_partitions stays empty (db_ltm.rs:2187,2258,2362), so simlin_analyze_get_relative_loop_score returns an empty map on dense models that previously would have returned a (wrong, but non-empty) series. The compilation diagnostic at db_ltm.rs:2302-2318 explains this to users who read warnings, but programmatic consumers get a silent empty HashMap. Arguably correct, but worth mentioning in the function-level docstring on compute_rel_loop_scores since the current wording ("loops whose loop_score is absent... are omitted") conflates "LTM off" with "LTM auto-flipped by cap."

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 (ltm_post.rs:74-81) is the kind of non-obvious decision that's correctly documented inline. Cache invalidation in libsimlin/src/simulation.rs is placed on every path that mutates state.results (run_to_end, reset, set_value_by_offset) and correctly not placed on run_to, set_value, or clear_values (which touch VM state but not saved results). The estimate/emit count match is the one place a drift bug would have been easy to introduce and would silently break the auto-flip gate, so the line-by-line parallelism there is load-bearing and worth preserving under future refactors of build_element_level_loops.

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

claude Bot commented Apr 19, 2026

Copy link
Copy Markdown

Took a full pass at this. The core design — auto-flip gate + post-sim rel_loop_score — is sound: estimate_emitted_loop_count faithfully mirrors build_element_level_loops's per-group collapse rules (pure-A2A → 1, cross-element-by-repeated-vars → 1 when unique_cycle.len() >= 2, cross-element-by-differing-leading-subscripts → 1, scalar/mixed → group.len()), the streaming distinct_limit + node_limit pair in JohnsonState correctly guards both failure modes, and loop_partitions is captured in try_detect_ltm_loops_incremental and at simlin_sim_new time before LTM is turned back off so the post-sim normalization has the mapping it needs. The libsimlin cached_rel_scores invalidation covers run_to_end, reset, and set_value_by_offset — which are the only mutators of state.results. compute_rel_loop_scores in ltm_post.rs uses BTreeMap (deterministic partition iteration, important because float sum isn't associative) and applies SAFEDIV-0 at the partition level, matching what the pre-PR compile-time equation did. The test matrix in db_ltm_unified_tests.rs exercises both auto-flip triggers (total-circuits overflow and truncation via enumeration caps), the user-discovery no-warning case, and the sparse-large-SCC / pure-A2A-over-large-dimension cases that the iter-13 SCC-size heuristic got wrong.

One finding:

[P3] model_detected_loops docstring references the wrong constant. In src/simlin-engine/src/db_analysis.rs the top-of-function docstring at lines 1102–1108 says "Bounded by [`crate::ltm::MAX_LTM_TOTAL_CIRCUITS`]" and "The same threshold is the backstop inside `model_ltm_variables`". Neither is true for the implementation below it — lines 1152–1154 call `find_loops_if_under_limit_ex(MAX_LTM_DETECTED_LOOPS, MAX_LTM_ENUMERATION_NODES)`, and the body comment at 1132–1143 correctly explains that the structural-only cap (100_000) is deliberately split from the LTM-synthesis cap (10_000). The inline comment is right; only the docstring is stale. Worth fixing so a future reader opening `model_detected_loops` from its signature doesn't walk away with the wrong threshold in their head.

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

claude Bot commented Apr 19, 2026

Copy link
Copy Markdown

Review

Read through the engine changes (ltm.rs, ltm_post.rs, db_ltm.rs, db_analysis.rs, db.rs, layout/mod.rs, ltm_augment.rs), the libsimlin FFI diffs (lib.rs, simulation.rs, analysis.rs, patch.rs, project.rs), and the added tests. The core transformation — replacing O(P²) compile-time rel_loop_score synthesis with a post-simulation pass, adding streaming distinct-count and enumeration caps, and threading auto-flip diagnostics through salsa → libsimlin → simlin_project_get_errors — is well-structured and correctly handles the tricky cases (snapshot isolation across patches, cache invalidation on results mutation, element-level SCC sizing, user discovery suppression).

Findings

[P3] is_ltm_diagnostic substring match is fragile under message-text edits

src/libsimlin/src/simulation.rs: the filter keys on the phrases "discovery mode" and "MAX_LTM_TOTAL_CIRCUITS" appearing in DiagnosticError::Assembly(msg). If a future edit to model_ltm_variables rewords either warning (for example, renames the constant or localises the copy) these diagnostics would silently stop being captured on pending_ltm_diagnostics — the salsa accumulator re-runs without LTM after ltm_enabled resets and drops them, so the regression would only be caught by the existing test_auto_flip_warning_surfaces_via_get_errors_after_sim_new integration test.

Consider tagging the engine-side diagnostic (e.g. DiagnosticTag::LtmCapacity) so the filter becomes matches!(diag.tag, Some(DiagnosticTag::LtmCapacity)). Non-blocking — the rationale comment is present and the happy path is guarded.

[P3] partition_key fallthrough pollutes the denominator cache for unknown loop ids

src/libsimlin/src/analysis.rs: when loop_partitions is non-empty but loop_id is unknown, state.loop_partitions.get(loop_id).copied().flatten() yields None, which inserts the None-bucket denominator into the cache even though we immediately hit the error path when compute_rel_loop_score_for_id returns None. The cached entry is numerically correct for real None-partition loops so it's not a bug, but every bogus lookup pays the denominator scan. A cheap guard would avoid it and tighten the two-message distinction the code already makes:

    let partition_key = match state.loop_partitions.get(loop_id).copied() {
        Some(key) => key,
        None if state.loop_partitions.is_empty() => None,
        None => {
            store_error(
                out_error,
                SimlinError::new(SimlinErrorCode::DoesNotExist).with_message(format!(
                    "loop '{loop_id}' is not in the LTM partition map for this \
                     simulation; verify the id returned by simlin_analyze_get_loops"
                )),
            );
            return;
        }
    };

Overall correctness

Looks correct. The post-sim normalization preserves SAFEDIV-0 semantics; the partition-granularity cache is invalidated on every path that mutates state.results (run_to_end, reset, set_value_by_offset) and correctly not invalidated on run_to since that only advances the VM without publishing results; loop_partitions snapshotting at sim_new insulates post-sim reads from concurrent patches; and estimate_emitted_loop_count mirrors build_element_level_loops' collapse rules (pure-A2A → 1, cross-element via repeated names → 1 when unique_cycle_len >= 2, otherwise group.len()). The WRLD3 regression (wrld3_element_level_enumeration_is_uncapped asserting 1,863,803 circuits) plus the proptest coverage in ltm_post.rs give high confidence the cap-lift does not regress scoring on real models. Comfortable merging once the minor points above are either addressed or acknowledged.

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

claude Bot commented Apr 19, 2026

Copy link
Copy Markdown

Review

I reviewed the substantive code changes in src/simlin-engine/src/{ltm_post.rs,layout/mod.rs,db.rs,db_ltm.rs,ltm.rs,ltm_augment.rs} and src/libsimlin/src/{analysis.rs,simulation.rs,lib.rs}. The math, partition keying, NaN/SAFEDIV-0 handling, FFI cache lifetimes/invalidation, and diagnostic plumbing all check out:

  • ltm_post::compute_rel_loop_scores, compute_partition_denominator, and compute_rel_loop_score_for_id are bit-for-bit consistent (sorted IDs + BTreeMap groups), with the per_id_rel_loop_score_bit_parity_with_mixed_magnitudes test pinning the IEEE-754 ordering invariant.
  • The mixed-arity per-element path correctly drops short loops out of both denominator and numerator via elem_index and writes into preallocated zeroed slots so misaligned reads can't bleed across loops.
  • cached_partition_denominators is invalidated on simlin_sim_run_to_end, simlin_sim_reset, and set_value_by_offset — the three paths that mutate the saved results buffer.
  • model_all_diagnostics is correctly gated on project.ltm_enabled(db) to surface the auto-flip Warning, with simlin_sim_new capturing the LTM-specific subset into pending_ltm_diagnostics before flipping the flag back.
  • layout/mod.rs snapshots loop_partitions while LTM is enabled and intentionally falls through to empty importance_series when auto-flip fires (preserving topology/polarity while degrading only the behavioral score).

Minor (P3, optional)

  • src/libsimlin/src/analysis.rs:479-495 — the disambiguation branches based on state.loop_partitions.is_empty() only distinguish two cases. A third case (loop_partitions non-empty AND loop_id present in it AND loop_score_X absent from results.offsets) falls into the "not in the LTM partition map" arm and would mislead. In practice both sets are populated together by the same model_ltm_variables call so this is theoretical, but a short condition like if !state.loop_partitions.contains_key(loop_id) for the second message would close the gap.

Overall correctness

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

claude Bot commented Apr 19, 2026

Copy link
Copy Markdown

Review

I reviewed this PR focusing on the post-simulation rel_loop_score pipeline, the auto-flip gate logic, and the FFI diagnostic capture path. I traced:

  • ltm_post::{compute_rel_loop_scores, compute_rel_loop_scores_per_element, compute_partition_denominator, compute_rel_loop_score_for_id} and their determinism / SAFEDIV-0 semantics.
  • db_ltm::{estimate_emitted_loop_count, model_ltm_variables} auto-flip gate (circuits_result.truncated || estimated_loops > MAX_LTM_TOTAL_CIRCUITS) and its alignment with build_element_level_loops's per-group collapse rules.
  • The three caps (MAX_LTM_ENUMERATION_CAP, MAX_LTM_ENUMERATION_NODES, MAX_LTM_TOTAL_CIRCUITS) and how enumerate_indexed_circuits_ex uses saturating budgets.
  • The FFI capture path: simlin_sim_new partition snapshot → pending_ltm_diagnostics → append_captured_diagnostics dedup via (model, message).
  • Cache invalidation of cached_partition_denominators at run_to_end, reset, set_value_by_offset, and apply_patch.

Findings

None at P0/P1/P2/P3 that an author would fix.

Things I initially flagged and then cleared:

  • A2A slot-0 collapse in compute_rel_loop_scores / compute_partition_denominator. Potential concern that arrayed loops contribute only slot 0 to the denominator. Cleared: this is documented as matching pre-PR FFI semantics (which also returned a scalar series), and compute_rel_loop_scores_per_element exists for callers that need per-element normalization (pysimlin, future FFI).
  • Substring match in is_ltm_diagnostic (simulation.rs:43). Potential concern that "discovery mode" / "MAX_LTM_TOTAL_CIRCUITS" is fragile. Cleared: both auto-flip messages in db_ltm.rs:2298-2332 contain "discovery mode", unit tests assert the phrase, and the decoupling rationale from DiagnosticError classification is documented inline.
  • Dedup keying in append_captured_diagnostics. Uses (model_name, message) structural key rather than message alone, which survives formatter changes for multi-model projects — already has the test test_pending_ltm_diagnostics_multi_model_project.
  • Cache invalidation completeness. Verified: run_to_end (line 252), reset (line 320), set_value_by_offset (line 604), and apply_patch commit (patch.rs:611) all clear cached_partition_denominators / pending_ltm_diagnostics. run_to doesn't populate state.results so there's nothing to invalidate on that path.
  • Determinism of float summation. compute_rel_loop_scores, compute_rel_loop_scores_per_element, and compute_partition_denominator all sort loop ids before the sum and use BTreeMap for partition-group iteration — inline comments explain the IEEE-754 non-associativity rationale, and the proptest (ltm_post::tests) mirrors this ordering.
  • estimate_emitted_loop_count vs build_element_level_loops drift. The function documents its mirroring of the collapse criteria (pure-A2A: 1 per group; cross-element via repeated names or mismatched leading subscripts: 1 per group with unique_cycle_len >= 2 gate; scalar/mixed: group_indices.len()) and the disjoint-3-cycles regression test in tests/analysis.rs exercises the scalar path at the cap boundary.

Overall correctness

Correct. The PR is unusually well-commented — the key design decisions (post-sim normalization, partition snapshot at sim_new, structural dedup key, unconditional pending-slot overwrite, three-tier cap architecture) all have inline rationale referencing prior review cycles (iter-13, iter-18 codex P2) and the design plan at docs/design-plans/2026-04-18-ltm-cap-lift-diagnosis.md. Tests cover the auto-flip boundary, multi-model projects, repeated sim_new dedup, and the post-sim numerical equivalence via proptest against a reference implementation. I did not find any behavior an author would change.

@bpowers

bpowers commented Apr 19, 2026

Copy link
Copy Markdown
Owner Author

Completed iterative review cycle with /address-feedback. The branch has now passed through iterations 16-20 with both codex and claude reviewers; each iteration's feedback was addressed in a single atomic commit (8957b14, f55ba73, 3f6304a, d46ba7f).

High-level improvements layered on top of the original auto-flip + post-sim cap-lift work:

  1. Structural vs synthesis cap separation -- MAX_LTM_DETECTED_LOOPS = 100_000 gates structural consumers (layout, simlin_analyze_get_loops, simlin-cli --ltm) independently of the stricter MAX_LTM_TOTAL_CIRCUITS = 10_000 that governs LTM equation synthesis. Structural callers no longer lose topology information just because LTM synthesis would auto-flip. The node-count safety cap was raised from 10M to 100M to keep the distinct-circuit cap as the primary trigger on WRLD3-shape models, with the node cap remaining as the backstop for long-loop pathologies.

  2. Bounded FFI memory -- simlin_analyze_get_relative_loop_score previously materialized the full loop_count * step_count rel_score matrix on first call (~800 MB at the 10k-loop cap). Replaced with per-cycle-partition denominator caching that bounds peak memory at O(num_partitions * step_count), while still amortizing denominator work across the iterate-every-loop usage pattern. The same streaming pattern now applies in layout::try_detect_ltm_loops_incremental, cutting transient layout memory by an equivalent factor.

  3. Persistent LTM diagnostics -- simlin_sim_new(enable_ltm=true) resets the ltm_enabled flag after compile to avoid leaking LTM synthesis into later patch validation; that reset invalidated the salsa accumulator's LTM warnings and made simlin_project_get_errors() silent about models that auto-flipped. LTM-specific diagnostics are now captured on SimlinProject::pending_ltm_diagnostics at sim_new time and replayed through get_errors, with per-(model, message) dedup so multi-model projects do not lose one model's warning to another's. Cleared on apply_patch since patches can change which models trip the threshold.

  4. Determinism and test strength -- The post-sim rel_loop_score helpers now sort loop IDs before float summation in both the full-pass and streamed paths, keeping denominator bits stable across salsa cache invalidations. A new property-style test hashes with 16 fresh RandomState seeds to reliably catch a missing sort (verified to fail ~93% of the time with 8 trials, >99% with 16).

  5. Docstring and test hygiene -- Refreshed stale rustdoc in db_analysis.rs, renamed stale cap references in test assertion messages, consolidated duplicated comment blocks in the FFI, added a node-cap unit test for find_loops_if_under_limit_ex, added FFI integration tests covering both the auto-flip warning surfacing path and its dedup semantics, and fixed ltm_full_bench to mark truncation explicitly on dense models instead of reporting circuits=0.

Tracked as tech debt for future follow-up: dedicated integration coverage for the detected.truncated fallback branch (#467), and preserving the removed compile-time emitter's exact summation order so the post-sim path is bit-for-bit identical rather than only deterministic (#468, sub-ULP drift below all existing test tolerances).

@bpowers
bpowers merged commit 5f5f6cd into main Apr 19, 2026
8 of 10 checks passed
@bpowers
bpowers deleted the ltm-perf-enable-always branch April 19, 2026 22:25
bpowers added a commit that referenced this pull request Apr 21, 2026
bpowers added a commit that referenced this pull request Apr 24, 2026
## 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.
bpowers added a commit that referenced this pull request Jun 10, 2026
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant