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
feat(profiles): serialize profile turns with a turn gate
Steven Enamakel00d6ec109c68
diff --git a/crates/openhuman-core/src/channels/providers/relay/ops.rs b/crates/openhuman-core/src/channels/providers/relay/ops.rsindex 43d5a83279..32f295b8ba 100644--- a/crates/openhuman-core/src/channels/providers/relay/ops.rs+++ b/crates/openhuman-core/src/channels/providers/relay/ops.rs@@ -87,6 +87,8 @@ pub(crate) async fn run_relay_turn(thread_id: String,request_id: String,) -> Vec<String> {+ // One turn at a time per profile: wait behind its chat and cron turns.+ let _turn = crate::profiles::turn_gate::acquire().await;let workspace_dir = config.workspace_dir.clone();// The thread is busy for the whole turn, so a background result due on it// waits instead of landing mid-turn. The pipeline's session id does notdiff --git a/crates/openhuman-core/src/profiles/cron.rs b/crates/openhuman-core/src/profiles/cron.rsindex ea2e07ae88..a79836f470 100644--- a/crates/openhuman-core/src/profiles/cron.rs+++ b/crates/openhuman-core/src/profiles/cron.rs@@ -98,6 +98,9 @@ pub async fn sweep(host: &ProfileHost, now: DateTime<Utc>) -> SweepReport {report.skipped += due.len();continue;}+ // The profile's turn gate, taken before the occurrences are claimed so+ // a wait behind a live chat turn does not eat into the claim lease.+ let turn = super::turn_gate::acquire_profile(id.as_str()).await;let mut claimed = Vec::new();for job in due {match claims::claim_occurrence(docs.as_ref(), &job, host.node(), now).await {@@ -138,6 +141,7 @@ pub async fn sweep(host: &ProfileHost, now: DateTime<Utc>) -> SweepReport {}}).await;+ drop(turn);if outcome {report.ran += count;} else {diff --git a/crates/openhuman-core/src/profiles/mod.rs b/crates/openhuman-core/src/profiles/mod.rsindex f568a405bb..b299908437 100644--- a/crates/openhuman-core/src/profiles/mod.rs+++ b/crates/openhuman-core/src/profiles/mod.rs@@ -39,6 +39,7 @@ pub mod registry;pub mod schemas;pub mod surface;pub mod tools;+pub mod turn_gate;pub mod types;pub use host::{current, Profile, ProfileHost};diff --git a/crates/openhuman-core/src/profiles/turn_gate.rs b/crates/openhuman-core/src/profiles/turn_gate.rsnew file mode 100644index 0000000000..9ac7fd032d--- /dev/null+++ b/crates/openhuman-core/src/profiles/turn_gate.rs@@ -0,0 +1,47 @@+//! One turn at a time per hosted profile.+//!+//! A profile's chat turns, relayed-message turns and scheduled cron runs all+//! work the same conversation state, memory and workspace, and the host cannot+//! order them from outside because the cron sweep runs inside OpenHuman. Each+//! of them therefore takes the profile's gate for the whole turn+//! ([`acquire`]): turns of one profile queue behind each other, turns of+//! different profiles never contend.+//!+//! Work with no profile (the desktop, single-user embedded agents) is not+//! gated.+//!+//! The gate is a process-wide table keyed by profile id; an entry is a bare+//! mutex that lives for the life of the process.++use std::collections::HashMap;+use std::sync::{Arc, Mutex, OnceLock};++use tokio::sync::{Mutex as AsyncMutex, OwnedMutexGuard};++/// Held for the duration of one turn; dropping it lets the next one start.+pub type TurnGuard = OwnedMutexGuard<()>;++fn gates() -> &'static Mutex<HashMap<String, Arc<AsyncMutex<()>>>> {+ static GATES: OnceLock<Mutex<HashMap<String, Arc<AsyncMutex<()>>>>> = OnceLock::new();+ GATES.get_or_init(Default::default)+}++/// Wait for `profile`'s turn gate.+pub async fn acquire_profile(profile: &str) -> TurnGuard {+ let gate = {+ let mut gates = gates().lock().unwrap_or_else(|e| e.into_inner());+ Arc::clone(gates.entry(profile.to_owned()).or_default())+ };+ gate.lock_owned().await+}++/// Wait for the gate of the profile the calling task runs for, or return+/// `None` at once when it runs for no profile.+pub async fn acquire() -> Option<TurnGuard> {+ let profile = crate::core::runtime::current_tenant().ok()?.profile?;+ Some(acquire_profile(&profile).await)+}++#[cfg(test)]+#[path = "turn_gate_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/profiles/turn_gate_tests.rs b/crates/openhuman-core/src/profiles/turn_gate_tests.rsnew file mode 100644index 0000000000..2e65ef4ebf--- /dev/null+++ b/crates/openhuman-core/src/profiles/turn_gate_tests.rs@@ -0,0 +1,31 @@+//! The turn gate queues one profile's turns and leaves other profiles alone.++use std::time::Duration;++use super::*;++#[tokio::test]+async fn a_profile_runs_one_turn_at_a_time() {+ let first = acquire_profile("gate-a").await;+ let second = tokio::spawn(acquire_profile("gate-a"));+ tokio::time::sleep(Duration::from_millis(50)).await;+ assert!(!second.is_finished(), "the second turn waits for the first");+ drop(first);+ tokio::time::timeout(Duration::from_secs(5), second)+ .await+ .expect("released gate admits the next turn")+ .unwrap();+}++#[tokio::test]+async fn other_profiles_are_not_held_up() {+ let _held = acquire_profile("gate-b").await;+ tokio::time::timeout(Duration::from_secs(5), acquire_profile("gate-c"))+ .await+ .expect("a different profile's gate is free");+}++#[tokio::test]+async fn work_without_a_profile_is_not_gated() {+ assert!(acquire().await.is_none());+}diff --git a/crates/openhuman-core/src/web_chat/run_task.rs b/crates/openhuman-core/src/web_chat/run_task.rsindex a7fbc4aae2..ef2de109bf 100644--- a/crates/openhuman-core/src/web_chat/run_task.rs+++ b/crates/openhuman-core/src/web_chat/run_task.rs@@ -43,6 +43,9 @@ pub(crate) async fn run_chat_task(// clobbered by — the primary turn's cached agent. See `QueueMode::Parallel`.fork: bool,) -> Result<WebChatTaskResult, String> {+ // One turn at a time per profile: wait behind its relay and cron turns.+ let _turn = crate::profiles::turn_gate::acquire().await;+#[cfg(any(test, debug_assertions))]{let mut slot = TEST_FORCED_RUN_CHAT_TASK_ERROR.lock().await;diff --git a/crates/openhuman-embed/tests/profile_turn_serialization.rs b/crates/openhuman-embed/tests/profile_turn_serialization.rsnew file mode 100644index 0000000000..e677ba97a1--- /dev/null+++ b/crates/openhuman-embed/tests/profile_turn_serialization.rs@@ -0,0 +1,146 @@+//! One profile runs one turn at a time: a due cron job waits for the profile's+//! in-flight chat turn instead of running beside it, while another profile's+//! turn is not held up. One runtime and one test: SaaS operating mode is+//! process-wide.++mod common;++use std::sync::{Arc, Mutex};+use std::time::{Duration, Instant};++use common::{chat_completion, last_user_message, runtime_without_master_key, PointedTransport};+use openhuman_core::cron::{self, AgentJobSpec, Schedule};+use openhuman_embed::profiles::ProfileCredentialKind;+use openhuman_embed::{ProfileRuntime, SaasConfig};+use wiremock::{Mock, Request, Respond, ResponseTemplate};++/// How long the slow chat turn's model request takes to answer.+const SLOW: Duration = Duration::from_millis(2500);++/// Records when each marked prompt's model request arrived. Prompts containing+/// `slow` are answered after [`SLOW`]; the rest at once.+#[derive(Clone, Default)]+struct Arrivals(Arc<Mutex<Vec<(String, Instant)>>>);++impl Arrivals {+ fn at(&self, marker: &str) -> Option<Instant> {+ self.0+ .lock()+ .unwrap()+ .iter()+ .find(|(prompt, _)| prompt.contains(marker))+ .map(|(_, at)| *at)+ }++ async fn wait_for(&self, marker: &str) -> Instant {+ for _ in 0..600 {+ if let Some(at) = self.at(marker) {+ return at;+ }+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+ panic!("no model request for {marker:?}");+ }+}++impl Respond for Arrivals {+ fn respond(&self, request: &Request) -> ResponseTemplate {+ let body: serde_json::Value = serde_json::from_slice(&request.body).unwrap();+ let prompt = last_user_message(&body);+ self.0.lock().unwrap().push((prompt.clone(), Instant::now()));+ let reply = ResponseTemplate::new(200).set_body_json(chat_completion("ok"));+ if prompt.contains("slow") {+ reply.set_delay(SLOW)+ } else {+ reply+ }+ }+}++#[test]+fn a_profiles_cron_run_waits_for_its_chat_turn_but_other_profiles_do_not() {+ runtime_without_master_key().block_on(async {+ tokio::spawn(scenario()).await.unwrap();+ });+}++async fn scenario() {+ let arrivals = Arrivals::default();+ let inference = wiremock::MockServer::start().await;+ Mock::given(wiremock::matchers::path_regex(r"chat/completions$"))+ .respond_with(arrivals.clone())+ .with_priority(1)+ .mount(&inference)+ .await;+ Mock::given(wiremock::matchers::any())+ .respond_with(+ ResponseTemplate::new(200).set_body_json(serde_json::json!({"success":true,"data":[]})),+ )+ .with_priority(10)+ .mount(&inference)+ .await;+ PointedTransport::install(&inference.uri());+ openhuman_core::storage::install(Arc::new(openhuman_core::storage::MemoryStorage::new()));++ let root = tempfile::tempdir().unwrap();+ let runtime = ProfileRuntime::builder(SaasConfig::new(root.path()))+ .configure(|config| config.lease_ttl_secs = 3600)+ .build()+ .await+ .unwrap();++ let mut handles = Vec::new();+ for user in ["alice", "bob"] {+ let provisioned = runtime.provision(user).await.unwrap();+ runtime+ .set_credential(+ &provisioned.profile_id,+ ProfileCredentialKind::ApiKey,+ "fixture-key",+ )+ .await+ .unwrap();+ handles.push(runtime.open(user).await.unwrap());+ }+ let (alice, bob) = (handles.remove(0), handles.remove(0));++ // Alice has a cron job that will be due.+ let soon = chrono::Utc::now() + chrono::Duration::seconds(5);+ let config = alice.context().embedder_config().unwrap().clone();+ alice+ .scope(async {+ let spec = AgentJobSpec::new(Schedule::At { at: soon }, "alice cron".to_string());+ cron::add_agent_job_from_spec(&config, spec).unwrap();+ })+ .await;++ // Alice's chat turn is mid-model-call when the sweep fires.+ let chat = tokio::spawn({+ let alice = alice.clone();+ async move { alice.chat("t1", "alice slow chat").await }+ });+ let chat_started = arrivals.wait_for("alice slow chat").await;++ // Another profile is not held up by Alice's turn.+ tokio::time::timeout(Duration::from_secs(60), bob.chat("t1", "bob chat"))+ .await+ .expect("bob's turn finishes")+ .expect("bob's turn");+ assert!(+ chat_started.elapsed() < SLOW,+ "bob's turn must finish while alice's is still in flight"+ );+ assert!(!chat.is_finished(), "alice's turn is still running");++ // The sweep runs Alice's job, but only once her chat turn is over.+ let later = chrono::Utc::now() + chrono::Duration::hours(1);+ let report = runtime.sweep_cron_at(later).await;+ assert_eq!(report.ran, 1, "the occurrence is deferred, not skipped: {report:?}");+ let cron_started = arrivals.wait_for("alice cron").await;+ assert!(+ cron_started >= chat_started + SLOW,+ "the cron run started {:?} after the chat turn began; it must wait {SLOW:?}",+ cron_started.duration_since(chat_started)+ );+ chat.await.unwrap().expect("alice's chat turn");+}