Repository navigation
Description
Summary
When a reducer (SUM/MEAN/STDDEV/MIN/MAX/SIZE) is applied to a PREVIOUS()-wrapped array argument -- e.g. SUM(PREVIOUS(pop[*])) -- in an equation that is evaluated with an active apply-to-all (A2A) dimension, the reducer silently evaluates to 0.0 at every simulation step, even though the underlying array (pop) has non-zero values. There is no compile error and no diagnostic; the result is just wrong.
Concretely: for an A2A model share[Region] = pop[Region] / SUM(pop[*]), LTM augmentation generates the "Bare numerator" link score $⁚ltm⁚link_score⁚pop→share via generate_auxiliary_to_auxiliary_equation, which PREVIOUS-wraps the SUM(pop[*]) denominator element-wise (wrap_non_matching_in_previous -> build_partial_equation_shaped in ltm_augment.rs), producing a partial of the form pop[r] / SUM(PREVIOUS(pop[*])). The printed equation text is correct (and round-trips fine), but at simulation time the inner SUM(PREVIOUS(pop[*])) is 0.0 for every element at every step, so the link score is identically 0.0 despite the equation implying a value around the population total.
A minimal non-LTM repro: an A2A model with a dimension Region={a,b}, pop[Region] with non-zero values, and an aux denom[Region] = SUM(PREVIOUS(pop[*])). Simulate; denom is 0.0 at every step.
Root cause (suspected)
The codegen path for PREVIOUS() only handles a scalar variable-reference argument:
src/simlin-engine/src/compiler/codegen.rs:701-718-- theBuiltinFn::Previous(arg, fallback)arm matchesargagainstExpr::Var(off, _)and emitsOpcode::LoadPrev { off }(a single-slot read from theprev_valuesbuffer). Anything that isn't anExpr::Varfalls through tosim_err!(NotSimulatable, "PREVIOUS requires a variable reference after helper rewriting").src/simlin-engine/src/compiler/codegen.rs:283-361--walk_expr_as_view(used byemit_array_reduce) has no arm forExpr::App(BuiltinFn::Previous, ...); an array-valuedPREVIOUS(pop[*])reaching it would hit the catch-allsim_err!(Generic, "Cannot push view for expression type ... expected array expression").
So there is no "LoadPrev of an array view" in the bytecode. To make SUM(PREVIOUS(pop[*])) work at all, something upstream must be rewriting PREVIOUS(pop[*]) (an array-valued, "expression" argument) -- per src/simlin-engine/CLAUDE.md and the comment at src/simlin-engine/src/builtins_visitor.rs:130 ("module-backed or expression args are first rewritten through synthesized scalar helper auxes"). A synthesized scalar helper for pop[*] evaluated in scalar context cannot represent the array, so the reducer ends up summing a zero/ill-defined scalar. Either way -- whether the visitor produces a degenerate scalar helper or codegen would have errored -- the observed behaviour (silent 0.0) is a real correctness defect: PREVIOUS() of an array sub-expression inside a reducer is not actually supported, but it neither works nor produces an error in this configuration.
Why it matters
x[r] = x[r] / SUM(x[*])-style normalisation (share / fraction / proportion structures) is extremely common in SD models. Whenever LTM is enabled on such a model, the numerator path's link score (pop -> share) -- and therefore the loop score and post-sim importance ranking that depend on it -- is silently zeroed. The user sees a plausible-looking equation and a 0.0 series with no warning.
More broadly, if a user writes PREVIOUS() of an array expression inside a reducer directly (not via LTM), they hit the same silent-zero / can't-push-view path. So this is arguably a general array-eval limitation that LTM happens to exercise, not strictly an LTM bug -- but the only observed trigger today is the LTM-generated link-score equation.
Affected components
src/simlin-engine/src/vm.rs--LoadPrev/prev_valuesbuffer (no array-view variant);ArraySum/ArrayMean/ArrayStddev/ArrayMin/ArrayMaxopcodes (Opcode::ArraySum {}atvm.rs:2013, etc.)src/simlin-engine/src/compiler/codegen.rs--BuiltinFn::Previousarm (codegen.rs:701-718);walk_expr_as_view(codegen.rs:283-361);emit_array_reduce(codegen.rs:365-370)src/simlin-engine/src/builtins_visitor.rs-- PREVIOUS/INIT helper rewriting (the "module-backed or expression args ... synthesized scalar helper auxes" path; comment atbuiltins_visitor.rs:130); how isPREVIOUS(pop[*])(an array-valued arg ofSUM) rewritten?src/simlin-engine/src/ltm_augment.rs--wrap_non_matching_in_previous/build_partial_equation_shaped(the LTM side that producespop[r] / SUM(PREVIOUS(pop[*])));generate_auxiliary_to_auxiliary_equationindb_ltm.rs
Possible approaches
- Add a real "previous of an array view" path: when
PREVIOUS()'s argument is array-valued, push the array view but back it by theprev_valuesbuffer (aLoadPrevView-style opcode, or aprev_valuesflag on the view-push) so reducers iterate previous-timestep slots correctly. This is the principled fix and would also unblockPREVIOUS(arr[*])written directly by users. - Alternatively, on the LTM augmentation side, when the non-matching sub-expression to be PREVIOUS-wrapped is itself an array reducer (
SUM(pop[*])), wrap the whole reducer result in a synthesized scalar helper that isPREVIOUS(<scalar-helper-for-SUM(pop[*])>)-- i.e. snapshot the reducer's scalar output, not the array inside it. (This is what already happens forshare[r] = pop[r] / SUM(pop[*])'s Wildcard shape per tech-debt item switch to new engine #26 --PREVIOUS(pop) / SUM(pop[*])-- but the Bare numerator shape PREVIOUS-wraps the denominator and producespop[r] / SUM(PREVIOUS(pop[*]))instead ofpop[r] / PREVIOUS(SUM(pop[*])). Note tech-debt switch to new engine #26's own text claims the Bare link score ispop / PREVIOUS(SUM(pop[*]))-- the desired form -- which suggests a regression or that the desired form was never actually emitted for the A2A case.) - At minimum: detect the unsupported construct (
PREVIOUS()of an array sub-expression that can't be lowered toLoadPrev) at compile time and emit a clear diagnostic instead of silently summing zero.
Discovery context
Noticed by a bug-fixer subagent (out of scope for its task) during Phase 5 of the "LTM Cross-Element Aggregate Scoring" implementation plan (branch ltm-503-cross-element-agg; design plan under docs/implementation-plans/2026-05-09-ltm-503-cross-element-agg/). The Phase-5 aggregate-node link scores are separately verified and correct; this is a pre-existing defect in the Bare-numerator link score for x[r] = x[r]/SUM(x[*])-style models and is not a blocker for Phase 5.
The existing regression test cross_dim_link_score_equations_match_between_exhaustive_and_discovery (src/simlin-engine/src/db_ltm_unified_tests.rs:1564) is sometimes described as "defending against the sum(PREVIOUS(pop[*])) zero-numerator bug", but it only asserts the generated equation text for pop[nyc]->total_pop does not contain the broken sum(PREVIOUS(pop[*])) - PREVIOUS(total_pop) form (an LTM text-generation bug, already fixed) and that exhaustive/discovery modes agree. It does not simulate the model and check that a correctly-generated pop[r] / SUM(PREVIOUS(pop[*])) produces a non-zero series -- so the runtime bug described here slips past it.
Tracking
Part of the LTM tracking epic #488 and adjacent to the LTM array umbrella #273 -- but the root cause is in the general VM/codegen array-evaluation path (PREVIOUS() of an array sub-expression inside a reducer), so it may ultimately not be LTM-specific. Distinct from:
- ltm-augment: subscripted-A2A-reference link-score partial fails to compile (PREVIOUS arg must be Var) #511 (
PREVIOUSarg must beVar) -- that's a hard compile error for aSubscript-shaped arg (PREVIOUS(row_sum[D1])); this is a silent zero for a wildcard-array arg with no error. - ltm: cross-element loops should normalize by Δ-aggregate, not diagonal A2A link score #503 (normalize by Δ-aggregate) -- that's about LTM's normalisation strategy at the augmentation layer; this is about the VM mis-evaluating an already-generated equation.
- tech-debt identify + be able to edit variables with tables #20 / switch to new engine #26 (RESOLVED -- per-shape partial equations) -- those fixed the which references get PREVIOUS-wrapped logic; this is downstream of correct wrapping.
Activity
engine: fix LTM agg-hop polarity and inlined-reducer PREVIOUS wrapping
engine: pin LTM per-element rows inside the wrap, not after it