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): keep connection root records safe across failures and syncs
M3gA-Mind4c5359800fab
diff --git a/crates/openhuman-core/src/memory/sources/composio.rs b/crates/openhuman-core/src/memory/sources/composio.rsindex 02afe65440..b6deec8d9b 100644--- a/crates/openhuman-core/src/memory/sources/composio.rs+++ b/crates/openhuman-core/src/memory/sources/composio.rs@@ -89,7 +89,12 @@ pub async fn store_records(&config.workspace_dir,connection_id,&layout.root().to_string(),- );+ )+ .map_err(|error| {+ MemoryError::Engine(format!(+ "recording the connection's memory root failed: {error}"+ ))+ })?;}super::sync::store_all(config,@@ -184,8 +189,9 @@ pub async fn forget_connection(Err(MemoryError::Off(_)) => return Ok(0),Err(error) => return Err(error),};+ let recorded = super::roots::of(&config.workspace_dir, connection_id);let reaches = match toolkit {- Some(toolkit) => toolkit_reaches(config, connection_id, toolkit)?,+ Some(toolkit) => toolkit_reaches(config, toolkit, &recorded)?,None => {tracing::warn!(connection_id = %connection_id,@@ -228,23 +234,23 @@ pub async fn forget_connection(.await?.forgotten;}- super::roots::drop_connection(&config.workspace_dir, connection_id);+ super::roots::forget(&config.workspace_dir, connection_id, &recorded);Ok(forgotten)}-/// `source:<toolkit>` under the current root and under every root-/// `connection_id` filed items under.+/// `source:<toolkit>` under the current root and under every `recorded`+/// root.fn toolkit_reaches(config: &Config,- connection_id: &str,toolkit: &str,+ recorded: &std::collections::BTreeSet<String>,) -> MemoryResult<Vec<tinymemory_api::Reach>> {let source = crate::memory::brain::brain_source(crate::config::schema::MemorySourceKind::Composio,toolkit,);let current = super::layout_of(config, &source_id_for_toolkit(config, toolkit));- let mut roots = super::roots::of(&config.workspace_dir, connection_id);+ let mut roots = recorded.clone();roots.insert(current.root().to_string());let mut reaches = Vec::with_capacity(roots.len());for root in roots {diff --git a/crates/openhuman-core/src/memory/sources/roots.rs b/crates/openhuman-core/src/memory/sources/roots.rsindex 83c3f9bf81..1397e27116 100644--- a/crates/openhuman-core/src/memory/sources/roots.rs+++ b/crates/openhuman-core/src/memory/sources/roots.rs@@ -11,64 +11,103 @@ use std::collections::{BTreeMap, BTreeSet};use std::path::{Path, PathBuf};use std::sync::{LazyLock, Mutex};-/// Serialises read-modify-writes of the file in this process.+/// Serialises every read and read-modify-write of the file in this process.static LOCK: LazyLock<Mutex<()>> = LazyLock::new(|| Mutex::new(()));+type Roots = BTreeMap<String, BTreeSet<String>>;+fn path(workspace_dir: &Path) -> PathBuf {workspace_dir.join("memory").join("connection_roots.json")}-fn read(workspace_dir: &Path) -> BTreeMap<String, BTreeSet<String>> {- std::fs::read_to_string(path(workspace_dir))- .ok()- .and_then(|text| serde_json::from_str(&text).ok())- .unwrap_or_default()+/// The file's contents. A file that exists but cannot be read is set aside+/// (`.corrupt`) with a warning rather than overwritten.+fn load(workspace_dir: &Path) -> Roots {+ let file = path(workspace_dir);+ let text = match std::fs::read_to_string(&file) {+ Ok(text) => text,+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Roots::new(),+ Err(error) => {+ tracing::warn!(error = %error, "[memory:sources] connection roots unreadable");+ return set_aside(&file);+ }+ };+ serde_json::from_str(&text).unwrap_or_else(|error| {+ tracing::warn!(error = %error, "[memory:sources] connection roots unparsable");+ set_aside(&file)+ })+}++fn set_aside(file: &Path) -> Roots {+ if let Err(error) = std::fs::rename(file, file.with_extension("json.corrupt")) {+ tracing::warn!(error = %error, "[memory:sources] could not set the roots file aside");+ }+ Roots::new()}-fn write(workspace_dir: &Path, all: &BTreeMap<String, BTreeSet<String>>) {+/// Writes through a temporary file and a rename, so a stop mid-write never+/// leaves a partial file.+fn save(workspace_dir: &Path, all: &Roots) -> std::io::Result<()> {let file = path(workspace_dir);- let result = file- .parent()- .map_or(Ok(()), std::fs::create_dir_all)- .and_then(|()| {- let json = serde_json::to_vec_pretty(all).map_err(std::io::Error::other)?;- std::fs::write(&file, json)- });- if let Err(error) = result {- tracing::warn!(error = %error, "[memory:sources] writing connection roots failed");+ let temp = file.with_extension("json.tmp");+ if let Some(parent) = file.parent() {+ std::fs::create_dir_all(parent)?;}+ let json = serde_json::to_vec_pretty(all).map_err(std::io::Error::other)?;+ std::fs::write(&temp, json)?;+ std::fs::rename(&temp, &file)+}++fn locked() -> std::sync::MutexGuard<'static, ()> {+ LOCK.lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)}-/// Records that `connection_id` filed items under `root`.-pub fn record(workspace_dir: &Path, connection_id: &str, root: &str) {- let _guard = LOCK- .lock()- .unwrap_or_else(std::sync::PoisonError::into_inner);- let mut all = read(workspace_dir);+/// Records that `connection_id` files items under `root`.+///+/// # Errors+///+/// The record could not be written: the caller must not file items under+/// a root a later forget would not know.+pub fn record(workspace_dir: &Path, connection_id: &str, root: &str) -> std::io::Result<()> {+ let _guard = locked();+ let mut all = load(workspace_dir);if all.entry(connection_id.to_string()).or_default().insert(root.to_string()){- write(workspace_dir, &all);+ save(workspace_dir, &all)?;}+ Ok(())}/// Every root `connection_id` filed items under.#[must_use]pub fn of(workspace_dir: &Path, connection_id: &str) -> BTreeSet<String> {- read(workspace_dir)+ let _guard = locked();+ load(workspace_dir).remove(connection_id).unwrap_or_default()}-/// Forgets `connection_id`'s roots, once its items are gone.-pub fn drop_connection(workspace_dir: &Path, connection_id: &str) {- let _guard = LOCK- .lock()- .unwrap_or_else(std::sync::PoisonError::into_inner);- let mut all = read(workspace_dir);- if all.remove(connection_id).is_some() {- write(workspace_dir, &all);+/// Forgets `roots` of `connection_id`, once its items under them are gone.+/// A root recorded meanwhile (a sync during the forget) is kept.+pub fn forget(workspace_dir: &Path, connection_id: &str, roots: &BTreeSet<String>) {+ let _guard = locked();+ let mut all = load(workspace_dir);+ let Some(held) = all.get_mut(connection_id) else {+ return;+ };+ held.retain(|root| !roots.contains(root));+ if held.is_empty() {+ all.remove(connection_id);+ }+ if let Err(error) = save(workspace_dir, &all) {+ tracing::warn!(error = %error, "[memory:sources] writing connection roots failed");}}++#[cfg(test)]+#[path = "roots_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/memory/sources/roots_tests.rs b/crates/openhuman-core/src/memory/sources/roots_tests.rsnew file mode 100644index 0000000000..063d4ee88a--- /dev/null+++ b/crates/openhuman-core/src/memory/sources/roots_tests.rs@@ -0,0 +1,39 @@+use super::*;++#[test]+fn forgetting_keeps_a_root_recorded_meanwhile() {+ let tmp = tempfile::tempdir().unwrap();+ let dir = tmp.path();+ record(dir, "c", "root").unwrap();+ let seen = of(dir, "c");+ // A sync records another root while the forget runs.+ record(dir, "c", "team:new").unwrap();+ forget(dir, "c", &seen);+ assert_eq!(of(dir, "c"), BTreeSet::from(["team:new".to_string()]));+ forget(dir, "c", &of(dir, "c"));+ assert!(of(dir, "c").is_empty());+}++#[test]+fn an_unparsable_file_is_set_aside_not_overwritten() {+ let tmp = tempfile::tempdir().unwrap();+ let dir = tmp.path();+ let file = path(dir);+ std::fs::create_dir_all(file.parent().unwrap()).unwrap();+ std::fs::write(&file, "{ not json").unwrap();+ assert!(of(dir, "c").is_empty());+ assert_eq!(+ std::fs::read_to_string(file.with_extension("json.corrupt")).unwrap(),+ "{ not json"+ );+ record(dir, "c", "root").unwrap();+ assert_eq!(of(dir, "c").len(), 1, "recording resumed");+}++#[test]+fn a_record_that_cannot_be_written_is_an_error() {+ let tmp = tempfile::tempdir().unwrap();+ // `memory` is a file, so the record's directory cannot be made.+ std::fs::write(tmp.path().join("memory"), "").unwrap();+ assert!(record(tmp.path(), "c", "root").is_err());+}diff --git a/tests/memory_v2_e2e.rs b/tests/memory_v2_e2e.rsindex 61273f83b8..4d2a960ecf 100644--- a/tests/memory_v2_e2e.rs+++ b/tests/memory_v2_e2e.rs@@ -272,7 +272,13 @@ impl Fixture {if done(&result) || std::time::Instant::now() >= deadline {return result;}- tokio::time::sleep(std::time::Duration::from_millis(100)).await;+ // Never start a call the deadline leaves no time for: the sleep+ // may cross it, and the last result is then the answer.+ let pause = std::time::Duration::from_millis(100);+ if std::time::Instant::now() + pause >= deadline {+ return result;+ }+ tokio::time::sleep(pause).await;}}