Skip to main content

a2a_protocol_client/delegation/
resume.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Tom F. <[email protected]> (https://github.com/tomtom215)
3
4//! Getting a lost stream back, and picking a child up again (audit H4,
5//! ADR 0030).
6//!
7//! Until 2026-10-31 any end of a child's stream before the child settled, a
8//! reset connection, a proxy rollout or the idle timeout, was read as "the
9//! child is lost": the delegation cancelled it. The client already had what a
10//! resume needs (`EventStream::last_event_id`, `subscribe_to_task_from`, and
11//! servers that replay from a `Last-Event-ID`) and nothing used it, so one
12//! blip on one link killed healthy work, and in a tree of delegations the
13//! cancel cascaded.
14
15use std::sync::Arc;
16use std::time::Duration;
17
18use a2a_protocol_types::TaskQueryParams;
19
20use super::origin::Origin;
21use super::{DEFAULT_ID_WAIT, Delegation, Outcome, ResumePolicy};
22use crate::client::A2aClient;
23use crate::error::{ClientError, ClientResult};
24use crate::streaming::EventStream;
25
26/// What a lost stream came to.
27pub(super) enum Resumed {
28    /// The stream is open again; keep following.
29    Streaming,
30    /// The child had settled while the stream was down.
31    Settled(Box<Outcome>),
32    /// The policy is spent with the child still running or unreachable.
33    GaveUp,
34}
35
36impl Delegation {
37    /// Sets how a lost stream is resumed; see [`ResumePolicy`].
38    #[must_use]
39    pub const fn with_resume(mut self, policy: ResumePolicy) -> Self {
40        self.resume_policy = policy;
41        self
42    }
43
44    /// The position of the last event received: the id to resume from, to
45    /// record with [`task_id`](Self::task_id) before [`detach`](Self::detach)
46    /// so that [`reattach`](Self::reattach) can pick the child up again.
47    /// `None` until an event carried one, and always `None` on gRPC and
48    /// WebSocket streams.
49    #[must_use]
50    pub fn last_event_id(&self) -> Option<&str> {
51        self.last_event_id.as_deref()
52    }
53
54    /// Follows a child that is already running, from the position
55    /// `last_event_id` (or from its current state when `None`): a supervisor
56    /// that recorded [`task_id`](Self::task_id) and
57    /// [`last_event_id`](Self::last_event_id) before it stopped picks the
58    /// child up after a restart.
59    ///
60    /// A child that has settled in the meantime returns a handle that is
61    /// already settled, so [`wait`](Self::wait) answers at once with what it
62    /// became. The handle owns the child again: dropped unsettled, it
63    /// cancels. A lease or budget grant is not restored (ADR 0030).
64    ///
65    /// # Errors
66    ///
67    /// The subscription's error when the stream cannot be opened and the
68    /// child's state cannot be read to show it settled. No handle exists
69    /// then, and nothing is cancelled.
70    pub async fn reattach(
71        client: Arc<A2aClient>,
72        tenant: Option<String>,
73        task_id: impl Into<String>,
74        last_event_id: Option<String>,
75    ) -> ClientResult<Self> {
76        let id = task_id.into();
77        let mut this = Self {
78            client,
79            tenant,
80            stream: None,
81            task_id: Some(id.clone()),
82            settled: None,
83            armed: true,
84            id_wait: DEFAULT_ID_WAIT,
85            renewal: None,
86            budget: None,
87            idempotency_key: None,
88            origin: Origin::current(),
89            resume_policy: ResumePolicy::default(),
90            last_event_id,
91            streak: 0,
92            resumed_at: None,
93            opened_at: None,
94            events_since_open: 0,
95            message: None,
96            context_id: None,
97            handed_back: false,
98            continued: 0,
99            hand_off_policy: super::HandOffPolicy::default(),
100            journal: None,
101        };
102        match this.reopen(&id).await {
103            Ok(stream) => {
104                this.stream = Some(stream);
105                this.stream_opened();
106            }
107            Err(e) => {
108                if let Some(outcome) = this.state_of(&id).await {
109                    this.settled = Some(outcome);
110                } else {
111                    // Never held: dropping this must not cancel a child it
112                    // could not even look at.
113                    this.armed = false;
114                    return Err(e);
115                }
116            }
117        }
118        Ok(this)
119    }
120
121    /// Records the position of the stream, from the stream itself or from the
122    /// error that ended it.
123    pub(super) fn remember_position(&mut self, error: Option<&ClientError>) {
124        if let Some(ClientError::IncompleteStream {
125            last_event_id: Some(id),
126            ..
127        }) = error
128        {
129            self.last_event_id = Some(id.clone());
130        } else if let Some(id) = self.stream.as_ref().and_then(EventStream::last_event_id) {
131            self.last_event_id = Some(id.to_owned());
132        }
133    }
134
135    /// Notes that a stream has just been opened: the clock a later loss is
136    /// judged by starts here, with no event seen on it yet.
137    pub(super) fn stream_opened(&mut self) {
138        self.opened_at = Some(tokio::time::Instant::now());
139        self.events_since_open = 0;
140    }
141
142    /// Whether the stream that was lost delivered at least one event and had
143    /// been open for `healthy_after`.
144    fn stream_worked(&self, healthy_after: Duration) -> bool {
145        self.events_since_open > 0
146            && self
147                .opened_at
148                .is_some_and(|at| at.elapsed() >= healthy_after)
149    }
150
151    /// Opens the child's stream again from the recorded position.
152    async fn reopen(&self, id: &str) -> ClientResult<EventStream> {
153        self.client
154            .subscribe_in(
155                self.tenant.clone(),
156                id.to_owned(),
157                self.last_event_id.clone(),
158            )
159            .await
160    }
161
162    /// What the child has become, if it has settled: the A2A rule that a
163    /// terminal task cannot be subscribed to makes this the usual reason a
164    /// resubscription is refused.
165    async fn state_of(&self, id: &str) -> Option<Outcome> {
166        let mut query = TaskQueryParams::new(id).with_history_length(0);
167        query.tenant.clone_from(&self.tenant);
168        let task = self.client.get_task(query).await.ok()?;
169        Outcome::of(task.status)
170    }
171
172    /// Works on a lost stream until it is open again, the child is found
173    /// settled, or the policy is spent. See [`ResumePolicy`].
174    pub(super) async fn resume(&mut self) -> Resumed {
175        let Some(id) = self.task_id.clone() else {
176            return Resumed::GaveUp;
177        };
178        let policy = self.resume_policy;
179        if self.last_event_id != self.resumed_at || self.stream_worked(policy.healthy_after) {
180            // The position moved since the last loss, or the stream stayed up
181            // and delivered: that stream worked.
182            self.streak = 0;
183        }
184        let started = tokio::time::Instant::now();
185        loop {
186            if self.streak >= policy.attempts {
187                break;
188            }
189            let wait = policy.attempt_wait(self.streak, crate::retry::jittered);
190            if !wait.is_zero() {
191                let left = policy.deadline.saturating_sub(started.elapsed());
192                if left.is_zero() {
193                    break;
194                }
195                tokio::time::sleep(wait.min(left)).await;
196            }
197            let left = policy.deadline.saturating_sub(started.elapsed());
198            if left.is_zero() {
199                break;
200            }
201            self.streak += 1;
202            match tokio::time::timeout(left, self.reopen(&id)).await {
203                Ok(Ok(stream)) => {
204                    trace_debug!(task_id = %id, "delegation: stream reopened");
205                    self.stream = Some(stream);
206                    self.stream_opened();
207                    self.resumed_at.clone_from(&self.last_event_id);
208                    return Resumed::Streaming;
209                }
210                Ok(Err(_e)) => {
211                    trace_debug!(task_id = %id, error = %_e, "delegation: stream not reopened");
212                    // The child may have settled while the stream was down.
213                    if let Some(outcome) = self.state_of(&id).await {
214                        return Resumed::Settled(Box::new(outcome));
215                    }
216                }
217                Err(_) => break,
218            }
219        }
220        self.resumed_at.clone_from(&self.last_event_id);
221        Resumed::GaveUp
222    }
223}
224
225#[cfg(test)]
226mod tests {
227    use super::super::testing::parked;
228    use super::*;
229
230    fn ms(n: u64) -> Duration {
231        Duration::from_millis(n)
232    }
233
234    #[tokio::test(start_paused = true)]
235    async fn a_stream_has_worked_only_with_an_event_and_once_it_was_open_long_enough() {
236        let five = Duration::from_secs(5);
237        let mut d = parked();
238        assert!(!d.stream_worked(five), "never opened");
239        d.stream_opened();
240        tokio::time::advance(Duration::from_secs(600)).await;
241        assert!(!d.stream_worked(five), "open for ten minutes with no event");
242
243        d.stream_opened();
244        d.events_since_open = 1;
245        tokio::time::advance(ms(4_999)).await;
246        assert!(!d.stream_worked(five), "one millisecond short");
247        tokio::time::advance(ms(1)).await;
248        assert!(d.stream_worked(five), "exactly the healthy time counts");
249        assert!(d.stream_worked(Duration::ZERO));
250    }
251
252    #[tokio::test(start_paused = true)]
253    async fn opening_a_stream_forgets_the_events_of_the_one_before() {
254        let mut d = parked();
255        d.stream_opened();
256        d.events_since_open = 9;
257        tokio::time::advance(Duration::from_secs(60)).await;
258        assert!(d.stream_worked(Duration::from_secs(5)));
259        d.stream_opened();
260        assert_eq!(d.events_since_open, 0);
261        assert!(
262            !d.stream_worked(Duration::ZERO),
263            "a new stream has no events"
264        );
265    }
266
267    /// A listener that counts connections and closes each at once.
268    async fn counting_listener() -> (
269        std::net::SocketAddr,
270        std::sync::Arc<std::sync::atomic::AtomicUsize>,
271    ) {
272        use std::sync::atomic::{AtomicUsize, Ordering};
273        let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
274            .await
275            .expect("bind");
276        let addr = listener.local_addr().expect("addr");
277        let count = std::sync::Arc::new(AtomicUsize::new(0));
278        let seen = std::sync::Arc::clone(&count);
279        tokio::spawn(async move {
280            while let Ok((_socket, _)) = listener.accept().await {
281                seen.fetch_add(1, Ordering::SeqCst);
282            }
283        });
284        (addr, count)
285    }
286
287    async fn resume_against(
288        addr: std::net::SocketAddr,
289        worked: bool,
290    ) -> (usize, std::sync::Arc<std::sync::atomic::AtomicUsize>) {
291        let client = std::sync::Arc::new(
292            crate::ClientBuilder::new(format!("http://{addr}"))
293                .build()
294                .expect("a client"),
295        );
296        let mut d = parked();
297        d.client = client;
298        d.resume_policy = ResumePolicy::default()
299            .with_attempts(2)
300            .with_backoff(Duration::ZERO, Duration::ZERO)
301            .with_jitter(false)
302            .with_healthy_after(Duration::ZERO);
303        // The count is spent: without a reason to start it again nothing is tried.
304        d.streak = 2;
305        d.stream_opened();
306        d.events_since_open = u32::from(worked);
307        let count = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
308        let _ = &count;
309        let outcome = d.resume().await;
310        assert!(matches!(outcome, Resumed::GaveUp), "nothing answers");
311        (d.streak as usize, count)
312    }
313
314    #[tokio::test]
315    async fn a_stream_that_worked_gets_its_attempts_back_and_one_that_did_not_does_not() {
316        use std::sync::atomic::Ordering;
317        let (addr, hits) = counting_listener().await;
318        let (streak, _) = resume_against(addr, false).await;
319        assert_eq!(
320            streak, 2,
321            "a spent count with no healthy stream tries nothing"
322        );
323        assert_eq!(hits.load(Ordering::SeqCst), 0);
324
325        let (streak, _) = resume_against(addr, true).await;
326        assert_eq!(streak, 2, "the two attempts were made again");
327        assert!(
328            hits.load(Ordering::SeqCst) >= 2,
329            "the agent was asked again after a stream that worked"
330        );
331    }
332}