| /* | |
| * Licensed to the Apache Software Foundation (ASF) under one | |
| * or more contributor license agreements. See the NOTICE file | |
| * distributed with this work for additional information | |
| * regarding copyright ownership. The ASF licenses this file | |
| * to you under the Apache License, Version 2.0 (the | |
| * "License"); you may not use this file except in compliance | |
| * with the License. You may obtain a copy of the License at | |
| * | |
| * http://www.apache.org/licenses/LICENSE-2.0 | |
| * | |
| * Unless required by applicable law or agreed to in writing, | |
| * software distributed under the License is distributed on an | |
| * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | |
| * KIND, either express or implied. See the License for the | |
| * specific language governing permissions and limitations | |
| * under the License. | |
| */ | |
| use super::*; | |
| use crate::recall::{number, unsigned}; | |
| pub struct SearchFacts { | |
| pub personal: Scope, | |
| pub project: Option<(Scope, String)>, | |
| pub terms: Vec<String>, | |
| pub after: u64, | |
| pub limit: usize, | |
| pub since: Option<u64>, | |
| pub until: Option<u64>, | |
| } | |
| #[derive(Default)] | |
| pub struct FactPage { | |
| pub facts: Vec<RecallFact>, | |
| pub next: Option<u64>, | |
| pub gaps: Vec<String>, | |
| } | |
| const SEARCH: &str = " | |
| WITH hits AS MATERIALIZED ( | |
| SELECT rowid seq FROM agent_memory_recall_terms | |
| WHERE agent_memory_recall_terms MATCH ?1 AND rowid>?2 ORDER BY rowid LIMIT 65 | |
| ) | |
| SELECT k.seq,k.scope,k.id,m.revision,m.assertion,v.body,m.modified_at,v.metadata, | |
| (SELECT json_group_array(json_object('source',json_remove(e.source,'$.reference.quote','$.reference.fingerprint'),'visible', | |
| CASE WHEN s.id IS NOT NULL AND s.archived=0 AND COALESCE(s.configuration->>'incognito',0)=0 | |
| AND EXISTS(SELECT 1 FROM session_creations route WHERE route.session_id=s.id AND route.ready=1 AND route.visible=1) | |
| AND NOT EXISTS(SELECT 1 FROM session_retirements retired WHERE retired.session_id=s.id AND retired.remove_session=1) | |
| AND h.fact_id=e.source->>'$.reference.factId' | |
| THEN json('true') ELSE json('false') END)) | |
| FROM (SELECT source FROM agent_memory_evidence WHERE namespace=k.namespace AND scope=k.scope AND id=k.id AND assertion=m.assertion | |
| ORDER BY sequence LIMIT 5) e | |
| LEFT JOIN session_control s ON s.id=e.source->>'$.reference.sessionId' | |
| LEFT JOIN agent_namespaces ns ON ns.owner=m.namespace AND ns.session=s.id | |
| LEFT JOIN agent_session_history h ON h.namespace_id=ns.id AND h.sequence=e.source->>'$.reference.sequence') | |
| FROM hits f CROSS JOIN agent_memory_recall_keys k ON k.seq=f.seq | |
| CROSS JOIN agent_memories m USING(namespace,scope,id) | |
| CROSS JOIN agent_memory_versions v ON v.namespace=m.namespace AND v.scope=m.scope AND v.id=m.id AND v.revision=m.assertion | |
| WHERE k.namespace=?3 AND k.scope IN (?4,?5) AND m.state='active' AND v.disposition='current' | |
| ORDER BY f.seq"; | |
| #[derive(serde::Deserialize)] | |
| struct SourceRow { | |
| source: StoredSource, | |
| visible: bool, | |
| } | |
| #[derive(serde::Deserialize)] | |
| #[serde( | |
| tag = "kind", | |
| rename_all = "snake_case", | |
| rename_all_fields = "camelCase" | |
| )] | |
| enum StoredSource { | |
| UserOperation { operation_id: uuid::Uuid }, | |
| Conversation { reference: Locator }, | |
| } | |
| #[derive(serde::Deserialize)] | |
| #[serde(rename_all = "camelCase")] | |
| struct Locator { | |
| session_id: String, | |
| sequence: u64, | |
| item_index: u64, | |
| fact_id: maka_agent_facts::durable::FactId, | |
| start: u32, | |
| end: u32, | |
| } | |
| impl Query for SearchFacts { | |
| type Output = FactPage; | |
| fn execute(self, c: &Connection) -> Result<FactPage, StoreError> { | |
| self.personal.validate(c)?; | |
| let namespace = &self.personal.namespace; | |
| let location = |s: &Scope| { | |
| format!( | |
| "location:\"{}x{}\"", | |
| hex::encode(namespace), | |
| hex::encode(&s.location) | |
| ) | |
| }; | |
| let mut page = FactPage::default(); | |
| let project = self.project.filter(|(scope, _)| match scope.validate(c) { | |
| Ok(()) => true, | |
| Err(reason) => { | |
| page.gaps.push(reason.to_string()); | |
| false | |
| } | |
| }); | |
| let mut locations = location(&self.personal); | |
| if let Some((scope, _)) = &project { | |
| locations.push_str(" OR "); | |
| locations.push_str(&location(scope)); | |
| } | |
| let terms = self | |
| .terms | |
| .iter() | |
| .map(|t| format!("body:\"{}\"*", t.replace('"', "\"\""))) | |
| .collect::<Vec<_>>(); | |
| if terms.is_empty() { | |
| return Ok(page); | |
| } | |
| let expression = format!("({locations}) AND ({})", terms.join(" OR ")); | |
| let mut stmt = c.prepare_cached(SEARCH)?; | |
| let limit = self.limit.min(16); | |
| let mut rows = stmt.query(params![ | |
| expression, | |
| number(self.after)?, | |
| namespace, | |
| self.personal.location, | |
| project.as_ref().map(|(s, _)| &s.location), | |
| ])?; | |
| let now: i64 = c.query_row( | |
| "SELECT CAST(unixepoch('subsec')*1000 AS INTEGER)", | |
| [], | |
| |row| row.get(0), | |
| )?; | |
| let mut last = self.after; | |
| let mut bytes = 0; | |
| let mut examined = 0; | |
| while let Some(row) = rows.next()? { | |
| if examined == 64 { | |
| page.next = Some(last); | |
| break; | |
| } | |
| examined += 1; | |
| let seq = unsigned(row.get(0)?)?; | |
| let modified = unsigned(row.get(6)?)?; | |
| if self.since.is_some_and(|since| modified < since) | |
| || self.until.is_some_and(|until| modified > until) | |
| { | |
| last = seq; | |
| continue; | |
| } | |
| let metadata: MemoryMetadata = serde_json::from_str(&row.get::<_, String>(7)?)?; | |
| if let MemoryTemporal::Interval { start, end } = &metadata.temporal | |
| && (now < *start || end.is_some_and(|end| now >= end)) | |
| { | |
| last = seq; | |
| continue; | |
| } | |
| let body: String = row.get(5)?; | |
| let evidence: Vec<SourceRow> = serde_json::from_str(&row.get::<_, String>(8)?)?; | |
| let count = evidence.len(); | |
| let sources: Vec<_> = evidence | |
| .into_iter() | |
| .take(4) | |
| .filter_map(|row| match row.source { | |
| StoredSource::UserOperation { operation_id } => { | |
| Some(RecallFactSource::UserOperation { operation_id }) | |
| } | |
| StoredSource::Conversation { reference: r } if row.visible => { | |
| Some(RecallFactSource::Conversation { | |
| session_id: r.session_id, | |
| start: r.start, | |
| end: r.end, | |
| row: maka_agent_facts::history::HistoryRowAddress::Live { | |
| sequence: r.sequence, | |
| fact: r.fact_id, | |
| item_index: r.item_index, | |
| }, | |
| }) | |
| } | |
| _ => None, | |
| }) | |
| .collect(); | |
| let sources_complete = count > 0 && sources.len() == count; | |
| let scope = if row.get::<_, String>(1)? == self.personal.location { | |
| MemoryScope::Personal | |
| } else { | |
| MemoryScope::Project { | |
| session_id: project | |
| .as_ref() | |
| .ok_or_else(|| invalid("missing project binding"))? | |
| .1 | |
| .clone(), | |
| } | |
| }; | |
| let fact = RecallFact { | |
| id: MemoryId( | |
| uuid::Uuid::parse_str(&row.get::<_, String>(2)?) | |
| .map_err(|e| invalid(e.to_string()))?, | |
| ), | |
| revision: revision_value(row.get(3)?)?, | |
| assertion: revision_value(row.get(4)?)?, | |
| scope, | |
| metadata, | |
| body, | |
| sources, | |
| sources_complete, | |
| }; | |
| // Include the model renderer's line prefix and newline in the byte bound. | |
| let size = serde_json::to_vec(&fact)?.len() + "Memory fact: ".len() + 1; | |
| const BYTE_BUDGET: usize = 32 * 1024; | |
| if size > BYTE_BUDGET { | |
| last = seq; | |
| page.gaps | |
| .push("A memory fact exceeds the Recall output budget".into()); | |
| continue; | |
| } | |
| if page.facts.len() == limit || bytes + size > BYTE_BUDGET { | |
| page.next = Some(last); | |
| break; | |
| } | |
| if !sources_complete && !page.gaps.iter().any(|g| g == "Memory evidence incomplete") { | |
| page.gaps.push("Memory evidence incomplete".into()); | |
| } | |
| bytes += size; | |
| last = seq; | |
| page.facts.push(fact); | |
| } | |
| Ok(page) | |
| } | |
| } | |
| pub(crate) fn configure_writer(connection: &Connection) -> Result<(), StoreError> { | |
| use rusqlite::functions::FunctionFlags; | |
| use unicode_normalization::UnicodeNormalization; | |
| connection.create_scalar_function( | |
| "maka_nfc", | |
| 1, | |
| FunctionFlags::SQLITE_UTF8 | |
| | FunctionFlags::SQLITE_DETERMINISTIC | |
| | FunctionFlags::SQLITE_INNOCUOUS, | |
| |ctx| Ok(ctx.get::<String>(0)?.nfc().collect::<String>()), | |
| )?; | |
| register_read_classifier(connection) | |
| } | |
| pub(crate) fn register_read_classifier(c: &Connection) -> Result<(), StoreError> { | |
| use rusqlite::functions::FunctionFlags; | |
| if c.prepare_cached("SELECT maka_reads_history_resource(NULL)") | |
| .is_ok() | |
| { | |
| return Ok(()); | |
| } | |
| c.create_scalar_function( | |
| "maka_reads_history_resource", | |
| 1, | |
| FunctionFlags::SQLITE_UTF8 | |
| | FunctionFlags::SQLITE_DETERMINISTIC | |
| | FunctionFlags::SQLITE_INNOCUOUS, | |
| |ctx| { | |
| Ok(maka_agent_facts::read::reads_history_resource( | |
| &ctx.get::<String>(0)?, | |
| )) | |
| }, | |
| )?; | |
| Ok(()) | |
| } | |
| #[cfg(test)] | |
| mod tests { | |
| use super::*; | |
| use std::collections::BTreeSet; | |
| fn migrate(db: &Connection, through: i64) { | |
| let migrations: Vec<_> = maka_event_log::ROOT_MIGRATIONS | |
| .iter() | |
| .chain(crate::MIGRATIONS) | |
| .filter(|m| m.version <= through) | |
| .copied() | |
| .collect(); | |
| maka_event_log::migration::run(db, &migrations).unwrap(); | |
| } | |
| #[test] | |
| fn broad_prefix_pages_current_assertions_over_large_restricted_history() { | |
| let mut db = Connection::open_in_memory().unwrap(); | |
| migrate(&db, i64::MAX); | |
| let scope = Scope { | |
| namespace: "owner".into(), | |
| location: "personal".into(), | |
| binding: None, | |
| }; | |
| let query = |after| SearchFacts { | |
| personal: scope.clone(), | |
| project: None, | |
| terms: vec!["a".into()], | |
| after, | |
| limit: 16, | |
| since: None, | |
| until: None, | |
| }; | |
| let source = serde_json::to_string(&MemorySource::UserOperation { | |
| operation_id: uuid::Uuid::new_v4(), | |
| observed_at: 0, | |
| }) | |
| .unwrap(); | |
| let mut active = BTreeSet::new(); | |
| let tx = db.transaction().unwrap(); | |
| for n in 0..4352 { | |
| let id = uuid::Uuid::new_v4(); | |
| let state = if n % 17 == 0 { | |
| active.insert(id); | |
| "active" | |
| } else { | |
| "suppressed" | |
| }; | |
| tx.execute( | |
| "INSERT INTO agent_memories VALUES('owner','personal',?,1,1,'user_recall',?,0,0)", | |
| params![id.to_string(), state], | |
| ) | |
| .unwrap(); | |
| tx.execute("INSERT INTO agent_memory_versions(namespace,scope,id,revision,body,source,digest,disposition) VALUES('owner','personal',?,1,'apricot',?,'digest',?)",params![id.to_string(),source,if state=="active" {"current"}else{"suppressed"}]).unwrap(); | |
| tx.execute("INSERT INTO agent_memory_evidence(namespace,scope,id,assertion,source,source_key) VALUES('owner','personal',?,1,?,'original')",params![id.to_string(),source]).unwrap(); | |
| } | |
| tx.commit().unwrap(); | |
| let mut lost_project = query(0); | |
| lost_project.project = Some(( | |
| Scope { | |
| namespace: scope.namespace.clone(), | |
| location: "project".into(), | |
| binding: Some(( | |
| "retired-session".into(), | |
| maka_sandbox::workspace::PermissionBasis { | |
| boundary_revision: 1, | |
| binding: maka_sandbox::workspace::BindingStamp { | |
| id: uuid::Uuid::new_v4(), | |
| permission_epoch: 1, | |
| }, | |
| }, | |
| )), | |
| }, | |
| "retired-session".into(), | |
| )); | |
| let fallback = lost_project.execute(&db).unwrap(); | |
| assert_eq!(fallback.facts.len(), 16); | |
| assert!( | |
| fallback | |
| .gaps | |
| .iter() | |
| .any(|reason| reason.contains("memory scope binding changed")) | |
| ); | |
| let start = std::time::Instant::now(); | |
| let mut pages = 0; | |
| let mut after = 0; | |
| loop { | |
| let page = query(after).execute(&db).unwrap(); | |
| assert!(page.gaps.is_empty(), "{:?}", page.gaps); | |
| assert_eq!(page.facts.len(), 16); | |
| for fact in page.facts { | |
| assert!(active.remove(&fact.id.0)); | |
| } | |
| pages += 1; | |
| let Some(next) = page.next else { | |
| break; | |
| }; | |
| assert!(next > after); | |
| after = next; | |
| } | |
| eprintln!( | |
| "Recall: 4096 suppressed, 256 active, {pages} pages in {:?}", | |
| start.elapsed() | |
| ); | |
| assert!(active.is_empty()); | |
| db.execute( | |
| "UPDATE agent_memory_versions SET metadata=json_set(metadata,'$.temporal',json(?)) | |
| WHERE disposition='current'", | |
| [r#"{"kind":"interval","start":0,"end":1}"#], | |
| ) | |
| .unwrap(); | |
| let expired = query(0).execute(&db).unwrap(); | |
| assert!(expired.facts.is_empty()); | |
| assert!( | |
| expired.next.is_some(), | |
| "time filtering must preserve the bounded scan cursor" | |
| ); | |
| } | |
| #[test] | |
| fn recall_indexes_assertions_written_after_upgrade() { | |
| use unicode_normalization::UnicodeNormalization; | |
| let c = Connection::open_in_memory().unwrap(); | |
| migrate(&c, 50); | |
| let scope = Scope { | |
| namespace: "owner".into(), | |
| location: "personal".into(), | |
| binding: None, | |
| }; | |
| let write = |edit| { | |
| UserChange { | |
| source_scope: None, | |
| scope: scope.clone(), | |
| edit, | |
| operation: uuid::Uuid::new_v4(), | |
| at: 1, | |
| } | |
| .apply(&c) | |
| .unwrap() | |
| }; | |
| let MemoryResult::Saved { id, revision } = write(MemoryEdit::Create { | |
| body: "oldword".into(), | |
| metadata: MemoryMetadata::default(), | |
| }) else { | |
| panic!("expected a saved memory") | |
| }; | |
| migrate(&c, i64::MAX); | |
| let search = |terms: &[&str]| { | |
| SearchFacts { | |
| personal: scope.clone(), | |
| project: None, | |
| terms: terms.iter().map(|term| (*term).to_owned()).collect(), | |
| limit: 16, | |
| after: 0, | |
| since: None, | |
| until: None, | |
| } | |
| .execute(&c) | |
| .unwrap() | |
| }; | |
| assert!(search(&["oldword"]).facts.is_empty()); | |
| let body: String = "νκΈ μ€μ π§".nfd().collect(); | |
| let MemoryResult::Saved { revision, .. } = write(MemoryEdit::Correct { | |
| id: id.clone(), | |
| expected_revision: revision, | |
| body: body.clone(), | |
| metadata: MemoryMetadata::default(), | |
| }) else { | |
| panic!("expected a corrected memory") | |
| }; | |
| for terms in [&["ν"][..], &["π§"], &["!", "π§", "absent"]] { | |
| let page = search(terms); | |
| assert_eq!(page.facts.len(), 1, "terms {terms:?}"); | |
| assert_eq!(page.facts[0].body, body); | |
| } | |
| assert!(search(&["!"]).facts.is_empty()); | |
| assert!(matches!( | |
| write(MemoryEdit::Delete { | |
| id, | |
| expected_revision: revision | |
| }), | |
| MemoryResult::Deleted { .. } | |
| )); | |
| assert!(search(&["π§"]).facts.is_empty()); | |
| } | |
| } |