clm-kernel 0.0.7

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
//! In-Process Hot Module Replacement (HMR) Reloader (CRD-05).
//! Canonical Path: kernel/clm_rust_core/src/fiber/hmr_reloader.rs
//!
//! Implements:
//! - DoD-CRD-05-01: Detects handle updates and triggers epoch migration without process restart
//! - DoD-CRD-05-02: Epoch-k fiber Active -> Unloading -> Disposed (LIFO unwind);
//!   Epoch-(k+1) fiber Pending -> Loading -> Active
//! - DoD-CRD-05-03: Long-running conversational session state preserved across HMR upgrades
//! - DoD-CRD-05-04: Bitemporal fiber execution logging (g_time transaction time + valid time)
//! - DoD-CRD-05-06: Pre-verification gating with automatic rollback to epoch k on failure
//! - DoD-CRD-05-07: Function-binding rebinding hot-swap in Rust

use super::context::{Fiber, FiberState};
use chrono::Utc;
use dashmap::DashMap;
use serde_json::Value;
use std::sync::{Arc, Mutex};
use std::time::Instant;

pub type DynamicFunctionBinding = Arc<
    dyn Fn(&Value, &DashMap<String, String>) -> Result<Value, String> + Send + Sync + 'static,
>;

pub type PreVerificationCheck = Arc<
    dyn Fn(&DashMap<String, String>) -> bool + Send + Sync + 'static,
>;

#[derive(Debug, Clone)]
pub struct BitemporalExecutionRecord {
    pub handle: String,
    pub epoch: u64,
    pub transaction_time: String, // g_time
    pub valid_time: String,       // execution time
    pub input: Value,
    pub output: Value,
    pub fiber_id: String,
}

#[derive(Debug, Clone)]
pub struct HmrMigrationReport {
    pub handle: String,
    pub previous_epoch: u64,
    pub new_epoch: u64,
    pub migration_latency_ms: f64,
    pub session_preserved: bool,
    pub success: bool,
    pub rollback_occurred: bool,
    pub failure_reason: Option<String>,
}

pub struct RegisteredBinding {
    pub handle: String,
    pub epoch: u64,
    pub fiber: Arc<Fiber>,
    pub binding: DynamicFunctionBinding,
    pub g_time: String,
}

pub struct HmrReloader {
    bindings: DashMap<String, RegisteredBinding>,
    session_store: Arc<DashMap<String, String>>,
    execution_log: Mutex<Vec<BitemporalExecutionRecord>>,
}

impl Default for HmrReloader {
    fn default() -> Self {
        Self::new()
    }
}

impl HmrReloader {
    pub fn new() -> Self {
        Self {
            bindings: DashMap::new(),
            session_store: Arc::new(DashMap::new()),
            execution_log: Mutex::new(Vec::new()),
        }
    }

    pub fn set_session_var(&self, key: impl Into<String>, value: impl Into<String>) {
        self.session_store.insert(key.into(), value.into());
    }

    pub fn get_session_var(&self, key: &str) -> Option<String> {
        self.session_store.get(key).map(|v| v.value().clone())
    }

    pub fn get_epoch(&self, handle: &str) -> Option<u64> {
        self.bindings.get(handle).map(|b| b.epoch)
    }

    pub fn get_execution_log(&self) -> Vec<BitemporalExecutionRecord> {
        self.execution_log.lock().unwrap().clone()
    }

    /// Registers a new function binding at epoch 1.
    pub fn register<F>(
        &self,
        handle: impl Into<String>,
        binding: F,
        g_time: Option<String>,
    ) -> Result<u64, String>
    where
        F: Fn(&Value, &DashMap<String, String>) -> Result<Value, String> + Send + Sync + 'static,
    {
        let handle_str = handle.into();
        let epoch = 1;
        let fiber = Arc::new(Fiber::new(format!("{}:epoch_{}", handle_str, epoch), vec![]));
        fiber.transition_to(FiberState::Active)?;

        let registered = RegisteredBinding {
            handle: handle_str.clone(),
            epoch,
            fiber,
            binding: Arc::new(binding),
            g_time: g_time.unwrap_or_else(|| Utc::now().to_rfc3339()),
        };

        self.bindings.insert(handle_str, registered);
        Ok(epoch)
    }

