gadk_agent/teardown.rs
1// Copyright 2026 Chris Olson
2// Portions derived from ADK-Go (https://github.com/google/adk-go), Copyright 2026 Google LLC.
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! Per-invocation teardown registry: lets work started by a component finish when a consumer
17//! stops reading early.
18//!
19//! A consumer that stops reading a run's event stream early drops the nested streams, but work
20//! they started (a parallel agent's branches, a workflow scheduler's nodes, tool tasks) must
21//! still finish before the runner's after-run callbacks run. Dropping a Rust stream cannot wait,
22//! so a component that owns still-running work cancels it plainly (never aborts it) and hands the
23//! rest of it to [`Teardowns`] as a spawned task ([`InvocationContext::spawn_teardown`] /
24//! [`InvocationContext::register_teardown`]). The runner's deferred after-run callbacks await
25//! [`Teardowns::wait`] first, so the started work finishes before them. A context
26//! without a registry (a stream used outside the runner) detaches the work instead: it still
27//! finishes, nobody waits for it.
28
29use std::future::Future;
30use std::sync::Arc;
31
32use futures::FutureExt;
33use tokio::task::JoinHandle;
34use tracing::Instrument;
35
36use crate::context::InvocationContext;
37use crate::fiber;
38
39/// The still-running teardown work of one invocation (see the module docs). Shared by every
40/// context derived within the invocation.
41#[derive(Debug, Default)]
42pub struct Teardowns {
43 tasks: parking_lot::Mutex<Vec<JoinHandle<()>>>,
44}
45
46impl Teardowns {
47 /// An empty registry.
48 pub fn new() -> Self {
49 Self::default()
50 }
51
52 /// Adds a spawned teardown task; [`Teardowns::wait`] awaits it. Tasks that already finished
53 /// are dropped first (a panic among them is logged as [`Teardowns::wait`] logs it), so a long
54 /// invocation with many early drops does not accumulate finished handles.
55 pub fn register(&self, task: JoinHandle<()>) {
56 let mut tasks = self.tasks.lock();
57 tasks.retain_mut(|h| {
58 if !h.is_finished() {
59 return true;
60 }
61 if let Some(Err(e)) = h.now_or_never()
62 && e.is_panic()
63 {
64 tracing::warn!("adk: a teardown task panicked");
65 }
66 false
67 });
68 tasks.push(task);
69 }
70
71 /// Awaits every registered task, including tasks registered while waiting (a teardown can
72 /// drop a nested component that registers its own), until none is left. A task that panicked
73 /// or was aborted counts as finished.
74 pub async fn wait(&self) {
75 loop {
76 let next = self.tasks.lock().pop();
77 let Some(task) = next else { return };
78 if let Err(e) = task.await
79 && e.is_panic()
80 {
81 tracing::warn!("adk: a teardown task panicked");
82 }
83 }
84 }
85
86 /// Whether no teardown task is registered (finished or not).
87 pub fn is_empty(&self) -> bool {
88 self.tasks.lock().is_empty()
89 }
90}
91
92impl InvocationContext {
93 /// The invocation's teardown registry, if the runner installed one
94 /// ([`crate::ContextBuilder::teardowns`]).
95 pub fn teardowns(&self) -> Option<Arc<Teardowns>> {
96 self.inner().shared.teardowns.clone()
97 }
98
99 /// Hands an already spawned task that finishes started work to the invocation's teardown
100 /// registry; without a registry the task is detached (it still runs to completion). A task
101 /// registered after [`Teardowns::wait`] returned (the runner's after-run already started) is
102 /// never awaited: it runs to completion detached.
103 pub fn register_teardown(&self, task: JoinHandle<()>) {
104 if let Some(t) = self.teardowns() {
105 t.register(task);
106 }
107 }
108
109 /// Spawns `work` (the rest of the started work of a component being dropped) on the current
110 /// tokio runtime, in the current fiber and tracing span, and registers it
111 /// ([`InvocationContext::register_teardown`]). Outside a runtime `work` is dropped (there is
112 /// nothing to run it on).
113 pub fn spawn_teardown<F>(&self, work: F)
114 where
115 F: Future<Output = ()> + Send + 'static,
116 {
117 let Ok(handle) = tokio::runtime::Handle::try_current() else {
118 return;
119 };
120 let task = handle.spawn(fiber::current().scope(work).in_current_span());
121 self.register_teardown(task);
122 }
123}
124
125#[cfg(test)]
126#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
127mod tests {
128 use std::sync::Arc;
129 use std::sync::atomic::{AtomicUsize, Ordering};
130
131 use crate::context::{ContextDelta, InvocationContext};
132
133 use super::Teardowns;
134
135 #[tokio::test]
136 async fn register_drops_finished_tasks() {
137 let reg = Teardowns::new();
138 let done = tokio::spawn(async {});
139 while !done.is_finished() {
140 tokio::task::yield_now().await;
141 }
142 reg.register(done);
143 let (tx, rx) = tokio::sync::oneshot::channel::<()>();
144 reg.register(tokio::spawn(async move {
145 let _ = rx.await;
146 }));
147 assert_eq!(reg.tasks.lock().len(), 1, "the finished task was pruned");
148 let _ = tx.send(());
149 reg.wait().await;
150 assert!(reg.is_empty());
151 }
152
153 #[tokio::test]
154 async fn wait_awaits_tasks_registered_while_waiting() {
155 let reg = Arc::new(Teardowns::new());
156 let ctx = InvocationContext::builder()
157 .teardowns(reg.clone())
158 .build_invocation();
159 let done = Arc::new(AtomicUsize::new(0));
160 let (inner_ctx, d) = (ctx.clone(), done.clone());
161 ctx.spawn_teardown(async move {
162 tokio::task::yield_now().await;
163 let d2 = d.clone();
164 // A nested teardown registered by the first one.
165 inner_ctx.spawn_teardown(async move {
166 tokio::task::yield_now().await;
167 d2.fetch_add(1, Ordering::SeqCst);
168 });
169 d.fetch_add(1, Ordering::SeqCst);
170 });
171 reg.wait().await;
172 assert_eq!(done.load(Ordering::SeqCst), 2);
173 assert!(reg.is_empty());
174 }
175
176 #[tokio::test]
177 async fn every_derived_context_shares_the_registry() {
178 let reg = Arc::new(Teardowns::new());
179 let ctx = InvocationContext::builder()
180 .teardowns(reg.clone())
181 .build_invocation();
182 let derived = ctx.with_delta(ContextDelta {
183 fresh_invocation: true,
184 ..Default::default()
185 });
186 assert!(Arc::ptr_eq(&derived.teardowns().unwrap(), ®));
187 let (scoped, _guard) = ctx.clone().into_context().with_agent_cancel();
188 assert!(Arc::ptr_eq(&scoped.teardowns().unwrap(), ®));
189 }
190
191 #[tokio::test]
192 async fn without_a_registry_the_work_is_detached_and_still_runs() {
193 let ctx = InvocationContext::builder().build_invocation();
194 assert!(ctx.teardowns().is_none());
195 let (tx, rx) = tokio::sync::oneshot::channel();
196 ctx.spawn_teardown(async move {
197 let _ = tx.send(());
198 });
199 rx.await.unwrap();
200 }
201}