use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use async_trait::async_trait;
use futures_util::{FutureExt as _, StreamExt, stream::FuturesUnordered};
use multicast::command::RequestContext;
use multicast::telemetry::opentelemetry::{Context, trace::FutureExt};
use multicast::tool::{ToolCallControl, ToolEvent, ToolEventSink};
use serde_json::Value;
use tokio::sync::{Mutex, Semaphore};
use tokio_util::sync::CancellationToken;
use crate::{
ArtifactStore, CapabilitySnapshot, Clock, CodeExecutor, CodeModeRuntime, Connector,
ConnectorDescription, DispatchRequest, DispatchSession, ExecutionEvent, ExecutionHost,
ExecutionState, ExecutionStatus, RuntimeStore, SearchOutput, Snippet, SystemClock, ToolContext,
};
#[derive(Clone)]
pub struct CodeModeRunOptions {
pub telemetry_context: Context,
pub workflow: Option<crate::WorkflowIdentity>,
pub cancellation: CancellationToken,
pub request: Option<RequestContext>,
}
impl Default for CodeModeRunOptions {
fn default() -> Self {
Self {
cancellation: CancellationToken::new(),
request: None,
telemetry_context: Context::current(),
workflow: None,
}
}
}
struct RuntimeEventSink {
runtime: Arc<CodeModeRuntime>,
execution_id: String,
clock: Arc<dyn Clock>,
}
#[async_trait]
impl ToolEventSink for RuntimeEventSink {
async fn emit(&self, event: ToolEvent) {
let at = self.clock.now_ms();
let event = match event {
ToolEvent::Progress { message, fraction } => ExecutionEvent::Progress {
message,
fraction,
at,
},
ToolEvent::Log { level, message } => ExecutionEvent::Log { level, message, at },
ToolEvent::Chunk { data } => ExecutionEvent::Chunk { data, at },
};
let _ = self.runtime.event(&self.execution_id, event).await;
}
}
pub struct CodeMode {
runtime: Arc<CodeModeRuntime>,
executor: Box<dyn CodeExecutor>,
connectors: Vec<Arc<dyn Connector>>,
clock: Arc<dyn Clock>,
contexts: Mutex<HashMap<String, ToolContext>>,
pass_gates: Mutex<HashMap<String, Arc<Semaphore>>>,
active_rollbacks: Mutex<HashSet<String>>,
}
impl CodeMode {
pub fn new(
store: Arc<dyn RuntimeStore>,
executor: impl CodeExecutor + 'static,
connectors: Vec<Arc<dyn Connector>>,
) -> Self {
Self::with_clock(store, executor, connectors, SystemClock)
}
pub fn with_artifact_store(
store: Arc<dyn RuntimeStore>,
artifacts: Arc<dyn ArtifactStore>,
executor: impl CodeExecutor + 'static,
connectors: Vec<Arc<dyn Connector>>,
) -> Self {
Self {
runtime: Arc::new(CodeModeRuntime::with_artifacts(store, artifacts)),
executor: Box::new(executor),
connectors,
clock: Arc::new(SystemClock),
contexts: Mutex::new(HashMap::new()),
pass_gates: Mutex::new(HashMap::new()),
active_rollbacks: Mutex::new(HashSet::new()),
}
}
pub fn with_clock(
store: Arc<dyn RuntimeStore>,
executor: impl CodeExecutor + 'static,
connectors: Vec<Arc<dyn Connector>>,
clock: impl Clock + 'static,
) -> Self {
Self {
runtime: Arc::new(CodeModeRuntime::new(store)),
executor: Box::new(executor),
connectors,
clock: Arc::new(clock),
contexts: Mutex::new(HashMap::new()),
pass_gates: Mutex::new(HashMap::new()),
active_rollbacks: Mutex::new(HashSet::new()),
}
}
pub fn with_clock_and_artifact_store(
store: Arc<dyn RuntimeStore>,
artifacts: Arc<dyn ArtifactStore>,
executor: impl CodeExecutor + 'static,
connectors: Vec<Arc<dyn Connector>>,
clock: impl Clock + 'static,
) -> Self {
Self {
runtime: Arc::new(CodeModeRuntime::with_artifacts(store, artifacts)),
executor: Box::new(executor),
connectors,
clock: Arc::new(clock),
contexts: Mutex::new(HashMap::new()),
pass_gates: Mutex::new(HashMap::new()),
active_rollbacks: Mutex::new(HashSet::new()),
}
}
pub fn with_workflow_limits(mut self, limits: crate::WorkflowLimits) -> Result<Self, String> {
limits.check()?;
Arc::get_mut(&mut self.runtime)
.ok_or("Workflow limits must be configured before sharing the runtime")?
.workflow_limits = limits;
Ok(self)
}
pub fn workflow_limits(&self) -> &crate::WorkflowLimits {
&self.runtime.workflow_limits
}
pub fn runtime(&self) -> Arc<CodeModeRuntime> {
Arc::clone(&self.runtime)
}
pub async fn instructions(&self) -> Result<String, String> {
let mut descriptions = Vec::new();
for connector in &self.connectors {
descriptions.push(connector.describe().await?);
}
let mut sections = descriptions
.iter()
.filter_map(|connector| {
connector
.instructions
.as_ref()
.map(|instructions| format!("## {}\n\n{instructions}", connector.name))
})
.collect::<Vec<_>>();
sections.extend(descriptions.iter().map(crate::generate_types));
sections.push(crate::workflow_api::types());
Ok(sections.join("\n\n"))
}
pub async fn search(&self, query: &str) -> Result<SearchOutput, String> {
let mut descriptions = Vec::new();
for connector in &self.connectors {
descriptions.push(connector.describe().await?);
}
let snippets = self
.runtime
.snippets()
.await
.map_err(|error| error.to_string())?;
Ok(crate::search(query, &descriptions, &snippets))
}
pub async fn execution(&self, execution_id: &str) -> Result<ExecutionState, String> {
self.require(execution_id).await
}
pub async fn execution_snapshot(&self, execution_id: &str) -> Result<ExecutionState, String> {
self.runtime
.execution_snapshot(execution_id)
.await
.map_err(|error| error.to_string())?
.ok_or_else(|| format!("Execution \"{execution_id}\" not found"))
}
pub async fn artifact(&self, execution_id: &str, artifact_id: &str) -> Result<Value, String> {
self.runtime
.artifact(execution_id, artifact_id)
.await
.map_err(|error| error.to_string())?
.ok_or_else(|| {
format!("Artifact \"{artifact_id}\" not found for execution \"{execution_id}\"")
})
}
pub async fn save_snippet(
&self,
name: &str,
description: &str,
execution_id: &str,
input_schema: Option<Value>,
) -> Result<Snippet, String> {
self.runtime
.save_snippet(
name,
description,
execution_id,
input_schema,
self.clock.now_ms(),
)
.await
.map_err(|error| error.to_string())
}
pub async fn publish_snippet(
&self,
name: &str,
description: &str,
code: &str,
input_schema: Option<Value>,
) -> Result<Snippet, String> {
self.runtime
.publish_snippet(Snippet {
name: name.into(),
description: description.into(),
code: code.into(),
saved_at: self.clock.now_ms(),
input_schema,
connectors: self
.connectors
.iter()
.map(|connector| connector.name().to_string())
.collect(),
})
.await
.map_err(|error| error.to_string())
}
pub async fn snippets(&self) -> Result<Vec<Snippet>, String> {
self.runtime
.snippets()
.await
.map_err(|error| error.to_string())
}
pub async fn delete_snippet(&self, name: &str) -> Result<bool, String> {
self.runtime
.delete_snippet(name)
.await
.map_err(|error| error.to_string())
}
pub async fn events(&self, execution_id: &str) -> Result<Vec<ExecutionEvent>, String> {
Ok(self.require(execution_id).await?.events)
}
pub async fn cancel(&self, execution_id: &str) -> Result<ExecutionState, String> {
self.cancel_descendants(execution_id).await?;
let previous = self.require(execution_id).await?;
let now = self.clock.now_ms();
let pass_active = self.contexts.lock().await.contains_key(execution_id);
if let Some(context) = self.contexts.lock().await.get(execution_id) {
context.control.cancellation.cancel();
}
let changed = self
.runtime
.cancel(execution_id, now)
.await
.map_err(|error| error.to_string())?;
if changed {
crate::telemetry::approval(&previous, now, "cancelled");
}
if changed && !pass_active {
self.notify_execution_end(execution_id, "cancelled").await;
}
self.require(execution_id).await
}
fn namespace_stubs(&self) -> Vec<ConnectorDescription> {
self.connectors
.iter()
.map(|connector| ConnectorDescription {
name: connector.name().to_string(),
instructions: None,
tools: Vec::new(),
})
.collect()
}
pub async fn start(&self, code: &str) -> Result<ExecutionState, String> {
self.start_retained(code, None, None).await
}
pub async fn start_retained(
&self,
code: &str,
retention_ms: Option<u64>,
execution_id: Option<String>,
) -> Result<ExecutionState, String> {
let capabilities = CapabilitySnapshot::new(self.namespace_stubs())?;
let now = self.clock.now_ms();
let id = self
.runtime
.begin_retained(
code,
capabilities,
now,
retention_ms.map(|duration| now.saturating_add(duration)),
execution_id,
)
.await
.map_err(|error| error.to_string())?;
self.require(&id).await
}
pub async fn execute(&self, code: &str) -> Result<ExecutionState, String> {
self.execute_with(code, CodeModeRunOptions::default()).await
}
pub async fn execute_with(
&self,
code: &str,
options: CodeModeRunOptions,
) -> Result<ExecutionState, String> {
let state = self.start(code).await?;
self.drive_with(&state.id, options).await
}
pub async fn prepare_resume(&self, execution_id: &str) -> Result<ExecutionState, String> {
let state = self.require(execution_id).await?;
match state.status {
ExecutionStatus::Running => Ok(state),
ExecutionStatus::Paused => self
.runtime
.resume(execution_id, self.clock.now_ms())
.await
.map_err(|error| error.to_string()),
_ => Err("Only interrupted running or recovery-paused executions can resume".into()),
}
}
pub async fn resume(&self, execution_id: &str) -> Result<ExecutionState, String> {
self.resume_with(execution_id, CodeModeRunOptions::default())
.await
}
pub async fn resume_with(
&self,
execution_id: &str,
options: CodeModeRunOptions,
) -> Result<ExecutionState, String> {
self.runtime
.resume(execution_id, self.clock.now_ms())
.await
.map_err(|error| error.to_string())?;
self.drive_with(execution_id, options).await
}
pub async fn approve(&self, execution_id: &str, seq: u64) -> Result<ExecutionState, String> {
self.approve_with(execution_id, seq, CodeModeRunOptions::default())
.await
}
pub async fn approve_with(
&self,
execution_id: &str,
seq: u64,
options: CodeModeRunOptions,
) -> Result<ExecutionState, String> {
if !self
.approve_pending(execution_id, seq)
.with_context(options.telemetry_context.clone())
.await?
{
return self.require(execution_id).await;
}
self.drive_with(execution_id, options).await
}
pub async fn approve_pending(&self, execution_id: &str, seq: u64) -> Result<bool, String> {
let previous = self.require(execution_id).await?;
let now = self.clock.now_ms();
let changed = self
.runtime
.approve(execution_id, seq, now)
.await
.map_err(|error| error.to_string())?;
if changed {
crate::telemetry::approval(&previous, now, "approved");
}
Ok(changed)
}
pub async fn reject(&self, execution_id: &str, seq: u64) -> Result<ExecutionState, String> {
let previous = self.require(execution_id).await?;
let now = self.clock.now_ms();
if self
.runtime
.reject(execution_id, seq, now)
.await
.map_err(|error| error.to_string())?
{
crate::telemetry::approval(&previous, now, "rejected");
self.notify_execution_end(execution_id, "rejected").await;
}
if let Some((root, _, _)) = self.runtime.workflow_nodes(execution_id).await?
&& root != execution_id
{
self.drive_if_idle(&root, CodeModeRunOptions::default())
.await?;
}
self.require(execution_id).await
}
pub async fn rollback(&self, execution_id: &str) -> Result<ExecutionState, String> {
{
let mut active = self.active_rollbacks.lock().await;
if !active.insert(execution_id.to_string()) {
return Err(format!(
"Execution \"{execution_id}\" is already rolling back"
));
}
}
let result = self.rollback_inner(execution_id).await;
self.active_rollbacks.lock().await.remove(execution_id);
result
}
async fn rollback_inner(&self, execution_id: &str) -> Result<ExecutionState, String> {
for action in self
.runtime
.actions_to_revert(execution_id)
.await
.map_err(|error| error.to_string())?
{
let connector = self
.connector(&action.connector)
.await?
.ok_or_else(|| format!("Connector \"{}\" not found", action.connector))?;
if !connector
.revert(
&action.method,
action.arguments,
action.result.unwrap_or(Value::Null),
&ToolContext {
call: None,
execution_id: execution_id.to_string(),
control: Default::default(),
request: None,
telemetry_context: multicast::telemetry::opentelemetry::Context::current(),
},
)
.await?
{
return Err(format!(
"{}.{} did not compensate step {}",
action.connector, action.method, action.seq
));
}
self.runtime
.mark_reverted(execution_id, action.seq, self.clock.now_ms())
.await
.map_err(|error| error.to_string())?;
}
self.runtime
.finish_rollback(execution_id, self.clock.now_ms())
.await
.map_err(|error| error.to_string())?;
self.notify_execution_end(execution_id, "rolled_back").await;
self.require(execution_id).await
}
pub async fn expire(&self, max_age_ms: u64) -> Result<Vec<String>, String> {
let ids = self
.runtime
.expire(self.clock.now_ms(), max_age_ms)
.await
.map_err(|error| error.to_string())?;
for id in &ids {
let status = self.require(id).await?.status;
self.notify_execution_end(
id,
if status == ExecutionStatus::Rejected {
"rejected"
} else {
"error"
},
)
.await;
}
Ok(ids)
}
pub async fn dispatch(&self, request: DispatchRequest) -> Result<Value, String> {
match request {
DispatchRequest::LoadCheckpoint { execution_id } => {
let _ = self.active_context(&execution_id).await?;
serde_json::to_value(
self.runtime
.checkpoint(&execution_id)
.await
.map_err(|e| e.to_string())?,
)
.map_err(|e| e.to_string())
}
DispatchRequest::SaveCheckpoint {
execution_id,
checkpoint,
} => {
let _ = self.active_context(&execution_id).await?;
self.runtime
.save_checkpoint(&execution_id, &checkpoint)
.await
.map_err(|e| e.to_string())?;
Ok(serde_json::json!({"ok": true}))
}
DispatchRequest::Call {
execution_id,
seq,
connector,
method,
arguments,
} => {
let session = self.session(&execution_id).await?;
serde_json::to_value(
session
.call_at(seq, &connector, &method, arguments, self.clock.now_ms())
.await,
)
.map_err(|error| error.to_string())
}
DispatchRequest::BeginStep {
execution_id,
seq,
name,
} => {
let session = self.session(&execution_id).await?;
serde_json::to_value(
session
.begin_step_at(seq, &name, self.clock.now_ms())
.await
.map_err(|error| error.to_string())?,
)
.map_err(|error| error.to_string())
}
DispatchRequest::RecordStep {
execution_id,
seq,
result,
} => {
let _ = self.active_context(&execution_id).await?;
self.runtime
.record_result(&execution_id, seq, result, self.clock.now_ms())
.await
.map_err(|error| error.to_string())?;
Ok(serde_json::json!({ "ok": true }))
}
}
}
pub async fn drive_with(
&self,
execution_id: &str,
options: CodeModeRunOptions,
) -> Result<ExecutionState, String> {
let root = self
.runtime
.workflow_nodes(execution_id)
.await?
.map(|n| n.0)
.unwrap_or_else(|| execution_id.to_string());
let gate = self.pass_gate(&format!("tree:{root}")).await;
let _permit = gate
.acquire_owned()
.await
.map_err(|_| "Code Mode execution gate closed".to_string())?;
self.drive_tree(&root, options).await?;
self.require(execution_id).await
}
async fn pass_gate(&self, execution_id: &str) -> Arc<Semaphore> {
Arc::clone(
self.pass_gates
.lock()
.await
.entry(execution_id.to_string())
.or_insert_with(|| Arc::new(Semaphore::new(1))),
)
}
pub async fn drive_if_idle(
&self,
execution_id: &str,
options: CodeModeRunOptions,
) -> Result<ExecutionState, String> {
let root = self
.runtime
.workflow_nodes(execution_id)
.await?
.map(|n| n.0)
.unwrap_or_else(|| execution_id.to_string());
let Ok(_permit) = self
.pass_gate(&format!("tree:{root}"))
.await
.try_acquire_owned()
else {
return self.require(execution_id).await;
};
self.drive_tree(&root, options).await?;
self.require(execution_id).await
}
async fn drive_tree(&self, root: &str, options: CodeModeRunOptions) -> Result<(), String> {
let result = self.drive_tree_inner(root, options.clone()).await;
if let Err(error) = &result {
options.cancellation.cancel();
self.runtime
.fail_tree(root, error.clone(), self.clock.now_ms())
.await
.map_err(|e| e.to_string())?;
if let Some((_, _, nodes)) = self.runtime.workflow_nodes(root).await? {
for (id, _) in nodes {
if let Some(context) = self.contexts.lock().await.remove(&id) {
context.control.cancellation.cancel();
}
if id != root
&& self
.runtime
.execution(&id)
.await
.map_err(|e| e.to_string())?
.is_some_and(|s| {
matches!(
s.status,
ExecutionStatus::Running | ExecutionStatus::Paused
)
})
{
self.runtime
.cancel(&id, self.clock.now_ms())
.await
.map_err(|e| e.to_string())?;
}
}
}
}
result
}
async fn drive_tree_inner(
&self,
root: &str,
options: CodeModeRunOptions,
) -> Result<(), String> {
type TreePlan = Result<(usize, Vec<(String, Option<String>)>), String>;
enum Event {
Deadline,
Pass(String, Box<Result<ExecutionState, String>>),
Plan(TreePlan),
}
let mut active = HashSet::new();
let mut events: FuturesUnordered<futures_util::future::LocalBoxFuture<'_, Event>> =
FuturesUnordered::new();
if let Some(deadline) = self
.runtime
.workflow_admit_root(root, self.clock.now_ms())
.await?
{
events.push(
async move {
self.clock
.sleep(deadline.saturating_sub(self.clock.now_ms()))
.await;
Event::Deadline
}
.boxed_local(),
);
}
let mut planning = false;
let mut dirty = true;
let mut failed = Vec::new();
loop {
if dirty && !planning {
let active = active.clone();
let failed = std::mem::take(&mut failed);
events.push(
async move { Event::Plan(self.plan_tree(root, &active, failed).await) }
.boxed_local(),
);
planning = true;
dirty = false;
}
let Some(event) = events.next().await else {
break;
};
match event {
Event::Deadline => {
dirty = true;
}
Event::Pass(id, result) => {
active.remove(&id);
let state = match *result {
Ok(state) => state,
Err(error) => {
if self.require(&id).await?.status == ExecutionStatus::Running {
self.runtime
.fail(&id, error, Vec::new(), self.clock.now_ms())
.await
.map_err(|e| e.to_string())?;
}
self.require(&id).await?
}
};
if matches!(
state.status,
ExecutionStatus::Error
| ExecutionStatus::Rejected
| ExecutionStatus::Cancelled
) {
failed.push(id);
}
dirty = true;
}
Event::Plan(result) => {
planning = false;
let (limit, nodes) = result?;
if nodes.is_empty() && active.is_empty() && !dirty {
break;
}
for (id, parent) in nodes {
if active.len() >= limit {
break;
}
if !active.insert(id.clone()) {
continue;
}
let mut pass_options = options.clone();
pass_options.cancellation = options.cancellation.child_token();
events.push(
async move {
let result = async {
if let Some(parent) = parent {
for connector in &self.connectors {
connector
.admit_child(
&parent,
&id,
pass_options.request.as_ref(),
)
.await?;
}
}
self.drive_pass(&id, pass_options).await
}
.await;
Event::Pass(id, Box::new(result))
}
.boxed_local(),
);
}
}
}
}
self.runtime.workflow_sweep().await?;
Ok(())
}
async fn plan_tree(
&self,
root: &str,
active: &HashSet<String>,
failed: Vec<String>,
) -> Result<(usize, Vec<(String, Option<String>)>), String> {
for id in failed {
self.cancel_descendants(&id).await?;
}
if let Some((_, _, nodes)) = self.runtime.workflow_nodes(root).await? {
for (id, _) in nodes {
let state = self.require(&id).await.map_err(|_| {
"WORKFLOW_BOUND_CHILD_MISSING: reconciliation required".to_string()
})?;
if matches!(
state.status,
ExecutionStatus::Error | ExecutionStatus::Rejected | ExecutionStatus::Cancelled
) {
if let Some(context) = self.contexts.lock().await.get(&id) {
context.control.cancellation.cancel();
}
self.cancel_descendants(&id).await?;
}
}
}
if let Err(error) = self
.runtime
.workflow_deadline(root, self.clock.now_ms())
.await
{
self.runtime
.workflow_wake(root, self.clock.now_ms())
.await?;
self.runtime
.fail_tree(root, error, self.clock.now_ms())
.await
.map_err(|e| e.to_string())?;
self.cancel_descendants(root).await?;
return Ok((1, Vec::new()));
}
let (_, limit, nodes) = self.runtime.workflow_nodes(root).await?.unwrap_or((
root.to_string(),
1,
vec![(root.to_string(), None)],
));
let mut runnable = Vec::new();
for (id, parent) in nodes {
let state = self.require(&id).await?;
if let Some(wait) = &state.workflow_wait {
let mut all = true;
let mut failed = false;
for child in &wait.children {
let child = self.require(child).await.map_err(|_| {
"WORKFLOW_BOUND_CHILD_MISSING: reconciliation required".to_string()
})?;
if matches!(
child.status,
ExecutionStatus::Running | ExecutionStatus::Paused
) {
all = false;
} else if child.status != ExecutionStatus::Completed {
failed = true;
}
}
if all || (!wait.settle && failed) {
self.runtime.workflow_wake(&id, self.clock.now_ms()).await?;
}
}
if !active.contains(&id) && self.require(&id).await?.status == ExecutionStatus::Running
{
runnable.push((id, parent));
}
}
Ok((limit, runnable))
}
async fn cancel_descendants(&self, id: &str) -> Result<(), String> {
let Some((_, _, nodes)) = self.runtime.workflow_nodes(id).await? else {
return Ok(());
};
let mut descendants = HashSet::from([id.to_string()]);
loop {
let before = descendants.len();
for (child, parent) in &nodes {
if parent.as_ref().is_some_and(|p| descendants.contains(p)) {
descendants.insert(child.clone());
}
}
if descendants.len() == before {
break;
}
}
descendants.remove(id);
for child in descendants {
if let Some(context) = self.contexts.lock().await.get(&child) {
context.control.cancellation.cancel();
}
let state = self.require(&child).await?;
if matches!(
state.status,
ExecutionStatus::Running | ExecutionStatus::Paused
) {
self.runtime
.cancel(&child, self.clock.now_ms())
.await
.map_err(|e| e.to_string())?;
self.notify_execution_end(&child, "cancelled").await;
}
}
Ok(())
}
async fn drive_pass(
&self,
execution_id: &str,
options: CodeModeRunOptions,
) -> Result<ExecutionState, String> {
let state = self.require(execution_id).await?;
if matches!(
state.status,
ExecutionStatus::Completed
| ExecutionStatus::Error
| ExecutionStatus::Rejected
| ExecutionStatus::RolledBack
| ExecutionStatus::Cancelled
) {
return Ok(state);
}
let parent = options.telemetry_context.clone();
async {
let workflow = state
.trace
.as_ref()
.and_then(|trace| trace.workflow.clone())
.or(options.workflow.clone());
let mut observation = crate::telemetry::Observation::pass(&state, workflow.as_ref());
if let Some((root, parent, definition)) =
self.runtime.workflow_lineage(execution_id).await?
{
observation.lineage(&root, parent.as_deref(), definition.as_ref());
}
if let Some(trace) = observation.trace(workflow) {
self.runtime
.record_trace(execution_id, trace)
.await
.map_err(|error| error.to_string())?;
}
let mut options = options;
options.telemetry_context = observation.context();
let cancellation = options.cancellation.clone();
let result = self
.drive_pass_inner(execution_id, state, options)
.with_context(observation.context())
.await;
observation.finish(if cancellation.is_cancelled() {
"cancelled"
} else {
result
.as_ref()
.map(|state| crate::telemetry::outcome(state.status))
.unwrap_or("error")
});
result
}
.with_context(parent)
.await
}
async fn drive_pass_inner(
&self,
execution_id: &str,
state: ExecutionState,
options: CodeModeRunOptions,
) -> Result<ExecutionState, String> {
let context = self.context(execution_id, options);
let cancellation = context.control.cancellation.clone();
self.contexts
.lock()
.await
.insert(execution_id.to_string(), context.clone());
let session = match self.session_with_context(execution_id, context).await {
Ok(session) => session,
Err(error) => {
self.contexts.lock().await.remove(execution_id);
return Err(error);
}
};
let descriptions = session.descriptions();
let execution = self.executor.execute(
&state.code,
&descriptions,
execution_id,
Arc::new(ExecutionHost::new(
Arc::clone(&session),
Arc::clone(&self.clock),
)),
);
tokio::pin!(execution);
let response = tokio::select! {
_ = cancellation.cancelled() => None,
response = &mut execution => Some(response),
};
self.contexts.lock().await.remove(execution_id);
let Some(response) = response else {
self.runtime
.cancel(execution_id, self.clock.now_ms())
.await
.map_err(|error| error.to_string())?;
session.pass_ended("cancelled").await;
session.execution_ended("cancelled").await;
return self.require(execution_id).await;
};
let response = match response {
Ok(response) => response,
Err(error) => {
self.runtime
.fail(execution_id, error, Vec::new(), self.clock.now_ms())
.await
.map_err(|error| error.to_string())?;
session.pass_ended("error").await;
session.execution_ended("error").await;
return self.require(execution_id).await;
}
};
let current = self.require(execution_id).await?;
if current.status == ExecutionStatus::Paused {
session.pass_ended("paused").await;
return Ok(current);
}
if current.status == ExecutionStatus::Error {
session.pass_ended("error").await;
session.execution_ended("error").await;
return Ok(current);
}
if current.status == ExecutionStatus::Cancelled {
session.pass_ended("cancelled").await;
session.execution_ended("cancelled").await;
return Ok(current);
}
if let Some(error) = response.error {
self.runtime
.fail(execution_id, error, response.logs, self.clock.now_ms())
.await
.map_err(|error| error.to_string())?;
session.pass_ended("error").await;
session.execution_ended("error").await;
} else {
let value = response.result.unwrap_or(Value::Null);
if let Err(error) = self.runtime.workflow_output(execution_id, &value).await {
self.runtime
.fail(execution_id, error, response.logs, self.clock.now_ms())
.await
.map_err(|e| e.to_string())?;
session.pass_ended("error").await;
session.execution_ended("error").await;
return self.require(execution_id).await;
}
match self
.runtime
.workflow_finish(execution_id, self.clock.now_ms())
.await
{
Ok(true) => {
session.pass_ended("paused").await;
return self.require(execution_id).await;
}
Err(error) => {
self.runtime
.fail(execution_id, error, response.logs, self.clock.now_ms())
.await
.map_err(|e| e.to_string())?;
session.pass_ended("error").await;
session.execution_ended("error").await;
return self.require(execution_id).await;
}
Ok(false) => {}
}
self.runtime
.complete(execution_id, value, response.logs, self.clock.now_ms())
.await
.map_err(|error| error.to_string())?;
session.pass_ended("completed").await;
session.execution_ended("completed").await;
}
self.require(execution_id).await
}
async fn session(&self, execution_id: &str) -> Result<Arc<DispatchSession>, String> {
let context = self.active_context(execution_id).await?;
self.session_with_context(execution_id, context).await
}
async fn active_context(&self, execution_id: &str) -> Result<ToolContext, String> {
self.contexts
.lock()
.await
.get(execution_id)
.cloned()
.ok_or_else(|| format!("Execution \"{execution_id}\" does not have an active pass"))
}
async fn session_with_context(
&self,
execution_id: &str,
context: ToolContext,
) -> Result<Arc<DispatchSession>, String> {
let state = self.require(execution_id).await?;
let descriptions = match state.capabilities {
Some(capabilities) => capabilities.connectors,
None => self.namespace_stubs(),
};
Ok(Arc::new(
DispatchSession::new_with_descriptions_and_context(
Arc::clone(&self.runtime),
context,
self.connectors.clone(),
descriptions,
)
.await?,
))
}
fn context(&self, execution_id: &str, options: CodeModeRunOptions) -> ToolContext {
ToolContext {
call: None,
execution_id: execution_id.to_string(),
control: ToolCallControl {
cancellation: options.cancellation,
events: Some(Arc::new(RuntimeEventSink {
runtime: Arc::clone(&self.runtime),
execution_id: execution_id.to_string(),
clock: Arc::clone(&self.clock),
})),
},
request: options.request,
telemetry_context: options.telemetry_context,
}
}
async fn require(&self, execution_id: &str) -> Result<ExecutionState, String> {
self.runtime
.execution(execution_id)
.await
.map_err(|error| error.to_string())?
.ok_or_else(|| format!("Execution \"{execution_id}\" not found"))
}
async fn connector(&self, name: &str) -> Result<Option<&Arc<dyn Connector>>, String> {
for connector in &self.connectors {
if connector.describe().await?.name == name {
return Ok(Some(connector));
}
}
Ok(None)
}
async fn notify_execution_end(&self, execution_id: &str, status: &str) {
for connector in &self.connectors {
connector.execution_ended(execution_id, status).await;
}
}
}
#[cfg(test)]
mod tests {
use std::sync::atomic::{AtomicUsize, Ordering};
use serde_json::json;
use tokio::sync::Notify;
use super::*;
use crate::{
ConnectorDescription, ConnectorTool, ExecuteResult, MemoryStore, ReplayPolicy,
ToolAnnotations, ToolPolicy,
};
struct TestConnector {
calls: AtomicUsize,
ended: Mutex<Vec<String>>,
started: Notify,
release: Notify,
blocked: bool,
}
impl TestConnector {
fn new(blocked: bool) -> Self {
Self {
calls: AtomicUsize::new(0),
ended: Mutex::new(Vec::new()),
started: Notify::new(),
release: Notify::new(),
blocked,
}
}
}
#[async_trait]
impl Connector for TestConnector {
fn name(&self) -> &str {
"test"
}
async fn describe(&self) -> Result<ConnectorDescription, String> {
Ok(ConnectorDescription {
name: "test".to_string(),
instructions: None,
tools: vec![ConnectorTool {
name: "run".to_string(),
description: None,
input_schema: json!({"type": "object"}),
output_schema: Some(json!({"type": "integer"})),
instructions: None,
examples: Vec::new(),
annotations: ToolAnnotations {
read_only: Some(true),
..ToolAnnotations::default()
},
policy: ToolPolicy {
requires_approval: false,
replay: ReplayPolicy::Log,
},
}],
})
}
async fn execute(
&self,
_method: &str,
_arguments: Value,
_context: &ToolContext,
) -> Result<Value, String> {
self.calls.fetch_add(1, Ordering::SeqCst);
self.started.notify_one();
if self.blocked {
self.release.notified().await;
}
Ok(json!(42))
}
async fn execution_ended(&self, _execution_id: &str, status: &str) {
self.ended.lock().await.push(status.to_string());
}
}
struct HostExecutor;
#[async_trait(?Send)]
impl CodeExecutor for HostExecutor {
async fn execute(
&self,
_code: &str,
_connectors: &[ConnectorDescription],
_execution_id: &str,
host: Arc<ExecutionHost>,
) -> Result<ExecuteResult, String> {
let response = host.call(0, "test", "run", json!({})).await;
Ok(ExecuteResult {
result: response.result,
error: response.message,
logs: Vec::new(),
})
}
}
#[tokio::test(flavor = "current_thread")]
async fn dispatch_requires_an_active_pass() {
let connector = Arc::new(TestConnector::new(false));
let code_mode = CodeMode::new(
Arc::new(MemoryStore::default()),
HostExecutor,
vec![connector.clone()],
);
let state = code_mode.start("ignored").await.unwrap();
let error = code_mode
.dispatch(DispatchRequest::Call {
execution_id: state.id.clone(),
seq: 0,
connector: "test".to_string(),
method: "run".to_string(),
arguments: json!({}),
})
.await
.unwrap_err();
assert!(error.contains("active pass"));
for request in [
DispatchRequest::LoadCheckpoint {
execution_id: state.id.clone(),
},
DispatchRequest::SaveCheckpoint {
execution_id: state.id.clone(),
checkpoint: crate::ExecutionCheckpoint {
identity: "fixture".into(),
bytes: vec![1, 2],
},
},
] {
assert!(
code_mode
.dispatch(request)
.await
.unwrap_err()
.contains("active pass")
);
}
assert_eq!(connector.calls.load(Ordering::SeqCst), 0);
assert_eq!(
code_mode.execution(&state.id).await.unwrap().status,
ExecutionStatus::Running
);
}
#[tokio::test(flavor = "current_thread")]
async fn cancelling_an_idle_execution_ends_connector_lifecycle_once() {
let connector = Arc::new(TestConnector::new(false));
let code_mode = CodeMode::new(
Arc::new(MemoryStore::default()),
HostExecutor,
vec![connector.clone()],
);
let state = code_mode.start("ignored").await.unwrap();
code_mode.cancel(&state.id).await.unwrap();
code_mode.cancel(&state.id).await.unwrap();
assert_eq!(&*connector.ended.lock().await, &["cancelled"]);
}
#[tokio::test(flavor = "current_thread")]
async fn concurrent_drive_calls_execute_one_pass() {
let connector = Arc::new(TestConnector::new(true));
let code_mode = CodeMode::new(
Arc::new(MemoryStore::default()),
HostExecutor,
vec![connector.clone()],
);
let state = code_mode.start("ignored").await.unwrap();
let first = code_mode.drive_with(&state.id, CodeModeRunOptions::default());
let second = code_mode.drive_with(&state.id, CodeModeRunOptions::default());
let release = async {
connector.started.notified().await;
tokio::task::yield_now().await;
connector.release.notify_waiters();
};
let (first, second, ()) = tokio::join!(first, second, release);
assert_eq!(first.unwrap().status, ExecutionStatus::Completed);
assert_eq!(second.unwrap().status, ExecutionStatus::Completed);
assert_eq!(connector.calls.load(Ordering::SeqCst), 1);
}
#[tokio::test(flavor = "current_thread")]
async fn rollback_rejects_live_executions() {
let code_mode = CodeMode::new(
Arc::new(MemoryStore::default()),
HostExecutor,
vec![Arc::new(TestConnector::new(false))],
);
let state = code_mode.start("ignored").await.unwrap();
let error = code_mode.rollback(&state.id).await.unwrap_err();
assert!(error.contains("not rollback eligible"));
assert_eq!(
code_mode.execution(&state.id).await.unwrap().status,
ExecutionStatus::Running
);
}
}