icepick 0.4.1

Experimental Rust client for Apache Iceberg with WASM support for AWS S3 Tables and Cloudflare R2
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
//! Compaction planning with bin-packing algorithm

use crate::compact::options::CompactOptions;
use crate::error::Result;
use crate::spec::DataFile;
use crate::table::Table;
use std::collections::HashMap;

/// A group of files to be compacted together
#[derive(Debug, Clone)]
pub struct CompactionGroup {
    /// Input files to compact
    input_files: Vec<DataFile>,
    /// Total size of input files in bytes
    input_bytes: u64,
    /// Total record count in input files
    input_records: u64,
}

impl CompactionGroup {
    /// Create a new compaction group from input files
    ///
    /// Automatically computes total bytes and records from the files.
    ///
    /// # Errors
    ///
    /// Returns an error if `input_files` is empty
    pub fn new(input_files: Vec<DataFile>) -> Result<Self> {
        if input_files.is_empty() {
            return Err(crate::error::Error::invalid_input(
                "CompactionGroup cannot be created with empty input_files",
            ));
        }

        let input_bytes = input_files
            .iter()
            .map(|f| f.file_size_in_bytes() as u64)
            .sum();

        let input_records = input_files.iter().map(|f| f.record_count() as u64).sum();

        Ok(Self {
            input_files,
            input_bytes,
            input_records,
        })
    }

    /// Get the input files to compact
    pub fn files(&self) -> &[DataFile] {
        &self.input_files
    }

    /// Get the total size of input files in bytes
    pub fn total_bytes(&self) -> u64 {
        self.input_bytes
    }

    /// Get the total record count in input files
    pub fn total_records(&self) -> u64 {
        self.input_records
    }
}

/// Plan for compacting a single partition
#[derive(Debug, Clone)]
pub struct PartitionPlan {
    /// Partition value (None for unpartitioned tables)
    pub partition_value: Option<String>,
    /// Groups of files to compact
    pub groups: Vec<CompactionGroup>,
    /// Total number of input files
    pub total_input_files: usize,
    /// Total input bytes
    pub total_input_bytes: u64,
}

impl PartitionPlan {
    /// Estimate the number of output files based on target size
    pub fn estimated_output_files(&self, target_size: u64) -> usize {
        self.groups
            .iter()
            .map(|g| {
                let files = (g.total_bytes() as f64 / target_size as f64).ceil() as usize;
                files.max(1)
            })
            .sum()
    }
}

/// Complete compaction plan for a table
#[derive(Debug, Clone)]
pub struct CompactionPlan {
    /// Plans for each partition
    pub partitions: Vec<PartitionPlan>,
}

impl CompactionPlan {
    /// Create a compaction plan for a table
    pub async fn create(table: &Table, options: &CompactOptions) -> Result<Self> {
        // Get all data files from current snapshot
        let files = match table.current_snapshot() {
            Some(_) => table.files().await?,
            None => {
                // No snapshot means no files to compact
                return Ok(Self {
                    partitions: Vec::new(),
                });
            }
        };

        // Convert DataFileEntry to DataFile for easier manipulation
        let data_files: Vec<DataFile> = files
            .into_iter()
            .map(|entry| {
                DataFile::builder()
                    .with_file_path(&entry.file_path)
                    .with_file_format(&entry.file_format)
                    .with_record_count(entry.record_count)
                    .with_file_size_in_bytes(entry.file_size_in_bytes)
                    .build()
            })
            .collect::<Result<Vec<_>>>()?;

        // Group files by partition value
        let mut partition_groups: HashMap<Option<String>, Vec<DataFile>> = HashMap::new();

        for file in data_files {
            // Extract partition value from file path or partition data
            let partition_key = extract_partition_value(file.file_path());

            // Apply partition filter if specified
            if let Some(filter) = options.partition_filter() {
                if partition_key.as_deref() != Some(filter) {
                    continue;
                }
            }

            partition_groups
                .entry(partition_key)
                .or_default()
                .push(file);
        }

        // Build compaction plan for each partition
        let mut partitions = Vec::new();

        for (partition_value, mut files) in partition_groups {
            // Filter to files smaller than max_input_file_size
            files.retain(|f| (f.file_size_in_bytes() as u64) < options.max_input_file_size());

            if files.len() < options.min_files_per_group() {
                // Not enough files to compact
                continue;
            }

            // Sort by size ascending for better bin-packing
            files.sort_by_key(|f| f.file_size_in_bytes());

            // Greedy bin-packing (first-fit with ascending size order)
            // Use the minimum of target_file_size and max_compaction_group_bytes
            // to ensure groups don't exceed memory limits
            let max_group_bytes = options
                .target_file_size()
                .min(options.max_compaction_group_bytes());
            let groups = bin_pack_files(files, max_group_bytes, options.min_files_per_group());

            if groups.is_empty() {
                continue;
            }

            let total_input_files: usize = groups.iter().map(|g| g.files().len()).sum();
            let total_input_bytes: u64 = groups.iter().map(|g| g.total_bytes()).sum();

            partitions.push(PartitionPlan {
                partition_value,
                groups,
                total_input_files,
                total_input_bytes,
            });
        }

        Ok(Self { partitions })
    }

