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


##########
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:
   **[P2] Preserve the `OffsetIndex` when statistics produce no candidate 
ranges**
   
   I reproduced this on `789b8d6c` with a merged Data Evolution split. Select 
only `_ROW_ID = 102117` through the caller's row range, project `id` and 
`_ROW_ID`, and apply `id >= 0`, which matches every row in the group. The 
Parquet provider has a valid `OffsetIndex` and omits page row-count histograms 
for the `NOT NULL` `id` column.
   
   Both settings of `data-evolution.merged-read.stats-pushdown.enabled` return 
`(id=2117, _ROW_ID=102117)`. Column data I/O rises from **167 B with pruning 
disabled** (one 37-row page) to **3,312 B with pruning enabled** (the full 
733-row column chunk).
   
   When candidate planning returns `None` here, decoding still reuses metadata 
with the `OffsetIndex` removed. Please retain usable offsets on this fallback. 
Keep independent page-boundary validation when statistics produce candidates, 
even if their intersection leaves the caller's selection unchanged.



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