Skip to content

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

feat(agent): add session lease module

Steven Enamakelb4933fabb7c2
diff --git a/crates/openhuman-core/src/agent/mod.rs b/crates/openhuman-core/src/agent/mod.rs
index 54c0476fb6..96dbea5d3a 100644
--- a/crates/openhuman-core/src/agent/mod.rs
+++ b/crates/openhuman-core/src/agent/mod.rs
@@ -68,6 +68,9 @@ pub mod session_db;
/// snapshots are owned by `tinyagents-runtime`.
pub mod session_host;
pub mod session_import;
+/// Shared keyed leases preventing distinct host runners from checking out the
+/// same durable conversation concurrently.
+pub(crate) mod session_lease;
pub mod session_store;
pub mod stop_hooks;
/// Product-specific adapters around `tinyagents_orchestration::subagent`.
diff --git a/crates/openhuman-core/src/agent/session_lease.rs b/crates/openhuman-core/src/agent/session_lease.rs
new file mode 100644
index 0000000000..969c0644d4
--- /dev/null
+++ b/crates/openhuman-core/src/agent/session_lease.rs
@@ -0,0 +1,71 @@
+//! Cross-runner serialization for one durable agent session.
+//!
+//! TinyAgents serializes turns inside a `TurnRunner`, but inbound surfaces can
+//! own separate runner instances. This lease coordinates those instances at
+//! the host boundary, keyed by the complete tenant, agent, and canonical
+//! session identity.
+
+use std::{collections::HashMap, sync::{Arc, LazyLock, Mutex, Weak}};
+
+use tinyagents_harness::CancellationToken;
+use tokio::sync::{Mutex as AsyncMutex, OwnedMutexGuard};
+
+#[derive(Clone, Debug, Eq, Hash, PartialEq)]
+pub(crate) struct SessionLeaseKey {
+ tenant: String,
+ agent: String,
+ session: String,
+}
+
+impl SessionLeaseKey {
+ pub(crate) fn new(tenant: impl Into<String>, agent: impl Into<String>, session: impl Into<String>) -> Self {
+ Self { tenant: tenant.into(), agent: agent.into(), session: session.into() }
+ }
+}
+
+static LEASES: LazyLock<Mutex<HashMap<SessionLeaseKey, Weak<AsyncMutex<()>>>>> =
+ LazyLock::new(|| Mutex::new(HashMap::new()));
+
+/// An owned guard keeps serialization active across async turn work and can be
+/// stored in a request slot until its surface has completed delivery.
+pub(crate) struct SessionLease {
+ _guard: OwnedMutexGuard<()>,
+}
+
+impl SessionLease {
+ pub(crate) async fn acquire(
+ key: SessionLeaseKey,
+ cancellation: Option<&CancellationToken>,
+ ) -> Result<Self, ()> {
+ let lock = {
+ let mut leases = LEASES.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
+ leases.retain(|_, lock| lock.strong_count() > 0);
+ if let Some(lock) = leases.get(&key).and_then(Weak::upgrade) {
+ lock
+ } else {
+ let lock = Arc::new(AsyncMutex::new(()));
+ leases.insert(key, Arc::downgrade(&lock));
+ lock
+ }
+ };
+ let guard = match cancellation {
+ Some(token) => tokio::select! {
+ biased;
+ _ = token.cancelled() => return Err(()),
+ guard = lock.lock_owned() => guard,
+ },
+ None => lock.lock_owned().await,
+ };
+ Ok(Self { _guard: guard })
+ }
+}
+
+impl std::fmt::Debug for SessionLease {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("SessionLease").field("held", &true).finish()
+ }
+}
+
+#[cfg(test)]
+#[path = "session_lease_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/agent/session_lease_tests.rs b/crates/openhuman-core/src/agent/session_lease_tests.rs
new file mode 100644
index 0000000000..960804ea9e
--- /dev/null
+++ b/crates/openhuman-core/src/agent/session_lease_tests.rs
@@ -0,0 +1,70 @@
+use super::*;
+
+#[tokio::test]
+async fn independent_runners_serialize_the_same_tenant_agent_session() {
+ let key = SessionLeaseKey::new("tenant-a", "agent-a", "session-a");
+ let first = SessionLease::acquire(key.clone(), None)
+ .await
+ .expect("first runner acquires the session");
+ let cancellation = CancellationToken::new();
+ let waiting = tokio::spawn({
+ let key = key.clone();
+ let cancellation = cancellation.clone();
+ async move { SessionLease::acquire(key, Some(&cancellation)).await }
+ });
+ tokio::task::yield_now().await;
+ assert!(!waiting.is_finished(), "same identity must wait for checkout");
+
+ drop(first);
+ let second = tokio::time::timeout(std::time::Duration::from_secs(1), waiting)
+ .await
+ .expect("released session lease wakes the next runner")
+ .expect("lease task does not panic")
+ .expect("second runner acquires the released session");
+ drop(second);
+}
+
+#[tokio::test]
+async fn distinct_tenant_agent_or_session_keys_do_not_serialize() {
+ let first = SessionLease::acquire(
+ SessionLeaseKey::new("tenant-a", "agent-a", "session-a"),
+ None,
+ )
+ .await
+ .expect("first lease");
+ let second = tokio::time::timeout(
+ std::time::Duration::from_secs(1),
+ SessionLease::acquire(
+ SessionLeaseKey::new("tenant-b", "agent-a", "session-a"),
+ None,
+ ),
+ )
+ .await
+ .expect("a different tenant has independent session state")
+ .expect("second lease");
+ drop((first, second));
+}
+
+#[tokio::test]
+async fn cancelled_waiter_does_not_acquire_a_session_lease() {
+ let key = SessionLeaseKey::new("tenant-a", "agent-a", "session-a");
+ let first = SessionLease::acquire(key.clone(), None)
+ .await
+ .expect("first lease");
+ let cancellation = CancellationToken::new();
+ let waiting = tokio::spawn({
+ let key = key.clone();
+ let cancellation = cancellation.clone();
+ async move { SessionLease::acquire(key, Some(&cancellation)).await }
+ });
+ tokio::task::yield_now().await;
+ cancellation.cancel();
+ assert!(
+ tokio::time::timeout(std::time::Duration::from_secs(1), waiting)
+ .await
+ .expect("cancelled waiter completes promptly")
+ .expect("lease task does not panic")
+ .is_err()
+ );
+ drop(first);
+}