Repository navigation
ltm: scoring-correctness and visibility batch from epic #488 - #775
Conversation
recover_agg_hop_polarities compared the bare synthetic agg name against
the link's FULL ident, but an arrayed agg's element-graph hops carry a
slot subscript ($⁚ltm⁚agg⁚0[a]), so neither endpoint match ever fired:
the hops stayed Unknown and every scored/pinned loop through an arrayed
agg classified Undetermined (u{n}) even when the hop polarity was
statically derivable. The non-agg side of the same comparisons already
stripped subscripts; this makes the agg side symmetric.
The strip is safe for agg identity: strip_subscript only removes the
trailing [...] element subscript, and the agg index lives in the name
before the bracket (agg⁚0[a] strips to agg⁚0, never aliasing agg⁚1) --
pinned by the new opposing-sign two-arrayed-agg probe, where an aliased
match would read the wrong agg body and swap r/b. The hop analyses are
unchanged and variable-level on both sides (the same treatment bare
names already got).
What flips: per-slot loops through arrayed aggs on the scored and
pinned surfaces now come back r/b instead of u (and re-sort under
assign_loop_ids accordingly), which also closes the scored-vs-detected
polarity disagreement for arrayed-agg loops -- the detected surface's
spliced agg hops are bare-named and were already recovered. No existing
test pinned the u-prefix for these loops, so the full suite is
unchanged apart from the new coverage.
The SUM/MEAN linear shortcut scored every source row of a reducer as if the body were the bare source element (an implicit d_agg/d_source[e] of 1), ignoring any coefficient the body applies to that source. For a hoisted multi-source reducer like grow = 1 + SUM(pop[*] * (1 - weight[*])) the true partial d_agg/d_weight[e] = -pop[e] is negative, so the weight[e]->agg runtime series was wrong-signed (and wrong in magnitude for pop), and runtime loop-polarity reclassification rubber-stamped the wrong static label instead of correcting it (GH 744). classify_reducer's is_bare only guarded arithmetic AROUND the reducer, never inside its argument, and the agg-half emitters additionally hardcoded is_bare = true. classify_reducer now also returns the reducer argument's canonical text, and the Linear arm builds the changed-first row partial from that BODY: pin every arrayed reference to the row (wildcards, iterated dims including the GH 534 mapped case, literal elements -- each validated positionally, bailing to the documented delta-ratio fallback when a correspondence is unprovable or the body nests another reducer), then emit PREVIOUS(target) + (body live-at-row - body all-frozen), divided by N for MEAN. The fully-frozen co-reduced rows cancel against PREVIOUS(target), so the partial needs only scalar/fixed-element PREVIOUS reads and always compiles (no lagged whole-array read). A bare body collapses to the legacy shortcut byte-identically, and the scalar feeder's changed-last equation is untouched, preserving the GH 737 bilinear additivity (per-row changed-first numerators plus the feeder's changed-last numerator sum exactly to delta-agg) -- all pinned by tests. The variable-backed whole-RHS reducer path (try_cross_dimensional_link_scores) shared the defect and gets the same body context. generate_nonlinear_partial (MIN/MAX/STDDEV) has the sibling limitation for non-bare bodies; documented on the function and tracked separately.
The GH 744 body-aware row partial's cancellation invariant -- every fully-frozen co-reduced row contributes exactly its share of PREVIOUS(target) -- silently failed for a FIXED-literal reference to the live source inside the reducer body: in SUM(pop[*] * pop[north]) the north row pinned to PREVIOUS(tp) + (pop[north]^2 - PREVIOUS(pop[north])^2), but the OTHER rows' bodies (pop[i] * pop[north]) also reference the live element, so they do not cancel and the partial drops their cross-terms (measured 0.5 vs the true changed-first 0.7497; sign-flippable for mixed-sign sources). The south row meanwhile fell back to delta-ratio -- inconsistent treatment of one defect. pin_body_index now reports whether each index MOVES with the row (wildcard/StarRange and iterated/mapped-dim indices do; literal-element and ordinal indices are fixed), and pin_body_to_row rejects a live-source reference with no moving index, sending every row of the shape to the documented delta-ratio fallback consistently. References with at least one moving axis (the pinned-slice shape SUM(pop[nyc,*])) instantiate to a different element in each row, so cancellation holds and they keep the exact body partial. The invariant rustdoc now states the exclusion and why. Also from review: the ReducerBodyCtx doc now attributes positional row pinning to the engine's positional subscript resolution (the slice-agreement gate compares axis shapes, never dimension names -- same-size differently-named co-sources are hoisted and read slot-aligned elements); the freeze_pinned_body doc states the model/non-model index boundary precisely instead of claiming all indices are literal elements.
generate_nonlinear_partial substituted the BARE source elements into the MIN/MAX nested-binary and STDDEV unrolled-variance per-row partials, ignoring arithmetic inside the reducer argument: MIN(pop[*] * scale) compared raw pop terms against a scaled aggregate, yielding garbage link scores (~74 on the regression fixture where the true changed-first value is ~0.003) -- the nonlinear sibling of the GH 744 linear-shortcut defect (GH 762). The new generate_nonlinear_body_partial reuses the GH 744 pin/freeze machinery: for agg = R(body(r)) the changed-first partial for row e is R over one term per co-reduced row -- the scored row's body pinned with the source live and other model refs frozen, every other row's body fully frozen -- anchored against PREVIOUS(agg). Unlike SUM/MEAN there is no single-row collapse (frozen terms do not cancel inside MIN/MAX/ STDDEV), so each row's frozen body is spelled out, exactly the structure the bare builder used with body(r) in place of the bare element. MIN/MAX keep the right-to-left binary nesting; STDDEV keeps the GH 483 population-variance form (divisor N, inlined mean) over the body terms. A bare body delegates to the legacy builder byte- identically (pinned against the pre-change emission), RANK keeps its body-independent delta-ratio stand-in, and an un-pinnable body (including the GH 744 fixed-literal self-reference bail) degrades to the documented delta-ratio fallback, the same contract as the linear arm. Also corrects the ec72e19 breadcrumb on is_other_dep_iterated_dim_subscript: its non-natural-position collapse limitation is a distinct, still-open issue, not the GH 762 reducer-body work.
Two follow-ups from the GH #762 adversarial review: the body-aware nonlinear partial's rustdoc now states the TIME/time-builtin/PREVIOUS anchor-identity caveat (a non-model factor stays live in frozen terms, so the PREVIOUS(agg) subtraction attributes time-drift to every row -- demonstrated and tracked as GH #763), and the other-dep iterated-subscript breadcrumb now cites GH #526, which the review confirmed covers exactly that limitation (the ec72e19 one-liner had aimed GH #762 at it by mistake).
A feedback loop through a VARIABLE-BACKED partial-reduce reducer (`inflow[D1] = SUM(matrix[D1,*])` as the whole RHS -- the variable IS the agg, no synthetic node minted) silently scored 0 (GH #752): the element graph kept the conservative Wildcard cross-product for the reducer reference, the phantom off-diagonal `matrix[a,x] -> inflow[b]` edges drove loop-score equations referencing the subscripted `"matrix[a,x]->inflow"[b]` and bare A2A `"matrix->inflow"` link-score names, but the only names try_cross_dimensional_link_scores emits for a partial reduce are the per-(row, slot) scalars `matrix[a,x]->inflow[a]` -- so every loop score through the reducer failed fragment compile (Assembly Warnings) and stubbed to 0. Direction: the issue's option (A), read-slice element edges, routed through the variable's OWN element nodes. Option (B) -- teaching the loop-score resolver the per-(row, slot) forms -- cannot work: the cross-product's off-diagonal circuits are phantoms (`SUM(matrix[a,*])` never reads row b), so no real score can represent them; the emitted per-(row, slot) set has no off-diagonal members by construction. We also did not extend the GH #534 synthetic-agg minting to this class: the literal whole-RHS case's per-(row, slot) link scores, loop-builder predicate (is_partial_reduce_edge), and resolver case already exist and match -- minting an agg would duplicate the variable's value at runtime and churn every name for no benefit (the #534 exception exists only because the name-based variable-backed path cannot remap a mapped axis). The single new gate, ltm_agg::variable_backed_partial_reduce_agg (non-synthetic agg named `to` reading `from`, at least one Iterated axis, result_dims equal to the target's dims in order), is shared by both consumers so they cannot disagree: model_element_causal_edges reroutes the Direct Wildcard site through emit_agg_routed_edges (which now skips the agg->to half for a variable-backed agg -- the slots ARE the target's element nodes, the second half would emit self-edges), and build_element_level_loops routes all-subscripted circuit groups containing such a hop to the per-circuit path (the pure-dimension A2A collapse is unrepresentable here: |D2| distinct circuits share each slot and only per-(row, slot) scalar scores exist). Whole-extent variable-backed reducers (`total = SUM(pop[*])`, the broadcast `share[R] = SUM(pop[*])`) are excluded by the gate (no Iterated axis / result_dims mismatch) and keep their exact prior path; link-score emission is untouched everywhere. Loop counts and ids change only for the affected class: the fixture's five broken loops (four phantom cross-element 6-cycles plus one uncompilable A2A loop) become four real per-(d1, d2) scalar loops r1-r4, each multiplying three emitted link scores, finite and sustained non-zero end to end. The fragment-diagnostics positive fixture relied on this bug existing (the GH #547 test-debt coupling), so the positive tests now inject a deterministic failure via a #[cfg(test)] LtmFragmentFailureGuard hook in compile_ltm_synthetic_fragment (mirroring AggLoopBudgetGuard), and the old fixture is repurposed as a zero-warning regression test plus an end-to-end finite/sustained-score test in ltm_array_agg.
Review follow-up for the GH #752 fix: the variable_backed_partial_reduce_agg gate accepted Pinned+Iterated MIXED read slices (`outf[D1] = MEAN(cube[D1,x,*])`), but try_cross_dimensional_link_scores derives each slot's co-reduced slice from the FULL source cartesian product, ignoring Pinned axes -- the MEAN divisor counts the unread rows (4 where the read slice has 2), so the per-(row, slot) scores read 0.25 where the true partial is 0.5 and the unread rows get garbage plus-or-minus-1 scores. That VALUE bug is pre-existing, but before the read-slice routing the same model surfaced 16 fragment-compile Warnings; routing the Pinned-mixed subset through the diagonal made the wrong values fully silent. Require every read-slice axis to be Iterated or Reduced: Pinned-bearing slices stay on the loud conservative regime (cross-product element edges whose loop scores reference never-emitted names and surface fragment Warnings) until the co-reduced-slice derivation respects the read slice (tracked separately; the gate's rustdoc carries the reasoning). The aligned one-axis and two-axis all-Iterated/Reduced shapes are unchanged, pinned by a new two-axis element-graph test. Also from review: assert the exact post-fix loop count (4) in the e2e test so a phantom-loop reintroduction trips it directly; document that emit_agg_routed_edges' defensive read-slice fallback would emit a dangling bare node (silently dropping the loop) for a variable-backed arrayed agg -- unreachable today but load-bearing if the gate widens; and correct the CLAUDE.md / module-doc claim that the excluded shapes' conservative edges are "the true reads" (true only for whole-extent; the broadcast/permuted shapes get a SUPERSET with no matching link scores, GH #764).
The 3ba78eb cite over-stretched GH #765 onto the StarRange-over- subdimension coarseness, which has a different root cause (the read_slice itself maps *:SubDim to Reduced over the full parent extent, so #765's downstream-derivation fix cannot tighten it). The subrange defect is now tracked as GH #766; point the breadcrumb there.
GH #743 root cause: for an un-hoisted multi-source reducer whose per-row feeder is arrayed over the iterated dim (growth[D1] = SUM(matrix[D1,*] * frac[D1]), declined by combined_read_slice's slice-disagreement carve-out), the Bare frac->growth link score's changed-first partial froze the wildcard co-source as PREVIOUS(matrix[PREVIOUS(d1), *]). PREVIOUS of an array slice has no codegen path (no LoadPrev-of-array-view): in a user equation it is a hard NotSimulatable error, but as an LTM implicit helper ($⁚$⁚ltm⁚…⁚arg0) it fails fragment-compile SILENTLY -- layout slot, no bytecode, constant 0 -- so the partial evaluated to sum(0 * frac) = 0 and the score degenerated to -PREVIOUS(growth)/|dgrowth| = -1/growth-rate: the issue's constant ~-250 (0.4%/step growth), with no diagnostic anywhere. This lands the issue's direction 2 (conservative-path fix), but with CORRECT scores rather than just a loud floor: the new shaped_guard_form_text chooser builds the changed-first guard form as before, and when that partial would embed PREVIOUS of an array slice (contains_unfreezable_previous) it falls back to the changed-last attribution -- only the live source frozen, numerator (target - frozen) -- the convention generate_scalar_feeder_to_agg_equation already established for scalar feeders of hoisted reducers. For the fixture the emitted partial is sum(matrix[d1, *] * PREVIOUS(frac)), which compiles (GH #541 bare-arrayed PREVIOUS) and scores the trivially-reinforcing loop exactly +1 per element. When BOTH conventions are unfreezable (or changed-last has no live occurrence to freeze, which would silently score 0) the chooser fails loudly: PartialEquationError gains an UnfreezablePartial kind and the existing emit_ltm_partial_equation warning path skips the variable -- never silent garbage. Direction 1 (hoisting the feeder-sub-slice combination) was assessed and deferred as a follow-up: it needs per-source read slices on AggNode plus coordinated extensions to emit_agg_routed_edges, try_cross_dimensional_link_scores' row/slot enumeration, the body-aware partial pinning, and the loop builder's fast-path-vs-per-circuit routing -- well beyond this batch and destabilizing the settled #752 and #534 paths. Composition is unchanged: hoisting logic is untouched (agreeing multi-source reducers stay hoisted byte-identically), the #752 variable_backed_partial_reduce_agg gate remains None for this class (pinned by the new e2e test's no-synthetic-agg assertion), and non-doomed partials are byte-identical (the chooser is a pure pass-through to the historical changed-first output; the corpus's pinned equation-text tests all pass unchanged). The co-source-closure sibling (loop through the wildcard-read matrix) keeps its loud warned zero-stub degradation, pinned by a characterization test.
Review follow-ups to 7012d9f. The LTM reference doc's attribution- convention note described changed-last as a single special case (the scalar feeder of a hoisted reducer); it now documents the general fallback rule that commit introduced -- changed-first by convention, changed-last whenever the changed-first partial would freeze an array slice inside PREVIOUS() (listing both shapes that hit it today), and a loud warned skip when both legs are unrenderable -- since shaped_guard_form_text's rustdoc points readers at that note as the convention documentation. The UnfreezablePartial diagnostic claimed the changed-last fallback was 'unfreezable too', but the same error is also returned when the source has no matching occurrence to freeze (the frozen equation would equal the target's own, silently scoring 0); the wording now covers both causes. The chooser's changed-first leg duplicated build_partial_equation_shaped_with_live_ref's body (other-deps filter, GH #311 loud parse failure, wrap); both now call a shared wrap_changed_first_ast helper returning the transformed AST, so the two sites cannot drift -- the chooser's changed-last leg re-parses the already-proven-parseable text instead of threading the pristine AST through, since that leg only runs on the rare doomed path. Also documents wrap_live_shaped_in_previous's index-position boundary: it never recurses into subscript indices, so an index-nested live-source occurrence stays current in the changed-last partial (unreached today).
GH #758 root cause: a DECLINED mapped sliced reducer (an inline SUM(matrix[State,*]) over an element-mapped State->Region pair, which the GH #756 positional-only gate keeps off the hoisting path) falls back to the conservative per-shape link score, and that score is broken-by-construction. The edge's only site classifies DynamicIndex, so PR #761's Bare-site gate makes link_score_dimensions return [] (the arrayed retarget is reserved for edges whose element graph is the mapped DIAGONAL; this edge's is the cross-product), and retarget_ltm_equation_dims then collapses the shaped ApplyToAll equation to a SCALAR one whose guard form references the multi-slot target (growth) bare and whose partial body references matrix[state,*] -- a fragment that can never compile. The result was a warned constant-0 link-score stub plus one cascading fragment-failure warning per loop score through the edge (17 on the probe fixture), all reading 0. No compiling-and-correct form exists for this shape: the GH #743 changed-first/changed-last chooser cannot help (its doom detector is about PREVIOUS-of-array-slice freezability, and PREVIOUS(SUM(slice)) is legitimately freezable -- the doom here is arrayed references in scalar context, which afflicts both attribution legs), and the arrayed form would be silently WRONG (off-diagonal cross-product loop links would read the diagonal partial of the wrong slot -- exactly what the #761 gate prevents). So this lands the GH #510-style loud treatment: emit_per_shape_link_scores now detects the class (both endpoints arrayed non-module, no dimension correspondence), accumulates ONE Warning naming the edge, emits NO link-score variable, and records the edge so model_ltm_variables drops enumerated loop scores traversing it (their product could only be a guaranteed-zero stub: the subscripted reference to the missing name fail-warns, an unsubscripted one silently multiplies a 0 stub-dep). A pinned loop through such an edge is skipped with a Warning naming the pin, mirroring the invalid-pin treatment. Detected loops remain visible structurally (model_detected_loops is unchanged); consumers already keep the structural classification when a loop_score series is absent. Blast radius: the gate only fires where target_dims came back empty with both endpoints arrayed -- the element-mapped (GH #756) and reverse-declared (GH #757) mapped pairs, disjoint-dim ApplyToAll-target references, and incompatible-dim dynamic-index reducers -- every one of which previously emitted the same never-compiling scalar equation. Compatible-dim conservative shapes (arr[i+1], dynamic-index reducers with partial-collapse dims, the GH #525 degenerate) keep their arrayed scores byte-identically, pinned by the existing suite and a new positional-twin regression test. The #757 characterization test is updated from pinning the warned zero-stub cascade to pinning the loud skip. Sub-model pathway scores referencing a skipped edge keep their pre-existing stub-dep zero contribution (now under the edge's single warning).
Round-2 follow-up to 5c9c2d4, unifying the pre-existing GH #510 skip with the unscoreable_edges mechanism that commit introduced. A disjoint Ast::Arrayed target referencing its source via a dynamic index already warned-and-skipped the link score, but loop scores through the edge still referenced the never-emitted source[m]->target names: the subscripted reference to a scalar stub-dep fails fragment compile, so each loop produced its own cascading Assembly warning plus a zero-stub series -- exactly the cascade 5c9c2d4 eliminated for the dim-incompatible class, surviving one function away. try_disjoint_dim_arrayed_link_scores now records the edge in unscoreable_edges at its warning site -- specifically NOT on the caller's empty-vec return, because Some(vec![]) is also reachable when every per-element shaped equation fails, which is not unscoreable-by-construction -- so model_ltm_variables drops loops through it under the (extended) single edge warning. The insert-dedup also fixes a latent double-warn: the pinned pass's emitted_edges set only tracks edges that emitted a variable, so a pin re-visiting a #510 edge re-warned before this. Also from review: the pinned-loop unscoreable skip now warns once per PIN naming the user label (a cross-element pin expands to many pin{n}-instance loops, and one warning per instance is the same cascade this treatment exists to avoid); the stale link_score_dimensions comment claiming the alternative to the arrayed retarget is "the conservative scalar stub" now describes the loud skip; and the reverse-declared characterization test is renamed (stays_scalar was the pre-#758 semantics; it now asserts the score is skipped loudly). The FixedIndex-into-disjoint-ApplyToAll-target sub-case (recoverable in principle via a per-element score with no wrong-slot hazard) stays on the loud skip, tracked separately.
model_ltm_variables' early return tested parent-level stocks only (edges_result.stocks), so a root model whose only state lives inside modules -- driver -> sub_model(with internal INTEG) -> reader -> driver, or a SMOOTH/DELAY instance -- has genuine feedback and genuine state but bailed out of the LTM pass entirely: no link scores, no loop scores, and pinned loops were never validated (not even the invalid-pin warning fired). The GH #673 integration fixture needed a disjoint bystander stock purely to sidestep this; that workaround is removed and the fixture is the regression handle. The new gate bails only for genuinely STATELESS models: no parent-level stocks, no input ports, and no transitively stock-carrying module instance (modules_carry_state, a visited-set walk over cached model_causal_edges). dynamic_modules non-emptiness alone would be over-inclusive -- a model whose only module is a stockless passthrough has no state anywhere, so any causal cycle through it is an instantaneous algebraic CircularDependency (a compile error, not feedback) and the early bail plus its "always Exhaustive, no mode flip possible" invariant remain correct for it (pinned by stateless_passthrough_module_root_bails_early, which uses discovery mode so the gate's firing is observable rather than vacuous). model_ltm_mode's stock-free arm gets the identical gate so the two queries cannot disagree.
model_ltm_fragment_diagnostics covered only the LTM synthetic variables themselves; the implicit helpers synthesized during LTM equation parsing (builtins_visitor::make_temp_arg's PREVIOUS/INIT captures, registered in model_ltm_implicit_var_info) ride the exact same silent-drop assembly path -- compile_ltm_implicit_var_fragment fails, assemble_module skips the fragment, the helper keeps its layout slot and reads a constant 0 -- corrupting every link score that consumes it with NO warning anywhere. The GH #759 pinned-index shape (growth[D1] = matrix[D1, c1] * frac[D1]) demonstrates it organically: two doomed helpers read 0 and the frac->growth link score is a constant wrong -40 with zero diagnostics. The pass now probes each implicit helper the way assembly does. The one divergence is the input set: assembly compiles per module INSTANCE while this pass is keyed per (model, project), so it probes with the empty set, mirroring model_all_diagnostics' compile_var_fragment precedent. That is byte-identical to assembly for the root (whose input set IS empty), and for sub-model instances the inputs only flip how a resolved name loads (ModuleInput slot vs stubbed var -- every dependency is stubbed into the fragment's mini-layout either way), never whether the equation compiles. "Compiled ok" requires bytecode for the helper's value-bearing phase (flow for plain aux helpers, stock for stock/module-typed ones), since compile_ltm_implicit_var_fragment returns Some even when every phase failed. LtmFragmentFailureGuard (GH #547) is extended to the helper path so the positive diagnostic tests survive GH #759 being fixed; the organic fixtures additionally pin today's reachable failure end-to-end, including through libsimlin's simlin_project_get_errors LtmEnabledGuard harvest (same accumulator as the GH #466 auto-flip flow). No existing warning-count test shifted: the previously-pinned fixtures' helpers all genuinely compile.
Review follow-up on the GH #748 change: the composite stateless predicate was written twice inline (model_ltm_mode's stocks.is_empty() && !modules_carry_state vs model_ltm_variables' same two legs plus !has_input_ports), and the variables query's bail hardcoded LtmMode::Exhaustive -- a future edit adding a state source to one site only would make model_detected_loops (a model_ltm_mode reader) and the emitted vars/mode diverge, the same two-surface drift class GH #761 addressed, and #748 itself was a two-site predicate change. model_is_stateless(db, project, edges) is now the single predicate both queries consume (model_ltm_variables adds its !has_input_ports leg on top), and the bail reads its mode from model_ltm_mode instead of hardcoding: by construction that reads Exhaustive (the mode query's stateless arm fires on the same shared predicate), but reading the shared query makes drift structurally impossible, matching the mode read at the function's tail. The new parity guard test_ltm_mode_and_variables_agree_on_stateless_gate sweeps {stateless passthrough, module-internal state} x {exhaustive, user discovery} on a module-only root and pins that the two queries agree and that the stateless bail stays Exhaustive even under the user discovery flag. Also two review-minor comments on the #741 diagnostic leg (no behavior change): the fragment_vars_in_layout drop of a successfully-compiled helper is still silent (the #683-class gap, open for the helper leg too), and the value-bearing-phase check is deliberately blind to a divergent init-phase failure (likely unreachable: both phases compile from the same lowered equation).
The ceteris-paribus partial builders treated a bare dimension name inside a subscript index (matrix[D1, c1]'s D1 -- the iterated-dim reference form) as a causal dependency and froze it as PREVIOUS(d1), because the A2A/scalar link-score generators built their dep sets via identifier_set with empty dims (so subscript-index identifiers leaked into other_deps) and the GH 587 wrapper guards only recognize dimension elements, never dimension names. The doomed PREVIOUS-capture helpers were warned (post GH 741) but stubbed to 0, so scores read constant garbage (-40 on the GH 759 probe) on a mundane apply-to-all equation. Fix both directions for defense-in-depth (GH 759): the generators now pass the target's AST dims to identifier_set and strip the source's dimension/element tokens (mirroring build_arrayed_link_score_equation), and wrap_index_non_matching_in_previous gains a dimension-name guard (project dims via dims_ctx, plus the iter_ctx iterated/source dims for callers without one) alongside the element-name guards. The wrapper guard is the backstop for co-source dimensions spelled in neither the target's nor the source's dim space. This also resolves the GH 525 hard-failure shape: the partially iterated subscript's conservative DynamicIndex partial (and its PREVIOUS(SUM(...)) guard term) now compiles, so pop[Region, young] references score instead of stubbing. The previously-pinned degraded expectations (helper warnings, constant-0 stubs) flip to correct-value assertions; GH 741's diagnostic pass stays covered by the guard-injected ltm_unified_tests case, and libsimlin's get_errors harvest test repoints at the still-failing GH 742 RANK-agg shape with a sub-class-agnostic assertion.
RANK is in the reducer table (the agg machinery enumerates and scores it like one) but RANK(arr, dir) is ARRAY-valued -- Vensim's VECTOR RANK -- not a scalar-collapsing reduce. Two consumers wrongly treated it as scalar-valued: builtins_visitor's arg_has_bare_var_ref refused to descend into any reducer-table builtin, so a ceteris-paribus partial's frozen PREVIOUS(RANK(pop, 1)) subtree was captured into per-element SCALAR helpers whose equation rank(pop, 1) is ill-typed, the helpers stubbed to 0 (warned post GH 741), and the consuming link score read -100-class garbage; the same shape in a USER equation (PREVIOUS(RANK(pop, 1)) in an A2A aux) was a hard NotSimulatable. Add ltm_agg::reducer_collapses_to_scalar (the reducer set minus RANK) and consult it at both sites (GH 742): arg_has_bare_var_ref now descends into RANK so a bare arrayed name inside it routes through the GH 541 ARRAYED capture helper (ApplyToAll over the active dims, which compiles exactly like the model's own A2A equation), and expr_is_array_slice_valued treats RANK as transparent so a slice-bearing argument (PREVIOUS(rank(matrix[d1,*],1))) is detected as unfreezable and the GH 743 chooser falls back to changed-last instead of emitting a doomed capture. The predicate lowercases builtin names (parsed Expr0 names keep source casing; the old exact-case reducer_kind_from_name call missed uppercase spellings). Arrayed capture helpers also need dimension-aware plumbing on the LTM side: model_ltm_implicit_var_info now sizes a non-module helper from its equation's dims (a 1-slot layout entry would overlap successors), and compile_ltm_equation_fragment registers an arrayed helper dep with its true size plus an ApplyToAll stub AST (mirroring the tech-debt-34 LTM-var dep stubs) so the consuming fragment's helper[dim-elem] subscript resolves. Out of scope, pinned loudly by the new e2e test: enumerate_agg_nodes still hoists a whole-extent RANK into a scalar agg whose own array-valued equation cannot compile (the 'RANK as the scored reducer itself' family, docs/tech-debt.md entry 27) -- one synthetic-variable Warning, agg-routed loop scores zeroed.
The GH 525 filing -- an A2A equation referencing a multi-dim source by a partially-iterated subscript (pop[Region, young] inside an A2A-over-Region target) hard-failing LTM compilation with 'PREVIOUS requires a variable reference after helper rewriting' -- is resolved by the GH 759 dimension-name-index fix on this branch: the reference still classifies DynamicIndex (classify_iterated_dim_shape's all-iterated rule deliberately excludes the iterated+literal mix), but the conservative partial it produces now compiles (the iterated dim name stays verbatim in the subscript and in the PREVIOUS(SUM(...)) guard term, which routes through a per-element capture helper) and scores its true value. Pin the exact filed repro end-to-end: two partially-iterated references in one equation, a multi-dim flow closing the loop, zero assembly warnings, the pop->row_sum score exactly +1 per element (pop is row_sum's only dependency, so the all-references-live conservative partial is exact), and the same-element loop through row_sum carrying real values. The residual conservatism -- DynamicIndex's cross-product element edges enumerate cross-element loops that don't exist causally -- is documented on the classifier and stays tracked on GH 525; the per-element-family classification that would remove it is a classification/expansion/emission change beyond this batch's scope.
Review follow-ups on the ltm-fix-batch-2 cluster: The gh525 repro test now pins the residual's exact values instead of finiteness-only: the conservative DynamicIndex cross-product enumerates four scalar phantom loops (the a<->b cross circuit at the 2x2 Age-slot pairings of its two row_sum->growth hops), each a 6-factor product whose cross edges read the WRONG element's real per-slot link score -- silent confident phantoms reading ~0.4949^2 ~= 0.245 with no diagnostic, and diluting the shared partition's rel-score denominator (~20% here). Pinning them loudly (count == 4, value within 1e-3 of 0.245, with a flip-note) follows the repo's degraded-behavior convention so the future GH 525 classifier fix consciously flips the assertions. An assembly-time advisory naming such loops was considered and skipped: without the iterated+literal classification itself it cannot distinguish phantoms from legitimate dynamic-index cross-element loops, so it would warn spuriously on valid models. Doc corrections: the GH 742 commit claimed parsed Expr0 builtin names keep source casing -- false; the parser lowercases function-call identifiers, so the to_ascii_lowercase at the two new call sites (and in is_array_reducer_name, which carried the same stale claim) is defensive belt-and-suspenders, not load-bearing. Also document scalar_or_a2a_target_deps' name-based over-strip boundary (a variable named like a source dimension element, referenced outside a subscript, stays live) as a pre-existing characteristic shared with build_arrayed_link_score_equation and classify_dependencies.
For a feedback cycle through an arrayed variable, model_detected_loops
enumerated one variable-level loop per cycle while the scored surface
(model_ltm_variables) enumerated per-element loops, both numbering
their own sequence from the shared r{n}/b{n}/u{n} namespace. The
runtime id join (reclassify_loops_from_results, libsimlin's
rel-loop-score FFI, pysimlin's get_relative_loop_score, and layout's
importance-series pairing) reads "$:ltm:loop_score:{id}" keyed purely
on the detected id, so a detected loop silently read ANOTHER loop's
score series (GH #746). model_detected_loops now builds its exhaustive
loop set with the same machinery the scored surface uses --
model_loop_circuits_tiered feeding build_loops_from_tiered under the
shared cross_agg_loop_budget, plus the shared
recover_agg_hop_polarities pass -- so the two surfaces' loop sets,
polarities, and ids are identical by construction for every model
shape. The former per-agg splice (expand_loops_through_routed_aggs,
the GH #737 fix that only restored bijection for all-scalar cycles)
is deleted along with its silent 64-variant cap: with one shared
builder and one shared budget there is no second enumeration to
desync, resolving the issue's cap-without-Warning aggravator
structurally (the scored surface already warns on cross-agg
truncation, and a truncated enumeration now clips both surfaces
identically -- pinned by a budget-guard test). The only remaining
detected-without-scored ids are the GH #758 unscoreable-edge drops
and discovery mode, both of which degrade to a loud absent series,
never a wrong one.
Partition metadata moves to the element-level cycle partitions
(model_element_cycle_partitions), the granularity the scored and
discovery surfaces already use: the per-element loops carry
element-level stock names a variable-level map could never resolve,
and the partition stock sets -- the durable cross-surface identity --
now agree across the exhaustive and discovery surfaces for arrayed
models too (the GH #685-adjacent granularity divergence). A
cross-element loop's DetectedLoop.variables are element-subscripted
(pool[a]), the convention cross-element pins already used; layout
strips the subscripts before matching chain entries against view
idents. Rejected alternatives: a content-keyed (stock-set) join keeps
the granularities different, so one detected loop maps to potentially
many scored loops and the mapping is inherently lossy; disjoint id
namespaces make wrong reads impossible but trade them for missing
data on every arrayed model. Both leave two enumerations to maintain;
sharing the builder makes the bijection a structural property instead
of a maintained invariant.
The 7d9a4b3 detected-surface rewrite moved exhaustive partitions to element granularity but missed four contract texts the review caught: the MCP PartitionOutput.stocks rustdoc (the user-facing wire type) and two pysimlin test docstrings still taught the old scalar-only stock-set agreement, and the pin stock-validation comment still attributed model_detected_loops to find_loops_with_limit plus enrichment. All four now describe the post-#746 reality (element granularity on both surfaces; stock sets agree for arrayed models too).
A stockless cycle broken by PREVIOUS (a = PREVIOUS(b, 0); b = a * k) compiles, simulates as a genuine first-order lag, and was scored by the loop enumerator -- but pin validation rejected it with the false rationale "contains no stock", and on a fully stock-free model the stateless early return (GH #748's gate) suppressed all scoring while model_detected_loops still reported the loop, so the pin was dropped without any diagnostic at all. Characterization at HEAD confirmed the enumerator's score for this cycle is meaningful (exactly 1 once active: each variable on the cycle has a single input, so the loop fully accounts for its own activity), and the LTM reference (section 7) explicitly lists PREVIOUS among the state-retaining builtins it scores via the perfect-mixing approximation. So the resolution is to ACCEPT the cycle as feedback on every surface, not to filter it from enumeration (which would contradict the reference and discard meaningful scores): - model_is_stateless gains a lagged leg: a parent-level variable with a previous_only dt dependency (dt_previous_referenced_vars) is state. previous_only presence is exactly the conservative superset of "a lagged feedback cycle can exist": a mixed (inside-and-outside PREVIOUS) reference keeps its instantaneous edge, so a cycle through it only compiles if some other previous_only edge or stock breaks it. A lagged-but-acyclic model just runs the normal enumeration path and scores nothing, output-equivalent to the bail. - model_pinned_loops accepts a stockless cycle that traverses a previous_only edge, so the pinned and scored surfaces agree; the rejection message now names the lagged-state exception. Module-INTERNAL lagged state is deliberately NOT counted on either surface (the stateless gate's module leg stays stocks-only and pin validation cannot see inside a module's pathway), so the two surfaces also agree on that shape -- both treat it as stateless. The residual detected-vs-scored gap for instantaneous module-passthrough cycles and module-internal-PREVIOUS cycles (model_detected_loops has no stateless gate) is pre-existing and reported for tracking separately.
Loops whose cycle partition resolves to None -- module-internal-stock loops (reachable since GH #673 made module pins validate) and PREVIOUS-lagged stockless loops (scoreable since GH #749) -- all shared ONE default normalization bucket for relative loop scores, so two unrelated subsystems cross-normalized each other's rel_loop_score: the GH #487-class cross-pollution, in the None bucket. In the discovery ranker the pooled bucket was worse than dilution: an unrelated big loop could push a small module-internal loop's peak relative contribution below MIN_CONTRIBUTION and censor it from the result entirely. A None partition means "no provable stock-to-stock coupling", so the honest semantics is to never cross-normalize: each None-partition loop (or slot) now forms its own singleton group (NormGroup::Solo, keyed by emission-order loop index), collapsing to the already-documented lone-pin degeneracy (sign-preserving +/-1, SAFEDIV-0 at zero). Applied consistently across every normalization surface so they cannot disagree: ltm_post's full-sweep pair (slot-0 view and the per-element (group, slot) grid, including the scalar broadcast stride), libsimlin's streaming ensure_denom_for_element membership (a None bucket is the querying loop alone, bypassing the shared cache whose (None, k) key would collide across distinct solo loops), and ltm_finding's rank_and_filter grouping (totals, retention filter, and the competing-vs-solo classification -- a Solo-group loop is solo by definition). Resolved partitions are untouched, preserving the GH #468 bit-for-bit emission-order sums. Partition METADATA is deliberately unchanged: every surface still reports None/-1 for these loops, which now consistently reads as "compared with nothing". Rejected alternative: resolving partitions for module-internal stocks by treating state-carrying module instances as partition nodes. It is the more principled fix for genuinely-coupled module loops (the Solo rule under-merges those -- each normalizes alone instead of against its true siblings), but it spans three partition-construction sites plus an FFI-visible change to partition stock sets (the documented durable cross-surface key), and it would still not cover the PREVIOUS-lagged stockless loops that also land in None -- the singleton rule is the necessary backstop regardless. Tracked as a follow-up refinement that would move module-stock loops out of the None bucket entirely.
A parent-level PREVIOUS lag of a module output (reader = PREVIOUS(sub.output, 0) through a stockless passthrough sub) recreated the scored-but-unpinnable disagreement inside the gate/pin pair GH #749 aligned: cycle_has_lagged_edge compared the cycle's module-normalized node name ("sub") against the UN-normalized previous_only entry ("sub·output") that the empty-context dependency classification stores, so contains() never matched. The stateless gate was unaffected (it only tests non-emptiness), so the enumerator scored and detected the loop while the pin was rejected -- and the post-#749 rejection message ("... or other state, such as a PREVIOUS-lagged reference") was false for the cycle, which genuinely traverses one. Collapse each previous_only entry through the same normalize_module_ref_str the causal-edge builder applies before comparing. The module-INTERNAL exclusion (GH #773) is unchanged: a lag INSIDE the sub-model lives in the sub-model's variables, which neither the parent's lagged-deps gate nor the parent-source_vars pin check ever reads -- only a parent variable's own lag of a module OUTPUT is now seen, matching the causal edge it creates. Also true up the model_has_lagged_dt_deps rustdoc: the lagged-but- acyclic unbail is NOT output-equivalent to the old bail in DISCOVERY mode (discovery scores ALL edges, so such a model now emits link scores where the gate emitted none); that difference is deliberate stock/lag parity -- a no-feedback stock model never bailed either.
Codecov Report❌ Patch coverage is Additional details and impacted files☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
Review summaryI reviewed the changes across the 38 modified files, focusing on the new logic in The patch reads as a coherent, well-engineered burn-down. Major mechanisms I traced:
I traced potential edge cases - empty FindingsNone. Overall correctness verdictCorrect. No blocking issues found. |
Second burn-down batch on epic #488, following the PR #761 pattern: fourteen issues fixed across 28 commits, each implemented by a fresh agent under TDD and adversarially reviewed by a separate fresh agent to zero material findings (most took 2 rounds; the reviews caught a demonstrated wrong-score regression, two falsified soundness claims, a live layout misjoin, and four stale public contracts before merge). The batch invariant throughout: no silent wrong numbers -- every un-scoreable shape now either scores correctly or degrades to one loud warning, never garbage and never a quiet zero.
What changed, by cluster
Polarity recovery (#745). Arrayed-agg loop hops now match their subscripted element-graph endpoints, so loops through arrayed reducers classify concretely (r/b) instead of blanket-Undetermined, shrinking the #746 cross-surface polarity disagreement.
Body-aware reducer partials (#744, #762). The per-row source-to-agg link score is now derived from the reducer BODY (live row, frozen co-reduced rows and co-sources) instead of asserting a bare unit coefficient:
SUM(pop[*] * (1 - weight[*]))w.r.t. weight now scores negative as the true partial demands (it read sustained-positive before), with the changed-first/changed-last bilinear additivity contract preserved exactly and pinned. The MIN/MAX/STDDEV arm got the same treatment (a coefficient inside MIN previously produced garbage scores around 2884); literal self-references bail to the delta-ratio fallback rather than emitting a cancellation-violating partial. The TIME-bearing-body anchor caveat is documented and tracked (#763).Conservative-path scoring (#752, #743, #758, plus the #510 unification). Whole-RHS partial reducers get read-slice element edges through their own variable nodes, so their loops compose real per-(row,slot) link scores instead of referencing names that were never emitted (silent zeros before). Un-hoisted multi-source reducers' feeder edges now render a compiling changed-last partial (a constant -250-class garbage score before); when neither attribution convention can render, the edge skips loudly -- one warning naming it, no link-score variable, and loop scores through it dropped rather than zero-stubbed (the same drop now also covers the #510 disjoint-dim skip, fixing a latent double-warn). Dim-incompatible conservative scores (the element-mapped #756/#757 declines) take the same loud-skip treatment: one warning instead of 17-22 cascading fragment failures. Pinned-mixed slices are excluded from the new read-slice gate until the underlying divisor bug (#765) is fixed, keeping them loud rather than silently wrong.
Visibility (#741, #748). Failed LTM implicit-helper fragment compiles now emit a Warning naming the helper and its parent score variable -- this silent-stub mechanism turned out to be the hidden leg of four separate bugs in this batch alone. The stock-free early return is module-state-aware (transitively, including SMOOTH/DELAY builtin instances), so a root model whose only state lives inside modules runs the LTM pass instead of silently emitting nothing; both query surfaces consume one shared stateless predicate and the bail reads its mode from the shared query, making gate drift structurally impossible.
PREVIOUS capture/wrap class (#759, #742). Dimension-name subscript indices are no longer PREVIOUS-wrapped (both generator-side dep filtering and a wrapper-side guard), fixing reachable silent wrong scores on mundane shapes like
growth[D1] = matrix[D1, c1] * frac[D1]-- and, it turned out, the live leg of #525's filed compile failure. Frozen array-valued RANK subtrees capture into arrayed helpers (the #541 mechanism extended), soPREVIOUS(RANK(...))compiles per element instead of corrupting link scores through ill-typed scalar helpers.#525 is deliberately NOT closed by this PR. Its filed hard failure is fixed (routed through #759), and the genuine reference now scores exactly +1 -- but the iterated+literal classification residual remains: phantom cross-element loops from the conservative cross-product now carry confident nonzero scores (~0.245 in the repro), pinned loudly in tests with a flip note, and #525 has been rescoped/retitled to track exactly that.
Cross-surface identity (#746).
model_detected_loopsnow builds its loop set with the scored surface's exact machinery (tiered circuits, shared budget, shared polarity recovery), deleting the #737-era per-agg splice and its silent 64-variant cap entirely: detected and scored ids, polarities, and partitions agree by construction for every model shape, the runtime id join can no longer read another loop's series on arrayed models, and a previously-unknown live misjoin in diagram layout's loop-importance pairing is fixed as a consequence. Exhaustive partitions move to element granularity, so partition stock sets -- the durable cross-surface key -- agree across surfaces for arrayed models too.Pins and normalization (#749, #750). Stockless PREVIOUS-lagged cycles are accepted as genuine feedback on every surface (the LTM reference lists PREVIOUS among state-retaining builtins, and the measured scores are meaningful), including a parent-level lag of a module output; pin validation and the stateless gate agree by construction. Unpartitioned (None-partition) loops normalize alone instead of sharing one default bucket -- the cross-pollution was live on four surfaces, including a discovery-mode case where an unrelated large loop could censor a small module-internal loop out of the result set entirely.
Discovered along the way
Twelve previously-untracked pre-existing defects were filed and added to epic #488 (#763 through #774, notably #765's pinned-slice divisor bug and #767's feeder-sub-slice hoist), #759 and #525 were rescoped with corrected severity and reachability, and scoped follow-up notes were added to #655, #683, and #716.
Fixes #741
Fixes #742
Fixes #743
Fixes #744
Fixes #745
Fixes #746
Fixes #748
Fixes #749
Fixes #750
Fixes #752
Fixes #758
Fixes #759
Fixes #762