The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(aux): the runtime-main lookup reads only the context variable
kshitijk4poor57d491383b3c
diff --git a/agent/auxiliary_client.py b/agent/auxiliary_client.pyindex c5fbb661f55..6815b645587 100644--- a/agent/auxiliary_client.py+++ b/agent/auxiliary_client.py@@ -2521,14 +2521,7 @@ def _read_main_api_key_if_same_origin(aux_base_url: str) -> str | Callable[[], sreturn _read_main_api_key()-# Compatibility mirrors for older readers/tests; the ContextVar below is-# authoritative (overlapping gateway sessions make a process-global unsafe).-_RUNTIME_MAIN_PROVIDER: str = ""-_RUNTIME_MAIN_MODEL: str = ""-_RUNTIME_MAIN_BASE_URL: str = ""-_RUNTIME_MAIN_API_KEY: Any = ""-_RUNTIME_MAIN_API_MODE: str = ""-_RUNTIME_MAIN_AUTH_MODE: str = ""+# The live main runtime, per context: overlapping gateway sessions make a process-global unsafe._RUNTIME_MAIN_CONTEXT: contextvars.ContextVar[Optional[dict[str, Any]]] = (contextvars.ContextVar("auxiliary_runtime_main", default=None))@@ -2711,40 +2704,9 @@ def _relay_sync_stream()-_RUNTIME_MAIN_COMPAT_SNAPSHOT: tuple[Any, ...] = ("", "", "", "", "", "")-_RUNTIME_MAIN_COMPAT_LOCK = threading.Lock()---def _publish_runtime_main_mirrors(values: tuple[Any, ...]) -> None:- """Write the legacy globals + compat snapshot (``_MAIN_RUNTIME_FIELDS`` order) under the lock."""- global _RUNTIME_MAIN_PROVIDER, _RUNTIME_MAIN_MODEL, _RUNTIME_MAIN_BASE_URL, _RUNTIME_MAIN_API_KEY- global _RUNTIME_MAIN_API_MODE, _RUNTIME_MAIN_AUTH_MODE, _RUNTIME_MAIN_COMPAT_SNAPSHOT- with _RUNTIME_MAIN_COMPAT_LOCK:- (_RUNTIME_MAIN_PROVIDER, _RUNTIME_MAIN_MODEL, _RUNTIME_MAIN_BASE_URL,- _RUNTIME_MAIN_API_KEY, _RUNTIME_MAIN_API_MODE, _RUNTIME_MAIN_AUTH_MODE) = values- _RUNTIME_MAIN_COMPAT_SNAPSHOT = tuple(values)---def _compat_runtime_main() -> Optional[dict[str, Any]]:- """Expose deliberately patched legacy globals as a main context.-- Mirrors must never become runtime inputs: a direct patch counts only when it differs from- the mirrored snapshot and only on the main thread.- """- if threading.current_thread() is not threading.main_thread():- return None- values = (_RUNTIME_MAIN_PROVIDER, _RUNTIME_MAIN_MODEL, _RUNTIME_MAIN_BASE_URL,- _RUNTIME_MAIN_API_KEY, _RUNTIME_MAIN_API_MODE, _RUNTIME_MAIN_AUTH_MODE)- if values == _RUNTIME_MAIN_COMPAT_SNAPSHOT:- return None- return dict(zip(_MAIN_RUNTIME_FIELDS, values))--def _runtime_main_value(field: str) -> Any:- """Read one runtime field through context-local/controlled legacy state."""+ """Read one field of the current context's main runtime ("" when unbound)."""runtime = _RUNTIME_MAIN_CONTEXT.get()- if runtime is None:- runtime = _compat_runtime_main()return (runtime.get(field) or "") if isinstance(runtime, dict) else ""@@ -2755,9 +2717,7 @@ def set_runtime_main() -> contextvars.Token:"""Record the current context's live main runtime for auxiliary routing.- Context-local so concurrent gateway sessions don't clobber each other; legacy mirrors are- updated for old readers. ``cache_scope`` is the rotation-stable logical cache scope,- preferred over ``session_id`` for prompt_cache_key derivation.+ Context-local so concurrent gateway sessions don't clobber each other.``cache_scope`` is the rotation-stable logical cache scope (compression- lineage root —agent/prompt_cache_scope.py) resolved once per turn by turn_context; auxiliary Responses calls prefer it@@ -2774,10 +2734,7 @@ def set_runtime_main("session_id": (session_id or "").strip(),"cache_scope": (cache_scope or "").strip(),}- # Publish authoritative context before updating the locked mirrors.- token = _RUNTIME_MAIN_CONTEXT.set(runtime)- _publish_runtime_main_mirrors(tuple(runtime[field] for field in _MAIN_RUNTIME_FIELDS))- return token+ return _RUNTIME_MAIN_CONTEXT.set(runtime)def reset_runtime_main(token: contextvars.Token) -> None:@@ -2792,7 +2749,7 @@ def reset_runtime_main(token: contextvars.Token) -> None:@contextlib.contextmanagerdef scoped_runtime_main(main_runtime: Optional[dict[str, Any]]):- """Temporarily bind an explicit runtime without touching legacy mirrors."""+ """Temporarily bind an explicit runtime for the current context."""runtime = _normalize_main_runtime(main_runtime)token = _RUNTIME_MAIN_CONTEXT.set(runtime or None)try:@@ -2804,7 +2761,6 @@ def scoped_runtime_main(main_runtime: Optional[dict[str, Any]]):def clear_runtime_main() -> None:"""Clear the runtime override in the current context."""_RUNTIME_MAIN_CONTEXT.set(None)- _publish_runtime_main_mirrors(("", "", "", "", "", ""))def _resolve_custom_runtime() -> tuple[Optional[str], Optional[str], Optional[str]]:@@ -3104,10 +3060,7 @@ def _normalize_main_runtime(main_runtime: Optional[dict[str, Any]]) -> dict[str,— preserved as-is so aux clients share main-agent auth."""if main_runtime is None:- # Context-local state first; compat mirrors may hold another concurrent session's endpoint/key.main_runtime = _RUNTIME_MAIN_CONTEXT.get()- if main_runtime is None:- main_runtime = _compat_runtime_main()if not isinstance(main_runtime, dict):return {}normalized: dict[str, Any] = {}diff --git a/agent/auxiliary_key_rotation.py b/agent/auxiliary_key_rotation.pyindex eb365f90264..f3c50c23445 100644--- a/agent/auxiliary_key_rotation.py+++ b/agent/auxiliary_key_rotation.py@@ -16,8 +16,6 @@ def rotate_runtime_main_api_key(old: Any, new: Any) -> None:"""from agent.auxiliary_client import _RUNTIME_MAIN_CONTEXT, _normalize_api_key- # The legacy mirrors are left alone: _compat_runtime_main() ignores them while they equal the compat- # snapshot, and republishing from here cannot tell which runtime published them.runtime = _RUNTIME_MAIN_CONTEXT.get()if isinstance(runtime, dict) and runtime.get("api_key") == old:runtime["api_key"] = _normalize_api_key(new)diff --git a/tests/agent/test_anthropic_third_party_oauth_guard.py b/tests/agent/test_anthropic_third_party_oauth_guard.pyindex c84f1b40a3c..84bfb79d7e6 100644--- a/tests/agent/test_anthropic_third_party_oauth_guard.py+++ b/tests/agent/test_anthropic_third_party_oauth_guard.py@@ -205,12 +205,11 @@ class TestOAuthFlagOnRefresh:"anthropic", agent.model, runtime.get("base_url", ""), runtime.get("api_key"), "anthropic_messages",)assert seen["api_key"] == new- # A scoped runtime rotates in place; the legacy mirrors are never republished by a rotation.+ # A scoped runtime rotates in place and leaves the outer binding alone.with aux.scoped_runtime_main({"provider": "anthropic", "api_key": new, "model": "m"}):rotate_runtime_main_api_key(new, "sk-ant...cccc")assert aux._RUNTIME_MAIN_CONTEXT.get()["api_key"] == "sk-ant...cccc"- assert (aux._RUNTIME_MAIN_MODEL, aux._RUNTIME_MAIN_API_KEY) == (agent.model, old)- assert aux._compat_runtime_main() is None # unchanged mirrors never become a runtime input+ assert aux._normalize_main_runtime(None).get("api_key") == newfinally:aux.clear_runtime_main()diff --git a/tests/agent/test_aux_runtime_main_context_only.py b/tests/agent/test_aux_runtime_main_context_only.pynew file mode 100644index 00000000000..6e272fb575f--- /dev/null+++ b/tests/agent/test_aux_runtime_main_context_only.py@@ -0,0 +1,59 @@+"""The auxiliary client's main runtime lives only in a context variable (Code Health PRV-09).++The process-global mirrors (``_RUNTIME_MAIN_PROVIDER`` and friends) were rewritten by every+session in the process, and a main-thread lookup with no context binding fell back to them. The+six fields were stored one at a time, unlocked for readers, so that fallback could return another+session's runtime, or one session's base_url paired with another's api_key. The+``auxiliary_is_nous`` flag was likewise written by every session and read by nothing.+"""++import threading++import agent.auxiliary_client as aux++_DELETED = (+ "auxiliary_is_nous",+ "get_auxiliary_extra_body",+ "_RUNTIME_MAIN_PROVIDER",+ "_RUNTIME_MAIN_MODEL",+ "_RUNTIME_MAIN_BASE_URL",+ "_RUNTIME_MAIN_API_KEY",+ "_RUNTIME_MAIN_API_MODE",+ "_RUNTIME_MAIN_AUTH_MODE",+ "_RUNTIME_MAIN_COMPAT_SNAPSHOT",+ "_RUNTIME_MAIN_COMPAT_LOCK",+ "_publish_runtime_main_mirrors",+ "_compat_runtime_main",+)+++def test_no_process_global_runtime_state():+ assert [name for name in _DELETED if hasattr(aux, name)] == []+++def test_a_binding_on_another_thread_never_reaches_this_one():+ aux.clear_runtime_main()+ bound = threading.Event()++ def other_session():+ aux.set_runtime_main(+ "custom", "other-model", base_url="https://other.example/v1", api_key="sk-other",+ )+ assert aux._runtime_main_value("base_url") == "https://other.example/v1"+ bound.set()++ worker = threading.Thread(target=other_session)+ worker.start()+ worker.join()++ assert bound.is_set()+ assert aux._normalize_main_runtime(None) == {}+ assert aux._runtime_main_value("base_url") == ""+ assert aux._runtime_main_value("api_key") == ""+++def test_scoped_binding_is_visible_inside_and_gone_after():+ aux.clear_runtime_main()+ with aux.scoped_runtime_main({"base_url": "https://scoped.example/v1", "api_key": "sk-scoped"}):+ assert aux._runtime_main_value("base_url") == "https://scoped.example/v1"+ assert aux._runtime_main_value("base_url") == ""diff --git a/tests/agent/test_auxiliary_client.py b/tests/agent/test_auxiliary_client.pyindex d8ded60d535..8cf0d36155e 100644--- a/tests/agent/test_auxiliary_client.py+++ b/tests/agent/test_auxiliary_client.py@@ -4830,8 +4830,8 @@ class TestCustomEndpointApiKeyInheritance:def test_runtime_override_key_is_used(self, monkeypatch):- """When _RUNTIME_MAIN_API_KEY is set (by set_runtime_main), it takes- precedence over config.yaml for the custom endpoint key."""+ """A key bound by set_runtime_main takes precedence over config.yaml+ for the custom endpoint key."""import agent.auxiliary_client as acmonkeypatch.delenv("OPENAI_API_KEY", raising=False)@@ -4842,8 +4842,7 @@ class TestCustomEndpointApiKeyInheritance:captured.update(kwargs)return MagicMock()- with patch.object(ac, "_RUNTIME_MAIN_API_KEY", "sk-runtime-key"), \- patch.object(ac, "_RUNTIME_MAIN_BASE_URL", "https://gw.example.com/v1"), \+ with ac.scoped_runtime_main({"base_url": "https://gw.example.com/v1", "api_key": "sk-runtime-key"}), \patch("hermes_cli.config.load_config", return_value={"model": {}}), patch("hermes_cli.config.load_config_readonly", return_value={"model": {}}), \patch.object(ac, "_create_openai_client", side_effect=_capture_create):_client, _model = resolve_provider_client(diff --git a/tests/agent/test_auxiliary_main_first.py b/tests/agent/test_auxiliary_main_first.pyindex 4e67b83e511..d951475980a 100644--- a/tests/agent/test_auxiliary_main_first.py+++ b/tests/agent/test_auxiliary_main_first.py@@ -403,15 +403,11 @@ class TestResolveVisionCustomProvider:``set_runtime_main()`` recorded for the turn."""- def test_custom_main_forwards_runtime_endpoint(self, monkeypatch):+ def test_custom_main_forwards_runtime_endpoint(self):"""custom main with recorded runtime endpoint → Step 1 builds a client."""import agent.auxiliary_client as aux- monkeypatch.setattr(aux, "_RUNTIME_MAIN_BASE_URL", "https://my.endpoint.example/v1")- monkeypatch.setattr(aux, "_RUNTIME_MAIN_API_KEY", "sk-runtime-key")- monkeypatch.setattr(aux, "_RUNTIME_MAIN_API_MODE", "anthropic_messages")-- with patch(+ with aux.scoped_runtime_main({"base_url": "https://my.endpoint.example/v1", "api_key": "sk-runtime-key", "api_mode": "anthropic_messages"}), patch("agent.auxiliary_client._read_main_provider", return_value="custom",), patch("agent.auxiliary_client._read_main_model", return_value="claude-opus-4-8",@@ -438,15 +434,11 @@ class TestResolveVisionCustomProvider:assert kwargs.get("explicit_api_key") == "sk-runtime-key"assert kwargs.get("is_vision") is True- def test_custom_prefixed_main_forwards_runtime_endpoint(self, monkeypatch):+ def test_custom_prefixed_main_forwards_runtime_endpoint(self):"""A ``custom:<name>`` provider id also forwards the runtime endpoint."""import agent.auxiliary_client as aux- monkeypatch.setattr(aux, "_RUNTIME_MAIN_BASE_URL", "https://named.example/v1")- monkeypatch.setattr(aux, "_RUNTIME_MAIN_API_KEY", "sk-named")- monkeypatch.setattr(aux, "_RUNTIME_MAIN_API_MODE", "")-- with patch(+ with aux.scoped_runtime_main({"base_url": "https://named.example/v1", "api_key": "sk-named"}), patch("agent.auxiliary_client._read_main_provider",return_value="custom:copilot-gateway",), patch(@@ -471,15 +463,11 @@ class TestResolveVisionCustomProvider:assert kwargs.get("explicit_api_key") == "sk-named"assert kwargs.get("is_vision") is True- def test_custom_main_no_runtime_falls_back_to_configured_endpoint(self, monkeypatch):+ def test_custom_main_no_runtime_falls_back_to_configured_endpoint(self):"""No recorded runtime endpoint → resolve the configured custom endpoint."""import agent.auxiliary_client as aux- monkeypatch.setattr(aux, "_RUNTIME_MAIN_BASE_URL", "")- monkeypatch.setattr(aux, "_RUNTIME_MAIN_API_KEY", "")- monkeypatch.setattr(aux, "_RUNTIME_MAIN_API_MODE", "")-- with patch(+ with aux.scoped_runtime_main({}), patch("agent.auxiliary_client._read_main_provider", return_value="custom",), patch("agent.auxiliary_client._read_main_model", return_value="claude-opus-4-8",diff --git a/tests/conftest.py b/tests/conftest.pyindex 93b78ebdae0..9203402a4a5 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -1454,49 +1454,30 @@ def _isolate_computer_use_approval_state():pass-def _aux_runtime_main_mirrors(aux) -> dict:- """The legacy ``_RUNTIME_MAIN_*`` globals set_runtime_main publishes (not the ContextVar or lock)."""- return {- name: value for name, value in vars(aux).items()- if name.startswith("_RUNTIME_MAIN_")- and name not in ("_RUNTIME_MAIN_CONTEXT", "_RUNTIME_MAIN_COMPAT_LOCK")- }--@pytest.fixture(autouse=True)def _restore_aux_runtime_main():"""Restore the auxiliary client's main-runtime binding after every test.``build_turn_context`` binds the turn's main route with- ``agent.auxiliary_client.set_runtime_main`` in a ContextVar and publishes- it to the legacy ``_RUNTIME_MAIN_*`` mirrors. Production turns each run in- their own context; a single pytest process runs every test in one, so a- fake agent's route outlives its test and later tests' auxiliary routing- treats it as the main model. For example, after+ ``agent.auxiliary_client.set_runtime_main`` in a ContextVar. Production+ turns each run in their own context; a single pytest process runs every+ test in one, so a fake agent's route outlives its test and later tests'+ auxiliary routing treats it as the main model. For example, after``test_api_content_row_addressed_backfill.py`` (which drives the prologuewith a fake ``test/model`` on OpenRouter), six tests in``test_auxiliary_main_first.py`` fail in the same process: a patchedcustom vision main resolves to openrouter. Snapshot/restore keeps bindingsmade by wider-scoped fixtures; a module first imported during the test- goes back to its import-time state; a near no-op otherwise.+ goes back to its import-time state; a near no-op otherwise. The binding is+ compared by identity, so a test that mutates a wider fixture's runtime dict+ in place (``rotate_runtime_main_api_key``) must restore it itself."""aux = sys.modules.get("agent.auxiliary_client")- before = None- if aux is not None:- before = (aux._RUNTIME_MAIN_CONTEXT.get(), _aux_runtime_main_mirrors(aux))+ before = aux._RUNTIME_MAIN_CONTEXT.get() if aux is not None else Noneyieldaux = sys.modules.get("agent.auxiliary_client")- if aux is None:- return- if before is None:- aux.clear_runtime_main()- return- context, mirrors = before- if aux._RUNTIME_MAIN_CONTEXT.get() is not context:- aux._RUNTIME_MAIN_CONTEXT.set(context)- for name, value in mirrors.items():- if getattr(aux, name) is not value:- setattr(aux, name, value)+ if aux is not None and aux._RUNTIME_MAIN_CONTEXT.get() is not before:+ aux._RUNTIME_MAIN_CONTEXT.set(before)@pytest.fixture(autouse=True)