Skip to content

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

fix(channels): hold progressive transports weakly and guard cancelled sessions

Steven Enamakelf127ef2d7d5c
diff --git a/crates/openhuman-core/src/channels/runtime/startup/callback.rs b/crates/openhuman-core/src/channels/runtime/startup/callback.rs
index 98bae2d0c9..6a8dd1cb47 100644
--- a/crates/openhuman-core/src/channels/runtime/startup/callback.rs
+++ b/crates/openhuman-core/src/channels/runtime/startup/callback.rs
@@ -51,7 +51,8 @@ pub(super) struct ChannelHostCallbacks {
tenant: crate::core::runtime::Tenant,
cancellation: tokio_util::sync::CancellationToken,
context: Arc<OnceLock<Weak<ChannelRuntimeContext>>>,
- progressive_channels: Arc<OnceLock<Arc<HashMap<String, Arc<dyn ProgressiveChannelTransport>>>>>,
+ progressive_channels:
+ Arc<OnceLock<Arc<HashMap<String, Weak<dyn ProgressiveChannelTransport>>>>>,
output_observer: Option<Arc<dyn ProgressiveOutputObserver>>,
dispatch: mpsc::Sender<RuntimeChannelMessage>,
}
@@ -62,7 +63,7 @@ impl ChannelHostCallbacks {
config: Arc<Config>,
context: Arc<OnceLock<Weak<ChannelRuntimeContext>>>,
progressive_channels: Arc<
- OnceLock<Arc<HashMap<String, Arc<dyn ProgressiveChannelTransport>>>>,
+ OnceLock<Arc<HashMap<String, Weak<dyn ProgressiveChannelTransport>>>>,
>,
output_observer: Option<Arc<dyn ProgressiveOutputObserver>>,
dispatch: mpsc::Sender<RuntimeChannelMessage>,
@@ -285,6 +286,9 @@ impl ChannelHostCallbacks {
&self,
request: ProgressiveTransportRequest,
) -> Result<ProgressiveTransportResult> {
+ if self.cancellation.is_cancelled() {
+ return Err(Error::failed("channel session ended"));
+ }
if let ProgressiveTransportRequest::OutputEvent {
channel: route,
channel_ref,
@@ -295,6 +299,9 @@ impl ChannelHostCallbacks {
..
} = &request
{
+ if self.cancellation.is_cancelled() {
+ return Err(Error::failed("channel session ended"));
+ }
let channel = channel_ref
.as_ref()
.ok_or_else(|| Error::failed("progressive output channel identity is required"))?;
@@ -368,7 +375,7 @@ impl ChannelHostCallbacks {
.ok_or_else(|| Error::failed("progressive channel adapters are unavailable"))?;
let adapter = adapters
.get(account)
- .cloned()
+ .and_then(Weak::upgrade)
.ok_or_else(|| Error::failed("configured channel account is unavailable"))?;
let configured_provider =
tinychannels_bus::capabilities::provider_id(adapter.configured_name());
diff --git a/crates/openhuman-core/src/channels/runtime/startup/callback_tests.rs b/crates/openhuman-core/src/channels/runtime/startup/callback_tests.rs
index 9a02e3863c..edc4609fdd 100644
--- a/crates/openhuman-core/src/channels/runtime/startup/callback_tests.rs
+++ b/crates/openhuman-core/src/channels/runtime/startup/callback_tests.rs
@@ -1,9 +1,9 @@
use super::*;
use super::{ProgressiveChannelTransport, ProgressiveOutputObserver};
-use crate::channels::Channel;
use crate::channels::context::ChannelRuntimeContext;
use crate::channels::runtime::dispatch::RuntimeChannelMessage;
+use crate::channels::Channel;
use std::collections::HashMap;
use std::sync::{Arc, Mutex, OnceLock, Weak};
use tinychannels_bus::channel::{
@@ -176,7 +176,14 @@ fn callback_for_channels(
let context_slot: Arc<OnceLock<Weak<ChannelRuntimeContext>>> = Arc::new(OnceLock::new());
assert!(context_slot.set(Arc::downgrade(&context)).is_ok());
let progressive_slot = Arc::new(OnceLock::new());
- assert!(progressive_slot.set(Arc::new(progressive_channels)).is_ok());
+ assert!(progressive_slot
+ .set(Arc::new(
+ progressive_channels
+ .into_iter()
+ .map(|(name, adapter)| (name, Arc::downgrade(&adapter)))
+ .collect()
+ ))
+ .is_ok());
let (dispatch, _receiver) = tokio::sync::mpsc::channel::<RuntimeChannelMessage>(1);
(
ChannelHostCallbacks::new(
@@ -508,3 +515,28 @@ async fn native_progressive_output_event_validates_scope_before_observer() {
}
assert!(observer.seen.lock().await.is_empty());
}
+
+#[tokio::test]
+async fn native_progressive_callbacks_stop_after_channel_session_cancellation() {
+ let observer = Arc::new(RecordingOutputObserver::default());
+ let adapter = Arc::new(RecordingChannel::new("telegram:bot-b"));
+ let (callback, _context) = callback_for_channels(
+ HashMap::from([("telegram:bot-b".into(), adapter.clone() as Arc<dyn Channel>)]),
+ HashMap::from([(
+ "telegram:bot-b".into(),
+ adapter as Arc<dyn ProgressiveChannelTransport>,
+ )]),
+ Some(observer.clone() as Arc<dyn ProgressiveOutputObserver>),
+ );
+
+ callback.cancellation.cancel();
+ assert!(callback
+ .dispatch_controller_backend(output_event_request(
+ Some("telegram:bot-b"),
+ Some("chat-42"),
+ Some("turn-15"),
+ ))
+ .await
+ .is_err());
+ assert!(observer.seen.lock().await.is_empty());
+}
diff --git a/crates/openhuman-core/src/channels/runtime/startup/module_providers.rs b/crates/openhuman-core/src/channels/runtime/startup/module_providers.rs
index ee0b5d6424..5ba725e96b 100644
--- a/crates/openhuman-core/src/channels/runtime/startup/module_providers.rs
+++ b/crates/openhuman-core/src/channels/runtime/startup/module_providers.rs
@@ -149,10 +149,8 @@ impl ModuleChannelRuntime {
};
let channel = Arc::new(channel);
channels.insert(info.name.clone(), channel.clone() as Arc<dyn Channel>);
- progressive.insert(
- info.name.clone(),
- channel as Arc<dyn ProgressiveChannelTransport>,
- );
+ let progressive_channel: Arc<dyn ProgressiveChannelTransport> = channel.clone();
+ progressive.insert(info.name.clone(), Arc::downgrade(&progressive_channel));
}
progressive_channels
.set(Arc::new(progressive))
@@ -533,10 +531,10 @@ impl ModuleChannel {
if receipt.primary_platform_message_id.is_none() {
receipt.primary_platform_message_id = result.message_id.clone();
}
- if receipt.platform_message_ids.is_empty()
- && let Some(message_id) = result.message_id
- {
- receipt.platform_message_ids.push(message_id);
+ if receipt.platform_message_ids.is_empty() {
+ if let Some(message_id) = result.message_id {
+ receipt.platform_message_ids.push(message_id);
+ }
}
Ok(tinychannels_bus::channel::ChannelSendOutcome {
receipt,
diff --git a/crates/openhuman-core/src/channels/runtime/startup/progressive_transport.rs b/crates/openhuman-core/src/channels/runtime/startup/progressive_transport.rs
index 49ec9efece..23325070d0 100644
--- a/crates/openhuman-core/src/channels/runtime/startup/progressive_transport.rs
+++ b/crates/openhuman-core/src/channels/runtime/startup/progressive_transport.rs
@@ -141,19 +141,13 @@ impl ProgressiveChannelTransport for ModuleChannel {
)
.await
{
- Ok(ChannelInteractionResult::Sent(outcome)) => {
- match outcome.error.as_ref().map(|error| error.kind) {
- Some(tinychannels_bus::channel::SendErrorKind::NotFound) => {
- Ok(Result::MessageGone)
- }
- Some(error) if error.unsupported => Ok(Result::EditUnsupported),
- _ => Ok(Result::Outcome(outcome)),
- }
- }
+ Ok(ChannelInteractionResult::Sent(outcome)) => Ok(map_edit_outcome(outcome)),
Ok(_) => Err(tinybus::Error::failed(
"channel returned an invalid edit result",
)),
- Err(error) => Err(error),
+ Err(error) => Err(tinybus::Error::failed(format!(
+ "channel edit callback failed: {error}"
+ ))),
}
}
Request::Delete {
@@ -186,7 +180,9 @@ impl ProgressiveChannelTransport for ModuleChannel {
Ok(_) => Err(tinybus::Error::failed(
"channel returned an invalid delete result",
)),
- Err(error) => Err(error),
+ Err(error) => Err(tinybus::Error::failed(format!(
+ "channel delete callback failed: {error}"
+ ))),
}
}
Request::Typing { conversation, .. } => {
@@ -203,6 +199,29 @@ impl ProgressiveChannelTransport for ModuleChannel {
}
}
+fn map_edit_outcome(
+ outcome: tinychannels_bus::channel::ChannelSendOutcome,
+) -> tinychannels_bus::module_progressive::ProgressiveTransportResult {
+ use tinychannels_bus::channel::SendErrorKind;
+ use tinychannels_bus::module_progressive::ProgressiveTransportResult as Result;
+
+ match outcome.error.as_ref().map(|error| error.kind) {
+ Some(SendErrorKind::NotFound) => Result::MessageGone,
+ _ if outcome
+ .error
+ .as_ref()
+ .is_some_and(|error| error.unsupported) =>
+ {
+ Result::EditUnsupported
+ }
+ _ => Result::Outcome(outcome),
+ }
+}
+
+#[cfg(test)]
+#[path = "progressive_transport_tests.rs"]
+mod tests;
+
fn receipt_matches_scope(
receipt: &tinychannels_bus::channel::MessageReceipt,
channel: Option<&tinychannels_bus::ChannelRef>,
diff --git a/crates/openhuman-core/src/channels/runtime/startup/progressive_transport_tests.rs b/crates/openhuman-core/src/channels/runtime/startup/progressive_transport_tests.rs
new file mode 100644
index 0000000000..24f4fa1225
--- /dev/null
+++ b/crates/openhuman-core/src/channels/runtime/startup/progressive_transport_tests.rs
@@ -0,0 +1,26 @@
+use super::*;
+
+#[test]
+fn forbidden_edit_error_is_preserved_instead_of_reported_as_unsupported() {
+ let outcome = tinychannels_bus::channel::ChannelSendOutcome {
+ receipt: Default::default(),
+ error: Some(tinychannels_bus::channel::ChannelSendError {
+ kind: tinychannels_bus::channel::SendErrorKind::Forbidden,
+ message: "edit denied by account policy".into(),
+ ..Default::default()
+ }),
+ };
+
+ let tinychannels_bus::module_progressive::ProgressiveTransportResult::Outcome(mapped) =
+ map_edit_outcome(outcome)
+ else {
+ panic!("a forbidden edit error must remain an outcome");
+ };
+ let error = mapped.error.expect("the denial details must be preserved");
+ assert_eq!(
+ error.kind,
+ tinychannels_bus::channel::SendErrorKind::Forbidden
+ );
+ assert_eq!(error.message, "edit denied by account policy");
+ assert!(!error.unsupported);
+}