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