返回 CodeWhale
limits_tests.rs
根目录 / crates / engine / src / tools / subagent / limits_tests.rs
1 use super::tests::{make_snapshot, make_worker_spec, stub_runtime};
2 use super::*;
3 use tempfile::tempdir;
4
5 #[test]
6 fn depth_one_child_cannot_spawn_a_grandchild_even_with_a_wider_profile() {
7 let root = stub_runtime().with_max_spawn_depth(1);
8 let mut child = root.child_runtime();
9 child.worker_profile = worker_profile_for_spawn(
10 &child,
11 &FleetRole::Worker,
12 &AgentWorkerToolProfile::Inherited,
13 "deepseek-v4-flash",
14 None,
15 false,
16 );
17 assert_eq!(child.spawn_depth, 1);
18 assert_eq!(child.max_spawn_depth, 1);
19 assert_eq!(child.worker_profile.max_spawn_depth, 1);
20 assert_eq!(child.worker_profile.spawn_depth, 1);
21 assert!(child.would_exceed_depth());
22 assert!(!child.worker_profile.can_spawn_child());
23 child.worker_profile.max_spawn_depth = u32::MAX;
24 assert!(
25 child.would_exceed_depth(),
26 "a widened projection cannot bypass runtime ceiling"
27 );
28 assert!(child.background_runtime().would_exceed_depth());
29 }
30
31 #[test]
32 fn depth_overflow_fails_closed() {
33 let mut runtime = stub_runtime();
34 runtime.spawn_depth = u32::MAX;
35 runtime.max_spawn_depth = u32::MAX;
36 assert!(runtime.would_exceed_depth());
37 assert_eq!(runtime.child_runtime().spawn_depth, u32::MAX);
38 }
39
40 #[test]
41 fn old_relative_profile_depth_does_not_gain_authority_on_recovery() {
42 let tmp = tempdir().unwrap();
43 let mut spec = make_worker_spec("legacy", tmp.path().to_path_buf());
44 spec.spawn_depth = 2;
45 spec.max_spawn_depth = 3;
46 spec.runtime_profile.max_spawn_depth = 1; // old remaining allowance
47 let record = AgentWorkerRecord::new(spec, epoch_millis_now());
48 let mut encoded = serde_json::to_value(&record).unwrap();
49 encoded["spec"]["runtime_profile"]
50 .as_object_mut()
51 .unwrap()
52 .remove("spawn_depth");
53 let decoded: AgentWorkerRecord = serde_json::from_value(encoded).unwrap();
54 let recovered = normalize_worker_record(decoded);
55 assert_eq!(recovered.spec.runtime_profile.spawn_depth, 2);
56 assert_eq!(recovered.spec.max_spawn_depth, 1);
57 assert_eq!(recovered.spec.runtime_profile.max_spawn_depth, 1);
58 assert!(!recovered.spec.runtime_profile.can_spawn_child());
59 }
60
61 #[test]
62 fn operator_and_inherited_budgets_only_narrow_including_zero_sentinels() {
63 assert_eq!(resolve_max_steps(FleetRole::Worker, Some(99), Some(7)), 7);
64 assert_eq!(resolve_max_steps(FleetRole::Worker, Some(0), Some(7)), 7);
65 let parent = WorkerRuntimeProfile {
66 max_steps: 8,
67 wall_time_secs: Some(40),
68 wall_deadline_ms: Some(123_000),
69 ..WorkerRuntimeProfile::default()
70 };
71 let requested = WorkerRuntimeProfile {
72 wall_time_secs: Some(4_000),
73 wall_deadline_ms: Some(456_000),
74 ..WorkerRuntimeProfile::default()
75 };
76 let child = parent.derive_child(&requested);
77 assert_eq!(child.max_steps, 8);
78 assert_eq!(child.wall_time_secs, Some(40));
79 assert_eq!(child.wall_deadline_ms, Some(123_000));
80 }
81
82 #[test]
83 fn child_runtime_budget_context_reports_every_resolved_limit() {
84 let mut runtime = stub_runtime();
85 runtime.worker_profile.wall_time_secs = Some(1_800);
86 runtime.worker_profile.wall_deadline_ms = Some(epoch_millis_now() + 1_700_000);
87 let context = child_runtime_budget_context(&runtime, 50);
88 assert!(context.contains("Runtime limits:"));
89 assert!(context.contains("wall clock: task work stops about"));
90 assert!(context.contains("total run budget 30m 00s"));
91 assert!(context.contains("50 model turns"));
92 assert!(!context.contains("reserved"));
93 assert!(context.contains("configured owner limits are enforced"));
94 assert!(context.contains("There is no token budget and no per-step context cap"));
95 }
96
97 #[test]
98 fn child_runtime_budget_context_names_unbounded_limits_honestly() {
99 let runtime = stub_runtime();
100 let context = child_runtime_budget_context(&runtime, 0);
101 assert!(context.contains("wall clock: no wall-clock limit."));
102 assert!(context.contains("model steps: no per-run step cap."));
103 assert!(context.contains("There is no token budget"));
104 assert!(context.contains("Continue until the task is complete"));
105 assert!(!context.contains("reserved hand-back turn"));
106 }
107
108 #[test]
109 fn child_runtime_budget_context_tells_the_child_it_compacts_like_the_parent() {
110 let mut runtime = stub_runtime();
111 let context = child_runtime_budget_context(&runtime, 0);
112 assert!(
113 !context.contains("no automatic compaction"),
114 "children compact like the parent: {context}"
115 );
116 assert!(
117 context.contains("compacts it automatically") && context.contains("the run continues"),
118 "{context}"
119 );
120 assert!(
121 !context.contains("input tokens"),
122 "no per-step input cap: {context}"
123 );
124
125 // The parent's opt-out is the child's opt-out, and the prompt says so.
126 runtime.compaction.enabled = false;
127 let context = child_runtime_budget_context(&runtime, 0);
128 assert!(
129 context.contains("Automatic context compaction is disabled for this session"),
130 "{context}"
131 );
132 assert!(!context.contains("compacts it automatically"), "{context}");
133 }
134
135 #[test]
136 fn child_compaction_config_inherits_the_parent_policy_for_the_child_route() {
137 let mut runtime = stub_runtime();
138 let route = runtime
139 .client
140 .effective_route_envelope(&runtime.model, chrono::Utc::now());
141 let window = crate::route_budget::route_context_window_tokens(
142 route.provider,
143 &route.model,
144 runtime.client.route_limits(),
145 );
146 runtime.compaction = crate::compaction::CompactionConfig {
147 enabled: false,
148 token_threshold: 12_345,
149 effective_context_window: Some(window),
150 summary_instructions: Some("keep file paths".to_string()),
151 retained_user_message_tokens: 777,
152 focus: Some("manual focus never leaks into auto passes".to_string()),
153 ..crate::compaction::CompactionConfig::default()
154 };
155
156 let config = child_compaction_config(
157 &runtime,
158 &route,
159 crate::model_profile::SupportState::Supported,
160 );
161 assert!(!config.enabled, "the parent's opt-out holds for children");
162 assert_eq!(config.token_threshold, 12_345, "same window, same trigger");
163 assert_eq!(config.effective_context_window, Some(window));
164 assert_eq!(config.model, runtime.model);
165 assert_eq!(
166 config.image_input,
167 crate::model_profile::SupportState::Supported
168 );
169 assert_eq!(
170 config.summary_instructions.as_deref(),
171 Some("keep file paths")
172 );
173 assert_eq!(config.retained_user_message_tokens, 777);
174 assert_eq!(config.focus, None);
175 assert_eq!(config.workspace, Some(runtime.context.workspace.clone()));
176
177 // A parent on a different window carries its trigger as the same
178 // fraction of the child's window, through the shared route helper.
179 runtime.compaction.enabled = true;
180 runtime.compaction.effective_context_window = Some(window.saturating_mul(2));
181 runtime.compaction.token_threshold = usize::try_from(window).unwrap();
182 let config = child_compaction_config(
183 &runtime,
184 &route,
185 crate::model_profile::SupportState::Unknown,
186 );
187 assert!(config.enabled);
188 assert_eq!(
189 config.token_threshold,
190 crate::route_budget::compaction_threshold_for_route_at_percent(
191 route.provider,
192 &route.model,
193 runtime.client.route_limits(),
194 50.0,
195 )
196 );
197 }
198
199 #[test]
200 fn per_call_budget_fields_reject_empty_zero_null_negative_and_oversized_values() {
201 for field in ["max_steps", "wall_time_secs"] {
202 for invalid in [
203 json!(0),
204 json!(-1),
205 json!(null),
206 json!(""),
207 json!("7"),
208 json!(false),
209 json!(1.5),
210 ] {
211 let mut input = json!({"prompt": "inspect"});
212 input[field] = invalid;
213 assert!(parse_spawn_request(&input).is_err(), "{input}");
214 }
215 }
216 for (field, value) in [
217 ("max_steps", u64::from(u32::MAX) + 1),
218 ("wall_time_secs", u64::MAX / 1_000 + 1),
219 ] {
220 let mut input = json!({"prompt": "inspect"});
221 input[field] = json!(value);
222 assert!(parse_spawn_request(&input).is_err(), "{input}");
223 }
224 }
225
226 #[test]
227 fn budget_partial_handback_is_bounded_and_keeps_unknown_usage_honest() {
228 let mut snapshot = make_snapshot(SubAgentStatus::Running);
229 snapshot.result = Some("partial 🐳 ".repeat(2_000));
230 let result = budget_partial_result(
231 snapshot,
232 Some(codewhale_protocol::agent_run::AgentLimitKind::WallTime),
233 "child wall-time budget exhausted",
234 None,
235 );
236 assert_eq!(result.status, SubAgentStatus::BudgetExhausted);
237 let summary = result.result.as_ref().unwrap();
238 assert!(summary.chars().count() < 4_500);
239 assert!(summary.contains("usage has not been reported"));
240 assert!(summary.contains("makes no further model request"));
241 let checkpoint = result.checkpoint.as_ref().unwrap();
242 assert!(!checkpoint.continuable);
243 assert_eq!(
244 subagent_failure_class(&result, &checkpoint.reason),
245 "wall_time_budget"
246 );
247 }
248
249 #[tokio::test]
250 async fn launch_narrows_all_limits_and_continuation_cannot_restart_deadline() {
251 let tmp = tempdir().unwrap();
252 let manager = Arc::new(RwLock::new(
253 SubAgentManager::new(tmp.path().to_path_buf(), 4)
254 .with_default_max_steps(Some(4))
255 .with_default_wall_time(Some(Duration::from_secs(10))),
256 ));
257 let mut runtime = stub_runtime().child_runtime();
258 runtime.context = ToolContext::new(tmp.path().to_path_buf());
259 runtime.manager = Arc::clone(&manager);
260 runtime.cancel_token.cancel(); // inspect admission; no provider request may run
261 let options = SubAgentSpawnOptions {
262 max_steps: Some(999),
263 wall_time: Some(Duration::from_secs(999)),
264 ..Default::default()
265 };
266 let mut guard = manager.write().await;
267 let child = guard
268 .spawn_background_with_assignment_options(
269 Arc::clone(&manager),
270 runtime.clone(),
271 FleetRole::Scout,
272 "inspect".to_string(),
273 SubAgentAssignment::new("inspect".to_string(), None),
274 Some(vec![]),
275 options,
276 None,
277 )
278 .unwrap();
279 let profile = &guard.worker_records[&child.agent_id].spec.runtime_profile;
280 assert_eq!(profile.max_steps, 4);
281 assert!(profile.wall_time_secs.unwrap() <= 10);
282 // Continuation admission requires the same actor to settle before its saved deadline is checked.
283 let requested = guard.cancel_agent(&child.agent_id).unwrap();
284 drop(guard);
285 let settled = settle_requested_child(&manager, requested).await;
286 assert_eq!(settled.status, SubAgentStatus::Cancelled);
287 let mut guard = manager.write().await;
288 guard
289 .worker_records
290 .get_mut(&child.agent_id)
291 .unwrap()
292 .spec
293 .runtime_profile
294 .wall_deadline_ms = Some(1);
295 let refused = guard.spawn_background_with_assignment_options(
296 Arc::clone(&manager),
297 runtime,
298 FleetRole::Scout,
299 "continue".to_string(),
300 SubAgentAssignment::new("continue".to_string(), None),
301 Some(vec![]),
302 SubAgentSpawnOptions {
303 resume_from_agent_id: Some(child.agent_id),
304 ..Default::default()
305 },
306 None,
307 );
308 assert!(
309 refused
310 .unwrap_err()
311 .to_string()
312 .contains("cannot reset its deadline")
313 );
314 }
315
316 #[tokio::test]
317 async fn child_wall_time_is_unbounded_unless_an_owner_sets_it() {
318 let tmp = tempdir().unwrap();
319 let manager = Arc::new(RwLock::new(SubAgentManager::new(
320 tmp.path().to_path_buf(),
321 4,
322 )));
323 let mut runtime = stub_runtime().child_runtime();
324 runtime.context = ToolContext::new(tmp.path().to_path_buf());
325 runtime.manager = Arc::clone(&manager);
326 runtime.worker_profile.wall_time_secs = None;
327 runtime.cancel_token.cancel(); // inspect admission; no provider request may run
328 let spawn = |guard: &mut SubAgentManager, wall_time: Option<Duration>| {
329 let child = guard
330 .spawn_background_with_assignment_options(
331 Arc::clone(&manager),
332 runtime.clone(),
333 FleetRole::Scout,
334 "inspect".to_string(),
335 SubAgentAssignment::new("inspect".to_string(), None),
336 Some(vec![]),
337 SubAgentSpawnOptions {
338 wall_time,
339 ..Default::default()
340 },
341 None,
342 )
343 .unwrap();
344 guard.worker_records[&child.agent_id]
345 .spec
346 .runtime_profile
347 .clone()
348 };
349 let mut guard = manager.write().await;
350 let unbounded = spawn(&mut guard, None);
351 assert_eq!(unbounded.wall_time_secs, None);
352 assert_eq!(unbounded.wall_deadline_ms, None);
353 assert_eq!(
354 spawn(&mut guard, Some(Duration::from_secs(48 * 60 * 60))).wall_time_secs,
355 Some(48 * 60 * 60),
356 "an owner-selected limit is not shortened by a built-in ceiling"
357 );
358 drop(guard);
359 for owner_steps in [0, 7, 90] {
360 runtime.worker_profile.max_steps = owner_steps;
361 let args = json!({
362 "action": "start",
363 "type": "explore",
364 "prompt": "inspect",
365 "max_steps": 1,
366 "wall_time_secs": 1,
367 "max_output_tokens": 1,
368 "max_depth": 0
369 });
370 let mut closed_before_commit = 0;
371 let result = loop {
372 match AgentTool::new(Arc::clone(&manager), runtime.clone())
373 .execute(args.clone(), &runtime.context)
374 .await
375 {
376 Ok(result) => break result,
377 Err(error)
378 if closed_before_commit < 50
379 && error
380 .to_string()
381 .contains("prepared child execution owner closed") =>
382 {
383 closed_before_commit += 1;
384 }
385 Err(error) => panic!("legacy model caps cannot restrict the child: {error}"),
386 }
387 };
388 let receipt: Value = serde_json::from_str(&result.content).unwrap();
389 assert_eq!(receipt["effective_limits"]["max_steps"], owner_steps);
390 assert!(receipt["effective_limits"]["wall_deadline_ms"].is_null());
391 assert_eq!(receipt["ignored_limit_fields"].as_array().unwrap().len(), 4);
392 let guard = manager.read().await;
393 let record = &guard.worker_records[receipt["agent_id"].as_str().unwrap()];
394 assert_eq!(record.spec.max_spawn_depth, runtime.max_spawn_depth);
395 }
396 }
397
398 #[tokio::test]
399 async fn resume_intersects_saved_write_shell_and_tool_permissions_with_current_caller() {
400 let tmp = tempdir().unwrap();
401 let manager = Arc::new(RwLock::new(SubAgentManager::new(
402 tmp.path().to_path_buf(),
403 4,
404 )));
405 let mut runtime = stub_runtime().child_runtime();
406 runtime.context = ToolContext::new(tmp.path().to_path_buf());
407 runtime.manager = Arc::clone(&manager);
408 runtime.cancel_token.cancel();
409 runtime.worker_profile.permissions.write = false;
410 runtime.worker_profile.permissions.network = false;
411 runtime.worker_profile.shell = ShellPolicy::ReadOnly;
412 runtime.worker_profile.tools = ToolScope::Explicit(vec!["read_file".to_string()]);
413 runtime.worker_profile.denied_tools = vec!["exec_shell".to_string()];
414 let saved = WorkerRuntimeProfile::for_role(FleetRole::Worker);
415 let mut guard = manager.write().await;
416 let child = guard
417 .spawn_background_with_assignment_options(
418 Arc::clone(&manager),
419 runtime,
420 FleetRole::Worker,
421 "resume".to_string(),
422 SubAgentAssignment::new("resume".to_string(), None),
423 None,
424 SubAgentSpawnOptions {
425 preserve_runtime_profile: Some(saved),
426 ..Default::default()
427 },
428 None,
429 )
430 .unwrap();
431 let profile = &guard.worker_records[&child.agent_id].spec.runtime_profile;
432 assert!(!profile.permissions.write);
433 assert!(!profile.permissions.network);
434 assert_eq!(profile.shell, ShellPolicy::ReadOnly);
435 assert_eq!(
436 profile.tools,
437 ToolScope::Explicit(vec!["read_file".to_string()])
438 );
439 assert!(profile.denied_tools.contains(&"exec_shell".to_string()));
440 }
441
442 #[tokio::test]
443 async fn root_fork_of_depth_two_leaf_cannot_regain_a_generation() {
444 let tmp = tempdir().unwrap();
445 let manager = Arc::new(RwLock::new(SubAgentManager::new(
446 tmp.path().to_path_buf(),
447 4,
448 )));
449 let mut runtime = stub_runtime().with_max_spawn_depth(3).child_runtime();
450 runtime.context = ToolContext::new(tmp.path().to_path_buf());
451 runtime.manager = Arc::clone(&manager);
452 runtime.cancel_token.cancel();
453 let mut guard = manager.write().await;
454 let (canonical, directory) =
455 codewhale_util::workspace_dir::open_workspace_directory(tmp.path()).unwrap();
456 guard
457 .admit_coordination_workspace(tmp.path().to_path_buf(), canonical, Arc::new(directory))
458 .unwrap();
459 let source_id = guard.insert_test_running_direct_child("leaf", tmp.path());
460 guard.cancel_agent(&source_id).unwrap();
461 let mut source = make_worker_spec(&source_id, tmp.path().to_path_buf());
462 source.spawn_depth = 2;
463 source.max_spawn_depth = 2;
464 source.runtime_profile.spawn_depth = 2;
465 source.runtime_profile.max_spawn_depth = 2;
466 // Preserve the existing actor/origin/session receipt while installing the depth-2 profile.
467 guard.worker_records.get_mut(&source_id).unwrap().spec = source;
468 let child = guard
469 .spawn_background_with_assignment_options(
470 Arc::clone(&manager),
471 runtime,
472 FleetRole::Scout,
473 "fork leaf".to_string(),
474 SubAgentAssignment::new("fork leaf".to_string(), None),
475 Some(vec![]),
476 SubAgentSpawnOptions {
477 resume_from_agent_id: Some(source_id),
478 ..Default::default()
479 },
480 None,
481 )
482 .unwrap();
483 let spec = &guard.worker_records[&child.agent_id].spec;
484 assert_eq!(spec.spawn_depth, 2);
485 assert_eq!(spec.max_spawn_depth, 2);
486 assert_eq!(spec.runtime_profile.spawn_depth, 2);
487 assert!(!spec.runtime_profile.can_spawn_child());
488 }
489
490 // ── #6282 tool-result cap tests ───────────────────────────────────────────
491
492 fn cap_tokens(n: u32) -> std::num::NonZeroU32 {
493 std::num::NonZeroU32::new(n).expect("n > 0")
494 }
495
496 #[test]
497 fn hard_cap_passes_through_content_below_both_caps() {
498 let content = "small".to_string();
499 let capped = hard_cap_tool_result(content.clone(), cap_tokens(10_000));
500 assert_eq!(capped, content);
501 assert!(!capped.contains("truncated"));
502 }
503
504 #[test]
505 fn hard_cap_truncates_content_above_byte_cap_and_stamps_truncated_marker() {
506 let content = "X".repeat(1_048_577); // 1 byte over the 1 MiB cap
507 let capped = hard_cap_tool_result(content, cap_tokens(u32::MAX));
508 assert!(capped.len() <= 1_048_576 + "\n[truncated: true]".len());
509 assert!(capped.ends_with("\n[truncated: true]"));
510 assert!(capped.starts_with('X'));
511 }
512
513 #[test]
514 fn hard_cap_truncates_content_above_token_cap() {
515 // 10k tokens × 3 bytes/token = 30k byte cap. 100k chars should trigger it.
516 let content = "A".repeat(100_000);
517 let capped = hard_cap_tool_result(content, cap_tokens(10_000));
518 // The effective cap is min(30k bytes, 1 MiB) = 30k bytes.
519 let token_cap_bytes = 10_000usize.saturating_mul(3);
520 assert!(capped.len() <= token_cap_bytes + "\n[truncated: true]".len());
521 assert!(capped.ends_with("\n[truncated: true]"));
522 }
523
524 #[test]
525 fn hard_cap_truncates_at_valid_utf8_boundary() {
526 // Build content where 1 MiB boundary falls mid-char.
527 // '好' is 3 bytes in UTF-8.
528 let mut content = String::new();
529 let target = 1_048_576; // exactly at boundary
530 while content.len() < target + 2 {
531 content.push('好');
532 }
533 assert!(content.len() > target);
534 let capped = hard_cap_tool_result(content, cap_tokens(u32::MAX));
535 // Must be valid UTF-8 (no panic during slicing or display).
536 assert!(capped.ends_with("\n[truncated: true]"));
537 // The marker is ASCII; verify the rest is still valid UTF-8.
538 let without_marker = &capped[..capped.len() - "\n[truncated: true]".len()];
539 assert!(std::str::from_utf8(without_marker.as_bytes()).is_ok());
540 }
541
542 #[test]
543 fn hard_cap_respects_custom_max_output_tokens_nonzero() {
544 let content = "X".repeat(10_000);
545 // 100 tokens × 3 bytes = 300 byte cap — much tighter than default.
546 let capped = hard_cap_tool_result(content.clone(), cap_tokens(100));
547 assert!(capped.len() <= 300 + "\n[truncated: true]".len());
548 assert!(capped.ends_with("\n[truncated: true]"));
549 }
550
551 #[test]
552 fn hard_cap_min_token_value_produces_three_byte_cap() {
553 // NonZeroU32::MIN = 1 token → cap at 3 bytes.
554 let content = "hello world".to_string();
555 let capped = hard_cap_tool_result(content, std::num::NonZeroU32::MIN);
556 assert!(capped.len() <= 3 + "\n[truncated: true]".len());
557 assert!(capped.ends_with("\n[truncated: true]"));
558 }
559
559 lines RUST