Skip to content

engine: dedup ltm cycles by canonical edge sequence (#308) - #494

Merged
bpowers merged 24 commits into
mainfrom
ltm/308-canonical-cycle-dedup
May 8, 2026
Merged

bpowers merged 24 commits into
mainfrom
ltm/308-canonical-cycle-dedup

Conversation

@bpowers

@bpowers bpowers commented May 7, 2026

Copy link
Copy Markdown
Owner

Summary

LTM currently dedups feedback loops by sorted node-set, collapsing distinct directed cycles like A -> B -> C -> A and A -> C -> B -> A into one Loop. This contradicts the elementary-circuit identity used in the LTM literature: cycle identity is determined by the directed edge sequence, not just the set of participating variables. Two cycles with the same node set can have different polarity products and different scores.

This PR replaces the sorted-node-set dedup key with a canonical edge-sequence rotation: rotate each circuit so it starts at the lex-smallest position, then compare the ordered node sequence (which on an elementary cycle determines the edge sequence). Two distinct directed cycles over the same node set now canonicalize to different keys and are retained as separate loops.

Fixes #308.

Identity rule

A circuit [v0, v1, ..., v_{n-1}] represents the directed elementary cycle v0 -> v1 -> ... -> v_{n-1} -> v0. Two circuits represent the same cycle iff one is a cyclic rotation of the other. The canonical rotation is the one whose full ordered node sequence is lex-smallest among all n rotations. Element-wise comparison proceeds left-to-right; the first differing position decides. The (node, next_node) lex order is the natural tiebreaker for any hypothetical input with equal starting nodes (elementary cycles never have repeated nodes).

The new helper canonical_rotation<T: Ord + Clone> is shared by all three call sites; the IndexedGraph path keys on Vec<u32> and the discovery path on Vec<String>.

Design note: docs/design-plans/2026-05-06-ltm-308-canonical-cycle-dedup.md.

Application points

Site File Key type
IndexedGraph::johnson_circuit src/simlin-engine/src/ltm.rs Vec<u32> (rapidhash fingerprint)
SearchGraph::add_loop_if_unique src/simlin-engine/src/ltm_finding.rs Vec<String>
discover_loops_with_graph (cross-timestep dedup) src/simlin-engine/src/ltm_finding.rs Vec<String>

Fixture changes

Fixture Before After Notes
discovery_arms_race_3party (tests/simulate_ltm.rs) 7 loops 8 loops 3 self-balancing + 3 pairwise reinforcing + 2 three-way (forward + reverse)
johnson_complete_k3_all_directed_cycles (src/ltm.rs) 4 circuits 5 circuits K3 multidigraph: 3 two-cycles + 2 distinct three-cycles
johnson_multidigraph_dedups_to_single_node_set (src/ltm.rs) 1 three-cycle 2 three-cycles Renamed johnson_multidigraph_keeps_distinct_directed_cycles
johnson_budget_charges_duplicate_raw_cycles (src/ltm.rs) 11 circuits 20 circuits Renamed johnson_budget_bounds_unique_directed_cycles. K4 has 6 + 8 + 6 distinct directed cycles

The wrld3_element_level_enumeration_is_uncapped test (#[ignore]d) had its assertion loosened from ==1_863_803 to >=1_863_803 because the exact post-fix count will be remeasured next time it is run on-demand.

Determinism / id stability

  • The canonical rotation is uniquely defined by the input slice, so rotation order is fully deterministic across runs.
  • Loop ids assigned by assign_loop_ids (sorted by underlying variable set) are stable: existing loops keep their ids; previously-collapsed loops simply gain new ids.
  • Salsa cache keys (LoopCircuitsResult from model_loop_circuits) remain deterministic. The rapidhash fingerprint seed is unchanged; only the bytes hashed differ (canonical rotation vs sorted set), and the cache stores actual circuits, not fingerprints.

The dedup_deterministic_across_calls unit test continues to pin within-process determinism on K3 with all 6 directed edges.

Risks

  • This is a correctness behavior change. Loop counts grow on any model whose dependency graph contains symmetric / multidigraph SCCs. Empirically rare in real SD models -- only the explicitly-symmetric arms-race fixture among existing tests was affected.
  • Loop ids previously assigned to a node-set may now point to one of two siblings (forward direction); the second direction gets a new id. Downstream callers that assume "one loop per node set" must be updated separately if any exist outside this PR's scope -- a search of the repo did not surface any.

Drive-by fix in the same branch (commit 1)

src/simlin-serve/src/git.rs::run_git and the in-test must_git helpers now strip every GIT_* env variable before spawning. Without this, cargo test --workspace invoked from inside the project pre-commit hook inherits GIT_DIR/GIT_WORK_TREE and the inner git commit operates on the outer repository instead of the freshly-git init'd temp dir, producing pathspec failures and recursive pre-commit hook invocation. Discovered while running this branch's pre-commit hook.

Test plan

  • cargo test -p simlin-engine passes (3,161 lib tests + 48 simulate_ltm + every other integration suite).
  • cargo clippy --workspace --all-targets -- -D warnings clean.
  • All three application sites have failing-test-first regressions (canonical_rotation_distinguishes_opposite_directions, deduplicate_keeps_both_directed_three_cycles_in_multidigraph, add_loop_if_unique_keeps_distinct_directed_three_cycles) plus the existing discovery_arms_race_3party integration test now exercises the change end-to-end.
  • Workspace tests via pre-commit hook (run on review).

@claude

claude Bot commented May 7, 2026

Copy link
Copy Markdown

Review

I worked through the PR end-to-end (canonical-rotation algorithm, all three application sites, fixture updates, and the git.rs env-strip drive-by). The dedup change is sound and the algorithm is correct on every elementary and non-elementary case I traced (forward/reverse 3-cycles, rotations of the same cycle, repeated starting elements, all-equal, single, empty). Test fixture updates match the K3 / K4 / arms-race counts implied by the new identity rule.

Findings

[P3] Stale doc snippet in hash_u32_slice rustdoc — src/simlin-engine/src/ltm.rs:538

The benchmark-context paragraph still claims that the non-hashing portion of the enumerator is "Johnson's DFS, Vec/HashSet bookkeeping, and sort_unstable on the scratch buffer." After this PR the scratch buffer is no longer sorted; it is filled by canonical_rotation. CLAUDE.md asks for nearby comments to be updated in the same commit when behavior changes. Worth a one-line tweak ("…and canonical_rotation on the scratch buffer") so the doc keeps tracking the code.

Non-blocking observations (not findings)

  • state.hash_scratch.extend(canonical_rotation(&state.path)) allocates a fresh Vec<u32> per emitted raw cycle in the hot Johnson path. Bounded by MAX_LTM_SCC_NODES = 50, but on the WRLD3 benchmark (~1.86M raw emissions) that is ~1.86M throwaway allocations where the prior code reused hash_scratch. A future cleanup could compute just the canonical start index and push directly into hash_scratch, preserving the buffer-reuse property. Not a correctness issue.
  • The GIT_* env stripping in src/simlin-serve/src/git.rs and the test helpers also removes GIT_AUTHOR_NAME / GIT_COMMITTER_*; the test commits will fall back to global user.name / user.email. Fine for CI and any developer machine with a global git identity, but worth being aware of if the test ever runs on a host without one.

Overall correctness

Correct. The behavior change is intentional and well-tested; identified items are doc/perf nits that do not block the change.

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

Adversarial review: canonical edge-sequence cycle dedup (#494)

Verification: ran cargo test -p simlin-engine --lib, cargo test -p simlin-engine --features file_io --test simulate_ltm, cargo test --workspace --features file_io, and cargo clippy --all-targets -- -D warnings. All test suites pass; clippy is clean.

Critical

cargo fmt --check fails in 4 places -- pre-commit hook will block this PR

src/simlin-engine/src/ltm.rs:948
state
    .hash_scratch
    .extend(canonical_rotation(&state.path));
-> single line.

src/simlin-engine/src/ltm.rs:5439
let mut seconds: Vec<&str> = three_loops
    .iter()
    .map(|l| l.links[0].to.as_str())
    .collect();
-> single line.

src/simlin-engine/src/ltm_finding.rs:715
let path_strings: Vec<String> =
    path.iter().map(|id| id.as_str().to_string()).collect();
-> single line.

src/simlin-engine/src/ltm_finding.rs:1169
let forward: Vec<Ident<Canonical>> = vec![Ident::new("a"), Ident::new("b"), Ident::new("c")];
let reverse: Vec<Ident<Canonical>> = vec![Ident::new("a"), Ident::new("c"), Ident::new("b")];
-> wrap to two lines each.

The PR body's test-plan note ("Workspace tests via pre-commit hook (run on review)") is unchecked, which is presumably how this slipped through. Run cargo fmt -p simlin-engine and amend.

Important

wrld3_element_level_enumeration_is_uncapped -- >=1_863_803 is too permissive

The original assertion ==1_863_803 was a tight regression lock pinning the post-dedup count under the previous (sorted-node-set) rule. Switching to >= means a future regression that drops the count to e.g. 1,200,000 would silently pass. Since the test is #[ignore]d and runs only on demand, the only protection it offered was the exact equality.

The design doc (lines 172-178) explicitly committed to "adjust its expected value when the change lands, with the new count documented in the test comment for traceability." The PR retreated from that plan. Required action: run cargo test --release -p simlin-engine --test wrld3_ltm_panic -- --ignored wrld3_element_level_enumeration_is_uncapped once, capture the new count, and pin it back to ==. ~30s in release; one-time cost.

If you genuinely cannot remeasure now, file a tracked issue ("re-pin wrld3 element-level enumeration count") so the loose bound doesn't survive indefinitely. A permanent >= on a regression-locking test is a tech-debt landmine.

Drive-by GIT_* env scrub is missing the tests/watcher_git.rs extension

Branch ltm/480-array-reducer-polarity extends the same fix to src/simlin-serve/tests/watcher_git.rs::must_git. The brief noted "this branch has the original (pre-watcher_git extension) version" -- confirmed: branch #494's commit 34c4befa only patches src/git.rs, src/git.rs::tests::must_git, and tests/git_integration.rs. watcher_git.rs::must_git (lines 41 and 116-171 use the helper) is untouched.

If this is a genuine production GitProbe bug, every git-spawning helper is equally affected. Either:

  1. Extend this PR's commit to cover watcher_git.rs::must_git, OR
  2. Land a follow-up commit before merging that aligns with the 480 version.

Don't merge with an inconsistent fix across siblings.

Loop-id stability is more subtle than the PR claims (still likely OK in practice)

The PR/design doc state: "Loop ids assigned by assign_loop_ids (sorted by underlying variable set) are stable: existing loops keep their ids; previously-collapsed loops simply gain new ids."

assign_loop_ids (ltm.rs:1967-1977) sorts by the dedup'd-and-joined variable set, which is identical for forward and reverse cycles over the same node set. Stability between forward and reverse depends entirely on sort_by_key's stable-sort fallback preserving the enumeration order fed to it. That ordering, in turn, depends on Johnson's DFS visit sequence, which is unchanged by this PR -- so the cycle that master kept as "the survivor" is still the first one out of Johnson's, gets the lower ID, and is preserved. The newly-added direction gets the next available counter.

This is fine in practice but the doc oversells it. Suggested clarification: "Existing IDs remain stable as long as Johnson's DFS visit order is unchanged; this PR does not modify Johnson's traversal logic, so within-process ID assignments are identical to master for previously-existing loops. The newly-uncollapsed direction gets the next sequential ID per polarity bucket."

This matters if any downstream consumer (model snapshots, persisted UI state) holds onto loop IDs across versions: since the new loop IDs cluster (r3 appears alongside r2 for the same node set), any UI that treats IDs as opaque keys is fine; any UI that infers structure from the ID sequence could be surprised.

Minor

canonicalize_circuits test helper is now redundant with the inline dedup

src/ltm.rs:5141-5148 -- canonicalize_circuits first canonical-rotates then sorts/dedups. Johnson's emissions are already canonical-rotation-deduped during enumeration, so the only useful work this helper does on the Johnson side is sorting. It's still needed on the Tiernan oracle side. Keep as-is, but a one-line comment clarifying "the canonical_rotation step is a no-op for Johnson's output but reduces Tiernan's redundant rotations" would help readers.

johnson_complete_k3_all_directed_cycles still uses the sorted-node-set assertion as a sanity check

src/ltm.rs:5301-5311 keeps the original vec!["a", "b", "c"] repeated entry as the "expected sorted node sets" form, with a comment explaining the duplicate is real. This is a deliberate cross-check, fine. But the test name still reads "all_directed_cycles" -- the assertion only checks counts and node sets, not directionality. The actual directionality check is in johnson_multidigraph_keeps_distinct_directed_cycles. Consider renaming this test to johnson_complete_k3_circuit_count_and_node_sets to set expectations correctly, or merge the two tests.

arms_race_3party cross-validation uses node-set equality

tests/simulate_ltm.rs:435-444 -- the assertion "discovered loop should exist in exhaustive results" still uses sorted node-set comparison, so it cannot distinguish forward from reverse three-way loops. The exact-count found.len() == 8 assertion saves correctness, but the cross-check is weaker than it appears. Pre-existing weakness, not introduced by this PR; flagging for awareness.

Minor: O(n^2) where O(n) is available

canonical_rotation is the textbook least-rotation problem; Booth's 1980 algorithm gives O(n). For n ≤ 50 (the SCC gate), the current implementation is fine -- 2500 comparisons per emitted cycle. The justification comment is correct. A future tightening would only help WRLD3-scale enumeration where the helper runs millions of times, and even then the hot-loop cost is hash, not rotation. Not a blocker.

Praise

Algorithm is correct

I traced the algorithm by hand on [1,2,3], [2,3,1], [3,1,2], the reverse [1,3,2], and the documented edge case [1,5,1,3]. The lex-smallest cyclic rotation is computed correctly in all cases. The (node, next_node) tiebreaker described in the design doc is implemented as full-rotation-sequence lex compare, which is the right realization (the doc's "(node_index, next_node_index) pair-sequence" reads as if it were a position-by-position score; in practice the two produce identical outputs for any valid input). Forward and reverse three-cycles canonicalize to different keys; rotations of the same directed cycle canonicalize to the same key; empty input returns empty; one- and two-element cycles are trivially correct (no other rotations to consider).

Generic over T: Ord + Clone

Single helper used at three call sites (numeric Vec<u32> in IndexedGraph and string Vec<String> in two ltm_finding sites). No string-specific assumptions. Good.

K3=5 / K4=20 math is right

Verified by hand:

  • K3: C(3,2)=3 two-cycles + 2 directed three-cycles = 5.
  • K4: C(4,2)=6 two-cycles + C(4,3)·2 = 8 three-cycles + (4-1)!/2·2 = 6 directed Hamilton 4-cycles = 20.

Strong test coverage of the helper

canonical_rotation_picks_lex_smallest_start, _distinguishes_opposite_directions, _handles_repeated_starting_element, _empty_input_returns_empty -- comprehensive. The repeated-starting-element test is particularly nice because elementary cycles never trigger that path; it's defensive coverage.

Direct regression tests at all three application sites

deduplicate_keeps_both_directed_three_cycles_in_multidigraph (Johnson's), add_loop_if_unique_keeps_distinct_directed_three_cycles (discovery), and discovery_arms_race_3party (cross-timestep). Each fails-loud on a regression in the corresponding site.

Determinism preserved

dedup_deterministic_across_calls continues to pin within-process byte-identical output on the multidigraph. Rapidhash seed unchanged; canonical_rotation is fully deterministic (no float ops, no hashmap iteration). Salsa cache stability holds.

Comments updated alongside behavior

has_no_duplicate_node_sets -> has_no_duplicate_canonical_rotations, loops_have_unique_node_sets -> loops_have_unique_canonical_rotations, plus updated rustdoc explaining why the rotation matters and what it doesn't catch. The dedup-in-place comment block in johnson_circuit correctly explains both the multidigraph case and that the budget charges raw emissions before dedup as defense-in-depth.

Design doc is excellent

Identity rule, application points, stability, fixture impact, polarity composition with a worked example -- all answered. The polarity composition example is hypothetical (the actual arms-race fixture has symmetric polarities), which is appropriately flagged. K4 math is shown.

Multi-commit scope discipline

Three logical commits (design doc, algorithm + tests, fixture update) plus the unrelated GIT_* drive-by. No drift into unrelated tests; no comment cleanup beyond the dedup change.

Overall verdict

Block on the formatting issue (Critical). After fmt, fix the wrld3 >= (Important) and align watcher_git.rs (Important). Then ship.

The core change -- replacing sorted-node-set with canonical-rotation dedup at three call sites -- is correct, well-tested, and matches the elementary-circuit identity used in the LTM literature. This is the right fix for #308.

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

Review feedback addressed

Critical (fmt): fixed in 58a47fb. cargo fmt --check now clean.

Important (wrld3 assertion): re-measured and pinned in ad483c1.
New count: 1,863,803 (identical to the 2026-04-18 sorted-node-set
measurement, because WRLD3-03's element-level graph happens to
contain no pairs of opposite-direction cycles over the same node
set). Comment notes the post-canonical-dedup source.

Important (watcher_git extension): aligned with PR #491 in baeeef4.
This branch's version of the GIT_* fix now matches the canonical
version carried on ltm/480-array-reducer-polarity (commit 16c59b0
on that branch). Whichever PR lands first carries the canonical
version and the other can drop the duplicate during rebase.

End-to-end pre-commit was green on each of the three new commits:
fmt, cbindgen, clippy, cargo test --workspace, TypeScript checks,
and pysimlin tests all pass.

PR remains in draft.

@claude

claude Bot commented May 7, 2026

Copy link
Copy Markdown

Review summary

I reviewed the canonical-rotation dedup change end-to-end (helper, three application sites, fixture updates, debug-only invariant checks, plus the drive-by GIT_* env stripping in simlin-serve). I did not find any blocking bugs.

A few observations worth a quick sanity check from the author, none rising to a finding:

  • PR-description vs. diff drift on the WRLD3 assertion. The PR description says the assertion in wrld3_element_level_enumeration_is_uncapped was loosened from ==1_863_803 to >=1_863_803, but the diff keeps assert_eq! at 1_863_803 (with new commentary explicitly arguing for keeping the strict equality so silent count drops can't sneak in). The strict form is the right call IMO — just the PR description is stale.

  • Loop-id ordering on multidigraph SCCs. With siblings now retained, assign_loop_ids (src/simlin-engine/src/ltm.rs:1965) sorts by joined sorted-unique node names. Two loops over the same node set produce identical sort keys, so the stable sort preserves insertion order, which traces back to HashMap iteration in IndexedGraph::from_edges. Within a process this is stable (matches the comment); across processes the relative order of two siblings can swap, so e.g. r3 vs r4 for the forward/reverse 3-cycle on the arms-race fixture is process-dependent. The PR's stability discussion only addresses rotations of a single cycle, not sibling ordering. If any consumer ever relies on cross-process loop-id stability for multidigraph models, an explicit secondary tiebreaker (e.g. canonical rotation of the link sequence) would close this. None of the existing tests or persisted state I could find depend on it.

  • canonical_rotation correctness/perf. The naive O(n²) lex-smallest-rotation algorithm is correct (verified by trace on [1,5,1,3] and on a periodic input). Bounded by MAX_LTM_SCC_NODES = 50 per call so 2500 comparisons worst-case. The per-emission Vec allocation in johnson_circuit (canonical_rotation(&state.path) then extend) costs an extra allocation per cycle; for the 1.86M-cycle WRLD3 enumeration this is noticeable but acceptable given the test is #[ignore]d. Could be trimmed by exposing a "rotate into existing buffer" variant if it ever shows up in profiles.

  • K3/K4 expected counts. Re-derived from scratch: K3 → 3 + 2 = 5; K4 → 6 + 8 + 6 = 20. Matches the test assertions and the budget-19/20 boundary checks.

  • GIT_ stripping breadth.* Stripping the entire GIT_* namespace is a bit broader than strictly required (GIT_DIR/GIT_WORK_TREE/GIT_INDEX_FILE/GIT_OBJECT_DIRECTORY/GIT_COMMON_DIR are the ones that affect repo targeting); this also clears GIT_TERMINAL_PROMPT, GIT_SSH_COMMAND, GIT_AUTHOR_*, etc. Fine for the test paths since tests configure user.* via git config; for simlin-serve::run_git this is read-only-style operations so author/committer aren't relevant. Only flagging in case a future deployment relies on GIT_TERMINAL_PROMPT=0 to avoid hangs.

Overall verdict

Correct. No blocking issues; the canonical-rotation identity is the right fix for #308 and the test coverage (helper unit tests + per-site regression tests + updated K3/K4/arms-race fixtures + invariant checks renamed accordingly) is appropriate.

@codecov

codecov Bot commented May 7, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 90.44118% with 39 lines in your changes missing coverage. Please review.
✅ Project coverage is 82.43%. Comparing base (957b20f) to head (0a1f906).
⚠️ Report is 4 commits behind head on main.

Files with missing lines Patch % Lines
src/simlin-engine/tests/simulate_ltm.rs 84.09% 14 Missing ⚠️
src/simlin-engine/src/db_analysis.rs 94.01% 10 Missing ⚠️
src/simlin-engine/src/db_ltm.rs 79.59% 10 Missing ⚠️
src/simlin-engine/src/analysis.rs 50.00% 2 Missing ⚠️
src/simlin-engine/src/ltm/mod.rs 91.66% 2 Missing ⚠️
src/simlin-engine/tests/wrld3_ltm_panic.rs 0.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #494      +/-   ##
==========================================
+ Coverage   82.39%   82.43%   +0.04%     
==========================================
  Files         243      243              
  Lines       61533    61887     +354     
==========================================
+ Hits        50701    51019     +318     
- Misses      10832    10868      +36     

☔ 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 14:45
@bpowers

bpowers commented May 7, 2026

Copy link
Copy Markdown
Owner Author

@codex review

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

Latest review feedback addressed

P3 (stale hash_u32_slice rustdoc): fixed in f01755c. The non-hash overhead now references canonical_rotation (Booth's O(n)) instead of the long-removed sort_unstable step.

Per-emission Vec allocation: addressed in db5da91. The Johnson hot path now calls lex_smallest_rotation_start with a long-lived rotation_scratch on JohnsonState and writes the canonical rotation halves directly into the existing reusable hash_scratch via extend_from_slice. Both per-emission allocations the bot review and owner review flagged (the throwaway Vec<u32> path copy and Booth's failure-function Vec<i32>) are gone.

Algorithmic improvement: addressed in 359ce6a. canonical_rotation now uses Booth's algorithm (1980) for an O(n) lex-smallest-rotation lookup instead of the prior O(n^2) cyclic comparison loop. The new lex_smallest_rotation_start helper exposes a scratch parameter so the hot path can amortize Booth's failure-function buffer; canonical_rotation itself is a thin wrapper that allocates a temporary scratch. Booth output is verified against the previous O(n^2) reference on every existing fixture (empty, singleton, periodic, all-equal, repeated-start) plus a deterministic 256-input sweep over short random inputs with small alphabets.

PR is now marked ready for review.

@claude

claude Bot commented May 7, 2026

Copy link
Copy Markdown

Review summary

Reviewed the canonical edge-sequence dedup change. The Booth's-algorithm helper, the three application sites, and the fixture updates are all internally consistent and well-tested. The drive-by GIT_* env stripping fix is clean.

Notes (non-blocking)

  • The Booth-vs-naive cross-check tests at src/simlin-engine/src/ltm.rs:5630-5670 and :5680-5710 compare rotations via rot(start) = (0..len).map(|i| s[(start + i) % len]), which masks any pathological case where Booth's might return start >= n. canonical_rotation (and the johnson_circuit slicing on lines 1070-1071) use non-modular indexing and would panic if start >= n. Booth's literature guarantees start < n and the WRLD3 ignore-test has been re-run without panicking (~1.86M invocations), so this is empirically safe — but the tests don't directly assert it. Adding assert!(booth < len) in the cross-check would make the safety guarantee explicit. Not a bug, just a defensive nit.
  • PR description claims the WRLD3 assertion was loosened from ==1_863_803 to >=1_863_803, but tests/wrld3_ltm_panic.rs:131 still uses assert_eq!. The code is fine (and the description's later text confirms the count was re-validated); the bullet at the top of the description is just out-of-sync with the diff.

Overall correctness

Correct. The implementation of Booth's algorithm and its integration into the three dedup sites are sound, tests are added at the right granularity, and the loop-id stability claim holds because assign_loop_ids uses stable sort_by_key. No blocking issues identified.

@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: f01755c4f7

ℹ️ 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
Comment on lines 1012 to 1013
if state.seen.insert(fp) {
state.circuits.push(state.path.clone());

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 Add deterministic tie-breaker for same-node-set loop IDs

This change intentionally keeps both directed 3-cycles for the same node set (state.circuits.push(state.path.clone()) now allows siblings like a->b->c->a and a->c->b->a), but loop IDs are still assigned by assign_loop_ids using only the deduped variable set as the sort key. When two loops share that key, their final rN/bN ordering falls back to enumeration order, which is influenced by HashMap iteration in graph construction and can differ across process runs. The result is non-stable loop IDs for the newly un-collapsed sibling cycles, which can break reproducibility for any downstream consumer that keys on loop ID.

Useful? React with 👍 / 👎.

@bpowers
bpowers force-pushed the ltm/308-canonical-cycle-dedup branch from f01755c to 879811d Compare May 7, 2026 15:05

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

Empirical correction: O(n) algorithms slower than the simple loop here

I posted a previous reply claiming Booth's was a win; that turned out to be wrong on measurement and I've reset the branch to a single clean commit (879811d). Apologies for the noise.

What changed

The new commit lands the per-emission Vec allocation fix the bot review and owner review both flagged: canonical_rotation is split into a start-index helper (lex_smallest_rotation_start) plus a thin allocating wrapper, and johnson_circuit calls the helper directly with extend_from_slice into the reusable hash_scratch, eliminating the throwaway Vec<u32> per raw cycle.

The stale hash_u32_slice rustdoc snippet (P3) is also fixed in the same commit; it now references canonical_rotation rather than the long-removed sort_unstable step.

What didn't change (and why)

I implemented Booth's (1980) and Duval/Lyndon factorization to address the algorithmic improvement question. Both are provably O(n) and beat the simple cyclic-comparison loop's worst-case O(n^2). On this specific workload they are slower, not faster, end-to-end.

WRLD3 element-level enumeration wall time on three runs each, release with the workspace's default opt-level = "z":

Variant Wall time
Baseline (before any of this PR's edits) 1.70s
Booth's + alloc fix 1.94s (+14%)
Duval + alloc fix 1.86s (+9%)
Simple O(n^2) + alloc fix (this PR) 1.57s (-8%)

At opt-level = 3 the relative ranking is identical: 1.25s baseline -> 1.53s Booth -> 1.40s Duval -> 1.18s simple-with-alloc-fix.

The reason is structural to LTM cycle data: cycles use distinct u32 node indices (no repeated elements), so the simple loop's inner comparison almost always exits at the first differing element after one or two reads. The algorithm runs in roughly O(n) on real inputs while paying near-zero per-element overhead. Booth/Duval pay constant-factor overhead per position (failure-function bookkeeping or Lyndon-word extension state) that dominates for n capped at MAX_LTM_SCC_NODES = 50.

The rustdoc on lex_smallest_rotation_start records this empirical finding with a pointer back to the PR so a future maintainer doesn't relitigate it without measurement.

Verification

  • cargo test -p simlin-engine --features file_io -- all integration tests green; no test value changes.
  • cargo clippy --workspace --all-targets -- -D warnings -- clean.
  • cargo fmt --check -- clean.
  • WRLD3 ignored benchmark: count still 1,863,803, wall time 1.70s -> 1.57s in release at default opt-level.

PR remains marked ready for review.

@claude

claude Bot commented May 7, 2026

Copy link
Copy Markdown

Review

[P3] Sorted-UID LoopMetadata keys collide when two directed cycles share a node set

src/simlin-engine/src/analysis.rs lines 287–339, with LoopMetadata.uids defined in src/simlin-engine/src/datamodel.rs:756 and written by apply_set_loop_name in src/simlin-engine/src/patch.rs:367-372.

The PR notes that "Downstream callers that assume 'one loop per node set' must be updated separately ... a search of the repo did not surface any," but resolve_loop_name is one such caller: it builds loop_uids from the loop's variables, sorts, and looks the sorted set up in uid_to_loop_name, which itself was built from LoopMetadata.uids (also sorted). When the canonical-rotation dedup retains both directions of a cycle over the same node set, both FoundLoops resolve to the same persisted name, so the user-visible loop summaries can no longer distinguish forward vs. reverse via name. apply_set_loop_name similarly merges/overwrites the metadata for the second direction. This is a follow-up concern — only triggered when (a) two opposite-direction cycles exist (rare) and (b) the user has named the loop — not a release blocker, but worth tracking so the metadata schema can grow a direction key.


Overall correctness

Correct. The canonical-rotation key correctly distinguishes opposite-direction cycles while folding rotational duplicates of the same directed cycle (verified mentally on K3, K4, and the [1,5,1,3] worked example), the inline rewrite into hash_scratch preserves the buffer-reuse invariant, the O(n²) algorithm is fine inside MAX_LTM_SCC_NODES = 50, fixture counts (K3: 5, K4: 20, arms-race: 8) match the directed-cycle math, and the GIT_* env stripping in simlin-serve is a sound defensive fix. The loop_metadata interaction noted above does not affect engine correctness, only the human-readable name resolution.

bpowers and others added 13 commits May 8, 2026 07:44
Plans the tiered enumeration that runs Johnson on the variable graph
first, classifies each cycle by RefShape composition, and emits
pure-A2A and pure-scalar cycles as Loops directly without entering
the element-level enumerator. Only mixed and cross-element cycles
flow through element-level Johnson, and only on the subgraph induced
by their nodes -- not the full element graph.

Cost becomes additive in N for pure-A2A loops where today it is
multiplicative; the auto-flip gate's domain narrows to the
cross-element / mixed slice. The full assessment, fixture
predictions, and stage breakdown are in the design plan.
Adds `model_edge_shapes`, a salsa-tracked function that classifies every
variable-level edge `(from, to)` by the set of `RefShape` values seen at
any AST reference site of `from` in `to`'s equation. The result is the
input the upcoming tiered loop enumerator needs to decide whether each
variable-level cycle is pure-A2A (every edge has only Bare references),
pure-scalar, or cross-element / mixed (any Wildcard, DynamicIndex, or
FixedIndex shape).

Structural flow->stock edges have no AST reference, so they map to
`{Bare}` directly -- semantically a same-element diagonal, matching
the classification `model_element_causal_edges` already uses for the
same case. Module input edges and unable-to-reconstruct fallbacks
likewise map to `{Bare}` (modules are scalar nodes; the fallback is
defensive).

`RefShape` gains a derived `Ord` so the result type can use
`BTreeSet<RefShape>` for deterministic iteration. The walker reuses
the existing `collect_reference_shapes` helper; the per-target AST
parse results are already cached by salsa, so the second walk that
`model_element_causal_edges` performs is cheap.

This is Stage 1 of the variable-level loop enumeration plan
(docs/design-plans/2026-05-06-ltm-482-variable-level-loop-enumeration.md);
behavior on existing fixtures is unchanged because the new function
is not yet consumed by any downstream code path.
Adds `model_loop_circuits_tiered`, the salsa-tracked tiered loop
enumerator that runs Johnson on the variable graph first and only
descends to element-level Johnson for cycles that actually need it.

The classifier (`classify_cycle`) labels each variable-level cycle
as PureScalar, PureSameElementA2A, or CrossElementOrMixed by reading
the per-edge RefShape map from `model_edge_shapes`. Pure-scalar and
pure-A2A cycles materialize directly into a single Loop without
entering element-level enumeration; only mixed/cross-element cycles
flow through Johnson on the slow-path subgraph induced by their
nodes.

The slow-path subgraph is a strict subset of the full element graph
on any model where pure cycles exist. For purely scalar models
(e.g. WRLD3) and purely A2A models (e.g. arrayed_population_ltm),
the slow-path subgraph is empty and zero element-level circuits are
enumerated. The cost asymmetry that made pure-A2A cycles inflate
multiplicatively in N is gone.

The new function is salsa-tracked separately from
`model_element_loop_circuits`; the latter is unchanged because no
caller has been wired to the tiered representation yet. Stage 4 will
update `build_element_level_loops` in db_ltm to consume the tiered
result and emit Loops directly for fast-path cycles.
Wires `model_ltm_variables` to consume `model_loop_circuits_tiered`
via a new `build_loops_from_tiered` helper. Pure-A2A and pure-scalar
cycles are now emitted directly as Loops without paying for
element-level Johnson; only cross-element / mixed cycles flow through
the legacy element-grouping logic on the slow-path subgraph.

The legacy `build_element_level_loops` helper is preserved and is
still called by `build_loops_from_tiered` to handle slow-path
element circuits. The merged Loop list (fast-path + slow-path) gets
one final `assign_loop_ids` pass so loop ID numbering is consistent
across both paths.

Existing fixtures continue to pass: `assign_loop_ids` sorts loops
by content-derived key (sorted distinct variable names) before
numbering, so r1/b1/u1 IDs are stable regardless of which path
produced each Loop. The 48 `tests/simulate_ltm.rs` integration
tests pass without modification.

Stage 4 of `docs/design-plans/2026-05-06-ltm-482-variable-level-loop-enumeration.md`.
… graph

Restructures the LTM auto-flip gate from a single check on the full
element-level graph SCC into two phased checks:

  1. Variable-level SCC (cheap Tarjan on the variable graph). If
     this exceeds MAX_LTM_SCC_NODES, auto-flip immediately -- no
     variable-level Johnson runs.
  2. Slow-path subgraph SCC (computed inside
     model_loop_circuits_tiered). When the cross-element / mixed
     subgraph's SCC exceeds the threshold, the tiered enumerator
     skips Johnson on that subgraph and emits an empty slow_path;
     the caller flips to discovery mode and emits a diagnostic.

After the per-reference element graph refactor (#448), pure-A2A
models already have N small element-level SCCs (one per element),
so the legacy gate didn't actually trip on them. The structural
benefit of the new gate is that gate cost is now proportional to
the variable graph and slow-path subgraph rather than the full
N-times-inflated element graph, and TieredCircuitsResult exposes
slow_path_largest_scc so the gate logic is local and explicit.

The headline performance win for #482 is the elimination of
redundant per-element circuit enumeration on pure-A2A loops:
`tests::pure_a2a_eliminates_per_element_circuit_redundancy`
asserts that the legacy element-level Johnson enumerates 30
circuits on a 30-element pure-A2A model while the tiered
enumerator emits one fast-path cycle and zero slow-path Johnson.

FastPathCircuit.dimensions stores canonical dimension names as
Vec<String> rather than Vec<Dimension> so the salsa-tracked result
type's Debug derive doesn't depend on the engine's debug-derive
feature (off by default in libsimlin's simlin-engine dependency).

Stages 5 and 6 of the design plan.
Same fix as commit e534590 (`serve: clear inherited GIT_* env in
git probe and tests`) extended to the watcher_git integration test
suite. The `must_git` helper there was not previously updated and
inherits the parent's GIT_DIR / GIT_WORK_TREE / GIT_INDEX_FILE when
running under the project pre-commit hook (`cargo test --workspace`),
which makes the inner git operate on the outer repository instead
of the freshly-`git init`'d temp dir.
Stage 7 of the variable-level loop enumeration work: documentation
updates and measurement capture.

- design-plan postscript records var/element SCC, var-level circuit
  count, legacy element-level circuit count, fast-path count,
  slow-path count, and slow-path SCC for the cross_element_ltm and
  arrayed_population_ltm fixtures.
- engine CLAUDE.md describes `model_edge_shapes`,
  `model_loop_circuits_tiered`, `classify_cycle`,
  `TieredCircuitsResult`, and the dual-gate auto-flip strategy.
- LTM design doc rewrites the loop-score section to describe the
  PureScalar / PureSameElementA2A / CrossElementOrMixed
  classification and the slow-path subgraph that drives element-level
  Johnson on the remaining mixed cycles. The two-tier auto-flip
  strategy (variable-level early gate, slow-path subgraph late gate)
  is documented in the divergence-from-papers section.
- tech-debt #25 marked RESOLVED with pointers to the design plan and
  the resolving stages of this PR.
- new `measurement_postscript_*` integration tests in
  simulate_ltm.rs pin the post-refactor numbers so future regressions
  surface as test failures.
Stage 7 follow-up: the exhaustive-mode flow in
docs/design/ltm--loops-that-matter.md still described
`model_loop_circuits` directly enumerating elementary circuits.
After the tiered refactor, `model_loop_circuits_tiered` is the
primary entry point used by `model_ltm_variables`; the design doc
now describes the fast / slow path partition and how each is
materialized into Loops.
The slow-path subgraph in model_loop_circuits_tiered is induced on every
variable that appears in any CrossElementOrMixed cycle. That is
intentionally broad -- a variable participating in even one cross-element
cycle must keep its element nodes in the subgraph -- but when a pure-A2A
cycle shares variables with a cross-element cycle (e.g., "a -> grow ->
stock -> b -> a" co-existing with "a -> grow -> stock -> b -> c -> a"
where c[r] = b[NYC] + ...), the pure-A2A cycle's nodes get pulled into
the subgraph too. Johnson then re-finds the per-element reflections of
that pure-A2A cycle, which build_element_level_loops re-collapses into
an A2A Loop, duplicating the Loop the fast path already emitted.

Filter slow-path circuits whose stripped variable-level node sequence
matches a fast-path circuit's node sequence (rotation-invariant via
canonical_cycle_rotation). This drops only the per-element reflections;
genuine cross-element cycles (which traverse extra variables and
therefore have a different stripped sequence) survive the filter.

Add a permanent regression fixture in tests/simulate_ltm.rs that
constructs the reviewer's reproducer (a/grow/stock/b/c with FixedIndex
through b[NYC]) and asserts exactly 2 distinct loops are emitted. The
unfixed branch produces 3 (r1, r2, u1).
…string

The post-#482 LTM pipeline routes through model_loop_circuits_tiered;
model_element_loop_circuits is retained only for diagnostic /
measurement-postscript tests and external consumers that want the
unfiltered element-level circuit list. Mark it #[deprecated] so new LTM
callers get an automatic warning if they wire it up by accident, while
keeping it callable for the existing measurement helpers in
tests/simulate_ltm.rs, the internal unit tests in db_element_graph_tests
and db_ltm_unified_tests, and the ltm_full_bench example. Each remaining
caller carries an #[allow(deprecated)] with a comment explaining why it
intentionally targets the legacy surface.

The salsa::tracked macro expansion references the function by name in
its generated code, so the inner #[allow(deprecated)] is required on
the function definition itself; an outer-only deprecation lint would
fire inside the macro expansion and there is no #[allow] we can apply
inside the salsa-generated code.

Update MAX_LTM_SCC_NODES's docstring to describe the post-#482
two-granularity gate: variable-level SCC (cheap pre-Johnson) and
slow-path subgraph SCC (computed inside the tiered enumerator). Pre-#482
the docstring described a single element-graph SCC gate, which no
longer exists.
Tighten three loose ends from the PR #496 review of the variable-level
loop enumeration refactor:

- build_loops_from_tiered's canonical-name-to-datamodel-name mapping
  silently fell back to the canonical (lower-cased) string when a fast-
  path A2A cycle's dimension name didn't appear in dm_dims. Replace with
  unreachable! that lists the known dimensions, since the only way the
  fall-back fires is an internal dim-cache or synthesizer mismatch -- a
  bug we want surfaced at the cause site rather than as a parse error
  on the downstream loop-score equation.

- Fix measurement_postscript_cross_element_ltm's docstring: the post-
  #482 measurement is var_scc=5 / elem_scc=10, not 4/8. The births flow
  closes the population<->births A2A pair so it sits in the same SCC as
  the migration variables.

- Mark tech-debt #25 as 'RESOLVED (pending #496 merge)' so the entry
  re-flips to RESOLVED automatically when the PR lands and doesn't read
  as resolved on main while the PR is still in review.
The previous serve: clear inherited GIT_* env... commit stripped
every env var beginning with GIT_, including author/committer
identity (GIT_AUTHOR_*/GIT_COMMITTER_*), transport (GIT_SSH_COMMAND),
credential helpers (GIT_ASKPASS), and interaction flags
(GIT_TERMINAL_PROMPT). The original motivation only requires
neutralizing the path-targeting vars (GIT_DIR, GIT_WORK_TREE,
GIT_INDEX_FILE, GIT_OBJECT_DIRECTORY, GIT_COMMON_DIR) that override
the per-call current_dir(cwd). Restrict the strip to that set and
update the explanatory comment so future code that uses run_git to
commit, push, or pull still inherits author/transport/credential
config from the calling environment.

Promote the constant + helper (strip_git_path_env / GIT_PATH_TARGETING_VARS)
to a single source of truth in simlin_serve::git and have both integration
tests (tests/git_integration.rs, tests/watcher_git.rs) plus the in-crate
tests::must_git helper call it, so the rule cannot drift between sites.
build_loops_from_tiered previously hit unreachable! when a
canonical dimension name didn't appear in the datamodel's
dimension list, panicking the whole LTM pipeline. The legacy
build_element_level_loops path falls back to the canonical name
as a recoverable warning -- mirror that behavior so incremental
or partially-invalid model states surface as analysis warnings
rather than hard crashes.
test and others added 11 commits May 8, 2026 08:12
Add MostlyReinforcing and MostlyBalancing (Rux/Bux) loop polarity
variants and a polarity_confidence f64 (range 0..=1) on
DetectedLoop. from_runtime_scores no longer collapses any sign
change to Undetermined; loops with one dominant polarity above the
configured threshold are classified mostly-R/B with their
confidence ratio.

Threshold POLARITY_CONFIDENCE_THRESHOLD = 0.99 follows
Schoenberg & Eberlein (2020) "Seamlessly Integrating LTM into the
Modeling Process" (section 13.7 of docs/reference/ltm--loops-that-matter.md
and section 7.6 of the thesis summary), which uses the same
|r - |b|| / (r + |b|) ratio to distinguish predominantly-R/B
loops from genuinely mixed ones in simplified CLDs. The papers
describe the cutoff verbally as "above 0.99" while section 13.7's
formula is inclusive; this implementation uses confidence >=
threshold to match the formula and avoid surfacing high-dominance
loops as Undetermined. Filtering on !is_finite() rather than just
is_nan() keeps Inf/-Inf from poisoning the denominator and
producing NaN confidence (which clamp would not repair).

Existing matches on LoopPolarity / DetectedLoopPolarity were made
exhaustive: src/simlin-engine/src/{analysis.rs,db_analysis.rs,
layout/mod.rs,ltm/{graph,types,tests}.rs,ltm_finding.rs},
src/libsimlin/src/analysis.rs (C ABI keeps R/B/U; mostly-R/B
coalesce to their dominant cousins since the FFI struct has no
confidence field today), and the exhaustive test match in
tests/simulate_ltm.rs.
The Python LoopPolarity.from_runtime_scores reimplementation was still
using the pre-#485 semantics (collapse any sign change to UNDETERMINED),
so Rust and Python silently disagreed on Rux/Bux loops once the engine
landed the new variants. Bring the Python port up to the same algorithm:
compute the polarity-confidence ratio |r - |b|| / (r + |b|) and
classify mostly-* when one polarity dominates above the
POLARITY_CONFIDENCE_THRESHOLD = 0.99 cutoff that mirrors the Rust
constant.

The C FFI struct still has no confidence field, so structural loops
delivered through the FFI continue to surface as REINFORCING/BALANCING/
UNDETERMINED (values 0-2). The new MOSTLY_REINFORCING and
MOSTLY_BALANCING variants take values 3 and 4 and only arise from the
Python-only from_runtime_scores path; downstream consumers like
Run._calculate_dominant_periods bucket them with their dominant pure
cousin so existing dominance heuristics keep working.
The MCP instructions and the loop-dominance skill markdown still
claimed the JSON polarity field is exactly one of three values, but
to_loop_summary in simlin-engine emits five strings now (reinforcing,
balancing, undetermined, plus mostly_reinforcing / mostly_balancing).
Enumerate all five in instructions.md and the skill, and explain when
the mostly_* variants are produced (Rux/Bux: dominant polarity with
>=0.99 confidence per Schoenberg & Eberlein 2020) so AI agents reading
either resource don't treat the new strings as garbage.

Note that Model.loops (structural-only) still reports just the legacy
three because the MOSTLY_* variants require simulated runtime scores;
the skill text spells this out so callers know which surface they're
on.
PR #490 implements the Eberlein/Schoenberg polarity-confidence ratio
(`|r - |b|| / (r + |b|)`) and the new MostlyReinforcing/MostlyBalancing
variants on DetectedLoop. The tech-debt entry was last reviewed before
the implementation landed; refresh the description to point at the
in-flight branch and bump the review date so the entry will be marked
RESOLVED with the merge SHA once the PR lands.
The polarity analyzer treated SUM, MEAN, single-arg MAX/MIN, STDDEV, and
RANK applications as Unknown via the catch-all App arm. Each of these
reducers is monotone in every input element (or, for STDDEV/RANK,
explicitly non-monotone in a way the user expects to surface as
Unknown), so propagate inner polarity for the monotone reducers and
return Unknown explicitly for STDDEV / RANK so a future reducer
addition cannot accidentally pick up the wrong default.

Add an Expr2::Subscript arm that mirrors Expr2::Var so the production
case SUM(x[*]) -- which lowers to Sum(Subscript(x, [Wildcard], _, _)),
not Sum(Var(x, ...)) -- actually exercises the new reducer arms.
Without this, the reducer arms only fire on synthetic Sum(Var) shapes
that never appear in real models.

Hoist the self-reference + Unknown short circuit ahead of the per-arg
combiner in the variadic MEAN path so MEAN(ABS(x), x) collapses to
Unknown regardless of arg order, mirroring how BinaryOp::Add handles
the same case. Without the hoist, a leading ABS(x) seeded `combined`
with Unknown and then any later known-polarity arg silently
overwrote it.

Remove the trailing `_ => LinkPolarity::Unknown` catch-all: every
Expr2 variant is now matched explicitly, so a future variant addition
becomes a compile error rather than a silent miscategorization.
Three new unit tests in src/simlin-engine/src/ltm/tests.rs:

- test_analyze_expr_polarity_array_reducers exercises each new reducer
  arm (SUM, MEAN, single-arg MAX/MIN, STDDEV, RANK) on a plain
  Expr2::Var argument so the reducer logic is verified independently
  of the Subscript handling.
- test_analyze_expr_polarity_array_reducers_subscript_wildcard drives
  the production-shape Sum(Subscript(x, [Wildcard], _, _)) and the
  parallel MEAN/MAX/MIN/STDDEV/RANK shapes through the analyzer. This
  is the headline case for issue #480: without an Expr2::Subscript arm
  the new reducer arms produce Unknown for any real SUM(x[*]) call.
- test_variadic_mean_polarity_with_non_monotone_arg pins the variadic
  MEAN(ABS(x), x) ordering bug. The hoisted self-reference + Unknown
  short circuit must collapse the result to Unknown regardless of arg
  order; this test covers ABS first, x first, both-x agree, and x/-x
  disagreement.
test_cross_dim_sum_algebraic now goes beyond the per-element link
score sanity checks and asserts the structural polarity of the
population -> total_pop edge. SUM(population[*]) is monotone-positive
in every population element, so compute_link_polarities must surface
Positive there; the resulting reinforcing loop (population -> growth
-> population, with total_pop as a downstream consumer) must classify
as Reinforcing rather than Undetermined.

This is the headline integration check for issue #480: without the
Expr2::Subscript arm in the polarity analyzer the parsed
Sum(Subscript(...)) shape would fall through to Unknown despite the
new reducer arm, and a model whose link is structurally monotone
would still be classified as Undetermined.
Replace sorted-node-set dedup keys at the three call sites
(IndexedGraph::johnson_circuit, SearchGraph::add_loop_if_unique, and
discover_loops_with_graph) with a canonical edge-sequence rotation
helper (rotate to the lex-smallest start position, compare ordered
node sequence). Two distinct directed cycles over the same node set
are now retained as distinct loops, matching the elementary-circuit
identity used by the LTM literature.

Add canonical_rotation<T: Ord + Clone> and lex_smallest_rotation_start
<T: Ord> to ltm/mod.rs as pub(crate) helpers shared by indexed.rs and
ltm_finding.rs. The Johnson hot path uses lex_smallest_rotation_start
plus extend_from_slice to write the canonical rotation directly into
the reusable hash_scratch buffer, avoiding the per-emission Vec<u32>
that an allocating canonical_rotation call would have produced (saves
~1.86M allocations on WRLD3 element-level enumeration). The simple
O(n^2) inner loop is retained over Booth or Duval/Lyndon: empirical
timing on real LTM inputs (mean cycle length ~47, alphabet of distinct
u32 indices, gated upstream at MAX_LTM_SCC_NODES = 50) showed the
simple loop runs in roughly O(n) because the inner comparison almost
always exits at the first differing element. The rustdoc on
lex_smallest_rotation_start records this empirical justification so a
future maintainer doesn't relitigate it without measurement.

Tests updated under the new identity rule:
- johnson_complete_k3_all_directed_cycles now expects 5 circuits
  (was 4): K3 has 3 two-cycles + 2 three-cycles (forward + reverse).
- johnson_multidigraph_dedups_to_single_node_set becomes
  johnson_multidigraph_keeps_distinct_directed_cycles with the
  inverted assertion.
- johnson_budget_charges_duplicate_raw_cycles is renamed
  johnson_budget_bounds_unique_directed_cycles. K4 now has 20
  distinct directed cycles (was 11 by node-set); raw and unique
  coincide because Johnson's emits each elementary cycle exactly
  once from its lex-smallest start.
- johnson_multi_scc_in_large_node_space_golden gains a duplicate
  three-node entry for the K3 multidigraph SCC (the two distinct
  3-cycles share a node-set under the sorted-name-set view but
  remain separate loops).

Issue #308. Design note:
docs/design-plans/2026-05-06-ltm-308-canonical-cycle-dedup.md.
Pairs with the canonical-edge-sequence dedup change. The arms-race
model has three stocks each with a target that sums the other two,
producing a multidigraph SCC with both directions of the three-way
feedback loop. The old fixture encoded the buggy sorted-node-set
collapse (7 loops); under the corrected identity rule it has 8
loops -- the pairwise, self-adjustment, and forward/reverse three-
way reinforcing loops.

Issue #308.
…edup

Re-measured the #[ignore]'d wrld3 element-level enumeration in
release after issue #308 switched dedup to canonical edge-sequence
rotation. The new count is 1,863,803 -- identical to the pre-canonical
sorted-node-set measurement, because WRLD3-03's element-level graph
happens to contain no pairs of opposite-direction cycles over the
same node set. Replaced the old `==` assertion message with one that
documents the post-canonical-dedup provenance so a future
remeasurement has clear baseline to compare against. The exact-match
form (rather than `>=`) is intentional: a future change that silently
drops circuits or duplicates them is caught instead of slipping
through.

Issue #308.
LTM currently dedups feedback loops by sorted node-set, collapsing
distinct directed cycles like A->B->C->A and A->C->B->A into one Loop.
This note specifies the canonical-edge-sequence rotation (rotate to
lex-smallest start position, compare ordered node sequence) that will
replace the buggy dedup, lists the three call sites that need to
change, walks through the arms-race-3party fixture to show the
identity rule in action, and enumerates the fixture-count updates
expected after the change lands.

Issue #308.
@bpowers
bpowers force-pushed the ltm/308-canonical-cycle-dedup branch from 879811d to 0a1f906 Compare May 8, 2026 15:55
@bpowers
bpowers changed the base branch from main to ltm/480-array-reducer-polarity May 8, 2026 15:55

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

Rebased onto PR #491 (top of stacked chain)

This PR is now stacked on top of #491 (ltm/480-array-reducer-polarity), which itself stacks #490 -> #496 -> main. As each PR below merges, GitHub auto-updates this PR's base.

  • Canonical-rotation helper + start-index variant now in src/simlin-engine/src/ltm/mod.rs (post-#498 module split).
  • IndexedGraph::johnson_circuit allocation fix preserved: writes the canonical rotation directly into the reusable hash_scratch via lex_smallest_rotation_start + extend_from_slice (no per-emission Vec).
  • Empirical decision to keep the simple O(n^2) inner over Booth/Duval is preserved; rustdoc on lex_smallest_rotation_start documents the wall-time benchmark.
  • All three call sites use the helper: IndexedGraph::johnson_circuit (now in ltm/indexed.rs), SearchGraph::add_loop_if_unique (ltm_finding.rs), discover_loops_with_graph cross-timestep dedup (ltm_finding.rs).
  • K3=5, K4=20, multidigraph distinct cycles, arms_race_3party=8 fixture updates preserved in ltm/tests.rs and tests/simulate_ltm.rs.
  • WRLD3 count pinned at the exact 1,863,803 with the empirical comment explaining why post-canonical-dedup matches pre-canonical-dedup on this fixture.
  • Older GIT_* prep commits dropped; the chain #496 narrowed allowlist > #489 vars_os > older vars() is established on the parent branches.
  • Design doc preserved.

mergeable: MERGEABLE on top of base ltm/480-array-reducer-polarity.

@claude

claude Bot commented May 8, 2026

Copy link
Copy Markdown

Review summary

I reviewed the canonical-edge-sequence dedup change (issue #308). The algorithm in lex_smallest_rotation_start is correct on the cases I traced (including the tied-starting-element case that the test pins), the three application sites consistently use canonical_rotation / lex_smallest_rotation_start, and the fixture math holds: K3 multidigraph yields 3 + 2 = 5 cycles, K4 yields 6 + 8 + 6 = 20, and 2-cycles correctly merge under rotation while 3-cycles correctly split by second-position node.

A few non-blocking observations:

  • The PR description states the WRLD3 #[ignore]d test would be loosened from ==1_863_803 to >=1_863_803, but the actual code keeps assert_eq!(1_863_803). The in-code comment claims the value was remeasured on 2026-05-06 and happens to match (no symmetric multidigraph cycles in WRLD3). Since this is #[ignore]d, CI won't catch a divergence -- the comment's claim has to be trusted.
  • The PR description references a "drive-by fix in commit 1" to src/simlin-serve/src/git.rs::run_git for stripping GIT_* env vars, but no such change appears in the diff. Likely the PR description is stale rather than the code being broken.
  • apply_set_loop_name in src/simlin-engine/src/patch.rs still keys LoopMetadata by sorted UID list, so two distinct directed cycles over the same node set will share a single user-facing loop name. This is a pre-existing limitation rather than a regression -- worth noting because the PR description claims a repo search surfaced no callers assuming "one loop per node set", and this one does (though the consequence is "two loops share a name", not data corruption).
  • The function-level docstring for IndexedGraph::from_edges (indexed.rs:192-194) still says "Successor indices are de-duplicated and sorted" while the inline comment explicitly says "We deliberately do NOT sort". This inconsistency is pre-existing and outside the PR's scope.

Inside johnson_circuit the canonical-rotation step is effectively a no-op for elementary cycles (the w >= start invariant already forces path[0] to be the lex-smallest node), so the new lex_smallest_rotation_start call there is purely defensive -- the comment sells it as normalizing alternate orderings, which slightly overstates the case. Not a bug, just slightly misleading wording.

Overall correctness

Correct. I did not find any qualifying bugs. The change is well-tested at the helper, per-site, and end-to-end levels, and the count changes in the affected fixtures match the elementary-circuit identity used in the LTM literature.

Base automatically changed from ltm/480-array-reducer-polarity to main May 8, 2026 16:09
@bpowers
bpowers merged commit 04614fe into main May 8, 2026
14 checks passed
@bpowers
bpowers deleted the ltm/308-canonical-cycle-dedup branch May 8, 2026 16:10
@bpowers bpowers mentioned this pull request May 11, 2026
1 of 29 tasks
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: dedup by node set merges distinct directed loops

1 participant