Skip to content

Stop conditions end the run where they hold (#2018) - #2148

Merged
wshlavacek merged 13 commits into
mainfrom
fix/2018-stop-during-run
Dec 4, 2026
Merged

wshlavacek merged 13 commits into
mainfrom
fix/2018-stop-during-run

Conversation

@wshlavacek

@wshlavacek wshlavacek commented Dec 4, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #2018.

The bug

A stop condition was asked of the result only after the run had gone to its end time. Two things followed.

  • A run that failed after the condition held failed. A' = A² from A = 1 passes 10 at t = 0.9 and blows up at t = 1. With add_stop_condition("Atot > 10") over (0, 2), main raised SimulationError at t = 1. The branch returns StopConditionMet at t = 0.8999992701816443 (91 rows).
  • A long span was paid for in full.
    • A' = -A to Atot < 1e-3 over (0, 1e6): main took 189 steps and reported the stop at the sample t = 7.0. The branch takes 108 steps and stops at the crossing, t = 6.90777.
    • A Lotka-Volterra cycle met at t = 5 on a (0, 1e4) span: 253,428 steps on main, 156 on the branch.
    • An SSA run of A → 2A to Atot > 1e4 over (0, 30) ran to its timeout on main. On the branch it ends at t ≈ 7.

The fix

  • Asked at each row. The engine now asks an expression stop condition at each row the run records (ODE, SSA, PSA) and ends the run at the first row any condition holds at. When two hold at the same row, the condition added first names the stop.
  • ODE runs end at the crossing. A condition of the form lhs < rhs (or <=, >, >=), or a bare number that is met where > 0, is also a CVODE root function. The run then ends at the crossing, not at the next sample.
  • Where the run is left. The model is left at the stop, with current_time at its time. On main it was left at the end of the span.
  • What the result reports is decided as before. Simulator._stopped asks the result rows after the run. If the engine stopped but no condition holds at any row the result reports, the run raises instead of returning a run cut short.
  • Batches. run_batch, run_replicates and parameter_scan cut rows the same way.
  • A screen in the engine. Before calling into Python at a row, the engine evaluates each condition's comparison itself. It uses the same IEEE operations in the same order as numpy, so it gets the same sign. Where every condition is surely not met, Python is not asked. A NaN, a power of a column, or a condition it cannot compile leaves the decision to Python.

Still asked of the whole result after the run, as on main:

  • callables;
  • conditions that read a species whose reported column is remapped after the solve (assignment-rule targets, variable compartments);
  • NFsim and RuleMonkey runs;
  • ODE runs that re-take rows at a state switch (.net rate laws that switch on the state).

A condition that never holds gives the same run as main, bit for bit. The exceptions, both under Left alone: a comparison only rounding decides, which the branch can find met between samples, and a threshold met at the instant an event fires.

Review

Found while building the branch, fixed in it:

  • Warm path hang. A strict condition whose root landed exactly on an output: CVODE asked for the same output returns the same root, and the warm path went round it for ever. The cold path skipped the root and ended at the next sample.
  • A row the run records again. A .net rate law that switches on the state re-takes the step that crossed the switch, and records the rows inside it again. A condition that held only on the first reading (Y = 9.4e-134, later 0.0063) stopped the run on a row the result then rewrote. Such runs now ask their conditions after the run, as main did.
  • Far starts. A run that starts at t = 1e12 integrates on the time since its start. A root on the time there is quantized (steps of 1.2e-4 on the caller's clock), and the run failed with CV_ILL_INPUT. A condition on the time is asked at the samples alone there.
  • Cost of the per-row call. Calling Python at each of 100k rows cost the EGFR model 583 ms against main's 345 ms. The engine now screens each condition's comparison itself and calls Python only where some condition may hold.
  • Mutation. Two screen mutants (NaN read as not met; constants folded in a different order) left the arrays right but let the run go past the stop. The test now checks that the clock is left at the stop.

Review 1 (whole branch), three defects, all fixed:

  • F3: a crossing on the last sample of a longer span became a stop. sample_times=[1, 5] over (0, 10) with t > 5: the run ended on a row at 5.000000000000018 the caller never asked for, in place of the 5.0 row. Main ran it whole. Cause: an exact zero at a root was asked just past it, and that probe stood in for an unreported row.
  • F1: an event at the stop's threshold raised "This is a bug in bngsim". at (A > 5): A = 0 with stop A > 5: the stop root ended the row, the row's read-ahead then fired the event, and the recorded row no longer held the condition. Main returned the whole run.
  • F2: a total compared with its own value failed with CV_ILL_INPUT. A <-> B with Tot < 10, Tot = 10 conserved: g sat at 0 to rounding, and CVODE refused to go on ("root found at and very near t").
  • Fix for all three: a stop root's exact 0 now reads as the smallest double on the side the condition is on at equality (>: not met; >=: met). CVODE then sees g change sign exactly where the condition does, and returns a root where it already holds. g is never parked at 0, and there is no probe past the root. A stop at a root is not taken where an event's trigger rises there: the row would hold the state after the event, so the condition is asked at the next row recorded, as on main.
  • Notes, also addressed: the docs now say that a callable beside an expression condition is asked of the result up to the stop (N3), that a crossing at an event ends the run at the next sample (N4), and that a condition only rounding decides can be met anywhere rounding puts it (N1). A kernel.py comment that still said the whole interval is integrated was corrected.
  • Full suite: run-time messages cited the issue number, which test_messages_carry_no_issue_references refuses. Reworded.

Review 2 (the fixes after review 1): F1, F2 and F3 rerun on the new build, all fixed. An event fuzz of 6,336 event × condition × sample-grid cases (1,584 more with sensitivities) found no new error, no stop later than main's, and no stop on a row the condition does not hold at. Sensitivities at the last row agree with main to 9e-14. 435 never-met runs are bit-identical. Batch and scan rows equal the single runs. It found:

  • C: from a start far from zero, a stop could return two rows with the same time. From 1e9, A = t with A_tot > 5 crosses on the sample at +5, and returned a second row at 1e9 + 5 with A = 5.000000000000057. A condition met just past the start returned two rows at the start, and the clock did not move. The run integrates on the time since its start, and a root one root tolerance past the row rounds onto the row's time on the caller's clock. Fixed: such a root is declined, and the condition is asked at the next sample (+6, +1), the row main stopped at. The same holds through run_batch and parameter_scan.
  • B: a strict condition on its threshold at the start ends the run just after it. Ctot > 0 with C made from 0 stops at t = 7.6e-25; main stopped at the sample at t = 1. That is the crossing. It is now tested, and the user guide says so.
  • A: a comparison only rounding decides can stop a run main ran whole. Tot < 10 with Tot conserved at 10, over (0, 2000) with 11 samples: the branch stops at t = 5.3e-5, where Tot = 9.999999999999998. Main ran whole, and on a grid of 2,001 samples it stops too (t = 7). The row the branch stops on does hold the condition. The changelog said a condition that never holds gives main's run; it now names this case, and the user guide says to compare with a margin.
  • E: the changelog sentence, two stale comments, and a run-time message that cited the issue number, fixed.
  • D: a delayed event due at the crossing, and a larger bound on the difference at an event's crossing: under Left alone.

CI (Windows): every Windows leg failed to build with an MSVC internal compiler error (C1001) at the screen in make_stop_check: a generic lambda passed to std::any_of read a thread_local declared inside the check's own lambda. The screen loop is now a plain function that owns its thread_local stack and asks the screens in the same order. A stop root's least normal double is written (std::numeric_limits<double>::min)(), so a Windows min macro cannot touch it. The stop-condition test files pass unchanged (853 tests).

Left alone

  • A crossing at an event's trigger is not bit-for-bit main's. Where the condition crosses at the instant an event fires and the event undoes the crossing (at (A < 5): A = 20 with stop A < 5), CVODE locates the event from the stop root's return rather than from the step. The event time moves within CVODE's root tolerance: the species differ from main by up to 1.8e-13 absolute on the tests' two models, and by up to 2.6e-12 absolute (1.9e-12 relative) over review 2's fuzz. Where an event freezes the compared quantity on its threshold (at (A > 5 - 1e-13): k = 0 with stop A > 5), the side rounding leaves it on decides the stop. In 34 such fuzz cases main stopped (A = 5.000000000000063) and the branch did not (4.999999999999904). An event that does not coincide with a crossing, and a condition that never crosses, give main's run bit for bit.
  • A delayed event is not looked ahead to. -> A at rate 1 with at 1 after (time > 4): A = 0 and stop A > 5: the trigger is located up to a root tolerance late, so A passes 5 about 1e-13 before the reset. The branch stops there (t = 5.000000000000044, A = 5.000000000000043). Main ran whole, because none of its samples lands in that window. A sample there would record the same state: main also records a row just before a delayed execution with the state before it. Whether such a run stops is decided at the root tolerance (10 cases in review 2's fuzz). The user guide says so.
  • A condition only rounding decides (a conserved total against its own value, a decaying species against 0) is met where rounding puts it past the value. Main's answer was grid-dependent too (Tot > 10 stopped at t = 0.5 on main). The branch also asks between samples, so it can stop earlier. Documented; no tolerance band.
  • Unscreened conditions cost a Python call per row: a power of a column, or a condition the screen cannot compile, about 1.9 us per row (EGFR, 100k rows: 64.7 ms on main, 255.9 ms on the branch, review 1's measurement).
  • run_batch rebuilds the condition's name map for each row (in_run_stops walks every species). The whole stop overhead of a 200-row batch was about 50 us per row.
  • A broken later condition now raises even where an earlier one stops (Ctot > 2 then Atot.nope > 2): every condition is asked at each row, so the broken one raises UsageError at t = 0. Main stopped on the first at t = 3.
  • Still asked after the run, as on main: network-free runs, .net runs that re-take rows at a state switch, conditions on remapped species, and conditions on the time in a run started far from zero (asked at the samples).

Tests

  • python/tests/test_stop_condition_during_the_run.py, 154 tests: 114 fail on main. The 40 that pass on main are controls, and their docstrings say so (11 test functions).
  • The tests from review 1's probes (F1, F2, F3, the event at a stop) fail on review 1's build: 21 of 25 there. The four from review 2's C fail on review 2's build.
  • Existing stop-condition tests are updated to the new stop: the model and the clock are left at the stop, and the stop is at the crossing time.

Mutation checks

Each mutant was switched on by an environment variable in a separate copy of the package; the source was then restored and the rebuilt extension checked byte-identical.

  • Round 1, 46 mutants of the first implementation (C++ ODE, SSA and PSA paths; Python wiring). Each survivor got a test that kills it, was shown to change no result (an assignment-rule target the run copies back is never read by an in-run condition), or sat in code the branch later removed or rewrote. Two of the tests it led to found bugs in the branch (the re-taken rows and the far-start time root in Review above).
  • Round 2, 12 mutants of the screen. Two (a NaN read as not met; constants folded in another order) left the arrays right but let the run go past the stop: the test now checks that the clock is left at the stop. One is provably no change (a power is NaN to the screen, so Python decides).
  • Round 3, 12 mutants of the post-review-1 code (the side of an exact zero, the event check at a root, the side check in set_stop_roots, the warm path's loop guard). Ten are caught; two needed new tests (a trigger already true at the crossing; a root on an output the check declines, through the engine's own options). Two remain:
    • A dormant event counted as rising is not caught. The filter is the row read-ahead's own, which main has. An event is dormant only after a clamp chatters on solver noise (GH fix(codegen): bound the sensitivity df/dp derivation with a #95-style budget (#90) #95), and I could not build a test that makes one rise at a stop's crossing (a clamp under decay held its species at exactly 0 and never went dormant).
    • Not putting the species back after the event check changes no result: every path after it sets them from the state before reading them.
  • Round 4, 5 mutants of the far-start check added after review 2 (no check; >= for >; compared with the start alone; compared with the row's own time; compared on the run's clock). All five are caught. The last two decline every far root, and the existing far-start crossing test catches them.

Corpus A/B

824 models (224 .net and 600 SBML from the parity corpora), each run plain and with two never-met conditions (time < -1, and X > 1e300 for the model's first observable X), on main and on the branch. ODE (0, 10), 21 points: 809 of 809 runs bit-identical to main, both ways. SSA (0, 1), 11 points, seed 7: 223 of 223 bit-identical; two runs hit the 60 s timeout on both builds, and their messages differ only in the elapsed time they print. The A/B ran on the code before review 2. The one engine change since then acts only when a stop root is found in a run started far from zero, and none of these runs has either.

Cost

EGFR (Blinov 2006 .net), ODE over (0, 100) with 100,001 rows, 555 steps; best of 3, two runs each agreeing to 2 ms:

main branch
no condition 305 ms 305 ms
a condition never met (X > 1e300) 343 ms 403 ms
the same, roots switched off 345 ms
the same, the engine's screen switched off 578 ms

With no condition, nothing changes. A condition never met costs about 0.6 us per row more than main's check after the run. That cost is CVODE evaluating the stop root at each output it returns to; the per-row check itself costs no more than main's, because the engine's screen keeps Python out of it. A condition met early costs the short run (see The bug).

Local runs

On the head 047ba77 (the branch merged with main at 49c1979), macOS arm64, built as CI's macos-15 leg builds it (MIR on, KLU required; HAS_KLU, HAS_MIR, HAS_LAPACK_DENSE and HAS_NFSIM true), BNGSIM_SKIP_AUDIT=strict pytest -p no:cacheprovider python/tests -n auto --dist worksteal:

  • Without BNGPATH: 27,292 passed, 437 skipped, 153 xfailed, 0 failed. The parity-harness tests: 2,444 passed, 68 skipped. The SBML suite gate matches its baseline (1,578 of 1,789 pass). Per-file counts match main's macos-15 counts (ci/test_file_counts.py compare, rc 0).
  • With BNGPATH (BNG2.pl 2.9.3): 27,569 passed, 160 skipped, 153 xfailed, 0 failed.

These stand in for the macos-15 legs while GitHub has no macOS runner for them (see the PR comment).

…n output (#2018)

A strict condition whose root CVODE landed on an output time exactly was not
met there, and the warm path asked CVODE for the same output again, which
returned the same root, for ever; the cold path skipped it and ended at the
next output. A root on the output is now the output's row, and the time a
few roundings past it stands in for the row up to the next output.

New tests in test_stop_condition_during_the_run.py (34 of 53 fail on main;
the rest are controls). Docs, CLI help, the add_stop_condition docstring and
the stubs say where a run ends.
#2018)

- A run whose rows a state-switch re-take can record again (an ODE run of a
  .net model with a state switch) asks its conditions of the result alone: a
  stop on a row the re-take later rewrote returned Y = 9.4e-134 where the run
  holds 0.0063.
- A run integrated on the time since a start far from zero drops the stop
  roots that read the time and asks those conditions at its rows: the root
  there was quantized and CVODE failed with CV_ILL_INPUT at 1e12.
- The engine decides a comparison it can compute as numpy does (no power of a
  column) without calling Python at each row; Python is asked where one may
  hold. A condition never met cost 2 us a row, 0.2 s over 1e5 rows.
- Constants that read no column are folded as Python computes them.
- The SSA run's clock write-back drops a branch that could not change it.
- Tests for each, and for the rows before the first and after the last
  sample time, PSA integrals and rate-rule targets at a stop, a far-start
  stochastic clock, and the safety net on run_batch and run_replicates.
…t holds (#2018)

Two screen mutants left every result array right: a NaN read as not met
(inf >= inf), and a folded constant reckoned in doubles (2**53 + 1 - 2**53).
The engine then ran past the stop and the result was cut after the run,
leaving the clock at the end of the span. The test now holds the clock at
the stop and asks that Python saw the row.
…2018)

A stop root's g of exactly 0 now reads as the smallest number on the side
the condition is on at equality, so CVODE sees g change sign where the
condition does and returns the root where it already holds. The probe past
the root is gone. A conserved total compared with its own value no longer
parks g at 0, which CVODE refused to go on from (CV_ILL_INPUT).

A crossing at the instant an event's trigger rises is not taken as the stop:
the row there holds the state after the event. The condition is asked at the
next row recorded, as on main. A crossing on the last sample of a longer span
belongs to no reported row and is not a stop.

run_batch and run_replicates take a row's early end for a stop only where
the engine was given conditions to ask, as run() does. Docs: a callable
beside an expression is asked of the result up to the stop; conditions that
only rounding decides; a crossing at an event. Run-time messages cite no
issue numbers.
…ety net (#2018)

run_batch and run_replicates take any short row for a stop, as before:
a row ends short only on a stop or a steady state (a timeout raises), so
a short row no condition holds at is a bug, and the check says so rather
than returning the row.
…2018)

A run far from zero keeps its own clock, and a stop root lies past the
row before it by about its root tolerance. Moved back to the caller's
clock it can round onto that row's time: from 1e9, A = t crossing 5 on
the sample at +5 returned a second row at 1e9 + 5, and a condition met
just past the start returned two rows at the start with the clock left
there. Such a root is now declined, and the condition is asked at the
next sample, the row main stopped at.

Tests for that, and for a strict condition on its threshold at the
start, which now ends the run within the root tolerance of the start.
The user guide says both, and that a delayed event is not looked ahead
to. The changelog no longer says a condition only rounding decides gives
main's run. Two stale comments; a run-time message no longer cites the
issue.
MSVC failed on the stop check with an internal compiler error (C1001)
at the std::any_of whose generic lambda read a thread_local declared in
the check's own lambda; every Windows leg stopped there. The screen loop
is now a plain function holding its own thread_local stack, and asks the
screens in the same order, stopping at the first that may hold.

The least normal double at a stop root's side is written
(std::numeric_limits<double>::min)(), safe from a min macro.
@wshlavacek

Copy link
Copy Markdown
Collaborator Author

The macos-15 legs of python-tests have had no runner for over an hour, so I ran them here on an arm64 Mac (macOS 27.2) in their place, the way the workflow runs them.

Head 047ba77, which is this branch merged with main at 49c1979. Built with BNGSIM_ENABLE_MIR=ON and KLU required, and checked that HAS_KLU, HAS_MIR, HAS_LAPACK_DENSE and HAS_NFSIM are all true. BNGPATH unset.

  • Python suite (BNGSIM_SKIP_AUDIT=strict, pytest -p no:cacheprovider python/tests -n auto --dist worksteal, both shards in one run): 27,292 passed, 437 skipped, 153 xfailed, 0 failed; rc 0.
  • Parity-harness tests (parity_checks/tests): 2,444 passed, 68 skipped, 0 failed; rc 0.
  • SBML suite gate (ci/sbml_suite_gate.py): matches the baseline. 1,789 cases ran: 1,578 pass, 175 fail to load, 33 fail to simulate and 3 give wrong values, the same as the baseline.
  • Per-file counts (ci/test_file_counts.py compare) against main's macos-15 counts artifact from run 47348212722 at 49c1979: rc 0. The only change is one more skip in test_version_consistency.py, test_cmake_project_version_picks_up_pyproject. It skips because the CMake build directory is outside the checkout here, so it says nothing about this change.
  • The same Python suite with BNGPATH pointing at BNG2.pl 2.9.3, on the same build: 27,569 passed, 160 skipped, 153 xfailed, 0 failed; rc 0.

@wshlavacek
wshlavacek merged commit d412bf8 into main Dec 4, 2026
22 checks passed
@wshlavacek
wshlavacek deleted the fix/2018-stop-during-run branch December 4, 2026 17:20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant