Skip to content

engine: read tables by kind and keep projects in protobuf - #1071

Merged
bpowers merged 4 commits into
mainfrom
sweep/engine-fidelity
Oct 3, 2026
Merged

bpowers merged 4 commits into
mainfrom
sweep/engine-fidelity

Conversation

@bpowers

@bpowers bpowers commented Oct 2, 2026 •

Copy link
Copy Markdown
Owner

Why

A fresh-eyes review of what landed between e6f95a6b and 5f2b7f94 looked at the four small engine fixes in that range as instances of bug classes, and went looking for the rest of each class. This is what it found in the engine and the formats. Each item below started as a failing probe test.

  • A graphical function's type decided nothing at simulation. The compiler dropped GraphicalFunctionKind, and the XMILE reader never read it: Gf.kind was declared as a child element where XMILE 4.1.3 makes type an attribute. An extrapolating or discrete table ran as a continuous one. Vensim's own documented example, LOOKUP EXTRAPOLATE(LOOK, 2.5) over LOOK((0,1),(1,1),(2,2)), gave 2.0 where the documentation says 2.5.
  • Vensim's DELAY FIXED ran as a first-order delay, a different function, with no diagnostic.
  • A project stored as protobuf lost a model's own simulation specs (the engine runs the root model under them) and the Vensim sketch metadata an MDL save writes back. The only round-trip property compared trip 2 with trip 3, which holds for a writer that drops a field.
  • model_links returned links in hash-map order: two opens of one file gave hosts differently ordered link lists in roughly 200 of 483 corpus files.
  • The web editor never showed the engine's reason for an equation error. It rendered the code's generic description; 40 engine codes collapse to "Generic error from core engine" on the wire.

What

  • Lookups. How a lookup reads its table is an operand of the lookup opcode, bytecode::LookupMode { Interpolate, Forward, Backward, Extrapolate }. A plain application takes the mode of the table's kind; LOOKUP FORWARD, LOOKUP BACKWARD and a new LOOKUP_EXTRAPOLATE builtin keep their own reading whatever the kind. The mode is on the opcode rather than the stored table because assembly de-duplicates tables by their points. A lookup that picks its table at run time across tables of different kinds is refused. The VM and wasm twins share one differential test over every mode.
  • One table. variable::parse_table refuses x that is not in ascending order (BadTable, citing XMILE 4.1.3, which says x values "MUST be in ascending order"), a reversed or non-finite x scale, and an infinite x. The MDL importer puts every lookup it builds in x order as it reads it, which is how Vensim reads a lookup in a model file (below). A GET DIRECT DATA or LOOKUPS series goes through the same one rule; that Vensim reads an external series this way is the engine's assumption, unverified. Nothing downstream knows about sorting.
  • The XMILE reader reads <gf type> leniently (trimmed, any case). A value it does not know opens as continuous and is reported as an import warning naming the variable, wherever the reader reads a <gf> (models, macro bodies, per-element tables); it never fails the open.
  • DELAY (DELAY FIXED) is refused on its variable (NotSimulatable, with a reason) instead of lowering to DELAY1. The MCP instructions and the Vensim-syntax skill say so.
  • Protobuf. project_io.proto gains Model.sim_specs, ViewElementCompat.shape/name_field/tail and View.sketch_compat. Fields are added, none renumbered, and an absent field reads as before. serde::deserialize returns a Result: a message that lacks what every writer writes is a ProtobufDecode error naming what is missing, where the reader panicked (an empty buffer decodes to such a message).
  • Link order. CausalEdgesResult.edges is a BTreeMap, so model_links returns (from, to) order.
  • Web editor. EquationError carries the engine's details, and ErrorDetails/VariableDetails render details ?? description.

