clm-kernel 0.0.24

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
use super::*;

    #[test]
    fn test_cached_statement_queries() {
        let mut conn = Connection::open_in_memory().unwrap();
        migrations::apply_migrations(&mut conn, "content_memory").unwrap();

        // Insert card via cached statement
        let mut stmt = conn
            .prepare_cached("INSERT OR IGNORE INTO card (hash, content, g_time) VALUES (?1, ?2, ?3)")
            .unwrap();
        stmt.execute(rusqlite::params![&crate::hash::raw_hash_string("test_content_1"), "test_content_1", crate::fs_utils::compute_g_time()])
            .unwrap();

        // Retrieve card via helper function using prepared cache
        let content = get_card_cached(&conn, &crate::hash::raw_hash_string("test_content_1")).unwrap();
        assert_eq!(content, Some("test_content_1".to_string()));

        let exists = card_exists_cached(&conn, &crate::hash::raw_hash_string("test_content_1")).unwrap();
        assert!(exists);

        let not_exists = card_exists_cached(&conn, "nonexistent").unwrap();
        assert!(!not_exists);

        // Insert handle registry
        let now = crate::utils::now_iso8601();
        let mut stmt_h = conn
            // ORC-23/27: three columns. `created_at` is the first history row, not a column —
            // so the fixture writes a history row rather than a column that does not exist.
            .prepare_cached("INSERT OR IGNORE INTO handle_registry (handle, current_hash, updated_at) VALUES (?1, ?2, ?3)")
            .unwrap();
        stmt_h.execute(params!["test_handle_1", &crate::hash::raw_hash_string("test_content_1"), &now]).unwrap();
        conn.prepare_cached(
            "INSERT INTO handle_history (handle, previous_hash, changed_at) VALUES (?1, ?2, ?3)",
        )
        .unwrap()
        .execute(params!["test_handle_1", &crate::hash::raw_hash_string("test_content_1"), &now])
        .unwrap();

        let resolved_hash = resolve_handle_hash_cached(&conn, "test_handle_1").unwrap();
        assert_eq!(resolved_hash, Some(crate::hash::raw_hash_string("test_content_1")));

        let resolved_content = resolve_handle_content_cached(&conn, "test_handle_1").unwrap();
        assert_eq!(resolved_content, Some("test_content_1".to_string()));
    }

    #[cfg(any(feature = "native", feature = "db"))]
    #[test]
    fn test_concurrent_readers_in_pool() {
        let temp_dir = tempfile::tempdir().unwrap();
        let clm_root = temp_dir.path().to_str().unwrap();
        let pool = DbPillarPool::new("content_memory", clm_root).unwrap();

        // Pre-populate with 50 cards using the writer
        {
            let writer_arc = pool.writer();
            let mut conn = writer_arc.lock().unwrap();
            let tx = conn.transaction().unwrap();
            for i in 0..50 {
                let hash = crate::hash::raw_hash_string(&format!("content_{:04}", i));
                let content = format!("content_{:04}", i);
                let mut stmt = tx
                    .prepare_cached("INSERT INTO card (hash, content, g_time) VALUES (?1, ?2, ?3)")
                    .unwrap();
                stmt.execute(rusqlite::params![hash, content, crate::fs_utils::compute_g_time()])
                    .unwrap();
            }
            tx.commit().unwrap();
        }

        // Spawn 16 concurrent reader threads querying simultaneously
        let mut handles = Vec::new();
        for thread_idx in 0..16 {
            let pool_clone = pool.clone();
            let h = std::thread::spawn(move || {
                let reader = pool_clone.reader().expect("Acquiring reader connection should succeed");
                for j in 0..50 {
                    let card_idx = (thread_idx * 7 + j) % 50;
                    let target_hash = crate::hash::raw_hash_string(&format!("content_{:04}", card_idx));
                    let expected_content = format!("content_{:04}", card_idx);

                    let content = get_card_cached(&reader, &target_hash)
                        .expect("Read query should not fail");
                    assert_eq!(content, Some(expected_content));
                }
            });
            handles.push(h);
        }

        for h in handles {
            h.join().expect("Reader thread should complete without panicking");
        }
    }

    #[tokio::test]
    async fn test_query_db_async_isolation() {
        let temp_dir = tempfile::tempdir().unwrap();
        let clm_root = temp_dir.path().to_str().unwrap();
        let pool = DbPillarPool::new("content_memory", clm_root).unwrap();

        // Write via writer connection
        let pool_writer = pool.clone();
        query_db_async(move || {
            let writer_arc = pool_writer.writer();
            let mut conn = writer_arc.lock().unwrap();
            let tx = conn.transaction()?;
            {
                let mut stmt = tx.prepare_cached("INSERT OR REPLACE INTO card (hash, content, g_time) VALUES (?1, ?2, ?3)")?;
                stmt.execute(rusqlite::params![&crate::hash::raw_hash_string("async_content"), "async_content", crate::fs_utils::compute_g_time()])?;
            }
            tx.commit()?;
            Ok(())
        })
        .await
        .unwrap();

        // Read concurrently via query_db_async
        let pool_reader = pool.clone();
        let res = query_db_async(move || {
            let reader = pool_reader.reader()?;
            let content = get_card_cached(&reader, &crate::hash::raw_hash_string("async_content"))?;
            Ok(content)
        })
        .await
        .unwrap();

        assert_eq!(res, Some("async_content".to_string()));
    }