vortex-io 0.95.0

Core async and blocking IO traits and implementations, used by IPC and file format
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright the Vortex contributors

use std::any::Any;
use std::panic::AssertUnwindSafe;
use std::pin::Pin;
use std::sync::Arc;
use std::sync::Weak;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use std::task::Context;
use std::task::Poll;
use std::task::ready;

use futures::FutureExt;
use futures::channel::oneshot;
use tracing::Instrument;
use vortex_error::vortex_panic;

use crate::runtime::AbortHandle;
use crate::runtime::AbortHandleRef;
use crate::runtime::Executor;
use crate::runtime::platform;

/// A handle to an active Vortex runtime.
///
/// Users should obtain a handle from one of the Vortex runtime's and use it to spawn new async
/// tasks, blocking I/O tasks, CPU-heavy tasks, or to open files for reading or writing.
///
/// Note that a [`Handle`] is a weak reference to the underlying runtime. If the associated
/// runtime has been dropped, then any requests to spawn new tasks will panic.
#[derive(Clone)]
pub struct Handle {
    runtime: Weak<dyn Executor>,
}

impl Handle {
    pub fn new(runtime: Weak<dyn Executor>) -> Self {
        Self { runtime }
    }

    fn runtime(&self) -> Arc<dyn Executor> {
        self.runtime.upgrade().unwrap_or_else(|| {
            vortex_panic!("Attempted to use a Handle after its runtime was dropped")
        })
    }

    /// Returns a handle to the current runtime, if such a reasonable choice exists.
    ///
    /// For example, if called from within a Tokio context this will return a
    /// `TokioRuntime` handle. On browser WebAssembly with the `wasm-bindgen` feature this returns
    /// the global `WasmRuntime` handle; without it there is no event loop to schedule onto, and
    /// callers must drive a `SingleThreadRuntime` and install its handle themselves.
    pub fn find() -> Option<Self> {
        #[cfg(feature = "tokio")]
        {
            use tokio::runtime::Handle as TokioHandle;

            use crate::runtime::tokio::TokioRuntime;
            if TokioHandle::try_current().is_ok() {
                return Some(TokioRuntime::current());
            }
        }

        platform::default_handle()
    }

    /// Spawn a new future onto the runtime.
    ///
    /// These futures are expected to not perform expensive CPU work and instead simply schedule
    /// either CPU tasks or I/O tasks. See [`Handle::spawn_cpu`] for spawning CPU-bound work.
    ///
    /// See [`Task`] for details on cancelling or detaching the spawned task.
    pub fn spawn<Fut, R>(&self, f: Fut) -> Task<R>
    where
        Fut: Future<Output = R> + Send + 'static,
        R: Send + 'static,
    {
        let (send, recv) = oneshot::channel();
        // Instrument with a dedicated, named span on its own target rather than
        // re-entering `Span::current()`. `Instrumented::poll` enters and exits the
        // span on every poll, so re-entering the caller's span makes its cost scale
        // with poll count. A distinct target lets subscribers opt these spans in or
        // out via filtering; when filtered out the span is disabled and enter/exit
        // are no-ops, which keeps frequently-polled spawned futures cheap.
        let span = tracing::trace_span!(target: "vortex_io::spawn", "spawn");
        let abort_handle = self.runtime().spawn(
            async move {
                // Catch a panic so it can be re-raised on the joining side (see `Task::poll`)
                // rather than being lost, matching `tokio::JoinError` / `smol::Task` semantics.
                let output = AssertUnwindSafe(f).catch_unwind().await;
                // Task::detach allows the receiver to be dropped, so we ignore send errors.
                drop(send.send(output));
            }
            .instrument(span)
            .boxed(),
        );
        Task {
            recv,
            abort_handle: Some(abort_handle),
        }
    }

    /// A helper function to avoid manually cloning the handle when spawning nested tasks.
    pub fn spawn_nested<F, Fut, R>(&self, f: F) -> Task<R>
    where
        F: FnOnce(Handle) -> Fut,
        Fut: Future<Output = R> + Send + 'static,
        R: Send + 'static,
    {
        self.spawn(f(Handle::new(Weak::clone(&self.runtime))))
    }

