Skip to main content

weirdnet_agent/
budget.rs

1//! Research budgets: searches, pages, concurrency and time.
2
3use std::sync::atomic::{AtomicU32, Ordering};
4use std::sync::{Arc, Mutex};
5use std::time::Duration;
6
7use serde::{Deserialize, Serialize};
8use tokio::sync::{OwnedSemaphorePermit, Semaphore};
9use tokio::time::Instant;
10
11/// Limits for one task. Defaults follow Companions design decision 21.
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
13pub struct Budget {
14    pub max_searches: u32,
15    pub max_pages: u32,
16    /// Pages added by one user-approved extension ("+5 pages").
17    pub page_extension: u32,
18    /// Hidden views or fetches at a time.
19    pub max_concurrent: u32,
20    pub per_page: Duration,
21    /// Time the task's tools may run, in total. Only time inside tool calls counts (see
22    /// [`BudgetTracker::time_tool`]): model turns and waiting for the user to answer an
23    /// approval card do not.
24    pub per_task: Duration,
25    /// Tokens of extracted text kept per page.
26    pub tokens_per_page: u32,
27    /// Model turns per task.
28    pub max_steps: u32,
29}
30
31impl Default for Budget {
32    fn default() -> Self {
33        Self {
34            max_searches: 3,
35            max_pages: 12,
36            page_extension: 5,
37            max_concurrent: 2,
38            per_page: Duration::from_secs(15),
39            per_task: Duration::from_secs(90),
40            tokens_per_page: 4_000,
41            max_steps: 16,
42        }
43    }
44}
45
46#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, thiserror::Error)]
47#[serde(rename_all = "snake_case", tag = "kind")]
48#[non_exhaustive]
49pub enum BudgetExceeded {
50    #[error("search budget used ({limit} searches)")]
51    Searches { limit: u32 },
52    #[error("page budget used ({limit} pages)")]
53    Pages { limit: u32 },
54    #[error("task time budget used ({limit_ms} ms)")]
55    Time { limit_ms: u64 },
56    #[error("step budget used ({limit} steps)")]
57    Steps { limit: u32 },
58}
59
60/// What a task has used so far.
61#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
62pub struct BudgetUsage {
63    pub searches: u32,
64    pub pages: u32,
65    pub page_limit: u32,
66    /// Tool time used, the time counted against [`Budget::per_task`].
67    pub elapsed_ms: u64,
68}
69
70/// Live counters for one task. Cheap to share by reference across tool calls.
71#[derive(Debug)]
72pub struct BudgetTracker {
73    budget: Budget,
74    searches: AtomicU32,
75    pages: AtomicU32,
76    extensions: AtomicU32,
77    started: Instant,
78    tools: Mutex<ToolClock>,
79    slots: Arc<Semaphore>,
80}
81
82/// Time spent in tool calls. Overlapping calls count once (wall time while any runs).
83#[derive(Debug, Default)]
84struct ToolClock {
85    spent: Duration,
86    running: u32,
87    since: Option<Instant>,
88}
89
90impl ToolClock {
91    fn now(&self) -> Duration {
92        self.spent + self.since.map(|t| t.elapsed()).unwrap_or_default()
93    }
94}
95
96/// Counts tool time against the task budget until dropped (see [`BudgetTracker::time_tool`]).
97#[derive(Debug)]
98#[must_use = "tool time counts only while the timer is held"]
99pub struct ToolTimer<'a> {
100    tracker: &'a BudgetTracker,
101}
102
103impl Drop for ToolTimer<'_> {
104    fn drop(&mut self) {
105        let mut c = self.tracker.tools.lock().unwrap_or_else(|e| e.into_inner());
106        c.running = c.running.saturating_sub(1);
107        if c.running == 0
108            && let Some(t) = c.since.take()
109        {
110            c.spent += t.elapsed();
111        }
112    }
113}
114
115impl BudgetTracker {
116    pub fn start(budget: Budget) -> Self {
117        Self {
118            budget,
119            searches: AtomicU32::new(0),
120            pages: AtomicU32::new(0),
121            extensions: AtomicU32::new(0),
122            started: Instant::now(),
123            tools: Mutex::new(ToolClock::default()),
124            slots: Arc::new(Semaphore::new(budget.max_concurrent.max(1) as usize)),
125        }
126    }
127
128    pub fn budget(&self) -> &Budget {
129        &self.budget
130    }
131
132    fn take(counter: &AtomicU32, limit: u32) -> bool {
133        counter.try_update(Ordering::SeqCst, Ordering::SeqCst, |n| (n < limit).then_some(n + 1)).is_ok()
134    }
135
136    pub fn charge_search(&self) -> Result<(), BudgetExceeded> {
137        self.check_time()?;
138        let limit = self.budget.max_searches;
139        if Self::take(&self.searches, limit) { Ok(()) } else { Err(BudgetExceeded::Searches { limit }) }
140    }
141
142    pub fn page_limit(&self) -> u32 {
143        self.budget.max_pages + self.extensions.load(Ordering::SeqCst) * self.budget.page_extension
144    }
145
146    pub fn charge_page(&self) -> Result<(), BudgetExceeded> {
147        self.check_time()?;
148        let limit = self.page_limit();
149        if Self::take(&self.pages, limit) { Ok(()) } else { Err(BudgetExceeded::Pages { limit }) }
150    }
151
152    /// Adds one page extension. Call only after the user asked for more pages.
153    pub fn extend_pages(&self) -> u32 {
154        self.extensions.fetch_add(1, Ordering::SeqCst);
155        self.page_limit()
156    }
157
158    /// Tool time used so far: what [`Budget::per_task`] limits.
159    pub fn elapsed(&self) -> Duration {
160        self.tools.lock().unwrap_or_else(|e| e.into_inner()).now()
161    }
162
163    /// Wall time since the task started, model turns and approval waits included (not limited;
164    /// for display and logs).
165    pub fn wall_elapsed(&self) -> Duration {
166        self.started.elapsed()
167    }
168
169    /// Starts counting tool time; it counts until the timer is dropped. The session holds one
170    /// around every tool call. Timers that overlap count the shared time once.
171    pub fn time_tool(&self) -> ToolTimer<'_> {
172        let mut c = self.tools.lock().unwrap_or_else(|e| e.into_inner());
173        if c.running == 0 {
174            c.since = Some(Instant::now());
175        }
176        c.running += 1;
177        ToolTimer { tracker: self }
178    }
179
180    /// Tool time left.
181    pub fn remaining(&self) -> Duration {
182        self.budget.per_task.saturating_sub(self.elapsed())
183    }
184
185    pub fn check_time(&self) -> Result<(), BudgetExceeded> {
186        if self.remaining().is_zero() { Err(BudgetExceeded::Time { limit_ms: self.budget.per_task.as_millis() as u64 }) } else { Ok(()) }
187    }
188
189    /// Time a page fetch may take: the per-page limit or what's left of the task.
190    pub fn page_timeout(&self) -> Duration {
191        self.budget.per_page.min(self.remaining())
192    }
193
194    /// Waits for a concurrency slot (hidden view or fetch).
195    pub async fn acquire_slot(&self) -> OwnedSemaphorePermit {
196        self.slots.clone().acquire_owned().await.expect("budget semaphore is never closed")
197    }
198
199    pub fn usage(&self) -> BudgetUsage {
200        BudgetUsage {
201            searches: self.searches.load(Ordering::SeqCst),
202            pages: self.pages.load(Ordering::SeqCst),
203            page_limit: self.page_limit(),
204            elapsed_ms: self.elapsed().as_millis() as u64,
205        }
206    }
207}
208
209#[cfg(test)]
210mod tests {
211    use super::*;
212
213    #[tokio::test(start_paused = true)]
214    async fn searches_and_pages_are_capped_and_extendable() {
215        let t = BudgetTracker::start(Budget::default());
216        for _ in 0..3 {
217            t.charge_search().unwrap();
218        }
219        assert_eq!(t.charge_search(), Err(BudgetExceeded::Searches { limit: 3 }));
220        for _ in 0..12 {
221            t.charge_page().unwrap();
222        }
223        assert_eq!(t.charge_page(), Err(BudgetExceeded::Pages { limit: 12 }));
224        assert_eq!(t.extend_pages(), 17);
225        for _ in 0..5 {
226            t.charge_page().unwrap();
227        }
228        assert!(t.charge_page().is_err());
229        let u = t.usage();
230        assert_eq!((u.searches, u.pages, u.page_limit), (3, 17, 17));
231    }
232
233    #[tokio::test(start_paused = true)]
234    async fn time_budget_runs_out_on_tool_time() {
235        let t = BudgetTracker::start(Budget::default());
236        assert_eq!(t.page_timeout(), Duration::from_secs(15));
237        let timer = t.time_tool();
238        tokio::time::advance(Duration::from_secs(80)).await;
239        assert_eq!(t.page_timeout(), Duration::from_secs(10));
240        tokio::time::advance(Duration::from_secs(10)).await;
241        drop(timer);
242        assert_eq!(t.check_time(), Err(BudgetExceeded::Time { limit_ms: 90_000 }));
243        assert!(matches!(t.charge_page(), Err(BudgetExceeded::Time { .. })));
244        assert_eq!(t.usage().elapsed_ms, 90_000);
245    }
246
247    #[tokio::test(start_paused = true)]
248    async fn only_tool_time_counts() {
249        let t = BudgetTracker::start(Budget::default());
250        // A model turn or an approval card: no timer, nothing counted.
251        tokio::time::advance(Duration::from_secs(600)).await;
252        assert_eq!(t.elapsed(), Duration::ZERO);
253        assert!(t.check_time().is_ok());
254        {
255            let _call = t.time_tool();
256            tokio::time::advance(Duration::from_secs(5)).await;
257            assert_eq!(t.elapsed(), Duration::from_secs(5), "counts while the call runs");
258        }
259        tokio::time::advance(Duration::from_secs(60)).await;
260        assert_eq!(t.elapsed(), Duration::from_secs(5));
261        assert_eq!(t.wall_elapsed(), Duration::from_secs(665));
262        assert_eq!(t.remaining(), Duration::from_secs(85));
263    }
264
265    #[tokio::test(start_paused = true)]
266    async fn overlapping_tool_calls_count_once() {
267        let t = BudgetTracker::start(Budget::default());
268        let a = t.time_tool();
269        tokio::time::advance(Duration::from_secs(2)).await;
270        let b = t.time_tool();
271        tokio::time::advance(Duration::from_secs(3)).await;
272        drop(a);
273        tokio::time::advance(Duration::from_secs(1)).await;
274        drop(b);
275        tokio::time::advance(Duration::from_secs(10)).await;
276        assert_eq!(t.elapsed(), Duration::from_secs(6));
277    }
278
279    #[tokio::test(start_paused = true)]
280    async fn concurrency_slots() {
281        let t = BudgetTracker::start(Budget::default());
282        let a = t.acquire_slot().await;
283        let _b = t.acquire_slot().await;
284        let third = tokio::time::timeout(Duration::from_millis(10), t.acquire_slot()).await;
285        assert!(third.is_err());
286        drop(a);
287        let _c = tokio::time::timeout(Duration::from_millis(10), t.acquire_slot()).await.unwrap();
288    }
289
290    #[test]
291    fn serde_roundtrip() {
292        let b = Budget::default();
293        let back: Budget = serde_json::from_str(&serde_json::to_string(&b).unwrap()).unwrap();
294        assert_eq!(b, back);
295    }
296}