Skip to content

engine: re-land LTM always-on (auto-flip) + test timeout cap - #469

Merged
bpowers merged 25 commits into
mainfrom
ltm-cap-lift-v2
Apr 24, 2026
Merged

bpowers merged 25 commits into
mainfrom
ltm-cap-lift-v2

Conversation

@bpowers

@bpowers bpowers commented Apr 24, 2026

Copy link
Copy Markdown
Owner

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 2dbce501 checkpoint (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 engine: enable LTM always-on via auto-flip + post-sim rel_loop_score #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 17 commits April 23, 2026 19:35
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.
@claude

claude Bot commented Apr 24, 2026

Copy link
Copy Markdown

Review findings

[P2] simlin_analyze_get_relative_loop_score recomputes every loop's relative score on each FFI call

File: src/libsimlin/src/analysis.rs (lines 441-462)

The previous implementation was O(T) per call: it canonicalized one variable name, looked up its offset in results.offsets, and copied the slice. The new implementation calls ltm_post::compute_rel_loop_scores(results, &ltm.loop_partitions), which builds the full HashMap<String, Vec<f64>> covering every loop in the project (see ltm_post.rs:59-117, a double loop over partitions × steps), then discards all entries except loop_id. The typical FFI usage pattern iterates over N loops returned by simlin_analyze_get_loops, producing O(N²×T) total work where the old code was O(N×T). On a model with a few hundred loops and thousands of timesteps this is noticeable. Also, the work is not cached: two successive calls for different loop IDs recompute the same denominators. Consider either (a) computing only the requested loop's partition, or (b) caching the computed map on SimState until results change.

[P3] wrld3_element_level_enumeration_is_uncapped consumes a large slice of the new 180s cap

File: src/simlin-engine/tests/wrld3_ltm_panic.rs (lines 93-125)

Per the PR description the new test takes ~29s at this checkpoint — ~16% of the 180s cargo test --workspace cap this PR introduces, on a single test. The PR's premise is that the suite should have ~3× headroom above its ~60s baseline; a single test that eats 29s shrinks that margin to ~2× before any other regression lands. The PR description acknowledges this as a follow-up to gate with #[ignore], but since the companion test wrld3_ltm_compilation_finishes_in_time already covers the compile-time path, it is low-risk to #[ignore] this one in the same commit that installs the safety rail rather than trusting a follow-up PR.

Overall correctness verdict

Correct with a non-blocking performance concern. The semantic changes (auto-flip on large SCCs, post-sim rel_loop_score, usize::MAX enumeration budget) are well-tested, preserve existing LTM fixture expectations to within 1e-10, and the accompanying diagnostic surfacing ensures users see the mode change. The FFI quadratic is the only thing I'd hold up a merge for if you plan to ship this to Go/C callers soon; otherwise it's addressable in a follow-up.

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

Comment on lines +1087 to +1088
.find_loops_with_limit(usize::MAX)
.expect("usize::MAX cannot exhaust the enumeration budget");

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

Comment thread scripts/pre-commit Outdated
Comment on lines +139 to +140
wait $PID_TEST
TEST_EXIT=$?

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

Comment thread .github/workflows/ci.yaml Outdated
# for per-test budget guidance.
- name: Test
run: cargo test --workspace
run: timeout --kill-after=30 180 cargo test --workspace

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

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

claude Bot commented Apr 24, 2026

Copy link
Copy Markdown

Review findings

[P2] Quadratic cost when iterating loops through simlin_analyze_get_relative_loop_score

File: src/libsimlin/src/analysis.rs:453

Each call to this FFI now invokes compute_rel_loop_scores(results, &ltm.loop_partitions), which computes the full N_loops × N_steps normalization and then returns the series for the single requested loop_id. The previous implementation read the pre-computed $⁚ltm⁚rel_loop_score⁚{id} offset in O(N_steps).

pysimlin's _populate_loop_behavior (src/pysimlin/simlin/run.py:246-248) calls this once per structural loop in a Python for loop, so iterating L loops becomes O(L² × N_steps) instead of O(L × N_steps). For auto-flipped (discovery-mode) models the partition map is empty and the cost is nil, but for the exhaustive path — which can still contain thousands of circuits under the 50-node SCC ceiling (e.g. a 50-clique-like structure) — the regression is noticeable. A simple mitigation is to compute compute_rel_loop_scores once and memoize it on sim_ref.state next to results, or expose a bulk FFI that returns all series in one shot.

Verdict

Overall correctness looks good: the auto-flip gate on MAX_LTM_SCC_NODES = 50 plus post-sim compute_rel_loop_scores is a clean replacement for the O(P²) compile-time emitter, tests cover threshold edges, disjoint-SCCs, user-vs-auto discovery mode, and the A2A path (via the _per_element test helper). The timeout cap in pre-commit/CI is well-motivated and conservative. The quadratic FFI behavior is the only non-nit concern I see, and it is recoverable with a small follow-up rather than a blocker.

@claude

claude Bot commented Apr 24, 2026

Copy link
Copy Markdown

Review findings

[P1] Timeout diagnostic never runs because set -e aborts the subshell at the wait

File: scripts/pre-commit:149-161

The subshell starts with set -e on line 97, so the bare wait \$PID_TEST on line 149 is a simple command in no conditional/!/&&/|| context. When cargo test fails (including the 124/137 timeout exits this PR exists to surface), set -e exits the subshell immediately — before TEST_EXIT=\$?, before echo \"Rust tests failed:\", before cat \"\$TEST_TMP\", and before the new "cargo test exceeded the 180s wall-clock cap" hint at lines 154-158. \$PIPELINE_A_OUT will end at the last line that did run (e.g., [rust] Running clippy and tests...), so the outer cat \"\$PIPELINE_A_OUT\" on line 232 prints no failure context. The preceding if ! wait \$PID_CLIPPY on line 144 avoids this precisely because !/if suppresses set -e; dropping the same pattern for \$PID_TEST defeats the diagnostic this PR is meant to introduce. Easiest fix is wait \$PID_TEST || true before TEST_EXIT=\$?, or restore the if ! wait \$PID_TEST; then conditional and stash \$? inside it. Worth verifying by spot-checking with timeout --kill-after=30 1 cargo test as the PR description's unchecked test-plan item notes.

Overall correctness verdict

Incorrect. The core engine changes (LTM auto-flip gate on MAX_LTM_SCC_NODES, removal of compile-time rel_loop_score emission in favor of post-sim compute_rel_loop_scores, and test coverage for both) look cohesive and well-instrumented, but the pre-commit timeout-handling regression defeats the safety-rail half of the PR's stated goal: the timeout hint will never print when tripped, and test-failure output will be swallowed entirely.

bpowers added 4 commits April 23, 2026 21:09
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).
@bpowers

