Skip to content

ltm: enumerate variable-level loops first, expand only cross-element subgraph - #496

Merged
bpowers merged 13 commits into
mainfrom
ltm/482-variable-level-loops-first
May 8, 2026
Merged

bpowers merged 13 commits into
mainfrom
ltm/482-variable-level-loops-first

Conversation

@bpowers

@bpowers bpowers commented May 7, 2026

Copy link
Copy Markdown
Owner

Summary

Implements the variable-level loop enumeration refactor planned in
docs/design-plans/2026-05-06-ltm-482-variable-level-loop-enumeration.md.
LTM exhaustive-mode loop detection now runs Johnson on the variable graph
first, classifies each cycle by its RefShape composition, and emits
pure-A2A and pure-scalar cycles directly as Loops without entering
element-level Johnson. Only cross-element / mixed cycles flow through
element-level Johnson, and only on the subgraph induced by their nodes.

Cost asymmetry that made pure-A2A cycles inflate multiplicatively in N
is gone. The auto-flip gate's domain narrows to the variable graph and
the cross-element subgraph.

Fixes #482.

Architecture

Step Today After this PR
Cycle enumeration Johnson on the full element graph (model_element_loop_circuits) Johnson on the variable graph + classify by RefShape + Johnson on the slow-path subgraph (model_loop_circuits_tiered)
Pure-A2A cycle N element-level circuits, collapsed back to 1 Loop in build_element_level_loops 1 fast-path circuit, materialized directly into 1 Loop
Pure-scalar cycle 1 element-level circuit -> 1 Loop 1 fast-path circuit -> 1 Loop
Cross-element cycle element-level Johnson on full element graph element-level Johnson on the slow-path subgraph (the element graph restricted to cross-element variables)
Auto-flip gate full element-graph SCC > 50 variable-level SCC > 50 (early gate) OR slow-path subgraph SCC > 50 (late gate)

The new model_edge_shapes salsa-tracked function records the
multiset of RefShape values seen at every reference site for each
variable-level edge. The cycle classifier
(classify_cycle) reads this map plus per-variable dimension
information to decide PureScalar / PureSameElementA2A /
CrossElementOrMixed.

Design plan

docs/design-plans/2026-05-06-ltm-482-variable-level-loop-enumeration.md
covers the staging breakdown, cost model, fixture impact predictions,
auto-flip threshold reasoning, and risks. The measurement postscript
in that document is filled in with the actuals captured by the new
integration tests.

Measurements

Captured by tests/simulate_ltm.rs::measurement_postscript_* on the
post-Stage-7 branch tip. Numbers come from
model_loop_circuits_tiered (fast / slow path counts and slow-path
SCC) plus the legacy model_element_loop_circuits (for the legacy
column).

Fixture var SCC elem SCC var circuits elem circuits (legacy) fast path slow path slow-path SCC auto-flip
cross_element_ltm 5 10 3 8 1 6 8 no / no
arrayed_population_ltm 3 3 2 6 2 0 0 no / no

Notes:

  • arrayed_population_ltm (pure-A2A, 3 regions): legacy enumerated
    6 element-level circuits (2 cycles * 3 regions); tiered enumerator
    produces 0 element-level circuits and 2 fast-path cycles. Slow-path
    subgraph is empty.
  • cross_element_ltm (mixed): the population<->births A2A cycle
    classifies as PureSameElementA2A (1 fast-path entry); the two
    FixedIndex-driven migration cycles drive the slow-path subgraph.
    Slow-path Johnson enumerates 6 element-level circuits versus 8 in
    the legacy full-element Johnson run because the slow-path subgraph
    excludes births[*].

WRLD3-03 (scalar, 166-node SCC) auto-flips on the new variable-level
SCC gate exactly as it did on the legacy element-graph SCC gate
(WRLD3 is fully scalar, so var SCC == elem SCC). hero_culture_ltm
(scalar) classifies every cycle as PureScalar; fast_path equals
var_circuits and slow_path is empty.

Loop output stability

All 48 tests in src/simlin-engine/tests/simulate_ltm.rs pass
without modification. Loop IDs are content-stable: assign_loop_ids
sorts loops by sorted distinct variable names before numbering, so
the merged Loop list (fast + slow) gets consistent r1/b1/u1
assignments across the refactor.

New fixture

tests::pure_a2a_eliminates_per_element_circuit_redundancy in
src/simlin-engine/src/db_analysis.rs builds a 30-element pure-A2A
fixture and asserts that the legacy enumerator produces 30
element-level circuits while the tiered enumerator produces 1
fast-path cycle and 0 slow-path Johnson runs. This is the
structural-win demonstration described in the design plan.

