Skip to content

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

17.4 KB
Raw Blame
use std::collections::HashMap;

use cocoindex_core::engine::context::{
    DataDepIdentity, DataDepRecord, DataDepVerdict, DataDepVerdicts, MemoStatesPayload,
};
use cocoindex_core::engine::function::FnCallMemoGuard;
use cocoindex_core::engine::profile::Persist;
use cocoindex_core::engine::runtime::get_runtime;
use cocoindex_utils::fingerprint::Fingerprint;
use pyo3::types::{PyDict, PyList};
use pyo3_async_runtimes::tokio::future_into_py;

use crate::context::{PyComponentProcessorContext, PyFnCallContext};
use crate::fingerprint::PyFingerprint;
use crate::prelude::*;
use crate::value::PyStoredValue;

/// Build a `MemoStatesPayload<PyEngineProfile>` from the Python-side inputs.
///
/// `context_entries` is a Python `dict[Fingerprint, list[Any]]` extracted by
/// pyo3 directly into a `HashMap` β€” no intermediate list-of-tuples.
/// A data dependency as the Python probe hands it back after validation:
/// `(kind_fp, key_fp, key, state)`, where `key` is the stored `StoredValue`
/// and `state` is either the stored `StoredValue` (unchanged) or the
/// validator's new state object.
pub(crate) type PyRefreshedDataDep = (PyFingerprint, PyFingerprint, Py<PyAny>, Py<PyAny>);

/// Wrap a Python object as a stored value. A `StoredValue` handed back from a
/// probe (an unchanged state) is used as is, so its bytes and fingerprint
/// stay exactly those that were stored; anything else is a fresh object.
fn to_stored_value(py: Python<'_>, obj: Py<PyAny>) -> PyStoredValue {
    match obj.bind(py).cast::<PyStoredValue>() {
        Ok(stored) => stored.borrow().clone(),
        Err(_) => PyStoredValue::new(obj),
    }
}

/// The serialized bytes of a data-dependency key or state handed back from a
/// probe: the stored bytes for a `StoredValue`, a fresh serialization
/// otherwise.
fn data_dep_bytes(py: Python<'_>, obj: Py<PyAny>) -> PyResult<bytes::Bytes> {
    to_stored_value(py, obj).to_bytes().into_py_result()
}

pub(crate) fn build_data_dep_records(
    py: Python<'_>,
    records: Vec<PyRefreshedDataDep>,
) -> PyResult<Vec<DataDepRecord>> {
    records
        .into_iter()
        .map(|(kind_fp, key_fp, key, state)| {
            let key = data_dep_bytes(py, key)?;
            let state = data_dep_bytes(py, state)?;
            Ok(DataDepRecord {
                kind_fp: kind_fp.0,
                key_fp: key_fp.0,
                state_fp: Fingerprint::from_bytes(&state),
                key,
                state,
            })
        })
        .collect()
}

/// Build a `MemoStatesPayload<PyEngineProfile>` from the Python-side inputs.
///
/// `context_entries` is a Python `dict[Fingerprint, list[Any]]` extracted by
/// pyo3 directly into a `HashMap` β€” no intermediate list-of-tuples.
pub(crate) fn build_memo_states_payload(
    py: Python<'_>,
    positional: Option<Vec<Py<PyAny>>>,
    context_entries: Option<HashMap<PyFingerprint, Vec<Py<PyAny>>>>,
    data_deps: Option<Vec<PyRefreshedDataDep>>,
) -> PyResult<MemoStatesPayload<PyEngineProfile>> {
    let positional = positional
        .unwrap_or_default()
        .into_iter()
        .map(|obj| to_stored_value(py, obj))
        .collect();
    let by_context_fp = context_entries
        .unwrap_or_default()
        .into_iter()
        .map(|(fp, values)| {
            (
                fp.0,
                values
                    .into_iter()
                    .map(|obj| to_stored_value(py, obj))
                    .collect::<Vec<_>>(),
            )
        })
        .collect();
    let data_deps = build_data_dep_records(py, data_deps.unwrap_or_default())?;
    Ok(MemoStatesPayload {
        positional,
        by_context_fp,
        data_deps,
    })
}

/// Convert stored data-dependency records into a Python list of
/// `(kind_fp, key_fp, state_fp, key, state)` tuples, key and state as
/// `StoredValue`s the probe decodes through the kind's deserializers. The
/// three fingerprints are the record's identity (see `DataDepVerdicts`).
pub(crate) fn data_deps_to_pylist<'py>(
    py: Python<'py>,
    records: &[DataDepRecord],
) -> PyResult<Bound<'py, PyList>> {
    let items = records
        .iter()
        .map(|r| {
            let key = Py::new(py, PyStoredValue::from_bytes(&r.key).into_py_result()?)?;
            let state = Py::new(py, PyStoredValue::from_bytes(&r.state).into_py_result()?)?;
            Ok((
                Py::new(py, PyFingerprint(r.kind_fp))?,
                Py::new(py, PyFingerprint(r.key_fp))?,
                Py::new(py, PyFingerprint(r.state_fp))?,
                key,
                state,
            ))
        })
        .collect::<PyResult<Vec<_>>>()?;
    PyList::new(py, items)
}

