clm-kernel 0.0.18

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
//! Hoare Fiber State Machine & Deterministic Rollback (Sprint 192).
//!
//! Enforces:
//! 1. Formal Hoare Triples {P} S {Q} across Fiber lifecycles.
//! 2. Preconditions {P} verified in LOADING state before state mutation.
//! 3. Postconditions {Q} verified in ACTIVE state after mutation.
//! 4. Deterministic LIFO rollback (<1ms) via SavepointGuard and DisposableList.
//! 5. Bail Verdict integration with Cordis EventBus DispatchMode::Bail.

use super::context::{Context, Fiber, FiberState};
use crate::domain::{BailVerdict, BooleanPCard};
#[cfg(any(feature = "native", feature = "db"))]
use crate::domain::InvariantPhase;
#[cfg(any(feature = "native", feature = "db"))]
use crate::error::{ClmError, EvaluatorErrorCode, Result};
use serde_json::Value;
use std::sync::Arc;
#[cfg(any(feature = "native", feature = "db"))]
use std::time::Instant;

#[cfg(any(feature = "native", feature = "db"))]
use super::savepoint_guard::SavepointGuard;
#[cfg(any(feature = "native", feature = "db"))]
use rusqlite::Connection;
#[cfg(any(feature = "native", feature = "db"))]
use std::sync::Mutex;

pub type PreconditionFn = Arc<dyn Fn(&Context) -> BailVerdict + Send + Sync + 'static>;
pub type TransitionFn = Arc<dyn Fn(&Context, &Fiber) -> std::result::Result<Value, String> + Send + Sync + 'static>;
pub type PostconditionFn = Arc<dyn Fn(&Context, &Value) -> BailVerdict + Send + Sync + 'static>;

/// Formal specification of a state transition as a Hoare Triple {P} S {Q}.
#[derive(Clone)]
pub struct HoareTriple {
    pub name: String,
    pub precondition: Option<PreconditionFn>,
    pub transition: TransitionFn,
    pub postcondition: Option<PostconditionFn>,
    pub boolean_pcard: Option<BooleanPCard>,
}

impl HoareTriple {
    /// Constructs a new HoareTriple with transition logic.
    pub fn new<F>(name: impl Into<String>, transition: F) -> Self
    where
        F: Fn(&Context, &Fiber) -> std::result::Result<Value, String> + Send + Sync + 'static,
    {
        Self {
            name: name.into(),
            precondition: None,
            transition: Arc::new(transition),
            postcondition: None,
            boolean_pcard: None,
        }
    }

    /// Attaches a precondition predicate {P}.
    pub fn with_precondition<P>(mut self, pred: P) -> Self
    where
        P: Fn(&Context) -> BailVerdict + Send + Sync + 'static,
    {
        self.precondition = Some(Arc::new(pred));
        self
    }

    /// Attaches a postcondition predicate {Q}.
    pub fn with_postcondition<Q>(mut self, post: Q) -> Self
    where
        Q: Fn(&Context, &Value) -> BailVerdict + Send + Sync + 'static,
    {
        self.postcondition = Some(Arc::new(post));
        self
    }

    /// Binds a formal BooleanPCard invariant to this triple.
    pub fn with_boolean_pcard(mut self, pcard: BooleanPCard) -> Self {
        self.boolean_pcard = Some(pcard);
        self
    }
}

/// Execution telemetry report measuring rollback timing and determinism.
#[derive(Debug, Clone)]
pub struct HoareExecutionReport {
    pub fiber_id: String,
    pub success: bool,
    pub rollback_triggered: bool,
    pub rollback_duration_nanos: u128,
    pub final_state: FiberState,
    pub value: Option<Value>,
}

/// High-performance Hoare Fiber Executor enforcing invariants and zero-residual rollbacks.
pub struct HoareFiberExecutor;