Drive-by fixes

Two simlin-serve test helpers (must_git in git.rs,
tests/git_integration.rs, and tests/watcher_git.rs) inherited
GIT_DIR / GIT_WORK_TREE / GIT_INDEX_FILE from the parent
process. When the workspace test suite runs from inside an outer
git commit (the project pre-commit hook invokes
cargo test --workspace), those env vars made the test's inner
git commit operate on the OUTER repository instead of the
freshly-git init'd temp dir, causing recursive pre-commit-hook
invocation. Fixed by stripping GIT_* env vars before spawning.
Discovered while running this PR's pre-commit on a developer
machine that has core.hooksPath configured globally.

Test plan

  • cargo test -p simlin-engine -- all 3176 tests pass
  • cargo test -p simlin-engine --features file_io --test simulate_ltm -- all 50 tests pass (48 prior + 2 new measurement-postscript tests)
  • cargo clippy --workspace --all-targets --all-features -- -D warnings -- clean
  • cargo build -p simlin --no-default-features -- clean (verifies TieredCircuitsResult works without the debug-derive feature)
  • Pre-commit hook passes on every commit in this branch

@claude

claude Bot commented May 7, 2026

Copy link
Copy Markdown

Review findings

[P2] Slow-path subgraph can re-enumerate fast-path A2A cycles, producing duplicate Loops

src/simlin-engine/src/db_analysis.rs:1395-1432 — The slow-path subgraph is built by including every element edge whose endpoints' underlying variables are in slow_path_var_nodes. The set is the union of variables that participate in any CrossElementOrMixed cycle. If a fast-path PureSameElementA2A cycle's variables happen to all also appear in slow_path_var_nodes (because each one independently participates in some cross-element cycle), the A2A cycle's pure-Bare element edges remain in the projected subgraph, so find_indexed_circuits_with_limit re-enumerates the per-element A2A copies. build_element_level_loops then groups them and emits an A2A Loop, which build_loops_from_tiered (db_ltm.rs:2032-2044) appends to the already-emitted fast-path A2A Loop. assign_loop_ids (ltm.rs:1871) sorts by content key but does not dedupe, so the user sees two Loops with identical links/stocks/dimensions and consecutive IDs (r1, r2).

Concretely, this triggers when arrayed variables a and b form a Bare-only A2A cycle and each independently sits in a cross-element cycle (e.g. a -> c -> a with a FixedIndex/Wildcard edge, plus b -> d -> b with another). None of the current fixtures exercise that topology — cross_element_ltm avoids it because births is only in the A2A cycle, not in any migration cycle, so the slow-path subgraph excludes births[*]. A defensive fix would skip cycles in the slow-path circuit list whose stripped variable sequence already appears as a fast-path FastPathCircuit.

Overall correctness

Correct for the topologies covered by the existing test suite, but the slow-path-subgraph projection above is a latent correctness issue worth addressing before models with the described shape land in user fixtures.

@bpowers bpowers left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Code Review: PR #496 -- LTM Variable-Level Loop Enumeration

Status

CHANGES REQUIRED

Issue Summary

Critical: 1 | Important: 2 | Minor: 4 | Praise: several

Verification Evidence

Tests: cargo test -p simlin-engine --features file_io
       -> 3,476+ tests passed; 14 ignored; 0 failed (across all binaries).
       simulate_ltm: 50 passed + 1 ignored. db tests / lib tests: 3,212 passed.
       Wall clock: ~10s total. Well under the 3-minute cap.

Build: cargo build -p simlin --no-default-features
       -> clean (verifies tracked types compile without debug-derive feature).

Clippy: cargo clippy --workspace --all-targets --all-features
        -> clean (only unrelated xmutil C++ warnings).

All existing tests/simulate_ltm.rs tests pass without modification (no expected-value
updates), confirming the byte-identical loop output claim on the existing test
fixtures
. See Critical-1 below for a topology not exercised by any existing test.

Plan Alignment

Implemented Requirements

  • AC1 (Edge-shape extraction): met.
  • AC2 (Cycle classification): met.
  • AC3 (Tiered enumeration): met.
  • AC4 (Loop output stability on existing fixtures): met for the fixtures that
    exist; not met in general -- see Critical-1.
  • AC5 (Structural-win demonstration): partially met. The plan called for a
    test-only override of MAX_LTM_SCC_NODES to demonstrate before/after
    auto-flip behavior. The implementation instead pins circuit-count
    inequality on a 30-element pure-A2A fixture, which is also fine and the
    PR description acknowledges the gate-behavior win is a no-op on existing
    fixtures (since #448 already broke up element SCCs into N independent
    size-2 SCCs).
  • AC6 (Documentation): met -- design plan, engine CLAUDE.md, LTM design
    doc, and tech-debt all updated.

