The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
perf(toolsets): memoise resolve_toolset keyed on registry generation
spfcraze7b45d1d04920
diff --git a/tests/test_toolsets.py b/tests/test_toolsets.pyindex e59ce350f26..73ce7a9eabd 100644--- a/tests/test_toolsets.py+++ b/tests/test_toolsets.py@@ -1,5 +1,6 @@"""Tests for toolsets.py — toolset resolution, validation, and composition."""+import toolsets as toolsets_modfrom tools.registry import ToolRegistryfrom toolsets import (TOOLSETS,@@ -281,3 +282,77 @@ class TestResolveToolsetIncludeRegistry:def test_registry_only_toolset_static_view_is_empty(self):assert resolve_toolset("__definitely_not_a_real_toolset__", include_registry=False) == []+++class TestResolveToolsetMemo:+ """Measured-work pins for the generation-keyed resolution memo."""++ def test_second_resolution_is_cached(self, monkeypatch):+ """Repeated resolves of the same toolset must not re-walk the registry.++ resolve_toolset is called dozens of times per _get_platform_tools()+ (every /tools completion keystroke). The memo keyed on the registry+ generation makes repeat calls a dict lookup instead of a full+ includes-walk + registry snapshot.+ """+ from tools.registry import registry++ toolsets_mod._resolve_toolset_memo.clear()+ get_toolset_calls = {"n": 0}++ orig_get_toolset = toolsets_mod.get_toolset++ def counting_get_toolset(name, *, include_registry=True):+ get_toolset_calls["n"] += 1+ return orig_get_toolset(name, include_registry=include_registry)++ monkeypatch.setattr(toolsets_mod, "get_toolset", counting_get_toolset)++ registry_id = id(registry)+ generation = registry._generation++ first = resolve_toolset("hermes-cli")+ second = resolve_toolset("hermes-cli")++ assert first == second+ assert get_toolset_calls["n"] == 1, (+ "second resolution must be a memo hit (no get_toolset re-walk), "+ f"got {get_toolset_calls['n']} calls"+ )+ assert (+ "hermes-cli", True, registry_id, generation+ ) in toolsets_mod._resolve_toolset_memo++ def test_generation_bump_invalidates_memo(self, monkeypatch):+ """A registry mutation (generation bump) must force a fresh resolve."""+ from tools.registry import registry++ toolsets_mod._resolve_toolset_memo.clear()+ get_toolset_calls = {"n": 0}++ orig_get_toolset = toolsets_mod.get_toolset++ def counting_get_toolset(name, *, include_registry=True):+ get_toolset_calls["n"] += 1+ return orig_get_toolset(name, include_registry=include_registry)++ monkeypatch.setattr(toolsets_mod, "get_toolset", counting_get_toolset)++ resolve_toolset("hermes-cli")+ assert get_toolset_calls["n"] == 1++ # Simulate a registry mutation bumping the generation.+ registry._generation += 1+ resolve_toolset("hermes-cli")+ assert get_toolset_calls["n"] == 2, (+ "generation bump must invalidate the memo and re-resolve"+ )++ def test_memo_result_matches_fresh_resolution(self):+ """The memo must never change the resolved result."""+ toolsets_mod._resolve_toolset_memo.clear()+ first = resolve_toolset("hermes-cli", include_registry=False)+ second = resolve_toolset("hermes-cli", include_registry=False)+ assert first == second+ assert first # non-empty sanity+diff --git a/toolsets.py b/toolsets.pyindex 26d635043f2..46ad8205d93 100644--- a/toolsets.py+++ b/toolsets.py@@ -23,7 +23,7 @@ Usage:all_tools = resolve_toolset("full_stack")"""-from typing import List, Dict, Any, Set, Optional+from typing import Dict, List, Any, Set, Optional, Tuple# Shared tool list for CLI and all messaging platform toolsets.@@ -753,6 +753,19 @@ def bundle_non_core_tools(toolset_name: str) -> Set[str]:return to_remove+# Resolution memo keyed on (toolset name, include_registry, registry+# generation). resolve_toolset() recursively walks toolset includes and, with+# include_registry=True, merges registry-registered tools on every call —+# measured ~2us/toolset in isolation but called dozens of times per+# _get_platform_tools() (per-keystroke /tools completion) and per picker+# render. The registry exposes a monotonic _generation counter (bumped on+# every register/deregister/alias/MCP refresh — see tools/registry.py), so a+# cache entry is valid for as long as the generation is unchanged; external+# callers never pass ``visited``, so the memo engages exactly at the public+# entry and the internal cycle-detection recursion stays untouched.+_resolve_toolset_memo: Dict[Tuple[str, bool, int, int], List[str]] = {}++def resolve_toolset(name: str, visited: Set[str] = None, *, include_registry: bool = True) -> List[str]:"""Recursively resolve a toolset to get all tool names.@@ -773,6 +786,21 @@ def resolve_toolset(name: str, visited: Set[str] = None, *, include_registry: boReturns:List[str]: List of all tool names in the toolset"""+ external_call = visited is None+ if external_call:+ try:+ from tools.registry import registry++ registry_id = id(registry)+ generation = getattr(registry, "_generation", 0)+ except Exception:+ registry_id = 0+ generation = 0+ memo_key = (name, include_registry, registry_id, generation)+ cached = _resolve_toolset_memo.get(memo_key)+ if cached is not None:+ return list(cached)+if visited is None:visited = set()@@ -832,7 +860,18 @@ def resolve_toolset(name: str, visited: Set[str] = None, *, include_registry: boincluded_tools = resolve_toolset(included_name, visited, include_registry=include_registry)tools.update(included_tools)- return sorted(tools)+ result = sorted(tools)+ if external_call:+ try:+ from tools.registry import registry++ registry_id = id(registry)+ generation = getattr(registry, "_generation", 0)+ except Exception:+ registry_id = 0+ generation = 0+ _resolve_toolset_memo[(name, include_registry, registry_id, generation)] = list(result)+ return resultdef resolve_multiple_toolsets(toolset_names: List[str]) -> List[str]: