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    #[cfg_attr(
133        feature = "profiling",
134        tracing::instrument(name = "memory.cross_session", skip_all, fields(result_count = tracing::field::Empty))
135    )]
136    pub async fn search_session_summaries(
137        &self,
138        query: &str,
139        limit: usize,
140        exclude_conversation_id: Option<ConversationId>,
141    ) -> Result<Vec<SessionSummaryResult>, MemoryError> {
142        let Some(qdrant) = &self.qdrant else {
143            tracing::debug!("session-summaries: skipped, no vector store");
144            return Ok(Vec::new());
145        };
146        if !self.provider.supports_embeddings() {
147            tracing::debug!("session-summaries: skipped, no embedding support");
148            return Ok(Vec::new());
149        }
150
151        let vector = self.provider.embed(query).await?;
152        let vector_size = u64::try_from(vector.len()).unwrap_or(896);
153        qdrant
154            .ensure_named_collection(SESSION_SUMMARIES_COLLECTION, vector_size)
155            .await?;
156
157        let filter = exclude_conversation_id.map(|cid| VectorFilter {
158            must: vec![],
159            must_not: vec![FieldCondition {
160                field: "conversation_id".into(),
161                value: FieldValue::Integer(cid.0),
162            }],
163        });
164
165        let points = qdrant
166            .search_collection(SESSION_SUMMARIES_COLLECTION, &vector, limit, filter)
167            .await?;
168
169        tracing::debug!(
170            results = points.len(),
171            limit,
172            exclude_conversation_id = exclude_conversation_id.map(|c| c.0),
173            "session-summaries: search complete"
174        );
175
176        let results = points
177            .into_iter()
178            .filter_map(|point| {
179                let summary_text = point.payload.get("summary_text")?.as_str()?.to_owned();
180                let conversation_id =
181                    ConversationId(point.payload.get("conversation_id")?.as_i64()?);
182                Some(SessionSummaryResult {
183                    summary_text,
184                    score: point.score,
185                    conversation_id,
186                })
187            })
188            .collect();
189
190        Ok(results)
191    }
192}
193
194#[cfg(test)]
195mod tests {
196    use zeph_llm::any::AnyProvider;
197    use zeph_llm::mock::MockProvider;
198
199    use crate::types::MessageId;
200
201    use super::*;
202
203    async fn make_memory() -> SemanticMemory {
204        SemanticMemory::new(
205            ":memory:",
206            "http://127.0.0.1:1",
207            AnyProvider::Mock(MockProvider::default()),
208            "test-model",
209        )
210        .await
211        .unwrap()
212    }
213
214    /// Insert a real message into the conversation and return its `MessageId`.
215    /// Required because the `summaries` table has FK constraints on `messages.id`.
216    async fn insert_message(memory: &SemanticMemory, cid: ConversationId) -> MessageId {
217        memory
218            .sqlite()
219            .save_message(cid, "user", "test message")
220            .await
221            .unwrap()
222    }
223
224    #[tokio::test]
225    async fn has_session_summary_returns_false_when_no_summaries() {
226        let memory = make_memory().await;
227        let cid = memory.sqlite().create_conversation().await.unwrap();
228
229        let result = memory.has_session_summary(cid).await.unwrap();
230        assert!(!result, "new conversation must have no summaries");
231    }
232
233    #[tokio::test]
234    async fn has_session_summary_returns_true_after_summary_stored_via_sqlite() {
235        let memory = make_memory().await;
236        let cid = memory.sqlite().create_conversation().await.unwrap();
237        let msg_id = insert_message(&memory, cid).await;
238
239        // Use sqlite directly to insert a valid summary with real FK references.
240        memory
241            .sqlite()
242            .save_summary(
243                cid,
244                "session about Rust and async",
245                Some(msg_id),
246                Some(msg_id),
247                10,
248            )
249            .await
250            .unwrap();
251
252        let result = memory.has_session_summary(cid).await.unwrap();
253        assert!(result, "must return true after a summary is persisted");
254    }
255
256    #[tokio::test]
257    async fn has_session_summary_is_isolated_per_conversation() {
258        let memory = make_memory().await;
259        let cid_a = memory.sqlite().create_conversation().await.unwrap();
260        let cid_b = memory.sqlite().create_conversation().await.unwrap();
261        let msg_id = insert_message(&memory, cid_a).await;
262
263        memory
264            .sqlite()
265            .save_summary(
266                cid_a,
267                "summary for conversation A",
268                Some(msg_id),
269                Some(msg_id),
270                5,
271            )
272            .await
273            .unwrap();
274
275        assert!(
276            memory.has_session_summary(cid_a).await.unwrap(),
277            "cid_a must have a summary"
278        );
279        assert!(
280            !memory.has_session_summary(cid_b).await.unwrap(),
281            "cid_b must not be affected by cid_a summary"
282        );
283    }
284
285    #[test]
286    fn store_session_summary_point_id_is_deterministic() {
287        // Same conversation_id must always produce the same UUID v5 point ID,
288        // ensuring that repeated compaction calls upsert rather than insert a new point.
289        const NS: uuid::Uuid = uuid::Uuid::NAMESPACE_OID;
290        let cid = ConversationId(42);
291        let id1 = uuid::Uuid::new_v5(&NS, cid.0.to_string().as_bytes()).to_string();
292        let id2 = uuid::Uuid::new_v5(&NS, cid.0.to_string().as_bytes()).to_string();
293        assert_eq!(
294            id1, id2,
295            "point_id must be deterministic for the same conversation_id"
296        );
297
298        let cid2 = ConversationId(43);
299        let id3 = uuid::Uuid::new_v5(&NS, cid2.0.to_string().as_bytes()).to_string();
300        assert_ne!(
301            id1, id3,
302            "different conversation_ids must produce different point_ids"
303        );
304    }
305
306    #[test]
307    fn store_session_summary_point_id_boundary_ids() {
308        // conversation_id = 0 and negative values are valid i64 variants — confirm they produce
309        // valid, distinct, and stable UUIDs.
310        const NS: uuid::Uuid = uuid::Uuid::NAMESPACE_OID;
311
312        let id_zero_a = uuid::Uuid::new_v5(&NS, ConversationId(0).0.to_string().as_bytes());
313        let id_zero_b = uuid::Uuid::new_v5(&NS, ConversationId(0).0.to_string().as_bytes());
314        assert_eq!(id_zero_a, id_zero_b, "zero conversation_id must be stable");
315
316        let id_neg = uuid::Uuid::new_v5(&NS, ConversationId(-1).0.to_string().as_bytes());
317        assert_ne!(
318            id_zero_a, id_neg,
319            "zero and -1 conversation_ids must produce different point_ids"
320        );
321
322        // Confirm the UUID version is 5 (deterministic SHA-1 name-based).
323        assert_eq!(
324            id_zero_a.get_version_num(),
325            5,
326            "generated UUID must be version 5"
327        );
328    }
329
330    #[tokio::test]
331    async fn store_shutdown_summary_succeeds_with_null_message_ids() {
332        let memory = make_memory().await;
333        let cid = memory.sqlite().create_conversation().await.unwrap();
334
335        let result = memory
336            .store_shutdown_summary(cid, "summary text", &[])
337            .await;
338
339        assert!(
340            result.is_ok(),
341            "shutdown summary must succeed without messages"
342        );
343        assert!(
344            memory.has_session_summary(cid).await.unwrap(),
345            "SQLite must record the shutdown summary"
346        );
347    }
348}