Skip to content

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

feat(memory): one account takes a shared legacy tree

M3gA-Mind3d04c7e6ec3c
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 24dc4b0c5f..9ce593661f 100644
--- a/crates/openhuman-core/src/memory/layout_migration/app_host.rs
+++ b/crates/openhuman-core/src/memory/layout_migration/app_host.rs
@@ -4,10 +4,11 @@
use async_trait::async_trait;
+use super::claim::ClaimKey;
use super::copy::Engines;
use super::host::LayoutHost;
use super::map::{FlowPlacement, Placement};
-use crate::config::Config;
+use crate::config::{Config, MemoryLayoutMode};
use crate::memory::engine::{self, CORTEXDB_ENGINE};
use crate::memory::error::{MemoryError, MemoryResult};
use crate::memory::scope::{self, MemoryIdentity};
@@ -18,9 +19,7 @@ pub struct AppHost;
#[async_trait]
impl LayoutHost for AppHost {
fn engines(&self, config: &Config) -> MemoryResult<Engines> {
- let root = scope::user_root(config).ok_or_else(|| {
- MemoryError::Off("sign in to move memory into its own layout".to_string())
- })?;
+ let root = signed_in_root(config)?;
Ok(Engines {
legacy: engine::bind_with_root(config, None)?.engine,
tree: engine::bind_with_root(config, Some(&root))?.engine,
@@ -28,7 +27,11 @@ impl LayoutHost for AppHost {
}
fn placement(&self, config: &Config) -> MemoryResult<Placement> {
- let layout = MemoryIdentity::root().resolve(config).layout;
+ // The v3 layout, whatever the setting says: the copy runs before the
+ // switch.
+ let mut v3 = config.clone();
+ v3.memory.layout = MemoryLayoutMode::V3;
+ let layout = MemoryIdentity::root().resolve(&v3).layout;
let chat_node = scope::chat_node(&layout);
Ok(Placement {
layout,
@@ -49,13 +52,33 @@ impl LayoutHost for AppHost {
crate::memory::billing::free_period_active(config).await
}
- fn shared_legacy(&self, config: &Config) -> bool {
+ fn legacy_claim(&self, config: &Config) -> MemoryResult<Option<ClaimKey>> {
// A self-hosted key is the operator's: every local account using it
// shares one legacy tree. The hosted engine is one tenant per person.
- config.memory.engine.trim() == CORTEXDB_ENGINE
+ if config.memory.engine.trim() != CORTEXDB_ENGINE {
+ return Ok(None);
+ }
+ let owner = signed_in_root(config)?;
+ // `<app>/users/<id>/config.toml`: the app directory every account shares.
+ let app_dir = config
+ .config_path
+ .parent()
+ .and_then(std::path::Path::parent)
+ .and_then(std::path::Path::parent)
+ .ok_or_else(signed_out)?;
+ let endpoint = engine::bind_with_root(config, None)?.endpoint;
+ Ok(Some(ClaimKey::new(app_dir, &endpoint, &owner)))
}
}
+fn signed_in_root(config: &Config) -> MemoryResult<String> {
+ scope::user_root(config).ok_or_else(signed_out)
+}
+
+fn signed_out() -> MemoryError {
+ MemoryError::Off("sign in to move memory into its own layout".to_string())
+}
+
#[cfg(test)]
#[path = "app_host_tests.rs"]
mod tests;
diff --git a/crates/openhuman-core/src/memory/layout_migration/app_host_tests.rs b/crates/openhuman-core/src/memory/layout_migration/app_host_tests.rs
index 2c44e0e1ec..68e823bda8 100644
--- a/crates/openhuman-core/src/memory/layout_migration/app_host_tests.rs
+++ b/crates/openhuman-core/src/memory/layout_migration/app_host_tests.rs
@@ -45,3 +45,59 @@ async fn binds_the_legacy_tree_and_the_users_own() {
assert!(placement.chat_node.to_string().ends_with("ws:main"));
assert!(matches!(placement.flows, FlowPlacement::WithRoot));
}
+
+#[test]
+fn places_into_the_v3_layout_before_the_switch() {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = signed_in(&tmp);
+ assert!(!crate::memory::scope::layout_is_v3(&config));
+ let mut v3 = config.clone();
+ v3.memory.layout = crate::config::MemoryLayoutMode::V3;
+ let legacy = crate::memory::scope::MemoryIdentity::root()
+ .resolve(&config)
+ .layout;
+ let placement = AppHost.placement(&config).unwrap();
+ assert_ne!(placement.layout, legacy, "chats are pooled at ws:main");
+ assert_eq!(
+ placement.layout.conversations("a").unwrap(),
+ placement.chat_node
+ );
+}
+
+#[test]
+fn every_account_on_a_self_hosted_engine_shares_one_claim() {
+ let tmp = tempfile::tempdir().unwrap();
+ let mut a = signed_in(&tmp);
+ a.memory.engine = CORTEXDB_ENGINE.to_string();
+ let mut b = a.clone();
+ b.config_path = tmp
+ .path()
+ .join("users")
+ .join("fedcba9876543210fedcba98")
+ .join("config.toml");
+ for config in [&a, &b] {
+ install_test_engine_for_root(
+ &config.workspace_dir,
+ None,
+ Arc::new(ReferenceEngine::new()),
+ );
+ }
+ let key_a = AppHost.legacy_claim(&a).unwrap().unwrap();
+ let key_b = AppHost.legacy_claim(&b).unwrap().unwrap();
+ assert_eq!(key_a.marker, key_b.marker);
+ assert_eq!(
+ key_a
+ .marker
+ .parent()
+ .unwrap()
+ .parent()
+ .unwrap()
+ .parent()
+ .unwrap(),
+ tmp.path()
+ );
+ assert_eq!(key_a.owner, format!("user:{ACCOUNT}"));
+
+ let hosted = signed_in(&tmp);
+ assert!(AppHost.legacy_claim(&hosted).unwrap().is_none());
+}
diff --git a/crates/openhuman-core/src/memory/layout_migration/claim.rs b/crates/openhuman-core/src/memory/layout_migration/claim.rs
new file mode 100644
index 0000000000..5a88d94e0c
--- /dev/null
+++ b/crates/openhuman-core/src/memory/layout_migration/claim.rs
@@ -0,0 +1,133 @@
+//! Which account on this machine takes a shared legacy tree.
+//!
+//! With a self-hosted CortexDB every account on the machine reaches the same
+//! `app:tinymemory/…` tree, so only one of them may move it into its own
+//! per-user tree. The first to start a consented move claims it with a marker
+//! in the app directory shared by all accounts,
+//! `<app>/memory/legacy_claims/<digest of the endpoint>.json`; other accounts
+//! then have nothing to move. The marker is created with a hard link, which
+//! fails when it exists, so two accounts racing cannot both claim the tree.
+
+use std::path::{Path, PathBuf};
+
+use serde::{Deserialize, Serialize};
+use sha2::Digest;
+
+use crate::memory::error::{MemoryError, MemoryResult};
+
+/// Where a legacy tree's marker lives and who would own it.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct ClaimKey {
+ /// The marker file.
+ pub marker: PathBuf,
+ /// The claiming account's scope root (`user:<id>`).
+ pub owner: String,
+ /// The engine endpoint the tree lives on, normalised.
+ pub endpoint: String,
+}
+
+impl ClaimKey {
+ /// The key for the tree at `endpoint`, below the shared app directory.
+ #[must_use]
+ pub fn new(app_dir: &Path, endpoint: &str, owner: &str) -> Self {
+ let endpoint = normalize(endpoint);
+ let digest: String = sha2::Sha256::digest(endpoint.as_bytes())
+ .iter()
+ .map(|byte| format!("{byte:02x}"))
+ .collect();
+ Self {
+ marker: app_dir
+ .join("memory")
+ .join("legacy_claims")
+ .join(format!("{digest}.json")),
+ owner: owner.to_string(),
+ endpoint,
+ }
+ }
+}
+
+#[derive(Serialize, Deserialize)]
+struct Marker {
+ endpoint: String,
+ owner: String,
+}
+
+/// One spelling per endpoint: trimmed, scheme and host lowercased, default
+/// port and trailing `/` dropped.
+fn normalize(endpoint: &str) -> String {
+ let endpoint = endpoint.trim();
+ match url::Url::parse(endpoint) {
+ Ok(url) => url.as_str().trim_end_matches('/').to_string(),
+ Err(_) => endpoint.trim_end_matches('/').to_ascii_lowercase(),
+ }
+}
+
+/// The account that claimed the tree, if any.
+///
+/// # Errors
+///
+/// When the marker exists but cannot be read.
+fn owner(key: &ClaimKey) -> MemoryResult<Option<String>> {
+ match std::fs::read(&key.marker) {
+ Ok(bytes) => serde_json::from_slice::<Marker>(&bytes)
+ .map(|marker| Some(marker.owner))
+ .map_err(|error| unreadable(&error)),
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
+ Err(error) => Err(unreadable(&error)),
+ }
+}
+
+/// Whether another account claimed the tree.
+///
+/// # Errors
+///
+/// When the marker exists but cannot be read.
+pub fn held_by_other(key: &ClaimKey) -> MemoryResult<bool> {
+ Ok(owner(key)?.is_some_and(|owner| owner != key.owner))
+}
+
+/// Claims the tree for `key.owner`: `true` when it is now (or already was)
+/// theirs, `false` when another account holds it.
+///
+/// # Errors
+///
+/// When the marker cannot be read or written.
+pub fn take(key: &ClaimKey) -> MemoryResult<bool> {
+ if let Some(owner) = owner(key)? {
+ return Ok(owner == key.owner);
+ }
+ let write = || -> std::io::Result<()> {
+ if let Some(dir) = key.marker.parent() {
+ std::fs::create_dir_all(dir)?;
+ }
+ let temp = tempfile::NamedTempFile::new_in(key.marker.parent().unwrap_or(Path::new(".")))?;
+ let marker = Marker {
+ endpoint: key.endpoint.clone(),
+ owner: key.owner.clone(),
+ };
+ serde_json::to_writer(temp.as_file(), &marker).map_err(std::io::Error::other)?;
+ temp.as_file().sync_all()?;
+ // Fails when the marker exists: never replaces another's claim.
+ std::fs::hard_link(temp.path(), &key.marker)
+ };
+ match write() {
+ Ok(()) => {
+ tracing::info!("[memory:layout_migration] legacy tree claimed");
+ Ok(true)
+ }
+ Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
+ Ok(owner(key)?.is_some_and(|owner| owner == key.owner))
+ }
+ Err(error) => Err(MemoryError::Engine(format!(
+ "legacy tree claim not saved: {error}"
+ ))),
+ }
+}
+
+fn unreadable(error: &dyn std::fmt::Display) -> MemoryError {
+ MemoryError::Engine(format!("legacy tree claim unreadable: {error}"))
+}
+
+#[cfg(test)]
+#[path = "claim_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/memory/layout_migration/claim_tests.rs b/crates/openhuman-core/src/memory/layout_migration/claim_tests.rs
new file mode 100644
index 0000000000..f9edb11d48
--- /dev/null
+++ b/crates/openhuman-core/src/memory/layout_migration/claim_tests.rs
@@ -0,0 +1,44 @@
+use super::*;
+
+const LOCAL: &str = "http://127.0.0.1:3141";
+
+#[test]
+fn one_endpoint_has_one_marker_however_it_is_spelled() {
+ let dir = Path::new("/app");
+ let key = ClaimKey::new(dir, LOCAL, "user:a");
+ for spelling in [
+ " http://127.0.0.1:3141/ ",
+ "HTTP://127.0.0.1:3141",
+ "http://127.0.0.1:3141/",
+ ] {
+ assert_eq!(ClaimKey::new(dir, spelling, "user:b").marker, key.marker);
+ }
+ assert_ne!(
+ ClaimKey::new(dir, "http://127.0.0.1:3142", "user:a").marker,
+ key.marker
+ );
+}
+
+#[test]
+fn the_first_account_takes_the_tree_and_keeps_it() {
+ let tmp = tempfile::tempdir().unwrap();
+ let a = ClaimKey::new(tmp.path(), LOCAL, "user:a");
+ let b = ClaimKey::new(tmp.path(), LOCAL, "user:b");
+ assert!(!held_by_other(&a).unwrap());
+ assert!(take(&a).unwrap());
+ assert!(take(&a).unwrap(), "taking again is a no-op");
+ assert!(!held_by_other(&a).unwrap());
+ assert!(held_by_other(&b).unwrap());
+ assert!(!take(&b).unwrap(), "never replaces another's claim");
+ assert!(!held_by_other(&a).unwrap());
+}
+
+#[test]
+fn an_unreadable_marker_is_an_error_not_a_free_tree() {
+ let tmp = tempfile::tempdir().unwrap();
+ let a = ClaimKey::new(tmp.path(), LOCAL, "user:a");
+ std::fs::create_dir_all(a.marker.parent().unwrap()).unwrap();
+ std::fs::write(&a.marker, b"{torn").unwrap();
+ assert!(held_by_other(&a).is_err());
+ assert!(take(&a).is_err());
+}
diff --git a/crates/openhuman-core/src/memory/layout_migration/host.rs b/crates/openhuman-core/src/memory/layout_migration/host.rs
index fab9418eec..a0c1b6c71e 100644
--- a/crates/openhuman-core/src/memory/layout_migration/host.rs
+++ b/crates/openhuman-core/src/memory/layout_migration/host.rs
@@ -7,6 +7,7 @@
use async_trait::async_trait;
+use super::claim::ClaimKey;
use super::copy::Engines;
use super::map::Placement;
use crate::config::Config;
@@ -47,7 +48,12 @@ pub trait LayoutHost: Send + Sync {
/// the hosted engine).
async fn free_now(&self, config: &Config) -> bool;
- /// Whether the legacy tree may be shared with other accounts on this
- /// machine (a self-hosted key), so taking it needs the user's consent.
- fn shared_legacy(&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 c28ab5c4d6..ae9f212a4f 100644
--- a/crates/openhuman-core/src/memory/layout_migration/job.rs
+++ b/crates/openhuman-core/src/memory/layout_migration/job.rs
@@ -18,6 +18,7 @@
//! 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 super::cleanup::cleanup;
use super::copy::{copy, legacy_present};
use super::host::LayoutHost;
@@ -46,6 +47,9 @@ pub enum Outcome {
/// Not started: the legacy tree may be shared, and the user has not
/// agreed to take it.
NeedsTakeover,
+ /// Not started: another account on this machine took the shared legacy
+ /// tree.
+ ClaimedElsewhere,
/// Not started or not continued automatically: moving is not free now.
NotFree,
/// Stopped where it was; [`run`] again continues.
@@ -83,8 +87,16 @@ where
state.takeover = true;
state::save(dir, &state)?;
}
- if host.shared_legacy(config) && !state.takeover {
- return Ok(Outcome::NeedsTakeover);
+ if let Some(key) = host.legacy_claim(config)? {
+ if claim::held_by_other(&key)? {
+ return Ok(Outcome::ClaimedElsewhere);
+ }
+ if !state.takeover {
+ return Ok(Outcome::NeedsTakeover);
+ }
+ if !claim::take(&key)? {
+ return Ok(Outcome::ClaimedElsewhere);
+ }
}
let auto = trigger == Trigger::Auto;
if auto && !host.free_now(config).await {
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 f14cf3d489..8b7c82f03c 100644
--- a/crates/openhuman-core/src/memory/layout_migration/job_tests.rs
+++ b/crates/openhuman-core/src/memory/layout_migration/job_tests.rs
@@ -3,6 +3,7 @@ use std::sync::atomic::Ordering;
use tinymemory_api::{ListRequest, MemoryEngine, MetaFilter};
use super::*;
+use crate::memory::layout_migration::claim::ClaimKey;
use crate::memory::layout_migration::test_host::{count, fact, FakeHost};
async fn go(config: &Config, host: &FakeHost, trigger: Trigger) -> Outcome {
@@ -49,7 +50,7 @@ async fn a_shared_legacy_tree_moves_only_with_consent() {
let tmp = tempfile::tempdir().unwrap();
let config = crate::memory::test_fixtures::config_in(&tmp);
let mut host = FakeHost::with(3).await;
- host.shared = true;
+ host.claim = Some(ClaimKey::new(tmp.path(), "http://127.0.0.1:3141", "user:a"));
assert_eq!(
go(&config, &host, Trigger::Auto).await,
Outcome::NeedsTakeover
@@ -120,3 +121,29 @@ async fn a_write_racing_the_switch_is_caught_up() {
assert!(texts.iter().any(|t| t == "written as the switch happened"));
assert_eq!(count(host.legacy.as_ref()).await, 0);
}
+
+#[tokio::test]
+async fn a_tree_another_account_took_is_left_alone() {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = crate::memory::test_fixtures::config_in(&tmp);
+ let theirs = ClaimKey::new(tmp.path(), "http://127.0.0.1:3141", "user:b");
+ assert!(claim::take(&theirs).unwrap());
+ let mut host = FakeHost::with(3).await;
+ host.claim = Some(ClaimKey::new(
+ tmp.path(),
+ "http://127.0.0.1:3141/",
+ "user:a",
+ ));
+ assert_eq!(
+ go(&config, &host, Trigger::Manual { takeover: true }).await,
+ Outcome::ClaimedElsewhere
+ );
+ assert_eq!(count(&*host.legacy).await, 3, "nothing moved");
+ assert_eq!(count(&*host.tree).await, 0);
+ assert!(
+ !crate::memory::layout_migration::scan(&config, &host)
+ .await
+ .unwrap()
+ .needed
+ );
+}
diff --git a/crates/openhuman-core/src/memory/layout_migration/mod.rs b/crates/openhuman-core/src/memory/layout_migration/mod.rs
index 143646b7f7..fa80da2d38 100644
--- a/crates/openhuman-core/src/memory/layout_migration/mod.rs
+++ b/crates/openhuman-core/src/memory/layout_migration/mod.rs
@@ -13,6 +13,7 @@
//! catch-up pass, cleanup and the RPCs build on it.
pub mod app_host;
+pub mod claim;
pub mod cleanup;
pub mod copy;
pub mod host;
diff --git a/crates/openhuman-core/src/memory/layout_migration/service.rs b/crates/openhuman-core/src/memory/layout_migration/service.rs
index e497677e89..1443bfa6c8 100644
--- a/crates/openhuman-core/src/memory/layout_migration/service.rs
+++ b/crates/openhuman-core/src/memory/layout_migration/service.rs
@@ -17,6 +17,7 @@ use std::sync::{Arc, LazyLock, Mutex, PoisonError};
use serde::Serialize;
+use super::claim;
use super::copy::legacy_present;
use super::host::LayoutHost;
use super::job::{run, Trigger};
@@ -65,9 +66,16 @@ pub struct MigrationStatus {
/// 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 claim = match host.legacy_claim(config) {
+ // Memory off or signed out: nothing to show.
+ Err(MemoryError::Off(_)) => None,
+ claim => claim?,
+ };
+ let shared = claim.is_some();
let needed = match state.phase {
Phase::Cleaned => false,
+ // Another account on this machine took the shared tree.
+ Phase::Idle if claim.as_ref().map(claim::held_by_other).transpose()? == Some(true) => false,
Phase::Idle if !state.switched => match host.engines(config) {
// Memory off or signed out: nothing to show.
Err(MemoryError::Off(_)) => false,
@@ -102,10 +110,10 @@ fn is_running(config: &Config) -> bool {
.contains(&config.workspace_dir)
}
-/// Releases the workspace's claim when the run ends, however it ends.
-struct Claim(PathBuf);
+/// Releases the workspace's run slot when the run ends, however it ends.
+struct RunGuard(PathBuf);
-impl Drop for Claim {
+impl Drop for RunGuard {
fn drop(&mut self) {
RUNNING
.lock()
@@ -130,9 +138,9 @@ pub fn start(
{
return false;
}
- let claim = Claim(workspace);
+ let guard = RunGuard(workspace);
tokio::spawn(async move {
- let _claim = claim;
+ let _guard = guard;
let outcome = run(&config, host.as_ref(), trigger, || {
let paused = paused();
async move { paused }
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 7a84dddbd5..506e9f5a34 100644
--- a/crates/openhuman-core/src/memory/layout_migration/test_host.rs
+++ b/crates/openhuman-core/src/memory/layout_migration/test_host.rs
@@ -9,6 +9,7 @@ use tinymemory_api::{
};
use tinymemory_tools::MemoryLayout;
+use super::claim::ClaimKey;
use super::copy::Engines;
use super::host::LayoutHost;
use super::map::{FlowPlacement, Placement};
@@ -21,7 +22,8 @@ pub(crate) struct FakeHost {
pub(crate) tree: Arc<ReferenceEngine>,
pub(crate) switched: AtomicBool,
pub(crate) free: AtomicBool,
- pub(crate) shared: bool,
+ /// The claim when the legacy tree is shared.
+ pub(crate) claim: Option<ClaimKey>,
/// 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).
@@ -39,7 +41,7 @@ impl FakeHost {
tree: Arc::new(ReferenceEngine::new()),
switched: AtomicBool::new(false),
free: AtomicBool::new(true),
- shared: false,
+ claim: None,
free_for: AtomicUsize::new(usize::MAX),
racing_write: Mutex::new(None),
}
@@ -101,7 +103,7 @@ impl LayoutHost for FakeHost {
self.free.load(Ordering::SeqCst) && left > 0
}
- fn shared_legacy(&self, _: &Config) -> bool {
- self.shared
+ fn legacy_claim(&self, _: &Config) -> MemoryResult<Option<ClaimKey>> {
+ Ok(self.claim.clone())
}
}