1#![forbid(unsafe_code)]
13
14pub mod maint;
15pub mod memory;
16pub mod pack;
17mod persist;
18pub mod shared;
19
20use std::path::{Path, PathBuf};
21use std::sync::atomic::{AtomicU64, Ordering};
22use std::time::{Duration, SystemTime};
23
24use sail_key::{QueryKey, sha256};
25use serde::{Deserialize, Serialize};
26
27static TMP_SEQ: AtomicU64 = AtomicU64::new(0);
29
30pub const ENTRY_VERSION: u32 = 2;
32
33#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
35pub struct Meta {
36 #[serde(default = "default_mode")]
38 pub mode: String,
39 pub entry_version: u32,
41 pub key: String,
43 pub reply_sha256: String,
45 pub command: String,
47 pub solver: String,
49 pub stored_unix: u64,
51 pub provenance: String,
53 #[serde(default, skip_serializing_if = "Option::is_none")]
56 pub effort: Option<Effort>,
57}
58
59fn default_mode() -> String {
60 "default".to_owned()
61}
62
63pub struct StoreContext<'a> {
65 pub solver: &'a str,
67 pub provenance: &'a str,
69 pub mode: &'a str,
71}
72
73#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
75pub struct Effort {
76 pub limit: Option<u64>,
78 pub used: Option<u64>,
80 pub reason: Option<String>,
82}
83
84pub(crate) fn hex(bytes: &[u8]) -> String {
85 use std::fmt::Write as _;
86 bytes.iter().fold(String::with_capacity(64), |mut s, b| {
87 let _ = write!(s, "{b:02x}");
88 s
89 })
90}
91
92pub const TOUCH_INTERVAL: Duration = Duration::from_secs(60);
96
97#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
106pub struct FileStamp {
107 dev: u64,
108 ino: u64,
109 len: u64,
110 mtime_ns: i128,
111}
112
113impl FileStamp {
114 #[must_use]
116 pub fn of(meta: &std::fs::Metadata) -> Self {
117 #[cfg(unix)]
118 {
119 use std::os::unix::fs::MetadataExt as _;
120 Self {
121 dev: meta.dev(),
122 ino: meta.ino(),
123 len: meta.len(),
124 mtime_ns: i128::from(meta.mtime()) * 1_000_000_000 + i128::from(meta.mtime_nsec()),
125 }
126 }
127 #[cfg(not(unix))]
128 {
129 let mtime_ns = meta
130 .modified()
131 .ok()
132 .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
133 .map_or(0, |d| i128::try_from(d.as_nanos()).unwrap_or(i128::MAX));
134 Self {
135 dev: 0,
136 ino: 0,
137 len: meta.len(),
138 mtime_ns,
139 }
140 }
141 }
142}
143
144#[derive(Debug, Clone, PartialEq, Eq)]
146pub struct Stored {
147 pub meta: Meta,
149 pub reply: Vec<u8>,
151 pub stamp: FileStamp,
153}
154
155#[derive(Debug, Clone, Copy, PartialEq, Eq)]
157pub enum PutOutcome {
158 Written(FileStamp),
160 Exists,
162}
163
164#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
166#[serde(rename_all = "kebab-case")]
167pub enum Problem {
168 Unreadable,
170 BadHeader,
172 WrongVersion,
174 KeyMismatch,
176 HashMismatch,
178 BadShape,
180 Directory,
182 Stray,
185 StaleTemp,
188}
189
190impl Problem {
191 #[must_use]
193 pub fn name(self) -> &'static str {
194 match self {
195 Self::Unreadable => "unreadable",
196 Self::BadHeader => "bad-header",
197 Self::WrongVersion => "wrong-version",
198 Self::KeyMismatch => "key-mismatch",
199 Self::HashMismatch => "hash-mismatch",
200 Self::BadShape => "bad-shape",
201 Self::Directory => "directory",
202 Self::Stray => "stray",
203 Self::StaleTemp => "stale-temp",
204 }
205 }
206}
207
208pub const STALE_TEMP: Duration = Duration::from_secs(3600);
212
213#[must_use]
220pub fn shape_ok(command: &str, reply: &[u8]) -> bool {
221 if !sail_smtlib::split::is_single_response(reply) {
222 return false;
223 }
224 let body = reply.trim_ascii();
225 match command {
226 "check-sat" | "check-sat-assuming" | "check-sat-using" => {
227 matches!(body, b"sat" | b"unsat" | b"unknown")
228 }
229 "echo" => reply.ends_with(b"\n"),
230 "get-info" => body.starts_with(b"(:") && body.ends_with(b")"),
231 _ => !body.is_empty() && !body.starts_with(b"(error"),
232 }
233}
234
235pub fn parse_entry(data: &[u8], key: &str) -> Result<(Meta, Vec<u8>), Problem> {
243 let (header, payload) =
244 sail_acceptance::cache_record::split_record(data).ok_or(Problem::BadHeader)?;
245 let meta: Meta = serde_json::from_slice(header).map_err(|_| Problem::BadHeader)?;
246 let reply = payload.to_vec();
247 let computed = hex(&sha256(&reply));
248 let version = meta.entry_version;
249 let recorded_key = meta.key.as_bytes().to_vec();
250 let recorded_digest = meta.reply_sha256.as_bytes().to_vec();
251 sail_acceptance::query::RecoveryRecord::new(meta, reply, version, recorded_key, recorded_digest)
252 .recover(ENTRY_VERSION, key.as_bytes(), computed.as_bytes())
253 .map_err(|rejection| match rejection {
254 sail_acceptance::query::RecoveryRejection::WrongVersion => Problem::WrongVersion,
255 sail_acceptance::query::RecoveryRejection::KeyMismatch => Problem::KeyMismatch,
256 sail_acceptance::query::RecoveryRejection::HashMismatch => Problem::HashMismatch,
257 })
258}
259
260fn access_stale(meta: &std::fs::Metadata) -> bool {
262 meta.accessed()
263 .ok()
264 .and_then(|a| SystemTime::now().duration_since(a).ok())
265 .is_none_or(|age| age >= TOUCH_INTERVAL)
266}
267
268fn touch_if_stale(file: &std::fs::File, meta: &std::fs::Metadata) {
273 if access_stale(meta) {
274 let _ = file.set_times(std::fs::FileTimes::new().set_accessed(SystemTime::now()));
275 }
276}
277
278#[derive(Debug, Clone)]
280pub struct DiskCache {
281 root: PathBuf,
282}
283
284impl DiskCache {
285 #[must_use]
287 pub fn new(root: impl Into<PathBuf>) -> Self {
288 Self { root: root.into() }
289 }
290
291 #[must_use]
293 pub fn root(&self) -> &Path {
294 &self.root
295 }
296
297 #[must_use]
299 pub fn entries_dir(&self) -> PathBuf {
300 self.root.join("v2")
301 }
302
303 #[must_use]
305 pub fn entry_path(&self, key: &QueryKey) -> PathBuf {
306 let k = key.to_string();
307 self.entries_dir().join(k.get(..2).unwrap_or("xx")).join(k)
308 }
309
310 #[must_use]
312 pub fn get(&self, key: &QueryKey) -> Option<(Meta, Vec<u8>)> {
313 self.get_stamped(key).map(|s| (s.meta, s.reply))
314 }
315
316 #[must_use]
320 pub fn get_stamped(&self, key: &QueryKey) -> Option<Stored> {
321 use std::io::Read as _;
322 let path = self.entry_path(key);
323 let mut file = std::fs::File::open(&path).ok()?;
324 let meta = file.metadata().ok()?;
325 if !meta.is_file() {
326 return None;
328 }
329 let mut data = Vec::with_capacity(usize::try_from(meta.len()).unwrap_or(0));
330 let parsed = file
331 .read_to_end(&mut data)
332 .ok()
333 .and_then(|_| parse_entry(&data, &key.to_string()).ok());
334 let Some((m, reply)) = parsed else {
335 let _ = std::fs::remove_file(&path);
337 return None;
338 };
339 touch_if_stale(&file, &meta);
340 Some(Stored {
341 meta: m,
342 reply,
343 stamp: FileStamp::of(&meta),
344 })
345 }
346
347 #[must_use]
351 pub fn stamp_for_hit(&self, key: &QueryKey) -> Option<FileStamp> {
352 let path = self.entry_path(key);
353 let meta = std::fs::metadata(&path).ok()?;
354 if !meta.is_file() {
355 return None;
356 }
357 if access_stale(&meta)
358 && let Ok(f) = std::fs::File::open(&path)
359 {
360 touch_if_stale(&f, &meta);
361 }
362 Some(FileStamp::of(&meta))
363 }
364
365 #[must_use]
367 pub fn contains(&self, key: &QueryKey) -> bool {
368 self.entry_path(key).is_file()
369 }
370
371 pub fn put(
378 &self,
379 key: &QueryKey,
380 reply: &[u8],
381 command: &str,
382 solver: &str,
383 provenance: &str,
384 effort: Option<&Effort>,
385 ) -> std::io::Result<()> {
386 self.put_stamped(key, reply, command, solver, provenance, effort)
387 .map(|_| ())
388 }
389
390 pub fn put_stamped(
397 &self,
398 key: &QueryKey,
399 reply: &[u8],
400 command: &str,
401 solver: &str,
402 provenance: &str,
403 effort: Option<&Effort>,
404 ) -> std::io::Result<PutOutcome> {
405 self.put_scoped(
406 key,
407 reply,
408 command,
409 &StoreContext {
410 solver,
411 provenance,
412 mode: "default",
413 },
414 effort,
415 )
416 }
417
418 pub fn put_scoped(
424 &self,
425 key: &QueryKey,
426 reply: &[u8],
427 command: &str,
428 context: &StoreContext<'_>,
429 effort: Option<&Effort>,
430 ) -> std::io::Result<PutOutcome> {
431 let path = self.entry_path(key);
432 if path.is_file() {
433 return Ok(PutOutcome::Exists);
434 }
435 let dir = path.parent().unwrap_or(&self.root).to_path_buf();
436 std::fs::create_dir_all(&dir)?;
437 let meta = Meta {
438 mode: context.mode.to_owned(),
439 entry_version: ENTRY_VERSION,
440 key: key.to_string(),
441 reply_sha256: hex(&sha256(reply)),
442 command: command.to_owned(),
443 solver: context.solver.to_owned(),
444 stored_unix: SystemTime::now()
445 .duration_since(std::time::UNIX_EPOCH)
446 .map_or(0, |d| d.as_secs()),
447 provenance: context.provenance.to_owned(),
448 effort: effort.cloned(),
449 };
450 let seq = TMP_SEQ.fetch_add(1, Ordering::Relaxed);
453 let tmp = dir.join(format!(".tmp-{}-{seq}-{key}", std::process::id()));
454 persist::write_record(&tmp, &path, &meta, reply).map(PutOutcome::Written)
458 }
459}
460
461#[cfg(test)]
462mod tests {
463 use super::*;
464
465 fn scratch(name: &str) -> PathBuf {
466 let d = std::env::temp_dir().join(format!("sail-cache-test-{}-{name}", std::process::id()));
467 let _ = std::fs::remove_dir_all(&d);
468 d
469 }
470
471 #[test]
472 fn shape_requires_exactly_one_response_frame() {
473 assert!(super::shape_ok("get-info", b"(:name \"Z3\")\n"));
474 assert!(super::shape_ok("check-sat", b"unsat\n"));
475 assert!(!super::shape_ok(
476 "get-info",
477 b"(:name \"Z3\")(:evil \"extra\")\n"
478 ));
479 assert!(!super::shape_ok("check-sat", b"unsat\nsat\n"));
480 assert!(!super::shape_ok("get-model", b"(model)\n(model)\n"));
481 assert!(!super::shape_ok("echo", b"a\nb\n"));
482 }
483
484 #[test]
485 fn round_trips_exact_bytes() {
486 let c = DiskCache::new(scratch("rt"));
487 let k = QueryKey([1; 32]);
488 assert!(c.get(&k).is_none());
489 let reply = b"(model\n (define-fun x () Int 1)\n)\n\x00\xff";
490 assert!(
491 c.put(&k, reply, "get-model", "z3", "pinned-solver", None)
492 .is_ok()
493 );
494 let (meta, got) = c.get(&k).unwrap_or_default_for_test();
495 assert_eq!(got, reply);
496 assert_eq!(meta.command, "get-model");
497 let _ = std::fs::remove_dir_all(c.root());
498 }
499
500 #[test]
501 fn entries_without_session_silence_evidence_are_rejected() {
502 let c = DiskCache::new(scratch("legacy-stderr"));
503 let k = QueryKey([19; 32]);
504 assert!(
505 c.put(&k, b"unsat\n", "check-sat", "z3", "pinned-solver", None)
506 .is_ok()
507 );
508 let data = std::fs::read(c.entry_path(&k)).unwrap_or_default();
509 let end = data.iter().position(|&b| b == b'\n').unwrap_or(0);
510 let mut header: serde_json::Value =
511 serde_json::from_slice(&data[..end]).unwrap_or_default();
512 header["entry_version"] = 1.into();
513 let mut old = serde_json::to_vec(&header).unwrap_or_default();
514 old.extend_from_slice(&data[end..]);
515 assert!(matches!(
516 parse_entry(&old, &k.to_string()),
517 Err(Problem::WrongVersion)
518 ));
519 let _ = std::fs::remove_dir_all(c.root());
520 }
521
522 #[test]
523 fn corrupt_entries_are_misses_and_removed() {
524 let c = DiskCache::new(scratch("corrupt"));
525 let k = QueryKey([2; 32]);
526 assert!(
527 c.put(&k, b"unsat\n", "check-sat", "z3", "pinned-solver", None)
528 .is_ok()
529 );
530 let path = c.entry_path(&k);
531 let mut data = std::fs::read(&path).unwrap_or_default();
532 if let Some(last) = data.last_mut() {
533 *last ^= 1;
534 }
535 assert!(std::fs::write(&path, &data).is_ok());
536 assert!(c.get(&k).is_none());
537 assert!(!path.exists());
538 let other = QueryKey([3; 32]);
540 assert!(
541 c.put(&k, b"sat\n", "check-sat", "z3", "pinned-solver", None)
542 .is_ok()
543 );
544 assert!(std::fs::create_dir_all(c.entry_path(&other).parent().unwrap_or(c.root())).is_ok());
545 assert!(std::fs::copy(c.entry_path(&k), c.entry_path(&other)).is_ok());
546 assert!(c.get(&other).is_none());
547 let _ = std::fs::remove_dir_all(c.root());
548 }
549
550 #[test]
551 fn concurrent_puts_of_one_key_leave_a_valid_entry() {
552 let c = DiskCache::new(scratch("race"));
556 let k = QueryKey([4; 32]);
557 for round in 0..40 {
558 let _ = std::fs::remove_file(c.entry_path(&k));
559 let barrier = std::sync::Barrier::new(8);
560 std::thread::scope(|s| {
561 for t in 0..8u8 {
562 let (c, barrier) = (&c, &barrier);
563 s.spawn(move || {
564 let reply = vec![b'a' + t; 4096 * (usize::from(t) + 1)];
565 barrier.wait();
566 let _ = c.put(&k, &reply, "get-info", "z3", "pinned-solver", None);
567 });
568 }
569 });
570 let got = c.get(&k).map(|(_, r)| r);
571 assert!(
572 got.as_ref()
573 .is_some_and(|r| r.iter().all(|&b| Some(&b) == r.first())),
574 "round {round}: no valid entry"
575 );
576 }
577 let _ = std::fs::remove_dir_all(c.root());
578 }
579
580 #[cfg(unix)]
581 #[test]
582 fn put_refuses_a_preexisting_temporary_name() {
583 let c = DiskCache::new(scratch("tmp-symlink"));
586 let k = QueryKey([5; 32]);
587 let dir = c.entry_path(&k).parent().map(Path::to_path_buf);
588 let dir = dir.unwrap_or_else(|| c.root().to_path_buf());
589 assert!(std::fs::create_dir_all(&dir).is_ok());
590 let target = c.root().join("owned-by-someone-else");
591 assert!(std::fs::write(&target, b"sentinel").is_ok());
592 let seq = TMP_SEQ.load(Ordering::Relaxed);
593 let links: Vec<PathBuf> = (seq..seq + 64)
596 .map(|n| dir.join(format!(".tmp-{}-{n}-{k}", std::process::id())))
597 .collect();
598 for l in &links {
599 assert!(std::os::unix::fs::symlink(&target, l).is_ok());
600 }
601 let mut refused = false;
602 for _ in 0..64 {
603 match c.put(&k, b"unsat\n", "check-sat", "z3", "pinned-solver", None) {
604 Err(e) => {
605 assert_eq!(e.kind(), std::io::ErrorKind::AlreadyExists);
606 refused = true;
607 }
608 Ok(()) => break,
609 }
610 }
611 assert!(refused, "a preexisting temporary name must be refused");
612 assert_eq!(
613 std::fs::read(&target).ok().as_deref(),
614 Some(&b"sentinel"[..])
615 );
616 let entry = c.entry_path(&k);
617 assert!(
618 std::fs::symlink_metadata(&entry).map_or(true, |m| !m.file_type().is_symlink()),
619 "the entry must never be a renamed symlink"
620 );
621 assert!(
622 links
623 .iter()
624 .all(|l| std::fs::symlink_metadata(l).is_ok_and(|m| m.file_type().is_symlink())),
625 "a name this writer did not create must not be removed"
626 );
627 let _ = std::fs::remove_dir_all(c.root());
628 }
629
630 trait OrDefault {
631 fn unwrap_or_default_for_test(self) -> (Meta, Vec<u8>);
632 }
633
634 impl OrDefault for Option<(Meta, Vec<u8>)> {
635 fn unwrap_or_default_for_test(self) -> (Meta, Vec<u8>) {
636 match self {
637 Some(x) => x,
638 None => unreachable!("expected a cache hit"),
639 }
640 }
641 }
642}