Skip to content

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

fix(embed): serialize approval decisions with removal claims

Steven Enamakel7b3c27535c91
diff --git a/crates/openhuman-core/src/security/approval/registration_scope_tests.rs b/crates/openhuman-core/src/security/approval/registration_scope_tests.rs
index c2e2c11a7b..06778f5471 100644
--- a/crates/openhuman-core/src/security/approval/registration_scope_tests.rs
+++ b/crates/openhuman-core/src/security/approval/registration_scope_tests.rs
@@ -12,11 +12,10 @@ fn removal_refuses_late_registration_without_creating_a_pending_row() {
}
#[test]
-fn removal_waits_for_accepted_registration_before_taking_its_snapshot() {
+fn accepted_registration_holds_the_removal_barrier_until_it_finishes() {
let scope = Arc::new(ApprovalScope::default());
let (entered_tx, entered_rx) = mpsc::channel();
let (release_tx, release_rx) = mpsc::channel();
- let (closed_tx, closed_rx) = mpsc::channel();
let registering = scope.clone();
let registration = std::thread::spawn(move || {
registering.register(|| {
@@ -25,21 +24,20 @@ fn removal_waits_for_accepted_registration_before_taking_its_snapshot() {
})
});
entered_rx.recv().unwrap();
- let removing = scope.clone();
- let removal = std::thread::spawn(move || {
- removing.close("agent_removed");
- closed_tx.send(()).unwrap();
- });
- let closed_early = closed_rx
- .recv_timeout(std::time::Duration::from_millis(100))
- .is_ok();
+ // Observe ownership directly while the accepted registration is suspended;
+ // no scheduler delay or elapsed-time assertion can hide an unlocked barrier.
+ let held = matches!(
+ scope.closed.try_lock(),
+ Err(std::sync::TryLockError::WouldBlock)
+ );
release_tx.send(()).unwrap();
assert_eq!(registration.join().unwrap(), Ok(()));
- removal.join().unwrap();
assert!(
- !closed_early,
- "removal snapshot raced an accepted registration"
+ held,
+ "registration released the removal barrier before finishing"
);
+ scope.close("agent_removed");
+ assert_eq!(scope.register(|| ()), Err("agent_removed".to_owned()));
}
#[test]
diff --git a/crates/openhuman-embed/src/agent/approval_handler.rs b/crates/openhuman-embed/src/agent/approval_handler.rs
index 1f888de68c..68e4174f38 100644
--- a/crates/openhuman-embed/src/agent/approval_handler.rs
+++ b/crates/openhuman-embed/src/agent/approval_handler.rs
@@ -26,6 +26,7 @@ impl ApprovalSubscription {
agent_id: &str,
handler: Arc<dyn ApprovalHandler>,
removed: tokio::sync::watch::Receiver<bool>,
+ lifecycle: Arc<super::lifecycle::ApprovalState>,
) -> Self {
let cancellation = CancellationToken::new();
let subscriber = Arc::new(Handler {
@@ -33,6 +34,7 @@ impl ApprovalSubscription {
handler,
cancellation: cancellation.clone(),
removed,
+ lifecycle,
});
Self {
_subscription: BUS.subscribe(subscriber),
@@ -45,6 +47,7 @@ struct Handler {
handler: Arc<dyn ApprovalHandler>,
cancellation: CancellationToken,
removed: tokio::sync::watch::Receiver<bool>,
+ lifecycle: Arc<super::lifecycle::ApprovalState>,
}
#[async_trait::async_trait]
impl EventHandler<DomainEvent> for Handler {
@@ -63,7 +66,8 @@ impl EventHandler<DomainEvent> for Handler {
if agent_id.as_deref() != Some(&self.agent_id) || *self.removed.borrow() {
return;
}
- let approvals = Approvals::new(&self.agent_id, self.removed.clone());
+ let approvals =
+ Approvals::new(&self.agent_id, self.removed.clone(), self.lifecycle.clone());
let Ok(pending) = approvals.pending() else {
return;
};
diff --git a/crates/openhuman-embed/src/agent/approvals.rs b/crates/openhuman-embed/src/agent/approvals.rs
index 8816fcde74..822dd284c4 100644
--- a/crates/openhuman-embed/src/agent/approvals.rs
+++ b/crates/openhuman-embed/src/agent/approvals.rs
@@ -32,13 +32,19 @@ pub enum ApprovalsError {
pub struct Approvals {
agent_id: String,
removed: tokio::sync::watch::Receiver<bool>,
+ lifecycle: std::sync::Arc<super::lifecycle::ApprovalState>,
}
impl Approvals {
- pub(crate) fn new(agent_id: &str, removed: tokio::sync::watch::Receiver<bool>) -> Self {
+ pub(crate) fn new(
+ agent_id: &str,
+ removed: tokio::sync::watch::Receiver<bool>,
+ lifecycle: std::sync::Arc<super::lifecycle::ApprovalState>,
+ ) -> Self {
Self {
agent_id: agent_id.to_string(),
removed,
+ lifecycle,
}
}
@@ -69,6 +75,16 @@ impl Approvals {
&self,
request_id: &str,
decision: ApprovalDecision,
+ ) -> Result<PendingApproval, ApprovalsError> {
+ self.lifecycle
+ .with_live(|| self.decide_live(request_id, decision))
+ .unwrap_or_else(|| Err(ApprovalsError::NotFound(request_id.to_owned())))
+ }
+
+ fn decide_live(
+ &self,
+ request_id: &str,
+ decision: ApprovalDecision,
) -> Result<PendingApproval, ApprovalsError> {
let removed = self.removed.borrow();
if *removed {
diff --git a/crates/openhuman-embed/src/agent/build.rs b/crates/openhuman-embed/src/agent/build.rs
index 7279943654..e6b5a87a6e 100644
--- a/crates/openhuman-embed/src/agent/build.rs
+++ b/crates/openhuman-embed/src/agent/build.rs
@@ -280,7 +280,12 @@ pub(crate) fn instantiate(runtime: &Runtime, spec: AgentSpec) -> Result<AgentInn
}
let lifecycle = super::lifecycle::Lifecycle::new();
let approval_subscription = parts.approval_handler.map(|handler| {
- super::approval_handler::ApprovalSubscription::new(&id, handler, lifecycle.removed())
+ super::approval_handler::ApprovalSubscription::new(
+ &id,
+ handler,
+ lifecycle.removed(),
+ lifecycle.approval_state(),
+ )
});
let overlay = ContextOverlay {
host_overrides: Some(overrides.clone()),
diff --git a/crates/openhuman-embed/src/agent/lifecycle.rs b/crates/openhuman-embed/src/agent/lifecycle.rs
index 1c4eccdc96..85f02e4cee 100644
--- a/crates/openhuman-embed/src/agent/lifecycle.rs
+++ b/crates/openhuman-embed/src/agent/lifecycle.rs
@@ -2,6 +2,7 @@
//! flight, and the teardown of the per-agent state the core keeps for it.
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
+use std::sync::{Arc, Mutex};
use std::time::Duration;
use tokio::sync::{watch, Notify};
@@ -11,17 +12,46 @@ use crate::CoreError;
/// Turn admission and in-flight accounting for one agent.
pub(crate) struct Lifecycle {
removed: watch::Sender<bool>,
- removal_claimed: AtomicBool,
+ approvals: Arc<ApprovalState>,
in_flight: AtomicUsize,
idle: Notify,
torn_down: AtomicBool,
}
+/// Serializes live approval decisions with the instance's removal claim.
+#[derive(Debug, Default)]
+pub(crate) struct ApprovalState {
+ claimed: AtomicBool,
+ decisions: Mutex<()>,
+}
+
+impl ApprovalState {
+ pub(crate) fn with_live<T>(&self, decide: impl FnOnce() -> T) -> Option<T> {
+ let _decision = self
+ .decisions
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ if self.claimed.load(Ordering::SeqCst) {
+ None
+ } else {
+ Some(decide())
+ }
+ }
+
+ fn claim_removal(&self) -> bool {
+ let _decision = self
+ .decisions
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ !self.claimed.swap(true, Ordering::SeqCst)
+ }
+}
+
impl Lifecycle {
pub(crate) fn new() -> Self {
Self {
removed: watch::Sender::new(false),
- removal_claimed: AtomicBool::new(false),
+ approvals: Arc::new(ApprovalState::default()),
in_flight: AtomicUsize::new(0),
idle: Notify::new(),
torn_down: AtomicBool::new(false),
@@ -36,7 +66,7 @@ impl Lifecycle {
/// Claim removal and settle owned approvals before waking in-flight turns.
pub(crate) fn mark_removed_with(&self, before_notify: impl FnOnce()) -> bool {
- if self.removal_claimed.swap(true, Ordering::SeqCst) {
+ if !self.approvals.claim_removal() {
return false;
}
before_notify();
@@ -46,6 +76,10 @@ impl Lifecycle {
true
}
+ pub(crate) fn approval_state(&self) -> Arc<ApprovalState> {
+ self.approvals.clone()
+ }
+
/// Bind handles to this agent instance, even after its public id is reused.
pub(crate) fn removed(&self) -> watch::Receiver<bool> {
self.removed.subscribe()
@@ -66,7 +100,7 @@ impl Lifecycle {
let mut watcher = self.removed.subscribe();
// Claiming removal closes admission immediately; waking existing turns
// waits until their approvals have been settled with the removal reason.
- if self.removal_claimed.load(Ordering::SeqCst) || *watcher.borrow_and_update() {
+ if self.approvals.claimed.load(Ordering::SeqCst) || *watcher.borrow_and_update() {
log::debug!("[embed][agent] turn refused: agent removed id={agent_id}");
return Err(removed());
}
diff --git a/crates/openhuman-embed/src/agent/lifecycle_tests.rs b/crates/openhuman-embed/src/agent/lifecycle_tests.rs
index 2505ec4b8f..2890887c3a 100644
--- a/crates/openhuman-embed/src/agent/lifecycle_tests.rs
+++ b/crates/openhuman-embed/src/agent/lifecycle_tests.rs
@@ -84,3 +84,56 @@ async fn a_claimed_removal_refuses_turns_before_approvals_are_settled() {
"removal admitted a new turn while settling approvals"
);
}
+
+#[test]
+fn a_claimed_removal_refuses_approval_decisions_before_denial_finishes() {
+ let lifecycle = Arc::new(Lifecycle::new());
+ let approvals = crate::Approvals::new("a", lifecycle.removed(), lifecycle.approval_state());
+ let removing = lifecycle.clone();
+ let (entered, callback_entered) = std::sync::mpsc::channel();
+ let (release, callback_release) = std::sync::mpsc::channel();
+ let removal = std::thread::spawn(move || {
+ removing.mark_removed_with(|| {
+ entered.send(()).unwrap();
+ callback_release.recv().unwrap();
+ })
+ });
+ callback_entered.recv().unwrap();
+ let outcome = approvals.decide("pending-request", crate::ApprovalDecision::ApproveOnce);
+ release.send(()).unwrap();
+ assert!(removal.join().unwrap());
+ assert!(
+ matches!(outcome, Err(crate::ApprovalsError::NotFound(_))),
+ "{outcome:?}"
+ );
+}
+
+#[test]
+fn accepted_approval_decisions_hold_the_removal_claim_barrier() {
+ let state = Arc::new(ApprovalState::default());
+ let deciding = state.clone();
+ let (entered, decision_entered) = std::sync::mpsc::channel();
+ let (release, decision_release) = std::sync::mpsc::channel();
+ let decision = std::thread::spawn(move || {
+ deciding.with_live(|| {
+ entered.send(()).unwrap();
+ decision_release.recv().unwrap();
+ 7
+ })
+ });
+ decision_entered.recv().unwrap();
+ let held = matches!(
+ state.decisions.try_lock(),
+ Err(std::sync::TryLockError::WouldBlock)
+ );
+ release.send(()).unwrap();
+ assert_eq!(decision.join().unwrap(), Some(7));
+ assert!(
+ held,
+ "removal could claim while a decision was still being applied"
+ );
+ assert!(state.claim_removal());
+ let mut ran = false;
+ assert_eq!(state.with_live(|| ran = true), None);
+ assert!(!ran);
+}
diff --git a/crates/openhuman-embed/src/agent/mod.rs b/crates/openhuman-embed/src/agent/mod.rs
index 9d3c52e064..61d178dfd6 100644
--- a/crates/openhuman-embed/src/agent/mod.rs
+++ b/crates/openhuman-embed/src/agent/mod.rs
@@ -264,7 +264,12 @@ impl Agent {
/// Subscribe a host callback to this agent’s pending approvals.
/// Removing the agent cancels its callbacks, even if its id is reused.
pub fn handle_approvals(&self, handler: Arc<dyn ApprovalHandler>) -> ApprovalSubscription {
- ApprovalSubscription::new(self.id(), handler, self.inner.lifecycle.removed())
+ ApprovalSubscription::new(
+ self.id(),
+ handler,
+ self.inner.lifecycle.removed(),
+ self.inner.lifecycle.approval_state(),
+ )
}
/// Add, replace, or remove an agent-local post-turn hook by name.
@@ -280,7 +285,11 @@ impl Agent {
/// This agent's pending approvals: the requests its turns parked, and
/// only those.
pub fn approvals(&self) -> Approvals {
- Approvals::new(&self.inner.id, self.inner.lifecycle.removed())
+ Approvals::new(
+ &self.inner.id,
+ self.inner.lifecycle.removed(),
+ self.inner.lifecycle.approval_state(),
+ )
}
/// The agent's read/write root for acting tools.
diff --git a/crates/openhuman-embed/tests/agent_lifecycle.rs b/crates/openhuman-embed/tests/agent_lifecycle.rs
index 408b7f94f1..7e1169153c 100644
--- a/crates/openhuman-embed/tests/agent_lifecycle.rs
+++ b/crates/openhuman-embed/tests/agent_lifecycle.rs
@@ -140,7 +140,7 @@ fn removing_an_agent_releases_everything_it_held() {
// snapshot. Its retained context must refuse registration entirely.
let gate = openhuman_core::security::approval::ApprovalGate::try_global().unwrap();
let late = tokio::time::timeout(
- Duration::from_millis(500),
+ Duration::from_secs(10),
openhuman_core::core::runtime::CoreContext::scope(
old_context,
openhuman_core::agent::turn_origin::with_origin(
diff --git a/docs/TEST-COVERAGE-MATRIX.md b/docs/TEST-COVERAGE-MATRIX.md
index 89398dc9ba..565349f5a3 100644
--- a/docs/TEST-COVERAGE-MATRIX.md
+++ b/docs/TEST-COVERAGE-MATRIX.md
@@ -659,7 +659,7 @@ The thread JSONL store moved to `tinyagents_session::threads` (`vendor/tinyagent
| 16.1.8 | MCP servers declared programmatically | RU | `crates/openhuman-embed/src/harness/mcp_tests.rs` | ✅ | stdio/HTTP transports mutually exclusive, enabled by default, env accumulation, allow/deny filters, auth carried through |
| 16.1.9 | Skill bundles installed into the workspace | RU | `crates/openhuman-embed/src/harness/skills_tests.rs` | ✅ | Copied not linked (discovery rejects symlinked bundles and manifests by design); symlinks skipped both as bundles and inside them; `Inherit` refuses the copy |
| 16.1.10 | One runtime per process | RU+RI | `crates/openhuman-embed/src/runtime/builder_tests.rs`, `crates/openhuman-embed/tests/harness_embed.rs` | ✅ | A second `Runtime` (or `Harness`) returns `AlreadyRunning` rather than sharing process-global keyring/event-bus/subscribers; a failed build releases the slot so a retry is possible |
-| 16.1.11 | Many agents on one runtime | RU+RI | `crates/openhuman-embed/src/agent/spec_tests.rs`, `crates/openhuman-embed/tests/runtime_agents.rs`, `crates/openhuman-embed/tests/agent_lifecycle.rs`, `crates/openhuman-core/src/security/approval/registration_scope_tests.rs` | ✅ | Three agents with different providers, access tiers, skills, MCP servers and action dirs; turns land on their own provider; per-agent MCP visibility; thread-scoped resume; duplicate/invalid ids and widening are refused; removal settles pending approvals with `agent_removed` before cancelling turns; a claimed removal immediately refuses new admission; instance-owned approval registration closes before the denial snapshot and rejects late registrations without persisting rows |
+| 16.1.11 | Many agents on one runtime | RU+RI | `crates/openhuman-embed/src/agent/spec_tests.rs`, `crates/openhuman-embed/tests/runtime_agents.rs`, `crates/openhuman-embed/tests/agent_lifecycle.rs`, `crates/openhuman-core/src/security/approval/registration_scope_tests.rs`, `crates/openhuman-embed/src/agent/lifecycle_tests.rs` | ✅ | Three agents with different providers, access tiers, skills, MCP servers and action dirs; turns land on their own provider; per-agent MCP visibility; thread-scoped resume; duplicate/invalid ids and widening are refused; removal settles pending approvals with `agent_removed` before cancelling turns; a claimed removal immediately refuses new admission; instance-owned approval registration closes before the denial snapshot and rejects late registrations without persisting rows; polling and callback approval decisions serialize with the removal claim |
| 16.1.12 | API-key credential for library mode | RU+RI | `crates/openhuman-core/src/security/credentials/api_key_tests.rs`, `crates/openhuman-embed/tests/runtime_agents.rs` | ✅ | Key stored as an `api-key` auth profile; wins over an expired session; managed inference sends it as a bearer with no `x-api-key`; auth state reports `credential = "api-key"` |
| 16.1.14 | Host-backed read-only repository toolset | RI | `crates/openhuman-embed/tests/repository_tools.rs`, `crates/openhuman-embed/tests/repository_host_only.rs` | ✅ | Validated tree/range/search/symbol/git queries delegate only to the host; mandatory redaction, fenced bounded output, sanitized failures, and real HostOnly + readonly + untrusted-input refusal of shell/write/network. |
| 16.1.15 | Strict structured output and bounded repair | RI | `crates/openhuman-embed/tests/structured_validation.rs`, `crates/openhuman-embed/tests/structured_turns.rs`, `crates/openhuman-embed/tests/unit/turn_usage.rs` | ✅ | Wrong types and numeric combinators refused, invalid/external schemas make no call, repair bounded with usage, terminal length rejected even for complete JSON; successful charged usage reaches outcome/meter, invalid buyer charges stay unknown, root overlays retain child spend and session context. |