This is an automated email from the ASF dual-hosted git repository.
zhjwpku 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 037190e0 refactor: add bin packing utility (#1170)
037190e0 is described below
commit 037190e0637c71d1466c830d5b2a8f34c5f13d42
Author: Gang Wu <[email protected]>
AuthorDate: Thu Nov 26 23:03:38 2026 +0800
refactor: add bin packing utility (#1170)
---
src/iceberg/manifest/manifest_merge_manager.cc | 36 +---
src/iceberg/scan_task_planning.cc | 99 ++---------
src/iceberg/test/CMakeLists.txt | 1 +
src/iceberg/test/bin_packing_test.cc | 165 ++++++++++++++++++
src/iceberg/test/scan_task_planning_test.cc | 8 +-
src/iceberg/util/bin_packing_internal.h | 224 +++++++++++++++++++++++++
6 files changed, 418 insertions(+), 115 deletions(-)
diff --git a/src/iceberg/manifest/manifest_merge_manager.cc
b/src/iceberg/manifest/manifest_merge_manager.cc
index fc9183d1..40847a01 100644
--- a/src/iceberg/manifest/manifest_merge_manager.cc
+++ b/src/iceberg/manifest/manifest_merge_manager.cc
@@ -33,6 +33,7 @@
#include "iceberg/manifest/manifest_entry.h"
#include "iceberg/manifest/manifest_reader.h"
#include "iceberg/table_metadata.h"
+#include "iceberg/util/bin_packing_internal.h"
#include "iceberg/util/macros.h"
namespace iceberg {
@@ -126,35 +127,12 @@ Result<std::vector<ManifestFile>>
ManifestMergeManager::MergeManifests(
Result<std::vector<ManifestFile>> ManifestMergeManager::MergeGroup(
const std::vector<const ManifestFile*>& group, const ManifestFile* first,
const TableMetadata& metadata, const ManifestWriterFactory&
writer_factory) {
- // Match packEnd(group, ManifestFile::length) with lookback 1:
- // 1. Process manifests in reverse order (oldest-first).
- // 2. Greedy forward-pack with lookback=1: emit the current bin when the
next item
- // doesn't fit, then start a new bin.
- // 3. Reverse each bin (restoring original item order within a bin).
- // 4. Reverse the bin list (newest manifest's bin ends up first).
- // Effect: the newest manifest is in the first, possibly under-filled, bin.
- std::vector<std::vector<const ManifestFile*>> bins;
- std::vector<const ManifestFile*> current_bin;
- int64_t bin_size = 0;
-
- for (const auto* manifest : std::views::reverse(group)) {
- if (!current_bin.empty() &&
- bin_size + manifest->manifest_length > target_size_bytes_) {
- bins.push_back(std::move(current_bin));
- current_bin.clear();
- bin_size = 0;
- }
- current_bin.push_back(manifest);
- bin_size += manifest->manifest_length;
- }
- if (!current_bin.empty()) {
- bins.push_back(std::move(current_bin));
- }
-
- for (auto& bin : bins) {
- std::ranges::reverse(bin);
- }
- std::ranges::reverse(bins);
+ // Pack from the end with lookback 1 to keep manifest order and leave the
newest
+ // bin under-filled for the next merge.
+ internal::bin_packing::ListPacker<const ManifestFile*> packer(
+ target_size_bytes_, /*lookback=*/1, /*largest_bin_first=*/false);
+ ICEBERG_ASSIGN_OR_RAISE(auto bins,
+ packer.PackEnd(group,
&ManifestFile::manifest_length));
// Process each bin: if the bin contains the newest manifest and is too
small,
// pass its contents through unchanged.
diff --git a/src/iceberg/scan_task_planning.cc
b/src/iceberg/scan_task_planning.cc
index 7196305a..2a4ec435 100644
--- a/src/iceberg/scan_task_planning.cc
+++ b/src/iceberg/scan_task_planning.cc
@@ -20,7 +20,6 @@
#include <algorithm>
#include <cstddef>
#include <cstdint>
-#include <deque>
#include <limits>
#include <memory>
#include <optional>
@@ -33,6 +32,7 @@
#include "iceberg/result.h"
#include "iceberg/scan_task_planning_internal.h"
#include "iceberg/table_properties.h"
+#include "iceberg/util/bin_packing_internal.h"
#include "iceberg/util/content_file_util.h"
#include "iceberg/util/int128.h"
#include "iceberg/util/string_util.h"
@@ -63,13 +63,6 @@ int128_t DeleteContentBytes(const FileScanTask& task) {
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(
@@ -171,69 +164,6 @@ class FileScanTaskSplitCursor {
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.
@@ -241,19 +171,24 @@ class TaskGroupPlanningStream final : public
FileScanTaskGroupStream {
public:
TaskGroupPlanningStream(FileScanTaskStreamPtr tasks,
const TaskGroupPlanningOptions& options)
- : tasks_(std::move(tasks)), target_size_(options.target_size),
packer_(options) {}
+ : tasks_(std::move(tasks)),
+ target_size_(options.target_size),
+ packer_([this] { return NextTask(); }, options.target_size,
options.lookback,
+ kMaxTasksPerTaskGroup,
+ [open_file_cost = options.open_file_cost](const auto& task) {
+ return TaskGroupWeight(*task, open_file_cost);
+ },
+ /*largest_bin_first=*/true) {}
+
+ TaskGroupPlanningStream(TaskGroupPlanningStream&&) = delete;
+ TaskGroupPlanningStream& operator=(TaskGroupPlanningStream&&) = delete;
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;
- }
+ ICEBERG_ASSIGN_OR_RAISE(auto tasks, packer_.Next());
+ if (!tasks) {
+ return std::nullopt;
}
+ return std::make_shared<FileScanTaskGroup>(std::move(*tasks));
}
private:
@@ -276,7 +211,7 @@ class TaskGroupPlanningStream final : public
FileScanTaskGroupStream {
FileScanTaskStreamPtr tasks_;
int64_t target_size_;
- TaskGroupPacker packer_;
+ bin_packing::PackingIterator<std::shared_ptr<FileScanTask>> packer_;
std::optional<FileScanTaskSplitCursor> splits_;
};
diff --git a/src/iceberg/test/CMakeLists.txt b/src/iceberg/test/CMakeLists.txt
index 70c31275..f412a6aa 100644
--- a/src/iceberg/test/CMakeLists.txt
+++ b/src/iceberg/test/CMakeLists.txt
@@ -165,6 +165,7 @@ add_iceberg_test(util_test
USE_DATA
SOURCES
base64_test.cc
+ bin_packing_test.cc
bucket_util_test.cc
cache_test.cc
config_test.cc
diff --git a/src/iceberg/test/bin_packing_test.cc
b/src/iceberg/test/bin_packing_test.cc
new file mode 100644
index 00000000..8379129a
--- /dev/null
+++ b/src/iceberg/test/bin_packing_test.cc
@@ -0,0 +1,165 @@
+/*
+ * 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 <vector>
+
+#include <gmock/gmock.h>
+#include <gtest/gtest.h>
+
+#include "iceberg/test/matchers.h"
+#include "iceberg/util/bin_packing_internal.h"
+
+namespace iceberg::internal::bin_packing {
+namespace {
+
+using Bins = std::vector<std::vector<int>>;
+constexpr int kUnlimitedLookback = std::numeric_limits<int>::max();
+
+Result<Bins> Pack(const std::vector<int>& items, int64_t target_weight,
+ int lookback = kUnlimitedLookback, bool largest_bin_first =
false,
+ int64_t max_items_per_bin =
std::numeric_limits<int64_t>::max()) {
+ ListPacker<int> packer(target_weight, lookback, largest_bin_first,
max_items_per_bin);
+ return packer.Pack(items, [](int item) { return item; });
+}
+
+Result<Bins> PackEnd(const std::vector<int>& items, int64_t target_weight,
+ int lookback = kUnlimitedLookback) {
+ ListPacker<int> packer(target_weight, lookback, /*largest_bin_first=*/false);
+ return packer.PackEnd(items, [](int item) { return item; });
+}
+
+TEST(BinPackingTest, BasicBinPacking) {
+ EXPECT_THAT(Pack({1, 2, 3, 4, 5}, 3),
+ HasValue(::testing::Eq(Bins{{1, 2}, {3}, {4}, {5}})));
+ EXPECT_THAT(Pack({1, 2, 3, 4, 5}, 5),
+ HasValue(::testing::Eq(Bins{{1, 2}, {3}, {4}, {5}})));
+ EXPECT_THAT(Pack({1, 2, 3, 4, 5}, 6),
+ HasValue(::testing::Eq(Bins{{1, 2, 3}, {4}, {5}})));
+ EXPECT_THAT(Pack({1, 2, 3, 4, 5}, 8),
+ HasValue(::testing::Eq(Bins{{1, 2, 3}, {4}, {5}})));
+ EXPECT_THAT(Pack({1, 2, 3, 4, 5}, 9), HasValue(::testing::Eq(Bins{{1, 2, 3},
{4, 5}})));
+ EXPECT_THAT(Pack({1, 2, 3, 4, 5}, 10),
+ HasValue(::testing::Eq(Bins{{1, 2, 3, 4}, {5}})));
+ EXPECT_THAT(Pack({1, 2, 3, 4, 5}, 14),
+ HasValue(::testing::Eq(Bins{{1, 2, 3, 4}, {5}})));
+ EXPECT_THAT(Pack({1, 2, 3, 4, 5}, 15), HasValue(::testing::Eq(Bins{{1, 2, 3,
4, 5}})));
+}
+
+TEST(BinPackingTest, BasicBinPackingTargetSize) {
+ EXPECT_THAT(
+ Pack({1, 2, 3, 4, 5}, 3, kUnlimitedLookback,
/*largest_bin_first=*/false, 2),
+ HasValue(::testing::Eq(Bins{{1, 2}, {3}, {4}, {5}})));
+ EXPECT_THAT(
+ Pack({1, 2, 3, 4, 5}, 5, kUnlimitedLookback,
/*largest_bin_first=*/false, 2),
+ HasValue(::testing::Eq(Bins{{1, 2}, {3}, {4}, {5}})));
+ EXPECT_THAT(
+ Pack({1, 2, 3, 4, 5}, 6, kUnlimitedLookback,
/*largest_bin_first=*/false, 2),
+ HasValue(::testing::Eq(Bins{{1, 2}, {3}, {4}, {5}})));
+ EXPECT_THAT(
+ Pack({1, 2, 3, 4, 5}, 8, kUnlimitedLookback,
/*largest_bin_first=*/false, 3),
+ HasValue(::testing::Eq(Bins{{1, 2, 3}, {4}, {5}})));
+ EXPECT_THAT(
+ Pack({1, 2, 3, 4, 5}, 9, kUnlimitedLookback,
/*largest_bin_first=*/false, 3),
+ HasValue(::testing::Eq(Bins{{1, 2, 3}, {4, 5}})));
+ EXPECT_THAT(
+ Pack({1, 2, 3, 4, 5}, 10, kUnlimitedLookback,
/*largest_bin_first=*/false, 3),
+ HasValue(::testing::Eq(Bins{{1, 2, 3}, {4, 5}})));
+ EXPECT_THAT(
+ Pack({1, 2, 3, 4, 5}, 14, kUnlimitedLookback,
/*largest_bin_first=*/false, 3),
+ HasValue(::testing::Eq(Bins{{1, 2, 3}, {4, 5}})));
+}
+
+TEST(BinPackingTest, ReverseBinPackingSingleLookback) {
+ EXPECT_THAT(PackEnd({1, 2, 3, 4, 5}, 3, 1),
+ HasValue(::testing::Eq(Bins{{1, 2}, {3}, {4}, {5}})));
+ EXPECT_THAT(PackEnd({1, 2, 3, 4, 5}, 4, 1),
+ HasValue(::testing::Eq(Bins{{1, 2}, {3}, {4}, {5}})));
+ EXPECT_THAT(PackEnd({1, 2, 3, 4, 5}, 5, 1),
+ HasValue(::testing::Eq(Bins{{1}, {2, 3}, {4}, {5}})));
+ EXPECT_THAT(PackEnd({1, 2, 3, 4, 5}, 6, 1),
+ HasValue(::testing::Eq(Bins{{1, 2, 3}, {4}, {5}})));
+ EXPECT_THAT(PackEnd({1, 2, 3, 4, 5}, 7, 1),
+ HasValue(::testing::Eq(Bins{{1, 2}, {3, 4}, {5}})));
+ EXPECT_THAT(PackEnd({1, 2, 3, 4, 5}, 8, 1),
+ HasValue(::testing::Eq(Bins{{1, 2}, {3, 4}, {5}})));
+ EXPECT_THAT(PackEnd({1, 2, 3, 4, 5}, 9, 1),
+ HasValue(::testing::Eq(Bins{{1, 2, 3}, {4, 5}})));
+ EXPECT_THAT(PackEnd({1, 2, 3, 4, 5}, 11, 1),
+ HasValue(::testing::Eq(Bins{{1, 2, 3}, {4, 5}})));
+ EXPECT_THAT(PackEnd({1, 2, 3, 4, 5}, 12, 1),
+ HasValue(::testing::Eq(Bins{{1, 2}, {3, 4, 5}})));
+ EXPECT_THAT(PackEnd({1, 2, 3, 4, 5}, 14, 1),
+ HasValue(::testing::Eq(Bins{{1}, {2, 3, 4, 5}})));
+ EXPECT_THAT(PackEnd({1, 2, 3, 4, 5}, 15, 1),
+ HasValue(::testing::Eq(Bins{{1, 2, 3, 4, 5}})));
+}
+
+TEST(BinPackingTest, ReverseBinPackingUnlimitedLookback) {
+ EXPECT_THAT(PackEnd({1, 2, 3, 4, 5}, 3),
+ HasValue(::testing::Eq(Bins{{1, 2}, {3}, {4}, {5}})));
+ EXPECT_THAT(PackEnd({1, 2, 3, 4, 5}, 4),
+ HasValue(::testing::Eq(Bins{{2}, {1, 3}, {4}, {5}})));
+ EXPECT_THAT(PackEnd({1, 2, 3, 4, 5}, 5),
+ HasValue(::testing::Eq(Bins{{2, 3}, {1, 4}, {5}})));
+ EXPECT_THAT(PackEnd({1, 2, 3, 4, 5}, 6),
+ HasValue(::testing::Eq(Bins{{3}, {2, 4}, {1, 5}})));
+ EXPECT_THAT(PackEnd({1, 2, 3, 4, 5}, 7),
+ HasValue(::testing::Eq(Bins{{1}, {3, 4}, {2, 5}})));
+ EXPECT_THAT(PackEnd({1, 2, 3, 4, 5}, 8),
+ HasValue(::testing::Eq(Bins{{1, 2, 4}, {3, 5}})));
+ EXPECT_THAT(PackEnd({1, 2, 3, 4, 5}, 9),
+ HasValue(::testing::Eq(Bins{{1, 2, 3}, {4, 5}})));
+ EXPECT_THAT(PackEnd({1, 2, 3, 4, 5}, 10),
+ HasValue(::testing::Eq(Bins{{2, 3}, {1, 4, 5}})));
+ EXPECT_THAT(PackEnd({1, 2, 3, 4, 5}, 11),
+ HasValue(::testing::Eq(Bins{{1, 3}, {2, 4, 5}})));
+ EXPECT_THAT(PackEnd({1, 2, 3, 4, 5}, 12),
+ HasValue(::testing::Eq(Bins{{1, 2}, {3, 4, 5}})));
+ EXPECT_THAT(PackEnd({1, 2, 3, 4, 5}, 13),
+ HasValue(::testing::Eq(Bins{{2}, {1, 3, 4, 5}})));
+ EXPECT_THAT(PackEnd({1, 2, 3, 4, 5}, 14),
+ HasValue(::testing::Eq(Bins{{1}, {2, 3, 4, 5}})));
+ EXPECT_THAT(PackEnd({1, 2, 3, 4, 5}, 15),
+ HasValue(::testing::Eq(Bins{{1, 2, 3, 4, 5}})));
+}
+
+TEST(BinPackingTest, BinPackingLookBack) {
+ EXPECT_THAT(Pack({5, 1, 5, 1, 5, 1}, 8),
+ HasValue(::testing::Eq(Bins{{5, 1, 1, 1}, {5}, {5}})));
+ EXPECT_THAT(Pack({5, 1, 5, 1, 5, 1}, 8, 2),
+ HasValue(::testing::Eq(Bins{{5, 1, 1}, {5, 1}, {5}})));
+ EXPECT_THAT(Pack({5, 1, 5, 1, 5, 1}, 8, 1),
+ HasValue(::testing::Eq(Bins{{5, 1}, {5, 1}, {5, 1}})));
+ EXPECT_THAT(Pack({36, 36, 36, 36, 65, 65, 128}, 128, 2,
/*largest_bin_first=*/true),
+ HasValue(::testing::Eq(Bins{{36, 36, 36}, {128}, {36, 65},
{65}})));
+ EXPECT_THAT(Pack({64, 64, 128, 32, 32, 32, 32}, 128, 1,
/*largest_bin_first=*/true),
+ HasValue(::testing::Eq(Bins{{64, 64}, {128}, {32, 32, 32,
32}})));
+}
+
+TEST(BinPackingTest, BinWeightDoesNotOverflow) {
+ const int64_t max = std::numeric_limits<int64_t>::max();
+ ListPacker<int64_t> packer(max, 1, /*largest_bin_first=*/false);
+ EXPECT_THAT(
+ packer.Pack(std::vector<int64_t>{max, 1}, [](int64_t item) { return
item; }),
+ HasValue(::testing::Eq(std::vector<std::vector<int64_t>>{{max}, {1}})));
+}
+
+} // namespace
+} // namespace iceberg::internal::bin_packing
diff --git a/src/iceberg/test/scan_task_planning_test.cc
b/src/iceberg/test/scan_task_planning_test.cc
index 8d3e335b..b076059b 100644
--- a/src/iceberg/test/scan_task_planning_test.cc
+++ b/src/iceberg/test/scan_task_planning_test.cc
@@ -309,13 +309,13 @@ TEST(ScanTaskPlanningTest,
PackingFillsFirstGroupThatFits) {
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 a = MakeTask(MakeDataFile("a", 60));
+ auto b = MakeTask(MakeDataFile("b", 100));
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[0]->tasks(), ElementsAre(b));
+ EXPECT_THAT(groups[1]->tasks(), ElementsAre(a));
EXPECT_THAT(groups[2]->tasks(), ElementsAre(c));
}
diff --git a/src/iceberg/util/bin_packing_internal.h
b/src/iceberg/util/bin_packing_internal.h
new file mode 100644
index 00000000..3ce454ff
--- /dev/null
+++ b/src/iceberg/util/bin_packing_internal.h
@@ -0,0 +1,224 @@
+/*
+ * 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
+
+#include <algorithm>
+#include <cstdint>
+#include <functional>
+#include <limits>
+#include <list>
+#include <optional>
+#include <ranges>
+#include <utility>
+#include <vector>
+
+#include "iceberg/util/int128.h"
+#include "iceberg/util/macros.h"
+#include "iceberg/util/stream.h"
+
+namespace iceberg::internal::bin_packing {
+
+// Mirrors org.apache.iceberg.util.BinPacking.
+template <typename T>
+class Bin {
+ public:
+ Bin(int64_t target_weight, int64_t max_size)
+ : target_weight_(target_weight), max_size_(max_size) {}
+
+ bool CanAdd(int64_t weight) const {
+ return bin_weight_ + weight <= target_weight_ &&
+ std::cmp_less(items_.size(), max_size_);
+ }
+
+ void Add(T item, int64_t weight) {
+ bin_weight_ += weight;
+ items_.push_back(std::move(item));
+ }
+
+ int128_t weight() const { return bin_weight_; }
+ std::vector<T> items() && { return std::move(items_); }
+
+ private:
+ int64_t target_weight_;
+ int64_t max_size_;
+ std::vector<T> items_;
+ // Widen the sum so two large weights cannot wrap and appear to fit.
+ int128_t bin_weight_ = 0;
+};
+
+template <typename T>
+class PackingIterator final : public Stream<std::vector<T>> {
+ public:
+ using NextItem = std::function<Result<std::optional<T>>()>;
+ using WeightFunc = std::function<Result<int64_t>(const T&)>;
+
+ PackingIterator(NextItem items, int64_t target_weight, int64_t lookback,
+ int64_t max_size, WeightFunc weight_func, bool
largest_bin_first)
+ : items_(std::move(items)),
+ target_weight_(target_weight),
+ lookback_(lookback),
+ max_size_(max_size),
+ weight_func_(std::move(weight_func)),
+ largest_bin_first_(largest_bin_first) {
+ ICEBERG_DCHECK(lookback > 0, "Bin look-back size must be greater than 0");
+ }
+
+ private:
+ Result<std::optional<std::vector<T>>> NextImpl() override {
+ while (true) {
+ ICEBERG_ASSIGN_OR_RAISE(auto item, items_());
+ if (!item) {
+ break;
+ }
+ ICEBERG_ASSIGN_OR_RAISE(auto weight, weight_func_(*item));
+ if (auto* bin = FindBin(weight)) {
+ bin->Add(std::move(*item), weight);
+ } else {
+ auto new_bin = NewBin();
+ new_bin.Add(std::move(*item), weight);
+ bins_.push_back(std::move(new_bin));
+
+ if (std::cmp_greater(bins_.size(), lookback_)) {
+ auto bin_to_remove = largest_bin_first_ ? RemoveLargestBin() :
RemoveFirst();
+ return std::move(bin_to_remove).items();
+ }
+ }
+ }
+
+ if (bins_.empty()) {
+ return std::nullopt;
+ }
+ return RemoveFirst().items();
+ }
+
+ Bin<T>* FindBin(int64_t weight) {
+ for (auto& bin : bins_) {
+ if (bin.CanAdd(weight)) {
+ return &bin;
+ }
+ }
+ return nullptr;
+ }
+
+ Bin<T> NewBin() const { return Bin<T>(target_weight_, max_size_); }
+
+ Bin<T> RemoveLargestBin() {
+ auto largest = std::ranges::max_element(bins_, {}, &Bin<T>::weight);
+ auto bin = std::move(*largest);
+ bins_.erase(largest);
+ return bin;
+ }
+
+ Bin<T> RemoveFirst() {
+ auto bin = std::move(bins_.front());
+ bins_.pop_front();
+ return bin;
+ }
+
+ std::list<Bin<T>> bins_;
+ NextItem items_;
+ int64_t target_weight_;
+ int64_t lookback_;
+ int64_t max_size_;
+ WeightFunc weight_func_;
+ bool largest_bin_first_;
+};
+
+// The range must outlive its iterators. Single-pass streams use
PackingIterator directly.
+template <typename T, std::ranges::forward_range Range>
+class PackingIterable {
+ public:
+ using WeightFunc = typename PackingIterator<T>::WeightFunc;
+
+ PackingIterable(Range& iterable, int64_t target_weight, int64_t lookback,
+ WeightFunc weight_func, bool largest_bin_first = false,
+ int64_t max_size = std::numeric_limits<int64_t>::max())
+ : iterable_(iterable),
+ target_weight_(target_weight),
+ lookback_(lookback),
+ weight_func_(std::move(weight_func)),
+ largest_bin_first_(largest_bin_first),
+ max_size_(max_size) {}
+
+ Result<PackingIterator<T>> Iterator() const {
+ ICEBERG_PRECHECK(lookback_ > 0, "Bin look-back size must be greater than
0: {}",
+ lookback_);
+ auto it = std::ranges::begin(iterable_);
+ auto end = std::ranges::end(iterable_);
+ auto items = [it, end]() mutable -> Result<std::optional<T>> {
+ if (it == end) {
+ return std::nullopt;
+ }
+ return std::optional<T>{*it++};
+ };
+ return PackingIterator<T>(std::move(items), target_weight_, lookback_,
max_size_,
+ weight_func_, largest_bin_first_);
+ }
+
+ private:
+ Range& iterable_;
+ int64_t target_weight_;
+ int64_t lookback_;
+ WeightFunc weight_func_;
+ bool largest_bin_first_;
+ int64_t max_size_;
+};
+
+template <typename T>
+class ListPacker {
+ public:
+ using WeightFunc = typename PackingIterator<T>::WeightFunc;
+
+ ListPacker(int64_t target_weight, int64_t lookback, bool largest_bin_first,
+ int64_t max_items_per_bin = std::numeric_limits<int64_t>::max())
+ : target_weight_(target_weight),
+ lookback_(lookback),
+ largest_bin_first_(largest_bin_first),
+ max_items_per_bin_(max_items_per_bin) {}
+
+ Result<std::vector<std::vector<T>>> PackEnd(const std::vector<T>& items,
+ WeightFunc weight_func) const {
+ ICEBERG_ASSIGN_OR_RAISE(auto bins,
+ Pack(std::views::reverse(items),
std::move(weight_func)));
+ for (auto& bin : bins) {
+ std::ranges::reverse(bin);
+ }
+ std::ranges::reverse(bins);
+ return bins;
+ }
+
+ template <typename Range>
+ Result<std::vector<std::vector<T>>> Pack(const Range& items,
+ WeightFunc weight_func) const {
+ PackingIterable<T, const Range> iterable(items, target_weight_, lookback_,
+ std::move(weight_func),
largest_bin_first_,
+ max_items_per_bin_);
+ ICEBERG_ASSIGN_OR_RAISE(auto iter, iterable.Iterator());
+ return iter.ToVector();
+ }
+
+ private:
+ int64_t target_weight_;
+ int64_t lookback_;
+ bool largest_bin_first_;
+ int64_t max_items_per_bin_;
+};
+
+} // namespace iceberg::internal::bin_packing