use crate::infrastructure::BackendError as InfraBackendError;
use crate::infrastructure::{DisplaySafePyErr, InterpreterUnavailable};
use pyo3::exceptions::{PyException, PyKeyboardInterrupt, PyTypeError, PyValueError};
use pyo3::sync::PyOnceLock;
use pyo3::types::{PyDict, PyTuple, PyType};
use pyo3::{create_exception, intern, Bound, Py, PyErr, PyResult, Python};
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,
InsufficientMemoryError,
BackendError,
"A statevector would not fit in the memory budget, so the run was refused before \
starting instead of being killed by the out-of-memory killer. The budget is \
POLYPUS_MEM_BUDGET when set (e.g. POLYPUS_MEM_BUDGET=64G), else the detected \
RAM/cgroup limit minus a safety reserve."
);
create_exception!(
polypus,
EvaluationError,
PolypusError,
"An oracle/expectation-evaluation failure during training."
);
pub(crate) fn configuration_error_type(py: Python<'_>) -> PyResult<&Bound<'_, PyType>> {
use pyo3::types::{PyAnyMethods, PyDictMethods};
static TYPE: PyOnceLock<Py<PyType>> = PyOnceLock::new();
TYPE.get_or_try_init(py, || {
let bases = PyTuple::new(
py,
[py.get_type::<PolypusError>(), py.get_type::<PyValueError>()],
)?;
let namespace = PyDict::new(py);
namespace.set_item("__module__", "polypus")?;
namespace.set_item(
"__doc__",
"An invalid argument or configuration. Also a ValueError. The entry points \
check these before creating any backend.",
)?;
py.get_type::<PyType>()
.call1(("ConfigurationError", bases, namespace))?
.cast_into::<PyType>()
.map(Bound::unbind)
.map_err(PyErr::from)
})
.map(|class| class.bind(py))
}
pub(crate) fn configuration_error(message: impl Into<String>) -> PyErr {
let message = message.into();
crate::infrastructure::attach_or(
|| PyValueError::new_err(message.clone()),
|py| match configuration_error_type(py) {
Ok(class) => PyErr::from_type(class.clone(), message.clone()),
Err(_) => PyValueError::new_err(message.clone()),
},
)
}
pub(crate) fn backend_error_to_pyerr(err: InfraBackendError) -> PyErr {
match err {
InfraBackendError::UnknownInfrastructure { name } => configuration_error(format!(
"unknown infrastructure '{name}'; expected \"local\", \"cunqa\" or \"qmio\""
)),
InfraBackendError::InvalidCircuitCount { expected, got } => {
configuration_error(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),
InfraBackendError::Unresponsive(m) => {
BackendError::new_err(format!("the backend stopped responding: {m}"))
}
InfraBackendError::Aborted(m) => {
PyKeyboardInterrupt::new_err(format!("the run was aborted: {m}"))
}
InfraBackendError::InsufficientMemory(e) => insufficient_memory_to_pyerr(&e),
InfraBackendError::External(boxed) => external_to_pyerr(boxed),
other => BackendError::new_err(other.to_string()),
}
}
pub(crate) fn insufficient_memory_to_pyerr(
err: &crate::infrastructure::InsufficientMemory,
) -> PyErr {
InsufficientMemoryError::new_err(err.to_string())
}
fn external_to_pyerr(boxed: Box<dyn std::error::Error + Send + Sync>) -> PyErr {
let boxed = match boxed.downcast::<DisplaySafePyErr>() {
Ok(py_err) => return qiskit_error_to_pyerr(py_err.into_inner()),
Err(other) => other,
};
let boxed = match boxed.downcast::<InterpreterUnavailable>() {
Ok(unavailable) => return interpreter_unavailable_to_pyerr(*unavailable),
Err(other) => other,
};
#[cfg(feature = "qmio")]
let boxed = match boxed.downcast::<polypus_infrastructure::qmio::QmioError>() {
Ok(qmio_err) => return QmioError::new_err(qmio_err.to_string()),
Err(other) => other,
};
BackendError::new_err(boxed.to_string())
}
pub(crate) fn interpreter_unavailable_to_pyerr(err: InterpreterUnavailable) -> PyErr {
PyKeyboardInterrupt::new_err(format!("the run was aborted: {err}"))
}
fn is_qiskit_module(module: &str) -> bool {
let root = module.split('.').next().unwrap_or(module);
root == "qiskit" || root.starts_with("qiskit_")
}
pub(crate) fn is_qiskit_exception(py: pyo3::Python<'_>, err: &PyErr) -> bool {
use pyo3::types::{PyAnyMethods, PyTupleMethods, PyTypeMethods};
err.get_type(py).mro().iter().any(|class| {
class
.getattr(intern!(py, "__module__"))
.and_then(|module| module.extract::<String>())
.is_ok_and(|module| is_qiskit_module(&module))
})
}
pub(crate) fn describe_python_error(py: pyo3::Python<'_>, err: &PyErr) -> String {
use pyo3::types::{PyAnyMethods, PyTypeMethods};
let class = err
.get_type(py)
.fully_qualified_name()
.map_or_else(|_| "<unknown exception>".to_string(), |n| n.to_string());
let message = err
.value(py)
.str()
.map_or_else(|_| "<unprintable message>".to_string(), |m| m.to_string());
format!("{class}: {message}")
}
pub(crate) fn qiskit_error_to_pyerr(err: PyErr) -> PyErr {
wrap_qiskit_error::<BackendError>(err)
}
pub(crate) fn qiskit_error_to_evaluation_error(err: PyErr) -> PyErr {
wrap_qiskit_error::<EvaluationError>(err)
}
fn wrap_qiskit_error<E: pyo3::PyTypeInfo>(err: PyErr) -> PyErr {
let wrapper = crate::infrastructure::attach_or(
|| None,
|py| {
let preserved = err.is_instance_of::<PyValueError>(py)
|| err.is_instance_of::<PyTypeError>(py)
|| err.is_instance_of::<PyKeyboardInterrupt>(py);
(!preserved && is_qiskit_exception(py, &err))
.then(|| PyErr::new::<E, _>(describe_python_error(py, &err)))
},
);
match wrapper {
Some(wrapper) => {
crate::infrastructure::attach_or(|| (), |py| wrapper.set_cause(py, Some(err)));
wrapper
}
None => err,
}
}
fn observable_error_to_pyerr(err: polypus_observable::ObservableError) -> PyErr {
use polypus_observable::ObservableError as ObsErr;
match err {
ObsErr::External(boxed) => match boxed.downcast::<DisplaySafePyErr>() {
Ok(py_err) => py_err.into_inner(),
Err(other) => match other.downcast::<InterpreterUnavailable>() {
Ok(unavailable) => interpreter_unavailable_to_pyerr(*unavailable),
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.into_inner(),
EvalErr::Qiskit(py_err) => qiskit_error_to_evaluation_error(py_err.into_inner()),
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()),
non_finite_score @ EvalErr::NonFiniteScore { .. } => {
EvaluationError::new_err(non_finite_score.to_string())
}
label_count @ EvalErr::LabelCount { .. } => {
EvaluationError::new_err(label_count.to_string())
}
invalid_variance @ EvalErr::InvalidVariance { .. } => {
EvaluationError::new_err(invalid_variance.to_string())
}
qml @ EvalErr::Qml(_) => EvaluationError::new_err(qml.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::Cancelled => PyKeyboardInterrupt::new_err("the run was cancelled"),
InfraErr::IncompatiblePlanner(m) => configuration_error(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(
"InsufficientMemoryError",
py.get_type::<InsufficientMemoryError>(),
)?;
m.add("EvaluationError", py.get_type::<EvaluationError>())?;
m.add("ConfigurationError", configuration_error_type(py)?)?;
Ok(())
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
use pyo3::prelude::*;
use pyo3::PyTypeInfo;
fn assert_maps_to<E: PyTypeInfo>(err: InfraBackendError, expected_message: &str) {
pyo3::Python::initialize();
let py_err = backend_error_to_pyerr(err);
Python::attach(|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}"
);
});
}
pub(crate) fn assert_configuration_error(py_err: &PyErr, expected_message: &str) {
pyo3::Python::initialize();
Python::attach(|py| {
let class = configuration_error_type(py).expect("the class is created");
assert!(py_err.matches(py, class).expect("matches"), "{py_err}");
assert!(py_err.is_instance_of::<PolypusError>(py), "{py_err}");
assert!(py_err.is_instance_of::<PyValueError>(py), "{py_err}");
assert!(py_err.to_string().contains(expected_message), "{py_err}");
});
}
#[test]
fn configuration_error_is_a_polypus_error_and_a_value_error() {
assert_configuration_error(&configuration_error("bad shots"), "bad shots");
}
#[test]
fn unknown_infrastructure_maps_to_configuration_error() {
let err = backend_error_to_pyerr(InfraBackendError::UnknownInfrastructure {
name: "nowhere".to_string(),
});
assert_configuration_error(&err, "unknown infrastructure 'nowhere'");
}
#[test]
fn invalid_circuit_count_maps_to_configuration_error() {
let err = backend_error_to_pyerr(InfraBackendError::InvalidCircuitCount {
expected: 1,
got: 2,
});
assert_configuration_error(&err, "expected exactly 1 circuit(s), got 2");
}
#[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 insufficient_memory_maps_to_insufficient_memory_error() {
use crate::infrastructure::{BudgetSource, InsufficientMemory};
let refusal = || {
InfraBackendError::InsufficientMemory(InsufficientMemory {
num_qubits: 20,
required_bytes: 16 << 20,
budget_bytes: 1 << 20,
source: BudgetSource::Explicit,
})
};
assert_maps_to::<InsufficientMemoryError>(refusal(), "20-qubit statevector");
assert_maps_to::<BackendError>(refusal(), "POLYPUS_MEM_BUDGET");
}
#[test]
fn unresponsive_maps_to_the_backend_error_base_class() {
assert_maps_to::<BackendError>(
InfraBackendError::Unresponsive("worker died (signal 9)".to_string()),
"the backend stopped responding: worker died (signal 9)",
);
}
#[test]
fn aborted_maps_to_keyboard_interrupt() {
pyo3::Python::initialize();
let py_err = backend_error_to_pyerr(InfraBackendError::Aborted("Ctrl+C".to_string()));
Python::attach(|py| {
assert!(
py_err.is_instance_of::<PyKeyboardInterrupt>(py),
"an aborted backend call 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 aborted: Ctrl+C"));
});
}
#[test]
fn external_provider_error_maps_to_the_backend_error_base_class() {
#[derive(Debug)]
struct Provider(&'static str);
impl std::fmt::Display for Provider {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "provider failure: {}", self.0)
}
}
impl std::error::Error for Provider {}
assert_maps_to::<BackendError>(
InfraBackendError::External(Box::new(Provider("device offline"))),
"provider failure: device offline",
);
}
#[test]
fn entropy_error_maps_to_the_backend_error_base_class_not_a_panic() {
let entropy_failure = || {
InfraBackendError::from(crate::infrastructure::EntropyError::new(
std::io::Error::other("getrandom: device not available"),
))
};
assert_maps_to::<BackendError>(entropy_failure(), "OS entropy source unavailable");
let py_err = backend_error_to_pyerr(entropy_failure());
Python::attach(|py| {
assert!(
py_err.is_instance_of::<pyo3::exceptions::PyException>(py),
"must be catchable as Exception: {py_err}"
);
assert!(
!py_err.is_instance_of::<pyo3::panic::PanicException>(py),
"must not cross as a PanicException: {py_err}"
);
assert!(
py_err
.to_string()
.contains("getrandom: device not available"),
"the underlying cause must reach Python: {py_err}"
);
});
}
pub(super) fn fake_error(py: Python<'_>, class: &str, message: &str) -> PyErr {
let module = pyo3::types::PyModule::from_code(
py,
c"class QiskitError(Exception): pass\n\
QiskitError.__module__ = 'qiskit.exceptions'\n\
class AerError(QiskitError): pass\n\
AerError.__module__ = 'qiskit_aer.aererror'\n\
class UserError(QiskitError): pass\n\
UserError.__module__ = 'user_code'\n\
class QiskitValueError(QiskitError, ValueError): pass\n\
class QiskitKeyboardInterrupt(QiskitError, KeyboardInterrupt): pass\n\
class NotQiskit(Exception): pass\n\
NotQiskit.__module__ = 'qiskitlike'\n",
c"fake_qiskit.py",
c"fake_qiskit",
)
.expect("the stand-in module compiles");
let value = module
.getattr(class)
.and_then(|c| c.call1((message,)))
.expect("the stand-in class instantiates");
PyErr::from_value(value)
}
#[test]
fn qiskit_modules_are_recognised_by_their_root_package() {
for module in ["qiskit", "qiskit.exceptions", "qiskit.qasm2.exceptions"] {
assert!(is_qiskit_module(module), "{module}");
}
for module in ["qiskit_aer", "qiskit_aer.aererror", "qiskit_ibm_runtime.x"] {
assert!(is_qiskit_module(module), "{module}");
}
for module in [
"builtins",
"qiskitlike",
"my_qiskit",
"polypus",
"user.qiskit",
] {
assert!(!is_qiskit_module(module), "{module}");
}
}
#[test]
fn qiskit_exception_is_detected_through_the_mro() {
pyo3::Python::initialize();
Python::attach(|py| {
for class in ["QiskitError", "AerError", "UserError", "QiskitValueError"] {
assert!(
is_qiskit_exception(py, &fake_error(py, class, "x")),
"{class}"
);
}
assert!(!is_qiskit_exception(py, &fake_error(py, "NotQiskit", "x")));
let runtime = pyo3::exceptions::PyRuntimeError::new_err("x");
assert!(!is_qiskit_exception(py, &runtime));
});
}
#[test]
fn external_qiskit_error_maps_to_backend_error_with_its_cause() {
pyo3::Python::initialize();
for (class, qualified) in [
("QiskitError", "qiskit.exceptions.QiskitError"),
("AerError", "qiskit_aer.aererror.AerError"),
("UserError", "user_code.UserError"),
] {
let original = Python::attach(|py| fake_error(py, class, "no counts"));
let original_value = Python::attach(|py| original.value(py).clone().unbind());
let expected = format!("{qualified}: no counts");
let py_err = backend_error_to_pyerr(InfraBackendError::External(Box::new(
DisplaySafePyErr::from(original),
)));
Python::attach(|py| {
assert!(
py_err.get_type(py).is(py.get_type::<BackendError>()),
"exactly polypus.BackendError, not a subclass: {py_err}"
);
assert!(py_err.is_instance_of::<PolypusError>(py), "{py_err}");
assert!(
py_err.to_string().contains(&expected),
"the Qiskit class and message must survive: {py_err}"
);
let cause = py_err.cause(py).expect("the Qiskit original is chained");
assert!(
cause.value(py).is(original_value.bind(py)),
"__cause__ must be the original exception object"
);
});
}
}
#[test]
fn qiskit_error_that_is_also_a_c1_type_is_preserved() {
pyo3::Python::initialize();
let value_error = Python::attach(|py| fake_error(py, "QiskitValueError", "bad kwarg"));
let py_err = backend_error_to_pyerr(InfraBackendError::External(Box::new(
DisplaySafePyErr::from(value_error),
)));
Python::attach(|py| {
assert!(py_err.is_instance_of::<PyValueError>(py), "{py_err}");
assert!(!py_err.is_instance_of::<PolypusError>(py), "{py_err}");
});
let interrupt = Python::attach(|py| fake_error(py, "QiskitKeyboardInterrupt", "stop"));
let py_err = backend_error_to_pyerr(InfraBackendError::External(Box::new(
DisplaySafePyErr::from(interrupt),
)));
Python::attach(|py| {
assert!(py_err.is_instance_of::<PyKeyboardInterrupt>(py), "{py_err}");
assert!(!py_err.is_instance_of::<PolypusError>(py), "{py_err}");
});
}
#[test]
fn non_qiskit_python_errors_are_reraised_verbatim() {
pyo3::Python::initialize();
let cases: [(PyErr, &str); 4] = [
(
pyo3::exceptions::PyRuntimeError::new_err("boom"),
"RuntimeError",
),
(PyTypeError::new_err("bad kwarg"), "TypeError"),
(
PyValueError::new_err("unknown infrastructure"),
"ValueError",
),
(
Python::attach(|py| fake_error(py, "NotQiskit", "x")),
"NotQiskit",
),
];
for (err, class) in cases {
let py_err = backend_error_to_pyerr(InfraBackendError::External(Box::new(
DisplaySafePyErr::from(err),
)));
Python::attach(|py| {
assert_eq!(py_err.get_type(py).name().unwrap().to_string(), class);
assert!(!py_err.is_instance_of::<PolypusError>(py), "{py_err}");
assert!(py_err.cause(py).is_none(), "nothing is chained: {py_err}");
});
}
}
#[test]
fn display_safe_py_err_reraises_the_original_exception() {
pyo3::Python::initialize();
let original = PyTypeError::new_err("bad kwarg");
let original_value = Python::attach(|py| original.value(py).clone().unbind());
let py_err = backend_error_to_pyerr(InfraBackendError::External(Box::new(
DisplaySafePyErr::from(original),
)));
Python::attach(|py| {
assert!(py_err.is_instance_of::<PyTypeError>(py), "{py_err}");
assert!(!py_err.is_instance_of::<PolypusError>(py), "{py_err}");
assert!(py_err.value(py).is(original_value.bind(py)));
});
}
#[test]
fn bare_py_err_in_external_is_not_reraised_verbatim() {
assert_maps_to::<BackendError>(
InfraBackendError::External(Box::new(PyValueError::new_err("bad kwarg"))),
"ValueError: bad kwarg",
);
let py_err = backend_error_to_pyerr(InfraBackendError::External(Box::new(
PyValueError::new_err("bad kwarg"),
)));
Python::attach(|py| assert!(!py_err.is_instance_of::<PyValueError>(py)));
}
pub(super) fn assert_aborted_by_unavailable_interpreter(py_err: PyErr) {
let expected = format!(
"the run was aborted: {}",
crate::infrastructure::InterpreterUnavailable
);
Python::attach(|py| {
assert!(
py_err.is_instance_of::<PyKeyboardInterrupt>(py),
"an unreachable interpreter must abort the run as KeyboardInterrupt: {py_err}"
);
assert!(!py_err.is_instance_of::<PolypusError>(py), "{py_err}");
assert_eq!(py_err.value(py).to_string(), expected);
});
}
#[test]
fn interpreter_unavailable_in_external_maps_to_keyboard_interrupt() {
pyo3::Python::initialize();
assert_aborted_by_unavailable_interpreter(backend_error_to_pyerr(InfraBackendError::from(
crate::infrastructure::InterpreterUnavailable,
)));
let original = PyValueError::new_err("bad kwarg");
let original_value = Python::attach(|py| original.value(py).clone().unbind());
let py_err = backend_error_to_pyerr(InfraBackendError::External(Box::new(
DisplaySafePyErr::from(original),
)));
Python::attach(|py| {
assert!(py_err.is_instance_of::<PyValueError>(py), "{py_err}");
assert!(py_err.value(py).is(original_value.bind(py)));
});
}
#[test]
fn provider_errors_stay_catchable_as_backend_error() {
pyo3::Python::initialize();
let cunqa = backend_error_to_pyerr(InfraBackendError::Cunqa("x".to_string()));
let native = backend_error_to_pyerr(InfraBackendError::UnsupportedCircuit("y".to_string()));
Python::attach(|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::Python::initialize();
Python::attach(|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::Python::initialize();
Python::attach(|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::Python::initialize();
Python::attach(|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::Python::initialize();
let py_err = evaluation_error_to_pyerr(err);
Python::attach(|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 non_finite_score_maps_to_evaluation_error_naming_the_row() {
assert_maps_to_evaluation_error(
EvalErr::NonFiniteScore {
sample: 5,
value: f64::NEG_INFINITY,
},
"x_train row 5",
);
}
#[test]
fn label_count_maps_to_evaluation_error() {
assert_maps_to_evaluation_error(
EvalErr::LabelCount {
labels: 2,
samples: 3,
},
"contract C-8",
);
}
#[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 qml_maps_to_evaluation_error() {
assert_maps_to_evaluation_error(
EvalErr::Qml(crate::evaluation::QmlError::NoExactGradient {
reason: "a Qiskit source".to_string(),
}),
"no exact parameter-shift gradient",
);
}
#[test]
fn backend_variant_delegates_to_the_backend_mapping() {
pyo3::Python::initialize();
let py_err = evaluation_error_to_pyerr(EvalErr::Backend(BackendError::Cunqa(
"qraise failed".to_string(),
)));
Python::attach(|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 qiskit_binding_error_maps_to_evaluation_error_with_its_cause() {
pyo3::Python::initialize();
let original = Python::attach(|py| super::tests::fake_error(py, "QiskitError", "bad"));
let original_value = Python::attach(|py| original.value(py).clone().unbind());
let py_err = evaluation_error_to_pyerr(EvalErr::Qiskit(original.into()));
Python::attach(|py| {
assert!(
py_err.get_type(py).is(py.get_type::<EvaluationError>()),
"exactly polypus.EvaluationError: {py_err}"
);
assert!(py_err.is_instance_of::<PolypusError>(py));
assert!(
py_err
.to_string()
.contains("qiskit.exceptions.QiskitError: bad"),
"{py_err}"
);
let cause = py_err.cause(py).expect("the Qiskit original is chained");
assert!(cause.value(py).is(original_value.bind(py)));
});
}
#[test]
fn qiskit_variant_keeps_non_qiskit_and_c1_typed_errors() {
pyo3::Python::initialize();
let cases: [(PyErr, &str); 3] = [
(PyValueError::new_err("Mismatching number"), "ValueError"),
(PyTypeError::new_err("Cannot assign object"), "TypeError"),
(
Python::attach(|py| super::tests::fake_error(py, "QiskitValueError", "x")),
"QiskitValueError",
),
];
for (err, class) in cases {
let py_err = evaluation_error_to_pyerr(EvalErr::Qiskit(err.into()));
Python::attach(|py| {
assert_eq!(py_err.get_type(py).name().unwrap().to_string(), class);
assert!(!py_err.is_instance_of::<PolypusError>(py), "{py_err}");
});
}
}
#[test]
fn python_variant_stays_verbatim_even_for_a_qiskit_class() {
pyo3::Python::initialize();
let py_err = evaluation_error_to_pyerr(EvalErr::Python(
Python::attach(|py| super::tests::fake_error(py, "QiskitError", "from a callback"))
.into(),
));
Python::attach(|py| {
assert_eq!(
py_err.get_type(py).name().unwrap().to_string(),
"QiskitError"
);
assert!(!py_err.is_instance_of::<PolypusError>(py), "{py_err}");
assert!(py_err.cause(py).is_none());
});
}
#[test]
fn observable_external_preserves_the_original_python_class() {
pyo3::Python::initialize();
let py_err =
evaluation_error_to_pyerr(EvalErr::Observable(ObservableError::External(Box::new(
DisplaySafePyErr::from(PyZeroDivisionError::new_err("callback divided by zero")),
))));
Python::attach(|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"));
});
}
#[test]
fn interpreter_unavailable_maps_to_keyboard_interrupt_on_the_evaluation_path() {
use crate::infrastructure::InterpreterUnavailable;
pyo3::Python::initialize();
super::tests::assert_aborted_by_unavailable_interpreter(evaluation_error_to_pyerr(
EvalErr::Backend(BackendError::from(InterpreterUnavailable)),
));
super::tests::assert_aborted_by_unavailable_interpreter(evaluation_error_to_pyerr(
EvalErr::Observable(ObservableError::External(Box::new(InterpreterUnavailable))),
));
let py_err = evaluation_error_to_pyerr(EvalErr::Observable(ObservableError::External(
Box::new(DisplaySafePyErr::from(PyValueError::new_err("bad row"))),
)));
Python::attach(|py| assert!(py_err.is_instance_of::<PyValueError>(py), "{py_err}"));
}
#[test]
fn bare_py_err_in_observable_external_is_not_reraised_verbatim() {
assert_maps_to_evaluation_error(
EvalErr::Observable(ObservableError::External(Box::new(
PyZeroDivisionError::new_err("callback divided by zero"),
))),
"ZeroDivisionError: 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, PyZeroDivisionError};
use pyo3::PyTypeInfo;
fn assert_maps_to<E: PyTypeInfo>(err: InfraErr, expected_message: &str) {
pyo3::Python::initialize();
let py_err = infrastructure_error_to_pyerr(err);
Python::attach(|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::Python::initialize();
let py_err = infrastructure_error_to_pyerr(InfraErr::Backend(InfraBackendError::Cunqa(
"qraise failed".to_string(),
)));
Python::attach(|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::Python::initialize();
let py_err =
infrastructure_error_to_pyerr(InfraErr::Observable(ObsErr::External(Box::new(
DisplaySafePyErr::from(PyZeroDivisionError::new_err("callback divided by zero")),
))));
Python::attach(|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 external_backend_error_reraises_verbatim() {
pyo3::Python::initialize();
let py_err = infrastructure_error_to_pyerr(InfraErr::Backend(InfraBackendError::External(
Box::new(DisplaySafePyErr::from(PyRuntimeError::new_err(
"planner boom",
))),
)));
Python::attach(|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 interpreter_unavailable_maps_to_keyboard_interrupt() {
use crate::infrastructure::InterpreterUnavailable;
pyo3::Python::initialize();
super::tests::assert_aborted_by_unavailable_interpreter(infrastructure_error_to_pyerr(
InfraErr::from(InterpreterUnavailable),
));
super::tests::assert_aborted_by_unavailable_interpreter(infrastructure_error_to_pyerr(
InfraErr::Observable(ObsErr::External(Box::new(InterpreterUnavailable))),
));
}
#[test]
fn cancelled_maps_to_keyboard_interrupt() {
pyo3::Python::initialize();
let py_err = infrastructure_error_to_pyerr(InfraErr::Cancelled);
Python::attach(|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_configuration_error() {
let py_err = infrastructure_error_to_pyerr(InfraErr::IncompatiblePlanner(
"shot distribution unsupported".to_string(),
));
super::tests::assert_configuration_error(&py_err, "shot distribution unsupported");
}
}