Skip to main content

stateknot_runtime/
execution_activity.rs

1// Copyright 2026 StateKnot contributors
2// SPDX-License-Identifier: Apache-2.0
3
4use std::future::Future;
5use tokio_util::task::TaskTracker;
6
7/// Shared completion accounting for node futures dispatched by one driver.
8/// Clones do not own the store or executors and do not cancel execution.
9#[derive(Clone, Default, Debug)]
10pub struct GraphExecutionActivity(TaskTracker);
11
12impl GraphExecutionActivity {
13    /// Number of registered node futures, including ones not yet polled.
14    pub fn active_nodes(&self) -> usize {
15        self.0.len()
16    }
17
18    /// Waits for destruction of all tracked node futures. The caller MUST first
19    /// stop and join every producer using this driver (including its clones).
20    /// This is not a dispatch lock: subsequent dispatch remains possible.
21    /// Cancelling the wait does not lose task accounting.
22    pub async fn wait_for_idle(&self) {
23        self.0.close();
24        self.0.wait().await;
25    }
26
27    pub(crate) fn track<F: Future>(&self, future: F) -> impl Future<Output = F::Output> + use<F> {
28        self.0.track_future(future)
29    }
30}
31
32#[cfg(test)]
33mod tests {
34    use super::*;
35    use std::sync::{
36        Arc,
37        atomic::{AtomicBool, Ordering},
38    };
39
40    struct Dropped(Arc<AtomicBool>);
41    impl Drop for Dropped {
42        fn drop(&mut self) {
43            self.0.store(true, Ordering::Release);
44        }
45    }
46
47    #[tokio::test]
48    async fn tracks_before_poll_and_waits_for_future_destruction() {
49        let activity = GraphExecutionActivity::default();
50        let dropped = Arc::new(AtomicBool::new(false));
51        let guard = Dropped(dropped.clone());
52        let future = activity.track(async move {
53            let _guard = guard;
54            std::future::pending::<()>().await;
55        });
56        assert_eq!(activity.active_nodes(), 1);
57        let mut tasks = tokio::task::JoinSet::new();
58        tasks.spawn(future);
59        tasks.abort_all();
60        while tasks.join_next().await.is_some() {}
61        activity.wait_for_idle().await;
62        assert!(dropped.load(Ordering::Acquire));
63        assert_eq!(activity.active_nodes(), 0);
64    }
65}