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

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

Reply via email to