返回 CodeWhale
turn_budget.rs
根目录 / crates / runtime / src / turn_budget.rs
1 //! Turn budgets shared by interactive hosts and headless execution.
2 //!
3 //! Model steps and the cumulative per-turn wall clock are uncapped by
4 //! default. Explicit positive limits still apply; neither a step counter nor
5 //! elapsed time is a measure of useful progress, and a long autonomous turn
6 //! should not stop at an arbitrary hour. Per-step stream budgets remain
7 //! finite: they bound one stuck request, not the whole turn.
8 //!
9 //! `EngineConfig` retains its integer representation for embedders:
10 //! `u32::MAX` represents no model-step limit. `TurnContext::step_limit`
11 //! resolves that representation to `None` before checking a ceiling or
12 //! emitting diagnostics. It is not a very large finite fallback.
13 //!
14 //! ## Honesty at the limit
15 //!
16 //! Hitting a budget is never a clean success. The step ceiling already ends
17 //! the turn as `TurnOutcomeStatus::Failed` with the limit named (or, when
18 //! the model still owes work, grants exactly one bounded final-report turn
19 //! first). [`TurnWallClock`] follows the same contract in `run_turn`.
20
21 use std::time::{Duration, Instant};
22
23 /// No model-step limit unless the caller configures one. This is the
24 /// compatibility representation, not a ceiling checked at `u32::MAX`.
25 pub const DEFAULT_MAX_MODEL_STEPS: u32 = u32::MAX;
26
27 /// No per-turn wall-clock limit unless the caller configures one.
28 ///
29 /// `Duration::MAX` is the representation, mirroring
30 /// [`DEFAULT_MAX_MODEL_STEPS`]: [`TurnWallClock::exhausted`] can never reach
31 /// it, and callers turning it into an absolute deadline must use
32 /// `checked_add` (see `exec_agent`). When configured, the budget is measured
33 /// across every model step of one turn, not per request, and time blocked on
34 /// a human approval decision is excluded (see
35 /// [`TurnWallClock::begin_human_wait`]).
36 pub const DEFAULT_TURN_WALL_CLOCK: Duration = Duration::MAX;
37
38 /// Default per-step cap on accumulated streamed content, in bytes: the total
39 /// text, reasoning and tool-argument content before aborting the stream.
40 /// Preserves the pre-R1 hard-coded value; R1 only makes it overridable.
41 pub const DEFAULT_STREAM_MAX_CONTENT_BYTES: usize = 10 * 1024 * 1024;
42 /// Smallest accepted per-step stream content cap (64 KiB).
43 pub const MIN_STREAM_MAX_CONTENT_BYTES: usize = 64 * 1024;
44 /// Largest accepted per-step stream content cap (512 MiB).
45 pub const MAX_STREAM_MAX_CONTENT_BYTES: usize = 512 * 1024 * 1024;
46
47 /// Default per-step cap on a single stream's wall-clock duration, in
48 /// seconds. Preserves the pre-R1 hard-coded value.
49 ///
50 /// Sanity backstop for total stream wall-clock duration. **Not** a routine
51 /// kill switch — the stream chunk idle timeout is the primary stall
52 /// detector. The wall-clock cap is here only to bound pathological cases
53 /// (e.g. a server that keeps sending heartbeats forever without progress).
54 ///
55 /// History: this used to be 300s (5 min) which was too aggressive — V4
56 /// thinking turns on hard prompts legitimately exceed 5 minutes wall-clock
57 /// while still emitting reasoning_content chunks the whole way. Bumped to
58 /// 30 min in v0.6.6 after long-reasoning turns hit the old cap. Codex defaults to a
59 /// per-chunk idle of 300s with no wall-clock cap; we keep both layers but
60 /// give the wall-clock a generous window so it never fires in practice.
61 pub const DEFAULT_STREAM_MAX_DURATION_SECS: u64 = 1800;
62 /// Smallest accepted per-step stream duration cap.
63 pub const MIN_STREAM_MAX_DURATION_SECS: u64 = 10;
64 /// Largest accepted per-step stream duration cap (24 hours).
65 pub const MAX_STREAM_MAX_DURATION_SECS: u64 = 86_400;
66
67 /// Default retry budget for proven pre-dispatch stream-open failures.
68 /// An unknown dispatched outcome never spends this budget to replay a POST.
69 pub const DEFAULT_STREAM_MAX_RESUMES: u32 = 3;
70 /// Largest accepted safe-open retry budget. `0` disables outer open retries.
71 pub const MAX_STREAM_MAX_RESUMES: u32 = 10;
72 pub const DEFAULT_STREAM_OPEN_RETRIES: u32 = 1;
73 pub const MAX_STREAM_OPEN_RETRIES: u32 = 3;
74 pub const DEFAULT_STREAM_UNKNOWN_OUTCOME_RETRIES: u32 = 0;
75 pub const MAX_STREAM_UNKNOWN_OUTCOME_RETRIES: u32 = 3;
76 /// Historical default retained for configuration compatibility; inactive in Core.
77 pub const DEFAULT_STREAM_MAX_TRANSPARENT_RETRIES: u32 = 2;
78 /// Historical accepted bound for the inactive compatibility setting.
79 pub const MAX_STREAM_MAX_TRANSPARENT_RETRIES: u32 = 10;
80 /// Historical error-count default retained for compatibility; Core ends on
81 /// the first uncertain admitted stream error.
82 pub const DEFAULT_STREAM_MAX_ERRORS: u32 = 5;
83 /// Smallest accepted compatibility value. `0` selects the historical default.
84 pub const MIN_STREAM_MAX_ERRORS: u32 = 1;
85 /// Largest accepted compatibility value.
86 pub const MAX_STREAM_MAX_ERRORS: u32 = 50;
87
88 /// Stream-open retries and parsed historical stream settings. The compatibility
89 /// fields never authorize replay or error tolerance for an opened stream.
90 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
91 pub struct StreamRetryLimits {
92 /// Proven pre-dispatch stream-open retries.
93 pub max_resumes: u32,
94 pub open_retries: u32,
95 pub unknown_outcome_retries: u32,
96 /// Inactive Core compatibility setting.
97 pub max_transparent_retries: u32,
98 /// Inactive Core compatibility setting; an uncertain error ends the stream.
99 pub max_errors: u32,
100 }
101
102 impl Default for StreamRetryLimits {
103 fn default() -> Self {
104 resolve_stream_retry_limits(None, None, None, None, None)
105 }
106 }
107
108 /// Resolve configured stream retry budgets.
109 ///
110 /// `None` selects each default. The retry counts accept `0` (no
111 /// retries) and clamp to their maximum. The error streak is a finite stream
112 /// budget like `stream_max_content_mb`: `0` selects its default, and other
113 /// values clamp to `MIN_STREAM_MAX_ERRORS..=MAX_STREAM_MAX_ERRORS`.
114 #[must_use]
115 pub fn resolve_stream_retry_limits(
116 max_resumes: Option<u32>,
117 max_transparent_retries: Option<u32>,
118 max_errors: Option<u32>,
119 open_retries: Option<u32>,
120 unknown_outcome_retries: Option<u32>,
121 ) -> StreamRetryLimits {
122 StreamRetryLimits {
123 max_resumes: max_resumes
124 .unwrap_or(DEFAULT_STREAM_MAX_RESUMES)
125 .min(MAX_STREAM_MAX_RESUMES),
126 open_retries: open_retries
127 .unwrap_or(DEFAULT_STREAM_OPEN_RETRIES)
128 .min(MAX_STREAM_OPEN_RETRIES),
129 unknown_outcome_retries: unknown_outcome_retries
130 .unwrap_or(DEFAULT_STREAM_UNKNOWN_OUTCOME_RETRIES)
131 .min(MAX_STREAM_UNKNOWN_OUTCOME_RETRIES),
132 max_transparent_retries: max_transparent_retries
133 .unwrap_or(DEFAULT_STREAM_MAX_TRANSPARENT_RETRIES)
134 .min(MAX_STREAM_MAX_TRANSPARENT_RETRIES),
135 max_errors: match max_errors {
136 None | Some(0) => DEFAULT_STREAM_MAX_ERRORS,
137 Some(value) => value.clamp(MIN_STREAM_MAX_ERRORS, MAX_STREAM_MAX_ERRORS),
138 },
139 }
140 }
141
142 /// Resolve a configured model-step ceiling.
143 ///
144 /// `None` and `0` select the uncapped default. Positive values are preserved;
145 /// `u32::MAX` remains the compatibility representation for no limit.
146 #[must_use]
147 pub fn resolve_max_model_steps(raw: Option<u32>) -> u32 {
148 match raw {
149 None | Some(0) => DEFAULT_MAX_MODEL_STEPS,
150 Some(value) => value,
151 }
152 }
153
154 /// Resolve a configured per-turn wall-clock budget.
155 ///
156 /// `None` and `0` select the uncapped default ([`DEFAULT_TURN_WALL_CLOCK`]).
157 /// Explicit positive values, in seconds, are preserved.
158 #[must_use]
159 pub fn resolve_turn_wall_clock(raw: Option<u64>) -> Duration {
160 match raw {
161 None | Some(0) => DEFAULT_TURN_WALL_CLOCK,
162 Some(value) => Duration::from_secs(value),
163 }
164 }
165
166 /// Resolve a configured per-step stream content cap, given megabytes.
167 ///
168 /// `None` and `0` both resolve to [`DEFAULT_STREAM_MAX_CONTENT_BYTES`].
169 #[must_use]
170 pub fn resolve_stream_max_content_bytes(raw_mb: Option<u64>) -> usize {
171 match raw_mb {
172 None | Some(0) => DEFAULT_STREAM_MAX_CONTENT_BYTES,
173 Some(mb) => usize::try_from(mb.saturating_mul(1024 * 1024))
174 .unwrap_or(MAX_STREAM_MAX_CONTENT_BYTES)
175 .clamp(MIN_STREAM_MAX_CONTENT_BYTES, MAX_STREAM_MAX_CONTENT_BYTES),
176 }
177 }
178
179 /// Resolve a configured per-step stream duration cap, in seconds.
180 ///
181 /// `None` and `0` both resolve to [`DEFAULT_STREAM_MAX_DURATION_SECS`].
182 #[must_use]
183 pub fn resolve_stream_max_duration_secs(raw: Option<u64>) -> u64 {
184 match raw {
185 None | Some(0) => DEFAULT_STREAM_MAX_DURATION_SECS,
186 Some(value) => value.clamp(MIN_STREAM_MAX_DURATION_SECS, MAX_STREAM_MAX_DURATION_SECS),
187 }
188 }
189
190 /// Cumulative wall-clock budget for one turn.
191 ///
192 /// Started once at the top of `Engine::run_turn` and checked at the
193 /// provider-request boundary, so a turn that trips the budget stops before
194 /// authorizing another billable request and keeps every tool result already
195 /// in the transcript.
196 ///
197 /// Time blocked on a human approval decision is excluded: the budget bounds
198 /// what the agent spends on its own, not how long a person takes to answer.
199 /// Without that exclusion an approval prompt left open overnight would fail
200 /// the turn — and discard the work the user just approved — the moment they
201 /// came back.
202 #[derive(Debug)]
203 pub struct TurnWallClock {
204 budget: Duration,
205 started_at: Instant,
206 /// Total time already excluded because the turn was blocked on a human.
207 excluded: Duration,
208 /// Set while currently blocked on a human decision.
209 blocked_since: Option<Instant>,
210 }
211
212 impl TurnWallClock {
213 /// Start a fresh budget. A zero budget is legal here (and only here):
214 /// it is how tests assert the stop path without sleeping. Configuration
215 /// never produces one — [`resolve_turn_wall_clock`] reads `0` as no limit.
216 pub fn start(budget: Duration) -> Self {
217 Self {
218 budget,
219 started_at: Instant::now(),
220 excluded: Duration::ZERO,
221 blocked_since: None,
222 }
223 }
224
225 /// The budget this clock was started with.
226 pub fn budget(&self) -> Duration {
227 self.budget
228 }
229
230 /// Wall-clock time this turn has spent on its own work, excluding time
231 /// blocked on a human decision.
232 pub fn spent(&self) -> Duration {
233 let blocked_now = self
234 .blocked_since
235 .map_or(Duration::ZERO, |since| since.elapsed());
236 self.started_at
237 .elapsed()
238 .saturating_sub(self.excluded)
239 .saturating_sub(blocked_now)
240 }
241
242 /// Whether the cumulative budget is spent.
243 pub fn exhausted(&self) -> bool {
244 self.spent() >= self.budget
245 }
246
247 /// Stop counting: the turn is now waiting on a human decision.
248 /// Idempotent — a second call while already blocked does nothing, so a
249 /// nested or re-entered approval cannot double-exclude.
250 pub fn begin_human_wait(&mut self) {
251 if self.blocked_since.is_none() {
252 self.blocked_since = Some(Instant::now());
253 }
254 }
255
256 /// Resume counting after a human decision, banking the blocked time.
257 pub fn end_human_wait(&mut self) {
258 if let Some(since) = self.blocked_since.take() {
259 self.excluded = self.excluded.saturating_add(since.elapsed());
260 }
261 }
262
263 /// Test-only: pretend `elapsed` more wall-clock time has passed, so the
264 /// exhaustion path can be exercised without sleeping. An in-progress
265 /// human wait is rewound too — otherwise the simulated time would count
266 /// as agent-owned work that never actually happened.
267 #[cfg(any(test, feature = "test-support"))]
268 pub fn rewind_for_test(&mut self, elapsed: Duration) {
269 self.started_at = self
270 .started_at
271 .checked_sub(elapsed)
272 .unwrap_or(self.started_at);
273 if let Some(since) = self.blocked_since {
274 self.blocked_since = Some(since.checked_sub(elapsed).unwrap_or(since));
275 }
276 }
277 }
278
279 #[cfg(test)]
280 mod tests {
281 use super::*;
282
283 #[test]
284 fn model_step_defaults_do_not_install_a_ceiling() {
285 assert_eq!(resolve_max_model_steps(None), DEFAULT_MAX_MODEL_STEPS);
286 assert_eq!(resolve_max_model_steps(Some(0)), DEFAULT_MAX_MODEL_STEPS);
287 assert_eq!(DEFAULT_MAX_MODEL_STEPS, u32::MAX);
288 assert_eq!(resolve_max_model_steps(Some(u32::MAX)), u32::MAX);
289 }
290
291 #[test]
292 fn model_step_ceiling_preserves_the_owner_limit() {
293 assert_eq!(resolve_max_model_steps(Some(7)), 7);
294 assert_eq!(resolve_max_model_steps(Some(1)), 1);
295 assert_eq!(
296 resolve_max_model_steps(Some(200_000)),
297 200_000,
298 "explicit positive overrides retain the configured ceiling"
299 );
300 }
301
302 #[test]
303 fn turn_wall_clock_defaults_to_no_limit() {
304 assert_eq!(resolve_turn_wall_clock(None), DEFAULT_TURN_WALL_CLOCK);
305 assert_eq!(resolve_turn_wall_clock(Some(0)), DEFAULT_TURN_WALL_CLOCK);
306 let mut clock = TurnWallClock::start(resolve_turn_wall_clock(None));
307 clock.rewind_for_test(Duration::from_secs(10 * 24 * 60 * 60));
308 assert!(!clock.exhausted(), "the default never stops a turn");
309 }
310
311 /// Code mode and headless exec sleep toward what is left of the default
312 /// budget; a near-`Duration::MAX` sleep must park, not panic.
313 #[tokio::test]
314 async fn an_unbounded_remaining_budget_is_a_safe_sleep() {
315 let remaining = DEFAULT_TURN_WALL_CLOCK.saturating_sub(Duration::from_secs(1));
316 let woke =
317 tokio::time::timeout(Duration::from_millis(20), tokio::time::sleep(remaining)).await;
318 assert!(woke.is_err(), "the sleep parks until cancelled");
319 let started = std::time::Instant::now();
320 assert!(started.checked_add(remaining).is_none());
321 }
322
323 #[test]
324 fn turn_wall_clock_preserves_the_owner_limit() {
325 assert_eq!(resolve_turn_wall_clock(Some(120)), Duration::from_secs(120));
326 assert_eq!(resolve_turn_wall_clock(Some(1)), Duration::from_secs(1));
327 assert_eq!(
328 resolve_turn_wall_clock(Some(u64::MAX)),
329 Duration::from_secs(u64::MAX)
330 );
331 }
332
333 #[test]
334 fn stream_caps_default_reject_zero_and_are_overridable() {
335 assert_eq!(
336 resolve_stream_max_content_bytes(None),
337 DEFAULT_STREAM_MAX_CONTENT_BYTES
338 );
339 assert_eq!(
340 resolve_stream_max_content_bytes(Some(0)),
341 DEFAULT_STREAM_MAX_CONTENT_BYTES
342 );
343 assert_eq!(resolve_stream_max_content_bytes(Some(1)), 1024 * 1024);
344 assert_eq!(
345 resolve_stream_max_content_bytes(Some(u64::MAX)),
346 MAX_STREAM_MAX_CONTENT_BYTES
347 );
348
349 assert_eq!(
350 resolve_stream_max_duration_secs(None),
351 DEFAULT_STREAM_MAX_DURATION_SECS
352 );
353 assert_eq!(
354 resolve_stream_max_duration_secs(Some(0)),
355 DEFAULT_STREAM_MAX_DURATION_SECS
356 );
357 assert_eq!(resolve_stream_max_duration_secs(Some(60)), 60);
358 assert_eq!(
359 resolve_stream_max_duration_secs(Some(u64::MAX)),
360 MAX_STREAM_MAX_DURATION_SECS
361 );
362 }
363
364 #[test]
365 fn stream_retry_limits_default_to_historical_values_and_clamp() {
366 let defaults = resolve_stream_retry_limits(None, None, None, None, None);
367 assert_eq!(defaults, StreamRetryLimits::default());
368 assert_eq!(defaults.max_resumes, 3);
369 assert_eq!(defaults.open_retries, 1);
370 assert_eq!(defaults.unknown_outcome_retries, 0);
371 assert_eq!(defaults.max_transparent_retries, 2);
372 assert_eq!(defaults.max_errors, 5);
373 assert_eq!(
374 resolve_stream_retry_limits(None, None, None, None, Some(2)).unknown_outcome_retries,
375 2
376 );
377
378 let disabled = resolve_stream_retry_limits(Some(0), Some(0), Some(0), Some(0), Some(0));
379 assert_eq!(disabled.max_resumes, 0, "0 disables resumes");
380 assert_eq!(
381 disabled.open_retries, 0,
382 "0 disables header-timeout retries"
383 );
384 assert_eq!(
385 disabled.unknown_outcome_retries, 0,
386 "0 disables unknown-outcome retries"
387 );
388 assert_eq!(disabled.max_transparent_retries, 0);
389 assert_eq!(
390 disabled.max_errors, DEFAULT_STREAM_MAX_ERRORS,
391 "0 selects the error-streak default, like the other finite stream budgets"
392 );
393 assert_eq!(
394 resolve_stream_retry_limits(None, None, Some(1), None, None).max_errors,
395 MIN_STREAM_MAX_ERRORS
396 );
397
398 let huge = resolve_stream_retry_limits(
399 Some(u32::MAX),
400 Some(u32::MAX),
401 Some(u32::MAX),
402 Some(u32::MAX),
403 Some(u32::MAX),
404 );
405 assert_eq!(huge.max_resumes, MAX_STREAM_MAX_RESUMES);
406 assert_eq!(huge.open_retries, MAX_STREAM_OPEN_RETRIES);
407 assert_eq!(
408 huge.unknown_outcome_retries,
409 MAX_STREAM_UNKNOWN_OUTCOME_RETRIES
410 );
411 assert_eq!(
412 huge.max_transparent_retries,
413 MAX_STREAM_MAX_TRANSPARENT_RETRIES
414 );
415 assert_eq!(huge.max_errors, MAX_STREAM_MAX_ERRORS);
416 }
417
418 #[test]
419 fn wall_clock_exhausts_once_the_budget_is_spent() {
420 let mut clock = TurnWallClock::start(Duration::from_secs(60));
421 assert!(!clock.exhausted());
422 clock.rewind_for_test(Duration::from_secs(61));
423 assert!(clock.exhausted());
424 assert!(clock.spent() >= clock.budget());
425 }
426
427 #[test]
428 fn wall_clock_excludes_time_blocked_on_a_human_decision() {
429 let mut clock = TurnWallClock::start(Duration::from_secs(60));
430 clock.begin_human_wait();
431 // The human took two minutes; the agent spent none of its budget.
432 clock.rewind_for_test(Duration::from_secs(120));
433 assert!(
434 !clock.exhausted(),
435 "an unanswered approval prompt must not burn the turn budget"
436 );
437 clock.end_human_wait();
438 assert!(!clock.exhausted());
439 // Agent-owned time after the decision still counts.
440 clock.rewind_for_test(Duration::from_secs(61));
441 assert!(clock.exhausted());
442 }
443
444 #[test]
445 fn nested_human_waits_cannot_double_exclude() {
446 let mut clock = TurnWallClock::start(Duration::from_secs(60));
447 clock.begin_human_wait();
448 clock.begin_human_wait();
449 clock.rewind_for_test(Duration::from_secs(30));
450 clock.end_human_wait();
451 // A second unmatched end is a no-op, not another exclusion.
452 clock.end_human_wait();
453 clock.rewind_for_test(Duration::from_secs(61));
454 assert!(clock.exhausted());
455 }
456 }
457
457 lines RUST