use std::ffi::CString;
use std::fs;
use std::io;
use std::os::unix::ffi::OsStrExt;
use std::os::unix::fs::{MetadataExt, PermissionsExt};
use std::path::{Path, PathBuf};
use second_brain_core::embedding;
use second_brain_core::model_cache::{self, CachedModel};
use second_brain_core::private_files::{PRIVATE_DIR_MODE, PRIVATE_FILE_MODE, visit_private_paths};
use super::fixes;
use super::report::{Check, Context};
const GIB: u64 = 1024 * 1024 * 1024;
const DISK_FAIL_BELOW: u64 = GIB;
const DISK_WARN_BELOW: u64 = 5 * GIB;
pub(crate) fn checks(ctx: &Context, free_bytes: &dyn Fn(&Path) -> io::Result<u64>) -> Vec<Check> {
vec![data_dir(ctx), models(ctx), disk(ctx, free_bytes)]
}
#[allow(
clippy::useless_conversion,
reason = "statvfs field widths differ by platform"
)]
pub(crate) fn free_bytes(path: &Path) -> io::Result<u64> {
let c_path = c_path(path)?;
let mut stat: libc::statvfs = unsafe { std::mem::zeroed() };
if unsafe { libc::statvfs(c_path.as_ptr(), &mut stat) } != 0 {
return Err(io::Error::last_os_error());
}
Ok(u64::from(stat.f_bavail).saturating_mul(u64::from(stat.f_frsize)))
}
fn data_dir(ctx: &Context) -> Check {
let dir = &ctx.data_dir;
let Ok(meta) = fs::metadata(dir) else {
return Check::fail(
"data-dir",
format!(
"{} does not exist, so the daemon has nowhere to store memories",
dir.display()
),
"sb setup",
);
};
let me = fixes::current_uid();
if meta.uid() != me {
return Check::fail(
"data-dir",
format!(
"{} is owned by uid {}, not by you (uid {me}), so the daemon running as you cannot write memories",
dir.display(),
meta.uid()
),
chown_to_me(dir),
);
}
let private = private_paths(dir, me);
if let Some(check) = exposed_private_paths(&private, me) {
return check;
}
if !private.unreadable.is_empty() {
return Check::warn(
"data-dir",
format!(
"could not check who can read {}",
private
.unreadable
.iter()
.map(|(path, e)| format!("{}: {e}", path.display()))
.collect::<Vec<_>>()
.join(", ")
),
"sb restart, which makes the data dir and the index tree readable only by you",
);
}
Check::ok("data-dir", dir.display().to_string())
}
fn exposed_private_paths(private: &PrivatePaths, me: u32) -> Option<Check> {
if private.foreign.is_empty() && private.loose.is_empty() {
return None;
}
let mut problems: Vec<String> = private
.foreign
.iter()
.map(|f| {
format!(
"{} is owned by uid {}, not by you (uid {me})",
f.path.display(),
f.uid
)
})
.collect();
problems.extend(
private
.loose
.iter()
.map(|l| format!("{} is mode {:o}", l.path.display(), l.mode)),
);
let mut effects = Vec::new();
let mut fix: Vec<String> = private.foreign.iter().map(Foreign::fix).collect();
if !private.foreign.is_empty() {
effects.push("the daemon running as you cannot open or tighten what another user owns");
}
if !private.loose.is_empty() {
effects.push("other users on this machine can read your memories and the API token");
fix.push(format!(
"{} (the daemon also tightens these on sb restart)",
chmod_commands(&private.loose)
));
}
Some(Check::fail(
"data-dir",
format!("{}; {}", problems.join(", "), effects.join(", and ")),
fix.join(" && "),
))
}
struct LooseMode {
path: PathBuf,
mode: u32,
want: u32,
}
struct Foreign {
path: PathBuf,
uid: u32,
is_dir: bool,
}
impl Foreign {
fn fix(&self) -> String {
if self.is_dir {
chown_to_me(&self.path)
} else {
fixes::reclaim_private_file(&self.path)
}
}
}
struct PrivatePaths {
foreign: Vec<Foreign>,
loose: Vec<LooseMode>,
unreadable: Vec<(PathBuf, io::Error)>,
}
fn private_paths(dir: &Path, me: u32) -> PrivatePaths {
let db = dir.join("brain.db");
let index = db.with_extension("indexes");
let mut foreign: Vec<Foreign> = Vec::new();
let mut loose = Vec::new();
let mut unreadable = Vec::new();
let errors = visit_private_paths(dir, &db, &index, |path, want| {
let meta = match fs::metadata(path) {
Ok(meta) => meta,
Err(e) => return unreadable.push((path.to_path_buf(), e)),
};
if foreign
.iter()
.any(|f| f.is_dir && path.starts_with(&f.path))
{
return;
}
let is_dir = meta.is_dir();
if meta.uid() != me {
foreign.push(Foreign {
path: path.to_path_buf(),
uid: meta.uid(),
is_dir,
});
if !is_dir {
return;
}
}
let mode = meta.permissions().mode();
if mode & 0o077 != 0 {
loose.push(LooseMode {
path: path.to_path_buf(),
mode: mode & 0o777,
want,
});
}
});
unreadable.extend(errors);
PrivatePaths {
foreign,
loose,
unreadable,
}
}
fn chmod_commands(loose: &[LooseMode]) -> String {
[PRIVATE_DIR_MODE, PRIVATE_FILE_MODE]
.into_iter()
.filter_map(|want| {
let paths: Vec<String> = loose
.iter()
.filter(|l| l.want == want)
.map(|l| fixes::quoted(&l.path))
.collect();
(!paths.is_empty()).then(|| format!("chmod {want:o} {}", paths.join(" ")))
})
.collect::<Vec<_>>()
.join(" && ")
}
fn models(ctx: &Context) -> Check {
let cache = &ctx.model_cache;
let required = match [
embedding::cached_model(),
model_cache::default_reranker_model(),
]
.into_iter()
.collect::<anyhow::Result<Vec<CachedModel>>>()
{
Ok(models) => models,
Err(e) => {
return Check::fail(
"models",
format!("this build of sb cannot name the models the daemon loads: {e:#}"),
"reinstall second-brain from a release build",
);
}
};
let missing = required
.iter()
.filter(|model| model.loadable_snapshot(cache).is_none())
.map(|model| model.code.as_str())
.collect::<Vec<_>>()
.join(" and ");
if cache.exists() {
let read_only = !writable(cache);
if missing.is_empty() {
if read_only {
return Check::ok(
"models",
format!(
"{} (read-only to you; it already holds every model the daemon loads)",
cache.display()
),
);
}
return Check::ok("models", cache.display().to_string());
}
if read_only {
return Check::fail(
"models",
format!(
"{missing} not fully downloaded to {}, and it is not writable by you, so the daemon cannot download them",
cache.display()
),
unwritable_cache_fix(cache),
);
}
} else if let Some(ancestor) = cache
.ancestors()
.skip(1)
.find(|dir| dir.exists())
.filter(|dir| !writable(dir))
{
return Check::fail(
"models",
format!(
"{missing} not downloaded: {} does not exist and {} is not writable by you, so the daemon cannot create the cache or download them",
cache.display(),
ancestor.display()
),
unwritable_cache_fix(ancestor),
);
}
Check::warn(
"models",
format!(
"{missing} not fully downloaded to {} yet; the daemon downloads models on start, which needs network access to Hugging Face",
cache.display()
),
"sb restart once this machine can reach huggingface.co",
)
}
fn unwritable_cache_fix(dir: &Path) -> String {
match fs::metadata(dir) {
Ok(meta) if meta.uid() != fixes::current_uid() => chown_to_me(dir),
_ => format!("chmod u+rwx {}", fixes::quoted(dir)),
}
}
fn writable(dir: &Path) -> bool {
c_path(dir).is_ok_and(|p| unsafe { libc::access(p.as_ptr(), libc::W_OK | libc::X_OK) } == 0)
}
fn disk(ctx: &Context, free_bytes: &dyn Fn(&Path) -> io::Result<u64>) -> Check {
let dir = if ctx.data_dir.exists() {
&ctx.data_dir
} else {
&ctx.home
};
let free = match free_bytes(dir) {
Ok(free) => free,
Err(e) => {
return Check::warn(
"disk",
format!("could not measure free space on {}: {e}", dir.display()),
format!("df -h {}", fixes::quoted(dir)),
);
}
};
let gib = free as f64 / GIB as f64;
if free >= DISK_WARN_BELOW {
return Check::ok(
"disk",
format!("{gib:.1} GiB free on the disk holding {}", dir.display()),
);
}
let reason = format!(
"only {gib:.1} GiB free on the disk holding {}; writes and index merges fail when the disk fills",
dir.display()
);
let fix = format!("free space on the filesystem holding {}", dir.display());
if free < DISK_FAIL_BELOW {
Check::fail("disk", reason, fix)
} else {
Check::warn("disk", reason, fix)
}
}
fn c_path(path: &Path) -> io::Result<CString> {
CString::new(path.as_os_str().as_bytes())
.map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))
}
fn chown_to_me(path: &Path) -> String {
fixes::chown_to_me(path, true)
}
#[cfg(test)]
mod tests {
use std::cell::RefCell;
use std::fs;
use std::os::unix::fs::PermissionsExt;
use std::path::PathBuf;
use second_brain_core::embedding;
use second_brain_core::model_cache::{self, CachedModel, snapshots_dir};
use super::*;
use crate::commands::doctor::report::Status;
use crate::daemon::Os;
const GIB: u64 = 1024 * 1024 * 1024;
struct Home {
_tmp: tempfile::TempDir,
ctx: Context,
}
impl Home {
fn data(&self, name: &str) -> PathBuf {
self.ctx.data_dir.join(name)
}
fn cache(&self) -> PathBuf {
self.ctx.model_cache.clone()
}
fn indexes(&self) -> PathBuf {
self.data("brain.indexes")
}
fn snapshot(&self, model: &CachedModel) -> PathBuf {
snapshots_dir(&self.cache(), &model.code).join("rev1")
}
fn repo(&self, model: &CachedModel) -> PathBuf {
snapshots_dir(&self.cache(), &model.code)
.parent()
.unwrap()
.to_path_buf()
}
fn main_ref(&self, model: &CachedModel) -> PathBuf {
self.repo(model).join("refs").join("main")
}
}
fn embed_model() -> CachedModel {
embedding::cached_model().unwrap()
}
fn rerank_model() -> CachedModel {
model_cache::default_reranker_model().unwrap()
}
fn chmod(path: &Path, mode: u32) {
fs::set_permissions(path, fs::Permissions::from_mode(mode)).unwrap();
}
fn seed_model(h: &Home, model: &CachedModel) {
let snapshot = h.snapshot(model);
for file in &model.files {
let path = snapshot.join(file);
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(path, b"x").unwrap();
}
let main_ref = h.main_ref(model);
fs::create_dir_all(main_ref.parent().unwrap()).unwrap();
fs::write(main_ref, "rev1").unwrap();
}
fn bare_home() -> Home {
let tmp = tempfile::tempdir().unwrap();
let home = tmp.path().to_path_buf();
let ctx = Context {
os: Os::Linux,
data_dir: home.join(".second-brain"),
sb_bin: home.join("bin").join("sb"),
mcp_bin: Ok(home.join(".cargo/bin/second-brain-mcp")),
claude_config_dir: None,
search_path: None,
model_cache: home.join("models"),
home,
};
Home { _tmp: tmp, ctx }
}
fn healthy_home() -> Home {
let h = bare_home();
fs::create_dir_all(&h.ctx.data_dir).unwrap();
chmod(&h.ctx.data_dir, 0o700);
for name in [
"api.token",
"sync.key",
"brain.db",
"brain.db-wal",
"brain.db-shm",
] {
let path = h.data(name);
fs::write(&path, b"x").unwrap();
chmod(&path, 0o600);
}
let tantivy = h.indexes().join("tantivy");
fs::create_dir_all(&tantivy).unwrap();
chmod(&h.indexes(), 0o700);
chmod(&tantivy, 0o700);
for path in [
h.indexes().join("vectors.usearch"),
tantivy.join("meta.json"),
] {
fs::write(&path, b"x").unwrap();
chmod(&path, 0o600);
}
fs::create_dir_all(h.cache()).unwrap();
seed_model(&h, &embed_model());
seed_model(&h, &rerank_model());
h
}
fn plenty(_: &Path) -> std::io::Result<u64> {
Ok(100 * GIB)
}
fn find(checks: &[Check], name: &str) -> Check {
checks
.iter()
.find(|c| c.name == name)
.unwrap_or_else(|| panic!("no {name} check in {checks:?}"))
.clone()
}
fn run(h: &Home, name: &str) -> Check {
find(&checks(&h.ctx, &plenty), name)
}
fn run_disk(h: &Home, free: u64) -> Check {
let measure = |_: &Path| -> std::io::Result<u64> { Ok(free) };
find(&checks(&h.ctx, &measure), "disk")
}
fn fix(check: &Check) -> String {
check.fix.clone().unwrap_or_default()
}
fn running_as_root() -> bool {
unsafe { libc::getuid() == 0 }
}
#[test]
fn host_checks_are_data_dir_then_models_then_disk() {
let h = healthy_home();
let names: Vec<&str> = checks(&h.ctx, &plenty).iter().map(|c| c.name).collect();
assert_eq!(names, ["data-dir", "models", "disk"]);
}
#[test]
fn data_dir_ok_names_the_path() {
let h = healthy_home();
let check = run(&h, "data-dir");
assert_eq!(check.status, Status::Ok, "{check:?}");
assert!(check.detail.contains(&h.ctx.data_dir.display().to_string()));
assert_eq!(check.fix, None);
}
#[test]
fn missing_data_dir_fails_with_sb_setup() {
let h = bare_home();
let check = run(&h, "data-dir");
assert_eq!(check.status, Status::Fail, "{check:?}");
assert!(check.detail.contains(&h.ctx.data_dir.display().to_string()));
assert!(fix(&check).contains("sb setup"), "{check:?}");
}
#[test]
fn group_readable_data_dir_fails_with_chmod_700() {
let h = healthy_home();
chmod(&h.ctx.data_dir, 0o755);
let check = run(&h, "data-dir");
let dir = h.ctx.data_dir.display().to_string();
assert_eq!(check.status, Status::Fail, "{check:?}");
assert!(check.detail.contains(&dir), "{check:?}");
assert!(check.detail.contains("755"), "{check:?}");
assert!(
fix(&check).contains(&format!("chmod 700 {dir}")),
"{check:?}"
);
}
#[test]
fn group_or_other_readable_secrets_fail_listing_each_with_its_mode() {
let h = healthy_home();
let token = h.data("api.token");
let wal = h.data("brain.db-wal");
chmod(&token, 0o640);
chmod(&wal, 0o604);
let check = run(&h, "data-dir");
assert_eq!(check.status, Status::Fail, "{check:?}");
let token = token.display().to_string();
let wal = wal.display().to_string();
assert!(check.detail.contains(&token), "{check:?}");
assert!(check.detail.contains("640"), "{check:?}");
assert!(check.detail.contains(&wal), "{check:?}");
assert!(check.detail.contains("604"), "{check:?}");
assert!(
!check
.detail
.contains(&h.data("sync.key").display().to_string()),
"a 0600 file is not a problem: {check:?}"
);
let fix = fix(&check);
assert!(fix.contains("chmod 600"), "{check:?}");
assert!(fix.contains(&token), "{check:?}");
assert!(fix.contains(&wal), "{check:?}");
assert!(!fix.contains("chmod 700"), "{check:?}");
assert!(
format!("{} {fix}", check.detail).contains("restart"),
"{check:?}"
);
}
#[test]
fn world_readable_file_under_brain_indexes_fails_with_chmod_600() {
let h = healthy_home();
let meta = h.indexes().join("tantivy").join("meta.json");
chmod(&meta, 0o644);
let check = run(&h, "data-dir");
assert_eq!(check.status, Status::Fail, "{check:?}");
let meta = meta.display().to_string();
assert!(check.detail.contains(&meta), "{check:?}");
assert!(check.detail.contains("644"), "{check:?}");
let fix = fix(&check);
assert!(fix.contains(&format!("chmod 600 {meta}")), "{check:?}");
assert!(!fix.contains("chmod 700"), "{check:?}");
}
#[test]
fn group_readable_index_dir_fails_with_chmod_700() {
let h = healthy_home();
let tantivy = h.indexes().join("tantivy");
chmod(&tantivy, 0o750);
let check = run(&h, "data-dir");
assert_eq!(check.status, Status::Fail, "{check:?}");
let tantivy = tantivy.display().to_string();
assert!(check.detail.contains(&tantivy), "{check:?}");
assert!(check.detail.contains("750"), "{check:?}");
assert!(
fix(&check).contains(&format!("chmod 700 {tantivy}")),
"{check:?}"
);
}
#[test]
fn unreadable_index_dir_warns_naming_it_and_restart() {
if running_as_root() {
return;
}
let h = healthy_home();
let tantivy = h.indexes().join("tantivy");
chmod(&tantivy, 0o300);
let check = run(&h, "data-dir");
chmod(&tantivy, 0o700);
assert_eq!(check.status, Status::Warn, "{check:?}");
assert!(
check.detail.contains(&tantivy.display().to_string()),
"{check:?}"
);
assert!(fix(&check).contains("sb restart"), "{check:?}");
}
#[test]
fn absent_optional_files_are_not_reported() {
let h = healthy_home();
fs::remove_file(h.data("brain.db-wal")).unwrap();
fs::remove_file(h.data("brain.db-shm")).unwrap();
fs::remove_file(h.data("sync.key")).unwrap();
fs::remove_dir_all(h.indexes()).unwrap();
let check = run(&h, "data-dir");
assert_eq!(check.status, Status::Ok, "{check:?}");
}
#[test]
fn data_dir_owned_by_another_user_fails_with_chown() {
if running_as_root() {
return;
}
let mut h = bare_home();
h.ctx.data_dir = PathBuf::from("/");
let check = run(&h, "data-dir");
assert_eq!(check.status, Status::Fail, "{check:?}");
assert!(check.detail.contains("uid 0"), "{check:?}");
assert!(fix(&check).contains("chown"), "{check:?}");
}
fn root_owned_file(candidates: &[&str], loose: bool) -> Option<PathBuf> {
candidates.iter().map(PathBuf::from).find(|path| {
fs::metadata(path)
.is_ok_and(|m| m.uid() == 0 && m.is_file() && (m.mode() & 0o077 != 0) == loose)
})
}
fn replace_with_link(path: &Path, target: &Path) {
fs::remove_file(path).unwrap();
std::os::unix::fs::symlink(target, path).unwrap();
}
fn without_chown_of(fix: &str, path: &Path) -> String {
fix.replace(&fixes::reclaim_private_file(path), "")
.replace(&fixes::chown_to_me(path, true), "")
.replace(&fixes::chown_to_me(path, false), "")
}
#[test]
fn loose_private_file_owned_by_another_user_fails_with_chown_not_chmod() {
if running_as_root() {
return;
}
let Some(foreign) = root_owned_file(&["/etc/passwd", "/etc/hostname", "/etc/group"], true)
else {
return;
};
let h = healthy_home();
let wal = h.data("brain.db-wal");
replace_with_link(&wal, &foreign);
let check = run(&h, "data-dir");
assert_eq!(check.status, Status::Fail, "{check:?}");
assert!(
check.detail.contains(&wal.display().to_string()),
"{check:?}"
);
let fix = fix(&check);
assert!(fix.contains("sudo chown"), "{check:?}");
let rest = without_chown_of(&fix, &wal);
assert_ne!(rest, fix, "the fix must chown {}: {check:?}", wal.display());
assert!(
!rest.contains(&fixes::quoted(&wal)),
"a chmod alone cannot fix a file you do not own: {check:?}"
);
}
#[test]
fn private_file_owned_by_another_user_fails_even_at_mode_600() {
if running_as_root() {
return;
}
let Some(foreign) = root_owned_file(
&[
"/etc/ssh/ssh_host_ed25519_key",
"/etc/ssh/ssh_host_ecdsa_key",
"/etc/ssh/ssh_host_rsa_key",
],
false,
) else {
return;
};
let h = healthy_home();
let db = h.data("brain.db");
replace_with_link(&db, &foreign);
let check = run(&h, "data-dir");
assert_eq!(check.status, Status::Fail, "{check:?}");
assert!(
check.detail.contains(&db.display().to_string()),
"{check:?}"
);
let fix = fix(&check);
assert!(fix.contains("sudo chown"), "{check:?}");
assert!(
!without_chown_of(&fix, &db).contains(&fixes::quoted(&db)),
"{check:?}"
);
}
#[test]
fn chown_of_a_foreign_file_comes_before_chmod_of_your_own() {
if running_as_root() {
return;
}
let Some(foreign) = root_owned_file(&["/etc/passwd", "/etc/hostname", "/etc/group"], true)
else {
return;
};
let h = healthy_home();
let wal = h.data("brain.db-wal");
replace_with_link(&wal, &foreign);
let token = h.data("api.token");
chmod(&token, 0o640);
let check = run(&h, "data-dir");
assert_eq!(check.status, Status::Fail, "{check:?}");
let token_q = fixes::quoted(&token);
assert!(
check.detail.contains(&token.display().to_string()),
"{check:?}"
);
assert!(
check.detail.contains(&wal.display().to_string()),
"{check:?}"
);
let fix = fix(&check);
let chown_at = fix
.find("sudo chown")
.expect("a chown for the foreign file");
let chmod_at = fix
.find(&format!("chmod 600 {token_q}"))
.expect("the mode-only fix for the file you own stays");
assert!(chown_at < chmod_at, "{check:?}");
assert!(
!fix.contains(&fixes::chown_to_me(&token, false)),
"a file you own needs no chown: {check:?}"
);
}
#[test]
fn models_ok_names_the_cache_path() {
let h = healthy_home();
let check = run(&h, "models");
assert_eq!(check.status, Status::Ok, "{check:?}");
assert!(check.detail.contains(&h.cache().display().to_string()));
assert_eq!(check.fix, None);
}
#[test]
fn missing_embedding_model_warns_to_restart_once_online() {
let h = healthy_home();
let embed = embed_model();
fs::remove_dir_all(h.repo(&embed)).unwrap();
let check = run(&h, "models");
assert_eq!(check.status, Status::Warn, "{check:?}");
assert!(check.detail.contains(&embed.code), "{check:?}");
let fix = fix(&check);
assert!(fix.contains("sb restart"), "{check:?}");
assert!(fix.contains("huggingface.co"), "{check:?}");
}
#[test]
fn missing_reranker_model_warns_to_restart_once_online() {
let h = healthy_home();
let rerank = rerank_model();
fs::remove_dir_all(h.repo(&rerank)).unwrap();
let check = run(&h, "models");
assert_eq!(check.status, Status::Warn, "{check:?}");
assert!(check.detail.contains(&rerank.code), "{check:?}");
let fix = fix(&check);
assert!(fix.contains("sb restart"), "{check:?}");
assert!(fix.contains("huggingface.co"), "{check:?}");
}
#[test]
fn embedding_snapshot_without_tokenizer_json_warns() {
let h = healthy_home();
let embed = embed_model();
fs::remove_file(h.snapshot(&embed).join("tokenizer.json")).unwrap();
let check = run(&h, "models");
assert_eq!(check.status, Status::Warn, "{check:?}");
assert!(check.detail.contains(&embed.code), "{check:?}");
assert!(!check.detail.contains(&rerank_model().code), "{check:?}");
assert!(fix(&check).contains("sb restart"), "{check:?}");
}
#[test]
fn reranker_snapshot_without_its_onnx_file_warns() {
let h = healthy_home();
let rerank = rerank_model();
let onnx = rerank
.files
.iter()
.find(|f| f.ends_with(".onnx"))
.expect("the reranker loads an onnx file");
fs::remove_file(h.snapshot(&rerank).join(onnx)).unwrap();
let check = run(&h, "models");
assert_eq!(check.status, Status::Warn, "{check:?}");
assert!(check.detail.contains(&rerank.code), "{check:?}");
assert!(fix(&check).contains("sb restart"), "{check:?}");
}
#[test]
fn complete_embedder_snapshot_without_refs_main_warns() {
let h = healthy_home();
let embed = embed_model();
fs::remove_file(h.main_ref(&embed)).unwrap();
let check = run(&h, "models");
assert_eq!(check.status, Status::Warn, "{check:?}");
assert!(check.detail.contains(&embed.code), "{check:?}");
assert!(!check.detail.contains(&rerank_model().code), "{check:?}");
assert!(fix(&check).contains("sb restart"), "{check:?}");
}
#[test]
fn complete_reranker_snapshot_without_refs_main_is_ok() {
let h = healthy_home();
fs::remove_file(h.main_ref(&rerank_model())).unwrap();
let check = run(&h, "models");
assert_eq!(check.status, Status::Ok, "{check:?}");
}
#[test]
fn absent_cache_dir_warns_that_models_are_not_downloaded() {
let h = healthy_home();
fs::remove_dir_all(h.cache()).unwrap();
let check = run(&h, "models");
assert_eq!(check.status, Status::Warn, "{check:?}");
assert!(check.detail.contains(&embed_model().code), "{check:?}");
assert!(fix(&check).contains("sb restart"), "{check:?}");
}
#[test]
fn unwritable_cache_dir_missing_a_model_fails_with_chmod() {
if running_as_root() {
return;
}
let h = healthy_home();
let embed = embed_model();
fs::remove_dir_all(h.repo(&embed)).unwrap();
let cache = h.cache();
chmod(&cache, 0o555);
let check = run(&h, "models");
chmod(&cache, 0o755);
assert_eq!(check.status, Status::Fail, "{check:?}");
let path = cache.display().to_string();
assert!(check.detail.contains(&path), "{check:?}");
assert!(check.detail.contains("writable"), "{check:?}");
assert!(check.detail.contains(&embed.code), "{check:?}");
let fix = fix(&check);
assert!(fix.contains("chmod"), "{check:?}");
assert!(fix.contains(&path), "{check:?}");
}
#[test]
fn missing_cache_dir_under_an_unwritable_ancestor_fails_naming_that_ancestor() {
if running_as_root() {
return;
}
let mut h = healthy_home();
let user_cache = h.ctx.home.join(".cache");
fs::create_dir_all(&user_cache).unwrap();
h.ctx.model_cache = model_cache::model_cache_dir_in(&user_cache);
chmod(&user_cache, 0o555);
let check = run(&h, "models");
chmod(&user_cache, 0o755);
assert!(!h.cache().exists(), "{check:?}");
assert_eq!(check.status, Status::Fail, "{check:?}");
let ancestor = user_cache.display().to_string();
assert!(check.detail.contains(&ancestor), "{check:?}");
assert!(check.detail.contains("writable"), "{check:?}");
let fix = fix(&check);
assert!(fix.contains("chmod"), "{check:?}");
assert!(fix.contains(&ancestor), "{check:?}");
assert!(!fix.contains(&h.cache().display().to_string()), "{check:?}");
assert!(!fix.contains("huggingface.co"), "{check:?}");
}
#[test]
fn read_only_cache_holding_every_model_is_ok_and_says_read_only() {
if running_as_root() {
return;
}
let h = healthy_home();
let cache = h.cache();
chmod(&cache, 0o555);
let check = run(&h, "models");
chmod(&cache, 0o755);
assert_eq!(check.status, Status::Ok, "{check:?}");
assert!(
check.detail.contains(&cache.display().to_string()),
"{check:?}"
);
assert!(check.detail.contains("read-only"), "{check:?}");
assert_eq!(check.fix, None, "{check:?}");
}
#[test]
fn disk_ok_reports_free_gib() {
let h = healthy_home();
let check = run_disk(&h, 20 * GIB);
assert_eq!(check.status, Status::Ok, "{check:?}");
assert!(check.detail.contains("20"), "{check:?}");
assert!(check.detail.contains("GiB"), "{check:?}");
assert_eq!(check.fix, None);
}
#[test]
fn disk_under_five_gib_warns() {
let h = healthy_home();
let check = run_disk(&h, 3 * GIB);
assert_eq!(check.status, Status::Warn, "{check:?}");
let fix = fix(&check);
assert!(fix.contains("free space"), "{check:?}");
assert!(
fix.contains(&h.ctx.data_dir.display().to_string()),
"{check:?}"
);
}
#[test]
fn disk_under_one_gib_fails() {
let h = healthy_home();
let check = run_disk(&h, GIB / 2);
assert_eq!(check.status, Status::Fail, "{check:?}");
assert!(check.detail.contains("disk"), "{check:?}");
let fix = fix(&check);
assert!(fix.contains("free space"), "{check:?}");
assert!(
fix.contains(&h.ctx.data_dir.display().to_string()),
"{check:?}"
);
}
#[test]
fn disk_thresholds_are_strictly_under() {
let h = healthy_home();
assert_eq!(run_disk(&h, GIB).status, Status::Warn);
assert_eq!(run_disk(&h, 5 * GIB).status, Status::Ok);
}
#[test]
fn disk_measure_error_warns_with_the_error() {
let h = healthy_home();
let failing =
|_: &Path| -> std::io::Result<u64> { Err(std::io::Error::other("statvfs exploded")) };
let check = find(&checks(&h.ctx, &failing), "disk");
assert_eq!(check.status, Status::Warn, "{check:?}");
assert!(check.detail.contains("statvfs exploded"), "{check:?}");
assert!(check.fix.is_some(), "{check:?}");
}
#[test]
fn disk_measures_the_data_dir_when_it_exists_and_home_otherwise() {
let seen = RefCell::new(Vec::new());
let record = |p: &Path| -> std::io::Result<u64> {
seen.borrow_mut().push(p.to_path_buf());
Ok(100 * GIB)
};
let h = healthy_home();
checks(&h.ctx, &record);
assert_eq!(
seen.borrow().as_slice(),
std::slice::from_ref(&h.ctx.data_dir)
);
seen.borrow_mut().clear();
let bare = bare_home();
let check = find(&checks(&bare.ctx, &record), "disk");
assert_eq!(
seen.borrow().as_slice(),
std::slice::from_ref(&bare.ctx.home)
);
assert_eq!(check.status, Status::Ok, "{check:?}");
}
#[test]
fn free_bytes_measures_a_real_directory() {
let tmp = tempfile::tempdir().unwrap();
let free = free_bytes(tmp.path()).unwrap();
assert!(free > 0);
}
#[test]
fn free_bytes_errors_on_a_missing_path() {
let tmp = tempfile::tempdir().unwrap();
assert!(free_bytes(&tmp.path().join("absent")).is_err());
}
}