#![cfg(all(feature = "quickjs", feature = "sqlite"))]
use multicast_codemode::{CodeMode, ExecutionStatus, MemoryStore};
use multicast_codemode_local::LocalExecutor;
use serde_json::json;
use std::sync::Arc;
#[tokio::test]
async fn define_compose_publish_delete_and_recurse_in_one_program() {
let runtime = CodeMode::new(
Arc::new(MemoryStore::default()),
LocalExecutor::default(),
vec![],
);
let state = runtime.execute(r#"async () => {
const w = codemode.workflows;
const inc = await w.define('async (input, bindings) => input + bindings.amount',
{input:{type:'integer'}, output:{type:'integer'}}, {amount:2});
const twice = await w.define('async input => input * 2',
{input:{type:'integer'}, output:{type:'integer'}});
const pipeline = await w.pipe([inc, twice]);
const published = await w.publish(pipeline, 'pipeline');
const pinned = await w.resolve('pipeline');
await w.delete('pipeline', published.version);
const values = await w.map(pinned, [1,2,3], 2);
const factorial = await w.define('async (n, bindings, self) => n < 2 ? 1 : n * await self(n-1)',
{input:{type:'integer',minimum:0}, output:{type:'integer'}});
return {values, factorial:await factorial(5)};
}"#).await.unwrap();
assert_eq!(
state.status,
ExecutionStatus::Completed,
"{:?} log={:?}",
state.error,
state.log
);
assert_eq!(
state.result,
Some(json!({"values":[6,8,10],"factorial":120}))
);
}
#[tokio::test]
async fn hidden_lexical_capture_is_rejected_before_child_admission() {
let runtime = CodeMode::new(
Arc::new(MemoryStore::default()),
LocalExecutor::default(),
vec![],
);
let state = runtime
.execute(
r#"async () => {
const secret = 41;
return await codemode.workflows.define('async input => input + secret');
}"#,
)
.await
.unwrap();
assert_eq!(state.status, ExecutionStatus::Error);
assert!(state.error.unwrap().contains("WORKFLOW_CAPTURE"));
}
use async_trait::async_trait;
use multicast_codemode::{
Connector, ConnectorDescription, ConnectorTool, RuntimeStore, ToolAnnotations, ToolContext,
ToolPolicy, WorkflowLimits,
};
use std::sync::atomic::{AtomicUsize, Ordering};
use tokio::sync::Mutex;
#[derive(Default)]
struct Probe {
active: AtomicUsize,
maximum: AtomicUsize,
events: Mutex<Vec<(bool, i64)>>,
calls: AtomicUsize,
approval: bool,
}
#[async_trait]
impl Connector for Probe {
fn name(&self) -> &str {
"probe"
}
async fn describe(&self) -> Result<ConnectorDescription, String> {
Ok(ConnectorDescription {
name: "probe".into(),
instructions: None,
tools: vec![ConnectorTool {
name: "run".into(),
description: None,
input_schema: json!({"type":"object"}),
output_schema: None,
instructions: None,
examples: vec![],
annotations: ToolAnnotations::default(),
policy: ToolPolicy {
requires_approval: self.approval,
..Default::default()
},
}],
})
}
async fn execute(
&self,
_method: &str,
args: serde_json::Value,
_context: &ToolContext,
) -> Result<serde_json::Value, String> {
self.calls.fetch_add(1, Ordering::SeqCst);
let id = args["id"].as_i64().unwrap_or(0);
self.events.lock().await.push((true, id));
let active = self.active.fetch_add(1, Ordering::SeqCst) + 1;
self.maximum.fetch_max(active, Ordering::SeqCst);
if args["block"] == true {
return std::future::pending().await;
}
tokio::time::sleep(std::time::Duration::from_millis(20)).await;
self.events.lock().await.push((false, id));
self.active.fetch_sub(1, Ordering::SeqCst);
Ok(json!(id * 10))
}
}
fn runtime_with(probe: Arc<Probe>, limits: WorkflowLimits) -> CodeMode {
CodeMode::new(
Arc::new(MemoryStore::default()),
LocalExecutor::default(),
vec![probe],
)
.with_workflow_limits(limits)
.unwrap()
}
#[tokio::test]
async fn map_measures_overlapping_effects_with_two_slots_and_preserves_input_order() {
let probe = Arc::new(Probe::default());
let runtime = runtime_with(
probe.clone(),
WorkflowLimits {
concurrency: 2,
..Default::default()
},
);
let state = tokio::time::timeout(
std::time::Duration::from_secs(10),
runtime.execute(
r#"async () =>{
const w=codemode.workflows;
const f=await w.define('async id => probe.run({id})');
return await w.map(f,[3,1,4,2,5],2);
}"#,
),
)
.await
.expect("parallel scheduler stalled")
.unwrap();
assert_eq!(
state.status,
ExecutionStatus::Completed,
"{:?}",
state.error
);
assert_eq!(state.result, Some(json!([30, 10, 40, 20, 50])));
assert_eq!(probe.maximum.load(Ordering::SeqCst), 2);
let events = probe.events.lock().await;
assert!(
events[0].0 && events[1].0 && !events[2].0,
"two independent starts must precede a finish: {events:?}"
);
}
#[tokio::test]
async fn mutual_recursion_releases_the_only_execution_slot() {
let runtime = runtime_with(
Arc::new(Probe::default()),
WorkflowLimits {
concurrency: 1,
..Default::default()
},
);
let state = runtime
.execute(
r#"async () =>{
const pair=await codemode.workflows.bundle({
even:{source:'async (n,b,self,peers)=>n===0?true:await peers.odd(n-1)'},
odd:{source:'async (n,b,self,peers)=>n===0?false:await peers.even(n-1)'}
});
return await pair.even(8);
}"#,
)
.await
.unwrap();
assert_eq!(
state.status,
ExecutionStatus::Completed,
"{:?}",
state.error
);
assert_eq!(state.result, Some(json!(true)));
}
#[tokio::test]
async fn root_depth_and_admission_budgets_do_not_reset_in_recursive_children() {
for limits in [
WorkflowLimits {
depth: 3,
..Default::default()
},
WorkflowLimits {
admissions: 3,
..Default::default()
},
] {
let runtime = runtime_with(Arc::new(Probe::default()), limits);
let state=runtime.execute(r#"async () =>{const f=await codemode.workflows.define('async (n,b,self)=>n?await self(n-1):0');return await f(20);}"#).await.unwrap();
assert_eq!(state.status, ExecutionStatus::Error);
assert!(
state
.error
.as_deref()
.is_some_and(|s| s.contains("WORKFLOW_DEPTH") || s.contains("WORKFLOW_ADMISSIONS")),
"{:?}",
state.error
);
}
}
#[tokio::test]
async fn child_approval_is_visible_and_only_approval_continues_the_tree() {
let probe = Arc::new(Probe {
approval: true,
..Default::default()
});
let runtime = runtime_with(probe.clone(), WorkflowLimits::default());
let root=runtime.execute(r#"async () =>{const f=await codemode.workflows.define('async id=>probe.run({id})');return (await f(7))+1;}"#).await.unwrap();
assert_eq!(root.status, ExecutionStatus::Paused);
assert!(root.workflow_wait.is_some());
assert_eq!(probe.calls.load(Ordering::SeqCst), 0);
assert!(runtime.resume(&root.id).await.is_err());
let pending = runtime.runtime().pending(None).await.unwrap();
assert_eq!(pending.len(), 1);
assert_ne!(pending[0].execution_id, root.id);
runtime
.approve(&pending[0].execution_id, pending[0].seq)
.await
.unwrap();
let completed = runtime.execution(&root.id).await.unwrap();
assert_eq!(
completed.status,
ExecutionStatus::Completed,
"{:?}",
completed.error
);
assert_eq!(completed.result, Some(json!(71)));
assert_eq!(probe.calls.load(Ordering::SeqCst), 1);
}
#[tokio::test]
async fn invalid_output_stops_the_next_effect() {
let probe = Arc::new(Probe::default());
let runtime = runtime_with(probe.clone(), WorkflowLimits::default());
let state = runtime
.execute(
r#"async () =>{const w=codemode.workflows;
const bad=await w.define('async () =>"wrong"',{output:{type:'integer'}});
const effect=await w.define('async id=>probe.run({id})');
return await (await w.pipe([bad,effect]))(0);
}"#,
)
.await
.unwrap();
assert_eq!(state.status, ExecutionStatus::Error);
assert!(state.error.unwrap().contains("WORKFLOW_OUTPUT"));
assert_eq!(probe.calls.load(Ordering::SeqCst), 0);
}
#[tokio::test]
async fn fail_fast_cancels_a_sibling_blocked_in_an_effect() {
let probe = Arc::new(Probe::default());
let runtime = runtime_with(probe.clone(), WorkflowLimits::default());
let state=tokio::time::timeout(std::time::Duration::from_secs(5),runtime.execute(r#"async () =>{const w=codemode.workflows;
const f=await w.define('async id=>{if(id===1)throw new Error("child failed");return await probe.run({id,block:true});}');
return await w.map(f,[0,1],2);
}"#)).await.expect("fail-fast left a blocked sibling").unwrap();
assert_eq!(state.status, ExecutionStatus::Error);
let children = runtime.runtime().executions().await.unwrap();
assert!(
children
.iter()
.any(|s| s.status == ExecutionStatus::Cancelled)
);
assert!(
!children
.iter()
.any(|s| matches!(s.status, ExecutionStatus::Running | ExecutionStatus::Paused))
);
}
#[tokio::test]
async fn settle_collects_outcomes_and_unawaited_children_are_joined() {
let runtime = runtime_with(Arc::new(Probe::default()), WorkflowLimits::default());
let state = runtime
.execute(
r#"async () =>{const w=codemode.workflows;
const f=await w.define('async x=>{if(x<0)throw new Error("negative");return x*2;}');
const a=await f.start(3), b=await f.start(-1);
return await w.settle([a,b]);
}"#,
)
.await
.unwrap();
assert_eq!(
state.status,
ExecutionStatus::Completed,
"{:?}",
state.error
);
assert_eq!(
state.result,
Some(json!([{"status":"fulfilled","value":6},{"status":"rejected","reason":"negative"}]))
);
let state=runtime.execute(r#"async () =>{const f=await codemode.workflows.define('async id=>probe.run({id})');await f.start(2);return 99;}"#).await.unwrap();
assert_eq!(state.status, ExecutionStatus::Completed);
assert!(
runtime
.runtime()
.executions()
.await
.unwrap()
.iter()
.all(|s| !matches!(s.status, ExecutionStatus::Running | ExecutionStatus::Paused))
);
}
#[tokio::test]
async fn scope_expiration_and_publication_retain_only_the_needed_graph() {
let store = Arc::new(MemoryStore::default());
let runtime = CodeMode::new(store.clone(), LocalExecutor::default(), vec![]);
let state=runtime.execute(r#"async () =>{const w=codemode.workflows;
const expired=await w.scope(async scope=>await scope.define('async x=>x+9'));
let expiredCode;try {await expired(1);} catch(error) {expiredCode=error.message;}
await w.scope(async scope=>{const a=await scope.define('async x=>x+1');const b=await scope.define('async x=>x*3');const p=await scope.pipe([a,b]);await scope.publish(p,'retained');});
return expiredCode;
}"#).await.unwrap();
assert_eq!(
state.status,
ExecutionStatus::Completed,
"{:?}",
state.error
);
assert!(
state
.result
.unwrap()
.as_str()
.unwrap()
.contains("WORKFLOW_REFERENCE")
);
let state = runtime
.execute(r#"async () =>await (await codemode.workflows.resolve('retained'))(4)"#)
.await
.unwrap();
assert_eq!(state.result, Some(json!(15)), "{:?}", state.error);
let catalog = store.get_workflows().await.unwrap().unwrap();
assert_eq!(catalog["definitions"].as_object().unwrap().len(), 3);
}
#[tokio::test]
async fn publication_cas_permission_and_foreign_references_fail_closed() {
let runtime = runtime_with(Arc::new(Probe::default()), WorkflowLimits::default());
let state=runtime.execute(r#"async () =>{const w=codemode.workflows;
const f=await w.define('async x=>x');const p=await w.publish(f,'p',null);
const failures=[];
try {await w.publish(f,'p',null);}catch(e){failures.push(e.message);}
try {await w.delete('p','stale');}catch(e){failures.push(e.message);}
try {await w.hydrate({__workflow_ref:{...f.__workflow_ref,store:'foreign'}})(1);}catch(e){failures.push(e.message);}
return failures;
}"#).await.unwrap();
assert_eq!(state.status, ExecutionStatus::Completed);
let messages = state.result.unwrap();
assert_eq!(messages.as_array().unwrap().len(), 3);
assert!(messages[0].as_str().unwrap().contains("WORKFLOW_VERSION"));
assert!(messages[1].as_str().unwrap().contains("WORKFLOW_VERSION"));
assert!(messages[2].as_str().unwrap().contains("WORKFLOW_REFERENCE"));
let runtime = runtime_with(
Arc::new(Probe::default()),
WorkflowLimits {
allow_publication: false,
..Default::default()
},
);
let state=runtime.execute(r#"async () =>{const w=codemode.workflows;return await w.publish(await w.define('async x=>x'),'no');}"#).await.unwrap();
assert_eq!(state.status, ExecutionStatus::Error);
assert!(state.error.unwrap().contains("WORKFLOW_PERMISSION"));
}
#[tokio::test]
async fn partial_binding_validates_the_complete_original_contract_and_rejects_override() {
let runtime = runtime_with(Arc::new(Probe::default()), WorkflowLimits::default());
let state=runtime.execute(r#"async () =>{const w=codemode.workflows;
const f=await w.define('async x=>x.a+x.b',{input:{type:'object',required:['a','b'],properties:{a:{type:'integer'},b:{type:'integer'}},additionalProperties:false},output:{type:'integer'}});
const g=await w.bind(f,{a:5});const result=await g({b:2});let error;
try {await g({a:99,b:2});}catch(e){error=e.message;}
return {result,error};
}"#).await.unwrap();
assert_eq!(
state.status,
ExecutionStatus::Completed,
"{:?}",
state.error
);
assert_eq!(state.result.as_ref().unwrap()["result"], 7);
assert!(
state.result.unwrap()["error"]
.as_str()
.unwrap()
.contains("WORKFLOW_BIND_OVERRIDE")
);
}
#[tokio::test]
async fn sqlite_restart_reuses_child_ids_and_approval_checkpoint() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("fluency.sqlite");
let probe = Arc::new(Probe {
approval: true,
..Default::default()
});
let (root, child, seq) = {
let store = Arc::new(multicast_codemode_local::DurableStore::open(&path).unwrap());
let runtime = CodeMode::new(store, LocalExecutor::default(), vec![probe.clone()]);
let state=runtime.execute(r#"async () =>{const f=await codemode.workflows.define('async id=>probe.run({id})');return await f(8);}"#).await.unwrap();
let pending = runtime.runtime().pending(None).await.unwrap().remove(0);
(state.id, pending.execution_id, pending.seq)
};
let store = Arc::new(multicast_codemode_local::DurableStore::open(&path).unwrap());
let runtime = CodeMode::new(store, LocalExecutor::default(), vec![probe.clone()]);
let before = runtime.runtime().executions().await.unwrap().len();
runtime
.drive_if_idle(&root, Default::default())
.await
.unwrap();
assert_eq!(runtime.runtime().executions().await.unwrap().len(), before);
runtime.approve(&child, seq).await.unwrap();
assert_eq!(
runtime.execution(&root).await.unwrap().result,
Some(json!(80))
);
assert_eq!(probe.calls.load(Ordering::SeqCst), 1);
}
#[tokio::test]
async fn root_attempts_and_metadata_limits_stop_descendant_effects() {
let probe = Arc::new(Probe::default());
let runtime = runtime_with(
probe.clone(),
WorkflowLimits {
attempts: 2,
..Default::default()
},
);
let state = runtime.execute(r#"async () => { const w=codemode.workflows; const f=await w.define('async id=>probe.run({id})'); return await w.map(f,[1,2,3],1); }"#).await.unwrap();
assert_eq!(state.status, ExecutionStatus::Error);
assert!(state.error.unwrap().contains("WORKFLOW_ATTEMPTS"));
assert_eq!(probe.calls.load(Ordering::SeqCst), 2);
let probe = Arc::new(Probe::default());
let runtime = runtime_with(
probe.clone(),
WorkflowLimits {
bytes: 1024,
..Default::default()
},
);
let state = runtime.execute(r#"async () => { const w=codemode.workflows; const f=await w.define('async (id,b)=>probe.run({id})',{}, {large:'x'.repeat(2048)}); return await f(1); }"#).await.unwrap();
assert_eq!(state.status, ExecutionStatus::Error);
assert!(state.error.unwrap().contains("WORKFLOW_BYTES"));
assert_eq!(probe.calls.load(Ordering::SeqCst), 0);
}
#[tokio::test]
async fn absolute_deadline_interrupts_a_blocked_effect_and_expires_pending_approval() {
let probe = Arc::new(Probe::default());
let runtime = runtime_with(
probe.clone(),
WorkflowLimits {
lifetime_ms: 500,
..Default::default()
},
);
let state = tokio::time::timeout(std::time::Duration::from_secs(3), runtime.execute(r#"async () => {const f=await codemode.workflows.define('async id=>probe.run({id,block:true})');return await f(1);}"#)).await.expect("deadline did not interrupt active effect").unwrap();
assert_eq!(state.status, ExecutionStatus::Error);
assert!(state.error.unwrap().contains("WORKFLOW_DEADLINE"));
assert_eq!(probe.calls.load(Ordering::SeqCst), 1);
assert!(
runtime
.runtime()
.executions()
.await
.unwrap()
.iter()
.all(|s| !matches!(s.status, ExecutionStatus::Running | ExecutionStatus::Paused))
);
let probe = Arc::new(Probe {
approval: true,
..Default::default()
});
let runtime = runtime_with(
probe.clone(),
WorkflowLimits {
lifetime_ms: 200,
..Default::default()
},
);
let state = runtime.execute(r#"async () => {const f=await codemode.workflows.define('async id=>probe.run({id})');return await f(1);}"#).await.unwrap();
assert_eq!(state.status, ExecutionStatus::Paused);
tokio::time::sleep(std::time::Duration::from_millis(220)).await;
runtime
.drive_if_idle(&state.id, Default::default())
.await
.unwrap();
assert_eq!(
runtime.execution(&state.id).await.unwrap().status,
ExecutionStatus::Error
);
assert_eq!(probe.calls.load(Ordering::SeqCst), 0);
assert!(runtime.runtime().pending(None).await.unwrap().is_empty());
}
#[tokio::test]
async fn child_rejection_and_parent_cancellation_stop_the_owned_tree() {
let probe = Arc::new(Probe {
approval: true,
..Default::default()
});
let runtime = runtime_with(probe.clone(), WorkflowLimits::default());
let code = r#"async () => {const f=await codemode.workflows.define('async id=>probe.run({id})');return await f(7);}"#;
let state = runtime.execute(code).await.unwrap();
let pending = runtime
.runtime()
.pending(Some(&state.id))
.await
.unwrap()
.remove(0);
runtime
.reject(&pending.execution_id, pending.seq)
.await
.unwrap();
assert_eq!(
runtime.execution(&state.id).await.unwrap().status,
ExecutionStatus::Error
);
let state = runtime.execute(code).await.unwrap();
runtime.cancel(&state.id).await.unwrap();
assert_eq!(
runtime.execution(&state.id).await.unwrap().status,
ExecutionStatus::Cancelled
);
assert!(
runtime
.runtime()
.pending(Some(&state.id))
.await
.unwrap()
.is_empty()
);
assert_eq!(probe.calls.load(Ordering::SeqCst), 0);
}
#[tokio::test]
async fn pinned_versions_and_contract_discovery_survive_publication_replacement() {
let runtime = runtime_with(Arc::new(Probe::default()), WorkflowLimits::default());
let state=runtime.execute(r#"async () => {const w=codemode.workflows;
const a=await w.define('async n=>n+1',{input:{type:'integer'},output:{type:'integer'}});
const p=await w.publish(a,'replace');const old=await w.resolve('replace');
const b=await w.define('async n=>n+100',{input:{type:'integer'},output:{type:'integer'}});
await w.publish(b,'replace',p.version);
const fresh=await w.resolve('replace');
const same=await w.pipe([a,b]);const unknown=await w.pipe([a,await w.define('async n=>n',{input:{type:'number'}})]);
let incompatible;try {await w.pipe([a,await w.define('async x=>x',{input:{type:'string'}})]);} catch(e){incompatible=e.message;}
return {old:await old(1),fresh:await fresh(1),same:same.compatibility,unknown:unknown.compatibility,contract:await w.inspect(a),incompatible};
}"#).await.unwrap();
assert_eq!(
state.status,
ExecutionStatus::Completed,
"{:?}",
state.error
);
let value = state.result.unwrap();
assert_eq!(value["old"], 2);
assert_eq!(value["fresh"], 101);
assert_eq!(value["same"], json!(["compatible"]));
assert_eq!(value["unknown"], json!(["unknown"]));
assert_eq!(value["contract"]["input"], json!({"type":"integer"}));
assert!(
value["contract"]["types"]
.as_str()
.unwrap()
.contains("number")
);
assert!(
value["incompatible"]
.as_str()
.unwrap()
.contains("WORKFLOW_SCHEMA_INCOMPATIBLE")
);
let found = runtime.search("workflow define").await.unwrap();
assert!(
found
.results
.iter()
.any(|r| r.path == "codemode.workflows.define")
);
}
#[tokio::test]
async fn missing_bound_child_never_creates_a_replacement() {
let store = Arc::new(MemoryStore::default());
let probe = Arc::new(Probe {
approval: true,
..Default::default()
});
let runtime = CodeMode::new(store.clone(), LocalExecutor::default(), vec![probe.clone()]);
let root=runtime.execute(r#"async () => {const f=await codemode.workflows.define('async id=>probe.run({id})');return await f(7);}"#).await.unwrap();
let pending = runtime
.runtime()
.pending(Some(&root.id))
.await
.unwrap()
.remove(0);
store.delete_execution(&pending.execution_id).await.unwrap();
let before = store.list_executions().await.unwrap().len();
let error = runtime
.drive_if_idle(&root.id, Default::default())
.await
.unwrap_err();
assert!(error.contains("WORKFLOW_BOUND_CHILD_MISSING"), "{error}");
assert_eq!(store.list_executions().await.unwrap().len(), before);
assert_eq!(probe.calls.load(Ordering::SeqCst), 0);
}
#[tokio::test]
async fn release_keeps_a_live_childs_definition_until_approval_and_retention_expire() {
let store = Arc::new(MemoryStore::default());
let probe = Arc::new(Probe {
approval: true,
..Default::default()
});
let runtime = CodeMode::new(store.clone(), LocalExecutor::default(), vec![probe.clone()]);
let root=runtime.execute(r#"async () => {const w=codemode.workflows;const f=await w.define('async id=>probe.run({id})');const run=await f.start(3);await w.release(f);return await run.result();}"#).await.unwrap();
assert_eq!(root.status, ExecutionStatus::Paused);
let pending = runtime
.runtime()
.pending(Some(&root.id))
.await
.unwrap()
.remove(0);
assert_eq!(
store.get_workflows().await.unwrap().unwrap()["definitions"]
.as_object()
.unwrap()
.len(),
1
);
runtime
.approve(&pending.execution_id, pending.seq)
.await
.unwrap();
assert_eq!(
runtime.execution(&root.id).await.unwrap().result,
Some(json!(30))
);
assert_eq!(probe.calls.load(Ordering::SeqCst), 1);
runtime.runtime().prune_at(0, u64::MAX).await.unwrap();
runtime.execute("return 0;").await.unwrap();
assert_eq!(
store.get_workflows().await.unwrap().unwrap()["definitions"]
.as_object()
.unwrap()
.len(),
0
);
}
#[tokio::test]
async fn heap_checkpoints_count_against_root_retained_storage() {
let probe = Arc::new(Probe::default());
let runtime = runtime_with(
probe.clone(),
WorkflowLimits {
bytes: 16_384,
..Default::default()
},
);
let state=runtime.execute("async () => { const payload='x'.repeat(50000); return await probe.run({id:payload.length}); } ").await.unwrap();
assert_eq!(state.status, ExecutionStatus::Error, "{:?}", state.error);
assert!(state.error.unwrap().contains("WORKFLOW_BYTES"));
assert_eq!(probe.calls.load(Ordering::SeqCst), 0);
}
#[tokio::test]
async fn measure_direct_and_fluent_cold_and_warm_execution() {
let mut measurements = Vec::new();
for (mode, code) in [
(
"direct",
"async () => { const values=[]; for (const id of [1,2,3,4,5]) values.push(await probe.run({id})); return values; }",
),
(
"fluent",
"async () => { const f=await codemode.workflows.define('async id=>probe.run({id})'); return await codemode.workflows.map(f,[1,2,3,4,5],2); }",
),
] {
let store = Arc::new(MemoryStore::default());
let probe = Arc::new(Probe::default());
let runtime = CodeMode::new(store.clone(), LocalExecutor::default(), vec![probe.clone()]);
for temperature in ["cold", "warm"] {
let before = probe.calls.load(Ordering::SeqCst);
let start = std::time::Instant::now();
let state = runtime.execute(code).await.unwrap();
let elapsed_ms = start.elapsed().as_secs_f64() * 1000.0;
assert_eq!(
state.status,
ExecutionStatus::Completed,
"{:?}",
state.error
);
assert_eq!(state.result, Some(json!([10, 20, 30, 40, 50])));
let state = runtime
.runtime()
.execution_snapshot(&state.id)
.await
.unwrap()
.unwrap();
let children = state.workflow_children.len();
let mut ids = vec![state.id.clone()];
ids.extend(state.workflow_children.iter().map(|c| c.id.clone()));
let mut checkpoint_bytes = 0;
let mut execution_bytes = 0;
let mut dispatches = 0;
for id in ids {
if let Some(checkpoint) = store.get_checkpoint(&id).await.unwrap() {
checkpoint_bytes += serde_json::to_vec(&checkpoint).unwrap().len();
}
let execution = store.get_execution(&id).await.unwrap().unwrap();
dispatches += execution.log.len();
execution_bytes += serde_json::to_vec(&execution).unwrap().len();
}
let catalog = store.get_workflows().await.unwrap().unwrap();
assert!(
checkpoint_bytes <= 131_072,
"checkpoint bytes: {checkpoint_bytes}"
);
assert!(catalog["roots"][&state.id]["bytes"].as_u64().unwrap() <= 262_144);
assert!(runtime.instructions().await.unwrap().len() <= 4096);
if let Ok(path) = std::env::var("MULTICAST_WORKFLOW_TYPES_OUTPUT") {
std::fs::write(path, runtime.instructions().await.unwrap()).unwrap();
}
measurements.push(json!({"mode":mode,"temperature":temperature,"elapsedMs":elapsed_ms,"effects":probe.calls.load(Ordering::SeqCst)-before,"children":children,"hostDispatches":dispatches,"checkpointBytes":checkpoint_bytes,"executionBytes":execution_bytes,"rootRetainedBytes":catalog["roots"][&state.id]["bytes"],"discoveryBytes":runtime.instructions().await.unwrap().len()}));
}
}
println!(
"WORKFLOW_MEASUREMENTS={}",
serde_json::to_string(&measurements).unwrap()
);
}