Skip to content

engine: reduce LTM circuit-enumeration memory and time on dense graphs - #459

Merged
bpowers merged 12 commits into
mainfrom
reduce-ltm-mem
Apr 18, 2026
Merged

bpowers merged 12 commits into
mainfrom
reduce-ltm-mem

Conversation

@bpowers

@bpowers bpowers commented Apr 18, 2026

Copy link
Copy Markdown
Owner

Summary

Five-commit stack that takes wrld3-03 LTM circuit enumeration from 8.45 GiB / 27 s to 491 MiB / 1.2 s (17x smaller, 22x faster) while preserving all existing LTM semantics. Production MAX_LTM_CIRCUITS=100_000 path drops from 322 MiB / 569 ms to 33 MiB / ~29 ms.

Commit What it does wrld3-03 uncapped impact
7303af3 SCC-restricted indexed (u32) DFS, skip trivial SCCs 8.45 GiB → 5.87 GiB, 26.8 s → 2.87 s
2fd4a8f Indexed LoopCircuitsResult (names table + Vec<Vec<u32>>) 5.87 GiB → 914 MiB, 2.87 s → 1.73 s
7334e1d Hash-fingerprint dedup keys 914 MiB → 491 MiB, 1.73 s → 1.49 s
aa56c5a Johnson 1975 with blocked-set unblocking 491 MiB (unchanged), 1.49 s → 1.23 s
c0e9aa9 Tech-debt items from LTM critical review --

Test plan

  • cargo test -p simlin-engine --lib (3016 passed)
  • cargo test -p simlin-engine --features file_io --test simulate_ltm (45 passed)
  • cargo test -p simlin-engine --test layout (includes test_layout_arms_race, 31 passed)
  • cargo test -p simlin-engine --test wrld3_ltm_panic (60 s budget, passes comfortably)
  • Johnson-vs-Tiernan equivalence test: fixture corpus + 256-case proptest (both agree)
  • Peak RSS measured via ltm_mem_bench example on wrld3-03 at budget 100K and unbounded

bpowers added 5 commits April 17, 2026 20:25
Replace the Ident-keyed, whole-graph DFS in CausalGraph with a private
IndexedGraph that (1) sorts nodes lexicographically so u32 indices carry
the small-start invariant; (2) decomposes the graph into strongly-connected
components and restricts DFS to one SCC at a time; and (3) stores path,
visited, and dedup keys as Vec<u32> / Vec<bool> instead of
Vec<Ident<Canonical>> / HashSet<Ident<Canonical>> / String-joined keys.

On wrld3-03 (313 nodes, 148 SCCs, 166-node non-trivial SCC, 1.86M elementary
circuits) the production MAX_LTM_CIRCUITS=100_000 path drops from ~322 MiB
peak RSS and 0.57 s to ~33 MiB peak RSS and ~26 ms -- an order of magnitude
on both axes. Full enumeration at a 10M budget falls from 8.45 GiB / 26.8 s
to 5.87 GiB / 2.87 s; the remaining memory is dominated by the final
Vec<Vec<Ident<Canonical>>> materialization required by the public API, which
is outside the scope of this change. SCC restriction also skips the 147
trivial-SCC feeder nodes outright, saving wasted DFS work on cross-SCC
edges that cannot close a cycle.

Public signatures of find_loops_with_limit and find_circuit_node_lists_with_limit
are preserved (same circuits, same dedup semantics, same TruncatedByBudget
contract). Correctness is pinned down by new unit tests covering empty
graphs, 2-node back-edges, 3-node cycles, disjoint cycles, figure-8 SCCs,
self-loop exclusion, and budget semantics. Existing unit and integration
tests (simulate_ltm, wrld3_ltm_panic) all pass unchanged.

Also checks in the ltm_mem_bench example used to measure these results
(with minor collapsible-if cleanup so the example passes -D warnings).
LoopCircuitsResult previously held a flat `Vec<Vec<String>>`, which on
dense causal graphs (WRLD3-03's 166-node SCC enumerating ~1.86M
elementary circuits) forced ~87M per-node String allocations over only
~166 distinct variable names -- ~530kx redundancy. Full enumeration
pushed peak RSS to 5.87 GiB even after the SCC-restricted enumerator.

Replace the owned-per-circuit shape with a shared `names: Vec<String>`
table plus `circuits: Vec<Vec<u32>>` indices into it, accessed via new
`len`, `is_empty`, `circuit_names`, and `to_named_circuits` helpers.
Expose `CausalGraph::find_indexed_circuits_with_limit` so
`model_loop_circuits` / `model_element_loop_circuits` can produce the
indexed form without going through the legacy `Vec<Vec<Ident>>`
materialization. Update the sole production consumer
(`build_element_level_loops`) to work directly off the indexed view by
pre-materializing borrowed `&str` slices into the shared name table.

Test helpers switch to the indexed shape or call `to_named_circuits`
where legacy owned-string comparisons are still more natural. Salsa
caching still pointer-matches across equation edits that don't move
edges, because the ordering of both `names` (lex-sorted via the indexed
graph) and `circuits` remains deterministic.

wrld3-03 (`ltm_mem_bench`) before/after:
  budget 100_000:    33.63 MiB peak (unchanged; the bounded path was
                     already dominated by intermediate state, not final
                     materialization).
  budget 10_000_000: 5870.5 MiB -> 914.9 MiB peak, 3.14s -> 1.73s.
The circuit-enumeration dedup keys sorted node-index vectors to collapse
multidigraph circuits that share a node set.  Storing full Vec<u32> keys
cost ~440 MiB of transient HashSet state on wrld3-03 at uncapped
enumeration -- proportional to circuit count x mean path length, both of
which are large on dense SD graphs.

