multicast-codemode-local 2.0.0

Local QuickJS executor for multicast Code Mode
Documentation
//! Process-kill probes at the durable composition protocol boundaries.
#![cfg(all(feature = "quickjs", feature = "sqlite"))]
use async_trait::async_trait;
use multicast_codemode::{
    CallRecovery, CodeMode, Connector, ConnectorDescription, ConnectorTool, ExecutionCheckpoint,
    ExecutionState, ExecutionStatus, RuntimeStore, Snippet, ToolAnnotations, ToolContext,
    ToolPolicy,
};
use multicast_codemode_local::{DurableStore, LocalExecutor};
use serde_json::{Value, json};
use std::{
    path::PathBuf,
    sync::{
        Arc,
        atomic::{AtomicBool, Ordering},
    },
    time::{Duration, Instant},
};

struct FaultStore {
    inner: DurableStore,
    directory: PathBuf,
    phase: String,
    tripped: AtomicBool,
}
impl FaultStore {
    async fn stop(&self, phase: &str) {
        if self.phase == phase && !self.tripped.swap(true, Ordering::SeqCst) {
            std::fs::write(self.directory.join("ready"), phase).unwrap();
            std::future::pending::<()>().await;
        }
    }
}
#[async_trait]
impl RuntimeStore for FaultStore {
    async fn workflow_identity(&self) -> Result<String, String> {
        self.inner.workflow_identity().await
    }
    async fn get_workflows(&self) -> Result<Option<Value>, String> {
        self.inner.get_workflows().await
    }
    async fn put_workflows(&self, v: &Value) -> Result<(), String> {
        self.inner.put_workflows(v).await?;
        let nodes = v["nodes"].as_object().unwrap();
        if nodes
            .values()
            .any(|n| n["parent"].is_string() && n["bound"] == false)
        {
            self.stop("reservation").await;
        }
        if nodes
            .values()
            .any(|n| n["parent"].is_string() && n["bound"] == true)
        {
            self.stop("binding").await;
        }
        if v["publications"].get("persisted").is_some() {
            self.stop("publication").await;
        }
        if v["scopes"]
            .as_object()
            .unwrap()
            .values()
            .any(|s| s["closed"] == true)
        {
            self.stop("scope-close").await;
        }
        Ok(())
    }
    async fn get_checkpoint(&self, id: &str) -> Result<Option<ExecutionCheckpoint>, String> {
        self.inner.get_checkpoint(id).await
    }
    async fn put_checkpoint(&self, id: &str, c: &ExecutionCheckpoint) -> Result<(), String> {
        self.inner.put_checkpoint(id, c).await
    }
    async fn get_execution(&self, id: &str) -> Result<Option<ExecutionState>, String> {
        self.inner.get_execution(id).await
    }
    async fn put_execution(&self, s: &ExecutionState) -> Result<(), String> {
        self.inner.put_execution(s).await?;
        if s.id.starts_with("child_") {
            if s.status == ExecutionStatus::Running {
                self.stop("preparation").await;
            }
            if s.status == ExecutionStatus::Completed {
                self.stop("child-completion").await;
            }
        }
        Ok(())
    }
    async fn list_executions(&self) -> Result<Vec<ExecutionState>, String> {
        self.inner.list_executions().await
    }
    async fn delete_execution(&self, id: &str) -> Result<(), String> {
        RuntimeStore::delete_execution(&self.inner, id).await
    }
    async fn get_snippet(&self, n: &str) -> Result<Option<Snippet>, String> {
        self.inner.get_snippet(n).await
    }
    async fn put_snippet(&self, s: &Snippet) -> Result<(), String> {
        self.inner.put_snippet(s).await
    }
    async fn list_snippets(&self) -> Result<Vec<Snippet>, String> {
        self.inner.list_snippets().await
    }
    async fn delete_snippet(&self, n: &str) -> Result<bool, String> {
        self.inner.delete_snippet(n).await
    }
}
struct Effect {
    directory: PathBuf,
    crash: bool,
}
#[async_trait]
impl Connector for Effect {
    fn name(&self) -> &str {
        "effect"
    }
    async fn describe(&self) -> Result<ConnectorDescription, String> {
        Ok(ConnectorDescription {
            name: "effect".into(),
            instructions: None,
            tools: vec![ConnectorTool {
                name: "write".into(),
                description: None,
                input_schema: json!({"type":"object"}),
                output_schema: None,
                instructions: None,
                examples: vec![],
                annotations: ToolAnnotations::default(),
                policy: ToolPolicy::default(),
            }],
        })
    }
    async fn execute(&self, _: &str, args: Value, context: &ToolContext) -> Result<Value, String> {
        use std::io::Write;
        let key = &context.call.as_ref().unwrap().idempotency_key;
        let mut receipts = std::fs::OpenOptions::new()
            .create(true)
            .append(true)
            .open(self.directory.join("effects"))
            .unwrap();
        writeln!(receipts, "{key}").unwrap();
        receipts.sync_all().unwrap();
        std::fs::write(
            self.directory.join("applied"),
            serde_json::to_vec(&args["value"]).unwrap(),
        )
        .unwrap();
        if self.crash {
            std::fs::write(self.directory.join("ready"), "effect").unwrap();
            std::future::pending::<()>().await;
        }
        Ok(args["value"].clone())
    }
    async fn recover(&self, _: &str, _: &Value, _: &ToolContext) -> Result<CallRecovery, String> {
        match std::fs::read(self.directory.join("applied")) {
            Ok(bytes) => Ok(CallRecovery::Applied(
                serde_json::from_slice(&bytes).unwrap(),
            )),
            Err(_) => Ok(CallRecovery::Uncertain),
        }
    }
}
#[tokio::test]
async fn crash_worker_entry() {
    let Ok(directory) = std::env::var("MULTICAST_FLUENCY_CRASH_DIRECTORY") else {
        return;
    };
    let directory = PathBuf::from(directory);
    let phase = std::env::var("MULTICAST_FLUENCY_CRASH_PHASE").unwrap();
    let store = Arc::new(FaultStore {
        inner: DurableStore::open(directory.join("store.sqlite")).unwrap(),
        directory: directory.clone(),
        phase: phase.clone(),
        tripped: AtomicBool::new(false),
    });
    let runtime = CodeMode::new(
        store,
        LocalExecutor::default(),
        vec![Arc::new(Effect {
            directory: directory.clone(),
            crash: phase == "effect",
        })],
    );
    let root=runtime.start(r#"async () => {const w=codemode.workflows;return await w.scope(async s=>{
        const f=await s.define('async value=>effect.write({value})',{input:{type:'integer'},output:{type:'integer'}});
        const run=await s.start(f,42);const value=await run.result();await s.publish(f,'persisted');return value;
    });}"#).await.unwrap();
    std::fs::write(directory.join("root"), &root.id).unwrap();
    runtime
        .drive_with(&root.id, Default::default())
        .await
        .unwrap();
    panic!("fault boundary was not reached");
}
#[tokio::test]
async fn kills_at_every_durable_boundary_reuse_the_child_and_effect_receipt() {
    for phase in [
        "reservation",
        "preparation",
        "binding",
        "effect",
        "child-completion",
        "publication",
        "scope-close",
    ] {
        let dir = tempfile::tempdir().unwrap();
        let mut process = std::process::Command::new(std::env::current_exe().unwrap())
            .args(["--exact", "crash_worker_entry", "--nocapture"])
            .env("MULTICAST_FLUENCY_CRASH_DIRECTORY", dir.path())
            .env("MULTICAST_FLUENCY_CRASH_PHASE", phase)
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::piped())
            .spawn()
            .unwrap();
        let end = Instant::now() + Duration::from_secs(15);
        while !dir.path().join("ready").exists() {
            if Instant::now() >= end {
                let _ = process.kill();
                let output = process.wait_with_output().unwrap();
                panic!(
                    "fault {phase} was not reached: {}",
                    String::from_utf8_lossy(&output.stderr)
                );
            }
            assert!(
                process.try_wait().unwrap().is_none(),
                "fault child exited before {phase}"
            );
            tokio::time::sleep(Duration::from_millis(10)).await;
        }
        assert_eq!(
            std::fs::read_to_string(dir.path().join("ready")).unwrap(),
            phase
        );
        process.kill().unwrap();
        process.wait().unwrap();
        let root = std::fs::read_to_string(dir.path().join("root")).unwrap();
        let store = Arc::new(DurableStore::open(dir.path().join("store.sqlite")).unwrap());
        let before = store.get_workflows().await.unwrap().unwrap();
        let child = before["nodes"]
            .as_object()
            .unwrap()
            .iter()
            .find(|(_, n)| n["parent"] == root)
            .map(|(id, _)| id.clone());
        assert!(
            child.is_some() || phase == "publication" || phase == "scope-close",
            "reservation absent at {phase}"
        );
        let runtime = CodeMode::new(
            store.clone(),
            LocalExecutor::default(),
            vec![Arc::new(Effect {
                directory: dir.path().into(),
                crash: false,
            })],
        );
        tokio::time::timeout(
            Duration::from_secs(10),
            runtime.drive_if_idle(&root, Default::default()),
        )
        .await
        .expect("recovery stalled")
        .unwrap();
        let result = runtime.execution(&root).await.unwrap();
        assert_eq!(
            result.status,
            ExecutionStatus::Completed,
            "{phase}: {:?}",
            result.error
        );
        assert_eq!(result.result, Some(json!(42)), "{phase}");
        let children: Vec<_> = store
            .list_executions()
            .await
            .unwrap()
            .into_iter()
            .filter(|s| s.id.starts_with("child_"))
            .collect();
        assert_eq!(children.len(), 1, "replacement child at {phase}");
        if let Some(id) = child {
            assert_eq!(children[0].id, id, "{phase}");
        }
        assert_eq!(
            std::fs::read_to_string(dir.path().join("effects"))
                .unwrap()
                .lines()
                .count(),
            1,
            "effect repeated at {phase}"
        );
        let after = store.get_workflows().await.unwrap().unwrap();
        assert!(
            after["scopes"]
                .as_object()
                .unwrap()
                .values()
                .all(|s| s["closed"] == true),
            "{phase}"
        );
        assert!(after["owners"].as_object().unwrap().is_empty(), "{phase}");
        assert_eq!(
            after["publications"].as_object().unwrap().len(),
            1,
            "{phase}"
        );
        assert_eq!(
            after["definitions"].as_object().unwrap().len(),
            1,
            "{phase}"
        );
    }
}