Skip to content

engine: a validation battery a modeler can trust - #1077

Merged
bpowers merged 2 commits into
mainfrom
sweep/battery
Oct 3, 2026
Merged

bpowers merged 2 commits into
mainfrom
sweep/battery

Conversation

@bpowers

@bpowers bpowers commented Oct 3, 2026

Copy link
Copy Markdown
Owner

Why

run_tests is how an agent asks whether a model is well behaved, and what it flags, an agent repeats to the modeler. A fresh-eyes review ran it over the corpus and found its findings were mostly noise:

  • 39 of 51 extreme-condition failures were divisions by a reference constant set to exactly zero.
  • All 26 "goes negative" flags were false.
  • Dates were scaled as if they were durations.
  • Behavior families flipped on wiggles of 1 to 5% of a series' range.
  • One integration measurement was reported twice.

Meanwhile a real flaw passed: an AI-generated model whose cash falls to -6.5 million in its own run.

What

  • Each check says what happened, not why. Under an extreme, a stock's element or a series the model marks non-negative is flagged when it goes below zero and the model's own run keeps it at or above zero. A stock already below zero somewhere in its own run is a signed quantity and is not judged.
  • The model's own run is a check of its own, listed first. A series that is not a number there is said once; a marked series below zero comes with a note that the engine does not enforce the marking.
  • Nothing checked is reported as passed. A model that does not simulate says why once (runFails); a test that would compare nothing (stocks only inside modules, nothing recorded) is skipped saying so.
  • Extremes are conditions of the system: a tenth of a divisor; a time constant down to a tenth and at least four DTs a stage, in its own unit of time; a date to the run's start and past its stop; a fractional rate up to 1/(2 DT); a share up to the whole. A caller can give its own extremes.
  • Integration error is one measurement: Richardson's estimate and the observed order from the half- and quarter-DT runs, read at the model's own row times, on or off the step grid. At or under 1% of a stock's scale passes, up to 5% is flagged, above fails, naming the time constant DT is too large for.
  • Sensitivity flags a change of behavior family that moves the series materially in one of the runs. Each run is read at its own scale with magnitudes shared (series::compared_scales, the one owner, which run_experiment uses too). A response shows an oscillation's damping in both runs.
  • Listing: checks that make the same change of the same series are listed once, naming the others; at most three responses per check; what the defaults leave out is said once.
  • Memory: value-only runs hold at most 64 MiB of results at once (runs::concurrent_runs).

Decisions worth a reviewer's eye

  • Rules were deleted when a labeled corpus showed they bought nothing. Each of these was switched off and the corpus re-run, with identical listed rows and labels: a selector default, a second coarser reading of turns, an at-rest special case, divisor-following through flows and tables. Also removed: the inference of why a stock went negative (it told a modeler false things for arrayed and signed stocks), a finer-DT re-run of sensitivity, and a growing-oscillation family (it added false alarms on four models and found nothing).
  • Loss of stability is shown, not flagged: the response carries the classifier's damping for both runs.
  • A folded row leads with its strongest check. No rule picks a "more meaningful" lead.
  • The labels are one implementer's judgment. An independent reviewer sampled 57 rows of an earlier version and agreed with 53.

