Skip to main content

lean_ctx_ext/core/
storage_maintenance.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Daemon-safe storage maintenance.
3//!
4//! Unlike the interactive `lean-ctx cache prune` (which prints per-file output),
5//! these routines are silent (tracing only) so they can run inside the MCP
6//! daemon without corrupting the stdio protocol. They enforce the disk budget
7//! that the field had been silently exceeding (see EPIC 6 / #2364): unbounded
8//! archive FTS growth and accumulated quarantined BM25 indexes.
9
10use std::path::PathBuf;
11
12/// Result of a quiet maintenance pass.
13#[derive(Debug, Default, Clone, Copy)]
14pub struct MaintenanceResult {
15    pub quarantined_removed: u32,
16    pub bytes_freed: u64,
17    pub archive_entries_pruned: u32,
18    pub archive_db_bytes_after: u64,
19}
20
21const QUARANTINED_FILES: &[&str] = &[
22    "bm25_index.json.quarantined",
23    "bm25_index.bin.quarantined",
24    "bm25_index.bin.zst.quarantined",
25];
26
27/// Remove accumulated quarantined BM25 index files. These are dead weight: an
28/// index is only quarantined when it failed a load/size check and was replaced.
29fn prune_quarantined_bm25() -> (u32, u64) {
30    let mut removed = 0u32;
31    let mut freed = 0u64;
32    let Ok(data_dir) = crate::core::data_dir::lean_ctx_data_dir() else {
33        return (removed, freed);
34    };
35    let vectors_dir = data_dir.join("vectors");
36    let Ok(entries) = std::fs::read_dir(&vectors_dir) else {
37        return (removed, freed);
38    };
39    for entry in entries.flatten() {
40        let dir = entry.path();
41        if !dir.is_dir() {
42            continue;
43        }
44        for q_name in QUARANTINED_FILES {
45            let q: PathBuf = dir.join(q_name);
46            if q.exists() {
47                if let Ok(meta) = std::fs::metadata(&q) {
48                    freed = freed.saturating_add(meta.len());
49                }
50                if std::fs::remove_file(&q).is_ok() {
51                    removed += 1;
52                }
53            }
54        }
55    }
56    (removed, freed)
57}
58
59/// Run a silent maintenance pass: prune quarantined BM25 indexes and enforce
60/// the archive FTS size cap. Safe to call from the MCP daemon.
61pub fn run_quiet() -> MaintenanceResult {
62    let (quarantined_removed, bytes_freed) = prune_quarantined_bm25();
63    // Enforce the archive TTL + on-disk size budget (prunes `.txt`/`.meta.json`
64    // + FTS rows together), then backstop the DB cap. Without this the archive
65    // grew unbounded on disk and exhausted host RAM via the page cache (#417).
66    let archive_entries_pruned = crate::core::archive::cleanup();
67    let archive_db_bytes_after = crate::core::archive_fts::enforce_cap();
68    if quarantined_removed > 0 || archive_entries_pruned > 0 {
69        tracing::info!(
70            "storage maintenance: pruned {quarantined_removed} quarantined BM25 index file(s) \
71             (freed {bytes_freed} bytes) + {archive_entries_pruned} archive entry/entries; \
72             archive DB now {archive_db_bytes_after} bytes"
73        );
74    }
75    MaintenanceResult {
76        quarantined_removed,
77        bytes_freed,
78        archive_entries_pruned,
79        archive_db_bytes_after,
80    }
81}
82
83#[cfg(test)]
84pub mod tests {
85    use super::*;
86
87    #[test]
88    fn prune_removes_quarantined_files() {
89        let _lock = crate::core::data_dir::test_env_lock();
90        let tmp = tempfile::tempdir().unwrap();
91        crate::test_env::set_var("LEAN_CTX_DATA_DIR", tmp.path());
92
93        let idx_dir = tmp.path().join("vectors").join("proj_abc");
94        std::fs::create_dir_all(&idx_dir).unwrap();
95        std::fs::write(idx_dir.join("bm25_index.json.quarantined"), b"dead").unwrap();
96        std::fs::write(idx_dir.join("bm25_index.bin"), b"live").unwrap();
97
98        let (removed, freed) = prune_quarantined_bm25();
99        assert_eq!(removed, 1);
100        assert!(freed >= 4);
101        assert!(!idx_dir.join("bm25_index.json.quarantined").exists());
102        assert!(
103            idx_dir.join("bm25_index.bin").exists(),
104            "live index must be preserved"
105        );
106
107        crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
108    }
109}