Skip to content

engine: fix mdl roundtrip edge cases - #332

Merged
bpowers merged 5 commits into
mainfrom
engine/fix-mdl-roundtrip-325-329
Feb 26, 2026
Merged

bpowers merged 5 commits into
mainfrom
engine/fix-mdl-roundtrip-325-329

Conversation

@bpowers

@bpowers bpowers commented Feb 25, 2026

Copy link
Copy Markdown
Owner

Summary

  • preserve MDL view titles by adding name: Option<String> to datamodel::StockFlow and wiring it through MDL/XMILE/JSON/protobuf conversion paths
  • fix format_f64 to emit finite MDL-compatible sentinels for +/-infinity instead of Rust's inf/-inf
  • refactor stock MDL emission to handle Equation::Scalar, Equation::ApplyToAll, and Equation::Arrayed so INTEG initial values are never dropped for arrayed stocks
  • emit type-1 flow pipe connector geometry from flow.points, including endpoint attachment connectors and intermediate waypoints
  • add targeted regression tests covering infinity formatting, view title roundtrip, arrayed stock INTEG reconstruction, and flow pipe connector serialization

Testing

  • cargo test -p simlin-engine mdl::writer::tests::
  • cargo test -p simlin-engine mdl::view::convert::tests::test_build_single_view
  • cargo test -p simlin-engine json_proptest::
  • cargo test -p simlin-engine --features file_io --test simulate simulates_models_correctly
  • full pre-commit hook suite via git commit

Fixes #325
Fixes #326
Fixes #328
Fixes #329

@claude

claude Bot commented Feb 25, 2026

Copy link
Copy Markdown

Code Review

I reviewed all 15 changed files in this PR. The changes cover five distinct areas:

  1. Adding name: Option<String> to StockFlow wired through MDL/XMILE/JSON/protobuf paths
  2. format_f64 infinity sentinel handling
  3. Arrayed stock INTEG reconstruction (Scalar, ApplyToAll, Arrayed)
  4. Flow pipe connector (type-1) emission from flow.points
  5. Regression tests for each fix

Areas examined closely:

  • Protobuf backward compatibility: Field string name = 7 on View is a new tag in proto3; old serialized data will deserialize to "", correctly converted to None via serde.rs:1767. No issues.
  • Arrayed stock entry formatting: Intermediate entries use ~~| separator, final entry carries units/docs via write_units_and_comment. Correct MDL format.
  • write_flow_pipe_connectors iterator logic: skip(1).take(len.saturating_sub(2)) correctly produces 0 intermediate points for lengths 0, 1, and 2. Endpoints handled separately with attachment checks.
  • format_f64 NaN behavior: NaN falls through to format!("{}", v) both before and after this change — no regression.
  • merge_views setting name: None: Correct — the merged view is synthetic and no single original name would be appropriate.
  • v.name.clone() in xmile/views.rs:2178: Necessary because &v is borrowed on line 2187 for ViewObject::from. Not a bug.

Findings

No bugs found. The changes are well-structured, properly wired through all conversion paths, and covered by targeted regression tests. The protobuf versioning is correct (additive field with unused tag).

Overall Correctness

Correct. The patch should not break existing code or tests, and is free of bugs.

@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: 762d9ff52f

ℹ️ 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".

Comment on lines +1080 to +1082
*next_connector_uid,
valve_uid,
valve_uid,

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 Avoid emitting valve-to-valve flow connectors

For flows with intermediate waypoints (flow.points.len() > 2), this loop writes type-1 connectors with both endpoints set to the valve UID. On MDL import, mdl/view/convert.rs::convert_connector applies valve indirection on both sides and turns those lines into variable-to-variable links (often a flow linking to itself), so exporting then re-importing mutates the diagram by adding bogus causal links. This regression is triggered specifically by bent flow pipes with interior points.

Useful? React with 👍 / 👎.

@codecov

codecov Bot commented Feb 25, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 95.12195% with 10 lines in your changes missing coverage. Please review.
✅ Project coverage is 79.69%. Comparing base (94647e1) to head (ff9aaf9).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
src/simlin-engine/src/mdl/writer.rs 94.28% 6 Missing ⚠️
src/simlin-engine/src/mdl/view/processing.rs 91.11% 4 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #332      +/-   ##
==========================================
+ Coverage   79.61%   79.69%   +0.08%     
==========================================
  Files         134      134              
  Lines       32650    32820     +170     
