diff --git a/src/iceberg/benchmark/CMakeLists.txt b/src/iceberg/benchmark/CMakeLists.txt index 58c7f5f10..930413555 100644 --- a/src/iceberg/benchmark/CMakeLists.txt +++ b/src/iceberg/benchmark/CMakeLists.txt @@ -28,3 +28,11 @@ endfunction() add_iceberg_benchmark(benchmark_smoke) add_iceberg_benchmark(metrics_evaluator_benchmark) add_iceberg_benchmark(mumbling_bitmap_benchmark) + +# Reads real Parquet tables, so it needs the bundle. +if(ICEBERG_BUILD_BUNDLE) + add_executable(parallel_scan_benchmark parallel_scan_benchmark.cc) + target_link_libraries(parallel_scan_benchmark + PRIVATE "$,iceberg_bundle_static,iceberg_bundle_shared>" + ) +endif() diff --git a/src/iceberg/benchmark/parallel_scan_benchmark.cc b/src/iceberg/benchmark/parallel_scan_benchmark.cc new file mode 100644 index 000000000..983eb6e04 --- /dev/null +++ b/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 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#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 metrics; +}; + +std::shared_ptr TableSchema() { + return std::make_shared( + std::vector{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> WriteFile(const std::shared_ptr& io, + const std::shared_ptr& 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(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{"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> CreateTable(const Config& config, + const std::shared_ptr& 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 ScanFilter() { + return Expressions::GreaterThanOrEqual("id", Literal::Long(0)); +} + +FileScanTaskReader::Options ReaderOptions(const std::shared_ptr& io, + const std::shared_ptr& schema) { + return {.io = io, + .table_schema = schema, + .projected_schema = schema, + .case_sensitive = true, + .properties = {{"read.batch-size", "8192"}}, + .apply_residuals = true}; +} + +Result> BuildScan(const Table& table, bool filter) { + ICEBERG_ASSIGN_OR_RAISE(auto builder, table.NewScan()); + if (filter) { + builder->Filter(ScanFilter()); + } + return builder->Build(); +} + +Result 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(duration).count(); +} + +Result RunSerial(const Table& table, const std::shared_ptr& io, + const std::shared_ptr& 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 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 RunParallel(const Table& table, const std::shared_ptr& io, + const std::shared_ptr& schema, int workers, bool filter) { + Run run; + static ScanExecutor executor; + auto metrics = std::make_shared(); + 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 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 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& ratios) { + constexpr int kResamples = 10000; + std::mt19937_64 random(20261123); + std::uniform_int_distribution pick(0, ratios.size() - 1); + std::vector medians; + medians.reserve(kResamples); + std::vector 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(0.025 * kResamples)], + .high = medians[static_cast(0.975 * kResamples) - 1]}; +} + +double CoefficientOfVariation(const std::vector& 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; +} + +Status RunWorkload(const Config& config, const Workload& workload) { + auto io = std::shared_ptr(arrow::ArrowFileSystemFileIO::MakeLocalFileIO()); + const auto setup_start = Clock::now(); + ICEBERG_ASSIGN_OR_RAISE(auto table, CreateTable(config, io, workload)); + ICEBERG_ASSIGN_OR_RAISE(auto schema, table->schema()); + ICEBERG_ASSIGN_OR_RAISE(auto plan, BuildScan(*table, config.filter)); + ICEBERG_ASSIGN_OR_RAISE(auto groups, plan->PlanTasks()); + size_t tasks = 0; + for (const auto& group : groups) { + tasks += group->tasks().size(); + } + std::cout << std::format( + "\n== Workload {}: {} files x {} rows, {} rows per row group; {} groups, {} tasks " + "(setup {:.1f}s)\n", + workload.name, workload.files, workload.rows_per_file, workload.rows_per_row_group, + groups.size(), tasks, Seconds(Clock::now() - setup_start)); + + // Warm the page cache once; runs are labeled warm. + ICEBERG_ASSIGN_OR_RAISE(auto warm, RunSerial(*table, io, schema, config.filter)); + const int64_t expected_rows = workload.files * workload.rows_per_file; + if (warm.rows != expected_rows) { + return Invalid("Serial scan read {} rows, expected {}", warm.rows, expected_rows); + } + + std::vector planning; + for (int trial = 0; trial < 5; ++trial) { + ICEBERG_ASSIGN_OR_RAISE(auto seconds, PlanningSeconds(*table, config.filter)); + planning.push_back(seconds); + } + std::cout << std::format("planning (PlanTasks, median of 5): {:.4f}s\n", + Median(planning)); + + if (config.sweep) { + ICEBERG_ASSIGN_OR_RAISE(auto serial, RunSerial(*table, io, schema, config.filter)); + std::cout << std::format("sweep serial: {:.3f}s, {:.2f} Mrows/s\n", + serial.total_seconds, + serial.rows / serial.total_seconds / 1e6); + for (int workers : {1, 2, 4, 8}) { + ICEBERG_ASSIGN_OR_RAISE(auto run, + RunParallel(*table, io, schema, workers, config.filter)); + if (run.rows != expected_rows) { + return Invalid("Parallel scan read {} rows, expected {}", run.rows, + expected_rows); + } + std::cout << std::format("sweep {} workers: {:.3f}s, {:.2f} Mrows/s\n", workers, + run.total_seconds, run.rows / run.total_seconds / 1e6); + } + } + + std::vector serial_total; + std::vector parallel_total; + std::vector total_ratios; + std::vector read_ratios; + // Indexed by path: 0 = serial, 1 = parallel. + std::array, 2> bytes_read; + std::array, 2> allocations; + std::array, 2> allocated_bytes; + internal::ParallelScanMetricsSnapshot peak; + for (int trial = 0; trial < config.trials; ++trial) { + Run serial; + Run parallel; + if (trial % 2 == 0) { + ICEBERG_ASSIGN_OR_RAISE(serial, RunSerial(*table, io, schema, config.filter)); + ICEBERG_ASSIGN_OR_RAISE( + parallel, + RunParallel(*table, io, schema, config.primary_workers, config.filter)); + } else { + ICEBERG_ASSIGN_OR_RAISE( + parallel, + RunParallel(*table, io, schema, config.primary_workers, config.filter)); + ICEBERG_ASSIGN_OR_RAISE(serial, RunSerial(*table, io, schema, config.filter)); + } + if (serial.rows != expected_rows || parallel.rows != expected_rows) { + return Invalid("Row count mismatch: serial {}, parallel {}, expected {}", + serial.rows, parallel.rows, expected_rows); + } + serial_total.push_back(serial.total_seconds); + parallel_total.push_back(parallel.total_seconds); + total_ratios.push_back(serial.total_seconds / parallel.total_seconds); + read_ratios.push_back(serial.read_seconds / parallel.read_seconds); + for (const auto& [path, run] : {std::pair{0, &serial}, std::pair{1, ¶llel}}) { + bytes_read[path].push_back(static_cast(run->counters.bytes_read)); + allocations[path].push_back(static_cast(run->counters.allocations)); + allocated_bytes[path].push_back(static_cast(run->counters.allocated_bytes)); + } + const auto& metrics = *parallel.metrics; + peak.peak_queued_bytes = std::max(peak.peak_queued_bytes, metrics.peak_queued_bytes); + peak.peak_queued_batches = + std::max(peak.peak_queued_batches, metrics.peak_queued_batches); + peak.peak_held_bytes = std::max(peak.peak_held_bytes, metrics.peak_held_bytes); + peak.oversized_admissions += metrics.oversized_admissions; + peak.producer_wait += metrics.producer_wait; + peak.tasks_opened = metrics.tasks_opened; + } + + const auto total = BootstrapMedian(total_ratios); + const auto read = BootstrapMedian(read_ratios); + std::cout << std::format( + "paired trials: {} (serial vs {} workers, alternating order)\n" + "serial median {:.3f}s (CV {:.1f}%), {:.2f} Mrows/s\n" + "parallel median {:.3f}s (CV {:.1f}%), {:.2f} Mrows/s\n" + "end-to-end speedup: median {:.2f}x, 95% CI [{:.2f}, {:.2f}]\n" + "read-phase speedup: median {:.2f}x, 95% CI [{:.2f}, {:.2f}]\n" + "parallel queue: peak {} bytes / {} batches, peak held {} bytes, " + "{} oversized admissions, producer wait {:.3f}s total, {} task opens per scan\n" + "per scan (median, serial / parallel): bytes read {:.1f} / {:.1f} MiB, " + "Arrow pool allocations {:.0f} / {:.0f} ({:.1f} / {:.1f} MiB)\n" + "peak process RSS so far: {} MiB\n", + config.trials, config.primary_workers, Median(serial_total), + 100 * CoefficientOfVariation(serial_total), + expected_rows / Median(serial_total) / 1e6, Median(parallel_total), + 100 * CoefficientOfVariation(parallel_total), + expected_rows / Median(parallel_total) / 1e6, total.median, total.low, total.high, + read.median, read.low, read.high, peak.peak_queued_bytes, peak.peak_queued_batches, + peak.peak_held_bytes, peak.oversized_admissions, + std::chrono::duration(peak.producer_wait).count(), peak.tasks_opened, + Median(bytes_read[0]) / (1 << 20), Median(bytes_read[1]) / (1 << 20), + Median(allocations[0]), Median(allocations[1]), + Median(allocated_bytes[0]) / (1 << 20), Median(allocated_bytes[1]) / (1 << 20), + PeakRssKiB() / 1024); + return {}; +} + +int PrimaryWorkers() { + const unsigned cores = std::max(1U, std::thread::hardware_concurrency()); + if (cores >= 16) { + return 8; + } + return cores >= 8 ? 4 : 2; +} + +Config ParseArgs(int argc, char** argv) { + Config config; + for (int index = 1; index < argc; ++index) { + std::string_view arg = argv[index]; + auto value = [&](std::string_view prefix) -> std::optional { + if (arg.starts_with(prefix)) { + return std::string(arg.substr(prefix.size())); + } + return std::nullopt; + }; + if (auto dir = value("--dir=")) { + config.dir = *dir; + } else if (auto trials = value("--trials=")) { + config.trials = std::max(2, std::stoi(*trials)); + } else if (auto workers = value("--workers=")) { + config.primary_workers = std::stoi(*workers); + } else if (auto workload = value("--workload=")) { + config.workload = *workload; + } else if (arg == "--sweep") { + config.sweep = true; + } else if (auto filter = value("--filter=")) { + config.filter = *filter != "none"; + } else { + std::cerr << "Unknown argument: " << arg << "\n"; + std::exit(2); + } + } + if (config.primary_workers <= 0) { + config.primary_workers = PrimaryWorkers(); + } + return config; +} + +int RunBenchmark(int argc, char** argv) { + parquet::RegisterAll(); + avro::RegisterAll(); + const Config config = ParseArgs(argc, argv); + std::cout << std::format( + "hardware threads: {}, primary workers: {}, residual filter: {}, dir: {}\n", + std::thread::hardware_concurrency(), config.primary_workers, + config.filter ? "all-pass" : "none", config.dir.string()); + + const std::vector workloads = { + {.name = "large", + .files = 4, + .rows_per_file = 2'000'000, + .rows_per_row_group = 125'000, + .target_split_size = int64_t{16} << 20}, + {.name = "small", + .files = 400, + .rows_per_file = 2'000, + .rows_per_row_group = 2'000, + .target_split_size = int64_t{128} << 20}, + }; + for (const auto& workload : workloads) { + if (config.workload != "all" && config.workload != workload.name) { + continue; + } + if (auto status = RunWorkload(config, workload); !status.has_value()) { + std::cerr << "Workload " << workload.name << " failed: " << status.error().message + << "\n"; + return 1; + } + } + return 0; +} + +} // namespace +} // namespace iceberg + +int main(int argc, char** argv) { return iceberg::RunBenchmark(argc, argv); } diff --git a/src/iceberg/test/CMakeLists.txt b/src/iceberg/test/CMakeLists.txt index c69ad54c7..e73e7bf96 100644 --- a/src/iceberg/test/CMakeLists.txt +++ b/src/iceberg/test/CMakeLists.txt @@ -287,6 +287,7 @@ if(ICEBERG_BUILD_BUNDLE) incremental_append_scan_test.cc incremental_changelog_scan_test.cc parallel_scan_reader_test.cc + parallel_table_scan_test.cc scan_planning_metrics_test.cc table_scan_test.cc) diff --git a/src/iceberg/test/parallel_table_scan_test.cc b/src/iceberg/test/parallel_table_scan_test.cc new file mode 100644 index 000000000..4fccfb5a1 --- /dev/null +++ b/src/iceberg/test/parallel_table_scan_test.cc @@ -0,0 +1,685 @@ +/* + * 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 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#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> 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 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]( + const char* name, + bool required) -> Result> { + 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(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 data_file; + int32_t first_id = 0; + int32_t rows = 0; + }; + + Result 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 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> WritePositionDeletes( + const std::string& path, const std::string& data_path, + const std::vector& 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> 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 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 MakeMetadata( + const std::vector& files, + std::vector> delete_files = {}) { + std::vector data_entries; + for (const auto& file : files) { + data_entries.push_back(MakeEntry(ManifestStatus::kAdded, kSnapshotId, + kSequenceNumber, file.data_file)); + } + std::vector manifests; + manifests.push_back(WriteDataManifest(GetParam(), kSnapshotId, + std::move(data_entries), unpartitioned_spec_)); + if (!delete_files.empty()) { + std::vector 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_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 filter; + bool case_sensitive = true; + std::shared_ptr projection; + }; + + Result> BuildScan( + const std::shared_ptr& metadata, const ScanSettings& settings) { + ICEBERG_ASSIGN_OR_RAISE(auto builder, MakeScanBuilder(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> ReadSerially(const std::shared_ptr& 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 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> ReadInParallel(const std::shared_ptr& 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>> PlanGroups( + const std::shared_ptr& metadata, const ScanSettings& settings) { + ICEBERG_ASSIGN_OR_RAISE(auto scan, BuildScan(metadata, settings)); + return scan->PlanTasks(); + } + + static size_t CountSplitTasks( + const std::vector>& 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 ExpectedRows(const std::vector& files, + const std::unordered_set& deleted = {}) { + std::vector 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& metadata, + const ScanSettings& settings, + const std::vector& 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 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 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 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 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 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 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 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}; + ICEBERG_UNWRAP_OR_FAIL(auto groups, PlanGroups(metadata, settings)); + for (const auto& group : groups) { + for (const auto& task : group->tasks()) { + if (task->data_file()->file_format == FileFormatType::kAvro) { + EXPECT_FALSE(task->is_split()); + } + } + } + ExpectParallelMatches(metadata, settings, ExpectedRows(files)); +} + +TEST_P(ParallelTableScanTest, CaseInsensitiveResidualFilter) { + std::vector files; + for (int file = 0; file < 2; ++file) { + ICEBERG_UNWRAP_OR_FAIL( + auto written, WriteDataFile(std::format("filtered-{}.parquet", file), file * 1000, + 1000, /*max_row_group_rows=*/100)); + files.push_back(std::move(written)); + } + auto metadata = MakeMetadata(files); + ScanSettings settings{ + .target_split_size = files[0].data_file->file_size_in_bytes / 4, + .filter = Expressions::And(Expressions::GreaterThanOrEqual("ID", Literal::Int(450)), + Expressions::Equal("Data", Literal::String("value-3"))), + .case_sensitive = false}; + std::vector expected; + for (const auto& row : ExpectedRows(files)) { + if (row.id >= 450 && row.data == "value-3") { + expected.push_back(row); + } + } + ASSERT_FALSE(expected.empty()); + ExpectParallelMatches(metadata, settings, expected); +} + +TEST_P(ParallelTableScanTest, PlannedProjectionRequiresResidualFields) { + ICEBERG_UNWRAP_OR_FAIL(auto file, WriteDataFile("folded.parquet", 0, 25)); + auto metadata = MakeMetadata({file}); + for (bool case_sensitive : {true, false}) { + for (bool combined : {false, true}) { + SCOPED_TRACE(case_sensitive); + SCOPED_TRACE(combined); + ICEBERG_UNWRAP_OR_FAIL(auto builder, MakeScanBuilder(metadata)); + auto filter = Expressions::NotNull(case_sensitive ? "id" : "ID"); + std::shared_ptr residual = filter; + if (combined) { + residual = Expressions::And( + filter, Expressions::Equal("data", Literal::String("value-3"))); + } + builder->Select({"data"}).CaseSensitive(case_sensitive).Filter(residual); + ICEBERG_UNWRAP_OR_FAIL(auto scan, builder->Build()); + ICEBERG_UNWRAP_OR_FAIL(auto projection, scan->schema()); + ASSERT_EQ(projection->fields().size(), 1); + ASSERT_EQ(projection->fields()[0].name(), "data"); + ICEBERG_UNWRAP_OR_FAIL(auto groups, scan->PlanTasksStream()); + FileScanTaskReader::Options reader_options{.io = file_io_, + .table_schema = schema_, + .projected_schema = projection, + .case_sensitive = case_sensitive}; + ICEBERG_UNWRAP_OR_FAIL( + auto stream, + ParallelScanReader::Open(std::move(groups), {.reader_options = reader_options, + .executor = &executor_, + .worker_count = 4, + .max_queued_batches = 1, + .max_queued_bytes = 1 << 20})); + // Every original residual reference must be in the read projection, even + // if binding against table_schema would fold its predicate to a constant. + { + auto batches = ::arrow::ImportRecordBatchReader(&stream).ValueOrDie(); + auto next = batches->Next(); + ASSERT_FALSE(next.ok()); + EXPECT_THAT(next.status().message(), + testing::HasSubstr(std::format("Cannot find field '{}'", + case_sensitive ? "id" : "ID"))); + EXPECT_THAT(next.status().message(), testing::HasSubstr("folded.parquet")); + } + + // Explicitly including the residual column makes the same planned scan + // readable, with both columns retained in the output. + reader_options.projected_schema = schema_; + ICEBERG_UNWRAP_OR_FAIL(auto valid_groups, scan->PlanTasksStream()); + ICEBERG_UNWRAP_OR_FAIL(auto valid_stream, + ParallelScanReader::Open(std::move(valid_groups), + {.reader_options = reader_options, + .executor = &executor_, + .worker_count = 4, + .max_queued_batches = 1, + .max_queued_bytes = 1 << 20})); + ICEBERG_UNWRAP_OR_FAIL(auto rows, CollectRows(&valid_stream)); + auto expected = ExpectedRows({file}); + if (combined) { + std::erase_if(expected, [](const Row& row) { return row.data != "value-3"; }); + } + EXPECT_EQ(rows, expected); + } + } +} + +TEST_P(ParallelTableScanTest, PositionDeletesApplyToEverySplit) { + if (GetParam() < 2) { + GTEST_SKIP() << "Delete files require format version 2"; + } + ICEBERG_UNWRAP_OR_FAIL(auto written, WriteDataFile("with-deletes.parquet", 0, 2000, + /*max_row_group_rows=*/200)); + std::vector positions; + std::unordered_set deleted; + for (int32_t id = 3; id < 2000; id += 7) { + positions.push_back(id); + deleted.insert(id); + } + ICEBERG_UNWRAP_OR_FAIL( + auto deletes, + WritePositionDeletes("deletes.parquet", written.data_file->file_path, positions)); + std::vector files{written}; + auto metadata = MakeMetadata(files, {deletes}); + ScanSettings settings{.target_split_size = written.data_file->file_size_in_bytes / 4}; + ICEBERG_UNWRAP_OR_FAIL(auto groups, PlanGroups(metadata, settings)); + // Row groups are merged toward the target, so the file has at least two splits. + ASSERT_GE(CountSplitTasks(groups), 2U); + for (const auto& group : groups) { + for (const auto& task : group->tasks()) { + EXPECT_EQ(task->delete_files().size(), 1U); + } + } + ExpectParallelMatches(metadata, settings, ExpectedRows(files, deleted)); +} + +TEST_P(ParallelTableScanTest, RowLineageAndPositionsAreAbsolute) { + if (GetParam() < 3) { + GTEST_SKIP() << "Row lineage requires format version 3"; + } + std::vector files; + for (int file = 0; file < 2; ++file) { + ICEBERG_UNWRAP_OR_FAIL( + auto written, WriteDataFile(std::format("lineage-{}.parquet", file), file * 1200, + 1200, /*max_row_group_rows=*/150)); + files.push_back(std::move(written)); + } + auto metadata = MakeMetadata(files); + auto projection = std::make_shared( + std::vector{SchemaField::MakeRequired(1, "id", int32()), + MetadataColumns::kRowId, MetadataColumns::kRowPosition}); + ScanSettings settings{.target_split_size = files[0].data_file->file_size_in_bytes / 4, + .projection = projection}; + + // The manifest assigns first row ids in file order. + std::map first_row_ids; + int64_t next_row_id = 0; + for (const auto& file : files) { + first_row_ids[file.first_id] = next_row_id; + next_row_id += file.rows; + } + std::vector expected; + for (const auto& file : files) { + for (int32_t row = 0; row < file.rows; ++row) { + expected.push_back(Row{.id = file.first_id + row, + .row_id = first_row_ids[file.first_id] + row, + .pos = row}); + } + } + std::ranges::sort(expected); + ExpectParallelMatches(metadata, settings, expected); +} + +TEST_P(ParallelTableScanTest, EarlyReleaseBetweenCallbacks) { + std::vector files; + for (int file = 0; file < 4; ++file) { + ICEBERG_UNWRAP_OR_FAIL( + auto written, WriteDataFile(std::format("early-{}.parquet", file), file * 1000, + 1000, /*max_row_group_rows=*/100)); + 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 scan, BuildScan(metadata, settings)); + ICEBERG_UNWRAP_OR_FAIL(auto groups, scan->PlanTasksStream()); + ICEBERG_UNWRAP_OR_FAIL( + auto stream, ParallelScanReader::Open(std::move(groups), + {.reader_options = ReaderOptions(settings), + .executor = &executor_, + .worker_count = 4, + .max_queued_batches = 1, + .max_queued_bytes = 1 << 20})); + ArrowArray first{}; + ASSERT_EQ(stream.get_next(&stream, &first), 0); + ASSERT_NE(first.release, nullptr); + stream.release(&stream); + // The caller still owns the returned batch. + EXPECT_GT(first.length, 0); + first.release(&first); +} + +INSTANTIATE_TEST_SUITE_P(ParallelTableScanVersions, ParallelTableScanTest, + testing::Values(1, 2, 3)); + +} // namespace iceberg