Skip to content

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

fix(storage): make rebind testable and fail on directory errors

Steven Enamakelaacc83f8597b
diff --git a/crates/openhuman-core/src/storage/rebind.rs b/crates/openhuman-core/src/storage/rebind.rs
index 5017967a2b..0ecf3b89d2 100644
--- a/crates/openhuman-core/src/storage/rebind.rs
+++ b/crates/openhuman-core/src/storage/rebind.rs
@@ -47,7 +47,25 @@ pub struct Rebound {
/// When the new backend cannot be opened or the session store refuses it. The
/// previous backend stays installed on error.
pub fn rebind(config: &Config) -> Result<Option<Rebound>> {
- let Some(current) = super::installed_url() else {
+ rebind_with(config, super::installed_url(), |url, backend| {
+ // Sessions first: no store may read one workspace's sessions beside
+ // another's documents, so both move together.
+ let rebound = crate::agent::session_store::rebind_all(&backend);
+ super::install_for_url(url, backend);
+ rebound
+ })
+}
+
+/// [`rebind`] with the URL the host installed and the installation made
+/// explicit, so the rule is testable without touching the process's slot.
+/// `install` receives the new URL and backend and returns how many session
+/// stores it moved.
+pub(crate) fn rebind_with(
+ config: &Config,
+ current: Option<String>,
+ install: impl FnOnce(&str, Arc<dyn StorageBackend>) -> usize,
+) -> Result<Option<Rebound>> {
+ let Some(current) = current else {
return Ok(None);
};
let Some(next) = super::configured_url(config) else {
@@ -65,18 +83,16 @@ pub fn rebind(config: &Config) -> Result<Option<Rebound>> {
workspace = %config.workspace_dir.display(),
"[storage] the workspace moved; reopening the storage backend"
);
- if let Some(parent) = config.workspace_dir.join(super::config::DEFAULT_DIR).parent() {
- std::fs::create_dir_all(parent).ok();
- }
+ std::fs::create_dir_all(config.workspace_dir.join(super::config::DEFAULT_DIR))
+ .with_context(|| format!("create the storage directory under {}", config.workspace_dir.display()))?;
let url = next.clone();
let backend = super::block_on_anyhow(async move { Ok(super::open(&url).await?) })
.with_context(|| format!("open the storage backend {redacted_to}"))?;
- let rebound = crate::agent::session_store::rebind_all(&backend);
- super::install_for_url(&next, Arc::clone(&backend));
+ let session_stores = install(&next, Arc::clone(&backend));
tracing::debug!(
target: "openhuman::storage",
- session_stores = rebound,
+ session_stores,
"[storage] backend reinstalled"
);
diff --git a/crates/openhuman-core/src/storage/rebind_tests.rs b/crates/openhuman-core/src/storage/rebind_tests.rs
new file mode 100644
index 0000000000..d7dfa2b849
--- /dev/null
+++ b/crates/openhuman-core/src/storage/rebind_tests.rs
@@ -0,0 +1,176 @@
+use super::*;
+use crate::storage::import::Outcome;
+use std::sync::Mutex;
+use tempfile::TempDir;
+
+fn config_in(dir: &TempDir) -> Config {
+ Config {
+ workspace_dir: dir.path().to_path_buf(),
+ ..Config::default()
+ }
+}
+
+/// Records what `rebind_with` installed instead of touching the process slot.
+#[derive(Default)]
+struct Installed(Mutex<Vec<(String, Arc<dyn StorageBackend>)>>);
+
+impl Installed {
+ fn install(&self) -> impl FnOnce(&str, Arc<dyn StorageBackend>) -> usize + '_ {
+ |url, backend| {
+ self.0.lock().unwrap().push((url.to_string(), backend));
+ 0
+ }
+ }
+
+ fn urls(&self) -> Vec<String> {
+ self.0.lock().unwrap().iter().map(|(url, _)| url.clone()).collect()
+ }
+}
+
+#[test]
+fn a_different_workspace_reopens_the_default_backend_there() {
+ let first = TempDir::new().unwrap();
+ let second = TempDir::new().unwrap();
+ let installed = Installed::default();
+ let current = super::super::config::default_url(first.path());
+
+ let rebound = rebind_with(&config_in(&second), Some(current), installed.install())
+ .unwrap()
+ .expect("the workspace moved");
+
+ assert_eq!(
+ installed.urls(),
+ [super::super::config::default_url(second.path())]
+ );
+ assert!(rebound.to.ends_with("/storage"), "{}", rebound.to);
+ assert!(
+ second.path().join("storage").is_dir(),
+ "the new workspace got its storage directory"
+ );
+}
+
+#[test]
+fn the_new_workspace_is_a_different_database() {
+ let first = TempDir::new().unwrap();
+ let second = TempDir::new().unwrap();
+ let installed = Installed::default();
+ let current = super::super::config::default_url(first.path());
+ rebind_with(&config_in(&second), Some(current), installed.install())
+ .unwrap()
+ .unwrap();
+ let backend = Arc::clone(&installed.0.lock().unwrap()[0].1);
+
+ // A record written for the second workspace is not in the first one's.
+ let scoped = backend.for_scope(&Scope::local()).unwrap();
+ let docs = Arc::clone(scoped.documents());
+ crate::storage::block_on(async move {
+ docs.ensure_collection(&CollectionSpec::new("probe")).await?;
+ docs.put("probe", "k", serde_json::json!({"v": 1}), Precondition::None)
+ .await
+ })
+ .unwrap();
+
+ let other = super::super::block_on_anyhow({
+ let url = super::super::config::default_url(first.path());
+ async move { Ok(super::super::open(&url).await?) }
+ })
+ .unwrap();
+ let docs = Arc::clone(other.for_scope(&Scope::local()).unwrap().documents());
+ let found = crate::storage::block_on(async move {
+ docs.ensure_collection(&CollectionSpec::new("probe")).await?;
+ docs.get("probe", "k").await
+ })
+ .unwrap();
+ assert!(found.is_none(), "the first workspace never saw the record");
+}
+
+#[test]
+fn the_legacy_files_of_the_new_workspace_are_imported() {
+ let first = TempDir::new().unwrap();
+ let second = TempDir::new().unwrap();
+ // A user who last ran an older build in `second` has a devices database.
+ let db = second.path().join("devices").join("devices.db");
+ std::fs::create_dir_all(db.parent().unwrap()).unwrap();
+ let conn = crate::storage::rusqlite::Connection::open(&db).unwrap();
+ conn.execute_batch(
+ "CREATE TABLE paired_devices (
+ channel_id TEXT PRIMARY KEY, label TEXT NOT NULL, device_pubkey TEXT NOT NULL,
+ core_session_token_hash TEXT NOT NULL, shared_secret_encrypted BLOB,
+ created_at TEXT NOT NULL, last_seen_at TEXT, revoked INTEGER NOT NULL DEFAULT 0
+ );
+ INSERT INTO paired_devices (channel_id, label, device_pubkey, core_session_token_hash, created_at)
+ VALUES ('chan-a', 'Phone', 'pk', 'hash', '2026-01-01T00:00:00+00:00');",
+ )
+ .unwrap();
+ drop(conn);
+ let installed = Installed::default();
+ let current = super::super::config::default_url(first.path());
+
+ let rebound = rebind_with(&config_in(&second), Some(current), installed.install())
+ .unwrap()
+ .unwrap();
+
+ let devices = rebound
+ .imports
+ .iter()
+ .find(|report| report.domain == "devices")
+ .expect("the devices importer ran");
+ assert!(matches!(
+ devices.outcome,
+ Ok(Outcome::Imported { found: 1, written: 1 })
+ ));
+}
+
+#[test]
+fn an_explicit_url_is_never_replaced() {
+ let first = TempDir::new().unwrap();
+ let second = TempDir::new().unwrap();
+ let installed = Installed::default();
+ let mut config = config_in(&second);
+ config.storage.url = Some("memory".into());
+
+ // The host installed `memory` from the same explicit URL: nothing moved.
+ let rebound = rebind_with(&config, Some("memory".into()), installed.install()).unwrap();
+
+ assert!(rebound.is_none());
+ assert!(installed.urls().is_empty());
+ let _ = first;
+}
+
+#[test]
+fn the_same_workspace_is_left_alone() {
+ let dir = TempDir::new().unwrap();
+ let installed = Installed::default();
+ let current = super::super::config::default_url(dir.path());
+
+ let rebound = rebind_with(&config_in(&dir), Some(current), installed.install()).unwrap();
+
+ assert!(rebound.is_none());
+ assert!(installed.urls().is_empty());
+}
+
+#[test]
+fn a_backend_installed_without_a_url_is_never_rebound() {
+ let dir = TempDir::new().unwrap();
+ let installed = Installed::default();
+
+ let rebound = rebind_with(&config_in(&dir), None, installed.install()).unwrap();
+
+ assert!(rebound.is_none());
+ assert!(installed.urls().is_empty());
+}
+
+#[test]
+fn a_backend_that_cannot_be_opened_keeps_the_previous_one() {
+ let first = TempDir::new().unwrap();
+ let second = TempDir::new().unwrap();
+ // The storage directory cannot be created: a file is in the way.
+ std::fs::write(second.path().join("storage"), b"in the way").unwrap();
+ let installed = Installed::default();
+ let current = super::super::config::default_url(first.path());
+
+ let error = rebind_with(&config_in(&second), Some(current), installed.install());
+
+ assert!(error.is_err());
+ assert!(installed.urls().is_empty(), "nothing was installed");
+}