Skip to content

The agent that grows with you

fix(tool-search): preserve exact and per-query ranking semantics

alt-glitch1e86a263ed4e
diff --git a/tests/tools/test_tool_search.py b/tests/tools/test_tool_search.py
index 1a0c01eaaae..d0f24616450 100644
--- a/tests/tools/test_tool_search.py
+++ b/tests/tools/test_tool_search.py
@@ -323,14 +323,17 @@ class TestBridgeDispatch:
current_tool_defs=[tool_def],
))
- assert result["results"] == [{"query": "unrelated vocabulary", "matches": []}]
+ [group] = result["results"]
+ assert group["query"] == "unrelated vocabulary"
+ assert group["matches"] == []
assert result["tools"] == {}
assert result["total_available"] == 1
- assert result["available_sources"] == [
+ assert group["available_sources"] == [
{"name": "recovery-catalog", "tool_count": 1},
]
- assert "remain available" in result["hint"]
- assert "before concluding" in result["hint"]
+ assert "remain available" in group["hint"]
+ assert "before concluding" in group["hint"]
+ assert "available_sources" not in result
def test_resolve_underlying_call_parses_object_args(self):
diff --git a/tests/tools/test_tool_search_multiquery.py b/tests/tools/test_tool_search_multiquery.py
index 1aacd68f70f..cc7a3d20e89 100644
--- a/tests/tools/test_tool_search_multiquery.py
+++ b/tests/tools/test_tool_search_multiquery.py
@@ -86,6 +86,54 @@ class TestStemming:
assert names == ["mq_slack_post_message"]
+# ---------------------------------------------------------------------------
+# Exact-name ranking and shared corpus statistics
+# ---------------------------------------------------------------------------
+
+
+class TestCatalogRanking:
+ def test_exact_name_beats_shorter_siblings(self):
+ from tools.tool_search import build_catalog, search_catalog
+
+ exact = _td(
+ "github_create_issue",
+ "Create a new issue with a title, body, assignees, labels, "
+ "milestone, project metadata, and linked context for a repository.",
+ )
+ catalog = build_catalog([
+ exact,
+ _td("github_create_issue_comment", "Comment."),
+ _td("github_create_issue_label", "Label."),
+ ])
+
+ assert search_catalog(catalog, "github_create_issue", limit=1) == [catalog[0]]
+
+ def test_exact_short_name_beats_prefixed_names(self):
+ from tools.tool_search import build_catalog, search_catalog
+
+ catalog = build_catalog([
+ _td("list", "List one item."),
+ _td("list_x", "List x."),
+ _td("list_all_the_open_items", "List every open item."),
+ ])
+
+ assert search_catalog(catalog, "list", limit=1) == [catalog[0]]
+
+ def test_precomputed_corpus_stats_preserve_results(self, issue_defs):
+ from tools.tool_search import _corpus_stats, build_catalog, search_catalog
+
+ catalog = build_catalog(issue_defs)
+ expected = search_catalog(catalog, "create issues", limit=3)
+ actual = search_catalog(
+ catalog,
+ "create issues",
+ limit=3,
+ corpus_stats=_corpus_stats(catalog),
+ )
+
+ assert actual == expected
+
+
# ---------------------------------------------------------------------------
# Multi-query dispatch_tool_search
# ---------------------------------------------------------------------------
@@ -133,7 +181,7 @@ class TestMultiQuerySearch:
for group in result["results"]:
assert len(group["matches"]) <= 1
- def test_partial_miss_adds_single_toplevel_fallback(self, issue_defs):
+ def test_partial_miss_adds_fallback_to_empty_group(self, issue_defs):
from tools.tool_search import ToolSearchConfig, dispatch_tool_search
result = json.loads(dispatch_tool_search(
@@ -142,14 +190,14 @@ class TestMultiQuerySearch:
config=ToolSearchConfig.from_raw({}),
))
assert result["results"][1]["matches"] == []
- # ONE fallback block at top level — not per empty group.
- assert "available_sources" in result
- assert "Some queries" in result["hint"]
- for group in result["results"]:
- assert "available_sources" not in group
- assert "hint" not in group
- source_names = {s["name"] for s in result["available_sources"]}
+ assert "available_sources" not in result["results"][0]
+ assert "hint" not in result["results"][0]
+ missed = result["results"][1]
+ assert "This query returned no lexical matches" in missed["hint"]
+ source_names = {s["name"] for s in missed["available_sources"]}
assert {"mq-linear", "mq-slack"} <= source_names
+ assert "available_sources" not in result
+ assert "hint" not in result
def test_bare_string_query_coerced_to_single_query(self, issue_defs):
from tools.tool_search import ToolSearchConfig, dispatch_tool_search
diff --git a/tools/tool_search.py b/tools/tool_search.py
index 809ad5c016a..48c9a56b35c 100644
--- a/tools/tool_search.py
+++ b/tools/tool_search.py
@@ -502,7 +502,27 @@ def _bm25_score(query_tokens: List[str], doc_tokens: List[str],
return score
-def search_catalog(catalog: List[CatalogEntry], query: str, limit: int = 5) -> List[CatalogEntry]:
+_CorpusStats = Tuple[List[int], float, Dict[str, int], int]
+
+
+def _corpus_stats(catalog: List[CatalogEntry]) -> _CorpusStats:
+ """Compute the BM25 statistics shared by every query over a catalog."""
+ doc_lengths = [len(entry._tokens) for entry in catalog]
+ avg_dl = sum(doc_lengths) / max(len(doc_lengths), 1)
+ doc_freq: Dict[str, int] = {}
+ for entry in catalog:
+ for token in set(entry._tokens):
+ doc_freq[token] = doc_freq.get(token, 0) + 1
+ return doc_lengths, avg_dl, doc_freq, len(catalog)
+
+
+def search_catalog(
+ catalog: List[CatalogEntry],
+ query: str,
+ limit: int = 5,
+ *,
+ corpus_stats: Optional[_CorpusStats] = None,
+) -> List[CatalogEntry]:
"""Return the top-``limit`` catalog entries for ``query`` by BM25.
Falls back to a stable name-substring match when every query token
@@ -519,18 +539,16 @@ def search_catalog(catalog: List[CatalogEntry], query: str, limit: int = 5) -> L
if not query_tokens:
return []
- # Precompute doc statistics.
- doc_lengths = [len(e._tokens) for e in catalog]
- avg_dl = sum(doc_lengths) / max(len(doc_lengths), 1)
- doc_freq: Dict[str, int] = {}
- for e in catalog:
- seen = set(e._tokens)
- for t in seen:
- doc_freq[t] = doc_freq.get(t, 0) + 1
- n_docs = len(catalog)
+ if corpus_stats is None:
+ corpus_stats = _corpus_stats(catalog)
+ doc_lengths, avg_dl, doc_freq, n_docs = corpus_stats
scored: List[Tuple[float, CatalogEntry]] = []
+ exact_name = query.strip().lower()
for entry in catalog:
+ if entry.name.lower() == exact_name:
+ scored.append((float("inf"), entry))
+ continue
s = _bm25_score(query_tokens, entry._tokens, doc_lengths, avg_dl,
doc_freq, n_docs)
if s > 0:
@@ -995,9 +1013,9 @@ def dispatch_tool_search(args: Dict[str, Any],
"description": ..., "required": [...]}}
}
- ``limit`` applies PER QUERY. When one or more queries return no matches,
- a single top-level ``available_sources`` + ``hint`` block is added so a
- lexical miss is not mistaken for a missing capability.
+ ``limit`` applies PER QUERY. Each query group that returns no matches gets
+ an ``available_sources`` + ``hint`` block so a lexical miss is not mistaken
+ for a missing capability.
"""
if config is None:
config = load_config()
@@ -1028,15 +1046,23 @@ def dispatch_tool_search(args: Dict[str, Any],
results: List[Dict[str, Any]] = []
tools_map: Dict[str, Dict[str, Any]] = {}
- any_empty = False
+ corpus_stats = _corpus_stats(catalog)
+ available_sources = _available_source_summary(catalog) if catalog else []
for query in queries:
- hits = search_catalog(catalog, query, limit=limit)
- if not hits:
- any_empty = True
+ hits = search_catalog(catalog, query, limit=limit, corpus_stats=corpus_stats)
for h in hits:
if h.name not in tools_map:
tools_map[h.name] = _shared_tool_record(h)
- results.append({"query": query, "matches": [h.name for h in hits]})
+ group: Dict[str, Any] = {"query": query, "matches": [h.name for h in hits]}
+ if not hits and catalog:
+ group["available_sources"] = available_sources
+ group["hint"] = (
+ "This query returned no lexical matches, but the sources above "
+ "are connected and their tools remain available. Retry "
+ "tool_search with the service name plus a concrete action or "
+ "object before concluding the capability is unavailable."
+ )
+ results.append(group)
result: Dict[str, Any] = {
"queries": queries,
@@ -1044,14 +1070,6 @@ def dispatch_tool_search(args: Dict[str, Any],
"results": results,
"tools": tools_map,
}
- if any_empty and catalog:
- result["available_sources"] = _available_source_summary(catalog)
- result["hint"] = (
- "Some queries returned no lexical matches, but the sources above "
- "are connected and their tools remain available. Retry "
- "tool_search with the service name plus a concrete action or "
- "object before concluding the capability is unavailable."
- )
return json.dumps(result, ensure_ascii=False)