Skip to main content

vortex_scan/execution/pipeline/
compile.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Compiling plans into pipelines, and counting the readers of each segment so segments read
5//! more than once are decoded once.
6
7use std::ops::Range;
8
9use vortex_error::VortexResult;
10use vortex_mask::Mask;
11use vortex_session::VortexSession;
12
13use super::DEFAULT_CAPACITY;
14use super::port::PortId;
15use super::port::SourceEnd;
16use super::scan::Core;
17use super::values::ValueCache;
18use crate::execution::operator::Operator;
19use crate::execution::operator::Source;
20use crate::plan::ConcatPlan;
21use crate::plan::PlanRef;
22use crate::source::SegmentId;
23
24/// A pipeline under construction: a source and the stages after it, not yet given outlets, so a
25/// parent plan can add stages before it becomes a pipeline.
26pub struct Chain {
27    pub(crate) source: Box<dyn Source>,
28    pub(crate) stages: Vec<Box<dyn Operator>>,
29    pub(crate) inlets: Vec<PortId>,
30}
31
32impl Chain {
33    /// A chain of `source` alone.
34    pub fn new(source: impl Source + 'static) -> Self {
35        Self {
36            source: Box::new(source),
37            stages: Vec::new(),
38            inlets: Vec::new(),
39        }
40    }
41
42    /// A chain passing the batches of `port` through.
43    /// This chain with `stage` after its last stage.
44    pub fn with(mut self, stage: impl Operator + 'static) -> Self {
45        self.stages.push(Box::new(stage));
46        self
47    }
48}
49
50impl Core {
51    /// Compiles `plan` over `rows`, restricted to `mask`. See [`Compiler::compile`].
52    pub(crate) fn compile(
53        &mut self,
54        plan: &PlanRef,
55        rows: Range<u64>,
56        mask: &Mask,
57    ) -> VortexResult<Option<Chain>> {
58        Compiler { core: self }.compile(plan, rows, mask)
59    }
60}
61
62/// What a plan compiles its children through. See
63/// [`PlanVTable::compile`](crate::plan::PlanVTable::compile).
64pub struct Compiler<'a> {
65    pub(crate) core: &'a mut Core,
66}
67
68impl Compiler<'_> {
69    /// Compiles `plan` over `rows` of its domain, restricted to `mask`, into a chain producing
70    /// the rows `mask` selects, in order, or `None` when that is no row.
71    pub fn compile(
72        &mut self,
73        plan: &PlanRef,
74        rows: Range<u64>,
75        mask: &Mask,
76    ) -> VortexResult<Option<Chain>> {
77        if rows.start >= rows.end {
78            return Ok(None);
79        }
80        plan.compile(rows, mask, self)
81    }
82
83    /// A chain reading `chains` through `source`: each chain becomes a pipeline writing a new
84    /// port, inlet `i` of `source` reading chain `i`, holding [`DEFAULT_CAPACITY`] batches.
85    pub fn join(&mut self, chains: Vec<Chain>, source: impl Source + 'static) -> Chain {
86        self.join_with(chains, |_| DEFAULT_CAPACITY, source)
87    }
88
89    /// [`join`](Self::join), with inlet `i` holding `capacity(i)` batches before its sink is
90    /// blocked: `usize::MAX` for an inlet the source needs whole. An empty inlet always has
91    /// room.
92    pub fn join_with(
93        &mut self,
94        chains: Vec<Chain>,
95        capacity: impl Fn(usize) -> usize,
96        source: impl Source + 'static,
97    ) -> Chain {
98        let inlets = chains
99            .into_iter()
100            .enumerate()
101            .map(|(index, chain)| {
102                let port = self
103                    .core
104                    .arena
105                    .create(capacity(index), None, SourceEnd::Unclaimed);
106                self.core.add_pipeline(chain, smallvec::smallvec![port]);
107                port
108            })
109            .collect();
110        Chain {
111            source: Box::new(source),
112            stages: Vec::new(),
113            inlets,
114        }
115    }
116
117    /// The global row index of the scanned plan's row zero.
118    pub fn row_offset(&self) -> u64 {
119        self.core.row_offset
120    }
121
122    /// The session used for decoding and evaluation.
123    pub fn session(&self) -> &VortexSession {
124        &self.core.session
125    }
126
127    /// Whole values kept between the scans of the split compiling.
128    pub(crate) fn values(&self) -> &ValueCache {
129        &self.core.values
130    }
131
132    /// Records a source's segment dependency while compiling, without issuing IO.
133    ///
134    /// Source adapters call this for each segment their chain will request so filter prefetching
135    /// and projection announcements see the same dependencies as execution.
136    pub fn register_segment(&mut self, segment: SegmentId) {
137        self.core.segments.push(segment);
138    }
139}
140
141/// The chunks of `concat` overlapping `rows`: each chunk's index, where it starts, and the rows
142/// of `rows` it holds, in the concatenation's domain. Found by binary search, so a split pays
143/// for the chunks it overlaps, not for the chunks of the file.
144pub(crate) fn overlapping<'a>(
145    concat: &'a ConcatPlan,
146    rows: &Range<u64>,
147) -> impl Iterator<Item = (usize, u64, Range<u64>)> + 'a {
148    let offsets = concat.row_offsets();
149    let first = offsets
150        .partition_point(|&offset| offset <= rows.start)
151        .saturating_sub(1);
152    let end = offsets.partition_point(|&offset| offset < rows.end);
153    let rows = rows.clone();
154    (first..end).filter_map(move |index| {
155        let start = offsets[index];
156        let chunk_end = offsets
157            .get(index + 1)
158            .copied()
159            .unwrap_or_else(|| concat.row_count());
160        let local = rows.start.max(start)..rows.end.min(chunk_end);
161        (local.start < local.end).then_some((index, start, local))
162    })
163}