==========================================
+ Hits        25993    26157     +164     
- Misses       6657     6663       +6     

☔ View full report in Codecov by Sentry.
📢 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.

@bpowers

bpowers commented Feb 25, 2026

Copy link
Copy Markdown
Owner Author

@codex review

@claude

claude Bot commented Feb 25, 2026

Copy link
Copy Markdown

Code Review

I reviewed all 15 changed files in this PR covering five distinct improvements: view title preservation, infinity formatting, arrayed stock INTEG roundtrip, flow pipe connector emission, and self-connector filtering.

Analysis

View name field threading — The new name: Option<String> field on StockFlow is correctly wired through all conversion paths: datamodel, JSON, XMILE, protobuf, and MDL. The protobuf addition (string name = 7;) is backward compatible — old serialized data will have an empty string default, and the deserializer in serde.rs correctly maps empty string to None. The merge_views function reasonably drops individual names since a merged view has no single canonical title.

format_f64 infinity handling — Mapping +/-Infinity to +/-1e+38 is the standard Vensim sentinel convention. The implementation is clean and correctly prioritizes the infinity check before the truncation check.

Arrayed stock INTEG — The refactored write_stock_variable now correctly handles all three Equation variants. The MDL multi-definition separator (~~|) between arrayed elements is correct. Edge cases (empty elements, single element) are handled properly via saturating_sub.

Flow pipe connectors — The write_flow_pipe_connectors logic correctly emits endpoint connectors (valve→stock) for first/last points and self-connectors (valve→valve) for interior bend points. The iterator logic .skip(1).take(len.saturating_sub(2)) correctly selects only middle points. UID allocation via max_sketch_uid prevents collisions.

Self-connector filtering — The early-return in convert_connector for attached-valve self-connectors correctly prevents these flow-pipe geometry artifacts from becoming spurious causal links.

Findings

No bugs found. The changes are well-structured, backward compatible, and thoroughly tested with targeted regression tests for each fix.

Overall Correctness

Correct. The patch is free of bugs and blocking issues. All conversion paths are properly handled, protobuf compatibility is maintained, and edge cases are addressed.

@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: aecfb85150

ℹ️ 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".

Comment thread src/simlin-engine/src/mdl/writer.rs Outdated
Comment on lines +1412 to +1413
let view_title = sf.name.as_deref().unwrap_or("View 1");
writeln!(self.buf, "*{}", view_title).unwrap();

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 Sanitize stock-flow view titles before MDL emission

write_stock_flow_view now writes sf.name directly into the *<title> line, but this field is accepted verbatim from JSON/protobuf/XMILE without validation. If a title contains a newline ("\n"/"\r"), the generated sketch header is split across lines and parse_views (in mdl/view/mod.rs) can no longer interpret the next line as the expected font/element content, breaking MDL round-trip parsing for that project. Replacing line breaks with spaces (or otherwise escaping them) before writing the title avoids producing malformed MDL.

Useful? React with 👍 / 👎.

@bpowers

bpowers commented Feb 25, 2026

Copy link
Copy Markdown
Owner Author

@codex review

@claude

claude Bot commented Feb 25, 2026

Copy link
Copy Markdown

Code Review

Reviewed the full diff across all 15 changed files. The PR fixes MDL roundtrip edge cases: view title preservation, infinity formatting, arrayed stock INTEG emission, and flow pipe connector geometry.

Analysis

Protobuf backward compatibility (serde.rs, project_io.proto): Tag 7 is new and unused by existing data. Proto3 string defaults to "", and the From impls correctly map "" ↔ None. Roundtrip is sound.

format_f64 infinity (writer.rs:624-630): Uses finite MDL-compatible sentinels (1e+38/-1e+38) — correct Vensim convention.

Stock equation refactor (writer.rs:710-802): All three Equation variants are handled with correct MDL formatting. write_arrayed_stock_entries properly uses ~~| separators between elements with units/comment only on the final entry. normalized_stock_initial safely defaults empty initials to "0".

