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, Default, Clone)]
22pub struct CheckReport {
23 pub runs_checked: usize,
24 pub runs_ok: usize,
25 pub issues: Vec<String>,
26}
27
28#[derive(Debug, Default, Clone)]
32pub struct DoctorReport {
33 pub runs_dropped: Vec<u128>,
34}
35
36impl Table {
37 pub fn gc(&self) -> Result<GcReport> {
40 let mut report = GcReport::default();
41 let live: HashSet<u128> = self.run_refs().iter().map(|r| r.run_id).collect();
42
43 for entry in std::fs::read_dir(self.runs_dir())? {
44 let entry = entry?;
45 let path = entry.path();
46 let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
47 continue;
48 };
49 let Some(id) = name
50 .strip_prefix("r-")
51 .and_then(|s| s.strip_suffix(".sr"))
52 .and_then(|s| s.parse::<u128>().ok())
53 else {
54 continue;
55 };
56 if !live.contains(&id) {
57 let bytes = std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0);
58 if std::fs::remove_file(&path).is_ok() {
59 report.runs_removed += 1;
60 report.bytes_freed += bytes;
61 }
62 }
63 }
64
65 let mut segs: Vec<(u32, std::path::PathBuf)> = Vec::new();
67 for entry in std::fs::read_dir(self.wal_dir())? {
68 let entry = entry?;
69 let path = entry.path();
70 let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
71 continue;
72 };
73 let Some(n) = name
74 .strip_prefix("seg-")
75 .and_then(|s| s.strip_suffix(".wal"))
76 .and_then(|s| s.parse::<u32>().ok())
77 else {
78 continue;
79 };
80 segs.push((n, path));
81 }
82 segs.sort_by_key(|(n, _)| *n);
83 if let Some((_, active)) = segs.last() {
84 let active = active.clone();
85 for (_, path) in segs {
86 if path != active {
87 let bytes = std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0);
88 if std::fs::remove_file(&path).is_ok() {
89 report.wal_segments_removed += 1;
90 report.bytes_freed += bytes;
91 }
92 }
93 }
94 }
95 Ok(report)
96 }
97
98 pub fn check(&self) -> Result<CheckReport> {
100 let mut report = CheckReport::default();
101 for rr in self.run_refs() {
102 report.runs_checked += 1;
103 let path = self.run_path(rr.run_id as u64);
104 match read_header(&path) {
105 Ok(_) => report.runs_ok += 1,
106 Err(e) => report.issues.push(format!("run {}: {e}", rr.run_id)),
107 }
108 }
109 Ok(report)
110 }
111
112 pub fn doctor(&mut self) -> Result<DoctorReport> {
115 let mut report = DoctorReport::default();
116 let live: Vec<u128> = self.run_refs().iter().map(|r| r.run_id).collect();
117 let mut kept: Vec<crate::manifest::RunRef> = Vec::new();
118 for id in live {
119 let path = self.run_path(id as u64);
120 if read_header(&path).is_ok() {
121 if let Some(rr) = self.run_refs().iter().find(|r| r.run_id == id).cloned() {
122 kept.push(rr);
123 }
124 } else {
125 report.runs_dropped.push(id);
126 }
127 }
128 self.set_run_refs(kept);
129 self.persist_manifest(self.current_epoch())?;
130 if !report.runs_dropped.is_empty() {
133 self.invalidate_index_checkpoint();
134 }
135 Ok(report)
136 }
137}
138
139#[cfg(test)]
140mod tests {
141 use super::*;
142 use crate::schema::{ColumnDef, ColumnFlags, Schema, TypeId};
143 use crate::Value;
144 use tempfile::tempdir;
145
146 fn schema() -> Schema {
147 Schema {
148 schema_id: 1,
149 columns: vec![ColumnDef {
150 id: 1,
151 name: "v".into(),
152 ty: TypeId::Int64,
153 flags: ColumnFlags::empty().with(ColumnFlags::PRIMARY_KEY),
154 }],
155 indexes: Vec::new(),
156 colocation: vec![],
157 constraints: Default::default(),
158 }
159 }
160
161 #[test]
162 fn gc_removes_orphan_runs_and_old_wal_segments() {
163 let dir = tempdir().unwrap();
164 let mut db = Table::create(dir.path(), schema(), 1).unwrap();
165 db.set_mutable_run_spill_bytes(1); db.put(vec![(1, Value::Int64(1))]).unwrap();
167 db.flush().unwrap(); std::fs::write(dir.path().join("_runs").join("r-777.sr"), b"junk").unwrap();
170
171 let report = db.gc().unwrap();
172 assert!(report.runs_removed >= 1, "orphan run removed");
173 assert!(!dir.path().join("_runs").join("r-777.sr").exists());
174
175 let check = db.check().unwrap();
177 assert_eq!(check.runs_checked, 1);
178 assert!(check.issues.is_empty(), "{:?}", check.issues);
179 }
180
181 #[test]
182 fn check_flags_a_corrupt_run() {
183 let dir = tempdir().unwrap();
184 let mut db = Table::create(dir.path(), schema(), 1).unwrap();
185 db.set_mutable_run_spill_bytes(1); db.put(vec![(1, Value::Int64(1))]).unwrap();
187 db.flush().unwrap();
188 let live = dir.path().join("_runs").join("r-1.sr");
190 let mut bytes = std::fs::read(&live).unwrap();
191 bytes[300] ^= 0xFF;
192 std::fs::write(&live, bytes).unwrap();
193
194 let check = db.check().unwrap();
195 assert_eq!(check.runs_checked, 1);
196 assert!(!check.issues.is_empty(), "corruption must be flagged");
197 }
198}