clm-kernel 0.0.24

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
use std::collections::HashMap;
use super::types::{AssertionsYaml, PetriNetYaml, hash_string};
use super::invariants::{check_assertions, render_assertion_results};

fn event_count(run_id: &str, event_type: &str, clm_root: &str) -> i64 {
    if let Some(log_path) = crate::cross_cutting::context::CLMContext::get_scoped_or_env(
        crate::layer0::vocabulary_env::ENV_CLM_EVENT_LOG_PATH,
    ) {
        let p = std::path::Path::new(&log_path);
        if p.exists() {
            if let Ok(content) = std::fs::read_to_string(p) {
                let target = format!("\"event\":\"{}\"", event_type);
                let target_space = format!("\"event\": \"{}\"", event_type);
                return content
                    .lines()
                    .filter(|line| line.contains(&target) || line.contains(&target_space))
                    .count() as i64;
            }
        }
    }

    let handle = format!("run:{}:event:{}", run_id, event_type);
    if let Ok(conn) = crate::db::get_reader_connection(
        crate::layer0::vocabulary_env::PILLAR_EXECUTION_LOG,
        clm_root,
    ) {
        let n: i64 = conn
            .query_row(
                "SELECT (SELECT COUNT(*) FROM handle_registry WHERE handle = ?1) + \
                        (SELECT COUNT(*) FROM handle_history WHERE handle = ?1)",
                rusqlite::params![handle],
                |row| row.get(0),
            )
            .unwrap_or(0);
        if n > 0 {
            return n;
        }

        let any_run_events: i64 = conn
            .query_row(
                "SELECT COUNT(*) FROM handle_registry WHERE handle LIKE ?1",
                rusqlite::params![format!("run:{}:event:%", run_id)],
                |row| row.get(0),
            )
            .unwrap_or(0);
        if any_run_events > 0 {
            return 0;
        }
    }

    match crate::db::resolve_handle_content(
        crate::layer0::vocabulary_env::PILLAR_EXECUTION_LOG,
        clm_root,
        &format!("run:{}:events", run_id),
    ) {
        Ok(Some(content)) => content
            .lines()
            .filter(|line| {
                line.contains(&format!("\"event\":\"{}\"", event_type))
                    || line.contains(&format!("\"event\": \"{}\"", event_type))
            })
            .count() as i64,
        _ => 0,
    }
}

/// Read persisted/logged event counts and evaluate + format net assertions.
pub fn check_net_assertions(
    assertions: &AssertionsYaml,
    run_id: &str,
    clm_root: &str,
    fire_count: i64,
    deadlocked: bool,
    place_markings: &HashMap<String, i64>,
) -> (String, i64, i64) {
    let mut observed_events = HashMap::new();
    for key in assertions.event_counts.keys() {
        observed_events.insert(key.clone(), event_count(run_id, key, clm_root));
    }
    let results = check_assertions(assertions, &observed_events, fire_count, deadlocked, place_markings);
    render_assertion_results(&results)
}

pub fn evaluate_engine_assertions(
    net: &PetriNetYaml,
    run_id: &str,
    clm_root: &str,
    fire_count: i64,
    deadlocked: bool,
    place_markings: &HashMap<String, i64>,
    is_kenotic: bool,
    sponsor_did: &str,
    mut out_buf: String,
) -> Result<String, String> {
    let mut assert_pass = 0;
    let mut assert_fail = 0;
    if let Some(assertions) = &net.assertions {
        let (buf, pass, fail) = check_net_assertions(
            assertions,
            run_id,
            clm_root,
            fire_count,
            deadlocked,
            place_markings,
        );
        out_buf.push_str(&buf);
        assert_pass = pass;
        assert_fail = fail;
    }

    if is_kenotic {
        let final_status = if assert_fail == 0 { "completed" } else { "failed" };
        let final_err_msg = if assert_fail > 0 {
            format!("{} assertion(s) failed", assert_fail)
        } else {
            String::new()
        };

        let mut final_marking_hash = String::new();
        if let Ok(Some(hash)) = crate::db::resolve_handle_hash(
            crate::layer0::vocabulary_env::PILLAR_EXECUTION_LOG,
            clm_root,
            &format!("run:{}:marking", run_id),
        ) {
            final_marking_hash = hash;
        }
        let now = crate::utils::now_iso8601();
        let status_json = if final_status == "completed" {
            serde_json::json!({
                "@type": "RunStatus",
                "status": "completed",
                "final_marking_hash": final_marking_hash,
                "sponsor_did": sponsor_did,
                "completed_at": now
            })
            .to_string()
        } else {
            serde_json::json!({
                "@type": "RunStatus",
                "status": "failed",
                "error": final_err_msg,
                "last_marking_hash": final_marking_hash,
                "sponsor_did": sponsor_did,
                "failed_at": now
            })
            .to_string()
        };

        let status_hash = hash_string(&status_json);
        crate::db::handle_register_batch(
            crate::layer0::vocabulary_env::PILLAR_EXECUTION_LOG,
            clm_root,
            &format!("run:{}:status", run_id),
            &status_hash,
            &status_json,
        )
        .map_err(|e| e.to_string())?;
    }

    let mut final_marking_map = serde_json::Map::new();
    for (pid, tok) in place_markings {
        final_marking_map.insert(pid.clone(), serde_json::Value::Number((*tok).into()));
    }
    out_buf.push_str(&format!("  [FINAL_MARKING] {}\n", serde_json::Value::Object(final_marking_map)));

    out_buf.push_str(&format!(
        "  → {} passed, {} failed ({} firings)\n",
        assert_pass, assert_fail, fire_count
    ));

    if assert_fail > 0 {
        Err(out_buf)
    } else {
        Ok(out_buf)
    }
}