Skip to main content

aidaemon_memory/sqlite/
retention.rs

1//! Age-based cleanup of the memory tables. Each step has a safe guard: only
2//! superseded facts, unrecalled episodes, decayed patterns, zero-success
3//! procedures and net-negative error solutions go, in small batches.
4
5use std::sync::Arc;
6
7use chrono::{Duration, Utc};
8use sqlx::SqlitePool;
9
10use crate::history::MessageLog;
11use tracing::warn;
12
13/// How long each kind of memory is kept, in days. Zero keeps it forever.
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub struct MemoryRetentionPolicy {
16    pub superseded_facts_days: u32,
17    pub episodes_days: u32,
18    pub behavior_patterns_days: u32,
19    pub procedures_days: u32,
20    pub error_solutions_days: u32,
21}
22
23/// Rows removed by one pass.
24#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
25pub struct MemoryRetentionStats {
26    pub facts_deleted: u64,
27    pub episodes_deleted: u64,
28    pub behavior_patterns_deleted: u64,
29    pub procedures_deleted: u64,
30    pub error_solutions_deleted: u64,
31    pub derived_memory_deleted: u64,
32}
33
34/// One pass of retention over a database holding the memory tables.
35pub struct MemoryRetention {
36    pool: SqlitePool,
37    config: MemoryRetentionPolicy,
38    messages: Option<Arc<dyn MessageLog>>,
39}
40
41impl MemoryRetention {
42    pub fn new(pool: SqlitePool, config: MemoryRetentionPolicy) -> Self {
43        Self {
44            pool,
45            config,
46            messages: None,
47        }
48    }
49
50    /// Drops indexed messages the host no longer keeps. Without a log,
51    /// indexed messages stay until their claims and episodes go.
52    pub fn with_message_log(mut self, messages: Arc<dyn MessageLog>) -> Self {
53        self.messages = Some(messages);
54        self
55    }
56
57    /// Delete message spans, not backing any claim, whose message the host
58    /// no longer keeps.
59    async fn cleanup_spans_of_dropped_messages(&self) -> anyhow::Result<u64> {
60        let Some(messages) = &self.messages else {
61            return Ok(0);
62        };
63        let spans: Vec<(i64, i64)> = sqlx::query_as(
64            "SELECT id, source_event_id FROM memory_spans
65             WHERE source_event_id IS NOT NULL
66               AND NOT EXISTS (
67                   SELECT 1 FROM memory_claims c WHERE c.source_span_id = memory_spans.id
68               )",
69        )
70        .fetch_all(&self.pool)
71        .await?;
72        let mut dropped = Vec::new();
73        for chunk in spans.chunks(500) {
74            let sources: Vec<i64> = chunk.iter().map(|(_, source)| *source).collect();
75            let kept = messages.retained(&sources).await?;
76            dropped.extend(
77                chunk
78                    .iter()
79                    .filter(|(_, source)| !kept.contains(source))
80                    .map(|(span_id, _)| *span_id),
81            );
82        }
83        if dropped.is_empty() {
84            return Ok(0);
85        }
86        // One transaction, a set-based delete per batch of ids. A claim
87        // filed since the scan keeps its span.
88        let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
89        let mut deleted = 0;
90        for ids in dropped.chunks(500) {
91            let placeholders = vec!["?"; ids.len()].join(", ");
92            let sql = format!(
93                "DELETE FROM memory_spans WHERE id IN ({placeholders})
94                   AND NOT EXISTS (
95                       SELECT 1 FROM memory_claims c WHERE c.source_span_id = memory_spans.id
96                   )"
97            );
98            let mut query = sqlx::query(sqlx::AssertSqlSafe(&*sql));
99            for id in ids {
100                query = query.bind(id);
101            }
102            deleted += query.execute(&mut *tx).await?.rows_affected();
103        }
104        tx.commit().await?;
105        Ok(deleted)
106    }
107
108    /// Run every step. One failing does not stop the others.
109    pub async fn run_all(&self) -> MemoryRetentionStats {
110        fn counted(step: &str, result: anyhow::Result<u64>) -> u64 {
111            result.unwrap_or_else(|error| {
112                warn!("Retention: {step} cleanup failed: {error}");
113                0
114            })
115        }
116        MemoryRetentionStats {
117            facts_deleted: counted("facts", self.cleanup_superseded_facts().await),
118            episodes_deleted: counted("episodes", self.cleanup_episodes().await),
119            behavior_patterns_deleted: counted(
120                "behavior_patterns",
121                self.cleanup_behavior_patterns().await,
122            ),
123            procedures_deleted: counted("procedures", self.cleanup_procedures().await),
124            error_solutions_deleted: counted(
125                "error_solutions",
126                self.cleanup_error_solutions().await,
127            ),
128            derived_memory_deleted: counted("derived memory", self.cleanup_derived_memory().await),
129        }
130    }
131
132    /// Delete old superseded fact versions.
133    /// Safety: only deletes facts that have been superseded (replaced by newer version).
134    pub async fn cleanup_superseded_facts(&self) -> anyhow::Result<u64> {
135        if self.config.superseded_facts_days == 0 {
136            return Ok(0);
137        }
138        let cutoff =
139            (Utc::now() - Duration::days(self.config.superseded_facts_days as i64)).to_rfc3339();
140        let result = sqlx::query(
141            "DELETE FROM facts WHERE id IN (
142                SELECT id FROM facts
143                WHERE superseded_at IS NOT NULL AND superseded_at < ?
144                LIMIT 500
145            )",
146        )
147        .bind(&cutoff)
148        .execute(&self.pool)
149        .await?;
150        Ok(result.rows_affected())
151    }
152
153    /// Delete episodes with recall_count=0 older than cutoff.
154    /// Safety: preserves episodes that have been recalled (referenced).
155    pub async fn cleanup_episodes(&self) -> anyhow::Result<u64> {
156        if self.config.episodes_days == 0 {
157            return Ok(0);
158        }
159        let cutoff = (Utc::now() - Duration::days(self.config.episodes_days as i64)).to_rfc3339();
160        let result = sqlx::query(
161            "DELETE FROM episodes WHERE id IN (
162                SELECT id FROM episodes
163                WHERE recall_count = 0 AND created_at < ?
164                LIMIT 500
165            )",
166        )
167        .bind(&cutoff)
168        .execute(&self.pool)
169        .await?;
170        Ok(result.rows_affected())
171    }
172
173    /// Delete behavior patterns at confidence floor that haven't been seen recently.
174    /// Safety: only deletes already-decayed patterns (confidence <= 0.1).
175    pub async fn cleanup_behavior_patterns(&self) -> anyhow::Result<u64> {
176        if self.config.behavior_patterns_days == 0 {
177            return Ok(0);
178        }
179        let cutoff =
180            (Utc::now() - Duration::days(self.config.behavior_patterns_days as i64)).to_rfc3339();
181        let result = sqlx::query(
182            "DELETE FROM behavior_patterns WHERE id IN (
183                SELECT id FROM behavior_patterns
184                WHERE confidence <= 0.1 AND (last_seen_at IS NULL OR last_seen_at < ?)
185                LIMIT 500
186            )",
187        )
188        .bind(&cutoff)
189        .execute(&self.pool)
190        .await?;
191        Ok(result.rows_affected())
192    }
193
194    /// Delete zero-success procedures older than cutoff.
195    /// Safety: preserves any procedure that has succeeded at least once.
196    pub async fn cleanup_procedures(&self) -> anyhow::Result<u64> {
197        if self.config.procedures_days == 0 {
198            return Ok(0);
199        }
200        let cutoff = (Utc::now() - Duration::days(self.config.procedures_days as i64)).to_rfc3339();
201        let result = sqlx::query(
202            "DELETE FROM procedures WHERE id IN (
203                SELECT id FROM procedures
204                WHERE success_count = 0 AND (last_used_at IS NULL OR last_used_at < ?)
205                LIMIT 500
206            )",
207        )
208        .bind(&cutoff)
209        .execute(&self.pool)
210        .await?;
211        Ok(result.rows_affected())
212    }
213
214    /// Delete net-negative error solutions older than cutoff.
215    /// Safety: preserves solutions where success_count >= failure_count.
216    pub async fn cleanup_error_solutions(&self) -> anyhow::Result<u64> {
217        if self.config.error_solutions_days == 0 {
218            return Ok(0);
219        }
220        let cutoff =
221            (Utc::now() - Duration::days(self.config.error_solutions_days as i64)).to_rfc3339();
222        let result = sqlx::query(
223            "DELETE FROM error_solutions WHERE id IN (
224                SELECT id FROM error_solutions
225                WHERE failure_count > success_count AND (last_used_at IS NULL OR last_used_at < ?)
226                LIMIT 500
227            )",
228        )
229        .bind(&cutoff)
230        .execute(&self.pool)
231        .await?;
232        Ok(result.rows_affected())
233    }
234
235    /// Remove projections whose authoritative source no longer exists. Derived
236    /// rows are disposable and must not outlive an explicit source deletion.
237    pub async fn cleanup_derived_memory(&self) -> anyhow::Result<u64> {
238        let has_tables: i64 = sqlx::query_scalar(
239            "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'memory_claims'",
240        )
241        .fetch_one(&self.pool)
242        .await?;
243        if has_tables == 0 {
244            return Ok(0);
245        }
246
247        let mut deleted = 0;
248        deleted += sqlx::query(
249            "DELETE FROM memory_edges
250             WHERE source_claim_id IS NOT NULL
251               AND NOT EXISTS (SELECT 1 FROM memory_claims c WHERE c.id = source_claim_id)",
252        )
253        .execute(&self.pool)
254        .await?
255        .rows_affected();
256        deleted += sqlx::query(
257            "DELETE FROM memory_edges
258             WHERE source_claim_id IN (
259                 SELECT c.id FROM memory_claims c
260                 WHERE c.source_fact_id IS NOT NULL
261                   AND NOT EXISTS (SELECT 1 FROM facts f WHERE f.id = c.source_fact_id)
262             )",
263        )
264        .execute(&self.pool)
265        .await?
266        .rows_affected();
267        deleted += sqlx::query(
268            "DELETE FROM memory_embeddings
269             WHERE (owner_type = 'claim' AND NOT EXISTS (
270                       SELECT 1 FROM memory_claims c
271                       WHERE c.id = CAST(owner_id AS INTEGER)
272                         AND CAST(c.id AS TEXT) = owner_id))
273                OR (owner_type = 'span' AND NOT EXISTS (
274                       SELECT 1 FROM memory_spans s
275                       WHERE s.id = CAST(owner_id AS INTEGER)
276                         AND CAST(s.id AS TEXT) = owner_id))
277                OR (owner_type = 'procedure' AND NOT EXISTS (
278                       SELECT 1 FROM procedures p
279                       WHERE p.id = CAST(owner_id AS INTEGER)
280                         AND CAST(p.id AS TEXT) = owner_id))
281                OR (owner_type = 'error_solution' AND NOT EXISTS (
282                       SELECT 1 FROM error_solutions e
283                       WHERE e.id = CAST(owner_id AS INTEGER)
284                         AND CAST(e.id AS TEXT) = owner_id))
285                OR (owner_type = 'fact_key' AND NOT EXISTS (
286                       SELECT 1 FROM facts f
287                       WHERE f.id = CAST(owner_id AS INTEGER)
288                         AND CAST(f.id AS TEXT) = owner_id
289                         AND f.superseded_at IS NULL))
290                OR (stale_at IS NOT NULL AND stale_at < datetime('now', '-30 days'))",
291        )
292        .execute(&self.pool)
293        .await?
294        .rows_affected();
295        deleted += sqlx::query(
296            "DELETE FROM memory_claims
297             WHERE source_fact_id IS NOT NULL
298               AND NOT EXISTS (SELECT 1 FROM facts f WHERE f.id = source_fact_id)",
299        )
300        .execute(&self.pool)
301        .await?
302        .rows_affected();
303        deleted += sqlx::query(
304            "DELETE FROM memory_spans
305             WHERE source_episode_id IS NOT NULL AND NOT EXISTS (
306                       SELECT 1 FROM episodes ep WHERE ep.id = source_episode_id)
307               AND NOT EXISTS (
308                   SELECT 1 FROM memory_claims c WHERE c.source_span_id = memory_spans.id
309               )",
310        )
311        .execute(&self.pool)
312        .await?
313        .rows_affected();
314        deleted += self.cleanup_spans_of_dropped_messages().await?;
315        deleted += sqlx::query(
316            "DELETE FROM memory_embeddings
317             WHERE (owner_type = 'claim' AND NOT EXISTS (
318                       SELECT 1 FROM memory_claims c
319                       WHERE c.id = CAST(owner_id AS INTEGER)
320                         AND CAST(c.id AS TEXT) = owner_id))
321                OR (owner_type = 'span' AND NOT EXISTS (
322                       SELECT 1 FROM memory_spans s
323                       WHERE s.id = CAST(owner_id AS INTEGER)
324                         AND CAST(s.id AS TEXT) = owner_id))",
325        )
326        .execute(&self.pool)
327        .await?
328        .rows_affected();
329        deleted += sqlx::query(
330            "DELETE FROM memory_entities
331             WHERE canonical_name != 'owner'
332               AND NOT EXISTS (
333                   SELECT 1 FROM memory_edges edge
334                   WHERE edge.source_entity_id = memory_entities.id
335                      OR edge.target_entity_id = memory_entities.id
336               )
337               AND NOT EXISTS (
338                   SELECT 1 FROM memory_aliases alias
339                   WHERE alias.entity_id = memory_entities.id
340               )
341               AND NOT EXISTS (
342                   SELECT 1 FROM memory_entity_facts fact
343                   WHERE fact.subject_entity_id = memory_entities.id
344               )
345               AND NOT EXISTS (
346                   SELECT 1 FROM memory_relationships relationship
347                   WHERE relationship.source_entity_id = memory_entities.id
348                      OR relationship.target_entity_id = memory_entities.id
349               )
350               AND NOT EXISTS (
351                   SELECT 1 FROM memory_write_audit audit
352                   WHERE audit.entity_id = memory_entities.id
353               )",
354        )
355        .execute(&self.pool)
356        .await?
357        .rows_affected();
358        Ok(deleted)
359    }
360}
361
362#[cfg(test)]
363mod tests {
364    use super::*;
365    use std::collections::HashSet;
366
367    /// A host log that keeps only the listed message ids.
368    struct Keeps(HashSet<i64>);
369
370    #[async_trait::async_trait]
371    impl MessageLog for Keeps {
372        async fn message_bounds(
373            &self,
374            _session_id: &str,
375            _start: chrono::DateTime<Utc>,
376            _end: chrono::DateTime<Utc>,
377        ) -> anyhow::Result<(Option<i64>, Option<i64>)> {
378            Ok((None, None))
379        }
380
381        async fn retained(&self, ids: &[i64]) -> anyhow::Result<HashSet<i64>> {
382            Ok(ids
383                .iter()
384                .copied()
385                .filter(|id| self.0.contains(id))
386                .collect())
387        }
388    }
389
390    async fn span(pool: &SqlitePool, source_event_id: i64) -> i64 {
391        sqlx::query(
392            "INSERT INTO memory_spans
393                (span_kind, source_event_id, content, content_hash, valid_from)
394             VALUES ('message', ?, 'synthetic', ?, '2026-01-01T00:00:00Z')",
395        )
396        .bind(source_event_id)
397        .bind(format!("hash-{source_event_id}"))
398        .execute(pool)
399        .await
400        .unwrap()
401        .last_insert_rowid()
402    }
403
404    /// Spans of dropped messages go, in batches over the 500-id limit;
405    /// spans of kept messages, and spans backing a claim, stay.
406    #[tokio::test]
407    async fn spans_of_dropped_messages_go_unless_kept_or_claimed() {
408        let pool = sqlx::sqlite::SqlitePoolOptions::new()
409            .max_connections(1)
410            .connect("sqlite::memory:")
411            .await
412            .unwrap();
413        crate::sqlite::migrate(&pool).await.unwrap();
414        let mut kept = HashSet::new();
415        let mut expected_left = Vec::new();
416        for event_id in 1..=1200 {
417            let span_id = span(&pool, event_id).await;
418            if event_id % 3 == 0 {
419                kept.insert(event_id);
420                expected_left.push(span_id);
421            }
422        }
423        let claimed = span(&pool, 5000).await;
424        sqlx::query(
425            "INSERT INTO memory_claims
426                (subject, predicate, object, claim_text, source_span_id, provenance, valid_from)
427             VALUES ('owner', 'likes', 'tea', 'owner likes tea', ?, 'test',
428                     '2026-01-01T00:00:00Z')",
429        )
430        .bind(claimed)
431        .execute(&pool)
432        .await
433        .unwrap();
434        expected_left.push(claimed);
435
436        let retention = MemoryRetention::new(
437            pool.clone(),
438            MemoryRetentionPolicy {
439                superseded_facts_days: 0,
440                episodes_days: 0,
441                behavior_patterns_days: 0,
442                procedures_days: 0,
443                error_solutions_days: 0,
444            },
445        )
446        .with_message_log(Arc::new(Keeps(kept)));
447        assert_eq!(
448            retention.cleanup_spans_of_dropped_messages().await.unwrap(),
449            800
450        );
451        let mut left: Vec<i64> = sqlx::query_scalar("SELECT id FROM memory_spans")
452            .fetch_all(&pool)
453            .await
454            .unwrap();
455        left.sort();
456        expected_left.sort();
457        assert_eq!(left, expected_left);
458        assert_eq!(
459            retention.cleanup_spans_of_dropped_messages().await.unwrap(),
460            0
461        );
462    }
463}