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
feat(memory): replace a connector record's previous version on re-sync
M3gA-Mind544c4fc6bcf8
diff --git a/crates/openhuman-core/src/integrations/composio/ops/sync.rs b/crates/openhuman-core/src/integrations/composio/ops/sync.rsindex 4eabfb905e..180004fae2 100644--- a/crates/openhuman-core/src/integrations/composio/ops/sync.rs+++ b/crates/openhuman-core/src/integrations/composio/ops/sync.rs@@ -236,21 +236,19 @@ pub async fn run_sync_pass(let more_pending = failure.is_none() && !response.batch.complete;let records_read = response.batch.records.len();- let written = if records_read == 0 {- 0- } else {- store_records(- config,- bound,- toolkit,- connection_id,- source_id,- &crate::memory::sources::layout_of(config, source_id),- &response.batch.records,- )- .await- .map_err(|error| format!("storing {toolkit} records failed: {}", String::from(error)))?- };+ // Called with no records too: memory retries forgetting the previous+ // versions an earlier pass could not.+ let written = store_records(+ config,+ bound,+ toolkit,+ connection_id,+ source_id,+ &crate::memory::sources::layout_of(config, source_id),+ &response.batch.records,+ )+ .await+ .map_err(|error| format!("storing {toolkit} records failed: {}", String::from(error)))?;if more_pending {// The module's note says why (today's request budget, typically).diff --git a/crates/openhuman-core/src/memory/sources/composio.rs b/crates/openhuman-core/src/memory/sources/composio.rsindex 4544d7d80c..7d4639eb4a 100644--- a/crates/openhuman-core/src/memory/sources/composio.rs+++ b/crates/openhuman-core/src/memory/sources/composio.rs@@ -68,7 +68,9 @@ pub fn record_item(}/// Files every non-empty record into `layout`'s brain, under the toolkit's-/// brain source. Returns how many were stored.+/// brain source, and forgets the previous version of each record that+/// changed or came back empty upstream ([`super::versions`]). Returns how+/// many were stored.pub async fn store_records(config: &Config,bound: &BoundEngine,@@ -78,10 +80,19 @@ pub async fn store_records(layout: &tinymemory_tools::MemoryLayout,records: &[ConnectorRecord],) -> MemoryResult<u64> {- let items: Vec<StoreItem> = records- .iter()- .filter_map(|record| record_item(toolkit, connection_id, source_id, record))- .collect();+ let mut keys = Vec::with_capacity(records.len());+ let mut items = Vec::with_capacity(records.len());+ let mut emptied = Vec::new();+ for record in records {+ let key = super::versions::key(connection_id, &record.item_id);+ match record_item(toolkit, connection_id, source_id, record) {+ Some(item) => {+ keys.push(key);+ items.push(item);+ }+ None => emptied.push(key),+ }+ }if !items.is_empty() {// Before the write, so an item stored is never under an unrecorded// root.@@ -96,7 +107,7 @@ pub async fn store_records())})?;}- super::sync::store_all(+ let ids = super::sync::store_all_ids(config,bound,items,@@ -107,7 +118,50 @@ pub async fn store_records(),layout,)- .await+ .await?;+ let stored: Vec<(String, String)> = keys+ .into_iter()+ .zip(ids)+ .filter_map(|(key, id)| Some((key, id?)))+ .collect();+ let stale = super::versions::begin(&config.workspace_dir, &stored, &emptied);+ forget_stale(config, bound, toolkit, stale).await;+ Ok(stored.len() as u64)+}++/// Forgets the previous versions [`super::versions::begin`] handed back and+/// settles them. A failed forget leaves them pending, so the next sync+/// retries; it never fails the sync.+async fn forget_stale(config: &Config, bound: &BoundEngine, toolkit: &str, stale: Vec<String>) {+ if stale.is_empty() {+ return;+ }+ let ids = stale+ .iter()+ .cloned()+ .map(tinymemory_api::ItemId::new)+ .collect();+ match bound+ .engine+ .forget(tinymemory_api::ForgetTarget::Ids(ids))+ .await+ {+ Ok(report) => {+ tracing::debug!(+ toolkit = %toolkit,+ stale = stale.len(),+ forgotten = report.forgotten,+ "[memory:sources] forgot the previous versions of edited records"+ );+ super::versions::settle(&config.workspace_dir, &stale);+ }+ Err(error) => tracing::warn!(+ toolkit = %toolkit,+ stale = stale.len(),+ code = MemoryError::from(error).code(),+ "[memory:sources] forgetting previous versions failed; retrying next sync"+ ),+ }}/// Syncs every active connection of the source's toolkit.@@ -241,6 +295,7 @@ pub async fn forget_connection(if let Some(recorded) = &recorded {super::roots::forget(&config.workspace_dir, connection_id, recorded);}+ super::versions::drop_connection(&config.workspace_dir, connection_id);Ok(forgotten)}diff --git a/crates/openhuman-core/src/memory/sources/composio_tests.rs b/crates/openhuman-core/src/memory/sources/composio_tests.rsindex e1c248d1cd..644edd630b 100644--- a/crates/openhuman-core/src/memory/sources/composio_tests.rs+++ b/crates/openhuman-core/src/memory/sources/composio_tests.rs@@ -279,6 +279,71 @@ async fn forget_connection_reads_every_root_its_items_were_filed_under() {.is_empty());}+#[tokio::test]+async fn an_edited_record_replaces_its_previous_version() {+ let tmp = tempfile::tempdir().unwrap();+ let config = config_in(&tmp);+ let engine = bind_reference(&config);+ let bound = crate::memory::engine::resolve(&config).engine().unwrap();+ let sync = |records: Vec<ConnectorRecord>| {+ let (config, bound) = (&config, &bound);+ async move {+ store_records(+ config,+ bound,+ "notion",+ "conn-a",+ "src",+ &MemoryLayout::default(),+ &records,+ )+ .await+ .unwrap()+ }+ };+ let texts = || async {+ let mut texts: Vec<String> = stored(&engine, MetaFilter::default())+ .await+ .into_iter()+ .map(|hit| hit.text)+ .collect();+ texts.sort();+ texts+ };++ sync(vec![+ record("p1", "Plan", "v1"),+ record("p2", "Notes", "kept"),+ ])+ .await;+ // The same records again: nothing is stale.+ sync(vec![+ record("p1", "Plan", "v1"),+ record("p2", "Notes", "kept"),+ ])+ .await;+ assert_eq!(texts().await, ["# Notes\n\nkept", "# Plan\n\nv1"]);++ // p1 edited upstream: its old version goes, p2 stays.+ assert_eq!(sync(vec![record("p1", "Plan", "v2")]).await, 1);+ assert_eq!(texts().await, ["# Notes\n\nkept", "# Plan\n\nv2"]);++ // p2 comes back empty upstream: its stored version goes.+ sync(vec![record("p2", "Notes", " ")]).await;+ assert_eq!(texts().await, ["# Plan\n\nv2"]);++ // Disconnecting drops the record ids with the items.+ forget_connection(&config, "conn-a", Some("notion"))+ .await+ .unwrap();+ assert!(super::super::versions::begin(+ &config.workspace_dir,+ &[(super::super::versions::key("conn-a", "p1"), "other".into())],+ &[]+ )+ .is_empty());+}+#[tokio::test]async fn forget_connection_with_memory_off_forgets_nothing() {let tmp = tempfile::tempdir().unwrap();diff --git a/crates/openhuman-core/src/memory/sources/mod.rs b/crates/openhuman-core/src/memory/sources/mod.rsindex cf8adb5c94..8168e1d6fb 100644--- a/crates/openhuman-core/src/memory/sources/mod.rs+++ b/crates/openhuman-core/src/memory/sources/mod.rs@@ -12,6 +12,7 @@ pub mod composio;pub mod roots;pub mod state;mod sync;+pub mod versions;use chrono::{DateTime, Utc};use tinymemory_api::{ForgetTarget, MetaFilter};diff --git a/crates/openhuman-core/src/memory/sources/sync.rs b/crates/openhuman-core/src/memory/sources/sync.rsindex 12550c2c41..a1929d1fdf 100644--- a/crates/openhuman-core/src/memory/sources/sync.rs+++ b/crates/openhuman-core/src/memory/sources/sync.rs@@ -109,10 +109,23 @@ pub(crate) async fn store_all(config: &Config,bound: &BoundEngine,items: Vec<tinymemory_api::StoreItem>,- (kind, target, source_id): (crate::config::schema::MemorySourceKind, &str, &str),+ source: (crate::config::schema::MemorySourceKind, &str, &str),layout: &tinymemory_tools::MemoryLayout,) -> MemoryResult<u64> {- let mut stored = 0u64;+ let ids = store_all_ids(config, bound, items, source, layout).await?;+ Ok(ids.iter().flatten().count() as u64)+}++/// [`store_all`], returning the id each item was stored under, in order+/// (`None` for an item that failed).+pub(crate) async fn store_all_ids(+ config: &Config,+ bound: &BoundEngine,+ items: Vec<tinymemory_api::StoreItem>,+ (kind, target, source_id): (crate::config::schema::MemorySourceKind, &str, &str),+ layout: &tinymemory_tools::MemoryLayout,+) -> MemoryResult<Vec<Option<String>>> {+ let mut ids = Vec::with_capacity(items.len());let mut last_error = None;let mut touched = std::collections::BTreeSet::new();for item in items {@@ -120,8 +133,8 @@ pub(crate) async fn store_all(let node = crate::memory::brain::brain_node(config, layout, &brain_source, &item)?;let item = crate::memory::brain::file_into(node.clone(), item);match store_on(bound, item).await {- Ok(_) => {- stored += 1;+ Ok(receipt) => {+ ids.push(Some(receipt.id.to_string()));touched.insert(node);}// Out of credits or unreachable refuses every item, so stop@@ -129,6 +142,7 @@ pub(crate) async fn store_all(Err(error) if error.is_account_wide() => return Err(error),Err(error) => {tracing::debug!(id = %source_id, code = error.code(), "[memory:sources] item store failed");+ ids.push(None);last_error = Some(error);}}@@ -146,9 +160,9 @@ pub(crate) async fn store_all(}).collect();crate::memory::lifecycle::jobs::enqueue(config, layout.root(), jobs).await;- match (stored, last_error) {- (0, Some(error)) => Err(error),- _ => Ok(stored),+ match last_error {+ Some(error) if ids.iter().all(Option::is_none) => Err(error),+ _ => Ok(ids),}}diff --git a/crates/openhuman-core/src/memory/sources/versions.rs b/crates/openhuman-core/src/memory/sources/versions.rsnew file mode 100644index 0000000000..2a912257f6--- /dev/null+++ b/crates/openhuman-core/src/memory/sources/versions.rs@@ -0,0 +1,177 @@+//! Which stored item holds the current version of each connector record.+//!+//! A memory item's id is a digest of its content, so a record edited+//! upstream (a Notion page, a Linear issue) syncs as a new item and the old+//! version stays beside it. This file remembers, per record+//! ([`key`]), the id of the item last stored for it. A sync pass+//! ([`begin`]) records the ids it stored and the records that came back+//! empty, and hands back the ids no record uses any more; the caller+//! forgets them and then [`settle`]s them. Until settled they stay pending+//! and are handed back again by the next pass, so a failed forget is+//! retried and never orphans a version. It lives in+//! `<workspace>/memory/connector_items.json`.+//!+//! A workspace without the file (a new device) cannot tell an old version+//! from a new one, so versions stored before it existed stay until the+//! source is re-synced from scratch.++use std::collections::{BTreeMap, BTreeSet};+use std::path::{Path, PathBuf};+use std::sync::{LazyLock, Mutex};++use serde::{Deserialize, Serialize};++/// Serialises every read and read-modify-write of the file in this process.+static LOCK: LazyLock<Mutex<()>> = LazyLock::new(|| Mutex::new(()));++/// The file's contents.+#[derive(Debug, Default, Serialize, Deserialize)]+struct Versions {+ /// Record key → the id of the item holding its current version.+ #[serde(default)]+ items: BTreeMap<String, String>,+ /// Ids no record uses any more, not yet forgotten.+ #[serde(default)]+ stale: BTreeSet<String>,+}++fn path(workspace_dir: &Path) -> PathBuf {+ workspace_dir.join("memory").join("connector_items.json")+}++// ponytail: the whole map is read and rewritten per sync pass (~100 B a+// record, so ~1 MB at 10k records); a keyed store if accounts grow past that.+/// The file's contents, or `None` when it cannot be read right now: the+/// caller then changes nothing. A file that reads but does not parse is set+/// aside (`.corrupt`) with a warning rather than overwritten, and tracking+/// starts again from empty.+fn load(workspace_dir: &Path) -> Option<Versions> {+ 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 Some(Versions::default())+ }+ Err(error) => {+ tracing::warn!(error = %error, "[memory:sources] connector item versions unreadable; skipping");+ return None;+ }+ };+ Some(serde_json::from_str(&text).unwrap_or_else(|error| {+ tracing::warn!(error = %error, "[memory:sources] connector item versions unparsable");+ set_aside(&file)+ }))+}++fn set_aside(file: &Path) -> Versions {+ if let Err(error) = std::fs::rename(file, file.with_extension("json.corrupt")) {+ tracing::warn!(error = %error, "[memory:sources] could not set the versions file aside");+ }+ Versions::default()+}++/// Writes through a temporary file and a rename, so a stop mid-write never+/// leaves a partial file.+/// (`std::fs::rename` replaces an existing file on every platform.)+fn save(workspace_dir: &Path, versions: &Versions) -> bool {+ let file = path(workspace_dir);+ let temp = file.with_extension("json.tmp");+ let result = file+ .parent()+ .map_or(Ok(()), std::fs::create_dir_all)+ .and_then(|()| {+ let json = serde_json::to_vec(versions).map_err(std::io::Error::other)?;+ std::fs::write(&temp, json)?;+ std::fs::rename(&temp, &file)+ });+ if let Err(error) = &result {+ tracing::warn!(error = %error, "[memory:sources] writing connector item versions failed");+ }+ result.is_ok()+}++fn locked() -> std::sync::MutexGuard<'static, ()> {+ LOCK.lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+}++/// The key one record of `connection_id` is remembered under. The+/// connection id is length-prefixed, so no pair of ids shares a key.+#[must_use]+pub fn key(connection_id: &str, item_id: &str) -> String {+ format!("{}{item_id}", prefix(connection_id))+}++fn prefix(connection_id: &str) -> String {+ format!("{}:{connection_id}:", connection_id.len())+}++/// Starts a sync pass: `stored` records (key, id now stored) and `emptied`+/// records (keys that came back with no content). Remembers their state and+/// returns every id to forget: those no record uses any more, and those an+/// earlier pass could not forget, even when this pass stored nothing.+/// Forget them, then [`settle`] them. Hands back nothing when the state+/// cannot be read or written, so no id is forgotten unrecorded.+#[must_use]+pub fn begin(workspace_dir: &Path, stored: &[(String, String)], emptied: &[String]) -> Vec<String> {+ let _guard = locked();+ let Some(mut versions) = load(workspace_dir) else {+ return Vec::new();+ };+ if stored.is_empty() && emptied.is_empty() {+ return versions.stale.into_iter().collect();+ }+ let mut replaced = Vec::new();+ for (key, id) in stored {+ if let Some(old) = versions.items.insert(key.clone(), id.clone()) {+ if old != *id {+ replaced.push(old);+ }+ }+ }+ for key in emptied {+ replaced.extend(versions.items.remove(key));+ }+ versions.stale.extend(replaced);+ // An id another record still holds (two records with the same content)+ // is not stale.+ let current: BTreeSet<&String> = versions.items.values().collect();+ versions.stale.retain(|id| !current.contains(id));+ if !save(workspace_dir, &versions) {+ return Vec::new();+ }+ versions.stale.into_iter().collect()+}++/// Marks `forgotten` as gone: they are no longer handed back.+pub fn settle(workspace_dir: &Path, forgotten: &[String]) {+ if forgotten.is_empty() {+ return;+ }+ let _guard = locked();+ let Some(mut versions) = load(workspace_dir) else {+ return;+ };+ for id in forgotten {+ versions.stale.remove(id);+ }+ let _ = save(workspace_dir, &versions);+}++/// Forgets every record of `connection_id`, once its items are gone.+pub fn drop_connection(workspace_dir: &Path, connection_id: &str) {+ let _guard = locked();+ let Some(mut versions) = load(workspace_dir) else {+ return;+ };+ let prefix = prefix(connection_id);+ let before = versions.items.len();+ versions.items.retain(|key, _| !key.starts_with(&prefix));+ if versions.items.len() != before {+ let _ = save(workspace_dir, &versions);+ }+}++#[cfg(test)]+#[path = "versions_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/memory/sources/versions_tests.rs b/crates/openhuman-core/src/memory/sources/versions_tests.rsnew file mode 100644index 0000000000..3e7ecb8b57--- /dev/null+++ b/crates/openhuman-core/src/memory/sources/versions_tests.rs@@ -0,0 +1,116 @@+use super::*;++fn pair(key: &str, id: &str) -> (String, String) {+ (key.to_string(), id.to_string())+}++#[test]+fn a_changed_record_hands_back_its_previous_id() {+ let tmp = tempfile::tempdir().unwrap();+ let dir = tmp.path();+ assert!(begin(dir, &[pair("k1", "a"), pair("k2", "b")], &[]).is_empty());++ // Unchanged, edited and new records: only the edited one's old id.+ let stale = begin(+ dir,+ &[pair("k1", "a"), pair("k2", "b2"), pair("k3", "c")],+ &[],+ );+ assert_eq!(stale, ["b"]);+ settle(dir, &stale);+ assert!(begin(dir, &[pair("k2", "b2")], &[]).is_empty());+}++#[test]+fn an_unsettled_id_is_handed_back_again_and_the_new_one_is_kept() {+ let tmp = tempfile::tempdir().unwrap();+ let dir = tmp.path();+ let _ = begin(dir, &[pair("k", "v1")], &[]);+ // The forget of v1 fails: nothing is settled.+ assert_eq!(begin(dir, &[pair("k", "v2")], &[]), ["v1"]);+ // Edited again before the retry: v2 is stale too, v1 is still owed.+ assert_eq!(begin(dir, &[pair("k", "v3")], &[]), ["v1", "v2"]);+ settle(dir, &["v1".into(), "v2".into()]);+ assert!(begin(dir, &[pair("k", "v3")], &[]).is_empty());+}++#[test]+fn an_id_another_record_still_holds_is_not_stale() {+ let tmp = tempfile::tempdir().unwrap();+ let dir = tmp.path();+ // Two records with the same content share an id.+ let _ = begin(dir, &[pair("a", "x"), pair("b", "x")], &[]);+ assert!(+ begin(dir, &[pair("a", "y")], &[]).is_empty(),+ "b still holds x"+ );+ assert_eq!(begin(dir, &[pair("b", "z")], &[]), ["x"]);+}++#[test]+fn a_record_that_comes_back_empty_hands_back_its_id() {+ let tmp = tempfile::tempdir().unwrap();+ let dir = tmp.path();+ let _ = begin(dir, &[pair("k", "v1")], &[]);+ assert_eq!(begin(dir, &[], &["k".into()]), ["v1"]);+}++#[test]+fn keys_do_not_collide_across_connections() {+ assert_ne!(key("a:b", "c"), key("a", "b:c"));+ let tmp = tempfile::tempdir().unwrap();+ let dir = tmp.path();+ let _ = begin(+ dir,+ &[pair(&key("a:b", "c"), "x"), pair(&key("a", "b:c"), "y")],+ &[],+ );+ drop_connection(dir, "a");+ // `a:b`'s record is untouched by dropping `a`.+ let stale = begin(dir, &[pair(&key("a:b", "c"), "x2")], &[]);+ assert_eq!(stale, ["x"]);+ settle(dir, &stale);+ // `a`'s record was dropped, so its new id replaces nothing.+ assert!(begin(dir, &[pair(&key("a", "b:c"), "y2")], &[]).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!(begin(dir, &[pair("k", "v")], &[]).is_empty());+ assert_eq!(+ std::fs::read_to_string(file.with_extension("json.corrupt")).unwrap(),+ "{ not json"+ );+ assert_eq!(+ begin(dir, &[pair("k", "v2")], &[]),+ ["v"],+ "tracking resumed"+ );+}++#[test]+fn a_pass_with_no_records_still_hands_back_pending_ids() {+ let tmp = tempfile::tempdir().unwrap();+ let dir = tmp.path();+ let _ = begin(dir, &[pair("k", "v1")], &[]);+ let _ = begin(dir, &[pair("k", "v2")], &[]); // the forget of v1 fails+ assert_eq!(begin(dir, &[], &[]), ["v1"]);+}++#[test]+fn an_unreadable_file_changes_nothing() {+ let tmp = tempfile::tempdir().unwrap();+ let dir = tmp.path();+ let _ = begin(dir, &[pair("k", "v1")], &[]);+ // A directory where the file should be cannot be read as text.+ let file = path(dir);+ std::fs::remove_file(&file).unwrap();+ std::fs::create_dir(&file).unwrap();+ assert!(begin(dir, &[pair("k", "v2")], &[]).is_empty());+ assert!(file.is_dir(), "nothing was set aside or overwritten");+}