Flow pipe connectors (writer.rs:1064-1125): The iterator logic skip(1).take(len.saturating_sub(2)) correctly isolates interior bend points for all edge cases (0, 1, 2, 3+ points). First/last endpoints use attached_to_uid, interior points use valve self-connectors.

Self-connector filtering (view/convert.rs:571-576): Correctly skips attached-valve self-connectors during MDL→datamodel conversion, preventing spurious causal links from flow pipe geometry.

max_sketch_uid (writer.rs:987-1003): Scans all element types plus valve UIDs to ensure generated connector UIDs never collide.

View title sanitization (writer.rs:1007-1025): Collapses CR/LF runs into a single space, preventing untrusted titles from breaking MDL sketch structure.

XMILE wiring (xmile/views.rs): Name attribute correctly serialized/deserialized via @name, conditionally emitted only when present.

Findings

No bugs found. The changes are well-structured with targeted regression tests for each fix. Protobuf versioning is backward compatible, MDL format output is correct, and edge cases are handled properly.

Verdict: Correct

The patch introduces no regressions. Existing code and tests will not break. All conversion paths (MDL, XMILE, JSON, protobuf) correctly wire the new name field, and the stock/flow emission fixes properly handle all equation variants and flow geometry.

@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: bd1297c867

ℹ️ 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".

}

