Repository navigation
engine: one equation normal form and a sound save check - #1073
Conversation
A reference to a variable named like a zero-argument builtin ("pi",
"dt", "time") was printed bare, which reads the builtin, so renaming an
unrelated variable could change what an equation computes.
ast::needs_quoting quotes those names, and every stage after the parse
reads a name only as a variable: the parse alone decides that a bare
word is the builtin, so name resolution, helpers, LTM and unit checking
no longer ask. The rule is the engine's own. XMILE 1.0 reserves function
names (2.1) and makes quotes no part of an identifier (3.2.2.1); the
rule serves Vensim models that declare dt = TIME STEP, and what Vensim
does with such a name is unverified. The MDL importer still leaves such
a reference bare, a gap stated in mdl/CLAUDE.md and pinned by tests its
fix deletes.
ast::CanonicalEqn is the one normal form behind "do two equations say
the same thing". It applies the engine's own rewrites except where a
macro takes the name or an alias's target. save_check compares by it,
destructures every datamodel type it reads without `..` (a table test
rows each field), asks save_check::column_variable which variable a
results column belongs to (a name may itself start with `$` or hold
`[`), and reads the clock from its slot. A non-negative marking a stock
or flow loses is a change to results, because the engine does not
enforce it. tests/integration/save_meaning.rs lists every corpus save
that does not keep its model, ratcheted both ways.
The systems translator spells names through the printer, so a stock
named pi is read as the stock, and the agent tools' edit gate finds a
variable's column by the same rule save_check does.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #1073 +/- ##
==========================================
+ Coverage 92.40% 92.44% +0.03%
==========================================
Files 304 307 +3
Lines 184569 184971 +402
==========================================
+ Hits 170555 170990 +435
+ Misses 14014 13981 -33 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
ReviewReviewed the engine changes (ast canonical form, save_check rewrite, printer No correctness findings. The review was structured around four concerns the PR body itself called out as decisions worth checking:
One minor nit (not a correctness bug), take it or leave it: Overall correctness: correct. |
## 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
Why
Every rename and save goes through the equation printer, and
save_checkis what tells a host whether saving in a format keeps what a model means. A fresh-eyes review of both found three ways a saved or renamed model could silently compute something else:"pi","dt"and"time"came back aspi,dtandtime, which read the builtin, so renaming an unrelated variable rebound"pi" * rto the constant.save_checkcould miss things. Its structure walk used.., so a field added to the datamodel was skipped without notice, and its run comparison skipped any variable whose name starts with$or holds[, reporting "no change" for a difference only the run shows.What
ast::needs_quotingquotes the nine zero-argument builtin names.Expr0::newmakes a call of a bare builtin word, so after the parse a name is only ever a variable. Name resolution (resolve_referenced_heads,implicit_referenced_heads,lower_ltm_variable) and unit checking no longer ask whether a name is a clock name, andis_implicit_globalis gone. An undeclared quoted"dt"is an unknown dependency like any other.ast::CanonicalEqnis the one normal form of an equation. It folds the engine's own rewrites (aliases,MODULO,PI(),INF()), never where a macro takes the name or the alias's target.save_checkand helper identity read it.save_checkdestructures every datamodel type it reads without.., andsave_check_field_tests.rsrows every field.save_check::column_variablewhich variable a results column belongs to (whole column first, then the compiler's own synthetic prefix, then the longest declared name the column extends), and reads the clock from its slot.Resultschange, because the engine does not enforce it. An auxiliary's is not compared: no writer keeps it.tests/integration/save_meaning.rsis oneEXPECTEDtable (115 rows) of every corpus save that does not keep its model, ratcheted both ways. The whole-corpus sweep (1,940 saves) is an ignored gate; five models run in the default suite.ast::print_ident, and the agent tools' edit gate finds a variable's column throughcolumn_variable.Decisions worth a reviewer's eye
dt = TIME STEP(Theil_2011.mdl,IDch15d.mdl). What Vensim itself does with such a name is unverified; the rustdoc says so.x = dt * 2besidedt = 0.25imports as the builtin's value, a flow list'sdtand a net-flow expression'sdtmean different things in one model, and an MDL save ofdt = TIME STEPwritesdt = dt. Three characterization tests inkeyword_ident_tests.rsstate what the engine does today; the fix (the importer quotes, the writer tellsTIME STEPfrom a variabledt) belongs with the MDL writer work and deletes them.time,dt,initial_timeorfinal_timetakes that slot's results key; the clock keeps its slot with no key.Evidence
ast::print_eqn_proptestover everyExpr0variant, index form and name class (mixed-case and spaced call names, all nine nullary calls, a NaN constant, one to four indices), at 100,000 cases. The adversarial review also ran 290 hand-written strings and 433,000 random parsed strings with no counterexample.CanonicalEqn: every alias andMODULOover divisors of either sign and zero run through the VM against the canonical form as printed; the review ran 1,026 equations through the VM with no two equal forms computing differently, apart from the macro-alias case fixed here.save_check: the review applied 73 mutations and 5 survived; each survivor has a row now, and 27 of 27 mutations of the fix round's rules are killed. The corpus gate's ratchet was mutation-tested both ways.What this does not establish
dtorpi.pichanged (0 before, because the generated text printed it bare); one test pins the new behavior per name, none pins values on a corpus model.🤖 Generated with Claude Code
https://claude.ai/code/session_01LYR7N9WZwQuFnZFW8JDUgx