1use std::collections::BTreeMap;
13use std::path::{Path, PathBuf};
14use std::time::SystemTime;
15
16use sail_key::QueryKey;
17use serde::{Deserialize, Serialize};
18
19use crate::{DiskCache, Meta, Problem, STALE_TEMP, parse_entry, shape_ok};
20
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub enum FileKind {
24 Entry(QueryKey),
26 EntryDirectory,
28 Temp,
30 Stray,
32}
33
34#[derive(Debug, Clone)]
36pub struct Listed {
37 pub path: PathBuf,
39 pub kind: FileKind,
41 pub bytes: u64,
43 pub used: SystemTime,
46}
47
48#[must_use]
50pub fn parse_key(hex: &str) -> Option<QueryKey> {
51 if hex.len() != 64 || hex.bytes().any(|b| !matches!(b, b'0'..=b'9' | b'a'..=b'f')) {
52 return None;
53 }
54 let mut k = [0u8; 32];
55 for (i, b) in k.iter_mut().enumerate() {
56 *b = u8::from_str_radix(hex.get(2 * i..2 * i + 2)?, 16).ok()?;
57 }
58 Some(QueryKey(k))
59}
60
61fn last_used(meta: &std::fs::Metadata) -> SystemTime {
62 let m = meta.modified().unwrap_or(SystemTime::UNIX_EPOCH);
63 let a = meta.accessed().unwrap_or(SystemTime::UNIX_EPOCH);
64 m.max(a)
65}
66
67fn listed(path: PathBuf, kind: FileKind, meta: &std::fs::Metadata) -> Listed {
68 Listed {
69 path,
70 kind,
71 bytes: meta.len(),
72 used: last_used(meta),
73 }
74}
75
76fn is_prefix_dir(name: &str) -> bool {
77 name.len() == 2 && name.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
78}
79
80impl DiskCache {
81 #[must_use]
84 pub fn list(&self) -> Vec<Listed> {
85 let mut out = Vec::new();
86 let Ok(dirs) = std::fs::read_dir(self.entries_dir()) else {
87 return out;
88 };
89 for d in dirs.flatten() {
90 let path = d.path();
91 let name = d.file_name().to_string_lossy().into_owned();
92 let Ok(meta) = std::fs::symlink_metadata(&path) else {
93 continue;
94 };
95 if !meta.is_dir() || !is_prefix_dir(&name) {
96 out.push(listed(path, FileKind::Stray, &meta));
97 continue;
98 }
99 let Ok(files) = std::fs::read_dir(&path) else {
100 continue;
101 };
102 for f in files.flatten() {
103 let fpath = f.path();
104 let fname = f.file_name().to_string_lossy().into_owned();
105 let Ok(fmeta) = std::fs::symlink_metadata(&fpath) else {
106 continue;
107 };
108 let key = parse_key(&fname).filter(|_| fname.starts_with(name.as_str()));
109 let kind = match key {
110 Some(k) if fmeta.is_file() => FileKind::Entry(k),
111 Some(_) if fmeta.is_dir() => FileKind::EntryDirectory,
112 _ if fname.starts_with(".tmp-") && fmeta.is_file() => FileKind::Temp,
113 _ => FileKind::Stray,
114 };
115 out.push(listed(fpath, kind, &fmeta));
116 }
117 }
118 out.sort_by(|a, b| a.path.cmp(&b.path));
119 out
120 }
121
122 #[must_use]
124 pub fn usage(&self) -> Usage {
125 let mut u = Usage::default();
126 for l in self.list() {
127 if matches!(l.kind, FileKind::Entry(_)) {
128 u.entries += 1;
129 u.bytes += l.bytes;
130 }
131 }
132 u
133 }
134
135 pub fn check_file(path: &Path, key: &QueryKey) -> Result<(Meta, Vec<u8>), Problem> {
142 let data = std::fs::read(path).map_err(|_| Problem::Unreadable)?;
143 let (meta, reply) = parse_entry(&data, &key.to_string())?;
144 if !shape_ok(&meta.command, &reply) {
145 return Err(Problem::BadShape);
146 }
147 Ok((meta, reply))
148 }
149
150 fn problem(l: &Listed, now: SystemTime) -> Option<Problem> {
153 match l.kind {
154 FileKind::Entry(k) => Self::check_file(&l.path, &k).err(),
155 FileKind::EntryDirectory => Some(Problem::Directory),
156 FileKind::Temp => now
157 .duration_since(l.used)
158 .is_ok_and(|age| age >= STALE_TEMP)
159 .then_some(Problem::StaleTemp),
160 FileKind::Stray => Some(Problem::Stray),
161 }
162 }
163
164 #[must_use]
168 pub fn summarize(&self) -> Summary {
169 let mut s = Summary::default();
170 let mut fractions = Vec::new();
171 for l in self.list() {
172 let FileKind::Entry(k) = l.kind else {
173 match l.kind {
174 FileKind::Temp => s.temp_files += 1,
175 _ => s.invalid += 1,
176 }
177 continue;
178 };
179 let Ok((meta, reply)) = Self::check_file(&l.path, &k) else {
180 if l.path.exists() {
182 s.invalid += 1;
183 }
184 continue;
185 };
186 s.entries += 1;
187 s.bytes += l.bytes;
188 let by = s.by_command.entry(meta.command.clone()).or_default();
189 by.entries += 1;
190 by.bytes += l.bytes;
191 if meta.command.starts_with("check-sat") && reply.trim_ascii() == b"unknown" {
192 let unknown = &mut s.unknown;
193 unknown.entries += 1;
194 match meta.effort {
195 Some(e) => {
196 unknown.with_effort += 1;
197 let reason = e.reason.clone().unwrap_or_else(|| "(none)".to_owned());
198 *unknown.by_reason.entry(reason).or_default() += 1;
199 if let (Some(used), Some(limit)) = (e.used, e.limit)
200 && limit > 0
201 {
202 #[allow(clippy::cast_precision_loss, reason = "a ratio for display")]
203 fractions.push(used as f64 / limit as f64);
204 if used.saturating_mul(2) <= limit {
205 unknown.within_half_limit += 1;
206 }
207 }
208 }
209 None => {
210 *unknown
211 .by_reason
212 .entry("(no effort)".to_owned())
213 .or_default() += 1;
214 }
215 }
216 }
217 }
218 fractions.sort_by(f64::total_cmp);
219 if let (Some(&min), Some(&max)) = (fractions.first(), fractions.last()) {
220 s.unknown.used_fraction = Some(Spread {
221 min,
222 median: fractions.get(fractions.len() / 2).copied().unwrap_or(min),
223 max,
224 });
225 }
226 s
227 }
228
229 #[must_use]
232 pub fn verify(&self, remove: bool) -> VerifyReport {
233 let mut r = VerifyReport::default();
234 let now = SystemTime::now();
235 for l in self.list() {
236 if matches!(l.kind, FileKind::Entry(_)) {
237 r.checked += 1;
238 }
239 match Self::problem(&l, now) {
240 None if matches!(l.kind, FileKind::Entry(_)) => r.valid += 1,
241 None => {}
242 Some(Problem::Unreadable) if !l.path.exists() => r.checked -= 1,
245 Some(problem) => {
246 let removed = remove && remove_path(&l.path);
247 if removed {
248 r.removed += 1;
249 }
250 *r.by_problem.entry(problem.name().to_owned()).or_default() += 1;
251 r.bad.push(BadFile {
252 path: l.path.display().to_string(),
253 problem,
254 removed,
255 });
256 }
257 }
258 }
259 r
260 }
261
262 #[must_use]
267 pub fn gc(&self, max_bytes: u64) -> GcReport {
268 let now = SystemTime::now();
269 let mut entries = Vec::new();
270 let mut r = GcReport {
271 max_bytes,
272 ..GcReport::default()
273 };
274 for l in self.list() {
275 match l.kind {
276 FileKind::Entry(_) => {
277 r.before.entries += 1;
278 r.before.bytes += l.bytes;
279 entries.push(l);
280 }
281 FileKind::Temp => {
282 let stale = now
283 .duration_since(l.used)
284 .is_ok_and(|age| age >= STALE_TEMP);
285 if stale && remove_path(&l.path) {
286 r.temp_removed += 1;
287 }
288 }
289 FileKind::EntryDirectory | FileKind::Stray => {}
290 }
291 }
292 entries.sort_by(|a, b| a.used.cmp(&b.used).then_with(|| a.path.cmp(&b.path)));
294 let mut total = r.before.bytes;
295 for l in entries {
296 if total <= max_bytes {
297 break;
298 }
299 if remove_path(&l.path) {
300 r.evicted.entries += 1;
301 r.evicted.bytes += l.bytes;
302 }
303 total = total.saturating_sub(l.bytes);
304 }
305 r.after = Usage {
306 entries: r.before.entries - r.evicted.entries,
307 bytes: r.before.bytes - r.evicted.bytes,
308 };
309 r
310 }
311
312 pub fn clear(&self) -> std::io::Result<Usage> {
320 let usage = self.usage();
321 let dir = self.entries_dir();
322 if !dir.exists() {
323 return Ok(usage);
324 }
325 let nanos = SystemTime::now()
326 .duration_since(SystemTime::UNIX_EPOCH)
327 .map_or(0, |d| d.as_nanos());
328 let trash = self
329 .root()
330 .join(format!(".clear-{}-{nanos}", std::process::id()));
331 std::fs::rename(&dir, &trash)?;
332 std::fs::remove_dir_all(&trash)?;
333 Ok(usage)
334 }
335}
336
337fn remove_path(path: &Path) -> bool {
338 match std::fs::symlink_metadata(path) {
339 Ok(m) if m.is_dir() => std::fs::remove_dir_all(path).is_ok(),
340 Ok(_) => std::fs::remove_file(path).is_ok(),
341 Err(_) => false,
342 }
343}
344
345#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
347pub struct Usage {
348 pub entries: u64,
350 pub bytes: u64,
352}
353
354#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
356pub struct Spread {
357 pub min: f64,
359 pub median: f64,
361 pub max: f64,
363}
364
365#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
368pub struct UnknownSummary {
369 pub entries: u64,
371 pub with_effort: u64,
373 pub within_half_limit: u64,
375 pub by_reason: BTreeMap<String, u64>,
377 pub used_fraction: Option<Spread>,
379}
380
381#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
383pub struct Summary {
384 pub entries: u64,
386 pub bytes: u64,
388 pub by_command: BTreeMap<String, Usage>,
390 pub unknown: UnknownSummary,
392 pub invalid: u64,
394 pub temp_files: u64,
396}
397
398#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
400pub struct BadFile {
401 pub path: String,
403 pub problem: Problem,
405 pub removed: bool,
407}
408
409#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
411pub struct VerifyReport {
412 pub checked: u64,
414 pub valid: u64,
416 pub bad: Vec<BadFile>,
418 pub by_problem: BTreeMap<String, u64>,
420 pub removed: u64,
422}
423
424#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
426pub struct GcReport {
427 pub max_bytes: u64,
429 pub before: Usage,
431 pub evicted: Usage,
433 pub after: Usage,
435 pub temp_removed: u64,
437}
438
439#[cfg(test)]
440mod tests {
441 use super::*;
442 use std::fs::FileTimes;
443 use std::time::Duration;
444
445 fn scratch(name: &str) -> DiskCache {
446 let d = std::env::temp_dir().join(format!("sail-maint-{}-{name}", std::process::id()));
447 let _ = std::fs::remove_dir_all(&d);
448 DiskCache::new(d)
449 }
450
451 fn put(c: &DiskCache, i: u8, reply: &[u8], command: &str) -> QueryKey {
452 let k = QueryKey([i; 32]);
453 assert!(c.put(&k, reply, command, "", "pinned-solver", None).is_ok());
454 k
455 }
456
457 fn age(c: &DiskCache, k: &QueryKey, secs: u64) {
458 let t = SystemTime::now() - Duration::from_secs(secs);
459 let f = std::fs::File::options().write(true).open(c.entry_path(k));
460 assert!(
461 f.and_then(|f| f.set_times(FileTimes::new().set_accessed(t).set_modified(t)))
462 .is_ok()
463 );
464 }
465
466 #[test]
467 fn gc_evicts_least_recently_used_first() {
468 let c = scratch("gc");
469 let reply = [vec![b'x'; 999], b"\n".to_vec()].concat();
471 let keys: Vec<QueryKey> = (0..6u8).map(|i| put(&c, i, &reply, "get-model")).collect();
472 for (i, k) in keys.iter().enumerate() {
475 age(&c, k, 1000 - 100 * i as u64);
476 }
477 assert!(c.get(&keys[1]).is_some());
478 let size = c.usage().bytes / 6;
479 let r = c.gc(size * 3);
480 assert_eq!(r.evicted.entries, 3);
481 assert!(r.after.bytes <= size * 3);
482 let left: Vec<bool> = keys.iter().map(|k| c.entry_path(k).exists()).collect();
483 assert_eq!(left, [false, true, false, false, true, true]);
484 assert_eq!(c.verify(false).bad.len(), 0);
486 assert_eq!(c.gc(0).after.entries, 0);
487 let _ = std::fs::remove_dir_all(c.root());
488 }
489
490 #[test]
491 fn verify_reports_and_removes_bad_files() {
492 let c = scratch("verify");
493 let good = put(&c, 1, b"unsat\n", "check-sat");
494 let shape = put(&c, 2, b"(error \"x\")\n", "check-sat");
495 let flipped = put(&c, 3, b"sat\n", "check-sat");
496 let p = c.entry_path(&flipped);
497 let mut data = std::fs::read(&p).unwrap_or_default();
498 if let Some(b) = data.last_mut() {
499 *b ^= 1;
500 }
501 assert!(std::fs::write(&p, data).is_ok());
502 let dir = c.entry_path(&good).parent().map(Path::to_path_buf);
503 let dir = dir.unwrap_or_default();
504 assert!(std::fs::write(dir.join("junk"), b"x").is_ok());
505 assert!(std::fs::write(dir.join(".tmp-1-2-x"), b"partial").is_ok());
506 let r = c.verify(false);
507 assert_eq!((r.checked, r.valid, r.bad.len()), (3, 1, 3));
508 assert_eq!(r.by_problem.get("bad-shape"), Some(&1));
509 assert_eq!(r.by_problem.get("hash-mismatch"), Some(&1));
510 assert_eq!(r.by_problem.get("stray"), Some(&1));
511 assert!(c.entry_path(&shape).exists());
512 let r = c.verify(true);
513 assert_eq!(r.removed, 3);
514 assert!(!c.entry_path(&shape).exists());
515 assert!(dir.join(".tmp-1-2-x").exists());
517 let r = c.verify(false);
518 assert_eq!((r.checked, r.valid, r.bad.len()), (1, 1, 0));
519 let _ = std::fs::remove_dir_all(c.root());
520 }
521
522 #[test]
523 fn summarize_counts_commands_and_unknowns() {
524 let c = scratch("summary");
525 put(&c, 1, b"unsat\n", "check-sat");
526 put(&c, 2, b"hi\n", "echo");
527 for (i, used) in [(3u8, 10u64), (4, 90)] {
528 let k = QueryKey([i; 32]);
529 let effort = crate::Effort {
530 limit: Some(100),
531 used: Some(used),
532 reason: Some("(incomplete quantifiers)".to_owned()),
533 };
534 assert!(
535 c.put(&k, b"unknown\n", "check-sat", "", "p", Some(&effort))
536 .is_ok()
537 );
538 }
539 let s = c.summarize();
540 assert_eq!(s.entries, 4);
541 assert_eq!(s.by_command.get("check-sat").map(|u| u.entries), Some(3));
542 assert_eq!(s.unknown.entries, 2);
543 assert_eq!(s.unknown.within_half_limit, 1);
544 assert_eq!(
545 s.unknown.by_reason.get("(incomplete quantifiers)"),
546 Some(&2)
547 );
548 assert!(s.unknown.used_fraction.is_some_and(|f| f.max > 0.8));
549 let cleared = c.clear();
550 assert_eq!(cleared.ok().map(|u| u.entries), Some(4));
551 assert_eq!(c.usage().entries, 0);
552 let _ = std::fs::remove_dir_all(c.root());
553 }
554}