/// What a validator answered for one record identity, as a probe reads it.
#[pyclass(frozen, name = "DataDepVerdict")]
pub struct PyDataDepVerdict {
    memo_valid: bool,
    new_state: Option<PyStoredValue>,
}

#[pymethods]
impl PyDataDepVerdict {
    #[getter]
    fn memo_valid(&self) -> bool {
        self.memo_valid
    }

    /// The validator's changed state; `None` when it equals the stored one.
    #[getter]
    fn new_state(&self) -> Option<PyStoredValue> {
        self.new_state.clone()
    }
}

fn verdict_to_py(verdict: DataDepVerdict) -> PyResult<PyDataDepVerdict> {
    let new_state = verdict
        .new_state
        .map(|bytes| PyStoredValue::from_bytes(&bytes).into_py_result())
        .transpose()?;
    Ok(PyDataDepVerdict {
        memo_valid: verdict.memo_valid,
        new_state,
    })
}

fn identity(
    kind_fp: &PyFingerprint,
    key_fp: &PyFingerprint,
    state_fp: &PyFingerprint,
) -> DataDepIdentity {
    DataDepIdentity {
        kind_fp: kind_fp.0,
        key_fp: key_fp.0,
        state_fp: state_fp.0,
    }
}

/// The data-dependency verdicts of one operation (`DataDepVerdicts` in the
/// core): a probe takes the verdict of a record identity validated earlier in
/// the operation instead of calling its validator, and records the answer of
/// each validator it does call.
#[pyclass(frozen, name = "DataDepVerdicts")]
pub struct PyDataDepVerdicts(pub Arc<DataDepVerdicts>);

#[pymethods]
impl PyDataDepVerdicts {
    /// The verdict this operation holds for the record identity, if any.
    fn get(
        &self,
        kind_fp: PyFingerprint,
        key_fp: PyFingerprint,
        state_fp: PyFingerprint,
    ) -> PyResult<Option<PyDataDepVerdict>> {
        self.0
            .get(&identity(&kind_fp, &key_fp, &state_fp))
            .map(verdict_to_py)
            .transpose()
    }

    /// Record a validator's answer for the record identity: `memo_valid`, and
    /// the state it returned, which is kept only when `state_changed` (it
    /// differs from the stored one). Returns the verdict the operation acts
    /// on: this one, or one a concurrent probe recorded first.
    #[allow(clippy::too_many_arguments)]
    fn record(
        &self,
        py: Python<'_>,
        kind_fp: PyFingerprint,
        key_fp: PyFingerprint,
        state_fp: PyFingerprint,
        memo_valid: bool,
        state_changed: bool,
        state: Py<PyAny>,
    ) -> PyResult<PyDataDepVerdict> {
        let new_state = state_changed
            .then(|| data_dep_bytes(py, state))
            .transpose()?;
        let verdict = self.0.record(
            identity(&kind_fp, &key_fp, &state_fp),
            DataDepVerdict {
                memo_valid,
                new_state,
            },
        );
        verdict_to_py(verdict)
    }
}

/// Convert the stored context-borne memo states into a Python `dict`
/// `{Fingerprint: list[PyStoredValue]}` keyed by fingerprint for O(1) lookup
/// on the Python side.
///
/// Used by the cache-hit validation path, which calls `.get(deserializer)`
/// on each value to extract a typed Python object from stored bytes or a
/// cached Python object reference.
pub(crate) fn context_memo_states_to_pydict<'py>(
    py: Python<'py>,
    entries: &[(Fingerprint, Vec<PyStoredValue>)],
) -> PyResult<Bound<'py, PyDict>> {
    let dict = PyDict::new(py);
    for (fp, values) in entries {
        let values_list = PyList::new(py, values.iter().map(|v| Py::new(py, v.clone()).unwrap()))?;
        let fp_obj = Py::new(py, PyFingerprint(*fp))?;
        dict.set_item(fp_obj, values_list)?;
    }
    Ok(dict)
}

