Skip to content

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

refactor(agent): track pending cleanup in the registry

Steven Enamakel00632d50e473
diff --git a/crates/openhuman-embed/src/agent/mcp_cleanup.rs b/crates/openhuman-embed/src/agent/mcp_cleanup.rs
index c0065d76dd..e78a3c7cd9 100644
--- a/crates/openhuman-embed/src/agent/mcp_cleanup.rs
+++ b/crates/openhuman-embed/src/agent/mcp_cleanup.rs
@@ -1,89 +1,101 @@
//! Retiring one captured agent owner before its id or home is reusable.
use super::*;
+use crate::runtime::PendingCleanup;
use std::sync::{atomic::Ordering, Weak};
-fn finish_removal(
+pub(crate) fn finish_removal(
registry: &crate::runtime::AgentMap,
id: &str,
- instance: &Weak<AgentInner>,
- home: &Path,
- purge: bool,
+ pending: &PendingCleanup,
) -> Result<(), AgentError> {
let mut agents = registry.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
- if !agents.get(id).is_some_and(|current| Weak::ptr_eq(current, instance)) {
+ if !agents.get(id).is_some_and(|current| Weak::ptr_eq(current, &pending.instance)) {
return Ok(());
}
- // Keep the id reserved during purge. A second cleanup cannot delete the
- // home of a replacement that another caller has already instantiated.
- if purge && home.exists() {
- std::fs::remove_dir_all(home).map_err(|source| AgentError::Workspace {
+ let purge = pending.purge || agents.pending.get(id).is_some_and(|current| current.purge);
+ // Keep the id reserved throughout purge; never touch a successor's home.
+ if purge && pending.home.exists() {
+ std::fs::remove_dir_all(&pending.home).map_err(|source| AgentError::Workspace {
what: "delete the removed agent's home", source,
})?;
}
agents.remove(id);
+ agents.pending.remove(id);
Ok(())
}
+/// Run at most three retries on the process module executor. The future owns
+/// the workspace guard only while running; retained records contain no guard.
+pub(crate) fn defer_pending(
+ registry: Arc<crate::runtime::AgentMap>,
+ id: String,
+ pending: PendingCleanup,
+ guard: Arc<crate::runtime::CoreGuard>,
+) {
+ if pending.cleanup.as_ref().is_none_or(|cleanup| cleanup.finish_if_idle()) {
+ if let Err(error) = finish_removal(&registry, &id, &pending) {
+ log::warn!("[embed][agent] removed home cleanup remains pending: {error}");
+ }
+ return;
+ }
+ if pending.retry_running.swap(true, Ordering::AcqRel) { return; }
+ let running = Arc::clone(&pending.retry_running);
+ let future = async move {
+ let _guard = guard;
+ for attempt in 0..3 {
+ let result = match &pending.cleanup {
+ Some(cleanup) => cleanup.finish().await.map_err(AgentError::McpCleanup),
+ None => Ok(()),
+ }.and_then(|()| finish_removal(&registry, &id, &pending));
+ match result {
+ Ok(()) => { running.store(false, Ordering::Release); return; }
+ Err(error) => log::warn!("[embed][agent] captured cleanup remains pending: {error}"),
+ }
+ if attempt < 2 {
+ tokio::time::sleep(std::time::Duration::from_millis(250 * (1 << attempt))).await;
+ }
+ }
+ // The original receipt, id reservation and purge intent stay in the
+ // registry. A later remove_agent call retries them explicitly.
+ running.store(false, Ordering::Release);
+ };
+ if let Err(error) = openhuman_core::mcp::host::spawn_agent_cleanup(future) {
+ pending_running_reset(&registry_placeholder());
+ log::warn!("[embed][agent] cleanup executor unavailable: {error}");
+ }
+}
+
impl AgentInner {
- pub(crate) fn cleanup_is_pending(&self) -> bool {
- self.mcp_cleanup.lock().unwrap_or_else(std::sync::PoisonError::into_inner).is_some()
+ pub(crate) fn reserve_cleanup(&self, purge: bool) -> Option<PendingCleanup> {
+ let cleanup = self.mcp_cleanup.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone();
+ let mut agents = self.registry.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
+ let instance = agents.get(&self.id).filter(|weak| std::ptr::eq(weak.as_ptr(), self)).cloned()?;
+ let pending = agents.pending.entry(self.id.clone()).or_insert_with(|| PendingCleanup {
+ cleanup, instance, home: self.layout.home.clone(), purge,
+ retry_running: Default::default(),
+ });
+ pending.purge |= purge;
+ Some(pending.clone())
}
pub(crate) async fn finish_mcp_cleanup(&self) -> Result<(), AgentError> {
let cleanup = self.mcp_cleanup.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone();
if let Some(cleanup) = cleanup {
cleanup.finish().await.map_err(AgentError::McpCleanup)?;
- self.mcp_cleanup.lock().unwrap_or_else(std::sync::PoisonError::into_inner).take();
}
Ok(())
}
pub(crate) fn finish_removal(&self, purge: bool) -> Result<(), AgentError> {
- let instance = self.registry.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
- .get(&self.id).filter(|weak| std::ptr::eq(weak.as_ptr(), self)).cloned();
- if let Some(instance) = instance {
- finish_removal(&self.registry, &self.id, &instance, &self.layout.home, purge)?;
+ if let Some(pending) = self.reserve_cleanup(purge) {
+ finish_removal(&self.registry, &self.id, &pending)?;
}
Ok(())
}
- /// Retry independently of the caller runtime. The task, rather than a
- /// process-global callback, holds the workspace guard while cleanup runs.
pub(crate) fn defer_cleanup(&self, purge: bool) {
- let cleanup = self.mcp_cleanup.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone();
- if cleanup.as_ref().is_none_or(|cleanup| cleanup.finish_if_idle()) {
- if let Err(error) = self.finish_removal(purge) {
- log::warn!("[embed][agent] removed home cleanup failed: {error}");
- }
- return;
- }
- if self.cleanup_started.swap(true, Ordering::AcqRel) { return; }
- let Some(cleanup) = cleanup else { return; };
- let instance = self.registry.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
- .get(&self.id).filter(|weak| std::ptr::eq(weak.as_ptr(), self)).cloned();
- let Some(instance) = instance else { return; };
- let registry = Arc::clone(&self.registry);
- let guard = Arc::clone(&self._runtime_guard);
- let home = self.layout.home.clone();
- let id = self.id.clone();
- let future = async move {
- let _guard = guard;
- let mut delay = std::time::Duration::from_millis(250);
- loop {
- let result = match cleanup.finish().await {
- Ok(()) => finish_removal(&registry, &id, &instance, &home, purge),
- Err(error) => Err(AgentError::McpCleanup(error)),
- };
- match result {
- Ok(()) => return,
- Err(error) => log::warn!("[embed][agent] captured cleanup remains pending: {error}"),
- }
- tokio::time::sleep(delay).await;
- delay = (delay * 2).min(std::time::Duration::from_secs(5));
- }
- };
- if let Err(error) = openhuman_core::mcp::host::spawn_agent_cleanup(future) {
- log::warn!("[embed][agent] cleanup executor unavailable: {error}");
+ if let Some(pending) = self.reserve_cleanup(purge) {
+ defer_pending(Arc::clone(&self.registry), self.id.clone(), pending, Arc::clone(&self._runtime_guard));
}
}
}