Deviations from Plan

  • Stage 5 plan said "leave the gate alone, document the change, and file a
    follow-up issue to retarget the gate after measurement." The PR instead
    retargets the gate to max(variable_scc, slow_path_largest_scc).
    Justified: the design plan also reasons through the retarget
    rationale on lines 786-805, and the new gate is strictly safer
    (pure-A2A models with huge N stop tripping the gate; WRLD3 still trips
    it from the variable-level SCC). Moving Stage 5 forward is the right
    call.

Critical Issues (count: 1)

Critical-1: Double-counting of pure-A2A loops when their variables overlap with a slow-path cycle's variable set

  • Issue: A pure-A2A cycle whose variables are a SUBSET of the variables
    in some CrossElementOrMixed cycle gets emitted TWICE as a Loop.

  • Location: src/simlin-engine/src/db_analysis.rs:1928-2013 (slow-path
    subgraph induction in model_loop_circuits_tiered).

  • Impact: Violates the stated "byte-identical loop output" guarantee.
    Produces duplicate loop_score synthetic variables in model_ltm_variables,
    which means the same A2A reinforcing/balancing loop ends up with two
    distinct loop IDs (e.g., r1 AND r2 for the same content), inflating
    the user-visible loop list and breaking downstream rel-loop-score
    normalization (post-sim divides by sum of |scores| within a partition;
    the duplicate inflates the denominator).

  • Reproduction (verified by code probe; minimal fixture):

    state[Region] stock with inflow a[r]
    a[r]   = b + c        (flow)
    b[r]   = state + 0.01 (Bare reference to state)
    c[r]   = b[NYC] + 0.05 (FixedIndex reference to b)
    

    Variable cycles:

    • [a, state, b]: every edge Bare/structural -> classified PureSameElementA2A -> fast.
    • [a, state, b, c]: b -> c is FixedIndex -> CrossElementOrMixed -> slow.

    slow_path_var_nodes = {a, state, b, c} (every var in the slow cycle).
    The induced element-level subgraph keeps a[*], state[*], b[*],
    c[*] element nodes AND every element edge among them. Johnson on this
    subgraph produces:

    • a[NYC] -> state[NYC] -> b[NYC] -> a[NYC] (the A2A cycle reflected at NYC)
    • a[Boston] -> state[Boston] -> b[Boston] -> a[Boston] (the A2A cycle reflected at Boston)
    • a[NYC] -> state[NYC] -> b[NYC] -> c[NYC] -> a[NYC] (the legitimate cross-element cycle)

    Then build_element_level_loops on the slow path groups the two pure-A2A
    element circuits by their stripped key a\0state\0b and emits ONE A2A
    Loop -- a duplicate of the fast-path emission.

    Observed (PR branch):

    fast_path: 1
      fast: ["a", "state", "b"] dims=["region"]
    slow_path: 3 circuits
      slow: ["a[boston]", "state[boston]", "b[boston]"]   <-- duplicate of fast path
      slow: ["a[nyc]",    "state[nyc]",    "b[nyc]"]      <-- duplicate of fast path
      slow: ["a[nyc]",    "state[nyc]",    "b[nyc]", "c[nyc]"]
    --- LTM loop_score vars: 3 ---
      $⁚ltm⁚loop_score⁚r1 dims=["Region"]   <-- A2A
      $⁚ltm⁚loop_score⁚r2 dims=["Region"]   <-- DUPLICATE A2A (same cycle as r1)
      $⁚ltm⁚loop_score⁚u1 dims=["Region"]   <-- legitimate cross-element loop
    

    Same fixture on main:

    --- main: LTM loop_score vars: 2 ---
      $⁚ltm⁚loop_score⁚r1 dims=["Region"]   <-- A2A
      $⁚ltm⁚loop_score⁚u1 dims=["Region"]   <-- legitimate cross-element loop
    

    i.e. main emits the structurally correct 2 loops; this PR emits 3.

    Why existing fixtures don't catch this: in cross_element_ltm the A2A
    cycle is [population, births] and births does not appear in any
    slow-path-classified cycle (migration cycles use population +
    migration_pressure + migration_in/out). So slow_path_var_nodes
    excludes births, the induced subgraph drops births[*] element
    nodes, and the A2A cycle's element-level reflection cannot close in
    the subgraph. The bug only manifests when every variable of a
    fast-path cycle ALSO participates in a slow-path cycle. None of the
    existing test fixtures (cross_element_ltm, arrayed_population_ltm,
    hero_culture_ltm, WRLD3, the in-tree synthetic 30-element pure-A2A
    fixture) construct that topology.

  • Fix: Two viable approaches:

    1. After Johnson on the slow-path subgraph, drop any element-level
      circuit whose stripped variable-level node sequence (modulo cyclic
      rotation) matches a FastPathCircuit.variables sequence. The
      fast-path emission is the canonical source for those cycles; the
      slow-path enumeration must yield additional cycles only.
    2. Before running Johnson on the slow-path subgraph, prune element-level
      edges that participate ONLY in same-element pure-A2A cycles -- i.e.
      restrict the subgraph to edges that have a non-Bare reference shape
      OR cross-element same-shape variants. (Trickier to get right at
      element-edge granularity; approach 1 is simpler.)

    Either fix needs a regression test that pins the fixture above (or any
    other model that constructs the overlapping-cycle topology). The fixture
    in this review is small enough to live in simulate_ltm.rs as a unit
    test.

