Repository navigation
engine: re-land LTM always-on (auto-flip) + test timeout cap - #469
Conversation
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).
PR #461 was reverted after a single test binary in its suite ran for 44 minutes and the ubuntu CI job hit GitHub's 60-minute per-job cap. The underlying pathology was a test that built a ~30k-variable fixture (10,001 disjoint 3-cycles) to trip the production MAX_LTM_TOTAL_CIRCUITS = 10_000 gate -- the test's wall-clock was tied to the gate it was exercising, so every CI run paid the full gate cost, and doing it three times in a loop (to exercise dedup semantics) turned into 43 minutes. Nothing in pre-commit or CI noticed until the GitHub job cap fired. Wrap `cargo test` (pre-commit Pipeline A and CI Test step) and `cargo tarpaulin` (CI Coverage step) in `timeout(1)` from coreutils. No new third-party dep; GNU + BSD compatible so macos-latest runners work as-is. 180s is ~3x the post-revert CI baseline (~60s on ubuntu-latest, ~40s on macos-latest): a healthy run stays comfortably inside it, and any regression that pushes a single test binary into the minutes fails the build immediately instead of silently burning CI budget. Tarpaulin's 2700s outer cap (~1.9x its ~23-minute baseline) is belt-and-suspenders on top of its built-in per-test timeout, which caught the PR #461 blow-up at 8 minutes but only on the coverage job. Document the per-test budget (a few seconds on debug; 5s soft ceiling) and the anti-pattern that caused the disaster. Testing a production threshold gate by constructing a fixture large enough to trip it ties test runtime to the production constant; expose a test-only override and use a tiny fixture instead. Expensive tests that genuinely need to exercise a real-world case should be gated with #[ignore] and documented with an opt-in command.
Review findings[P2]
|
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 1f9381bf8f
ℹ️ 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".
| .find_loops_with_limit(usize::MAX) | ||
| .expect("usize::MAX cannot exhaust the enumeration budget"); |
There was a problem hiding this comment.
Restore a production cap in model_detected_loops
model_detected_loops now runs Johnson enumeration with usize::MAX, but interactive paths like layout::try_detect_ltm_loops_incremental and simlin_analyze_get_loops call this query directly before any model_ltm_variables auto-flip guard can apply. On dense models this can force full loop enumeration in user-facing flows (metadata/analysis), causing severe latency or memory blowups where the previous capped path would short-circuit safely.
Useful? React with 👍 / 👎.
| wait $PID_TEST | ||
| TEST_EXIT=$? |
There was a problem hiding this comment.
Capture cargo-test exit without tripping errexit
This script runs under set -e, so the bare wait $PID_TEST exits the subshell immediately on any non-zero test status (including timeout exits 124/137) before TEST_EXIT is read. That means the new diagnostic block is skipped exactly when needed, and contributors lose the intended failure/timeout guidance.
Useful? React with 👍 / 👎.
| # for per-test budget guidance. | ||
| - name: Test | ||
| run: cargo test --workspace | ||
| run: timeout --kill-after=30 180 cargo test --workspace |
There was a problem hiding this comment.
Make the CI timeout command portable to macOS runners
The build job runs on both ubuntu-latest and macos-latest, but this step now assumes GNU timeout with --kill-after. The workflow does not install coreutils on macOS, so the macOS leg can fail before executing tests due to missing/unsupported timeout invocation, turning the matrix red even when the code is fine.
Useful? React with 👍 / 👎.
macos-latest's GitHub runner does not have `timeout` on PATH, even though coreutils is pre-installed -- the binary is named `gtimeout` there. PR #469's first revision invoked `timeout` directly and the Build (macos-latest) job failed with "timeout: command not found" before running any tests. Pick whichever of `timeout` / `gtimeout` is on PATH in both scripts/pre-commit and the two timeout-wrapped CI steps. Document the macOS setup path (`brew install coreutils`) in docs/dev/rust.md. No flag differences between the two commands for the invocations we use (`--kill-after` + duration + command).
The previous attempt at macOS support assumed coreutils was pre-installed on macos-latest and provided `gtimeout`. It isn't -- neither `timeout` nor `gtimeout` is on PATH on the current runner image, so the `TIMEOUT_CMD=$(command -v timeout || command -v gtimeout)` lookup failed silently under `set -e` and the step exited 1 before any tests ran. Switch the CI Test and Coverage steps to GitHub Actions' step-level `timeout-minutes` field. It is portable across runner OSes, does not need any external tool, and GitHub's runner handles the SIGTERM -> SIGKILL sequence natively. Granularity is minutes, so 180s becomes `timeout-minutes: 3` and 2700s becomes `timeout-minutes: 45` -- effectively the same caps. scripts/pre-commit keeps the `timeout`/`gtimeout` lookup because it runs locally and needs to give a clear error when the tool is missing (with an install hint). Docs updated to describe the split.
Review findings[P2] Quadratic cost when iterating loops through
|
Review findings[P1] Timeout diagnostic never runs because
|
The Pipeline A subshell runs under `set -e`, and on the previous revision the bare `wait $PID_TEST` tripped errexit immediately on any non-zero test status -- including the 124/137 timeout exits this whole diagnostic block was added to surface. The subshell bailed out before `TEST_EXIT=$?` captured anything, so neither the test-failure output nor the new "180s wall-clock cap" hint ever printed. The outer pipeline just saw an empty log and a non-zero exit, which is exactly the no-context failure mode we were trying to avoid. Use the `wait $PID_TEST && TEST_EXIT=0 || TEST_EXIT=$?` pattern instead. The `&&`/`||` chain is an errexit-suppressing context that also captures the real exit code, unlike `wait || true` (which clobbers $? to `true`'s zero) or `if ! wait`'s `then` block (where $? is the `!` negation, not wait's exit). Verified by mirroring the subshell structure with `timeout --kill-after=1 1 sleep 30`: the failure message, the timeout hint, and the propagated exit=1 all appear as intended.
At ~29s in debug the test ate ~16% of the new 180s `cargo test` workspace cap -- a meaningful slice of the safety rail, consumed by a single test we chose to add. Document the opt-in `cargo test --release -- --ignored` invocation next to the test and let the sibling `wrld3_ltm_compilation_finishes_in_time` (which wraps the real compile path in its own 60s thread budget) cover every-push regressions of the pipeline that actually ships. The enumeration test still has value as an on-demand regression pin for Johnson's algorithm's raw output shape on WRLD3, which is why it stays in the tree rather than being deleted.
model_detected_loops runs Johnson's algorithm against the full variable-level causal graph with `find_loops_with_limit(usize::MAX)`, and is called directly by `simlin_analyze_get_loops` (FFI) and `layout::try_detect_ltm_loops_incremental` (diagram path). Neither caller goes through `model_ltm_variables`, so neither benefits from the SCC-size auto-flip gate that protects the LTM compilation pipeline. On a WRLD3-shape model (166-node SCC, 1.86M elementary circuits) that's seconds of CPU and gigabytes of intermediate state per call -- exactly the class of cost that motivated the LTM gate. Apply the same gate: when the largest SCC exceeds MAX_LTM_SCC_NODES (= 50), return an empty DetectedLoopsResult without running Johnson's. Same constant, same mechanism, no new knob. Empty is also what the retired MAX_LTM_CIRCUITS = 100_000 cap produced for callers on dense graphs before the cap-lift work, so this keeps the contract with FFI/layout consumers unchanged at the "what the user sees" layer while removing the latency cliff. Tests cover both sides of the boundary: a 4-node SCC still returns its feedback loop (gate does not accidentally trip on real models) and a 60-node ring returns empty (gate fires before enumeration).
simlin_analyze_get_relative_loop_score previously called compute_rel_loop_scores on every invocation, materializing the full loop-by-timestep rel-score map just to slice out one loop's series. pysimlin's _populate_loop_behavior (and any FFI caller that iterates the project's loops) spends O(L^2 * T) doing that, where the old compile-time rel_loop_score offset lookup was O(T). Exploit the math: rel_loop_score is loop_score / Σ|loop_score| within a cycle partition, so the denominator is per-partition, not per-loop. Caching it once per partition turns L iterated FFI calls for a partition of size L into O(L * T) amortized, with O(T) work per call after the first. No bulk FFI surface (the root CLAUDE.md rules that out), no new caps -- just recognizing that a shared sub-expression is worth naming. Engine side (src/simlin-engine/src/ltm_post.rs): - compute_partition_denominator(results, loop_ids) produces the shared Σ|loop_score_j| series for a partition's loops. - compute_rel_loop_score_for_id(results, id, denominator) produces the single-loop numerator series divided by the pre-computed denominator with SAFEDIV-0 semantics. - per_id_helpers_match_full_sweep pins bit-for-bit agreement against compute_rel_loop_scores (same float multiply / divide order), so the cached path is observationally identical to the full-sweep path. Libsimlin side: - SimState carries cached_partition_denominators: Map<partition_key, Vec<f64>>, lazily populated in simlin_analyze_get_relative_loop_score. - Cleared on every results-mutating path (run_to_end, reset, set_value_by_offset) so cache lifetime tracks results lifetime. set_value_by_offset can't identify which partition owns the touched offset, so it flushes the whole map -- the next call repopulates lazily, which is cheap vs. the cost of serving stale. - Four integration tests: stability across repeat reads, |rel_a|+|rel_b|=1 invariant for loops sharing a partition, "no results" after reset (cache not served against absent results), and identical series after reset+rerun (cache rebuilt, not reused).
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 7ec84c06b8
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| } else { | ||
| }; | ||
|
|
||
| let ltm = engine::db::model_ltm_variables(&*db_locked, synced_model.source, sync.project); |
There was a problem hiding this comment.
Use simulation snapshot for relative loop partitions
simlin_analyze_get_relative_loop_score now derives loop_partitions from the current project DB (model_ltm_variables) instead of from the simulation that produced state.results. If the project is patched after a sim run (rename/delete model, or any loop-structure change), this call can return BadModelName/DoesNotExist or compute denominators from the wrong loop grouping even though the sim still has valid results. The previous implementation read scores purely from the simulation output, so this introduces a state-coupling regression for long-lived sims across patches.
Useful? React with 👍 / 👎.
Review summaryReviewed the LTM cap-lift re-land + test-time-budget safety rail. The change is well-structured: a clean SCC-based auto-flip gate replaces the brittle A few minor non-blocking observations (would not block merge):
Overall correctness verdictCorrect. No blocking bugs identified. Functional behavior, salsa caching, FFI cache invalidation, and test coverage all check out. Non-blocking notes above are informational. |
simlin_analyze_get_relative_loop_score previously re-queried model_ltm_variables against the current project DB on every call, even though the loop IDs it was about to look up came from the VM run that produced state.results. If the project was patched after sim_new (rename / delete / structural change), the current DB's loop_partitions could have different IDs -- or be empty -- while the sim's results still carried the compile-era loop_score variables. The FFI would then return DoesNotExist for IDs whose series are sitting right there in state.results. Capture the loop_partitions map on SimState while the db lock is still held and ltm_enabled is still set, before sim_new resets the flag. Post-sim rel-score queries read the snapshot directly and stop touching the db entirely: bound to the simulation's era, not the project's current state. This also lets us drop the db_locked + sync_state + sync + canonical_model + synced_model + model_ltm_variables chain that was gating every FFI call, which was pure overhead once the snapshot is available. The snapshot is empty when LTM was disabled at sim_new, when compilation failed, or when the LTM pipeline auto-flipped to discovery (which already produces an empty loop_partitions in model_ltm_variables). Empty-map semantics match the existing "loop does not have relative score data" error, so callers see the same behaviour. New test test_rel_loop_score_survives_post_sim_rename pins the regression: create sim with LTM, fetch a loop's rel-score series, apply a renameVariable patch to the loop's stock, and fetch the same id again. Snapshot path returns the same series; a bug reintroducing the db re-query would fail on the stale id.
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## main #469 +/- ##
==========================================
+ Coverage 81.75% 81.82% +0.07%
==========================================
Files 184 186 +2
Lines 52329 52659 +330
==========================================
+ Hits 42779 43087 +308
- Misses 9550 9572 +22 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 0db2e85477
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| let Some(off) = offsets[i] else { continue }; | ||
| let num = row[off]; | ||
| let val = if denom == 0.0 { 0.0 } else { num / denom }; |
There was a problem hiding this comment.
Normalize A2A loop scores per element, not just slot 0
For arrayed (A2A) loops, this code reads only row[off], i.e. the first slot of each loop-score series, so relative loop scores are computed from element 0 and then exposed as if they represented the whole loop. In models where the same loop ID has multiple element slots, this produces incorrect rankings/percentages for non-zero elements (the same scalar trace is reused), which regresses the previous per-element rel_loop_score behavior and affects downstream consumers like layout/FFI queries; the denominator path above uses the same scalar indexing pattern.
Useful? React with 👍 / 👎.
Review SummaryReviewed the re-land of LTM always-on (auto-flip) + the test-time safety rail. The diff is large but the core changes are well-scoped:
Things I considered and ruled out:
Overall correctness verdictCorrect. |
Codex iter-3 P1: the scalar `compute_rel_loop_scores` (and the per-id helpers added for the libsimlin denominator cache) read only slot 0 of every loop_score series, so arrayed (A2A) loops get element-0's series regardless of which element the caller might conceptually want. That matches the pre-PR FFI contract (which also returned a scalar series per loop, verified by reading the old libsimlin analysis.rs), so no existing public surface regresses -- but the function is the canonical replacement for the retired compile-time rel_loop_score aux, and callers that want per-element data (diagram UI reading per-element importance, a dimension-aware pysimlin reader, a future arrayed FFI) need a production path that reproduces the pre-PR compile-time per-element math. Add compute_rel_loop_scores_per_element(results, loop_partitions, n_slots_by_loop) alongside the scalar variant. Per-group `max_slots` is the largest slot count among loops sharing the partition; each loop's output is a flat Vec<f64> of length step_count * max_slots, with step varying slowest. Scalar loops in a mixed partition broadcast their single value across every element slot, matching the pre-PR compile-time emitter (a scalar loop_score referenced from an A2A rel_loop_score equation expanded uniformly across the target's elements). Grouping uses BTreeMap so float-sum order stays deterministic, the same rationale the scalar variant documents. Docstrings on the three scalar helpers (compute_rel_loop_scores, compute_partition_denominator, compute_rel_loop_score_for_id) now call out the slot-0 scalar semantics explicitly and point at the per-element variant for dimension-aware callers. The private helper previously duplicated in simulate_ltm.rs is now a thin forwarder to the production function, so the existing A2A integration tests (test_a2a_pure_dimension_loop_scores, test_arrayed_population_ltm_exhaustive) pin the production code rather than a parallel implementation. Two new unit tests in ltm_post pin the per-element math directly: normalize-within-each-slot (pure-A2A two-loop partition) and broadcast-scalar-across-elements (mixed scalar + A2A partition).
|
@codex review |
|
Review summary: no blocking bugs found; patch looks correct and well-tested. Strengths:
Minor non-blocking observations:
Overall correctness verdict: correct. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c6ccac0291
ℹ️ 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".
| cargo clippy --all-targets --all-features -- -D warnings > "$CLIPPY_TMP" 2>&1 & | ||
| PID_CLIPPY=$! | ||
| RUST_BACKTRACE=1 cargo test > "$TEST_TMP" 2>&1 & | ||
| RUST_BACKTRACE=1 "$TIMEOUT_CMD" --kill-after=30 180 cargo test > "$TEST_TMP" 2>&1 & | ||
| PID_TEST=$! |
There was a problem hiding this comment.
Exclude build-lock wait time from rust test timeout
Running cargo clippy and cargo test concurrently means one process can block on Cargo's workspace lock while the other compiles; with the new timeout 180 cargo test, that lock wait counts toward the 180s cap and can kill tests before they actually run. This is reproducible on cold/slow environments (or after dependency churn), causing false hook failures even when the test suite itself is healthy. The timeout should be applied after lock/compile contention is removed (e.g., serialize Rust commands or separate compile/no-run from execution as in CI).
Useful? React with 👍 / 👎.
| let loop_ids_in_partition = partitions_snapshot.iter().filter_map(|(id, pk)| { | ||
| if *pk == partition_key { | ||
| Some(id.as_str()) | ||
| } else { |
There was a problem hiding this comment.
Sort partition loop IDs before cached denominator summation
The cached denominator is built from state.loop_partitions.iter(), which is HashMap iteration order and therefore process-seed dependent. Because floating-point summation is non-associative, this makes simlin_analyze_get_relative_loop_score outputs slightly nondeterministic across runs for the same model/results, regressing reproducibility guarantees the new post-sim path is trying to preserve. Collecting and sorting loop IDs before calling compute_partition_denominator avoids this drift.
Useful? React with 👍 / 👎.
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.
MAX_LTM_SCC_NODES = 50auto-flip gate + post-simcompute_rel_loop_scores, no layered iterations).cargo test --workspacewall-clock at 180s in bothscripts/pre-commitand.github/workflows/ci.yaml, withtimeout(1)from coreutils (no new dep).cargo tarpaulingets a matching 2700s outer cap.docs/dev/rust.mdgrows a "Test time budgets" section;CLAUDE.mdanddocs/dev/commands.mdpoint 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 = 50gate 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 newMAX_LTM_TOTAL_CIRCUITS = 10_000gate 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 reportedfinished 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)
cargo test --workspaceTest stepcargo tarpaulin --out Xml180s is ~3x the cargo-test baseline. Local dev machines run the suite in ~25s, so ~7x headroom there.
Design guidance added
docs/dev/rust.mddocuments 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
./scripts/pre-commitpasses (verified on this branch with the new timeout in place).timeout --kill-after=30 1 cargo testshould fail with a clear message pointing atdocs/dev/rust.md).Follow-ups (not this PR)
wrld3_element_level_enumeration_is_uncappedtest insrc/simlin-engine/tests/wrld3_ltm_panic.rstakes ~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.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.