use crate::infrastructure::BackendError as InfraBackendError;
use pyo3::create_exception;
use pyo3::exceptions::{PyException, PyKeyboardInterrupt, PyValueError};
use pyo3::PyErr;
create_exception!(
polypus,
PolypusError,
PyException,
"Base class for every Polypus runtime error."
);
create_exception!(
polypus,
BackendError,
PolypusError,
"A quantum-execution backend failed at runtime."
);
create_exception!(
polypus,
CunqaError,
BackendError,
"A failure originating in the CUNQA distributed-QPU backend."
);
create_exception!(
polypus,
QmioError,
BackendError,
"A failure on the QMIO real-QPU network/serialisation path."
);
create_exception!(
polypus,
NativeCircuitError,
BackendError,
"The native (pure-Rust) circuit or statevector-simulator path failed."
);
create_exception!(
polypus,
EvaluationError,
PolypusError,
"An oracle/expectation-evaluation failure during training."
);
pub(crate) fn backend_error_to_pyerr(err: InfraBackendError) -> PyErr {
match err {
InfraBackendError::Seam(py_err) => py_err,
InfraBackendError::UnknownInfrastructure { name } => PyValueError::new_err(format!(
"unknown infrastructure '{name}'; expected \"local\", \"cunqa\" or \"qmio\""
)),
InfraBackendError::InvalidCircuitCount { expected, got } => {
PyValueError::new_err(format!("expected exactly {expected} circuit(s), got {got}"))
}
InfraBackendError::UnsupportedCircuit(m) => NativeCircuitError::new_err(m),
InfraBackendError::InvalidResults(m) => {
BackendError::new_err(format!("backend returned invalid results: {m}"))
}
InfraBackendError::NativeCircuit(m) => NativeCircuitError::new_err(m),
InfraBackendError::Cunqa(m) => CunqaError::new_err(m),
InfraBackendError::Conversion(m) => BackendError::new_err(m),
#[cfg(feature = "qmio")]
InfraBackendError::Qmio(qmio_err) => QmioError::new_err(qmio_err.to_string()),
}
}
fn observable_error_to_pyerr(err: polypus_observable::ObservableError) -> PyErr {
use polypus_observable::ObservableError as ObsErr;
match err {
ObsErr::External(boxed) => match boxed.downcast::<PyErr>() {
Ok(py_err) => *py_err,
Err(other) => EvaluationError::new_err(other.to_string()),
},
other => EvaluationError::new_err(other.to_string()),
}
}
pub(crate) fn evaluation_error_to_pyerr(err: crate::evaluation::EvaluationError) -> PyErr {
use crate::evaluation::EvaluationError as EvalErr;
match err {
EvalErr::Backend(backend_err) => backend_error_to_pyerr(backend_err),
EvalErr::Binding(circuit_err) => EvaluationError::new_err(circuit_err.to_string()),
EvalErr::Observable(obs_err) => observable_error_to_pyerr(obs_err),
EvalErr::Python(py_err) => py_err,
EvalErr::Runtime(m) => EvaluationError::new_err(m),
EvalErr::Conversion(m) => EvaluationError::new_err(m),
wrong_length @ EvalErr::WrongLength { .. } => {
EvaluationError::new_err(wrong_length.to_string())
}
non_finite @ EvalErr::NonFinite { .. } => EvaluationError::new_err(non_finite.to_string()),
invalid_variance @ EvalErr::InvalidVariance { .. } => {
EvaluationError::new_err(invalid_variance.to_string())
}
}
}
pub(crate) fn infrastructure_error_to_pyerr(
err: crate::infrastructure::InfrastructureError,
) -> PyErr {
use crate::infrastructure::InfrastructureError as InfraErr;
match err {
InfraErr::Backend(e) => backend_error_to_pyerr(e),
InfraErr::Observable(e) => observable_error_to_pyerr(e),
InfraErr::Python(e) => e,
InfraErr::Cancelled => PyKeyboardInterrupt::new_err("the run was cancelled"),
InfraErr::IncompatiblePlanner(m) => PyValueError::new_err(m),
}
}
pub fn register(m: &pyo3::Bound<'_, pyo3::types::PyModule>) -> pyo3::PyResult<()> {
use pyo3::types::PyModuleMethods;
let py = m.py();
m.add("PolypusError", py.get_type::<PolypusError>())?;
m.add("BackendError", py.get_type::<BackendError>())?;
m.add("CunqaError", py.get_type::<CunqaError>())?;
m.add("QmioError", py.get_type::<QmioError>())?;
m.add("NativeCircuitError", py.get_type::<NativeCircuitError>())?;
m.add("EvaluationError", py.get_type::<EvaluationError>())?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use pyo3::prelude::*;
use pyo3::PyTypeInfo;
fn assert_maps_to<E: PyTypeInfo>(err: InfraBackendError, expected_message: &str) {
pyo3::prepare_freethreaded_python();
let py_err = backend_error_to_pyerr(err);
Python::with_gil(|py| {
assert!(
py_err.is_instance_of::<E>(py),
"wrong exception class for: {py_err}"
);
assert!(
py_err.is_instance_of::<PolypusError>(py),
"every polypus.* class must stay catchable as PolypusError: {py_err}"
);
assert!(
py_err.to_string().contains(expected_message),
"message lost in translation: {py_err}"
);
});
}
#[test]
fn unsupported_circuit_maps_to_native_circuit_error() {
assert_maps_to::<NativeCircuitError>(
InfraBackendError::UnsupportedCircuit(
"the native statevector backend cannot execute a Qiskit QuantumCircuit".to_string(),
),
"cannot execute a Qiskit QuantumCircuit",
);
}
#[test]
fn native_circuit_maps_to_native_circuit_error() {
assert_maps_to::<NativeCircuitError>(
InfraBackendError::NativeCircuit("could not parse OpenQASM 2.0".to_string()),
"could not parse OpenQASM 2.0",
);
}
#[test]
fn conversion_maps_to_the_backend_error_base_class() {
assert_maps_to::<BackendError>(
InfraBackendError::Conversion("counts were not convertible".to_string()),
"counts were not convertible",
);
}
#[test]
fn cunqa_maps_to_cunqa_error() {
assert_maps_to::<CunqaError>(
InfraBackendError::Cunqa("injected release failure".to_string()),
"injected release failure",
);
}
#[test]
fn provider_errors_stay_catchable_as_backend_error() {
pyo3::prepare_freethreaded_python();
let cunqa = backend_error_to_pyerr(InfraBackendError::Cunqa("x".to_string()));
let native = backend_error_to_pyerr(InfraBackendError::UnsupportedCircuit("y".to_string()));
Python::with_gil(|py| {
assert!(cunqa.is_instance_of::<BackendError>(py));
assert!(native.is_instance_of::<BackendError>(py));
});
}
}
#[cfg(test)]
mod evaluation_mapping_tests {
use super::*;
use crate::evaluation::EvaluationError as EvalErr;
use polypus_circuit::CircuitError;
use polypus_infrastructure::BackendError;
use polypus_observable::ObservableError;
use pyo3::exceptions::{PyMemoryError, PyRuntimeError, PyTypeError, PyZeroDivisionError};
use pyo3::prelude::*;
use pyo3::types::PyAnyMethods;
#[test]
fn runtime_variant_maps_to_typed_evaluation_error() {
pyo3::prepare_freethreaded_python();
Python::with_gil(|py| {
let err = evaluation_error_to_pyerr(EvalErr::Runtime("worker panicked".to_string()));
assert!(
err.value(py).is_instance_of::<EvaluationError>(),
"Runtime must surface as polypus.EvaluationError"
);
assert!(
!err.value(py).is_instance_of::<PyRuntimeError>(),
"Runtime must not surface as the generic RuntimeError"
);
assert!(err.to_string().contains("worker panicked"));
});
}
#[test]
fn conversion_variant_maps_to_typed_evaluation_error() {
pyo3::prepare_freethreaded_python();
Python::with_gil(|py| {
let err = evaluation_error_to_pyerr(EvalErr::Conversion("not list[float]".to_string()));
assert!(err.value(py).is_instance_of::<EvaluationError>());
assert!(
!err.value(py).is_instance_of::<PyTypeError>(),
"Conversion must not surface as the generic TypeError"
);
assert!(err.to_string().contains("not list[float]"));
});
}
#[test]
fn counts_conversion_failure_maps_to_typed_evaluation_error() {
pyo3::prepare_freethreaded_python();
Python::with_gil(|py| {
let msg = "failed to convert the backend results into a Python list[dict]: OOM";
let err = evaluation_error_to_pyerr(EvalErr::Conversion(msg.to_string()));
assert!(err.value(py).is_instance_of::<EvaluationError>());
assert!(
!err.value(py).is_instance_of::<PyMemoryError>(),
"a counts conversion failure must not surface as a raised MemoryError"
);
assert!(err
.to_string()
.contains("backend results into a Python list[dict]"));
});
}
fn assert_maps_to_evaluation_error(err: EvalErr, expected_message: &str) {
pyo3::prepare_freethreaded_python();
let py_err = evaluation_error_to_pyerr(err);
Python::with_gil(|py| {
assert!(
py_err.is_instance_of::<EvaluationError>(py),
"wrong exception class for: {py_err}"
);
assert!(
py_err.is_instance_of::<PolypusError>(py),
"EvaluationError must stay catchable as PolypusError: {py_err}"
);
assert!(
py_err.to_string().contains(expected_message),
"message lost in translation: {py_err}"
);
});
}
#[test]
fn binding_maps_to_evaluation_error() {
assert_maps_to_evaluation_error(
EvalErr::Binding(CircuitError::WrongNumberOfParams {
expected: 3,
got: 1,
}),
"circuit declares 3 free parameter(s) but 1 value(s) were provided",
);
}
#[test]
fn wrong_length_maps_to_evaluation_error() {
assert_maps_to_evaluation_error(
EvalErr::WrongLength {
expected: 4,
got: 2,
},
"contract C-5",
);
}
#[test]
fn non_finite_maps_to_evaluation_error() {
assert_maps_to_evaluation_error(
EvalErr::NonFinite {
index: 3,
value: f64::NAN,
},
"contract C-5",
);
}
#[test]
fn invalid_variance_maps_to_evaluation_error() {
assert_maps_to_evaluation_error(
EvalErr::InvalidVariance {
param_index: 1,
value: -1.0,
},
"finite, non-negative",
);
}
#[test]
fn backend_variant_delegates_to_the_backend_mapping() {
pyo3::prepare_freethreaded_python();
let py_err = evaluation_error_to_pyerr(EvalErr::Backend(BackendError::Cunqa(
"qraise failed".to_string(),
)));
Python::with_gil(|py| {
assert!(py_err.is_instance_of::<CunqaError>(py));
assert!(
!py_err.is_instance_of::<EvaluationError>(py),
"a wrapped backend failure must keep its own class"
);
});
}
#[test]
fn observable_non_external_maps_to_evaluation_error() {
assert_maps_to_evaluation_error(
EvalErr::Observable(ObservableError::Invalid("coupling i == j".to_string())),
"coupling i == j",
);
}
#[test]
fn observable_external_preserves_the_original_python_class() {
pyo3::prepare_freethreaded_python();
let py_err = evaluation_error_to_pyerr(EvalErr::Observable(ObservableError::External(
Box::new(PyZeroDivisionError::new_err("callback divided by zero")),
)));
Python::with_gil(|py| {
assert!(
py_err.is_instance_of::<PyZeroDivisionError>(py),
"the callback's original class must survive the FFI: {py_err}"
);
assert!(
!py_err.is_instance_of::<EvaluationError>(py),
"the original class must not be flattened into EvaluationError"
);
assert!(py_err.to_string().contains("callback divided by zero"));
});
}
}
#[cfg(test)]
mod infrastructure_mapping_tests {
use super::*;
use crate::infrastructure::InfrastructureError as InfraErr;
use polypus_observable::ObservableError as ObsErr;
use pyo3::exceptions::{
PyKeyboardInterrupt, PyRuntimeError, PyValueError, PyZeroDivisionError,
};
use pyo3::prelude::*;
use pyo3::PyTypeInfo;
fn assert_maps_to<E: PyTypeInfo>(err: InfraErr, expected_message: &str) {
pyo3::prepare_freethreaded_python();
let py_err = infrastructure_error_to_pyerr(err);
Python::with_gil(|py| {
assert!(
py_err.is_instance_of::<E>(py),
"wrong exception class for: {py_err}"
);
assert!(
py_err.is_instance_of::<PolypusError>(py),
"every polypus.* class must stay catchable as PolypusError: {py_err}"
);
assert!(
py_err.to_string().contains(expected_message),
"message lost in translation: {py_err}"
);
});
}
#[test]
fn backend_variant_delegates_to_the_backend_mapping() {
pyo3::prepare_freethreaded_python();
let py_err = infrastructure_error_to_pyerr(InfraErr::Backend(InfraBackendError::Cunqa(
"qraise failed".to_string(),
)));
Python::with_gil(|py| {
assert!(py_err.is_instance_of::<CunqaError>(py));
assert!(
!py_err.is_instance_of::<EvaluationError>(py),
"a wrapped backend failure must keep its own class"
);
});
}
#[test]
fn observable_non_external_maps_to_evaluation_error() {
assert_maps_to::<EvaluationError>(
InfraErr::Observable(ObsErr::Invalid("coupling i == j".to_string())),
"coupling i == j",
);
}
#[test]
fn observable_external_preserves_the_original_python_class() {
pyo3::prepare_freethreaded_python();
let py_err = infrastructure_error_to_pyerr(InfraErr::Observable(ObsErr::External(
Box::new(PyZeroDivisionError::new_err("callback divided by zero")),
)));
Python::with_gil(|py| {
assert!(
py_err.is_instance_of::<PyZeroDivisionError>(py),
"a callback's ZeroDivisionError must re-raise with its original class: {py_err}"
);
assert!(
!py_err.is_instance_of::<EvaluationError>(py),
"the original class must not be flattened into EvaluationError"
);
assert!(py_err.to_string().contains("callback divided by zero"));
});
}
#[test]
fn python_variant_reraises_verbatim() {
pyo3::prepare_freethreaded_python();
let py_err = infrastructure_error_to_pyerr(InfraErr::Python(PyRuntimeError::new_err(
"planner boom",
)));
Python::with_gil(|py| {
assert!(
py_err.is_instance_of::<PyRuntimeError>(py),
"a planner Python exception must re-raise with its original class: {py_err}"
);
assert!(
!py_err.is_instance_of::<PolypusError>(py),
"a verbatim Python exception is not a polypus.* class"
);
assert!(py_err.to_string().contains("planner boom"));
});
}
#[test]
fn cancelled_maps_to_keyboard_interrupt() {
pyo3::prepare_freethreaded_python();
let py_err = infrastructure_error_to_pyerr(InfraErr::Cancelled);
Python::with_gil(|py| {
assert!(
py_err.is_instance_of::<PyKeyboardInterrupt>(py),
"a cooperative cancel must surface as KeyboardInterrupt: {py_err}"
);
assert!(
!py_err.is_instance_of::<PolypusError>(py),
"KeyboardInterrupt is a native Python exception, not a polypus.* class"
);
assert!(py_err.to_string().contains("the run was cancelled"));
});
}
#[test]
fn incompatible_planner_maps_to_value_error() {
pyo3::prepare_freethreaded_python();
let py_err = infrastructure_error_to_pyerr(InfraErr::IncompatiblePlanner(
"shot distribution unsupported".to_string(),
));
Python::with_gil(|py| {
assert!(
py_err.is_instance_of::<PyValueError>(py),
"an incompatible planner must surface as ValueError: {py_err}"
);
assert!(
!py_err.is_instance_of::<PolypusError>(py),
"ValueError is a native Python exception, not a polypus.* class"
);
assert!(py_err.to_string().contains("shot distribution unsupported"));
});
}
}