Skip to main content

mongreldb_core/
gc.rs

1//! Operational tools: garbage collection and integrity check.
2//!
3//! `gc` removes run files not referenced by the manifest (orphans from aborted
4//! flushes / old compaction inputs) and stale WAL segments (all but the active
5//! one). `check` re-verifies every referenced run's footer checksum.
6
7use crate::engine::Table;
8use crate::sorted_run::read_header;
9use crate::Result;
10use std::collections::HashSet;
11
12/// Outcome of a [`Table::gc`] pass.
13#[derive(Debug, Default, Clone)]
14pub struct GcReport {
15    pub runs_removed: usize,
16    pub wal_segments_removed: usize,
17    pub bytes_freed: u64,
18}
19
20/// Outcome of a [`Table::gc_versions`] pass (S1C-004).
21#[derive(Debug, Clone)]
22pub struct GcVersionsReport {
23    /// The unified version-retention floor the pass consulted: the oldest
24    /// epoch still held by ANY pin source (oldest active transaction
25    /// snapshot, configured history retention, and every registered
26    /// backup/PITR, replication, cursor/read-generation, and
27    /// online-index-build pin).
28    pub floor: crate::epoch::Epoch,
29    /// Retiring runs physically reaped because their `retire_epoch` was at or
30    /// below `floor`.
31    pub runs_reaped: usize,
32}
33
34/// Outcome of a [`Table::check`] pass.
35#[derive(Debug, Default, Clone)]
36pub struct CheckReport {
37    pub runs_checked: usize,
38    pub runs_ok: usize,
39    pub issues: Vec<String>,
40}
41
42/// Outcome of a [`Table::doctor`] pass (best-effort repair): corrupt runs are
43/// dropped from the manifest so the table is usable again, at the cost of the
44/// data they held.
45#[derive(Debug, Default, Clone)]
46pub struct DoctorReport {
47    pub runs_dropped: Vec<u128>,
48}
49
50impl Table {
51    /// Remove orphan run files (not in the manifest) and all but the active WAL
52    /// segment. Safe to run any time; readers pin snapshots, not files.
53    pub fn gc(&self) -> Result<GcReport> {
54        let mut report = GcReport::default();
55        let live: HashSet<u128> = self
56            .run_refs()
57            .iter()
58            .map(|r| r.run_id)
59            .chain(self.retiring_run_ids())
60            .collect();
61
62        for entry in std::fs::read_dir(self.runs_dir())? {
63            let entry = entry?;
64            let path = entry.path();
65            let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
66                continue;
67            };
68            let Some(id) = name
69                .strip_prefix("r-")
70                .and_then(|s| s.strip_suffix(".sr"))
71                .and_then(|s| s.parse::<u128>().ok())
72            else {
73                continue;
74            };
75            if !live.contains(&id) {
76                let bytes = std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0);
77                self.release_run_reader(id);
78                if std::fs::remove_file(&path).is_ok() {
79                    report.runs_removed += 1;
80                    report.bytes_freed += bytes;
81                }
82            }
83        }
84
85        // WAL: keep only the highest-numbered segment.
86        let mut segs: Vec<(u32, std::path::PathBuf)> = Vec::new();
87        for entry in std::fs::read_dir(self.wal_dir())? {
88            let entry = entry?;
89            let path = entry.path();
90            let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
91                continue;
92            };
93            let Some(n) = name
94                .strip_prefix("seg-")
95                .and_then(|s| s.strip_suffix(".wal"))
96                .and_then(|s| s.parse::<u32>().ok())
97            else {
98                continue;
99            };
100            segs.push((n, path));
101        }
102        segs.sort_by_key(|(n, _)| *n);
103        if let Some((_, active)) = segs.last() {
104            let active = active.clone();
105            for (_, path) in segs {
106                if path != active {
107                    let bytes = std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0);
108                    if std::fs::remove_file(&path).is_ok() {
109                        report.wal_segments_removed += 1;
110                        report.bytes_freed += bytes;
111                    }
112                }
113            }
114        }
115        Ok(report)
116    }
117
118    /// Reclaim retiring runs gated on the unified version-retention floor
119    /// (S1C-004). The floor — [`Table::version_gc_floor`] — is the oldest
120    /// epoch held by ANY pin source: the oldest active transaction snapshot,
121    /// the configured history-retention window, and every pin registered in
122    /// the table's [`crate::retention::PinRegistry`] (backup/PITR,
123    /// replication, cursor/read-generation, online-index-build). A retiring
124    /// run is reaped only when its `retire_epoch` is at or below that floor,
125    /// so no pin source can lose versions it still reads.
126    ///
127    /// The `Database`-level backup run-file pins (`backup_pins`) are still
128    /// consulted by the `Database` GC/checkpoint paths; merging that
129    /// mechanism into the [`crate::retention::PinRegistry`] is a documented
130    /// follow-up.
131    pub fn gc_versions(&mut self) -> Result<GcVersionsReport> {
132        let floor = self.version_gc_floor();
133        let runs_reaped = self.reap_retiring(floor, &std::collections::HashSet::new())?;
134        Ok(GcVersionsReport { floor, runs_reaped })
135    }
136
137    /// Verify every manifest-referenced run's footer checksum.
138    pub fn check(&self) -> Result<CheckReport> {
139        let mut report = CheckReport::default();
140        for rr in self.run_refs() {
141            report.runs_checked += 1;
142            let path = self.run_path(rr.run_id as u64);
143            match read_header(&path) {
144                Ok(_) => report.runs_ok += 1,
145                Err(e) => report.issues.push(format!("run {}: {e}", rr.run_id)),
146            }
147        }
148        Ok(report)
149    }
150
151    /// Best-effort repair: drop any manifest-referenced run that fails its
152    /// checksum, so the table reopens in a consistent (if lossy) state.
153    pub fn doctor(&mut self) -> Result<DoctorReport> {
154        let mut report = DoctorReport::default();
155        let live: Vec<u128> = self.run_refs().iter().map(|r| r.run_id).collect();
156        let mut kept: Vec<crate::manifest::RunRef> = Vec::new();
157        for id in live {
158            let path = self.run_path(id as u64);
159            if read_header(&path).is_ok() {
160                if let Some(rr) = self.run_refs().iter().find(|r| r.run_id == id).cloned() {
161                    kept.push(rr);
162                }
163            } else {
164                report.runs_dropped.push(id);
165            }
166        }
167        self.set_run_refs(kept);
168        self.persist_manifest(self.current_epoch())?;
169        // If any run was dropped, the checkpoint now references row-ids whose
170        // data is gone → invalidate it so reopen rebuilds from survivors.
171        if !report.runs_dropped.is_empty() {
172            self.invalidate_index_checkpoint();
173        }
174        Ok(report)
175    }
176}
177
178#[cfg(test)]
179mod tests {
180    use super::*;
181    use crate::schema::{ColumnDef, ColumnFlags, Schema, TypeId};
182    use crate::Value;
183    use tempfile::tempdir;
184
185    fn schema() -> Schema {
186        Schema {
187            schema_id: 1,
188            columns: vec![ColumnDef {
189                id: 1,
190                name: "v".into(),
191                ty: TypeId::Int64,
192                flags: ColumnFlags::empty().with(ColumnFlags::PRIMARY_KEY),
193                default_value: None,
194                embedding_source: None,
195            }],
196            indexes: Vec::new(),
197            colocation: vec![],
198            constraints: Default::default(),
199            clustered: false,
200        }
201    }
202
203    #[test]
204    fn gc_removes_orphan_runs_and_old_wal_segments() {
205        let dir = tempdir().unwrap();
206        let mut db = Table::create(dir.path(), schema(), 1).unwrap();
207        db.set_mutable_run_spill_bytes(1); // spill every flush to a run
208        db.put(vec![(1, Value::Int64(1))]).unwrap();
209        db.flush().unwrap(); // run 1 + rotated WAL
210                             // Orphan run file.
211        std::fs::write(dir.path().join("_runs").join("r-777.sr"), b"junk").unwrap();
212
213        let report = db.gc().unwrap();
214        assert!(report.runs_removed >= 1, "orphan run removed");
215        assert!(!dir.path().join("_runs").join("r-777.sr").exists());
216
217        // check should still pass for the live run.
218        let check = db.check().unwrap();
219        assert_eq!(check.runs_checked, 1);
220        assert!(check.issues.is_empty(), "{:?}", check.issues);
221    }
222
223    #[test]
224    fn check_flags_a_corrupt_run() {
225        let dir = tempdir().unwrap();
226        let mut db = Table::create(dir.path(), schema(), 1).unwrap();
227        db.set_mutable_run_spill_bytes(1); // spill every flush to a run
228        db.put(vec![(1, Value::Int64(1))]).unwrap();
229        db.flush().unwrap();
230        // Corrupt the live run.
231        let live = dir.path().join("_runs").join("r-1.sr");
232        let mut bytes = std::fs::read(&live).unwrap();
233        bytes[300] ^= 0xFF;
234        std::fs::write(&live, bytes).unwrap();
235
236        let check = db.check().unwrap();
237        assert_eq!(check.runs_checked, 1);
238        assert!(!check.issues.is_empty(), "corruption must be flagged");
239    }
240
241    /// S1C-004: every pin source blocks version GC while held; reclamation
242    /// proceeds once the pin is released.
243    #[test]
244    fn gc_versions_blocked_by_each_pin_source_and_reclaims_after_release() {
245        use crate::epoch::Epoch;
246        use crate::retention::PinSource;
247
248        let dir = tempdir().unwrap();
249        let mut db = Table::create(dir.path(), schema(), 1).unwrap();
250        db.set_mutable_run_spill_bytes(1);
251        db.put(vec![(1, Value::Int64(1))]).unwrap();
252        db.flush().unwrap(); // run 1
253        db.put(vec![(1, Value::Int64(2))]).unwrap();
254        db.flush().unwrap(); // run 2
255        db.compact().unwrap(); // merged run 3; runs 1+2 retiring at epoch 2
256        assert_eq!(db.run_count(), 1);
257        assert_eq!(db.current_epoch(), Epoch(2));
258
259        for source in PinSource::ALL {
260            let guard = db.pin_registry().pin(source, Epoch(1));
261            assert_eq!(
262                db.version_gc_floor(),
263                Epoch(1),
264                "{source:?} pin must lower the reclamation floor"
265            );
266            let report = db.gc_versions().unwrap();
267            assert_eq!(report.floor, Epoch(1));
268            assert_eq!(
269                report.runs_reaped, 0,
270                "{source:?} pin must block retiring-run reclamation"
271            );
272            drop(guard);
273        }
274
275        // No pins left: the floor returns to the visible epoch (2), which is
276        // at the retire epoch — both superseded runs are reclaimed.
277        assert_eq!(db.version_gc_floor(), Epoch(2));
278        let report = db.gc_versions().unwrap();
279        assert_eq!(report.runs_reaped, 2, "all retiring runs reaped");
280    }
281
282    /// S1C-004 diagnostics: local snapshot pins project as the transaction
283    /// source; registered pins appear with their own source and epoch.
284    #[test]
285    fn version_pins_report_lists_registered_and_projected_sources() {
286        use crate::epoch::Epoch;
287        use crate::retention::PinSource;
288
289        let dir = tempdir().unwrap();
290        let mut db = Table::create(dir.path(), schema(), 1).unwrap();
291        db.put(vec![(1, Value::Int64(1))]).unwrap();
292        db.commit().unwrap();
293        assert!(db.version_pins_report().is_empty());
294
295        let snapshot = db.pin_snapshot();
296        let backup = db.pin_registry().pin(PinSource::BackupPitr, Epoch(0));
297        let report = db.version_pins_report();
298        assert_eq!(report.len(), 2);
299        let transaction = report.get(PinSource::TransactionSnapshot).unwrap();
300        assert_eq!(transaction.oldest_epoch, snapshot.epoch);
301        assert_eq!(transaction.pin_count, 0, "projection carries no guard");
302        let backup_info = report.get(PinSource::BackupPitr).unwrap();
303        assert_eq!(backup_info.oldest_epoch, Epoch(0));
304        assert_eq!(backup_info.pin_count, 1);
305        assert_eq!(report.oldest_epoch(), Some(Epoch(0)));
306
307        drop(backup);
308        db.unpin_snapshot(snapshot);
309        assert!(db.version_pins_report().is_empty());
310    }
311}