clm-kernel 0.0.14

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
//! DisposableList — Reversible side-effect stack for Cordis Fibers.
//!
//! Implements strict Last-In, First-Out (LIFO) unwinding of side-effect closures,
//! guaranteeing zero residual state, zero leaked sockets/memory, and transactional
//! rollback upon fiber disposal or failure.

use std::fmt;

pub type DisposerFn = Box<dyn FnOnce() -> Result<(), String> + Send>;

/// Stack of reversible side effects belonging to an active Fiber.
pub struct DisposableList {
    disposers: Vec<DisposerFn>,
}

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

impl fmt::Debug for DisposableList {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("DisposableList")
            .field("pending_count", &self.disposers.len())
            .finish()
    }
}

impl DisposableList {
    /// Creates a new, empty `DisposableList`.
    pub fn new() -> Self {
        Self {
            disposers: Vec::new(),
        }
    }

    /// Registers a reversible cleanup closure onto the stack.
    /// Closures are executed in exact reverse order (LIFO) upon `dispose()`.
    pub fn push<F>(&mut self, cleanup: F)
    where
        F: FnOnce() -> Result<(), String> + Send + 'static,
    {
        self.disposers.push(Box::new(cleanup));
    }

    /// Alias for `push` matching the Cordis `register` convention.
    pub fn register<F>(&mut self, cleanup: F)
    where
        F: FnOnce() -> Result<(), String> + Send + 'static,
    {
        self.push(cleanup);
    }

    /// Returns the number of registered disposers awaiting execution.
    pub fn len(&self) -> usize {
        self.disposers.len()
    }

    /// Returns `true` if there are no registered disposers.
    pub fn is_empty(&self) -> bool {
        self.disposers.is_empty()
    }

    /// Unwinds all registered disposers in strict LIFO order.
    /// If any disposer returns an error, the unwinding continues for all remaining
    /// disposers to prevent partial leaks, and errors are aggregated.
    pub fn dispose(mut self) -> Result<(), Vec<String>> {
        let mut errors = Vec::new();
        while let Some(disposer) = self.disposers.pop() {
            if let Err(e) = disposer() {
                errors.push(e);
            }
        }
        if errors.is_empty() {
            Ok(())
        } else {
            Err(errors)
        }
    }
}

