Skip to main content

vtcode_bash_runner/
process.rs

1//! Unified process handle types for PTY and pipe backends.
2//!
3//! This module provides abstractions for interacting with spawned processes
4//! regardless of whether they use a PTY or regular pipes.
5//!
6//! Inspired by [codex-rs] PTY process handle patterns (Apache-2.0).
7//! Copyright 2025 OpenAI. See the repository `THIRD-PARTY-NOTICES` file for
8//! full attribution.
9//!
10//! [codex-rs]: https://github.com/openai/codex
11
12use std::fmt;
13use std::io;
14use std::sync::Arc;
15use std::sync::Mutex as StdMutex;
16use std::sync::MutexGuard as StdMutexGuard;
17use std::sync::atomic::{AtomicBool, Ordering};
18
19use bytes::Bytes;
20use tokio::sync::{broadcast, mpsc, oneshot};
21use tokio::task::{AbortHandle, JoinHandle};
22
23const POST_EXIT_DRAIN_QUIET_MS: u64 = 50;
24const POST_EXIT_DRAIN_MAX_MS: u64 = 500;
25
26/// Trait for process termination strategies.
27///
28/// Different backends (PTY vs pipe) may need different termination approaches.
29pub trait ChildTerminator: Send + Sync {
30    /// Kill the child process.
31    fn kill(&mut self) -> io::Result<()>;
32}
33
34/// Keep-alive guard for PTY master/slave handles.
35///
36/// This is a marker trait for opaque OS handles (e.g. `portable-pty` pair
37/// halves) whose only contract is ownership: dropping the handle releases the
38/// underlying resource. It exists so `PtyHandles` can name its vtable instead
39/// of erasing to bare `dyn Send` (which carries an empty vtable and documents
40/// no intent).
41///
42/// Memory layout note: `Box<dyn PtyHandle>` is a wide pointer (data pointer +
43/// vtable pointer, 16 bytes on 64-bit). There is one vtable per concrete
44/// handle type, emitted as external static data and paired with the object at
45/// the construction site — Rust chooses dynamic dispatch at the call site, so
46/// storing the concrete handle type directly (instead of boxing) would use
47/// static dispatch. Boxing is justified here only because PTY backends are
48/// selected at runtime and their handle types are heterogeneous.
49///
50/// The blanket implementation covers every `Send` handle, so existing backends
51/// can wrap their concrete handle with `Box::new(handle) as Box<dyn PtyHandle>`
52/// without additional work.
53pub trait PtyHandle: Send {}
54
55impl<T: Send> PtyHandle for T {}
56
57/// Optional PTY-specific handles that must be preserved.
58///
59/// For PTY processes, the slave handle must be kept alive because the process
60/// will receive SIGHUP if it's closed.
61pub struct PtyHandles {
62    /// The slave PTY handle (kept alive to prevent SIGHUP).
63    pub _slave: Option<Box<dyn PtyHandle>>,
64    /// The master PTY handle.
65    pub _master: Box<dyn PtyHandle>,
66}
67
68impl fmt::Debug for PtyHandles {
69    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
70        f.debug_struct("PtyHandles").finish()
71    }
72}
73
74/// Coherent snapshot of the direct child's exit facts.
75///
76/// `has_exited`, `has_observed_exit` and `exit_code` describe a single event.
77/// When they lived in three independent atomics/mutexes, the writer published
78/// them in sequence, so a reader could observe `has_exited() == true` while
79/// `exit_code()` was still `None` — the same "two fields that must stay in
80/// sync" failure mode as a dangling pointer after a reallocation, just with
81/// atomics. Keeping all three behind one lock makes a torn state
82/// unrepresentable: every accessor reads one published snapshot.
83#[derive(Clone, Copy, Debug, Default)]
84pub(crate) struct ProcessExitState {
85    status_recorded: bool,
86    observed: bool,
87    code: Option<i32>,
88}
89
90impl ProcessExitState {
91    /// Publish all exit facts in one critical section. `observed` is false
92    /// when the OS wait itself failed; `code` is still recorded so callers can
93    /// distinguish "wait failed" from "still running" via `has_exited`.
94    pub(crate) fn publish(state: &StdMutex<Self>, observed: bool, code: i32) {
95        let mut guard = state.lock().unwrap_or_else(|e| e.into_inner());
96        guard.status_recorded = true;
97        guard.observed = observed;
98        guard.code = Some(code);
99        // The single writer repaired the state, so future readers need not
100        // keep taking the poison-recovery path.
101        state.clear_poison();
102    }
103}
104
105/// Handle for driving an interactive or non-interactive process.
106///
107/// This provides a unified interface for both PTY and pipe-based processes:
108/// - Write to stdin via `writer_sender()`
109/// - Read merged stdout/stderr via `output_receiver()`
110/// - Check exit status via `has_exited()` and `exit_code()`
111/// - Clean up via `terminate()`
112pub struct ProcessHandle {
113    writer_tx: mpsc::Sender<Vec<u8>>,
114    output_tx: broadcast::Sender<Bytes>,
115    killer: StdMutex<Option<Box<dyn ChildTerminator>>>,
116    reader_handle: StdMutex<Option<JoinHandle<()>>>,
117    reader_abort_handles: StdMutex<Vec<AbortHandle>>,
118    writer_handle: StdMutex<Option<JoinHandle<()>>>,
119    wait_handle: StdMutex<Option<JoinHandle<()>>>,
120    exit_state: Arc<StdMutex<ProcessExitState>>,
121    // PTY handles must be preserved to prevent the process from receiving Control+C
122    _pty_handles: StdMutex<Option<PtyHandles>>,
123}
124
125impl fmt::Debug for ProcessHandle {
126    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
127        f.debug_struct("ProcessHandle")
128            .field("has_exited", &self.has_exited())
129            .field("exit_code", &self.exit_code())
130            .finish()
131    }
132}
133
134impl ProcessHandle {
135    /// Create a new process handle with all required components.
136    #[allow(
137        clippy::too_many_arguments,
138        reason = "Intentional compatibility, platform, or test-only suppression."
139    )]
140    pub(crate) fn new(
141        writer_tx: mpsc::Sender<Vec<u8>>,
142        output_tx: broadcast::Sender<Bytes>,
143        initial_output_rx: broadcast::Receiver<Bytes>,
144        killer: Box<dyn ChildTerminator>,
145        reader_handle: JoinHandle<()>,
146        reader_abort_handles: Vec<AbortHandle>,
147        writer_handle: JoinHandle<()>,
148        wait_handle: JoinHandle<()>,
149        exit_state: Arc<StdMutex<ProcessExitState>>,
150        pty_handles: Option<PtyHandles>,
151    ) -> (Self, broadcast::Receiver<Bytes>) {
152        (
153            Self {
154                writer_tx,
155                output_tx,
156                killer: StdMutex::new(Some(killer)),
157                reader_handle: StdMutex::new(Some(reader_handle)),
158                reader_abort_handles: StdMutex::new(reader_abort_handles),
159                writer_handle: StdMutex::new(Some(writer_handle)),
160                wait_handle: StdMutex::new(Some(wait_handle)),
161                exit_state,
162                _pty_handles: StdMutex::new(pty_handles),
163            },
164            initial_output_rx,
165        )
166    }
167
168    /// One coherent read of the exit snapshot. Readers never mutate the state,
169    /// so a recovered poison is not cleared here — the writer repairs it on
170    /// its next `publish`.
171    fn exit_state(&self) -> StdMutexGuard<'_, ProcessExitState> {
172        self.exit_state.lock().unwrap_or_else(|e| e.into_inner())
173    }
174
175    /// Returns a channel sender for writing raw bytes to the child stdin.
176    ///
177    /// # Example
178    /// ```ignore
179    /// let writer = handle.writer_sender();
180    /// writer.send(b"input\n".to_vec()).await?;
181    /// ```
182    #[inline]
183    pub fn writer_sender(&self) -> mpsc::Sender<Vec<u8>> {
184        self.writer_tx.clone()
185    }
186
187    /// Returns a broadcast receiver that yields stdout/stderr chunks.
188    ///
189    /// Multiple receivers can be created; each receives all output from the
190    /// point of subscription.
191    #[inline]
192    pub fn output_receiver(&self) -> broadcast::Receiver<Bytes> {
193        self.output_tx.subscribe()
194    }
195
196    /// True when the wait task finished, including when waiting failed.
197    /// Use [`Self::has_observed_exit`] when successful wait evidence matters.
198    #[inline]
199    pub fn has_exited(&self) -> bool {
200        self.exit_state().status_recorded
201    }
202
203    /// Whether waiting for the direct child returned an exit status. Unlike
204    /// `has_exited`, this remains false if the operating-system wait failed.
205    #[inline]
206    pub fn has_observed_exit(&self) -> bool {
207        self.exit_state().observed
208    }
209
210    /// Returns the exit code if the process has exited.
211    #[inline]
212    pub fn exit_code(&self) -> Option<i32> {
213        self.exit_state().code
214    }
215
216    /// True once the stdout/stderr reader task has drained the child streams.
217    #[inline]
218    pub fn is_output_drained(&self) -> bool {
219        self.reader_handle
220            .lock()
221            .ok()
222            .and_then(|guard| guard.as_ref().map(JoinHandle::is_finished))
223            .unwrap_or(true)
224    }
225
226    /// Attempts to kill the child and abort helper tasks.
227    ///
228    /// This is idempotent and safe to call multiple times.
229    pub fn terminate(&self) {
230        self.terminate_internal();
231    }
232
233    /// Kill the child process group without aborting the readers or wait task.
234    ///
235    /// Session owners use this path when they still need to drain output and
236    /// reap the child after termination. Call [`Self::terminate`] when the
237    /// caller is abandoning the session and does not need that final drain.
238    pub fn terminate_process(&self) {
239        let _ = self.try_terminate_process();
240    }
241
242    /// Request termination without consuming the handle on failure, so a
243    /// caller that needs a confirmed shutdown can report or retry the error.
244    ///
245    /// # Errors
246    /// Returns the process-kill error or an error if the handle lock is poisoned.
247    pub fn try_terminate_process(&self) -> io::Result<()> {
248        let mut killer = self
249            .killer
250            .lock()
251            .map_err(|_error| io::Error::other("process termination lock poisoned"))?;
252        if let Some(terminator) = killer.as_mut() {
253            terminator.kill()?;
254            *killer = None;
255        }
256        Ok(())
257    }
258
259    /// Internal termination that aborts all tasks.
260    fn terminate_internal(&self) {
261        // Kill the child process
262        if let Ok(mut killer_opt) = self.killer.lock()
263            && let Some(mut killer) = killer_opt.take()
264        {
265            let _ = killer.kill();
266        }
267
268        self.abort_tasks();
269    }
270
271    /// Abort all background tasks associated with this process.
272    fn abort_tasks(&self) {
273        // Abort reader handle
274        if let Ok(mut h) = self.reader_handle.lock()
275            && let Some(handle) = h.take()
276        {
277            handle.abort();
278        }
279
280        // Abort individual reader abort handles
281        if let Ok(mut handles) = self.reader_abort_handles.lock() {
282            for handle in handles.drain(..) {
283                handle.abort();
284            }
285        }
286
287        // Abort writer handle
288        if let Ok(mut h) = self.writer_handle.lock()
289            && let Some(handle) = h.take()
290        {
291            handle.abort();
292        }
293
294        // Abort wait handle
295        if let Ok(mut h) = self.wait_handle.lock()
296            && let Some(handle) = h.take()
297        {
298            handle.abort();
299        }
300    }
301
302    /// Check if the process is still running.
303    #[inline]
304    pub fn is_running(&self) -> bool {
305        !self.has_exited() && !self.is_writer_closed()
306    }
307
308    /// Send bytes to the process stdin.
309    ///
310    /// Returns an error if the stdin channel is closed.
311    pub async fn write(&self, bytes: impl Into<Vec<u8>>) -> Result<(), mpsc::error::SendError<Vec<u8>>> {
312        self.writer_tx.send(bytes.into()).await
313    }
314
315    /// Check if the writer channel is closed.
316    #[inline]
317    pub fn is_writer_closed(&self) -> bool {
318        self.writer_tx.is_closed()
319    }
320}
321
322impl Drop for ProcessHandle {
323    fn drop(&mut self) {
324        // Synchronous kill + task aborts, reusing the same body as
325        // `terminate_internal`. Both operations are non-blocking (`kill`
326        // signals the process group; `abort` flags the tasks), so Drop never
327        // parks the caller. A previous revision bridged this through a
328        // dedicated thread + Tokio runtime (`async_drop`) for zero async
329        // work — the thread/runtime only added spawn latency per Drop and
330        // blocked the dropping thread, which serialized shutdown storms
331        // (many handles dropped at registry teardown) and could stall a Tokio
332        // worker during TUI exit.
333        self.terminate_internal();
334    }
335}
336
337/// Return value from spawn helpers (PTY or pipe).
338///
339/// Bundles the process handle with receivers for output and exit notification.
340#[derive(Debug)]
341pub struct SpawnedProcess {
342    /// Handle for interacting with the process.
343    pub session: ProcessHandle,
344    /// Operating-system process identifier for the direct child.
345    pub process_id: u32,
346    /// Receiver for stdout/stderr output chunks.
347    pub output_rx: broadcast::Receiver<Bytes>,
348    /// Bounded, lossless receiver for consumers that must spool complete
349    /// output. Unlike `output_rx`, this channel applies backpressure to the
350    /// child-process readers instead of dropping lagged chunks.
351    pub reliable_output_rx: mpsc::Receiver<Bytes>,
352    /// Whether the producer is connected to `reliable_output_rx`.
353    pub(crate) reliable_output_enabled: bool,
354    /// Receiver for exit code (receives once when process exits).
355    pub exit_rx: oneshot::Receiver<i32>,
356}
357
358impl SpawnedProcess {
359    /// Convenience method to wait for the process to exit and collect output.
360    ///
361    /// Returns (collected_output, exit_code).
362    pub async fn wait_with_output(self, timeout_ms: u64) -> (Vec<u8>, i32) {
363        if self.reliable_output_enabled {
364            collect_reliable_output_until_exit(self.reliable_output_rx, self.exit_rx, timeout_ms).await
365        } else {
366            collect_output_until_exit(self.output_rx, self.exit_rx, timeout_ms).await
367        }
368    }
369}
370
371/// Collect all output from the bounded process stream until exit or timeout.
372async fn collect_reliable_output_until_exit(
373    mut output_rx: mpsc::Receiver<Bytes>,
374    exit_rx: oneshot::Receiver<i32>,
375    timeout_ms: u64,
376) -> (Vec<u8>, i32) {
377    let mut collected = Vec::new();
378    let deadline = tokio::time::Instant::now() + tokio::time::Duration::from_millis(timeout_ms);
379    tokio::pin!(exit_rx);
380
381    loop {
382        tokio::select! {
383            chunk = output_rx.recv() => {
384                if let Some(chunk) = chunk {
385                    collected.extend_from_slice(&chunk);
386                } else {
387                    return (collected, exit_rx.await.unwrap_or(-1));
388                }
389            }
390            res = &mut exit_rx => {
391                let code = res.unwrap_or(-1);
392                // A descendant may inherit stdout/stderr after the direct
393                // child exits. Keep the lossless path bounded just like the
394                // compatibility broadcast path instead of waiting forever
395                // for an inherited pipe descriptor to close.
396                let quiet = tokio::time::Duration::from_millis(POST_EXIT_DRAIN_QUIET_MS);
397                let max_deadline = tokio::time::Instant::now()
398                    + tokio::time::Duration::from_millis(POST_EXIT_DRAIN_MAX_MS);
399                while tokio::time::Instant::now() < max_deadline {
400                    match tokio::time::timeout(quiet, output_rx.recv()).await {
401                        Ok(Some(chunk)) => collected.extend_from_slice(&chunk),
402                        Ok(None) | Err(_) => break,
403                    }
404                }
405                return (collected, code);
406            }
407            _ = tokio::time::sleep_until(deadline) => {
408                return (collected, -1);
409            }
410        }
411    }
412}
413
414/// Collect output from a process until it exits or times out.
415///
416/// This is useful for tests and simple use cases where you want all output.
417pub async fn collect_output_until_exit(
418    mut output_rx: broadcast::Receiver<Bytes>,
419    exit_rx: oneshot::Receiver<i32>,
420    timeout_ms: u64,
421) -> (Vec<u8>, i32) {
422    let mut collected = Vec::new();
423    let deadline = tokio::time::Instant::now() + tokio::time::Duration::from_millis(timeout_ms);
424    tokio::pin!(exit_rx);
425
426    loop {
427        tokio::select! {
428            res = output_rx.recv() => {
429                if let Ok(chunk) = res {
430                    collected.extend_from_slice(&chunk);
431                }
432            }
433            res = &mut exit_rx => {
434                let code = res.unwrap_or(-1);
435                // Drain remaining output briefly after exit
436                let quiet = tokio::time::Duration::from_millis(POST_EXIT_DRAIN_QUIET_MS);
437                let max_deadline = tokio::time::Instant::now()
438                    + tokio::time::Duration::from_millis(POST_EXIT_DRAIN_MAX_MS);
439
440                while tokio::time::Instant::now() < max_deadline {
441                    match tokio::time::timeout(quiet, output_rx.recv()).await {
442                        Ok(Ok(chunk)) => collected.extend_from_slice(&chunk),
443                        Ok(Err(broadcast::error::RecvError::Lagged(count))) => {
444                            vtcode_commons::diagnostics::stderr(format_args!("Warning: output stream lagged ({count} dropped)"));
445                            continue;
446                        }
447                        Ok(Err(broadcast::error::RecvError::Closed)) => break,
448                        Err(_) => break, // Timeout - quiet period reached
449                    }
450                }
451                return (collected, code);
452            }
453            _ = tokio::time::sleep_until(deadline) => {
454                return (collected, -1);
455            }
456        }
457    }
458}
459
460/// Backwards-compatible alias for ProcessHandle.
461pub type ExecCommandSession = ProcessHandle;
462
463/// Backwards-compatible alias for SpawnedProcess.
464pub type SpawnedPty = SpawnedProcess;
465
466#[cfg(test)]
467mod tests {
468    use super::*;
469
470    struct NoopTerminator;
471    impl ChildTerminator for NoopTerminator {
472        fn kill(&mut self) -> io::Result<()> {
473            Ok(())
474        }
475    }
476
477    fn fresh_exit_state() -> Arc<StdMutex<ProcessExitState>> {
478        Arc::new(StdMutex::new(ProcessExitState::default()))
479    }
480
481    #[tokio::test]
482    async fn test_process_handle_debug() {
483        // Just verify Debug impl doesn't panic
484        let (writer_tx, _) = mpsc::channel(1);
485        let (output_tx, initial_rx) = broadcast::channel(1);
486
487        let (handle, _) = ProcessHandle::new(
488            writer_tx,
489            output_tx,
490            initial_rx,
491            Box::new(NoopTerminator),
492            tokio::spawn(async {}),
493            vec![],
494            tokio::spawn(async {}),
495            tokio::spawn(async {}),
496            fresh_exit_state(),
497            None,
498        );
499
500        let debug_str = format!("{handle:?}");
501        assert!(debug_str.contains("ProcessHandle"));
502    }
503
504    #[tokio::test]
505    async fn exit_facts_are_one_coherent_snapshot() {
506        let exit_state = fresh_exit_state();
507
508        let (writer_tx, _) = mpsc::channel(1);
509        let (output_tx, initial_rx) = broadcast::channel(1);
510
511        let (handle, _) = ProcessHandle::new(
512            writer_tx,
513            output_tx,
514            initial_rx,
515            Box::new(NoopTerminator),
516            tokio::spawn(async {}),
517            vec![],
518            tokio::spawn(async {}),
519            tokio::spawn(async {}),
520            Arc::clone(&exit_state),
521            None,
522        );
523
524        assert!(!handle.has_exited());
525        assert!(!handle.has_observed_exit());
526        assert_eq!(handle.exit_code(), None);
527
528        // A failed OS wait still publishes a complete snapshot: "exited" with
529        // a code, but not "observed". The old three-field layout allowed a
530        // reader to see exited=true while the code was still None.
531        ProcessExitState::publish(&exit_state, false, -1);
532        assert!(handle.has_exited());
533        assert!(!handle.has_observed_exit(), "a completed wait is not necessarily a successful wait");
534        assert_eq!(handle.exit_code(), Some(-1));
535
536        ProcessExitState::publish(&exit_state, true, 7);
537        assert!(handle.has_exited());
538        assert!(handle.has_observed_exit());
539        assert_eq!(handle.exit_code(), Some(7));
540    }
541
542    #[tokio::test]
543    async fn poisoned_exit_state_recovers_and_publish_clears_poison() {
544        let exit_state = fresh_exit_state();
545        let poisoner = Arc::clone(&exit_state);
546        let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
547            let _guard = poisoner.lock().unwrap();
548            panic!("intentional poison of exit state");
549        }));
550        assert!(outcome.is_err());
551        assert!(exit_state.is_poisoned());
552
553        let (writer_tx, _) = mpsc::channel(1);
554        let (output_tx, initial_rx) = broadcast::channel(1);
555        let (handle, _) = ProcessHandle::new(
556            writer_tx,
557            output_tx,
558            initial_rx,
559            Box::new(NoopTerminator),
560            tokio::spawn(async {}),
561            vec![],
562            tokio::spawn(async {}),
563            tokio::spawn(async {}),
564            Arc::clone(&exit_state),
565            None,
566        );
567
568        // Readers recover a coherent snapshot instead of silently skipping.
569        assert!(!handle.has_exited());
570        assert_eq!(handle.exit_code(), None);
571
572        // The single writer repairs the state and clears poison.
573        ProcessExitState::publish(&exit_state, true, 5);
574        assert!(!exit_state.is_poisoned());
575        assert!(handle.has_exited());
576        assert!(handle.has_observed_exit());
577        assert_eq!(handle.exit_code(), Some(5));
578    }
579
580    struct RecordingTerminator(Arc<AtomicBool>);
581    impl ChildTerminator for RecordingTerminator {
582        fn kill(&mut self) -> io::Result<()> {
583            self.0.store(true, Ordering::SeqCst);
584            Ok(())
585        }
586    }
587
588    struct FailOnceTerminator(Arc<std::sync::atomic::AtomicUsize>);
589    impl ChildTerminator for FailOnceTerminator {
590        fn kill(&mut self) -> io::Result<()> {
591            if self.0.fetch_add(1, Ordering::SeqCst) == 0 {
592                Err(io::Error::other("simulated kill failure"))
593            } else {
594                Ok(())
595            }
596        }
597    }
598
599    #[tokio::test]
600    async fn failed_termination_retains_the_handle_for_retry() {
601        let attempts = Arc::new(std::sync::atomic::AtomicUsize::new(0));
602        let (writer_tx, _) = mpsc::channel(1);
603        let (output_tx, initial_rx) = broadcast::channel(1);
604        let (handle, _) = ProcessHandle::new(
605            writer_tx,
606            output_tx,
607            initial_rx,
608            Box::new(FailOnceTerminator(Arc::clone(&attempts))),
609            tokio::spawn(async {}),
610            vec![],
611            tokio::spawn(async {}),
612            tokio::spawn(async {}),
613            fresh_exit_state(),
614            None,
615        );
616        assert!(handle.try_terminate_process().is_err());
617        assert!(handle.try_terminate_process().is_ok());
618        assert!(handle.try_terminate_process().is_ok());
619        assert_eq!(attempts.load(Ordering::SeqCst), 2);
620    }
621
622    /// Drop must kill the child and abort helper tasks synchronously, without
623    /// spawning a bridging thread/runtime (regression: a previous revision
624    /// bridged Drop through `async_drop`, adding spawn latency and blocking
625    /// the dropping thread during shutdown storms).
626    #[tokio::test]
627    async fn drop_kills_child_synchronously_without_bridging_runtime() {
628        let killed = Arc::new(AtomicBool::new(false));
629        let (writer_tx, _) = mpsc::channel(1);
630        let (output_tx, initial_rx) = broadcast::channel(1);
631
632        // Tasks that never complete; Drop must abort them rather than wait.
633        let (handle, _) = ProcessHandle::new(
634            writer_tx,
635            output_tx,
636            initial_rx,
637            Box::new(RecordingTerminator(Arc::clone(&killed))),
638            tokio::spawn(std::future::pending()),
639            vec![],
640            tokio::spawn(std::future::pending()),
641            tokio::spawn(std::future::pending()),
642            fresh_exit_state(),
643            None,
644        );
645
646        let started = std::time::Instant::now();
647        drop(handle);
648        assert!(killed.load(Ordering::SeqCst), "Drop must kill the child");
649        assert!(started.elapsed() < std::time::Duration::from_millis(250), "Drop must not block on async cleanup");
650    }
651}