Polypus Engineering Guide — invariants and style¶
This document records the engineering rules that live inside the modules:
workspace boundaries, GIL discipline, numerical/quantum correctness,
memory-safety (unsafe) policy, feature hygiene, security decisions, and Rust
style. It complements:
docs/CONTRACTS.md— the agreements between layers (seams).docs/CONTRIBUTING.md— process: setup, checks, commits, PRs.
Like docs/CONTRACTS.md, this file is deliberately public: it is equally useful to
external contributors and to AI coding assistants working on a clone of this
repo. If a rule here and the code disagree, treat that as a bug in one of the
two and open an issue — do not silently pick a side.
1. Architecture at a glance¶
Polypus is an open-source distributed quantum computing library: a Rust core
with PyO3 Python bindings. The Cargo workspace has fourteen crates (the fuzz/ crate is excluded):
| Crate | Role | PyO3? |
|---|---|---|
polypus-circuit |
Circuit IR + OpenQASM 2.0 and OpenQASM 3 import/export + QIR export | No |
polypus-sim |
Statevector simulator (GIL-free; optional rayon via the parallel feature) |
No |
polypus-physics |
Physics: classical Monte Carlo transport + quantum Hamiltonians as multi-qubit Pauli sums (fermion-to-qubit mappings, Z-type Z₂-symmetry tapering, exact diagonalization, also within one electron sector) + molecular integrals, H₂ and the FCIDUMP reader (chemistry); pure Rust |
No |
polypus-optimizers |
Variational optimizers (DE, PSO, QNG, CMA-ES, Adam, SPSA, Rotosolve) behind evaluation and gradient oracles, and AlgorithmExternal, the bridge that runs an AskTell optimizer (Optuna, Nevergrad, pycma through the Python bindings) |
No |
polypus-observable |
Cost observables reducing measurement counts to a cost: Qubo / Ising, and Pauli sums (qubit-wise-commuting grouping with basis rotations, and a parity reducer); pure math | No |
polypus-qml |
Quantum machine learning: datasets, layered variational models (encoders, ansatz, convolution, pooling), Pauli readout and losses; produces polypus-circuit circuits and turns counts into fitness, never executes them |
No |
polypus-backend |
The pyo3-free backend contract a third party implements: the QuantumBackend trait, BoundCircuit, RunParams, BackendError/InfrastructureError, the Planner, the transpiler seam, the memory budget and the runtime backend registry (register_backend, BackendBuildContext). Zero PyO3 in its dependency tree |
No |
polypus-backend-conformance |
Reusable conformance battery a third party runs against its QuantumBackend (error classification, shot conservation, batching/waves, concurrency, result validation); depends only on polypus-backend and polypus-circuit |
No |
polypus-subprocess-backend |
A pyo3-free QuantumBackend bridging to a provider's Python SDK running in its own subprocess over a versioned length-prefixed JSON protocol; registered as the built-in "subprocess" backend. The interpreter runs in the child, never embedded here |
No |
polypus-infrastructure |
The concrete execution backends (local/Aer, cunqa, qmio, native), the Infrastructure factory (which routes unknown names through the registry and registers the built-in subprocess/qmio backends), the Qiskit boundary (QiskitCircuit, to_py_object) and the construction-time ExecutionConfig; re-exports the polypus-backend contract |
GIL only |
polypus-orchestration |
Flow orchestration (policy): Resources, the monomorphic Scheduler, the Flow trait + all flows (RunCircuitFlow, TrainFlow) with the OracleFactory seam, dispatch_optimizer and the type-erased OracleErrorSlot, and the trace module: the call trace's CallTracer and the decorators that record a run's batches, waves, iterations and QNG metric calls (contract C-12) |
No |
polypus-evaluation |
Candidate evaluation: the oracles (VqcOracle, QmlOracle, and PauliSumOracle for Pauli-sum Hamiltonians, docs/adr/0009-pauli-sum-oracle.md) and the OracleFactory implementations that build them (VqcOracleFactory, QmlOracleFactory, PauliSumOracleFactory), plus PyVarianceOracle, PyCallbackObservable, the supervised QML objectives (SupervisedObjective: PyLabelledCost, PySampleCost; see docs/adr/0002-qml-supervised-labels.md), CircuitSource and EvaluationError |
GIL only |
polypus-logger |
log::Log sink shared by the workspace; installed only by the app layer |
No |
polypus |
The library + Python extension module; the FFI edge — #[pyclass]es, kwarg parsing, and error→PyErr conversion |
Yes |
Interoperability: Qiskit ≥ 2.0 and qiskit-aer ≥ 0.17 (pinned in the root
pyproject.toml, [project] dependencies), CUNQA (distributed QPUs over
SLURM) and QMIO (CESGA's real QPU). Formats: OpenQASM 2.0 and QIR (LLVM IR
.ll, plus bitcode .bc assembled by the external llvm-as tool — that
boundary stays out-of-process and explicit; see
crates/polypus-circuit/src/qir.rs).
2. Workspace boundaries¶
polypus-circuit,polypus-sim,polypus-physics,polypus-optimizers,polypus-observable,polypus-qml,polypus-backend,polypus-backend-conformance,polypus-subprocess-backendandpolypus-loggerare pure Rust: they must not depend onpyo3or Python. Do not introducePy<...>,PyAny,Python, the GIL, or Python types into them.polypus-backendis the strictest of these: it is the public backend contract, so its whole dependency tree must stay PyO3-free (a third party implements a backend against it without pulling the interpreter) — a Python/provider failure crosses it type-erased inBackendError::External, and the concrete backends live one layer up inpolypus-infrastructure.polypus-subprocess-backendis pure Rust too and stays PyO3-free by construction: it reaches a provider's Python SDK by running it in a separate process, not by embedding the interpreter (its own tests spawn apython3worker as a subprocess, which is not a link-time dependency).polypus-infrastructuremay depend onpyo3for the GIL and for carrying aPyErrverbatim (its Aer/CUNQA/QMIO seams call into Python), but it defines no#[pyclass]and noFrom<_> for PyErr: turning aBackendErrorinto a typedpolypus.*exception is the edge's job (polypus::exceptions::backend_error_to_pyerr).polypus-orchestrationispyo3-free at the source level: it must not namepyo3,Python,PyError the GIL (itsCargo.tomlhas nopyo3). It still links libpython transitively throughpolypus-infrastructure, so its tests run in the same job aspolypus, not the pure-Rust group. A real oracle failure reaches it type-erased as aBox<dyn Error + Send>in theOracleErrorSlot; thepolypusedge downcasts it back to the concreteEvaluationErrorto re-raise (plan §10.1). It owns everyFlow, including the training flow (TrainFlow): a training flow'spyo3-touching oracle is built through anOracleFactoryimplemented inpolypus-evaluation, so the order lives here with the scheduler while only its assembly stays behind the GIL.polypus-evaluationmay depend onpyo3(Qiskit binding under the GIL, Python callbacks) likepolypus-infrastructure, but likewise defines no#[pyclass]and noFrom<_> for PyErr: turning anEvaluationErrorinto a typedpolypus.*exception is the edge's job (polypus::exceptions::evaluation_error_to_pyerr).- Only the
polypuscrate may contain#[pyclass]/#[pymethods]/#[pyfunction], own the exception hierarchy, and convert errors toPyErr. - Enforcement. The
pyo3limits above are checked bycargo deny check(thecargo-denyCI job) through thebanssection ofdeny.toml.pyo3-ffi, which links libpython, may be a direct dependency only ofpyo3.pyo3may be a direct dependency only ofpolypus,polypus-infrastructure,polypus-evaluationandnumpy, which keeps it out ofpolypus-orchestration'sCargo.tomltoo. The crates that link it may be depended on only by the crates above them in the graph:numpyonly bypolypus;polypus-infrastructure,polypus-orchestrationandpolypus-evaluationonly by the crates that build on them; andpolypus, the PyO3 edge, by no crate at all. Those entries cover every crate that links Python (pyo3-ffi,pyo3, its direct dependents and the chain that leads to them), so a pure crate fails CI both when it namespyo3and when it depends on any crate that links it. Moving a boundary means updatingdeny.tomlin the same change. - The optimizers are decoupled from circuits and Python via the
EvaluationOracle/VarianceOracletraits (contract C-5). A new optimizer is implemented against those oracles; it must not call Python or know about the backend. - Logging: library crates emit through the
logfacade only and never depend onpolypus-logger; only the top-levelpolypuscrate installs the sink.
3. GIL discipline (polypus crate only)¶
- Parameter binding and heavy computation are GIL-free; this is a core performance property of the project and must not regress.
- Never hold the GIL while waiting (
block_on, join) on workers that themselves need to acquire it: release it first withPython::attach(|py| py.detach(...)). Ignoring this deadlocks: the waiting thread holds the GIL that every worker is blocked trying to acquire. This is why the entry points (train,qml.train,run_quantum_circuit) runScheduler::run_cancellableinsidepy.detach: the Python-backed pieces below it (the Aer and CUNQA backends, Python cost callbacks, apolypus.Externaloptimizer'sask()andtell(), the trainingcallbackoftrain,qml.trainandModel.fit) attach on their own, on whichever thread evaluates them. Each of those attaches is a fresh one (detachresets the thread's attachment), so each goes throughattach_orand turns an unreachable interpreter into the typedInterpreterUnavailableerror, never a panic or a hang (§9). The one attach that cannot fail this way,BackendConfig::clonewith a noise model, is never called while detached. - Releasing the GIL does not by itself process signals.
detachlets other Python threads run, but a pending SIGINT (Ctrl+C) is turned into aKeyboardInterruptonly when the main thread runs Python bytecode or whenPyErr_CheckSignalsis called explicitly. Long-running Rust work is otherwise deaf to Ctrl+C until it returns. So a GIL-free loop that must stay interruptible has to callpy.check_signals()at a safe boundary: the optimizer entry points (train/qml.train) release the GIL around the wholeoptimize()call, and thePlannerruns a host-interrupt check between execution waves (insideexecute) — the one place that boundary now lives, so both the VQC and QML oracles stay interruptible without their own signal loop. - The
Planneritself no longer namespy.check_signals()— it moved to the edge. The planner and all its types now live in the pyo3-freepolypus-backendcrate, so between waves it calls a small injected guard, theInterrupttrait, carried (optionally) on theCancelToken(CancelToken::poll_interrupt). The one implementation that actually callspy.check_signals()isSignalInterruptincrates/polypus/src/bindings/interrupt.rs(the edge). It runs while the thread is detached, so it attaches throughattach_orrather thanPython::attachand aborts the run withInterpreterUnavailable(raised asKeyboardInterrupt, like every other site reached while detached) when the interpreter cannot be reached — see below and §9.train,qml.trainandrun_quantum_circuitbuild a guarded token with it and drive the run throughScheduler::run_cancellable. A pure-Rust caller uses a guard-less token (Scheduler::run) and the check is a no-op — which is whyrunis documented as not interruptible and is never used on a Python-facing path. The resultingPyErr— aKeyboardInterrupt, or an error raised by the userexpectation_function/ variance callback /polypus.Externaloptimizer'sask()ortell()(which also callpy.check_signals()before the user's code, so a Ctrl+C during a batch stops the run before the library's next call) — is recorded in the sharedOracleErrorSlotand re-raised to Python by the entry point as the original exception. The interrupt travels type-erased through the pyo3-free layers, boxed inBackendError::Externalas aDisplaySafePyErr(§9), and the edge downcasts it back and re-raises it verbatim (external_to_pyerr); a callback exception rides inEvaluationError::Python/ObservableError::Externalthe same way. It is never swallowed into a panic by an.expect()(that would surface as an opaquePanicException; see §9 andOracleErrorSlotinpolypus-orchestration). - How many waves that boundary produces is backend- and batch-dependent
(issue #147).
SequentialPlanner::executesizes each wave frombackend.capabilities_for(tasks).max_concurrency, a batch-aware companion to the frozen, argument-freeQuantumBackend::capabilities(). The native and local backends cap their real concurrency by a statevector memory budget scaled by the batch's widest circuit (mem_budget::max_statevector_concurrency); they overridecapabilities_forto expose that cap only when the whole batch cannot be held in the budget at once — the high-qubit regime — so a high-qubit batch is split into several waves and the between-wave interrupt check (the edge'sSignalInterrupt, above) runs once per wave: a whole training generation is no longer one uninterruptible call. When the batch fits (the common low-qubit case) they report an unbounded wave, so the whole population still reaches the backend as a single call (Aer parallelises the experiments internally; splitting would only add per-call overhead — pinned bytests/python/test_qml_concurrency.py). The "does it fit" test (wave_concurrency) is made against the pure memory limit — how many statevectors the budget holds, with the thread count removed — not the thread-capped cap: a thread-based gate (cap >= cores) degenerates on a single-core allocation (a common SLURM/container case, orRAYON_NUM_THREADS=1), where the cap always equals the core count regardless of qubit count and would wrongly report one uninterruptible wave for a memory-heavy batch (issue #147's single-thread case). Backends whose cap is static (CUNQA atn_qpus, QMIO at 1) do not override it and inherit the default, which delegates tocapabilities()ignoring the batch, so their behaviour is unchanged. capabilities_foris fallible, so a Ctrl+C during width-reading is not swallowed. It runs at the top of everyexecute— for training, once per generation on the optimizer thread, with the GIL released.LocalBackendsizes waves from every circuit's width, including aQiskitcircuit'snum_qubits, which it reads viagetattrunder the GIL exactly asrun_circuitsdoes — so a high-qubit Qiskit population (a Qiskit-templated ansatz onbackend="aer", the common QML case) is still wave-split for interruptibility. Thatgetattrruns Python bytecode, which CPython can abort with aKeyboardInterruptfor a pending Ctrl+C; mapping that to "width unknown" (an.ok()that discards it) clears the signal before the planner's between-wave interrupt check can see it, which madeqml.trainunresponsive to Ctrl+C on constrained runners (issue #147 follow-up). Socapabilities_forreturnsResult<BackendCapabilities, InfrastructureError>: aKeyboardInterruptfrom the read is propagated verbatim (boxed inBackendError::ExternalinsideInfrastructureError::Backend, re-raised by the edge), and only a genuine non-interrupt failure (a missing attribute, which a realQuantumCircuitnever has) falls back to "width unknown". The default impl and the native backend read widths GIL-free and never error (they returnOk); the call site inexecutepropagates with?, the same way it already handlesrun_circuits' errors.- Why a new method rather than changing
capabilities(). The argument-freecapabilities()is called without a batch byResources::new(to validate the planner/backend pairing up front) and is overridden by test mocks; its signature and meaning are load-bearing outside this crate, so the fix is strictly additive —capabilities_for(&[CircuitTask]) -> Result<BackendCapabilities, InfrastructureError>, taking the planner's borrowed task slice (eachCircuitTaskalready holds a&BoundCircuit) so sizing a wave clones no circuit. The override reuses the exact cap arithmetic each backend'srun_circuitsalready applies internally, so the wave size the planner picks matches the memory bound the backend would enforce anyway — and collapses to a single wave whenever the batch fits in the budget. - The same discipline applies to
run_quantum_circuit: it releases the GIL around the wholescheduler.run_cancellable(flow, &token)call, wheretokencarries the edge'sSignalInterruptguard; thePlannerruns that guard between execution waves (inexecute), and the counts are converted to a Python object back at the edge — GIL re-acquired — only after the run returns. A pending Ctrl+C surfaces there as aKeyboardInterruptpropagated verbatim through the function'sResult, never swallowed or retyped. statevectorfollows the same rule at a smaller scale: it releases the GIL around theStatevectorSimulator::run_cancellablecall (parameter binding stays on the GIL side — it is O(gates) and allocates nothing of size2^n), and callspy.check_signals()both mid-run and the moment the GIL is reacquired, before handing the amplitudes to NumPy — the latter being the same "reacquire-then-check-before-building-the-result" boundaryrun_quantum_circuituses.- The mid-run half is worth spelling out, because it is how a pure-Rust crate
stays interruptible without learning about Python (§2).
polypus-sim's gate loop takes anOption<&mut dyn FnMut() -> bool>and polls it periodically;trueabandons the run withSimError::Cancelled. It knows nothing about why — a signal, a deadline, a cancel button all look the same to it. Onlystatevectorfills that hook with apy.check_signals()call. The hook runs insidedetach, anddetachresets the thread's attachment, so attaching there is a fresh attach, not a reuse:Python::attachcould panic, hang, or attach to a finalizing interpreter, if the interpreter were shutting down. It attaches throughattach_orinstead and treats an unreachable interpreter as a cancellation, raised as the sameKeyboardInterrupt("the run was aborted: …", fromInterpreterUnavailable) that the planner's between-wave guard (SignalInterrupt) gets for the same event, since in both cases the run is aborted rather than given invalid input — see §9. Two rules make it work: - Throttle inside the pure crate, not at the Python boundary. The hook is
called at most once per ~25ms of wall clock (with the clock itself read once
per ~64k amplitude updates), so its frequency is decoupled from gate cost —
a cheap 1-qubit gate and a 25-qubit gate differ by orders of magnitude — and
a circuit that finishes quickly never calls it at all. Interrupt latency is
then bounded by a constant instead of by the run's own duration, which
matters because
polypus_sim::MAX_QUBITSbounds a run's memory, not its wall-clock time: cost scales with gates ×2^nand nothing bounds the gate count. The interval is also stretched to a multiple of the hook's measured duration, because the simulator cannot know what a hook costs: this one is ~1µs when nothing else wants the GIL and milliseconds when another Python thread holds it (the interpreter only yields on its switch interval), and without that adaptation the latter case measurably slowed a contended run down. Backed bybenchmarks/bench_statevector.py. - Recover the real exception at the Python-facing boundary.
SimErrorcannot carry aPyErr(§2), so the hook stashes thePyErrandstatevectorre-raises that verbatim when the run comes backCancelled— neverPyValueError::new_err(e.to_string()), which would downgrade aKeyboardInterruptinto a bogusValueError. Same problem, and the same answer, asOracleErrorSlotincrates/polypus-orchestration/src/dispatch.rs; no shared slot is needed here becausestatevectoris single-shot and the hook runs on the calling thread. What is not interruptible isStatevector::new's2^nallocation — one allocation with nowhere to put a checkpoint — which is why the post-run check above stays: near the qubit ceiling that allocation is the whole run. - Preserve concurrent execution: candidates that bind/evaluate truly in parallel. If you add a path that runs circuits from worker threads, keep this guarantee.
- The Rust test suite needs no installed Python package: Qiskit, Aer,
polypus_pythonandcunqaare required only by the Python test suite (tests/python/), and CI's Rust job installs none of them (.github/workflows/ci.yml). The pure crates' tests (circuit, sim, physics, optimizers, observable, backend, …) don't touch Python at all; that is what proves GIL-freedom. The PyO3-touching crates (polypus-infrastructure,polypus-evaluation,polypus) may start a bare embedded interpreter withPython::initialize()when the behaviour under test exists only at the FFI edge: exception classes,Pythontokens, attach and detach, a Python callback built in-test. A test that must run with no interpreter (e.g. what happens when it is unavailable) runs in a fresh child process, since initialization cannot be undone (run_in_fresh_processinpolypus-infrastructure/src/attach.rs). A test that would need a package belongs intests/python/, or must skip cleanly when the package is absent, aspolypus-infrastructure/tests/conformance.rsdoes.
4. Numerical and quantum correctness¶
- The statevector must remain normalized; gate matrices must be
unitary. Every new gate/kernel needs matrix- and state-level tests (see
crates/polypus-sim/tests/gate_matrices.rsandcrates/polypus-sim/tests/canonical_states.rs). - Parallel == sequential: kernels under the
parallelfeature (rayon) must produce bit-identical results to the sequential path. Every new parallel kernel is tested against its sequential version. - Qubit ceiling: a dense statevector needs
2^ncomplex amplitudes (16 · 2^nbytes), sopolypus-simrefuses circuits abovepolypus_sim::MAX_QUBITS(40 ≈ 16 TiB) as the first thingStatevectorSimulator::rundoes — before any allocation, and low enough that neither1 << nnor16 · 2^ncan overflow a 64-bitusize. At the seam this surfaces as aValueErrornaming the requested and the supported count (polypus.statevector;tests/python/test_statevector.py). Below it, the memory budget (polypus-backend'smem_budget, issue #428) decides: with a known limit (POLYPUS_MEM_BUDGETor the detected RAM/cgroup) a statevector that does not fit isInsufficientMemoryErrorbefore allocating and one that fits runs; with no limit detected (the blind 16 GiB fallback, which never refuses) the ceiling stays at 30 qubits (mem_budget::FALLBACK_MAX_QUBITS), with the same ceiling error plus a hint namingPOLYPUS_MEM_BUDGET. A directpolypus-simcaller has no budget:Statevector::newallocates fallibly (try_reserve_exact) and returnsSimError::AllocationFailedwhen the system refuses the memory, instead of aborting (with Linux overcommit the system may grant it and kill the process later, so the budget stays the real guard). The calibration cache's "parallelism disabled" value is pinned at31, its value when the ceiling was 30, and read as "never" whatever the ceiling. Below the ceiling, those amplitudes cross the seam as a NumPy array ofdtype=complex128— one contiguous buffer moved out of theStatevector(into_amplitudes, no copy) and wrapped by rust-numpy — rather than as alistof boxed Pythoncomplexobjects. That removes a2^n-sized conversion which, at these sizes, cost more than the simulation: a gateless 30-qubit call went from 29.7s to 5.0s, and a 26-qubit one from 1.9s to 0.4s (one-off measurement on a 32-core dev box, not a trackedbenchmarks/script; deep circuits gain proportionally less because the gates dominate — 30 qubits with a Hadamard layer: 50.4s → 25.6s). It does not make near-ceiling statevectors cheap, though: what remains isStatevector::new's2^nallocation, which is why even a gateless 30-qubit call still costs ~5s. The ceiling is a memory bound and says nothing about wall-clock.polypus.Circuititself stays unbounded on purpose: it is backend-agnostic IR, and CUNQA/QMIO/Aer have their own, different capacities — the ceiling is enforced where it applies, not in the IR. - Memory budget (issue #215): below the ceiling, what bounds a run is the
memory actually available.
polypus_backend::mem_budgetresolves one byte budget — a validPOLYPUS_MEM_BUDGET(32G,512M,1048576; base 1024; an invalid value is logged once withlog::warn!and ignored, never dropped silently), else the minimum ofMemAvailableand the cgroup v2/v1 limit of the process and its ancestors minus a reserve (clamp(10 %, 512 MiB, 50 %)of that limit), else a 16 GiB fallback when nothing can be detected — and uses it twice: to throttle how many statevectors run at once (max_statevector_concurrency, counts unchanged), and to refuse up front a single statevector that cannot fit (check_fits→BackendError::InsufficientMemory→polypus.InsufficientMemoryError) instead of letting the OOM-killer end the process. The Rust refusal applies where the memory is the dense16 · 2^nmodel — the native backend,polypus.statevector, Aer'sstatevectormethod. Aer's other methods (automaticmay pickstabilizerfor a Clifford circuit;density_matrixis16 · 4^n) are not refused in Rust, which would reject circuits that run: the local backend passes the budget to Aer asmax_memory_mbinstead, Aer validates against the method it picks, andpython/polypus_python/local.pyraises its refusal as the same class (contract C-1). The refusal never uses the fallback (it is a guess, not a limit). The detected limit is read once per process (OnceLock), the variable on every call. The model is16 · 2^nbytes (BYTES_PER_AMPLITUDE), which is the native backend's real peak because shot sampling (Statevector::sample) needs onlyO(shots)extra memory, not a2^nCDF. The one run that holds two is the adjoint gradient (#503: the state and the pulled-back observable,polypus_sim::ADJOINT_STATEVECTORS): the native backend counts each as one(n + 1)-qubit statevector, the same bytes, both to throttle and to refuse, and its exact QML gradient falls back to the parameter shift (one statevector, logged once per backend atinfo) when the budget holds one but not two. The budget's parsers andresolve_budgetare pure (they take text / values), so the budget logic is tested without/procor the environment. Tests never write the environment —set_varin a multithreaded test binary is racy andunsafeis off-limits (§5). The tests of the wrappers over the active budget (check_statevector_fits,max_statevector_concurrency,wave_concurrency) read it as the process sees it, and assert only what holds for any budget, plus what any Linux host guarantees: there they need/proc/meminfo, which a Linux test environment must provide. Several processes sharing one cgroup (MPI ranks of a job step) each see the whole limit and must setPOLYPUS_MEM_BUDGETper process. - Reproducibility: the in-repo generators are seedable: the workspace's
SplitMix64 (
rng.rsinpolypus-circuit, for shots, seeds, splits and minibatches) and the optimizers'OptRng(rng.rsinpolypus-optimizers);polypus-physicsdraws from therand::Rngits caller passes. Results must be deterministic given a seed. Don't introduce nondeterminism: iteration order over aHashMapaffecting results, unseeded RNG, parallelism that changes reduction order, etc. A floating-point reduction over aHashMap/HashSettherefore accumulates in sorted-key order, never in iteration order (which differs per map and per process): the cost reducers sum a counts map in ascending bitstring order. - Angle expressions (
polypus_circuit::expr) are evaluated exactly as written: the same floating-point operations in source order, with no reassociation and no folding of constant subexpressions (only an expression without free parameters is evaluated at once, to a fixed angle; contract C-2). The evaluation order is therefore deterministic; the elementary functions (sin,exp, …) are the platform's, so their last bit may differ between platforms. Expressions are stored flat (postfix) and never walked recursively, so their depth cannot overflow the stack; construction bounds their size and their nesting as written. - In numeric tests, compare with a tolerance (epsilon), not exact float equality — except where bit-identity is the property under test: the QASM round-trip (contract C-2), parallel == sequential, and a reduction's independence from iteration order.
- Use
f64andnum-complex::Complex64consistently with the rest of the simulator.
5. unsafe policy¶
unsafeis allowed only in thepolypus-simkernels (crates/polypus-sim/src/kernels.rs), where raw-pointer access to the statevector is performance-critical, and in the one signed-off exception below.- Every
unsafeblock keeps its// SAFETY: ...comment justifying the invariants (indices< 2^n = data.len(); the amplitude pair does not alias). Do not weaken those invariants. - Adding
unsafeanywhere else requires a benchmark that justifies it, the same// SAFETY:documentation, and explicit maintainer sign-off in the PR. - Signed-off exception —
polypus-subprocess-backend'spre_exec. The subprocess bridge holds exactly oneunsafeblock, inWorker::spawn(crates/polypus-subprocess-backend/src/lib.rs):Command::pre_exec, used to arm thePR_SET_PDEATHSIGorphan guard on the worker child so it cannot outlive a hard kill of the host process (a real HPC requirement — an orphaned worker would hold a SLURM node/QPU). This one is not a performance optimisation, so the "benchmark that justifies it" rule does not apply; it is unavoidable within the host process, becauseCommand::pre_execis anunsafe fnin std with no safe equivalent, andPR_SET_PDEATHSIGresets acrossforkso it can only be armed in the child, between fork and exec — which is exactly whatpre_execis for. The onlyunsafe-free alternative, evaluated in issue #557, moves the arming out of the process: a separate launcher binary that arms the signal, checks its parent andexecs the worker in its place. It was rejected because that binary would have to ship in the wheel and be located at run time, and Rust users of the crate would have to build it and point the bridge at it. The block's body is itself safe: it callsnix's auditedset_pdeathsigandgetppidwrappers (async-signal-safeprctl(2)/getppid(2)) and captures only aCopypid, with no allocation, locks or logging between fork and exec. It is not hand-written FFI and carries the mandated// SAFETY:comment. Thegetppidcheck makes the child exit beforeexecrather than run as an orphan if the parent died before the signal was armed. The kernel binds the signal to the forking thread, so the fork happens on a dedicated long-lived spawner thread (Worker::spawn_detached) that outlives the worker. Everything else the bridge needs from POSIX — notablykillfor out-of-band cancellation — goes throughnix's safe wrappers with nounsafe. Do not add a secondunsafeblock to this crate without the same sign-off. - Enforcement. The root
Cargo.tomldeniesunsafe_codeandclippy::undocumented_unsafe_blocksfor every crate ([workspace.lints]). Each authorised site carries its own block-scoped#[allow(unsafe_code)]: the two blocks inkernels.rs(apply_pairs, shared by the dense and the controlled 1-qubit kernels, andapply_2q) and thepre_execabove. So the repository has exactly three of them, and any otherunsafe, even a third one inkernels.rs, fails to compile. A new site still needs the benchmark, the// SAFETY:comment and the sign-off above. Itsallowgoes on that one block, never on a module or a crate. The order is fixed:#[allow(unsafe_code)], then the// SAFETY:comment, then the block. With the attribute between the comment and the block,undocumented_unsafe_blocksno longer sees the comment and reports the block as undocumented. - Let the compiler prove
Send/Sync; never force them withunsafe impl.
6. Feature hygiene¶
- The default build stays lean: it must not pull ZeroMQ or pickle —
those belong to the opt-in
qmiofeature.polypus-simis sequential by default; rayon lives behind itsparallelfeature (thepolypuscrate enablesparalleldeliberately for the HPC target; a runtime threshold —DEFAULT_PARALLEL_THRESHOLD— keeps small circuits on the sequential path). - Every heavy or optional dependency goes behind a feature.
extension-modulecontrols linking of the PyO3 extension. Declare features additively and don't enable them implicitly. - No crate has default features. The compile-time log-level toggles
(
info-logset al., forwarded topolypus-logger) are global to a build and mutually exclusive, so only the final artifact picks one: the wheel usesdebug-logs([tool.maturin] featuresinpyproject.toml). - A feature that exists only for tests (today
polypus-qml'stest-support) is enabled from[dev-dependencies]only, never from[dependencies]. The wheel enforces it: a const assertion incrates/polypus/src/lib.rsfails a wheel build whiletest-supportis on. A wheel build is one with theextension-modulefeature or thePYO3_BUILD_EXTENSION_MODULEenvironment variable, which maturin exports to the builds it runs (the floor inpyproject.toml's[build-system]is a release that does), also when a--featureson the command line replaces[tool.maturin] features. Building test targets as a wheel build (--all-targetsor--testswith either signal) turns the dev-dependencies' features on, so it trips the same guard.
7. Interoperability notes (beyond contract C-2)¶
Contract C-2 owns the gate vocabulary and the byte-identical round-trip. Additionally:
- Exported OpenQASM 2.0 uses standard
qelib1.incnames (plus thegatedeclarations of any declared gate it calls: verbatim for one imported from OpenQASM 2.0, printed from its definition for one imported from OpenQASM 3) and must remain accepted by Qiskit (QuantumCircuit.from_qasm_str). Aer runs it directly as long as every instruction is in Aer's basis;ch,u0,rccx,rc3x,c3sqrtxand every declared gate are not (c3xandc4xparse as Qiskit'smcx, which is) and Aer never unrolls them by itself, soLocal.run_qcs(python/polypus_python/local.py) lowers a circuit that holds one just beforeAerSimulator.run, with the synthesis and basis-translation passes oftranspile(qc, AerSimulator(), optimization_level=0)(same circuit, without the layout stage, a fixed cost on every lowered call that also caps the width at the target's qubit count) — the third lowering boundary of C-2, invisible to the exported QASM.Cunqa.run_qcs(python/polypus_python/cunqa.py) does the same for CUNQA, whose converter takes only the names in itscunqa.circuit.ir.SUPPORTED_QISKIT_OPERATIONS(mcxincluded among those it lacks): the fourth boundary, withbasis_gates= the standard gates in that list; with a CUNQA that does not publish the list, circuits go unchanged. Whether an instruction is "outside the basis" is decided on the names Qiskit parsed (rc3xisrcccx,c3sqrtxisc3sx) against the defaultAerSimulator()target, control-flow bodies included, never the target of the configuredsim_methodornoise_model; a circuit already in the basis is passed to Aer as it is, neither copied nor transpiled. An OpenQASM text (how apolypus.Circuitreachesrun_qcs) that needed lowering keeps its lowered circuit in a bounded, thread-safe LRU cache keyed by the text (_LOWERED_QASM): running the same program again, or on several QPUs, neither re-parses nor re-lowers it. That matters for declared gates, whose definitions are rebuilt and unrolled on every parse at a cost that grows quickly with their size. The kept circuit is shared and never modified; texts already in the basis andQuantumCircuitinputs (mutable) are not cached. from_qasm2accepts both Polypus output andqiskit.qasm2.dumpsoutput,gatedeclarations included. Canonicalizations performed on import: the builtinsU→uandCX→cx(Qiskit's own names for them), multipleqreg/cregdeclarations flattened into one index space, constant parameter expressions (e.g.pi/2) evaluated. Nothing is decomposed or re-spelled otherwise (C-2):p,u1,u2,u,u3all stay as written.- Exported OpenQASM 3 is the canonical form of the profile (contract C-10)
and must remain accepted by Qiskit's
qasm3.loads(qiskit-qasm3-import, a test-only dependency);from_qasm3acceptsqiskit.qasm3.dumpsoutput. Both are tested for the pinned versions inrequirements-dev.txt, not promised for others. Canonicalizations on import:U→u,CX→cx,phase→p,cphase→cp; registers flattened; constant expressions evaluated. Qiskit's exporter drops the global phase of the circuit and of every gate definition it writes (sxdgbecomess; h; s), so amplitudes match the original Qiskit circuit only up to that dropped phase. - Parse errors carry the 1-based line number (
CircuitError::Parseon the Rust side,ValueErroronce across the Python boundary).
8. Security¶
- Validate and sanitize all inputs; never trust external data. Apply least privilege and secure-by-default values. Never embed secrets, credentials or tokens in code — use environment variables or a secrets manager.
- Untrusted peers: the QMIO backend speaks the pickle-over-ZMQ protocol,
but it uses
serde-pickle— which does not execute__reduce__/GLOBAL— instead of Python'spickle.loads, specifically to avoid RCE from a malicious peer. Any code that deserializes data coming from a QPU, backend or network peer must treat that data as untrusted and must not use a deserializer capable of executing code. Do not introduce dependencies that reintroduce a deserialization-RCE surface. - Unauthenticated transport: the QMIO ZeroMQ link is neither encrypted nor
authenticated, and the backend has no default endpoint. The assumed threat model
and the decision to rely on the private network (or a tunnel) are in
backends.md. Do not reintroduce a hard-coded endpoint fallback. - The
zeromqcrate was chosen because it is pure Rust (no Clibzmqbuild dependency, at the cost of an async tokio API). Do not replace it with a C binding without an explicit trade-off discussion with the maintainers.
9. Rust style¶
- The workspace uses edition 2021; keep code compatible with it. All code
passes
cargo fmtandcargo clippy --workspace --all-targets -- -D warnings(seeCONTRIBUTING.mdfor the full check list and the lint-level policy).
Error handling. Use Result<T, E> and ?. No unwrap() / expect() /
panic! in production paths (acceptable in tests, examples, or truly
unrecoverable invariants, always with a clear message). Each crate defines its
own error type (error.rs); reuse and extend it instead of introducing ad-hoc
errors or bare strings. Never silence or discard errors (let _ = ...).
Errors crossing the FFI boundary become PyErr via Result — never a panic.
In the polypus crate this means every path reachable from a #[pyfunction] /
#[pymethods] returns a typed error (BackendError, EvaluationError, or the
crate's QmioError) mapped to the polypus::exceptions Python hierarchy — even
where the failure is "unlikely". A Python exception raised by the
polypus_python seam is carried verbatim and re-raised with its original type,
so contract C-1's ValueError/TypeError failure modes are preserved —
except an exception raised by Qiskit (issue #218): one whose class, or any
class in its MRO, is defined in a qiskit* module is raised as
polypus.BackendError, with the Qiskit class's qualified name and message as
its message and the original chained as __cause__. A Qiskit failure while
composing or binding the user's Qiskit circuits before any backend runs
(qml.train, qml.predict, the oracles' parameter binding) follows the same
rule but becomes polypus.EvaluationError. In both cases a Qiskit class that is
also a ValueError, TypeError or KeyboardInterrupt keeps its class, and an
exception raised by a user callback is never retyped. The rule lives in one
helper, polypus::exceptions::wrap_qiskit_error, and detection reads class
names only, so Qiskit is never imported for it.
Argument-conversion errors are PyO3's, not ours. When a #[pyfunction] /
#[pymethods] argument fails to convert, the caller gets the conversion's own
exception (for an angle, TypeError: angle must be a number, polypus.Param or
polypus.ParamExpr), and since PyO3 0.29 the argument is named in an exception note
(__notes__ == ["while processing 'theta'"]) rather than in the message
(PyO3 ≤ 0.25 raised argument 'theta': …). Notes need Python ≥ 3.11, so on
3.10 the argument name is not reported at all. This is accepted, not a
contract; test_argument_conversion_error_format in
tests/python/test_native_circuit.py pins it so the next PyO3 bump cannot
change it silently.
Drop must be panic-free. No Drop impl may panic under any circumstance:
a panic while another panic is already unwinding aborts the whole process,
defeating the RAII guarantee (for CunqaBackend this would leak the SLURM
allocation). A Drop that does fallible cleanup (releasing QPUs, closing a
socket) logs the failure with log::error! and continues — it never
propagates the error. Because a per-instance flag is worthless once the instance
is gone, the failure is also recorded in process-wide state that a higher
layer can inspect (the backend_cleanup_failures() counter, exposed to Python).
Acquiring the GIL inside a Drop is allowed only when it is explicitly safe
against re-entrancy and cannot propagate a panic through the in-progress unwind.
Attaching reuses an existing attachment only when the thread is already
attached — never inside detach, which resets it. A fresh Python::attach
panics during a GC traversal and before the interpreter is initialized, and
once the interpreter has started shutting down it either panics or attaches to
the finalizing interpreter, which can hang the thread. This happens on every
Python version: CPython clears its initialized flag right after marking itself
finalizing, so to PyO3 a shutting-down interpreter looks uninitialized, and
Python::try_attach reports it as unavailable. The only gap left is a
check-then-attach race, which PyO3 documents as best effort. So a Drop, and
any code that runs while detached (see "Code reached while detached" below),
attaches through the shared helpers in
crates/polypus-infrastructure/src/attach.rs: attach_or for callbacks,
choosing explicitly what an unreachable interpreter means, and
attach_for_cleanup for cleanup, which also formats a Python exception while
still attached (with a fixed fallback if even that fails, as to_string() would
panic). That matters because formatting a bare PyErr (Display, Debug,
to_string()) attaches again with Python::attach, so a bare PyErr that is
formatted after the attached closure returns, while detached or at shutdown,
reintroduces the panic (see the next paragraph). CunqaBackend is the reference
use: its release operation receives the Python token, and close is the one
place that attaches. An attach inside the release operation then reuses that
attachment without re-checking the interpreter, as long as it stays on the same
thread and outside a detach; detaching inside it would make the next attach a
fresh one, with the same hazards as above. Keep the fallible operation behind a
Result-returning helper so the Drop body only logs and counts.
Code reached while detached attaches fallibly. Everything the scheduler
reaches inside py.detach that needs Python attaches with attach_or: the Aer
and CUNQA run_circuits, LocalBackend::capabilities_for, CUNQA's raise_qpus
(it fails before anything is asked of SLURM), the noise-model clone in
Infrastructure::create_backend (only when there is a noise model), the Qiskit
parameter binding, PyCallbackObservable, the supervised objectives,
PyVarianceOracle, the External bridge (PyAskTell), the training callback
(PyTrainObserver, which calls py.check_signals() before the user's code, as
PyAskTell does) and the planner's between-wave guard (SignalInterrupt). The
attach_or "unavailable" branch of each of these sites returns
polypus_infrastructure::InterpreterUnavailable (in attach.rs), an error that
holds nothing from Python and so can be formatted, logged or dropped anywhere.
It is boxed in BackendError::External (From impls exist for BackendError,
InfrastructureError and EvaluationError) or in ObservableError::External,
never added as a variant: none of those enums is #[non_exhaustive], and
BackendError is the third-party backend contract. A site whose signature
cannot fail (VarianceOracle) records it in the run's OracleErrorSlot and
returns its finite sentinel, as it does for a callback error; the training
callback records it there too and stops the run. The FFI edge
downcasts it after DisplaySafePyErr and raises KeyboardInterrupt ("the run
was aborted: …"), the class BackendError::Aborted and a Ctrl+C get: the run is
abandoned and its result could not reach Python anyway (contract C-1, failure
modes). Outside the scheduler, statevector's cancellation hook also attaches
with attach_or, but its "unavailable" branch cancels the simulation instead;
cancellation_error then raises the same KeyboardInterrupt. A Qiskit circuit
is held as Arc<Py<PyAny>> inside QiskitCircuit, so duplicate(), which the
planner calls per wave while detached, shares it without attaching. Dropping a
Py while detached is safe because PyO3 defers the reference-count decrement to
its reference pool; never enable pyo3_disable_reference_pool, which turns that
drop into an abort. A Clone that must attach cannot report failure, so
BackendConfig::clone (which clones a noise model) is called only while
attached, and nothing reached while detached may start calling it. Likewise
OracleErrorSlot::record formats the error before taking its mutex: formatting
a DisplaySafePyErr attaches, and a thread holding the interpreter may be
waiting on that mutex in failed().
To test an "unavailable" branch, use a process that never initialized Python
(run_in_fresh_process in attach.rs; initialization cannot be undone) when
the code needs no Python object. When it needs one (a user callback, a Qiskit
circuit), building it initializes the interpreter, so run the code from inside
a GC traversal instead, where PyO3 forbids attaching and try_attach returns
None deterministically (test_support::run_while_attaching_is_forbidden in
polypus-evaluation), and check that it did not call the object.
tests/python/test_interpreter_shutdown.py covers a real interpreter shutdown
end to end.
An error that may hold a PyErr is formatted only if its Display is
attach-safe. The pyo3-free layers log errors with {e} while the thread is
detached (the planner's cancellation path, OracleErrorSlot::record; the whole
scheduler runs inside py.detach), and a run still in flight on a daemon thread
when the interpreter shuts down would panic there if the error held a bare
PyErr. So a Python exception that travels through code that may format it
while detached is never carried as a bare PyErr: it is carried as
polypus_infrastructure::DisplaySafePyErr (in attach.rs), whose Display
and Debug attach through attach_or. With the interpreter available its text
is the PyErr's; without it, a fixed fallback (DisplaySafePyErr::UNAVAILABLE).
It is the only authorized carrier of a Python exception
(InterpreterUnavailable, above, carries none): seam_error boxes it into
BackendError::External, a callback observable into
ObservableError::External, and EvaluationError::Python / Qiskit hold one.
The FFI edge (polypus::exceptions) downcasts only to it to recover a Python
exception, and re-raises the original PyErr (into_inner); a bare PyErr
boxed by mistake is mapped like any other provider error, losing its class, so a
C-1 test that exercises that path fails instead of passing silently. Formatting
a bare PyErr remains fine where the thread is known to be attached, inside an
attach closure (as the backends' log::error! calls next to seam_error do).
Ownership and types. Prefer borrowing over cloning; avoid unnecessary
.clone(). In signatures accept &str over &String and &[T] over
&Vec<T>. Leverage the type system: newtypes, enums for state,
Option/Result instead of sentinels — make illegal states unrepresentable.
Derive the usual traits (Debug, Clone, PartialEq, …) where sensible and
use exhaustive match.
Concurrency and async. The async runtime is Tokio (rt-multi-thread).
Never block the executor: wrap blocking operations in spawn_blocking. Don't
hold a lock (Mutex/RwLock) across an .await. GIL rules: §3.
A log record may block, so none is emitted while holding a lock. A log
sink is not guaranteed to return quickly: polypus.log_to_python() installs one
that attaches to the interpreter, so emitting a record waits for the GIL. If the
emitting thread holds a lock (Mutex, RwLock, a file lock) or is inside a
one-time initialiser (OnceLock::get_or_init, Once::call_once,
get_or_try_init), and a thread holding the GIL waits for that same lock or
initialiser, the two deadlock. The same holds for a thread that holds the GIL
while it waits (a join, a channel recv, a block_on) for another thread
that logs. So the rule, in every crate: format the record's data under the
guard if needed, release the guard, then log, as OracleErrorSlot::record_as
does. Out of a one-time initialiser, return what the record needs and let the
thread that ran it log after get_or_init returns (polypus_sim's
resolution, mem_budget's detected_memory_limit). The only accepted
exception is a lock or initialiser that no thread can wait for while holding
the GIL, and the site must say why; today there are two, both in the gate
calibration: AUTOCALIBRATION in bindings/calibration.rs (its call_once
runs inside py.detach) and the calibration cache's file lock (only
calibrate_and_cache takes it, which the bindings call detached, and the wait
gives up after LOCK_TIMEOUT). Releasing the guard first is also what keeps a
slow sink from stalling every other thread that needs the lock. One known gap
remains, in the qmio feature only: QmioBackend::close (a block_on) and the
drop of its Tokio runtime can run with the GIL held while zeromq's tasks log
from the runtime's worker threads, so with the Python bridge installed that
close can hang; docs/guide/running.md documents it. CI runs the Python
suite once more with the bridge installed at DEBUG (the logging bridge leg
of python-tests), so a record emitted under such a lock, on a path the suite
covers, hangs that leg until its timeout fails it.
Performance. Don't optimize prematurely; justify any
performance/readability trade-off. Any claimed performance improvement is
backed by the scripts in benchmarks/ (run_benchmarks.py,
bench_native_vs_qiskit.py, bench_batching.py). Reserve with
Vec::with_capacity when the size is known; use slices and Cow<str> to
avoid copies; prefer iterators/combinators over manual loops when clearer.
Design. Prefer decoupled, stateless designs. Watch structures that don't
scale with qubit count or number of QPUs; don't load everything into memory.
Apply DRY and single responsibility; don't over-engineer — the simplest
solution that meets the requirements is preferred. Add log statements where
they aid debugging and observability (through the facade — see §2).
API and documentation. Follow the Rust API Guidelines. Control visibility
deliberately (pub/pub(crate)); don't expose more than necessary. Document
public items with /// including examples that work as doctests — CI builds
the rustdoc with -D warnings, so broken intra-doc links fail the build.
Dependencies. Pin shared external dependencies once in
[workspace.dependencies] and reuse them. Adding a dependency is a
maintainer decision: propose it explicitly in the PR description, never slip
it into an unrelated diff. cargo deny check gates licenses, advisories and
the §2 pyo3 bans.
10. Pre-PR checklist¶
- [ ] Does the affected crate respect its PyO3/Python boundary? (§2)
- [ ] If it touches
polypus: is the GIL released before waiting on workers? Is binding/computation still GIL-free? (§3) - [ ] If it touches the simulator: statevector normalized, gates unitary, and parallel == sequential with tests? (§4)
- [ ] Deterministic given a seed? (§4)
- [ ] Any new
unsafe? Only insim/kernels.rs(with// SAFETY:and a benchmark) or the signed-offpre_execexception inpolypus-subprocess-backend; anything else needs the same sign-off. (§5) - [ ] If it touches circuits: byte-identical round-trip and Qiskit compatibility preserved? (§7, contract C-2)
- [ ] Heavy dependencies behind an opt-in feature? Default build lean? (§6)
- [ ] Network/backend data treated as untrusted, no execution-capable deserializers? (§8)
- [ ]
fmt+clippy -D warnings+ tests green; performance claims backed by a benchmark? (§9,docs/CONTRIBUTING.md) - [ ] Explicit errors (no
unwrap/panicin production, including#[pyfunction]-reachable paths), noDropthat can panic, edge cases covered, public items documented? (§9) - [ ] Does the change touch a seam listed in
docs/CONTRACTS.md? Then the same PR updates the contract and its enforcing test. - [ ] If a requirement was ambiguous: the PR description states which interpretation was chosen and why.