Repository navigation
engine: LTM arrays hardening (epic #488) - #537
Conversation
The array-reducer recognition set was restated five times across db_analysis, ltm_agg, and ltm_augment (with subtle disagreements on SIZE and multi-arg MEAN). Introduce one ReducerKind table in ltm_agg (reducer_kind / reducer_kind_from_name) plus the thin predicates the former sites need: reducer_name_is_monotone, reducer_is_monotone, and reducer_is_hoistable. ReducerKind moves here from ltm_augment, which now re-exports it. Monotonicity is keyed on the reducer name rather than carried by the 3-variant ReducerKind enum because Nonlinear lumps the monotone 1-arg MIN/MAX with the non-monotone STDDEV/RANK; the name-keyed predicate lives next to reducer_kind so the set and its classification still sit in one place. The functions carry a temporary #[allow(dead_code)] -- the next commit rewires the five recognition sites onto them and removes the attributes.
…is_array_reducer
Mechanical, behavior-preserving rewiring of the former reducer-set
restatements onto the consolidated reducer_kind table:
- db_analysis::builtin_is_array_reducer is deleted; collect_in_expr's
in_reducer marker now reads ltm_agg::reducer_is_hoistable.
- ltm_agg::reducer_source_vars drops its inline is_reducer match for
reducer_is_hoistable (source-extraction and the >=1-arrayed-source
requirement are unchanged).
- ltm_agg::agg_reducer_is_monotone extracts the leading function name
from the agg's printed equation text and defers to
reducer_name_is_monotone; the prior starts_with("sum(" | ...) set is
preserved exactly (print_eqn output has no space before the paren).
- ltm_augment::is_array_reducer_name becomes a reader of
reducer_kind_from_name (still includes SIZE; mean/min/max only at
arity 1).
- ltm_augment::classify_builtin_if_references_source recognizes via
reducer_kind, then checks the reduced array (the first argument in
every recognized reducer) against the source. Multi-argument MEAN now
yields None there, matching reducer_kind; classify_reducer is only
ever reached for a hoisted (and therefore recognized) reducer, so this
case cannot occur in practice. The temporary #[allow(dead_code)] from
the previous commit is removed (reducer_is_monotone keeps it -- its
natural caller, the static polarity pass, is out of scope here).
check-docs.py stripped fenced code blocks before running the [text](target) markdown-link regex but left inline code spans intact, so code/math notation like `s[d](t)` inside backticks was mis-parsed as a broken link. The script's docstring already promised that code identifiers in backticks aren't checked; this makes that true for link targets too by blanking single-line inline code spans (length preserved so reported line numbers stay accurate) before the link scan. The backtick-path check for CLAUDE.md still sees the spans, as it must.
The eight per-phase task files and test-requirements.md produced from the 2026-05-11 design plan. These are the working artifacts that execute-implementation-plan runs against; tracking them keeps the branch self-contained alongside the already-committed design plan.
Documentation-only follow-up to the Phase 1 reducer-recognition
consolidation; no behavior change.
- classify_builtin_if_references_source: the multi-arg-MEAN / 2-arg
MIN/MAX case returning None is not an unreachable fallback. A target
like result = MEAN(pop[NYC], other[Boston]) does reach classify_reducer
via try_cross_dimensional_link_scores; with None there it falls through
to per-shape link scoring off the FixedIndex sites in the
classification IR, which is strictly more correct than the old
hand-rolled Mean(any arity) arm (that emitted a spurious full-reduce
over pop, including pop[boston] -> result).
- agg_reducer_is_monotone: document that the leading-name extraction is
intentionally lenient (tolerates an optional paren / whitespace) and
that this is harmless because the input is always print_eqn output and
an aggregate equation always has a paren -- an explicit choice rather
than restating the literal "sum(" | "mean(" | ... set the
consolidation removed.
- reducer_is_hoistable: drop the stale reference to the deleted
db_analysis::builtin_is_array_reducer; describe the predicate by what
it is (recognized AND not Constant; the gate the reference-site IR walk
and reducer_source_vars share).
Fold Phase 2 Tasks 1-3 (the engine half of GH #487, partition-correct A2A loop normalization): they land together because `LtmVariablesResult`'s `loop_partitions` shape change couples the `partition_for_loop` return, the element-level `Loop::stocks` construction, and the post-sim rel-loop-score normalizer through their shared `layout/mod.rs` call site -- a split would need throwaway adapter code. - `Loop::stocks` is now element-level for arrayed models in *all* cases. A2A loops carry one `"{var}[{elem-tuple}]"` per element of the loop's dimension element space (row-major over the loop's dimensions, the runtime/`LoopElementIndex` slot order), for each cycle variable that is a stock -- the same strip-and-rebuild the cross-element/mixed branches already used. Loop IDs are derived from `links`, not `stocks`, so this doesn't perturb `r{n}`/`b{n}` numbering. - `CyclePartitions::partition_for_loop(loop, dims)` returns `Vec<Option<usize>>` -- one partition per slot. A scalar/cross-element loop has a singleton; an A2A loop has one entry per element, looked up by grouping its element-level stocks by their element-tuple suffix. Within a slot every parent-level stock shares a partition (the per-element SCC's diagonal hop); across slots of an element-wise-uncoupled A2A dimension they differ -- the per-slot grouping is the fix. `dims` enumerates the element-tuple slot order the way `build_loop_element_index` does; missing dims fall back to the suffixes present on the loop's stocks, sorted. `LtmVariablesResult.loop_partitions` becomes `HashMap<String, Vec<Option<usize>>>` with a debug_assert reconciling the vector length against `build_loop_element_index`'s `n_slots`. - `ltm_post::compute_rel_loop_scores{,_per_element}` take the per-slot map. `compute_rel_loop_scores` is the slot-0 convenience view (groups by each loop's slot-0 partition). `compute_rel_loop_scores_per_element` groups by `(slot_partition(id, k), k)` and drops the `n_slots_by_loop` arg (the slot count is the vector length); a coupled-dim A2A loop's slots land in `(p, 0), (p, 1), ...`; an uncoupled-dim A2A loop spreads across `(p0, 0), (p1, 1), ...` so two disconnected per-element subsystems stop cross-normalizing; scalar loops keep the existing broadcast. `ltm_finding::rank_and_filter` collapses the (always-length-1) discovered loops to slot 0; `layout/mod.rs` drops `n_slots_by_loop` from the call. - `libsimlin`: mechanical field/alias type changes only -- `SimState`'s `loop_partitions` and `simulation.rs`'s `CompileSnapshot` become per-slot, and `analysis.rs` groups the rel-loop-score denominator by the loop's slot-0 partition. Teaching `simlin_analyze_get_relative_loop_score` to group by the *queried* slot's partition (so an uncoupled A2A loop normalizes per element through the FFI), plus the round-trip test, are a follow-up; the C header / `@simlin/engine` / `pysimlin` are unaffected. Golden data: `test/logistic_growth_ltm/ltm_results.tsv` is byte-unchanged (scalar model); no arrayed-LTM expected-output file or inline hand-calc constant changed.
…via subscripted loop id Phase 2 Task 4 (GH #487, AC2.5). `SimState.loop_partitions` is already the per-slot `HashMap<String, Vec<Option<usize>>>` shape from the engine-side commit; this teaches `simlin_analyze_get_relative_loop_score` to actually use the queried slot's partition rather than slot 0: - The rel-loop-score denominator for `loop_id="r1[elem]"` is now keyed on `loop_partitions["r1"][element_k]` -- the cycle partition of *that* slot -- so an element-wise-uncoupled A2A loop normalizes per element instead of against a pooled slot-0 bucket. `ensure_denom_for_element` filters member loops by their slot-`element_k` partition using the same `slot_partition` convention `ltm_post::compute_rel_loop_scores_per_element` uses (broadcast a scalar loop's single partition into every slot it is compared in; an arrayed loop contributes its own slot k for k < n_slots and is skipped past that). Combined with `compute_partition_denominator_for_element`'s `effective_slot` read offsets, the FFI's amortized per-bucket cache reproduces the engine's full-sweep `(partition, slot)` bucket sums bit-for-bit. The argmax-abs aggregator (bare arrayed loop id) keys each slot's denominator on that slot's partition too. The no-element / scalar form is unchanged: a scalar loop's `loop_partitions[id]` is `[Some(p)]`, so slot 0 is `p`. - `cached_partition_denominators`'s key stays `(Option<usize>, usize)`; the `Option<usize>` now means "partition of slot k", consistent with the new bucketing. A `debug_assert!` in `simlin_sim_new` reconciles each loop's `loop_partitions[id].len()` against `loop_element_index[id].n_slots` (both projected from the same `LtmSyntheticVar` metadata). The per-slot relative loop score is reachable via the existing subscripted loop id accessor -- `simlin_analyze_get_relative_loop_score("r1[elem]")` -- with `simlin_analyze_get_relative_loop_score("r1")` (the bare arrayed form, which is the argmax-abs aggregator across slots) and `simlin_analyze_get_loop_element_count("r1")` for the slot count; no new C API, so `simlin.h` is byte-unchanged. New `tests/analysis.rs` round-trip test: compiles a two-disconnected-A2A- subsystem model (`pop[Region]` and `widgets[Product]` over different dims, both reinforcing), runs it both through the FFI and directly through the engine, and asserts the FFI's per-element rel-loop-score for every `{loop}[{elem}]` matches `ltm_post::compute_rel_loop_scores_per_element` exactly and equals 1.0 (each loop alone in its per-element partition -- not the pre-fix pooled ~0.5 the two loops would share if they cross-normalized).
Phase 2 changed `compute_rel_loop_scores_per_element` so an arrayed loop's series is laid out at `stride == n_slots` (its own slot count) instead of the partition's max stride, eliminating the trailing padding slots that an arrayed loop in a mixed-dimensionality partition used to carry. The rustdoc on `aggregate_per_element_argmax_abs` still described the old "padded to the partition max, skip n_slots..stride" contract; rewrite it (and the adjacent inline comments and the `aggregate_arrayed_in_mixed_partition_*` test's framing) to reflect that an arrayed loop now has no padding, and that a scalar loop's stride is just the largest slot index its partition covers. The aggregator code is unchanged -- it already iterates the loop's own `n_slots` defensively, which is still correct (and still useful if a caller hands it a series with a wider recovered stride). Add a proptest pairing `compute_rel_loop_scores_per_element` against a from-first-principles oracle: rather than the engine's pre-built `(partition, slot)` BTreeMap grid, the reference loops over each `(loop, output-slot, step)` and re-derives the SAFEDIV denominator by scanning every loop and asking whether it is a member of that bucket (spelling out the `slot_partition` broadcast and the arrayed-loop slot gating inline). Generated partition vectors cover coupled (all entries the same `Some(p)`), uncoupled (distinct `Some(p)` per slot), `None`-laced, and scalar shapes; the comparison is bit-exact because both paths sum the same floats in sorted-loop-id order. This is the regression net for the GH #487 bucket-grouping fix.
The `debug_assert!` in `simlin_sim_new` that cross-checks `loop_partitions[id].len()` against `loop_element_index[id].n_slots` was unconditional, but the engine's analogous assert in `model_ltm_variables` has an escape hatch: when `loop_dimension_element_tuples` returns empty (a mid-edit project whose dimensions don't yet cover a loop's declared dimensions), `partition_for_loop` falls back to the element suffixes on the loop's stocks while `build_loop_element_index` only products the resolved dims, so the two counts can transiently disagree. Make the FFI assert symmetric: fire only when both sides look genuinely arrayed (`n_slots > 1` and `pv.len() > 1`), which is the closest expressible form given `loop_dimension_element_tuples` isn't visible across the crate boundary. It still catches a real slot-count mismatch between two genuinely-arrayed views without firing on the can't-happen-in-prod singleton-collapse transient.
…ce-site IR GH #511: an A2A equation that references an arrayed dependency by its iterated dimension (`growth[Region,Age] = row_sum[Region] * c` with `row_sum` over `Region`) was misclassified as `DynamicIndex` because `resolve_literal_index` rejects a dimension name. Add `classify_iterated_dim_shape` to the #520 reference-site IR walker: a subscript whose indices are exactly the target equation's iterated dimensions, in the position matching the source's declared dimension order (each index either named the same as the source's i-th dim or a dimension that maps to it -- the AC3.5 mapped-dimension case), is a same-element-on-shared-dims reference (`RefShape::Bare`), which `emit_edges_for_reference` already projects via `expand_same_element` (`row_sum[d1] -> growth[d1,*]`, not the full cross-product). A partially-iterated subscript stays with its existing classification (Phase 4 handles sliced reducers). The mapped case needs a `DimensionsContext` built from `project_datamodel_dims`, so the IR is recomputed when a dimension's mappings change. Bundle the read-only walk context (`variables`, the target's iterated dim names, the `DimensionsContext`) into a `WalkCtx` struct so the recursive walker's signature stays short.
…als (#511) An A2A target that references an arrayed dependency by its iterated dimension (`row_val[Region] = level[Region] * c`, both over `Region`) now produces a working link score: the #511 reference-site classifier (Phase 1) marks the subscript `Bare`, and the partial-equation builder normalizes `level[Region]` to a bare `Var(level)` in the LTM partial's Expr0 -- so it is either held live (`live_shape == Bare`) or wrapped as `PREVIOUS(Var(level))` (a `Var` arg, which codegen accepts) instead of the `PREVIOUS(Subscript(...))` the pre-fix code produced (the "PREVIOUS requires a variable reference after helper rewriting" codegen error). The model equation itself is untouched -- only the LTM partial's Expr0 is normalized -- so simulation still evaluates `level[r]` correctly: in each slot, the subscript and a bare reference inside an apply-to-all-over- the-target's-dims equation pick the same element. Thread an `IteratedDimCtx` (the live source's declared dim names + the target equation's iterated dims + an optional `DimensionsContext` for the AC3.5 mapped-dimension case) through `build_partial_equation_shaped` -> `wrap_non_matching_in_previous` -> `classify_expr0_subscript_shape`, and into `generate_auxiliary_to_auxiliary_equation` / `generate_stock_to_flow_equation` / `build_arrayed_link_score_equation` (each derives `target_iterated_dims` from `to_var.ast()`). A non-live dep that is itself subscripted by iterated dims (`pop[Region,Age]` in a `(row_sum, growth)` partial) is collapsed too -- conservatively, since the dep's declared dims aren't known in the partial builder -- to avoid the same codegen assertion. For a `Bare` source ref the guard form's source side is `quote_ident(from)` (no spurious `SUM(...)`).
…ts; diagnostic for unscoreable edges (#510) A disjoint-dim arrayed -> arrayed edge whose target is a per-element- equation (`Ast::Arrayed`) variable referencing the source by literal element subscripts of a disjoint dimension (`target[D1,D2]` whose `<element subscript>` equations reference `source[m]`, `m ∈ D3`, D3 disjoint from D1/D2) used to degenerate to a silent scalarized stand-in: `link_score_dimensions` returned `[]` for the edge, so `retarget_ltm_equation_dims` collapsed the per-element `Equation::Arrayed` partial `build_arrayed_link_score_equation` had built to the first slot's text alone. Add `try_disjoint_dim_arrayed_link_scores` (called from `emit_link_scores_for_edge` before the `emit_per_shape_link_scores` fallback): it reuses the Phase-1 reference-site IR for `(from, to)` (each site's shape is `FixedIndex(elems)` for `source[m]`) and emits one `$⁚ltm⁚link_score⁚{from}[{m}]→{to}` per distinct referenced source element -- an `Equation::Arrayed` over the target's dims (via the salsa-cached shaped path), holding `source[m]` live in the slots that reference it and the trivial-zero guard form (`source[m]` frozen at `PREVIOUS`) elsewhere. If the target references the source via a non-literal index (a `DynamicIndex` site -- genuinely unscoreable), accumulate a `CompilationDiagnostic` `Warning` naming the edge and emit no link-score variable (and don't fall through to the scalarizing path). Also fix a phantom-dependency bug `build_arrayed_link_score_equation` exposed once it reached the disjoint-dim case: a subscript `source[m]` where `m` is an element of *`source`'s* dimension (disjoint from the target's dims) leaked `m` into the per-slot dep set as a phantom variable, which then got PREVIOUS-wrapped inside the subscript (`source[PREVIOUS(m)]`); strip the source's dimension/element names from the dep set so the partial sees only real deps.
Extend the is_other_dep_iterated_dim_subscript rustdoc to call out the transposed sub-case (arr[D2,D1] inside an A2A-over-D1xD2 equation) as a known non-natural-position imprecision alongside the already-documented mapped-but-position-mismatched case -- the conservative collapse to PREVIOUS(dep) is intentional (never a codegen error, sign preserved) but magnitude-imprecise there. Drop the redundant lsv.name reassignment in try_disjoint_dim_arrayed_link_scores: the salsa-cached shaped path already sets name = link_score_var_name(from, to, &shape). Make the AC3.2 hand-calc test fail loudly if the loop-score equation ever grows a non-product factor: assert the loop-score equation references all three expected link-score var names, and validate every ' * '-split term parses as a link-score var name (clear panic otherwise), with a comment documenting the loop-score-is-a-product-of-link-scores assumption the split relies on.
Hoist *sliced* reducer subexpressions into aggregate nodes, not just
whole-extent ones. `AggNode` gains a `read_slice: Vec<AxisRead>` where
`AxisRead in {Pinned(elem), Iterated(dim), Reduced}` -- one entry per
source axis, recording which rows of the arrayed source the reducer
actually reads. `compute_read_slice` decides hoistability: `SUM(pop[*])`
=> all-`Reduced` (whole extent); `SUM(pop[NYC,*])` => `[Pinned(nyc),
Reduced]`; `SUM(matrix[D1,*])` over an apply-to-all-`D1` body =>
`[Iterated(d1), Reduced]` and an arrayed agg over `D1`
(`result_dims = [D1]`). The one carve-out: a reducer over a dynamic index
(`SUM(pop[idx,*])`, `idx` non-literal) is not statically describable
(`compute_read_slice` returns `None`), so it is not hoisted and its
reference stays on the conservative path. `reducer_is_full_reduce` /
`expr_is_full_extent` are subsumed by the read-slice computation.
`model_element_causal_edges` (via the #520 IR's `ThroughAgg` routing)
now routes only the read-slice rows through the agg via
`emit_agg_routed_edges`: `source[<pinned>,<iterated>,<reduced->all>] ->
agg[<iterated>]` per `Iterated`-axis combination, then
`agg[<iterated>] -> to[e]` with the agg's `result_dims` driving the
diagonal/broadcast fan-out (the same projection `Bare` uses). A
whole-extent reducer degenerates to the prior "every source element ->
scalar agg -> every target element". No `source[d] -> to[e]` direct edge
is emitted for a hoisted reducer.
`emit_source_to_agg_link_scores` emits a per-element reducer link score
only for the rows the slice reads (and `...->{agg}[<slot>]` when the agg
is arrayed -- the partial-reduce shape), so the unread rows get no
garbage link score; `emit_agg_to_target_link_scores` subscripts the agg
side of the link-score name when the agg is arrayed over its
`result_dims`; the agg-aux emission's existing `Equation::ApplyToAll` arm
now carries a non-empty `result_dims` for an arrayed synthetic agg.
The variable-backed-agg path (`total = SUM(pop[*])`,
`row_sum[D1] = SUM(matrix[D1,*])`) records the new `read_slice`/
`result_dims` too, but its element graph stays the conservative
cross-product (a variable-backed agg is a real variable node; its edges
go through the normal reference walker).
…dcard cross-product (#514) Reclassify the one not-hoistable reducer carve-out -- a reducer over a dynamic index, `SUM(pop[idx,*])` (`idx` non-literal) -- in `model_ltm_reference_sites`: a `Direct` `Wildcard` reference that is `in_reducer` but was not hoisted into any synthetic agg and whose target is not itself a variable-backed agg of that source becomes `DynamicIndex` instead. After this, the `Wildcard` *shape* on a `Direct` site only ever means "a whole-RHS variable-backed reducer's argument" (`total = SUM(population[*])`, `row_sum[D1] = SUM(matrix[D1,*])` -- where the edge is the agg edge and the conservative reduction/cross-product into the real variable node is the right semantics) or a rare non-reducer whole-array reference; a sliced inline reducer that *can't* be hoisted takes the `DynamicIndex` conservative path, and `emit_edges_for_reference` never produces a `Wildcard`-cross-product element edge or link score for a reducer reference that could otherwise have been routed through an aggregate node.
…e; mapped slice carve-out (#514) The Phase 4 sliced-reducer hoisting (#514) left several gaps that code review surfaced: - An *arrayed* synthetic aggregate's link/loop scores were silently zero. The `agg→target` link-score equation now carries the projected `[<slot>]` subscript on both the agg reference and its Δsource denominator (`generate_scalar_to_element_equation` gained a `source_ref_override`), and the element-level subscripted-link/loop builders force any circuit through a synthetic agg onto the cross-element per-circuit path so the agg's per-slot link scores are actually referenced. The diagonal case (the agg's result dims equal the target's iterated dims) is now exact; the strict-prefix broadcast case still over-subscribes the agg -- tracked as GH #528. - A *scalar* feeder of a hoisted reducer (`scale` in `growth[D1] = SUM(matrix[D1,*] * scale)`) produced a malformed `scale[]` element-graph node. `emit_agg_routed_edges` now special-cases an empty `from_dims` -- emit `scale → agg[<each result-dim combo>]` (or the bare `scale → agg` when the agg is scalar) -- and derives the agg's result-axis dimensions from `AggNode::result_dims` resolved against the `from`/`to` dims rather than `read_slice ∩ from_dims`. - A sliced reducer whose iterated index only lines up with the source's row axis via a dimension mapping (`SUM(matrix[State,*])` over `matrix[Region,D2]`, `State→Region`) is no longer hoisted: `compute_read_slice` returns `None` for the remapped-axis case because the `Iterated`-driven slice/link-score/element-graph machinery assumes the agg result axis and the source row axis are literally the same dimension. Honoring mappings here is tracked tech debt. (`classify_iterated_dim_shape`'s own mapped branch -- a whole-equation-iterated subscript, not a sliced reducer argument -- is a separate path and is unaffected.) Removing the mapping case left `compute_read_slice`'s `DimensionsContext` plumbing dead, so it is gone. Adds an end-to-end simulation test for an arrayed-synthetic-agg loop (diagonal fixture), element-graph and `ltm_agg` tests for the scalar feeder and the mapped/multi-source/mixed-slice cases, and an IR test pinning the dynamic-index reducer site as `Direct`/`DynamicIndex`.
…gnostic (#515) `recover_cross_agg_loops` reconstructs the cross-element-through-aggregate loops Johnson can't enumerate directly (they visit the agg node twice or more) by stitching disjoint "petals" together. The pre-#515 code hard- dropped any agg with >8 petals (`petals.len() > MAX_AGG_PETALS -> continue`), so a reducer in a feedback loop over a >8-element dimension got *zero* cross-element loops. Replace the hard drop with a deterministic petal priority (fewest internal nodes first, then a stable joined-`nodes` tiebreaker) plus an overall loop-count budget (`MAX_CROSS_AGG_LOOPS = 256`, threaded as `agg_loop_budget` through `build_loops_from_tiered` / `build_element_level_loops` so it has no global state in production and is `#[cfg(test)]`-overridable via `AggLoopBudgetGuard` -- per docs/dev/rust.md#test-time-budgets, the tests use a tiny budget + a 5-element fixture rather than a fixture large enough to trip a real gate). `MAX_AGG_PETALS` survives as a soft per-agg petal cap bounding the `2^k` subset enumeration. When the budget or the petal cap clips, recovery stops, `LtmVariablesResult.agg_recovery_truncated` is set (the robust signal -- #466's diagnostic-reachability limitation is out of scope), and `model_ltm_variables` accumulates a `Warning` naming the budget and the affected aggregate node(s), mirroring the auto-flip-to-discovery gate. The deterministic petal order is what makes the *truncated* loop set reproducible rather than HashMap-iteration-order dependent. The subset masks are walked smallest-cardinality-first so the few-petal (likely most interesting) loops survive a tight budget. This commit keeps one cyclic ordering per disjoint subset (chosen-index order, which equals the pre-fix per-subset output for the m=2 case); the remaining distinct cyclic orderings are added in the follow-up. Adding `agg_recovery_truncated: bool` to `LtmVariablesResult` needed `db.rs` (at the 6000-line cap) to trim a few stale-verbose comments to stay under it.
Follow-up to the budgeted cross-agg loop recovery: where the pre-#515 code (and the previous commit) emitted *one* loop per disjoint petal subset, `recover_cross_agg_loops` now emits each subset's distinct *cyclic orderings* -- `1` for a 2-petal subset, `(m-1)!/2` for an m-petal subset (m>=3), with mirror reversals skipped -- via a small hand-rolled `cyclic_orderings(n)` (pin index 0 to kill rotations; generate the tail's permutations with Heap's algorithm; keep a permutation iff it is lexicographically <= its reverse, so one of each mirror pair survives). The Heap's-algorithm order is deterministic, which `assign_loop_ids`' stable sort relies on for stable, distinct loop ids. Each cyclic ordering of one subset is a distinct directed cycle (per #308, loop identity is the directed-edge sequence), so it gets its own `Loop` and loop_score var -- but all of them traverse the same edge *multiset* (every petal always contributes the same `A -> first_internal -> ... -> last_internal -> A` edges, the sequence being cyclic), so their loop_score *values* coincide (the score is the commutative product over the loop's edges). The loop budget from the previous commit stops recovery long before it reaches a subset large enough for `(m-1)!/2` to be a concern. Tests: `cyclic_orderings` unit test (n in {0,1,2,3,4} exact vectors plus the (n-1)!/2 count and mirror-distinctness for n in 3..6); a k=4 fixture asserting the full 4-petal subset's 3 distinct cyclic orderings are recovered (distinct ids, distinct edge sequences, same factor set) alongside the 6+4 lower-cardinality subsets; an end-to-end k=4 fixture (heterogeneous stock initials so loop scores don't degenerate under symmetry) confirming the 3 orderings' simulated loop_score series are equal step-by-step and each loop score equals the product of its 16 link scores; and a subscripted-agg ($:ltm:agg:0[d1]) recovery test for the Phase 4 interaction. The golden-data files are byte-unchanged (no existing fixture has >=3 disjoint petals through any synthetic agg). Also bumps the simlin-engine CLAUDE.md notes.
`recover_cross_agg_loops` now returns the (sorted, deduped) names of the aggregate nodes whose petal enumeration was clipped instead of a bare `bool`, threaded up through `build_element_level_loops` and `build_loops_from_tiered`. `model_ltm_variables` surfaces those names in the truncation `Warning` rather than listing every synthetic agg in the model as a candidate set, so the message points the author at the affected reducers. An agg is reported as truncated when the soft per-agg petal cap drops >= 1 of its petals or when the global loop-count budget fires while enumerating it or before it would have been reached -- a conservative over-report (an agg whose subsets would have collapsed to zero loops is still flagged if the budget never reached it), in the same safe direction as the petal-cap flag. Also binds `cross_agg_loop_budget()` once in `model_ltm_variables` (passed to the loop builder and reported in the `Warning`) rather than reading the thread-local twice, and adds a comment at the petal-cap clip site documenting why dropping any petal flags truncation even when the dropped petals could not have contributed a disjoint-pair loop.
…ime (#483) End-to-end coverage for #483's analytic STDDEV ceteris-paribus partial: - build_stddev_feedback_model: Region={a,b,c}, s[Region] stock (inits 10/20/30) <- a per-element-equation flow update[a]=total*c, update[b]=total*c*0.5, update[c]=total*c*2, total=STDDEV(s[*]). The differing multipliers make the elements drift apart at different rates so STDDEV genuinely keeps changing. test_stddev_link_score_matches_hand_calc runs the VM, reads the s[d]->total link-score series, and hand-computes the analytic partial sqrt((sum_i (s'_i - m)^2)/N) (with s[d] live, the others frozen at PREVIOUS, divisor N to match the engine's population-variance STDDEV) wrapped in the standard link-score formula -- matching within 1e-6 at every step. It also asserts the recorded value is not the degenerate-1 magnitude the pre-#483 delta-ratio produced (partial_eq == target => ABS(SAFEDIV(dtotal, dtotal, 0)) == 1), so the test fails on the pre-fix code (verified: "recorded link score 1 != hand calc -0.748..." at step 1, with total changing 8.16 -> 12.13). - build_stddev_invariant_model: same stock but a constant uniform flow update[Region]=k, so every element shifts by the same amount each step, STDDEV is bit-for-bit constant, and the dtarget=0 guard zeros every s[d]->total link score. test_stddev_invariant_regime_link_scores_zero pins AC6.2 (compiled in discovery mode -- the constant flow has no feedback loop, but discovery scores every causal edge). This passes with both the old and new code, so it pins the AC but does not distinguish the fix; the distinguishing test is the hand-calc one above. Drive-by: corrected the stale "(size-1) divisor" / "size - 1 overflow" comments on the ArrayStddev empty-view guard test in vm.rs -- the opcode uses a population-variance divisor `size`, not `size - 1`, and the size==0 guard exists to make `variance_sum / 0.0 == NaN` explicit. No golden-data changes: test/logistic_growth_ltm/ltm_results.tsv is a scalar model (no STDDEV) and is byte-unchanged; no existing simulate_ltm.rs hand-calc constant changed (no prior fixture had an STDDEV-in-a-feedback loop -- test_cross_dim_stddev_expansion's build_arrayed_to_scalar_model is feed-forward only, so its assertions don't depend on the partial).
…483 Phase 6 added the analytic STDDEV ceteris-paribus partial in generate_nonlinear_partial, but generate_element_to_reduced_equation's rustdoc still claimed STDDEV (and RANK, and nested reducers) fall back to the delta-ratio form -- which became wrong for STDDEV the moment that arm landed. generate_element_to_reduced_equation delegates to the same build_element_reducer_link_score as generate_element_to_scalar_equation, so a partial-reduce target like agg[D1] = STDDEV(matrix[D1,*]) gets the analytic per-element partial over the co-reduced slice -- consistent with the scalar case, not a fallback. Reword the rustdoc to spell out the per-reducer treatment (SUM/MEAN algebraic shortcut, MIN/MAX unroll, STDDEV analytic partial, RANK + nested delta-ratio). Also de-stale the nearby comment in test_cross_dim_compound_nonlinear, which still called STDDEV a fallback. Rustdoc/comment only -- no behavior change.
Adds direct test coverage for branches the Phase 7 work introduced but left untested: the merged LOOKUP / LOOKUP_FORWARD / LOOKUP_BACKWARD polarity arm (a datamodel fixture exercising lookup_forward and lookup_backward), and lookup_table_polarity's defensive subscript branches -- a Const integer-literal FixedIndex (in-range picks the right element's table, out-of-range bails to Unknown), a multi-dimensional GF source (the conservative bail), and a Wildcard subscript -- via a focused unit test that hand-builds the Expr2 shapes the parser does not emit for a well-formed model but the arm must still classify totally. Also drops the now-stale #[allow(unused)] on Dimension::name() (used by ltm/polarity.rs and ast/expr2.rs) and points the graphical-function monotonicity epsilon comment at GH #536 for the non-uniform-x-spacing follow-up.
Phases 1 and 4 already removed the obviated predicates/arms/helpers (`builtin_is_array_reducer`, the inline `route_through_agg`/`routed_aggs` in `model_element_causal_edges`, `enumerate_shapes`, `expr_is_full_extent` /`reducer_is_full_reduce`, the `collect_reference_shapes` re-export), and the tests pinned to old behavior were rewritten in place (`slice_reducer_subexpression_is_hoisted`, `element_graph_sliced_reducer_reads_only_pinned_row`); `cargo clippy --workspace --all-targets --all-features -- -D warnings` is clean. This sweep is the residual doc/comment cleanup the symbol moves and the #514 hoisting left behind: references to the deleted `expr_is_full_extent` become `compute_read_slice` (with the matching `Wildcard`/`StarRange` ⇒ `AxisRead::Reduced` phrasing); the `db_analysis::resolve_literal_index` module path in `ltm_augment.rs` becomes `db_ltm_ir::resolve_literal_index` after the AST-walker helpers moved to `db_ltm_ir.rs`; and the `RefShape` / `link_score_var_name` doc comments stop calling `SUM(pop[NYC, *])` a "non-hoisted slice" -- post-#514 every statically-describable inlined reducer (whole-extent or sliced) is hoisted, so the conservative-path references are the dynamic-index reducer carve-out, a mapped-dimension sliced reducer, a bare dynamic index, and a whole-RHS variable-backed reducer's argument.
Bring the LTM documentation current with Phases 1-7 of the arrays
hardening plan:
- `src/simlin-engine/CLAUDE.md`: extend the "Last updated" note with the
Phase 6/7 work (analytic STDDEV partial, RANK's documented delta-ratio,
per-element graphical-function static polarity, the y-range-relative
GF-monotonicity epsilon); update the `polarity.rs` and `ltm_augment.rs`
bullets to match.
- `docs/design/ltm--loops-that-matter.md`: in `## Array Support`, add a
"reference-site classification IR" subsection (`model_ltm_reference_sites`
-- `ClassifiedSite` = shape + per-element target + routing -- as the
single source `model_element_causal_edges` / `model_edge_shapes` /
`model_ltm_variables` all read); rewrite the `RefShape` truth table to
drop the conservative-slice cross-product rows; describe `AggNode.read_slice`
(`AxisRead ∈ {Pinned, Iterated, Reduced}`) + `result_dims` + sliced-reducer
hoisting, the consolidated `reducer_kind`/`ReducerKind` table,
iterated-dimension and mapped-dimension references, disjoint-dim
arrayed→arrayed per-source-element link scores + the unscoreable-edge
`Warning`, the analytic STDDEV partial / RANK delta-ratio, element-level
A2A `Loop::stocks` + per-slot `loop_partitions` + per-(partition, slot)
normalization, the budgeted cyclic-ordering cross-agg loop recovery +
`agg_recovery_truncated`; add a "Residual array carve-outs" entry under
`## Current Limitations`; add per-element-GF and y-range-epsilon bullets
under `### Static Polarity`.
- `docs/reference/ltm--loops-that-matter.md`: add a new user-facing section
"15. Arrayed Variables and Aggregate Nodes" (element-level loops, the
element causal graph, array reducers as implicit aggregate nodes trimmed
from reported loops, sliced/iterated/mapped-dimension handling, per-element
vs cross-element loops), renumbering the subsequent sections; add the
residual array limitations (dynamic-index reducer, RANK approximation,
bounded cross-agg-loop recovery) under "16. Weaknesses and Limitations".
- The two prior LTM design-plan postscripts: a "Re-measurement after the
arrays-hardening work (2026-05-13)" block on the per-ref-elem-graph plan
(the checked-in fixtures are structurally unchanged -- the cluster's
element-graph changes fire on inlined sliced/iterated-dim reducers, which
`src/db_*_tests.rs` covers rather than golden files), and a "Postscript"
on the cross-element-agg plan noting which deferred carve-outs (#514,
#487, #511, #510, #483) the cluster closed.
Mark the LTM arrays-hardening cluster's tech-debt items resolved: - #20 (FixedIndex N-squared edges): the conservative-slice carve-out is closed by #514's `AggNode.read_slice`; only the bare dynamic index (`SUM(pop[idx, *])`, `arr[i+1]`) stays full-cross-product -- a deliberate narrow carve-out (mapped-dimension sliced reducers tracked as GH #534). Also fix the stale `collect_reference_sites` reference (the AST walker moved to `db_ltm_ir.rs` as `collect_all_reference_sites`). - #21 (polarity reducer blind spots): the GF-monotonicity half is resolved via #492's y-range-relative epsilon; Phase 7 also added per-element GF static polarity (#502). The residual `dy`-vs-slope nuance is GH #536; the agg-hop-polarity half is #516. - #27 (STDDEV/RANK fallback): STDDEV RESOLVED via #483's analytic population-variance partial; RANK keeps the delta-ratio by design (an order statistic, unreachable as a real reducer RHS, pinned by `test_generate_rank_keeps_delta_ratio`). Drop the stale `ltm_augment.rs:1374-1381` line ref. - #35 (A2A `partition = None`): RESOLVED via #487 -- element-level `Loop::stocks`, per-slot `loop_partitions: HashMap<String, Vec<Option<usize>>>`, per-(partition, slot) normalization. (There is no #520-related tech-debt entry -- #520 is tracked only in epic #488's checklist.)
The per-element graphical-function link-polarity work (#502) was described in three places as walking `Table::elements()`, but no such method exists on `crate::variable::Table`. The actual mechanism reads the per-element `tables: Vec<Table>` field on `Variable::Var` (`lookup_table_polarity`) and folds the per-table polarities into one link polarity (`fold_per_element_table_polarity`). Reword the design doc and the two engine CLAUDE.md spots to name the real field and helpers so a reader grepping for the mechanism actually finds it. Doc-only; no code change.
The LTM arrays-hardening cluster added src/simlin-engine/src/db_ltm_ir.rs as a new top-level salsa module (the model_ltm_reference_sites classification IR). The architecture overview enumerates the salsa modules by name, so add it there to keep that list accurate. The per-module detail already lives in src/simlin-engine/CLAUDE.md, which was updated in the cluster's Phase 8.
The BuiltinFn-generic reducer_is_monotone<E> was added for API symmetry alongside reducer_kind, but its only consumer is the reducer_kind classification unit test -- the production monotone consumer (recover_agg_hop_polarities) has the agg's printed equation text and uses the str-keyed agg_reducer_is_monotone. Shipping #[allow(dead_code)] on a non-test production symbol violates the "no test-only methods in production" rule and the "simple/testable over preserving an interface" hard rule, and the "natural future caller" (a static-polarity pass) never materialized in this cluster. Move the helper into mod tests next to the test that uses it; the str-keyed reducer_name_is_monotone keeps its production callers and stays at module scope.
…normalization AC2.1 (the per-slot loop_partitions fix, GH #487) only had end-to-end coverage through the libsimlin FFI crate (test_two_a2a_subsystems_per_slot_rel_score_round_trips); test-requirements.md anticipated an engine-level guard in simulate_ltm.rs. Add test_disconnected_a2a_loops_normalize_per_partition: a two-subsystem model (a reinforcing pop loop over Region={a,b,c}, an independent reinforcing widgets loop over Product={x,y}, no cross-coupling) compiled with LTM and run through the engine's public API. It asserts (1) the two subsystems' loops occupy five distinct loop_partitions slots -- not one pooled bucket, which is what the pre-fix HashMap<String, Option<usize>> shape produced -- and (2) each loop's per-element relative score is exactly +1.0 (alone in its single-stock partition), where the pre-fix pooled behavior would yield ~0.5; the assertions and a doc comment make it clear the test fails on the old code.
The test-analyst pass over the 8-phase LTM arrays-hardening cluster (epic #488) confirmed all 38 acceptance criteria have passing automated tests. This records the human verification plan that complements the automated suite: documentation prose review, GitHub issue-tracking checks, and a couple of end-to-end smoke checks through real model files (disjoint A2A subsystems normalizing per partition; the analytic STDDEV per-element link-score partial). LTM arrays are engine-internal with no dedicated UI surface, so the human plan is deliberately small.
Code reviewReviewed the engine, libsimlin, and LTM changes across the eight phases. Spot-checked the higher-risk areas: No blocking issues found. The implementation is internally consistent (Expr2 vs Expr0 classifiers kept in sync, row-major slot ordering consistent across Overall correctness: correct. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 66f32f23c7
ℹ️ 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".
| .filter_map(|&(i, rs)| offsets[i].map(|off| row[off + rs].abs())) | ||
| .sum(); |
There was a problem hiding this comment.
Guard slot reads with actual loop_score width
compute_rel_loop_scores_per_element now derives slot membership from loop_partitions[id].len() and then reads row[off + rs] directly. If partition vectors and emitted loop_score slot counts diverge (the commit itself documents this transient mismatch path in the new debug-assert comments around per-slot partition snapshots), rs can exceed the loop variable’s real width, which can panic or read into the next variable’s columns while computing layout LTM metadata. Please gate reads with the loop’s actual slot count (e.g., effective_slot/n_slots_by_loop) before indexing.
Useful? React with 👍 / 👎.
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## main #537 +/- ##
==========================================
+ Coverage 82.44% 82.72% +0.27%
==========================================
Files 242 244 +2
Lines 63290 65071 +1781
==========================================
+ Hits 52178 53828 +1650
- Misses 11112 11243 +131 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
Summary
Hardens the Loops That Matter (LTM) static causal-graph analysis and post-simulation loop/link scoring for arrayed variables. Eight phases, each independently code-reviewed to zero issues, plus a final whole-plan review and a test-coverage pass (38/38 acceptance criteria covered by automated tests).
The structural change is a single, salsa-tracked reference-site classification IR (
db_ltm_ir.rs):model_ltm_reference_sitesproduces oneClassifiedSite { shape, target_element, routing }per variable reference, where routing isDirectorThroughAgg. The element causal graph (db_analysis.rs), edge shapes, and link/loop-score emission (db_ltm.rs) all read this IR instead of independently re-walking and re-classifying ASTs -- so a reference is classified in exactly one place.Phase-by-phase:
reducer_kind/ReducerKindtable inltm_agg.rs(retiresbuiltin_is_array_reducerand friends).Loop::stocks;LtmVariablesResult.loop_partitionswidens to one partition slot per array element;libsimlin'sSimState.loop_partitionsandsimlin_analyze_get_relative_loop_scorekey the relative-score denominator on the queried slot's partition (simlin.hbyte-unchanged).row_sum[D1]insidegrowth[D1,D2]) classify asBareand normalize to bare source-refs in LTM partials; per-source-element link scores for disjoint-dim arrayed-to-arrayed targets; aWarningdiagnostic for genuinely unscoreable disjoint-dim edges.SUM(pop[NYC,*]),SUM(matrix[D1,*])) hoist into aggregate nodes carrying aread_slice: Vec<AxisRead>(Pinned/Iterated/Reduced) andresult_dims; the old Wildcard cross-product expansion is retired in favor of read-slice-driven edge emission.MAX_CROSS_AGG_LOOPS = 256,MAX_AGG_PETALS = 8) with anagg_recovery_truncatedflag and a diagnostic naming the truncated aggregates;cyclic_orderingsenumerates the distinct cyclic orderings of a petal subset (Heap's algorithm,(m-1)!/2form >= 3, mirror reversals skipped, index 0 pinned).sqrt(...)form, divisor N); RANK keeps its documented delta-ratio approximation (an order statistic, unreachable as a real reducer RHS), now pinned by a test with an in-code justification.lookup_table_polarity/fold_per_element_table_polarityover the per-elementtableslist onVariable::Var; theAst::Arrayedadopt-first-concrete fold; multi-dim staysUnknown); y-range-relative epsilon(1e-6 * (y_max - y_min)).max(1e-12)for graphical-function monotonicity; the polarity Lookup arm covers all threeLookup/LookupForward/LookupBackwardbuiltins.docs/design/ltm--loops-that-matter.md,docs/reference/ltm--loops-that-matter.md,src/simlin-engine/CLAUDE.md,docs/architecture.md, two design-plan postscripts, anddocs/tech-debt.md(identify + be able to edit variables with tables #20/fix new user creation flow #21/problems with variable names with / in them #27/unit checking #35) updated; the nine implementing issues closed; epic epic: Loops that Matter (LTM) -- open work #488's checklist ticked.Implementing issues (closed by commits on this branch): #520, #487, #511, #510, #514, #515, #483, #502, #492. Advances epic #488 (kept open for the remaining follow-ups). Residual array carve-outs are documented and tracked separately: #525 (PREVIOUS(SUM()) codegen for partial-iterated subscripts), #526, #527, #528, #533, #534 (mapped sliced reducers stay conservative), #536 (non-uniform-x graphical-function monotonicity nuance).
db.rsnow sits at the 6000-line lint cap -- extract a sibling module before the next change to it (tracked as #518).No checked-in golden fixture under
test/changed; behavior changes are covered by unit tests insrc/simlin-engine/src/db_*_tests.rsand integration tests insrc/simlin-engine/tests/simulate_ltm.rs/src/libsimlin/tests/analysis.rs.Test plan
cargo test --workspace-- green (~20s, well under the 3-minute cap)cargo test -p simlin-engine --features file_io --test simulate_ltm-- 77 passedcargo test -p simlin --test analysis-- libsimlin FFI per-slot loop-score round-trips greencargo clippy --all-targets --all-features -- -D warnings-- cleancargo fmt --check-- cleanpython3 scripts/check-docs.py-- doc links resolvegit diff main..HEAD -- test/-- empty (no golden-fixture changes)simlin.h-- byte-unchangeddocs/test-plans/2026-05-11-ltm-arrays-hardening.md(documentation prose review; GitHub issue-tracking check; end-to-end arrayed-LTM and STDDEV-reducer model-file round-trips)