This is an automated email from the ASF dual-hosted git repository.
wgtmac pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/iceberg-cpp.git
The following commit(s) were added to refs/heads/main by this push:
new 4002e313 feat(scan): Support split and parallel scans - Part-3: lazy
split and group planning (#1113)
4002e313 is described below
commit 4002e3139d1eb7b750a3dc73cbef0e1fc50f7650
Author: kamcheungting-db <[email protected]>
AuthorDate: Sun Nov 22 08:21:51 2026 -0800
feat(scan): Support split and parallel scans - Part-3: lazy split and group
planning (#1113)
## What this PR does
Adds task-group planning for parallel scans, on top of the byte ranges from
#976 and the range-aware Parquet reads from #1002:
- `DataTableScan::PlanTasksStream()` — lazy, fallible stream of
`FileScanTaskGroup`
- `DataTableScan::PlanTasks()` — the same, collected into a vector
Eligible Parquet files are split into byte ranges, and the tasks are packed
into groups of roughly `read.split.target-size` bytes.
## How it works
```
PlanFilesStream()
|
v
Whole Parquet file larger than target? -- no --> keep task as is
|
yes
v
Valid manifest split_offsets?
| yes | no
v v
merge intervals fixed-size byte ranges
toward target (shorter final range if needed)
| |
+---------+----------+
v
pack tasks into groups
|
v
FileScanTaskGroup stream
```
**Packing** — follows Java Iceberg’s first-fit and eviction rules:
- task weight = `max(range bytes + delete content bytes, (1 + delete files)
* open-file-cost)`; a deletion vector counts its blob size, not its container
file size
- a task joins the first open group that still fits
- at most `planning-lookback` groups stay open; when a new one opens, the
largest open group is closed first
- at most 1,024 tasks per group; a task heavier than the target becomes its
own group
**Files that stay whole:** files at or below the target size, non-Parquet
files, and Parquet files whose valid manifest offsets yield only one range.
## Settings
| Property | Default | Resolves from |
|---|---|---|
| `read.split.target-size` | 128 MB | scan option > table property >
default |
| `read.split.planning-lookback` | 10 | same |
| `read.split.open-file-cost` | 4 MB | same |
Malformed or invalid values fail planning before any planning work starts.
## Stream behavior
Single pass, lazy, owns the underlying task stream and its metrics, and can
outlive the scan. An executor set with `PlanWith()` is borrowed and must stay
alive until the group stream is destroyed. Destroying the stream
mid-consumption releases all planning resources. The stream retains the current
file’s remaining splits across calls to `Next()`. Splitting requires no
data-file I/O or Parquet bundle registration.
## Tests
- `table_test` (core-only, includes `ScanTaskPlanningTest`): split coverage
and merging, delete files and residual filters carried into every split, mixed
Parquet/Avro groups, the Java weight formula, group packing (first fit,
lookback, 1,024 cap, oversized singleton), settings precedence and errors,
incremental consumption, early destruction.
- Bundled `scan_test`, across manifest format versions: split offsets used
with no footer read (the file path does not exist), fixed-size ranges for
missing or invalid offsets, files at or below target stay whole, every row read
exactly once across splits, scan option beats table property, no-snapshot
scans, delete files carried into every split.
`pre-commit` is clean.
## Related
Part 1 #976 · Part 2a #1002 · Part 2b #1062 · Part 2c #1065. The bounded
parallel reader and end-to-end validation follow in later parts.
---
src/iceberg/CMakeLists.txt | 1 +
src/iceberg/data_table_scan.cc | 16 ++
src/iceberg/data_table_scan.h | 19 ++
src/iceberg/scan_task_planning.cc | 305 +++++++++++++++++++++
src/iceberg/scan_task_planning_internal.h | 76 ++++++
src/iceberg/table_scan.cc | 36 +++
src/iceberg/table_scan.h | 39 +++
src/iceberg/test/CMakeLists.txt | 1 +
src/iceberg/test/scan_task_planning_test.cc | 403 ++++++++++++++++++++++++++++
src/iceberg/test/table_scan_test.cc | 353 ++++++++++++++++++++++++
10 files changed, 1249 insertions(+)
diff --git a/src/iceberg/CMakeLists.txt b/src/iceberg/CMakeLists.txt
index 0768f1aa..0065b838 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 f35f454c..5eea6088 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<FileScanTaskStreamPtr>
DataTableScan::PlanFilesStream() const {
context_.metrics_reporter, std::move(report).value());
}
+Result<std::vector<std::shared_ptr<FileScanTaskGroup>>>
DataTableScan::PlanTasks() const {
+ ICEBERG_ASSIGN_OR_RAISE(auto stream, PlanTasksStream());
+ return stream->ToVector();
+}
+
+Result<FileScanTaskGroupStreamPtr> 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 96804d95..3a4be4c8 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<FileScanTaskStreamPtr> PlanFilesStream() const;
+ /// \brief Collects PlanTasksStream() into a vector.
+ /// \return A Result containing task groups or an error.
+ Result<std::vector<std::shared_ptr<FileScanTaskGroup>>> 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<FileScanTaskGroupStreamPtr> 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 00000000..7196305a
--- /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 <algorithm>
+#include <cstddef>
+#include <cstdint>
+#include <deque>
+#include <limits>
+#include <memory>
+#include <optional>
+#include <span>
+#include <unordered_map>
+#include <utility>
+#include <vector>
+
+#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 <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()) {
+ total += ContentFileUtil::ContentSizeInBytes(*delete_file);
+ }
+ 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
+
+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);
+}
+
+namespace {
+
+std::span<const int64_t> 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<FileScanTask> 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<std::shared_ptr<FileScanTask>> 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<FileScanTask> task_;
+ int64_t target_size_;
+ std::span<const int64_t> 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<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)
+ : tasks_(std::move(tasks)), target_size_(options.target_size),
packer_(options) {}
+
+ Result<std::optional<std::shared_ptr<FileScanTaskGroup>>> 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<std::optional<std::shared_ptr<FileScanTask>>> 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<FileScanTaskSplitCursor> splits_;
+};
+
+} // namespace
+
+Result<FileScanTaskGroupStreamPtr> 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<TaskGroupPlanningStream>(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 00000000..72f7bc40
--- /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 <cstdint>
+#include <string>
+#include <unordered_map>
+
+#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<TaskGroupPlanningOptions>
ResolveTaskGroupPlanningOptions(
+ const std::unordered_map<std::string, std::string>& scan_options,
+ const std::unordered_map<std::string, std::string>& 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<int64_t> 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<FileScanTaskGroupStreamPtr> PlanTaskGroupStream(
+ FileScanTaskStreamPtr tasks, const TaskGroupPlanningOptions& options);
+
+} // namespace iceberg::internal
diff --git a/src/iceberg/table_scan.cc b/src/iceberg/table_scan.cc
index d04e3385..a29ee004 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<int64_t>(count_at_end - count_at_start);
}
+// FileScanTaskGroup implementation
+
+FileScanTaskGroup::FileScanTaskGroup(std::vector<std::shared_ptr<FileScanTask>>
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<int64_t>(
+ std::min<int128_t>(total, std::numeric_limits<int64_t>::max()));
+}
+
+int32_t FileScanTaskGroup::files_count() const {
+ int64_t total = 0;
+ for (const auto& task : tasks_) {
+ total += task->files_count();
+ }
+ return static_cast<int32_t>(
+ std::min<int64_t>(total, std::numeric_limits<int32_t>::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<int64_t>(
+ std::min<int128_t>(total, std::numeric_limits<int64_t>::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 1307089e..3781d88c 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<std::shared_ptr<FileScanTask>>;
/// \brief Owning pointer to a file scan task stream.
using FileScanTaskStreamPtr = std::unique_ptr<FileScanTaskStream>;
+/// \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<std::shared_ptr<FileScanTask>> tasks);
+
+ /// \brief The tasks in this group, in planning order.
+ const std::vector<std::shared_ptr<FileScanTask>>& 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<std::shared_ptr<FileScanTask>> tasks_;
+};
+
+/// \brief Stream of file scan task groups.
+using FileScanTaskGroupStream = Stream<std::shared_ptr<FileScanTaskGroup>>;
+
+/// \brief Owning pointer to a file scan task group stream.
+using FileScanTaskGroupStreamPtr = std::unique_ptr<FileScanTaskGroupStream>;
+
enum class ChangelogOperation : uint8_t {
kInsert,
kDelete,
diff --git a/src/iceberg/test/CMakeLists.txt b/src/iceberg/test/CMakeLists.txt
index 6b2c6dbc..a6f3d8ba 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 00000000..8d3e335b
--- /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 <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));
+ 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;
+}
+
+TEST(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(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(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(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(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<int64_t>::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<int64_t, int64_t>{0,
100}));
+ EXPECT_THAT(RangesOf(*groups[1]), ElementsAre(std::pair<int64_t,
int64_t>{100, 100}));
+ EXPECT_THAT(RangesOf(*groups[2]), ElementsAre(std::pair<int64_t,
int64_t>{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<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(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<int64_t>::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<int64_t, int64_t>{0,
kTarget}));
+ EXPECT_THAT(RangesOf(*groups[1]),
+ ElementsAre(std::pair<int64_t, int64_t>{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<std::shared_ptr<FileScanTask>> 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<int64_t>::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 40b51bd5..a71031bd 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 <algorithm>
#include <limits>
#include <memory>
+#include <numeric>
#include <optional>
#include <string>
#include <unordered_map>
+#include <utility>
#include <vector>
+#include <arrow/array.h>
+#include <arrow/c/bridge.h>
+#include <arrow/json/from_string.h>
+#include <arrow/record_batch.h>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
+#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<std::shared_ptr<DataFile>> 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<TableMetadata> MakeTaskPlanningMetadata(
+ std::vector<ManifestEntry> data_entries,
+ std::vector<ManifestEntry> delete_entries = {}) {
+ constexpr int64_t kSnapshotId = 1000L;
+ constexpr int64_t kSequenceNumber = 1L;
+
+ std::vector<ManifestFile> 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{.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<DataFile> MakePositionDeleteFile(
const std::string& path, const PartitionValues& partition, int32_t
spec_id,
std::optional<std::string> 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<DataFile> MakeSplitPlanningDataFile(const std::string& path,
+ int64_t file_size,
+ std::vector<int64_t>
split_offsets,
+ int64_t record_count) {
+ auto file = std::make_shared<DataFile>();
+ 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<std::pair<int64_t, int64_t>> CollectGroupRanges(
+ const std::vector<std::shared_ptr<FileScanTaskGroup>>& groups) {
+ std::vector<std::pair<int64_t, int64_t>> 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("/missing/data.parquet", 3000, {1200, 2300},
30))});
+
+ ICEBERG_UNWRAP_OR_FAIL(auto builder,
MakeScanBuilder<DataTableScan>(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<int64_t, int64_t>{0, 1200},
+ std::pair<int64_t, int64_t>{1200, 1100},
+ std::pair<int64_t, int64_t>{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("/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<std::vector<int64_t>>{{}, {1200, 1200}, {1200, 1100},
{1200, 2600}}) {
+ auto metadata = MakeTaskPlanningMetadata({MakeEntry(
+ ManifestStatus::kAdded, 1000L, 1L,
+ MakeSplitPlanningDataFile("/missing/data.parquet", 2600, offsets,
26))});
+ ICEBERG_UNWRAP_OR_FAIL(auto builder,
MakeScanBuilder<DataTableScan>(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<int64_t, int64_t>{0, 1000},
+ std::pair<int64_t, int64_t>{1000, 1000},
+ std::pair<int64_t, int64_t>{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<DataTableScan>(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<int32_t> 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<const
::arrow::Int32Array&>(*(*next)->column(0));
+ for (int64_t row = 0; row < column.length(); ++row) {
+ ids.push_back(column.Value(row));
+ }
+ }
+ }
+ }
+ std::ranges::sort(ids);
+ std::vector<int32_t> 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("/missing/small.parquet", file_size, {},
10))});
+ ICEBERG_UNWRAP_OR_FAIL(auto builder,
MakeScanBuilder<DataTableScan>(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("/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<DataTableScan>(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<DataTableScan>(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<DataTableScan>(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("/missing/data.parquet", 3000, {1000, 2000},
30))});
+ invalid_metadata->properties =
+ TableProperties::FromMap({{"read.split.target-size", "0"}});
+ ICEBERG_UNWRAP_OR_FAIL(auto builder,
+ MakeScanBuilder<DataTableScan>(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>(
+ 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<DataTableScan>(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("/missing/data.parquet", 3000, {1000, 2000},
30))});
+
+ ICEBERG_UNWRAP_OR_FAIL(auto builder,
MakeScanBuilder<DataTableScan>(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 = "/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("/missing/pos-deletes.parquet",
+
PartitionValues(std::vector<Literal>{}),
+ unpartitioned_spec_->spec_id(),
data_path))});
+
+ ICEBERG_UNWRAP_OR_FAIL(auto builder,
MakeScanBuilder<DataTableScan>(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("/missing/pos-deletes.parquet"));
+ }
+}
+
INSTANTIATE_TEST_SUITE_P(TableScanVersions, TableScanTest, testing::Values(1,
2, 3));
} // namespace iceberg