Skip to content

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

fix(memory): migration review round

M3gA-Mindf2ce5b26d521
diff --git a/crates/openhuman-core/src/memory/layout_migration/app_host.rs b/crates/openhuman-core/src/memory/layout_migration/app_host.rs
index dcefd6f123..cced44bcef 100644
--- a/crates/openhuman-core/src/memory/layout_migration/app_host.rs
+++ b/crates/openhuman-core/src/memory/layout_migration/app_host.rs
@@ -6,7 +6,7 @@ use async_trait::async_trait;
use super::claim::ClaimKey;
use super::copy::Engines;
-use super::host::LayoutHost;
+use super::job::LayoutHost;
use super::map::{FlowPlacement, Placement};
use crate::config::{Config, MemoryLayoutMode};
use crate::memory::engine::{self, CORTEXDB_ENGINE};
diff --git a/crates/openhuman-core/src/memory/layout_migration/cleanup.rs b/crates/openhuman-core/src/memory/layout_migration/cleanup.rs
index 6f72462594..1a0ab234ba 100644
--- a/crates/openhuman-core/src/memory/layout_migration/cleanup.rs
+++ b/crates/openhuman-core/src/memory/layout_migration/cleanup.rs
@@ -7,8 +7,10 @@
//! - **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.
+//! - **Otherwise**, on an engine that cannot erase (the hosted one), and on
+//! a legacy tree other accounts share (whose writes can land between the
+//! survey and an erase), 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.
@@ -108,6 +110,7 @@ pub async fn cleanup<P>(
workspace_dir: &Path,
engines: &Engines,
placement: &Placement,
+ shared: bool,
state: &mut MigrationState,
paused: impl Fn() -> P,
) -> MemoryResult<()>
@@ -118,7 +121,7 @@ where
state.cleaning = true;
state.error = None;
state::save(workspace_dir, state)?;
- match remove_moved(engines, placement, &paused).await {
+ match remove_moved(engines, placement, shared, &paused).await {
Ok(true) => {}
Ok(false) => return pause(workspace_dir, state, "background work is paused".into()),
Err(error) if error.is_account_wide() => {
@@ -148,13 +151,14 @@ where
async fn remove_moved<P>(
engines: &Engines,
placement: &Placement,
+ shared: bool,
paused: &impl Fn() -> P,
) -> MemoryResult<bool>
where
P: std::future::Future<Output = bool>,
{
let found = survey(engines, placement).await?;
- let mut can_erase = !found.partial;
+ let mut can_erase = !found.partial && !shared;
for ((_, kind), (namespace, group)) in found.groups {
if paused().await {
return Ok(false);
diff --git a/crates/openhuman-core/src/memory/layout_migration/cleanup_tests.rs b/crates/openhuman-core/src/memory/layout_migration/cleanup_tests.rs
index da56a1b8ae..e138dcd221 100644
--- a/crates/openhuman-core/src/memory/layout_migration/cleanup_tests.rs
+++ b/crates/openhuman-core/src/memory/layout_migration/cleanup_tests.rs
@@ -2,9 +2,9 @@ use std::sync::Arc;
use tinymemory_api::conformance::ReferenceEngine;
use tinymemory_api::{
- async_trait, EngineDescriptor, EngineHealth, ExportPage, FetchPage, FetchRequest, ForgetReport,
- Hit, LearningKind, ListPage, MemoryEngine, MemoryMeta, RecallAnswer, RecallRequest, Result,
- StoreItem, StoreReceipt,
+ async_trait, EngineDescriptor, EngineHealth, EraseReport, ExportPage, FetchPage, FetchRequest,
+ ForgetReport, Hit, LearningKind, ListPage, MemoryEngine, MemoryMeta, RecallAnswer,
+ RecallRequest, Result, StoreItem, StoreReceipt,
};
use tinymemory_tools::MemoryLayout;
@@ -67,6 +67,43 @@ async fn copied(tmp: &Path, engines: &Engines) -> MigrationState {
/// A reference engine that cannot erase, as the hosted one cannot.
struct NoErase(ReferenceEngine);
+/// A reference engine whose erase must never be called.
+struct NeverErase(ReferenceEngine);
+
+#[async_trait]
+impl MemoryEngine for NeverErase {
+ 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
+ }
+ async fn erase(&self, _: EraseRequest) -> Result<EraseReport> {
+ panic!("a shared legacy tree is never erased scope-wide");
+ }
+}
+
#[async_trait]
impl MemoryEngine for NoErase {
fn descriptor(&self) -> &EngineDescriptor {
@@ -108,9 +145,14 @@ async fn everything_moved_is_erased_from_the_legacy_tree() {
tree: tree.clone(),
};
let mut state = copied(tmp.path(), &engines).await;
- cleanup(tmp.path(), &engines, &placement(), &mut state, || async {
- false
- })
+ cleanup(
+ tmp.path(),
+ &engines,
+ &placement(),
+ false,
+ &mut state,
+ || async { false },
+ )
.await
.unwrap();
assert_eq!(state.phase, Phase::Cleaned);
@@ -139,9 +181,14 @@ async fn an_item_without_its_twin_is_never_removed() {
.unwrap();
tree.forget(ForgetTarget::Ids(vec![lost.id])).await.unwrap();
- cleanup(tmp.path(), &engines, &placement(), &mut state, || async {
- false
- })
+ cleanup(
+ tmp.path(),
+ &engines,
+ &placement(),
+ false,
+ &mut state,
+ || async { false },
+ )
.await
.unwrap();
assert_eq!(state.phase, Phase::Cleaned);
@@ -168,9 +215,14 @@ async fn an_engine_that_cannot_erase_forgets_by_id() {
tree: Arc::new(ReferenceEngine::new()),
};
let mut state = copied(tmp.path(), &engines).await;
- cleanup(tmp.path(), &engines, &placement(), &mut state, || async {
- false
- })
+ cleanup(
+ tmp.path(),
+ &engines,
+ &placement(),
+ false,
+ &mut state,
+ || async { false },
+ )
.await
.unwrap();
assert_eq!(state.phase, Phase::Cleaned);
@@ -185,12 +237,51 @@ async fn a_paused_cleanup_says_it_was_cleaning() {
tree: Arc::new(ReferenceEngine::new()),
};
let mut state = copied(tmp.path(), &engines).await;
- cleanup(tmp.path(), &engines, &placement(), &mut state, || async {
- true
- })
+ cleanup(
+ tmp.path(),
+ &engines,
+ &placement(),
+ false,
+ &mut state,
+ || async { 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);
}
+
+#[tokio::test]
+async fn a_shared_legacy_tree_is_forgotten_by_id_never_erased() {
+ let tmp = tempfile::tempdir().unwrap();
+ let legacy = Arc::new(NeverErase(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(),
+ true,
+ &mut state,
+ || async { false },
+ )
+ .await
+ .unwrap();
+ assert_eq!(state.phase, Phase::Cleaned);
+ assert!(texts(legacy.as_ref()).await.is_empty());
+}
diff --git a/crates/openhuman-core/src/memory/layout_migration/copy.rs b/crates/openhuman-core/src/memory/layout_migration/copy.rs
index eb2b9ad3e3..ffab5888c6 100644
--- a/crates/openhuman-core/src/memory/layout_migration/copy.rs
+++ b/crates/openhuman-core/src/memory/layout_migration/copy.rs
@@ -62,6 +62,14 @@ where
{
state.phase = Phase::Copying;
state.error = None;
+ if state.cursor.is_none() {
+ // A pass from the top (the first, or the catch-up after the switch)
+ // meets every item again: count it afresh.
+ state.copied = 0;
+ state.replayed = 0;
+ state.failures.clear();
+ state.incomplete.clear();
+ }
state::save(workspace_dir, state)?;
loop {
if paused().await {
@@ -83,17 +91,16 @@ where
return Err(error);
}
};
- state
- .incomplete
- .extend(page.incomplete.into_iter().map(|id| id.0));
+ for id in page.incomplete {
+ if !state.incomplete.contains(&id.0) {
+ state.incomplete.push(id.0);
+ }
+ }
let mut placed = Vec::with_capacity(page.items.len());
for exported in page.items {
match placement.place(exported.item) {
Ok(item) => placed.push((exported.id.0, item)),
- Err(error) => state.failures.push(Failure {
- id: exported.id.0,
- reason: error.code().to_string(),
- }),
+ Err(error) => note_failure(state, exported.id.0, error.code()),
}
}
if let Err(error) = store_and_check(engines.tree.as_ref(), placed, state).await {
@@ -115,6 +122,17 @@ where
}
}
+/// Records `id` as not copied, once: a page sent again after a pause meets
+/// the same items.
+fn note_failure(state: &mut MigrationState, id: String, reason: &str) {
+ if !state.failures.iter().any(|failure| failure.id == id) {
+ state.failures.push(Failure {
+ id,
+ reason: reason.to_string(),
+ });
+ }
+}
+
fn pause(workspace_dir: &Path, state: &mut MigrationState, why: String) -> MemoryResult<()> {
tracing::info!(%why, copied = state.copied, "[memory:layout_migration] paused");
state.phase = Phase::Paused;
@@ -149,10 +167,7 @@ async fn store_and_check(
match tree.store(item).await {
Ok(receipt) => stored.push((legacy, receipt.id, receipt.replayed)),
Err(error) if !skips_item(&error) => return Err(error.into()),
- Err(error) => state.failures.push(Failure {
- id: legacy,
- reason: MemoryError::from(error).code().to_string(),
- }),
+ Err(error) => note_failure(state, legacy, MemoryError::from(error).code()),
}
}
}
@@ -167,10 +182,7 @@ async fn store_and_check(
state.copied += 1;
state.replayed += u64::from(replayed);
} else {
- state.failures.push(Failure {
- id: legacy,
- reason: "not_readable_after_store".to_string(),
- });
+ note_failure(state, legacy, "not_readable_after_store");
}
}
Ok(())
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 f0d34920e2..82465e00c9 100644
--- a/crates/openhuman-core/src/memory/layout_migration/copy_tests.rs
+++ b/crates/openhuman-core/src/memory/layout_migration/copy_tests.rs
@@ -165,6 +165,26 @@ async fn a_repeated_page_is_a_replay() {
assert_eq!(count(tree.as_ref()).await, 4);
}
+#[tokio::test]
+async fn the_catch_up_pass_counts_each_item_once() {
+ let tmp = tempfile::tempdir().unwrap();
+ let engines = Engines {
+ legacy: legacy_tree(3).await,
+ tree: Arc::new(ReferenceEngine::new()),
+ };
+ let mut state = MigrationState::default();
+ for _ in 0..2 {
+ // The first pass, then the catch-up pass on the same state.
+ copy(tmp.path(), &engines, &placement(), &mut state, || async {
+ false
+ })
+ .await
+ .unwrap();
+ }
+ assert_eq!(state.copied, 4, "not 8");
+ assert_eq!(state.replayed, 4, "the second pass replays every item");
+}
+
#[tokio::test]
async fn an_account_that_cannot_write_pauses_without_advancing() {
let tmp = tempfile::tempdir().unwrap();
diff --git a/crates/openhuman-core/src/memory/layout_migration/host.rs b/crates/openhuman-core/src/memory/layout_migration/host.rs
deleted file mode 100644
index 5ab9efab47..0000000000
--- a/crates/openhuman-core/src/memory/layout_migration/host.rs
+++ /dev/null
@@ -1,60 +0,0 @@
-//! What the migration needs from the host, behind one trait so the job is
-//! tested without a TinyHumans session or a CortexDB server.
-//!
-//! The real host (the engine binding and the layout setting) implements it
-//! over `memory::engine` and `memory::scope`; tests implement it over two
-//! in-memory engines.
-
-use async_trait::async_trait;
-
-use super::claim::ClaimKey;
-use super::copy::Engines;
-use super::map::Placement;
-use crate::config::Config;
-use crate::memory::error::MemoryResult;
-
-/// The host side of a layout migration.
-#[async_trait]
-pub trait LayoutHost: Send + Sync {
- /// The legacy-layout engine and the per-user engine for `config`'s
- /// account, on one endpoint and credential.
- ///
- /// # Errors
- ///
- /// When memory is off or the account has no per-user root.
- fn engines(&self, config: &Config) -> MemoryResult<Engines>;
-
- /// Where items go in the per-user tree.
- ///
- /// # Errors
- ///
- /// When the layout cannot be built.
- fn placement(&self, config: &Config) -> MemoryResult<Placement>;
-
- /// Whether reads and writes already use the per-user tree.
- fn is_switched(&self, config: &Config) -> bool;
-
- /// Moves reads and writes to the per-user tree: persists the layout
- /// setting and drops the cached engines. The real host loads the migrated
- /// person's own config file fresh, so a setting changed during a long
- /// migration is never reverted and an account switch mid-move never
- /// writes another person's config.
- ///
- /// # Errors
- ///
- /// When the setting cannot be saved.
- async fn switch(&self, config: &Config) -> MemoryResult<()>;
-
- /// Whether moving memory costs the user nothing right now (always, off
- /// the hosted engine).
- async fn free_now(&self, config: &Config) -> bool;
-
- /// The claim on the legacy tree when other accounts on this machine may
- /// share it (a self-hosted engine), so taking it needs the user's
- /// consent and only one account may; `None` when it is the account's own.
- ///
- /// # Errors
- ///
- /// When memory is off or the account has no per-user root.
- fn legacy_claim(&self, config: &Config) -> MemoryResult<Option<ClaimKey>>;
-}
diff --git a/crates/openhuman-core/src/memory/layout_migration/job.rs b/crates/openhuman-core/src/memory/layout_migration/job.rs
index ae9f212a4f..dc8b84c658 100644
--- a/crates/openhuman-core/src/memory/layout_migration/job.rs
+++ b/crates/openhuman-core/src/memory/layout_migration/job.rs
@@ -18,10 +18,12 @@
//! Every step saves its progress, so [`run`] called again (after a pause, a
//! crash or a restart) continues where the last one stopped.
-use super::claim;
+use async_trait::async_trait;
+
+use super::claim::{self, ClaimKey};
use super::cleanup::cleanup;
-use super::copy::{copy, legacy_present};
-use super::host::LayoutHost;
+use super::copy::{copy, legacy_present, Engines};
+use super::map::Placement;
use super::state::{self, MigrationState, Phase};
use crate::config::Config;
use crate::memory::error::MemoryResult;
@@ -58,6 +60,57 @@ pub enum Outcome {
Done,
}
+/// What the migration needs from the host, behind one trait so the job is
+/// tested without a TinyHumans session or a CortexDB server.
+///
+/// The real host (the engine binding and the layout setting) implements it
+/// over `memory::engine` and `memory::scope`; tests implement it over two
+/// in-memory engines.
+#[async_trait]
+pub trait LayoutHost: Send + Sync {
+ /// The legacy-layout engine and the per-user engine for `config`'s
+ /// account, on one endpoint and credential.
+ ///
+ /// # Errors
+ ///
+ /// When memory is off or the account has no per-user root.
+ fn engines(&self, config: &Config) -> MemoryResult<Engines>;
+
+ /// Where items go in the per-user tree.
+ ///
+ /// # Errors
+ ///
+ /// When the layout cannot be built.
+ fn placement(&self, config: &Config) -> MemoryResult<Placement>;
+
+ /// Whether reads and writes already use the per-user tree.
+ fn is_switched(&self, config: &Config) -> bool;
+
+ /// Moves reads and writes to the per-user tree: persists the layout
+ /// setting and drops the cached engines. The real host loads the migrated
+ /// person's own config file fresh, so a setting changed during a long
+ /// migration is never reverted and an account switch mid-move never
+ /// writes another person's config.
+ ///
+ /// # Errors
+ ///
+ /// When the setting cannot be saved.
+ async fn switch(&self, config: &Config) -> MemoryResult<()>;
+
+ /// Whether moving memory costs the user nothing right now (always, off
+ /// the hosted engine).
+ async fn free_now(&self, config: &Config) -> bool;
+
+ /// The claim on the legacy tree when other accounts on this machine may
+ /// share it (a self-hosted engine), so taking it needs the user's
+ /// consent and only one account may; `None` when it is the account's own.
+ ///
+ /// # Errors
+ ///
+ /// When memory is off or the account has no per-user root.
+ fn legacy_claim(&self, config: &Config) -> MemoryResult<Option<ClaimKey>>;
+}
+
/// Runs (or resumes) the migration of `config`'s account. `paused` is the
/// scheduler's own pause (background work held), asked before every page.
///
@@ -87,15 +140,16 @@ where
state.takeover = true;
state::save(dir, &state)?;
}
- if let Some(key) = host.legacy_claim(config)? {
- if claim::held_by_other(&key)? {
- return Ok(Outcome::ClaimedElsewhere);
+ let shared = host.legacy_claim(config)?;
+ if let Some(key) = &shared {
+ if claim::held_by_other(key)? {
+ return claimed_elsewhere(config, host, &mut state).await;
}
if !state.takeover {
return Ok(Outcome::NeedsTakeover);
}
- if !claim::take(&key)? {
- return Ok(Outcome::ClaimedElsewhere);
+ if !claim::take(key)? {
+ return claimed_elsewhere(config, host, &mut state).await;
}
}
let auto = trigger == Trigger::Auto;
@@ -127,7 +181,15 @@ where
state.caught_up = true;
state::save(dir, &state)?;
}
- cleanup(dir, &engines, &placement, &mut state, stop).await?;
+ cleanup(
+ dir,
+ &engines,
+ &placement,
+ shared.is_some(),
+ &mut state,
+ stop,
+ )
+ .await?;
Ok(if state.phase == Phase::Cleaned {
Outcome::Done
} else {
@@ -135,6 +197,18 @@ where
})
}
+/// Another account took the shared legacy tree: this one has nothing to
+/// move, and goes on in its own per-user tree like an account that never had
+/// legacy memory, rather than in the tree the other account emptied.
+async fn claimed_elsewhere(
+ config: &Config,
+ host: &dyn LayoutHost,
+ state: &mut MigrationState,
+) -> MemoryResult<Outcome> {
+ nothing_to_move(config, host, state).await?;
+ Ok(Outcome::ClaimedElsewhere)
+}
+
async fn nothing_to_move(
config: &Config,
host: &dyn LayoutHost,
diff --git a/crates/openhuman-core/src/memory/layout_migration/job_tests.rs b/crates/openhuman-core/src/memory/layout_migration/job_tests.rs
index 8b7c82f03c..c827b5a65d 100644
--- a/crates/openhuman-core/src/memory/layout_migration/job_tests.rs
+++ b/crates/openhuman-core/src/memory/layout_migration/job_tests.rs
@@ -140,6 +140,10 @@ async fn a_tree_another_account_took_is_left_alone() {
);
assert_eq!(count(&*host.legacy).await, 3, "nothing moved");
assert_eq!(count(&*host.tree).await, 0);
+ assert!(
+ host.switched.load(Ordering::SeqCst),
+ "this account goes on in its own tree, not the one another took"
+ );
assert!(
!crate::memory::layout_migration::scan(&config, &host)
.await
diff --git a/crates/openhuman-core/src/memory/layout_migration/mod.rs b/crates/openhuman-core/src/memory/layout_migration/mod.rs
index fa80da2d38..f5747f1f9a 100644
--- a/crates/openhuman-core/src/memory/layout_migration/mod.rs
+++ b/crates/openhuman-core/src/memory/layout_migration/mod.rs
@@ -16,7 +16,6 @@ pub mod app_host;
pub mod claim;
pub mod cleanup;
pub mod copy;
-pub mod host;
pub mod job;
pub mod map;
pub mod service;
@@ -28,8 +27,7 @@ mod test_host;
pub use app_host::AppHost;
pub use cleanup::cleanup;
pub use copy::{copy, legacy_present, Engines};
-pub use host::LayoutHost;
-pub use job::{run, Outcome, Trigger};
+pub use job::{run, LayoutHost, Outcome, Trigger};
pub use map::{FlowPlacement, Placement};
pub use service::{retry, scan, start, status, tick, MigrationStatus, ScanView, StartParams};
pub use state::{MigrationState, Phase};
diff --git a/crates/openhuman-core/src/memory/layout_migration/service.rs b/crates/openhuman-core/src/memory/layout_migration/service.rs
index 1443bfa6c8..590dc78a83 100644
--- a/crates/openhuman-core/src/memory/layout_migration/service.rs
+++ b/crates/openhuman-core/src/memory/layout_migration/service.rs
@@ -19,7 +19,7 @@ use serde::Serialize;
use super::claim;
use super::copy::legacy_present;
-use super::host::LayoutHost;
+use super::job::LayoutHost;
use super::job::{run, Trigger};
use super::state::{self, MigrationState, Phase};
use crate::config::Config;
diff --git a/crates/openhuman-core/src/memory/layout_migration/test_host.rs b/crates/openhuman-core/src/memory/layout_migration/test_host.rs
index 506e9f5a34..1cb58ed033 100644
--- a/crates/openhuman-core/src/memory/layout_migration/test_host.rs
+++ b/crates/openhuman-core/src/memory/layout_migration/test_host.rs
@@ -11,7 +11,7 @@ use tinymemory_tools::MemoryLayout;
use super::claim::ClaimKey;
use super::copy::Engines;
-use super::host::LayoutHost;
+use super::job::LayoutHost;
use super::map::{FlowPlacement, Placement};
use crate::config::Config;
use crate::memory::error::{MemoryError, MemoryResult};
diff --git a/docs/specs/memory-v2.md b/docs/specs/memory-v2.md
index 7ffa44ab90..b0589f0842 100644
--- a/docs/specs/memory-v2.md
+++ b/docs/specs/memory-v2.md
@@ -251,8 +251,10 @@ stopped. The memory background job runs it on its own only while moving is
free (always off the hosted engine); `memory_migration_start` runs it now.
On a self-hosted CortexDB every account on the machine shares the legacy
tree: it moves only with `takeover: true`, and the first account to take it
-claims it in `<app>/memory/legacy_claims/`, so other accounts have nothing
-to move. Items that could not be moved stay in the legacy tree;
+claims it in `<app>/memory/legacy_claims/`; other accounts have nothing
+to move and go on in their own per-user tree. A shared tree is cleaned up by
+forgetting moved items by id, never by erasing a whole scope, since other
+accounts may still write there. Items that could not be moved stay in the legacy tree;
`memory_migration_retry` puts them back in line.
**Past conversations.** `memory_conversations_backfill_start` walks the