From 0f59a115f8c997e1c158949d86f680c0aeeba012 Mon Sep 17 00:00:00 2001 From: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com> Date: Wed, 2 Dec 2026 14:51:43 -0800 Subject: [PATCH] refactor: split page index pruning into steps PagePruningAccessPlanFilter::prune_plan_with_page_index_and_metrics is one function of about 250 lines with 11 mutable locals. It mixes four things: ordinary page pruning of a row group, the update of the access plan, the search for fully matched rows that LIMIT pruning uses, and the row and page counts. The same four references to the file go to every helper that it calls. Add PagePruner, which holds the file and the counts of one pass. Each step is one method: - prune_row_group applies the predicates to one row group - apply_selection records the result in the access plan - fully_matched_selection finds the rows that pass for certain - prune_pages_for_predicate, which was a free function with six arguments PagePruningCounts holds the four counters and writes them to the metrics. inverted_predicates builds the inverse predicates. The entry point is now about 100 lines and reads as the sequence of those steps. No behavior changes: the order of the early returns, the counts and the number of predicate evaluations are the same. Co-Authored-By: Claude Fable 5.2 --- .../datasource-parquet/src/page_filter.rs | 488 ++++++++++-------- 1 file changed, 275 insertions(+), 213 deletions(-) diff --git a/datafusion/datasource-parquet/src/page_filter.rs b/datafusion/datasource-parquet/src/page_filter.rs index ef998b0e0beed..7d3932e7e72fe 100644 --- a/datafusion/datasource-parquet/src/page_filter.rs +++ b/datafusion/datasource-parquet/src/page_filter.rs @@ -219,61 +219,25 @@ impl PagePruningAccessPlanFilter { ) -> PagePruningResult { // scoped timer updates on drop let _timer_guard = file_metrics.page_index_eval_time.timer(); - if self.predicates.is_empty() { - return PagePruningResult::new(access_plan, 0, 0); - } - - let page_index_predicates = &self.predicates; let groups = parquet_metadata.row_groups(); - - if groups.is_empty() { + if self.predicates.is_empty() || groups.is_empty() { return PagePruningResult::new(access_plan, 0, 0); } - if !parquet_metadata - .page_index() - .is_some_and(|page_index| page_index.is_complete()) - { - debug!( - "Can not prune pages due to lack of indexes. Have offset: {}, column index: {}", - parquet_metadata - .page_index() - .is_some_and(|page_index| page_index.has_offset_indexes()), - parquet_metadata - .page_index() - .is_some_and(|page_index| page_index.has_column_indexes()) - ); + let mut pruner = + PagePruner::new(arrow_schema, parquet_schema, parquet_metadata, file_metrics); + if !pruner.has_complete_page_index() { return PagePruningResult::new(access_plan, 0, 0); } // Build inverse predicates only for unordered LIMIT queries. Ordinary // page pruning does not need them. - let inverted_predicates: Option> = - if limit.is_some() && self.all_predicates_supported { - self.predicates - .iter() - .map(|predicate| { - let inverted = PruningPredicateBuilder::new() - .with_file_schema(Arc::clone(predicate.schema())) - .with_max_in_list_size(predicate.max_in_list_size()) - .try_build_inverse(Arc::clone(predicate.orig_expr())) - .ok() - .flatten()?; - single_column(&inverted).is_some().then_some(inverted) - }) - .collect() - } else { - None - }; + let inverted_predicates = if limit.is_some() && self.all_predicates_supported { + self.inverted_predicates() + } else { + None + }; - // track the total number of rows that should be skipped - let mut total_skip = 0; - // track the total number of rows that should not be skipped - let mut total_select = 0; - // track the total number of pages that should be skipped - let mut total_pages_skip = 0; - // track the total number of pages that should not be skipped - let mut total_pages_select = 0; // track pages for which page-index pruning was skipped because the // containing row group was already proven fully matched by statistics let mut total_pages_skipped_by_fully_matched = 0; @@ -283,17 +247,12 @@ impl PagePruningAccessPlanFilter { let mut guaranteed_rows = 0; // for each row group specified in the access plan - let row_group_indexes = access_plan.row_group_indexes(); - // Page index sets, reused across row groups - let mut matched_pages_in_group: HashSet = HashSet::new(); - let mut matched_pages_indexes: HashSet = HashSet::new(); - for row_group_index in row_group_indexes { + for row_group_index in access_plan.row_group_indexes() { // Skip page pruning for fully matched row groups: all rows are // known to satisfy the predicate, so page-level pruning is wasted work. if access_plan.is_fully_matched(row_group_index) { - let page_count = - fully_matched_page_count(row_group_index, parquet_metadata); - total_pages_skipped_by_fully_matched += page_count; + total_pages_skipped_by_fully_matched += + pruner.page_count(row_group_index); guaranteed_rows += selected_rows_in_access( &access_plan.inner()[row_group_index], &groups[row_group_index], @@ -301,146 +260,29 @@ impl PagePruningAccessPlanFilter { continue; } - // The selection for this particular row group - let mut overall_selection = None; - - let total_pages_in_group = parquet_metadata - .page_index() - .and_then(|page_index| page_index.offset_index(row_group_index, 0)) - .map_or(0, |offset_index| offset_index.page_locations().len()); - // stores the indexes of the matched pages - matched_pages_in_group.clear(); - matched_pages_in_group.extend(0..total_pages_in_group); - - for predicate in page_index_predicates { - let selection = prune_pages_for_predicate( - row_group_index, - predicate, - arrow_schema, - parquet_schema, - parquet_metadata, - file_metrics, - ); - let Some((selection, pages)) = selection else { - trace!("No pages pruned in prune_pages_in_one_row_group"); - continue; - }; - - debug!( - "Use filter and page index to create RowSelection {:?} from predicate: {:?}", - selection, - predicate.predicate_expr(), - ); - - matched_pages_indexes.clear(); - matched_pages_indexes - .extend(pages.into_iter().enumerate().filter(|x| x.1).map(|x| x.0)); - matched_pages_in_group.retain(|x| matched_pages_indexes.contains(x)); - - overall_selection = update_selection(overall_selection, selection); - - // if the overall selection has ruled out all rows, no need to - // continue with the other predicates - let selects_any = overall_selection - .as_ref() - .map(|selection| selection.selects_any()) - .unwrap_or(true); - - if !selects_any { - break; - } - } - - if let Some(overall_selection) = overall_selection { - let rows_selected = overall_selection.row_count(); - if rows_selected > 0 { - let rows_skipped = overall_selection.skipped_row_count(); - trace!( - "Overall selection from predicate skipped {rows_skipped}, selected {rows_selected}: {overall_selection:?}" - ); - total_skip += rows_skipped; - total_select += rows_selected; - access_plan.scan_selection(row_group_index, overall_selection) - } else { - // Selection skips all rows, so skip the entire row group - let rows_skipped = groups[row_group_index].num_rows() as usize; - access_plan.skip(row_group_index); - total_skip += rows_skipped; - trace!( - "Overall selection from predicate is empty, \ - skipping all {rows_skipped} rows in row group {row_group_index}" - ); - } - } else { - total_select += - parquet_metadata.row_group(row_group_index).num_rows() as usize; - } + let selection = pruner.prune_row_group(row_group_index, &self.predicates); + pruner.apply_selection(&mut access_plan, row_group_index, selection); if guaranteed_rows < limit.unwrap_or(0) && access_plan.should_scan(row_group_index) && let Some(inverted_predicates) = &inverted_predicates + && let Some(selections) = fully_matched_page_selections.as_mut() + && let Some(selection) = + pruner.fully_matched_selection(row_group_index, inverted_predicates) { - let mut fully_matched_selection = None; - let mut complete = true; - - for predicate in inverted_predicates { - let Some((selection, _)) = prune_pages_for_predicate( - row_group_index, - predicate, - arrow_schema, - parquet_schema, - parquet_metadata, - file_metrics, - ) else { - complete = false; - break; - }; - - fully_matched_selection = update_selection( - fully_matched_selection, - complement_selection(selection), - ); - - // An empty intersection cannot gain rows from later conjuncts. - if !fully_matched_selection - .as_ref() - .is_some_and(|selection| selection.selects_any()) - { - break; + guaranteed_rows += match &access_plan.inner()[row_group_index] { + RowGroupAccess::Skip => 0, + RowGroupAccess::Scan => selection.row_count(), + RowGroupAccess::Selection(existing) => { + existing.intersection(&selection).row_count() } - } - - if complete - && let Some(selections) = fully_matched_page_selections.as_mut() - && let Some(selection) = fully_matched_selection - { - guaranteed_rows += match &access_plan.inner()[row_group_index] { - RowGroupAccess::Skip => 0, - RowGroupAccess::Scan => selection.row_count(), - RowGroupAccess::Selection(existing) => { - existing.intersection(&selection).row_count() - } - }; - selections[row_group_index] = Some(selection); - } + }; + selections[row_group_index] = Some(selection); } - - let pages_matched = matched_pages_in_group.len(); - total_pages_select += pages_matched; - total_pages_skip += total_pages_in_group - pages_matched; } - file_metrics.page_index_rows_pruned.add_pruned(total_skip); - file_metrics - .page_index_rows_pruned - .add_matched(total_select); - file_metrics - .page_index_pages_pruned - .add_pruned(total_pages_skip); - file_metrics - .page_index_pages_pruned - .add_matched(total_pages_select); + pruner.counts.add_to(file_metrics); let mut limit_pruned_rows = 0; if let Some(limit) = limit @@ -467,6 +309,24 @@ impl PagePruningAccessPlanFilter { ) } + /// Returns the inverse of each predicate, see + /// [`PruningPredicateBuilder::try_build_inverse`]. Returns `None` if page + /// pruning cannot use the inverse of every predicate. + fn inverted_predicates(&self) -> Option> { + self.predicates + .iter() + .map(|predicate| { + let inverted = PruningPredicateBuilder::new() + .with_file_schema(Arc::clone(predicate.schema())) + .with_max_in_list_size(predicate.max_in_list_size()) + .try_build_inverse(Arc::clone(predicate.orig_expr())) + .ok() + .flatten()?; + single_column(&inverted).is_some().then_some(inverted) + }) + .collect() + } + /// Returns the number of filters in the [`PagePruningAccessPlanFilter`] pub fn filter_number(&self) -> usize { self.predicates.len() @@ -594,32 +454,233 @@ fn selected_rows_in_access(access: &RowGroupAccess, group: &RowGroupMetaData) -> } } -/// Returns the number of pages for which page-index pruning is skipped because -/// the containing row group is fully matched by row-group statistics. -fn fully_matched_page_count( - row_group_index: usize, - parquet_metadata: &ParquetMetaData, -) -> usize { - parquet_metadata - .page_index() - .and_then(|page_index| page_index.offset_index(row_group_index, 0)) - .map_or(0, |offset_index| offset_index.page_locations().len()) +/// The rows and pages that one pass of page pruning counts. +#[derive(Debug, Default)] +struct PagePruningCounts { + /// Rows that should be skipped + rows_pruned: usize, + /// Rows that should not be skipped + rows_matched: usize, + /// Pages that should be skipped + pages_pruned: usize, + /// Pages that should not be skipped + pages_matched: usize, } -fn prune_pages_for_predicate( - row_group_index: usize, - predicate: &PruningPredicate, - arrow_schema: &Schema, - parquet_schema: &SchemaDescriptor, - parquet_metadata: &ParquetMetaData, - metrics: &ParquetFileMetrics, -) -> Option<(RowSelection, Vec)> { - #[cfg(test)] - tests::PAGE_PREDICATE_CALLS.set(tests::PAGE_PREDICATE_CALLS.get() + 1); +impl PagePruningCounts { + fn add_to(&self, file_metrics: &ParquetFileMetrics) { + let rows = &file_metrics.page_index_rows_pruned; + rows.add_pruned(self.rows_pruned); + rows.add_matched(self.rows_matched); + let pages = &file_metrics.page_index_pages_pruned; + pages.add_pruned(self.pages_pruned); + pages.add_matched(self.pages_matched); + } +} + +/// One pass of page pruning over the row groups of one file. +/// +/// It holds the file that the pass reads and the counts that the pass +/// reports. +struct PagePruner<'a> { + arrow_schema: &'a Schema, + parquet_schema: &'a SchemaDescriptor, + parquet_metadata: &'a ParquetMetaData, + file_metrics: &'a ParquetFileMetrics, + counts: PagePruningCounts, + /// The pages of the current row group that every predicate matches. + /// The pruner reuses the allocation across row groups. + matched_pages_in_group: HashSet, + /// The pages of the current row group that one predicate matches. + /// The pruner reuses the allocation across row groups. + matched_pages_indexes: HashSet, +} - let column = single_column(predicate)?; - let converter = - match StatisticsConverter::try_new(column.name(), arrow_schema, parquet_schema) { +impl<'a> PagePruner<'a> { + fn new( + arrow_schema: &'a Schema, + parquet_schema: &'a SchemaDescriptor, + parquet_metadata: &'a ParquetMetaData, + file_metrics: &'a ParquetFileMetrics, + ) -> Self { + Self { + arrow_schema, + parquet_schema, + parquet_metadata, + file_metrics, + counts: PagePruningCounts::default(), + matched_pages_in_group: HashSet::new(), + matched_pages_indexes: HashSet::new(), + } + } + + /// Returns true if the file has the column index and the offset index of + /// every column. Page pruning needs both. + fn has_complete_page_index(&self) -> bool { + let page_index = self.parquet_metadata.page_index(); + let complete = page_index.is_some_and(|page_index| page_index.is_complete()); + if !complete { + debug!( + "Can not prune pages due to lack of indexes. Have offset: {}, column index: {}", + page_index.is_some_and(|page_index| page_index.has_offset_indexes()), + page_index.is_some_and(|page_index| page_index.has_column_indexes()) + ); + } + complete + } + + /// Returns the number of pages of the first column of the row group. + /// Page pruning reports this number as the pages of the row group. + fn page_count(&self, row_group_index: usize) -> usize { + self.parquet_metadata + .page_index() + .and_then(|page_index| page_index.offset_index(row_group_index, 0)) + .map_or(0, |offset_index| offset_index.page_locations().len()) + } + + /// Applies each predicate to the pages of one row group, and counts the + /// pages that every predicate matches. + /// + /// Returns the rows that every predicate can match. Returns `None` if no + /// predicate can prune the row group. + fn prune_row_group( + &mut self, + row_group_index: usize, + predicates: &[PruningPredicate], + ) -> Option { + // The selection for this particular row group + let mut overall_selection = None; + + let total_pages_in_group = self.page_count(row_group_index); + // stores the indexes of the matched pages + self.matched_pages_in_group.clear(); + self.matched_pages_in_group.extend(0..total_pages_in_group); + + for predicate in predicates { + let selection = self.prune_pages_for_predicate(row_group_index, predicate); + + let Some((selection, pages)) = selection else { + trace!("No pages pruned in prune_pages_in_one_row_group"); + continue; + }; + + debug!( + "Use filter and page index to create RowSelection {:?} from predicate: {:?}", + selection, + predicate.predicate_expr(), + ); + + self.matched_pages_indexes.clear(); + self.matched_pages_indexes + .extend(pages.into_iter().enumerate().filter(|x| x.1).map(|x| x.0)); + let matched_pages_indexes = &self.matched_pages_indexes; + self.matched_pages_in_group + .retain(|x| matched_pages_indexes.contains(x)); + + overall_selection = update_selection(overall_selection, selection); + + // if the overall selection has ruled out all rows, no need to + // continue with the other predicates + let selects_any = overall_selection + .as_ref() + .map(|selection| selection.selects_any()) + .unwrap_or(true); + + if !selects_any { + break; + } + } + + let pages_matched = self.matched_pages_in_group.len(); + self.counts.pages_matched += pages_matched; + self.counts.pages_pruned += total_pages_in_group - pages_matched; + + overall_selection + } + + /// Records the result of [`Self::prune_row_group`] in the access plan, and + /// counts the rows that the selection skips and selects. + fn apply_selection( + &mut self, + access_plan: &mut ParquetAccessPlan, + row_group_index: usize, + selection: Option, + ) { + let rows_in_group = + self.parquet_metadata.row_group(row_group_index).num_rows() as usize; + let Some(selection) = selection else { + self.counts.rows_matched += rows_in_group; + return; + }; + + let rows_selected = selection.row_count(); + if rows_selected > 0 { + let rows_skipped = selection.skipped_row_count(); + trace!( + "Overall selection from predicate skipped {rows_skipped}, selected {rows_selected}: {selection:?}" + ); + self.counts.rows_pruned += rows_skipped; + self.counts.rows_matched += rows_selected; + access_plan.scan_selection(row_group_index, selection) + } else { + // Selection skips all rows, so skip the entire row group + access_plan.skip(row_group_index); + self.counts.rows_pruned += rows_in_group; + trace!( + "Overall selection from predicate is empty, \ + skipping all {rows_in_group} rows in row group {row_group_index}" + ); + } + } + + /// Returns the rows of one row group that pass every predicate for + /// certain. `inverted_predicates` holds the inverse of each predicate. + /// + /// Returns `None` if a page index cannot evaluate one of the inverses. + fn fully_matched_selection( + &self, + row_group_index: usize, + inverted_predicates: &[PruningPredicate], + ) -> Option { + let mut fully_matched_selection = None; + + for predicate in inverted_predicates { + let (selection, _) = + self.prune_pages_for_predicate(row_group_index, predicate)?; + + fully_matched_selection = update_selection( + fully_matched_selection, + complement_selection(selection), + ); + + // An empty intersection cannot gain rows from later conjuncts. + if !fully_matched_selection + .as_ref() + .is_some_and(|selection| selection.selects_any()) + { + break; + } + } + + fully_matched_selection + } + + /// Applies one predicate to the pages of the column that it reads, see + /// [`prune_pages_in_one_row_group`]. + fn prune_pages_for_predicate( + &self, + row_group_index: usize, + predicate: &PruningPredicate, + ) -> Option<(RowSelection, Vec)> { + #[cfg(test)] + tests::PAGE_PREDICATE_CALLS.set(tests::PAGE_PREDICATE_CALLS.get() + 1); + + let column = single_column(predicate)?; + let converter = match StatisticsConverter::try_new( + column.name(), + self.arrow_schema, + self.parquet_schema, + ) { Ok(converter) => converter, Err(e) => { debug!( @@ -630,13 +691,14 @@ fn prune_pages_for_predicate( } }; - prune_pages_in_one_row_group( - row_group_index, - predicate, - converter, - parquet_metadata, - metrics, - ) + prune_pages_in_one_row_group( + row_group_index, + predicate, + converter, + self.parquet_metadata, + self.file_metrics, + ) + } } /// Returns a [`RowSelection`] for the rows in this row group to scan, in addition to a vec of