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


##########
src/iceberg/benchmark/parallel_scan_benchmark.cc:
##########
@@ -0,0 +1,625 @@
+/*
+ * 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.
+ */
+
+// Compares serial and parallel scans of local tables.
+//
+// Two workloads are written under --dir: a few large multi-row-group Parquet 
files,
+// and hundreds of small Parquet files. For each workload the benchmark runs 
paired
+// trials of the serial path (PlanFilesStream() and FileScanTaskReader) and the
+// parallel path (PlanTasksStream() and ParallelScanReader) with the same 
projection,
+// filter, and batch size, alternating which runs first. It reports the 
bootstrapped
+// median and 95% confidence interval of the paired elapsed-time speedup, end 
to end
+// and for the read phase. Timings are not stable enough for CI assertions.
+//
+// Usage: parallel_scan_benchmark [--dir=PATH] [--trials=N] [--workers=N]
+//                                [--workload=large|small|all] [--sweep]
+//                                [--filter=all-pass|none]
+
+#include <algorithm>
+#include <array>
+#include <chrono>
+#include <cmath>
+#include <cstdint>
+#include <cstdio>
+#include <cstdlib>
+#include <filesystem>
+#include <format>
+#include <fstream>
+#include <iostream>
+#include <memory>
+#include <numeric>
+#include <optional>
+#include <random>
+#include <string>
+#include <string_view>
+#include <thread>
+#include <utility>
+#include <vector>
+
+#include <arrow/array.h>
+#include <arrow/builder.h>
+#include <arrow/c/bridge.h>
+#include <arrow/memory_pool.h>
+#include <arrow/util/thread_pool.h>
+#include <sys/resource.h>
+
+#include "iceberg/arrow/arrow_io_internal.h"
+#include "iceberg/avro/avro_register.h"
+#include "iceberg/catalog/memory/in_memory_catalog.h"
+#include "iceberg/data/data_writer.h"
+#include "iceberg/data/file_scan_task_reader.h"
+#include "iceberg/data/parallel_scan_reader.h"
+#include "iceberg/data/parallel_scan_reader_internal.h"
+#include "iceberg/data_table_scan.h"
+#include "iceberg/expression/expressions.h"
+#include "iceberg/parquet/parquet_register.h"
+#include "iceberg/partition_spec.h"
+#include "iceberg/schema.h"
+#include "iceberg/sort_order.h"
+#include "iceberg/table.h"
+#include "iceberg/table_identifier.h"
+#include "iceberg/type.h"
+#include "iceberg/update/fast_append.h"
+#include "iceberg/util/executor.h"
+#include "iceberg/util/macros.h"
+
+namespace iceberg {
+namespace {
+
+using Clock = std::chrono::steady_clock;
+
+struct Workload {
+  std::string name;
+  int files;
+  int64_t rows_per_file;
+  int64_t rows_per_row_group;
+  // read.split.target-size table property, so large files are split into 
ranges.
+  int64_t target_split_size;
+};
+
+struct Config {
+  std::filesystem::path dir = std::filesystem::temp_directory_path() / 
"iceberg-pss";
+  int trials = 10;
+  int primary_workers = 0;
+  std::string workload = "all";
+  bool sweep = false;
+  // Whether scans carry an always-true residual filter that is evaluated per 
row.
+  bool filter = true;
+};
+
+// One timed scan.
+// Process-wide I/O and Arrow default-pool counters. A scan's cost is the
+// difference between readings taken before and after it.
+struct Counters {
+  // Bytes read through read(2)-family calls (/proc/self/io rchar); -1 if 
unavailable.
+  int64_t bytes_read = -1;
+  int64_t allocations = 0;
+  int64_t allocated_bytes = 0;
+
+  Counters operator-(const Counters& before) const {
+    return {.bytes_read = bytes_read < 0 || before.bytes_read < 0
+                              ? -1
+                              : bytes_read - before.bytes_read,
+            .allocations = allocations - before.allocations,
+            .allocated_bytes = allocated_bytes - before.allocated_bytes};
+  }
+};
+
+Counters ReadCounters() {
+  Counters counters;
+  std::ifstream io("/proc/self/io");
+  std::string key;
+  int64_t value = 0;
+  while (io >> key >> value) {
+    if (key == "rchar:") {
+      counters.bytes_read = value;
+      break;
+    }
+  }
+  auto* pool = ::arrow::default_memory_pool();
+  counters.allocations = pool->num_allocations();
+  counters.allocated_bytes = pool->total_bytes_allocated();
+  return counters;
+}
+
+struct Run {
+  Counters counters;
+  double total_seconds = 0;
+  double read_seconds = 0;
+  int64_t rows = 0;
+  int64_t batches = 0;
+  std::optional<internal::ParallelScanMetricsSnapshot> metrics;
+};
+
+std::shared_ptr<Schema> TableSchema() {
+  return std::make_shared<Schema>(
+      std::vector<SchemaField>{SchemaField::MakeRequired(1, "id", int64()),
+                               SchemaField::MakeRequired(2, "data", string()),
+                               SchemaField::MakeRequired(3, "value", 
float64())});
+}
+
+Status Check(const ::arrow::Status& status) {
+  if (!status.ok()) {
+    return IOError("{}", status.ToString());
+  }
+  return {};
+}
+
+Result<std::shared_ptr<DataFile>> WriteFile(const std::shared_ptr<FileIO>& io,
+                                            const std::shared_ptr<Schema>& 
schema,
+                                            const std::string& path, int64_t 
first_id,
+                                            const Workload& workload) {
+  ICEBERG_ASSIGN_OR_RAISE(
+      auto writer,
+      DataWriter::Make(
+          {.path = path,
+           .schema = schema,
+           .spec = PartitionSpec::Unpartitioned(),
+           .partition = PartitionValues{},
+           .format = FileFormatType::kParquet,
+           .io = io,
+           .properties = {{"write.parquet.max-row-group-rows",
+                           std::to_string(workload.rows_per_row_group)},
+                          {"write.parquet.compression-codec", 
"uncompressed"}}}));
+  constexpr int64_t kChunkRows = 65536;
+  for (int64_t start = 0; start < workload.rows_per_file; start += kChunkRows) 
{
+    const int64_t rows = std::min(kChunkRows, workload.rows_per_file - start);
+    ::arrow::Int64Builder ids;
+    ::arrow::StringBuilder data;
+    ::arrow::DoubleBuilder values;
+    for (int64_t row = 0; row < rows; ++row) {
+      const int64_t id = first_id + start + row;
+      ICEBERG_RETURN_UNEXPECTED(Check(ids.Append(id)));
+      ICEBERG_RETURN_UNEXPECTED(
+          Check(data.Append(std::format("payload-{:08}-{}", id % 100000, id % 
7))));
+      ICEBERG_RETURN_UNEXPECTED(Check(values.Append(static_cast<double>(id) * 
0.5)));
+    }
+    std::shared_ptr<::arrow::Array> id_array;
+    std::shared_ptr<::arrow::Array> data_array;
+    std::shared_ptr<::arrow::Array> value_array;
+    ICEBERG_RETURN_UNEXPECTED(Check(ids.Finish(&id_array)));
+    ICEBERG_RETURN_UNEXPECTED(Check(data.Finish(&data_array)));
+    ICEBERG_RETURN_UNEXPECTED(Check(values.Finish(&value_array)));
+    auto batch =
+        ::arrow::StructArray::Make({id_array, data_array, value_array},
+                                   std::vector<std::string>{"id", "data", 
"value"});
+    if (!batch.ok()) {
+      return IOError("{}", batch.status().ToString());
+    }
+    ArrowArray c_array{};
+    ICEBERG_RETURN_UNEXPECTED(Check(::arrow::ExportArray(**batch, &c_array)));
+    auto status = writer->Write(&c_array);
+    if (c_array.release != nullptr) {
+      c_array.release(&c_array);
+    }
+    ICEBERG_RETURN_UNEXPECTED(status);
+  }
+  ICEBERG_RETURN_UNEXPECTED(writer->Close());
+  ICEBERG_ASSIGN_OR_RAISE(auto metadata, writer->Metadata());
+  return metadata.data_files.at(0);
+}
+
+Result<std::shared_ptr<Table>> CreateTable(const Config& config,
+                                           const std::shared_ptr<FileIO>& io,
+                                           const Workload& workload) {
+  const auto table_dir = config.dir / workload.name;
+  std::filesystem::remove_all(table_dir);
+  std::filesystem::create_directories(table_dir / "data");
+  std::filesystem::create_directories(table_dir / "metadata");
+
+  ICEBERG_ASSIGN_OR_RAISE(auto catalog,
+                          InMemoryCatalog::Make("bench", io, 
config.dir.string(), {}));
+  const Namespace ns{.levels = {"bench"}};
+  ICEBERG_RETURN_UNEXPECTED(catalog->CreateNamespace(ns, {}));
+  const TableIdentifier identifier{.ns = ns, .name = workload.name};
+  auto schema = TableSchema();
+  ICEBERG_ASSIGN_OR_RAISE(
+      auto table, catalog->CreateTable(identifier, schema, 
PartitionSpec::Unpartitioned(),
+                                       SortOrder::Unsorted(), 
table_dir.string(),
+                                       {{"format-version", "2"},
+                                        {"read.split.target-size",
+                                         
std::to_string(workload.target_split_size)}}));
+
+  ICEBERG_ASSIGN_OR_RAISE(auto append, table->NewFastAppend());
+  for (int file = 0; file < workload.files; ++file) {
+    const auto path = (table_dir / "data" / std::format("{:05}.parquet", 
file)).string();
+    ICEBERG_ASSIGN_OR_RAISE(
+        auto data_file,
+        WriteFile(io, schema, path, file * workload.rows_per_file, workload));
+    append->AppendFile(data_file);
+  }
+  ICEBERG_RETURN_UNEXPECTED(append->Commit());
+  return catalog->LoadTable(identifier);
+}
+
+// Every row passes, so the residual is evaluated without changing the result 
size.
+std::shared_ptr<Expression> ScanFilter() {
+  return Expressions::GreaterThanOrEqual("id", Literal::Long(0));
+}
+
+FileScanTaskReader::Options ReaderOptions(const std::shared_ptr<FileIO>& io,
+                                          const std::shared_ptr<Schema>& 
schema) {
+  return {.io = io,
+          .table_schema = schema,
+          .projected_schema = schema,
+          .case_sensitive = true,
+          .properties = {{"read.batch-size", "8192"}},
+          .apply_residuals = true};
+}
+
+Result<std::unique_ptr<DataTableScan>> BuildScan(const Table& table, bool 
filter) {
+  ICEBERG_ASSIGN_OR_RAISE(auto builder, table.NewScan());
+  if (filter) {
+    builder->Filter(ScanFilter());
+  }
+  return builder->Build();
+}
+
+Result<int64_t> Drain(ArrowArrayStream* stream, int64_t* batches) {
+  int64_t rows = 0;
+  while (true) {
+    ArrowArray array{};
+    if (int code = stream->get_next(stream, &array); code != 0) {
+      const char* message = stream->get_last_error(stream);
+      return IOError("get_next failed ({}): {}", code, message ? message : "");
+    }
+    if (array.release == nullptr) {
+      return rows;
+    }
+    rows += array.length;
+    ++*batches;
+    array.release(&array);
+  }
+}
+
+double Seconds(Clock::duration duration) {
+  return std::chrono::duration<double>(duration).count();
+}
+
+Result<Run> RunSerial(const Table& table, const std::shared_ptr<FileIO>& io,
+                      const std::shared_ptr<Schema>& schema, bool filter) {
+  Run run;
+  const auto before = ReadCounters();
+  const auto start = Clock::now();
+  ICEBERG_ASSIGN_OR_RAISE(auto scan, BuildScan(table, filter));
+  ICEBERG_ASSIGN_OR_RAISE(auto tasks, scan->PlanFilesStream());
+  ICEBERG_ASSIGN_OR_RAISE(auto reader,
+                          FileScanTaskReader::Make(ReaderOptions(io, schema)));
+  std::optional<Clock::time_point> read_start;
+  while (true) {
+    ICEBERG_ASSIGN_OR_RAISE(auto task, tasks->Next());
+    if (!task.has_value()) {
+      break;
+    }
+    if (!read_start.has_value()) {
+      read_start = Clock::now();
+    }
+    ICEBERG_ASSIGN_OR_RAISE(auto stream, reader->Open(**task));
+    auto rows = Drain(&stream, &run.batches);
+    stream.release(&stream);
+    ICEBERG_ASSIGN_OR_RAISE(auto count, std::move(rows));
+    run.rows += count;
+  }
+  tasks.reset();
+  const auto end = Clock::now();
+  run.counters = ReadCounters() - before;
+  run.total_seconds = Seconds(end - start);
+  run.read_seconds = Seconds(end - read_start.value_or(end));
+  return run;
+}
+
+// Reuse Arrow's process-wide bounded CPU pool across benchmark scans.
+class ScanExecutor : public Executor {
+ public:
+  Status Submit(ExecutorTask task) override {
+    auto status = ::arrow::internal::GetCpuThreadPool()->Spawn(
+        [task = std::move(task)]() mutable { std::move(task)(); });
+    if (!status.ok()) {
+      return UnknownError("Arrow executor rejected a scan task: {}", 
status.ToString());
+    }
+    return {};
+  }
+};
+
+Result<Run> RunParallel(const Table& table, const std::shared_ptr<FileIO>& io,
+                        const std::shared_ptr<Schema>& schema, int workers, 
bool filter) {
+  Run run;
+  static ScanExecutor executor;
+  auto metrics = std::make_shared<internal::ParallelScanMetrics>();
+  const auto before = ReadCounters();
+  const auto start = Clock::now();
+  ICEBERG_ASSIGN_OR_RAISE(auto scan, BuildScan(table, filter));
+  ICEBERG_ASSIGN_OR_RAISE(auto groups, scan->PlanTasksStream());
+  ICEBERG_ASSIGN_OR_RAISE(auto stream, internal::OpenParallelScan(
+                                           std::move(groups),
+                                           {.reader_options = 
ReaderOptions(io, schema),
+                                            .executor = &executor,
+                                            .worker_count = workers,
+                                            .max_queued_batches = 2 * workers,
+                                            .max_queued_bytes = int64_t{64} << 
20},
+                                           metrics));
+  // Workers claim the first group as soon as the stream opens.
+  const auto read_start = Clock::now();
+  auto rows = Drain(&stream, &run.batches);
+  stream.release(&stream);
+  const auto end = Clock::now();
+  run.counters = ReadCounters() - before;
+  ICEBERG_ASSIGN_OR_RAISE(run.rows, std::move(rows));
+  run.total_seconds = Seconds(end - start);
+  run.read_seconds = Seconds(end - read_start);
+  run.metrics = metrics->Snapshot();
+  return run;
+}
+
+Result<double> PlanningSeconds(const Table& table, bool filter) {
+  const auto start = Clock::now();
+  ICEBERG_ASSIGN_OR_RAISE(auto scan, BuildScan(table, filter));
+  ICEBERG_ASSIGN_OR_RAISE(auto groups, scan->PlanTasks());
+  return Seconds(Clock::now() - start);
+}
+
+struct Interval {
+  double median = 0;
+  double low = 0;
+  double high = 0;
+};
+
+double Median(std::vector<double> values) {
+  std::ranges::sort(values);
+  const size_t mid = values.size() / 2;
+  return values.size() % 2 == 1 ? values[mid] : (values[mid - 1] + 
values[mid]) / 2;
+}
+
+// Percentile bootstrap of the median of paired ratios.
+Interval BootstrapMedian(const std::vector<double>& ratios) {
+  constexpr int kResamples = 10000;
+  std::mt19937_64 random(20261123);
+  std::uniform_int_distribution<size_t> pick(0, ratios.size() - 1);
+  std::vector<double> medians;
+  medians.reserve(kResamples);
+  std::vector<double> sample(ratios.size());
+  for (int resample = 0; resample < kResamples; ++resample) {
+    for (auto& value : sample) {
+      value = ratios[pick(random)];
+    }
+    medians.push_back(Median(sample));
+  }
+  std::ranges::sort(medians);
+  return Interval{.median = Median(ratios),
+                  .low = medians[static_cast<size_t>(0.025 * kResamples)],
+                  .high = medians[static_cast<size_t>(0.975 * kResamples) - 
1]};
+}
+
+double CoefficientOfVariation(const std::vector<double>& values) {
+  const double mean = std::accumulate(values.begin(), values.end(), 0.0) / 
values.size();
+  double sum = 0;
+  for (double value : values) {
+    sum += (value - mean) * (value - mean);
+  }
+  return std::sqrt(sum / (values.size() - 1)) / mean;
+}
+
+int64_t PeakRssKiB() {
+  rusage usage{};
+  getrusage(RUSAGE_SELF, &usage);
+  return usage.ru_maxrss;

Review Comment:
   Done



##########
src/iceberg/test/parallel_table_scan_test.cc:
##########
@@ -0,0 +1,670 @@
+/*
+ * 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.
+ */
+
+// End-to-end tests that plan real tables with PlanTasksStream() and read them 
with
+// ParallelScanReader, compared with PlanFilesStream() and the serial task 
reader.
+
+#include <algorithm>
+#include <cstdint>
+#include <format>
+#include <map>
+#include <memory>
+#include <optional>
+#include <string>
+#include <tuple>
+#include <unordered_set>
+#include <utility>
+#include <vector>
+
+#include <arrow/array.h>
+#include <arrow/c/bridge.h>
+#include <arrow/json/from_string.h>
+#include <arrow/record_batch.h>
+#include <gmock/gmock.h>
+#include <gtest/gtest.h>
+#include <parquet/arrow/reader.h>
+#include <parquet/file_reader.h>
+#include <parquet/metadata.h>
+
+#include "iceberg/arrow/arrow_io_internal.h"
+#include "iceberg/data/data_writer.h"
+#include "iceberg/data/file_scan_task_reader.h"
+#include "iceberg/data/parallel_scan_reader.h"
+#include "iceberg/data/position_delete_writer.h"
+#include "iceberg/data_table_scan.h"
+#include "iceberg/expression/expressions.h"
+#include "iceberg/metadata_columns.h"
+#include "iceberg/parquet/parquet_register.h"
+#include "iceberg/schema_internal.h"
+#include "iceberg/test/executor.h"
+#include "iceberg/test/scan_test_base.h"
+#include "iceberg/util/macros.h"
+
+namespace iceberg {
+
+namespace {
+
+// A row read from a scan. Lineage fields are -1 when not projected.
+struct Row {
+  int32_t id = 0;
+  std::string data;
+  int64_t row_id = -1;
+  int64_t pos = -1;
+
+  auto operator<=>(const Row&) const = default;
+};
+
+std::string DataValue(int32_t id) { return std::format("value-{}", id % 10); }
+
+// Converts an Arrow C stream into sorted rows, or returns the stream's error.
+Result<std::vector<Row>> CollectRows(ArrowArrayStream* stream) {
+  auto reader_result = ::arrow::ImportRecordBatchReader(stream);
+  if (!reader_result.ok()) {
+    return IOError("Failed to import stream: {}", 
reader_result.status().ToString());
+  }
+  std::vector<Row> rows;
+  for (auto next : **reader_result) {
+    if (!next.ok()) {
+      return IOError("{}", next.status().message());
+    }
+    const auto& batch = **next;
+    // Optional columns may be absent from the projection, but a present 
column must
+    // have the expected type.
+    auto column = [&batch]<typename ArrayType>(
+                      const char* name,
+                      bool required) -> Result<std::shared_ptr<ArrayType>> {
+      auto array = batch.GetColumnByName(name);
+      if (array == nullptr) {
+        if (required) {
+          return Invalid("Result has no column {}", name);
+        }
+        return nullptr;
+      }
+      auto typed = std::dynamic_pointer_cast<ArrayType>(array);
+      if (typed == nullptr) {
+        return Invalid("Column {} has unexpected type {}", name,
+                       array->type()->ToString());
+      }
+      return typed;
+    };
+    ICEBERG_ASSIGN_OR_RAISE(auto ids,
+                            column.template 
operator()<::arrow::Int32Array>("id", true));
+    ICEBERG_ASSIGN_OR_RAISE(
+        auto data, column.template operator()<::arrow::StringArray>("data", 
false));
+    ICEBERG_ASSIGN_OR_RAISE(
+        auto row_ids, column.template 
operator()<::arrow::Int64Array>("_row_id", false));
+    ICEBERG_ASSIGN_OR_RAISE(
+        auto positions, column.template 
operator()<::arrow::Int64Array>("_pos", false));
+    for (int64_t index = 0; index < batch.num_rows(); ++index) {
+      Row row;
+      row.id = ids->Value(index);
+      if (data != nullptr) {
+        row.data = data->GetString(index);
+      }
+      if (row_ids != nullptr) {
+        row.row_id = row_ids->Value(index);
+      }
+      if (positions != nullptr) {
+        row.pos = positions->Value(index);
+      }
+      rows.push_back(std::move(row));
+    }
+  }
+  std::ranges::sort(rows);
+  return rows;
+}
+
+}  // namespace
+
+class ParallelTableScanTest : public ScanTestBase {
+ protected:
+  test::ThreadPoolExecutor executor_{4};
+
+  static constexpr int64_t kSnapshotId = 1000L;
+  static constexpr int64_t kSequenceNumber = 1L;
+
+  void SetUp() override {
+    ScanTestBase::SetUp();
+    parquet::RegisterAll();
+  }
+
+  // A written data file and the ids it holds, in file order.
+  struct WrittenFile {
+    std::shared_ptr<DataFile> data_file;
+    int32_t first_id = 0;
+    int32_t rows = 0;
+  };
+
+  Result<WrittenFile> WriteDataFile(const std::string& path, int32_t first_id,
+                                    int32_t rows, int64_t max_row_group_rows = 
1 << 20,
+                                    FileFormatType format = 
FileFormatType::kParquet) {
+    std::string json = "[";
+    for (int32_t row = 0; row < rows; ++row) {
+      const int32_t id = first_id + row;
+      json += std::format("{}[{},\"{}\"]", row == 0 ? "" : ",", id, 
DataValue(id));
+    }
+    json += "]";
+
+    ArrowSchema c_schema;
+    ICEBERG_RETURN_UNEXPECTED(ToArrowSchema(*schema_, &c_schema));
+    auto arrow_type = ::arrow::ImportType(&c_schema);
+    if (!arrow_type.ok()) {
+      return Invalid("{}", arrow_type.status().ToString());
+    }
+    auto array = ::arrow::json::ArrayFromJSONString(
+        ::arrow::struct_((*arrow_type)->fields()), json);
+    if (!array.ok()) {
+      return Invalid("{}", array.status().ToString());
+    }
+    ArrowArray c_array{};
+    if (!::arrow::ExportArray(**array, &c_array).ok()) {
+      return Invalid("Failed to export a batch for {}", path);
+    }
+
+    std::unordered_map<std::string, std::string> properties;
+    if (format == FileFormatType::kParquet) {
+      properties["write.parquet.max-row-group-rows"] = 
std::to_string(max_row_group_rows);
+    }
+    ICEBERG_ASSIGN_OR_RAISE(auto writer, DataWriter::Make({.path = path,
+                                                           .schema = schema_,
+                                                           .spec = 
unpartitioned_spec_,
+                                                           .partition = 
PartitionValues{},
+                                                           .format = format,
+                                                           .io = file_io_,
+                                                           .properties = 
properties}));
+    auto write_status = writer->Write(&c_array);
+    if (c_array.release != nullptr) {
+      c_array.release(&c_array);
+    }
+    ICEBERG_RETURN_UNEXPECTED(write_status);
+    ICEBERG_RETURN_UNEXPECTED(writer->Close());
+    ICEBERG_ASSIGN_OR_RAISE(auto result, writer->Metadata());
+    if (result.data_files.size() != 1) {
+      return Invalid("Expected one data file for {}", path);
+    }
+    return WrittenFile{
+        .data_file = result.data_files[0], .first_id = first_id, .rows = rows};
+  }
+
+  Result<std::shared_ptr<DataFile>> WritePositionDeletes(
+      const std::string& path, const std::string& data_path,
+      const std::vector<int64_t>& positions) {
+    ICEBERG_ASSIGN_OR_RAISE(auto writer, PositionDeleteWriter::Make({
+                                             .path = path,
+                                             .schema = schema_,
+                                             .spec = unpartitioned_spec_,
+                                             .partition = PartitionValues{},
+                                             .format = 
FileFormatType::kParquet,
+                                             .io = file_io_,
+                                         }));
+    for (int64_t position : positions) {
+      ICEBERG_RETURN_UNEXPECTED(writer->WriteDelete(data_path, position));
+    }
+    ICEBERG_RETURN_UNEXPECTED(writer->Close());
+    ICEBERG_ASSIGN_OR_RAISE(auto result, writer->Metadata());
+    return result.data_files[0];
+  }
+
+  // Reads the canonical row-group starts that the Parquet reader assigns to 
ranges.
+  Result<std::vector<int64_t>> RowGroupStarts(const DataFile& data_file) {
+    ICEBERG_ASSIGN_OR_RAISE(auto input,
+                            arrow::OpenArrowInputStream(file_io_, 
data_file.file_path));
+    auto metadata = ::parquet::ReadMetaData(input);
+    std::vector<int64_t> starts;
+    for (int group = 0; group < metadata->num_row_groups(); ++group) {
+      auto column = metadata->RowGroup(group)->ColumnChunk(0);
+      int64_t start = column->data_page_offset();
+      if (column->has_dictionary_page() && column->dictionary_page_offset() > 
0 &&
+          column->dictionary_page_offset() < start) {
+        start = column->dictionary_page_offset();
+      }
+      starts.push_back(start);
+    }
+    return starts;
+  }
+
+  std::shared_ptr<TableMetadata> MakeMetadata(
+      const std::vector<WrittenFile>& files,
+      std::vector<std::shared_ptr<DataFile>> delete_files = {}) {
+    std::vector<ManifestEntry> data_entries;
+    for (const auto& file : files) {
+      data_entries.push_back(MakeEntry(ManifestStatus::kAdded, kSnapshotId,
+                                       kSequenceNumber, file.data_file));
+    }
+    std::vector<ManifestFile> manifests;
+    manifests.push_back(WriteDataManifest(GetParam(), kSnapshotId,
+                                          std::move(data_entries), 
unpartitioned_spec_));
+    if (!delete_files.empty()) {
+      std::vector<ManifestEntry> delete_entries;
+      for (auto& file : delete_files) {
+        delete_entries.push_back(MakeEntry(ManifestStatus::kAdded, kSnapshotId,
+                                           kSequenceNumber, std::move(file)));
+      }
+      manifests.push_back(WriteDeleteManifest(
+          GetParam(), kSnapshotId, std::move(delete_entries), 
unpartitioned_spec_));
+    }
+    auto manifest_list = ScanTestBase::WriteManifestList(
+        GetParam(), kSnapshotId, /*parent_snapshot_id=*/0L, kSequenceNumber, 
manifests);
+    auto snapshot = std::make_shared<Snapshot>(
+        Snapshot{.snapshot_id = kSnapshotId,
+                 .parent_snapshot_id = std::nullopt,
+                 .sequence_number = kSequenceNumber,
+                 .timestamp_ms = TimePointMsFromUnixMs(1609459200000L),
+                 .manifest_list = manifest_list,
+                 .schema_id = schema_->schema_id()});
+    auto metadata =
+        ScanTestBase::MakeTableMetadata({snapshot}, kSnapshotId, {}, 
unpartitioned_spec_);
+    if (GetParam() >= 3) {
+      int64_t total_rows = 0;
+      for (const auto& file : files) {
+        total_rows += file.rows;
+      }
+      metadata->next_row_id = total_rows;
+    }
+    return metadata;
+  }
+
+  struct ScanSettings {
+    int64_t target_split_size = 0;
+    std::shared_ptr<Expression> filter;
+    bool case_sensitive = true;
+    std::shared_ptr<Schema> projection;
+  };
+
+  Result<std::unique_ptr<DataTableScan>> BuildScan(
+      const std::shared_ptr<TableMetadata>& metadata, const ScanSettings& 
settings) {
+    ICEBERG_ASSIGN_OR_RAISE(auto builder, 
MakeScanBuilder<DataTableScan>(metadata));
+    if (settings.target_split_size > 0) {
+      builder->Option("read.split.target-size",
+                      std::to_string(settings.target_split_size));
+    }
+    builder->CaseSensitive(settings.case_sensitive);
+    if (settings.filter != nullptr) {
+      builder->Filter(settings.filter);
+    }
+    return builder->Build();
+  }
+
+  FileScanTaskReader::Options ReaderOptions(const ScanSettings& settings) 
const {
+    return {.io = file_io_,
+            .table_schema = schema_,
+            .projected_schema = settings.projection ? settings.projection : 
schema_,
+            .case_sensitive = settings.case_sensitive,
+            .apply_residuals = true};
+  }
+
+  // PlanFilesStream() and the serial task reader, one task at a time.
+  Result<std::vector<Row>> ReadSerially(const std::shared_ptr<TableMetadata>& 
metadata,
+                                        const ScanSettings& settings) {
+    ICEBERG_ASSIGN_OR_RAISE(auto scan, BuildScan(metadata, settings));
+    ICEBERG_ASSIGN_OR_RAISE(auto tasks, scan->PlanFilesStream());
+    ICEBERG_ASSIGN_OR_RAISE(auto reader,
+                            FileScanTaskReader::Make(ReaderOptions(settings)));
+    std::vector<Row> rows;
+    while (true) {
+      ICEBERG_ASSIGN_OR_RAISE(auto task, tasks->Next());
+      if (!task.has_value()) {
+        break;
+      }
+      ICEBERG_ASSIGN_OR_RAISE(auto stream, reader->Open(**task));
+      ICEBERG_ASSIGN_OR_RAISE(auto task_rows, CollectRows(&stream));
+      rows.insert(rows.end(), task_rows.begin(), task_rows.end());
+    }
+    std::ranges::sort(rows);
+    return rows;
+  }
+
+  // PlanTasksStream() and the parallel reader.
+  Result<std::vector<Row>> ReadInParallel(const 
std::shared_ptr<TableMetadata>& metadata,
+                                          const ScanSettings& settings, 
int32_t workers,
+                                          int64_t max_queued_batches = 4,
+                                          int64_t max_queued_bytes = 1 << 20) {
+    ICEBERG_ASSIGN_OR_RAISE(auto scan, BuildScan(metadata, settings));
+    ICEBERG_ASSIGN_OR_RAISE(auto groups, scan->PlanTasksStream());
+    ICEBERG_ASSIGN_OR_RAISE(
+        auto stream, ParallelScanReader::Open(std::move(groups),
+                                              {.reader_options = 
ReaderOptions(settings),
+                                               .executor = &executor_,
+                                               .worker_count = workers,
+                                               .max_queued_batches = 
max_queued_batches,
+                                               .max_queued_bytes = 
max_queued_bytes}));
+    return CollectRows(&stream);
+  }
+
+  Result<std::vector<std::shared_ptr<FileScanTaskGroup>>> PlanGroups(
+      const std::shared_ptr<TableMetadata>& metadata, const ScanSettings& 
settings) {
+    ICEBERG_ASSIGN_OR_RAISE(auto scan, BuildScan(metadata, settings));
+    return scan->PlanTasks();
+  }
+
+  static size_t CountSplitTasks(
+      const std::vector<std::shared_ptr<FileScanTaskGroup>>& groups) {
+    size_t count = 0;
+    for (const auto& group : groups) {
+      for (const auto& task : group->tasks()) {
+        count += task->is_split() ? 1 : 0;
+      }
+    }
+    return count;
+  }
+
+  static std::vector<Row> ExpectedRows(const std::vector<WrittenFile>& files,
+                                       const std::unordered_set<int32_t>& 
deleted = {}) {
+    std::vector<Row> rows;
+    for (const auto& file : files) {
+      for (int32_t row = 0; row < file.rows; ++row) {
+        const int32_t id = file.first_id + row;
+        if (!deleted.contains(id)) {
+          rows.push_back(Row{.id = id, .data = DataValue(id)});
+        }
+      }
+    }
+    std::ranges::sort(rows);
+    return rows;
+  }
+
+  // Checks parallel results against independent expectations and the serial 
path,
+  // for one and several workers.
+  void ExpectParallelMatches(const std::shared_ptr<TableMetadata>& metadata,
+                             const ScanSettings& settings,
+                             const std::vector<Row>& expected) {
+    ICEBERG_UNWRAP_OR_FAIL(auto serial, ReadSerially(metadata, settings));
+    EXPECT_EQ(serial, expected);
+    for (int32_t workers : {1, 4}) {
+      SCOPED_TRACE(std::format("workers={}", workers));
+      ICEBERG_UNWRAP_OR_FAIL(auto parallel, ReadInParallel(metadata, settings, 
workers));
+      EXPECT_EQ(parallel, expected);
+    }
+  }
+};
+
+TEST_P(ParallelTableScanTest, LargeMultiRowGroupFilesWithManifestOffsets) {
+  std::vector<WrittenFile> files;
+  for (int file = 0; file < 3; ++file) {
+    ICEBERG_UNWRAP_OR_FAIL(
+        auto written, WriteDataFile(std::format("large-{}.parquet", file), 
file * 2000,
+                                    2000, /*max_row_group_rows=*/200));
+    ASSERT_EQ(written.data_file->split_offsets.size(), 10U);
+    files.push_back(std::move(written));
+  }
+  auto metadata = MakeMetadata(files);
+  ScanSettings settings{.target_split_size = 
files[0].data_file->file_size_in_bytes / 4};
+  ICEBERG_UNWRAP_OR_FAIL(auto groups, PlanGroups(metadata, settings));
+  EXPECT_GE(CountSplitTasks(groups), 9U);
+  ExpectParallelMatches(metadata, settings, ExpectedRows(files));
+}
+
+TEST_P(ParallelTableScanTest, MissingManifestOffsetsUseFixedRanges) {
+  ICEBERG_UNWRAP_OR_FAIL(auto written, WriteDataFile("no-offsets.parquet", 0, 
3000,
+                                                     
/*max_row_group_rows=*/250));
+  written.data_file->split_offsets.clear();
+  std::vector<WrittenFile> files{written};
+  auto metadata = MakeMetadata(files);
+  ScanSettings settings{.target_split_size = 
written.data_file->file_size_in_bytes / 5};
+  ICEBERG_UNWRAP_OR_FAIL(auto groups, PlanGroups(metadata, settings));
+  EXPECT_GE(CountSplitTasks(groups), 5U);
+  ExpectParallelMatches(metadata, settings, ExpectedRows(files));
+}
+
+TEST_P(ParallelTableScanTest, ManifestOffsetsThatMissCanonicalStarts) {
+  ICEBERG_UNWRAP_OR_FAIL(auto written, WriteDataFile("shifted.parquet", 0, 
2400,
+                                                     
/*max_row_group_rows=*/200));
+  ICEBERG_UNWRAP_OR_FAIL(auto starts, RowGroupStarts(*written.data_file));
+  ASSERT_EQ(starts.size(), 12U);
+  // Valid (increasing, in-bounds) offsets that fall inside row groups, so that

Review Comment:
   Done



##########
src/iceberg/test/parallel_table_scan_test.cc:
##########
@@ -0,0 +1,670 @@
+/*
+ * 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.
+ */
+
+// End-to-end tests that plan real tables with PlanTasksStream() and read them 
with
+// ParallelScanReader, compared with PlanFilesStream() and the serial task 
reader.
+
+#include <algorithm>
+#include <cstdint>
+#include <format>
+#include <map>
+#include <memory>
+#include <optional>
+#include <string>
+#include <tuple>
+#include <unordered_set>
+#include <utility>
+#include <vector>
+
+#include <arrow/array.h>
+#include <arrow/c/bridge.h>
+#include <arrow/json/from_string.h>
+#include <arrow/record_batch.h>
+#include <gmock/gmock.h>
+#include <gtest/gtest.h>
+#include <parquet/arrow/reader.h>
+#include <parquet/file_reader.h>
+#include <parquet/metadata.h>
+
+#include "iceberg/arrow/arrow_io_internal.h"
+#include "iceberg/data/data_writer.h"
+#include "iceberg/data/file_scan_task_reader.h"
+#include "iceberg/data/parallel_scan_reader.h"
+#include "iceberg/data/position_delete_writer.h"
+#include "iceberg/data_table_scan.h"
+#include "iceberg/expression/expressions.h"
+#include "iceberg/metadata_columns.h"
+#include "iceberg/parquet/parquet_register.h"
+#include "iceberg/schema_internal.h"
+#include "iceberg/test/executor.h"
+#include "iceberg/test/scan_test_base.h"
+#include "iceberg/util/macros.h"
+
+namespace iceberg {
+
+namespace {
+
+// A row read from a scan. Lineage fields are -1 when not projected.
+struct Row {
+  int32_t id = 0;
+  std::string data;
+  int64_t row_id = -1;
+  int64_t pos = -1;
+
+  auto operator<=>(const Row&) const = default;
+};
+
+std::string DataValue(int32_t id) { return std::format("value-{}", id % 10); }
+
+// Converts an Arrow C stream into sorted rows, or returns the stream's error.
+Result<std::vector<Row>> CollectRows(ArrowArrayStream* stream) {
+  auto reader_result = ::arrow::ImportRecordBatchReader(stream);
+  if (!reader_result.ok()) {
+    return IOError("Failed to import stream: {}", 
reader_result.status().ToString());
+  }
+  std::vector<Row> rows;
+  for (auto next : **reader_result) {
+    if (!next.ok()) {
+      return IOError("{}", next.status().message());
+    }
+    const auto& batch = **next;
+    // Optional columns may be absent from the projection, but a present 
column must
+    // have the expected type.
+    auto column = [&batch]<typename ArrayType>(
+                      const char* name,
+                      bool required) -> Result<std::shared_ptr<ArrayType>> {
+      auto array = batch.GetColumnByName(name);
+      if (array == nullptr) {
+        if (required) {
+          return Invalid("Result has no column {}", name);
+        }
+        return nullptr;
+      }
+      auto typed = std::dynamic_pointer_cast<ArrayType>(array);
+      if (typed == nullptr) {
+        return Invalid("Column {} has unexpected type {}", name,
+                       array->type()->ToString());
+      }
+      return typed;
+    };
+    ICEBERG_ASSIGN_OR_RAISE(auto ids,
+                            column.template 
operator()<::arrow::Int32Array>("id", true));
+    ICEBERG_ASSIGN_OR_RAISE(
+        auto data, column.template operator()<::arrow::StringArray>("data", 
false));
+    ICEBERG_ASSIGN_OR_RAISE(
+        auto row_ids, column.template 
operator()<::arrow::Int64Array>("_row_id", false));
+    ICEBERG_ASSIGN_OR_RAISE(
+        auto positions, column.template 
operator()<::arrow::Int64Array>("_pos", false));
+    for (int64_t index = 0; index < batch.num_rows(); ++index) {
+      Row row;
+      row.id = ids->Value(index);
+      if (data != nullptr) {
+        row.data = data->GetString(index);
+      }
+      if (row_ids != nullptr) {
+        row.row_id = row_ids->Value(index);
+      }
+      if (positions != nullptr) {
+        row.pos = positions->Value(index);
+      }
+      rows.push_back(std::move(row));
+    }
+  }
+  std::ranges::sort(rows);
+  return rows;
+}
+
+}  // namespace
+
+class ParallelTableScanTest : public ScanTestBase {
+ protected:
+  test::ThreadPoolExecutor executor_{4};
+
+  static constexpr int64_t kSnapshotId = 1000L;
+  static constexpr int64_t kSequenceNumber = 1L;
+
+  void SetUp() override {
+    ScanTestBase::SetUp();
+    parquet::RegisterAll();
+  }
+
+  // A written data file and the ids it holds, in file order.
+  struct WrittenFile {
+    std::shared_ptr<DataFile> data_file;
+    int32_t first_id = 0;
+    int32_t rows = 0;
+  };
+
+  Result<WrittenFile> WriteDataFile(const std::string& path, int32_t first_id,
+                                    int32_t rows, int64_t max_row_group_rows = 
1 << 20,
+                                    FileFormatType format = 
FileFormatType::kParquet) {
+    std::string json = "[";
+    for (int32_t row = 0; row < rows; ++row) {
+      const int32_t id = first_id + row;
+      json += std::format("{}[{},\"{}\"]", row == 0 ? "" : ",", id, 
DataValue(id));
+    }
+    json += "]";
+
+    ArrowSchema c_schema;
+    ICEBERG_RETURN_UNEXPECTED(ToArrowSchema(*schema_, &c_schema));
+    auto arrow_type = ::arrow::ImportType(&c_schema);
+    if (!arrow_type.ok()) {
+      return Invalid("{}", arrow_type.status().ToString());
+    }
+    auto array = ::arrow::json::ArrayFromJSONString(
+        ::arrow::struct_((*arrow_type)->fields()), json);
+    if (!array.ok()) {
+      return Invalid("{}", array.status().ToString());
+    }
+    ArrowArray c_array{};
+    if (!::arrow::ExportArray(**array, &c_array).ok()) {
+      return Invalid("Failed to export a batch for {}", path);
+    }
+
+    std::unordered_map<std::string, std::string> properties;
+    if (format == FileFormatType::kParquet) {
+      properties["write.parquet.max-row-group-rows"] = 
std::to_string(max_row_group_rows);
+    }
+    ICEBERG_ASSIGN_OR_RAISE(auto writer, DataWriter::Make({.path = path,
+                                                           .schema = schema_,
+                                                           .spec = 
unpartitioned_spec_,
+                                                           .partition = 
PartitionValues{},
+                                                           .format = format,
+                                                           .io = file_io_,
+                                                           .properties = 
properties}));
+    auto write_status = writer->Write(&c_array);
+    if (c_array.release != nullptr) {
+      c_array.release(&c_array);
+    }
+    ICEBERG_RETURN_UNEXPECTED(write_status);
+    ICEBERG_RETURN_UNEXPECTED(writer->Close());
+    ICEBERG_ASSIGN_OR_RAISE(auto result, writer->Metadata());
+    if (result.data_files.size() != 1) {
+      return Invalid("Expected one data file for {}", path);
+    }
+    return WrittenFile{
+        .data_file = result.data_files[0], .first_id = first_id, .rows = rows};
+  }
+
+  Result<std::shared_ptr<DataFile>> WritePositionDeletes(
+      const std::string& path, const std::string& data_path,
+      const std::vector<int64_t>& positions) {
+    ICEBERG_ASSIGN_OR_RAISE(auto writer, PositionDeleteWriter::Make({
+                                             .path = path,
+                                             .schema = schema_,
+                                             .spec = unpartitioned_spec_,
+                                             .partition = PartitionValues{},
+                                             .format = 
FileFormatType::kParquet,
+                                             .io = file_io_,
+                                         }));
+    for (int64_t position : positions) {
+      ICEBERG_RETURN_UNEXPECTED(writer->WriteDelete(data_path, position));
+    }
+    ICEBERG_RETURN_UNEXPECTED(writer->Close());
+    ICEBERG_ASSIGN_OR_RAISE(auto result, writer->Metadata());
+    return result.data_files[0];
+  }
+
+  // Reads the canonical row-group starts that the Parquet reader assigns to 
ranges.
+  Result<std::vector<int64_t>> RowGroupStarts(const DataFile& data_file) {
+    ICEBERG_ASSIGN_OR_RAISE(auto input,
+                            arrow::OpenArrowInputStream(file_io_, 
data_file.file_path));
+    auto metadata = ::parquet::ReadMetaData(input);
+    std::vector<int64_t> starts;
+    for (int group = 0; group < metadata->num_row_groups(); ++group) {
+      auto column = metadata->RowGroup(group)->ColumnChunk(0);
+      int64_t start = column->data_page_offset();
+      if (column->has_dictionary_page() && column->dictionary_page_offset() > 
0 &&
+          column->dictionary_page_offset() < start) {
+        start = column->dictionary_page_offset();
+      }
+      starts.push_back(start);
+    }
+    return starts;
+  }
+
+  std::shared_ptr<TableMetadata> MakeMetadata(
+      const std::vector<WrittenFile>& files,
+      std::vector<std::shared_ptr<DataFile>> delete_files = {}) {
+    std::vector<ManifestEntry> data_entries;
+    for (const auto& file : files) {
+      data_entries.push_back(MakeEntry(ManifestStatus::kAdded, kSnapshotId,
+                                       kSequenceNumber, file.data_file));
+    }
+    std::vector<ManifestFile> manifests;
+    manifests.push_back(WriteDataManifest(GetParam(), kSnapshotId,
+                                          std::move(data_entries), 
unpartitioned_spec_));
+    if (!delete_files.empty()) {
+      std::vector<ManifestEntry> delete_entries;
+      for (auto& file : delete_files) {
+        delete_entries.push_back(MakeEntry(ManifestStatus::kAdded, kSnapshotId,
+                                           kSequenceNumber, std::move(file)));
+      }
+      manifests.push_back(WriteDeleteManifest(
+          GetParam(), kSnapshotId, std::move(delete_entries), 
unpartitioned_spec_));
+    }
+    auto manifest_list = ScanTestBase::WriteManifestList(
+        GetParam(), kSnapshotId, /*parent_snapshot_id=*/0L, kSequenceNumber, 
manifests);
+    auto snapshot = std::make_shared<Snapshot>(
+        Snapshot{.snapshot_id = kSnapshotId,
+                 .parent_snapshot_id = std::nullopt,
+                 .sequence_number = kSequenceNumber,
+                 .timestamp_ms = TimePointMsFromUnixMs(1609459200000L),
+                 .manifest_list = manifest_list,
+                 .schema_id = schema_->schema_id()});
+    auto metadata =
+        ScanTestBase::MakeTableMetadata({snapshot}, kSnapshotId, {}, 
unpartitioned_spec_);
+    if (GetParam() >= 3) {
+      int64_t total_rows = 0;
+      for (const auto& file : files) {
+        total_rows += file.rows;
+      }
+      metadata->next_row_id = total_rows;
+    }
+    return metadata;
+  }
+
+  struct ScanSettings {
+    int64_t target_split_size = 0;
+    std::shared_ptr<Expression> filter;
+    bool case_sensitive = true;
+    std::shared_ptr<Schema> projection;
+  };
+
+  Result<std::unique_ptr<DataTableScan>> BuildScan(
+      const std::shared_ptr<TableMetadata>& metadata, const ScanSettings& 
settings) {
+    ICEBERG_ASSIGN_OR_RAISE(auto builder, 
MakeScanBuilder<DataTableScan>(metadata));

Review Comment:
   Done



##########
src/iceberg/test/parallel_table_scan_test.cc:
##########
@@ -0,0 +1,670 @@
+/*
+ * 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.
+ */
+
+// End-to-end tests that plan real tables with PlanTasksStream() and read them 
with
+// ParallelScanReader, compared with PlanFilesStream() and the serial task 
reader.
+
+#include <algorithm>
+#include <cstdint>
+#include <format>
+#include <map>
+#include <memory>
+#include <optional>
+#include <string>
+#include <tuple>
+#include <unordered_set>
+#include <utility>
+#include <vector>
+
+#include <arrow/array.h>
+#include <arrow/c/bridge.h>
+#include <arrow/json/from_string.h>
+#include <arrow/record_batch.h>
+#include <gmock/gmock.h>
+#include <gtest/gtest.h>
+#include <parquet/arrow/reader.h>
+#include <parquet/file_reader.h>
+#include <parquet/metadata.h>
+
+#include "iceberg/arrow/arrow_io_internal.h"
+#include "iceberg/data/data_writer.h"
+#include "iceberg/data/file_scan_task_reader.h"
+#include "iceberg/data/parallel_scan_reader.h"
+#include "iceberg/data/position_delete_writer.h"
+#include "iceberg/data_table_scan.h"
+#include "iceberg/expression/expressions.h"
+#include "iceberg/metadata_columns.h"
+#include "iceberg/parquet/parquet_register.h"
+#include "iceberg/schema_internal.h"
+#include "iceberg/test/executor.h"
+#include "iceberg/test/scan_test_base.h"
+#include "iceberg/util/macros.h"
+
+namespace iceberg {
+
+namespace {
+
+// A row read from a scan. Lineage fields are -1 when not projected.
+struct Row {
+  int32_t id = 0;
+  std::string data;
+  int64_t row_id = -1;
+  int64_t pos = -1;
+
+  auto operator<=>(const Row&) const = default;
+};
+
+std::string DataValue(int32_t id) { return std::format("value-{}", id % 10); }
+
+// Converts an Arrow C stream into sorted rows, or returns the stream's error.
+Result<std::vector<Row>> CollectRows(ArrowArrayStream* stream) {
+  auto reader_result = ::arrow::ImportRecordBatchReader(stream);
+  if (!reader_result.ok()) {
+    return IOError("Failed to import stream: {}", 
reader_result.status().ToString());
+  }
+  std::vector<Row> rows;
+  for (auto next : **reader_result) {
+    if (!next.ok()) {
+      return IOError("{}", next.status().message());
+    }
+    const auto& batch = **next;
+    // Optional columns may be absent from the projection, but a present 
column must
+    // have the expected type.
+    auto column = [&batch]<typename ArrayType>(
+                      const char* name,
+                      bool required) -> Result<std::shared_ptr<ArrayType>> {
+      auto array = batch.GetColumnByName(name);
+      if (array == nullptr) {
+        if (required) {
+          return Invalid("Result has no column {}", name);
+        }
+        return nullptr;
+      }
+      auto typed = std::dynamic_pointer_cast<ArrayType>(array);
+      if (typed == nullptr) {
+        return Invalid("Column {} has unexpected type {}", name,
+                       array->type()->ToString());
+      }
+      return typed;
+    };
+    ICEBERG_ASSIGN_OR_RAISE(auto ids,
+                            column.template 
operator()<::arrow::Int32Array>("id", true));
+    ICEBERG_ASSIGN_OR_RAISE(
+        auto data, column.template operator()<::arrow::StringArray>("data", 
false));
+    ICEBERG_ASSIGN_OR_RAISE(
+        auto row_ids, column.template 
operator()<::arrow::Int64Array>("_row_id", false));
+    ICEBERG_ASSIGN_OR_RAISE(
+        auto positions, column.template 
operator()<::arrow::Int64Array>("_pos", false));
+    for (int64_t index = 0; index < batch.num_rows(); ++index) {
+      Row row;
+      row.id = ids->Value(index);
+      if (data != nullptr) {
+        row.data = data->GetString(index);
+      }
+      if (row_ids != nullptr) {
+        row.row_id = row_ids->Value(index);
+      }
+      if (positions != nullptr) {
+        row.pos = positions->Value(index);
+      }
+      rows.push_back(std::move(row));
+    }
+  }
+  std::ranges::sort(rows);
+  return rows;
+}
+
+}  // namespace
+
+class ParallelTableScanTest : public ScanTestBase {
+ protected:
+  test::ThreadPoolExecutor executor_{4};
+
+  static constexpr int64_t kSnapshotId = 1000L;
+  static constexpr int64_t kSequenceNumber = 1L;
+
+  void SetUp() override {
+    ScanTestBase::SetUp();
+    parquet::RegisterAll();
+  }
+
+  // A written data file and the ids it holds, in file order.
+  struct WrittenFile {
+    std::shared_ptr<DataFile> data_file;
+    int32_t first_id = 0;
+    int32_t rows = 0;
+  };
+
+  Result<WrittenFile> WriteDataFile(const std::string& path, int32_t first_id,
+                                    int32_t rows, int64_t max_row_group_rows = 
1 << 20,
+                                    FileFormatType format = 
FileFormatType::kParquet) {
+    std::string json = "[";
+    for (int32_t row = 0; row < rows; ++row) {
+      const int32_t id = first_id + row;
+      json += std::format("{}[{},\"{}\"]", row == 0 ? "" : ",", id, 
DataValue(id));
+    }
+    json += "]";
+
+    ArrowSchema c_schema;
+    ICEBERG_RETURN_UNEXPECTED(ToArrowSchema(*schema_, &c_schema));
+    auto arrow_type = ::arrow::ImportType(&c_schema);
+    if (!arrow_type.ok()) {
+      return Invalid("{}", arrow_type.status().ToString());
+    }
+    auto array = ::arrow::json::ArrayFromJSONString(
+        ::arrow::struct_((*arrow_type)->fields()), json);
+    if (!array.ok()) {
+      return Invalid("{}", array.status().ToString());
+    }
+    ArrowArray c_array{};
+    if (!::arrow::ExportArray(**array, &c_array).ok()) {
+      return Invalid("Failed to export a batch for {}", path);
+    }
+
+    std::unordered_map<std::string, std::string> properties;
+    if (format == FileFormatType::kParquet) {
+      properties["write.parquet.max-row-group-rows"] = 
std::to_string(max_row_group_rows);
+    }
+    ICEBERG_ASSIGN_OR_RAISE(auto writer, DataWriter::Make({.path = path,
+                                                           .schema = schema_,
+                                                           .spec = 
unpartitioned_spec_,
+                                                           .partition = 
PartitionValues{},
+                                                           .format = format,
+                                                           .io = file_io_,
+                                                           .properties = 
properties}));
+    auto write_status = writer->Write(&c_array);
+    if (c_array.release != nullptr) {
+      c_array.release(&c_array);
+    }
+    ICEBERG_RETURN_UNEXPECTED(write_status);
+    ICEBERG_RETURN_UNEXPECTED(writer->Close());
+    ICEBERG_ASSIGN_OR_RAISE(auto result, writer->Metadata());
+    if (result.data_files.size() != 1) {
+      return Invalid("Expected one data file for {}", path);
+    }
+    return WrittenFile{
+        .data_file = result.data_files[0], .first_id = first_id, .rows = rows};
+  }
+
+  Result<std::shared_ptr<DataFile>> WritePositionDeletes(
+      const std::string& path, const std::string& data_path,
+      const std::vector<int64_t>& positions) {
+    ICEBERG_ASSIGN_OR_RAISE(auto writer, PositionDeleteWriter::Make({
+                                             .path = path,
+                                             .schema = schema_,
+                                             .spec = unpartitioned_spec_,
+                                             .partition = PartitionValues{},
+                                             .format = 
FileFormatType::kParquet,
+                                             .io = file_io_,
+                                         }));
+    for (int64_t position : positions) {
+      ICEBERG_RETURN_UNEXPECTED(writer->WriteDelete(data_path, position));
+    }
+    ICEBERG_RETURN_UNEXPECTED(writer->Close());
+    ICEBERG_ASSIGN_OR_RAISE(auto result, writer->Metadata());
+    return result.data_files[0];
+  }
+
+  // Reads the canonical row-group starts that the Parquet reader assigns to 
ranges.
+  Result<std::vector<int64_t>> RowGroupStarts(const DataFile& data_file) {
+    ICEBERG_ASSIGN_OR_RAISE(auto input,
+                            arrow::OpenArrowInputStream(file_io_, 
data_file.file_path));
+    auto metadata = ::parquet::ReadMetaData(input);
+    std::vector<int64_t> starts;
+    for (int group = 0; group < metadata->num_row_groups(); ++group) {
+      auto column = metadata->RowGroup(group)->ColumnChunk(0);
+      int64_t start = column->data_page_offset();
+      if (column->has_dictionary_page() && column->dictionary_page_offset() > 
0 &&
+          column->dictionary_page_offset() < start) {
+        start = column->dictionary_page_offset();
+      }
+      starts.push_back(start);
+    }
+    return starts;
+  }
+
+  std::shared_ptr<TableMetadata> MakeMetadata(
+      const std::vector<WrittenFile>& files,
+      std::vector<std::shared_ptr<DataFile>> delete_files = {}) {
+    std::vector<ManifestEntry> data_entries;
+    for (const auto& file : files) {
+      data_entries.push_back(MakeEntry(ManifestStatus::kAdded, kSnapshotId,
+                                       kSequenceNumber, file.data_file));
+    }
+    std::vector<ManifestFile> manifests;
+    manifests.push_back(WriteDataManifest(GetParam(), kSnapshotId,
+                                          std::move(data_entries), 
unpartitioned_spec_));
+    if (!delete_files.empty()) {
+      std::vector<ManifestEntry> delete_entries;
+      for (auto& file : delete_files) {
+        delete_entries.push_back(MakeEntry(ManifestStatus::kAdded, kSnapshotId,
+                                           kSequenceNumber, std::move(file)));
+      }
+      manifests.push_back(WriteDeleteManifest(
+          GetParam(), kSnapshotId, std::move(delete_entries), 
unpartitioned_spec_));
+    }
+    auto manifest_list = ScanTestBase::WriteManifestList(
+        GetParam(), kSnapshotId, /*parent_snapshot_id=*/0L, kSequenceNumber, 
manifests);
+    auto snapshot = std::make_shared<Snapshot>(
+        Snapshot{.snapshot_id = kSnapshotId,
+                 .parent_snapshot_id = std::nullopt,
+                 .sequence_number = kSequenceNumber,
+                 .timestamp_ms = TimePointMsFromUnixMs(1609459200000L),
+                 .manifest_list = manifest_list,
+                 .schema_id = schema_->schema_id()});
+    auto metadata =
+        ScanTestBase::MakeTableMetadata({snapshot}, kSnapshotId, {}, 
unpartitioned_spec_);
+    if (GetParam() >= 3) {
+      int64_t total_rows = 0;
+      for (const auto& file : files) {
+        total_rows += file.rows;
+      }
+      metadata->next_row_id = total_rows;
+    }
+    return metadata;
+  }
+
+  struct ScanSettings {
+    int64_t target_split_size = 0;
+    std::shared_ptr<Expression> filter;
+    bool case_sensitive = true;
+    std::shared_ptr<Schema> projection;
+  };
+
+  Result<std::unique_ptr<DataTableScan>> BuildScan(
+      const std::shared_ptr<TableMetadata>& metadata, const ScanSettings& 
settings) {
+    ICEBERG_ASSIGN_OR_RAISE(auto builder, 
MakeScanBuilder<DataTableScan>(metadata));
+    if (settings.target_split_size > 0) {
+      builder->Option("read.split.target-size",
+                      std::to_string(settings.target_split_size));
+    }
+    builder->CaseSensitive(settings.case_sensitive);
+    if (settings.filter != nullptr) {
+      builder->Filter(settings.filter);
+    }
+    return builder->Build();
+  }
+
+  FileScanTaskReader::Options ReaderOptions(const ScanSettings& settings) 
const {
+    return {.io = file_io_,
+            .table_schema = schema_,
+            .projected_schema = settings.projection ? settings.projection : 
schema_,
+            .case_sensitive = settings.case_sensitive,
+            .apply_residuals = true};
+  }
+
+  // PlanFilesStream() and the serial task reader, one task at a time.
+  Result<std::vector<Row>> ReadSerially(const std::shared_ptr<TableMetadata>& 
metadata,
+                                        const ScanSettings& settings) {
+    ICEBERG_ASSIGN_OR_RAISE(auto scan, BuildScan(metadata, settings));
+    ICEBERG_ASSIGN_OR_RAISE(auto tasks, scan->PlanFilesStream());
+    ICEBERG_ASSIGN_OR_RAISE(auto reader,
+                            FileScanTaskReader::Make(ReaderOptions(settings)));
+    std::vector<Row> rows;
+    while (true) {
+      ICEBERG_ASSIGN_OR_RAISE(auto task, tasks->Next());
+      if (!task.has_value()) {
+        break;
+      }
+      ICEBERG_ASSIGN_OR_RAISE(auto stream, reader->Open(**task));
+      ICEBERG_ASSIGN_OR_RAISE(auto task_rows, CollectRows(&stream));
+      rows.insert(rows.end(), task_rows.begin(), task_rows.end());
+    }
+    std::ranges::sort(rows);
+    return rows;
+  }
+
+  // PlanTasksStream() and the parallel reader.
+  Result<std::vector<Row>> ReadInParallel(const 
std::shared_ptr<TableMetadata>& metadata,
+                                          const ScanSettings& settings, 
int32_t workers,
+                                          int64_t max_queued_batches = 4,
+                                          int64_t max_queued_bytes = 1 << 20) {
+    ICEBERG_ASSIGN_OR_RAISE(auto scan, BuildScan(metadata, settings));
+    ICEBERG_ASSIGN_OR_RAISE(auto groups, scan->PlanTasksStream());
+    ICEBERG_ASSIGN_OR_RAISE(
+        auto stream, ParallelScanReader::Open(std::move(groups),
+                                              {.reader_options = 
ReaderOptions(settings),
+                                               .executor = &executor_,
+                                               .worker_count = workers,
+                                               .max_queued_batches = 
max_queued_batches,
+                                               .max_queued_bytes = 
max_queued_bytes}));
+    return CollectRows(&stream);
+  }
+
+  Result<std::vector<std::shared_ptr<FileScanTaskGroup>>> PlanGroups(
+      const std::shared_ptr<TableMetadata>& metadata, const ScanSettings& 
settings) {
+    ICEBERG_ASSIGN_OR_RAISE(auto scan, BuildScan(metadata, settings));
+    return scan->PlanTasks();
+  }
+
+  static size_t CountSplitTasks(
+      const std::vector<std::shared_ptr<FileScanTaskGroup>>& groups) {
+    size_t count = 0;
+    for (const auto& group : groups) {
+      for (const auto& task : group->tasks()) {
+        count += task->is_split() ? 1 : 0;
+      }
+    }
+    return count;
+  }
+
+  static std::vector<Row> ExpectedRows(const std::vector<WrittenFile>& files,
+                                       const std::unordered_set<int32_t>& 
deleted = {}) {
+    std::vector<Row> rows;
+    for (const auto& file : files) {
+      for (int32_t row = 0; row < file.rows; ++row) {
+        const int32_t id = file.first_id + row;
+        if (!deleted.contains(id)) {
+          rows.push_back(Row{.id = id, .data = DataValue(id)});
+        }
+      }
+    }
+    std::ranges::sort(rows);
+    return rows;
+  }
+
+  // Checks parallel results against independent expectations and the serial 
path,
+  // for one and several workers.
+  void ExpectParallelMatches(const std::shared_ptr<TableMetadata>& metadata,
+                             const ScanSettings& settings,
+                             const std::vector<Row>& expected) {
+    ICEBERG_UNWRAP_OR_FAIL(auto serial, ReadSerially(metadata, settings));
+    EXPECT_EQ(serial, expected);
+    for (int32_t workers : {1, 4}) {
+      SCOPED_TRACE(std::format("workers={}", workers));
+      ICEBERG_UNWRAP_OR_FAIL(auto parallel, ReadInParallel(metadata, settings, 
workers));
+      EXPECT_EQ(parallel, expected);
+    }
+  }
+};
+
+TEST_P(ParallelTableScanTest, LargeMultiRowGroupFilesWithManifestOffsets) {
+  std::vector<WrittenFile> files;
+  for (int file = 0; file < 3; ++file) {
+    ICEBERG_UNWRAP_OR_FAIL(
+        auto written, WriteDataFile(std::format("large-{}.parquet", file), 
file * 2000,
+                                    2000, /*max_row_group_rows=*/200));
+    ASSERT_EQ(written.data_file->split_offsets.size(), 10U);
+    files.push_back(std::move(written));
+  }
+  auto metadata = MakeMetadata(files);
+  ScanSettings settings{.target_split_size = 
files[0].data_file->file_size_in_bytes / 4};
+  ICEBERG_UNWRAP_OR_FAIL(auto groups, PlanGroups(metadata, settings));
+  EXPECT_GE(CountSplitTasks(groups), 9U);
+  ExpectParallelMatches(metadata, settings, ExpectedRows(files));
+}
+
+TEST_P(ParallelTableScanTest, MissingManifestOffsetsUseFixedRanges) {
+  ICEBERG_UNWRAP_OR_FAIL(auto written, WriteDataFile("no-offsets.parquet", 0, 
3000,
+                                                     
/*max_row_group_rows=*/250));
+  written.data_file->split_offsets.clear();
+  std::vector<WrittenFile> files{written};
+  auto metadata = MakeMetadata(files);
+  ScanSettings settings{.target_split_size = 
written.data_file->file_size_in_bytes / 5};
+  ICEBERG_UNWRAP_OR_FAIL(auto groups, PlanGroups(metadata, settings));
+  EXPECT_GE(CountSplitTasks(groups), 5U);
+  ExpectParallelMatches(metadata, settings, ExpectedRows(files));
+}
+
+TEST_P(ParallelTableScanTest, ManifestOffsetsThatMissCanonicalStarts) {
+  ICEBERG_UNWRAP_OR_FAIL(auto written, WriteDataFile("shifted.parquet", 0, 
2400,
+                                                     
/*max_row_group_rows=*/200));
+  ICEBERG_UNWRAP_OR_FAIL(auto starts, RowGroupStarts(*written.data_file));
+  ASSERT_EQ(starts.size(), 12U);
+  // Valid (increasing, in-bounds) offsets that fall inside row groups, so that
+  // planned ranges disagree with the starts the reader assigns rows by.
+  std::vector<int64_t> shifted;
+  for (size_t group = 0; group < starts.size(); ++group) {
+    const int64_t end = group + 1 < starts.size() ? starts[group + 1]
+                                                  : 
written.data_file->file_size_in_bytes;
+    shifted.push_back(starts[group] + (end - starts[group]) / 2);
+  }
+  written.data_file->split_offsets = shifted;
+  std::vector<WrittenFile> files{written};
+  auto metadata = MakeMetadata(files);
+  ScanSettings settings{.target_split_size = 
written.data_file->file_size_in_bytes / 6};
+  ICEBERG_UNWRAP_OR_FAIL(auto groups, PlanGroups(metadata, settings));
+  EXPECT_GE(CountSplitTasks(groups), 3U);
+  ExpectParallelMatches(metadata, settings, ExpectedRows(files));
+}
+
+TEST_P(ParallelTableScanTest, OneLargeRowGroupWithoutOffsets) {
+  ICEBERG_UNWRAP_OR_FAIL(auto written, WriteDataFile("single-group.parquet", 
0, 2000));
+  ICEBERG_UNWRAP_OR_FAIL(auto starts, RowGroupStarts(*written.data_file));
+  ASSERT_EQ(starts.size(), 1U);
+  written.data_file->split_offsets.clear();
+  std::vector<WrittenFile> files{written};
+  auto metadata = MakeMetadata(files);
+  // Several ranges, only one of which holds the row group's start.
+  ScanSettings settings{.target_split_size = 
written.data_file->file_size_in_bytes / 4};
+  ICEBERG_UNWRAP_OR_FAIL(auto groups, PlanGroups(metadata, settings));
+  EXPECT_GE(CountSplitTasks(groups), 4U);
+  ExpectParallelMatches(metadata, settings, ExpectedRows(files));
+}
+
+TEST_P(ParallelTableScanTest, ManySmallFiles) {
+  std::vector<WrittenFile> files;
+  for (int file = 0; file < 60; ++file) {
+    ICEBERG_UNWRAP_OR_FAIL(
+        auto written,
+        WriteDataFile(std::format("small-{}.parquet", file), file * 10, 10));
+    files.push_back(std::move(written));
+  }
+  auto metadata = MakeMetadata(files);
+  ScanSettings settings;
+  ICEBERG_UNWRAP_OR_FAIL(auto groups, PlanGroups(metadata, settings));
+  // Small files are packed together.
+  EXPECT_LT(groups.size(), files.size());
+  ExpectParallelMatches(metadata, settings, ExpectedRows(files));
+}
+
+TEST_P(ParallelTableScanTest, MixedParquetAndAvroFiles) {
+  std::vector<WrittenFile> files;
+  for (int file = 0; file < 6; ++file) {
+    const auto format = file % 2 == 0 ? FileFormatType::kParquet : 
FileFormatType::kAvro;
+    const auto suffix = format == FileFormatType::kParquet ? "parquet" : 
"avro";
+    ICEBERG_UNWRAP_OR_FAIL(
+        auto written, WriteDataFile(std::format("mixed-{}.{}", file, suffix), 
file * 500,
+                                    500, /*max_row_group_rows=*/100, format));
+    files.push_back(std::move(written));
+  }
+  auto metadata = MakeMetadata(files);
+  ScanSettings settings{.target_split_size = 
files[0].data_file->file_size_in_bytes / 3};

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]


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

Reply via email to