Skip to content

engine: make an MDL save keep the model it saves - #1076

Merged
bpowers merged 3 commits into
mainfrom
sweep/mdl-save
Oct 3, 2026
Merged

bpowers merged 3 commits into
mainfrom
sweep/mdl-save

Conversation

@bpowers

@bpowers bpowers commented Oct 3, 2026 •

Copy link
Copy Markdown
Owner

Why

A fresh-eyes review of the MDL (Vensim) reader and writer found that a save could re-import as a different model: arrayed variables changed dimensions, elements were respelled, PULSE and INTEGER/MODULO had the wrong meaning, and a variable named dt was written dt = dt. Some saves were equations Vensim refuses, and some files aborted the reader.

What

  • Reader:
    • a per-axis dimension rule: a named dimension of exactly the elements defined, else the smallest, first declared; canonical element keys; a deterministic build order;
    • one space normalization for definitions and references;
    • a variable the model declares as dt or pi is read as the variable;
    • number lists, including with :EXCEPT:;
    • INTEGER/MODULO as the engine's TRUNC/REM, and QUANTUM for a quantum at or below zero (Vensim's fn_integer, fn_modulo, fn_quantum pages; the rounding and subscripted_round outputs in test/);
    • PULSE/PULSE TRAIN per fn_pulse, fn_pulse_train and pulsetrain.dat;
    • sketch elements kept in a map, a bound on subscript ranges and products, and two XMILE reader panics fixed, so a file's contents do not abort a host.
  • Writer:
    • number lists, grouped left-hand sides, and :EXCEPT: over the variable's dimensions or a subrange its default names, else element equations with a warning;
    • references spelled as definitions; builtins as Vensim's keywords; VMAX/VMIN/VECTOR RANK; bit-exact numbers;
    • warnings for NaN, a nested ACTIVE INITIAL, functions Vensim lacks, and partial arrays.
  • Engine: TRUNC/REM builtins; QUANTUM/REM arguments must share units; TRUNC propagates link polarity; the LTM zero-slot classifier reads builtin signatures.
  • Agent docs: the MCP Vensim syntax skill's tables corrected.

Decisions worth a reviewer's eye

  • Where Vensim's behavior could not be checked, the engine does the simple thing and says so in one line: PULSE widths of half a step or less, MODULO with a negative divisor, an excepted element nothing defines (it stays undefined), a wrong-length number list (refused).
  • The writer does not re-read its own output. An earlier round had a write-time read-back guard; it caught nothing and was deleted. The corpus save gate and the property test are the check, offline.
  • "The smallest declared dimension holding the defined elements" is Simlin's rule, not Vensim's: Vensim has no per-variable dimension.
  • trunc and rem are now reserved call names, and QUANTUM(x, q <= 0) returns its input for every format.

Evidence

  • Corpus gates, in release: every corpus .mdl keeps its datamodel through a save, with no exceptions listed, and every written equation obeys Vensim's subscript-range rule. On the save-meaning table, 64 MDL saves that used to change their model now keep it; 51 rows remain, each with a cause. The Vensim-truth gate pins each differing series by name (667 series) and fails both when a listed series starts matching and when an unlisted one differs.
  • Parity with Vensim's own output: measured by the adversarial reviewer over all 509 corpus files against main: 500 series newly match and none that matched was lost. No XMILE-origin series moves, bit for bit, across 247 files. INTEGER/MODULO/QUANTUM account for 35 of the moved series, in 2 files, all closer to Vensim.
  • Property tests: what is generated reads back, and the first save is a fixed point in text and in datamodel (clean at 4,000 cases).
  • Robustness: 153,000 mutated corpus inputs read and 47,000 projects written with no panic in the MDL reader or writer; 1,052 fuzz inputs replayed through both readers after the last round, 0 panics.
  • LTM: World3's 1,314 LTM series are bit-identical under the signature-driven classifier and the previous name list.
  • Review: two adversarial passes by a reviewer that did not write the code. The first found a reader abort and :EXCEPT: equations that broke Vensim's rule; the second found two saves the fix round had regressed. All are fixed and pinned.
  • Rebased onto main as of engine: read tables by kind and keep projects in protobuf #1071, engine: keep flow order and reach every reference in patches #1072 and engine: count a run's steps and read its rows by time #1075: with engine: read tables by kind and keep projects in protobuf #1071's lookup fix, subscripted_lookups moves from differing to matching Vensim, and the three DELAY FIXED models move from differing to refused.
  • The pre-commit hook passed in full on the rebased branch.

What this does not establish

  • That Vensim reads a saved file: no save was run in Vensim.
  • Rules taken from Vensim's pages rather than its output: PULSE widths of half a step or less, PULSE TRAIN intervals, MODULO with a negative divisor.
  • The dt/pi reading moves no corpus series, so it rests on the rule, not on Vensim output.
  • Warned rather than exact: functions Vensim lacks (ROUND, INT, MOD), conveyors and queues, an :EXCEPT: default naming a mapped range (written as element equations), variables over some elements of a dimension.
  • An XMILE PULSE saved as MDL can still differ for intervals that are not binary fractions; the writer's expression should be rewritten against the engine's pulse rule as engine: count a run's steps and read its rows by time #1075 states it, which is a follow-up.
  • The corpus gates are ignored tests that no CI job runs yet.

