Skip to content

The agent that grows with you

perf(moa): cache resolved preset + per-slot runtime to cut cold-start latency (#66793)

Ahmett101d1c6c6b58e87
diff --git a/agent/moa_loop.py b/agent/moa_loop.py
index 26e9523ec34..0e15492a8fc 100644
--- a/agent/moa_loop.py
+++ b/agent/moa_loop.py
@@ -12,6 +12,7 @@ import hashlib
import logging
import re
import threading
+import time
from concurrent.futures import ThreadPoolExecutor, wait as _futures_wait
from types import SimpleNamespace
from typing import Any
@@ -151,6 +152,24 @@ def _redact_trace_accounting(acct: Any) -> Any:
)
+# Cold-start caches. A MoA preset switch used to re-resolve the full
+# config + preset + every slot's provider runtime on EACH create() call
+# (once per tool-loop iteration), serially before the parallel fan-out could
+# start — adding 5-30s of "frozen" latency on complex presets
+# (#66793). The preset structure is immutable for the life of a turn, so
+# cache both the resolved preset and each (provider, model) runtime.
+_preset_cache_lock = threading.Lock()
+_preset_cache: dict[tuple, Any] = {}
+
+_runtime_cache_lock = threading.Lock()
+_runtime_cache: dict[tuple[str, str], tuple[float, dict[str, Any]]] = {}
+
+# Runtime entries go stale when providers/credentials change (key rotation,
+# base_url edits). Deliberately short-lived: 300s collapses the per-iteration
+# re-resolution inside a turn while bounding credential staleness between
+# turns — the non-MoA path picks up rotated keys immediately, this path
+# within 5 minutes.
+_RUNTIME_CACHE_TTL_SECONDS = 300.0
# Upper bound on concurrent reference-model calls. References are independent
# advisory calls (no tools, no inter-dependence), so we fan them out the same
@@ -322,34 +341,33 @@ def _slot_runtime(slot: dict[str, Any]) -> dict[str, Any]:
api_key resolver the CLI, gateway, and delegate_task all use), so the slot
gets its provider's real API surface — e.g. MiniMax → anthropic_messages,
GPT-5/o-series → max_completion_tokens, custom endpoints → their base_url.
-
Returns the kwargs to pass through to ``call_llm`` (provider/model plus the
resolved base_url/api_key when available). Falls back to the bare
provider/model on any resolution error so a misconfigured slot still
attempts the call rather than aborting the whole MoA turn.
+
+ The resolved runtime is cached per (provider, model) with a short TTL
+ (``_RUNTIME_CACHE_TTL_SECONDS``): the resolution does real I/O (catalog
+ query + config read) that used to run serially per create() call before
+ the parallel fan-out could start — the dominant source of MoA cold-start
+ latency (#66793). The TTL bounds credential staleness (key rotation,
+ base_url edits) instead of caching for the process lifetime.
"""
provider = str(slot.get("provider") or "").strip()
model = str(slot.get("model") or "").strip()
+ cache_key = (provider, model)
+ now = time.monotonic()
+ with _runtime_cache_lock:
+ entry = _runtime_cache.get(cache_key)
+ if entry is not None:
+ stamped_at, cached = entry
+ if now - stamped_at < _RUNTIME_CACHE_TTL_SECONDS:
+ return cached
out: dict[str, Any] = {"provider": provider, "model": model}
try:
from hermes_cli.runtime_provider import resolve_runtime_provider
rt = resolve_runtime_provider(requested=provider, target_model=model)
- # Forward the resolved endpoint through to call_llm unconditionally.
- # call_llm's _resolve_task_provider_model() is the single chokepoint that
- # decides whether an explicit base_url collapses a call to the generic
- # ``custom`` route or keeps the provider's real identity: it preserves
- # identity for any first-class provider (via
- # _preserve_provider_with_base_url, a provider-catalog capability check),
- # so provider branches that add auth refresh / request metadata /
- # request-shape adapters — anthropic OAuth (Bearer + anthropic-beta),
- # openai-codex Responses wrapping + Cloudflare headers, xai-oauth,
- # bedrock SigV4 signing, nous Portal tags — still fire. Those branches
- # re-resolve their own credentials by name and ignore a forwarded
- # base_url/api_key, so forwarding is safe even for a placeholder key
- # (bedrock's "aws-sdk"). We used to maintain a name-preservation set here
- # too; that duplicated the chokepoint and drifted out of sync, so the
- # single source of truth now lives in call_llm.
if rt.get("base_url"):
out["base_url"] = rt["base_url"]
if rt.get("api_key"):
@@ -362,7 +380,14 @@ def _slot_runtime(slot: dict[str, Any]) -> dict[str, Any]:
if isinstance(extra_body, dict) and extra_body:
out["extra_body"] = dict(extra_body)
except Exception as exc: # pragma: no cover - defensive
- logger.debug("MoA slot runtime resolution failed for %s: %s", _slot_label(slot), exc)
+ logger.debug("MoA slot runtime resolution failed for %s: %s",
+ _slot_label(slot), exc)
+ # Never cache a fallback-shaped result: a transient resolution error
+ # (config mid-write, catalog hiccup) would otherwise pin the bare
+ # provider/model kwargs for a full TTL.
+ return out
+ with _runtime_cache_lock:
+ _runtime_cache[cache_key] = (now, out)
return out
@@ -1830,11 +1855,35 @@ class MoAChatCompletions:
raise TypeError("_moa_prepared_request must be a dict")
return self._call_prepared_aggregator(prepared_request, api_kwargs)
- from hermes_cli.config import load_config
+ from hermes_cli.config import get_config_path, load_config
from hermes_cli.moa_config import resolve_moa_preset
+ # Resolve the preset once per (config st_mtime_ns, preset_name).
+ # resolve_moa_preset re-normalizes + re-validates the whole moa
+ # config block on every call, and create() runs once per tool-loop
+ # iteration — a serial cold-start cost before the parallel fan-out
+ # can begin (#66793). Keyed on the config FILE's mtime_ns (not a
+ # config-object attribute, which load_config()'s dicts don't carry),
+ # so a config edit invalidates on the next call.
+ try:
+ _cfg_stamp = get_config_path().stat().st_mtime_ns
+ except OSError:
+ _cfg_stamp = None
+ # load_config() is itself (mtime_ns, size)-cached upstream, so this
+ # read is cheap; the expensive part this cache skips is
+ # resolve_moa_preset's re-normalization + re-validation.
_moa_raw = load_config().get("moa") or {}
- preset = resolve_moa_preset(_moa_raw, self.preset_name)
+ preset_cache_key = (_cfg_stamp, self.preset_name)
+ preset = None
+ if _cfg_stamp is not None:
+ with _preset_cache_lock:
+ preset = _preset_cache.get(preset_cache_key)
+ if preset is None:
+ preset = resolve_moa_preset(_moa_raw, self.preset_name)
+ if _cfg_stamp is not None:
+ with _preset_cache_lock:
+ _preset_cache.clear() # one live config stamp at a time
+ _preset_cache[preset_cache_key] = preset
# Privacy filter mode: '' (off, default) | 'display' | 'full'. See
# coerce_privacy_filter / the pattern block at the top of this module.
# Remembered on self so _call_prepared_aggregator (which may run on a
diff --git a/tests/agent/test_moa_cold_start_cache_66793.py b/tests/agent/test_moa_cold_start_cache_66793.py
new file mode 100644
index 00000000000..96e5a2bbc75
--- /dev/null
+++ b/tests/agent/test_moa_cold_start_cache_66793.py
@@ -0,0 +1,226 @@
+"""Regression tests for MoA cold-start caching (#66793).
+
+The preset switch used to re-parse + re-validate the full config and
+re-resolve every slot's provider runtime on EACH create() call (once
+per tool-loop iteration), serially before the parallel fan-out could
+begin — 5-30s of "frozen" latency on complex presets.
+Both the resolved preset and each (provider, model) runtime are now
+cached for the process lifetime (config is immutable per turn), so the
+underlying ``resolve_runtime_provider`` (real provider-catalog I/O)
+runs once per distinct slot, not once per create() iteration.
+"""
+
+import types # noqa: F401 (used by _fake_response)
+
+import pytest
+
+
+def _make_preset_config() -> dict:
+ return {
+ "moa": {
+ "default_preset": "demo",
+ "presets": {
+ "demo": {
+ "enabled": True,
+ "aggregator": {"provider": "openai", "model": "gpt-5"},
+ "reference_models": [
+ {"provider": "deepseek", "model": "deepseek-v4"},
+ {"provider": "minimax", "model": "minimax-m3"},
+ ],
+ }
+ },
+ }
+ }
+
+
+def test_preset_resolution_is_cached_across_create_calls(monkeypatch, tmp_path):
+ """resolve_moa_preset must run once per (config-mtime, preset_name),
+ not on every create() iteration."""
+ import agent.moa_loop as moa
+
+ moa._preset_cache.clear()
+
+ calls = {"n": 0}
+ import hermes_cli.moa_config as moa_cfg_mod
+ real_resolve = moa_cfg_mod.resolve_moa_preset
+
+ def counting_resolve(config, name=None):
+ calls["n"] += 1
+ return real_resolve(config, name)
+
+ monkeypatch.setattr(moa_cfg_mod, "resolve_moa_preset", counting_resolve)
+ import hermes_cli.config as cfg_mod
+ # The cache keys on the config FILE's st_mtime_ns — give the test a real
+ # stat-able file (no config file -> stamp=None -> caching fails open).
+ cfg_file = tmp_path / "config.yaml"
+ cfg_file.write_text("moa: {}\n")
+ monkeypatch.setattr(cfg_mod, "get_config_path", lambda: cfg_file)
+ monkeypatch.setattr(cfg_mod, "load_config", lambda: _make_preset_config())
+ monkeypatch.setattr(moa, "call_llm", lambda **k: _fake_response())
+
+ cc = moa.MoAChatCompletions("demo")
+ for _ in range(3):
+ cc.create(messages=[{"role": "user", "content": "hi"}])
+
+ # One preset resolution for the whole turn (not 3).
+ assert calls["n"] == 1, f"expected 1 preset resolution, got {calls['n']}"
+
+
+def test_preset_cache_invalidates_on_config_edit(monkeypatch, tmp_path):
+ """Editing config.yaml must invalidate the preset cache on the next
+ create() — the original PR keyed on a nonexistent config-object mtime
+ attribute, which never invalidated (review finding)."""
+ import os
+
+ import agent.moa_loop as moa
+
+ moa._preset_cache.clear()
+
+ calls = {"n": 0}
+ import hermes_cli.moa_config as moa_cfg_mod
+ real_resolve = moa_cfg_mod.resolve_moa_preset
+
+ def counting_resolve(config, name=None):
+ calls["n"] += 1
+ return real_resolve(config, name)
+
+ monkeypatch.setattr(moa_cfg_mod, "resolve_moa_preset", counting_resolve)
+ import hermes_cli.config as cfg_mod
+ cfg_file = tmp_path / "config.yaml"
+ cfg_file.write_text("moa: {}\n")
+ monkeypatch.setattr(cfg_mod, "get_config_path", lambda: cfg_file)
+ monkeypatch.setattr(cfg_mod, "load_config", lambda: _make_preset_config())
+ monkeypatch.setattr(moa, "call_llm", lambda **k: _fake_response())
+
+ cc = moa.MoAChatCompletions("demo")
+ cc.create(messages=[{"role": "user", "content": "hi"}])
+ assert calls["n"] == 1
+
+ # Simulate a config edit: bump the file's mtime past ns resolution.
+ st = cfg_file.stat()
+ os.utime(cfg_file, ns=(st.st_atime_ns, st.st_mtime_ns + 1_000_000))
+
+ cc.create(messages=[{"role": "user", "content": "hi"}])
+ assert calls["n"] == 2, "config edit must invalidate the preset cache"
+
+
+def test_no_config_file_fails_open(monkeypatch, tmp_path):
+ """No config.yaml (stat raises) -> caching disabled, create() still works."""
+ import agent.moa_loop as moa
+
+ moa._preset_cache.clear()
+
+ import hermes_cli.config as cfg_mod
+ monkeypatch.setattr(
+ cfg_mod, "get_config_path", lambda: tmp_path / "missing.yaml"
+ )
+ monkeypatch.setattr(cfg_mod, "load_config", lambda: _make_preset_config())
+ monkeypatch.setattr(moa, "call_llm", lambda **k: _fake_response())
+
+ cc = moa.MoAChatCompletions("demo")
+ cc.create(messages=[{"role": "user", "content": "hi"}])
+ assert moa._preset_cache == {}, "must not cache under a None stamp"
+
+
+def test_slot_runtime_is_cached_across_create_calls(monkeypatch, tmp_path):
+ """resolve_runtime_provider (real I/O) must run once per
+ (provider, model) across all create() iterations, not per call."""
+ import agent.moa_loop as moa
+
+ moa._runtime_cache.clear()
+ moa._preset_cache.clear()
+
+ calls = {"n": 0}
+
+ def counting_resolve(*a, **k):
+ calls["n"] += 1
+ return {"base_url": None, "api_key": None, "api_mode": None}
+
+ import hermes_cli.runtime_provider as rt_mod
+ monkeypatch.setattr(rt_mod, "resolve_runtime_provider", counting_resolve)
+ import hermes_cli.config as cfg_mod
+ cfg_file = tmp_path / "config.yaml"
+ cfg_file.write_text("moa: {}\n")
+ monkeypatch.setattr(cfg_mod, "get_config_path", lambda: cfg_file)
+ monkeypatch.setattr(cfg_mod, "load_config", lambda: _make_preset_config())
+ monkeypatch.setattr(moa, "call_llm", lambda **k: _fake_response())
+
+ cc = moa.MoAChatCompletions("demo")
+ for _ in range(2):
+ cc.create(messages=[{"role": "user", "content": "hi"}])
+
+ # aggregator(1) + 2 references = 3 distinct slots, resolved once
+ # each regardless of 2 create() iterations.
+ assert calls["n"] == 3, f"expected 3 slot resolutions, got {calls['n']}"
+
+
+def test_slot_runtime_cache_expires_after_ttl(monkeypatch):
+ """A stale runtime entry (key rotation window) must re-resolve after
+ the TTL — the original PR cached for the process lifetime, pinning
+ rotated credentials forever (review finding)."""
+ import agent.moa_loop as moa
+
+ moa._runtime_cache.clear()
+
+ calls = {"n": 0}
+
+ def counting_resolve(*a, **k):
+ calls["n"] += 1
+ return {"base_url": "http://x", "api_key": f"key-{calls['n']}",
+ "api_mode": None}
+
+ import hermes_cli.runtime_provider as rt_mod
+ monkeypatch.setattr(rt_mod, "resolve_runtime_provider", counting_resolve)
+
+ slot = {"provider": "openai", "model": "gpt-5"}
+ first = moa._slot_runtime(slot)
+ assert calls["n"] == 1 and first["api_key"] == "key-1"
+
+ # Within TTL: cached.
+ assert moa._slot_runtime(slot)["api_key"] == "key-1"
+ assert calls["n"] == 1
+
+ # Age the entry past the TTL and confirm re-resolution.
+ key = ("openai", "gpt-5")
+ stamped_at, cached = moa._runtime_cache[key]
+ moa._runtime_cache[key] = (
+ stamped_at - moa._RUNTIME_CACHE_TTL_SECONDS - 1, cached
+ )
+ assert moa._slot_runtime(slot)["api_key"] == "key-2"
+ assert calls["n"] == 2
+
+
+def test_slot_runtime_resolution_error_is_not_cached(monkeypatch):
+ """A transient resolution failure must not pin the bare-kwargs fallback
+ for a TTL — the next call must retry the real resolver."""
+ import agent.moa_loop as moa
+
+ moa._runtime_cache.clear()
+
+ calls = {"n": 0}
+
+ def flaky_resolve(*a, **k):
+ calls["n"] += 1
+ if calls["n"] == 1:
+ raise RuntimeError("catalog hiccup")
+ return {"base_url": "http://ok", "api_key": None, "api_mode": None}
+
+ import hermes_cli.runtime_provider as rt_mod
+ monkeypatch.setattr(rt_mod, "resolve_runtime_provider", flaky_resolve)
+
+ slot = {"provider": "openai", "model": "gpt-5"}
+ fallback = moa._slot_runtime(slot)
+ assert "base_url" not in fallback # bare kwargs on error
+ assert moa._runtime_cache == {}, "error result must not be cached"
+
+ recovered = moa._slot_runtime(slot)
+ assert recovered.get("base_url") == "http://ok"
+ assert calls["n"] == 2
+
+
+# ─── test harness helpers ──────────────────────────────────────────────
+
+def _fake_response():
+ ns = types.SimpleNamespace()
+ ns.usage = None
+ return ns
diff --git a/tests/conftest.py b/tests/conftest.py
index 672723a6d91..26c034edc96 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -1449,3 +1449,22 @@ def _isolate_computer_use_approval_state():
_cu_tool._session_auto_approve.clear()
except Exception:
pass
+
+
[email protected](autouse=True)
+def _moa_caches_isolated():
+ """Clear module-level MoA cold-start caches before each test.
+
+ ``agent.moa_loop`` caches the resolved preset and each slot's provider
+ runtime at module level (keyed on config mtime / provider+model) so the
+ tool loop doesn't re-resolve them serially on every iteration. Tests
+ monkeypatch resolvers and config paths, so a cache entry leaked from one
+ test would poison the next. Clear both around every test.
+ """
+ import agent.moa_loop as moa
+
+ moa._preset_cache.clear()
+ moa._runtime_cache.clear()
+ yield
+ moa._preset_cache.clear()
+ moa._runtime_cache.clear()