Skip to content

engine: count a run's steps and read its rows by time - #1075

Merged
bpowers merged 3 commits into
mainfrom
sweep/run-grid
Oct 3, 2026
Merged

bpowers merged 3 commits into
mainfrom
sweep/run-grid

Conversation

@bpowers

@bpowers bpowers commented Oct 2, 2026 •

Copy link
Copy Markdown
Owner

Why

A fresh-eyes review of the run and behavior half of the agent tools started at the tools and ended in the engine's clock. A run's steps were found by accumulating time += dt and its saved rows by rounding save_step / dt, so:

  • the clock drifted by ulps, and PULSE could fire a step late or lose its last pulse;
  • a save step off the DT grid silently changed how many rows a run saved and when;
  • the VM and the wasm backend could disagree;
  • some finite specs panicked, aborted on allocation, or (in the tools' sliced runs) never ended;
  • a second run call after a run's end aborted the process inside extern "C".

The agent tools read runs on top of this. They also judged "at rest" with no notion of scale, so rounding residue of 1e-15 read as goal seeking, and named behavior modes with a classifier never tested on real series.

What

  • results::Specs states the step grid once: step k is at start + k*dt; a run is steps 0..=final_step; saved row m is the first step at or after start + m*save_step; a time written as a step's is read as that step within STEP_TOLERANCE. The VM and wasm compute it in the same f64 operations.
  • Specs::refusal is the one statement of specs no run can be made under, and both backends refuse with it. Every other finite spec runs from step zero or is refused with BadSimSpecs, its numbers written as a person writes them.
  • A save step off the grid keeps its declared rows and is reported as SaveStepOffTheStepGrid.
  • PULSE fires at the first step at or after each pulse time, pulse times computed by multiplication.
  • A run rests at the step after the last it evaluated, unevaluated. After the final step that is one step past the stop, as on main, so time never goes back. A further run call on a finished run takes no step.
  • The agent tools:
    • take a run in slices counted in steps, so a run whose clock is coarser than its DT ends;
    • make a value set "from t" hold from the first step at or after t, under every method (Vm::run_until);
    • key a run's freshness on the salsa sync's own field extraction;
    • read a series as residue when it never leaves zero by more than 64 f64::EPSILON of the scale it is computed from (per element), and otherwise report the series' own numbers;
    • name behavior modes by large movements read against their times.
  • Dominant periods begin and end at the times of the rows the run saved, read from its results, so a save step off the DT grid moves no boundary off a row.

Decisions worth a reviewer's eye

  • PULSE off the grid. XMILE 1.0 section 3.5.4 does not settle a pulse time between steps; "the first step at or after" is the engine's rule, and Stella's choice is unverified. The corpus's three Stella PULSEs are all at step times.
  • The off-grid save rule is the engine's own. Vensim's SAVEPER handling there is unverified.
  • The VM and the wasm blob do not rest in the same state in every case. They agree bit for bit while the target is before the blob's last saved row. From there the blob rests at that row and the VM at the next step. This is documented and pinned by a table rather than changed: it is a question of the blob's ABI. Main differs the same way.
  • Residue is bounded by floating point, not a fraction. A stock's scale counts each flow at the larger of what it reaches and its own scale as a sum, times the horizon, which already counts its steps. Measured residue never exceeded 0.97 epsilon of its scale, so 64 has a margin of about 66; a real inflow of 2e-5 beside cancelling flows of 1e9 (90 epsilons) is seen moving and 1e-5 (45) is not. An earlier round of this change used a fraction (1e-9) and erased real movement; the adversarial review caught it.
  • Every reader judges "at rest" against the run's own equations, its replacements applied: an experiment that replaces a cancellation of large terms with a small real flow sees the flow move. An experiment's two runs share their magnitudes, so residue in one beside a movement in the other still reads at rest, but not each other's structure.
  • Known limit: residue through a quotient or a function (gap / 4 feeding a stock, SMTH1, MAX) reads as moving, so analyze_loops can report a share for a loop whose stocks move only by rounding.
  • The classifier's disagreements with a modeler are a table, not hidden: thirteen of 59 labeled series, each with what the classifier says and why. The table fails when a listed series starts agreeing and when an unlisted one disagrees.
  • The simulation key hashes text as written, so it may split one simulation into two, never merge two into one.

Evidence

  • Corpus, main against this change: 398 models simulate on both and none changed whether it simulates. Six moved: five by clock ulps, mostly closer to the Vensim/Stella expected outputs (simple_harmonic_oscillator's worst error 2.2e-12 to 7.1e-15), and Single_Pendulum, an off-grid SAVEPER, from 985 to 1,001 rows.
  • PULSE: 19,240 series checked against the stated rule in rational arithmetic, all equal; 4,548 differ from main where main fired a step late on a pulse time that is exactly a step's. VM against wasm over 29,220 series: 0 differ.
  • Every finite spec runs or is refused: 528 engine cases (1e308, subnormals, zero and negative DT, stop before start), 372 through the FFI in child processes, 404 through the tools: 0 panics, 0 crashes, 0 hangs.
  • Resting state: an FFI transcript against main differs only in last-bit clock values and in nine lines where main's drifted clock skipped a step a named time asked for; a table over targets and save steps pins where the VM and the blob agree (1,800 of 2,436 resting rows) and differ.
  • At rest: 21 rows, from true residue to a 0-to-50 movement beside flows of 1e9, each asserted through read_behavior, read_variables, run_experiment and verify_findings, which agree on mode and numbers.
  • Classifier: 27 labeled real series in the default suite and 59 in a gate (World3, C-LEARN, land_model, hares and lynxes). Run side by side with main's classifier at the second review pass, oscillation labels had fallen from 39 to 9 on World3 and from 757 to 462 on C-LEARN, with no name that was not an oscillation changing; the last round changed 18 of 4,245 names further (13 better or neutral, 3 listed as known disagreements, 2 the regressions it fixed).
  • Review: three adversarial passes by a reviewer that did not write the code. The first two found defects (the fraction-based residue rule; a start-up hump read as exponential; a tools run that never ended), which are fixed and pinned; the third returned commit-as-is with nits, which are done. Mutation testing: every rule mutated is killed except one mutant shown equivalent.
  • The pre-commit hook passed in full: Rust, TypeScript and pysimlin.

What this does not establish

  • What Vensim or Stella do with an off-grid SAVEPER or PULSE time.
  • That the blob rests where the VM does after its last saved row: it does not.
  • That the classifier's labels match every modeler. The thirteen known disagreements are open behavior, and the labeled set is one reviewer's and one implementer's reading.
  • That the scale sees every residue: it covers sums, not products or quotients.
  • Runs of 1e8 or more steps with few saved rows are bounded only by the tools' budget, not by the VM.
  • The fixture's fidelity to the models is checked only by an ignored gate, which no CI job runs yet.

🤖 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-02T22:16:26.880263Z a4c28e5 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.

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

ℹ️ 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/layout/mod.rs Outdated
Comment on lines 3619 to 3622
// A run saves a step at most once (`results::Specs::save_step`), so
// the effective cadence is never faster than dt.
let effective_save_step = raw_save_step.max(dt);
crate::ltm_dominance::calculate_dominant_periods(

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 saved row times for dominant periods

When save_step / dt is nonintegral (for example, 0.3/0.25), this commit saves irregularly timed rows such as 0, 0.5, 0.75, 1.0, but this call still passes 0.3 to calculate_dominant_periods, which reconstructs timestamps as start + index * dt. Consequently the layout's dominant-period boundaries are incorrect; the analysis path has the same problem at analysis.rs:436-439, despite its separate time array now reading actual row times. Pass the saved-row time vector to the period calculation rather than a constant cadence.

Useful? React with 👍 / 👎.

Comment on lines +48 to +50
/// the rows are not evenly spaced. This is the engine's rule: it keeps the
/// rows a declared save step asks for (as many, each at the time asked for or
/// the step after, the stop time among them when it is a save time), where

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 Align integration checks using actual sample times

For an off-grid save step, halving DT changes which timestamps are actually saved, so the integration-error battery no longer compares equivalent points. For example, with DT 0.6 and save step 0.7, the base saves its second row at 1.2 while the half-DT run saves rows at 0.9 and 1.5; battery.rs:2231-2235 selects 0.9 for the base's 1.2 row via row_at(t + dt/4), turning ordinary time evolution into an apparent integration error. The refined run needs samples at or interpolated to the base run's actual row times.

Useful? React with 👍 / 👎.

Comment on lines +186 to +188
let text = match var.get_equation() {
Some(datamodel::Equation::Scalar(text))
| Some(datamodel::Equation::ApplyToAll(_, text)) => Some(text.as_str()),

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 Derive behavior scale from each run's replacement equations

When a named experiment replaces an equation, scale_in_run still reads that variable's equation from the unchanged project model rather than from the run's RunPlan. For example, replacing a flow originally defined as a subtraction of billion-scale terms with a small real flow leaves its stock classified against the old billion-scale cancellation bound, so read_behavior, experiment comparisons, verification, and at-rest loop detection can incorrectly report the new movement as floating-point residue. Apply the run's accumulated equation replacements when deriving the scale, or derive it from the staged run structure.

Useful? React with 👍 / 👎.

A run's clock accumulated dt and its saved rows came from a rounded
save_step/dt, so time drifted by ulps, a save step off the DT grid
changed how many rows a run saved and when, the VM and wasm could
disagree, and some finite specs panicked, aborted on allocation, or
left a sliced tool run that never ended. results::Specs states the
grid once (step k at start + k*dt, row m at the first step at or after
its save time), both backends compute it identically and refuse specs
for one reason, every other finite spec runs from step zero or is
refused with its numbers written plainly, and an off-grid save step
keeps its declared rows and says so. A run rests at the step after the
last it evaluated, so time never goes back, and a further run call on
a finished run takes no step where it used to abort; the wasm blob
rests there only before its last saved row, which is recorded rather
than changed. PULSE fires at the first step at or after its time;
Stella's choice off the grid is unverified.

The agent tools build on that grid: values from a time take effect at
that step, runs are sliced in steps, freshness is keyed on the sync's
own extraction, a series is residue only within 64 units of f64
rounding of the scale it is computed from (each element its own) and
otherwise reported as its own numbers, and the behavior classifier
names a series by its large movements, its disagreements with a
modeler kept in a table that fails when one is resolved.
@codecov

codecov Bot commented Oct 2, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.52448% with 22 lines in your changes missing coverage. Please review.
✅ Project coverage is 92.47%. Comparing base (3104bef) to head (0f92d5d).

Files with missing lines Patch % Lines
src/simlin-engine/src/tools/runs.rs 93.93% 10 Missing ⚠️
src/simlin-engine/src/tools/series.rs 95.83% 7 Missing ⚠️
src/simlin-engine/src/db/sync.rs 99.46% 2 Missing ⚠️
src/libsimlin/src/lib.rs 0.00% 1 Missing ⚠️
src/simlin-engine/src/results.rs 99.49% 1 Missing ⚠️
src/simlin-engine/src/tools/experiment.rs 96.42% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1075      +/-   ##
==========================================
+ Coverage   92.44%   92.47%   +0.03%     
==========================================
  Files         307      307              
  Lines      184971   185998    +1027     
==========================================
+ Hits       170989   172009    +1020     
- Misses      13982    13989       +7     

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

calculate_dominant_periods rebuilt each row's time as start plus the
row's index times the save step. A save step off the DT grid saves its
rows at the first step at or after each save time, so those times are
not a cadence, and a period could begin where no row is. It takes the
rows' times, read from the results, in the analysis and in the layout.

The scale a series is judged at rest against was derived from the
model's equations, also for a run that replaces one. An experiment
that replaced a cancellation of large terms with a small real flow had
its stock judged against the old cancellation and read as rounding
residue. Every reader derives the scale from the run's own equations,
its plan's replacements applied through the function that stages them,
and an experiment's two runs share their magnitudes, not each other's
structure.
@bpowers

bpowers commented Oct 3, 2026

Copy link
Copy Markdown
Owner Author

Follow-up commit 9bd004e for the Codex review:

  • Dominant periods at the rows' times: taken. calculate_dominant_periods takes the saved rows' times, read from the results, in the analysis and in the layout; pinned by dominant_periods_begin_and_end_at_the_rows_times (a save step of 0.3 at DT 0.25, which failed first with a period starting where no row is). An on-grid run's periods are unchanged and the LTM gates did not move.
  • The at-rest scale under an experiment's replacement equations: taken. Every reader derives the scale from the run's own equations, the plan's replacements applied through the function that stages them; pinned by a_run_is_read_at_the_scale_of_its_own_equations (the reviewer's case, its mirror, a value-only experiment, and the model's own runs, each through every reader). An experiment's two runs now share their magnitudes and not each other's structure.
  • The integration check at an off-grid save step: correct, and it lands with the battery change that follows this one (that change rewrites the integration measurement and is stacked on this branch); it gets a row at DT 0.6 with a save step of 0.7.

Vm::run_until_step was crate-private with the agent tools its only
caller, so an engine built without them warned that it is never used.
It is the step-counted form of the public Vm::run_until and is public
beside it.
@claude

claude Bot commented Oct 3, 2026

Copy link
Copy Markdown

Review findings

[P1] tools/battery.rs:2343-2344 — responses() still uses scale-less classify, which no longer treats residue as at rest

This PR removes the REST_FLOOR = 1e-9 fallback from behavior::classify: with scale = 0, a series is now at rest only when its reported range is zero or its magnitude is ≤ 64 * EPSILON * 0 = 0. Every other site in the tools switched to classify_at fed by scale_in_run (verify.rs:597,650, loops.rs:1137, series.rs:327,353,650, variables.rs:430, experiment.rs:694,700), but battery::responses was left on the old classify(&times, &values)/classify(&base_times, &base_values) path. A stock sitting at computational equilibrium (flows that cancel, residue ~ 1e-15) now classifies as Oscillation (or Other) instead of AtRest. This affects the was field and changed_family in battery responses — in particular, a knockout/disturbance that changes a residue-equilibrium base run to a residue-equilibrium perturbed run can now flip was to Oscillation and silently mask a real behavior change if the perturbed run also reads as noisy. Switch to classify_at with scale_in_run(&run.results, model, &run.plan, &key) (and the same for base), matching the design doc's "every tool reads a series at the scale of what it is computed from" and the pattern in verify.rs/experiment.rs.

[P1] tools/series.rs:160-162 — scale_in_run can panic via unreachable! on a stale named run after a rename or delete

scale_in_run clones model, calls runs::apply_equations(&mut replaced, plan), and asserts unreachable!(\"a run's plan replaces variables of its model\") on error. The invariant does not hold for named runs that have gone stale: RunStore::get returns Kept::Run(run) without a key check (only Kept::Planned is key-gated), so read_behavior/experiment::compare/verify.rs can be handed a stale run whose plan.equations references a variable the user has since renamed or deleted. Concrete trigger: run an experiment that replaces equation of variable a, keep the result as a named run, rename a → a_new, then call read_behavior for an unrelated variable b on the stale run — keyed_series_upto succeeds for b (its offset is unchanged), then scale_in_run enters the equations branch, apply_equations fails to find a, and unreachable! panics inside the engine (process abort across the FFI). Fallback to model unchanged (or to scale 0.0) when apply_equations returns Err instead of asserting; the stale-run case can only widen the scale, which is the safe direction.

Overall verdict

Not blocking — the invariants the refactor is built on (step grid, Specs::refusal, VM/wasm parity, PULSE on-step reading, resumable cursor, simulation_key sync-driven extraction) hold cleanly on review, and the two findings above are localized touches rather than redesigns.

(Reviewed with a batch of focused agents over results.rs, vm.rs, wasmgen/, tools/behavior.rs+series.rs+experiment.rs, tools/runs.rs+db/sync.rs, and analysis.rs+ltm_dominance.rs; the full tool/module and FFI changes against origin/main were walked in-session.)

🤖 Generated with Claude Code

@bpowers
bpowers merged commit 3ac5b34 into main Oct 3, 2026
18 checks passed
@bpowers
bpowers deleted the sweep/run-grid branch October 3, 2026 04:27
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