wgtmac commented on code in PR #1113: URL: https://github.com/apache/iceberg-cpp/pull/1113#discussion_r4658639324
########## src/iceberg/scan_task_planning.cc: ########## @@ -0,0 +1,323 @@ +/* + * 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 <algorithm> +#include <cstdint> +#include <deque> +#include <limits> +#include <mutex> +#include <unordered_map> +#include <utility> +#include <vector> + +#include "iceberg/result.h" +#include "iceberg/scan_task_planning_internal.h" +#include "iceberg/table_properties.h" +#include "iceberg/util/int128.h" +#include "iceberg/util/string_util.h" + +namespace iceberg::internal { + +namespace { + +std::mutex& SplitPolicyMutex() { + static std::mutex mutex; + return mutex; +} + +std::unordered_map<FileFormatType, std::unique_ptr<SplitPolicy>>& SplitPolicies() { + static std::unordered_map<FileFormatType, std::unique_ptr<SplitPolicy>> policies; + return policies; +} + +template <typename T> +Result<T> ResolveValue( + const std::string& key, T default_value, + const std::unordered_map<std::string, std::string>& scan_options, + const std::unordered_map<std::string, std::string>& table_properties) { + for (const auto* source : {&scan_options, &table_properties}) { + auto value = source->find(key); + if (value != source->end()) { + return StringUtils::ParseNumber<T>(value->second); + } + } + return default_value; +} + +int128_t DeleteContentBytes(const FileScanTask& task) { + int128_t total = 0; + for (const auto& delete_file : task.delete_files()) { + int64_t size = delete_file->file_size_in_bytes; Review Comment: Reuse `ContentFileUtil::ContentSizeInBytes()` here and keep the `int128_t` accumulator. ########## src/iceberg/scan_task_planning.cc: ########## @@ -0,0 +1,323 @@ +/* + * 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 <algorithm> +#include <cstdint> +#include <deque> +#include <limits> +#include <mutex> +#include <unordered_map> +#include <utility> +#include <vector> + +#include "iceberg/result.h" +#include "iceberg/scan_task_planning_internal.h" +#include "iceberg/table_properties.h" +#include "iceberg/util/int128.h" +#include "iceberg/util/string_util.h" + +namespace iceberg::internal { + +namespace { + +std::mutex& SplitPolicyMutex() { + static std::mutex mutex; + return mutex; +} + +std::unordered_map<FileFormatType, std::unique_ptr<SplitPolicy>>& SplitPolicies() { + static std::unordered_map<FileFormatType, std::unique_ptr<SplitPolicy>> policies; + return policies; +} + +template <typename T> +Result<T> ResolveValue( + const std::string& key, T default_value, + const std::unordered_map<std::string, std::string>& scan_options, + const std::unordered_map<std::string, std::string>& table_properties) { + for (const auto* source : {&scan_options, &table_properties}) { + auto value = source->find(key); + if (value != source->end()) { + return StringUtils::ParseNumber<T>(value->second); + } + } + return default_value; +} + +int128_t DeleteContentBytes(const FileScanTask& task) { + int128_t total = 0; + for (const auto& delete_file : task.delete_files()) { + int64_t size = delete_file->file_size_in_bytes; + // A deletion vector stores a blob inside a larger container; charge the blob, + // like Java's ScanTaskUtil.contentSizeInBytes. + if (delete_file->file_format == FileFormatType::kPuffin && + delete_file->content_size_in_bytes.has_value()) { + size = *delete_file->content_size_in_bytes; + } + total += size; + } + return total; +} + +// One group that is still open while packing. Mirrors Java's BinPacking.Bin. +struct OpenGroup { + std::vector<std::shared_ptr<FileScanTask>> tasks; + int128_t weight = 0; + int64_t count = 0; +}; + +} // namespace + +void SplitPolicyRegistry::Register(FileFormatType format, + std::unique_ptr<SplitPolicy> policy) { + std::lock_guard lock(SplitPolicyMutex()); + SplitPolicies()[format] = std::move(policy); +} + +void SplitPolicyRegistry::Unregister(FileFormatType format) { + std::lock_guard lock(SplitPolicyMutex()); + SplitPolicies().erase(format); +} + +SplitPolicy* SplitPolicyRegistry::Find(FileFormatType format) { + std::lock_guard lock(SplitPolicyMutex()); + auto policy = SplitPolicies().find(format); + return policy == SplitPolicies().end() ? nullptr : policy->second.get(); +} + +Result<TaskGroupPlanningOptions> ResolveTaskGroupPlanningOptions( + const std::unordered_map<std::string, std::string>& scan_options, + const std::unordered_map<std::string, std::string>& table_properties) { + using TableProps = TableProperties; + ICEBERG_ASSIGN_OR_RAISE( + auto target_size, + ResolveValue<int64_t>(TableProps::kSplitSize.key(), TableProps::kSplitSize.value(), + scan_options, table_properties)); + ICEBERG_ASSIGN_OR_RAISE(auto lookback, + ResolveValue<int32_t>(TableProps::kSplitLookback.key(), + TableProps::kSplitLookback.value(), + scan_options, table_properties)); + ICEBERG_ASSIGN_OR_RAISE(auto open_file_cost, + ResolveValue<int64_t>(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<int64_t> TaskGroupWeight(const FileScanTask& task, int64_t open_file_cost) { + const int128_t content_cost = + static_cast<int128_t>(task.length()) + DeleteContentBytes(task); + const int128_t open_cost = + (static_cast<int128_t>(task.delete_files().size()) + 1) * open_file_cost; + const auto weight = std::max(content_cost, open_cost); + if (weight > std::numeric_limits<int64_t>::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<int64_t>(weight); +} + +Result<std::vector<std::shared_ptr<FileScanTask>>> SplitFileScanTask( + const std::shared_ptr<FileScanTask>& task, int64_t target_size, + const std::shared_ptr<FileIO>& io) { + const int64_t length = task->length(); + if (task->is_split() || length <= target_size) { + return std::vector<std::shared_ptr<FileScanTask>>{task}; + } + + SplitPolicy* policy = SplitPolicyRegistry::Find(task->data_file()->file_format); + if (policy == nullptr) { + return std::vector<std::shared_ptr<FileScanTask>>{task}; + } + ICEBERG_ASSIGN_OR_RAISE(auto boundaries, + policy->SplitBoundaries(io, *task->data_file())); + auto make_split = [&](int64_t start, int64_t split_length) { + return FileScanTask::MakeSplit(task->data_file(), start, split_length, + task->delete_files(), task->residual_filter()); + }; + + // Coalesce adjacent boundary intervals toward the target size. The first range + // starts at zero, so the ranges cover [0, file size) exactly, including the bytes + // before the first boundary. + std::vector<std::shared_ptr<FileScanTask>> splits; + int64_t split_start = 0; + for (int64_t boundary : boundaries) { + if (boundary - split_start >= target_size) { + ICEBERG_ASSIGN_OR_RAISE(auto split, + make_split(split_start, boundary - split_start)); + splits.push_back(std::move(split)); + split_start = boundary; + } + } + if (splits.empty()) { + // No boundary is far enough from the start to reach the target size; the file + // stays whole, like a file with a single huge row group. + return std::vector<std::shared_ptr<FileScanTask>>{task}; + } + if (split_start < length) { + ICEBERG_ASSIGN_OR_RAISE(auto tail, make_split(split_start, length - split_start)); + splits.push_back(std::move(tail)); + } + return splits; +} + +namespace { + +// 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<std::optional<std::shared_ptr<FileScanTaskGroup>>> Add( + std::shared_ptr<FileScanTask> 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<std::shared_ptr<FileScanTaskGroup>>{CloseLargestGroup()}; + } + return std::nullopt; + } + + /// Returns the next remaining group after the input ends, or std::nullopt when all + /// groups have been returned. + std::optional<std::shared_ptr<FileScanTaskGroup>> NextRemainingGroup() { + if (open_groups_.empty()) { + return std::nullopt; + } + std::vector<std::shared_ptr<FileScanTask>> tasks = + std::move(open_groups_.front().tasks); + open_groups_.pop_front(); + return std::make_shared<FileScanTaskGroup>(std::move(tasks)); + } + + private: + std::shared_ptr<FileScanTaskGroup> 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<std::shared_ptr<FileScanTask>> tasks = std::move(largest->tasks); + open_groups_.erase(largest); + return std::make_shared<FileScanTaskGroup>(std::move(tasks)); + } + + TaskGroupPlanningOptions options_; + std::deque<OpenGroup> 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, + std::shared_ptr<FileIO> io) + : tasks_(std::move(tasks)), + options_(options), + packer_(options), + io_(std::move(io)) {} + + Result<std::optional<std::shared_ptr<FileScanTaskGroup>>> NextImpl() override { + while (true) { + if (input_exhausted_) { + return packer_.NextRemainingGroup(); + } + ICEBERG_ASSIGN_OR_RAISE(auto task, tasks_->Next()); + if (!task.has_value()) { + input_exhausted_ = true; + continue; + } + ICEBERG_ASSIGN_OR_RAISE(auto splits, + SplitFileScanTask(*task, options_.target_size, io_)); + for (auto& split : splits) { + ICEBERG_ASSIGN_OR_RAISE(auto group, packer_.Add(std::move(split))); + if (group.has_value()) { + return group; Review Comment: With lookback 1 and three target-sized splits from one file, the second split closes the first group. Returning here destroys the local `splits` vector, so the third split is never scheduled. Can we keep a per-file split cursor across `Next()` calls and add a regression for this case? ########## src/iceberg/parquet/parquet_split_policy.cc: ########## @@ -0,0 +1,86 @@ +/* + * 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 <cstdint> +#include <memory> +#include <utility> +#include <vector> + +#include <parquet/file_reader.h> + +#include "iceberg/arrow/arrow_io_internal.h" +#include "iceberg/manifest/manifest_entry.h" +#include "iceberg/parquet/parquet_data_util_internal.h" +#include "iceberg/parquet/parquet_register.h" +#include "iceberg/result.h" +#include "iceberg/scan_task_planning_internal.h" + +namespace iceberg::parquet { + +namespace { + +// Manifest split offsets are usable when they are present, strictly increasing, and +// inside the file. Usable offsets are returned without reading the file. +Result<std::vector<int64_t>> ManifestSplitBoundaries(const DataFile& file) { + std::vector<int64_t> boundaries; + int64_t previous = 0; + for (int64_t offset : file.split_offsets) { + if (offset <= previous || offset >= file.file_size_in_bytes) { + return std::vector<int64_t>{}; + } + boundaries.push_back(offset); + previous = offset; + } + return boundaries; +} + +class ParquetSplitPolicy final : public internal::SplitPolicy { + public: + Result<std::vector<int64_t>> SplitBoundaries(const std::shared_ptr<FileIO>& io, + const DataFile& file) override { + ICEBERG_ASSIGN_OR_RAISE(auto manifest_boundaries, ManifestSplitBoundaries(file)); + if (!manifest_boundaries.empty()) { + return manifest_boundaries; + } + + // Manifest offsets are missing or unusable: inspect the footer once and use the + // canonical row-group starts. Boundaries that differ from read offsets cost + // balance, not correctness, because reads assign row groups by midpoint. + ICEBERG_ASSIGN_OR_RAISE(auto input, arrow::OpenArrowInputStream(io, file.file_path)); + auto reader = ::parquet::ParquetFileReader::Open(input); Review Comment: Can we follow Java’s fallback when manifest offsets are unavailable or unusable? Keep files at or below the target whole and generate target-sized byte ranges lazily for larger Parquet files. The reader already assigns row groups by midpoint, so the planner can work from manifest metadata alone and drop its `FileIO` dependency and split-policy registry. [Java fallback](https://github.com/apache/iceberg/blob/0ff724da9d835b11de2a472e80ddc45245c4010d/core/src/main/java/org/apache/iceberg/BaseContentScanTask.java#L99-L116) ########## src/iceberg/test/scan_task_planning_test.cc: ########## @@ -0,0 +1,459 @@ +/* + * 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 <cstdint> +#include <limits> +#include <memory> +#include <optional> +#include <string> +#include <unordered_map> +#include <utility> +#include <vector> + +#include <gmock/gmock.h> +#include <gtest/gtest.h> + +#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<DataFile> MakeDataFile(const std::string& path, int64_t file_size, + std::vector<int64_t> split_offsets = {}) { + auto file = std::make_shared<DataFile>(); + 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<DataFile> MakeDeleteFile(int64_t file_size, + std::optional<int64_t> content_size = {}, + bool puffin = false) { + auto file = std::make_shared<DataFile>(); + 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<FileScanTask> MakeTask( + std::shared_ptr<DataFile> file, std::vector<std::shared_ptr<DataFile>> deletes = {}) { + return std::make_shared<FileScanTask>(std::move(file), std::move(deletes)); +} + +FileScanTaskStreamPtr TaskStream(std::vector<std::shared_ptr<FileScanTask>> 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<std::vector<std::shared_ptr<FileScanTaskGroup>>> PlanAll( + std::vector<std::shared_ptr<FileScanTask>> tasks, + const TaskGroupPlanningOptions& options) { + ICEBERG_ASSIGN_OR_RAISE( + auto stream, PlanTaskGroupStream(TaskStream(std::move(tasks)), options, nullptr)); + std::vector<std::shared_ptr<FileScanTaskGroup>> 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<std::pair<int64_t, int64_t>> RangesOf(const FileScanTaskGroup& group) { + std::vector<std::pair<int64_t, int64_t>> ranges; + for (const auto& task : group.tasks()) { + ranges.emplace_back(task->start(), task->length()); + } + return ranges; +} + +// A split policy with fixed boundaries that counts how often it is consulted. +class CountingSplitPolicy final : public SplitPolicy { + public: + explicit CountingSplitPolicy(std::vector<int64_t> boundaries) + : boundaries_(std::move(boundaries)) {} + + Result<std::vector<int64_t>> SplitBoundaries(const std::shared_ptr<FileIO>&, + const DataFile&) override { + ++calls_; + return boundaries_; + } + + int calls() const { return calls_; } + + private: + std::vector<int64_t> boundaries_; + int calls_ = 0; +}; + +// Registers a policy for a format and unregisters it when the test ends. +class ScopedSplitPolicy { + public: + ScopedSplitPolicy(FileFormatType format, std::unique_ptr<SplitPolicy> policy) + : format_(format) { + SplitPolicyRegistry::Register(format_, std::move(policy)); + } + + ~ScopedSplitPolicy() { SplitPolicyRegistry::Unregister(format_); } + + private: + FileFormatType format_; +}; + +class ScanTaskPlanningTest : public ::testing::Test { + protected: + void SetUp() override { + // Core-only builds have no registered policies; make bundled builds match by + // removing anything registered before the test. + SplitPolicyRegistry::Unregister(FileFormatType::kParquet); + } + + ~ScanTaskPlanningTest() override { + SplitPolicyRegistry::Unregister(FileFormatType::kParquet); + } +}; + +TEST_F(ScanTaskPlanningTest, ResolveOptionsUsesDefaults) { + const std::unordered_map<std::string, std::string> 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_F(ScanTaskPlanningTest, ResolveOptionsPrefersScanOptionOverTableProperty) { + const std::unordered_map<std::string, std::string> scan_options{ + {"read.split.target-size", "1000"}}; + const std::unordered_map<std::string, std::string> 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_F(ScanTaskPlanningTest, ResolveOptionsPrefersTablePropertyOverDefault) { + const std::unordered_map<std::string, std::string> scan_options; + const std::unordered_map<std::string, std::string> 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_F(ScanTaskPlanningTest, ResolveOptionsRejectsInvalidValues) { + const std::unordered_map<std::string, std::string> empty; + const std::unordered_map<std::string, std::string> 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_F(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_F(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_F(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_F(ScanTaskPlanningTest, WeightRejectsCostOverflow) { + const int64_t kMax = std::numeric_limits<int64_t>::max(); + auto task = MakeTask(MakeDataFile("file", kMax), {MakeDeleteFile(kMax)}); + EXPECT_THAT(TaskGroupWeight(*task, 0), IsError(ErrorKind::kInvalid)); +} + +TEST_F(ScanTaskPlanningTest, NoPolicyKeepsLargeTaskWhole) { + auto task = MakeTask(MakeDataFile("file", 1000)); + 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_F(ScanTaskPlanningTest, UnsplittableFormatKeepsLargeTaskWhole) { + auto avro = MakeDataFile("avro-file", 1000); + avro->file_format = FileFormatType::kAvro; + auto task = MakeTask(std::move(avro)); + ScopedSplitPolicy scoped( + FileFormatType::kParquet, + std::make_unique<CountingSplitPolicy>(std::vector<int64_t>{100, 500})); + 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_F(ScanTaskPlanningTest, SmallTaskSkipsPolicy) { + auto policy = std::make_unique<CountingSplitPolicy>(std::vector<int64_t>{}); + const CountingSplitPolicy* policy_view = policy.get(); + ScopedSplitPolicy scoped(FileFormatType::kParquet, std::move(policy)); + + auto small = MakeTask(MakeDataFile("small", 500)); + ICEBERG_UNWRAP_OR_FAIL(auto groups, PlanAll({small}, Options(1000))); + ASSERT_THAT(groups.size(), Eq(1)); + EXPECT_THAT(policy_view->calls(), Eq(0)); +} + +TEST_F(ScanTaskPlanningTest, SplitCoversFileExactlyAndCoalescesTowardTarget) { + auto policy = + std::make_unique<CountingSplitPolicy>(std::vector<int64_t>{100, 250, 300}); + ScopedSplitPolicy scoped(FileFormatType::kParquet, std::move(policy)); + + auto file = MakeDataFile("file", 1000); + file->record_count = 100; + auto deletes = std::vector<std::shared_ptr<DataFile>>{MakeDeleteFile(7)}; + const auto residual = Expressions::GreaterThan("id", Literal::Int(1)); + auto task = std::make_shared<FileScanTask>(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<int64_t, int64_t>{0, 250})); + EXPECT_THAT(RangesOf(*groups[1]), ElementsAre(std::pair<int64_t, int64_t>{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_F(ScanTaskPlanningTest, BoundariesBelowTargetKeepFileWhole) { + ScopedSplitPolicy scoped( + FileFormatType::kParquet, + std::make_unique<CountingSplitPolicy>(std::vector<int64_t>{10})); + + auto task = MakeTask(MakeDataFile("file", 1000)); + 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_F(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)); + + // No split policy is registered: both files stay whole and pack together. + 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_F(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_F(ScanTaskPlanningTest, AlreadySplitTaskPassesThrough) { + ScopedSplitPolicy scoped( + FileFormatType::kParquet, + std::make_unique<CountingSplitPolicy>(std::vector<int64_t>{100, 500})); + + ICEBERG_UNWRAP_OR_FAIL(auto split, + FileScanTask::MakeSplit(MakeDataFile("file", 1000), 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_F(ScanTaskPlanningTest, PackingFillsFirstGroupThatFits) { + auto a = MakeTask(MakeDataFile("a", 100)); Review Comment: Use weights `60, 70, 20` with target `100` and expect `60` and `20` in the same group. Both open groups can fit `20`, so this distinguishes first-fit from best-fit. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
