From a4c5be8b55e2911b65ace44e0bf5ecb7b24a8824 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Mon, 23 Nov 2026 17:48:03 -0500 Subject: [PATCH] Skip the executor in block_on when the future is already ready Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-io/src/runtime/current.rs | 32 ++++++++++++++++++++++++++++++-- 1 file changed, 30 insertions(+), 2 deletions(-) diff --git a/vortex-io/src/runtime/current.rs b/vortex-io/src/runtime/current.rs index 203d7858359..adea7c77386 100644 --- a/vortex-io/src/runtime/current.rs +++ b/vortex-io/src/runtime/current.rs @@ -2,9 +2,11 @@ // SPDX-FileCopyrightText: Copyright the Vortex contributors use std::future::Future; +use std::pin::pin; use std::sync::Arc; use async_channel::TryRecvError; +use futures::FutureExt; use futures::SinkExt; use futures::Stream; use futures::StreamExt; @@ -136,7 +138,7 @@ impl BlockingRuntime for CurrentThreadRuntime { where Fut: Future, { - block_on(self.executor.run(fut)) + drive(&self.executor, fut) } fn block_on_stream<'a, S, R>(&self, stream: S) -> Self::BlockingIterator<'a, R> @@ -151,6 +153,22 @@ impl BlockingRuntime for CurrentThreadRuntime { } } +/// Drives `fut` to completion on the calling thread. +/// +/// The future is polled once before entering the executor and returned from directly if it is +/// ready. Each entry into [`smol::Executor::run`] registers the thread with the executor's shared +/// state, under a write lock that every thread entering the runtime contends on, and a caller that +/// blocks on many futures which are mostly ready already, such as one batch of a scan after +/// another, would otherwise pay that for each of them. A future that is not ready is polled again +/// inside the executor, which runs the runtime's tasks while the thread waits for it. +fn drive(executor: &SmolExecutor, fut: Fut) -> Fut::Output { + let mut fut = pin!(fut); + if let Some(output) = fut.as_mut().now_or_never() { + return output; + } + block_on(executor.run(fut)) +} + /// An iterator that wraps up a stream to drive it using the current thread execution. pub struct CurrentThreadIterator<'a, T> { executor: Arc, @@ -161,7 +179,7 @@ impl Iterator for CurrentThreadIterator<'_, T> { type Item = T; fn next(&mut self) -> Option { - block_on(self.executor.run(self.stream.next())) + drive(&self.executor, self.stream.next()) } } @@ -259,6 +277,16 @@ mod tests { use super::*; + #[test] + fn block_on_runs_tasks_for_a_future_that_is_not_ready() { + let runtime = CurrentThreadRuntime::new(); + assert_eq!(runtime.block_on(async { 7 }), 7); + // The spawned task has not run when the future is first polled, so it is ready only once + // block_on enters the executor, which runs the task. + let task = runtime.handle().spawn(async { 11 }); + assert_eq!(runtime.block_on(task), 11); + } + #[test] fn test_worker_thread() { let runtime = CurrentThreadRuntime::new();