Skip to main content

lean_ctx_cloud/
background.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Cloud requests a tool call hands off (connector rule "Cloud never blocks a
3//! tool call").
4//!
5//! A tool call that needs Cloud (`ctx_tasks`, the Cloud side of a
6//! `ctx_agent` lease) checks what it can locally, queues the request here
7//! with [`submit`] and answers at once that it is pending. One low-priority
8//! thread per process runs the queue in order, so a later request of the
9//! same caller (a lease release after its acquire, an update after a
10//! claim) always goes out after the earlier one. What Cloud answered is kept
11//! per caller and put in front of that caller's next answer of the same
12//! tool ([`earlier`]); nothing is presented as confirmed before Cloud
13//! confirmed it.
14//!
15//! The queue lives in this process: requests of a process that ends before
16//! they ran are never sent, and the agent's session ended with it.
17
18use std::collections::{BTreeMap, BTreeSet, VecDeque};
19use std::sync::{Condvar, Mutex, MutexGuard, PoisonError};
20use std::time::{Duration, Instant};
21
22/// A queued request: runs off the tool call, returns the line for the caller.
23type Job = Box<dyn FnOnce() -> Option<String> + Send>;
24
25#[derive(Default)]
26struct Queue {
27    jobs: VecDeque<(String, Option<String>, Job)>,
28    /// Caller → answers not yet shown.
29    answers: BTreeMap<String, Vec<String>>,
30    /// Dedupe keys of queued or running jobs ([`submit_once`]).
31    keys: BTreeSet<String>,
32    running: bool,
33    started: bool,
34}
35
36static QUEUE: Mutex<Option<Queue>> = Mutex::new(None);
37static WAKE: Condvar = Condvar::new();
38
39fn queue() -> MutexGuard<'static, Option<Queue>> {
40    QUEUE.lock().unwrap_or_else(PoisonError::into_inner)
41}
42
43fn with_queue<T>(change: impl FnOnce(&mut Queue) -> T) -> T {
44    let mut guard = queue();
45    change(guard.get_or_insert_with(Queue::default))
46}
47
48/// Queue `job` for `caller` (e.g. `ctx_agent:<agent id>`). Its line, if
49/// any, is shown with the caller's next answer.
50pub fn submit(caller: &str, job: impl FnOnce() -> Option<String> + Send + 'static) {
51    push(caller, None, Box::new(job));
52}
53
54/// [`submit`], unless a job with `key` is already queued or running (a
55/// cache refresh asked for twice is fetched once). `false` when skipped.
56pub fn submit_once(
57    caller: &str,
58    key: &str,
59    job: impl FnOnce() -> Option<String> + Send + 'static,
60) -> bool {
61    if with_queue(|q| q.keys.contains(key)) {
62        return false;
63    }
64    push(caller, Some(key.to_string()), Box::new(job));
65    true
66}
67
68fn push(caller: &str, key: Option<String>, job: Job) {
69    let start = with_queue(|q| {
70        if let Some(key) = &key {
71            q.keys.insert(key.clone());
72        }
73        q.jobs.push_back((caller.to_string(), key, job));
74        !std::mem::replace(&mut q.started, true)
75    });
76    WAKE.notify_all();
77    if start {
78        let spawned = std::thread::Builder::new()
79            .name("cloud-calls".into())
80            .spawn(run);
81        if spawned.is_err() {
82            // No thread: the requests stay queued, never run in the tool call.
83            with_queue(|q| q.started = false);
84        }
85    }
86}
87
88fn run() {
89    loop {
90        let (caller, key, job) = {
91            let mut guard = queue();
92            loop {
93                let q = guard.get_or_insert_with(Queue::default);
94                if let Some(next) = q.jobs.pop_front() {
95                    q.running = true;
96                    break next;
97                }
98                q.running = false;
99                WAKE.notify_all();
100                guard = WAKE.wait(guard).unwrap_or_else(PoisonError::into_inner);
101            }
102        };
103        let line = job();
104        with_queue(|q| {
105            if let Some(key) = key {
106                q.keys.remove(&key);
107            }
108            if let Some(line) = line {
109                q.answers.entry(caller).or_default().push(line);
110            }
111        });
112    }
113}
114
115/// The answers waiting for `caller`, taken (shown once).
116pub fn take(caller: &str) -> Vec<String> {
117    with_queue(|q| q.answers.remove(caller).unwrap_or_default())
118}
119
120/// `text` with the answers waiting for `caller` in front of it.
121pub fn with_answers(caller: &str, text: String) -> String {
122    earlier(caller).present(text)
123}
124
125/// The answers waiting for `caller` as a call starts, taken before the call
126/// queues anything: an answer to this call's own request, however fast Cloud
127/// answers it, always comes with the next call (CI #2183). Dropped without
128/// [`Earlier::present`] (a call that failed early), they wait again.
129pub fn earlier(caller: &str) -> Earlier {
130    Earlier {
131        caller: caller.to_string(),
132        answers: take(caller),
133    }
134}
135
136/// See [`earlier`].
137pub struct Earlier {
138    caller: String,
139    answers: Vec<String>,
140}
141
142impl Earlier {
143    /// `text` with these answers in front of it.
144    pub fn present(mut self, text: String) -> String {
145        let answers = std::mem::take(&mut self.answers);
146        if answers.is_empty() {
147            return text;
148        }
149        let mut out = String::from("The Cloud answered your earlier requests:\n");
150        for answer in answers {
151            out.push_str("- ");
152            out.push_str(&answer);
153            out.push('\n');
154        }
155        out.push('\n');
156        out.push_str(&text);
157        out
158    }
159}
160
161impl Drop for Earlier {
162    fn drop(&mut self) {
163        if self.answers.is_empty() {
164            return;
165        }
166        let answers = std::mem::take(&mut self.answers);
167        with_queue(|q| {
168            let waiting = q
169                .answers
170                .entry(std::mem::take(&mut self.caller))
171                .or_default();
172            waiting.splice(0..0, answers);
173        });
174    }
175}
176
177/// Wait until every queued request has run (tests and CLI commands that
178/// end the process); `false` when `timeout` passed first.
179pub fn wait_idle(timeout: Duration) -> bool {
180    let deadline = Instant::now() + timeout;
181    let mut guard = queue();
182    loop {
183        let idle = guard
184            .as_ref()
185            .is_none_or(|q| q.jobs.is_empty() && !q.running);
186        if idle {
187            return true;
188        }
189        let Some(left) = deadline.checked_duration_since(Instant::now()) else {
190            return false;
191        };
192        guard = WAKE
193            .wait_timeout(guard, left)
194            .unwrap_or_else(PoisonError::into_inner)
195            .0;
196    }
197}
198
199#[cfg(test)]
200mod tests {
201    use super::*;
202
203    #[test]
204    fn requests_run_in_order_off_the_caller_and_answer_once() {
205        let caller = "test:requests_run_in_order";
206        let order = std::sync::Arc::new(Mutex::new(Vec::new()));
207        for n in 0..3 {
208            let order = std::sync::Arc::clone(&order);
209            submit(caller, move || {
210                order.lock().unwrap().push(n);
211                Some(format!("answer {n}"))
212            });
213        }
214        assert!(wait_idle(Duration::from_secs(10)));
215        assert_eq!(*order.lock().unwrap(), vec![0, 1, 2]);
216        let shown = with_answers(caller, "now".into());
217        assert_eq!(
218            shown,
219            "The Cloud answered your earlier requests:\n- answer 0\n- answer 1\n- answer 2\n\nnow"
220        );
221        assert_eq!(with_answers(caller, "again".into()), "again", "shown once");
222    }
223
224    #[test]
225    fn an_answer_during_the_call_comes_with_the_next_one() {
226        let caller = "test:during_the_call";
227        let call = earlier(caller);
228        // Cloud answers before the call returns (a refused connection).
229        submit(caller, || Some("fast".into()));
230        assert!(wait_idle(Duration::from_secs(10)));
231        assert_eq!(call.present("first".into()), "first");
232        let next = earlier(caller).present("second".into());
233        assert!(
234            next.contains("- fast") && next.ends_with("second"),
235            "{next}"
236        );
237
238        // A call that fails early keeps what it took for the one after it.
239        submit(caller, || Some("kept".into()));
240        assert!(wait_idle(Duration::from_secs(10)));
241        drop(earlier(caller));
242        submit(caller, || Some("later".into()));
243        assert!(wait_idle(Duration::from_secs(10)));
244        let shown = with_answers(caller, "third".into());
245        assert!(shown.find("- kept") < shown.find("- later"), "{shown}");
246    }
247
248    #[test]
249    fn a_keyed_request_is_queued_once() {
250        let caller = "test:keyed";
251        let gate = std::sync::Arc::new((Mutex::new(false), Condvar::new()));
252        let held = std::sync::Arc::clone(&gate);
253        assert!(submit_once(caller, "test:key", move || {
254            let (open, cv) = &*held;
255            let mut open = open.lock().unwrap();
256            while !*open {
257                open = cv.wait(open).unwrap();
258            }
259            None
260        }));
261        assert!(!submit_once(caller, "test:key", || None), "already queued");
262        *gate.0.lock().unwrap() = true;
263        gate.1.notify_all();
264        assert!(wait_idle(Duration::from_secs(10)));
265        assert!(submit_once(caller, "test:key", || None), "done, so again");
266        assert!(wait_idle(Duration::from_secs(10)));
267    }
268}