core: cache the tool search handler per session (#27258)

## Why

Tool router construction rebuilds the deferred-tool BM25 index during
session initialization and before each sampling continuation, even when
the searchable tool metadata is unchanged. Local profiling measured
`append_tool_search_executor` at roughly 113 ms per continuation, making
repeated index construction the largest measured router-building cost.

## What changed

- Add a session-scoped `ToolSearchHandlerCache` so continuations and
user turns can reuse the existing handler.
- Key reuse on the complete ordered `Vec<ToolSearchInfo>`, rebuilding
when searchable text, loadable tool specs, source metadata, or ordering
changes.
- Build handlers outside the cache lock and recheck before publishing
them, avoiding holding the mutex during index construction.

## Verification

- `cache_reuses_identical_search_infos_and_rebuilds_changed_inputs`
covers exact cache reuse and invalidation when the ordered search
metadata changes.
- Local rollout profiling showed the initial router build populating the
cache and unchanged later continuations reusing it:
  - uncached: 118 ms median across 14 spans from 3 rollouts
  - cached: 4 ms median across 12 spans from 3 rollouts
This commit is contained in:
mchen-oai authored and GitHub committed 2026-06-15 14:48:30 -07:00
1 parent fbbe7706d6
commit af99f6a72f
12 files changed
+169 -29

No files matched your search

+1 -1
View File
@@ -69,7 +69,7 @@ pub use request_user_input::RequestUserInputHandler;
pub use shell::ShellCommandHandler;
pub(crate) use shell::ShellCommandHandlerOptions;
pub use test_sync::TestSyncHandler;
pub use tool_search::ToolSearchHandler;
pub(crate) use tool_search::ToolSearchHandlerCache;
pub use unified_exec::ExecCommandHandler;
pub(crate) use unified_exec::ExecCommandHandlerOptions;
pub use unified_exec::WriteStdinHandler;
+79 -21
View File
@@ -16,29 +16,63 @@ use codex_tools::TOOL_SEARCH_TOOL_NAME;
use codex_tools::ToolName;
use codex_tools::ToolSearchEntry;
use codex_tools::ToolSearchInfo;
use codex_tools::ToolSearchSourceInfo;
use codex_tools::ToolSpec;
use codex_tools::coalesce_loadable_tool_specs;
use std::sync::Arc;
use std::sync::Mutex;
pub struct ToolSearchHandler {
entries: Vec<ToolSearchEntry>,
search_source_infos: Vec<ToolSearchSourceInfo>,
search_infos: Vec<ToolSearchInfo>,
spec: ToolSpec,
search_engine: SearchEngine<usize>,
}
#[derive(Default)]
pub(crate) struct ToolSearchHandlerCache {
cached: Mutex<Option<Arc<ToolSearchHandler>>>,
}
impl ToolSearchHandlerCache {
pub(crate) fn get_or_build(&self, search_infos: Vec<ToolSearchInfo>) -> Arc<ToolSearchHandler> {
{
let cached = self.cached();
if let Some(cached) = cached.as_ref()
&& cached.search_infos == search_infos
{
return Arc::clone(cached);
}
}
let handler = Arc::new(ToolSearchHandler::new(search_infos));
let mut cached = self.cached();
if let Some(cached) = cached.as_ref()
&& cached.search_infos == handler.search_infos
{
return Arc::clone(cached);
}
*cached = Some(Arc::clone(&handler));
handler
}
fn cached(&self) -> std::sync::MutexGuard<'_, Option<Arc<ToolSearchHandler>>> {
match self.cached.lock() {
Ok(cached) => cached,
Err(poisoned) => poisoned.into_inner(),
}
}
}
impl ToolSearchHandler {
pub(crate) fn new(search_infos: Vec<ToolSearchInfo>) -> Self {
let mut entries = Vec::with_capacity(search_infos.len());
let mut search_source_infos = Vec::new();
for search_info in search_infos {
entries.push(search_info.entry);
if let Some(source_info) = search_info.source_info {
search_source_infos.push(source_info);
}
}
let documents: Vec<Document<usize>> = entries
let search_source_infos = search_infos
.iter()
.map(|entry| entry.search_text.clone())
.filter_map(|search_info| search_info.source_info.clone())
.collect::<Vec<_>>();
let spec = create_tool_search_tool(&search_source_infos, TOOL_SEARCH_DEFAULT_LIMIT);
let documents: Vec<Document<usize>> = search_infos
.iter()
.map(|search_info| search_info.entry.search_text.clone())
.enumerate()
.map(|(idx, search_text)| Document::new(idx, search_text))
.collect();
@@ -46,8 +80,8 @@ impl ToolSearchHandler {
SearchEngineBuilder::<usize>::with_documents(Language::English, documents).build();
Self {
entries,
search_source_infos,
search_infos,
spec,
search_engine,
}
}
@@ -59,7 +93,7 @@ impl ToolExecutor<ToolInvocation> for ToolSearchHandler {
}
fn spec(&self) -> ToolSpec {
create_tool_search_tool(&self.search_source_infos, TOOL_SEARCH_DEFAULT_LIMIT)
self.spec.clone()
}
fn supports_parallel_tool_calls(&self) -> bool {
@@ -101,7 +135,7 @@ impl ToolSearchHandler {
));
}
if self.entries.is_empty() {
if self.search_infos.is_empty() {
return Ok(boxed_tool_output(ToolSearchOutput { tools: Vec::new() }));
}
@@ -124,7 +158,8 @@ impl ToolSearchHandler {
.search(query, limit)
.into_iter()
.map(|result| result.document.id)
.filter_map(|id| self.entries.get(id));
.filter_map(|id| self.search_infos.get(id))
.map(|search_info| &search_info.entry);
self.search_output_tools(results)
}
@@ -153,6 +188,29 @@ mod tests {
use rmcp::model::Tool;
use std::sync::Arc;
#[test]
fn cache_reuses_handler_for_identical_search_infos_and_rebuilds_for_changes() {
let cache = ToolSearchHandlerCache::default();
let search_infos = vec![
McpHandler::new(tool_info("calendar", "create_event", "Create events"))
.expect("MCP tool should convert")
.search_info()
.expect("MCP handler should return search info"),
];
let first = cache.get_or_build(search_infos.clone());
let second = cache.get_or_build(search_infos.clone());
assert!(Arc::ptr_eq(&first, &second));
let mut changed_search_infos = search_infos;
changed_search_infos[0]
.entry
.search_text
.push_str(" changed");
let changed = cache.get_or_build(changed_search_infos);
assert!(!Arc::ptr_eq(&first, &changed));
}
#[test]
fn mixed_search_results_coalesce_mcp_namespaces() {
let dynamic_namespace = DynamicToolNamespaceSpec {
@@ -194,9 +252,9 @@ mod tests {
}));
let handler = ToolSearchHandler::new(search_infos);
let results = [
&handler.entries[0],
&handler.entries[2],
&handler.entries[1],
&handler.search_infos[0].entry,
&handler.search_infos[2].entry,
&handler.search_infos[1].entry,
];
let tools = handler