From 829cf31cca67c50feb952a9069baf5be98db5e84 Mon Sep 17 00:00:00 2001 From: Kam Cheung Ting Date: Mon, 23 Nov 2026 08:23:13 +0000 Subject: [PATCH 1/5] feat(data): Support split and parallel scans - Part-4: bounded parallel Arrow reader Add ParallelScanReader, which reads the groups of a FileScanTaskGroupStream with a fixed set of workers and returns one Arrow C stream. - Each worker owns a FileScanTaskReader with residual enforcement forced on. Workers claim groups through a planning token: only one calls the group stream at a time, outside all locks. - Completed batches enter an output queue bounded by batch count and by charged bytes. Producers are admitted in FIFO order; a batch larger than the byte budget is admitted only into an empty queue. - ArrowBatchSizer charges a batch as the checked sum of its Arrow buffer spans, after preflighting offsets, lengths, buffer counts, and every layout-dependent size product for overflow. List views and run-end encoded arrays are rejected. - Each task stream's schema is compared with the projected schema before its batches are read. - The first planning, read, schema, or sizing error stops new work, releases queued batches, and is reported from get_next as EIO with the file and byte range in get_last_error. Releasing the stream between callbacks stops and joins the workers. - iceberg_data now links Threads unconditionally. Co-authored-by: Isaac --- .../IcebergThirdpartyToolchain.cmake | 8 +- src/iceberg/CMakeLists.txt | 13 +- src/iceberg/cpp20_compatibility_internal.h | 1 + src/iceberg/data/arrow_batch_sizer.cc | 364 +++++++ src/iceberg/data/arrow_batch_sizer_internal.h | 72 ++ src/iceberg/data/parallel_scan_reader.cc | 592 ++++++++++++ src/iceberg/data/parallel_scan_reader.h | 104 ++ .../data/parallel_scan_reader_internal.h | 87 ++ src/iceberg/test/CMakeLists.txt | 7 + src/iceberg/test/arrow_batch_sizer_test.cc | 372 ++++++++ src/iceberg/test/parallel_scan_reader_test.cc | 886 ++++++++++++++++++ 11 files changed, 2500 insertions(+), 6 deletions(-) create mode 100644 src/iceberg/data/arrow_batch_sizer.cc create mode 100644 src/iceberg/data/arrow_batch_sizer_internal.h create mode 100644 src/iceberg/data/parallel_scan_reader.cc create mode 100644 src/iceberg/data/parallel_scan_reader.h create mode 100644 src/iceberg/data/parallel_scan_reader_internal.h create mode 100644 src/iceberg/test/arrow_batch_sizer_test.cc create mode 100644 src/iceberg/test/parallel_scan_reader_test.cc diff --git a/cmake_modules/IcebergThirdpartyToolchain.cmake b/cmake_modules/IcebergThirdpartyToolchain.cmake index b176dead8a..54e02404a7 100644 --- a/cmake_modules/IcebergThirdpartyToolchain.cmake +++ b/cmake_modules/IcebergThirdpartyToolchain.cmake @@ -713,8 +713,6 @@ function(resolve_spdlog_dependency) list(APPEND ICEBERG_SYSTEM_DEPENDENCIES spdlog) endif() - list(APPEND ICEBERG_SYSTEM_DEPENDENCIES Threads) - set(ICEBERG_SYSTEM_DEPENDENCIES ${ICEBERG_SYSTEM_DEPENDENCIES} PARENT_SCOPE) @@ -969,6 +967,12 @@ resolve_nanoarrow_dependency() resolve_croaring_dependency() resolve_utf8proc_dependency() resolve_nlohmann_json_dependency() + +# iceberg_data starts worker threads for parallel scans, so Threads is required +# even when spdlog is disabled. +find_package(Threads REQUIRED) +list(APPEND ICEBERG_SYSTEM_DEPENDENCIES Threads) + if(ICEBERG_SPDLOG) resolve_spdlog_dependency() endif() diff --git a/src/iceberg/CMakeLists.txt b/src/iceberg/CMakeLists.txt index 0065b838b1..422622304d 100644 --- a/src/iceberg/CMakeLists.txt +++ b/src/iceberg/CMakeLists.txt @@ -251,11 +251,13 @@ if(MSVC_TOOLCHAIN) endif() set(ICEBERG_DATA_SOURCES + data/arrow_batch_sizer.cc data/data_writer.cc data/delete_filter.cc data/delete_loader.cc data/equality_delete_writer.cc data/file_scan_task_reader.cc + data/parallel_scan_reader.cc data/position_delete_writer.cc data/writer.cc) @@ -264,18 +266,21 @@ set(ICEBERG_DATA_SHARED_BUILD_INTERFACE_LIBS) set(ICEBERG_DATA_STATIC_INSTALL_INTERFACE_LIBS) set(ICEBERG_DATA_SHARED_INSTALL_INTERFACE_LIBS) +# The parallel scan reader starts worker threads. list(APPEND ICEBERG_DATA_STATIC_BUILD_INTERFACE_LIBS - "$,iceberg_static,iceberg_shared>") + "$,iceberg_static,iceberg_shared>" + Threads::Threads) list(APPEND ICEBERG_DATA_SHARED_BUILD_INTERFACE_LIBS - "$,iceberg_shared,iceberg_static>") + "$,iceberg_shared,iceberg_static>" + Threads::Threads) list(APPEND ICEBERG_DATA_STATIC_INSTALL_INTERFACE_LIBS "$,iceberg::iceberg_static,iceberg::iceberg_shared>" -) + Threads::Threads) list(APPEND ICEBERG_DATA_SHARED_INSTALL_INTERFACE_LIBS "$,iceberg::iceberg_shared,iceberg::iceberg_static>" -) + Threads::Threads) add_iceberg_lib(iceberg_data SOURCES diff --git a/src/iceberg/cpp20_compatibility_internal.h b/src/iceberg/cpp20_compatibility_internal.h index d9c64d36a2..cbd7049640 100644 --- a/src/iceberg/cpp20_compatibility_internal.h +++ b/src/iceberg/cpp20_compatibility_internal.h @@ -40,6 +40,7 @@ #include "iceberg/data/delete_loader.h" #include "iceberg/data/equality_delete_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/writer.h" #include "iceberg/data_table_scan.h" diff --git a/src/iceberg/data/arrow_batch_sizer.cc b/src/iceberg/data/arrow_batch_sizer.cc new file mode 100644 index 0000000000..dff088b740 --- /dev/null +++ b/src/iceberg/data/arrow_batch_sizer.cc @@ -0,0 +1,364 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "iceberg/data/arrow_batch_sizer_internal.h" +#include "iceberg/util/macros.h" + +namespace iceberg::internal { + +namespace { + +constexpr int64_t kInt64Max = std::numeric_limits::max(); + +// The number of leading buffers a binary or string view array always has. +constexpr int64_t kBinaryViewFixedBuffers = 2; + +constexpr int64_t kVariadicSizeBytes = static_cast(sizeof(int64_t)); + +bool IsBinaryView(ArrowType type) { + return type == NANOARROW_TYPE_BINARY_VIEW || type == NANOARROW_TYPE_STRING_VIEW; +} + +std::optional CheckedAdd(int64_t lhs, int64_t rhs) { + if (lhs < 0 || rhs < 0 || lhs > kInt64Max - rhs) { + return std::nullopt; + } + return lhs + rhs; +} + +std::optional CheckedMultiply(int64_t lhs, int64_t rhs) { + if (lhs < 0 || rhs < 0) { + return std::nullopt; + } + if (lhs != 0 && rhs > kInt64Max / lhs) { + return std::nullopt; + } + return lhs * rhs; +} + +// Returns whether `bytes` can also be represented as a size_t, which nanoarrow and +// the allocator use for buffer sizes. +bool FitsSizeT(int64_t bytes) { + if constexpr (sizeof(size_t) >= sizeof(int64_t)) { + return bytes >= 0; + } else { + return bytes >= 0 && + static_cast(bytes) <= std::numeric_limits::max(); + } +} + +// The position of a nested array, e.g. "root.1.dictionary". Only formatted when an +// error is reported, so measuring a valid batch does not allocate strings. +class ArrayPath { + public: + static constexpr int64_t kDictionary = -1; + + // Appends a child index (or kDictionary) until the returned scope ends. + class Scope { + public: + Scope(ArrayPath& path, int64_t step) : path_(path) { path_.steps_.push_back(step); } + ~Scope() { path_.steps_.pop_back(); } + Scope(const Scope&) = delete; + Scope& operator=(const Scope&) = delete; + + private: + ArrayPath& path_; + }; + + std::string ToString() const { + std::string result = "root"; + for (int64_t step : steps_) { + result += step == kDictionary ? ".dictionary" : "." + std::to_string(step); + } + return result; + } + + private: + std::vector steps_; +}; + +// Returns the minimum byte size nanoarrow derives for fixed buffer `index` from the +// array's offset and length alone, or std::nullopt when the product overflows. +// Buffers whose size depends on data (for example string data) report zero here. +std::optional LayoutBufferBytes(const ArrowLayout& layout, int index, + int64_t offset_plus_length) { + const int64_t element_size_bits = layout.element_size_bits[index]; + const int64_t element_size_bytes = element_size_bits / 8; + switch (layout.buffer_type[index]) { + case NANOARROW_BUFFER_TYPE_VALIDITY: + return offset_plus_length / 8 + (offset_plus_length % 8 != 0 ? 1 : 0); + case NANOARROW_BUFFER_TYPE_DATA_OFFSET: { + if (offset_plus_length == 0) { + return 0; + } + auto offset_count = CheckedAdd(offset_plus_length, 1); + if (!offset_count.has_value()) { + return std::nullopt; + } + return CheckedMultiply(*offset_count, element_size_bytes); + } + case NANOARROW_BUFFER_TYPE_SIZE: + case NANOARROW_BUFFER_TYPE_VIEW_OFFSET: + case NANOARROW_BUFFER_TYPE_TYPE_ID: + case NANOARROW_BUFFER_TYPE_UNION_OFFSET: + return CheckedMultiply(offset_plus_length, element_size_bytes); + case NANOARROW_BUFFER_TYPE_DATA: { + auto bits = CheckedMultiply(offset_plus_length, element_size_bits); + if (!bits.has_value()) { + return std::nullopt; + } + auto rounded = CheckedAdd(*bits, 7); + if (!rounded.has_value()) { + return std::nullopt; + } + return *rounded / 8; + } + case NANOARROW_BUFFER_TYPE_NONE: + case NANOARROW_BUFFER_TYPE_VARIADIC_DATA: + case NANOARROW_BUFFER_TYPE_VARIADIC_SIZE: + return 0; + } + return std::nullopt; +} + +int FixedBufferCount(const ArrowArrayView& view) { + if (IsBinaryView(view.storage_type)) { + return static_cast(kBinaryViewFixedBuffers); + } + int count = 0; + while (count < NANOARROW_MAX_FIXED_BUFFERS && + view.layout.buffer_type[count] != NANOARROW_BUFFER_TYPE_NONE) { + ++count; + } + return count; +} + +// Checks everything nanoarrow trusts before it sizes buffers: counts used to index +// array members, and every product that it computes without overflow checks. +Status Preflight(const ArrowArrayView& view, const ArrowArray& array, ArrayPath& path) { + switch (view.storage_type) { + case NANOARROW_TYPE_LIST_VIEW: + case NANOARROW_TYPE_LARGE_LIST_VIEW: + case NANOARROW_TYPE_RUN_END_ENCODED: + return NotSupported("Cannot size Arrow {} array at {}: unsupported layout", + ArrowTypeString(view.storage_type), path.ToString()); + default: + break; + } + + if (array.length < 0 || array.offset < 0) { + return InvalidArrowData("Arrow array at {} has negative offset {} or length {}", + path.ToString(), array.offset, array.length); + } + auto offset_plus_length = CheckedAdd(array.offset, array.length); + if (!offset_plus_length.has_value()) { + return InvalidArrowData("Arrow array at {} offset {} plus length {} overflows", + path.ToString(), array.offset, array.length); + } + + const int fixed_buffers = FixedBufferCount(view); + if (IsBinaryView(view.storage_type)) { + // Validity, views, zero or more variadic data buffers, then the size buffer. + if (array.n_buffers < kBinaryViewFixedBuffers + 1) { + return InvalidArrowData("Arrow {} array at {} has {} buffers; expected at least {}", + ArrowTypeString(view.storage_type), path.ToString(), + array.n_buffers, kBinaryViewFixedBuffers + 1); + } + const int64_t variadic_buffers = array.n_buffers - kBinaryViewFixedBuffers - 1; + if (variadic_buffers > std::numeric_limits::max()) { + return InvalidArrowData("Arrow array at {} has too many variadic buffers: {}", + path.ToString(), variadic_buffers); + } + auto size_buffer_bytes = CheckedMultiply(variadic_buffers, kVariadicSizeBytes); + if (!size_buffer_bytes.has_value() || !FitsSizeT(*size_buffer_bytes)) { + return InvalidArrowData("Arrow array at {} variadic size buffer overflows", + path.ToString()); + } + if (array.buffers == nullptr || + (variadic_buffers > 0 && array.buffers[array.n_buffers - 1] == nullptr)) { + return InvalidArrowData("Arrow array at {} is missing its variadic size buffer", + path.ToString()); + } + } else if (array.n_buffers != fixed_buffers) { + return InvalidArrowData("Arrow {} array at {} has {} buffers; expected {}", + ArrowTypeString(view.storage_type), path.ToString(), + array.n_buffers, fixed_buffers); + } + if (array.n_buffers > 0 && array.buffers == nullptr) { + return InvalidArrowData("Arrow array at {} has a null buffer list", path.ToString()); + } + + for (int index = 0; index < fixed_buffers; ++index) { + auto bytes = LayoutBufferBytes(view.layout, index, *offset_plus_length); + if (!bytes.has_value() || !FitsSizeT(*bytes)) { + return InvalidArrowData( + "Arrow {} array at {} buffer {} size overflows for offset {} and length {}", + ArrowTypeString(view.storage_type), path.ToString(), index, array.offset, + array.length); + } + } + + if (view.storage_type == NANOARROW_TYPE_FIXED_SIZE_LIST) { + auto child_length = + CheckedMultiply(*offset_plus_length, view.layout.child_size_elements); + if (!child_length.has_value()) { + return InvalidArrowData( + "Arrow fixed_size_list array at {} child length overflows for offset {}, " + "length {}, and list size {}", + path.ToString(), array.offset, array.length, view.layout.child_size_elements); + } + } + + if (array.n_children != view.n_children) { + return InvalidArrowData("Arrow array at {} has {} children; expected {}", + path.ToString(), array.n_children, view.n_children); + } + if (array.n_children > 0 && array.children == nullptr) { + return InvalidArrowData("Arrow array at {} has a null child list", path.ToString()); + } + for (int64_t index = 0; index < view.n_children; ++index) { + ArrayPath::Scope child(path, index); + if (array.children[index] == nullptr) { + return InvalidArrowData("Arrow array at {} is null", path.ToString()); + } + ICEBERG_RETURN_UNEXPECTED( + Preflight(*view.children[index], *array.children[index], path)); + } + + if ((view.dictionary == nullptr) != (array.dictionary == nullptr)) { + return InvalidArrowData("Arrow array at {} dictionary does not match its schema", + path.ToString()); + } + if (view.dictionary != nullptr) { + ArrayPath::Scope dictionary(path, ArrayPath::kDictionary); + ICEBERG_RETURN_UNEXPECTED(Preflight(*view.dictionary, *array.dictionary, path)); + } + return {}; +} + +// Sums the spans of the buffers that nanoarrow sized for `view`. +Result SumBufferSpans(const ArrowArrayView& view, ArrayPath& path) { + int64_t total = 0; + auto add = [&](int64_t bytes, std::string_view what) -> Status { + if (bytes < 0) { + return NotSupported("Cannot size Arrow {} array at {}: unknown {} size", + ArrowTypeString(view.storage_type), path.ToString(), what); + } + auto sum = CheckedAdd(total, bytes); + if (!sum.has_value() || !FitsSizeT(*sum)) { + return InvalidArrowData("Arrow array at {} buffer sizes overflow", path.ToString()); + } + total = *sum; + return {}; + }; + + const int fixed_buffers = FixedBufferCount(view); + for (int index = 0; index < fixed_buffers; ++index) { + ICEBERG_RETURN_UNEXPECTED(add(view.buffer_views[index].size_bytes, "buffer")); + } + + if (IsBinaryView(view.storage_type)) { + for (int32_t index = 0; index < view.n_variadic_buffers; ++index) { + ICEBERG_RETURN_UNEXPECTED( + add(view.variadic_buffer_sizes[index], "variadic buffer")); + } + ICEBERG_RETURN_UNEXPECTED( + add(static_cast(view.n_variadic_buffers) * kVariadicSizeBytes, + "variadic size buffer")); + } + + for (int64_t index = 0; index < view.n_children; ++index) { + ArrayPath::Scope child(path, index); + ICEBERG_ASSIGN_OR_RAISE(auto child_bytes, + SumBufferSpans(*view.children[index], path)); + ICEBERG_RETURN_UNEXPECTED(add(child_bytes, "child")); + } + if (view.dictionary != nullptr) { + ArrayPath::Scope dictionary(path, ArrayPath::kDictionary); + ICEBERG_ASSIGN_OR_RAISE(auto dictionary_bytes, + SumBufferSpans(*view.dictionary, path)); + ICEBERG_RETURN_UNEXPECTED(add(dictionary_bytes, "dictionary")); + } + return total; +} + +} // namespace + +class ArrowBatchSizer::Impl { + public: + Impl() = default; + ~Impl() { ArrowArrayViewReset(&view_); } + + Impl(const Impl&) = delete; + Impl& operator=(const Impl&) = delete; + + Status Init(const ArrowSchema& schema) { + ArrowError error; + ArrowErrorInit(&error); + if (ArrowArrayViewInitFromSchema(&view_, &schema, &error) != NANOARROW_OK) { + return InvalidArrowData("Cannot size batches for Arrow schema: {}", error.message); + } + return {}; + } + + Result Measure(const ArrowArray& array) { + if (array.release == nullptr) { + return InvalidArrowData("Cannot size a released Arrow array"); + } + ArrayPath path; + ICEBERG_RETURN_UNEXPECTED(Preflight(view_, array, path)); + ArrowError error; + ArrowErrorInit(&error); + if (ArrowArrayViewSetArray(&view_, &array, &error) != NANOARROW_OK) { + return InvalidArrowData("Cannot size Arrow batch: {}", error.message); + } + return SumBufferSpans(view_, path); + } + + private: + ArrowArrayView view_{}; +}; + +Result> ArrowBatchSizer::Make( + const ArrowSchema& schema) { + auto impl = std::make_unique(); + ICEBERG_RETURN_UNEXPECTED(impl->Init(schema)); + return std::unique_ptr(new ArrowBatchSizer(std::move(impl))); +} + +ArrowBatchSizer::ArrowBatchSizer(std::unique_ptr impl) : impl_(std::move(impl)) {} + +ArrowBatchSizer::~ArrowBatchSizer() = default; + +Result ArrowBatchSizer::Measure(const ArrowArray& array) { + return impl_->Measure(array); +} + +} // namespace iceberg::internal diff --git a/src/iceberg/data/arrow_batch_sizer_internal.h b/src/iceberg/data/arrow_batch_sizer_internal.h new file mode 100644 index 0000000000..9ec9eafa67 --- /dev/null +++ b/src/iceberg/data/arrow_batch_sizer_internal.h @@ -0,0 +1,72 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +#pragma once + +/// \file iceberg/data/arrow_batch_sizer_internal.h +/// Measures the Arrow buffer bytes that a batch occupies in a scan queue. + +#include +#include + +#include "iceberg/arrow_c_data.h" +#include "iceberg/iceberg_data_export.h" +#include "iceberg/result.h" + +namespace iceberg::internal { + +/// \brief Charges Arrow batches that share one physical schema. +/// +/// The charge is the checked sum of the spans of every present buffer in the root +/// array, its children, and its dictionaries, including variadic data buffers and +/// their size buffer. Each buffer occurrence is counted, even when several buffers +/// share a pointer, so a charge can overstate retained memory but never understates +/// the measured spans. +/// +/// Before any nanoarrow call that sizes buffers, Measure() checks that offsets and +/// lengths are nonnegative, that their sum and every layout-dependent buffer or +/// child-length product fit in `int64_t` and `size_t`, and that buffer, child, and +/// dictionary counts match the schema. Layouts whose spans nanoarrow cannot +/// determine (list views and run-end encoded arrays) are rejected. +/// +/// A sizer is not thread-safe; use one per thread. +class ICEBERG_DATA_EXPORT ArrowBatchSizer { + public: + /// \brief Create a sizer for batches described by `schema`. + /// + /// The schema is copied; the caller keeps ownership of `schema`. + static Result> Make(const ArrowSchema& schema); + + ~ArrowBatchSizer(); + + ArrowBatchSizer(const ArrowBatchSizer&) = delete; + ArrowBatchSizer& operator=(const ArrowBatchSizer&) = delete; + + /// \brief Return the charged bytes of `array`, or an error if it cannot be sized. + /// + /// `array` remains owned by the caller and is not modified. + Result Measure(const ArrowArray& array); + + private: + class Impl; + explicit ArrowBatchSizer(std::unique_ptr impl); + std::unique_ptr impl_; +}; + +} // namespace iceberg::internal diff --git a/src/iceberg/data/parallel_scan_reader.cc b/src/iceberg/data/parallel_scan_reader.cc new file mode 100644 index 0000000000..7c54bcc4a4 --- /dev/null +++ b/src/iceberg/data/parallel_scan_reader.cc @@ -0,0 +1,592 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +#include "iceberg/data/parallel_scan_reader.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "iceberg/arrow_c_data_guard_internal.h" +#include "iceberg/arrow_c_data_util_internal.h" +#include "iceberg/data/arrow_batch_sizer_internal.h" +#include "iceberg/data/parallel_scan_reader_internal.h" +#include "iceberg/file_reader.h" +#include "iceberg/manifest/manifest_entry.h" +#include "iceberg/nanoarrow_status_internal.h" +#include "iceberg/schema.h" +#include "iceberg/schema_internal.h" +#include "iceberg/util/macros.h" + +namespace iceberg { + +namespace internal { + +ParallelScanMetricsSnapshot ParallelScanMetrics::Snapshot() const { + std::lock_guard lock(mutex_); + return snapshot_; +} + +namespace { + +// Names a task in error messages, e.g. "data file s3://b/f.parquet [0, 1024)". +std::string DescribeTask(const FileScanTask& task) { + const auto& data_file = task.data_file(); + if (data_file == nullptr) { + return "task without a data file"; + } + if (!task.is_split()) { + return std::format("data file {}", data_file->file_path); + } + return std::format("data file {} [{}, {})", data_file->file_path, task.start(), + task.start() + task.length()); +} + +Error WithContext(const Error& error, std::string_view context) { + return Error{.kind = error.kind, + .message = std::format("{}: {}", context, error.message)}; +} + +std::string_view NullSafe(const char* value) { + return value == nullptr ? std::string_view{} : std::string_view{value}; +} + +// Compares the physical layout of two Arrow schemas. Field names, formats, +// nullability, children, and dictionaries must match; metadata is ignored and the +// root name is not compared. +Status CheckSameLayout(const ArrowSchema& expected, const ArrowSchema& actual, + const std::string& path, bool compare_name) { + if (NullSafe(expected.format) != NullSafe(actual.format)) { + return InvalidSchema("Field {} has Arrow format '{}', expected '{}'", path, + NullSafe(actual.format), NullSafe(expected.format)); + } + if (compare_name && NullSafe(expected.name) != NullSafe(actual.name)) { + return InvalidSchema("Field {} is named '{}', expected '{}'", path, + NullSafe(actual.name), NullSafe(expected.name)); + } + if ((expected.flags & ARROW_FLAG_NULLABLE) != (actual.flags & ARROW_FLAG_NULLABLE)) { + return InvalidSchema("Field {} nullability differs from the projected schema", path); + } + if (expected.n_children != actual.n_children) { + return InvalidSchema("Field {} has {} children, expected {}", path, actual.n_children, + expected.n_children); + } + for (int64_t index = 0; index < expected.n_children; ++index) { + const ArrowSchema* expected_child = expected.children[index]; + const ArrowSchema* actual_child = actual.children[index]; + if (actual_child == nullptr || expected_child == nullptr) { + return InvalidSchema("Field {} has a null child", path); + } + std::string child_path = std::format("{}.{}", path, NullSafe(expected_child->name)); + ICEBERG_RETURN_UNEXPECTED( + CheckSameLayout(*expected_child, *actual_child, child_path, true)); + } + if ((expected.dictionary == nullptr) != (actual.dictionary == nullptr)) { + return InvalidSchema("Field {} dictionary encoding differs from the projected schema", + path); + } + if (expected.dictionary != nullptr) { + ICEBERG_RETURN_UNEXPECTED(CheckSameLayout(*expected.dictionary, *actual.dictionary, + path + ".dictionary", false)); + } + return {}; +} + +// Releases an ArrowArrayStream on scope exit. +class StreamGuard { + public: + explicit StreamGuard(ArrowArrayStream* stream) : stream_(stream) {} + ~StreamGuard() { + if (stream_->release != nullptr) { + stream_->release(stream_); + } + } + StreamGuard(const StreamGuard&) = delete; + StreamGuard& operator=(const StreamGuard&) = delete; + + private: + ArrowArrayStream* stream_; +}; + +void ReleaseArray(ArrowArray* array) { + if (array->release != nullptr) { + array->release(array); + } +} + +struct QueuedBatch { + ArrowArray array; + int64_t charge; +}; + +void ReleaseAll(std::deque& batches) { + for (auto& batch : batches) { + ReleaseArray(&batch.array); + } + batches.clear(); +} + +// Shared state of one parallel read. All fields below `mutex_` are guarded by it. +// No planning or reader callback, Arrow release callback, thread join, or group +// stream destructor runs while `mutex_` is held. +class ParallelScan { + public: + ParallelScan(FileScanTaskGroupStreamPtr groups, ArrowSchema output_schema, + int64_t max_queued_batches, int64_t max_queued_bytes, + std::shared_ptr metrics) + : groups_(std::move(groups)), + output_schema_(output_schema), + max_queued_batches_(max_queued_batches), + max_queued_bytes_(max_queued_bytes), + metrics_(std::move(metrics)) {} + + ~ParallelScan() { + Shutdown(); + if (output_schema_.release != nullptr) { + output_schema_.release(&output_schema_); + } + } + + ParallelScan(const ParallelScan&) = delete; + ParallelScan& operator=(const ParallelScan&) = delete; + + Status Start(const FileScanTaskReader::Options& reader_options, int32_t worker_count) { + std::vector> readers; + std::vector> sizers; + readers.reserve(static_cast(worker_count)); + sizers.reserve(static_cast(worker_count)); + for (int32_t index = 0; index < worker_count; ++index) { + ICEBERG_ASSIGN_OR_RAISE(auto reader, FileScanTaskReader::Make(reader_options)); + ICEBERG_ASSIGN_OR_RAISE(auto sizer, ArrowBatchSizer::Make(output_schema_)); + readers.push_back(std::move(reader)); + sizers.push_back(std::move(sizer)); + } + + { + std::lock_guard lock(mutex_); + active_workers_ = worker_count; + } + workers_.reserve(static_cast(worker_count)); + for (int32_t index = 0; index < worker_count; ++index) { + try { + workers_.emplace_back([this, reader = std::move(readers[index]), + sizer = std::move(sizers[index])]() mutable { + WorkerMain(*reader, *sizer); + }); + } catch (const std::exception& e) { + // Threads that never started will not decrement the active count. + { + std::lock_guard lock(mutex_); + active_workers_ -= worker_count - index; + } + Shutdown(); + return UnknownError("Failed to start parallel scan worker: {}", e.what()); + } + } + return {}; + } + + // Consumer side of get_next. Not called concurrently with itself or Shutdown(). + Result> Next() { + std::unique_lock lock(mutex_); + consumer_cv_.wait(lock, [this] { + return error_.has_value() || !queue_.empty() || active_workers_ == 0; + }); + if (error_.has_value()) { + return unexpected(*error_); + } + if (queue_.empty()) { + return std::nullopt; + } + QueuedBatch batch = queue_.front(); + queue_.pop_front(); + queued_bytes_ -= batch.charge; + lock.unlock(); + // Producers are admitted in ticket order, and a condition variable cannot wake + // one specific waiter, so wake them all and let the head ticket re-check. At + // most worker_count threads wait here. + producer_cv_.notify_all(); + return batch.array; + } + + Result Schema() const { + ArrowSchema schema{}; + ICEBERG_NANOARROW_RETURN_UNEXPECTED(ArrowSchemaDeepCopy(&output_schema_, &schema)); + return schema; + } + + // Stops new work, joins workers, and releases every batch that was not returned. + // Idempotent. + void Shutdown() { + std::deque drained; + { + std::lock_guard lock(mutex_); + stopped_ = true; + drained.swap(queue_); + queued_bytes_ = 0; + } + planning_cv_.notify_all(); + producer_cv_.notify_all(); + consumer_cv_.notify_all(); + ReleaseAll(drained); + + for (auto& worker : workers_) { + if (worker.joinable()) { + worker.join(); + } + } + workers_.clear(); + + // Workers have exited, so nothing else can enqueue or plan. + { + std::lock_guard lock(mutex_); + drained.swap(queue_); + } + ReleaseAll(drained); + groups_.reset(); + } + + private: + void WorkerMain(FileScanTaskReader& reader, ArrowBatchSizer& sizer) { + Status status; + try { + status = RunWorker(reader, sizer); + } catch (const std::exception& e) { + status = UnknownError("Parallel scan worker failed: {}", e.what()); + } catch (...) { + status = UnknownError("Parallel scan worker failed with an unknown exception"); + } + if (!status.has_value()) { + Fail(status.error()); + } + { + std::lock_guard lock(mutex_); + --active_workers_; + } + consumer_cv_.notify_all(); + } + + Status RunWorker(FileScanTaskReader& reader, ArrowBatchSizer& sizer) { + while (true) { + ICEBERG_ASSIGN_OR_RAISE(auto group, ClaimGroup()); + if (group == nullptr) { + return {}; + } + for (const auto& task : group->tasks()) { + if (IsStopped()) { + return {}; + } + if (task == nullptr) { + return InvalidArgument("Task group contains a null task"); + } + ICEBERG_RETURN_UNEXPECTED(ReadTask(reader, sizer, *task)); + } + } + } + + // Returns the next group, or nullptr when planning is exhausted or the read stopped. + // Only one worker calls the group stream at a time, outside all locks. + Result> ClaimGroup() { + { + std::unique_lock lock(mutex_); + planning_cv_.wait(lock, [this] { return stopped_ || !planning_in_progress_; }); + if (stopped_ || planning_done_) { + return nullptr; + } + planning_in_progress_ = true; + } + + Result>> next = std::nullopt; + try { + next = groups_->Next(); + } catch (const std::exception& e) { + next = UnknownError("Planning task groups failed: {}", e.what()); + } catch (...) { + next = UnknownError("Planning task groups failed with an unknown exception"); + } + + const bool finished = !next.has_value() || !next.value().has_value(); + if (finished) { + // This worker still holds the planning token, so no other worker uses the + // stream. Destroy it now, outside locks, so metrics reporting runs at EOF. + groups_.reset(); + } + + { + std::lock_guard lock(mutex_); + planning_in_progress_ = false; + if (finished) { + planning_done_ = true; + } + } + planning_cv_.notify_all(); + + if (!next.has_value()) { + return unexpected(WithContext(next.error(), "Failed to plan task groups")); + } + if (!next.value().has_value()) { + return nullptr; + } + auto group = std::move(next.value().value()); + if (group == nullptr) { + return InvalidArgument("Task group stream returned a null group"); + } + if (metrics_ != nullptr) { + metrics_->Update([](auto& snapshot) { ++snapshot.groups_claimed; }); + } + return group; + } + + Status ReadTask(FileScanTaskReader& reader, ArrowBatchSizer& sizer, + const FileScanTask& task) { + const std::string context = DescribeTask(task); + auto opened = reader.Open(task); + if (!opened.has_value()) { + return unexpected(WithContext(opened.error(), "Failed to open " + context)); + } + ArrowArrayStream stream = std::move(opened.value()); + StreamGuard stream_guard(&stream); + if (metrics_ != nullptr) { + metrics_->Update([](auto& snapshot) { ++snapshot.tasks_opened; }); + } + + auto last_error = [&stream]() { + const char* message = stream.get_last_error(&stream); + return message == nullptr ? std::string("unknown error") : std::string(message); + }; + + ArrowSchema task_schema{}; + if (int code = stream.get_schema(&stream, &task_schema); code != 0) { + return IOError("Failed to read the schema of {} (code {}): {}", context, code, + last_error()); + } + internal::ArrowSchemaGuard task_schema_guard(&task_schema); + if (auto status = CheckSameLayout(output_schema_, task_schema, "root", false); + !status.has_value()) { + return unexpected(WithContext( + status.error(), + "Task stream schema does not match the projected schema for " + context)); + } + + // Enqueue() reports a stop, so no separate check is needed per batch. + while (true) { + ArrowArray batch{}; + if (int code = stream.get_next(&stream, &batch); code != 0) { + return IOError("Failed to read {} (code {}): {}", context, code, last_error()); + } + if (batch.release == nullptr) { + return {}; + } + auto charge = sizer.Measure(batch); + if (!charge.has_value()) { + ReleaseArray(&batch); + return unexpected( + WithContext(charge.error(), "Failed to size a batch of " + context)); + } + if (!Enqueue(batch, charge.value())) { + // Stopped while waiting; the array was not admitted. + ReleaseArray(&batch); + return {}; + } + } + } + + // Blocks until the batch is admitted in FIFO order or the read stops. Returns + // false when stopped, in which case the caller still owns `batch`. + bool Enqueue(const ArrowArray& batch, int64_t charge) { + const auto wait_start = std::chrono::steady_clock::now(); + std::unique_lock lock(mutex_); + const uint64_t ticket = next_ticket_++; + held_bytes_ += charge; + RecordMetrics([this](auto& snapshot) { + snapshot.peak_held_bytes = std::max(snapshot.peak_held_bytes, held_bytes_); + }); + + producer_cv_.wait(lock, [&] { + return stopped_ || (ticket == serving_ticket_ && CanAdmit(charge)); + }); + held_bytes_ -= charge; + const auto waited = std::chrono::steady_clock::now() - wait_start; + if (stopped_) { + RecordMetrics([&](auto& snapshot) { snapshot.producer_wait += waited; }); + return false; + } + + const bool oversized = charge > max_queued_bytes_; + queue_.push_back(QueuedBatch{.array = batch, .charge = charge}); + queued_bytes_ += charge; + ++serving_ticket_; + RecordMetrics([&](auto& snapshot) { + snapshot.producer_wait += waited; + ++snapshot.batches_admitted; + snapshot.bytes_admitted += charge; + if (oversized) { + ++snapshot.oversized_admissions; + } + snapshot.peak_queued_batches = + std::max(snapshot.peak_queued_batches, static_cast(queue_.size())); + snapshot.peak_queued_bytes = std::max(snapshot.peak_queued_bytes, queued_bytes_); + }); + lock.unlock(); + producer_cv_.notify_all(); + consumer_cv_.notify_one(); + return true; + } + + // Requires `mutex_`. + bool CanAdmit(int64_t charge) const { + if (static_cast(queue_.size()) >= max_queued_batches_) { + return false; + } + if (charge > max_queued_bytes_) { + // An oversized batch enters only as the sole queued batch. + return queue_.empty(); + } + return queued_bytes_ <= max_queued_bytes_ - charge; + } + + // Requires `mutex_`; the metrics lock is always taken after it. + template + void RecordMetrics(Update&& update) { + if (metrics_ != nullptr) { + metrics_->Update(std::forward(update)); + } + } + + bool IsStopped() { + std::lock_guard lock(mutex_); + return stopped_; + } + + // Records the first error, stops new work, and releases queued batches. + void Fail(const Error& error) { + std::deque drained; + { + std::lock_guard lock(mutex_); + if (!error_.has_value()) { + error_ = error; + } + stopped_ = true; + drained.swap(queue_); + queued_bytes_ = 0; + } + planning_cv_.notify_all(); + producer_cv_.notify_all(); + consumer_cv_.notify_all(); + ReleaseAll(drained); + } + + // Only touched by the worker holding the planning token, or after all workers + // have joined. + FileScanTaskGroupStreamPtr groups_; + ArrowSchema output_schema_; + const int64_t max_queued_batches_; + const int64_t max_queued_bytes_; + std::shared_ptr metrics_; + std::vector workers_; + + std::mutex mutex_; + std::condition_variable planning_cv_; + std::condition_variable producer_cv_; + std::condition_variable consumer_cv_; + bool stopped_ = false; + bool planning_in_progress_ = false; + bool planning_done_ = false; + int32_t active_workers_ = 0; + std::optional error_; + std::deque queue_; + int64_t queued_bytes_ = 0; + int64_t held_bytes_ = 0; + uint64_t next_ticket_ = 0; + uint64_t serving_ticket_ = 0; +}; + +// Adapts ParallelScan to the ArrowArrayStream provider interface. +class ParallelScanSource { + public: + explicit ParallelScanSource(std::unique_ptr scan) + : scan_(std::move(scan)) {} + + Status Close() { + scan_->Shutdown(); + return {}; + } + + Result> Next() { return scan_->Next(); } + + Result Schema() { return scan_->Schema(); } + + private: + std::unique_ptr scan_; +}; + +} // namespace + +Result OpenParallelScan(FileScanTaskGroupStreamPtr groups, + ParallelScanReader::Options options, + std::shared_ptr metrics) { + ICEBERG_PRECHECK(groups != nullptr, "Task group stream must not be null"); + ICEBERG_PRECHECK(options.worker_count > 0, "Worker count must be positive: {}", + options.worker_count); + ICEBERG_PRECHECK(options.max_queued_batches > 0, + "Maximum queued batches must be positive: {}", + options.max_queued_batches); + ICEBERG_PRECHECK(options.max_queued_bytes > 0, + "Maximum queued bytes must be positive: {}", options.max_queued_bytes); + ICEBERG_PRECHECK(options.reader_options.projected_schema != nullptr, + "Projected schema must not be null"); + + options.reader_options.apply_residuals = true; + const auto properties = ReaderProperties::FromMap(options.reader_options.properties); + + ArrowSchema output_schema{}; + ICEBERG_RETURN_UNEXPECTED( + ToArrowSchema(*options.reader_options.projected_schema, &output_schema, + properties.Get(ReaderProperties::kArrowUseLargeList))); + + auto scan = std::make_unique( + std::move(groups), output_schema, options.max_queued_batches, + options.max_queued_bytes, std::move(metrics)); + ICEBERG_RETURN_UNEXPECTED(scan->Start(options.reader_options, options.worker_count)); + return MakeArrowArrayStream(std::make_unique(std::move(scan))); +} + +} // namespace internal + +Result ParallelScanReader::Open(FileScanTaskGroupStreamPtr groups, + Options options) { + return internal::OpenParallelScan(std::move(groups), std::move(options), + /*metrics=*/nullptr); +} + +} // namespace iceberg diff --git a/src/iceberg/data/parallel_scan_reader.h b/src/iceberg/data/parallel_scan_reader.h new file mode 100644 index 0000000000..92ef5b5aca --- /dev/null +++ b/src/iceberg/data/parallel_scan_reader.h @@ -0,0 +1,104 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +#pragma once + +/// \file iceberg/data/parallel_scan_reader.h +/// Reads planned FileScanTaskGroups concurrently into one Arrow stream. + +#include + +#include "iceberg/arrow_c_data.h" +#include "iceberg/data/file_scan_task_reader.h" +#include "iceberg/iceberg_data_export.h" +#include "iceberg/result.h" +#include "iceberg/table_scan.h" + +namespace iceberg { + +/// \brief Reads the groups of a FileScanTaskGroupStream with a fixed set of workers. +/// +/// Each worker owns its own FileScanTaskReader. Workers take groups from the +/// single-pass group stream one at a time, read the tasks within a group in order, +/// and place each completed batch into an output queue bounded by batch count and +/// by charged bytes. The caller receives one Arrow C stream that yields batches as +/// workers admit them. +/// +/// Output order across groups and tasks is unspecified; the batches of one task keep +/// their order relative to each other. Every batch matches the projected schema. +/// +/// Residual filters are always enforced: `apply_residuals` in the reader options is +/// forced on. `reader_options.case_sensitive` must match the planning scan's +/// `TableScan::is_case_sensitive()`, because task residuals are unbound and groups do +/// not carry that setting. +/// +/// Queue memory: `max_queued_bytes` limits admission using the summed spans of the +/// Arrow buffers of queued batches, counting every buffer occurrence. A batch larger +/// than the budget is admitted only when the queue is empty, as its sole batch. +/// Zero-byte batches still count toward `max_queued_batches`. This is not a limit +/// on process memory: format reader buffers, delete indexes, allocator overhead, and +/// arrays already returned to the caller are outside the budget. Each worker can also +/// hold one completed batch while it waits for admission. Per worker, expect roughly +/// one open format reader with its read buffers, one task's delete index, and one +/// completed batch, in addition to the queue budget. +/// +/// Preconditions, which the reader cannot check: +/// - Format reader factories are registered before Open() and are not changed until +/// the returned stream is released. +/// - `reader_options.io` supports concurrent reads from several threads. +/// - Tasks and their shared data and delete file metadata are not mutated while the +/// stream is in use. +/// - Any executor passed to `TableScanBuilder::PlanWith()` outlives the returned +/// stream, which owns the lazy group stream. +/// +/// Stream callbacks follow the Arrow C stream contract: they must not be called +/// concurrently, and `release` must not race with `get_next`, `get_schema`, or +/// `get_last_error`. Releasing the stream between callbacks stops assigning work, +/// wakes waiting workers, releases batches that were not returned, and joins the +/// workers. A planning call or read that is already in progress finishes first. +/// Cancelling a `get_next` that is blocked on another thread is not supported. +/// +/// When planning, reading, schema checking, or batch sizing fails, the reader stops +/// assigning work, releases queued batches, and reports the first error from the +/// next `get_next` call as `EIO`, with a message that names the file and byte range +/// available from `get_last_error`. Arrays already returned to the caller remain +/// valid after the stream is released. +class ICEBERG_DATA_EXPORT ParallelScanReader { + public: + /// \brief Options for one parallel read. + struct Options { + /// Options for the per-worker task readers. `apply_residuals` is forced on. + FileScanTaskReader::Options reader_options; + /// Number of worker threads. Must be positive. + int32_t worker_count = 0; + /// Maximum number of batches waiting in the output queue. Must be positive. + int64_t max_queued_batches = 0; + /// Target for the charged bytes of batches waiting in the output queue. Must be + /// positive. + int64_t max_queued_bytes = 0; + }; + + /// \brief Start reading `groups` and return a stream of their projected live rows. + /// + /// The returned stream owns `groups`. Workers start before Open() returns. + static Result Open(FileScanTaskGroupStreamPtr groups, + Options options); +}; + +} // namespace iceberg diff --git a/src/iceberg/data/parallel_scan_reader_internal.h b/src/iceberg/data/parallel_scan_reader_internal.h new file mode 100644 index 0000000000..d9f318e039 --- /dev/null +++ b/src/iceberg/data/parallel_scan_reader_internal.h @@ -0,0 +1,87 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +#pragma once + +/// \file iceberg/data/parallel_scan_reader_internal.h +/// Queue and producer metrics for ParallelScanReader. Not a stable API. + +#include +#include +#include +#include + +#include "iceberg/arrow_c_data.h" +#include "iceberg/data/parallel_scan_reader.h" +#include "iceberg/iceberg_data_export.h" +#include "iceberg/result.h" + +namespace iceberg::internal { + +/// \brief A point-in-time copy of a parallel read's queue and producer counters. +struct ParallelScanMetricsSnapshot { + /// Groups taken from the group stream. + int64_t groups_claimed = 0; + /// Tasks opened by workers. + int64_t tasks_opened = 0; + /// Batches admitted to the output queue. + int64_t batches_admitted = 0; + /// Charged bytes of all admitted batches. + int64_t bytes_admitted = 0; + /// Batches admitted although their charge exceeded `max_queued_bytes`. + int64_t oversized_admissions = 0; + /// Peak number of batches in the output queue. + int64_t peak_queued_batches = 0; + /// Peak charged bytes in the output queue. + int64_t peak_queued_bytes = 0; + /// Peak charged bytes of completed batches that workers held while waiting. + int64_t peak_held_bytes = 0; + /// Total time that workers waited for admission. + std::chrono::nanoseconds producer_wait{0}; +}; + +/// \brief Thread-safe counters shared between a parallel read and its observers. +/// +/// Snapshot() takes only this object's lock, so it may be called from any thread, +/// including from a group stream destructor or a metrics reporter. +class ICEBERG_DATA_EXPORT ParallelScanMetrics { + public: + /// \brief Return a copy of the current counters. + ParallelScanMetricsSnapshot Snapshot() const; + + /// \brief Apply `update` to the counters under this object's lock. + template + void Update(Update&& update) { + std::lock_guard lock(mutex_); + update(snapshot_); + } + + private: + mutable std::mutex mutex_; + ParallelScanMetricsSnapshot snapshot_; +}; + +/// \brief Same as ParallelScanReader::Open(), also returning live metrics. +/// +/// `metrics` may be retained after the stream is released. +ICEBERG_DATA_EXPORT Result OpenParallelScan( + FileScanTaskGroupStreamPtr groups, ParallelScanReader::Options options, + std::shared_ptr metrics); + +} // namespace iceberg::internal diff --git a/src/iceberg/test/CMakeLists.txt b/src/iceberg/test/CMakeLists.txt index a6f3d8ba12..825608245b 100644 --- a/src/iceberg/test/CMakeLists.txt +++ b/src/iceberg/test/CMakeLists.txt @@ -197,6 +197,13 @@ add_iceberg_test(util_test uuid_test.cc visit_type_test.cc) +# Parallel scan reader tests use fake readers and do not need the bundle. +add_iceberg_test(parallel_scan_test + USE_DATA + SOURCES + arrow_batch_sizer_test.cc + parallel_scan_reader_test.cc) + add_iceberg_test(puffin_test USE_DATA SOURCES diff --git a/src/iceberg/test/arrow_batch_sizer_test.cc b/src/iceberg/test/arrow_batch_sizer_test.cc new file mode 100644 index 0000000000..88c638b8b8 --- /dev/null +++ b/src/iceberg/test/arrow_batch_sizer_test.cc @@ -0,0 +1,372 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +#include +#include +#include +#include + +#include +#include + +#include "iceberg/data/arrow_batch_sizer_internal.h" +#include "iceberg/test/matchers.h" + +namespace iceberg::internal { + +namespace { + +// Owns a schema and an array built with nanoarrow. +struct OwnedBatch { + ArrowSchema schema{}; + ArrowArray array{}; + + OwnedBatch() = default; + OwnedBatch(const OwnedBatch&) = delete; + OwnedBatch& operator=(const OwnedBatch&) = delete; + ~OwnedBatch() { + if (array.release != nullptr) { + array.release(&array); + } + if (schema.release != nullptr) { + schema.release(&schema); + } + } +}; + +void InitPrimitive(OwnedBatch& batch, ArrowType type) { + ASSERT_EQ(ArrowSchemaInitFromType(&batch.schema, type), NANOARROW_OK); + ASSERT_EQ(ArrowArrayInitFromSchema(&batch.array, &batch.schema, nullptr), NANOARROW_OK); + ASSERT_EQ(ArrowArrayStartAppending(&batch.array), NANOARROW_OK); +} + +void Finish(OwnedBatch& batch) { + ASSERT_EQ(ArrowArrayFinishBuildingDefault(&batch.array, nullptr), NANOARROW_OK); +} + +Result Measure(const OwnedBatch& batch) { + ICEBERG_ASSIGN_OR_RAISE(auto sizer, ArrowBatchSizer::Make(batch.schema)); + return sizer->Measure(batch.array); +} + +// A release callback for hand-built arrays whose members are not heap allocated. +void ReleaseNothing(ArrowArray* array) { array->release = nullptr; } + +} // namespace + +TEST(ArrowBatchSizerTest, FixedWidthWithAndWithoutNulls) { + OwnedBatch no_nulls; + InitPrimitive(no_nulls, NANOARROW_TYPE_INT32); + for (int32_t value = 0; value < 10; ++value) { + ASSERT_EQ(ArrowArrayAppendInt(&no_nulls.array, value), NANOARROW_OK); + } + Finish(no_nulls); + // nanoarrow omits the validity buffer when there are no nulls. + EXPECT_THAT(Measure(no_nulls), HasValue(::testing::Eq(40))); + + OwnedBatch with_nulls; + InitPrimitive(with_nulls, NANOARROW_TYPE_INT32); + for (int32_t value = 0; value < 10; ++value) { + ASSERT_EQ(ArrowArrayAppendInt(&with_nulls.array, value), NANOARROW_OK); + } + ASSERT_EQ(ArrowArrayAppendNull(&with_nulls.array, 1), NANOARROW_OK); + Finish(with_nulls); + // 11 values: 2 validity bytes and 44 data bytes. + EXPECT_THAT(Measure(with_nulls), HasValue(::testing::Eq(2 + 44))); +} + +TEST(ArrowBatchSizerTest, SlicedArrayCountsBuffersFromZero) { + OwnedBatch batch; + InitPrimitive(batch, NANOARROW_TYPE_INT64); + for (int64_t value = 0; value < 8; ++value) { + ASSERT_EQ(ArrowArrayAppendInt(&batch.array, value), NANOARROW_OK); + } + Finish(batch); + batch.array.offset = 3; + batch.array.length = 5; + EXPECT_THAT(Measure(batch), HasValue(::testing::Eq(64))); +} + +TEST(ArrowBatchSizerTest, VariableWidth) { + OwnedBatch batch; + InitPrimitive(batch, NANOARROW_TYPE_STRING); + ASSERT_EQ(ArrowArrayAppendString(&batch.array, ArrowCharView("abc")), NANOARROW_OK); + ASSERT_EQ(ArrowArrayAppendString(&batch.array, ArrowCharView("")), NANOARROW_OK); + ASSERT_EQ(ArrowArrayAppendString(&batch.array, ArrowCharView("hello")), NANOARROW_OK); + Finish(batch); + // 4 offsets of 4 bytes, then 8 data bytes. + EXPECT_THAT(Measure(batch), HasValue(::testing::Eq(16 + 8))); +} + +TEST(ArrowBatchSizerTest, NestedStructAndList) { + OwnedBatch batch; + ASSERT_EQ(ArrowSchemaInitFromType(&batch.schema, NANOARROW_TYPE_STRUCT), NANOARROW_OK); + ASSERT_EQ(ArrowSchemaAllocateChildren(&batch.schema, 2), NANOARROW_OK); + ASSERT_EQ(ArrowSchemaInitFromType(batch.schema.children[0], NANOARROW_TYPE_INT32), + NANOARROW_OK); + ASSERT_EQ(ArrowSchemaSetName(batch.schema.children[0], "id"), NANOARROW_OK); + ASSERT_EQ(ArrowSchemaInitFromType(batch.schema.children[1], NANOARROW_TYPE_LIST), + NANOARROW_OK); + ASSERT_EQ(ArrowSchemaSetName(batch.schema.children[1], "values"), NANOARROW_OK); + ASSERT_EQ( + ArrowSchemaSetType(batch.schema.children[1]->children[0], NANOARROW_TYPE_INT16), + NANOARROW_OK); + ASSERT_EQ(ArrowArrayInitFromSchema(&batch.array, &batch.schema, nullptr), NANOARROW_OK); + ASSERT_EQ(ArrowArrayStartAppending(&batch.array), NANOARROW_OK); + + ArrowArray* ids = batch.array.children[0]; + ArrowArray* lists = batch.array.children[1]; + for (int32_t row = 0; row < 3; ++row) { + ASSERT_EQ(ArrowArrayAppendInt(ids, row), NANOARROW_OK); + for (int32_t element = 0; element <= row; ++element) { + ASSERT_EQ(ArrowArrayAppendInt(lists->children[0], element), NANOARROW_OK); + } + ASSERT_EQ(ArrowArrayFinishElement(lists), NANOARROW_OK); + ASSERT_EQ(ArrowArrayFinishElement(&batch.array), NANOARROW_OK); + } + Finish(batch); + // ids: 12 bytes. list offsets: 4 * 4 bytes. list values: 6 int16 = 12 bytes. + EXPECT_THAT(Measure(batch), HasValue(::testing::Eq(12 + 16 + 12))); +} + +TEST(ArrowBatchSizerTest, ZeroColumnStructIsZeroBytes) { + OwnedBatch batch; + ASSERT_EQ(ArrowSchemaInitFromType(&batch.schema, NANOARROW_TYPE_STRUCT), NANOARROW_OK); + ASSERT_EQ(ArrowSchemaAllocateChildren(&batch.schema, 0), NANOARROW_OK); + ASSERT_EQ(ArrowArrayInitFromSchema(&batch.array, &batch.schema, nullptr), NANOARROW_OK); + ASSERT_EQ(ArrowArrayStartAppending(&batch.array), NANOARROW_OK); + for (int row = 0; row < 7; ++row) { + ASSERT_EQ(ArrowArrayFinishElement(&batch.array), NANOARROW_OK); + } + Finish(batch); + ASSERT_EQ(batch.array.length, 7); + EXPECT_THAT(Measure(batch), HasValue(::testing::Eq(0))); +} + +TEST(ArrowBatchSizerTest, DictionaryIsCharged) { + OwnedBatch batch; + ASSERT_EQ(ArrowSchemaInitFromType(&batch.schema, NANOARROW_TYPE_INT8), NANOARROW_OK); + ASSERT_EQ(ArrowSchemaAllocateDictionary(&batch.schema), NANOARROW_OK); + ASSERT_EQ(ArrowSchemaInitFromType(batch.schema.dictionary, NANOARROW_TYPE_STRING), + NANOARROW_OK); + ASSERT_EQ(ArrowArrayInitFromSchema(&batch.array, &batch.schema, nullptr), NANOARROW_OK); + // Starting the indices also starts the dictionary. + ASSERT_EQ(ArrowArrayStartAppending(&batch.array), NANOARROW_OK); + ASSERT_EQ(ArrowArrayAppendString(batch.array.dictionary, ArrowCharView("red")), + NANOARROW_OK); + ASSERT_EQ(ArrowArrayAppendString(batch.array.dictionary, ArrowCharView("blue")), + NANOARROW_OK); + for (int index : {0, 1, 1, 0}) { + ASSERT_EQ(ArrowArrayAppendInt(&batch.array, index), NANOARROW_OK); + } + Finish(batch); + // Indices: 4 bytes. Dictionary: 3 offsets * 4 bytes + 7 data bytes. + EXPECT_THAT(Measure(batch), HasValue(::testing::Eq(4 + 12 + 7))); +} + +TEST(ArrowBatchSizerTest, StringViewChargesVariadicBuffers) { + OwnedBatch batch; + InitPrimitive(batch, NANOARROW_TYPE_STRING_VIEW); + // Strings of at most 12 bytes are inlined in the view. + ASSERT_EQ(ArrowArrayAppendString(&batch.array, ArrowCharView("short")), NANOARROW_OK); + const std::string long_value(40, 'x'); + ASSERT_EQ(ArrowArrayAppendString(&batch.array, ArrowCharView(long_value.c_str())), + NANOARROW_OK); + Finish(batch); + ASSERT_GE(batch.array.n_buffers, 3); + const int64_t variadic_buffers = batch.array.n_buffers - 3; + ASSERT_EQ(variadic_buffers, 1); + // Two 16-byte views, one 40-byte variadic buffer, and one 8-byte size entry. + EXPECT_THAT(Measure(batch), HasValue(::testing::Eq(32 + 40 + 8))); +} + +TEST(ArrowBatchSizerTest, ListViewIsUnsupported) { + OwnedBatch batch; + ASSERT_EQ(ArrowSchemaInitFromType(&batch.schema, NANOARROW_TYPE_LIST_VIEW), + NANOARROW_OK); + ASSERT_EQ(ArrowSchemaSetType(batch.schema.children[0], NANOARROW_TYPE_INT32), + NANOARROW_OK); + ASSERT_EQ(ArrowArrayInitFromSchema(&batch.array, &batch.schema, nullptr), NANOARROW_OK); + ASSERT_EQ(ArrowArrayStartAppending(&batch.array), NANOARROW_OK); + Finish(batch); + EXPECT_THAT(Measure(batch), IsError(ErrorKind::kNotSupported)); +} + +TEST(ArrowBatchSizerTest, RejectsNegativeLengthAndOffset) { + OwnedBatch batch; + InitPrimitive(batch, NANOARROW_TYPE_INT32); + Finish(batch); + batch.array.length = -1; + EXPECT_THAT(Measure(batch), IsError(ErrorKind::kInvalidArrowData)); + batch.array.length = 0; + batch.array.offset = -1; + EXPECT_THAT(Measure(batch), IsError(ErrorKind::kInvalidArrowData)); + batch.array.offset = 0; +} + +TEST(ArrowBatchSizerTest, RejectsOverflowBeforeSizingBuffers) { + ArrowSchema schema{}; + ASSERT_EQ(ArrowSchemaInitFromType(&schema, NANOARROW_TYPE_INT64), NANOARROW_OK); + ICEBERG_UNWRAP_OR_FAIL(auto sizer, ArrowBatchSizer::Make(schema)); + schema.release(&schema); + + // The buffers are never dereferenced: the size checks fail first. + const void* buffers[2] = {nullptr, nullptr}; + ArrowArray array{}; + array.n_buffers = 2; + array.buffers = buffers; + array.release = ReleaseNothing; + + // offset + length overflows. + array.offset = std::numeric_limits::max(); + array.length = 1; + EXPECT_THAT(sizer->Measure(array), IsError(ErrorKind::kInvalidArrowData)); + + // (offset + length) * 64 bits overflows. + array.offset = 0; + array.length = std::numeric_limits::max() / 8; + EXPECT_THAT(sizer->Measure(array), IsError(ErrorKind::kInvalidArrowData)); +} + +TEST(ArrowBatchSizerTest, RejectsOffsetBufferOverflow) { + ArrowSchema schema{}; + ASSERT_EQ(ArrowSchemaInitFromType(&schema, NANOARROW_TYPE_LARGE_STRING), NANOARROW_OK); + ICEBERG_UNWRAP_OR_FAIL(auto sizer, ArrowBatchSizer::Make(schema)); + schema.release(&schema); + + const void* buffers[3] = {nullptr, nullptr, nullptr}; + ArrowArray array{}; + array.n_buffers = 3; + array.buffers = buffers; + array.release = ReleaseNothing; + // (length + 1) * 8 offset bytes overflows. + array.length = std::numeric_limits::max() / 8; + EXPECT_THAT(sizer->Measure(array), IsError(ErrorKind::kInvalidArrowData)); +} + +TEST(ArrowBatchSizerTest, RejectsFixedSizeListChildLengthOverflow) { + ArrowSchema schema{}; + ArrowSchemaInit(&schema); + ASSERT_EQ(ArrowSchemaSetTypeFixedSize(&schema, NANOARROW_TYPE_FIXED_SIZE_LIST, 1 << 20), + NANOARROW_OK); + ASSERT_EQ(ArrowSchemaSetType(schema.children[0], NANOARROW_TYPE_INT8), NANOARROW_OK); + ICEBERG_UNWRAP_OR_FAIL(auto sizer, ArrowBatchSizer::Make(schema)); + schema.release(&schema); + + const void* child_buffers[2] = {nullptr, nullptr}; + ArrowArray child{}; + child.n_buffers = 2; + child.buffers = child_buffers; + child.release = ReleaseNothing; + ArrowArray* children[1] = {&child}; + + const void* buffers[1] = {nullptr}; + ArrowArray array{}; + array.n_buffers = 1; + array.buffers = buffers; + array.n_children = 1; + array.children = children; + array.release = ReleaseNothing; + // length * 2^20 child elements overflows. + array.length = std::numeric_limits::max() / 1024; + EXPECT_THAT(sizer->Measure(array), IsError(ErrorKind::kInvalidArrowData)); +} + +TEST(ArrowBatchSizerTest, RejectsMismatchedBufferAndChildCounts) { + OwnedBatch batch; + InitPrimitive(batch, NANOARROW_TYPE_STRING); + Finish(batch); + const int64_t buffers = batch.array.n_buffers; + batch.array.n_buffers = 2; + EXPECT_THAT(Measure(batch), IsError(ErrorKind::kInvalidArrowData)); + batch.array.n_buffers = buffers; + + const int64_t children = batch.array.n_children; + batch.array.n_children = 1; + EXPECT_THAT(Measure(batch), IsError(ErrorKind::kInvalidArrowData)); + batch.array.n_children = children; +} + +TEST(ArrowBatchSizerTest, RejectsBinaryViewWithoutSizeBuffer) { + OwnedBatch batch; + InitPrimitive(batch, NANOARROW_TYPE_BINARY_VIEW); + Finish(batch); + const int64_t buffers = batch.array.n_buffers; + // Two buffers would make nanoarrow read the view buffer as variadic sizes. + batch.array.n_buffers = 2; + EXPECT_THAT(Measure(batch), IsError(ErrorKind::kInvalidArrowData)); + batch.array.n_buffers = buffers; +} + +TEST(ArrowBatchSizerTest, ChildrenNeedNoReleaseCallback) { + OwnedBatch batch; + ASSERT_EQ(ArrowSchemaInitFromType(&batch.schema, NANOARROW_TYPE_STRUCT), NANOARROW_OK); + ASSERT_EQ(ArrowSchemaAllocateChildren(&batch.schema, 1), NANOARROW_OK); + ASSERT_EQ(ArrowSchemaInitFromType(batch.schema.children[0], NANOARROW_TYPE_INT32), + NANOARROW_OK); + ASSERT_EQ(ArrowArrayInitFromSchema(&batch.array, &batch.schema, nullptr), NANOARROW_OK); + ASSERT_EQ(ArrowArrayStartAppending(&batch.array), NANOARROW_OK); + ASSERT_EQ(ArrowArrayAppendInt(batch.array.children[0], 7), NANOARROW_OK); + ASSERT_EQ(ArrowArrayFinishElement(&batch.array), NANOARROW_OK); + Finish(batch); + + ICEBERG_UNWRAP_OR_FAIL(auto sizer, ArrowBatchSizer::Make(batch.schema)); + // Only the root's release callback is required; parents release their children. + auto child_release = batch.array.children[0]->release; + batch.array.children[0]->release = nullptr; + EXPECT_THAT(sizer->Measure(batch.array), HasValue(::testing::Eq(4))); + batch.array.children[0]->release = child_release; +} + +TEST(ArrowBatchSizerTest, ErrorsNameTheNestedArray) { + OwnedBatch batch; + ASSERT_EQ(ArrowSchemaInitFromType(&batch.schema, NANOARROW_TYPE_STRUCT), NANOARROW_OK); + ASSERT_EQ(ArrowSchemaAllocateChildren(&batch.schema, 2), NANOARROW_OK); + for (int index = 0; index < 2; ++index) { + ASSERT_EQ(ArrowSchemaInitFromType(batch.schema.children[index], NANOARROW_TYPE_INT32), + NANOARROW_OK); + } + ASSERT_EQ(ArrowArrayInitFromSchema(&batch.array, &batch.schema, nullptr), NANOARROW_OK); + ASSERT_EQ(ArrowArrayStartAppending(&batch.array), NANOARROW_OK); + Finish(batch); + batch.array.children[1]->length = -1; + EXPECT_THAT(Measure(batch), HasErrorMessage("root.1")); + batch.array.children[1]->length = 0; +} + +TEST(ArrowBatchSizerTest, ReusesSizerAcrossBatches) { + OwnedBatch first; + InitPrimitive(first, NANOARROW_TYPE_INT32); + ASSERT_EQ(ArrowArrayAppendInt(&first.array, 1), NANOARROW_OK); + Finish(first); + + OwnedBatch second; + InitPrimitive(second, NANOARROW_TYPE_INT32); + for (int32_t value = 0; value < 100; ++value) { + ASSERT_EQ(ArrowArrayAppendInt(&second.array, value), NANOARROW_OK); + } + Finish(second); + + ICEBERG_UNWRAP_OR_FAIL(auto sizer, ArrowBatchSizer::Make(first.schema)); + EXPECT_THAT(sizer->Measure(first.array), HasValue(::testing::Eq(4))); + EXPECT_THAT(sizer->Measure(second.array), HasValue(::testing::Eq(400))); + EXPECT_THAT(sizer->Measure(first.array), HasValue(::testing::Eq(4))); +} + +} // namespace iceberg::internal diff --git a/src/iceberg/test/parallel_scan_reader_test.cc b/src/iceberg/test/parallel_scan_reader_test.cc new file mode 100644 index 0000000000..0bb7f9f2a8 --- /dev/null +++ b/src/iceberg/test/parallel_scan_reader_test.cc @@ -0,0 +1,886 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +#include "iceberg/data/parallel_scan_reader.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include "iceberg/data/parallel_scan_reader_internal.h" +#include "iceberg/expression/expressions.h" +#include "iceberg/expression/literal.h" +#include "iceberg/file_format.h" +#include "iceberg/file_reader.h" +#include "iceberg/manifest/manifest_entry.h" +#include "iceberg/schema.h" +#include "iceberg/schema_field.h" +#include "iceberg/schema_internal.h" +#include "iceberg/table_scan.h" +#include "iceberg/test/matchers.h" +#include "iceberg/test/mock_io.h" +#include "iceberg/type.h" + +namespace iceberg { + +namespace { + +using internal::OpenParallelScan; +using internal::ParallelScanMetrics; +using internal::ParallelScanMetricsSnapshot; +using ::testing::ElementsAreArray; +using ::testing::HasSubstr; +using ::testing::UnorderedElementsAreArray; + +constexpr int32_t kIdFieldId = 1; +constexpr int32_t kNameFieldId = 2; + +// Counts the root arrays created by fake readers that have not been released yet. +std::atomic g_live_arrays{0}; + +struct TrackedArray { + ArrowArray inner; +}; + +void ReleaseTracked(ArrowArray* array) { + auto* tracked = static_cast(array->private_data); + tracked->inner.release(&tracked->inner); + delete tracked; + array->release = nullptr; + g_live_arrays.fetch_sub(1); +} + +// Moves `array` behind a release callback that updates g_live_arrays. +ArrowArray Track(ArrowArray array) { + auto* tracked = new TrackedArray{array}; + ArrowArray outer = array; + outer.private_data = tracked; + outer.release = ReleaseTracked; + g_live_arrays.fetch_add(1); + return outer; +} + +// Describes what a fake reader produces for one file path. +struct FakeFile { + // Row ids of each batch. + std::vector> batches; + // Length of the `name` value in every row. + int32_t name_length = 1; + // Index of the batch whose Next() returns an error, or -1. + int fail_at = -1; + // Index of the batch whose Next() throws, or -1. + int throw_at = -1; + // Report `id` as int64 to provoke a schema mismatch. + bool wrong_schema = false; +}; + +class FakeFiles { + public: + static FakeFiles& Get() { + static FakeFiles files; + return files; + } + + void Clear() { + std::lock_guard lock(mutex_); + files_.clear(); + } + + void Add(const std::string& path, FakeFile file) { + std::lock_guard lock(mutex_); + files_[path] = std::move(file); + } + + std::optional Find(const std::string& path) { + std::lock_guard lock(mutex_); + auto it = files_.find(path); + if (it == files_.end()) { + return std::nullopt; + } + return it->second; + } + + private: + std::mutex mutex_; + std::unordered_map files_; +}; + +class FakeReader : public Reader { + public: + Status Open(const ReaderOptions& options) override { + auto file = FakeFiles::Get().Find(options.path); + if (!file.has_value()) { + return NotFound("No fake file: {}", options.path); + } + file_ = std::move(*file); + projection_ = options.projection; + return {}; + } + + Status Close() override { return {}; } + + Result> Next() override { + const int index = next_batch_++; + if (index == file_.fail_at) { + return IOError("injected read failure"); + } + if (index == file_.throw_at) { + throw std::runtime_error("injected reader exception"); + } + if (index >= static_cast(file_.batches.size())) { + return std::nullopt; + } + ICEBERG_ASSIGN_OR_RAISE(auto array, BuildBatch(file_.batches[index])); + return Track(array); + } + + Result Schema() override { + ArrowSchema schema{}; + if (!file_.wrong_schema) { + ICEBERG_RETURN_UNEXPECTED(ToArrowSchema(*projection_, &schema)); + return schema; + } + std::vector fields; + for (const auto& field : projection_->fields()) { + if (field.field_id() == kIdFieldId) { + fields.push_back(SchemaField::MakeRequired(kIdFieldId, "id", int64())); + } else { + fields.push_back(field); + } + } + ICEBERG_RETURN_UNEXPECTED(ToArrowSchema(iceberg::Schema(std::move(fields)), &schema)); + return schema; + } + + Result> Metadata() override { + return std::unordered_map{}; + } + + private: + Result BuildBatch(const std::vector& ids) const { + ArrowSchema schema{}; + ICEBERG_RETURN_UNEXPECTED(ToArrowSchema(*projection_, &schema)); + ArrowArray array{}; + const int init = ArrowArrayInitFromSchema(&array, &schema, nullptr); + schema.release(&schema); + if (init != NANOARROW_OK) { + return UnknownError("ArrowArrayInitFromSchema failed"); + } + const std::string name(static_cast(file_.name_length), 'x'); + if (ArrowArrayStartAppending(&array) != NANOARROW_OK) { + array.release(&array); + return UnknownError("ArrowArrayStartAppending failed"); + } + for (int32_t id : ids) { + for (size_t index = 0; index < projection_->fields().size(); ++index) { + ArrowArray* child = array.children[index]; + const int32_t field_id = projection_->fields()[index].field_id(); + int code = NANOARROW_OK; + if (field_id == kIdFieldId) { + code = ArrowArrayAppendInt(child, id); + } else if (field_id == kNameFieldId) { + code = ArrowArrayAppendString(child, ArrowCharView(name.c_str())); + } + if (code != NANOARROW_OK) { + array.release(&array); + return UnknownError("Appending to a fake batch failed"); + } + } + if (ArrowArrayFinishElement(&array) != NANOARROW_OK) { + array.release(&array); + return UnknownError("ArrowArrayFinishElement failed"); + } + } + if (ArrowArrayFinishBuildingDefault(&array, nullptr) != NANOARROW_OK) { + array.release(&array); + return UnknownError("ArrowArrayFinishBuildingDefault failed"); + } + return array; + } + + FakeFile file_; + std::shared_ptr projection_; + int next_batch_ = 0; +}; + +// Installs FakeReader for Parquet and Avro and restores the previous factories. +class ScopedFakeReaders { + public: + ScopedFakeReaders() + : previous_parquet_(ReaderFactoryRegistry::GetFactory(FileFormatType::kParquet)), + previous_avro_(ReaderFactoryRegistry::GetFactory(FileFormatType::kAvro)) { + auto factory = []() -> Result> { + return std::make_unique(); + }; + ReaderFactoryRegistry::GetFactory(FileFormatType::kParquet) = factory; + ReaderFactoryRegistry::GetFactory(FileFormatType::kAvro) = factory; + } + + ~ScopedFakeReaders() { + ReaderFactoryRegistry::GetFactory(FileFormatType::kParquet) = + std::move(previous_parquet_); + ReaderFactoryRegistry::GetFactory(FileFormatType::kAvro) = std::move(previous_avro_); + } + + ScopedFakeReaders(const ScopedFakeReaders&) = delete; + ScopedFakeReaders& operator=(const ScopedFakeReaders&) = delete; + + private: + ReaderFactory previous_parquet_; + ReaderFactory previous_avro_; +}; + +class FakeGroupStream : public FileScanTaskGroupStream { + public: + explicit FakeGroupStream(std::vector> groups) + : groups_(std::move(groups)) {} + + ~FakeGroupStream() override { + if (on_destroy) { + on_destroy(); + } + } + + // Index of the Next() call that returns an error, or -1. + int fail_at = -1; + // Index of the Next() call that throws, or -1. + int throw_at = -1; + std::function on_destroy; + + protected: + Result>> NextImpl() override { + const int index = calls_++; + if (index == fail_at) { + return IOError("injected planning failure"); + } + if (index == throw_at) { + throw std::runtime_error("injected planning exception"); + } + if (static_cast(index) >= groups_.size()) { + return std::nullopt; + } + return groups_[static_cast(index)]; + } + + private: + std::vector> groups_; + int calls_ = 0; +}; + +std::vector Range(int32_t begin, int32_t end) { + std::vector values; + for (int32_t value = begin; value < end; ++value) { + values.push_back(value); + } + return values; +} + +// Owns an ArrowArrayStream and releases it unless the test already did. +struct OwnedStream { + ArrowArrayStream stream{}; + + OwnedStream() = default; + explicit OwnedStream(ArrowArrayStream value) : stream(value) {} + OwnedStream(OwnedStream&& other) noexcept : stream(other.stream) { + other.stream.release = nullptr; + } + OwnedStream(const OwnedStream&) = delete; + OwnedStream& operator=(const OwnedStream&) = delete; + OwnedStream& operator=(OwnedStream&&) = delete; + ~OwnedStream() { Release(); } + + void Release() { + if (stream.release != nullptr) { + stream.release(&stream); + } + } +}; + +struct ReadResult { + // Ids of each batch, in the order the stream returned them. + std::vector> batches; + int error_code = 0; + std::string error_message; + + std::vector AllIds() const { + std::vector ids; + for (const auto& batch : batches) { + ids.insert(ids.end(), batch.begin(), batch.end()); + } + return ids; + } +}; + +// Reads the `id` column of a batch described by `schema`. +std::vector ReadIds(const ArrowSchema& schema, const ArrowArray& array) { + std::vector ids; + ArrowArrayView view; + EXPECT_EQ(ArrowArrayViewInitFromSchema(&view, &schema, nullptr), NANOARROW_OK); + EXPECT_EQ(ArrowArrayViewSetArray(&view, &array, nullptr), NANOARROW_OK); + for (int64_t row = 0; row < array.length; ++row) { + ids.push_back( + static_cast(ArrowArrayViewGetIntUnsafe(view.children[0], row))); + } + ArrowArrayViewReset(&view); + return ids; +} + +ReadResult ReadAll(ArrowArrayStream& stream, int64_t max_batches = -1) { + ReadResult result; + ArrowSchema schema{}; + EXPECT_EQ(stream.get_schema(&stream, &schema), 0); + while (max_batches < 0 || static_cast(result.batches.size()) < max_batches) { + ArrowArray array{}; + int code = stream.get_next(&stream, &array); + if (code != 0) { + result.error_code = code; + const char* message = stream.get_last_error(&stream); + result.error_message = message == nullptr ? "" : message; + break; + } + if (array.release == nullptr) { + break; + } + if (schema.n_children > 0) { + result.batches.push_back(ReadIds(schema, array)); + } else { + result.batches.emplace_back(static_cast(array.length), 0); + } + array.release(&array); + } + schema.release(&schema); + return result; +} + +// Polls `predicate` until it holds or a generous timeout expires. +bool WaitFor(const std::function& predicate) { + const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(30); + while (std::chrono::steady_clock::now() < deadline) { + if (predicate()) { + return true; + } + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } + return predicate(); +} + +} // namespace + +class ParallelScanReaderTest : public ::testing::Test { + protected: + void SetUp() override { + FakeFiles::Get().Clear(); + g_live_arrays.store(0); + table_schema_ = std::make_shared(std::vector{ + SchemaField::MakeRequired(kIdFieldId, "id", int32()), + SchemaField::MakeOptional(kNameFieldId, "name", string())}); + } + + void TearDown() override { + EXPECT_EQ(g_live_arrays.load(), 0) + << "Fake reader arrays leaked or were not released"; + FakeFiles::Get().Clear(); + } + + std::shared_ptr AddFile(const std::string& path, FakeFile file, + FileFormatType format = FileFormatType::kParquet, + std::shared_ptr residual = nullptr) { + FakeFiles::Get().Add(path, std::move(file)); + return std::make_shared(MakeDataFile(path, format), + std::vector>{}, + std::move(residual)); + } + + static std::shared_ptr MakeDataFile(const std::string& path, + FileFormatType format) { + auto data_file = std::make_shared(); + data_file->file_path = path; + data_file->file_format = format; + data_file->file_size_in_bytes = 100; + data_file->record_count = 10; + return data_file; + } + + static std::shared_ptr Group( + std::vector> tasks) { + return std::make_shared(std::move(tasks)); + } + + ParallelScanReader::Options MakeOptions(int32_t workers, int64_t max_batches, + int64_t max_bytes) const { + ParallelScanReader::Options options; + options.reader_options.io = std::make_shared(); + options.reader_options.table_schema = table_schema_; + options.reader_options.projected_schema = table_schema_; + options.worker_count = workers; + options.max_queued_batches = max_batches; + options.max_queued_bytes = max_bytes; + return options; + } + + Result Open(std::vector> groups, + ParallelScanReader::Options options, + std::shared_ptr metrics = nullptr) { + ICEBERG_ASSIGN_OR_RAISE( + auto stream, + OpenParallelScan(std::make_unique(std::move(groups)), + std::move(options), std::move(metrics))); + return OwnedStream(stream); + } + + // Builds `file_count` single-task groups with `batches` batches of 4 rows each. + std::vector> ManyFiles(int file_count, int batches, + int32_t name_length = 1) { + std::vector> groups; + int32_t next_id = 0; + for (int file = 0; file < file_count; ++file) { + FakeFile spec; + spec.name_length = name_length; + for (int batch = 0; batch < batches; ++batch) { + spec.batches.push_back(Range(next_id, next_id + 4)); + next_id += 4; + } + groups.push_back(Group({AddFile("file-" + std::to_string(file), spec)})); + } + return groups; + } + + ScopedFakeReaders fake_readers_; + std::shared_ptr table_schema_; +}; + +TEST_F(ParallelScanReaderTest, RejectsInvalidOptions) { + auto make_groups = [] { + return std::make_unique( + std::vector>{}); + }; + EXPECT_THAT(ParallelScanReader::Open(make_groups(), MakeOptions(0, 1, 1)), + IsError(ErrorKind::kInvalidArgument)); + EXPECT_THAT(ParallelScanReader::Open(make_groups(), MakeOptions(1, 0, 1)), + IsError(ErrorKind::kInvalidArgument)); + EXPECT_THAT(ParallelScanReader::Open(make_groups(), MakeOptions(1, 1, 0)), + IsError(ErrorKind::kInvalidArgument)); + EXPECT_THAT(ParallelScanReader::Open(nullptr, MakeOptions(1, 1, 1)), + IsError(ErrorKind::kInvalidArgument)); + + auto options = MakeOptions(1, 1, 1); + options.reader_options.io = nullptr; + EXPECT_THAT(ParallelScanReader::Open(make_groups(), options), + IsError(ErrorKind::kInvalidArgument)); +} + +TEST_F(ParallelScanReaderTest, ZeroGroupsEndsImmediately) { + ICEBERG_UNWRAP_OR_FAIL(auto owned, Open({}, MakeOptions(4, 4, 1 << 20))); + auto result = ReadAll(owned.stream); + EXPECT_EQ(result.error_code, 0); + EXPECT_TRUE(result.batches.empty()); + + // End of stream is sticky. + ArrowArray array{}; + EXPECT_EQ(owned.stream.get_next(&owned.stream, &array), 0); + EXPECT_EQ(array.release, nullptr); +} + +TEST_F(ParallelScanReaderTest, SchemaMatchesProjection) { + ICEBERG_UNWRAP_OR_FAIL(auto owned, Open({}, MakeOptions(1, 1, 1))); + ArrowSchema schema{}; + ASSERT_EQ(owned.stream.get_schema(&owned.stream, &schema), 0); + ASSERT_EQ(schema.n_children, 2); + EXPECT_STREQ(schema.children[0]->name, "id"); + EXPECT_STREQ(schema.children[0]->format, "i"); + EXPECT_STREQ(schema.children[1]->name, "name"); + EXPECT_STREQ(schema.children[1]->format, "u"); + schema.release(&schema); +} + +TEST_F(ParallelScanReaderTest, OneGroup) { + FakeFile file; + file.batches = {Range(0, 3), Range(3, 5)}; + ICEBERG_UNWRAP_OR_FAIL( + auto owned, Open({Group({AddFile("one", file)})}, MakeOptions(2, 4, 1 << 20))); + auto result = ReadAll(owned.stream); + EXPECT_EQ(result.error_code, 0) << result.error_message; + EXPECT_THAT(result.AllIds(), ElementsAreArray(Range(0, 5))); +} + +TEST_F(ParallelScanReaderTest, OneAndManyWorkersReturnTheSameRows) { + for (int32_t workers : {1, 2, 8}) { + SCOPED_TRACE(workers); + FakeFiles::Get().Clear(); + auto groups = ManyFiles(/*file_count=*/20, /*batches=*/3); + ICEBERG_UNWRAP_OR_FAIL(auto owned, + Open(std::move(groups), MakeOptions(workers, 3, 1 << 20))); + auto result = ReadAll(owned.stream); + EXPECT_EQ(result.error_code, 0) << result.error_message; + EXPECT_EQ(result.batches.size(), 60U); + EXPECT_THAT(result.AllIds(), UnorderedElementsAreArray(Range(0, 240))); + } +} + +TEST_F(ParallelScanReaderTest, GroupTasksAndMixedFormatsAreRead) { + FakeFile parquet; + parquet.batches = {Range(0, 2)}; + FakeFile avro; + avro.batches = {Range(2, 4)}; + FakeFile second_parquet; + second_parquet.batches = {Range(4, 6)}; + auto group = Group({AddFile("a.parquet", parquet), + AddFile("b.avro", avro, FileFormatType::kAvro), + AddFile("c.parquet", second_parquet)}); + ICEBERG_UNWRAP_OR_FAIL(auto owned, Open({group}, MakeOptions(3, 2, 1 << 20))); + auto result = ReadAll(owned.stream); + EXPECT_EQ(result.error_code, 0) << result.error_message; + // One worker reads a group's tasks in order. + EXPECT_THAT(result.AllIds(), ElementsAreArray(Range(0, 6))); +} + +TEST_F(ParallelScanReaderTest, KeepsTaskLocalOrderAcrossInterleavedGroups) { + FakeFile ordered; + for (int32_t batch = 0; batch < 50; ++batch) { + ordered.batches.push_back(Range(batch * 2, batch * 2 + 2)); + } + std::vector> groups = { + Group({AddFile("ordered", ordered)})}; + for (int file = 0; file < 10; ++file) { + FakeFile other; + for (int32_t batch = 0; batch < 5; ++batch) { + const int32_t begin = 1000 + file * 100 + batch * 2; + other.batches.push_back(Range(begin, begin + 2)); + } + groups.push_back(Group({AddFile("other-" + std::to_string(file), other)})); + } + ICEBERG_UNWRAP_OR_FAIL(auto owned, Open(std::move(groups), MakeOptions(4, 2, 1 << 20))); + auto result = ReadAll(owned.stream); + ASSERT_EQ(result.error_code, 0) << result.error_message; + + std::vector ordered_ids; + std::map> other_ids; + for (const auto& batch : result.batches) { + for (int32_t id : batch) { + if (id < 1000) { + ordered_ids.push_back(id); + } else { + other_ids[(id - 1000) / 100].push_back(id); + } + } + } + EXPECT_THAT(ordered_ids, ElementsAreArray(Range(0, 100))); + ASSERT_EQ(other_ids.size(), 10U); + for (const auto& [file, ids] : other_ids) { + EXPECT_TRUE(std::is_sorted(ids.begin(), ids.end())) << "file " << file; + } +} + +TEST_F(ParallelScanReaderTest, EnforcesResiduals) { + FakeFile file; + file.batches = {Range(0, 4), Range(4, 8), Range(8, 10)}; + auto residual = Expressions::GreaterThanOrEqual("id", Literal::Int(5)); + auto task = AddFile("filtered", file, FileFormatType::kParquet, residual); + // apply_residuals is forced on even when the caller leaves it off. + auto options = MakeOptions(2, 2, 1 << 20); + options.reader_options.apply_residuals = false; + ICEBERG_UNWRAP_OR_FAIL(auto owned, Open({Group({task})}, std::move(options))); + auto result = ReadAll(owned.stream); + EXPECT_EQ(result.error_code, 0) << result.error_message; + EXPECT_THAT(result.AllIds(), ElementsAreArray(Range(5, 10))); +} + +TEST_F(ParallelScanReaderTest, SchemaMismatchFailsWithContext) { + FakeFile file; + file.batches = {Range(0, 2)}; + file.wrong_schema = true; + ICEBERG_UNWRAP_OR_FAIL(auto owned, Open({Group({AddFile("mismatch.parquet", file)})}, + MakeOptions(1, 2, 1 << 20))); + auto result = ReadAll(owned.stream); + EXPECT_EQ(result.error_code, EIO); + EXPECT_THAT(result.error_message, HasSubstr("does not match the projected schema")); + EXPECT_THAT(result.error_message, HasSubstr("mismatch.parquet")); + EXPECT_THAT(result.error_message, HasSubstr("root.id")); +} + +TEST_F(ParallelScanReaderTest, ReadFailureNamesTheFileRange) { + FakeFile file; + file.batches = {Range(0, 2), Range(2, 4), Range(4, 6)}; + file.fail_at = 1; + FakeFiles::Get().Add("broken.parquet", file); + ICEBERG_UNWRAP_OR_FAIL( + auto task, FileScanTask::MakeSplit( + MakeDataFile("broken.parquet", FileFormatType::kParquet), 10, 40)); + ICEBERG_UNWRAP_OR_FAIL(auto owned, Open({Group({task})}, MakeOptions(1, 8, 1 << 20))); + auto result = ReadAll(owned.stream); + EXPECT_EQ(result.error_code, EIO); + EXPECT_THAT(result.error_message, HasSubstr("broken.parquet [10, 50)")); + EXPECT_THAT(result.error_message, HasSubstr("injected read failure")); + + // The error is sticky. + ArrowArray array{}; + EXPECT_EQ(owned.stream.get_next(&owned.stream, &array), EIO); +} + +TEST_F(ParallelScanReaderTest, OpenFailureIsReported) { + auto task = std::make_shared( + MakeDataFile("missing.parquet", FileFormatType::kParquet)); + ICEBERG_UNWRAP_OR_FAIL(auto owned, Open({Group({task})}, MakeOptions(2, 2, 1 << 20))); + auto result = ReadAll(owned.stream); + EXPECT_EQ(result.error_code, EIO); + EXPECT_THAT(result.error_message, + HasSubstr("Failed to open data file missing.parquet")); +} + +TEST_F(ParallelScanReaderTest, WorkerExceptionIsReported) { + FakeFile file; + file.batches = {Range(0, 2), Range(2, 4)}; + file.throw_at = 1; + ICEBERG_UNWRAP_OR_FAIL( + auto owned, Open({Group({AddFile("throws", file)})}, MakeOptions(2, 8, 1 << 20))); + auto result = ReadAll(owned.stream); + EXPECT_EQ(result.error_code, EIO); + EXPECT_THAT(result.error_message, HasSubstr("injected reader exception")); +} + +TEST_F(ParallelScanReaderTest, PlanningFailureIsReported) { + auto groups = ManyFiles(/*file_count=*/3, /*batches=*/2); + auto stream = std::make_unique(std::move(groups)); + stream->fail_at = 1; + ICEBERG_UNWRAP_OR_FAIL( + auto raw, ParallelScanReader::Open(std::move(stream), MakeOptions(2, 8, 1 << 20))); + OwnedStream owned(raw); + auto result = ReadAll(owned.stream); + EXPECT_EQ(result.error_code, EIO); + EXPECT_THAT(result.error_message, HasSubstr("Failed to plan task groups")); + EXPECT_THAT(result.error_message, HasSubstr("injected planning failure")); +} + +TEST_F(ParallelScanReaderTest, PlanningExceptionIsReported) { + auto stream = std::make_unique(ManyFiles(2, 1)); + stream->throw_at = 0; + ICEBERG_UNWRAP_OR_FAIL( + auto raw, ParallelScanReader::Open(std::move(stream), MakeOptions(3, 8, 1 << 20))); + OwnedStream owned(raw); + auto result = ReadAll(owned.stream); + EXPECT_EQ(result.error_code, EIO); + EXPECT_THAT(result.error_message, HasSubstr("injected planning exception")); +} + +TEST_F(ParallelScanReaderTest, BytesBindBeforeCount) { + auto metrics = std::make_shared(); + // Measure one batch so the byte budget holds exactly two. + auto groups = ManyFiles(/*file_count=*/1, /*batches=*/10, /*name_length=*/1000); + int64_t charge = 0; + { + auto probe = std::make_shared(); + FakeFile single; + single.batches = {Range(0, 4)}; + single.name_length = 1000; + ICEBERG_UNWRAP_OR_FAIL(auto owned, Open({Group({AddFile("probe", single)})}, + MakeOptions(1, 1, 1 << 30), probe)); + ASSERT_EQ(ReadAll(owned.stream).batches.size(), 1U); + charge = probe->Snapshot().bytes_admitted; + } + ASSERT_GT(charge, 4000); + + const int64_t budget = 2 * charge; + ICEBERG_UNWRAP_OR_FAIL(auto owned, + Open(std::move(groups), MakeOptions(1, 100, budget), metrics)); + // The worker queues two batches and then holds a third. + ASSERT_TRUE(WaitFor([&] { + auto snapshot = metrics->Snapshot(); + return snapshot.batches_admitted == 2 && snapshot.peak_held_bytes == charge; + })); + std::this_thread::sleep_for(std::chrono::milliseconds(20)); + auto blocked = metrics->Snapshot(); + EXPECT_EQ(blocked.batches_admitted, 2); + EXPECT_EQ(blocked.peak_queued_batches, 2); + EXPECT_EQ(blocked.peak_queued_bytes, budget); + + auto result = ReadAll(owned.stream); + EXPECT_EQ(result.error_code, 0) << result.error_message; + EXPECT_EQ(result.batches.size(), 10U); + auto done = metrics->Snapshot(); + EXPECT_LE(done.peak_queued_bytes, budget); + EXPECT_EQ(done.peak_queued_batches, 2); + EXPECT_EQ(done.oversized_admissions, 0); +} + +TEST_F(ParallelScanReaderTest, CountBindsBeforeBytes) { + auto metrics = std::make_shared(); + ICEBERG_UNWRAP_OR_FAIL(auto owned, + Open(ManyFiles(4, 5), MakeOptions(4, 3, 1 << 30), metrics)); + ASSERT_TRUE(WaitFor([&] { return metrics->Snapshot().batches_admitted == 3; })); + auto result = ReadAll(owned.stream); + EXPECT_EQ(result.error_code, 0) << result.error_message; + EXPECT_EQ(result.batches.size(), 20U); + EXPECT_EQ(metrics->Snapshot().peak_queued_batches, 3); +} + +TEST_F(ParallelScanReaderTest, ZeroByteBatchesCountTowardTheBatchLimit) { + auto metrics = std::make_shared(); + auto groups = ManyFiles(/*file_count=*/2, /*batches=*/4); + auto options = MakeOptions(2, 2, 1); + options.reader_options.projected_schema = + std::make_shared(std::vector{}); + ICEBERG_UNWRAP_OR_FAIL(auto owned, + Open(std::move(groups), std::move(options), metrics)); + ASSERT_TRUE(WaitFor([&] { return metrics->Snapshot().batches_admitted == 2; })); + std::this_thread::sleep_for(std::chrono::milliseconds(20)); + EXPECT_EQ(metrics->Snapshot().batches_admitted, 2); + + auto result = ReadAll(owned.stream); + EXPECT_EQ(result.error_code, 0) << result.error_message; + ASSERT_EQ(result.batches.size(), 8U); + for (const auto& batch : result.batches) { + EXPECT_EQ(batch.size(), 4U); + } + auto snapshot = metrics->Snapshot(); + EXPECT_EQ(snapshot.bytes_admitted, 0); + EXPECT_EQ(snapshot.peak_queued_batches, 2); +} + +TEST_F(ParallelScanReaderTest, OversizedBatchesAreQueuedAlone) { + auto metrics = std::make_shared(); + ICEBERG_UNWRAP_OR_FAIL(auto owned, + Open(ManyFiles(3, 4, 100), MakeOptions(3, 10, 1), metrics)); + auto result = ReadAll(owned.stream); + EXPECT_EQ(result.error_code, 0) << result.error_message; + EXPECT_EQ(result.batches.size(), 12U); + auto snapshot = metrics->Snapshot(); + EXPECT_EQ(snapshot.oversized_admissions, 12); + EXPECT_EQ(snapshot.peak_queued_batches, 1); +} + +TEST_F(ParallelScanReaderTest, OversizedBatchIsNotStarvedBySmallBatches) { + auto metrics = std::make_shared(); + FakeFile big; + big.batches = {Range(0, 4)}; + big.name_length = 100000; + std::vector> groups = {Group({AddFile("big", big)})}; + for (int file = 0; file < 4; ++file) { + FakeFile small; + for (int32_t batch = 0; batch < 25; ++batch) { + const int32_t begin = 1000 + file * 1000 + batch * 4; + small.batches.push_back(Range(begin, begin + 4)); + } + groups.push_back(Group({AddFile("small-" + std::to_string(file), small)})); + } + ICEBERG_UNWRAP_OR_FAIL(auto owned, + Open(std::move(groups), MakeOptions(5, 100, 8192), metrics)); + auto result = ReadAll(owned.stream); + EXPECT_EQ(result.error_code, 0) << result.error_message; + EXPECT_EQ(result.batches.size(), 101U); + auto snapshot = metrics->Snapshot(); + EXPECT_EQ(snapshot.oversized_admissions, 1); +} + +TEST_F(ParallelScanReaderTest, EarlyReleaseWhileProducersWait) { + auto metrics = std::make_shared(); + std::atomic group_stream_destroyed{false}; + auto groups = std::make_unique(ManyFiles(4, 20)); + groups->on_destroy = [&] { + // A metrics reporter may query diagnostics while the stream is destroyed. + std::ignore = metrics->Snapshot(); + group_stream_destroyed = true; + }; + ICEBERG_UNWRAP_OR_FAIL( + auto raw, OpenParallelScan(std::move(groups), MakeOptions(3, 1, 1 << 20), metrics)); + OwnedStream owned(raw); + + ArrowSchema schema{}; + ASSERT_EQ(owned.stream.get_schema(&owned.stream, &schema), 0); + ArrowArray kept{}; + ASSERT_EQ(owned.stream.get_next(&owned.stream, &kept), 0); + ASSERT_NE(kept.release, nullptr); + + // Wait until the queue is full again and other workers hold completed batches. + ASSERT_TRUE(WaitFor([&] { + auto snapshot = metrics->Snapshot(); + return snapshot.batches_admitted >= 2 && snapshot.peak_held_bytes > 0; + })); + owned.Release(); + EXPECT_TRUE(group_stream_destroyed.load()); + + // The returned array outlives the stream. + EXPECT_EQ(g_live_arrays.load(), 1); + auto ids = ReadIds(schema, kept); + EXPECT_EQ(ids.size(), 4U); + kept.release(&kept); + schema.release(&schema); + EXPECT_EQ(g_live_arrays.load(), 0); +} + +TEST_F(ParallelScanReaderTest, ReleaseWithoutReading) { + auto metrics = std::make_shared(); + ICEBERG_UNWRAP_OR_FAIL(auto owned, + Open(ManyFiles(8, 10), MakeOptions(4, 2, 1 << 20), metrics)); + ASSERT_TRUE(WaitFor([&] { return metrics->Snapshot().batches_admitted == 2; })); + owned.Release(); + EXPECT_EQ(g_live_arrays.load(), 0); +} + +TEST_F(ParallelScanReaderTest, GroupStreamIsDestroyedAtEndOfPlanning) { + auto metrics = std::make_shared(); + std::atomic groups_seen{-1}; + auto groups = std::make_unique(ManyFiles(5, 2)); + groups->on_destroy = [&] { groups_seen = metrics->Snapshot().groups_claimed; }; + ICEBERG_UNWRAP_OR_FAIL( + auto raw, OpenParallelScan(std::move(groups), MakeOptions(2, 4, 1 << 20), metrics)); + OwnedStream owned(raw); + auto result = ReadAll(owned.stream); + EXPECT_EQ(result.error_code, 0) << result.error_message; + EXPECT_EQ(result.batches.size(), 10U); + // Destroyed when planning reached its end, before the output stream is released. + EXPECT_EQ(groups_seen.load(), 5); + auto snapshot = metrics->Snapshot(); + EXPECT_EQ(snapshot.groups_claimed, 5); + EXPECT_EQ(snapshot.tasks_opened, 5); +} + +TEST_F(ParallelScanReaderTest, ErrorReleasesQueuedBatches) { + auto metrics = std::make_shared(); + auto groups = ManyFiles(/*file_count=*/2, /*batches=*/10); + FakeFile broken; + broken.batches = {Range(5000, 5004), Range(5004, 5008)}; + broken.fail_at = 1; + groups.push_back(Group({AddFile("broken", broken)})); + ICEBERG_UNWRAP_OR_FAIL(auto owned, + Open(std::move(groups), MakeOptions(3, 4, 1 << 20), metrics)); + auto result = ReadAll(owned.stream); + EXPECT_EQ(result.error_code, EIO); + EXPECT_THAT(result.error_message, HasSubstr("broken")); + owned.Release(); + EXPECT_EQ(g_live_arrays.load(), 0); +} + +} // namespace iceberg From 2d11068d75b483fa5f3e69e2c69d8e3d2dd1f2f6 Mon Sep 17 00:00:00 2001 From: Kam Cheung Ting Date: Mon, 23 Nov 2026 20:24:01 +0000 Subject: [PATCH 2/5] fix(data): avoid template parameter shadowing ParallelScanMetrics::Update GCC and AppleClang reject a template parameter that shares the member function's name. Also replace C-style arrays in the batch sizer tests. Co-authored-by: Isaac --- .../data/parallel_scan_reader_internal.h | 4 ++-- src/iceberg/test/arrow_batch_sizer_test.cc | 21 ++++++++++--------- 2 files changed, 13 insertions(+), 12 deletions(-) diff --git a/src/iceberg/data/parallel_scan_reader_internal.h b/src/iceberg/data/parallel_scan_reader_internal.h index d9f318e039..6d5945de2e 100644 --- a/src/iceberg/data/parallel_scan_reader_internal.h +++ b/src/iceberg/data/parallel_scan_reader_internal.h @@ -66,8 +66,8 @@ class ICEBERG_DATA_EXPORT ParallelScanMetrics { ParallelScanMetricsSnapshot Snapshot() const; /// \brief Apply `update` to the counters under this object's lock. - template - void Update(Update&& update) { + template + void Update(Fn&& update) { std::lock_guard lock(mutex_); update(snapshot_); } diff --git a/src/iceberg/test/arrow_batch_sizer_test.cc b/src/iceberg/test/arrow_batch_sizer_test.cc index 88c638b8b8..a202262537 100644 --- a/src/iceberg/test/arrow_batch_sizer_test.cc +++ b/src/iceberg/test/arrow_batch_sizer_test.cc @@ -17,6 +17,7 @@ * under the License. */ +#include #include #include #include @@ -227,10 +228,10 @@ TEST(ArrowBatchSizerTest, RejectsOverflowBeforeSizingBuffers) { schema.release(&schema); // The buffers are never dereferenced: the size checks fail first. - const void* buffers[2] = {nullptr, nullptr}; + std::array buffers = {nullptr, nullptr}; ArrowArray array{}; array.n_buffers = 2; - array.buffers = buffers; + array.buffers = buffers.data(); array.release = ReleaseNothing; // offset + length overflows. @@ -250,10 +251,10 @@ TEST(ArrowBatchSizerTest, RejectsOffsetBufferOverflow) { ICEBERG_UNWRAP_OR_FAIL(auto sizer, ArrowBatchSizer::Make(schema)); schema.release(&schema); - const void* buffers[3] = {nullptr, nullptr, nullptr}; + std::array buffers = {nullptr, nullptr, nullptr}; ArrowArray array{}; array.n_buffers = 3; - array.buffers = buffers; + array.buffers = buffers.data(); array.release = ReleaseNothing; // (length + 1) * 8 offset bytes overflows. array.length = std::numeric_limits::max() / 8; @@ -269,19 +270,19 @@ TEST(ArrowBatchSizerTest, RejectsFixedSizeListChildLengthOverflow) { ICEBERG_UNWRAP_OR_FAIL(auto sizer, ArrowBatchSizer::Make(schema)); schema.release(&schema); - const void* child_buffers[2] = {nullptr, nullptr}; + std::array child_buffers = {nullptr, nullptr}; ArrowArray child{}; child.n_buffers = 2; - child.buffers = child_buffers; + child.buffers = child_buffers.data(); child.release = ReleaseNothing; - ArrowArray* children[1] = {&child}; + std::array children = {&child}; - const void* buffers[1] = {nullptr}; + std::array buffers = {nullptr}; ArrowArray array{}; array.n_buffers = 1; - array.buffers = buffers; + array.buffers = buffers.data(); array.n_children = 1; - array.children = children; + array.children = children.data(); array.release = ReleaseNothing; // length * 2^20 child elements overflows. array.length = std::numeric_limits::max() / 1024; From 47f803d2bf975509eed203efc5baab140519b814 Mon Sep 17 00:00:00 2001 From: Kam Cheung Ting Date: Tue, 24 Nov 2026 00:34:46 +0000 Subject: [PATCH 3/5] style(data): fix clang-tidy warnings in parallel scan reader Use std::cmp_* for signed/unsigned comparisons and std::ranges::is_sorted. Co-authored-by: Isaac --- src/iceberg/data/parallel_scan_reader.cc | 2 +- src/iceberg/test/parallel_scan_reader_test.cc | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/iceberg/data/parallel_scan_reader.cc b/src/iceberg/data/parallel_scan_reader.cc index 7c54bcc4a4..233c7330a4 100644 --- a/src/iceberg/data/parallel_scan_reader.cc +++ b/src/iceberg/data/parallel_scan_reader.cc @@ -465,7 +465,7 @@ class ParallelScan { // Requires `mutex_`. bool CanAdmit(int64_t charge) const { - if (static_cast(queue_.size()) >= max_queued_batches_) { + if (std::cmp_greater_equal(queue_.size(), max_queued_batches_)) { return false; } if (charge > max_queued_bytes_) { diff --git a/src/iceberg/test/parallel_scan_reader_test.cc b/src/iceberg/test/parallel_scan_reader_test.cc index 0bb7f9f2a8..b49c761893 100644 --- a/src/iceberg/test/parallel_scan_reader_test.cc +++ b/src/iceberg/test/parallel_scan_reader_test.cc @@ -160,7 +160,7 @@ class FakeReader : public Reader { if (index == file_.throw_at) { throw std::runtime_error("injected reader exception"); } - if (index >= static_cast(file_.batches.size())) { + if (std::cmp_greater_equal(index, file_.batches.size())) { return std::nullopt; } ICEBERG_ASSIGN_OR_RAISE(auto array, BuildBatch(file_.batches[index])); @@ -362,7 +362,7 @@ ReadResult ReadAll(ArrowArrayStream& stream, int64_t max_batches = -1) { ReadResult result; ArrowSchema schema{}; EXPECT_EQ(stream.get_schema(&stream, &schema), 0); - while (max_batches < 0 || static_cast(result.batches.size()) < max_batches) { + while (max_batches < 0 || std::cmp_less(result.batches.size(), max_batches)) { ArrowArray array{}; int code = stream.get_next(&stream, &array); if (code != 0) { @@ -600,7 +600,7 @@ TEST_F(ParallelScanReaderTest, KeepsTaskLocalOrderAcrossInterleavedGroups) { EXPECT_THAT(ordered_ids, ElementsAreArray(Range(0, 100))); ASSERT_EQ(other_ids.size(), 10U); for (const auto& [file, ids] : other_ids) { - EXPECT_TRUE(std::is_sorted(ids.begin(), ids.end())) << "file " << file; + EXPECT_TRUE(std::ranges::is_sorted(ids)) << "file " << file; } } From 6c4a84959b2978fa47d4246691a619f3a459931f Mon Sep 17 00:00:00 2001 From: Kam Cheung Ting Date: Mon, 23 Nov 2026 08:44:55 +0000 Subject: [PATCH 4/5] test(scan): Support split and parallel scans - Part-5: end-to-end validation and benchmark Plan real tables with PlanTasksStream() and read them with ParallelScanReader, comparing the rows with PlanFilesStream() and the serial FileScanTaskReader and with independently expected values, for one and four workers and format versions 1-3: - multi-row-group Parquet files split by manifest offsets, by fixed ranges when offsets are missing, and by valid offsets that fall inside row groups instead of on their canonical starts - one large row group split into several ranges - many small files packed into groups - mixed Parquet and Avro files (Avro stays whole) - case-insensitive residual filters - position deletes carried into every split - absolute _row_id and _pos values across splits (v3) - releasing the stream between callbacks while workers are busy Add parallel_scan_benchmark (bundle builds with ICEBERG_BUILD_BENCHMARKS), which writes a large-file and a small-file local table and reports paired, order-alternated serial versus parallel trials with a bootstrapped median and 95% confidence interval of the speedup, end to end and for the read phase, plus planning time, queue peaks, producer wait, and peak RSS. It is not run in CI. Co-authored-by: Isaac --- src/iceberg/benchmark/CMakeLists.txt | 8 + .../benchmark/parallel_scan_benchmark.cc | 606 +++++++++++++++++ src/iceberg/test/CMakeLists.txt | 1 + src/iceberg/test/parallel_table_scan_test.cc | 616 ++++++++++++++++++ 4 files changed, 1231 insertions(+) create mode 100644 src/iceberg/benchmark/parallel_scan_benchmark.cc create mode 100644 src/iceberg/test/parallel_table_scan_test.cc diff --git a/src/iceberg/benchmark/CMakeLists.txt b/src/iceberg/benchmark/CMakeLists.txt index a34995ff1f..8bfdf94996 100644 --- a/src/iceberg/benchmark/CMakeLists.txt +++ b/src/iceberg/benchmark/CMakeLists.txt @@ -27,3 +27,11 @@ endfunction() add_iceberg_benchmark(benchmark_smoke) add_iceberg_benchmark(metrics_evaluator_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 0000000000..04cc9f6cd3 --- /dev/null +++ b/src/iceberg/benchmark/parallel_scan_benchmark.cc @@ -0,0 +1,606 @@ +/* + * 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 "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/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; +} + +Result RunParallel(const Table& table, const std::shared_ptr& io, + const std::shared_ptr& schema, int workers, bool filter) { + Run run; + 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), + .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::vector bytes_read[2]; + std::vector allocations[2]; + std::vector allocated_bytes[2]; + 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; +} + +} // namespace +} // namespace iceberg + +int main(int argc, char** argv) { + using namespace iceberg; + 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; +} diff --git a/src/iceberg/test/CMakeLists.txt b/src/iceberg/test/CMakeLists.txt index 825608245b..142fd3302a 100644 --- a/src/iceberg/test/CMakeLists.txt +++ b/src/iceberg/test/CMakeLists.txt @@ -286,6 +286,7 @@ if(ICEBERG_BUILD_BUNDLE) file_scan_task_test.cc incremental_append_scan_test.cc incremental_changelog_scan_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 0000000000..fee4f859ce --- /dev/null +++ b/src/iceberg/test/parallel_table_scan_test.cc @@ -0,0 +1,616 @@ +/* + * 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/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: + 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), + .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, 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), + .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 From 2bcce44ff1fb0c0415ec8b8f69dfdbb523c1b876 Mon Sep 17 00:00:00 2001 From: Kam Cheung Ting Date: Tue, 24 Nov 2026 00:36:16 +0000 Subject: [PATCH 5/5] style(benchmark): fix clang-tidy warnings in parallel scan benchmark Use std::array for per-path samples and move main's body into the iceberg namespace instead of a using-directive. Co-authored-by: Isaac --- .../benchmark/parallel_scan_benchmark.cc | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/src/iceberg/benchmark/parallel_scan_benchmark.cc b/src/iceberg/benchmark/parallel_scan_benchmark.cc index 04cc9f6cd3..27e0ed43d2 100644 --- a/src/iceberg/benchmark/parallel_scan_benchmark.cc +++ b/src/iceberg/benchmark/parallel_scan_benchmark.cc @@ -32,6 +32,7 @@ // [--filter=all-pass|none] #include +#include #include #include #include @@ -457,9 +458,9 @@ Status RunWorkload(const Config& config, const Workload& workload) { std::vector total_ratios; std::vector read_ratios; // Indexed by path: 0 = serial, 1 = parallel. - std::vector bytes_read[2]; - std::vector allocations[2]; - std::vector allocated_bytes[2]; + 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; @@ -567,11 +568,7 @@ Config ParseArgs(int argc, char** argv) { return config; } -} // namespace -} // namespace iceberg - -int main(int argc, char** argv) { - using namespace iceberg; +int RunBenchmark(int argc, char** argv) { parquet::RegisterAll(); avro::RegisterAll(); const Config config = ParseArgs(argc, argv); @@ -604,3 +601,8 @@ int main(int argc, char** argv) { } return 0; } + +} // namespace +} // namespace iceberg + +int main(int argc, char** argv) { return iceberg::RunBenchmark(argc, argv); }