1use crate::embedding::EmbeddingProvider;
54use crate::key::encode_segment;
55use crate::service::*;
56use adk_core::Result;
57use async_trait::async_trait;
58use chrono::DateTime;
59use neo4rs::Graph;
60use std::collections::HashSet;
61use std::sync::Arc;
62use tracing::instrument;
63
64pub struct Neo4jMemoryService {
80 graph: Graph,
81 embedding_provider: Option<Arc<dyn EmbeddingProvider>>,
82 vector_candidate_cap: usize,
83 default_ttl: Option<std::time::Duration>,
84}
85
86pub const DEFAULT_VECTOR_CANDIDATE_CAP: usize = 1000;
90
91const VECTOR_OVERFETCH_FACTOR: usize = 10;
94
95const SCHEMA_ALREADY_EXISTS: [&str; 4] = [
97 "Neo.ClientError.Schema.EquivalentSchemaRuleAlreadyExists",
98 "Neo.ClientError.Schema.ConstraintAlreadyExists",
99 "Neo.ClientError.Schema.IndexAlreadyExists",
100 "Neo.ClientError.Schema.ConstraintWithNameAlreadyExists",
101];
102
103async fn run_schema_statement(
106 graph: &Graph,
107 cypher: &str,
108) -> std::result::Result<(), neo4rs::Error> {
109 match graph.run(neo4rs::query(cypher)).await {
110 Err(neo4rs::Error::Neo4j(error)) if SCHEMA_ALREADY_EXISTS.contains(&error.code()) => Ok(()),
111 result => result,
112 }
113}
114
115fn vector_candidate_count(limit: usize, cap: usize) -> usize {
119 limit.saturating_mul(VECTOR_OVERFETCH_FACTOR).min(cap).max(limit)
120}
121
122fn scope_segment(project_id: Option<&str>) -> String {
127 match project_id {
128 None => "g".to_string(),
129 Some(project) => format!("p:{}", encode_segment(project)),
130 }
131}
132
133fn session_entry_id(
139 app_name: &str,
140 user_id: &str,
141 project_id: Option<&str>,
142 session_id: &str,
143 index: usize,
144) -> String {
145 format!(
146 "s:{}:{}:{}:{}:{index}",
147 encode_segment(app_name),
148 encode_segment(user_id),
149 scope_segment(project_id),
150 encode_segment(session_id)
151 )
152}
153
154fn direct_entry_id(app_name: &str, user_id: &str, project_id: &str, unique: uuid::Uuid) -> String {
156 format!(
157 "d:{}:{}:{}:{unique}",
158 encode_segment(app_name),
159 encode_segment(user_id),
160 scope_segment(Some(project_id))
161 )
162}
163
164impl Neo4jMemoryService {
165 const REGISTRY_LABEL: &'static str = "_AdkMemoryMigration";
167
168 const NEO4J_MEMORY_MIGRATIONS: &'static [(i64, &'static str, &'static [&'static str])] = &[
176 (
177 1,
178 "create initial constraints and indexes",
179 &[
180 "CREATE CONSTRAINT memory_entry_unique IF NOT EXISTS \
181 FOR (m:MemoryEntry) REQUIRE (m.id) IS UNIQUE",
182 "CREATE INDEX memory_app_user IF NOT EXISTS \
183 FOR (m:MemoryEntry) ON (m.app_name, m.user_id)",
184 "CREATE FULLTEXT INDEX memory_content IF NOT EXISTS \
185 FOR (m:MemoryEntry) ON EACH [m.content_text]",
186 ],
187 ),
188 (
189 2,
190 "add project_id index",
191 &["CREATE INDEX memory_project_id IF NOT EXISTS \
192 FOR (m:MemoryEntry) ON (m.project_id)"],
193 ),
194 (
195 3,
196 "add memory_id and expires_at indexes",
197 &[
198 "CREATE INDEX memory_memory_id IF NOT EXISTS \
199 FOR (m:MemoryEntry) ON (m.app_name, m.user_id, m.memory_id)",
200 "CREATE INDEX memory_expires_at IF NOT EXISTS \
201 FOR (m:MemoryEntry) ON (m.expires_at)",
202 ],
203 ),
204 ];
205
206 pub fn new(
226 graph: Graph,
227 embedding_provider: Option<Arc<dyn EmbeddingProvider>>,
228 ) -> adk_core::Result<Self> {
229 Ok(Self {
230 graph,
231 embedding_provider,
232 vector_candidate_cap: DEFAULT_VECTOR_CANDIDATE_CAP,
233 default_ttl: None,
234 })
235 }
236
237 pub fn with_default_ttl(mut self, ttl: std::time::Duration) -> Self {
249 self.default_ttl = Some(ttl);
250 self
251 }
252
253 pub fn with_vector_candidate_cap(mut self, cap: usize) -> Self {
271 self.vector_candidate_cap = cap;
272 self
273 }
274
275 pub fn graph(&self) -> &Graph {
277 &self.graph
278 }
279
280 pub async fn migrate(&self) -> adk_core::Result<()> {
296 run_schema_statement(
298 &self.graph,
299 &format!(
300 "CREATE CONSTRAINT {}_version_unique IF NOT EXISTS \
301 FOR (m:{}) REQUIRE (m.version) IS UNIQUE",
302 Self::REGISTRY_LABEL.to_lowercase(),
303 Self::REGISTRY_LABEL,
304 ),
305 )
306 .await
307 .map_err(|e| {
308 adk_core::AdkError::memory(format!("migration registry creation failed: {e}"))
309 })?;
310
311 let mut max_applied = self.read_max_applied_version().await?;
313
314 if max_applied == 0 {
317 let existing = self.detect_existing_tables().await?;
318 if existing
319 && let Some(&(version, description, _)) = Self::NEO4J_MEMORY_MIGRATIONS.first()
320 {
321 self.record_migration(version, description).await?;
322 max_applied = version;
323 }
324 }
325
326 let max_compiled = Self::NEO4J_MEMORY_MIGRATIONS.last().map(|s| s.0).unwrap_or(0);
328
329 if max_applied > max_compiled {
331 return Err(adk_core::AdkError::memory(format!(
332 "schema version mismatch: database is at v{max_applied} \
333 but code only knows up to v{max_compiled}. \
334 Upgrade your ADK version."
335 )));
336 }
337
338 for &(version, description, cypher_statements) in Self::NEO4J_MEMORY_MIGRATIONS {
340 if version <= max_applied {
341 continue;
342 }
343
344 for cypher in cypher_statements {
345 run_schema_statement(&self.graph, cypher).await.map_err(|e| {
346 adk_core::AdkError::memory(format!(
347 "{}",
348 crate::migration::MigrationError {
349 version,
350 description: description.to_string(),
351 cause: e.to_string(),
352 }
353 ))
354 })?;
355 }
356
357 self.record_migration(version, description).await?;
358 }
359
360 if let Some(provider) = &self.embedding_provider {
364 let dims = provider.dimensions();
365 let vector_index_query = format!(
366 "CREATE VECTOR INDEX memory_embedding IF NOT EXISTS \
367 FOR (m:MemoryEntry) ON (m.embedding) \
368 OPTIONS {{indexConfig: {{`vector.dimensions`: {dims}, \
369 `vector.similarity_function`: 'cosine'}}}}"
370 );
371 run_schema_statement(&self.graph, &vector_index_query).await.map_err(|e| {
372 adk_core::AdkError::memory(format!(
373 "migration failed: vector index creation failed: {e}"
374 ))
375 })?;
376 }
377
378 Ok(())
379 }
380
381 pub async fn schema_version(&self) -> Result<i64> {
384 self.read_max_applied_version().await
385 }
386
387 async fn read_max_applied_version(&self) -> Result<i64> {
389 let query_str =
390 format!("OPTIONAL MATCH (m:{}) RETURN max(m.version) AS max_v", Self::REGISTRY_LABEL);
391 let mut row_stream = self.graph.execute(neo4rs::query(&query_str)).await.map_err(|e| {
392 adk_core::AdkError::memory(format!("migration registry read failed: {e}"))
393 })?;
394
395 if let Some(row) = row_stream.next().await.map_err(|e| {
396 adk_core::AdkError::memory(format!("migration registry read failed: {e}"))
397 })? {
398 Ok(row.get::<i64>("max_v").unwrap_or(0))
400 } else {
401 Ok(0)
402 }
403 }
404
405 async fn detect_existing_tables(&self) -> Result<bool> {
409 let mut row_stream = self
410 .graph
411 .execute(neo4rs::query(
412 "SHOW INDEXES YIELD name WHERE name = 'memory_content' RETURN name",
413 ))
414 .await
415 .map_err(|e| adk_core::AdkError::memory(format!("baseline detection failed: {e}")))?;
416
417 let found = row_stream
418 .next()
419 .await
420 .map_err(|e| adk_core::AdkError::memory(format!("baseline detection failed: {e}")))?
421 .is_some();
422
423 Ok(found)
424 }
425
426 async fn record_migration(&self, version: i64, description: &str) -> Result<()> {
430 let query_str = format!(
431 "MERGE (m:{} {{version: $version}}) \
432 ON CREATE SET m.description = $description, m.applied_at = datetime()",
433 Self::REGISTRY_LABEL,
434 );
435 self.graph
436 .run(
437 neo4rs::query(&query_str)
438 .param("version", version)
439 .param("description", description.to_string()),
440 )
441 .await
442 .map_err(|e| {
443 adk_core::AdkError::memory(format!(
444 "{}",
445 crate::migration::MigrationError {
446 version,
447 description: description.to_string(),
448 cause: format!("registry record failed: {e}"),
449 }
450 ))
451 })?;
452 Ok(())
453 }
454
455 async fn ingest_session(
461 &self,
462 app_name: &str,
463 user_id: &str,
464 session_id: &str,
465 project_id: Option<&str>,
466 entries: Vec<MemoryEntry>,
467 ) -> Result<()> {
468 let operation = if project_id.is_some() { "add_session_to_project" } else { "add_session" };
469 let failed =
470 |e: neo4rs::Error| adk_core::AdkError::memory(format!("{operation} failed: {e}"));
471
472 let texts: Vec<String> =
473 entries.iter().map(|e| crate::text::extract_text(&e.content)).collect();
474
475 let embeddings = if let Some(provider) = &self.embedding_provider {
476 let non_empty_texts: Vec<String> = texts
477 .iter()
478 .map(|t| if t.is_empty() { " ".to_string() } else { t.clone() })
479 .collect();
480 let embeddings = provider.embed(&non_empty_texts).await.map_err(|e| {
481 adk_core::AdkError::memory(format!("embedding generation failed: {e}"))
482 })?;
483 if embeddings.len() != entries.len() {
484 return Err(adk_core::AdkError::memory(format!(
485 "embedding provider returned {} vectors for {} entries",
486 embeddings.len(),
487 entries.len()
488 )));
489 }
490 Some(embeddings)
491 } else {
492 None
493 };
494
495 let mut txn = self
496 .graph
497 .start_txn()
498 .await
499 .map_err(|e| adk_core::AdkError::memory(format!("transaction failed: {e}")))?;
500
501 txn.run(
502 neo4rs::query(
503 "MERGE (:MemorySession {session_id: $session_id, \
504 app_name: $app_name, user_id: $user_id})",
505 )
506 .param("session_id", session_id.to_string())
507 .param("app_name", app_name.to_string())
508 .param("user_id", user_id.to_string()),
509 )
510 .await
511 .map_err(failed)?;
512
513 let entry_ids: Vec<String> = (0..entries.len())
514 .map(|i| session_entry_id(app_name, user_id, project_id, session_id, i))
515 .collect();
516
517 let now = chrono::Utc::now();
518 for (i, entry) in entries.iter().enumerate() {
519 let memory_id = entry.id.clone().unwrap_or_else(|| entry_ids[i].clone());
520 let expires_at = crate::expiry::resolve_expiry(entry, self.default_ttl, now)
521 .map(|at| at.timestamp_millis());
522 let content_json = serde_json::to_string(&entry.content)
523 .map_err(|e| adk_core::AdkError::memory(format!("serialization failed: {e}")))?;
524 let embedding: Option<Vec<f64>> =
526 embeddings.as_ref().map(|embs| embs[i].iter().map(|&v| f64::from(v)).collect());
527
528 txn.run(
531 neo4rs::query(
532 "MATCH (s:MemorySession {session_id: $session_id, \
533 app_name: $app_name, user_id: $user_id}) \
534 MERGE (e:MemoryEntry {id: $id}) \
535 SET e.app_name = $app_name, e.user_id = $user_id, \
536 e.session_id = $session_id, e.content = $content, \
537 e.content_text = $content_text, e.author = $author, \
538 e.timestamp = $timestamp, e.embedding = $embedding, \
539 e.project_id = $project_id, e.memory_id = $memory_id, \
540 e.expires_at = $expires_at \
541 MERGE (s)-[:FROM_SESSION]->(e)",
542 )
543 .param("session_id", session_id.to_string())
544 .param("app_name", app_name.to_string())
545 .param("user_id", user_id.to_string())
546 .param("id", entry_ids[i].clone())
547 .param("content", content_json)
548 .param("content_text", texts[i].clone())
549 .param("author", entry.author.clone())
550 .param("timestamp", entry.timestamp.to_rfc3339())
551 .param("embedding", embedding)
552 .param("project_id", project_id.map(str::to_string))
553 .param("memory_id", memory_id)
554 .param("expires_at", expires_at),
555 )
556 .await
557 .map_err(failed)?;
558 }
559
560 for pair in entry_ids.windows(2) {
561 txn.run(
562 neo4rs::query(
563 "MATCH (prev:MemoryEntry {id: $prev_id}) \
564 MATCH (curr:MemoryEntry {id: $curr_id}) \
565 MERGE (prev)-[:FOLLOWS]->(curr)",
566 )
567 .param("prev_id", pair[0].clone())
568 .param("curr_id", pair[1].clone()),
569 )
570 .await
571 .map_err(|e| {
572 adk_core::AdkError::memory(format!("{operation} failed: FOLLOWS creation: {e}"))
573 })?;
574 }
575
576 txn.commit()
577 .await
578 .map_err(|e| adk_core::AdkError::memory(format!("commit failed: {e}")))?;
579
580 Ok(())
581 }
582}
583
584#[async_trait]
585impl MemoryService for Neo4jMemoryService {
586 #[instrument(skip_all, fields(app_name = %app_name, user_id = %user_id, session_id = %session_id, entry_count = entries.len()))]
587 async fn add_session(
588 &self,
589 app_name: &str,
590 user_id: &str,
591 session_id: &str,
592 entries: Vec<MemoryEntry>,
593 ) -> Result<()> {
594 if entries.is_empty() {
595 return Ok(());
596 }
597 self.ingest_session(app_name, user_id, session_id, None, entries).await
598 }
599
600 fn supports_project_scoping(&self) -> bool {
601 true
602 }
603
604 #[instrument(skip_all, fields(app_name = %app_name, user_id = %user_id, session_id = %session_id, project_id = %project_id, entry_count = entries.len()))]
605 async fn add_session_to_project(
606 &self,
607 app_name: &str,
608 user_id: &str,
609 session_id: &str,
610 project_id: &str,
611 entries: Vec<MemoryEntry>,
612 ) -> Result<()> {
613 validate_project_id(project_id)?;
614
615 if entries.is_empty() {
616 return Ok(());
617 }
618 self.ingest_session(app_name, user_id, session_id, Some(project_id), entries).await
619 }
620
621 #[instrument(skip_all, fields(app_name = %app_name, user_id = %user_id, project_id = %project_id))]
622 async fn add_entry_to_project(
623 &self,
624 app_name: &str,
625 user_id: &str,
626 project_id: &str,
627 entry: MemoryEntry,
628 ) -> Result<()> {
629 validate_project_id(project_id)?;
630
631 let content_text = crate::text::extract_text(&entry.content);
632 let content_json = serde_json::to_string(&entry.content)
633 .map_err(|e| adk_core::AdkError::memory(format!("serialization failed: {e}")))?;
634 let entry_id = direct_entry_id(app_name, user_id, project_id, uuid::Uuid::new_v4());
635 let memory_id = entry.id.clone().unwrap_or_else(|| entry_id.clone());
636 let expires_at =
637 crate::expiry::resolve_expiry(&entry, self.default_ttl, chrono::Utc::now())
638 .map(|at| at.timestamp_millis());
639
640 let embedding: Option<Vec<f64>> = match &self.embedding_provider {
641 Some(provider) => {
642 let text_for_embed =
643 if content_text.is_empty() { " ".to_string() } else { content_text.clone() };
644 let embeddings = provider.embed(&[text_for_embed]).await.map_err(|e| {
645 adk_core::AdkError::memory(format!("embedding generation failed: {e}"))
646 })?;
647 Some(embeddings[0].iter().map(|&v| f64::from(v)).collect())
648 }
649 None => None,
650 };
651
652 self.graph
654 .run(
655 neo4rs::query(
656 "CREATE (e:MemoryEntry { \
657 id: $id, app_name: $app_name, user_id: $user_id, \
658 content: $content, content_text: $content_text, \
659 author: $author, timestamp: $timestamp, \
660 embedding: $embedding, project_id: $project_id, \
661 memory_id: $memory_id, expires_at: $expires_at \
662 })",
663 )
664 .param("id", entry_id)
665 .param("app_name", app_name.to_string())
666 .param("user_id", user_id.to_string())
667 .param("content", content_json)
668 .param("content_text", content_text)
669 .param("author", entry.author.clone())
670 .param("timestamp", entry.timestamp.to_rfc3339())
671 .param("embedding", embedding)
672 .param("project_id", project_id.to_string())
673 .param("memory_id", memory_id)
674 .param("expires_at", expires_at),
675 )
676 .await
677 .map_err(|e| adk_core::AdkError::memory(format!("add_entry_to_project failed: {e}")))?;
678
679 Ok(())
680 }
681
682 #[instrument(skip_all, fields(app_name = %req.app_name, user_id = %req.user_id))]
683 async fn search(&self, req: SearchRequest) -> Result<SearchResponse> {
684 let limit = req.limit.unwrap_or(10);
685
686 let project_filter = match &req.project_id {
688 None => "AND node.project_id IS NULL".to_string(),
689 Some(_) => "AND (node.project_id IS NULL OR node.project_id = $project_id)".to_string(),
690 };
691 let now = chrono::Utc::now().timestamp_millis();
695
696 let results = if let Some(ref provider) = self.embedding_provider {
697 let query_embedding = provider
699 .embed(std::slice::from_ref(&req.query))
700 .await
701 .map_err(|e| adk_core::AdkError::memory(format!("query embedding failed: {e}")))?;
702 let query_vec: Vec<f64> = query_embedding[0].iter().map(|&v| v as f64).collect();
703
704 let cypher = format!(
707 "CALL db.index.vector.queryNodes('memory_embedding', $candidates, \
708 $query_embedding) \
709 YIELD node, score \
710 WHERE node.app_name = $app_name AND node.user_id = $user_id \
711 {project_filter} \
712 AND (node.expires_at IS NULL OR node.expires_at > $now) \
713 WITH node, score ORDER BY score DESC LIMIT $limit \
714 OPTIONAL MATCH (node)-[:FOLLOWS]-(adjacent:MemoryEntry) \
715 WHERE adjacent.expires_at IS NULL OR adjacent.expires_at > $now \
716 RETURN node.id AS id, node.content AS content, \
717 node.author AS author, node.timestamp AS timestamp, \
718 coalesce(node.memory_id, node.id) AS memory_id, \
719 node.expires_at AS expires_at, \
720 score, \
721 collect(adjacent.id) AS adj_ids, \
722 collect(coalesce(adjacent.memory_id, adjacent.id)) AS adj_memory_ids, \
723 collect(coalesce(adjacent.expires_at, -1)) AS adj_expires_at, \
724 collect(adjacent.content) AS adj_contents, \
725 collect(adjacent.author) AS adj_authors, \
726 collect(adjacent.timestamp) AS adj_timestamps \
727 ORDER BY score DESC"
728 );
729
730 let candidates = vector_candidate_count(limit, self.vector_candidate_cap);
731 let mut query = neo4rs::query(&cypher)
732 .param("candidates", candidates as i64)
733 .param("limit", limit as i64)
734 .param("query_embedding", query_vec)
735 .param("app_name", req.app_name.clone())
736 .param("user_id", req.user_id.clone())
737 .param("now", now);
738
739 if let Some(ref pid) = req.project_id {
740 query = query.param("project_id", pid.clone());
741 }
742
743 let mut row_stream = self
744 .graph
745 .execute(query)
746 .await
747 .map_err(|e| adk_core::AdkError::memory(format!("search failed: {e}")))?;
748
749 let mut entries = Vec::new();
750 let mut seen_ids: HashSet<String> = HashSet::new();
751
752 while let Some(row) = row_stream
753 .next()
754 .await
755 .map_err(|e| adk_core::AdkError::memory(format!("search failed: {e}")))?
756 {
757 if let Some(entry) = row_to_memory_entry(&row) {
759 let id = row.get::<String>("id").unwrap_or_default();
760 if seen_ids.insert(id) {
761 entries.push(entry);
762 }
763 }
764
765 collect_adjacent_entries(&row, &mut seen_ids, &mut entries);
767 }
768
769 entries
770 } else {
771 let cypher = format!(
773 "CALL db.index.fulltext.queryNodes('memory_content', $query) \
774 YIELD node, score \
775 WHERE node.app_name = $app_name AND node.user_id = $user_id \
776 {project_filter} \
777 AND (node.expires_at IS NULL OR node.expires_at > $now) \
778 OPTIONAL MATCH (node)-[:FOLLOWS]-(adjacent:MemoryEntry) \
779 WHERE adjacent.expires_at IS NULL OR adjacent.expires_at > $now \
780 RETURN node.id AS id, node.content AS content, \
781 node.author AS author, node.timestamp AS timestamp, \
782 coalesce(node.memory_id, node.id) AS memory_id, \
783 node.expires_at AS expires_at, \
784 score, \
785 collect(adjacent.id) AS adj_ids, \
786 collect(coalesce(adjacent.memory_id, adjacent.id)) AS adj_memory_ids, \
787 collect(coalesce(adjacent.expires_at, -1)) AS adj_expires_at, \
788 collect(adjacent.content) AS adj_contents, \
789 collect(adjacent.author) AS adj_authors, \
790 collect(adjacent.timestamp) AS adj_timestamps \
791 ORDER BY score DESC \
792 LIMIT $limit"
793 );
794
795 let mut query = neo4rs::query(&cypher)
796 .param("query", req.query.clone())
797 .param("app_name", req.app_name.clone())
798 .param("user_id", req.user_id.clone())
799 .param("limit", limit as i64)
800 .param("now", now);
801
802 if let Some(ref pid) = req.project_id {
803 query = query.param("project_id", pid.clone());
804 }
805
806 let mut row_stream = self
807 .graph
808 .execute(query)
809 .await
810 .map_err(|e| adk_core::AdkError::memory(format!("search failed: {e}")))?;
811
812 let mut entries = Vec::new();
813 let mut seen_ids: HashSet<String> = HashSet::new();
814
815 while let Some(row) = row_stream
816 .next()
817 .await
818 .map_err(|e| adk_core::AdkError::memory(format!("search failed: {e}")))?
819 {
820 if let Some(entry) = row_to_memory_entry(&row) {
822 let id = row.get::<String>("id").unwrap_or_default();
823 if seen_ids.insert(id) {
824 entries.push(entry);
825 }
826 }
827
828 collect_adjacent_entries(&row, &mut seen_ids, &mut entries);
830 }
831
832 entries
833 };
834
835 Ok(SearchResponse { memories: results })
836 }
837
838 #[instrument(skip_all, fields(app_name = %app_name, user_id = %user_id, project_id = %project_id))]
839 async fn delete_entries_in_project(
840 &self,
841 app_name: &str,
842 user_id: &str,
843 project_id: &str,
844 query: &str,
845 ) -> Result<u64> {
846 validate_project_id(project_id)?;
847
848 let mut row_stream = self
850 .graph
851 .execute(
852 neo4rs::query(
853 "CALL db.index.fulltext.queryNodes('memory_content', $query) \
854 YIELD node \
855 WHERE node.app_name = $app_name AND node.user_id = $user_id \
856 AND node.project_id = $project_id \
857 DETACH DELETE node \
858 RETURN count(node) AS deleted_count",
859 )
860 .param("query", query.to_string())
861 .param("app_name", app_name.to_string())
862 .param("user_id", user_id.to_string())
863 .param("project_id", project_id.to_string()),
864 )
865 .await
866 .map_err(|e| {
867 adk_core::AdkError::memory(format!("delete_entries_in_project failed: {e}"))
868 })?;
869
870 let count = if let Some(row) = row_stream.next().await.map_err(|e| {
871 adk_core::AdkError::memory(format!("delete_entries_in_project failed: {e}"))
872 })? {
873 row.get::<i64>("deleted_count").unwrap_or(0) as u64
874 } else {
875 0
876 };
877
878 Ok(count)
879 }
880
881 #[instrument(skip_all, fields(app_name = %app_name, user_id = %user_id, project_id = %project_id))]
882 async fn delete_project(&self, app_name: &str, user_id: &str, project_id: &str) -> Result<u64> {
883 validate_project_id(project_id)?;
884
885 let mut row_stream = self
886 .graph
887 .execute(
888 neo4rs::query(
889 "MATCH (e:MemoryEntry {app_name: $app_name, user_id: $user_id, \
890 project_id: $project_id}) \
891 DETACH DELETE e \
892 RETURN count(e) AS deleted_count",
893 )
894 .param("app_name", app_name.to_string())
895 .param("user_id", user_id.to_string())
896 .param("project_id", project_id.to_string()),
897 )
898 .await
899 .map_err(|e| adk_core::AdkError::memory(format!("delete_project failed: {e}")))?;
900
901 let count = if let Some(row) = row_stream
902 .next()
903 .await
904 .map_err(|e| adk_core::AdkError::memory(format!("delete_project failed: {e}")))?
905 {
906 row.get::<i64>("deleted_count").unwrap_or(0) as u64
907 } else {
908 0
909 };
910
911 self.graph
913 .run(
914 neo4rs::query(
915 "MATCH (s:MemorySession {app_name: $app_name, user_id: $user_id}) \
916 WHERE NOT (s)-[:FROM_SESSION]->() \
917 DELETE s",
918 )
919 .param("app_name", app_name.to_string())
920 .param("user_id", user_id.to_string()),
921 )
922 .await
923 .map_err(|e| {
924 adk_core::AdkError::memory(format!("delete_project cleanup failed: {e}"))
925 })?;
926
927 Ok(count)
928 }
929
930 #[instrument(skip_all, fields(app_name = %app_name, user_id = %user_id))]
931 async fn export_user(&self, app_name: &str, user_id: &str) -> Result<Vec<UserMemory>> {
932 let failed =
933 |e: neo4rs::Error| adk_core::AdkError::memory(format!("export_user failed: {e}"));
934 let mut rows = self
935 .graph
936 .execute(
937 neo4rs::query(
938 "MATCH (e:MemoryEntry {app_name: $app_name, user_id: $user_id}) \
939 RETURN e.content AS content, e.author AS author, e.timestamp AS timestamp, \
940 coalesce(e.memory_id, e.id) AS memory_id, e.expires_at AS expires_at, \
941 e.session_id AS session_id, e.project_id AS project_id \
942 ORDER BY e.timestamp, e.id",
943 )
944 .param("app_name", app_name.to_string())
945 .param("user_id", user_id.to_string()),
946 )
947 .await
948 .map_err(failed)?;
949 let mut memories = Vec::new();
950 while let Some(row) = rows.next().await.map_err(failed)? {
951 let entry = row_to_memory_entry(&row).ok_or_else(|| {
952 adk_core::AdkError::memory("export_user found an entry with no content")
953 })?;
954 memories.push(UserMemory {
955 entry,
956 session_id: row.get::<String>("session_id").ok(),
957 project_id: row.get::<String>("project_id").ok(),
958 });
959 }
960 Ok(memories)
961 }
962
963 #[instrument(skip_all, fields(app_name = %app_name, user_id = %user_id))]
964 async fn delete_user(&self, app_name: &str, user_id: &str) -> Result<()> {
965 self.graph
966 .run(
967 neo4rs::query(
968 "MATCH (e:MemoryEntry {app_name: $app_name, user_id: $user_id}) \
969 DETACH DELETE e",
970 )
971 .param("app_name", app_name.to_string())
972 .param("user_id", user_id.to_string()),
973 )
974 .await
975 .map_err(|e| adk_core::AdkError::memory(format!("delete_user failed: {e}")))?;
976
977 self.graph
979 .run(
980 neo4rs::query(
981 "MATCH (s:MemorySession {app_name: $app_name, user_id: $user_id}) \
982 WHERE NOT (s)-[:FROM_SESSION]->() \
983 DELETE s",
984 )
985 .param("app_name", app_name.to_string())
986 .param("user_id", user_id.to_string()),
987 )
988 .await
989 .map_err(|e| adk_core::AdkError::memory(format!("delete_user cleanup failed: {e}")))?;
990
991 Ok(())
992 }
993
994 #[instrument(skip_all, fields(app_name = %app_name, user_id = %user_id, session_id = %session_id))]
995 async fn delete_session(&self, app_name: &str, user_id: &str, session_id: &str) -> Result<()> {
996 self.graph
997 .run(
998 neo4rs::query(
999 "MATCH (e:MemoryEntry {app_name: $app_name, user_id: $user_id, session_id: $session_id}) \
1000 DETACH DELETE e",
1001 )
1002 .param("app_name", app_name.to_string())
1003 .param("user_id", user_id.to_string())
1004 .param("session_id", session_id.to_string()),
1005 )
1006 .await
1007 .map_err(|e| adk_core::AdkError::memory(format!("delete_session failed: {e}")))?;
1008
1009 self.graph
1011 .run(
1012 neo4rs::query(
1013 "MATCH (s:MemorySession {session_id: $session_id, app_name: $app_name, user_id: $user_id}) \
1014 WHERE NOT (s)-[:FROM_SESSION]->() \
1015 DELETE s",
1016 )
1017 .param("app_name", app_name.to_string())
1018 .param("user_id", user_id.to_string())
1019 .param("session_id", session_id.to_string()),
1020 )
1021 .await
1022 .map_err(|e| adk_core::AdkError::memory(format!("delete_session cleanup failed: {e}")))?;
1023
1024 Ok(())
1025 }
1026
1027 #[instrument(skip_all, fields(app_name = %app_name, user_id = %user_id))]
1028 async fn delete_memory(&self, app_name: &str, user_id: &str, memory_id: &str) -> Result<u64> {
1029 let failed =
1030 |e: neo4rs::Error| adk_core::AdkError::memory(format!("delete_memory failed: {e}"));
1031 let mut rows = self
1032 .graph
1033 .execute(
1034 neo4rs::query(
1035 "MATCH (e:MemoryEntry {app_name: $app_name, user_id: $user_id}) \
1036 WHERE coalesce(e.memory_id, e.id) = $memory_id \
1037 DETACH DELETE e \
1038 RETURN count(e) AS deleted_count",
1039 )
1040 .param("app_name", app_name.to_string())
1041 .param("user_id", user_id.to_string())
1042 .param("memory_id", memory_id.to_string()),
1043 )
1044 .await
1045 .map_err(failed)?;
1046 let removed = match rows.next().await.map_err(failed)? {
1047 Some(row) => row.get::<i64>("deleted_count").unwrap_or(0) as u64,
1048 None => 0,
1049 };
1050 Ok(removed)
1051 }
1052
1053 #[instrument(skip_all)]
1054 async fn purge_expired(&self) -> Result<u64> {
1055 let failed =
1056 |e: neo4rs::Error| adk_core::AdkError::memory(format!("purge_expired failed: {e}"));
1057 let mut rows = self
1058 .graph
1059 .execute(
1060 neo4rs::query(
1061 "MATCH (e:MemoryEntry) WHERE e.expires_at <= $now \
1062 DETACH DELETE e \
1063 RETURN count(e) AS deleted_count",
1064 )
1065 .param("now", chrono::Utc::now().timestamp_millis()),
1066 )
1067 .await
1068 .map_err(failed)?;
1069 let removed = match rows.next().await.map_err(failed)? {
1070 Some(row) => row.get::<i64>("deleted_count").unwrap_or(0) as u64,
1071 None => 0,
1072 };
1073 self.graph
1075 .run(neo4rs::query(
1076 "MATCH (s:MemorySession) WHERE NOT (s)-[:FROM_SESSION]->() DELETE s",
1077 ))
1078 .await
1079 .map_err(failed)?;
1080 Ok(removed)
1081 }
1082
1083 #[instrument(skip_all)]
1084 async fn health_check(&self) -> Result<()> {
1085 let _ = self
1086 .graph
1087 .execute(neo4rs::query("RETURN 1"))
1088 .await
1089 .map_err(|e| adk_core::AdkError::memory(format!("health check failed: {e}")))?;
1090 Ok(())
1091 }
1092}
1093
1094fn row_to_memory_entry(row: &neo4rs::Row) -> Option<MemoryEntry> {
1096 let content_str = row.get::<String>("content").ok()?;
1097 let content: adk_core::Content = serde_json::from_str(&content_str)
1098 .unwrap_or_else(|_| adk_core::Content { role: "user".to_string(), parts: vec![] });
1099 let author = row.get::<String>("author").unwrap_or_else(|_| "unknown".to_string());
1100 let timestamp_str = row.get::<String>("timestamp").unwrap_or_default();
1101 let timestamp = DateTime::parse_from_rfc3339(×tamp_str)
1102 .map(|dt| dt.with_timezone(&chrono::Utc))
1103 .unwrap_or_default();
1104
1105 let mut entry = MemoryEntry::new(content, author).with_timestamp(timestamp);
1106 entry.id = row.get::<String>("memory_id").ok();
1107 entry.expires_at = row.get::<i64>("expires_at").ok().and_then(DateTime::from_timestamp_millis);
1108 Some(entry)
1109}
1110
1111fn collect_adjacent_entries(
1113 row: &neo4rs::Row,
1114 seen_ids: &mut HashSet<String>,
1115 entries: &mut Vec<MemoryEntry>,
1116) {
1117 let adj_ids: Vec<String> = row.get("adj_ids").unwrap_or_default();
1118 let adj_contents: Vec<String> = row.get("adj_contents").unwrap_or_default();
1119 let adj_authors: Vec<String> = row.get("adj_authors").unwrap_or_default();
1120 let adj_timestamps: Vec<String> = row.get("adj_timestamps").unwrap_or_default();
1121 let adj_memory_ids: Vec<String> = row.get("adj_memory_ids").unwrap_or_default();
1122 let adj_expires_at: Vec<i64> = row.get("adj_expires_at").unwrap_or_default();
1123
1124 for (i, adj_id) in adj_ids.iter().enumerate() {
1125 if !seen_ids.insert(adj_id.clone()) {
1126 continue;
1127 }
1128
1129 let content_str = adj_contents.get(i).cloned().unwrap_or_default();
1130 let content: adk_core::Content = serde_json::from_str(&content_str)
1131 .unwrap_or_else(|_| adk_core::Content { role: "user".to_string(), parts: vec![] });
1132 let author = adj_authors.get(i).cloned().unwrap_or_else(|| "unknown".to_string());
1133 let timestamp_str = adj_timestamps.get(i).cloned().unwrap_or_default();
1134 let timestamp = DateTime::parse_from_rfc3339(×tamp_str)
1135 .map(|dt| dt.with_timezone(&chrono::Utc))
1136 .unwrap_or_default();
1137
1138 let mut entry = MemoryEntry::new(content, author).with_timestamp(timestamp);
1139 entry.id = adj_memory_ids.get(i).cloned();
1140 entry.expires_at = adj_expires_at
1142 .get(i)
1143 .filter(|at| **at >= 0)
1144 .and_then(|at| DateTime::from_timestamp_millis(*at));
1145 entries.push(entry);
1146 }
1147}
1148
1149#[cfg(test)]
1150mod tests {
1151 use super::*;
1152
1153 #[test]
1154 fn test_session_entry_ids_are_scoped_by_tenant_project_and_session() {
1155 let base = session_entry_id("app", "alice", None, "s1", 0);
1156 let variants = [
1157 session_entry_id("other", "alice", None, "s1", 0),
1158 session_entry_id("app", "bob", None, "s1", 0),
1159 session_entry_id("app", "alice", Some("proj"), "s1", 0),
1160 session_entry_id("app", "alice", None, "s2", 0),
1161 session_entry_id("app", "alice", None, "s1", 1),
1162 ];
1163 for variant in &variants {
1164 assert_ne!(&base, variant);
1165 }
1166 }
1167
1168 #[test]
1169 fn test_session_entry_ids_are_stable_for_re_ingestion() {
1170 assert_eq!(
1171 session_entry_id("app", "alice", Some("proj"), "s1", 3),
1172 session_entry_id("app", "alice", Some("proj"), "s1", 3)
1173 );
1174 }
1175
1176 #[test]
1177 fn test_session_entry_ids_encode_delimiters() {
1178 assert_eq!(
1179 [
1180 session_entry_id("a:b", "u", None, "s", 0),
1181 session_entry_id("a", "u", Some("p:1"), "s%", 2),
1182 ],
1183 ["s:a%3Ab:u:g:s:0".to_string(), "s:a:u:p:p%3A1:s%25:2".to_string()]
1184 );
1185 assert_ne!(
1186 session_entry_id("a:b", "c", None, "s", 0),
1187 session_entry_id("a", "b:c", None, "s", 0)
1188 );
1189 assert_ne!(
1191 session_entry_id("a", "u", None, "p:x:s", 0),
1192 session_entry_id("a", "u", Some("x"), "s", 0)
1193 );
1194 }
1195
1196 #[test]
1197 fn test_direct_entry_ids_never_collide() {
1198 let first = direct_entry_id("app", "alice", "proj", uuid::Uuid::new_v4());
1199 let second = direct_entry_id("app", "alice", "proj", uuid::Uuid::new_v4());
1200 assert_ne!(first, second);
1201 assert!(first.starts_with("d:app:alice:p:proj:"), "{first}");
1202
1203 let fixed = uuid::Uuid::nil();
1204 assert_ne!(
1205 direct_entry_id("app", "alice", "proj", fixed),
1206 direct_entry_id("app", "bob", "proj", fixed)
1207 );
1208 }
1209
1210 #[test]
1211 fn test_vector_candidate_count() {
1212 assert_eq!(
1213 [
1214 vector_candidate_count(10, DEFAULT_VECTOR_CANDIDATE_CAP),
1215 vector_candidate_count(500, DEFAULT_VECTOR_CANDIDATE_CAP),
1216 vector_candidate_count(5000, DEFAULT_VECTOR_CANDIDATE_CAP),
1217 vector_candidate_count(0, DEFAULT_VECTOR_CANDIDATE_CAP),
1218 vector_candidate_count(usize::MAX, 10),
1219 ],
1220 [100, 1000, 5000, 0, usize::MAX]
1221 );
1222 }
1223}