From 5bc536d6a2c4e07a031f09aec302ed251dece525 Mon Sep 17 00:00:00 2001 From: "linchen.23" Date: Tue, 1 Dec 2026 17:20:45 +0800 Subject: [PATCH] feat(read): prune Parquet row groups for multi-file data evolution Use the newest file for each predicate field and intersect candidate row ID ranges before merging. Cover cross-file predicates and residual filtering in the Data Evolution regression. --- include/paimon/reader/file_batch_reader.h | 22 ++ src/paimon/common/reader/batch_reader.cpp | 4 + .../common/reader/concat_batch_reader.cpp | 7 +- .../common/reader/concat_batch_reader.h | 4 +- .../reader/delegating_prefetch_reader.h | 16 +- .../prefetch_file_batch_reader_impl.cpp | 38 ++- .../reader/prefetch_file_batch_reader_impl.h | 4 + .../core/operation/abstract_split_read.cpp | 35 +- .../core/operation/abstract_split_read.h | 14 +- .../operation/data_evolution_split_read.cpp | 180 +++++++--- .../operation/data_evolution_split_read.h | 33 +- .../data_evolution_split_read_test.cpp | 38 +-- src/paimon/core/utils/field_mapping.h | 6 +- .../parquet/parquet_file_batch_reader.cpp | 119 ++++++- .../parquet/parquet_file_batch_reader.h | 9 +- test/inte/data_evolution_table_test.cpp | 320 +++++++++++++++++- 16 files changed, 744 insertions(+), 105 deletions(-) diff --git a/include/paimon/reader/file_batch_reader.h b/include/paimon/reader/file_batch_reader.h index 32f2508c2..685589d0c 100644 --- a/include/paimon/reader/file_batch_reader.h +++ b/include/paimon/reader/file_batch_reader.h @@ -20,11 +20,13 @@ #pragma once #include +#include #include #include #include "paimon/predicate/predicate.h" #include "paimon/reader/batch_reader.h" +#include "paimon/utils/range.h" #include "paimon/utils/roaring_bitmap32.h" namespace paimon { /// The batch reader for a single file supports returning the line number of the last batch read for @@ -85,4 +87,24 @@ class PAIMON_EXPORT FileBatchReader : public BatchReader { virtual void Warmup() {} }; +/// Optional statistics filtering interface for an open file reader. +class PAIMON_EXPORT RowGroupFilter { + public: + virtual ~RowGroupFilter(); + + /// Uses metadata to find sorted, disjoint, inclusive file-local candidate ranges without + /// configuring the reader or reading column data. The predicate uses physical column names. + /// The expected row count comes from the file manifest. An empty vector means no rows can + /// match, and nullopt means no narrower selection is available. The caller must still + /// evaluate the predicate on candidate rows. + virtual Result>> GetRowGroupCandidateRanges( + int64_t expected_row_count, const std::shared_ptr& predicate) const = 0; + + /// Records metadata I/O for an open reader discarded before scanning rows. Prefetch wrappers + /// count row groups once and may supply the bytes read through a shared cache. + virtual std::shared_ptr GetSkippedReaderMetrics( + bool count_row_groups = true, + std::optional storage_read_bytes = std::nullopt) const = 0; +}; + } // namespace paimon diff --git a/src/paimon/common/reader/batch_reader.cpp b/src/paimon/common/reader/batch_reader.cpp index 1a1734d25..c4f8f30b4 100644 --- a/src/paimon/common/reader/batch_reader.cpp +++ b/src/paimon/common/reader/batch_reader.cpp @@ -21,8 +21,12 @@ #include "arrow/c/abi.h" #include "paimon/common/reader/reader_utils.h" +#include "paimon/reader/file_batch_reader.h" namespace paimon { + +RowGroupFilter::~RowGroupFilter() = default; + BatchReader::ReadBatch BatchReader::MakeEofBatch() { return std::make_pair(std::unique_ptr(), std::unique_ptr()); } diff --git a/src/paimon/common/reader/concat_batch_reader.cpp b/src/paimon/common/reader/concat_batch_reader.cpp index 2200dd519..abae0c35a 100644 --- a/src/paimon/common/reader/concat_batch_reader.cpp +++ b/src/paimon/common/reader/concat_batch_reader.cpp @@ -49,8 +49,11 @@ static auto CatchPreparationErrors(Func&& func) -> decltype(func()) { } ConcatBatchReader::ConcatBatchReader(std::vector>&& readers, - const std::shared_ptr& arrow_pool) - : arrow_pool_(arrow_pool), finished_reader_metrics_(std::make_shared()) { + const std::shared_ptr& arrow_pool, + std::shared_ptr finished_reader_metrics) + : arrow_pool_(arrow_pool), + finished_reader_metrics_(finished_reader_metrics ? std::move(finished_reader_metrics) + : std::make_shared()) { for (auto& reader : readers) { readers_.emplace_back(); readers_.back().file_reader = dynamic_cast(reader.get()); diff --git a/src/paimon/common/reader/concat_batch_reader.h b/src/paimon/common/reader/concat_batch_reader.h index 5e5474f3b..ce67f7035 100644 --- a/src/paimon/common/reader/concat_batch_reader.h +++ b/src/paimon/common/reader/concat_batch_reader.h @@ -58,8 +58,10 @@ class ConcatBatchReader : public BatchReader { const std::shared_ptr& arrow_pool, const std::shared_ptr& build_executor); + /// Can start with metrics from readers already closed during preparation. ConcatBatchReader(std::vector>&& readers, - const std::shared_ptr& arrow_pool); + const std::shared_ptr& arrow_pool, + std::shared_ptr finished_reader_metrics = nullptr); ~ConcatBatchReader() override; Result NextBatch() override; diff --git a/src/paimon/common/reader/delegating_prefetch_reader.h b/src/paimon/common/reader/delegating_prefetch_reader.h index b91c04187..72b9b0104 100644 --- a/src/paimon/common/reader/delegating_prefetch_reader.h +++ b/src/paimon/common/reader/delegating_prefetch_reader.h @@ -30,7 +30,7 @@ namespace paimon { -class DelegatingPrefetchReader : public FileBatchReader { +class DelegatingPrefetchReader : public FileBatchReader, public RowGroupFilter { public: explicit DelegatingPrefetchReader(std::unique_ptr prefetch_reader) : prefetch_reader_(std::move(prefetch_reader)) {} @@ -52,6 +52,20 @@ class DelegatingPrefetchReader : public FileBatchReader { return GetReader()->GetFileSchema(); } + Result>> GetRowGroupCandidateRanges( + int64_t expected_row_count, const std::shared_ptr& predicate) const override { + if (const auto* filter = + dynamic_cast(prefetch_reader_->GetFirstReader())) { + return filter->GetRowGroupCandidateRanges(expected_row_count, predicate); + } + return std::optional>(); + } + + std::shared_ptr GetSkippedReaderMetrics( + bool count_row_groups, std::optional storage_read_bytes) const override { + return prefetch_reader_->GetSkippedReaderMetrics(count_row_groups, storage_read_bytes); + } + Status SetReadSchema(::ArrowSchema* read_schema, const std::shared_ptr& predicate, const std::optional& selection_bitmap) override { return prefetch_reader_->SetReadSchema(read_schema, predicate, selection_bitmap); diff --git a/src/paimon/common/reader/prefetch_file_batch_reader_impl.cpp b/src/paimon/common/reader/prefetch_file_batch_reader_impl.cpp index b3d89b2f7..57a5403a3 100644 --- a/src/paimon/common/reader/prefetch_file_batch_reader_impl.cpp +++ b/src/paimon/common/reader/prefetch_file_batch_reader_impl.cpp @@ -39,6 +39,7 @@ #include "paimon/format/reader_builder.h" #include "paimon/fs/file_system.h" #include "paimon/memory/memory_pool.h" +#include "paimon/reader/file_batch_reader.h" namespace arrow { class Schema; @@ -961,6 +962,40 @@ std::shared_ptr PrefetchFileBatchReaderImpl::GetReaderMetrics() const { result->Merge(readers_[0]->GetReaderMetrics()); } + CollectPrefetchMetrics(result); + return result; +} + +std::shared_ptr PrefetchFileBatchReaderImpl::GetSkippedReaderMetrics( + bool count_row_groups, std::optional storage_read_bytes) const { + const auto* first_filter = dynamic_cast(GetFirstReader()); + if (first_filter == nullptr) { + return GetReaderMetrics(); + } + + auto result = std::make_shared(); + CollectPrefetchMetrics(result); + if (!storage_read_bytes && cache_) { + // Only footer reads have run. The cache counters separate storage fetches from + // requests served by the cache and from misses that fell back to a direct read. + storage_read_bytes = result->GetCounter(ReadAheadCacheMetrics::IO_BYTES).value() + + result->GetCounter(ReadAheadCacheMetrics::READ_MISS_BYTES).value(); + } + if (storage_read_bytes) { + result->Merge(first_filter->GetSkippedReaderMetrics(count_row_groups, storage_read_bytes)); + } else { + result->Merge(first_filter->GetSkippedReaderMetrics(count_row_groups)); + for (size_t i = 1; i < readers_.size(); ++i) { + if (const auto* filter = dynamic_cast(readers_[i].get())) { + result->Merge(filter->GetSkippedReaderMetrics(/*count_row_groups=*/false)); + } + } + } + return result; +} + +void PrefetchFileBatchReaderImpl::CollectPrefetchMetrics( + const std::shared_ptr& result) const { auto set_prefetch_counter = [&result](const char* name, const std::atomic& value) { result->SetCounter(name, value.load(kMetricsMemoryOrder)); }; @@ -996,7 +1031,7 @@ std::shared_ptr PrefetchFileBatchReaderImpl::GetReaderMetrics() const { } if (!io_metrics_) { - return result; + return; } auto set_io_counter = [&result](const char* name, const std::atomic& value) { result->SetCounter(name, value.load(kMetricsMemoryOrder)); @@ -1016,7 +1051,6 @@ std::shared_ptr PrefetchFileBatchReaderImpl::GetReaderMetrics() const { set_io_counter(PrefetchIoMetrics::ASYNC_LATENCY_SUM_US, io_metrics_->async_latency_sum_us); result->SetGauge(PrefetchIoMetrics::ASYNC_PENDING, static_cast(io_metrics_->async_pending.load(kMetricsMemoryOrder))); - return result; } Result> PrefetchFileBatchReaderImpl::GetFileSchema() const { diff --git a/src/paimon/common/reader/prefetch_file_batch_reader_impl.h b/src/paimon/common/reader/prefetch_file_batch_reader_impl.h index 164cf6c6b..5012f5ccf 100644 --- a/src/paimon/common/reader/prefetch_file_batch_reader_impl.h +++ b/src/paimon/common/reader/prefetch_file_batch_reader_impl.h @@ -80,6 +80,8 @@ class PrefetchFileBatchReaderImpl : public PrefetchFileBatchReader { Result NextBatchWithBitmap() override; std::shared_ptr GetReaderMetrics() const override; + std::shared_ptr GetSkippedReaderMetrics( + bool count_row_groups, std::optional storage_read_bytes) const; Result> GetFileSchema() const override; Status SetReadSchema(::ArrowSchema* read_schema, const std::shared_ptr& predicate, @@ -127,6 +129,8 @@ class PrefetchFileBatchReaderImpl : public PrefetchFileBatchReader { const std::shared_ptr& io_metrics, WarmupLevel warmup_level, const std::shared_ptr& arrow_pool); + void CollectPrefetchMetrics(const std::shared_ptr& result) const; + Status CleanUp(); void Workloop(); /// Starts the background prefetch thread if it is not running yet. The first read does this diff --git a/src/paimon/core/operation/abstract_split_read.cpp b/src/paimon/core/operation/abstract_split_read.cpp index f14e2cede..73c9b36fb 100644 --- a/src/paimon/core/operation/abstract_split_read.cpp +++ b/src/paimon/core/operation/abstract_split_read.cpp @@ -415,13 +415,38 @@ Result> AbstractSplitRead::CreateFileBatchReade options_.GetFileSystem(), executor_, pool_, arrow_pool_); } +Result> AbstractSplitRead::OpenDataFileReader( + const std::shared_ptr& file, + const DataFilePathFactory& data_file_path_factory) const { + PAIMON_ASSIGN_OR_RAISE(std::string format_identifier, file->FileFormat()); + PAIMON_ASSIGN_OR_RAISE(std::unique_ptr reader_builder, + PrepareReaderBuilder(format_identifier, /*extra_format_options=*/{})); + return CreateFileBatchReader(format_identifier, data_file_path_factory.ToPath(file), + file->file_size, std::move(reader_builder)); +} + +Result> AbstractSplitRead::ConfigureOpenedFileReader( + const BinaryRow& partition, const std::shared_ptr& file, + const std::shared_ptr& read_schema, DeletionVector::Factory dv_factory, + const std::optional>& row_ranges, + const std::shared_ptr& data_file_path_factory, + std::unique_ptr file_reader) const { + PAIMON_ASSIGN_OR_RAISE(std::unique_ptr field_mapping_builder, + FieldMappingBuilder::Create(read_schema, context_->GetPartitionKeys(), + /*predicate=*/nullptr)); + return CreateFieldMappingReader(data_file_path_factory->ToPath(file), file, partition, + /*reader_builder=*/nullptr, field_mapping_builder.get(), + dv_factory, row_ranges, data_file_path_factory, + /*exact_selection=*/nullptr, std::move(file_reader)); +} + Result> AbstractSplitRead::CreateFieldMappingReader( const std::string& data_file_path, const std::shared_ptr& file_meta, const BinaryRow& partition, std::unique_ptr reader_builder, const FieldMappingBuilder* field_mapping_builder, DeletionVector::Factory dv_factory, const std::optional>& row_ranges, const std::shared_ptr& data_file_path_factory, - const RoaringBitmap32* exact_selection) const { + const RoaringBitmap32* exact_selection, std::unique_ptr file_reader) const { std::shared_ptr data_schema; if (file_meta->schema_id == context_->GetTableSchema()->Id()) { data_schema = context_->GetTableSchema(); @@ -456,9 +481,11 @@ Result> AbstractSplitRead::CreateFieldMappingRe field_mapping->non_partition_info.non_partition_data_schema); PAIMON_ASSIGN_OR_RAISE(std::string file_format_identifier, file_meta->FileFormat()); - PAIMON_ASSIGN_OR_RAISE(std::unique_ptr file_reader, - CreateFileBatchReader(file_format_identifier, data_file_path, - file_meta->file_size, std::move(reader_builder))); + if (!file_reader) { + PAIMON_ASSIGN_OR_RAISE( + file_reader, CreateFileBatchReader(file_format_identifier, data_file_path, + file_meta->file_size, std::move(reader_builder))); + } if (VectorFileBatchReader::ContainsVector(read_schema)) { file_reader = std::make_unique(std::move(file_reader), arrow_pool_); } diff --git a/src/paimon/core/operation/abstract_split_read.h b/src/paimon/core/operation/abstract_split_read.h index 70ea02c0c..f0325d280 100644 --- a/src/paimon/core/operation/abstract_split_read.h +++ b/src/paimon/core/operation/abstract_split_read.h @@ -128,6 +128,17 @@ class AbstractSplitRead : public SplitRead { const std::map& extra_format_options, bool attach_blob_context) const; + Result> OpenDataFileReader( + const std::shared_ptr& file, + const DataFilePathFactory& data_file_path_factory) const; + + Result> ConfigureOpenedFileReader( + const BinaryRow& partition, const std::shared_ptr& file, + const std::shared_ptr& read_schema, DeletionVector::Factory dv_factory, + const std::optional>& row_ranges, + const std::shared_ptr& data_file_path_factory, + std::unique_ptr file_reader) const; + Result> ApplyPredicateFilterIfNeeded( std::unique_ptr&& reader, const std::shared_ptr& predicate) const; @@ -193,7 +204,8 @@ class AbstractSplitRead : public SplitRead { const FieldMappingBuilder* field_mapping_builder, DeletionVector::Factory dv_factory, const std::optional>& row_ranges, const std::shared_ptr& data_file_path_factory, - const RoaringBitmap32* exact_selection) const; + const RoaringBitmap32* exact_selection, + std::unique_ptr opened_reader = nullptr) const; /// The returned field ID set contains MAP fields handled by shredding read plans. It tells /// FieldMappingReader to skip its generic selected-key filtering because the plans have already diff --git a/src/paimon/core/operation/data_evolution_split_read.cpp b/src/paimon/core/operation/data_evolution_split_read.cpp index d13cb9199..bf0178d93 100644 --- a/src/paimon/core/operation/data_evolution_split_read.cpp +++ b/src/paimon/core/operation/data_evolution_split_read.cpp @@ -38,6 +38,7 @@ #include "paimon/common/data/blob_utils.h" #include "paimon/common/data/blob_view_struct.h" #include "paimon/common/file_index/bitmap/apply_bitmap_index_batch_reader.h" +#include "paimon/common/metrics/metrics_impl.h" #include "paimon/common/reader/blob_fallback_batch_reader.h" #include "paimon/common/reader/blob_view_resolving_batch_reader.h" #include "paimon/common/reader/complete_index_score_batch_reader.h" @@ -49,11 +50,13 @@ #include "paimon/common/utils/checked_cast.h" #include "paimon/common/utils/object_utils.h" #include "paimon/common/utils/range_helper.h" +#include "paimon/common/utils/string_utils.h" #include "paimon/common/utils/vector_store_utils.h" #include "paimon/core/core_options.h" #include "paimon/core/deletionvectors/apply_deletion_vector_batch_reader.h" #include "paimon/core/deletionvectors/bitmap_deletion_vector.h" #include "paimon/core/global_index/indexed_split_impl.h" +#include "paimon/core/io/data_file_path_factory.h" #include "paimon/core/io/file_index_evaluator.h" #include "paimon/core/io/file_index_options.h" #include "paimon/core/table/format/lazy_concat_batch_reader.h" @@ -63,6 +66,7 @@ #include "paimon/file_index/bitmap_index_result.h" #include "paimon/file_index/file_index_result.h" #include "paimon/predicate/predicate_utils.h" +#include "paimon/reader/file_batch_reader.h" namespace paimon { namespace { @@ -421,11 +425,29 @@ Result> DataEvolutionSplitRead::InnerCreateReader( MergeRangesAndSort(std::move(metas))); std::vector> sub_readers; + auto finished_reader_metrics = std::make_shared(); + auto close_unused_readers = + [&finished_reader_metrics](const OpenedFileReaders& opened_readers) { + for (const auto& entry : opened_readers) { + const auto& opened = entry.second; + if (opened.ok() && opened.value()) { + const auto& reader = opened.value(); + const auto* filter = dynamic_cast(reader.get()); + auto metrics = + filter ? filter->GetSkippedReaderMetrics() : reader->GetReaderMetrics(); + reader->Close(); + finished_reader_metrics->Merge(metrics); + } + } + }; for (const std::vector>& need_merge_files : split_by_row_id) { - PAIMON_ASSIGN_OR_RAISE(std::optional group_selection, - SelectByFileIndex(push_down_predicate, need_merge_files, read_schema, - row_ranges, data_file_path_factory)); + OpenedFileReaders opened_readers; + PAIMON_ASSIGN_OR_RAISE( + std::optional group_selection, + SelectGroupRows(push_down_predicate, need_merge_files, read_schema, row_ranges, + data_file_path_factory, &opened_readers)); if (group_selection && group_selection->IsEmpty()) { + close_unused_readers(opened_readers); continue; } PAIMON_ASSIGN_OR_RAISE(std::optional group_dv, @@ -437,6 +459,7 @@ Result> DataEvolutionSplitRead::InnerCreateReader( *group_selection, ExcludeDeletedPositions(std::move(*group_selection), group_dv->deletion_vector)); if (group_selection->IsEmpty()) { + close_unused_readers(opened_readers); continue; } } @@ -463,12 +486,13 @@ Result> DataEvolutionSplitRead::InnerCreateReader( std::unique_ptr evolution_reader, group_read.CreateUnionReader(split_impl->Partition(), need_merge_files, row_ranges, data_file_path_factory, group_dv_factory, group_dv, - read_schema)); + read_schema, &opened_readers)); sub_readers.push_back(std::move(evolution_reader)); } + close_unused_readers(opened_readers); } - auto concat_batch_reader = - std::make_unique(std::move(sub_readers), arrow_pool_); + auto concat_batch_reader = std::make_unique( + std::move(sub_readers), arrow_pool_, std::move(finished_reader_metrics)); PAIMON_ASSIGN_OR_RAISE( std::unique_ptr batch_reader, ApplyPredicateFilterIfNeeded(std::move(concat_batch_reader), context_->GetPredicate())); @@ -488,12 +512,13 @@ Result> DataEvolutionSplitRead::CreatePushDownPredica return PredicateUtils::CreatePickedFieldFilter(predicate, picked_field_name_to_idx); } -Result> DataEvolutionSplitRead::SelectByFileIndex( +Result> DataEvolutionSplitRead::SelectGroupRows( const std::shared_ptr& predicate, const std::vector>& files, const std::shared_ptr& read_schema, const std::optional>& row_ranges, - const std::shared_ptr& data_file_path_factory) const { + const std::shared_ptr& data_file_path_factory, + OpenedFileReaders* opened_readers) const { if (row_ranges) { std::vector file_ranges; for (const auto& file : files) { @@ -506,7 +531,19 @@ Result> DataEvolutionSplitRead::SelectByFileIndex return std::optional(RoaringBitmap32()); } } - if (!options_.FileIndexReadEnabled() || !predicate) { + if (!predicate) { + return std::optional(); + } + const bool use_file_indexes = options_.FileIndexReadEnabled(); + const bool can_use_row_group_stats = + opened_readers != nullptr && files.size() > 1 && + !context_->EnablePreciseFileIndexEvaluate() && !context_->EnableLateMaterializing() && + std::all_of(files.begin(), files.end(), [](const auto& file) { + return DataEvolutionUtils::IsNormalFile(file->file_name) && + StringUtils::EndsWith(file->file_name, ".parquet") && + file->row_count <= std::numeric_limits::max(); + }); + if (!use_file_indexes && !can_use_row_group_stats) { return std::optional(); } @@ -528,10 +565,24 @@ Result> DataEvolutionSplitRead::SelectByFileIndex } } + const bool use_row_group_stats = can_use_row_group_stats && can_push_down_selection; + if (!use_file_indexes && !use_row_group_stats) { + return std::optional(); + } + PAIMON_ASSIGN_OR_RAISE( std::unique_ptr field_mapping_builder, FieldMappingBuilder::Create(read_schema, context_->GetPartitionKeys(), predicate)); std::optional selection; + auto intersect_selection = [&selection](const RoaringBitmap32& candidate) { + if (selection) { + *selection &= candidate; + } else { + selection = candidate; + } + }; + std::vector, std::shared_ptr>> + row_group_predicates; std::set claimed_field_ids; for (const auto& file : files) { // Blob and vector-store files may cover only part of the row range, so their indexes @@ -565,10 +616,8 @@ Result> DataEvolutionSplitRead::SelectByFileIndex } } - PAIMON_ASSIGN_OR_RAISE(std::unique_ptr field_mapping, - field_mapping_builder->CreateFieldMapping(written_fields)); - std::shared_ptr data_predicate = - field_mapping->non_partition_info.non_partition_filter; + PAIMON_ASSIGN_OR_RAISE(std::shared_ptr data_predicate, + field_mapping_builder->CreateDataFilters(written_fields)); if (!overwritten_field_names.empty()) { PAIMON_ASSIGN_OR_RAISE(data_predicate, PredicateUtils::ExcludePredicateWithFields( data_predicate, overwritten_field_names)); @@ -577,31 +626,44 @@ Result> DataEvolutionSplitRead::SelectByFileIndex continue; } - auto written_schema = DataField::ConvertDataFieldsToArrowSchema(written_fields); - auto field_name_mapping = FieldMappingBuilder::CreateFieldNameMapping( - context_->GetTableSchema()->Fields(), written_fields); - std::map file_index_options; - PAIMON_ASSIGN_OR_RAISE(file_index_options, FileIndexOptions::RewriteFieldNames( - options_.ToMap(), field_name_mapping)); - PAIMON_ASSIGN_OR_RAISE( - std::unique_ptr evaluator, - FileIndexEvaluator::Create(written_schema, file_index_options, data_file_path_factory, + if (use_file_indexes) { + auto written_schema = DataField::ConvertDataFieldsToArrowSchema(written_fields); + auto field_name_mapping = FieldMappingBuilder::CreateFieldNameMapping( + context_->GetTableSchema()->Fields(), written_fields); + std::map file_index_options; + PAIMON_ASSIGN_OR_RAISE(file_index_options, FileIndexOptions::RewriteFieldNames( + options_.ToMap(), field_name_mapping)); + PAIMON_ASSIGN_OR_RAISE(std::unique_ptr evaluator, + FileIndexEvaluator::Create( + written_schema, file_index_options, data_file_path_factory, file, options_.GetFileSystem(), /*cache=*/nullptr, pool_)); - PAIMON_ASSIGN_OR_RAISE(std::shared_ptr index_result, - evaluator->Evaluate(data_predicate)); - PAIMON_ASSIGN_OR_RAISE(bool is_remain, index_result->IsRemain()); - if (!is_remain) { - return std::optional(RoaringBitmap32()); + PAIMON_ASSIGN_OR_RAISE(std::shared_ptr index_result, + evaluator->Evaluate(data_predicate)); + PAIMON_ASSIGN_OR_RAISE(bool is_remain, index_result->IsRemain()); + if (!is_remain) { + return std::optional(RoaringBitmap32()); + } + const auto* bitmap_index = dynamic_cast(index_result.get()); + if (can_push_down_selection && bitmap_index) { + PAIMON_ASSIGN_OR_RAISE(const RoaringBitmap32* bitmap, bitmap_index->GetBitmap()); + intersect_selection(*bitmap); + } } - if (!can_push_down_selection) { - continue; + if (use_row_group_stats) { + row_group_predicates.emplace_back(file, std::move(data_predicate)); } - if (auto* bitmap_index = dynamic_cast(index_result.get())) { - PAIMON_ASSIGN_OR_RAISE(const RoaringBitmap32* bitmap, bitmap_index->GetBitmap()); - if (selection) { - *selection &= *bitmap; - } else { - selection = *bitmap; + } + + // Evaluate sidecar indexes before opening data readers for their footer statistics. + if (use_row_group_stats) { + for (const auto& [file, data_predicate] : row_group_predicates) { + if (selection && selection->IsEmpty()) { + return selection; + } + auto candidates = SelectByRowGroupStats(file, data_predicate, *data_file_path_factory, + *opened_readers); + if (candidates) { + intersect_selection(*candidates); } } } @@ -615,6 +677,31 @@ Result> DataEvolutionSplitRead::SelectByFileIndex return selection; } +std::optional DataEvolutionSplitRead::SelectByRowGroupStats( + const std::shared_ptr& file, const std::shared_ptr& predicate, + const DataFilePathFactory& data_file_path_factory, OpenedFileReaders& opened_readers) const { + const auto& opened = + opened_readers.emplace(file.get(), OpenDataFileReader(file, data_file_path_factory)) + .first->second; + // Keep open errors for reader construction if the merge still needs this file. + if (!opened.ok()) { + return std::nullopt; + } + const auto* row_group_filter = dynamic_cast(opened.value().get()); + if (!row_group_filter) { + return std::nullopt; + } + auto candidates = row_group_filter->GetRowGroupCandidateRanges(file->row_count, predicate); + if (!candidates.ok() || !candidates.value()) { + return std::nullopt; + } + RoaringBitmap32 selection; + for (const auto& range : candidates.value().value()) { + selection.AddRange(static_cast(range.from), static_cast(range.to + 1)); + } + return selection; +} + Result> DataEvolutionSplitRead::ApplyIndexAndDvReaderIfNeeded( std::unique_ptr&& file_reader, const std::shared_ptr& file, const std::shared_ptr& data_schema, @@ -898,13 +985,13 @@ Result> DataEvolutionSplitRead::CreateUnionReader( const std::shared_ptr& data_file_path_factory, const DeletionVector::Factory& group_dv_factory, const std::optional& group_dv, - const std::shared_ptr& read_schema) const { + const std::shared_ptr& read_schema, OpenedFileReaders* opened_readers) const { if (std::none_of(need_merge_files.begin(), need_merge_files.end(), [](const auto& file) { return VectorStoreUtils::IsVectorStoreFile(file->file_name); })) { return CreateFieldUnionReader(partition, need_merge_files, row_ranges, data_file_path_factory, group_dv_factory, group_dv, - read_schema); + read_schema, opened_readers); } PAIMON_ASSIGN_OR_RAISE(std::vector read_fields, @@ -993,7 +1080,7 @@ Result> DataEvolutionSplitRead::CreateFieldUnionRea const std::shared_ptr& data_file_path_factory, const DeletionVector::Factory& group_dv_factory, const std::optional& group_dv, - const std::shared_ptr& read_schema) const { + const std::shared_ptr& read_schema, OpenedFileReaders* opened_readers) const { auto blob_field_to_field_id = [&](const std::shared_ptr& file_meta) -> Result { if (!BlobUtils::IsBlobFile(file_meta->file_name)) { @@ -1017,7 +1104,7 @@ Result> DataEvolutionSplitRead::CreateFieldUnionRea /*has_row_ranges_selection=*/row_ranges.has_value())); return CreateFieldUnionReader(partition, fields_files, row_ranges, data_file_path_factory, - group_dv_factory, group_dv, read_schema); + group_dv_factory, group_dv, read_schema, opened_readers); } Result> DataEvolutionSplitRead::CreateFieldUnionReader( @@ -1026,7 +1113,7 @@ Result> DataEvolutionSplitRead::CreateFieldUnionRea const std::shared_ptr& data_file_path_factory, const DeletionVector::Factory& group_dv_factory, const std::optional& group_dv, - const std::shared_ptr& read_schema) const { + const std::shared_ptr& read_schema, OpenedFileReaders* opened_readers) const { assert(!fields_files.empty()); auto bunch_first_row_id = [](const std::shared_ptr& bunch) -> Result { if (auto blob_bunch = std::dynamic_pointer_cast(bunch)) { @@ -1152,6 +1239,19 @@ Result> DataEvolutionSplitRead::CreateFieldUnionRea file_read_schema, row_ranges, data_file_path_factory, group_dv_factory, group_dv)); } else { + if (opened_readers != nullptr) { + auto opened = opened_readers->find(first_file.get()); + if (opened != opened_readers->end()) { + PAIMON_ASSIGN_OR_RAISE(std::unique_ptr reader, + std::move(opened->second)); + PAIMON_ASSIGN_OR_RAISE( + file_batch_readers[file_idx], + ConfigureOpenedFileReader(partition, first_file, file_read_schema, + group_dv_factory, row_ranges, + data_file_path_factory, std::move(reader))); + continue; + } + } PAIMON_ASSIGN_OR_RAISE( std::vector> file_readers, CreateRawFileReaders(partition, bunch->Files(), file_read_schema, diff --git a/src/paimon/core/operation/data_evolution_split_read.h b/src/paimon/core/operation/data_evolution_split_read.h index 70075fb7e..9dc5ede4c 100644 --- a/src/paimon/core/operation/data_evolution_split_read.h +++ b/src/paimon/core/operation/data_evolution_split_read.h @@ -71,8 +71,8 @@ struct DeletionFile; /// /// A union `SplitRead` to read multiple inner files to merge columns. A single-file row range /// group gets both file-index and format-level predicate pushdown. A merged group of normal -/// files sharing one row-id range shares the intersection of its file-index selections across -/// all child readers to preserve alignment. +/// files with the same row-id range shares a selection from file indexes and Parquet row-group +/// statistics across all child readers to preserve alignment. /// /// Deletion vectors are supported: a row range group's vector is maintained against the /// group's anchor file (DataEvolutionUtils::RetrieveAnchorFile), so its positions are @@ -184,16 +184,23 @@ class DataEvolutionSplitRead : public AbstractSplitRead { const std::shared_ptr& predicate, const std::shared_ptr& read_schema); - /// Evaluates the winning files' indexes before opening the group's DV or data files. Shared - /// bitmap selection is restricted to normal files with the same row-id range; a single-file - /// group may always use its bitmap. The bitmap uses file-local positions and is intersected - /// with `row_ranges`. Nullopt means no bitmap restriction; an empty bitmap rejects the group. - Result> SelectByFileIndex( + using OpenedFileReaders = + std::unordered_map>>; + + /// Intersects candidates from file indexes and Parquet row-group statistics of the newest + /// files for the predicate fields. A shared bitmap requires aligned normal data files. + /// Nullopt keeps the original row selection; an empty bitmap rejects the group. + Result> SelectGroupRows( const std::shared_ptr& predicate, const std::vector>& files, const std::shared_ptr& read_schema, const std::optional>& row_ranges, - const std::shared_ptr& data_file_path_factory) const; + const std::shared_ptr& data_file_path_factory, + OpenedFileReaders* opened_readers = nullptr) const; + + std::optional SelectByRowGroupStats( + const std::shared_ptr& file, const std::shared_ptr& predicate, + const DataFilePathFactory& data_file_path_factory, OpenedFileReaders& opened_readers) const; /// Builds the deletion vector factory over the split's deletion files, keyed by data file /// name. Only anchor files carry one. Returns a null factory when the split has none. @@ -282,7 +289,7 @@ class DataEvolutionSplitRead : public AbstractSplitRead { const std::shared_ptr& data_file_path_factory, const DeletionVector::Factory& group_dv_factory, const std::optional& group_dv, - const std::shared_ptr& read_schema) const; + const std::shared_ptr& read_schema, OpenedFileReaders* opened_readers) const; Result> CreateFieldUnionReader( const BinaryRow& partition, @@ -291,7 +298,8 @@ class DataEvolutionSplitRead : public AbstractSplitRead { const std::shared_ptr& data_file_path_factory, const DeletionVector::Factory& group_dv_factory, const std::optional& group_dv, - const std::shared_ptr& read_schema) const; + const std::shared_ptr& read_schema, + OpenedFileReaders* opened_readers = nullptr) const; Result> CreateFieldUnionReader( const BinaryRow& partition, const std::vector>& fields_files, @@ -299,7 +307,8 @@ class DataEvolutionSplitRead : public AbstractSplitRead { const std::shared_ptr& data_file_path_factory, const DeletionVector::Factory& group_dv_factory, const std::optional& group_dv, - const std::shared_ptr& read_schema) const; + const std::shared_ptr& read_schema, + OpenedFileReaders* opened_readers = nullptr) const; /// Builds the row-level fallback reader for a blob bunch spanning multiple max sequence /// number layers: groups the files by max sequence number, pads uncovered row id ranges of @@ -315,7 +324,7 @@ class DataEvolutionSplitRead : public AbstractSplitRead { const DeletionVector::Factory& group_dv_factory, const std::optional& group_dv) const; - /// Set only on a per-group reader after SelectByFileIndex has evaluated its indexes. + /// Set only on a per-group reader after SelectGroupRows has evaluated its indexes. /// Lazy child readers inherit it so no sidecar is reopened during reader construction. bool file_indexes_evaluated_ = false; diff --git a/src/paimon/core/operation/data_evolution_split_read_test.cpp b/src/paimon/core/operation/data_evolution_split_read_test.cpp index 69607ef25..c29dbcfd6 100644 --- a/src/paimon/core/operation/data_evolution_split_read_test.cpp +++ b/src/paimon/core/operation/data_evolution_split_read_test.cpp @@ -1437,28 +1437,28 @@ TEST_F(DataEvolutionSplitReadTest, TestFileIndexSelectionOnlyPushesDownNormalGro for (const auto& other : {blob, vector, different_range}) { ASSERT_OK_AND_ASSIGN( std::optional selection, - split_read.SelectByFileIndex(match, {normal, other}, schema, std::nullopt, - /*data_file_path_factory=*/nullptr)); + split_read.SelectGroupRows(match, {normal, other}, schema, std::nullopt, + /*data_file_path_factory=*/nullptr)); ASSERT_FALSE(selection.has_value()); std::vector row_ranges = {Range(100, 102)}; - ASSERT_OK_AND_ASSIGN( - selection, split_read.SelectByFileIndex(match, {normal, other}, schema, row_ranges, - /*data_file_path_factory=*/nullptr)); + ASSERT_OK_AND_ASSIGN(selection, + split_read.SelectGroupRows(match, {normal, other}, schema, row_ranges, + /*data_file_path_factory=*/nullptr)); ASSERT_FALSE(selection.has_value()); // The normal file can still reject the entire group when its index has no matches. - ASSERT_OK_AND_ASSIGN( - selection, split_read.SelectByFileIndex(miss, {normal, other}, schema, std::nullopt, - /*data_file_path_factory=*/nullptr)); + ASSERT_OK_AND_ASSIGN(selection, + split_read.SelectGroupRows(miss, {normal, other}, schema, std::nullopt, + /*data_file_path_factory=*/nullptr)); ASSERT_TRUE(selection.has_value()); ASSERT_TRUE(selection->IsEmpty()); } for (const auto& files : {std::vector>{normal}, std::vector>{normal, same_range}}) { ASSERT_OK_AND_ASSIGN(std::optional selection, - split_read.SelectByFileIndex(match, files, schema, std::nullopt, - /*data_file_path_factory=*/nullptr)); + split_read.SelectGroupRows(match, files, schema, std::nullopt, + /*data_file_path_factory=*/nullptr)); ASSERT_EQ(selection, std::optional(RoaringBitmap32::From({1}))); // Row ranges use absolute IDs; the returned bitmap keeps file-local positions. @@ -1472,20 +1472,20 @@ TEST_F(DataEvolutionSplitReadTest, TestFileIndexSelectionOnlyPushesDownNormalGro {{Range(103, 103), Range(100, 101), Range(101, 102)}, {1, 3}}, {{Range(103, 110), Range(99, 101)}, {1, 3}}}; for (const auto& [row_ranges, expected] : cases) { - ASSERT_OK_AND_ASSIGN( - selection, split_read.SelectByFileIndex(sparse_match, files, schema, row_ranges, - /*data_file_path_factory=*/nullptr)); + ASSERT_OK_AND_ASSIGN(selection, + split_read.SelectGroupRows(sparse_match, files, schema, row_ranges, + /*data_file_path_factory=*/nullptr)); ASSERT_EQ(selection, std::optional(RoaringBitmap32::From(expected))); } ASSERT_OK_AND_ASSIGN(selection, - split_read.SelectByFileIndex(/*predicate=*/nullptr, files, schema, - std::vector{Range(100, 102)}, - /*data_file_path_factory=*/nullptr)); + split_read.SelectGroupRows(/*predicate=*/nullptr, files, schema, + std::vector{Range(100, 102)}, + /*data_file_path_factory=*/nullptr)); ASSERT_FALSE(selection.has_value()); ASSERT_OK_AND_ASSIGN(selection, - split_read.SelectByFileIndex(/*predicate=*/nullptr, files, schema, - std::vector{Range(200, 201)}, - /*data_file_path_factory=*/nullptr)); + split_read.SelectGroupRows(/*predicate=*/nullptr, files, schema, + std::vector{Range(200, 201)}, + /*data_file_path_factory=*/nullptr)); ASSERT_TRUE(selection.has_value()); ASSERT_TRUE(selection->IsEmpty()); } diff --git a/src/paimon/core/utils/field_mapping.h b/src/paimon/core/utils/field_mapping.h index cc80ee683..ad971902f 100644 --- a/src/paimon/core/utils/field_mapping.h +++ b/src/paimon/core/utils/field_mapping.h @@ -63,6 +63,10 @@ class FieldMappingBuilder { Result> CreateFieldMapping( const std::shared_ptr& data_schema) const; + /// Maps the predicate to physical fields for pushdown without building a read projection. + Result> CreateDataFilters( + const std::vector& data_fields) const; + /// Map current table field names to file field names by field ID, independently of projection. /// Fields absent from the file schema are omitted. static std::map CreateFieldNameMapping( @@ -93,8 +97,6 @@ class FieldMappingBuilder { Result CreateNonPartitionInfo( const std::vector& data_fields, const ExistFieldInfo& exist_field_info, const std::map& partition_keys) const; - Result> CreateDataFilters( - const std::vector& data_fields) const; static Result>> ReconstructLeafPredicate( const std::shared_ptr& leaf_predicate, diff --git a/src/paimon/format/parquet/parquet_file_batch_reader.cpp b/src/paimon/format/parquet/parquet_file_batch_reader.cpp index d8d5d5d3e..52ad1c16b 100644 --- a/src/paimon/format/parquet/parquet_file_batch_reader.cpp +++ b/src/paimon/format/parquet/parquet_file_batch_reader.cpp @@ -20,6 +20,7 @@ #include #include +#include #include #include #include @@ -40,6 +41,7 @@ #include "arrow/io/interfaces.h" #include "arrow/record_batch.h" #include "arrow/type.h" +#include "arrow/type_traits.h" #include "arrow/util/range.h" #include "arrow/util/thread_pool.h" #include "fmt/format.h" @@ -58,6 +60,12 @@ #include "paimon/format/parquet/parquet_read_type_adapter.h" #include "paimon/format/parquet/parquet_schema_util.h" #include "paimon/format/parquet/predicate_converter.h" +#include "paimon/predicate/compound_predicate.h" +#include "paimon/predicate/function.h" +#include "paimon/predicate/leaf_predicate.h" +#include "paimon/predicate/literal.h" +#include "paimon/predicate/predicate_builder.h" +#include "paimon/predicate/predicate_utils.h" #include "paimon/reader/batch_reader.h" #include "paimon/utils/roaring_bitmap32.h" #include "parquet/arrow/reader.h" @@ -74,8 +82,31 @@ class Predicate; } // namespace paimon namespace paimon::parquet { - namespace { + +bool NeedsMergedRowGroupFallback(const std::shared_ptr& predicate) { + const auto type = predicate->GetFunction().GetType(); + if (type == Function::Type::IS_NULL) { + // Arrow 17 treats an absent Parquet null count as zero when simplifying statistics. + return true; + } + if (type == Function::Type::LIKE) { + // Arrow's LIKE shortcuts can interpret a pattern's escapes literally. + const auto* leaf = dynamic_cast(predicate.get()); + if (!leaf || leaf->Literals().size() != 1) { + return true; + } + const auto& pattern = leaf->Literals().front(); + return pattern.IsNull() || pattern.GetType() != FieldType::STRING || + pattern.GetValue().find('\\') != std::string::npos; + } + if (const auto* compound = dynamic_cast(predicate.get())) { + const auto& children = compound->Children(); + return std::any_of(children.begin(), children.end(), NeedsMergedRowGroupFallback); + } + return false; +} + // LIST, MAP, and FIXED_SIZE_LIST do not support partial projection of their nested values. // Require matching nested structures while allowing the leaf-type representation differences // explicitly handled below. @@ -471,6 +502,70 @@ Status ParquetFileBatchReader::SetReadSchema( return Status::OK(); } +Result>> ParquetFileBatchReader::GetRowGroupCandidateRanges( + int64_t expected_row_count, const std::shared_ptr& predicate) const { + try { + if (!predicate || expected_row_count <= 0 || + static_cast(expected_row_count) != reader_->GetNumberOfRows()) { + return std::optional>(); + } + + PAIMON_ASSIGN_OR_RAISE(std::shared_ptr file_schema, reader_->GetSchema()); + std::map physical_fields; + for (int32_t i = 0; i < file_schema->num_fields(); ++i) { + const auto& field = file_schema->field(i); + // Parquet min/max can omit NaN, which can satisfy Paimon's floating-point predicates. + if (!arrow::is_floating(field->type()->id())) { + physical_fields.emplace(field->name(), i); + } + } + PAIMON_ASSIGN_OR_RAISE(std::shared_ptr physical_predicate, + PredicateUtils::CreatePickedFieldFilter(predicate, physical_fields)); + auto conjuncts = PredicateUtils::SplitAnd(physical_predicate); + conjuncts.erase( + std::remove_if(conjuncts.begin(), conjuncts.end(), NeedsMergedRowGroupFallback), + conjuncts.end()); + if (conjuncts.empty()) { + return std::optional>(); + } + PAIMON_ASSIGN_OR_RAISE(physical_predicate, PredicateBuilder::And(conjuncts)); + + const auto& row_group_ranges = reader_->GetAllRowGroupRanges(); + const auto all_row_groups = TargetRowGroup::MakeForAllRowGroups(row_group_ranges); + PAIMON_ASSIGN_OR_RAISE( + TargetRowGroups selected_row_groups, + FilterRowGroupsByPredicate(physical_predicate, file_schema, all_row_groups)); + if (selected_row_groups.size() == all_row_groups.size()) { + return std::optional>(); + } + + std::vector ranges; + ranges.reserve(selected_row_groups.size()); + for (const auto& row_group : selected_row_groups) { + const auto& [start, end] = row_group_ranges[row_group.GetRowGroupIndex()]; + if (start < end) { + ranges.emplace_back(static_cast(start), static_cast(end) - 1); + } + } + return std::optional>( + Range::SortAndMergeOverlap(ranges, /*adjacent=*/true)); + } + PAIMON_PARQUET_CATCH_AND_RETURN_STATUS("ParquetFileBatchReader::GetRowGroupCandidateRanges") +} + +std::shared_ptr ParquetFileBatchReader::GetSkippedReaderMetrics( + bool count_row_groups, std::optional storage_read_bytes) const { + auto result = std::make_shared(); + result->SetCounter( + ParquetMetrics::READ_STORAGE_BYTES, + storage_read_bytes.value_or(storage_read_bytes_ ? storage_read_bytes_->load() : 0)); + if (count_row_groups) { + result->SetCounter(ParquetMetrics::READ_ROW_GROUPS_TOTAL, reader_->GetNumberOfRowGroups()); + result->SetCounter(ParquetMetrics::READ_ROW_GROUPS_AFTER_FILTER, 0); + } + return result; +} + Result ParquetFileBatchReader::FilterRowGroupsByPredicate( const std::shared_ptr& predicate, const std::shared_ptr file_schema, const TargetRowGroups& src_row_groups) const { @@ -502,20 +597,26 @@ Result ParquetFileBatchReader::FilterRowGroupsByPredicate( file_fragment->EnsureCompleteMetadata(reader_->GetFileReader())); PAIMON_ASSIGN_OR_RAISE_FROM_ARROW(arrow::dataset::FragmentVector target_fragments, file_fragment->SplitByRowGroup(bind_expr)); - TargetRowGroups target_row_groups; - target_row_groups.reserve(src_row_groups.size()); + + std::vector selected(reader_->GetNumberOfRowGroups(), false); for (const auto& fragment : target_fragments) { - auto parquet_fragment = dynamic_cast(fragment.get()); + const auto* parquet_fragment = + dynamic_cast(fragment.get()); if (!parquet_fragment) { return Status::Invalid("cannot cast to ParquetFileFragment in ParquetFileBatchReader"); } for (auto rg_index : parquet_fragment->row_groups()) { - for (const auto& row_group : src_row_groups) { - if (row_group.GetRowGroupIndex() == rg_index) { - target_row_groups.emplace_back(row_group); - break; - } + if (static_cast(rg_index) >= selected.size()) { + return Status::Invalid("selected row group is outside the Parquet file"); } + selected[rg_index] = true; + } + } + TargetRowGroups target_row_groups; + target_row_groups.reserve(src_row_groups.size()); + for (const auto& row_group : src_row_groups) { + if (selected[row_group.GetRowGroupIndex()]) { + target_row_groups.emplace_back(row_group); } } return target_row_groups; diff --git a/src/paimon/format/parquet/parquet_file_batch_reader.h b/src/paimon/format/parquet/parquet_file_batch_reader.h index 565dec9b2..14282deae 100644 --- a/src/paimon/format/parquet/parquet_file_batch_reader.h +++ b/src/paimon/format/parquet/parquet_file_batch_reader.h @@ -49,6 +49,7 @@ #include "paimon/reader/prefetch_file_batch_reader.h" #include "paimon/result.h" #include "paimon/status.h" +#include "paimon/utils/range.h" #include "parquet/arrow/reader.h" #include "parquet/properties.h" @@ -70,7 +71,7 @@ class RoaringBitmap32; namespace paimon::parquet { -class ParquetFileBatchReader : public PrefetchFileBatchReader { +class ParquetFileBatchReader : public PrefetchFileBatchReader, public RowGroupFilter { public: static Result> Create( std::shared_ptr&& input_stream, @@ -90,6 +91,12 @@ class ParquetFileBatchReader : public PrefetchFileBatchReader { Status SetReadSchema(::ArrowSchema* read_schema, const std::shared_ptr& predicate, const std::optional& selection_bitmap) override; + Result>> GetRowGroupCandidateRanges( + int64_t expected_row_count, const std::shared_ptr& predicate) const override; + + std::shared_ptr GetSkippedReaderMetrics( + bool count_row_groups, std::optional storage_read_bytes) const override; + Status SeekToRow(uint64_t row_number) override { assert(reader_); return reader_->SeekToRow(row_number); diff --git a/test/inte/data_evolution_table_test.cpp b/test/inte/data_evolution_table_test.cpp index 79e16a6f2..fadb725d5 100644 --- a/test/inte/data_evolution_table_test.cpp +++ b/test/inte/data_evolution_table_test.cpp @@ -44,6 +44,7 @@ #include "paimon/defs.h" #include "paimon/executor.h" #include "paimon/format/mosaic/mosaic_format_defs.h" +#include "paimon/format/parquet/parquet_format_defs.h" #include "paimon/fs/file_system.h" #include "paimon/global_index/bitmap_global_index_result.h" #include "paimon/global_index/bitmap_scored_global_index_result.h" @@ -51,12 +52,14 @@ #include "paimon/predicate/literal.h" #include "paimon/predicate/predicate_builder.h" #include "paimon/predicate/predicate_utils.h" +#include "paimon/reader/prefetch_file_batch_reader.h" #include "paimon/result.h" #include "paimon/status.h" #include "paimon/testing/utils/deletion_vector_test_helper.h" #include "paimon/testing/utils/io_exception_helper.h" #include "paimon/testing/utils/test_helper.h" #include "paimon/testing/utils/testharness.h" +#include "paimon/utils/roaring_bitmap64.h" #include "paimon/utils/row_range_index.h" namespace paimon::test { using DataEvolutionTableParam = std::tuple; @@ -1700,16 +1703,16 @@ TEST_P(DataEvolutionTableTest, TestPartitionWithPredicate) { SetFirstRowId(3, commit_msgs3); ASSERT_OK(Commit(table_path, commit_msgs3)); { - // only set data field predicate, predicate only takes effective in file skip - // read will not push down + // Parquet also prunes row groups within the merged files. auto equal = PredicateBuilder::Equal(/*field_index=*/0, /*field_name=*/"f0", FieldType::INT, Literal(11)); - auto expected_array = std::dynamic_pointer_cast( - arrow::ipc::internal::json::ArrayFromJSON(arrow::struct_(fields_), R"([ + const char* expected_rows = file_format == "parquet" ? R"([[11, "2024", "a"]])" : R"([ [11, "2024", "a"], [12, "2024", "b"], [13, "2024", "c"] - ])") + ])"; + auto expected_array = std::dynamic_pointer_cast( + arrow::ipc::internal::json::ArrayFromJSON(arrow::struct_(fields_), expected_rows) .ValueOrDie()); ASSERT_OK(ScanAndRead(table_path, schema->field_names(), expected_array, equal)); } @@ -1792,14 +1795,18 @@ TEST_P(DataEvolutionTableTest, TestPartitionWithPredicate) { Literal(11)); CheckScanResult(table_path, /*predicate=*/equal, /*row_ranges=*/row_ranges, /*expected_first_row_ids=*/{0, 0}, /*expected_row_counts=*/{3, 3}); - auto expected_array = std::dynamic_pointer_cast( - arrow::ipc::internal::json::ArrayFromJSON(arrow::struct_(fields_), R"([ - [12, "2024", "b"] - ])") - .ValueOrDie()); + // The selected row ID lies outside the matching Parquet row group. + std::shared_ptr expected_array; + if (file_format != "parquet") { + expected_array = std::dynamic_pointer_cast( + arrow::ipc::internal::json::ArrayFromJSON(arrow::struct_(fields_), + R"([[12, "2024", "b"]])") + .ValueOrDie()); + } ASSERT_OK(ScanAndRead(table_path, schema->field_names(), expected_array, /*predicate=*/equal, - /*row_ranges=*/row_ranges)); + /*row_ranges=*/row_ranges, + /*check_scan_plan_when_empty_result=*/false)); } { std::vector row_ranges = {Range(1l, 1l)}; @@ -2968,6 +2975,297 @@ TEST_P(DataEvolutionTableTest, TestScanAndReadWithIndex) { } } +TEST_P(DataEvolutionTableTest, TestMergedParquetRowGroupPredicatePushDown) { + if (FileFormat() != "parquet") { + return; + } + std::map options = { + {Options::FILE_FORMAT, FileFormat()}, + {Options::FILE_SYSTEM, "local"}, + {Options::BUCKET, "-1"}, + {Options::ROW_TRACKING_ENABLED, "true"}, + {Options::DATA_EVOLUTION_ENABLED, "true"}, + {Options::FILE_INDEX_READ_ENABLED, "false"}, + {"parquet.read.enable-page-index-filter", "false"}, + {"parquet.write.max-row-group-length", "2"}}; + auto fields = fields_; + fields.push_back(arrow::field("f3", arrow::float64())); + CreateTable(fields, /*partition_keys=*/{"f1"}, options); + std::string table_path = PathUtil::JoinPath(dir_->Str(), "foo.db/bar"); + const std::map partition = {{"f1", "p"}}; + auto base = arrow::ipc::internal::json::ArrayFromJSON(arrow::struct_(fields), R"([ + [1, "p", "old", 1.0], + [2, "p", "old", NaN], + [3, "p", "old", 3.0], + [4, "p", "old", 4.0] + ])") + .ValueOrDie(); + ASSERT_OK_AND_ASSIGN(auto base_messages, + WriteArray(table_path, partition, {"f0", "f1", "f2", "f3"}, base)); + SetFirstRowId(10, base_messages); + ASSERT_OK(Commit(table_path, base_messages)); + + // The update covers the same rows but uses row groups of 3 + 1 instead of 2 + 2. + auto update = arrow::ipc::internal::json::ArrayFromJSON(arrow::struct_({fields_[2]}), R"([ + ["new-1"], + ["new-2"], + ["new-3"], + ["a\\b"] + ])") + .ValueOrDie(); + ASSERT_OK_AND_ASSIGN(auto update_messages, + WriteArray(table_path, partition, {"f2"}, update, + {{"parquet.write.max-row-group-length", "3"}})); + SetFirstRowId(10, update_messages); + ASSERT_OK(Commit(table_path, update_messages)); + + ScanContextBuilder scan_builder(table_path); + ASSERT_OK_AND_ASSIGN(auto scan_context, FinishScanContext(scan_builder)); + ASSERT_OK_AND_ASSIGN(auto table_scan, TableScan::Create(std::move(scan_context))); + ASSERT_OK_AND_ASSIGN(auto plan, table_scan->CreatePlan()); + const auto& splits = plan->Splits(); + + const std::vector read_fields = {"f0", "f2"}; + auto read_type = arrow::struct_({fields_[0], fields_[2]}); + const auto result_type = + arrow::struct_({SpecialFields::ValueKind().ArrowField(), fields[0], fields[2]}); + auto base_predicate = PredicateBuilder::GreaterThan(/*field_index=*/0, /*field_name=*/"f0", + FieldType::INT, Literal(2)); + auto update_predicate = PredicateBuilder::Equal( + /*field_index=*/1, /*field_name=*/"f2", FieldType::STRING, + Literal(FieldType::STRING, "new-3", 5)); + + // An escaped LIKE stays for row-level filtering while the base statistics narrow the scan. + { + ASSERT_OK_AND_ASSIGN( + auto like, + PredicateBuilder::Like(/*field_index=*/1, /*field_name=*/"f2", FieldType::STRING, + Literal(FieldType::STRING, R"(a\\b%)", 5))); + ASSERT_OK_AND_ASSIGN(auto predicate, PredicateBuilder::And({base_predicate, like})); + auto expected = std::dynamic_pointer_cast( + arrow::ipc::internal::json::ArrayFromJSON(read_type, R"([ + [3, "new-3"], + [4, "a\\b"] + ])") + .ValueOrDie()); + ASSERT_OK(ScanAndRead(table_path, read_fields, expected, predicate, /*row_ranges=*/{}, + /*check_scan_plan_when_empty_result=*/true, + /*apply_predicate_to_scan=*/false)); + } + for (bool enable_prefetch : {false, true}) { + // The base keeps rows 3 and 4, and the newest f2 file keeps rows 1 through 3. + ASSERT_OK_AND_ASSIGN(auto predicate, + PredicateBuilder::And({base_predicate, update_predicate})); + ReadContextBuilder read_builder(table_path); + read_builder.SetReadFieldNames(read_fields) + .SetPredicate(predicate) + .EnablePredicateFilter(false) + .EnablePrefetch(enable_prefetch) + .SetPrefetchBatchCount(3); + ASSERT_OK_AND_ASSIGN(auto read_context, read_builder.Finish()); + ASSERT_OK_AND_ASSIGN(auto table_read, TableRead::Create(std::move(read_context))); + ASSERT_OK_AND_ASSIGN(auto reader, table_read->CreateReader(splits)); + ScopeGuard close_reader([&reader]() { reader->Close(); }); + ASSERT_OK_AND_ASSIGN(auto result, ReadResultCollector::CollectResult(reader.get())); + + auto expected = + arrow::ipc::internal::json::ArrayFromJSON(result_type, R"([[0, 3, "new-3"]])") + .ValueOrDie(); + ASSERT_TRUE(result); + ASSERT_TRUE(result->Equals(arrow::ChunkedArray(expected))); + + if (!enable_prefetch) { + const auto metrics = reader->GetReaderMetrics(); + ASSERT_OK_AND_ASSIGN( + uint64_t total, + metrics->GetCounter(parquet::ParquetMetrics::READ_ROW_GROUPS_TOTAL)); + ASSERT_OK_AND_ASSIGN( + uint64_t selected, + metrics->GetCounter(parquet::ParquetMetrics::READ_ROW_GROUPS_AFTER_FILTER)); + ASSERT_EQ(4u, total); + ASSERT_EQ(2u, selected); + } + } + { + // The footer of the newest f2 file rejects the entire group. + auto missing = + PredicateBuilder::Equal(/*field_index=*/1, /*field_name=*/"f2", FieldType::STRING, + Literal(FieldType::STRING, "zzzz", 4)); + for (const auto& [enable_prefetch, enable_cache] : + {std::pair{false, false}, std::pair{true, false}, std::pair{true, true}}) { + ReadContextBuilder read_builder(table_path); + read_builder.SetReadFieldNames(read_fields) + .SetPredicate(missing) + .EnablePrefetch(enable_prefetch) + .SetPrefetchMaxParallelNum(3) + .SetReadAheadCacheEnabled(enable_cache) + .AddOption(Options::PREFETCH_IO_METRICS_ENABLED, "true"); + ASSERT_OK_AND_ASSIGN(auto read_context, read_builder.Finish()); + ASSERT_OK_AND_ASSIGN(auto table_read, TableRead::Create(std::move(read_context))); + ASSERT_OK_AND_ASSIGN(auto reader, table_read->CreateReader(splits)); + ScopeGuard close_reader([&reader]() { reader->Close(); }); + ASSERT_OK_AND_ASSIGN(auto batch, reader->NextBatch()); + ASSERT_TRUE(BatchReader::IsEofBatch(batch)); + + const auto metrics = reader->GetReaderMetrics(); + ASSERT_OK_AND_ASSIGN(uint64_t bytes, + metrics->GetCounter(parquet::ParquetMetrics::READ_STORAGE_BYTES)); + ASSERT_GT(bytes, 0u); + if (enable_prefetch) { + ASSERT_OK_AND_ASSIGN(uint64_t sync_bytes, + metrics->GetCounter(PrefetchIoMetrics::READ_PHYSICAL_BYTES)); + ASSERT_OK_AND_ASSIGN(uint64_t async_bytes, + metrics->GetCounter(PrefetchIoMetrics::ASYNC_PHYSICAL_BYTES)); + ASSERT_EQ(sync_bytes + async_bytes, bytes); + } + ASSERT_OK_AND_ASSIGN( + uint64_t total, + metrics->GetCounter(parquet::ParquetMetrics::READ_ROW_GROUPS_TOTAL)); + ASSERT_OK_AND_ASSIGN( + uint64_t selected, + metrics->GetCounter(parquet::ParquetMetrics::READ_ROW_GROUPS_AFTER_FILTER)); + ASSERT_EQ(2u, total); + ASSERT_EQ(0u, selected); + } + } + { + // The base conjunct prunes row groups while the cross-file OR stays for row filtering. + auto first = PredicateBuilder::Equal(/*field_index=*/0, /*field_name=*/"f0", FieldType::INT, + Literal(1)); + ASSERT_OK_AND_ASSIGN(std::shared_ptr residual, + PredicateBuilder::Or({first, update_predicate})); + ASSERT_OK_AND_ASSIGN(std::shared_ptr predicate, + PredicateBuilder::And({base_predicate, residual})); + for (bool enable_predicate_filter : {false, true}) { + ReadContextBuilder read_builder(table_path); + read_builder.SetReadFieldNames(read_fields) + .SetPredicate(predicate) + .EnablePredicateFilter(enable_predicate_filter); + ASSERT_OK_AND_ASSIGN(std::unique_ptr read_context, read_builder.Finish()); + ASSERT_OK_AND_ASSIGN(std::unique_ptr table_read, + TableRead::Create(std::move(read_context))); + ASSERT_OK_AND_ASSIGN(std::unique_ptr reader, + table_read->CreateReader(splits)); + ScopeGuard close_reader([&reader]() { reader->Close(); }); + ASSERT_OK_AND_ASSIGN(std::shared_ptr result, + ReadResultCollector::CollectResult(reader.get())); + + const char* expected_rows = enable_predicate_filter + ? R"([[0, 3, "new-3"]])" + : R"([[0, 3, "new-3"], [0, 4, "a\\b"]])"; + auto expected = + arrow::ipc::internal::json::ArrayFromJSON(result_type, expected_rows).ValueOrDie(); + ASSERT_TRUE(result); + ASSERT_TRUE(result->Equals(arrow::ChunkedArray(expected))); + ASSERT_OK_AND_ASSIGN(uint64_t selected, + reader->GetReaderMetrics()->GetCounter( + parquet::ParquetMetrics::READ_ROW_GROUPS_AFTER_FILTER)); + ASSERT_EQ(3u, selected); + } + } + { + // Parquet min/max can omit NaN, which Paimon orders above finite values. + auto predicate = PredicateBuilder::GreaterThan(/*field_index=*/0, /*field_name=*/"f3", + FieldType::DOUBLE, Literal(10.0)); + ReadContextBuilder read_builder(table_path); + read_builder.SetReadFieldNames({"f3", "f2", SpecialFields::RowId().Name()}) + .SetPredicate(predicate) + .EnablePredicateFilter(true); + ASSERT_OK_AND_ASSIGN(auto read_context, read_builder.Finish()); + ASSERT_OK_AND_ASSIGN(auto table_read, TableRead::Create(std::move(read_context))); + ASSERT_OK_AND_ASSIGN(auto reader, table_read->CreateReader(splits)); + ScopeGuard close_reader([&reader]() { reader->Close(); }); + ASSERT_OK_AND_ASSIGN(auto result, ReadResultCollector::CollectResult(reader.get())); + + auto expected_type = arrow::struct_({SpecialFields::ValueKind().ArrowField(), fields[3], + fields[2], SpecialFields::RowId().ArrowField()}); + auto expected = + arrow::ipc::internal::json::ArrayFromJSON(expected_type, R"([[0, NaN, "new-2", 11]])") + .ValueOrDie(); + ASSERT_TRUE(result); + ASSERT_TRUE(result->Equals(arrow::ChunkedArray(expected), + arrow::EqualOptions::Defaults().nans_equal(true))); + } + { + // The indexed row range intersects the pruned base range. Scores follow row IDs. + RoaringBitmap64 scored_rows; + scored_rows.AddRange(10, 13); + ScanContextBuilder scored_scan_builder(table_path); + scored_scan_builder.SetGlobalIndexResult(std::make_shared( + std::move(scored_rows), std::vector{1.0f, 2.0f, 3.0f})); + ASSERT_OK_AND_ASSIGN(auto scored_scan_context, FinishScanContext(scored_scan_builder)); + ASSERT_OK_AND_ASSIGN(auto scored_table_scan, + TableScan::Create(std::move(scored_scan_context))); + ASSERT_OK_AND_ASSIGN(auto scored_plan, scored_table_scan->CreatePlan()); + + ReadContextBuilder read_builder(table_path); + read_builder.SetReadFieldNames({"f0", "f2", SpecialFields::IndexScore().Name()}) + .SetPredicate(base_predicate) + .EnablePredicateFilter(false); + ASSERT_OK_AND_ASSIGN(auto read_context, read_builder.Finish()); + ASSERT_OK_AND_ASSIGN(auto table_read, TableRead::Create(std::move(read_context))); + ASSERT_OK_AND_ASSIGN(auto reader, table_read->CreateReader(scored_plan->Splits())); + ScopeGuard close_reader([&reader]() { reader->Close(); }); + ASSERT_OK_AND_ASSIGN(auto result, ReadResultCollector::CollectResult(reader.get())); + + auto expected_type = arrow::struct_({SpecialFields::ValueKind().ArrowField(), fields[0], + fields[2], SpecialFields::IndexScore().ArrowField()}); + auto expected = + arrow::ipc::internal::json::ArrayFromJSON(expected_type, R"([[0, 3, "new-3", 3.0]])") + .ValueOrDie(); + ASSERT_TRUE(result); + ASSERT_TRUE(result->Equals(arrow::ChunkedArray(expected))); + } +} + +TEST_P(DataEvolutionTableTest, TestMergedParquetPushDownWithOverwrittenNestedField) { + if (FileFormat() != "parquet") { + return; + } + const std::map options = { + {Options::FILE_FORMAT, FileFormat()}, + {Options::FILE_SYSTEM, "local"}, + {Options::BUCKET, "-1"}, + {Options::ROW_TRACKING_ENABLED, "true"}, + {Options::DATA_EVOLUTION_ENABLED, "true"}, + {Options::FILE_INDEX_READ_ENABLED, "false"}, + {"parquet.write.max-row-group-length", "1"}}; + auto id = arrow::field("id", arrow::int32()); + auto a = arrow::field("a", arrow::int32()); + auto old_record = arrow::field("s", arrow::struct_({a})); + const arrow::FieldVector old_fields = {id, old_record}; + CreateTable(old_fields, /*partition_keys=*/{}, options); + std::string table_path = PathUtil::JoinPath(dir_->Str(), "foo.db/bar"); + auto base = arrow::ipc::internal::json::ArrayFromJSON(arrow::struct_(old_fields), + R"([[1, [10]], [2, [20]]])") + .ValueOrDie(); + ASSERT_OK_AND_ASSIGN(auto base_messages, WriteArray(table_path, {"id", "s"}, base)); + SetFirstRowId(/*reset_first_row_id=*/0, base_messages); + ASSERT_OK(Commit(table_path, base_messages)); + + auto b = arrow::field("b", arrow::int32()); + auto new_record = arrow::field( + "s", DataField::ConvertDataFieldsToArrowStructType({DataField(2, a), DataField(3, b)})); + ASSERT_OK(TestHelper::WriteNextSchema(dir_->GetFileSystem(), table_path, + {DataField(0, id), DataField(1, new_record)}, + /*highest_field_id=*/3, options)); + auto update = arrow::ipc::internal::json::ArrayFromJSON(arrow::struct_({new_record}), + R"([[[30, 31]], [[40, 41]]])") + .ValueOrDie(); + ASSERT_OK_AND_ASSIGN(auto update_messages, WriteArray(table_path, {"s"}, update)); + SetFirstRowId(/*reset_first_row_id=*/0, update_messages); + ASSERT_OK(Commit(table_path, update_messages)); + + auto predicate = PredicateBuilder::Equal(/*field_index=*/0, "id", FieldType::INT, Literal(2)); + auto expected = checked_pointer_cast( + arrow::ipc::internal::json::ArrayFromJSON(arrow::struct_({id, new_record}), + R"([[2, [40, 41]]])") + .ValueOrDie()); + ASSERT_OK(ScanAndRead(table_path, {"id", "s"}, expected, predicate, /*row_ranges=*/{}, + /*check_scan_plan_when_empty_result=*/true, + /*apply_predicate_to_scan=*/false)); +} + TEST_P(DataEvolutionTableTest, TestDataEvolutionPredicatePushDownBoundaries) { if (FileFormat() == "mosaic" || FileFormat() == "lance") { return;