Skip to content

Commit a251eec

Browse files
committed
fix(background): abort adopted work when its owner is cancelled
1 parent ca7d1d0 commit a251eec

2 files changed

Lines changed: 56 additions & 1 deletion

File tree

‎crates/jcode-base/src/background.rs‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,17 @@ use model::{
3232
progress_event_record, progress_wait_reason, push_task_event, task_dir, terminal_event_record,
3333
};
3434

35+
/// Own an adopted task rather than detaching it when its wrapper is aborted.
36+
/// Construct before the first await, including before spawning the wrapper, so
37+
/// cancellation during registration or before its first poll is also safe.
38+
struct AbortAdoptedTask<T>(JoinHandle<T>);
39+
40+
impl<T> Drop for AbortAdoptedTask<T> {
41+
fn drop(&mut self) {
42+
self.0.abort();
43+
}
44+
}
45+
3546
/// Manages background task execution
3647
pub struct BackgroundTaskManager {
3748
tasks: Arc<RwLock<HashMap<String, RunningTask>>>,
@@ -648,6 +659,7 @@ impl BackgroundTaskManager {
648659
wake: bool,
649660
handle: JoinHandle<Result<jcode_tool_types::ToolOutput>>,
650661
) -> BackgroundTaskInfo {
662+
let mut handle = AbortAdoptedTask(handle);
651663
// Reserve before the foreground caller can release its turn/tool guard.
652664
let runtime_activity = crate::runtime_activity::global().enter().await;
653665
let (notify, wake) = normalize_delivery(notify, wake);
@@ -707,7 +719,7 @@ impl BackgroundTaskManager {
707719

708720
let wrapper_handle = tokio::spawn(async move {
709721
let _runtime_activity = runtime_activity;
710-
let tool_result = handle.await;
722+
let tool_result = (&mut handle.0).await;
711723
let duration_secs = started_at.elapsed().as_secs_f64();
712724

713725
let (status, exit_code, error, output_text) = match tool_result {

‎crates/jcode-base/src/background/tests.rs‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,49 @@ use anyhow::anyhow;
44
use tempfile::tempdir;
55
use tokio::time::{Duration, sleep};
66

7+
struct SignalDrop(Option<tokio::sync::oneshot::Sender<()>>);
8+
9+
impl Drop for SignalDrop {
10+
fn drop(&mut self) {
11+
if let Some(tx) = self.0.take() {
12+
let _ = tx.send(());
13+
}
14+
}
15+
}
16+
17+
async fn assert_adopted_owner_cancelled(reload: bool) -> Result<()> {
18+
let tmp = tempdir()?;
19+
let manager = BackgroundTaskManager::with_output_dir(tmp.path().to_path_buf());
20+
let (dropped_tx, dropped_rx) = tokio::sync::oneshot::channel();
21+
// Capture the guard before spawn so even an unpolled task owns its work.
22+
let owner = SignalDrop(Some(dropped_tx));
23+
let handle = tokio::spawn(async move {
24+
let _owner = owner;
25+
std::future::pending::<()>().await;
26+
Ok(jcode_tool_types::ToolOutput::new("unreachable"))
27+
});
28+
let info = manager.adopt("agentgrep", "cancel-owner", handle).await;
29+
if reload {
30+
assert_eq!(manager.abort_live_tasks_for_reload().await, 1);
31+
} else {
32+
assert!(manager.cancel(&info.task_id).await?);
33+
}
34+
tokio::time::timeout(Duration::from_secs(5), dropped_rx)
35+
.await
36+
.expect("aborting the background wrapper must drop the adopted owner")?;
37+
Ok(())
38+
}
39+
40+
#[tokio::test]
41+
async fn cancelling_adopted_task_drops_actual_owner() -> Result<()> {
42+
assert_adopted_owner_cancelled(false).await
43+
}
44+
45+
#[tokio::test]
46+
async fn reload_drops_adopted_task_owner() -> Result<()> {
47+
assert_adopted_owner_cancelled(true).await
48+
}
49+
750
#[tokio::test]
851
async fn adopted_task_output_exists_while_running_and_is_replaced_on_completion() -> Result<()> {
952
let tmp = tempdir()?;

0 commit comments

Comments
 (0)