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/3] 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/3] 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/3] 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; } }