You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@paimon.apache.org by "zhf999 (via GitHub)" <gi...@apache.org> on 2026/08/24 08:04:37 UTC
[PR] feat(reader): support late materialization with probe/payload two-phase reads [paimon-cpp]
zhf999 opened a new pull request, #243:
URL: https://github.com/apache/paimon-cpp/pull/243
> **Note:** This branch is still under active development. The PR is created temporarily to
> synchronize progress; it is not ready for review or merge.
This PR is inspired by #242, thanks @gripleaf for the initial work.
### Purpose
This PR introduces a **late-materializing file batch reader** (`LateMaterializingFileBatchReader`)
that performs probe/payload two-phase reads when a predicate is pushed down through
`SetReadSchema`.
**Motivation.** In a standard read, all projected columns are materialized together, even though a
pushed-down predicate may filter out the vast majority of rows. Late materialization splits the
read into two passes:
1. **Probe pass** — read only the predicate columns, evaluate the predicate batch by batch, and
build a `matched_bitmap_` of surviving rows.
2. **Payload pass** — read the remaining (payload) columns, compacted to only the matched rows,
then assemble the probe and payload columns into a single struct array in `full_schema_` field
order.
This avoids decoding and holding the wide payload columns for rows that will be discarded.
**Architecture.** The reader is installed **below the prefetch layer** by wrapping the
format-specific `ReaderBuilder` with a `LateMaterializingReaderBuilder`
(`AbstractSplitRead::CreateFileBatchReader`). Each parallel reader under the prefetch layer thus
gets its own late-materializing wrapper. The reader implements the full
`PrefetchFileBatchReader` interface, forwarding schema, row-count, seek, read-range, and metric
queries to the inner reader while interposing the two-phase logic in `SetReadSchema` /
`NextBatch`.
**Key files:**
- `src/paimon/common/reader/late_materializing_file_batch_reader.{h,cpp}` — core reader with a
state machine (`kInit → kProbing → kRunning | kNoLatMat → kEOF`), probe data filtering, payload
batch reading with bitmap compaction, and full-batch assembly.
- `src/paimon/common/reader/late_materializing_reader_builder.h` — `ReaderBuilder` wrapper that
installs the late-materializing reader around each format reader produced by the inner builder.
- `src/paimon/core/operation/abstract_split_read.{h,cpp}` — integration: the reader builder is
wrapped with `LateMaterializingReaderBuilder` inside `CreateFileBatchReader`.
- `src/paimon/testing/mock/mock_file_batch_reader.h` — enhanced to faithfully emulate a real
format reader: `SetReadSchema` now resets position and read ranges; `NextBatchWithBitmap`
honours assigned read ranges; a `ProjectBatch` helper supports column re-selection.
- `src/paimon/CMakeLists.txt` — registers the new source and test files.
### Tests
A dedicated test suite `LateMaterializingFileBatchReaderTest` is added in
`src/paimon/common/reader/late_materializing_file_batch_reader_test.cpp` (15 cases):
| Test case | Verifies |
|---|---|
| `PassThroughWhenNoPredicate` | No predicate → passthrough, single batch returned |
| `PassThroughWhenPayloadEmpty` | All fields are probe fields → passthrough |
| `ContiguousSubsetAcrossBatches` | Contiguous matched rows spanning multiple batches |
| `ScatteredAlternatingMatch` | Non-contiguous alternating matches compacted correctly |
| `MatchedIntersectsSelection` | Predicate bitmap intersected with `selection_bitmap` |
| `EmptyMatchReturnsEof` | Zero matched rows → immediate EOF |
| `SeekToRowRealignsProbeCursor` | `SeekToRow` realigns the probe cursor and state |
| `ReadRangesForwardedAcrossPhases` | Read ranges forwarded to inner reader across phases |
| `ReentrantSetReadSchema` | Repeated `SetReadSchema` resets state cleanly |
| `ForwardsRowCountAndFileSchema` | `GetNumberOfRows` / `GetFileSchema` forwarded |
| `MultiFieldPreservesColumnOrder` | Multi-field schema preserves field order in assembled batch |
| `NestedPayloadColumn` | Nested-type payload column handled correctly |
| `WorksAsInnerOfPrefetchReader` | Works as inner reader of `PrefetchFileBatchReaderImpl` |
| `PrefetchInnerReentrantSetReadSchema` | Reentrant `SetReadSchema` under prefetch |
| `PrefetchInnerParallelReadersWithSeek` | Parallel prefetch readers with seek interleave correctly |
> **Note:** As the branch is still in development, not all validation commands above have been run
> to completion. The final validation will be performed before marking the PR ready for review.
### API and Format
No change to public API under `include/paimon/`, no storage format or protocol change.
The only signature changes are **internal** to the split-read path:
- `AbstractSplitRead::CreateFileBatchReader` — `const ReaderBuilder*` →
`std::unique_ptr<ReaderBuilder>` (ownership transfer to allow wrapping).
- `AbstractSplitRead::CreateFieldMappingReader` — same change for the `reader_builder` parameter.
Both are private methods of `AbstractSplitRead`; all call sites within the class are updated in the
same change.
### Documentation
No user-facing documentation change yet. As the feature stabilizes, documentation for the
late-materialization read mode and its configuration options will be added in a follow-up.
### Generative AI tooling
Generated-by: Qoder
--
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: issues-unsubscribe@paimon.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(reader): support late materialization with probe/payload two-phase reads [paimon-cpp]
Posted by "zhf999 (via GitHub)" <gi...@apache.org>.
zhf999 commented on code in PR #243:
URL: https://github.com/apache/paimon-cpp/pull/243#discussion_r3859434255
##########
src/paimon/common/reader/late_materializing_file_batch_reader.cpp:
##########
@@ -0,0 +1,352 @@
+/*
+ * 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.
+ */
+
+#include "paimon/common/reader/late_materializing_file_batch_reader.h"
+
+#include <map>
+#include <set>
+#include <string>
+#include <utility>
+#include <vector>
+
+#include "arrow/array/concatenate.h"
+#include "arrow/array/util.h"
+#include "arrow/c/bridge.h"
+#include "arrow/memory_pool.h"
+#include "arrow/type.h"
+#include "arrow/util/checked_cast.h"
+#include "fmt/format.h"
+#include "paimon/common/predicate/predicate_filter.h"
+#include "paimon/common/predicate/predicate_validator.h"
+#include "paimon/common/reader/reader_utils.h"
+#include "paimon/common/utils/arrow/arrow_utils.h"
+#include "paimon/common/utils/arrow/mem_utils.h"
+#include "paimon/common/utils/arrow/status_utils.h"
+#include "paimon/predicate/predicate_utils.h"
+#include "paimon/status.h"
+
+namespace paimon {
+
+Result<std::unique_ptr<LateMaterializingFileBatchReader>> LateMaterializingFileBatchReader::Create(
+ std::unique_ptr<PrefetchFileBatchReader> inner, std::shared_ptr<MemoryPool> pool) {
+ // The reader's own compaction allocations go through an arrow pool; bridge the paimon pool
+ // once here so the accounting matches the rest of the read path.
+ if (pool == nullptr) {
+ return Status::Invalid("pool could not be nullptr.");
+ }
+ std::shared_ptr<arrow::MemoryPool> arrow_pool = GetArrowPool(pool);
+ auto reader = std::unique_ptr<LateMaterializingFileBatchReader>(
+ new LateMaterializingFileBatchReader(std::move(inner), std::move(arrow_pool)));
+ return reader;
+}
+
+Result<FileBatchReader::ReadBatch> LateMaterializingFileBatchReader::NextBatch() {
+ if (state_ == kInit) {
+ // SetReadSchema has not been called: read with the file schema, matching the
+ // FileBatchReader contract for schema-less reads.
+ state_ = kNoLatMat;
+ }
+ if (state_ == kProbing) {
+ PAIMON_RETURN_NOT_OK(ReadAndFilterProbeData());
+ if (matched_bitmap_.IsEmpty()) {
+ state_ = kEOF;
+ } else {
+ // payload pass reads only the matched rows (matched_bitmap_ is non-empty here).
+ PAIMON_RETURN_NOT_OK(
+ SetInnerReadSchema(payload_schema_, /*predicate=*/nullptr, matched_bitmap_));
+ state_ = kRunning;
+ }
+ }
+
+ if (state_ == kNoLatMat) {
+ return inner_->NextBatch();
+ } else if (state_ == kRunning) {
+ return ReadPayloadBatch();
+ } else if (state_ == kEOF) {
+ return MakeEofBatch();
+ }
+ return Status::Invalid("invalid state when calling NextBatch: " + std::to_string(state_));
+}
+
+Result<RoaringBitmap32> LateMaterializingFileBatchReader::FilterProbeBatch(
+ const std::shared_ptr<arrow::Array>& array,
+ const std::shared_ptr<PredicateFilter>& bound_filter) {
+ // TODO(zhouhonfeng.zhf): use arrow::compute::Filter instead of PredicateFilter
+ PAIMON_ASSIGN_OR_RAISE(std::vector<char> results, bound_filter->Test(*array));
+ if (results.size() != static_cast<size_t>(array->length())) {
+ return Status::Invalid(
+ fmt::format("predicate result size {} does not match probe batch length {}",
+ results.size(), array->length()));
+ }
+ // batch-local offsets of the rows passing both the predicate and the selection
+ RoaringBitmap32 batch_matched;
+ for (int64_t i = 0; i < array->length(); ++i) {
+ if (!results[static_cast<size_t>(i)]) {
+ continue;
+ }
+ // map batch offset to file row id
+ PAIMON_ASSIGN_OR_RAISE(uint64_t file_row,
+ inner_->GetPreviousBatchFileRowId(static_cast<uint64_t>(i)));
+ if (selection_ && !selection_->Contains(static_cast<int32_t>(file_row))) {
+ continue;
+ }
+ batch_matched.Add(static_cast<uint32_t>(i));
+ matched_bitmap_.Add(file_row);
+ }
+ return batch_matched;
+}
+
+Status LateMaterializingFileBatchReader::ReadAndFilterProbeData() {
+ matched_bitmap_ = RoaringBitmap32();
+ probe_cursor_ = 0;
+ arrow::ArrayVector probe_arrays;
+ while (true) {
+ PAIMON_ASSIGN_OR_RAISE(FileBatchReader::ReadBatch batch, inner_->NextBatch());
+ if (BatchReader::IsEofBatch(batch)) {
+ break;
+ }
+ auto& [c_array, c_schema] = batch;
+ PAIMON_ASSIGN_OR_RAISE_FROM_ARROW(std::shared_ptr<arrow::Array> array,
+ arrow::ImportArray(c_array.get(), c_schema.get()));
+ PAIMON_ASSIGN_OR_RAISE(RoaringBitmap32 batch_matched,
+ FilterProbeBatch(array, probe_filter_));
+ // Compact each probe batch down to its matched rows so probe_data_ aligns row-for-row
+ // (ascending file order) with matched_bitmap_ and the later payload output.
+ if (!batch_matched.IsEmpty()) {
+ PAIMON_ASSIGN_OR_RAISE(arrow::ArrayVector matched_slices,
+ ReaderUtils::GenerateFilteredArrayVector(array, batch_matched));
+ probe_arrays.insert(probe_arrays.end(), std::make_move_iterator(matched_slices.begin()),
+ std::make_move_iterator(matched_slices.end()));
+ }
+ }
+
+ std::shared_ptr<arrow::Array> probe_array;
+ if (probe_arrays.empty()) {
+ PAIMON_ASSIGN_OR_RAISE_FROM_ARROW(
+ probe_array, arrow::MakeEmptyArray(arrow::struct_(probe_schema_->fields())));
+ } else {
+ PAIMON_ASSIGN_OR_RAISE_FROM_ARROW(probe_array,
+ arrow::Concatenate(probe_arrays, arrow_pool_.get()));
+ }
+ probe_data_ = arrow::internal::checked_pointer_cast<arrow::StructArray>(probe_array);
+ return Status::OK();
+}
+
+Result<FileBatchReader::ReadBatch> LateMaterializingFileBatchReader::ReadPayloadBatch() {
+ while (true) {
+ PAIMON_ASSIGN_OR_RAISE(FileBatchReader::ReadBatchWithBitmap batch_with_bitmap,
+ inner_->NextBatchWithBitmap());
+ if (BatchReader::IsEofBatch(batch_with_bitmap)) {
+ state_ = kEOF;
+ if (probe_cursor_ != probe_data_->length()) {
+ return Status::Invalid(
+ fmt::format("probe cursor {} does not match probe data length {}",
+ probe_cursor_, probe_data_->length()));
+ }
+ return MakeEofBatch();
+ }
+ auto& [batch, bitmap] = batch_with_bitmap;
+ if (bitmap.IsEmpty()) {
+ ReaderUtils::ReleaseReadBatch(std::move(batch));
+ continue;
+ }
+ auto& [c_array, c_schema] = batch;
+ PAIMON_ASSIGN_OR_RAISE_FROM_ARROW(std::shared_ptr<arrow::Array> payload_array,
+ arrow::ImportArray(c_array.get(), c_schema.get()));
+
+ // Generate the valid bitmap and row_mapping_
+ RoaringBitmap32 valid;
+ row_mapping_.clear();
+ for (auto it = bitmap.Begin(); it != bitmap.End(); ++it) {
+ auto offset = static_cast<uint64_t>(*it);
+ PAIMON_ASSIGN_OR_RAISE(uint64_t file_row, inner_->GetPreviousBatchFileRowId(offset));
+ if (!matched_bitmap_.Contains(file_row)) {
+ continue;
+ }
+ valid.Add(static_cast<uint32_t>(offset));
+ row_mapping_.push_back(file_row);
+ }
+ if (valid.IsEmpty()) {
+ ReaderUtils::ReleaseReadBatch(std::move(batch));
+ continue;
+ }
+
+ // Compact the payload superset down to the matched rows (ascending file row order).
+ PAIMON_ASSIGN_OR_RAISE(arrow::ArrayVector payload_slices,
+ ReaderUtils::GenerateFilteredArrayVector(payload_array, valid));
+ PAIMON_ASSIGN_OR_RAISE_FROM_ARROW(std::shared_ptr<arrow::Array> payload_compacted,
+ arrow::Concatenate(payload_slices, arrow_pool_.get()));
+
+ auto card = static_cast<int64_t>(valid.Cardinality());
+ if (probe_cursor_ + card > probe_data_->length()) {
+ return Status::Invalid(
+ fmt::format("probe cache underflow: cursor {} + {} exceeds probe rows {}",
+ probe_cursor_, card, probe_data_->length()));
+ }
+ std::shared_ptr<arrow::Array> probe_selected = probe_data_->Slice(probe_cursor_, card);
+ PAIMON_ASSIGN_OR_RAISE(
+ probe_selected, ArrowUtils::NormalizeArrayOffsets(probe_selected, arrow_pool_.get()));
+ probe_cursor_ += card;
+
+ PAIMON_ASSIGN_OR_RAISE(FileBatchReader::ReadBatch assembled,
+ AssembleFullBatch(payload_compacted, probe_selected));
+ return assembled;
+ }
+}
+
+Result<FileBatchReader::ReadBatch> LateMaterializingFileBatchReader::AssembleFullBatch(
+ const std::shared_ptr<arrow::Array>& payload_array,
+ const std::shared_ptr<arrow::Array>& probe_array) {
+ auto payload_struct = arrow::internal::checked_pointer_cast<arrow::StructArray>(payload_array);
+ auto probe_struct = arrow::internal::checked_pointer_cast<arrow::StructArray>(probe_array);
+ arrow::ArrayVector children;
+ children.reserve(full_schema_->num_fields());
+ for (const auto& field : full_schema_->fields()) {
+ std::shared_ptr<arrow::Array> col = payload_struct->GetFieldByName(field->name());
+ if (!col) {
+ col = probe_struct->GetFieldByName(field->name());
+ }
+ if (!col) {
+ return Status::Invalid(
+ fmt::format("field {} missing in both payload and probe columns", field->name()));
+ }
+ PAIMON_ASSIGN_OR_RAISE(col, ArrowUtils::NormalizeArrayOffsets(col, arrow_pool_.get()));
+ children.push_back(std::move(col));
+ }
+ PAIMON_ASSIGN_OR_RAISE_FROM_ARROW(std::shared_ptr<arrow::StructArray> full_struct,
+ arrow::StructArray::Make(children, full_schema_->fields()));
+ std::unique_ptr<::ArrowArray> c_array = std::make_unique<::ArrowArray>();
+ std::unique_ptr<::ArrowSchema> c_schema = std::make_unique<::ArrowSchema>();
+ PAIMON_RETURN_NOT_OK_FROM_ARROW(
+ arrow::ExportArray(*full_struct, c_array.get(), c_schema.get()));
+ return std::make_pair(std::move(c_array), std::move(c_schema));
+}
+
+Status LateMaterializingFileBatchReader::SetInnerReadSchema(
+ const std::shared_ptr<arrow::Schema>& read_schema, const std::shared_ptr<Predicate>& predicate,
+ const std::optional<RoaringBitmap32>& selection) {
+ ::ArrowSchema c_read_schema;
+ PAIMON_RETURN_NOT_OK_FROM_ARROW(arrow::ExportSchema(*read_schema, &c_read_schema));
+ /// Note: calling inner->SetReadSchema may refresh the read ranges of the inner reader.
+ PAIMON_RETURN_NOT_OK(inner_->SetReadSchema(&c_read_schema, predicate, selection));
+ if (!read_ranges_.empty()) {
+ PAIMON_RETURN_NOT_OK(inner_->SetReadRanges(read_ranges_));
+ }
+ return Status::OK();
+}
+
+Status LateMaterializingFileBatchReader::SetReadSchema(
+ ::ArrowSchema* read_schema, const std::shared_ptr<Predicate>& predicate,
+ const std::optional<RoaringBitmap32>& selection_bitmap) {
+ PAIMON_ASSIGN_OR_RAISE_FROM_ARROW(full_schema_, arrow::ImportSchema(read_schema));
+ predicate_ = predicate;
+ selection_ = selection_bitmap;
+ matched_bitmap_ = RoaringBitmap32();
+ probe_data_.reset();
+ probe_cursor_ = 0;
+ row_mapping_.clear();
+ probe_schema_.reset();
+ payload_schema_.reset();
+ probe_filter_.reset();
+ if (predicate_ != nullptr) {
+ std::set<std::string> probe_names;
+ PAIMON_RETURN_NOT_OK(PredicateUtils::GetAllNames(predicate_, &probe_names));
+ arrow::FieldVector probe_fields;
+ arrow::FieldVector payload_fields;
+ for (const auto& field : full_schema_->fields()) {
+ if (probe_names.count(field->name()) > 0) {
+ probe_fields.push_back(field);
+ } else {
+ payload_fields.push_back(field);
+ }
+ }
+ // probing only pays off when the predicate fields are a strict subset of the read schema
+ if (!probe_fields.empty() && !payload_fields.empty()) {
+ probe_schema_ = arrow::schema(probe_fields, full_schema_->metadata());
+ payload_schema_ = arrow::schema(payload_fields, full_schema_->metadata());
+ PAIMON_RETURN_NOT_OK(PredicateValidator::ValidatePredicateWithSchema(
Review Comment:
In most case of our code, metadata is `nullptr`, `schema` is contructed with metadata here is simply a defensive passthrough.
--
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: issues-unsubscribe@paimon.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(reader): support late materialization with probe/payload two-phase reads [paimon-cpp]
Posted by "lxy-9602 (via GitHub)" <gi...@apache.org>.
lxy-9602 commented on code in PR #243:
URL: https://github.com/apache/paimon-cpp/pull/243#discussion_r3860852895
##########
src/paimon/common/reader/late_materializing_file_batch_reader_test.cpp:
##########
@@ -0,0 +1,647 @@
+/*
+ * 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.
+ */
+
+#include "paimon/common/reader/late_materializing_file_batch_reader.h"
+
+#include <algorithm>
+#include <cstdint>
+#include <limits>
+#include <memory>
+#include <optional>
+#include <string>
+#include <utility>
+#include <vector>
+
+#include "arrow/api.h"
+#include "arrow/array/builder_nested.h"
+#include "arrow/c/bridge.h"
+#include "gtest/gtest.h"
+#include "paimon/common/reader/late_materializing_reader_builder.h"
+#include "paimon/common/reader/prefetch_file_batch_reader_impl.h"
+#include "paimon/common/reader/reader_utils.h"
+#include "paimon/common/utils/arrow/status_utils.h"
+#include "paimon/common/utils/checked_cast.h"
+#include "paimon/common/utils/read_ahead_cache.h"
+#include "paimon/executor.h"
+#include "paimon/format/reader_builder.h"
+#include "paimon/memory/memory_pool.h"
+#include "paimon/predicate/literal.h"
+#include "paimon/predicate/predicate.h"
+#include "paimon/predicate/predicate_builder.h"
+#include "paimon/reader/prefetch_file_batch_reader.h"
+#include "paimon/status.h"
+#include "paimon/testing/mock/mock_file_batch_reader.h"
+#include "paimon/testing/mock/mock_file_system.h"
+#include "paimon/testing/mock/mock_format_reader_builder.h"
+#include "paimon/testing/utils/read_result_collector.h"
+#include "paimon/testing/utils/testharness.h"
+#include "paimon/utils/roaring_bitmap32.h"
+
+namespace paimon::test {
+
+class LateMaterializingFileBatchReaderTest : public ::testing::Test {
+ public:
+ void SetUp() override {
+ k_field_ = arrow::field("k", arrow::int64());
+ v_field_ = arrow::field("v", arrow::utf8());
+ full_fields_ = {k_field_, v_field_};
+ full_type_ = arrow::struct_(full_fields_);
+ }
+
+ // Build a struct array with column k (int64, values = ks) and column v (utf8, "v_<index>").
+ std::shared_ptr<arrow::Array> BuildData(const std::vector<int64_t>& ks) {
+ arrow::StructBuilder builder(
+ full_type_, arrow::default_memory_pool(),
+ {std::make_shared<arrow::Int64Builder>(), std::make_shared<arrow::StringBuilder>()});
+ auto* k_builder = checked_cast<arrow::Int64Builder*>(builder.field_builder(0));
+ auto* v_builder = checked_cast<arrow::StringBuilder*>(builder.field_builder(1));
+ for (size_t i = 0; i < ks.size(); ++i) {
+ EXPECT_TRUE(builder.Append().ok());
+ EXPECT_TRUE(k_builder->Append(ks[i]).ok());
+ EXPECT_TRUE(v_builder->Append("v_" + std::to_string(i)).ok());
+ }
+ std::shared_ptr<arrow::Array> array;
+ EXPECT_TRUE(builder.Finish(&array).ok());
+ return array;
+ }
+
+ struct Row {
+ int64_t k;
+ std::string v;
+ uint64_t file_row;
+ };
+
+ // Drive the reader through NextBatchWithBitmap to EOF, decoding the full-schema output rows.
+ Result<std::vector<Row>> Collect(LateMaterializingFileBatchReader* reader) {
+ std::vector<Row> rows;
+ while (true) {
+ PAIMON_ASSIGN_OR_RAISE(BatchReader::ReadBatchWithBitmap batch_with_bitmap,
+ reader->NextBatchWithBitmap());
+ if (BatchReader::IsEofBatch(batch_with_bitmap)) {
+ break;
+ }
+ auto& [batch, bitmap] = batch_with_bitmap;
+ auto& [c_array, c_schema] = batch;
+ PAIMON_ASSIGN_OR_RAISE_FROM_ARROW(std::shared_ptr<arrow::Array> array,
+ arrow::ImportArray(c_array.get(), c_schema.get()));
+ auto struct_array = arrow::internal::checked_pointer_cast<arrow::StructArray>(array);
+ EXPECT_EQ(bitmap.Cardinality(), static_cast<int32_t>(struct_array->length()));
+ auto k_array = arrow::internal::checked_pointer_cast<arrow::Int64Array>(
+ struct_array->GetFieldByName("k"));
+ if (!k_array) {
+ return Status::Invalid("output batch missing k column");
+ }
+ // v is only present when it belongs to the read schema (payload projection).
+ auto v_array = arrow::internal::checked_pointer_cast<arrow::StringArray>(
+ struct_array->GetFieldByName("v"));
+ for (int64_t i = 0; i < struct_array->length(); ++i) {
+ PAIMON_ASSIGN_OR_RAISE(uint64_t file_row,
+ reader->GetPreviousBatchFileRowId(static_cast<uint64_t>(i)));
+ rows.push_back(Row{k_array->Value(i),
+ v_array ? v_array->GetString(i) : std::string(), file_row});
+ }
+ }
+ return rows;
+ }
+
+ Status SetReadSchema(LateMaterializingFileBatchReader* reader,
+ const std::shared_ptr<arrow::Schema>& schema,
+ const std::shared_ptr<Predicate>& predicate,
+ const std::optional<RoaringBitmap32>& selection) {
+ ::ArrowSchema c_schema;
+ PAIMON_RETURN_NOT_OK_FROM_ARROW(arrow::ExportSchema(*schema, &c_schema));
+ return reader->SetReadSchema(&c_schema, predicate, selection);
+ }
+
+ // Collect all output rows as a single concatenated struct array (for schema/nested checks),
+ // reusing the shared collector so the batch-offset and bitmap contracts are checked too.
+ Result<std::shared_ptr<arrow::StructArray>> CollectStruct(FileBatchReader* reader) {
+ PAIMON_ASSIGN_OR_RAISE(std::shared_ptr<arrow::ChunkedArray> chunked,
+ ReadResultCollector::CollectResult(reader));
+ if (chunked == nullptr) {
+ return std::shared_ptr<arrow::StructArray>();
+ }
+ PAIMON_ASSIGN_OR_RAISE_FROM_ARROW(std::shared_ptr<arrow::Array> combined,
+ arrow::Concatenate(chunked->chunks()));
+ return arrow::internal::checked_pointer_cast<arrow::StructArray>(combined);
+ }
+
+ // Build a struct with 5 columns [a:int64, b:utf8, c:int64, d:utf8, e:int64], each carrying a
+ // distinct value pattern so any column reordering is detected.
+ std::shared_ptr<arrow::Array> BuildMultiFieldData(int32_t n) {
+ auto type =
+ arrow::struct_({arrow::field("a", arrow::int64()), arrow::field("b", arrow::utf8()),
+ arrow::field("c", arrow::int64()), arrow::field("d", arrow::utf8()),
+ arrow::field("e", arrow::int64())});
+ arrow::StructBuilder builder(
+ type, arrow::default_memory_pool(),
+ {std::make_shared<arrow::Int64Builder>(), std::make_shared<arrow::StringBuilder>(),
+ std::make_shared<arrow::Int64Builder>(), std::make_shared<arrow::StringBuilder>(),
+ std::make_shared<arrow::Int64Builder>()});
+ auto* a = checked_cast<arrow::Int64Builder*>(builder.field_builder(0));
+ auto* b = checked_cast<arrow::StringBuilder*>(builder.field_builder(1));
+ auto* c = checked_cast<arrow::Int64Builder*>(builder.field_builder(2));
+ auto* d = checked_cast<arrow::StringBuilder*>(builder.field_builder(3));
+ auto* e = checked_cast<arrow::Int64Builder*>(builder.field_builder(4));
+ for (int32_t i = 0; i < n; ++i) {
+ EXPECT_TRUE(builder.Append().ok());
+ EXPECT_TRUE(a->Append(i).ok());
+ EXPECT_TRUE(b->Append("b_" + std::to_string(i)).ok());
+ EXPECT_TRUE(c->Append(static_cast<int64_t>(i) * 100).ok());
+ EXPECT_TRUE(d->Append("d_" + std::to_string(i)).ok());
+ EXPECT_TRUE(e->Append(static_cast<int64_t>(i) * 10000).ok());
+ }
+ std::shared_ptr<arrow::Array> array;
+ EXPECT_TRUE(builder.Finish(&array).ok());
+ return array;
+ }
+
+ // Build a struct with a nested payload column [k:int64, arr:list<int64>, tag:utf8].
+ std::shared_ptr<arrow::Array> BuildNestedData(int32_t n) {
+ auto type = arrow::struct_({arrow::field("k", arrow::int64()),
+ arrow::field("arr", arrow::list(arrow::int64())),
+ arrow::field("tag", arrow::utf8())});
+ auto arr_value_builder = std::make_shared<arrow::Int64Builder>();
+ arrow::StructBuilder builder(
+ type, arrow::default_memory_pool(),
+ {std::make_shared<arrow::Int64Builder>(),
+ std::make_shared<arrow::ListBuilder>(arrow::default_memory_pool(), arr_value_builder),
+ std::make_shared<arrow::StringBuilder>()});
+ auto* k = checked_cast<arrow::Int64Builder*>(builder.field_builder(0));
+ auto* arr = checked_cast<arrow::ListBuilder*>(builder.field_builder(1));
+ auto* arr_values = checked_cast<arrow::Int64Builder*>(arr->value_builder());
+ auto* tag = checked_cast<arrow::StringBuilder*>(builder.field_builder(2));
+ for (int32_t i = 0; i < n; ++i) {
+ EXPECT_TRUE(builder.Append().ok());
+ EXPECT_TRUE(k->Append(i).ok());
+ EXPECT_TRUE(arr->Append().ok());
+ EXPECT_TRUE(arr_values->Append(i).ok());
+ EXPECT_TRUE(arr_values->Append(i + 1).ok());
+ EXPECT_TRUE(tag->Append("t_" + std::to_string(i)).ok());
+ }
+ std::shared_ptr<arrow::Array> array;
+ EXPECT_TRUE(builder.Finish(&array).ok());
+ return array;
+ }
+
+ protected:
+ std::shared_ptr<arrow::Field> k_field_;
+ std::shared_ptr<arrow::Field> v_field_;
+ arrow::FieldVector full_fields_;
+ std::shared_ptr<arrow::DataType> full_type_;
+};
+
+// No predicate: the reader must pass through the inner reader unchanged (all rows, all columns).
+TEST_F(LateMaterializingFileBatchReaderTest, PassThroughWhenNoPredicate) {
+ auto data = BuildData({0, 1, 2, 3, 4});
+ auto mock = std::make_unique<MockFileBatchReader>(data, full_type_, /*batch_size=*/2);
+ ASSERT_OK_AND_ASSIGN(
+ auto reader, LateMaterializingFileBatchReader::Create(std::move(mock), GetDefaultPool()));
+ ASSERT_OK(SetReadSchema(reader.get(), arrow::schema(full_fields_), /*predicate=*/nullptr,
+ std::nullopt));
+
+ ASSERT_OK_AND_ASSIGN(std::vector<Row> rows, Collect(reader.get()));
+ ASSERT_EQ(rows.size(), 5u);
+ for (int64_t i = 0; i < 5; ++i) {
+ EXPECT_EQ(rows[i].k, i);
+ EXPECT_EQ(rows[i].v, "v_" + std::to_string(i));
+ EXPECT_EQ(rows[i].file_row, static_cast<uint64_t>(i));
+ }
+}
+
+// The predicate references every projected column, so the payload set is empty: no late
+// materialization, plain pass-through.
+TEST_F(LateMaterializingFileBatchReaderTest, PassThroughWhenPayloadEmpty) {
+ auto data = BuildData({0, 1, 2, 3, 4});
+ auto mock = std::make_unique<MockFileBatchReader>(data, full_type_, /*batch_size=*/2);
+ ASSERT_OK_AND_ASSIGN(
+ auto reader, LateMaterializingFileBatchReader::Create(std::move(mock), GetDefaultPool()));
+ // read schema is just {k}; the predicate on k covers all columns -> payload empty
+ auto predicate = PredicateBuilder::GreaterOrEqual(/*field_index=*/0, /*field_name=*/"k",
+ FieldType::BIGINT, Literal(0l));
+ ASSERT_OK(SetReadSchema(reader.get(), arrow::schema({k_field_}), predicate, std::nullopt));
+
+ ASSERT_OK_AND_ASSIGN(std::vector<Row> rows, Collect(reader.get()));
+ ASSERT_EQ(rows.size(), 5u);
+}
+
+// Contiguous matched subset spanning multiple batches.
+TEST_F(LateMaterializingFileBatchReaderTest, ContiguousSubsetAcrossBatches) {
+ auto data = BuildData({0, 1, 2, 3, 4, 5, 6, 7, 8, 9});
+ auto mock = std::make_unique<MockFileBatchReader>(data, full_type_, /*batch_size=*/3);
+ ASSERT_OK_AND_ASSIGN(
+ auto reader, LateMaterializingFileBatchReader::Create(std::move(mock), GetDefaultPool()));
+ auto predicate = PredicateBuilder::GreaterThan(/*field_index=*/0, /*field_name=*/"k",
+ FieldType::BIGINT, Literal(4l));
+ ASSERT_OK(SetReadSchema(reader.get(), arrow::schema(full_fields_), predicate, std::nullopt));
+
+ ASSERT_OK_AND_ASSIGN(std::vector<Row> rows, Collect(reader.get()));
+ ASSERT_EQ(rows.size(), 5u); // k = 5..9
+ for (size_t idx = 0; idx < rows.size(); ++idx) {
+ int64_t expected = 5 + static_cast<int64_t>(idx);
+ EXPECT_EQ(rows[idx].k, expected);
+ EXPECT_EQ(rows[idx].v, "v_" + std::to_string(expected));
+ EXPECT_EQ(rows[idx].file_row, static_cast<uint64_t>(expected));
+ }
+}
+
+// Scattered (alternating) matched rows: predicate matches every other row.
+TEST_F(LateMaterializingFileBatchReaderTest, ScatteredAlternatingMatch) {
+ // k = 0,1,0,1,... ; predicate k == 1 matches all odd file rows.
+ std::vector<int64_t> ks;
+ for (int i = 0; i < 12; ++i) {
+ ks.push_back(i % 2);
+ }
+ auto data = BuildData(ks);
+ auto mock = std::make_unique<MockFileBatchReader>(data, full_type_, /*batch_size=*/3);
+ ASSERT_OK_AND_ASSIGN(
+ auto reader, LateMaterializingFileBatchReader::Create(std::move(mock), GetDefaultPool()));
+ auto predicate = PredicateBuilder::Equal(/*field_index=*/0, /*field_name=*/"k",
+ FieldType::BIGINT, Literal(1l));
+ ASSERT_OK(SetReadSchema(reader.get(), arrow::schema(full_fields_), predicate, std::nullopt));
+
+ ASSERT_OK_AND_ASSIGN(std::vector<Row> rows, Collect(reader.get()));
+ ASSERT_EQ(rows.size(), 6u); // odd rows 1,3,5,7,9,11
+ for (size_t idx = 0; idx < rows.size(); ++idx) {
+ uint64_t expected_row = 2 * idx + 1;
+ EXPECT_EQ(rows[idx].k, 1);
+ EXPECT_EQ(rows[idx].v, "v_" + std::to_string(expected_row));
+ EXPECT_EQ(rows[idx].file_row, expected_row);
+ }
+}
+
+// The selection bitmap further restricts the matched rows: matched must be a subset of selection.
+TEST_F(LateMaterializingFileBatchReaderTest, MatchedIntersectsSelection) {
+ std::vector<int64_t> ks;
+ for (int i = 0; i < 12; ++i) {
+ ks.push_back(i % 2);
+ }
+ auto data = BuildData(ks);
+ auto mock = std::make_unique<MockFileBatchReader>(data, full_type_, /*batch_size=*/4);
+ ASSERT_OK_AND_ASSIGN(
+ auto reader, LateMaterializingFileBatchReader::Create(std::move(mock), GetDefaultPool()));
+ auto predicate = PredicateBuilder::Equal(/*field_index=*/0, /*field_name=*/"k",
+ FieldType::BIGINT, Literal(1l));
+ // predicate hits {1,3,5,7,9,11}; selection keeps only {1,5,9}
+ RoaringBitmap32 selection;
+ selection.Add(1);
+ selection.Add(5);
+ selection.Add(9);
+ ASSERT_OK(SetReadSchema(reader.get(), arrow::schema(full_fields_), predicate,
+ std::optional<RoaringBitmap32>(selection)));
+
+ ASSERT_OK_AND_ASSIGN(std::vector<Row> rows, Collect(reader.get()));
+ ASSERT_EQ(rows.size(), 3u);
+ EXPECT_EQ(rows[0].file_row, 1u);
+ EXPECT_EQ(rows[1].file_row, 5u);
+ EXPECT_EQ(rows[2].file_row, 9u);
+ EXPECT_EQ(rows[0].v, "v_1");
+ EXPECT_EQ(rows[1].v, "v_5");
+ EXPECT_EQ(rows[2].v, "v_9");
+}
+
+// No matched rows: the reader returns EOF immediately.
+TEST_F(LateMaterializingFileBatchReaderTest, EmptyMatchReturnsEof) {
+ auto data = BuildData({0, 1, 2, 3, 4});
+ auto mock = std::make_unique<MockFileBatchReader>(data, full_type_, /*batch_size=*/2);
+ ASSERT_OK_AND_ASSIGN(
+ auto reader, LateMaterializingFileBatchReader::Create(std::move(mock), GetDefaultPool()));
+ auto predicate = PredicateBuilder::GreaterThan(/*field_index=*/0, /*field_name=*/"k",
+ FieldType::BIGINT, Literal(100l));
+ ASSERT_OK(SetReadSchema(reader.get(), arrow::schema(full_fields_), predicate, std::nullopt));
+
+ ASSERT_OK_AND_ASSIGN(std::vector<Row> rows, Collect(reader.get()));
+ ASSERT_TRUE(rows.empty());
+}
+
+// SeekToRow during payload emission must re-align the probe cursor so probe/payload stay matched.
+TEST_F(LateMaterializingFileBatchReaderTest, SeekToRowRealignsProbeCursor) {
+ auto data = BuildData({0, 1, 2, 3, 4, 5, 6, 7, 8, 9});
+ auto mock = std::make_unique<MockFileBatchReader>(data, full_type_, /*batch_size=*/4);
+ ASSERT_OK_AND_ASSIGN(
+ auto reader, LateMaterializingFileBatchReader::Create(std::move(mock), GetDefaultPool()));
+ auto predicate = PredicateBuilder::GreaterOrEqual(/*field_index=*/0, /*field_name=*/"k",
+ FieldType::BIGINT, Literal(5l));
+ ASSERT_OK(SetReadSchema(reader.get(), arrow::schema(full_fields_), predicate, std::nullopt));
+
+ // First payload batch triggers the probe scan; matched rows are 5..9.
+ ASSERT_OK_AND_ASSIGN(BatchReader::ReadBatchWithBitmap first, reader->NextBatchWithBitmap());
+ ASSERT_FALSE(BatchReader::IsEofBatch(first));
+ ReaderUtils::ReleaseReadBatch(std::move(first.first));
+
+ // Seek forward to file row 8: subsequent output must be exactly rows 8 and 9, correctly paired.
+ ASSERT_OK(reader->SeekToRow(8));
+ ASSERT_OK_AND_ASSIGN(std::vector<Row> rows, Collect(reader.get()));
+ ASSERT_EQ(rows.size(), 2u);
+ EXPECT_EQ(rows[0].k, 8);
+ EXPECT_EQ(rows[0].v, "v_8");
+ EXPECT_EQ(rows[0].file_row, 8u);
+ EXPECT_EQ(rows[1].k, 9);
+ EXPECT_EQ(rows[1].v, "v_9");
+ EXPECT_EQ(rows[1].file_row, 9u);
+}
+
+// SetReadRanges must be cached and re-forwarded to the inner reader across the probe/payload
+// schema switches (SetReadSchema resets the inner reader's ranges).
+TEST_F(LateMaterializingFileBatchReaderTest, ReadRangesForwardedAcrossPhases) {
+ auto data = BuildData({0, 1, 2, 3, 4, 5, 6, 7});
+ auto mock = std::make_unique<MockFileBatchReader>(data, full_type_, /*batch_size=*/4);
+ auto* mock_ptr = mock.get();
+ ASSERT_OK_AND_ASSIGN(
+ auto reader, LateMaterializingFileBatchReader::Create(std::move(mock), GetDefaultPool()));
+ auto predicate = PredicateBuilder::GreaterOrEqual(/*field_index=*/0, /*field_name=*/"k",
+ FieldType::BIGINT, Literal(2l));
+ ASSERT_OK(SetReadSchema(reader.get(), arrow::schema(full_fields_), predicate, std::nullopt));
+
+ std::vector<std::pair<uint64_t, uint64_t>> ranges = {{0, 8}};
+ ASSERT_OK(reader->SetReadRanges(ranges));
+
+ // Drive to EOF; this performs the probe pass and the payload schema switch.
+ ASSERT_OK_AND_ASSIGN(std::vector<Row> rows, Collect(reader.get()));
+ ASSERT_EQ(rows.size(), 6u); // k = 2..7
+
+ // The inner reader must have received the cached ranges again after the payload switch.
+ // SetReadSchema (invoked on the payload switch) clears the inner reader's ranges, so the
+ // cached ranges still being present at the end proves LM re-forwarded them after the switch.
+ ASSERT_EQ(mock_ptr->GetReadRanges(), ranges);
+}
+
+// SetReadSchema is re-entrant: a second call with a different predicate resets probe state.
+TEST_F(LateMaterializingFileBatchReaderTest, ReentrantSetReadSchema) {
+ auto data = BuildData({0, 1, 2, 3, 4, 5, 6, 7, 8, 9});
+ auto mock = std::make_unique<MockFileBatchReader>(data, full_type_, /*batch_size=*/3);
+ ASSERT_OK_AND_ASSIGN(
+ auto reader, LateMaterializingFileBatchReader::Create(std::move(mock), GetDefaultPool()));
+
+ auto predicate1 = PredicateBuilder::GreaterThan(/*field_index=*/0, /*field_name=*/"k",
+ FieldType::BIGINT, Literal(7l));
+ ASSERT_OK(SetReadSchema(reader.get(), arrow::schema(full_fields_), predicate1, std::nullopt));
+ ASSERT_OK_AND_ASSIGN(std::vector<Row> rows1, Collect(reader.get()));
+ ASSERT_EQ(rows1.size(), 2u); // k = 8,9
+
+ auto predicate2 = PredicateBuilder::LessThan(/*field_index=*/0, /*field_name=*/"k",
+ FieldType::BIGINT, Literal(3l));
+ ASSERT_OK(SetReadSchema(reader.get(), arrow::schema(full_fields_), predicate2, std::nullopt));
+ ASSERT_OK_AND_ASSIGN(std::vector<Row> rows2, Collect(reader.get()));
+ ASSERT_EQ(rows2.size(), 3u); // k = 0,1,2
+ for (size_t idx = 0; idx < rows2.size(); ++idx) {
+ EXPECT_EQ(rows2[idx].k, static_cast<int64_t>(idx));
+ EXPECT_EQ(rows2[idx].file_row, static_cast<uint64_t>(idx));
+ }
+}
+
+// Forwarded metadata accessors should reflect the inner reader.
+TEST_F(LateMaterializingFileBatchReaderTest, ForwardsRowCountAndFileSchema) {
+ auto data = BuildData({0, 1, 2, 3});
+ auto mock = std::make_unique<MockFileBatchReader>(data, full_type_, /*batch_size=*/2);
+ ASSERT_OK_AND_ASSIGN(
+ auto reader, LateMaterializingFileBatchReader::Create(std::move(mock), GetDefaultPool()));
+
+ ASSERT_OK_AND_ASSIGN(uint64_t num_rows, reader->GetNumberOfRows());
+ EXPECT_EQ(num_rows, 4u);
+ ASSERT_OK_AND_ASSIGN(std::unique_ptr<::ArrowSchema> c_file_schema, reader->GetFileSchema());
+ auto import_result = arrow::ImportType(c_file_schema.get());
+ ASSERT_TRUE(import_result.ok());
+ EXPECT_TRUE(import_result.ValueOrDie()->Equals(full_type_));
+}
+
+// With many columns and a predicate over two non-adjacent probe columns, the output must keep the
+// full read-schema field order (and each probe/payload column's values must not be scrambled).
+TEST_F(LateMaterializingFileBatchReaderTest, MultiFieldPreservesColumnOrder) {
+ auto data = BuildMultiFieldData(10);
+ auto type = data->type();
+ auto mock = std::make_unique<MockFileBatchReader>(data, type, /*batch_size=*/3);
+ ASSERT_OK_AND_ASSIGN(
+ auto reader, LateMaterializingFileBatchReader::Create(std::move(mock), GetDefaultPool()));
+ // probe columns = {a (idx0), c (idx2)}; payload columns = {b, d, e}
+ auto pred_a =
+ PredicateBuilder::GreaterOrEqual(/*field_index=*/0, "a", FieldType::BIGINT, Literal(3l));
+ auto pred_c =
+ PredicateBuilder::LessThan(/*field_index=*/2, "c", FieldType::BIGINT, Literal(700l));
+ ASSERT_OK_AND_ASSIGN(auto predicate, PredicateBuilder::And({pred_a, pred_c}));
+ ASSERT_OK(SetReadSchema(reader.get(), arrow::schema(type->fields()), predicate, std::nullopt));
+
+ ASSERT_OK_AND_ASSIGN(std::shared_ptr<arrow::StructArray> result, CollectStruct(reader.get()));
+ ASSERT_TRUE(result);
+ // a >= 3 and c(=i*100) < 700 -> i in {3,4,5,6}
+ ASSERT_EQ(result->length(), 4);
+ // output field order must equal the requested full schema order
+ ASSERT_EQ(result->num_fields(), 5);
+ auto out_type = arrow::internal::checked_pointer_cast<arrow::StructType>(result->type());
+ EXPECT_EQ(out_type->field(0)->name(), "a");
+ EXPECT_EQ(out_type->field(1)->name(), "b");
+ EXPECT_EQ(out_type->field(2)->name(), "c");
+ EXPECT_EQ(out_type->field(3)->name(), "d");
+ EXPECT_EQ(out_type->field(4)->name(), "e");
+ auto a = arrow::internal::checked_pointer_cast<arrow::Int64Array>(result->GetFieldByName("a"));
+ auto b = arrow::internal::checked_pointer_cast<arrow::StringArray>(result->GetFieldByName("b"));
+ auto c = arrow::internal::checked_pointer_cast<arrow::Int64Array>(result->GetFieldByName("c"));
+ auto d = arrow::internal::checked_pointer_cast<arrow::StringArray>(result->GetFieldByName("d"));
+ auto e = arrow::internal::checked_pointer_cast<arrow::Int64Array>(result->GetFieldByName("e"));
+ const std::vector<int64_t> expected = {3, 4, 5, 6};
+ for (size_t j = 0; j < expected.size(); ++j) {
+ int64_t i = expected[j];
+ EXPECT_EQ(a->Value(j), i);
+ EXPECT_EQ(b->GetString(j), "b_" + std::to_string(i));
+ EXPECT_EQ(c->Value(j), i * 100);
+ EXPECT_EQ(d->GetString(j), "d_" + std::to_string(i));
+ EXPECT_EQ(e->Value(j), i * 10000);
+ }
+}
+
+// A nested (list) payload column must round-trip unchanged for the matched rows.
+TEST_F(LateMaterializingFileBatchReaderTest, NestedPayloadColumn) {
+ auto data = BuildNestedData(8);
+ auto type = data->type();
+ auto mock = std::make_unique<MockFileBatchReader>(data, type, /*batch_size=*/3);
+ ASSERT_OK_AND_ASSIGN(
+ auto reader, LateMaterializingFileBatchReader::Create(std::move(mock), GetDefaultPool()));
+ // probe = {k}; payload = {arr (list<int64>), tag}
+ auto predicate =
+ PredicateBuilder::GreaterOrEqual(/*field_index=*/0, "k", FieldType::BIGINT, Literal(5l));
+ ASSERT_OK(SetReadSchema(reader.get(), arrow::schema(type->fields()), predicate, std::nullopt));
+
+ ASSERT_OK_AND_ASSIGN(std::shared_ptr<arrow::StructArray> result, CollectStruct(reader.get()));
+ ASSERT_TRUE(result);
+ ASSERT_EQ(result->length(), 3); // k = 5,6,7
Review Comment:
How about just writing the JSON result by hand? It’s only three lines anyway.
--
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: issues-unsubscribe@paimon.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(reader): support late materialization with probe/payload two-phase reads [paimon-cpp]
Posted by "zhf999 (via GitHub)" <gi...@apache.org>.
zhf999 commented on code in PR #243:
URL: https://github.com/apache/paimon-cpp/pull/243#discussion_r3860105376
##########
test/inte/scan_and_read_inte_test.cpp:
##########
@@ -744,6 +744,47 @@ TEST_P(ScanAndReadInteTest, TestWithPKWithDvBatchScanSnapshot6WithPredicate) {
ASSERT_TRUE(expected->Equals(read_result)) << read_result->ToString();
}
+TEST_P(ScanAndReadInteTest, TestWithPKWithDvBatchScanSnapshot6WithLateMaterializing) {
+ auto file_format = FileFormat();
+ std::string table_path = paimon::test::GetDataDir() + file_format +
+ "/pk_table_scan_and_read_dv.db/pk_table_scan_and_read_dv/";
+ ScanContextBuilder scan_context_builder(table_path);
+ scan_context_builder.AddOption(Options::SCAN_SNAPSHOT_ID, "6");
+
+ std::string literal_str = "Alice";
+ auto not_equal = PredicateBuilder::NotEqual(
+ /*field_index=*/0, /*field_name=*/"f0", FieldType::STRING,
+ Literal(FieldType::STRING, literal_str.data(), literal_str.size()));
+ auto greater_than = PredicateBuilder::GreaterThan(/*field_index=*/3, /*field_name=*/"f3",
+ FieldType::DOUBLE, Literal(18.0));
+ ASSERT_OK_AND_ASSIGN(auto predicate, PredicateBuilder::And({not_equal, greater_than}));
+ scan_context_builder.SetPredicate(predicate);
+ ASSERT_OK_AND_ASSIGN(auto scan_context, FinishScanContext(scan_context_builder));
+ ASSERT_OK_AND_ASSIGN(auto table_scan, TableScan::Create(std::move(scan_context)));
+
+ ReadContextBuilder read_context_builder(table_path);
+ AddReadOptionsForPrefetch(&read_context_builder);
+ read_context_builder.SetPredicate(predicate)
+ .EnablePredicateFilter(true)
+ .EnableLateMaterializing(true);
Review Comment:
Done.
##########
src/paimon/common/reader/late_materializing_file_batch_reader_test.cpp:
##########
@@ -0,0 +1,658 @@
+/*
+ * 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.
+ */
+
+#include "paimon/common/reader/late_materializing_file_batch_reader.h"
+
+#include <algorithm>
+#include <cstdint>
+#include <limits>
+#include <memory>
+#include <optional>
+#include <string>
+#include <utility>
+#include <vector>
+
+#include "arrow/api.h"
+#include "arrow/array/builder_nested.h"
+#include "arrow/c/bridge.h"
+#include "gtest/gtest.h"
+#include "paimon/common/reader/late_materializing_reader_builder.h"
+#include "paimon/common/reader/prefetch_file_batch_reader_impl.h"
+#include "paimon/common/reader/reader_utils.h"
+#include "paimon/common/utils/arrow/status_utils.h"
+#include "paimon/common/utils/checked_cast.h"
+#include "paimon/common/utils/read_ahead_cache.h"
+#include "paimon/executor.h"
+#include "paimon/format/reader_builder.h"
+#include "paimon/memory/memory_pool.h"
+#include "paimon/predicate/literal.h"
+#include "paimon/predicate/predicate.h"
+#include "paimon/predicate/predicate_builder.h"
+#include "paimon/reader/prefetch_file_batch_reader.h"
+#include "paimon/status.h"
+#include "paimon/testing/mock/mock_file_batch_reader.h"
+#include "paimon/testing/mock/mock_file_system.h"
+#include "paimon/testing/mock/mock_format_reader_builder.h"
+#include "paimon/testing/utils/testharness.h"
+#include "paimon/utils/roaring_bitmap32.h"
+
+namespace paimon::test {
+
+class LateMaterializingFileBatchReaderTest : public ::testing::Test {
+ public:
+ void SetUp() override {
+ k_field_ = arrow::field("k", arrow::int64());
+ v_field_ = arrow::field("v", arrow::utf8());
+ full_fields_ = {k_field_, v_field_};
+ full_type_ = arrow::struct_(full_fields_);
+ }
+
+ // Build a struct array with column k (int64, values = ks) and column v (utf8, "v_<index>").
+ std::shared_ptr<arrow::Array> BuildData(const std::vector<int64_t>& ks) {
+ arrow::StructBuilder builder(
+ full_type_, arrow::default_memory_pool(),
+ {std::make_shared<arrow::Int64Builder>(), std::make_shared<arrow::StringBuilder>()});
+ auto* k_builder = checked_cast<arrow::Int64Builder*>(builder.field_builder(0));
+ auto* v_builder = checked_cast<arrow::StringBuilder*>(builder.field_builder(1));
+ for (size_t i = 0; i < ks.size(); ++i) {
+ EXPECT_TRUE(builder.Append().ok());
+ EXPECT_TRUE(k_builder->Append(ks[i]).ok());
+ EXPECT_TRUE(v_builder->Append("v_" + std::to_string(i)).ok());
+ }
+ std::shared_ptr<arrow::Array> array;
+ EXPECT_TRUE(builder.Finish(&array).ok());
+ return array;
+ }
+
+ struct Row {
+ int64_t k;
+ std::string v;
+ uint64_t file_row;
+ };
+
+ // Drive the reader through NextBatchWithBitmap to EOF, decoding the full-schema output rows.
+ Result<std::vector<Row>> Collect(LateMaterializingFileBatchReader* reader) {
+ std::vector<Row> rows;
+ while (true) {
+ PAIMON_ASSIGN_OR_RAISE(BatchReader::ReadBatchWithBitmap batch_with_bitmap,
+ reader->NextBatchWithBitmap());
+ if (BatchReader::IsEofBatch(batch_with_bitmap)) {
+ break;
+ }
+ auto& [batch, bitmap] = batch_with_bitmap;
+ auto& [c_array, c_schema] = batch;
+ PAIMON_ASSIGN_OR_RAISE_FROM_ARROW(std::shared_ptr<arrow::Array> array,
+ arrow::ImportArray(c_array.get(), c_schema.get()));
+ auto struct_array = arrow::internal::checked_pointer_cast<arrow::StructArray>(array);
+ EXPECT_EQ(bitmap.Cardinality(), static_cast<int32_t>(struct_array->length()));
+ auto k_array = arrow::internal::checked_pointer_cast<arrow::Int64Array>(
+ struct_array->GetFieldByName("k"));
+ if (!k_array) {
+ return Status::Invalid("output batch missing k column");
+ }
+ // v is only present when it belongs to the read schema (payload projection).
+ auto v_array = arrow::internal::checked_pointer_cast<arrow::StringArray>(
+ struct_array->GetFieldByName("v"));
+ for (int64_t i = 0; i < struct_array->length(); ++i) {
+ PAIMON_ASSIGN_OR_RAISE(uint64_t file_row,
+ reader->GetPreviousBatchFileRowId(static_cast<uint64_t>(i)));
+ rows.push_back(Row{k_array->Value(i),
+ v_array ? v_array->GetString(i) : std::string(), file_row});
+ }
+ }
+ return rows;
+ }
+
+ Status SetReadSchema(LateMaterializingFileBatchReader* reader,
+ const std::shared_ptr<arrow::Schema>& schema,
+ const std::shared_ptr<Predicate>& predicate,
+ const std::optional<RoaringBitmap32>& selection) {
+ ::ArrowSchema c_schema;
+ PAIMON_RETURN_NOT_OK_FROM_ARROW(arrow::ExportSchema(*schema, &c_schema));
+ return reader->SetReadSchema(&c_schema, predicate, selection);
+ }
+
+ // Collect all output rows as a single concatenated struct array (for schema/nested checks).
+ Result<std::shared_ptr<arrow::StructArray>> CollectStruct(FileBatchReader* reader) {
+ arrow::ArrayVector chunks;
Review Comment:
Done.
--
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: issues-unsubscribe@paimon.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(reader): support late materialization with probe/payload two-phase reads [paimon-cpp]
Posted by "lxy-9602 (via GitHub)" <gi...@apache.org>.
lxy-9602 commented on code in PR #243:
URL: https://github.com/apache/paimon-cpp/pull/243#discussion_r3853604031
##########
src/paimon/common/reader/late_materializing_file_batch_reader.h:
##########
@@ -0,0 +1,149 @@
+/*
+ * 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.
+ */
+
+#pragma once
+
+#include <arrow/array/array_nested.h>
+#include <arrow/c/abi.h>
+
+#include <cstdint>
+#include <memory>
+#include <utility>
+#include <vector>
+
+#include "paimon/reader/prefetch_file_batch_reader.h"
+
+namespace paimon {
+
+class PredicateFilter;
+
+// For convenience, we abbreviate `Later Materializing` as `LatMat`.
+// This reader is installed below the prefetch layer (see
+// AbstractSplitRead::CreateFileBatchReader) and performs probe/payload two-phase reads when a
+// predicate is pushed down through SetReadSchema; without a predicate it is a plain passthrough.
+class LateMaterializingFileBatchReader : public PrefetchFileBatchReader {
+ public:
+ static Result<std::unique_ptr<LateMaterializingFileBatchReader>> Create(
+ std::unique_ptr<PrefetchFileBatchReader> inner, std::shared_ptr<MemoryPool> pool);
+
+ Result<FileBatchReader::ReadBatch> NextBatch() override;
+
+ std::shared_ptr<Metrics> GetReaderMetrics() const override {
+ return inner_->GetReaderMetrics();
+ };
+
+ void Close() override {
+ inner_->Close();
Review Comment:
`Close()` should also clean up internal data, such as `probe_data_` and similar state.
##########
src/paimon/common/reader/late_materializing_file_batch_reader.cpp:
##########
@@ -0,0 +1,352 @@
+/*
+ * 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.
+ */
+
+#include "paimon/common/reader/late_materializing_file_batch_reader.h"
+
+#include <map>
+#include <set>
+#include <string>
+#include <utility>
+#include <vector>
+
+#include "arrow/array/concatenate.h"
+#include "arrow/array/util.h"
+#include "arrow/c/bridge.h"
+#include "arrow/memory_pool.h"
+#include "arrow/type.h"
+#include "arrow/util/checked_cast.h"
+#include "fmt/format.h"
+#include "paimon/common/predicate/predicate_filter.h"
+#include "paimon/common/predicate/predicate_validator.h"
+#include "paimon/common/reader/reader_utils.h"
+#include "paimon/common/utils/arrow/arrow_utils.h"
+#include "paimon/common/utils/arrow/mem_utils.h"
+#include "paimon/common/utils/arrow/status_utils.h"
+#include "paimon/predicate/predicate_utils.h"
+#include "paimon/status.h"
+
+namespace paimon {
+
+Result<std::unique_ptr<LateMaterializingFileBatchReader>> LateMaterializingFileBatchReader::Create(
+ std::unique_ptr<PrefetchFileBatchReader> inner, std::shared_ptr<MemoryPool> pool) {
+ // The reader's own compaction allocations go through an arrow pool; bridge the paimon pool
+ // once here so the accounting matches the rest of the read path.
+ if (pool == nullptr) {
+ return Status::Invalid("pool could not be nullptr.");
+ }
+ std::shared_ptr<arrow::MemoryPool> arrow_pool = GetArrowPool(pool);
+ auto reader = std::unique_ptr<LateMaterializingFileBatchReader>(
+ new LateMaterializingFileBatchReader(std::move(inner), std::move(arrow_pool)));
+ return reader;
+}
+
+Result<FileBatchReader::ReadBatch> LateMaterializingFileBatchReader::NextBatch() {
+ if (state_ == kInit) {
+ // SetReadSchema has not been called: read with the file schema, matching the
+ // FileBatchReader contract for schema-less reads.
+ state_ = kNoLatMat;
+ }
+ if (state_ == kProbing) {
+ PAIMON_RETURN_NOT_OK(ReadAndFilterProbeData());
+ if (matched_bitmap_.IsEmpty()) {
+ state_ = kEOF;
+ } else {
+ // payload pass reads only the matched rows (matched_bitmap_ is non-empty here).
+ PAIMON_RETURN_NOT_OK(
+ SetInnerReadSchema(payload_schema_, /*predicate=*/nullptr, matched_bitmap_));
+ state_ = kRunning;
+ }
+ }
+
+ if (state_ == kNoLatMat) {
+ return inner_->NextBatch();
+ } else if (state_ == kRunning) {
+ return ReadPayloadBatch();
+ } else if (state_ == kEOF) {
+ return MakeEofBatch();
+ }
+ return Status::Invalid("invalid state when calling NextBatch: " + std::to_string(state_));
+}
+
+Result<RoaringBitmap32> LateMaterializingFileBatchReader::FilterProbeBatch(
+ const std::shared_ptr<arrow::Array>& array,
+ const std::shared_ptr<PredicateFilter>& bound_filter) {
+ // TODO(zhouhonfeng.zhf): use arrow::compute::Filter instead of PredicateFilter
+ PAIMON_ASSIGN_OR_RAISE(std::vector<char> results, bound_filter->Test(*array));
+ if (results.size() != static_cast<size_t>(array->length())) {
+ return Status::Invalid(
+ fmt::format("predicate result size {} does not match probe batch length {}",
+ results.size(), array->length()));
+ }
+ // batch-local offsets of the rows passing both the predicate and the selection
+ RoaringBitmap32 batch_matched;
+ for (int64_t i = 0; i < array->length(); ++i) {
+ if (!results[static_cast<size_t>(i)]) {
+ continue;
+ }
+ // map batch offset to file row id
+ PAIMON_ASSIGN_OR_RAISE(uint64_t file_row,
+ inner_->GetPreviousBatchFileRowId(static_cast<uint64_t>(i)));
+ if (selection_ && !selection_->Contains(static_cast<int32_t>(file_row))) {
+ continue;
+ }
+ batch_matched.Add(static_cast<uint32_t>(i));
+ matched_bitmap_.Add(file_row);
+ }
+ return batch_matched;
+}
+
+Status LateMaterializingFileBatchReader::ReadAndFilterProbeData() {
+ matched_bitmap_ = RoaringBitmap32();
+ probe_cursor_ = 0;
+ arrow::ArrayVector probe_arrays;
+ while (true) {
+ PAIMON_ASSIGN_OR_RAISE(FileBatchReader::ReadBatch batch, inner_->NextBatch());
+ if (BatchReader::IsEofBatch(batch)) {
+ break;
+ }
+ auto& [c_array, c_schema] = batch;
+ PAIMON_ASSIGN_OR_RAISE_FROM_ARROW(std::shared_ptr<arrow::Array> array,
+ arrow::ImportArray(c_array.get(), c_schema.get()));
+ PAIMON_ASSIGN_OR_RAISE(RoaringBitmap32 batch_matched,
+ FilterProbeBatch(array, probe_filter_));
+ // Compact each probe batch down to its matched rows so probe_data_ aligns row-for-row
+ // (ascending file order) with matched_bitmap_ and the later payload output.
+ if (!batch_matched.IsEmpty()) {
+ PAIMON_ASSIGN_OR_RAISE(arrow::ArrayVector matched_slices,
+ ReaderUtils::GenerateFilteredArrayVector(array, batch_matched));
+ probe_arrays.insert(probe_arrays.end(), std::make_move_iterator(matched_slices.begin()),
+ std::make_move_iterator(matched_slices.end()));
+ }
+ }
+
+ std::shared_ptr<arrow::Array> probe_array;
+ if (probe_arrays.empty()) {
+ PAIMON_ASSIGN_OR_RAISE_FROM_ARROW(
+ probe_array, arrow::MakeEmptyArray(arrow::struct_(probe_schema_->fields())));
+ } else {
+ PAIMON_ASSIGN_OR_RAISE_FROM_ARROW(probe_array,
+ arrow::Concatenate(probe_arrays, arrow_pool_.get()));
+ }
+ probe_data_ = arrow::internal::checked_pointer_cast<arrow::StructArray>(probe_array);
+ return Status::OK();
+}
+
+Result<FileBatchReader::ReadBatch> LateMaterializingFileBatchReader::ReadPayloadBatch() {
+ while (true) {
+ PAIMON_ASSIGN_OR_RAISE(FileBatchReader::ReadBatchWithBitmap batch_with_bitmap,
+ inner_->NextBatchWithBitmap());
+ if (BatchReader::IsEofBatch(batch_with_bitmap)) {
+ state_ = kEOF;
+ if (probe_cursor_ != probe_data_->length()) {
+ return Status::Invalid(
+ fmt::format("probe cursor {} does not match probe data length {}",
+ probe_cursor_, probe_data_->length()));
+ }
+ return MakeEofBatch();
+ }
+ auto& [batch, bitmap] = batch_with_bitmap;
+ if (bitmap.IsEmpty()) {
+ ReaderUtils::ReleaseReadBatch(std::move(batch));
+ continue;
+ }
+ auto& [c_array, c_schema] = batch;
+ PAIMON_ASSIGN_OR_RAISE_FROM_ARROW(std::shared_ptr<arrow::Array> payload_array,
+ arrow::ImportArray(c_array.get(), c_schema.get()));
+
+ // Generate the valid bitmap and row_mapping_
+ RoaringBitmap32 valid;
+ row_mapping_.clear();
+ for (auto it = bitmap.Begin(); it != bitmap.End(); ++it) {
+ auto offset = static_cast<uint64_t>(*it);
+ PAIMON_ASSIGN_OR_RAISE(uint64_t file_row, inner_->GetPreviousBatchFileRowId(offset));
+ if (!matched_bitmap_.Contains(file_row)) {
+ continue;
+ }
+ valid.Add(static_cast<uint32_t>(offset));
+ row_mapping_.push_back(file_row);
+ }
+ if (valid.IsEmpty()) {
+ ReaderUtils::ReleaseReadBatch(std::move(batch));
+ continue;
+ }
+
+ // Compact the payload superset down to the matched rows (ascending file row order).
+ PAIMON_ASSIGN_OR_RAISE(arrow::ArrayVector payload_slices,
+ ReaderUtils::GenerateFilteredArrayVector(payload_array, valid));
+ PAIMON_ASSIGN_OR_RAISE_FROM_ARROW(std::shared_ptr<arrow::Array> payload_compacted,
+ arrow::Concatenate(payload_slices, arrow_pool_.get()));
+
+ auto card = static_cast<int64_t>(valid.Cardinality());
+ if (probe_cursor_ + card > probe_data_->length()) {
+ return Status::Invalid(
+ fmt::format("probe cache underflow: cursor {} + {} exceeds probe rows {}",
+ probe_cursor_, card, probe_data_->length()));
+ }
+ std::shared_ptr<arrow::Array> probe_selected = probe_data_->Slice(probe_cursor_, card);
+ PAIMON_ASSIGN_OR_RAISE(
+ probe_selected, ArrowUtils::NormalizeArrayOffsets(probe_selected, arrow_pool_.get()));
+ probe_cursor_ += card;
+
+ PAIMON_ASSIGN_OR_RAISE(FileBatchReader::ReadBatch assembled,
+ AssembleFullBatch(payload_compacted, probe_selected));
+ return assembled;
+ }
+}
+
+Result<FileBatchReader::ReadBatch> LateMaterializingFileBatchReader::AssembleFullBatch(
+ const std::shared_ptr<arrow::Array>& payload_array,
+ const std::shared_ptr<arrow::Array>& probe_array) {
+ auto payload_struct = arrow::internal::checked_pointer_cast<arrow::StructArray>(payload_array);
+ auto probe_struct = arrow::internal::checked_pointer_cast<arrow::StructArray>(probe_array);
+ arrow::ArrayVector children;
+ children.reserve(full_schema_->num_fields());
+ for (const auto& field : full_schema_->fields()) {
+ std::shared_ptr<arrow::Array> col = payload_struct->GetFieldByName(field->name());
+ if (!col) {
+ col = probe_struct->GetFieldByName(field->name());
+ }
+ if (!col) {
+ return Status::Invalid(
+ fmt::format("field {} missing in both payload and probe columns", field->name()));
+ }
+ PAIMON_ASSIGN_OR_RAISE(col, ArrowUtils::NormalizeArrayOffsets(col, arrow_pool_.get()));
+ children.push_back(std::move(col));
+ }
+ PAIMON_ASSIGN_OR_RAISE_FROM_ARROW(std::shared_ptr<arrow::StructArray> full_struct,
+ arrow::StructArray::Make(children, full_schema_->fields()));
+ std::unique_ptr<::ArrowArray> c_array = std::make_unique<::ArrowArray>();
+ std::unique_ptr<::ArrowSchema> c_schema = std::make_unique<::ArrowSchema>();
+ PAIMON_RETURN_NOT_OK_FROM_ARROW(
+ arrow::ExportArray(*full_struct, c_array.get(), c_schema.get()));
+ return std::make_pair(std::move(c_array), std::move(c_schema));
+}
+
+Status LateMaterializingFileBatchReader::SetInnerReadSchema(
+ const std::shared_ptr<arrow::Schema>& read_schema, const std::shared_ptr<Predicate>& predicate,
+ const std::optional<RoaringBitmap32>& selection) {
+ ::ArrowSchema c_read_schema;
+ PAIMON_RETURN_NOT_OK_FROM_ARROW(arrow::ExportSchema(*read_schema, &c_read_schema));
+ /// Note: calling inner->SetReadSchema may refresh the read ranges of the inner reader.
+ PAIMON_RETURN_NOT_OK(inner_->SetReadSchema(&c_read_schema, predicate, selection));
+ if (!read_ranges_.empty()) {
+ PAIMON_RETURN_NOT_OK(inner_->SetReadRanges(read_ranges_));
+ }
+ return Status::OK();
+}
+
+Status LateMaterializingFileBatchReader::SetReadSchema(
+ ::ArrowSchema* read_schema, const std::shared_ptr<Predicate>& predicate,
+ const std::optional<RoaringBitmap32>& selection_bitmap) {
+ PAIMON_ASSIGN_OR_RAISE_FROM_ARROW(full_schema_, arrow::ImportSchema(read_schema));
+ predicate_ = predicate;
+ selection_ = selection_bitmap;
+ matched_bitmap_ = RoaringBitmap32();
+ probe_data_.reset();
+ probe_cursor_ = 0;
+ row_mapping_.clear();
+ probe_schema_.reset();
+ payload_schema_.reset();
+ probe_filter_.reset();
+ if (predicate_ != nullptr) {
+ std::set<std::string> probe_names;
+ PAIMON_RETURN_NOT_OK(PredicateUtils::GetAllNames(predicate_, &probe_names));
+ arrow::FieldVector probe_fields;
+ arrow::FieldVector payload_fields;
+ for (const auto& field : full_schema_->fields()) {
+ if (probe_names.count(field->name()) > 0) {
+ probe_fields.push_back(field);
+ } else {
+ payload_fields.push_back(field);
+ }
+ }
+ // probing only pays off when the predicate fields are a strict subset of the read schema
+ if (!probe_fields.empty() && !payload_fields.empty()) {
+ probe_schema_ = arrow::schema(probe_fields, full_schema_->metadata());
+ payload_schema_ = arrow::schema(payload_fields, full_schema_->metadata());
+ PAIMON_RETURN_NOT_OK(PredicateValidator::ValidatePredicateWithSchema(
Review Comment:
In what scenarios would schema metadata be set here?
##########
src/paimon/common/reader/late_materializing_file_batch_reader.cpp:
##########
@@ -0,0 +1,352 @@
+/*
+ * 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.
+ */
+
+#include "paimon/common/reader/late_materializing_file_batch_reader.h"
+
+#include <map>
+#include <set>
+#include <string>
+#include <utility>
+#include <vector>
+
+#include "arrow/array/concatenate.h"
+#include "arrow/array/util.h"
+#include "arrow/c/bridge.h"
+#include "arrow/memory_pool.h"
+#include "arrow/type.h"
+#include "arrow/util/checked_cast.h"
+#include "fmt/format.h"
+#include "paimon/common/predicate/predicate_filter.h"
+#include "paimon/common/predicate/predicate_validator.h"
+#include "paimon/common/reader/reader_utils.h"
+#include "paimon/common/utils/arrow/arrow_utils.h"
+#include "paimon/common/utils/arrow/mem_utils.h"
+#include "paimon/common/utils/arrow/status_utils.h"
+#include "paimon/predicate/predicate_utils.h"
+#include "paimon/status.h"
+
+namespace paimon {
+
+Result<std::unique_ptr<LateMaterializingFileBatchReader>> LateMaterializingFileBatchReader::Create(
+ std::unique_ptr<PrefetchFileBatchReader> inner, std::shared_ptr<MemoryPool> pool) {
+ // The reader's own compaction allocations go through an arrow pool; bridge the paimon pool
+ // once here so the accounting matches the rest of the read path.
+ if (pool == nullptr) {
+ return Status::Invalid("pool could not be nullptr.");
+ }
+ std::shared_ptr<arrow::MemoryPool> arrow_pool = GetArrowPool(pool);
+ auto reader = std::unique_ptr<LateMaterializingFileBatchReader>(
+ new LateMaterializingFileBatchReader(std::move(inner), std::move(arrow_pool)));
+ return reader;
+}
+
+Result<FileBatchReader::ReadBatch> LateMaterializingFileBatchReader::NextBatch() {
+ if (state_ == kInit) {
+ // SetReadSchema has not been called: read with the file schema, matching the
+ // FileBatchReader contract for schema-less reads.
+ state_ = kNoLatMat;
+ }
+ if (state_ == kProbing) {
+ PAIMON_RETURN_NOT_OK(ReadAndFilterProbeData());
+ if (matched_bitmap_.IsEmpty()) {
+ state_ = kEOF;
+ } else {
+ // payload pass reads only the matched rows (matched_bitmap_ is non-empty here).
+ PAIMON_RETURN_NOT_OK(
+ SetInnerReadSchema(payload_schema_, /*predicate=*/nullptr, matched_bitmap_));
+ state_ = kRunning;
+ }
+ }
+
+ if (state_ == kNoLatMat) {
+ return inner_->NextBatch();
+ } else if (state_ == kRunning) {
+ return ReadPayloadBatch();
+ } else if (state_ == kEOF) {
+ return MakeEofBatch();
+ }
+ return Status::Invalid("invalid state when calling NextBatch: " + std::to_string(state_));
+}
Review Comment:
Read-ahead cache does not explicitly cover payload columns
`PrefetchFileBatchReaderImpl::Workloop()` initializes the shared read-ahead cache only once. At that point, this reader is configured with `probe_schema_`, so `inner_->PreBufferRange()` only returns byte ranges for the probe columns.
After probing, `SetInnerReadSchema(payload_schema_, ...)` switches to the payload columns, but no additional pre-buffer ranges are collected or registered. `ReadAheadCache` does not dynamically add ranges on a miss, so payload reads fall back to the underlying input stream unless they happen to be covered by a coalesced probe range.
This is especially relevant for Parquet because its native pre-buffering is disabled when the shared read-ahead cache is enabled. Could we initialize the cache with the union of probe and payload byte ranges, or otherwise add the payload ranges when switching phases?
##########
src/paimon/common/reader/late_materializing_file_batch_reader.h:
##########
@@ -0,0 +1,149 @@
+/*
+ * 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.
+ */
+
+#pragma once
+
+#include <arrow/array/array_nested.h>
+#include <arrow/c/abi.h>
+
+#include <cstdint>
+#include <memory>
+#include <utility>
+#include <vector>
+
+#include "paimon/reader/prefetch_file_batch_reader.h"
+
+namespace paimon {
+
+class PredicateFilter;
+
+// For convenience, we abbreviate `Later Materializing` as `LatMat`.
+// This reader is installed below the prefetch layer (see
+// AbstractSplitRead::CreateFileBatchReader) and performs probe/payload two-phase reads when a
+// predicate is pushed down through SetReadSchema; without a predicate it is a plain passthrough.
+class LateMaterializingFileBatchReader : public PrefetchFileBatchReader {
+ public:
+ static Result<std::unique_ptr<LateMaterializingFileBatchReader>> Create(
+ std::unique_ptr<PrefetchFileBatchReader> inner, std::shared_ptr<MemoryPool> pool);
+
+ Result<FileBatchReader::ReadBatch> NextBatch() override;
+
+ std::shared_ptr<Metrics> GetReaderMetrics() const override {
+ return inner_->GetReaderMetrics();
+ };
+
+ void Close() override {
+ inner_->Close();
+ }
+
+ Result<std::unique_ptr<::ArrowSchema>> GetFileSchema() const override {
+ return inner_->GetFileSchema();
+ }
+
+ Status SetReadSchema(::ArrowSchema* read_schema, const std::shared_ptr<Predicate>& predicate,
+ const std::optional<RoaringBitmap32>& selection_bitmap) override;
+
+ Result<uint64_t> GetPreviousBatchFileRowId(uint64_t batch_row_id) const override;
+
+ Result<uint64_t> GetNumberOfRows() const override {
+ return inner_->GetNumberOfRows();
+ }
+
+ bool SupportPreciseBitmapSelection() const override {
+ // When probe_schema_ or payload_schema_ is null, lat-mat does not take effect.
+ // Here we simply pass through the inner reader's support.
+ return inner_->SupportPreciseBitmapSelection();
+ }
+
+ Status SeekToRow(uint64_t row_number) override;
+
+ uint64_t GetNextRowToRead() const override {
+ return inner_->GetNextRowToRead();
+ }
+
+ Result<std::vector<std::pair<uint64_t, uint64_t>>> GenReadRanges(
+ bool* need_prefetch) const override {
+ return inner_->GenReadRanges(need_prefetch);
Review Comment:
ORC read ranges are not enforced during late materialization
The ORC implementation of `SetReadRanges()` currently returns `OK` without applying the supplied ranges. Normally, the prefetch reader still respects range boundaries by calling `EnsureReaderPosition()` before each batch and slicing the returned batch.
Late materialization bypasses that control point: a single `NextBatch()` call drains the probe reader until EOF. Therefore, each parallel ORC reader may probe from its first assigned range to the end of the file, including ranges assigned to other readers.
The payload phase can amplify this further: `SetReadSchema()` recreates the ORC row reader at row 0, reapplying `SetReadRanges()` has no effect, and ORC does not apply the selection bitmap precisely. The payload reader may consequently scan from the beginning again.
This can cause substantial duplicated I/O and decoding when late materialization and parallel prefetch are enabled together. Could we enforce the assigned ranges in the ORC reader?
##########
src/paimon/common/reader/late_materializing_reader_builder.h:
##########
@@ -0,0 +1,74 @@
+/*
+ * 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.
+ */
+
+#pragma once
+
+#include <memory>
+#include <utility>
+
+#include "paimon/common/reader/late_materializing_file_batch_reader.h"
+#include "paimon/format/reader_builder.h"
+#include "paimon/memory/memory_pool.h"
+#include "paimon/reader/prefetch_file_batch_reader.h"
+#include "paimon/result.h"
+
+namespace paimon {
+
+class LateMaterializingReaderBuilder : public ReaderBuilder {
+ public:
+ LateMaterializingReaderBuilder(std::unique_ptr<ReaderBuilder> inner,
+ std::shared_ptr<MemoryPool> pool)
+ : inner_(std::move(inner)), pool_(std::move(pool)) {}
+
+ ReaderBuilder* WithMemoryPool(const std::shared_ptr<MemoryPool>& pool) override {
+ pool_ = pool;
+ inner_->WithMemoryPool(pool);
+ return this;
+ }
+
+ ReaderBuilder* WithCache(const std::shared_ptr<Cache>& cache) override {
+ inner_->WithCache(cache);
+ return this;
+ }
+
+ ReaderBuilder* WithReadHints(const std::optional<ReadHints>& hints) override {
+ inner_->WithReadHints(hints);
+ return this;
+ }
+
+ Result<std::unique_ptr<FileBatchReader>> Build(
+ const std::shared_ptr<InputStream>& stream) const override {
+ PAIMON_ASSIGN_OR_RAISE(std::unique_ptr<FileBatchReader> base, inner_->Build(stream));
+ auto* prefetch = dynamic_cast<PrefetchFileBatchReader*>(base.get());
+ if (prefetch == nullptr) {
Review Comment:
This feels a bit awkward — does enabling late materialization have to depend on the format supporting prefetch? If the format doesn’t support prefetch, does that mean late materialization can’t be enabled at all?
##########
src/paimon/common/reader/late_materializing_file_batch_reader_test.cpp:
##########
@@ -0,0 +1,658 @@
+/*
+ * 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.
+ */
+
+#include "paimon/common/reader/late_materializing_file_batch_reader.h"
+
+#include <algorithm>
+#include <cstdint>
+#include <limits>
+#include <memory>
+#include <optional>
+#include <string>
+#include <utility>
+#include <vector>
+
+#include "arrow/api.h"
+#include "arrow/array/builder_nested.h"
+#include "arrow/c/bridge.h"
+#include "gtest/gtest.h"
+#include "paimon/common/reader/late_materializing_reader_builder.h"
+#include "paimon/common/reader/prefetch_file_batch_reader_impl.h"
+#include "paimon/common/reader/reader_utils.h"
+#include "paimon/common/utils/arrow/status_utils.h"
+#include "paimon/common/utils/checked_cast.h"
+#include "paimon/common/utils/read_ahead_cache.h"
+#include "paimon/executor.h"
+#include "paimon/format/reader_builder.h"
+#include "paimon/memory/memory_pool.h"
+#include "paimon/predicate/literal.h"
+#include "paimon/predicate/predicate.h"
+#include "paimon/predicate/predicate_builder.h"
+#include "paimon/reader/prefetch_file_batch_reader.h"
+#include "paimon/status.h"
+#include "paimon/testing/mock/mock_file_batch_reader.h"
+#include "paimon/testing/mock/mock_file_system.h"
+#include "paimon/testing/mock/mock_format_reader_builder.h"
+#include "paimon/testing/utils/testharness.h"
+#include "paimon/utils/roaring_bitmap32.h"
+
+namespace paimon::test {
+
+class LateMaterializingFileBatchReaderTest : public ::testing::Test {
+ public:
+ void SetUp() override {
+ k_field_ = arrow::field("k", arrow::int64());
+ v_field_ = arrow::field("v", arrow::utf8());
+ full_fields_ = {k_field_, v_field_};
+ full_type_ = arrow::struct_(full_fields_);
+ }
+
+ // Build a struct array with column k (int64, values = ks) and column v (utf8, "v_<index>").
+ std::shared_ptr<arrow::Array> BuildData(const std::vector<int64_t>& ks) {
+ arrow::StructBuilder builder(
+ full_type_, arrow::default_memory_pool(),
+ {std::make_shared<arrow::Int64Builder>(), std::make_shared<arrow::StringBuilder>()});
+ auto* k_builder = checked_cast<arrow::Int64Builder*>(builder.field_builder(0));
+ auto* v_builder = checked_cast<arrow::StringBuilder*>(builder.field_builder(1));
+ for (size_t i = 0; i < ks.size(); ++i) {
+ EXPECT_TRUE(builder.Append().ok());
+ EXPECT_TRUE(k_builder->Append(ks[i]).ok());
+ EXPECT_TRUE(v_builder->Append("v_" + std::to_string(i)).ok());
+ }
+ std::shared_ptr<arrow::Array> array;
+ EXPECT_TRUE(builder.Finish(&array).ok());
+ return array;
+ }
+
+ struct Row {
+ int64_t k;
+ std::string v;
+ uint64_t file_row;
+ };
+
+ // Drive the reader through NextBatchWithBitmap to EOF, decoding the full-schema output rows.
+ Result<std::vector<Row>> Collect(LateMaterializingFileBatchReader* reader) {
+ std::vector<Row> rows;
+ while (true) {
+ PAIMON_ASSIGN_OR_RAISE(BatchReader::ReadBatchWithBitmap batch_with_bitmap,
+ reader->NextBatchWithBitmap());
+ if (BatchReader::IsEofBatch(batch_with_bitmap)) {
+ break;
+ }
+ auto& [batch, bitmap] = batch_with_bitmap;
+ auto& [c_array, c_schema] = batch;
+ PAIMON_ASSIGN_OR_RAISE_FROM_ARROW(std::shared_ptr<arrow::Array> array,
+ arrow::ImportArray(c_array.get(), c_schema.get()));
+ auto struct_array = arrow::internal::checked_pointer_cast<arrow::StructArray>(array);
+ EXPECT_EQ(bitmap.Cardinality(), static_cast<int32_t>(struct_array->length()));
+ auto k_array = arrow::internal::checked_pointer_cast<arrow::Int64Array>(
+ struct_array->GetFieldByName("k"));
+ if (!k_array) {
+ return Status::Invalid("output batch missing k column");
+ }
+ // v is only present when it belongs to the read schema (payload projection).
+ auto v_array = arrow::internal::checked_pointer_cast<arrow::StringArray>(
+ struct_array->GetFieldByName("v"));
+ for (int64_t i = 0; i < struct_array->length(); ++i) {
+ PAIMON_ASSIGN_OR_RAISE(uint64_t file_row,
+ reader->GetPreviousBatchFileRowId(static_cast<uint64_t>(i)));
+ rows.push_back(Row{k_array->Value(i),
+ v_array ? v_array->GetString(i) : std::string(), file_row});
+ }
+ }
+ return rows;
+ }
+
+ Status SetReadSchema(LateMaterializingFileBatchReader* reader,
+ const std::shared_ptr<arrow::Schema>& schema,
+ const std::shared_ptr<Predicate>& predicate,
+ const std::optional<RoaringBitmap32>& selection) {
+ ::ArrowSchema c_schema;
+ PAIMON_RETURN_NOT_OK_FROM_ARROW(arrow::ExportSchema(*schema, &c_schema));
+ return reader->SetReadSchema(&c_schema, predicate, selection);
+ }
+
+ // Collect all output rows as a single concatenated struct array (for schema/nested checks).
+ Result<std::shared_ptr<arrow::StructArray>> CollectStruct(FileBatchReader* reader) {
+ arrow::ArrayVector chunks;
Review Comment:
What’s the difference between this and `read_result_collector.h`? It seems like we may be duplicating the same logic here.
##########
test/inte/read_inte_test.cpp:
##########
@@ -3109,6 +3194,7 @@ TEST_P(ReadInteTest, TestPkReadSnapshot6WithSchemaEvolutionWithPredicateOnlyPush
context_builder.SetReadAheadCacheEnabled(param.read_ahead_cache_enabled);
context_builder.SetPredicate(predicate);
context_builder.EnablePrefetch(param.enable_prefetch)
+ .EnableLateMaterializing(false)
.AddOption("test.enable-adaptive-prefetch-strategy",
Review Comment:
I remember `EnableLateMaterializing` defaults to `false`. Was this change made because some tests were failing, or was it simply adjusted to keep the results stable since the test involves predicates?
##########
test/inte/scan_and_read_inte_test.cpp:
##########
@@ -744,6 +744,47 @@ TEST_P(ScanAndReadInteTest, TestWithPKWithDvBatchScanSnapshot6WithPredicate) {
ASSERT_TRUE(expected->Equals(read_result)) << read_result->ToString();
}
+TEST_P(ScanAndReadInteTest, TestWithPKWithDvBatchScanSnapshot6WithLateMaterializing) {
+ auto file_format = FileFormat();
+ std::string table_path = paimon::test::GetDataDir() + file_format +
+ "/pk_table_scan_and_read_dv.db/pk_table_scan_and_read_dv/";
+ ScanContextBuilder scan_context_builder(table_path);
+ scan_context_builder.AddOption(Options::SCAN_SNAPSHOT_ID, "6");
+
+ std::string literal_str = "Alice";
+ auto not_equal = PredicateBuilder::NotEqual(
+ /*field_index=*/0, /*field_name=*/"f0", FieldType::STRING,
+ Literal(FieldType::STRING, literal_str.data(), literal_str.size()));
+ auto greater_than = PredicateBuilder::GreaterThan(/*field_index=*/3, /*field_name=*/"f3",
+ FieldType::DOUBLE, Literal(18.0));
+ ASSERT_OK_AND_ASSIGN(auto predicate, PredicateBuilder::And({not_equal, greater_than}));
+ scan_context_builder.SetPredicate(predicate);
+ ASSERT_OK_AND_ASSIGN(auto scan_context, FinishScanContext(scan_context_builder));
+ ASSERT_OK_AND_ASSIGN(auto table_scan, TableScan::Create(std::move(scan_context)));
+
+ ReadContextBuilder read_context_builder(table_path);
+ AddReadOptionsForPrefetch(&read_context_builder);
+ read_context_builder.SetPredicate(predicate)
+ .EnablePredicateFilter(true)
+ .EnableLateMaterializing(true);
Review Comment:
From the integration test, it looks like if `EnablePredicateFilter` is also enabled, the final output will always reflect the filtered result anyway. Could that end up masking the effect of `EnableLateMaterializing`?
##########
src/paimon/common/reader/late_materializing_file_batch_reader.cpp:
##########
@@ -0,0 +1,352 @@
+/*
+ * 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.
+ */
+
+#include "paimon/common/reader/late_materializing_file_batch_reader.h"
+
+#include <map>
+#include <set>
+#include <string>
+#include <utility>
+#include <vector>
+
+#include "arrow/array/concatenate.h"
+#include "arrow/array/util.h"
+#include "arrow/c/bridge.h"
+#include "arrow/memory_pool.h"
+#include "arrow/type.h"
+#include "arrow/util/checked_cast.h"
+#include "fmt/format.h"
+#include "paimon/common/predicate/predicate_filter.h"
+#include "paimon/common/predicate/predicate_validator.h"
+#include "paimon/common/reader/reader_utils.h"
+#include "paimon/common/utils/arrow/arrow_utils.h"
+#include "paimon/common/utils/arrow/mem_utils.h"
+#include "paimon/common/utils/arrow/status_utils.h"
+#include "paimon/predicate/predicate_utils.h"
+#include "paimon/status.h"
+
+namespace paimon {
+
+Result<std::unique_ptr<LateMaterializingFileBatchReader>> LateMaterializingFileBatchReader::Create(
+ std::unique_ptr<PrefetchFileBatchReader> inner, std::shared_ptr<MemoryPool> pool) {
+ // The reader's own compaction allocations go through an arrow pool; bridge the paimon pool
+ // once here so the accounting matches the rest of the read path.
+ if (pool == nullptr) {
+ return Status::Invalid("pool could not be nullptr.");
+ }
+ std::shared_ptr<arrow::MemoryPool> arrow_pool = GetArrowPool(pool);
+ auto reader = std::unique_ptr<LateMaterializingFileBatchReader>(
+ new LateMaterializingFileBatchReader(std::move(inner), std::move(arrow_pool)));
+ return reader;
+}
+
+Result<FileBatchReader::ReadBatch> LateMaterializingFileBatchReader::NextBatch() {
+ if (state_ == kInit) {
+ // SetReadSchema has not been called: read with the file schema, matching the
+ // FileBatchReader contract for schema-less reads.
+ state_ = kNoLatMat;
+ }
+ if (state_ == kProbing) {
+ PAIMON_RETURN_NOT_OK(ReadAndFilterProbeData());
+ if (matched_bitmap_.IsEmpty()) {
+ state_ = kEOF;
+ } else {
+ // payload pass reads only the matched rows (matched_bitmap_ is non-empty here).
+ PAIMON_RETURN_NOT_OK(
+ SetInnerReadSchema(payload_schema_, /*predicate=*/nullptr, matched_bitmap_));
+ state_ = kRunning;
+ }
+ }
+
+ if (state_ == kNoLatMat) {
+ return inner_->NextBatch();
+ } else if (state_ == kRunning) {
+ return ReadPayloadBatch();
+ } else if (state_ == kEOF) {
+ return MakeEofBatch();
+ }
+ return Status::Invalid("invalid state when calling NextBatch: " + std::to_string(state_));
+}
+
+Result<RoaringBitmap32> LateMaterializingFileBatchReader::FilterProbeBatch(
+ const std::shared_ptr<arrow::Array>& array,
+ const std::shared_ptr<PredicateFilter>& bound_filter) {
+ // TODO(zhouhonfeng.zhf): use arrow::compute::Filter instead of PredicateFilter
+ PAIMON_ASSIGN_OR_RAISE(std::vector<char> results, bound_filter->Test(*array));
+ if (results.size() != static_cast<size_t>(array->length())) {
+ return Status::Invalid(
+ fmt::format("predicate result size {} does not match probe batch length {}",
+ results.size(), array->length()));
+ }
+ // batch-local offsets of the rows passing both the predicate and the selection
+ RoaringBitmap32 batch_matched;
+ for (int64_t i = 0; i < array->length(); ++i) {
+ if (!results[static_cast<size_t>(i)]) {
+ continue;
+ }
+ // map batch offset to file row id
+ PAIMON_ASSIGN_OR_RAISE(uint64_t file_row,
+ inner_->GetPreviousBatchFileRowId(static_cast<uint64_t>(i)));
+ if (selection_ && !selection_->Contains(static_cast<int32_t>(file_row))) {
+ continue;
+ }
+ batch_matched.Add(static_cast<uint32_t>(i));
+ matched_bitmap_.Add(file_row);
+ }
+ return batch_matched;
+}
+
+Status LateMaterializingFileBatchReader::ReadAndFilterProbeData() {
+ matched_bitmap_ = RoaringBitmap32();
+ probe_cursor_ = 0;
+ arrow::ArrayVector probe_arrays;
+ while (true) {
+ PAIMON_ASSIGN_OR_RAISE(FileBatchReader::ReadBatch batch, inner_->NextBatch());
+ if (BatchReader::IsEofBatch(batch)) {
+ break;
+ }
+ auto& [c_array, c_schema] = batch;
+ PAIMON_ASSIGN_OR_RAISE_FROM_ARROW(std::shared_ptr<arrow::Array> array,
+ arrow::ImportArray(c_array.get(), c_schema.get()));
+ PAIMON_ASSIGN_OR_RAISE(RoaringBitmap32 batch_matched,
+ FilterProbeBatch(array, probe_filter_));
+ // Compact each probe batch down to its matched rows so probe_data_ aligns row-for-row
+ // (ascending file order) with matched_bitmap_ and the later payload output.
+ if (!batch_matched.IsEmpty()) {
+ PAIMON_ASSIGN_OR_RAISE(arrow::ArrayVector matched_slices,
+ ReaderUtils::GenerateFilteredArrayVector(array, batch_matched));
+ probe_arrays.insert(probe_arrays.end(), std::make_move_iterator(matched_slices.begin()),
+ std::make_move_iterator(matched_slices.end()));
+ }
+ }
+
+ std::shared_ptr<arrow::Array> probe_array;
+ if (probe_arrays.empty()) {
+ PAIMON_ASSIGN_OR_RAISE_FROM_ARROW(
+ probe_array, arrow::MakeEmptyArray(arrow::struct_(probe_schema_->fields())));
+ } else {
+ PAIMON_ASSIGN_OR_RAISE_FROM_ARROW(probe_array,
+ arrow::Concatenate(probe_arrays, arrow_pool_.get()));
+ }
+ probe_data_ = arrow::internal::checked_pointer_cast<arrow::StructArray>(probe_array);
+ return Status::OK();
+}
+
+Result<FileBatchReader::ReadBatch> LateMaterializingFileBatchReader::ReadPayloadBatch() {
+ while (true) {
+ PAIMON_ASSIGN_OR_RAISE(FileBatchReader::ReadBatchWithBitmap batch_with_bitmap,
+ inner_->NextBatchWithBitmap());
+ if (BatchReader::IsEofBatch(batch_with_bitmap)) {
+ state_ = kEOF;
+ if (probe_cursor_ != probe_data_->length()) {
+ return Status::Invalid(
+ fmt::format("probe cursor {} does not match probe data length {}",
+ probe_cursor_, probe_data_->length()));
+ }
+ return MakeEofBatch();
+ }
+ auto& [batch, bitmap] = batch_with_bitmap;
+ if (bitmap.IsEmpty()) {
+ ReaderUtils::ReleaseReadBatch(std::move(batch));
+ continue;
Review Comment:
In theory, no reader should return a batch with `bitmap.IsEmpty()` to the upper layer. It seems it would be better to return a bad status or simply assert in this case.
--
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: issues-unsubscribe@paimon.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(reader): support late materialization with probe/payload two-phase reads [paimon-cpp]
Posted by "zhf999 (via GitHub)" <gi...@apache.org>.
zhf999 commented on code in PR #243:
URL: https://github.com/apache/paimon-cpp/pull/243#discussion_r3848946673
##########
src/paimon/core/operation/abstract_split_read.cpp:
##########
@@ -152,13 +153,17 @@ Result<std::unique_ptr<ReaderBuilder>> AbstractSplitRead::PrepareReaderBuilder(
Result<std::unique_ptr<FileBatchReader>> AbstractSplitRead::CreateFileBatchReader(
const std::string& file_format_identifier, const std::string& data_file_path,
- int64_t data_file_size, const ReaderBuilder* reader_builder) const {
+ int64_t data_file_size, std::unique_ptr<ReaderBuilder> reader_builder) const {
if (context_->EnablePrefetch() && file_format_identifier != "blob" &&
file_format_identifier != "avro") {
+ if (context_->EnableLateMaterializing()) {
Review Comment:
Nice proposal, I will change this logic.
--
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: issues-unsubscribe@paimon.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(reader): support late materialization with probe/payload two-phase reads [paimon-cpp]
Posted by "gripleaf (via GitHub)" <gi...@apache.org>.
gripleaf commented on code in PR #243:
URL: https://github.com/apache/paimon-cpp/pull/243#discussion_r3843270013
##########
src/paimon/core/operation/abstract_split_read.cpp:
##########
@@ -152,13 +153,17 @@ Result<std::unique_ptr<ReaderBuilder>> AbstractSplitRead::PrepareReaderBuilder(
Result<std::unique_ptr<FileBatchReader>> AbstractSplitRead::CreateFileBatchReader(
const std::string& file_format_identifier, const std::string& data_file_path,
- int64_t data_file_size, const ReaderBuilder* reader_builder) const {
+ int64_t data_file_size, std::unique_ptr<ReaderBuilder> reader_builder) const {
if (context_->EnablePrefetch() && file_format_identifier != "blob" &&
file_format_identifier != "avro") {
+ if (context_->EnableLateMaterializing()) {
Review Comment:
Could we also support late materialization when prefetch is disabled?
Our main read path runs with EnablePrefetch(false). With the current integration, LateMaterializingReaderBuilder is only installed inside the prefetch branch, so those reads always fall back to the regular format reader and never benefit from late materialization.
Late materialization and prefetch should ideally be independent capabilities: the non-prefetch path should also wrap a compatible format reader, or the two-phase orchestration should be moved above the prefetch/non-prefetch split. PR #196 supports both modes by implementing the probe/payload orchestration at the RawFileSplitRead layer.
--
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: issues-unsubscribe@paimon.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(reader): support late materialization with probe/payload two-phase reads [paimon-cpp]
Posted by "zhf999 (via GitHub)" <gi...@apache.org>.
zhf999 commented on code in PR #243:
URL: https://github.com/apache/paimon-cpp/pull/243#discussion_r3859506533
##########
src/paimon/common/reader/late_materializing_file_batch_reader.h:
##########
@@ -0,0 +1,149 @@
+/*
+ * 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.
+ */
+
+#pragma once
+
+#include <arrow/array/array_nested.h>
+#include <arrow/c/abi.h>
+
+#include <cstdint>
+#include <memory>
+#include <utility>
+#include <vector>
+
+#include "paimon/reader/prefetch_file_batch_reader.h"
+
+namespace paimon {
+
+class PredicateFilter;
+
+// For convenience, we abbreviate `Later Materializing` as `LatMat`.
+// This reader is installed below the prefetch layer (see
+// AbstractSplitRead::CreateFileBatchReader) and performs probe/payload two-phase reads when a
+// predicate is pushed down through SetReadSchema; without a predicate it is a plain passthrough.
+class LateMaterializingFileBatchReader : public PrefetchFileBatchReader {
+ public:
+ static Result<std::unique_ptr<LateMaterializingFileBatchReader>> Create(
+ std::unique_ptr<PrefetchFileBatchReader> inner, std::shared_ptr<MemoryPool> pool);
+
+ Result<FileBatchReader::ReadBatch> NextBatch() override;
+
+ std::shared_ptr<Metrics> GetReaderMetrics() const override {
+ return inner_->GetReaderMetrics();
+ };
+
+ void Close() override {
+ inner_->Close();
Review Comment:
Done.
##########
src/paimon/common/reader/late_materializing_file_batch_reader.cpp:
##########
@@ -0,0 +1,352 @@
+/*
+ * 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.
+ */
+
+#include "paimon/common/reader/late_materializing_file_batch_reader.h"
+
+#include <map>
+#include <set>
+#include <string>
+#include <utility>
+#include <vector>
+
+#include "arrow/array/concatenate.h"
+#include "arrow/array/util.h"
+#include "arrow/c/bridge.h"
+#include "arrow/memory_pool.h"
+#include "arrow/type.h"
+#include "arrow/util/checked_cast.h"
+#include "fmt/format.h"
+#include "paimon/common/predicate/predicate_filter.h"
+#include "paimon/common/predicate/predicate_validator.h"
+#include "paimon/common/reader/reader_utils.h"
+#include "paimon/common/utils/arrow/arrow_utils.h"
+#include "paimon/common/utils/arrow/mem_utils.h"
+#include "paimon/common/utils/arrow/status_utils.h"
+#include "paimon/predicate/predicate_utils.h"
+#include "paimon/status.h"
+
+namespace paimon {
+
+Result<std::unique_ptr<LateMaterializingFileBatchReader>> LateMaterializingFileBatchReader::Create(
+ std::unique_ptr<PrefetchFileBatchReader> inner, std::shared_ptr<MemoryPool> pool) {
+ // The reader's own compaction allocations go through an arrow pool; bridge the paimon pool
+ // once here so the accounting matches the rest of the read path.
+ if (pool == nullptr) {
+ return Status::Invalid("pool could not be nullptr.");
+ }
+ std::shared_ptr<arrow::MemoryPool> arrow_pool = GetArrowPool(pool);
+ auto reader = std::unique_ptr<LateMaterializingFileBatchReader>(
+ new LateMaterializingFileBatchReader(std::move(inner), std::move(arrow_pool)));
+ return reader;
+}
+
+Result<FileBatchReader::ReadBatch> LateMaterializingFileBatchReader::NextBatch() {
+ if (state_ == kInit) {
+ // SetReadSchema has not been called: read with the file schema, matching the
+ // FileBatchReader contract for schema-less reads.
+ state_ = kNoLatMat;
+ }
+ if (state_ == kProbing) {
+ PAIMON_RETURN_NOT_OK(ReadAndFilterProbeData());
+ if (matched_bitmap_.IsEmpty()) {
+ state_ = kEOF;
+ } else {
+ // payload pass reads only the matched rows (matched_bitmap_ is non-empty here).
+ PAIMON_RETURN_NOT_OK(
+ SetInnerReadSchema(payload_schema_, /*predicate=*/nullptr, matched_bitmap_));
+ state_ = kRunning;
+ }
+ }
+
+ if (state_ == kNoLatMat) {
+ return inner_->NextBatch();
+ } else if (state_ == kRunning) {
+ return ReadPayloadBatch();
+ } else if (state_ == kEOF) {
+ return MakeEofBatch();
+ }
+ return Status::Invalid("invalid state when calling NextBatch: " + std::to_string(state_));
+}
+
+Result<RoaringBitmap32> LateMaterializingFileBatchReader::FilterProbeBatch(
+ const std::shared_ptr<arrow::Array>& array,
+ const std::shared_ptr<PredicateFilter>& bound_filter) {
+ // TODO(zhouhonfeng.zhf): use arrow::compute::Filter instead of PredicateFilter
+ PAIMON_ASSIGN_OR_RAISE(std::vector<char> results, bound_filter->Test(*array));
+ if (results.size() != static_cast<size_t>(array->length())) {
+ return Status::Invalid(
+ fmt::format("predicate result size {} does not match probe batch length {}",
+ results.size(), array->length()));
+ }
+ // batch-local offsets of the rows passing both the predicate and the selection
+ RoaringBitmap32 batch_matched;
+ for (int64_t i = 0; i < array->length(); ++i) {
+ if (!results[static_cast<size_t>(i)]) {
+ continue;
+ }
+ // map batch offset to file row id
+ PAIMON_ASSIGN_OR_RAISE(uint64_t file_row,
+ inner_->GetPreviousBatchFileRowId(static_cast<uint64_t>(i)));
+ if (selection_ && !selection_->Contains(static_cast<int32_t>(file_row))) {
+ continue;
+ }
+ batch_matched.Add(static_cast<uint32_t>(i));
+ matched_bitmap_.Add(file_row);
+ }
+ return batch_matched;
+}
+
+Status LateMaterializingFileBatchReader::ReadAndFilterProbeData() {
+ matched_bitmap_ = RoaringBitmap32();
+ probe_cursor_ = 0;
+ arrow::ArrayVector probe_arrays;
+ while (true) {
+ PAIMON_ASSIGN_OR_RAISE(FileBatchReader::ReadBatch batch, inner_->NextBatch());
+ if (BatchReader::IsEofBatch(batch)) {
+ break;
+ }
+ auto& [c_array, c_schema] = batch;
+ PAIMON_ASSIGN_OR_RAISE_FROM_ARROW(std::shared_ptr<arrow::Array> array,
+ arrow::ImportArray(c_array.get(), c_schema.get()));
+ PAIMON_ASSIGN_OR_RAISE(RoaringBitmap32 batch_matched,
+ FilterProbeBatch(array, probe_filter_));
+ // Compact each probe batch down to its matched rows so probe_data_ aligns row-for-row
+ // (ascending file order) with matched_bitmap_ and the later payload output.
+ if (!batch_matched.IsEmpty()) {
+ PAIMON_ASSIGN_OR_RAISE(arrow::ArrayVector matched_slices,
+ ReaderUtils::GenerateFilteredArrayVector(array, batch_matched));
+ probe_arrays.insert(probe_arrays.end(), std::make_move_iterator(matched_slices.begin()),
+ std::make_move_iterator(matched_slices.end()));
+ }
+ }
+
+ std::shared_ptr<arrow::Array> probe_array;
+ if (probe_arrays.empty()) {
+ PAIMON_ASSIGN_OR_RAISE_FROM_ARROW(
+ probe_array, arrow::MakeEmptyArray(arrow::struct_(probe_schema_->fields())));
+ } else {
+ PAIMON_ASSIGN_OR_RAISE_FROM_ARROW(probe_array,
+ arrow::Concatenate(probe_arrays, arrow_pool_.get()));
+ }
+ probe_data_ = arrow::internal::checked_pointer_cast<arrow::StructArray>(probe_array);
+ return Status::OK();
+}
+
+Result<FileBatchReader::ReadBatch> LateMaterializingFileBatchReader::ReadPayloadBatch() {
+ while (true) {
+ PAIMON_ASSIGN_OR_RAISE(FileBatchReader::ReadBatchWithBitmap batch_with_bitmap,
+ inner_->NextBatchWithBitmap());
+ if (BatchReader::IsEofBatch(batch_with_bitmap)) {
+ state_ = kEOF;
+ if (probe_cursor_ != probe_data_->length()) {
+ return Status::Invalid(
+ fmt::format("probe cursor {} does not match probe data length {}",
+ probe_cursor_, probe_data_->length()));
+ }
+ return MakeEofBatch();
+ }
+ auto& [batch, bitmap] = batch_with_bitmap;
+ if (bitmap.IsEmpty()) {
+ ReaderUtils::ReleaseReadBatch(std::move(batch));
+ continue;
Review Comment:
Done.
--
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: issues-unsubscribe@paimon.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(reader): support late materialization with probe/payload two-phase reads [paimon-cpp]
Posted by "zhf999 (via GitHub)" <gi...@apache.org>.
zhf999 commented on code in PR #243:
URL: https://github.com/apache/paimon-cpp/pull/243#discussion_r3861401327
##########
src/paimon/common/reader/late_materializing_file_batch_reader.h:
##########
@@ -0,0 +1,149 @@
+/*
+ * 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.
+ */
+
+#pragma once
+
+#include <arrow/array/array_nested.h>
+#include <arrow/c/abi.h>
+
+#include <cstdint>
+#include <memory>
+#include <utility>
+#include <vector>
+
+#include "paimon/reader/prefetch_file_batch_reader.h"
+
+namespace paimon {
+
+class PredicateFilter;
+
+// For convenience, we abbreviate `Later Materializing` as `LatMat`.
+// This reader is installed below the prefetch layer (see
+// AbstractSplitRead::CreateFileBatchReader) and performs probe/payload two-phase reads when a
+// predicate is pushed down through SetReadSchema; without a predicate it is a plain passthrough.
+class LateMaterializingFileBatchReader : public PrefetchFileBatchReader {
+ public:
+ static Result<std::unique_ptr<LateMaterializingFileBatchReader>> Create(
+ std::unique_ptr<PrefetchFileBatchReader> inner, std::shared_ptr<MemoryPool> pool);
+
+ Result<FileBatchReader::ReadBatch> NextBatch() override;
+
+ std::shared_ptr<Metrics> GetReaderMetrics() const override {
+ return inner_->GetReaderMetrics();
+ };
+
+ void Close() override {
+ inner_->Close();
+ }
+
+ Result<std::unique_ptr<::ArrowSchema>> GetFileSchema() const override {
+ return inner_->GetFileSchema();
+ }
+
+ Status SetReadSchema(::ArrowSchema* read_schema, const std::shared_ptr<Predicate>& predicate,
+ const std::optional<RoaringBitmap32>& selection_bitmap) override;
+
+ Result<uint64_t> GetPreviousBatchFileRowId(uint64_t batch_row_id) const override;
+
+ Result<uint64_t> GetNumberOfRows() const override {
+ return inner_->GetNumberOfRows();
+ }
+
+ bool SupportPreciseBitmapSelection() const override {
+ // When probe_schema_ or payload_schema_ is null, lat-mat does not take effect.
+ // Here we simply pass through the inner reader's support.
+ return inner_->SupportPreciseBitmapSelection();
+ }
+
+ Status SeekToRow(uint64_t row_number) override;
+
+ uint64_t GetNextRowToRead() const override {
+ return inner_->GetNextRowToRead();
+ }
+
+ Result<std::vector<std::pair<uint64_t, uint64_t>>> GenReadRanges(
+ bool* need_prefetch) const override {
+ return inner_->GenReadRanges(need_prefetch);
Review Comment:
Remain it for future work.
--
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: issues-unsubscribe@paimon.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(reader): support late materialization with probe/payload two-phase reads [paimon-cpp]
Posted by "zhf999 (via GitHub)" <gi...@apache.org>.
zhf999 commented on code in PR #243:
URL: https://github.com/apache/paimon-cpp/pull/243#discussion_r3859423583
##########
test/inte/read_inte_test.cpp:
##########
@@ -3109,6 +3194,7 @@ TEST_P(ReadInteTest, TestPkReadSnapshot6WithSchemaEvolutionWithPredicateOnlyPush
context_builder.SetReadAheadCacheEnabled(param.read_ahead_cache_enabled);
context_builder.SetPredicate(predicate);
context_builder.EnablePrefetch(param.enable_prefetch)
+ .EnableLateMaterializing(false)
.AddOption("test.enable-adaptive-prefetch-strategy",
Review Comment:
In there tests, result would diff from expected because LM reader returns a precise reuslt set. I set `EnableLateMaterializing` to false to avoid test failure in the future when late materialization is set to `true` by default.
--
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: issues-unsubscribe@paimon.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(reader): support late materialization with probe/payload two-phase reads [paimon-cpp]
Posted by "zhf999 (via GitHub)" <gi...@apache.org>.
zhf999 commented on code in PR #243:
URL: https://github.com/apache/paimon-cpp/pull/243#discussion_r3861864176
##########
src/paimon/common/reader/late_materializing_file_batch_reader_test.cpp:
##########
@@ -0,0 +1,647 @@
+/*
+ * 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.
+ */
+
+#include "paimon/common/reader/late_materializing_file_batch_reader.h"
+
+#include <algorithm>
+#include <cstdint>
+#include <limits>
+#include <memory>
+#include <optional>
+#include <string>
+#include <utility>
+#include <vector>
+
+#include "arrow/api.h"
+#include "arrow/array/builder_nested.h"
+#include "arrow/c/bridge.h"
+#include "gtest/gtest.h"
+#include "paimon/common/reader/late_materializing_reader_builder.h"
+#include "paimon/common/reader/prefetch_file_batch_reader_impl.h"
+#include "paimon/common/reader/reader_utils.h"
+#include "paimon/common/utils/arrow/status_utils.h"
+#include "paimon/common/utils/checked_cast.h"
+#include "paimon/common/utils/read_ahead_cache.h"
+#include "paimon/executor.h"
+#include "paimon/format/reader_builder.h"
+#include "paimon/memory/memory_pool.h"
+#include "paimon/predicate/literal.h"
+#include "paimon/predicate/predicate.h"
+#include "paimon/predicate/predicate_builder.h"
+#include "paimon/reader/prefetch_file_batch_reader.h"
+#include "paimon/status.h"
+#include "paimon/testing/mock/mock_file_batch_reader.h"
+#include "paimon/testing/mock/mock_file_system.h"
+#include "paimon/testing/mock/mock_format_reader_builder.h"
+#include "paimon/testing/utils/read_result_collector.h"
+#include "paimon/testing/utils/testharness.h"
+#include "paimon/utils/roaring_bitmap32.h"
+
+namespace paimon::test {
+
+class LateMaterializingFileBatchReaderTest : public ::testing::Test {
+ public:
+ void SetUp() override {
+ k_field_ = arrow::field("k", arrow::int64());
+ v_field_ = arrow::field("v", arrow::utf8());
+ full_fields_ = {k_field_, v_field_};
+ full_type_ = arrow::struct_(full_fields_);
+ }
+
+ // Build a struct array with column k (int64, values = ks) and column v (utf8, "v_<index>").
+ std::shared_ptr<arrow::Array> BuildData(const std::vector<int64_t>& ks) {
+ arrow::StructBuilder builder(
+ full_type_, arrow::default_memory_pool(),
+ {std::make_shared<arrow::Int64Builder>(), std::make_shared<arrow::StringBuilder>()});
+ auto* k_builder = checked_cast<arrow::Int64Builder*>(builder.field_builder(0));
+ auto* v_builder = checked_cast<arrow::StringBuilder*>(builder.field_builder(1));
+ for (size_t i = 0; i < ks.size(); ++i) {
+ EXPECT_TRUE(builder.Append().ok());
+ EXPECT_TRUE(k_builder->Append(ks[i]).ok());
+ EXPECT_TRUE(v_builder->Append("v_" + std::to_string(i)).ok());
+ }
+ std::shared_ptr<arrow::Array> array;
+ EXPECT_TRUE(builder.Finish(&array).ok());
+ return array;
+ }
+
+ struct Row {
+ int64_t k;
+ std::string v;
+ uint64_t file_row;
+ };
+
+ // Drive the reader through NextBatchWithBitmap to EOF, decoding the full-schema output rows.
+ Result<std::vector<Row>> Collect(LateMaterializingFileBatchReader* reader) {
+ std::vector<Row> rows;
+ while (true) {
+ PAIMON_ASSIGN_OR_RAISE(BatchReader::ReadBatchWithBitmap batch_with_bitmap,
+ reader->NextBatchWithBitmap());
+ if (BatchReader::IsEofBatch(batch_with_bitmap)) {
+ break;
+ }
+ auto& [batch, bitmap] = batch_with_bitmap;
+ auto& [c_array, c_schema] = batch;
+ PAIMON_ASSIGN_OR_RAISE_FROM_ARROW(std::shared_ptr<arrow::Array> array,
+ arrow::ImportArray(c_array.get(), c_schema.get()));
+ auto struct_array = arrow::internal::checked_pointer_cast<arrow::StructArray>(array);
+ EXPECT_EQ(bitmap.Cardinality(), static_cast<int32_t>(struct_array->length()));
+ auto k_array = arrow::internal::checked_pointer_cast<arrow::Int64Array>(
+ struct_array->GetFieldByName("k"));
+ if (!k_array) {
+ return Status::Invalid("output batch missing k column");
+ }
+ // v is only present when it belongs to the read schema (payload projection).
+ auto v_array = arrow::internal::checked_pointer_cast<arrow::StringArray>(
+ struct_array->GetFieldByName("v"));
+ for (int64_t i = 0; i < struct_array->length(); ++i) {
+ PAIMON_ASSIGN_OR_RAISE(uint64_t file_row,
+ reader->GetPreviousBatchFileRowId(static_cast<uint64_t>(i)));
+ rows.push_back(Row{k_array->Value(i),
+ v_array ? v_array->GetString(i) : std::string(), file_row});
+ }
+ }
+ return rows;
+ }
+
+ Status SetReadSchema(LateMaterializingFileBatchReader* reader,
+ const std::shared_ptr<arrow::Schema>& schema,
+ const std::shared_ptr<Predicate>& predicate,
+ const std::optional<RoaringBitmap32>& selection) {
+ ::ArrowSchema c_schema;
+ PAIMON_RETURN_NOT_OK_FROM_ARROW(arrow::ExportSchema(*schema, &c_schema));
+ return reader->SetReadSchema(&c_schema, predicate, selection);
+ }
+
+ // Collect all output rows as a single concatenated struct array (for schema/nested checks),
+ // reusing the shared collector so the batch-offset and bitmap contracts are checked too.
+ Result<std::shared_ptr<arrow::StructArray>> CollectStruct(FileBatchReader* reader) {
+ PAIMON_ASSIGN_OR_RAISE(std::shared_ptr<arrow::ChunkedArray> chunked,
+ ReadResultCollector::CollectResult(reader));
+ if (chunked == nullptr) {
+ return std::shared_ptr<arrow::StructArray>();
+ }
+ PAIMON_ASSIGN_OR_RAISE_FROM_ARROW(std::shared_ptr<arrow::Array> combined,
+ arrow::Concatenate(chunked->chunks()));
+ return arrow::internal::checked_pointer_cast<arrow::StructArray>(combined);
+ }
+
+ // Build a struct with 5 columns [a:int64, b:utf8, c:int64, d:utf8, e:int64], each carrying a
+ // distinct value pattern so any column reordering is detected.
+ std::shared_ptr<arrow::Array> BuildMultiFieldData(int32_t n) {
+ auto type =
+ arrow::struct_({arrow::field("a", arrow::int64()), arrow::field("b", arrow::utf8()),
+ arrow::field("c", arrow::int64()), arrow::field("d", arrow::utf8()),
+ arrow::field("e", arrow::int64())});
+ arrow::StructBuilder builder(
+ type, arrow::default_memory_pool(),
+ {std::make_shared<arrow::Int64Builder>(), std::make_shared<arrow::StringBuilder>(),
+ std::make_shared<arrow::Int64Builder>(), std::make_shared<arrow::StringBuilder>(),
+ std::make_shared<arrow::Int64Builder>()});
+ auto* a = checked_cast<arrow::Int64Builder*>(builder.field_builder(0));
+ auto* b = checked_cast<arrow::StringBuilder*>(builder.field_builder(1));
+ auto* c = checked_cast<arrow::Int64Builder*>(builder.field_builder(2));
+ auto* d = checked_cast<arrow::StringBuilder*>(builder.field_builder(3));
+ auto* e = checked_cast<arrow::Int64Builder*>(builder.field_builder(4));
+ for (int32_t i = 0; i < n; ++i) {
+ EXPECT_TRUE(builder.Append().ok());
+ EXPECT_TRUE(a->Append(i).ok());
+ EXPECT_TRUE(b->Append("b_" + std::to_string(i)).ok());
+ EXPECT_TRUE(c->Append(static_cast<int64_t>(i) * 100).ok());
+ EXPECT_TRUE(d->Append("d_" + std::to_string(i)).ok());
+ EXPECT_TRUE(e->Append(static_cast<int64_t>(i) * 10000).ok());
+ }
+ std::shared_ptr<arrow::Array> array;
+ EXPECT_TRUE(builder.Finish(&array).ok());
+ return array;
+ }
+
+ // Build a struct with a nested payload column [k:int64, arr:list<int64>, tag:utf8].
+ std::shared_ptr<arrow::Array> BuildNestedData(int32_t n) {
+ auto type = arrow::struct_({arrow::field("k", arrow::int64()),
+ arrow::field("arr", arrow::list(arrow::int64())),
+ arrow::field("tag", arrow::utf8())});
+ auto arr_value_builder = std::make_shared<arrow::Int64Builder>();
+ arrow::StructBuilder builder(
+ type, arrow::default_memory_pool(),
+ {std::make_shared<arrow::Int64Builder>(),
+ std::make_shared<arrow::ListBuilder>(arrow::default_memory_pool(), arr_value_builder),
+ std::make_shared<arrow::StringBuilder>()});
+ auto* k = checked_cast<arrow::Int64Builder*>(builder.field_builder(0));
+ auto* arr = checked_cast<arrow::ListBuilder*>(builder.field_builder(1));
+ auto* arr_values = checked_cast<arrow::Int64Builder*>(arr->value_builder());
+ auto* tag = checked_cast<arrow::StringBuilder*>(builder.field_builder(2));
+ for (int32_t i = 0; i < n; ++i) {
+ EXPECT_TRUE(builder.Append().ok());
+ EXPECT_TRUE(k->Append(i).ok());
+ EXPECT_TRUE(arr->Append().ok());
+ EXPECT_TRUE(arr_values->Append(i).ok());
+ EXPECT_TRUE(arr_values->Append(i + 1).ok());
+ EXPECT_TRUE(tag->Append("t_" + std::to_string(i)).ok());
+ }
+ std::shared_ptr<arrow::Array> array;
+ EXPECT_TRUE(builder.Finish(&array).ok());
+ return array;
+ }
+
+ protected:
+ std::shared_ptr<arrow::Field> k_field_;
+ std::shared_ptr<arrow::Field> v_field_;
+ arrow::FieldVector full_fields_;
+ std::shared_ptr<arrow::DataType> full_type_;
+};
+
+// No predicate: the reader must pass through the inner reader unchanged (all rows, all columns).
+TEST_F(LateMaterializingFileBatchReaderTest, PassThroughWhenNoPredicate) {
+ auto data = BuildData({0, 1, 2, 3, 4});
+ auto mock = std::make_unique<MockFileBatchReader>(data, full_type_, /*batch_size=*/2);
+ ASSERT_OK_AND_ASSIGN(
+ auto reader, LateMaterializingFileBatchReader::Create(std::move(mock), GetDefaultPool()));
+ ASSERT_OK(SetReadSchema(reader.get(), arrow::schema(full_fields_), /*predicate=*/nullptr,
+ std::nullopt));
+
+ ASSERT_OK_AND_ASSIGN(std::vector<Row> rows, Collect(reader.get()));
+ ASSERT_EQ(rows.size(), 5u);
+ for (int64_t i = 0; i < 5; ++i) {
+ EXPECT_EQ(rows[i].k, i);
+ EXPECT_EQ(rows[i].v, "v_" + std::to_string(i));
+ EXPECT_EQ(rows[i].file_row, static_cast<uint64_t>(i));
+ }
+}
+
+// The predicate references every projected column, so the payload set is empty: no late
+// materialization, plain pass-through.
+TEST_F(LateMaterializingFileBatchReaderTest, PassThroughWhenPayloadEmpty) {
+ auto data = BuildData({0, 1, 2, 3, 4});
+ auto mock = std::make_unique<MockFileBatchReader>(data, full_type_, /*batch_size=*/2);
+ ASSERT_OK_AND_ASSIGN(
+ auto reader, LateMaterializingFileBatchReader::Create(std::move(mock), GetDefaultPool()));
+ // read schema is just {k}; the predicate on k covers all columns -> payload empty
+ auto predicate = PredicateBuilder::GreaterOrEqual(/*field_index=*/0, /*field_name=*/"k",
+ FieldType::BIGINT, Literal(0l));
+ ASSERT_OK(SetReadSchema(reader.get(), arrow::schema({k_field_}), predicate, std::nullopt));
+
+ ASSERT_OK_AND_ASSIGN(std::vector<Row> rows, Collect(reader.get()));
+ ASSERT_EQ(rows.size(), 5u);
+}
+
+// Contiguous matched subset spanning multiple batches.
+TEST_F(LateMaterializingFileBatchReaderTest, ContiguousSubsetAcrossBatches) {
+ auto data = BuildData({0, 1, 2, 3, 4, 5, 6, 7, 8, 9});
+ auto mock = std::make_unique<MockFileBatchReader>(data, full_type_, /*batch_size=*/3);
+ ASSERT_OK_AND_ASSIGN(
+ auto reader, LateMaterializingFileBatchReader::Create(std::move(mock), GetDefaultPool()));
+ auto predicate = PredicateBuilder::GreaterThan(/*field_index=*/0, /*field_name=*/"k",
+ FieldType::BIGINT, Literal(4l));
+ ASSERT_OK(SetReadSchema(reader.get(), arrow::schema(full_fields_), predicate, std::nullopt));
+
+ ASSERT_OK_AND_ASSIGN(std::vector<Row> rows, Collect(reader.get()));
+ ASSERT_EQ(rows.size(), 5u); // k = 5..9
+ for (size_t idx = 0; idx < rows.size(); ++idx) {
+ int64_t expected = 5 + static_cast<int64_t>(idx);
+ EXPECT_EQ(rows[idx].k, expected);
+ EXPECT_EQ(rows[idx].v, "v_" + std::to_string(expected));
+ EXPECT_EQ(rows[idx].file_row, static_cast<uint64_t>(expected));
+ }
+}
+
+// Scattered (alternating) matched rows: predicate matches every other row.
+TEST_F(LateMaterializingFileBatchReaderTest, ScatteredAlternatingMatch) {
+ // k = 0,1,0,1,... ; predicate k == 1 matches all odd file rows.
+ std::vector<int64_t> ks;
+ for (int i = 0; i < 12; ++i) {
+ ks.push_back(i % 2);
+ }
+ auto data = BuildData(ks);
+ auto mock = std::make_unique<MockFileBatchReader>(data, full_type_, /*batch_size=*/3);
+ ASSERT_OK_AND_ASSIGN(
+ auto reader, LateMaterializingFileBatchReader::Create(std::move(mock), GetDefaultPool()));
+ auto predicate = PredicateBuilder::Equal(/*field_index=*/0, /*field_name=*/"k",
+ FieldType::BIGINT, Literal(1l));
+ ASSERT_OK(SetReadSchema(reader.get(), arrow::schema(full_fields_), predicate, std::nullopt));
+
+ ASSERT_OK_AND_ASSIGN(std::vector<Row> rows, Collect(reader.get()));
+ ASSERT_EQ(rows.size(), 6u); // odd rows 1,3,5,7,9,11
+ for (size_t idx = 0; idx < rows.size(); ++idx) {
+ uint64_t expected_row = 2 * idx + 1;
+ EXPECT_EQ(rows[idx].k, 1);
+ EXPECT_EQ(rows[idx].v, "v_" + std::to_string(expected_row));
+ EXPECT_EQ(rows[idx].file_row, expected_row);
+ }
+}
+
+// The selection bitmap further restricts the matched rows: matched must be a subset of selection.
+TEST_F(LateMaterializingFileBatchReaderTest, MatchedIntersectsSelection) {
+ std::vector<int64_t> ks;
+ for (int i = 0; i < 12; ++i) {
+ ks.push_back(i % 2);
+ }
+ auto data = BuildData(ks);
+ auto mock = std::make_unique<MockFileBatchReader>(data, full_type_, /*batch_size=*/4);
+ ASSERT_OK_AND_ASSIGN(
+ auto reader, LateMaterializingFileBatchReader::Create(std::move(mock), GetDefaultPool()));
+ auto predicate = PredicateBuilder::Equal(/*field_index=*/0, /*field_name=*/"k",
+ FieldType::BIGINT, Literal(1l));
+ // predicate hits {1,3,5,7,9,11}; selection keeps only {1,5,9}
+ RoaringBitmap32 selection;
+ selection.Add(1);
+ selection.Add(5);
+ selection.Add(9);
+ ASSERT_OK(SetReadSchema(reader.get(), arrow::schema(full_fields_), predicate,
+ std::optional<RoaringBitmap32>(selection)));
+
+ ASSERT_OK_AND_ASSIGN(std::vector<Row> rows, Collect(reader.get()));
+ ASSERT_EQ(rows.size(), 3u);
+ EXPECT_EQ(rows[0].file_row, 1u);
+ EXPECT_EQ(rows[1].file_row, 5u);
+ EXPECT_EQ(rows[2].file_row, 9u);
+ EXPECT_EQ(rows[0].v, "v_1");
+ EXPECT_EQ(rows[1].v, "v_5");
+ EXPECT_EQ(rows[2].v, "v_9");
+}
+
+// No matched rows: the reader returns EOF immediately.
+TEST_F(LateMaterializingFileBatchReaderTest, EmptyMatchReturnsEof) {
+ auto data = BuildData({0, 1, 2, 3, 4});
+ auto mock = std::make_unique<MockFileBatchReader>(data, full_type_, /*batch_size=*/2);
+ ASSERT_OK_AND_ASSIGN(
+ auto reader, LateMaterializingFileBatchReader::Create(std::move(mock), GetDefaultPool()));
+ auto predicate = PredicateBuilder::GreaterThan(/*field_index=*/0, /*field_name=*/"k",
+ FieldType::BIGINT, Literal(100l));
+ ASSERT_OK(SetReadSchema(reader.get(), arrow::schema(full_fields_), predicate, std::nullopt));
+
+ ASSERT_OK_AND_ASSIGN(std::vector<Row> rows, Collect(reader.get()));
+ ASSERT_TRUE(rows.empty());
+}
+
+// SeekToRow during payload emission must re-align the probe cursor so probe/payload stay matched.
+TEST_F(LateMaterializingFileBatchReaderTest, SeekToRowRealignsProbeCursor) {
+ auto data = BuildData({0, 1, 2, 3, 4, 5, 6, 7, 8, 9});
+ auto mock = std::make_unique<MockFileBatchReader>(data, full_type_, /*batch_size=*/4);
+ ASSERT_OK_AND_ASSIGN(
+ auto reader, LateMaterializingFileBatchReader::Create(std::move(mock), GetDefaultPool()));
+ auto predicate = PredicateBuilder::GreaterOrEqual(/*field_index=*/0, /*field_name=*/"k",
+ FieldType::BIGINT, Literal(5l));
+ ASSERT_OK(SetReadSchema(reader.get(), arrow::schema(full_fields_), predicate, std::nullopt));
+
+ // First payload batch triggers the probe scan; matched rows are 5..9.
+ ASSERT_OK_AND_ASSIGN(BatchReader::ReadBatchWithBitmap first, reader->NextBatchWithBitmap());
+ ASSERT_FALSE(BatchReader::IsEofBatch(first));
+ ReaderUtils::ReleaseReadBatch(std::move(first.first));
+
+ // Seek forward to file row 8: subsequent output must be exactly rows 8 and 9, correctly paired.
+ ASSERT_OK(reader->SeekToRow(8));
+ ASSERT_OK_AND_ASSIGN(std::vector<Row> rows, Collect(reader.get()));
+ ASSERT_EQ(rows.size(), 2u);
+ EXPECT_EQ(rows[0].k, 8);
+ EXPECT_EQ(rows[0].v, "v_8");
+ EXPECT_EQ(rows[0].file_row, 8u);
+ EXPECT_EQ(rows[1].k, 9);
+ EXPECT_EQ(rows[1].v, "v_9");
+ EXPECT_EQ(rows[1].file_row, 9u);
+}
+
+// SetReadRanges must be cached and re-forwarded to the inner reader across the probe/payload
+// schema switches (SetReadSchema resets the inner reader's ranges).
+TEST_F(LateMaterializingFileBatchReaderTest, ReadRangesForwardedAcrossPhases) {
+ auto data = BuildData({0, 1, 2, 3, 4, 5, 6, 7});
+ auto mock = std::make_unique<MockFileBatchReader>(data, full_type_, /*batch_size=*/4);
+ auto* mock_ptr = mock.get();
+ ASSERT_OK_AND_ASSIGN(
+ auto reader, LateMaterializingFileBatchReader::Create(std::move(mock), GetDefaultPool()));
+ auto predicate = PredicateBuilder::GreaterOrEqual(/*field_index=*/0, /*field_name=*/"k",
+ FieldType::BIGINT, Literal(2l));
+ ASSERT_OK(SetReadSchema(reader.get(), arrow::schema(full_fields_), predicate, std::nullopt));
+
+ std::vector<std::pair<uint64_t, uint64_t>> ranges = {{0, 8}};
+ ASSERT_OK(reader->SetReadRanges(ranges));
+
+ // Drive to EOF; this performs the probe pass and the payload schema switch.
+ ASSERT_OK_AND_ASSIGN(std::vector<Row> rows, Collect(reader.get()));
+ ASSERT_EQ(rows.size(), 6u); // k = 2..7
+
+ // The inner reader must have received the cached ranges again after the payload switch.
+ // SetReadSchema (invoked on the payload switch) clears the inner reader's ranges, so the
+ // cached ranges still being present at the end proves LM re-forwarded them after the switch.
+ ASSERT_EQ(mock_ptr->GetReadRanges(), ranges);
+}
+
+// SetReadSchema is re-entrant: a second call with a different predicate resets probe state.
+TEST_F(LateMaterializingFileBatchReaderTest, ReentrantSetReadSchema) {
+ auto data = BuildData({0, 1, 2, 3, 4, 5, 6, 7, 8, 9});
+ auto mock = std::make_unique<MockFileBatchReader>(data, full_type_, /*batch_size=*/3);
+ ASSERT_OK_AND_ASSIGN(
+ auto reader, LateMaterializingFileBatchReader::Create(std::move(mock), GetDefaultPool()));
+
+ auto predicate1 = PredicateBuilder::GreaterThan(/*field_index=*/0, /*field_name=*/"k",
+ FieldType::BIGINT, Literal(7l));
+ ASSERT_OK(SetReadSchema(reader.get(), arrow::schema(full_fields_), predicate1, std::nullopt));
+ ASSERT_OK_AND_ASSIGN(std::vector<Row> rows1, Collect(reader.get()));
+ ASSERT_EQ(rows1.size(), 2u); // k = 8,9
+
+ auto predicate2 = PredicateBuilder::LessThan(/*field_index=*/0, /*field_name=*/"k",
+ FieldType::BIGINT, Literal(3l));
+ ASSERT_OK(SetReadSchema(reader.get(), arrow::schema(full_fields_), predicate2, std::nullopt));
+ ASSERT_OK_AND_ASSIGN(std::vector<Row> rows2, Collect(reader.get()));
+ ASSERT_EQ(rows2.size(), 3u); // k = 0,1,2
+ for (size_t idx = 0; idx < rows2.size(); ++idx) {
+ EXPECT_EQ(rows2[idx].k, static_cast<int64_t>(idx));
+ EXPECT_EQ(rows2[idx].file_row, static_cast<uint64_t>(idx));
+ }
+}
+
+// Forwarded metadata accessors should reflect the inner reader.
+TEST_F(LateMaterializingFileBatchReaderTest, ForwardsRowCountAndFileSchema) {
+ auto data = BuildData({0, 1, 2, 3});
+ auto mock = std::make_unique<MockFileBatchReader>(data, full_type_, /*batch_size=*/2);
+ ASSERT_OK_AND_ASSIGN(
+ auto reader, LateMaterializingFileBatchReader::Create(std::move(mock), GetDefaultPool()));
+
+ ASSERT_OK_AND_ASSIGN(uint64_t num_rows, reader->GetNumberOfRows());
+ EXPECT_EQ(num_rows, 4u);
+ ASSERT_OK_AND_ASSIGN(std::unique_ptr<::ArrowSchema> c_file_schema, reader->GetFileSchema());
+ auto import_result = arrow::ImportType(c_file_schema.get());
+ ASSERT_TRUE(import_result.ok());
+ EXPECT_TRUE(import_result.ValueOrDie()->Equals(full_type_));
+}
+
+// With many columns and a predicate over two non-adjacent probe columns, the output must keep the
+// full read-schema field order (and each probe/payload column's values must not be scrambled).
+TEST_F(LateMaterializingFileBatchReaderTest, MultiFieldPreservesColumnOrder) {
+ auto data = BuildMultiFieldData(10);
+ auto type = data->type();
+ auto mock = std::make_unique<MockFileBatchReader>(data, type, /*batch_size=*/3);
+ ASSERT_OK_AND_ASSIGN(
+ auto reader, LateMaterializingFileBatchReader::Create(std::move(mock), GetDefaultPool()));
+ // probe columns = {a (idx0), c (idx2)}; payload columns = {b, d, e}
+ auto pred_a =
+ PredicateBuilder::GreaterOrEqual(/*field_index=*/0, "a", FieldType::BIGINT, Literal(3l));
+ auto pred_c =
+ PredicateBuilder::LessThan(/*field_index=*/2, "c", FieldType::BIGINT, Literal(700l));
+ ASSERT_OK_AND_ASSIGN(auto predicate, PredicateBuilder::And({pred_a, pred_c}));
+ ASSERT_OK(SetReadSchema(reader.get(), arrow::schema(type->fields()), predicate, std::nullopt));
+
+ ASSERT_OK_AND_ASSIGN(std::shared_ptr<arrow::StructArray> result, CollectStruct(reader.get()));
+ ASSERT_TRUE(result);
+ // a >= 3 and c(=i*100) < 700 -> i in {3,4,5,6}
+ ASSERT_EQ(result->length(), 4);
+ // output field order must equal the requested full schema order
+ ASSERT_EQ(result->num_fields(), 5);
+ auto out_type = arrow::internal::checked_pointer_cast<arrow::StructType>(result->type());
+ EXPECT_EQ(out_type->field(0)->name(), "a");
+ EXPECT_EQ(out_type->field(1)->name(), "b");
+ EXPECT_EQ(out_type->field(2)->name(), "c");
+ EXPECT_EQ(out_type->field(3)->name(), "d");
+ EXPECT_EQ(out_type->field(4)->name(), "e");
+ auto a = arrow::internal::checked_pointer_cast<arrow::Int64Array>(result->GetFieldByName("a"));
+ auto b = arrow::internal::checked_pointer_cast<arrow::StringArray>(result->GetFieldByName("b"));
+ auto c = arrow::internal::checked_pointer_cast<arrow::Int64Array>(result->GetFieldByName("c"));
+ auto d = arrow::internal::checked_pointer_cast<arrow::StringArray>(result->GetFieldByName("d"));
+ auto e = arrow::internal::checked_pointer_cast<arrow::Int64Array>(result->GetFieldByName("e"));
+ const std::vector<int64_t> expected = {3, 4, 5, 6};
+ for (size_t j = 0; j < expected.size(); ++j) {
+ int64_t i = expected[j];
+ EXPECT_EQ(a->Value(j), i);
+ EXPECT_EQ(b->GetString(j), "b_" + std::to_string(i));
+ EXPECT_EQ(c->Value(j), i * 100);
+ EXPECT_EQ(d->GetString(j), "d_" + std::to_string(i));
+ EXPECT_EQ(e->Value(j), i * 10000);
+ }
+}
+
+// A nested (list) payload column must round-trip unchanged for the matched rows.
+TEST_F(LateMaterializingFileBatchReaderTest, NestedPayloadColumn) {
+ auto data = BuildNestedData(8);
+ auto type = data->type();
+ auto mock = std::make_unique<MockFileBatchReader>(data, type, /*batch_size=*/3);
+ ASSERT_OK_AND_ASSIGN(
+ auto reader, LateMaterializingFileBatchReader::Create(std::move(mock), GetDefaultPool()));
+ // probe = {k}; payload = {arr (list<int64>), tag}
+ auto predicate =
+ PredicateBuilder::GreaterOrEqual(/*field_index=*/0, "k", FieldType::BIGINT, Literal(5l));
+ ASSERT_OK(SetReadSchema(reader.get(), arrow::schema(type->fields()), predicate, std::nullopt));
+
+ ASSERT_OK_AND_ASSIGN(std::shared_ptr<arrow::StructArray> result, CollectStruct(reader.get()));
+ ASSERT_TRUE(result);
+ ASSERT_EQ(result->length(), 3); // k = 5,6,7
Review Comment:
The result record values are validated in later loop.
--
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: issues-unsubscribe@paimon.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(reader): support late materialization with probe/payload two-phase reads [paimon-cpp]
Posted by "gripleaf (via GitHub)" <gi...@apache.org>.
gripleaf commented on code in PR #243:
URL: https://github.com/apache/paimon-cpp/pull/243#discussion_r3860836335
##########
src/paimon/common/reader/late_materializing_file_batch_reader.h:
##########
@@ -0,0 +1,153 @@
+/*
+ * 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.
+ */
+
+#pragma once
+
+#include <arrow/array/array_nested.h>
+#include <arrow/c/abi.h>
+
+#include <cstdint>
+#include <memory>
+#include <utility>
+#include <vector>
+
+#include "paimon/reader/prefetch_file_batch_reader.h"
+
+namespace paimon {
+
+class PredicateFilter;
+
+// For convenience, we abbreviate `Later Materializing` as `LatMat`.
+// This reader is installed below the prefetch layer (see
+// AbstractSplitRead::CreateFileBatchReader) and performs probe/payload two-phase reads when a
+// predicate is pushed down through SetReadSchema; without a predicate it is a plain passthrough.
+class LateMaterializingFileBatchReader : public PrefetchFileBatchReader {
+ public:
+ static Result<std::unique_ptr<LateMaterializingFileBatchReader>> Create(
+ std::unique_ptr<PrefetchFileBatchReader> inner, std::shared_ptr<MemoryPool> pool);
+
+ Result<FileBatchReader::ReadBatch> NextBatch() override;
+
+ std::shared_ptr<Metrics> GetReaderMetrics() const override {
+ return inner_->GetReaderMetrics();
+ };
+
+ void Close() override {
+ Reset();
+ inner_->Close();
+ }
+
+ Result<std::unique_ptr<::ArrowSchema>> GetFileSchema() const override {
+ return inner_->GetFileSchema();
+ }
+
+ Status SetReadSchema(::ArrowSchema* read_schema, const std::shared_ptr<Predicate>& predicate,
+ const std::optional<RoaringBitmap32>& selection_bitmap) override;
+
+ Result<uint64_t> GetPreviousBatchFileRowId(uint64_t batch_row_id) const override;
+
+ Result<uint64_t> GetNumberOfRows() const override {
+ return inner_->GetNumberOfRows();
+ }
+
+ bool SupportPreciseBitmapSelection() const override {
+ // When probe_schema_ or payload_schema_ is null, lat-mat does not take effect.
+ // Here we simply pass through the inner reader's support.
+ return inner_->SupportPreciseBitmapSelection();
+ }
+
+ Status SeekToRow(uint64_t row_number) override;
+
+ uint64_t GetNextRowToRead() const override {
+ return inner_->GetNextRowToRead();
+ }
+
+ Result<std::vector<std::pair<uint64_t, uint64_t>>> GenReadRanges(
+ bool* need_prefetch) const override {
+ return inner_->GenReadRanges(need_prefetch);
+ }
+
+ Status SetReadRanges(const std::vector<std::pair<uint64_t, uint64_t>>& read_ranges) override;
+
+ Result<std::vector<std::pair<uint64_t, uint64_t>>> PreBufferRange() override {
+ // TODO(zhouhongfeng.zhf): PrebufferRange (called by PrefetchFileBatchReader) only read the
Review Comment:
In point-lookup scenarios, especially when the payload is large, pre-buffering payload columns before the probe result is available may introduce significant read amplification, because most prefetched payload data may never be used. I suggest keeping probe-only pre-buffering as the default behavior.
If payload pre-buffering is introduced later, it would be better to make it configurable so users can choose between minimizing I/O and reducing payload-read latency based on their workload.
--
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: issues-unsubscribe@paimon.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(reader): support late materialization with probe/payload two-phase reads [paimon-cpp]
Posted by "zhf999 (via GitHub)" <gi...@apache.org>.
zhf999 commented on code in PR #243:
URL: https://github.com/apache/paimon-cpp/pull/243#discussion_r3861390914
##########
src/paimon/common/reader/late_materializing_file_batch_reader.cpp:
##########
@@ -0,0 +1,352 @@
+/*
+ * 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.
+ */
+
+#include "paimon/common/reader/late_materializing_file_batch_reader.h"
+
+#include <map>
+#include <set>
+#include <string>
+#include <utility>
+#include <vector>
+
+#include "arrow/array/concatenate.h"
+#include "arrow/array/util.h"
+#include "arrow/c/bridge.h"
+#include "arrow/memory_pool.h"
+#include "arrow/type.h"
+#include "arrow/util/checked_cast.h"
+#include "fmt/format.h"
+#include "paimon/common/predicate/predicate_filter.h"
+#include "paimon/common/predicate/predicate_validator.h"
+#include "paimon/common/reader/reader_utils.h"
+#include "paimon/common/utils/arrow/arrow_utils.h"
+#include "paimon/common/utils/arrow/mem_utils.h"
+#include "paimon/common/utils/arrow/status_utils.h"
+#include "paimon/predicate/predicate_utils.h"
+#include "paimon/status.h"
+
+namespace paimon {
+
+Result<std::unique_ptr<LateMaterializingFileBatchReader>> LateMaterializingFileBatchReader::Create(
+ std::unique_ptr<PrefetchFileBatchReader> inner, std::shared_ptr<MemoryPool> pool) {
+ // The reader's own compaction allocations go through an arrow pool; bridge the paimon pool
+ // once here so the accounting matches the rest of the read path.
+ if (pool == nullptr) {
+ return Status::Invalid("pool could not be nullptr.");
+ }
+ std::shared_ptr<arrow::MemoryPool> arrow_pool = GetArrowPool(pool);
+ auto reader = std::unique_ptr<LateMaterializingFileBatchReader>(
+ new LateMaterializingFileBatchReader(std::move(inner), std::move(arrow_pool)));
+ return reader;
+}
+
+Result<FileBatchReader::ReadBatch> LateMaterializingFileBatchReader::NextBatch() {
+ if (state_ == kInit) {
+ // SetReadSchema has not been called: read with the file schema, matching the
+ // FileBatchReader contract for schema-less reads.
+ state_ = kNoLatMat;
+ }
+ if (state_ == kProbing) {
+ PAIMON_RETURN_NOT_OK(ReadAndFilterProbeData());
+ if (matched_bitmap_.IsEmpty()) {
+ state_ = kEOF;
+ } else {
+ // payload pass reads only the matched rows (matched_bitmap_ is non-empty here).
+ PAIMON_RETURN_NOT_OK(
+ SetInnerReadSchema(payload_schema_, /*predicate=*/nullptr, matched_bitmap_));
+ state_ = kRunning;
+ }
+ }
+
+ if (state_ == kNoLatMat) {
+ return inner_->NextBatch();
+ } else if (state_ == kRunning) {
+ return ReadPayloadBatch();
+ } else if (state_ == kEOF) {
+ return MakeEofBatch();
+ }
+ return Status::Invalid("invalid state when calling NextBatch: " + std::to_string(state_));
+}
Review Comment:
Remain it for future work.
--
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: issues-unsubscribe@paimon.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(reader): support late materialization with probe/payload two-phase reads [paimon-cpp]
Posted by "lxy-9602 (via GitHub)" <gi...@apache.org>.
lxy-9602 merged PR #243:
URL: https://github.com/apache/paimon-cpp/pull/243
--
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: issues-unsubscribe@paimon.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org