Skip to content

engine: an iterated-dimension subscript over an undeclared, disjoint-named axis reads by ordinal on the static subscript path and is refused on the dynamic one #1044

Closed

Description

@bpowers

Problem

A subscript that names the dimension an apply-to-all equation iterates, read against a source axis declared over a DIFFERENT dimension with which it shares no element name and no declared mapping (equal cardinality), is executed by two rules on compiler-unification-v2 (PR #1040, head 78d0195a), and which rule fires is decided by an unrelated sibling index of the same reference:

Spelling Route Result
target[state] = m[state, 1] * w static: normalize_subscripts3 -> IndexOp::ActiveDimRef -> build_view_from_ops compiles, reads by ORDINAL (target[s1] reads m[a, c], target[s2] reads m[b, c])
target[state] = m[state, idx] * w (idx an aux) dynamic: lower_dynamic_subscript -> lower_index_expr3, IndexExpr3::Dimension arm refused: mismatched_dimensions -- m

The state index is spelled identically in both; only the sibling (1 vs idx) differs. Both were measured with target/debug/simlin simulate built from 78d0195a.

Reproduction (the V9b review's q17a / q17b probes)

Shared declarations (sim_specs Euler, start 0, stop 4, dt 1):

<dimensions>
  <dim name="region"><elem name="a"/><elem name="b"/></dim>
  <dim name="state"><elem name="s1"/><elem name="s2"/></dim>
  <dim name="d2"><elem name="c"/><elem name="d"/></dim>
</dimensions>
<model name="main"><variables>
  <stock name="level">
    <element subscript="a"><eqn>100</eqn></element>
    <element subscript="b"><eqn>200</eqn></element>
    <inflow>inflow</inflow>
    <dimensions><dim name="region"/></dimensions>
  </stock>
  <aux name="w"><eqn>1 + TIME / 100</eqn></aux>
  <aux name="m"><eqn>level[region] * (1 + TIME / 50)</eqn>
    <dimensions><dim name="region"/><dim name="d2"/></dimensions></aux>
  <flow name="inflow"><eqn>SUM(target[*]) * 0.01</eqn>
    <dimensions><dim name="region"/></dimensions></flow>

q17a (static sibling) -- compiles, ordinal:

  <aux name="target"><eqn>m[state, 1] * w</eqn>
    <dimensions><dim name="state"/></dimensions></aux>
time  ...  m[a,c]  m[a,d]  m[b,c]  m[b,d]  target[s1]  target[s2]  w
0     ...  100     100     200     200     100         200         1

target[s1] = 100 = m[a, c] and target[s2] = 200 = m[b, c]: s1 (ordinal 0 in state) indexes region at 0 (a), s2 at 1 (b). No mapping between state and region is declared anywhere in the model.

q17b (dynamic sibling) -- refused:

  <aux name="idx"><eqn>IF TIME > 2 THEN 1 ELSE 2</eqn></aux>
  <aux name="target"><eqn>m[state, idx] * w</eqn>
    <dimensions><dim name="state"/></dimensions></aux>
error in model 'main' variable 'target': mismatched_dimensions -- m
error compiling model 'main': SimulationError{not_simulatable: failed to compile fragments for variables: target}

Where the two rules live

Which spellings reach the static path. compiler::subscript::normalize_subscripts3 (src/simlin-engine/src/compiler/subscript.rs) returns Some(ops) only when EVERY index of the reference is static: * / *:Sub over a declared relation, a range with constant or element-name bounds, @N with N >= 1, a numeric literal, an element name of the axis, Dim.N in range, or the name of a declared dimension that Subscript3Config::active_dim_ref can pair with an active axis. Any index that is a variable reference or computed expression (idx, TIME, i + 1, INT(x)), or a range with such bounds, returns None -- for the WHOLE reference. Context::lower_subscript (src/simlin-engine/src/compiler/context.rs) then hands every index, including the dimension-named one, to lower_dynamic_subscript -> lower_index_expr3. (lower_static_subscript also returns None for an @N sibling inside an apply-to-all body, which is how the corpus's LOOKUP table arguments reach the dynamic arm.)

Static path: ordinal last resort. build_view_from_ops's IndexOp::ActiveDimRef arm resolves the active element on the source axis by name, then through DimensionsContext::resolve_mapped_read (name, declared map, mapped parent), and then -- only when has_mapping_to / has_mapping_to_parent_of find nothing declared in either direction -- falls back to active_dim.get_offset(subscript).filter(|o| *o < dim.len()): the active element's ordinal in its OWN dimension, indexing the source axis raw. The comment there says it mirrors Context::resolve_iteration_element's target_offset fallback (target_dim.get_offset(subscript) when no source offset resolves and no declared mapping failed), which is the same ordinal last resort for the wildcard and pass-0 bare spellings (target[state] = m[*, 1], target[state] = x).

Dynamic path: refusal. lower_index_expr3's IndexExpr3::Dimension arm builds by_name.chain(by_mapping) candidates and tries resolve_mapped_read on each; with nothing declared and no shared name every candidate misses and the arm returns sim_err!(MismatchedDimensions). It has no declared-check-then-ordinal step. Its comment still asserts that "its static twin build_view_from_ops has no such fallback at all" and that "both paths REFUSE an unresolvable subscript rather than one of them inventing an index" -- true for the indexed-numeral case it was written about, and no longer true for a named active dimension since the static twin gained the ordinal arm.

The IndexExpr3::Expr(Expr3::Var(dim-name)) arm of the same function (reached when Expr3::from_expr2 did not classify the name as IndexExpr3::Dimension) has a third behaviour: name-identity, else parse::<usize>() of the active element, else it lowers the dimension name as a variable reference.

Which of this is pre-existing on main, and which is new in PR #1040

On main (5c406dd5) the split between static and dynamic siblings does not exist for this spelling. Pass 1 (ast/expr3.rs::transform_index_expr_inner) folds any IndexExpr3::Dimension naming an ACTIVE dimension to IndexExpr3::Expr(Const(ordinal)) -- the active element's 1-based index within its own dimension, with no look at the source axis -- before normalize_subscripts3 runs. Both q17a and q17b therefore arrive as m[<const>, ...] and read by ordinal. Measured with a release simlin built from 5c406dd5 (2026-09-03): q17a gives target[s1] = 100, target[s2] = 200 at t=0, and q17b compiles and gives the same target series (idx 2 then 1, both columns of m being equal at every step). GH #997's table and Phase 6b's ledger entry 2 in docs/design-plans/2026-08-25-compiler-unification.md describe the same fold. main's build_view_from_ops has no ordinal arm at all (it ends in resolve_mapped_read(...)?) and its dynamic Dimension arm already refuses, but for this spelling neither is reachable except under the DimensionRefs::Preserve contexts (LOOKUP table arguments) that skipped the fold -- where both paths refuse, consistently.

Phase 6b (be7adbbf, "engine: one materialization pass over the lowered fragment", branch-only) deleted the Pass-1 fold so that every dimension-named subscript resolves through resolve_mapped_read (the subrange_merge correction), and to keep the mapped_reference_semantics_tests::no_mapping_* cells green it added the ordinal last resort to build_view_from_ops. The dynamic twin was not given the same last resort. That is what turns "one rule (ordinal) per spelling" into "two rules keyed on the sibling".

What IS pre-existing on main is that the undeclared disjoint pair has no single decided rule ACROSS spellings: no_mapping_equal_cardinality (identical on main and the branch) pins IteratedDim and BareInEquation as reads [10, 20, 30] and SourceOwnDim and StockFlow (get_implicit_subscript_off) as MismatchedDimensions refusals. PR #1040 adds a fifth row -- the iterated spelling with a dynamic sibling -- to the refusal side.

What the other tools say

  • Vensim's subscript-mapping reference (https://www.vensim.com/documentation/ref_subscript_mapping.html, fetched 2026-09-03): "Normally, an equation such as Quality[product] = work quality[worker type] would generate an error." A mapping (worker type : wtclay, wtplastic, wtwood -> product) is "an indication to Vensim that a Subscript that appears on the right but not the left of an equation has a valid interpretation." Vensim's rule for the undeclared pair is refusal.
  • XMILE v1.0 section 3.7.1 (docs/reference/xmile-v1.0.html): "A dimension name is a placeholder for the subscript index used by the element in which the equation appears", bound "to (replaced by) their index in that dimension". Its only examples are same-dimension (revenue[Location, Product] = sales[Location, Product]); it defines no mapping and does not say what an unrelated dimension of equal size reads. The reading is Simlin's to define.

Why it matters

  • A silent wrong number and a loud refusal for one spelling. A modeller who has target[state] = m[state, col] refused and "fixes" it by making col a constant gets a model that compiles and silently reads region by state's ordinal. The reverse edit turns a running model into a refusal with a diagnostic (mismatched_dimensions -- m) that names nothing about the sibling that caused it.
  • Loops That Matter carries a carve-out to describe this. DimensionsContext::executed_read_correspondence deliberately declines the undeclared disjoint pair (dimensions.rs, test an_undeclared_pair_with_disjoint_names_declines), db::analysis::bare_axis_pairing collapses it to a broadcast, and the element graph / score admission decline the edge loudly (engine CLAUDE.md, the LTM rules list: "The one executed read the describers leave undescribed is the ordinal fallback of an undeclared pair with disjoint element names at equal cardinality (GH ltm: expand_same_element is over-conservative for mapped dimensions (full cross-product instead of the positional-mapping diagonal) #527); it is declined loudly, never described positionally"; the design doc's "Phase LTM semantic divergences (V9b)"). LTM keeps that carve-out precisely because it cannot describe two rules. With one rule the carve-out goes either way: an ordinal read is describable (executed_read_correspondence gains the same last-resort arm), and a refused read has nothing to describe.
  • The dynamic arm's comment documents a parity that no longer holds, so the next reader of lower_index_expr3 is told the two paths agree.

Components affected

  • src/simlin-engine/src/compiler/subscript.rs -- build_view_from_ops, IndexOp::ActiveDimRef arm (the ordinal last resort); normalize_subscripts3 (decides which references stay static).
  • src/simlin-engine/src/compiler/context.rs -- lower_index_expr3, IndexExpr3::Dimension arm (the refusal, and the stale "both paths refuse" comment) and IndexExpr3::Expr(Var) arm; resolve_iteration_element's target_offset fallback (the same ordinal rule for the wildcard/bare spellings); get_implicit_subscript_off (refuses the stock/flow spelling).
  • src/simlin-engine/src/dimensions.rs -- resolve_mapped_read / executed_read_correspondence rustdoc (states the ordinal as "the one read this rule does not cover").
  • src/simlin-engine/src/mapped_reference_semantics_tests.rs -- no_mapping_equal_cardinality, no_mapping_unequal_cardinality (pin the per-spelling table; have no dynamic-sibling row).
  • LTM consumers of the carve-out: db/analysis.rs (bare_axis_pairing), db/element_graph_tests.rs, ltm_agg.rs, ltm_augment_partial_error.rs, ltm_augment_post_transform.rs, axis_match_tests.rs, engine CLAUDE.md.

The ask: decide ONE rule and pin it

Either is coherent; what is not coherent is choosing per path.

  1. Refusal everywhere (Vensim's documented rule). Delete the ordinal last resort from build_view_from_ops and the target_offset fallback from resolve_iteration_element (or gate it on a declared relation the way build_view_from_ops's declared check already does); flip no_mapping_equal_cardinality's IteratedDim and BareInEquation rows to Refused(MismatchedDimensions) and add a dynamic-sibling row; the LTM carve-out becomes dead and is deleted (an_undeclared_pair_with_disjoint_names_declines stays, now as a description of execution rather than a "deliberate superset"). Cost to check: whether any model in test/ or the sdeverywhere corpus relies on the equal-size positional read (the Phase 6b sweep reports nothing the base compiles being refused, but that sweep ran with the ordinal arm present).
  2. Ordinal everywhere (Simlin's own definition, since XMILE leaves it open). Give lower_index_expr3's Dimension arm (and the Expr(Var) arm) the same declared-check-then-ordinal last resort, ideally by moving that step INTO resolve_mapped_read so there is one function rather than two copies; add the dynamic-sibling row to no_mapping_* as Reads; give executed_read_correspondence the same last resort and delete the LTM decline, so the element graph and scores describe the diagonal the VM reads. This also makes SourceOwnDim and StockFlow questions to answer explicitly rather than by omission.

Whichever is chosen, the gate is mapped_reference_semantics_tests with a row per (spelling, sibling kind) so the decision is pinned against the VM, not read off the lowering, and the dynamic arm's parity comment is rewritten to say what is true.

Context

Surfaced by the V9b review of PR #1040 (compiler-unification-v2), probes q17a / q17b, 2026-09-03. Related: #527 (closed; the LTM carve-out's origin), #997 (closed; resolve_mapped_read as the one executed rule, whose rustdoc names the ordinal as the read it does not cover), #1029 (subrange dimension reference reads positionally -- a different pair relation, a subrange of the same parent), #1035 (the hoisted module-function argument reading the iterated dimension by ordinal under a declared map -- the same "ordinal vs rule" split at a different site), #756 / #753 (the declared-map family Phase 6b addresses).

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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions