Skip to content

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

10.0 KB
Raw Blame
use crate::fingerprint::PyFingerprint;
use crate::function::{PyDataDepVerdicts, context_initial_states_to_pydict};
use crate::prelude::*;

use crate::deadline::PyDeadlineContext;
use crate::stable_path::PyStableKey;

use crate::app::PyStatsGroupHandle;
use crate::value::PyStoredValue;
use crate::{environment::PyEnvironment, stable_path::PyStablePath};
use cocoindex_core::engine::context::{ComponentProcessorContext, DataDepRecord, FnCallContext};
use cocoindex_utils::fingerprint::Fingerprint;
use pyo3::types::PyDict;
use pyo3_async_runtimes::tokio::future_into_py;

#[pyclass(name = "ComponentProcessorContext", from_py_object)]
#[derive(Clone)]
pub struct PyComponentProcessorContext(pub ComponentProcessorContext<PyEngineProfile>);

#[pymethods]
impl PyComponentProcessorContext {
    #[getter]
    fn environment(&self) -> PyEnvironment {
        PyEnvironment(self.0.app_ctx().env().clone())
    }

    #[getter]
    fn stable_path(&self) -> PyStablePath {
        PyStablePath(self.0.stable_path().clone())
    }

    #[getter]
    fn live(&self) -> bool {
        self.0.live()
    }

    /// The data-dependency verdicts of this context's operation.
    #[getter]
    fn data_dep_verdicts(&self) -> PyDataDepVerdicts {
        PyDataDepVerdicts(self.0.data_dep_verdicts().clone())
    }

    fn join_fn_call(&self, fn_ctx: &PyFnCallContext) -> PyResult<()> {
        self.0.join_fn_call(&fn_ctx.0);
        Ok(())
    }

    /// Open a stats group rooted at this context. Returns the derived context
    /// (whose mounts aggregate into the group, split out of the enclosing
    /// scope) and a `StatsGroupHandle` for `stats()`/`watch()`.
    #[pyo3(signature = (title, report_to_stdout, refresh_interval_secs=None))]
    fn begin_stats_group(
        &self,
        title: String,
        report_to_stdout: bool,
        refresh_interval_secs: Option<f64>,
    ) -> (PyComponentProcessorContext, PyStatsGroupHandle) {
        let (derived, stats) =
            self.0
                .begin_stats_group(title, report_to_stdout, refresh_interval_secs);
        (
            PyComponentProcessorContext(derived),
            PyStatsGroupHandle::new(stats),
        )
    }

    /// Close the group (stop registering members). Non-blocking β€” readiness
    /// resolves asynchronously once the members finish.
    fn end_stats_group(&self) {
        self.0.end_stats_group();
    }

    /// Count a component failure that no exception handler took ownership of
    /// (no handler registered, or every handler re-raised). Recorded on the
    /// root of the stats chain, so failures inside a stats group are covered
    /// too; drives the exit status of `cocoindex update`.
    fn record_unhandled_failure(&self) {
        self.0.processing_stats().record_unhandled_failure();
    }

    /// Collect eager initial memo states for the change-detection context fingerprints
    /// observed so far on this component (from `logic_deps`). Returns a
    /// `dict[Fingerprint, list[Any]]` directly β€” fingerprints with no
    /// registered state functions are skipped. Values are the *raw* Python
    /// state objects (not `StoredValue` wrappers), ready to be passed into
    /// `guard.resolve(..., context_memo_states=...)` without double wrapping.
    ///
    /// Used on cache miss to populate the new entry's `context_memo_states`
    /// without snapshotting `logic_deps` to Python.
    fn initial_context_memo_states<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyDict>> {
        let entries = self.0.collect_context_initial_states();
        context_initial_states_to_pydict(py, &entries)
    }

    /// Get the next ID for the given key.
    ///
    /// Args:
    ///     key: Optional stable key for the ID sequencer. If None, uses a default sequencer.
    ///
    /// Returns:
    ///     A coroutine that resolves to the next unique ID as an integer.
    #[pyo3(signature = (key=None, *, deadline))]
    fn next_id<'py>(
        &self,
        py: Python<'py>,
        key: Option<PyStableKey>,
        deadline: PyDeadlineContext,
    ) -> PyResult<Bound<'py, PyAny>> {
        let app_ctx = self.0.app_ctx().clone();
        // Required hand-off: the caller's current (possibly narrowed) scope,
        // not this ctx's mount-time base. See deadline_for_engine() in the
        // Python SDK.
        let deadline = deadline.0;
        future_into_py(py, async move {
            let id = app_ctx
                .next_id(key.as_ref().map(|k| &k.0), deadline)
                .await
                .into_py_result()?;
            Ok(id)
        })
    }

    /// Declare a persistent state key for this component build.
    ///
    /// `initial_value` is wrapped in an object-backed `StoredValue` without
    /// being serialized.
    ///
    /// - A value is already stored for `key` (from a previous run): the core
    ///   returns that *bytes-backed* `StoredValue` and this run's
    ///   `initial_value` is dropped (unserialized). Decoding those bytes back
    ///   to a Python object is deferred until the value is actually read.
    /// - Brand-new key (no stored value): the core keeps and returns the
    ///   `initial_value` cell as-is (*object-backed*). It is serialized once,
    ///   at commit (only if it survives as the component's state).
    ///
    /// Either way the `StoredValue` cell is returned directly, so the Python
    /// `StateHandle` reads through it lazily: a fresh value needs no
    /// serialize/deserialize round-trip, and a reloaded value is decoded at
    /// most once, on first access.
    ///
    /// Raises if the same key is declared more than once within the same run.
    fn use_state(&self, key: PyStableKey, initial_value: Py<PyAny>) -> PyResult<PyStoredValue> {
        self.0
            .use_state(key.0, PyStoredValue::new(initial_value))
            .into_py_result()
    }

    /// Update the value for an already-declared state key.
    ///
    /// Wraps the raw Python object in an object-backed `StoredValue` without
    /// serializing β€” serialization is deferred to commit time
    /// (`into_flush_plan`), so repeated writes in one run cost no serialization
    /// and only the final value is encoded once. Returns the wrapping cell so
    /// the `StateHandle` can keep it for subsequent in-run reads.
    ///
    /// Raises if `key` was not declared via `use_state` in this component run.
    fn update_user_state(&self, key: PyStableKey, value: Py<PyAny>) -> PyResult<PyStoredValue> {
        let stored = PyStoredValue::new(value);
        self.0
            .update_user_state(&key.0, stored.clone())
            .into_py_result()?;
        Ok(stored)
    }
}

#[pyclass(name = "FnCallContext")]
pub struct PyFnCallContext(pub FnCallContext);

#[pymethods]
impl PyFnCallContext {
    #[new]
    #[pyo3(signature = (*, propagate_children_fn_logic=true))]
    pub fn new(propagate_children_fn_logic: bool) -> Self {
        Self(FnCallContext::new(propagate_children_fn_logic))
    }

    pub fn join_child(&self, child_fn_ctx: &PyFnCallContext) -> PyResult<()> {
        self.0.join_child(&child_fn_ctx.0);
        Ok(())
    }

    /// Join a tunneled callback's collector frame; what it offered is addressed
    /// to `owner`, the frame that created the tunnel. See
    /// `FnCallContext::join_tunneled_child`.
    pub fn join_tunneled_child(
        &self,
        child_fn_ctx: &PyFnCallContext,
        owner: &PyFnCallContext,
    ) -> PyResult<()> {
        self.0.join_tunneled_child(&child_fn_ctx.0, owner.0.id());
        Ok(())
    }

    /// Whether this frame has been joined into its parent or component, i.e.
    /// its call has returned. A tunnel created in a closed frame is invalid.
    #[getter]
    pub fn closed(&self) -> bool {
        self.0.is_closed()
    }

    pub fn join_child_memo(&self, memo_fp: PyFingerprint) -> PyResult<()> {
        self.0.update(|inner| {
            inner.dependency_memo_entries.insert(memo_fp.0);
        });
        Ok(())
    }

    pub fn add_fn_logic_dep(&self, fp: PyFingerprint) -> PyResult<()> {
        self.0.add_fn_logic_dep(fp.0);
        Ok(())
    }

    pub fn add_context_change_dep(&self, fp: PyFingerprint) -> PyResult<()> {
        self.0.add_context_change_dep(fp.0);
        Ok(())
    }

    /// Record a data dependency (`coco.use_data_dep`) into this frame.
    ///
    /// `key` and `state` are serialized here, once, and the record's identity
    /// (`key_fp`) and equality (`state_fp`) are fingerprints of those bytes:
    /// the snapshot is what gets stored and validated, and the memo-key
    /// pipeline is deliberately not involved (a `__coco_memo_key__` that
    /// ignores fields must not merge two unequal observations).
    pub fn add_data_dep(
        &self,
        py: Python<'_>,
        kind_fp: PyFingerprint,
        key: &Bound<'_, PyAny>,
        state: &Bound<'_, PyAny>,
    ) -> PyResult<()> {
        let objects = crate::runtime::python_objects();
        let key = objects.serialize(py, key).into_py_result()?;
        let state = objects.serialize(py, state).into_py_result()?;
        self.0.add_data_dep(DataDepRecord {
            kind_fp: kind_fp.0,
            key_fp: Fingerprint::from_bytes(&key),
            state_fp: Fingerprint::from_bytes(&state),
            key,
            state,
        });
        Ok(())
    }

    /// Collect eager initial memo states for the change-detection context fingerprints
    /// captured in this fn call context, by looking them up in the given
    /// environment's registry. Returns a `dict[Fingerprint, list[Any]]`
    /// directly β€” fingerprints with no registered state functions are
    /// skipped. Values are the *raw* Python state objects (not `StoredValue`
    /// wrappers), ready to be passed into
    /// `guard.resolve(..., context_memo_states=...)` without double wrapping.
    ///
    /// Used on cache miss in the function-level memoization path to populate
    /// a new memo entry's `context_memo_states`.
    pub fn initial_context_memo_states<'py>(
        &self,
        py: Python<'py>,
        env: &PyEnvironment,
    ) -> PyResult<Bound<'py, PyDict>> {
        let entries = self.0.collect_context_initial_states(&env.0);
        context_initial_states_to_pydict(py, &entries)
    }
}