    /// Check if there's nothing to compact
    pub fn is_empty(&self) -> bool {
        self.partitions.is_empty()
    }

    /// Total files across all partitions
    pub fn total_input_files(&self) -> usize {
        self.partitions.iter().map(|p| p.total_input_files).sum()
    }

    /// Total bytes across all partitions
    pub fn total_input_bytes(&self) -> u64 {
        self.partitions.iter().map(|p| p.total_input_bytes).sum()
    }

    /// Estimated output files across all partitions
    pub fn estimated_output_files(&self, target_size: u64) -> usize {
        self.partitions
            .iter()
            .map(|p| p.estimated_output_files(target_size))
            .sum()
    }

    /// Total number of partitions to compact
    pub fn partition_count(&self) -> usize {
        self.partitions.len()
    }
}

/// Extract partition value from file path (Hive-style partitioning)
fn extract_partition_value(file_path: &str) -> Option<String> {
    // Look for patterns like /key=value/ in the path
    // Supports multi-level partitions: /year=2024/month=01/ -> "year=2024/month=01"
    let partitions: Vec<&str> = file_path
        .split('/')
        .filter(|segment| {
            segment.contains('=') && !segment.starts_with("s3://") && !segment.starts_with("http")
        })
        .collect();

    if partitions.is_empty() {
        None
    } else {
        Some(partitions.join("/"))
    }
}

