Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

fix(composio): scope integration cache to profile and credential

Steven Enamakelc1911c772575
diff --git a/crates/openhuman-core/src/integrations/composio/connected_integrations/cache.rs b/crates/openhuman-core/src/integrations/composio/connected_integrations/cache.rs
index 337bb0f36f..4d36813798 100644
--- a/crates/openhuman-core/src/integrations/composio/connected_integrations/cache.rs
+++ b/crates/openhuman-core/src/integrations/composio/connected_integrations/cache.rs
@@ -11,7 +11,7 @@ use sha2::{Digest, Sha256};
use std::collections::{HashMap, HashSet};
use std::sync::atomic::{AtomicU64, Ordering};
-use std::sync::{LazyLock, RwLock};
+use std::sync::{Arc, LazyLock, RwLock};
use std::time::Instant;
// ── Prompt integration discovery ────────────────────────────────────
@@ -23,15 +23,71 @@ pub(crate) struct CachedIntegrations {
pub(crate) cached_at: Instant,
}
-/// Process-wide cache for connected integrations, keyed by the Composio
-/// credential identity ([`cache_key`]) so two agents on different
-/// credentials never read each other's connections.
+/// Process-wide cache for connected integrations, keyed by the calling
+/// profile/operator scope and credential identity ([`checked_cache_key`]), so profiles
+/// with identical service credentials never read each other's connections.
pub(crate) static INTEGRATIONS_CACHE: LazyLock<RwLock<HashMap<String, CachedIntegrations>>> =
LazyLock::new(|| RwLock::new(HashMap::new()));
/// Prevent an in-flight startup warm from restoring a snapshot that was
/// invalidated while its backend requests were running.
-pub(crate) static CACHE_GENERATION: AtomicU64 = AtomicU64::new(0);
+static CACHE_GENERATIONS: LazyLock<RwLock<HashMap<String, Arc<AtomicU64>>>> =
+ LazyLock::new(|| RwLock::new(HashMap::new()));
+
+/// The same scope epoch is shared across its config/credential snapshots. An
+/// invalidation fences its in-flight fetches even before any entry is cached.
+pub(crate) fn cache_generation(key: &str) -> Arc<AtomicU64> {
+ let scope = key.split_once('/').map(|(scope, _)| scope).unwrap_or(key);
+ let mut guard = CACHE_GENERATIONS
+ .write()
+ .unwrap_or_else(|error| error.into_inner());
+ guard
+ .entry(scope.to_owned())
+ .or_insert_with(|| Arc::new(AtomicU64::new(0)))
+ .clone()
+}
+
+fn current_cache_scope_prefix() -> Option<String> {
+ let tenant = crate::core::runtime::current_tenant().ok()?;
+ // Connected accounts belong to the profile/operator, shared by its agents.
+ // scope_from keeps the storage profile encoding and refuses missing SaaS
+ // profiles, while no-profile SingleUser work keeps its local identity.
+ let scope = crate::storage::scope_from(
+ tenant.profile.as_deref(),
+ None,
+ crate::core::runtime::is_saas(),
+ )
+ .ok()?;
+ let mut digest = Sha256::new();
+ digest.update(b"openhuman-integrations-cache-scope-v1\0");
+ digest.update(scope.as_str().as_bytes());
+ Some(format!("scope:{}/", hex::encode(digest.finalize())))
+}
+
+/// Admit a fetched snapshot only while its calling scope's epoch is current.
+/// Fetch and tests use this same insertion path; the cache write lock orders
+/// admission against invalidation and reconciliation.
+pub(crate) fn store_fetched_integrations(
+ key: String,
+ epoch: &AtomicU64,
+ generation: u64,
+ entries: Vec<ConnectedIntegration>,
+) -> bool {
+ let Ok(mut guard) = INTEGRATIONS_CACHE.write() else {
+ return false;
+ };
+ if epoch.load(Ordering::SeqCst) != generation {
+ return false;
+ }
+ guard.insert(
+ key,
+ CachedIntegrations {
+ entries,
+ cached_at: Instant::now(),
+ },
+ );
+ true
+}
/// Crate-wide test serialization lock for all tests that mutate or read
/// the process-global `INTEGRATIONS_CACHE`. Defined here so it is shared
@@ -52,14 +108,24 @@ pub(crate) async fn composio_cache_test_lock_async() -> tokio::sync::MutexGuard<
#[cfg(test)]
static COMPOSIO_CACHE_TEST_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
-/// Bind a cached integration list to its backend endpoint, backend credential,
-/// and effective Composio credential identity. Digests keep secrets out of
-/// cache keys and logs while preventing cross-agent cache hits after rotation.
-pub(crate) fn cache_key(config: &Config) -> String {
+/// Bind a snapshot to the calling profile/operator's scope and its
+/// credentials. SaaS work without a profile cannot read or populate the cache.
+pub(crate) fn checked_cache_key(config: &Config) -> Option<String> {
+ let prefix = current_cache_scope_prefix()?;
let backend_url = crate::backend::base_url(&config.api_url)
.map(|url| crate::util::url::normalize_backend_api_base_url(&url))
.unwrap_or_default();
- cache_key_with_backend_url(config, &backend_url)
+ Some(format!(
+ "{prefix}{}",
+ cache_key_with_backend_url(config, &backend_url)
+ ))
+}
+
+/// Existing credential-cache tests always run under a valid single-user or
+/// explicitly scoped tenant context. Production callers use the checked API.
+#[cfg(test)]
+pub(crate) fn cache_key(config: &Config) -> String {
+ checked_cache_key(config).expect("integration cache test requires a valid scope")
}
fn cache_key_with_backend_url(config: &Config, backend_url: &str) -> String {
@@ -120,13 +186,17 @@ fn cache_key_with_backend_url(config: &Config, backend_url: &str) -> String {
/// Called by [`crate::integrations::composio::bus::ComposioConnectionCreatedSubscriber`] when a
/// new OAuth connection completes, by [`composio_list_connections`]
/// when it observes a divergence between the backend response and the
-/// cached snapshot, and from tests. Clears the entire map because the
-/// callers don't carry a config reference.
+/// cached snapshot, and from tests. Clears that scope's snapshots because the
+/// callers resolve the authoritative calling scope. Other profiles are untouched;
+/// absent SaaS scope is a no-op.
pub fn invalidate_connected_integrations_cache() {
+ let Some(prefix) = current_cache_scope_prefix() else {
+ return;
+ };
if let Ok(mut guard) = INTEGRATIONS_CACHE.write() {
- let entries = guard.len();
- guard.clear();
- CACHE_GENERATION.fetch_add(1, Ordering::SeqCst);
+ let entries = guard.keys().filter(|key| key.starts_with(&prefix)).count();
+ cache_generation(&prefix).fetch_add(1, Ordering::SeqCst);
+ guard.retain(|key, _| !key.starts_with(&prefix));
tracing::info!(
cached_keys = entries,
"[composio][integrations] cache invalidated"
@@ -165,7 +235,7 @@ pub(crate) fn read_cached_integrations_from(
cache: &RwLock<HashMap<String, CachedIntegrations>>,
config: &Config,
) -> Option<Vec<ConnectedIntegration>> {
- let key = cache_key(config);
+ let key = checked_cache_key(config)?;
let guard = match cache.try_read() {
Ok(g) => g,
Err(_) => {
@@ -193,10 +263,6 @@ pub(crate) fn read_cached_integrations_from(
Some(cached.entries.clone())
}
-#[cfg(test)]
-#[path = "cache_tests.rs"]
-mod tests;
-
/// Stable hash of the *routing-relevant* slice of a connected-integrations
/// snapshot.
///
@@ -269,6 +335,9 @@ fn connected_toolkit_set(integrations: &[ConnectedIntegration]) -> HashSet<Strin
pub(crate) fn sync_cache_with_connections(
connections: &[crate::integrations::composio::types::ComposioConnection],
) -> bool {
+ let Some(prefix) = current_cache_scope_prefix() else {
+ return false;
+ };
let live_active: HashSet<String> = connections
.iter()
.filter(|c| c.is_active())
@@ -301,6 +370,7 @@ pub(crate) fn sync_cache_with_connections(
};
guard
.iter()
+ .filter(|(key, _)| key.starts_with(&prefix))
.filter_map(|(key, cached)| {
let cached_set = connected_toolkit_set(&cached.entries);
// Also check per-toolkit connection IDs (not just counts)
@@ -337,7 +407,7 @@ pub(crate) fn sync_cache_with_connections(
}
if let Ok(mut guard) = INTEGRATIONS_CACHE.write() {
- CACHE_GENERATION.fetch_add(1, Ordering::SeqCst);
+ cache_generation(&prefix).fetch_add(1, Ordering::SeqCst);
for (key, cached_set, live_set) in divergent_keys {
// Diff logging — makes Windows-timing regressions easy to
// catch in user-supplied debug dumps without leaking any
@@ -357,6 +427,10 @@ pub(crate) fn sync_cache_with_connections(
false
}
+#[cfg(test)]
+#[path = "cache_tests.rs"]
+mod tests;
+
#[cfg(test)]
#[path = "cache_scope_tests.rs"]
mod scope_tests;
diff --git a/crates/openhuman-core/src/integrations/composio/connected_integrations/cache_scope_tests.rs b/crates/openhuman-core/src/integrations/composio/connected_integrations/cache_scope_tests.rs
index 6f07d81f73..090decca57 100644
--- a/crates/openhuman-core/src/integrations/composio/connected_integrations/cache_scope_tests.rs
+++ b/crates/openhuman-core/src/integrations/composio/connected_integrations/cache_scope_tests.rs
@@ -125,3 +125,125 @@ fn profile_invalidation_preserves_another_profiles_snapshot() {
});
INTEGRATIONS_CACHE.write().unwrap().remove(&alice_key);
}
+
+#[test]
+fn profile_invalidation_does_not_cancel_another_profiles_in_flight_warm() {
+ let _guard = composio_cache_test_lock();
+ let dir = tempfile::tempdir().unwrap();
+ let config = config(dir.path());
+ let alice = profile(&config, "warm-alice");
+ let bob = profile(&config, "warm-bob");
+ let alice_key = CoreContext::sync_scope(alice, || cache_key(&config));
+ let bob_key = CoreContext::sync_scope(bob.clone(), || cache_key(&config));
+ let alice_epoch = cache_generation(&alice_key);
+ let bob_epoch = cache_generation(&bob_key);
+ let alice_generation = alice_epoch.load(Ordering::SeqCst);
+ let bob_generation = bob_epoch.load(Ordering::SeqCst);
+ CoreContext::sync_scope(bob, invalidate_connected_integrations_cache);
+ assert_eq!(
+ alice_epoch.load(Ordering::SeqCst),
+ alice_generation,
+ "Alice's in-flight fetch must remain admissible"
+ );
+ assert_ne!(
+ bob_epoch.load(Ordering::SeqCst),
+ bob_generation,
+ "Bob's own in-flight fetch must be fenced even with no cached entries"
+ );
+ assert!(
+ store_fetched_integrations(alice_key.clone(), &alice_epoch, alice_generation, vec![]),
+ "Alice's completed warm must still be admitted through the production insertion path"
+ );
+ assert!(
+ !store_fetched_integrations(bob_key.clone(), &bob_epoch, bob_generation, vec![]),
+ "Bob's invalidated warm must never repopulate the cache"
+ );
+ let mut guard = INTEGRATIONS_CACHE.write().unwrap();
+ assert!(guard.remove(&alice_key).is_some());
+ assert!(!guard.contains_key(&bob_key));
+}
+
+#[test]
+fn no_saas_profile_cannot_invalidate_or_reconcile_any_snapshot() {
+ const CHILD: &str = "OPENHUMAN_TEST_UNSCOPED_CACHE_MUTATION_CHILD";
+ if std::env::var_os(CHILD).is_none() {
+ let status = std::process::Command::new(std::env::current_exe().unwrap())
+ .args(["--exact", "integrations::composio::connected_integrations::cache::scope_tests::no_saas_profile_cannot_invalidate_or_reconcile_any_snapshot", "--nocapture"])
+ .env(CHILD, "1").status().unwrap();
+ assert!(
+ status.success(),
+ "isolated SaaS cache mutation regression failed"
+ );
+ return;
+ }
+ crate::core::runtime::mode::lock_mode(crate::core::runtime::Mode::Saas).unwrap();
+ let dir = tempfile::tempdir().unwrap();
+ let config = config(dir.path());
+ let alice = profile(&config, "unscoped-mutation-alice");
+ let key = seed(&config, alice, "gmail");
+ let epoch = cache_generation(&key);
+ let generation = epoch.load(Ordering::SeqCst);
+ invalidate_connected_integrations_cache();
+ assert!(
+ INTEGRATIONS_CACHE.read().unwrap().contains_key(&key),
+ "absent profile must not clear any cache"
+ );
+ assert!(
+ !sync_cache_with_connections(&[]),
+ "absent profile must not reconcile any cache"
+ );
+ assert!(INTEGRATIONS_CACHE.read().unwrap().contains_key(&key));
+ assert_eq!(
+ epoch.load(Ordering::SeqCst),
+ generation,
+ "absent profile must not fence another tenant's warm"
+ );
+}
+
+#[test]
+fn desktop_agents_share_catalog_and_default_context_invalidates_their_warms() {
+ let _guard = composio_cache_test_lock();
+ let dir = tempfile::tempdir().unwrap();
+ let config = config(dir.path());
+ let root = CoreContext::for_test_with_config(DomainSet::kernel(), config.clone());
+ let agent = |id: &str| {
+ let mut overlay =
+ ContextOverlay::new(config.clone(), DomainSet::kernel(), ToolGroups::none());
+ overlay.session_agent = Some(id.into());
+ root.derive_with(overlay)
+ };
+ let first = agent("desktop-first");
+ let second = agent("desktop-second");
+ let key = seed(&config, first, "gmail");
+ let other_profile = profile(&config, "desktop-other-profile");
+ let other_key = seed(&config, other_profile, "slack");
+ let epoch = cache_generation(&key);
+ let generation = epoch.load(Ordering::SeqCst);
+ CoreContext::sync_scope(second, || {
+ assert_eq!(
+ cache_key(&config),
+ key,
+ "the connected-account catalog belongs to the operator, shared by their agents"
+ );
+ assert_eq!(
+ cached_active_integrations(&config).unwrap()[0].toolkit,
+ "gmail"
+ );
+ });
+ CoreContext::sync_scope(root, invalidate_connected_integrations_cache);
+ assert!(
+ !INTEGRATIONS_CACHE.read().unwrap().contains_key(&key),
+ "the desktop settings/default context must invalidate its agents' catalog"
+ );
+ assert_ne!(
+ epoch.load(Ordering::SeqCst),
+ generation,
+ "the desktop settings/default context must fence its agents' in-flight warms"
+ );
+ assert!(!store_fetched_integrations(key, &epoch, generation, vec![]));
+ let mut guard = INTEGRATIONS_CACHE.write().unwrap();
+ assert!(
+ guard.remove(&other_key).is_some(),
+ "desktop invalidation must preserve explicit profiles"
+ );
+}
diff --git a/crates/openhuman-core/src/integrations/composio/connected_integrations/fetch.rs b/crates/openhuman-core/src/integrations/composio/connected_integrations/fetch.rs
index 705ddb15f1..f1e3e1e25e 100644
--- a/crates/openhuman-core/src/integrations/composio/connected_integrations/fetch.rs
+++ b/crates/openhuman-core/src/integrations/composio/connected_integrations/fetch.rs
@@ -4,12 +4,13 @@
//! on a miss), plus their small toolkit-membership/description helpers.
use std::sync::atomic::Ordering;
-use std::time::Instant;
use crate::agent::prompts::ConnectedIntegration;
use crate::config::Config;
-use super::cache::{cache_key, CachedIntegrations, CACHE_GENERATION, INTEGRATIONS_CACHE};
+use super::cache::{
+ cache_generation, checked_cache_key, store_fetched_integrations, INTEGRATIONS_CACHE,
+};
use super::fetch_uncached::fetch_connected_integrations_uncached;
/// Fetch the user's active Composio connections and their available
@@ -19,7 +20,7 @@ use super::fetch_uncached::fetch_connected_integrations_uncached;
/// data injected into system prompts — both the agent turn loop and
/// the debug dump CLI call this function.
///
-/// Results are cached process-wide (keyed by credential identity) and
+/// Results are cached process-wide (keyed by storage scope and credential identity) and
/// returned instantly on subsequent calls. The cache is invalidated
/// when a connection changes (via [`invalidate_connected_integrations_cache`]
/// or `list_connections` reconciliation), or on process restart.
@@ -64,6 +65,11 @@ pub enum FetchConnectedIntegrationsStatus {
pub async fn fetch_connected_integrations_status(
config: &Config,
) -> FetchConnectedIntegrationsStatus {
+ // A task that lost its SaaS profile must neither reuse another profile's
+ // snapshot nor request and cache connections under operator credentials.
+ if crate::storage::current_scope().is_err() {
+ return FetchConnectedIntegrationsStatus::Unavailable;
+ }
// Composio switched off: nothing to ask. An authoritative empty set also
// keeps the first turn from awaiting a hosted round trip.
if config.composio.mode.trim() == crate::config::schema::COMPOSIO_MODE_DISABLED {
@@ -86,8 +92,10 @@ pub async fn fetch_connected_integrations_status(
{
return FetchConnectedIntegrationsStatus::Authoritative(Vec::new());
}
- let key = cache_key(config);
+ let Some(key) = checked_cache_key(config) else {
+ return FetchConnectedIntegrationsStatus::Unavailable;
+ };
// A connection event or a divergent list_connections response invalidates
// this snapshot. Idle time alone must never put a network request on the
// first-token path.
@@ -104,25 +112,14 @@ pub async fn fetch_connected_integrations_status(
}
}
- let generation = CACHE_GENERATION.load(Ordering::SeqCst);
+ let epoch = cache_generation(&key);
+ let generation = epoch.load(Ordering::SeqCst);
match fetch_connected_integrations_uncached(config).await {
Some(result) => {
// Backend was reachable — cache the result (even if empty).
- if let Ok(mut guard) = INTEGRATIONS_CACHE.write() {
- if CACHE_GENERATION.load(Ordering::SeqCst) == generation {
- guard.insert(
- key,
- CachedIntegrations {
- entries: result.clone(),
- cached_at: Instant::now(),
- },
- );
- } else {
- tracing::debug!(
- "[composio][integrations] discarded fetch invalidated in flight"
- );
- return FetchConnectedIntegrationsStatus::Unavailable;
- }
+ if !store_fetched_integrations(key, &epoch, generation, result.clone()) {
+ tracing::debug!("[composio][integrations] discarded fetch invalidated in flight");
+ return FetchConnectedIntegrationsStatus::Unavailable;
}
FetchConnectedIntegrationsStatus::Authoritative(result)
}
@@ -189,6 +186,6 @@ pub(crate) fn resolve_toolkit_description(
slug: &str,
) -> String {
catalog_descriptions.get(slug).cloned().unwrap_or_else(|| {
- crate::integrations::composio::contract::toolkit_description(slug).to_string()
+ crate::integrations::composio::providers::toolkit_description(slug).to_string()
})
}
diff --git a/crates/openhuman-core/src/integrations/composio/ops/connections.rs b/crates/openhuman-core/src/integrations/composio/ops/connections.rs
index 50147aaa66..fdde3f341e 100644
--- a/crates/openhuman-core/src/integrations/composio/ops/connections.rs
+++ b/crates/openhuman-core/src/integrations/composio/ops/connections.rs
@@ -97,7 +97,7 @@ pub async fn composio_list_connections(
// connection-created subscriber's readiness window. Re-warm here so
// the next chat turn does not perform the three discovery requests.
let config = config.clone();
- tokio::spawn(async move {
+ crate::core::runtime::spawn_scoped(async move {
let _ = fetch_connected_integrations_status(&config).await;
});
}
diff --git a/crates/openhuman-core/src/integrations/composio/ops_fetch_integrations_and_triggers_tests.rs b/crates/openhuman-core/src/integrations/composio/ops_fetch_integrations_and_triggers_tests.rs
index c422413cec..aa55269560 100644
--- a/crates/openhuman-core/src/integrations/composio/ops_fetch_integrations_and_triggers_tests.rs
+++ b/crates/openhuman-core/src/integrations/composio/ops_fetch_integrations_and_triggers_tests.rs
@@ -185,7 +185,10 @@ fn sync_cache_invalidates_when_connection_becomes_active() {
// not connected. This is exactly the state the chat runtime
// gets stuck in on Windows when the user completes OAuth
// after the event-bus 60 s readiness poll times out.
- let key = "windows-regression-1";
+ let tmp = tempfile::tempdir().unwrap();
+ let config = test_config(&tmp);
+ let key_string = cache_key(&config);
+ let key = key_string.as_str();
clear_cache_key(key);
seed_cache(
key,
@@ -215,7 +218,10 @@ fn sync_cache_invalidates_when_connection_is_removed() {
// Cache remembers gmail as connected. The user just
// disconnected it from Settings; the next UI poll returns an
// empty list. Chat must forget gmail within one poll.
- let key = "windows-regression-2";
+ let tmp = tempfile::tempdir().unwrap();
+ let config = test_config(&tmp);
+ let key_string = cache_key(&config);
+ let key = key_string.as_str();
clear_cache_key(key);
seed_cache(key, vec![integration("gmail", true)]);
@@ -234,7 +240,10 @@ fn sync_cache_noop_when_backend_matches_cached_state() {
// Steady state: UI polls confirm cache is accurate. No
// invalidation — we must not thrash the chat runtime's tool
// registry on every 5 s UI poll.
- let key = "windows-regression-3";
+ let tmp = tempfile::tempdir().unwrap();
+ let config = test_config(&tmp);
+ let key_string = cache_key(&config);
+ let key = key_string.as_str();
clear_cache_key(key);
seed_cache(
key,
@@ -261,7 +270,10 @@ fn sync_cache_ignores_non_active_connection_rows() {
// while the OAuth handshake is in flight, which is wasteful
// and would also clear `tools` vecs for real active
// integrations already on disk.
- let key = "windows-regression-4";
+ let tmp = tempfile::tempdir().unwrap();
+ let config = test_config(&tmp);
+ let key_string = cache_key(&config);
+ let key = key_string.as_str();
clear_cache_key(key);
seed_cache(key, vec![integration("gmail", true)]);
@@ -286,7 +298,10 @@ fn sync_cache_treats_connected_status_equivalent_to_active() {
// `fetch_connected_integrations_uncached` filter). Make sure
// the new diff path matches that convention so it doesn't
// produce a false-positive invalidation.
- let key = "windows-regression-5";
+ let tmp = tempfile::tempdir().unwrap();
+ let config = test_config(&tmp);
+ let key_string = cache_key(&config);
+ let key = key_string.as_str();
clear_cache_key(key);
seed_cache(key, vec![integration("gmail", true)]);