Skip to main content

vortex_scan/execution/
chunk.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Cuts a scan's rows into chunks and plans each one.
5
6use std::ops::Range;
7use std::sync::Arc;
8use std::vec::IntoIter;
9
10use vortex_error::VortexExpect;
11use vortex_error::VortexResult;
12use vortex_io::request::IoConsumer;
13use vortex_io::request::IoRequestId;
14use vortex_io::request::IoResult;
15use vortex_mask::Mask;
16
17use super::PreparedScan;
18use super::SegmentLocation;
19use super::selection::plan_selection;
20use crate::planning::planner::Planner;
21use crate::planning::planner::PlannerOutput;
22use crate::planning::planner::State;
23use crate::planning::planner::WorkScope;
24use crate::selection::Selection;
25
26/// The row grid every chunk boundary lies on.
27pub(crate) const ROW_BLOCK_SIZE: usize = 8192;
28/// The rows of a projection chunk.
29pub(crate) const MAX_ROWS_PER_CHUNK: usize = 8 * ROW_BLOCK_SIZE;
30/// The rows of a filtered chunk, balancing conjunct setup against parallelism.
31pub(crate) const FILTERED_ROWS_PER_CHUNK: usize = 16 * ROW_BLOCK_SIZE;
32const TARGET_BYTES_PER_CHUNK: u64 = 8 * 1024 * 1024;
33
34/// Limit estimated bytes per chunk without changing the writer-aligned row granularity.
35pub(crate) fn rows_per_chunk(row_count: u64, locations: &[SegmentLocation]) -> usize {
36    if row_count <= MAX_ROWS_PER_CHUNK as u64 {
37        return MAX_ROWS_PER_CHUNK;
38    }
39    let bytes: u64 = locations
40        .iter()
41        .map(|location| u64::from(location.length))
42        .sum();
43    let bytes_per_row = bytes.div_ceil(row_count).max(1);
44    let blocks = TARGET_BYTES_PER_CHUNK / bytes_per_row / ROW_BLOCK_SIZE as u64;
45    blocks.clamp(1, 8) as usize * ROW_BLOCK_SIZE
46}
47
48/// Fixed boundaries in the file's row domain, clipped to the requested range.
49pub(crate) fn row_chunks(rows: Range<u64>, rows_per_chunk: usize) -> Vec<Range<u64>> {
50    if rows.is_empty() {
51        return Vec::new();
52    }
53    let first = rows.start / rows_per_chunk as u64 * rows_per_chunk as u64;
54    (first..rows.end)
55        .step_by(rows_per_chunk)
56        .map(|start| {
57            start.max(rows.start)..start.saturating_add(rows_per_chunk as u64).min(rows.end)
58        })
59        .collect()
60}
61
62/// The chunks a scan of `rows` plans: [`row_chunks`], with a chunk at either edge of `rows` that
63/// is under half of `rows_per_chunk` joined to its neighbour. An engine cuts a file into
64/// partitions whose edges fall off the chunk grid, and a short edge chunk would cost a whole
65/// chunk's planning and conjunct setup for a few rows.
66pub(crate) fn scan_chunks(rows: Range<u64>, rows_per_chunk: usize) -> Vec<Range<u64>> {
67    let mut chunks = row_chunks(rows, rows_per_chunk);
68    let short = |chunk: &Range<u64>| chunk.end - chunk.start < rows_per_chunk as u64 / 2;
69    if chunks.len() > 1 && chunks.last().is_some_and(short) {
70        let last = chunks.pop().vortex_expect("more than one chunk");
71        chunks.last_mut().vortex_expect("more than one chunk").end = last.end;
72    }
73    if chunks.len() > 1 && short(&chunks[0]) {
74        let first = chunks.remove(0);
75        chunks[0].start = first.start;
76    }
77    chunks
78}
79
80/// Emits one planner per chunk of a scan's rows, in row order, each spawned as independent so
81/// the driver may run it beside the others. A chunk none of whose rows is selected and kept is
82/// never planned.
83pub struct ChunkPlanner {
84    scan: Arc<PreparedScan>,
85    rows: Range<u64>,
86    chunks: IntoIter<Range<u64>>,
87    selection: Selection,
88    /// The rows zone pruning kept, over `rows`, or `None` when nothing was pruned.
89    kept: Option<Mask>,
90}
91
92impl ChunkPlanner {
93    /// The planner of the chunks of `rows`, planning only what `selection` and `kept`, the rows
94    /// zone pruning left over `rows`, leave something of.
95    pub fn new(
96        scan: Arc<PreparedScan>,
97        rows: Range<u64>,
98        selection: Selection,
99        kept: Option<Mask>,
100    ) -> Self {
101        let chunks = scan_chunks(rows.clone(), scan.chunk_rows).into_iter();
102        Self {
103            scan,
104            rows,
105            chunks,
106            selection,
107            kept,
108        }
109    }
110}
111
112impl IoConsumer for ChunkPlanner {
113    fn set_io_result(&mut self, _request: IoRequestId, _result: IoResult) {}
114}
115
116impl Planner for ChunkPlanner {
117    fn state(&self) -> State {
118        if self.chunks.as_slice().is_empty() {
119            State::Done
120        } else {
121            State::NeedsCompute
122        }
123    }
124
125    fn compute(&mut self) -> VortexResult<PlannerOutput> {
126        let kept = self.kept.as_ref().map(|kept| (kept, self.rows.start));
127        for chunk in self.chunks.by_ref() {
128            let scope = WorkScope {
129                file_ordinal: 0,
130                rows: chunk,
131            };
132            if let Some((scope, planner)) = plan_selection(&self.scan, scope, &self.selection, kept)
133            {
134                return Ok(PlannerOutput::Spawn(scope, planner));
135            }
136        }
137        Ok(PlannerOutput::Done)
138    }
139}