Repository navigation
engine: count a run's steps and read its rows by time - #1075
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. |
There was a problem hiding this comment.
💡 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".
| // 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( |
There was a problem hiding this comment.
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 👍 / 👎.
| /// 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 |
There was a problem hiding this comment.
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 👍 / 👎.
| let text = match var.get_equation() { | ||
| Some(datamodel::Equation::Scalar(text)) | ||
| | Some(datamodel::Equation::ApplyToAll(_, text)) => Some(text.as_str()), |
There was a problem hiding this comment.
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.
a4c28e5 to
0b7a52c
Compare
Codecov Report❌ Patch coverage is 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. 🚀 New features to boost your workflow:
|
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.
|
Follow-up commit 9bd004e for the Codex review:
|
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.
Review findings[P1]
|
## 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 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 += dtand its saved rows by roundingsave_step / dt, so:PULSEcould fire a step late or lose its last pulse;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::Specsstates the step grid once: stepkis atstart + k*dt; a run is steps0..=final_step; saved rowmis the first step at or afterstart + m*save_step; a time written as a step's is read as that step withinSTEP_TOLERANCE. The VM and wasm compute it in the samef64operations.Specs::refusalis 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 withBadSimSpecs, its numbers written as a person writes them.SaveStepOffTheStepGrid.PULSEfires at the first step at or after each pulse time, pulse times computed by multiplication.Vm::run_until);f64::EPSILONof the scale it is computed from (per element), and otherwise report the series' own numbers;Decisions worth a reviewer's eye
PULSEoff 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 StellaPULSEs are all at step times.SAVEPERhandling there is unverified.gap / 4feeding a stock,SMTH1,MAX) reads as moving, soanalyze_loopscan report a share for a loop whose stocks move only by rounding.Evidence
simple_harmonic_oscillator's worst error 2.2e-12 to 7.1e-15), andSingle_Pendulum, an off-gridSAVEPER, 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.read_behavior,read_variables,run_experimentandverify_findings, which agree on mode and numbers.What this does not establish
SAVEPERorPULSEtime.🤖 Generated with Claude Code
https://claude.ai/code/session_01LYR7N9WZwQuFnZFW8JDUgx