trusty_code/session/registry_cancel.rs
1//! `SessionRegistry::await_cancelled` (#8207), split out of `registry.rs` for
2//! the 500-SLOC cap — a child module of `registry` (declared via
3//! `#[path = ...] mod cancel_confirm;`), so it keeps full access to
4//! `SessionRegistry`'s private `lock` helper and `Execution`'s private fields
5//! exactly as if the method were still defined there.
6//!
7//! Why: `registry.rs` sits within a few lines of its cap; the same reason
8//! `registry_task_result.rs` and `registry_events.rs` exist.
9//! What: [`SessionRegistry::await_cancelled`] — the half of `session.cancel`
10//! that turns a cancel REQUEST into a confirmed STOP.
11//! Test: `registry_cancel_tests::*`.
12
13use super::*;
14use crate::session::task_result::{TaskResult, TaskResultStatus};
15
16/// How often a cancel that found a PEER already confirming re-checks whether
17/// the run it is waiting on is gone (#8207).
18///
19/// Why: the peer owns the `JoinHandle`, so this caller has nothing to await
20/// directly; the observable it can poll is the execution slot itself. Ten
21/// milliseconds is far below any human-perceptible cancel latency and costs
22/// one uncontended mutex acquisition per tick.
23const PEER_POLL_INTERVAL: Duration = Duration::from_millis(10);
24
25/// What a `session.cancel` found when it went looking for the run it must
26/// confirm has stopped (#8207).
27///
28/// Why: `handle: None` meant two opposite things — "nobody has attached a
29/// handle yet" (unconfirmable, fail closed) and "a concurrent cancel is
30/// already joining it" (confirmable, just not by me). Collapsing them into one
31/// `Option` is what made a second Esc answer `-32603 internal`.
32enum CancelClaim {
33 /// This caller owns the handle and must join it itself.
34 Owned(Arc<AtomicBool>, JoinHandle<()>),
35 /// A concurrent cancel holds the handle; wait on the execution slot.
36 Peer(Arc<AtomicBool>),
37 /// Tracked, never joinable: the window between `begin_execution` and
38 /// `attach_execution_handle`.
39 Unjoinable,
40 /// Nothing is executing — already stopped.
41 Idle,
42}
43
44impl SessionRegistry {
45 /// Wait, bounded by `grace`, for `id`'s cancelled execution to ACTUALLY
46 /// stop (#8207).
47 ///
48 /// Why: [`Self::request_cancel`] only flips a cooperative flag, so a
49 /// caller that reported "cancelled" the moment it returned was reporting a
50 /// request, not an outcome — the daemon-side task kept running and the
51 /// next `task.run` on the same session was rejected with
52 /// `invalid_argument` ("already has a task running"). "Reported cancelled"
53 /// and "actually stopped" have to be the same fact, so `session.cancel`
54 /// blocks here until the spawned run's `JoinHandle` resolves. The run
55 /// clears its own slot as its last act (`task::executor::run_and_record`
56 /// calls `finish_execution`), so a resolved handle IS the guarantee that a
57 /// following `begin_execution` will be accepted.
58 /// What: claims the run via [`Self::claim_cancel_confirm`] and then, per
59 /// claim: joins the handle it owns ([`Self::join_owned`]), waits for the
60 /// peer that owns it ([`Self::await_peer_confirm`]), returns `Ok(())` for
61 /// an idle session (nothing left to wait for), or fails closed for an
62 /// execution that is tracked with no handle at all. Never downgrades a
63 /// failure to success: every unconfirmed outcome is
64 /// `RpcError::cancel_unconfirmed`, so the caller can say "still
65 /// cancelling" rather than lie. `Err(session_not_found)` for an unknown
66 /// `id`.
67 /// Test: `registry_cancel_tests::await_cancelled_returns_once_the_task_has_stopped`,
68 /// `registry_cancel_tests::await_cancelled_errors_when_the_task_outlives_the_grace`,
69 /// `registry_cancel_tests::await_cancelled_is_ok_when_nothing_is_executing`,
70 /// `registry_cancel_tests::await_cancelled_errors_when_the_execution_has_no_handle`,
71 /// `registry_cancel_tests::await_cancelled_unknown_session_errors`,
72 /// `registry_cancel_tests::a_panicked_run_lands_failed_and_releases_its_slot`,
73 /// `registry_cancel_tests::a_dead_handle_never_fails_a_newer_run`,
74 /// `registry_cancel_tests::the_grace_timeout_never_clobbers_a_newer_runs_handle`,
75 /// `registry_cancel_tests::two_concurrent_cancels_both_learn_the_run_stopped`.
76 pub async fn await_cancelled(&self, id: &str, grace: Duration) -> Result<(), RpcError> {
77 match self.claim_cancel_confirm(id)? {
78 CancelClaim::Idle => Ok(()),
79 CancelClaim::Unjoinable => Err(RpcError::cancel_unconfirmed(format!(
80 "session {id}: cancellation could not be confirmed — its run is \
81 tracked but not yet joinable"
82 ))),
83 CancelClaim::Owned(cancel, handle) => self.join_owned(id, &cancel, handle, grace).await,
84 CancelClaim::Peer(cancel) => self.await_peer_confirm(id, &cancel, grace).await,
85 }
86 }
87
88 /// Decide, under one lock, which half of the cancel-confirm protocol this
89 /// caller is running (#8207).
90 ///
91 /// Why: taking the handle and marking the execution "being confirmed" must
92 /// be one atomic step, or two concurrent cancels both see an untaken
93 /// handle or both see an untouched `None`.
94 /// What: takes the handle when there is one (latching `confirming`), and
95 /// otherwise reports whether a peer already took it. Returns the
96 /// execution's cancel flag alongside, as the identity token the restore
97 /// and peer-wait paths compare against.
98 /// Test: covered through [`Self::await_cancelled`]'s tests.
99 fn claim_cancel_confirm(&self, id: &str) -> Result<CancelClaim, RpcError> {
100 let mut sessions = self.lock();
101 let entry = sessions
102 .get_mut(id)
103 .ok_or_else(|| RpcError::session_not_found(id))?;
104 let Some(execution) = entry.execution.as_mut() else {
105 return Ok(CancelClaim::Idle);
106 };
107 let cancel = Arc::clone(&execution.cancel);
108 Ok(match execution.handle.take() {
109 Some(handle) => {
110 execution.confirming = true;
111 CancelClaim::Owned(cancel, handle)
112 }
113 None if execution.confirming => CancelClaim::Peer(cancel),
114 None => CancelClaim::Unjoinable,
115 })
116 }
117
118 /// Join the handle this caller took, bounded by `grace` (#8207).
119 ///
120 /// Why: three outcomes hide behind `timeout(..).await`, and the original
121 /// cut tested only whether the OUTER `Elapsed` fired — folding a
122 /// `JoinError` into "confirmed stop". A panicked run joins instantly, so
123 /// that arm answered `Ok` while `run_and_record` had never reached
124 /// `finish_execution`: the slot stayed held and every later prompt on that
125 /// session failed with `-32003`.
126 /// What: a clean join is `Ok(())`. A `JoinError` (panic or abort) is still
127 /// a stopped run, so the WAIT stays `Ok(())` — but the run itself failed,
128 /// and [`Self::land_dead_run`] is what makes that visible instead of
129 /// logging it. An elapsed `grace` restores the handle and fails closed.
130 /// Test: `registry_cancel_tests::a_panicked_run_lands_failed_and_releases_its_slot`,
131 /// `registry_cancel_tests::await_cancelled_errors_when_the_task_outlives_the_grace`.
132 async fn join_owned(
133 &self,
134 id: &str,
135 cancel: &Arc<AtomicBool>,
136 mut handle: JoinHandle<()>,
137 grace: Duration,
138 ) -> Result<(), RpcError> {
139 match tokio::time::timeout(grace, &mut handle).await {
140 Ok(Ok(())) => Ok(()),
141 Ok(Err(join_error)) => {
142 self.land_dead_run(id, cancel, &join_error);
143 Ok(())
144 }
145 Err(_elapsed) => {
146 self.restore_claimed_handle(id, cancel, handle);
147 Err(RpcError::cancel_unconfirmed(format!(
148 "session {id}: cancellation requested but the task did not stop \
149 within {}s",
150 grace.as_secs_f32()
151 )))
152 }
153 }
154 }
155
156 /// Wait for the concurrent cancel that owns the handle to finish
157 /// confirming (#8207).
158 ///
159 /// Why: a second Esc (or a second GUI click through
160 /// `trusty-code-gui`'s `POST /sessions/{id}/cancel`) must learn the truth
161 /// about the run, not `-32603 internal`. This caller cannot join a handle
162 /// it does not hold, so it polls the one observable that tells it the run
163 /// is over: the execution slot the run clears on its way out.
164 /// What: returns `Ok(())` as soon as the claimed execution is gone or has
165 /// been replaced by a newer one (identity by `Arc::ptr_eq` on the cancel
166 /// flag), and `cancel_unconfirmed` if `grace` elapses first — the same
167 /// fail-closed answer the owning caller gets for the same run.
168 /// Test: `registry_cancel_tests::two_concurrent_cancels_both_learn_the_run_stopped`,
169 /// `registry_cancel_tests::a_concurrent_cancel_that_never_confirms_fails_closed`.
170 async fn await_peer_confirm(
171 &self,
172 id: &str,
173 cancel: &Arc<AtomicBool>,
174 grace: Duration,
175 ) -> Result<(), RpcError> {
176 let deadline = tokio::time::Instant::now() + grace;
177 loop {
178 if !self.execution_is(id, cancel) {
179 return Ok(());
180 }
181 let now = tokio::time::Instant::now();
182 if now >= deadline {
183 return Err(RpcError::cancel_unconfirmed(format!(
184 "session {id}: another cancel is still confirming this run, \
185 which did not stop within {}s",
186 grace.as_secs_f32()
187 )));
188 }
189 tokio::time::sleep(PEER_POLL_INTERVAL.min(deadline - now)).await;
190 }
191 }
192
193 /// Whether `id`'s tracked execution is still the one identified by
194 /// `cancel` (#8207).
195 ///
196 /// Why: "the slot is occupied" is not the question — "the slot is occupied
197 /// by the run I am waiting on" is. A newer run holds a different cancel
198 /// `Arc`, and every waiter keeps a strong clone of the one it claimed, so
199 /// the old allocation cannot be freed and its address reused underneath
200 /// the comparison.
201 fn execution_is(&self, id: &str, cancel: &Arc<AtomicBool>) -> bool {
202 self.lock()
203 .get(id)
204 .and_then(|entry| entry.execution.as_ref())
205 .is_some_and(|execution| Arc::ptr_eq(&execution.cancel, cancel))
206 }
207
208 /// Land a run that died without unwinding: release its slot, record a
209 /// `Failed` result, and finish the session `Failed` (#8207).
210 ///
211 /// Why: a `JoinError` means the run PANICKED (or was aborted) — it never
212 /// reached `task::executor::run_and_record`'s own
213 /// `set_task_result`/`finish` pair, so without this the only trace is a log
214 /// line the client never sees. Landing `Cancelled` with no result was worse
215 /// than silent: `Cancelled` is resumable (`SessionStatus::is_resumable`), so
216 /// the next prompt resumed a crashed session as if the user had stopped it
217 /// on purpose. `Failed` is the status `finish_with_failure` already uses for
218 /// a run that broke, and it is not resumable, so the next prompt is refused
219 /// with a reason rather than silently continuing.
220 /// What: mirrors `executor::finish_with_failure`'s shape (failed
221 /// `TaskResult` carrying the reason, then `finish(Failed)`) but only when
222 /// [`Self::release_claimed_execution`] confirms the dead run still holds the
223 /// slot — a NEWER run that has already taken it owns both the slot and the
224 /// session's status, and must not be failed for its predecessor's crash.
225 /// Test: `registry_cancel_tests::a_panicked_run_lands_failed_and_releases_its_slot`,
226 /// `registry_cancel_tests::a_dead_handle_never_fails_a_newer_run`.
227 fn land_dead_run(
228 &self,
229 id: &str,
230 cancel: &Arc<AtomicBool>,
231 join_error: &tokio::task::JoinError,
232 ) {
233 tracing::error!(
234 session_id = %id,
235 error = %join_error,
236 "cancelled run did not exit cleanly"
237 );
238 if !self.release_claimed_execution(id, cancel) {
239 // A newer run owns the slot; its lifecycle is not this one's to end.
240 return;
241 }
242 let reason = format!("the run did not exit cleanly: {join_error}");
243 self.set_task_result(
244 id,
245 TaskResult::new(TaskResultStatus::Failed).with_summary(Some(reason)),
246 );
247 // The only error `finish` returns is `session_not_found`, which a
248 // session pruned mid-cancel reaches legitimately — there is nothing left
249 // to land, so log it rather than inventing a caller-facing failure out
250 // of a run that did in fact stop.
251 if let Err(err) = self.finish(id, SessionStatus::Failed) {
252 tracing::warn!(
253 session_id = %id,
254 error = %err.message,
255 "could not land Failed for a crashed run"
256 );
257 }
258 }
259
260 /// Clear the execution slot still held by a run that died without clearing
261 /// it (#8207).
262 ///
263 /// Why: `finish_execution` clears whatever is there; if a NEWER run has
264 /// already taken the slot, that would cancel-by-accident a run nobody
265 /// asked about.
266 /// What: clears the slot only when it still holds the claimed execution,
267 /// returning whether it did — the caller reads that as "the dead run is
268 /// still the session's current run", which is what makes the terminal
269 /// transition in [`Self::land_dead_run`] safe.
270 fn release_claimed_execution(&self, id: &str, cancel: &Arc<AtomicBool>) -> bool {
271 let mut sessions = self.lock();
272 if let Some(entry) = sessions.get_mut(id)
273 && entry
274 .execution
275 .as_ref()
276 .is_some_and(|execution| Arc::ptr_eq(&execution.cancel, cancel))
277 {
278 entry.execution = None;
279 return true;
280 }
281 false
282 }
283
284 /// Put a timed-out run's handle back, but only if the slot still holds
285 /// THAT run (#8207).
286 ///
287 /// Why: the handle has to go back or `shutdown_executions` would have
288 /// nothing left to await for this session — a dropped `JoinHandle`
289 /// detaches its task. But the restore used to be unconditional, and the
290 /// race it loses is real: the old run can clear its slot just before the
291 /// grace ends, a new `task.run` can be accepted and attach its own live
292 /// handle, and the restore then overwrites that live handle with the dead
293 /// one. The new run becomes invisible to `shutdown_executions`, and a
294 /// later cancel joins the dead handle and reports a stop while the new run
295 /// is still going.
296 /// What: restores under the same lock that checks identity, clearing
297 /// `confirming` with it. When the slot has moved on, the stale handle is
298 /// dropped instead — that run's slot was already released by the run
299 /// itself, so there is nothing left to await.
300 /// Test: `registry_cancel_tests::await_cancelled_errors_when_the_task_outlives_the_grace`,
301 /// `registry_cancel_tests::the_grace_timeout_never_clobbers_a_newer_runs_handle`.
302 fn restore_claimed_handle(&self, id: &str, cancel: &Arc<AtomicBool>, handle: JoinHandle<()>) {
303 let mut sessions = self.lock();
304 if let Some(entry) = sessions.get_mut(id)
305 && let Some(execution) = entry.execution.as_mut()
306 && Arc::ptr_eq(&execution.cancel, cancel)
307 {
308 execution.handle = Some(handle);
309 execution.confirming = false;
310 }
311 }
312}
313
314#[cfg(test)]
315#[path = "registry_cancel_tests.rs"]
316mod tests;