gadk_memory/inmemory.rs
1// Copyright 2026 Chris Olson
2// Portions derived from ADK-Go (https://github.com/google/adk-go), Copyright 2026 Google LLC.
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! In-memory word-matching memory service.
17
18use std::collections::{HashMap, HashSet};
19
20use async_trait::async_trait;
21use chrono::{DateTime, Utc};
22use gadk_genai::Content;
23use gadk_session::{Event, Session, zero_time};
24use parking_lot::RwLock;
25use serde_json::{Map, Value};
26use unicode_normalization::UnicodeNormalization;
27use unicode_properties::{GeneralCategoryGroup, UnicodeGeneralCategory};
28
29use crate::service::{
30 AddEventsRequest, EventAdder, MemoryEntry, MemoryError, MemoryService, SearchRequest,
31 SearchResponse,
32};
33
34/// The most entries a search returns.
35const MAX_SEARCH_RESULTS: usize = 10;
36
37/// A session bucket within a user scope. The default bucket, for events added with no session
38/// ID, never equals the key of a session, even one whose ID is `""`.
39#[derive(Debug, Clone, PartialEq, Eq, Hash)]
40enum SessionKey {
41 Default,
42 Id(String),
43}
44
45/// One stored event.
46struct StoredValue {
47 id: String,
48 content: Content,
49 author: String,
50 timestamp: Option<DateTime<Utc>>,
51 custom_metadata: Map<String, Value>,
52 /// Precomputed set of words in the content for simple keyword matching.
53 words: HashSet<String>,
54 /// Cached lowercase copy of the event text, to avoid joining and lowercasing content parts
55 /// on each substring search.
56 text_lower: String,
57}
58
59/// The memories of one (app, user) scope: session buckets in insertion order.
60#[derive(Default)]
61struct UserMemories {
62 sessions: HashMap<SessionKey, Vec<StoredValue>>,
63 session_order: Vec<SessionKey>,
64}
65
66impl UserMemories {
67 /// Creates bucket `key` if absent. A new bucket takes the next position in the session order
68 /// even when nothing is stored in it, as in Python's dict, and replacing a bucket keeps its
69 /// position.
70 fn ensure_bucket(&mut self, key: &SessionKey) -> &mut Vec<StoredValue> {
71 if !self.sessions.contains_key(key) {
72 self.session_order.push(key.clone());
73 }
74 self.sessions.entry(key.clone()).or_default()
75 }
76}
77
78/// An in-memory implementation of [`MemoryService`]. Thread-safe.
79///
80/// Searches return at most ten entries, ranked by the number of distinct query words they
81/// match. Ties follow session insertion order, then event order.
82///
83/// It also implements [`EventAdder`]: [`EventAdder::add_events`] appends to the bucket of
84/// `req.session_id` and keeps the first stored event of each non-empty event ID in that
85/// bucket; [`MemoryService::add_session_to_memory`] replaces the bucket of the session.
86///
87/// Both add methods skip events whose content is `None` or holds no part; such an event does
88/// not reserve its ID. Thought parts are left out of both matching and the returned content.
89/// An event with parts but no searchable text, such as a blob-only or thought-only event, is
90/// stored and reserves its ID, but no search returns it.
91///
92/// A query and the stored text are split into words: runs of letters, numbers and
93/// underscores, taken after Unicode NFC normalization and lowercased with full Unicode case
94/// mapping. An event matches a query word when it has that word. A query word with non-ASCII
95/// characters also matches anywhere inside the event's text, and a stored word that mixes Latin
96/// and other scripts, such as the Python in 私はPythonを使う, also yields each single-script
97/// run as a word. A query with no words returns no entries.
98pub struct InMemoryMemoryService {
99 /// Keyed by `(app_name, user_id)`.
100 store: RwLock<HashMap<(String, String), UserMemories>>,
101}
102
103impl InMemoryMemoryService {
104 /// A new, empty in-memory memory service.
105 pub fn new() -> Self {
106 Self {
107 store: RwLock::new(HashMap::new()),
108 }
109 }
110}
111
112impl Default for InMemoryMemoryService {
113 fn default() -> Self {
114 Self::new()
115 }
116}
117
118impl std::fmt::Debug for InMemoryMemoryService {
119 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
120 f.write_str("InMemoryMemoryService")
121 }
122}
123
124/// The stored form of `event`, or `None` for an event that has no content or no part, which is
125/// neither stored nor reserves its ID. An event with parts but no searchable words, such as a
126/// blob-only event, is stored so that its ID blocks later duplicates; search skips it.
127fn build_value(event: Event) -> Option<StoredValue> {
128 let content = event.response.content.filter(|c| !c.parts.is_empty())?;
129
130 // Thought parts are the model's reasoning, not conversation, so they are neither searched
131 // nor returned (adk-python v2.12.0 does both; this keeps internal reasoning out of memory
132 // results).
133 let mut texts = Vec::new();
134 let mut visible_parts = Vec::new();
135 for part in content.parts {
136 if part.thought {
137 continue;
138 }
139 if !part.text.is_empty() {
140 texts.push(part.text.clone());
141 }
142 visible_parts.push(part);
143 }
144 let text = texts.join(" ");
145
146 Some(StoredValue {
147 id: event.id,
148 content: Content {
149 parts: visible_parts,
150 role: content.role,
151 },
152 author: event.author,
153 timestamp: (event.timestamp != zero_time()).then_some(event.timestamp),
154 custom_metadata: event.response.custom_metadata,
155 words: extract_searchable_words(&text),
156 text_lower: text.nfc().collect::<String>().to_lowercase(),
157 })
158}
159
160#[async_trait]
161impl MemoryService for InMemoryMemoryService {
162 /// Replaces the session's bucket with the session's events.
163 async fn add_session_to_memory(&self, session: &dyn Session) -> Result<(), MemoryError> {
164 let values: Vec<StoredValue> = session
165 .events()
166 .into_iter()
167 .filter_map(build_value)
168 .collect();
169
170 let key = (session.app_name().to_owned(), session.user_id().to_owned());
171 let bucket = SessionKey::Id(session.id().to_owned());
172 let mut store = self.store.write();
173 *store.entry(key).or_default().ensure_bucket(&bucket) = values;
174 Ok(())
175 }
176
177 /// Returns up to ten entries, ranked by the number of distinct query words matched.
178 async fn search_memory(&self, req: SearchRequest) -> Result<SearchResponse, MemoryError> {
179 // A true value allows substring matching for that non-ASCII query word.
180 let query_words: HashMap<String, bool> = extract_words_lower(&req.query)
181 .into_iter()
182 .map(|w| {
183 let non_ascii = !w.is_ascii();
184 (w, non_ascii)
185 })
186 .collect();
187
188 if query_words.is_empty() {
189 return Ok(SearchResponse::default());
190 }
191
192 // Hold the read lock for the whole scan (so the scan does not race a concurrent write).
193 let store = self.store.read();
194 let Some(memories) = store.get(&(req.app_name, req.user_id)) else {
195 return Ok(SearchResponse::default());
196 };
197
198 let mut scored: Vec<(usize, MemoryEntry)> = Vec::new();
199 for key in &memories.session_order {
200 let Some(values) = memories.sessions.get(key) else {
201 continue;
202 };
203 for v in values {
204 if v.words.is_empty() {
205 continue;
206 }
207 let score = query_words
208 .iter()
209 .filter(|(word, allow_substring)| {
210 v.words.contains(*word)
211 || (**allow_substring && v.text_lower.contains(*word))
212 })
213 .count();
214 if score > 0 {
215 scored.push((
216 score,
217 MemoryEntry {
218 id: v.id.clone(),
219 content: Some(v.content.clone()),
220 author: v.author.clone(),
221 timestamp: v.timestamp,
222 custom_metadata: v.custom_metadata.clone(),
223 },
224 ));
225 }
226 }
227 }
228 drop(store);
229
230 // Common words can match most of the store. Rank all matches before limiting results so
231 // that later, more relevant events can still reach the prompt. The sort is stable, so
232 // ties keep insertion order.
233 scored.sort_by_key(|(score, _)| std::cmp::Reverse(*score));
234 scored.truncate(MAX_SEARCH_RESULTS);
235
236 Ok(SearchResponse {
237 memories: scored.into_iter().map(|(_, entry)| entry).collect(),
238 })
239 }
240
241 fn as_event_adder(&self) -> Option<&dyn EventAdder> {
242 Some(self)
243 }
244}
245
246#[async_trait]
247impl EventAdder for InMemoryMemoryService {
248 /// Appends to the bucket of `req.session_id`
249 /// (the default bucket when it is empty), skipping an event whose non-empty ID the bucket
250 /// already holds. `req.custom_metadata` is ignored.
251 async fn add_events(&self, req: AddEventsRequest) -> Result<(), MemoryError> {
252 let values: Vec<StoredValue> = req.events.into_iter().filter_map(build_value).collect();
253 let bucket = if req.session_id.is_empty() {
254 SessionKey::Default
255 } else {
256 SessionKey::Id(req.session_id)
257 };
258
259 let mut store = self.store.write();
260 let existing = store
261 .entry((req.app_name, req.user_id))
262 .or_default()
263 .ensure_bucket(&bucket);
264 let mut existing_ids: HashSet<String> = existing
265 .iter()
266 .filter(|e| !e.id.is_empty())
267 .map(|e| e.id.clone())
268 .collect();
269 for value in values {
270 if !value.id.is_empty() && !existing_ids.insert(value.id.clone()) {
271 continue;
272 }
273 existing.push(value);
274 }
275 Ok(())
276 }
277}
278
279/// The lowercased `\w+` tokens of the NFC form of `text`, as adk-python's
280/// `_extract_words_lower` does. Combining marks are not word characters, so after NFC a mark that
281/// composes nowhere separates words.
282///
283/// `to_lowercase` is full Unicode case mapping.
284fn extract_words_lower(text: &str) -> HashSet<String> {
285 let nfc: String = text.nfc().collect();
286 nfc.split(|c: char| !is_word_char(c))
287 .filter(|piece| !piece.is_empty())
288 .map(str::to_lowercase)
289 .collect()
290}
291
292/// The words an event can be matched on, the tokens of [`extract_words_lower`]
293/// plus, for each non-ASCII token, its runs of Latin and of non-Latin characters. Japanese and
294/// Chinese are written without spaces, so in 私はPythonを使う the run `python` becomes a word of
295/// its own.
296fn extract_searchable_words(text: &str) -> HashSet<String> {
297 let mut words = extract_words_lower(text);
298 let mut runs = Vec::new();
299 for word in words.iter().filter(|w| !w.is_ascii()) {
300 let (mut start, mut run_latin) = (0, false);
301 for (i, c) in word.char_indices() {
302 let latin = is_latin(c);
303 if i > 0 && latin != run_latin {
304 runs.push(word[start..i].to_owned());
305 start = i;
306 }
307 run_latin = latin;
308 }
309 runs.push(word[start..].to_owned());
310 }
311 words.extend(runs);
312 words
313}
314
315/// Whether `c` is a word character: a letter, a number or `_`.
316///
317/// The Unicode version of `unicode-properties` may differ from other Unicode releases for newly
318/// assigned code points only.
319fn is_word_char(c: char) -> bool {
320 c == '_'
321 || matches!(
322 c.general_category_group(),
323 GeneralCategoryGroup::Letter | GeneralCategoryGroup::Number
324 )
325}
326
327/// Whether `c` belongs to a Latin run, as adk-python's `_is_latin` does:
328/// an ASCII word character, or a character whose Unicode name starts with `LATIN`. The name rule
329/// leaves out ª and º, which Unicode's Latin script includes.
330fn is_latin(c: char) -> bool {
331 if c.is_ascii() {
332 return c.is_ascii_alphanumeric() || c == '_';
333 }
334 unicode_names2::name(c).is_some_and(|name| name.to_string().starts_with("LATIN"))
335}