pub use super::savepoint_guard::{SavepointGuard, SavepointState};
#[cfg(any(feature = "native", feature = "db"))]
pub use super::savepoint_guard::TriDbSavepointGuard;

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::{Arc, Mutex};

    #[test]
    #[cfg(any(feature = "native", feature = "db"))]
    fn test_savepoint_guard_commit_and_rollback() {
        let conn = rusqlite::Connection::open_in_memory().unwrap();
        conn.execute("CREATE TABLE test (id INT, val TEXT);", []).unwrap();
        let arc_conn = Arc::new(Mutex::new(conn));

        // 1. Test commit
        {
            let mut sp = SavepointGuard::new(arc_conn.clone(), "sp1").unwrap();
            arc_conn.lock().unwrap().execute("INSERT INTO test VALUES (1, 'committed');", []).unwrap();
            sp.commit().unwrap();
        }
        let count: i64 = arc_conn.lock().unwrap().query_row("SELECT count(*) FROM test WHERE id=1;", [], |r| r.get(0)).unwrap();
        assert_eq!(count, 1);

        // 2. Test rollback on drop
        {
            let _sp = SavepointGuard::new(arc_conn.clone(), "sp2").unwrap();
            arc_conn.lock().unwrap().execute("INSERT INTO test VALUES (2, 'aborted');", []).unwrap();
            // drop without commit
        }
        let count2: i64 = arc_conn.lock().unwrap().query_row("SELECT count(*) FROM test WHERE id=2;", [], |r| r.get(0)).unwrap();
        assert_eq!(count2, 0);
    }

    #[test]
    #[cfg(any(feature = "native", feature = "db"))]
    fn test_savepoint_guard_submillisecond_rollback_benchmark() {
        let conn = rusqlite::Connection::open_in_memory().unwrap();
        conn.execute("CREATE TABLE card (hash TEXT PRIMARY KEY, content BLOB NOT NULL, g_time TEXT NOT NULL);", []).unwrap();
        conn.execute("CREATE TABLE handle_registry (handle TEXT PRIMARY KEY, current_hash TEXT NOT NULL, created_at TEXT, updated_at TEXT);", []).unwrap();
        let arc_conn = Arc::new(Mutex::new(conn));

        // Warm up connection and savepoint mechanism to prime SQLite statement caches and memory allocator
        for w in 0..5 {
            let mut sp = SavepointGuard::new(arc_conn.clone(), format!("sp_warmup_{}", w)).unwrap();
            let c = arc_conn.lock().unwrap();
            c.execute("INSERT INTO card (hash, content, g_time) VALUES (?1, ?2, datetime('now'))", rusqlite::params![format!("hash_warmup_{}", w), b"warmup_content"]).unwrap();
            drop(c);
            sp.rollback().unwrap();
        }

        let iterations = 100;
        let mut durations_micros = Vec::with_capacity(iterations);

        for i in 0..iterations {
            let sp_name = format!("sp_bench_{}", i);
            let mut sp = SavepointGuard::new(arc_conn.clone(), &sp_name).unwrap();

            // Insert dirty state into card and handle_registry
            {
                let c = arc_conn.lock().unwrap();
                c.execute("INSERT INTO card (hash, content, g_time) VALUES (?1, ?2, datetime('now'))", rusqlite::params![format!("hash_{}", i), b"test_content"]).unwrap();
                c.execute("INSERT INTO handle_registry (handle, current_hash, created_at, updated_at) VALUES (?1, ?2, datetime('now'), datetime('now'))", rusqlite::params![format!("mcard://bench/{}", i), format!("hash_{}", i)]).unwrap();
            }

            // Benchmark explicit rollback
            let t0 = std::time::Instant::now();
            sp.rollback().unwrap();
            let elapsed = t0.elapsed();
            durations_micros.push(elapsed.as_micros() as f64);

            // Assert zero dirty state
            let c = arc_conn.lock().unwrap();
            let card_count: i64 = c.query_row("SELECT count(*) FROM card", [], |r| r.get(0)).unwrap();
            let handle_count: i64 = c.query_row("SELECT count(*) FROM handle_registry", [], |r| r.get(0)).unwrap();
            assert_eq!(card_count, 0, "card table must be empty after rollback at iteration {}", i);
            assert_eq!(handle_count, 0, "handle_registry table must be empty after rollback at iteration {}", i);
        }

        durations_micros.sort_by(|a, b| a.partial_cmp(b).unwrap());
        // For N=100 samples (indices 0..99), the 99th percentile index is 98 (leaving the top 1% outlier at 99)
        let p99_idx = ((iterations - 1) as f64 * 0.99).round() as usize;
        let p99_micros = durations_micros[p99_idx];
        let p99_ms = p99_micros / 1000.0;
        eprintln!("[RUST BENCHMARK] SavepointGuard rollback 100 iterations: p99 = {:.3}ms ({:.1}µs)", p99_ms, p99_micros);
        assert!(p99_ms < 1.0, "Rust SavepointGuard p99 rollback must be < 1.0ms, got {:.3}ms", p99_ms);
    }

    #[test]
    fn test_strict_lifo_unwinding() {
        let execution_log = Arc::new(Mutex::new(Vec::<usize>::new()));
        let mut list = DisposableList::new();

        for i in 1..=4 {
            let log_clone = Arc::clone(&execution_log);
            list.push(move || {
                log_clone.lock().unwrap().push(i);
                Ok(())
            });
        }

        assert_eq!(list.len(), 4);
        assert!(list.dispose().is_ok());

        // Must unwind in reverse (LIFO): 4, 3, 2, 1
        let log = execution_log.lock().unwrap();
        assert_eq!(*log, vec![4, 3, 2, 1]);
    }

    #[test]
    fn test_unwind_continues_on_error() {
        let execution_log = Arc::new(Mutex::new(Vec::<usize>::new()));
        let mut list = DisposableList::new();

        let l1 = Arc::clone(&execution_log);
        list.push(move || {
            l1.lock().unwrap().push(1);
            Ok(())
        });

        let l2 = Arc::clone(&execution_log);
        list.push(move || {
            l2.lock().unwrap().push(2);
            Err("Failed closing resource 2".to_string())
        });

        let l3 = Arc::clone(&execution_log);
        list.push(move || {
            l3.lock().unwrap().push(3);
            Ok(())
        });

        let res = list.dispose();
        assert!(res.is_err());
        let errs = res.unwrap_err();
        assert_eq!(errs.len(), 1);
        assert_eq!(errs[0], "Failed closing resource 2");

        // All disposers must have been called despite the error in #2
        let log = execution_log.lock().unwrap();
        assert_eq!(*log, vec![3, 2, 1]);
    }
}