Fixes #1059

🤖 Generated with Claude Code

https://claude.ai/code/session_01LYR7N9WZwQuFnZFW8JDUgx

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 3, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-03T04:23:30.980726Z 47f6607 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@codecov

codecov Bot commented Oct 3, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 94.57014% with 108 lines in your changes missing coverage. Please review.
✅ Project coverage is 92.70%. Comparing base (afdc027) to head (e975765).

Files with missing lines Patch % Lines
src/simlin-engine/src/mdl/writer_arrayed.rs 91.76% 54 Missing ⚠️
src/simlin-engine/src/mdl/writer_proptest.rs 91.52% 29 Missing ⚠️
src/simlin-engine/src/mdl/convert/control.rs 97.11% 7 Missing ⚠️
src/simlin-engine/src/mdl/convert/variables.rs 96.09% 5 Missing ⚠️
src/simlin-engine/src/mdl/convert/stocks.rs 94.00% 3 Missing ⚠️
src/simlin-engine/src/units_check.rs 88.46% 3 Missing ⚠️
src/simlin-engine/src/mdl/xmile_compat.rs 98.58% 2 Missing ⚠️
src/simlin-engine/src/mdl/convert/dimensions.rs 98.07% 1 Missing ⚠️
src/simlin-engine/src/mdl/convert/helpers.rs 93.33% 1 Missing ⚠️
src/simlin-engine/src/mdl/convert/mod.rs 96.15% 1 Missing ⚠️
... and 2 more
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1076      +/-   ##
==========================================
+ Coverage   92.66%   92.70%   +0.04%     
==========================================
  Files         308      311       +3     
  Lines      188506   190063    +1557     
==========================================
+ Hits       174672   176194    +1522     
- Misses      13834    13869      +35     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@claude

claude Bot commented Oct 3, 2026

Copy link
Copy Markdown

Review of PR #1076

Reviewed the full diff (~14k lines) with focus on correctness bugs in the MDL reader/writer, engine builtins (TRUNC/REM/QUANTUM), VM/WASM lowering, LTM polarity, XMILE panic fixes, and unit checking.

Findings: none that meet the bar for flagging.

Specific areas verified:

  • TRUNC/REM/QUANTUM: VM quantum() helper, BuiltinId::Rem = a - quantum(a,b), Trunc = a.trunc(), and the WASM emit_quantum sequence all agree (both use <= so NaN divisor propagates identically; select operand order verified against the comment if b<=0.0 {a} else {(a/b).trunc()*b}). Matches Vensim ground truth in test/test-models/tests/rounding/output.tab.
  • LTM zero-slot classifier (classify_builtin_reach): the signature-driven filter (Invariance::Pure + ResultKind::Elementwise + min_args > 0 + all args Scalar) correctly captures the previously hand-maintained set and new additions; PI/INF special-cased; time globals and TIME stay Varying.
  • LTM polarity: BuiltinFn::Trunc added to the non-decreasing arm is sound (Trunc is strictly non-decreasing).
  • XMILE reader panic fixes in xmile/variables.rs and xmile/model.rs: get_noncanonical_name returning Option<&str> with is_some_and in get_var, and unwrap_or_default() on empty <dimensions> are correct; existing call sites filter Var::Unhandled before the unreachable!() arm.
  • Writer dimension/element formatting: format_mdl_element_key correctly handles missing dim slots, indexed_element bounds-checks (1..=size).contains(&position), declared_element canonicalizes with trim().
  • view::types::VensimView migration from sparse Vec<Option<_>> to BTreeMap<i32, _>: uid_span() returns max_uid + 26 matching the old elements.len() after resize(idx + 26, None); transform_view_coordinates uses it with saturating_add, and the test with 12999999999999999999998 and i32::MAX UIDs demonstrates safety.
  • PULSE/PULSE TRAIN semantics in xmile_compat.rs: the new comparisons (TIME + DT / 2 > start AND TIME + DT / 2 < start + width, with pulse_width folding literal 0 to DT) match the Vensim documentation and the simulated rows in pulse_tests.rs.
  • Unit checking for REM/QUANTUM: check_matching is correctly extracted from the old inline MAX/MIN logic; the inferer emits the matching a/b constraint uniformly.

Caveats (surfaced by comments in the code, not bugs):

  • REM(a, b<=0) = 0 is stated as "unverified against Vensim"; Vensim docs give two definitions that disagree for b<0. The code picks one and says so; no in-repo ground truth settles it.
  • PULSE widths of half a step or less are unverified in a Vensim run.