Replace the Vec<u32> key with a 64-bit SipHash-1-3 fingerprint of the
sorted-node-index vector via BuildHasher::hash_one.  Within a single
enumeration call every key is hashed with the same seeded RandomState,
so insert/contains remain correct; birthday-collision probability over
1.86M circuits is under 1e-7 and has no observable effect on loop
counts.  Semantics are otherwise identical: test_layout_arms_race (the
case that actually exercises the dedup) still passes unchanged.

wrld3-03 peak RSS at full enumeration drops from 914 MiB to 491 MiB
(another 46%), bringing the total from the 8.45 GiB pre-reduction-branch
baseline down 17.2x.  Wall time also improves from 1.73 s to 1.49 s
because hashing a fixed-size u64 is cheaper than allocating, sorting,
and comparing full Vec<u32> keys.  The production MAX_LTM_CIRCUITS=100_000
path is unchanged (33 MiB peak either way) since the dedup set never
grows large enough to matter at that cap.
Adds tech debt items 20-32 capturing findings from the LTM critical
review (grade A- scalar / B array): FixedIndex N-squared expansion,
reducer polarity blind spots, dedup keying for multidigraphs, Tiernan
vs Johnson's enumeration, Ident-keyed SearchGraph hot path, element-
level granularity, A2A mixed-reference partial equations, STDDEV/RANK
fallback, truncate-before-filter in discovery, missing LOOPSCORE /
PATHSCORE and polarity-confidence features, RK4 + LTM guard, and the
unused _is_affecting_stock flag.  Also checks in the design plan that
scoped the wrld3 memory work.
Swap the per-SCC DFS from a Tiernan 1970 lexicographic-restart
(repeated-visit) to Johnson 1975 with the blocked-set / B[] unblock
mechanism.  Nodes that enter the DFS stack are blocked, and stay
blocked on backtrack unless a cycle was discovered through them;
nodes that failed to close a cycle register as waiters on their
successors' b_list and are unblocked transitively when those
successors later participate in a cycle.  This avoids re-exploring
dead-end subtrees from different parent branches.

