From 117397f4bd885a764cf7c3ccf01a61c612e090c4 Mon Sep 17 00:00:00 2001 From: Ghost Scripter Date: Wed, 11 Nov 2026 17:46:22 +0530 Subject: [PATCH 1/6] fix(inbound): triage an event once when every queue ingest times out When every Ingest attempt was ambiguous, route::offer sent the event down the caller's direct path, yet the module could have persisted it and delivered its copy too: two triages, two decisions applied. New inbound::claims settles who runs such an event, by source:event_id: - offer_or_direct (the Composio trigger and agent webhook paths) opens a claim before the first attempt and closes it when the queues answer; - a Deliver of an event with an open claim takes it, and the offer that gives up later does not run it directly; - an offer that gives up first takes it for the direct path and records it in the host collection inbound.direct (30 days, the module's tombstone TTL), so Deliver leaves it out of its turn and drops it as handled_directly, across a restart and a redrive too. offer itself is unchanged for inbound.offer, which has no direct path: its pusher retries, so marking the event handled would lose it. Closes #8154 Co-Authored-By: Claude Opus 5.5 --- crates/openhuman-core/src/inbound/README.md | 1 + crates/openhuman-core/src/inbound/claims.rs | 282 ++++++++++++++++++ .../src/inbound/claims_tests.rs | 79 +++++ crates/openhuman-core/src/inbound/deliver.rs | 51 +++- .../src/inbound/deliver_tests.rs | 39 +++ crates/openhuman-core/src/inbound/mod.rs | 2 + crates/openhuman-core/src/inbound/route.rs | 88 +++++- .../openhuman-core/src/inbound/route_tests.rs | 91 +++++- .../composio/bus/trigger_subscriber.rs | 2 +- .../openhuman-core/src/skills/webhooks/bus.rs | 2 +- crates/openhuman-core/src/storage/schema.rs | 2 + docs/storage-schema.md | 1 + 12 files changed, 620 insertions(+), 20 deletions(-) create mode 100644 crates/openhuman-core/src/inbound/claims.rs create mode 100644 crates/openhuman-core/src/inbound/claims_tests.rs diff --git a/crates/openhuman-core/src/inbound/README.md b/crates/openhuman-core/src/inbound/README.md index 2f20594c233..bae4d45461e 100644 --- a/crates/openhuman-core/src/inbound/README.md +++ b/crates/openhuman-core/src/inbound/README.md @@ -23,6 +23,7 @@ Two kinds of event take this path: | [`settings.rs`](./settings.rs) | `[inbound]` resolved: queues, pipeline (with one policy per external source first), backend, whether routing is on | | [`events.rs`](./events.rs) | a trigger envelope or an external event as an `InboundEvent`, and back | | [`route.rs`](./route.rs) | the hand-off; the direct path when the queues do not take an event | +| [`claims.rs`](./claims.rs) | who runs an event whose hand-off was ambiguous: the direct path or `Deliver`, never both; direct-path events recorded in `inbound.direct` (30 days) | | [`deliver.rs`](./deliver.rs) | `Deliver` and `ClassifySalience`: triage or the pinned agent, ack semantics, retries, dead letters | | [`pinned.rs`](./pinned.rs) | rendering a batch's prompt, running the pinned agent under `external_inbound_origin`, resuming unfinished turns at boot | | [`results.rs`](./results.rs) | pinned turns' results: `running`, `completed`, `failed`; listing, ack, TTL pruning | diff --git a/crates/openhuman-core/src/inbound/claims.rs b/crates/openhuman-core/src/inbound/claims.rs new file mode 100644 index 00000000000..8cda8b1e3ea --- /dev/null +++ b/crates/openhuman-core/src/inbound/claims.rs @@ -0,0 +1,282 @@ +//! Who runs an event whose hand-off to the queues was ambiguous: the +//! caller's direct path or the queues' `Deliver`. +//! +//! [`super::route::offer_or_direct`] falls back to its caller's direct path +//! when every `Ingest` attempt was ambiguous (a timeout, a transport fault), +//! yet the module may have persisted the event all the same and deliver it +//! later. Without a record that event is triaged twice. The claims decide +//! which side runs it, by the event's dedupe key (`source:event_id`): +//! +//! - the offer opens a claim before its first attempt and closes it when the +//! queues answer; +//! - a `Deliver` of an event whose claim is open takes it: the queues run +//! the event, and an offer that gives up later does not run it directly; +//! - an offer that gives up first takes the claim for the direct path and +//! records it on the host's storage, and every later `Deliver` of the +//! event skips it (publishing `InboundEventDropped`), across a restart too. +//! +//! | Collection | Document id | Holds | +//! | --- | --- | --- | +//! | `inbound.direct` | `Key::of([source:event_id])` | an event the direct path ran, and when | +//! +//! Records are kept as long as the module keeps its tombstones (30 days), +//! so a dead-lettered copy redriven later is still recognised. They are +//! rare: only an offer whose every attempt was ambiguous writes one. + +use std::collections::{HashMap, VecDeque}; +use std::sync::{LazyLock, Mutex, OnceLock, PoisonError}; + +use serde::{Deserialize, Serialize}; +use tinystoragedrivers::{CollectionSpec, ErrorKind, Precondition, Query}; + +use tinyeventqueues_bus::Turn; + +use crate::config::Config; +use crate::core::bus::BUS; +use crate::core::events::DomainEvent; +use crate::storage::documents::Repo; +use crate::storage::schema_support::key_of; +use crate::storage::DocumentStoreExt; + +/// The collection of events the direct path ran. +pub const DIRECT: &str = "inbound.direct"; +const DOMAIN: &str = "inbound::claims"; + +/// How many direct-path events are remembered in memory. +const CAPACITY: usize = 4_096; + +/// How long a direct-path event is recorded: the module's tombstone TTL. +const TTL_MS: i64 = 30 * 24 * 60 * 60 * 1_000; + +/// Why an event the direct path ran is not delivered. +pub const HANDLED_DIRECTLY: &str = "handled_directly"; + +/// What the inbound host keeps for its claims. +pub fn collection_specs() -> Vec { + vec![CollectionSpec::new(DIRECT)] +} + +/// Where an event's claim stands. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Claim { + /// The offer is still waiting for the queues' answer. + Open, + /// The queues delivered it while the offer waited. + Delivered, + /// The direct path runs it. + Direct, +} + +/// An event the direct path ran, as stored. +#[derive(Debug, Clone, Serialize, Deserialize)] +struct Record { + key: String, + recorded_ms: i64, +} + +#[derive(Debug, Default)] +struct Memory { + claims: HashMap, + /// The `Direct` claims, oldest first, for eviction. + direct: VecDeque, +} + +impl Memory { + fn direct(&mut self, key: &str) { + if self.claims.insert(key.to_owned(), Claim::Direct) != Some(Claim::Direct) { + self.direct.push_back(key.to_owned()); + } + while self.direct.len() > CAPACITY { + if let Some(oldest) = self.direct.pop_front() { + self.claims.remove(&oldest); + } + } + } +} + +/// The claims of this process, over the host's storage once attached. +#[derive(Default)] +pub struct Claims { + memory: Mutex, + store: OnceLock>, +} + +impl std::fmt::Debug for Claims { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Claims") + .field("attached", &self.store.get().is_some_and(Option::is_some)) + .finish_non_exhaustive() + } +} + +static GLOBAL: LazyLock = LazyLock::new(Claims::default); + +impl Claims { + /// The claims the offers and deliveries of this process share. + #[must_use] + pub fn global() -> &'static Self { + &GLOBAL + } + + /// Claims over `scoped` storage, loaded at `now_ms` (tests). + #[cfg(test)] + pub(crate) fn over(scoped: &crate::storage::Storage, now_ms: i64) -> Self { + let claims = Self::default(); + claims.attach_repo(Repo::over(scoped, DOMAIN, collection_specs), now_ms); + claims + } + + fn memory(&self) -> std::sync::MutexGuard<'_, Memory> { + self.memory.lock().unwrap_or_else(PoisonError::into_inner) + } + + /// Record direct-path events on `config`'s workspace storage from now + /// on, and remember the ones recorded before (a previous process's). + /// Only the first call opens the store; a store that cannot be opened + /// leaves the claims in memory. + pub fn attach(&self, config: &Config, now_ms: i64) { + if self.store.get().is_some() { + return; + } + match Repo::current_for(&config.workspace_dir, DOMAIN, collection_specs) { + Ok(repo) => self.attach_repo(repo, now_ms), + Err(error) => { + tracing::warn!(error = %error, "[inbound::claims] store unavailable; claims kept in memory only"); + let _ = self.store.set(None); + } + } + } + + fn attach_repo(&self, repo: Repo, now_ms: i64) { + if self.store.set(Some(repo.clone())).is_err() { + return; + } + match load(&repo, now_ms) { + Ok(keys) => { + let mut memory = self.memory(); + for key in keys { + memory.direct(&key); + } + } + Err(error) => { + tracing::warn!(error = %error, "[inbound::claims] could not read earlier direct-path events"); + } + } + } + + /// An offer of `key` is about to be sent. + pub fn open(&self, key: &str) { + self.memory() + .claims + .entry(key.to_owned()) + .or_insert(Claim::Open); + } + + /// The queues answered the offer of `key`: they own the event, or + /// proved they never saw it. + pub fn close(&self, key: &str) { + let mut memory = self.memory(); + if matches!(memory.claims.get(key), Some(Claim::Open | Claim::Delivered)) { + memory.claims.remove(key); + } + } + + /// Every attempt to offer `key` was ambiguous: take it for the direct + /// path at `now_ms`. `false` when the queues delivered it meanwhile, so + /// the caller must not run it. + pub fn take_direct(&self, key: &str, now_ms: i64) -> bool { + { + let mut memory = self.memory(); + if memory.claims.get(key) == Some(&Claim::Delivered) { + memory.claims.remove(key); + return false; + } + memory.direct(key); + } + if let Some(Some(repo)) = self.store.get() { + if let Err(error) = record(repo, key, now_ms) { + // Still skipped in this process; only a restart before the + // queued copy is delivered could run it a second time. + tracing::warn!(key = %key, error = %error, "[inbound::claims] could not record a direct-path event"); + } + } + true + } + + /// The queues deliver `key`: `true` when the direct path ran it, so the + /// delivery skips it. + pub fn delivering(&self, key: &str) -> bool { + let mut memory = self.memory(); + match memory.claims.get(key) { + Some(Claim::Direct) => true, + Some(Claim::Open) => { + memory.claims.insert(key.to_owned(), Claim::Delivered); + false + } + Some(Claim::Delivered) | None => false, + } + } +} + +impl Claims { + /// Leave out of `turn`, which the queues deliver, the events the direct + /// path ran, each dropped as `handled_directly`. + pub fn leave_out_direct(&self, turn: &mut Turn) { + let turn_id = turn.turn_id.clone(); + turn.events.retain(|event| { + if !self.delivering(&event.dedupe_key()) { + return true; + } + tracing::info!( + turn = %turn_id, + source = %event.source, + event_id = %event.event_id, + "[inbound] event already handled on the direct path; not delivering it" + ); + BUS.publish(DomainEvent::InboundEventDropped { + source: event.source.clone(), + event_id: event.event_id.clone(), + reason: HANDLED_DIRECTLY.to_owned(), + }); + false + }); + } +} + +/// The keys recorded within the TTL at `now_ms`; older records are deleted. +fn load(repo: &Repo, now_ms: i64) -> anyhow::Result> { + repo.run(|docs| async move { + let mut keys = Vec::new(); + for found in docs.query_all(DIRECT, &Query::all()).await? { + let Ok(record) = serde_json::from_value::(found.doc.clone()) else { + continue; + }; + if now_ms - record.recorded_ms > TTL_MS { + match docs.delete(DIRECT, &found.id, found.unchanged()).await { + Ok(_) => {} + Err(error) if error.kind() == ErrorKind::Conflict => {} + Err(error) => return Err(error), + } + } else { + keys.push(record.key); + } + } + Ok(keys) + }) +} + +fn record(repo: &Repo, key: &str, now_ms: i64) -> anyhow::Result<()> { + let id = key_of(key)?; + let doc = serde_json::to_value(Record { + key: key.to_owned(), + recorded_ms: now_ms, + })?; + repo.run(|docs| async move { + docs.put(DIRECT, &id, doc, Precondition::None).await?; + Ok(()) + }) +} + +#[cfg(test)] +#[path = "claims_tests.rs"] +mod tests; diff --git a/crates/openhuman-core/src/inbound/claims_tests.rs b/crates/openhuman-core/src/inbound/claims_tests.rs new file mode 100644 index 00000000000..e6826df68c3 --- /dev/null +++ b/crates/openhuman-core/src/inbound/claims_tests.rs @@ -0,0 +1,79 @@ +//! Tests for the claims on events whose hand-off was ambiguous. + +use super::*; + +const NOW_MS: i64 = 1_000_000; + +fn storage() -> crate::storage::Storage { + tinystoragedrivers_testkit::memory_storage(&crate::storage::Scope::new("local").unwrap()) +} + +#[test] +fn an_event_taken_for_the_direct_path_is_skipped_by_its_delivery() { + let claims = Claims::default(); + claims.open("composio:slack:e1"); + assert!(claims.take_direct("composio:slack:e1", NOW_MS)); + assert!(claims.delivering("composio:slack:e1")); + // And by any redelivery of it. + assert!(claims.delivering("composio:slack:e1")); +} + +#[test] +fn an_event_delivered_while_its_offer_waited_is_not_taken_for_the_direct_path() { + let claims = Claims::default(); + claims.open("composio:slack:e2"); + assert!(!claims.delivering("composio:slack:e2")); + assert!(!claims.take_direct("composio:slack:e2", NOW_MS)); + // Settled: nothing is left behind. + assert!(!claims.delivering("composio:slack:e2")); +} + +#[test] +fn an_answered_offer_leaves_no_claim() { + let claims = Claims::default(); + claims.open("composio:slack:e3"); + claims.close("composio:slack:e3"); + assert!(!claims.delivering("composio:slack:e3")); + // Closing never undoes a direct-path claim. + assert!(claims.take_direct("composio:slack:e4", NOW_MS)); + claims.close("composio:slack:e4"); + assert!(claims.delivering("composio:slack:e4")); +} + +#[test] +fn an_event_never_offered_through_a_claim_is_delivered() { + let claims = Claims::default(); + assert!(!claims.delivering("webhook:t1:c1")); +} + +#[test] +fn a_direct_path_event_is_skipped_after_a_restart() { + let storage = storage(); + let before = Claims::over(&storage, NOW_MS); + assert!(before.take_direct("webhook:t1:c2", NOW_MS)); + // A new process over the same storage. + let after = Claims::over(&storage, NOW_MS + 1_000); + assert!(after.delivering("webhook:t1:c2")); + assert!(!after.delivering("webhook:t1:c3")); +} + +#[test] +fn a_direct_path_record_expires_with_the_module_tombstones() { + let storage = storage(); + assert!(Claims::over(&storage, NOW_MS).take_direct("webhook:t1:c4", NOW_MS)); + let later = Claims::over(&storage, NOW_MS + TTL_MS + 1); + assert!(!later.delivering("webhook:t1:c4")); + // The expired record was deleted, not just ignored. + let again = Claims::over(&storage, NOW_MS); + assert!(!again.delivering("webhook:t1:c4")); +} + +#[test] +fn direct_path_claims_are_bounded_in_memory() { + let claims = Claims::default(); + for n in 0..=CAPACITY { + assert!(claims.take_direct(&format!("composio:slack:b{n}"), NOW_MS)); + } + assert!(!claims.delivering("composio:slack:b0")); + assert!(claims.delivering(&format!("composio:slack:b{CAPACITY}"))); +} diff --git a/crates/openhuman-core/src/inbound/deliver.rs b/crates/openhuman-core/src/inbound/deliver.rs index 539a7b7badc..73c08840da2 100644 --- a/crates/openhuman-core/src/inbound/deliver.rs +++ b/crates/openhuman-core/src/inbound/deliver.rs @@ -41,6 +41,11 @@ //! callback deadline (`[inbound] triage_timeout_ms`, at most 25 s), and a //! turn that was already accepted is accepted again without triage, so a //! redelivery that raced a slow answer never applies a second decision. +//! +//! An event its offer already ran on the caller's direct path (every +//! `Ingest` attempt was ambiguous, yet the module persisted it, +//! [`super::claims`]) is left out of its turn and dropped with the reason +//! `handled_directly`; a turn left with no events is accepted as it is. use std::collections::{BTreeMap, HashMap, VecDeque}; use std::sync::{Arc, Mutex}; @@ -51,6 +56,7 @@ use tinyeventqueues_bus::{ DeliverStatus, InboundEvent, Lane, SalienceClass, Turn, }; +use super::claims::Claims; use super::events::{digest_envelope, envelope_of}; use super::pinned::{Delivered, Pinned}; use super::results::Results; @@ -159,6 +165,11 @@ pub struct Deliverer { inbound: tokio::sync::OnceCell>, /// What runs pinned sources' turns: given, or built on first use. pinned: tokio::sync::OnceCell>, + /// Who ran events whose offers were ambiguous. + claims: &'static Claims, + /// Whether `claims` was attached to the configured storage (done on + /// first use, or not at all when the deliverer was given its settings). + claims_attached: tokio::sync::OnceCell<()>, } impl std::fmt::Debug for Deliverer { @@ -179,8 +190,11 @@ impl Deliverer { /// It has no pinned sources unless given some ([`Self::with_inbound`]). #[must_use] pub fn new(runner: Arc, ctx: DispatchCtx, timeout: Duration) -> Self { - Self::build(runner, ctx, tokio::sync::OnceCell::new_with(Some(timeout))) - .with_inbound(InboundConfig::default()) + let mut deliverer = + Self::build(runner, ctx, tokio::sync::OnceCell::new_with(Some(timeout))) + .with_inbound(InboundConfig::default()); + deliverer.claims_attached = tokio::sync::OnceCell::new_with(Some(())); + deliverer } /// A deliverer whose triage timeout is `[inbound] triage_timeout_ms`, read @@ -209,6 +223,8 @@ impl Deliverer { accepted: Mutex::new(Accepted::default()), inbound: tokio::sync::OnceCell::new(), pinned: tokio::sync::OnceCell::new(), + claims: Claims::global(), + claims_attached: tokio::sync::OnceCell::new(), } } @@ -396,6 +412,32 @@ impl Deliverer { } } + /// The claims, attached to the configured storage on first use. + async fn claims(&self) -> &Claims { + self.claims_attached + .get_or_init(|| async { + match self.ctx.load_config().await { + Ok(config) => self.claims.attach(&config, (self.now_ms)()), + Err(error) => { + tracing::debug!(error = %error, "[inbound] config unavailable; claims kept in memory only"); + } + } + }) + .await; + self.claims + } + + /// `turn` without the events their offers already ran directly, each + /// dropped; `None` when that left none (a turn that came with none is + /// returned as it is, to be rejected). + async fn without_direct(&self, mut turn: Turn) -> Option { + if turn.events.is_empty() { + return Some(turn); + } + self.claims().await.leave_out_direct(&mut turn); + (!turn.events.is_empty()).then_some(turn) + } + fn classified(&self) -> std::sync::MutexGuard<'_, Classified> { self.classified .lock() @@ -464,6 +506,11 @@ impl Deliverer { ); return DeliverResponse::new(DeliverStatus::Accepted); } + let turn_id = turn.turn_id.clone(); + let Some(turn) = self.without_direct(turn).await else { + self.accepted().remember(&turn_id); + return DeliverResponse::new(DeliverStatus::Accepted); + }; if let Some((name, source)) = self.pinned_source(&turn.events).await { let remaining = self.budget.saturating_sub(started.elapsed()); let status = self.deliver_pinned(&turn, &name, &source, remaining).await; diff --git a/crates/openhuman-core/src/inbound/deliver_tests.rs b/crates/openhuman-core/src/inbound/deliver_tests.rs index 72537c9088b..29aa9d779fd 100644 --- a/crates/openhuman-core/src/inbound/deliver_tests.rs +++ b/crates/openhuman-core/src/inbound/deliver_tests.rs @@ -684,3 +684,42 @@ async fn a_pinned_source_in_a_mixed_digest_still_runs_its_agent() { #[path = "deliver_digest_tests.rs"] mod digest; + +#[tokio::test] +async fn an_event_handled_directly_is_not_delivered_again() { + // Its offer was ambiguous and ran on the caller's direct path, yet the + // module persisted it: the queued copy must not be triaged a second time. + let event = trigger_event("deliver-direct-1"); + assert!(Claims::global().take_direct(&event.dedupe_key(), NOW_MS)); + let triage = ScriptedTriage::new([decision(TriageAction::React)]); + let deliverer = deliverer(&triage); + let response = deliverer + .deliver(turn(vec![event.clone()], Lane::Background, 1)) + .await; + assert_eq!(response.status, DeliverStatus::Accepted); + assert_eq!(triage.runs(), 0); + assert!(triage.applied().is_empty()); + // A redelivery of the turn is not triaged either. + let again = deliverer + .deliver(turn(vec![event], Lane::Background, 2)) + .await; + assert_eq!(again.status, DeliverStatus::Accepted); + assert_eq!(triage.runs(), 0); +} + +#[tokio::test] +async fn a_digest_leaves_out_only_the_events_handled_directly() { + let direct = trigger_event("deliver-direct-2"); + let queued = trigger_event("deliver-direct-3"); + assert!(Claims::global().take_direct(&direct.dedupe_key(), NOW_MS)); + let triage = ScriptedTriage::new([decision(TriageAction::React)]); + let response = deliverer(&triage) + .deliver(turn(vec![direct, queued], Lane::Background, 1)) + .await; + assert_eq!(response.status, DeliverStatus::Accepted); + assert_eq!(triage.runs(), 1); + assert_eq!( + triage.until_applied(1, Duration::from_secs(5)).await.len(), + 1 + ); +} diff --git a/crates/openhuman-core/src/inbound/mod.rs b/crates/openhuman-core/src/inbound/mod.rs index 779808c7be5..74c645b04cc 100644 --- a/crates/openhuman-core/src/inbound/mod.rs +++ b/crates/openhuman-core/src/inbound/mod.rs @@ -21,6 +21,7 @@ //! | [`settings`] | `[inbound]` resolved: the queues and pipeline the module runs, the queue backend, whether routing is on | //! | [`events`] | a trigger envelope, or an external source's event, as an `InboundEvent`, and back | //! | [`route`] | the hand-off; the caller's direct path runs when the queues do not take an event | +//! | [`claims`] | who runs an event whose hand-off was ambiguous: the direct path or `Deliver`, never both | //! | [`deliver`] | `Deliver` and `ClassifySalience`: triage, ack semantics, retry and dead-letter events | //! | [`host`] | the served `ai.tinyhumans.tinyeventqueues.Host` callbacks | //! | [`pinned`] | a configured external source's batch run on its pinned agent, without triage | @@ -32,6 +33,7 @@ //! plus the configured queue manifest) and component (`eventqueues`) live //! with the other modules. +pub mod claims; pub mod deliver; pub mod events; pub mod host; diff --git a/crates/openhuman-core/src/inbound/route.rs b/crates/openhuman-core/src/inbound/route.rs index 2dfa4410aac..3b7fa08a684 100644 --- a/crates/openhuman-core/src/inbound/route.rs +++ b/crates/openhuman-core/src/inbound/route.rs @@ -15,10 +15,12 @@ //! failure that does not (a timeout, a transport fault) sends the event again: //! `Ingest` is idempotent on `source:event_id`, so an event the module did //! persist comes back `Duplicate` rather than queued twice. Only when every -//! attempt is ambiguous does the caller fall back to the direct path, and -//! that one case can triage an event the queues also deliver; it is logged. -//! Callers run the hand-off in their own task, never on a bus subscriber's -//! loop. +//! attempt is ambiguous does the caller fall back to the direct path. The +//! queues may hold that event all the same, so a caller with a direct path +//! offers through [`offer_or_direct`], which settles who runs it +//! ([`super::claims`]): the queues when they delivered it meanwhile, the +//! direct path otherwise, recorded so a later `Deliver` skips it. Callers +//! run the hand-off in their own task, never on a bus subscriber's loop. use std::time::Duration; @@ -30,6 +32,8 @@ use crate::core::bus::BUS; use crate::core::events::DomainEvent; use crate::modules::event_queues; +use super::claims::Claims; + /// What became of an offered event. #[derive(Debug, Clone, PartialEq, Eq)] pub enum Offered { @@ -80,16 +84,78 @@ async fn attempt(client: &ModuleClient, event: &InboundEvent, deadline: Duration } } -/// Offer `event` to the inbound event queues through `client`. +/// How a hand-off ended. +enum HandOff { + /// Settled: the queues answered, or proved they never saw the event. + Settled(Offered), + /// Every attempt was ambiguous: the queues may hold the event. + Ambiguous(String), +} + +/// Offer `event` to the inbound event queues through `client`, for a caller +/// with no direct path of its own: on [`Offered::Direct`] it reports the +/// failure, and an event the queues did hold is delivered once by them. pub async fn offer(config: &Config, client: &ModuleClient, event: InboundEvent) -> Offered { if !super::active(config) { return Offered::Direct("inbound event queues inactive".to_owned()); } + match hand_off(client, event, &ATTEMPT_DEADLINES).await { + HandOff::Settled(offered) => offered, + HandOff::Ambiguous(why) => Offered::Direct(why), + } +} + +/// Offer `event` like [`offer`], for a caller that runs its direct path on +/// [`Offered::Direct`]. When every attempt is ambiguous the event goes to +/// the direct path only if the queues have not delivered it meanwhile, and +/// is recorded so they skip it if they deliver it later. +pub async fn offer_or_direct( + config: &Config, + client: &ModuleClient, + event: InboundEvent, +) -> Offered { + offer_or_direct_with(config, client, event, Claims::global(), &ATTEMPT_DEADLINES).await +} + +async fn offer_or_direct_with( + config: &Config, + client: &ModuleClient, + event: InboundEvent, + claims: &Claims, + deadlines: &[Duration], +) -> Offered { + if !super::active(config) { + return Offered::Direct("inbound event queues inactive".to_owned()); + } + let now_ms = || chrono::Utc::now().timestamp_millis(); + claims.attach(config, now_ms()); + let key = event.dedupe_key(); + claims.open(&key); + match hand_off(client, event, deadlines).await { + HandOff::Settled(offered) => { + claims.close(&key); + offered + } + HandOff::Ambiguous(why) => { + if claims.take_direct(&key, now_ms()) { + Offered::Direct(why) + } else { + tracing::info!( + key = %key, + "[inbound] ingest never answered, but the queues delivered the event; not taking the direct path" + ); + Offered::Queued(Disposition::Accepted) + } + } + } +} + +async fn hand_off(client: &ModuleClient, event: InboundEvent, deadlines: &[Duration]) -> HandOff { let source = event.source.clone(); let event_id = event.event_id.clone(); let mut last = String::new(); let mut answered = None; - for (n, deadline) in ATTEMPT_DEADLINES.into_iter().enumerate() { + for (n, &deadline) in deadlines.iter().enumerate() { if n > 0 { tokio::time::sleep(RESEND_PAUSE).await; } @@ -105,7 +171,7 @@ pub async fn offer(config: &Config, client: &ModuleClient, event: InboundEvent) error = %error, "[inbound] queues unavailable; taking the direct path" ); - return Offered::Direct(format!("ingest failed: {error}")); + return HandOff::Settled(Offered::Direct(format!("ingest failed: {error}"))); } Attempt::Unknown(error) => { tracing::warn!( @@ -124,13 +190,13 @@ pub async fn offer(config: &Config, client: &ModuleClient, event: InboundEvent) source = %source, event_id = %event_id, error = %last, - "[inbound] ingest never answered; taking the direct path (the queues may also deliver it)" + "[inbound] ingest never answered; the queues may hold the event" ); - return Offered::Direct(format!("ingest failed: {last}")); + return HandOff::Ambiguous(format!("ingest failed: {last}")); }; let Some(result) = response.results.into_iter().next() else { tracing::warn!(source = %source, "[inbound] ingest answered no result; taking the direct path"); - return Offered::Direct("ingest answered no result".to_owned()); + return HandOff::Settled(Offered::Direct("ingest answered no result".to_owned())); }; let reason = result .reason @@ -155,7 +221,7 @@ pub async fn offer(config: &Config, client: &ModuleClient, event: InboundEvent) }); } } - Offered::Queued(result.disposition) + HandOff::Settled(Offered::Queued(result.disposition)) } #[cfg(test)] diff --git a/crates/openhuman-core/src/inbound/route_tests.rs b/crates/openhuman-core/src/inbound/route_tests.rs index ff5bc63c6fd..ac32c201011 100644 --- a/crates/openhuman-core/src/inbound/route_tests.rs +++ b/crates/openhuman-core/src/inbound/route_tests.rs @@ -7,7 +7,7 @@ use serde_json::json; use super::*; use crate::inbound::events; use crate::inbound::fixture::{active_config, Rig, ScriptedTriage, Step}; -use crate::triage::TriggerEnvelope; +use crate::triage::{TriageOutcome, TriggerEnvelope}; fn event(uuid: &str) -> InboundEvent { let envelope = TriggerEnvelope::from_composio("slack", "SLACK_MESSAGE", "", uuid, json!({})); @@ -36,9 +36,10 @@ async fn inactive_queues_send_the_event_down_the_direct_path() { assert!(!offered.is_queued()); } -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn an_unreachable_module_sends_the_event_down_the_direct_path() { - // A client bound to an object nobody serves: the call fails. +/// A client bound to an object nobody serves: every call fails without +/// proving the module never saw the event, so each attempt is ambiguous. +/// The connection is returned with it to keep the bus alive. +async fn ambiguous_client() -> (ModuleClient, tinybus::Connection) { let bus = tinybus::transport::memory::MemoryBus::new(); tinybus::broker::Broker::new().spawn(bus.clone()); let caller = tinybus::Connection::connect(bus.connect().await.unwrap()) @@ -51,11 +52,91 @@ async fn an_unreachable_module_sends_the_event_down_the_direct_path() { tinyeventqueues_bus::INTERFACE, ) .unwrap(); - let client = crate::modules::ops::fixture_client(proxy); + (crate::modules::ops::fixture_client(proxy), caller) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn an_unreachable_module_sends_the_event_down_the_direct_path() { + let (client, _bus) = ambiguous_client().await; let offered = offer(&active_config(), &client, event("u3")).await; assert!(matches!(offered, Offered::Direct(ref why) if why.contains("ingest failed"))); } +/// The caller's direct path, as the Composio and webhook paths run it. +async fn run_directly(triage: &ScriptedTriage, event: &InboundEvent) { + use crate::triage::TriageRunner; + let envelope = events::envelope_of(event).unwrap(); + let ctx = crate::core::runtime::DispatchCtx::host_default(); + let TriageOutcome::Decision(run) = triage.run(&ctx, &envelope).await.unwrap() else { + panic!("the scripted triage decides"); + }; + triage.apply(&ctx, run, &envelope).await.unwrap(); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_timed_out_ingest_that_landed_is_triaged_once() { + // #8154: every attempt is ambiguous, so the caller triages the event + // directly; the write had landed all the same and the module delivers + // its copy. Exactly one decision is applied. + let rig = Rig::new(ScriptedTriage::new(Vec::::new())).await; + let config = active_config(); + let (ambiguous, _bus) = ambiguous_client().await; + let offered = offer_or_direct(&config, &ambiguous, event("u5")).await; + assert!(matches!(offered, Offered::Direct(ref why) if why.contains("ingest failed"))); + run_directly(&rig.triage, &event("u5")).await; + // The write that landed: the module holds the event and delivers it. + let landed = event_queues::ingest(&rig.client, vec![event("u5")]) + .await + .unwrap(); + assert_eq!(landed.results[0].disposition, Disposition::Accepted); + let applied = rig.triage.until_applied(2, Duration::from_secs(2)).await; + assert_eq!(applied.len(), 1, "triaged twice: {applied:?}"); + assert_eq!(rig.triage.runs(), 1); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn an_event_delivered_while_its_offer_waited_is_not_run_directly() { + // The other order: the write lands and the module delivers it before + // the offer gives up, so the caller must not run it directly. + let rig = Rig::new(ScriptedTriage::new(Vec::::new())).await; + let config = active_config(); + let (ambiguous, _bus) = ambiguous_client().await; + let (offered, landed) = + tokio::join!(offer_or_direct(&config, &ambiguous, event("u6")), async { + let landed = event_queues::ingest(&rig.client, vec![event("u6")]).await; + rig.triage.until_applied(1, Duration::from_secs(5)).await; + landed + }); + assert_eq!( + landed.unwrap().results[0].disposition, + Disposition::Accepted + ); + assert_eq!(offered, Offered::Queued(Disposition::Accepted)); + assert_eq!(rig.triage.applied().len(), 1); +} + +#[tokio::test] +async fn an_ingest_that_surely_failed_still_takes_the_direct_path() { + // No new loss: the module never saw the event, so no claim is taken + // and a later offer of the same event is delivered by the queues. + let mut off = active_config(); + off.modules.enabled = false; + let client = crate::modules::ops::client(off); + let offered = offer_or_direct(&active_config(), &client, event("u7")).await; + assert!(matches!(offered, Offered::Direct(ref why) if why.contains("ingest failed"))); + assert!(!Claims::global().delivering(&event("u7").dedupe_key())); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn an_offer_without_a_direct_path_leaves_its_event_to_the_queues() { + // `inbound.offer` reports the failure and the pusher offers again, so + // an ambiguous offer must not mark its event as handled. + let (ambiguous, _bus) = ambiguous_client().await; + let offered = offer(&active_config(), &ambiguous, event("u8")).await; + assert!(!offered.is_queued()); + assert!(!Claims::global().delivering(&event("u8").dedupe_key())); +} + #[test] fn inbound_events_belong_to_the_inbound_domain_and_name_themselves() { use crate::core::events::DomainEvent; diff --git a/crates/openhuman-core/src/integrations/composio/bus/trigger_subscriber.rs b/crates/openhuman-core/src/integrations/composio/bus/trigger_subscriber.rs index 5e810c612c2..5942f6a1710 100644 --- a/crates/openhuman-core/src/integrations/composio/bus/trigger_subscriber.rs +++ b/crates/openhuman-core/src/integrations/composio/bus/trigger_subscriber.rs @@ -211,7 +211,7 @@ pub(super) async fn route_trigger( match crate::inbound::events::composio(&envelope) { Ok(event) => { let client = client.unwrap_or_else(|| crate::modules::ops::client(config.clone())); - let offered = crate::inbound::route::offer(config, &client, event).await; + let offered = crate::inbound::route::offer_or_direct(config, &client, event).await; if offered.is_queued() { tracing::debug!( label = %envelope.display_label, diff --git a/crates/openhuman-core/src/skills/webhooks/bus.rs b/crates/openhuman-core/src/skills/webhooks/bus.rs index a3df80a7b89..13056f9f7dd 100644 --- a/crates/openhuman-core/src/skills/webhooks/bus.rs +++ b/crates/openhuman-core/src/skills/webhooks/bus.rs @@ -275,7 +275,7 @@ pub(super) async fn route_agent_trigger( match crate::inbound::events::webhook(envelope, correlation_id) { Ok(event) => { let client = client.unwrap_or_else(|| crate::modules::ops::client(config.clone())); - if crate::inbound::route::offer(config, &client, event) + if crate::inbound::route::offer_or_direct(config, &client, event) .await .is_queued() { diff --git a/crates/openhuman-core/src/storage/schema.rs b/crates/openhuman-core/src/storage/schema.rs index e58bbac49c9..ad9c5445124 100644 --- a/crates/openhuman-core/src/storage/schema.rs +++ b/crates/openhuman-core/src/storage/schema.rs @@ -108,6 +108,8 @@ fn host_collections() -> Vec { collections.extend(super::journal_maintenance::collection_specs()); #[cfg(feature = "inbound-queues")] collections.extend(crate::inbound::results::collection_specs()); + #[cfg(feature = "inbound-queues")] + collections.extend(crate::inbound::claims::collection_specs()); collections } diff --git a/docs/storage-schema.md b/docs/storage-schema.md index 9b58dc23fd2..2861cf16313 100644 --- a/docs/storage-schema.md +++ b/docs/storage-schema.md @@ -21,6 +21,7 @@ Record shapes and migrations stay with their owners. | `config.documents` | | | | | `cost.records` | `by_time` (`ts_ms`) | | | | `devices.paired` | `by_active` (`revoked`, `created_ms`) | | | +| `inbound.direct` | | | | | `inbound.results` | `by_source` (`source`, `created_ms`)
`by_status` (`status`, `created_ms`) | | | | `notifications.core` | `by_read` (`workspace`, `read`, `timestamp_ms`) | | | | `notifications.dedup` | | | | From 30793249550f9bdd84f73416cb175dc44e6b107f Mon Sep 17 00:00:00 2001 From: Ghost Scripter Date: Wed, 11 Nov 2026 17:53:27 +0530 Subject: [PATCH 2/6] ci(inbound): isolate the new triage-once route tests with the staged modules The two route tests that attach the linked event queues module run in their own process beside the other inbound module tests (MODULE_TESTS). Relates to #8154 Co-Authored-By: Claude Opus 5.5 --- .github/workflows/test-reusable.yml | 2 ++ scripts/__tests__/test-module-installation.test.mjs | 2 ++ 2 files changed, 4 insertions(+) diff --git a/.github/workflows/test-reusable.yml b/.github/workflows/test-reusable.yml index 92cf19ed8ec..759de5adc40 100644 --- a/.github/workflows/test-reusable.yml +++ b/.github/workflows/test-reusable.yml @@ -246,6 +246,8 @@ jobs: inbound::ops::tests::the_operations_reach_the_module inbound::ops::tests::three_offers_within_the_window_run_one_turn_with_one_result_and_one_event inbound::route::tests::an_accepted_event_is_queued_and_a_redelivery_ends_at_ingress + inbound::route::tests::a_timed_out_ingest_that_landed_is_triaged_once + inbound::route::tests::an_event_delivered_while_its_offer_waited_is_not_run_directly integrations::composio::bus::trigger_subscriber::tests::a_deferred_composio_trigger_is_retried_at_its_defer_time_instead_of_dropped integrations::composio::bus::trigger_subscriber::tests::a_redelivered_composio_trigger_produces_one_turn integrations::composio::bus::trigger_subscriber::tests::without_a_config_a_trigger_is_triaged_directly diff --git a/scripts/__tests__/test-module-installation.test.mjs b/scripts/__tests__/test-module-installation.test.mjs index 4cde2fe38bb..7e01749bab2 100644 --- a/scripts/__tests__/test-module-installation.test.mjs +++ b/scripts/__tests__/test-module-installation.test.mjs @@ -601,6 +601,8 @@ test("the core workflow isolates tests that need staged callback modules", () => "inbound::ops::tests::the_operations_reach_the_module", "inbound::ops::tests::three_offers_within_the_window_run_one_turn_with_one_result_and_one_event", "inbound::route::tests::an_accepted_event_is_queued_and_a_redelivery_ends_at_ingress", + "inbound::route::tests::a_timed_out_ingest_that_landed_is_triaged_once", + "inbound::route::tests::an_event_delivered_while_its_offer_waited_is_not_run_directly", "integrations::composio::bus::trigger_subscriber::tests::a_deferred_composio_trigger_is_retried_at_its_defer_time_instead_of_dropped", "integrations::composio::bus::trigger_subscriber::tests::a_redelivered_composio_trigger_produces_one_turn", "integrations::composio::bus::trigger_subscriber::tests::without_a_config_a_trigger_is_triaged_directly", From e8606d5728ff392ea6b69b77bd194ff204e75a76 Mon Sep 17 00:00:00 2001 From: Ghost Scripter Date: Wed, 11 Nov 2026 18:11:35 +0530 Subject: [PATCH 3/6] docs(matrix): note the inbound triage-once behaviour on 10.3.5 Relates to #8154 Co-Authored-By: Claude Opus 5.5 --- docs/TEST-COVERAGE-MATRIX.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/TEST-COVERAGE-MATRIX.md b/docs/TEST-COVERAGE-MATRIX.md index 32e994dc8dd..0416a367b56 100644 --- a/docs/TEST-COVERAGE-MATRIX.md +++ b/docs/TEST-COVERAGE-MATRIX.md @@ -462,7 +462,7 @@ The thread JSONL store moved to `tinyagents_session::threads` (`vendor/tinyagent | 10.3.1 | Incoming Message Sync | RU+WD | `crates/openhuman-core/src/channels/tests/`, `gmail-flow.spec.ts` | ✅ | | | 10.3.2 | Message Deduplication | RU | `crates/openhuman-core/src/channels/tests/` | ✅ | | | 10.3.4 | Real-Time vs Delayed Sync | RU | `crates/openhuman-core/src/channels/tests/runtime_dispatch.rs` | ✅ | | -| 10.3.5 | Inbound Event Queues (Composio triggers, agent webhooks) | RU+RI | `crates/openhuman-core/src/integrations/composio/bus/trigger_subscriber_tests.rs`, `crates/openhuman-core/src/skills/webhooks/bus_tests.rs`, `crates/openhuman-core/src/inbound/`, `tests/components_e2e.rs`, `tests/inbound_module_e2e.rs` | ✅ | TinyEventQueues owns retry, deduplication, and delivery behavior. `inbound_module_e2e` exercises host admission against the staged digest-verified module and asserts that an accepted trigger is persisted before acknowledgment. `inbound.*` RPC answers `COMPONENT_DISABLED:eventqueues` when off. Host callbacks require the verified local-file source; linked factories are not eligible for them. | +| 10.3.5 | Inbound Event Queues (Composio triggers, agent webhooks) | RU+RI | `crates/openhuman-core/src/integrations/composio/bus/trigger_subscriber_tests.rs`, `crates/openhuman-core/src/skills/webhooks/bus_tests.rs`, `crates/openhuman-core/src/inbound/`, `tests/components_e2e.rs`, `tests/inbound_module_e2e.rs` | ✅ | TinyEventQueues owns retry, deduplication, and delivery behavior. `inbound_module_e2e` exercises host admission against the staged digest-verified module and asserts that an accepted trigger is persisted before acknowledgment. An offer whose every `Ingest` attempt was ambiguous runs once: on the caller's direct path (recorded in `inbound.direct`, so `Deliver` drops the queued copy as `handled_directly`, across restarts) or by `Deliver` when it got there first, never both (#8154). `inbound.*` RPC answers `COMPONENT_DISABLED:eventqueues` when off. Host callbacks require the verified local-file source; linked factories are not eligible for them. | | 10.3.6 | Inbound external sources (`inbound.offer`, pinned agent turns, `inbound.results` / `inbound.result_ack`) | RU | `crates/openhuman-core/src/inbound/` (`*_tests.rs` beside `pinned.rs`, `results.rs`, `events.rs`, `settings.rs`, `ops.rs`, `schemas.rs`), `crates/openhuman-core/src/config/schema/inbound_sources_tests.rs`, `crates/openhuman-core/src/triage/origin_tests.rs` | ✅ | Against the real `tinyeventqueues` module linked into the test binary: three offers inside the debounce window become one turn on the configured agent, one stored result and one `InboundTurnCompleted`; `max_batch` splits a larger batch; a prompt-injection event is left out of the turn and listed as `blocked`; an all-blocked batch makes no model call; a completed turn is not re-run; an unconfigured or reserved source is refused; the turn runs under the parked-approval external origin | ### 10.4 Messaging Operations From 3b0b7f96c8c3fc403a02b8ba98a5a9d131c0f973 Mon Sep 17 00:00:00 2001 From: Ghost Scripter Date: Wed, 11 Nov 2026 18:59:02 +0530 Subject: [PATCH 4/6] fix(inbound): keep triage-once claims per workspace The claims were one process-wide static whose store attached to the first workspace that used it: on a host serving several profiles, one profile's direct-path records would land in another's storage (process-statics flagged the new static). - Claims::of_workspace(config) keys them by workspace directory; each workspace's records stay in memory under its own entry and persist to its own inbound.direct. - The configured Deliverer resolves its workspace's claims from its config on first use; Deliverer::new gets claims of its own, shared explicitly with with_claims (the linked Rig hands one Claims to both sides instead of both resolving "the default workspace", which raced with tests changing the environment). - process-statics.json records the static (category B). - Tests: workspaces are kept apart; an ambiguous offer claims in its own workspace; inactive queues take no claim. Relates to #8154 Co-Authored-By: Claude Opus 5.5 --- crates/openhuman-core/src/inbound/claims.rs | 33 +++++++--- .../src/inbound/claims_tests.rs | 13 ++++ crates/openhuman-core/src/inbound/deliver.rs | 39 +++++++----- .../src/inbound/deliver_tests.rs | 9 ++- .../src/inbound/linked_fixture.rs | 8 ++- crates/openhuman-core/src/inbound/route.rs | 11 ++-- .../openhuman-core/src/inbound/route_tests.rs | 63 ++++++++++++++----- scripts/ci/process-statics.json | 10 +++ 8 files changed, 139 insertions(+), 47 deletions(-) diff --git a/crates/openhuman-core/src/inbound/claims.rs b/crates/openhuman-core/src/inbound/claims.rs index 8cda8b1e3ea..dde89c4337a 100644 --- a/crates/openhuman-core/src/inbound/claims.rs +++ b/crates/openhuman-core/src/inbound/claims.rs @@ -19,12 +19,17 @@ //! | --- | --- | --- | //! | `inbound.direct` | `Key::of([source:event_id])` | an event the direct path ran, and when | //! +//! Claims belong to a workspace: each workspace's are kept apart, in memory +//! and in that workspace's own storage, so no profile reads or writes +//! another's records. +//! //! Records are kept as long as the module keeps its tombstones (30 days), //! so a dead-lettered copy redriven later is still recognised. They are //! rare: only an offer whose every attempt was ambiguous writes one. use std::collections::{HashMap, VecDeque}; -use std::sync::{LazyLock, Mutex, OnceLock, PoisonError}; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, LazyLock, Mutex, OnceLock, PoisonError}; use serde::{Deserialize, Serialize}; use tinystoragedrivers::{CollectionSpec, ErrorKind, Precondition, Query}; @@ -94,7 +99,7 @@ impl Memory { } } -/// The claims of this process, over the host's storage once attached. +/// The claims of one workspace, over its storage once attached. #[derive(Default)] pub struct Claims { memory: Mutex, @@ -109,13 +114,27 @@ impl std::fmt::Debug for Claims { } } -static GLOBAL: LazyLock = LazyLock::new(Claims::default); +/// Each workspace's claims, by workspace directory. +static WORKSPACES: LazyLock>>> = LazyLock::new(Mutex::default); impl Claims { - /// The claims the offers and deliveries of this process share. + /// The claims the offers and deliveries of `config`'s workspace share, + /// attached to its storage (and loaded, at `now_ms`) on first use. #[must_use] - pub fn global() -> &'static Self { - &GLOBAL + pub fn of_workspace(config: &Config, now_ms: i64) -> Arc { + let claims = Self::for_dir(&config.workspace_dir); + claims.attach(config, now_ms); + claims + } + + fn for_dir(workspace_dir: &Path) -> Arc { + Arc::clone( + WORKSPACES + .lock() + .unwrap_or_else(PoisonError::into_inner) + .entry(workspace_dir.to_path_buf()) + .or_default(), + ) } /// Claims over `scoped` storage, loaded at `now_ms` (tests). @@ -134,7 +153,7 @@ impl Claims { /// on, and remember the ones recorded before (a previous process's). /// Only the first call opens the store; a store that cannot be opened /// leaves the claims in memory. - pub fn attach(&self, config: &Config, now_ms: i64) { + fn attach(&self, config: &Config, now_ms: i64) { if self.store.get().is_some() { return; } diff --git a/crates/openhuman-core/src/inbound/claims_tests.rs b/crates/openhuman-core/src/inbound/claims_tests.rs index e6826df68c3..39b4a4879c1 100644 --- a/crates/openhuman-core/src/inbound/claims_tests.rs +++ b/crates/openhuman-core/src/inbound/claims_tests.rs @@ -77,3 +77,16 @@ fn direct_path_claims_are_bounded_in_memory() { assert!(!claims.delivering("composio:slack:b0")); assert!(claims.delivering(&format!("composio:slack:b{CAPACITY}"))); } + +#[test] +fn each_workspace_keeps_its_own_claims() { + let (a, b) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap()); + let config = |dir: &tempfile::TempDir| { + let mut config = Config::default(); + config.workspace_dir = dir.path().to_path_buf(); + config + }; + assert!(Claims::of_workspace(&config(&a), NOW_MS).take_direct("composio:slack:w1", NOW_MS)); + assert!(!Claims::of_workspace(&config(&b), NOW_MS).delivering("composio:slack:w1")); + assert!(Claims::of_workspace(&config(&a), NOW_MS).delivering("composio:slack:w1")); +} diff --git a/crates/openhuman-core/src/inbound/deliver.rs b/crates/openhuman-core/src/inbound/deliver.rs index 73c08840da2..325e7038264 100644 --- a/crates/openhuman-core/src/inbound/deliver.rs +++ b/crates/openhuman-core/src/inbound/deliver.rs @@ -165,11 +165,9 @@ pub struct Deliverer { inbound: tokio::sync::OnceCell>, /// What runs pinned sources' turns: given, or built on first use. pinned: tokio::sync::OnceCell>, - /// Who ran events whose offers were ambiguous. - claims: &'static Claims, - /// Whether `claims` was attached to the configured storage (done on - /// first use, or not at all when the deliverer was given its settings). - claims_attached: tokio::sync::OnceCell<()>, + /// Who ran events whose offers were ambiguous: the configured + /// workspace's claims, resolved on first use. + claims: tokio::sync::OnceCell>, } impl std::fmt::Debug for Deliverer { @@ -193,7 +191,9 @@ impl Deliverer { let mut deliverer = Self::build(runner, ctx, tokio::sync::OnceCell::new_with(Some(timeout))) .with_inbound(InboundConfig::default()); - deliverer.claims_attached = tokio::sync::OnceCell::new_with(Some(())); + // Given its settings, it reads no configuration: its claims are its + // own unless given some (`Self::with_claims`). + deliverer.claims = tokio::sync::OnceCell::new_with(Some(Arc::new(Claims::default()))); deliverer } @@ -223,8 +223,7 @@ impl Deliverer { accepted: Mutex::new(Accepted::default()), inbound: tokio::sync::OnceCell::new(), pinned: tokio::sync::OnceCell::new(), - claims: Claims::global(), - claims_attached: tokio::sync::OnceCell::new(), + claims: tokio::sync::OnceCell::new(), } } @@ -243,6 +242,13 @@ impl Deliverer { self } + /// Share `claims` with the offers of the events it delivers. + #[must_use] + pub fn with_claims(mut self, claims: Arc) -> Self { + self.claims = tokio::sync::OnceCell::new_with(Some(claims)); + self + } + /// Use `now_ms` for the clock (tests). #[must_use] pub fn with_clock(mut self, now_ms: fn() -> i64) -> Self { @@ -412,19 +418,20 @@ impl Deliverer { } } - /// The claims, attached to the configured storage on first use. + /// The configured workspace's claims, resolved on first use. async fn claims(&self) -> &Claims { - self.claims_attached + self.claims .get_or_init(|| async { - match self.ctx.load_config().await { - Ok(config) => self.claims.attach(&config, (self.now_ms)()), + let config = match self.ctx.load_config().await { + Ok(config) => config, Err(error) => { - tracing::debug!(error = %error, "[inbound] config unavailable; claims kept in memory only"); + tracing::debug!(error = %error, "[inbound] config unavailable; the default workspace's claims"); + crate::config::Config::default() } - } + }; + Claims::of_workspace(&config, (self.now_ms)()) }) - .await; - self.claims + .await } /// `turn` without the events their offers already ran directly, each diff --git a/crates/openhuman-core/src/inbound/deliver_tests.rs b/crates/openhuman-core/src/inbound/deliver_tests.rs index 29aa9d779fd..8fa5d28498f 100644 --- a/crates/openhuman-core/src/inbound/deliver_tests.rs +++ b/crates/openhuman-core/src/inbound/deliver_tests.rs @@ -690,9 +690,10 @@ async fn an_event_handled_directly_is_not_delivered_again() { // Its offer was ambiguous and ran on the caller's direct path, yet the // module persisted it: the queued copy must not be triaged a second time. let event = trigger_event("deliver-direct-1"); - assert!(Claims::global().take_direct(&event.dedupe_key(), NOW_MS)); + let claims = Arc::new(Claims::default()); + assert!(claims.take_direct(&event.dedupe_key(), NOW_MS)); let triage = ScriptedTriage::new([decision(TriageAction::React)]); - let deliverer = deliverer(&triage); + let deliverer = deliverer(&triage).with_claims(claims); let response = deliverer .deliver(turn(vec![event.clone()], Lane::Background, 1)) .await; @@ -711,9 +712,11 @@ async fn an_event_handled_directly_is_not_delivered_again() { async fn a_digest_leaves_out_only_the_events_handled_directly() { let direct = trigger_event("deliver-direct-2"); let queued = trigger_event("deliver-direct-3"); - assert!(Claims::global().take_direct(&direct.dedupe_key(), NOW_MS)); + let claims = Arc::new(Claims::default()); + assert!(claims.take_direct(&direct.dedupe_key(), NOW_MS)); let triage = ScriptedTriage::new([decision(TriageAction::React)]); let response = deliverer(&triage) + .with_claims(claims) .deliver(turn(vec![direct, queued], Lane::Background, 1)) .await; assert_eq!(response.status, DeliverStatus::Accepted); diff --git a/crates/openhuman-core/src/inbound/linked_fixture.rs b/crates/openhuman-core/src/inbound/linked_fixture.rs index c23d7f747f2..5015b0f8e93 100644 --- a/crates/openhuman-core/src/inbound/linked_fixture.rs +++ b/crates/openhuman-core/src/inbound/linked_fixture.rs @@ -25,6 +25,7 @@ use tinystoragedrivers_api::StorageBackend; use tinystoragedrivers_busproxy::{PerCallerEndpoint, ServedStorage, StorageServer}; use tinystoragedrivers_testkit::MemoryBackend; +use super::claims::Claims; use super::deliver::Deliverer; use super::host::InboundHost; use super::pinned::{Pinned, PinnedAgent, PinnedRun}; @@ -299,6 +300,8 @@ pub(crate) struct Rig { pub(crate) client: ModuleClient, /// The triage the host callbacks run. pub(crate) triage: Arc, + /// The claims the host callbacks share with this rig's offers. + pub(crate) claims: Arc, _host: Connection, _storage: ServedStorage, _modules: ModuleHost, @@ -327,12 +330,14 @@ impl Rig { let host = Connection::connect(bus.connect().await.unwrap()) .await .unwrap(); + let claims = Arc::new(Claims::default()); let deliverer = Deliverer::new( triage.clone() as Arc, DispatchCtx::host_default(), Duration::from_secs(5), ) - .with_max_attempts(|_| Some(5)); + .with_max_attempts(|_| Some(5)) + .with_claims(Arc::clone(&claims)); let mut pipeline = fast_pipeline(); let deliverer = match pinned { Some((inbound, pinned)) => { @@ -413,6 +418,7 @@ impl Rig { Self { client: crate::modules::ops::fixture_client(proxy), triage, + claims, _host: host, _storage: storage, _modules: modules, diff --git a/crates/openhuman-core/src/inbound/route.rs b/crates/openhuman-core/src/inbound/route.rs index 3b7fa08a684..6cf4c0d8916 100644 --- a/crates/openhuman-core/src/inbound/route.rs +++ b/crates/openhuman-core/src/inbound/route.rs @@ -114,21 +114,20 @@ pub async fn offer_or_direct( client: &ModuleClient, event: InboundEvent, ) -> Offered { - offer_or_direct_with(config, client, event, Claims::global(), &ATTEMPT_DEADLINES).await + if !super::active(config) { + return Offered::Direct("inbound event queues inactive".to_owned()); + } + let claims = Claims::of_workspace(config, chrono::Utc::now().timestamp_millis()); + offer_or_direct_with(client, event, &claims, &ATTEMPT_DEADLINES).await } async fn offer_or_direct_with( - config: &Config, client: &ModuleClient, event: InboundEvent, claims: &Claims, deadlines: &[Duration], ) -> Offered { - if !super::active(config) { - return Offered::Direct("inbound event queues inactive".to_owned()); - } let now_ms = || chrono::Utc::now().timestamp_millis(); - claims.attach(config, now_ms()); let key = event.dedupe_key(); claims.open(&key); match hand_off(client, event, deadlines).await { diff --git a/crates/openhuman-core/src/inbound/route_tests.rs b/crates/openhuman-core/src/inbound/route_tests.rs index ac32c201011..e399fc6250d 100644 --- a/crates/openhuman-core/src/inbound/route_tests.rs +++ b/crates/openhuman-core/src/inbound/route_tests.rs @@ -79,9 +79,9 @@ async fn a_timed_out_ingest_that_landed_is_triaged_once() { // directly; the write had landed all the same and the module delivers // its copy. Exactly one decision is applied. let rig = Rig::new(ScriptedTriage::new(Vec::::new())).await; - let config = active_config(); let (ambiguous, _bus) = ambiguous_client().await; - let offered = offer_or_direct(&config, &ambiguous, event("u5")).await; + let offered = + offer_or_direct_with(&ambiguous, event("u5"), &rig.claims, &ATTEMPT_DEADLINES).await; assert!(matches!(offered, Offered::Direct(ref why) if why.contains("ingest failed"))); run_directly(&rig.triage, &event("u5")).await; // The write that landed: the module holds the event and delivers it. @@ -99,14 +99,13 @@ async fn an_event_delivered_while_its_offer_waited_is_not_run_directly() { // The other order: the write lands and the module delivers it before // the offer gives up, so the caller must not run it directly. let rig = Rig::new(ScriptedTriage::new(Vec::::new())).await; - let config = active_config(); let (ambiguous, _bus) = ambiguous_client().await; - let (offered, landed) = - tokio::join!(offer_or_direct(&config, &ambiguous, event("u6")), async { - let landed = event_queues::ingest(&rig.client, vec![event("u6")]).await; - rig.triage.until_applied(1, Duration::from_secs(5)).await; - landed - }); + let offer = offer_or_direct_with(&ambiguous, event("u6"), &rig.claims, &ATTEMPT_DEADLINES); + let (offered, landed) = tokio::join!(offer, async { + let landed = event_queues::ingest(&rig.client, vec![event("u6")]).await; + rig.triage.until_applied(1, Duration::from_secs(5)).await; + landed + }); assert_eq!( landed.unwrap().results[0].disposition, Disposition::Accepted @@ -119,22 +118,58 @@ async fn an_event_delivered_while_its_offer_waited_is_not_run_directly() { async fn an_ingest_that_surely_failed_still_takes_the_direct_path() { // No new loss: the module never saw the event, so no claim is taken // and a later offer of the same event is delivered by the queues. - let mut off = active_config(); + let workspace = tempfile::tempdir().unwrap(); + let config = config_in(&workspace); + let mut off = config.clone(); off.modules.enabled = false; let client = crate::modules::ops::client(off); - let offered = offer_or_direct(&active_config(), &client, event("u7")).await; + let offered = offer_or_direct(&config, &client, event("u7")).await; assert!(matches!(offered, Offered::Direct(ref why) if why.contains("ingest failed"))); - assert!(!Claims::global().delivering(&event("u7").dedupe_key())); + assert!(!Claims::of_workspace(&config, 0).delivering(&event("u7").dedupe_key())); } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn an_offer_without_a_direct_path_leaves_its_event_to_the_queues() { // `inbound.offer` reports the failure and the pusher offers again, so // an ambiguous offer must not mark its event as handled. + let workspace = tempfile::tempdir().unwrap(); + let config = config_in(&workspace); let (ambiguous, _bus) = ambiguous_client().await; - let offered = offer(&active_config(), &ambiguous, event("u8")).await; + let offered = offer(&config, &ambiguous, event("u8")).await; assert!(!offered.is_queued()); - assert!(!Claims::global().delivering(&event("u8").dedupe_key())); + assert!(!Claims::of_workspace(&config, 0).delivering(&event("u8").dedupe_key())); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn an_ambiguous_offer_claims_its_event_in_its_own_workspace() { + // The direct-path claim lands in the offering config's workspace, where + // that workspace's `Deliver` looks, and in no other. + let (mine, other) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap()); + let config = config_in(&mine); + let (ambiguous, _bus) = ambiguous_client().await; + let offered = offer_or_direct(&config, &ambiguous, event("u9")).await; + assert!(matches!(offered, Offered::Direct(ref why) if why.contains("ingest failed"))); + let key = event("u9").dedupe_key(); + assert!(Claims::of_workspace(&config, 0).delivering(&key)); + assert!(!Claims::of_workspace(&config_in(&other), 0).delivering(&key)); +} + +#[tokio::test] +async fn inactive_queues_send_a_direct_path_offer_down_it_without_a_claim() { + let workspace = tempfile::tempdir().unwrap(); + let mut config = config_in(&workspace); + config.inbound.enabled = false; + let client = crate::modules::ops::client(config.clone()); + let offered = offer_or_direct(&config, &client, event("u10")).await; + assert!(matches!(offered, Offered::Direct(ref why) if why.contains("inactive"))); + assert!(!Claims::of_workspace(&config, 0).delivering(&event("u10").dedupe_key())); +} + +/// The active config, over its own workspace. +fn config_in(workspace: &tempfile::TempDir) -> crate::config::Config { + let mut config = active_config(); + config.workspace_dir = workspace.path().to_path_buf(); + config } #[test] diff --git a/scripts/ci/process-statics.json b/scripts/ci/process-statics.json index 309e4f77d78..c96d141c661 100644 --- a/scripts/ci/process-statics.json +++ b/scripts/ci/process-statics.json @@ -209,6 +209,16 @@ "reason": "The module's shipped queues.json and pipeline.json, parsed once; immutable process configuration with no tenant data.", "verification": "inbound/settings_tests.rs: the_defaults_resolve_to_the_shipped_files_in_storage" }, + { + "file": "crates/openhuman-core/src/inbound/claims.rs", + "scope": "", + "name": "WORKSPACES", + "type": "LazyLock>>>", + "count": 1, + "category": "B", + "reason": "Inbound triage-once claims, keyed by workspace directory: each workspace's claims live in their own entry and persist only to that workspace's storage (inbound.direct), so one profile never reads or writes another's. An entry holds event dedupe keys (source:event_id) and claim states, no payloads.", + "verification": "inbound/claims_tests.rs: each_workspace_keeps_its_own_claims, a_direct_path_event_is_skipped_after_a_restart" + }, { "file": "crates/openhuman-core/src/inference/provider/factory/routing.rs", "scope": "", From 7663a314afd4974cbfecece70494901cf6d39a6d Mon Sep 17 00:00:00 2001 From: Ghost Scripter Date: Thu, 12 Nov 2026 11:03:08 +0530 Subject: [PATCH 5/6] fix(inbound): hold a direct-path claim until its triage ends Review follow-up (CodeRabbit, Codex). A direct-path claim no longer marks the event handled the moment the offer gives up: - The direct path holds a DirectClaim and finishes it with what it did: handled (a decision applied, or terminal) records it in inbound.direct and later deliveries drop the queued copy; not handled (failed or deferred triage, a dropped task) releases it and the queued copy runs, so a failed direct run loses nothing. While it runs, Deliver retries the turn after DIRECT_WAIT_MS instead of dropping or triaging it. - The direct path is granted once per event: a second ambiguous offer (running or done), or one after the queues delivered it, is refused (Queued(Duplicate)), and a delivered claim is kept, not removed. - Records are read before the claims answer (the store stays locked while they load); a failed read is retried on the next use instead of leaving an empty view, delivery answering from memory meanwhile. - A handled claim evicted from memory is looked up in the store. - Claims are keyed by workspace and acting storage scope, and Deliver resolves the workspace its context is bound to now on every delivery (desktop can switch the active workspace without a rebuild). - A later unsent attempt no longer settles an earlier ambiguous one. - Recording failures are reported through observability. Composio and webhook direct paths report their outcome through an OnHandled callback; turn sorting moved into claims.rs and the direct deliver tests into deliver_direct_tests.rs (file-size limit). Relates to #8154 Co-Authored-By: Claude Opus 5.5 --- .github/workflows/test-reusable.yml | 2 + crates/openhuman-core/src/inbound/claims.rs | 402 +++++++++++++----- .../src/inbound/claims_tests.rs | 191 +++++++-- crates/openhuman-core/src/inbound/deliver.rs | 73 ++-- .../src/inbound/deliver_direct_tests.rs | 79 ++++ .../src/inbound/deliver_tests.rs | 43 +- crates/openhuman-core/src/inbound/route.rs | 52 ++- .../openhuman-core/src/inbound/route_tests.rs | 67 ++- .../composio/bus/trigger_subscriber.rs | 28 +- .../composio/bus/trigger_subscriber_tests.rs | 11 +- .../openhuman-core/src/skills/webhooks/bus.rs | 46 +- .../src/skills/webhooks/bus_tests.rs | 7 +- .../test-module-installation.test.mjs | 2 + scripts/ci/process-statics.json | 4 +- 14 files changed, 733 insertions(+), 274 deletions(-) create mode 100644 crates/openhuman-core/src/inbound/deliver_direct_tests.rs diff --git a/.github/workflows/test-reusable.yml b/.github/workflows/test-reusable.yml index 759de5adc40..d8ab9c7e45d 100644 --- a/.github/workflows/test-reusable.yml +++ b/.github/workflows/test-reusable.yml @@ -248,6 +248,8 @@ jobs: inbound::route::tests::an_accepted_event_is_queued_and_a_redelivery_ends_at_ingress inbound::route::tests::a_timed_out_ingest_that_landed_is_triaged_once inbound::route::tests::an_event_delivered_while_its_offer_waited_is_not_run_directly + inbound::route::tests::an_ingest_that_landed_still_runs_once_when_the_direct_path_fails + inbound::route::tests::a_second_ambiguous_offer_of_an_event_does_not_run_it_directly_again integrations::composio::bus::trigger_subscriber::tests::a_deferred_composio_trigger_is_retried_at_its_defer_time_instead_of_dropped integrations::composio::bus::trigger_subscriber::tests::a_redelivered_composio_trigger_produces_one_turn integrations::composio::bus::trigger_subscriber::tests::without_a_config_a_trigger_is_triaged_directly diff --git a/crates/openhuman-core/src/inbound/claims.rs b/crates/openhuman-core/src/inbound/claims.rs index dde89c4337a..05ba11ba2e6 100644 --- a/crates/openhuman-core/src/inbound/claims.rs +++ b/crates/openhuman-core/src/inbound/claims.rs @@ -10,50 +10,59 @@ //! - the offer opens a claim before its first attempt and closes it when the //! queues answer; //! - a `Deliver` of an event whose claim is open takes it: the queues run -//! the event, and an offer that gives up later does not run it directly; -//! - an offer that gives up first takes the claim for the direct path and -//! records it on the host's storage, and every later `Deliver` of the -//! event skips it (publishing `InboundEventDropped`), across a restart too. +//! the event, and no ambiguous offer of it runs it directly any more; +//! - an offer that gives up first takes the event for the direct path +//! ([`DirectClaim`]), once: a second ambiguous offer of the same event is +//! not given it. While the direct path runs, a `Deliver` of the event is +//! asked to come back later; when it handled the event the claim is +//! recorded on the host's storage, and every later `Deliver` skips the +//! event (publishing `InboundEventDropped`), across a restart too. When it +//! did not (a failed or deferred triage, a dropped task), the claim is +//! released and the queues' copy runs, so nothing is lost. //! //! | Collection | Document id | Holds | //! | --- | --- | --- | -//! | `inbound.direct` | `Key::of([source:event_id])` | an event the direct path ran, and when | +//! | `inbound.direct` | `Key::of([source:event_id])` | an event the direct path handled, and when | //! -//! Claims belong to a workspace: each workspace's are kept apart, in memory -//! and in that workspace's own storage, so no profile reads or writes -//! another's records. +//! Claims belong to a workspace and storage scope: each one's are kept +//! apart, in memory and in that scope's own storage, so no profile reads or +//! writes another's records. The records are read before the claims answer +//! anything; a store that cannot be read is tried again on the next use, +//! the claims answering from memory meanwhile, so a broken store never stops +//! delivery. //! //! Records are kept as long as the module keeps its tombstones (30 days), //! so a dead-lettered copy redriven later is still recognised. They are -//! rare: only an offer whose every attempt was ambiguous writes one. +//! rare: only a direct path run after an ambiguous offer writes one. use std::collections::{HashMap, VecDeque}; use std::path::{Path, PathBuf}; -use std::sync::{Arc, LazyLock, Mutex, OnceLock, PoisonError}; +use std::sync::{Arc, LazyLock, Mutex, PoisonError}; use serde::{Deserialize, Serialize}; use tinystoragedrivers::{CollectionSpec, ErrorKind, Precondition, Query}; use tinyeventqueues_bus::Turn; -use crate::config::Config; use crate::core::bus::BUS; use crate::core::events::DomainEvent; +use crate::core::runtime::DispatchCtx; use crate::storage::documents::Repo; use crate::storage::schema_support::key_of; use crate::storage::DocumentStoreExt; -/// The collection of events the direct path ran. +/// The collection of events the direct path handled. pub const DIRECT: &str = "inbound.direct"; const DOMAIN: &str = "inbound::claims"; -/// How many direct-path events are remembered in memory. +/// How many settled claims (delivered, or handled directly) are remembered +/// in memory. const CAPACITY: usize = 4_096; /// How long a direct-path event is recorded: the module's tombstone TTL. const TTL_MS: i64 = 30 * 24 * 60 * 60 * 1_000; -/// Why an event the direct path ran is not delivered. +/// Why an event the direct path handled is not delivered. pub const HANDLED_DIRECTLY: &str = "handled_directly"; /// What the inbound host keeps for its claims. @@ -66,13 +75,26 @@ pub fn collection_specs() -> Vec { enum Claim { /// The offer is still waiting for the queues' answer. Open, - /// The queues delivered it while the offer waited. + /// The queues delivered it: they own it. Delivered, - /// The direct path runs it. + /// The direct path is running it. Direct, + /// The direct path handled it. + Handled, } -/// An event the direct path ran, as stored. +/// What a `Deliver` does with one event. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Delivery { + /// Deliver it. + Run, + /// The direct path is running it: deliver it later. + Wait, + /// The direct path handled it: drop it. + Skip, +} + +/// An event the direct path handled, as stored. #[derive(Debug, Clone, Serialize, Deserialize)] struct Record { key: String, @@ -82,66 +104,106 @@ struct Record { #[derive(Debug, Default)] struct Memory { claims: HashMap, - /// The `Direct` claims, oldest first, for eviction. - direct: VecDeque, + /// The settled claims, oldest first, for eviction. + settled: VecDeque, + /// Whether a handled claim was evicted, so a miss may be in the store. + evicted: bool, } impl Memory { - fn direct(&mut self, key: &str) { - if self.claims.insert(key.to_owned(), Claim::Direct) != Some(Claim::Direct) { - self.direct.push_back(key.to_owned()); + fn settle(&mut self, key: &str, claim: Claim) { + if !matches!( + self.claims.insert(key.to_owned(), claim), + Some(Claim::Delivered | Claim::Handled) + ) { + self.settled.push_back(key.to_owned()); } - while self.direct.len() > CAPACITY { - if let Some(oldest) = self.direct.pop_front() { - self.claims.remove(&oldest); + while self.settled.len() > CAPACITY { + if let Some(oldest) = self.settled.pop_front() { + if self.claims.remove(&oldest) == Some(Claim::Handled) { + self.evicted = true; + } } } } } -/// The claims of one workspace, over its storage once attached. -#[derive(Default)] +/// Where the claims' records live. +#[derive(Clone)] +enum Store { + /// Nowhere: the claims are memory only. + None, + /// In this workspace's storage, not read yet. + Unread(PathBuf), + /// In this repository, read into memory. + Read(Repo), +} + +/// The claims of one workspace and storage scope. pub struct Claims { memory: Mutex, - store: OnceLock>, + store: Mutex, +} + +impl Default for Claims { + /// Claims in memory only. + fn default() -> Self { + Self::with_store(Store::None) + } } impl std::fmt::Debug for Claims { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let read = matches!(*self.store(), Store::Read(_)); f.debug_struct("Claims") - .field("attached", &self.store.get().is_some_and(Option::is_some)) + .field("read", &read) .finish_non_exhaustive() } } -/// Each workspace's claims, by workspace directory. -static WORKSPACES: LazyLock>>> = LazyLock::new(Mutex::default); +/// Claims by workspace directory and storage scope. +type ByWorkspace = HashMap<(PathBuf, String), Arc>; + +/// Each workspace and storage scope's claims. +static WORKSPACES: LazyLock> = LazyLock::new(Mutex::default); impl Claims { - /// The claims the offers and deliveries of `config`'s workspace share, - /// attached to its storage (and loaded, at `now_ms`) on first use. - #[must_use] - pub fn of_workspace(config: &Config, now_ms: i64) -> Arc { - let claims = Self::for_dir(&config.workspace_dir); - claims.attach(config, now_ms); - claims + fn with_store(store: Store) -> Self { + Self { + memory: Mutex::new(Memory::default()), + store: Mutex::new(store), + } } - fn for_dir(workspace_dir: &Path) -> Arc { - Arc::clone( + /// The claims the offers and deliveries of `workspace_dir` share under + /// the acting storage scope, their records read (at `now_ms`) on first + /// use and again after a failed read. + #[must_use] + pub fn of_workspace(workspace_dir: &Path, now_ms: i64) -> Arc { + let scope = crate::storage::current_scope() + .map(|scope| scope.as_str().to_owned()) + .unwrap_or_default(); + let claims = Arc::clone( WORKSPACES .lock() .unwrap_or_else(PoisonError::into_inner) - .entry(workspace_dir.to_path_buf()) - .or_default(), - ) + .entry((workspace_dir.to_path_buf(), scope)) + .or_insert_with(|| { + Arc::new(Self::with_store(Store::Unread(workspace_dir.to_path_buf()))) + }), + ); + claims.read(now_ms); + claims } - /// Claims over `scoped` storage, loaded at `now_ms` (tests). + /// Claims over `scoped` storage, read at `now_ms` (tests). #[cfg(test)] pub(crate) fn over(scoped: &crate::storage::Storage, now_ms: i64) -> Self { - let claims = Self::default(); - claims.attach_repo(Repo::over(scoped, DOMAIN, collection_specs), now_ms); + let repo = Repo::over(scoped, DOMAIN, collection_specs); + let claims = Self::with_store(Store::None); + let keys = load(&repo, now_ms).expect("read the claims"); + claims.remember(keys); + *claims.store() = Store::Read(repo); claims } @@ -149,37 +211,41 @@ impl Claims { self.memory.lock().unwrap_or_else(PoisonError::into_inner) } - /// Record direct-path events on `config`'s workspace storage from now - /// on, and remember the ones recorded before (a previous process's). - /// Only the first call opens the store; a store that cannot be opened - /// leaves the claims in memory. - fn attach(&self, config: &Config, now_ms: i64) { - if self.store.get().is_some() { + fn store(&self) -> std::sync::MutexGuard<'_, Store> { + self.store.lock().unwrap_or_else(PoisonError::into_inner) + } + + /// Read the records into memory unless they were. The store stays locked + /// until they are, so no caller answers from a half-read memory. + fn read(&self, now_ms: i64) { + let mut store = self.store(); + let Store::Unread(workspace_dir) = &*store else { return; - } - match Repo::current_for(&config.workspace_dir, DOMAIN, collection_specs) { - Ok(repo) => self.attach_repo(repo, now_ms), + }; + let read = Repo::current_for(workspace_dir, DOMAIN, collection_specs) + .and_then(|repo| load(&repo, now_ms).map(|keys| (repo, keys))); + match read { + Ok((repo, keys)) => { + self.remember(keys); + *store = Store::Read(repo); + } Err(error) => { - tracing::warn!(error = %error, "[inbound::claims] store unavailable; claims kept in memory only"); - let _ = self.store.set(None); + tracing::warn!(error = %error, "[inbound::claims] records unreadable; answering from memory and reading again next time"); } } } - fn attach_repo(&self, repo: Repo, now_ms: i64) { - if self.store.set(Some(repo.clone())).is_err() { - return; + fn remember(&self, keys: Vec) { + let mut memory = self.memory(); + for key in keys { + memory.settle(&key, Claim::Handled); } - match load(&repo, now_ms) { - Ok(keys) => { - let mut memory = self.memory(); - for key in keys { - memory.direct(&key); - } - } - Err(error) => { - tracing::warn!(error = %error, "[inbound::claims] could not read earlier direct-path events"); - } + } + + fn repo(&self) -> Option { + match &*self.store() { + Store::Read(repo) => Some(repo.clone()), + Store::None | Store::Unread(_) => None, } } @@ -195,55 +261,148 @@ impl Claims { /// proved they never saw it. pub fn close(&self, key: &str) { let mut memory = self.memory(); - if matches!(memory.claims.get(key), Some(Claim::Open | Claim::Delivered)) { + if memory.claims.get(key) == Some(&Claim::Open) { memory.claims.remove(key); } } /// Every attempt to offer `key` was ambiguous: take it for the direct - /// path at `now_ms`. `false` when the queues delivered it meanwhile, so - /// the caller must not run it. - pub fn take_direct(&self, key: &str, now_ms: i64) -> bool { + /// path. `None` when the queues delivered it, or another offer has the + /// direct path running or done, so the caller must not run it. + pub fn take_direct(self: &Arc, key: &str) -> Option { + let mut memory = self.memory(); + match memory.claims.get(key) { + Some(Claim::Delivered | Claim::Direct | Claim::Handled) => None, + Some(Claim::Open) | None => { + memory.claims.insert(key.to_owned(), Claim::Direct); + Some(DirectClaim { + claims: Arc::clone(self), + key: key.to_owned(), + finished: false, + }) + } + } + } + + /// The queues deliver `key`. + pub fn delivering(&self, key: &str) -> Delivery { + let mut memory = self.memory(); + match memory.claims.get(key) { + Some(Claim::Handled) => Delivery::Skip, + Some(Claim::Direct) => Delivery::Wait, + Some(Claim::Open) => { + memory.settle(key, Claim::Delivered); + Delivery::Run + } + Some(Claim::Delivered) => Delivery::Run, + None if memory.evicted => { + drop(memory); + if self.recorded(key) { + self.memory().settle(key, Claim::Handled); + Delivery::Skip + } else { + Delivery::Run + } + } + None => Delivery::Run, + } + } + + /// Whether the store holds an unexpired record of `key` (a claim that + /// left memory). + fn recorded(&self, key: &str) -> bool { + let Some(repo) = self.repo() else { + return false; + }; + let Ok(id) = key_of(key) else { + return false; + }; + let now_ms = chrono::Utc::now().timestamp_millis(); + let found = repo.run(|docs| async move { docs.get(DIRECT, &id).await }); + match found { + Ok(Some(found)) => serde_json::from_value::(found.doc) + .is_ok_and(|record| now_ms - record.recorded_ms <= TTL_MS), + Ok(None) => false, + Err(error) => { + tracing::warn!(key = %key, error = %error, "[inbound::claims] could not read a direct-path record; delivering"); + false + } + } + } + + /// Settle `key`'s direct-path claim: recorded at `now_ms` when the + /// direct path handled the event, released otherwise. + fn finish(&self, key: &str, handled: bool, now_ms: i64) { { let mut memory = self.memory(); - if memory.claims.get(key) == Some(&Claim::Delivered) { + if memory.claims.get(key) != Some(&Claim::Direct) { + return; + } + if handled { + memory.settle(key, Claim::Handled); + } else { memory.claims.remove(key); - return false; } - memory.direct(key); } - if let Some(Some(repo)) = self.store.get() { - if let Err(error) = record(repo, key, now_ms) { + if !handled { + return; + } + if let Some(repo) = self.repo() { + if let Err(error) = record(&repo, key, now_ms) { // Still skipped in this process; only a restart before the // queued copy is delivered could run it a second time. - tracing::warn!(key = %key, error = %error, "[inbound::claims] could not record a direct-path event"); + let detail = + format!("[inbound::claims] could not record a direct-path event: {error:#}"); + crate::core::observability::report_error_or_expected( + detail.as_str(), + "inbound", + "record_direct", + &[], + ); } } - true } - /// The queues deliver `key`: `true` when the direct path ran it, so the - /// delivery skips it. - pub fn delivering(&self, key: &str) -> bool { - let mut memory = self.memory(); - match memory.claims.get(key) { - Some(Claim::Direct) => true, - Some(Claim::Open) => { - memory.claims.insert(key.to_owned(), Claim::Delivered); - false - } - Some(Claim::Delivered) | None => false, - } + /// The claims of the workspace `ctx` is bound to now (the active + /// workspace can change without the core being rebuilt), read at + /// `now_ms` on first use. + pub async fn of_ctx(ctx: &DispatchCtx, now_ms: i64) -> Arc { + let bound = ctx.core().and_then(|core| core.workspace_dir().ok()); + let workspace_dir = match bound { + Some(dir) => dir, + None => match ctx.load_config().await { + Ok(config) => config.workspace_dir, + Err(error) => { + tracing::debug!(error = %error, "[inbound::claims] config unavailable; the default workspace's claims"); + crate::config::Config::default().workspace_dir + } + }, + }; + Self::of_workspace(&workspace_dir, now_ms) } -} -impl Claims { - /// Leave out of `turn`, which the queues deliver, the events the direct - /// path ran, each dropped as `handled_directly`. - pub fn leave_out_direct(&self, turn: &mut Turn) { + /// What becomes of `turn`, which the queues deliver: delivered later + /// while a direct path is still running one of its events; otherwise + /// without the events the direct paths handled, each dropped as + /// `handled_directly`. A turn that came with no events is delivered as + /// it is (and rejected there). + pub fn sort(&self, mut turn: Turn) -> Sorted { + if turn.events.is_empty() { + return Sorted::Deliver(turn); + } + let deliveries: Vec = turn + .events + .iter() + .map(|event| self.delivering(&event.dedupe_key())) + .collect(); + if deliveries.contains(&Delivery::Wait) { + tracing::info!(turn = %turn.turn_id, "[inbound] the direct path is still running an event of this turn; delivering it later"); + return Sorted::Wait(turn); + } let turn_id = turn.turn_id.clone(); + let mut deliveries = deliveries.into_iter(); turn.events.retain(|event| { - if !self.delivering(&event.dedupe_key()) { + if deliveries.next() != Some(Delivery::Skip) { return true; } tracing::info!( @@ -259,6 +418,51 @@ impl Claims { }); false }); + if turn.events.is_empty() { + Sorted::Handled + } else { + Sorted::Deliver(turn) + } + } +} + +/// What becomes of a turn given the direct paths' claims on its events. +#[derive(Debug)] +pub enum Sorted { + /// Deliver what is left of it. + Deliver(Turn), + /// A direct path is running one of its events: deliver it later. + Wait(Turn), + /// The direct paths handled every event. + Handled, +} + +/// An event taken for the direct path. Its caller reports whether the +/// direct path handled it ([`Self::finish`]); dropped unreported, it is +/// released, so the queues' copy runs. +#[derive(Debug)] +pub struct DirectClaim { + claims: Arc, + key: String, + finished: bool, +} + +impl DirectClaim { + /// The direct path ended: `handled` when it decided the event (applied + /// or terminal), so the queues' copy is dropped; otherwise it is + /// released and the queues' copy runs. + pub fn finish(mut self, handled: bool) { + self.finished = true; + self.claims + .finish(&self.key, handled, chrono::Utc::now().timestamp_millis()); + } +} + +impl Drop for DirectClaim { + fn drop(&mut self) { + if !self.finished { + self.claims.finish(&self.key, false, 0); + } } } diff --git a/crates/openhuman-core/src/inbound/claims_tests.rs b/crates/openhuman-core/src/inbound/claims_tests.rs index 39b4a4879c1..7e80465f370 100644 --- a/crates/openhuman-core/src/inbound/claims_tests.rs +++ b/crates/openhuman-core/src/inbound/claims_tests.rs @@ -8,85 +8,188 @@ fn storage() -> crate::storage::Storage { tinystoragedrivers_testkit::memory_storage(&crate::storage::Scope::new("local").unwrap()) } +fn claims() -> Arc { + Arc::new(Claims::default()) +} + #[test] -fn an_event_taken_for_the_direct_path_is_skipped_by_its_delivery() { - let claims = Claims::default(); +fn a_running_direct_path_holds_its_delivery_and_a_handled_one_drops_it() { + let claims = claims(); claims.open("composio:slack:e1"); - assert!(claims.take_direct("composio:slack:e1", NOW_MS)); - assert!(claims.delivering("composio:slack:e1")); - // And by any redelivery of it. - assert!(claims.delivering("composio:slack:e1")); + let claim = claims.take_direct("composio:slack:e1").unwrap(); + assert_eq!(claims.delivering("composio:slack:e1"), Delivery::Wait); + claim.finish(true); + assert_eq!(claims.delivering("composio:slack:e1"), Delivery::Skip); + // And any redelivery of it. + assert_eq!(claims.delivering("composio:slack:e1"), Delivery::Skip); +} + +#[test] +fn a_direct_path_that_did_not_handle_its_event_releases_it_to_the_queues() { + // A failed or deferred triage: the queued copy runs, nothing is lost. + let claims = claims(); + claims + .take_direct("composio:slack:e2") + .unwrap() + .finish(false); + assert_eq!(claims.delivering("composio:slack:e2"), Delivery::Run); +} + +#[test] +fn a_direct_claim_dropped_unfinished_is_released() { + // The direct task ended without saying (a panic, a dropped future). + let claims = claims(); + drop(claims.take_direct("composio:slack:e3").unwrap()); + assert_eq!(claims.delivering("composio:slack:e3"), Delivery::Run); +} + +#[test] +fn the_direct_path_is_taken_once_per_event() { + // A second ambiguous offer of the event (a platform redelivery during the + // same outage) is not given it, running or done. + let claims = claims(); + let first = claims.take_direct("composio:slack:e4").unwrap(); + assert!(claims.take_direct("composio:slack:e4").is_none()); + first.finish(true); + assert!(claims.take_direct("composio:slack:e4").is_none()); } #[test] -fn an_event_delivered_while_its_offer_waited_is_not_taken_for_the_direct_path() { - let claims = Claims::default(); - claims.open("composio:slack:e2"); - assert!(!claims.delivering("composio:slack:e2")); - assert!(!claims.take_direct("composio:slack:e2", NOW_MS)); - // Settled: nothing is left behind. - assert!(!claims.delivering("composio:slack:e2")); +fn an_event_delivered_while_its_offer_waited_is_never_taken_for_the_direct_path() { + let claims = claims(); + claims.open("composio:slack:e5"); + assert_eq!(claims.delivering("composio:slack:e5"), Delivery::Run); + assert!(claims.take_direct("composio:slack:e5").is_none()); + // Not a later offer of it either: the queues own it. + claims.open("composio:slack:e5"); + claims.close("composio:slack:e5"); + assert!(claims.take_direct("composio:slack:e5").is_none()); } #[test] fn an_answered_offer_leaves_no_claim() { - let claims = Claims::default(); - claims.open("composio:slack:e3"); - claims.close("composio:slack:e3"); - assert!(!claims.delivering("composio:slack:e3")); + let claims = claims(); + claims.open("composio:slack:e6"); + claims.close("composio:slack:e6"); + assert_eq!(claims.delivering("composio:slack:e6"), Delivery::Run); // Closing never undoes a direct-path claim. - assert!(claims.take_direct("composio:slack:e4", NOW_MS)); - claims.close("composio:slack:e4"); - assert!(claims.delivering("composio:slack:e4")); + let claim = claims.take_direct("composio:slack:e7").unwrap(); + claims.close("composio:slack:e7"); + assert_eq!(claims.delivering("composio:slack:e7"), Delivery::Wait); + claim.finish(true); } #[test] fn an_event_never_offered_through_a_claim_is_delivered() { - let claims = Claims::default(); - assert!(!claims.delivering("webhook:t1:c1")); + assert_eq!(claims().delivering("webhook:t1:c1"), Delivery::Run); } #[test] -fn a_direct_path_event_is_skipped_after_a_restart() { +fn a_handled_direct_path_event_is_skipped_after_a_restart() { let storage = storage(); - let before = Claims::over(&storage, NOW_MS); - assert!(before.take_direct("webhook:t1:c2", NOW_MS)); + let before = Arc::new(Claims::over(&storage, NOW_MS)); + before.take_direct("webhook:t1:c2").unwrap().finish(true); + // A running one is not recorded: after a restart its copy runs. + let running = before.take_direct("webhook:t1:c3").unwrap(); // A new process over the same storage. let after = Claims::over(&storage, NOW_MS + 1_000); - assert!(after.delivering("webhook:t1:c2")); - assert!(!after.delivering("webhook:t1:c3")); + assert_eq!(after.delivering("webhook:t1:c2"), Delivery::Skip); + assert_eq!(after.delivering("webhook:t1:c3"), Delivery::Run); + drop(running); } #[test] fn a_direct_path_record_expires_with_the_module_tombstones() { let storage = storage(); - assert!(Claims::over(&storage, NOW_MS).take_direct("webhook:t1:c4", NOW_MS)); - let later = Claims::over(&storage, NOW_MS + TTL_MS + 1); - assert!(!later.delivering("webhook:t1:c4")); + Arc::new(Claims::over(&storage, NOW_MS)) + .take_direct("webhook:t1:c4") + .unwrap() + .finish(true); + // The record is stamped with the clock, so read it a TTL later. + let now = chrono::Utc::now().timestamp_millis(); + let later = Claims::over(&storage, now + TTL_MS + 1); + assert_eq!(later.delivering("webhook:t1:c4"), Delivery::Run); // The expired record was deleted, not just ignored. - let again = Claims::over(&storage, NOW_MS); - assert!(!again.delivering("webhook:t1:c4")); + let again = Claims::over(&storage, now); + assert_eq!(again.delivering("webhook:t1:c4"), Delivery::Run); +} + +#[test] +fn a_handled_claim_evicted_from_memory_is_still_found_in_the_store() { + let storage = storage(); + let claims = Arc::new(Claims::over(&storage, NOW_MS)); + claims + .take_direct("composio:slack:old") + .unwrap() + .finish(true); + for n in 0..CAPACITY { + claims.open(&format!("composio:slack:b{n}")); + claims.delivering(&format!("composio:slack:b{n}")); + } + assert!(!claims.memory().claims.contains_key("composio:slack:old")); + assert_eq!(claims.delivering("composio:slack:old"), Delivery::Skip); } #[test] -fn direct_path_claims_are_bounded_in_memory() { - let claims = Claims::default(); +fn settled_claims_are_bounded_in_memory() { + let claims = claims(); for n in 0..=CAPACITY { - assert!(claims.take_direct(&format!("composio:slack:b{n}"), NOW_MS)); + claims.open(&format!("composio:slack:b{n}")); + claims.delivering(&format!("composio:slack:b{n}")); } - assert!(!claims.delivering("composio:slack:b0")); - assert!(claims.delivering(&format!("composio:slack:b{CAPACITY}"))); + let memory = claims.memory(); + assert_eq!(memory.claims.len(), CAPACITY); + assert!(!memory.claims.contains_key("composio:slack:b0")); } #[test] fn each_workspace_keeps_its_own_claims() { let (a, b) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap()); - let config = |dir: &tempfile::TempDir| { - let mut config = Config::default(); - config.workspace_dir = dir.path().to_path_buf(); - config + Claims::of_workspace(a.path(), NOW_MS) + .take_direct("composio:slack:w1") + .unwrap() + .finish(true); + assert_eq!( + Claims::of_workspace(b.path(), NOW_MS).delivering("composio:slack:w1"), + Delivery::Run + ); + assert_eq!( + Claims::of_workspace(a.path(), NOW_MS).delivering("composio:slack:w1"), + Delivery::Skip + ); +} + +#[test] +fn a_turn_waits_for_a_running_direct_path_and_drops_only_handled_events() { + use tinyeventqueues_bus::{InboundEvent, Lane}; + let event = |id: &str| { + let envelope = crate::triage::TriggerEnvelope::from_composio( + "slack", + "SLACK_MESSAGE", + "", + id, + serde_json::json!({}), + ); + super::super::events::composio(&envelope).unwrap() }; - assert!(Claims::of_workspace(&config(&a), NOW_MS).take_direct("composio:slack:w1", NOW_MS)); - assert!(!Claims::of_workspace(&config(&b), NOW_MS).delivering("composio:slack:w1")); - assert!(Claims::of_workspace(&config(&a), NOW_MS).delivering("composio:slack:w1")); + let turn = |events: Vec| Turn::new("t", Lane::Background, "c", events); + let claims = claims(); + let running = claims.take_direct(&event("s1").dedupe_key()).unwrap(); + assert!(matches!( + claims.sort(turn(vec![event("s1"), event("s2")])), + Sorted::Wait(_) + )); + running.finish(true); + match claims.sort(turn(vec![event("s1"), event("s2")])) { + Sorted::Deliver(left) => { + assert_eq!(left.events.len(), 1); + assert_eq!(left.events[0].event_id, event("s2").event_id); + } + other => panic!("expected the rest delivered, got {other:?}"), + } + assert!(matches!( + claims.sort(turn(vec![event("s1")])), + Sorted::Handled + )); + assert!(matches!(claims.sort(turn(Vec::new())), Sorted::Deliver(_))); } diff --git a/crates/openhuman-core/src/inbound/deliver.rs b/crates/openhuman-core/src/inbound/deliver.rs index 325e7038264..2e2d54321e0 100644 --- a/crates/openhuman-core/src/inbound/deliver.rs +++ b/crates/openhuman-core/src/inbound/deliver.rs @@ -42,10 +42,12 @@ //! turn that was already accepted is accepted again without triage, so a //! redelivery that raced a slow answer never applies a second decision. //! -//! An event its offer already ran on the caller's direct path (every -//! `Ingest` attempt was ambiguous, yet the module persisted it, -//! [`super::claims`]) is left out of its turn and dropped with the reason -//! `handled_directly`; a turn left with no events is accepted as it is. +//! An event its offer took for the caller's direct path (every `Ingest` +//! attempt was ambiguous, yet the module persisted it, [`super::claims`]) +//! is not delivered twice: while the direct path runs the turn is retried +//! later; once it handled the event, the event is left out of its turn and +//! dropped with the reason `handled_directly`, and a turn left with no +//! events is accepted as it is. use std::collections::{BTreeMap, HashMap, VecDeque}; use std::sync::{Arc, Mutex}; @@ -56,7 +58,10 @@ use tinyeventqueues_bus::{ DeliverStatus, InboundEvent, Lane, SalienceClass, Turn, }; -use super::claims::Claims; +use super::claims::{Claims, Sorted}; + +/// How long a turn waits for a direct path still running one of its events. +const DIRECT_WAIT_MS: u64 = 60_000; use super::events::{digest_envelope, envelope_of}; use super::pinned::{Delivered, Pinned}; use super::results::Results; @@ -165,9 +170,10 @@ pub struct Deliverer { inbound: tokio::sync::OnceCell>, /// What runs pinned sources' turns: given, or built on first use. pinned: tokio::sync::OnceCell>, - /// Who ran events whose offers were ambiguous: the configured - /// workspace's claims, resolved on first use. - claims: tokio::sync::OnceCell>, + /// Who runs events whose offers were ambiguous: given, or the current + /// workspace's, resolved on every delivery (the active workspace can + /// change without the core being rebuilt). + claims: Option>, } impl std::fmt::Debug for Deliverer { @@ -193,7 +199,7 @@ impl Deliverer { .with_inbound(InboundConfig::default()); // Given its settings, it reads no configuration: its claims are its // own unless given some (`Self::with_claims`). - deliverer.claims = tokio::sync::OnceCell::new_with(Some(Arc::new(Claims::default()))); + deliverer.claims = Some(Arc::new(Claims::default())); deliverer } @@ -223,7 +229,7 @@ impl Deliverer { accepted: Mutex::new(Accepted::default()), inbound: tokio::sync::OnceCell::new(), pinned: tokio::sync::OnceCell::new(), - claims: tokio::sync::OnceCell::new(), + claims: None, } } @@ -245,7 +251,7 @@ impl Deliverer { /// Share `claims` with the offers of the events it delivers. #[must_use] pub fn with_claims(mut self, claims: Arc) -> Self { - self.claims = tokio::sync::OnceCell::new_with(Some(claims)); + self.claims = Some(claims); self } @@ -418,31 +424,12 @@ impl Deliverer { } } - /// The configured workspace's claims, resolved on first use. - async fn claims(&self) -> &Claims { - self.claims - .get_or_init(|| async { - let config = match self.ctx.load_config().await { - Ok(config) => config, - Err(error) => { - tracing::debug!(error = %error, "[inbound] config unavailable; the default workspace's claims"); - crate::config::Config::default() - } - }; - Claims::of_workspace(&config, (self.now_ms)()) - }) - .await - } - - /// `turn` without the events their offers already ran directly, each - /// dropped; `None` when that left none (a turn that came with none is - /// returned as it is, to be rejected). - async fn without_direct(&self, mut turn: Turn) -> Option { - if turn.events.is_empty() { - return Some(turn); + /// The given claims, or the current workspace's. + async fn claims(&self) -> Arc { + match &self.claims { + Some(claims) => Arc::clone(claims), + None => Claims::of_ctx(&self.ctx, (self.now_ms)()).await, } - self.claims().await.leave_out_direct(&mut turn); - (!turn.events.is_empty()).then_some(turn) } fn classified(&self) -> std::sync::MutexGuard<'_, Classified> { @@ -514,9 +501,19 @@ impl Deliverer { return DeliverResponse::new(DeliverStatus::Accepted); } let turn_id = turn.turn_id.clone(); - let Some(turn) = self.without_direct(turn).await else { - self.accepted().remember(&turn_id); - return DeliverResponse::new(DeliverStatus::Accepted); + let turn = match self.claims().await.sort(turn) { + Sorted::Deliver(turn) => turn, + Sorted::Wait(turn) => { + return DeliverResponse::new(self.retry( + &turn, + Some(DIRECT_WAIT_MS), + "the direct path is running an event of this turn", + )); + } + Sorted::Handled => { + self.accepted().remember(&turn_id); + return DeliverResponse::new(DeliverStatus::Accepted); + } }; if let Some((name, source)) = self.pinned_source(&turn.events).await { let remaining = self.budget.saturating_sub(started.elapsed()); diff --git a/crates/openhuman-core/src/inbound/deliver_direct_tests.rs b/crates/openhuman-core/src/inbound/deliver_direct_tests.rs new file mode 100644 index 00000000000..33c250cec1a --- /dev/null +++ b/crates/openhuman-core/src/inbound/deliver_direct_tests.rs @@ -0,0 +1,79 @@ +//! Events their offers took for the caller's direct path: held while it +//! runs, dropped once it handled them, delivered when it did not. + +use super::*; + +#[tokio::test] +async fn an_event_handled_directly_is_not_delivered_again() { + // Its offer was ambiguous and ran on the caller's direct path, yet the + // module persisted it: the queued copy must not be triaged a second time. + let event = trigger_event("deliver-direct-1"); + let claims = Arc::new(Claims::default()); + claims + .take_direct(&event.dedupe_key()) + .unwrap() + .finish(true); + let triage = ScriptedTriage::new([decision(TriageAction::React)]); + let deliverer = deliverer(&triage).with_claims(claims); + let response = deliverer + .deliver(turn(vec![event.clone()], Lane::Background, 1)) + .await; + assert_eq!(response.status, DeliverStatus::Accepted); + assert_eq!(triage.runs(), 0); + assert!(triage.applied().is_empty()); + // A redelivery of the turn is not triaged either. + let again = deliverer + .deliver(turn(vec![event], Lane::Background, 2)) + .await; + assert_eq!(again.status, DeliverStatus::Accepted); + assert_eq!(triage.runs(), 0); +} + +#[tokio::test] +async fn a_digest_leaves_out_only_the_events_handled_directly() { + let direct = trigger_event("deliver-direct-2"); + let queued = trigger_event("deliver-direct-3"); + let claims = Arc::new(Claims::default()); + claims + .take_direct(&direct.dedupe_key()) + .unwrap() + .finish(true); + let triage = ScriptedTriage::new([decision(TriageAction::React)]); + let response = deliverer(&triage) + .with_claims(claims) + .deliver(turn(vec![direct, queued], Lane::Background, 1)) + .await; + assert_eq!(response.status, DeliverStatus::Accepted); + assert_eq!(triage.runs(), 1); + assert_eq!( + triage.until_applied(1, Duration::from_secs(5)).await.len(), + 1 + ); +} + +#[tokio::test] +async fn a_turn_whose_event_the_direct_path_is_running_comes_back_later() { + // Neither dropped (the direct path may still fail) nor triaged again. + let event = trigger_event("deliver-direct-4"); + let claims = Arc::new(Claims::default()); + let running = claims.take_direct(&event.dedupe_key()).unwrap(); + let triage = ScriptedTriage::new([decision(TriageAction::React)]); + let deliverer = deliverer(&triage).with_claims(Arc::clone(&claims)); + let response = deliverer + .deliver(turn(vec![event.clone()], Lane::Background, 1)) + .await; + assert_eq!( + response.status, + DeliverStatus::Retry { + after_ms: Some(DIRECT_WAIT_MS) + } + ); + assert_eq!(triage.runs(), 0); + // The direct path failed: the queued copy is triaged on its redelivery. + running.finish(false); + let again = deliverer + .deliver(turn(vec![event], Lane::Background, 2)) + .await; + assert_eq!(again.status, DeliverStatus::Accepted); + assert_eq!(triage.runs(), 1); +} diff --git a/crates/openhuman-core/src/inbound/deliver_tests.rs b/crates/openhuman-core/src/inbound/deliver_tests.rs index 8fa5d28498f..0c0d3961147 100644 --- a/crates/openhuman-core/src/inbound/deliver_tests.rs +++ b/crates/openhuman-core/src/inbound/deliver_tests.rs @@ -685,44 +685,5 @@ async fn a_pinned_source_in_a_mixed_digest_still_runs_its_agent() { #[path = "deliver_digest_tests.rs"] mod digest; -#[tokio::test] -async fn an_event_handled_directly_is_not_delivered_again() { - // Its offer was ambiguous and ran on the caller's direct path, yet the - // module persisted it: the queued copy must not be triaged a second time. - let event = trigger_event("deliver-direct-1"); - let claims = Arc::new(Claims::default()); - assert!(claims.take_direct(&event.dedupe_key(), NOW_MS)); - let triage = ScriptedTriage::new([decision(TriageAction::React)]); - let deliverer = deliverer(&triage).with_claims(claims); - let response = deliverer - .deliver(turn(vec![event.clone()], Lane::Background, 1)) - .await; - assert_eq!(response.status, DeliverStatus::Accepted); - assert_eq!(triage.runs(), 0); - assert!(triage.applied().is_empty()); - // A redelivery of the turn is not triaged either. - let again = deliverer - .deliver(turn(vec![event], Lane::Background, 2)) - .await; - assert_eq!(again.status, DeliverStatus::Accepted); - assert_eq!(triage.runs(), 0); -} - -#[tokio::test] -async fn a_digest_leaves_out_only_the_events_handled_directly() { - let direct = trigger_event("deliver-direct-2"); - let queued = trigger_event("deliver-direct-3"); - let claims = Arc::new(Claims::default()); - assert!(claims.take_direct(&direct.dedupe_key(), NOW_MS)); - let triage = ScriptedTriage::new([decision(TriageAction::React)]); - let response = deliverer(&triage) - .with_claims(claims) - .deliver(turn(vec![direct, queued], Lane::Background, 1)) - .await; - assert_eq!(response.status, DeliverStatus::Accepted); - assert_eq!(triage.runs(), 1); - assert_eq!( - triage.until_applied(1, Duration::from_secs(5)).await.len(), - 1 - ); -} +#[path = "deliver_direct_tests.rs"] +mod direct; diff --git a/crates/openhuman-core/src/inbound/route.rs b/crates/openhuman-core/src/inbound/route.rs index 6cf4c0d8916..c432f7b99ea 100644 --- a/crates/openhuman-core/src/inbound/route.rs +++ b/crates/openhuman-core/src/inbound/route.rs @@ -22,6 +22,7 @@ //! direct path otherwise, recorded so a later `Deliver` skips it. Callers //! run the hand-off in their own task, never on a bus subscriber's loop. +use std::sync::Arc; use std::time::Duration; use tinybus::module::{ModuleCallError, ModuleClient}; @@ -32,7 +33,7 @@ use crate::core::bus::BUS; use crate::core::events::DomainEvent; use crate::modules::event_queues; -use super::claims::Claims; +use super::claims::{Claims, DirectClaim}; /// What became of an offered event. #[derive(Debug, Clone, PartialEq, Eq)] @@ -107,45 +108,48 @@ pub async fn offer(config: &Config, client: &ModuleClient, event: InboundEvent) /// Offer `event` like [`offer`], for a caller that runs its direct path on /// [`Offered::Direct`]. When every attempt is ambiguous the event goes to -/// the direct path only if the queues have not delivered it meanwhile, and -/// is recorded so they skip it if they deliver it later. +/// the direct path only if the queues have not delivered it and no other +/// offer of it took the direct path; the [`DirectClaim`] then returned is +/// the caller's to finish with what its direct path did, so the queues' +/// copy is dropped or delivered accordingly. pub async fn offer_or_direct( config: &Config, client: &ModuleClient, event: InboundEvent, -) -> Offered { +) -> (Offered, Option) { if !super::active(config) { - return Offered::Direct("inbound event queues inactive".to_owned()); + return ( + Offered::Direct("inbound event queues inactive".to_owned()), + None, + ); } - let claims = Claims::of_workspace(config, chrono::Utc::now().timestamp_millis()); + let claims = Claims::of_workspace(&config.workspace_dir, chrono::Utc::now().timestamp_millis()); offer_or_direct_with(client, event, &claims, &ATTEMPT_DEADLINES).await } async fn offer_or_direct_with( client: &ModuleClient, event: InboundEvent, - claims: &Claims, + claims: &Arc, deadlines: &[Duration], -) -> Offered { - let now_ms = || chrono::Utc::now().timestamp_millis(); +) -> (Offered, Option) { let key = event.dedupe_key(); claims.open(&key); match hand_off(client, event, deadlines).await { HandOff::Settled(offered) => { claims.close(&key); - offered + (offered, None) } - HandOff::Ambiguous(why) => { - if claims.take_direct(&key, now_ms()) { - Offered::Direct(why) - } else { + HandOff::Ambiguous(why) => match claims.take_direct(&key) { + Some(claim) => (Offered::Direct(why), Some(claim)), + None => { tracing::info!( key = %key, - "[inbound] ingest never answered, but the queues delivered the event; not taking the direct path" + "[inbound] ingest never answered, but the queues or another offer have the event; not taking the direct path" ); - Offered::Queued(Disposition::Accepted) + (Offered::Queued(Disposition::Duplicate), None) } - } + }, } } @@ -163,7 +167,7 @@ async fn hand_off(client: &ModuleClient, event: InboundEvent, deadlines: &[Durat answered = Some(response); break; } - Attempt::Unsent(error) => { + Attempt::Unsent(error) if n == 0 => { tracing::info!( source = %source, event_id = %event_id, @@ -172,6 +176,18 @@ async fn hand_off(client: &ModuleClient, event: InboundEvent, deadlines: &[Durat ); return HandOff::Settled(Offered::Direct(format!("ingest failed: {error}"))); } + Attempt::Unsent(error) => { + // This attempt never reached the module, but an earlier one + // may have: the hand-off stays ambiguous. + tracing::warn!( + source = %source, + event_id = %event_id, + attempt = n + 1, + error = %error, + "[inbound] queues unavailable after an unanswered ingest; the queues may hold the event" + ); + return HandOff::Ambiguous(format!("ingest failed: {last}; then {error}")); + } Attempt::Unknown(error) => { tracing::warn!( source = %source, diff --git a/crates/openhuman-core/src/inbound/route_tests.rs b/crates/openhuman-core/src/inbound/route_tests.rs index e399fc6250d..e0613e7a5fc 100644 --- a/crates/openhuman-core/src/inbound/route_tests.rs +++ b/crates/openhuman-core/src/inbound/route_tests.rs @@ -5,6 +5,7 @@ use std::time::Duration; use serde_json::json; use super::*; +use crate::inbound::claims::Delivery; use crate::inbound::events; use crate::inbound::fixture::{active_config, Rig, ScriptedTriage, Step}; use crate::triage::{TriageOutcome, TriggerEnvelope}; @@ -80,10 +81,11 @@ async fn a_timed_out_ingest_that_landed_is_triaged_once() { // its copy. Exactly one decision is applied. let rig = Rig::new(ScriptedTriage::new(Vec::::new())).await; let (ambiguous, _bus) = ambiguous_client().await; - let offered = + let (offered, claim) = offer_or_direct_with(&ambiguous, event("u5"), &rig.claims, &ATTEMPT_DEADLINES).await; assert!(matches!(offered, Offered::Direct(ref why) if why.contains("ingest failed"))); run_directly(&rig.triage, &event("u5")).await; + claim.expect("the direct path is taken").finish(true); // The write that landed: the module holds the event and delivers it. let landed = event_queues::ingest(&rig.client, vec![event("u5")]) .await @@ -110,10 +112,46 @@ async fn an_event_delivered_while_its_offer_waited_is_not_run_directly() { landed.unwrap().results[0].disposition, Disposition::Accepted ); - assert_eq!(offered, Offered::Queued(Disposition::Accepted)); + let (offered, claim) = offered; + assert_eq!(offered, Offered::Queued(Disposition::Duplicate)); + assert!(claim.is_none()); assert_eq!(rig.triage.applied().len(), 1); } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn an_ingest_that_landed_still_runs_once_when_the_direct_path_fails() { + // The direct triage fails, so the queues' copy is not dropped as + // handled: it is delivered and decided, once. + let rig = Rig::new(ScriptedTriage::new(Vec::::new())).await; + let (ambiguous, _bus) = ambiguous_client().await; + let (offered, claim) = + offer_or_direct_with(&ambiguous, event("u11"), &rig.claims, &ATTEMPT_DEADLINES).await; + assert!(matches!(offered, Offered::Direct(_))); + claim.expect("the direct path is taken").finish(false); + let landed = event_queues::ingest(&rig.client, vec![event("u11")]) + .await + .unwrap(); + assert_eq!(landed.results[0].disposition, Disposition::Accepted); + let applied = rig.triage.until_applied(1, Duration::from_secs(5)).await; + assert_eq!(applied.len(), 1, "the queued copy was lost"); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_second_ambiguous_offer_of_an_event_does_not_run_it_directly_again() { + // A platform redelivery during the same outage. + let rig = Rig::new(ScriptedTriage::new(Vec::::new())).await; + let (ambiguous, _bus) = ambiguous_client().await; + let (_, first) = + offer_or_direct_with(&ambiguous, event("u12"), &rig.claims, &ATTEMPT_DEADLINES).await; + first + .expect("the first offer takes the direct path") + .finish(true); + let (again, second) = + offer_or_direct_with(&ambiguous, event("u12"), &rig.claims, &ATTEMPT_DEADLINES).await; + assert_eq!(again, Offered::Queued(Disposition::Duplicate)); + assert!(second.is_none()); +} + #[tokio::test] async fn an_ingest_that_surely_failed_still_takes_the_direct_path() { // No new loss: the module never saw the event, so no claim is taken @@ -123,9 +161,11 @@ async fn an_ingest_that_surely_failed_still_takes_the_direct_path() { let mut off = config.clone(); off.modules.enabled = false; let client = crate::modules::ops::client(off); - let offered = offer_or_direct(&config, &client, event("u7")).await; + let (offered, claim) = offer_or_direct(&config, &client, event("u7")).await; assert!(matches!(offered, Offered::Direct(ref why) if why.contains("ingest failed"))); - assert!(!Claims::of_workspace(&config, 0).delivering(&event("u7").dedupe_key())); + assert!(claim.is_none()); + let claims = Claims::of_workspace(&config.workspace_dir, 0); + assert_eq!(claims.delivering(&event("u7").dedupe_key()), Delivery::Run); } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] @@ -137,7 +177,8 @@ async fn an_offer_without_a_direct_path_leaves_its_event_to_the_queues() { let (ambiguous, _bus) = ambiguous_client().await; let offered = offer(&config, &ambiguous, event("u8")).await; assert!(!offered.is_queued()); - assert!(!Claims::of_workspace(&config, 0).delivering(&event("u8").dedupe_key())); + let claims = Claims::of_workspace(&config.workspace_dir, 0); + assert_eq!(claims.delivering(&event("u8").dedupe_key()), Delivery::Run); } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] @@ -147,11 +188,15 @@ async fn an_ambiguous_offer_claims_its_event_in_its_own_workspace() { let (mine, other) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap()); let config = config_in(&mine); let (ambiguous, _bus) = ambiguous_client().await; - let offered = offer_or_direct(&config, &ambiguous, event("u9")).await; + let (offered, claim) = offer_or_direct(&config, &ambiguous, event("u9")).await; assert!(matches!(offered, Offered::Direct(ref why) if why.contains("ingest failed"))); let key = event("u9").dedupe_key(); - assert!(Claims::of_workspace(&config, 0).delivering(&key)); - assert!(!Claims::of_workspace(&config_in(&other), 0).delivering(&key)); + let theirs = Claims::of_workspace(&config_in(&other).workspace_dir, 0); + let mine = Claims::of_workspace(&config.workspace_dir, 0); + assert_eq!(mine.delivering(&key), Delivery::Wait); + assert_eq!(theirs.delivering(&key), Delivery::Run); + claim.expect("the direct path is taken").finish(true); + assert_eq!(mine.delivering(&key), Delivery::Skip); } #[tokio::test] @@ -160,9 +205,11 @@ async fn inactive_queues_send_a_direct_path_offer_down_it_without_a_claim() { let mut config = config_in(&workspace); config.inbound.enabled = false; let client = crate::modules::ops::client(config.clone()); - let offered = offer_or_direct(&config, &client, event("u10")).await; + let (offered, claim) = offer_or_direct(&config, &client, event("u10")).await; assert!(matches!(offered, Offered::Direct(ref why) if why.contains("inactive"))); - assert!(!Claims::of_workspace(&config, 0).delivering(&event("u10").dedupe_key())); + assert!(claim.is_none()); + let claims = Claims::of_workspace(&config.workspace_dir, 0); + assert_eq!(claims.delivering(&event("u10").dedupe_key()), Delivery::Run); } /// The active config, over its own workspace. diff --git a/crates/openhuman-core/src/integrations/composio/bus/trigger_subscriber.rs b/crates/openhuman-core/src/integrations/composio/bus/trigger_subscriber.rs index 5942f6a1710..4c1f19ba59c 100644 --- a/crates/openhuman-core/src/integrations/composio/bus/trigger_subscriber.rs +++ b/crates/openhuman-core/src/integrations/composio/bus/trigger_subscriber.rs @@ -206,12 +206,15 @@ pub(super) async fn route_trigger( runner: Arc, #[cfg(feature = "inbound-queues")] client: Option, ) -> Routed { + #[cfg_attr(not(feature = "inbound-queues"), allow(unused_mut))] + let mut on_handled: Option = None; #[cfg(feature = "inbound-queues")] if let Some(config) = config.as_ref() { match crate::inbound::events::composio(&envelope) { Ok(event) => { let client = client.unwrap_or_else(|| crate::modules::ops::client(config.clone())); - let offered = crate::inbound::route::offer_or_direct(config, &client, event).await; + let (offered, claim) = + crate::inbound::route::offer_or_direct(config, &client, event).await; if offered.is_queued() { tracing::debug!( label = %envelope.display_label, @@ -219,6 +222,10 @@ pub(super) async fn route_trigger( ); return Routed::Queued; } + // The queues may hold it too: tell them what the direct + // path did with it, so their copy is dropped or run. + on_handled = + claim.map(|claim| Box::new(move |handled| claim.finish(handled)) as OnHandled); } Err(why) => tracing::info!( label = %envelope.display_label, @@ -229,17 +236,23 @@ pub(super) async fn route_trigger( } #[cfg(not(feature = "inbound-queues"))] let _ = config; - Routed::Direct(triage_directly(ctx, envelope, runner)) + Routed::Direct(triage_directly(ctx, envelope, runner, on_handled)) } +/// Told, when the direct path ends, whether it handled the trigger (a +/// decision applied, or a terminal triage). +pub(super) type OnHandled = Box; + /// Triage `envelope` in its own task and apply a decision: the direct path. +/// `on_handled` hears whether it handled the trigger. pub(super) fn triage_directly( ctx: DispatchCtx, envelope: TriggerEnvelope, runner: Arc, + on_handled: Option, ) -> tokio::task::JoinHandle<()> { tokio::spawn(async move { - match runner.run(&ctx, &envelope).await { + let handled = match runner.run(&ctx, &envelope).await { Ok(TriageOutcome::Decision(run)) => { // Remote payload: a Composio trigger body is // attacker-influenceable, so the runner applies the decision @@ -250,6 +263,9 @@ pub(super) fn triage_directly( error = %e, "[composio][triage] apply_decision failed" ); + false + } else { + true } } Ok(TriageOutcome::Deferred { @@ -267,6 +283,7 @@ pub(super) fn triage_directly( reason = %reason, "[composio][triage] run_triage deferred" ); + false } Ok(TriageOutcome::Terminal { reason }) => { tracing::warn!( @@ -274,6 +291,7 @@ pub(super) fn triage_directly( reason = %reason, "[composio][triage] run_triage reached terminal state" ); + true } Err(e) => { // Route through the central observability classifier @@ -297,7 +315,11 @@ pub(super) fn triage_directly( "trigger_triage", &[("label", envelope.display_label.as_str())], ); + false } + }; + if let Some(on_handled) = on_handled { + on_handled(handled); } }) } diff --git a/crates/openhuman-core/src/integrations/composio/bus/trigger_subscriber_tests.rs b/crates/openhuman-core/src/integrations/composio/bus/trigger_subscriber_tests.rs index 545f3f4e2ca..3427e7d0d1d 100644 --- a/crates/openhuman-core/src/integrations/composio/bus/trigger_subscriber_tests.rs +++ b/crates/openhuman-core/src/integrations/composio/bus/trigger_subscriber_tests.rs @@ -117,9 +117,14 @@ async fn the_direct_path_logs_and_drops_a_deferral_and_a_terminal_outcome() { .into(), ]); for uuid in ["uuid-d1", "uuid-d2"] { - triage_directly(DispatchCtx::host_default(), trigger(uuid), triage.clone()) - .await - .unwrap(); + triage_directly( + DispatchCtx::host_default(), + trigger(uuid), + triage.clone(), + None, + ) + .await + .unwrap(); } assert_eq!(triage.runs(), 2); assert!(triage.applied().is_empty()); diff --git a/crates/openhuman-core/src/skills/webhooks/bus.rs b/crates/openhuman-core/src/skills/webhooks/bus.rs index 13056f9f7dd..dcb62e9a367 100644 --- a/crates/openhuman-core/src/skills/webhooks/bus.rs +++ b/crates/openhuman-core/src/skills/webhooks/bus.rs @@ -140,7 +140,7 @@ impl EventHandler for WebhookRequestSubscriber { let spawner = ctx.clone(); spawner.spawn(async move { let config = ctx.load_config().await.ok(); - let queued = route_agent_trigger( + let routed = route_agent_trigger( config, &envelope, &corr, @@ -148,12 +148,13 @@ impl EventHandler for WebhookRequestSubscriber { None, ) .await; - if !queued { + if let AgentRoute::Direct(on_handled) = routed { triage_agent_directly( ctx, envelope, corr, Arc::new(crate::triage::RemoteTriage), + on_handled, ); } }); @@ -261,30 +262,44 @@ impl EventHandler for WebhookRequestSubscriber { } } -/// Queue an agent webhook in the inbound event queues. `true` when they own -/// it; `false` when the caller triages it directly. `client` reaches the -/// queues module (`None`: the configured module client). +/// Told, when the direct path ends, whether it handled the webhook. +pub(super) type OnHandled = Box; + +/// Where an agent webhook went. +pub(super) enum AgentRoute { + /// The inbound event queues own it. + Queued, + /// The caller triages it directly, telling `on_handled` (when the queues + /// may hold it too) whether it handled it. + Direct(Option), +} + +/// Queue an agent webhook in the inbound event queues, or say it is the +/// caller's to triage directly. `client` reaches the queues module (`None`: +/// the configured module client). pub(super) async fn route_agent_trigger( config: Option, envelope: &crate::triage::TriggerEnvelope, correlation_id: &str, #[cfg(feature = "inbound-queues")] client: Option, -) -> bool { +) -> AgentRoute { #[cfg(feature = "inbound-queues")] if let Some(config) = config.as_ref() { match crate::inbound::events::webhook(envelope, correlation_id) { Ok(event) => { let client = client.unwrap_or_else(|| crate::modules::ops::client(config.clone())); - if crate::inbound::route::offer_or_direct(config, &client, event) - .await - .is_queued() - { + let (offered, claim) = + crate::inbound::route::offer_or_direct(config, &client, event).await; + if offered.is_queued() { tracing::debug!( correlation_id = %correlation_id, "[webhook] handed to the inbound event queues" ); - return true; + return AgentRoute::Queued; } + return AgentRoute::Direct( + claim.map(|claim| Box::new(move |handled| claim.finish(handled)) as OnHandled), + ); } Err(why) => tracing::info!( correlation_id = %correlation_id, @@ -295,16 +310,18 @@ pub(super) async fn route_agent_trigger( } #[cfg(not(feature = "inbound-queues"))] let _ = (config, envelope, correlation_id); - false + AgentRoute::Direct(None) } /// Triage an agent webhook in its own task and emit the result as a second -/// webhook response: the direct path. +/// webhook response: the direct path. `on_handled` hears whether the agent +/// answered. pub(super) fn triage_agent_directly( ctx: crate::core::runtime::DispatchCtx, envelope: crate::triage::TriggerEnvelope, corr: String, runner: Arc, + on_handled: Option, ) -> tokio::task::JoinHandle<()> { // Spawn the triage pipeline so we don't block the broadcast channel's // dispatch task during LLM calls. @@ -313,6 +330,9 @@ pub(super) fn triage_agent_directly( run_agent_trigger(&ctx, &envelope, runner.as_ref()).await }) .await; + if let Some(on_handled) = on_handled { + on_handled(matches!(result, Ok(Ok(_)))); + } let (resp, err) = match result { Ok(Ok(output)) => (build_agent_response(&corr, 200, &output), None), Ok(Err(e)) => { diff --git a/crates/openhuman-core/src/skills/webhooks/bus_tests.rs b/crates/openhuman-core/src/skills/webhooks/bus_tests.rs index 534ac10f14f..13260efdc46 100644 --- a/crates/openhuman-core/src/skills/webhooks/bus_tests.rs +++ b/crates/openhuman-core/src/skills/webhooks/bus_tests.rs @@ -148,7 +148,7 @@ mod inbound { use std::sync::Arc; use std::time::{Duration, Instant}; - use super::super::{route_agent_trigger, triage_agent_directly}; + use super::super::{route_agent_trigger, triage_agent_directly, AgentRoute}; use crate::core::runtime::DispatchCtx; use crate::inbound::fixture::{active_config, decision, deferred, Rig, ScriptedTriage}; use crate::triage::{TriageAction, TriggerEnvelope}; @@ -166,14 +166,15 @@ mod inbound { async fn route(rig: &Rig, config: Option, correlation_id: &str) { let envelope = request(); - let queued = + let routed = route_agent_trigger(config, &envelope, correlation_id, Some(rig.client.clone())).await; - if !queued { + if let AgentRoute::Direct(on_handled) = routed { triage_agent_directly( DispatchCtx::host_default(), envelope, correlation_id.to_owned(), rig.triage.clone() as Arc, + on_handled, ) .await .unwrap(); diff --git a/scripts/__tests__/test-module-installation.test.mjs b/scripts/__tests__/test-module-installation.test.mjs index 7e01749bab2..6a8439767a2 100644 --- a/scripts/__tests__/test-module-installation.test.mjs +++ b/scripts/__tests__/test-module-installation.test.mjs @@ -603,6 +603,8 @@ test("the core workflow isolates tests that need staged callback modules", () => "inbound::route::tests::an_accepted_event_is_queued_and_a_redelivery_ends_at_ingress", "inbound::route::tests::a_timed_out_ingest_that_landed_is_triaged_once", "inbound::route::tests::an_event_delivered_while_its_offer_waited_is_not_run_directly", + "inbound::route::tests::an_ingest_that_landed_still_runs_once_when_the_direct_path_fails", + "inbound::route::tests::a_second_ambiguous_offer_of_an_event_does_not_run_it_directly_again", "integrations::composio::bus::trigger_subscriber::tests::a_deferred_composio_trigger_is_retried_at_its_defer_time_instead_of_dropped", "integrations::composio::bus::trigger_subscriber::tests::a_redelivered_composio_trigger_produces_one_turn", "integrations::composio::bus::trigger_subscriber::tests::without_a_config_a_trigger_is_triaged_directly", diff --git a/scripts/ci/process-statics.json b/scripts/ci/process-statics.json index 9542fecb4dc..74d03e4b3c6 100644 --- a/scripts/ci/process-statics.json +++ b/scripts/ci/process-statics.json @@ -213,10 +213,10 @@ "file": "crates/openhuman-core/src/inbound/claims.rs", "scope": "", "name": "WORKSPACES", - "type": "LazyLock>>>", + "type": "LazyLock>", "count": 1, "category": "B", - "reason": "Inbound triage-once claims, keyed by workspace directory: each workspace's claims live in their own entry and persist only to that workspace's storage (inbound.direct), so one profile never reads or writes another's. An entry holds event dedupe keys (source:event_id) and claim states, no payloads.", + "reason": "Inbound triage-once claims, keyed by workspace directory and acting storage scope: each workspace and scope's claims live in their own entry and persist only to that scope's storage (inbound.direct), so one profile never reads or writes another's. An entry holds event dedupe keys (source:event_id) and claim states, no payloads.", "verification": "inbound/claims_tests.rs: each_workspace_keeps_its_own_claims, a_direct_path_event_is_skipped_after_a_restart" }, { From 084511f0f99a1d9cdb09f4b859bf9ef78868ad14 Mon Sep 17 00:00:00 2001 From: Ghost Scripter Date: Thu, 12 Nov 2026 12:49:45 +0530 Subject: [PATCH 6/6] fix(inbound): close the remaining triage-once gaps from re-review CodeRabbit re-review of 7663a314af: - After a handled claim is evicted, both take_direct and delivering consult inbound.direct for a key that is open again or unknown, so a repeated offer is not granted the direct path and its queued copy is still dropped. - Both recheck the claim after the storage lookup instead of answering from what they saw before it. - A handled claim the store could not take (unreadable) is held in memory, never evicted, and written once the store reads. - Concurrent offers of one event are counted (Open(n)): an offer whose first attempt was never sent no longer releases another pending offer, and goes through the claims when one is pending. - Webhook direct paths report a deferred triage as not handled, so the queued copy is delivered instead of dropped. - Each claims entry opens its repository under its own scope; Deliver derives the scope from its context's tenant, and a call with no scope gets claims of its own instead of a shared empty-scope bucket. Relates to #8154 Co-Authored-By: Claude Opus 5.5 --- crates/openhuman-core/src/inbound/claims.rs | 226 +++++++++++++----- .../src/inbound/claims_tests.rs | 80 +++++++ crates/openhuman-core/src/inbound/route.rs | 35 ++- .../openhuman-core/src/skills/webhooks/bus.rs | 27 ++- .../src/skills/webhooks/bus_tests.rs | 24 ++ 5 files changed, 313 insertions(+), 79 deletions(-) diff --git a/crates/openhuman-core/src/inbound/claims.rs b/crates/openhuman-core/src/inbound/claims.rs index 05ba11ba2e6..d634b5c320a 100644 --- a/crates/openhuman-core/src/inbound/claims.rs +++ b/crates/openhuman-core/src/inbound/claims.rs @@ -49,7 +49,7 @@ use crate::core::events::DomainEvent; use crate::core::runtime::DispatchCtx; use crate::storage::documents::Repo; use crate::storage::schema_support::key_of; -use crate::storage::DocumentStoreExt; +use crate::storage::{DocumentStoreExt, Scope}; /// The collection of events the direct path handled. pub const DIRECT: &str = "inbound.direct"; @@ -73,8 +73,8 @@ pub fn collection_specs() -> Vec { /// Where an event's claim stands. #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum Claim { - /// The offer is still waiting for the queues' answer. - Open, + /// This many offers are waiting for the queues' answer. + Open(u32), /// The queues delivered it: they own it. Delivered, /// The direct path is running it. @@ -106,6 +106,9 @@ struct Memory { claims: HashMap, /// The settled claims, oldest first, for eviction. settled: VecDeque, + /// Handled claims not recorded yet (the store was unreadable), with when + /// they were handled: written once it reads, never evicted meanwhile. + unrecorded: Vec<(String, i64)>, /// Whether a handled claim was evicted, so a miss may be in the store. evicted: bool, } @@ -126,6 +129,12 @@ impl Memory { } } } + + /// `key` was handled at `at_ms` but could not be recorded yet. + fn hold(&mut self, key: &str, at_ms: i64) { + self.claims.insert(key.to_owned(), Claim::Handled); + self.unrecorded.push((key.to_owned(), at_ms)); + } } /// Where the claims' records live. @@ -133,8 +142,8 @@ impl Memory { enum Store { /// Nowhere: the claims are memory only. None, - /// In this workspace's storage, not read yet. - Unread(PathBuf), + /// In this workspace's storage under this scope, not read yet. + Unread(PathBuf, Scope), /// In this repository, read into memory. Read(Repo), } @@ -162,7 +171,7 @@ impl std::fmt::Debug for Claims { } /// Claims by workspace directory and storage scope. -type ByWorkspace = HashMap<(PathBuf, String), Arc>; +type ByWorkspace = HashMap<(PathBuf, Scope), Arc>; /// Each workspace and storage scope's claims. static WORKSPACES: LazyLock> = LazyLock::new(Mutex::default); @@ -180,16 +189,34 @@ impl Claims { /// use and again after a failed read. #[must_use] pub fn of_workspace(workspace_dir: &Path, now_ms: i64) -> Arc { - let scope = crate::storage::current_scope() - .map(|scope| scope.as_str().to_owned()) - .unwrap_or_default(); + Self::of_scope(workspace_dir, crate::storage::current_scope(), now_ms) + } + + /// `workspace_dir`'s claims under `scope`. With no scope (SaaS without a + /// profile) they are this call's own, in memory only: no scope shares + /// another's claims. + fn of_scope( + workspace_dir: &Path, + scope: Result, + now_ms: i64, + ) -> Arc { + let scope = match scope { + Ok(scope) => scope, + Err(error) => { + tracing::debug!(error = %error, "[inbound::claims] no storage scope; claims of this call only"); + return Arc::new(Self::default()); + } + }; let claims = Arc::clone( WORKSPACES .lock() .unwrap_or_else(PoisonError::into_inner) - .entry((workspace_dir.to_path_buf(), scope)) + .entry((workspace_dir.to_path_buf(), scope.clone())) .or_insert_with(|| { - Arc::new(Self::with_store(Store::Unread(workspace_dir.to_path_buf()))) + Arc::new(Self::with_store(Store::Unread( + workspace_dir.to_path_buf(), + scope, + ))) }), ); claims.read(now_ms); @@ -211,22 +238,35 @@ impl Claims { self.memory.lock().unwrap_or_else(PoisonError::into_inner) } + /// The store; never taken while the memory is held. fn store(&self) -> std::sync::MutexGuard<'_, Store> { self.store.lock().unwrap_or_else(PoisonError::into_inner) } - /// Read the records into memory unless they were. The store stays locked - /// until they are, so no caller answers from a half-read memory. + /// Read the records into memory unless they were, then write the handled + /// claims that could not be recorded before. The store stays locked until + /// they are, so no caller answers from a half-read memory. fn read(&self, now_ms: i64) { let mut store = self.store(); - let Store::Unread(workspace_dir) = &*store else { + let Store::Unread(workspace_dir, scope) = &*store else { return; }; - let read = Repo::current_for(workspace_dir, DOMAIN, collection_specs) + let read = crate::storage::local::backend_for(workspace_dir) + .and_then(|backend| Repo::on(&backend, scope, DOMAIN, collection_specs)) .and_then(|repo| load(&repo, now_ms).map(|keys| (repo, keys))); match read { Ok((repo, keys)) => { self.remember(keys); + let unrecorded = std::mem::take(&mut self.memory().unrecorded); + for (key, at_ms) in unrecorded { + match record(&repo, &key, at_ms) { + Ok(()) => self.memory().settle(&key, Claim::Handled), + Err(error) => { + report_unrecorded(&error); + self.memory().unrecorded.push((key, at_ms)); + } + } + } *store = Store::Read(repo); } Err(error) => { @@ -245,35 +285,71 @@ impl Claims { fn repo(&self) -> Option { match &*self.store() { Store::Read(repo) => Some(repo.clone()), - Store::None | Store::Unread(_) => None, + Store::None | Store::Unread(..) => None, } } /// An offer of `key` is about to be sent. pub fn open(&self, key: &str) { - self.memory() - .claims - .entry(key.to_owned()) - .or_insert(Claim::Open); + let mut memory = self.memory(); + match memory.claims.get(key).copied() { + Some(Claim::Open(offers)) => { + memory + .claims + .insert(key.to_owned(), Claim::Open(offers + 1)); + } + None => { + memory.claims.insert(key.to_owned(), Claim::Open(1)); + } + Some(Claim::Delivered | Claim::Direct | Claim::Handled) => {} + } } - /// The queues answered the offer of `key`: they own the event, or - /// proved they never saw it. - pub fn close(&self, key: &str) { + /// The queues answered an offer of `key`: they own the event, or proved + /// they never saw this offer. `true` when no other offer of it is pending + /// and nothing claims it, so a direct path needs no claim. + pub fn close(&self, key: &str) -> bool { let mut memory = self.memory(); - if memory.claims.get(key) == Some(&Claim::Open) { - memory.claims.remove(key); + match memory.claims.get(key).copied() { + Some(Claim::Open(1)) => { + memory.claims.remove(key); + true + } + Some(Claim::Open(offers)) => { + memory + .claims + .insert(key.to_owned(), Claim::Open(offers - 1)); + false + } + Some(Claim::Delivered | Claim::Direct | Claim::Handled) => false, + None => true, } } /// Every attempt to offer `key` was ambiguous: take it for the direct /// path. `None` when the queues delivered it, or another offer has the - /// direct path running or done, so the caller must not run it. + /// direct path running or done (in memory or, once evicted, recorded), + /// so the caller must not run it. pub fn take_direct(self: &Arc, key: &str) -> Option { + let evicted = { + let memory = self.memory(); + match memory.claims.get(key) { + Some(Claim::Delivered | Claim::Direct | Claim::Handled) => return None, + // Open again after its handled claim was evicted, it may be + // recorded all the same. + Some(Claim::Open(_)) | None => memory.evicted, + } + }; + let recorded = evicted && self.recorded(key); + // Checked again: another offer or delivery may have moved it meanwhile. let mut memory = self.memory(); match memory.claims.get(key) { Some(Claim::Delivered | Claim::Direct | Claim::Handled) => None, - Some(Claim::Open) | None => { + Some(Claim::Open(_)) | None if recorded => { + memory.settle(key, Claim::Handled); + None + } + Some(Claim::Open(_)) | None => { memory.claims.insert(key.to_owned(), Claim::Direct); Some(DirectClaim { claims: Arc::clone(self), @@ -286,24 +362,36 @@ impl Claims { /// The queues deliver `key`. pub fn delivering(&self, key: &str) -> Delivery { + { + let mut memory = self.memory(); + match memory.claims.get(key) { + Some(Claim::Handled) => return Delivery::Skip, + Some(Claim::Direct) => return Delivery::Wait, + Some(Claim::Delivered) => return Delivery::Run, + // After an eviction an open or unknown key may be recorded. + Some(Claim::Open(_)) | None if memory.evicted => {} + Some(Claim::Open(_)) => { + memory.settle(key, Claim::Delivered); + return Delivery::Run; + } + None => return Delivery::Run, + } + } + let recorded = self.recorded(key); + // Checked again: an offer may have taken it during the lookup. let mut memory = self.memory(); match memory.claims.get(key) { Some(Claim::Handled) => Delivery::Skip, Some(Claim::Direct) => Delivery::Wait, - Some(Claim::Open) => { + Some(Claim::Delivered) => Delivery::Run, + Some(Claim::Open(_)) | None if recorded => { + memory.settle(key, Claim::Handled); + Delivery::Skip + } + Some(Claim::Open(_)) => { memory.settle(key, Claim::Delivered); Delivery::Run } - Some(Claim::Delivered) => Delivery::Run, - None if memory.evicted => { - drop(memory); - if self.recorded(key) { - self.memory().settle(key, Claim::Handled); - Delivery::Skip - } else { - Delivery::Run - } - } None => Delivery::Run, } } @@ -331,35 +419,33 @@ impl Claims { } /// Settle `key`'s direct-path claim: recorded at `now_ms` when the - /// direct path handled the event, released otherwise. + /// direct path handled the event, released otherwise. A record that + /// cannot be written yet is held in memory and written once the store + /// reads. fn finish(&self, key: &str, handled: bool, now_ms: i64) { { let mut memory = self.memory(); if memory.claims.get(key) != Some(&Claim::Direct) { return; } - if handled { - memory.settle(key, Claim::Handled); - } else { + if !handled { memory.claims.remove(key); + return; } } - if !handled { - return; - } - if let Some(repo) = self.repo() { - if let Err(error) = record(&repo, key, now_ms) { - // Still skipped in this process; only a restart before the - // queued copy is delivered could run it a second time. - let detail = - format!("[inbound::claims] could not record a direct-path event: {error:#}"); - crate::core::observability::report_error_or_expected( - detail.as_str(), - "inbound", - "record_direct", - &[], - ); - } + // Try an unreadable store again first. + self.read(now_ms); + let store = self.store().clone(); + match store { + Store::Read(repo) => match record(&repo, key, now_ms) { + Ok(()) => self.memory().settle(key, Claim::Handled), + Err(error) => { + report_unrecorded(&error); + self.memory().hold(key, now_ms); + } + }, + Store::Unread(..) => self.memory().hold(key, now_ms), + Store::None => self.memory().settle(key, Claim::Handled), } } @@ -378,7 +464,17 @@ impl Claims { } }, }; - Self::of_workspace(&workspace_dir, now_ms) + let scope = ctx + .tenant() + .map_err(|no_tenant| crate::storage::StorageError::invalid_input(no_tenant.to_string())) + .and_then(|tenant| { + crate::storage::scope_from( + tenant.profile.as_deref(), + tenant.agent.as_deref(), + crate::core::runtime::mode::is_saas(), + ) + }); + Self::of_scope(&workspace_dir, scope, now_ms) } /// What becomes of `turn`, which the queues deliver: delivered later @@ -466,6 +562,18 @@ impl Drop for DirectClaim { } } +/// A handled claim could not be recorded: still skipped in this process, but a +/// restart before the queued copy is delivered could run it a second time. +fn report_unrecorded(error: &anyhow::Error) { + let detail = format!("[inbound::claims] could not record a direct-path event: {error:#}"); + crate::core::observability::report_error_or_expected( + detail.as_str(), + "inbound", + "record_direct", + &[], + ); +} + /// The keys recorded within the TTL at `now_ms`; older records are deleted. fn load(repo: &Repo, now_ms: i64) -> anyhow::Result> { repo.run(|docs| async move { diff --git a/crates/openhuman-core/src/inbound/claims_tests.rs b/crates/openhuman-core/src/inbound/claims_tests.rs index 7e80465f370..0175f846e93 100644 --- a/crates/openhuman-core/src/inbound/claims_tests.rs +++ b/crates/openhuman-core/src/inbound/claims_tests.rs @@ -193,3 +193,83 @@ fn a_turn_waits_for_a_running_direct_path_and_drops_only_handled_events() { )); assert!(matches!(claims.sort(turn(Vec::new())), Sorted::Deliver(_))); } + +#[test] +fn an_evicted_handled_claim_is_not_taken_for_the_direct_path_again() { + let storage = storage(); + let claims = Arc::new(Claims::over(&storage, NOW_MS)); + claims + .take_direct("composio:slack:gone") + .unwrap() + .finish(true); + for n in 0..CAPACITY { + claims.open(&format!("composio:slack:f{n}")); + claims.delivering(&format!("composio:slack:f{n}")); + } + assert!(!claims.memory().claims.contains_key("composio:slack:gone")); + // A repeated ambiguous offer of it, after eviction. + claims.open("composio:slack:gone"); + assert!(claims.take_direct("composio:slack:gone").is_none()); +} + +#[test] +fn an_unsent_offer_does_not_release_another_pending_offer() { + // Offer A is still waiting; offer B of the same event was never sent. + let claims = claims(); + claims.open("composio:slack:p1"); + claims.open("composio:slack:p1"); + assert!(!claims.close("composio:slack:p1"), "A is still pending"); + // B goes through the claims, so A cannot take the direct path too. + let b = claims.take_direct("composio:slack:p1").unwrap(); + assert!(claims.take_direct("composio:slack:p1").is_none()); + b.finish(true); + // Alone, an unsent offer needs no claim. + claims.open("composio:slack:p2"); + assert!(claims.close("composio:slack:p2")); +} + +#[test] +fn a_handled_claim_the_store_could_not_take_is_written_once_it_reads() { + let workspace = tempfile::tempdir().unwrap(); + let unread = || { + Store::Unread( + workspace.path().to_path_buf(), + crate::storage::Scope::local(), + ) + }; + let claims = Claims::with_store(unread()); + // Handled while the store was unreadable: held in memory, unevictable. + claims.memory().hold("webhook:t1:held", NOW_MS); + claims.read(NOW_MS); + assert!(claims.memory().unrecorded.is_empty()); + // A new process over the same workspace finds it recorded. + let after = Claims::with_store(unread()); + after.read(NOW_MS + 1_000); + assert_eq!(after.delivering("webhook:t1:held"), Delivery::Skip); +} + +#[test] +fn claims_without_a_storage_scope_are_shared_with_no_one() { + let workspace = tempfile::tempdir().unwrap(); + let no_scope = || Err(crate::storage::StorageError::invalid_input("no profile")); + let first = Claims::of_scope(workspace.path(), no_scope(), NOW_MS); + first.take_direct("composio:slack:ns").unwrap().finish(true); + let second = Claims::of_scope(workspace.path(), no_scope(), NOW_MS); + assert_eq!(second.delivering("composio:slack:ns"), Delivery::Run); +} + +#[test] +fn an_evicted_handled_event_offered_again_is_still_dropped_on_delivery() { + let storage = storage(); + let claims = Arc::new(Claims::over(&storage, NOW_MS)); + claims + .take_direct("composio:slack:again") + .unwrap() + .finish(true); + for n in 0..CAPACITY { + claims.open(&format!("composio:slack:g{n}")); + claims.delivering(&format!("composio:slack:g{n}")); + } + claims.open("composio:slack:again"); + assert_eq!(claims.delivering("composio:slack:again"), Delivery::Skip); +} diff --git a/crates/openhuman-core/src/inbound/route.rs b/crates/openhuman-core/src/inbound/route.rs index c432f7b99ea..0dc306dd5d0 100644 --- a/crates/openhuman-core/src/inbound/route.rs +++ b/crates/openhuman-core/src/inbound/route.rs @@ -136,20 +136,35 @@ async fn offer_or_direct_with( let key = event.dedupe_key(); claims.open(&key); match hand_off(client, event, deadlines).await { + HandOff::Settled(Offered::Direct(why)) => { + // The queues never saw this offer. Alone, the direct path needs + // no claim; another offer of the event may have reached them, + // though, so then it goes through the claims like an ambiguous one. + if claims.close(&key) { + (Offered::Direct(why), None) + } else { + take_direct(claims, &key, why) + } + } HandOff::Settled(offered) => { claims.close(&key); (offered, None) } - HandOff::Ambiguous(why) => match claims.take_direct(&key) { - Some(claim) => (Offered::Direct(why), Some(claim)), - None => { - tracing::info!( - key = %key, - "[inbound] ingest never answered, but the queues or another offer have the event; not taking the direct path" - ); - (Offered::Queued(Disposition::Duplicate), None) - } - }, + HandOff::Ambiguous(why) => take_direct(claims, &key, why), + } +} + +/// The direct path for `key`, when the claims grant it. +fn take_direct(claims: &Arc, key: &str, why: String) -> (Offered, Option) { + match claims.take_direct(key) { + Some(claim) => (Offered::Direct(why), Some(claim)), + None => { + tracing::info!( + key = %key, + "[inbound] the queues or another offer have the event; not taking the direct path" + ); + (Offered::Queued(Disposition::Duplicate), None) + } } } diff --git a/crates/openhuman-core/src/skills/webhooks/bus.rs b/crates/openhuman-core/src/skills/webhooks/bus.rs index dcb62e9a367..1d253657250 100644 --- a/crates/openhuman-core/src/skills/webhooks/bus.rs +++ b/crates/openhuman-core/src/skills/webhooks/bus.rs @@ -331,10 +331,10 @@ pub(super) fn triage_agent_directly( }) .await; if let Some(on_handled) = on_handled { - on_handled(matches!(result, Ok(Ok(_)))); + on_handled(matches!(result, Ok(Ok((_, true))))); } let (resp, err) = match result { - Ok(Ok(output)) => (build_agent_response(&corr, 200, &output), None), + Ok(Ok((output, _))) => (build_agent_response(&corr, 200, &output), None), Ok(Err(e)) => { crate::core::observability::report_error( e.as_str(), @@ -400,12 +400,13 @@ fn decode_webhook_body(base64_body: &str) -> Result { } /// Run the triage pipeline for a trigger envelope and return the -/// human-readable decision summary on success. +/// human-readable decision summary on success, with whether it handled the +/// webhook (a decision applied, or a terminal triage; not a deferral). async fn run_agent_trigger( ctx: &crate::core::runtime::DispatchCtx, envelope: &crate::triage::TriggerEnvelope, runner: &dyn crate::triage::TriageRunner, -) -> Result { +) -> Result<(String, bool), String> { let outcome = runner .run(ctx, envelope) .await @@ -421,18 +422,24 @@ async fn run_agent_trigger( .await .map_err(|e| format!("apply_decision failed: {e}"))?; - Ok(format!( - "Triage decision: {} (agent: {:?})", - run.decision.action.as_str(), - run.decision.target_agent + Ok(( + format!( + "Triage decision: {} (agent: {:?})", + run.decision.action.as_str(), + run.decision.target_agent + ), + true, )) } crate::triage::TriageOutcome::Deferred { defer_until_ms, reason, - } => Ok(format!("Triage deferred until {defer_until_ms}: {reason}")), + } => Ok(( + format!("Triage deferred until {defer_until_ms}: {reason}"), + false, + )), crate::triage::TriageOutcome::Terminal { reason } => { - Ok(format!("Triage reached terminal state: {reason}")) + Ok((format!("Triage reached terminal state: {reason}"), true)) } } } diff --git a/crates/openhuman-core/src/skills/webhooks/bus_tests.rs b/crates/openhuman-core/src/skills/webhooks/bus_tests.rs index 13260efdc46..c33b9a25d33 100644 --- a/crates/openhuman-core/src/skills/webhooks/bus_tests.rs +++ b/crates/openhuman-core/src/skills/webhooks/bus_tests.rs @@ -233,4 +233,28 @@ mod inbound { assert_eq!(triage.applied(), vec![LABEL.to_owned()]); } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn a_deferred_direct_webhook_is_reported_as_not_handled() { + // So a copy the queues hold is delivered, not dropped as handled. + for (step, expected) in [ + (deferred(400), false), + (decision(TriageAction::React), true), + ] { + let triage = ScriptedTriage::new([step]); + let (sender, handled) = tokio::sync::oneshot::channel(); + triage_agent_directly( + DispatchCtx::host_default(), + request(), + "corr-reported".to_owned(), + triage.clone() as Arc, + Some(Box::new(move |handled| { + let _ = sender.send(handled); + })), + ) + .await + .unwrap(); + assert_eq!(handled.await.unwrap(), expected); + } + } }