Repository navigation
engine: keep flow order and reach every reference in patches - #1072
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 #1072 +/- ##
==========================================
+ Coverage 92.62% 92.66% +0.03%
==========================================
Files 308 308
Lines 187921 188506 +585
==========================================
+ Hits 174061 174673 +612
+ Misses 13860 13833 -27 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
ReviewNo blocking bugs found. The PR's mechanics check out across the areas most sensitive to the change:
Overall correctnessCorrect. The surviving edge cases the PR itself calls out (printer not yet quoting zero-argument builtins for a rename to |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 4e06575579
ℹ️ 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".
| let end = canonicalize(end); | ||
| let (_, path) = split_scope_prefix(&end); | ||
| path.split(MODULE_SEPARATOR).next() == Some(ident.as_ref()) |
There was a problem hiding this comment.
Preserve wiring for dotted local names on delete
When the deleted variable is a supported dotted local name such as x.foo and x is not a module instance, its canonical identifier is x·foo and the compiler resolves that entire spelling as the local variable. This predicate instead splits at · and compares only x against x·foo, so a module reference whose src is x.foo survives the deletion and leaves the project with an unknown dependency. Check the whole resolved local name before interpreting the first segment as a module-instance path.
AGENTS.md reference: src/simlin-engine/AGENTS.md:L178-L181
Useful? React with 👍 / 👎.
| export function canonicalModelName(name: string): string { | ||
| return name === '' ? 'main' : canonicalize(name); |
There was a problem hiding this comment.
Canonicalize model separators like the engine
When equivalent model names use . and · spellings—for example, an existing model named a·b and a module ident a.b—this helper reports the requested name as unused because the TypeScript canonicalize leaves . unchanged, while the Rust engine canonicalizes it to ·. The create-model handler then submits AddModel("a.b"), which the engine rejects as a duplicate, so creating or duplicating the module model fails despite this preflight helper being intended to choose a usable name.
Useful? React with 👍 / 👎.
| pub fn canonical_model_name(name: &str) -> std::borrow::Cow<'_, str> { | ||
| if name.is_empty() { | ||
| return std::borrow::Cow::Borrowed("main"); | ||
| } | ||
| crate::common::canonicalize(name) |
There was a problem hiding this comment.
Treat canonically empty model names as main
When a project already has the common unnamed model and a caller adds a nonempty spelling that canonicalizes to empty, such as whitespace-only " ", this function returns "main" for the former but "" for the latter. AddModel therefore accepts both and project_duplicate_models reports no collision, while db::sync::filed_models keys both with ordinary canonicalize and silently keeps only the later model; compilation can consequently run a different, potentially empty model instead of rejecting the project. Apply the main substitution after canonicalization so every empty canonical form receives the same key.
AGENTS.md reference: src/simlin-engine/AGENTS.md:L63-L63
Useful? React with 👍 / 👎.
|
Follow-up commit 816cf35 for the Codex review:
|
Review SummaryI reviewed the main structural changes in this PR (patch rename logic in
Potential inconsistency (not blocking)One minor pre-existing inconsistency the PR surfaces: VerdictOverall correctness: the patch is correct. No blocking issues found. |
816cf35 to
0844832
Compare
A patch sorted a stock's inflow and outflow lists, and a flow rename sorted every stock's. That order is the flows' priority (XMILE 1.0 section 4.2): renaming an unrelated flow swapped which of two queues a conveyor served first, and put a queue's overflow outflow first, which does not compile. Lists keep the order they were given. A rename missed references: a conveyor's parameters, a leak's fraction, a macro's parameters, and every read of a sub-model's variable from the models that instantiate it. Variable::expression_texts and Model::map_variable_names state once where a variable holds expression text and where a model holds a name; one resolver says what a reference names through module instances, as DepScope::resolve does; and the new name is spliced into the text at each reference's span, so the rest comes back as written. The compiler reads an identifier inside a subscript's brackets three ways, so a rename that would have to choose (a dimension's name, or an element written alone in a subscript, before or after) is refused and changes nothing, rather than replaying a rule that is not one rule. A rename does not give a variable one of the engine's clock names, deliberately more strictly than the compiler resolves them. SharedVec::edit_each kept a shared element's edit only when its closure said so; update takes a pass that reads an element and returns its replacement, which cannot change one and leave it out. Datamodel equality compares floats bit for bit, so a table holding a NaN equals itself and is set once, and db::sync skips a variable whose allocation is the one its input was last set from. InputMemory states when that memory may be trusted, and a db after any sequence of syncs, staged syncs and rollbacks is held to what a fresh one holds. Two models known by one name (canonical, an unnamed model being main) are refused at compile and by AddModel, because the db files both under one name and would run a model other than the one a patch edits; only the last is synced. A project model named for a stdlib model gets inputs of its own. SetSimSpecs clears the default model's own specs, so the edit is what the run reads. libsimlin's add_model stages its edit, and the editor compares model names as the engine does.
A delete unwired a module reference by the first segment of its path, so deleting a variable named `x.foo` left a read of it wired (a dependency on a variable the model no longer has), and deleting `x` took the wiring of `x.foo` with it. A path starts at its first segment only when that segment is a module instance; otherwise the whole spelling is one local name, as DepScope::resolve reads it. canonical_model_name decided "empty" on the name as written, so a blank name was not the unnamed model's, AddModel accepted both, and the db filed both under the one empty key and kept only the later. Empty is decided on the canonical form, in the engine and in the editor's twin.
0844832 to
3dbedc2
Compare
## 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 the structural-sharing work that landed between
e6f95a6band5f2b7f94(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.UpsertStockandUpdateStockFlowssorted 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_awent from 0, 2, 4, 6, 8 to all zeros), and moved a queue's<overflow/>outflow to the front, which does not compile.ACTIVE INITIALonly: 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_eachrested on a convention. It kept a shared element's edit only when the closure returnedtrue. Four of the rename's arms could reportfalseafter changing their text without any test failing, and "shared" is the state a host with undo history is in.==was not reflexive on NaN, so a lookup table holding one was set again, and its variable recompiled, on every sync.What
Variable::expression_texts) and where a model holds a variable's name (Model::map_variable_names, byNameRole). Both destructure without.., so a new field fails to compile until it is classified.patch::Rename, mirroringdb::DepScope::resolve), so it reaches equations, modulesrc/dstand 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 au16span 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>)replacesedit_each. A pass that reads an element and returns its replacement cannot change one and leave it out.bitwise_eq!, which refuses an unmarked float), every datamodel type isEq, and the separateIdenticaltrait is gone.db::syncskips a variable whoseArcis the one its input was last set from.InputMemoryis the one statement of when that memory may be trusted.main): by the compile, by one project-level diagnostic, and byAddModel.AddModelalso 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.SetSimSpecsclears the default model's own specs (Project::default_model), so the edit is what the run reads.add_modelstages its edit, so a refused add changes nothing; the diagram editor compares model names as the engine does.Decisions worth a reviewer's eye
RenameVariableleaves 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.Evidence
ModelOperationvariant; the two fixtures whose series depend on list order are unchanged by an unrelated rename (on main they flipped).a_rename_is_refused_or_changes_no_series, 26 rows checked againstRefusal::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.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).ModelOperationandProjectOperationwithout a wildcard.db.syncafter 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.pi) changes no series, now that the printer quotes such a name (engine: one equation normal form and a sound save check #1073).setting_the_sim_specs_of_a_stored_project_changes_its_run(added by engine: read tables by kind and keep projects in protobuf #1071 as an expected failure waiting on this change) passes, and its marker is removed.What this does not establish
tools::resolve_datamodel_model,analysis::model_snapshotand libsimlin'ssimlin_project_get_modeldo not yet useProject::default_model, and the db files an unnamed model under""rather thanmain.🤖 Generated with Claude Code
https://claude.ai/code/session_01LYR7N9WZwQuFnZFW8JDUgx