/// Convert the eager initial memo states into a Python `dict`
/// `{Fingerprint: list[Any]}` β€” each inner value is the *raw* Python object
/// that was originally stored, not a `StoredValue` wrapper.
///
/// Used by the cache-miss path to populate `guard.resolve(..., context_memo_states=...)`
/// which wraps the raw Python objects into `PyStoredValue` for storage. The
/// intermediate `PyStoredValue` instances that the registry holds are
/// transparently unwrapped here so the downstream path doesn't double-wrap
/// (which would leave the outer wrapper's `object` field pointing at a
/// Python `StoredValue` that msgspec can't serialize).
///
/// # Invariant
///
/// Every value stored in the registry was constructed via
/// `PyStoredValue::new(raw_py_obj)` inside `PyEnvironment::register_context_initial_states`,
/// which sets `object: Some(..)`. Nothing downstream ever calls `from_bytes`
/// on these values (which is the only way to construct a bytes-only
/// `PyStoredValue`), and `to_bytes` merely *caches* bytes alongside the
/// existing object reference β€” it never clears `object`. Therefore
/// `object_ref()` always returns `Some` here.
pub(crate) fn context_initial_states_to_pydict<'py>(
    py: Python<'py>,
    entries: &[(Fingerprint, Vec<PyStoredValue>)],
) -> PyResult<Bound<'py, PyDict>> {
    let dict = PyDict::new(py);
    for (fp, values) in entries {
        let unwrapped: Vec<Py<PyAny>> = values
            .iter()
            .map(|v| match v.object_ref(py) {
                Some(obj) => obj,
                None => unreachable!(
                    "context_initial_states registry holds a PyStoredValue \
                     with no Python object reference β€” see invariant in \
                     context_initial_states_to_pydict doc comment"
                ),
            })
            .collect();
        let values_list = PyList::new(py, unwrapped)?;
        let fp_obj = Py::new(py, PyFingerprint(*fp))?;
        dict.set_item(fp_obj, values_list)?;
    }
    Ok(dict)
}

/// Python-facing guard for a function-call memo entry.
///
/// Always holds a write lock on the underlying memo entry. On cache hits,
/// `cached_value`, `cached_memo_states`, and `cached_context_memo_states` are
/// pre-extracted owned copies. Call `resolve()` after (re-)execution, or
/// `close()` / drop to release.
#[pyclass(name = "FnCallMemoGuard")]
pub struct PyFnCallMemoGuard {
    guard: Option<FnCallMemoGuard<PyEngineProfile>>,
    is_cached: bool,
    cached_value: Option<Py<PyAny>>,
    cached_memo_states: Option<Py<PyAny>>, // Python list
    cached_context_memo_states: Option<Py<PyAny>>, // Python dict[Fingerprint, list]
    cached_data_deps: Option<Py<PyAny>>,   // Python list of 5-tuples, see `data_deps_to_pylist`
}

#[pymethods]
impl PyFnCallMemoGuard {
    /// Whether this guard represents a cache hit (true) or miss (false).
    ///
    /// When true, `cached_value`, `cached_memo_states`, and
    /// `cached_context_memo_states` hold the stored results. Note: `cached_value`
    /// itself may be Python `None` (e.g. for functions returning `None`), so use
    /// `is_cached` rather than `cached_value is not None` to distinguish cache
    /// hits from misses.
    #[getter]
    pub fn is_cached(&self) -> bool {
        self.is_cached
    }

    #[getter]
    pub fn cached_value(&self, py: Python<'_>) -> Option<Py<PyAny>> {
        self.cached_value.as_ref().map(|v| v.clone_ref(py))
    }

    #[getter]
    pub fn cached_memo_states(&self, py: Python<'_>) -> Option<Py<PyAny>> {
        self.cached_memo_states.as_ref().map(|s| s.clone_ref(py))
    }

    #[getter]
    pub fn cached_context_memo_states(&self, py: Python<'_>) -> Option<Py<PyAny>> {
        self.cached_context_memo_states
            .as_ref()
            .map(|s| s.clone_ref(py))
    }

    /// The stored data dependencies on a cache hit, as
    /// `list[tuple[Fingerprint, Fingerprint, StoredValue, StoredValue]]`.
    #[getter]
    pub fn cached_data_deps(&self, py: Python<'_>) -> Option<Py<PyAny>> {
        self.cached_data_deps.as_ref().map(|s| s.clone_ref(py))
    }

    /// Update memo states on a cache hit without re-execution.
    ///
    /// Used when the state function says `can_reuse=True` but the state value has changed.
    #[pyo3(signature = (memo_states=None, context_memo_states=None, data_deps=None))]
    pub fn update_memo_states(
        &mut self,
        py: Python<'_>,
        memo_states: Option<Vec<Py<PyAny>>>,
        context_memo_states: Option<HashMap<PyFingerprint, Vec<Py<PyAny>>>>,
        data_deps: Option<Vec<PyRefreshedDataDep>>,
    ) -> PyResult<()> {
        let payload = build_memo_states_payload(py, memo_states, context_memo_states, data_deps)?;
        if let Some(ref mut guard) = self.guard {
            guard.update_memo_states(payload);
        }
        Ok(())
    }

