diff --git a/codex-rs/core-plugins/src/discoverable.rs b/codex-rs/core-plugins/src/discoverable.rs index eb1df6ff52..972ccc9558 100644 --- a/codex-rs/core-plugins/src/discoverable.rs +++ b/codex-rs/core-plugins/src/discoverable.rs @@ -141,16 +141,7 @@ impl PluginsManager { } } if let Some(remote_installed_marketplaces) = remote_installed_marketplaces.as_ref() { - let mut installed_app_connector_ids = self - .plugins_for_config(&input.plugins) - .await - .capability_summaries() - .iter() - .flat_map(|plugin| plugin.app_connector_ids.iter()) - .map(|connector_id| connector_id.0.clone()) - .collect::>(); - installed_app_connector_ids - .extend(input.loaded_plugin_app_connector_ids.iter().cloned()); + let installed_app_connector_ids = &input.loaded_plugin_app_connector_ids; let installed_remote_plugin_ids = remote_installed_marketplaces .iter() .flat_map(|marketplace| marketplace.plugins.iter()) diff --git a/codex-rs/core-plugins/src/remote/catalog_cache.rs b/codex-rs/core-plugins/src/remote/catalog_cache.rs index d49885dfbb..e1b908defb 100644 --- a/codex-rs/core-plugins/src/remote/catalog_cache.rs +++ b/codex-rs/core-plugins/src/remote/catalog_cache.rs @@ -3,12 +3,16 @@ use super::RemotePluginServiceConfig; use codex_login::CodexAuth; use serde::Deserialize; use serde::Serialize; +use std::collections::VecDeque; use std::path::Path; use std::path::PathBuf; +use std::sync::OnceLock; +use std::sync::RwLock; use tracing::warn; const REMOTE_PLUGIN_CATALOG_DISK_CACHE_SCHEMA_VERSION: u8 = 1; const REMOTE_PLUGIN_CATALOG_DISK_CACHE_DIR: &str = "cache/remote_plugin_catalog"; +const REMOTE_PLUGIN_CATALOG_MEMORY_CACHE_CAPACITY: usize = 8; #[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] struct RemotePluginCatalogCacheKey { @@ -35,6 +39,48 @@ struct RemotePluginCatalogDiskCache { plugins: Vec, } +#[derive(Clone)] +struct MemoryCacheEntry { + path: PathBuf, + bytes: Vec, + plugins: Vec, +} + +#[derive(Default)] +struct MemoryCache { + entries: VecDeque, +} + +impl MemoryCache { + fn get(&self, path: &Path, bytes: &[u8]) -> Option> { + self.entries + .iter() + .find(|entry| entry.path == path && entry.bytes == bytes) + .map(|entry| entry.plugins.clone()) + } + + fn insert(&mut self, path: PathBuf, bytes: Vec, plugins: Vec) { + self.entries.retain(|entry| entry.path != path); + if self.entries.len() == REMOTE_PLUGIN_CATALOG_MEMORY_CACHE_CAPACITY { + self.entries.pop_front(); + } + self.entries.push_back(MemoryCacheEntry { + path, + bytes, + plugins, + }); + } + + fn remove(&mut self, path: &Path) { + self.entries.retain(|entry| entry.path != path); + } +} + +fn memory_cache() -> &'static RwLock { + static CACHE: OnceLock> = OnceLock::new(); + CACHE.get_or_init(|| RwLock::new(MemoryCache::default())) +} + pub(crate) fn load_cached_global_directory_plugins( codex_home: &Path, config: &RemotePluginServiceConfig, @@ -55,6 +101,19 @@ pub(crate) fn load_cached_global_directory_plugins( return None; } }; + if let Some(plugins) = memory_cache() + .read() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .get(&cache_path, &bytes) + { + return Some(plugins); + } + let mut memory_cache = memory_cache() + .write() + .unwrap_or_else(std::sync::PoisonError::into_inner); + if let Some(plugins) = memory_cache.get(&cache_path, &bytes) { + return Some(plugins); + } let cache: RemotePluginCatalogDiskCache = match serde_json::from_slice(&bytes) { Ok(cache) => cache, Err(err) => { @@ -62,15 +121,20 @@ pub(crate) fn load_cached_global_directory_plugins( cache_path = %cache_path.display(), "failed to parse remote plugin catalog disk cache: {err}" ); + memory_cache.remove(&cache_path); + drop(memory_cache); let _ = std::fs::remove_file(cache_path); return None; } }; if cache.schema_version != REMOTE_PLUGIN_CATALOG_DISK_CACHE_SCHEMA_VERSION { + memory_cache.remove(&cache_path); + drop(memory_cache); let _ = std::fs::remove_file(cache_path); return None; } + memory_cache.insert(cache_path, bytes, cache.plugins.clone()); Some(cache.plugins) } @@ -95,9 +159,18 @@ pub(crate) fn write_cached_global_directory_plugins( }) else { return; }; - let _ = std::fs::write(cache_path, bytes); + if std::fs::write(&cache_path, &bytes).is_ok() { + memory_cache() + .write() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .insert(cache_path, bytes, plugins.to_vec()); + } } +#[cfg(test)] +#[path = "catalog_cache_tests.rs"] +mod tests; + fn cache_path(codex_home: &Path, cache_key: &RemotePluginCatalogCacheKey) -> PathBuf { let cache_key_json = serde_json::to_vec(cache_key).unwrap_or_default(); let mut cache_key_hash = 0xcbf29ce484222325_u64; diff --git a/codex-rs/core-plugins/src/remote/catalog_cache_tests.rs b/codex-rs/core-plugins/src/remote/catalog_cache_tests.rs new file mode 100644 index 0000000000..ae3666e56a --- /dev/null +++ b/codex-rs/core-plugins/src/remote/catalog_cache_tests.rs @@ -0,0 +1,51 @@ +use super::*; +use tempfile::tempdir; + +#[test] +fn load_rejects_replaced_disk_cache_contents() { + let codex_home = tempdir().expect("tempdir should succeed"); + let config = RemotePluginServiceConfig { + chatgpt_base_url: "https://chatgpt.com".to_string(), + }; + let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing(); + write_cached_global_directory_plugins(codex_home.path(), &config, &auth, &[]); + assert_eq!( + load_cached_global_directory_plugins(codex_home.path(), &config, &auth), + Some(Vec::new()) + ); + + let path = cache_path( + codex_home.path(), + &RemotePluginCatalogCacheKey::global(&config, &auth), + ); + std::fs::write(&path, b"invalid json").expect("cache should be replaceable"); + + assert_eq!( + load_cached_global_directory_plugins(codex_home.path(), &config, &auth), + None + ); + assert!(!path.exists()); +} + +#[test] +fn memory_cache_is_bounded() { + let mut cache = MemoryCache::default(); + for index in 0..=REMOTE_PLUGIN_CATALOG_MEMORY_CACHE_CAPACITY { + cache.insert( + PathBuf::from(format!("catalog-{index}.json")), + Vec::new(), + Vec::new(), + ); + } + + assert_eq!( + cache.entries.len(), + REMOTE_PLUGIN_CATALOG_MEMORY_CACHE_CAPACITY + ); + assert!( + cache + .entries + .iter() + .all(|entry| entry.path.as_path() != Path::new("catalog-0.json")) + ); +} diff --git a/codex-rs/core-plugins/src/tool_suggest_metadata.rs b/codex-rs/core-plugins/src/tool_suggest_metadata.rs index 30065e6d94..550555f598 100644 --- a/codex-rs/core-plugins/src/tool_suggest_metadata.rs +++ b/codex-rs/core-plugins/src/tool_suggest_metadata.rs @@ -1,6 +1,8 @@ use std::collections::HashMap; use std::sync::Arc; use std::sync::RwLock; +use std::time::Duration; +use std::time::Instant; use codex_core_skills::config_rules::SkillConfigRules; use codex_plugin::AppDeclaration; @@ -25,9 +27,16 @@ use crate::marketplace::MarketplaceError; use crate::marketplace::MarketplacePluginSource; const MAX_TOOL_SUGGEST_METADATA_CACHE_ENTRIES: usize = 1024; +const TOOL_SUGGEST_METADATA_CACHE_TTL: Duration = Duration::from_secs(30); type ToolSuggestMetadataEntry = Result, String>; +#[derive(Clone)] +struct CachedToolSuggestMetadataEntry { + expires_at: Instant, + entry: ToolSuggestMetadataEntry, +} + /// Source-derived plugin metadata cached for tool suggestions. /// /// `PluginsManager` clears these entries alongside its loaded-plugin cache. Current skill config @@ -40,7 +49,7 @@ pub(crate) struct ToolSuggestMetadataCache { #[derive(Default)] struct ToolSuggestMetadataCacheState { generation: u64, - entries: HashMap, + entries: HashMap, } #[derive(Clone, PartialEq, Eq, Hash)] @@ -147,8 +156,12 @@ impl ToolSuggestMetadataCache { fn cached_entry(&self, artifact: &PluginArtifactIdentity) -> Option { match self.state.read() { - Ok(state) => state.entries.get(artifact).cloned(), - Err(err) => err.into_inner().entries.get(artifact).cloned(), + Ok(state) => state.entries.get(artifact).and_then(|cached| { + (Instant::now() < cached.expires_at).then(|| cached.entry.clone()) + }), + Err(err) => err.into_inner().entries.get(artifact).and_then(|cached| { + (Instant::now() < cached.expires_at).then(|| cached.entry.clone()) + }), } } @@ -177,7 +190,13 @@ impl ToolSuggestMetadataCache { { state.entries.clear(); } - state.entries.insert(artifact, entry); + state.entries.insert( + artifact, + CachedToolSuggestMetadataEntry { + expires_at: Instant::now() + TOOL_SUGGEST_METADATA_CACHE_TTL, + entry, + }, + ); true } } @@ -236,3 +255,7 @@ async fn load_plugin_metadata( skill_inventory: Some(skill_inventory), })) } + +#[cfg(test)] +#[path = "tool_suggest_metadata_tests.rs"] +mod tests; diff --git a/codex-rs/core-plugins/src/tool_suggest_metadata_tests.rs b/codex-rs/core-plugins/src/tool_suggest_metadata_tests.rs new file mode 100644 index 0000000000..d0c9da7c44 --- /dev/null +++ b/codex-rs/core-plugins/src/tool_suggest_metadata_tests.rs @@ -0,0 +1,32 @@ +use super::*; +use codex_utils_absolute_path::AbsolutePathBuf; + +#[test] +fn expired_metadata_is_not_reused() { + let cache = ToolSuggestMetadataCache::new(); + let artifact = PluginArtifactIdentity { + plugin_id: "sample@test".to_string(), + source: MarketplacePluginSource::Local { + path: AbsolutePathBuf::try_from("/tmp/sample").expect("absolute path"), + }, + }; + let entry = Ok(Arc::new(ToolSuggestMetadataFragment { + config_name: "sample@test".to_string(), + display_name: "sample".to_string(), + description: None, + mcp_server_names: Vec::new(), + app_declarations: Vec::new(), + skill_inventory: None, + })); + assert!(cache.cache_entry_if_current(cache.generation(), artifact.clone(), entry)); + cache + .state + .write() + .expect("cache lock should not be poisoned") + .entries + .get_mut(&artifact) + .expect("entry should be cached") + .expires_at = Instant::now(); + + assert!(cache.cached_entry(&artifact).is_none()); +}