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(modules): add failure reporting and client module
Steven Enamakelf0e2ac7f47b2
diff --git a/crates/openhuman-core/src/modules/client.rs b/crates/openhuman-core/src/modules/client.rsdeleted file mode 100644index 4e33edb467..0000000000--- a/crates/openhuman-core/src/modules/client.rs+++ /dev/null@@ -1,396 +0,0 @@-//! Shared module access for hosts, including before a core runtime is started.--use serde::{de::DeserializeOwned, Serialize};-use std::time::Duration;--use crate::config::Config;--use super::{failure, registry};--/// A sanitized terminal module outcome. Arguments and remote error text are absent.-#[derive(Clone, Copy, Debug, Eq, PartialEq)]-pub enum ModuleCallError {- Unavailable,- IncompatibleContract,- TransportFailed,- ModuleFault,-}--impl std::fmt::Display for ModuleCallError {- fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {- let reason = match self {- Self::Unavailable => "unavailable",- Self::IncompatibleContract => "incompatible contract",- Self::TransportFailed => "transport failed",- Self::ModuleFault => "execution failed",- };- // Later product reporting recognises this as an already reported- // module failure, rather than producing a second terminal event.- write!(formatter, "MODULE_CALL_REPORTED: module {reason}")- }-}--impl std::error::Error for ModuleCallError {}--/// Explicit configuration over the existing process-wide lazy module loader.-///-/// Constructing a client starts nothing. It needs neither a signed-in session-/// nor a core runtime. Set the bundled releases directory through the module-/// facade before the first call when artifacts ship with the host.-#[derive(Clone)]-pub struct ModuleClient {- config: Config,- timeout: Option<Duration>,- #[cfg(all(test, feature = "modules"))]- fixture: Option<tinybus::Proxy>,-}--impl ModuleClient {- #[must_use]- pub fn new(config: Config) -> Self {- Self {- config,- timeout: None,- #[cfg(all(test, feature = "modules"))]- fixture: None,- }- }-- #[cfg(all(test, feature = "modules"))]- pub(crate) fn fixture(proxy: tinybus::Proxy) -> Self {- Self {- config: Config::default(),- timeout: None,- fixture: Some(proxy),- }- }-- #[cfg(test)]- pub(crate) fn fixture_proxy(&self) -> Option<tinybus::Proxy> {- self.fixture.clone()- }-- /// Override the TinyBus deadline for every call made through this client.- ///- /// Use this for module operations whose contract has a longer bounded- /// duration than TinyBus's default. It applies equally to confidential- /// calls and test fixtures.- #[must_use]- pub fn with_timeout(mut self, timeout: Duration) -> Self {- self.timeout = Some(timeout);- self- }-- /// Execute a contract member, retaining its existing argument tuple arity.- ///- /// No implementation fallback is provided. The caller owns approvals,- /// cancellation, and lifecycle cleanup; use [`Self::with_timeout`] for a- /// longer module-specific deadline.- pub async fn call<R: DeserializeOwned>(- &self,- module: &str,- member: &str,- args: impl Serialize,- ) -> Result<R, ModuleCallError> {- self.invoke(module, member, args, false).await- }-- /// Execute a confidential member after TinyBus recipient attestation.- ///- /// Use this for credentials and other sensitive module inputs. A failure to- /// attest the pinned artifact fails the call; ordinary delivery is never retried.- pub async fn call_confidential<R: DeserializeOwned>(- &self,- module: &str,- member: &str,- args: impl Serialize,- ) -> Result<R, ModuleCallError> {- self.invoke(module, member, args, true).await- }-- /// Call a member that returns a JSON-encoded string and deserialize that- /// inner document. Malformed module output is reported using only the- /// registered module identity and the closed `module_fault` reason.- pub async fn call_json<R: DeserializeOwned>(- &self,- module: &str,- member: &str,- args: impl Serialize,- ) -> Result<R, ModuleCallError> {- let response: String = self.call(module, member, args).await?;- decode_module_json(module, &response)- }-- /// Confidential counterpart to [`Self::call_json`]. A decode failure is- /// terminal; the call is never retried through ordinary delivery.- pub async fn call_confidential_json<R: DeserializeOwned>(- &self,- module: &str,- member: &str,- args: impl Serialize,- ) -> Result<R, ModuleCallError> {- let response: String = self.call_confidential(module, member, args).await?;- decode_module_json(module, &response)- }-- /// Resolve a private proxy for an object returned by an owning module.- ///- /// Object paths are kept inside the owning host adapter; callers should- /// wrap this in a domain-specific client rather than expose the path as- /// product state.- #[cfg(feature = "modules")]- pub(crate) async fn object_client(- &self,- module: &str,- object_path: &str,- ) -> Result<ModuleObjectClient, ModuleCallError> {- let Some(record) = registry::find(module) else {- failure::report_unknown_module();- return Err(ModuleCallError::Unavailable);- };- if !self.config.modules.enabled {- failure::report(record, failure::Reason::Disabled);- return Err(ModuleCallError::Unavailable);- }- #[cfg(test)]- if let Some(fixture) = &self.fixture {- let proxy = fixture- .connection()- .proxy(- fixture.destination().as_str(),- object_path,- fixture.interface().as_str(),- )- .map_err(|_| ModuleCallError::IncompatibleContract)?;- let proxy = self- .timeout- .map_or(proxy.clone(), |timeout| proxy.with_timeout(timeout));- return Ok(ModuleObjectClient { record, proxy });- }- super::ops::ensure_loaded(&self.config, module)- .await- .map_err(|_| ModuleCallError::Unavailable)?;- let runtime = super::host::runtime().await.map_err(|_| {- failure::report(record, failure::Reason::TransportFailed);- ModuleCallError::TransportFailed- })?;- let proxy = runtime.proxy(record.bus_name, object_path).map_err(|_| {- failure::report(record, failure::Reason::IncompatibleContract);- ModuleCallError::IncompatibleContract- })?;- let proxy = self- .timeout- .map_or(proxy.clone(), |timeout| proxy.with_timeout(timeout));- Ok(ModuleObjectClient { record, proxy })- }-- /// Report a structurally invalid reply from a known module invocation.- pub(crate) fn report_malformed_reply(module: &str) {- if let Some(record) = registry::find(module) {- failure::report_invocation(record, failure::Reason::ModuleFault);- }- }-- /// Report a registered module that advertises an older wire contract.- pub(crate) fn report_incompatible_contract(module: &str) {- if let Some(record) = registry::find(module) {- failure::report(record, failure::Reason::IncompatibleContract);- }- }-- /// Report a known module that does not provide the requested capability.- pub(crate) fn report_unavailable(module: &str) {- if let Some(record) = registry::find(module) {- failure::report(record, failure::Reason::ModuleUnavailable);- }- }-- async fn invoke<R: DeserializeOwned>(- &self,- module: &str,- member: &str,- args: impl Serialize,- confidential: bool,- ) -> Result<R, ModuleCallError> {- let Some(record) = registry::find(module) else {- failure::report_unknown_module();- return Err(ModuleCallError::Unavailable);- };- if !self.config.modules.enabled {- failure::report(record, failure::Reason::Disabled);- return Err(ModuleCallError::Unavailable);- }- #[cfg(all(test, feature = "modules"))]- if let Some(proxy) = self.fixture.as_ref() {- let proxy = self.timeout.map_or_else(- || proxy.clone(),- |timeout| proxy.clone().with_timeout(timeout),- );- return invoke_proxy(record, &proxy, member, args, confidential).await;- }- #[cfg(not(feature = "modules"))]- {- let _ = (member, args, confidential);- failure::report(record, failure::Reason::LoaderDisabled);- Err(ModuleCallError::Unavailable)- }- #[cfg(feature = "modules")]- {- super::ops::ensure_loaded(&self.config, module)- .await- .map_err(|_| ModuleCallError::Unavailable)?;- let runtime = super::host::runtime().await.map_err(|_| {- failure::report(record, failure::Reason::TransportFailed);- ModuleCallError::TransportFailed- })?;- let proxy = runtime- .proxy(record.bus_name, record.object_path)- .map_err(|_| {- failure::report(record, failure::Reason::IncompatibleContract);- ModuleCallError::IncompatibleContract- })?;- let proxy = self- .timeout- .map_or(proxy.clone(), |timeout| proxy.with_timeout(timeout));- invoke_proxy(record, &proxy, member, args, confidential).await- }- }-}--/// A validated proxy for a module-owned object path.-///-/// This stays crate-private so bus object identities do not become product-/// state or leak into logs and controller responses.-#[cfg(feature = "modules")]-#[derive(Clone)]-pub(crate) struct ModuleObjectClient {- record: &'static super::types::ModuleRecord,- proxy: tinybus::Proxy,-}--#[cfg(feature = "modules")]-impl ModuleObjectClient {- pub(crate) async fn call<R: DeserializeOwned>(- &self,- member: &str,- args: impl Serialize,- ) -> Result<R, ModuleCallError> {- invoke_proxy(self.record, &self.proxy, member, args, false).await- }-- pub(crate) async fn call_confidential<R: DeserializeOwned>(- &self,- member: &str,- args: impl Serialize,- ) -> Result<R, ModuleCallError> {- invoke_proxy(self.record, &self.proxy, member, args, true).await- }-}--fn decode_module_json<R: DeserializeOwned>(- module: &str,- response: &str,-) -> Result<R, ModuleCallError> {- serde_json::from_str(response).map_err(|_| {- ModuleClient::report_malformed_reply(module);- ModuleCallError::ModuleFault- })-}--#[cfg(feature = "modules")]-async fn invoke_proxy<R: DeserializeOwned>(- record: &'static super::types::ModuleRecord,- proxy: &tinybus::Proxy,- member: &str,- args: impl Serialize,- confidential: bool,-) -> Result<R, ModuleCallError> {- let result = if confidential {- proxy.call_confidential(member, args).await- } else {- proxy.call(member, args).await- };- result.map_err(|error| report_proxy_failure(record, &error))-}--/// Report a bus failure without exposing its payload to telemetry. Product-/// adapters may separately decode a structured provider refusal for display.-#[cfg(feature = "modules")]-pub(super) fn report_proxy_failure(- record: &'static super::types::ModuleRecord,- error: &tinybus::Error,-) -> ModuleCallError {- let (outcome, reason) = classify(error);- if reason == failure::Reason::ModuleUnavailable {- failure::report(record, reason);- } else {- failure::report_invocation(record, reason);- }- outcome-}--#[cfg(feature = "modules")]-fn classify(error: &tinybus::Error) -> (ModuleCallError, failure::Reason) {- use tinybus::Error;- match error {- Error::ModuleUnavailable { .. } => (- ModuleCallError::Unavailable,- failure::Reason::ModuleUnavailable,- ),- Error::IncompatibleVersion { .. }- | Error::UnknownMethod { .. }- | Error::UnknownInterface { .. }- | Error::UnknownObject { .. }- | Error::BadArguments { .. } => (- ModuleCallError::IncompatibleContract,- failure::Reason::IncompatibleContract,- ),- Error::MethodFailed { name, .. }- if name == "ai.tinyhumans.tinybus.Error.ModuleUnavailable" =>- {- (- ModuleCallError::Unavailable,- failure::Reason::ModuleUnavailable,- )- }- Error::MethodFailed { name, .. }- if matches!(- name.as_str(),- Error::UNKNOWN_METHOD- | "ai.tinyhumans.tinybus.Error.IncompatibleVersion"- | "ai.tinyhumans.tinybus.Error.UnknownInterface"- | "ai.tinyhumans.tinybus.Error.UnknownObject"- | "ai.tinyhumans.tinybus.Error.BadArguments"- ) =>- {- (- ModuleCallError::IncompatibleContract,- failure::Reason::IncompatibleContract,- )- }- Error::Json(_) => (- ModuleCallError::IncompatibleContract,- failure::Reason::IncompatibleContract,- ),- Error::MethodFailed { name, .. }- if matches!(- name.as_str(),- Error::NOT_ATTESTED | Error::CONFIDENTIALITY_REQUIRED- ) =>- {- (- ModuleCallError::TransportFailed,- failure::Reason::TransportFailed,- )- }- Error::MethodFailed { .. } => (ModuleCallError::ModuleFault, failure::Reason::ModuleFault),- _ => (- ModuleCallError::TransportFailed,- failure::Reason::TransportFailed,- ),- }-}--#[cfg(test)]-#[path = "client_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/modules/failure.rs b/crates/openhuman-core/src/modules/failure.rsdeleted file mode 100644index bf78481a19..0000000000--- a/crates/openhuman-core/src/modules/failure.rs+++ /dev/null@@ -1,110 +0,0 @@-//! Sanitized terminal module reports with deduplication for cached outcomes.--use std::collections::HashSet;-use std::sync::{Mutex, OnceLock};--use super::types::ModuleRecord;--/// Closed reason vocabulary: never accept a module error, path or payload here.-#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]-pub(super) enum Reason {- UnknownModule,- Disabled,- LoaderDisabled,- ResolutionFailed,- IncompatibleContract,- TransportFailed,- ModuleFault,- ModuleUnavailable,-}--impl Reason {- fn code(self) -> &'static str {- match self {- Self::UnknownModule => "unknown_module",- Self::Disabled => "disabled",- Self::LoaderDisabled => "loader_disabled",- Self::ResolutionFailed => "resolution_failed",- Self::IncompatibleContract => "incompatible_contract",- Self::TransportFailed => "transport_failed",- Self::ModuleFault => "module_fault",- Self::ModuleUnavailable => "module_unavailable",- }- }-- fn stage(self) -> &'static str {- match self {- Self::UnknownModule => "registry",- Self::Disabled | Self::LoaderDisabled => "availability",- Self::ResolutionFailed => "resolve",- Self::IncompatibleContract => "contract",- Self::TransportFailed => "transport",- Self::ModuleFault => "execution",- Self::ModuleUnavailable => "execution",- }- }-}--/// Report a terminal outcome once. Registry records supply all identifying tags.-///-/// There are finitely many registry records and reasons, so the process cache-/// is bounded. Concurrent callers cannot duplicate the same terminal report.-pub(super) fn report(record: &'static ModuleRecord, reason: Reason) {- report_metadata(record.id, record.version, reason, true);-}--/// Report a failure from this invocation. Independent executions can fail-/// with the same sanitized reason and still represent distinct terminal events.-pub(super) fn report_invocation(record: &'static ModuleRecord, reason: Reason) {- report_metadata(record.id, record.version, reason, false);-}--/// Unknown identifiers never become event metadata or deduplication keys.-pub(super) fn report_unknown_module() {- report_metadata("unregistered", "unknown", Reason::UnknownModule, true);-}--fn report_metadata(module: &'static str, version: &'static str, reason: Reason, deduplicate: bool) {- static REPORTED: OnceLock<Mutex<HashSet<(&'static str, Reason)>>> = OnceLock::new();- let platform = format!("{}-{}", std::env::consts::OS, std::env::consts::ARCH);- let capture = || {- crate::core::observability::report_error(- "loadable module operation failed",- "modules",- reason.stage(),- &[- ("module", module),- ("version", version),- ("stage", reason.stage()),- ("platform", &platform),- ("reason_code", reason.code()),- ],- )- };- // Pre-core embedders may call before Sentry is initialized. Do not spend- // the process deduplication key on an event no bound client can receive.- #[cfg(feature = "crash-reporting")]- let retain_key = sentry::Hub::current().client().is_some();- #[cfg(not(feature = "crash-reporting"))]- let retain_key = true;- if retain_key && deduplicate {- let first = REPORTED- .get_or_init(|| Mutex::new(HashSet::new()))- .lock()- .unwrap_or_else(std::sync::PoisonError::into_inner)- .insert((module, reason));- if !first {- return;- }- }- // A host may have put request payloads or user paths on its current scope.- // These terminal events carry only the closed metadata above.- #[cfg(feature = "crash-reporting")]- sentry::with_scope(|scope| scope.clear(), capture);- #[cfg(not(feature = "crash-reporting"))]- capture();-}--#[cfg(test)]-#[path = "failure_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/modules/report.rs b/crates/openhuman-core/src/modules/report.rsnew file mode 100644index 0000000000..b074e22df4--- /dev/null+++ b/crates/openhuman-core/src/modules/report.rs@@ -0,0 +1,87 @@+//! Terminal module outcomes, reported to Sentry.+//!+//! Collecting, sanitising and deduplicating a report is `tinybus::module`'s+//! [`FailureReporter`]; this file supplies the one piece that is OpenHuman's own,+//! the sink that turns a report into a Sentry event, and the process-wide+//! reporter every resolver and client shares so a terminal outcome is reported+//! once per process however many clients observed it.++use std::sync::{Arc, OnceLock};++use tinybus::module::{FailureReport, FailureReporter, FailureSink, Reason};++use super::registry;++/// Delivers a [`FailureReport`] as a Sentry event carrying only closed metadata.+struct SentrySink;++impl FailureSink for SentrySink {+ /// Pre-core embedders may report before Sentry is initialised. The reporter+ /// does not spend its deduplication key on an event no bound client can+ /// receive.+ fn ready(&self) -> bool {+ #[cfg(feature = "crash-reporting")]+ {+ sentry::Hub::current().client().is_some()+ }+ #[cfg(not(feature = "crash-reporting"))]+ {+ true+ }+ }++ fn capture(&self, report: &FailureReport<'_>) {+ let capture = || {+ crate::core::observability::report_error(+ "loadable module operation failed",+ "modules",+ report.reason.stage(),+ &[+ ("module", report.module),+ ("version", report.version),+ ("stage", report.reason.stage()),+ ("platform", report.platform),+ ("reason_code", report.reason.code()),+ ],+ )+ };+ // A host may have put request payloads or user paths on its current+ // scope. These terminal events carry only the closed metadata above.+ #[cfg(feature = "crash-reporting")]+ sentry::with_scope(|scope| scope.clear(), capture);+ #[cfg(not(feature = "crash-reporting"))]+ capture();+ }+}++/// The reporter shared by every resolver and client in this process.+#[must_use]+pub(super) fn reporter() -> Arc<FailureReporter> {+ static REPORTER: OnceLock<Arc<FailureReporter>> = OnceLock::new();+ Arc::clone(REPORTER.get_or_init(|| Arc::new(FailureReporter::new(Arc::new(SentrySink)))))+}++/// Report a structurally invalid reply from a known module invocation.+pub(crate) fn malformed_reply(module: &str) {+ if let Some(record) = registry::find(module) {+ reporter().report_invocation(record.id, record.version, Reason::ModuleFault);+ }+}++/// Report a registered module that advertises an older wire contract.+pub(crate) fn incompatible_contract(module: &str) {+ if let Some(record) = registry::find(module) {+ reporter().report(record.id, record.version, Reason::IncompatibleContract);+ }+}++/// Report a known module that does not provide the requested capability.+pub(crate) fn unavailable(module: &str) {+ if let Some(record) = registry::find(module) {+ reporter().report(record.id, record.version, Reason::ModuleUnavailable);+ }+}++#[cfg(test)]+#[path = "report_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/modules/failure_tests.rs b/crates/openhuman-core/src/modules/report_tests.rssimilarity index 70%rename from crates/openhuman-core/src/modules/failure_tests.rsrename to crates/openhuman-core/src/modules/report_tests.rsindex 9aa4632f2e..155962b87c 100644--- a/crates/openhuman-core/src/modules/failure_tests.rs+++ b/crates/openhuman-core/src/modules/report_tests.rs@@ -14,8 +14,8 @@ fn terminal_reports_are_sanitized_and_deduplicated() {);},|| {- report(record, Reason::ModuleFault);- report(record, Reason::ModuleFault);+ reporter().report(record.id, record.version, Reason::ModuleFault);+ reporter().report(record.id, record.version, Reason::ModuleFault);},);});@@ -48,36 +48,18 @@ fn terminal_reports_are_sanitized_and_deduplicated() {);}-#[test]-fn reason_codes_and_stages_are_closed_vocabulary() {- for reason in [- Reason::UnknownModule,- Reason::Disabled,- Reason::LoaderDisabled,- Reason::ResolutionFailed,- Reason::IncompatibleContract,- Reason::TransportFailed,- Reason::ModuleFault,- Reason::ModuleUnavailable,- ] {- assert!(reason- .code()- .chars()- .all(|c| c.is_ascii_lowercase() || c == '_'));- assert!(reason.stage().chars().all(|c| c.is_ascii_lowercase()));- }-}-#[cfg(feature = "crash-reporting")]#[test]fn a_pre_core_report_without_a_sentry_client_can_be_captured_later() {let record = crate::modules::registry::find("tinyhosts").unwrap();let hub = std::sync::Arc::new(sentry::Hub::new_from_top(sentry::Hub::current()));hub.bind_client(None);- sentry::Hub::run(hub, || report(record, Reason::IncompatibleContract));+ sentry::Hub::run(hub, || {+ reporter().report(record.id, record.version, Reason::IncompatibleContract);+ });let events = sentry::test::with_captured_events(|| {- report(record, Reason::IncompatibleContract);- report(record, Reason::IncompatibleContract);+ reporter().report(record.id, record.version, Reason::IncompatibleContract);+ reporter().report(record.id, record.version, Reason::IncompatibleContract);});assert_eq!(events.len(), 1, "{events:?}");assert_eq!(@@ -85,3 +67,11 @@ fn a_pre_core_report_without_a_sentry_client_can_be_captured_later() {Some("tinyhosts"));}++#[test]+fn reports_for_unregistered_modules_are_dropped() {+ // An unknown id never becomes event metadata or a deduplication key.+ malformed_reply("not-a-registered-module");+ incompatible_contract("not-a-registered-module");+ unavailable("not-a-registered-module");+}