Skip to content

Incremental engine for long horizon agents 🌟 Star if you like it!

8.5 KB
Raw Blame
use cocoindex_utils::error::{CError, CResult, ClientErrorKind};
use pyo3::exceptions::{PyRuntimeError, PyTimeoutError, PyValueError};
use pyo3::prelude::*;
use pyo3::types::{PyDict, PyModule, PyString};
use std::any::Any;
use std::fmt::{Debug, Display};

pyo3::create_exception!(cocoindex_py_utils, DeadlineExceededError, PyTimeoutError);
// A `ValueError` subclass: every existing `except ValueError` keeps catching
// it, and a caller that cares can branch on the type instead of the text.
pyo3::create_exception!(cocoindex_py_utils, AlreadyDeclaredError, PyValueError);

pub struct PythonExecutionContext {
    pub event_loop: Py<PyAny>,
}

impl PythonExecutionContext {
    pub fn new(_py: Python<'_>, event_loop: Py<PyAny>) -> Self {
        Self { event_loop }
    }
}

pub struct HostedPyErr(PyErr);

impl Display for HostedPyErr {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        Display::fmt(&self.0, f)
    }
}

impl Debug for HostedPyErr {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let err = &self.0;
        Python::attach(|py| {
            let full_trace: PyResult<String> = (|| {
                let exc = err.value(py);
                let traceback = PyModule::import(py, "traceback")?;
                let tbe_class = traceback.getattr("TracebackException")?;
                let tbe = tbe_class.call_method1("from_exception", (exc,))?;
                let kwargs = PyDict::new(py);
                kwargs.set_item("chain", true)?;
                let lines = tbe.call_method("format", (), Some(&kwargs))?;
                let joined = PyString::new(py, "").call_method1("join", (lines,))?;
                joined.extract::<String>()
            })();

            match full_trace {
                Ok(trace) => {
                    write!(f, "Error calling Python function:\n{trace}")?;
                }
                Err(_) => {
                    write!(f, "Error calling Python function: {err}")?;
                    if let Some(tb) = err.traceback(py) {
                        write!(f, "\n{}", tb.format().unwrap_or_default())?;
                    }
                }
            };
            Ok(())
        })
    }
}

impl std::error::Error for HostedPyErr {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        self.0.source()
    }
}

impl cocoindex_utils::error::HostError for HostedPyErr {
    fn is_cancelled(&self) -> bool {
        Python::attach(|py| {
            let Ok(asyncio) = PyModule::import(py, "asyncio") else {
                return false;
            };
            let Ok(cancelled_cls) = asyncio.getattr("CancelledError") else {
                return false;
            };
            self.0.is_instance(py, &cancelled_cls)
        })
    }

    fn try_clone(&self) -> Option<Box<dyn cocoindex_utils::error::HostError>> {
        // `PyErr::clone_ref` shares the underlying Python exception object
        // (type + value + traceback), so every batch residual recipient gets
        // the original error β€” catchable by type, with the full Python
        // traceback intact β€” instead of a flattened string.
        Python::attach(|py| Some(Box::new(HostedPyErr(self.0.clone_ref(py))) as _))
    }
}

