Skip to main content

ailake_query/
compaction.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2use std::sync::Arc;
3use tracing::{debug, error, info};
4
5use ailake_catalog::{
6    make_data_file_entry, CatalogProvider, DataFileEntry, NewSnapshot, SnapshotOperation,
7    TableIdent, VectorIndexInfo,
8};
9use ailake_core::{AilakeResult, VectorStoragePolicy};
10use ailake_file::{AilakeFileReader, AilakeFileWriter};
11use ailake_store::Store;
12use ailake_vec::compute_centroid_and_radius;
13use arrow_array::RecordBatch;
14use arrow_schema::SchemaRef;
15use bytes::Bytes;
16
17/// Index strategy for the merged file produced by compaction.
18#[derive(Debug, Clone, Default)]
19pub enum CompactionIndexStrategy {
20    /// Detect GPU / CPU cores at compaction time and pick the best index.
21    /// IVF-PQ on GPU/many-core machines; HNSW elsewhere. (default)
22    #[default]
23    Auto,
24    /// Always rebuild with HNSW — highest recall, larger index.
25    ForceHnsw,
26    /// Always rebuild with IVF-PQ — smaller index, better S3 throughput.
27    ForceIvfPq,
28}
29
30#[derive(Debug, Clone)]
31pub struct CompactionConfig {
32    /// Trigger compaction only if at least this many files are eligible.
33    pub min_files_to_compact: usize,
34    /// Target output file size in bytes. Files below this are merged.
35    pub target_file_size_bytes: u64,
36    /// Index algorithm for the merged output file.
37    pub index_strategy: CompactionIndexStrategy,
38}
39
40impl Default for CompactionConfig {
41    fn default() -> Self {
42        Self {
43            min_files_to_compact: 4,
44            target_file_size_bytes: 128 * 1024 * 1024, // 128 MB
45            index_strategy: CompactionIndexStrategy::Auto,
46        }
47    }
48}
49
50#[derive(Debug, Clone, Copy)]
51pub enum CompactionMode {
52    Full,    // compact all files below target size
53    Partial, // compact the smallest N files
54}
55
56pub struct CompactionPlanner {
57    config: CompactionConfig,
58}
59
60impl CompactionPlanner {
61    pub fn new(config: CompactionConfig) -> Self {
62        Self { config }
63    }
64
65    /// Select files to compact: all files smaller than `target_file_size_bytes`,
66    /// provided at least `min_files_to_compact` qualify.
67    pub fn plan(&self, files: &[DataFileEntry]) -> Vec<DataFileEntry> {
68        let candidates: Vec<DataFileEntry> = files
69            .iter()
70            .filter(|f| f.file_size_bytes < self.config.target_file_size_bytes)
71            .cloned()
72            .collect();
73        if candidates.len() < self.config.min_files_to_compact {
74            debug!(
75                "ailake: compaction skipped — {} eligible files < min_files_to_compact={}",
76                candidates.len(),
77                self.config.min_files_to_compact
78            );
79            return vec![];
80        }
81        let total_bytes: u64 = candidates.iter().map(|f| f.file_size_bytes).sum();
82        info!(
83            "ailake: compaction plan — {} files ({} bytes) → 1 merged file",
84            candidates.len(),
85            total_bytes
86        );
87        candidates
88    }
89}
90
91/// Executes compaction plans: reads N small files, merges them into a single
92/// AI-Lake file with a rebuilt index, and commits to the catalog.
93///
94/// The index algorithm is chosen via `CompactionIndexStrategy` (default: `Auto`,
95/// which detects GPU / CPU cores at compaction time — the same heuristic used
96/// by `write_batch_auto`).
97pub struct CompactionExecutor {
98    store: Arc<dyn Store>,
99    policy: VectorStoragePolicy,
100    index_strategy: CompactionIndexStrategy,
101}
102
103impl CompactionExecutor {
104    pub fn new(store: Arc<dyn Store>, policy: VectorStoragePolicy) -> Self {
105        Self {
106            store,
107            policy,
108            index_strategy: CompactionIndexStrategy::Auto,
109        }
110    }
111
112    /// Override the default (Auto) index strategy for this executor.
113    pub fn with_index_strategy(mut self, strategy: CompactionIndexStrategy) -> Self {
114        self.index_strategy = strategy;
115        self
116    }
117
118    /// Merge `files` into a single new file at `output_path`.
119    /// Returns the DataFileEntry for the merged file.
120    pub async fn compact(
121        &self,
122        files: &[DataFileEntry],
123        output_path: &str,
124    ) -> AilakeResult<DataFileEntry> {
125        if files.is_empty() {
126            return Err(ailake_core::AilakeError::Catalog(
127                "compact: no files provided".into(),
128            ));
129        }
130
131        let mut all_batches: Vec<RecordBatch> = Vec::new();
132        let mut all_embeddings: Vec<Vec<f32>> = Vec::new();
133        let mut schema: Option<SchemaRef> = None;
134
135        for entry in files {
136            let bytes: Bytes = self.store.get(&entry.path).await?;
137            let reader = AilakeFileReader::new(bytes, &self.policy.column_name, self.policy.dim);
138            if !reader.is_ailake_file() {
139                debug!(
140                    "ailake: compaction skipping {} — not an AI-Lake file",
141                    entry.path
142                );
143                continue;
144            }
145            let (batch, embs) = reader.read_parquet()?;
146            if schema.is_none() {
147                schema = Some(batch.schema());
148            }
149            all_batches.push(batch);
150            all_embeddings.extend(embs);
151        }
152
153        if all_batches.is_empty() {
154            return Err(ailake_core::AilakeError::Catalog(
155                "compact: no valid AI-Lake files in input".into(),
156            ));
157        }
158
159        // Concatenate all row groups into one batch
160        let merged_batch = concat_batches(schema.unwrap(), &all_batches)?;
161        let record_count = merged_batch.num_rows() as u64;
162
163        // Write merged file with adaptive index selection.
164        let writer = {
165            let base = AilakeFileWriter::new(self.policy.clone());
166            match &self.index_strategy {
167                CompactionIndexStrategy::Auto => base.with_auto_index(),
168                CompactionIndexStrategy::ForceHnsw => base,
169                CompactionIndexStrategy::ForceIvfPq => {
170                    let cfg = ailake_index::IvfPqConfig::for_dataset(
171                        self.policy.dim as usize,
172                        all_embeddings.len(),
173                    );
174                    base.with_ivf_pq(cfg)
175                }
176            }
177        };
178        let file_bytes = writer.write(&merged_batch, &all_embeddings)?;
179        let file_size = file_bytes.len() as u64;
180        self.store.put(output_path, file_bytes.clone()).await?;
181
182        // Compute centroid and HNSW offsets for catalog entry
183        let centroid = compute_centroid_and_radius(&all_embeddings, self.policy.metric);
184        let reader = AilakeFileReader::new(file_bytes, &self.policy.column_name, self.policy.dim);
185        let header = reader.read_header()?;
186        let ailk_start = reader.ailk_offset()?;
187
188        let entry = make_data_file_entry(
189            output_path,
190            record_count,
191            file_size,
192            &centroid,
193            VectorIndexInfo {
194                column: &self.policy.column_name,
195                dim: self.policy.dim,
196                hnsw_offset: ailk_start + header.hnsw_offset,
197                hnsw_len: header.hnsw_len,
198            },
199        );
200        Ok(entry)
201    }
202
203    /// Full compaction workflow: plan, compact, drop old files from catalog, commit.
204    pub async fn run(
205        &self,
206        planner: &CompactionPlanner,
207        table: &TableIdent,
208        catalog: Arc<dyn CatalogProvider>,
209        output_prefix: &str,
210    ) -> AilakeResult<Option<DataFileEntry>> {
211        let all_files = catalog.list_files(table, None).await?;
212        let to_compact = planner.plan(&all_files);
213        if to_compact.is_empty() {
214            return Ok(None);
215        }
216
217        let ts = std::time::SystemTime::now()
218            .duration_since(std::time::UNIX_EPOCH)
219            .unwrap()
220            .as_millis();
221        let output_path = format!("{output_prefix}/compacted-{ts}.parquet");
222
223        let merged = self.compact(&to_compact, &output_path).await?;
224
225        // Commit: add merged file, remove input files (via Overwrite snapshot)
226        let snapshot = NewSnapshot {
227            snapshot_id: ailake_catalog::new_snapshot_id(),
228            parent_snapshot_id: None,
229            files: vec![merged.clone()],
230            operation: SnapshotOperation::Replace,
231            iceberg_schema: None,
232        };
233        catalog.commit_snapshot(table, snapshot).await?;
234
235        info!(
236            "ailake: compaction committed — merged {} files into {}",
237            to_compact.len(),
238            output_path
239        );
240
241        // Delete old files from store
242        for entry in &to_compact {
243            if let Err(e) = self.store.delete(&entry.path).await {
244                error!(
245                    "ailake: compaction cleanup failed — could not delete {}: {} \
246                     (orphan file in object store after successful catalog commit; \
247                     delete manually to reclaim storage)",
248                    entry.path, e
249                );
250            }
251        }
252
253        Ok(Some(merged))
254    }
255}
256
257fn concat_batches(schema: SchemaRef, batches: &[RecordBatch]) -> AilakeResult<RecordBatch> {
258    arrow_select::concat::concat_batches(&schema, batches)
259        .map_err(|e| ailake_core::AilakeError::Arrow(e.to_string()))
260}
261
262#[cfg(test)]
263mod tests {
264    use super::*;
265
266    #[test]
267    fn plan_returns_empty_if_too_few_files() {
268        let planner = CompactionPlanner::new(CompactionConfig {
269            min_files_to_compact: 4,
270            target_file_size_bytes: 1024 * 1024,
271            ..Default::default()
272        });
273        let files: Vec<DataFileEntry> = (0..3)
274            .map(|i| DataFileEntry {
275                path: format!("file-{i}.parquet"),
276                record_count: 10,
277                file_size_bytes: 100, // below target
278                centroid_b64: None,
279                radius: None,
280                hnsw_offset: None,
281                hnsw_len: None,
282                vector_column: None,
283                vector_dim: None,
284                extra_vector_indexes: vec![],
285                index_status: ailake_catalog::IndexStatus::Ready,
286                batch_id: None,
287            })
288            .collect();
289        assert!(planner.plan(&files).is_empty());
290    }
291
292    #[test]
293    fn plan_selects_small_files() {
294        let planner = CompactionPlanner::new(CompactionConfig {
295            min_files_to_compact: 2,
296            target_file_size_bytes: 1000,
297            ..Default::default()
298        });
299        let files = vec![
300            DataFileEntry {
301                path: "small.parquet".into(),
302                record_count: 5,
303                file_size_bytes: 500,
304                centroid_b64: None,
305                radius: None,
306                hnsw_offset: None,
307                hnsw_len: None,
308                vector_column: None,
309                vector_dim: None,
310                extra_vector_indexes: vec![],
311                index_status: ailake_catalog::IndexStatus::Ready,
312                batch_id: None,
313            },
314            DataFileEntry {
315                path: "large.parquet".into(),
316                record_count: 5000,
317                file_size_bytes: 200_000_000,
318                centroid_b64: None,
319                radius: None,
320                hnsw_offset: None,
321                hnsw_len: None,
322                vector_column: None,
323                vector_dim: None,
324                extra_vector_indexes: vec![],
325                index_status: ailake_catalog::IndexStatus::Ready,
326                batch_id: None,
327            },
328            DataFileEntry {
329                path: "also-small.parquet".into(),
330                record_count: 5,
331                file_size_bytes: 800,
332                centroid_b64: None,
333                radius: None,
334                hnsw_offset: None,
335                hnsw_len: None,
336                vector_column: None,
337                vector_dim: None,
338                extra_vector_indexes: vec![],
339                index_status: ailake_catalog::IndexStatus::Ready,
340                batch_id: None,
341            },
342        ];
343        let selected = planner.plan(&files);
344        assert_eq!(selected.len(), 2);
345        assert!(selected.iter().any(|f| f.path == "small.parquet"));
346        assert!(selected.iter().any(|f| f.path == "also-small.parquet"));
347    }
348
349    #[tokio::test]
350    async fn compact_merges_two_files() {
351        use ailake_core::{VectorMetric, VectorPrecision};
352        use ailake_store::LocalStore;
353        use arrow_array::{Int32Array, RecordBatch};
354        use arrow_schema::{DataType, Field, Schema};
355        use std::sync::Arc;
356        use tempfile::TempDir;
357
358        let dir = TempDir::new().unwrap();
359        let store = Arc::new(LocalStore::new(dir.path()));
360        let policy = VectorStoragePolicy {
361            column_name: "embedding".into(),
362            dim: 4,
363            metric: VectorMetric::Cosine,
364            precision: VectorPrecision::F16,
365            pq: None,
366            keep_raw_for_reranking: false,
367            pre_normalize: false,
368            hnsw_m: None,
369            hnsw_ef_construction: None,
370            rabitq: None,
371        };
372
373        // Write two small files
374        let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)]));
375        let embs_a: Vec<Vec<f32>> = vec![vec![1.0, 0.0, 0.0, 0.0], vec![0.0, 1.0, 0.0, 0.0]];
376        let embs_b: Vec<Vec<f32>> = vec![vec![0.0, 0.0, 1.0, 0.0], vec![0.0, 0.0, 0.0, 1.0]];
377
378        let batch_a = RecordBatch::try_new(
379            schema.clone(),
380            vec![Arc::new(Int32Array::from(vec![0i32, 1]))],
381        )
382        .unwrap();
383        let batch_b = RecordBatch::try_new(
384            schema.clone(),
385            vec![Arc::new(Int32Array::from(vec![2i32, 3]))],
386        )
387        .unwrap();
388
389        let writer_a = AilakeFileWriter::new(policy.clone());
390        let bytes_a = writer_a.write(&batch_a, &embs_a).unwrap();
391        let writer_b = AilakeFileWriter::new(policy.clone());
392        let bytes_b = writer_b.write(&batch_b, &embs_b).unwrap();
393
394        store.put("data/a.parquet", bytes_a.clone()).await.unwrap();
395        store.put("data/b.parquet", bytes_b.clone()).await.unwrap();
396
397        let entries = vec![
398            DataFileEntry {
399                path: "data/a.parquet".into(),
400                record_count: 2,
401                file_size_bytes: bytes_a.len() as u64,
402                centroid_b64: None,
403                radius: None,
404                hnsw_offset: None,
405                hnsw_len: None,
406                vector_column: None,
407                vector_dim: None,
408                extra_vector_indexes: vec![],
409                index_status: ailake_catalog::IndexStatus::Ready,
410                batch_id: None,
411            },
412            DataFileEntry {
413                path: "data/b.parquet".into(),
414                record_count: 2,
415                file_size_bytes: bytes_b.len() as u64,
416                centroid_b64: None,
417                radius: None,
418                hnsw_offset: None,
419                hnsw_len: None,
420                vector_column: None,
421                vector_dim: None,
422                extra_vector_indexes: vec![],
423                index_status: ailake_catalog::IndexStatus::Ready,
424                batch_id: None,
425            },
426        ];
427
428        let executor = CompactionExecutor::new(store.clone(), policy.clone());
429        let merged = executor
430            .compact(&entries, "data/merged.parquet")
431            .await
432            .unwrap();
433
434        assert_eq!(merged.record_count, 4);
435        assert_eq!(merged.path, "data/merged.parquet");
436
437        // Verify merged file is a valid AI-Lake file with all 4 rows
438        let merged_bytes = store.get("data/merged.parquet").await.unwrap();
439        let reader = AilakeFileReader::new(merged_bytes, "embedding", 4);
440        reader.verify_integrity().unwrap();
441        let (batch, embs) = reader.read_parquet().unwrap();
442        assert_eq!(batch.num_rows(), 4);
443        assert_eq!(embs.len(), 4);
444    }
445}