Skip to content

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

feat(runtime): add scoped task spawn helpers

Steven Enamakele63affee9f4d
diff --git a/crates/openhuman-core/src/core/runtime/mod.rs b/crates/openhuman-core/src/core/runtime/mod.rs
index 0cc4ba8c6b..b9d55dfc7a 100644
--- a/crates/openhuman-core/src/core/runtime/mod.rs
+++ b/crates/openhuman-core/src/core/runtime/mod.rs
@@ -51,9 +51,11 @@ pub mod domain_set;
pub mod mode;
pub mod saas;
pub mod services;
+pub mod spawn;
pub(crate) mod subscribers;
pub use builder::{CoreBuilder, CoreRuntime, DomainSet, ServiceSet, TokenSource};
pub use context::{ContextOverlay, CoreContext};
pub use mode::{current_mode, is_saas, Mode};
pub use saas::SaasConfig;
+pub use spawn::{spawn_blocking_scoped, spawn_scoped};
diff --git a/crates/openhuman-core/src/core/runtime/spawn.rs b/crates/openhuman-core/src/core/runtime/spawn.rs
new file mode 100644
index 0000000000..e1931fa5e0
--- /dev/null
+++ b/crates/openhuman-core/src/core/runtime/spawn.rs
@@ -0,0 +1,64 @@
+//! Spawning tasks without dropping who they work for.
+//!
+//! The ambient [`CoreContext`] and the memory identity are tokio task-locals,
+//! so a bare `tokio::spawn` starts its task with neither: the child falls back
+//! to the process default context and the root memory identity. In a
+//! single-user process that default is the right user by accident. In a SaaS
+//! process it is the operator, so a dropped scope writes one user's work
+//! somewhere it does not belong — or, with the SaaS config redirect, fails.
+//!
+//! [`spawn_scoped`] captures both at the call site and re-enters them in the
+//! child. New code in the core spawns through it; `scripts/ci/check-saas-ambient.mjs`
+//! ratchets the bare spawns that remain.
+
+use std::future::Future;
+
+use tokio::task::JoinHandle;
+
+use super::CoreContext;
+
+/// Like `tokio::spawn`, but the task keeps the caller's [`CoreContext`] and
+/// memory identity.
+pub fn spawn_scoped<F>(fut: F) -> JoinHandle<F::Output>
+where
+ F: Future + Send + 'static,
+ F::Output: Send + 'static,
+{
+ tokio::spawn(scoped(fut))
+}
+
+/// `fut`, wrapped to run under the caller's context and memory identity
+/// wherever it is eventually polled.
+pub fn scoped<F>(fut: F) -> impl Future<Output = F::Output> + Send
+where
+ F: Future + Send,
+ F::Output: Send,
+{
+ let identity = crate::memory::scope::current();
+ let fut = CoreContext::propagate(fut);
+ async move {
+ match identity {
+ Some(identity) => crate::memory::scope::within(identity, fut).await,
+ None => fut.await,
+ }
+ }
+}
+
+/// Like `tokio::task::spawn_blocking`, but the closure runs under the caller's
+/// [`CoreContext`].
+pub fn spawn_blocking_scoped<F, R>(f: F) -> JoinHandle<R>
+where
+ F: FnOnce() -> R + Send + 'static,
+ R: Send + 'static,
+{
+ let ctx = CoreContext::current();
+ let handle = tokio::runtime::Handle::current();
+ tokio::task::spawn_blocking(move || match ctx {
+ Some(ctx) => handle.block_on(CoreContext::scope(ctx, async move { f() })),
+ None => f(),
+ })
+}
+
+#[cfg(test)]
+#[path = "spawn_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/core/runtime/spawn_tests.rs b/crates/openhuman-core/src/core/runtime/spawn_tests.rs
new file mode 100644
index 0000000000..651a0bd963
--- /dev/null
+++ b/crates/openhuman-core/src/core/runtime/spawn_tests.rs
@@ -0,0 +1,63 @@
+use super::*;
+use crate::core::runtime::{ContextOverlay, DomainSet};
+use crate::memory::scope::MemoryIdentity;
+
+fn agent_context(agent: &str) -> std::sync::Arc<CoreContext> {
+ CoreContext::for_test(DomainSet::full(), None).derive_with(
+ ContextOverlay::new(
+ crate::config::Config::default(),
+ DomainSet::full(),
+ Default::default(),
+ )
+ .session_agent(agent),
+ )
+}
+
+fn seen() -> (Option<String>, Option<String>) {
+ (
+ CoreContext::current().and_then(|c| c.session_agent().map(str::to_owned)),
+ crate::memory::scope::current().and_then(|i| i.agent_id),
+ )
+}
+
+#[tokio::test]
+async fn a_bare_spawn_loses_the_scope_and_spawn_scoped_keeps_it() {
+ let ctx = agent_context("u-asha");
+ CoreContext::scope(ctx, async {
+ crate::memory::scope::within(MemoryIdentity::agent("orchestrator"), async {
+ let bare = tokio::spawn(async { seen() }).await.unwrap();
+ assert_ne!(
+ bare.0.as_deref(),
+ Some("u-asha"),
+ "a bare spawn falls back to the default context"
+ );
+ assert_eq!(bare.1, None, "and to no memory identity");
+
+ let scoped = spawn_scoped(async { seen() }).await.unwrap();
+ assert_eq!(scoped.0.as_deref(), Some("u-asha"));
+ assert_eq!(scoped.1.as_deref(), Some("orchestrator"));
+ })
+ .await;
+ })
+ .await;
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn spawn_blocking_scoped_keeps_the_context() {
+ let ctx = agent_context("u-ravi");
+ let agent = CoreContext::scope(ctx, async {
+ spawn_blocking_scoped(|| {
+ CoreContext::current().and_then(|c| c.session_agent().map(str::to_owned))
+ })
+ .await
+ .unwrap()
+ })
+ .await;
+ assert_eq!(agent.as_deref(), Some("u-ravi"));
+}
+
+#[tokio::test]
+async fn outside_any_scope_spawn_scoped_is_a_plain_spawn() {
+ let (_, identity) = spawn_scoped(async { seen() }).await.unwrap();
+ assert_eq!(identity, None);
+}