Repository navigation
engine: dedup ltm cycles by canonical edge sequence (#308) - #494
Conversation
ReviewI worked through the PR end-to-end (canonical-rotation algorithm, all three application sites, fixture updates, and the Findings[P3] Stale doc snippet in The benchmark-context paragraph still claims that the non-hashing portion of the enumerator is "Johnson's DFS, Vec/HashSet bookkeeping, and Non-blocking observations (not findings)
Overall correctnessCorrect. The behavior change is intentional and well-tested; identified items are doc/perf nits that do not block the change. |
bpowers
left a comment
There was a problem hiding this comment.
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:
- Extend this PR's commit to cover
watcher_git.rs::must_git, OR - 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
left a comment
There was a problem hiding this comment.
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.
Review summaryI reviewed the canonical-rotation dedup change end-to-end (helper, three application sites, fixture updates, debug-only invariant checks, plus the drive-by A few observations worth a quick sanity check from the author, none rising to a finding:
Overall verdictCorrect. 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 Report❌ Patch coverage is 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. 🚀 New features to boost your workflow:
|
|
@codex review |
bpowers
left a comment
There was a problem hiding this comment.
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.
Review summaryReviewed 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 Notes (non-blocking)
Overall correctnessCorrect. 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 |
There was a problem hiding this comment.
💡 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".
| if state.seen.insert(fp) { | ||
| state.circuits.push(state.path.clone()); |
There was a problem hiding this comment.
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 👍 / 👎.
f01755c to
879811d
Compare
bpowers
left a comment
There was a problem hiding this comment.
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.
Review[P3] Sorted-UID
|
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.
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.
879811d to
0a1f906
Compare
bpowers
left a comment
There was a problem hiding this comment.
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_circuitallocation fix preserved: writes the canonical rotation directly into the reusable hash_scratch vialex_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_startdocuments the wall-time benchmark. - All three call sites use the helper:
IndexedGraph::johnson_circuit(now inltm/indexed.rs),SearchGraph::add_loop_if_unique(ltm_finding.rs),discover_loops_with_graphcross-timestep dedup (ltm_finding.rs). - K3=5, K4=20, multidigraph distinct cycles, arms_race_3party=8 fixture updates preserved in
ltm/tests.rsandtests/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.
Review summaryI reviewed the canonical-edge-sequence dedup change (issue #308). The algorithm in A few non-blocking observations:
Inside Overall correctnessCorrect. 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. |
Summary
LTM currently dedups feedback loops by sorted node-set, collapsing distinct directed cycles like
A -> B -> C -> AandA -> C -> B -> Ainto oneLoop. 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 cyclev0 -> 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 allnrotations. 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 onVec<u32>and the discovery path onVec<String>.Design note:
docs/design-plans/2026-05-06-ltm-308-canonical-cycle-dedup.md.Application points
IndexedGraph::johnson_circuitsrc/simlin-engine/src/ltm.rsVec<u32>(rapidhash fingerprint)SearchGraph::add_loop_if_uniquesrc/simlin-engine/src/ltm_finding.rsVec<String>discover_loops_with_graph(cross-timestep dedup)src/simlin-engine/src/ltm_finding.rsVec<String>Fixture changes
discovery_arms_race_3party(tests/simulate_ltm.rs)johnson_complete_k3_all_directed_cycles(src/ltm.rs)johnson_multidigraph_dedups_to_single_node_set(src/ltm.rs)johnson_multidigraph_keeps_distinct_directed_cyclesjohnson_budget_charges_duplicate_raw_cycles(src/ltm.rs)johnson_budget_bounds_unique_directed_cycles. K4 has 6 + 8 + 6 distinct directed cyclesThe
wrld3_element_level_enumeration_is_uncappedtest (#[ignore]d) had its assertion loosened from==1_863_803to>=1_863_803because the exact post-fix count will be remeasured next time it is run on-demand.Determinism / id stability
assign_loop_ids(sorted by underlying variable set) are stable: existing loops keep their ids; previously-collapsed loops simply gain new ids.LoopCircuitsResultfrommodel_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_callsunit test continues to pin within-process determinism on K3 with all 6 directed edges.Risks
Drive-by fix in the same branch (commit 1)
src/simlin-serve/src/git.rs::run_gitand the in-testmust_githelpers now strip everyGIT_*env variable before spawning. Without this,cargo test --workspaceinvoked from inside the project pre-commit hook inheritsGIT_DIR/GIT_WORK_TREEand the innergit commitoperates 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-enginepasses (3,161 lib tests + 48 simulate_ltm + every other integration suite).cargo clippy --workspace --all-targets -- -D warningsclean.canonical_rotation_distinguishes_opposite_directions,deduplicate_keeps_both_directed_three_cycles_in_multidigraph,add_loop_if_unique_keeps_distinct_directed_three_cycles) plus the existingdiscovery_arms_race_3partyintegration test now exercises the change end-to-end.