Skip to main content

zeph_memory/semantic/
cross_session.rs

1// SPDX-FileCopyrightText: 2026 Andrei G <bug-ops>
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4use zeph_llm::provider::LlmProvider as _;
5
6use crate::error::MemoryError;
7use crate::types::ConversationId;
8use crate::vector_store::{FieldCondition, FieldValue, VectorFilter};
9
10use super::{SESSION_SUMMARIES_COLLECTION, SemanticMemory};
11
12#[derive(Debug, Clone)]
13pub struct SessionSummaryResult {
14    pub summary_text: String,
15    pub score: f32,
16    pub conversation_id: ConversationId,
17}
18
19impl SemanticMemory {
20    /// Check whether a session summary already exists for the given conversation.
21    ///
22    /// Returns `true` if at least one session summary is stored in `SQLite` for this conversation.
23    /// Used as the primary guard in the shutdown summary path to handle cases where hard
24    /// compaction fired but its Qdrant write failed (the `SQLite` record is the authoritative source).
25    ///
26    /// # Errors
27    ///
28    /// Returns an error if the database query fails.
29    pub async fn has_session_summary(
30        &self,
31        conversation_id: ConversationId,
32    ) -> Result<bool, MemoryError> {
33        let summaries = self.sqlite.load_summaries(conversation_id).await?;
34        Ok(!summaries.is_empty())
35    }
36
37    /// Store a shutdown session summary: persists to `SQLite`, embeds into the
38    /// `zeph_session_summaries` Qdrant collection (so cross-session search can find it),
39    /// and stores key facts into the key-facts collection.
40    ///
41    /// Unlike the hard-compaction path, `first_message_id` and `last_message_id` are `None`
42    /// because the shutdown hook does not track exact message boundaries.
43    ///
44    /// # Errors
45    ///
46    /// Returns an error if the `SQLite` insert fails. Qdrant errors are logged as warnings
47    /// and do not propagate — the `SQLite` record is the authoritative summary store.
48    pub async fn store_shutdown_summary(
49        &self,
50        conversation_id: ConversationId,
51        summary_text: &str,
52        key_facts: &[String],
53    ) -> Result<(), MemoryError> {
54        let token_estimate =
55            i64::try_from(self.token_counter.count_tokens(summary_text)).unwrap_or(0);
56        // Persist to SQLite first — this is the authoritative record and the source of truth
57        // for has_session_summary(). NULL message range = session-level summary.
58        let summary_id = self
59            .sqlite
60            .save_summary(conversation_id, summary_text, None, None, token_estimate)
61            .await?;
62
63        // Embed into SESSION_SUMMARIES_COLLECTION so search_session_summaries() can find it.
64        if let Err(e) = self
65            .store_session_summary(conversation_id, summary_text)
66            .await
67        {
68            tracing::warn!("shutdown summary: failed to embed into session summaries: {e:#}");
69        }
70
71        if !key_facts.is_empty() {
72            self.store_key_facts(conversation_id, summary_id, key_facts)
73                .await;
74        }
75
76        tracing::debug!(
77            conversation_id = conversation_id.0,
78            summary_id,
79            "stored shutdown session summary"
80        );
81        Ok(())
82    }
83
84    /// Store a session summary into the dedicated `zeph_session_summaries` Qdrant collection.
85    ///
86    /// # Errors
87    ///
88    /// Returns an error if embedding or Qdrant storage fails.
89    pub async fn store_session_summary(
90        &self,
91        conversation_id: ConversationId,
92        summary_text: &str,
93    ) -> Result<(), MemoryError> {
94        let Some(qdrant) = &self.qdrant else {
95            return Ok(());
96        };
97        if !self.provider.supports_embeddings() {
98            return Ok(());
99        }
100
101        let vector = self.provider.embed(summary_text).await?;
102        let vector_size = u64::try_from(vector.len()).unwrap_or(896);
103        qdrant
104            .ensure_named_collection(SESSION_SUMMARIES_COLLECTION, vector_size)
105            .await?;
106
107        let point_id = {
108            const NS: uuid::Uuid = uuid::Uuid::NAMESPACE_OID;
109            uuid::Uuid::new_v5(&NS, conversation_id.0.to_string().as_bytes()).to_string()
110        };
111        let payload = serde_json::json!({
112            "conversation_id": conversation_id.0,
113            "summary_text": summary_text,
114        });
115
116        qdrant
117            .upsert_to_collection(SESSION_SUMMARIES_COLLECTION, &point_id, payload, vector)
118            .await?;
119
120        tracing::debug!(
121            conversation_id = conversation_id.0,
122            "stored session summary"
123        );
124        Ok(())
125    }
126
127    /// Search session summaries from other conversations.
128    ///
129    /// # Errors
130    ///
131    /// Returns an error if embedding or Qdrant search fails.
132    pub async fn search_session_summaries(
133        &self,
134        query: &str,
135        limit: usize,
136        exclude_conversation_id: Option<ConversationId>,
137    ) -> Result<Vec<SessionSummaryResult>, MemoryError> {
138        let Some(qdrant) = &self.qdrant else {
139            tracing::debug!("session-summaries: skipped, no vector store");
140            return Ok(Vec::new());
141        };
142        if !self.provider.supports_embeddings() {
143            tracing::debug!("session-summaries: skipped, no embedding support");
144            return Ok(Vec::new());
145        }
146
147        let vector = self.provider.embed(query).await?;
148        let vector_size = u64::try_from(vector.len()).unwrap_or(896);
149        qdrant
150            .ensure_named_collection(SESSION_SUMMARIES_COLLECTION, vector_size)
151            .await?;
152
153        let filter = exclude_conversation_id.map(|cid| VectorFilter {
154            must: vec![],
155            must_not: vec![FieldCondition {
156                field: "conversation_id".into(),
157                value: FieldValue::Integer(cid.0),
158            }],
159        });
160
161        let points = qdrant
162            .search_collection(SESSION_SUMMARIES_COLLECTION, &vector, limit, filter)
163            .await?;
164
165        tracing::debug!(
166            results = points.len(),
167            limit,
168            exclude_conversation_id = exclude_conversation_id.map(|c| c.0),
169            "session-summaries: search complete"
170        );
171
172        let results = points
173            .into_iter()
174            .filter_map(|point| {
175                let summary_text = point.payload.get("summary_text")?.as_str()?.to_owned();
176                let conversation_id =
177                    ConversationId(point.payload.get("conversation_id")?.as_i64()?);
178                Some(SessionSummaryResult {
179                    summary_text,
180                    score: point.score,
181                    conversation_id,
182                })
183            })
184            .collect();
185
186        Ok(results)
187    }
188}
189
190#[cfg(test)]
191mod tests {
192    use zeph_llm::any::AnyProvider;
193    use zeph_llm::mock::MockProvider;
194
195    use crate::types::MessageId;
196
197    use super::*;
198
199    async fn make_memory() -> SemanticMemory {
200        SemanticMemory::new(
201            ":memory:",
202            "http://127.0.0.1:1",
203            AnyProvider::Mock(MockProvider::default()),
204            "test-model",
205        )
206        .await
207        .unwrap()
208    }
209
210    /// Insert a real message into the conversation and return its MessageId.
211    /// Required because the `summaries` table has FK constraints on `messages.id`.
212    async fn insert_message(memory: &SemanticMemory, cid: ConversationId) -> MessageId {
213        let id = memory
214            .sqlite()
215            .save_message(cid, "user", "test message")
216            .await
217            .unwrap();
218        id
219    }
220
221    #[tokio::test]
222    async fn has_session_summary_returns_false_when_no_summaries() {
223        let memory = make_memory().await;
224        let cid = memory.sqlite().create_conversation().await.unwrap();
225
226        let result = memory.has_session_summary(cid).await.unwrap();
227        assert!(!result, "new conversation must have no summaries");
228    }
229
230    #[tokio::test]
231    async fn has_session_summary_returns_true_after_summary_stored_via_sqlite() {
232        let memory = make_memory().await;
233        let cid = memory.sqlite().create_conversation().await.unwrap();
234        let msg_id = insert_message(&memory, cid).await;
235
236        // Use sqlite directly to insert a valid summary with real FK references.
237        memory
238            .sqlite()
239            .save_summary(
240                cid,
241                "session about Rust and async",
242                Some(msg_id),
243                Some(msg_id),
244                10,
245            )
246            .await
247            .unwrap();
248
249        let result = memory.has_session_summary(cid).await.unwrap();
250        assert!(result, "must return true after a summary is persisted");
251    }
252
253    #[tokio::test]
254    async fn has_session_summary_is_isolated_per_conversation() {
255        let memory = make_memory().await;
256        let cid_a = memory.sqlite().create_conversation().await.unwrap();
257        let cid_b = memory.sqlite().create_conversation().await.unwrap();
258        let msg_id = insert_message(&memory, cid_a).await;
259
260        memory
261            .sqlite()
262            .save_summary(
263                cid_a,
264                "summary for conversation A",
265                Some(msg_id),
266                Some(msg_id),
267                5,
268            )
269            .await
270            .unwrap();
271
272        assert!(
273            memory.has_session_summary(cid_a).await.unwrap(),
274            "cid_a must have a summary"
275        );
276        assert!(
277            !memory.has_session_summary(cid_b).await.unwrap(),
278            "cid_b must not be affected by cid_a summary"
279        );
280    }
281
282    #[test]
283    fn store_session_summary_point_id_is_deterministic() {
284        // Same conversation_id must always produce the same UUID v5 point ID,
285        // ensuring that repeated compaction calls upsert rather than insert a new point.
286        const NS: uuid::Uuid = uuid::Uuid::NAMESPACE_OID;
287        let cid = ConversationId(42);
288        let id1 = uuid::Uuid::new_v5(&NS, cid.0.to_string().as_bytes()).to_string();
289        let id2 = uuid::Uuid::new_v5(&NS, cid.0.to_string().as_bytes()).to_string();
290        assert_eq!(
291            id1, id2,
292            "point_id must be deterministic for the same conversation_id"
293        );
294
295        let cid2 = ConversationId(43);
296        let id3 = uuid::Uuid::new_v5(&NS, cid2.0.to_string().as_bytes()).to_string();
297        assert_ne!(
298            id1, id3,
299            "different conversation_ids must produce different point_ids"
300        );
301    }
302
303    #[test]
304    fn store_session_summary_point_id_boundary_ids() {
305        // conversation_id = 0 and negative values are valid i64 variants — confirm they produce
306        // valid, distinct, and stable UUIDs.
307        const NS: uuid::Uuid = uuid::Uuid::NAMESPACE_OID;
308
309        let id_zero_a = uuid::Uuid::new_v5(&NS, ConversationId(0).0.to_string().as_bytes());
310        let id_zero_b = uuid::Uuid::new_v5(&NS, ConversationId(0).0.to_string().as_bytes());
311        assert_eq!(id_zero_a, id_zero_b, "zero conversation_id must be stable");
312
313        let id_neg = uuid::Uuid::new_v5(&NS, ConversationId(-1).0.to_string().as_bytes());
314        assert_ne!(
315            id_zero_a, id_neg,
316            "zero and -1 conversation_ids must produce different point_ids"
317        );
318
319        // Confirm the UUID version is 5 (deterministic SHA-1 name-based).
320        assert_eq!(
321            id_zero_a.get_version_num(),
322            5,
323            "generated UUID must be version 5"
324        );
325    }
326
327    #[tokio::test]
328    async fn store_shutdown_summary_succeeds_with_null_message_ids() {
329        let memory = make_memory().await;
330        let cid = memory.sqlite().create_conversation().await.unwrap();
331
332        let result = memory
333            .store_shutdown_summary(cid, "summary text", &[])
334            .await;
335
336        assert!(
337            result.is_ok(),
338            "shutdown summary must succeed without messages"
339        );
340        assert!(
341            memory.has_session_summary(cid).await.unwrap(),
342            "SQLite must record the shutdown summary"
343        );
344    }
345}