The simplified form of Johnson's adopted here skips the classical
remove-processed-root / recompute-SCCs / recurse outer loop -- our
existing (SCC intersect index >= start) gate inside the DFS already
approximates it, and per-start reset of blocked/B[] is O(|SCC|)
per start (wrld3's 166-node SCC: 27K bool writes total, negligible).
The public contract (each circuit rotated to its lex-smallest node,
self-loops excluded, TruncatedByBudget on budget exhaustion, salsa-
stable deterministic ordering) is preserved.

wrld3-03 uncapped enumeration drops from 1.49 s to 1.23 s (~18%
faster); peak RSS unchanged at 491 MiB.  MAX_LTM_CIRCUITS=100_000
path stays at 33 MiB / ~29 ms (unchanged: the cap doesn't expose
enough wasted DFS work for Johnson's blocking to matter at that
scale).

The Tiernan oracle is retained as enumerate_circuits_in_scc_tiernan
under #[cfg(test)], used by the new Johnson-vs-Tiernan equivalence
tests:

  * 10 targeted unit tests for specific graph shapes (empty, DAG,
    self-loop excluded, back-edge, 3-cycle, disjoint cycles, figure-8,
    complete K3, budget semantics, lex-smallest rotation, unblock
    chain, cross-SCC restriction).
  * A fixture-corpus equivalence test covering multi-digraphs, bowtie,
    chain with dead-end spurs, three-clique (arms race shape), and
    self-loop + non-trivial SCC combinations.
  * A proptest (256 cases) generating random 2-8 node graphs with up
    to 16 directed edges, asserting Johnson's and Tiernan produce
    identical canonicalized circuit sets.  The proptest caught a
    self-loop-at-root bug in the first implementation pass; the
    regression seed is checked in under proptest-regressions/ltm.txt.

Attempted removing MAX_LTM_CIRCUITS entirely based on the reasoning
that its original purpose (avoiding WASM OOM during enumeration) is
obsolete after the memory-reduction work on this branch.  Testing
showed the cap also protects the downstream LTM variable-generation
pipeline: wrld3's 1.86M circuits would synthesize ~3.7M loop-score
variables, which OOMs the compiler.  The cap stays, with an updated
rustdoc explaining this secondary role.  Making uncapped enumeration
viable for production requires a separate cap on synthetic variable
generation inside model_ltm_variables -- tracked as 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: aa56c5a10d

ℹ️ 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/simlin-engine/src/ltm.rs Outdated
scratch.clear();
scratch.extend_from_slice(&c);
scratch.sort_unstable();
if seen.insert(state.hash_one(&scratch)) {

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 Verify dedup collisions before dropping circuits

dedup_circuits now treats state.hash_one(&scratch) as a unique key, so two different node sets that collide on the 64-bit fingerprint are silently merged and one loop is lost. On large models (the exact workload this patch optimizes), that creates a correctness risk in loop counts/polarity, and because RandomState is process-seeded it can also make results non-reproducible across runs when a collision occurs. Please keep a secondary equality check (e.g., per-hash bucket of sorted vectors) before discarding a circuit.

Useful? React with 👍 / 👎.

@claude

claude Bot commented Apr 18, 2026

Copy link
Copy Markdown

Reviewed the five-commit stack. The Johnson's algorithm implementation, SCC-restricted enumeration, and indexed-name-table refactor all check out. Key invariants I verified:

  • Small-start invariant preserved: scc.sort_unstable() in tarjan_scc guarantees for &start in scc iterates ascending; the w < start gate in johnson_circuit plus in_scc[w] correctly restricts to the induced subgraph.
  • Self-loop-at-root handling: when v == start (path.len() == 1) and a successor w == start is seen, the code takes the else if w == start branch without emitting and without setting found_cycle = true — intentional and documented.
  • State reuse across starts: blocked/b_list reset per start; path/circuits reused; state.path.pop() after each start handles the outermost pushed node.
  • Budget semantics preserved: pre-dedup circuit count, shared across all SCCs, propagates TruncatedByBudget cleanly.
  • Tarjan's iterative form: correct use of frames.last() (read-only) for lowlink propagation into the parent's outer lowlinks vec.
  • Hash-fingerprint dedup trade-off: 1e-7 birthday-bound collision at 1.86M circuits is explicitly documented; at the production 100K cap it's ~2.7e-10, well below observability.
  • Cross-validation: the fixture corpus + 256-case proptest comparing Johnson's against the retained Tiernan oracle is a strong correctness net; the checked-in regression seed documents a real bug caught during development.
  • API migration: LoopCircuitsResult's indexed form correctly exposes len/is_empty/circuit_names/to_named_circuits; the build_element_level_loops rewrite materializes Vec<&str> once and borrows into the shared name table.

No blocking issues. Overall correctness: correct.

@codecov

codecov Bot commented Apr 18, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 95.27559% with 18 lines in your changes missing coverage. Please review.
✅ Project coverage is 81.55%. Comparing base (d1870d2) to head (df2f240).

Files with missing lines Patch % Lines
src/simlin-engine/src/ltm.rs 96.12% 10 Missing ⚠️
src/simlin-engine/src/rapidhash.rs 92.22% 7 Missing ⚠️
src/simlin-engine/tests/simulate_ltm.rs 75.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #459      +/-   ##
==========================================
+ Coverage   81.49%   81.55%   +0.06%     
==========================================
  Files         176      177       +1     
  Lines       51195    51471     +276     
==========================================
+ Hits        41721    41977     +256     
- Misses       9474     9494      +20     

☔ 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 added 2 commits April 18, 2026 09:45
The LTM circuit enumerator fingerprints each elementary cycle by hashing
its sorted u32 vertex index list so a HashSet<u64> can reject duplicate
node-set circuits at emit time.  On wrld3 that's ~1.86M hashes with mean
~188 bytes and max 320 bytes per call, and the u32-wise FNV-1a we were
using sits around 10 GiB/s (long serial xor-mul dependency chain).

Ported the rapidhash V3 HashMicro variant from Nicolas De Carli's C
reference (third_party/rapidhash/rapidhash.h) through the idiomatic Go
port at third_party/go-rapidhash as a structural guide.  Picked
HashMicro specifically over the default Hash and HashNano variants:
HashMicro's 80-byte unrolled loop with four parallel accumulator lanes
is an exact match for our size distribution; the 224-byte unroll in the
full Hash variant only pays off above ~1 KB, and HashNano gives up
throughput beyond 48 bytes.  On an x86-64 workstation HashMicro hits
~34 GiB/s at 188 bytes vs. FNV-1a's ~10 GiB/s (3.5x) per-hash criterion
throughput.

End-to-end the ltm_mem_bench on WRLD3 shows ~4% wall time improvement
(47.2 ms -> 45.5 ms at budget 100K, 1.53 s -> 1.47 s at budget 10M,
median of 5 trials); memory footprint is unchanged.  The remainder of
the enumeration time is Johnson's DFS, Vec/HashSet bookkeeping, and the
per-cycle sort_unstable on the scratch buffer.

The Rust port is all-safe except for a single narrowly-scoped
from_raw_parts that reinterprets &[u32] as &[u8] -- documented with a
SAFETY comment covering liveness, alignment, overflow, and endianness.
A compile_error! guard refuses to build on big-endian targets; the hash
is intentionally byte-order-dependent so its output can key a salsa
cache across runs.  Byte-level output is cross-validated against the Go
reference port for 32+ test vectors spanning every branch of the length
dispatch cascade.

Two Rust-specific optimization notes baked into the port: (1) rapid_mum
uses u128::wrapping_mul so the 64x64->128 multiply lowers to a single
mulq on x86-64, (2) the 80-byte main loop and the 17..=80-byte tail
drain operate on typed &[u8; N] block slices so LLVM elides the
per-read slice bounds checks that would otherwise double runtime on our
inputs.  read64/read32 helpers are #[inline(always)]; hash_bytes and
hash_u32_slice are #[inline] to allow cross-crate inlining from
ltm.rs::johnson_circuit.
`generate_stock_to_flow_equation` computed `_is_affecting_stock` and
immediately discarded it.  The calculation didn't feed into the
generated equation (the LTM paper's stock-to-flow formula is symmetric
in whether the flow is an inflow or outflow of that stock) and was
dead code carried forward from earlier exploratory work.  Review found
it as part of the reduce-ltm-mem pass; filed as tech-debt #32 and
fixed inline here since it was a three-line removal.

The `all_vars: &HashMap<Ident<Canonical>, Variable>` parameter on the
function becomes unused and is removed at the same time; its sole
caller already had the map on hand but doesn't need to pass it.
@claude

claude Bot commented Apr 18, 2026

Copy link
Copy Markdown

Code Review

[P3] Stale test comment contradicts actual behavior

src/simlin-engine/src/db_analysis.rs (around lines 1610-1614, introduced in this PR):

/// A pure DAG produces zero circuits.  The `names` table still
/// reflects every node in the causal graph (the enumerator builds
/// the indexed graph before pruning SCCs), so we assert non-empty
/// -- callers that compare `names` to a legacy variable list should
/// use `to_named_circuits` for an exact match.
#[test]
fn test_loop_circuits_result_empty_on_dag() {

The comment claims the names table remains non-empty for a pure DAG and that the test asserts this, but find_indexed_circuits_with_limit returns (Vec::new(), circuits) whenever circuits.is_empty(), and the new find_indexed_circuits_empty_on_dag_returns_empty_names test in ltm.rs explicitly asserts names.is_empty() on a DAG. The test body here also never asserts names is non-empty — it only checks result.is_empty() and to_named_circuits().len() == 0. The comment should be updated to match the actual trimming behavior or removed.

[P3] Incorrect tech-debt cross-reference in MAX_LTM_CIRCUITS doc

src/simlin-engine/src/ltm.rs lines 28-30:

/// Removing this cap cleanly would require first capping the synthetic
/// variable count inside `model_ltm_variables` (or switching very
/// large models to discovery mode).  See tech-debt #31 for the plan.

Tech-debt item #31 added in this PR is RK4 + LTM Combination Has No Hard-Error Guard — unrelated to capping synthetic variable counts. No tech-debt item in the added #20–#32 range describes a plan for capping synthetic variables or splitting very large models into discovery mode. The #31 reference is stale; either point the comment at the correct item or add the missing tech-debt entry.

Overall correctness

Correct. The algorithmic changes (SCC-restricted Johnson's 1975 with blocked-set unblocking, indexed u32 DFS, shared rapidhash fingerprint dedup, compact name table) are well-tested: Tiernan oracle equivalence across a fixture corpus and 256-case proptest, budget semantics tests, multidigraph / figure-8 / cross-SCC coverage, and deterministic-across-calls verification. The rapidhash port is cross-validated byte-for-byte against the Go reference for small, medium, and large inputs including all-zero buffers. The unsafe slice::from_raw_parts cast is correctly SAFETY-commented and gated by a little-endian compile_error! guard. The 64-bit fingerprint collision risk (~1e-7 for wrld3-sized inputs) is an explicit, documented tradeoff already tracked in tech-debt #22. Only the two documentation nits above.

Two review-feedback fixes folded into one commit:

1) `ltm_mem_bench`'s root-model predicate was
`!m.is_stdlib && (n == "main" || n.is_empty() || m.source.name(&db) != "main")`,
whose third OR branch matches any non-stdlib model whose source name
isn't "main" -- i.e. every submodel on a multi-model project.
`sync.models` is a HashMap, so `.find()` returns an arbitrary entry and
the benchmark could silently report numbers for the wrong graph.
Replace with a direct lookup: the first entry of `datamodel.models` is
always the root, and looking it up by exact name in the sync result is
deterministic on any input.

2) `find_loops_with_limit` still invoked a separate `deduplicate_loops`
pass at the Loop level, and its comment referenced the long-removed
`dedup_circuits` helper.  After Johnson's inline per-SCC dedup in
`johnson_circuit`, every circuit that reaches `find_loops_with_limit`
already has a unique node-set, so the Loop-level pass is redundant.
Replace with a `debug_assert!(loops_have_unique_node_sets(...))`
invariant check so a future regression trips a test, delete the
function, and update the comment.
@claude

claude Bot commented Apr 18, 2026

Copy link
Copy Markdown

Review

No blocking issues found. This is a large but well-structured refactor with strong test coverage.

What I verified:

  • johnson_circuit correctly handles the budget/dedup interaction: duplicates (hash-collision or multidigraph rotations) mark found_cycle = true without consuming budget, preserving the unblock invariant. Unique emissions consume budget and push cycles; on bail-out, the stale seen.insert(fp) side effect is harmless since JohnsonState is discarded.
  • enumerate_circuits_in_scc resets blocked/b_list per start but carries seen across starts within an SCC. Cross-SCC duplicates are impossible because SCCs are vertex-disjoint, so the per-SCC state is sufficient.
  • find_indexed_circuits_with_limit trim+remap yields salsa-stable output: used_vec (sorted BTreeSet) maps into lex-sorted indexed.graph.nodes, so adding/renaming non-cyclic feeders doesn't perturb the trimmed names or compact indices. The find_indexed_circuits_trims_names_to_cycle_participants test pins this.
  • rapidhash.rs is deterministic given the fixed seed+secret, cross-validated against the Go reference port for lengths spanning every branch of the length cascade.
  • LoopCircuitsResult::is_empty() only checks circuits, but find_indexed_circuits_with_limit guarantees names.is_empty() == circuits.is_empty() by construction, and all circuit_names(idx) callers use 0..len() so no panic risk.
  • generate_stock_to_flow_equation dropping the all_vars parameter is justified — tech-debt build(deps-dev): bump react-dev-utils from 11.0.3 to 11.0.4 #32 documents the _is_affecting_stock was unused; caller generate_link_score_equation still uses all_vars for the flow-vs-stock dispatch, so nothing is lost.

Minor note (not flagging): The budget semantics shifted subtly — the old code decremented budget for every raw DFS emission and deduped post-hoc, while the new code decrements only on unique emissions. This is strictly better (duplicates no longer consume budget) and aligns with the MAX_LTM_CIRCUITS comment's stated intent of capping unique loops for the downstream pipeline.

Overall correctness

Correct.

bpowers added 2 commits April 18, 2026 10:21
Three review-feedback items rolled into one commit:

1) Budget accounting regression (P2).  After moving dedup into
`johnson_circuit`, the earlier change decremented the shared circuit
budget only for circuits that survived node-set deduplication.  On a
dense multidigraph the raw DFS discovers far more circuits than there
are unique node-sets (K9 has 125,664 elementary directed cycles but
only 502 distinct node sets), so a `find_*_with_limit(100_000)` call
could run the DFS past the cap before any `TruncatedByBudget` bail-out,
silently reintroducing the compile-time blow-up the cap is meant to
prevent.  Move the decrement ahead of the hash-fingerprint dedup step
so every raw emission is charged, and keep the `state.circuits.push`
guarded by `seen.insert(fp)` so peak memory stays proportional to
unique output.  A new K4 regression test pins the invariant: K4 has
11 unique node-set circuits but enough raw cycle discovery that a
budget of 11 correctly trips `TruncatedByBudget`.

2) Stale tech-debt cross-reference (P3).  `MAX_LTM_CIRCUITS`'s
rustdoc referenced "tech-debt #31" as the follow-up plan for cap
removal, but tech-debt #31 is the RK4+LTM guard item -- unrelated to
this cap.  Replace the cross-reference with a prose pointer to the
two real prerequisites (capping synthetic-variable count in
`model_ltm_variables`, or auto-falling back to discovery mode).

