Skip to content

The agent that grows with you

test: chat error/fallback, Codex pooled-login and custom-row pricing E2E (KNOWN #121270 #120608 #120741 #120757)

teknium130012d900420
diff --git a/tests/e2e/core/providers/test_chat_errors.py b/tests/e2e/core/providers/test_chat_errors.py
new file mode 100644
index 00000000000..c909c1570aa
--- /dev/null
+++ b/tests/e2e/core/providers/test_chat_errors.py
@@ -0,0 +1,152 @@
+"""Chat-completions provider faults through REAL ``hermes -z`` processes.
+
+The vendor boundary is ``FakeChatVariantServer`` (a plain ``provider: custom``
+chat-completions endpoint); everything between the CLI and that socket is real Hermes.
+
+Proven here:
+
+* a 429 carrying ``Retry-After`` is retried after the advertised wait (not the generic
+ jittered backoff), in both directions: a long hint is honoured in full, a short hint
+ is not padded up to the backoff floor; the turn answers once;
+* a transient 503 is retried on the same endpoint and the turn answers once;
+* a stream that drops mid-tool-call is retried without executing the half-streamed call,
+ and the completed call runs EXACTLY once with exactly one persisted call/result pair;
+* an upstream account ban relayed as an ``error`` object inside an HTTP-200 SSE stream
+ fails the turn once, visibly, without a retry storm.
+"""
+
+from __future__ import annotations
+
+import json
+import sys
+
+import pytest
+
+from tests.e2e.core.providers._openai_helpers import (
+ Home,
+ custom_chat_config,
+ db_messages,
+ db_tool_calls,
+ oneshot,
+ tool_call_args,
+)
+from tests.fakes.providers.chat_variants import (
+ CDropToolCall,
+ CError,
+ CStreamError,
+ CText,
+ CTools,
+ FakeChatVariantServer,
+)
+
+pytestmark = pytest.mark.skipif(not sys.platform.startswith("linux"), reason="subprocess harness is Linux-gated")
+
+# Scenario -> "#issue one-line symptom" for scenarios red on origin/main. Strict: the test
+# FAILS the moment the bug is fixed, forcing the entry out.
+KNOWN: dict[str, str] = {
+ "in_stream_ban_fails_once": "#121270 in-stream error code 403 ignored: ban retried, reported as temporarily unavailable",
+}
+
+DOTENV = {"OPENAI_API_KEY": "sk-fake"}
+# Generic retry backoff for the first retry is jittered in [2.0, 3.0] s; the hints below
+# sit clearly on either side of that window so honouring vs ignoring them is observable.
+BACKOFF_FLOOR = 2.0
+EPSILON = 0.1
+
+
+def known(name: str) -> list:
+ """Marks for a scenario: a strict xfail while it is in KNOWN, nothing once fixed."""
+ return [pytest.mark.xfail(strict=True, raises=AssertionError, reason=KNOWN[name])] if name in KNOWN else []
+
+
+def _home(tmp_path, srv: FakeChatVariantServer, **config) -> Home:
+ cfg = custom_chat_config(srv.base_url)
+ cfg.update(config)
+ return Home(tmp_path).write(cfg, DOTENV)
+
+
+def _assistant_answers(h: Home, sid: str | None, text: str) -> list[dict]:
+ return [r for r in db_messages(h, sid) if r["role"] == "assistant" and text in (r.get("content") or "")]
+
+
[email protected]("retry_after", [
+ pytest.param(4.0, id="long_hint_honoured"),
+ pytest.param(0.5, id="short_hint_not_padded"),
+])
+def test_rate_limit_retry_waits_for_retry_after(tmp_path, retry_after: float) -> None:
+ script = [CError(429, "Rate limit exceeded, slow down", code="rate_limit_exceeded", retry_after=retry_after),
+ CText("AFTER-RATE-LIMIT")]
+ with FakeChatVariantServer(script) as srv:
+ h = _home(tmp_path, srv)
+ run = oneshot(h, "say hello")
+ records = srv.main_records()
+
+ assert run.proc.returncode == 0 and run.stdout.strip() == "AFTER-RATE-LIMIT", run.describe()
+ assert [r["response"] for r in records] == ["CError", "CText"], run.describe()
+ gap = records[1]["t"] - records[0]["t"]
+ assert gap >= retry_after - EPSILON, f"retried {gap:.2f}s after a 429 advertising Retry-After {retry_after}s"
+ if retry_after < BACKOFF_FLOOR:
+ assert gap < BACKOFF_FLOOR - EPSILON, f"short Retry-After {retry_after}s padded to {gap:.2f}s"
+ assert len(_assistant_answers(h, run.session_id, "AFTER-RATE-LIMIT")) == 1, db_messages(h, run.session_id)
+
+
+def test_service_unavailable_is_retried_on_same_endpoint(tmp_path) -> None:
+ script = [CError(503, "Service temporarily unavailable", code="service_unavailable"), CText("AFTER-503")]
+ with FakeChatVariantServer(script) as srv:
+ h = _home(tmp_path, srv)
+ run = oneshot(h, "say hello")
+ records = srv.main_records()
+
+ assert run.proc.returncode == 0 and run.stdout.strip() == "AFTER-503", run.describe()
+ assert [r["response"] for r in records] == ["CError", "CText"], run.describe()
+ # The retry resends the same conversation, not a truncated or mutated one.
+ assert records[1]["body"]["messages"] == records[0]["body"]["messages"]
+ assert run.usage.get("failed") is not True, run.describe()
+ assert len(_assistant_answers(h, run.session_id, "AFTER-503")) == 1, db_messages(h, run.session_id)
+
+
+def test_stream_drop_mid_tool_call_executes_tool_once(tmp_path) -> None:
+ command = "echo ran >> count.txt"
+ script = [CDropToolCall("terminal", partial_args='{"command": "echo ran >> cou'),
+ CTools([("terminal", {"command": command})]),
+ CText("TOOL-DONE")]
+ with FakeChatVariantServer(script) as srv:
+ h = _home(tmp_path, srv, approvals={"mode": "off"})
+ run = oneshot(h, "append a line to count.txt", env={"TERMINAL_ENV": "local"})
+ records = srv.main_records()
+
+ assert run.proc.returncode == 0 and run.stdout.strip() == "TOOL-DONE", run.describe()
+ assert [r["response"] for r in records] == ["CDropToolCall", "CTools", "CText"], run.describe()
+ count = h.project / "count.txt"
+ assert count.exists(), f"tool never ran: {run.describe()}"
+ assert count.read_text(encoding="utf-8").splitlines() == ["ran"], "side effect ran more than once"
+ # The dropped half-call never reaches the wire again: the retry resends the bare prompt.
+ assert [m["role"] for m in records[1]["body"]["messages"]] == [m["role"] for m in records[0]["body"]["messages"]]
+ rows = db_messages(h, run.session_id)
+ calls = db_tool_calls(rows)
+ results = [r for r in rows if r["role"] == "tool"]
+ assert [tool_call_args(c) for c in calls] == [{"command": command}], calls
+ assert [r["tool_call_id"] for r in results] == [calls[0]["id"]], results
+ # The final request replays exactly one call and exactly one matching result.
+ final = records[2]["body"]["messages"]
+ replayed = [tc for m in final if m.get("role") == "assistant" for tc in (m.get("tool_calls") or [])]
+ assert [tc["id"] for tc in replayed] == [m["tool_call_id"] for m in final if m.get("role") == "tool"], final
+
+
+BAN = {"code": 403, "message": "Your account has been banned by the upstream provider",
+ "metadata": {"provider_name": "UpstreamCo", "raw": json.dumps({"error": "account banned"})}}
+
+
[email protected]("_", [pytest.param(None, id="ban", marks=known("in_stream_ban_fails_once"))])
+def test_in_stream_upstream_ban_fails_once_and_visibly(tmp_path, _) -> None:
+ script: list = [CStreamError(BAN) for _ in range(6)]
+ with FakeChatVariantServer(script, default_text="SHOULD-NOT-ANSWER") as srv:
+ h = _home(tmp_path, srv)
+ run = oneshot(h, "say hello")
+ records = srv.main_records()
+
+ assert "SHOULD-NOT-ANSWER" not in run.stdout, run.describe()
+ assert run.proc.returncode != 0 or run.usage.get("failed") is True, run.describe()
+ surfaced = (run.stdout + run.proc.stderr).lower()
+ assert "banned" in surfaced, f"ban not surfaced to the user: {run.describe()}"
+ assert len(records) == 1, f"{len(records)} requests for a permanent account ban: {run.describe()}"
diff --git a/tests/e2e/core/providers/test_fallback_providers.py b/tests/e2e/core/providers/test_fallback_providers.py
new file mode 100644
index 00000000000..bd6e4a1292e
--- /dev/null
+++ b/tests/e2e/core/providers/test_fallback_providers.py
@@ -0,0 +1,190 @@
+"""Provider fallback (``fallback_providers``) through REAL ``hermes -z`` processes.
+
+Two loopback fakes stand in for two vendors: the primary and the fallback. Everything
+between the CLI and those sockets is real Hermes: config loading, credential resolution,
+the retry ladder, fallback activation and the fallback client.
+
+Proven here:
+
+* a primary that answers every request with 503 is tried, then the turn is answered by
+ the configured fallback, which receives the user's conversation and is reported as the
+ model that served the turn;
+* a primary whose credentials cannot be resolved walks ``fallback_providers`` at
+ resolution time: a Nous Portal OAuth refresh answered with 5xx (an ``AuthError``) does,
+ and one that cannot connect at all (an outage: connection refused) must too (#120608).
+"""
+
+from __future__ import annotations
+
+import base64
+import json
+import socket
+import subprocess
+import sys
+import threading
+import time
+from contextlib import contextmanager
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from typing import Iterator
+
+import pytest
+
+from tests.e2e.core.providers._openai_helpers import (
+ Home,
+ chat_messages,
+ custom_chat_config,
+ db_messages,
+ oneshot,
+)
+from tests.fakes.fake_llm_provider import FakeLLMServer
+from tests.fakes.providers.chat_variants import CError, FakeChatVariantServer
+
+pytestmark = pytest.mark.skipif(not sys.platform.startswith("linux"), reason="subprocess harness is Linux-gated")
+
+# Scenario -> "#issue one-line symptom" for scenarios red on origin/main. Strict: the test
+# FAILS the moment the bug is fixed, forcing the entry out.
+KNOWN: dict[str, str] = {
+ "unreachable_portal_falls_back": "#120608 transport error during credential resolution skips fallback_providers",
+}
+
+FALLBACK_MODEL = "fallback-model"
+PROMPT = "CANARY-PROMPT say hello"
+TURN_BUDGET = 45.0
+
+
+def known(name: str) -> list:
+ """Marks for a scenario: a strict xfail while it is in KNOWN, nothing once fixed."""
+ return [pytest.mark.xfail(strict=True, raises=AssertionError, reason=KNOWN[name])] if name in KNOWN else []
+
+
+def _fallback_entry(fallback: FakeLLMServer) -> list[dict]:
+ return [{"provider": "custom", "model": FALLBACK_MODEL, "base_url": fallback.base_url}]
+
+
+def _bounded_turn(h: Home, prompt: str, **kw):
+ """One turn that must finish well inside the harness budget: a primary that is never
+ abandoned for the fallback keeps backing off for minutes, which is itself the failure."""
+ try:
+ return oneshot(h, prompt, timeout=TURN_BUDGET, **kw)
+ except subprocess.TimeoutExpired as exc:
+ raise AssertionError(f"turn still running after {TURN_BUDGET}s: the fallback never took over") from exc
+
+
+def _user_texts(body: dict) -> list[str]:
+ return [str(m.get("content")) for m in chat_messages(body, "user")]
+
+
+def test_persistent_primary_503_is_answered_by_fallback(tmp_path) -> None:
+ def always_503(_record: dict) -> CError:
+ return CError(503, "Service temporarily unavailable", code="service_unavailable")
+
+ with FakeChatVariantServer(always_503) as primary, FakeLLMServer(default_text="FROM-FALLBACK") as fallback:
+ cfg = custom_chat_config(primary.base_url)
+ cfg["fallback_providers"] = _fallback_entry(fallback)
+ h = Home(tmp_path).write(cfg, {"OPENAI_API_KEY": "sk-fake"})
+ run = _bounded_turn(h, PROMPT)
+ primary_mains = primary.main_requests()
+ fallback_mains = fallback.main_requests()
+
+ assert run.proc.returncode == 0 and run.stdout.strip() == "FROM-FALLBACK", run.describe()
+ assert primary_mains, "the primary was never tried"
+ assert fallback_mains, f"fallback never received a request: {run.describe()}"
+ assert any(PROMPT in t for t in _user_texts(fallback_mains[0])), fallback_mains[0].get("messages")
+ assert fallback_mains[0].get("model") == FALLBACK_MODEL, fallback_mains[0].get("model")
+ assert run.usage.get("model") == FALLBACK_MODEL, run.describe()
+ answers = [r for r in db_messages(h, run.session_id)
+ if r["role"] == "assistant" and "FROM-FALLBACK" in (r.get("content") or "")]
+ assert len(answers) == 1, db_messages(h, run.session_id)
+
+
+# Nous Portal credential-resolution outage (#120608) ------------------------------------
+
+
+def _jwt(claims: dict) -> str:
+ def seg(obj: dict) -> str:
+ return base64.urlsafe_b64encode(json.dumps(obj).encode()).rstrip(b"=").decode()
+ return f"{seg({'alg': 'none', 'typ': 'JWT'})}.{seg(claims)}.sig"
+
+
+def _expired_nous_auth() -> dict:
+ """An auth.json whose Nous invoke JWT expired an hour ago but whose refresh token is fine:
+ the next turn must redeem it against the Portal before any inference call."""
+ past = int(time.time()) - 3600
+ iso = time.strftime("%Y-%m-%dT%H:%M:%S+00:00", time.gmtime(past))
+ return {"version": 1, "active_provider": "nous", "providers": {"nous": {
+ "portal_base_url": "https://portal.nousresearch.com",
+ "inference_base_url": "https://inference-api.nousresearch.com/v1",
+ "client_id": "hermes-cli", "token_type": "Bearer", "scope": "inference:invoke",
+ "access_token": _jwt({"sub": "e2e-user", "scope": "inference:invoke", "exp": past}),
+ "refresh_token": "refresh-e2e", "obtained_at": iso, "expires_in": 3600, "expires_at": iso,
+ "agent_key": None, "agent_key_id": None, "agent_key_expires_at": None,
+ "agent_key_expires_in": None, "agent_key_reused": None, "agent_key_obtained_at": None,
+ }}}
+
+
+def _closed_port() -> int:
+ """A loopback port nothing listens on: connecting is refused immediately."""
+ with socket.socket() as s:
+ s.bind(("127.0.0.1", 0))
+ return s.getsockname()[1]
+
+
+class _Portal5xx(BaseHTTPRequestHandler):
+ """A Portal that is up but failing: every token refresh gets a 503 OAuth error body."""
+
+ hits: list[str] = []
+
+ def log_message(self, *_a: object) -> None:
+ pass
+
+ def do_POST(self) -> None: # noqa: N802
+ self.hits.append(self.path)
+ body = json.dumps({"error": "server_error", "error_description": "portal overloaded"}).encode()
+ self.send_response(503)
+ self.send_header("Content-Type", "application/json")
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+
+@contextmanager
+def _portal(kind: str) -> Iterator[tuple[str, list[str]]]:
+ """``(portal_base_url, refresh_paths_hit)``: a 5xx-answering Portal or a refused port."""
+ if kind == "refused":
+ yield f"http://127.0.0.1:{_closed_port()}", []
+ return
+ handler = type("Portal", (_Portal5xx,), {"hits": []})
+ server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
+ threading.Thread(target=server.serve_forever, daemon=True).start()
+ try:
+ yield f"http://127.0.0.1:{server.server_address[1]}", handler.hits
+ finally:
+ server.shutdown()
+ server.server_close()
+
+
[email protected]("portal_kind", [
+ pytest.param("5xx", id="portal_5xx"),
+ pytest.param("refused", id="portal_refused", marks=known("unreachable_portal_falls_back")),
+])
+def test_primary_credential_resolution_failure_falls_back(tmp_path, portal_kind: str) -> None:
+ dead = f"http://127.0.0.1:{_closed_port()}"
+ with _portal(portal_kind) as (portal_url, portal_hits), FakeLLMServer(default_text="FROM-FALLBACK") as fallback:
+ env = {
+ "HERMES_PORTAL_BASE_URL": portal_url,
+ # Nothing may reach a real vendor host; the loopback fakes stay direct.
+ "HTTPS_PROXY": dead, "HTTP_PROXY": dead, "NO_PROXY": "127.0.0.1,localhost",
+ "HERMES_NOUS_TIMEOUT_SECONDS": "5",
+ }
+ cfg = {"model": {"provider": "nous", "default": "Hermes-4-70B", "context_length": 128000},
+ "fallback_providers": _fallback_entry(fallback)}
+ h = Home(tmp_path).write(cfg, {"OPENAI_API_KEY": "sk-fake"}, auth=_expired_nous_auth())
+ run = _bounded_turn(h, PROMPT, env=env)
+ fallback_mains = fallback.main_requests()
+
+ if portal_kind == "5xx":
+ assert "/api/oauth/token" in portal_hits, f"precondition: the expired token was never refreshed: {run.describe()}"
+ assert fallback_mains, f"fallback_providers never consulted: {run.describe()}"
+ assert any(PROMPT in t for t in _user_texts(fallback_mains[0])), fallback_mains[0].get("messages")
+ assert run.proc.returncode == 0 and run.stdout.strip() == "FROM-FALLBACK", run.describe()
+ assert run.usage.get("model") == FALLBACK_MODEL, run.describe()
diff --git a/tests/e2e/core/providers/test_openai_codex_pool.py b/tests/e2e/core/providers/test_openai_codex_pool.py
new file mode 100644
index 00000000000..7e7c2de60b7
--- /dev/null
+++ b/tests/e2e/core/providers/test_openai_codex_pool.py
@@ -0,0 +1,277 @@
+"""Codex credential pool: a dead refresh grant retires only the rows tied to that grant.
+
+Tier (stated honestly): REAL ``hermes -z`` processes with ``model.provider: openai-codex``
+and a seeded two-login pool in ``auth.json``. Two vendor boundaries are faked:
+
+* the ChatGPT Codex Responses backend — ``HERMES_CODEX_BASE_URL`` points at
+ ``FakeResponsesServer``, which accepts ONLY login A's bearer, so a reply proves which login
+ served the turn;
+* the OpenAI OAuth token endpoint. Its URL is a hard-coded ``https://`` constant with no
+ override, and the proxy-impersonation route cannot carry https, so a ``sitecustomize`` shim
+ on the child's ``PYTHONPATH`` redirects exactly that URL, at the ``httpx.Client.send``
+ layer, to a loopback token fake. No Hermes function is patched; everything from the pool
+ through the refresh POST, the terminal classification and the auth.json write-back runs as
+ shipped.
+
+The pool is the #120741 layout: login A is the singleton plus its seeded ``device_code`` row
+(fresh), login B is an independently authorized ``manual:device_code`` row (``hermes auth
+add``) whose access token is about to expire, so every selection defers a refresh of B.
+"""
+
+from __future__ import annotations
+
+import base64
+import json
+import socket
+import sys
+import threading
+import time
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from pathlib import Path
+from typing import Any
+from urllib.parse import parse_qs
+
+import pytest
+
+from tests.e2e.core.providers._openai_helpers import REPO_ROOT, Home, oneshot
+from tests.fakes.providers.openai_responses import FakeResponsesServer, Message, Turn
+
+pytestmark = pytest.mark.skipif(not sys.platform.startswith("linux"), reason="subprocess harness is Linux-gated")
+
+KNOWN: dict[str, str] = {
+ "independent_login_survives": "#120741 terminal refresh failure on one pooled login quarantines an independent login",
+}
+
+
+def known(name: str) -> list:
+ """Marks for a scenario: a strict xfail while it is in KNOWN, nothing once fixed."""
+ return [pytest.mark.xfail(strict=True, raises=AssertionError, reason=KNOWN[name])] if name in KNOWN else []
+
+
+TOKEN_URL = "https://auth.openai.com/oauth/token"
+MODEL = "gpt-5.3-codex"
+
+_SHIM = '''\
+"""E2E vendor-boundary shim: route the hard-coded OAuth token URL to a loopback fake."""
+import os
+
+_pairs = [p.split("=", 1) for p in os.environ.get("HERMES_E2E_URL_REDIRECT", "").split(";") if "=" in p]
+if _pairs:
+ import httpx
+
+ _redirect = dict(_pairs)
+ _send = httpx.Client.send
+
+ def send(self, request, *args, **kwargs):
+ target = _redirect.get(str(request.url))
+ if target:
+ request.url = httpx.URL(target)
+ request.headers["Host"] = request.url.netloc.decode()
+ return _send(self, request, *args, **kwargs)
+
+ httpx.Client.send = send
+'''
+
+
+class FakeTokenServer:
+ """OAuth token endpoint: ``invalid_grant`` for the configured refresh tokens, else a rotation."""
+
+ def __init__(self, rejected: set[str], minted: dict[str, tuple[str, str]] | None = None,
+ throttled: set[str] | None = None) -> None:
+ self.rejected = rejected
+ self.throttled = throttled or set()
+ self.minted = minted or {}
+ self.posts: list[dict[str, str]] = []
+ self._httpd = ThreadingHTTPServer(("127.0.0.1", 0), self._handler())
+ self._thread = threading.Thread(target=self._httpd.serve_forever, daemon=True)
+
+ def __enter__(self) -> "FakeTokenServer":
+ self._thread.start()
+ return self
+
+ def __exit__(self, *_exc: object) -> None:
+ self._httpd.shutdown()
+ self._httpd.server_close()
+
+ @property
+ def url(self) -> str:
+ return f"http://127.0.0.1:{self._httpd.server_address[1]}/oauth/token"
+
+ def refresh_tokens_posted(self) -> list[str]:
+ return [p.get("refresh_token", "") for p in self.posts]
+
+ def _handler(self) -> type[BaseHTTPRequestHandler]:
+ server = self
+
+ class Handler(BaseHTTPRequestHandler):
+ def log_message(self, *_a: object) -> None: # noqa: D401 - silence per-request logging
+ pass
+
+ def do_POST(self) -> None: # noqa: N802
+ raw = self.rfile.read(int(self.headers.get("Content-Length") or 0)).decode()
+ form = {k: v[0] for k, v in parse_qs(raw).items()}
+ server.posts.append(form)
+ rt = form.get("refresh_token", "")
+ extra = {}
+ if rt in server.throttled:
+ status, body, extra = 429, {"error": "rate_limited"}, {"Retry-After": "600"}
+ elif form.get("grant_type") != "refresh_token" or rt in server.rejected or rt not in server.minted:
+ status, body = 400, {"error": "invalid_grant",
+ "error_description": "The refresh token is invalid or has been revoked."}
+ else:
+ at, next_rt = server.minted[rt]
+ status, body = 200, {"access_token": at, "refresh_token": next_rt, "id_token": at,
+ "token_type": "Bearer", "expires_in": 28800}
+ data = json.dumps(body).encode()
+ self.send_response(status)
+ self.send_header("Content-Type", "application/json")
+ for k, v in extra.items():
+ self.send_header(k, v)
+ self.send_header("Content-Length", str(len(data)))
+ self.end_headers()
+ self.wfile.write(data)
+
+ return Handler
+
+
+def _jwt(account: str, sub: str, exp: float) -> str:
+ def seg(obj: dict) -> str:
+ return base64.urlsafe_b64encode(json.dumps(obj).encode()).rstrip(b"=").decode()
+
+ payload = {"exp": int(exp), "sub": sub, "https://api.openai.com/auth": {"chatgpt_account_id": account}}
+ return f"{seg({'alg': 'none'})}.{seg(payload)}.sig"
+
+
+def _iso(ts: float) -> str:
+ return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(ts))
+
+
+def _pool_store(a: dict[str, str], b: dict[str, str], now: float) -> dict[str, Any]:
+ a_refresh = _iso(now - 3600)
+ return {
+ "version": 1,
+ "active_provider": "openai-codex",
+ "providers": {"openai-codex": {"tokens": dict(a), "last_refresh": a_refresh, "auth_mode": "chatgpt"}},
+ "credential_pool": {"openai-codex": [
+ {"id": "login-a", "label": "device_code", "auth_type": "oauth", "priority": 0,
+ "source": "device_code", **a, "last_refresh": a_refresh},
+ {"id": "login-b", "label": "second-account", "auth_type": "oauth", "priority": 1,
+ "source": "manual:device_code", **b, "last_refresh": _iso(now - 7200)},
+ ]},
+ }
+
+
+def _home(tmp_path: Path, store: dict[str, Any]) -> Home:
+ h = Home(tmp_path).write({"model": {"provider": "openai-codex", "default": MODEL, "context_length": 128000}},
+ auth=store)
+ (tmp_path / "shim").mkdir(exist_ok=True)
+ (tmp_path / "shim" / "sitecustomize.py").write_text(_SHIM, encoding="utf-8")
+ return h
+
+
+def _env(tmp_path: Path, codex_url: str, token: FakeTokenServer, dead_port: int) -> dict[str, str]:
+ """Child env: the shim, the Codex fake, and every other egress pinned to a refusing proxy."""
+ proxy = f"http://127.0.0.1:{dead_port}"
+ return {"HERMES_CODEX_BASE_URL": codex_url, "PYTHONPATH": f"{tmp_path / 'shim'}:{REPO_ROOT}",
+ "HERMES_E2E_URL_REDIRECT": f"{TOKEN_URL}={token.url}",
+ **{k: proxy for k in ("HTTP_PROXY", "http_proxy", "HTTPS_PROXY", "https_proxy")},
+ "NO_PROXY": "127.0.0.1,localhost", "no_proxy": "127.0.0.1,localhost"}
+
+
+def _auth(h: Home) -> dict[str, Any]:
+ return json.loads((h.hermes_home / "auth.json").read_text(encoding="utf-8"))
+
+
+def _answer(run) -> str:
+ return run.stdout.strip()
+
+
+def _pair(account: str, rt: str, ttl: float) -> dict[str, str]:
+ return {"access_token": _jwt(account, f"user-{account}", time.time() + ttl), "refresh_token": rt}
+
+
+def _two_logins(tmp_path: Path, a: dict[str, str], b: dict[str, str], token: FakeTokenServer,
+ replies: list[str], bearer: str) -> tuple[list, list[dict[str, Any]], list[dict[str, Any]]]:
+ """Two sequential real ``hermes -z`` turns against the seeded pool; auth.json after each."""
+ runs, stores = [], []
+ with FakeResponsesServer([Turn([Message(r)]) for r in replies], api_key=bearer) as codex, \
+ socket.socket() as dead:
+ dead.bind(("127.0.0.1", 0)) # bound, never listening: a proxy that refuses at once
+ h = _home(tmp_path, _pool_store(a, b, time.time()))
+ env = _env(tmp_path, codex.base_url, token, dead.getsockname()[1])
+ for n in range(len(replies)):
+ runs.append(oneshot(h, f"hello {n}", env=env))
+ stores.append(_auth(h))
+ return runs, stores, [s.get("credential_pool", {}).get("openai-codex", []) for s in stores]
+
+
+def _live_order(rows: list[dict[str, Any]]) -> list[tuple[str, str]]:
+ """``(id, source)`` of rows still in rotation, in fill_first (priority) order."""
+ live = [r for r in rows if r.get("last_status") != "dead"]
+ return [(r["id"], r["source"]) for r in sorted(live, key=lambda r: r.get("priority", 0))]
+
+
[email protected]("scenario", [pytest.param("independent_login_survives",
+ marks=known("independent_login_survives"))])
+def test_dead_grant_on_independent_login_keeps_login_a(tmp_path, scenario) -> None:
+ """B's refresh token is terminally rejected (``invalid_grant``). B leaves rotation; A — a
+ different grant, a different account — keeps its pool row (id, source, first place in the
+ fill_first order), its singleton tokens, and keeps serving turns in later processes."""
+ a, b = _pair("acct-A", "rt-A", 8 * 3600), _pair("acct-B", "rt-B", 60)
+ with FakeTokenServer(rejected={"rt-B"}) as token:
+ runs, stores, pools = _two_logins(tmp_path, a, b, token, ["SERVED-BY-A-1", "SERVED-BY-A-2"],
+ a["access_token"])
+ posted = token.refresh_tokens_posted()
+
+ for run, want in zip(runs, ["SERVED-BY-A-1", "SERVED-BY-A-2"]):
+ assert run.proc.returncode == 0 and _answer(run) == want, run.describe()
+ # The terminal failure happened on the wire, for B's grant only, and B is retired.
+ assert posted and set(posted) == {"rt-B"}, posted
+ b_row = next((r for r in pools[0] if r["id"] == "login-b"), None)
+ assert b_row is None or b_row.get("last_status") == "dead", b_row
+ # A is a different grant: nothing about it may change.
+ assert stores[0]["providers"]["openai-codex"]["tokens"] == a, stores[0]["providers"]["openai-codex"]
+ for rows in pools:
+ assert _live_order(rows) == [("login-a", "device_code")], (
+ f"login A was quarantined by B's invalid_grant: live pool is {_live_order(rows)}")
+
+
+def test_throttled_refresh_on_independent_login_leaves_login_a_untouched(tmp_path) -> None:
+ """Control (green on main): a non-terminal token-endpoint failure for B (HTTP 429 quota)
+ benches B only. A keeps its row, first place, singleton tokens, and serves every turn;
+ no re-login is demanded."""
+ a, b = _pair("acct-A", "rt-A", 8 * 3600), _pair("acct-B", "rt-B", 60)
+ with FakeTokenServer(rejected=set(), throttled={"rt-B"}) as token:
+ runs, stores, pools = _two_logins(tmp_path, a, b, token, ["SERVED-BY-A-1", "SERVED-BY-A-2"],
+ a["access_token"])
+ posted = token.refresh_tokens_posted()
+
+ for run, want in zip(runs, ["SERVED-BY-A-1", "SERVED-BY-A-2"]):
+ assert run.proc.returncode == 0 and _answer(run) == want, run.describe()
+ assert posted and set(posted) == {"rt-B"}, posted
+ singleton = stores[-1]["providers"]["openai-codex"]
+ assert singleton["tokens"] == a and "last_auth_error" not in singleton, singleton
+ assert _live_order(pools[-1])[0] == ("login-a", "device_code"), _live_order(pools[-1])
+ rows = {r["id"]: r for r in pools[-1]}
+ assert rows["login-b"].get("last_status") == "exhausted", rows["login-b"]
+
+
+def test_dead_shared_grant_retires_every_row_of_it(tmp_path) -> None:
+ """Control (green on main): when the singleton, its seeded row and a ``manual:`` alias all
+ hold the SAME rejected refresh token, none stays selectable. The user gets the re-login
+ instruction, no answer is fabricated, and auth.json records the dead grant (tokens gone,
+ ``relogin_required``) so the next process does not re-seed it."""
+ shared = _pair("acct-A", "rt-S", -60)
+ with FakeTokenServer(rejected={"rt-S"}) as token:
+ runs, stores, pools = _two_logins(tmp_path, shared, dict(shared), token, ["NEVER-1", "NEVER-2"],
+ "no-login-holds-this-bearer")
+ posted = token.refresh_tokens_posted()
+
+ assert posted and set(posted) == {"rt-S"}, posted
+ for run, store, rows in zip(runs, stores, pools):
+ assert run.proc.returncode != 0 and "NEVER" not in run.stdout, run.describe()
+ assert "hermes auth add openai-codex" in run.stdout, run.describe()
+ singleton = store["providers"]["openai-codex"]
+ assert not singleton.get("tokens", {}).get("refresh_token"), singleton
+ assert (singleton.get("last_auth_error") or {}).get("relogin_required") is True, singleton
+ assert _live_order(rows) == [], rows
diff --git a/tests/e2e/core/providers/test_openai_pricing.py b/tests/e2e/core/providers/test_openai_pricing.py
new file mode 100644
index 00000000000..942772cf5b6
--- /dev/null
+++ b/tests/e2e/core/providers/test_openai_pricing.py
@@ -0,0 +1,255 @@
+"""Model-picker pricing for a config-defined twin of a priced aggregator (#120757).
+
+Tier (stated honestly): a REAL ``python -m tui_gateway.entry`` process — the backend the TUI
+and Desktop model picker talk to — answering the ``model.options`` JSON-RPC exactly as the
+picker calls it. The only fake is the vendor's price catalog: the aggregator catalog URL
+(``https://openrouter.ai/api/v1/models``) is a hard-coded https constant with no override and
+lives only in process memory, so a ``sitecustomize`` shim on the child's ``PYTHONPATH``
+rewrites exactly that origin, at the ``urllib`` opener layer, to a loopback fake serving the
+vendor's catalog shape. No Hermes function is patched. Every other egress is pinned to a
+closed loopback proxy so nothing reaches a real vendor.
+
+The config is the issue's: a ``providers:`` entry keyed ``openrouter`` pointing at the
+aggregator's base URL. Its picker row is ``custom:openrouter``; the built-in ``openrouter``
+row (credentialed from ``.env``) is the control that prices from the same catalog, and a
+``myrelay`` provider serving a catalog model id is the decoy that must NOT borrow its prices.
+
+The picker is driven with ``refresh: true`` (its explicit reload: catalogs are fetched
+synchronously, so no background prewarm timing is involved). ``get_pricing_for_provider`` is
+the single choke point for both that path and the cached-only normal open.
+"""
+
+from __future__ import annotations
+
+import json
+import socket
+import sys
+import threading
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from pathlib import Path
+from typing import Any
+
+import pytest
+
+from tests.e2e.core.providers._openai_helpers import REPO_ROOT, Home
+from tests.e2e.core.providers._openai_tui import TuiGateway
+
+pytestmark = pytest.mark.skipif(not sys.platform.startswith("linux"), reason="subprocess harness is Linux-gated")
+
+KNOWN: dict[str, str] = {
+ "custom_twin_priced": "#120757 custom:<key> row pointing at a priced aggregator gets no picker prices",
+}
+
+
+def known(name: str) -> list:
+ """Marks for a scenario: a strict xfail while it is in KNOWN, nothing once fixed."""
+ return [pytest.mark.xfail(strict=True, raises=AssertionError, reason=KNOWN[name])] if name in KNOWN else []
+
+
+VENDOR_ORIGIN = "https://openrouter.ai"
+# (id, $/token prompt, $/token completion) — the catalog the fake aggregator publishes.
+CATALOG = [
+ ("fakevendor/alpha-large", "0.000003", "0.000015"),
+ ("fakevendor/beta-mini", "0.0000004", "0.0000016"),
+ ("fakevendor/gamma-coder", "0.000002", "0.000008"),
+]
+TWIN_MODELS = [mid for mid, _p, _c in CATALOG]
+RELAY_MODEL = TWIN_MODELS[-1]
+
+_SHIM = '''\
+"""E2E vendor-boundary shim: route a hard-coded vendor origin to a loopback fake."""
+import os
+
+_pairs = [p.split("=", 1) for p in os.environ.get("HERMES_E2E_ORIGIN_REDIRECT", "").split(";") if "=" in p]
+if _pairs:
+ import urllib.request
+
+ _open = urllib.request.OpenerDirector.open
+
+ def open(self, fullurl, *args, **kwargs):
+ req = fullurl if isinstance(fullurl, urllib.request.Request) else None
+ url = req.full_url if req is not None else str(fullurl)
+ for src, dst in _pairs:
+ if url.startswith(src + "/"):
+ url = dst + url[len(src):]
+ if req is not None:
+ req.full_url = url
+ else:
+ fullurl = url
+ break
+ return _open(self, fullurl, *args, **kwargs)
+
+ urllib.request.OpenerDirector.open = open
+'''
+
+
+class FakeCatalog:
+ """The aggregator's public ``GET /api/v1/models`` price catalog (vendor JSON shape), plus
+ the decoy relay's plain ``GET /relay/v1/models`` listing on the same loopback server."""
+
+ def __init__(self) -> None:
+ self.requests: list[tuple[str, str]] = []
+ self._httpd = ThreadingHTTPServer(("127.0.0.1", 0), self._handler())
+ self._thread = threading.Thread(target=self._httpd.serve_forever, daemon=True)
+
+ def __enter__(self) -> "FakeCatalog":
+ self._thread.start()
+ return self
+
+ def __exit__(self, *_exc: object) -> None:
+ self._httpd.shutdown()
+ self._httpd.server_close()
+
+ @property
+ def origin(self) -> str:
+ return f"http://127.0.0.1:{self._httpd.server_address[1]}"
+
+ def _handler(self) -> type[BaseHTTPRequestHandler]:
+ server = self
+
+ class Handler(BaseHTTPRequestHandler):
+ def log_message(self, *_a: object) -> None: # noqa: D401 - silence per-request logging
+ pass
+
+ def do_GET(self) -> None: # noqa: N802
+ server.requests.append((self.path, self.headers.get("Authorization", "")))
+ path = self.path.split("?")[0].rstrip("/")
+ if path == "/relay/v1/models": # the decoy relay: plain OpenAI model list, no prices
+ status, body = 200, {"object": "list", "data": [{"id": RELAY_MODEL, "object": "model"}]}
+ elif path == "/api/v1/models":
+ status, body = 200, {"data": [
+ {"id": mid, "name": mid, "context_length": 200000, "created": 1780000000,
+ "architecture": {"modality": "text->text", "input_modalities": ["text"],
+ "output_modalities": ["text"]},
+ "pricing": {"prompt": p, "completion": c, "request": "0", "image": "0"},
+ "supported_parameters": ["tools", "reasoning", "max_tokens"]}
+ for mid, p, c in CATALOG]}
+ else:
+ status, body = 404, {"error": {"message": "not found"}}
+ data = json.dumps(body).encode()
+ self.send_response(status)
+ self.send_header("Content-Type", "application/json")
+ self.send_header("Content-Length", str(len(data)))
+ self.end_headers()
+ self.wfile.write(data)
+
+ return Handler
+
+
+class _ShimHome(Home):
+ """A Home whose child env carries the vendor-boundary shim and the egress guard."""
+
+ extra: dict[str, str]
+
+ def env(self, extra: dict[str, str] | None = None) -> dict[str, str]:
+ return super().env({**self.extra, **(extra or {})})
+
+
+def _closed_port() -> socket.socket:
+ """A bound, never-listening loopback socket: connecting to it is refused at once."""
+ sock = socket.socket()
+ sock.bind(("127.0.0.1", 0))
+ return sock
+
+
+def _home(tmp_path: Path, catalog: FakeCatalog, dead: socket.socket) -> _ShimHome:
+ h = _ShimHome(tmp_path)
+ (tmp_path / "shim").mkdir(exist_ok=True)
+ (tmp_path / "shim" / "sitecustomize.py").write_text(_SHIM, encoding="utf-8")
+ proxy = f"http://127.0.0.1:{dead.getsockname()[1]}"
+ h.extra = {"PYTHONPATH": f"{tmp_path / 'shim'}:{REPO_ROOT}",
+ "HERMES_E2E_ORIGIN_REDIRECT": f"{VENDOR_ORIGIN}={catalog.origin}",
+ **{k: proxy for k in ("HTTP_PROXY", "http_proxy", "HTTPS_PROXY", "https_proxy")},
+ "NO_PROXY": "127.0.0.1,localhost", "no_proxy": "127.0.0.1,localhost"}
+ h.write({
+ "model": {"provider": "openrouter", "default": TWIN_MODELS[0]},
+ "providers": {
+ "openrouter": {"name": "OpenRouter-Full", "base_url": f"{VENDOR_ORIGIN}/api/v1",
+ "api_key": "sk-or-fake-twin", "models": TWIN_MODELS},
+ # Decoy: serves a catalog model id, but is a relay with no price catalog of its own.
+ "myrelay": {"name": "My Relay", "base_url": f"{catalog.origin}/relay/v1",
+ "api_key": "sk-relay-fake", "models": [RELAY_MODEL]},
+ },
+ }, dotenv={"OPENROUTER_API_KEY": "sk-or-fake-builtin"})
+ return h
+
+
+def _row(payload: dict[str, Any], slug: str) -> dict[str, Any] | None:
+ return next((r for r in payload.get("providers") or [] if r.get("slug") == slug), None)
+
+
+def _priced(row: dict[str, Any] | None) -> dict[str, Any]:
+ """``{model: price entry}`` for the row's models that carry a real price."""
+ pricing = (row or {}).get("pricing") or {}
+ return {m: p for m, p in pricing.items() if isinstance(p, dict) and (p.get("input") or p.get("output"))}
+
+
+def _refreshed_options(tmp_path: Path) -> tuple[dict[str, Any], list[tuple[str, str]]]:
+ """One picker refresh (the picker's explicit reload: fetches price catalogs synchronously,
+ so no background timing is involved) against a real gateway."""
+ dead = _closed_port()
+ try:
+ with FakeCatalog() as catalog:
+ h = _home(tmp_path, catalog, dead)
+ gw = TuiGateway(h)
+ try:
+ payload = gw.call("model.options", {"refresh": True})
+ finally:
+ gw.close()
+ return payload, list(catalog.requests)
+ finally:
+ dead.close()
+
+
[email protected](scope="module")
+def picker(tmp_path_factory) -> tuple[dict[str, Any], list[tuple[str, str]]]:
+ return _refreshed_options(tmp_path_factory.mktemp("pricing"))
+
+
+def _expected_price(mid: str) -> tuple[float, float]:
+ """The catalog's own $/token for *mid*, as $/MTok."""
+ _m, p, c = next(row for row in CATALOG if row[0] == mid)
+ return float(p) * 1e6, float(c) * 1e6
+
+
+def _dollars(text: str) -> float:
+ return float(str(text).lstrip("$"))
+
+
+def test_builtin_aggregator_row_prices_from_catalog(picker) -> None:
+ """Control (green on main): the built-in aggregator row prices every catalog model it
+ lists with the catalog's own $/MTok, read from the aggregator's catalog endpoint."""
+ payload, requests = picker
+ assert any(path.startswith("/api/v1/models") for path, _auth in requests), requests
+ row = _row(payload, "openrouter")
+ priced = _priced(row)
+ listed = [m for m in (row or {}).get("models") or [] if m in TWIN_MODELS]
+ assert listed and set(listed) <= set(priced), (listed, (row or {}).get("pricing"))
+ for mid in listed:
+ assert (_dollars(priced[mid]["input"]), _dollars(priced[mid]["output"])) == pytest.approx(
+ _expected_price(mid)), (mid, priced[mid])
+
+
+def test_relay_without_catalog_gets_no_borrowed_prices(picker) -> None:
+ """Control (green on main): a config-defined relay that is NOT a priced aggregator serves
+ the same model ids but must not borrow the aggregator's prices."""
+ payload, _requests = picker
+ relay = _row(payload, "myrelay")
+ assert relay is not None and RELAY_MODEL in (relay.get("models") or []), payload.get("providers")
+ assert _priced(relay) == {}, relay.get("pricing")
+
+
[email protected]("scenario", [pytest.param("custom_twin_priced", marks=known("custom_twin_priced"))])
+def test_config_defined_twin_row_is_priced_like_the_aggregator(picker, scenario) -> None:
+ """The ``custom:openrouter`` row serves the same upstream as the built-in row; its models
+ must carry the aggregator's prices, not none."""
+ payload, _requests = picker
+ twin, builtin = _row(payload, "custom:openrouter"), _row(payload, "openrouter")
+ assert twin is not None and set(TWIN_MODELS) <= set(twin.get("models") or []), payload.get("providers")
+ priced = _priced(twin)
+ assert set(priced) == set(TWIN_MODELS), (
+ f"custom:openrouter row has {len(priced)}/{len(TWIN_MODELS)} models priced "
+ f"(pricing={twin.get('pricing')!r})")
+ for mid, entry in _priced(builtin).items():
+ if mid in priced:
+ assert priced[mid] == entry, (mid, priced[mid], entry)