    /// Spawn a new I/O future onto the runtime.
    ///
    /// See [`Executor::spawn_io`] for more details about how this future is expected to run.
    // See [`Task`] for details on cancelling or detaching the spawned task.
    pub fn spawn_io<Fut, R>(&self, f: Fut) -> Task<R>
    where
        Fut: Future<Output = R> + Send + 'static,
        R: Send + 'static,
    {
        let (send, recv) = oneshot::channel();
        // See `spawn` above: a dedicated target rather than `Span::current()` so
        // subscribers can filter these spans in or out. I/O futures are polled
        // frequently, so disabling the span (the default for an unconfigured
        // target) avoids per-poll enter/exit cost.
        let span = tracing::trace_span!(target: "vortex_io::spawn_io", "spawn_io");
        let abort_handle = self.runtime().spawn_io(
            async move {
                // See `spawn`: catch a panic so it re-raises on the joining side.
                let output = AssertUnwindSafe(f).catch_unwind().await;
                // Task::detach allows the receiver to be dropped, so we ignore send errors.
                drop(send.send(output));
            }
            .instrument(span)
            .boxed(),
        );
        Task {
            recv,
            abort_handle: Some(abort_handle),
        }
    }

    /// Spawn a CPU-bound task for execution on the runtime.
    ///
    /// Note that many runtimes will interleave this work on the same async runtime. See the
    /// documentation for each runtime implementation for details.
    ///
    /// See [`Task`] for details on cancelling or detaching the spawned work, although note that
    /// once started, CPU work cannot be cancelled.
    pub fn spawn_cpu<F, R>(&self, f: F) -> Task<R>
    where
        // Unlike scheduling futures, the CPU task should have a static lifetime because it
        // doesn't need to access to handle to spawn more work.
        F: FnOnce() -> R + Send + 'static,
        R: Send + 'static,
    {
        let (send, recv) = oneshot::channel();
        let aborted = Arc::new(AtomicBool::new(false));
        let task_aborted = Arc::clone(&aborted);
        let span = tracing::Span::current();
        let abort_handle = self.runtime().spawn_cpu(Box::new(move || {
            let _guard = span.enter();
            // Skip queued work only if the task was explicitly aborted (dropped without detach).
            if !task_aborted.load(Ordering::Acquire) {
                // Catch a panic so it re-raises on the joining side (see `Task::poll`).
                let output = std::panic::catch_unwind(AssertUnwindSafe(f));
                // Task::detach allows the receiver to be dropped, so we ignore send errors.
                drop(send.send(output));
            }
        }));
        Task {
            recv,
            abort_handle: Some(Box::new(SyncTaskAbortHandle {
                aborted,
                inner: abort_handle,
            })),
        }
    }

    /// Spawn a blocking I/O task for execution on the runtime.
    pub fn spawn_blocking<F, R>(&self, f: F) -> Task<R>
    where
        F: FnOnce() -> R + Send + 'static,
        R: Send + 'static,
    {
        let (send, recv) = oneshot::channel();
        let aborted = Arc::new(AtomicBool::new(false));
        let task_aborted = Arc::clone(&aborted);
        let span = tracing::Span::current();
        let abort_handle = self.runtime().spawn_blocking_io(Box::new(move || {
            let _guard = span.enter();
            // Skip queued work only if the task was explicitly aborted (dropped without detach).
            if !task_aborted.load(Ordering::Acquire) {
                // Catch a panic so it re-raises on the joining side (see `Task::poll`).
                let output = std::panic::catch_unwind(AssertUnwindSafe(f));
                // Task::detach allows the receiver to be dropped, so we ignore send errors.
                drop(send.send(output));
            }
        }));
        Task {
            recv,
            abort_handle: Some(Box::new(SyncTaskAbortHandle {
                aborted,
                inner: abort_handle,
            })),
        }
    }
}

/// Abort handle for synchronous (`spawn_cpu` / `spawn_blocking`) tasks.
///
/// Sets an explicit pre-dispatch cancellation flag only on [`AbortHandle::abort`] (ordinary
/// [`Task`] drop), leaving detached tasks free to run even after their result receiver is dropped.
struct SyncTaskAbortHandle {
    aborted: Arc<AtomicBool>,
    inner: AbortHandleRef,
}

impl AbortHandle for SyncTaskAbortHandle {
    fn abort(self: Box<Self>) {
        self.aborted.store(true, Ordering::Release);
        self.inner.abort();
    }
}

/// The value carried from a spawned task back to its [`Task`] handle: either the task's output,
/// or the panic payload if the task panicked, so it can be re-raised on the joining side.
type TaskOutput<T> = Result<T, Box<dyn Any + Send>>;

