Repository navigation
feat(rust)!: pybamm.rust's own errors, array-likes, threads and Ctrl-C - #6138
Open
BradyPlanden wants to merge 7 commits into
Open
BradyPlanden wants to merge 7 commits into
BradyPlanden wants to merge 7 commits into
Conversation
This was referenced Nov 30, 2026
BradyPlanden
marked this pull request as ready for review
November 30, 2026 12:00
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## stack/10a-input-interpolant #6138 +/- ##
===============================================================
- Coverage 98.42% 98.41% -0.01%
===============================================================
Files 364 364
Lines 39303 39311 +8
===============================================================
+ Hits 38683 38688 +5
- Misses 620 623 +3 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
Contributor
|
| Project | PyBaMM |
| Branch | stack/10b-rust-bindings |
| Testbed | bare-metal |
🐰 View full continuous benchmarking report in Bencher
⚠️ WARNING: Truncated view!The full continuous benchmarking report exceeds the maximum length allowed on this platform.
BradyPlanden
force-pushed
the
stack/10b-rust-bindings
branch
from
November 30, 2026 15:40
b1f03db to
7b72a9f
Compare
BradyPlanden
force-pushed
the
stack/10b-rust-bindings
branch
from
December 2, 2026 09:22
7b72a9f to
ed735a2
Compare
The bindings raised bare ValueError, NotImplementedError and RuntimeError, so a caller could not tell a refused argument from any other ValueError. They now raise InvalidInputError, a ValueError, for a refused argument or malformed graph; UnsupportedExpressionError, a NotImplementedError, for an expression the core cannot lower; and IntegrationError, a RuntimeError, for a failed solve or a pool that cannot start. Each subclasses the built-in it replaces, so existing `except` clauses still catch it. A core error reaches its class through `?`, by way of a BindingError newtype. DiffsolSolver and Interpolant catch the new classes rather than the built-ins, so an unrelated ValueError no longer turns into a SolverError or ModelError. DiffsolSolver keeps the class of a core refusal it re-raises, refuses a non-numeric rtol as a SolverError again, and raises a SolverError for a batch that cannot start. The module is declared with `#[pymodule_export]`, which exports the exception classes beside the others.
Array arguments took only float64 arrays, some only contiguous ones, and a list or an integer array raised TypeError. One extractor per kind of argument now serves every binding: RealVector and RealMatrix take any real array-like, IndexVector any integer one, and RealOutput the buffer a call writes into. A contiguous float64 array, or a trajectory stored column by column, is read in place; anything else is converted or gathered once, so lists, integer and float32 arrays, and strided or Fortran-ordered arrays all work. An array `p` is read in place rather than copied on every call. An array is read in place only when it is aligned with strides of whole elements: rust-numpy divides byte strides by the item size, so a field of a packed record array was read as garbage, without an error. A refused array raises InvalidInputError naming the argument and how NumPy read it, as does an `out` buffer that is not a contiguous, writeable float64 array. Sparsity patterns come back as int64, the index type SciPy and IDAKLU take without converting. BREAKING CHANGE: an array argument of the wrong type, or an `out` buffer of the wrong dtype or layout, raises pybamm.rust.InvalidInputError (a ValueError) instead of TypeError.
ExprGraph kept its arena in a mutable pyclass, so a build that ran while another thread held the graph raised a borrow conflict. It is now frozen, with its state behind an RwLock that waits detached from the interpreter, so threads building into one graph take turns, and compiled artifacts read it concurrently. A lock a panicking call poisoned raises RuntimeError on every later use. SolveOutcome and SolverStatistics are frozen too. SolveOutcome hands each of the solver's buffers to NumPy once, uncopied, and returns the same object on every read, so DiffsolSolver need not bind its sensitivities or statistics to avoid a rebuild; sensitivity blocks come back as tuples. `_pool_ids` copies the pool cache out before building its dict, so a thread waiting on that lock never blocks a free-threaded garbage-collection pause. With every class frozen, the module declares `gil_used = false`, so free-threaded Python keeps the GIL off when it loads the extension. PyBaMM's wheels do not target free-threaded Python yet.
Single-point evaluations always kept the GIL, while trajectory evaluations and Jacobian assembly always released it, whatever their size. Each evaluation, JVP, residual and Jacobian assembly now releases it once the tape slots it writes, a proxy for its run time, reach 4096: a large model's call lets other Python threads run, and a small one skips the round trip, which costs more than the call. Building a CompiledModel releases it too.
A solve ran detached from Python, which runs signal handlers only on its main thread and only between bytecodes, so Ctrl-C waited for the whole solve. A solve called from the main thread now runs the handlers while it is in flight, through the core's interrupt: a serial solve between steps, and a pooled or batched one from the calling thread between waits on the pool, which hands back its result through a condition variable that a forked child can still use. A handler that raises stops every step still running, and the solve raises its exception, KeyboardInterrupt for Ctrl-C, leaving the solver and its pool fit for the next solve. A serial solve reads the clock once per stride of steps, the stride growing while steps are cheap and falling to one once a step is slow: reading it every step costs a 2-state model 10%, and a fixed stride leaves a large model's Ctrl-C waiting on many slow steps. The handlers run every 100 ms. A poll that waits for a GIL another thread holds defers the next by 100 times its wait, up to a second, so a solve beside a busy thread spends 1-2% polling, not 6%. Off the main thread, where Python never runs the handlers, nothing polls, so a solve called from a worker thread runs to completion.
Lowering converted sparse-matrix indices and interpolant tables to Python lists only for the bindings to convert them back. It now passes the NumPy arrays, which the bindings read directly. A CompiledModel pickles its mass matrix and algebraic indices as arrays, its indices in the narrowest unsigned dtype that holds them. On a 7,622-state DFN that part pickles in 0.01 ms rather than 0.33 ms, and 20% smaller; a pickle of lists still loads.
BradyPlanden
force-pushed
the
stack/10b-rust-bindings
branch
from
December 4, 2026 10:47
ed735a2 to
32ac0d4
Compare
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Description
Hardens the
pybamm.rustbindings, which shipped in 26.11.InvalidInputError(aValueError) for a refused argument,UnsupportedExpressionError(aNotImplementedError) for an expression the core cannot lower,IntegrationError(aRuntimeError) for a failed solve. Each subclasses the built-in it replaces, so existingexceptclauses still catch it.DiffsolSolverandInterpolantcatch these, so an unrelatedValueErrorno longer becomes aSolverErrororModelError.outbuffer of the wrong dtype or layout, raisesInvalidInputErrorinstead ofTypeError. Sparsity patterns come back as int64.ExprGraphkeeps its state behind anRwLock, so threads building into one graph take turns and compiled artifacts read it concurrently. The module declaresgil_used = false.CompiledModelbuilds; smaller calls keep it.DiffsolSolversolve called from the main thread raisesKeyboardInterruptand leaves the solver and its pool fit for the next solve.CompiledModelpickles its indices as arrays, and a pickle of lists still loads.Evidence
outbuffer is refused.Merge Danger
Door: two-way. Blast radius: direct
pybamm.rustcallers that catchTypeErrorfor a bad array; migration: catchValueError(orpybamm.rust.InvalidInputError).Type of change
Breaking change and new features:
6138.breaking.md,6138.feature.md,6138.feature.1.md,6138.feature.2.md.Key checklist
pre-commit runcargo test --all-features, clippy over every feature combination, MSRV 1.89DiffsolSolverRust execution engine stack: proposal #5667, showcase #5732
Each PR builds on the one above it.
Function.create_copykeeps the function's classRegPowerand uniform-grid interpolant lookups matchevaluatepybamm-core: expression graph, typed IR, interpreters, forward-mode ADpybamm-core:CompiledModel, coloured Jacobians, the C ABIpybamm.rustbindings, built into thepybammwheelSymbol.to_rustconvert_to_format = "rust"forScipySolver,AlgebraicSolverand EISpybammsolvers: IDAKLU over the C ABIIDAKLUSolveron rust modelspybamm-core: diffsol DAE solverpybamm.DiffsolSolverInterpolantover input parameters and expressionspybamm.rust's own errors, array-likes, threads and Ctrl-C ← this PRpybamm.rust.inspection; every tape derived in one place"rust"as the defaultconvert_to_format