Decisions worth a reviewer's eye

  • Out-of-order x is sorted on MDL import and refused everywhere else. Vensim DSS's own output for test/test-models/tests/subscripted_lookups reads a lookup listed with descending x as the curve through its points, and Vensim's documentation says "The Input/Output pairs are always stored in ascending x order" (ref_editing_lookups.html) and, in the 5.10b release notes, that out-of-order XY pairs are "now sorted before use". XMILE requires ascending order. So the sort lives in the importer and the datamodel holds one table. That evidence is about lookups in a model file; an external series (GET DIRECT DATA, GET DIRECT LOOKUPS) is sorted by the same rule, as the simple and likely reading, though Vensim's pages for those functions say nothing of row order. A project already stored from an MDL import with out-of-order x now gets BadTable on that variable; it used to run a binary search over unsorted points and answer garbage. One table of 558 in the corpus has this shape.
  • Points that share an x are a vertical step and are in order. Each mode reads a step by its own rule wherever in the table it sits, the same on both backends. That rule is the engine's own, unverified against Vensim and Stella; no corpus table has a repeated x.
  • DELAY FIXED is refused, not implemented. It needs a ring buffer sized at initialization and a third native per-step pass beside conveyors and queues (scoped at a few days, best done after the run-loop work). Six corpus models that had been simulating with a first-order delay in its place are now refused; none was in a run set against expected output.
  • <gf discrete="true">, a draft-format spelling, is reported and not acted on: that it means type="discrete" is unverified.
  • ISEE's AI information is not stored or written. The record is signed and the engine cannot sign.
  • Protobuf is kept only for stored server-side projects. The reader's Result is the simple fix; nothing checks that every decodable message is read or refused without a panic.

Evidence

  • Vensim ground truth: simulates_subscripted_lookups_mdl (fails without the importer sort); vensims_documented_lookup_examples_simulate_as_documented holds the LOOKUP FORWARD/BACKWARD/EXTRAPOLATE example values from the Vensim function pages.
  • XMILE: an_xmile_graphical_functions_type_decides_how_it_is_read; the three kinds match section 3.1.4 at, between and beyond knots.
  • VM against wasm: any table, any index, every mode, bit for bit (24 cases by default, 4,000 in the gate), plus a table-driven row for a vertical step at the first x, in the middle and at the last x.
  • Corpus, against a base build, 510 files: every model that ran is identical except subscripted_lookups, which now matches Vensim, and the six DELAY models now refused. Continuous lookups equal the base on about 808,000 lookups; tables without a repeated x at an end read as before on about 395,000.
  • Protobuf: round_trip(p) == normalize(p) on the first trip over generated projects (NaN, both zeros, both infinities and a subnormal included, compared bit for bit) and every corpus import; twelve stored projects read to checked-in goldens, pinned by SHA-256, and every schema field is on the wire of one of them, so renumbering a field fails (the mutation was run). A base-built reader reproduces the ten earlier goldens byte for byte.
  • Determinism: build_determinism builds every artifact twice from one file (three models by default, the corpus in the gate); before the change the link lists differed in about 200 of 483 files, after it none do.
  • Importer sort: one row per lookup syntax and shape, derived from the importer's arms; a skip-the-sort mutation in each arm fails.
  • Web editor: unit tests for both renderers and a real-engine row asserting an unknown-dependency error's reason names the variable. The hand-written error-code tables in TypeScript (two) and Python are held to simlin_error_str by tests.
  • Review: an adversarial review (33 mutations) and a follow-up check of its findings (25 more) ran against this change; the survivors they found are now pinned.
  • The pre-commit hook passed in full.

What this does not establish

  • Stella's reading of anything here, and what Vensim or Stella answers at a vertical step.
  • That discrete="true" means discrete, or that TABXL equals LOOKUP EXTRAPOLATE. The MDL writer still writes TABXL for a plain call on an extrapolating table, which this engine's reader has no builtin for; that is a follow-up in the MDL writer.
  • A browser journey for the error text: the tests are jsdom and engine-level.
  • The web lookup editor still draws every table as a clamped interpolated curve, whatever its kind.
  • setting_the_sim_specs_of_a_stored_project_changes_its_run is held as an expected failure: SetSimSpecs writes only the project's specs, so it is inert for a model that carries its own. The fix is in the patch layer and lands separately; that change removes the marker.
  • Reading of the production database: the stored projects are checked-in stand-ins.

🤖 Generated with Claude Code

https://claude.ai/code/session_01LYR7N9WZwQuFnZFW8JDUgx

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 2, 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-02T16:13:23.879881Z 89dfb69 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 2, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 91.80328% with 185 lines in your changes missing coverage. Please review.
✅ Project coverage is 92.59%. Comparing base (3104bef) to head (1ca7e6f).

Files with missing lines Patch % Lines
src/simlin-engine/src/project_io.gen.rs 78.49% 77 Missing ⚠️
src/simlin-engine/src/serde_proptest.rs 91.19% 75 Missing ⚠️
src/simlin-engine/src/serde.rs 93.72% 14 Missing ⚠️
src/simlin-engine/src/wasmgen/lookup.rs 98.26% 4 Missing ⚠️
src/simlin-engine/src/variable.rs 98.48% 3 Missing ⚠️
src/simlin-engine/src/builtins.rs 91.66% 2 Missing ⚠️
src/simlin-engine/src/compiler/codegen.rs 96.15% 2 Missing ⚠️
src/simlin-engine/src/units_check.rs 0.00% 2 Missing ⚠️
src/simlin-engine/src/units_infer.rs 0.00% 2 Missing ⚠️
src/simlin-engine/src/xmile/unread.rs 97.80% 2 Missing ⚠️
... and 2 more
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1071      +/-   ##
==========================================
+ Coverage   92.44%   92.59%   +0.15%     
==========================================
  Files         307      308       +1     
  Lines      184971   186894    +1923     
==========================================
+ Hits       170989   173048    +2059     
+ Misses      13982    13846     -136     

☔ 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.

@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: 89dfb6988f

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

return (x_vals, y_vals);
}
let mut points: Vec<(f64, f64)> = x_vals.into_iter().zip(y_vals).collect();
points.sort_by(|a, b| a.0.total_cmp(&b.0));

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 Preserve signed-zero step order during sorting

When an out-of-order MDL or external-data lookup contains a vertical step spelled with both -0.0 and +0.0, total_cmp treats those numerically equal x-values as distinct and moves -0.0 ahead of +0.0. The runtime lookup comparisons treat them as the same x, so this changes which y-value interpolation/forward/backward modes select at the step, contrary to the documented requirement that equal-x points retain their listed order. Treat numerically equal x-values as Equal before applying a total ordering for the remaining values.

AGENTS.md reference: src/simlin-engine/AGENTS.md:L105-L105

Useful? React with 👍 / 👎.

Comment on lines +432 to +435
let (x_points, y_points) = points_in_x_order(
pairs.iter().map(|(x, _)| *x).collect(),
pairs.iter().map(|(_, y)| *y).collect(),
);

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 Verify external-series ordering before sorting it

When GET DIRECT DATA or GET DIRECT LOOKUPS returns out-of-order x-values, this silently sorts the provider's rows even though the adjacent rustdoc expressly says Vensim's behavior for such data is undocumented and the chosen behavior is unverified. If Vensim rejects the series, consumes it in row order, or handles duplicate x-values differently, imported models now produce plausible but incorrect results instead of a BadTable diagnostic. Establish this behavior with real Vensim output and cite it, or leave the points untouched so the compiler refuses the unsupported ordering.

AGENTS.md reference: AGENTS.md:L105-L111

Useful? React with 👍 / 👎.

@claude

claude Bot commented Oct 2, 2026

Copy link
Copy Markdown

Review summary

Did a correctness pass on this PR focused on: lookup/table semantics (VM/WASM parity, edge clamps, vertical steps), protobuf serde (field numbering, missing-field refusals, writer/reader symmetry, backward compat), MDL/XMILE importers (x-order sort coverage, <gf type> attribute parsing, DELAY FIXED refusal), determinism (CausalEdgesResult::edges → BTreeMap), and the web editor's error-reason rendering.

No high-confidence correctness defects found. Verdict: correct.

Notable things that look right that I'd normally expect to see slip:

  • The flip in vm::lookup_forward from >= to > at the last-x edge and in vm::lookup_backward from <= to < at the first-x edge is exactly the change needed to let a vertical step at an end be read by the mode's own rule rather than clamped; the WASM twin mirrors it opcode-for-opcode.
  • extend_end_segment's dx == 0 || dy == 0 → end.1 guard correctly avoids 0 * inf = NaN for flat/vertical end segments on both backends.
  • Protobuf changes are strictly additive (Model.sim_specs=8, View.sketch_compat=10, ViewElementCompat.shape=4/name_field=5/tail=6); legacy stored projects read as before via unwrap_or/None.
  • Compiler::lookup_mode correctly refuses runtime-selected lookups across differently-kinded tables (as NotSimulatable) rather than silently using one kind for all.
  • points_in_x_order is reached from every pair-building path in the MDL importer (lookup definitions, WITH LOOKUP, GET DIRECT DATA, GET DIRECT LOOKUPS) and uses total_cmp on a stable sort, so vertical steps keep their listed order.
  • The TypeScript ErrorCode tables in src/core/errors.ts and src/engine/src/errors.ts are identical copies and now pinned to libsimlin's names via new tests in both languages.

