clm-kernel 0.0.6

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
//! Layer 0: Enriched Function PCard Deserialization & Zero-Allocation Parser
//! Canonical Path: kernel/clm_rust_core/src/layer0/function_pcard_enriched.rs
//! Governed by: EPIC-CRD Sprint CRD-01 (DoD-CRD-01-06)

use serde::{Deserialize, Serialize};

fn default_true() -> bool {
    true
}

fn default_cleanup_policy() -> String {
    "lifo_unwind".to_string()
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CoeffectAccessMode {
    ReadOnly,
    ReadWrite,
    Execute,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RequiredService {
    pub service_name: String,
    pub interface: String,
    pub access_mode: CoeffectAccessMode,
    #[serde(default)]
    pub optional: bool,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CoeffectsRecord {
    #[serde(default)]
    pub required_services: Vec<RequiredService>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FiberExecutionMode {
    SynchronousAtomic,
    AsynchronousStream,
    AsynchronousBatch,
    CooperativeTurn,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FiberContextIsolation {
    None,
    Shared,
    IsolatedScratchpad,
    IsolatedWorkspace,
    IsolatedProcess,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FiberSpec {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub context_isolation: Option<FiberContextIsolation>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub execution_mode: Option<FiberExecutionMode>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub memory_quota_bytes: Option<u64>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SavepointGuardContract {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_rollback_timeout_us: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_rollback_latency_us: Option<u32>,
    #[serde(default = "default_true")]
    pub lifo_disposers: bool,
    #[serde(default = "default_cleanup_policy")]
    pub cleanup_policy: String,
}

impl SavepointGuardContract {
    pub fn effective_timeout_us(&self) -> Option<u32> {
        self.max_rollback_timeout_us.or(self.max_rollback_latency_us)
    }

    pub fn validate_bound(&self) -> Result<(), &'static str> {
        match self.effective_timeout_us() {
            Some(t) if t <= 1000 => Ok(()),
            Some(_) => Err("SavepointGuard timeout exceeds 1000µs bound"),
            None => Err("SavepointGuard requires max_rollback_timeout_us or max_rollback_latency_us"),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FacesRecord {
    pub r#abstract: String,
    pub concrete: String,
    pub balanced: String,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DependencyEdge {
    pub target_function_id: String,
    pub target_pcard_ref: String,
    pub kind: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub source: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub confidence: Option<f64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub observed_at: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct EnrichedPCard {
    pub function_id: String,
    pub domain: String,
    pub operation: String,
    pub pcard_ref: String,
    pub faces: FacesRecord,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub dependencies: Option<Vec<DependencyEdge>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub coeffects: Option<CoeffectsRecord>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub fiber_spec: Option<FiberSpec>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub savepoint_guard: Option<SavepointGuardContract>,
}

pub fn parse_enriched_pcard(json_str: &str) -> Result<EnrichedPCard, serde_json::Error> {
    serde_json::from_str(json_str)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_enriched_pcard_deserialization() {
        let minimal_json = r#"{
            "function_id": "urn:mcard:codec/canonical-json",
            "domain": "codec",
            "operation": "canonical-json",
            "pcard_ref": "blake3:1111111111111111111111111111111111111111111111111111111111111111",
            "faces": {
                "abstract": "blake3:2222222222222222222222222222222222222222222222222222222222222222",
                "concrete": "blake3:3333333333333333333333333333333333333333333333333333333333333333",
                "balanced": "blake3:4444444444444444444444444444444444444444444444444444444444444444"
            }
        }"#;

        let pcard = parse_enriched_pcard(minimal_json).expect("Minimal PCard must deserialize cleanly");
        assert_eq!(pcard.function_id, "urn:mcard:codec/canonical-json");
        // Zero allocation overhead: optional fields are None
        assert!(pcard.coeffects.is_none());
        assert!(pcard.fiber_spec.is_none());
        assert!(pcard.savepoint_guard.is_none());

        let enriched_json = r#"{
            "function_id": "urn:mcard:storage/create-record",
            "domain": "storage",
            "operation": "create-record",
            "pcard_ref": "blake3:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
            "faces": {
                "abstract": "blake3:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
                "concrete": "blake3:cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc",
                "balanced": "blake3:dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd"
            },
            "coeffects": {
                "required_services": [
                    {
                        "service_name": "sqlite_pool",
                        "interface": "clm.layer0.storage.ISQLitePool",
                        "access_mode": "read_write"
                    },
                    {
                        "service_name": "crypto_hasher",
                        "interface": "clm.layer0.hash.IHasher",
                        "access_mode": "execute"
                    }
                ]
            },
            "fiber_spec": {
                "context_isolation": "isolated_workspace",
                "execution_mode": "synchronous_atomic",
                "memory_quota_bytes": 1048576
            },
            "savepoint_guard": {
                "max_rollback_timeout_us": 500,
                "lifo_disposers": true,
                "cleanup_policy": "lifo_unwind"
            }
        }"#;

        let enriched = parse_enriched_pcard(enriched_json).expect("Enriched PCard must deserialize");
        let coeffects = enriched.coeffects.expect("Must have coeffects");
        assert_eq!(coeffects.required_services.len(), 2);
        assert_eq!(coeffects.required_services[0].service_name, "sqlite_pool");
        assert_eq!(coeffects.required_services[0].access_mode, CoeffectAccessMode::ReadWrite);

        let fiber_spec = enriched.fiber_spec.expect("Must have fiber_spec");
        assert_eq!(fiber_spec.context_isolation, Some(FiberContextIsolation::IsolatedWorkspace));
        assert_eq!(fiber_spec.execution_mode, Some(FiberExecutionMode::SynchronousAtomic));
        assert_eq!(fiber_spec.memory_quota_bytes, Some(1048576));

        let sp_guard = enriched.savepoint_guard.expect("Must have savepoint_guard");
        assert_eq!(sp_guard.max_rollback_timeout_us, Some(500));
        assert!(sp_guard.lifo_disposers);
        assert!(sp_guard.validate_bound().is_ok());

        // Verify bound rejection on invalid timeout
        let invalid_guard = SavepointGuardContract {
            max_rollback_timeout_us: Some(5000),
            max_rollback_latency_us: None,
            lifo_disposers: true,
            cleanup_policy: "lifo_unwind".to_string(),
        };
        assert!(invalid_guard.validate_bound().is_err());
    }
}