JingsongLi commented on code in PR #1469: URL: https://github.com/apache/paimon-rust/pull/1469#discussion_r4716526489
########## crates/paimon/src/table/data_evolution_reader/candidate_ranges.rs: ########## @@ -0,0 +1,292 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +use super::{DataEvolutionReader, FieldSource, SourcePlan}; +use crate::arrow::filtering::build_field_mapping; +use crate::arrow::format::parquet::{MergedReadMetadata, ParquetFormatReader, SelectedRowsFilter}; +use crate::predicate_stats::stats_evolution_is_safe; +use crate::spec::{CoreOptions, DataFileMeta, DataType, Predicate}; +use crate::table::data_file_reader::{open_file_reader, to_local_row_ranges}; +use crate::table::row_id_predicate::intersect_sorted_ranges; +use crate::table::row_sidecar; +use crate::table::RowRange; +use crate::{DataSplit, Error}; +use parquet::arrow::arrow_reader::RowSelection; +use std::collections::HashSet; + +#[cfg(test)] +#[path = "candidate_ranges_tests.rs"] +mod tests; + +impl DataEvolutionReader { + /// Logical row IDs that may match in the winning providers. An empty list + /// skips the group and `None` leaves its selection unchanged. + pub(super) async fn candidate_ranges( + &self, + split: &DataSplit, + plan: &mut SourcePlan, + selected_ranges: Option<&[RowRange]>, + sidecar_ranges: Option<&[RowRange]>, + ) -> Option<Vec<RowRange>> { + let FieldSource::DataFile { file, .. } = plan.sources.first()? else { + return None; + }; + let (first, last) = file.row_id_range()?; + self.compute_candidate_ranges(split, plan, first, selected_ranges, sidecar_ranges) + .await + .unwrap_or_else(|error| { + log::warn!( + "Parquet statistics pruning failed for row IDs {first}..={last} in {}. Using the original row selection ({error})", + split.bucket_path() + ); + None + }) + } + + async fn compute_candidate_ranges( + &self, + split: &DataSplit, + plan: &mut SourcePlan, + first_row_id: i64, + selected_ranges: Option<&[RowRange]>, + sidecar_ranges: Option<&[RowRange]>, + ) -> crate::Result<Option<Vec<RowRange>>> { + for source in &plan.sources { + if !self.can_use_source_stats(source, sidecar_ranges)? { + return Ok(None); + } + } + let reader = ParquetFormatReader::with_options(&self.table_options, None)?; + let selected_span = selected_ranges.and_then(|ranges| { + let first = ranges.first()?.from() - first_row_id; + let last = ranges.last()?.to() - first_row_id; + Some(RowRange::new(first, last)) + }); + let mut candidates: Option<Vec<RowRange>> = None; + let mut deferred_sources = Vec::new(); + let mut loaded_metadata = Vec::new(); + for source in &mut plan.sources { + let FieldSource::DataFile { + file, + data_fields, + read_fields, + parquet_metadata, + } = source + else { + return Ok(None); + }; + if read_fields.is_empty() { + continue; + } + let file_fields = data_fields.as_deref().unwrap_or(&self.table_fields); + let winning_ids: HashSet<_> = read_fields.iter().map(|field| field.id()).collect(); + let mut mapping = build_field_mapping(&self.table_fields, file_fields); + for (index, field) in mapping.iter_mut().zip(&self.table_fields) { + *index = index.filter(|&i| { + winning_ids.contains(&field.id()) + && supports_stats(field.data_type()) + && !self.partition_fields.iter().any(|p| p.id() == field.id()) + && stats_evolution_is_safe(file_fields[i].data_type(), field.data_type()) Review Comment: **[P1] Use the effective read type when deciding whether bounds can prune.** I read a merged Parquet split containing `rating INT = 2117` through `with_read_type` with the same field ID projected as `TINYINT`, and applied the table predicate `rating = 69`. With merged statistics disabled, the normal reader narrows 2117 to 69 and returns row 2117. With the new pruning enabled, the scan returns no rows. The statistics check compares the physical field with the table field and skips the non-order-preserving conversion to the actual provider read type. Bypass stats for predicates on a field whose effective read conversion can change the comparison, and cover explicit read types in the merged-split regression. ########## crates/paimon/src/arrow/format/parquet.rs: ########## @@ -88,9 +130,120 @@ impl ParquetFormatReader { page_index_enabled: core_options.parquet_filter_column_index_enabled()?, // Format-table files may be replaced in place. metadata_cache_enabled: !core_options.is_format_table(), + merged_metadata: None, + }) + } + + pub(crate) fn with_merged_read_metadata(mut self, metadata: MergedReadMetadata) -> Self { + self.merged_metadata = Some(metadata); + self + } + + fn reader_options(&self, has_predicate: bool, has_selection: bool) -> ArrowReaderOptions { + let mut options = ArrowReaderOptions::new(); + if self.page_index_enabled { + if has_predicate { + options = options.with_column_index_policy(PageIndexPolicy::Optional); + } + if has_predicate || has_selection { + options = options.with_offset_index_policy(PageIndexPolicy::Optional); + } + } + options + } + + pub(crate) async fn load_merged_read_metadata( + &self, + reader: Box<dyn FileRead>, + file_size: u64, + selected_filter: Option<SelectedRowsFilter<'_>>, + ) -> parquet::errors::Result<MergedReadMetadata> { + let mut reader = ArrowFileReader::new(file_size, reader.into()) + .with_metadata_cache_enabled(self.metadata_cache_enabled); + let mut fetch = ParquetMetadataFetch::new(&mut reader); + let indexed_selection = selected_filter.as_ref().filter(|_| self.page_index_enabled); + let row_group_match = match indexed_selection { + Some(filter) => selected_row_group_match(fetch.load(None).await?.as_ref(), filter), + None => RowGroupMatch::Unknown, + }; + let use_statistics = match row_group_match { + RowGroupMatch::AllRows => false, + RowGroupMatch::NoRows => true, + // For a single selected row, read its pages with the OffsetIndex and + // let the merged residual filter decide whether the row matches. + RowGroupMatch::Unknown => { + !indexed_selection.is_some_and(|filter| filter.span.from() == filter.span.to()) Review Comment: **[P2] Keep offset-only I/O for a tiny range inside one data page.** On the 100,000-row fixture with 49 rating-provider columns and 64 rows per page, I explicitly selected rows 2117–2118 and filtered `rating >= 2117`. Both rows survived with pruning on and off. The enabled read fetched 3,159,015 bytes versus 1,939,935 bytes, and column-data reads rose from 450 to 3,595 bytes. The inconclusive-footer fallback only handles exactly one row, even when both selected rows fit on one page. Consider the selection and index costs before fetching the ColumnIndex, and let the residual check a tiny selected range. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