3) Stale test comment (P3).  `test_loop_circuits_result_empty_on_dag`
's comment described the pre-trimming behaviour ("names table still
reflects every node in the causal graph"), which contradicts how
`find_indexed_circuits_with_limit` works after the name-table
trimming landed earlier on this branch.  Update the comment to
describe the post-trim invariant, and strengthen the test body to
actively assert `result.names.is_empty()` on a pure DAG.
Comment listed "3 two-cycles" then enumerated six pairs; the test body
itself uses the correct C(4,2)+C(4,3)+C(4,4)=11 count so the assertion
was never affected, but the prose mismatch was confusing.
@claude

claude Bot commented Apr 18, 2026

Copy link
Copy Markdown

Review

Traced the three load-bearing pieces end to end:

  • Iterative Tarjan SCC in IndexedGraph::strongly_connected_components — frame push/pop ordering is correct; lowlink propagates to the parent only after the child frame completes, and the on_stack guard prevents cross-SCC contamination.
  • Johnson's circuit enumeration in johnson_circuit (src/simlin-engine/src/ltm.rs:730) — caller contract (push+block before recurse, pop after, unblock via johnson_unblock) matches the 1975 paper. Deviation from classical Johnson's — letting b_list[w] contain duplicate entries — is safe because johnson_unblock short-circuits on already-unblocked nodes, and the in-line comment at ltm.rs:822 explains this.
  • rapidhash V3 port (src/simlin-engine/src/rapidhash.rs) — the unsafe { slice::from_raw_parts } cast for u32→u8 is properly guarded by a compile-time little-endian assertion and the SAFETY comment covers alignment/lifetime/len. Cross-validation vectors against the Go reference are reassuring.

