Skip to content

engine: size johnson state to scc not whole graph - #493

Merged
bpowers merged 1 commit into
mainfrom
ltm/460-johnson-per-scc-alloc
May 7, 2026
Merged

bpowers merged 1 commit into
mainfrom
ltm/460-johnson-per-scc-alloc

Conversation

@bpowers

@bpowers bpowers commented May 7, 2026

Copy link
Copy Markdown
Owner

Summary

IndexedGraph::enumerate_circuits_in_scc now sizes its JohnsonState (blocked, b_list) to the SCC's node count rather than the whole indexed graph. SCC membership and local indexing are funneled through a global_to_local: Vec<i32> map allocated once per top-level enumeration call (in enumerate_indexed_circuits) and reset between SCCs by walking the previous SCC's members. The in_scc: Vec<bool> field is gone -- global_to_local[w] >= 0 plays the same role on the hot path while folding the membership probe into the same array we already have to consult to index the per-SCC buffers.

Emitted circuits keep using global node ids (the public contract that downstream dedup and build_element_level_loops rely on); only blocked and b_list are indexed by local ids. The cycle-fingerprint hash is computed on the already-global path, so dedup behaviour is byte-identical to the pre-refactor version.

A golden multi-SCC unit test (johnson_multi_scc_in_large_node_space_golden) pins the emitted circuits against the pre-fix output, plus the existing Johnson<->Tiernan property test still covers the random graphs path.

The johnson_unblock work stack and b_list waiter slots stay as u32 (matching the pre-refactor element width) so per-allocation byte counts on graphs like wrld3 remain identical.

Benchmark numbers

Captured via examples/ltm_mem_bench, which now also accepts --synthetic to build ~10K nodes spread across 200 SCCs of mixed sizes (50x5-cycle, 50x10-cycle, 80x50-cycle, 20x100-cycle) plus 3.5K acyclic feeder/sink padding. The benchmark uses a tracking GlobalAlloc to surface enumeration-window allocations directly (peak RSS is too page-coarse to move on transient per-SCC allocations).

Synthetic (10,250 nodes-with-out-edges, 200 non-trivial SCCs, sizes 5/10/50/100):

bytes allocated wall-time (median of 10)
BEFORE 76,023,954 (72.5 MiB) ~27 ms
AFTER 4,747,704 (4.5 MiB) ~9 ms

~16x fewer bytes through the enumeration window, ~3x faster wall-time. The wall-time win comes from less allocator pressure; raw DFS work was already O(|SCC|) per start.

wrld3 (313 nodes, 1 non-trivial SCC of 166 members, budget=100,000):

bytes allocated wall-time (median of 15)
BEFORE 53,878,487 (51.383 MiB) ~89.7 ms
AFTER 53,875,751 (51.380 MiB) ~87.7 ms

Single-SCC path is essentially unchanged: same allocation count (2,512,173) and within ~3 KiB on bytes (the ~313-byte savings from removing in_scc partly offset by the one-time global_to_local: Vec<i32> allocation). Wall-time is within noise; AFTER median is marginally faster, well under the 5% regression threshold called out in the issue brief. The DFS extra indirection through global_to_local[w] did not measurably hurt the dense-graph case.

TDD

  1. Added johnson_multi_scc_in_large_node_space_golden. Captured the byte-identical baseline output BEFORE the fix (matches the existing implementation exactly); the test still passes after the fix.
  2. Implemented the per-SCC sizing with a global<->local remap.
  3. cargo test -p simlin-engine -- 3,156 lib tests pass; integration tests including simulate_ltm (48 tests, file_io feature) pass.
  4. cargo clippy --workspace --all-targets -- -D warnings -- clean (the only remaining warnings are pre-existing C++ warnings from xmutil, unrelated to this PR).

Fixes #460

Per-SCC allocations in enumerate_circuits_in_scc now size to
scc.len() with a global<->local index remap. Drops transient
allocation from O(|graph|) to O(|SCC|) per call without changing
emitted circuit output. Wrld3 single-SCC path validated for no
DFS regression.
@claude

claude Bot commented May 7, 2026

Copy link
Copy Markdown

Review summary