Some(View::StockFlow(datamodel::StockFlow {
name: Some(view.title().to_string()),

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 Use unnormalized title when persisting MDL view names

build_views normalizes and deduplicates view titles via make_view_names_unique before convert_view, so storing view.title() here persists the rewritten value rather than the original MDL title. That means titles containing normalized punctuation (like /, -, *) or colliding names still change on MDL roundtrip, which breaks the new title-preservation behavior for those models.

Useful? React with 👍 / 👎.

Comment thread src/simlin-engine/src/serde.rs Outdated
elements: view.elements.into_iter().map(ViewElement::from).collect(),
view_box: view.view_box.map(Rect::from).unwrap_or_default(),
zoom: if approx_eq!(f64, view.zoom, 0.0) {
name: if name.is_empty() { None } else { Some(name) },

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3 Badge Preserve empty view titles during protobuf decode

This conversion maps an empty protobuf name to None, which collapses an explicit blank title into “no title.” For MDL inputs that intentionally use * with an empty title, a protobuf roundtrip will later re-emit the default View 1 instead of the blank title, so title fidelity is lost.

Useful? React with 👍 / 👎.

@claude

claude Bot commented Feb 26, 2026

Copy link
Copy Markdown

Code Review

I've reviewed the full diff for this PR covering view title preservation, infinity formatting, arrayed stock INTEG emission, flow pipe connector geometry, and the supporting protobuf/JSON/XMILE wiring.

Analysis

View title (StockFlow.name): The Option<String> is correctly threaded through all serialization paths. The protobuf encoding using name + has_name properly handles the proto3 limitation (no native optional for scalar strings), and backward compatibility for old data without has_name is correctly maintained (has_name=false, name="" → None). The title sanitization in sanitize_view_title_for_mdl correctly prevents newlines from breaking MDL's single-line *title format.

format_f64 infinity handling: Mapping +/-inf to 1e+38/-1e+38 (Vensim numeric sentinels) is correct and lossy-by-design. NaN still falls through to the format!("{}", v) branch as before.

Arrayed stock INTEG emission: The old code dropped initial values for ApplyToAll and Arrayed stocks (empty string → INTEG(net_flow, )). The new code correctly handles all three Equation variants, and normalized_stock_initial provides a sensible "0" default for empty equations. The ~~| separator between arrayed elements and terminal write_units_and_comment on the last element follows MDL conventions.

Flow pipe connectors in write_flow_pipe_connectors: The iterator logic skip(1).take(len.saturating_sub(2)) correctly isolates intermediate waypoints for all edge cases (0, 1, 2, and 3+ points). The max_sketch_uid function ensures next_connector_uid won't collide with existing element or valve UIDs. Endpoint connectors use (valve_uid, endpoint_uid) while bend-point connectors use (valve_uid, valve_uid), matching the MDL convention that the import side (convert_connector) now correctly filters.

UTF-8 marker: Adding {UTF-8}\n at the start of write_project is standard Vensim MDL format.

Findings

No bugs found.

Verdict

Correct. The patch is well-structured with targeted regression tests for each fix. Serialization roundtrips are properly covered, edge cases are handled, and backward compatibility with existing protobuf data is maintained.

@bpowers

bpowers commented Feb 26, 2026

Copy link
Copy Markdown
Owner Author

@codex review

@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: a9911cb85d

ℹ️ 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".

Comment on lines +1085 to +1087
*next_connector_uid,
valve_uid,
endpoint_uid,

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 Emit flow pipe connectors with parser-compatible valve IDs

The new flow-pipe connector serialization uses valve_uid as the connector source, but the MDL import path still derives attached-flow relationships from the assumption that the valve is adjacent to the flow (valve_uid == flow_uid - 1 in compute_flow_data, and cloud mapping uses conn.from_uid + 1 in is_cloud_endpoint). Because allocate_valve_uids can remap valves far away from flow.uid (for example, the new test case uses valve 100 for flow 6), reparsing writer output can no longer recover endpoint attachments or bend geometry, so the advertised flow-connector roundtrip is not preserved.

Useful? React with 👍 / 👎.

Address four MDL writer regressions from PR 324 by handling non-finite numeric formatting, preserving stock initial values across all equation variants, emitting flow pipe connector geometry, and carrying stock-flow view titles through conversion and serialization.

The changes keep behavior deterministic and backwards-safe by defaulting missing titles to View 1, using finite sentinels for infinities, and preserving existing output structure while extending the writer to handle previously dropped metadata.
Flow pipe interior bend points are encoded in MDL as type-1 connectors\nfrom an attached valve back to the same valve. Our connector converter\nwas applying valve indirection on both ends and incorrectly materializing\nthese geometry records as flow self-links during import.\n\nTreating attached-valve self-connectors as geometry preserves flow pipe\nserialization without introducing bogus causal links on re-import. Tests\nnow cover both convert_connector directly and the full build_views path.
StockFlow names are user-provided data and were written directly into the title sketch header line. Embedded CR/LF characters split the header across lines and made generated MDL sketch sections unparsable.

Normalize view titles to a single line at emission time by collapsing line-break runs to a single space. Add a regression test that writes a multiline title, verifies single-line emission, and roundtrips through parse_mdl with the sanitized title.
Fix two remaining title roundtrip regressions and align MDL output encoding.

First, build_views now preserves the original MDL view title for persisted StockFlow names instead of the normalized/deduplicated internal title used for composition. This keeps punctuation and collision-prone titles stable across MDL roundtrips.

Second, protobuf view serialization now carries an explicit title-presence bit so an intentionally blank title can roundtrip as Some() while still decoding legacy missing-name payloads to None. MDL writing now always starts with {UTF-8} on the first line, with regression coverage for all changes.
MDL import assumed attached valves always used , but the
writer can allocate non-adjacent valve UIDs to avoid collisions. That
caused flow endpoint/cloud connectors to lose their flow association on
roundtrip and produced detached flow endpoints.

Build a per-view attached valve<->flow mapping once and reuse it for
cloud detection, connector valve indirection, and flow endpoint
resolution. Keep legacy +1 adjacency as a fallback for compatibility,
and add regressions that cover non-adjacent valve IDs in both conversion
and full MDL roundtrip paths.
@bpowers
bpowers force-pushed the engine/fix-mdl-roundtrip-325-329 branch from ba3dcf5 to ff9aaf9 Compare February 26, 2026 01:24
@claude

claude Bot commented Feb 26, 2026

Copy link
Copy Markdown

Code Review

I reviewed all 16 changed files in this PR covering: view title preservation, infinity formatting, arrayed stock INTEG reconstruction, flow pipe connector serialization, and the supporting protobuf/JSON/XMILE plumbing.

Findings

No bugs found.

The implementation is well-constructed:

  • Protobuf backward compatibility is correctly handled. New fields name (tag 7) and has_name (tag 8) default to "" and false for old serialized data, which maps to name: None in the deserialization path. The has_name flag correctly distinguishes None from Some("").
  • build_attached_valve_flow_maps — The min-scan with tiebreaker (valve_uid < best_uid) produces deterministic results regardless of HashMap iteration order, since it examines all entries and always converges on the valve with the smallest UID among minimum-distance candidates.
  • write_arrayed_stock_entries correctly omits the dims parameter because Equation::Arrayed elements already carry their full subscript names (e.g., "north", "south"); dimension names are only needed for ApplyToAll.
  • Flow pipe connector iteration (skip(1).take(len.saturating_sub(2))) correctly handles all edge cases: 0 points, 1 point, 2 endpoints only, and multi-waypoint flows.
  • sanitize_view_title_for_mdl correctly collapses \r\n sequences into a single space (the prev_was_line_break flag prevents double-spacing).
  • next_connector_uid allocation starts after max_sketch_uid and is only incremented monotonically during flow element emission, which precedes links/clouds/aliases in the write loop, so no UID collisions are possible.
  • The {UTF-8} header addition, format_f64 infinity sentinels, and XMILE @name attribute round-trip are all consistent with existing patterns.

Test coverage is comprehensive — the new tests cover infinity formatting, view title roundtrip (including sanitization), arrayed stock INTEG for both ApplyToAll and Arrayed, flow pipe connector serialization, non-adjacent valve resolution, and self-connector filtering.

Overall Correctness Verdict

Correct. The patch is free of bugs and blocking issues. Existing code and tests will not break.

@claude

claude Bot commented Feb 26, 2026

Copy link
Copy Markdown

Code Review

I reviewed all 16 changed files in this PR covering: view title preservation, infinity formatting, arrayed stock INTEG handling, flow pipe connector emission, robust valve-flow UID mapping, UTF-8 marker, and protobuf/JSON/XMILE wiring.

Findings

No bugs found.

Analysis of Key Changes

Arrayed stock handling (writer.rs): The prior code silently dropped initial values for ApplyToAll and Arrayed stock equations (matched _ => String::new()). The new write_stock_entry / write_arrayed_stock_entries correctly emit per-element INTEG equations with the shared net_flow and per-element initial values. The ~~| separator between arrayed entries is standard MDL.

Valve-flow mapping (processing.rs): build_attached_valve_flow_maps correctly prefers the legacy flow_uid - 1 adjacency when available and falls back to nearest-position matching for non-adjacent UIDs. The tie-breaking on valve_uid < best_uid ensures deterministic pairing.

Flow pipe connectors (writer.rs): write_flow_pipe_connectors correctly emits: source endpoint connector, interior self-connectors (bend points), and sink endpoint connector. The skip(1).take(len.saturating_sub(2)) iteration correctly selects only interior waypoints.

Protobuf Option<String> encoding (serde.rs, project_io.proto): The has_name + name pattern correctly distinguishes None from Some(""). Deserialization with if has_name || !name.is_empty() provides forward compatibility with older writers that may set name without has_name.

Self-connector filtering (convert.rs): The new guard in convert_connector that returns None for attached-valve self-connectors (from_uid == to_uid) correctly identifies these as flow pipe geometry rather than causal links.

View title sanitization (writer.rs): sanitize_view_title_for_mdl correctly collapses \r\n, \n, \r runs into a single space, preventing injected newlines from breaking MDL sketch structure.

Overall Correctness Verdict

Correct. The patch is free of bugs and blocking issues. All changes are well-tested with targeted regression tests, the MDL format output is consistent with Vensim conventions, and the protobuf schema change is backward-compatible.

@bpowers

bpowers commented Feb 26, 2026 •

Copy link
Copy Markdown
Owner Author

Addressed the latest Codex feedback around MDL valve/flow roundtripping by removing the strict valve_uid + 1 assumption during import. The MDL view conversion path now builds a per-view attached valve↔flow mapping and reuses it consistently for cloud endpoint detection, connector valve indirection, and flow endpoint reconstruction. This keeps legacy adjacency behavior as a fallback while correctly handling writer-emitted non-adjacent valve IDs.

I also added regression coverage at two levels: an end-to-end project_to_mdl -> parse_mdl roundtrip test in mdl/writer.rs and a conversion-level test in mdl/view/convert.rs for non-adjacent attached valves. Review iteration count for this local feedback cycle: 1.

@bpowers
bpowers merged commit 2d8125e into main Feb 26, 2026
12 checks passed
@bpowers
bpowers deleted the engine/fix-mdl-roundtrip-325-329 branch February 26, 2026 01:41
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant