clm-kernel 0.0.0

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

/// Incidence matrix components for a Petri net.
///
/// Contains the input (D⁻), output (D⁺), and combined (D = D⁺ − D⁻) matrices,
/// plus index mappings from place/transition IDs to matrix row/column indices.
pub struct IncidenceMatrix {
    pub d: Vec<Vec<i64>>,
    pub place_to_idx: HashMap<String, usize>,
    pub trans_to_idx: HashMap<String, usize>,
    pub place_count: usize,
    pub trans_count: usize,
}

/// Build the incidence matrix D = D⁺ − D⁻ from the Petri net topology.
///
/// Each row represents a place, each column a transition.
/// D[p][t] = (tokens added to p by firing t) − (tokens removed from p by firing t).
pub fn build_incidence_matrix(net: &PetriNetYaml) -> IncidenceMatrix {
    let place_count = net.places.len();
    let trans_count = net.transitions.len();

    let mut place_to_idx = HashMap::new();
    for (i, p) in net.places.iter().enumerate() {
        place_to_idx.insert(p.id.clone(), i);
    }
    let mut trans_to_idx = HashMap::new();
    for (j, t) in net.transitions.iter().enumerate() {
        trans_to_idx.insert(t.id.clone(), j);
    }

    let mut d_minus = vec![vec![0i64; trans_count]; place_count];
    let mut d_plus = vec![vec![0i64; trans_count]; place_count];
    for (j, t) in net.transitions.iter().enumerate() {
        for inp in &t.inputs {
            if let Some(&pidx) = place_to_idx.get(inp) {
                d_minus[pidx][j] += 1;
            }
        }
        for outp in &t.outputs {
            if let Some(&pidx) = place_to_idx.get(outp) {
                d_plus[pidx][j] += 1;
            }
        }
    }

    let mut d = vec![vec![0i64; trans_count]; place_count];
    for r in 0..place_count {
        for c in 0..trans_count {
            d[r][c] = d_plus[r][c] - d_minus[r][c];
        }
    }

    IncidenceMatrix {
        d,
        place_to_idx,
        trans_to_idx,
        place_count,
        trans_count,
    }
}

/// Computed Noetherian invariants for a Petri net execution.
pub struct ComputedInvariants {
    /// P-invariant weight vectors (one per invariant, indexed by place).
    pub p_invariants: Vec<Vec<i64>>,
    /// Expected constant for each P-invariant: x^T · M₀.
    pub p_constants: Vec<i64>,
    /// T-invariant firing count vectors (one per invariant, indexed by transition).
    pub t_invariants: Vec<Vec<i64>>,
}

/// Compute or load P-invariants and T-invariants for the Petri net.
///
/// If the topology declares explicit invariants in `assertions.noetherian_invariants`,
/// those are used. Otherwise, invariants are computed from the nullspace of D.
pub fn compute_invariants(
    net: &PetriNetYaml,
    matrix: &IncidenceMatrix,
    place_ids: &[String],
    place_markings: &HashMap<String, i64>,
) -> ComputedInvariants {
    let mut p_invariants = Vec::new();
    let mut p_constants = Vec::new();

    let has_declared_p = net.assertions.as_ref()
        .and_then(|a| a.noetherian_invariants.as_ref())
        .map_or(false, |n| !n.p_invariants.is_empty());

    if has_declared_p {
        if let Some(noether) = net.assertions.as_ref()
            .and_then(|a| a.noetherian_invariants.as_ref())
        {
            for pinv in &noether.p_invariants {
                let mut weights_vec = vec![0i64; matrix.place_count];
                for (pid, &w) in &pinv.weights {
                    if let Some(&pidx) = matrix.place_to_idx.get(pid) {
                        weights_vec[pidx] = w;
                    }
                }
                p_invariants.push(weights_vec);
                p_constants.push(pinv.expected_constant);
            }
        }
    } else {
        let basis = crate::cpn::solver::solve_nullspace(
            &matrix.d, matrix.place_count, matrix.trans_count, true,
        );
        for basis_vector in basis {
            let mut init_sum = 0;
            for (p_idx, &weight) in basis_vector.iter().enumerate() {
                let pid = &place_ids[p_idx];
                let tokens = place_markings.get(pid).cloned().unwrap_or(0);
                init_sum += weight * tokens;
            }
            p_invariants.push(basis_vector);
            p_constants.push(init_sum);
        }
    }

    let mut t_invariants = Vec::new();
    let has_declared_t = net.assertions.as_ref()
        .and_then(|a| a.noetherian_invariants.as_ref())
        .map_or(false, |n| !n.t_invariants.is_empty());

    if has_declared_t {
        if let Some(noether) = net.assertions.as_ref()
            .and_then(|a| a.noetherian_invariants.as_ref())
        {
            for tinv in &noether.t_invariants {
                let mut firings_vec = vec![0i64; matrix.trans_count];
                for (tid, &f) in &tinv.firing_counts {
                    if let Some(&tidx) = matrix.trans_to_idx.get(tid) {
                        firings_vec[tidx] = f;
                    }
                }
                t_invariants.push(firings_vec);
            }
        }
    } else {
        let basis = crate::cpn::solver::solve_nullspace(
            &matrix.d, matrix.place_count, matrix.trans_count, false,
        );
        for basis_vector in basis {
            t_invariants.push(basis_vector);
        }
    }

    ComputedInvariants {
        p_invariants,
        p_constants,
        t_invariants,
    }
}

