SteNicholas commented on code in PR #1469:
URL: https://github.com/apache/paimon-rust/pull/1469#discussion_r4657518211


##########
crates/paimon/src/table/data_evolution_reader/candidate_ranges.rs:
##########
@@ -0,0 +1,268 @@
+// 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::ParquetFormatReader;
+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::{ArrowReaderMetadata, 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 mut candidates: Option<Vec<RowRange>> = None;
+        let mut unfiltered_sources = 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())
+                });
+            }
+            // Remap a whole conjunct so an OR or NOT spanning providers stays 
residual.
+            let predicates: Vec<_> = self
+                .predicates
+                .iter()
+                .filter_map(|p| p.remap_field_index(&mapping))
+                .filter(|p| !matches!(p, Predicate::AlwaysTrue))
+                .collect();
+            if predicates.is_empty() {
+                unfiltered_sources.push((file, parquet_metadata));
+                continue;
+            }
+            let metadata = self
+                .cache_source_metadata(split, file, &reader, parquet_metadata)
+                .await?;
+            let selection = reader.candidate_row_selection(metadata, 
predicates, file_fields);
+            if let Some(selection) = selection {
+                let ranges = absolute_row_ranges(first_row_id, &selection);
+                let live = match candidates.as_deref().or(selected_ranges) {
+                    Some(previous) => intersect_sorted_ranges(previous, 
&ranges),
+                    None => ranges,
+                };
+                if live.is_empty() {
+                    return Ok(Some(live));
+                }
+                candidates = Some(live);
+            }
+        }
+        let Some(candidates) = candidates else {
+            return Ok(None);

Review Comment:
   Fixed in 
[`05bb9b71`](https://github.com/apache/paimon-rust/pull/1469/commits/05bb9b7106c788b20fed7b92c2fbe091fcd4e1be).
 The merged reader keeps the cached `OffsetIndex` when statistics rule out no 
rows, so the caller's original sparse selection still reads just the needed 
page.
   
   The single-row regression applies `id >= 0` to `_ROW_ID = 102117`. Both 
settings return `(id=2117, _ROW_ID=102117)` with identical column-data I/O. 
[Sparse-read 
regression](https://github.com/SteNicholas/paimon-rust/blob/05bb9b7106c788b20fed7b92c2fbe091fcd4e1be/crates/paimon/src/table/data_evolution_reader/candidate_ranges_tests.rs#L433)
   
   When statistics do produce candidates, projected page boundaries still need 
independent row counts, even if intersecting with the caller's selection leaves 
it unchanged. [Projected page-boundary 
regression](https://github.com/SteNicholas/paimon-rust/blob/05bb9b7106c788b20fed7b92c2fbe091fcd4e1be/crates/paimon/src/table/data_evolution_reader/candidate_ranges_tests.rs#L923)
   



-- 
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]

Reply via email to