The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
fix(memory): learn returns on accept; time every engine call
M3gA-Mindedbd1bb5cde7
diff --git a/crates/openhuman-core/src/memory/guard.rs b/crates/openhuman-core/src/memory/guard.rsindex 935332b805..5c6f8eeafe 100644--- a/crates/openhuman-core/src/memory/guard.rs+++ b/crates/openhuman-core/src/memory/guard.rs@@ -7,27 +7,66 @@//! write through TinyMemory's own types (`AgentMemory::pre_turn` ///! `post_turn`, `Brain::ingest`, background ingests) as well as the host's.//! Reads pass through untouched.+//!+//! The same wrapper times every engine call: one `[memory:timing]` debug+//! line with the op, engine, `elapsed_ms`, outcome (`ok` or the error code)+//! and a result count, never user content (tinyhumansai/backend#1405).+use std::future::Future;use std::sync::Arc;+use std::time::Instant;use async_trait::async_trait;use tinymemory_api::{BeliefsRequest, ConsolidateReceipt, ConsolidateRequest, EngineDescriptor, EngineHealth,ExplorePage, ExploreRequest, FetchPage, FetchRequest, ForgetReport, ForgetTarget, GetRequest,Hit, ListPage, ListRequest, MemoryEngine, RecallAnswer, RecallRequest, Result, StoreItem,- StoreReceipt, WriteOptions,+ StoreReceipt, WaitFor, WriteOptions,};-/// `inner` with every stored item scrubbed first.+use super::error::MemoryError;++/// `inner` with every stored item scrubbed first, and every call timed.pub struct ScrubbingEngine {inner: Arc<dyn MemoryEngine>,+ id: String,}impl ScrubbingEngine {/// Guards `inner`.#[must_use]pub fn wrap(inner: Arc<dyn MemoryEngine>) -> Arc<dyn MemoryEngine> {- Arc::new(Self { inner })+ let id = inner.descriptor().id.to_string();+ Arc::new(Self { inner, id })+ }++ /// Runs `call` and logs its timing; `count` sizes a success.+ async fn timed<T>(+ &self,+ op: &'static str,+ call: impl Future<Output = Result<T>>,+ count: impl FnOnce(&T) -> usize,+ ) -> Result<T> {+ let started = Instant::now();+ let result = call.await;+ let elapsed_ms = started.elapsed().as_millis() as u64;+ tracing::debug!(+ op,+ engine = %self.id,+ elapsed_ms,+ outcome = outcome(&result),+ count = result.as_ref().map_or(0, count),+ "[memory:timing]"+ );+ result+ }+}++/// `ok`, or the stable code of the error a call failed with.+fn outcome<T>(result: &Result<T>) -> &'static str {+ match result {+ Ok(_) => "ok",+ Err(error) => MemoryError::from(error.clone()).code(),}}@@ -55,53 +94,88 @@ impl MemoryEngine for ScrubbingEngine {}async fn health(&self) -> EngineHealth {- self.inner.health().await+ let started = Instant::now();+ let health = self.inner.health().await;+ let outcome = match &health {+ EngineHealth::Ok => "ok",+ EngineHealth::Degraded(_) => "degraded",+ EngineHealth::Down(_) => "down",+ };+ tracing::debug!(+ op = "health",+ engine = %self.id,+ elapsed_ms = started.elapsed().as_millis() as u64,+ outcome,+ "[memory:timing]"+ );+ health}async fn recall(&self, req: RecallRequest) -> Result<RecallAnswer> {- self.inner.recall(req).await+ self.timed("recall", self.inner.recall(req), |answer| {+ answer.citations.len()+ })+ .await}async fn fetch(&self, req: FetchRequest) -> Result<FetchPage> {- self.inner.fetch(req).await+ self.timed("fetch", self.inner.fetch(req), |page| page.hits.len())+ .await}async fn store(&self, item: StoreItem) -> Result<StoreReceipt> {- self.inner.store(scrub(item)).await+ self.timed("store", self.inner.store(scrub(item)), |_| 1)+ .await}async fn store_with(&self, item: StoreItem, options: WriteOptions) -> Result<StoreReceipt> {- self.inner.store_with(scrub(item), options).await+ let op = match options.wait {+ WaitFor::Accepted => "store_accepted",+ WaitFor::Visible => "store",+ };+ self.timed(op, self.inner.store_with(scrub(item), options), |_| 1)+ .await}async fn store_many(&self, items: Vec<StoreItem>) -> Result<Vec<StoreReceipt>> {- self.inner- .store_many(items.into_iter().map(scrub).collect())+ let items = items.into_iter().map(scrub).collect();+ self.timed("store_many", self.inner.store_many(items), Vec::len).await}async fn forget(&self, target: ForgetTarget) -> Result<ForgetReport> {- self.inner.forget(target).await+ self.timed("forget", self.inner.forget(target), |report| {+ report.forgotten+ })+ .await}async fn list(&self, req: ListRequest) -> Result<ListPage> {- self.inner.list(req).await+ self.timed("list", self.inner.list(req), |page| page.items.len())+ .await}async fn explore(&self, req: ExploreRequest) -> Result<ExplorePage> {- self.inner.explore(req).await+ self.timed("explore", self.inner.explore(req), |page| {+ page.buckets.len()+ })+ .await}async fn get(&self, req: GetRequest) -> Result<Vec<Hit>> {- self.inner.get(req).await+ self.timed("get", self.inner.get(req), Vec::len).await}async fn consolidate(&self, req: ConsolidateRequest) -> Result<ConsolidateReceipt> {- self.inner.consolidate(req).await+ self.timed("consolidate", self.inner.consolidate(req), |receipt| {+ receipt.jobs.len()+ })+ .await}async fn beliefs(&self, req: BeliefsRequest) -> Result<Vec<Hit>> {- self.inner.beliefs(req).await+ self.timed("beliefs", self.inner.beliefs(req), Vec::len)+ .await}}diff --git a/crates/openhuman-core/src/memory/guard_tests.rs b/crates/openhuman-core/src/memory/guard_tests.rsindex 331b41cac3..53d3c3b93b 100644--- a/crates/openhuman-core/src/memory/guard_tests.rs+++ b/crates/openhuman-core/src/memory/guard_tests.rs@@ -45,3 +45,10 @@ async fn every_write_path_is_scrubbed() {);assert_eq!(guarded.descriptor().id, reference.descriptor().id);}++#[test]+fn a_timed_call_reports_ok_or_the_error_code() {+ assert_eq!(outcome(&Ok::<(), _>(())), "ok");+ let refused: Result<()> = Err(tinymemory_api::Error::Unauthorized("bad key".into()));+ assert_eq!(outcome(&refused), "UNAUTHORIZED");+}diff --git a/crates/openhuman-core/src/memory/lifecycle/hooks.rs b/crates/openhuman-core/src/memory/lifecycle/hooks.rsindex 0544970515..c19c5d5d53 100644--- a/crates/openhuman-core/src/memory/lifecycle/hooks.rs+++ b/crates/openhuman-core/src/memory/lifecycle/hooks.rs@@ -412,6 +412,7 @@ pub async fn post_turn(config: &Config, identity: &ResolvedIdentity, input: Postid: call.id.clone(),}).collect();+ let started = std::time::Instant::now();match memory.post_turn(post).await {Ok(report) => {tracing::debug!(@@ -419,6 +420,7 @@ pub async fn post_turn(config: &Config, identity: &ResolvedIdentity, input: Postagent_id = %identity.agent_id,turn = input.turn_index,jobs = report.jobs.len(),+ elapsed_ms = started.elapsed().as_millis() as u64,"[memory:hooks] reply logged");jobs::enqueue(config, identity.root(), report.jobs).await;@@ -427,6 +429,7 @@ pub async fn post_turn(config: &Config, identity: &ResolvedIdentity, input: Posttracing::warn!(thread_id = %input.thread_id,%error,+ elapsed_ms = started.elapsed().as_millis() as u64,"[memory:hooks] reply not logged");}diff --git a/crates/openhuman-core/src/memory/ops.rs b/crates/openhuman-core/src/memory/ops.rsindex dc0fa88649..f72578b52d 100644--- a/crates/openhuman-core/src/memory/ops.rs+++ b/crates/openhuman-core/src/memory/ops.rs@@ -9,7 +9,7 @@use chrono::Utc;use tinymemory_api::{FetchRequest, ForgetTarget, ItemId, LearningKind, ListRequest, MemoryMeta, RecallRequest,- StoreItem, StoreReceipt,+ StoreItem, StoreReceipt, WriteOptions,};use crate::config::Config;@@ -259,14 +259,27 @@ fn merge_meta(meta: &mut MemoryMeta, host: MemoryMeta) {}}-/// `memory_learn`.+/// `memory_learn`: returns once the learning is readable.pub async fn learn(config: &Config,params: LearnParams,host_meta: Option<MemoryMeta>,+) -> MemoryResult<LearnView> {+ learn_with(config, params, host_meta, WriteOptions::visible()).await+}++/// [`learn`], returning as soon as `options` allows. The agent's `memory`+/// tool passes [`WriteOptions::accepted`] so a turn never waits on the+/// engine indexing the learning.+pub async fn learn_with(+ config: &Config,+ params: LearnParams,+ host_meta: Option<MemoryMeta>,+ options: WriteOptions,) -> MemoryResult<LearnView> {let item = learning_item(params, host_meta)?;- let receipt = store_item(config, item).await?;+ let bound = bound(config)?;+ let receipt = store_on_with(&bound, item, options).await?;Ok(LearnView { id: receipt.id.0 })}@@ -278,11 +291,21 @@ pub async fn store_item(config: &Config, item: StoreItem) -> MemoryResult<StoreR/// Stores `item` on `bound`; the bound engine scrubs it ([`super::guard`]).pub async fn store_on(bound: &BoundEngine, item: StoreItem) -> MemoryResult<StoreReceipt> {+ store_on_with(bound, item, WriteOptions::visible()).await+}++/// [`store_on`], returning as soon as `options` allows.+pub async fn store_on_with(+ bound: &BoundEngine,+ item: StoreItem,+ options: WriteOptions,+) -> MemoryResult<StoreReceipt> {let kind = item.kind();- let receipt = bound.engine.store(item).await?;+ let receipt = bound.engine.store_with(item, options).await?;tracing::debug!(engine = %bound.id,kind = kind.as_str(),+ wait = ?options.wait,replayed = receipt.replayed,"[memory:ops] item stored");diff --git a/crates/openhuman-core/src/memory/tools.rs b/crates/openhuman-core/src/memory/tools.rsindex 4336ee72ec..2c87d67d1b 100644--- a/crates/openhuman-core/src/memory/tools.rs+++ b/crates/openhuman-core/src/memory/tools.rs@@ -186,6 +186,10 @@ impl CallFacts {}}+/// What a `learn` result tells the model: the write was accepted, and+/// recall may not find it for a moment.+pub const LEARN_STATUS: &str = "saved; searchable in recall shortly";+fn arg_str(args: &Value, key: &str) -> Option<String> {args.get(key).and_then(Value::as_str)@@ -238,17 +242,24 @@ pub async fn run_action(config: &Config, args: &Value, facts: &CallFacts) -> TooOk(mut params) => {params.meta = None;let kind = params.kind.unwrap_or(tinymemory_api::LearningKind::Fact);- ops::learn(config, params, Some(facts.learn_meta()))- .await- .map(|view| {- BUS.publish(DomainEvent::MemoryStored {- key: view.id.clone(),- category: kind.as_str().to_string(),- namespace: "learnings".to_string(),- });- json!(view)- })- .map_err(render_error)+ // Accepted, not visible: indexing can take minutes on a+ // hosted engine and the turn must not wait for it.+ ops::learn_with(+ config,+ params,+ Some(facts.learn_meta()),+ tinymemory_api::WriteOptions::accepted(),+ )+ .await+ .map(|view| {+ BUS.publish(DomainEvent::MemoryStored {+ key: view.id.clone(),+ category: kind.as_str().to_string(),+ namespace: "learnings".to_string(),+ });+ json!({"id": view.id, "status": LEARN_STATUS})+ })+ .map_err(render_error)}Err(error) => Err(error),},diff --git a/crates/openhuman-core/src/memory/tools_tests.rs b/crates/openhuman-core/src/memory/tools_tests.rsindex f560f9f340..5c494ef8a1 100644--- a/crates/openhuman-core/src/memory/tools_tests.rs+++ b/crates/openhuman-core/src/memory/tools_tests.rs@@ -426,3 +426,131 @@ async fn learnings_are_shared_under_a_root_and_a_team_root_is_kept_apart() {.iter().all(|hit| hit.meta.namespace != Namespace::agent("nobody")));}++/// The reference engine, recording how far each single store waited.+struct WaitRecorder {+ inner: tinymemory_api::conformance::ReferenceEngine,+ waits: std::sync::Mutex<Vec<tinymemory_api::WaitFor>>,+}++#[async_trait]+impl tinymemory_api::MemoryEngine for WaitRecorder {+ fn descriptor(&self) -> &tinymemory_api::EngineDescriptor {+ self.inner.descriptor()+ }+ async fn health(&self) -> tinymemory_api::EngineHealth {+ self.inner.health().await+ }+ async fn recall(+ &self,+ req: tinymemory_api::RecallRequest,+ ) -> tinymemory_api::Result<tinymemory_api::RecallAnswer> {+ self.inner.recall(req).await+ }+ async fn fetch(+ &self,+ req: tinymemory_api::FetchRequest,+ ) -> tinymemory_api::Result<tinymemory_api::FetchPage> {+ self.inner.fetch(req).await+ }+ async fn store(+ &self,+ item: tinymemory_api::StoreItem,+ ) -> tinymemory_api::Result<tinymemory_api::StoreReceipt> {+ self.store_with(item, tinymemory_api::WriteOptions::visible())+ .await+ }+ async fn store_with(+ &self,+ item: tinymemory_api::StoreItem,+ options: tinymemory_api::WriteOptions,+ ) -> tinymemory_api::Result<tinymemory_api::StoreReceipt> {+ self.waits.lock().unwrap().push(options.wait);+ self.inner.store(item).await+ }+ async fn forget(+ &self,+ target: tinymemory_api::ForgetTarget,+ ) -> tinymemory_api::Result<tinymemory_api::ForgetReport> {+ self.inner.forget(target).await+ }+ async fn list(+ &self,+ req: tinymemory_api::ListRequest,+ ) -> tinymemory_api::Result<tinymemory_api::ListPage> {+ self.inner.list(req).await+ }+ async fn consolidate(+ &self,+ req: tinymemory_api::ConsolidateRequest,+ ) -> tinymemory_api::Result<tinymemory_api::ConsolidateReceipt> {+ self.inner.consolidate(req).await+ }+}++#[tokio::test]+async fn learn_returns_on_accept_and_says_recall_may_lag() {+ let tmp = tempfile::tempdir().unwrap();+ let config = config_in(&tmp);+ let engine = Arc::new(WaitRecorder {+ inner: tinymemory_api::conformance::ReferenceEngine::new(),+ waits: std::sync::Mutex::new(Vec::new()),+ });+ crate::memory::engine::install_test_engine(&config.workspace_dir, engine.clone());++ let learned = run_action(+ &config,+ &json!({"action": "learn", "text": "The user drinks oolong"}),+ &facts(),+ )+ .await;++ assert!(!learned.is_error, "{}", text(&learned));+ // A turn must never wait on the engine indexing a learning.+ assert_eq!(+ *engine.waits.lock().unwrap(),+ vec![tinymemory_api::WaitFor::Accepted]+ );+ let view = serde_json::from_str::<Value>(&text(&learned)).unwrap();+ assert!(!view["id"].as_str().unwrap().is_empty(), "{view}");+ assert_eq!(view["status"], LEARN_STATUS);++ // The RPC path still reads its own write.+ crate::memory::ops::learn(+ &config,+ LearnParams {+ text: "The user drinks puerh".into(),+ kind: None,+ confidence: None,+ meta: None,+ },+ None,+ )+ .await+ .unwrap();+ assert_eq!(+ engine.waits.lock().unwrap().last(),+ Some(&tinymemory_api::WaitFor::Visible)+ );+}++#[tokio::test]+async fn a_failed_learn_is_reported_to_the_model() {+ let tmp = tempfile::tempdir().unwrap();+ let config = config_in(&tmp);+ crate::memory::test_fixtures::RefusingEngine::out_of_credits().bind(&config);++ let learned = run_action(+ &config,+ &json!({"action": "learn", "text": "The user drinks oolong"}),+ &facts(),+ )+ .await;++ assert!(learned.is_error, "{}", text(&learned));+ assert!(+ text(&learned).contains("INSUFFICIENT_CREDITS"),+ "{}",+ text(&learned)+ );+}