Skip to content

engine: one equation normal form and a sound save check - #1073

Merged
bpowers merged 1 commit into
mainfrom
sweep/save-check
Oct 2, 2026
Merged

bpowers merged 1 commit into
mainfrom
sweep/save-check

Conversation

@bpowers

@bpowers bpowers commented Oct 2, 2026

Copy link
Copy Markdown
Owner

Why

Every rename and save goes through the equation printer, and save_check is 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:

  • The printer wrote a reference to a variable named like a zero-argument builtin bare. "pi", "dt" and "time" came back as pi, dt and time, which read the builtin, so renaming an unrelated variable rebound "pi" * r to the constant.
  • "Do these two equations say the same thing" was answered in several places that had drifted apart.
  • save_check could 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_quoting quotes the nine zero-argument builtin names.
  • One rule, one owner: bare is the builtin, quoted is the variable. Expr0::new makes 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, and is_implicit_global is gone. An undeclared quoted "dt" is an unknown dependency like any other.
  • ast::CanonicalEqn is 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_check and helper identity read it.
  • save_check destructures every datamodel type it reads without .., and save_check_field_tests.rs rows every field.
  • The run comparison asks save_check::column_variable which 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.
  • A non-negative marking a stock or flow loses is a Results change, because the engine does not enforce it. An auxiliary's is not compared: no writer keeps it.
  • tests/integration/save_meaning.rs is one EXPECTED table (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.
  • The systems translator spells names through ast::print_ident, and the agent tools' edit gate finds a variable's column through column_variable.

Decisions worth a reviewer's eye

  • "Bare is the builtin, quoted is the variable" goes beyond XMILE 1.0, which makes quotes no part of an identifier (3.2.2.1) and reserves function names (2.1). It exists for Vensim models that declare dt = TIME STEP (Theil_2011.mdl, IDch15d.mdl). What Vensim itself does with such a name is unverified; the rustdoc says so.
  • Known gap, pinned rather than fixed here: the MDL importer leaves such a reference bare. So x = dt * 2 beside dt = 0.25 imports as the builtin's value, a flow list's dt and a net-flow expression's dt mean different things in one model, and an MDL save of dt = TIME STEP writes dt = dt. Three characterization tests in keyword_ident_tests.rs state what the engine does today; the fix (the importer quotes, the writer tells TIME STEP from a variable dt) belongs with the MDL writer work and deletes them.
  • A variable named time, dt, initial_time or final_time takes that slot's results key; the clock keeps its slot with no key.
  • On a base where these models did not compile, declaring a variable named for a clock is newly reachable, which is why unit checking and the edit gate changed with the resolution sites.

Evidence

  • No corpus model moves. All 510 corpus files give byte-identical VM series, diagnostics (LTM overlay off and on) and LTM series before and after, by a whole-corpus hash sweep against the base commit, run by the adversarial reviewer and again after the fix round.
  • Printer round trip: ast::print_eqn_proptest over every Expr0 variant, 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 and MODULO over 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.
  • Units: a row per nullary builtin name, declared and inferred.
  • The pre-commit hook passed in full.

What this does not establish

  • That a writer and reader that agree with each other agree with Vensim or Stella: the check reads a save back with this engine's own reader.
  • Anything about how Vensim treats a variable named dt or pi.
  • That the MDL importer reads such models as Vensim does: the gap above is pinned, not fixed.
  • The default suite covers five corpus models; the rest of the corpus is held only by the ignored gate, which no CI job runs yet.
  • LTM scores for a loop through a variable named pi changed (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

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.
@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-02T18:33:06.924211Z f5fb8b1 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 99.70326% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 92.44%. Comparing base (ce72237) to head (f5fb8b1).

Files with missing lines Patch % Lines
src/simlin-engine/src/tools/edit.rs 88.88% 1 Missing ⚠️
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.
📢 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 2, 2026

Copy link
Copy Markdown

Review

Reviewed the engine changes (ast canonical form, save_check rewrite, printer needs_quoting, Expr0::eq_ignoring_loc widening, and the tools/edit, systems/translate, mdl/xmile_compat, units_check ripple edits).

No correctness findings. The review was structured around four concerns the PR body itself called out as decisions worth checking:

  1. CanonicalEqn under Aliases::Engine (src/simlin-engine/src/ast/canonical.rs:151-209): in_subscript propagates correctly through walk and the explicit per-arm recursion; alias normalization still runs inside a subscript (so x[STARTTIME] == x[INITIAL_TIME]), only constant_for_call/operator_for_call are gated by !in_subscript. The two macro guards (!is_macro(&func) and !is_macro(sig.name)) cover all four arms exercised by a_call_a_macro_takes_is_left_as_written. operator_for_call's one-entry list (modulo) is complete: // lowers to safediv (no BinaryOp twin), and AND/OR/MOD are keyword tokens so they never reach the parser as calls.

  2. needs_quoting + builtin names (src/simlin-engine/src/ast/mod.rs:565-579, src/simlin-engine/src/builtins.rs:1145): the nullary builtin list in is_0_arity_builtin_fn_ci matches BuiltinSig::ALL's zero-arity entries (pinned by nullary_name_list_matches_the_signature_table), and reify_0_arity_builtins sees quoted names with their quotes still attached from Lexer::quoted_identifier (src/simlin-engine/src/lexer/mod.rs:205), so is_0_arity_builtin_fn_ci("\"pi\"") is false and the "bare is the builtin, quoted is the variable" invariant holds end-to-end.

  3. save_check structural walk and column resolution (src/simlin-engine/src/save_check.rs): every datamodel::* destructure names every field (Project, Model, SimSpecs, Dimension, Stock, Flow/Aux/Module, Conveyor, Leakage, GraphicalFunction, MacroSpec, Equation arms); column_variable correctly tries whole-column first, then the synthetic-prefix bail, then longest-declared-prefix with [/· as the only separators; TIME_OFF is read directly from slot 0 regardless of what key the offsets map carries, which matches root_shifted.

  4. Non-negative grading (src/simlin-engine/src/save_check.rs:1137-1147,1861-1872): stripped on non-Stock/Flow kinds, forced to ChangeKind::Results in every Runs arm that has results and only graded Structure under NeitherSimulates. The new libsimlin integration test test_check_save_grades_a_lost_non_negative_marking_as_an_error pins the Error-severity contract.

One minor nit (not a correctness bug), take it or leave it: CONTROL_VARIABLES at src/simlin-engine/src/save_check.rs:1197 lists only the Vensim-form names (initial_time, final_time, time_step, saveper). A model that declares dt/starttime/stoptime matching the spec would miss the control-variable-kept short-circuit and surface a Structure noise change. This is pre-existing, not introduced here, and the meaning check is still correct — just louder than it needs to be in that corner. If worth touching, canonicalizing through BuiltinSig::by_name would collapse the aliases.

Overall correctness: correct.

@bpowers
bpowers merged commit 3104bef into main Oct 2, 2026
18 checks passed
@bpowers
bpowers deleted the sweep/save-check branch October 2, 2026 21:23
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
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