Skip to content

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

fix(embed): preserve ephemeral workspace when cleanup is unconfirmed

Steven Enamakel1bc675bf0d5f
diff --git a/crates/openhuman-embed/src/agent/mcp_cleanup.rs b/crates/openhuman-embed/src/agent/mcp_cleanup.rs
index 24bffa48fb..f7288703a2 100644
--- a/crates/openhuman-embed/src/agent/mcp_cleanup.rs
+++ b/crates/openhuman-embed/src/agent/mcp_cleanup.rs
@@ -47,6 +47,7 @@ pub(crate) fn defer_pending(
.is_none_or(|cleanup| cleanup.finish_if_idle())
{
if let Err(error) = finish_removal(&registry, &id, &pending) {
+ guard.preserve_ephemeral_workspace();
log::warn!("[embed][agent] removed home cleanup remains pending: {error}");
}
return;
@@ -56,23 +57,30 @@ pub(crate) fn defer_pending(
}
let running = Arc::clone(&pending.retry_running);
let executor_failed = Arc::clone(&running);
- let future = async move {
- retry_cleanup(
- guard,
- || {
- let cleanup = pending.cleanup.clone();
- async move {
- match cleanup {
- Some(cleanup) => cleanup.finish().await.map_err(AgentError::McpCleanup),
- None => Ok(()),
- }
+ let pending_for_completion = pending.clone();
+ // Construct the RAII owner before scheduling, so rejection or cancellation
+ // of an unpolled future cannot delete the unconfirmed workspace.
+ let cleanup = retry_cleanup(
+ guard,
+ move || {
+ let cleanup = pending.cleanup.clone();
+ async move {
+ match cleanup {
+ Some(cleanup) => cleanup.finish().await.map_err(AgentError::McpCleanup),
+ None => Ok(()),
}
- },
- || finish_removal(&registry, &id, &pending),
- )
- .await;
- // The original receipt, id reservation and purge intent stay in the
- // registry. A later remove_agent call retries them explicitly.
+ }
+ },
+ {
+ let registry = Arc::clone(&registry);
+ let pending = pending_for_completion;
+ move || finish_removal(&registry, &id, &pending)
+ },
+ );
+ let future = async move {
+ cleanup.await;
+ // Retained metadata has no runtime guard. A live Runtime can explicitly
+ // retry; after it is gone, retained files require manual reclamation.
running.store(false, Ordering::Release);
};
if let Err(error) = openhuman_core::mcp::host::spawn_agent_cleanup(future) {
@@ -81,26 +89,52 @@ pub(crate) fn defer_pending(
}
}
-async fn retry_cleanup<F, Fut, C>(
+struct CleanupWorkspaceOwner {
+ guard: Option<Arc<crate::runtime::CoreGuard>>,
+ confirmed: bool,
+}
+
+impl Drop for CleanupWorkspaceOwner {
+ fn drop(&mut self) {
+ if !self.confirmed {
+ if let Some(guard) = &self.guard {
+ guard.preserve_ephemeral_workspace();
+ }
+ }
+ }
+}
+
+fn retry_cleanup<F, Fut, C>(
guard: Arc<crate::runtime::CoreGuard>,
mut close: F,
mut complete: C,
-) where
+) -> impl std::future::Future<Output = ()>
+where
F: FnMut() -> Fut,
Fut: std::future::Future<Output = Result<(), AgentError>>,
C: FnMut() -> Result<(), AgentError>,
{
- let mut guard = Some(guard);
- for attempt in 0..3 {
- let result = close()
- .await
- .and_then(|()| complete_with_guard(&mut guard, &mut complete));
- match result {
- Ok(()) => 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;
+ let mut owner = CleanupWorkspaceOwner {
+ guard: Some(guard),
+ confirmed: false,
+ };
+ async move {
+ for attempt in 0..3 {
+ let result = close()
+ .await
+ .and_then(|()| complete_with_guard(&mut owner.guard, &mut complete));
+ match result {
+ Ok(()) => {
+ owner.confirmed = true;
+ 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;
+ }
}
}
}
diff --git a/crates/openhuman-embed/src/runtime/mod.rs b/crates/openhuman-embed/src/runtime/mod.rs
index 5c89640207..82ceabc55e 100644
--- a/crates/openhuman-embed/src/runtime/mod.rs
+++ b/crates/openhuman-embed/src/runtime/mod.rs
@@ -190,6 +190,8 @@ pub enum RuntimeError {
pub(crate) struct CoreGuard {
pub(crate) events: Arc<crate::events::EventHub>,
core: Option<Core>,
+ /// Terminal or cancelled agent cleanup must not erase unconfirmed state.
+ preserve_ephemeral_workspace: AtomicBool,
/// Held for its `Drop`: an ephemeral workspace lives exactly as long as
/// the last owner of this guard.
workspace: ResolvedWorkspace,
@@ -208,6 +210,13 @@ pub(crate) struct CoreGuard {
seams: Mutex<Option<seams::InstalledSeams>>,
}
+impl CoreGuard {
+ pub(crate) fn preserve_ephemeral_workspace(&self) {
+ self.preserve_ephemeral_workspace
+ .store(true, std::sync::atomic::Ordering::Release);
+ }
+}
+
impl Drop for CoreGuard {
fn drop(&mut self) {
// Stop handing this runtime's agents and handlers to the core's
@@ -241,21 +250,31 @@ impl Drop for CoreGuard {
// writes settle before giving up.
if let Some(temp) = self.workspace._temp.take() {
let root = temp.keep();
- let mut quiet_passes = 0;
- for _ in 0..20 {
- match std::fs::remove_dir_all(&root) {
- Ok(()) => quiet_passes += 1,
- Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
- quiet_passes += 1;
+ if self
+ .preserve_ephemeral_workspace
+ .load(std::sync::atomic::Ordering::Acquire)
+ {
+ log::warn!(
+ "[embed][runtime] unresolved cleanup; preserved ephemeral workspace at {}",
+ root.display()
+ );
+ } else {
+ let mut quiet_passes = 0;
+ for _ in 0..20 {
+ match std::fs::remove_dir_all(&root) {
+ Ok(()) => quiet_passes += 1,
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
+ quiet_passes += 1;
+ }
+ Err(_) => quiet_passes = 0,
}
- Err(_) => quiet_passes = 0,
- }
- if quiet_passes >= 5 {
- break;
+ if quiet_passes >= 5 {
+ break;
+ }
+ std::thread::sleep(std::time::Duration::from_millis(50));
}
- std::thread::sleep(std::time::Duration::from_millis(50));
+ let _ = std::fs::remove_dir_all(&root);
}
- let _ = std::fs::remove_dir_all(&root);
}
RUNTIME_LIVE.store(false, std::sync::atomic::Ordering::Release);
log::debug!("[embed][runtime] released");
@@ -606,6 +625,7 @@ impl Runtime {
guard: Arc::new(CoreGuard {
events: crate::events::EventHub::new(256),
core: Some(core),
+ preserve_ephemeral_workspace: AtomicBool::new(false),
workspace,
session_store,
previous_session_store,