Hash-only dedup tradeoff. JohnsonState.seen: HashSet<u64> at ltm.rs:448 deliberately trades ~5e-8 (wrld3 birthday-bound) worth of silent circuit loss for bounded transient memory vs. the pre-PR HashSet<String> on main which did full-equality dedup. The comment at ltm.rs:490 frames this as "identical to the FNV-1a tradeoff the callsite already accepted," which is accurate for the intermediate state within this PR's commit chain but could read as implying main already accepted a hashing tradeoff — minor doc nit, not a correctness issue. debug_assert! on has_no_duplicate_node_sets guards over-emission in debug builds, and tech-debt item #28 already tracks the under-emission risk. Comfortable with the tradeoff as documented.

Overall correctness

Correct. No blocking issues found. The refactor preserves the enumeration contract (each node-set emitted at most once per SCC, self-loops excluded, circuits ≥ 2 nodes), and the memory-reduction changes don't introduce observable behavioral regressions beyond the acknowledged hash-collision tail risk.

@claude

claude Bot commented Apr 18, 2026

Copy link
Copy Markdown

Code review

No [P0]–[P2] findings.

Minor / nitpicks

  • [P3] src/simlin-engine/src/rapidhash.rs — the unsafe { slice::from_raw_parts } in hash_u32_slice is sound (alignment of u32 ≥ alignment of u8, length in bytes cannot overflow isize since values.len() * 4 on a 64-bit target is bounded by usize::MAX/4, and the little-endian compile-time guard covers the byte-order assumption). The SAFETY comment already captures this; no change required, just flagging that this is the only place where endianness is load-bearing if the crate is ever ported to a BE target.

  • [P3] src/simlin-engine/src/ltm.rs — state.seen is intentionally shared across starts within an SCC. This is correct because Johnson's algorithm emits each elementary circuit exactly once from the lex-smallest start, so cycles emitted from different starts have disjoint node-set fingerprints. A one-line comment above the field would save future readers the trace I just did.

  • [P3] src/simlin-engine/src/ltm.rs — find_indexed_circuits_with_limit trims the name table to only the indices referenced by returned circuits; the existing comment explains this. Consider a debug_assert! that every index in the returned circuits is < names.len() after trimming, as a cheap guard against a future refactor silently producing dangling indices.

  • [P3] The loops_have_unique_node_sets debug helper keys on (min_from, max_from, len). For circuits of length ≥ 2 with distinct nodes this is a reasonable fingerprint, but it's not a full node-set identity, so collisions are possible in principle. Since it's #[cfg(debug_assertions)]-only, the worst case is a false negative on the assertion, not a correctness bug — fine to leave as-is.

Overall correctness