bpowers commented Apr 24, 2026

Copy link
Copy Markdown
Owner Author

@codex review

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

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

@claude

claude Bot commented Apr 24, 2026

Copy link
Copy Markdown

Review summary

Reviewed 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 MAX_LTM_CIRCUITS count cap, rel_loop_score is correctly moved to a post-sim computation that preserves SAFEDIV-0 and IEEE-754 NaN semantics, and the libsimlin FFI cache (per-partition denominator) is invalidated in lockstep with results (run_to_end, reset, set_value_by_offset). The test suite materially improves coverage: the auto-flip threshold is exercised at boundary values (49/51/60-node SCCs, two-disjoint-SCC adversarial case, element-vs-variable-graph distinction, user-vs-auto discovery), ltm_post has property-based equivalence against the retired SAFEDIV formula, and the FFI cache has dedicated stability/invalidation/repopulation tests. The pre-commit wait $PID_TEST && TEST_EXIT=0 || TEST_EXIT=$? exit-code-capture pattern is correct under the surrounding set -e subshell, and the GH Actions step-level timeout-minutes: 3 cap avoids the macOS timeout(1) portability problem cleanly.

A few minor non-blocking observations (would not block merge):

  • compute_rel_loop_scores sorts loop_ids before summing partition denominators, but the libsimlin FFI path (simlin_analyze_get_relative_loop_score in src/libsimlin/src/analysis.rs:479) iterates ltm.loop_partitions in HashMap order when building the denominator. Floating-point summation is not associative, so the two paths can produce bit-different denominators on the same inputs. The proptest in ltm_post.rs does not catch this because its loop list is already sorted. Practical impact is negligible (well under the 1e-9 tolerance used in the FFI partition-sum test), but worth noting if anyone later writes a cross-path bit-equality assertion.
  • model_detected_loops (src/simlin-engine/src/db_analysis.rs:1098) silently returns an empty loops vec when largest_scc_size > MAX_LTM_SCC_NODES, while the analogous gate in model_ltm_variables accumulates a CompilationDiagnostic::Warning. The rustdoc is explicit that this matches the prior MAX_LTM_CIRCUITS truncation behavior, so it appears intentional, but it does mean FFI/layout consumers (simlin_analyze_get_loops, try_detect_ltm_loops_incremental) cannot distinguish "no loops" from "too dense to enumerate" without separately calling model_ltm_variables and checking for the auto-flip warning.
  • model_detected_loops and model_ltm_variables apply the same numeric threshold (MAX_LTM_SCC_NODES = 50) but to different graphs (variable-level vs element-level). For arrayed cross-element models it is possible for model_detected_loops to return loops while model_ltm_variables auto-flips and produces an empty loop_partitions; in that case try_detect_ltm_loops_incremental (src/simlin-engine/src/layout/mod.rs:3848-3866) renders loops with empty importance_series rather than failing. Soft degradation, not a correctness bug.

