clm-kernel 0.0.15

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
use crate::layer2::sync::codec::validate_transition_payload;
use crate::layer2::sync::types::{TransitionGateResult, TransitionPayload};
use std::collections::{BTreeMap, BTreeSet};

pub const LIFECYCLE_PLACES: &[&str] = &[
    "p_unborn",
    "p_active",
    "p_retired_tombstone",
    "p_conflict_quarantine",
];

pub const TRANSFER_PLACES: &[&str] = &["p_source", "p_in_flight", "p_target", "p_rejected"];

pub fn lifecycle_transitions() -> Vec<(&'static str, Vec<&'static str>, Vec<&'static str>)> {
    vec![
        ("t_create", vec!["p_unborn"], vec!["p_active"]),
        ("t_update", vec!["p_active"], vec!["p_active"]),
        ("t_seal", vec!["p_active"], vec!["p_active"]),
        ("t_rotate", vec!["p_active"], vec!["p_active"]),
        ("t_relocate_out", vec!["p_active"], vec!["p_retired_tombstone"]),
        ("t_relocate_in", vec!["p_unborn"], vec!["p_active"]),
        ("t_tombstone", vec!["p_active"], vec!["p_retired_tombstone"]),
        ("t_restore", vec!["p_retired_tombstone"], vec!["p_active"]),
        ("t_quarantine", vec!["p_active"], vec!["p_conflict_quarantine"]),
        ("t_resolve_conflict", vec!["p_conflict_quarantine"], vec!["p_active"]),
        ("t_branch_conflict", vec!["p_unborn"], vec!["p_conflict_quarantine"]),
        ("t_merge_conflict", vec!["p_conflict_quarantine"], vec!["p_active"]),
        ("t_retire_conflict", vec!["p_conflict_quarantine"], vec!["p_retired_tombstone"]),
        ("t_seed", vec!["p_unborn"], vec!["p_active"]),
        ("t_fork", vec!["p_active"], vec!["p_active"]),
        ("t_fork_in", vec!["p_unborn"], vec!["p_active"]),
        ("t_pin", vec!["p_active"], vec!["p_active"]),
        ("t_conflict_branch", vec!["p_active"], vec!["p_conflict_quarantine"]),
    ]
}

pub fn transfer_transitions() -> Vec<(&'static str, Vec<&'static str>, Vec<&'static str>)> {
    vec![
        ("t_enqueue_push", vec!["p_source"], vec!["p_in_flight"]),
        ("t_commit_push", vec!["p_in_flight"], vec!["p_target"]),
        ("t_reject", vec!["p_in_flight"], vec!["p_rejected"]),
        ("t_retry", vec!["p_in_flight"], vec!["p_in_flight"]),
        ("t_enqueue_pull", vec!["p_target"], vec!["p_in_flight"]),
        ("t_commit_pull", vec!["p_in_flight"], vec!["p_source"]),
        ("t_prepare_transfer", vec!["p_source"], vec!["p_in_flight"]),
        ("t_commit_transfer", vec!["p_in_flight"], vec!["p_target"]),
        ("t_reject_transfer", vec!["p_in_flight"], vec!["p_rejected"]),
        ("t_retry_transfer", vec!["p_rejected"], vec!["p_source"]),
        ("t_seed_transfer", vec!["p_source"], vec!["p_in_flight"]),
        ("t_fork_transfer", vec!["p_source"], vec!["p_in_flight"]),
        ("t_pin_transfer", vec!["p_target"], vec!["p_target"]),
        ("t_conflict_branch_transfer", vec!["p_in_flight"], vec!["p_rejected"]),
    ]
}

pub fn compute_marking_state_hash(marking: &BTreeMap<String, i64>) -> String {
    let entries: Vec<String> = marking.iter().map(|(k, v)| format!("\"{k}\":{v}")).collect();
    let json = format!("{{{}}}", entries.join(","));
    format!("blake3:{}", blake3::hash(json.as_bytes()).to_hex())
}

pub fn verify_p_invariant(
    places: &[&str],
    transitions: &[(&str, Vec<&str>, Vec<&str>)],
    weights: &[i64],
) -> bool {
    if places.len() != weights.len() {
        return false;
    }
    for (_, inputs, outputs) in transitions {
        let mut delta = 0i64;
        for inp in inputs {
            let Some(idx) = places.iter().position(|p| p == inp) else { return false };
            delta -= weights[idx];
        }
        for out in outputs {
            let Some(idx) = places.iter().position(|p| p == out) else { return false };
            delta += weights[idx];
        }
        if delta != 0 {
            return false;
        }
    }
    true
}