Overall correctness verdict: correct. The patch is internally consistent across VM/WASM/codegen/LTM/units, has extensive proptest and corpus-gate coverage, and the save-meaning table ratchets both ways so a regression on any corpus file fails CI.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 47f6607237

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

pub fn uid_span(&self) -> i32 {
self.elements
.last_key_value()
.map_or(0, |(uid, _)| uid.saturating_add(26))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Avoid saturating composed view UIDs

When the first view in a multi-view MDL contains a UID at or above i32::MAX - 25—a case the new map representation explicitly permits—this clamps its span to i32::MAX. compose_views consequently assigns that offset to the next view, and convert_view saturating-adds every positive local UID there to the same i32::MAX value. Elements in subsequent views therefore receive duplicate UIDs, so links and aliases can attach to the wrong element; use checked wider arithmetic or reject/remap overflowing UIDs instead of saturating them.

Useful? React with 👍 / 👎.

return Vec::new();
};
let held: HashSet<Vec<String>> = slots.iter().map(|slot| key_parts(&slot.0)).collect();
product(axes)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Bound EXCEPT warning expansion

When an arrayed variable has an :EXCEPT: default the writer cannot represent—for example, an external-data default—this eagerly materializes the full Cartesian product solely to enumerate undefined elements in a warning. A compact sparse model with four 100-element dimensions therefore attempts to allocate 100 million key vectors and then an enormous message during save, which can hang or exhaust the process; cap/count/sample this diagnostic expansion behind the same kind of production threshold used by the importer, and exercise that threshold through a tiny test-only override.

AGENTS.md reference: AGENTS.md:L93-L95

Useful? React with 👍 / 👎.

Comment thread src/simlin-engine/src/mdl/writer.rs Outdated
Comment on lines +265 to +266
if is_mdl_quoted_ident(name) {
return name.to_owned();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Escape newlines inside pre-quoted identifiers

When a project supplied by XMILE or the API contains an already-quoted identifier whose interior has a real newline, this early return emits that newline verbatim even though the new rustdoc promises the \n escape. Because format_sketch_name delegates here too, the newline splits the comma-delimited sketch record as well as the equation identifier, producing an MDL file that cannot reliably re-import; preserve underscores without bypassing newline and trailing-backslash escaping for the quoted interior.

AGENTS.md reference: AGENTS.md:L117-L120

Useful? React with 👍 / 👎.

The MDL reader and writer disagreed on arrayed dimensions, element
spelling, PULSE, INTEGER/MODULO, names and groups, so a save could
re-import as a different model, and the writer could write equations
Vensim refuses.

The reader settles each axis on a named dimension of exactly the
elements defined, else the smallest, first declared (GH #1059). It keys
elements canonically, spells a reference as its definition does, and
reads a declared `dt` or `pi` as the variable. It imports INTEGER and
MODULO as TRUNC and REM, and PULSE / PULSE TRAIN as the comparisons
Vensim documents. It refuses a list of the wrong length and a range or
product past a bound rather than guess or abort.

The writer names dimensions through number lists, grouped left-hand
sides and :EXCEPT: equations, never writing one that defines no
element. It keeps subscript ranges on their left-hand side, writes a
builtin as Vensim's keyword and a variable as its name, and warns where
MDL cannot hold the model.

save_roundtrip_tests, writer_proptest, import_determinism_tests,
mdl_vensim_truth and save_meaning's table hold the reader and writer to
this.
The writer's pass that spells a view element's name as its definition
is written used SharedVec::edit_each, which main replaced with update:
a pass that reads an element and returns its replacement, so it cannot
change one and leave it out. The pass returns the renamed element.
The warning for an :EXCEPT: default that cannot be written built the
whole product of the variable's elements to name the ones only the
default defines: four dimensions of 100 elements took 90 seconds and a
1.67 GB message on save. It names a dozen, walking the product lazily,
and counts the rest by arithmetic.

An already-quoted name was written as it stands, a real newline inside
it included, which splits the equation and the sketch record that
names it. A newline is written as the escape, and a final backslash is
doubled so it cannot escape the closing quote.
@bpowers

bpowers commented Oct 3, 2026

Copy link
Copy Markdown
Owner Author

Follow-up commit e975765 for the Codex review:

  • Bound the EXCEPT warning's expansion: taken. The warning names a dozen of the elements only the default defines, walking the product lazily, and counts the rest by arithmetic. Four dimensions of 100 elements took 90 s and a 1.67 GB message before; the_elements_a_dropped_default_defines_are_named_a_few_and_counted runs in a millisecond.
  • Newlines inside pre-quoted identifiers: taken. A quoted name's interior is written as it stands except that a real newline becomes the \n escape and a final backslash is doubled (a_quoted_name_holding_a_line_break_is_written_with_the_escape: the save reads back).
  • Saturating composed view UIDs: declined. It needs a sketch UID within 25 of i32::MAX; no file has one, and the saturating arithmetic already keeps a hostile one from aborting the reader.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

engine: MDL reader declares partially defined subscripted variables over the full dimension and fabricates zeros for undefined elements

1 participant