/// The terminal outcome of joining a spawned [`Task`] with [`Task::poll_join`], without
/// re-raising a panic.
pub enum JoinOutcome<T> {
    /// The task ran to completion and produced this value.
    Completed(T),
    /// The task panicked. Carries the original panic payload, ready to be re-raised with
    /// [`std::panic::resume_unwind`].
    Panicked(Box<dyn Any + Send>),
    /// The runtime dropped the task's future before it completed, for example because the task
    /// was aborted or the runtime shut down. No value or panic payload is available.
    Aborted,
}

/// A handle to a spawned Task.
///
/// If this handle is dropped, the task is cancelled where possible. In order to allow the task to
/// continue running in the background, call [`Task::detach`].
#[must_use = "When a Task is dropped without being awaited, it is cancelled"]
pub struct Task<T> {
    recv: oneshot::Receiver<TaskOutput<T>>,
    abort_handle: Option<AbortHandleRef>,
}

impl<T> Task<T> {
    /// Detach the task, allowing it to continue running in the background after being dropped.
    /// This is only possible if the underlying runtime has a 'static lifetime.
    pub fn detach(mut self) {
        drop(self.abort_handle.take());
    }

    /// Poll the task to completion, reporting the terminal state as a [`JoinOutcome`] instead of
    /// re-raising a panic or panicking on abort.
    ///
    /// This lets a caller distinguish a task panic (which it may re-raise via
    /// [`std::panic::resume_unwind`]) from the runtime dropping the task before it completed — for
    /// example a runtime shutting down while work is in flight — which is benign. The [`Future`]
    /// implementation, by contrast, re-raises a panic and itself panics on abort.
    pub fn poll_join(&mut self, cx: &mut Context<'_>) -> Poll<JoinOutcome<T>> {
        match ready!(self.recv.poll_unpin(cx)) {
            Ok(Ok(output)) => Poll::Ready(JoinOutcome::Completed(output)),
            Ok(Err(panic)) => Poll::Ready(JoinOutcome::Panicked(panic)),
            // The result channel closed without delivering a value: the runtime dropped the task's
            // future before it completed (for example the task was aborted or the runtime shut
            // down).
            Err(_recv_err) => Poll::Ready(JoinOutcome::Aborted),
        }
    }
}

impl<T> Future for Task<T> {
    type Output = T;

    #[expect(clippy::panic)]
    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        match ready!(self.get_mut().poll_join(cx)) {
            JoinOutcome::Completed(output) => Poll::Ready(output),
            // The task panicked: re-raise the original panic on the joining side, preserving its
            // message and payload rather than collapsing it into a generic error.
            JoinOutcome::Panicked(panic) => std::panic::resume_unwind(panic),
            JoinOutcome::Aborted => {
                // The runtime dropped the task's future before it completed. If the caller aborted
                // this task by dropping it, they wouldn't be able to poll it anymore, so we
                // consider a closed channel a runtime programming error and panic.

                // NOTE(ngates): we don't use vortex_panic to avoid printing a useless backtrace.
                panic!("Runtime dropped task without completing it")
            }
        }
    }
}

impl<T> Drop for Task<T> {
    fn drop(&mut self) {
        // Optimistically abort the task if it's still running.
        if let Some(handle) = self.abort_handle.take() {
            handle.abort();
        }
    }
}

#[cfg(test)]
mod tests {
    use std::sync::atomic::AtomicUsize;
    use std::sync::atomic::Ordering;

    use futures::future::BoxFuture;
    use futures::task::noop_waker;
    use parking_lot::Mutex;

    use super::*;
    use crate::runtime::AbortHandle;

    struct GatedAbortHandle {
        abort_calls: Arc<AtomicUsize>,
    }

    impl AbortHandle for GatedAbortHandle {
        fn abort(self: Box<Self>) {
            self.abort_calls.fetch_add(1, Ordering::SeqCst);
        }
    }

    struct GatedExecutor {
        queue: Mutex<Vec<Box<dyn FnOnce() + Send + 'static>>>,
        abort_calls: Arc<AtomicUsize>,
    }

    impl GatedExecutor {
        fn new() -> Arc<Self> {
            Arc::new(Self {
                queue: Mutex::new(Vec::new()),
                abort_calls: Arc::new(AtomicUsize::new(0)),
            })
        }

        fn enqueue(&self, work: Box<dyn FnOnce() + Send + 'static>) -> AbortHandleRef {
            self.queue.lock().push(work);
            Box::new(GatedAbortHandle {
                abort_calls: Arc::clone(&self.abort_calls),
            })
        }

