Skip to main content

vortex_scan/execution/pipeline/
scan.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! The scan: its pipelines, the driver that runs one, the scheduler that picks which, and the
5//! splits whose stages it compiles.
6
7use std::collections::VecDeque;
8use std::fmt;
9use std::ops::Range;
10
11use rustc_hash::FxHashMap;
12use smallvec::SmallVec;
13use vortex_array::ArrayRef;
14use vortex_array::ExecutionCtx;
15use vortex_array::VortexSessionExecute;
16use vortex_array::buffer::BufferHandle;
17use vortex_array::optimizer::ArrayOptimizer;
18use vortex_error::VortexResult;
19use vortex_error::vortex_bail;
20use vortex_error::vortex_ensure;
21use vortex_error::vortex_err;
22use vortex_mask::Mask;
23use vortex_session::VortexSession;
24
25use super::DEFAULT_CAPACITY;
26use super::compile::Chain;
27use super::port::Arena;
28use super::port::PipelineId;
29use super::port::PortId;
30use super::port::Slab;
31use super::port::SourceEnd;
32use super::values::ValueCache;
33use crate::execution::operator::Cx;
34use crate::execution::operator::InletSet;
35use crate::execution::operator::Input;
36use crate::execution::operator::Operator;
37use crate::execution::operator::Source;
38use crate::execution::operator::SourceBlocked;
39use crate::execution::operator::SourceReady;
40use crate::execution::operator::Step;
41use crate::plan::PlanRef;
42use crate::source::SegmentId;
43
44#[cfg(debug_assertions)]
45mod validate;
46
47/// Identifies a read a scan asked its owner for.
48#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
49pub struct ReadId(u64);
50
51/// A segment the scan needs read.
52#[derive(Clone, Debug)]
53pub struct ReadRequest {
54    /// Identifies the read when its bytes are delivered.
55    pub id: ReadId,
56    /// The segment to read.
57    pub segment_id: SegmentId,
58}
59
60/// A row range of the plan's domain, and the rows of it to produce.
61#[derive(Clone, Debug)]
62pub struct Split {
63    /// The rows.
64    pub rows: Range<u64>,
65    /// Which of them to produce; as long as `rows`.
66    pub mask: Mask,
67}
68
69impl Split {
70    /// Every row of `rows`.
71    pub fn all(rows: Range<u64>) -> Self {
72        let len = usize::try_from(rows.end - rows.start).unwrap_or(usize::MAX);
73        Self {
74            mask: Mask::new_true(len),
75            rows,
76        }
77    }
78}
79
80/// What the owner of a [`Scan`] does next.
81#[derive(Debug)]
82pub enum Turn {
83    /// Read this segment and [`deliver`](Scan::deliver) its bytes.
84    Read(ReadRequest),
85    /// The next rows of split `split`, in row order within the split.
86    Output(usize, ArrayRef),
87    /// Nothing can run until a read is delivered.
88    Waiting,
89    /// Every split has produced all its rows.
90    Done,
91}
92
93/// Whether a pipeline can run, and if not, what it waits for.
94#[derive(Clone, Copy, Debug, PartialEq, Eq)]
95enum State {
96    Runnable,
97    /// What its source said it waits for.
98    Blocked(SourceBlocked),
99    /// Room in a full outlet, found by the driver before the source ran.
100    Outlet,
101}
102
103/// A source, its stages, and the ports they read and write.
104pub(crate) struct Pipeline {
105    source: Box<dyn Source>,
106    stages: Vec<Box<dyn Operator>>,
107    inlets: Vec<PortId>,
108    outlets: SmallVec<[PortId; 1]>,
109    /// The segments it asked for that have arrived, in order of arrival.
110    bytes: VecDeque<(SegmentId, BufferHandle)>,
111    /// Reads it asked for that have not arrived, so retiring it cancels them only when any
112    /// are left.
113    pending: usize,
114    /// Once its source has finished, the next stage to finish: stages are finished one at a
115    /// time, each when the outlets have room for what it flushes.
116    finishing: Option<usize>,
117    /// Stages with more output for their current input, resumed deepest first.
118    continuing: Vec<usize>,
119    /// The source can compute again without checking readiness.
120    source_more: bool,
121    touched: InletSet,
122    changed: InletSet,
123    state: State,
124    queued: bool,
125}
126
127/// What one run of a pipeline came to.
128enum Progress {
129    /// The source waits for this.
130    Blocked(SourceBlocked),
131    /// An outlet is full.
132    Outlet,
133    /// The pipeline has finished and closed its outlets.
134    Done,
135}
136
137/// Runs `pipe` until it blocks or finishes, collecting any reads its source requests.
138fn drive(
139    pipe: &mut Pipeline,
140    arena: &mut Arena,
141    session: &VortexSession,
142    exec: &mut ExecutionCtx,
143    reads: &mut SmallVec<[SegmentId; 1]>,
144) -> VortexResult<Progress> {
145    let Pipeline {
146        source,
147        stages,
148        inlets,
149        outlets,
150        bytes,
151        finishing,
152        continuing,
153        source_more,
154        touched,
155        changed,
156        ..
157    } = pipe;
158    let mut cx = Cx {
159        arena,
160        inlets,
161        bytes,
162        reads,
163        session,
164        exec,
165        touched,
166        changed,
167    };
168    loop {
169        // Closing needs no room, so a pipeline with nothing left to flush closes at once.
170        if *finishing == Some(stages.len()) && continuing.is_empty() {
171            for &outlet in outlets.iter() {
172                cx.arena.close(outlet);
173            }
174            return Ok(Progress::Done);
175        }
176        if !outlets.iter().all(|&outlet| cx.arena.has_room(outlet)) {
177            return Ok(Progress::Outlet);
178        }
179        if let Some(stage) = continuing.pop() {
180            let step = stages[stage].compute(Input::None, &mut cx)?;
181            push(stages, stage, step, continuing, outlets, &mut cx)?;
182            continue;
183        }
184        if let Some(stage) = *finishing {
185            *finishing = Some(stage + 1);
186            let step = stages[stage].compute(Input::End, &mut cx)?;
187            push(stages, stage, step, continuing, outlets, &mut cx)?;
188            continue;
189        }
190        if !*source_more {
191            let ready = source.ready(&mut cx)?;
192            cx.changed.clear();
193            vortex_ensure!(
194                cx.reads.is_empty() || ready == SourceReady::Blocked(SourceBlocked::Io),
195                "A source that queues reads must block on IO"
196            );
197            match ready {
198                SourceReady::Ready => {}
199                SourceReady::Blocked(blocked) => return Ok(Progress::Blocked(blocked)),
200            }
201        }
202        let step = source.compute(Input::None, &mut cx)?;
203        *source_more = matches!(&step, Step::More(_));
204        match step {
205            Step::More(batch) | Step::Final(batch) => {
206                push_batch(stages, 0, batch, continuing, outlets, &mut cx)?;
207            }
208            Step::End => *finishing = Some(0),
209        }
210    }
211}
212
213/// Records a stage's continuation before pushing its output through the remaining stages.
214fn push(
215    stages: &mut [Box<dyn Operator>],
216    stage: usize,
217    step: Step,
218    continuing: &mut Vec<usize>,
219    outlets: &[PortId],
220    cx: &mut Cx<'_>,
221) -> VortexResult<()> {
222    let batch = match step {
223        Step::End => return Ok(()),
224        Step::More(batch) => {
225            continuing.push(stage);
226            batch
227        }
228        Step::Final(batch) => batch,
229    };
230    push_batch(stages, stage + 1, batch, continuing, outlets, cx)
231}
232
233/// Pushes one batch, retaining continuations so outlet capacity bounds every output.
234fn push_batch(
235    stages: &mut [Box<dyn Operator>],
236    start: usize,
237    mut batch: ArrayRef,
238    continuing: &mut Vec<usize>,
239    outlets: &[PortId],
240    cx: &mut Cx<'_>,
241) -> VortexResult<()> {
242    for (index, stage) in stages.iter_mut().enumerate().skip(start) {
243        batch = match stage.compute(Input::Batch(batch), cx)? {
244            Step::More(batch) => {
245                continuing.push(index);
246                batch
247            }
248            Step::Final(batch) => batch,
249            Step::End => return Ok(()),
250        };
251    }
252    push_out(batch, outlets, cx.arena);
253    Ok(())
254}
255
256/// Writes `batch` into every outlet: one for a plain pipeline, one per claimant for a share.
257fn push_out(batch: ArrayRef, outlets: &[PortId], arena: &mut Arena) {
258    if let Some((&last, rest)) = outlets.split_last() {
259        for &outlet in rest {
260            arena.push(outlet, batch.clone());
261        }
262        arena.push(last, batch);
263    }
264}
265
266/// Everything a scan's pipelines share: the ports, the pipeline table, the scheduler, the reads
267/// in flight, and the shares.
268pub(crate) struct Core {
269    pub(crate) session: VortexSession,
270    pub(crate) exec: ExecutionCtx,
271    /// The global row index of plan row zero.
272    pub(crate) row_offset: u64,
273    pub(crate) arena: Arena,
274    pipelines: Slab<Option<Pipeline>>,
275    free_pipelines: Vec<PipelineId>,
276    /// Runnable pipelines, last in first out, so data a pipeline just produced is consumed
277    /// before more is produced.
278    ready: Vec<PipelineId>,
279    /// Reads in flight: the pipeline that asked, or `None` once that pipeline has finished and
280    /// the read is cancelled, and the segment.
281    reads: FxHashMap<ReadId, (Option<PipelineId>, SegmentId)>,
282    next_read: u64,
283    new_reads: VecDeque<ReadRequest>,
284    /// Split slots whose stage output has something new, with a flag per slot so a slot is
285    /// queued once.
286    dirty: Vec<usize>,
287    dirty_flags: Vec<bool>,
288    /// The segment of every scan source compiled so far, in compile order.
289    pub(crate) segments: Vec<SegmentId>,
290    /// Whole values kept for later scans of the same split.
291    pub(crate) values: ValueCache,
292}
293
294impl Core {
295    fn new(session: VortexSession, row_offset: u64) -> Self {
296        Self {
297            exec: session.create_execution_ctx(),
298            session,
299            row_offset,
300            arena: Arena::default(),
301            pipelines: Slab::default(),
302            free_pipelines: Vec::new(),
303            ready: Vec::new(),
304            reads: FxHashMap::default(),
305            next_read: 0,
306            new_reads: VecDeque::new(),
307            dirty: Vec::new(),
308            dirty_flags: Vec::new(),
309            segments: Vec::new(),
310            values: ValueCache::default(),
311        }
312    }
313
314    /// Makes `chain` a pipeline writing `outlets`, and queues it to run.
315    pub(crate) fn add_pipeline(
316        &mut self,
317        chain: Chain,
318        outlets: SmallVec<[PortId; 1]>,
319    ) -> PipelineId {
320        let touched = InletSet::new(chain.inlets.len());
321        let changed = InletSet::all(chain.inlets.len());
322        let pipeline = Pipeline {
323            continuing: Vec::new(),
324            source_more: false,
325            source: chain.source,
326            stages: chain.stages,
327            inlets: chain.inlets,
328            outlets,
329            bytes: VecDeque::new(),
330            pending: 0,
331            finishing: None,
332            touched,
333            changed,
334            state: State::Runnable,
335            queued: true,
336        };
337        let id = match self.free_pipelines.pop() {
338            Some(id) => id,
339            None => self.pipelines.push(None),
340        };
341        for (index, &inlet) in pipeline.inlets.iter().enumerate() {
342            self.arena.get_mut(inlet).source = SourceEnd::Pipeline { id, inlet: index };
343        }
344        for &outlet in &pipeline.outlets {
345            self.arena.get_mut(outlet).sink = Some(id);
346        }
347        self.pipelines[id] = Some(pipeline);
348        self.ready.push(id);
349        id
350    }
351
352    /// Compiles `plan` over `rows`, restricted to `mask`, into pipelines whose output the scan
353    /// reads for split `split` in slot `slot`, and returns the output port. `None` when nothing
354    /// is selected.
355    pub(crate) fn compile_stage(
356        &mut self,
357        plan: &PlanRef,
358        rows: Range<u64>,
359        mask: &Mask,
360        slot: usize,
361    ) -> VortexResult<Option<PortId>> {
362        let Some(chain) = self.compile(plan, rows, mask)? else {
363            return Ok(None);
364        };
365        let port = self
366            .arena
367            .create(DEFAULT_CAPACITY, None, SourceEnd::Scan(slot));
368        self.add_pipeline(chain, smallvec::smallvec![port]);
369        #[cfg(debug_assertions)]
370        self.validate();
371        Ok(Some(port))
372    }
373
374    fn pipeline(&self, id: PipelineId) -> &Pipeline {
375        self.pipelines[id]
376            .as_ref()
377            .unwrap_or_else(|| unreachable!("pipeline {id} is not live"))
378    }
379
380    fn pipeline_mut(&mut self, id: PipelineId) -> &mut Pipeline {
381        self.pipelines[id]
382            .as_mut()
383            .unwrap_or_else(|| unreachable!("pipeline {id} is not live"))
384    }
385
386    fn make_runnable(&mut self, id: PipelineId) {
387        let pipe = self.pipeline_mut(id);
388        pipe.state = State::Runnable;
389        if !pipe.queued {
390            pipe.queued = true;
391            self.ready.push(id);
392        }
393    }
394
395    /// Runs pipeline `id` once and settles what it did.
396    fn run(&mut self, id: PipelineId) -> VortexResult<()> {
397        let pipe = self.pipelines[id]
398            .as_mut()
399            .ok_or_else(|| vortex_err!("Pipeline {id} is not live"))?;
400        pipe.queued = false;
401        let mut reads = SmallVec::new();
402        let progress = drive(
403            pipe,
404            &mut self.arena,
405            &self.session,
406            &mut self.exec,
407            &mut reads,
408        )?;
409        for segment_id in reads {
410            self.ask(id, segment_id);
411        }
412        #[cfg(debug_assertions)]
413        self.validate_progress(id, &progress);
414        match &progress {
415            // A read-ahead source can still have delivered bytes to consume.
416            Progress::Blocked(SourceBlocked::Io) if !self.pipeline(id).bytes.is_empty() => {
417                self.make_runnable(id);
418            }
419            // Nothing changes a port while its source's pipeline runs, so the condition the run reported
420            // holds until a neighbour wakes it.
421            Progress::Blocked(blocked) => self.pipeline_mut(id).state = State::Blocked(*blocked),
422            Progress::Outlet => self.pipeline_mut(id).state = State::Outlet,
423            Progress::Done => {}
424        }
425        self.wake_neighbours(id);
426        if matches!(progress, Progress::Done) {
427            self.retire(id);
428        }
429        Ok(())
430    }
431
432    /// Issues a read of `segment_id`, which pipeline `id`'s source asked for.
433    fn ask(&mut self, id: PipelineId, segment_id: SegmentId) {
434        self.read(id, segment_id);
435        self.pipeline_mut(id).pending += 1;
436    }
437
438    /// Wakes the sources of what pipeline `id` pushed and the sinks of what it took.
439    fn wake_neighbours(&mut self, id: PipelineId) {
440        for index in 0..self.pipeline(id).outlets.len() {
441            let port = self.pipeline(id).outlets[index];
442            let queue = self.arena.get_mut(port);
443            if !queue.take_changed() {
444                continue;
445            }
446            match queue.source {
447                SourceEnd::Pipeline { id: source, inlet } => {
448                    // Record every change, including inlets the source is not waiting on.
449                    let source_pipe = self.pipeline_mut(source);
450                    source_pipe.changed.insert(inlet);
451                    if source_pipe.state == State::Blocked(SourceBlocked::Inlet(inlet)) {
452                        self.make_runnable(source);
453                    }
454                }
455                SourceEnd::Scan(slot) => self.mark_dirty(slot),
456                SourceEnd::Unclaimed => {}
457            }
458        }
459        // Only an inlet the run read can have gained room, so a source with many inlets, as a
460        // concatenation of many chunks, pays for the inlets it read, not for all of them.
461        let mut touched = std::mem::take(&mut self.pipeline_mut(id).touched);
462        for &index in touched.indices() {
463            if let Some(sink) = self.arena.get(self.pipeline(id).inlets[index]).sink
464                && sink != id
465                && self.sink_has_room(sink)
466            {
467                self.make_runnable(sink);
468            }
469        }
470        touched.clear();
471        self.pipeline_mut(id).touched = touched;
472    }
473
474    /// Queues split slot `slot` for the scan to read its stage's output.
475    fn mark_dirty(&mut self, slot: usize) {
476        if !self.dirty_flags[slot] {
477            self.dirty_flags[slot] = true;
478            self.dirty.push(slot);
479        }
480    }
481
482    /// Whether pipeline `sink` is blocked on its outlets and every one of them has room now.
483    fn sink_has_room(&self, sink: PipelineId) -> bool {
484        let pipe = self.pipeline(sink);
485        pipe.state == State::Outlet
486            && pipe
487                .outlets
488                .iter()
489                .all(|&outlet| self.arena.has_room(outlet))
490    }
491
492    /// Drops a finished pipeline. Its outlets are closed; its inlets lose their source; the reads
493    /// it asked for and never took are cancelled, so their bytes are dropped on arrival instead
494    /// of reaching a pipeline that reuses its id.
495    fn retire(&mut self, id: PipelineId) {
496        if let Some(pipe) = self.pipelines[id].take() {
497            for inlet in pipe.inlets {
498                self.arena.drop_source(inlet);
499            }
500            if pipe.pending > 0 {
501                self.cancel_reads(id);
502            }
503            self.free_pipelines.push(id);
504        }
505    }
506
507    /// Cancels the reads pipeline `id` waits for: they become reads for no pipeline, whose
508    /// bytes are dropped on arrival.
509    fn cancel_reads(&mut self, id: PipelineId) {
510        for (owner, _) in self.reads.values_mut() {
511            if *owner == Some(id) {
512                *owner = None;
513            }
514        }
515    }
516
517    /// The scan has read a stage's output: wakes its sink if the output was full.
518    fn read_output(&mut self, port: PortId) {
519        if let Some(sink) = self.arena.get(port).sink
520            && self.sink_has_room(sink)
521        {
522            self.make_runnable(sink);
523        }
524    }
525
526    fn deliver(&mut self, read: ReadId, bytes: BufferHandle) -> VortexResult<()> {
527        let (owner, segment) = self
528            .reads
529            .remove(&read)
530            .ok_or_else(|| vortex_err!("Unknown read {read:?}"))?;
531        if let Some(id) = owner {
532            let pipe = self.pipeline_mut(id);
533            pipe.pending -= 1;
534            pipe.bytes.push_back((segment, bytes));
535            self.make_runnable(id);
536        }
537        Ok(())
538    }
539
540    /// Issues a read of `segment` for pipeline `owner`.
541    fn read(&mut self, owner: PipelineId, segment_id: SegmentId) {
542        let read = ReadId(self.next_read);
543        self.next_read += 1;
544        self.reads.insert(read, (Some(owner), segment_id));
545        self.new_reads.push_back(ReadRequest {
546            id: read,
547            segment_id,
548        });
549    }
550
551    /// Every live pipeline's state, and for one waiting on an inlet, that port and its sink.
552    fn describe_blocked(&self) -> String {
553        self.pipelines
554            .iter()
555            .enumerate()
556            .filter_map(|(id, pipe)| {
557                let pipe = pipe.as_ref()?;
558                Some(match pipe.state {
559                    State::Blocked(SourceBlocked::Inlet(index)) => {
560                        let port = pipe.inlets[index];
561                        let queue = self.arena.get(port);
562                        format!(
563                            "{id}: {:?} (port {port}: {} queued, closed {}, sink {:?})",
564                            pipe.state,
565                            queue.len(),
566                            queue.closed(),
567                            queue.sink.map(|sink| (sink, self.pipeline(sink).state)),
568                        )
569                    }
570                    state => format!("{id}: {state:?}"),
571                })
572            })
573            .collect::<Vec<_>>()
574            .join(", ")
575    }
576}
577
578/// What a scan runs over each split.
579#[derive(Clone)]
580enum Root {
581    /// The plan, under the split's selection.
582    Plan(PlanRef),
583}
584
585/// A split being run.
586struct Active {
587    index: usize,
588    /// The output port of the stage running, read by the scan.
589    output: Option<PortId>,
590}
591
592/// Runs a plan over a list of splits.
593///
594/// The plan runs as one stage under each split's selection.
595///
596/// Up to [`with_max_active`](Self::with_max_active) splits are compiled at once, in order, so
597/// reads of later splits are in flight while earlier ones compute.
598pub struct Scan {
599    core: Core,
600    root: Option<Root>,
601    splits: Vec<Split>,
602    next: usize,
603    max_active: usize,
604    active: Vec<Option<Active>>,
605    live: usize,
606    outputs: VecDeque<(usize, ArrayRef)>,
607}
608
609impl fmt::Debug for Scan {
610    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
611        f.debug_struct("Scan")
612            .field("splits", &self.splits.len())
613            .field("next", &self.next)
614            .field("live", &self.live)
615            .finish()
616    }
617}
618
619impl Scan {
620    /// A scan of `plan` over `splits`, with one split active at a time.
621    ///
622    /// Counts, from the plan, how often each split will read each segment, so segments read
623    /// more than once are decoded once. Builds no pipeline and issues no read.
624    pub fn try_new(
625        session: VortexSession,
626        plan: PlanRef,
627        splits: Vec<Split>,
628    ) -> VortexResult<Self> {
629        for split in &splits {
630            vortex_ensure!(
631                split.rows.start <= split.rows.end
632                    && split.rows.end <= plan.row_count()
633                    && split.mask.len() as u64 == split.rows.end - split.rows.start,
634                "Split {:?} with a mask of {} rows does not fit a plan of {} rows",
635                split.rows,
636                split.mask.len(),
637                plan.row_count()
638            );
639        }
640        let root = Root::Plan(plan);
641        let mut core = Core::new(session, 0);
642        core.dirty_flags = vec![false; 1];
643        Ok(Self {
644            core,
645            root: Some(root),
646            splits,
647            next: 0,
648            max_active: 1,
649            active: vec![None],
650            live: 0,
651            outputs: VecDeque::new(),
652        })
653    }
654
655    /// The segments compiling `plan` over `rows` under `mask` reads, each once, in id order.
656    /// Compiling does no IO, so the segments a stage will read are known before it starts.
657    pub fn segments(
658        session: &VortexSession,
659        plan: &PlanRef,
660        rows: Range<u64>,
661        mask: &Mask,
662    ) -> VortexResult<Vec<SegmentId>> {
663        let mut core = Core::new(session.clone(), 0);
664        core.compile(plan, rows, mask)?;
665        let mut segments = core.segments;
666        segments.sort_unstable();
667        segments.dedup();
668        Ok(segments)
669    }
670
671    /// Runs up to `max_active` splits at once.
672    ///
673    /// Changing this after execution has started preserves live slots and queued dirty
674    /// notifications: shrinking lets already-active splits finish before admitting new ones
675    /// below the new limit, and growing appends free slots without moving active ones.
676    pub fn with_max_active(mut self, max_active: usize) -> Self {
677        let max_active = max_active.max(1);
678        self.max_active = max_active;
679        // Never truncate: live slots index into `active` and `dirty_flags`.
680        if max_active > self.active.len() {
681            self.active.resize_with(max_active, || None);
682            self.core.dirty_flags.resize(max_active, false);
683        }
684        self
685    }
686
687    /// Sets the global row index of plan row zero, which row-index plans add to their rows.
688    pub fn with_row_offset(mut self, row_offset: u64) -> Self {
689        self.core.row_offset = row_offset;
690        self
691    }
692
693    /// Shares whole values, such as dictionary values, with the other scans given `values`.
694    pub fn with_value_cache(mut self, values: ValueCache) -> Self {
695        self.core.values = values;
696        self
697    }
698
699    /// Runs pipelines until the owner has something to do.
700    pub fn step(&mut self) -> VortexResult<Turn> {
701        loop {
702            if let Some((split, array)) = self.outputs.pop_front() {
703                let array = array.optimize_ctx(&self.core.exec)?;
704                return Ok(Turn::Output(split, array));
705            }
706            if let Some(read) = self.core.new_reads.pop_front() {
707                return Ok(Turn::Read(read));
708            }
709            if let Some(slot) = self.core.dirty.pop() {
710                self.core.dirty_flags[slot] = false;
711                self.advance(slot)?;
712                continue;
713            }
714            if self.live < self.max_active && self.next < self.splits.len() {
715                self.activate()?;
716                continue;
717            }
718            if let Some(id) = self.core.ready.pop() {
719                self.core.run(id)?;
720                continue;
721            }
722            // Reads still in flight once every split has finished were cancelled; nothing waits
723            // for their bytes.
724            if self.live == 0 {
725                return Ok(Turn::Done);
726            }
727            if !self.core.reads.is_empty() {
728                return Ok(Turn::Waiting);
729            }
730            vortex_bail!(
731                "Scan is stuck with nothing runnable and no read in flight: {}",
732                self.core.describe_blocked()
733            );
734        }
735    }
736
737    /// Delivers the bytes of a read [`step`](Self::step) returned.
738    pub fn deliver(&mut self, read: ReadId, bytes: BufferHandle) -> VortexResult<()> {
739        self.core.deliver(read, bytes)
740    }
741
742    /// Starts the next split in a free slot.
743    fn activate(&mut self) -> VortexResult<()> {
744        let slot = self
745            .active
746            .iter()
747            .position(Option::is_none)
748            .ok_or_else(|| vortex_err!("No free split slot"))?;
749        let index = self.next;
750        self.next += 1;
751        let split = self.splits[index].clone();
752        let output = match self
753            .root
754            .as_ref()
755            .ok_or_else(|| vortex_err!("Scan has no plan for its next split"))?
756        {
757            Root::Plan(plan) => {
758                self.core
759                    .compile_stage(plan, split.rows.clone(), &split.mask, slot)?
760            }
761        };
762        if self.next == self.splits.len() {
763            // Compiled operators own what they need. The last split no longer needs the
764            // lowering tree or the source layouts retained by its lazy slots.
765            self.root = None;
766        }
767        if output.is_some() {
768            self.active[slot] = Some(Active { index, output });
769            self.live += 1;
770        }
771        Ok(())
772    }
773
774    /// Takes what the stage running in `slot` produced, and moves the split on when the stage
775    /// has finished.
776    fn advance(&mut self, slot: usize) -> VortexResult<()> {
777        let Some(active) = self.active[slot].as_mut() else {
778            return Ok(());
779        };
780        while let Some(port) = active.output {
781            while let Some(batch) = self.core.arena.get_mut(port).pop() {
782                self.outputs.push_back((active.index, batch));
783            }
784            self.core.read_output(port);
785            if !self.core.arena.get(port).closed() {
786                return Ok(());
787            }
788            self.core.arena.drop_source(port);
789            active.output = None;
790        }
791        self.active[slot] = None;
792        self.live -= 1;
793        Ok(())
794    }
795
796    /// Ports in use.
797    #[cfg(test)]
798    pub(crate) fn live_ports(&self) -> usize {
799        self.core.arena.live()
800    }
801
802    /// Reads in flight that a pipeline waits for.
803    #[cfg(test)]
804    pub(crate) fn awaited_reads(&self) -> usize {
805        self.core
806            .reads
807            .values()
808            .filter(|(owner, _)| owner.is_some())
809            .count()
810    }
811}