返回 CodeWhale
ownership_tests.rs
根目录 / crates / engine / src / task_manager / ownership_tests.rs
1 use super::*;
2 use std::io::Write;
3 use std::process::{Child, Command, Stdio};
4 use std::sync::atomic::{AtomicUsize, Ordering};
5
6 fn config(root: &Path, scope: &str) -> TaskManagerConfig {
7 TaskManagerConfig {
8 data_dir: root.to_path_buf(),
9 worker_count: 1,
10 default_workspace: root.join(scope),
11 default_model: format!("{scope}-model"),
12 default_mode: "plan".into(),
13 allow_shell: false,
14 trust_mode: false,
15 execution_limits: TaskExecutionLimits::default(),
16 human_waits_answerable: false,
17 }
18 }
19
20 struct RecordingExecutor {
21 root: PathBuf,
22 scope: String,
23 }
24
25 #[async_trait]
26 impl TaskExecutor for RecordingExecutor {
27 async fn execute(
28 &self,
29 task: ExecutionTask,
30 events: mpsc::Sender<TaskExecutionEvent>,
31 cancel: CancellationToken,
32 ) -> TaskExecutionResult {
33 let mut receipt = fs::OpenOptions::new()
34 .create(true)
35 .append(true)
36 .open(self.root.join(format!("{}.executions", self.scope)))
37 .unwrap();
38 writeln!(
39 receipt,
40 "{}",
41 serde_json::json!({
42 "id": task.id, "scope": self.scope, "model": task.model,
43 "provider": task.model_provider, "provider_id": task.model_provider_id,
44 "workspace": task.workspace, "prompt": task.prompt,
45 "allow_shell": task.allow_shell, "trust_mode": task.trust_mode,
46 })
47 )
48 .unwrap();
49 if task.prompt.ends_with("hold") {
50 cancel.cancelled().await;
51 fs::write(self.root.join(format!("{}.canceled", self.scope)), &task.id).unwrap();
52 }
53 events
54 .send(TaskExecutionEvent::MessageDelta {
55 content: format!("{} result", self.scope),
56 })
57 .await
58 .ok();
59 TaskExecutionResult {
60 status: TaskStatus::Completed,
61 result_text: Some(format!("{} completed", self.scope)),
62 error: None,
63 terminal_reason: TaskTerminalReason::Completed,
64 }
65 }
66 }
67
68 async fn manager(root: &Path, scope: &str) -> Result<SharedTaskManager> {
69 TaskManager::start_with_executor_in_scope(
70 config(root, scope),
71 Arc::new(RecordingExecutor {
72 root: root.to_path_buf(),
73 scope: scope.into(),
74 }),
75 scope,
76 )
77 .await
78 }
79
80 async fn wait_file(path: &Path) -> Result<Vec<u8>> {
81 tokio::time::timeout(Duration::from_secs(15), async {
82 loop {
83 match fs::read(path) {
84 Ok(bytes) if !bytes.is_empty() => return Ok(bytes),
85 Ok(_) => {}
86 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
87 Err(error) => return Err(error.into()),
88 }
89 sleep(Duration::from_millis(10)).await;
90 }
91 })
92 .await
93 .context("fixture receipt timeout")?
94 }
95
96 fn executions(root: &Path, scope: &str) -> Vec<Value> {
97 fs::read_to_string(root.join(format!("{scope}.executions")))
98 .unwrap_or_default()
99 .lines()
100 .map(|line| serde_json::from_str(line).unwrap())
101 .collect()
102 }
103
104 struct ChildOwner(Child);
105 impl Drop for ChildOwner {
106 fn drop(&mut self) {
107 let _ = self.0.kill();
108 let _ = self.0.wait();
109 }
110 }
111 fn child_owner(root: &Path) -> Result<ChildOwner> {
112 let log = fs::File::create(root.join("child.log"))?;
113 Ok(ChildOwner(
114 Command::new(std::env::current_exe()?)
115 .args([
116 "--exact",
117 "task_manager::ownership_tests::ownership_process_child",
118 "--ignored",
119 "--nocapture",
120 ])
121 .env("CW_TASK_OWNER_FIXTURE_ROOT", root)
122 .stdout(Stdio::from(log.try_clone()?))
123 .stderr(Stdio::from(log))
124 .spawn()?,
125 ))
126 }
127
128 #[tokio::test]
129 #[ignore = "subprocess entry; invoked by shared-store ownership fixtures"]
130 async fn ownership_process_child() -> Result<()> {
131 let root = PathBuf::from(std::env::var("CW_TASK_OWNER_FIXTURE_ROOT")?);
132 let owner = manager(&root, "A").await?;
133 let active = owner
134 .add_task(NewTaskRequest {
135 owner_session_id: Some("session-a".into()),
136 ..NewTaskRequest::from_prompt("A hold")
137 })
138 .await?;
139 wait_file(&root.join("A.executions")).await?;
140 let queued = owner
141 .add_task(NewTaskRequest {
142 owner_session_id: Some("session-a".into()),
143 ..NewTaskRequest::from_prompt("A queued")
144 })
145 .await?;
146 fs::write(
147 root.join("ready"),
148 serde_json::to_vec(&[active.id, queued.id])?,
149 )?;
150 wait_file(&root.join("stop")).await?;
151 owner.shutdown_and_wait().await?;
152 drop(owner);
153 Ok(())
154 }
155
156 #[tokio::test]
157 async fn second_process_preserves_live_owner_and_durable_cancel_reaches_that_owner() -> Result<()> {
158 let root = tempfile::tempdir()?;
159 let mut child = child_owner(root.path())?;
160 let ids: Vec<String> = serde_json::from_slice(&wait_file(&root.path().join("ready")).await?)?;
161 let active_path = root.path().join("tasks").join(format!("{}.json", ids[0]));
162 let before = fs::read(&active_path)?;
163 let other = manager(root.path(), "B").await?;
164 assert_eq!(other.get_task(&ids[0]).await?.status, TaskStatus::Running);
165 assert_eq!(
166 fs::read(&active_path)?,
167 before,
168 "opening a foreign scope cannot rewrite live work"
169 );
170 assert!(
171 other
172 .get_task_for_owner(&ids[0], "session-b")
173 .await
174 .is_err()
175 );
176 assert!(
177 other
178 .cancel_task_for_owner(&ids[0][..12], "session-b")
179 .await
180 .is_err()
181 );
182 assert!(
183 other
184 .list_tasks_for_owner(None, None, "session-b")
185 .await?
186 .is_empty()
187 );
188 let own = other
189 .add_task(NewTaskRequest::from_prompt("B quick"))
190 .await?;
191 let done = wait_for_terminal_state(&other, &own.id, Duration::from_secs(10)).await?;
192 assert_eq!(done.status, TaskStatus::Completed);
193 assert_eq!(executions(root.path(), "B").len(), 1);
194 assert_eq!(executions(root.path(), "B")[0]["model"], "B-model");
195 assert_eq!(
196 executions(root.path(), "A").len(),
197 1,
198 "B cannot claim A's queued request"
199 );
200 other.cancel_task(&ids[1]).await?;
201 other.cancel_task(&ids[0]).await?;
202 wait_file(&root.path().join("A.canceled")).await?;
203 let canceled = wait_for_terminal_state(&other, &ids[0], Duration::from_secs(10)).await?;
204 assert_eq!(canceled.status, TaskStatus::Canceled);
205 assert!(canceled.cancel_requested_seq > 0);
206 assert_eq!(other.get_task(&ids[1]).await?.status, TaskStatus::Canceled);
207 assert_eq!(executions(root.path(), "A").len(), 1);
208 fs::write(root.path().join("stop"), "stop")?;
209 assert!(child.0.wait()?.success());
210 other.shutdown_and_wait().await?;
211 Ok(())
212 }
213
214 #[tokio::test]
215 async fn killed_process_is_reconciled_once_and_only_its_scope_resumes_queued_work() -> Result<()> {
216 let root = tempfile::tempdir()?;
217 let mut child = child_owner(root.path())?;
218 let ids: Vec<String> = serde_json::from_slice(&wait_file(&root.path().join("ready")).await?)?;
219 let observer = manager(root.path(), "B").await?;
220 assert!(
221 manager(root.path(), "A").await.is_err(),
222 "live scope cannot have a second executor"
223 );
224 child.0.kill()?;
225 child.0.wait()?;
226 let restarted = manager(root.path(), "A").await?;
227 let interrupted = restarted.get_task(&ids[0]).await?;
228 assert_eq!(interrupted.status, TaskStatus::Failed);
229 assert!(
230 interrupted
231 .error
232 .as_deref()
233 .unwrap()
234 .contains("Interrupted by process restart")
235 );
236 let terminal = wait_for_terminal_state(&restarted, &ids[1], Duration::from_secs(10)).await?;
237 assert_eq!(terminal.status, TaskStatus::Completed);
238 let receipt = executions(root.path(), "A");
239 assert_eq!(receipt.len(), 2);
240 assert_eq!(
241 receipt.iter().filter(|r| r["id"] == ids[0]).count(),
242 1,
243 "accepted Running work cannot replay"
244 );
245 assert_eq!(receipt[1]["id"], ids[1]);
246 assert_eq!(receipt[1]["model"], "A-model");
247 assert!(executions(root.path(), "B").is_empty());
248 restarted.shutdown_and_wait().await?;
249 drop(restarted);
250 let again = manager(root.path(), "A").await?;
251 assert_eq!(
252 again.get_task(&ids[0]).await?.lifecycle_seq,
253 interrupted.lifecycle_seq
254 );
255 assert_eq!(executions(root.path(), "A").len(), 2);
256 again.shutdown_and_wait().await?;
257 observer.shutdown_and_wait().await?;
258 Ok(())
259 }
260
261 async fn stop_idle_workers(manager: &TaskManager) {
262 for worker in std::mem::take(&mut *manager.workers.lock().await) {
263 worker.join.abort();
264 let _ = worker.join.await;
265 }
266 }
267
268 struct CountExecutor(Arc<AtomicUsize>);
269 #[async_trait]
270 impl TaskExecutor for CountExecutor {
271 async fn execute(
272 &self,
273 _: ExecutionTask,
274 _: mpsc::Sender<TaskExecutionEvent>,
275 _: CancellationToken,
276 ) -> TaskExecutionResult {
277 self.0.fetch_add(1, Ordering::SeqCst);
278 TaskExecutionResult::from_reason(TaskTerminalReason::Completed, None)
279 }
280 }
281
282 #[tokio::test]
283 async fn cancellation_after_claim_before_first_poll_never_invokes_executor() -> Result<()> {
284 let root = tempfile::tempdir()?;
285 let calls = Arc::new(AtomicUsize::new(0));
286 let owner = TaskManager::start_with_executor_in_scope(
287 config(root.path(), "A"),
288 Arc::new(CountExecutor(calls.clone())),
289 "A",
290 )
291 .await?;
292 stop_idle_workers(&owner).await;
293 let task = owner
294 .add_task(NewTaskRequest::from_prompt("claim barrier"))
295 .await?;
296 let (id, request, cancel) = owner.claim_next_task().await?.context("claim")?;
297 let other = manager(root.path(), "B").await?;
298 other.cancel_task(&task.id).await?;
299 owner.run_task(id, request, cancel).await;
300 assert_eq!(calls.load(Ordering::SeqCst), 0);
301 assert_eq!(owner.get_task(&task.id).await?.status, TaskStatus::Canceled);
302 let healthy = owner
303 .add_task(NewTaskRequest::from_prompt("uncanceled control"))
304 .await?;
305 let (id, request, cancel) = owner.claim_next_task().await?.context("control claim")?;
306 owner.run_task(id, request, cancel).await;
307 assert_eq!(
308 calls.load(Ordering::SeqCst),
309 1,
310 "the same executor must run without cancellation"
311 );
312 assert_eq!(
313 owner.get_task(&healthy.id).await?.status,
314 TaskStatus::Completed
315 );
316 owner.shutdown_and_wait().await?;
317 other.shutdown_and_wait().await?;
318 Ok(())
319 }
320
321 #[tokio::test]
322 async fn pending_flush_and_finish_merge_fresh_metadata_and_monotonic_cancel() -> Result<()> {
323 let root = tempfile::tempdir()?;
324 let owner = manager(root.path(), "A").await?;
325 stop_idle_workers(&owner).await;
326 let task = owner
327 .add_task(NewTaskRequest::from_prompt("bounded deltas"))
328 .await?;
329 let (_, request, cancel) = owner.claim_next_task().await?.context("claim")?;
330 owner
331 .apply_execution_event(
332 &task.id,
333 TaskExecutionEvent::MessageDelta {
334 content: "accepted progress".into(),
335 },
336 )
337 .await?;
338 let other = manager(root.path(), "B").await?;
339 other
340 .record_tool_metadata(
341 &task.id,
342 &serde_json::json!({"task_updates": {"checklist": {
343 "items": [{"id": 1, "content": "merged checklist", "status": "done"}],
344 "completion_pct": 100,
345 "in_progress_id": null,
346 "updated_at": null
347 }}}),
348 )
349 .await?;
350 other.cancel_task(&task.id).await?;
351 let seq = other.get_task(&task.id).await?.cancel_requested_seq;
352 owner.flush_task(&task.id).await?;
353 owner
354 .finish_task(
355 &task.id,
356 TaskExecutionResult::from_reason(TaskTerminalReason::Completed, None),
357 cancel,
358 &request.mode_label,
359 )
360 .await?;
361 let final_task = other.get_task(&task.id).await?;
362 assert_eq!(final_task.status, TaskStatus::Canceled);
363 assert_eq!(final_task.cancel_requested_seq, seq);
364 assert_eq!(final_task.checklist.items.len(), 1);
365 assert_eq!(final_task.checklist.completion_pct, 100);
366 assert_eq!(
367 final_task
368 .timeline
369 .iter()
370 .filter(|event| event.summary == "accepted progress")
371 .count(),
372 1
373 );
374 owner.shutdown_and_wait().await?;
375 other.shutdown_and_wait().await?;
376 Ok(())
377 }
378
379 #[cfg(unix)]
380 struct ReadOnlyFixtureDir(PathBuf);
381 #[cfg(unix)]
382 impl ReadOnlyFixtureDir {
383 fn new(path: &Path) -> Result<Self> {
384 use std::os::unix::fs::PermissionsExt;
385 fs::set_permissions(path, fs::Permissions::from_mode(0o500))?;
386 Ok(Self(path.to_path_buf()))
387 }
388 }
389 #[cfg(unix)]
390 impl Drop for ReadOnlyFixtureDir {
391 fn drop(&mut self) {
392 use std::os::unix::fs::PermissionsExt;
393 let _ = fs::set_permissions(&self.0, fs::Permissions::from_mode(0o700));
394 }
395 }
396
397 #[cfg(unix)]
398 #[tokio::test]
399 async fn failed_running_persistence_leaves_queued_work_without_executor_poll() -> Result<()> {
400 let root = tempfile::tempdir()?;
401 let calls = Arc::new(AtomicUsize::new(0));
402 let owner = TaskManager::start_with_executor_in_scope(
403 config(root.path(), "A"),
404 Arc::new(CountExecutor(calls.clone())),
405 "A",
406 )
407 .await?;
408 stop_idle_workers(&owner).await;
409 let task = owner
410 .add_task(NewTaskRequest::from_prompt("claim write failure"))
411 .await?;
412 let blocked = ReadOnlyFixtureDir::new(&owner.tasks_dir)?;
413 assert!(owner.claim_next_task().await.is_err());
414 assert_eq!(calls.load(Ordering::SeqCst), 0);
415 assert_eq!(owner.get_task(&task.id).await?.status, TaskStatus::Queued);
416 drop(blocked);
417 let (id, request, cancel) = owner.claim_next_task().await?.context("retry claim")?;
418 owner.run_task(id, request, cancel).await;
419 assert_eq!(calls.load(Ordering::SeqCst), 1);
420 owner.shutdown_and_wait().await?;
421 Ok(())
422 }
423
424 #[cfg(unix)]
425 #[tokio::test]
426 async fn failed_event_persistence_is_bounded_and_retains_each_accepted_delta_once() -> Result<()> {
427 let root = tempfile::tempdir()?;
428 let owner = manager(root.path(), "A").await?;
429 stop_idle_workers(&owner).await;
430 let task = owner
431 .add_task(NewTaskRequest::from_prompt("bounded write failure"))
432 .await?;
433 let (_, request, cancel) = owner.claim_next_task().await?.context("claim")?;
434 let blocked = ReadOnlyFixtureDir::new(&owner.tasks_dir)?;
435 for seq in 0..TASK_EVENT_CHANNEL_CAPACITY {
436 owner
437 .apply_execution_event(
438 &task.id,
439 TaskExecutionEvent::RuntimeEvent {
440 seq: seq as u64,
441 event: "fixture".into(),
442 summary: seq.to_string(),
443 },
444 )
445 .await?;
446 }
447 let rejected = TaskExecutionEvent::RuntimeEvent {
448 seq: 999,
449 event: "fixture".into(),
450 summary: "after recovery".into(),
451 };
452 assert!(
453 owner
454 .apply_execution_event(&task.id, rejected.clone())
455 .await
456 .is_err()
457 );
458 assert_eq!(
459 owner.state.lock().await.pending_events[&task.id].len(),
460 TASK_EVENT_CHANNEL_CAPACITY
461 );
462 assert!(
463 cancel.is_cancelled(),
464 "failed persistence requests actual-owner cancellation"
465 );
466 drop(blocked);
467 owner.apply_execution_event(&task.id, rejected).await?;
468 owner.flush_task(&task.id).await?;
469 assert_eq!(
470 owner.get_task(&task.id).await?.runtime_event_count,
471 TASK_EVENT_CHANNEL_CAPACITY + 1
472 );
473 assert!(
474 !owner
475 .state
476 .lock()
477 .await
478 .pending_events
479 .contains_key(&task.id)
480 );
481 owner
482 .finish_task(
483 &task.id,
484 TaskExecutionResult::from_reason(TaskTerminalReason::Canceled, None),
485 cancel,
486 &request.mode_label,
487 )
488 .await?;
489 owner.shutdown_and_wait().await?;
490 Ok(())
491 }
492
493 #[tokio::test]
494 async fn legacy_queued_and_running_records_remain_visible_unverified_and_byte_identical()
495 -> Result<()> {
496 let root = tempfile::tempdir()?;
497 let owner = manager(root.path(), "A").await?;
498 stop_idle_workers(&owner).await;
499 let first = owner
500 .add_task(NewTaskRequest {
501 owner_session_id: Some("legacy-owner".into()),
502 ..NewTaskRequest::from_prompt("legacy running")
503 })
504 .await?;
505 owner.claim_next_task().await?.context("claim")?;
506 let second = owner
507 .add_task(NewTaskRequest::from_prompt("legacy queued"))
508 .await?;
509 let mut snapshots = Vec::new();
510 for id in [&first.id, &second.id] {
511 let path = owner.tasks_dir.join(format!("{id}.json"));
512 let mut legacy: Value = serde_json::from_slice(&fs::read(&path)?)?;
513 let object = legacy.as_object_mut().unwrap();
514 object.remove("execution_scope");
515 object.remove("execution_generation");
516 object.remove("cancel_requested_seq");
517 object.insert("schema_version".into(), Value::from(3));
518 let bytes = serde_json::to_vec(&legacy)?;
519 fs::write(&path, &bytes)?;
520 snapshots.push((path, bytes));
521 }
522 let other = manager(root.path(), "B").await?;
523 sleep(STORE_REFRESH_INTERVAL * 2).await;
524 let rows = other.list_tasks(None).await?;
525 assert_eq!(rows.len(), 2);
526 assert!(rows.iter().all(|row| !row.execution_binding_known));
527 for (path, bytes) in snapshots {
528 assert_eq!(fs::read(path)?, bytes);
529 }
530 assert_eq!(
531 other
532 .get_task_for_owner(&first.id, "legacy-owner")
533 .await?
534 .status,
535 TaskStatus::Running
536 );
537 assert!(executions(root.path(), "B").is_empty());
538 owner.shutdown_and_wait().await?;
539 other.shutdown_and_wait().await?;
540 Ok(())
541 }
542
543 #[tokio::test]
544 async fn unreadable_owner_before_first_poll_waits_for_storage_without_executing() -> Result<()> {
545 for already_canceled in [false, true] {
546 let root = tempfile::tempdir()?;
547 let calls = Arc::new(AtomicUsize::new(0));
548 let owner = TaskManager::start_with_executor_in_scope(
549 config(root.path(), "A"),
550 Arc::new(CountExecutor(calls.clone())),
551 "A",
552 )
553 .await?;
554 stop_idle_workers(&owner).await;
555 let task = owner
556 .add_task(NewTaskRequest::from_prompt("unavailable before poll"))
557 .await?;
558 let (id, request, cancel) = owner.claim_next_task().await?.context("claim")?;
559 if already_canceled {
560 cancel.cancel();
561 }
562 let path = owner.tasks_dir.join(format!("{}.json", task.id));
563 let stored = fs::read(&path)?;
564 fs::write(&path, b"{corrupt")?;
565 let running = tokio::spawn({
566 let owner = owner.clone();
567 async move { owner.run_task(id, request, cancel).await }
568 });
569 sleep(STORE_REFRESH_INTERVAL * 2).await;
570 assert_eq!(calls.load(Ordering::SeqCst), 0);
571 assert!(
572 !running.is_finished(),
573 "unpersisted terminal state is still pending recovery"
574 );
575 fs::write(&path, stored)?;
576 tokio::time::timeout(Duration::from_secs(5), running).await??;
577 assert_eq!(owner.get_task(&task.id).await?.status, TaskStatus::Canceled);
578 assert_eq!(calls.load(Ordering::SeqCst), 0);
579 owner.shutdown_and_wait().await?;
580 }
581 Ok(())
582 }
583
583 lines RUST