Overall correctness verdict

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

codecov Bot commented Apr 24, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 89.32806% with 54 lines in your changes missing coverage. Please review.
✅ Project coverage is 81.82%. Comparing base (55597e4) to head (c6ccac0).
⚠️ Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
src/simlin-engine/tests/wrld3_ltm_panic.rs 0.00% 20 Missing ⚠️
src/simlin-engine/src/ltm_augment.rs 33.33% 16 Missing ⚠️
src/libsimlin/src/simulation.rs 80.00% 4 Missing ⚠️
src/simlin-engine/tests/simulate_ltm.rs 94.73% 4 Missing ⚠️
src/libsimlin/src/analysis.rs 85.00% 3 Missing ⚠️
src/libsimlin/tests/analysis.rs 98.29% 3 Missing ⚠️
src/simlin-engine/src/ltm.rs 50.00% 3 Missing ⚠️
src/simlin-engine/src/ltm_post.rs 98.91% 1 Missing ⚠️
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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@bpowers

bpowers commented Apr 24, 2026

Copy link
Copy Markdown
Owner Author

@codex review

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

Comment on lines +102 to +104
let Some(off) = offsets[i] else { continue };
let num = row[off];
let val = if denom == 0.0 { 0.0 } else { num / denom };

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

@claude

claude Bot commented Apr 24, 2026

Copy link
Copy Markdown

Review Summary

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

  • MAX_LTM_SCC_NODES = 50 gate in model_ltm_variables (element-level SCC) and model_detected_loops (variable-level SCC) short-circuits before Johnson's.
  • rel_loop_score moves to post-sim ltm_post::compute_rel_loop_scores / compute_partition_denominator / compute_rel_loop_score_for_id. Unit + proptest coverage looks solid (SAFEDIV-0, NaN propagation, partition grouping, bit-for-bit match between full-sweep and streamed paths).
  • MAX_LTM_CIRCUITS retired; callers pass usize::MAX with an expect documenting unreachability.
  • SimState snapshots loop_partitions at sim_new time and caches per-partition denominators, with cache invalidation wired on run_to_end, reset, and set_value_by_offset. The post-patch rename regression test (test_rel_loop_score_survives_post_sim_rename) pins the snapshot behavior.
  • model_all_diagnostics now drives model_ltm_variables when ltm_enabled, surfacing the auto-flip warning to collect_all_diagnostics consumers, with positive + negative tests.
  • CI / pre-commit gain a 180s wall-clock cap on cargo test (GitHub timeout-minutes on CI, timeout(1)/gtimeout detection in pre-commit) and a 2700s cap on tarpaulin. The wait $PID_TEST && TEST_EXIT=0 || TEST_EXIT=$? pattern in the pre-commit subshell is the right way to capture the timeout's 124/137 exit under set -e.

