Repository navigation
ltm: enumerate variable-level loops first, expand only cross-element subgraph - #496
Conversation
Review findings[P2] Slow-path subgraph can re-enumerate fast-path A2A cycles, producing duplicate
|
bpowers
left a comment
There was a problem hiding this comment.
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 ofMAX_LTM_SCC_NODESto 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 tomax(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 someCrossElementOrMixedcycle gets emitted TWICE as a Loop. -
Location:
src/simlin-engine/src/db_analysis.rs:1928-2013(slow-path
subgraph induction inmodel_loop_circuits_tiered). -
Impact: Violates the stated "byte-identical loop output" guarantee.
Produces duplicateloop_scoresynthetic variables inmodel_ltm_variables,
which means the same A2A reinforcing/balancing loop ends up with two
distinct loop IDs (e.g.,r1ANDr2for 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 -> cis FixedIndex -> CrossElementOrMixed -> slow.
slow_path_var_nodes = {a, state, b, c}(every var in the slow cycle).
The induced element-level subgraph keepsa[*],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_loopson the slow path groups the two pure-A2A
element circuits by their stripped keya\0state\0band 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 loopSame 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 loopi.e. main emits the structurally correct 2 loops; this PR emits 3.
Why existing fixtures don't catch this: in
cross_element_ltmthe A2A
cycle is[population, births]andbirthsdoes not appear in any
slow-path-classified cycle (migration cycles use population +
migration_pressure + migration_in/out). Soslow_path_var_nodes
excludesbirths, the induced subgraph dropsbirths[*]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:
- After Johnson on the slow-path subgraph, drop any element-level
circuit whose stripped variable-level node sequence (modulo cyclic
rotation) matches aFastPathCircuit.variablessequence. The
fast-path emission is the canonical source for those cycles; the
slow-path enumeration must yield additional cycles only. - 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 insimulate_ltm.rsas a unit
test. - After Johnson on the slow-path subgraph, drop any element-level
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-46documents 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 indb_ltm.rsdocuments 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
thatmodel_element_loop_circuitsis now legacy (only the
measurement test and the newpure_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 = 5and 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_tieredmaps each canonical dim name back
to its raw datamodel name viadm_dims.iter().find(...). The fallback
unwrap_or_else(|| canonical.clone())returns the canonical (lower-case)
name, which would produce aLoop.dimensionsentry that doesn't match
any datamodel dim and would then fail to resolve when the equation
parser feeds it intoEquation::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 inslow_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 onwatcher_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/OrdonRefShapemakeBTreeSet<RefShape>deterministic.
cargo build --no-default-featuresclean confirmsDebugon the new
types is unconditional and correct.- Test budget within targets: each new test runs sub-second on debug
build. Thepure_a2a_eliminates_per_element_circuit_redundancy30-element
fixture finishes effectively instantly. - Engine CLAUDE.md update is accurate and concise: describes the
tiered enumerator entry points,classify_cyclecontract, and the
new auto-flip gate semantics in one paragraph each. build_loops_from_tiered'sassign_loop_idsre-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, andbuild_loops_from_tieredend-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:
- Add the worked-example fixture (above) as a new
simulate_ltm.rstest
that asserts the loop count matches main (or asserts no two Loops
share a stripped variable-name multiset). - Watch it fail on this PR.
- 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. - Re-run the full LTM test suite; confirm all numbers in the
measurement-postscript tests still match the design-plan table. - Address Important-1 (MAX_LTM_SCC_NODES docstring) and the four
Minor issues in the same fix-up pass.
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
left a comment
There was a problem hiding this comment.
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.
Review SummaryI reviewed the tiered loop enumeration refactor and the drive-by A few minor observations that don't rise to the level of bugs:
Neither blocks merging. The cycle-classification logic, dedup invariants, and gate updates all look right. Overall Correctness VerdictCorrect. No blocking issues. Existing tests (including the comprehensive new fixture set) pass according to the PR description, the legacy |
Codecov Report❌ Patch coverage is 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. 🚀 New features to boost your workflow:
|
|
@codex review |
bpowers
left a comment
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
💡 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".
| .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`)" | ||
| ) |
There was a problem hiding this comment.
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 👍 / 👎.
ReviewI reviewed the tiered loop-enumeration refactor (variable-level Johnson + classifier + cross-element subgraph Johnson), the auto-flip gate retargeting, and the simlin-serve The most subtle area is the slow-path / fast-path dedup in Other spots I checked:
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 verdictCorrect. |
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.
08c1874 to
a9637ca
Compare
bpowers
left a comment
There was a problem hiding this comment.
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.
Review summaryI reviewed the tiered loop enumeration refactor ( No blocking findings. Two minor non-blocking observations:
Overall correctness verdictCorrect. No blocking issues identified. |
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
RefShapecomposition, and emitspure-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
model_element_loop_circuits)RefShape+ Johnson on the slow-path subgraph (model_loop_circuits_tiered)build_element_level_loopsThe new
model_edge_shapessalsa-tracked function records themultiset of
RefShapevalues seen at every reference site for eachvariable-level edge. The cycle classifier
(
classify_cycle) reads this map plus per-variable dimensioninformation to decide PureScalar / PureSameElementA2A /
CrossElementOrMixed.
Design plan
docs/design-plans/2026-05-06-ltm-482-variable-level-loop-enumeration.mdcovers 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 thepost-Stage-7 branch tip. Numbers come from
model_loop_circuits_tiered(fast / slow path counts and slow-pathSCC) plus the legacy
model_element_loop_circuits(for the legacycolumn).
Notes:
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.
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.rspasswithout modification. Loop IDs are content-stable:
assign_loop_idssorts 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_redundancyinsrc/simlin-engine/src/db_analysis.rsbuilds a 30-element pure-A2Afixture 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_gitingit.rs,tests/git_integration.rs, andtests/watcher_git.rs) inheritedGIT_DIR/GIT_WORK_TREE/GIT_INDEX_FILEfrom the parentprocess. When the workspace test suite runs from inside an outer
git commit(the project pre-commit hook invokescargo test --workspace), those env vars made the test's innergit commitoperate on the OUTER repository instead of thefreshly-
git init'd temp dir, causing recursive pre-commit-hookinvocation. Fixed by stripping
GIT_*env vars before spawning.Discovered while running this PR's pre-commit on a developer
machine that has
core.hooksPathconfigured globally.Test plan
cargo test -p simlin-engine-- all 3176 tests passcargo 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-- cleancargo build -p simlin --no-default-features-- clean (verifiesTieredCircuitsResultworks without thedebug-derivefeature)