/// Greedy bin-packing algorithm (first-fit)
fn bin_pack_files(
    files: Vec<DataFile>,
    target_size: u64,
    min_files_per_group: usize,
) -> Vec<CompactionGroup> {
    // Track groups as Vec<Vec<DataFile>> during packing
    let mut group_files: Vec<Vec<DataFile>> = Vec::new();
    let mut group_sizes: Vec<u64> = Vec::new();

    for file in files {
        let file_size = file.file_size_in_bytes() as u64;

        // Try to find an existing group that can fit this file
        let mut placed = false;
        for (idx, current_size) in group_sizes.iter_mut().enumerate() {
            if *current_size + file_size <= target_size {
                *current_size += file_size;
                group_files[idx].push(file.clone());
                placed = true;
                break;
            }
        }

        // Create a new group if no existing group can fit the file
        if !placed {
            group_files.push(vec![file]);
            group_sizes.push(file_size);
        }
    }

    // Convert Vec<Vec<DataFile>> to Vec<CompactionGroup>
    // Filter out groups that don't meet the minimum file count
    group_files
        .into_iter()
        .filter(|files| files.len() >= min_files_per_group)
        .filter_map(|files| CompactionGroup::new(files).ok())
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_compaction_group_new_with_valid_files() {
        let file1 = DataFile::builder()
            .with_file_path("s3://bucket/file1.parquet")
            .with_file_format("PARQUET")
            .with_record_count(100)
            .with_file_size_in_bytes(1024)
            .build()
            .unwrap();

        let file2 = DataFile::builder()
            .with_file_path("s3://bucket/file2.parquet")
            .with_file_format("PARQUET")
            .with_record_count(200)
            .with_file_size_in_bytes(2048)
            .build()
            .unwrap();

        let group = CompactionGroup::new(vec![file1, file2]).unwrap();

        assert_eq!(group.files().len(), 2);
        assert_eq!(group.total_bytes(), 1024 + 2048);
        assert_eq!(group.total_records(), 100 + 200);
    }

    #[test]
    fn test_compaction_group_new_with_empty_files() {
        let result = CompactionGroup::new(vec![]);
        assert!(result.is_err());

        let err = result.unwrap_err();
        assert!(err
            .to_string()
            .contains("CompactionGroup cannot be created with empty input_files"));
    }

    #[test]
    fn test_compaction_group_getters() {
        let file = DataFile::builder()
            .with_file_path("s3://bucket/file.parquet")
            .with_file_format("PARQUET")
            .with_record_count(150)
            .with_file_size_in_bytes(3000)
            .build()
            .unwrap();

        let group = CompactionGroup::new(vec![file.clone()]).unwrap();

        // Test getter methods
        assert_eq!(group.files().len(), 1);
        assert_eq!(group.files()[0].file_path(), file.file_path());
        assert_eq!(group.total_bytes(), 3000);
        assert_eq!(group.total_records(), 150);
    }

    #[test]
    fn test_compaction_group_automatic_aggregates() {
        // Verify that aggregates are computed automatically and correctly
        let files: Vec<DataFile> = (0..5)
            .map(|i| {
                DataFile::builder()
                    .with_file_path(&format!("s3://bucket/file{}.parquet", i))
                    .with_file_format("PARQUET")
                    .with_record_count(100 + i as i64)
                    .with_file_size_in_bytes(1000 + i as i64)
                    .build()
                    .unwrap()
            })
            .collect();

        let expected_bytes: u64 = files.iter().map(|f| f.file_size_in_bytes() as u64).sum();
        let expected_records: u64 = files.iter().map(|f| f.record_count() as u64).sum();

        let group = CompactionGroup::new(files).unwrap();

        assert_eq!(group.total_bytes(), expected_bytes);
        assert_eq!(group.total_records(), expected_records);
    }

    #[test]
    fn test_extract_partition_value() {
        // Single partition
        assert_eq!(
            extract_partition_value("s3://bucket/table/data/dt=2024-01-15/file.parquet"),
            Some("dt=2024-01-15".to_string())
        );

        // No partition
        assert_eq!(
            extract_partition_value("s3://bucket/table/data/file.parquet"),
            None
        );

        // Multi-level partitions - should return all partition keys
        assert_eq!(
            extract_partition_value("s3://bucket/table/data/year=2024/month=01/file.parquet"),
            Some("year=2024/month=01".to_string())
        );

        // Three-level partitions
        assert_eq!(
            extract_partition_value(
                "s3://bucket/table/data/year=2024/month=01/day=15/file.parquet"
            ),
            Some("year=2024/month=01/day=15".to_string())
        );
    }

    #[test]
    fn test_bin_pack_empty() {
        let groups = bin_pack_files(vec![], 256 * 1024 * 1024, 3);
        assert!(groups.is_empty());
    }

    #[test]
    fn test_bin_pack_filters_small_groups() {
        // Create 2 files that are small enough to fit in target but below min_files_per_group
        let files: Vec<DataFile> = (0..2)
            .map(|i| {
                DataFile::builder()
                    .with_file_path(&format!("s3://bucket/file{}.parquet", i))
                    .with_file_format("PARQUET")
                    .with_record_count(100)
                    .with_file_size_in_bytes(1024)
                    .build()
                    .unwrap()
            })
            .collect();

        let groups = bin_pack_files(files, 256 * 1024 * 1024, 3);
        // Should be empty because group has only 2 files but min is 3
        assert!(groups.is_empty());
    }

    #[test]
    fn test_bin_pack_creates_valid_groups() {
        // Create enough files to form a valid group
        let files: Vec<DataFile> = (0..5)
            .map(|i| {
                DataFile::builder()
                    .with_file_path(&format!("s3://bucket/file{}.parquet", i))
                    .with_file_format("PARQUET")
                    .with_record_count(100)
                    .with_file_size_in_bytes(1024)
                    .build()
                    .unwrap()
            })
            .collect();

        let groups = bin_pack_files(files, 256 * 1024 * 1024, 3);
        // Should create one group with all 5 files
        assert_eq!(groups.len(), 1);
        assert_eq!(groups[0].files().len(), 5);
    }
}