Skip to main content

sqlite_graphrag/commands/
purge.rs

1//! Handler for the `purge` CLI subcommand.
2
3use crate::errors::AppError;
4use crate::i18n::errors_msg;
5use crate::output;
6use crate::paths::AppPaths;
7use crate::storage::connection::open_rw;
8use serde::Serialize;
9
10#[derive(clap::Args)]
11#[command(after_long_help = "EXAMPLES:\n  \
12    # Permanently delete soft-deleted memories older than 90 days (default retention)\n  \
13    sqlite-graphrag purge\n\n  \
14    # Custom retention window in days\n  \
15    sqlite-graphrag purge --retention-days 30\n\n  \
16    # Purge ALL soft-deleted memories regardless of age\n  \
17    sqlite-graphrag purge --retention-days 0\n\n  \
18    # Preview what would be purged without deleting\n  \
19    sqlite-graphrag purge --dry-run\n\n  \
20    # Purge a specific memory by name\n  \
21    sqlite-graphrag purge --name old-memory --namespace my-project\n\n\
22NOTES:\n  \
23    `--yes` only confirms intent and does NOT override `--retention-days`.\n  \
24    To wipe every soft-deleted memory immediately, pair `--yes` with `--retention-days 0`.")]
25pub struct PurgeArgs {
26    #[arg(long)]
27    pub name: Option<String>,
28    /// Namespace to purge. Defaults to the contextual namespace (SQLITE_GRAPHRAG_NAMESPACE env var or "global").
29    #[arg(long)]
30    pub namespace: Option<String>,
31    /// Retention days: memories with deleted_at older than (now - retention_days*86400) will be
32    /// permanently removed. Default: PURGE_RETENTION_DAYS_DEFAULT (90). Use 0 to purge all
33    /// soft-deleted memories regardless of age. Alias: `--max-age-days`.
34    #[arg(
35        long,
36        alias = "days",
37        alias = "max-age-days",
38        value_name = "DAYS",
39        default_value_t = crate::constants::PURGE_RETENTION_DAYS_DEFAULT
40    )]
41    pub retention_days: u32,
42    /// [DEPRECATED in v2.0.0] Legacy alias — use --retention-days instead.
43    #[arg(long, hide = true)]
44    pub older_than_seconds: Option<u64>,
45    /// Does not execute DELETE: computes and reports what WOULD be purged.
46    #[arg(long, default_value_t = false)]
47    pub dry_run: bool,
48    /// Confirms destructive intent for tools that require explicit acknowledgement.
49    /// Does NOT override `--retention-days`: combine with `--retention-days 0` to wipe
50    /// every soft-deleted memory regardless of age.
51    #[arg(long, default_value_t = false)]
52    pub yes: bool,
53    #[arg(long, hide = true, help = "No-op; JSON is always emitted on stdout")]
54    pub json: bool,
55    #[arg(long, env = "SQLITE_GRAPHRAG_DB_PATH")]
56    pub db: Option<String>,
57}
58
59#[derive(Serialize)]
60pub struct PurgeResponse {
61    pub purged_count: usize,
62    pub bytes_freed: i64,
63    pub oldest_deleted_at: Option<i64>,
64    pub retention_days_used: u32,
65    pub dry_run: bool,
66    pub namespace: Option<String>,
67    pub cutoff_epoch: i64,
68    pub warnings: Vec<String>,
69    /// Total execution time in milliseconds from handler start to serialisation.
70    pub elapsed_ms: u64,
71    /// Human-readable explanation surfaced when nothing was purged so callers
72    /// understand the retention semantics. Present only when
73    /// `purged_count == 0` (M2 in v1.0.32) — kept absent otherwise to preserve
74    /// the existing JSON contract.
75    #[serde(skip_serializing_if = "Option::is_none")]
76    pub message: Option<String>,
77}
78
79/// Permanently delete soft-deleted memories that have exceeded the retention window.
80///
81/// Only memories with `deleted_at IS NOT NULL AND deleted_at <= cutoff_epoch` are affected.
82/// When `--dry-run` is set the DELETE is skipped and the response reflects candidates only.
83pub fn run(args: PurgeArgs) -> Result<(), AppError> {
84    let inicio = std::time::Instant::now();
85    let namespace = crate::namespace::resolve_namespace(args.namespace.as_deref())?;
86    let paths = AppPaths::resolve(args.db.as_deref())?;
87
88    crate::storage::connection::ensure_db_ready(&paths)?;
89
90    let mut warnings: Vec<String> = Vec::new();
91    let now = current_epoch()?;
92
93    let cutoff_epoch = if let Some(secs) = args.older_than_seconds {
94        warnings.push(
95            "--older-than-seconds is deprecated; use --retention-days in v2.0.0+".to_string(),
96        );
97        now - secs as i64
98    } else {
99        now - (args.retention_days as i64) * 86_400
100    };
101
102    let namespace_opt: Option<&str> = Some(namespace.as_str());
103
104    let mut conn = open_rw(&paths.db)?;
105
106    let (bytes_freed, oldest_deleted_at, candidates_count) =
107        compute_metrics(&conn, cutoff_epoch, namespace_opt, args.name.as_deref())?;
108
109    if candidates_count == 0 && args.name.is_some() {
110        return Err(AppError::NotFound(
111            errors_msg::soft_deleted_memory_not_found(
112                args.name.as_deref().unwrap_or_default(),
113                &namespace,
114            ),
115        ));
116    }
117
118    if !args.dry_run {
119        let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
120        execute_purge(
121            &tx,
122            &namespace,
123            args.name.as_deref(),
124            cutoff_epoch,
125            &mut warnings,
126        )?;
127        tx.commit()?;
128    }
129
130    let message = if candidates_count == 0 {
131        Some(format!(
132            "no soft-deleted memories older than {retention_days} day(s); use --retention-days 0 to purge all soft-deleted memories regardless of age",
133            retention_days = args.retention_days
134        ))
135    } else {
136        None
137    };
138
139    output::emit_json(&PurgeResponse {
140        purged_count: candidates_count,
141        bytes_freed,
142        oldest_deleted_at,
143        retention_days_used: args.retention_days,
144        dry_run: args.dry_run,
145        namespace: Some(namespace),
146        cutoff_epoch,
147        warnings,
148        elapsed_ms: inicio.elapsed().as_millis() as u64,
149        message,
150    })?;
151
152    Ok(())
153}
154
155fn current_epoch() -> Result<i64, AppError> {
156    let now = std::time::SystemTime::now()
157        .duration_since(std::time::UNIX_EPOCH)
158        .map_err(|err| AppError::Internal(anyhow::anyhow!("system clock error: {err}")))?;
159    Ok(now.as_secs() as i64)
160}
161
162fn compute_metrics(
163    conn: &rusqlite::Connection,
164    cutoff_epoch: i64,
165    namespace_opt: Option<&str>,
166    name: Option<&str>,
167) -> Result<(i64, Option<i64>, usize), AppError> {
168    let (bytes_freed, oldest_deleted_at): (i64, Option<i64>) = if let Some(name) = name {
169        conn.query_row(
170            "SELECT COALESCE(SUM(LENGTH(COALESCE(body,'')) + LENGTH(COALESCE(description,'')) + LENGTH(name)), 0),
171                    MIN(deleted_at)
172             FROM memories
173             WHERE deleted_at IS NOT NULL AND deleted_at <= ?1
174                   AND (?2 IS NULL OR namespace = ?2)
175                   AND name = ?3",
176            rusqlite::params![cutoff_epoch, namespace_opt, name],
177            |r| Ok((r.get::<_, i64>(0)?, r.get::<_, Option<i64>>(1)?)),
178        )?
179    } else {
180        conn.query_row(
181            "SELECT COALESCE(SUM(LENGTH(COALESCE(body,'')) + LENGTH(COALESCE(description,'')) + LENGTH(name)), 0),
182                    MIN(deleted_at)
183             FROM memories
184             WHERE deleted_at IS NOT NULL AND deleted_at <= ?1
185                   AND (?2 IS NULL OR namespace = ?2)",
186            rusqlite::params![cutoff_epoch, namespace_opt],
187            |r| Ok((r.get::<_, i64>(0)?, r.get::<_, Option<i64>>(1)?)),
188        )?
189    };
190
191    let count: usize = if let Some(name) = name {
192        conn.query_row(
193            "SELECT COUNT(*) FROM memories
194             WHERE deleted_at IS NOT NULL AND deleted_at <= ?1
195                   AND (?2 IS NULL OR namespace = ?2)
196                   AND name = ?3",
197            rusqlite::params![cutoff_epoch, namespace_opt, name],
198            |r| r.get::<_, usize>(0),
199        )?
200    } else {
201        conn.query_row(
202            "SELECT COUNT(*) FROM memories
203             WHERE deleted_at IS NOT NULL AND deleted_at <= ?1
204                   AND (?2 IS NULL OR namespace = ?2)",
205            rusqlite::params![cutoff_epoch, namespace_opt],
206            |r| r.get::<_, usize>(0),
207        )?
208    };
209
210    Ok((bytes_freed, oldest_deleted_at, count))
211}
212
213fn execute_purge(
214    tx: &rusqlite::Transaction,
215    namespace: &str,
216    name: Option<&str>,
217    cutoff_epoch: i64,
218    warnings: &mut Vec<String>,
219) -> Result<(), AppError> {
220    let candidates = select_candidates(tx, namespace, name, cutoff_epoch)?;
221
222    for (memory_id, _name) in &candidates {
223        if let Err(err) = tx.execute(
224            "DELETE FROM vec_chunks WHERE memory_id = ?1",
225            rusqlite::params![memory_id],
226        ) {
227            warnings.push(format!(
228                "failed to clean vec_chunks for memory_id {memory_id}: {err}"
229            ));
230        }
231        if let Err(err) = tx.execute(
232            "DELETE FROM vec_memories WHERE memory_id = ?1",
233            rusqlite::params![memory_id],
234        ) {
235            warnings.push(format!(
236                "failed to clean vec_memories for memory_id {memory_id}: {err}"
237            ));
238        }
239        tx.execute(
240            "DELETE FROM memories WHERE id = ?1 AND namespace = ?2 AND deleted_at IS NOT NULL",
241            rusqlite::params![memory_id, namespace],
242        )?;
243    }
244
245    Ok(())
246}
247
248fn select_candidates(
249    conn: &rusqlite::Connection,
250    namespace: &str,
251    name: Option<&str>,
252    cutoff_epoch: i64,
253) -> Result<Vec<(i64, String)>, AppError> {
254    let query = if name.is_some() {
255        "SELECT id, name FROM memories
256         WHERE namespace = ?1 AND name = ?2 AND deleted_at IS NOT NULL AND deleted_at <= ?3
257         ORDER BY deleted_at ASC"
258    } else {
259        "SELECT id, name FROM memories
260         WHERE namespace = ?1 AND deleted_at IS NOT NULL AND deleted_at <= ?2
261         ORDER BY deleted_at ASC"
262    };
263
264    let mut stmt = conn.prepare(query)?;
265    let rows = if let Some(name) = name {
266        stmt.query_map(rusqlite::params![namespace, name, cutoff_epoch], |row| {
267            Ok((row.get::<_, i64>(0)?, row.get::<_, String>(1)?))
268        })?
269        .collect::<Result<Vec<_>, _>>()?
270    } else {
271        stmt.query_map(rusqlite::params![namespace, cutoff_epoch], |row| {
272            Ok((row.get::<_, i64>(0)?, row.get::<_, String>(1)?))
273        })?
274        .collect::<Result<Vec<_>, _>>()?
275    };
276    Ok(rows)
277}
278
279#[cfg(test)]
280mod tests {
281    use super::*;
282    use rusqlite::Connection;
283
284    fn setup_test_db() -> Connection {
285        let conn = Connection::open_in_memory().expect("failed to open in-memory db");
286        conn.execute_batch(
287            "CREATE TABLE memories (
288                id INTEGER PRIMARY KEY AUTOINCREMENT,
289                name TEXT NOT NULL,
290                namespace TEXT NOT NULL DEFAULT 'global',
291                description TEXT,
292                body TEXT,
293                deleted_at INTEGER
294            );
295            CREATE TABLE IF NOT EXISTS vec_chunks (memory_id INTEGER);
296            CREATE TABLE IF NOT EXISTS vec_memories (memory_id INTEGER);",
297        )
298        .expect("failed to create test tables");
299        conn
300    }
301
302    fn insert_deleted_memory(
303        conn: &Connection,
304        name: &str,
305        namespace: &str,
306        body: &str,
307        deleted_at: i64,
308    ) -> i64 {
309        conn.execute(
310            "INSERT INTO memories (name, namespace, body, deleted_at) VALUES (?1, ?2, ?3, ?4)",
311            rusqlite::params![name, namespace, body, deleted_at],
312        )
313        .expect("failed to insert test memory");
314        conn.last_insert_rowid()
315    }
316
317    #[test]
318    fn retention_days_used_default_is_90() {
319        assert_eq!(crate::constants::PURGE_RETENTION_DAYS_DEFAULT, 90u32);
320    }
321
322    #[test]
323    fn compute_metrics_bytes_freed_positive_for_populated_body() {
324        let conn = setup_test_db();
325        let now = current_epoch().expect("epoch failed");
326        let old_epoch = now - 100 * 86_400;
327        insert_deleted_memory(&conn, "mem-test", "global", "memory body", old_epoch);
328
329        let cutoff = now - 30 * 86_400;
330        let (bytes, oldest, count) =
331            compute_metrics(&conn, cutoff, Some("global"), None).expect("compute_metrics failed");
332
333        assert!(bytes > 0, "bytes_freed must be > 0 for populated body");
334        assert!(oldest.is_some(), "oldest_deleted_at must be Some");
335        assert_eq!(count, 1);
336    }
337
338    #[test]
339    fn compute_metrics_returns_zero_without_candidates() {
340        let conn = setup_test_db();
341        let now = current_epoch().expect("epoch failed");
342        let cutoff = now - 90 * 86_400;
343
344        let (bytes, oldest, count) =
345            compute_metrics(&conn, cutoff, Some("global"), None).expect("compute_metrics failed");
346
347        assert_eq!(bytes, 0);
348        assert!(oldest.is_none());
349        assert_eq!(count, 0);
350    }
351
352    #[test]
353    fn dry_run_does_not_delete_records() {
354        let conn = setup_test_db();
355        let now = current_epoch().expect("epoch failed");
356        let old_epoch = now - 200 * 86_400;
357        insert_deleted_memory(&conn, "mem-dry", "global", "dry run content", old_epoch);
358
359        let cutoff = now - 30 * 86_400;
360        let (_, _, count_before) =
361            compute_metrics(&conn, cutoff, Some("global"), None).expect("compute_metrics failed");
362        assert_eq!(count_before, 1, "must have 1 candidate before dry run");
363
364        let (_, _, count_after) =
365            compute_metrics(&conn, cutoff, Some("global"), None).expect("compute_metrics failed");
366        assert_eq!(
367            count_after, 1,
368            "dry_run must not remove records: count must remain 1"
369        );
370    }
371
372    #[test]
373    fn oldest_deleted_at_returns_smallest_epoch() {
374        let conn = setup_test_db();
375        let now = current_epoch().expect("epoch failed");
376        let epoch_old = now - 300 * 86_400;
377        let epoch_recent = now - 200 * 86_400;
378
379        insert_deleted_memory(&conn, "mem-a", "global", "body-a", epoch_old);
380        insert_deleted_memory(&conn, "mem-b", "global", "body-b", epoch_recent);
381
382        let cutoff = now - 30 * 86_400;
383        let (_, oldest, count) =
384            compute_metrics(&conn, cutoff, Some("global"), None).expect("compute_metrics failed");
385
386        assert_eq!(count, 2);
387        assert_eq!(
388            oldest,
389            Some(epoch_old),
390            "oldest_deleted_at must be the oldest epoch"
391        );
392    }
393
394    #[test]
395    fn purge_args_namespace_accepts_none_without_default() {
396        // P1-C: namespace must be None when not provided, allowing resolve_namespace
397        // to consult SQLITE_GRAPHRAG_NAMESPACE before falling back to "global".
398        // The field was `default_value = "global"` before P1-C; with that removed,
399        // resolve_namespace(None) consults the env var correctly.
400        let resolved = crate::namespace::resolve_namespace(None)
401            .expect("resolve_namespace(None) must return Ok");
402        assert_eq!(
403            resolved, "global",
404            "without env var, resolve_namespace(None) must fall back to 'global'"
405        );
406    }
407
408    #[test]
409    fn purge_response_serializes_all_new_fields() {
410        let resp = PurgeResponse {
411            purged_count: 3,
412            bytes_freed: 1024,
413            oldest_deleted_at: Some(1_700_000_000),
414            retention_days_used: 90,
415            dry_run: false,
416            namespace: Some("global".to_string()),
417            cutoff_epoch: 1_710_000_000,
418            warnings: vec![],
419            elapsed_ms: 42,
420            message: None,
421        };
422        let json = serde_json::to_string(&resp).expect("serialization failed");
423        assert!(json.contains("bytes_freed"));
424        assert!(json.contains("oldest_deleted_at"));
425        assert!(json.contains("retention_days_used"));
426        assert!(json.contains("dry_run"));
427        assert!(json.contains("elapsed_ms"));
428        // M2: when no purge happened, `message` is omitted to keep payloads stable.
429        assert!(!json.contains("\"message\""));
430    }
431
432    #[test]
433    fn purge_response_serializes_message_when_present() {
434        // M2 (v1.0.32): zero purges include a human-readable hint message.
435        let resp = PurgeResponse {
436            purged_count: 0,
437            bytes_freed: 0,
438            oldest_deleted_at: None,
439            retention_days_used: 90,
440            dry_run: false,
441            namespace: Some("global".to_string()),
442            cutoff_epoch: 1_710_000_000,
443            warnings: vec![],
444            elapsed_ms: 5,
445            message: Some(
446                "no soft-deleted memories older than 90 day(s); use --retention-days 0 to purge all soft-deleted memories regardless of age"
447                    .to_string(),
448            ),
449        };
450        let json = serde_json::to_string(&resp).expect("serialization failed");
451        assert!(json.contains("\"message\""));
452        assert!(json.contains("--retention-days 0"));
453    }
454}