Skip to content

ltm: iterated+literal mixed subscript keeps the cross-product element expansion -- phantom cross-element loops carry silent nonzero scores (rescoped: hard compile failure fixed) #525

Closed

Description

@bpowers

Status (2026-06 rescope)

The hard failure this issue was filed for is FIXED; what remains is a classification tightening. Scope as of branch ltm-fix-batch-2 (commits 9b0723d9 / c1120706), from the #759/#742/#525 cluster review:

Fixed -- the filed symptom

The hard codegen failure -- "PREVIOUS requires a variable reference after helper rewriting" for row_sum[Region] = pop[Region, young] + pop[Region, old] -- actually routed through the #759 dimension-name PREVIOUS-wrap: the partial builders PREVIOUS-wrapped the bare dimension name region inside the subscript index. With #759 fixed (9b0723d9), the conservative DynamicIndex partial for the partially-iterated reference compiles, and the GENUINE same-element reference scores exactly +1. Pinned by gh525_two_reference_partially_iterated_row_sum_scores (src/simlin-engine/tests/integration/ltm_array_agg.rs, added in c1120706) -- the exact repro filed below, with TWO partially-iterated references in one A2A equation.

Remaining -- the classification residual (this issue's scope now)

The iterated+literal mixed subscript still classifies RefShape::DynamicIndex: classify_iterated_dim_shape (src/simlin-engine/src/db/ltm_ir.rs ~201) deliberately recognizes only the all-iterated subscript as Bare; a mix of iterated dims and literal elements falls through to classify_subscript_shape and lands DynamicIndex. The element graph therefore keeps the conservative CROSS-PRODUCT expansion (pop[a,young] -> row_sum[b] alongside the genuine pop[a,young] -> row_sum[a]), and the enumerator reports phantom (non-causal) cross-element loops.

These phantom loops are not harmless conservatism. They now carry SILENT, CONFIDENT, NONZERO scores (~0.245 in the symmetric repro): each phantom loop's 6-factor score product reads the per-slot link score at the WRONG element, so the wrong element's REAL contribution is attributed to a causal pathway that does not exist. And the phantom loops dilute the shared cycle partition's rel-loop-score denominator (~20% in the repro). This is arguably worse-in-kind than the pre-fix warned 0-stubs -- silent plausible numbers instead of loud zeros -- even though the absolute scores of the real loops went from non-compiling/0 to correct.

Fix direction

A per-element shape family pinned on the literal axes. classify_iterated_dim_shape already sees the discriminating information -- which indices are target-iterated dims in matching positions, which are literal element names -- and currently discards it by bailing to DynamicIndex. The work is phase-sized:

  • a classifier variant (Bare-like with pinned axes: "same element on the shared iterated dims, fixed literal element on the rest") in src/simlin-engine/src/db/ltm_ir.rs,
  • a diagonal-with-pinned-axis arm in emit_edges_for_reference (src/simlin-engine/src/db_analysis.rs) so the element graph emits only pop[a,young] -> row_sum[a], killing the phantom loops at enumeration time,
  • partial emission/naming for the new shape (live reference in the matching slot, the literal axis rendered as a real subscript index).

Severity

medium (stands) -- no longer a hard compile failure, but silent confidently-wrong loop scores plus rel-score denominator dilution on a legal, mundane model shape (aux[D1] = arr[D1, elem] + ...).


Original report (historical -- the hard compile failure described below is fixed on ltm-fix-batch-2)

Summary

When LTM (Loops That Matter) is enabled, an apply-to-all (A2A) equation that references a multi-dimensional arrayed variable with a partially-iterated subscript -- one index iterated over the target equation's dimension, one a literal element name, e.g. pop[Region, young] referenced inside an A2A equation over Region -- breaks LTM compilation with:

PREVIOUS requires a variable reference after helper rewriting

(error originates at src/simlin-engine/src/compiler/codegen.rs:712, the BuiltinFn::Previous arm at codegen.rs:701). Without LTM the same model compiles and simulates fine.

This is the close cousin of #511 -- same codegen error, same general failure mode (an A2A reference to an arrayed dep that classifies DynamicIndex ⇒ the partial PREVIOUS-wraps a non-Var expression ⇒ codegen rejects it). #511's repro and Phase-3 fix cover the all-iterated, matching-positions case (row_sum[D1] where row_sum is arrayed over a single dim D1, referenced by [D1] from growth[D1,D2] -- now classified RefShape::Bare by classify_iterated_dim_shape in db_ltm_ir.rs). The partially-iterated case here -- pop[Region, young] (one iterated index, one literal element, on a 2-D source) -- is explicitly out of scope for Phase 3: classify_iterated_dim_shape requires the subscript length to equal the target's iterated-dim count and every index to be a target iterated dim, so pop[Region, young] (2 indices, only Region iterated) falls through to classify_subscript_shape, where Region (a dimension name, not an element name / integer literal) does not resolve via resolve_literal_index ⇒ RefShape::DynamicIndex. (See the doc comment on classify_iterated_dim_shape and src/simlin-engine/CLAUDE.md: "A partially-iterated subscript (some indices iterated, some literal/wildcard) is out of scope -- it keeps its classify_subscript_shape result; Phase 4 handles sliced reducers.")

The Phase-3 plan deferred this to "Phase 4 / sliced reducers", but #514 / Phase 4 is about sliced reducer subexpressions (SUM(pop[NYC,*])) -- adding AggNode.read_slice + compute_read_slice, consulted only in walk_subexpr_for_aggs / walk_var_equation for reducers that get hoisted into $⁚ltm⁚agg⁚{n} nodes. A bare pop[Region, young] reference that is not inside a reducer is never hoisted into an agg node, so it stays on the Direct per-element non-reducer link-score path (emit_per_shape_link_scores), where it would still classify DynamicIndex and still produce the broken PREVIOUS(SUM(...)) even after Phase 4. So this specific shape is covered by neither #511 (all-iterated, fixed by Phase 3) nor #514 (sliced reducers).

Failure chain

  1. model_ltm_reference_sites (src/simlin-engine/src/db_ltm_ir.rs) walks row_sum's A2A equation; for the pop[Region, young] reference it calls classify_iterated_dim_shape -- the subscript has 2 indices but row_sum's only iterated dim is Region, so the length check fails and it falls back to classify_subscript_shape. Region is a dimension name (not a literal element / integer), so resolve_literal_index returns None ⇒ the site is classified RefShape::DynamicIndex.
  2. The non-reducer per-shape link-score path emits the ceteris-paribus partial for the (pop, row_sum) edge. build_partial_equation_shaped / wrap_non_matching_in_previous -- since this is the only pop reference and it doesn't "match" the (non-Bare/FixedIndex) shape -- wraps it: PREVIOUS(pop[region, young]). And source_ref_for_guard(from, RefShape::DynamicIndex, live_ref) (src/simlin-engine/src/ltm_augment.rs:1659, the Wildcard | DynamicIndex arm at :1666) renders the source-side guard / SIGN normalizer as SUM(pop[region, young]) -- a bare arrayed pop in a scalar fragment would be a dimension error, so the code wraps the isolated source slice in SUM(...). The denominator/guard must match the live partial reference, so the partial side likewise ends up PREVIOUS(SUM(pop[region, young])).
  3. After helper rewriting desugars PREVIOUS(...), codegen (src/simlin-engine/src/compiler/codegen.rs:701, BuiltinFn::Previous arm) requires the argument to be a plain Expr::Var. SUM(pop[region, young]) compiles to an Expr::App(...), not Expr::Var ⇒ the assertion at codegen.rs:712 fires with "PREVIOUS requires a variable reference after helper rewriting" and the model is NotSimulatable.

So a valid model construct -- an A2A equation that references a multi-dim arrayed dependency by [<iterated-dim>, <literal-element>] -- breaks LTM compilation when that edge is in a detected loop / gets scored.

Repro shape

  • Region = {a, b}, Age = {young, old}
  • pop[Region, Age] -- an arrayed stock (or aux)
  • row_sum[Region] = pop[Region, young] + pop[Region, old] -- an A2A aux over Region that references pop by the partially-iterated subscript pop[Region, young] (and pop[Region, old])
  • something that closes a feedback loop through (pop, row_sum) (e.g. growth[Region, Age] = row_sum[Region] * 0.0001 * pop[Region, Age] flowing into pop)
  • enable LTM ⇒ "PREVIOUS requires a variable reference after helper rewriting" at codegen

Interestingly, phase_03.md's Task 2 fixture suggestion (docs/implementation-plans/2026-05-11-ltm-arrays-hardening/phase_03.md, ~line 82) literally proposes row_sum[Region] = pop[Region, young] + pop[Region, old] as a "cleaner #511 demonstration without the SUM aggregate complicating things" -- but phase_03.md line ~31 says the partially-iterated case is not handled in Phase 3. So that suggested fixture, used verbatim, would trip exactly this bug; the Phase-3 plan has an internal inconsistency on this point (the actual Phase-3 fixtures used the all-iterated x[Region] form and sidestepped it).

Why it matters

medium -- an unfixed correctness/robustness gap in LTM scoring of arrayed models with partially-iterated subscripts. A real model author who writes aux[D1] = arr[D1, some_element] + ... (perfectly legal XMILE/Vensim) over a multi-dim arrayed arr, then turns on LTM with that edge in a loop, gets a hard compile error whose message points at internal helper-rewriting machinery, with no hint that the trigger is the subscripted reference. The same model is fine without LTM. It's not blocking the LTM arrays hardening epic (#488) -- Phase 3's test fixtures avoid this shape -- but it's a known limitation that should be on record.

Components affected

  • src/simlin-engine/src/db_ltm_ir.rs -- model_ltm_reference_sites, classify_iterated_dim_shape, classify_subscript_shape, resolve_literal_index (the partially-iterated subscript lands in DynamicIndex)
  • src/simlin-engine/src/ltm_augment.rs -- build_partial_equation_shaped, wrap_non_matching_in_previous, classify_expr0_subscript_shape, source_ref_for_guard (:1659, the Wildcard | DynamicIndex arm at :1666 that emits the SUM(...)-wrapped source ref)
  • src/simlin-engine/src/compiler/codegen.rs -- :701 BuiltinFn::Previous arm; :712 the "PREVIOUS requires a variable reference after helper rewriting" assertion
  • src/simlin-engine/src/db_analysis.rs -- emit_edges_for_reference / expand_same_element (the Bare projection a fixed solution would route through)

Possible approaches

  • Extend the iterated-dim recognizer (classify_iterated_dim_shape in db_ltm_ir.rs) to handle the mixed case: a subscript whose iterated indices are exactly the target equation's iterated dim(s) in matching positions, with the remaining indices literal element names / integer literals, is a FixedIndex-like reference projected through the iterated dim -- i.e. "the same Region element of pop, fixed at Age = young". The element graph would then need a "partial-fixed-index" projection (pop[Region, young] from row_sum[Region] ⇒ pop[a,young] -> row_sum[a], pop[b,young] -> row_sum[b]), and the partial generator would emit pop[region, young] live in the matching slots and the frozen form elsewhere -- with the source-side guard being pop[region, young] rendered as a subscript expression (a real Expr::Subscript, not SUM(...)), so the PREVIOUS(...) arg after helper rewriting is... still a Subscript, not a Var. Which means this likely also needs the second fix below to land cleanly.
  • In the partial generator, when the source reference resolves to a per-element slot of an arrayed var (the FixedIndex / partially-iterated case), emit a synthetic scalar "previous of this slice" helper aux so PREVIOUS(...) gets a real Expr::Var -- the same trick ltm-augment: subscripted-A2A-reference link-score partial fails to compile (PREVIOUS arg must be Var) #511's "Alternative" approach proposes, generalized. (This is the structural fix; arguably it belongs in codegen / builtins_visitor.rs's PREVIOUS helper rewriting -- desugar PREVIOUS(expr) for any expr, not just Expr::Var, via a synthesized scalar helper -- which would also subsume parts of ltm-augment: subscripted-A2A-reference link-score partial fails to compile (PREVIOUS arg must be Var) #511 and the related codegen-side gaps.)
  • At minimum, if the construct genuinely can't be scored this way, emit a clear compile-time Warning diagnostic ("LTM cannot score the link from pop to row_sum because pop is referenced with a partially-iterated subscript pop[Region, young]; rewrite as ... or score will be unavailable") instead of the internal "after helper rewriting" assertion -- mirroring the AC3.4 unscoreable-edge warning pattern that ltm: degenerate link score for disjoint-dimension arrayed-to-arrayed edges with per-element target equations #510's try_disjoint_dim_arrayed_link_scores already uses.

The proper fix probably belongs alongside #514's Phase-4 work (the sliced-reducer / read_slice machinery is the natural place to also generalize "partially-pinned access" handling) or as a sibling issue threaded through the same db_ltm_ir.rs classifier; it is not covered by #514 as currently scoped (sliced reducers only, hoisted into agg nodes -- this is a bare non-reducer subscript on the Direct path).

Discovery context

Identified during Phase 3 of the LTM arrays hardening epic (#488; design plan under docs/implementation-plans/2026-05-11-ltm-arrays-hardening/, see phase_03.md lines ~31 and ~82, and phase_04.md for the sliced-reducer scope). Pre-existing on main, not a regression -- and not a Phase-3 blocker, since the Phase-3 fixtures use the all-iterated x[Region] form and sidestep it.

Tracking

Part of LTM tracking epic #488. Related to #511 (subscripted-A2A-reference link-score partial -- the all-iterated case, fixed by Phase 3), #514 (sliced reducers not hoisted into agg nodes -- Phase 4), and the LTM array-support umbrella #273. Distinct from all of them: this is the partially-iterated, non-reducer subscript shape, which falls through Phase 3's all-iterated Bare recognition and is never reached by Phase 4's reducer-hoisting path.

Activity

  1. added
    ltm
    on May 13, 2026
  2. bpowers commented on Jun 2, 2026

    @bpowers
    OwnerAuthor

    Status update from the ltm-gaps hardening branch (2026-06-02):

    The crash half is fixed. This issue's shape (a partially-iterated subscript like pop[Region, young] in an A2A link-score partial) had regressed from the filed clean-NotSimulatable into a hard PANIC at codegen.rs's array-view index walk (.unwrap() on the propagated PREVIOUS requires a variable reference error). Commit 77be8ae converts the view-path index-walk (and sibling SafeDiv/EvalModule sites) to error propagation, so the fragment now degrades gracefully: the link score is stubbed to 0 and model_ltm_fragment_diagnostics emits a Warning naming it. The integration test unloweable_ltm_link_score_degrades_gracefully_no_panic (tests/ltm_array_agg.rs) pins the current degraded behavior and points back here.

    The root cause (mis-scoring) remains open, re-verified against current code: classify_iterated_dim_shape (db/ltm_ir.rs) requires every index to be a target-iterated dim, so the mixed iterated+literal case falls through classify_subscript_shape to RefShape::DynamicIndex, and the partial generator emits the unloweable PREVIOUS(SUM(pop[region, young])) stand-in. Fix direction (medium-large): recognize the mixed case as a partial-fixed-index projection in the classifier, add the matching element-graph projection in emit_edges_for_reference/expand_same_element, and emit a per-element subscripted source-ref in the partial generator — the natural sibling of the #514 read-slice machinery.

  3. changed the title [-]ltm-augment: partially-iterated arrayed subscript in A2A link-score partial fails to compile (PREVIOUS arg must be Var)[/-] [+]ltm: iterated+literal mixed subscript keeps the cross-product element expansion -- phantom cross-element loops carry silent nonzero scores (rescoped: hard compile failure fixed)[/+] on Jun 10, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    ltm

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions