Skip to main content

strands/
cancel.rs

1//! Cooperative cancellation: [`CancelHandle`], [`CancelSignal`] and [`CancelOptions`].
2//!
3//! The handle requests cancellation and the signal, which can be cloned freely, observes it.
4
5use std::fmt;
6use std::sync::atomic::{AtomicBool, Ordering};
7use std::sync::{Arc, Mutex, PoisonError};
8
9use tokio_util::sync::CancellationToken;
10
11/// Options for [`CancelHandle::cancel`] (`CancelOptions`).
12#[derive(Debug, Clone, Default, PartialEq, Eq, bon::Builder)]
13pub struct CancelOptions {
14    /// Final assistant message for the cancelled invocation. When several callers set one, the
15    /// last write wins; a cancel without a message keeps a previously stored one.
16    #[builder(into)]
17    pub message: Option<String>,
18    /// Defer cancellation until the running tool batch finishes, so sibling tools complete
19    /// normally instead of seeing the signal fire. Only the agent loop acts on the deferral: it
20    /// stops after the batch. Until then [`CancelSignal::is_cancelled`] stays `false` for every
21    /// other observer.
22    #[builder(default)]
23    pub after_current_tools: bool,
24    /// Also cancel every queued, working or input-required background task of the agent
25    /// immediately, even with `after_current_tools` and whether or not an invocation is running
26    /// (`cancelBackgroundTasks`). Background tasks keep running by default, and a
27    /// `cancel_signal` passed into an invocation never cancels them. Their cancelled results are
28    /// delivered like a cancel the model requested. If the invocation was only waiting for its
29    /// background tasks, it ends with its natural stop reason and the results are delivered on the
30    /// next invocation. Only an agent's own handle acts on it.
31    #[builder(default)]
32    pub cancel_background_tasks: bool,
33}
34
35/// Cancels an agent's background tasks; installed on the agent's own handle.
36pub(crate) type BackgroundCancelFn = Arc<dyn Fn() + Send + Sync>;
37
38struct Shared {
39    token: Mutex<CancellationToken>,
40    deferred: AtomicBool,
41    message: Mutex<Option<String>>,
42    /// Set for an agent's own handle: a cancel only counts while an invocation runs.
43    active: Option<AtomicBool>,
44    background_cancel: Mutex<Option<BackgroundCancelFn>>,
45}
46
47impl Shared {
48    fn token(&self) -> CancellationToken {
49        self.token.lock().unwrap_or_else(PoisonError::into_inner).clone()
50    }
51
52    fn message(&self) -> Option<String> {
53        self.message.lock().unwrap_or_else(PoisonError::into_inner).clone()
54    }
55}
56
57/// Requests cancellation of the work observing its [`CancelSignal`].
58///
59/// Cheap to clone; clones control the same signal.
60///
61/// ```
62/// use strands::{CancelHandle, CancelOptions};
63///
64/// let handle = CancelHandle::new();
65/// let signal = handle.signal();
66/// handle.cancel(CancelOptions { message: Some("stopped".into()), ..Default::default() });
67/// assert!(signal.is_cancelled());
68/// assert_eq!(signal.reason().as_deref(), Some("stopped"));
69/// ```
70#[derive(Clone)]
71pub struct CancelHandle {
72    shared: Arc<Shared>,
73}
74
75impl CancelHandle {
76    /// Creates a handle whose signal has not fired.
77    pub fn new() -> Self {
78        Self::with_gate(None)
79    }
80
81    /// An agent's own handle: cancels are ignored while no invocation runs, and each invocation
82    /// starts with a fresh signal.
83    pub(crate) fn for_agent() -> Self {
84        Self::with_gate(Some(AtomicBool::new(false)))
85    }
86
87    fn with_gate(active: Option<AtomicBool>) -> Self {
88        Self {
89            shared: Arc::new(Shared {
90                token: Mutex::new(CancellationToken::new()),
91                deferred: AtomicBool::new(false),
92                message: Mutex::new(None),
93                active,
94                background_cancel: Mutex::new(None),
95            }),
96        }
97    }
98
99    /// The signal this handle controls.
100    #[must_use]
101    pub fn signal(&self) -> CancelSignal {
102        CancelSignal {
103            sources: Arc::from([Source {
104                shared: Arc::clone(&self.shared),
105                token: self.shared.token(),
106            }]),
107        }
108    }
109
110    /// Requests cancellation. Idempotent.
111    ///
112    /// With `after_current_tools` the request is recorded but the signal does not fire; the agent
113    /// stops once the running tool batch finishes. Otherwise the signal fires now. On an agent's
114    /// handle ([`Agent::cancel_handle`](crate::Agent::cancel_handle)) a cancel while the agent is
115    /// idle does nothing, except that `cancel_background_tasks` still applies.
116    pub fn cancel(&self, options: CancelOptions) {
117        if options.cancel_background_tasks {
118            let background_cancel = self
119                .shared
120                .background_cancel
121                .lock()
122                .unwrap_or_else(PoisonError::into_inner)
123                .clone();
124            if let Some(background_cancel) = background_cancel {
125                background_cancel();
126            }
127        }
128        if let Some(active) = &self.shared.active
129            && !active.load(Ordering::SeqCst)
130        {
131            return;
132        }
133        if let Some(message) = options.message {
134            *self.shared.message.lock().unwrap_or_else(PoisonError::into_inner) = Some(message);
135        }
136        if options.after_current_tools {
137            self.shared.deferred.store(true, Ordering::SeqCst);
138            return;
139        }
140        self.shared.token().cancel();
141    }
142
143    /// Starts a fresh signal: clears the message and the deferred flag. Signals taken before keep
144    /// their state.
145    pub(crate) fn reset(&self) {
146        *self.shared.token.lock().unwrap_or_else(PoisonError::into_inner) = CancellationToken::new();
147        self.shared.deferred.store(false, Ordering::SeqCst);
148        *self.shared.message.lock().unwrap_or_else(PoisonError::into_inner) = None;
149    }
150
151    /// Installs what `cancel_background_tasks` runs: the agent's background tasks, once they are
152    /// attached.
153    pub(crate) fn set_background_cancel(&self, background_cancel: BackgroundCancelFn) {
154        *self
155            .shared
156            .background_cancel
157            .lock()
158            .unwrap_or_else(PoisonError::into_inner) = Some(background_cancel);
159    }
160
161    /// Marks whether an invocation runs, for an agent's own handle.
162    pub(crate) fn set_active(&self, value: bool) {
163        if let Some(active) = &self.shared.active {
164            active.store(value, Ordering::SeqCst);
165        }
166    }
167}
168
169impl Default for CancelHandle {
170    fn default() -> Self {
171        Self::new()
172    }
173}
174
175impl fmt::Debug for CancelHandle {
176    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
177        f.debug_struct("CancelHandle")
178            .field("cancelled", &self.shared.token().is_cancelled())
179            .finish_non_exhaustive()
180    }
181}
182
183struct Source {
184    shared: Arc<Shared>,
185    token: CancellationToken,
186}
187
188/// Observes cancellation requested through a [`CancelHandle`].
189///
190/// Cheap to clone; every clone sees the same state. Pass one as `InvokeOptions::cancel_signal`
191/// to cancel an invocation from outside the agent, or read it in tools and providers to stop
192/// in-flight work.
193#[derive(Clone)]
194pub struct CancelSignal {
195    sources: Arc<[Source]>,
196}
197
198impl CancelSignal {
199    /// A signal that fires when either signal fires. Its reason and deferral come from the first
200    /// signal that has one.
201    pub(crate) fn any(first: &Self, second: &Self) -> Self {
202        let sources: Vec<Source> = first
203            .sources
204            .iter()
205            .chain(second.sources.iter())
206            .map(|source| Source {
207                shared: Arc::clone(&source.shared),
208                token: source.token.clone(),
209            })
210            .collect();
211        Self {
212            sources: Arc::from(sources),
213        }
214    }
215
216    /// Whether cancellation has fired (`aborted`).
217    #[must_use]
218    pub fn is_cancelled(&self) -> bool {
219        self.sources.iter().any(|source| source.token.is_cancelled())
220    }
221
222    /// Completes when cancellation fires; immediately if it already has.
223    pub async fn cancelled(&self) {
224        let waits = self.sources.iter().map(|source| Box::pin(source.token.cancelled()));
225        futures::future::select_all(waits).await;
226    }
227
228    /// The message passed with the latest cancel that carried one.
229    #[must_use]
230    pub fn reason(&self) -> Option<String> {
231        self.sources.iter().find_map(|source| source.shared.message())
232    }
233
234    /// Whether a cancel deferred until the running tool batch finishes is pending.
235    pub(crate) fn is_deferred(&self) -> bool {
236        self.sources
237            .iter()
238            .any(|source| source.shared.deferred.load(Ordering::SeqCst))
239    }
240}
241
242impl fmt::Debug for CancelSignal {
243    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
244        f.debug_struct("CancelSignal")
245            .field("cancelled", &self.is_cancelled())
246            .finish_non_exhaustive()
247    }
248}
249
250#[cfg(test)]
251mod tests {
252    use std::time::Duration;
253
254    use super::*;
255
256    #[test]
257    fn a_new_signal_has_not_fired() {
258        let signal = CancelHandle::new().signal();
259        assert!(!signal.is_cancelled());
260        assert_eq!(signal.reason(), None);
261        assert!(!signal.is_deferred());
262    }
263
264    #[test]
265    fn cancel_fires_every_clone_of_the_signal() {
266        let handle = CancelHandle::new();
267        let signal = handle.signal();
268        let clone = signal.clone();
269        let other = handle.clone();
270        other.cancel(CancelOptions::default());
271        assert!(signal.is_cancelled());
272        assert!(clone.is_cancelled());
273        assert!(handle.signal().is_cancelled());
274    }
275
276    #[test]
277    fn a_deferred_cancel_records_the_request_without_firing() {
278        let handle = CancelHandle::new();
279        let signal = handle.signal();
280        handle.cancel(CancelOptions::builder().after_current_tools(true).build());
281        assert!(!signal.is_cancelled());
282        assert!(signal.is_deferred());
283        handle.cancel(CancelOptions::default());
284        assert!(signal.is_cancelled());
285    }
286
287    #[test]
288    fn the_last_message_wins_and_a_cancel_without_one_keeps_it() {
289        let handle = CancelHandle::new();
290        let signal = handle.signal();
291        handle.cancel(CancelOptions::builder().message("first").build());
292        handle.cancel(CancelOptions::builder().message("second").build());
293        handle.cancel(CancelOptions::default());
294        assert_eq!(signal.reason().as_deref(), Some("second"));
295    }
296
297    #[tokio::test]
298    async fn cancelled_completes_when_the_signal_fires() {
299        let handle = CancelHandle::new();
300        let signal = handle.signal();
301        let waiter = tokio::spawn(async move { signal.cancelled().await });
302        tokio::task::yield_now().await;
303        assert!(!waiter.is_finished());
304        handle.cancel(CancelOptions::default());
305        tokio::time::timeout(Duration::from_secs(5), waiter)
306            .await
307            .unwrap()
308            .unwrap();
309    }
310
311    #[tokio::test]
312    async fn cancelled_completes_at_once_after_cancellation() {
313        let handle = CancelHandle::new();
314        handle.cancel(CancelOptions::default());
315        handle.signal().cancelled().await;
316    }
317
318    #[test]
319    fn an_agent_handle_ignores_cancels_while_idle() {
320        let handle = CancelHandle::for_agent();
321        handle.cancel(CancelOptions::default());
322        assert!(!handle.signal().is_cancelled());
323        handle.set_active(true);
324        handle.cancel(CancelOptions::builder().message("stop").build());
325        assert!(handle.signal().is_cancelled());
326    }
327
328    #[test]
329    fn reset_starts_a_fresh_signal_and_keeps_old_signals_cancelled() {
330        let handle = CancelHandle::new();
331        let old = handle.signal();
332        handle.cancel(CancelOptions::builder().message("stop").build());
333        handle.reset();
334        assert!(old.is_cancelled());
335        assert!(!handle.signal().is_cancelled());
336        assert_eq!(handle.signal().reason(), None);
337    }
338
339    #[tokio::test]
340    async fn any_fires_when_either_signal_fires() {
341        let own = CancelHandle::new();
342        let external = CancelHandle::new();
343        let merged = CancelSignal::any(&own.signal(), &external.signal());
344        assert!(!merged.is_cancelled());
345        external.cancel(
346            CancelOptions::builder()
347                .message("outside")
348                .after_current_tools(true)
349                .build(),
350        );
351        assert!(merged.is_deferred());
352        assert_eq!(merged.reason().as_deref(), Some("outside"));
353        external.cancel(CancelOptions::default());
354        merged.cancelled().await;
355        assert!(merged.is_cancelled());
356    }
357}