    /// Executes the active function binding for the given handle.
    pub fn execute(&self, handle: &str, input: &Value) -> Result<Value, String> {
        let binding_entry = self
            .bindings
            .get(handle)
            .ok_or_else(|| format!("HmrReloader: handle '{}' not registered", handle))?;

        if binding_entry.fiber.get_state() != FiberState::Active {
            return Err(format!(
                "HmrReloader: fiber for '{}' is not Active ({:?})",
                handle,
                binding_entry.fiber.get_state()
            ));
        }

        let valid_time = Utc::now().to_rfc3339();
        let output = (binding_entry.binding)(input, &self.session_store)?;

        let record = BitemporalExecutionRecord {
            handle: handle.to_string(),
            epoch: binding_entry.epoch,
            transaction_time: binding_entry.g_time.clone(),
            valid_time,
            input: input.clone(),
            output: output.clone(),
            fiber_id: binding_entry.fiber.id.clone(),
        };

        self.execution_log.lock().unwrap().push(record);
        Ok(output)
    }

    /// Atomic Hot Module Replacement.
    /// Unwinds epoch k disposables, creates epoch k+1 fiber, and updates binding.
    pub fn migrate_epoch<F>(
        &self,
        handle: &str,
        new_binding: F,
        g_time: Option<String>,
        pre_check: Option<PreVerificationCheck>,
    ) -> Result<HmrMigrationReport, String>
    where
        F: Fn(&Value, &DashMap<String, String>) -> Result<Value, String> + Send + Sync + 'static,
    {
        let current_binding = self
            .bindings
            .get(handle)
            .ok_or_else(|| format!("HmrReloader: handle '{}' not registered", handle))?;

        let t0 = Instant::now();
        let prev_epoch = current_binding.epoch;
        let next_epoch = prev_epoch + 1;
        let g_time_str = g_time.unwrap_or_else(|| Utc::now().to_rfc3339());

        // 1. Evaluate pre-verification check (V_pre)
        if let Some(ref check) = pre_check
            && !check(&self.session_store) {
                let elapsed_ms = t0.elapsed().as_secs_f64() * 1000.0;
                return Ok(HmrMigrationReport {
                    handle: handle.to_string(),
                    previous_epoch: prev_epoch,
                    new_epoch: prev_epoch,
                    migration_latency_ms: elapsed_ms,
                    session_preserved: true,
                    success: false,
                    rollback_occurred: true,
                    failure_reason: Some(format!("Pre-verification V_pre failed for epoch {}", next_epoch)),
                });
            }

        // 2. Epoch-k fiber Active -> Unloading -> Disposed
        current_binding.fiber.transition_to(FiberState::Unloading)?;
        let _ = current_binding.fiber.unwind_disposables();
        current_binding.fiber.transition_to(FiberState::Disposed)?;

        // Drop read lock before insertion to prevent DashMap deadlock
        drop(current_binding);

        // 3. Epoch-(k+1) fiber Pending -> Loading -> Active
        let next_fiber = Arc::new(Fiber::new(format!("{}:epoch_{}", handle, next_epoch), vec![]));
        next_fiber.transition_to(FiberState::Loading)?;
        next_fiber.transition_to(FiberState::Active)?;

        // 4. Update binding in memory
        let updated = RegisteredBinding {
            handle: handle.to_string(),
            epoch: next_epoch,
            fiber: next_fiber,
            binding: Arc::new(new_binding),
            g_time: g_time_str,
        };
        self.bindings.insert(handle.to_string(), updated);

        let elapsed_ms = t0.elapsed().as_secs_f64() * 1000.0;
        Ok(HmrMigrationReport {
            handle: handle.to_string(),
            previous_epoch: prev_epoch,
            new_epoch: next_epoch,
            migration_latency_ms: elapsed_ms,
            session_preserved: true,
            success: true,
            rollback_occurred: false,
            failure_reason: None,
        })
    }
}