Skip to main content

agentmux_srv/drone/executor/blocks/
join.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The Join block: where branches that split come together
5//! (docs/specs/SPEC_DRONE_GENERAL_AUTOMATION_2026_11_11.md ยง3.7).
6//!
7//! Block config (`node.data`):
8//!   * `mode`             `all` (default), `any` or `n_of_m`.
9//!   * `n`                with `n_of_m`, how many of the incoming branches must arrive.
10//!   * `on_branch_error`  `fail` (default): a branch that failed fails the run, as any
11//!                        block that failed does. `skip`: a branch that failed is left out,
12//!                        and the mode says whether the join still holds.
13//!
14//! A branch *arrives* when the edge into the join is taken. One that was not taken
15//! because its source did not run (the other side of a Condition) is *pruned*: it does
16//! not count for or against the join. One whose source failed is *failed*.
17//!
18//!   * `all`     holds when no branch failed: every branch that ran arrived.
19//!   * `any`     holds when at least one arrived.
20//!   * `n_of_m`  holds when at least `n` arrived.
21//!
22//! The join runs once its branches are decided, so `any` does not stop the slower
23//! branches: they have finished by then.
24
25use serde_json::{json, Map, Value};
26
27use crate::backend::storage::drone_types::FlowNode;
28
29/// When a join holds.
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub enum Mode {
32    All,
33    Any,
34    NOfM(usize),
35}
36
37/// What the block is set to.
38#[derive(Debug, Clone, Copy, PartialEq, Eq)]
39pub struct JoinSpec {
40    pub mode: Mode,
41    /// A branch that failed is left out instead of failing the run.
42    pub skip_failed: bool,
43}
44
45/// The block's settings, or what is wrong with them.
46pub fn parse(node: &FlowNode) -> Result<JoinSpec, String> {
47    let id = &node.id;
48    let text = |key: &str| node.data.get(key).and_then(Value::as_str).map(str::trim);
49    let mode = match text("mode").unwrap_or("all") {
50        "all" => Mode::All,
51        "any" => Mode::Any,
52        "n_of_m" => {
53            let n = node.data.get("n").and_then(Value::as_u64).filter(|n| *n >= 1).ok_or_else(|| format!("{id}: a Join with `n_of_m` needs `n`, how many branches must arrive (1 or more)"))?;
54            Mode::NOfM(usize::try_from(n).unwrap_or(usize::MAX))
55        }
56        other => return Err(format!("{id}: `mode` must be all, any or n_of_m, not {other:?}")),
57    };
58    if !matches!(mode, Mode::NOfM(_)) && node.data.get("n").is_some_and(|n| !n.is_null()) {
59        return Err(format!("{id}: `n` goes with `n_of_m`"));
60    }
61    let skip_failed = match text("on_branch_error").unwrap_or("fail") {
62        "fail" => false,
63        "skip" => true,
64        other => return Err(format!("{id}: `on_branch_error` must be fail or skip, not {other:?}")),
65    };
66    Ok(JoinSpec { mode, skip_failed })
67}
68
69/// The settings, and that the join can hold with the branches it has.
70pub fn check(node: &FlowNode, branches: usize) -> Result<(), String> {
71    let spec = parse(node)?;
72    if branches < 2 {
73        return Err(format!("{}: a Join brings branches together and has {branches} edge{} into it: it needs at least two", node.id, if branches == 1 { "" } else { "s" }));
74    }
75    if let Mode::NOfM(n) = spec.mode {
76        if n > branches {
77            return Err(format!("{}: `n` is {n}, but only {branches} branches lead to this Join", node.id));
78        }
79    }
80    Ok(())
81}
82
83/// How the branches into a join ended, each by the block it came from.
84#[derive(Debug, Default)]
85pub struct Branches {
86    pub arrived: Vec<(String, Value)>,
87    /// A branch whose source failed, with what it said.
88    pub failed: Vec<(String, String)>,
89    pub pruned: Vec<String>,
90}
91
92/// The join's output, or why it does not hold.
93pub fn evaluate(id: &str, spec: JoinSpec, branches: Branches) -> Result<Value, String> {
94    let Branches { arrived, failed, pruned } = branches;
95    let failures = || failed.iter().map(|(b, why)| format!("{b}: {why}")).collect::<Vec<_>>().join("; ");
96    if !failed.is_empty() && !spec.skip_failed {
97        return Err(format!("{id}: a branch failed ({})", failures()));
98    }
99    match spec.mode {
100        Mode::All if !failed.is_empty() => return Err(format!("{id}: every branch must arrive, and a branch failed ({})", failures())),
101        Mode::Any if arrived.is_empty() => return Err(format!("{id}: no branch arrived{}", if failed.is_empty() { String::new() } else { format!(" ({})", failures()) })),
102        Mode::NOfM(n) if arrived.len() < n => {
103            return Err(format!("{id}: {} of {n} branches arrived{}", arrived.len(), if failed.is_empty() { String::new() } else { format!(" ({})", failures()) }));
104        }
105        _ => {}
106    }
107    let outputs: Map<String, Value> = arrived.iter().cloned().collect();
108    let errors: Map<String, Value> = failed.iter().map(|(b, why)| (b.clone(), json!(why))).collect();
109    Ok(json!({
110        "arrived": arrived.len(),
111        "outputs": outputs,
112        "failed": failed.iter().map(|(b, _)| b.as_str()).collect::<Vec<_>>(),
113        "errors": errors,
114        "pruned": pruned,
115    }))
116}
117
118#[cfg(test)]
119mod tests {
120    use super::*;
121    use crate::drone::types::NodePosition;
122
123    fn join(data: Value) -> FlowNode {
124        let mut full = json!({ "kind": "join" });
125        full.as_object_mut().unwrap().extend(data.as_object().cloned().unwrap_or_default());
126        FlowNode { id: "j".to_string(), position: NodePosition::default(), data: full, node_type: None }
127    }
128
129    fn spec(mode: Mode, skip_failed: bool) -> JoinSpec {
130        JoinSpec { mode, skip_failed }
131    }
132
133    fn branches(arrived: &[&str], failed: &[&str], pruned: &[&str]) -> Branches {
134        Branches {
135            arrived: arrived.iter().map(|b| (b.to_string(), json!({ "value": b }))).collect(),
136            failed: failed.iter().map(|b| (b.to_string(), "boom".to_string())).collect(),
137            pruned: pruned.iter().map(|b| b.to_string()).collect(),
138        }
139    }
140
141    #[test]
142    fn a_join_is_all_of_its_branches_and_fails_on_a_failed_one_unless_told_otherwise() {
143        assert_eq!(parse(&join(json!({}))).unwrap(), spec(Mode::All, false));
144        assert_eq!(parse(&join(json!({ "mode": "any", "on_branch_error": "skip" }))).unwrap(), spec(Mode::Any, true));
145        assert_eq!(parse(&join(json!({ "mode": "n_of_m", "n": 2 }))).unwrap(), spec(Mode::NOfM(2), false));
146    }
147
148    #[test]
149    fn a_join_that_is_set_wrongly_says_what_to_fix() {
150        assert!(parse(&join(json!({ "mode": "first" }))).unwrap_err().contains("`mode` must be"));
151        assert!(parse(&join(json!({ "mode": "n_of_m" }))).unwrap_err().contains("needs `n`"));
152        assert!(parse(&join(json!({ "mode": "n_of_m", "n": 0 }))).unwrap_err().contains("needs `n`"));
153        assert!(parse(&join(json!({ "mode": "any", "n": 2 }))).unwrap_err().contains("goes with `n_of_m`"));
154        assert!(parse(&join(json!({ "on_branch_error": "ignore" }))).unwrap_err().contains("`on_branch_error` must be"));
155        assert!(check(&join(json!({})), 1).unwrap_err().contains("at least two"));
156        assert!(check(&join(json!({ "mode": "n_of_m", "n": 3 })), 2).unwrap_err().contains("only 2 branches"));
157        assert!(check(&join(json!({ "mode": "n_of_m", "n": 2 })), 3).is_ok());
158    }
159
160    #[test]
161    fn all_holds_when_no_branch_failed_and_a_pruned_one_does_not_count() {
162        let out = evaluate("j", spec(Mode::All, false), branches(&["a", "b"], &[], &["c"])).unwrap();
163        assert_eq!(out["arrived"], json!(2));
164        assert_eq!(out["outputs"]["a"], json!({ "value": "a" }));
165        assert_eq!(out["pruned"], json!(["c"]));
166        assert!(evaluate("j", spec(Mode::All, true), branches(&["a"], &["b"], &[])).unwrap_err().contains("every branch must arrive"));
167    }
168
169    #[test]
170    fn a_failed_branch_fails_the_join_unless_it_is_skipped() {
171        assert!(evaluate("j", spec(Mode::Any, false), branches(&["a"], &["b"], &[])).unwrap_err().contains("a branch failed (b: boom)"));
172        let out = evaluate("j", spec(Mode::Any, true), branches(&["a"], &["b"], &[])).unwrap();
173        assert_eq!(out["failed"], json!(["b"]));
174        assert_eq!(out["errors"]["b"], json!("boom"));
175    }
176
177    #[test]
178    fn any_needs_one_and_n_of_m_needs_n() {
179        assert!(evaluate("j", spec(Mode::Any, true), branches(&[], &["a", "b"], &[])).unwrap_err().contains("no branch arrived"));
180        assert!(evaluate("j", spec(Mode::NOfM(2), true), branches(&["a"], &["b"], &["c"])).unwrap_err().contains("1 of 2 branches arrived"));
181        assert!(evaluate("j", spec(Mode::NOfM(2), true), branches(&["a", "c"], &["b"], &[])).is_ok());
182    }
183}