Skip to main content

aft_base/
tool_progress.rs

1//! A call-scoped, non-blocking progress channel. Completed work and live child
2//! supervision report here; a blocked observation must not report progress.
3
4use std::sync::atomic::{AtomicU64, Ordering};
5use std::sync::{Arc, Mutex};
6use std::time::{Duration, Instant};
7
8#[derive(Clone)]
9pub struct Progress(Arc<Inner>);
10
11struct Inner {
12    last_sent: Mutex<Option<Instant>>,
13    clock: Box<dyn Fn() -> Instant + Send + Sync>,
14    send: Box<dyn Fn(usize) -> bool + Send + Sync>,
15}
16
17impl std::fmt::Debug for Progress {
18    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
19        f.write_str("Progress")
20    }
21}
22
23impl Progress {
24    pub fn new(send: impl Fn(usize) -> bool + Send + Sync + 'static) -> Self {
25        Self::with_clock(Instant::now, send)
26    }
27
28    #[rustfmt::skip]
29    test_support_visibility! {
30
31    pub(crate) fn with_clock(
32        clock: impl Fn() -> Instant + Send + Sync + 'static,
33        send: impl Fn(usize) -> bool + Send + Sync + 'static,
34    ) -> Self {
35        Self(Arc::new(Inner {
36            last_sent: Mutex::new(Some(clock())),
37            clock: Box::new(clock),
38            send: Box::new(send),
39        }))
40    }
41    }
42
43    pub fn report(&self) {
44        let now = (self.0.clock)();
45        let mut last = self.0.last_sent.lock().unwrap_or_else(|e| e.into_inner());
46        let Some(last) = last.as_mut() else {
47            return;
48        };
49        if now.saturating_duration_since(*last)
50            >= Duration::from_millis(cortexkit_role_tool_provider::KEEPALIVE_INTERVAL_MS)
51            && (self.0.send)(self.key())
52        {
53            *last = now;
54        }
55    }
56
57    /// End the original request's keepalives for every clone, including one
58    /// installed by a later approved rerun. Taking the report lock also waits
59    /// for any in-flight send before the terminal reply can be queued.
60    pub fn close(&self) {
61        self.0
62            .last_sent
63            .lock()
64            .unwrap_or_else(|e| e.into_inner())
65            .take();
66    }
67
68    pub fn key(&self) -> usize {
69        Arc::as_ptr(&self.0) as usize
70    }
71}
72
73pub fn report() {
74    if let Some(token) = crate::executor::current_job_cancellation() {
75        token.report_progress();
76    }
77}
78
79thread_local! {
80    static FILES: std::cell::RefCell<Option<FileProgress>> = const { std::cell::RefCell::new(None) };
81}
82
83/// Shared scanners outlive individual requests. Count their completed files so
84/// only requests waiting for that scanner can turn the counts into keepalive frames.
85#[derive(Clone, Default)]
86pub struct FileProgress(Arc<AtomicU64>);
87
88impl FileProgress {
89    pub fn current() -> Option<Self> {
90        FILES.with(|files| files.borrow().clone())
91    }
92
93    pub fn enter(&self) -> FileProgressGuard {
94        FileProgressGuard {
95            previous: FILES.with(|files| files.replace(Some(self.clone()))),
96            _thread_bound: std::marker::PhantomData,
97        }
98    }
99
100    pub fn finished(&self) {
101        self.0.fetch_add(1, Ordering::Relaxed);
102    }
103
104    pub fn completed(&self) -> u64 {
105        self.0.load(Ordering::Relaxed)
106    }
107}
108
109pub struct FileProgressGuard {
110    previous: Option<FileProgress>,
111    _thread_bound: std::marker::PhantomData<std::rc::Rc<()>>,
112}
113
114impl Drop for FileProgressGuard {
115    fn drop(&mut self) {
116        FILES.with(|files| files.replace(self.previous.take()));
117    }
118}
119
120#[cfg(test)]
121mod tests {
122    use super::*;
123    use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
124
125    #[test]
126    fn call_keepalive_close_survives_clone_and_new_job_token() {
127        let origin = Instant::now();
128        let clock = Arc::new(AtomicU64::new(0));
129        let sent = Arc::new(AtomicUsize::new(0));
130        let progress = Progress::with_clock(
131            {
132                let clock = clock.clone();
133                move || origin + Duration::from_millis(clock.load(Ordering::SeqCst))
134            },
135            {
136                let sent = sent.clone();
137                move |_| {
138                    sent.fetch_add(1, Ordering::SeqCst);
139                    true
140                }
141            },
142        );
143        let clone = progress.clone();
144        clock.store(30_000, Ordering::SeqCst);
145        progress.report();
146        assert_eq!(sent.load(Ordering::SeqCst), 1);
147        progress.close();
148        clock.store(60_000, Ordering::SeqCst);
149        clone.report();
150        let rerun = crate::executor::JobCancellation::new();
151        rerun.set_progress(clone);
152        clock.store(90_000, Ordering::SeqCst);
153        rerun.report_progress();
154        assert_eq!(sent.load(Ordering::SeqCst), 1);
155    }
156
157    #[test]
158    fn call_keepalive_close_waits_for_an_in_flight_send() {
159        let clock = Arc::new(AtomicU64::new(0));
160        let origin = Instant::now();
161        let entered = Arc::new(std::sync::Barrier::new(2));
162        let release = Arc::new(std::sync::Barrier::new(2));
163        let progress = Progress::with_clock(
164            {
165                let clock = clock.clone();
166                move || origin + Duration::from_millis(clock.load(Ordering::SeqCst))
167            },
168            {
169                let entered = entered.clone();
170                let release = release.clone();
171                move |_| {
172                    entered.wait();
173                    release.wait();
174                    true
175                }
176            },
177        );
178        clock.store(30_000, Ordering::SeqCst);
179        let reporter = {
180            let progress = progress.clone();
181            std::thread::spawn(move || progress.report())
182        };
183        entered.wait();
184        let (closing, started) = std::sync::mpsc::channel();
185        let (closed, finished) = std::sync::mpsc::channel();
186        let closer = std::thread::spawn(move || {
187            closing.send(()).unwrap();
188            progress.close();
189            closed.send(()).unwrap();
190        });
191        started.recv_timeout(Duration::from_secs(5)).unwrap();
192        let premature_close = finished.recv_timeout(Duration::from_millis(50));
193        release.wait();
194        reporter.join().unwrap();
195        closer.join().unwrap();
196        assert!(matches!(
197            premature_close,
198            Err(std::sync::mpsc::RecvTimeoutError::Timeout)
199        ));
200    }
201}
202
203/// Only uninterrupted, same-thread intervals have an attributable CPU delta.
204/// Queueing, async writes, and aggregate egress span awaits or worker handoffs.
205/// Platforms without a sufficiently fine thread clock always report unknown.
206#[derive(Debug, Clone, Default)]
207pub struct ToolCallPhaseCpu {
208    pub setup: Option<Duration>,
209    pub translate: Option<Duration>,
210    pub execute: Option<Duration>,
211    pub format: Option<Duration>,
212    pub finalize: Option<Duration>,
213    pub egress_prepare: Option<Duration>,
214}
215
216/// Causal wait recorded on a tool call so slow-call logs can name the blocker.
217#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
218pub enum WaitingOn {
219    #[default]
220    None,
221    Build,
222    Limiter,
223    ArtifactLoad,
224    Resolver,
225}
226
227impl WaitingOn {
228    pub fn as_str(self) -> &'static str {
229        match self {
230            Self::None => "none",
231            Self::Build => "build",
232            Self::Limiter => "limiter",
233            Self::ArtifactLoad => "artifact_load",
234            Self::Resolver => "resolver",
235        }
236    }
237}
238
239#[derive(Debug, Clone)]
240pub struct ToolCallPhaseDurations {
241    pub cpu: ToolCallPhaseCpu,
242    pub queue: Duration,
243    /// From executor admission to the start of argument translation: the
244    /// route's call policy (confinement admission, access-policy scope, the
245    /// formatter launch-policy handle) and repeat-breaker capture. Kept apart
246    /// from `translate` so per-call policy work is not mistaken for argument
247    /// translation.
248    pub setup: Duration,
249    /// From the start of argument translation to a dispatchable request:
250    /// disabled-tool and database gates, hashline registration, and the
251    /// translation itself.
252    pub translate: Duration,
253    pub execute: Duration,
254    pub format: Duration,
255    pub finalize: Duration,
256    pub egress_enqueue: Duration,
257    pub egress_queue: Duration,
258    pub egress_prepare: Duration,
259    pub egress_write: Duration,
260    pub egress: Duration,
261    pub frame_bytes: usize,
262    pub writer_queue_depth: usize,
263    pub writer_active_at_enqueue: bool,
264    pub writer_queue_was_full: bool,
265    pub writer_reserve_timeouts: u32,
266    pub total: Duration,
267    pub waiting_on: WaitingOn,
268    pub waiting_on_build_id: Option<String>,
269    pub wait_ms: u64,
270    /// Execution includes a requested wait, not just AFT's own work.
271    pub intentional_wait: bool,
272    /// What the call was asked to do, without any content: the target kind
273    /// and, for edits, the match and replacement sizes and the outcome code.
274    /// See [`crate::run_tool_call::tool_call_arg_shape`].
275    pub arg_shape: Option<String>,
276    /// Milliseconds per edit pipeline step, when the call ran any.
277    pub edit_phases: Option<String>,
278}