Repository navigation
Description
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(reversesdims/strides/dim_names, thensparse: self.sparse.clone()).src/simlin-engine/src/ast/array_view.rs--ArrayView::reorder_dimensions(same pattern, used bycompiler/context.rsapply_dimension_reorderingon an existingStaticSubscriptview).
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.rsarray_view_to_static_in(~lines 406-444):dim_index: s.dim_index as u8intoStaticArrayView.sparse.- VM:
bytecode.rsStaticArrayView::to_runtime_viewclonessparseintoRuntimeView;RuntimeView::flat_offset(~line 318) finds the mapping withs.dim_index as usize == iand remapsoffsets[idx]along that axis. - wasm backend:
wasmgen/views.rsViewDesc::from_staticcopiesdim_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/-infwith 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.rsstatic_view_geometries_address_like_vmrows a transpose and a star range separately but not composed;array_tests.rstranspose_testshas no subdimension row; notest/corpus model combines*:Subwith'.
Components affected
src/simlin-engine/src/ast/array_view.rs(transpose,reorder_dimensions)src/simlin-engine/src/compiler/context.rs(UnaryOp::Transposelowering,apply_dimension_reordering)- consumers:
compiler/codegen.rs,bytecode.rs(RuntimeView),wasmgen/views.rs(ViewDesc)
Suggested fix
- In
ArrayView::transposeandArrayView::reorder_dimensions, renumber eachSparseInfo.dim_indexthrough the same permutation applied todims(fortranspose:new = len - 1 - old; forreorder_dimensions:new = position of old in reordering). Any future dim-reordering transform must do the same -- consider a single private helper that permutesdims/strides/dim_names/sparsetogether so the four cannot drift. - Add a debug assertion (or a unit test over every constructor/transform) that every
sparse[i].dim_index < dims.len()andparent_offsets.len() == dims[dim_index], which would have caught this at construction. - Tests:
wasmgen/views.rsstatic_view_geometries_address_like_vm: add the "transpose applied on top of a star range" row (its rustdoc on branchcompiler-unificationalready 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 thattranspose/reorder_dimensionsof a sparse view keepparent_offsets.len() == dims[dim_index].- A simulate test (e.g.
array_tests.rstranspose_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
bpowers commentedon Aug 26, 2026
Fixed on the
compiler-unificationbranch, in the Phase 6(a) chunk (not yet merged; the PR will carryFixes #1027). The issue's reading ofArrayView::transposeis 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_viewon the probe shows what each reducer actually reads:SUM(arr[*:Sub, *])reduces the static view directly and is right.SUM(arr[*:Sub, *]')reduces a temp: Pass 1 hoists the transposed subscript into anAssignTemp, and the temp'sdim_idsare[1, 2]=[Sub, Other]while the source static view's are[0, 2]=[Parent, Other].LoadIterViewAt's broadcast path runsmatch_dimensions_two_pass, cannot pairParentwithSub, takes its "no matching dimension" branch and pushes NaN for every element. The temp is written, entirely with NaN;SUMfolds to NaN andMAXstays at its-infseed. So the staleSparseInfo.dim_indexwas never consulted on this path.The larger defect
The
dim_idmismatch 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.rsbuild_view_from_opsnamed it for the parent, with aTODOsaying 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}):SUM(arr[*:Sub, *])SUM(arr[*:Sub, *]')MAX(arr[*:Sub, *]')SUM(arr[*, *]')SUM(arr[*:Con, *])SUM(arr[*:Con, *]')SUM(arr[*:Sub, *] * 2)SUM(arr[*:Con, *] * 2)SUM(arr[*, *] * 2)SUM(row[*:Sub])SUM(row[*:Sub]')SUM(row[*:Sub] * 2)out[Other,Sub] = arr[*:Sub, *]'(per element)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_offsetwith the stale mapping and indexing a 2-elementparent_offsetsat 2 -- the bounds panic the issue predicted, which underpanic = aborttakes 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
ArrayView::transposeandreorder_dimensionsare one privatepermute_axes(order)that movesdims,strides,dim_namesand everySparseInfo.dim_indexthrough 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.IndexOp::RangeandIndexOp::SparseRangecarry the dimension the axis ranges over, sobuild_view_from_opsnames a star-range axis for the subdimension and theTODOis 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, thenensure_wasm_matchesso 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) andtest/test-models/tests/subscript_transposition, which carries genuine Vensim DSS 7.3.4 ground truth (output.tab) that no test asserts: its transposedoutput2goes from all-NaN to exactly Vensim's109, 1090, 109, 141, -13, while the untransposedoutputmatches in both. C-LEARN's compiled artifacts are byte-identical, plain and underCLEARN_LTM=1.engine: one dimension matcher and a decomposed subscript lowering
bpowers commentedon Aug 27, 2026
Confirmed against the complete acceptance in
6cf3660bonmain: sparse-axis permutation is centralized, transpose and general reordering renumberSparseInfo.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.