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
fix(channels): persist delivery state across restarts
Steven Enamakel807945879399
diff --git a/crates/openhuman-core/src/channels/runtime/startup.rs b/crates/openhuman-core/src/channels/runtime/startup.rsindex 821e8a6fd2..52e7210ede 100644--- a/crates/openhuman-core/src/channels/runtime/startup.rs+++ b/crates/openhuman-core/src/channels/runtime/startup.rs@@ -3,7 +3,7 @@mod callback;mod chat_workload;mod credentials;-mod delivery_store;+mod delivery_import;mod module_providers;mod prompt;#[cfg(test)]diff --git a/crates/openhuman-core/src/channels/runtime/startup/delivery_store.rs b/crates/openhuman-core/src/channels/runtime/startup/delivery_store.rsdeleted file mode 100644index c75227af2d..0000000000--- a/crates/openhuman-core/src/channels/runtime/startup/delivery_store.rs+++ /dev/null@@ -1,271 +0,0 @@-//! Durable host-owned storage for TinyChannels delivery callbacks.--use std::collections::{BTreeMap, HashMap};-use std::path::{Path, PathBuf};-use std::sync::{Arc, Mutex as StdMutex, OnceLock};-use tinychannels_bus::module_delivery::{- DeliveryQueueEntry, DeliveryTerminalResult, DELIVERY_PENDING_CAPACITY, DELIVERY_RECORD_BYTES,- DELIVERY_RESULT_CAPACITY, DELIVERY_RESULT_TTL_SECONDS,-};-use tokio::sync::Mutex;--const FILE_NAME: &str = "channel-delivery.json";-const MAX_STORE_BYTES: u64 = (DELIVERY_PENDING_CAPACITY * DELIVERY_RECORD_BYTES * 2) as u64- + (DELIVERY_RESULT_CAPACITY * DELIVERY_RECORD_BYTES) as u64;--type Locks = HashMap<PathBuf, Arc<Mutex<()>>>;-static WORKSPACE_LOCKS: OnceLock<StdMutex<Locks>> = OnceLock::new();--#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]-#[serde(default)]-struct DeliveryState {- pending: BTreeMap<String, DeliveryQueueEntry>,- failed: BTreeMap<String, DeliveryQueueEntry>,- results: BTreeMap<String, DeliveryTerminalResult>,-}--/// Shared store keyed by the captured workspace, so concurrent channel-/// sessions serialize updates to the same durable queue.-#[derive(Clone)]-pub(super) struct ChannelDeliveryStore {- path: PathBuf,- gate: Arc<Mutex<()>>,-}--impl ChannelDeliveryStore {- pub(super) fn for_workspace(workspace: &Path) -> Self {- let path = workspace.join("channels").join(FILE_NAME);- let locks = WORKSPACE_LOCKS.get_or_init(|| StdMutex::new(HashMap::new()));- let gate = locks- .lock()- .unwrap_or_else(|error| error.into_inner())- .entry(path.clone())- .or_insert_with(|| Arc::new(Mutex::new(())))- .clone();- Self { path, gate }- }-- async fn locked_state(- &self,- ) -> anyhow::Result<(tokio::sync::OwnedMutexGuard<()>, DeliveryState)> {- let guard = Arc::clone(&self.gate).lock_owned().await;- let state = self.read_state().await?;- Ok((guard, state))- }-- async fn read_state(&self) -> anyhow::Result<DeliveryState> {- let bytes = match tokio::fs::read(&self.path).await {- Ok(bytes) => bytes,- Err(error) if error.kind() == std::io::ErrorKind::NotFound => {- return Ok(DeliveryState::default());- }- Err(error) => return Err(error.into()),- };- anyhow::ensure!(- bytes.len() as u64 <= MAX_STORE_BYTES,- "channel delivery store is oversized"- );- let state: DeliveryState = serde_json::from_slice(&bytes)?;- validate_state(&state)?;- Ok(state)- }-- async fn write_state(&self, state: DeliveryState) -> anyhow::Result<()> {- validate_state(&state)?;- let bytes = serde_json::to_vec(&state)?;- anyhow::ensure!(- bytes.len() as u64 <= MAX_STORE_BYTES,- "channel delivery store is oversized"- );- let path = self.path.clone();- tokio::task::spawn_blocking(move || {- crate::security::secret_storage::file_store::write_atomic(&path, &bytes)- .map_err(anyhow::Error::from)- })- .await??;- Ok(())- }-- pub(super) async fn save_pending(&self, entry: DeliveryQueueEntry) -> anyhow::Result<()> {- validate_entry(&entry)?;- let (_guard, mut state) = self.locked_state().await?;- if let Some(existing) = state.pending.get(&entry.id) {- anyhow::ensure!(- existing == &entry,- "delivery id conflicts with pending entry"- );- return Ok(());- }- anyhow::ensure!(- !state.failed.contains_key(&entry.id) && !state.results.contains_key(&entry.id),- "delivery id already has a terminal result"- );- anyhow::ensure!(- state.pending.len() < DELIVERY_PENDING_CAPACITY,- "delivery queue is full"- );- state.pending.insert(entry.id.clone(), entry);- self.write_state(state).await- }-- pub(super) async fn load_pending(- &self,- id: String,- ) -> anyhow::Result<Option<DeliveryQueueEntry>> {- validate_id(&id)?;- let (_guard, state) = self.locked_state().await?;- Ok(state.pending.get(&id).cloned())- }-- pub(super) async fn load_pending_all(&self) -> anyhow::Result<Vec<DeliveryQueueEntry>> {- let (_guard, state) = self.locked_state().await?;- let mut entries: Vec<_> = state.pending.into_values().collect();- entries.sort_by(|left, right| {- left.enqueued_at_unix_ms- .cmp(&right.enqueued_at_unix_ms)- .then_with(|| left.id.cmp(&right.id))- });- Ok(entries)- }-- pub(super) async fn remove_pending(&self, id: String) -> anyhow::Result<()> {- validate_id(&id)?;- let (_guard, mut state) = self.locked_state().await?;- if state.pending.remove(&id).is_some() {- self.write_state(state).await?;- }- Ok(())- }-- pub(super) async fn save_failed(&self, entry: DeliveryQueueEntry) -> anyhow::Result<()> {- validate_entry(&entry)?;- let (_guard, mut state) = self.locked_state().await?;- if let Some(existing) = state.failed.get(&entry.id) {- anyhow::ensure!(- existing == &entry,- "delivery id conflicts with failed entry"- );- return Ok(());- }- anyhow::ensure!(- state.failed.len() < DELIVERY_PENDING_CAPACITY,- "failed delivery store is full"- );- state.failed.insert(entry.id.clone(), entry);- self.write_state(state).await- }-- pub(super) async fn load_failed(- &self,- id: String,- ) -> anyhow::Result<Option<DeliveryQueueEntry>> {- validate_id(&id)?;- let (_guard, state) = self.locked_state().await?;- Ok(state.failed.get(&id).cloned())- }-- pub(super) async fn save_result(&self, result: DeliveryTerminalResult) -> anyhow::Result<()> {- validate_id(&result.id)?;- anyhow::ensure!(- !result.intent_fingerprint.is_empty() && result.intent_fingerprint.len() <= 128,- "delivery fingerprint is invalid"- );- anyhow::ensure!(- serde_json::to_vec(&result).is_ok_and(|bytes| bytes.len() <= DELIVERY_RECORD_BYTES),- "delivery result exceeds its record limit"- );- let (_guard, mut state) = self.locked_state().await?;- prune_results(&mut state, now_unix_ms());- if let Some(existing) = state.results.get(&result.id) {- anyhow::ensure!(- existing == &result,- "delivery id conflicts with terminal result"- );- return Ok(());- }- anyhow::ensure!(- state.results.len() < DELIVERY_RESULT_CAPACITY,- "delivery result replay store is full"- );- state.results.insert(result.id.clone(), result);- self.write_state(state).await- }-- pub(super) async fn load_result(- &self,- id: String,- ) -> anyhow::Result<Option<DeliveryTerminalResult>> {- validate_id(&id)?;- let (_guard, mut state) = self.locked_state().await?;- prune_results(&mut state, now_unix_ms());- let result = state.results.get(&id).cloned();- if result.is_none() {- self.write_state(state).await?;- }- Ok(result)- }-}--fn validate_state(state: &DeliveryState) -> anyhow::Result<()> {- anyhow::ensure!(- state.pending.len() <= DELIVERY_PENDING_CAPACITY,- "pending delivery store exceeds capacity"- );- anyhow::ensure!(- state.failed.len() <= DELIVERY_PENDING_CAPACITY,- "failed delivery store exceeds capacity"- );- anyhow::ensure!(- state.results.len() <= DELIVERY_RESULT_CAPACITY,- "delivery result store exceeds capacity"- );- for (id, entry) in state.pending.iter().chain(state.failed.iter()) {- anyhow::ensure!(id == &entry.id, "delivery store key does not match record");- validate_entry(entry)?;- }- for (id, result) in &state.results {- validate_id(id)?;- anyhow::ensure!(- id == &result.id,- "delivery result key does not match record"- );- }- Ok(())-}--fn validate_entry(entry: &DeliveryQueueEntry) -> anyhow::Result<()> {- validate_id(&entry.id)?;- anyhow::ensure!(- entry.intent.idempotency_key == entry.id,- "delivery id does not match intent key"- );- anyhow::ensure!(- serde_json::to_vec(entry).is_ok_and(|bytes| bytes.len() <= DELIVERY_RECORD_BYTES),- "delivery record exceeds its limit"- );- Ok(())-}--fn validate_id(id: &str) -> anyhow::Result<()> {- anyhow::ensure!(!id.is_empty() && id.len() <= 256, "delivery id is invalid");- Ok(())-}--fn prune_results(state: &mut DeliveryState, now_ms: u64) {- let ttl_ms = DELIVERY_RESULT_TTL_SECONDS.saturating_mul(1000);- state- .results- .retain(|_, result| result.completed_at_unix_ms.saturating_add(ttl_ms) > now_ms);-}--fn now_unix_ms() -> u64 {- std::time::SystemTime::now()- .duration_since(std::time::UNIX_EPOCH)- .unwrap_or_default()- .as_millis()- .min(u64::MAX as u128) as u64-}--#[cfg(test)]-#[path = "delivery_store_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/channels/runtime/startup/delivery_store_tests.rs b/crates/openhuman-core/src/channels/runtime/startup/delivery_store_tests.rsdeleted file mode 100644index ad24b65b97..0000000000--- a/crates/openhuman-core/src/channels/runtime/startup/delivery_store_tests.rs+++ /dev/null@@ -1,123 +0,0 @@-use super::*;-use tinychannels_bus::{ChannelOutboundIntent, DeliveryDurability, OutboundPayload};--fn entry(id: &str, at: u64) -> DeliveryQueueEntry {- DeliveryQueueEntry::new(- id,- ChannelOutboundIntent {- idempotency_key: id.to_owned(),- channel_id: "telegram".into(),- conversation_id: "chat-1".into(),- reply_to_id: None,- thread_id: None,- durability: DeliveryDurability::Required,- payload: OutboundPayload::Text {- text: "hello".into(),- },- },- at,- )-}--fn store(path: &Path) -> ChannelDeliveryStore {- ChannelDeliveryStore {- path: path.to_path_buf(),- gate: Arc::new(Mutex::new(())),- }-}--#[tokio::test]-async fn pending_delivery_is_durable_ordered_and_idempotent() {- let dir = tempfile::tempdir().unwrap();- let path = dir.path().join("delivery.json");- let first = store(&path);- first.save_pending(entry("later", 20)).await.unwrap();- first.save_pending(entry("earlier", 10)).await.unwrap();- first.save_pending(entry("earlier", 10)).await.unwrap();-- let reopened = store(&path);- assert_eq!(- reopened.load_pending("earlier".into()).await.unwrap(),- Some(entry("earlier", 10))- );- assert_eq!(- reopened- .load_pending_all()- .await- .unwrap()- .iter()- .map(|item| item.id.as_str())- .collect::<Vec<_>>(),- vec!["earlier", "later"]- );-}--#[tokio::test]-async fn changed_intent_cannot_reuse_a_pending_delivery_id() {- let dir = tempfile::tempdir().unwrap();- let store = store(&dir.path().join("delivery.json"));- store.save_pending(entry("same", 1)).await.unwrap();- let mut changed = entry("same", 1);- changed.intent.conversation_id = "other-chat".into();- assert!(store.save_pending(changed).await.is_err());- assert_eq!(- store.load_pending_all().await.unwrap(),- vec![entry("same", 1)]- );-}--#[tokio::test]-async fn terminal_result_is_replayed_and_conflicts_are_rejected() {- let dir = tempfile::tempdir().unwrap();- let store = store(&dir.path().join("delivery.json"));- let result = DeliveryTerminalResult {- id: "done".into(),- intent_fingerprint: "abc123".into(),- completed_at_unix_ms: now_unix_ms(),- };- store.save_result(result.clone()).await.unwrap();- store.save_result(result.clone()).await.unwrap();- assert_eq!(- store.load_result("done".into()).await.unwrap(),- Some(result.clone())- );-- let conflict = DeliveryTerminalResult {- intent_fingerprint: "different".into(),- ..result- };- assert!(store.save_result(conflict).await.is_err());-}--#[tokio::test]-async fn removal_and_failed_delivery_are_idempotent_and_durable() {- let dir = tempfile::tempdir().unwrap();- let path = dir.path().join("delivery.json");- let delivery_store = store(&path);- let failed = entry("failed", 1);- delivery_store.save_failed(failed.clone()).await.unwrap();- delivery_store.save_failed(failed.clone()).await.unwrap();- delivery_store- .save_pending(entry("pending", 2))- .await- .unwrap();- delivery_store- .remove_pending("pending".into())- .await- .unwrap();- delivery_store- .remove_pending("pending".into())- .await- .unwrap();-- let reopened = store(&path);- assert_eq!(- reopened.load_failed("failed".into()).await.unwrap(),- Some(failed)- );- assert!(reopened- .load_pending("pending".into())- .await- .unwrap()- .is_none());-}diff --git a/crates/openhuman-core/src/modules/storage_host.rs b/crates/openhuman-core/src/modules/storage_host.rsindex 69f9c9f201..498d53d8db 100644--- a/crates/openhuman-core/src/modules/storage_host.rs+++ b/crates/openhuman-core/src/modules/storage_host.rs@@ -475,6 +475,18 @@ impl tinybus::Interface for ObjectService {}}+/// The scope the host serves `module_id` under right now: what a bus call from+/// that module would be bound to. The host's own one-time legacy imports use it+/// to write a module's records where the module will read them.+///+/// # Errors+///+/// When the acting scope cannot be resolved (SaaS mode with no profile) or the+/// module id is not a plain name under a profile.+pub(crate) fn current_module_scope(module_id: &str) -> Result<Scope, StorageError> {+ Live::scope_of(module_id)+}+/// Production wiring: the broker's name owners, the installed backend, the/// host's scope rule and the compiled grants.struct Live {