Skip to main content

vortex_scan/execution/
driver.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Drives a prepared scan on the session's runtime.
5//!
6//! A planner says what it needs: compute, or reads. This driver decides where each runs. It
7//! composes the planners over a [`PreparedScan`], the pruning plans first when the scan has a
8//! filter and the chunks of the rows they keep after, and runs them on planning runs it owns:
9//! the root run stepped on `spawn_cpu` tasks as the stream is polled, each spawned chunk on a
10//! task of its own, up to the concurrency, or on the root run when driving chunks inline. Each
11//! root reads through its own IO session. Per-batch output mapping runs on the task that
12//! produced the batch, beside the scan's other chunks.
13
14use std::future;
15use std::sync::Arc;
16use std::task::Poll;
17
18use async_lock::Semaphore;
19use async_lock::SemaphoreGuardArc;
20use futures::SinkExt;
21use futures::StreamExt;
22use futures::TryStreamExt;
23use futures::channel::mpsc;
24use futures::future::Either;
25use futures::stream;
26use futures::stream::BoxStream;
27use vortex_array::ArrayRef;
28use vortex_error::VortexResult;
29use vortex_error::vortex_err;
30use vortex_io::request::IoService;
31use vortex_io::runtime::Handle;
32use vortex_mask::Mask;
33
34use crate::planning::driver::Progress;
35use crate::planning::driver::Run;
36use crate::planning::planner::Planner;
37use crate::planning::planner::WorkScope;
38use crate::prepare::ChunkPlanner;
39use crate::prepare::PreparedScan;
40use crate::prepare::PrunePlanner;
41use crate::prepare::ScanBuilder;
42
43/// Runs a scan on the session's runtime.
44pub struct ScanDriver {
45    handle: Handle,
46    concurrency: usize,
47    budget: Option<ChunkBudget>,
48    ordered: bool,
49}
50
51/// A bound on the chunks in flight that the scans of several drivers share, so a scan with more
52/// work left can use the slots the others leave idle.
53#[derive(Clone)]
54pub struct ChunkBudget {
55    chunks: usize,
56    slots: Arc<Semaphore>,
57}
58
59impl ChunkBudget {
60    /// A budget of `chunks` chunks in flight at once.
61    pub fn new(chunks: usize) -> Self {
62        Self {
63            chunks,
64            slots: Arc::new(Semaphore::new(chunks)),
65        }
66    }
67}
68
69impl ScanDriver {
70    /// A driver spawning on `handle`, with at most `concurrency` chunks in flight at once, whatever
71    /// the machine's core count. If `concurrency` is zero, chunks run inline on the root run,
72    /// which interleaves every chunk's reads. When `ordered`, the driver holds batches until the
73    /// scan is done and yields them in row order.
74    pub fn new(handle: Handle, concurrency: usize, ordered: bool) -> Self {
75        Self {
76            handle,
77            concurrency,
78            budget: None,
79            ordered,
80        }
81    }
82
83    /// A driver spawning on `handle` whose chunks take their slots from `budget`, shared with
84    /// every other driver holding it. Each driver can also always run one chunk of its own, so a
85    /// scan whose output is not being read cannot hold up the others.
86    pub fn with_budget(handle: Handle, budget: ChunkBudget, ordered: bool) -> Self {
87        Self {
88            handle,
89            concurrency: budget.chunks + 1,
90            budget: Some(budget),
91            ordered,
92        }
93    }
94
95    /// Prepares `builder` where compute runs, composes its planners, and streams their batches.
96    /// Preparation errors are the stream's first item.
97    pub fn run(
98        self,
99        builder: impl Into<ScanBuilder>,
100    ) -> BoxStream<'static, VortexResult<ArrayRef>> {
101        self.run_mapped(builder, Ok)
102    }
103
104    /// Prepares and runs a scan, applying `map_fn` to each batch on the worker producing it.
105    ///
106    /// Output adapters can perform per-batch work here so it runs alongside the scan's other
107    /// chunks instead of on the single task polling the output stream. Mapping errors are
108    /// yielded through that stream.
109    pub fn run_mapped<A: Send + 'static>(
110        self,
111        builder: impl Into<ScanBuilder>,
112        map_fn: impl Fn(ArrayRef) -> VortexResult<A> + Send + Sync + 'static,
113    ) -> BoxStream<'static, VortexResult<A>> {
114        let builder = builder.into();
115        let handle = self.handle.clone();
116        stream::once(async move {
117            handle
118                .spawn_cpu(move || {
119                    let scan = builder.prepare()?;
120                    VortexResult::Ok(self.run_prepared(scan, map_fn))
121                })
122                .await
123        })
124        .try_flatten()
125        .boxed()
126    }
127
128    /// Runs an already prepared scan, applying `map_fn` on the task that produced each batch.
129    /// Use this when preparation errors must be reported before returning the stream.
130    pub fn run_prepared<A: Send + 'static>(
131        self,
132        scan: PreparedScan,
133        map_fn: impl Fn(ArrayRef) -> VortexResult<A> + Send + Sync + 'static,
134    ) -> BoxStream<'static, VortexResult<A>> {
135        let scan = Arc::new(scan);
136        let map_fn: MapFn<A> = Arc::new(map_fn);
137        let in_flight = self.concurrency;
138        let inline = in_flight == 0;
139        let scope = WorkScope {
140            file_ordinal: 0,
141            rows: scan.rows().clone(),
142        };
143        let io = scan.io();
144        let root = compose(&scan);
145        let (chunk_handle, chunk_io, chunk_map) =
146            (self.handle.clone(), Arc::clone(&io), Arc::clone(&map_fn));
147        let slots = self
148            .budget
149            .map(|budget| (Arc::new(Semaphore::new(1)), budget.slots));
150        let batches = run_stream(self.handle, root, scope, io, map_fn, inline)
151            .map_ok(move |yielded| match yielded {
152                Yielded::Batch(start, batch) => {
153                    stream::once(future::ready(Ok((start, batch)))).boxed()
154                }
155                Yielded::Spawn(scope, chunk) => {
156                    let (handle, io, map_fn) = (
157                        chunk_handle.clone(),
158                        Arc::clone(&chunk_io),
159                        Arc::clone(&chunk_map),
160                    );
161                    let Some((own, shared)) = slots.clone() else {
162                        return chunk_stream(&handle, chunk, scope, io, map_fn);
163                    };
164                    stream::once(async move {
165                        let slot = acquire_slot(own, shared).await;
166                        chunk_stream(&handle, chunk, scope, io, map_fn).map(move |batch| {
167                            let _ = &slot;
168                            batch
169                        })
170                    })
171                    .flatten()
172                    .boxed()
173                }
174            })
175            .try_flatten_unordered(in_flight);
176        // The prepared scan holds the file's shared cache: keep it until the stream ends, so
177        // scans of the file that start meanwhile find it.
178        let batches = batches.chain(stream::poll_fn(move |_| {
179            let _ = &scan;
180            Poll::Ready(None)
181        }));
182        if !self.ordered {
183            return batches.map_ok(|(_, batch)| batch).boxed();
184        }
185        stream::once(async move {
186            let mut held: Vec<(u64, A)> = batches.try_collect().await?;
187            // Morsels finish in whatever order their reads arrive.
188            held.sort_by_key(|(start, _)| *start);
189            VortexResult::Ok(stream::iter(held.into_iter().map(|(_, batch)| Ok(batch))))
190        })
191        .try_flatten()
192        .boxed()
193    }
194}
195
196/// Waits for a slot to run a chunk in: the driver's own slot or one from the shared budget,
197/// whichever frees first. The chunk holds it until it ends.
198async fn acquire_slot(own: Arc<Semaphore>, shared: Arc<Semaphore>) -> SemaphoreGuardArc {
199    if let Some(slot) = own.try_acquire_arc().or_else(|| shared.try_acquire_arc()) {
200        return slot;
201    }
202    match futures::future::select(Box::pin(own.acquire_arc()), Box::pin(shared.acquire_arc())).await
203    {
204        Either::Left((slot, _)) | Either::Right((slot, _)) => slot,
205    }
206}
207
208/// The planners of a scan, composed: with a filter, its pruning plans first over the whole scan,
209/// continuing into the chunks of the rows they keep; without, the chunks directly.
210fn compose(scan: &Arc<PreparedScan>) -> Box<dyn Planner> {
211    let rows = scan.rows().clone();
212    let chunks = {
213        let scan = Arc::clone(scan);
214        let rows = rows.clone();
215        move |kept: Option<Mask>| -> Box<dyn Planner> {
216            let selection = scan.selection().clone();
217            Box::new(ChunkPlanner::new(scan, rows, selection, kept))
218        }
219    };
220    if scan.filter().is_some() {
221        Box::new(PrunePlanner::new(Arc::clone(scan), rows, Box::new(chunks)))
222    } else {
223        chunks(None)
224    }
225}
226
227/// A mapping applied to each batch on the task that produced it.
228type MapFn<A> = Arc<dyn Fn(ArrayRef) -> VortexResult<A> + Send + Sync>;
229
230/// What the root run's stream yields: a mapped batch with the row it starts at, or a chunk a
231/// planner of the run spawned.
232enum Yielded<A> {
233    Batch(u64, A),
234    Spawn(WorkScope, Box<dyn Planner>),
235}
236
237/// One CPU step of a run, taken on a `spawn_cpu` task with the run.
238enum Step<A> {
239    Batch(u64, A),
240    Spawn(WorkScope, Box<dyn Planner>),
241    RootDone,
242    Idle,
243    Waiting,
244}
245
246/// The state of the root run's stream.
247struct RunState<A> {
248    handle: Handle,
249    /// Taken while a CPU step runs on its task and put back with its result.
250    run: Option<Run>,
251    /// Each root owns a session that the run clears when the root retires.
252    io: Arc<dyn IoService>,
253    map_fn: MapFn<A>,
254    /// Whether a spawned chunk runs on this run, as another root, instead of being yielded.
255    inline: bool,
256}
257
258/// Runs `root` over `scope` on a planning run of its own, reading through `io`, each CPU step
259/// on a `spawn_cpu` task, and yields its mapped batches and, unless `inline`, the chunks it
260/// spawns.
261fn run_stream<A: Send + 'static>(
262    handle: Handle,
263    root: Box<dyn Planner>,
264    scope: WorkScope,
265    io: Arc<dyn IoService>,
266    map_fn: MapFn<A>,
267    inline: bool,
268) -> BoxStream<'static, VortexResult<Yielded<A>>> {
269    let mut run = Run::new();
270    run.admit(root, scope, io.session());
271    let state = RunState {
272        handle,
273        run: Some(run),
274        io,
275        map_fn,
276        inline,
277    };
278    stream::try_unfold(state, |mut state| async move {
279        loop {
280            let run = state
281                .run
282                .take()
283                .ok_or_else(|| vortex_err!("the scan's run is missing"))?;
284            let map_fn = Arc::clone(&state.map_fn);
285            let (run, step) = state
286                .handle
287                .spawn_cpu(move || {
288                    let mut run = run;
289                    let step = run.advance().and_then(|progress| {
290                        Ok(match progress {
291                            Progress::Batch(batch) => {
292                                Step::Batch(batch.scope.rows.start, map_fn(batch.array)?)
293                            }
294                            Progress::Spawn(scope, child) => Step::Spawn(scope, child),
295                            Progress::RootDone(_) => Step::RootDone,
296                            Progress::Idle => Step::Idle,
297                            Progress::Waiting => Step::Waiting,
298                        })
299                    });
300                    (run, step)
301                })
302                .await;
303            let run = state.run.insert(run);
304            match step? {
305                Step::Batch(start, batch) => {
306                    return Ok(Some((Yielded::Batch(start, batch), state)));
307                }
308                Step::Spawn(scope, child) if state.inline => {
309                    run.admit(child, scope, state.io.session());
310                }
311                Step::Spawn(scope, child) => {
312                    return Ok(Some((Yielded::Spawn(scope, child), state)));
313                }
314                Step::RootDone if run.live_roots() > 0 => {}
315                Step::RootDone | Step::Idle => return Ok(None),
316                Step::Waiting => future::poll_fn(|cx| run.poll_completion(cx)).await?,
317            }
318        }
319    })
320    .boxed()
321}
322
323/// Runs a spawned chunk's `root` over `scope` on a planning run of its own, on one task that
324/// drives the run to its end and awaits only its reads, and yields its mapped batches with the
325/// row each starts at. A planner the chunk spawns in turn runs as another root of the same run.
326fn chunk_stream<A: Send + 'static>(
327    handle: &Handle,
328    root: Box<dyn Planner>,
329    scope: WorkScope,
330    io: Arc<dyn IoService>,
331    map_fn: MapFn<A>,
332) -> BoxStream<'static, VortexResult<(u64, A)>> {
333    let (mut send, recv) = mpsc::channel(1);
334    let task = handle.spawn(async move {
335        let mut run = Run::new();
336        run.admit(root, scope, io.session());
337        loop {
338            match run.advance()? {
339                Progress::Batch(batch) => {
340                    let start = batch.scope.rows.start;
341                    let batch = map_fn(batch.array);
342                    let failed = batch.is_err();
343                    if send.send(batch.map(|batch| (start, batch))).await.is_err() || failed {
344                        return Ok(());
345                    }
346                }
347                Progress::Spawn(scope, child) => {
348                    run.admit(child, scope, io.session());
349                }
350                Progress::RootDone(_) if run.live_roots() > 0 => {}
351                Progress::RootDone(_) | Progress::Idle => return Ok(()),
352                Progress::Waiting => future::poll_fn(|cx| run.poll_completion(cx)).await?,
353            }
354        }
355    });
356    let errors = stream::once(task)
357        .filter_map(|result: VortexResult<()>| future::ready(result.err().map(Err)));
358    stream::select(recv, errors).boxed()
359}
360
361#[cfg(test)]
362mod tests;