use super::*;
use crate::binding::ProjectBinding;
use std::sync::atomic::{AtomicBool, Ordering};
fn executing_session(registry: &SessionRegistry) -> (String, Arc<AtomicBool>) {
let session = registry.create("t".to_string(), None, ProjectBinding::None);
let flag = registry
.begin_execution(&session.id)
.expect("fresh session accepts an execution");
(session.id, flag)
}
#[tokio::test]
async fn await_cancelled_returns_once_the_task_has_stopped() {
let registry = Arc::new(SessionRegistry::new());
let (id, flag) = executing_session(®istry);
let stopped = Arc::new(AtomicBool::new(false));
let registry_for_task = Arc::clone(®istry);
let id_for_task = id.clone();
let stopped_for_task = Arc::clone(&stopped);
let handle = tokio::spawn(async move {
while !flag.load(Ordering::Relaxed) {
tokio::time::sleep(Duration::from_millis(5)).await;
}
tokio::time::sleep(Duration::from_millis(40)).await;
stopped_for_task.store(true, Ordering::Relaxed);
registry_for_task.finish_execution(&id_for_task);
});
registry.attach_execution_handle(&id, handle);
registry.request_cancel(&id).expect("session exists");
registry
.await_cancelled(&id, Duration::from_secs(5))
.await
.expect("the task stops well inside the grace");
assert!(
stopped.load(Ordering::Relaxed),
"await_cancelled returned before the task had stopped"
);
assert!(
!registry.is_executing(&id),
"the stopped run must have released its execution slot"
);
}
#[tokio::test]
async fn await_cancelled_errors_when_the_task_outlives_the_grace() {
let registry = Arc::new(SessionRegistry::new());
let (id, _flag) = executing_session(®istry);
let handle = tokio::spawn(async {
tokio::time::sleep(Duration::from_secs(30)).await;
});
registry.attach_execution_handle(&id, handle);
registry.request_cancel(&id).expect("session exists");
let err = registry
.await_cancelled(&id, Duration::from_millis(30))
.await
.expect_err("a task that did not stop must not report a stop");
assert_eq!(err.code, -32010, "unexpected error shape: {err:?}");
assert!(
registry.is_executing(&id),
"the still-running execution must stay tracked"
);
let again = registry
.await_cancelled(&id, Duration::from_millis(30))
.await
.expect_err("the run is still going");
assert!(
again.message.contains("did not stop within"),
"the handle must have been restored, so a second confirm joins it \
again rather than finding nothing to await; got {again:?}"
);
}
#[tokio::test]
async fn await_cancelled_is_ok_when_nothing_is_executing() {
let registry = SessionRegistry::new();
let session = registry.create("t".to_string(), None, ProjectBinding::None);
registry
.await_cancelled(&session.id, Duration::from_millis(10))
.await
.expect("an idle session is already stopped");
}
#[tokio::test]
async fn await_cancelled_errors_when_the_execution_has_no_handle() {
let registry = SessionRegistry::new();
let (id, _flag) = executing_session(®istry);
let err = registry
.await_cancelled(&id, Duration::from_millis(10))
.await
.expect_err("an unjoinable run must not report a stop");
assert_eq!(err.code, -32010, "unexpected error shape: {err:?}");
assert!(
err.message.contains("not yet joinable"),
"this arm must name the window it is in, not a peer cancel: {err:?}"
);
}
#[tokio::test]
async fn await_cancelled_unknown_session_errors() {
let registry = SessionRegistry::new();
let err = registry
.await_cancelled("nope", Duration::from_millis(10))
.await
.expect_err("unknown session");
assert_eq!(err.code, -32007);
}
fn spawn_flag_watching_run(registry: &Arc<SessionRegistry>, id: &str, flag: Arc<AtomicBool>) {
let registry_for_task = Arc::clone(registry);
let id_for_task = id.to_string();
let handle = tokio::spawn(async move {
while !flag.load(Ordering::Relaxed) {
tokio::time::sleep(Duration::from_millis(5)).await;
}
registry_for_task.finish_execution(&id_for_task);
});
registry.attach_execution_handle(id, handle);
}
#[tokio::test]
async fn a_panicked_run_lands_failed_and_releases_its_slot() {
let registry = Arc::new(SessionRegistry::new());
let (id, _flag) = executing_session(®istry);
let handle = tokio::spawn(async {
panic!("the run died mid-flight");
});
registry.attach_execution_handle(&id, handle);
registry.request_cancel(&id).expect("session exists");
registry
.await_cancelled(&id, Duration::from_secs(5))
.await
.expect("a panicked run is a stopped run");
assert!(
!registry.is_executing(&id),
"the dead task's execution slot must not stay held"
);
let snapshot = registry.status(&id).expect("session exists");
assert_eq!(
snapshot.status,
SessionStatus::Failed,
"a crashed run must not land in the same status a clean cancel does"
);
let result = snapshot
.result
.expect("a crashed run must record a result, not only a log line");
assert_eq!(
result.status,
crate::session::task_result::TaskResultStatus::Failed
);
assert!(
result
.summary
.as_deref()
.is_some_and(|s| s.contains("did not exit cleanly")),
"the result must say WHY the run ended: {result:?}"
);
assert_eq!(
registry.begin_execution(&id).unwrap_err().code,
-32003,
"a crashed session must not resume as if it had been cleanly cancelled"
);
}
#[tokio::test]
async fn a_dead_handle_never_fails_a_newer_run() {
let registry = Arc::new(SessionRegistry::new());
let (id, _old_flag) = executing_session(®istry);
let release = Arc::new(tokio::sync::Notify::new());
let old_handle = {
let registry = Arc::clone(®istry);
let id = id.clone();
let release = Arc::clone(&release);
tokio::spawn(async move {
release.notified().await;
registry.finish_execution(&id);
tokio::time::sleep(Duration::from_millis(200)).await;
panic!("the old run died after releasing its slot");
})
};
registry.attach_execution_handle(&id, old_handle);
registry.request_cancel(&id).expect("session exists");
let confirming = {
let registry = Arc::clone(®istry);
let id = id.clone();
tokio::spawn(async move { registry.await_cancelled(&id, Duration::from_secs(5)).await })
};
tokio::time::sleep(Duration::from_millis(20)).await;
release.notify_one();
tokio::time::sleep(Duration::from_millis(20)).await;
let new_flag = registry
.begin_execution(&id)
.expect("the old run released its slot");
spawn_flag_watching_run(®istry, &id, Arc::clone(&new_flag));
confirming
.await
.expect("the confirming task must not panic")
.expect("a panicked run is still a stopped run");
let snapshot = registry.status(&id).expect("session exists");
assert!(
!snapshot.status.is_terminal(),
"the newer run must not be ended by its predecessor's crash, got {:?}",
snapshot.status
);
assert!(
snapshot.result.is_none(),
"the newer run has not finished, so it owns no result yet: {:?}",
snapshot.result
);
assert!(
registry.is_executing(&id),
"the newer run must still be tracked"
);
registry.request_cancel(&id).expect("session exists");
registry
.await_cancelled(&id, Duration::from_secs(5))
.await
.expect("the newer run confirms on its own handle");
}
#[tokio::test]
async fn the_grace_timeout_never_clobbers_a_newer_runs_handle() {
let registry = Arc::new(SessionRegistry::new());
let (id, _old_flag) = executing_session(®istry);
let release = Arc::new(tokio::sync::Notify::new());
let old_handle = {
let registry = Arc::clone(®istry);
let id = id.clone();
let release = Arc::clone(&release);
tokio::spawn(async move {
release.notified().await;
registry.finish_execution(&id);
std::future::pending::<()>().await
})
};
registry.attach_execution_handle(&id, old_handle);
registry.request_cancel(&id).expect("session exists");
let confirming = {
let registry = Arc::clone(®istry);
let id = id.clone();
tokio::spawn(async move {
registry
.await_cancelled(&id, Duration::from_millis(200))
.await
})
};
tokio::time::sleep(Duration::from_millis(20)).await;
release.notify_one();
tokio::time::sleep(Duration::from_millis(20)).await;
let new_flag = registry
.begin_execution(&id)
.expect("the old run released its slot");
spawn_flag_watching_run(®istry, &id, Arc::clone(&new_flag));
confirming
.await
.expect("the confirming task must not panic")
.expect_err("the old run never stopped, so its cancel must fail closed");
registry.request_cancel(&id).expect("session exists");
registry
.await_cancelled(&id, Duration::from_secs(5))
.await
.expect("the newer run's own handle must still be the tracked one");
assert!(
!registry.is_executing(&id),
"the newer run must have released its slot"
);
}
#[tokio::test]
async fn two_concurrent_cancels_both_learn_the_run_stopped() {
let registry = Arc::new(SessionRegistry::new());
let (id, flag) = executing_session(®istry);
let handle = {
let registry = Arc::clone(®istry);
let id = id.clone();
let flag = Arc::clone(&flag);
tokio::spawn(async move {
while !flag.load(Ordering::Relaxed) {
tokio::time::sleep(Duration::from_millis(5)).await;
}
tokio::time::sleep(Duration::from_millis(40)).await;
registry.finish_execution(&id);
})
};
registry.attach_execution_handle(&id, handle);
registry.request_cancel(&id).expect("session exists");
let spawn_cancel = || {
let registry = Arc::clone(®istry);
let id = id.clone();
tokio::spawn(async move { registry.await_cancelled(&id, Duration::from_secs(5)).await })
};
let (first, second) = tokio::join!(spawn_cancel(), spawn_cancel());
assert!(
first.expect("no panic").is_ok(),
"the owning cancel must confirm the stop"
);
assert!(
second.expect("no panic").is_ok(),
"the concurrent cancel must learn the run stopped, not report a fault"
);
assert!(!registry.is_executing(&id), "the slot must be released");
}
#[tokio::test]
async fn a_concurrent_cancel_that_never_confirms_fails_closed() {
let registry = Arc::new(SessionRegistry::new());
let (id, _flag) = executing_session(®istry);
let handle = tokio::spawn(async { std::future::pending::<()>().await });
registry.attach_execution_handle(&id, handle);
registry.request_cancel(&id).expect("session exists");
let owner = {
let registry = Arc::clone(®istry);
let id = id.clone();
tokio::spawn(async move { registry.await_cancelled(&id, Duration::from_secs(5)).await })
};
tokio::time::sleep(Duration::from_millis(20)).await;
let err = registry
.await_cancelled(&id, Duration::from_millis(40))
.await
.expect_err("a run that never stopped must not report a stop");
assert_eq!(err.code, -32010, "unexpected error shape: {err:?}");
assert!(
err.message.contains("another cancel"),
"the message must name the state it is really in: {err:?}"
);
owner.abort();
}