Skip to main content

vortex_scan/execution/
prune.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Evaluates a filter's pruning plans once over a scan's rows, before any chunk is planned.
5
6use std::ops::Range;
7use std::sync::Arc;
8use std::vec::IntoIter;
9
10use rustc_hash::FxHashSet;
11use vortex_error::VortexResult;
12use vortex_error::vortex_ensure_eq;
13use vortex_error::vortex_err;
14use vortex_io::request::IoConsumer;
15use vortex_io::request::IoIntent;
16use vortex_io::request::IoRequestId;
17use vortex_io::request::IoResult;
18use vortex_mask::Mask;
19
20use super::PreparedScan;
21use super::adaptor::AdaptorStep;
22use super::adaptor::ScanAdaptor;
23use super::filter::hint;
24use super::filter::piece_mask;
25use super::filter::segments_read;
26use crate::execution::pipeline::Scan;
27use crate::execution::pipeline::Split;
28use crate::plan::PlanRef;
29use crate::planning::planner::Planner;
30use crate::planning::planner::PlannerOutput;
31use crate::planning::planner::State;
32use crate::planning::planner::WorkScope;
33
34/// The planner a prune planner continues into, given the rows pruning kept, or `None` when
35/// no pruning plan ran.
36pub type PruneNext = Box<dyn FnOnce(Option<Mask>) -> Box<dyn Planner> + Send>;
37
38/// Evaluates the filter's pruning plans over the scan's rows and emits the planner it was
39/// built to continue into, with the rows no plan pruned. The zone maps are the only reads,
40/// started together. Rows every plan prunes end the scan here: nothing is emitted. A filter
41/// without pruning plans emits the next planner at once.
42pub struct PrunePlanner {
43    scan: Arc<PreparedScan>,
44    rows: Range<u64>,
45    /// What to emit once every pruning plan has run, taken when it is.
46    next: Option<PruneNext>,
47    /// Whether any pruning plan ran, so the kept rows mean something.
48    pruned: bool,
49    /// The rows no pruning plan has excluded yet, over `rows`.
50    mask: Mask,
51    pruning: IntoIter<PlanRef>,
52    active: Option<ScanAdaptor>,
53    pieces: Vec<Mask>,
54    announced: bool,
55    /// Ids for hints, counting down from `u32::MAX` so they never meet an adaptor's fetch ids.
56    next_hint: u32,
57    done: bool,
58}
59
60impl PrunePlanner {
61    /// The planner of `scan`'s filter's pruning plans over `rows`, continuing into `next`.
62    pub fn new(scan: Arc<PreparedScan>, rows: Range<u64>, next: PruneNext) -> Self {
63        let pruning: Vec<_> = scan
64            .filter
65            .iter()
66            .flat_map(|filter| filter.pruning_over(rows.end - rows.start).cloned())
67            .collect();
68        let len = usize::try_from(rows.end - rows.start).unwrap_or(usize::MAX);
69        Self {
70            scan,
71            rows,
72            next: Some(next),
73            pruned: false,
74            mask: Mask::new_true(len),
75            pruning: pruning.into_iter(),
76            active: None,
77            pieces: Vec::new(),
78            announced: false,
79            next_hint: u32::MAX,
80            done: false,
81        }
82    }
83}
84
85impl IoConsumer for PrunePlanner {
86    fn set_io_result(&mut self, request: IoRequestId, result: IoResult) {
87        if let Some(adaptor) = &mut self.active {
88            adaptor.set_io_result(request, result);
89        }
90    }
91}
92
93impl Planner for PrunePlanner {
94    fn state(&self) -> State {
95        if self.done {
96            return State::Done;
97        }
98        match &self.active {
99            Some(adaptor) if adaptor.state() != State::Done => adaptor.state(),
100            _ => State::NeedsCompute,
101        }
102    }
103
104    fn compute(&mut self) -> VortexResult<PlannerOutput> {
105        if self.done {
106            return Ok(PlannerOutput::Done);
107        }
108        if !self.announced {
109            self.announced = true;
110            // A pruning plan whose zones an earlier scan of the file pruned compiles to its kept
111            // result and lists no segment, so only unpruned plans prefetch their zone maps.
112            let segments = segments_read(
113                &self.scan.session,
114                self.pruning.as_slice().iter(),
115                self.rows.clone(),
116                &self.mask,
117            )?;
118            let mut batch = Vec::new();
119            let mut seen = FxHashSet::default();
120            hint(
121                &self.scan.locations,
122                &mut self.next_hint,
123                IoIntent::Prefetch,
124                &segments,
125                &mut seen,
126                &mut batch,
127            );
128            if !batch.is_empty() {
129                return Ok(PlannerOutput::NeedsIO(batch));
130            }
131        }
132        if let Some(adaptor) = &mut self.active {
133            if adaptor.state() != State::Done {
134                return Ok(match adaptor.compute()? {
135                    AdaptorStep::Yield => PlannerOutput::Continue,
136                    AdaptorStep::NeedsIO(batch) => PlannerOutput::NeedsIO(batch),
137                    AdaptorStep::Piece(piece) => {
138                        self.pieces.push(piece_mask(&self.scan.session, piece)?);
139                        PlannerOutput::Continue
140                    }
141                });
142            }
143            let input = self.mask.true_count();
144            let excluded = Mask::concat(self.pieces.iter())?;
145            vortex_ensure_eq!(excluded.len(), input);
146            self.mask = self.mask.intersect_by_rank(&!excluded);
147            tracing::debug!(
148                row_start = self.rows.start,
149                row_end = self.rows.end,
150                input_rows = input,
151                output_rows = self.mask.true_count(),
152                "v2 pruning plan evaluated"
153            );
154            self.active = None;
155            self.pieces.clear();
156            self.pruned = true;
157        }
158        if self.mask.all_false() {
159            self.done = true;
160            return Ok(PlannerOutput::Done);
161        }
162        if let Some(plan) = self.pruning.next() {
163            let scan = Scan::try_new(
164                self.scan.session.clone(),
165                plan,
166                vec![Split {
167                    rows: self.rows.clone(),
168                    mask: self.mask.clone(),
169                }],
170            )?
171            .with_row_offset(self.scan.row_offset)
172            .with_value_cache(self.scan.values.clone());
173            self.active = Some(ScanAdaptor::new(scan, Arc::clone(&self.scan.locations)));
174            return Ok(PlannerOutput::Continue);
175        }
176        // Every pruning plan has run: the planner this one continues into gets the kept rows.
177        self.done = true;
178        tracing::debug!(
179            row_start = self.rows.start,
180            row_end = self.rows.end,
181            kept_rows = self.mask.true_count(),
182            "v2 pruning finished"
183        );
184        let next = self
185            .next
186            .take()
187            .ok_or_else(|| vortex_err!("the prune planner has nothing to continue into"))?;
188        let kept = self
189            .pruned
190            .then(|| std::mem::replace(&mut self.mask, Mask::new_true(0)));
191        Ok(PlannerOutput::Planner(
192            WorkScope {
193                file_ordinal: 0,
194                rows: self.rows.clone(),
195            },
196            next(kept),
197        ))
198    }
199}