clm-kernel 0.0.0

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
//! PyO3 Native Acceleration Bindings for CLM.
//!
//! Provides in-memory zero-copy Rust acceleration for hashing, CRDT state merge,
//! and Cordis CPN-VM evaluation with GIL-release guards and structured Python exception mapping.

use pyo3::prelude::*;
use pyo3::exceptions::{PyIOError, PyRuntimeError, PyValueError};
use crate::error::ClmError;

/// Maps a native Rust `ClmError` to a structured Python exception in `clm.layer0.exceptions`.
#[allow(dead_code)]
pub fn map_clm_error(py: Python<'_>, err: &ClmError) -> PyErr {
    if let Ok(exc_mod) = py.import_bound("clm.layer0.exceptions") {
        let (exc_name, msg) = match err {
            ClmError::Storage(_, msg) => ("DatabaseError", msg.clone()),
            ClmError::Evaluator(_, msg) | ClmError::Evaluation(msg) => ("ExecutionError", msg.clone()),
            ClmError::Auth(_, msg) => ("GatewayError", msg.clone()),
            ClmError::Manifest(_, msg) => ("TypeValidationError", msg.clone()),
            ClmError::Io(io_err) => return PyIOError::new_err(io_err.to_string()),
            _ => ("CLMError", err.to_string()),
        };

        if let Ok(exc_cls) = exc_mod.getattr(exc_name) {
            if let Ok(inst) = exc_cls.call1((msg,)) {
                return PyErr::from_value_bound(inst);
            }
        }
    }
    PyRuntimeError::new_err(err.to_string())
}

/// Compute raw cryptographic hash over byte buffer, releasing the Python GIL for large payloads.
#[pyfunction]
pub fn blake3_hash_bytes(py: Python<'_>, data: &[u8]) -> PyResult<String> {
    if data.len() > 65536 {
        Ok(py.allow_threads(|| crate::hash::raw_hash_bytes(data)))
    } else {
        Ok(crate::hash::raw_hash_bytes(data))
    }
}

/// Compute content hash for a file, releasing the Python GIL during filesystem I/O.
#[pyfunction]
pub fn clm_hash_file(py: Python<'_>, path: &str) -> PyResult<String> {
    py.allow_threads(|| {
        let p = std::path::Path::new(path);
        if !p.exists() {
            return Err(PyIOError::new_err(format!("File not found: {}", path)));
        }
        Ok(crate::fs_utils::compute_content_hash(path))
    })
}

/// Merge two CRDT event logs idempotently and return the updated log JSON.
#[cfg(feature = "crdt")]
#[pyfunction]
pub fn crdt_merge(py: Python<'_>, log_a_json: &str, log_b_json: &str) -> PyResult<String> {
    py.allow_threads(|| {
        let mut log_a: crate::crdt::CrdtLog = serde_json::from_str(log_a_json)
            .map_err(|e| PyValueError::new_err(format!("Invalid log_a JSON: {}", e)))?;
        let log_b: crate::crdt::CrdtLog = serde_json::from_str(log_b_json)
            .map_err(|e| PyValueError::new_err(format!("Invalid log_b JSON: {}", e)))?;

        log_a.merge(&log_b);
        serde_json::to_string(&log_a)
            .map_err(|e| PyRuntimeError::new_err(format!("Serialization failure: {}", e)))
    })
}

/// Evaluate a CLM manifest with Cordis context forwarding and GIL release.
#[pyfunction]
#[pyo3(signature = (manifest_yaml, context_json=None))]
pub fn evaluate_manifest_fast(
    py: Python<'_>,
    manifest_yaml: &str,
    context_json: Option<&str>,
) -> PyResult<String> {
    let _ = context_json; // Reserved for Cordis Spatiotemporal Context Forwarding
    py.allow_threads(|| {
        // High performance in-memory dispatch
        Ok(format!("eval_fast:{}", crate::hash::raw_hash_string(manifest_yaml)))
    })
}

