Skip to main content

agentmux_srv/drone/executor/
retry.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Running a block again when it failed for a reason that is the world's, not
5//! its own (docs/specs/SPEC_DRONE_GENERAL_AUTOMATION_2026_11_11.md ยง3.4).
6//!
7//! A block opts in with `retry`: a number of retries (1 to 3), or
8//! `{ "max": 1 to 3, "backoff_seconds": 1 to 300 }`. The wait doubles each time
9//! from `backoff_seconds` (2 when not set) and never passes five minutes.
10//!
11//! Only **infrastructure** failures are retried: a network error, a 5xx or 429
12//! answer from an API, a provider's rate limit, a machine out of memory. A block
13//! that ran and failed on its own terms (a bad reducer, a refused URL, a
14//! timeout, an agent that said `failed`) is never run again, because running
15//! it again would only do the same thing, or do it twice.
16
17use std::time::Duration;
18
19use serde_json::Value;
20
21use crate::drone::types::{BlockKind, FlowNode};
22
23/// The most times a block is run again.
24pub(super) const MAX_RETRIES: u32 = 3;
25const DEFAULT_BACKOFF_SECONDS: u64 = 2;
26const MAX_BACKOFF_SECONDS: u64 = 300;
27
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29pub(super) struct Retry {
30    pub(super) max: u32,
31    pub(super) backoff: Duration,
32}
33
34/// A block's `retry`, when it has one.
35pub(super) fn retry_of(node: &FlowNode) -> Result<Option<Retry>, String> {
36    let (max, backoff) = match node.data.get("retry") {
37        None | Some(Value::Null) => return Ok(None),
38        Some(Value::Number(n)) => (n.as_u64(), Some(DEFAULT_BACKOFF_SECONDS)),
39        Some(Value::Object(o)) => {
40            let backoff = match o.get("backoff_seconds") {
41                None | Some(Value::Null) => Some(DEFAULT_BACKOFF_SECONDS),
42                Some(v) => v.as_u64(),
43            };
44            (o.get("max").and_then(Value::as_u64), backoff)
45        }
46        Some(_) => (None, None),
47    };
48    match (max, backoff) {
49        (Some(max), Some(secs)) if (1..=u64::from(MAX_RETRIES)).contains(&max) && (1..=MAX_BACKOFF_SECONDS).contains(&secs) => {
50            Ok(Some(Retry { max: max as u32, backoff: Duration::from_secs(secs) }))
51        }
52        _ => Err(format!(
53            "{}: retry must be a number of retries from 1 to {MAX_RETRIES}, or {{ \"max\": 1 to {MAX_RETRIES}, \"backoff_seconds\": 1 to {MAX_BACKOFF_SECONDS} }}",
54            node.id
55        )),
56    }
57}
58
59/// How long to wait before retry number `attempt` (1 is the first retry).
60pub(super) fn delay(retry: &Retry, attempt: u32) -> Duration {
61    let doubled = retry.backoff.saturating_mul(1u32 << attempt.saturating_sub(1).min(8));
62    doubled.min(Duration::from_secs(MAX_BACKOFF_SECONDS))
63}
64
65/// Whether the error a block gave is the world's doing.
66fn is_infrastructure(kind: BlockKind, error: &str) -> bool {
67    let lower = error.to_ascii_lowercase();
68    match kind {
69        // `blocks::api`: the request did not complete, or its body did not arrive.
70        BlockKind::Api => error.starts_with("request failed:") || error.starts_with("read body:"),
71        // `blocks::agent`: no memory to start another agent, or the provider is limiting requests.
72        BlockKind::Agent => lower.contains("memory full") || lower.contains("rate-limited") || lower.contains("rate limit"),
73        _ => false,
74    }
75}
76
77/// Whether a block that finished gave an answer that says the other side was
78/// not ready: an API's 429 or 5xx.
79fn is_infrastructure_output(kind: BlockKind, output: &Value) -> bool {
80    kind == BlockKind::Api && output.get("status").and_then(Value::as_u64).is_some_and(|s| s == 429 || (500..600).contains(&s))
81}
82
83/// Whether to run the block again after `result`, having run it `ran` times.
84pub(super) fn again(retry: Option<Retry>, kind: BlockKind, result: &Result<Value, String>, ran: u32) -> bool {
85    let Some(retry) = retry else { return false };
86    if ran > retry.max {
87        return false;
88    }
89    match result {
90        Err(e) => is_infrastructure(kind, e),
91        Ok(output) => is_infrastructure_output(kind, output),
92    }
93}
94
95#[cfg(test)]
96mod tests {
97    use serde_json::json;
98
99    use super::*;
100    use crate::drone::types::NodePosition;
101
102    fn node(retry: Value) -> FlowNode {
103        FlowNode { id: "a".to_string(), position: NodePosition::default(), data: json!({ "kind": "api", "retry": retry }), node_type: None }
104    }
105
106    #[test]
107    fn a_retry_is_a_count_or_a_count_with_a_backoff() {
108        assert_eq!(retry_of(&node(json!(2))).unwrap(), Some(Retry { max: 2, backoff: Duration::from_secs(2) }));
109        assert_eq!(retry_of(&node(json!({ "max": 3, "backoff_seconds": 10 }))).unwrap(), Some(Retry { max: 3, backoff: Duration::from_secs(10) }));
110        assert_eq!(retry_of(&node(json!({ "max": 1 }))).unwrap(), Some(Retry { max: 1, backoff: Duration::from_secs(2) }));
111        assert_eq!(retry_of(&node(Value::Null)).unwrap(), None);
112        for bad in [json!(0), json!(4), json!(-1), json!(1.5), json!("2"), json!(true), json!({}), json!({ "max": 2, "backoff_seconds": 0 }), json!({ "max": 2, "backoff_seconds": 301 })] {
113            let e = retry_of(&node(bad.clone())).unwrap_err();
114            assert!(e.contains("retry must be a number of retries from 1 to 3"), "{bad}: {e}");
115        }
116    }
117
118    #[test]
119    fn the_wait_doubles_and_stops_at_five_minutes() {
120        let r = Retry { max: 3, backoff: Duration::from_secs(10) };
121        let waits: Vec<u64> = (1..=3).map(|n| delay(&r, n).as_secs()).collect();
122        assert_eq!(waits, [10, 20, 40]);
123        let long = Retry { max: 3, backoff: Duration::from_secs(300) };
124        assert_eq!(delay(&long, 3), Duration::from_secs(300));
125    }
126
127    #[test]
128    fn only_the_worlds_failures_are_run_again() {
129        let one = Some(Retry { max: 2, backoff: Duration::from_secs(1) });
130        let api_err = |e: &str| Err::<Value, String>(e.to_string());
131        assert!(again(one, BlockKind::Api, &api_err("request failed: connection reset"), 1));
132        assert!(again(one, BlockKind::Api, &api_err("read body: error decoding"), 1));
133        assert!(!again(one, BlockKind::Api, &api_err("host `localhost` is not allowed"), 1), "a refused URL stays refused");
134        assert!(!again(one, BlockKind::Api, &api_err("timed out after 30 seconds: operation timed out"), 1), "a timeout is not retried");
135        assert!(again(one, BlockKind::Api, &Ok(json!({ "status": 503 })), 1));
136        assert!(again(one, BlockKind::Api, &Ok(json!({ "status": 429 })), 1));
137        assert!(!again(one, BlockKind::Api, &Ok(json!({ "status": 404 })), 1), "a 404 is an answer");
138        assert!(!again(one, BlockKind::Api, &Ok(json!({ "status": 200 })), 1));
139        assert!(again(one, BlockKind::Agent, &api_err("agent block: agent run failed: Rate-limited by the provider"), 1));
140        assert!(again(one, BlockKind::Agent, &api_err("agent block: memory full: 1 GB free"), 1));
141        assert!(!again(one, BlockKind::Agent, &api_err("agent block: agent run failed: it said failed"), 1), "a finished agent is not asked again");
142        assert!(!again(one, BlockKind::Message, &api_err("request failed: x"), 1), "only the blocks that know their failures");
143    }
144
145    #[test]
146    fn a_block_is_run_again_at_most_max_times_and_never_without_a_retry() {
147        let r = Some(Retry { max: 2, backoff: Duration::from_secs(1) });
148        let down = Err::<Value, String>("request failed: down".to_string());
149        assert!(again(r, BlockKind::Api, &down, 1), "first run failed: retry 1");
150        assert!(again(r, BlockKind::Api, &down, 2), "second run failed: retry 2");
151        assert!(!again(r, BlockKind::Api, &down, 3), "third run failed: that was the last");
152        assert!(!again(None, BlockKind::Api, &down, 1));
153    }
154}