Skip to content

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

feat(channels): debounce inbound messages per conversation

Steven Enamakel40466a37de6a
diff --git a/crates/openhuman-core/src/channels/outbound.rs b/crates/openhuman-core/src/channels/outbound.rs
deleted file mode 100644
index f600cf685d..0000000000
--- a/crates/openhuman-core/src/channels/outbound.rs
+++ /dev/null
@@ -1,53 +0,0 @@
-//! Host adapters for canonical TinyChannels outbound messages.
-
-use tinychannels_bus::{
- ChannelOutboundIntent, ChannelOutboundMessage, ChannelRef, ConversationRef, DeliveryDurability,
- OutboundPayload,
-};
-
-use super::Channel;
-
-/// Build a text message addressed to one channel conversation.
-pub(crate) fn text_message(
- channel: &str,
- conversation: &str,
- text: impl Into<String>,
- thread_id: Option<String>,
-) -> ChannelOutboundMessage {
- let intent = ChannelOutboundIntent {
- idempotency_key: uuid::Uuid::new_v4().to_string(),
- channel_id: channel.to_owned(),
- conversation_id: conversation.to_owned(),
- channel_ref: Some(ChannelRef {
- id: channel.to_owned(),
- account_id: None,
- }),
- conversation_ref: Some(ConversationRef {
- id: conversation.to_owned(),
- thread_id: thread_id.clone(),
- ..Default::default()
- }),
- thread_id,
- durability: DeliveryDurability::BestEffort,
- payload: OutboundPayload::Text { text: text.into() },
- ..Default::default()
- };
- ChannelOutboundMessage::from_intent(&intent)
-}
-
-/// Start a draft through the only progressive draft method exposed by the
-/// pinned v22 Channel trait. The contract still accepts its v21 text DTO here.
-#[allow(
- deprecated,
- reason = "TinyChannels v0.1.39 exposes no typed v22 send-draft trait method"
-)]
-pub(crate) async fn send_draft(
- channel: &dyn Channel,
- conversation: &str,
- text: &str,
- thread_id: Option<String>,
-) -> anyhow::Result<Option<String>> {
- channel
- .send_draft(&tinychannels_bus::SendMessage::new(text, conversation).in_thread(thread_id))
- .await
-}
diff --git a/crates/openhuman-core/src/channels/runtime/dispatch/mod.rs b/crates/openhuman-core/src/channels/runtime/dispatch/mod.rs
index 54481d3e85..aac766db63 100644
--- a/crates/openhuman-core/src/channels/runtime/dispatch/mod.rs
+++ b/crates/openhuman-core/src/channels/runtime/dispatch/mod.rs
@@ -12,6 +12,7 @@
mod helpers;
pub(crate) mod host_agent;
+mod inbound_batch;
mod native_runner;
mod processor;
diff --git a/crates/openhuman-core/src/channels/runtime/dispatch/processor.rs b/crates/openhuman-core/src/channels/runtime/dispatch/processor.rs
index 02dd0bcf42..fbb96507d6 100644
--- a/crates/openhuman-core/src/channels/runtime/dispatch/processor.rs
+++ b/crates/openhuman-core/src/channels/runtime/dispatch/processor.rs
@@ -10,9 +10,11 @@
//! * [`bus_turn`] — the orchestrator path: an unbound channel's turn over
//! the native bus. A channel bound to a host agent runs through
//! [`super::host_agent`] instead.
-//! * [`run_message_dispatch_loop`] — feeds messages into
-//! [`process_channel_runtime_message`] with a bounded set of host workers
-//! and joins them when the inbound queue closes.
+//! * [`admit`] — preparation, the received event, and the runtime-command and
+//! approval-reply intercepts that run before any debounce.
+//! * [`run_message_dispatch_loop`] — admits inbound messages, debounces them
+//! per conversation through [`crate::inbound_debounce`], and starts one turn
+//! per batch with a bounded set of host workers.
mod admit;
mod approval;
@@ -26,9 +28,16 @@ mod turn;
#[cfg(test)]
pub(crate) use native_media::drop_media_read_lease_for_test;
+use super::inbound_batch::{merge_channel_batch, QueuedInbound};
use crate::channels::context::ChannelRuntimeContext;
+use crate::config::InboundDebounceConfig;
+use crate::inbound_debounce::KeyedDebouncer;
+use in_order::InOrder;
+use std::collections::{HashMap, VecDeque};
use std::sync::Arc;
use tinychannels_bus::{ChannelInboundEnvelope, ChannelMessage};
+use tokio::task::JoinSet;
+use tokio::time::Instant;
/// Host-side inbound work item. Relay authentication remains out-of-band and
/// can only be set by the native callback after receiving the trusted module
@@ -96,37 +105,162 @@ impl From<ChannelMessage> for RuntimeChannelMessage {
#[cfg(test)]
pub(crate) use approval::channel_has_approval_surface;
pub(crate) use reset::reset_durable_channel_session;
+use admit::admit_runtime_message;
+pub(crate) use admit::AdmittedInbound;
pub(crate) use turn::process_channel_runtime_message;
+use turn::run_admitted_turn;
pub(crate) async fn process_channel_message(ctx: Arc<ChannelRuntimeContext>, msg: ChannelMessage) {
process_channel_runtime_message(ctx, RuntimeChannelMessage::from(msg)).await;
}
-/// Run every inbound message through the agent pipeline, at most
-/// `max_in_flight_messages` at a time, until `rx` closes.
+/// Run every inbound message through the agent pipeline until `rx` closes.
+///
+/// Each message is admitted first (preparation, the received event, runtime
+/// commands and approval replies), concurrently but released in receive order.
+/// Admitted messages are then debounced per conversation (`history_key`): a
+/// burst becomes one turn. The debouncer only delays and merges intake. It
+/// releases a conversation as soon as its batch is handed to a turn, so the
+/// shared TinyAgents turn runner still owns queueing and steering for
+/// messages that arrive while a turn runs. At most `max_in_flight_messages`
+/// turns start concurrently, and the loop stops receiving while
+/// [`intake_budget`] admitted messages are waiting for a turn, so a sustained
+/// sender is held back by the bounded inbound queue.
pub(crate) async fn run_message_dispatch_loop(
rx: tokio::sync::mpsc::Receiver<RuntimeChannelMessage>,
ctx: Arc<ChannelRuntimeContext>,
max_in_flight_messages: usize,
+ debounce: InboundDebounceConfig,
) {
+ let max_in_flight = max_in_flight_messages.max(1);
+ let budget = intake_budget(max_in_flight, &debounce);
+ let mut held: usize = 0;
let mut rx = rx;
- let mut workers = tokio::task::JoinSet::new();
- while let Some(message) = rx.recv().await {
- while workers.len() >= max_in_flight_messages.max(1) {
- if let Some(Err(error)) = workers.join_next().await {
- tracing::warn!("channel dispatch worker failed: {error}");
+ let mut inbound_open = true;
+ let mut next_seq: u64 = 0;
+ let mut admitting = JoinSet::new();
+ let mut admit_seqs: HashMap<tokio::task::Id, u64> = HashMap::new();
+ let mut admission_order = InOrder::new();
+ let mut turns = JoinSet::new();
+ let mut debouncer: KeyedDebouncer<String, QueuedInbound> = KeyedDebouncer::new();
+ let mut ready: VecDeque<(String, Vec<QueuedInbound>)> = VecDeque::new();
+
+ loop {
+ while turns.len() < max_in_flight {
+ let Some((key, batch)) = ready.pop_front() else {
+ break;
+ };
+ let batch_len = batch.len();
+ held = held.saturating_sub(batch_len);
+ // The turn runner serializes and steers per conversation, so the
+ // debouncer lets go of the key as soon as the batch is dispatched.
+ debouncer.complete(&key);
+ if let Some(admitted) = merge_channel_batch(batch) {
+ tracing::debug!(
+ channel = %admitted.msg.channel,
+ message_id = %admitted.msg.id,
+ batch_len,
+ in_flight = turns.len() + 1,
+ held,
+ "[dispatch][debounce] starting turn"
+ );
+ turns.spawn(run_admitted_turn(Arc::clone(&ctx), admitted));
}
}
- workers.spawn(process_channel_runtime_message(Arc::clone(&ctx), message));
- while let Some(result) = workers.try_join_next() {
- if let Err(error) = result {
- tracing::warn!("channel dispatch worker failed: {error}");
+ if !inbound_open
+ && admitting.is_empty()
+ && turns.is_empty()
+ && ready.is_empty()
+ && debouncer.is_empty()
+ {
+ break;
+ }
+
+ let wakeup = debouncer.next_wakeup();
+ tokio::select! {
+ received = rx.recv(), if inbound_open
+ && admitting.len() < max_in_flight
+ && admitting.len() + admission_order.waiting() + held < budget => {
+ match received {
+ Some(message) => {
+ let seq = next_seq;
+ next_seq += 1;
+ let handle = admitting.spawn(admit_runtime_message(Arc::clone(&ctx), message));
+ admit_seqs.insert(handle.id(), seq);
+ }
+ None => {
+ tracing::debug!(
+ buffered_keys = debouncer.tracked(),
+ "[dispatch][debounce] inbound queue closed; flushing buffered messages"
+ );
+ inbound_open = false;
+ }
+ }
+ }
+ Some(joined) = admitting.join_next_with_id(), if !admitting.is_empty() => {
+ let (id, result) = match joined {
+ Ok((id, result)) => (id, result),
+ Err(error) => {
+ let id = error.id();
+ log_join_error("admission", Some(error));
+ (id, None)
+ }
+ };
+ if let Some(seq) = admit_seqs.remove(&id) {
+ for (seq, inbound) in admission_order.finish(seq, result) {
+ held += 1;
+ buffer_admitted(&debounce, &mut debouncer, seq, inbound);
+ }
+ }
}
+ Some(joined) = turns.join_next(), if !turns.is_empty() => {
+ if let Err(error) = joined {
+ log_join_error("turn", Some(error));
+ }
+ }
+ _ = tokio::time::sleep_until(wakeup.unwrap_or_else(Instant::now)), if wakeup.is_some() => {}
}
- }
- while let Some(result) = workers.join_next().await {
- if let Err(error) = result {
- tracing::warn!("channel dispatch worker failed: {error}");
+
+ let now = Instant::now();
+ if !inbound_open && admitting.is_empty() {
+ debouncer.flush_all(now);
}
+ ready.extend(debouncer.poll_ready(now));
+ }
+}
+
+/// Admitted messages the loop holds before it stops receiving: a full batch
+/// for every turn worker.
+fn intake_budget(max_in_flight: usize, debounce: &InboundDebounceConfig) -> usize {
+ max_in_flight.saturating_mul(debounce.max_batch_messages.max(1))
+}
+
+fn buffer_admitted(
+ debounce: &InboundDebounceConfig,
+ debouncer: &mut KeyedDebouncer<String, QueuedInbound>,
+ seq: u64,
+ inbound: AdmittedInbound,
+) {
+ let settings = debounce.settings_for(&inbound.msg.channel);
+ let channel = inbound.msg.channel.clone();
+ let key = inbound.history_key.clone();
+ let push = debouncer.push(
+ key,
+ QueuedInbound { seq, inbound },
+ &settings,
+ Instant::now(),
+ );
+ tracing::debug!(
+ channel = %channel,
+ seq,
+ outcome = ?push,
+ tracked = debouncer.tracked(),
+ "[dispatch][debounce] buffered inbound message"
+ );
+}
+
+fn log_join_error(stage: &str, error: Option<tokio::task::JoinError>) {
+ if let Some(error) = error {
+ tracing::warn!("channel dispatch {stage} worker failed: {error}");
}
}
diff --git a/crates/openhuman-core/src/channels/runtime/startup/start_channels.rs b/crates/openhuman-core/src/channels/runtime/startup/start_channels.rs
index 8c09338d67..57fe9f6948 100644
--- a/crates/openhuman-core/src/channels/runtime/startup/start_channels.rs
+++ b/crates/openhuman-core/src/channels/runtime/startup/start_channels.rs
@@ -269,7 +269,12 @@ async fn start_channels_inner(mut config: Config, session: CancellationToken) ->
tokio::select! {
biased;
_ = session.cancelled() => {},
- _ = run_message_dispatch_loop(rx, runtime_ctx, max_in_flight_messages) => {},
+ _ = run_message_dispatch_loop(
+ rx,
+ runtime_ctx,
+ max_in_flight_messages,
+ config.inbound_debounce.clone(),
+ ) => {},
}
crate::cron::channel_bridge::clear_channel_bridge();
if let Some(runtime) = module_runtime.as_mut() {