Skip to content

Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors

Rust

fix(store): keep the raw capture of a session with a queued consolidation

Djalma Júnior59b2218e60c7
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1a9a3964..99fbd544 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,6 +11,17 @@ version in [`docs/changelog/`](docs/changelog/):
## [Unreleased]
+### Fixed
+- Fixed the forget sweep's raw-observation prune deleting the raw capture of
+ a session that still has a queued consolidation. A session resumed after its
+ first summary gets a new `session_consolidation_jobs` row (`pending` or
+ `running`) while its old summary page is still live, so the prune could
+ delete the session's raw observations before the queued job read them, and
+ the job would consolidate a truncated session. The prune and its dry-run
+ count now share one exclusion: a session with a `pending` or `running`
+ consolidation job keeps every observation, however old; `completed`,
+ `failed` and `superseded` jobs do not block. (#PRNUM)
+
## [3.0.1] - 2026-10-15
### Fixed
diff --git a/crates/ai-memory-store/src/ops.rs b/crates/ai-memory-store/src/ops.rs
index 3f8b15a7..c3d862be 100644
--- a/crates/ai-memory-store/src/ops.rs
+++ b/crates/ai-memory-store/src/ops.rs
@@ -4047,6 +4047,19 @@ pub struct ObservationPruneOutcome {
pub sessions_resynced: usize,
}
+/// Queued-consolidation exclusion shared, byte for byte, by the observation
+/// prune and its dry-run count (`ReaderPool::prunable_observation_count`):
+/// a session with a `session_consolidation_jobs` row in `pending` or
+/// `running` still needs its raw capture, so those rows never match, however
+/// old. Defined once here and interpolated at both call sites so the two
+/// queries cannot drift apart. The primary key `(session_id, generation)`
+/// already serves the lookup by `session_id`; no extra index is needed.
+pub(crate) const CONSOLIDATION_QUEUE_GUARD_SQL: &str = "NOT EXISTS ( \
+ SELECT 1 FROM session_consolidation_jobs j \
+ WHERE j.session_id = o.session_id \
+ AND j.state IN ('pending', 'running') \
+)";
+
/// Permanently delete one bounded batch of raw observations belonging to
/// sessions that were already distilled into a live summary page.
///
@@ -4061,6 +4074,15 @@ pub struct ObservationPruneOutcome {
/// foreign key has already cleared the pointer. A session with no `sessions`
/// row, or one that never ended, matches nothing and can never be pruned.
///
+/// A session with a consolidation job the worker can still claim is excluded
+/// by [`CONSOLIDATION_QUEUE_GUARD_SQL`] even when every other predicate
+/// holds: that job — a `pending` row (a transient failure is recorded as a
+/// `pending` retry, not `failed`) or a `running` row whose stale lease the
+/// next claim reclaims — still reads the raw capture to consolidate the
+/// session, and pruning underneath it would consolidate a truncated session.
+/// `completed`, `failed` and `superseded` rows are terminal for the automatic
+/// worker and block nothing.
+///
/// `ORDER BY created_at` makes the batching deterministic: a run interrupted
/// halfway leaves a clean age boundary rather than holes, so the next run
/// resumes on a store whose invariant ("everything older than X is gone for
@@ -4088,7 +4110,7 @@ pub fn prune_consolidated_observations(
let mut deleted = 0usize;
let mut sessions: BTreeSet<Vec<u8>> = BTreeSet::new();
{
- let mut stmt = tx.prepare(
+ let mut stmt = tx.prepare(&format!(
"DELETE FROM observations \
WHERE id IN ( \
SELECT o.id FROM observations o \
@@ -4101,11 +4123,12 @@ pub fn prune_consolidated_observations(
WHERE s.id = o.session_id \
AND p.superseded_at IS NULL \
) \
+ AND {CONSOLIDATION_QUEUE_GUARD_SQL} \
ORDER BY o.created_at \
LIMIT ?4 \
) \
RETURNING session_id",
- )?;
+ ))?;
let rows = stmt.query_map(
params![
workspace_id.as_bytes(),
diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rs
index 878a0354..e64e659d 100644
--- a/crates/ai-memory-store/src/reader.rs
+++ b/crates/ai-memory-store/src/reader.rs
@@ -5203,7 +5203,11 @@ impl ReaderPool {
/// [`prune_consolidated_observations`](crate::ops::prune_consolidated_observations),
/// read-only, so a dry run can report a number without any chance of a
/// write. Kept beside the delete rather than derived from it because the
- /// dry run must never open a write transaction at all.
+ /// dry run must never open a write transaction at all. The
+ /// queued-consolidation exclusion is the shared fragment
+ /// `CONSOLIDATION_QUEUE_GUARD_SQL` (interpolated verbatim here and in the
+ /// delete), so a dry run can never report rows the real pass would keep,
+ /// or miss rows it would delete.
///
/// # Errors
/// Propagates SQL errors.
@@ -5214,7 +5218,8 @@ impl ReaderPool {
cutoff_us: i64,
) -> StoreResult<usize> {
self.with_conn(move |conn| {
- let n: i64 = conn.query_row(
+ let guard = crate::ops::CONSOLIDATION_QUEUE_GUARD_SQL;
+ let sql = format!(
"SELECT COUNT(*) FROM observations o \
WHERE o.workspace_id = ?1 \
AND o.project_id = ?2 \
@@ -5224,7 +5229,11 @@ impl ReaderPool {
JOIN pages p ON p.id = s.summary_page_id \
WHERE s.id = o.session_id \
AND p.superseded_at IS NULL \
- )",
+ ) \
+ AND {guard}"
+ );
+ let n: i64 = conn.query_row(
+ &sql,
params![workspace_id.as_bytes(), project_id.as_bytes(), cutoff_us],
|row| row.get(0),
)?;
diff --git a/crates/ai-memory-store/tests/suite/mod.rs b/crates/ai-memory-store/tests/suite/mod.rs
index 7e48dc0a..54fef78e 100644
--- a/crates/ai-memory-store/tests/suite/mod.rs
+++ b/crates/ai-memory-store/tests/suite/mod.rs
@@ -16,6 +16,7 @@ mod handoff_ownership;
mod identity_resolution;
mod most_recently_active_scope;
mod multi_session;
+mod observation_prune;
mod page_first_created;
mod pinned_pages;
mod profile;
diff --git a/crates/ai-memory-store/tests/suite/observation_prune.rs b/crates/ai-memory-store/tests/suite/observation_prune.rs
new file mode 100644
index 00000000..32a954aa
--- /dev/null
+++ b/crates/ai-memory-store/tests/suite/observation_prune.rs
@@ -0,0 +1,312 @@
+//! The raw-observation retention prune and its dry-run count, held to the
+//! queued-consolidation exclusion.
+//!
+//! A session that resumed after its first summary gets a new
+//! `session_consolidation_jobs` row (`pending` or `running`) while its old
+//! summary page is still live. The prune predicate (live summary page + old
+//! rows) matches such a session, and without the exclusion the prune would
+//! delete the raw capture before the queued job reads it, leaving the job to
+//! consolidate a truncated session. These tests pin both halves of the fix:
+//! the delete leaves every observation of a session with a claimable job in
+//! place while still pruning a sibling session in the same batch, and the
+//! dry-run count — which shares the one SQL fragment
+//! (`ops::CONSOLIDATION_QUEUE_GUARD_SQL`) with the delete — equals what the
+//! prune deletes in every job state.
+
+use ai_memory_core::{ProjectId, SessionId, WorkspaceId};
+use ai_memory_store::Store;
+use rusqlite::{Connection, params};
+
+/// A fixed reference instant in microseconds. Every observation lands before
+/// the cutoff used below, so age is never what separates the fixtures.
+const NOW: i64 = 1_700_000_000_000_000;
+/// Far past every `created_at` seeded below: all rows pass the age gate.
+const CUTOFF: i64 = NOW + 100;
+const OBSERVATIONS_PER_SESSION: i64 = 3;
+
+fn id(n: u8) -> [u8; 16] {
+ let mut b = [0u8; 16];
+ b[15] = n;
+ b
+}
+
+fn ws() -> WorkspaceId {
+ WorkspaceId::from_slice(&id(1)).unwrap()
+}
+
+fn proj() -> ProjectId {
+ ProjectId::from_slice(&id(2)).unwrap()
+}
+
+/// Session 10 carries the consolidation job under test; session 11 is the
+/// same-project control that never has a job.
+fn s1() -> SessionId {
+ SessionId::from_slice(&id(10)).unwrap()
+}
+
+fn s2() -> SessionId {
+ SessionId::from_slice(&id(11)).unwrap()
+}
+
+/// Two ended sessions, each distilled into its own live summary page and
+/// holding three old observations, with `ended_observation_count` recording
+/// the three the way the session-end marker does.
+fn seed(conn: &Connection) {
+ let (ws, proj) = (id(1), id(2));
+
+ conn.execute(
+ "INSERT INTO workspaces (id, name, created_at) VALUES (?1, 'w', ?2)",
+ params![&ws[..], NOW],
+ )
+ .unwrap();
+ conn.execute(
+ "INSERT INTO projects (id, workspace_id, name, repo_path, created_at) \
+ VALUES (?1, ?2, ?3, ?4, ?5)",
+ params![&proj[..], &ws[..], "proj", "/w/proj", NOW],
+ )
+ .unwrap();
+
+ for (n, page_n) in [(10, 100), (11, 101)] {
+ let path = format!("sessions/s{n}.md");
+ conn.execute(
+ "INSERT INTO pages \
+ (id, workspace_id, project_id, path, title, tier, body, body_sha256, \
+ frontmatter_json, is_latest, created_at, updated_at) \
+ VALUES (?1, ?2, ?3, ?4, ?4, 'episodic', 'distilled', ?5, '{}', 1, ?6, ?6)",
+ params![
+ &id(page_n)[..],
+ &ws[..],
+ &proj[..],
+ path,
+ &[0u8; 32][..],
+ NOW,
+ ],
+ )
+ .unwrap();
+ conn.execute(
+ "INSERT INTO sessions \
+ (id, workspace_id, project_id, agent_kind, cwd, started_at, ended_at, \
+ summary_page_id, ended_observation_count) \
+ VALUES (?1, ?2, ?3, 'claude-code', '/w/proj', ?4, ?5, ?6, 3)",
+ params![
+ &id(n)[..],
+ &ws[..],
+ &proj[..],
+ NOW + i64::from(n),
+ NOW + 50 + i64::from(n),
+ &id(page_n)[..],
+ ],
+ )
+ .unwrap();
+ for i in 1..=OBSERVATIONS_PER_SESSION {
+ let obs_n = 30u8 + (n - 10) * 3 + i as u8;
+ conn.execute(
+ "INSERT INTO observations \
+ (id, session_id, workspace_id, project_id, kind, title, body, importance, \
+ created_at) \
+ VALUES (?1, ?2, ?3, ?4, 'user-prompt', ?5, ?6, 7, ?7)",
+ params![
+ &id(obs_n)[..],
+ &id(n)[..],
+ &ws[..],
+ &proj[..],
+ format!("obs {n}-{i}"),
+ "old capture",
+ NOW + i,
+ ],
+ )
+ .unwrap();
+ }
+ }
+}
+
+/// Insert session 10's consolidation job in the given state, shaped the way
+/// the queue writes it: `next_attempt_at` for `pending`, `started_at` and
+/// `claim_id` for `running`.
+fn queue_job(conn: &Connection, state: &str) {
+ let (ws, proj) = (id(1), id(2));
+ conn.execute(
+ "INSERT INTO session_consolidation_jobs \
+ (session_id, workspace_id, project_id, generation, state, requested_at, \
+ next_attempt_at, started_at, claim_id) \
+ VALUES (?1, ?2, ?3, 1, ?4, ?5, ?5, \
+ CASE WHEN ?4 = 'running' THEN ?5 ELSE NULL END, \
+ CASE WHEN ?4 = 'running' THEN ?6 ELSE NULL END)",
+ params![&id(10)[..], &ws[..], &proj[..], state, NOW, &[1u8; 16][..]],
+ )
+ .unwrap();
+}
+
+/// Everything the assertions need: the dry-run count before the prune, the
+/// prune outcome, and the row counts and watermarks after it.
+struct Measured {
+ count_before: usize,
+ count_after: usize,
+ deleted: usize,
+ touched: Vec<SessionId>,
+ resynced: usize,
+ s1_rows: i64,
+ s2_rows: i64,
+ s1_watermark: i64,
+ s2_watermark: i64,
+}
+
+async fn measure(store: &Store) -> Measured {
+ let count_before = store
+ .reader
+ .prunable_observation_count(ws(), proj(), CUTOFF)
+ .await
+ .unwrap();
+ let outcome = store
+ .writer
+ .prune_consolidated_observations(ws(), proj(), CUTOFF, 100)
+ .await
+ .unwrap();
+ let conn = Connection::open(store.db_path()).unwrap();
+ conn.pragma_update(None, "busy_timeout", 5_000).unwrap();
+ let rows = |sid: SessionId| {
+ conn.query_row(
+ "SELECT COUNT(*) FROM observations WHERE session_id = ?1",
+ params![sid.as_bytes()],
+ |row| row.get(0),
+ )
+ .unwrap()
+ };
+ let watermark = |sid: SessionId| {
+ conn.query_row(
+ "SELECT ended_observation_count FROM sessions WHERE id = ?1",
+ params![sid.as_bytes()],
+ |row| row.get(0),
+ )
+ .unwrap()
+ };
+ let count_after = store
+ .reader
+ .prunable_observation_count(ws(), proj(), CUTOFF)
+ .await
+ .unwrap();
+ Measured {
+ count_before,
+ count_after,
+ deleted: outcome.deleted,
+ touched: outcome.sessions_touched,
+ resynced: outcome.sessions_resynced,
+ s1_rows: rows(s1()),
+ s2_rows: rows(s2()),
+ s1_watermark: watermark(s1()),
+ s2_watermark: watermark(s2()),
+ }
+}
+
+fn open_seeded(state: Option<&str>) -> (tempfile::TempDir, Store) {
+ let tmp = tempfile::tempdir().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let conn = Connection::open(store.db_path()).unwrap();
+ conn.pragma_update(None, "busy_timeout", 5_000).unwrap();
+ seed(&conn);
+ if let Some(state) = state {
+ queue_job(&conn, state);
+ }
+ (tmp, store)
+}
+
+/// What each job state must yield. `pending` and `running` protect session 10
+/// (the count and the delete both see only session 11's three rows); every
+/// other state — and no job at all — prunes both sessions.
+fn expect(state: Option<&str>) -> (bool, usize) {
+ match state {
+ Some("pending") | Some("running") => (true, 3),
+ Some("completed") | Some("failed") | Some("superseded") | None => (false, 6),
+ other => panic!("unexpected job state {other:?}"),
+ }
+}
+
+fn assert_case(m: &Measured, state: Option<&str>) {
+ let (protected, prunable) = expect(state);
+ assert_eq!(m.count_before, prunable, "dry-run count for {state:?}");
+ assert_eq!(m.deleted, prunable, "rows deleted for {state:?}");
+ assert_eq!(
+ m.s1_rows,
+ if protected { 3 } else { 0 },
+ "session 10 rows after the prune for {state:?}"
+ );
+ assert_eq!(
+ m.s2_rows, 0,
+ "the job-less session 11 is pruned in the same batch for {state:?}"
+ );
+ // The watermark resync covers exactly the sessions that lost rows.
+ assert_eq!(
+ m.s1_watermark,
+ if protected { 3 } else { 0 },
+ "session 10 watermark for {state:?}"
+ );
+ assert_eq!(m.s2_watermark, 0, "session 11 watermark for {state:?}");
+ if protected {
+ assert_eq!(
+ m.touched,
+ vec![s2()],
+ "only the job-less session may be touched for {state:?}"
+ );
+ assert_eq!(
+ m.resynced, 1,
+ "only the job-less session resyncs for {state:?}"
+ );
+ } else {
+ assert_eq!(m.touched, vec![s1(), s2()], "touched for {state:?}");
+ assert_eq!(m.resynced, 2, "resynced for {state:?}");
+ }
+ assert_eq!(
+ m.count_after, 0,
+ "nothing left for the dry run to report after the prune for {state:?}"
+ );
+}
+
+/// A session that still has a `pending` consolidation job keeps every
+/// observation, however old, while its job-less same-project sibling is
+/// pruned by the very same batch.
+#[tokio::test]
+async fn a_pending_job_protects_a_consolidated_sessions_observations() {
+ let (_tmp, store) = open_seeded(Some("pending"));
+ assert_case(&measure(&store).await, Some("pending"));
+}
+
+/// The same protection applies to a `running` job: the worker may still be
+/// inside its lease (or about to reclaim a stale one) and read the raw
+/// capture.
+#[tokio::test]
+async fn a_running_job_protects_a_consolidated_sessions_observations() {
+ let (_tmp, store) = open_seeded(Some("running"));
+ assert_case(&measure(&store).await, Some("running"));
+}
+
+/// `completed`, `failed` and `superseded` are terminal for the automatic
+/// worker: each control prunes both sessions exactly as before the fix.
+#[tokio::test]
+async fn a_terminal_job_state_does_not_protect_a_consolidated_session() {
+ for state in ["completed", "failed", "superseded"] {
+ let (_tmp, store) = open_seeded(Some(state));
+ assert_case(&measure(&store).await, Some(state));
+ }
+}
+
+/// The dry run and the real pass share one SQL fragment, so the count must
+/// equal what the prune deletes — and only that — in every job state.
+#[tokio::test]
+async fn the_dry_run_count_equals_the_prune_deletes_in_every_job_state() {
+ for state in [
+ None,
+ Some("pending"),
+ Some("running"),
+ Some("completed"),
+ Some("failed"),
+ Some("superseded"),
+ ] {
+ let (_tmp, store) = open_seeded(state);
+ let m = measure(&store).await;
+ assert_eq!(
+ m.count_before, m.deleted,
+ "dry-run count must equal the prune for {state:?}"
+ );
+ assert_case(&m, state);
+ }
+}
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 6c8a304f..6996129b 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -198,7 +198,10 @@ from hook paths.
is positive, then deletes raw `observations` older than that age, but only
for sessions already consolidated into a summary page that is still live, so
raw capture is never removed while it is the last copy of that session's
- work. It runs last so this run's own evictions and hard-deletes already
+ work, and never for a session that still has a `session_consolidation_jobs`
+ row in `pending` or `running` — a queued (or lease-stale) consolidation
+ still reads the raw capture, and the dry-run count applies the same guard,
+ so the two can never disagree. It runs last so this run's own evictions and hard-deletes already
exclude their sessions, deletes in `observation_prune_batch` transactions so
a multi-million row prune cannot hold the write lock, and repairs
`sessions.ended_observation_count` downward in the same transaction. The