Correct. The patch preserves existing LTM semantics while delivering a substantial memory/time reduction (the PR description cites ~17× memory and ~22× time on wrld3-03's 166-node SCC). Budget accounting was regressed in an earlier commit and correctly restored in commit 9 (budget decrements per raw cycle, before hash dedup), and the K4 regression test pins this behavior. Coverage is strong: Johnson-vs-Tiernan proptest equivalence (256 cases), the fixture corpus, targeted unit tests for unblock / dedup / budget, and the downstream LoopCircuitsResult API change is covered by build_element_level_loops's existing tests. The rapidhash port is cross-validated against the Go reference and gated to little-endian at compile time. Nothing here that I'd ask the author to change before merge.

Codex iteration 5 flagged that sorting each successor list in
`IndexedGraph::from_edges` "changes which directed-cycle rotation
survives dedup on multidigraph SCCs, which flows through to
polarity analysis".  That is true, but the pre-refactor code iterated
successors in HashMap-insertion order (the result of `from_model`
walking a `HashMap<Ident, Variable>`), which is **non-deterministic
across processes**.  So polarity on multidigraph cycles wasn't
previously pinned to any specific choice -- it varied with HashMap
seed between builds.

The sort turns that non-determinism into a deterministic canonical
representative: combined with the lex-ascending node order and the
hash-fingerprint node-set dedup in `johnson_circuit`, we now pick
the **lexicographically smallest sequence** among all rotations and
orientations of a given node-set.  For a fully-bidirectional K3 with
two three-cycles [a,b,c] and [a,c,b], the surviving representative
is [a,b,c].

Strengthen this from an implementation detail into a pinned invariant:
update the rustdoc on `IndexedGraph::from_edges` to state the
canonical-representative guarantee explicitly, and add a regression
test (`johnson_canonical_multidigraph_representative`) that asserts
K3 dedups to [a,b,c] specifically and that two independent
enumerations on the same graph are byte-identical.  Also cross-
referenced the test name from the rustdoc so future refactors can
find it.

This is a behaviour change only in the sense that the new behaviour
is DEFINED where the old behaviour was undefined; it is a strict
improvement for salsa cache stability, reproducible builds, and the
"representative's polarity" concern the review raised.
@bpowers

bpowers commented Apr 18, 2026

Copy link
Copy Markdown
Owner Author

Review-cycle summary

Six automated-review iterations over this branch; both reviewers (codex-review and the /review skill) landed clean in the same iteration at df2f240c.

Post-review improvements driven by reviewer feedback, beyond the original stack:

  • Hash determinism and correctness. The initial dedup used std::hash::RandomState (process-seeded), which meant the LoopCircuitsResult salsa cache value could silently reshuffle after the rare 2^64 collision. Ported a narrow rapidhash V3 slice (HashMicro variant) to src/simlin-engine/src/rapidhash.rs, cross-validated byte-for-byte against the Go reference port, with a compile-error guard against big-endian targets. All dedup fingerprints are now deterministic across runs; 3.5x faster throughput at LTM's 188-byte mean input size than the interim FNV-1a.

  • Dedup moved into per-SCC enumeration. Previously dedup ran as a post-hoc pass over all emitted circuits, which meant peak transient memory on dense multidigraph inputs was proportional to raw cycle count rather than unique output. Folding the dedup into johnson_circuit keeps state.circuits proportional to unique node-sets.

  • Name table trimmed to cycle-participants only. LoopCircuitsResult.names used to include every graph node, so renaming an acyclic feeder invalidated the salsa cache. Now compacted to only the nodes that appear in at least one circuit; find_indexed_circuits_trims_names_to_cycle_participants regression-tests the invariant.

  • Budget correctly charges on every raw cycle. The intermediate implementation only decremented max_circuits for unique-node-set survivors, which let dense multidigraphs run DFS past the cap (K9: 125k raw cycles but only 502 unique node-sets). New johnson_budget_charges_duplicate_raw_cycles test pins K4 as a minimal fixture.

  • Canonical multidigraph representative pinned. The pre-refactor code iterated successors in HashMap-insertion order, so polarity on multidigraph cycles was non-deterministic across processes. Sorting successors lex-ascending converts that into a canonical "lex-smallest sequence" guarantee; johnson_canonical_multidigraph_representative documents and pins the invariant with an explicit K3 assertion.

  • Small hygiene. Dropped the unused _is_affecting_stock flag in ltm_augment.rs, tightened the bench's root-model lookup to be deterministic on multi-model projects, removed the now-redundant Loop-level deduplicate_loops call (replaced with a debug_assert! invariant check), and fixed several stale doc comments that referenced removed helpers or the wrong tech-debt item.

Net wrld3-03 impact unchanged from the opening numbers (17x memory, 22x wall-time at uncapped; the production 100K-cap path at ~33 MiB / ~29 ms). The six review iterations tightened correctness, determinism, and observability around those numbers without changing them.

@claude

claude Bot commented Apr 18, 2026

Copy link
Copy Markdown

Review of PR #459 — engine: reduce LTM circuit-enumeration memory and time on dense graphs

I reviewed the stack end-to-end against main: the IndexedGraph/Tarjan/Johnson rewrite in src/simlin-engine/src/ltm.rs, the rapidhash port, the LoopCircuitsResult refactor in db_analysis.rs/db_ltm.rs, the salsa caching story, the new ltm_mem_bench harness, and the test surface (proptest regressions, Johnson↔Tiernan equivalence, fixtures, multidigraph canonical-representative test).

Findings

Nothing rising to P0/P1. A few minor notes:

[P3] ltm.rs from_edges — edge-list iteration is non-deterministic before dedup
from_edges pushes successors in HashMap-iteration order, then sort_unstable/dedup. The sort+dedup does recover determinism for the final successor list, so this is cosmetic — but a one-line comment confirming the subsequent sort is what the determinism claim leans on would help future readers (the commentary around L530–L548 already nails the canonical-representative invariant; this is just belt-and-suspenders on the prior push order).

[P3] ltm.rs enumerate_circuits_in_scc — per-SCC vec![_; n] allocation
JohnsonState allocates blocked, b_list, and in_scc sized to self.nodes.len() (the whole graph) once per SCC. On a graph with many small SCCs this is wasteful vs. sizing to scc.len() with a local index remap. On wrld3-03's single 166-node SCC this is a no-op; filing as a note, not a blocker.

[P3] rapidhash.rs — #[cfg(target_endian = "little")] guard
The compile_error! on big-endian is correct and defensive. Worth noting: WASM (our primary non-native target) is LE, so this doesn't foreclose anything real. No change needed.

[P3] MAX_LTM_CIRCUITS = 100_000
The updated rustdoc (pointing at downstream OOM risk in the variable-generation pipeline rather than the enumerator itself) is accurate and the right framing. If the cap is ever lifted, the enumerator itself is now easily capable of 1.86M; the bottleneck has genuinely moved downstream.

What I verified

  • Johnson correctness. Budget is charged per raw emitted cycle (pre-dedup) at the recursive-call site, matching the ad2beb95 fix; dedup happens after budget accounting so a pathological duplicate-heavy SCC cannot sneak past the cap. b_list registration and transitive unblock match the 1975 paper. Self-loop exclusion via path.len() > 1 is consistent with the enumerate_circuits_in_scc size-1 short-circuit.
  • Iterative Tarjan. Enter/Resume frame pattern is correct; lowlink propagation to the parent frame happens before SCC emission; on_stack is cleared on pop; SCC order is sorted for determinism.
  • Canonical multidigraph representative. Lex-smallest start node + sorted successors + sort-before-hash gives a deterministic representative across processes. Regression test johnson_canonical_multidigraph_representative pins this.
  • rapidhash determinism. Fixed CIRCUIT_HASH_SEED + default secret + little-endian byte view → salsa cache stability across runs. Cross-validated against Go reference with 32+ vectors. Single unsafe block for &[u32]→&[u8] reinterpret has a thorough SAFETY comment covering alignment (u32 ≥ u8) and length.
  • Collision probability. ~5e-8 over 1.86M circuits (2^64 birthday), documented at the hash callsite; same tradeoff already accepted for the prior FNV-1a keying, and vastly cheaper than HashSet<Vec<u32>>.
  • Name-table trimming. find_indexed_circuits_with_limit trims the shared names table to only idents actually referenced by surviving circuits, which is what lets db_ltm::build_element_level_loops materialize Vec<&str> slices borrowing into that table without bloat.
  • Test coverage. 256-case proptest with regression seed file, Johnson↔Tiernan equivalence oracle, fixture corpus, multidigraph canonical-rep test, ltm_mem_bench on wrld3. Extensive debug_assert!s on invariants.

Overall correctness

Correct. The stack is a well-engineered memory/time win (8.45 GiB / 27s → 491 MiB / 1.2s on wrld3-03) with no correctness regressions I can identify. Trade-offs (fingerprint collisions, fixed seed as salsa-schema constant, retention of the MAX_LTM_CIRCUITS cap) are all explicitly called out in rustdoc with appropriate reasoning. The Tiernan oracle is retained as a test-only equivalence check, which is exactly the right belt-and-suspenders for swapping algorithmic cores. Ship it.

Triaged the P3 nits on PR #459 and took this further: where the
pre-refactor code was non-deterministic across processes and tests
didn't require any specific ordering, we were adding sorts in
production code to pin incidental behaviour.  Following the "Go
philosophy" -- embrace HashMap-iteration non-determinism and force
callers to normalize where they actually need a specific order -- the
following sorts are now dropped:

* Per-node successor list in `IndexedGraph::from_edges`: was sorted
  ascending + `dedup()`.  The sort pinned a canonical "lex-smallest
  rotation" for multidigraph cycles (cases like K_n with every pair
  bidirectional).  No production consumer requires that rotation --
  downstream polarity, stock enrichment, and loop ID assignment all
  consume either the node-set (rotation-invariant) or content-sorted
  content (independent of DFS order).  Replaced the sort with a
  per-node HashSet<u32> dedup that preserves first-seen insertion
  order, which matches the pre-refactor behaviour exactly (the same
  HashMap-iteration-driven non-determinism).

