Skip to main content

velesdb_core/column_store/
vacuum.rs

1//! Vacuum and compaction operations for `ColumnStore`.
2//!
3//! Extracted from `mod.rs` for maintainability (04-06 module splitting).
4//! Handles tombstone removal, column compaction, and deletion bitmap operations.
5
6use super::types::{TypedColumn, VacuumConfig, VacuumStats};
7use super::ColumnStore;
8
9use roaring::RoaringBitmap;
10use std::collections::HashMap;
11
12/// Filters a column vector, removing entries at deleted indices and counting reclaimed bytes.
13fn compact_vec<T: Copy>(
14    data: &[T],
15    deleted: &rustc_hash::FxHashSet<usize>,
16    element_bytes: u64,
17) -> (Vec<T>, u64) {
18    let mut new_data = Vec::with_capacity(data.len().saturating_sub(deleted.len()));
19    let mut bytes_reclaimed = 0u64;
20    for (idx, value) in data.iter().enumerate() {
21        if deleted.contains(&idx) {
22            bytes_reclaimed += element_bytes;
23        } else {
24            new_data.push(*value);
25        }
26    }
27    (new_data, bytes_reclaimed)
28}
29
30/// Clone-based variant of `compact_vec` for non-Copy types (e.g., `SmallVec`).
31fn compact_vec_clone<T: Clone>(
32    data: &[T],
33    deleted: &rustc_hash::FxHashSet<usize>,
34    element_bytes: u64,
35) -> (Vec<T>, u64) {
36    let mut new_data = Vec::with_capacity(data.len().saturating_sub(deleted.len()));
37    let mut bytes_reclaimed = 0u64;
38    for (idx, value) in data.iter().enumerate() {
39        if deleted.contains(&idx) {
40            bytes_reclaimed += element_bytes;
41        } else {
42            new_data.push(value.clone());
43        }
44    }
45    (new_data, bytes_reclaimed)
46}
47
48impl ColumnStore {
49    /// Runs vacuum to remove tombstones and compact data.
50    ///
51    /// This operation removes deleted rows from the column store, reclaiming
52    /// space and improving query performance. The operation is done in-place
53    /// by building new column vectors without the deleted rows.
54    ///
55    /// # Arguments
56    ///
57    /// * `_config` - Vacuum configuration. **Currently ignored**: the vacuum
58    ///   runs as a single in-memory pass (`batch_size`, `sync`, and
59    ///   `yield_interval_ms` have no effect).
60    ///
61    /// # Returns
62    ///
63    /// Statistics about the vacuum operation.
64    pub fn vacuum(&mut self, _config: VacuumConfig) -> VacuumStats {
65        let start = std::time::Instant::now();
66        let tombstones_found = self.deleted_rows.len();
67
68        if tombstones_found == 0 {
69            return VacuumStats {
70                tombstones_found: 0,
71                completed: true,
72                duration_ms: start.elapsed().as_millis() as u64,
73                ..Default::default()
74            };
75        }
76
77        let mut stats = VacuumStats {
78            tombstones_found,
79            ..Default::default()
80        };
81
82        let (old_to_new, new_row_count) = self.build_compaction_map();
83        self.compact_all_columns(&mut stats);
84        self.remap_primary_index(&old_to_new);
85        self.remap_row_expiry(&old_to_new);
86
87        stats.tombstones_removed = self.deleted_rows.len();
88        self.deleted_rows.clear();
89        self.deletion_bitmap.clear();
90        self.row_count = new_row_count;
91
92        stats.completed = true;
93        stats.duration_ms = start.elapsed().as_millis() as u64;
94        stats
95    }
96
97    /// Builds the old-to-new row index mapping, skipping deleted rows.
98    fn build_compaction_map(&self) -> (HashMap<usize, usize>, usize) {
99        let mut old_to_new: HashMap<usize, usize> = HashMap::new();
100        let mut new_idx = 0;
101        for old_idx in 0..self.row_count {
102            if !self.deleted_rows.contains(&old_idx) {
103                old_to_new.insert(old_idx, new_idx);
104                new_idx += 1;
105            }
106        }
107        (old_to_new, new_idx)
108    }
109
110    /// Compacts all columns, removing deleted rows and accumulating reclaimed bytes.
111    fn compact_all_columns(&mut self, stats: &mut VacuumStats) {
112        for column in self.columns.values_mut() {
113            let (new_col, bytes) = Self::compact_column(column, &self.deleted_rows);
114            stats.bytes_reclaimed += bytes;
115            *column = new_col;
116        }
117    }
118
119    /// Remaps the primary index to use compacted row indices.
120    fn remap_primary_index(&mut self, old_to_new: &HashMap<usize, usize>) {
121        if self.primary_key_column.is_none() {
122            return;
123        }
124        let mut new_primary_index: HashMap<i64, usize> = HashMap::new();
125        let mut new_row_idx_to_pk: HashMap<usize, i64> = HashMap::new();
126        for (pk, old_idx) in &self.primary_index {
127            if let Some(&new_idx) = old_to_new.get(old_idx) {
128                new_primary_index.insert(*pk, new_idx);
129                new_row_idx_to_pk.insert(new_idx, *pk);
130            }
131        }
132        self.primary_index = new_primary_index;
133        self.row_idx_to_pk = new_row_idx_to_pk;
134    }
135
136    /// Remaps row expiry timestamps to compacted row indices.
137    fn remap_row_expiry(&mut self, old_to_new: &HashMap<usize, usize>) {
138        let mut new_row_expiry: HashMap<usize, u64> = HashMap::new();
139        for (old_idx, expiry) in &self.row_expiry {
140            if let Some(&new_idx) = old_to_new.get(old_idx) {
141                new_row_expiry.insert(new_idx, *expiry);
142            }
143        }
144        self.row_expiry = new_row_expiry;
145    }
146
147    /// Compacts a single column by removing deleted rows.
148    fn compact_column(
149        column: &TypedColumn,
150        deleted: &rustc_hash::FxHashSet<usize>,
151    ) -> (TypedColumn, u64) {
152        match column {
153            TypedColumn::Int(data) => {
154                let (new_data, bytes) = compact_vec(data, deleted, 8);
155                (TypedColumn::Int(new_data), bytes)
156            }
157            TypedColumn::Float(data) => {
158                let (new_data, bytes) = compact_vec(data, deleted, 8);
159                (TypedColumn::Float(new_data), bytes)
160            }
161            TypedColumn::String(data) => {
162                let (new_data, bytes) = compact_vec(data, deleted, 4);
163                (TypedColumn::String(new_data), bytes)
164            }
165            TypedColumn::Bool(data) => {
166                let (new_data, bytes) = compact_vec(data, deleted, 1);
167                (TypedColumn::Bool(new_data), bytes)
168            }
169            TypedColumn::Array {
170                element_type, data, ..
171            } => {
172                // Estimate ~64 bytes per array cell (SmallVec overhead).
173                let (new_data, bytes) = compact_vec_clone(data, deleted, 64);
174                (
175                    TypedColumn::Array {
176                        element_type: element_type.clone(),
177                        data: new_data,
178                    },
179                    bytes,
180                )
181            }
182            TypedColumn::GeoPoint(data) => {
183                let (new_data, bytes) = compact_vec(data, deleted, 16);
184                (TypedColumn::GeoPoint(new_data), bytes)
185            }
186        }
187    }
188
189    /// Returns whether vacuum is recommended based on tombstone ratio.
190    ///
191    /// # Arguments
192    ///
193    /// * `threshold` - Ratio of deleted rows to trigger vacuum (0.0-1.0)
194    #[must_use]
195    pub fn should_vacuum(&self, threshold: f64) -> bool {
196        if self.row_count == 0 {
197            return false;
198        }
199        let ratio = self.deleted_rows.len() as f64 / self.row_count as f64;
200        ratio >= threshold
201    }
202
203    // =========================================================================
204    // EPIC-043 US-002: RoaringBitmap Filtering
205    // =========================================================================
206
207    /// Checks if a row is deleted using RoaringBitmap (O(1) lookup).
208    ///
209    /// This is faster than FxHashSet for large deletion sets.
210    #[must_use]
211    #[inline]
212    pub fn is_row_deleted_bitmap(&self, row_idx: usize) -> bool {
213        if let Ok(idx) = u32::try_from(row_idx) {
214            self.deletion_bitmap.contains(idx)
215        } else {
216            // Fallback to FxHashSet for indices > u32::MAX
217            self.deleted_rows.contains(&row_idx)
218        }
219    }
220
221    /// Returns an iterator over live (non-deleted) row indices.
222    ///
223    /// Uses RoaringBitmap for efficient filtering.
224    pub fn live_row_indices(&self) -> impl Iterator<Item = usize> + '_ {
225        (0..self.row_count).filter(|&idx| !self.is_row_deleted_bitmap(idx))
226    }
227
228    /// Returns the deletion bitmap for advanced filtering operations.
229    #[must_use]
230    pub fn deletion_bitmap(&self) -> &RoaringBitmap {
231        &self.deletion_bitmap
232    }
233
234    /// Returns the number of deleted rows using the bitmap (O(1)).
235    #[must_use]
236    pub fn deleted_count_bitmap(&self) -> u64 {
237        self.deletion_bitmap.len()
238    }
239}