Skip to content

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

fix(embed): preserve completed dispatches and close removal admission

Steven Enamakeld73443617e75
diff --git a/crates/openhuman-embed/src/agent/lifecycle.rs b/crates/openhuman-embed/src/agent/lifecycle.rs
index 5bc8e22a2e..1c4eccdc96 100644
--- a/crates/openhuman-embed/src/agent/lifecycle.rs
+++ b/crates/openhuman-embed/src/agent/lifecycle.rs
@@ -64,7 +64,9 @@ impl Lifecycle {
agent_id: agent_id.to_string(),
};
let mut watcher = self.removed.subscribe();
- if *watcher.borrow_and_update() {
+ // 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() {
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 be547d2a09..2505ec4b8f 100644
--- a/crates/openhuman-embed/src/agent/lifecycle_tests.rs
+++ b/crates/openhuman-embed/src/agent/lifecycle_tests.rs
@@ -55,3 +55,32 @@ fn teardown_is_claimed_once() {
assert!(lifecycle.begin_teardown());
assert!(!lifecycle.begin_teardown());
}
+
+#[tokio::test]
+async fn a_claimed_removal_refuses_turns_before_approvals_are_settled() {
+ let lifecycle = Arc::new(Lifecycle::new());
+ 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 ran = AtomicBool::new(false);
+ let outcome = lifecycle
+ .admit("a", "test", async {
+ ran.store(true, Ordering::SeqCst);
+ Ok(())
+ })
+ .await;
+ release.send(()).unwrap();
+ assert!(removal.join().unwrap());
+ assert!(removed(outcome));
+ assert!(
+ !ran.load(Ordering::SeqCst),
+ "removal admitted a new turn while settling approvals"
+ );
+}
diff --git a/crates/openhuman-embed/src/turn_control.rs b/crates/openhuman-embed/src/turn_control.rs
index 6976449cd1..bcfa0aca63 100644
--- a/crates/openhuman-embed/src/turn_control.rs
+++ b/crates/openhuman-embed/src/turn_control.rs
@@ -229,18 +229,7 @@ impl Turn {
Err(CoreError::DeadlineExceeded { method: AGENT_CHAT })
},
outcome = Box::pin(self.send_inner(&meter.usage)) => {
- // The relay can interrupt a long dispatch poll before
- // this select polls its control branches again. Keep
- // the public error tied to the triggering control.
- if token.as_ref().is_some_and(|token| token.is_cancelled())
- || cancellation.is_cancelled()
- {
- Err(CoreError::TurnCancelled { method: AGENT_CHAT })
- } else if deadline.is_some_and(|deadline| tokio::time::Instant::now() >= deadline) {
- Err(CoreError::DeadlineExceeded { method: AGENT_CHAT })
- } else {
- outcome
- }
+ controlled_outcome(outcome, &native, token.as_ref(), &cancellation, deadline)
},
}
})
@@ -525,3 +514,33 @@ impl Turn {
Ok(())
}
}
+
+// Classify the result at the control boundary after a native dispatch poll.
+fn controlled_outcome<T>(
+ outcome: Result<T, CoreError>,
+ native: &crate::CancellationToken,
+ token: Option<&crate::CancellationToken>,
+ cancellation: &crate::TurnCancellation,
+ deadline: Option<tokio::time::Instant>,
+) -> Result<T, CoreError> {
+ // The native session runtime currently crosses the RPC boundary as this
+ // cancellation error. Only that interrupted dispatch needs classification;
+ // completed replies and unrelated failures retain their original result.
+ let interrupted = native.is_cancelled()
+ && matches!(&outcome, Err(CoreError::Rpc { method, message })
+ if *method == AGENT_CHAT && message == "session turn cancelled");
+ if !interrupted {
+ return outcome;
+ }
+ if token.is_some_and(|token| token.is_cancelled()) || cancellation.is_cancelled() {
+ Err(CoreError::TurnCancelled { method: AGENT_CHAT })
+ } else if deadline.is_some_and(|deadline| tokio::time::Instant::now() >= deadline) {
+ Err(CoreError::DeadlineExceeded { method: AGENT_CHAT })
+ } else {
+ outcome
+ }
+}
+
+#[cfg(test)]
+#[path = "turn_control_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-embed/src/turn_control_tests.rs b/crates/openhuman-embed/src/turn_control_tests.rs
new file mode 100644
index 0000000000..4d95009fe8
--- /dev/null
+++ b/crates/openhuman-embed/src/turn_control_tests.rs
@@ -0,0 +1,48 @@
+//! Completed dispatches retain their outcome when control arrives afterward.
+use super::*;
+
+#[tokio::test]
+async fn completed_replies_survive_later_cancellation() {
+ let native = crate::CancellationToken::new();
+ let token = crate::CancellationToken::new();
+ let handle = crate::TurnCancellation::default();
+ let reply = Ok("completed reply");
+ token.cancel();
+ native.cancel();
+ handle.cancel().await;
+ assert_eq!(
+ controlled_outcome(reply, &native, Some(&token), &handle, None).unwrap(),
+ "completed reply"
+ );
+}
+
+#[test]
+fn completed_failures_survive_later_deadlines() {
+ let native = crate::CancellationToken::new();
+ native.cancel();
+ let outcome = controlled_outcome::<()>(
+ Err(CoreError::InvalidRoute { method: AGENT_CHAT }),
+ &native,
+ None,
+ &crate::TurnCancellation::default(),
+ Some(tokio::time::Instant::now()),
+ );
+ assert!(matches!(outcome, Err(CoreError::InvalidRoute { .. })));
+}
+
+#[test]
+fn a_native_cancelled_dispatch_keeps_the_deadline_reason() {
+ let native = crate::CancellationToken::new();
+ native.cancel();
+ let outcome = controlled_outcome::<()>(
+ Err(CoreError::Rpc {
+ method: AGENT_CHAT,
+ message: "session turn cancelled".into(),
+ }),
+ &native,
+ None,
+ &crate::TurnCancellation::default(),
+ Some(tokio::time::Instant::now()),
+ );
+ assert!(matches!(outcome, Err(CoreError::DeadlineExceeded { .. })));
+}
diff --git a/docs/TEST-COVERAGE-MATRIX.md b/docs/TEST-COVERAGE-MATRIX.md
index 6680585297..e827603f76 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` | ✅ | 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 |
+| 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` | ✅ | 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 |
| 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. |
@@ -667,7 +667,7 @@ The thread JSONL store moved to `tinyagents_session::threads` (`vendor/tinyagent
| 16.1.19 | Pinned standalone Embed source consumer | Script+RI | `scripts/__tests__/embed-consumer-bootstrap.test.mjs` | ✅ | Exact SHA verification, inherited workspace edition, generated active patches, stable locked offline builds with optional Embed enabled/disabled, default dependency tree without HTTP, no untracked secrets or Git metadata, refused malformed/escaping patches and existing destinations |
| 16.1.17 | Enforced shared turn/run budgets | RU+RI | `crates/openhuman-embed/tests/budget_fanout.rs`, `vendor/tinyagents/vendor/tinyinference/crates/tinyinference-llm/src/model/budget_tests.rs` | ✅ | Atomic parent/child reservations, physical provider admission, conservative unknown spend, cancellation and output cap |
| 16.1.18 | Ordered bounded fanout | RI | `crates/openhuman-embed/tests/budget_fanout.rs` | ✅ | Input-order results, per-branch and child error isolation, branch ceilings, shared-budget concurrent refusal and empty fanout |
-| 16.1.13 | Awaited per-turn cancellation | RI | `crates/openhuman-embed/tests/turn_cancellation.rs`, `crates/openhuman-embed/tests/process_cancellation.rs` | ✅ | Before send, during inference and during a builtin shell command; agent reuse, concurrent cancellation handles, failure/drop acknowledgement, bounded and unbounded descendant termination plus direct-child reaping on Linux; deadline errors stay typed when the native cancellation relay interrupts dispatch |
+| 16.1.13 | Awaited per-turn cancellation | RU+RI | `crates/openhuman-embed/tests/turn_cancellation.rs`, `crates/openhuman-embed/tests/process_cancellation.rs`, `crates/openhuman-embed/src/turn_control_tests.rs` | ✅ | Before send, during inference and during a builtin shell command; agent reuse, concurrent cancellation handles, failure/drop acknowledgement, bounded and unbounded descendant termination plus direct-child reaping on Linux; deadline errors stay typed when the native cancellation relay interrupts dispatch; later cancellation/deadlines do not replace completed outcomes |
| 16.1.21 | Agent and turn hook isolation | RI | `crates/openhuman-embed/tests/scoped_hooks.rs` | ✅ | Additive same-named callbacks, overlapping worker turns, one-turn callback lifetime, resumed-session snapshots, core-scheduled turn callbacks and reuse of a removed agent id without registry leakage |
| 16.1.22 | Agent-turn route attribution headers | RU+RI | `crates/openhuman-embed/tests/route_headers.rs`, `crates/openhuman-embed/src/turn_tests.rs` | ✅ | Per-route headers reach only the named endpoint and turn, remain absent on other agents and backend requests, and are redacted in Debug; wire fields pinned against the registered controller schema |
| 16.1.23 | Tool-hook turn identity and cwd | RU+RI | `crates/openhuman-embed/tests/tool_hook_context.rs`, `crates/openhuman-core/src/hooks/bridge_tests.rs` | ✅ | Before and after hooks report the worker/session and working root used by builtin shell; a later turn returns to its agent default; configured hooks use resolved cwd even when tool arguments omit it |