Skip to content

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

chore: files changed crates/openhuman-core/src/memory/import_tests.rs,crates/openhuman-core/src/memo

Steven Enamakel2f3a2be0182f
diff --git a/crates/openhuman-core/src/memory/import_tests.rs b/crates/openhuman-core/src/memory/import_tests.rs
index 2f73ea74d9..e0276941ff 100644
--- a/crates/openhuman-core/src/memory/import_tests.rs
+++ b/crates/openhuman-core/src/memory/import_tests.rs
@@ -143,12 +143,9 @@ async fn a_live_import_blocks_migration_and_does_not_make_a_stale_migration_look
let config = config_in(&tmp);
let host = Arc::new(FakeHost::with(2, &config).await);
let workspace = config.workspace_dir.clone();
- let inserted = RUNNING
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner)
- .insert(workspace.clone());
- assert!(inserted, "the test owns a live import reservation");
- let _reservation = LiveImportReservation(workspace.clone());
+ let _reservation = crate::memory::run_slots::IMPORT
+ .try_acquire(workspace.clone())
+ .expect("the test owns a live import slot");
let mut stale = state::load(&workspace).unwrap();
stale.phase = Phase::Copying;
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 fc1c072953..e652be879d 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
@@ -5,10 +5,9 @@ use tinymemory_api::MemoryEngine;
use super::*;
use crate::memory::engine::install_test_engine_for_root;
-use crate::memory::layout_migration::claim;
-use crate::memory::layout_migration::service::scan;
+use crate::memory::layout_migration::ops::scan;
use crate::memory::layout_migration::test_host::{count, fact};
-use tinymemory_tools::layout_migration::{LayoutHost, Outcome, Trigger};
+use tinymemory_tools::layout_migration::{FsLegacyClaim, LayoutHost, Outcome, Trigger};
const ACCOUNT: &str = "0123456789abcdef01234567";
@@ -88,24 +87,14 @@ fn every_account_on_a_self_hosted_engine_shares_one_claim() {
Arc::new(ReferenceEngine::new()),
);
}
- let key_a = claim_key(&a).unwrap().unwrap();
- let key_b = claim_key(&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 key_a = claim(&a).unwrap().unwrap();
+ let key_b = claim(&b).unwrap().unwrap();
+ assert_eq!(key_a.marker_path(), key_b.marker_path());
+ assert_eq!(key_a.marker_path().parent().unwrap().parent().unwrap().parent().unwrap(), tmp.path());
+ assert_eq!(key_a.owner(), &format!("user:{ACCOUNT}"));
let hosted = signed_in(&tmp);
- assert!(claim_key(&hosted).unwrap().is_none());
+ assert!(claim(&hosted).unwrap().is_none());
}
#[tokio::test]
@@ -157,19 +146,14 @@ async fn a_shared_tree_reaches_the_module_as_a_claim() {
assert_eq!(count(&*host.engines().unwrap().tree).await, 0);
// Another account on the machine took the tree first.
- let key = claim_key(&config).unwrap().unwrap();
- let other = ClaimKey::new(
- key.marker
- .parent()
- .unwrap()
- .parent()
- .unwrap()
- .parent()
- .unwrap(),
- &key.endpoint,
+ let key = claim(&config).unwrap().unwrap();
+ let app_dir = key.marker_path().parent().unwrap().parent().unwrap().parent().unwrap();
+ let other = FsLegacyClaim::new(
+ app_dir,
+ key.endpoint(),
"user:fedcba9876543210fedcba98",
);
- assert!(claim::take(&other).unwrap());
+ assert!(other.take().unwrap());
let view = scan(&host).await.unwrap();
assert!(!view.needed && view.shared, "{view:?}");
}
@@ -198,3 +182,40 @@ fn errors_keep_their_wire_codes_across_the_module_boundary() {
assert!(matches!(back, Error::InsufficientCredits(_)));
assert!(back.is_account_wide());
}
+
+
+#[test]
+fn one_endpoint_has_one_marker_however_it_is_spelled() {
+ let dir = tempfile::tempdir().unwrap();
+ let local = "http://127.0.0.1:3141";
+ let key = FsLegacyClaim::new(dir.path(), local, "user:a");
+ for spelling in ["HTTP://127.0.0.1:3141/", " http://127.0.0.1:3141 "] {
+ assert_eq!(FsLegacyClaim::new(dir.path(), spelling, "user:b").marker_path(), key.marker_path());
+ }
+ assert_ne!(
+ FsLegacyClaim::new(dir.path(), "http://127.0.0.1:3142", "user:a").marker_path(),
+ key.marker_path()
+ );
+}
+
+#[test]
+fn the_first_account_takes_the_tree_and_keeps_it() {
+ let dir = tempfile::tempdir().unwrap();
+ let a = FsLegacyClaim::new(dir.path(), "http://127.0.0.1:3141", "user:a");
+ let b = FsLegacyClaim::new(dir.path(), "http://127.0.0.1:3141", "user:b");
+ assert!(a.take().unwrap());
+ assert!(!b.take().unwrap());
+ assert!(b.held_by_other().unwrap());
+ assert!(a.take().unwrap());
+ assert!(!a.held_by_other().unwrap());
+}
+
+#[test]
+fn an_unreadable_marker_is_an_error_not_a_free_tree() {
+ let dir = tempfile::tempdir().unwrap();
+ let claim = FsLegacyClaim::new(dir.path(), "http://127.0.0.1:3141", "user:a");
+ std::fs::create_dir_all(claim.marker_path().parent().unwrap()).unwrap();
+ std::fs::write(claim.marker_path(), b"{ torn").unwrap();
+ assert!(claim.held_by_other().is_err());
+ assert!(claim.take().is_err());
+}
diff --git a/crates/openhuman-core/src/memory/layout_migration/claim.rs b/crates/openhuman-core/src/memory/layout_migration/claim.rs
deleted file mode 100644
index 918c792b71..0000000000
--- a/crates/openhuman-core/src/memory/layout_migration/claim.rs
+++ /dev/null
@@ -1,146 +0,0 @@
-//! 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 tinymemory_tools::layout_migration::{LegacyClaim, Result as ModuleResult};
-
-use super::app_host::to_module;
-use tinymemory_api::{Error, Result};
-
-/// 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 actor (`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) -> Result<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) -> Result<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) -> Result<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(Error::Engine(format!(
- "legacy tree claim not saved: {error}"
- ))),
- }
-}
-
-impl LegacyClaim for ClaimKey {
- fn held_by_other(&self) -> ModuleResult<bool> {
- held_by_other(self).map_err(to_module)
- }
-
- fn take(&self) -> ModuleResult<bool> {
- take(self).map_err(to_module)
- }
-}
-
-fn unreadable(error: &dyn std::fmt::Display) -> Error {
- Error::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
deleted file mode 100644
index f9edb11d48..0000000000
--- a/crates/openhuman-core/src/memory/layout_migration/claim_tests.rs
+++ /dev/null
@@ -1,44 +0,0 @@
-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());
-}