1use 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 #[arg(long)]
30 pub namespace: Option<String>,
31 #[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 #[arg(long, hide = true)]
44 pub older_than_seconds: Option<u64>,
45 #[arg(long, default_value_t = false)]
47 pub dry_run: bool,
48 #[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 action: String,
62 pub purged_count: usize,
63 pub bytes_freed: i64,
64 pub oldest_deleted_at: Option<i64>,
65 pub retention_days_used: u32,
66 pub dry_run: bool,
67 pub namespace: Option<String>,
68 pub cutoff_epoch: i64,
69 pub warnings: Vec<String>,
70 pub elapsed_ms: u64,
72 #[serde(skip_serializing_if = "Option::is_none")]
77 pub message: Option<String>,
78}
79
80pub fn run(args: PurgeArgs) -> Result<(), AppError> {
85 let inicio = std::time::Instant::now();
86 let namespace = crate::namespace::resolve_namespace(args.namespace.as_deref())?;
87 let paths = AppPaths::resolve(args.db.as_deref())?;
88
89 crate::storage::connection::ensure_db_ready(&paths)?;
90
91 let mut warnings: Vec<String> = Vec::with_capacity(1);
92 let now = current_epoch()?;
93
94 let cutoff_epoch = if let Some(secs) = args.older_than_seconds {
95 warnings.push(
96 "--older-than-seconds is deprecated; use --retention-days in v2.0.0+".to_string(),
97 );
98 now - secs as i64
99 } else {
100 now - (args.retention_days as i64) * 86_400
101 };
102
103 let namespace_opt: Option<&str> = Some(namespace.as_str());
104
105 let mut conn = open_rw(&paths.db)?;
106
107 let (bytes_freed, oldest_deleted_at, candidates_count) =
108 compute_metrics(&conn, cutoff_epoch, namespace_opt, args.name.as_deref())?;
109
110 if candidates_count == 0 && args.name.is_some() {
111 return Err(AppError::NotFound(
112 errors_msg::soft_deleted_memory_not_found(
113 args.name.as_deref().unwrap_or_default(),
114 &namespace,
115 ),
116 ));
117 }
118
119 if !args.dry_run && !args.yes {
120 return Err(AppError::Validation(
121 "destructive operation: pass --yes to confirm purge (use --dry-run to preview)".to_string(),
122 ));
123 }
124
125 if !args.dry_run {
126 let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
127 execute_purge(
128 &tx,
129 &namespace,
130 args.name.as_deref(),
131 cutoff_epoch,
132 &mut warnings,
133 )?;
134 tx.commit()?;
135 conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE);")?;
136 }
137
138 let message = if candidates_count == 0 {
139 Some(format!(
140 "no soft-deleted memories older than {retention_days} day(s); use --retention-days 0 to purge all soft-deleted memories regardless of age",
141 retention_days = args.retention_days
142 ))
143 } else {
144 None
145 };
146
147 output::emit_json(&PurgeResponse {
148 action: if args.dry_run {
149 "dry_run".to_string()
150 } else {
151 "purged".to_string()
152 },
153 purged_count: candidates_count,
154 bytes_freed,
155 oldest_deleted_at,
156 retention_days_used: args.retention_days,
157 dry_run: args.dry_run,
158 namespace: Some(namespace),
159 cutoff_epoch,
160 warnings,
161 elapsed_ms: inicio.elapsed().as_millis() as u64,
162 message,
163 })?;
164
165 Ok(())
166}
167
168fn current_epoch() -> Result<i64, AppError> {
169 let now = std::time::SystemTime::now()
170 .duration_since(std::time::UNIX_EPOCH)
171 .map_err(|err| AppError::Internal(anyhow::anyhow!("system clock error: {err}")))?;
172 Ok(now.as_secs() as i64)
173}
174
175fn compute_metrics(
176 conn: &rusqlite::Connection,
177 cutoff_epoch: i64,
178 namespace_opt: Option<&str>,
179 name: Option<&str>,
180) -> Result<(i64, Option<i64>, usize), AppError> {
181 let (bytes_freed, oldest_deleted_at): (i64, Option<i64>) = if let Some(name) = name {
182 conn.query_row(
183 "SELECT COALESCE(SUM(LENGTH(COALESCE(body,'')) + LENGTH(COALESCE(description,'')) + LENGTH(name)), 0),
184 MIN(deleted_at)
185 FROM memories
186 WHERE deleted_at IS NOT NULL AND deleted_at <= ?1
187 AND (?2 IS NULL OR namespace = ?2)
188 AND name = ?3",
189 rusqlite::params![cutoff_epoch, namespace_opt, name],
190 |r| Ok((r.get::<_, i64>(0)?, r.get::<_, Option<i64>>(1)?)),
191 )?
192 } else {
193 conn.query_row(
194 "SELECT COALESCE(SUM(LENGTH(COALESCE(body,'')) + LENGTH(COALESCE(description,'')) + LENGTH(name)), 0),
195 MIN(deleted_at)
196 FROM memories
197 WHERE deleted_at IS NOT NULL AND deleted_at <= ?1
198 AND (?2 IS NULL OR namespace = ?2)",
199 rusqlite::params![cutoff_epoch, namespace_opt],
200 |r| Ok((r.get::<_, i64>(0)?, r.get::<_, Option<i64>>(1)?)),
201 )?
202 };
203
204 let count: usize = if let Some(name) = name {
205 conn.query_row(
206 "SELECT COUNT(*) FROM memories
207 WHERE deleted_at IS NOT NULL AND deleted_at <= ?1
208 AND (?2 IS NULL OR namespace = ?2)
209 AND name = ?3",
210 rusqlite::params![cutoff_epoch, namespace_opt, name],
211 |r| r.get::<_, usize>(0),
212 )?
213 } else {
214 conn.query_row(
215 "SELECT COUNT(*) FROM memories
216 WHERE deleted_at IS NOT NULL AND deleted_at <= ?1
217 AND (?2 IS NULL OR namespace = ?2)",
218 rusqlite::params![cutoff_epoch, namespace_opt],
219 |r| r.get::<_, usize>(0),
220 )?
221 };
222
223 Ok((bytes_freed, oldest_deleted_at, count))
224}
225
226fn execute_purge(
227 tx: &rusqlite::Transaction,
228 namespace: &str,
229 name: Option<&str>,
230 cutoff_epoch: i64,
231 warnings: &mut Vec<String>,
232) -> Result<(), AppError> {
233 let candidates = select_candidates(tx, namespace, name, cutoff_epoch)?;
234
235 for (memory_id, _name) in &candidates {
236 if let Err(err) = tx.execute(
237 "DELETE FROM vec_chunks WHERE memory_id = ?1",
238 rusqlite::params![memory_id],
239 ) {
240 warnings.push(format!(
241 "failed to clean vec_chunks for memory_id {memory_id}: {err}"
242 ));
243 }
244 if let Err(err) = tx.execute(
245 "DELETE FROM vec_memories WHERE memory_id = ?1",
246 rusqlite::params![memory_id],
247 ) {
248 warnings.push(format!(
249 "failed to clean vec_memories for memory_id {memory_id}: {err}"
250 ));
251 }
252 tx.execute(
253 "DELETE FROM memories WHERE id = ?1 AND namespace = ?2 AND deleted_at IS NOT NULL",
254 rusqlite::params![memory_id, namespace],
255 )?;
256 }
257
258 Ok(())
259}
260
261fn select_candidates(
262 conn: &rusqlite::Connection,
263 namespace: &str,
264 name: Option<&str>,
265 cutoff_epoch: i64,
266) -> Result<Vec<(i64, String)>, AppError> {
267 let query = if name.is_some() {
268 "SELECT id, name FROM memories
269 WHERE namespace = ?1 AND name = ?2 AND deleted_at IS NOT NULL AND deleted_at <= ?3
270 ORDER BY deleted_at ASC"
271 } else {
272 "SELECT id, name FROM memories
273 WHERE namespace = ?1 AND deleted_at IS NOT NULL AND deleted_at <= ?2
274 ORDER BY deleted_at ASC"
275 };
276
277 let mut stmt = conn.prepare_cached(query)?;
278 let rows = if let Some(name) = name {
279 stmt.query_map(rusqlite::params![namespace, name, cutoff_epoch], |row| {
280 Ok((row.get::<_, i64>(0)?, row.get::<_, String>(1)?))
281 })?
282 .collect::<Result<Vec<_>, _>>()?
283 } else {
284 stmt.query_map(rusqlite::params![namespace, cutoff_epoch], |row| {
285 Ok((row.get::<_, i64>(0)?, row.get::<_, String>(1)?))
286 })?
287 .collect::<Result<Vec<_>, _>>()?
288 };
289 Ok(rows)
290}
291
292#[cfg(test)]
293mod tests {
294 use super::*;
295 use rusqlite::Connection;
296
297 fn setup_test_db() -> Connection {
298 let conn = Connection::open_in_memory().expect("failed to open in-memory db");
299 conn.execute_batch(
300 "CREATE TABLE memories (
301 id INTEGER PRIMARY KEY AUTOINCREMENT,
302 name TEXT NOT NULL,
303 namespace TEXT NOT NULL DEFAULT 'global',
304 description TEXT,
305 body TEXT,
306 deleted_at INTEGER
307 );
308 CREATE TABLE IF NOT EXISTS vec_chunks (memory_id INTEGER);
309 CREATE TABLE IF NOT EXISTS vec_memories (memory_id INTEGER);",
310 )
311 .expect("failed to create test tables");
312 conn
313 }
314
315 fn insert_deleted_memory(
316 conn: &Connection,
317 name: &str,
318 namespace: &str,
319 body: &str,
320 deleted_at: i64,
321 ) -> i64 {
322 conn.execute(
323 "INSERT INTO memories (name, namespace, body, deleted_at) VALUES (?1, ?2, ?3, ?4)",
324 rusqlite::params![name, namespace, body, deleted_at],
325 )
326 .expect("failed to insert test memory");
327 conn.last_insert_rowid()
328 }
329
330 #[test]
331 fn retention_days_used_default_is_90() {
332 assert_eq!(crate::constants::PURGE_RETENTION_DAYS_DEFAULT, 90u32);
333 }
334
335 #[test]
336 fn compute_metrics_bytes_freed_positive_for_populated_body() {
337 let conn = setup_test_db();
338 let now = current_epoch().expect("epoch failed");
339 let old_epoch = now - 100 * 86_400;
340 insert_deleted_memory(&conn, "mem-test", "global", "memory body", old_epoch);
341
342 let cutoff = now - 30 * 86_400;
343 let (bytes, oldest, count) =
344 compute_metrics(&conn, cutoff, Some("global"), None).expect("compute_metrics failed");
345
346 assert!(bytes > 0, "bytes_freed must be > 0 for populated body");
347 assert!(oldest.is_some(), "oldest_deleted_at must be Some");
348 assert_eq!(count, 1);
349 }
350
351 #[test]
352 fn compute_metrics_returns_zero_without_candidates() {
353 let conn = setup_test_db();
354 let now = current_epoch().expect("epoch failed");
355 let cutoff = now - 90 * 86_400;
356
357 let (bytes, oldest, count) =
358 compute_metrics(&conn, cutoff, Some("global"), None).expect("compute_metrics failed");
359
360 assert_eq!(bytes, 0);
361 assert!(oldest.is_none());
362 assert_eq!(count, 0);
363 }
364
365 #[test]
366 fn dry_run_does_not_delete_records() {
367 let conn = setup_test_db();
368 let now = current_epoch().expect("epoch failed");
369 let old_epoch = now - 200 * 86_400;
370 insert_deleted_memory(&conn, "mem-dry", "global", "dry run content", old_epoch);
371
372 let cutoff = now - 30 * 86_400;
373 let (_, _, count_before) =
374 compute_metrics(&conn, cutoff, Some("global"), None).expect("compute_metrics failed");
375 assert_eq!(count_before, 1, "must have 1 candidate before dry run");
376
377 let (_, _, count_after) =
378 compute_metrics(&conn, cutoff, Some("global"), None).expect("compute_metrics failed");
379 assert_eq!(
380 count_after, 1,
381 "dry_run must not remove records: count must remain 1"
382 );
383 }
384
385 #[test]
386 fn oldest_deleted_at_returns_smallest_epoch() {
387 let conn = setup_test_db();
388 let now = current_epoch().expect("epoch failed");
389 let epoch_old = now - 300 * 86_400;
390 let epoch_recent = now - 200 * 86_400;
391
392 insert_deleted_memory(&conn, "mem-a", "global", "body-a", epoch_old);
393 insert_deleted_memory(&conn, "mem-b", "global", "body-b", epoch_recent);
394
395 let cutoff = now - 30 * 86_400;
396 let (_, oldest, count) =
397 compute_metrics(&conn, cutoff, Some("global"), None).expect("compute_metrics failed");
398
399 assert_eq!(count, 2);
400 assert_eq!(
401 oldest,
402 Some(epoch_old),
403 "oldest_deleted_at must be the oldest epoch"
404 );
405 }
406
407 #[test]
408 fn purge_args_namespace_accepts_none_without_default() {
409 let resolved = crate::namespace::resolve_namespace(None)
414 .expect("resolve_namespace(None) must return Ok");
415 assert_eq!(
416 resolved, "global",
417 "without env var, resolve_namespace(None) must fall back to 'global'"
418 );
419 }
420
421 #[test]
422 fn purge_response_serializes_all_new_fields() {
423 let resp = PurgeResponse {
424 action: "purged".to_string(),
425 purged_count: 3,
426 bytes_freed: 1024,
427 oldest_deleted_at: Some(1_700_000_000),
428 retention_days_used: 90,
429 dry_run: false,
430 namespace: Some("global".to_string()),
431 cutoff_epoch: 1_710_000_000,
432 warnings: vec![],
433 elapsed_ms: 42,
434 message: None,
435 };
436 let json = serde_json::to_string(&resp).expect("serialization failed");
437 assert!(json.contains("bytes_freed"));
438 assert!(json.contains("oldest_deleted_at"));
439 assert!(json.contains("retention_days_used"));
440 assert!(json.contains("dry_run"));
441 assert!(json.contains("elapsed_ms"));
442 assert!(!json.contains("\"message\""));
444 }
445
446 #[test]
447 fn purge_response_serializes_message_when_present() {
448 let resp = PurgeResponse {
450 action: "purged".to_string(),
451 purged_count: 0,
452 bytes_freed: 0,
453 oldest_deleted_at: None,
454 retention_days_used: 90,
455 dry_run: false,
456 namespace: Some("global".to_string()),
457 cutoff_epoch: 1_710_000_000,
458 warnings: vec![],
459 elapsed_ms: 5,
460 message: Some(
461 "no soft-deleted memories older than 90 day(s); use --retention-days 0 to purge all soft-deleted memories regardless of age"
462 .to_string(),
463 ),
464 };
465 let json = serde_json::to_string(&resp).expect("serialization failed");
466 assert!(json.contains("\"message\""));
467 assert!(json.contains("--retention-days 0"));
468 }
469}