Skip to main content

orbok_workers/
recovery.rs

1//! Crash recovery (RFC-018): detects and repairs interrupted state
2//! left by a previous session that terminated abnormally.
3//!
4//! Called at startup before any work begins. All repairs are non-destructive:
5//! running jobs are reset to queued (not deleted), and the previous active
6//! index is preserved (RFC-006 §12 replace-on-success guarantee).
7
8use orbok_core::{OrbokResult, now_iso8601};
9use orbok_db::Catalog;
10use std::path::Path;
11
12/// Results of the startup recovery scan (RFC-018 §16 requirements).
13#[derive(Debug, Default)]
14pub struct RecoveryReport {
15    /// Jobs that were `running` and reset to `queued`.
16    pub jobs_reset: u64,
17    /// Jobs already `queued` from a prior session (still pending).
18    pub jobs_pending: u64,
19    /// Whether the cache DB was missing and recreated (empty).
20    pub cache_recreated: bool,
21    /// Whether the cache DB was detected as corrupt and rebuilt.
22    pub cache_rebuilt: bool,
23}
24
25/// Run all startup recovery steps.
26///
27/// Must be called before any worker processes jobs or any search is run.
28pub fn run_startup_recovery(
29    catalog: &Catalog,
30    cache_db_path: &Path,
31) -> OrbokResult<RecoveryReport> {
32    let mut report = RecoveryReport::default();
33    report.jobs_reset = reset_interrupted_jobs(catalog)?;
34    report.jobs_pending = count_pending_jobs(catalog)?;
35    let cache_status = ensure_cache_db(cache_db_path)?;
36    report.cache_recreated = cache_status == CacheDbStatus::Recreated;
37    report.cache_rebuilt = cache_status == CacheDbStatus::Rebuilt;
38    if report.jobs_reset > 0 {
39        tracing::warn!(
40            reset = report.jobs_reset,
41            "reset interrupted jobs to queued on startup"
42        );
43    }
44    Ok(report)
45}
46
47/// RFC-018 §16 test 1: any job left in `running` state from a previous
48/// session is reset to `queued` so workers will retry it.
49fn reset_interrupted_jobs(catalog: &Catalog) -> OrbokResult<u64> {
50    let conn = catalog.lock();
51    let n = conn
52        .execute(
53            "UPDATE index_jobs SET status = 'queued', updated_at = ?1 WHERE status = 'running'",
54            rusqlite::params![now_iso8601()],
55        )
56        .map_err(|e| orbok_core::OrbokError::Database(e.to_string()))?;
57    Ok(n as u64)
58}
59
60fn count_pending_jobs(catalog: &Catalog) -> OrbokResult<u64> {
61    let conn = catalog.lock();
62    let n: i64 = conn
63        .query_row(
64            "SELECT COUNT(*) FROM index_jobs WHERE status = 'queued'",
65            [],
66            |r| r.get(0),
67        )
68        .map_err(|e| orbok_core::OrbokError::Database(e.to_string()))?;
69    Ok(n as u64)
70}
71
72#[derive(PartialEq)]
73enum CacheDbStatus {
74    Ok,
75    Recreated,
76    Rebuilt,
77}
78
79/// RFC-018 §16 test 3/4: ensure the cache DB is accessible.
80/// Missing → recreate empty. Corrupt → back up and recreate.
81fn ensure_cache_db(path: &Path) -> OrbokResult<CacheDbStatus> {
82    if !path.exists() {
83        // Missing: localcache will create it on first open; nothing to do.
84        return Ok(CacheDbStatus::Recreated);
85    }
86    // Integrity probe: open and run `PRAGMA integrity_check`.
87    match rusqlite::Connection::open(path) {
88        Ok(conn) => {
89            let result: String = conn
90                .query_row("PRAGMA integrity_check", [], |r| r.get(0))
91                .unwrap_or_else(|_| "error".to_string());
92            if result != "ok" {
93                tracing::error!(path = %path.display(), "cache DB corrupt — backing up and removing");
94                let backup = path.with_extension("sqlite3.corrupt-backup");
95                let _ = std::fs::rename(path, &backup);
96                return Ok(CacheDbStatus::Rebuilt);
97            }
98        }
99        Err(e) => {
100            tracing::error!(path = %path.display(), error = %e, "cache DB unreadable");
101            let backup = path.with_extension("sqlite3.corrupt-backup");
102            let _ = std::fs::rename(path, &backup);
103            return Ok(CacheDbStatus::Rebuilt);
104        }
105    }
106    Ok(CacheDbStatus::Ok)
107}
108
109/// Catalog integrity report (RFC-018 §16 test 7).
110#[derive(Debug, Default)]
111pub struct IntegrityReport {
112    /// Chunks whose parent chunk no longer exists.
113    pub orphaned_child_chunks: u64,
114    /// Keyword index records without a matching chunk.
115    pub orphaned_kw_records: u64,
116    /// Embedding records without a matching chunk.
117    pub orphaned_embedding_records: u64,
118    /// Files without a parent source.
119    pub orphaned_files: u64,
120}
121
122impl IntegrityReport {
123    pub fn is_clean(&self) -> bool {
124        self.orphaned_child_chunks == 0
125            && self.orphaned_kw_records == 0
126            && self.orphaned_embedding_records == 0
127            && self.orphaned_files == 0
128    }
129}
130
131/// Run catalog integrity checks (RFC-018 §16 test 7).
132/// Read-only — does not repair, only reports.
133pub fn check_catalog_integrity(catalog: &Catalog) -> OrbokResult<IntegrityReport> {
134    let conn = catalog.lock();
135    let mut report = IntegrityReport::default();
136    let q = |sql: &str| -> OrbokResult<u64> {
137        let n: i64 = conn
138            .query_row(sql, [], |r| r.get(0))
139            .map_err(|e| orbok_core::OrbokError::Database(e.to_string()))?;
140        Ok(n as u64)
141    };
142    report.orphaned_child_chunks = q("SELECT COUNT(*) FROM chunks c \
143         WHERE c.parent_chunk_id IS NOT NULL \
144         AND NOT EXISTS (SELECT 1 FROM chunks p WHERE p.chunk_id = c.parent_chunk_id)")?;
145    report.orphaned_kw_records = q("SELECT COUNT(*) FROM keyword_index_records k \
146         WHERE NOT EXISTS (SELECT 1 FROM chunks c WHERE c.chunk_id = k.chunk_id)")?;
147    report.orphaned_embedding_records = q("SELECT COUNT(*) FROM embeddings e \
148         WHERE NOT EXISTS (SELECT 1 FROM chunks c WHERE c.chunk_id = e.chunk_id)")?;
149    report.orphaned_files = q("SELECT COUNT(*) FROM files f \
150         WHERE NOT EXISTS (SELECT 1 FROM sources s WHERE s.source_id = f.source_id)")?;
151    Ok(report)
152}