Minor cosmetic observations (not blocking):

  • serde.rs ~line 668: a bad <gf> inside an arrayed element's slot doesn't go through variable_gf's variable '{ident}': prefix, so its error context names the model but not the variable.
  • View::try_from doesn't wrap propagated element errors with the view's name the way Model::try_from does.
  • ElementCausalEdgesResult::edges is still a HashMap even though it's now populated from a BTreeMap; downstream readers (db/ltm/pinned.rs:420, analysis.rs:3296) feed it into further HashMaps, so determinism of hosts' output is preserved — but the type is now stricter than it needs to be, if it mattered to tighten it.

🤖 Generated with Claude Code

@bpowers

bpowers commented Oct 2, 2026

Copy link
Copy Markdown
Owner Author

Follow-up commit for the Codex review, both points taken:

  • External-series ordering: the importer no longer sorts a GET DIRECT DATA / GET DIRECT LOOKUPS series. Vensim's pages for the two functions say nothing of row order and no run in test/ settles it, so the file's order is kept and the compiler refuses a table whose x decreases (BadTable), rather than computing from an unverified reading. The sort of a lookup written in the model file stays: Vensim DSS's own run in test/test-models/tests/subscripted_lookups backs it. Pinned by an_external_series_listed_out_of_x_order_is_kept_as_listed_and_refused.
  • Signed zero: points_in_x_order compares x as numbers, so -0 and 0 at a vertical step keep their listed order (points_that_share_an_x_keep_their_listed_order, which fails under total_cmp).

A graphical function's type decided nothing at simulation: the compiler
dropped it and the XMILE reader read the attribute as a child element.
How a lookup reads its table is an operand of the lookup opcode
(LookupMode): a plain application takes the mode of the table's kind,
and LOOKUP FORWARD, BACKWARD and EXTRAPOLATE keep their own. The table
the compiler reads is the one the datamodel holds: x out of ascending
order is refused, as XMILE requires, and the MDL importer puts a
lookup's points in x order as it reads them, which is what Vensim's own
output shows it does. Points that share an x are a vertical step, read
by each mode's own rule wherever in the table they sit. A type the XMILE
reader does not know opens as continuous and is reported, never a
failed open.

