Skip to main content

vortex_scan/execution/planning/driver/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! A single-worker driver for the protocol.
5//!
6//! A [`Run`] drives any number of root planners, each with its own IO session, and hands their
7//! batches to its caller as they are produced. Runnable items are prioritised in DFS preorder,
8//! with roots ordered by admission and children by emission. Each visit takes at most one CPU
9//! step. A parent's continuation follows its emitted child's entire subtree. Waiting work is
10//! skipped and regains its priority when IO makes it runnable. Published IO is registered
11//! immediately and state is inspected again before parking. Output follows emission order,
12//! not global row order. An earlier runnable branch can starve later branches.
13//!
14//! A run never blocks: [`Run::advance`] returns [`Progress::Waiting`] when every live item waits
15//! for IO, and the caller decides how to wait, by awaiting [`Run::poll_completion`] or by handing
16//! a completion it took from a source to [`Run::complete`]. [`Driver::run`] is the blocking
17//! convenience for one root.
18
19use std::collections::BTreeMap;
20use std::collections::VecDeque;
21use std::sync::Arc;
22use std::task::Context;
23use std::task::Poll;
24
25use vortex_array::ArrayRef;
26use vortex_error::VortexResult;
27use vortex_error::vortex_bail;
28use vortex_error::vortex_err;
29use vortex_io::request::Completion;
30use vortex_io::request::IoBatch;
31use vortex_io::request::IoConsumer;
32use vortex_io::request::IoIntent;
33use vortex_io::request::IoOwnerId;
34use vortex_io::request::IoRequestId;
35use vortex_io::request::IoResult;
36use vortex_io::request::IoSource;
37use vortex_io::request::IoTarget;
38use vortex_utils::aliases::hash_map::Entry;
39use vortex_utils::aliases::hash_map::HashMap;
40
41use crate::planning::morsel::Morsel;
42use crate::planning::morsel::MorselOutput;
43use crate::planning::planner::Planner;
44use crate::planning::planner::PlannerOutput;
45use crate::planning::planner::State;
46use crate::planning::planner::WorkScope;
47
48/// Identifies one root admitted to a [`Run`]. Unique within the run, in admission order.
49#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
50pub struct RootId(pub u64);
51
52/// One array produced by a morsel, with the scope the morsel was created for.
53pub struct Batch {
54    /// The root the morsel descends from.
55    pub root: RootId,
56    /// Scope of the morsel that produced the array.
57    pub scope: WorkScope,
58    /// The non-empty array.
59    pub array: ArrayRef,
60}
61
62/// What a call to [`Run::advance`] left behind.
63pub enum Progress {
64    /// A morsel's batch. One morsel's batches arrive in the order it emitted them.
65    Batch(Batch),
66    /// Every item descended from the root has retired, and its IO session was cleared.
67    RootDone(RootId),
68    /// A planner declared this child independent. The run has not queued it: the owner runs it,
69    /// on this run as another root through [`Run::admit`] or on a run of its own elsewhere.
70    Spawn(WorkScope, Box<dyn Planner>),
71    /// Every live item waits for IO. Await [`Run::poll_completion`], or pass the next completion
72    /// to [`Run::complete`].
73    Waiting,
74    /// Nothing is live: every admitted root has finished.
75    Idle,
76}
77
78enum Item {
79    Planner(Box<dyn Planner>),
80    Morsel(Box<dyn Morsel>),
81}
82
83/// What one item's `compute()` produced.
84enum Output {
85    Planner(PlannerOutput),
86    Morsel(MorselOutput),
87}
88
89/// One live planner or morsel. Boxed in the run queue and the parked map, so scheduling moves a
90/// pointer.
91struct Work {
92    id: IoOwnerId,
93    root: RootId,
94    scope: WorkScope,
95    item: Item,
96    /// Stable child-ordinal path, beginning with the root's admission ordinal.
97    path: Vec<u64>,
98    /// The parent continuation sorts after all previously emitted child subtrees.
99    next_child: u64,
100    /// Published `Fetch` requests not yet delivered, with the target each must be answered with.
101    outstanding: HashMap<IoRequestId, IoTarget>,
102}
103
104impl Work {
105    fn priority(&self) -> Vec<u64> {
106        let mut priority = self.path.clone();
107        priority.push(self.next_child);
108        priority
109    }
110
111    // Child k takes the continuation's old key as its path. Its subtree then sorts before
112    // the parent's new continuation at k + 1, even if descendants are discovered after IO.
113    fn child_path(&mut self) -> Vec<u64> {
114        let path = self.priority();
115        self.next_child += 1;
116        path
117    }
118
119    fn state(&self) -> State {
120        match &self.item {
121            Item::Planner(planner) => planner.state(),
122            Item::Morsel(morsel) => morsel.state(),
123        }
124    }
125
126    fn consumer(&mut self) -> &mut dyn IoConsumer {
127        match &mut self.item {
128            Item::Planner(planner) => &mut **planner,
129            Item::Morsel(morsel) => &mut **morsel,
130        }
131    }
132
133    /// Checks `result` against the outstanding request it answers and hands it to the item.
134    fn deliver(&mut self, request: IoRequestId, result: IoResult) -> VortexResult<()> {
135        let Some(target) = self.outstanding.remove(&request) else {
136            vortex_bail!(
137                "completion for {request:?} of {:?}, which is not outstanding",
138                self.id
139            );
140        };
141        if !result.matches(&target) {
142            vortex_bail!("IO source answered {target:?} with {}", result.kind());
143        }
144        self.consumer().set_io_result(request, result);
145        Ok(())
146    }
147}
148
149/// Keeps scheduling order separate from lookup for deliveries to runnable work.
150#[derive(Default)]
151struct ReadyQueue {
152    priorities: BTreeMap<Vec<u64>, IoOwnerId>,
153    work: HashMap<IoOwnerId, Box<Work>>,
154}
155
156impl ReadyQueue {
157    fn insert(&mut self, work: Box<Work>) {
158        self.priorities.insert(work.priority(), work.id);
159        self.work.insert(work.id, work);
160    }
161
162    fn pop(&mut self) -> Option<Box<Work>> {
163        let (_, owner) = self.priorities.pop_first()?;
164        self.work.remove(&owner)
165    }
166
167    fn is_empty(&self) -> bool {
168        self.priorities.is_empty()
169    }
170
171    fn cancel(&mut self, root: RootId) {
172        self.work.retain(|_, work| work.root != root);
173        self.priorities
174            .retain(|_, owner| self.work.contains_key(owner));
175    }
176}
177
178/// Poll IO even when one high-priority branch keeps producing CPU work.
179const IO_POLL_INTERVAL: usize = 64;
180
181/// One admitted root: the session its descendants read through, and how many of them are live.
182struct Root {
183    io: Arc<dyn IoSource>,
184    live: usize,
185}
186
187/// A set of root planners advanced by its caller on one thread at a time.
188///
189/// Dropping a run clears the IO session of every root still live, even when it ends in an error.
190#[derive(Default)]
191pub struct Run {
192    roots: HashMap<RootId, Root>,
193    next_root: u64,
194    next_owner: u64,
195    queue: ReadyQueue,
196    parked: HashMap<IoOwnerId, Box<Work>>,
197    /// Batches and finished roots not yet returned by [`advance`](Self::advance).
198    events: VecDeque<Progress>,
199    /// Visits left before the sources are polled for completions again.
200    visits_until_poll: usize,
201    step_limit: Option<usize>,
202    steps: usize,
203}
204
205impl Drop for Run {
206    fn drop(&mut self) {
207        for root in self.roots.values() {
208            root.io.clear();
209        }
210    }
211}
212
213impl Run {
214    /// Creates a run with nothing admitted.
215    pub fn new() -> Self {
216        Self::default()
217    }
218
219    /// Fails with an error naming the limit if more than `steps` visits are needed. Tests use it
220    /// to catch loops.
221    pub fn with_step_limit(mut self, steps: usize) -> Self {
222        self.step_limit = Some(steps);
223        self
224    }
225
226    /// Admits `root` and everything it spawns, reading through `io`.
227    ///
228    /// The session belongs to the root: the run submits the requests of every descendant to it,
229    /// and clears it once they have all retired or the root is cancelled.
230    pub fn admit(
231        &mut self,
232        root: Box<dyn Planner>,
233        scope: WorkScope,
234        io: Arc<dyn IoSource>,
235    ) -> RootId {
236        let id = RootId(self.next_root);
237        self.next_root += 1;
238        self.roots.insert(id, Root { io, live: 0 });
239        self.spawn(id, scope, Item::Planner(root), vec![id.0]);
240        id
241    }
242
243    /// Drops every live item descended from `root` and clears its session. Batches the root
244    /// already produced are still returned, followed by no [`Progress::RootDone`].
245    pub fn cancel(&mut self, root: RootId) {
246        let Some(cancelled) = self.roots.remove(&root) else {
247            return;
248        };
249        self.queue.cancel(root);
250        self.parked.retain(|_, work| work.root != root);
251        cancelled.io.clear();
252    }
253
254    /// The number of admitted roots that have not finished.
255    pub fn live_roots(&self) -> usize {
256        self.roots.len()
257    }
258
259    /// Runs ready work, taking completions the sources already have, until there is something to
260    /// hand back or everything left waits for IO. Never blocks.
261    pub fn advance(&mut self) -> VortexResult<Progress> {
262        loop {
263            if let Some(event) = self.events.pop_front() {
264                return Ok(event);
265            }
266            if self.visits_until_poll == 0 || self.queue.is_empty() {
267                self.take_completions()?;
268                self.visits_until_poll = IO_POLL_INTERVAL;
269                if self.queue.is_empty() {
270                    return Ok(if self.parked.is_empty() {
271                        Progress::Idle
272                    } else {
273                        Progress::Waiting
274                    });
275                }
276            }
277            self.visits_until_poll -= 1;
278            let Some(work) = self.queue.pop() else {
279                continue;
280            };
281            self.steps += 1;
282            if let Some(limit) = self.step_limit
283                && self.steps > limit
284            {
285                vortex_bail!("driver exceeded its step limit of {limit}");
286            }
287            self.visit(work)?;
288        }
289    }
290
291    /// Delivers a completion taken from the session of one of the run's roots.
292    pub fn complete(&mut self, completion: Completion) -> VortexResult<()> {
293        let Completion {
294            owner,
295            request,
296            result,
297        } = completion;
298        let result = result?;
299        if let Entry::Occupied(mut parked) = self.parked.entry(owner) {
300            let work = parked.get_mut();
301            work.deliver(request, result)?;
302            // An item that still waits for other requests stays parked.
303            if work.state() != State::Waiting {
304                let work = parked.remove();
305                self.queue.insert(work);
306            } else if work.outstanding.is_empty() {
307                vortex_bail!(
308                    "work for scope {:?} waits with no outstanding fetch",
309                    work.scope
310                );
311            }
312            return Ok(());
313        }
314        // An item that published fetches and had CPU work left is still in the run queue.
315        let Some(work) = self.queue.work.get_mut(&owner) else {
316            vortex_bail!("completion for unknown work {owner:?}");
317        };
318        work.deliver(request, result)
319    }
320
321    /// Waits for a completion from any root's session, registering `cx` to be woken by the next
322    /// one, and delivers every completion that is ready.
323    ///
324    /// Call it after [`advance`](Self::advance) returned [`Progress::Waiting`].
325    pub fn poll_completion(&mut self, cx: &mut Context<'_>) -> Poll<VortexResult<()>> {
326        let sources: Vec<_> = self
327            .roots
328            .values()
329            .map(|root| Arc::clone(&root.io))
330            .collect();
331        if sources.is_empty() {
332            return Poll::Ready(Err(vortex_err!(
333                "the run is waiting for IO with no live root"
334            )));
335        }
336        let mut delivered = false;
337        for io in sources {
338            match io.poll_completion(cx) {
339                Poll::Ready(Ok(completion)) => {
340                    if let Err(error) = self.complete(completion) {
341                        return Poll::Ready(Err(error));
342                    }
343                    delivered = true;
344                }
345                Poll::Ready(Err(error)) => return Poll::Ready(Err(error)),
346                Poll::Pending => {}
347            }
348        }
349        if delivered {
350            Poll::Ready(Ok(()))
351        } else {
352            Poll::Pending
353        }
354    }
355
356    /// Delivers the completions every root's session has ready, without blocking.
357    fn take_completions(&mut self) -> VortexResult<()> {
358        if self.roots.len() == 1 {
359            // The common case, without collecting the sessions.
360            let Some(io) = self.roots.values().next().map(|root| Arc::clone(&root.io)) else {
361                return Ok(());
362            };
363            while let Some(completion) = io.poll()? {
364                self.complete(completion)?;
365            }
366            return Ok(());
367        }
368        let sources: Vec<_> = self
369            .roots
370            .values()
371            .map(|root| Arc::clone(&root.io))
372            .collect();
373        for io in sources {
374            while let Some(completion) = io.poll()? {
375                self.complete(completion)?;
376            }
377        }
378        Ok(())
379    }
380
381    fn spawn(&mut self, root: RootId, scope: WorkScope, item: Item, path: Vec<u64>) {
382        let id = IoOwnerId(self.next_owner);
383        self.next_owner += 1;
384        if let Some(root) = self.roots.get_mut(&root) {
385            root.live += 1;
386        }
387        let work = Box::new(Work {
388            id,
389            root,
390            scope,
391            item,
392            path,
393            next_child: 0,
394            outstanding: HashMap::default(),
395        });
396        self.queue.insert(work);
397    }
398
399    /// Retires a finished item, and its root once nothing descended from it is live.
400    fn retire(&mut self, work: &Work) {
401        let Entry::Occupied(mut root) = self.roots.entry(work.root) else {
402            return;
403        };
404        root.get().io.release(work.id);
405        root.get_mut().live -= 1;
406        if root.get().live == 0 {
407            root.remove().io.clear();
408            self.events.push_back(Progress::RootDone(work.root));
409        }
410    }
411
412    /// Parks an item that waits for IO, which is a protocol error with no fetch outstanding.
413    fn park(&mut self, work: Box<Work>) -> VortexResult<()> {
414        if work.outstanding.is_empty() {
415            vortex_bail!(
416                "work for scope {:?} waits with no outstanding fetch",
417                work.scope
418            );
419        }
420        self.parked.insert(work.id, work);
421        Ok(())
422    }
423
424    /// Requeues, parks, or retires an item according to the state it reports.
425    fn settle(&mut self, work: Box<Work>) -> VortexResult<()> {
426        match work.state() {
427            State::Done => self.retire(&work),
428            State::NeedsCompute => self.queue.insert(work),
429            State::Waiting => self.park(work)?,
430        }
431        Ok(())
432    }
433
434    /// Visits one item: computes once if it is ready, and settles it otherwise.
435    fn visit(&mut self, mut work: Box<Work>) -> VortexResult<()> {
436        let output = match &mut work.item {
437            Item::Planner(planner) => match planner.state() {
438                State::NeedsCompute => Output::Planner(planner.compute()?),
439                _ => return self.settle(work),
440            },
441            Item::Morsel(morsel) => match morsel.state() {
442                State::NeedsCompute => Output::Morsel(morsel.compute()?),
443                _ => return self.settle(work),
444            },
445        };
446        match output {
447            Output::Planner(PlannerOutput::Done) | Output::Morsel(MorselOutput::Done) => {
448                self.retire(&work);
449            }
450            Output::Planner(PlannerOutput::Continue) | Output::Morsel(MorselOutput::Continue) => {
451                self.queue.insert(work);
452            }
453            Output::Planner(PlannerOutput::NeedsIO(batch))
454            | Output::Morsel(MorselOutput::NeedsIO(batch)) => {
455                self.submit(&mut work, batch)?;
456                self.settle(work)?;
457            }
458            Output::Planner(PlannerOutput::Planner(scope, child)) => {
459                let path = work.child_path();
460                self.spawn(work.root, scope, Item::Planner(child), path);
461                self.queue.insert(work);
462            }
463            Output::Planner(PlannerOutput::Morsel(scope, morsel)) => {
464                let path = work.child_path();
465                self.spawn(work.root, scope, Item::Morsel(morsel), path);
466                self.queue.insert(work);
467            }
468            Output::Planner(PlannerOutput::Spawn(scope, child)) => {
469                self.events.push_back(Progress::Spawn(scope, child));
470                self.queue.insert(work);
471            }
472            Output::Morsel(MorselOutput::Batch(array)) => {
473                if array.is_empty() {
474                    vortex_bail!("morsel for scope {:?} returned an empty batch", work.scope);
475                }
476                self.events.push_back(Progress::Batch(Batch {
477                    root: work.root,
478                    scope: work.scope.clone(),
479                    array,
480                }));
481                self.queue.insert(work);
482            }
483        }
484        Ok(())
485    }
486
487    /// Registers the requests an item published with its root's session.
488    fn submit(&mut self, work: &mut Work, batch: IoBatch) -> VortexResult<()> {
489        if batch.is_empty() {
490            vortex_bail!("compute() published an empty batch");
491        }
492        for request in &batch {
493            if request.intent == IoIntent::Fetch
494                && work
495                    .outstanding
496                    .insert(request.request, request.target)
497                    .is_some()
498            {
499                vortex_bail!(
500                    "fetch {:?} of {:?} was published while it is outstanding",
501                    request.request,
502                    work.id
503                );
504            }
505        }
506        let Some(root) = self.roots.get(&work.root) else {
507            vortex_bail!("work {:?} outlived its root {:?}", work.id, work.root);
508        };
509        root.io.submit(work.id, batch)
510    }
511}
512
513/// Drives one root to completion on the calling thread, blocking while it waits for IO.
514pub struct Driver {
515    io: Arc<dyn IoSource>,
516    step_limit: Option<usize>,
517}
518
519impl Driver {
520    /// Creates a driver that submits every request to `io`.
521    pub fn new(io: Arc<dyn IoSource>) -> Self {
522        Self {
523            io,
524            step_limit: None,
525        }
526    }
527
528    /// Fails with an error naming the limit if more than `steps` visits are needed. Tests use it
529    /// to catch loops.
530    pub fn with_step_limit(self, steps: usize) -> Self {
531        Self {
532            step_limit: Some(steps),
533            ..self
534        }
535    }
536
537    /// Runs a single `root` to completion, returning batches in emission order.
538    ///
539    /// Returns an error if `root` spawns an independent root; use
540    /// [`ScanDriver`](crate::execution::driver::ScanDriver) or drive [`Run`] directly with a
541    /// separate [`IoSource`] per root instead.
542    pub fn run(&self, root: Box<dyn Planner>) -> VortexResult<Vec<Batch>> {
543        let mut run = Run::new();
544        run.step_limit = self.step_limit;
545        let scope = WorkScope {
546            file_ordinal: 0,
547            rows: 0..0,
548        };
549        run.admit(root, scope, Arc::clone(&self.io));
550        let mut batches = Vec::new();
551        loop {
552            match run.advance()? {
553                Progress::Batch(batch) => batches.push(batch),
554                Progress::Spawn(..) => vortex_bail!(
555                    "Driver only supports a single root; use ScanDriver or drive Run directly \
556                     with a separate IoSource per root"
557                ),
558                Progress::RootDone(_) | Progress::Idle => return Ok(batches),
559                Progress::Waiting => run.complete(self.io.wait()?)?,
560            }
561        }
562    }
563}
564
565#[cfg(test)]
566mod tests;