|
| 1 | +// Licensed to the Apache Software Foundation (ASF) under one |
| 2 | +// or more contributor license agreements. See the NOTICE file |
| 3 | +// distributed with this work for additional information |
| 4 | +// regarding copyright ownership. The ASF licenses this file |
| 5 | +// to you under the Apache License, Version 2.0 (the |
| 6 | +// "License"); you may not use this file except in compliance |
| 7 | +// with the License. You may obtain a copy of the License at |
| 8 | +// |
| 9 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +// |
| 11 | +// Unless required by applicable law or agreed to in writing, |
| 12 | +// software distributed under the License is distributed on an |
| 13 | +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 14 | +// KIND, either express or implied. See the License for the |
| 15 | +// specific language governing permissions and limitations |
| 16 | +// under the License. |
| 17 | + |
| 18 | +//! First-fit-decreasing bin packing with lookback. |
| 19 | +//! |
| 20 | +//! Used by [`TableScan::plan_tasks()`] to combine split scan tasks into |
| 21 | +//! balanced groups whose total weight is roughly `target_weight`. |
| 22 | +
|
| 23 | +use std::collections::VecDeque; |
| 24 | + |
| 25 | +struct Bin<T> { |
| 26 | + items: Vec<T>, |
| 27 | + weight: u64, |
| 28 | +} |
| 29 | + |
| 30 | +/// Bin-pack `items` into groups whose total weight is roughly `target_weight`. |
| 31 | +/// |
| 32 | +/// Uses a first-fit-decreasing strategy with a sliding `lookback` window of |
| 33 | +/// open bins, matching the algorithm in Java Iceberg's `BinPacking.java`. |
| 34 | +/// |
| 35 | +/// Items heavier than `target_weight` are placed in their own bin. |
| 36 | +pub(crate) fn bin_pack<T, F>( |
| 37 | + mut items: Vec<T>, |
| 38 | + target_weight: u64, |
| 39 | + lookback: usize, |
| 40 | + weight_fn: F, |
| 41 | +) -> Vec<Vec<T>> |
| 42 | +where |
| 43 | + F: Fn(&T) -> u64, |
| 44 | +{ |
| 45 | + if items.is_empty() { |
| 46 | + return vec![]; |
| 47 | + } |
| 48 | + |
| 49 | + let lookback = lookback.max(1); |
| 50 | + |
| 51 | + // Compute weights and sort descending (heaviest first) |
| 52 | + let mut weighted: Vec<(T, u64)> = items |
| 53 | + .drain(..) |
| 54 | + .map(|item| { |
| 55 | + let w = weight_fn(&item); |
| 56 | + (item, w) |
| 57 | + }) |
| 58 | + .collect(); |
| 59 | + weighted.sort_by(|a, b| b.1.cmp(&a.1)); |
| 60 | + |
| 61 | + let mut result: Vec<Vec<T>> = Vec::new(); |
| 62 | + let mut open_bins: VecDeque<Bin<T>> = VecDeque::new(); |
| 63 | + |
| 64 | + for (item, weight) in weighted { |
| 65 | + // Try to fit into an existing open bin |
| 66 | + let fit_idx = open_bins |
| 67 | + .iter() |
| 68 | + .position(|bin| bin.weight + weight <= target_weight); |
| 69 | + |
| 70 | + if let Some(idx) = fit_idx { |
| 71 | + open_bins[idx].weight += weight; |
| 72 | + open_bins[idx].items.push(item); |
| 73 | + } else { |
| 74 | + // Evict the largest bin if we've exceeded lookback |
| 75 | + if open_bins.len() >= lookback { |
| 76 | + let max_idx = open_bins |
| 77 | + .iter() |
| 78 | + .enumerate() |
| 79 | + .max_by_key(|(_, b)| b.weight) |
| 80 | + .map(|(i, _)| i) |
| 81 | + .unwrap(); |
| 82 | + let evicted = open_bins.remove(max_idx).unwrap(); |
| 83 | + result.push(evicted.items); |
| 84 | + } |
| 85 | + |
| 86 | + open_bins.push_back(Bin { |
| 87 | + items: vec![item], |
| 88 | + weight, |
| 89 | + }); |
| 90 | + } |
| 91 | + } |
| 92 | + |
| 93 | + // Flush remaining bins |
| 94 | + for bin in open_bins { |
| 95 | + result.push(bin.items); |
| 96 | + } |
| 97 | + |
| 98 | + result |
| 99 | +} |
| 100 | + |
| 101 | +#[cfg(test)] |
| 102 | +mod tests { |
| 103 | + use super::*; |
| 104 | + |
| 105 | + #[test] |
| 106 | + fn test_empty_input() { |
| 107 | + let items: Vec<u64> = vec![]; |
| 108 | + let result = bin_pack(items, 100, 10, |&x| x); |
| 109 | + assert!(result.is_empty()); |
| 110 | + } |
| 111 | + |
| 112 | + #[test] |
| 113 | + fn test_single_item_fits() { |
| 114 | + let result = bin_pack(vec![50u64], 100, 10, |&x| x); |
| 115 | + assert_eq!(result.len(), 1); |
| 116 | + assert_eq!(result[0], vec![50]); |
| 117 | + } |
| 118 | + |
| 119 | + #[test] |
| 120 | + fn test_single_oversized_item() { |
| 121 | + let result = bin_pack(vec![200u64], 100, 10, |&x| x); |
| 122 | + assert_eq!(result.len(), 1); |
| 123 | + assert_eq!(result[0], vec![200]); |
| 124 | + } |
| 125 | + |
| 126 | + #[test] |
| 127 | + fn test_multiple_small_items_pack_together() { |
| 128 | + let result = bin_pack(vec![30u64, 20, 10, 25, 15], 100, 10, |&x| x); |
| 129 | + // Total weight = 100, fits in one bin |
| 130 | + assert_eq!(result.len(), 1); |
| 131 | + assert_eq!(result[0].iter().sum::<u64>(), 100); |
| 132 | + } |
| 133 | + |
| 134 | + #[test] |
| 135 | + fn test_items_split_into_multiple_bins() { |
| 136 | + let result = bin_pack(vec![60u64, 60, 60], 100, 10, |&x| x); |
| 137 | + // Each 60 can pair with at most one other 60 (120 > 100), so need at least 2 bins |
| 138 | + // With first-fit-decreasing: first 60 -> bin1, second 60 -> bin2, third 60 -> bin3 |
| 139 | + // (none can combine since 60+60=120 > 100) |
| 140 | + assert_eq!(result.len(), 3); |
| 141 | + } |
| 142 | + |
| 143 | + #[test] |
| 144 | + fn test_bin_packing_balances_load() { |
| 145 | + // 4 items: 50, 40, 30, 20 with target 70 |
| 146 | + let result = bin_pack(vec![50u64, 40, 30, 20], 70, 10, |&x| x); |
| 147 | + // Sorted descending: 50, 40, 30, 20 |
| 148 | + // 50 -> bin1(50), 40 -> bin2(40), 30 -> bin2(70), 20 -> bin1(70) |
| 149 | + assert_eq!(result.len(), 2); |
| 150 | + for bin in &result { |
| 151 | + let sum: u64 = bin.iter().sum(); |
| 152 | + assert!(sum <= 70, "Bin weight {sum} exceeds target 70"); |
| 153 | + } |
| 154 | + } |
| 155 | + |
| 156 | + #[test] |
| 157 | + fn test_lookback_limits_open_bins() { |
| 158 | + // With lookback=1, only one bin is kept open at a time |
| 159 | + let result = bin_pack(vec![10u64, 10, 10, 10], 100, 1, |&x| x); |
| 160 | + // All items are same weight (10). With lookback=1: |
| 161 | + // item1(10)->bin1(10), item2(10)->bin1(20), item3(10)->bin1(30), item4(10)->bin1(40) |
| 162 | + // They all fit, so 1 bin |
| 163 | + assert_eq!(result.len(), 1); |
| 164 | + } |
| 165 | + |
| 166 | + #[test] |
| 167 | + fn test_lookback_causes_suboptimal_packing() { |
| 168 | + // With lookback=1, a tight fit may be missed |
| 169 | + // Items: 80, 70, 30, 20 with target=100, lookback=1 |
| 170 | + let result = bin_pack(vec![80u64, 70, 30, 20], 100, 1, |&x| x); |
| 171 | + // Sorted: 80, 70, 30, 20 |
| 172 | + // 80->bin1(80). lookback=1, only bin1 open. |
| 173 | + // 70 doesn't fit in bin1(80+70=150>100). Evict bin1([80]). 70->bin2(70). |
| 174 | + // 30 fits in bin2(70+30=100). bin2(100). |
| 175 | + // 20 doesn't fit in bin2(100+20=120>100). Evict bin2([70,30]). 20->bin3(20). |
| 176 | + assert_eq!(result.len(), 3); |
| 177 | + } |
| 178 | + |
| 179 | + #[test] |
| 180 | + fn test_custom_weight_function() { |
| 181 | + // Weight function that doubles the value |
| 182 | + let result = bin_pack(vec![30u64, 30, 30], 100, 10, |&x| x * 2); |
| 183 | + // Effective weights: 60, 60, 60 |
| 184 | + // 60+60=120 > 100, so each in its own bin |
| 185 | + assert_eq!(result.len(), 3); |
| 186 | + } |
| 187 | +} |
0 commit comments