fn rejected_gate(marking: &BTreeMap<String, i64>, transition_id: &str, reason: String) -> TransitionGateResult {
    let pre_hash = compute_marking_state_hash(marking);
    TransitionGateResult {
        enabled: false,
        transition_id: transition_id.to_string(),
        pre_marking: marking.clone(),
        post_marking: marking.clone(),
        pre_state_hash: pre_hash.clone(),
        post_state_hash: pre_hash,
        error_code: Some("guard-rejected".to_string()),
        reason: Some(reason),
    }
}

pub fn evaluate_lifecycle_guard(
    marking: &BTreeMap<String, i64>,
    transition_id: &str,
    payload: Option<&TransitionPayload>,
) -> TransitionGateResult {
    let Some((_, inputs, outputs)) = lifecycle_transitions().into_iter().find(|(id, _, _)| *id == transition_id) else {
        return rejected_gate(marking, transition_id, format!("Unknown lifecycle transition: {transition_id}"));
    };
    if let Some(p) = payload {
        if let Err(err) = validate_transition_payload(p) {
            return rejected_gate(marking, transition_id, err);
        }
    }
    let mut next = marking.clone();
    for inp in inputs {
        let cur = *next.get(inp).unwrap_or(&0);
        if cur <= 0 {
            return rejected_gate(marking, transition_id, format!("Insufficient tokens in place {inp}"));
        }
        next.insert(inp.to_string(), cur - 1);
    }
    for out in outputs {
        *next.entry(out.to_string()).or_insert(0) += 1;
    }
    TransitionGateResult {
        enabled: true,
        transition_id: transition_id.to_string(),
        pre_marking: marking.clone(),
        post_marking: next.clone(),
        pre_state_hash: compute_marking_state_hash(marking),
        post_state_hash: compute_marking_state_hash(&next),
        error_code: None,
        reason: None,
    }
}

pub fn evaluate_transfer_guard(
    marking: &BTreeMap<String, i64>,
    transition_id: &str,
    fan_out_count: i64,
) -> TransitionGateResult {
    let Some((_, inputs, outputs)) = transfer_transitions().into_iter().find(|(id, _, _)| *id == transition_id) else {
        return rejected_gate(marking, transition_id, format!("Invalid transfer transition: {transition_id}"));
    };
    if fan_out_count <= 0 {
        return rejected_gate(marking, transition_id, "Invalid fanOutCount".to_string());
    }
    let mut next = marking.clone();
    for inp in inputs {
        let cur = *next.get(inp).unwrap_or(&0);
        if cur < fan_out_count {
            return rejected_gate(marking, transition_id, format!("Insufficient tokens in transfer place {inp}"));
        }
        next.insert(inp.to_string(), cur - fan_out_count);
    }
    for out in outputs {
        *next.entry(out.to_string()).or_insert(0) += fan_out_count;
    }
    TransitionGateResult {
        enabled: true,
        transition_id: transition_id.to_string(),
        pre_marking: marking.clone(),
        post_marking: next.clone(),
        pre_state_hash: compute_marking_state_hash(marking),
        post_state_hash: compute_marking_state_hash(&next),
        error_code: None,
        reason: None,
    }
}

pub fn resolve_concurrent_head_winner(
    local_ref: Option<&str>,
    remote_ref: Option<&str>,
    local_clock: &BTreeMap<String, u64>,
    remote_clock: &BTreeMap<String, u64>,
) -> (String, Option<String>, Option<String>, BTreeMap<String, u64>) {
    let keys: BTreeSet<&String> = local_clock.keys().chain(remote_clock.keys()).collect();
    let (mut gt, mut lt, mut merged) = (false, false, BTreeMap::new());
    for k in keys {
        let (v1, v2) = (*local_clock.get(k).unwrap_or(&0), *remote_clock.get(k).unwrap_or(&0));
        gt |= v1 > v2;
        lt |= v1 < v2;
        merged.insert(k.clone(), v1.max(v2));
    }
    if !gt && !lt {
        return ("equal".to_string(), local_ref.or(remote_ref).map(String::from), None, merged);
    }
    if gt && !lt {
        return ("after".to_string(), local_ref.map(String::from), remote_ref.map(String::from), merged);
    }
    if !gt && lt {
        return ("before".to_string(), remote_ref.map(String::from), local_ref.map(String::from), merged);
    }
    let remote_wins = remote_ref.unwrap_or("") > local_ref.unwrap_or("");
    let (w, l) = if remote_wins { (remote_ref, local_ref) } else { (local_ref, remote_ref) };
    ("concurrent".to_string(), w.map(String::from), l.map(String::from), merged)
}