Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions gateway/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -5991,6 +5991,10 @@ async def _on_model_selected(
"api_key": result.api_key,
"base_url": result.base_url,
"api_mode": result.api_mode,
# The new provider's credential pool — without
# this, future-turn rotation on 429 stays bound
# to the original provider's pool. See #16678.
"credential_pool": result.credential_pool,
}
Comment on lines +6000 to 6004

Copilot AI Apr 27, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These overrides now store credential_pool, which is not a str. However, _session_model_overrides is annotated and documented as Dict[str, Dict[str, str]] (and described as holding only model/provider/api_key/base_url/api_mode). Please update the type annotation (and the comment describing the override shape) to allow credential_pool (e.g., Dict[str, Dict[str, Any]] or a TypedDict with credential_pool: CredentialPool | None). This avoids misleading types and helps static analysis.

Copilot uses AI. Check for mistakes.

# Evict cached agent so the next turn creates a fresh
Expand Down Expand Up @@ -6119,6 +6123,9 @@ async def _on_model_selected(
"api_key": result.api_key,
"base_url": result.base_url,
"api_mode": result.api_mode,
# Carry the new provider's credential pool so future-turn 429
# rotation runs against the right pool (see #16678).
"credential_pool": result.credential_pool,
}

# Evict cached agent so the next turn creates a fresh agent from the
Expand Down Expand Up @@ -8915,6 +8922,12 @@ def _apply_session_model_override(
config.yaml defaults so the switched model is actually used for
subsequent messages. Fields with ``None`` values are skipped so
partial overrides don't clobber valid config defaults.

``credential_pool`` is the exception: a ``None`` override is a
legitimate "no pool for the new provider" signal, and leaving the
startup pool in place would let 429 rotation run against the
wrong provider's credentials (#16678). When the override carries
the key at all, it always wins — even when its value is ``None``.
"""
override = self._session_model_overrides.get(session_key)
if not override:
Expand All @@ -8924,6 +8937,8 @@ def _apply_session_model_override(
val = override.get(key)
if val is not None:
runtime_kwargs[key] = val
if "credential_pool" in override:
runtime_kwargs["credential_pool"] = override["credential_pool"]
return model, runtime_kwargs

def _is_intentional_model_switch(self, session_key: str, agent_model: str) -> bool:
Expand Down
17 changes: 16 additions & 1 deletion hermes_cli/model_switch.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
import logging
import re
from dataclasses import dataclass
from typing import List, NamedTuple, Optional
from typing import Any, List, NamedTuple, Optional

from hermes_cli.providers import (
custom_provider_slug,
Expand Down Expand Up @@ -241,6 +241,13 @@ class ModelSwitchResult:
capabilities: Optional[ModelCapabilities] = None
model_info: Optional[ModelInfo] = None
is_global: bool = False
# CredentialPool for the resolved target provider, when one was loaded.
# Callers that maintain runtime kwargs (e.g. the gateway session-override
# store) must propagate this so per-provider rotation continues to work
# after a /model switch — without it, a 429 on the new provider rotates
# within the original provider's pool (or skips rotation entirely and
# falls through to the configured fallback model). See #16678.
credential_pool: Optional[Any] = None

Copilot AI Apr 27, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ModelSwitchResult.credential_pool is typed as Optional[Any], but the runtime provider resolver returns a concrete CredentialPool (see hermes_cli/runtime_provider.py importing CredentialPool). Using Any loses type-safety and makes it harder for callers to know what’s expected. Consider typing this as Optional[CredentialPool] (or Optional["CredentialPool"] with a TYPE_CHECKING import) to document the contract and catch misuse.

Copilot uses AI. Check for mistakes.


@dataclass
Expand Down Expand Up @@ -811,6 +818,11 @@ def switch_model(
api_key = current_api_key
base_url = current_base_url
api_mode = ""
# Track the credential pool resolved for the *target* provider so the
# caller can wire it into runtime_kwargs / session overrides. Stays
# None if resolution fails or the provider has no pool — the caller
# treats that as "no rotation available", which is correct.
credential_pool: Optional[Any] = None

if provider_changed or explicit_provider:
try:
Expand All @@ -821,6 +833,7 @@ def switch_model(
api_key = runtime.get("api_key", "")
base_url = runtime.get("base_url", "")
api_mode = runtime.get("api_mode", "")
credential_pool = runtime.get("credential_pool")
except Exception as e:
return ModelSwitchResult(
success=False,
Expand All @@ -846,6 +859,7 @@ def switch_model(
api_key = runtime.get("api_key", "")
base_url = runtime.get("base_url", "")
api_mode = runtime.get("api_mode", "")
credential_pool = runtime.get("credential_pool")
except Exception:
pass

Expand Down Expand Up @@ -966,6 +980,7 @@ def switch_model(
capabilities=capabilities,
model_info=model_info,
is_global=is_global,
credential_pool=credential_pool,
)


Expand Down
115 changes: 115 additions & 0 deletions tests/gateway/test_session_model_override_routing.py
Original file line number Diff line number Diff line change
Expand Up @@ -163,3 +163,118 @@ async def test_background_task_prefers_session_override_over_global_runtime(monk
assert _CapturingAgent.last_init["base_url"] == "https://chatgpt.com/backend-api/codex"
assert _CapturingAgent.last_init["api_key"] == "***"
assert _CapturingAgent.last_init["reasoning_config"] == {"enabled": True, "effort": "high"}


# ---------------------------------------------------------------------------
# credential_pool propagation (#16678)
#
# Without the override carrying credential_pool, /model switching to a new
# provider in the gateway leaves runtime_kwargs["credential_pool"] pointing
# at the *original* provider's pool — so a 429 on the new provider rotates
# (or fails to rotate) against the wrong provider's credentials, and the
# session falls through to the configured fallback model instead of
# rotating to the next credential on the new provider.
# ---------------------------------------------------------------------------


def test_apply_session_model_override_propagates_credential_pool():
"""An override-supplied credential_pool overwrites the global one."""
runner = _make_runner()
session_key = "agent:main:local:dm"

new_pool = MagicMock(name="new_provider_pool")
runner._session_model_overrides[session_key] = {
"model": "gpt-5.4",
"provider": "openai-codex",
"api_key": "***",
"base_url": "https://chatgpt.com/backend-api/codex",
"api_mode": "codex_responses",
"credential_pool": new_pool,
}

old_pool = MagicMock(name="old_provider_pool")
runtime_kwargs = {
"api_key": "old-key",
"base_url": "https://api.old.example",
"provider": "anthropic",
"api_mode": "anthropic_messages",
"credential_pool": old_pool,
}

model, kwargs = gateway_run.GatewayRunner._apply_session_model_override(
runner, session_key, "claude-sonnet", runtime_kwargs
)

assert model == "gpt-5.4"
assert kwargs["provider"] == "openai-codex"
# Critical assertion — without the fix this would still be ``old_pool``.
assert kwargs["credential_pool"] is new_pool


def test_apply_session_model_override_replaces_pool_with_none():
"""An explicit ``credential_pool: None`` clears the prior pool.

A switched-to provider may legitimately have no pool (e.g. only an env
var key configured). Skipping ``None`` would leave the original
provider's pool live and rotate against the wrong credentials on 429.
"""
runner = _make_runner()
session_key = "agent:main:local:dm"

runner._session_model_overrides[session_key] = {
"model": "gpt-5.4",
"provider": "openai-codex",
"api_key": "***",
"base_url": "https://chatgpt.com/backend-api/codex",
"api_mode": "codex_responses",
"credential_pool": None,
}

runtime_kwargs = {
"api_key": "old-key",
"base_url": "https://api.old.example",
"provider": "anthropic",
"api_mode": "anthropic_messages",
"credential_pool": MagicMock(name="old_provider_pool"),
}

_model, kwargs = gateway_run.GatewayRunner._apply_session_model_override(
runner, session_key, "claude-sonnet", runtime_kwargs
)

assert kwargs["credential_pool"] is None


def test_apply_session_model_override_omitting_pool_keeps_existing():
"""A pre-fix override (no ``credential_pool`` key) is left alone.

Older callers (and persisted overrides, if any) may not carry the
new key at all. Those should keep the existing runtime pool — not
blank it — so we don't regress sessions that never switched provider.
"""
runner = _make_runner()
session_key = "agent:main:local:dm"

runner._session_model_overrides[session_key] = {
"model": "gpt-5.4",
"provider": "openai-codex",
"api_key": "***",
"base_url": "https://chatgpt.com/backend-api/codex",
"api_mode": "codex_responses",
# credential_pool intentionally omitted (legacy override shape)
}

existing_pool = MagicMock(name="existing_pool")
runtime_kwargs = {
"api_key": "old-key",
"base_url": "https://api.old.example",
"provider": "anthropic",
"api_mode": "anthropic_messages",
"credential_pool": existing_pool,
}

_model, kwargs = gateway_run.GatewayRunner._apply_session_model_override(
runner, session_key, "claude-sonnet", runtime_kwargs
)

assert kwargs["credential_pool"] is existing_pool
145 changes: 145 additions & 0 deletions tests/hermes_cli/test_model_switch_credential_pool.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
"""Regression tests for credential_pool propagation through switch_model.

The shared /model pipeline (``hermes_cli.model_switch.switch_model``) calls
``resolve_runtime_provider()`` for the target provider, which returns the
provider's credential pool alongside ``api_key`` / ``base_url`` / ``api_mode``.
Historically the pool was discarded, so the gateway's session-override
machinery had nothing to propagate — leaving the original provider's pool
live across a /model switch (#16678).

These tests pin the contract: ``ModelSwitchResult.credential_pool`` carries
the resolved pool for the target provider on both the explicit-provider
path and the same-provider re-resolve path.
"""

from unittest.mock import MagicMock

from hermes_cli.model_switch import switch_model


_MOCK_VALIDATION = {
"accepted": True,
"persist": True,
"recognized": True,
"message": None,
}


def _stub_model_metadata(monkeypatch):
monkeypatch.setattr(
"hermes_cli.models.validate_requested_model",
lambda *a, **k: _MOCK_VALIDATION,
)
monkeypatch.setattr("hermes_cli.model_switch.get_model_info", lambda *a, **k: None)
monkeypatch.setattr("hermes_cli.model_switch.get_model_capabilities", lambda *a, **k: None)


def test_switch_model_returns_credential_pool_on_explicit_provider(monkeypatch):
"""Explicit --provider switch must surface the new provider's pool.

Without this, a 429 on the new provider rotates against the original
provider's pool (or skips rotation entirely) — see #16678.
"""
target_pool = MagicMock(name="codex_pool")

def _fake_resolve_runtime_provider(**kwargs):
assert kwargs["requested"] == "openai-codex"
return {
"api_key": "sk-codex",
"base_url": "https://chatgpt.com/backend-api/codex",
"api_mode": "codex_responses",
"provider": "openai-codex",
"credential_pool": target_pool,
}

monkeypatch.setattr(
"hermes_cli.runtime_provider.resolve_runtime_provider",
_fake_resolve_runtime_provider,
)
_stub_model_metadata(monkeypatch)

result = switch_model(
raw_input="gpt-5.4",
current_provider="anthropic",
current_model="claude-sonnet-4-6",
current_base_url="https://api.anthropic.com",
current_api_key="sk-ant-old",
explicit_provider="openai-codex",
)

assert result.success is True
assert result.target_provider == "openai-codex"
# Critical: the new provider's pool must round-trip through the result
# so the gateway can store it on the session override.
assert result.credential_pool is target_pool


def test_switch_model_returns_credential_pool_on_same_provider_reresolve(monkeypatch):
"""Same-provider switches still re-resolve runtime, including the pool.

Models that don't change provider still go through resolve_runtime_provider
so credential rotation / OpenCode base_url adjustments are picked up.
The pool returned by that call must surface in the result.
"""
pool = MagicMock(name="anthropic_pool")

def _fake_resolve_runtime_provider(**kwargs):
assert kwargs["requested"] == "anthropic"
return {
"api_key": "sk-ant-rotated",
"base_url": "https://api.anthropic.com",
"api_mode": "anthropic_messages",
"provider": "anthropic",
"credential_pool": pool,
}

monkeypatch.setattr(
"hermes_cli.runtime_provider.resolve_runtime_provider",
_fake_resolve_runtime_provider,
)
_stub_model_metadata(monkeypatch)

result = switch_model(
raw_input="claude-opus-4-7",
current_provider="anthropic",
current_model="claude-sonnet-4-6",
current_base_url="https://api.anthropic.com",
current_api_key="sk-ant-old",
)

assert result.success is True
assert result.target_provider == "anthropic"
assert result.credential_pool is pool


def test_switch_model_default_credential_pool_is_none(monkeypatch):
"""When runtime resolution yields no pool, the result carries None.

Some providers (single env-var key, custom local endpoints without a
saved pool) genuinely have no pool — the gateway override layer must
see ``None`` so it can clear the previous provider's pool rather than
leaving stale rotation in place.
"""
monkeypatch.setattr(
"hermes_cli.runtime_provider.resolve_runtime_provider",
lambda **kwargs: {
"api_key": "sk-codex",
"base_url": "https://chatgpt.com/backend-api/codex",
"api_mode": "codex_responses",
"provider": "openai-codex",
# No credential_pool key — older code paths sometimes omit it.
},
)
_stub_model_metadata(monkeypatch)

result = switch_model(
raw_input="gpt-5.4",
current_provider="anthropic",
current_model="claude-sonnet-4-6",
current_base_url="https://api.anthropic.com",
current_api_key="sk-ant-old",
explicit_provider="openai-codex",
)

assert result.success is True
assert result.credential_pool is None
Loading