Repository navigation
engine: size johnson state to scc not whole graph - #493
Conversation
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.
Review summaryReviewed the per-SCC sizing refactor and the bench harness changes. The local/global indexing split is consistent throughout: No blocking issues found. Overall correctness verdictCorrect. |
bpowers
left a comment
There was a problem hiding this comment.
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-casejohnson_matches_tiernan_on_random_small_graphsproptest 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:
- The membership probe
let w_local = global_to_local[w as usize]; if w_local < 0 || w < start { continue; }short-circuits on-1BEFORE any local-indexed access; the subsequentlet w_local = w_local as usizeshadow is reached only withw_local >= 0, so noas usizecast on-1. johnson_circuitis only called from insideenumerate_circuits_in_sccwith vertices already established as SCC members (thefor &start in sccloop and the post-membership-check recurse at line 948), solet v_local = global_to_local[v as usize] as usize;at the top of the function is safe.- 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 innerfor &start in sccloop and BEFORE the next SCC's setup writes, so no contamination. - Path entries (
state.path) and emitted circuits stay in GLOBAL ids;state.blocked/state.b_listuse 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. johnson_unblockoperates entirely in the local index space (waiters pushed asv_local as u32, popped and indexed intostate.blocked/state.b_listas locals). The work-stackVec<u32>width is preserved per the PR description's wrld3 byte-identical claim.- 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_circuitreturnsErr(TruncatedByBudgetInternal), the cleanup loop is skipped andglobal_to_localis left dirty. This is harmless because the only caller (enumerate_indexed_circuits) propagates the error and drops itsVec, but the comment at lines 832-834 ("Restoreglobal_to_localfor 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 byundir.entry(from).or_default().push(to)inside thetosloop -- the leadingentry().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
JohnsonStateblock (lines 484-507) is exemplary "explain the why" rustdoc: it pins the global-vs-local indexing convention in one place that every future reader ofenumerate_circuits_in_sccandjohnson_circuitcan refer to. The matching identifier-conventions paragraph onjohnson_circuit(lines 853-859) is the right level of repetition for a recursive function. - The
in_sccremoval is the right level of follow-through. Folding the membership probe intoglobal_to_localremoves 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_goldenis 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 inscc4. Plus it cross-checks viaassert_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
GlobalAllocis a standard counters-around-System pattern (no exotic per-thread state) and is gated to theexamples/ltm_mem_bench.rsbinary -- it does NOT apply tolib.rsor 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:
- Was the resize alone (keeping
in_sccwhole-graph) ever measured separately? If yes, what fraction of the 16x synthetic byte savings is attributable to the resize vs. thein_sccremoval? 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 thein_sccremoval 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.) - 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 Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
|
@codex review |
|
Codex Review: Didn't find any major issues. More of your lovely PRs please. ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
Summary
IndexedGraph::enumerate_circuits_in_sccnow sizes itsJohnsonState(blocked,b_list) to the SCC's node count rather than the whole indexed graph. SCC membership and local indexing are funneled through aglobal_to_local: Vec<i32>map allocated once per top-level enumeration call (inenumerate_indexed_circuits) and reset between SCCs by walking the previous SCC's members. Thein_scc: Vec<bool>field is gone --global_to_local[w] >= 0plays 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_loopsrely on); onlyblockedandb_listare indexed by local ids. The cycle-fingerprint hash is computed on the already-globalpath, 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_unblockwork stack andb_listwaiter slots stay asu32(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--syntheticto 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 trackingGlobalAllocto 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):
~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):
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_sccpartly offset by the one-timeglobal_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 throughglobal_to_local[w]did not measurably hurt the dense-graph case.TDD
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.cargo test -p simlin-engine-- 3,156 lib tests pass; integration tests includingsimulate_ltm(48 tests, file_io feature) pass.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