Skip to content

mdl: one file imports differently from run to run #859

Closed

Description

@bpowers

Importing the same .mdl file in two separate processes could give two different models, and different simulation results.
An import should be a function of the file.

Example

test/test-models/tests/subscript_transposition/test_subscript_transposition.mdl declares two dimensions with the same five elements, sector and sector1.
Over 40 runs of simlin simulate, output2 came out two ways: all NaN, or 480, 4800, 480, 640, -96.
Vensim's run beside the fixture gives 109, 1090, 109, 141, -13.
The same split showed in arrays_cname.mdl, arrays_varname.mdl (sdeverywhere) and subscript_switching.mdl: which dimension a variable was declared over, and whether a bang subscript was imported as * or Dim.*, changed from run to run.
With LTM on, the set of loop-score variables and the warnings changed too.

Why it matters

Silent wrong numbers that change between runs, on test models with Vensim ground truth.
In-process determinism tests could not see it, because a process seeds its hash maps once.

Cause

When two dimensions of the same size share elements, the importer gave the elements to whichever dimension a HashMap yielded first.
That one choice decided the declared dimension and the * vs Dim.* spelling.
A second instance: resolving a per-element equation's mapped dimensions iterated a HashMap.

Status

Both are now decided in declaration order (element_owners in convert/dimensions.rs; build_element_context in convert/variables.rs).
import_determinism_tests.rs imports every corpus file 13 times and requires one result (each map has its own seed, so this works in one process), and mdl_vensim_truth.rs holds the first three fixtures to Vensim's output (subscript_switching does not simulate, for an unrelated reason).

Pointers

  • src/simlin-engine/src/mdl/convert/dimensions.rs: element_owners
  • src/simlin-engine/src/mdl/import_determinism_tests.rs
  • src/simlin-engine/tests/integration/mdl_vensim_truth.rs

