Skip to content

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

chore: files changed crates/openhuman-core/src/flows/bus/trigger.rs,crates/openhuman-core/src/flows/

Steven Enamakela0bb7380edbc
diff --git a/crates/openhuman-core/src/flows/bus/trigger.rs b/crates/openhuman-core/src/flows/bus/trigger.rs
index 1cc430d057..7d05a1c5b3 100644
--- a/crates/openhuman-core/src/flows/bus/trigger.rs
+++ b/crates/openhuman-core/src/flows/bus/trigger.rs
@@ -94,6 +94,8 @@ struct DispatchKey {
struct FlowRunQueue {
sender: mpsc::Sender<QueuedRun>,
+ receiver: Mutex<Option<mpsc::Receiver<QueuedRun>>>,
+ worker_started: std::sync::atomic::AtomicBool,
admission: Arc<AsyncMutex<()>>,
outstanding: AtomicUsize,
}
@@ -104,6 +106,30 @@ struct QueuedRun {
request: TriggerRunRequest,
}
+struct QueueOutstanding {
+ queue: Arc<FlowRunQueue>,
+ armed: bool,
+}
+
+impl QueueOutstanding {
+ fn new(queue: Arc<FlowRunQueue>) -> Self {
+ queue.outstanding.fetch_add(1, Ordering::AcqRel);
+ Self { queue, armed: true }
+ }
+
+ fn transfer_to_worker(mut self) {
+ self.armed = false;
+ }
+}
+
+impl Drop for QueueOutstanding {
+ fn drop(&mut self) {
+ if self.armed {
+ self.queue.outstanding.fetch_sub(1, Ordering::AcqRel);
+ }
+ }
+}
+
pub(crate) struct TriggerRunRequest {
pub(crate) flow_id: String,
pub(crate) input: Value,
@@ -246,12 +272,38 @@ impl FlowTriggerSubscriber {
let (sender, receiver) = mpsc::channel(self.queue_capacity);
let queue = Arc::new(FlowRunQueue {
sender,
+ receiver: Mutex::new(Some(receiver)),
+ worker_started: std::sync::atomic::AtomicBool::new(false),
admission: Arc::new(AsyncMutex::new(())),
outstanding: AtomicUsize::new(0),
});
queues.insert(key.clone(), Arc::clone(&queue));
+ queue
+ }
+
+ fn start_worker_if_needed(
+ &self,
+ key: &DispatchKey,
+ queue: &Arc<FlowRunQueue>,
+ ctx: &crate::core::runtime::DispatchCtx,
+ ) {
+ if queue
+ .worker_started
+ .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
+ .is_err()
+ {
+ return;
+ }
+ let Some(receiver) = queue
+ .receiver
+ .lock()
+ .unwrap_or_else(|error| error.into_inner())
+ .take()
+ else {
+ return;
+ };
let worker_key = key.clone();
- let worker_queue = Arc::clone(&queue);
+ let worker_queue = Arc::clone(queue);
let worker_queues = Arc::clone(&self.queues);
let runner = Arc::clone(&self.runner);
#[cfg(test)]
@@ -268,7 +320,6 @@ impl FlowTriggerSubscriber {
)
.await;
});
- queue
}
async fn enqueue_app_event(
@@ -286,12 +337,17 @@ impl FlowTriggerSubscriber {
continue;
}
- queue.outstanding.fetch_add(1, Ordering::AcqRel);
+ let outstanding = QueueOutstanding::new(Arc::clone(&queue));
match queue.sender.send(queued).await {
- Ok(()) => return,
+ Ok(()) => {
+ outstanding.transfer_to_worker();
+ drop(admission);
+ self.start_worker_if_needed(&key, &queue, ctx);
+ return;
+ }
Err(error) => {
queued = error.0;
- queue.outstanding.fetch_sub(1, Ordering::AcqRel);
+ drop(outstanding);
drop(admission);
self.remove_queue_if_current(&key, &queue);
}
@@ -342,7 +398,11 @@ impl FlowTriggerSubscriber {
queue.outstanding.fetch_add(1, Ordering::AcqRel);
match queue.sender.try_send(queued) {
- Ok(()) => return,
+ Ok(()) => {
+ drop(admission);
+ self.start_worker_if_needed(&key, &queue, ctx);
+ return;
+ }
Err(mpsc::error::TrySendError::Full(_)) => {
queue.outstanding.fetch_sub(1, Ordering::AcqRel);
tracing::debug!(target: "flows", flow_id = %key.flow_id, "[flows] schedule tick coalesced while a trigger run is queued");
@@ -497,9 +557,11 @@ async fn run_queue_worker(
while let Some(mut queued) = next {
loop {
let run_ctx = queued.ctx.clone();
- run_ctx
- .enter((runner)(queued.ctx, queued.config, queued.request))
- .await;
+ let flow_id = queued.request.flow_id.clone();
+ let run = run_ctx.spawn((runner)(queued.ctx, queued.config, queued.request));
+ if let Err(error) = run.await {
+ tracing::warn!(target: "flows", %flow_id, error = %error, "[flows] trigger run task exited unexpectedly");
+ }
queue.outstanding.fetch_sub(1, Ordering::AcqRel);
if let Ok(queued) = receiver.try_recv() {
@@ -513,7 +575,7 @@ async fn run_queue_worker(
// slot before retirement gets SendError and retries with the new
// slot.
#[cfg(test)]
- retiring.notify_waiters();
+ retiring.notify_one();
let admission = Arc::clone(&queue.admission).lock_owned().await;
match receiver.try_recv() {
Ok(queued) => {
@@ -522,6 +584,7 @@ async fn run_queue_worker(
break;
}
Err(mpsc::error::TryRecvError::Empty | mpsc::error::TryRecvError::Disconnected) => {
+ receiver.close();
let mut current = queues.lock().unwrap_or_else(|error| error.into_inner());
if current
.get(&key)
diff --git a/crates/openhuman-core/src/flows/bus_subscriber_tests.rs b/crates/openhuman-core/src/flows/bus_subscriber_tests.rs
index 0e30364ba1..6209704d0b 100644
--- a/crates/openhuman-core/src/flows/bus_subscriber_tests.rs
+++ b/crates/openhuman-core/src/flows/bus_subscriber_tests.rs
@@ -175,6 +175,7 @@ async fn handle_schedule_tick_ignores_disabled_flow() {
#[tokio::test]
async fn schedule_tick_is_coalesced_while_a_trigger_run_is_active() {
+ use std::sync::Mutex;
use tokio::sync::{mpsc, oneshot};
let tmp = tempfile::TempDir::new().unwrap();
@@ -271,14 +272,8 @@ async fn app_event_runs_queue_fifo_per_tenant_while_other_tenants_progress() {
.dispatch_test_app_event(&tenant_b, "shared-flow", json!({"event": "b1"}))
.await;
- let receive = async |rx: &mut mpsc::UnboundedReceiver<_>| {
- tokio::time::timeout(std::time::Duration::from_secs(2), rx.recv())
- .await
- .expect("queued trigger did not finish within the hang guard")
- .unwrap()
- };
assert_eq!(
- receive(&mut completed_rx).await,
+ receive_trigger_run(&mut completed_rx).await,
(
"tenant-b".to_string(),
"shared-flow".to_string(),
@@ -288,7 +283,7 @@ async fn app_event_runs_queue_fifo_per_tenant_while_other_tenants_progress() {
);
release_first_tx.send(()).unwrap();
assert_eq!(
- receive(&mut completed_rx).await,
+ receive_trigger_run(&mut completed_rx).await,
(
"tenant-a".to_string(),
"shared-flow".to_string(),
@@ -296,7 +291,7 @@ async fn app_event_runs_queue_fifo_per_tenant_while_other_tenants_progress() {
)
);
assert_eq!(
- receive(&mut completed_rx).await,
+ receive_trigger_run(&mut completed_rx).await,
(
"tenant-a".to_string(),
"shared-flow".to_string(),
@@ -306,6 +301,150 @@ async fn app_event_runs_queue_fifo_per_tenant_while_other_tenants_progress() {
);
}
+async fn receive_trigger_run(
+ receiver: &mut tokio::sync::mpsc::UnboundedReceiver<(String, String, String)>,
+) -> (String, String, String) {
+ tokio::time::timeout(std::time::Duration::from_secs(2), receiver.recv())
+ .await
+ .expect("queued trigger did not finish within the hang guard")
+ .unwrap()
+}
+
+#[tokio::test]
+async fn full_app_event_queue_backpressures_until_a_slot_opens() {
+ use std::sync::Mutex;
+ use tokio::sync::{mpsc, oneshot};
+
+ let tmp = tempfile::TempDir::new().unwrap();
+ let (started_tx, started_rx) = oneshot::channel();
+ let started_tx = Arc::new(Mutex::new(Some(started_tx)));
+ let (release_tx, release_rx) = oneshot::channel();
+ let release_rx = Arc::new(tokio::sync::Mutex::new(Some(release_rx)));
+ let (runs_tx, mut runs_rx) = mpsc::unbounded_channel();
+ let runner = move |_ctx: crate::core::runtime::DispatchCtx,
+ _config: Arc<Config>,
+ request: crate::flows::bus::trigger::TriggerRunRequest| {
+ let started_tx = Arc::clone(&started_tx);
+ let release_rx = Arc::clone(&release_rx);
+ let runs_tx = runs_tx.clone();
+ async move {
+ let event = request.input["event"].as_str().unwrap().to_owned();
+ if event == "a1" {
+ if let Some(started_tx) = started_tx.lock().unwrap().take() {
+ let _ = started_tx.send(());
+ }
+ if let Some(release) = release_rx.lock().await.take() {
+ let _ = release.await;
+ }
+ }
+ runs_tx.send(event).unwrap();
+ }
+ };
+ let subscriber = FlowTriggerSubscriber::with_runner(test_config(&tmp), 1, runner);
+ let ctx = crate::core::runtime::DispatchCtx::host_default();
+
+ subscriber
+ .dispatch_test_app_event(&ctx, "f1", json!({"event": "a1"}))
+ .await;
+ started_rx.await.unwrap();
+ subscriber
+ .dispatch_test_app_event(&ctx, "f1", json!({"event": "a2"}))
+ .await;
+ let third = subscriber.dispatch_test_app_event(&ctx, "f1", json!({"event": "a3"}));
+ tokio::pin!(third);
+ assert!(
+ futures::poll!(third.as_mut()).is_pending(),
+ "a full bounded queue must wait for capacity instead of dropping the event"
+ );
+
+ release_tx.send(()).unwrap();
+ third.await;
+ for expected in ["a1", "a2", "a3"] {
+ assert_eq!(
+ tokio::time::timeout(std::time::Duration::from_secs(2), runs_rx.recv())
+ .await
+ .expect("backpressured trigger did not finish")
+ .unwrap(),
+ expected
+ );
+ }
+}
+
+#[tokio::test]
+async fn arrival_racing_worker_retirement_is_retried_on_a_fresh_queue() {
+ use std::sync::Mutex;
+ use tokio::sync::{mpsc, oneshot};
+
+ let tmp = tempfile::TempDir::new().unwrap();
+ let (started_tx, started_rx) = oneshot::channel();
+ let started_tx = Arc::new(Mutex::new(Some(started_tx)));
+ let (release_tx, release_rx) = oneshot::channel();
+ let release_rx = Arc::new(tokio::sync::Mutex::new(Some(release_rx)));
+ let (runs_tx, mut runs_rx) = mpsc::unbounded_channel();
+ let runner = move |_ctx: crate::core::runtime::DispatchCtx,
+ _config: Arc<Config>,
+ request: crate::flows::bus::trigger::TriggerRunRequest| {
+ let started_tx = Arc::clone(&started_tx);
+ let release_rx = Arc::clone(&release_rx);
+ let runs_tx = runs_tx.clone();
+ async move {
+ let event = request.input["event"].as_str().unwrap().to_owned();
+ if event == "first" {
+ if let Some(started_tx) = started_tx.lock().unwrap().take() {
+ let _ = started_tx.send(());
+ }
+ if let Some(release) = release_rx.lock().await.take() {
+ let _ = release.await;
+ }
+ }
+ runs_tx.send(event).unwrap();
+ }
+ };
+ let subscriber = Arc::new(FlowTriggerSubscriber::with_runner(test_config(&tmp), 1, runner));
+ let ctx = crate::core::runtime::DispatchCtx::host_default();
+ let retiring = subscriber.retirement_notifier_test();
+ let retirement_started = retiring.notified();
+ tokio::pin!(retirement_started);
+
+ subscriber
+ .dispatch_test_app_event(&ctx, "f1", json!({"event": "first"}))
+ .await;
+ started_rx.await.unwrap();
+ let admission = subscriber.hold_queue_admission_test(&ctx, "f1").await;
+ release_tx.send(()).unwrap();
+ retirement_started.await;
+
+ // The worker notified just before it queued on the held admission gate.
+ // Tokio's mutex is FIFO, so its retirement request is ahead of this send.
+ let retry_subscriber = Arc::clone(&subscriber);
+ let retry_ctx = ctx.clone();
+ let arrival = tokio::spawn(async move {
+ retry_subscriber
+ .dispatch_test_app_event(&retry_ctx, "f1", json!({"event": "after-retirement"}))
+ .await;
+ });
+ tokio::task::yield_now().await;
+ drop(admission);
+ tokio::time::timeout(std::time::Duration::from_secs(2), arrival)
+ .await
+ .expect("the arrival stayed attached to a retired queue")
+ .unwrap();
+ assert_eq!(
+ tokio::time::timeout(std::time::Duration::from_secs(2), runs_rx.recv())
+ .await
+ .expect("arrival after worker retirement was lost")
+ .unwrap(),
+ "first"
+ );
+ assert_eq!(
+ tokio::time::timeout(std::time::Duration::from_secs(2), runs_rx.recv())
+ .await
+ .expect("retry on the fresh worker was lost")
+ .unwrap(),
+ "after-retirement"
+ );
+}
+
#[test]
fn default_constructs_the_same_as_new() {
let tmp = tempfile::TempDir::new().unwrap();