1use crate::engine::Table;
8use crate::sorted_run::read_header;
9use crate::Result;
10use std::collections::HashSet;
11
12#[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#[derive(Debug, Clone)]
22pub struct GcVersionsReport {
23 pub floor: crate::epoch::Epoch,
29 pub runs_reaped: usize,
32}
33
34#[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#[derive(Debug, Default, Clone)]
46pub struct DoctorReport {
47 pub runs_dropped: Vec<u128>,
48}
49
50impl Table {
51 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 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 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 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 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 !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); db.put(vec![(1, Value::Int64(1))]).unwrap();
209 db.flush().unwrap(); 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 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); db.put(vec![(1, Value::Int64(1))]).unwrap();
229 db.flush().unwrap();
230 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 #[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(); db.put(vec![(1, Value::Int64(2))]).unwrap();
254 db.flush().unwrap(); db.compact().unwrap(); 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 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 #[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}