Repository navigation
engine: read tables by kind and keep projects in protobuf - #1071
Conversation
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 #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. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
💡 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)); |
There was a problem hiding this comment.
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 👍 / 👎.
| let (x_points, y_points) = points_in_x_order( | ||
| pairs.iter().map(|(x, _)| *x).collect(), | ||
| pairs.iter().map(|(_, y)| *y).collect(), | ||
| ); |
There was a problem hiding this comment.
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 👍 / 👎.
Review summaryDid 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, No high-confidence correctness defects found. Verdict: correct. Notable things that look right that I'd normally expect to see slip:
Minor cosmetic observations (not blocking):
🤖 Generated with Claude Code |
|
Follow-up commit for the Codex review, both points taken:
|
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.
006eaf1 to
9d2e058
Compare
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.
ReviewNo 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
Overall correctnessCorrect. |
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.
|
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. |
Review summary — no blocking findingsI reviewed this PR focusing on the correctness-critical areas: Each area is backed by tests derived from the enumeration it constrains (every Behavioral note (not a bug, worth a reader's attention)
Overall correctness verdict: 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 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
Why
A fresh-eyes review of what landed between
e6f95a6band5f2b7f94looked 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.GraphicalFunctionKind, and the XMILE reader never read it:Gf.kindwas declared as a child element where XMILE 4.1.3 makestypean attribute. An extrapolating or discrete table ran as a continuous one. Vensim's own documented example,LOOKUP EXTRAPOLATE(LOOK, 2.5)overLOOK((0,1),(1,1),(2,2)), gave 2.0 where the documentation says 2.5.model_linksreturned links in hash-map order: two opens of one file gave hosts differently ordered link lists in roughly 200 of 483 corpus files.What
bytecode::LookupMode { Interpolate, Forward, Backward, Extrapolate }. A plain application takes the mode of the table's kind;LOOKUP FORWARD,LOOKUP BACKWARDand a newLOOKUP_EXTRAPOLATEbuiltin 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.variable::parse_tablerefuses 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.<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 toDELAY1. The MCP instructions and the Vensim-syntax skill say so.project_io.protogainsModel.sim_specs,ViewElementCompat.shape/name_field/tailandView.sketch_compat. Fields are added, none renumbered, and an absent field reads as before.serde::deserializereturns aResult: a message that lacks what every writer writes is aProtobufDecodeerror naming what is missing, where the reader panicked (an empty buffer decodes to such a message).CausalEdgesResult.edgesis aBTreeMap, somodel_linksreturns(from, to)order.EquationErrorcarries the engine'sdetails, andErrorDetails/VariableDetailsrenderdetails ?? description.Decisions worth a reviewer's eye
test/test-models/tests/subscripted_lookupsreads 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 getsBadTableon 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.<gf discrete="true">, a draft-format spelling, is reported and not acted on: that it meanstype="discrete"is unverified.Resultis the simple fix; nothing checks that every decodable message is read or refused without a panic.Evidence
simulates_subscripted_lookups_mdl(fails without the importer sort);vensims_documented_lookup_examples_simulate_as_documentedholds the LOOKUP FORWARD/BACKWARD/EXTRAPOLATE example values from the Vensim function pages.an_xmile_graphical_functions_type_decides_how_it_is_read; the three kinds match section 3.1.4 at, between and beyond knots.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.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.build_determinismbuilds 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.simlin_error_strby tests.What this does not establish
discrete="true"means discrete, or thatTABXLequalsLOOKUP EXTRAPOLATE. The MDL writer still writesTABXLfor 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.setting_the_sim_specs_of_a_stored_project_changes_its_runis held as an expected failure:SetSimSpecswrites 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.🤖 Generated with Claude Code
https://claude.ai/code/session_01LYR7N9WZwQuFnZFW8JDUgx