Important Issues (count: 2)

Important-1: MAX_LTM_SCC_NODES docstring not updated for the new gate semantics

  • Issue: src/simlin-engine/src/ltm.rs:1-46 documents the constant as
    applying to "the largest SCC of the element graph." Stage 5 of the
    design plan explicitly called for updating this docstring to reflect
    the new two-tier gate (variable-level SCC OR slow-path subgraph SCC).
    The new gate code in db_ltm.rs documents the change in-line, but the
    constant's own doc comment is now misleading.
  • Location: src/simlin-engine/src/ltm.rs:5-46.
  • Fix: Update the docstring to enumerate the two SCCs the gate now
    applies to and link to the 2026-05-06 design plan alongside the
    existing 2026-04-18 link.

Important-2: Legacy model_element_loop_circuits retained but documented as legacy

  • Issue: The PR description and engine CLAUDE.md correctly state
    that model_element_loop_circuits is now legacy (only the
    measurement test and the new pure_a2a_eliminates_per_element_circuit_redundancy
    unit test consume it). Keeping the legacy function alive in production
    code is a deliberate choice (Stage 8 in the plan defers its removal),
    but there is no #[deprecated] attribute and no compile-time
    enforcement that production callers don't accidentally re-introduce
    a dependency on it. As tech-debt #25 notes "(...) the auto-flip gate
    retargeting is a follow-up", but the legacy enumerator and the new
    enumerator now diverge on the topology described in Critical-1, so
    any future caller that picks the legacy path will silently get the
    pre-#482 (correct) behavior while the LTM path gets the buggy
    behavior. Either #[deprecated] it, or add an internal #[doc(hidden)]
    / module-level rustdoc warning, or convert it into a thin wrapper
    around the tiered enumerator's slow-path output (deferred to Stage 8
    in the plan, fine for now -- but track the divergence in tech-debt).

Minor Issues (count: 4)

Minor-1: measurement_postscript_cross_element_ltm doc comment claims var_scc = 4 but actual is 5

  • Location: src/simlin-engine/tests/simulate_ltm.rs:3895-3905.
  • Issue: The doc comment says var_scc = 4 (population, migration_pressure, migration_in, migration_out are in one variable-level SCC; total_population is acyclic), but the actual measured value (printed by --nocapture)
    is 5, matching the design plan's table on line 753 and the PR
    description. The comment lists 4 variables (missing births) but the
    actual SCC is 5 (population, births, migration_pressure, migration_in,
    migration_out). The test doesn't assert the exact value (only loose
    inequalities) so this isn't a test failure -- just a stale comment.
  • Fix: Either update the comment to var_scc = 5 and list all 5
    participating variables, or tighten the assertion to pin the exact
    numbers from the design-plan table.

