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
refactor(orchestration): extract delivery event scheduling into its own module
Steven Enamakele406fba46193
diff --git a/crates/openhuman-core/src/agent/orchestration/background_completions_migration_tests.rs b/crates/openhuman-core/src/agent/orchestration/background_completions_migration_tests.rsnew file mode 100644index 0000000000..bfc8fed9f7--- /dev/null+++ b/crates/openhuman-core/src/agent/orchestration/background_completions_migration_tests.rs@@ -0,0 +1,162 @@+use super::*;++/// A store whose writes always fail, like a full disk.+struct FullDisk(InMemoryCompletionStore);++impl CompletionStore for FullDisk {+ fn get(&self, task_id: &str) -> Option<CompletionRecord> {+ self.0.get(task_id)+ }+ fn put(&self, _record: &CompletionRecord) -> tinyagents_harness::error::Result<()> {+ Err(tinyagents_harness::error::TinyAgentsError::Graph(+ "disk full".into(),+ ))+ }+ fn list(&self, parent_key: Option<&str>) -> Vec<CompletionRecord> {+ self.0.list(parent_key)+ }+}++#[derive(Default)]+struct ToggleStore {+ inner: InMemoryCompletionStore,+ fail_writes: AtomicBool,+}++impl CompletionStore for ToggleStore {+ fn get(&self, task_id: &str) -> Option<CompletionRecord> {+ self.inner.get(task_id)+ }++ fn put(&self, record: &CompletionRecord) -> tinyagents_harness::error::Result<()> {+ if self.fail_writes.load(Ordering::SeqCst) {+ return Err(tinyagents_harness::error::TinyAgentsError::Graph(+ "disk full".into(),+ ));+ }+ self.inner.put(record)+ }++ fn list(&self, parent_key: Option<&str>) -> Vec<CompletionRecord> {+ self.inner.list(parent_key)+ }+}++#[tokio::test]+async fn a_store_that_keeps_failing_degrades_to_memory_instead_of_losing_the_result() {+ let _guard = crate::config::TEST_ENV_LOCK.lock().await;+ let ws = workspace();+ let w = ws.path();+ install_store_for_test(w, Arc::new(FullDisk(InMemoryCompletionStore::new())));++ record_completion(+ &cx(),+ w,+ "sess-fd",+ "sub-1",+ "researcher",+ "must not be lost",+ Some("thread-fd".into()),+ )+ .await;++ let pending = pending_for(w, "thread-fd");+ assert_eq!(pending.len(), 1, "the result is held in memory");+ assert_eq!(pending[0].result.text, "must not be lost");+}++#[tokio::test]+async fn reopening_a_durable_store_preserves_pending_memory_fallback_records() {+ let _guard = crate::config::TEST_ENV_LOCK.lock().await;+ let ws = workspace();+ let w = ws.path();+ install_store_for_test(w, Arc::new(FullDisk(InMemoryCompletionStore::new())));++ record_completion(+ &cx(),+ w,+ "sess-reopen",+ "memory-task",+ "researcher",+ "held in memory",+ Some("thread-reopen".into()),+ )+ .await;++ let before = pending_for(w, "thread-reopen");+ assert_eq!(before.len(), 1);+ assert_eq!(before[0].result.text, "held in memory");+ drop(before);++ let ctx = crate::core::runtime::DispatchCtx::ambient();+ forget_recovery_ctx(&ctx, w);++ let after = pending_for(w, "thread-reopen");+ assert_eq!(+ after.len(),+ 1,+ "re-opening must migrate memory-held records"+ );+ assert_eq!(after[0].result.text, "held in memory");+}++#[tokio::test]+async fn concurrent_degradation_installs_one_fallback() {+ let _guard = crate::config::TEST_ENV_LOCK.lock().await;+ let ws = workspace();+ let w = ws.path();+ let failing = router_for_workspace(w);++ // Two records saw the same failing router; both ask to degrade.+ let ctx = crate::core::runtime::DispatchCtx::ambient();+ let first = degrade_to_memory(&ctx, w, &failing);+ let second = degrade_to_memory(&ctx, w, &failing);++ assert!(+ Arc::ptr_eq(&first.router, &second.router),+ "the second caller reuses the fallback the first installed"+ );+ assert!(Arc::ptr_eq(&entry_for(w).router, &first.router));+}++#[tokio::test]+async fn degrading_a_leased_completion_keeps_its_lease() {+ let _guard = crate::config::TEST_ENV_LOCK.lock().await;+ let ws = workspace();+ let w = ws.path();+ let ctx = crate::core::runtime::DispatchCtx::ambient();+ let store = Arc::new(ToggleStore::default());+ install_store_for_test(w, store.clone());+ let router = router_for_workspace(w);+ router+ .record(CompletionRecord::new(+ "leased-task",+ "leased-thread",+ "researcher",+ CompletionStatus::Success,+ CompletionResult::text("done"),+ ))+ .await+ .expect("record completion");+ assert_eq!(router.claim_pending("leased-thread", 1).unwrap().len(), 1);+ store.fail_writes.store(true, Ordering::SeqCst);++ record_completion(+ &ctx,+ w,+ "leased-session",+ "trigger-task",+ "researcher",+ "force fallback",+ Some("leased-thread".into()),+ )+ .await;++ let claims = router_for_workspace(w)+ .claim_pending("leased-thread", 10)+ .unwrap();+ assert!(+ claims.iter().all(|record| record.task_id != "leased-task"),+ "a fallback router must not make another delivery claim while the first lease is active"+ );+}diff --git a/crates/openhuman-core/src/agent/orchestration/background_completions_tests.rs b/crates/openhuman-core/src/agent/orchestration/background_completions_tests.rsindex 5e454b5b92..df55db2170 100644--- a/crates/openhuman-core/src/agent/orchestration/background_completions_tests.rs+++ b/crates/openhuman-core/src/agent/orchestration/background_completions_tests.rs@@ -609,163 +609,5 @@ fn a_completion_for_a_removed_workspace_does_not_recreate_it() {assert!(!gone.exists(), "the workspace directory is not recreated");}-/// A store whose writes always fail, like a full disk.-struct FullDisk(InMemoryCompletionStore);--impl CompletionStore for FullDisk {- fn get(&self, task_id: &str) -> Option<CompletionRecord> {- self.0.get(task_id)- }- fn put(&self, _record: &CompletionRecord) -> tinyagents_harness::error::Result<()> {- Err(tinyagents_harness::error::TinyAgentsError::Graph(- "disk full".into(),- ))- }- fn list(&self, parent_key: Option<&str>) -> Vec<CompletionRecord> {- self.0.list(parent_key)- }-}--#[derive(Default)]-struct ToggleStore {- inner: InMemoryCompletionStore,- fail_writes: AtomicBool,-}--impl CompletionStore for ToggleStore {- fn get(&self, task_id: &str) -> Option<CompletionRecord> {- self.inner.get(task_id)- }-- fn put(&self, record: &CompletionRecord) -> tinyagents_harness::error::Result<()> {- if self.fail_writes.load(Ordering::SeqCst) {- return Err(tinyagents_harness::error::TinyAgentsError::Graph(- "disk full".into(),- ));- }- self.inner.put(record)- }-- fn list(&self, parent_key: Option<&str>) -> Vec<CompletionRecord> {- self.inner.list(parent_key)- }-}--#[tokio::test]-async fn a_store_that_keeps_failing_degrades_to_memory_instead_of_losing_the_result() {- let _guard = crate::config::TEST_ENV_LOCK.lock().await;- let ws = workspace();- let w = ws.path();- install_store_for_test(w, Arc::new(FullDisk(InMemoryCompletionStore::new())));-- record_completion(- &cx(),- w,- "sess-fd",- "sub-1",- "researcher",- "must not be lost",- Some("thread-fd".into()),- )- .await;-- let pending = pending_for(w, "thread-fd");- assert_eq!(pending.len(), 1, "the result is held in memory");- assert_eq!(pending[0].result.text, "must not be lost");-}--#[tokio::test]-async fn reopening_a_durable_store_preserves_pending_memory_fallback_records() {- let _guard = crate::config::TEST_ENV_LOCK.lock().await;- let ws = workspace();- let w = ws.path();- install_store_for_test(w, Arc::new(FullDisk(InMemoryCompletionStore::new())));-- record_completion(- &cx(),- w,- "sess-reopen",- "memory-task",- "researcher",- "held in memory",- Some("thread-reopen".into()),- )- .await;-- let before = pending_for(w, "thread-reopen");- assert_eq!(before.len(), 1);- assert_eq!(before[0].result.text, "held in memory");- drop(before);-- let ctx = crate::core::runtime::DispatchCtx::ambient();- forget_recovery_ctx(&ctx, w);-- let after = pending_for(w, "thread-reopen");- assert_eq!(- after.len(),- 1,- "re-opening must migrate memory-held records"- );- assert_eq!(after[0].result.text, "held in memory");-}--#[tokio::test]-async fn concurrent_degradation_installs_one_fallback() {- let _guard = crate::config::TEST_ENV_LOCK.lock().await;- let ws = workspace();- let w = ws.path();- let failing = router_for_workspace(w);-- // Two records saw the same failing router; both ask to degrade.- let ctx = crate::core::runtime::DispatchCtx::ambient();- let first = degrade_to_memory(&ctx, w, &failing);- let second = degrade_to_memory(&ctx, w, &failing);-- assert!(- Arc::ptr_eq(&first.router, &second.router),- "the second caller reuses the fallback the first installed"- );- assert!(Arc::ptr_eq(&entry_for(w).router, &first.router));-}--#[tokio::test]-async fn degrading_a_leased_completion_keeps_its_lease() {- let _guard = crate::config::TEST_ENV_LOCK.lock().await;- let ws = workspace();- let w = ws.path();- let ctx = crate::core::runtime::DispatchCtx::ambient();- let store = Arc::new(ToggleStore::default());- install_store_for_test(w, store.clone());- let router = router_for_workspace(w);- router- .record(CompletionRecord::new(- "leased-task",- "leased-thread",- "researcher",- CompletionStatus::Success,- CompletionResult::text("done"),- ))- .await- .expect("record completion");- assert_eq!(router.claim_pending("leased-thread", 1).unwrap().len(), 1);- store.fail_writes.store(true, Ordering::SeqCst);-- record_completion(- &ctx,- w,- "leased-session",- "trigger-task",- "researcher",- "force fallback",- Some("leased-thread".into()),- )- .await;-- let claims = router_for_workspace(w)- .claim_pending("leased-thread", 10)- .unwrap();- assert!(- claims.iter().all(|record| record.task_id != "leased-task"),- "a fallback router must not make another delivery claim while the first lease is active"- );-}+#[path = "background_completions_migration_tests.rs"]+mod migration_tests;diff --git a/crates/openhuman-core/src/agent/orchestration/background_delivery.rs b/crates/openhuman-core/src/agent/orchestration/background_delivery.rsindex 00a9f00ff9..e89125de6a 100644--- a/crates/openhuman-core/src/agent/orchestration/background_delivery.rs+++ b/crates/openhuman-core/src/agent/orchestration/background_delivery.rs@@ -60,6 +60,10 @@ use super::busy_guard::{busy, clear_busy_for_thread, TurnBusy};use super::completion_notice::build_undelivered_notice;use super::completion_owners;use super::delivery_drain::{DrainFence, RECOVERY_BUSY_POLL};+mod delivery_events;+pub(super) use delivery_events::{drain_schedule_in, Drain};+#[cfg(test)]+pub(super) use delivery_events::drain_schedule;use crate::core::runtime::CoreContext;/// Coalesce completions landing within this window into one delivery turn.@@ -121,138 +125,6 @@ impl EventHandler<DomainEvent> for BackgroundDeliveryHandler {}}-/// One drain an event asks for: the thread, how soon, and the context of the-/// profile that owns it (`None` on the desktop, where nothing is per profile).-pub(super) struct Drain {- pub(super) owner: Option<Arc<CoreContext>>,- pub(super) thread_id: String,- pub(super) delay: Duration,-}--/// Which thread to drain, and after how long, for an event, outside any-/// profile. A session that maps to no thread (cron, voice, skills) has nothing-/// to deliver into.-#[cfg(test)]-fn drain_schedule(event: &DomainEvent) -> Option<(String, Duration)> {- let drain = drain_schedule_in(false, event, |_| None)- .into_iter()- .next()?;- Some((drain.thread_id, drain.delay))-}--/// The session, task and delay an event drains on, if it asks for a drain.-fn drain_target(event: &DomainEvent) -> Option<(&String, Option<&String>, Duration)> {- match event {- // A user turn just ended (or failed) — drain anything that finished while- // it ran.- DomainEvent::AgentTurnCompleted { session_id, .. }- | DomainEvent::AgentError { session_id, .. } => {- Some((session_id, None, Duration::from_millis(300)))- }- // Any subagent terminal state — completed, failed, or awaiting-user — can- // arrive after the parent turn already went idle. Schedule a debounced- // drain for all three so the pending result is delivered promptly instead- // of sitting until some unrelated later turn. Only `SubagentCompleted`- // used to trigger a drain, so a failure (or an awaiting-user pause) after- // the parent turn went idle left the chat stuck on the original- // "Accepted" response (#4896). Debounce so a burst batches into a single- // turn.- DomainEvent::SubagentCompleted {- parent_session,- task_id,- ..- }- | DomainEvent::SubagentFailed {- parent_session,- task_id,- ..- }- | DomainEvent::SubagentAwaitingUser {- parent_session,- task_id,- ..- } => Some((parent_session, Some(task_id), DEBOUNCE)),- _ => None,- }-}--/// Profiles recorded as owning the task (else the session).-fn owners_of(session: &str, task: Option<&String>) -> Vec<String> {- let mut profiles = task- .map(|t| completion_owners::profiles_of(t))- .unwrap_or_default();- if profiles.is_empty() {- profiles = completion_owners::profiles_of(session);- }- profiles-}--/// The profiles whose contexts [`drain_schedule_in`] will ask for.-fn owning_profiles(event: &DomainEvent) -> Vec<String> {- drain_target(event)- .map(|(session, task, _)| owners_of(session, task))- .unwrap_or_default()-}--/// The drains for `event`. This subscriber runs off-task, with no tenant scope,-/// but the thread tables are keyed per profile: the profiles that recorded the-/// completion (by task id) or ran the session are looked up in-/// [`completion_owners`] and each is resolved through `resolve` and drained in-/// its own scope, where it reaches only its own tables. In SaaS (`saas`) an id-/// with no owner is dropped; elsewhere it drains unscoped, as on the desktop.-pub(super) fn drain_schedule_in(- saas: bool,- event: &DomainEvent,- resolve: impl Fn(&str) -> Option<Arc<CoreContext>>,-) -> Vec<Drain> {- let Some((session, task, delay)) = drain_target(event) else {- return Vec::new();- };- // A task id is core-minted and unique, so it names its one owner; a- // session id can be shared by profiles, so it may name several.- let profiles = owners_of(session, task);- let thread_in = |owner: Option<Arc<CoreContext>>| {- let thread_id = match &owner {- Some(ctx) => background_completions::thread_for_session(- &DispatchCtx::new(Arc::clone(ctx)),- session,- ),- // No owner: the unscoped (desktop) drain reads the host's own context.- None => {- background_completions::thread_for_session(&DispatchCtx::host_default(), session)- }- };- if thread_id.is_none() {- log::trace!("[background_delivery] session has no delivery thread; not scheduling");- }- thread_id.map(|thread_id| Drain {- owner,- thread_id,- delay,- })- };- if profiles.is_empty() {- if saas {- log::debug!(- "[background_delivery] no owning profile for the session or task; dropping \- the drain (fails closed in SaaS)"- );- return Vec::new();- }- return thread_in(None).into_iter().collect();- }- profiles- .iter()- .filter_map(|profile| match resolve(profile) {- Some(ctx) => thread_in(Some(ctx)),- None => {- log::debug!("[background_delivery] owning profile has no live context; dropping");- None- }- })- .collect()-}-/// Schedule a debounced delivery attempt for a thread, fenced by the calling/// profile's lease ([`DrainFence::current`]).fn schedule_delivery(ctx: &DispatchCtx, thread_id: String, delay: Duration) {diff --git a/crates/openhuman-core/src/agent/orchestration/delivery_events.rs b/crates/openhuman-core/src/agent/orchestration/delivery_events.rsnew file mode 100644index 0000000000..6dc26b0e7b--- /dev/null+++ b/crates/openhuman-core/src/agent/orchestration/delivery_events.rs@@ -0,0 +1,136 @@+//! Event-to-drain projection for detached completion delivery.++use super::*;++/// One drain an event asks for: the thread, how soon, and the context of the+/// profile that owns it (`None` on the desktop, where nothing is per profile).+pub(super) struct Drain {+ pub(super) owner: Option<Arc<CoreContext>>,+ pub(super) thread_id: String,+ pub(super) delay: Duration,+}++/// Which thread to drain, and after how long, for an event, outside any+/// profile. A session that maps to no thread (cron, voice, skills) has nothing+/// to deliver into.+#[cfg(test)]+fn drain_schedule(event: &DomainEvent) -> Option<(String, Duration)> {+ let drain = drain_schedule_in(false, event, |_| None)+ .into_iter()+ .next()?;+ Some((drain.thread_id, drain.delay))+}++/// The session, task and delay an event drains on, if it asks for a drain.+fn drain_target(event: &DomainEvent) -> Option<(&String, Option<&String>, Duration)> {+ match event {+ // A user turn just ended (or failed) — drain anything that finished while+ // it ran.+ DomainEvent::AgentTurnCompleted { session_id, .. }+ | DomainEvent::AgentError { session_id, .. } => {+ Some((session_id, None, Duration::from_millis(300)))+ }+ // Any subagent terminal state — completed, failed, or awaiting-user — can+ // arrive after the parent turn already went idle. Schedule a debounced+ // drain for all three so the pending result is delivered promptly instead+ // of sitting until some unrelated later turn. Only `SubagentCompleted`+ // used to trigger a drain, so a failure (or an awaiting-user pause) after+ // the parent turn went idle left the chat stuck on the original+ // "Accepted" response (#4896). Debounce so a burst batches into a single+ // turn.+ DomainEvent::SubagentCompleted {+ parent_session,+ task_id,+ ..+ }+ | DomainEvent::SubagentFailed {+ parent_session,+ task_id,+ ..+ }+ | DomainEvent::SubagentAwaitingUser {+ parent_session,+ task_id,+ ..+ } => Some((parent_session, Some(task_id), DEBOUNCE)),+ _ => None,+ }+}++/// Profiles recorded as owning the task (else the session).+fn owners_of(session: &str, task: Option<&String>) -> Vec<String> {+ let mut profiles = task+ .map(|t| completion_owners::profiles_of(t))+ .unwrap_or_default();+ if profiles.is_empty() {+ profiles = completion_owners::profiles_of(session);+ }+ profiles+}++/// The profiles whose contexts [`drain_schedule_in`] will ask for.+fn owning_profiles(event: &DomainEvent) -> Vec<String> {+ drain_target(event)+ .map(|(session, task, _)| owners_of(session, task))+ .unwrap_or_default()+}++/// The drains for `event`. This subscriber runs off-task, with no tenant scope,+/// but the thread tables are keyed per profile: the profiles that recorded the+/// completion (by task id) or ran the session are looked up in+/// [`completion_owners`] and each is resolved through `resolve` and drained in+/// its own scope, where it reaches only its own tables. In SaaS (`saas`) an id+/// with no owner is dropped; elsewhere it drains unscoped, as on the desktop.+pub(super) fn drain_schedule_in(+ saas: bool,+ event: &DomainEvent,+ resolve: impl Fn(&str) -> Option<Arc<CoreContext>>,+) -> Vec<Drain> {+ let Some((session, task, delay)) = drain_target(event) else {+ return Vec::new();+ };+ // A task id is core-minted and unique, so it names its one owner; a+ // session id can be shared by profiles, so it may name several.+ let profiles = owners_of(session, task);+ let thread_in = |owner: Option<Arc<CoreContext>>| {+ let thread_id = match &owner {+ Some(ctx) => background_completions::thread_for_session(+ &DispatchCtx::new(Arc::clone(ctx)),+ session,+ ),+ // No owner: the unscoped (desktop) drain reads the host's own context.+ None => {+ background_completions::thread_for_session(&DispatchCtx::host_default(), session)+ }+ };+ if thread_id.is_none() {+ log::trace!("[background_delivery] session has no delivery thread; not scheduling");+ }+ thread_id.map(|thread_id| Drain {+ owner,+ thread_id,+ delay,+ })+ };+ if profiles.is_empty() {+ if saas {+ log::debug!(+ "[background_delivery] no owning profile for the session or task; dropping \+ the drain (fails closed in SaaS)"+ );+ return Vec::new();+ }+ return thread_in(None).into_iter().collect();+ }+ profiles+ .iter()+ .filter_map(|profile| match resolve(profile) {+ Some(ctx) => thread_in(Some(ctx)),+ None => {+ log::debug!("[background_delivery] owning profile has no live context; dropping");+ None+ }+ })+ .collect()+}+