/// Verify T-invariant idempotency: D · σ = 0 and no state drift.
///
/// Returns additional output for `out_buf`, or an error if T-invariant violation detected.
pub fn verify_t_invariant_idempotency(
    d: &[Vec<i64>],
    cumulative_fires: &[i64],
    _fire_count: i64,
    place_count: usize,
    trans_count: usize,
    net: &PetriNetYaml,
    place_markings: &HashMap<String, i64>,
) -> Result<String, String> {
    let mut buf = String::new();

    let mut is_t_invariant = true;
    for r in 0..place_count {
        let mut sum = 0;
        for c in 0..trans_count {
            sum += d[r][c] * cumulative_fires[c];
        }
        if sum != 0 {
            is_t_invariant = false;
            break;
        }
    }

    let total_fires: i64 = cumulative_fires.iter().sum();
    if is_t_invariant && total_fires > 0 {
        buf.push_str(&format!(
            "  🔍 Firing sequence is a proven T-invariant cycle ({} total fires)\n",
            total_fires
        ));

        let mut mismatch = false;
        for p in &net.places {
            let final_tok = place_markings.get(&p.id).cloned().unwrap_or(0);
            if final_tok != p.initial_tokens {
                buf.push_str("  ❌ [NOETHER_ERR] T-Invariant Idempotency Violation (State Drift)!\n");
                buf.push_str(&format!("    Place:           {}\n", p.id));
                buf.push_str(&format!("    Initial Tokens:  {}\n", p.initial_tokens));
                buf.push_str(&format!("    Final Tokens:    {}\n", final_tok));
                mismatch = true;
            }
        }

        if mismatch {
            return Err(buf);
        } else {
            buf.push_str("  ✅ Temporal idempotency proven (zero state drift)\n");
        }
    }

    Ok(buf)
}

/// Check topology-level assertions (event_counts, deadlock, final_marking, fire_count).
///
/// Returns `(output_text, pass_count, fail_count)`.
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 buf = String::new();
    let mut pass = 0i64;
    let mut fail = 0i64;

    // Resolve events content
    let mut events_content = String::new();
    let events_handle = format!("run:{}:events", run_id);
    if let Ok(Some(content)) =
        crate::db::resolve_handle_content("execution_log", clm_root, &events_handle)
    {
        events_content = content;
    }

    for (key, &expected) in &assertions.event_counts {
        let mut actual = 0;
        for line in events_content.lines() {
            if line.contains(&format!("\"event\":\"{}\"", key)) {
                actual += 1;
            }
        }
        if actual == expected {
            buf.push_str(&format!("  ✅ {}: {} (expected {})\n", key, actual, expected));
            pass += 1;
        } else {
            buf.push_str(&format!("  ❌ {}: {} (expected {})\n", key, actual, expected));
            fail += 1;
        }
    }

    if let Some(expected_deadlock) = assertions.deadlock {
        if expected_deadlock == deadlocked {
            buf.push_str(&format!(
                "  ✅ deadlock: {} (expected)\n",
                if deadlocked { "detected" } else { "none" }
            ));
            pass += 1;
        } else {
            buf.push_str(&format!(
                "  ❌ deadlock: {} (expected {})\n",
                deadlocked, expected_deadlock
            ));
            fail += 1;
        }
    }

    for (key, &expected) in &assertions.final_marking {
        let actual = place_markings.get(key).cloned().unwrap_or(0);
        if actual == expected {
            buf.push_str(&format!(
                "  ✅ marking[{}]: {} (expected {})\n",
                key, actual, expected
            ));
            pass += 1;
        } else {
            buf.push_str(&format!(
                "  ❌ marking[{}]: {} (expected {})\n",
                key, actual, expected
            ));
            fail += 1;
        }
    }

    if assertions.fire_count >= 0 {
        if fire_count == assertions.fire_count {
            buf.push_str(&format!(
                "  ✅ fire_count: {} (expected {})\n",
                fire_count, assertions.fire_count
            ));
            pass += 1;
        } else {
            buf.push_str(&format!(
                "  ❌ fire_count: {} (expected {})\n",
                fire_count, assertions.fire_count
            ));
            fail += 1;
        }
    }

    (buf, pass, fail)
}