Skip to content

engine: SUM(PREVIOUS(arr[*])) silently evaluates to 0.0 under an active A2A dimension (no LoadPrev-of-array-view path) #517

Closed

Description

@bpowers

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 -- the BuiltinFn::Previous(arg, fallback) arm matches arg against Expr::Var(off, _) and emits Opcode::LoadPrev { off } (a single-slot read from the prev_values buffer). Anything that isn't an Expr::Var falls through to sim_err!(NotSimulatable, "PREVIOUS requires a variable reference after helper rewriting").
  • src/simlin-engine/src/compiler/codegen.rs:283-361 -- walk_expr_as_view (used by emit_array_reduce) has no arm for Expr::App(BuiltinFn::Previous, ...); an array-valued PREVIOUS(pop[*]) reaching it would hit the catch-all sim_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_values buffer (no array-view variant); ArraySum / ArrayMean / ArrayStddev / ArrayMin / ArrayMax opcodes (Opcode::ArraySum {} at vm.rs:2013, etc.)
  • src/simlin-engine/src/compiler/codegen.rs -- BuiltinFn::Previous arm (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 at builtins_visitor.rs:130); how is PREVIOUS(pop[*]) (an array-valued arg of SUM) rewritten?
  • src/simlin-engine/src/ltm_augment.rs -- wrap_non_matching_in_previous / build_partial_equation_shaped (the LTM side that produces pop[r] / SUM(PREVIOUS(pop[*]))); generate_auxiliary_to_auxiliary_equation in db_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 the prev_values buffer (a LoadPrevView-style opcode, or a prev_values flag on the view-push) so reducers iterate previous-timestep slots correctly. This is the principled fix and would also unblock PREVIOUS(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 is PREVIOUS(<scalar-helper-for-SUM(pop[*])>) -- i.e. snapshot the reducer's scalar output, not the array inside it. (This is what already happens for share[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 produces pop[r] / SUM(PREVIOUS(pop[*])) instead of pop[r] / PREVIOUS(SUM(pop[*])). Note tech-debt switch to new engine #26's own text claims the Bare link score is pop / 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 to LoadPrev) 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:

Activity

  1. added
    bug
    engine
    ltm
    on May 9, 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

    bugengineltm

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions