Skip to content

feat(rust)!: pybamm.rust's own errors, array-likes, threads and Ctrl-C - #6138

Open
BradyPlanden wants to merge 7 commits into
stack/10a-input-interpolantfrom
stack/10b-rust-bindings
Open

BradyPlanden wants to merge 7 commits into
stack/10a-input-interpolantfrom
stack/10b-rust-bindings

Conversation

@BradyPlanden

Copy link
Copy Markdown
Member

Description

Hardens the pybamm.rust bindings, which shipped in 26.11.

  • Errors: InvalidInputError (a ValueError) for a refused argument, UnsupportedExpressionError (a NotImplementedError) for an expression the core cannot lower, IntegrationError (a RuntimeError) for a failed solve. Each subclasses the built-in it replaces, so existing except clauses still catch it. DiffsolSolver and Interpolant catch these, so an unrelated ValueError no longer becomes a SolverError or ModelError.
  • Arrays (breaking): array arguments take any real array-like (lists, integer, float32, strided, Fortran-ordered); a contiguous float64 array is read in place. A wrong type, or an out buffer of the wrong dtype or layout, raises InvalidInputError instead of TypeError. Sparsity patterns come back as int64.
  • Threads: every class is frozen and ExprGraph keeps its state behind an RwLock, so threads building into one graph take turns and compiled artifacts read it concurrently. The module declares gil_used = false.
  • GIL: released for an evaluation, JVP, residual or Jacobian assembly once its tape writes 4096 slots, and while a CompiledModel builds; smaller calls keep it.
  • Ctrl-C: a DiffsolSolver solve called from the main thread raises KeyboardInterrupt and leaves the solver and its pool fit for the next solve.
  • Lowering passes NumPy arrays instead of lists; a CompiledModel pickles its indices as arrays, and a pickle of lists still loads.

Evidence

  • Lists, integer, float32, strided and Fortran-ordered arrays solve like float64 arrays; a packed record field reads correctly, where it was read as garbage; a float32 or strided out buffer is refused.
  • Threads building into one graph each get their own nodes; threads share one prepared solver.
  • Ctrl-C stops a serial solve, every set of a batch, and a solve beside a thread holding the GIL; a solve on a worker thread runs to completion.

Merge Danger

Door: two-way. Blast radius: direct pybamm.rust callers that catch TypeError for a bad array; migration: catch ValueError (or pybamm.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

  • No style issues: pre-commit run
  • Unit tests pass (7479), as do the integration tests (812)
  • Rust: cargo test --all-features, clippy over every feature combination, MSRV 1.89
  • Tests added: array coercion, thread sharing and Ctrl-C, for the bindings and through DiffsolSolver
Rust execution engine stack: proposal #5667, showcase #5732

Each PR builds on the one above it.

# PR Adds
0 #5954 Function.create_copy keeps the function's class
0b #5955 CasADi's RegPower and uniform-grid interpolant lookups match evaluate
1 #5956 pybamm-core: expression graph, typed IR, interpreters, forward-mode AD
2 #5957 pybamm-core: CompiledModel, coloured Jacobians, the C ABI
3 #5958 pybamm.rust bindings, built into the pybamm wheel
4 #5959 Symbol.to_rust
5 #5960 convert_to_format = "rust" for ScipySolver, AlgebraicSolver and EIS
6 #5961 pybammsolvers: IDAKLU over the C ABI
7 #5962 IDAKLUSolver on rust models
8 #5963 variables and sensitivities read in Rust
9 #5964 pybamm-core: diffsol DAE solver
10 #5965 pybamm.DiffsolSolver
10a #6134 Interpolant over input parameters and expressions
10b #6138 pybamm.rust's own errors, array-likes, threads and Ctrl-C ← this PR
10c #6135 pybamm.rust.inspection; every tape derived in one place
11 #5966 "rust" as the default convert_to_format

@codecov

codecov Bot commented Nov 30, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 98.41%. Comparing base (03b1a3a) to head (ed735a2).

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

@github-actions

github-actions Bot commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

🐰 Bencher Report

ProjectPyBaMM
Branchstack/10b-rust-bindings
Testbedbare-metal

⚠️ WARNING: Truncated view!

The full continuous benchmarking report exceeds the maximum length allowed on this platform.

🐰 View full continuous benchmarking report in Bencher

🔗 Link this project to GitHub

@BradyPlanden
BradyPlanden force-pushed the stack/10b-rust-bindings branch from b1f03db to 7b72a9f Compare November 30, 2026 15:40
@BradyPlanden
BradyPlanden force-pushed the stack/10b-rust-bindings branch from 7b72a9f to ed735a2 Compare December 2, 2026 09:22
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
BradyPlanden force-pushed the stack/10b-rust-bindings branch from ed735a2 to 32ac0d4 Compare December 4, 2026 10:47

This branch has not been deployed

No deployments
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