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.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
recall-hardening: per-model similarity floor, no missed fill, no retries on a rejected host key (N1–N5) (#630)
Oleksandr Ivanchenko9f4fc99a9e7d
diff --git a/docs/mission-control.md b/docs/mission-control.mdindex f3259de0..6f4287ae 100644--- a/docs/mission-control.md+++ b/docs/mission-control.md@@ -1527,10 +1527,10 @@ Routine and hand-off turns aren't tied to a task, so they get the chat-sized bloA 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.+**Provider.** First the space's OpenAI account: a Codex API-key account, else the host's OpenAI key (Settings, else `OPENAI_API_KEY`) when the OpenAI API engine's last check passed and This machine isn't off for Codex (the same `host_off` rule turns use). 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.+**With a provider.** The query is embedded once, with a 1.5 s timeout. The keyword top 20 and the cosine top 20 above the model's floor (0.25 for OpenAI `text-embedding-3-small`; 0.5 for a local model, which scores unrelated text 0.3–0.4) 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.+**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; a note written while one runs makes it do one more pass when it ends. A fill that fails or is cancelled frees its bot for the next one. Deleting a note deletes its vector through a trigger.diff --git a/src/server/memory_recall.rs b/src/server/memory_recall.rsindex 46b0d221..4224713b 100644--- a/src/server/memory_recall.rs+++ b/src/server/memory_recall.rs@@ -13,14 +13,14 @@//! 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 super::{profile_turn, 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::collections::HashMap;use std::sync::{LazyLock, Mutex};use std::time::{Duration, Instant};@@ -42,8 +42,13 @@ pub const COOLDOWN: Duration = Duration::from_secs(60);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;+/// Below this cosine a note isn't related enough to be a by-meaning candidate, for OpenAI+/// `text-embedding-3-small`: it scores unrelated text about 0.0–0.15 and a paraphrase 0.3 or more.+pub const OPENAI_MIN_COSINE: f32 = 0.25;+/// The same floor for a local Ollama model. `nomic-embed-text` and `mxbai-embed-large` score+/// unrelated text 0.3–0.4, so a lower floor keeps every note; any other local model gets this,+/// the stricter of the two.+pub const LOCAL_MIN_COSINE: f32 = 0.5;/// Where a space's embeddings come from.#[derive(Clone, PartialEq)]@@ -72,6 +77,14 @@ impl EmbedSource {}}+ /// The lowest cosine that counts as related, on this model's own scale.+ pub fn min_cosine(&self) -> f32 {+ match self {+ EmbedSource::OpenAi { .. } => OPENAI_MIN_COSINE,+ EmbedSource::Ollama { .. } => LOCAL_MIN_COSINE,+ }+ }+/// Cooldown key: one per provider endpoint, never containing the key.fn cooldown_key(&self) -> String {match self {@@ -96,8 +109,9 @@ pub fn pick_ollama_model<'a>(models: impl IntoIterator<Item = &'a str>) -> Optio/// 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.+/// 2. The host's OpenAI key (Settings, else `OPENAI_API_KEY`), when the OpenAI API engine's last+/// check passed (so a revoked key isn't tried again every minute) and This machine isn't off+/// for Codex in the space (the rule turns use: [`profile_turn::host_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;@@ -111,8 +125,8 @@ pub async fn source_for_space(state: &AppState, space: &SpaceId) -> Option<Embed}}}- let host_off = profiles.iter().any(|p| p.kind == "system" && !p.enabled && Engine::parse(&p.engine) == Some(Engine::Codex));- if !host_off {+ let host_ready = state.engines.report(EngineId::OpenaiApi).status == EngineStatus::Ready;+ if host_ready && !profile_turn::host_off(state, space).await.contains(&Engine::Codex) {let key = db.get_setting("openai_api_key").await@@ -229,8 +243,56 @@ pub fn rrf(lists: &[&[String]]) -> Vec<String> {/// 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()));+/// Kwants with a fill running, each with whether a note changed since that fill read its notes.+static FILLING: LazyLock<Mutex<HashMap<String, bool>>> = LazyLock::new(|| Mutex::new(HashMap::new()));++fn filling() -> std::sync::MutexGuard<'static, HashMap<String, bool>> {+ FILLING.lock().unwrap_or_else(|e| e.into_inner())+}++/// A kwant's place in [`FILLING`]: one fill per kwant at a time. Dropping it frees the place, so+/// a fill that panics or is cancelled doesn't leave the kwant marked as filling until restart.+struct FillSlot {+ kwant_id: String,+ released: bool,+}++impl FillSlot {+ /// The kwant's slot, or `None` when a fill is already running; then that fill is told to run+ /// one more pass, so the note that changed gets its vector without waiting for a search.+ fn take(kwant_id: &str) -> Option<FillSlot> {+ let mut map = filling();+ if let Some(dirty) = map.get_mut(kwant_id) {+ *dirty = true;+ return None;+ }+ map.insert(kwant_id.to_string(), false);+ Some(FillSlot { kwant_id: kwant_id.to_string(), released: false })+ }++ /// After a pass: `true` (and the flag cleared) when a note changed during it, so another+ /// pass is due; else frees the slot. One lock for both, so no change slips in between.+ fn again_or_release(&mut self) -> bool {+ let mut map = filling();+ if let Some(dirty) = map.get_mut(&self.kwant_id) {+ if *dirty {+ *dirty = false;+ return true;+ }+ }+ map.remove(&self.kwant_id);+ self.released = true;+ false+ }+}++impl Drop for FillSlot {+ fn drop(&mut self) {+ if !self.released {+ filling().remove(&self.kwant_id);+ }+ }+}fn cooling(source: &EmbedSource) -> bool {let mut map = COOLING.lock().unwrap();@@ -294,7 +356,7 @@ pub async fn search(state: &AppState, kwant_id: &str, q: &str, limit: i64) -> Relet mut by_meaning: Vec<(f32, &String)> = vectors.iter().map(|(id, v)| (cosine(&query_vec, v), id))- .filter(|(c, _)| *c >= MIN_COSINE)+ .filter(|(c, _)| *c >= source.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();@@ -318,13 +380,15 @@ pub fn fill_soon(state: &AppState, kwant_id: &str) {/// 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.+/// when another fill for the kwant is running: that fill then makes one more pass when it ends.pub async fn fill_now(state: &AppState, kwant_id: &str, rounds: usize) -> usize {- if !FILLING.lock().unwrap().insert(kwant_id.to_string()) {+ let Some(mut slot) = FillSlot::take(kwant_id) else {return 0;+ };+ let mut stored = fill_rounds(state, kwant_id, rounds).await;+ while slot.again_or_release() {+ stored += fill_rounds(state, kwant_id, rounds).await;}- let stored = fill_rounds(state, kwant_id, rounds).await;- FILLING.lock().unwrap().remove(kwant_id);stored}@@ -435,6 +499,46 @@ mod tests {assert_eq!(ollama.model_id(), "ollama/nomic-embed-text");}+ #[test]+ fn each_model_has_its_own_floor() {+ let openai = EmbedSource::OpenAi { base: "https://x".into(), key: "k".into() };+ assert_eq!(openai.min_cosine(), 0.25);+ for model in ["nomic-embed-text:latest", "mxbai-embed-large", "snowflake-arctic-embed:s"] {+ let local = EmbedSource::Ollama { root: "http://o".into(), model: model.into() };+ assert_eq!(local.min_cosine(), 0.5, "{model}: the stricter floor");+ }+ }++ #[test]+ fn a_panicking_fill_frees_its_kwant() {+ let kwant = "fill-slot-panic-test";+ let caught = std::panic::catch_unwind(|| {+ let _slot = FillSlot::take(kwant).unwrap();+ assert!(FillSlot::take(kwant).is_none(), "one fill per kwant");+ panic!("a fill panicked");+ });+ assert!(caught.is_err());+ assert!(!filling().contains_key(kwant), "the slot was freed by the panic");+ let mut slot = FillSlot::take(kwant).expect("a new fill may start");+ assert!(!slot.again_or_release());+ assert!(!filling().contains_key(kwant));+ }++ #[test]+ fn a_change_during_a_fill_asks_for_one_more_pass() {+ let kwant = "fill-slot-dirty-test";+ let mut slot = FillSlot::take(kwant).unwrap();+ assert!(FillSlot::take(kwant).is_none(), "a write while the fill runs");+ assert!(FillSlot::take(kwant).is_none(), "and another: still one more pass");+ assert!(slot.again_or_release(), "one more pass");+ assert!(filling().contains_key(kwant), "still filling during that pass");+ assert!(!slot.again_or_release(), "nothing changed during it");+ assert!(!filling().contains_key(kwant));+ drop(slot);+ assert!(FillSlot::take(kwant).is_some(), "drop after release frees nothing twice");+ filling().remove(kwant);+ }+#[test]fn text_hash_tells_texts_apart() {assert_eq!(text_hash("a"), text_hash("a"));diff --git a/tests/memory_hybrid_recall_test.rs b/tests/memory_hybrid_recall_test.rsindex 96ba4c9e..59be048e 100644--- a/tests/memory_hybrid_recall_test.rs+++ b/tests/memory_hybrid_recall_test.rs@@ -15,8 +15,12 @@ use axum::{use kwnt::{broker::PermissionBroker,config::Config,- db::{models::Kwant, spaces::SpaceId, Database},- drivers::engines::{EngineId, ProbeEnv},+ db::{+ models::{Kwant, LlmProfilePatch},+ spaces::SpaceId,+ Database,+ },+ drivers::engines::{EngineId, EngineStatus, ProbeEnv},router::LayaRouter,server::{continuity::SelfScope,@@ -27,7 +31,7 @@ use kwnt::{tools::ToolRunner,};use serde_json::{json, Value};-use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};+use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};use std::sync::Arc;use std::time::{Duration, Instant};use tempfile::{tempdir, TempDir};@@ -54,6 +58,19 @@ fn fake_embedding(text: &str) -> Vec<f32> {v}+/// A concept-axis embedding with one axis every text shares, as real local models have: any two+/// unrelated texts score [`UNRELATED_COSINE`] (nomic-embed-text gives unrelated text 0.3–0.4).+fn shared_axis_embedding(text: &str) -> Vec<f32> {+ let v = fake_embedding(text);+ let norm = v.iter().map(|x| x * x).sum::<f32>().sqrt();+ let mut v: Vec<f32> = v.iter().map(|x| if norm > 0.0 { x / norm } else { 0.0 }).collect();+ // cos(a, b) = (a·b + s²) / (1 + s²) for unit a, b; a·b = 0 gives s² / (1 + s²)+ v.push((UNRELATED_COSINE / (1.0 - UNRELATED_COSINE)).sqrt());+ v+}++const UNRELATED_COSINE: f32 = 0.35;+#[derive(Clone, Default)]struct Fake {/// Every request the server got, of any kind.@@ -63,6 +80,10 @@ struct Fake {embedded_texts: Arc<AtomicUsize>,/// Milliseconds to wait before answering a one-text (query) embedding.query_delay_ms: Arc<AtomicU64>,+ /// Milliseconds to wait before answering a batch of several texts (a fill).+ batch_delay_ms: Arc<AtomicU64>,+ /// Embed with [`shared_axis_embedding`] instead of [`fake_embedding`].+ shared_axis: Arc<AtomicBool>,/// Ollama's pulled models.models: Arc<std::sync::Mutex<Vec<String>>>,}@@ -83,11 +104,12 @@ async fn inputs(f: &Fake, body: &Value) -> Vec<Vec<f32>> {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 {+ let delay = if texts.len() == 1 { &f.query_delay_ms } else { &f.batch_delay_ms }.load(Ordering::SeqCst);+ if delay > 0 {tokio::time::sleep(Duration::from_millis(delay)).await;}- texts.iter().map(|t| fake_embedding(t)).collect()+ let shared = f.shared_axis.load(Ordering::SeqCst);+ texts.iter().map(|t| if shared { shared_axis_embedding(t) } else { fake_embedding(t) }).collect()}async fn ollama_embed(State(f): State<Fake>, Json(body): Json<Value>) -> Json<Value> {@@ -107,6 +129,24 @@ async fn openai_embed(State(f): State<Fake>, headers: HeaderMap, Json(body): JsoJson(json!({"data": data})).into_response()}+/// The OpenAI API engine check: listing models needs a valid key.+async fn openai_models(State(f): State<Fake>, headers: HeaderMap) -> axum::response::Response {+ use axum::response::IntoResponse;+ f.calls.fetch_add(1, Ordering::SeqCst);+ if headers.get("authorization").and_then(|h| h.to_str().ok()) != Some("Bearer sk-test") {+ let body = json!({"error": {"message": "Incorrect API key provided", "type": "invalid_request_error", "code": "invalid_api_key"}});+ return (axum::http::StatusCode::UNAUTHORIZED, Json(body)).into_response();+ }+ Json(json!({"data": [{"id": "gpt-5.5"}]})).into_response()+}++/// Runs the OpenAI API engine check with `key` against the fake, as the app does with its key.+async fn check_openai(state: &AppState, url: &str, key: &str) -> EngineStatus {+ let env = ProbeEnv { openai_key: Some(key.into()), openai_base: url.to_string(), ..ProbeEnv::default() };+ state.engines.recheck_one(EngineId::OpenaiApi, &env).await;+ state.engines.report(EngineId::OpenaiApi).status+}+async fn fake_server(models: &[&str]) -> (String, Fake) {let fake = Fake::default();*fake.models.lock().unwrap() = models.iter().map(|m| m.to_string()).collect();@@ -115,6 +155,7 @@ async fn fake_server(models: &[&str]) -> (String, Fake) {.route("/api/version", get(version)).route("/api/embed", post(ollama_embed)).route("/v1/embeddings", post(openai_embed))+ .route("/v1/models", get(openai_models)).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());@@ -344,20 +385,25 @@ async fn an_openai_account_embeds_with_its_key() {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 wrong = EmbedSource::OpenAi { base: url.clone(), 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+ // The host's OpenAI key (Settings) is chosen before a local Ollama, once its check passedlet (_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();+ state.db.set_setting("openai_api_key", "sk-test").await.unwrap();+ assert!(+ matches!(memory_recall::source_for_kwant(&state, &k.id).await, Some(EmbedSource::Ollama { .. })),+ "not before the OpenAI API check has passed"+ );+ assert_eq!(check_openai(&state, &url, "sk-test").await, EngineStatus::Ready);assert_eq!(memory_recall::source_for_kwant(&state, &k.id).await,- Some(EmbedSource::OpenAi { base: "https://api.openai.com".into(), key: "sk-space".into() })+ Some(EmbedSource::OpenAi { base: "https://api.openai.com".into(), key: "sk-test".into() }));// …unless the OpenAI API engine is turned offstate.engines.set_enabled(EngineId::OpenaiApi, false);@@ -419,3 +465,127 @@ async fn search_latency_with_500_memories() {assert!(keywords < Duration::from_millis(200) && none < Duration::from_millis(200), "{keywords:?} {none:?}");assert!(hybrid < Duration::from_millis(500), "{hybrid:?}");}++/// N1: with a local model, unrelated notes score about 0.35. A search with no real match says+/// "No matching notes." instead of returning `limit` unrelated notes, and a paraphrase is still found.+#[tokio::test]+async fn unrelated_notes_stay_out_when_the_model_scores_them_at_0_35() {+ let (app, state, _tmp) = setup().await;+ let k = first_kwant(&state).await;+ let money_back = state.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"] {+ state.db.add_memory(&k.id, text, "agent").await.unwrap();+ }+ for i in 0..10 {+ state.db.add_memory(&k.id, &format!("Weekly team lunch {i} is on Thursday at noon"), "agent").await.unwrap();+ }+ let (url, fake) = fake_server(&["nomic-embed-text:latest"]).await;+ fake.shared_axis.store(true, Ordering::SeqCst);+ use_ollama(&state, &url).await;+ assert_eq!(memory_recall::fill_now(&state, &k.id, memory_recall::FILL_ROUNDS).await, 14);++ // The fake is as loose as nomic-embed-text: every note is 0.35 from "car"+ let q = shared_axis_embedding("car");+ for row in state.db.memory_vector_rows(&k.id).await.unwrap() {+ let c = memory_recall::cosine(&q, &shared_axis_embedding(&row.text));+ assert!((c - UNRELATED_COSINE).abs() < 1e-3, "{c} for {:?}", row.text);+ }+ assert_eq!(memory_recall::search(&state, &k.id, "car", 10).await.unwrap(), vec![], "no note is about cars");+ assert_eq!(memory_search(&app, &state, &k, "car").await, "No matching notes.");++ // A paraphrase is still found, alone+ let hits = memory_recall::search(&state, &k.id, "customer refund rules", 10).await.unwrap();+ assert_eq!(hits.iter().map(|m| m.id.as_str()).collect::<Vec<_>>(), [money_back.as_str()]);+ // Keywords still find what they find+ let hits = memory_recall::search(&state, &k.id, "lunch", 10).await.unwrap();+ assert_eq!(hits.len(), 10, "keyword hits are not cut by the floor");+}++/// N2: a note written while a fill runs gets its vector when that fill ends, with no search.+#[tokio::test]+async fn a_note_written_during_a_fill_gets_its_vector_without_a_search() {+ 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;+ fake.batch_delay_ms.store(400, Ordering::SeqCst);++ let running = {+ let (state, k) = (state.clone(), k.id.clone());+ tokio::spawn(async move { memory_recall::fill_now(&state, &k, memory_recall::FILL_ROUNDS).await })+ };+ let mut waited = 0;+ while fake.embed_calls.load(Ordering::SeqCst) == 0 && waited < 100 {+ tokio::time::sleep(Duration::from_millis(10)).await;+ waited += 1;+ }+ assert_eq!(fake.embed_calls.load(Ordering::SeqCst), 1, "the fill's first batch is in flight");+ // The bot writes a note; the listener's fill finds the running one and leaves it to that+ let late = state.db.add_memory(&k.id, "The car is a blue estate", "agent").await.unwrap().id;+ assert_eq!(memory_recall::fill_now(&state, &k.id, memory_recall::FILL_ROUNDS).await, 0);++ assert_eq!(running.await.unwrap(), 6, "5 notes, then one more pass for the late one");+ let row = state.db.memory_vector_rows(&k.id).await.unwrap().into_iter().find(|r| r.id == late).unwrap();+ assert!(row.fresh_vector("ollama/nomic-embed-text", &memory_recall::text_hash(&row.text)).is_some());+ assert_eq!(fake.embed_calls.load(Ordering::SeqCst), 2, "no query embedding: no search ran");+ assert_eq!(memory_recall::fill_now(&state, &k.id, memory_recall::FILL_ROUNDS).await, 0, "nothing left");+}++/// N4: a fill that is cancelled (or panics) frees the kwant, so the next fill runs.+#[tokio::test]+async fn a_cancelled_fill_does_not_block_the_next_one() {+ 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;+ fake.batch_delay_ms.store(2000, Ordering::SeqCst);+ let cut = tokio::time::timeout(Duration::from_millis(200), memory_recall::fill_now(&state, &k.id, 4)).await;+ assert!(cut.is_err(), "the fill was dropped mid-batch");+ fake.batch_delay_ms.store(0, Ordering::SeqCst);+ assert_eq!(memory_recall::fill_now(&state, &k.id, 4).await, 5, "the kwant isn't stuck as filling");+}++/// N3 and N5: the host's OpenAI key is used only while its engine check passes, and never in a+/// space whose This machine is off for Codex.+#[tokio::test]+async fn a_rejected_host_key_is_not_tried_and_this_machine_off_is_one_rule() {+ let (_app, state, _tmp) = setup().await;+ let k = first_kwant(&state).await;+ seed(&state, &k).await;+ let (url, fake) = fake_server(&[]).await;+ state.db.set_setting("openai_api_key", "sk-revoked").await.unwrap();+ assert_eq!(memory_recall::source_for_kwant(&state, &k.id).await, None, "not before a check");+ assert_eq!(check_openai(&state, &url, "sk-revoked").await, EngineStatus::SignedOut);+ assert_eq!(memory_recall::source_for_kwant(&state, &k.id).await, None, "a rejected key is not a provider");+ for _ in 0..3 {+ assert_eq!(memory_recall::search(&state, &k.id, "car", 10).await.unwrap(), state.db.search_memories(&k.id, "car", 10).await.unwrap());+ }+ tokio::time::sleep(Duration::from_millis(100)).await;+ assert_eq!(fake.calls.load(Ordering::SeqCst), 1, "only the engine check itself, no embedding call");++ // The key is fixed and checked again: it is the provider again+ state.db.set_setting("openai_api_key", "sk-test").await.unwrap();+ assert_eq!(check_openai(&state, &url, "sk-test").await, EngineStatus::Ready);+ let host = Some(EmbedSource::OpenAi { base: "https://api.openai.com".into(), key: "sk-test".into() });+ assert_eq!(memory_recall::source_for_kwant(&state, &k.id).await, host);++ // This machine off for Codex in the space: the same rule turns use (profile_turn::host_off)+ let space = SpaceId::default_space();+ let this_machine = state+ .db+ .list_profiles(&space)+ .await+ .unwrap()+ .into_iter()+ .find(|p| p.kind == "system" && p.engine == "codex")+ .expect("the space's This machine profile for Codex");+ let off = LlmProfilePatch { enabled: Some(false), ..Default::default() };+ state.db.update_profile(&this_machine.id, &off).await.unwrap();+ assert!(kwnt::server::profile_turn::host_off(&state, &space).await.contains(&kwnt::profiles::Engine::Codex));+ assert_eq!(memory_recall::source_for_kwant(&state, &k.id).await, None);+ let on = LlmProfilePatch { enabled: Some(true), ..Default::default() };+ state.db.update_profile(&this_machine.id, &on).await.unwrap();+ assert_eq!(memory_recall::source_for_kwant(&state, &k.id).await, host);+}diff --git a/tests/transcribe_test.rs b/tests/transcribe_test.rsindex 51519f59..9c3fd6a2 100644--- a/tests/transcribe_test.rs+++ b/tests/transcribe_test.rs@@ -38,8 +38,13 @@ type Call = (String, String, Option<String>, String, usize);static CALLS: Mutex<Vec<Call>> = Mutex::new(Vec::new());+/// The stub's log. Tests run in parallel, so a panic in one must not poison it for the rest.+fn calls() -> std::sync::MutexGuard<'static, Vec<Call>> {+ CALLS.lock().unwrap_or_else(|e| e.into_inner())+}+fn calls_with(key: &str) -> Vec<Call> {- CALLS.lock().unwrap().iter().filter(|c| c.0 == key).cloned().collect()+ calls().iter().filter(|c| c.0 == key).cloned().collect()}/// The value of a multipart text field, or the file part's name and size.@@ -65,7 +70,7 @@ async fn stub(headers: HeaderMap, body: Bytes) -> Response {let model = field(&body, "model").unwrap();assert_eq!(field(&body, "response_format").as_deref(), Some("json"));let (file, size) = file_part(&body);- CALLS.lock().unwrap().push((key.clone(), model.clone(), field(&body, "language"), file, size));+ calls().push((key.clone(), model.clone(), field(&body, "language"), file, size));match (key.as_str(), model.as_str()) {("sk-bad", _) => (StatusCode::UNAUTHORIZED,@@ -182,11 +187,12 @@ async fn with_no_key_it_is_unavailable_and_says_why() {assert_eq!(code, StatusCode::OK);assert_eq!(v, json!({"available": false, "source": null, "why": transcribe::WHY_NO_KEY}));- let before = CALLS.lock().unwrap().len();- let (code, v) = call(&app, audio_post(DEF, "", "audio/webm", vec![1; 1000])).await;+ // Other tests call the shared stub at the same time, so a total count races. This+ // recording's size (1001 bytes) is used by no other test: no stub call may carry it.+ let (code, v) = call(&app, audio_post(DEF, "", "audio/webm", vec![1; 1001])).await;assert_eq!(code, StatusCode::CONFLICT);assert_eq!(v, json!({"error": transcribe::WHY_NO_KEY, "code": "no_transcriber", "why": transcribe::WHY_NO_KEY}));- assert_eq!(CALLS.lock().unwrap().len(), before, "no upstream call without a key");+ assert!(calls().iter().all(|c| c.4 != 1001), "no upstream call without a key");let (code, _) = status(&app, "spc_missing").await;assert_eq!(code, StatusCode::NOT_FOUND);