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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to