Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

feat(memory): remove the legacy copies of moved memory, after checking each

M3gA-Mind1192ac245935
diff --git a/crates/openhuman-core/src/memory/layout_migration/cleanup.rs b/crates/openhuman-core/src/memory/layout_migration/cleanup.rs
new file mode 100644
index 0000000000..16bf90655b
--- /dev/null
+++ b/crates/openhuman-core/src/memory/layout_migration/cleanup.rs
@@ -0,0 +1,188 @@
+//! Cleanup: removing the legacy copies of what was moved.
+//!
+//! Nothing is removed on the strength of the state file: the legacy tree is
+//! exported again, each item placed again, and its twin in the per-user tree
+//! read back by id. Only items whose twin is there are removed.
+//!
+//! - **A legacy scope whose every item has its twin**, with no partial item
+//! anywhere, is erased whole ([`MemoryEngine::erase`]), which releases the
+//! write keys.
+//! - **Otherwise**, and on an engine that cannot erase (the hosted one), the
+//! items with a twin are forgotten by id; the rest stay where they are.
+//!
+//! The pass ends by exporting the legacy tree once more: [`Phase::Cleaned`]
+//! is written only if nothing left there has a twin.
+
+use std::collections::BTreeMap;
+use std::path::Path;
+
+use tinymemory_api::{
+ EraseRequest, ForgetTarget, GetRequest, ItemId, ItemKind, ListRequest, MemoryEngine,
+ MetaFilter, Namespace, Reach, MAX_GET_IDS,
+};
+
+use super::copy::Engines;
+use super::map::Placement;
+use super::state::{self, MigrationState, Phase};
+use crate::memory::error::{MemoryError, MemoryResult};
+
+/// The legacy items of one kind at one node: their ids, and whether every
+/// one of them has its twin.
+#[derive(Default)]
+struct Group {
+ moved: Vec<ItemId>,
+ complete: bool,
+}
+
+/// What a pass over the legacy tree found.
+#[derive(Default)]
+struct Survey {
+ groups: BTreeMap<(String, ItemKind), (Namespace, Group)>,
+ partial: bool,
+}
+
+/// Exports the whole legacy tree and finds, for every item, whether its twin
+/// is in the per-user tree.
+async fn survey(engines: &Engines, placement: &Placement) -> MemoryResult<Survey> {
+ let mut found = Survey::default();
+ let mut cursor = None;
+ loop {
+ let mut request = ListRequest::new(MetaFilter::default(), MAX_GET_IDS);
+ request.cursor = cursor;
+ let page = engines.legacy.export(request).await?;
+ found.partial |= !page.incomplete.is_empty();
+ let mut twins = Vec::with_capacity(page.items.len());
+ for exported in &page.items {
+ let twin = placement
+ .place(exported.item.clone())
+ .map(|item| ItemId(item.fingerprint()))
+ .ok();
+ twins.push(twin);
+ }
+ let ids: Vec<ItemId> = twins.iter().flatten().cloned().collect();
+ let present = if ids.is_empty() {
+ Vec::new()
+ } else {
+ engines
+ .tree
+ .get(GetRequest { ids, reach: None })
+ .await?
+ .into_iter()
+ .map(|hit| hit.id)
+ .collect()
+ };
+ for (exported, twin) in page.items.into_iter().zip(twins) {
+ let namespace = exported.item.meta().namespace.clone();
+ let key = (namespace.to_string(), exported.item.kind());
+ let (_, group) = found.groups.entry(key).or_insert_with(|| {
+ (
+ namespace,
+ Group {
+ complete: true,
+ ..Group::default()
+ },
+ )
+ });
+ if twin.is_some_and(|twin| present.contains(&twin)) {
+ group.moved.push(exported.id);
+ } else {
+ group.complete = false;
+ }
+ }
+ match page.next_cursor {
+ Some(next) => cursor = Some(next),
+ None => return Ok(found),
+ }
+ }
+}
+
+/// Removes the legacy copies of everything moved, then checks nothing moved
+/// is left. Pauses (resumably) when `paused` says so or the account cannot
+/// go on.
+///
+/// # Errors
+///
+/// When the state cannot be saved, or the legacy tree cannot be read or
+/// changed for a reason that is not account-wide.
+pub async fn cleanup(
+ workspace_dir: &Path,
+ engines: &Engines,
+ placement: &Placement,
+ state: &mut MigrationState,
+ paused: impl Fn() -> bool,
+) -> MemoryResult<()> {
+ state.phase = Phase::Cleaning;
+ state.cleaning = true;
+ state.error = None;
+ state::save(workspace_dir, state)?;
+ match remove_moved(engines, placement, &paused).await {
+ Ok(true) => {}
+ Ok(false) => return pause(workspace_dir, state, "background work is paused".into()),
+ Err(error) if error.is_account_wide() => {
+ return pause(workspace_dir, state, error.to_string())
+ }
+ Err(error) => return Err(error),
+ }
+ let left = survey(engines, placement).await?;
+ let still_moved: usize = left.groups.values().map(|(_, g)| g.moved.len()).sum();
+ if still_moved > 0 {
+ return pause(
+ workspace_dir,
+ state,
+ format!("{still_moved} moved items are still in the legacy tree"),
+ );
+ }
+ state.phase = Phase::Cleaned;
+ state::save(workspace_dir, state)?;
+ tracing::info!(
+ left = left.groups.len(),
+ "[memory:layout_migration] legacy tree cleaned"
+ );
+ Ok(())
+}
+
+/// One removal pass; `false` when it stopped for a pause.
+async fn remove_moved(
+ engines: &Engines,
+ placement: &Placement,
+ paused: &impl Fn() -> bool,
+) -> MemoryResult<bool> {
+ let found = survey(engines, placement).await?;
+ let mut can_erase = !found.partial;
+ for ((_, kind), (namespace, group)) in found.groups {
+ if paused() {
+ return Ok(false);
+ }
+ if group.moved.is_empty() {
+ continue;
+ }
+ if can_erase && group.complete {
+ let mut erase = EraseRequest::new(Reach::exact(namespace.clone()));
+ erase.kinds = vec![kind];
+ match engines.legacy.erase(erase).await {
+ Ok(_) => continue,
+ Err(tinymemory_api::Error::Unsupported(_)) => can_erase = false,
+ Err(error) => return Err(error.into()),
+ }
+ }
+ for batch in group.moved.chunks(100) {
+ engines
+ .legacy
+ .forget(ForgetTarget::Ids(batch.to_vec()))
+ .await
+ .map_err(MemoryError::from)?;
+ }
+ }
+ Ok(true)
+}
+
+fn pause(workspace_dir: &Path, state: &mut MigrationState, why: String) -> MemoryResult<()> {
+ tracing::info!(%why, "[memory:layout_migration] cleanup paused");
+ state.phase = Phase::Paused;
+ state.error = Some(why);
+ state::save(workspace_dir, state)
+}
+
+#[cfg(test)]
+#[path = "cleanup_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/memory/layout_migration/cleanup_tests.rs b/crates/openhuman-core/src/memory/layout_migration/cleanup_tests.rs
new file mode 100644
index 0000000000..08a8390466
--- /dev/null
+++ b/crates/openhuman-core/src/memory/layout_migration/cleanup_tests.rs
@@ -0,0 +1,188 @@
+use std::sync::Arc;
+
+use tinymemory_api::conformance::ReferenceEngine;
+use tinymemory_api::{
+ async_trait, EngineDescriptor, EngineHealth, ExportPage, FetchPage, FetchRequest, ForgetReport,
+ Hit, LearningKind, ListPage, MemoryMeta, RecallAnswer, RecallRequest, Result, StoreItem,
+ StoreReceipt,
+};
+use tinymemory_tools::MemoryLayout;
+
+use super::*;
+use crate::memory::layout_migration::copy::copy;
+use crate::memory::layout_migration::map::FlowPlacement;
+
+fn placement() -> Placement {
+ Placement {
+ layout: MemoryLayout::new(Namespace::ROOT).unwrap(),
+ chat_node: "ws:main".parse().unwrap(),
+ flows: FlowPlacement::WithRoot,
+ }
+}
+
+async fn seeded(n: usize) -> Arc<ReferenceEngine> {
+ let legacy = Arc::new(ReferenceEngine::new());
+ for i in 0..n {
+ legacy
+ .store(StoreItem::learning(
+ format!("fact {i}"),
+ LearningKind::Fact,
+ 0.5,
+ MemoryMeta {
+ namespace: if i % 2 == 0 {
+ Namespace::ROOT
+ } else {
+ "agent:a".parse().unwrap()
+ },
+ ..MemoryMeta::default()
+ },
+ ))
+ .await
+ .unwrap();
+ }
+ legacy
+}
+
+async fn texts(engine: &dyn MemoryEngine) -> Vec<String> {
+ let mut texts: Vec<String> = engine
+ .list(ListRequest::new(MetaFilter::default(), 100))
+ .await
+ .unwrap()
+ .items
+ .into_iter()
+ .map(|hit| hit.text)
+ .collect();
+ texts.sort();
+ texts
+}
+
+async fn copied(tmp: &Path, engines: &Engines) -> MigrationState {
+ let mut state = MigrationState::default();
+ copy(tmp, engines, &placement(), &mut state, || false)
+ .await
+ .unwrap();
+ state
+}
+
+/// A reference engine that cannot erase, as the hosted one cannot.
+struct NoErase(ReferenceEngine);
+
+#[async_trait]
+impl MemoryEngine for NoErase {
+ fn descriptor(&self) -> &EngineDescriptor {
+ self.0.descriptor()
+ }
+ async fn health(&self) -> EngineHealth {
+ self.0.health().await
+ }
+ async fn recall(&self, req: RecallRequest) -> Result<RecallAnswer> {
+ self.0.recall(req).await
+ }
+ async fn fetch(&self, req: FetchRequest) -> Result<FetchPage> {
+ self.0.fetch(req).await
+ }
+ async fn store(&self, item: StoreItem) -> Result<StoreReceipt> {
+ self.0.store(item).await
+ }
+ async fn forget(&self, target: ForgetTarget) -> Result<ForgetReport> {
+ self.0.forget(target).await
+ }
+ async fn list(&self, req: ListRequest) -> Result<ListPage> {
+ self.0.list(req).await
+ }
+ async fn export(&self, req: ListRequest) -> Result<ExportPage> {
+ self.0.export(req).await
+ }
+ async fn get(&self, req: GetRequest) -> Result<Vec<Hit>> {
+ self.0.get(req).await
+ }
+}
+
+#[tokio::test]
+async fn everything_moved_is_erased_from_the_legacy_tree() {
+ let tmp = tempfile::tempdir().unwrap();
+ let legacy = seeded(10).await;
+ let tree = Arc::new(ReferenceEngine::new());
+ let engines = Engines {
+ legacy: legacy.clone(),
+ tree: tree.clone(),
+ };
+ let mut state = copied(tmp.path(), &engines).await;
+ cleanup(tmp.path(), &engines, &placement(), &mut state, || false)
+ .await
+ .unwrap();
+ assert_eq!(state.phase, Phase::Cleaned);
+ assert!(texts(legacy.as_ref()).await.is_empty());
+ assert_eq!(texts(tree.as_ref()).await.len(), 10, "the moved items stay");
+}
+
+#[tokio::test]
+async fn an_item_without_its_twin_is_never_removed() {
+ let tmp = tempfile::tempdir().unwrap();
+ let legacy = seeded(10).await;
+ let tree = Arc::new(ReferenceEngine::new());
+ let engines = Engines {
+ legacy: legacy.clone(),
+ tree: tree.clone(),
+ };
+ let mut state = copied(tmp.path(), &engines).await;
+ // The per-user copy of "fact 3" is lost after the copy.
+ let lost = tree
+ .list(ListRequest::new(MetaFilter::default(), 100))
+ .await
+ .unwrap()
+ .items
+ .into_iter()
+ .find(|hit| hit.text == "fact 3")
+ .unwrap();
+ tree.forget(ForgetTarget::Ids(vec![lost.id])).await.unwrap();
+
+ cleanup(tmp.path(), &engines, &placement(), &mut state, || false)
+ .await
+ .unwrap();
+ assert_eq!(state.phase, Phase::Cleaned);
+ assert_eq!(texts(legacy.as_ref()).await, vec!["fact 3".to_string()]);
+}
+
+#[tokio::test]
+async fn an_engine_that_cannot_erase_forgets_by_id() {
+ let tmp = tempfile::tempdir().unwrap();
+ let legacy = Arc::new(NoErase(ReferenceEngine::new()));
+ for i in 0..5 {
+ legacy
+ .store(StoreItem::learning(
+ format!("fact {i}"),
+ LearningKind::Fact,
+ 0.5,
+ MemoryMeta::default(),
+ ))
+ .await
+ .unwrap();
+ }
+ let engines = Engines {
+ legacy: legacy.clone(),
+ tree: Arc::new(ReferenceEngine::new()),
+ };
+ let mut state = copied(tmp.path(), &engines).await;
+ cleanup(tmp.path(), &engines, &placement(), &mut state, || false)
+ .await
+ .unwrap();
+ assert_eq!(state.phase, Phase::Cleaned);
+ assert!(texts(legacy.as_ref()).await.is_empty());
+}
+
+#[tokio::test]
+async fn a_paused_cleanup_says_it_was_cleaning() {
+ let tmp = tempfile::tempdir().unwrap();
+ let engines = Engines {
+ legacy: seeded(4).await,
+ tree: Arc::new(ReferenceEngine::new()),
+ };
+ let mut state = copied(tmp.path(), &engines).await;
+ cleanup(tmp.path(), &engines, &placement(), &mut state, || true)
+ .await
+ .unwrap();
+ assert_eq!(state.phase, Phase::Paused);
+ assert!(state.cleaning, "a resume goes back to cleanup");
+ assert_eq!(texts(engines.legacy.as_ref()).await.len(), 4);
+}
diff --git a/crates/openhuman-core/src/memory/layout_migration/copy_tests.rs b/crates/openhuman-core/src/memory/layout_migration/copy_tests.rs
index acc474b4fd..0caec739f6 100644
--- a/crates/openhuman-core/src/memory/layout_migration/copy_tests.rs
+++ b/crates/openhuman-core/src/memory/layout_migration/copy_tests.rs
@@ -192,3 +192,71 @@ async fn a_legacy_tree_that_cannot_be_read_pauses() {
.unwrap();
assert_eq!(state.phase, Phase::Paused);
}
+
+#[tokio::test]
+async fn old_brain_nodes_are_refiled_by_connector() {
+ let tmp = tempfile::tempdir().unwrap();
+ let legacy = Arc::new(ReferenceEngine::new());
+ let doc = |text: &str, node: &str, kind: SourceKind, path: Option<&str>| {
+ StoreItem::document(
+ text,
+ MemoryMeta {
+ namespace: node.parse().unwrap(),
+ source: SourceRef { kind, id: None },
+ file_path: path.map(str::to_string),
+ ..MemoryMeta::default()
+ },
+ )
+ };
+ for item in [
+ doc("a pdf", "source:pdf", SourceKind::File, Some("a.pdf")),
+ doc("a note", "source:markdown", SourceKind::File, Some("a.md")),
+ doc("a link", "source:web", SourceKind::Link, None),
+ doc(
+ "an upload",
+ "source:web",
+ SourceKind::Link,
+ Some("page.html"),
+ ),
+ doc(
+ "a drive doc",
+ "source:google_drive",
+ SourceKind::Composio,
+ None,
+ ),
+ doc("a notion page", "source:notion", SourceKind::Composio, None),
+ ] {
+ legacy.store(item).await.unwrap();
+ }
+ let tree = Arc::new(ReferenceEngine::new());
+ let engines = Engines {
+ legacy,
+ tree: tree.clone(),
+ };
+ let mut state = MigrationState::default();
+ copy(tmp.path(), &engines, &placement(), &mut state, || false)
+ .await
+ .unwrap();
+ assert_eq!(state.phase, Phase::Copied);
+ let mut placed: Vec<(String, String)> = tree
+ .list(ListRequest::new(MetaFilter::default(), 50))
+ .await
+ .unwrap()
+ .items
+ .into_iter()
+ .map(|hit| (hit.text, hit.meta.namespace.to_string()))
+ .collect();
+ placed.sort();
+ let expect = |text: &str, node: &str| (text.to_string(), node.to_string());
+ assert_eq!(
+ placed,
+ vec![
+ expect("a drive doc", "source:googledrive"),
+ expect("a link", "source:web"),
+ expect("a note", "source:files"),
+ expect("a notion page", "source:notion"),
+ expect("a pdf", "source:files"),
+ expect("an upload", "source:files"),
+ ]
+ );
+}
diff --git a/crates/openhuman-core/src/memory/layout_migration/mod.rs b/crates/openhuman-core/src/memory/layout_migration/mod.rs
index a910f11d9c..da2aef5f34 100644
--- a/crates/openhuman-core/src/memory/layout_migration/mod.rs
+++ b/crates/openhuman-core/src/memory/layout_migration/mod.rs
@@ -12,10 +12,12 @@
//! engines. Binding the two engines, the switch to the per-user tree, the
//! catch-up pass, cleanup and the RPCs build on it.
+pub mod cleanup;
pub mod copy;
pub mod map;
pub mod state;
+pub use cleanup::cleanup;
pub use copy::{copy, legacy_present, Engines};
pub use map::{FlowPlacement, Placement};
pub use state::{MigrationState, Phase};
diff --git a/crates/openhuman-core/src/memory/layout_migration/state.rs b/crates/openhuman-core/src/memory/layout_migration/state.rs
index 2065ff07ff..b6dba03aca 100644
--- a/crates/openhuman-core/src/memory/layout_migration/state.rs
+++ b/crates/openhuman-core/src/memory/layout_migration/state.rs
@@ -23,6 +23,11 @@ pub enum Phase {
Paused,
/// Every item it could copy is copied and verified.
Copied,
+ /// Removing the legacy copies of what was moved.
+ Cleaning,
+ /// The legacy tree holds nothing that was moved; what is left there (if
+ /// anything) is in `failures` or `incomplete`.
+ Cleaned,
}
/// An item that could not be copied.
@@ -56,6 +61,9 @@ pub struct MigrationState {
/// Why it is paused.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub error: Option<String>,
+ /// Cleanup has started, so a pause resumes it, not the copy.
+ #[serde(default)]
+ pub cleaning: bool,
}
/// The state file of `workspace_dir`.
diff --git a/crates/openhuman-core/src/memory/layout_migration/state_tests.rs b/crates/openhuman-core/src/memory/layout_migration/state_tests.rs
index 03723144cb..f4b39bd34e 100644
--- a/crates/openhuman-core/src/memory/layout_migration/state_tests.rs
+++ b/crates/openhuman-core/src/memory/layout_migration/state_tests.rs
@@ -20,6 +20,7 @@ fn a_saved_state_loads_back_and_leaves_no_temporary_file() {
}],
incomplete: vec!["def".into()],
error: Some("background work is paused".into()),
+ cleaning: true,
};
save(tmp.path(), &state).unwrap();
assert_eq!(load(tmp.path()).unwrap(), state);