//! Persistent SQLite WAL directory cache and visualization projections. use crate::domain::{ AGE_BUCKET_COUNT, AccessStatus, AgeBucket, AgeHistogram, CATEGORY_COUNT, CategoryHistogram, DirectoryRecord, FileCategory, FileEntry, RelPath, SizeMetric, apply_signed_u64, }; use crate::scanner::{DirectDirScan, FullScanResult, current_time_ns}; use rusqlite::{Connection, OpenFlags, OptionalExtension, params}; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::path::Path; use std::sync::Mutex; use thiserror::Error; const SCHEMA_VERSION: &str = "3"; /// Errors returned by [`CacheStore`]. #[derive(Debug, Error)] pub enum CacheError { /// Failed to create cache directory. #[error("failed to create cache directory {path}: {source}")] CreateDir { path: String, #[source] source: std::io::Error, }, /// SQLite error. #[error("sqlite error: {0}")] Sqlite(#[from] rusqlite::Error), /// JSON serialization/deserialization error. #[error("json error: {0}")] Json(#[from] serde_json::Error), /// Invalid relative path. #[error(transparent)] Domain(#[from] crate::domain::DomainError), } /// Metadata persisted in the `meta` table. #[derive(Debug, Clone, Default, Serialize, Deserialize)] pub struct CacheMeta { pub schema_version: String, pub home_root: String, pub root_dev: u64, pub last_full_scan_started_ns: i64, pub last_full_scan_completed_ns: i64, } /// Summary of an incremental directory update. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct DirDeltaSummary { pub path: String, pub delta_physical_bytes: i64, pub delta_logical_bytes: i64, } /// Sort order for `/api/directory`. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum DirectorySort { #[default] Size, Name, Mtime, Count, } /// Coloring mode for `/api/analytics/hilbert`. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum HilbertColorBy { #[default] Category, Age, Depth, } /// Hierarchical tree node for spatial lenses (Voronoi, Treemap, Sunburst, Icicle, Circle Pack). #[derive(Debug, Clone, Serialize, Deserialize)] pub struct TreeNode { pub path: String, pub name: String, pub bytes: u64, pub physical_bytes: u64, pub logical_bytes: u64, pub file_count: u64, pub dir_count: u64, pub depth: u32, pub is_hidden: bool, pub is_synthetic: bool, pub access_status: AccessStatus, pub dominant_category: FileCategory, pub mtime_ns: i64, pub children: Vec, } /// Bloat-radar hint for heavy regenerable or model directories. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct BloatHint { pub path: String, pub name: String, pub kind: String, pub physical_bytes: u64, pub logical_bytes: u64, } /// Full directory inspection payload for `/api/directory`. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct DirectoryView { pub directory: DirectoryRecord, pub child_dirs: Vec, pub top_files: Vec, pub bloat_hints: Vec, } /// A point in the *Fossils & Dust* scatter plot. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ScatterPoint { pub path: String, pub dir_path: String, pub name: String, pub kind: String, pub category: FileCategory, pub bytes: u64, pub physical_bytes: u64, pub logical_bytes: u64, pub age_days: f64, pub mtime_ns: i64, pub is_hidden: bool, pub is_dataless: bool, } /// Response payload for `/api/analytics/scatter`. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ScatterResponse { pub root_path: String, pub total_bytes: u64, pub points: Vec, } /// A single cell along the Hilbert space-filling curve. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct HilbertCell { pub index: u32, pub x: u32, pub y: u32, pub path: String, pub name: String, pub bytes: u64, pub category: FileCategory, pub age_bucket: AgeBucket, pub depth: u32, } /// Response payload for `/api/analytics/hilbert`. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct HilbertResponse { pub root_path: String, pub order: u32, pub grid_size: u32, pub color_by: HilbertColorBy, pub total_bytes: u64, pub cells: Vec, } /// A node in the 3-column *Storage River* Sankey diagram. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct SankeyNode { pub id: String, pub label: String, pub column: u8, pub bytes: u64, pub path: Option, pub category: Option, } /// A weighted link in the 3-column *Storage River* Sankey diagram. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct SankeyLink { pub source: String, pub target: String, pub bytes: u64, } /// Response payload for `/api/analytics/sankey`. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct SankeyResponse { pub root_path: String, pub total_bytes: u64, pub nodes: Vec, pub links: Vec, } /// Search match item for `/api/search`. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct SearchHit { pub path: String, pub name: String, pub kind: String, pub physical_bytes: u64, pub logical_bytes: u64, pub category: Option, pub mtime_ns: i64, } /// Thread-safe SQLite WAL directory cache with a dedicated non-blocking reader connection. #[derive(Debug)] pub struct CacheStore { write_conn: Mutex, read_conn: Option>, } impl CacheStore { /// Open or create a persistent SQLite WAL cache at `db_path`. pub fn open(db_path: &Path) -> Result { if let Some(parent) = db_path.parent() && !parent.as_os_str().is_empty() { std::fs::create_dir_all(parent).map_err(|source| CacheError::CreateDir { path: parent.display().to_string(), source, })?; } let write_conn = Connection::open(db_path)?; Self::init_schema(&write_conn)?; let read_conn = Connection::open_with_flags( db_path, OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX, )?; read_conn.execute_batch( "PRAGMA busy_timeout = 5000; PRAGMA query_only = ON;", )?; Ok(Self { write_conn: Mutex::new(write_conn), read_conn: Some(Mutex::new(read_conn)), }) } /// Open an existing SQLite cache strictly read-only without creating `-wal`/`-shm` or mutating schema. pub fn open_read_only(db_path: &Path) -> Result { let flags = OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX; let read_conn = Connection::open_with_flags(db_path, flags)?; read_conn.execute_batch( "PRAGMA busy_timeout = 5000; PRAGMA query_only = ON;", )?; let write_conn = Connection::open_with_flags(db_path, flags)?; write_conn.execute_batch("PRAGMA query_only = ON;")?; Ok(Self { write_conn: Mutex::new(write_conn), read_conn: Some(Mutex::new(read_conn)), }) } /// Open an in-memory SQLite cache (for tests). pub fn open_in_memory() -> Result { let conn = Connection::open_in_memory()?; Self::init_schema(&conn)?; Ok(Self { write_conn: Mutex::new(conn), read_conn: None, }) } fn init_schema(conn: &Connection) -> Result<(), CacheError> { conn.execute_batch( "PRAGMA auto_vacuum = INCREMENTAL; PRAGMA journal_mode = WAL; PRAGMA journal_size_limit = 33554432; PRAGMA synchronous = NORMAL; PRAGMA foreign_keys = ON; PRAGMA busy_timeout = 5000;", )?; conn.execute_batch( "CREATE TABLE IF NOT EXISTS meta ( key TEXT PRIMARY KEY, value TEXT NOT NULL );", )?; let existing_ver: Option = conn .query_row( "SELECT value FROM meta WHERE key = 'schema_version'", [], |r| r.get(0), ) .optional()?; if existing_ver.as_deref() != Some(SCHEMA_VERSION) { conn.execute_batch( "DROP TABLE IF EXISTS top_files; DROP TABLE IF EXISTS directories;", )?; } conn.execute_batch( "CREATE TABLE IF NOT EXISTS directories ( id INTEGER PRIMARY KEY, path TEXT NOT NULL UNIQUE, parent_id INTEGER, name TEXT NOT NULL, depth INTEGER NOT NULL, is_hidden INTEGER NOT NULL, direct_physical_bytes INTEGER NOT NULL, direct_logical_bytes INTEGER NOT NULL, direct_file_count INTEGER NOT NULL, direct_dir_count INTEGER NOT NULL, direct_dataless_count INTEGER NOT NULL DEFAULT 0, direct_dataless_logical_bytes INTEGER NOT NULL DEFAULT 0, dataless_count INTEGER NOT NULL, dataless_logical_bytes INTEGER NOT NULL, subtree_physical_bytes INTEGER NOT NULL, subtree_logical_bytes INTEGER NOT NULL, subtree_file_count INTEGER NOT NULL, subtree_dir_count INTEGER NOT NULL, inaccessible_count INTEGER NOT NULL, mtime_ns INTEGER NOT NULL, max_subtree_mtime_ns INTEGER NOT NULL, last_scanned_ns INTEGER NOT NULL, direct_categories_blob BLOB, subtree_categories_blob BLOB, direct_categories_logical_blob BLOB, subtree_categories_logical_blob BLOB, direct_age_buckets_blob BLOB, subtree_age_buckets_blob BLOB, direct_age_buckets_logical_blob BLOB, subtree_age_buckets_logical_blob BLOB, access_status TEXT NOT NULL ); CREATE INDEX IF NOT EXISTS idx_directories_parent_id ON directories(parent_id); CREATE INDEX IF NOT EXISTS idx_directories_bloat ON directories(name, subtree_physical_bytes DESC) WHERE name IN ('target', 'node_modules', '.venv', 'DerivedData', 'Caches', '.cache', 'ollama', 'huggingface'); CREATE INDEX IF NOT EXISTS idx_directories_subtree_phys ON directories(subtree_physical_bytes DESC); CREATE TABLE IF NOT EXISTS top_files ( id INTEGER PRIMARY KEY, dir_id INTEGER NOT NULL, name TEXT NOT NULL, extension TEXT NOT NULL, category INTEGER NOT NULL, physical_bytes INTEGER NOT NULL, logical_bytes INTEGER NOT NULL, mtime_ns INTEGER NOT NULL, is_hidden INTEGER NOT NULL, is_dataless INTEGER NOT NULL, UNIQUE(dir_id, name) ); CREATE INDEX IF NOT EXISTS idx_top_files_phys ON top_files(physical_bytes DESC);", )?; conn.execute( "INSERT OR REPLACE INTO meta (key, value) VALUES ('schema_version', ?1)", params![SCHEMA_VERSION], )?; Ok(()) } fn lock_write(&self) -> std::sync::MutexGuard<'_, Connection> { self.write_conn.lock().unwrap_or_else(|poisoned| { tracing::error!("CacheStore write mutex was poisoned; recovering inner connection"); poisoned.into_inner() }) } fn lock_read(&self) -> std::sync::MutexGuard<'_, Connection> { if let Some(rc) = &self.read_conn { rc.lock().unwrap_or_else(|poisoned| { tracing::error!("CacheStore read mutex was poisoned; recovering inner connection"); poisoned.into_inner() }) } else { self.lock_write() } } /// Read cache metadata. pub fn meta(&self) -> Result { let conn = self.lock_read(); let mut stmt = conn.prepare("SELECT key, value FROM meta")?; let rows = stmt.query_map([], |row| { Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)) })?; let mut meta = CacheMeta::default(); for row in rows { let (k, v) = row?; match k.as_str() { "schema_version" => meta.schema_version = v, "home_root" => meta.home_root = v, "root_dev" => meta.root_dev = v.parse().unwrap_or(0), "last_full_scan_started_ns" => { meta.last_full_scan_started_ns = v.parse().unwrap_or(0); } "last_full_scan_completed_ns" => { meta.last_full_scan_completed_ns = v.parse().unwrap_or(0); } _ => {} } } Ok(meta) } /// Check whether the cache has at least the Home Root (`""`) indexed. pub fn has_root(&self) -> Result { let conn = self.lock_read(); let count: i64 = conn.query_row( "SELECT COUNT(*) FROM directories WHERE path = ''", [], |r| r.get(0), )?; Ok(count > 0) } /// Replace the cached tree with a full scan result in one atomic transaction. pub fn replace_full_scan( &self, scan: &FullScanResult, home_root: &Path, started_ns: i64, completed_ns: i64, ) -> Result<(), CacheError> { let mut conn = self.lock_write(); let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?; tx.execute("DELETE FROM top_files", [])?; tx.execute("DELETE FROM directories", [])?; let dir_ids = upsert_directories_tx(&tx, &scan.directories)?; upsert_files_tx(&tx, &scan.top_files, Some(&dir_ids))?; set_meta_kv(&tx, "home_root", &home_root.display().to_string())?; set_meta_kv(&tx, "root_dev", &scan.root_dev.to_string())?; set_meta_kv(&tx, "last_full_scan_started_ns", &started_ns.to_string())?; set_meta_kv( &tx, "last_full_scan_completed_ns", &completed_ns.to_string(), )?; tx.commit()?; // Reclaim freed pages and truncate the WAL so full scans do not leave multi-GB files on disk. let auto_vacuum: i64 = conn .query_row("PRAGMA auto_vacuum", [], |r| r.get(0)) .unwrap_or(0); if auto_vacuum == 0 { let _ = conn.execute_batch("PRAGMA auto_vacuum = INCREMENTAL; VACUUM;"); } else { let _ = conn.execute_batch("PRAGMA incremental_vacuum;"); } let _ = conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE);"); Ok(()) } /// Apply a single-directory direct rescan and bubble signed deltas up to `""` (`O(depth)`). pub fn apply_directory_delta( &self, rel_path: &RelPath, scan: &DirectDirScan, ) -> Result { let mut conn = self.lock_write(); let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?; let existing = load_directory_tx(&tx, rel_path.as_str())?; let new_rec = &scan.record; let mut pruned_delta = DeltaBubble::default(); if existing.is_some() { let cached_children = load_child_directories(&tx, rel_path.as_str())?; for child in cached_children { if !scan.child_dir_names.iter().any(|n| n == &child.name) { delete_subtree_tx(&tx, &child.path)?; pruned_delta.subtract_record(&child); } } } let mut bubble = if let Some(old) = existing { update_existing_directory_delta_tx(&tx, &old, new_rec, &pruned_delta)? } else { upsert_directories_tx(&tx, std::slice::from_ref(new_rec))?; DeltaBubble::from_new_record(new_rec) }; bubble.max_mtime_ns = new_rec.max_subtree_mtime_ns; tx.execute( "DELETE FROM top_files WHERE dir_id = (SELECT id FROM directories WHERE path = ?1)", params![rel_path.as_str()], )?; upsert_files_tx(&tx, &scan.top_files, None)?; bubble_deltas_tx(&tx, rel_path.parent(), &bubble)?; tx.commit()?; Ok(DirDeltaSummary { path: rel_path.as_str().to_string(), delta_physical_bytes: bubble.phys, delta_logical_bytes: bubble.log, }) } /// Replace an entire subtree (e.g. after `MustScanSubDirs` or directory rename) and bubble deltas up. pub fn upsert_subtree( &self, rel_path: &RelPath, scan: &FullScanResult, ) -> Result { let mut conn = self.lock_write(); let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?; let old_root = load_directory_tx(&tx, rel_path.as_str())?; let new_root = scan .directories .iter() .find(|d| d.path == rel_path.as_str()); delete_subtree_tx(&tx, rel_path.as_str())?; let dir_ids = upsert_directories_tx(&tx, &scan.directories)?; upsert_files_tx(&tx, &scan.top_files, Some(&dir_ids))?; let bubble = DeltaBubble::diff(new_root, old_root.as_ref()); bubble_deltas_tx(&tx, rel_path.parent(), &bubble)?; tx.commit()?; Ok(DirDeltaSummary { path: rel_path.as_str().to_string(), delta_physical_bytes: bubble.phys, delta_logical_bytes: bubble.log, }) } /// Remove a deleted directory subtree and bubble negative deltas up to `""`. pub fn remove_subtree(&self, rel_path: &RelPath) -> Result { if rel_path.is_root() { return Ok(DirDeltaSummary { path: String::new(), delta_physical_bytes: 0, delta_logical_bytes: 0, }); } let mut conn = self.lock_write(); let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?; let Some(old) = load_directory_tx(&tx, rel_path.as_str())? else { return Ok(DirDeltaSummary { path: rel_path.as_str().to_string(), delta_physical_bytes: 0, delta_logical_bytes: 0, }); }; delete_subtree_tx(&tx, rel_path.as_str())?; let bubble = DeltaBubble::diff(None, Some(&old)); bubble_deltas_tx(&tx, rel_path.parent(), &bubble)?; tx.commit()?; Ok(DirDeltaSummary { path: rel_path.as_str().to_string(), delta_physical_bytes: bubble.phys, delta_logical_bytes: bubble.log, }) } /// Fetch a single cached directory record. pub fn get_directory_record( &self, rel_path: &RelPath, ) -> Result, CacheError> { let conn = self.lock_read(); load_directory_conn(&conn, rel_path.as_str()) } /// Bounded hierarchical tree projection for `/api/tree`. pub fn get_tree( &self, rel_path: &RelPath, max_depth: u32, metric: SizeMetric, include_hidden: bool, ) -> Result, CacheError> { let conn = self.lock_read(); let Some(root_rec) = load_directory_conn(&conn, rel_path.as_str())? else { return Ok(None); }; let clamped_depth = max_depth.clamp(1, 6); let descendants = load_subtree_up_to_depth(&conn, &root_rec, clamped_depth)?; let mut by_parent: HashMap> = HashMap::new(); for rec in descendants { let key = rec.parent_path.clone().unwrap_or_default(); by_parent.entry(key).or_default().push(rec); } let node = build_tree_node_from_map( &root_rec, &mut by_parent, clamped_depth, metric, include_hidden, ); Ok(Some(node)) } /// Detailed directory view for `/api/directory`. pub fn get_directory( &self, rel_path: &RelPath, sort: DirectorySort, metric: SizeMetric, ) -> Result, CacheError> { let conn = self.lock_read(); let Some(dir) = load_directory_conn(&conn, rel_path.as_str())? else { return Ok(None); }; let mut child_dirs = load_child_directories(&conn, rel_path.as_str())?; match sort { DirectorySort::Size => child_dirs.sort_unstable_by(|a, b| { b.subtree_bytes(metric) .cmp(&a.subtree_bytes(metric)) .then_with(|| a.name.cmp(&b.name)) }), DirectorySort::Name => child_dirs.sort_unstable_by(|a, b| a.name.cmp(&b.name)), DirectorySort::Mtime => child_dirs.sort_unstable_by(|a, b| { b.max_subtree_mtime_ns .cmp(&a.max_subtree_mtime_ns) .then_with(|| a.name.cmp(&b.name)) }), DirectorySort::Count => child_dirs.sort_unstable_by(|a, b| { b.subtree_file_count .cmp(&a.subtree_file_count) .then_with(|| a.name.cmp(&b.name)) }), } let mut top_files = load_top_files_for_dir(&conn, rel_path.as_str())?; match sort { DirectorySort::Size => top_files.sort_unstable_by(|a, b| { b.bytes(metric) .cmp(&a.bytes(metric)) .then_with(|| a.name.cmp(&b.name)) }), DirectorySort::Name => top_files.sort_unstable_by(|a, b| a.name.cmp(&b.name)), DirectorySort::Mtime => top_files.sort_unstable_by(|a, b| { b.mtime_ns .cmp(&a.mtime_ns) .then_with(|| a.name.cmp(&b.name)) }), DirectorySort::Count => {} } let bloat_hints = find_bloat_hints(&conn, rel_path.as_str(), metric)?; Ok(Some(DirectoryView { directory: dir, child_dirs, top_files, bloat_hints, })) } /// *Fossils & Dust* scatter projection for `/api/analytics/scatter`. pub fn get_scatter( &self, rel_path: &RelPath, metric: SizeMetric, limit: usize, ) -> Result, CacheError> { let conn = self.lock_read(); let Some(root_rec) = load_directory_conn(&conn, rel_path.as_str())? else { return Ok(None); }; let now_ns = current_time_ns(); let order_col = match metric { SizeMetric::Physical => "physical_bytes", SizeMetric::Logical => "logical_bytes", }; let clamped_limit = limit.clamp(10, 2000); let (lower, upper) = subtree_bounds(rel_path.as_str()); let sql = if rel_path.is_root() { format!( "SELECT CASE WHEN d.path = '' THEN f.name ELSE d.path || '/' || f.name END, d.path, f.name, f.extension, f.category, f.physical_bytes, f.logical_bytes, f.mtime_ns, f.is_hidden, f.is_dataless FROM top_files f JOIN directories d ON f.dir_id = d.id ORDER BY f.{order_col} DESC LIMIT ?1" ) } else { format!( "SELECT CASE WHEN d.path = '' THEN f.name ELSE d.path || '/' || f.name END, d.path, f.name, f.extension, f.category, f.physical_bytes, f.logical_bytes, f.mtime_ns, f.is_hidden, f.is_dataless FROM top_files f JOIN directories d ON f.dir_id = d.id WHERE d.path = ?1 OR (d.path >= ?2 AND d.path < ?3) ORDER BY f.{order_col} DESC LIMIT ?4" ) }; let mut stmt = conn.prepare(&sql)?; let rows = if rel_path.is_root() { stmt.query_map(params![clamped_limit as i64], map_file_row)? .collect::, _>>()? } else { stmt.query_map( params![rel_path.as_str(), lower, upper, clamped_limit as i64], map_file_row, )? .collect::, _>>()? }; let mut points: Vec = rows .into_iter() .map(|f| { let bytes = f.bytes(metric); let age_days = ((now_ns.saturating_sub(f.mtime_ns)) as f64) / (86_400.0 * 1_000_000_000.0); ScatterPoint { path: f.path, dir_path: f.dir_path, name: f.name, kind: "file".to_string(), category: f.category, bytes, physical_bytes: f.physical_bytes, logical_bytes: f.logical_bytes, age_days: age_days.max(0.01), mtime_ns: f.mtime_ns, is_hidden: f.is_hidden, is_dataless: f.is_dataless, } }) .collect(); // Also include top child directories as directory bubbles when files are sparse if points.len() < clamped_limit { let children = load_child_directories(&conn, rel_path.as_str())?; for child in children.into_iter().take(32) { let bytes = child.subtree_bytes(metric); if bytes == 0 { continue; } let age_days = ((now_ns.saturating_sub(child.max_subtree_mtime_ns)) as f64) / (86_400.0 * 1_000_000_000.0); let category = dominant_category(child.subtree_categories_for(metric)); points.push(ScatterPoint { path: child.path.clone(), dir_path: child.parent_path.unwrap_or_default(), name: child.name, kind: "directory".to_string(), category, bytes, physical_bytes: child.subtree_physical_bytes, logical_bytes: child.subtree_logical_bytes, age_days: age_days.max(0.01), mtime_ns: child.max_subtree_mtime_ns, is_hidden: child.is_hidden, is_dataless: false, }); } } Ok(Some(ScatterResponse { root_path: root_rec.path.clone(), total_bytes: root_rec.subtree_bytes(metric), points, })) } /// *Block Tapestry* Hilbert curve projection for `/api/analytics/hilbert`. pub fn get_hilbert( &self, rel_path: &RelPath, order: u32, color_by: HilbertColorBy, metric: SizeMetric, ) -> Result, CacheError> { let conn = self.lock_read(); let Some(root_rec) = load_directory_conn(&conn, rel_path.as_str())? else { return Ok(None); }; let clamped_order = order.clamp(4, 7); let grid_size = 1_u32 << clamped_order; let total_cells = grid_size * grid_size; let total_bytes = root_rec.subtree_bytes(metric); let children = load_child_directories(&conn, rel_path.as_str())?; let mut spans: Vec<(&DirectoryRecord, u64)> = children .iter() .filter_map(|c| { let b = c.subtree_bytes(metric); (b > 0).then_some((c, b)) }) .collect(); spans.sort_unstable_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.path.cmp(&b.0.path))); let mut cells = Vec::with_capacity(total_cells as usize); if total_bytes == 0 { return Ok(Some(HilbertResponse { root_path: root_rec.path, order: clamped_order, grid_size, color_by, total_bytes: 0, cells, })); } let direct_bytes = root_rec.direct_bytes(metric); let mut segments: Vec<(String, String, u64, FileCategory, AgeBucket, u32)> = spans .into_iter() .map(|(c, b)| { ( c.path.clone(), c.name.clone(), b, dominant_category(c.subtree_categories_for(metric)), dominant_age_bucket(c.subtree_age_buckets_for(metric)), c.depth, ) }) .collect(); if direct_bytes > 0 { segments.push(( root_rec.path.clone(), format!("{} (direct)", root_rec.name), direct_bytes, dominant_category(root_rec.direct_categories_for(metric)), dominant_age_bucket(root_rec.direct_age_buckets_for(metric)), root_rec.depth, )); } let seg_sum: u64 = segments.iter().map(|s| s.2).sum(); let norm_total = seg_sum.max(1); let mut cell_idx: u32 = 0; for (seg_idx, (path, name, bytes, cat, age_b, depth)) in segments.iter().enumerate() { let remaining_cells = total_cells.saturating_sub(cell_idx); if remaining_cells == 0 { break; } let alloc = if seg_idx + 1 == segments.len() { remaining_cells } else { let proportional = ((*bytes as f64 / norm_total as f64) * f64::from(total_cells)).round() as u32; proportional.max(1).min(remaining_cells) }; let bytes_per_cell = *bytes / u64::from(alloc.max(1)); let remainder = *bytes % u64::from(alloc.max(1)); for k in 0..alloc { let (x, y) = hilbert_d2xy(grid_size, cell_idx); let cell_bytes = if k == 0 { bytes_per_cell + remainder } else { bytes_per_cell }; cells.push(HilbertCell { index: cell_idx, x, y, path: path.clone(), name: name.clone(), bytes: cell_bytes, category: *cat, age_bucket: *age_b, depth: *depth, }); cell_idx += 1; } } Ok(Some(HilbertResponse { root_path: root_rec.path, order: clamped_order, grid_size, color_by, total_bytes, cells, })) } /// *Storage River* 3-column Sankey projection for `/api/analytics/sankey`. pub fn get_sankey( &self, rel_path: &RelPath, metric: SizeMetric, ) -> Result, CacheError> { let conn = self.lock_read(); let Some(root_rec) = load_directory_conn(&conn, rel_path.as_str())? else { return Ok(None); }; let mut children = load_child_directories(&conn, rel_path.as_str())?; children.sort_unstable_by(|a, b| { b.subtree_bytes(metric) .cmp(&a.subtree_bytes(metric)) .then_with(|| a.name.cmp(&b.name)) }); let root_id = "root".to_string(); let total_bytes = root_rec.subtree_bytes(metric); let mut nodes = vec![SankeyNode { id: root_id.clone(), label: root_rec.name.clone(), column: 0, bytes: total_bytes, path: Some(root_rec.path.clone()), category: None, }]; let mut links = Vec::new(); let mut cat_totals = CategoryHistogram::default(); let mut other_bytes = root_rec.direct_bytes(metric); let mut other_cats = *root_rec.direct_categories_for(metric); for (idx, child) in children.into_iter().enumerate() { let b = child.subtree_bytes(metric); if b == 0 { continue; } if idx < 10 { let node_id = format!("dir:{idx}"); nodes.push(SankeyNode { id: node_id.clone(), label: child.name.clone(), column: 1, bytes: b, path: Some(child.path.clone()), category: None, }); links.push(SankeyLink { source: root_id.clone(), target: node_id.clone(), bytes: b, }); add_sankey_category_links( &node_id, child.subtree_categories_for(metric), &mut cat_totals, &mut links, ); } else { other_bytes = other_bytes.saturating_add(b); other_cats.merge_from(child.subtree_categories_for(metric)); } } if other_bytes > 0 { let other_id = "dir:other".to_string(); nodes.push(SankeyNode { id: other_id.clone(), label: "Direct & Other".to_string(), column: 1, bytes: other_bytes, path: None, category: None, }); links.push(SankeyLink { source: root_id, target: other_id.clone(), bytes: other_bytes, }); add_sankey_category_links(&other_id, &other_cats, &mut cat_totals, &mut links); } for cat in FileCategory::ALL { let cb = cat_totals.get(cat); if cb > 0 { nodes.push(SankeyNode { id: format!("cat:{}", cat.as_str()), label: cat.as_str().to_string(), column: 2, bytes: cb, path: None, category: Some(cat), }); } } Ok(Some(SankeyResponse { root_path: root_rec.path, total_bytes, nodes, links, })) } /// Instant SQLite prefix/substring search over cached directories and top files. pub fn search( &self, query: &str, scope_path: &RelPath, limit: usize, ) -> Result, CacheError> { let trimmed = query.trim(); if trimmed.is_empty() { return Ok(Vec::new()); } let conn = self.lock_read(); let clamped_limit = limit.clamp(1, 100); let escaped = escape_like_pattern(trimmed); let pattern = format!("%{escaped}%"); let (scope_lower, scope_upper) = subtree_bounds(scope_path.as_str()); let mut hits = search_dirs( &conn, &pattern, scope_path, &scope_lower, &scope_upper, (clamped_limit / 2).max(1), )?; hits.extend(search_files( &conn, &pattern, scope_path, &scope_lower, &scope_upper, clamped_limit, )?); hits.sort_unstable_by(|a, b| { b.physical_bytes .cmp(&a.physical_bytes) .then_with(|| a.path.cmp(&b.path)) }); hits.truncate(clamped_limit); Ok(hits) } } const DIRECTORY_INSERT_SQL: &str = "INSERT INTO directories ( path, parent_id, name, depth, is_hidden, direct_physical_bytes, direct_logical_bytes, direct_file_count, direct_dir_count, direct_dataless_count, direct_dataless_logical_bytes, dataless_count, dataless_logical_bytes, subtree_physical_bytes, subtree_logical_bytes, subtree_file_count, subtree_dir_count, inaccessible_count, mtime_ns, max_subtree_mtime_ns, last_scanned_ns, direct_categories_blob, subtree_categories_blob, direct_categories_logical_blob, subtree_categories_logical_blob, direct_age_buckets_blob, subtree_age_buckets_blob, direct_age_buckets_logical_blob, subtree_age_buckets_logical_blob, access_status ) VALUES ( ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18, ?19, ?20, ?21, ?22, ?23, ?24, ?25, ?26, ?27, ?28, ?29, ?30 ) ON CONFLICT(path) DO UPDATE SET parent_id = excluded.parent_id, name = excluded.name, depth = excluded.depth, is_hidden = excluded.is_hidden, direct_physical_bytes = excluded.direct_physical_bytes, direct_logical_bytes = excluded.direct_logical_bytes, direct_file_count = excluded.direct_file_count, direct_dir_count = excluded.direct_dir_count, direct_dataless_count = excluded.direct_dataless_count, direct_dataless_logical_bytes = excluded.direct_dataless_logical_bytes, dataless_count = excluded.dataless_count, dataless_logical_bytes = excluded.dataless_logical_bytes, subtree_physical_bytes = excluded.subtree_physical_bytes, subtree_logical_bytes = excluded.subtree_logical_bytes, subtree_file_count = excluded.subtree_file_count, subtree_dir_count = excluded.subtree_dir_count, inaccessible_count = excluded.inaccessible_count, mtime_ns = excluded.mtime_ns, max_subtree_mtime_ns = excluded.max_subtree_mtime_ns, last_scanned_ns = excluded.last_scanned_ns, direct_categories_blob = excluded.direct_categories_blob, subtree_categories_blob = excluded.subtree_categories_blob, direct_categories_logical_blob = excluded.direct_categories_logical_blob, subtree_categories_logical_blob = excluded.subtree_categories_logical_blob, direct_age_buckets_blob = excluded.direct_age_buckets_blob, subtree_age_buckets_blob = excluded.subtree_age_buckets_blob, direct_age_buckets_logical_blob = excluded.direct_age_buckets_logical_blob, subtree_age_buckets_logical_blob = excluded.subtree_age_buckets_logical_blob, access_status = excluded.access_status RETURNING id"; fn resolve_dir_id_tx( tx: &rusqlite::Transaction<'_>, path: &str, cache: &mut HashMap, ) -> Result, CacheError> { if let Some(&id) = cache.get(path) { return Ok(Some(id)); } let id: Option = tx .query_row( "SELECT id FROM directories WHERE path = ?1", params![path], |r| r.get(0), ) .optional()?; if let Some(found) = id { cache.insert(path.to_string(), found); } Ok(id) } fn upsert_directories_tx( tx: &rusqlite::Transaction<'_>, dirs: &[DirectoryRecord], ) -> Result, CacheError> { let mut ids = HashMap::with_capacity(dirs.len()); let mut stmt = tx.prepare(DIRECTORY_INSERT_SQL)?; for dir in dirs { let parent_id = match dir.parent_path.as_deref() { Some(p) => resolve_dir_id_tx(tx, p, &mut ids)?, None => None, }; let id = insert_directory_row(&mut stmt, dir, parent_id)?; ids.insert(dir.path.clone(), id); } Ok(ids) } fn upsert_files_tx( tx: &rusqlite::Transaction<'_>, files: &[FileEntry], pre_ids: Option<&HashMap>, ) -> Result<(), CacheError> { let mut local_ids = HashMap::new(); let mut stmt = tx.prepare( "INSERT OR REPLACE INTO top_files ( dir_id, name, extension, category, physical_bytes, logical_bytes, mtime_ns, is_hidden, is_dataless ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)", )?; for file in files { let dir_id = if let Some(map) = pre_ids && let Some(&id) = map.get(&file.dir_path) { id } else if let Some(id) = resolve_dir_id_tx(tx, &file.dir_path, &mut local_ids)? { id } else { continue; }; insert_file_row(&mut stmt, dir_id, file)?; } Ok(()) } #[derive(Default)] struct DeltaBubble { phys: i64, log: i64, files: i64, dirs: i64, dataless_count: i64, dataless_logical_bytes: i64, inaccessible_count: i64, cats: [i64; CATEGORY_COUNT], cats_log: [i64; CATEGORY_COUNT], ages: [i64; AGE_BUCKET_COUNT], ages_log: [i64; AGE_BUCKET_COUNT], max_mtime_ns: i64, } impl DeltaBubble { fn from_new_record(rec: &DirectoryRecord) -> Self { Self { phys: rec.direct_physical_bytes as i64, log: rec.direct_logical_bytes as i64, files: rec.direct_file_count as i64, dirs: rec.direct_dir_count as i64, dataless_count: rec.direct_dataless_count as i64, dataless_logical_bytes: rec.direct_dataless_logical_bytes as i64, inaccessible_count: rec.inaccessible_count as i64, cats: CategoryHistogram::signed_diff( &rec.direct_categories, &CategoryHistogram::default(), ), cats_log: CategoryHistogram::signed_diff( &rec.direct_categories_logical, &CategoryHistogram::default(), ), ages: AgeHistogram::signed_diff(&rec.direct_age_buckets, &AgeHistogram::default()), ages_log: AgeHistogram::signed_diff( &rec.direct_age_buckets_logical, &AgeHistogram::default(), ), max_mtime_ns: rec.max_subtree_mtime_ns, } } fn subtract_record(&mut self, child: &DirectoryRecord) { self.phys -= child.subtree_physical_bytes as i64; self.log -= child.subtree_logical_bytes as i64; self.files -= child.subtree_file_count as i64; self.dirs -= child.subtree_dir_count as i64; self.dataless_count -= child.dataless_count as i64; self.dataless_logical_bytes -= child.dataless_logical_bytes as i64; self.inaccessible_count -= child.inaccessible_count as i64; let dc = CategoryHistogram::signed_diff( &CategoryHistogram::default(), &child.subtree_categories, ); let dcl = CategoryHistogram::signed_diff( &CategoryHistogram::default(), &child.subtree_categories_logical, ); let da = AgeHistogram::signed_diff(&AgeHistogram::default(), &child.subtree_age_buckets); let dal = AgeHistogram::signed_diff(&AgeHistogram::default(), &child.subtree_age_buckets_logical); for i in 0..CATEGORY_COUNT { self.cats[i] += dc[i]; self.cats_log[i] += dcl[i]; } for i in 0..AGE_BUCKET_COUNT { self.ages[i] += da[i]; self.ages_log[i] += dal[i]; } } fn diff(new_rec: Option<&DirectoryRecord>, old_rec: Option<&DirectoryRecord>) -> Self { let zero_cats = CategoryHistogram::default(); let zero_ages = AgeHistogram::default(); let ( new_phys, new_log, new_files, new_dirs, new_dl, new_dl_log, new_inacc, new_cats, new_cats_log, new_ages, new_ages_log, max_mtime, ) = match new_rec { Some(r) => ( r.subtree_physical_bytes as i64, r.subtree_logical_bytes as i64, r.subtree_file_count as i64, r.subtree_dir_count as i64, r.dataless_count as i64, r.dataless_logical_bytes as i64, r.inaccessible_count as i64, &r.subtree_categories, &r.subtree_categories_logical, &r.subtree_age_buckets, &r.subtree_age_buckets_logical, r.max_subtree_mtime_ns, ), None => ( 0, 0, 0, 0, 0, 0, 0, &zero_cats, &zero_cats, &zero_ages, &zero_ages, 0, ), }; let ( old_phys, old_log, old_files, old_dirs, old_dl, old_dl_log, old_inacc, old_cats, old_cats_log, old_ages, old_ages_log, ) = match old_rec { Some(r) => ( r.subtree_physical_bytes as i64, r.subtree_logical_bytes as i64, r.subtree_file_count as i64, r.subtree_dir_count as i64, r.dataless_count as i64, r.dataless_logical_bytes as i64, r.inaccessible_count as i64, &r.subtree_categories, &r.subtree_categories_logical, &r.subtree_age_buckets, &r.subtree_age_buckets_logical, ), None => ( 0, 0, 0, 0, 0, 0, 0, &zero_cats, &zero_cats, &zero_ages, &zero_ages, ), }; Self { phys: new_phys - old_phys, log: new_log - old_log, files: new_files - old_files, dirs: new_dirs - old_dirs, dataless_count: new_dl - old_dl, dataless_logical_bytes: new_dl_log - old_dl_log, inaccessible_count: new_inacc - old_inacc, cats: CategoryHistogram::signed_diff(new_cats, old_cats), cats_log: CategoryHistogram::signed_diff(new_cats_log, old_cats_log), ages: AgeHistogram::signed_diff(new_ages, old_ages), ages_log: AgeHistogram::signed_diff(new_ages_log, old_ages_log), max_mtime_ns: max_mtime, } } } fn compute_existing_delta_bubble( old: &DirectoryRecord, new_rec: &DirectoryRecord, pruned: &DeltaBubble, ) -> DeltaBubble { let mut bubble = DeltaBubble { phys: (new_rec.direct_physical_bytes as i64 - old.direct_physical_bytes as i64) + pruned.phys, log: (new_rec.direct_logical_bytes as i64 - old.direct_logical_bytes as i64) + pruned.log, files: (new_rec.direct_file_count as i64 - old.direct_file_count as i64) + pruned.files, dirs: (new_rec.direct_dir_count as i64 - old.direct_dir_count as i64) + pruned.dirs, dataless_count: (new_rec.direct_dataless_count as i64 - old.direct_dataless_count as i64) + pruned.dataless_count, dataless_logical_bytes: (new_rec.direct_dataless_logical_bytes as i64 - old.direct_dataless_logical_bytes as i64) + pruned.dataless_logical_bytes, inaccessible_count: (new_rec.inaccessible_count as i64 - u64::from(old.access_status == AccessStatus::PermissionDenied) as i64) + pruned.inaccessible_count, cats: CategoryHistogram::signed_diff(&new_rec.direct_categories, &old.direct_categories), cats_log: CategoryHistogram::signed_diff( &new_rec.direct_categories_logical, &old.direct_categories_logical, ), ages: AgeHistogram::signed_diff(&new_rec.direct_age_buckets, &old.direct_age_buckets), ages_log: AgeHistogram::signed_diff( &new_rec.direct_age_buckets_logical, &old.direct_age_buckets_logical, ), max_mtime_ns: new_rec.max_subtree_mtime_ns, }; for i in 0..CATEGORY_COUNT { bubble.cats[i] += pruned.cats[i]; bubble.cats_log[i] += pruned.cats_log[i]; } for i in 0..AGE_BUCKET_COUNT { bubble.ages[i] += pruned.ages[i]; bubble.ages_log[i] += pruned.ages_log[i]; } bubble } fn update_existing_directory_delta_tx( tx: &rusqlite::Transaction<'_>, old: &DirectoryRecord, new_rec: &DirectoryRecord, pruned: &DeltaBubble, ) -> Result { let bubble = compute_existing_delta_bubble(old, new_rec, pruned); let mut updated_sub_cats = old.subtree_categories; updated_sub_cats.apply_signed_delta(&bubble.cats); let mut updated_sub_cats_log = old.subtree_categories_logical; updated_sub_cats_log.apply_signed_delta(&bubble.cats_log); let mut updated_sub_ages = old.subtree_age_buckets; updated_sub_ages.apply_signed_delta(&bubble.ages); let mut updated_sub_ages_log = old.subtree_age_buckets_logical; updated_sub_ages_log.apply_signed_delta(&bubble.ages_log); let is_leaf = new_rec.direct_dir_count == 0; let sub_cat_blob = (!is_leaf).then(|| updated_sub_cats.to_blob()).flatten(); let sub_cat_log_blob = (!is_leaf).then(|| updated_sub_cats_log.to_blob()).flatten(); let sub_age_blob = (!is_leaf).then(|| updated_sub_ages.to_blob()).flatten(); let sub_age_log_blob = (!is_leaf).then(|| updated_sub_ages_log.to_blob()).flatten(); tx.execute( "UPDATE directories SET direct_physical_bytes = ?2, direct_logical_bytes = ?3, direct_file_count = ?4, direct_dir_count = ?5, direct_dataless_count = ?6, direct_dataless_logical_bytes = ?7, dataless_count = ?8, dataless_logical_bytes = ?9, subtree_physical_bytes = ?10, subtree_logical_bytes = ?11, subtree_file_count = ?12, subtree_dir_count = ?13, inaccessible_count = ?14, mtime_ns = ?15, max_subtree_mtime_ns = MAX(max_subtree_mtime_ns, ?16), last_scanned_ns = ?17, direct_categories_blob = ?18, subtree_categories_blob = ?19, direct_categories_logical_blob = ?20, subtree_categories_logical_blob = ?21, direct_age_buckets_blob = ?22, subtree_age_buckets_blob = ?23, direct_age_buckets_logical_blob = ?24, subtree_age_buckets_logical_blob = ?25, access_status = ?26 WHERE path = ?1", params![ new_rec.path, new_rec.direct_physical_bytes as i64, new_rec.direct_logical_bytes as i64, new_rec.direct_file_count as i64, new_rec.direct_dir_count as i64, new_rec.direct_dataless_count as i64, new_rec.direct_dataless_logical_bytes as i64, apply_signed_u64(old.dataless_count, bubble.dataless_count) as i64, apply_signed_u64(old.dataless_logical_bytes, bubble.dataless_logical_bytes) as i64, apply_signed_u64(old.subtree_physical_bytes, bubble.phys) as i64, apply_signed_u64(old.subtree_logical_bytes, bubble.log) as i64, apply_signed_u64(old.subtree_file_count, bubble.files) as i64, apply_signed_u64(old.subtree_dir_count, bubble.dirs) as i64, apply_signed_u64(old.inaccessible_count, bubble.inaccessible_count) as i64, new_rec.mtime_ns, new_rec.max_subtree_mtime_ns, new_rec.last_scanned_ns, new_rec.direct_categories.to_blob(), sub_cat_blob, new_rec.direct_categories_logical.to_blob(), sub_cat_log_blob, new_rec.direct_age_buckets.to_blob(), sub_age_blob, new_rec.direct_age_buckets_logical.to_blob(), sub_age_log_blob, new_rec.access_status.as_str(), ], )?; Ok(bubble) } fn add_sankey_category_links( source_id: &str, cats: &CategoryHistogram, cat_totals: &mut CategoryHistogram, links: &mut Vec, ) { for cat in FileCategory::ALL { let cb = cats.get(cat); if cb > 0 { cat_totals.add(cat, cb); links.push(SankeyLink { source: source_id.to_string(), target: format!("cat:{}", cat.as_str()), bytes: cb, }); } } } fn search_dirs( conn: &Connection, pattern: &str, scope_path: &RelPath, scope_lower: &str, scope_upper: &str, limit: usize, ) -> Result, CacheError> { let sql = if scope_path.is_root() { "SELECT path, name, subtree_physical_bytes, subtree_logical_bytes, max_subtree_mtime_ns FROM directories WHERE path != '' AND (name LIKE ?1 ESCAPE '\\' OR path LIKE ?1 ESCAPE '\\') ORDER BY subtree_physical_bytes DESC LIMIT ?2" } else { "SELECT path, name, subtree_physical_bytes, subtree_logical_bytes, max_subtree_mtime_ns FROM directories WHERE (path = ?2 OR (path >= ?3 AND path < ?4)) AND (name LIKE ?1 ESCAPE '\\' OR path LIKE ?1 ESCAPE '\\') ORDER BY subtree_physical_bytes DESC LIMIT ?5" }; let mut stmt = conn.prepare(sql)?; let mapper = |r: &rusqlite::Row<'_>| -> rusqlite::Result { Ok(SearchHit { path: r.get(0)?, name: r.get(1)?, kind: "directory".to_string(), physical_bytes: r.get::<_, i64>(2)? as u64, logical_bytes: r.get::<_, i64>(3)? as u64, category: None, mtime_ns: r.get(4)?, }) }; let rows = if scope_path.is_root() { stmt.query_map(params![pattern, limit as i64], mapper)? .collect::, _>>()? } else { stmt.query_map( params![ pattern, scope_path.as_str(), scope_lower, scope_upper, limit as i64 ], mapper, )? .collect::, _>>()? }; Ok(rows) } fn search_files( conn: &Connection, pattern: &str, scope_path: &RelPath, scope_lower: &str, scope_upper: &str, limit: usize, ) -> Result, CacheError> { let sql = if scope_path.is_root() { "SELECT CASE WHEN d.path = '' THEN f.name ELSE d.path || '/' || f.name END AS full_path, f.name, f.category, f.physical_bytes, f.logical_bytes, f.mtime_ns FROM top_files f JOIN directories d ON f.dir_id = d.id WHERE f.name LIKE ?1 ESCAPE '\\' OR full_path LIKE ?1 ESCAPE '\\' ORDER BY f.physical_bytes DESC LIMIT ?2" } else { "SELECT CASE WHEN d.path = '' THEN f.name ELSE d.path || '/' || f.name END AS full_path, f.name, f.category, f.physical_bytes, f.logical_bytes, f.mtime_ns FROM top_files f JOIN directories d ON f.dir_id = d.id WHERE (d.path = ?2 OR (d.path >= ?3 AND d.path < ?4)) AND (f.name LIKE ?1 ESCAPE '\\' OR full_path LIKE ?1 ESCAPE '\\') ORDER BY f.physical_bytes DESC LIMIT ?5" }; let mut stmt = conn.prepare(sql)?; let mapper = |r: &rusqlite::Row<'_>| -> rusqlite::Result { let cat_id: i64 = r.get(2)?; Ok(SearchHit { path: r.get(0)?, name: r.get(1)?, kind: "file".to_string(), physical_bytes: r.get::<_, i64>(3)? as u64, logical_bytes: r.get::<_, i64>(4)? as u64, category: Some(FileCategory::from_u8(cat_id as u8)), mtime_ns: r.get(5)?, }) }; let rows = if scope_path.is_root() { stmt.query_map(params![pattern, limit as i64], mapper)? .collect::, _>>()? } else { stmt.query_map( params![ pattern, scope_path.as_str(), scope_lower, scope_upper, limit as i64 ], mapper, )? .collect::, _>>()? }; Ok(rows) } fn set_meta_kv(conn: &Connection, key: &str, value: &str) -> Result<(), CacheError> { conn.execute( "INSERT OR REPLACE INTO meta (key, value) VALUES (?1, ?2)", params![key, value], )?; Ok(()) } fn insert_directory_row( stmt: &mut rusqlite::Statement<'_>, dir: &DirectoryRecord, parent_id: Option, ) -> Result { let is_leaf = dir.direct_dir_count == 0; let id: i64 = stmt.query_row( params![ dir.path, parent_id, dir.name, dir.depth, i64::from(dir.is_hidden), dir.direct_physical_bytes as i64, dir.direct_logical_bytes as i64, dir.direct_file_count as i64, dir.direct_dir_count as i64, dir.direct_dataless_count as i64, dir.direct_dataless_logical_bytes as i64, dir.dataless_count as i64, dir.dataless_logical_bytes as i64, dir.subtree_physical_bytes as i64, dir.subtree_logical_bytes as i64, dir.subtree_file_count as i64, dir.subtree_dir_count as i64, dir.inaccessible_count as i64, dir.mtime_ns, dir.max_subtree_mtime_ns, dir.last_scanned_ns, dir.direct_categories.to_blob(), if is_leaf { None } else { dir.subtree_categories.to_blob() }, dir.direct_categories_logical.to_blob(), if is_leaf { None } else { dir.subtree_categories_logical.to_blob() }, dir.direct_age_buckets.to_blob(), if is_leaf { None } else { dir.subtree_age_buckets.to_blob() }, dir.direct_age_buckets_logical.to_blob(), if is_leaf { None } else { dir.subtree_age_buckets_logical.to_blob() }, dir.access_status.as_str(), ], |r| r.get(0), )?; Ok(id) } fn insert_file_row( stmt: &mut rusqlite::Statement<'_>, dir_id: i64, file: &FileEntry, ) -> Result<(), CacheError> { stmt.execute(params![ dir_id, file.name, file.extension, i64::from(file.category as u8), file.physical_bytes as i64, file.logical_bytes as i64, file.mtime_ns, i64::from(file.is_hidden), i64::from(file.is_dataless), ])?; Ok(()) } fn load_directory_tx( tx: &rusqlite::Transaction<'_>, path: &str, ) -> Result, CacheError> { load_directory_conn(tx, path) } const DIRECTORY_SELECT_COLS: &str = "d.path, d.name, d.depth, d.is_hidden, d.direct_physical_bytes, d.direct_logical_bytes, d.direct_file_count, d.direct_dir_count, d.direct_dataless_count, d.direct_dataless_logical_bytes, d.dataless_count, d.dataless_logical_bytes, d.subtree_physical_bytes, d.subtree_logical_bytes, d.subtree_file_count, d.subtree_dir_count, d.inaccessible_count, d.mtime_ns, d.max_subtree_mtime_ns, d.last_scanned_ns, d.direct_categories_blob, d.subtree_categories_blob, d.direct_categories_logical_blob, d.subtree_categories_logical_blob, d.direct_age_buckets_blob, d.subtree_age_buckets_blob, d.direct_age_buckets_logical_blob, d.subtree_age_buckets_logical_blob, d.access_status"; fn parent_path_from_rel(path: &str) -> Option { if path.is_empty() { None } else { Some( path.rsplit_once('/') .map_or_else(String::new, |(parent, _)| parent.to_string()), ) } } fn load_directory_conn( conn: &Connection, path: &str, ) -> Result, CacheError> { let sql = format!("SELECT {DIRECTORY_SELECT_COLS} FROM directories d WHERE d.path = ?1"); conn.query_row(&sql, params![path], map_directory_row) .optional() .map_err(CacheError::from) } fn load_child_directories( conn: &Connection, parent_path: &str, ) -> Result, CacheError> { let sql = format!( "SELECT {DIRECTORY_SELECT_COLS} FROM directories d WHERE d.parent_id = (SELECT id FROM directories WHERE path = ?1)" ); let mut stmt = conn.prepare(&sql)?; let rows = stmt.query_map(params![parent_path], map_directory_row)?; rows.collect::, _>>() .map_err(CacheError::from) } fn load_subtree_up_to_depth( conn: &Connection, root_rec: &DirectoryRecord, clamped_depth: u32, ) -> Result, CacheError> { let sql = format!( "WITH RECURSIVE tree(id, rel_depth) AS ( SELECT id, 0 FROM directories WHERE path = ?1 UNION ALL SELECT c.id, t.rel_depth + 1 FROM directories c JOIN tree t ON c.parent_id = t.id WHERE t.rel_depth < ?2 ) SELECT {DIRECTORY_SELECT_COLS} FROM directories d JOIN tree t ON d.id = t.id WHERE t.rel_depth > 0" ); let mut stmt = conn.prepare(&sql)?; let rows = stmt.query_map(params![root_rec.path, clamped_depth], map_directory_row)?; rows.collect::, _>>() .map_err(CacheError::from) } fn map_directory_row(row: &rusqlite::Row<'_>) -> rusqlite::Result { let path: String = row.get(0)?; let direct_dir_count = row.get::<_, i64>(7)? as u64; let is_leaf = direct_dir_count == 0; let direct_cat_blob: Option> = row.get(20)?; let subtree_cat_blob: Option> = row.get(21)?; let direct_cat_log_blob: Option> = row.get(22)?; let subtree_cat_log_blob: Option> = row.get(23)?; let direct_age_blob: Option> = row.get(24)?; let subtree_age_blob: Option> = row.get(25)?; let direct_age_log_blob: Option> = row.get(26)?; let subtree_age_log_blob: Option> = row.get(27)?; let status_str: String = row.get(28)?; let direct_categories = CategoryHistogram::from_blob(direct_cat_blob.as_deref()); let subtree_categories = if is_leaf && subtree_cat_blob.is_none() { direct_categories } else { CategoryHistogram::from_blob(subtree_cat_blob.as_deref()) }; let direct_categories_logical = CategoryHistogram::from_blob(direct_cat_log_blob.as_deref()); let subtree_categories_logical = if is_leaf && subtree_cat_log_blob.is_none() { direct_categories_logical } else { CategoryHistogram::from_blob(subtree_cat_log_blob.as_deref()) }; let direct_age_buckets = AgeHistogram::from_blob(direct_age_blob.as_deref()); let subtree_age_buckets = if is_leaf && subtree_age_blob.is_none() { direct_age_buckets } else { AgeHistogram::from_blob(subtree_age_blob.as_deref()) }; let direct_age_buckets_logical = AgeHistogram::from_blob(direct_age_log_blob.as_deref()); let subtree_age_buckets_logical = if is_leaf && subtree_age_log_blob.is_none() { direct_age_buckets_logical } else { AgeHistogram::from_blob(subtree_age_log_blob.as_deref()) }; Ok(DirectoryRecord { parent_path: parent_path_from_rel(&path), path, name: row.get(1)?, depth: row.get::<_, u32>(2)?, is_hidden: row.get::<_, i64>(3)? != 0, direct_physical_bytes: row.get::<_, i64>(4)? as u64, direct_logical_bytes: row.get::<_, i64>(5)? as u64, direct_file_count: row.get::<_, i64>(6)? as u64, direct_dir_count, direct_dataless_count: row.get::<_, i64>(8)? as u64, direct_dataless_logical_bytes: row.get::<_, i64>(9)? as u64, dataless_count: row.get::<_, i64>(10)? as u64, dataless_logical_bytes: row.get::<_, i64>(11)? as u64, subtree_physical_bytes: row.get::<_, i64>(12)? as u64, subtree_logical_bytes: row.get::<_, i64>(13)? as u64, subtree_file_count: row.get::<_, i64>(14)? as u64, subtree_dir_count: row.get::<_, i64>(15)? as u64, inaccessible_count: row.get::<_, i64>(16)? as u64, mtime_ns: row.get(17)?, max_subtree_mtime_ns: row.get(18)?, last_scanned_ns: row.get(19)?, direct_categories, subtree_categories, direct_categories_logical, subtree_categories_logical, direct_age_buckets, subtree_age_buckets, direct_age_buckets_logical, subtree_age_buckets_logical, access_status: AccessStatus::from_db_str(&status_str), }) } fn load_top_files_for_dir(conn: &Connection, dir_path: &str) -> Result, CacheError> { let mut stmt = conn.prepare( "SELECT CASE WHEN d.path = '' THEN f.name ELSE d.path || '/' || f.name END, d.path, f.name, f.extension, f.category, f.physical_bytes, f.logical_bytes, f.mtime_ns, f.is_hidden, f.is_dataless FROM top_files f JOIN directories d ON f.dir_id = d.id WHERE d.path = ?1", )?; let rows = stmt.query_map(params![dir_path], map_file_row)?; rows.collect::, _>>() .map_err(CacheError::from) } fn map_file_row(row: &rusqlite::Row<'_>) -> rusqlite::Result { let cat_id: i64 = row.get(4)?; Ok(FileEntry { path: row.get(0)?, dir_path: row.get(1)?, name: row.get(2)?, extension: row.get(3)?, category: FileCategory::from_u8(cat_id as u8), physical_bytes: row.get::<_, i64>(5)? as u64, logical_bytes: row.get::<_, i64>(6)? as u64, mtime_ns: row.get(7)?, is_hidden: row.get::<_, i64>(8)? != 0, is_dataless: row.get::<_, i64>(9)? != 0, }) } fn subtree_bounds(path: &str) -> (String, String) { (format!("{path}/"), format!("{path}0")) } fn escape_like_pattern(raw: &str) -> String { let mut out = String::with_capacity(raw.len()); for ch in raw.chars() { if matches!(ch, '\\' | '%' | '_') { out.push('\\'); } out.push(ch); } out } fn delete_subtree_tx(tx: &rusqlite::Transaction<'_>, rel_path: &str) -> Result<(), CacheError> { if rel_path.is_empty() { tx.execute("DELETE FROM top_files", [])?; tx.execute("DELETE FROM directories", [])?; } else { let (lower, upper) = subtree_bounds(rel_path); tx.execute( "DELETE FROM top_files WHERE dir_id IN ( SELECT id FROM directories WHERE path = ?1 OR (path >= ?2 AND path < ?3) )", params![rel_path, lower, upper], )?; tx.execute( "DELETE FROM directories WHERE path = ?1 OR (path >= ?2 AND path < ?3)", params![rel_path, lower, upper], )?; } Ok(()) } fn bubble_deltas_tx( tx: &rusqlite::Transaction<'_>, mut cursor: Option, bubble: &DeltaBubble, ) -> Result<(), CacheError> { while let Some(ancestor_rel) = cursor { if let Some(anc) = load_directory_tx(tx, ancestor_rel.as_str())? { let new_phys = apply_signed_u64(anc.subtree_physical_bytes, bubble.phys); let new_log = apply_signed_u64(anc.subtree_logical_bytes, bubble.log); let new_files = apply_signed_u64(anc.subtree_file_count, bubble.files); let new_dirs = apply_signed_u64(anc.subtree_dir_count, bubble.dirs); let new_dl = apply_signed_u64(anc.dataless_count, bubble.dataless_count); let new_dl_log = apply_signed_u64(anc.dataless_logical_bytes, bubble.dataless_logical_bytes); let new_inacc = apply_signed_u64(anc.inaccessible_count, bubble.inaccessible_count); let mut new_cats = anc.subtree_categories; new_cats.apply_signed_delta(&bubble.cats); let mut new_cats_log = anc.subtree_categories_logical; new_cats_log.apply_signed_delta(&bubble.cats_log); let mut new_ages = anc.subtree_age_buckets; new_ages.apply_signed_delta(&bubble.ages); let mut new_ages_log = anc.subtree_age_buckets_logical; new_ages_log.apply_signed_delta(&bubble.ages_log); tx.execute( "UPDATE directories SET dataless_count = ?2, dataless_logical_bytes = ?3, subtree_physical_bytes = ?4, subtree_logical_bytes = ?5, subtree_file_count = ?6, subtree_dir_count = ?7, inaccessible_count = ?8, max_subtree_mtime_ns = MAX(max_subtree_mtime_ns, ?9), subtree_categories_blob = ?10, subtree_categories_logical_blob = ?11, subtree_age_buckets_blob = ?12, subtree_age_buckets_logical_blob = ?13 WHERE path = ?1", params![ anc.path, new_dl as i64, new_dl_log as i64, new_phys as i64, new_log as i64, new_files as i64, new_dirs as i64, new_inacc as i64, bubble.max_mtime_ns, new_cats.to_blob(), new_cats_log.to_blob(), new_ages.to_blob(), new_ages_log.to_blob(), ], )?; } cursor = ancestor_rel.parent(); } Ok(()) } fn build_tree_node_from_map( rec: &DirectoryRecord, by_parent: &mut HashMap>, remaining_depth: u32, metric: SizeMetric, include_hidden: bool, ) -> TreeNode { let total_bytes = rec.subtree_bytes(metric); let mut children = Vec::new(); if remaining_depth > 0 { let mut child_recs = by_parent.remove(&rec.path).unwrap_or_default(); if !include_hidden { child_recs.retain(|c| !c.is_hidden); } child_recs.sort_unstable_by(|a, b| { b.subtree_bytes(metric) .cmp(&a.subtree_bytes(metric)) .then_with(|| a.name.cmp(&b.name)) }); let threshold = (total_bytes as f64) * 0.002; let mut collapsed_phys = 0_u64; let mut collapsed_log = 0_u64; let mut collapsed_files = 0_u64; let mut collapsed_dirs = 0_u64; let mut collapsed_count = 0_usize; for (idx, child) in child_recs.into_iter().enumerate() { let child_bytes = child.subtree_bytes(metric); if idx >= 40 || (idx >= 8 && (child_bytes as f64) < threshold) { collapsed_phys = collapsed_phys.saturating_add(child.subtree_physical_bytes); collapsed_log = collapsed_log.saturating_add(child.subtree_logical_bytes); collapsed_files = collapsed_files.saturating_add(child.subtree_file_count); collapsed_dirs = collapsed_dirs.saturating_add(child.subtree_dir_count); collapsed_count += 1; continue; } children.push(build_tree_node_from_map( &child, by_parent, remaining_depth - 1, metric, include_hidden, )); } let collapsed_bytes = match metric { SizeMetric::Physical => collapsed_phys, SizeMetric::Logical => collapsed_log, }; if collapsed_count > 0 && collapsed_bytes > 0 { children.push(TreeNode { path: format!("{}:__other__", rec.path), name: format!("Other ({collapsed_count} items <0.2%)"), bytes: collapsed_bytes, physical_bytes: collapsed_phys, logical_bytes: collapsed_log, file_count: collapsed_files, dir_count: collapsed_dirs, depth: rec.depth + 1, is_hidden: false, is_synthetic: true, access_status: AccessStatus::Ok, dominant_category: FileCategory::Other, mtime_ns: rec.max_subtree_mtime_ns, children: Vec::new(), }); } } TreeNode { path: rec.path.clone(), name: rec.name.clone(), bytes: total_bytes, physical_bytes: rec.subtree_physical_bytes, logical_bytes: rec.subtree_logical_bytes, file_count: rec.subtree_file_count, dir_count: rec.subtree_dir_count, depth: rec.depth, is_hidden: rec.is_hidden, is_synthetic: false, access_status: rec.access_status, dominant_category: dominant_category(rec.subtree_categories_for(metric)), mtime_ns: rec.max_subtree_mtime_ns, children, } } fn find_bloat_hints( conn: &Connection, scope_path: &str, metric: SizeMetric, ) -> Result, CacheError> { let order_col = match metric { SizeMetric::Physical => "subtree_physical_bytes", SizeMetric::Logical => "subtree_logical_bytes", }; let (lower, upper) = subtree_bounds(scope_path); let sql = if scope_path.is_empty() { format!( "SELECT path, name, subtree_physical_bytes, subtree_logical_bytes FROM directories WHERE name IN ('target', 'node_modules', '.venv', 'DerivedData', 'Caches', '.cache', 'ollama', 'huggingface') AND {order_col} >= 1048576 ORDER BY {order_col} DESC LIMIT 12" ) } else { format!( "SELECT path, name, subtree_physical_bytes, subtree_logical_bytes FROM directories WHERE (path = ?1 OR (path >= ?2 AND path < ?3)) AND name IN ('target', 'node_modules', '.venv', 'DerivedData', 'Caches', '.cache', 'ollama', 'huggingface') AND {order_col} >= 1048576 ORDER BY {order_col} DESC LIMIT 12" ) }; let mut stmt = conn.prepare(&sql)?; let mapper = |r: &rusqlite::Row<'_>| -> rusqlite::Result { let name: String = r.get(1)?; let kind = match name.as_str() { "target" | "node_modules" | ".venv" | "DerivedData" => "build_artifact", "ollama" | "huggingface" => "model_cache", _ => "cache", }; Ok(BloatHint { path: r.get(0)?, name, kind: kind.to_string(), physical_bytes: r.get::<_, i64>(2)? as u64, logical_bytes: r.get::<_, i64>(3)? as u64, }) }; let rows = if scope_path.is_empty() { stmt.query_map([], mapper)?.collect::, _>>()? } else { stmt.query_map(params![scope_path, lower, upper], mapper)? .collect::, _>>()? }; Ok(rows) } /// Return the category with the maximum byte count in `hist`. #[must_use] pub fn dominant_category(hist: &CategoryHistogram) -> FileCategory { let mut best = FileCategory::Other; let mut best_val = 0_u64; for cat in FileCategory::ALL { let v = hist.get(cat); if v > best_val { best_val = v; best = cat; } } best } fn dominant_age_bucket(hist: &AgeHistogram) -> AgeBucket { let pairs = [ (AgeBucket::Lt24h, hist.lt_24h), (AgeBucket::Days1To7, hist.days_1_7), (AgeBucket::Days7To30, hist.days_7_30), (AgeBucket::Days30To90, hist.days_30_90), (AgeBucket::Days90To1y, hist.days_90_1y), (AgeBucket::Years1To3, hist.years_1_3), (AgeBucket::Gt3y, hist.gt_3y), ]; pairs .into_iter() .max_by_key(|&(_, v)| v) .map_or(AgeBucket::Lt24h, |(b, _)| b) } /// Convert a 1D Hilbert distance `dist` in `[0, grid_size * grid_size)` to 2D coordinates `(x, y)`. #[must_use] pub fn hilbert_d2xy(grid_size: u32, mut dist: u32) -> (u32, u32) { let mut coord_x = 0_u32; let mut coord_y = 0_u32; let mut step = 1_u32; while step < grid_size { let rx = 1 & (dist / 2); let ry = 1 & (dist ^ rx); if ry == 0 { if rx == 1 { coord_x = step - 1 - coord_x; coord_y = step - 1 - coord_y; } std::mem::swap(&mut coord_x, &mut coord_y); } coord_x += step * rx; coord_y += step * ry; dist /= 4; step *= 2; } (coord_x, coord_y) } #[cfg(test)] #[allow(clippy::unwrap_used, clippy::expect_used)] mod tests { use super::*; use crate::scanner::{ApfsScanner, Scanner}; use proptest::prelude::*; use std::collections::HashMap; use std::fs; use tempfile::TempDir; fn assert_subtree_invariants(store: &CacheStore) { let conn = store.lock_read(); let mut stmt = conn.prepare("SELECT path FROM directories").unwrap(); let paths: Vec = stmt .query_map([], |r| r.get(0)) .unwrap() .collect::, _>>() .unwrap(); let mut by_path: HashMap = HashMap::new(); for p in &paths { by_path.insert(p.clone(), load_directory_conn(&conn, p).unwrap().unwrap()); } for (p, rec) in &by_path { let children: Vec<&DirectoryRecord> = by_path .values() .filter(|c| c.parent_path.as_deref() == Some(p.as_str())) .collect(); let expected_phys = rec.direct_physical_bytes + children .iter() .map(|c| c.subtree_physical_bytes) .sum::(); let expected_log = rec.direct_logical_bytes + children .iter() .map(|c| c.subtree_logical_bytes) .sum::(); assert_eq!(rec.subtree_physical_bytes, expected_phys, "path={p}"); assert_eq!(rec.subtree_logical_bytes, expected_log, "path={p}"); } } #[test] fn full_scan_and_projections_preserve_totals() { let tmp = TempDir::new().unwrap(); fs::create_dir_all(tmp.path().join("Projects/app")).unwrap(); fs::create_dir_all(tmp.path().join("Documents")).unwrap(); fs::write(tmp.path().join("Projects/app/main.rs"), vec![b'a'; 8192]).unwrap(); fs::write(tmp.path().join("Documents/spec.pdf"), vec![b'b'; 65_536]).unwrap(); let scanner = ApfsScanner::new(); let scan = scanner.scan_full(tmp.path(), &|_| {}).unwrap(); let store = CacheStore::open_in_memory().unwrap(); store.replace_full_scan(&scan, tmp.path(), 10, 20).unwrap(); assert_subtree_invariants(&store); let root_rec = store .get_directory_record(&RelPath::root()) .unwrap() .unwrap(); let hilbert = store .get_hilbert( &RelPath::root(), 5, HilbertColorBy::Category, SizeMetric::Logical, ) .unwrap() .unwrap(); let cell_sum: u64 = hilbert.cells.iter().map(|c| c.bytes).sum(); assert_eq!(cell_sum, root_rec.subtree_logical_bytes); let sankey = store .get_sankey(&RelPath::root(), SizeMetric::Logical) .unwrap() .unwrap(); let col0_to_col1: u64 = sankey .links .iter() .filter(|l| l.source == "root") .map(|l| l.bytes) .sum(); assert_eq!(col0_to_col1, root_rec.subtree_logical_bytes); let hits = store.search("spec", &RelPath::root(), 10).unwrap(); assert!(hits.iter().any(|h| h.name == "spec.pdf")); } proptest! { #[test] fn proptest_delta_propagation_keeps_subtree_sums_exact( ops in prop::collection::vec((0_usize..3, 0_u64..50_000), 1..20) ) { let tmp = TempDir::new().unwrap(); let dirs = ["a", "a/b", "c"]; for d in &dirs { fs::create_dir_all(tmp.path().join(d)).unwrap(); } let scanner = ApfsScanner::new(); let initial = scanner.scan_full(tmp.path(), &|_| {}).unwrap(); let store = CacheStore::open_in_memory().unwrap(); store.replace_full_scan(&initial, tmp.path(), 1, 2).unwrap(); for (idx, (dir_idx, size)) in ops.into_iter().enumerate() { let rel_str = dirs[dir_idx]; let rel = RelPath::parse(rel_str).unwrap(); let file_path = tmp.path().join(rel_str).join(format!("f_{}.bin", idx % 4)); if size == 0 { let _ = fs::remove_file(&file_path); } else { fs::write(&file_path, vec![b'z'; size as usize]).unwrap(); } let direct = scanner.scan_directory_direct(tmp.path(), &rel).unwrap(); store.apply_directory_delta(&rel, &direct).unwrap(); assert_subtree_invariants(&store); } } } #[test] fn wal_reader_does_not_block_during_active_write_transaction() { let tmp = TempDir::new().unwrap(); let db_path = tmp.path().join("cache.sqlite3"); fs::create_dir_all(tmp.path().join("Projects")).unwrap(); fs::write(tmp.path().join("Projects/a.rs"), vec![b'a'; 4096]).unwrap(); let store = CacheStore::open(&db_path).unwrap(); let scan = ApfsScanner::new().scan_full(tmp.path(), &|_| {}).unwrap(); store.replace_full_scan(&scan, tmp.path(), 1, 2).unwrap(); // Hold an active write transaction on write_conn let mut write_guard = store.lock_write(); let tx = write_guard .transaction_with_behavior(rusqlite::TransactionBehavior::Immediate) .unwrap(); tx.execute("DELETE FROM top_files", []).unwrap(); // Reader must still return the committed snapshot immediately without blocking let tree = store .get_tree(&RelPath::root(), 2, SizeMetric::Physical, true) .unwrap(); assert!(tree.is_some()); let dir = store .get_directory(&RelPath::root(), DirectorySort::Size, SizeMetric::Physical) .unwrap(); assert!(dir.is_some()); tx.rollback().unwrap(); } #[test] fn like_wildcards_and_case_do_not_corrupt_sibling_subtrees() { let tmp = TempDir::new().unwrap(); fs::create_dir_all(tmp.path().join("my_app/sub")).unwrap(); fs::create_dir_all(tmp.path().join("myXapp/sub")).unwrap(); fs::write(tmp.path().join("my_app/sub/a.bin"), vec![b'a'; 4096]).unwrap(); fs::write(tmp.path().join("myXapp/sub/b.bin"), vec![b'b'; 8192]).unwrap(); let scan = ApfsScanner::new().scan_full(tmp.path(), &|_| {}).unwrap(); let store = CacheStore::open_in_memory().unwrap(); store.replace_full_scan(&scan, tmp.path(), 1, 2).unwrap(); // Removing `my_app` must NOT remove `myXapp` store .remove_subtree(&RelPath::parse("my_app").unwrap()) .unwrap(); assert!( store .get_directory_record(&RelPath::parse("my_app").unwrap()) .unwrap() .is_none() ); assert!( store .get_directory_record(&RelPath::parse("myXapp/sub").unwrap()) .unwrap() .is_some() ); assert_subtree_invariants(&store); // Searching `_` must not match `myXapp` let hits = store.search("_", &RelPath::root(), 20).unwrap(); assert!(!hits.iter().any(|h| h.path.contains("myXapp"))); } #[test] fn apply_directory_delta_prunes_disappeared_child_and_preserves_totals() { let tmp = TempDir::new().unwrap(); fs::create_dir_all(tmp.path().join("Parent/Child")).unwrap(); fs::write(tmp.path().join("Parent/Child/data.bin"), vec![b'x'; 8192]).unwrap(); let scanner = ApfsScanner::new(); let scan = scanner.scan_full(tmp.path(), &|_| {}).unwrap(); let store = CacheStore::open_in_memory().unwrap(); store.replace_full_scan(&scan, tmp.path(), 1, 2).unwrap(); fs::remove_dir_all(tmp.path().join("Parent/Child")).unwrap(); let parent_rel = RelPath::parse("Parent").unwrap(); let direct = scanner .scan_directory_direct(tmp.path(), &parent_rel) .unwrap(); store.apply_directory_delta(&parent_rel, &direct).unwrap(); assert!( store .get_directory_record(&RelPath::parse("Parent/Child").unwrap()) .unwrap() .is_none() ); assert_subtree_invariants(&store); } #[test] fn open_read_only_reads_committed_cache() { let tmp = TempDir::new().unwrap(); let db_path = tmp.path().join("cache.sqlite3"); fs::write(tmp.path().join("a.txt"), vec![b'a'; 4096]).unwrap(); let store = CacheStore::open(&db_path).unwrap(); let scan = ApfsScanner::new().scan_full(tmp.path(), &|_| {}).unwrap(); store.replace_full_scan(&scan, tmp.path(), 1, 2).unwrap(); drop(store); let ro = CacheStore::open_read_only(&db_path).unwrap(); let meta = ro.meta().unwrap(); assert_eq!(meta.last_full_scan_completed_ns, 2); } #[test] fn full_scan_truncates_wal_and_reclaims_freelist_pages() { let tmp = TempDir::new().unwrap(); let db_path = tmp.path().join("cache.sqlite3"); let root = tmp.path().join("home"); fs::create_dir_all(root.join("big")).unwrap(); for i in 0..40 { fs::write(root.join(format!("big/file_{i}.bin")), vec![b'x'; 2048]).unwrap(); } let scanner = ApfsScanner::new(); let store = CacheStore::open(&db_path).unwrap(); let scan1 = scanner.scan_full(&root, &|_| {}).unwrap(); store.replace_full_scan(&scan1, &root, 1, 2).unwrap(); // Shrink the tree significantly and re-run full scan fs::remove_dir_all(root.join("big")).unwrap(); fs::write(root.join("small.txt"), b"hi").unwrap(); let scan2 = scanner.scan_full(&root, &|_| {}).unwrap(); store.replace_full_scan(&scan2, &root, 3, 4).unwrap(); let wal_path = db_path.with_extension("sqlite3-wal"); let wal_len = wal_path.metadata().map_or(0, |m| m.len()); assert_eq!(wal_len, 0, "expected -wal to be truncated to 0 bytes"); let conn = store.lock_write(); let auto_vacuum: i64 = conn .query_row("PRAGMA auto_vacuum", [], |r| r.get(0)) .unwrap(); let freelist_count: i64 = conn .query_row("PRAGMA freelist_count", [], |r| r.get(0)) .unwrap(); assert_eq!(auto_vacuum, 2, "expected INCREMENTAL auto_vacuum (2)"); assert_eq!(freelist_count, 0, "expected 0 freelist pages after vacuum"); } #[test] fn schema_v3_normalizes_paths_and_drops_redundant_indexes() { let store = CacheStore::open_in_memory().unwrap(); let conn = store.lock_read(); let dir_cols: Vec = conn .prepare("PRAGMA table_info(directories)") .unwrap() .query_map([], |r| r.get(1)) .unwrap() .collect::>() .unwrap(); assert!(dir_cols.contains(&"id".to_string())); assert!(dir_cols.contains(&"parent_id".to_string())); assert!(!dir_cols.contains(&"parent_path".to_string())); let file_cols: Vec = conn .prepare("PRAGMA table_info(top_files)") .unwrap() .query_map([], |r| r.get(1)) .unwrap() .collect::>() .unwrap(); assert!(file_cols.contains(&"dir_id".to_string())); assert!(!file_cols.contains(&"path".to_string())); assert!(!file_cols.contains(&"dir_path".to_string())); let indexes: Vec = conn .prepare("SELECT name FROM sqlite_master WHERE type = 'index'") .unwrap() .query_map([], |r| r.get(0)) .unwrap() .collect::>() .unwrap(); assert!(!indexes.contains(&"idx_directories_depth".to_string())); assert!(!indexes.contains(&"idx_directories_name".to_string())); assert!(!indexes.contains(&"idx_top_files_dir".to_string())); assert!(indexes.contains(&"idx_directories_bloat".to_string())); assert!(indexes.contains(&"idx_directories_parent_id".to_string())); } }