1use crate::service::{MemoryEntry, MemoryService, SearchRequest};
41use adk_core::Content;
42use async_trait::async_trait;
43use chrono::Utc;
44use std::sync::Arc;
45use std::time::Duration;
46
47#[async_trait]
49pub trait MemoryServiceHarness: Send + Sync {
50 async fn open(&self, default_ttl: Option<Duration>) -> Arc<dyn MemoryService>;
56}
57
58const SHORT_TTL: Duration = Duration::from_secs(2);
60
61fn unique(prefix: &str) -> String {
62 format!("{prefix}-{}", uuid::Uuid::new_v4().simple())
63}
64
65fn entry(text: &str) -> MemoryEntry {
66 MemoryEntry::new(Content::new("user").with_text(text), "user")
67}
68
69async fn recalled(
71 service: &dyn MemoryService,
72 app: &str,
73 user: &str,
74 query: &str,
75 project: Option<&str>,
76) -> Vec<MemoryEntry> {
77 let mut memories = service
78 .search(SearchRequest {
79 query: query.to_string(),
80 user_id: user.to_string(),
81 app_name: app.to_string(),
82 limit: Some(20),
83 min_score: None,
84 project_id: project.map(str::to_string),
85 })
86 .await
87 .expect("search")
88 .memories;
89 memories.sort_by(|a, b| a.id.cmp(&b.id));
90 memories
91}
92
93fn ids(memories: &[MemoryEntry]) -> Vec<String> {
94 memories
95 .iter()
96 .map(|memory| memory.id.clone().expect("a returned entry carries an id"))
97 .collect()
98}
99
100pub async fn ids_are_assigned_and_kept<H: MemoryServiceHarness + ?Sized>(harness: &H) {
103 let service = harness.open(None).await;
104 let (app, user) = (unique("app"), unique("user"));
105 service
106 .add_session(
107 &app,
108 &user,
109 "s1",
110 vec![entry("kestrel alpha").with_id("kept-1"), entry("kestrel beta")],
111 )
112 .await
113 .expect("add_session");
114
115 let found = ids(&recalled(service.as_ref(), &app, &user, "kestrel", None).await);
116 assert_eq!(found.len(), 2, "both entries are recalled: {found:?}");
117 assert!(found.contains(&"kept-1".to_string()), "a given id is kept: {found:?}");
118 let assigned: Vec<&String> = found.iter().filter(|id| *id != "kept-1").collect();
119 assert!(!assigned[0].is_empty(), "an entry without an id is given one");
120
121 let mut exported: Vec<String> = service
122 .export_user(&app, &user)
123 .await
124 .expect("export_user")
125 .into_iter()
126 .filter_map(|memory| memory.entry.id)
127 .collect();
128 exported.sort();
129 assert_eq!(exported, found, "export returns the ids search does");
130}
131
132pub async fn expired_entries_are_not_recalled<H: MemoryServiceHarness + ?Sized>(harness: &H) {
135 let service = harness.open(None).await;
136 let (app, user) = (unique("app"), unique("user"));
137 let in_an_hour = Utc::now() + chrono::Duration::hours(1);
138 let fresh = entry("heron fresh").with_id("fresh").with_expires_at(in_an_hour);
139 service
140 .add_session(
141 &app,
142 &user,
143 "s1",
144 vec![
145 entry("heron stale")
146 .with_id("stale")
147 .with_expires_at(Utc::now() - chrono::Duration::minutes(1)),
148 fresh.clone(),
149 entry("heron forever").with_id("forever"),
150 ],
151 )
152 .await
153 .expect("add_session");
154
155 let found = recalled(service.as_ref(), &app, &user, "heron", None).await;
156 assert_eq!(ids(&found), ["forever", "fresh"], "only unexpired entries are recalled");
157 assert_eq!(found[0].expires_at, None, "an entry without an expiry has none");
158 assert_eq!(found[1].expires_at, fresh.expires_at, "the expiry round-trips");
159}
160
161pub async fn the_default_ttl_applies<H: MemoryServiceHarness + ?Sized>(harness: &H) {
164 let service = harness.open(Some(SHORT_TTL)).await;
165 let (app, user) = (unique("app"), unique("user"));
166 let own = Utc::now() + chrono::Duration::hours(1);
167 let before = crate::expiry::to_millis(Utc::now());
168 service
169 .add_session(
170 &app,
171 &user,
172 "s1",
173 vec![
174 entry("osprey default").with_id("default"),
175 entry("osprey own").with_id("own").with_expires_at(own),
176 ],
177 )
178 .await
179 .expect("add_session");
180 let after = Utc::now();
181
182 let found = recalled(service.as_ref(), &app, &user, "osprey", None).await;
183 assert_eq!(ids(&found), ["default", "own"], "both are live right after the write");
184 let defaulted = found[0].expires_at.expect("the default TTL sets an expiry");
185 assert!(
186 defaulted >= crate::expiry::expiry_after(before, SHORT_TTL)
187 && defaulted <= crate::expiry::expiry_after(after, SHORT_TTL),
188 "the default TTL is measured from the write, got {defaulted}"
189 );
190 assert_eq!(found[1].expires_at, Some(crate::expiry::to_millis(own)));
191
192 let wait = (defaulted - Utc::now()).to_std().unwrap_or_default() + Duration::from_millis(500);
193 tokio::time::sleep(wait).await;
194 let found = recalled(service.as_ref(), &app, &user, "osprey", None).await;
195 assert_eq!(ids(&found), ["own"], "the defaulted entry expires; the one with its own lives");
196}
197
198pub async fn project_entries_expire_too<H: MemoryServiceHarness + ?Sized>(harness: &H) {
201 let service = harness.open(None).await;
202 if !service.supports_project_scoping() {
203 return;
204 }
205 let (app, user) = (unique("app"), unique("user"));
206 service
207 .add_session_to_project(
208 &app,
209 &user,
210 "s1",
211 "p1",
212 vec![
213 entry("falcon stale")
214 .with_id("stale")
215 .with_expires_at(Utc::now() - chrono::Duration::minutes(1)),
216 entry("falcon fresh").with_id("fresh"),
217 ],
218 )
219 .await
220 .expect("add_session_to_project");
221 let found = recalled(service.as_ref(), &app, &user, "falcon", Some("p1")).await;
222 assert_eq!(ids(&found), ["fresh"]);
223}
224
225pub async fn delete_memory_removes_one_entry<H: MemoryServiceHarness + ?Sized>(harness: &H) {
228 let service = harness.open(None).await;
229 let (app, user, other) = (unique("app"), unique("user"), unique("user"));
230 service
231 .add_session(
232 &app,
233 &user,
234 "s1",
235 vec![entry("plover one").with_id("del-a"), entry("plover two").with_id("del-b")],
236 )
237 .await
238 .expect("add_session");
239 service
240 .add_session(&app, &other, "s1", vec![entry("plover other").with_id("del-a")])
241 .await
242 .expect("add_session");
243
244 assert_eq!(service.delete_memory(&app, &user, "del-a").await.expect("delete_memory"), 1);
245 assert_eq!(ids(&recalled(service.as_ref(), &app, &user, "plover", None).await), ["del-b"]);
246 assert_eq!(
247 ids(&recalled(service.as_ref(), &app, &other, "plover", None).await),
248 ["del-a"],
249 "another user's entry with the same id is kept"
250 );
251 assert_eq!(service.delete_memory(&app, &user, "missing").await.expect("delete_memory"), 0);
252
253 if service.supports_project_scoping() {
254 service
255 .add_session_to_project(
256 &app,
257 &user,
258 "s2",
259 "p1",
260 vec![entry("plover project").with_id("del-p")],
261 )
262 .await
263 .expect("add_session_to_project");
264 assert_eq!(service.delete_memory(&app, &user, "del-p").await.expect("delete_memory"), 1);
265 assert_eq!(
266 ids(&recalled(service.as_ref(), &app, &user, "plover", Some("p1")).await),
267 ["del-b"]
268 );
269 }
270}
271
272pub async fn purge_removes_only_expired_entries<H: MemoryServiceHarness + ?Sized>(harness: &H) {
275 let service = harness.open(None).await;
276 let (app, user) = (unique("app"), unique("user"));
277 service
278 .add_session(
279 &app,
280 &user,
281 "s1",
282 vec![
283 entry("tern stale")
284 .with_id("stale")
285 .with_expires_at(Utc::now() - chrono::Duration::minutes(1)),
286 entry("tern fresh").with_id("fresh"),
287 ],
288 )
289 .await
290 .expect("add_session");
291
292 service.purge_expired().await.expect("purge_expired");
293 let mut held: Vec<String> = service
294 .export_user(&app, &user)
295 .await
296 .expect("export_user")
297 .into_iter()
298 .filter_map(|memory| memory.entry.id)
299 .collect();
300 held.sort();
301 assert_eq!(held, ["fresh"], "the purge removed the expired entry and kept the live one");
302 assert_eq!(ids(&recalled(service.as_ref(), &app, &user, "tern", None).await), ["fresh"]);
303}
304
305#[macro_export]
311macro_rules! memory_conformance_tests {
312 ($(#[$attr:meta])* harness = $harness:expr $(,)?) => {
313 $(#[$attr])*
314 #[tokio::test]
315 async fn memory_ids_are_assigned_and_kept() {
316 $crate::conformance::ids_are_assigned_and_kept(&$harness).await;
317 }
318 $(#[$attr])*
319 #[tokio::test]
320 async fn memory_expired_entries_are_not_recalled() {
321 $crate::conformance::expired_entries_are_not_recalled(&$harness).await;
322 }
323 $(#[$attr])*
324 #[tokio::test]
325 async fn memory_the_default_ttl_applies() {
326 $crate::conformance::the_default_ttl_applies(&$harness).await;
327 }
328 $(#[$attr])*
329 #[tokio::test]
330 async fn memory_project_entries_expire_too() {
331 $crate::conformance::project_entries_expire_too(&$harness).await;
332 }
333 $(#[$attr])*
334 #[tokio::test]
335 async fn memory_delete_memory_removes_one_entry() {
336 $crate::conformance::delete_memory_removes_one_entry(&$harness).await;
337 }
338 $(#[$attr])*
339 #[tokio::test]
340 async fn memory_purge_removes_only_expired_entries() {
341 $crate::conformance::purge_removes_only_expired_entries(&$harness).await;
342 }
343 };
344}