use crate::{
CapabilitySnapshot, CodeModeRuntime, DispatchResponse, ExecutionState, ExecutionStatus, Snippet,
};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use sha2::{Digest, Sha256};
use std::collections::{BTreeMap, BTreeSet};
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct WorkflowLimits {
pub depth: u32,
pub admissions: u32,
pub concurrency: usize,
pub attempts: u32,
pub bytes: usize,
pub lifetime_ms: u64,
pub allow_publication: bool,
}
impl Default for WorkflowLimits {
fn default() -> Self {
Self {
depth: 32,
admissions: 256,
concurrency: 8,
attempts: 1024,
bytes: 32 * 1024 * 1024,
lifetime_ms: 300_000,
allow_publication: true,
}
}
}
impl WorkflowLimits {
pub fn check(&self) -> Result<(), String> {
if self.depth == 0
|| self.admissions == 0
|| self.concurrency == 0
|| self.attempts == 0
|| self.bytes == 0
|| self.lifetime_ms == 0
{
return Err("WORKFLOW_LIMITS: host limits must be finite and positive".into());
}
Ok(())
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct WorkflowDefinition {
pub source: String,
#[serde(default = "any_schema")]
pub input: Value,
#[serde(default = "any_schema")]
pub output: Value,
#[serde(default = "empty_object")]
pub bindings: Value,
}
fn any_schema() -> Value {
Value::Bool(true)
}
fn empty_object() -> Value {
json!({})
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct WorkflowReference {
pub store: String,
pub version: String,
pub member: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct WorkflowWait {
pub children: Vec<String>,
pub settle: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkflowChild {
pub id: String,
pub parent: String,
pub reference: Option<WorkflowReference>,
pub status: ExecutionStatus,
pub pending: Vec<u64>,
pub error: Option<String>,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub(crate) struct Catalog {
#[serde(default)]
abi: u32,
store: String,
definitions: BTreeMap<String, BTreeMap<String, WorkflowDefinition>>,
publications: BTreeMap<String, Publication>,
nodes: BTreeMap<String, Node>,
roots: BTreeMap<String, Root>,
receipts: BTreeMap<String, Receipt>,
scopes: BTreeMap<String, Scope>,
#[serde(default)]
owners: BTreeMap<String, BTreeSet<String>>,
#[serde(default)]
deleted: BTreeSet<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct Publication {
reference: WorkflowReference,
protected: bool,
at: u64,
#[serde(default)]
legacy: Option<Snippet>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct Root {
limits: WorkflowLimits,
deadline: u64,
admissions: u32,
attempts: u32,
bytes: usize,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct Node {
root: String,
parent: Option<String>,
reference: Option<WorkflowReference>,
depth: u32,
bound: bool,
scope: String,
released: BTreeSet<String>,
observed: bool,
#[serde(default)]
dependencies: BTreeSet<String>,
#[serde(default)]
checkpoint_bytes: usize,
#[serde(default)]
execution_bytes: usize,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct Scope {
owner: String,
closed: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct Receipt {
method: String,
arguments: Value,
result: Value,
}
fn digest(value: &impl Serialize) -> Result<String, String> {
Ok(format!(
"{:x}",
Sha256::digest(serde_json::to_vec(value).map_err(|e| e.to_string())?)
))
}
fn text<'a>(args: &'a Value, key: &str) -> Result<&'a str, String> {
args.get(key)
.and_then(Value::as_str)
.ok_or_else(|| format!("WORKFLOW_ARGUMENT: {key} must be a string"))
}
fn reference(value: &Value) -> Result<WorkflowReference, String> {
serde_json::from_value(value.get("__workflow_ref").unwrap_or(value).clone())
.map_err(|_| "WORKFLOW_REFERENCE: invalid workflow reference".into())
}
fn wire(reference: &WorkflowReference) -> Value {
json!({"__workflow_ref":reference})
}
fn run_wire(store: &str, id: &str) -> Value {
json!({"__workflow_run":{"store":store,"id":id}})
}
fn run_id<'a>(value: &'a Value, store: &str) -> Result<&'a str, String> {
let r = value.get("__workflow_run").unwrap_or(value);
if r["store"].as_str() != Some(store) {
return Err("WORKFLOW_REFERENCE: foreign run store".into());
}
text(r, "id")
}
fn result(value: Value) -> DispatchResponse {
DispatchResponse {
result: Some(value),
control: None,
message: None,
}
}
fn pause() -> DispatchResponse {
DispatchResponse {
result: None,
control: Some("pause".into()),
message: None,
}
}
impl Catalog {
fn member(&self, r: &WorkflowReference) -> Result<&WorkflowDefinition, String> {
if r.store != self.store {
return Err("WORKFLOW_REFERENCE: foreign definition store".into());
}
self.definitions
.get(&r.version)
.and_then(|bundle| bundle.get(&r.member))
.ok_or_else(|| "WORKFLOW_REFERENCE: released or unknown definition".into())
}
fn root(&self, id: &str, now: u64) -> Result<&Root, String> {
let node = self.nodes.get(id).ok_or("WORKFLOW_ROOT_MISSING")?;
let root = self.roots.get(&node.root).ok_or("WORKFLOW_ROOT_MISSING")?;
if now >= root.deadline {
return Err("WORKFLOW_DEADLINE: root deadline exhausted".into());
}
Ok(root)
}
fn insert_bundle(
&mut self,
bundle: BTreeMap<String, WorkflowDefinition>,
owner: &str,
) -> Result<Vec<WorkflowReference>, String> {
let version = digest(&(1u32, &bundle))?;
let refs = bundle
.keys()
.map(|member| WorkflowReference {
store: self.store.clone(),
version: version.clone(),
member: member.clone(),
})
.collect();
if !self.definitions.contains_key(&version) {
let bytes = serde_json::to_vec(&bundle)
.map_err(|e| e.to_string())?
.len();
let root_id = self.nodes[owner].root.clone();
let root = self
.roots
.get_mut(&root_id)
.ok_or("WORKFLOW_ROOT_MISSING")?;
if root.bytes.saturating_add(bytes) > root.limits.bytes {
return Err("WORKFLOW_BYTES: retained storage budget exhausted".into());
}
root.bytes += bytes;
self.definitions.insert(version, bundle);
}
Ok(refs)
}
fn validate_bindings(&self, value: &Value) -> Result<(), String> {
match value {
Value::Object(fields) if fields.contains_key("__workflow_ref") => {
self.member(&reference(value)?)?;
}
Value::Object(fields) => {
if fields.contains_key("__codemode_type") || fields.contains_key("__workflow_run") {
return Err(
"WORKFLOW_BINDINGS: only JSON data and workflow references are portable"
.into(),
);
}
for v in fields.values() {
self.validate_bindings(v)?;
}
}
Value::Array(values) => {
for v in values {
self.validate_bindings(v)?;
}
}
_ => {}
}
Ok(())
}
}
impl CodeModeRuntime {
async fn workflow_catalog(&self) -> Result<Catalog, String> {
let state = self.store.get_workflows().await?;
let mut c = match state {
None => Catalog {
store: self.store.workflow_identity().await?,
abi: 1,
..Default::default()
},
Some(v) => {
let c: Catalog =
serde_json::from_value(v).map_err(|e| format!("WORKFLOW_STORE: {e}"))?;
if c.abi != 1 {
return Err("WORKFLOW_ABI: incompatible workflow metadata".into());
}
c
}
};
for snippet in self.store.list_snippets().await? {
if c.publications.contains_key(&snippet.name) || c.deleted.contains(&snippet.name) {
continue;
}
if c.store.is_empty() {
c.store = digest(&(&snippet.name, snippet.saved_at))?;
c.abi = 1;
}
let bundle = BTreeMap::from([(
"main".into(),
WorkflowDefinition {
source: crate::normalize_code(&snippet.code),
input: snippet.input_schema.clone().unwrap_or(Value::Bool(true)),
output: Value::Bool(true),
bindings: json!({}),
},
)]);
let version = digest(&(1u32, &bundle))?;
c.definitions.insert(version.clone(), bundle);
c.publications.insert(
snippet.name.clone(),
Publication {
reference: WorkflowReference {
store: c.store.clone(),
version,
member: "main".into(),
},
protected: false,
at: snippet.saved_at,
legacy: Some(snippet),
},
);
}
Ok(c)
}
async fn save_workflows(&self, c: &Catalog) -> Result<(), String> {
let v = serde_json::to_value(c).map_err(|e| e.to_string())?;
if serde_json::to_vec(&v).map_err(|e| e.to_string())?.len() > 32_000_000 {
return Err(
"WORKFLOW_STORE_FULL: prune retained executions before further admission".into(),
);
}
self.store.put_workflows(&v).await
}
fn workflow_init(
&self,
c: &mut Catalog,
state: &ExecutionState,
now: u64,
) -> Result<(), String> {
if c.nodes.contains_key(&state.id) {
c.root(&state.id, now)?;
return Ok(());
}
self.workflow_limits.check()?;
if c.store.is_empty() {
c.store = digest(&(&state.id, now))?;
c.abi = 1;
}
c.roots.insert(
state.id.clone(),
Root {
limits: self.workflow_limits.clone(),
deadline: state
.created_at
.saturating_add(self.workflow_limits.lifetime_ms),
admissions: 0,
attempts: 0,
bytes: 0,
},
);
c.nodes.insert(
state.id.clone(),
Node {
root: state.id.clone(),
parent: None,
reference: None,
depth: 0,
bound: true,
scope: state.id.clone(),
released: BTreeSet::new(),
observed: false,
dependencies: BTreeSet::new(),
checkpoint_bytes: 0,
execution_bytes: 0,
},
);
Ok(())
}
pub async fn install_workflows(
&self,
definitions: BTreeMap<String, WorkflowDefinition>,
now: u64,
) -> Result<(), String> {
let _guard = self.workflow_gate.lock().await;
let mut c = match self.workflow_catalog().await {
Ok(catalog) => catalog,
Err(error) if definitions.is_empty() && error.contains("WORKFLOW_UNSUPPORTED") => {
return Ok(());
}
Err(error) => return Err(error),
};
if c.store.is_empty() {
c.store = digest(&(now, definitions.keys().collect::<Vec<_>>()))?;
c.abi = 1;
}
let removed: Vec<String> = c
.publications
.iter()
.filter(|(name, p)| p.protected && !definitions.contains_key(*name))
.map(|(name, _)| name.clone())
.collect();
for name in removed {
let p = c
.publications
.remove(&name)
.ok_or("WORKFLOW_PUBLICATION_MISSING")?;
if let Some(snippet) = p.legacy {
let bundle = BTreeMap::from([(
"main".into(),
WorkflowDefinition {
source: crate::normalize_code(&snippet.code),
input: snippet.input_schema.clone().unwrap_or(Value::Bool(true)),
output: Value::Bool(true),
bindings: json!({}),
},
)]);
let version = digest(&(1u32, &bundle))?;
c.definitions.insert(version.clone(), bundle);
c.publications.insert(
name,
Publication {
reference: WorkflowReference {
store: c.store.clone(),
version,
member: "main".into(),
},
protected: false,
at: snippet.saved_at,
legacy: Some(snippet),
},
);
}
}
for (name, definition) in definitions {
validate_definition(&definition, &[], false)?;
let bundle = BTreeMap::from([("main".into(), definition)]);
let version = digest(&(1u32, &bundle))?;
c.definitions.insert(version.clone(), bundle);
c.deleted.remove(&name);
let legacy = c.publications.get(&name).and_then(|p| p.legacy.clone());
c.publications.insert(
name,
Publication {
reference: WorkflowReference {
store: c.store.clone(),
version,
member: "main".into(),
},
protected: true,
at: now,
legacy,
},
);
}
self.save_workflows(&c).await
}
pub(crate) async fn workflow_publish_snippet(&self, snippet: &Snippet) -> Result<bool, String> {
let _guard = self.workflow_gate.lock().await;
let mut c = match self.workflow_catalog().await {
Ok(c) => c,
Err(e) if e == "WORKFLOW_UNSUPPORTED" => return Ok(false),
Err(e) => return Err(e),
};
validate_name(&snippet.name)?;
check_publication(&c, &snippet.name, None)?;
if c.store.is_empty() {
c.store = digest(&(&snippet.name, snippet.saved_at))?;
c.abi = 1;
}
let d = WorkflowDefinition {
source: crate::normalize_code(&snippet.code),
input: snippet.input_schema.clone().unwrap_or(Value::Bool(true)),
output: Value::Bool(true),
bindings: json!({}),
};
validate_definition(&d, &snippet.connectors, false)?;
let bundle = BTreeMap::from([("main".into(), d)]);
let version = digest(&(1u32, &bundle))?;
c.definitions.insert(version.clone(), bundle);
c.deleted.remove(&snippet.name);
c.publications.insert(
snippet.name.clone(),
Publication {
reference: WorkflowReference {
store: c.store.clone(),
version,
member: "main".into(),
},
protected: false,
at: snippet.saved_at,
legacy: Some(snippet.clone()),
},
);
self.sweep_catalog(&mut c).await?;
self.save_workflows(&c).await?;
Ok(true)
}
pub(crate) async fn workflow_snippets(&self) -> Result<Vec<Snippet>, String> {
let _guard = self.workflow_gate.lock().await;
let c = match self.workflow_catalog().await {
Ok(c) => c,
Err(e) if e == "WORKFLOW_UNSUPPORTED" => return Ok(Vec::new()),
Err(e) => return Err(e),
};
c.publications
.iter()
.filter(|(_, p)| !p.protected || p.legacy.is_some())
.map(|(name, p)| {
if let Some(s) = &p.legacy {
return Ok(s.clone());
}
let d = c.member(&p.reference)?;
Ok(Snippet {
name: name.clone(),
description: "Published callable workflow".into(),
code: format!(
"async input => await codemode.workflows.hydrate({})(input)",
wire(&p.reference)
),
saved_at: p.at,
input_schema: Some(d.input.clone()),
connectors: Vec::new(),
})
})
.collect()
}
pub(crate) async fn workflow_delete_snippet(&self, name: &str) -> Result<bool, String> {
let _guard = self.workflow_gate.lock().await;
let mut c = match self.workflow_catalog().await {
Ok(c) => c,
Err(e) if e == "WORKFLOW_UNSUPPORTED" => return Ok(false),
Err(e) => return Err(e),
};
check_publication(&c, name, None)?;
let removed = c.publications.remove(name).is_some();
c.deleted.insert(name.into());
if removed {
self.sweep_catalog(&mut c).await?;
self.save_workflows(&c).await?;
}
Ok(removed)
}
pub(crate) async fn workflow_call(
&self,
id: &str,
seq: u64,
method: &str,
args: Value,
now: u64,
) -> Result<DispatchResponse, String> {
let _guard = self.workflow_gate.lock().await;
let state = self
.store
.get_execution(id)
.await?
.ok_or("WORKFLOW_EXECUTION_MISSING")?;
if state.status != ExecutionStatus::Running {
return Ok(pause());
}
let mut c = self.workflow_catalog().await?;
self.workflow_init(&mut c, &state, now)?;
let key = format!("{id}:{seq}");
if let Some(receipt) = c.receipts.get(&key) {
if receipt.method != method || receipt.arguments != args {
return Err("WORKFLOW_DIVERGENCE: operation receipt differs".into());
}
return Ok(result(receipt.result.clone()));
}
let value = match method {
"define" | "bundle" => {
let bundle: BTreeMap<String, WorkflowDefinition> = if method == "define" {
BTreeMap::from([(
"main".into(),
serde_json::from_value(args["definition"].clone())
.map_err(|e| format!("WORKFLOW_DEFINITION: {e}"))?,
)])
} else {
serde_json::from_value(args["definitions"].clone())
.map_err(|e| format!("WORKFLOW_DEFINITION: {e}"))?
};
if bundle.is_empty() {
return Err("WORKFLOW_DEFINITION: empty bundle".into());
}
for definition in bundle.values() {
validate_definition(definition, &state.connectors, true)?;
c.validate_bindings(&definition.bindings)?;
}
let refs = c.insert_bundle(bundle, id)?;
if method == "define" {
wire(&refs[0])
} else {
Value::Object(refs.iter().map(|r| (r.member.clone(), wire(r))).collect())
}
}
"resolve" => {
let name = text(&args, "name")?;
if c.deleted.contains(name) {
return Err(format!("WORKFLOW_NOT_FOUND: {name}"));
}
let r = if let Some(p) = c.publications.get(name) {
p.reference.clone()
} else {
let s = self
.store
.get_snippet(name)
.await?
.ok_or_else(|| format!("WORKFLOW_NOT_FOUND: {name}"))?;
let d = WorkflowDefinition {
source: crate::normalize_code(&s.code),
input: s.input_schema.unwrap_or(Value::Bool(true)),
output: Value::Bool(true),
bindings: json!({}),
};
c.insert_bundle(BTreeMap::from([("main".into(), d)]), id)?
.remove(0)
};
if let Some(version) = args.get("version").and_then(Value::as_str)
&& r.version != version
{
return Err("WORKFLOW_VERSION: publication version differs".into());
}
wire(&r)
}
"inspect" => {
let r = reference(&args["handle"])?;
let d = c.member(&r)?;
json!({"reference":wire(&r),"input":d.input,"output":d.output,"types":format!("WorkflowHandle<{}, {}>",crate::json_schema_to_type(&d.input),crate::json_schema_to_type(&d.output))})
}
"bind" => {
let r = reference(&args["handle"])?;
let d = c.member(&r)?.clone();
let values = args["values"]
.as_object()
.ok_or("WORKFLOW_BIND: bound values must be an object")?;
c.validate_bindings(&args["values"])?;
let mut input = d.input.clone();
if let Some(required) = input.get_mut("required").and_then(Value::as_array_mut) {
required.retain(|v| !values.contains_key(v.as_str().unwrap_or("")));
}
if let Some(properties) = d.input.get("properties").and_then(Value::as_object) {
for (key, value) in values {
if let Some(schema) = properties.get(key) {
crate::workflow_schema::validate(schema, value)
.map_err(|e| format!("WORKFLOW_BIND: {}", e.join("; ")))?;
}
}
}
let bound=WorkflowDefinition {source:"async (input, bindings) => { for (const key of Object.keys(bindings.values)) { if (Object.prototype.hasOwnProperty.call(input, key)) throw new Error('WORKFLOW_BIND_OVERRIDE: bound input cannot be overridden'); } return await bindings.target({...input,...bindings.values}); }".into(),input,output:d.output,bindings:json!({"target":wire(&r),"values":values})};
wire(&c.insert_bundle(BTreeMap::from([("main".into(), bound)]), id)?[0])
}
"pipe" => {
let handles = args["handles"]
.as_array()
.ok_or("WORKFLOW_PIPE: expected handles")?;
if handles.is_empty() {
return Err("WORKFLOW_PIPE: expected at least one handle".into());
}
let refs = handles
.iter()
.map(reference)
.collect::<Result<Vec<_>, _>>()?;
let definitions = refs
.iter()
.map(|r| c.member(r).cloned())
.collect::<Result<Vec<_>, _>>()?;
for pair in definitions.windows(2) {
if schema_disjoint(&pair[0].output, &pair[1].input) {
return Err("WORKFLOW_SCHEMA_INCOMPATIBLE: pipe output and input have disjoint types".into());
}
}
let d=WorkflowDefinition {source:"async (input, bindings) => { let value=input; for (const handle of bindings.handles) value=await handle(value); return value; }".into(),input:definitions[0].input.clone(),output:definitions.last().unwrap().output.clone(),bindings:json!({"handles":refs.iter().map(wire).collect::<Vec<_>>()})};
let compatibility: Vec<_> = definitions
.windows(2)
.map(|pair| {
if pair[1].input == Value::Bool(true)
|| pair[0].output == Value::Bool(false)
|| pair[0].output == pair[1].input
{
"compatible"
} else {
"unknown"
}
})
.collect();
let mut value =
wire(&c.insert_bundle(BTreeMap::from([("main".into(), d)]), id)?[0]);
value["__workflow_compatibility"] = json!(compatibility);
value
}
"start" => {
let r = reference(&args["handle"])?;
let d = c.member(&r)?.clone();
let scope = args.get("scope").and_then(Value::as_str).unwrap_or(id);
check_scope(&c, id, scope)?;
if c.nodes[id].released.contains(&r.version) {
return Err("WORKFLOW_REFERENCE: handle released by this execution".into());
}
c.validate_bindings(&args["input"])?;
crate::workflow_schema::validate(&d.input, &args["input"])
.map_err(|e| format!("WORKFLOW_INPUT: {}", e.join("; ")))?;
let child_id = format!("child_{}", digest(&(id, seq))?);
if !c.nodes.contains_key(&child_id) {
let parent = c.nodes[id].clone();
let root = c
.roots
.get_mut(&parent.root)
.ok_or("WORKFLOW_ROOT_MISSING")?;
if parent.depth >= root.limits.depth {
return Err("WORKFLOW_DEPTH: recursive depth exhausted".into());
}
if root.admissions >= root.limits.admissions {
return Err("WORKFLOW_ADMISSIONS: root child budget exhausted".into());
}
let bytes = serde_json::to_vec(&args).map_err(|e| e.to_string())?.len();
if root.bytes.saturating_add(bytes) > root.limits.bytes {
return Err("WORKFLOW_BYTES: retained storage budget exhausted".into());
}
root.admissions += 1;
root.bytes += bytes;
c.nodes.insert(
child_id.clone(),
Node {
root: parent.root,
parent: Some(id.into()),
reference: Some(r.clone()),
depth: parent.depth + 1,
bound: false,
scope: scope.into(),
released: BTreeSet::new(),
observed: false,
dependencies: BTreeSet::new(),
checkpoint_bytes: 0,
execution_bytes: 0,
},
);
self.save_workflows(&c).await?; }
let mut dependencies = BTreeSet::new();
collect_references(&args["input"], &mut dependencies);
for version in &dependencies {
if !c.definitions.contains_key(version) {
return Err("WORKFLOW_REFERENCE: unknown input definition".into());
}
}
c.nodes
.get_mut(&child_id)
.ok_or("WORKFLOW_CHILD_MISSING")?
.dependencies = dependencies;
let code = definition_program(&c, &r, &args["input"])?;
match self.store.get_execution(&child_id).await? {
None if c.nodes[&child_id].bound => {
return Err("WORKFLOW_BOUND_CHILD_MISSING: reconciliation required".into());
}
None => {
self.begin_retained(
&code,
CapabilitySnapshot::new(
state
.capabilities
.as_ref()
.map(|s| s.connectors.clone())
.unwrap_or_default(),
)?,
now,
Some(
c.roots[&c.nodes[id].root]
.deadline
.saturating_add(86_400_000),
),
Some(child_id.clone()),
)
.await
.map_err(|e| e.to_string())?;
}
Some(child) if child.code != code => {
return Err("WORKFLOW_BOUND_CHILD_MISMATCH".into());
}
Some(_) => {}
}
c.nodes
.get_mut(&child_id)
.ok_or("WORKFLOW_CHILD_MISSING")?
.bound = true;
run_wire(&c.store, &child_id)
}
"join" => {
let runs = args["runs"]
.as_array()
.ok_or("WORKFLOW_ARGUMENT: runs must be an array")?;
let mut ids = Vec::new();
for run in runs {
let child = run_id(run, &c.store)?.to_string();
let node = c
.nodes
.get(&child)
.ok_or("WORKFLOW_REFERENCE: unknown run")?;
if node.root != c.nodes[id].root {
return Err("WORKFLOW_REFERENCE: run belongs to another root".into());
}
let mut ancestor = Some(id);
while let Some(a) = ancestor {
if a == child {
return Err("WORKFLOW_WAIT_CYCLE: cannot await self or ancestor".into());
}
ancestor = c.nodes.get(a).and_then(|n| n.parent.as_deref());
}
let mut pending = vec![child.clone()];
let mut visited = BTreeSet::new();
while let Some(next) = pending.pop() {
if next == id {
return Err(
"WORKFLOW_WAIT_CYCLE: wait graph would contain a cycle".into()
);
}
if visited.insert(next.clone())
&& let Some(wait) = self
.store
.get_execution(&next)
.await?
.and_then(|s| s.workflow_wait)
{
pending.extend(wait.children);
}
}
ids.push(child);
}
let settle = args["settle"].as_bool().unwrap_or(false);
let mut values = Vec::new();
let mut unfinished = false;
let mut failure = None;
for child in &ids {
let s = self
.store
.get_execution(child)
.await?
.ok_or("WORKFLOW_BOUND_CHILD_MISSING")?;
match s.status {
ExecutionStatus::Completed => values.push(if settle {
json!({"status":"fulfilled","value":s.result})
} else {
s.result.unwrap_or(Value::Null)
}),
ExecutionStatus::Running | ExecutionStatus::Paused => {
unfinished = true;
}
_ => {
let e = s
.error
.unwrap_or_else(|| format!("Child {child} {:?}", s.status));
if settle {
values.push(json!({"status":"rejected","reason":e}));
} else {
failure = Some(e);
}
}
}
}
if unfinished && (failure.is_none() || settle) {
self.save_workflows(&c).await?;
self.workflow_suspend(
id,
WorkflowWait {
children: ids,
settle,
},
now,
)
.await?;
return Ok(pause());
}
if failure.is_some() && !settle {
for child in &ids {
if !owned_descendant(&c, id, child) {
continue;
}
let s = self
.store
.get_execution(child)
.await?
.ok_or("WORKFLOW_BOUND_CHILD_MISSING")?;
if matches!(s.status, ExecutionStatus::Running | ExecutionStatus::Paused) {
self.cancel(child, now).await.map_err(|e| e.to_string())?;
}
}
}
for child in ids {
if let Some(n) = c.nodes.get_mut(&child) {
n.observed = true;
}
}
if let Some(e) = failure {
json!({"__workflow_error":e})
} else {
Value::Array(values)
}
}
"publish" => {
if !c.root(id, now)?.limits.allow_publication {
return Err("WORKFLOW_PERMISSION: publication disabled by host".into());
}
let name = text(&args, "name")?.to_string();
validate_name(&name)?;
let r = reference(&args["handle"])?;
c.member(&r)?;
check_publication(&c, &name, args.get("expectedVersion"))?;
c.deleted.remove(&name);
c.publications.insert(
name.clone(),
Publication {
reference: r.clone(),
protected: false,
at: now,
legacy: None,
},
);
json!({"name":name,"version":r.version,"handle":wire(&r)})
}
"delete" => {
if !c.root(id, now)?.limits.allow_publication {
return Err("WORKFLOW_PERMISSION: deletion disabled by host".into());
}
let name = text(&args, "name")?;
if args
.get("expectedVersion")
.and_then(Value::as_str)
.is_none()
{
return Err("WORKFLOW_VERSION: deletion requires expectedVersion".into());
}
check_publication(&c, name, args.get("expectedVersion"))?;
let removed = c.publications.remove(name).is_some();
c.deleted.insert(name.into());
json!(removed)
}
"release" => {
let r = reference(&args["handle"])?;
c.member(&r)?;
c.nodes
.get_mut(id)
.ok_or("WORKFLOW_ROOT_MISSING")?
.released
.insert(r.version.clone());
for (owner, versions) in &mut c.owners {
if owner == id || c.scopes.get(owner).is_some_and(|s| s.owner == id) {
versions.remove(&r.version);
}
}
Value::Null
}
"scope_open" => {
let scope = format!("scope_{}", digest(&(id, seq))?);
c.scopes.insert(
scope.clone(),
Scope {
owner: id.into(),
closed: false,
},
);
json!(scope)
}
"scope_close" => {
let scope = text(&args, "scope")?;
check_scope(&c, id, scope)?;
let children: Vec<String> = c
.nodes
.iter()
.filter(|(_, n)| n.parent.as_deref() == Some(id) && n.scope == scope && n.bound)
.map(|(id, _)| id.clone())
.collect();
let mut unfinished = false;
for child in &children {
let s = self
.store
.get_execution(child)
.await?
.ok_or("WORKFLOW_BOUND_CHILD_MISSING")?;
if matches!(s.status, ExecutionStatus::Running | ExecutionStatus::Paused) {
if args["failed"].as_bool().unwrap_or(false) {
self.cancel(child, now).await.map_err(|e| e.to_string())?;
} else {
unfinished = true;
}
}
}
if unfinished {
self.save_workflows(&c).await?;
self.workflow_suspend(
id,
WorkflowWait {
children,
settle: args["failed"].as_bool().unwrap_or(false),
},
now,
)
.await?;
return Ok(pause());
}
c.scopes
.get_mut(scope)
.ok_or("WORKFLOW_SCOPE_MISSING")?
.closed = true;
c.owners.remove(scope);
Value::Null
}
_ => return Err(format!("WORKFLOW_OPERATION: unsupported {method}")),
};
if matches!(method, "define" | "bundle" | "resolve" | "bind" | "pipe") {
let scope = args.get("scope").and_then(Value::as_str).unwrap_or(id);
check_scope(&c, id, scope)?;
let mut refs = BTreeSet::new();
collect_references(&value, &mut refs);
for version in &refs {
c.nodes
.get_mut(id)
.ok_or("WORKFLOW_ROOT_MISSING")?
.released
.remove(version);
}
c.owners.entry(scope.into()).or_default().extend(refs);
}
c.receipts.insert(
key,
Receipt {
method: method.into(),
arguments: args,
result: value.clone(),
},
);
self.sweep_catalog(&mut c).await?;
let root_id = c.nodes[id].root.clone();
let bytes = root_bytes(&c, &root_id)?;
let root = c.roots.get_mut(&root_id).ok_or("WORKFLOW_ROOT_MISSING")?;
if bytes > root.limits.bytes {
return Err("WORKFLOW_BYTES: retained storage budget exhausted".into());
}
root.bytes = bytes;
self.save_workflows(&c).await?;
Ok(result(value))
}
pub(crate) async fn workflow_sweep(&self) -> Result<(), String> {
let _guard = self.workflow_gate.lock().await;
let mut c = match self.workflow_catalog().await {
Ok(c) => c,
Err(e) if e == "WORKFLOW_UNSUPPORTED" => return Ok(()),
Err(e) => return Err(e),
};
if c.abi == 0 {
return Ok(());
}
self.sweep_catalog(&mut c).await?;
self.save_workflows(&c).await
}
async fn sweep_catalog(&self, c: &mut Catalog) -> Result<(), String> {
let mut missing = BTreeSet::new();
let mut terminal = BTreeSet::new();
for id in c.nodes.keys() {
match self.store.get_execution(id).await? {
None => {
missing.insert(id.clone());
}
Some(s)
if !matches!(s.status, ExecutionStatus::Running | ExecutionStatus::Paused) =>
{
terminal.insert(id.clone());
}
_ => {}
}
}
for id in &missing {
let node = &c.nodes[id];
if node.bound
&& node
.parent
.as_ref()
.is_some_and(|parent| !missing.contains(parent) && !terminal.contains(parent))
{
return Err("WORKFLOW_BOUND_CHILD_MISSING: reconciliation required".into());
}
}
let retained_roots: BTreeSet<String> = c
.nodes
.iter()
.filter(|(id, _)| !missing.contains(*id))
.map(|(_, node)| node.root.clone())
.collect();
missing.retain(|id| !retained_roots.contains(id));
for id in &missing {
c.nodes.remove(id);
c.owners.remove(id);
c.roots.remove(id);
}
for id in &terminal {
c.owners.remove(id);
}
for (scope, owner) in &c.scopes {
if owner.closed || missing.contains(&owner.owner) || terminal.contains(&owner.owner) {
c.owners.remove(scope);
}
}
let mut retained: BTreeSet<String> = c
.publications
.values()
.map(|p| p.reference.version.clone())
.collect();
for versions in c.owners.values() {
retained.extend(versions.iter().cloned());
}
for node in c.nodes.values() {
if let Some(r) = &node.reference {
retained.insert(r.version.clone());
}
retained.extend(node.dependencies.iter().cloned());
}
loop {
let before = retained.len();
for version in retained.clone() {
if let Some(bundle) = c.definitions.get(&version) {
for d in bundle.values() {
collect_references(&d.bindings, &mut retained);
}
}
}
if retained.len() == before {
break;
}
}
c.definitions
.retain(|version, _| retained.contains(version));
c.receipts
.retain(|key, _| !missing.iter().any(|id| key.starts_with(&format!("{id}:"))));
c.scopes.retain(|_, s| !missing.contains(&s.owner));
Ok(())
}
pub(crate) async fn workflow_lineage(
&self,
id: &str,
) -> Result<Option<(String, Option<String>, Option<WorkflowReference>)>, String> {
let _guard = self.workflow_gate.lock().await;
let c = match self.workflow_catalog().await {
Ok(c) => c,
Err(e) if e == "WORKFLOW_UNSUPPORTED" => return Ok(None),
Err(e) => return Err(e),
};
Ok(c.nodes.get(id).map(|node| {
(
node.root.clone(),
node.parent.clone(),
node.reference.clone(),
)
}))
}
pub(crate) async fn workflow_children(&self, id: &str) -> Result<Vec<WorkflowChild>, String> {
let _guard = self.workflow_gate.lock().await;
let c = match self.workflow_catalog().await {
Ok(c) => c,
Err(e) if e == "WORKFLOW_UNSUPPORTED" => return Ok(Vec::new()),
Err(e) => return Err(e),
};
let mut children = Vec::new();
for (child, node) in &c.nodes {
if owned_descendant(&c, id, child) && node.bound {
let state = self
.store
.get_execution(child)
.await?
.ok_or("WORKFLOW_BOUND_CHILD_MISSING")?;
children.push(WorkflowChild {
id: child.clone(),
parent: node.parent.clone().unwrap_or_default(),
reference: node.reference.clone(),
status: state.status,
pending: state
.log
.iter()
.filter(|e| e.state == crate::LogEntryState::Pending)
.map(|e| e.seq)
.collect(),
error: state.error,
});
}
}
Ok(children)
}
pub(crate) async fn workflow_admit_root(
&self,
id: &str,
now: u64,
) -> Result<Option<u64>, String> {
let _guard = self.workflow_gate.lock().await;
let mut c = match self.workflow_catalog().await {
Ok(c) => c,
Err(e) if e == "WORKFLOW_UNSUPPORTED" => return Ok(None),
Err(e) => return Err(e),
};
let state = self
.store
.get_execution(id)
.await?
.ok_or("WORKFLOW_EXECUTION_MISSING")?;
if !c.nodes.contains_key(id) {
self.workflow_init(&mut c, &state, now)?;
self.save_workflows(&c).await?;
}
Ok(Some(c.roots[&c.nodes[id].root].deadline))
}
pub(crate) async fn workflow_deadline(&self, id: &str, now: u64) -> Result<(), String> {
let _guard = self.workflow_gate.lock().await;
let c = match self.workflow_catalog().await {
Ok(c) => c,
Err(e) if e == "WORKFLOW_UNSUPPORTED" => return Ok(()),
Err(e) => return Err(e),
};
if c.nodes.contains_key(id) {
c.root(id, now)?;
}
Ok(())
}
pub(crate) async fn workflow_finish(&self, id: &str, now: u64) -> Result<bool, String> {
let _guard = self.workflow_gate.lock().await;
let c = match self.workflow_catalog().await {
Ok(c) => c,
Err(e) if e == "WORKFLOW_UNSUPPORTED" => return Ok(false),
Err(e) => return Err(e),
};
let children: Vec<String> = c
.nodes
.iter()
.filter(|(_, n)| n.parent.as_deref() == Some(id) && n.bound)
.map(|(id, _)| id.clone())
.collect();
let mut unfinished = false;
for child in &children {
let s = self
.store
.get_execution(child)
.await?
.ok_or("WORKFLOW_BOUND_CHILD_MISSING")?;
if matches!(s.status, ExecutionStatus::Running | ExecutionStatus::Paused) {
unfinished = true;
} else if s.status != ExecutionStatus::Completed && !c.nodes[child].observed {
return Err(format!(
"WORKFLOW_CHILD_FAILED: {child}: {}",
s.error.unwrap_or_default()
));
}
}
if unfinished {
self.workflow_suspend(
id,
WorkflowWait {
children,
settle: false,
},
now,
)
.await?;
}
Ok(unfinished)
}
async fn workflow_suspend(&self, id: &str, wait: WorkflowWait, now: u64) -> Result<(), String> {
let _guard = self.gate.lock().await;
let mut s = self
.store
.get_execution(id)
.await?
.ok_or("WORKFLOW_EXECUTION_MISSING")?;
if s.status == ExecutionStatus::Running {
s.status = ExecutionStatus::Paused;
s.workflow_wait = Some(wait);
s.updated_at = now;
self.store.put_execution(&s).await?;
}
Ok(())
}
pub(crate) async fn workflow_wake(&self, id: &str, now: u64) -> Result<(), String> {
let _guard = self.gate.lock().await;
let mut s = self
.store
.get_execution(id)
.await?
.ok_or("WORKFLOW_EXECUTION_MISSING")?;
if s.workflow_wait.take().is_some() && s.status == ExecutionStatus::Paused {
s.status = ExecutionStatus::Running;
s.updated_at = now;
self.store.put_execution(&s).await?;
}
Ok(())
}
pub(crate) async fn workflow_nodes(
&self,
id: &str,
) -> Result<Option<(String, usize, Vec<(String, Option<String>)>)>, String> {
let _guard = self.workflow_gate.lock().await;
let c = match self.workflow_catalog().await {
Ok(c) => c,
Err(e) if e == "WORKFLOW_UNSUPPORTED" => return Ok(None),
Err(e) => return Err(e),
};
let Some(n) = c.nodes.get(id) else {
return Ok(None);
};
Ok(Some((
n.root.clone(),
c.roots[&n.root].limits.concurrency,
c.nodes
.iter()
.filter(|(_, v)| v.root == n.root && v.bound)
.map(|(id, n)| (id.clone(), n.parent.clone()))
.collect(),
)))
}
pub(crate) async fn workflow_checkpoint_bytes(
&self,
id: &str,
checkpoint: &crate::ExecutionCheckpoint,
) -> Result<(), String> {
let _guard = self.workflow_gate.lock().await;
let mut c = match self.workflow_catalog().await {
Ok(c) => c,
Err(e) if e == "WORKFLOW_UNSUPPORTED" => return Ok(()),
Err(e) => return Err(e),
};
let Some(node) = c.nodes.get_mut(id) else {
return Ok(());
};
node.checkpoint_bytes = serde_json::to_vec(checkpoint)
.map_err(|e| e.to_string())?
.len();
node.execution_bytes = match self.store.get_execution(id).await? {
Some(state) => serde_json::to_vec(&state).map_err(|e| e.to_string())?.len(),
None => return Err("WORKFLOW_EXECUTION_MISSING".into()),
};
let root = node.root.clone();
check_retained_bytes(&mut c, &root)?;
self.save_workflows(&c).await
}
pub(crate) async fn workflow_output(&self, id: &str, value: &Value) -> Result<(), String> {
let _guard = self.workflow_gate.lock().await;
let mut c = match self.workflow_catalog().await {
Ok(c) => c,
Err(e) if e == "WORKFLOW_UNSUPPORTED" => return Ok(()),
Err(e) => return Err(e),
};
if let Some(r) = c.nodes.get(id).and_then(|n| n.reference.as_ref()) {
crate::workflow_schema::validate(&c.member(r)?.output, value)
.map_err(|e| format!("WORKFLOW_OUTPUT: {}", e.join("; ")))?;
}
if let Some(node) = c.nodes.get_mut(id) {
let state = self
.store
.get_execution(id)
.await?
.ok_or("WORKFLOW_EXECUTION_MISSING")?;
node.execution_bytes = serde_json::to_vec(&state)
.map_err(|e| e.to_string())?
.len()
.saturating_add(serde_json::to_vec(value).map_err(|e| e.to_string())?.len());
let root = node.root.clone();
check_retained_bytes(&mut c, &root)?;
self.save_workflows(&c).await?;
}
Ok(())
}
pub(crate) async fn workflow_charge(&self, id: &str, now: u64) -> Result<(), String> {
let _guard = self.workflow_gate.lock().await;
let mut c = match self.workflow_catalog().await {
Ok(c) => c,
Err(e) if e == "WORKFLOW_UNSUPPORTED" => return Ok(()),
Err(e) => return Err(e),
};
if let Some(node) = c.nodes.get(id) {
c.root(id, now)?;
let root = c.roots.get_mut(&node.root).ok_or("WORKFLOW_ROOT_MISSING")?;
if root.attempts >= root.limits.attempts {
return Err("WORKFLOW_ATTEMPTS: root tool budget exhausted".into());
}
root.attempts += 1;
self.save_workflows(&c).await?;
}
Ok(())
}
}
fn check_scope(c: &Catalog, id: &str, scope: &str) -> Result<(), String> {
if scope == id {
return Ok(());
}
match c.scopes.get(scope) {
Some(s) if s.owner == id && !s.closed => Ok(()),
_ => Err("WORKFLOW_SCOPE: closed or foreign scope".into()),
}
}
fn validate_name(name: &str) -> Result<(), String> {
if name.is_empty()
|| name.len() > 128
|| !name
.chars()
.all(|c| c.is_ascii_alphanumeric() || "-_.".contains(c))
{
Err("WORKFLOW_NAME: use 1-128 ASCII letters, digits, -, _, or .".into())
} else {
Ok(())
}
}
fn check_publication(c: &Catalog, name: &str, expected: Option<&Value>) -> Result<(), String> {
if c.publications.get(name).is_some_and(|p| p.protected) {
return Err("WORKFLOW_PROTECTED: shipped publication".into());
}
if let Some(expected) = expected {
let actual = c
.publications
.get(name)
.map(|p| p.reference.version.as_str());
if (expected.is_null() && actual.is_some())
|| (!expected.is_null() && expected.as_str() != actual)
{
return Err("WORKFLOW_VERSION: publication changed".into());
}
}
Ok(())
}
fn definition_program(c: &Catalog, r: &WorkflowReference, input: &Value) -> Result<String, String> {
let d = c.member(r)?;
let peers: Value = Value::Object(
c.definitions[&r.version]
.keys()
.map(|member| {
(
member.clone(),
wire(&WorkflowReference {
member: member.clone(),
..r.clone()
}),
)
})
.collect(),
);
Ok(format!(
"async () => {{ const w = codemode.workflows; return await ({})(w.hydrate({}), w.hydrate({}), w.hydrate({}), w.hydrate({})); }}",
d.source,
input,
d.bindings,
wire(r),
peers
))
}
fn validate_definition(
d: &WorkflowDefinition,
connectors: &[String],
lexical: bool,
) -> Result<(), String> {
crate::workflow_schema::check_supported(&d.input)
.map_err(|e| format!("WORKFLOW_SCHEMA: {}", e.join("; ")))?;
crate::workflow_schema::check_supported(&d.output)
.map_err(|e| format!("WORKFLOW_SCHEMA: {}", e.join("; ")))?;
if !lexical {
return Ok(());
}
let source = format!("({});", d.source);
let allocator = oxc_allocator::Allocator::default();
let parsed = oxc_parser::Parser::new(&allocator, &source, oxc_span::SourceType::mjs()).parse();
if !parsed.errors.is_empty() {
return Err(format!("WORKFLOW_SYNTAX: {}", parsed.errors[0]));
}
if !matches!(parsed.program.body.first(),Some(oxc_ast::ast::Statement::ExpressionStatement(statement)) if statement.expression.get_inner_expression().is_function())
{
return Err("WORKFLOW_DEFINITION: source must be a function expression".into());
}
let semantics = oxc_semantic::SemanticBuilder::new()
.with_check_syntax_error(true)
.build(&parsed.program);
if !semantics.errors.is_empty() {
return Err(format!("WORKFLOW_SYNTAX: {}", semantics.errors[0]));
}
const GLOBALS: &[&str] = &[
"codemode",
"console",
"Promise",
"Error",
"TypeError",
"RangeError",
"JSON",
"Object",
"Array",
"String",
"Number",
"Boolean",
"BigInt",
"Uint8Array",
"Math",
"Symbol",
"Map",
"Set",
"Date",
"RegExp",
"undefined",
"NaN",
"Infinity",
"parseInt",
"parseFloat",
"isNaN",
"isFinite",
];
for (name, _) in semantics.semantic.scoping().root_unresolved_references() {
if !GLOBALS.contains(name) && !connectors.iter().any(|c| c == name) {
return Err(format!(
"WORKFLOW_CAPTURE: unresolved identifier {name}; pass explicit bindings"
));
}
}
Ok(())
}
fn schema_disjoint(output: &Value, input: &Value) -> bool {
fn types(value: &Value) -> Option<BTreeSet<String>> {
match value.get("type")? {
Value::String(t) => Some(BTreeSet::from([t.clone()])),
Value::Array(a) => Some(
a.iter()
.filter_map(Value::as_str)
.map(str::to_string)
.collect(),
),
_ => None,
}
}
match (types(output), types(input)) {
(Some(a), Some(b)) => !a.iter().any(|x| {
b.iter().any(|y| {
x == y || (x == "integer" && y == "number") || (x == "number" && y == "integer")
})
}),
_ => false,
}
}
fn collect_references(value: &Value, refs: &mut BTreeSet<String>) {
match value {
Value::Object(fields) => {
if let Some(version) = fields
.get("__workflow_ref")
.and_then(|r| r.get("version"))
.and_then(Value::as_str)
{
refs.insert(version.into());
}
for child in fields.values() {
collect_references(child, refs);
}
}
Value::Array(values) => {
for child in values {
collect_references(child, refs);
}
}
_ => {}
}
}
fn owned_descendant(c: &Catalog, owner: &str, child: &str) -> bool {
let mut at = c.nodes.get(child).and_then(|node| node.parent.as_deref());
while let Some(id) = at {
if id == owner {
return true;
}
at = c.nodes.get(id).and_then(|node| node.parent.as_deref());
}
false
}
fn root_bytes(c: &Catalog, root: &str) -> Result<usize, String> {
let nodes: BTreeMap<_, _> = c.nodes.iter().filter(|(_, n)| n.root == root).collect();
let receipts: BTreeMap<_, _> = c
.receipts
.iter()
.filter(|(key, _)| nodes.keys().any(|id| key.starts_with(&format!("{id}:"))))
.collect();
let scopes: BTreeMap<_, _> = c
.scopes
.iter()
.filter(|(_, s)| nodes.contains_key(&s.owner))
.collect();
let owners: BTreeMap<_, _> = c
.owners
.iter()
.filter(|(id, _)| nodes.contains_key(id) || scopes.contains_key(id))
.collect();
let mut versions = BTreeSet::new();
for n in nodes.values() {
if let Some(r) = &n.reference {
versions.insert(r.version.clone());
}
versions.extend(n.dependencies.iter().cloned());
}
for refs in owners.values() {
versions.extend(refs.iter().cloned());
}
loop {
let before = versions.len();
for version in versions.clone() {
if let Some(bundle) = c.definitions.get(&version) {
for d in bundle.values() {
collect_references(&d.bindings, &mut versions);
}
}
}
if before == versions.len() {
break;
}
}
let definitions: BTreeMap<_, _> = c
.definitions
.iter()
.filter(|(version, _)| versions.contains(*version))
.collect();
let retained = nodes.values().fold(0usize, |bytes, node| {
bytes
.saturating_add(node.checkpoint_bytes)
.saturating_add(node.execution_bytes)
});
serde_json::to_vec(&(nodes, receipts, scopes, owners, definitions))
.map(|bytes| bytes.len().saturating_add(retained))
.map_err(|e| e.to_string())
}
fn check_retained_bytes(c: &mut Catalog, root: &str) -> Result<(), String> {
let bytes = root_bytes(c, root)?;
let budget = c.roots.get_mut(root).ok_or("WORKFLOW_ROOT_MISSING")?;
if bytes > budget.limits.bytes {
return Err("WORKFLOW_BYTES: retained storage budget exhausted".into());
}
budget.bytes = bytes;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::MemoryStore;
use std::sync::Arc;
#[tokio::test]
async fn ancestor_and_sibling_wait_cycles_are_rejected() {
let store = Arc::new(MemoryStore::default());
let runtime = CodeModeRuntime::new(store);
let root = runtime.begin("return 1;", vec![], 100).await.unwrap();
let definition=runtime.workflow_call(&root,0,"define",json!({"definition":{"source":"async n=>n","input":true,"output":true,"bindings":{}}}),101).await.unwrap().result.unwrap();
let first = runtime
.workflow_call(
&root,
1,
"start",
json!({"handle":definition,"input":1}),
102,
)
.await
.unwrap()
.result
.unwrap();
let second = runtime
.workflow_call(
&root,
2,
"start",
json!({"handle":definition,"input":2}),
103,
)
.await
.unwrap()
.result
.unwrap();
let c = runtime.workflow_catalog().await.unwrap();
let a = run_id(&first, &c.store).unwrap();
let b = run_id(&second, &c.store).unwrap();
let ancestor = runtime
.workflow_call(
a,
0,
"join",
json!({"runs":[run_wire(&c.store,&root)]}),
104,
)
.await
.unwrap_err();
assert!(ancestor.contains("WORKFLOW_WAIT_CYCLE"), "{ancestor}");
let wait = runtime
.workflow_call(a, 1, "join", json!({"runs":[second]}), 105)
.await
.unwrap();
assert_eq!(wait.control.as_deref(), Some("pause"));
let sibling = runtime
.workflow_call(b, 0, "join", json!({"runs":[first]}), 106)
.await
.unwrap_err();
assert!(sibling.contains("WORKFLOW_WAIT_CYCLE"), "{sibling}");
}
}