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


##########
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());

Review Comment:
   Done



##########
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);

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