Minor-2: Tech-debt #25 marked RESOLVED before merge

  • Location: docs/tech-debt.md:225-233.
  • Issue: Same convention concern as PR #490: marking RESOLVED is
    premature if the PR isn't merged. If the PR is force-pushed or
    abandoned, the tech-debt status would silently lie. Other entries
    (#20, #23, #26) follow the same convention so this isn't unique to
    this PR, but the project has not yet adopted a "(pending #N)" prefix
    to make the conditional visible.
  • Fix: Either revert the resolved marker until merge, or rephrase
    to "RESOLVED (pending #496)" to make the conditional explicit.

Minor-3: FastPathCircuit.dimensions fallback could produce mismatched casing

  • Location: src/simlin-engine/src/db_ltm.rs:2002-2015.
  • Issue: build_loops_from_tiered maps each canonical dim name back
    to its raw datamodel name via dm_dims.iter().find(...). The fallback
    unwrap_or_else(|| canonical.clone()) returns the canonical (lower-case)
    name, which would produce a Loop.dimensions entry that doesn't match
    any datamodel dim and would then fail to resolve when the equation
    parser feeds it into Equation::ApplyToAll. This shouldn't happen for
    well-formed projects because every cycle node's dim must be in
    dm_dims, but there's no diagnostic if it ever does.
  • Fix: Either add a debug-assert that the canonical name was found
    (panics in debug, defaults silently in release) or document the
    invariant in a code comment so the reader knows the fallback is a
    defensive no-op.

Minor-4: Slow-path subgraph induction is not commented to explain the no-double-counting reasoning

  • Location: src/simlin-engine/src/db_analysis.rs:1928-1965.
  • Issue: The slow-path induction excludes element nodes for variables
    not in slow_path_var_nodes. The reasoning that this excluded set
    prevents double-counting is critical to correctness, but the comment
    block doesn't explain it. With Critical-1 above showing the reasoning
    is in fact incomplete (the bug arises because variables CAN be in
    both sets when fast-path cycles' variable sets are subsets of slow
    cycles' variable sets), this is exactly the kind of comment that
    should have been there to make the bug visible during review.
  • Fix: Whichever fix is chosen for Critical-1, document the
    invariant the slow-path subgraph is supposed to preserve, and the
    test that pins the topology. (This minor is largely subsumed by the
    Critical-1 fix.)

Praise

  • Comprehensive design plan: 805 lines, walks through architecture,
    cost model, fixture predictions vs measurements (postscript filled in
    with actuals), risks (R1-R5), 8 stages, ACs. Honest about what
    post-#448 the gate-behavior win is, and what is purely circuit-count
    reduction.
  • Honest measurement table in the design plan and PR description:
    the post-#448 baseline is acknowledged, and the actual win is
    characterized correctly as additive-not-multiplicative cost (not as
    a gate-behavior fix).
  • GIT_ drive-by commits are byte-identical* to the equivalent commits
    on PRs #491 (16c59b07) and #494 (34c4befa, baeeef48) modulo a
    minor docstring rewording on watcher_git.rs. Consistent across PRs.
  • No emoji, no Co-Authored-By, no "Generated with" in commits, PR
    body, or design plan. Lowercase commit-message prefixes follow the
    project convention.
  • #[salsa::Update] derives correctly applied to the new tracked
    types (EdgeShapesResult, FastPathCircuit, TieredCircuitsResult).
    Hash/Ord on RefShape make BTreeSet<RefShape> deterministic.
    cargo build --no-default-features clean confirms Debug on the new
    types is unconditional and correct.
  • Test budget within targets: each new test runs sub-second on debug
    build. The pure_a2a_eliminates_per_element_circuit_redundancy 30-element
    fixture finishes effectively instantly.
  • Engine CLAUDE.md update is accurate and concise: describes the
    tiered enumerator entry points, classify_cycle contract, and the
    new auto-flip gate semantics in one paragraph each.
  • build_loops_from_tiered's assign_loop_ids re-run on the merged
    fast/slow Loop list correctly preserves the legacy ID assignment
    scheme (sort by stripped distinct var-name set). The merging strategy
    is right; the bug is in WHAT goes into the merged list.

Skills Applied

  • coding-effectively (defense-in-depth, writing-good-tests):
    applied to validate that the existing tests don't actually pin the
    byte-identical loop output claim across all topologies. The test
    fixtures don't construct the variable-set-overlap topology.
  • Code reading: traced cycle classification, slow-path subgraph
    induction, and build_loops_from_tiered end-to-end on a worked
    example before and after the change.
  • Verification before completion: ran the test suite, clippy, no-default-features
    build, and a custom probe to verify the double-counting hypothesis
    on both branches.

Decision

BLOCKED -- CHANGES REQUIRED

Critical-1 is a real correctness regression: this PR emits duplicate Loops
on a topology that any moderately complex arrayed model can produce. The
test suite happens to not exercise it, so CI is green, but the bug is
demonstrable in two evaluations of an 8-line TestProject fixture.

Recommended path forward:

  1. Add the worked-example fixture (above) as a new simulate_ltm.rs test
    that asserts the loop count matches main (or asserts no two Loops
    share a stripped variable-name multiset).
  2. Watch it fail on this PR.
  3. Fix via the slow-path-circuit dedup approach (Critical-1 fix
    suggestion 1) or the slow-path-subgraph edge-pruning approach
    (suggestion 2). Suggestion 1 is simpler.
  4. Re-run the full LTM test suite; confirm all numbers in the
    measurement-postscript tests still match the design-plan table.
  5. Address Important-1 (MAX_LTM_SCC_NODES docstring) and the four
    Minor issues in the same fix-up pass.

bpowers pushed a commit that referenced this pull request May 7, 2026
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.

@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 (slow-path A2A duplicate Loop): fixed in b74364f. Approach:
Option A -- dedupe slow-path circuits against fast-path emissions
inside model_loop_circuits_tiered. After the slow-path Johnson run,
each circuit's stripped variable-level node sequence is compared
(rotation-invariant via canonical_cycle_rotation) against the set of
fast-path circuit node sequences and dropped if it matches. This is the
robust fix that stays correct even if the induction set is broader than
strictly necessary; Option B (refining the slow-path induction set) was
considered but the risk of subtle topology misses was higher than the
clarity benefit. Added the reviewer's reproducer (a/grow/stock/b pure-
A2A reinforcing + a/grow/stock/b/c cross-element with c[r] = b[NYC] * 0.5) as test_dedup_slow_path_a2a_against_fast_path in
tests/simulate_ltm.rs. Verified the fixture fails on the prior commit
(3 loops emitted: r1, r2, u1) and passes after the fix (2 loops).

Important (MAX_LTM_SCC_NODES docstring): updated in 41b778c to
describe the post-#482 two-granularity gate (variable-level SCC plus
slow-path subgraph SCC).

