clm-kernel 0.0.11

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.

#![allow(clippy::useless_conversion)]
#![allow(unsafe_op_in_unsafe_fn)]

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)
            && 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)),
            }
        }
    })
}

/// Native Rust TypeInterpreter judgment bridge.
#[pyfunction]
#[pyo3(signature = (data=None, filename=None, ext_hint=None))]
pub fn py_judge_type(
    py: Python<'_>,
    data: Option<&[u8]>,
    filename: Option<&str>,
    ext_hint: Option<&str>,
) -> PyResult<String> {
    py.allow_threads(|| {
        let interpreter = crate::type_interpreter::TypeInterpreter::create_default();
        let judgment = interpreter.judge(data, filename, ext_hint);
        serde_json::to_string(&judgment)
            .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("Serialization failure: {}", e)))
    })
}

/// Detect MIME type and extension using native Rust TypeInterpreter.
#[pyfunction]
#[pyo3(signature = (data, ext_hint=None))]
pub fn detect_content_type(
    py: Python<'_>,
    data: &[u8],
    ext_hint: Option<&str>,
) -> PyResult<(String, String)> {
    py.allow_threads(|| {
        let interpreter = crate::type_interpreter::TypeInterpreter::create_default();
        Ok(interpreter.detect_content_type(data, ext_hint))
    })
}

/// Check if byte content is binary using native Rust TypeInterpreter.
#[pyfunction]
pub fn is_binary_content(py: Python<'_>, data: &[u8]) -> PyResult<bool> {
    py.allow_threads(|| {
        let interpreter = crate::type_interpreter::TypeInterpreter::create_default();
        Ok(interpreter.is_binary_content(data))
    })
}

/// Native Rust TypedValue canonical JSON serialization and validation bridge.
#[pyfunction]
#[pyo3(signature = (mime, universe, data_json, schema_ref=None, metadata_json=None))]
pub fn py_typed_value_to_json(
    _py: Python<'_>,
    mime: &str,
    universe: &str,
    data_json: &str,
    schema_ref: Option<&str>,
    metadata_json: Option<&str>,
) -> PyResult<String> {
    let data: serde_json::Value = serde_json::from_str(data_json)
        .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("Invalid data JSON: {}", e)))?;

    let metadata: Option<std::collections::BTreeMap<String, serde_json::Value>> = match metadata_json {
        Some(s) => Some(serde_json::from_str(s).map_err(|e| {
            pyo3::exceptions::PyValueError::new_err(format!("Invalid metadata JSON: {}", e))
        })?),
        None => None,
    };

    let tv = crate::typed_value::TypedValue::new(
        mime,
        universe,
        data,
        schema_ref.map(|s| s.to_string()),
        metadata,
    )
    .map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))?;

    tv.to_json()
        .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))
}

/// 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_function(wrap_pyfunction!(py_judge_type, m)?)?;
    m.add_function(wrap_pyfunction!(detect_content_type, m)?)?;
    m.add_function(wrap_pyfunction!(is_binary_content, m)?)?;
    m.add_function(wrap_pyfunction!(py_typed_value_to_json, m)?)?;
    m.add("__version__", env!("CARGO_PKG_VERSION"))?;
    m.add("HAS_NATIVE_ACCELERATION", true)?;
    Ok(())
}