kamcheungting-db commented on code in PR #1167:
URL: https://github.com/apache/iceberg-cpp/pull/1167#discussion_r4733567682


##########
src/iceberg/data/parallel_scan_reader.cc:
##########
@@ -0,0 +1,592 @@
+/*
+ * 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 "iceberg/data/parallel_scan_reader.h"
+
+#include <algorithm>
+#include <chrono>
+#include <condition_variable>
+#include <cstdint>
+#include <deque>
+#include <exception>
+#include <format>
+#include <memory>
+#include <mutex>
+#include <optional>
+#include <string>
+#include <string_view>
+#include <thread>
+#include <utility>
+#include <vector>
+
+#include <nanoarrow/nanoarrow.h>
+
+#include "iceberg/arrow_c_data_guard_internal.h"
+#include "iceberg/arrow_c_data_util_internal.h"
+#include "iceberg/data/arrow_batch_sizer_internal.h"
+#include "iceberg/data/parallel_scan_reader_internal.h"
+#include "iceberg/file_reader.h"
+#include "iceberg/manifest/manifest_entry.h"
+#include "iceberg/nanoarrow_status_internal.h"
+#include "iceberg/schema.h"
+#include "iceberg/schema_internal.h"
+#include "iceberg/util/macros.h"
+
+namespace iceberg {
+
+namespace internal {
+
+ParallelScanMetricsSnapshot ParallelScanMetrics::Snapshot() const {
+  std::lock_guard lock(mutex_);
+  return snapshot_;
+}
+
+namespace {
+
+// Names a task in error messages, e.g. "data file s3://b/f.parquet [0, 1024)".
+std::string DescribeTask(const FileScanTask& task) {
+  const auto& data_file = task.data_file();
+  if (data_file == nullptr) {
+    return "task without a data file";
+  }
+  if (!task.is_split()) {
+    return std::format("data file {}", data_file->file_path);
+  }
+  return std::format("data file {} [{}, {})", data_file->file_path, 
task.start(),
+                     task.start() + task.length());
+}
+
+Error WithContext(const Error& error, std::string_view context) {
+  return Error{.kind = error.kind,
+               .message = std::format("{}: {}", context, error.message)};
+}
+
+std::string_view NullSafe(const char* value) {
+  return value == nullptr ? std::string_view{} : std::string_view{value};
+}
+
+// Compares the physical layout of two Arrow schemas. Field names, formats,
+// nullability, children, and dictionaries must match; metadata is ignored and 
the
+// root name is not compared.
+Status CheckSameLayout(const ArrowSchema& expected, const ArrowSchema& actual,
+                       const std::string& path, bool compare_name) {
+  if (NullSafe(expected.format) != NullSafe(actual.format)) {
+    return InvalidSchema("Field {} has Arrow format '{}', expected '{}'", path,
+                         NullSafe(actual.format), NullSafe(expected.format));
+  }
+  if (compare_name && NullSafe(expected.name) != NullSafe(actual.name)) {
+    return InvalidSchema("Field {} is named '{}', expected '{}'", path,
+                         NullSafe(actual.name), NullSafe(expected.name));
+  }
+  if ((expected.flags & ARROW_FLAG_NULLABLE) != (actual.flags & 
ARROW_FLAG_NULLABLE)) {
+    return InvalidSchema("Field {} nullability differs from the projected 
schema", path);
+  }
+  if (expected.n_children != actual.n_children) {
+    return InvalidSchema("Field {} has {} children, expected {}", path, 
actual.n_children,
+                         expected.n_children);
+  }
+  for (int64_t index = 0; index < expected.n_children; ++index) {
+    const ArrowSchema* expected_child = expected.children[index];
+    const ArrowSchema* actual_child = actual.children[index];
+    if (actual_child == nullptr || expected_child == nullptr) {
+      return InvalidSchema("Field {} has a null child", path);
+    }
+    std::string child_path = std::format("{}.{}", path, 
NullSafe(expected_child->name));
+    ICEBERG_RETURN_UNEXPECTED(
+        CheckSameLayout(*expected_child, *actual_child, child_path, true));
+  }
+  if ((expected.dictionary == nullptr) != (actual.dictionary == nullptr)) {
+    return InvalidSchema("Field {} dictionary encoding differs from the 
projected schema",
+                         path);
+  }
+  if (expected.dictionary != nullptr) {
+    ICEBERG_RETURN_UNEXPECTED(CheckSameLayout(*expected.dictionary, 
*actual.dictionary,
+                                              path + ".dictionary", false));
+  }
+  return {};
+}
+
+// Releases an ArrowArrayStream on scope exit.
+class StreamGuard {
+ public:
+  explicit StreamGuard(ArrowArrayStream* stream) : stream_(stream) {}
+  ~StreamGuard() {
+    if (stream_->release != nullptr) {
+      stream_->release(stream_);
+    }
+  }
+  StreamGuard(const StreamGuard&) = delete;
+  StreamGuard& operator=(const StreamGuard&) = delete;
+
+ private:
+  ArrowArrayStream* stream_;
+};
+
+void ReleaseArray(ArrowArray* array) {
+  if (array->release != nullptr) {
+    array->release(array);
+  }
+}
+
+struct QueuedBatch {
+  ArrowArray array;
+  int64_t charge;
+};
+
+void ReleaseAll(std::deque<QueuedBatch>& batches) {
+  for (auto& batch : batches) {
+    ReleaseArray(&batch.array);
+  }
+  batches.clear();
+}
+
+// Shared state of one parallel read. All fields below `mutex_` are guarded by 
it.
+// No planning or reader callback, Arrow release callback, thread join, or 
group
+// stream destructor runs while `mutex_` is held.
+class ParallelScan {
+ public:
+  ParallelScan(FileScanTaskGroupStreamPtr groups, ArrowSchema output_schema,
+               int64_t max_queued_batches, int64_t max_queued_bytes,
+               std::shared_ptr<ParallelScanMetrics> metrics)
+      : groups_(std::move(groups)),
+        output_schema_(output_schema),
+        max_queued_batches_(max_queued_batches),
+        max_queued_bytes_(max_queued_bytes),
+        metrics_(std::move(metrics)) {}
+
+  ~ParallelScan() {
+    Shutdown();
+    if (output_schema_.release != nullptr) {
+      output_schema_.release(&output_schema_);
+    }
+  }
+
+  ParallelScan(const ParallelScan&) = delete;
+  ParallelScan& operator=(const ParallelScan&) = delete;
+
+  Status Start(const FileScanTaskReader::Options& reader_options, int32_t 
worker_count) {
+    std::vector<std::unique_ptr<FileScanTaskReader>> readers;
+    std::vector<std::unique_ptr<ArrowBatchSizer>> sizers;
+    readers.reserve(static_cast<size_t>(worker_count));
+    sizers.reserve(static_cast<size_t>(worker_count));
+    for (int32_t index = 0; index < worker_count; ++index) {
+      ICEBERG_ASSIGN_OR_RAISE(auto reader, 
FileScanTaskReader::Make(reader_options));

Review Comment:
   Done.
   
   - Name-mapping indexes are now built during construction, so concurrent 
lookups are read-only.
   - Added ConcurrentFirstLookups regression coverage.



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


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to