impl HoareFiberExecutor {
    /// Executes a transition under formal Hoare contract verification with deterministic rollback.
    #[cfg(any(feature = "native", feature = "db"))]
    pub fn execute(
        context: &Context,
        fiber: &Fiber,
        triple: &HoareTriple,
        conn: Option<Arc<Mutex<Connection>>>,
    ) -> Result<HoareExecutionReport> {
        // 1. Transition to LOADING state
        {
            let mut state = fiber.state.lock().unwrap();
            *state = FiberState::Loading;
        }

        // 2. Evaluate Precondition {P}
        if let Some(ref pre) = triple.precondition {
            match pre(context) {
                BailVerdict::Pass => {}
                BailVerdict::Bail {
                    reason,
                    invariant_code,
                    ..
                } => {
                    let mut state = fiber.state.lock().unwrap();
                    *state = FiberState::Failed(format!("Precondition [{}] bail: {}", invariant_code, reason));
                    return Err(ClmError::evaluator(
                        EvaluatorErrorCode::PreconditionFailed,
                        format!("{}: {}", invariant_code, reason),
                    ));
                }
            }
        }

        // Also check BooleanPCard if marked as Precondition
        if let Some(ref pcard) = triple.boolean_pcard
            && pcard.phase == InvariantPhase::Precondition {
                // In full implementation this evaluates CEL; default passes unless empty
                if pcard.expression.is_empty() {
                    return Err(ClmError::evaluator(
                        EvaluatorErrorCode::PreconditionFailed,
                        "Empty CEL expression in BooleanPCard".to_string(),
                    ));
                }
            }

        // 3. Establish Transactional Savepoint Guard (if connection provided)
        let savepoint: Option<SavepointGuard> = if let Some(ref c) = conn {
            Some(
                SavepointGuard::new(c.clone(), format!("hoare_{}", fiber.id))
                    .map_err(|e| ClmError::evaluator(EvaluatorErrorCode::FiberFailure, e))?,
            )
        } else {
            None
        };

        // 4. Transition to ACTIVE state
        {
            let mut state = fiber.state.lock().unwrap();
            *state = FiberState::Active;
        }

        // 5. Execute State Transition S
        let exec_result = (triple.transition)(context, fiber);

        match exec_result {
            Err(transition_err) => {
                // Rollback phase
                let rollback_start = Instant::now();
                let _ = fiber.unwind_disposables();
                if let Some(mut sp) = savepoint {
                    let _ = sp.rollback();
                }
                let rollback_duration_nanos = rollback_start.elapsed().as_nanos();

                {
                    let mut state = fiber.state.lock().unwrap();
                    *state = FiberState::Failed(transition_err.clone());
                }

                Ok(HoareExecutionReport {
                    fiber_id: fiber.id.clone(),
                    success: false,
                    rollback_triggered: true,
                    rollback_duration_nanos,
                    final_state: FiberState::Failed(transition_err.clone()),
                    value: None,
                })
            }
            Ok(output_val) => {
                // 6. Evaluate Postcondition {Q}
                let mut post_failed = None;
                if let Some(ref post) = triple.postcondition
                    && let BailVerdict::Bail {
                        reason,
                        invariant_code,
                        ..
                    } = post(context, &output_val)
                    {
                        post_failed = Some((reason, invariant_code));
                    }

                if let Some((reason, invariant_code)) = post_failed {
                    // Postcondition failed: execute immediate LIFO rollback
                    let _rollback_start = Instant::now();
                    let _ = fiber.unwind_disposables();
                    if let Some(mut sp) = savepoint {
                        let _ = sp.rollback();
                    }
                    let _rollback_duration_nanos = _rollback_start.elapsed().as_nanos();

                    let fail_msg = format!("Postcondition [{}] bail: {}", invariant_code, reason);
                    {
                        let mut state = fiber.state.lock().unwrap();
                        *state = FiberState::Failed(fail_msg.clone());
                    }

                    return Err(ClmError::evaluator(
                        EvaluatorErrorCode::PostconditionFailed,
                        format!("{}: {}", invariant_code, reason),
                    ));
                }

                // 7. Success: Commit savepoint
                if let Some(mut sp) = savepoint {
                    let _ = sp.commit();
                }

                let final_state = {
                    fiber.state.lock().unwrap().clone()
                };

                Ok(HoareExecutionReport {
                    fiber_id: fiber.id.clone(),
                    success: true,
                    rollback_triggered: false,
                    rollback_duration_nanos: 0,
                    final_state,
                    value: Some(output_val),
                })
            }
        }
    }
}