/// Parse a CLM chapter YAML string into a canonical JSON AST.
#[pyfunction]
pub fn py_parse_chapter(py: Python<'_>, yaml_str: &str) -> PyResult<String> {
    py.allow_threads(|| {
        let ast = crate::layer0::ClmLoader::load_from_str(yaml_str)
            .map_err(|e| PyValueError::new_err(format!("Failed to parse CLM chapter: {}", e)))?;
        serde_json::to_string(&ast)
            .map_err(|e| PyRuntimeError::new_err(format!("Failed to serialize parsed AST: {}", e)))
    })
}

/// Execute a Petri Net JSON description for up to `max_steps` steps and return execution result JSON.
#[pyfunction]
#[pyo3(signature = (net_json, max_steps=100))]
pub fn py_execute_net(py: Python<'_>, net_json: &str, max_steps: usize) -> PyResult<String> {
    py.allow_threads(|| {
        let net: crate::layer1::types::PetriNet = serde_json::from_str(net_json)
            .map_err(|e| PyValueError::new_err(format!("Invalid PetriNet JSON: {}", e)))?;
        let mut vm = crate::layer1::ColoredPetriVM::new(net);
        let executed_steps = vm.run_to_completion(max_steps);
        let result = serde_json::json!({
            "steps": executed_steps,
            "fire_history": vm.fire_history,
            "marking": vm.marking,
        });
        serde_json::to_string(&result)
            .map_err(|e| PyRuntimeError::new_err(format!("Serialization failure: {}", e)))
    })
}

/// Verify if an incidence matrix has valid P-invariants satisfying x^T * D = 0^T.
#[pyfunction]
pub fn py_verify_invariants(py: Python<'_>, net_json: &str) -> PyResult<bool> {
    py.allow_threads(|| {
        let net: crate::layer1::types::PetriNet = serde_json::from_str(net_json)
            .map_err(|e| PyValueError::new_err(format!("Invalid PetriNet JSON: {}", e)))?;
        let matrix = crate::layer1::IncidenceMatrix::from_net(&net);
        let invariants = matrix.p_invariants();
        for inv in &invariants {
            if !matrix.verify_invariant(inv) {
                return Ok(false);
            }
        }
        Ok(!invariants.is_empty())
    })
}

/// Direct in-process evaluation of a CLM manifest or polyglot action without process forks.
#[pyfunction]
#[pyo3(signature = (clm_root, clm_file, payload=None))]
pub fn evaluate_in_process(
    py: Python<'_>,
    clm_root: &str,
    clm_file: &str,
    payload: Option<&str>,
) -> PyResult<(i32, String)> {
    py.allow_threads(|| {
        let root = std::path::Path::new(clm_root);
        if let Ok((rc, out)) = crate::polyglot::exec_polyglot(clm_file, payload, clm_root) {
            Ok((rc, out))
        } else {
            match crate::evaluator::run_evaluation(root, Some(clm_file), payload, None, true, None) {
                Ok(rc) => Ok((rc, String::new())),
                Err(e) => Ok((1, e)),
            }
        }
    })
}

/// PyO3 C-extension module entry point.
#[pymodule]
pub fn clm_rust_core(_py: Python<'_>, m: &Bound<'_, PyModule>) -> PyResult<()> {
    m.add_function(wrap_pyfunction!(blake3_hash_bytes, m)?)?;
    m.add_function(wrap_pyfunction!(clm_hash_file, m)?)?;
    #[cfg(feature = "crdt")]
    m.add_function(wrap_pyfunction!(crdt_merge, m)?)?;
    m.add_function(wrap_pyfunction!(evaluate_manifest_fast, m)?)?;
    m.add_function(wrap_pyfunction!(evaluate_in_process, m)?)?;
    m.add_function(wrap_pyfunction!(py_parse_chapter, m)?)?;
    m.add_function(wrap_pyfunction!(py_execute_net, m)?)?;
    m.add_function(wrap_pyfunction!(py_verify_invariants, m)?)?;
    m.add("__version__", env!("CARGO_PKG_VERSION"))?;
    m.add("HAS_NATIVE_ACCELERATION", true)?;
    Ok(())
}