Reviewed the per-SCC sizing refactor and the bench harness changes. The local/global indexing split is consistent throughout: path/circuits/hash_scratch retain global ids (preserving the public contract), blocked/b_list are local-indexed, the cycle gates (w == start, w < start) use globals, and johnson_unblock operates entirely in local space because b_list waiters are pushed as v_local as u32. The global_to_local map's lifecycle is correct in practice — populated on SCC entry, walked-clear on success exit, and on the truncation early-return path the stale entries are unobservable because the only callers drop the Vec immediately. The new johnson_multi_scc_in_large_node_space_golden test pins the emitted circuits across mixed SCC sizes embedded in a large node space, and the Johnson↔Tiernan equivalence test is threaded through with the new param.

No blocking issues found.

Overall correctness verdict

Correct.

@bpowers bpowers left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Code Review: PR #493 - engine: size johnson state to scc not whole graph

Verification evidence

  • cargo test -p simlin-engine --lib johnson -- 18/18 johnson tests pass (including the 256-case johnson_matches_tiernan_on_random_small_graphs proptest and the new golden), <0.01s wall.
  • cargo test -p simlin-engine --lib -- 3,156 passed, 0 failed, 2 ignored, 3.59s.
  • cargo test -p simlin-engine --lib ltm -- 267/267 ltm tests pass.
  • cargo clippy -p simlin-engine --all-targets -- -D warnings -- clean.
  • Reproduced reported numbers locally with the same hardware on both sides of the diff:
    • main + this PR's bench: 76,023,954 bytes / 24.65 ms (BEFORE)
    • PR branch: 4,747,704 bytes / 10.47 ms (AFTER)
    • Same circuit count (200), same length distribution (min=5, max=100, mean=33.8) -> output is byte-identical, as the PR description claims.

Plan alignment

Issue #460 asks for blocked / b_list / in_scc to be sized to scc.len() with a global_to_local: Vec<i32> map (sentinel -1) hoisted to one allocation per top-level call. The PR does exactly that, plus removes in_scc entirely (re-using global_to_local's >= 0 check for membership). The in_scc removal is the load-bearing piece for the wrld3 timing claim ("marginally faster" instead of marginally slower) -- splitting it out would shed one of the two reported wins. I do not consider it scope creep; see the question for the author below.

Critical issues

None. The DFS hot path is correct under the new indexing scheme:

  1. The membership probe let w_local = global_to_local[w as usize]; if w_local < 0 || w < start { continue; } short-circuits on -1 BEFORE any local-indexed access; the subsequent let w_local = w_local as usize shadow is reached only with w_local >= 0, so no as usize cast on -1.
  2. johnson_circuit is only called from inside enumerate_circuits_in_scc with vertices already established as SCC members (the for &start in scc loop and the post-membership-check recurse at line 948), so let v_local = global_to_local[v as usize] as usize; at the top of the function is safe.
  3. The reset between SCCs walks ONLY the previous SCC's members (lines 835-837), never the whole global_to_local -- O(|SCC|) not O(|graph|). The walk is ordered AFTER the inner for &start in scc loop and BEFORE the next SCC's setup writes, so no contamination.
  4. Path entries (state.path) and emitted circuits stay in GLOBAL ids; state.blocked/state.b_list use LOCAL ids; the cycle-fingerprint hash is computed on the global path, so byte-identical dedup behavior. The 3,156-test suite confirms this empirically, and the synthetic-bench output reproduces the same circuit count and length distribution byte-for-byte across the diff.
  5. johnson_unblock operates entirely in the local index space (waiters pushed as v_local as u32, popped and indexed into state.blocked/state.b_list as locals). The work-stack Vec<u32> width is preserved per the PR description's wrld3 byte-identical claim.
  6. The proptest johnson_matches_tiernan_on_random_small_graphs (256 cases, n in 2..=8, up to 16 random edges) exercises the multi-SCC, self-loop, and bidirectional-edge paths; the Tiernan oracle path is untouched, and equivalence still holds.

Important issues

None.

