diff --git a/src/iceberg/CMakeLists.txt b/src/iceberg/CMakeLists.txt index 0768f1aaf..0065b838b 100644 --- a/src/iceberg/CMakeLists.txt +++ b/src/iceberg/CMakeLists.txt @@ -109,6 +109,7 @@ set(ICEBERG_SOURCES row/manifest_wrapper.cc row/partition_values.cc row/struct_like.cc + scan_task_planning.cc schema.cc schema_field.cc schema_internal.cc diff --git a/src/iceberg/data_table_scan.cc b/src/iceberg/data_table_scan.cc index f35f454c0..5eea6088e 100644 --- a/src/iceberg/data_table_scan.cc +++ b/src/iceberg/data_table_scan.cc @@ -30,6 +30,7 @@ #include "iceberg/metrics/metrics_context.h" #include "iceberg/metrics/metrics_reporter.h" #include "iceberg/metrics/scan_report.h" +#include "iceberg/scan_task_planning_internal.h" #include "iceberg/schema.h" #include "iceberg/snapshot.h" #include "iceberg/table_metadata.h" @@ -217,4 +218,19 @@ Result DataTableScan::PlanFilesStream() const { context_.metrics_reporter, std::move(report).value()); } +Result>> DataTableScan::PlanTasks() const { + ICEBERG_ASSIGN_OR_RAISE(auto stream, PlanTasksStream()); + return stream->ToVector(); +} + +Result DataTableScan::PlanTasksStream() const { + // Resolve the settings before planning so invalid values fail before any + // planning resources are created. + ICEBERG_ASSIGN_OR_RAISE(auto options, + internal::ResolveTaskGroupPlanningOptions( + context_.options, metadata_->properties.configs())); + ICEBERG_ASSIGN_OR_RAISE(auto tasks, PlanFilesStream()); + return internal::PlanTaskGroupStream(std::move(tasks), options); +} + } // namespace iceberg diff --git a/src/iceberg/data_table_scan.h b/src/iceberg/data_table_scan.h index 96804d953..3a4be4c8b 100644 --- a/src/iceberg/data_table_scan.h +++ b/src/iceberg/data_table_scan.h @@ -56,6 +56,25 @@ class ICEBERG_EXPORT DataTableScan : public TableScan { /// work to it. virtual Result PlanFilesStream() const; + /// \brief Collects PlanTasksStream() into a vector. + /// \return A Result containing task groups or an error. + Result>> PlanTasks() const; + + /// \brief Lazily splits and groups this scan's planned tasks. + /// + /// Parquet files larger than read.split.target-size use manifest split offsets + /// coalesced toward the target size, or fixed-size byte ranges when offsets are + /// unavailable or invalid. Other files stay whole. Splitting does not open data + /// files. Tasks are weighted using read.split.open-file-cost and packed with at + /// most read.split.planning-lookback open groups. + /// + /// The returned fallible, single-pass stream owns the underlying task stream and its + /// metrics, and can outlive this scan. An executor configured through PlanWith() is + /// borrowed and must remain alive until the group stream is destroyed, as later + /// Next() calls may submit work to it. Split settings resolve from scan options, + /// then table properties, then their defaults. + virtual Result PlanTasksStream() const; + protected: using TableScan::TableScan; }; diff --git a/src/iceberg/scan_task_planning.cc b/src/iceberg/scan_task_planning.cc new file mode 100644 index 000000000..7196305aa --- /dev/null +++ b/src/iceberg/scan_task_planning.cc @@ -0,0 +1,305 @@ +/* + * 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 +#include + +#include "iceberg/manifest/manifest_entry.h" +#include "iceberg/result.h" +#include "iceberg/scan_task_planning_internal.h" +#include "iceberg/table_properties.h" +#include "iceberg/util/content_file_util.h" +#include "iceberg/util/int128.h" +#include "iceberg/util/string_util.h" + +namespace iceberg::internal { + +namespace { + +template +Result ResolveValue( + const std::string& key, T default_value, + const std::unordered_map& scan_options, + const std::unordered_map& table_properties) { + for (const auto* source : {&scan_options, &table_properties}) { + auto value = source->find(key); + if (value != source->end()) { + return StringUtils::ParseNumber(value->second); + } + } + return default_value; +} + +int128_t DeleteContentBytes(const FileScanTask& task) { + int128_t total = 0; + for (const auto& delete_file : task.delete_files()) { + total += ContentFileUtil::ContentSizeInBytes(*delete_file); + } + return total; +} + +// One group that is still open while packing. Mirrors Java's BinPacking.Bin. +struct OpenGroup { + std::vector> tasks; + int128_t weight = 0; + int64_t count = 0; +}; + +} // namespace + +Result ResolveTaskGroupPlanningOptions( + const std::unordered_map& scan_options, + const std::unordered_map& table_properties) { + using TableProps = TableProperties; + ICEBERG_ASSIGN_OR_RAISE( + auto target_size, + ResolveValue(TableProps::kSplitSize.key(), TableProps::kSplitSize.value(), + scan_options, table_properties)); + ICEBERG_ASSIGN_OR_RAISE(auto lookback, + ResolveValue(TableProps::kSplitLookback.key(), + TableProps::kSplitLookback.value(), + scan_options, table_properties)); + ICEBERG_ASSIGN_OR_RAISE(auto open_file_cost, + ResolveValue(TableProps::kSplitOpenFileCost.key(), + TableProps::kSplitOpenFileCost.value(), + scan_options, table_properties)); + if (target_size <= 0) { + return Invalid("read.split.target-size must be positive, but is {}", target_size); + } + if (lookback <= 0) { + return Invalid("read.split.planning-lookback must be positive, but is {}", lookback); + } + if (open_file_cost < 0) { + return Invalid("read.split.open-file-cost must not be negative, but is {}", + open_file_cost); + } + return TaskGroupPlanningOptions{ + .target_size = target_size, .lookback = lookback, .open_file_cost = open_file_cost}; +} + +Result TaskGroupWeight(const FileScanTask& task, int64_t open_file_cost) { + const int128_t content_cost = + static_cast(task.length()) + DeleteContentBytes(task); + const int128_t open_cost = + (static_cast(task.delete_files().size()) + 1) * open_file_cost; + const auto weight = std::max(content_cost, open_cost); + if (weight > std::numeric_limits::max()) { + return Invalid( + "Task group cost overflows 64 bits for data file {} (length {}, delete files {})", + task.data_file()->file_path, task.length(), task.delete_files().size()); + } + return static_cast(weight); +} + +namespace { + +std::span ValidSplitOffsets(const DataFile& file) { + int64_t previous = 0; + for (int64_t offset : file.split_offsets) { + if (offset <= previous || offset >= file.file_size_in_bytes) { + return {}; + } + previous = offset; + } + return file.split_offsets; +} + +// Generates ranges on demand so a small target size does not materialize every +// split of a large file before the first group can be returned. +class FileScanTaskSplitCursor { + public: + FileScanTaskSplitCursor(std::shared_ptr task, int64_t target_size) + : task_(std::move(task)), + target_size_(target_size), + boundaries_(ValidSplitOffsets(*task_->data_file())) {} + + bool HasNext() const { return next_start_ < task_->length(); } + + Result> Next() { + const int64_t file_size = task_->length(); + int64_t end = file_size; + if (boundaries_.empty()) { + end = next_start_ + std::min(target_size_, file_size - next_start_); + } else { + // Coalesce toward the target while covering the prefix and tail of the file. + while (next_boundary_ < boundaries_.size()) { + const int64_t boundary = boundaries_[next_boundary_++]; + if (boundary - next_start_ >= target_size_) { + end = boundary; + break; + } + } + } + const int64_t start = std::exchange(next_start_, end); + if (start == 0 && end == file_size) { + return task_; + } + return FileScanTask::MakeSplit(task_->data_file(), start, end - start, + task_->delete_files(), task_->residual_filter()); + } + + private: + std::shared_ptr task_; + int64_t target_size_; + std::span boundaries_; + int64_t next_start_ = 0; + size_t next_boundary_ = 0; +}; + +// Packs tasks into groups, mirroring Java's BinPacking.PackingIterator with +// largestBinFirst=true: at most `lookback` groups stay open, a task joins the first +// open group that fits, and the largest open group is closed first when a new group +// opens. +class TaskGroupPacker { + public: + explicit TaskGroupPacker(const TaskGroupPlanningOptions& options) : options_(options) {} + + /// Adds a task and returns a closed group when packing closes one. + Result>> Add( + std::shared_ptr task) { + ICEBERG_ASSIGN_OR_RAISE(auto weight, TaskGroupWeight(*task, options_.open_file_cost)); + for (auto& group : open_groups_) { + if (group.weight + weight <= options_.target_size && + group.count < kMaxTasksPerTaskGroup) { + group.tasks.push_back(std::move(task)); + group.weight += weight; + ++group.count; + return std::nullopt; + } + } + OpenGroup group; + group.tasks.push_back(std::move(task)); + group.weight = weight; + group.count = 1; + open_groups_.push_back(std::move(group)); + if (std::cmp_greater(open_groups_.size(), options_.lookback)) { + return std::optional>{CloseLargestGroup()}; + } + return std::nullopt; + } + + /// Returns the next remaining group after the input ends, or std::nullopt when all + /// groups have been returned. + std::optional> NextRemainingGroup() { + if (open_groups_.empty()) { + return std::nullopt; + } + std::vector> tasks = + std::move(open_groups_.front().tasks); + open_groups_.pop_front(); + return std::make_shared(std::move(tasks)); + } + + private: + std::shared_ptr CloseLargestGroup() { + // Like Java's Collections.max, the first open group with the largest weight is + // closed. + auto largest = open_groups_.begin(); + for (auto group = std::next(largest); group != open_groups_.end(); ++group) { + if (group->weight > largest->weight) { + largest = group; + } + } + std::vector> tasks = std::move(largest->tasks); + open_groups_.erase(largest); + return std::make_shared(std::move(tasks)); + } + + TaskGroupPlanningOptions options_; + std::deque open_groups_; +}; + +// Splits and packs one task stream into groups on demand. The stream owns the task +// stream, so destroying it releases the underlying planning resources, including a +// borrowed planning executor's work. +class TaskGroupPlanningStream final : public FileScanTaskGroupStream { + public: + TaskGroupPlanningStream(FileScanTaskStreamPtr tasks, + const TaskGroupPlanningOptions& options) + : tasks_(std::move(tasks)), target_size_(options.target_size), packer_(options) {} + + Result>> NextImpl() override { + while (true) { + ICEBERG_ASSIGN_OR_RAISE(auto task, NextTask()); + if (!task.has_value()) { + return packer_.NextRemainingGroup(); + } + ICEBERG_ASSIGN_OR_RAISE(auto group, packer_.Add(std::move(*task))); + if (group.has_value()) { + return group; + } + } + } + + private: + Result>> NextTask() { + if (!splits_ || !splits_->HasNext()) { + splits_.reset(); + ICEBERG_ASSIGN_OR_RAISE(auto task, tasks_->Next()); + if (!task || (*task)->is_split() || (*task)->length() <= target_size_) { + return task; + } + // FileScanTaskReader supports partial tasks for Parquet. + if ((*task)->data_file()->file_format != FileFormatType::kParquet) { + return task; + } + splits_.emplace(std::move(*task), target_size_); + } + ICEBERG_ASSIGN_OR_RAISE(auto split, splits_->Next()); + return std::optional{std::move(split)}; + } + + FileScanTaskStreamPtr tasks_; + int64_t target_size_; + TaskGroupPacker packer_; + std::optional splits_; +}; + +} // namespace + +Result PlanTaskGroupStream( + FileScanTaskStreamPtr tasks, const TaskGroupPlanningOptions& options) { + if (tasks == nullptr) { + return Invalid("Task stream must not be null"); + } + if (options.target_size <= 0) { + return Invalid("read.split.target-size must be positive, but is {}", + options.target_size); + } + if (options.lookback <= 0) { + return Invalid("read.split.planning-lookback must be positive, but is {}", + options.lookback); + } + if (options.open_file_cost < 0) { + return Invalid("read.split.open-file-cost must not be negative, but is {}", + options.open_file_cost); + } + return std::make_unique(std::move(tasks), options); +} + +} // namespace iceberg::internal diff --git a/src/iceberg/scan_task_planning_internal.h b/src/iceberg/scan_task_planning_internal.h new file mode 100644 index 000000000..72f7bc40a --- /dev/null +++ b/src/iceberg/scan_task_planning_internal.h @@ -0,0 +1,76 @@ +/* + * 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/scan_task_planning_internal.h +/// \brief Internal helpers that split and group file scan tasks for parallel reads. + +#include +#include +#include + +#include "iceberg/iceberg_export.h" +#include "iceberg/result.h" +#include "iceberg/table_scan.h" +#include "iceberg/type_fwd.h" + +namespace iceberg::internal { + +/// \brief Maximum number of tasks in one planned group in this version. +inline constexpr int64_t kMaxTasksPerTaskGroup = 1024; + +/// \brief Split-planning settings resolved from read.split.* properties. +struct TaskGroupPlanningOptions { + /// Target combined task weight per group; read.split.target-size. + int64_t target_size = 0; + /// Maximum number of open groups while packing; read.split.planning-lookback. + int64_t lookback = 0; + /// Cost charged for every file a group opens; read.split.open-file-cost. + int64_t open_file_cost = 0; +}; + +/// \brief Resolve split-planning settings by scan option, then table property, then +/// the default value. +/// +/// \return An error for malformed values, a nonpositive target size or lookback, or a +/// negative open-file cost. +ICEBERG_EXPORT Result ResolveTaskGroupPlanningOptions( + const std::unordered_map& scan_options, + const std::unordered_map& table_properties); + +/// \brief The group-packing weight of a task, matching Java Iceberg's TableScanUtil: +/// max(range length + delete content bytes, (1 + delete file count) * open file cost). +/// +/// Deletion vectors count their content size rather than their container file size, +/// matching Java's ScanTaskUtil.contentSizeInBytes. +/// \return An error when the cost overflows a signed 64-bit integer. +ICEBERG_EXPORT Result TaskGroupWeight(const FileScanTask& task, + int64_t open_file_cost); + +/// \brief Lazily split and pack the tasks of \p tasks into task groups. +/// +/// The returned single-pass stream owns \p tasks. +/// Groups are packed like Java Iceberg's bin packing: at most \p lookback groups stay +/// open, the largest open group is closed first, a group holds at most +/// kMaxTasksPerTaskGroup tasks, and an oversized task forms a singleton group. +ICEBERG_EXPORT Result PlanTaskGroupStream( + FileScanTaskStreamPtr tasks, const TaskGroupPlanningOptions& options); + +} // namespace iceberg::internal diff --git a/src/iceberg/table_scan.cc b/src/iceberg/table_scan.cc index d04e3385b..a29ee0043 100644 --- a/src/iceberg/table_scan.cc +++ b/src/iceberg/table_scan.cc @@ -258,6 +258,42 @@ int64_t FileScanTask::estimated_row_count() const { return static_cast(count_at_end - count_at_start); } +// FileScanTaskGroup implementation + +FileScanTaskGroup::FileScanTaskGroup(std::vector> tasks) + : tasks_(std::move(tasks)) { + for (const auto& task : tasks_) { + ICEBERG_DCHECK(task != nullptr, "Task in a file scan task group cannot be null"); + } +} + +int64_t FileScanTaskGroup::size_bytes() const { + int128_t total = 0; + for (const auto& task : tasks_) { + total += task->size_bytes(); + } + return static_cast( + std::min(total, std::numeric_limits::max())); +} + +int32_t FileScanTaskGroup::files_count() const { + int64_t total = 0; + for (const auto& task : tasks_) { + total += task->files_count(); + } + return static_cast( + std::min(total, std::numeric_limits::max())); +} + +int64_t FileScanTaskGroup::estimated_row_count() const { + int128_t total = 0; + for (const auto& task : tasks_) { + total += task->estimated_row_count(); + } + return static_cast( + std::min(total, std::numeric_limits::max())); +} + // ChangelogScanTask implementation ChangelogScanTask::ChangelogScanTask(int32_t change_ordinal, int64_t commit_snapshot_id, diff --git a/src/iceberg/table_scan.h b/src/iceberg/table_scan.h index 1307089e3..3781d88cf 100644 --- a/src/iceberg/table_scan.h +++ b/src/iceberg/table_scan.h @@ -47,6 +47,7 @@ class ICEBERG_EXPORT ScanTask { enum class Kind : uint8_t { kFileScanTask, kChangelogScanTask, + kFileScanTaskGroup, }; /// \brief The kind of scan task. @@ -141,6 +142,44 @@ using FileScanTaskStream = Stream>; /// \brief Owning pointer to a file scan task stream. using FileScanTaskStreamPtr = std::unique_ptr; +/// \brief A group of file scan tasks planned as one unit of parallel work. +/// +/// Groups are produced by DataTableScan::PlanTasksStream(). The tasks in a group are +/// read sequentially by one reader, and groups are the unit of parallelism for +/// parallel scans. +class ICEBERG_EXPORT FileScanTaskGroup : public ScanTask { + public: + /// \brief Construct a group that takes shared ownership of its tasks. + /// + /// \param tasks The group's tasks, in planning order. They must not be mutated + /// while the group is used. + explicit FileScanTaskGroup(std::vector> tasks); + + /// \brief The tasks in this group, in planning order. + const std::vector>& tasks() const { return tasks_; } + + /// \brief This scan task group's kind. + Kind kind() const override { return Kind::kFileScanTaskGroup; } + + /// \brief The number of bytes that should be read by this task group. + int64_t size_bytes() const override; + + /// \brief The number of files that should be read by this task group. + int32_t files_count() const override; + + /// \brief The estimated number of rows that should be read by this task group. + int64_t estimated_row_count() const override; + + private: + std::vector> tasks_; +}; + +/// \brief Stream of file scan task groups. +using FileScanTaskGroupStream = Stream>; + +/// \brief Owning pointer to a file scan task group stream. +using FileScanTaskGroupStreamPtr = std::unique_ptr; + enum class ChangelogOperation : uint8_t { kInsert, kDelete, diff --git a/src/iceberg/test/CMakeLists.txt b/src/iceberg/test/CMakeLists.txt index 6b2c6dbc0..a6f3d8ba1 100644 --- a/src/iceberg/test/CMakeLists.txt +++ b/src/iceberg/test/CMakeLists.txt @@ -107,6 +107,7 @@ add_iceberg_test(table_test metrics_config_test.cc metrics_reporter_test.cc metrics_test.cc + scan_task_planning_test.cc snapshot_summary_builder_test.cc snapshot_test.cc snapshot_util_test.cc diff --git a/src/iceberg/test/scan_task_planning_test.cc b/src/iceberg/test/scan_task_planning_test.cc new file mode 100644 index 000000000..8d3e335bf --- /dev/null +++ b/src/iceberg/test/scan_task_planning_test.cc @@ -0,0 +1,403 @@ +/* + * 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 + +#include "iceberg/expression/expressions.h" +#include "iceberg/manifest/manifest_entry.h" +#include "iceberg/result.h" +#include "iceberg/scan_task_planning_internal.h" +#include "iceberg/table_properties.h" +#include "iceberg/table_scan.h" +#include "iceberg/test/matchers.h" +#include "iceberg/util/stream.h" + +namespace iceberg::internal { +namespace { + +using testing::ElementsAre; +using testing::Eq; + +const int64_t kDefaultTargetSize = TableProperties::kSplitSize.value(); +const int32_t kDefaultLookback = TableProperties::kSplitLookback.value(); +const int64_t kDefaultOpenFileCost = TableProperties::kSplitOpenFileCost.value(); + +std::shared_ptr MakeDataFile(const std::string& path, int64_t file_size, + std::vector split_offsets = {}) { + auto file = std::make_shared(); + file->content = DataFile::Content::kData; + file->file_path = path; + file->file_format = FileFormatType::kParquet; + file->record_count = 10; + file->file_size_in_bytes = file_size; + file->split_offsets = std::move(split_offsets); + return file; +} + +std::shared_ptr MakeDeleteFile(int64_t file_size, + std::optional content_size = {}, + bool puffin = false) { + auto file = std::make_shared(); + file->content = DataFile::Content::kPositionDeletes; + file->file_path = "delete-file"; + file->file_format = puffin ? FileFormatType::kPuffin : FileFormatType::kParquet; + file->record_count = 1; + file->file_size_in_bytes = file_size; + file->content_size_in_bytes = content_size; + return file; +} + +std::shared_ptr MakeTask( + std::shared_ptr file, std::vector> deletes = {}) { + return std::make_shared(std::move(file), std::move(deletes)); +} + +FileScanTaskStreamPtr TaskStream(std::vector> tasks) { + return FileScanTaskStream::FromVector(std::move(tasks)); +} + +TaskGroupPlanningOptions Options(int64_t target_size, int64_t lookback = 10, + int64_t open_file_cost = 0) { + return TaskGroupPlanningOptions{ + .target_size = target_size, .lookback = lookback, .open_file_cost = open_file_cost}; +} + +Result>> PlanAll( + std::vector> tasks, + const TaskGroupPlanningOptions& options) { + ICEBERG_ASSIGN_OR_RAISE(auto stream, + PlanTaskGroupStream(TaskStream(std::move(tasks)), options)); + std::vector> groups; + while (true) { + ICEBERG_ASSIGN_OR_RAISE(auto group, stream->Next()); + if (!group.has_value()) { + return groups; + } + groups.push_back(std::move(group).value()); + } +} + +// (start, length) of each task in a group, in order. +std::vector> RangesOf(const FileScanTaskGroup& group) { + std::vector> ranges; + for (const auto& task : group.tasks()) { + ranges.emplace_back(task->start(), task->length()); + } + return ranges; +} + +TEST(ScanTaskPlanningTest, ResolveOptionsUsesDefaults) { + const std::unordered_map empty; + ICEBERG_UNWRAP_OR_FAIL(auto options, ResolveTaskGroupPlanningOptions(empty, empty)); + EXPECT_THAT(options.target_size, Eq(kDefaultTargetSize)); + EXPECT_THAT(options.lookback, Eq(kDefaultLookback)); + EXPECT_THAT(options.open_file_cost, Eq(kDefaultOpenFileCost)); +} + +TEST(ScanTaskPlanningTest, ResolveOptionsPrefersScanOptionOverTableProperty) { + const std::unordered_map scan_options{ + {"read.split.target-size", "1000"}}; + const std::unordered_map table_properties{ + {"read.split.target-size", "999"}}; + ICEBERG_UNWRAP_OR_FAIL(auto options, + ResolveTaskGroupPlanningOptions(scan_options, table_properties)); + EXPECT_THAT(options.target_size, Eq(1000)); +} + +TEST(ScanTaskPlanningTest, ResolveOptionsPrefersTablePropertyOverDefault) { + const std::unordered_map scan_options; + const std::unordered_map table_properties{ + {"read.split.planning-lookback", "3"}}; + ICEBERG_UNWRAP_OR_FAIL(auto options, + ResolveTaskGroupPlanningOptions(scan_options, table_properties)); + EXPECT_THAT(options.lookback, Eq(3)); +} + +TEST(ScanTaskPlanningTest, ResolveOptionsRejectsInvalidValues) { + const std::unordered_map empty; + const std::unordered_map malformed{ + {"read.split.target-size", "not-a-number"}}; + EXPECT_THAT(ResolveTaskGroupPlanningOptions(malformed, empty), + IsError(ErrorKind::kInvalidArgument)); + EXPECT_THAT(ResolveTaskGroupPlanningOptions(empty, malformed), + IsError(ErrorKind::kInvalidArgument)); + + for (const std::string& target : {"0", "-1"}) { + EXPECT_THAT( + ResolveTaskGroupPlanningOptions({{"read.split.target-size", target}}, empty), + IsError(ErrorKind::kInvalid)); + } + EXPECT_THAT(ResolveTaskGroupPlanningOptions( + {{"read.split.planning-lookback", "3000000000"}}, empty), + IsError(ErrorKind::kInvalidArgument)); + + for (const std::string& lookback : {"0", "-3"}) { + EXPECT_THAT(ResolveTaskGroupPlanningOptions( + {{"read.split.planning-lookback", lookback}}, empty), + IsError(ErrorKind::kInvalid)); + } + EXPECT_THAT( + ResolveTaskGroupPlanningOptions({{"read.split.open-file-cost", "-1"}}, empty), + IsError(ErrorKind::kInvalid)); +} + +TEST(ScanTaskPlanningTest, WeightMatchesJavaFormula) { + auto task = + MakeTask(MakeDataFile("file", 100), {MakeDeleteFile(50), MakeDeleteFile(30)}); + ICEBERG_UNWRAP_OR_FAIL(auto weight, TaskGroupWeight(*task, 10)); + // max(100 + 50 + 30, (1 + 2) * 10) = 180 + EXPECT_THAT(weight, Eq(180)); +} + +TEST(ScanTaskPlanningTest, WeightChargesOpenFileCost) { + auto task = MakeTask(MakeDataFile("file", 10)); + ICEBERG_UNWRAP_OR_FAIL(auto weight, TaskGroupWeight(*task, 1000)); + // max(10, (1 + 0) * 1000) = 1000 + EXPECT_THAT(weight, Eq(1000)); +} + +TEST(ScanTaskPlanningTest, WeightUsesDeletionVectorContentSize) { + auto task = MakeTask(MakeDataFile("file", 10), + {MakeDeleteFile(1000, /*content_size=*/40, /*puffin=*/true)}); + ICEBERG_UNWRAP_OR_FAIL(auto weight, TaskGroupWeight(*task, 0)); + // The deletion vector blob counts, not its 1000-byte container. + EXPECT_THAT(weight, Eq(50)); +} + +TEST(ScanTaskPlanningTest, WeightRejectsCostOverflow) { + const int64_t kMax = std::numeric_limits::max(); + auto task = MakeTask(MakeDataFile("file", kMax), {MakeDeleteFile(kMax)}); + EXPECT_THAT(TaskGroupWeight(*task, 0), IsError(ErrorKind::kInvalid)); +} + +TEST(ScanTaskPlanningTest, ParquetSplitsWithoutBundle) { + auto task = MakeTask(MakeDataFile("file", 250)); + ICEBERG_UNWRAP_OR_FAIL(auto groups, PlanAll({task}, Options(100))); + ASSERT_THAT(groups.size(), Eq(3)); + EXPECT_THAT(RangesOf(*groups[0]), ElementsAre(std::pair{0, 100})); + EXPECT_THAT(RangesOf(*groups[1]), ElementsAre(std::pair{100, 100})); + EXPECT_THAT(RangesOf(*groups[2]), ElementsAre(std::pair{200, 50})); +} + +TEST(ScanTaskPlanningTest, UnsplittableFormatKeepsLargeTaskWhole) { + auto avro = MakeDataFile("avro-file", 1000, {100, 500}); + avro->file_format = FileFormatType::kAvro; + auto task = MakeTask(std::move(avro)); + ICEBERG_UNWRAP_OR_FAIL(auto groups, PlanAll({task}, Options(100))); + ASSERT_THAT(groups.size(), Eq(1)); + ASSERT_THAT(groups[0]->tasks().size(), Eq(1)); + EXPECT_THAT(groups[0]->tasks()[0], Eq(task)); + EXPECT_FALSE(groups[0]->tasks()[0]->is_split()); +} + +TEST(ScanTaskPlanningTest, SmallParquetTaskStaysWhole) { + auto small = MakeTask(MakeDataFile("small", 500, {100, 200})); + ICEBERG_UNWRAP_OR_FAIL(auto groups, PlanAll({small}, Options(1000))); + ASSERT_THAT(groups.size(), Eq(1)); + EXPECT_THAT(groups[0]->tasks(), ElementsAre(small)); +} + +TEST(ScanTaskPlanningTest, SplitCoversFileExactlyAndCoalescesTowardTarget) { + auto file = MakeDataFile("file", 1000, {100, 250, 300}); + file->record_count = 100; + auto deletes = std::vector>{MakeDeleteFile(7)}; + const auto residual = Expressions::GreaterThan("id", Literal::Int(1)); + auto task = std::make_shared(file, deletes, residual); + + ICEBERG_UNWRAP_OR_FAIL(auto groups, PlanAll({task}, Options(120))); + // [0, 100) and [0, 250) coalesce to [0, 250); [250, 300) joins the tail + // [250, 1000). The ranges cover [0, 1000) exactly, including the bytes before + // the first boundary, and every range reaches the target size, so each packs + // as a singleton group. + ASSERT_THAT(groups.size(), Eq(2)); + EXPECT_THAT(RangesOf(*groups[0]), ElementsAre(std::pair{0, 250})); + EXPECT_THAT(RangesOf(*groups[1]), ElementsAre(std::pair{250, 750})); + + for (const auto& group : groups) { + for (const auto& split : group->tasks()) { + EXPECT_THAT(split->data_file(), Eq(file)); + EXPECT_THAT(split->delete_files(), ElementsAre(deletes[0])); + EXPECT_THAT(split->residual_filter(), Eq(residual)); + } + } + EXPECT_THAT(groups[0]->estimated_row_count() + groups[1]->estimated_row_count(), + Eq(100)); +} + +TEST(ScanTaskPlanningTest, BoundariesBelowTargetKeepFileWhole) { + auto task = MakeTask(MakeDataFile("file", 1000, {10})); + ICEBERG_UNWRAP_OR_FAIL(auto groups, PlanAll({task}, Options(100))); + ASSERT_THAT(groups.size(), Eq(1)); + ASSERT_THAT(groups[0]->tasks().size(), Eq(1)); + EXPECT_THAT(groups[0]->tasks()[0], Eq(task)); + EXPECT_FALSE(task->is_split()); +} + +TEST(ScanTaskPlanningTest, FixedSizeTailStaysWithinInt64FileRange) { + constexpr int64_t kFileSize = std::numeric_limits::max(); + constexpr int64_t kTarget = kFileSize / 2 + 1; + auto task = MakeTask(MakeDataFile("file", kFileSize)); + ICEBERG_UNWRAP_OR_FAIL(auto groups, PlanAll({task}, Options(kTarget, /*lookback=*/1))); + ASSERT_THAT(groups.size(), Eq(2)); + EXPECT_THAT(RangesOf(*groups[0]), ElementsAre(std::pair{0, kTarget})); + EXPECT_THAT(RangesOf(*groups[1]), + ElementsAre(std::pair{kTarget, kFileSize - kTarget})); +} + +TEST(ScanTaskPlanningTest, MixedFormatTasksShareOneGroup) { + auto avro_file = MakeDataFile("avro-file", 400); + avro_file->file_format = FileFormatType::kAvro; + auto avro = MakeTask(std::move(avro_file)); + auto parquet = MakeTask(MakeDataFile("parquet-file", 500)); + + ICEBERG_UNWRAP_OR_FAIL(auto groups, PlanAll({avro, parquet}, Options(1000))); + ASSERT_THAT(groups.size(), Eq(1)); + EXPECT_THAT(groups[0]->tasks(), ElementsAre(avro, parquet)); +} + +TEST(ScanTaskPlanningTest, EmptyFileStaysWhole) { + auto task = MakeTask(MakeDataFile("empty", 0)); + ICEBERG_UNWRAP_OR_FAIL(auto groups, PlanAll({task}, Options(100))); + ASSERT_THAT(groups.size(), Eq(1)); + EXPECT_THAT(groups[0]->tasks(), ElementsAre(task)); +} + +TEST(ScanTaskPlanningTest, AlreadySplitTaskPassesThrough) { + ICEBERG_UNWRAP_OR_FAIL( + auto split, + FileScanTask::MakeSplit(MakeDataFile("file", 1000, {100, 500}), 100, 50)); + ICEBERG_UNWRAP_OR_FAIL(auto groups, PlanAll({split}, Options(10))); + ASSERT_THAT(groups.size(), Eq(1)); + EXPECT_THAT(groups[0]->tasks(), ElementsAre(split)); +} + +TEST(ScanTaskPlanningTest, PackingFillsFirstGroupThatFits) { + auto a = MakeTask(MakeDataFile("a", 60)); + auto b = MakeTask(MakeDataFile("b", 70)); + auto c = MakeTask(MakeDataFile("c", 20)); + ICEBERG_UNWRAP_OR_FAIL(auto groups, PlanAll({a, b, c}, Options(100))); + ASSERT_THAT(groups.size(), Eq(2)); + EXPECT_THAT(groups[0]->tasks(), ElementsAre(a, c)); + EXPECT_THAT(groups[1]->tasks(), ElementsAre(b)); +} + +TEST(ScanTaskPlanningTest, PackingClosesLargestOpenGroupFirst) { + // With lookback 2, opening a third group closes the largest open group. + auto a = MakeTask(MakeDataFile("a", 100)); + auto b = MakeTask(MakeDataFile("b", 60)); + auto c = MakeTask(MakeDataFile("c", 60)); + ICEBERG_UNWRAP_OR_FAIL(auto groups, PlanAll({a, b, c}, Options(100, /*lookback=*/2))); + ASSERT_THAT(groups.size(), Eq(3)); + EXPECT_THAT(groups[0]->tasks(), ElementsAre(a)); + EXPECT_THAT(groups[1]->tasks(), ElementsAre(b)); + EXPECT_THAT(groups[2]->tasks(), ElementsAre(c)); +} + +TEST(ScanTaskPlanningTest, OversizedTaskFormsSingletonGroup) { + auto big = MakeTask(MakeDataFile("big", 80), {MakeDeleteFile(30)}); + auto small = MakeTask(MakeDataFile("small", 20)); + ICEBERG_UNWRAP_OR_FAIL(auto groups, + PlanAll({big, small}, Options(100, /*lookback=*/1))); + ASSERT_THAT(groups.size(), Eq(2)); + EXPECT_THAT(groups[0]->tasks(), ElementsAre(big)); + EXPECT_THAT(groups[1]->tasks(), ElementsAre(small)); +} + +TEST(ScanTaskPlanningTest, GroupHoldsAtMost1024Tasks) { + std::vector> tasks; + tasks.reserve(1025); + for (int i = 0; i < 1025; ++i) { + tasks.push_back(MakeTask(MakeDataFile("file-" + std::to_string(i), 1))); + } + ICEBERG_UNWRAP_OR_FAIL(auto groups, PlanAll(std::move(tasks), Options(2000))); + ASSERT_THAT(groups.size(), Eq(2)); + EXPECT_THAT(groups[0]->tasks().size(), Eq(1024)); + EXPECT_THAT(groups[1]->tasks().size(), Eq(1)); +} + +TEST(ScanTaskPlanningTest, GroupSumsTaskMetrics) { + auto first = MakeTask(MakeDataFile("first", 30)); + auto second = MakeTask(MakeDataFile("second", 20, {10})); + ICEBERG_UNWRAP_OR_FAIL(auto groups, PlanAll({first, second}, Options(100))); + ASSERT_THAT(groups.size(), Eq(1)); + const auto& group = *groups[0]; + EXPECT_THAT(group.kind(), Eq(ScanTask::Kind::kFileScanTaskGroup)); + EXPECT_THAT(group.size_bytes(), Eq(50)); + // FileScanTask::files_count() counts one file per task in this version. + EXPECT_THAT(group.files_count(), Eq(2)); + EXPECT_THAT(group.estimated_row_count(), Eq(20)); +} + +TEST(ScanTaskPlanningTest, CostOverflowSurfacesPlanningError) { + const int64_t kMax = std::numeric_limits::max(); + auto task = MakeTask(MakeDataFile("file", kMax), {MakeDeleteFile(kMax)}); + ICEBERG_UNWRAP_OR_FAIL(auto stream, + PlanTaskGroupStream(TaskStream({task}), Options(100))); + auto group = stream->Next(); + ASSERT_FALSE(group.has_value()); + EXPECT_THAT(group, IsError(ErrorKind::kInvalid)); +} + +TEST(ScanTaskPlanningTest, EmptyTaskStreamProducesNoGroups) { + ICEBERG_UNWRAP_OR_FAIL(auto stream, PlanTaskGroupStream(TaskStream({}), Options(100))); + ICEBERG_UNWRAP_OR_FAIL(auto group, stream->Next()); + EXPECT_FALSE(group.has_value()); +} + +TEST(ScanTaskPlanningTest, PlanRejectsInvalidOptions) { + auto tasks = TaskStream({}); + EXPECT_THAT(PlanTaskGroupStream(std::move(tasks), Options(0)), + IsError(ErrorKind::kInvalid)); + + tasks = TaskStream({}); + EXPECT_THAT(PlanTaskGroupStream(std::move(tasks), Options(100, /*lookback=*/0)), + IsError(ErrorKind::kInvalid)); + + tasks = TaskStream({}); + EXPECT_THAT( + PlanTaskGroupStream(std::move(tasks), Options(100, 10, /*open_file_cost=*/-1)), + IsError(ErrorKind::kInvalid)); +} + +TEST(ScanTaskPlanningTest, StreamStopsEarlyWithoutConsumingAllGroups) { + auto a = MakeTask(MakeDataFile("a", 100)); + auto b = MakeTask(MakeDataFile("b", 60)); + auto c = MakeTask(MakeDataFile("c", 60)); + ICEBERG_UNWRAP_OR_FAIL(auto stream, + PlanTaskGroupStream(TaskStream({a, b, c}), Options(100, 2))); + { + ICEBERG_UNWRAP_OR_FAIL(auto group, stream->Next()); + ASSERT_TRUE(group.has_value()); + EXPECT_THAT((*group)->tasks(), ElementsAre(a)); + } + // Destroying the stream mid-consumption releases the task stream. +} + +} // namespace +} // namespace iceberg::internal diff --git a/src/iceberg/test/table_scan_test.cc b/src/iceberg/test/table_scan_test.cc index 40b51bd5e..a71031bd8 100644 --- a/src/iceberg/test/table_scan_test.cc +++ b/src/iceberg/test/table_scan_test.cc @@ -17,22 +17,35 @@ * under the License. */ +#include #include #include +#include #include #include #include +#include #include +#include +#include +#include +#include #include #include +#include "iceberg/data/data_writer.h" +#include "iceberg/data/file_scan_task_reader.h" #include "iceberg/data_table_scan.h" #include "iceberg/expression/expressions.h" +#include "iceberg/parquet/parquet_register.h" +#include "iceberg/schema_internal.h" #include "iceberg/snapshot.h" #include "iceberg/table_metadata.h" +#include "iceberg/table_properties.h" #include "iceberg/test/executor.h" #include "iceberg/test/scan_test_base.h" +#include "iceberg/util/macros.h" namespace iceberg { @@ -79,6 +92,86 @@ class TableScanTest : public ScanTestBase { .retention = SnapshotRef::Branch{}})}}}); } + /// \brief Write a real Parquet data file into the mock file IO and return its + /// manifest entry data file. + Result> WriteParquetDataFile(const std::string& path, + int64_t row_count, + int64_t max_row_group_rows) { + std::string rows = "["; + for (int64_t row = 0; row < row_count; ++row) { + if (row > 0) { + rows += ","; + } + rows += std::format("[{},\"value-{}\"]", row, row % 10); + } + rows += "]"; + + ArrowSchema arrow_c_schema; + ICEBERG_THROW_NOT_OK(ToArrowSchema(*schema_, &arrow_c_schema)); + auto arrow_schema = ::arrow::ImportType(&arrow_c_schema).ValueOrDie(); + auto array = + ::arrow::json::ArrayFromJSONString(::arrow::struct_(arrow_schema->fields()), rows) + .ValueOrDie(); + + struct ExportedArray { + ArrowArray array{}; + ~ExportedArray() { + if (array.release != nullptr) { + array.release(&array); + } + } + } exported; + if (!::arrow::ExportArray(*array, &exported.array).ok()) { + return Invalid("Failed to export test batch for {}", path); + } + + ICEBERG_ASSIGN_OR_RAISE( + auto writer, + DataWriter::Make({.path = path, + .schema = schema_, + .spec = unpartitioned_spec_, + .partition = PartitionValues{}, + .format = FileFormatType::kParquet, + .io = file_io_, + .properties = {{"write.parquet.max-row-group-rows", + std::to_string(max_row_group_rows)}}})); + ICEBERG_RETURN_UNEXPECTED(writer->Write(&exported.array)); + ICEBERG_RETURN_UNEXPECTED(writer->Close()); + ICEBERG_ASSIGN_OR_RAISE(auto result, writer->Metadata()); + if (result.data_files.empty()) { + return Invalid("Data writer produced no data file for {}", path); + } + return result.data_files[0]; + } + + /// \brief Write manifests for the given entries and build a table metadata whose + /// single snapshot references them. + std::shared_ptr MakeTaskPlanningMetadata( + std::vector data_entries, + std::vector delete_entries = {}) { + constexpr int64_t kSnapshotId = 1000L; + constexpr int64_t kSequenceNumber = 1L; + + std::vector manifests; + manifests.push_back(WriteDataManifest(GetParam(), kSnapshotId, + std::move(data_entries), unpartitioned_spec_)); + if (!delete_entries.empty()) { + manifests.push_back(WriteDeleteManifest( + GetParam(), kSnapshotId, std::move(delete_entries), unpartitioned_spec_)); + } + std::string manifest_list_path = + WriteManifestList(GetParam(), kSnapshotId, kSequenceNumber, std::move(manifests)); + auto snapshot = std::make_shared( + Snapshot{.snapshot_id = kSnapshotId, + .parent_snapshot_id = std::nullopt, + .sequence_number = kSequenceNumber, + .timestamp_ms = TimePointMsFromUnixMs(1609459200000L), + .manifest_list = manifest_list_path, + .schema_id = schema_->schema_id()}); + return ScanTestBase::MakeTableMetadata({snapshot}, kSnapshotId, {}, + unpartitioned_spec_); + } + std::shared_ptr MakePositionDeleteFile( const std::string& path, const PartitionValues& partition, int32_t spec_id, std::optional referenced_file = std::nullopt) { @@ -858,6 +951,266 @@ TEST_P(TableScanTest, SchemaWithSelectedColumnsAndFilter) { } } +namespace { + +// A data file for split-planning tests. The path need not exist. +std::shared_ptr MakeSplitPlanningDataFile(const std::string& path, + int64_t file_size, + std::vector split_offsets, + int64_t record_count) { + auto file = std::make_shared(); + file->file_path = path; + file->file_format = FileFormatType::kParquet; + file->record_count = record_count; + file->file_size_in_bytes = file_size; + file->split_offsets = std::move(split_offsets); + file->sort_order_id = 0; + file->partition_spec_id = 0; + return file; +} + +std::vector> CollectGroupRanges( + const std::vector>& groups) { + std::vector> ranges; + for (const auto& group : groups) { + for (const auto& task : group->tasks()) { + ranges.emplace_back(task->start(), task->length()); + } + } + return ranges; +} + +} // namespace + +TEST_P(TableScanTest, PlanTasksWithManifestSplitOffsets) { + auto metadata = MakeTaskPlanningMetadata({MakeEntry( + ManifestStatus::kAdded, 1000L, 1L, + MakeSplitPlanningDataFile("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/missing/data.parquet", 3000, {1200, 2300}, 30))}); + + ICEBERG_UNWRAP_OR_FAIL(auto builder, MakeScanBuilder(metadata)); + builder->Option("read.split.target-size", "1000"); + ICEBERG_UNWRAP_OR_FAIL(auto scan, builder->Build()); + ICEBERG_UNWRAP_OR_FAIL(auto groups, scan->PlanTasks()); + + // These boundaries differ from the fixed-size fallback. + ASSERT_THAT(groups.size(), testing::Eq(3)); + EXPECT_THAT(CollectGroupRanges(groups), + testing::ElementsAre(std::pair{0, 1200}, + std::pair{1200, 1100}, + std::pair{2300, 700})); + for (const auto& group : groups) { + ASSERT_THAT(group->tasks().size(), testing::Eq(1)); + EXPECT_TRUE(group->tasks()[0]->is_split()); + EXPECT_THAT(group->tasks()[0]->data_file()->file_path, + testing::Eq("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/missing/data.parquet")); + } +} + +TEST_P(TableScanTest, PlanTasksUsesFixedByteRangesWithoutUsableManifestOffsets) { + // The data file does not exist. Neither absent nor unusable offsets need a footer. + for (const auto& offsets : + std::vector>{{}, {1200, 1200}, {1200, 1100}, {1200, 2600}}) { + auto metadata = MakeTaskPlanningMetadata({MakeEntry( + ManifestStatus::kAdded, 1000L, 1L, + MakeSplitPlanningDataFile("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/missing/data.parquet", 2600, offsets, 26))}); + ICEBERG_UNWRAP_OR_FAIL(auto builder, MakeScanBuilder(metadata)); + builder->Option("read.split.target-size", "1000"); + builder->Option("read.split.planning-lookback", "1"); + ICEBERG_UNWRAP_OR_FAIL(auto scan, builder->Build()); + ICEBERG_UNWRAP_OR_FAIL(auto groups, scan->PlanTasks()); + EXPECT_THAT(CollectGroupRanges(groups), + testing::ElementsAre(std::pair{0, 1000}, + std::pair{1000, 1000}, + std::pair{2000, 600})); + } +} + +TEST_P(TableScanTest, FixedByteRangesReadEveryParquetRowOnce) { + parquet::RegisterAll(); + + constexpr int32_t kRows = 200; + ICEBERG_UNWRAP_OR_FAIL(auto entry_file, + WriteParquetDataFile("planned-data.parquet", kRows, 50)); + ASSERT_GT(entry_file->split_offsets.size(), 1); + entry_file->split_offsets.clear(); + auto metadata = MakeTaskPlanningMetadata( + {MakeEntry(ManifestStatus::kAdded, 1000L, 1L, entry_file)}); + + const int64_t target = entry_file->file_size_in_bytes / 4; + ICEBERG_UNWRAP_OR_FAIL(auto builder, MakeScanBuilder(metadata)); + builder->Option("read.split.target-size", std::to_string(target)); + builder->Option("read.split.planning-lookback", "1"); + ICEBERG_UNWRAP_OR_FAIL(auto scan, builder->Build()); + ICEBERG_UNWRAP_OR_FAIL(auto groups, scan->PlanTasks()); + + ICEBERG_UNWRAP_OR_FAIL( + auto reader, + FileScanTaskReader::Make( + {.io = file_io_, .table_schema = schema_, .projected_schema = schema_})); + std::vector ids; + for (const auto& group : groups) { + for (const auto& task : group->tasks()) { + ICEBERG_UNWRAP_OR_FAIL(auto stream, reader->Open(*task)); + auto batches = ::arrow::ImportRecordBatchReader(&stream).ValueOrDie(); + for (auto next : *batches) { + ASSERT_TRUE(next.ok()) << next.status(); + const auto& column = static_cast(*(*next)->column(0)); + for (int64_t row = 0; row < column.length(); ++row) { + ids.push_back(column.Value(row)); + } + } + } + } + std::ranges::sort(ids); + std::vector expected(kRows); + std::ranges::iota(expected, 0); + EXPECT_EQ(ids, expected); +} + +TEST_P(TableScanTest, PlanTasksKeepsFilesAtOrBelowTargetWholeWithoutOffsets) { + for (int64_t file_size : {900, 1000}) { + auto metadata = MakeTaskPlanningMetadata({MakeEntry( + ManifestStatus::kAdded, 1000L, 1L, + MakeSplitPlanningDataFile("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/missing/small.parquet", file_size, {}, 10))}); + ICEBERG_UNWRAP_OR_FAIL(auto builder, MakeScanBuilder(metadata)); + builder->Option("read.split.target-size", "1000"); + ICEBERG_UNWRAP_OR_FAIL(auto scan, builder->Build()); + ICEBERG_UNWRAP_OR_FAIL(auto groups, scan->PlanTasks()); + ASSERT_THAT(groups.size(), testing::Eq(1)); + ASSERT_THAT(groups[0]->tasks().size(), testing::Eq(1)); + EXPECT_FALSE(groups[0]->tasks()[0]->is_split()); + EXPECT_EQ(groups[0]->tasks()[0]->length(), file_size); + } +} + +TEST_P(TableScanTest, PlanTasksSettingsResolveScanOptionThenTableProperty) { + auto metadata = MakeTaskPlanningMetadata({MakeEntry( + ManifestStatus::kAdded, 1000L, 1L, + MakeSplitPlanningDataFile("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/missing/data.parquet", 3000, {1000, 2000}, 30))}); + metadata->properties = TableProperties::FromMap({{"read.split.target-size", "1000"}}); + + // The table property applies when the scan sets no option. + { + ICEBERG_UNWRAP_OR_FAIL(auto builder, MakeScanBuilder(metadata)); + ICEBERG_UNWRAP_OR_FAIL(auto scan, builder->Build()); + ICEBERG_UNWRAP_OR_FAIL(auto groups, scan->PlanTasks()); + ASSERT_THAT(groups.size(), testing::Eq(3)); + } + + // The scan option wins over the table property. + { + ICEBERG_UNWRAP_OR_FAIL(auto builder, MakeScanBuilder(metadata)); + builder->Option("read.split.target-size", "5000"); + ICEBERG_UNWRAP_OR_FAIL(auto scan, builder->Build()); + ICEBERG_UNWRAP_OR_FAIL(auto groups, scan->PlanTasks()); + ASSERT_THAT(groups.size(), testing::Eq(1)); + ASSERT_THAT(groups[0]->tasks().size(), testing::Eq(1)); + EXPECT_FALSE(groups[0]->tasks()[0]->is_split()); + } + + // A malformed scan option fails planning. + { + ICEBERG_UNWRAP_OR_FAIL(auto builder, MakeScanBuilder(metadata)); + builder->Option("read.split.target-size", "not-a-number"); + ICEBERG_UNWRAP_OR_FAIL(auto scan, builder->Build()); + EXPECT_THAT(scan->PlanTasksStream(), IsError(ErrorKind::kInvalidArgument)); + } + + // An invalid table property fails planning when the scan sets no option. + { + auto invalid_metadata = MakeTaskPlanningMetadata({MakeEntry( + ManifestStatus::kAdded, 1000L, 1L, + MakeSplitPlanningDataFile("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/missing/data.parquet", 3000, {1000, 2000}, 30))}); + invalid_metadata->properties = + TableProperties::FromMap({{"read.split.target-size", "0"}}); + ICEBERG_UNWRAP_OR_FAIL(auto builder, + MakeScanBuilder(invalid_metadata)); + ICEBERG_UNWRAP_OR_FAIL(auto scan, builder->Build()); + EXPECT_THAT(scan->PlanTasksStream(), IsError(ErrorKind::kInvalid)); + } +} + +TEST_P(TableScanTest, PlanTasksWithNoSnapshot) { + auto empty_metadata = std::make_shared( + TableMetadata{.format_version = GetParam(), + .schemas = {schema_}, + .current_schema_id = schema_->schema_id(), + .partition_specs = {unpartitioned_spec_}, + .default_spec_id = unpartitioned_spec_->spec_id(), + .current_snapshot_id = -1, + .snapshots = {}, + .refs = {}}); + + ICEBERG_UNWRAP_OR_FAIL(auto builder, MakeScanBuilder(empty_metadata)); + ICEBERG_UNWRAP_OR_FAIL(auto scan, builder->Build()); + ICEBERG_UNWRAP_OR_FAIL(auto groups, scan->PlanTasks()); + EXPECT_TRUE(groups.empty()); + + ICEBERG_UNWRAP_OR_FAIL(auto stream, scan->PlanTasksStream()); + ICEBERG_UNWRAP_OR_FAIL(auto next, stream->Next()); + EXPECT_FALSE(next.has_value()); +} + +TEST_P(TableScanTest, PlanTasksStreamConsumesGroupsIncrementally) { + auto metadata = MakeTaskPlanningMetadata({MakeEntry( + ManifestStatus::kAdded, 1000L, 1L, + MakeSplitPlanningDataFile("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/missing/data.parquet", 3000, {1000, 2000}, 30))}); + + ICEBERG_UNWRAP_OR_FAIL(auto builder, MakeScanBuilder(metadata)); + builder->Option("read.split.target-size", "1000"); + builder->Option("read.split.planning-lookback", "1"); + ICEBERG_UNWRAP_OR_FAIL(auto scan, builder->Build()); + + { + // Destroying the stream after one group releases the planning resources. + ICEBERG_UNWRAP_OR_FAIL(auto stream, scan->PlanTasksStream()); + ICEBERG_UNWRAP_OR_FAIL(auto group, stream->Next()); + ASSERT_TRUE(group.has_value()); + EXPECT_THAT((*group)->tasks().size(), testing::Eq(1)); + } + + ICEBERG_UNWRAP_OR_FAIL(auto stream, scan->PlanTasksStream()); + int64_t expected_start = 0; + while (true) { + ICEBERG_UNWRAP_OR_FAIL(auto group, stream->Next()); + if (!group.has_value()) { + break; + } + ASSERT_THAT((*group)->tasks().size(), testing::Eq(1)); + const auto& task = (*group)->tasks()[0]; + EXPECT_THAT(task->start(), testing::Eq(expected_start)); + expected_start += task->length(); + } + EXPECT_THAT(expected_start, testing::Eq(3000)); +} + +TEST_P(TableScanTest, PlanTasksCarriesDeleteFilesIntoSplits) { + if (GetParam() < 2) { + GTEST_SKIP() << "delete manifests require format version 2"; + } + const std::string data_path = "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/missing/data-with-deletes.parquet"; + auto metadata = MakeTaskPlanningMetadata( + {MakeEntry(ManifestStatus::kAdded, 1000L, 1L, + MakeSplitPlanningDataFile(data_path, 3000, {1000, 2000}, 30))}, + {MakeEntry(ManifestStatus::kAdded, 1000L, 1L, + MakePositionDeleteFile("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/missing/pos-deletes.parquet", + PartitionValues(std::vector{}), + unpartitioned_spec_->spec_id(), data_path))}); + + ICEBERG_UNWRAP_OR_FAIL(auto builder, MakeScanBuilder(metadata)); + builder->Option("read.split.target-size", "1000"); + ICEBERG_UNWRAP_OR_FAIL(auto scan, builder->Build()); + ICEBERG_UNWRAP_OR_FAIL(auto groups, scan->PlanTasks()); + + ASSERT_THAT(groups.size(), testing::Eq(3)); + for (const auto& group : groups) { + ASSERT_THAT(group->tasks().size(), testing::Eq(1)); + ASSERT_THAT(group->tasks()[0]->delete_files().size(), testing::Eq(1u)); + EXPECT_THAT(group->tasks()[0]->delete_files()[0]->file_path, + testing::Eq("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/missing/pos-deletes.parquet")); + } +} + INSTANTIATE_TEST_SUITE_P(TableScanVersions, TableScanTest, testing::Values(1, 2, 3)); } // namespace iceberg