Skip to content

The agent that grows with you

perf(providers): memoize the bare-name custom check on the config signature

holnyd154248eb638
diff --git a/providers/__init__.py b/providers/__init__.py
index 46fc1ceae9b..3e69b1b3868 100644
--- a/providers/__init__.py
+++ b/providers/__init__.py
@@ -45,6 +45,7 @@ import time
from contextvars import ContextVar
from dataclasses import dataclass, field
from pathlib import Path
+from typing import Any
from providers.base import ProviderProfile
@@ -155,6 +156,39 @@ def provider_source(name: str) -> str | None:
return _SOURCES.get(canonical)
+# ``has_named_custom_provider`` walks the provider registry (``_shadowed_by_builtin`` →
+# ``resolve_provider``, which formats an AuthError for unregistered names) and loads config
+# on every call — ~2.5 ms per miss (Enough1122's profile on #120901, 40-50x the old miss
+# path). This sits on the profile-miss path that ``model_metadata._strip_provider_prefix``
+# reaches per model/prefix, so it must not be paid per iteration. Memo per home keyed on
+# the config file's ``file_signature`` — the same invalidation signal ``load_config`` uses —
+# so an edit re-arms the next lookup, and multiplex homes never borrow each other's answers.
+_NAMED_CUSTOM_MEMO: dict[str, dict[str, bool]] = {}
+_NAMED_CUSTOM_MEMO_SIG: dict[str, Any] = {}
+_NAMED_CUSTOM_MEMO_NO_SIG = object()
+
+
+def _has_named_custom_provider(name: str, home: "Path | None", hkey: str) -> bool:
+ """``has_named_custom_provider`` memoized on the home's config file signature."""
+ from utils import file_signature
+
+ try:
+ sig = file_signature((home / "config.yaml").stat()) if home is not None else None
+ except OSError:
+ sig = None # no readable config: nothing configured, stable until one appears
+ memo = _NAMED_CUSTOM_MEMO.get(hkey)
+ if memo is None or _NAMED_CUSTOM_MEMO_SIG.get(hkey, _NAMED_CUSTOM_MEMO_NO_SIG) != sig:
+ memo = {}
+ _NAMED_CUSTOM_MEMO[hkey] = memo
+ _NAMED_CUSTOM_MEMO_SIG[hkey] = sig
+ if name in memo:
+ return memo[name]
+ from hermes_cli.runtime_provider_custom import has_named_custom_provider
+
+ memo[name] = has_named_custom_provider(name)
+ return memo[name]
+
+
def get_provider_profile(name: str) -> ProviderProfile | None:
"""Look up a provider profile by name or alias.
@@ -184,11 +218,10 @@ def get_provider_profile(name: str) -> ProviderProfile | None:
profile = lookup("custom")
# Bare named custom providers (not ``custom:<name>``) that are configured in
# ``providers:`` / ``custom_providers:`` but lack an explicit profile entry
- # also share the generic wire policy. Check via the runtime helper so this
- # module never imports ``hermes_cli`` at module level.
+ # also share the generic wire policy. The helper is memoized (see
+ # ``_has_named_custom_provider``) so the miss path stays cheap for per-model loops.
if profile is None and isinstance(name, str) and not is_custom_route:
- from hermes_cli.runtime_provider_custom import has_named_custom_provider
- if has_named_custom_provider(name):
+ if _has_named_custom_provider(name, home, key):
profile = lookup("custom")
return profile
diff --git a/tests/providers/test_named_custom_reasoning.py b/tests/providers/test_named_custom_reasoning.py
index 425367d81b7..102d323506e 100644
--- a/tests/providers/test_named_custom_reasoning.py
+++ b/tests/providers/test_named_custom_reasoning.py
@@ -53,3 +53,65 @@ def test_named_custom_fallback_does_not_override_registered_routes(monkeypatch):
assert get_provider_profile("custom:fixture") is dedicated
assert get_provider_profile("CUSTOM:unregistered") is get_provider_profile("custom")
assert get_provider_profile("NONEXISTENT") is None
+
+
+def test_bare_named_custom_memo_caches_the_helper_result(monkeypatch):
+ """The miss-path helper runs once per (home, name); repeats are memo hits.
+
+ Uncached it walks the provider registry per call (~2.5ms; #120901 review),
+ which lands inside per-model prefix loops.
+ """
+ import providers
+ from hermes_constants import get_hermes_home, hermes_home_key
+
+ home, hkey = get_hermes_home(), hermes_home_key()
+ calls = []
+
+ def fake(name):
+ calls.append(name)
+ return False
+
+ with monkeypatch.context() as m:
+ m.setattr("hermes_cli.runtime_provider_custom.has_named_custom_provider", fake)
+ assert providers._has_named_custom_provider("zzz-unknown", home, hkey) is False
+ assert providers._has_named_custom_provider("zzz-unknown", home, hkey) is False
+ assert calls == ["zzz-unknown"], f"second lookup must be a memo hit, got calls={calls}"
+
+
+def test_bare_named_custom_memo_invalidates_on_config_change(monkeypatch):
+ """A config edit re-arms the memo: the signature is the same signal load_config uses."""
+ import providers
+ from hermes_constants import get_hermes_home, hermes_home_key
+
+ home, hkey = get_hermes_home(), hermes_home_key()
+ cfg = home / "config.yaml"
+
+ # No config file: nothing configured.
+ assert providers._has_named_custom_provider("my-endpoint", home, hkey) is False
+
+ cfg.write_text("providers:\n my-endpoint:\n base_url: http://127.0.0.1:1/v1\n")
+ assert providers._has_named_custom_provider("my-endpoint", home, hkey) is True
+
+ cfg.write_text("{}\n")
+ assert providers._has_named_custom_provider("my-endpoint", home, hkey) is False
+
+
+def test_bare_named_custom_memo_is_keyed_by_home(monkeypatch):
+ """Two home keys never borrow each other's answers (multiplex isolation)."""
+ import providers
+ from hermes_constants import get_hermes_home
+
+ home = get_hermes_home()
+ answers = {"key-a": True, "key-b": False}
+ current = {"k": "key-a"}
+
+ def fake(name):
+ return answers[current["k"]]
+
+ with monkeypatch.context() as m:
+ m.setattr("hermes_cli.runtime_provider_custom.has_named_custom_provider", fake)
+ assert providers._has_named_custom_provider("n", home, "key-a") is True
+ current["k"] = "key-b"
+ assert providers._has_named_custom_provider("n", home, "key-b") is False
+ # key-a's slot still holds True — key-b's False never leaked into it.
+ assert providers._has_named_custom_provider("n", home, "key-a") is True