The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
fix(subagent_sessions): guard close against concurrent session reuse
Steven Enamakel917619e42c99
diff --git a/crates/openhuman-core/src/agent/orchestration/subagent_sessions/mod.rs b/crates/openhuman-core/src/agent/orchestration/subagent_sessions/mod.rsindex 6c076435ae..3c51a59a4e 100644--- a/crates/openhuman-core/src/agent/orchestration/subagent_sessions/mod.rs+++ b/crates/openhuman-core/src/agent/orchestration/subagent_sessions/mod.rs@@ -5,9 +5,10 @@ mod tiny_port;mod types;pub use ops::{- action_root_key, cancel_driver_job_for_session, cancel_driver_jobs_for_thread, close,- find_reusable, list_for_parent, mark_failed, mark_finished, normalize_task_key,- resolve_lifecycle_key, reuse_decision, task_title_from_prompt, upsert_running,+ action_root_key, cancel_driver_job_for_observed_session, cancel_driver_job_for_session,+ cancel_driver_jobs_for_thread, close, close_if_current, find_reusable, list_for_parent,+ mark_failed, mark_finished, normalize_task_key, resolve_lifecycle_key, reuse_decision,+ task_title_from_prompt, upsert_running,};pub(crate) use tiny_port::OpenHumanTinySubagentSessionStore;pub use types::{diff --git a/crates/openhuman-core/src/agent/orchestration/subagent_sessions/ops.rs b/crates/openhuman-core/src/agent/orchestration/subagent_sessions/ops.rsindex 54838937e9..869911a044 100644--- a/crates/openhuman-core/src/agent/orchestration/subagent_sessions/ops.rs+++ b/crates/openhuman-core/src/agent/orchestration/subagent_sessions/ops.rs@@ -119,6 +119,49 @@ pub fn cancel_driver_job_for_session(jobs.cancel_key_owned(&key, owner).is_ok()}+/// Requests cancellation for the exact durable row observed by the caller.+/// Keeping this separate from a fresh session-id lookup prevents concurrent+/// reuse from redirecting cancellation to a replacement child.+pub fn cancel_driver_job_for_observed_session(+ store: &SubagentSessionStore,+ checkpoint_dir: &Path,+ jobs: &tinyagents_orchestration::subagent::SubAgentJobRegistry,+ session: &DurableSubagentSession,+ parent_session: &str,+ parent_thread_id: Option<&str>,+) -> bool {+ if session.parent_session != parent_session+ || session.parent_thread_id.as_deref() != parent_thread_id+ {+ return false;+ }+ let Some(task_id) = session.current_task_id.as_deref() else {+ return false;+ };+ let key = session+ .lifecycle_key+ .filter(|key| key.task_id == task_id && key.thread_id.as_deref() == parent_thread_id)+ .or_else(|| {+ resolve_lifecycle_key(+ store,+ &session.subagent_session_id,+ parent_session,+ parent_thread_id,+ checkpoint_dir,+ )+ .ok()+ .filter(|key| key.task_id == task_id)+ });+ let Some(key) = key else {+ return false;+ };+ let owner = crate::agent::tinyagents::tool_registration::subagent_owner_key(+ parent_session,+ parent_thread_id,+ );+ jobs.cancel_key_owned(&key, owner).is_ok()+}+/// Resolve a saved product session to its exact TinyAgents lifecycle key.////// The product session lookup is scoped by the authenticated parent session,@@ -249,6 +292,14 @@ pub fn upsert_running(.find(|session| session.subagent_session_id == session_id).cloned(){+ if let Some(reuse) = reuse {+ if existing.status == DurableSubagentStatus::Closed+ || existing.current_task_id != reuse.current_task_id+ || existing.lifecycle_key != reuse.lifecycle_key+ {+ return Err("stale reusable sub-agent session changed during upsert".into());+ }+ }existing} else {DurableSubagentSession {@@ -346,6 +397,40 @@ pub fn close(store: &SubagentSessionStore, subagent_session_id: &str) -> Result<})}+/// Closes a session only if it still contains the lifecycle snapshot that the+/// caller observed and cancelled. `false` means a concurrent reuse or close+/// won the race and this stale request did not alter the newer row.+pub fn close_if_current(+ store: &SubagentSessionStore,+ observed: &DurableSubagentSession,+) -> Result<bool, String> {+ let _guard = store_write_lock()+ .lock()+ .map_err(|_| "subagent session store lock poisoned".to_string())?;+ let mut sessions = store.load()?;+ let now = chrono::Utc::now().to_rfc3339();+ let Some(session) = sessions+ .iter_mut()+ .find(|session| session.subagent_session_id == observed.subagent_session_id)+ else {+ return Ok(false);+ };+ if session.status == DurableSubagentStatus::Closed+ || session.parent_session != observed.parent_session+ || session.parent_thread_id != observed.parent_thread_id+ || session.current_task_id != observed.current_task_id+ || session.lifecycle_key != observed.lifecycle_key+ {+ return Ok(false);+ }+ session.status = DurableSubagentStatus::Closed;+ session.reusable = false;+ session.updated_at = now.clone();+ session.last_used_at = now;+ store.save(&sessions)?;+ Ok(true)+}+pub fn list_for_parent(store: &SubagentSessionStore,parent_session: &str,diff --git a/crates/openhuman-core/src/agent/orchestration/subagent_sessions/tiny_port.rs b/crates/openhuman-core/src/agent/orchestration/subagent_sessions/tiny_port.rsindex 6fed66c9a0..24b2136893 100644--- a/crates/openhuman-core/src/agent/orchestration/subagent_sessions/tiny_port.rs+++ b/crates/openhuman-core/src/agent/orchestration/subagent_sessions/tiny_port.rs@@ -212,17 +212,21 @@ impl TinySessionStore for OpenHumanTinySubagentSessionStore {return Ok(false);};if let Some(jobs) = &self.jobs {- let _ = super::cancel_driver_job_for_session(+ let _ = super::cancel_driver_job_for_observed_session(&self.store,&self.checkpoint_dir,jobs,- id,+ &session,&self.parent_session,self.parent_thread_id.as_deref(),);}- drop(session);- super::close(&self.store, id).map_err(SubagentError::Persistence)+ match super::close_if_current(&self.store, &session).map_err(SubagentError::Persistence)? {+ true => Ok(true),+ false => Err(SubagentError::InvalidRequest(+ "subagent session changed while it was being closed".into(),+ )),+ }}async fn mark_finished(diff --git a/crates/openhuman-core/src/agent/orchestration/tools/close_subagent.rs b/crates/openhuman-core/src/agent/orchestration/tools/close_subagent.rsindex 25750d635f..63d1626346 100644--- a/crates/openhuman-core/src/agent/orchestration/tools/close_subagent.rs+++ b/crates/openhuman-core/src/agent/orchestration/tools/close_subagent.rs@@ -126,12 +126,12 @@ impl CloseSubagentTool {};let store = SubagentSessionStore::new(parent.workspace_dir.clone());let parent_thread_id = tool_context.and_then(ToolRunContext::thread_id);- let owned = match subagent_sessions::list_for_parent(+ let observed = match subagent_sessions::list_for_parent(&store,&parent.session_id,parent_thread_id,) {- Ok(sessions) => sessions.iter().any(|session| {+ Ok(sessions) => sessions.into_iter().find(|session| {session.subagent_session_id == subagent_session_id&& session.parent_thread_id.as_deref() == parent_thread_id}),@@ -141,7 +141,7 @@ impl CloseSubagentTool {)));}};- if !owned {+ let Some(observed) = observed else {log::warn!("[subagent_reuse] close rejected parent_session={} parent_thread_id={} subagent_session_id={}",parent.session_id,@@ -159,11 +159,11 @@ impl CloseSubagentTool {tinyagents_orchestration::subagent::SubAgentJobRegistry,>(&dispatch);let store = SubagentSessionStore::new(parent.workspace_dir.clone());- let cancelled = subagent_sessions::cancel_driver_job_for_session(+ let cancelled = subagent_sessions::cancel_driver_job_for_observed_session(&store,&parent.workspace_dir.join(".openhuman/subagent_checkpoints"),&jobs,- &subagent_session_id,+ &observed,&parent.session_id,thread_id,) || running_subagents::cancel_by_session_in_workspace(@@ -173,7 +173,13 @@ impl CloseSubagentTool {&parent.workspace_dir,).is_some();- match subagent_sessions::close(&store, &subagent_session_id) {+ match subagent_sessions::close_if_current(&store, &observed) {+ Ok(false) => Ok(ToolResult::error(+ "close_subagent: session changed while it was being closed; retry with its current reference",+ )),+ Err(err) => Ok(ToolResult::error(format!(+ "close_subagent: failed to update sub-agent session: {err}"+ ))),Ok(closed) => {log::info!("[subagent_reuse] close subagent_session_id={} parent_session={} closed={} cancelled_running={}",@@ -186,9 +192,6 @@ impl CloseSubagentTool {"Closed reusable sub-agent session `{subagent_session_id}` (closed={closed}, cancelled_running={cancelled}).")))}- Err(err) => Ok(ToolResult::error(format!(- "close_subagent: failed to update sub-agent session: {err}"- ))),}}}diff --git a/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent_execute.rs b/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent_execute.rsindex f973422814..ceaa84a907 100644--- a/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent_execute.rs+++ b/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent_execute.rs@@ -136,11 +136,11 @@ impl SpawnAsyncSubagentTool {let jobs = crate::core::runtime::slot_for::<tinyagents_orchestration::subagent::SubAgentJobRegistry,>(&dispatch);- let cancelled = subagent_sessions::cancel_driver_job_for_session(+ let cancelled = subagent_sessions::cancel_driver_job_for_observed_session(&store,&parent.workspace_dir.join(".openhuman/subagent_checkpoints"),&jobs,- &session.subagent_session_id,+ &session,&parent_session,parent_thread_id.as_deref(),);@@ -152,16 +152,23 @@ impl SpawnAsyncSubagentTool {&parent.workspace_dir,);}- if let Err(err) = subagent_sessions::close(&store, &session.subagent_session_id)- {- log::warn!(+ match subagent_sessions::close_if_current(&store, &session) {+ Ok(true) => {}+ Ok(false) => log::warn!(+ "[subagent_reuse] fresh close lost lifecycle race parent_thread_id={} subagent_session_id={} agent_id={} task_key={}",+ parent_thread_id.as_deref().unwrap_or("none"),+ session.subagent_session_id,+ definition.id,+ task_key+ ),+ Err(err) => log::warn!("[subagent_reuse] fresh close failed parent_thread_id={} subagent_session_id={} agent_id={} task_key={} error={}",parent_thread_id.as_deref().unwrap_or("none"),session.subagent_session_id,definition.id,task_key,err- );+ ),}}Ok(None) => {}