Skip to main content

vortex_scan/
prepare.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Preparation of source-independent scan plans.
5
6use std::ops::Range;
7use std::sync::Arc;
8
9use vortex_array::dtype::DType;
10use vortex_array::expr::BoundExpression;
11use vortex_error::VortexResult;
12use vortex_session::VortexSession;
13
14use crate::analysis::referenced_field_paths;
15pub use crate::execution::ChunkPlanner;
16use crate::execution::FILTERED_ROWS_PER_CHUNK;
17pub use crate::execution::FilterPlans;
18use crate::execution::MAX_ROWS_PER_CHUNK;
19pub use crate::execution::PreparedScan;
20pub use crate::execution::PruneNext;
21pub use crate::execution::PrunePlanner;
22use crate::execution::ROW_BLOCK_SIZE;
23pub use crate::execution::SegmentLocation;
24pub use crate::execution::cache::ScanCache;
25pub use crate::execution::cache::WeakScanCache;
26use crate::execution::io::segment_ranges;
27use crate::execution::rows_per_chunk;
28use crate::plan::optimize;
29use crate::plan::plan_row_idx_expression;
30use crate::selection::Selection;
31use crate::source::ScanInput;
32use crate::strict_sorted_buffer::StrictSortedBuffer;
33
34/// Prepares a scan on the planner-driven executor.
35///
36/// This builder plans a source without reading its payloads.
37/// Driving the plan is the engine's: see [`PreparedScan`]. Row limits are not supported.
38pub struct ScanBuilder {
39    session: VortexSession,
40    file: ScanInput,
41    projection: BoundExpression,
42    filter: Option<BoundExpression>,
43    row_range: Option<Range<u64>>,
44    selection: Selection,
45    row_offset: u64,
46    skip_unselective_dynamic: bool,
47}
48
49impl ScanBuilder {
50    /// Creates a scan over a lazily lowered plan and its byte source.
51    pub fn new(session: VortexSession, file: impl Into<ScanInput>) -> Self {
52        let file = file.into();
53        Self {
54            projection: BoundExpression::new_root(file.dtype.clone()),
55            filter: None,
56            session,
57            file,
58            row_range: None,
59            selection: Selection::default(),
60            row_offset: 0,
61            skip_unselective_dynamic: false,
62        }
63    }
64
65    /// The output dtype after projection.
66    pub fn dtype(&self) -> &DType {
67        self.projection.dtype()
68    }
69
70    /// The session the scan decodes and evaluates expressions with.
71    pub fn session(&self) -> &VortexSession {
72        &self.session
73    }
74
75    /// Sets a projection bound against the file's dtype.
76    pub fn with_projection(mut self, projection: BoundExpression) -> Self {
77        self.projection = projection;
78        self
79    }
80
81    /// Evaluates a bound predicate before projecting the surviving rows.
82    pub fn with_some_filter(mut self, filter: Option<BoundExpression>) -> Self {
83        self.filter = filter;
84        self
85    }
86
87    /// Allows the scan to switch off a filter conjunct containing dynamic expressions once it has
88    /// kept almost every row on several consecutive chunks, skipping its zone pruning and its
89    /// evaluation until its dynamic values change.
90    ///
91    /// The scan may then return rows the conjunct would reject, so only enable this when the
92    /// dynamic expressions are hints whose producer applies them again, such as DataFusion's
93    /// TopK and hash-join dynamic filters. Off by default.
94    pub fn with_skip_unselective_dynamic(mut self, skip: bool) -> Self {
95        self.skip_unselective_dynamic = skip;
96        self
97    }
98
99    /// Restricts scanning to a contiguous source-local row range. A range that starts after it
100    /// ends selects no rows.
101    pub fn with_row_range(mut self, row_range: Range<u64>) -> Self {
102        self.row_range = Some(row_range.start..row_range.end.max(row_range.start));
103        self
104    }
105
106    /// Applies a row selection within the scan's row range.
107    pub fn with_selection(mut self, selection: Selection) -> Self {
108        self.selection = selection;
109        self
110    }
111
112    /// Selects rows by strictly sorted source-local indices.
113    pub fn with_row_indices(self, row_indices: StrictSortedBuffer<u64>) -> Self {
114        self.with_selection(Selection::IncludeByIndex(row_indices))
115    }
116
117    /// Sets the root row offset used by row-index expressions.
118    pub fn with_row_offset(mut self, row_offset: u64) -> Self {
119        self.row_offset = row_offset;
120        self
121    }
122
123    /// Initializes the source plan and plans the filter and the projection, from the file's cache
124    /// where an earlier scan planned them already. Touches no segment. Lowering and optimizing a
125    /// wide file is real CPU, so a driver runs this where it runs compute.
126    pub fn prepare(self) -> VortexResult<PreparedScan> {
127        let file = self.file;
128        let cache = file.cache.unwrap_or_default();
129        let root = match cache.root() {
130            Some(root) => root,
131            None => cache.insert_root(file.root.get()?.clone()),
132        };
133        let row_count = root.row_count();
134        let filtered_chunk_rows = self
135            .filter
136            .as_ref()
137            .map(|filter| filtered_rows_per_chunk(root.dtype(), &self.projection, filter))
138            .transpose()?;
139        let filter = self
140            .filter
141            .map(|filter| -> VortexResult<_> {
142                let skip = self.skip_unselective_dynamic;
143                match cache.filter_plans(&filter) {
144                    Some(plans) if plans.skips_unselective_dynamic() == skip => Ok(plans),
145                    // A scan whose skipping differs from the cached plans' plans its own.
146                    Some(_) => Ok(Arc::new(FilterPlans::new(
147                        filter,
148                        &root,
149                        &self.session,
150                        skip,
151                    )?)),
152                    None => {
153                        let plans = Arc::new(FilterPlans::new(
154                            filter.clone(),
155                            &root,
156                            &self.session,
157                            skip,
158                        )?);
159                        Ok(cache.insert_filter_plans(filter, plans))
160                    }
161                }
162            })
163            .transpose()?;
164        // Optimizing drops the zone tables a projection never reads and keeps the chunks of a
165        // chunked column lazy, so an identity projection is optimized like any other.
166        let identity = self.projection.is_root() && self.projection.dtype() == root.dtype();
167        let projection = match cache.projection(&self.projection) {
168            Some(plan) => plan,
169            None => {
170                let plan = optimize(
171                    plan_row_idx_expression(self.projection.clone(), root, &self.session)?,
172                    &self.session,
173                )?;
174                cache.insert_projection(self.projection, plan)
175            }
176        };
177        let chunk_rows = if let Some(rows) = filtered_chunk_rows {
178            rows
179        } else if identity {
180            rows_per_chunk(row_count, &file.locations)
181        } else {
182            MAX_ROWS_PER_CHUNK
183        };
184        let ranges = match cache.ranges() {
185            Some(ranges) => ranges,
186            None => cache.insert_ranges(segment_ranges(&file.locations)),
187        };
188        let values = cache.values();
189        Ok(PreparedScan {
190            session: self.session,
191            rows: self.row_range.unwrap_or(0..row_count),
192            selection: self.selection,
193            segments: cache.retaining(file.segments),
194            ranges,
195            cache,
196            locations: file.locations,
197            projection,
198            filter,
199            row_offset: self.row_offset,
200            values,
201            chunk_rows,
202        })
203    }
204}
205
206pub(crate) fn filtered_rows_per_chunk(
207    dtype: &DType,
208    projection: &BoundExpression,
209    filter: &BoundExpression,
210) -> VortexResult<usize> {
211    let mut fields = referenced_field_paths(projection)?;
212    fields.extend(referenced_field_paths(filter)?);
213    let mut fields = fields.into_iter();
214    let first = fields.next();
215    // A scan of one fixed-width field is cheap enough that smaller chunks mainly add setup.
216    // Wider and variable-width scans need more chunks to avoid long tails on a few workers.
217    let narrow = fields.next().is_none()
218        && first
219            .and_then(|field| field.resolve(dtype.clone()))
220            .is_some_and(|dtype| matches!(dtype, DType::Primitive(..) | DType::Bool(..)));
221    Ok(if narrow {
222        128 * ROW_BLOCK_SIZE
223    } else {
224        FILTERED_ROWS_PER_CHUNK
225    })
226}