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): scan, start, status, retry and a background tick for the migration
M3gA-Mind23811db59528
diff --git a/crates/openhuman-core/src/memory/layout_migration/job_tests.rs b/crates/openhuman-core/src/memory/layout_migration/job_tests.rsindex 8e30b57a26..f14cf3d489 100644--- a/crates/openhuman-core/src/memory/layout_migration/job_tests.rs+++ b/crates/openhuman-core/src/memory/layout_migration/job_tests.rs@@ -1,107 +1,9 @@-use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};-use std::sync::{Arc, Mutex};+use std::sync::atomic::Ordering;-use tinymemory_api::conformance::ReferenceEngine;-use tinymemory_api::{- LearningKind, ListRequest, MemoryEngine, MemoryMeta, MetaFilter, Namespace, StoreItem,-};-use tinymemory_tools::MemoryLayout;+use tinymemory_api::{ListRequest, MemoryEngine, MetaFilter};use super::*;-use crate::memory::error::MemoryError;-use crate::memory::layout_migration::copy::Engines;-use crate::memory::layout_migration::map::{FlowPlacement, Placement};--/// Two in-memory engines and the switches a real host keeps.-struct FakeHost {- legacy: Arc<ReferenceEngine>,- tree: Arc<ReferenceEngine>,- switched: AtomicBool,- free: AtomicBool,- shared: bool,- /// Asks for free_now: after this many, moving stops being free.- free_for: AtomicUsize,- /// Written to the legacy tree as the switch happens (a turn racing it).- racing_write: Mutex<Option<StoreItem>>,-}--impl FakeHost {- async fn with(learnings: usize) -> Self {- let legacy = Arc::new(ReferenceEngine::new());- for i in 0..learnings {- legacy.store(fact(&format!("fact {i}"))).await.unwrap();- }- Self {- legacy,- tree: Arc::new(ReferenceEngine::new()),- switched: AtomicBool::new(false),- free: AtomicBool::new(true),- shared: false,- free_for: AtomicUsize::new(usize::MAX),- racing_write: Mutex::new(None),- }- }-}--fn fact(text: &str) -> StoreItem {- StoreItem::learning(text, LearningKind::Fact, 0.5, MemoryMeta::default())-}--async fn count(engine: &dyn MemoryEngine) -> usize {- let mut total = 0;- let mut cursor = None;- loop {- let mut request = ListRequest::new(MetaFilter::default(), 100);- request.cursor = cursor;- let page = engine.list(request).await.unwrap();- total += page.items.len();- match page.next_cursor {- Some(next) => cursor = Some(next),- None => return total,- }- }-}--#[async_trait::async_trait]-impl LayoutHost for FakeHost {- fn engines(&self, _: &Config) -> MemoryResult<Engines> {- Ok(Engines {- legacy: self.legacy.clone(),- tree: self.tree.clone(),- })- }-- fn placement(&self, _: &Config) -> MemoryResult<Placement> {- Ok(Placement {- layout: MemoryLayout::new(Namespace::ROOT)- .map_err(|e| MemoryError::invalid(e.to_string()))?,- chat_node: "ws:main".parse().unwrap(),- flows: FlowPlacement::WithRoot,- })- }-- fn is_switched(&self, _: &Config) -> bool {- self.switched.load(Ordering::SeqCst)- }-- fn switch(&self, _: &Config) -> MemoryResult<()> {- if let Some(item) = self.racing_write.lock().unwrap().take() {- // Synchronous on purpose: the reference engine stores in memory.- futures::executor::block_on(self.legacy.store(item)).unwrap();- }- self.switched.store(true, Ordering::SeqCst);- Ok(())- }-- async fn free_now(&self, _: &Config) -> bool {- let left = self.free_for.fetch_sub(1, Ordering::SeqCst);- self.free.load(Ordering::SeqCst) && left > 0- }-- fn shared_legacy(&self, _: &Config) -> bool {- self.shared- }-}+use crate::memory::layout_migration::test_host::{count, fact, FakeHost};async fn go(config: &Config, host: &FakeHost, trigger: Trigger) -> Outcome {run(config, host, trigger, || async { false })diff --git a/crates/openhuman-core/src/memory/layout_migration/mod.rs b/crates/openhuman-core/src/memory/layout_migration/mod.rsindex 9b610400a6..eed71d1703 100644--- a/crates/openhuman-core/src/memory/layout_migration/mod.rs+++ b/crates/openhuman-core/src/memory/layout_migration/mod.rs@@ -17,11 +17,16 @@ pub mod copy;pub mod host;pub mod job;pub mod map;+pub mod service;pub mod state;+#[cfg(test)]+mod test_host;+pub use cleanup::cleanup;pub use copy::{copy, legacy_present, Engines};pub use host::LayoutHost;pub use job::{run, Outcome, Trigger};pub use map::{FlowPlacement, Placement};+pub use service::{retry, scan, start, status, tick, MigrationStatus, ScanView};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.rsnew file mode 100644index 0000000000..9c7cb2207b--- /dev/null+++ b/crates/openhuman-core/src/memory/layout_migration/service.rs@@ -0,0 +1,207 @@+//! The migration as a service: what the RPCs and the background job call.+//!+//! - [`scan`]: whether there is anything to move (the UI shows nothing when+//! there is not).+//! - [`start`]: runs the migration in the background; at most one run per+//! workspace at a time.+//! - [`status`]: its progress, with a run the app quit in the middle of+//! reported as interrupted.+//! - [`retry`]: puts the items that could not be moved back in line.+//! - [`tick`]: memory's background job, every few minutes. It starts or+//! resumes an automatic run, which itself waits for a free period (and,+//! on a shared legacy tree, for the user's consent).++use std::collections::HashSet;+use std::path::PathBuf;+use std::sync::{Arc, LazyLock, Mutex, PoisonError};++use serde::Serialize;++use super::copy::legacy_present;+use super::host::LayoutHost;+use super::job::{run, Trigger};+use super::state::{self, MigrationState, Phase};+use crate::config::Config;+use crate::memory::error::{MemoryError, MemoryResult};++/// Workspaces with a migration running now.+static RUNNING: LazyLock<Mutex<HashSet<PathBuf>>> = LazyLock::new(|| Mutex::new(HashSet::new()));++/// What [`scan`] found.+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]+pub struct ScanView {+ /// There is legacy memory still to move.+ pub needed: bool,+ /// The legacy tree may be shared with other accounts, so moving it needs+ /// the user's consent.+ pub shared: bool,+}++/// [`status`]'s answer.+#[derive(Debug, Clone, PartialEq, Serialize)]+pub struct MigrationStatus {+ /// The saved progress.+ pub state: MigrationState,+ /// A run is going now.+ pub running: bool,+ /// The app stopped in the middle of a run; it resumes on its own, or the+ /// user starts it again.+ pub interrupted: bool,+}++/// Whether `config`'s account has legacy memory to move.+///+/// # Errors+///+/// When the state cannot be read, the engines cannot be bound, or the legacy+/// tree cannot be read.+pub async fn scan(config: &Config, host: &dyn LayoutHost) -> MemoryResult<ScanView> {+ let state = state::load(&config.workspace_dir)?;+ let shared = host.shared_legacy(config);+ let needed = match state.phase {+ Phase::Cleaned => false,+ Phase::Idle if !state.switched => {+ let engines = host.engines(config)?;+ legacy_present(&*engines.legacy).await?+ }+ _ => true,+ };+ Ok(ScanView { needed, shared })+}++/// The migration's progress for `config`'s workspace.+///+/// # Errors+///+/// When the state file cannot be read.+pub fn status(config: &Config) -> MemoryResult<MigrationStatus> {+ let state = state::load(&config.workspace_dir)?;+ let running = is_running(config);+ let interrupted = !running && matches!(state.phase, Phase::Copying | Phase::Cleaning);+ Ok(MigrationStatus {+ state,+ running,+ interrupted,+ })+}++fn is_running(config: &Config) -> bool {+ RUNNING+ .lock()+ .unwrap_or_else(PoisonError::into_inner)+ .contains(&config.workspace_dir)+}++/// Releases the workspace's claim when the run ends, however it ends.+struct Claim(PathBuf);++impl Drop for Claim {+ fn drop(&mut self) {+ RUNNING+ .lock()+ .unwrap_or_else(PoisonError::into_inner)+ .remove(&self.0);+ }+}++/// Starts a run in the background. Returns `false`, starting nothing, when+/// one is already running for this workspace.+pub fn start(+ config: Config,+ host: Arc<dyn LayoutHost>,+ trigger: Trigger,+ paused: Arc<dyn Fn() -> bool + Send + Sync>,+) -> bool {+ let workspace = config.workspace_dir.clone();+ if !RUNNING+ .lock()+ .unwrap_or_else(PoisonError::into_inner)+ .insert(workspace.clone())+ {+ return false;+ }+ let claim = Claim(workspace);+ tokio::spawn(async move {+ let _claim = claim;+ let outcome = run(&config, host.as_ref(), trigger, || {+ let paused = paused();+ async move { paused }+ })+ .await;+ match outcome {+ Ok(outcome) => {+ tracing::info!(?outcome, "[memory:layout_migration] run ended");+ }+ Err(error) => {+ tracing::warn!(code = error.code(), "[memory:layout_migration] run failed");+ record_failure(&config, &error);+ }+ }+ });+ true+}++/// Saves why a run stopped on an error, so the status shows it.+fn record_failure(config: &Config, error: &MemoryError) {+ if let Ok(mut state) = state::load(&config.workspace_dir) {+ state.phase = Phase::Paused;+ state.error = Some(error.to_string());+ if let Err(save) = state::save(&config.workspace_dir, &state) {+ tracing::warn!(+ code = save.code(),+ "[memory:layout_migration] state not saved"+ );+ }+ }+}++/// Puts the items that could not be moved back in line: the next run copies+/// again from the start (what was copied replays) and cleans up again.+///+/// # Errors+///+/// When the state cannot be read or saved, or a run is going now.+pub fn retry(config: &Config) -> MemoryResult<MigrationState> {+ if is_running(config) {+ return Err(MemoryError::invalid("the migration is running"));+ }+ let mut state = state::load(&config.workspace_dir)?;+ state.failures.clear();+ state.incomplete.clear();+ state.cursor = None;+ state.error = None;+ if state.switched {+ state.caught_up = false;+ state.cleaning = false;+ }+ if state.phase != Phase::Idle {+ state.phase = Phase::Paused;+ }+ state::save(&config.workspace_dir, &state)?;+ Ok(state)+}++/// Memory's background job: starts or resumes an automatic run unless the+/// migration is done or already running. Returns whether one started.+pub fn tick(+ config: &Config,+ host: Arc<dyn LayoutHost>,+ paused: Arc<dyn Fn() -> bool + Send + Sync>,+) -> bool {+ match state::load(&config.workspace_dir) {+ Ok(state) if state.phase == Phase::Cleaned => false,+ Ok(_) if paused() || is_running(config) => false,+ Ok(_) => start(config.clone(), host, Trigger::Auto, paused),+ Err(error) => {+ tracing::warn!(+ code = error.code(),+ "[memory:layout_migration] state unreadable"+ );+ false+ }+ }+}++#[cfg(test)]+#[path = "service_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/memory/layout_migration/service_tests.rs b/crates/openhuman-core/src/memory/layout_migration/service_tests.rsnew file mode 100644index 0000000000..eff131ae66--- /dev/null+++ b/crates/openhuman-core/src/memory/layout_migration/service_tests.rs@@ -0,0 +1,112 @@+use std::sync::atomic::Ordering;+use std::sync::Arc;++use tinymemory_api::MemoryEngine;++use super::*;+use crate::memory::layout_migration::test_host::{count, fact, FakeHost};++fn never() -> Arc<dyn Fn() -> bool + Send + Sync> {+ Arc::new(|| false)+}++/// Waits (by yielding, not by the clock) for the workspace's run to end.+async fn settle(config: &Config) {+ for _ in 0..100_000 {+ if !is_running(config) {+ return;+ }+ tokio::task::yield_now().await;+ }+ panic!("the run did not end");+}++#[tokio::test]+async fn scan_finds_legacy_memory_and_nothing_after_the_move() {+ let tmp = tempfile::tempdir().unwrap();+ let config = crate::memory::test_fixtures::config_in(&tmp);+ let host = Arc::new(FakeHost::with(3).await);+ assert_eq!(+ scan(&config, host.as_ref()).await.unwrap(),+ ScanView {+ needed: true,+ shared: false+ }+ );+ assert!(start(config.clone(), host.clone(), Trigger::Auto, never()));+ settle(&config).await;+ assert!(!scan(&config, host.as_ref()).await.unwrap().needed);+ assert_eq!(status(&config).unwrap().state.phase, Phase::Cleaned);+}++#[tokio::test]+async fn nothing_to_move_shows_nothing() {+ let tmp = tempfile::tempdir().unwrap();+ let config = crate::memory::test_fixtures::config_in(&tmp);+ let host = FakeHost::with(0).await;+ assert!(!scan(&config, &host).await.unwrap().needed);+}++#[tokio::test]+async fn one_run_per_workspace_at_a_time() {+ let tmp = tempfile::tempdir().unwrap();+ let config = crate::memory::test_fixtures::config_in(&tmp);+ let host = Arc::new(FakeHost::with(200).await);+ assert!(start(config.clone(), host.clone(), Trigger::Auto, never()));+ assert!(+ !start(config.clone(), host.clone(), Trigger::Auto, never()),+ "a second start while one runs starts nothing"+ );+ settle(&config).await;+ assert_eq!(count(host.tree.as_ref()).await, 200);+}++#[tokio::test]+async fn a_stopped_run_reads_as_interrupted_and_a_tick_resumes_it() {+ let tmp = tempfile::tempdir().unwrap();+ let config = crate::memory::test_fixtures::config_in(&tmp);+ let host = Arc::new(FakeHost::with(120).await);+ let mut stopped = state::load(&config.workspace_dir).unwrap();+ stopped.phase = Phase::Copying;+ state::save(&config.workspace_dir, &stopped).unwrap();+ assert!(status(&config).unwrap().interrupted);++ assert!(tick(&config, host.clone(), never()));+ settle(&config).await;+ assert_eq!(status(&config).unwrap().state.phase, Phase::Cleaned);+ assert!(!tick(&config, host, never()), "nothing left to do");+}++#[tokio::test]+async fn a_tick_starts_nothing_while_background_work_is_paused() {+ let tmp = tempfile::tempdir().unwrap();+ let config = crate::memory::test_fixtures::config_in(&tmp);+ let host = Arc::new(FakeHost::with(3).await);+ assert!(!tick(&config, host.clone(), Arc::new(|| true)));+ assert_eq!(count(host.tree.as_ref()).await, 0);+}++#[tokio::test]+async fn retry_puts_a_lost_copy_back_in_line() {+ let tmp = tempfile::tempdir().unwrap();+ let config = crate::memory::test_fixtures::config_in(&tmp);+ let host = Arc::new(FakeHost::with(4).await);+ host.free.store(true, Ordering::SeqCst);+ assert!(start(config.clone(), host.clone(), Trigger::Auto, never()));+ settle(&config).await;+ assert_eq!(status(&config).unwrap().state.phase, Phase::Cleaned);++ // A legacy item the move did not reach (written after cleanup).+ host.legacy.store(fact("late")).await.unwrap();+ let state = retry(&config).unwrap();+ assert!(!state.caught_up && !state.cleaning);+ assert!(start(+ config.clone(),+ host.clone(),+ Trigger::Manual { takeover: false },+ never()+ ));+ settle(&config).await;+ assert_eq!(count(host.tree.as_ref()).await, 5);+ assert_eq!(count(host.legacy.as_ref()).await, 0);+}diff --git a/crates/openhuman-core/src/memory/layout_migration/test_host.rs b/crates/openhuman-core/src/memory/layout_migration/test_host.rsnew file mode 100644index 0000000000..c90ca18087--- /dev/null+++ b/crates/openhuman-core/src/memory/layout_migration/test_host.rs@@ -0,0 +1,107 @@+//! A host over two in-memory engines, for the migration's tests.++use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};+use std::sync::{Arc, Mutex};++use tinymemory_api::conformance::ReferenceEngine;+use tinymemory_api::{+ LearningKind, ListRequest, MemoryEngine, MemoryMeta, MetaFilter, Namespace, StoreItem,+};+use tinymemory_tools::MemoryLayout;++use super::copy::Engines;+use super::host::LayoutHost;+use super::map::{FlowPlacement, Placement};+use crate::config::Config;+use crate::memory::error::{MemoryError, MemoryResult};++/// Two in-memory engines and the switches a real host keeps.+pub(crate) struct FakeHost {+ pub(crate) legacy: Arc<ReferenceEngine>,+ pub(crate) tree: Arc<ReferenceEngine>,+ pub(crate) switched: AtomicBool,+ pub(crate) free: AtomicBool,+ pub(crate) shared: bool,+ /// Asks for free_now: after this many, moving stops being free.+ pub(crate) free_for: AtomicUsize,+ /// Written to the legacy tree as the switch happens (a turn racing it).+ pub(crate) racing_write: Mutex<Option<StoreItem>>,+}++impl FakeHost {+ pub(crate) async fn with(learnings: usize) -> Self {+ let legacy = Arc::new(ReferenceEngine::new());+ for i in 0..learnings {+ legacy.store(fact(&format!("fact {i}"))).await.unwrap();+ }+ Self {+ legacy,+ tree: Arc::new(ReferenceEngine::new()),+ switched: AtomicBool::new(false),+ free: AtomicBool::new(true),+ shared: false,+ free_for: AtomicUsize::new(usize::MAX),+ racing_write: Mutex::new(None),+ }+ }+}++pub(crate) fn fact(text: &str) -> StoreItem {+ StoreItem::learning(text, LearningKind::Fact, 0.5, MemoryMeta::default())+}++pub(crate) async fn count(engine: &dyn MemoryEngine) -> usize {+ let mut total = 0;+ let mut cursor = None;+ loop {+ let mut request = ListRequest::new(MetaFilter::default(), 100);+ request.cursor = cursor;+ let page = engine.list(request).await.unwrap();+ total += page.items.len();+ match page.next_cursor {+ Some(next) => cursor = Some(next),+ None => return total,+ }+ }+}++#[async_trait::async_trait]+impl LayoutHost for FakeHost {+ fn engines(&self, _: &Config) -> MemoryResult<Engines> {+ Ok(Engines {+ legacy: self.legacy.clone(),+ tree: self.tree.clone(),+ })+ }++ fn placement(&self, _: &Config) -> MemoryResult<Placement> {+ Ok(Placement {+ layout: MemoryLayout::new(Namespace::ROOT)+ .map_err(|e| MemoryError::invalid(e.to_string()))?,+ chat_node: "ws:main".parse().unwrap(),+ flows: FlowPlacement::WithRoot,+ })+ }++ fn is_switched(&self, _: &Config) -> bool {+ self.switched.load(Ordering::SeqCst)+ }++ fn switch(&self, _: &Config) -> MemoryResult<()> {+ if let Some(item) = self.racing_write.lock().unwrap().take() {+ // Synchronous on purpose: the reference engine stores in memory.+ futures::executor::block_on(self.legacy.store(item)).unwrap();+ }+ self.switched.store(true, Ordering::SeqCst);+ Ok(())+ }++ async fn free_now(&self, _: &Config) -> bool {+ let left = self.free_for.fetch_sub(1, Ordering::SeqCst);+ self.free.load(Ordering::SeqCst) && left > 0+ }++ fn shared_legacy(&self, _: &Config) -> bool {+ self.shared+ }+}