    #[pyo3(signature = (fn_ctx, ret, memo_states=None, context_memo_states=None))]
    pub fn resolve(
        &mut self,
        py: Python<'_>,
        fn_ctx: &PyFnCallContext,
        ret: Py<PyAny>,
        memo_states: Option<Vec<Py<PyAny>>>,
        context_memo_states: Option<HashMap<PyFingerprint, Vec<Py<PyAny>>>>,
    ) -> PyResult<bool> {
        // Data dependencies of a miss come from the frame, never from here.
        let payload = build_memo_states_payload(py, memo_states, context_memo_states, None)?;
        let resolved = if let Some(guard) = self.guard.take() {
            guard
                .resolve(&fn_ctx.0, || PyStoredValue::new(ret), payload)
                .into_py_result()?
        } else {
            false
        };
        Ok(resolved)
    }

    /// On a cache hit, merge the stored entry's target-provider generation deps
    /// into the calling context. Call exactly when the cached value is used
    /// (next to `join_child_memo`) β€” see the core method for the rationale.
    pub fn join_cached_target_provider_deps(&self, parent_fn_ctx: &PyFnCallContext) {
        if let Some(guard) = &self.guard {
            guard.join_cached_target_provider_deps(&parent_fn_ctx.0);
        }
    }

    /// On a cache hit, re-offer the stored entry's logic deps through the
    /// callee's own frame (`fn_ctx`, the context created for this call). Call
    /// next to `join_cached_target_provider_deps` β€” see the core method.
    pub fn join_cached_logic_deps(&self, fn_ctx: &PyFnCallContext) {
        if let Some(guard) = &self.guard {
            guard.join_cached_logic_deps(&fn_ctx.0);
        }
    }

    /// On a cache hit, re-offer the stored entry's data dependencies through
    /// the callee's own frame. Call after `update_memo_states`, next to
    /// `join_cached_logic_deps` β€” see the core method.
    pub fn join_cached_data_deps(&self, fn_ctx: &PyFnCallContext) {
        if let Some(guard) = &self.guard {
            guard.join_cached_data_deps(&fn_ctx.0);
        }
    }

    /// Release the underlying Rust write lock without resolving the memo entry.
    ///
    /// Users should call this in a `finally` block if they don't end up calling `resolve(...)`.
    pub fn close(&mut self) {
        self.guard = None;
    }
}

async fn reserve_memoization_inner(
    comp_ctx: PyComponentProcessorContext,
    memo_fp: PyFingerprint,
) -> Result<Py<PyAny>> {
    let guard =
        cocoindex_core::engine::function::reserve_memoization(&comp_ctx.0, memo_fp.0).await?;

    Python::attach(|py| {
        // Extract cached data (if cache hit) as PyStoredValue objects (not inner Python objects).
        let (
            is_cached,
            cached_value,
            cached_memo_states,
            cached_context_memo_states,
            cached_data_deps,
        ) = match guard.cached() {
            Some(cached) => {
                let value = Py::new(py, cached.ret.clone())?.into_any();
                let states_list = PyList::new(
                    py,
                    cached
                        .memo_states
                        .iter()
                        .map(|s| Py::new(py, s.clone()).unwrap()),
                )?;
                let context_dict = context_memo_states_to_pydict(py, cached.context_memo_states)?;
                let data_deps = data_deps_to_pylist(py, cached.data_deps)?;
                (
                    true,
                    Some(value),
                    Some(states_list.unbind().into_any()),
                    Some(context_dict.unbind().into_any()),
                    Some(data_deps.unbind().into_any()),
                )
            }
            None => (false, None, None, None, None),
        };

        let py_guard = PyFnCallMemoGuard {
            guard: Some(guard),
            is_cached,
            cached_value,
            cached_memo_states,
            cached_context_memo_states,
            cached_data_deps,
        };

        Ok(Py::new(py, py_guard)?.into_any())
    })
}

#[pyfunction]
pub fn reserve_memoization(
    py: Python<'_>,
    comp_ctx: PyComponentProcessorContext,
    memo_fp: PyFingerprint,
) -> PyResult<Py<PyAny>> {
    py.detach(|| {
        get_runtime()
            .block_on(async move { reserve_memoization_inner(comp_ctx, memo_fp).await })
            .into_py_result()
    })
}

#[pyfunction]
pub fn reserve_memoization_async<'py>(
    py: Python<'py>,
    comp_ctx: PyComponentProcessorContext,
    memo_fp: PyFingerprint,
) -> PyResult<Bound<'py, PyAny>> {
    future_into_py(py, async move {
        reserve_memoization_inner(comp_ctx, memo_fp)
            .await
            .into_py_result()
    })
}