The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
feat(composio): add pass failure handling for composio runs
Steven Enamakeladea66435c73
diff --git a/crates/openhuman-core/src/integrations/composio/contract/runs.rs b/crates/openhuman-core/src/integrations/composio/contract/runs.rsdeleted file mode 100644index 284c39fd23..0000000000--- a/crates/openhuman-core/src/integrations/composio/contract/runs.rs+++ /dev/null@@ -1,65 +0,0 @@-//! What one `composio_sync` run was for, and what it reported.-//!-//! [`SyncReason`] is the run's trigger, passed to the connector module;-//! [`SyncOutcome`] is the `openhuman.composio_sync` reply. Both are serde-//! shapes with no behaviour.--use serde::{Deserialize, Serialize};--/// Reason a sync was triggered. Providers use this to decide whether to do a-/// full backfill or an incremental pull.-///-/// The serde form is `snake_case` and is mirrored into audit rows, so the-/// variant names are a compatibility surface.-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]-#[serde(rename_all = "snake_case")]-pub enum SyncReason {- /// First sync immediately after an OAuth handoff completes.- ConnectionCreated,- /// Periodic background sync from the scheduler.- Periodic,- /// Explicit user-driven sync from RPC or the UI.- Manual,-}--impl SyncReason {- /// Stable lowercase tag, matching the serde representation.- ///- /// Callers that stamp the reason into a log line or an audit row want the- /// string without a serde round-trip; this is that string, and the pin test- /// holds the two forms equal.- pub fn as_str(&self) -> &'static str {- match self {- SyncReason::ConnectionCreated => "connection_created",- SyncReason::Periodic => "periodic",- SyncReason::Manual => "manual",- }- }-}--/// The `openhuman.composio_sync` reply.-#[derive(Debug, Clone, Default, Serialize, Deserialize)]-pub struct SyncOutcome {- /// Composio toolkit slug the run covered.- pub toolkit: String,- /// The connection that was synced; `None` for toolkit-wide runs.- pub connection_id: Option<String>,- /// Why the run happened — normally a [`SyncReason::as_str`] tag, kept as a- /// `String` because a caller may report a reason the enum does not model.- pub reason: String,- /// How many items the run ingested.- pub items_ingested: usize,- /// Wall-clock start, epoch milliseconds.- pub started_at_ms: u64,- /// Wall-clock finish, epoch milliseconds.- pub finished_at_ms: u64,- /// One-line human summary for the status panel.- pub summary: String,- /// Provider-specific extras (raw JSON object).- #[serde(default)]- pub details: serde_json::Value,-}--#[cfg(test)]-#[path = "runs_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/integrations/composio/contract/runs_tests.rs b/crates/openhuman-core/src/integrations/composio/contract/runs_tests.rsdeleted file mode 100644index b582843fc3..0000000000--- a/crates/openhuman-core/src/integrations/composio/contract/runs_tests.rs+++ /dev/null@@ -1,68 +0,0 @@-//! Tests for the sync-run report vocabulary — the pure-data half.-//!-//! What is pinned here is what two separately compiled processes have to agree-//! on: the `snake_case` reason tags and the reply shape.--#![allow(clippy::expect_used, clippy::unwrap_used, clippy::panic)]--use super::{SyncOutcome, SyncReason};--#[test]-fn every_sync_reason_tag_matches_its_serde_form() {- for reason in [- SyncReason::ConnectionCreated,- SyncReason::Periodic,- SyncReason::Manual,- ] {- let json = serde_json::to_string(&reason).expect("serialize");- assert_eq!(- json,- format!("\"{}\"", reason.as_str()),- "as_str and the serde form disagree for {reason:?}"- );- let back: SyncReason = serde_json::from_str(&json).expect("deserialize");- assert_eq!(back, reason);- }-}--#[test]-fn sync_reason_tags_are_the_stable_strings() {- assert_eq!(SyncReason::ConnectionCreated.as_str(), "connection_created");- assert_eq!(SyncReason::Periodic.as_str(), "periodic");- assert_eq!(SyncReason::Manual.as_str(), "manual");-}--#[test]-fn an_outcome_round_trips_with_its_open_details_object() {- let outcome = SyncOutcome {- toolkit: "gmail".into(),- connection_id: Some("conn-1".into()),- reason: SyncReason::Periodic.as_str().to_string(),- items_ingested: 12,- started_at_ms: 5,- finished_at_ms: 9,- summary: "12 messages".into(),- details: serde_json::json!({ "pages": 3 }),- };- let json = serde_json::to_string(&outcome).expect("serialize");- let back: SyncOutcome = serde_json::from_str(&json).expect("deserialize");-- assert_eq!(back.toolkit, "gmail");- assert_eq!(back.connection_id.as_deref(), Some("conn-1"));- assert_eq!(back.reason, "periodic");- assert_eq!(back.items_ingested, 12);- assert_eq!(back.summary, "12 messages");- assert_eq!(back.details["pages"], 3);-}--#[test]-fn an_outcome_decodes_when_details_is_absent() {- // `details` is `#[serde(default)]`, so an older peer that never wrote the- // field still decodes rather than failing the whole frame.- let back: SyncOutcome = serde_json::from_str(- r#"{"toolkit":"slack","connection_id":null,"reason":"manual",- "items_ingested":0,"started_at_ms":0,"finished_at_ms":0,"summary":""}"#,- )- .expect("deserialize without details");- assert!(back.details.is_null());-}diff --git a/crates/openhuman-core/src/integrations/composio/ops/pass_failure.rs b/crates/openhuman-core/src/integrations/composio/ops/pass_failure.rsdeleted file mode 100644index 275ead1b10..0000000000--- a/crates/openhuman-core/src/integrations/composio/ops/pass_failure.rs+++ /dev/null@@ -1,111 +0,0 @@-//! When a connector sync pass has failed, and how long a `composio_sync` run-//! waits before asking again (openhuman#6255).-//!-//! The connector module reports a page it could not read as-//! [`SyncStage::Failed`]: it keeps the pages it had already read, puts the-//! reason in the response's `message`, and leaves the batch incomplete. An-//! incomplete batch otherwise means "call again", so a connector that failed on-//! its first page was asked again at once, up to fifty times a click, with the-//! reason logged nowhere. These two decisions end that: a failed pass is a-//! failure, and the only retries are a few spaced ones.--use std::time::Duration;--use tinyconnectors_bus::records::{ConnectorSyncResponse, SyncStage};--/// Longest failure reason kept, in characters.-///-/// A provider error can carry a whole response body. The reason is shown on-/// the source row and written to the log, so it is cut rather than kept whole.-pub(crate) const MAX_REASON_CHARS: usize = 300;--/// Attempts a `composio_sync` run makes at a pass the connector keeps failing:-/// the first try and two retries.-pub(crate) const MAX_FAILED_ATTEMPTS: u32 = 3;--/// Why a pass failed, or `None` for a pass that did not.-///-/// Only the connector's own failed stage counts. Host-side errors (the module-/// being unavailable, a timed-out call, an ingest error) are already `Err` at-/// the call site and are not retried: repeating them cannot help, and a timed-/// out call may still be running.-///-/// The reason is the connector's message on one line, cut to-/// [`MAX_REASON_CHARS`]. A failure that gave no message is still named, so a-/// row never reads "Sync failed:" with nothing after it.-pub(crate) fn failure_reason(- stage: SyncStage,- message: Option<&str>,- toolkit: &str,-) -> Option<String> {- if stage != SyncStage::Failed {- return None;- }- Some(- message- .map(one_line)- .filter(|message| !message.is_empty())- .map(clip)- .unwrap_or_else(|| format!("the {toolkit} connector stopped without saying why")),- )-}--/// The failure the connector reported for one sync pass, logged once.-///-/// See [`failure_reason`] for what counts. Logged here, where a pass's response-/// is read, so every caller gets the same line, with how far the pass got-/// before it stopped.-pub(crate) fn pass_failure(- response: &ConnectorSyncResponse,- toolkit: &str,- connection_id: &str,-) -> Option<String> {- let reason = failure_reason(response.stage, response.message.as_deref(), toolkit)?;- tracing::warn!(- toolkit = %toolkit,- connection_id = %connection_id,- pages_read = response.pages_read,- records = response.batch.records.len(),- reason = %reason,- "[composio] connector sync pass failed"- );- Some(reason)-}--/// `message` with every run of whitespace, line breaks included, made one-/// space. A provider error can span lines (the complaint, then the fields it-/// wanted), and the reason is shown as one row and logged as one line.-fn one_line(message: &str) -> String {- message.split_whitespace().collect::<Vec<_>>().join(" ")-}--/// `message` cut to at most [`MAX_REASON_CHARS`] characters, the ellipsis that-/// marks the cut included, on a character boundary.-fn clip(message: String) -> String {- if message.chars().count() <= MAX_REASON_CHARS {- return message;- }- let cut = message- .char_indices()- .nth(MAX_REASON_CHARS - 1)- .map_or(message.len(), |(index, _)| index);- format!("{}…", message[..cut].trim_end())-}--/// How long to wait before asking again after `failed_attempts` consecutive-/// failed passes, or `None` once the run should give up.-///-/// Five seconds after the first failure, ten after the second, and no third-/// retry: a transient provider error still recovers, and a connector that is-/// broken shows its failure within about fifteen seconds instead of holding-/// the row on "Syncing".-pub(crate) fn retry_delay(failed_attempts: u32) -> Option<Duration> {- if failed_attempts == 0 || failed_attempts >= MAX_FAILED_ATTEMPTS {- return None;- }- Some(Duration::from_secs(5 * 2_u64.pow(failed_attempts - 1)))-}--#[cfg(test)]-#[path = "pass_failure_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/integrations/composio/ops/pass_failure_tests.rs b/crates/openhuman-core/src/integrations/composio/ops/pass_failure_tests.rsdeleted file mode 100644index 06abcb836d..0000000000--- a/crates/openhuman-core/src/integrations/composio/ops/pass_failure_tests.rs+++ /dev/null@@ -1,143 +0,0 @@-//! When a connector pass counts as failed, and the Sources-row retry schedule-//! (openhuman#6255).--use super::*;--#[test]-fn only_the_connectors_failed_stage_is_a_failure() {- for stage in [- SyncStage::Requested,- SyncStage::Fetching,- SyncStage::Stored,- SyncStage::Ingesting,- SyncStage::Completed,- ] {- assert_eq!(- failure_reason(- stage,- Some("today's provider request budget is spent"),- "gmail"- ),- None,- "{stage:?} is not a failure, whatever its message says"- );- }-}--#[test]-fn a_failure_carries_the_connectors_reason_trimmed() {- assert_eq!(- failure_reason(- SyncStage::Failed,- Some(" action GITHUB_SEARCH_ISSUES_AND_PULL_REQUESTS failed "),- "github"- )- .as_deref(),- Some("action GITHUB_SEARCH_ISSUES_AND_PULL_REQUESTS failed")- );-}--#[test]-fn a_reason_that_spans_lines_is_kept_on_one_line() {- // The shape of the GitHub error seen on staging (tinyhumansai/tinyconnectors#20).- assert_eq!(- failure_reason(- SyncStage::Failed,- Some("`GITHUB_SEARCH_ISSUES_AND_PULL_REQUESTS` failed: Invalid request data provided\n- Following fields are missing: {'q'}\n"),- "github"- )- .as_deref(),- Some("`GITHUB_SEARCH_ISSUES_AND_PULL_REQUESTS` failed: Invalid request data provided - Following fields are missing: {'q'}")- );- assert_eq!(- failure_reason(- SyncStage::Failed,- Some("rate limited\r\n\t retry later"),- "notion"- )- .as_deref(),- Some("rate limited retry later")- );-}--#[test]-fn a_failure_without_a_reason_is_still_named() {- for message in [None, Some(""), Some(" "), Some("\n\t")] {- assert_eq!(- failure_reason(SyncStage::Failed, message, "github").as_deref(),- Some("the github connector stopped without saying why"),- "message {message:?}"- );- }-}--#[test]-fn a_long_reason_is_cut_to_the_limit() {- let long = "x".repeat(MAX_REASON_CHARS + 50);- let reason = failure_reason(SyncStage::Failed, Some(&long), "notion").expect("a failure");- assert_eq!(- reason.chars().count(),- MAX_REASON_CHARS,- "the ellipsis counts toward the limit"- );- assert!(reason.ends_with('…'));-- let one_over = "z".repeat(MAX_REASON_CHARS + 1);- assert_eq!(- failure_reason(SyncStage::Failed, Some(&one_over), "notion").map(|r| r.chars().count()),- Some(MAX_REASON_CHARS),- "one character over is cut, not kept"- );-- let exact = "y".repeat(MAX_REASON_CHARS);- assert_eq!(- failure_reason(SyncStage::Failed, Some(&exact), "notion"),- Some(exact),- "a reason at the limit is kept whole"- );-}--#[test]-fn a_reason_is_cut_on_a_character_boundary() {- // Multi-byte characters: a byte-offset cut would panic or split one.- let long = "é".repeat(MAX_REASON_CHARS + 10);- let reason = failure_reason(SyncStage::Failed, Some(&long), "slack").expect("a failure");- assert_eq!(reason.chars().count(), MAX_REASON_CHARS);- assert!(reason.starts_with('é') && reason.ends_with('…'));-}--#[test]-fn the_retry_schedule_waits_five_then_ten_seconds_then_gives_up() {- assert_eq!(retry_delay(0), None, "nothing has failed yet");- assert_eq!(retry_delay(1), Some(Duration::from_secs(5)));- assert_eq!(retry_delay(2), Some(Duration::from_secs(10)));- assert_eq!(- retry_delay(MAX_FAILED_ATTEMPTS),- None,- "the third failure ends the run"- );- assert_eq!(retry_delay(MAX_FAILED_ATTEMPTS + 7), None);-}--#[test]-fn a_failed_response_names_its_failure() {- let response = ConnectorSyncResponse {- stage: SyncStage::Failed,- message: Some("GITHUB_SEARCH_ISSUES_AND_PULL_REQUESTS failed".to_string()),- ..ConnectorSyncResponse::default()- };- assert_eq!(- pass_failure(&response, "github", "ca_1").as_deref(),- Some("GITHUB_SEARCH_ISSUES_AND_PULL_REQUESTS failed")- );-}--#[test]-fn a_response_that_stopped_short_without_failing_is_not_a_failure() {- let response = ConnectorSyncResponse {- stage: SyncStage::Completed,- message: Some("today's provider request budget is spent".to_string()),- ..ConnectorSyncResponse::default()- };- assert_eq!(pass_failure(&response, "gmail", "ca_1"), None);-}diff --git a/crates/openhuman-core/src/integrations/composio/ops/sync.rs b/crates/openhuman-core/src/integrations/composio/ops/sync.rsdeleted file mode 100644index bee540c8cf..0000000000--- a/crates/openhuman-core/src/integrations/composio/ops/sync.rs+++ /dev/null@@ -1,299 +0,0 @@-//! Syncing a connected account into memory.-//!-//! Reading the account is the connector module's job — it holds the-//! credential, the provider registry and the paging cursors. Storing what it-//! read is memory's: each pass hands the batch to-//! [`crate::memory::sources::composio::store_records`], which turns every-//! record into a document on the bound engine. Neither half knows about the-//! other: the module never reaches memory, and memory never sees a Composio-//! credential.-//!-//! Two callers drive passes: `openhuman.composio_sync` (one connection, on-//! demand, in the background — see [`composio_sync`]) and memory's own-//! scheduled Composio sources (`memory::sources::composio::sync_toolkit`),-//! which call [`run_sync_pass`] directly.--use crate::config::Config;-use crate::core::Outcome;-use crate::memory::engine::BoundEngine;-use crate::memory::sources::composio::{is_disconnected, source_id_for_toolkit, store_records};--use super::super::module_client::{self as connectors, methods};-use super::super::providers::{SyncOutcome, SyncReason};-use super::connections::resolve_toolkit_for_connection;-use super::error_utils::{report_composio_op_error, OpResult};-use super::pass_failure::{pass_failure, retry_delay};-use tinyconnectors_bus::records::{ConnectorSyncRequest, ConnectorSyncResponse};--/// Per-pass item budget handed to the connector's `Sync` member.-///-/// One pass is one budgeted slice of the account; [`MAX_PASSES`] bounds a-/// `composio_sync` run at 10k items per click.-pub const SYNC_PASS_MAX_ITEMS: usize = 200;--/// Most passes one `composio_sync` run makes before it stops; the next run-/// resumes from the module's cursor.-const MAX_PASSES: usize = 50;--/// What one [`run_sync_pass`] call did.-#[derive(Debug, Clone, Default)]-pub struct SyncPassOutcome {- /// Records the module returned in this pass.- pub records_read: usize,- /// Of those, how many memory stored (empty records are skipped).- pub written: u64,- /// Whether the module has more to read — the caller decides whether to- /// call again.- pub more_pending: bool,- /// Why the connector stopped this pass on an error (openhuman#6255). The- /// counts above still stand; the caller ends or retries the run.- pub failure: Option<String>,-}--/// `openhuman.composio_sync` — read one connected account into memory.-///-/// Returns as soon as the run is *started*: a full sync is minutes of paging,-/// and the RPC caller is a UI button. The engine is resolved up front so-/// memory being off is an error the caller sees, not a log line in a detached-/// task. Items are filed under the toolkit's configured Composio source, or-/// `composio:<toolkit>` when none is configured.-pub async fn composio_sync(- config: &Config,- connection_id: &str,- reason: Option<String>,-) -> OpResult<Outcome<SyncOutcome>> {- let reason = parse_sync_reason(reason.as_deref())?;- tracing::debug!(- connection_id = %connection_id,- reason = reason.as_str(),- "[composio] rpc sync (spawned)"- );- let toolkit = resolve_toolkit_for_connection(config, connection_id).await?;- let bound = crate::memory::engine::resolve(config)- .engine()- .map_err(String::from)?;- let source_id = source_id_for_toolkit(config, &toolkit);-- let started_at_ms = u64::try_from(- std::time::SystemTime::now()- .duration_since(std::time::UNIX_EPOCH)- .map(|d| d.as_millis())- .unwrap_or(0),- )- .unwrap_or(u64::MAX);-- let run = SyncRun {- config: config.clone(),- bound,- toolkit: toolkit.clone(),- connection_id: connection_id.to_string(),- source_id,- reason: reason.as_str().to_string(),- };- tokio::spawn(run.drive());-- let summary = format!("composio: {toolkit} sync started (background)");- let outcome = SyncOutcome {- toolkit,- connection_id: Some(connection_id.to_string()),- reason: reason.as_str().to_string(),- items_ingested: 0,- started_at_ms,- finished_at_ms: 0,- summary: summary.clone(),- details: serde_json::json!({ "status": "started" }),- };- Ok(Outcome::new(outcome, vec![summary]))-}--/// One background `composio_sync` run.-struct SyncRun {- config: Config,- bound: BoundEngine,- toolkit: String,- connection_id: String,- source_id: String,- reason: String,-}--impl SyncRun {- /// Runs passes until the connector reports the end, a pass reads nothing,- /// or [`MAX_PASSES`] is reached. A pass the connector reports as failed is- /// retried on [`retry_delay`]'s schedule, then ends the run.- async fn drive(self) {- let started = std::time::Instant::now();- let mut total_written: u64 = 0;- let mut passes = 0usize;- let mut failed_attempts = 0u32;- let outcome: Result<bool, String> = loop {- passes += 1;- let pass = match run_sync_pass(- &self.config,- &self.bound,- &self.toolkit,- &self.connection_id,- &self.source_id,- &self.reason,- SYNC_PASS_MAX_ITEMS,- )- .await- {- Ok(pass) => pass,- Err(error) => break Err(error),- };- total_written = total_written.saturating_add(pass.written);- if let Some(reason) = pass.failure {- failed_attempts += 1;- let Some(delay) = retry_delay(failed_attempts) else {- break Err(reason);- };- tracing::info!(- toolkit = %self.toolkit,- connection_id = %self.connection_id,- attempt = failed_attempts,- retry_in_secs = delay.as_secs(),- "[composio] connector sync pass failed; retrying"- );- tokio::time::sleep(delay).await;- continue;- }- failed_attempts = 0;- tracing::debug!(- toolkit = %self.toolkit,- connection_id = %self.connection_id,- pass = passes,- records_read = pass.records_read,- written = pass.written,- more_pending = pass.more_pending,- "[composio] background sync pass ok"- );- if !pass.more_pending || pass.records_read == 0 || passes >= MAX_PASSES {- break Ok(pass.more_pending);- }- };- match outcome {- Ok(more_pending) => tracing::info!(- toolkit = %self.toolkit,- connection_id = %self.connection_id,- passes,- written = total_written,- more_pending,- elapsed_ms = u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX),- "[composio] background sync complete"- ),- Err(error) => {- report_composio_op_error("sync", &anyhow::anyhow!("{error}"));- tracing::warn!(- toolkit = %self.toolkit,- connection_id = %self.connection_id,- written = total_written,- error = %error,- "[composio] background sync failed"- );- }- }- }-}--/// Read one pass of a connection through the module and store what it-/// returns under `source_id`.-///-/// A pass the connector reports as failed still stores the records it read-/// and comes back as `Ok`, with [`SyncPassOutcome::failure`] set and nothing-/// pending: whether to ask again is the caller's decision (openhuman#6255).-///-/// # Errors-///-/// The connector call fails, or memory cannot store the batch.-pub async fn run_sync_pass(- config: &Config,- bound: &BoundEngine,- toolkit: &str,- connection_id: &str,- source_id: &str,- reason: &str,- pass_budget: usize,-) -> Result<SyncPassOutcome, String> {- // A connection deleted meanwhile is not read again: an empty pass with- // nothing pending ends every caller's loop.- if is_disconnected(config, connection_id) {- tracing::debug!(connection_id = %connection_id, "[composio] connection deleted; sync pass skipped");- return Ok(SyncPassOutcome::default());- }- // Sync pages inside the call; the default 30s bus deadline reported- // failure on runs the module then finished successfully.- let response = connectors::call_slow::<_, ConnectorSyncResponse>(- config,- methods::SYNC,- ConnectorSyncRequest {- toolkit: toolkit.to_string(),- connection_id: Some(connection_id.to_string()),- reason: Some(reason.to_string()),- // One pass is one budgeted slice: complete=false at the budget →- // more_pending → the caller resumes from the module's cursor.- max_items: Some(pass_budget),- ..ConnectorSyncRequest::default()- },- )- .await?;-- // A failed pass keeps what it read but is not "more pending" (#6255).- let failure = pass_failure(&response, toolkit, connection_id);- let more_pending = failure.is_none() && !response.batch.complete;-- let records_read = response.batch.records.len();- // Called with no records too: memory retries forgetting the previous- // versions an earlier pass could not.- let written = store_records(- config,- bound,- toolkit,- connection_id,- source_id,- &crate::memory::sources::layout_of(config, source_id),- &response.batch.records,- )- .await- .map_err(|error| format!("storing {toolkit} records failed: {}", String::from(error)))?;-- if more_pending {- // The module's note says why (today's request budget, typically).- tracing::info!(- toolkit = %toolkit,- note = response.message.as_deref().unwrap_or(""),- "[composio] sync pass stopped short of the end; the next run resumes"- );- }- tracing::debug!(- toolkit = %toolkit,- stage = ?response.stage,- pages_read = response.pages_read,- records_skipped = response.records_skipped,- records_read,- written,- "[composio] sync pass stored"- );- Ok(SyncPassOutcome {- records_read,- written,- more_pending,- failure,- })-}--/// Parse the optional `reason` parameter into a [`SyncReason`].-///-/// `None` and the explicit `"manual"` value both map to-/// [`SyncReason::Manual`]. Any other unrecognized string is rejected-/// with a clear error so a typo in a caller surfaces at the RPC boundary.-pub(crate) fn parse_sync_reason(raw: Option<&str>) -> OpResult<SyncReason> {- match raw {- None | Some("manual") => Ok(SyncReason::Manual),- Some("periodic") => Ok(SyncReason::Periodic),- Some("connection_created") => Ok(SyncReason::ConnectionCreated),- Some(other) => Err(format!(- "[composio] unrecognized sync reason '{other}': expected one of \- 'manual', 'periodic', 'connection_created'"- )),- }-}