Skip to content

engine: transposed star-range (sparse subdimension) view reads all-NaN -- ArrayView::transpose keeps stale SparseInfo.dim_index #1027

Closed

Description

@bpowers

Summary

Transposing an array view that carries a star-range over a non-contiguous subdimension (arr[*:Sub, *]') produces a view whose sparse mapping points at the wrong axis. SUM(...) over it evaluates to NaN and MAX(...) to -inf with exit code 0 -- a silent wrong number on a legal XMILE expression. The untransposed star-range (SUM(arr[*:Sub, *])) and the dense transpose (SUM(arr[*, *]')) are both correct, so this is distinct from the closed #422 (dense-transpose NaN).

Reproduces identically at a510a1c0 and earlier; it is pre-existing and not introduced by any compiler-unification commit.

Reproduction

<dimensions>
    <dim name="Parent"><elem name="A"/><elem name="B"/><elem name="C"/><elem name="D"/></dim>
    <dim name="Sub"><elem name="A"/><elem name="C"/></dim>   <!-- non-contiguous in Parent -->
    <dim name="Other"><elem name="X"/><elem name="Y"/><elem name="Z"/></dim>
</dimensions>
<model>
    <variables>
        <aux name="arr">
            <element subscript="A, X"><eqn>11</eqn></element>
            <element subscript="A, Y"><eqn>12</eqn></element>
            <element subscript="A, Z"><eqn>13</eqn></element>
            <element subscript="B, X"><eqn>21</eqn></element>
            <element subscript="B, Y"><eqn>22</eqn></element>
            <element subscript="B, Z"><eqn>23</eqn></element>
            <element subscript="C, X"><eqn>31</eqn></element>
            <element subscript="C, Y"><eqn>32</eqn></element>
            <element subscript="C, Z"><eqn>33</eqn></element>
            <element subscript="D, X"><eqn>41</eqn></element>
            <element subscript="D, Y"><eqn>42</eqn></element>
            <element subscript="D, Z"><eqn>43</eqn></element>
            <dimensions><dim name="Parent"/><dim name="Other"/></dimensions>
        </aux>
        <!-- rows A and C, all columns: 11+12+13+31+32+33 = 132 -->
        <aux name="s_star"><eqn>SUM(arr[*:Sub, *])</eqn></aux>
        <!-- the same selection transposed: still 132; MAX still 33 -->
        <aux name="s_star_t"><eqn>SUM(arr[*:Sub, *]')</eqn></aux>
        <aux name="mx_star_t"><eqn>MAX(arr[*:Sub, *]')</eqn></aux>
        <!-- control: a contiguous transpose of the full array, 12 elements sum 324 -->
        <aux name="s_full_t"><eqn>SUM(arr[*, *]')</eqn></aux>
    </variables>
</model>

(sim_specs: Euler, start 0, stop 1, dt 1.)

Variable Expected Observed
s_star = SUM(arr[*:Sub, *]) 132 132
s_full_t = SUM(arr[*, *]') 324 324
s_star_t = SUM(arr[*:Sub, *]') 132 NaN
mx_star_t = MAX(arr[*:Sub, *]') 33 -inf

MAX = -inf with a non-empty view means every element read NaN (the fold if v > acc { v } else { acc } from -inf only stays at -inf if no element compares greater), so this is not a single bad element.

Root cause (verified by reading)

SparseInfo.dim_index is an index into the view's dims, but the dimension-reordering transforms on ast::ArrayView reverse/permute dims, strides, and dim_names while cloning sparse unchanged:

  • src/simlin-engine/src/ast/array_view.rs -- ArrayView::transpose (reverses dims/strides/dim_names, then sparse: self.sparse.clone()).
  • src/simlin-engine/src/ast/array_view.rs -- ArrayView::reorder_dimensions (same pattern, used by compiler/context.rs apply_dimension_reordering on an existing StaticSubscript view).

Upstream, compiler/subscript.rs (the IndexOp::SparseRange arm of the second pass, ~lines 453-462) sets dim_index: output_dim_idx correctly for the untransposed view. compiler/context.rs then applies view.transpose() to that view for ' (the Expr::StaticSubscript(base, view, _) => StaticSubscript(base, view.transpose(), ..) arm in the UnaryOp::Transpose lowering, ~line 2006). Downstream copies the stale index verbatim:

  • compiler/codegen.rs array_view_to_static_in (~lines 406-444): dim_index: s.dim_index as u8 into StaticArrayView.sparse.
  • VM: bytecode.rs StaticArrayView::to_runtime_view clones sparse into RuntimeView; RuntimeView::flat_offset (~line 318) finds the mapping with s.dim_index as usize == i and remaps offsets[idx] along that axis.
  • wasm backend: wasmgen/views.rs ViewDesc::from_static copies dim_index; ViewDesc::flat_element_offset / flat_offset_for_indices (~lines 246-295) address through it the same way at lowering time.

Both RuntimeView::apply_single_subscript (bytecode.rs ~line 388) and ViewDesc::apply_single_subscript_dynamic (wasmgen/views.rs ~line 220) do renumber dim_index when they remove an axis, so the invariant is understood on the runtime side; the AST-level transpose/reorder_dimensions are the transforms that violate it.

For the probe, arr[*:Sub, *] builds dims=[2,3] strides=[3,1] sparse=[{dim_index:0, parent_offsets:[0,2]}]. After transpose: dims=[3,2] strides=[1,3] sparse=[{dim_index:0, parent_offsets:[0,2]}] -- the mapping now claims the size-3 Other axis is the sparse one (with only 2 offsets) and the size-2 Parent axis is dense (so it walks rows A, B instead of A, C). Correct would be dim_index: 1.

Open question on the runtime route to NaN

By reading, the direct PushStaticView -> ArraySum -> reduce_view -> flat_offset path would index parent_offsets[2] on a 2-element mapping once the iteration reaches index 2 along the mis-tagged axis -- a bounds-check panic, not a NaN. The probe instead produced all-NaN with exit 0, so the reducer is reaching its operand through some other route: most plausibly a NaN-filled temp (fill_temp_nan) that is never written, or the per-element NaN that LoadIterViewAt returns for an unmatched dimension / out-of-bounds index (vm.rs, the broadcasting path). The reviewer did not trace past reduce_view. Whoever fixes this should confirm the route, and should expect that other spellings of the same defect (e.g. a larger subdimension along a transposed axis) may panic rather than NaN -- the fix is the same either way, but the test should cover both the reducer and an element-wise consumer.

Why it matters

  • Correctness / silent wrong number: a legal XMILE expression (star-range over a proper subdimension, then ') yields NaN/-inf with no diagnostic, and the NaN propagates downstream. This is exactly the class of defect the no-silent-wrong-numbers invariant exists to prevent.
  • Both backends: the VM and the wasm backend lower the same StaticArrayView, so both are wrong in the same way.
  • Hidden by the test matrix: wasmgen/views.rs static_view_geometries_address_like_vm rows a transpose and a star range separately but not composed; array_tests.rs transpose_tests has no subdimension row; no test/ corpus model combines *:Sub with '.

Components affected

  • src/simlin-engine/src/ast/array_view.rs (transpose, reorder_dimensions)
  • src/simlin-engine/src/compiler/context.rs (UnaryOp::Transpose lowering, apply_dimension_reordering)
  • consumers: compiler/codegen.rs, bytecode.rs (RuntimeView), wasmgen/views.rs (ViewDesc)

Suggested fix

  1. In ArrayView::transpose and ArrayView::reorder_dimensions, renumber each SparseInfo.dim_index through the same permutation applied to dims (for transpose: new = len - 1 - old; for reorder_dimensions: new = position of old in reordering). Any future dim-reordering transform must do the same -- consider a single private helper that permutes dims/strides/dim_names/sparse together so the four cannot drift.
  2. Add a debug assertion (or a unit test over every constructor/transform) that every sparse[i].dim_index < dims.len() and parent_offsets.len() == dims[dim_index], which would have caught this at construction.
  3. Tests:
    • wasmgen/views.rs static_view_geometries_address_like_vm: add the "transpose applied on top of a star range" row (its rustdoc on branch compiler-unification already names this as the un-rowed case and says it is tracked separately -- this issue is that tracking; repoint the comment here).
    • ast/array_view.rs: unit tests that transpose/reorder_dimensions of a sparse view keep parent_offsets.len() == dims[dim_index].
    • A simulate test (e.g. array_tests.rs transpose_tests) with the probe above: s_star_t == 132, mx_star_t == 33, plus an element-wise consumer of the transposed star-range view.

The compiler-unification plan's Phase 6(a) (one DimMatcher, Subscript-arm decomposition) rewrites this code and should carry the fix rather than leaving the stale-index behaviour to be re-implemented.

Context

Identified during the compiler-unification review (2026-08-26) while cross-checking the wasm ViewDesc against the VM's RuntimeView for every baked static-view geometry. Probe confirmed at a510a1c0. Not a duplicate of #422 (dense-transpose reduction NaN, closed; its control row passes here) or #766 (LTM read-slice coarseness for StarRange, closed).

Activity

  1. added
    bug
    engine
    on Aug 26, 2026
  2. bpowers commented on Aug 26, 2026

    @bpowers
    OwnerAuthor

    Fixed on the compiler-unification branch, in the Phase 6(a) chunk (not yet merged; the PR will carry Fixes #1027). The issue's reading of ArrayView::transpose is correct, but it is not why the probe read NaN, and the defect is larger than one spelling. Both halves had to be fixed together.

    The open question, answered

    The route is a NaN-filled temp, not a bad address. Instrumenting Vm::reduce_view on the probe shows what each reducer actually reads:

    P6A_TRACE reduce_view storage=Curr dims=[2, 3] strides=[3, 1] offset=0 sparse=[(0, [0, 2])] dim_ids=[0, 2] size=6   <- s_star, correct (132)
    P6A_TRACE reduce_view storage=Temp dims=[2, 3] strides=[3, 1] offset=0 sparse=[]             dim_ids=[1, 2] size=6   <- s_star_t / mx_star_t
    P6A_TRACE reduce_view storage=Temp dims=[4, 3] strides=[3, 1] offset=0 sparse=[]             dim_ids=[0, 2] size=12  <- s_full_t, correct (324)
    

    SUM(arr[*:Sub, *]) reduces the static view directly and is right. SUM(arr[*:Sub, *]') reduces a temp: Pass 1 hoists the transposed subscript into an AssignTemp, and the temp's dim_ids are [1, 2] = [Sub, Other] while the source static view's are [0, 2] = [Parent, Other]. LoadIterViewAt's broadcast path runs match_dimensions_two_pass, cannot pair Parent with Sub, takes its "no matching dimension" branch and pushes NaN for every element. The temp is written, entirely with NaN; SUM folds to NaN and MAX stays at its -inf seed. So the stale SparseInfo.dim_index was never consulted on this path.

    The larger defect

    The dim_id mismatch is two statements of one fact disagreeing:

    • ast/expr2.rs (Expr1::Subscript's bounds) names a star range's axis for the subdimension -- its comment says "Use the subdimension name, not the parent dimension";
    • compiler/subscript.rs build_view_from_ops named it for the parent, with a TODO saying it should not.

    So any star range that goes through a temp read NaN, transposed or not, contiguous subdimension or not. Measured on the pre-change CLI (Parent{A,B,C,D}, Sub{A,C} non-contiguous, Con{A,B} contiguous, Other{X,Y,Z}):

    equation expected before after
    SUM(arr[*:Sub, *]) 132 132 132
    SUM(arr[*:Sub, *]') 132 NaN 132
    MAX(arr[*:Sub, *]') 33 -inf 33
    SUM(arr[*, *]') 324 324 324
    SUM(arr[*:Con, *]) 102 102 102
    SUM(arr[*:Con, *]') 102 NaN 102
    SUM(arr[*:Sub, *] * 2) 264 NaN 264
    SUM(arr[*:Con, *] * 2) 204 NaN 204
    SUM(arr[*, *] * 2) 648 648 648
    SUM(row[*:Sub]) 5 5 5
    SUM(row[*:Sub]') 5 NaN 5
    SUM(row[*:Sub] * 2) 10 NaN 10
    out[Other,Sub] = arr[*:Sub, *]' (per element) 11,31,12,32,13,33 correct correct

    The per-element consumer was never broken: it resolves through the active element rather than through a temp.

    Why both halves are needed

    Fixing only the name leaves the transposed case reaching RuntimeView::flat_offset with the stale mapping and indexing a 2-element parent_offsets at 2 -- the bounds panic the issue predicted, which under panic = abort takes the host process rather than returning an error. Fixing only the renumbering leaves every one of the NaN rows above NaN. So: other spellings of this defect do not panic, they read NaN, and it is the fix for the name that turns the transposed one into a would-be panic.

    The fix

    1. ArrayView::transpose and reorder_dimensions are one private permute_axes(order) that moves dims, strides, dim_names and every SparseInfo.dim_index through the same permutation, with a debug assertion on the result that each mapping names an axis of the view and supplies one parent offset per element of it. Two existing tests built malformed sparse fixtures (a 2-offset mapping on a size-3 or size-4 axis) and now use a well-formed star-range view.
    2. IndexOp::Range and IndexOp::SparseRange carry the dimension the axis ranges over, so build_view_from_ops names a star-range axis for the subdimension and the TODO is gone.

    Tests

    • tests/integration/simulate.rs::transposed_star_range_over_a_noncontiguous_subdimension_reads_its_own_selection -- this issue's probe model plus the untransposed-through-a-temp and per-element rows, VM values derived from the rules, then ensure_wasm_matches so both backends are pinned.
    • ast/array_view.rs -- transpose_renumbers_a_sparse_axis, reorder_dimensions_renumbers_a_sparse_axis, transpose_renumbers_every_sparse_axis.
    • wasmgen/views.rs::static_view_geometries_address_like_vm -- the "transposed star range of a 4x3" row; its docstring no longer says the composed geometry is un-rowed and tracked here.

    Corpus evidence

    A differential sweep of a pre-change and a post-change CLI over all 509 models under test/: 397 byte-identical, 110 refused identically on both. The only movers were two models that flip between the same two outputs on both binaries (GH #859, an importer nondeterminism this change does not touch) and test/test-models/tests/subscript_transposition, which carries genuine Vensim DSS 7.3.4 ground truth (output.tab) that no test asserts: its transposed output2 goes from all-NaN to exactly Vensim's 109, 1090, 109, 141, -13, while the untransposed output matches in both. C-LEARN's compiled artifacts are byte-identical, plain and under CLEARN_LTM=1.

  3. bpowers commented on Aug 27, 2026

    @bpowers
    OwnerAuthor

    Confirmed against the complete acceptance in 6cf3660b on main: sparse-axis permutation is centralized, transpose and general reordering renumber SparseInfo.dim_index, production simulation covers the non-contiguous star-range reducer and elementwise forms with absolute values, and the composed static-view geometry has VM/wasm parity. Closing directly because that fix is already in the PR #1032 base rather than its diff.

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

    bugengine

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions