Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

Bots' memory search finds notes by meaning too (hybrid recall) (#603)

Oleksandr Ivanchenko1fb11e3a913e
diff --git a/docs/mission-control.md b/docs/mission-control.md
index 22f73299..f3259de0 100644
--- a/docs/mission-control.md
+++ b/docs/mission-control.md
@@ -1522,3 +1522,15 @@ GET /api/kwants/:id/lessons {enabled, window_days, lines: [{key, source, text
### Known limits
Routine and hand-off turns aren't tied to a task, so they get the chat-sized block with no holdout and no attribution. A goal line reflects the goal's status at the last check, so it can lag a fix until the goal's next run.
+
+## 24. Memory recall by meaning (hybrid recall)
+
+A bot's `memory_search` finds notes by meaning as well as by words, using the space's own embeddings (`src/server/memory_recall.rs`).
+
+**Provider.** First the space's OpenAI account: a Codex API-key account, else the host's OpenAI key (Settings, else `OPENAI_API_KEY`) unless This machine is off for Codex. Both need the OpenAI API engine enabled, and use `text-embedding-3-small`. Else a local Ollama whose last check was ready and that has an embedding model pulled (`nomic-embed-text`, then `mxbai-embed-large`, then any `*embed*`). Claude has no embeddings API. Picking the provider reads only the database and the cached engine checks.
+
+**No provider: today's search.** The result is exactly the FTS5 keyword search, with no HTTP call and nothing added to the wait.
+
+**With a provider.** The query is embedded once, with a 1.5 s timeout. The keyword top 20 and the cosine top 20 (cosine ≥ 0.2) are merged by Reciprocal Rank Fusion (score = Σ 1/(60 + rank)), then the Truth Ledger view filters the result as before. If the query can't be embedded in time, the search is keyword-only and that provider isn't asked again for 60 s.
+
+**Vectors.** They live in `kwant_memory_vectors(memory_id, model, dim, vec, text_hash)` as little-endian f32. They are filled in the background after each memory write, and lazily when a search finds missing or stale ones: the text or the model changed. Each fill embeds up to 4 batches of 32 notes, and only one runs per bot at a time. Deleting a note deletes its vector through a trigger.
diff --git a/src/db/continuity.rs b/src/db/continuity.rs
index 3aaea1ea..d2c8c4ff 100644
--- a/src/db/continuity.rs
+++ b/src/db/continuity.rs
@@ -54,6 +54,28 @@ pub struct Memory {
pub updated_at: DateTime<Utc>,
}
+/// One memory and the embedding stored for it (see [`Database::memory_vector_rows`]).
+#[derive(Debug, Clone, FromRow)]
+pub struct MemoryVectorRow {
+ pub id: String,
+ pub text: String,
+ pub model: Option<String>,
+ pub text_hash: Option<String>,
+ pub vec: Option<Vec<u8>>,
+}
+
+impl MemoryVectorRow {
+ /// The stored vector, when it was made by `model` from the memory's current text (`hash`).
+ pub fn fresh_vector(&self, model: &str, hash: &str) -> Option<Vec<f32>> {
+ if self.model.as_deref() != Some(model) || self.text_hash.as_deref() != Some(hash) {
+ return None;
+ }
+ let bytes = self.vec.as_deref()?;
+ let (floats, rest) = bytes.as_chunks::<4>();
+ (rest.is_empty() && !floats.is_empty()).then(|| floats.iter().map(|c| f32::from_le_bytes(*c)).collect())
+ }
+}
+
/// The external-content full-text indexes over chat messages and bot memories.
const SEARCH_INDEXES: [&str; 2] = ["messages_fts", "kwant_memories_fts"];
@@ -424,6 +446,26 @@ impl Database {
} else {
self.repair_search_index_if_out_of_step("kwant_memories", "kwant_memories_fts").await?;
}
+ self.migrate_memory_vectors().await
+ }
+
+ /// Additive: the side table hybrid recall keeps one embedding per memory in (see
+ /// `server::memory_recall`), and a trigger that drops a memory's vector with the memory, on
+ /// every delete path. Older binaries ignore both; a vector they leave stale is noticed by its
+ /// `text_hash` and filled again.
+ async fn migrate_memory_vectors(&self) -> Result<(), DbError> {
+ sqlx::query(
+ "CREATE TABLE IF NOT EXISTS kwant_memory_vectors (\
+ memory_id TEXT PRIMARY KEY, model TEXT NOT NULL, dim INTEGER NOT NULL, vec BLOB NOT NULL, text_hash TEXT NOT NULL)",
+ )
+ .execute(&self.pool)
+ .await?;
+ sqlx::query(
+ "CREATE TRIGGER IF NOT EXISTS kwant_memories_vectors_ad AFTER DELETE ON kwant_memories BEGIN \
+ DELETE FROM kwant_memory_vectors WHERE memory_id = old.id; END",
+ )
+ .execute(&self.pool)
+ .await?;
Ok(())
}
@@ -803,6 +845,38 @@ impl Database {
.await?)
}
+ /// Every note of the kwant with the vector stored for it, if any: what hybrid recall reads to
+ /// rank by meaning and to find vectors that are missing or stale.
+ pub async fn memory_vector_rows(&self, kwant_id: &str) -> Result<Vec<MemoryVectorRow>, DbError> {
+ Ok(sqlx::query_as::<_, MemoryVectorRow>(
+ "SELECT m.id, m.text, v.model, v.text_hash, v.vec FROM kwant_memories m \
+ LEFT JOIN kwant_memory_vectors v ON v.memory_id = m.id WHERE m.kwant_id = ? ORDER BY m.created_at, m.rowid",
+ )
+ .bind(kwant_id)
+ .fetch_all(&self.pool)
+ .await?)
+ }
+
+ /// Stores (or replaces) a memory's vector as little-endian f32s. Nothing is stored for a memory
+ /// deleted meanwhile, so a slow embedding call never leaves an orphan row. True when stored.
+ pub async fn put_memory_vector(&self, memory_id: &str, model: &str, vec: &[f32], text_hash: &str) -> Result<bool, DbError> {
+ let bytes: Vec<u8> = vec.iter().flat_map(|f| f.to_le_bytes()).collect();
+ let res = sqlx::query(
+ "INSERT INTO kwant_memory_vectors (memory_id, model, dim, vec, text_hash) \
+ SELECT ?1, ?2, ?3, ?4, ?5 WHERE EXISTS (SELECT 1 FROM kwant_memories WHERE id = ?1) \
+ ON CONFLICT(memory_id) DO UPDATE SET model = excluded.model, dim = excluded.dim, \
+ vec = excluded.vec, text_hash = excluded.text_hash",
+ )
+ .bind(memory_id)
+ .bind(model)
+ .bind(vec.len() as i64)
+ .bind(bytes)
+ .bind(text_hash)
+ .execute(&self.pool)
+ .await?;
+ Ok(res.rows_affected() > 0)
+ }
+
pub async fn delete_memory(&self, kwant_id: &str, id: &str) -> Result<bool, DbError> {
let res = sqlx::query("DELETE FROM kwant_memories WHERE id = ? AND kwant_id = ?")
.bind(id)
diff --git a/src/server/continuity.rs b/src/server/continuity.rs
index 772b2eba..68da68a7 100644
--- a/src/server/continuity.rs
+++ b/src/server/continuity.rs
@@ -1323,7 +1323,7 @@ async fn call_tool(
return ("query needs at least one word".into(), true);
};
let limit = args["limit"].as_i64().unwrap_or(10);
- match db.search_memories(&scope.kwant_id, query, limit).await {
+ match super::memory_recall::search(state, &scope.kwant_id, query, limit).await {
Ok(mut hits) => {
// With the Truth Ledger on, only notes whose fact is in force
if let Some(visible) = super::missions::truth_ledger::visible_memory_ids(state, &scope.kwant_id).await {
diff --git a/src/server/memory_recall.rs b/src/server/memory_recall.rs
new file mode 100644
index 00000000..46b0d221
--- /dev/null
+++ b/src/server/memory_recall.rs
@@ -0,0 +1,444 @@
+//! Hybrid memory recall (roadmap Next #11): a bot's `memory_search` finds notes by meaning as well
+//! as by words. Each memory gets an embedding from the space's own provider (its OpenAI account,
+//! else a local Ollama with an embedding model pulled), kept in `kwant_memory_vectors`; a search
+//! ranks the kwant's notes by cosine similarity and by FTS5 bm25 and merges the two lists with
+//! Reciprocal Rank Fusion.
+//!
+//! With no embedding provider the search is exactly the keyword search it always was: the
+//! provider lookup reads only the database and the cached engine checks, so it makes no HTTP call
+//! and adds no wait. Memory text only ever goes to a provider the space already set up. Claude has
+//! no embeddings API, so a Claude-only space stays keyword-only.
+//!
+//! Caps: one query embedding per search with a [`QUERY_TIMEOUT`]; vectors are filled in the
+//! background, at most [`FILL_BATCH`] × [`FILL_ROUNDS`] per fill and one fill per kwant at a time;
+//! after a provider error that provider is left alone for [`COOLDOWN`].
+
+use super::AppState;
+use crate::db::continuity::{Memory, MAX_MEMORY_SEARCH_LIMIT};
+use crate::db::spaces::SpaceId;
+use crate::drivers::engines::{EngineId, EngineStatus};
+use crate::profiles::Engine;
+use serde_json::{json, Value};
+use sha2::{Digest, Sha256};
+use std::collections::{HashMap, HashSet};
+use std::sync::{LazyLock, Mutex};
+use std::time::{Duration, Instant};
+
+/// The OpenAI embedding model.
+pub const OPENAI_MODEL: &str = "text-embedding-3-small";
+/// Ollama embedding models, best first; else any pulled model whose name has `embed` in it.
+const OLLAMA_PREFERRED: [&str; 2] = ["nomic-embed-text", "mxbai-embed-large"];
+/// Longest wait for the query's embedding; past it the search is keyword-only.
+pub const QUERY_TIMEOUT: Duration = Duration::from_millis(1500);
+/// Longest wait for one batch of memory embeddings (in the background).
+const FILL_TIMEOUT: Duration = Duration::from_secs(20);
+/// Memories embedded per provider call.
+pub const FILL_BATCH: usize = 32;
+/// Calls per background fill: 4 × 32 covers a kwant's 100 notes.
+pub const FILL_ROUNDS: usize = 4;
+/// After a provider error, how long that provider isn't asked again.
+pub const COOLDOWN: Duration = Duration::from_secs(60);
+/// Candidates taken from each ranking before the merge.
+const CANDIDATES: usize = MAX_MEMORY_SEARCH_LIMIT as usize;
+/// Reciprocal Rank Fusion constant: score = Σ 1/(RRF_K + rank).
+const RRF_K: f64 = 60.0;
+/// Below this cosine a note isn't related enough to be a by-meaning candidate.
+const MIN_COSINE: f32 = 0.2;
+
+/// Where a space's embeddings come from.
+#[derive(Clone, PartialEq)]
+pub enum EmbedSource {
+ /// `base` is the API root without `/v1` (`https://api.openai.com`).
+ OpenAi { base: String, key: String },
+ /// `root` is the Ollama server root without `/v1`.
+ Ollama { root: String, model: String },
+}
+
+impl std::fmt::Debug for EmbedSource {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ EmbedSource::OpenAi { base, .. } => write!(f, "OpenAi({base}, key <redacted>)"),
+ EmbedSource::Ollama { root, model } => write!(f, "Ollama({root}, {model})"),
+ }
+ }
+}
+
+impl EmbedSource {
+ /// What a stored vector was made with; a vector from another model is stale.
+ pub fn model_id(&self) -> String {
+ match self {
+ EmbedSource::OpenAi { .. } => format!("openai/{OPENAI_MODEL}"),
+ EmbedSource::Ollama { model, .. } => format!("ollama/{model}"),
+ }
+ }
+
+ /// Cooldown key: one per provider endpoint, never containing the key.
+ fn cooldown_key(&self) -> String {
+ match self {
+ EmbedSource::OpenAi { base, .. } => format!("openai {base}"),
+ EmbedSource::Ollama { root, model } => format!("ollama {root} {model}"),
+ }
+ }
+}
+
+/// The Ollama embedding model to use from the pulled `models`, if any.
+pub fn pick_ollama_model<'a>(models: impl IntoIterator<Item = &'a str>) -> Option<String> {
+ let models: Vec<&str> = models.into_iter().collect();
+ let base = |m: &str| m.split(':').next().unwrap_or(m).to_string();
+ OLLAMA_PREFERRED
+ .iter()
+ .find_map(|p| models.iter().find(|m| base(m) == *p))
+ .or_else(|| models.iter().find(|m| m.to_ascii_lowercase().contains("embed")))
+ .map(|m| m.to_string())
+}
+
+/// The space's embedding provider, or `None`. Reads only the database, the environment and the
+/// cached engine checks: never a network call.
+///
+/// 1. An enabled OpenAI API-key account of the space (an `api_key` profile on Codex) with a key.
+/// 2. The host's OpenAI key (Settings, else `OPENAI_API_KEY`), unless This machine is off for
+/// Codex in the space or the OpenAI API engine is turned off.
+/// 3. A local Ollama whose last check was ready and that has an embedding model pulled.
+pub async fn source_for_space(state: &AppState, space: &SpaceId) -> Option<EmbedSource> {
+ let db = &state.db;
+ let openai_on = state.engines.is_enabled(EngineId::OpenaiApi);
+ let profiles = db.list_profiles(space).await.unwrap_or_default();
+ if openai_on {
+ for p in profiles.iter().filter(|p| p.engine == "codex" && p.kind == "api_key" && p.enabled) {
+ if let Ok(Some(key)) = db.get_profile_key(&p.id).await {
+ if !key.0.trim().is_empty() {
+ return Some(EmbedSource::OpenAi { base: "https://api.openai.com".into(), key: key.0.trim().to_string() });
+ }
+ }
+ }
+ let host_off = profiles.iter().any(|p| p.kind == "system" && !p.enabled && Engine::parse(&p.engine) == Some(Engine::Codex));
+ if !host_off {
+ let key = db
+ .get_setting("openai_api_key")
+ .await
+ .ok()
+ .flatten()
+ .or_else(|| std::env::var("OPENAI_API_KEY").ok())
+ .filter(|k| !k.trim().is_empty());
+ if let Some(key) = key {
+ return Some(EmbedSource::OpenAi { base: "https://api.openai.com".into(), key: key.trim().to_string() });
+ }
+ }
+ }
+ let ollama = state.engines.report(EngineId::Ollama);
+ if ollama.status != EngineStatus::Ready {
+ return None;
+ }
+ let model = pick_ollama_model(ollama.models.iter().map(|m| m.id.as_str()))?;
+ let url = db.get_setting("ollama_url").await.ok().flatten();
+ Some(EmbedSource::Ollama { root: crate::drivers::ollama_root(url.as_deref()), model })
+}
+
+/// The kwant's space's provider (see [`source_for_space`]).
+pub async fn source_for_kwant(state: &AppState, kwant_id: &str) -> Option<EmbedSource> {
+ let space = state.db.space_of_kwant(kwant_id).await.ok().flatten()?;
+ source_for_space(state, &space).await
+}
+
+static CLIENT: LazyLock<reqwest::Client> = LazyLock::new(reqwest::Client::new);
+
+/// Embeds `texts` in one call, in order. `Err` with a short reason that never contains the key.
+pub async fn embed(source: &EmbedSource, texts: &[String], timeout: Duration) -> Result<Vec<Vec<f32>>, String> {
+ if texts.is_empty() {
+ return Ok(Vec::new());
+ }
+ let req = match source {
+ EmbedSource::OpenAi { base, key } => CLIENT
+ .post(format!("{}/v1/embeddings", base.trim_end_matches('/')))
+ .bearer_auth(key)
+ .json(&json!({"model": OPENAI_MODEL, "input": texts})),
+ EmbedSource::Ollama { root, model } => CLIENT
+ .post(format!("{}/api/embed", root.trim_end_matches('/')))
+ .json(&json!({"model": model, "input": texts})),
+ };
+ let resp = req.timeout(timeout).send().await.map_err(|e| if e.is_timeout() { "timed out".to_string() } else { "not reachable".to_string() })?;
+ if !resp.status().is_success() {
+ return Err(format!("HTTP {}", resp.status().as_u16()));
+ }
+ let body: Value = resp.json().await.map_err(|_| "unreadable answer".to_string())?;
+ let vectors = parse_embeddings(source, &body).ok_or_else(|| "unexpected answer".to_string())?;
+ if vectors.len() != texts.len() || vectors.iter().any(|v| v.is_empty() || v.len() != vectors[0].len()) {
+ return Err("wrong number or size of vectors".into());
+ }
+ Ok(vectors)
+}
+
+/// OpenAI: `data[].embedding` (by `index`); Ollama: `embeddings[]`.
+fn parse_embeddings(source: &EmbedSource, body: &Value) -> Option<Vec<Vec<f32>>> {
+ let floats = |v: &Value| v.as_array().map(|a| a.iter().filter_map(|x| x.as_f64().map(|f| f as f32)).collect::<Vec<f32>>());
+ match source {
+ EmbedSource::OpenAi { .. } => {
+ let mut items: Vec<(i64, Vec<f32>)> = body["data"]
+ .as_array()?
+ .iter()
+ .enumerate()
+ .map(|(i, d)| Some((d["index"].as_i64().unwrap_or(i as i64), floats(&d["embedding"])?)))
+ .collect::<Option<_>>()?;
+ items.sort_by_key(|(i, _)| *i);
+ Some(items.into_iter().map(|(_, v)| v).collect())
+ }
+ EmbedSource::Ollama { .. } => body["embeddings"].as_array()?.iter().map(floats).collect(),
+ }
+}
+
+/// Hash of a memory's text, to tell a stale vector from a fresh one.
+pub fn text_hash(text: &str) -> String {
+ Sha256::digest(text.as_bytes()).iter().take(16).map(|b| format!("{b:02x}")).collect()
+}
+
+pub fn cosine(a: &[f32], b: &[f32]) -> f32 {
+ if a.len() != b.len() || a.is_empty() {
+ return 0.0;
+ }
+ let (mut dot, mut na, mut nb) = (0f32, 0f32, 0f32);
+ for (x, y) in a.iter().zip(b) {
+ dot += x * y;
+ na += x * x;
+ nb += y * y;
+ }
+ if na == 0.0 || nb == 0.0 {
+ 0.0
+ } else {
+ dot / (na.sqrt() * nb.sqrt())
+ }
+}
+
+/// Reciprocal Rank Fusion of ranked id lists (best first): score = Σ 1/(60 + rank), rank from 1.
+/// Ties keep the order of the first list, then the second.
+pub fn rrf(lists: &[&[String]]) -> Vec<String> {
+ let mut score: HashMap<&str, f64> = HashMap::new();
+ let mut first_seen: Vec<&str> = Vec::new();
+ for list in lists {
+ for (i, id) in list.iter().enumerate() {
+ let s = score.entry(id.as_str()).or_insert_with(|| {
+ first_seen.push(id.as_str());
+ 0.0
+ });
+ *s += 1.0 / (RRF_K + (i + 1) as f64);
+ }
+ }
+ let mut ids: Vec<(usize, &str)> = first_seen.into_iter().enumerate().collect();
+ ids.sort_by(|(ia, a), (ib, b)| score[b].partial_cmp(&score[a]).unwrap_or(std::cmp::Ordering::Equal).then(ia.cmp(ib)));
+ ids.into_iter().map(|(_, id)| id.to_string()).collect()
+}
+
+/// Providers in their cooldown after an error, until when.
+static COOLING: LazyLock<Mutex<HashMap<String, Instant>>> = LazyLock::new(|| Mutex::new(HashMap::new()));
+/// Kwants with a fill running.
+static FILLING: LazyLock<Mutex<HashSet<String>>> = LazyLock::new(|| Mutex::new(HashSet::new()));
+
+fn cooling(source: &EmbedSource) -> bool {
+ let mut map = COOLING.lock().unwrap();
+ let key = source.cooldown_key();
+ match map.get(&key) {
+ Some(until) if *until > Instant::now() => true,
+ Some(_) => {
+ map.remove(&key);
+ false
+ }
+ None => false,
+ }
+}
+
+fn cool_down(source: &EmbedSource, why: &str) {
+ tracing::warn!(provider = ?source, reason = why, "memory embeddings failed; keyword search only for a minute");
+ COOLING.lock().unwrap().insert(source.cooldown_key(), Instant::now() + COOLDOWN);
+}
+
+/// Forgets every cooldown (tests).
+pub fn reset_cooldowns() {
+ COOLING.lock().unwrap().clear();
+}
+
+/// The kwant's notes for `q`, best first, at most `limit` (1..=20). With no embedding provider,
+/// or no stored vectors yet, or when the query can't be embedded in time, this is exactly
+/// [`crate::db::Database::search_memories`]. Missing or stale vectors are filled in the
+/// background; the reply never waits for that.
+pub async fn search(state: &AppState, kwant_id: &str, q: &str, limit: i64) -> Result<Vec<Memory>, crate::db::DbError> {
+ let db = &state.db;
+ let Some(source) = source_for_kwant(state, kwant_id).await else {
+ return db.search_memories(kwant_id, q, limit).await;
+ };
+ let limit = limit.clamp(1, MAX_MEMORY_SEARCH_LIMIT) as usize;
+ let model = source.model_id();
+ let rows = db.memory_vector_rows(kwant_id).await?;
+ let mut missing = false;
+ let vectors: Vec<(String, Vec<f32>)> = rows
+ .iter()
+ .filter_map(|r| {
+ let v = r.fresh_vector(&model, &text_hash(&r.text));
+ missing |= v.is_none();
+ v.map(|v| (r.id.clone(), v))
+ })
+ .collect();
+ if missing {
+ fill_soon(state, kwant_id);
+ }
+ if vectors.is_empty() || cooling(&source) {
+ return db.search_memories(kwant_id, q, limit as i64).await;
+ }
+ let query_vec = match embed(&source, &[q.to_string()], QUERY_TIMEOUT).await {
+ Ok(mut v) => v.remove(0),
+ Err(why) => {
+ cool_down(&source, &why);
+ return db.search_memories(kwant_id, q, limit as i64).await;
+ }
+ };
+ let by_words: Vec<Memory> = db.search_memories(kwant_id, q, CANDIDATES as i64).await?;
+ let word_ids: Vec<String> = by_words.iter().map(|m| m.id.clone()).collect();
+ let mut by_meaning: Vec<(f32, &String)> = vectors
+ .iter()
+ .map(|(id, v)| (cosine(&query_vec, v), id))
+ .filter(|(c, _)| *c >= MIN_COSINE)
+ .collect();
+ by_meaning.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(std::cmp::Ordering::Equal));
+ let meaning_ids: Vec<String> = by_meaning.into_iter().take(CANDIDATES).map(|(_, id)| id.clone()).collect();
+ let merged = rrf(&[&word_ids, &meaning_ids]);
+ let mut by_id: HashMap<String, Memory> = by_words.into_iter().map(|m| (m.id.clone(), m)).collect();
+ if merged.iter().any(|id| !by_id.contains_key(id)) {
+ for m in db.list_memories(kwant_id).await? {
+ by_id.entry(m.id.clone()).or_insert(m);
+ }
+ }
+ Ok(merged.into_iter().filter_map(|id| by_id.remove(&id)).take(limit).collect())
+}
+
+/// Starts a background fill of the kwant's missing or stale vectors, unless one is running.
+pub fn fill_soon(state: &AppState, kwant_id: &str) {
+ let (state, kwant_id) = (state.clone(), kwant_id.to_string());
+ tokio::spawn(async move {
+ fill_now(&state, &kwant_id, FILL_ROUNDS).await;
+ });
+}
+
+/// Embeds up to `rounds` × [`FILL_BATCH`] of the kwant's notes whose vector is missing or stale,
+/// and returns how many it stored. 0 without a provider (no call made), during a cooldown, or
+/// when another fill for the kwant is running.
+pub async fn fill_now(state: &AppState, kwant_id: &str, rounds: usize) -> usize {
+ if !FILLING.lock().unwrap().insert(kwant_id.to_string()) {
+ return 0;
+ }
+ let stored = fill_rounds(state, kwant_id, rounds).await;
+ FILLING.lock().unwrap().remove(kwant_id);
+ stored
+}
+
+async fn fill_rounds(state: &AppState, kwant_id: &str, rounds: usize) -> usize {
+ let Some(source) = source_for_kwant(state, kwant_id).await else {
+ return 0;
+ };
+ let model = source.model_id();
+ let mut stored = 0;
+ for _ in 0..rounds {
+ if cooling(&source) {
+ break;
+ }
+ let Ok(rows) = state.db.memory_vector_rows(kwant_id).await else {
+ break;
+ };
+ let todo: Vec<(String, String, String)> = rows
+ .into_iter()
+ .filter_map(|r| {
+ let hash = text_hash(&r.text);
+ r.fresh_vector(&model, &hash).is_none().then_some((r.id, r.text, hash))
+ })
+ .take(FILL_BATCH)
+ .collect();
+ if todo.is_empty() {
+ break;
+ }
+ let texts: Vec<String> = todo.iter().map(|(_, t, _)| t.clone()).collect();
+ match embed(&source, &texts, FILL_TIMEOUT).await {
+ Ok(vectors) => {
+ for ((id, _, hash), v) in todo.iter().zip(vectors) {
+ if let Ok(true) = state.db.put_memory_vector(id, &model, &v, hash).await {
+ stored += 1;
+ }
+ }
+ }
+ Err(why) => {
+ cool_down(&source, &why);
+ break;
+ }
+ }
+ if todo.len() < FILL_BATCH {
+ break;
+ }
+ }
+ stored
+}
+
+/// Fills a kwant's vectors after each memory write (bot or person, add or edit), until shutdown.
+/// Imports and anything this misses are filled lazily by the next search.
+pub fn spawn(state: AppState, shutdown: tokio_util::sync::CancellationToken) {
+ let mut rx = state.event_sender.subscribe();
+ tokio::spawn(async move {
+ loop {
+ let ev = tokio::select! {
+ _ = shutdown.cancelled() => return,
+ ev = rx.recv() => ev,
+ };
+ match ev {
+ Ok(crate::drivers::events::RuntimeEvent::MemoryChanged { kwant_id }) => fill_soon(&state, &kwant_id),
+ Ok(_) | Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {}
+ Err(tokio::sync::broadcast::error::RecvError::Closed) => return,
+ }
+ }
+ });
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn rrf_rewards_notes_both_lists_agree_on() {
+ let words: Vec<String> = ["a", "b", "c"].map(String::from).into();
+ let meaning: Vec<String> = ["c", "d", "a"].map(String::from).into();
+ // a: 1/61 + 1/63, c: 1/63 + 1/61 (tie, a first from the first list), b: 1/62, d: 1/62
+ assert_eq!(rrf(&[&words, &meaning]), ["a", "c", "b", "d"]);
+ assert_eq!(rrf(&[&words, &[]]), ["a", "b", "c"], "one list alone keeps its order");
+ assert!(rrf(&[&[], &[]]).is_empty());
+ }
+
+ #[test]
+ fn cosine_handles_zero_and_mismatched_vectors() {
+ assert!((cosine(&[1.0, 0.0], &[2.0, 0.0]) - 1.0).abs() < 1e-6);
+ assert_eq!(cosine(&[1.0, 0.0], &[0.0, 1.0]), 0.0);
+ assert_eq!(cosine(&[0.0, 0.0], &[1.0, 0.0]), 0.0);
+ assert_eq!(cosine(&[1.0], &[1.0, 0.0]), 0.0);
+ }
+
+ #[test]
+ fn picks_an_embedding_model_only() {
+ assert_eq!(pick_ollama_model(["llama3.2:latest", "nomic-embed-text:latest"]).as_deref(), Some("nomic-embed-text:latest"));
+ assert_eq!(pick_ollama_model(["mxbai-embed-large", "nomic-embed-text"]).as_deref(), Some("nomic-embed-text"));
+ assert_eq!(pick_ollama_model(["llama3.2", "snowflake-arctic-embed:s"]).as_deref(), Some("snowflake-arctic-embed:s"));
+ assert_eq!(pick_ollama_model(["llama3.2", "qwen3"]), None);
+ }
+
+ #[test]
+ fn parses_both_answer_shapes_and_hides_the_key() {
+ let openai = EmbedSource::OpenAi { base: "https://x".into(), key: "sk-secret".into() };
+ let body = json!({"data": [{"index": 1, "embedding": [0.0, 1.0]}, {"index": 0, "embedding": [1.0, 0.0]}]});
+ assert_eq!(parse_embeddings(&openai, &body).unwrap(), vec![vec![1.0, 0.0], vec![0.0, 1.0]]);
+ let ollama = EmbedSource::Ollama { root: "http://o".into(), model: "nomic-embed-text".into() };
+ assert_eq!(parse_embeddings(&ollama, &json!({"embeddings": [[0.5, 0.5]]})).unwrap(), vec![vec![0.5, 0.5]]);
+ assert!(parse_embeddings(&ollama, &json!({"error": "no"})).is_none());
+ assert!(!format!("{openai:?}").contains("sk-secret"));
+ assert_eq!(openai.model_id(), "openai/text-embedding-3-small");
+ assert_eq!(ollama.model_id(), "ollama/nomic-embed-text");
+ }
+
+ #[test]
+ fn text_hash_tells_texts_apart() {
+ assert_eq!(text_hash("a"), text_hash("a"));
+ assert_ne!(text_hash("a"), text_hash("b"));
+ assert_eq!(text_hash("a").len(), 32);
+ }
+}
diff --git a/src/server/mod.rs b/src/server/mod.rs
index ea162446..f3b3ac6b 100644
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -14,6 +14,7 @@ pub mod engine_login;
pub mod auth;
pub mod signin;
pub mod continuity;
+pub mod memory_recall;
pub mod fresh_eyes;
pub mod goals_remediation;
pub mod model_usage;
diff --git a/src/server/scheduler.rs b/src/server/scheduler.rs
index 88979dd2..164586a9 100644
--- a/src/server/scheduler.rs
+++ b/src/server/scheduler.rs
@@ -889,6 +889,7 @@ pub fn spawn_background(state: AppState, shutdown: CancellationToken) {
crate::zombie::hunt::spawn(state.clone(), shutdown.clone());
crate::documents::reminders::spawn(state.clone(), shutdown.clone());
super::missions::listener::spawn(state.clone(), shutdown.clone());
+ super::memory_recall::spawn(state.clone(), shutdown.clone());
super::missions::foundry::spawn(state.clone(), shutdown.clone());
super::goals::runner::spawn(state.clone(), shutdown.clone());
super::missions::discovery::spawn(state.clone(), shutdown.clone());
diff --git a/tests/memory_hybrid_recall_test.rs b/tests/memory_hybrid_recall_test.rs
new file mode 100644
index 00000000..96ba4c9e
--- /dev/null
+++ b/tests/memory_hybrid_recall_test.rs
@@ -0,0 +1,421 @@
+//! Hybrid memory recall (roadmap Next #11): the bots' `memory_search` finds notes by meaning
+//! through the space's own embedding provider, merged with the FTS5 keyword search; with no
+//! provider it is exactly the keyword search it was, with no HTTP call.
+//!
+//! The provider here is a fake Ollama (and a fake OpenAI endpoint) whose "embeddings" put words
+//! of one concept (car/vehicle, refund/money-back, …) on one axis, so paraphrases land close.
+
+use axum::{
+ body::{to_bytes, Body},
+ extract::State,
+ http::{HeaderMap, Request},
+ routing::{get, post},
+ Json, Router,
+};
+use kwnt::{
+ broker::PermissionBroker,
+ config::Config,
+ db::{models::Kwant, spaces::SpaceId, Database},
+ drivers::engines::{EngineId, ProbeEnv},
+ router::LayaRouter,
+ server::{
+ continuity::SelfScope,
+ create_router, mcp_runtime,
+ memory_recall::{self, EmbedSource},
+ AppState,
+ },
+ tools::ToolRunner,
+};
+use serde_json::{json, Value};
+use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
+use std::sync::Arc;
+use std::time::{Duration, Instant};
+use tempfile::{tempdir, TempDir};
+use tower::ServiceExt;
+
+const DIM: usize = 16;
+
+/// A concept-axis "embedding": words of one concept share an axis; any other word lands, lightly,
+/// on one of the remaining axes.
+fn fake_embedding(text: &str) -> Vec<f32> {
+ const CONCEPTS: [&[&str]; 4] = [
+ &["car", "cars", "vehicle", "vehicles", "auto", "automobile"],
+ &["refund", "refunds", "money", "back", "reimburse", "returned"],
+ &["rules", "rule", "policy", "policies"],
+ &["customer", "customers", "client", "clients"],
+ ];
+ let mut v = vec![0f32; DIM];
+ for word in text.to_lowercase().split(|c: char| !c.is_alphanumeric()).filter(|w| !w.is_empty()) {
+ match CONCEPTS.iter().position(|c| c.contains(&word)) {
+ Some(axis) => v[axis] += 1.0,
+ None => v[4 + word.bytes().map(usize::from).sum::<usize>() % (DIM - 4)] += 0.3,
+ }
+ }
+ v
+}
+
+#[derive(Clone, Default)]
+struct Fake {
+ /// Every request the server got, of any kind.
+ calls: Arc<AtomicUsize>,
+ /// Embedding requests only, and how many texts they carried.
+ embed_calls: Arc<AtomicUsize>,
+ embedded_texts: Arc<AtomicUsize>,
+ /// Milliseconds to wait before answering a one-text (query) embedding.
+ query_delay_ms: Arc<AtomicU64>,
+ /// Ollama's pulled models.
+ models: Arc<std::sync::Mutex<Vec<String>>>,
+}
+
+async fn tags(State(f): State<Fake>) -> Json<Value> {
+ f.calls.fetch_add(1, Ordering::SeqCst);
+ let models = f.models.lock().unwrap().clone();
+ Json(json!({"models": models.iter().map(|m| json!({"name": m})).collect::<Vec<_>>()}))
+}
+
+async fn version(State(f): State<Fake>) -> Json<Value> {
+ f.calls.fetch_add(1, Ordering::SeqCst);
+ Json(json!({"version": "0.0.0-fake"}))
+}
+
+async fn inputs(f: &Fake, body: &Value) -> Vec<Vec<f32>> {
+ f.calls.fetch_add(1, Ordering::SeqCst);
+ f.embed_calls.fetch_add(1, Ordering::SeqCst);
+ let texts: Vec<String> = body["input"].as_array().unwrap().iter().map(|t| t.as_str().unwrap().to_string()).collect();
+ f.embedded_texts.fetch_add(texts.len(), Ordering::SeqCst);
+ let delay = f.query_delay_ms.load(Ordering::SeqCst);
+ if texts.len() == 1 && delay > 0 {
+ tokio::time::sleep(Duration::from_millis(delay)).await;
+ }
+ texts.iter().map(|t| fake_embedding(t)).collect()
+}
+
+async fn ollama_embed(State(f): State<Fake>, Json(body): Json<Value>) -> Json<Value> {
+ Json(json!({"model": body["model"], "embeddings": inputs(&f, &body).await}))
+}
+
+async fn openai_embed(State(f): State<Fake>, headers: HeaderMap, Json(body): Json<Value>) -> axum::response::Response {
+ use axum::response::IntoResponse;
+ if headers.get("authorization").and_then(|h| h.to_str().ok()) != Some("Bearer sk-test") {
+ f.calls.fetch_add(1, Ordering::SeqCst);
+ return (axum::http::StatusCode::UNAUTHORIZED, Json(json!({"error": "bad key"}))).into_response();
+ }
+ assert_eq!(body["model"], "text-embedding-3-small");
+ let vectors = inputs(&f, &body).await;
+ // Answer out of order: the client must sort by index
+ let data: Vec<Value> = vectors.iter().enumerate().rev().map(|(i, v)| json!({"index": i, "embedding": v})).collect();
+ Json(json!({"data": data})).into_response()
+}
+
+async fn fake_server(models: &[&str]) -> (String, Fake) {
+ let fake = Fake::default();
+ *fake.models.lock().unwrap() = models.iter().map(|m| m.to_string()).collect();
+ let app = Router::new()
+ .route("/api/tags", get(tags))
+ .route("/api/version", get(version))
+ .route("/api/embed", post(ollama_embed))
+ .route("/v1/embeddings", post(openai_embed))
+ .with_state(fake.clone());
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let url = format!("http://{}", listener.local_addr().unwrap());
+ tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
+ (url, fake)
+}
+
+async fn setup() -> (Router, AppState, TempDir) {
+ // The host's own OpenAI key would be a provider; these tests choose theirs
+ std::env::remove_var("OPENAI_API_KEY");
+ std::env::remove_var("OLLAMA_URL");
+ let tmp = tempdir().unwrap();
+ let db = Database::init(tmp.path()).await.unwrap();
+ db.set_setting("mission_board", "false").await.unwrap();
+ let config = Config { data_dir: tmp.path().to_path_buf(), ..Config::default() };
+ let state = AppState::new(
+ config.clone(),
+ db,
+ ToolRunner::new(tmp.path().join("workspace")),
+ PermissionBroker::new(),
+ LayaRouter::new(config.laya_url.clone()),
+ );
+ (create_router(state.clone()), state, tmp)
+}
+
+/// Points the space at the fake Ollama and runs its engine check there, as the app does.
+async fn use_ollama(state: &AppState, url: &str) {
+ state.db.set_setting("ollama_url", url).await.unwrap();
+ let env = ProbeEnv { ollama_root: url.to_string(), ..ProbeEnv::default() };
+ state.engines.recheck_one(EngineId::Ollama, &env).await;
+}
+
+async fn first_kwant(state: &AppState) -> Kwant {
+ state.db.list_kwants(&SpaceId::default_space()).await.unwrap().remove(0)
+}
+
+/// Calls the kwant's own `memory_search` tool the way a turn does.
+async fn memory_search(app: &Router, state: &AppState, k: &Kwant, query: &str) -> String {
+ let (_ctx, token) = mcp_runtime::prepare_turn_with_self(
+ state,
+ k,
+ None,
+ None,
+ Some(SelfScope { kwant_id: k.id.clone(), kwant_name: k.name.clone(), ..Default::default() }),
+ )
+ .await
+ .unwrap();
+ let body = json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call",
+ "params": {"name": "memory_search", "arguments": {"query": query}}});
+ let resp = app
+ .clone()
+ .oneshot(
+ Request::builder()
+ .method("POST")
+ .uri("/api/mcp/self")
+ .header("content-type", "application/json")
+ .header("authorization", format!("Bearer {token}"))
+ .body(Body::from(body.to_string()))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ let v: Value = serde_json::from_slice(&to_bytes(resp.into_body(), usize::MAX).await.unwrap()).unwrap();
+ assert_eq!(v["result"]["isError"], false, "{v}");
+ v["result"]["content"][0]["text"].as_str().unwrap().to_string()
+}
+
+const VEHICLE: &str = "Oleks parks the vehicle in the garage on Elm street";
+const MONEY_BACK: &str = "Money-back policy: clients get their money returned within 30 days";
+
+async fn seed(state: &AppState, k: &Kwant) -> (String, String) {
+ let db = &state.db;
+ let v = db.add_memory(&k.id, VEHICLE, "user").await.unwrap().id;
+ let m = db.add_memory(&k.id, MONEY_BACK, "agent").await.unwrap().id;
+ for text in ["Daughter's birthday is 3 March", "Prefers short answers in the morning", "The office wifi password lives in the vault"] {
+ db.add_memory(&k.id, text, "agent").await.unwrap();
+ }
+ (v, m)
+}
+
+#[tokio::test]
+async fn paraphrases_are_found_with_embeddings_and_missed_without() {
+ let (app, state, _tmp) = setup().await;
+ let k = first_kwant(&state).await;
+ let (vehicle, money_back) = seed(&state, &k).await;
+
+ // Embeddings off: keyword search alone misses both paraphrases
+ assert_eq!(memory_search(&app, &state, &k, "car").await, "No matching notes.");
+ assert_eq!(memory_search(&app, &state, &k, "customer refund rules").await, "No matching notes.");
+
+ let (url, fake) = fake_server(&["llama3.2:latest", "nomic-embed-text:latest"]).await;
+ use_ollama(&state, &url).await;
+ assert_eq!(
+ memory_recall::source_for_kwant(&state, &k.id).await,
+ Some(EmbedSource::Ollama { root: url.clone(), model: "nomic-embed-text:latest".into() })
+ );
+ assert_eq!(memory_recall::fill_now(&state, &k.id, memory_recall::FILL_ROUNDS).await, 5);
+ assert_eq!(fake.embed_calls.load(Ordering::SeqCst), 1, "five notes in one batch");
+ assert_eq!(memory_recall::fill_now(&state, &k.id, memory_recall::FILL_ROUNDS).await, 0, "nothing left to fill");
+
+ // Embeddings on: found by meaning, through the bots' own tool
+ let found = memory_search(&app, &state, &k, "car").await;
+ assert!(found.contains(&vehicle) && found.contains(VEHICLE), "{found}");
+ assert!(!found.contains(&money_back), "unrelated notes stay out: {found}");
+ let found = memory_search(&app, &state, &k, "customer refund rules").await;
+ assert!(found.contains(&money_back) && found.contains("Money-back policy"), "{found}");
+ assert!(!found.contains(&vehicle), "{found}");
+ // Keywords still work, and come first when both agree
+ let found = memory_search(&app, &state, &k, "birthday").await;
+ assert!(found.contains("Daughter's birthday"), "{found}");
+ let found = memory_search(&app, &state, &k, "vehicle garage").await;
+ assert!(found.find(VEHICLE).is_some(), "{found}");
+ // One query embedding per search, nothing more
+ let before = fake.embed_calls.load(Ordering::SeqCst);
+ memory_search(&app, &state, &k, "car").await;
+ assert_eq!(fake.embed_calls.load(Ordering::SeqCst), before + 1);
+}
+
+#[tokio::test]
+async fn without_a_provider_search_is_todays_keyword_search_with_no_http_call() {
+ let (app, state, _tmp) = setup().await;
+ let k = first_kwant(&state).await;
+ seed(&state, &k).await;
+ for i in 0..12 {
+ state.db.add_memory(&k.id, &format!("garage note {i} about the garage door and the garage key"), "agent").await.unwrap();
+ }
+ // An Ollama server is configured but never checked ready, and there is no OpenAI key
+ let (url, fake) = fake_server(&["nomic-embed-text"]).await;
+ state.db.set_setting("ollama_url", &url).await.unwrap();
+ assert_eq!(memory_recall::source_for_kwant(&state, &k.id).await, None);
+
+ for q in ["garage", "garage door", "the", "car", "birthday March"] {
+ let today = state.db.search_memories(&k.id, q, 10).await.unwrap();
+ let now = memory_recall::search(&state, &k.id, q, 10).await.unwrap();
+ assert_eq!(now, today, "same notes in the same order for {q:?}");
+ }
+ assert_eq!(memory_recall::fill_now(&state, &k.id, memory_recall::FILL_ROUNDS).await, 0);
+ let text = memory_search(&app, &state, &k, "garage").await;
+ assert!(text.contains("garage note"), "{text}");
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ assert_eq!(fake.calls.load(Ordering::SeqCst), 0, "no HTTP call of any kind");
+
+ // A ready Ollama with chat models only is no embedding provider either
+ let (url, fake) = fake_server(&["llama3.2", "qwen3"]).await;
+ use_ollama(&state, &url).await;
+ let probed = fake.calls.load(Ordering::SeqCst);
+ assert_eq!(memory_recall::source_for_kwant(&state, &k.id).await, None);
+ assert_eq!(memory_recall::search(&state, &k.id, "garage", 10).await.unwrap(), state.db.search_memories(&k.id, "garage", 10).await.unwrap());
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ assert_eq!(fake.calls.load(Ordering::SeqCst), probed, "only the engine check itself");
+}
+
+#[tokio::test]
+async fn stale_vectors_are_refilled_and_deleted_with_their_memory() {
+ let (_app, state, tmp) = setup().await;
+ let k = first_kwant(&state).await;
+ let (vehicle, money_back) = seed(&state, &k).await;
+ let (url, fake) = fake_server(&["mxbai-embed-large"]).await;
+ use_ollama(&state, &url).await;
+ assert_eq!(memory_recall::fill_now(&state, &k.id, 4).await, 5);
+
+ // The person edits a note: its old vector no longer counts, a search starts a refill
+ state.db.update_memory(&k.id, &money_back, "Clients may get a refund within 30 days").await.unwrap();
+ let hits = memory_recall::search(&state, &k.id, "reimburse", 10).await.unwrap();
+ assert!(hits.iter().all(|m| m.id != money_back), "the stale vector isn't used");
+ let mut waited = 0;
+ while fake.embedded_texts.load(Ordering::SeqCst) < 7 && waited < 50 {
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ waited += 1;
+ }
+ // 5 notes + 1 query + the 1 edited note, filled in the background
+ assert_eq!(fake.embedded_texts.load(Ordering::SeqCst), 7);
+ let hits = memory_recall::search(&state, &k.id, "reimburse", 10).await.unwrap();
+ assert_eq!(hits.first().map(|m| m.id.as_str()), Some(money_back.as_str()));
+
+ // A vector made by another model is stale too
+ assert!(state.db.put_memory_vector(&money_back, "ollama/other-model", &[1.0; 16], &memory_recall::text_hash("Clients may get a refund within 30 days")).await.unwrap());
+ let row = state.db.memory_vector_rows(&k.id).await.unwrap().into_iter().find(|r| r.id == money_back).unwrap();
+ assert!(row.fresh_vector("ollama/other-model", &memory_recall::text_hash(&row.text)).is_some());
+ assert!(row.fresh_vector("ollama/mxbai-embed-large", &memory_recall::text_hash(&row.text)).is_none());
+ assert_eq!(memory_recall::fill_now(&state, &k.id, 4).await, 1, "refilled with the space's model");
+ let count = |sql: &'static str| {
+ let path = tmp.path().join("kwnt.db");
+ async move {
+ let pool = sqlx::sqlite::SqlitePoolOptions::new().connect(&format!("sqlite://{}", path.display())).await.unwrap();
+ let (n,): (i64,) = sqlx::query_as(sql).fetch_one(&pool).await.unwrap();
+ pool.close().await;
+ n
+ }
+ };
+ assert_eq!(count("SELECT COUNT(*) FROM kwant_memory_vectors").await, 5);
+
+ // Deleting a memory deletes its vector
+ assert!(state.db.delete_memory(&k.id, &vehicle).await.unwrap());
+ assert_eq!(count("SELECT COUNT(*) FROM kwant_memory_vectors").await, 4);
+ assert!(!state.db.put_memory_vector(&vehicle, "ollama/x", &[1.0], "h").await.unwrap(), "no vector for a deleted note");
+ assert_eq!(count("SELECT COUNT(*) FROM kwant_memory_vectors WHERE dim <> 16 OR model <> 'ollama/mxbai-embed-large'").await, 0);
+}
+
+#[tokio::test]
+async fn a_slow_provider_falls_back_to_keywords_and_cools_down() {
+ let (_app, state, _tmp) = setup().await;
+ let k = first_kwant(&state).await;
+ seed(&state, &k).await;
+ let (url, fake) = fake_server(&["nomic-embed-text"]).await;
+ use_ollama(&state, &url).await;
+ memory_recall::fill_now(&state, &k.id, 4).await;
+ fake.query_delay_ms.store(3000, Ordering::SeqCst);
+
+ let started = Instant::now();
+ let hits = memory_recall::search(&state, &k.id, "car", 10).await.unwrap();
+ let took = started.elapsed();
+ assert!(hits.is_empty(), "keyword-only result");
+ assert!(took < Duration::from_millis(2500), "gave up at the query timeout: {took:?}");
+ // In the cooldown no call is made at all
+ let calls = fake.embed_calls.load(Ordering::SeqCst);
+ let started = Instant::now();
+ assert!(memory_recall::search(&state, &k.id, "car", 10).await.unwrap().is_empty());
+ assert!(started.elapsed() < Duration::from_millis(300));
+ assert_eq!(fake.embed_calls.load(Ordering::SeqCst), calls);
+}
+
+#[tokio::test]
+async fn an_openai_account_embeds_with_its_key() {
+ let (url, fake) = fake_server(&[]).await;
+ let source = EmbedSource::OpenAi { base: url.clone(), key: "sk-test".into() };
+ let texts = vec!["car".to_string(), MONEY_BACK.to_string()];
+ let vectors = memory_recall::embed(&source, &texts, Duration::from_secs(2)).await.unwrap();
+ assert_eq!(vectors, vec![fake_embedding("car"), fake_embedding(MONEY_BACK)], "sorted back by index");
+ let wrong = EmbedSource::OpenAi { base: url, key: "sk-wrong".into() };
+ let err = memory_recall::embed(&wrong, &texts, Duration::from_secs(2)).await.unwrap_err();
+ assert_eq!(err, "HTTP 401");
+ assert_eq!(fake.embed_calls.load(Ordering::SeqCst), 1);
+
+ // The space's own OpenAI key (Settings) is chosen before a local Ollama
+ let (_app, state, _tmp) = setup().await;
+ let k = first_kwant(&state).await;
+ let (ollama, _) = fake_server(&["nomic-embed-text"]).await;
+ use_ollama(&state, &ollama).await;
+ state.db.set_setting("openai_api_key", "sk-space").await.unwrap();
+ assert_eq!(
+ memory_recall::source_for_kwant(&state, &k.id).await,
+ Some(EmbedSource::OpenAi { base: "https://api.openai.com".into(), key: "sk-space".into() })
+ );
+ // …unless the OpenAI API engine is turned off
+ state.engines.set_enabled(EngineId::OpenaiApi, false);
+ assert!(matches!(memory_recall::source_for_kwant(&state, &k.id).await, Some(EmbedSource::Ollama { .. })));
+}
+
+/// The latency of one search over ~500 notes, with and without embeddings (printed; run with
+/// `--nocapture`). The cap of 100 notes per bot is bypassed with direct inserts.
+#[tokio::test]
+async fn search_latency_with_500_memories() {
+ let (_app, state, tmp) = setup().await;
+ let k = first_kwant(&state).await;
+ let pool = sqlx::sqlite::SqlitePoolOptions::new()
+ .connect(&format!("sqlite://{}", tmp.path().join("kwnt.db").display()))
+ .await
+ .unwrap();
+ let words = ["garage", "vehicle", "refund", "policy", "birthday", "meeting", "invoice", "travel", "school", "doctor"];
+ for i in 0..500 {
+ let text = format!("note {i}: {} {} and {} details number {}", words[i % 10], words[(i / 10) % 10], words[(i / 7) % 10], i * 37);
+ sqlx::query("INSERT INTO kwant_memories (id, kwant_id, text, source, created_at, updated_at) VALUES (?, ?, ?, 'agent', ?, ?)")
+ .bind(format!("bench-{i}"))
+ .bind(&k.id)
+ .bind(text)
+ .bind(chrono::Utc::now())
+ .bind(chrono::Utc::now())
+ .execute(&pool)
+ .await
+ .unwrap();
+ }
+ pool.close().await;
+
+ let time = |label: &'static str, hybrid: bool| {
+ let (state, k) = (state.clone(), k.id.clone());
+ async move {
+ let runs = 20;
+ let started = Instant::now();
+ let mut n = 0;
+ for q in ["car", "refund rules", "garage", "doctor visit", "travel invoice"].iter().cycle().take(runs) {
+ n += if hybrid {
+ memory_recall::search(&state, &k, q, 10).await.unwrap().len()
+ } else {
+ state.db.search_memories(&k, q, 10).await.unwrap().len()
+ };
+ }
+ let per = started.elapsed() / runs as u32;
+ println!("{label}: {per:?} per search ({n} hits over {runs} searches)");
+ per
+ }
+ };
+ let keywords = time("keyword only (today, no provider)", false).await;
+ let none = time("memory_recall::search with no provider", true).await;
+
+ let (url, _fake) = fake_server(&["nomic-embed-text"]).await;
+ use_ollama(&state, &url).await;
+ let started = Instant::now();
+ assert_eq!(memory_recall::fill_now(&state, &k.id, 100).await, 500);
+ println!("embedding 500 notes in batches of {}: {:?}", memory_recall::FILL_BATCH, started.elapsed());
+ let hybrid = time("hybrid (local fake embedding server)", true).await;
+ assert!(keywords < Duration::from_millis(200) && none < Duration::from_millis(200), "{keywords:?} {none:?}");
+ assert!(hybrid < Duration::from_millis(500), "{hybrid:?}");
+}