diff --git a/.github/workflows/test-reusable.yml b/.github/workflows/test-reusable.yml index 92cf19ed8ec..d8ab9c7e45d 100644 --- a/.github/workflows/test-reusable.yml +++ b/.github/workflows/test-reusable.yml @@ -246,6 +246,10 @@ 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 + 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/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..d634b5c320a --- /dev/null +++ b/crates/openhuman-core/src/inbound/claims.rs @@ -0,0 +1,613 @@ +//! 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 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 handled, and when | +//! +//! 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 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, PoisonError}; + +use serde::{Deserialize, Serialize}; +use tinystoragedrivers::{CollectionSpec, ErrorKind, Precondition, Query}; + +use tinyeventqueues_bus::Turn; + +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, Scope}; + +/// The collection of events the direct path handled. +pub const DIRECT: &str = "inbound.direct"; +const DOMAIN: &str = "inbound::claims"; + +/// 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 handled 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 { + /// 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. + Direct, + /// The direct path handled it. + Handled, +} + +/// 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, + recorded_ms: i64, +} + +#[derive(Debug, Default)] +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, +} + +impl Memory { + 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.settled.len() > CAPACITY { + if let Some(oldest) = self.settled.pop_front() { + if self.claims.remove(&oldest) == Some(Claim::Handled) { + self.evicted = true; + } + } + } + } + + /// `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. +#[derive(Clone)] +enum Store { + /// Nowhere: the claims are memory only. + None, + /// In this workspace's storage under this scope, not read yet. + Unread(PathBuf, Scope), + /// In this repository, read into memory. + Read(Repo), +} + +/// The claims of one workspace and storage scope. +pub struct Claims { + memory: Mutex, + 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("read", &read) + .finish_non_exhaustive() + } +} + +/// Claims by workspace directory and storage scope. +type ByWorkspace = HashMap<(PathBuf, Scope), Arc>; + +/// Each workspace and storage scope's claims. +static WORKSPACES: LazyLock> = LazyLock::new(Mutex::default); + +impl Claims { + fn with_store(store: Store) -> Self { + Self { + memory: Mutex::new(Memory::default()), + store: Mutex::new(store), + } + } + + /// 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 { + 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.clone())) + .or_insert_with(|| { + Arc::new(Self::with_store(Store::Unread( + workspace_dir.to_path_buf(), + scope, + ))) + }), + ); + claims.read(now_ms); + claims + } + + /// Claims over `scoped` storage, read at `now_ms` (tests). + #[cfg(test)] + pub(crate) fn over(scoped: &crate::storage::Storage, now_ms: i64) -> Self { + 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 + } + + fn memory(&self) -> std::sync::MutexGuard<'_, Memory> { + 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, 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, scope) = &*store else { + return; + }; + 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) => { + tracing::warn!(error = %error, "[inbound::claims] records unreadable; answering from memory and reading again next time"); + } + } + } + + fn remember(&self, keys: Vec) { + let mut memory = self.memory(); + for key in keys { + memory.settle(&key, Claim::Handled); + } + } + + fn repo(&self) -> Option { + match &*self.store() { + Store::Read(repo) => Some(repo.clone()), + Store::None | Store::Unread(..) => None, + } + } + + /// An offer of `key` is about to be sent. + pub fn open(&self, key: &str) { + 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 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(); + 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 (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 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), + 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) => 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::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 + } + 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. 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.claims.remove(key); + return; + } + } + // 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), + } + } + + /// 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 + } + }, + }; + 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 + /// 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 deliveries.next() != Some(Delivery::Skip) { + 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 + }); + 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); + } + } +} + +/// 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 { + 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..0175f846e93 --- /dev/null +++ b/crates/openhuman-core/src/inbound/claims_tests.rs @@ -0,0 +1,275 @@ +//! 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()) +} + +fn claims() -> Arc { + Arc::new(Claims::default()) +} + +#[test] +fn a_running_direct_path_holds_its_delivery_and_a_handled_one_drops_it() { + let claims = claims(); + claims.open("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_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(); + 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. + 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() { + assert_eq!(claims().delivering("webhook:t1:c1"), Delivery::Run); +} + +#[test] +fn a_handled_direct_path_event_is_skipped_after_a_restart() { + let storage = storage(); + 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_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(); + 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); + 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 settled_claims_are_bounded_in_memory() { + let claims = claims(); + for n in 0..=CAPACITY { + claims.open(&format!("composio:slack:b{n}")); + claims.delivering(&format!("composio:slack:b{n}")); + } + 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()); + 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() + }; + 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(_))); +} + +#[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/deliver.rs b/crates/openhuman-core/src/inbound/deliver.rs index 539a7b7badc..2e2d54321e0 100644 --- a/crates/openhuman-core/src/inbound/deliver.rs +++ b/crates/openhuman-core/src/inbound/deliver.rs @@ -41,6 +41,13 @@ //! 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 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}; @@ -51,6 +58,10 @@ use tinyeventqueues_bus::{ DeliverStatus, InboundEvent, Lane, SalienceClass, Turn, }; +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; @@ -159,6 +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 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 { @@ -179,8 +194,13 @@ 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()); + // Given its settings, it reads no configuration: its claims are its + // own unless given some (`Self::with_claims`). + deliverer.claims = Some(Arc::new(Claims::default())); + deliverer } /// A deliverer whose triage timeout is `[inbound] triage_timeout_ms`, read @@ -209,6 +229,7 @@ impl Deliverer { accepted: Mutex::new(Accepted::default()), inbound: tokio::sync::OnceCell::new(), pinned: tokio::sync::OnceCell::new(), + claims: None, } } @@ -227,6 +248,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 = Some(claims); + self + } + /// Use `now_ms` for the clock (tests). #[must_use] pub fn with_clock(mut self, now_ms: fn() -> i64) -> Self { @@ -396,6 +424,14 @@ impl Deliverer { } } + /// 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, + } + } + fn classified(&self) -> std::sync::MutexGuard<'_, Classified> { self.classified .lock() @@ -464,6 +500,21 @@ impl Deliverer { ); return DeliverResponse::new(DeliverStatus::Accepted); } + let turn_id = turn.turn_id.clone(); + 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()); let status = self.deliver_pinned(&turn, &name, &source, remaining).await; 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 72537c9088b..0c0d3961147 100644 --- a/crates/openhuman-core/src/inbound/deliver_tests.rs +++ b/crates/openhuman-core/src/inbound/deliver_tests.rs @@ -684,3 +684,6 @@ async fn a_pinned_source_in_a_mixed_digest_still_runs_its_agent() { #[path = "deliver_digest_tests.rs"] mod digest; + +#[path = "deliver_direct_tests.rs"] +mod direct; 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/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..0dc306dd5d0 100644 --- a/crates/openhuman-core/src/inbound/route.rs +++ b/crates/openhuman-core/src/inbound/route.rs @@ -15,11 +15,14 @@ //! 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::sync::Arc; use std::time::Duration; use tinybus::module::{ModuleCallError, ModuleClient}; @@ -30,6 +33,8 @@ use crate::core::bus::BUS; use crate::core::events::DomainEvent; use crate::modules::event_queues; +use super::claims::{Claims, DirectClaim}; + /// What became of an offered event. #[derive(Debug, Clone, PartialEq, Eq)] pub enum Offered { @@ -80,16 +85,95 @@ 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 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, Option) { + if !super::active(config) { + return ( + Offered::Direct("inbound event queues inactive".to_owned()), + None, + ); + } + 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: &Arc, + deadlines: &[Duration], +) -> (Offered, Option) { + 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) => 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) + } + } +} + +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; } @@ -98,14 +182,26 @@ pub async fn offer(config: &Config, client: &ModuleClient, event: InboundEvent) answered = Some(response); break; } - Attempt::Unsent(error) => { + Attempt::Unsent(error) if n == 0 => { tracing::info!( source = %source, event_id = %event_id, 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::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!( @@ -124,13 +220,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 +251,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..e0613e7a5fc 100644 --- a/crates/openhuman-core/src/inbound/route_tests.rs +++ b/crates/openhuman-core/src/inbound/route_tests.rs @@ -5,9 +5,10 @@ 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::TriggerEnvelope; +use crate::triage::{TriageOutcome, TriggerEnvelope}; fn event(uuid: &str) -> InboundEvent { let envelope = TriggerEnvelope::from_composio("slack", "SLACK_MESSAGE", "", uuid, json!({})); @@ -36,9 +37,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 +53,172 @@ 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 (ambiguous, _bus) = ambiguous_client().await; + 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 + .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 (ambiguous, _bus) = ambiguous_client().await; + 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 + ); + 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 + // and a later offer of the same event is delivered by the queues. + 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, claim) = offer_or_direct(&config, &client, event("u7")).await; + assert!(matches!(offered, Offered::Direct(ref why) if why.contains("ingest failed"))); + 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)] +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(&config, &ambiguous, event("u8")).await; + assert!(!offered.is_queued()); + 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)] +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, 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(); + 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] +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, claim) = offer_or_direct(&config, &client, event("u10")).await; + assert!(matches!(offered, Offered::Direct(ref why) if why.contains("inactive"))); + 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. +fn config_in(workspace: &tempfile::TempDir) -> crate::config::Config { + let mut config = active_config(); + config.workspace_dir = workspace.path().to_path_buf(); + config +} + #[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..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(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 a3df80a7b89..1d253657250 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(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,8 +330,11 @@ 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((_, 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(), @@ -380,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 @@ -401,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 534ac10f14f..c33b9a25d33 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(); @@ -232,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); + } + } } 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/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 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` | | | | diff --git a/scripts/__tests__/test-module-installation.test.mjs b/scripts/__tests__/test-module-installation.test.mjs index 4cde2fe38bb..6a8439767a2 100644 --- a/scripts/__tests__/test-module-installation.test.mjs +++ b/scripts/__tests__/test-module-installation.test.mjs @@ -601,6 +601,10 @@ 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", + "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 42161a85442..74d03e4b3c6 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 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" + }, { "file": "crates/openhuman-core/src/inference/provider/factory/routing.rs", "scope": "",