#![cfg(all(feature = "quickjs", feature = "sqlite"))]
use std::collections::BTreeMap;
use std::sync::{
Arc,
atomic::{AtomicU64, AtomicUsize, Ordering},
};
use std::time::Duration;
use multicast::cli::Cli;
use multicast::command::{
CommandContext, CommandDef, CommandHandler, McpAnnotations, McpCommandOptions,
};
use multicast::output::CommandResult;
use multicast::tool::ToolCallOptions;
use multicast_codemode::opentelemetry::{
Context, global,
trace::{TraceContextExt, Tracer, TracerProvider},
};
use multicast_codemode::{
Clock, CodeMode, CodeModeRunOptions, CodeModeService, ExecutionState, ExecutionStatus,
MulticastConnector, WorkflowIdentity,
};
use multicast_codemode_local::{DurableStore, LocalCodeModeService, LocalExecutor};
use opentelemetry_sdk::metrics::{
InMemoryMetricExporter, PeriodicReader, SdkMeterProvider,
data::{AggregatedMetrics, MetricData},
};
use opentelemetry_sdk::trace::{InMemorySpanExporter, SdkTracerProvider, SpanData};
use serde_json::json;
const SECRET: &str = "private-workflow-payload-92742";
struct TestClock(Arc<AtomicU64>);
impl Clock for TestClock {
fn now_ms(&self) -> u64 {
self.0.load(Ordering::SeqCst)
}
}
struct Save(Arc<AtomicUsize>);
#[async_trait::async_trait]
impl CommandHandler for Save {
async fn run(&self, _: CommandContext) -> CommandResult {
let span = Context::current().span().span_context().clone();
tokio::task::yield_now().await;
assert_eq!(*Context::current().span().span_context(), span);
assert!(span.is_valid());
self.0.fetch_add(1, Ordering::SeqCst);
CommandResult::Ok {
data: json!(SECRET),
cta: None,
exit_code: None,
}
}
}
struct Wait(Arc<AtomicUsize>);
#[async_trait::async_trait]
impl CommandHandler for Wait {
async fn run(&self, _: CommandContext) -> CommandResult {
self.0.fetch_add(1, Ordering::SeqCst);
std::future::pending().await
}
}
struct DisabledRun(LocalCodeModeService);
#[async_trait::async_trait]
impl CommandHandler for DisabledRun {
async fn run(&self, _: CommandContext) -> CommandResult {
let state = self
.0
.execute(
"return await fixture.save({});".into(),
CodeModeRunOptions::default(),
)
.await
.unwrap();
let paused = settle(&self.0, &state.id).await;
assert_eq!(paused.status, ExecutionStatus::Paused);
assert!(paused.trace.is_none());
self.0.reject(paused.id, 0).await.unwrap();
CommandResult::Ok {
data: json!(true),
cta: None,
exit_code: None,
}
}
}
async fn settle(service: &LocalCodeModeService, id: &str) -> ExecutionState {
tokio::time::timeout(Duration::from_secs(5), async {
loop {
let state = service.execution(id.into()).await.unwrap();
if state.status != ExecutionStatus::Running {
return state;
}
tokio::task::yield_now().await;
}
})
.await
.unwrap()
}
fn attr(span: &SpanData, key: &str) -> Option<String> {
span.attributes
.iter()
.find(|kv| kv.key.as_str() == key)
.map(|kv| kv.value.to_string())
}
fn service(
store: Arc<DurableStore>,
now: Arc<AtomicU64>,
count: Arc<AtomicUsize>,
) -> LocalCodeModeService {
let cli = Cli::create("fixture")
.command(
"save",
CommandDef::build("save", Save(count.clone())).done(),
)
.command(
"wait",
CommandDef::build("wait", Wait(count))
.mcp(McpCommandOptions {
annotations: Some(McpAnnotations {
read_only_hint: Some(true),
..Default::default()
}),
..Default::default()
})
.done(),
);
LocalCodeModeService::spawn(move || {
CodeMode::with_clock_and_artifact_store(
store.clone(),
store,
LocalExecutor::default(),
vec![Arc::new(MulticastConnector::new(cli.tool_catalog()))],
TestClock(now),
)
})
.unwrap()
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn durable_pass_links_actor_context_and_approval_wait_are_exported() {
let spans = InMemorySpanExporter::default();
let traces = SdkTracerProvider::builder()
.with_simple_exporter(spans.clone())
.build();
let metrics = InMemoryMetricExporter::default();
let meters = SdkMeterProvider::builder()
.with_reader(
PeriodicReader::builder(metrics.clone())
.with_interval(Duration::from_secs(3600))
.build(),
)
.build();
global::set_tracer_provider(traces.clone());
global::set_meter_provider(meters.clone());
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("workflow.sqlite");
let clock = Arc::new(AtomicU64::new(1000));
let count = Arc::new(AtomicUsize::new(0));
let actor = service(
Arc::new(DurableStore::open(&path).unwrap()),
clock.clone(),
count.clone(),
);
let first_parent = Context::new().with_span(traces.tracer("host").start("first-request"));
let options = CodeModeRunOptions {
telemetry_context: first_parent.clone(),
workflow: Some(WorkflowIdentity {
name: "daily-report".into(),
version: "literal-version".into(),
}),
..Default::default()
};
let running = actor
.execute("return await fixture.save({});".into(), options)
.await
.unwrap();
let paused = settle(&actor, &running.id).await;
assert_eq!(paused.status, ExecutionStatus::Paused);
assert_eq!(count.load(Ordering::SeqCst), 0);
let first = paused
.trace
.clone()
.expect("trace link persisted before pause");
let mut old = serde_json::to_value(&paused).unwrap();
old.as_object_mut().unwrap().remove("trace");
assert!(
serde_json::from_value::<ExecutionState>(old)
.unwrap()
.trace
.is_none()
);
drop(actor);
let store = tokio::time::timeout(Duration::from_secs(5), async {
loop {
if let Ok(store) = DurableStore::open(&path) {
return Arc::new(store);
}
tokio::task::yield_now().await;
}
})
.await
.unwrap();
let actor = service(store, clock.clone(), count.clone());
assert_eq!(
actor
.execution(running.id.clone())
.await
.unwrap()
.trace
.unwrap()
.span_id,
first.span_id
);
clock.store(6000, Ordering::SeqCst);
let second_parent = Context::new().with_span(traces.tracer("host").start("approval-request"));
let options = CodeModeRunOptions {
telemetry_context: second_parent.clone(),
..Default::default()
};
let completed = actor
.approve(running.id.clone(), 0, options.clone())
.await
.unwrap();
assert_eq!(completed.status, ExecutionStatus::Completed);
assert_eq!(completed.result, Some(json!(SECRET)));
assert_eq!(count.load(Ordering::SeqCst), 1);
assert_eq!(
completed
.trace
.as_ref()
.unwrap()
.workflow
.as_ref()
.unwrap()
.name,
"daily-report"
);
actor.approve(running.id.clone(), 0, options).await.unwrap();
let before = spans.get_finished_spans().unwrap().len();
let disabled = Cli::create("disabled").open_telemetry(false).command(
"run",
CommandDef::build("run", DisabledRun(actor.clone())).done(),
);
disabled
.tool_catalog()
.call("run", BTreeMap::new(), ToolCallOptions::isolated())
.await;
assert_eq!(
spans.get_finished_spans().unwrap().len(),
before,
"opt-out reaches detached passes and approval decisions"
);
let failure = actor
.execute(
format!("throw new Error('{SECRET}');"),
CodeModeRunOptions::default(),
)
.await
.unwrap();
assert_eq!(
settle(&actor, &failure.id).await.status,
ExecutionStatus::Error
);
let exported = spans.get_finished_spans().unwrap();
let passes: Vec<_> = exported
.iter()
.filter(|s| s.name == "incurs.codemode.pass")
.collect();
assert_eq!(passes.len(), 3);
let first_pass = passes
.iter()
.find(|s| s.span_context.span_id().to_string() == first.span_id)
.unwrap();
assert_eq!(
first_pass.parent_span_id,
first_parent.span().span_context().span_id()
);
let second = passes
.iter()
.find(|s| s.span_context.span_id().to_string() == completed.trace.as_ref().unwrap().span_id)
.unwrap();
assert_eq!(
second.parent_span_id,
second_parent.span().span_context().span_id()
);
assert_eq!(second.links.links.len(), 1);
assert_eq!(
second.links.links[0].span_context.span_id().to_string(),
first.span_id
);
assert_eq!(
attr(second, "incurs.workflow.version").as_deref(),
Some("literal-version")
);
assert_eq!(
attr(second, "incurs.execution.id").as_deref(),
Some(running.id.as_str())
);
let call = exported
.iter()
.find(|s| {
s.name == "incurs.codemode.call" && s.parent_span_id == second.span_context.span_id()
})
.unwrap();
let command = exported
.iter()
.find(|s| s.name == "incurs.command save")
.unwrap();
assert_eq!(
command.parent_span_id,
call.span_context.span_id(),
"command is a child of the actual tool dispatch"
);
let approvals: Vec<_> = exported
.iter()
.filter(|s| s.name == "incurs.codemode.approval")
.collect();
assert_eq!(
approvals.len(),
1,
"duplicate decisions do not double count"
);
assert_eq!(
approvals[0].parent_span_id,
second_parent.span().span_context().span_id()
);
assert_eq!(
approvals[0].links.links[0]
.span_context
.span_id()
.to_string(),
first.span_id
);
assert!(!format!("{exported:?}").contains(SECRET));
meters.force_flush().unwrap();
let mut counts = BTreeMap::new();
for batch in metrics.get_finished_metrics().unwrap() {
for scope in batch.scope_metrics() {
for metric in scope.metrics() {
if !metric.name().starts_with("incurs.codemode.") {
continue;
}
assert_eq!(metric.unit(), "s");
let AggregatedMetrics::F64(MetricData::Histogram(hist)) = metric.data() else {
panic!("histogram")
};
for point in hist.data_points() {
*counts.entry(metric.name().to_string()).or_insert(0) += point.count();
assert!(point.attributes().all(|kv| {
![
"incurs.execution.id",
"incurs.workflow.name",
"incurs.workflow.version",
]
.contains(&kv.key.as_str())
}));
if metric.name() == "incurs.codemode.approval.duration" {
assert_eq!(point.sum(), 5.0);
}
if metric.name() == "incurs.codemode.pass.duration" {
assert!(point.sum() < 5.0, "paused time excluded from active passes");
}
}
}
}
}
assert_eq!(counts["incurs.codemode.pass.duration"], 3);
assert_eq!(counts["incurs.codemode.call.duration"], 2);
assert_eq!(counts["incurs.codemode.approval.duration"], 1);
let active = actor
.execute(
"return await fixture.wait({});".into(),
CodeModeRunOptions::default(),
)
.await
.unwrap();
tokio::time::timeout(Duration::from_secs(5), async {
while count.load(Ordering::SeqCst) != 2 {
tokio::task::yield_now().await;
}
})
.await
.unwrap();
assert_eq!(
actor.cancel(active.id.clone()).await.unwrap().status,
ExecutionStatus::Cancelled
);
tokio::time::timeout(Duration::from_secs(5), async {
loop {
if spans.get_finished_spans().unwrap().iter().any(|s| {
s.name == "incurs.codemode.pass"
&& attr(s, "incurs.execution.id").as_deref() == Some(active.id.as_str())
}) {
break;
}
tokio::task::yield_now().await;
}
})
.await
.unwrap();
let cancelled: Vec<_> = spans
.get_finished_spans()
.unwrap()
.into_iter()
.filter(|s| attr(s, "incurs.execution.id").as_deref() == Some(active.id.as_str()))
.collect();
assert_eq!(cancelled.len(), 2);
assert!(
cancelled
.iter()
.all(|s| attr(s, "incurs.outcome").as_deref() == Some("cancelled")),
"cancelled execution spans: {cancelled:?}"
);
meters.force_flush().unwrap();
let mut cancelled_counts = BTreeMap::new();
for batch in metrics.get_finished_metrics().unwrap() {
for scope in batch.scope_metrics() {
for metric in scope.metrics() {
if !metric.name().starts_with("incurs.codemode.") {
continue;
}
let AggregatedMetrics::F64(MetricData::Histogram(hist)) = metric.data() else {
panic!("histogram")
};
for point in hist.data_points() {
if point.attributes().any(|kv| {
kv.key.as_str() == "incurs.outcome" && kv.value.to_string() == "cancelled"
}) {
cancelled_counts.insert(metric.name().to_string(), point.count());
}
}
}
}
}
assert_eq!(cancelled_counts["incurs.codemode.pass.duration"], 1);
assert_eq!(cancelled_counts["incurs.codemode.call.duration"], 1);
let tree = actor.execute("async () => { const f=await codemode.workflows.define('async n=>n+1'); return await f(2); }".into(), CodeModeRunOptions::default()).await.unwrap();
let tree = tokio::time::timeout(Duration::from_secs(5), async {
loop {
let state = actor.execution(tree.id.clone()).await.unwrap();
if state.status == ExecutionStatus::Completed {
break state;
}
assert_ne!(state.status, ExecutionStatus::Error, "{:?}", state.error);
tokio::task::yield_now().await;
}
})
.await
.unwrap();
assert_eq!(tree.result, Some(json!(3)));
let child = &tree.workflow_children[0];
let child_span = spans
.get_finished_spans()
.unwrap()
.into_iter()
.find(|s| {
s.name == "incurs.codemode.pass"
&& attr(s, "incurs.execution.id").as_deref() == Some(child.id.as_str())
})
.unwrap();
assert_eq!(
attr(&child_span, "incurs.workflow.root.id").as_deref(),
Some(tree.id.as_str())
);
assert_eq!(
attr(&child_span, "incurs.workflow.parent.id").as_deref(),
Some(tree.id.as_str())
);
assert_eq!(
attr(&child_span, "incurs.workflow.definition.version").as_deref(),
Some(child.reference.as_ref().unwrap().version.as_str())
);
first_parent.span().end();
second_parent.span().end();
traces.shutdown().unwrap();
meters.shutdown().unwrap();
}