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(flows): prevent duplicate terminal events after process restart
Steven Enamakelef5b4f1598e3
diff --git a/crates/openhuman-core/src/flows/runs_adapter.rs b/crates/openhuman-core/src/flows/runs_adapter.rsindex b151777384..7e9dfeb381 100644--- a/crates/openhuman-core/src/flows/runs_adapter.rs+++ b/crates/openhuman-core/src/flows/runs_adapter.rs@@ -276,12 +276,19 @@ pub(crate) async fn register_resume_bindings(/// process-restarted waiter cannot mistake an earlier `parked` event for the/// result of this resume.pub(crate) async fn resume_and_wait(- ctx: &DispatchCtx,+ _ctx: &DispatchCtx,config: &Config,request: ResumeRun,candidate: Arc<RunBindings>,) -> Result<ResumeOutcome, String> {let storage = request.storage.clone();+ if candidate.flow_id != request.flow_id+ || candidate.run_id != request.run_id+ || candidate.storage() != storage+ || candidate.caps_host() != request.caps_host+ {+ return Err("resume bindings do not match the owner-scoped request".to_string());+ }let key = RunKey::new(&storage, &request.run_id);let proxy = module::runs_proxy(config).await?;let (session, inserted) = match session::get(&storage, &request.run_id) {@@ -328,9 +335,9 @@ pub(crate) async fn resume_and_wait(session.replace_flow(candidate.flow.clone()).await;session.set_trigger(FlowRunTrigger::Resume);+ session.mark_resumed();session.replace_bindings(candidate).await;session.start_polling(proxy);- let _ = ctx;wait_for_outcome(&mut receiver, &request.run_id, baseline).await}diff --git a/crates/openhuman-core/src/flows/runs_adapter/projection.rs b/crates/openhuman-core/src/flows/runs_adapter/projection.rsindex a72f990a5e..f330ca932d 100644--- a/crates/openhuman-core/src/flows/runs_adapter/projection.rs+++ b/crates/openhuman-core/src/flows/runs_adapter/projection.rs@@ -1,11 +1,20 @@//! Project module-owned PollRun events onto OpenHuman events and Langfuse.+use std::collections::{HashSet, VecDeque};+use std::sync::{LazyLock, Mutex};+use serde_json::Value;use tinyflows_bus::runs::{self, RunEvent};use tinyflows_catalog::types::FlowRunTrigger;use crate::core::events::DomainEvent;use crate::flows::runs_adapter::session::RunSession;+use crate::flows::runs_adapter::RunKey;++const RECENT_FINISHED_KEYS: usize = 4_096;++static FINISHED_KEYS: LazyLock<Mutex<(HashSet<RunKey>, VecDeque<RunKey>)>> =+ LazyLock::new(|| Mutex::new((HashSet::new(), VecDeque::new())));pub(super) async fn project(session: &RunSession, event: &RunEvent) {match event.kind.as_str() {@@ -17,7 +26,10 @@ pub(super) async fn project(session: &RunSession, event: &RunEvent) {});}}- "resumed" => session.set_trigger(FlowRunTrigger::Resume),+ "resumed" => {+ session.set_trigger(FlowRunTrigger::Resume);+ session.mark_resumed();+ }"step_started" => {if let Some(node_id) = event.data.get("node_id").and_then(Value::as_str) {publish_step(session, node_id, "running");@@ -42,11 +54,11 @@ pub(super) async fn project(session: &RunSession, event: &RunEvent) {),},"agent_progress" => {- // The UI's existing workflow overlay is node-based. The detailed- // agent events stay on the module stream; consume them here so the- // shared cursor remains the sole owner of event ordering.+ // Detailed agent events remain on the module stream. The OpenHuman+ // workflow overlay consumes the node-level progress events above.}"parked" => {+ session.mark_parked();let parked = match serde_json::from_value::<runs::RunParked>(event.data.clone()) {Ok(parked) => parked,Err(_) => {@@ -78,19 +90,58 @@ pub(super) async fn project(session: &RunSession, event: &RunEvent) {return;}};- if session.mark_finished() {+ if claim_finished(session.key()) {crate::core::bus::BUS.publish(DomainEvent::FlowRunFinished {flow_id: session.flow_id().to_owned(),run_id: session.run_id.clone(),status: finished.status.clone(),});+ export_segment(session, &finished.status).await;}- export_segment(session, &finished.status).await;+ session.mark_finished();}_ => {}}}+/// Project a recovery event when the run no longer has an in-process session.+/// This path publishes only the newly committed terminal event; historical+/// start/progress events are not replayed after a process restart.+pub(crate) fn project_recovered_finished(+ key: &RunKey,+ flow_id: &str,+ run_id: &str,+ event: &RunEvent,+) {+ let Ok(finished) = serde_json::from_value::<runs::RunFinished>(event.data.clone()) else {+ tracing::warn!(target: "flows", run_id, "[flows] recovery PollRun terminal outcome could not be decoded");+ return;+ };+ if claim_finished(key.clone()) {+ crate::core::bus::BUS.publish(DomainEvent::FlowRunFinished {+ flow_id: flow_id.to_owned(),+ run_id: run_id.to_owned(),+ status: finished.status,+ });+ }+}++fn claim_finished(key: RunKey) -> bool {+ let mut finished = FINISHED_KEYS+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner);+ if !finished.0.insert(key.clone()) {+ return false;+ }+ finished.1.push_back(key);+ while finished.1.len() > RECENT_FINISHED_KEYS {+ if let Some(expired) = finished.1.pop_front() {+ finished.0.remove(&expired);+ }+ }+ true+}+fn publish_step(session: &RunSession, node_id: &str, status: &str) {crate::core::bus::BUS.publish(DomainEvent::FlowRunProgress {run_id: session.run_id.clone(),diff --git a/crates/openhuman-core/src/flows/runs_adapter/session.rs b/crates/openhuman-core/src/flows/runs_adapter/session.rsindex ad9b44d1d1..054c1ec216 100644--- a/crates/openhuman-core/src/flows/runs_adapter/session.rs+++ b/crates/openhuman-core/src/flows/runs_adapter/session.rs@@ -45,6 +45,7 @@ pub(crate) struct RunSession {poller_started: std::sync::atomic::AtomicBool,started_event: std::sync::atomic::AtomicBool,finished_event: std::sync::atomic::AtomicBool,+ live_actor: std::sync::atomic::AtomicBool,observations: Mutex<Vec<tinyagents_graph::GraphObservation>>,}@@ -59,6 +60,7 @@ impl RunSession {trigger: FlowRunTrigger,cursor: u64,) -> Arc<Self> {+ let live_actor = trigger != FlowRunTrigger::Resume;Arc::new(Self {run_id: bindings.run_id.clone(),flow_id: bindings.flow_id.clone(),@@ -72,6 +74,7 @@ impl RunSession {poller_started: std::sync::atomic::AtomicBool::new(false),started_event: std::sync::atomic::AtomicBool::new(false),finished_event: std::sync::atomic::AtomicBool::new(false),+ live_actor: std::sync::atomic::AtomicBool::new(live_actor),observations: Mutex::new(Vec::new()),})}@@ -155,17 +158,39 @@ impl RunSession {}pub(super) fn mark_started(&self) -> bool {+ self.live_actor.store(true, std::sync::atomic::Ordering::Release);!self.started_event.swap(true, std::sync::atomic::Ordering::AcqRel)}pub(super) fn mark_finished(&self) -> bool {+ self.live_actor.store(false, std::sync::atomic::Ordering::Release);!self.finished_event.swap(true, std::sync::atomic::Ordering::AcqRel)}+ pub(super) fn mark_parked(&self) {+ self.live_actor.store(false, std::sync::atomic::Ordering::Release);+ }++ pub(super) fn mark_resumed(&self) {+ self.live_actor.store(true, std::sync::atomic::Ordering::Release);+ }++ pub(super) fn is_live_actor(&self) -> bool {+ self.live_actor.load(std::sync::atomic::Ordering::Acquire)+ }++ pub(super) fn key(&self) -> RunKey {+ let bindings = self+ .bindings+ .read()+ .unwrap_or_else(std::sync::PoisonError::into_inner);+ RunKey::new(&bindings.storage(), &self.run_id)+ }+/// Start the one PollRun task for this process/run owner.pub(super) fn start_polling(self: &Arc<Self>, proxy: tinybus::Proxy) {if self@@ -284,19 +309,3 @@ pub(crate) fn remove(session: &Arc<RunSession>) {}}-pub(crate) fn get_by_key(key: &RunKey) -> Option<Arc<RunSession>> {- SESSIONS- .lock()- .unwrap_or_else(std::sync::PoisonError::into_inner)- .get(key)- .cloned()-}--pub(crate) fn sessions() -> Vec<Arc<RunSession>> {- SESSIONS- .lock()- .unwrap_or_else(std::sync::PoisonError::into_inner)- .values()- .cloned()- .collect()-}