/// Convert an engine error into the Python exception surfaced to callers.
///
/// Tunneled Python exceptions (`HostedPyErr`) pass through as the original
/// object, including type, traceback and `__cause__`, with the engine's
/// context layers (e.g. which target states a failed sink was applying) added
/// as notes (`__notes__`, see [`add_context_notes`]). Engine-native errors
/// map to `asyncio.CancelledError` / `DeadlineExceededError` / `ValueError`
/// (client; `AlreadyDeclaredError` for a second declaration within one run) /
/// `RuntimeError` (internal).
pub fn cerror_to_pyerr(err: CError) -> PyErr {
    let inner = err.without_contexts();
    if let CError::HostLang(host_err) = inner {
        // Pass through tunneled Python errors as-is β€” preserves the
        // original exception object including traceback and any subclass
        // attributes. This applies to a tunneled `asyncio.CancelledError`
        // too: don't synthesize a fresh one from the cancellation branch
        // below; return the original.
        let any: &dyn Any = host_err.as_ref();
        let py_err = if let Some(hosted_py_err) = any.downcast_ref::<HostedPyErr>() {
            Some(&hosted_py_err.0)
        } else {
            any.downcast_ref::<PyErr>()
        };
        if let Some(py_err) = py_err {
            return Python::attach(|py| {
                let py_err = py_err.clone_ref(py);
                add_context_notes(py, &py_err, &err);
                py_err
            });
        }
    }
    // Cancellation-flavored errors that aren't tunneled Python exceptions
    // (e.g. Rust-constructed `Error::cancelled()` β†’ `CancelledError` HostError)
    // β†’ fresh `asyncio.CancelledError`. This lets Python callers
    // `except CancelledError` uniformly without string-matching the
    // Rust error message.
    if err.is_cancelled() {
        return Python::attach(|py| {
            let msg = format!("{}", err);
            match py
                .import("asyncio")
                .and_then(|m| m.getattr("CancelledError"))
                .and_then(|c| c.call1((msg,)))
            {
                Ok(exc) => PyErr::from_value(exc),
                Err(import_err) => import_err,
            }
        });
    }
    if err.is_deadline_exceeded() {
        return DeadlineExceededError::new_err(format!("{}", err));
    }
    if let CError::Client { kind, .. } = inner {
        return match kind {
            ClientErrorKind::AlreadyDeclared => AlreadyDeclaredError::new_err(format!("{}", err)),
            ClientErrorKind::Generic => PyValueError::new_err(format!("{}", err)),
        };
    }
    PyRuntimeError::new_err(format!("{}", err))
}

/// Add each context layer of `err`, outermost first, to the passed-through
/// exception `py_err` as a note, so the Python traceback shows what the engine
/// was doing (the message of an engine-native error carries its contexts
/// already). The exception object is shared by every conversion of the same
/// error (a component's result reaches every awaiter, and may cross into
/// Python more than once), so a note it carries already is not added again.
/// Best effort: a failure to add a note leaves the exception as it is.
fn add_context_notes(py: Python<'_>, py_err: &PyErr, err: &CError) {
    // A cancellation or a deadline is fanned out to every recipient of a
    // batch as one shared exception object; a note naming one recipient's
    // targets would mislead the others.
    if err.is_cancelled() || err.is_deadline_exceeded() {
        return;
    }
    let mut contexts = Vec::new();
    let mut current = err;
    while let CError::Context { msg, source } = current {
        contexts.push(msg.as_str());
        current = source.inner();
    }
    if contexts.is_empty() {
        return;
    }
    let exc = py_err.value(py);
    // `__notes__` may hold non-str entries (PEP 678 allows them); keep the
    // str ones, and what this call appends, to add each note once however
    // often the error crosses into Python.
    let mut existing: Vec<String> = exc
        .getattr("__notes__")
        .ok()
        .and_then(|notes| notes.try_iter().ok())
        .map(|notes| {
            notes
                .filter_map(|note| note.ok()?.extract::<String>().ok())
                .collect()
        })
        .unwrap_or_default();
    for context in contexts {
        if !existing.iter().any(|note| note == context) {
            let _ = exc.call_method1("add_note", (context,));
            existing.push(context.to_owned());
        }
    }
}

pub fn add_error_classes(m: &Bound<'_, PyModule>) -> PyResult<()> {
    m.add(
        "DeadlineExceededError",
        m.py().get_type::<DeadlineExceededError>(),
    )?;
    m.add(
        "AlreadyDeclaredError",
        m.py().get_type::<AlreadyDeclaredError>(),
    )
}

pub trait FromPyResult<T> {
    #[allow(
        clippy::wrong_self_convention,
        reason = "converts *from* a `PyResult`, the counterpart of `IntoPyResult::into_py_result`"
    )]
    fn from_py_result(self) -> CResult<T>;
}

impl<T> FromPyResult<T> for PyResult<T> {
    fn from_py_result(self) -> CResult<T> {
        self.map_err(|err| CError::host(HostedPyErr(err)))
    }
}

pub trait IntoPyResult<T> {
    fn into_py_result(self) -> PyResult<T>;
}

impl<T> IntoPyResult<T> for CResult<T> {
    fn into_py_result(self) -> PyResult<T> {
        self.map_err(cerror_to_pyerr)
    }
}