* Inner-SCC sort in `IndexedGraph::tarjan_scc`: each SCC's members
  were sorted ascending.  `enumerate_circuits_in_scc` iterates starts
  in whatever order they appear, and each cycle still surfaces from
  its index-smallest member via the `w < start` gate -- unaffected by
  iteration order.

* Outer SCC sort in `enumerate_indexed_circuits`: SCCs were sorted by
  smallest index before iteration.  Each SCC contributes independently
  to the output so ordering has no effect on correctness.

The node-index assignment in `IndexedGraph::from_edges` stays sorted
(nodes lex-ascending -> u32 index); this one provides user-facing
output consistency (`circuits[0]` starts with the lex-smallest node
of the cycle, which is nice for human diffing across builds) and
costs essentially nothing.

Test impact: `johnson_canonical_multidigraph_representative` was
removed (it pinned [a,b,c] specifically for K3, which no longer holds)
and replaced with `johnson_multidigraph_dedups_to_single_node_set`,
which only checks that the dedup folds K3's two directed 3-cycles
into exactly one circuit with node-set {a,b,c} -- rotation-invariant
and correct under any DFS order.  Within-process repeat-call
determinism is still guaranteed by `dedup_deterministic_across_calls`
(HashMap iteration order is stable per-instance, same hasher seed).

Also fold in several P3 doc/test-hygiene items from the PR review:

* Expanded the rustdoc above `JohnsonState.seen` to spell out why the
  fingerprint set is safely shared across all DFS starts within a
  single SCC (Johnson's emits each cycle from its index-smallest
  start, so per-start cycle node-sets are disjoint; the sharing only
  matters for multidigraph rotations within a single start).