Evidence

  • Labeled corpus (ignored gate, release), 29 models. Before this change the battery listed 96 non-passing checks, of which 71 would be accepted by a modeler and 25 not; now 68 listed, 52 accepted, 16 not. Every listed check carries a one-line reason a reader can disagree with.

    Model Before (the original review's probe) After (this branch on main)
    World3 extremes: 8 failed, 1 flagged; integration: 2 failed; sensitivity: 44 flagged; listing capped at 20 12 listed, 9 accepted: integration flagged (2 to 4% at DT 0.5) and 8 sensitivity findings (shifts in overshoot and collapse, consumption share, capital life, arable land). Rejected: land fertility half and double (start-up), a unit carrier. No extreme failures.
    C-LEARN extremes: 12 failed (zero divisors), 22 flagged; the listing was 12 zero-divisions and 7 false flags, with no sensitivity 9 listed, 4 accepted: two stop-growth-year rows (emissions go negative after 2000), integration flagged at 1.4%, natural N2O half. Rejected: definitional and reference constants.
    AI-generated model units failed; extremes: 4 failed, 1 flagged; integration failed; cash at -6.5M in its own run hidden 3 listed, 3 accepted: the own run first (three marked flows far below zero), then units and integration.
  • Integration against exact solutions (adversarial reviewer's measurements): reported against true error 0.0616 / 0.0636 for exponential decay at DT 0.6 with a save step of 0.7 under Euler; 0.336 / 0.340 for an oscillator under RK2. Read at the model's nominal save step instead of its row times, the first case would report 0.252.

  • Memory: C-LEARN peaks at 446 MB with the bound and 736 MB without, measured by the reviewer.

  • Each rule is pinned from both sides: the integration thresholds at 0.997% / 1.0001% and 4.990% / 5.021%; material movement exactly at 5%; the own run first with more failures than the list holds; the batch bound with a test budget and a peak-concurrency count; a non-simulating model's answer at 690 bytes.

  • Mutation testing: 31 of 32 mutations of the changed rules are killed; the survivor is a test written against the constant it checks.

  • The pre-commit hook passed in full.

What this does not establish

  • The labels are one person's judgment, sampled by one reviewer.
  • A folded row can lead with a check a modeler would reject, with an accepted one in sameChange.
  • Stocks inside modules are skipped, not tested.
  • 16 known false alarms remain, in three classes: start-up transients a parameter deepens, an oscillation whose period moves past the horizon, and constants that are definitions (which need Vensim's == or the author's declared input range, neither carried yet).
  • DELAY FIXED models do not simulate on main, so the corpus says nothing about them.

🤖 Generated with Claude Code

https://claude.ai/code/session_01LYR7N9WZwQuFnZFW8JDUgx

run_tests runs the model tests of system dynamics practice (units,
extreme conditions, integration error, sensitivity, loop knockouts and
disturbances), and an agent repeats what it flags to the modeler. On the
corpus most of that was noise: divisors tried at zero, dates scaled as
durations, rounding read as a stock going negative, families flipped by
wiggles, one measurement reported twice, while a model draining its cash
to -6.5 million in its own run passed.

Each check now says what happened, not why. Under an extreme, a stock's
element or a series the model marks non-negative is flagged when it goes
below zero and the model's own run keeps it at or above zero. The
model's own run is a check of its own, listed first. Nothing checked is
reported as passed: a model that does not simulate says why once, and a
test that would compare nothing is skipped saying so.

Extremes are conditions of the system: a tenth of a divisor, four DTs a
stage in a time constant's own unit, a date's start and past-stop, a
rate no faster than Euler can follow. Integration error is one
Richardson measurement at the model's own row times: it passes at or
under 1% of a stock's scale, is flagged up to 5% and fails above,
naming the time constant DT is too large for. Sensitivity flags a
change of behavior family that moves the series materially, reads each
run at its own scale with magnitudes shared (series::compared_scales,
which run_experiment uses too), shows an oscillation's damping, and
lists checks that make the same change of the same series once.

Rules a labeled corpus showed buy nothing are left out. Value-only runs
hold at most 64 MiB of results at once, so memory does not grow with
the host's cores. tools/battery_corpus.json labels every check the
battery lists over 29 corpus models, and an ignored gate holds it to
those labels' counts.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 3, 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-03T06:14:33.036434Z 839a364 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@codecov

codecov Bot commented Oct 3, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 97.26027% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 92.69%. Comparing base (afdc027) to head (2ad8658).

Files with missing lines Patch % Lines
src/simlin-engine/src/tools/runs.rs 86.66% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1077      +/-   ##
==========================================
+ Coverage   92.66%   92.69%   +0.03%     
==========================================
  Files         308      308              
  Lines      188506   189518    +1012     
==========================================
+ Hits       174672   175672    +1000     
- Misses      13834    13846      +12     

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

@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: 839a364b32

ℹ️ 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/tools/battery.rs Outdated
Comment on lines +3619 to +3620
if worst <= INTEGRATION_TOLERANCE {
return Ok(vec![check]);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Flag nonconvergence before applying the error tolerance

When the half-to-quarter-DT difference does not converge but the model-to-half-DT difference is at or below 1%, this early return leaves the check's default outcome as Passed and skips the branches that report nonconvergence. A discrete, chaotic, or DT-reading model can therefore pass solely because its first refinement happens to move less than the tolerance; handle !converges before allowing this return.

AGENTS.md reference: src/simlin-engine/AGENTS.md:L234-L234

Useful? React with 👍 / 👎.

Comment on lines +1395 to +1400
check
.result
.responses
.iter()
.find(|r| material(r))
.map(|r| (r.variable.clone(), r.family))

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 Compare every material response before folding checks

When a sensitivity check has multiple material responses, this key considers only the first one. If two parameters produce the same leading change but only one also changes another recorded stock, the weaker check is folded away wholesale and that distinct response disappears from the battery output; compare the complete set of material responses, or merge unique responses before discarding a check.

AGENTS.md reference: src/simlin-engine/AGENTS.md:L234-L234

Useful? React with 👍 / 👎.

Comment on lines +950 to +952
.filter(|(key, _)| {
super::series::column_of(model, key.as_str()).map(|(owner, _)| owner)
== Some(ident.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 Reject module instances as numeric series

When a citation names a module instance, column_of assigns every module·child result column to that module, so series_of now treats the module as a collection of numeric series. Consequently goes_negative can verify a claim about the module when any child is negative, and single-series citations such as ends_near can verify the module itself when it happens to contain only one result column, even though a module has no value of its own; reject Variable::Module here or require the caller to name a qualified child variable.

AGENTS.md reference: src/simlin-engine/AGENTS.md:L236-L236

Useful? React with 👍 / 👎.

Comment thread src/simlin-engine/src/tools/battery.rs Outdated
Comment on lines +1085 to +1088
(TestName::Units, _) if !declares_units(model) => Err(
"the model declares no units, so there is nothing to check: units are checked \
once variables declare them"
.to_string(),

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 Run the units check for invalid project unit definitions

When the project contains a malformed or conflicting unit declaration but the selected model's variables have no unit strings, this guard skips units_check entirely. units_check explicitly includes UnitDefinition diagnostics, which are project-level and exist independently of whether a model variable references a unit, so the battery reports that there is nothing to check while hiding a real unit-definition error; consult the project diagnostics before taking this skip path.

AGENTS.md reference: src/simlin-engine/AGENTS.md:L95-L95

Useful? React with 👍 / 👎.

@claude

claude Bot commented Oct 3, 2026

Copy link
Copy Markdown

Code review findings

Reviewed the new validation battery (src/simlin-engine/src/tools/battery.rs) and the shared helpers it touches in runs.rs, series.rs, experiment.rs, and verify.rs. Overall the implementation reads carefully and the surface matches the design, but a couple of edge cases in battery.rs can produce misleading or wrong outcomes.

[P2] integration_error divides by a zero scale for a stock that stays at exactly 0

src/simlin-engine/src/tools/battery.rs lines 3559-3575 (and scale at 3681-3690).

For every stock element, the test computes scale = scale(&a) from the base series a and then first = first.max((a[row] - at_half).abs() / scale). If a stock element is identically 0 throughout the base run, scale(a) == 0. A finer run that produces any non-zero value at that element (floating-point noise from reordered RK stages, a lookup, etc.) makes the division nonzero / 0 == +inf, which propagates through first = inf, observed = Some(inf), order = inf, converges = true, factor = 1.0, worst = inf > INTEGRATION_FAILURE, so the check reports Outcome::Failed with difference: inf on a model whose integration is actually fine. Contrast with responses at 3906-3910, which guards this case with shared.max(f64::MIN_POSITIVE); integration_error has no such guard. Clamping the denominator (e.g. scale.max(magnitude(a)).max(f64::MIN_POSITIVE)) would make the behavior consistent with the sensitivity path.

[P2] ExtremeRule::Zero and ExtremeRule::TenTimes violate the "no low above value, no high below value" invariant for negative constants

src/simlin-engine/src/tools/battery.rs lines 2007 (Zero: |_| 0.0) and 2028 (TenTimes: |value| value * EXTREME_FACTOR).

For a constant with a negative value that is not identified as a time constant, date, divisor, share, or fractional rate (e.g. a temperature offset, a signed delta, a negative setpoint), the low = 0 is above the value and the high = 10 * value is below it (ten times a negative is more negative). The skip filter in extreme_conditions only elides the check when to(value) == value, which does not fire here, so the check runs and the output labels extremes on the wrong side of the value - a reader sees "low: 0" when the extreme was actually a higher number than the constant, and "high: -50" when it was lower. Other rules guard this with within/beyond (ShortTime, Tenth, Whole, FastestRate) or by only firing for positive values (share_whole requires v > 0.0); only Zero and TenTimes leave the invariant unprotected. Wrapping with within(value, 0.0) and beyond(value, value * EXTREME_FACTOR), or picking the sign-aware extremes, would restore the invariant.

Overall correctness

The patch is mostly correct at this effort level. The two issues above are edge cases that do not block the branch's goal (the main battery, the Richardson/sensitivity logic, the concurrent_runs memory bound, the compared_scales/scale_in_run sharing, and the recheck path all look right), but each can produce a misleading result on a legitimate model and is worth folding into the branch.

The integration check passed a model whose first refinement moved it
under the tolerance before asking whether the second refinement moved
it less: a model that reads DT can move 0.5% at half the DT and 5% at a
quarter, and its error is not bounded by the first. Convergence is
decided first.

The units test was skipped when no variable declares units, though a
project's unit definitions can be malformed on their own. The check
runs, and is skipped only when it finds nothing and no variable
declares units.
@bpowers

bpowers commented Oct 3, 2026

Copy link
Copy Markdown
Owner Author

Follow-up commit 2ad8658 for the Codex review:

  • Non-convergence before the tolerance: taken. The early pass is converges && worst <= INTEGRATION_TOLERANCE; a flow that reads DT and moves the run 0.5% at half the DT and 5% at a quarter is flagged as not converging (a new row in a_model_whose_finer_runs_do_not_converge_is_flagged_saying_why).
  • Units check with a broken unit definition: taken. The check runs first and is skipped only when it finds nothing and no variable declares units (a_broken_unit_definition_is_checked_where_no_variable_declares_units).
  • Comparing every material response before folding: declined. A folded row is one finding about one series and names every constant; picking or merging leads is a rule this change deliberately does not have.
  • A module instance as a numeric series: correct, and it lands with the tools change that follows, which makes a module instance own no results column in the one place columns are mapped to variables.

@claude

claude Bot commented Oct 3, 2026

Copy link
Copy Markdown

Reviewed the diff against afdc027, focusing on correctness in battery.rs, series.rs, runs.rs, and surrounding files. No high-priority bugs surfaced. A few low-priority observations that likely do not need action:

  • [P3] element_start_values for a Module target emits inner-variable values with empty element keys. src/simlin-engine/src/tools/battery.rs:2962-2985 — save_check::column_variable(\"m·x\", declared) returns \"m\" as owner, so key[owner.len()..] = \"·x\", strip_prefix('[') fails, and unwrap_or_default() yields \"\". The duplicate (offset, \"\", value) entries do not reach a user-visible wrong result: loop_knockout rejects modules first, and extreme_conditions/sensitivity/disturbance run into settable() returning Err before anything consumes the garbage. The one minor behavior change is is_zero_valued(module) can be true when every inner variable happens to be zero at t=0, producing a misleading "is zero" rather than "is a module" not_run message in disturbance. Pre-change code returned an empty Vec here.
  • [P3] listed() subtraction is unguarded. src/simlin-engine/src/tools/battery.rs:1387 — MAX_RESULTS - taken.len() is safe today because the preceding while taken.len() < MAX_RESULTS cap guarantees taken.len() <= MAX_RESULTS, but a future change that emits more than one Condition::OwnRun check (per-test, per-model, etc.) would underflow. MAX_RESULTS.saturating_sub(taken.len()) would be defensive at no cost.
  • [P3] held_at only inspects the first element of an arrayed constant. src/simlin-engine/src/tools/battery.rs:~4082 — for an arrayed constant whose elements differ in how half/double clamps them, the reported ExtremeRule reflects only element 0. Minor reporting inconsistency; the check itself behaves per element.

Verified not bugs: memory accounting units in concurrent_runs (bytes vs. floats correctly multiplied by size_of::<f64>()); division-by-zero guards (run_bytes.max(1); DTS_PER_FASTEST_RATE, tc.stages, dt, per all > 0); saturating_mul on run_bytes; Richardson's factor = 2^p / (2^p - 1) applied to |x(h) − x(h/2)| is the correct error estimate at h; compared_scales is NaN-safe (magnitude returns non-negative finite); rows_at correctly maps base save times to half/quarter run indices for both on- and off-grid save steps; the pool-build fallback in execute_values is a correct serial fallback; verify.rs::GoesNegative with scale=0.0 correctly compares against rounded-reported values; the extremes input validation (duplicate detection, low > high, NaN rejection) is complete; BehaviorFamily::of's direction-None fallback is unreachable because trend()/single_turn()/overshoot() all set direction: Some(...).

Overall correctness: correct. The patch is a substantive, carefully-structured refactor that keeps the public types additive, pins its claims with corpus data, and does not introduce correctness regressions I can confirm.

@bpowers
bpowers merged commit 2eb1d51 into main Oct 3, 2026
18 checks passed
@bpowers
bpowers deleted the sweep/battery branch October 3, 2026 13:19
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