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 Enamakel58bef1318961
diff --git a/crates/openhuman-core/src/flows/bus/trigger.rs b/crates/openhuman-core/src/flows/bus/trigger.rs
index 09751c6dc7..1360abb498 100644
--- a/crates/openhuman-core/src/flows/bus/trigger.rs
+++ b/crates/openhuman-core/src/flows/bus/trigger.rs
@@ -191,13 +191,20 @@ impl FlowTriggerSubscriber {
payload: Value,
inputs: serde_json::Map<String, Value>,
) {
- self.spawn_run(
- ctx,
- flow_id,
- payload,
- inputs,
- tinyflows_catalog::FlowRunTrigger::AppEvent,
- );
+ let Some(key) = self.dispatch_key(ctx, &flow_id) else {
+ return;
+ };
+ let queued = QueuedRun {
+ ctx: ctx.clone(),
+ config: self.config_for_scope(ctx),
+ request: TriggerRunRequest {
+ flow_id,
+ input: payload,
+ inputs,
+ trigger: tinyflows_catalog::FlowRunTrigger::AppEvent,
+ },
+ };
+ self.enqueue_app_event(key, ctx, queued).await;
}
#[cfg(test)]
@@ -211,6 +218,160 @@ impl FlowTriggerSubscriber {
.await;
}
+ fn dispatch_key(
+ &self,
+ ctx: &crate::core::runtime::DispatchCtx,
+ flow_id: &str,
+ ) -> Option<DispatchKey> {
+ match ctx.tenant() {
+ Ok(tenant) => Some(DispatchKey {
+ tenant,
+ flow_id: flow_id.to_string(),
+ }),
+ Err(error) => {
+ tracing::warn!(target: "flows", %flow_id, error = %error, "[flows] trigger dispatch has no tenant scope; refusing to use the host config");
+ None
+ }
+ }
+ }
+
+ fn queue_for(
+ &self,
+ key: &DispatchKey,
+ ctx: &crate::core::runtime::DispatchCtx,
+ ) -> Arc<FlowRunQueue> {
+ let mut queues = self.queues.lock().unwrap_or_else(|error| error.into_inner());
+ if let Some(queue) = queues.get(key).filter(|queue| !queue.sender.is_closed()) {
+ return Arc::clone(queue);
+ }
+
+ let (sender, receiver) = mpsc::channel(self.queue_capacity);
+ let queue = Arc::new(FlowRunQueue {
+ sender,
+ admission: Arc::new(AsyncMutex::new(())),
+ outstanding: AtomicUsize::new(0),
+ });
+ queues.insert(key.clone(), Arc::clone(&queue));
+ let worker_key = key.clone();
+ let worker_queue = Arc::clone(&queue);
+ let worker_queues = Arc::clone(&self.queues);
+ let runner = Arc::clone(&self.runner);
+ #[cfg(test)]
+ let retiring = Arc::clone(&self.retiring);
+ ctx.spawn(async move {
+ run_queue_worker(
+ worker_key,
+ worker_queue,
+ receiver,
+ worker_queues,
+ runner,
+ #[cfg(test)]
+ retiring,
+ )
+ .await;
+ });
+ queue
+ }
+
+ async fn enqueue_app_event(
+ &self,
+ key: DispatchKey,
+ ctx: &crate::core::runtime::DispatchCtx,
+ mut queued: QueuedRun,
+ ) {
+ loop {
+ let queue = self.queue_for(&key, ctx);
+ let admission = Arc::clone(&queue.admission).lock_owned().await;
+ if queue.sender.is_closed() {
+ drop(admission);
+ self.remove_queue_if_current(&key, &queue);
+ continue;
+ }
+
+ queue.outstanding.fetch_add(1, Ordering::AcqRel);
+ match queue.sender.send(queued).await {
+ Ok(()) => return,
+ Err(error) => {
+ queued = error.0;
+ queue.outstanding.fetch_sub(1, Ordering::AcqRel);
+ drop(admission);
+ self.remove_queue_if_current(&key, &queue);
+ }
+ }
+ }
+ }
+
+ async fn enqueue_schedule(
+ &self,
+ ctx: &crate::core::runtime::DispatchCtx,
+ flow_id: String,
+ inputs: serde_json::Map<String, Value>,
+ ) {
+ let Some(key) = self.dispatch_key(ctx, &flow_id) else {
+ return;
+ };
+ let queued = QueuedRun {
+ ctx: ctx.clone(),
+ config: self.config_for_scope(ctx),
+ request: TriggerRunRequest {
+ flow_id: flow_id.clone(),
+ input: Value::Null,
+ inputs,
+ trigger: tinyflows_catalog::FlowRunTrigger::Schedule,
+ },
+ };
+ self.enqueue_schedule_request(key, ctx, queued).await;
+ }
+
+ async fn enqueue_schedule_request(
+ &self,
+ key: DispatchKey,
+ ctx: &crate::core::runtime::DispatchCtx,
+ mut queued: QueuedRun,
+ ) {
+ loop {
+ let queue = self.queue_for(&key, ctx);
+ let admission = Arc::clone(&queue.admission).lock_owned().await;
+ if queue.sender.is_closed() {
+ drop(admission);
+ self.remove_queue_if_current(&key, &queue);
+ continue;
+ }
+ if queue.outstanding.load(Ordering::Acquire) != 0 {
+ tracing::debug!(target: "flows", %flow_id, "[flows] schedule tick coalesced while a trigger run is queued or active");
+ return;
+ }
+
+ queue.outstanding.fetch_add(1, Ordering::AcqRel);
+ match queue.sender.try_send(queued) {
+ Ok(()) => return,
+ Err(mpsc::error::TrySendError::Full(_)) => {
+ queue.outstanding.fetch_sub(1, Ordering::AcqRel);
+ tracing::debug!(target: "flows", %flow_id, "[flows] schedule tick coalesced while a trigger run is queued");
+ return;
+ }
+ Err(mpsc::error::TrySendError::Closed(returned)) => {
+ queue.outstanding.fetch_sub(1, Ordering::AcqRel);
+ drop(admission);
+ self.remove_queue_if_current(&key, &queue);
+ // Keep the value available if the retiring worker won
+ // the race with this schedule tick.
+ queued = returned;
+ }
+ }
+ }
+ }
+
+ fn remove_queue_if_current(&self, key: &DispatchKey, queue: &Arc<FlowRunQueue>) {
+ let mut queues = self.queues.lock().unwrap_or_else(|error| error.into_inner());
+ if queues
+ .get(key)
+ .is_some_and(|current| Arc::ptr_eq(current, queue))
+ {
+ queues.remove(key);
+ }
+ }
+
/// The configuration to handle an event under (`super::owner::config_for_scope`).
pub(super) fn config_for_scope(&self, ctx: &crate::core::runtime::DispatchCtx) -> Arc<Config> {
super::owner::config_for_scope(ctx, &self.config)
@@ -255,13 +416,7 @@ impl FlowTriggerSubscriber {
return;
}
let inputs = pinned_trigger_inputs(&flow);
- self.spawn_run(
- &ctx,
- flow_id.to_string(),
- Value::Null,
- inputs,
- tinyflows_catalog::FlowRunTrigger::Schedule,
- );
+ self.enqueue_schedule(&ctx, flow_id.to_string(), inputs).await;
}
/// `DomainEvent::ComposioTriggerReceived` — scans every enabled flow for
@@ -301,64 +456,89 @@ impl FlowTriggerSubscriber {
tracing::debug!(target: "flows", %toolkit, %trigger_slug, matched, "[flows] app_event trigger matching complete");
}
- /// Spawns a background `flows::ops::flows_run` for `flow_id`. Fire-and-
- /// forget from the bus's perspective — `flows_run` itself records the
- /// outcome onto the flow's summary fields and a `flow_runs` history row,
- /// and surfaces a `CoreNotification` when the run pauses for approval.
- ///
- /// Skips the dispatch (see [`try_acquire_dispatch`]) if a trigger-driven
- /// run for this `flow_id` is already in flight, so a fast schedule or a
- /// burst of matching `app_event`s cannot run the same flow concurrently.
- fn spawn_run(
+ #[cfg(test)]
+ pub(crate) async fn dispatch_test_schedule(
&self,
ctx: &crate::core::runtime::DispatchCtx,
- flow_id: String,
- input: Value,
- inputs: serde_json::Map<String, Value>,
- trigger: tinyflows_catalog::FlowRunTrigger,
+ flow_id: &str,
) {
- let Some(guard) = self.try_acquire_dispatch(&flow_id) else {
- tracing::debug!(target: "flows", %flow_id, "[flows] trigger: flow already running — skipping this tick");
- return;
- };
+ self.enqueue_schedule(ctx, flow_id.to_string(), serde_json::Map::new())
+ .await;
+ }
- let run_ctx = ctx.clone();
- let config = self.config_for_scope(ctx);
- let request = TriggerRunRequest {
- flow_id: flow_id.clone(),
- input,
- inputs,
- trigger,
- };
- let runner = Arc::clone(&self.runner);
- // Scoped: the run keeps the owner's context the handler entered.
- ctx.spawn(async move {
- // Held for the lifetime of the run; released on drop (including
- // on panic) by `InFlightGuard`.
- let _guard = guard;
- run_ctx
- .enter((runner)(run_ctx.clone(), config, request))
- .await;
- });
+ #[cfg(test)]
+ pub(crate) async fn hold_queue_admission_test(
+ &self,
+ ctx: &crate::core::runtime::DispatchCtx,
+ flow_id: &str,
+ ) -> tokio::sync::OwnedMutexGuard<()> {
+ let key = self.dispatch_key(ctx, flow_id).unwrap();
+ let queue = self.queue_for(&key, ctx);
+ Arc::clone(&queue.admission).lock_owned().await
}
-}
-/// Drop guard releasing a [`FlowTriggerSubscriber::try_acquire_dispatch`]
-/// claim. Removing the `flow_id` on `Drop` (rather than only on the happy
-/// path) means a panicking or erroring `flows_run` still frees the flow up
-/// for its next trigger tick.
-pub(super) struct InFlightGuard {
- set: Arc<Mutex<HashSet<String>>>,
- flow_id: String,
+ #[cfg(test)]
+ pub(crate) fn retirement_notifier_test(&self) -> Arc<tokio::sync::Notify> {
+ Arc::clone(&self.retiring)
+ }
}
-impl Drop for InFlightGuard {
- fn drop(&mut self) {
- // Recover from a poisoned lock (mirrors `try_acquire_dispatch`) so the
- // flow_id is always removed — otherwise a poison would wedge this flow
- // out of every future trigger dispatch, defeating the guard's purpose.
- let mut set = self.set.lock().unwrap_or_else(|e| e.into_inner());
- set.remove(&self.flow_id);
+async fn run_queue_worker(
+ key: DispatchKey,
+ queue: Arc<FlowRunQueue>,
+ mut receiver: mpsc::Receiver<QueuedRun>,
+ queues: Arc<Mutex<HashMap<DispatchKey, Arc<FlowRunQueue>>>>,
+ runner: Arc<RunExecutor>,
+ #[cfg(test)] retiring: Arc<tokio::sync::Notify>,
+) {
+ let mut next = receiver.recv().await;
+ while let Some(mut queued) = next {
+ loop {
+ let run_ctx = queued.ctx.clone();
+ run_ctx
+ .enter((runner)(queued.ctx, queued.config, queued.request))
+ .await;
+ queue.outstanding.fetch_sub(1, Ordering::AcqRel);
+
+ if let Ok(queued) = receiver.try_recv() {
+ next = Some(queued);
+ break;
+ }
+
+ // A producer takes the same gate before sending. Once this worker
+ // holds it and observes an empty receiver, no successful send can
+ // be stranded behind a closed receiver. A sender that cloned this
+ // slot before retirement gets SendError and retries with the new
+ // slot.
+ #[cfg(test)]
+ retiring.notify_waiters();
+ let admission = Arc::clone(&queue.admission).lock_owned().await;
+ match receiver.try_recv() {
+ Ok(queued) => {
+ drop(admission);
+ next = Some(queued);
+ break;
+ }
+ Err(mpsc::error::TryRecvError::Empty | mpsc::error::TryRecvError::Disconnected) => {
+ let mut current = queues.lock().unwrap_or_else(|error| error.into_inner());
+ if current
+ .get(&key)
+ .is_some_and(|entry| Arc::ptr_eq(entry, &queue))
+ {
+ current.remove(&key);
+ }
+ return;
+ }
+ }
+ }
+ }
+
+ let mut current = queues.lock().unwrap_or_else(|error| error.into_inner());
+ if current
+ .get(&key)
+ .is_some_and(|entry| Arc::ptr_eq(entry, &queue))
+ {
+ current.remove(&key);
}
}
diff --git a/crates/openhuman-core/src/flows/bus_subscriber_tests.rs b/crates/openhuman-core/src/flows/bus_subscriber_tests.rs
index ab3ea1028f..46aa237440 100644
--- a/crates/openhuman-core/src/flows/bus_subscriber_tests.rs
+++ b/crates/openhuman-core/src/flows/bus_subscriber_tests.rs
@@ -173,27 +173,41 @@ async fn handle_schedule_tick_ignores_disabled_flow() {
// ── in-flight dedupe (CodeRabbit finding B) ─────────────────────
-#[test]
-fn try_acquire_dispatch_skips_a_flow_already_in_flight() {
- let tmp = tempfile::TempDir::new().unwrap();
- let sub = FlowTriggerSubscriber::new(test_config(&tmp));
-
- let guard = sub
- .try_acquire_dispatch("f1")
- .expect("first claim for f1 should succeed");
- assert!(
- sub.try_acquire_dispatch("f1").is_none(),
- "a second claim for the same flow while the first is held must be skipped"
- );
+#[tokio::test]
+async fn schedule_tick_is_coalesced_while_a_trigger_run_is_active() {
+ use tokio::sync::{mpsc, oneshot};
- // A different flow is unaffected.
- assert!(sub.try_acquire_dispatch("f2").is_some());
+ 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 {
+ 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(request.trigger.as_str()).unwrap();
+ }
+ };
+ let sub = FlowTriggerSubscriber::with_runner(test_config(&tmp), 1, runner);
+ let ctx = crate::core::runtime::DispatchCtx::host_default();
- drop(guard);
- assert!(
- sub.try_acquire_dispatch("f1").is_some(),
- "dropping the guard must release the claim so f1 can run again"
- );
+ sub.dispatch_test_schedule(&ctx, "f1").await;
+ started_rx.await.unwrap();
+ sub.dispatch_test_schedule(&ctx, "f1").await;
+ release_tx.send(()).unwrap();
+ assert_eq!(runs_rx.recv().await, Some("schedule"));
+ assert!(runs_rx.try_recv().is_err(), "a busy schedule tick must be dropped");
}
#[tokio::test]