Minor issues / observations

  • Clean-up on early-return is silently skipped on budget exhaustion (lines 829 + 832-837). If johnson_circuit returns Err(TruncatedByBudgetInternal), the cleanup loop is skipped and global_to_local is left dirty. This is harmless because the only caller (enumerate_indexed_circuits) propagates the error and drops its Vec, but the comment at lines 832-834 ("Restore global_to_local for the next SCC") is slightly misleading -- on bail-out there is no next SCC. A one-line clarification ("on success path; bail-out abandons the map and the caller drops its Vec") would prevent future readers from worrying.
  • Wall-time methodology not visible in code. The PR description quotes "median of 10" / "median of 15" runs, but the bench runs once per invocation. The implementer presumably ran the bench multiple times and computed the median externally; that is fine, but having it in the description (or a small driver script in the example) would make the result reproducible without trust. Worth a sentence in the PR body.
  • Trivial nit in connected_component_stats (examples/ltm_mem_bench.rs:228): undir.entry(from).or_default(); is followed by undir.entry(from).or_default().push(to) inside the tos loop -- the leading entry().or_default() is redundant when the source has out-edges. Pre-existing structure though, not introduced by this PR.
  • Commit author is test <[email protected]> rather than the user's git identity. Squash-merge through GitHub will fix this, but worth noting.

Praise

  • The redocumented JohnsonState block (lines 484-507) is exemplary "explain the why" rustdoc: it pins the global-vs-local indexing convention in one place that every future reader of enumerate_circuits_in_scc and johnson_circuit can refer to. The matching identifier-conventions paragraph on johnson_circuit (lines 853-859) is the right level of repetition for a recursive function.
  • The in_scc removal is the right level of follow-through. Folding the membership probe into global_to_local removes a parallel array and reduces hot-loop probes per neighbor from 2 to 1; that is the load-bearing reason wrld3 came out marginally faster instead of marginally slower (the issue's #1 fear was DFS regression on the dense-graph case).
  • The golden test johnson_multi_scc_in_large_node_space_golden is a real golden, not "non-empty": it asserts the exact set of node-sets per SCC, including the K3 multidigraph dedup-to-one-3-cycle invariant and the chord-induced 3-cycle in scc4. Plus it cross-checks via assert_johnson_matches_tiernan(&cg) so any drift the public dedup might mask still trips.
  • The synthetic bench mode is deterministic (seed-free, lex-ordered names) and matches the issue's exact prescription (50x5, 50x10, 80x50, 20x100 SCCs + 3.5K acyclic padding -> 13.75K total nodes).
  • The tracking GlobalAlloc is a standard counters-around-System pattern (no exotic per-thread state) and is gated to the examples/ltm_mem_bench.rs binary -- it does NOT apply to lib.rs or test builds.

Question for the author

The PR removes in_scc in the same commit as the per-SCC resize. That is in scope per the comment at lines 887-893 (folding the membership probe into global_to_local is what shaves the per-neighbor probe count and is what makes the wrld3 timing not regress). The reported numbers are consistent with both pieces being present.

Two questions, in order of importance:

  1. Was the resize alone (keeping in_scc whole-graph) ever measured separately? If yes, what fraction of the 16x synthetic byte savings is attributable to the resize vs. the in_scc removal? If the resize alone gets ~14-15x of the 16x and a clean ~2 ms wrld3 nudge, this PR is clearly best as one unit. If the resize alone gets the full 16x and the in_scc removal is purely a wrld3 hot-path tweak, the latter would be cleanly separable. (My read of the code says it is the latter, and the wrld3 number is consistent -- I am asking to confirm, not to redo the work.)
  2. Independent of #1: would you mind appending the wall-time sampling methodology ("median of 15 runs of cargo run --release --example ltm_mem_bench --, machine X, ...") to the PR body? It is not in the description today and the bench code itself only runs once per invocation.

Decision

COMMENT-ONLY -- not blocking. No correctness issues, all tests pass, reported numbers reproduce locally. The minor items above are non-blocking; address as you like.

@codecov

codecov Bot commented May 7, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 82.39%. Comparing base (dde79c3) to head (ad8ce2e).

Additional details and impacted files
@@           Coverage Diff           @@
##             main     #493   +/-   ##
=======================================
  Coverage   82.38%   82.39%           
=======================================
  Files         238      238           
  Lines       61512    61519    +7     
=======================================
+ Hits        50679    50686    +7     
  Misses      10833    10833           

☔ 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 marked this pull request as ready for review May 7, 2026 13:44
@bpowers

bpowers commented May 7, 2026

Copy link
Copy Markdown
Owner Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. More of your lovely PRs please.

ℹ️ 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".

@bpowers
bpowers merged commit d136a07 into main May 7, 2026
16 checks passed
@bpowers
bpowers deleted the ltm/460-johnson-per-scc-alloc branch May 7, 2026 14:02
@bpowers bpowers mentioned this pull request May 7, 2026
5 tasks done
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.

ltm: JohnsonState per-SCC allocation sized to whole-graph node count

1 participant