Skip to content

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

feat(mcp): defer agent home purge until module close is acknowledged

Steven Enamakel43c85e844b2b
diff --git a/crates/openhuman-core/src/mcp/host.rs b/crates/openhuman-core/src/mcp/host.rs
index 60d5fdf463..427ab975d8 100644
--- a/crates/openhuman-core/src/mcp/host.rs
+++ b/crates/openhuman-core/src/mcp/host.rs
@@ -50,6 +50,21 @@ pub fn schedule_agent_close(workspace_dir: &std::path::Path, agent_id: &str) {
);
}
+/// Schedules module close followed by host-owned cleanup for this agent's
+/// scoped data directory. The directory remains reserved until both the
+/// module acknowledgment and callback succeed.
+#[cfg(feature = "mcp")]
+pub fn schedule_agent_close_with_cleanup(
+ workspace_dir: &std::path::Path,
+ agent_id: &str,
+ after_close: std::sync::Arc<dyn Fn() -> bool + Send + Sync>,
+) {
+ crate::mcp::module_client::McpConfiguredClient::schedule_agent_close_and_cleanup(
+ &workspace_dir.join("agents").join(agent_id),
+ after_close,
+ );
+}
+
/// Whether a cached agent client still awaits module cleanup acknowledgment.
#[cfg(feature = "mcp")]
pub fn agent_close_pending(workspace_dir: &std::path::Path, agent_id: &str) -> bool {
@@ -68,6 +83,16 @@ pub async fn close_agent(_workspace_dir: &std::path::Path, _agent_id: &str) -> b
#[cfg(not(feature = "mcp"))]
pub fn schedule_agent_close(_workspace_dir: &std::path::Path, _agent_id: &str) {}
+/// Runs host-owned cleanup immediately when MCP is disabled.
+#[cfg(not(feature = "mcp"))]
+pub fn schedule_agent_close_with_cleanup(
+ _workspace_dir: &std::path::Path,
+ _agent_id: &str,
+ after_close: std::sync::Arc<dyn Fn() -> bool + Send + Sync>,
+) {
+ let _ = after_close();
+}
+
/// No agent-scoped module cleanup is pending when MCP is disabled.
#[cfg(not(feature = "mcp"))]
pub fn agent_close_pending(_workspace_dir: &std::path::Path, _agent_id: &str) -> bool {
diff --git a/crates/openhuman-core/src/mcp/module_client.rs b/crates/openhuman-core/src/mcp/module_client.rs
index 8b9d1db405..a93951576f 100644
--- a/crates/openhuman-core/src/mcp/module_client.rs
+++ b/crates/openhuman-core/src/mcp/module_client.rs
@@ -35,6 +35,15 @@ const MODULE: &str = "tinymcp";
const TRANSITION_TIMEOUT: Duration = Duration::from_secs(30);
const TRANSITION_POLL_INTERVAL: Duration = Duration::from_millis(20);
static CLIENTS: OnceLock<Mutex<HashMap<PathBuf, Arc<McpConfiguredClient>>>> = OnceLock::new();
+type CleanupAction = Arc<dyn Fn() -> bool + Send + Sync>;
+
+#[derive(Default)]
+struct CleanupReservation {
+ after_close: Mutex<Option<CleanupAction>>,
+}
+
+static CLEANUP_RESERVATIONS: OnceLock<Mutex<HashMap<PathBuf, Arc<CleanupReservation>>>> =
+ OnceLock::new();
static SHUTDOWN_REGISTERED: AtomicBool = AtomicBool::new(false);
static SHUTTING_DOWN: AtomicBool = AtomicBool::new(false);
@@ -251,10 +260,18 @@ impl McpConfiguredClient {
}
let data_dir = crate::core::runtime::agent_scope_dir(config);
+ if Self::cleanup_pending(&data_dir) {
+ return Err(ModuleCallError::Unavailable);
+ }
let clients = CLIENTS.get_or_init(|| Mutex::new(HashMap::new()));
let mut clients = clients
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
+ // The cleanup reservation can be installed after the first check but
+ // before this cache lock is acquired. Recheck before creating a client.
+ if Self::cleanup_pending(&data_dir) {
+ return Err(ModuleCallError::Unavailable);
+ }
if let Some(client) = clients.get(&data_dir) {
if client.retiring.load(Ordering::Acquire) {
return Err(ModuleCallError::Unavailable);
@@ -333,7 +350,9 @@ impl McpConfiguredClient {
.unwrap_or_default();
for client in clients {
if client.retiring.load(Ordering::Acquire) {
- Self::close_retired_client(PathBuf::from(&client.data_dir), client).await;
+ let data_dir = PathBuf::from(&client.data_dir);
+ let reservation = Self::reservation_for(&data_dir);
+ Self::close_retired_client(data_dir, client, reservation).await;
} else if let Err(error) = client.close().await {
tracing::warn!(?error, "[mcp] workspace cleanup is still pending");
}
@@ -393,10 +412,11 @@ impl McpConfiguredClient {
/// a later cleanup attempt can retry the module's retained transition.
pub(crate) async fn close_agent_data_dir(data_dir: &std::path::Path) -> bool {
let key = data_dir.to_path_buf();
+ let reservation = Self::reservation_for(&key);
let Some(client) = Self::retire_cached_client(&key) else {
- return true;
+ return Self::finish_cleanup(&key, None, reservation);
};
- Self::close_retired_client(key, client).await
+ Self::close_retired_client(key, client, reservation).await
}
/// Marks the exact cached client unavailable before scheduling cleanup.
@@ -404,21 +424,49 @@ impl McpConfiguredClient {
/// registered shutdown hook to close later.
pub(crate) fn schedule_agent_close_data_dir(data_dir: &std::path::Path) {
let key = data_dir.to_path_buf();
+ let reservation = Self::reservation_for(&key);
let Some(client) = Self::retire_cached_client(&key) else {
+ Self::finish_cleanup(&key, None, reservation);
return;
};
let Ok(runtime) = tokio::runtime::Handle::try_current() else {
return;
};
runtime.spawn(async move {
- if !Self::close_retired_client(key, client).await {
+ if !Self::close_retired_client(key, client, reservation).await {
tracing::warn!("[mcp] agent client close remains pending for retry");
}
});
}
+ /// Retires the exact scoped client and runs `after_close` only after the
+ /// module acknowledges its close. The path remains unavailable until the
+ /// callback succeeds, so a replacement cannot reuse files being purged.
+ pub(crate) fn schedule_agent_close_and_cleanup(
+ data_dir: &std::path::Path,
+ after_close: CleanupAction,
+ ) {
+ let key = data_dir.to_path_buf();
+ let reservation = Self::reservation_with_action(&key, after_close);
+ let Some(client) = Self::retire_cached_client(&key) else {
+ if !Self::finish_cleanup(&key, None, reservation) {
+ tracing::warn!("[mcp] agent cleanup remains pending for retry");
+ }
+ return;
+ };
+ let Ok(runtime) = tokio::runtime::Handle::try_current() else {
+ return;
+ };
+ runtime.spawn(async move {
+ if !Self::close_retired_client(key, client, reservation).await {
+ tracing::warn!("[mcp] agent close and cleanup remain pending for retry");
+ }
+ });
+ }
+
pub(crate) fn agent_close_pending(data_dir: &std::path::Path) -> bool {
- CLIENTS
+ Self::cleanup_pending(data_dir)
+ || CLIENTS
.get()
.and_then(|clients| {
clients
@@ -430,6 +478,58 @@ impl McpConfiguredClient {
.unwrap_or(false)
}
+ fn cleanup_pending(data_dir: &std::path::Path) -> bool {
+ CLEANUP_RESERVATIONS
+ .get()
+ .is_some_and(|reservations| {
+ reservations
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .contains_key(data_dir)
+ })
+ }
+
+ fn reservation_for(data_dir: &std::path::Path) -> Arc<CleanupReservation> {
+ let reservations = CLEANUP_RESERVATIONS.get_or_init(|| Mutex::new(HashMap::new()));
+ let mut reservations = reservations
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ Arc::clone(
+ reservations
+ .entry(data_dir.to_path_buf())
+ .or_insert_with(|| Arc::new(CleanupReservation::default())),
+ )
+ }
+
+ fn reservation_with_action(
+ data_dir: &std::path::Path,
+ action: CleanupAction,
+ ) -> Arc<CleanupReservation> {
+ loop {
+ let reservation = Self::reservation_for(data_dir);
+ let mut after_close = reservation
+ .after_close
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ let current = CLEANUP_RESERVATIONS
+ .get()
+ .and_then(|reservations| {
+ reservations
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .get(data_dir)
+ .is_some_and(|stored| Arc::ptr_eq(stored, &reservation))
+ .then_some(())
+ })
+ .is_some();
+ if !current {
+ continue;
+ }
+ after_close.get_or_insert(action);
+ return Arc::clone(&reservation);
+ }
+ }
+
fn retire_cached_client(data_dir: &std::path::Path) -> Option<Arc<Self>> {
let clients = CLIENTS.get().map(|clients| {
clients
@@ -441,22 +541,13 @@ impl McpConfiguredClient {
Some(Arc::clone(client))
}
- async fn close_retired_client(data_dir: PathBuf, client: Arc<Self>) -> bool {
+ async fn close_retired_client(
+ data_dir: PathBuf,
+ client: Arc<Self>,
+ reservation: Arc<CleanupReservation>,
+ ) -> bool {
match client.close().await {
- Ok(()) => {
- if let Some(clients) = CLIENTS.get() {
- let mut clients = clients
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner);
- if clients
- .get(&data_dir)
- .is_some_and(|current| Arc::ptr_eq(current, &client))
- {
- clients.remove(&data_dir);
- }
- }
- true
- }
+ Ok(()) => Self::finish_cleanup(&data_dir, Some(client), reservation),
Err(error) => {
tracing::warn!(?error, "[mcp] agent client close remains pending");
false
@@ -464,6 +555,56 @@ impl McpConfiguredClient {
}
}
+ fn finish_cleanup(
+ data_dir: &std::path::Path,
+ client: Option<Arc<Self>>,
+ reservation: Arc<CleanupReservation>,
+ ) -> bool {
+ let mut after_close = reservation
+ .after_close
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ let reservations = CLEANUP_RESERVATIONS.get_or_init(|| Mutex::new(HashMap::new()));
+ let is_current = reservations
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .get(data_dir)
+ .is_some_and(|stored| Arc::ptr_eq(stored, &reservation));
+ if !is_current {
+ return false;
+ }
+ if after_close.as_ref().is_some_and(|action| !action()) {
+ return false;
+ }
+ if let Some(client) = client {
+ if let Some(clients) = CLIENTS.get() {
+ let mut clients = clients
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ if clients
+ .get(data_dir)
+ .is_some_and(|current| Arc::ptr_eq(current, &client))
+ {
+ clients.remove(data_dir);
+ } else {
+ return false;
+ }
+ }
+ }
+ let mut reservations = reservations
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ if reservations
+ .get(data_dir)
+ .is_some_and(|stored| Arc::ptr_eq(stored, &reservation))
+ {
+ reservations.remove(data_dir);
+ true
+ } else {
+ false
+ }
+ }
+
/// Calls one member on this workspace's private configured object.
pub(crate) async fn call<R: DeserializeOwned>(
&self,
diff --git a/crates/openhuman-embed/src/agent/mod.rs b/crates/openhuman-embed/src/agent/mod.rs
index 8d35fa7bfc..af3b2c9e3f 100644
--- a/crates/openhuman-embed/src/agent/mod.rs
+++ b/crates/openhuman-embed/src/agent/mod.rs
@@ -147,6 +147,17 @@ impl AgentInner {
/// denied with `resolution`, its state slots are cleared, cached MCP
/// cleanup is scheduled, and its context leaves the registry. Runs once.
pub(crate) fn teardown(&self, resolution: &str) {
+ self.teardown_with_cleanup(resolution, true);
+ }
+
+ /// Tears down host state without scheduling a separate close task. The
+ /// removal owner uses this when it transfers cleanup to a deferred
+ /// close-and-purge callback.
+ pub(crate) fn teardown_without_mcp_cleanup(&self, resolution: &str) {
+ self.teardown_with_cleanup(resolution, false);
+ }
+
+ fn teardown_with_cleanup(&self, resolution: &str, schedule_mcp_cleanup: bool) {
if !self.lifecycle.begin_teardown() {
return;
}
@@ -158,7 +169,9 @@ impl AgentInner {
);
self.deny_approvals(resolution);
self.ctx.agent_state().clear();
- openhuman_core::mcp::host::schedule_agent_close(&self.config.workspace_dir, &self.id);
+ if schedule_mcp_cleanup {
+ openhuman_core::mcp::host::schedule_agent_close(&self.config.workspace_dir, &self.id);
+ }
openhuman_core::core::runtime::AgentContextRegistry::deregister(&self.id, &self.ctx);
log::debug!("[embed][agent] teardown complete id={}", self.id);
}
@@ -186,8 +199,8 @@ impl AgentInner {
impl Drop for AgentInner {
fn drop(&mut self) {
- self.teardown("agent_dropped");
let mut agents = self.registry.lock().unwrap_or_else(|e| e.into_inner());
+ self.teardown("agent_dropped");
if agents
.get(&self.id)
.is_some_and(|current| std::ptr::eq(current.as_ptr(), self))
diff --git a/crates/openhuman-embed/src/runtime/lifecycle.rs b/crates/openhuman-embed/src/runtime/lifecycle.rs
index d70aa834b4..4739c4f05d 100644
--- a/crates/openhuman-embed/src/runtime/lifecycle.rs
+++ b/crates/openhuman-embed/src/runtime/lifecycle.rs
@@ -41,27 +41,36 @@ impl RemovalSlot<'_> {
impl Drop for RemovalSlot<'_> {
fn drop(&mut self) {
- self.inner.teardown("agent_removed");
+ let mut agents = self
+ .runtime
+ .agents
+ .lock()
+ .unwrap_or_else(|e| e.into_inner());
if self.purge && !self.mcp_cleanup_confirmed {
- self.mcp_cleanup_confirmed = !openhuman_core::mcp::host::agent_close_pending(
+ self.inner.teardown_without_mcp_cleanup("agent_removed");
+ let home = self.inner.layout.home.clone();
+ let cleanup = Arc::new(move || match std::fs::remove_dir_all(&home) {
+ Ok(()) => true,
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => true,
+ Err(error) => {
+ log::warn!("[embed][runtime] deferred agent purge failed: {error}");
+ false
+ }
+ });
+ openhuman_core::mcp::host::schedule_agent_close_with_cleanup(
&self.inner.config.workspace_dir,
&self.inner.id,
+ cleanup,
);
- if !self.mcp_cleanup_confirmed {
- self.purge = false;
- log::warn!(
- "[embed][runtime] retaining agent home until MCP cleanup is acknowledged"
- );
+ // Ownership of the requested purge moved to the deferred cleanup
+ // reservation, which also fences this agent id until it completes.
+ self.purge = false;
+ } else {
+ self.inner.teardown("agent_removed");
+ if let Err(error) = self.purge_home() {
+ log::warn!("[embed][runtime] cancelled removal purge failed: {error}");
}
}
- if let Err(error) = self.purge_home() {
- log::warn!("[embed][runtime] cancelled removal purge failed: {error}");
- }
- let mut agents = self
- .runtime
- .agents
- .lock()
- .unwrap_or_else(|e| e.into_inner());
if agents
.get(&self.inner.id)
.and_then(std::sync::Weak::upgrade)
@@ -153,7 +162,6 @@ impl Runtime {
removal.mcp_cleanup_confirmed =
openhuman_core::mcp::host::close_agent(&inner.config.workspace_dir, &inner.id).await;
if !removal.mcp_cleanup_confirmed {
- removal.purge = false;
return Err(AgentError::CleanupPending);
}
inner.teardown("agent_removed");