Things I considered and ruled out:

  • The name.ends_with(&l.id) lookup in db_ltm.rs:2478 can alias (e.g., loop r11's variable name would match loop r1 first), but it's pre-existing code unchanged by this PR.
  • The compute_partition_denominator + _for_id cached path depends on caller-side loop_id iteration order for the "bit-for-bit" claim; libsimlin iterates a HashMap, so results are only bit-for-bit equal to the full-sweep when iteration order happens to match the sorted order. Numerically within 1e-10 regardless, so not observable in practice.
  • model_detected_loops gates on variable-level SCC while model_ltm_variables gates on element-level SCC — they can disagree on cross-element arrayed models. The downstream layout path handles the empty-importance-series case gracefully, and FFI consumers get consistent "empty" answers on oversized graphs matching the retired MAX_LTM_CIRCUITS semantics.

Overall correctness verdict

Correct.

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).
@bpowers

bpowers commented Apr 24, 2026

Copy link
Copy Markdown
Owner Author

@codex review

@claude

claude Bot commented Apr 24, 2026

Copy link
Copy Markdown

Review summary: no blocking bugs found; patch looks correct and well-tested.

Strengths:

  • Auto-flip gate in db_ltm.rs:2076-2112 keys on element-level largest SCC and fires BEFORE model_element_loop_circuits, so Cliffs A and B documented in docs/design-plans/2026-04-18-ltm-cap-lift-diagnosis.md are unreachable on dense models.
  • FFI snapshot consistency in libsimlin/src/simulation.rs:63-94 and analysis.rs:421-463 -- capturing loop_partitions at sim_new time and keeping the per-partition denominator cache in lockstep with results (cleared on run_to_end / reset / set_value_by_offset) correctly survives post-sim patches, as pinned by test_rel_loop_score_survives_post_sim_rename.
  • Diagnostic surfacing in model_all_diagnostics -- guarded on project.ltm_enabled(db) so non-LTM projects pay no synthesis cost, and guarded positively so MCP/libsimlin callers see the auto-flip warning.
  • Test-time budget safety rail: both scripts/pre-commit and .github/workflows/ci.yaml cap cargo test at 180s with matching documentation in docs/dev/rust.md.

Minor non-blocking observations:

  • model_detected_loops (db_analysis.rs:1097-1107) runs Tarjan once for the new largest_scc_size() gate and again inside find_loops_with_limit. O(V+E) so negligible, but worth a follow-up if profiling ever flags it.
  • compute_rel_loop_scores_per_element (ltm_post.rs:163-230) would index out of bounds if two arrayed loops in the same partition had different slot counts (at k exceeding a partitions minimum slot count but less than max_slots). Not reachable from any in-tree caller -- all current callers pass uniform slot counts -- so not a bug today, but worth asserting or clamping if this helper gets public consumers.

Overall correctness verdict: correct.

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

Comment thread scripts/pre-commit
Comment on lines 138 to 141
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=$!

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

Comment on lines +455 to +458
let loop_ids_in_partition = partitions_snapshot.iter().filter_map(|(id, pk)| {
if *pk == partition_key {
Some(id.as_str())
} else {

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

@bpowers
bpowers merged commit 88ca649 into main Apr 24, 2026
13 checks passed
@bpowers
bpowers deleted the ltm-cap-lift-v2 branch April 24, 2026 14:03
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