        fn drain(&self) {
            for job in std::mem::take(&mut *self.queue.lock()) {
                job();
            }
        }
    }

    impl Executor for GatedExecutor {
        fn spawn(&self, _fut: BoxFuture<'static, ()>) -> AbortHandleRef {
            panic!("async spawn not used in gated sync tests")
        }

        fn spawn_cpu(&self, cpu: Box<dyn FnOnce() + Send + 'static>) -> AbortHandleRef {
            self.enqueue(cpu)
        }

        fn spawn_blocking_io(&self, task: Box<dyn FnOnce() + Send + 'static>) -> AbortHandleRef {
            self.enqueue(task)
        }
    }

    #[test]
    fn detached_cpu_and_blocking_tasks_run_queued_work() {
        let executor = GatedExecutor::new();
        let dyn_exec: Arc<dyn Executor> = Arc::clone(&executor) as Arc<dyn Executor>;
        let handle = Handle::new(Arc::downgrade(&dyn_exec));

        let cpu_runs = Arc::new(AtomicUsize::new(0));
        let blocking_runs = Arc::new(AtomicUsize::new(0));

        let cpu_runs_clone = Arc::clone(&cpu_runs);
        let cpu_task = handle.spawn_cpu(move || {
            cpu_runs_clone.fetch_add(1, Ordering::SeqCst);
            1usize
        });

        let blocking_runs_clone = Arc::clone(&blocking_runs);
        let blocking_task = handle.spawn_blocking(move || {
            blocking_runs_clone.fetch_add(1, Ordering::SeqCst);
            2usize
        });

        cpu_task.detach();
        blocking_task.detach();

        executor.drain();

        assert_eq!(cpu_runs.load(Ordering::SeqCst), 1);
        assert_eq!(blocking_runs.load(Ordering::SeqCst), 1);
        assert_eq!(executor.abort_calls.load(Ordering::SeqCst), 0);
    }

    #[test]
    fn dropped_cpu_and_blocking_tasks_skip_queued_work() {
        let executor = GatedExecutor::new();
        let dyn_exec: Arc<dyn Executor> = Arc::clone(&executor) as Arc<dyn Executor>;
        let handle = Handle::new(Arc::downgrade(&dyn_exec));

        let cpu_runs = Arc::new(AtomicUsize::new(0));
        let blocking_runs = Arc::new(AtomicUsize::new(0));

        let cpu_runs_clone = Arc::clone(&cpu_runs);
        let cpu_task = handle.spawn_cpu(move || {
            cpu_runs_clone.fetch_add(1, Ordering::SeqCst);
        });

        let blocking_runs_clone = Arc::clone(&blocking_runs);
        let blocking_task = handle.spawn_blocking(move || {
            blocking_runs_clone.fetch_add(1, Ordering::SeqCst);
        });

        drop(cpu_task);
        drop(blocking_task);

        executor.drain();

        assert_eq!(cpu_runs.load(Ordering::SeqCst), 0);
        assert_eq!(blocking_runs.load(Ordering::SeqCst), 0);
        assert_eq!(executor.abort_calls.load(Ordering::SeqCst), 2);
    }

    // A task whose result channel closed without a value — the runtime dropped its future before
    // it sent a result — must report `Aborted`, so callers can treat a benign teardown as a
    // recoverable stop rather than a propagated panic.
    #[test]
    fn poll_join_reports_aborted_when_channel_closed_without_value() {
        let (send, recv) = oneshot::channel::<TaskOutput<()>>();
        // Simulate the runtime dropping the task's future before it sent a result.
        drop(send);

        let mut task = Task::<()> {
            recv,
            abort_handle: None,
        };

        let waker = noop_waker();
        let mut cx = Context::from_waker(&waker);
        assert!(matches!(
            task.poll_join(&mut cx),
            Poll::Ready(JoinOutcome::Aborted)
        ));
    }

    // A completed task reports its value through `poll_join` rather than re-raising or panicking.
    #[test]
    fn poll_join_reports_completed_value() {
        let (send, recv) = oneshot::channel::<TaskOutput<u32>>();
        // Ignore the send result: the payload type is not `Debug`, and the receiver is alive.
        drop(send.send(Ok(7)));

        let mut task = Task::<u32> {
            recv,
            abort_handle: None,
        };

        let waker = noop_waker();
        let mut cx = Context::from_waker(&waker);
        assert!(matches!(
            task.poll_join(&mut cx),
            Poll::Ready(JoinOutcome::Completed(7))
        ));
    }
}