* Reworded the "identical to FNV-1a tradeoff" rustdoc to avoid
  implying main ever keyed on FNV-1a.
* Added a `debug_assert!` in `find_indexed_circuits_with_limit` that
  every remapped compact index addresses a valid entry in the trimmed
  `names` table -- cheap guard against future refactors silently
  producing dangling indices.
* Marked tech-debt #23 (LTM was Tiernan-style) as resolved; production
  code now implements Johnson's proper.  Kept the entry as a
  historical pointer.

Benchmark unchanged within noise on wrld3-03: 100K-cap peak 32 MiB,
uncapped peak 467 MiB / 1.47 s.
@bpowers

bpowers commented Apr 18, 2026

Copy link
Copy Markdown
Owner Author

Address-feedback iteration 6b: strip incidental determinism

Triaged every comment/review on this PR. The P3 nits (updated state.seen rustdoc, FNV-1a phrasing, find_indexed_circuits_with_limit debug_assert, tech-debt #23 resolution note, from_edges non-determinism note) are addressed in e771dc27.

The same commit also takes the user's explicit "embrace non-determinism unless correctness demands it" guidance and rolls back the successor-list sort in from_edges, the inner-SCC sort in tarjan_scc, and the outer SCC-iteration sort in enumerate_indexed_circuits. All three were pure incidental determinism: no production consumer requires the specific order they pinned, and only one test (johnson_canonical_multidigraph_representative, which this PR itself added) relied on them. That test is replaced with johnson_multidigraph_dedups_to_single_node_set, which asserts the correctness-relevant property (K3's two 3-cycles fold into one circuit with node-set {a,b,c}) without pinning a rotation.

Within-process determinism is still guaranteed (HashMap iteration is stable for a given instance), so LoopCircuitsResult salsa caching continues to work. Cross-process rotation on multidigraph cycles now matches the pre-refactor behaviour -- which was already non-deterministic -- but the new code is organized to make the non-determinism explicit in code comments rather than incidental.

The one deferred item -- sizing JohnsonState.blocked / b_list to the current SCC's node count rather than the whole graph's -- was filed as issue #460 for a follow-up. It's a real allocation win on hypothetical graphs with many small SCCs in a large node space, but wrld3-03's single 166-node SCC makes it a no-op in practice.

wrld3-03 bench unchanged within noise: 100K-cap ~32 MiB / ~50 ms, uncapped ~467 MiB / ~1.47 s.

@claude

claude Bot commented Apr 18, 2026

Copy link
Copy Markdown

Review — LTM circuit enumeration rewrite

Read through the 5-commit stack end-to-end (Johnson + Tarjan + indexed graph + rapidhash + SCC dedup). The algorithmic work looks correct and well-tested: the Johnson/Tiernan proptest at 256 cases, the K_n multidigraph cases, and the fixture corpus give good coverage, and the budget/dedup/unblock interactions are carefully commented. The raw-cycle budget charge is called out explicitly and is defensible.

The issues I found are all in the docs, not the code: three spots assert a sort invariant that the implementation deliberately doesn't hold. Two of them directly contradict comments that sit a few lines away in the same function, which will mislead the next person doing surgery here.

P2 — Tarjan SCC docstring contradicts implementation

src/simlin-engine/src/ltm.rs:577-579 (docstring on tarjan_scc):

each inner `Vec` is sorted ascending so downstream iteration is deterministic regardless of the order nodes were popped from Tarjan's stack.

But the body (lines 650-658) explicitly says the opposite:

SCCs are returned in whatever order Tarjan's stack popped them; callers that need a specific iteration order over SCC members must sort themselves.

No `sort_unstable` is called on `scc` before the push. One or the other has to go — assuming the body comment is the truth (it matches the code), please strip the "sorted ascending" sentence from the docstring.

P2 — `IndexedGraph::from_edges` docstring contradicts implementation

`src/simlin-engine/src/ltm.rs:515-517`:

Successor indices are de-duplicated and sorted so the DFS can early-exit on the first out-of-range neighbor when needed.

The body (lines 534-551) dedups but deliberately does not sort, with a long comment explaining why (multidigraph rotation choice, no canonical invariant pinned). There's no early-exit on out-of-range neighbors in `johnson_circuit` either — it `continue`s on every mismatch. Please rewrite the docstring to match the body comment.

P2 — `johnson_circuit` inline comment asserts the same false sort invariant

`src/simlin-engine/src/ltm.rs:771-772`:

Successor list is already sorted ascending by `IndexedGraph::from_edges`. Index iteration avoids holding an immutable borrow on `self.succ` across the recursive call.

Same story — successor lists are in first-seen insertion order, not sorted. The second half (index iteration to avoid the borrow) is accurate and worth keeping; just fix the first sentence.

P3 — note, not a bug: budget semantics change

The budget is now charged per raw cycle rather than per unique emission (lines 802-809). On a dense multidigraph like K9, raw cycles can 250× the unique-set count, so `MAX_LTM_CIRCUITS` can now trip on models where the old unique-keyed counter wouldn't. The comment argues this correctly — the cap bounds DFS work, not output size — and I agree it's the right semantics. Just worth keeping in mind if a user reports "my model now hits the truncation cap where it didn't before"; the right fix in that case is raising the cap, not undoing this change.

Overall correctness: LGTM modulo docstring fixes

Algorithmically sound. The three doc bugs above are trivial to fix (no code change) but they're actively misleading because they contradict nearby comments that describe the real behavior. Worth catching before this ships as a reference point for future work in this file.

@bpowers
bpowers merged commit a4a632d into main Apr 18, 2026
9 of 10 checks passed
@bpowers
bpowers deleted the reduce-ltm-mem branch April 18, 2026 18:50
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