DELAY (Vensim's DELAY FIXED) ran as a first-order delay. It is refused
on its variable with a reason until the engine has a fixed delay.

A project stored as protobuf lost a model's own simulation specs and
the Vensim sketch metadata an MDL save writes back. The schema gains
those fields. The round trip is held on the first trip, bit for bit,
against an explicit list of what the format does not keep, and stored
projects pinned by hash carry every field of the schema on the wire, so
a field cannot be renumbered or lose its old reading unnoticed. Reading
a stored project returns an error where it panicked: an empty buffer
decodes to a message without its simulation specs, so opening one took
the process down.

model_links walked a hash map, so a host got a differently ordered list
on every open; the edge map is ordered, and a standing test builds every
artifact twice from one file. The web editor shows the engine's reason
for an equation or simulation error, and the hand-written error-code
tables are held to the engine's own.
The importer sorted a GET DIRECT DATA or GET DIRECT LOOKUPS series
listed out of x order, on the reading Vensim gives a lookup written
out of order in the model file. Nothing verifies that reading for a
data file: Vensim's pages for the two functions say nothing of row
order and no run in test/ settles it. So the importer keeps the
file's order and the compiler refuses the table, which names the
problem rather than computing from an order nobody checked.

The lookup sort compared x by total order, which puts -0 before 0, so
a vertical step written with both signs of zero in an out-of-order
list changed which y it answers. It compares x as numbers.
@bpowers
bpowers force-pushed the sweep/engine-fidelity branch from 006eaf1 to 9d2e058 Compare October 2, 2026 22:35
The details panel shows an error's reason as the engine gives it, in
place of the description the editor kept per code, so a variable with
no equation reads "the variable has no equation". The JupyterLab
journey asserted the old description and failed on every run of this
branch; it asserts the engine's reason.
@claude

claude Bot commented Oct 3, 2026

Copy link
Copy Markdown

Review

No blocking issues found in the diff. The PR is a careful, thoroughly-tested refactoring, and the critical new semantics are consistent across backends and formats.

Verified correct

  • LookupMode as opcode operand: bytecode::LookupMode is passed verbatim through the symbolic -> concrete lowering (the catch-all in renumber_operand!), survives GF-block dedup (keys are x/y bit patterns only), and vm::lookup_in_mode + wasmgen::lookup::emit_lookup_extrapolate match operation-for-operation on the vertical-step rule. The compile-time Compiler::lookup_mode refuses dynamic lookups across mixed-kind tables (src/simlin-engine/src/compiler/codegen.rs:641-686) rather than approximating.
  • parse_table ascending-x enforcement: NaN, infinite, reversed-scale and descending-x are each rejected with a distinct BadTable reason; the MDL importer's points_in_x_order (src/simlin-engine/src/mdl/convert/variables.rs:1654) is stable, so vertical-step order is preserved.
  • <gf type> leniency: GraphicalFunctionKind::from_type_attribute trims + case-folds; an unknown value falls through to the default kind and is reported by the xmile::unread pass with the variable name (src/simlin-engine/src/xmile/unread.rs:492).
  • Protobuf: new fields (Model.sim_specs, ViewElementCompat.shape/name_field/tail, View.sketch_compat) are additive and read as before when absent; serde::deserialize now returns Result and a short message (e.g. an empty buffer) is a ProtobufDecode error naming what is missing instead of a panic.
  • Determinism: CausalEdgesResult.edges is a BTreeMap, so analysis::model_links returns edges in (from, to) name order deterministically.
  • DELAY FIXED refusal: builtins_visitor::rewrite_alias_module_call emits NotSimulatable with a plain-language reason instead of silently lowering to DELAY1.
  • Error details propagation: EquationError.details is carried from the engine through project-controller.ts into the ErrorDetails/VariableDetails panels, with errorCodeDescription only as a fallback.

Overall correctness

Correct.

The importer puts a lookup listed out of x order into order, which is
how Vensim's own run reads one written in a model file. An external
series (GET DIRECT DATA, GET DIRECT LOOKUPS) goes through the same one
rule rather than being refused: it is the simple reading and the
likely one, and a refusal would fail files over a case nobody has
shown to differ. That Vensim reads an external series this way is the
engine's assumption, unverified, and the rustdoc says so.
@bpowers

bpowers commented Oct 3, 2026

Copy link
Copy Markdown
Owner Author

Commit 1ca7e6f puts the importer's sort of an external series back (it reverses the external-data half of 9d2e058; the signed-zero comparator fix stays). An out-of-order GET DIRECT DATA / LOOKUPS series goes through the same one ordering rule as a lookup in the model file, rather than being refused: it is the simple and likely reading, and a refusal would fail files over a case nobody has shown to differ. The rustdoc says it is the engine's assumption, unverified against Vensim.

@claude

claude Bot commented Oct 3, 2026

Copy link
Copy Markdown

Review summary — no blocking findings

I reviewed this PR focusing on the correctness-critical areas: variable::parse_table (new ascending/finite-x rules), mdl::convert::variables::points_in_x_order (importer sort), wasmgen/lookup.rs (per-mode wasm helpers), vm::lookup_in_mode and its differential tests, codegen::lookup_mode (mixed-kind refusal), serde::deserialize returning Result (and FFI/CLI/test migration), project_io.proto schema evolution (field numbering, backward compat), TryFrom<project_io::Project> and TryFrom<project_io::Model>, the XMILE <gf type> attribute reader + from_type_attribute, DELAY refusal (rewrite_alias_module_call), CausalEdgesResult.edges as BTreeMap, and the EquationError.details propagation through convertErrorDetails + the two renderer sites.

Each area is backed by tests derived from the enumeration it constrains (every LookupMode × VM/wasm bit-for-bit; parse_table_tests rows for ascending/NaN/infinite-x; lookup_order_tests for the importer arms; serde_stored_tests holding each stored project to a SHA-256 and asserting every schema field is on some wire). The field-number additions (Model.sim_specs=8, View.sketch_compat=10, ViewElementCompat.{shape=4,name_field=5,tail=6}) are backward-compatible, and view_compat_from_proto's "treat all-default message as absent" check was extended to include the new fields so round-trip is preserved.

Behavioral note (not a bug, worth a reader's attention)

lookup_forward / lookup_backward at the far-edge x of a vertical step changed from the inclusive-clamp answer (last-listed) to the search-based answer (first-listed for forward, last-listed-via-upper-bound for backward), aligning the end with the middle under one rule. For strictly ascending tables (no repeated x) this is a no-op. For [(0,1),(1,2),(1,5)], LOOKUP_FORWARD(t, 1) now returns 2 instead of 5. This is intentional (documented on LookupMode, matches Vensim's documented examples in vensims_documented_lookup_examples_simulate_as_documented), and the PR body already flags that no corpus table reaches this shape — but the "what this does not establish" section could mention the end-step numeric change explicitly, since the PR body otherwise frames the opcode move as a shape refactor.

Overall correctness verdict: correct.

@bpowers
bpowers merged commit 610cb2c into main Oct 3, 2026
18 checks passed
@bpowers
bpowers deleted the sweep/engine-fidelity branch October 3, 2026 04:28
bpowers added a commit that referenced this pull request Oct 3, 2026
## Why

A fresh-eyes review of the structural-sharing work that landed between
`e6f95a6b` and `5f2b7f94` (`SharedVec`, patch sharing, the undo-copy
path) found that the mechanism was sound, and that the patch layer under
it changed models in ways an edit never asked for. Each item below
started as a failing probe test.

- **Patches sorted a stock's inflow and outflow lists.** Every
`UpsertStock` and `UpdateStockFlows` sorted them, and a flow rename
sorted every stock's. XMILE 1.0 section 4.2 makes that order the
inflows' priority and a queue's outflow priority, and the queue and
conveyor passes read it. Renaming an unrelated flow swapped which of two
queues a conveyor served first (`waiting_a` went from 0, 2, 4, 6, 8 to
all zeros), and moved a queue's `<overflow/>` outflow to the front,
which does not compile.
- **A rename missed references.** It rewrote a variable's equation and
`ACTIVE INITIAL` only: a conveyor whose `<len>` named the variable
stopped compiling, a macro's parameter list went stale (a call went from
43 to 3), and renaming a sub-model's output left its parents reading a
name that no longer existed.
- **`SharedVec::edit_each` rested on a convention.** It kept a shared
element's edit only when the closure returned `true`. Four of the
rename's arms could report `false` after changing their text without any
test failing, and "shared" is the state a host with undo history is in.
- **Datamodel `==` was not reflexive on NaN,** so a lookup table holding
one was set again, and its variable recompiled, on every sync.

## What

- **Flow lists keep the order they were given.** A renamed flow keeps
its position; only stocks that name the flow are touched.
- **One owner each** of where a variable holds expression text
(`Variable::expression_texts`) and where a model holds a variable's name
(`Model::map_variable_names`, by `NameRole`). Both destructure without
`..`, so a new field fails to compile until it is classified.
- **A rename resolves references through module instances**
(`patch::Rename`, mirroring `db::DepScope::resolve`), so it reaches
equations, module `src`/`dst` and flow lists in every model that can
name the variable. It splices the new name into the text at each
reference's span, so spacing, builtin case and every other name come
back byte for byte; a text longer than a `u16` span reaches is respelled
by the printer. A delete unwires a module reference either end of which
starts at the deleted variable, in any spelling.
- **`SharedVec::update(|&T| -> Option<T>)` replaces `edit_each`.** A
pass that reads an element and returns its replacement cannot change one
and leave it out.
- **Datamodel equality is bit for bit** (`bitwise_eq!`, which refuses an
unmarked float), every datamodel type is `Eq`, and the separate
`Identical` trait is gone.
- **`db::sync` skips a variable whose `Arc` is the one its input was
last set from.** `InputMemory` is the one statement of when that memory
may be trusted.
- **Two models known by one name are refused** (canonical name, an
unnamed model being `main`): by the compile, by one project-level
diagnostic, and by `AddModel`. `AddModel` also refuses a name under the
stdlib prefix, and a project model named for a stdlib model gets inputs
of its own instead of overwriting the db's.
- **`SetSimSpecs` clears the default model's own specs**
(`Project::default_model`), so the edit is what the run reads.
- libsimlin's `add_model` stages its edit, so a refused add changes
nothing; the diagram editor compares model names as the engine does.

## Decisions worth a reviewer's eye

- **A rename refuses rather than guess what a bracketed identifier
means.** The compiler reads an identifier inside a subscript three ways:
the dependency walk skips a dimension or an element of any dimension, a
static subscript takes an element of its axis, and a range takes its
ends as elements only when both are. An earlier attempt in this change
to mirror "the compiler's rule" broke two shapes that ran on main,
because it is not one rule. So a rename is refused, changing nothing,
when the old or new name is a dimension's (XMILE 3.7.1 forbids such a
variable), or is an element of a dimension and the variable is written
alone in a subscript. Everywhere else there is no ambiguity. Unifying
the compiler's reading is separate work, after which the refusal can be
lifted. One of 7,590 corpus variables is named like a dimension or
element.
- **A rename does not give a variable the name of one of the run's clock
slots** (time, the time step, the initial and final time). The compiler
resolves such a name written quoted, so this is deliberately stricter
than it: a variable of that name takes the slot's key in the results,
where every host reads the clock. A model that already declares one
keeps it and can rename it away.
- **Duplicate canonical model names are ill-formed rather than
last-wins,** because last-wins runs a model other than the one a patch
edits. A stored project that has one is now refused with a diagnostic;
none of the 484 corpus projects does.
- **`RenameVariable` leaves diagram labels,** in every view, until a
view edit or a diagram sync that carries the patch relabels them. That
is main's behavior; the rustdoc now says so.
- The sync skip trusts a state's memory only while that state is of the
inputs' latest sync, because a rollback re-syncs with a state older than
the inputs.

## Evidence

- **Flow order:** a row per `ModelOperation` variant; the two fixtures
whose series depend on list order are unchanged by an unrelated rename
(on main they flipped).
- **Rename:** `a_rename_is_refused_or_changes_no_series`, 26 rows
checked against `Refusal::ALL`: a refused rename leaves the project
byte-equal, a carried-out one leaves every series identical. A row per
expression field and per name role, each with an oracle that is not the
function under test. In the gates, 1,095 renames across the corpus leave
every series identical.
- **Sync:** `db/sync_differential_tests.rs`: after any sequence of
syncs, staged syncs and rollbacks over a 47-project pool that varies
every field the sync writes, the db holds what a fresh db holds (inputs
in the default suite; every diagnostic, series, expanded input and loop
count in the gates, over 500 random sequences and every ordered pair).
- **Sharing:** every patch operation and both special-stock expansions
leave what they do not change in its allocation, and land the same on a
shared and an unshared project (two models by default, the corpus in the
gates). The generator matches `ModelOperation` and `ProjectOperation`
without a wildcard.
- **Cost:** `db.sync` after a one-variable edit on C-LEARN, 617.5 us and
10,784 allocations before, 322.4 us and 4,150 after; World3 169.1 us to
101.1 us. The default suite gains about 0.6 CPU-seconds in debug.
- **Review:** two adversarial reviews ran against this change (the first
found the sync skip running a stale model for two same-named models, and
the splice corrupting text past 64 KiB; the second found the resolver
disagreeing with the compiler). Their findings and surviving mutations
are fixed and pinned; the mutations of the final mechanisms are each
killed by a named test.
- A rename to a zero-argument builtin's name (`pi`) changes no series,
now that the printer quotes such a name (#1073).
- The pre-commit hook passed in full: Rust, TypeScript and pysimlin, on
this branch rebased onto main as of #1071 and #1075.
- `setting_the_sim_specs_of_a_stored_project_changes_its_run` (added by
#1071 as an expected failure waiting on this change) passes, and its
marker is removed.

## What this does not establish

- The subscript refusals rest on fixture rows; the corpus sample holds
no such name.
- `tools::resolve_datamodel_model`, `analysis::model_snapshot` and
libsimlin's `simlin_project_get_model` do not yet use
`Project::default_model`, and the db files an unnamed model under `""`
rather than `main`.
- Spans in texts over 64 KiB are still wrong for error snippets; only
the rename is protected.
- Whether any stored production project has two models of one canonical
name.
- No browser journey was run. The one UI change is the model-name check,
covered by unit tests and an engine-backed test.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_01LYR7N9WZwQuFnZFW8JDUgx
bpowers added a commit that referenced this pull request Oct 3, 2026
## 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 #1071, #1072 and #1075: with #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 #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.com/claude-code)

https://claude.ai/code/session_01LYR7N9WZwQuFnZFW8JDUgx
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.

1 participant