Important (legacy fn #[deprecated]): added in 41b778c.
model_element_loop_circuits now carries a #[deprecated] attribute.
Existing internal callers (measurement helpers, db_element_graph_tests,
db_ltm_unified_tests, ltm_full_bench example) carry
#[allow(deprecated)] with a comment explaining why each callsite
intentionally targets the legacy surface. The salsa-tracked function's
own definition needs an inner #[allow(deprecated)] because the
#[salsa::tracked] macro expansion references the function by name in
its generated code; the comment in the source explains this constraint.

Minor (var_scc=4 -> 5 in doc comment): fixed in 98c6193. Confirmed
post-#482 measurement is var_scc=5 / elem_scc=10 (births is in the
SCC because its structural inflow plus the population reference closes
the population<->births A2A pair).

Minor (tech-debt #25 RESOLVED reverted): fixed in 98c6193 to
RESOLVED (pending #496 merge).

Minor (FastPathCircuit casing fallback): fixed in 98c6193. The
unwrap_or_else(|| canonical.clone()) in build_loops_from_tiered
that masked an unmatched datamodel dimension is now an unreachable!
that lists the known dimensions, with a comment documenting the
invariant the panic enforces.

Minor (slow-path induction comment): added in b74364f alongside the
fix. The slow-path subgraph block now explains why the induction is
intentionally broad and why dedup is required.

PR remains in draft.

@claude

claude Bot commented May 7, 2026

Copy link
Copy Markdown

Review Summary

I reviewed the tiered loop enumeration refactor and the drive-by GIT_* env-var fix. The implementation matches the design plan, the cycle classifier is conservative in the right direction, the dedup logic for slow-path / fast-path overlap is correct (and well-pinned by test_dedup_slow_path_a2a_against_fast_path), and the auto-flip gate change is sound. Tests cover the structural-win demonstration (pure_a2a_eliminates_per_element_circuit_redundancy), AC1-AC3 (edge shapes, classifier, tiered enumeration), AC4 (loop ID stability is preserved by assign_loop_ids running once over the merged set in build_loops_from_tiered), and the new measurement-postscript integration tests pin the postscript numbers in the design plan.

A few minor observations that don't rise to the level of bugs:

  1. build_loops_from_tiered panics on dimension lookup failure where the legacy code fell back gracefully. The legacy build_element_level_loops used unwrap_or_else(|| canonical.to_string()) when a canonical dimension name didn't appear in dm_dims; the new code uses unreachable!(...). The author's invariant comment is plausible (variables only reference dims registered in dm_dims), but if there's ever a corner case (e.g., synthesized dimensions, mapped dimension aliases), this regresses from a silent fallback to a panic. Not a known reproducer, just worth noting.

  2. run_git in simlin-serve/src/git.rs (production path) strips every GIT_* env var, not only the path-related ones. The intent (per the comment) is to neutralize GIT_DIR / GIT_WORK_TREE / GIT_INDEX_FILE, but the loop also strips GIT_AUTHOR_*, GIT_COMMITTER_*, GIT_SSH_COMMAND, GIT_ASKPASS, etc. In practice the production callsite only runs git ls-files and git status --porcelain, neither of which uses author identity or transport vars, so behavior is unaffected. A future commit that uses run_git to commit/push would silently lose those vars.

Neither blocks merging. The cycle-classification logic, dedup invariants, and gate updates all look right.

Overall Correctness Verdict

Correct. No blocking issues. Existing tests (including the comprehensive new fixture set) pass according to the PR description, the legacy model_element_loop_circuits is preserved with a #[deprecated] annotation for diagnostic callers, and loop ID stability is preserved through canonical sorting in assign_loop_ids.

@codecov

codecov Bot commented May 7, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 89.93056% with 29 lines in your changes missing coverage. Please review.
✅ Project coverage is 82.42%. Comparing base (957b20f) to head (a9637ca).
⚠️ Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
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/tests/simulate_ltm.rs 85.93% 9 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #496      +/-   ##
==========================================
+ Coverage   82.39%   82.42%   +0.02%     
==========================================
  Files         243      243              
  Lines       61533    61802     +269     
==========================================
+ Hits        50701    50938     +237     
- Misses      10832    10864      +32     

☔ 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:10
@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

GIT_* env strip is now narrowed to path-targeting vars only
(GIT_DIR, GIT_WORK_TREE, GIT_INDEX_FILE, GIT_OBJECT_DIRECTORY,
GIT_COMMON_DIR). Fixed in 08c1874.

Future code that uses run_git to commit, push, or pull will now
inherit GIT_AUTHOR_, GIT_COMMITTER_, GIT_SSH_COMMAND, GIT_ASKPASS,
GIT_TERMINAL_PROMPT, etc. from the calling environment as expected.
The original pre-commit-hook reentrancy fix is preserved -- the
narrow set still includes every var that retargets git at the wrong
repository.

(PRs #491 and #494 carry their own copies of the broader strip; the
narrowing will land there as part of the cross-branch rebase once
one of these PRs merges to main.)

PR is now marked ready for 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

GIT_* env strip is now narrowed to path-targeting vars only
(GIT_DIR, GIT_WORK_TREE, GIT_INDEX_FILE, GIT_OBJECT_DIRECTORY,
GIT_COMMON_DIR). Fixed in 08c1874.

Future code that uses run_git to commit, push, or pull will now
inherit GIT_AUTHOR_, GIT_COMMITTER_, GIT_SSH_COMMAND, GIT_ASKPASS,
GIT_TERMINAL_PROMPT, etc. from the calling environment as expected.
The original pre-commit-hook reentrancy fix is preserved -- the
narrow set still includes every var that retargets git at the wrong
repository.

(PRs #491 and #494 carry their own copies of the broader strip; the
narrowing will land there as part of the cross-branch rebase once
one of these PRs merges to main.)

PR is now marked ready for review.

@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: 08c1874e60

ℹ️ 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/db_ltm.rs Outdated
Comment on lines +2024 to +2031
.unwrap_or_else(|| {
let known: Vec<&str> = dm_dims.iter().map(|d| d.name()).collect();
unreachable!(
"fast-path A2A cycle references dimension {canonical:?} that is \
not in the project's datamodel dimensions {known:?}; this is an \
internal invariant violation in `model_loop_circuits_tiered` \
(see `FastPathCircuit::dimensions`)"
)

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 Avoid panicking when fast-path dimension lookup misses

build_loops_from_tiered now treats an unmatched canonical dimension as unreachable!, which will panic the whole LTM pipeline instead of degrading gracefully. This is a regression from the existing element-loop path (build_element_level_loops/link-score mapping), which falls back to the canonical name when a datamodel name lookup misses. In incremental or partially-invalid model states (or any source/dimension mismatch), this turns a recoverable analysis warning into a hard crash.

Useful? React with 👍 / 👎.

@claude

claude Bot commented May 7, 2026

Copy link
Copy Markdown

Review

I reviewed the tiered loop-enumeration refactor (variable-level Johnson + classifier + cross-element subgraph Johnson), the auto-flip gate retargeting, and the simlin-serve GIT_* drive-by fix.

The most subtle area is the slow-path / fast-path dedup in model_loop_circuits_tiered (src/simlin-engine/src/db_analysis.rs:2046-2088). I traced it for several scenarios: per-element reflections of a pure-A2A cycle that shares variables with a cross-element cycle (correctly dropped), longer cross-element cycles whose stripped variable sequence matches a fast-path key by length but not topology (different lengths, kept), self-loop or repeat-bearing slow-path cycles (key computation skipped, kept). The canonical_cycle_rotation lex-smallest pivot is well-defined for all-distinct sequences, which matches the precondition. The new test_dedup_slow_path_a2a_against_fast_path regression pins the case the comment describes.

Other spots I checked:

  • classify_cycle rules cover the closure semantics correctly: any non-Bare shape (including Bare co-existing with Wildcard/FixedIndex/DynamicIndex) trips CrossElementOrMixed; mixed scalar/arrayed nodes and arrayed nodes with differing dim lists also trip it; pure same-dim Bare cycles emit PureSameElementA2A with the shared dim list.
  • model_edge_shapes short-circuits structural flow→stock and module-target edges to {Bare} consistent with model_element_causal_edges's behavior. The edge_keys_match_variable_edges test pins the coverage invariant.
  • The two-stage auto-flip in model_ltm_variables (variable SCC early gate, slow-path subgraph SCC late gate) correctly preserves the legacy behavior on WRLD3 (var SCC = 166 trips early gate before any Johnson runs) while letting pure-A2A models through.
  • build_loops_from_tiered re-runs assign_loop_ids over the merged fast+slow Loop list after stripping the slow-path IDs the helper assigned; this is mildly wasted work but keeps numbering stable.
  • The simlin-serve strip_git_path_env only removes path-targeting GIT_* vars and preserves identity / transport / credential ones — the test strip_git_path_env_removes_only_path_targeting_vars pins this contract.

I did not find any actionable bugs that meet the bar for flagging. The dedup logic, classification rules, gate retargeting, and env-var sanitization all look correct based on the documented invariants and the test coverage.

Findings

(none)

Overall correctness verdict

Correct.

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.
@bpowers
bpowers force-pushed the ltm/482-variable-level-loops-first branch from 08c1874 to a9637ca Compare May 8, 2026 14:51

@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 post-#498 main

  • Dropped the redundant older GIT_* commit (main's #489 carried the
    vars_os version; this branch's narrowed allowlist supersedes it).
  • Re-applied the narrowed-allowlist commit (strip_git_path_env helper
    with explicit const list of path-targeting vars only) -- preserves
    GIT_AUTHOR_, GIT_COMMITTER_, GIT_SSH_COMMAND, GIT_ASKPASS,
    GIT_TERMINAL_PROMPT for future commit/push code.
  • Carried the LTM tiered-enumeration changes onto the new ltm/
    module structure. The MAX_LTM_SCC_NODES docstring update now
    lives in src/simlin-engine/src/ltm/mod.rs.
  • Codex P2 (build_loops_from_tiered unreachable! on dim lookup
    miss): fixed in a9637ca. Replaced unreachable! with a
    fallback to the canonical dim name + debug_assert!, mirroring
    build_element_level_loops's behavior.

mergeable: MERGEABLE after rebase + force-push.

This PR is the bottom of the LTM stack. Subsequent rebases of
#490, #491, #494 will set their base branches to the next PR's
branch (then ultimately to main) so the stack flattens as PRs
land.

@claude

claude Bot commented May 8, 2026

Copy link
Copy Markdown

Review summary

I reviewed the tiered loop enumeration refactor (model_loop_circuits_tiered, model_edge_shapes, classify_cycle, build_loops_from_tiered), the auto-flip gate split, the slow-path subgraph projection, and the slow-path/fast-path dedup. The fast/slow partition logic is well-tested, the dedup correctly canonicalizes cycle rotations and skips circuits with repeated stripped names (preserving cross-element cycles), and the new regression test test_dedup_slow_path_a2a_against_fast_path pins the duplicate-Loop bug noted in the PR description. The git env-strip drive-by fix in simlin-serve correctly limits the strip to the path-targeting allowlist, with the rationale documented inline. I also walked the deprecation handling on model_element_loop_circuits (re-export plus internal #[allow(deprecated)] suppression for the salsa-generated callsite) and the new tests (classifier, edge-shapes, tiered enumerator) — all look sound.

No blocking findings.

Two minor non-blocking observations:

  • src/simlin-engine/src/db_ltm.rs:2592-2600 — the late-stage auto-flip diagnostic references only docs/design/ltm--loops-that-matter.md, while the early-stage message at lines 2516-2528 references both docs/design-plans/2026-04-18-... and docs/design-plans/2026-05-06-.... Adding the 2026-05-06 design plan to the late-stage message would make the two messages consistent and aid debugging.
  • src/simlin-engine/src/db_analysis.rs:1783 — the deprecation declares since = \"0.2.0\" but simlin-engine/Cargo.toml is at version = \"0.1.0\". Forward-looking but harmless.

Overall correctness verdict

Correct. No blocking issues identified.

@bpowers
bpowers merged commit 924725c into main May 8, 2026
14 checks passed
@bpowers
bpowers deleted the ltm/482-variable-level-loops-first branch May 8, 2026 16:07
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: enumerate variable-level loops first, expand only cross-element subgraph

1 participant