Activity

  1. bpowers commented on Aug 26, 2026

    @bpowers
    OwnerAuthor

    This reaches simulation output: silent wrong numbers, not just round-trip non-idempotence

    Re-confirmed independently during the compiler-unification Phase 6(a) differential sweep (2026-08-26), which ran a pre-change and a post-change CLI over all 509 models under test/. 397 models were byte-identical and 110 refused identically; the only three movers were all explained by this nondeterminism rather than by the change under test.

    The issue as filed frames the impact as importer datamodel differences plus EXPECTED_NON_IDEMPOTENT round-trip churn, and notes #847's writer change "masks the bug at the corpus re-parse ratchet". The masking is narrower than that reads: the same seed-dependent classification changes simulated values, and both outcomes exit 0. Measurements below use the prebuilt release CLI, N separate processes of the same binary, counting distinct md5sums of the whole TSV.

    model runs distinct convert --to xmile distinct simulate
    test/test-models/tests/subscript_transposition/test_subscript_transposition.mdl 40 2 2 (21/19)
    test/sdeverywhere/models/arrays_varname/arrays_varname.mdl 40 4 2 (17/23)
    test/sdeverywhere/models/arrays_cname/arrays_cname.mdl 40 4 2 (22/18)

    The nondeterminism is entirely upstream of compile

    Feeding each captured XMILE variant back through simlin simulate 40 times gives 1 distinct output per variant, for all 6 captured variants. So compile and simulation are deterministic; the whole split is introduced at import, which is exactly this issue's scope. (Worth stating explicitly because the natural first hypothesis — a HashMap reaching DimensionsContext or the compiled artifact — is disconfirmed here.)

    Manifestation 1 confirmed, and it produces wrong numbers

    subscript_transposition splits precisely along the Wildcard-vs-StarRange axis this issue describes:

    < SUM(input[*] * io_matrix[*, sector1])
    > SUM(input[sector.*] * io_matrix[sector.*, sector1])
    

    Vensim DSS 7.3.4 ground truth is checked in beside the fixture (output.tab, contributed by Eneko Martin, 12/02/20). Its two dimensions have identical element lists (sector1 and sector, both agriculture, industry, transport, tourism, comercial). Vensim's output2 is 109, 1090, 109, 141, -13. The engine gives, per process:

    • variant A: output2 = all NaN
    • variant B: output2 = 480, 4800, 480, 640, -96

    Neither matches. output (the non-transposed spelling) is 111, 251, 319, 495, 527 in both and does match Vensim, so the ambiguity only bites the transposed read.

    A third manifestation: the variable's declared dimension list

    Beyond the two manifestations already listed, arrays_varname varies in which dimension a variable is declared over — the <dim name> entries, not a wildcard binding. Two independent axes compose into the 4 datamodels:

    <dim name="DimA">   vs   <dim name="DimX">
    <dim name="DimC">   vs   <dim name="DimC&apos;">
    

    Here DimA is A1, A2, A3 and DimX is SubA, A1 where SubA: A2, A3 — the same element set in a different order. The DimC/DimC' axis is semantically inert (same elements, same order) and does not move values; the DimA/DimX axis does, which is why 4 datamodels collapse to 2 outputs.

    The wrong-number form here is a label/value mismatch, not a reordering. In one variant the element keys and values agree (inputab[a1,b1]=11 … inputab[a3,b3]=19) but the reducer p[DimA] = SUM(inputAB[DimA, DimB!]) reports:

    p[a1] = 45    p[a2] = 54    p[a3] = 36     <- a1's own row is 11,12,13 -> 36
    

    i.e. p[a1] carries a2's row sum under a1's label. The other variant gives the correct 36, 45, 54.

    Why no test catches it

    • Neither arrays_varname nor arrays_cname is in tests/integration/simulate.rs's corpus — they are commented out there (~line 2147, "xmutil drops subscript mappings in XMILE conversion").
    • subscript_transposition appears only in tests/integration/mdl_roundtrip.rs's EXPECTED_NON_IDEMPOTENT list, which says nothing about simulated values. Its Vensim output.tab therefore sits in the tree as unused ground truth.
    • fragment_determinism_tests / diagnostic_determinism_tests repeat 12 times inside one process, where RandomState is seeded once, so they are structurally blind to a per-process split.

    Suggested additions to the fix

    Beyond the ordered-container fix already proposed here:

    1. Decide and document what a reference means when two dimensions share an element set. Per CLAUDE.md this is a claim about an external system, so docs/reference/xmile-v1.0.html should be checked before choosing rather than reasoned from.
    2. Add a cross-process determinism guard — run one model in N subprocesses and compare — since the existing determinism suites cannot see this class.
    3. Once deterministic, add subscript_transposition to tests/integration/simulate.rs's corpus so its Vensim ground truth is actually asserted.

    Note for whoever picks this up

    Phase 6(a) separately fixes the transposed star-range/temp-name defect, which moves subscript_transposition's variant A from all-NaN to exactly Vensim's 109, 1090, 109, 141, -13. Variant B (480, 4800, …) is untouched and remains this issue.

  2. added
    bug
    engine
    on Aug 26, 2026
  3. bpowers commented on Sep 4, 2026

    @bpowers
    OwnerAuthor

    Root cause located (one site), plus three LTM-side faces of the same flip

    Re-confirmed on compiler-unification-v2 (PR #1040), where the design doc names arrays_cname, arrays_varname and subscript_transposition as "GH #859 flippers" and excludes them from its artifact claims. Everything below is pre-existing on main.

    The single site

    The body above says the root cause "needs confirmation via instrumentation". It is now confirmed by reading and by reproduction, and it is one tie-break, not a set of unordered iterations:

    src/simlin-engine/src/mdl/convert/dimensions.rs, build_dimensions Phase 4 (lines 75-89):

    let mut dims_by_size: Vec<_> = self.dimension_elements.iter()   // HashMap
        .map(|(name, elems)| (name.clone(), elems.clone())).collect();
    dims_by_size.sort_by_key(|(_, elems)| std::cmp::Reverse(elems.len()));  // stable
    for (dim_name, elements) in dims_by_size {
        for elem in elements {
            self.element_owners.entry(canonical_name(&elem)).or_insert_with(|| dim_name.clone());

    The sort is stable and keyed on cardinality only, so two dimensions of EQUAL size that share elements are ordered by HashMap (RandomState) iteration order, and the first one claims the elements. Every fixture that flips has exactly that shape:

    fixture tied dimensions (size)
    arrays_cname.mdl, arrays_varname.mdl DimA (3: A1,A2,A3) vs DimX (3: SubA+A1); DimC (3) vs DimC' (3 -- DimC': DimC is a subscript definition that expands recursively to the same three elements, not an <-> equivalence)
    subscript_switching.mdl Cats (5) vs dummy (5, identical list)
    subscript_transposition.mdl sector (5) vs sector1 (5, identical list)

    Two consumers of element_owners turn the winner into every manifestation listed in this issue:

    1. expand_subscript (dimensions.rs:349): a per-element slot x[A1] is declared over the element's OWNER, so the variable's <dim name> is DimA on one seed and DimX on another (manifestation 3 in the comment above).
    2. Implicit-subrange detection in convert/mod.rs:238-255 (and the same test in resolve_subrange_to_parent, dimensions.rs:415-425): the LOSER of the tie is classified as a subrange of the winner and put in XmileFormatter::subrange_dims, so its bang subscript formats as Dim.* (xmile_compat.rs:184-190, 678-684) while the winner's formats as * (manifestations 1 and 2).

    So Wildcard vs StarRange, "which dimension the wildcard binds to", and "which dimension the variable is declared over" are one bit, chosen per process. Other first-match loops over the same HashMap in convert/variables.rs (build_element_context ~line 878, build_subrange_mappings ~line 921, both break on the first hit) are hash-ordered too; I have not shown them to flip anything, but a fix should sweep them.

    The field comment on element_owners says "First/largest match wins like xmutil's owner assignment". The "first" it intends is presumably definition order, which self.dimensions (a Vec, in file order) already preserves; iterating that instead of dimension_elements would make the tie deterministic in the sense the comment describes. Which of two identical dimensions Vensim itself treats as the owner is a claim about an external tool and should be checked against the checked-in ground truth (subscript_switching/output.tab, subscript_transposition/output.tab, sdeverywhere's arrays_* expected output) rather than reasoned from; the earlier comment's suggestions 1-3 still apply.

    Reproduction (release CLI, convert --to xmile, 12 fresh processes per model)

    • subscript_switching.mdl: 2 distinct outputs (6/6). The whole diff is the bang spelling, in both directions:
      < Gain * SUM(Transition_Matrix[*, dummy] * Categories[*])
      > Gain * SUM(Transition_Matrix[Cats.*, dummy] * Categories[Cats.*])
      < Gain * SUM(Transition_Matrix[Cats, dummy.*] * Categories[Cats])
      > Gain * SUM(Transition_Matrix[Cats, *] * Categories[Cats])
      < SUM(Categories[*])
      > SUM(Categories[Cats.*])
      
    • arrays_cname.mdl: 4 distinct outputs (the DimA/DimX axis times the DimC/DimC' axis), matching the comment above.

    Three new faces, all in Loops That Matter

    The CLI shows only the already-known face: arrays_cname / arrays_varname under simulate --ltm flip stdout 2 ways exactly as plain simulate does (same 513-column set, different column ORDER and values -- d[a2],d[a3],d[a1] vs d[a1],d[a2],d[a3], inputab[a2,b1]=14 vs inputab[a1,b1]=11 in the first slot), and subscript_switching.mdl --ltm is refused identically for both import variants (failed to compile fragments for variables: categories). The faces below were seen through the branch's in-engine harnesses: the corpus LTM dump (model_ltm_variables output) and the diagnostics corpus (collect_all_diagnostics with LTM enabled), run 3x per binary on two binaries.

    (b) The discovery-mode LTM variable SET varies per process. arrays_cname.mdl produced 38 LTM variables on one run and 58 on another (V9b report: on the DimX side the shared-name reads are described, on the DimA side they are not); arrays_varname.mdl and subscript_switching.mdl "flip within a side" over 3 runs (V9b reviews). The branch lead's harness runs recorded discovery counts of 27/31/38 for arrays_varname and 54/83/84 for subscript_switching across processes; those specific figures are as reported, not re-reproduced here.

    (c) LTM-discovery DIAGNOSTICS for arrays_cname.mdl are 0 or 3 warnings depending on process state (Phase 9 review: base binary 0/3/0 over three runs, tree binary 3/3/3 in isolation and 0 inside the full corpus run). A diagnostics-are-a-function-of-the-model gate (the #999 / #1003 invariant) therefore flaps on this model even with every emission site sorted.

    (d) Engine-generated LTM aggregate equation TEXT flips. For subscript_switching.mdl the synthetic aggregate node's equation is sum(transition_matrix[cats, *:dummy] * ...) on one seed and sum(transition_matrix[cats, *] * ...) on another (V9a review D8, 4 runs each on both binaries, probes/repeat-eqs.sh). This is the dummy.* spelling from the reproduction above parsed as IndexExpr0::StarRange and printed as *:dummy; the LTM Reduced axis treats a StarRange over a proper subdimension differently from a bare wildcard (GH #766, ltm_agg.rs), which is why the variable set and the detected loops move with the spelling.

    Downstream-of-import check: each captured XMILE variant run 5x under simulate --ltm gives exactly one stdout digest, one sorted-stderr digest and one raw-stderr digest per variant. The LTM faces are a deterministic function of the imported datamodel; there is no second nondeterminism on the LTM side of these models.

    Not to be conflated with #1036: that issue is warning ORDER with a stable set (an LTM emission loop over a HashMap); this is CONTENT -- which LTM variables exist, what their equations say, and how many warnings are produced.

    Why the branch's harnesses caught it and the suites do not

    Same reason as the comment above: the determinism suites repeat inside one process. The branch's sweeps run N separate processes per binary and count distinct digests, which is what separates a flipper (same digest SET on both binaries) from a mover. An LTM-enabled row in whatever cross-process guard closes this issue would pin faces (b)-(d); the existing plain-output guard would not.

  4. changed the title [-]engine: MDL importer subscript/dimension classification is non-deterministic across process hash seeds[/-] [+]mdl: one file imports differently from run to run[/+] on Oct 12, 2026
  5. bpowers commented on Oct 12, 2026

    @bpowers
    OwnerAuthor

    Closing: already fixed on main.

    PR #1076 (f629e96): element_owners (src/simlin-engine/src/mdl/convert/dimensions.rs:503) iterates dimensions in declaration order with a stable sort, and build_element_context (convert/variables.rs:962) resolves mapped dimensions in LHS order with sorted rounds. mdl/import_determinism_tests.rs imports every corpus .mdl 13 times and requires one result, and tests/integration/mdl_vensim_truth.rs requires subscript_transposition, arrays_cname and arrays_varname (unlisted in EXPECTED, so class Matches) to match Vensim's output.

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