The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test: #120815 aux-call cell is a plain regression test; clock-expiry refresh cell; OAuth fake is the SDK oracle
teknium127a98dc04cb7
diff --git a/tests/e2e/core/providers/_oauth_helpers.py b/tests/e2e/core/providers/_oauth_helpers.pyindex 784035f1464..738844d87b9 100644--- a/tests/e2e/core/providers/_oauth_helpers.py+++ b/tests/e2e/core/providers/_oauth_helpers.py@@ -16,12 +16,13 @@ import threadingimport timeimport uuidfrom dataclasses import dataclass, field-from http.server import BaseHTTPRequestHandler, ThreadingHTTPServerfrom pathlib import Pathfrom typing import Any, Callableimport yaml+from tests.fakes.providers.anthropic_messages import ApiError, AnthropicMessagesServer, Reply, Response, Text, ToolUse+REPO_ROOT = Path(__file__).resolve().parents[4]TAG_VAR = "OAUTH_E2E_TAG"@@ -132,134 +133,44 @@ def wait_until(pred: Callable[[], Any], timeout: float, what: str, interval: flotime.sleep(interval)-# ---- minimal Anthropic Messages endpoint -----------------------------------+# ---- Anthropic Messages endpoint --------------------------------------------#-# Just enough of the Messages API for a text turn (JSON and SSE). The request-# record keeps the bearer so a test can prove which access token each call-# carried; ``decide`` maps a record to ("text", str) | ("tool", name, input)-# | ("error", status, type, msg) | ("hold", threading.Event, next_decision)-# | ("call", zero-arg callable returning the decision at send time).+# The SDK-oracle fake (tests/fakes/providers/anthropic_messages.py) validates every+# body and builds every reply from SDK models. A test's ``decide(record)`` returns a+# ``Decision``: a scripted ``Response`` (``Reply``/``ApiError``), a ``Hold`` that+# parks the reply on the handler thread until an event fires, or a zero-arg+# callable evaluated at send time. ``record["bearer"]`` / ``record["x_api_key"]``+# carry the credential each call presented.-def _sse(event: str, data: dict[str, Any]) -> bytes:- return f"event: {event}\ndata: {json.dumps(data)}\n\n".encode()+@dataclass+class Hold:+ event: threading.Event+ then: Any # Decision+ timeout: float = 120.0-class MessagesServer:- MODEL = "claude-sonnet-4-5"+def resolve(decision: Any) -> Response:+ """Follow ``Hold``s and callables down to the ``Response`` sent on the wire."""+ while not isinstance(decision, (Reply, ApiError)):+ if isinstance(decision, Hold):+ decision.event.wait(decision.timeout)+ decision = decision.then+ else:+ decision = decision()+ return decision- def __init__(self, decide: Callable[[dict[str, Any]], tuple]) -> None:- self.decide = decide- self.requests: list[dict[str, Any]] = []- self._lock = threading.Lock()- self._httpd: ThreadingHTTPServer | None = None- @property- def base_url(self) -> str:- assert self._httpd is not None- return f"http://127.0.0.1:{self._httpd.server_address[1]}/anthropic"+def text(s: str) -> Reply:+ return Reply([Text(s)])- def main_requests(self) -> list[dict[str, Any]]:- with self._lock:- return [r for r in self.requests if r["body"].get("tools")]- def start(self) -> "MessagesServer":- self._httpd = ThreadingHTTPServer(("127.0.0.1", 0), self._handler())- self._httpd.daemon_threads = True- threading.Thread(target=self._httpd.serve_forever, kwargs={"poll_interval": 0.05}, daemon=True).start()- return self+def tool(name: str, args: dict[str, Any]) -> Reply:+ return Reply([ToolUse(name, args)])- def stop(self) -> None:- if self._httpd is not None:- self._httpd.shutdown()- self._httpd.server_close()- self._httpd = None-- def _handler(self) -> type[BaseHTTPRequestHandler]:- outer = self-- class Handler(BaseHTTPRequestHandler):- protocol_version = "HTTP/1.1"-- def do_GET(self) -> None: # noqa: N802 - model listing probes- self._json(200, {"data": [{"id": outer.MODEL, "type": "model", "display_name": outer.MODEL}],- "has_more": False})-- def do_POST(self) -> None: # noqa: N802- raw = self.rfile.read(int(self.headers.get("Content-Length") or 0))- if not self.path.split("?", 1)[0].endswith("/v1/messages"):- # Local-endpoint capability probes (e.g. ``/api/show``) are not Messages calls.- return self._json(404, {"type": "error", "error": {"type": "not_found_error", "message": "no"}})- body = json.loads(raw or b"{}")- auth = self.headers.get("Authorization", "")- record = {"path": self.path, "body": body, "bearer": auth.removeprefix("Bearer ").strip(),- "x_api_key": self.headers.get("x-api-key", ""), "at": time.monotonic()}- with outer._lock:- outer.requests.append(record)- decision = outer.decide(record)- while decision[0] in ("hold", "call"):- if decision[0] == "call":- decision = decision[1]()- continue- decision[1].wait(120)- decision = decision[2]- if decision[0] == "error":- _, status, etype, msg = decision- return self._json(status, {"type": "error", "error": {"type": etype, "message": msg}})- if decision[0] == "tool":- block = {"type": "tool_use", "id": f"toolu_{uuid.uuid4().hex[:12]}", "name": decision[1],- "input": decision[2]}- stop = "tool_use"- else:- block, stop = {"type": "text", "text": decision[1]}, "end_turn"- if body.get("stream"):- return self._stream(block, stop)- self._json(200, {"id": "msg_fake", "type": "message", "role": "assistant", "model": outer.MODEL,- "content": [block], "stop_reason": stop,- "stop_sequence": None, "usage": {"input_tokens": 10, "output_tokens": 5}})-- def _stream(self, block: dict[str, Any], stop: str) -> None:- self.send_response(200)- self.send_header("Content-Type", "text/event-stream")- self.send_header("Connection", "close")- self.end_headers()- msg = {"id": "msg_fake", "type": "message", "role": "assistant", "model": outer.MODEL,- "content": [], "stop_reason": None, "stop_sequence": None,- "usage": {"input_tokens": 10, "output_tokens": 1}}- if block["type"] == "tool_use":- start = {**block, "input": {}}- delta = {"type": "input_json_delta", "partial_json": json.dumps(block["input"])}- else:- start = {"type": "text", "text": ""}- delta = {"type": "text_delta", "text": block["text"]}- for chunk in (- _sse("message_start", {"type": "message_start", "message": msg}),- _sse("content_block_start", {"type": "content_block_start", "index": 0, "content_block": start}),- _sse("content_block_delta", {"type": "content_block_delta", "index": 0, "delta": delta}),- _sse("content_block_stop", {"type": "content_block_stop", "index": 0}),- _sse("message_delta", {"type": "message_delta",- "delta": {"stop_reason": stop, "stop_sequence": None},- "usage": {"output_tokens": 5}}),- _sse("message_stop", {"type": "message_stop"}),- ):- self.wfile.write(chunk)- self.wfile.flush()- self.close_connection = True-- def _json(self, status: int, payload: dict[str, Any]) -> None:- data = json.dumps(payload).encode()- self.send_response(status)- self.send_header("Content-Type", "application/json")- self.send_header("Content-Length", str(len(data)))- self.send_header("Connection", "close")- self.end_headers()- self.wfile.write(data)- self.close_connection = True-- def log_message(self, format: str, *args: Any) -> None: # noqa: A003- return-- return Handler++def credential(record: dict[str, Any]) -> str:+ return record["bearer"] or record["x_api_key"]# ---- Anthropic OAuth rig ----------------------------------------------------@@ -270,6 +181,8 @@ class MessagesServer:ANTHROPIC_TOKEN_HOSTS = ("platform.claude.com", "console.anthropic.com")OLD_ACCESS = "sk-ant-oat01-e2e-old-access"+EXPIRED = ApiError(401, "authentication_error", "OAuth token has expired")+MODEL = "claude-sonnet-4-5"@dataclass@@ -277,7 +190,7 @@ class AnthropicOAuthRig:fh: FakeHometokens: Any # OAuthTokenServerproxy: Any # TLSInterceptProxy- messages: MessagesServer+ messages: AnthropicMessagesServerseed_refresh: strchild_env: dict[str, str]@@ -292,24 +205,29 @@ class AnthropicOAuthRig:return next((r for r in rows if r.get("id") == entry_id), {})-def start_anthropic_rig(root: Path, decide: Callable[[dict[str, Any]], tuple], *,- title_generation: bool, entries: int = 1) -> AnthropicOAuthRig:+def start_anthropic_rig(root: Path, decide: Callable[[dict[str, Any]], Any], *,+ title_generation: bool, entries: int = 1,+ expires_at_ms: int | None = None) -> AnthropicOAuthRig:+ """``expires_at_ms`` is the seeded row's clock expiry; default: an hour ahead, so only the+ vendor's 401 (early revocation/expiry) can trigger the refresh."""from tests.fakes.providers.oauth_token_server import OAuthTokenServer, TLSInterceptProxy, make_test_caca = make_test_ca(root / "ca", ANTHROPIC_TOKEN_HOSTS)tokens = OAuthTokenServer().start()proxy = TLSInterceptProxy(tokens, ca, ANTHROPIC_TOKEN_HOSTS).start()- messages = MessagesServer(decide).start()+ def responder(record: dict[str, Any]) -> Response:+ return resolve(decide(record))++ messages = AnthropicMessagesServer(responder, aux=responder, models=[MODEL]).start()fh = make_home(root)fh.write_config({- "model": {"provider": "anthropic", "default": MessagesServer.MODEL, "base_url": messages.base_url},+ "model": {"provider": "anthropic", "default": MODEL, "base_url": messages.base_url},"auxiliary": {"title_generation": {"enabled": title_generation}},})seed = tokens.seed_refresh_token()rows = [{"id": "e1", "label": "acct-1", "auth_type": "oauth", "priority": 0, "source": "manual","access_token": OLD_ACCESS, "refresh_token": seed,- # Not expired by the clock: the vendor revoking/expiring it early (401) is the trigger.- "expires_at_ms": int(time.time() * 1000) + 3_600_000}]+ "expires_at_ms": expires_at_ms if expires_at_ms is not None else int(time.time() * 1000) + 3_600_000}]for i in range(2, entries + 1):rows.append({"id": f"e{i}", "label": f"acct-{i}", "auth_type": "oauth", "priority": i - 1,"source": "manual", "access_token": f"sk-ant-oat01-e2e-spare-{i}",diff --git a/tests/e2e/core/providers/test_oauth_anthropic_refresh.py b/tests/e2e/core/providers/test_oauth_anthropic_refresh.pyindex 76b0df8d89a..8b4f95c632e 100644--- a/tests/e2e/core/providers/test_oauth_anthropic_refresh.py+++ b/tests/e2e/core/providers/test_oauth_anthropic_refresh.py@@ -1,16 +1,22 @@"""Anthropic OAuth access token expires mid-turn: one refresh, the turn completes, the rotation persists.Real ``hermes -z`` process, native ``anthropic`` provider on the OAuth route-(``sk-ant-oat…`` pool credential), inference against a loopback Messages-endpoint (accepted base-URL override ``http://127.0.0.1:<port>/anthropic``),+(``sk-ant-oat…`` pool credential), inference against the SDK-oracle loopback+Messages endpoint (accepted base-URL override ``http://127.0.0.1:<port>/anthropic``),and the vendor token endpoint (hardcoded ``https://platform.claude.com``)reached through the TLS-intercepting proxy — nothing of ours is faked.-The first model call is answered with a tool call; the follow-up call (same,-now expired, bearer) gets the vendor's 401. The single-use refresh token must-be spent exactly once, the retry must carry the new bearer, and auth.json must-hold the NEW, still-live refresh token afterwards — otherwise the next process-replays a spent token and the login is lost.+Two triggers for the refresh:++* the vendor's 401 — the first model call is answered with a tool call and the+ follow-up call (same, now expired, bearer) gets ``authentication_error``;+* the clock — the stored row's ``expires_at_ms`` is already in the past when the+ turn starts, so the refresh must happen BEFORE the first call (zero 401s).++Either way the single-use refresh token must be spent exactly once, every call+after the refresh must carry the new bearer, and auth.json must hold the NEW,+still-live refresh token afterwards — otherwise the next process replays a spent+token and the login is lost."""from __future__ import annotations@@ -22,19 +28,29 @@ import uuidimport pytest-from tests.e2e.core.providers._oauth_helpers import OLD_ACCESS, run_hermes, start_anthropic_rig, wait_until+from tests.e2e.core.providers._oauth_helpers import (+ EXPIRED,+ OLD_ACCESS,+ Hold,+ credential,+ run_hermes,+ start_anthropic_rig,+ text,+ tool,+ wait_until,+)pytestmark = pytest.mark.skipif(not sys.platform.startswith("linux"), reason="tagged-tree cleanup uses /proc")FINAL = "OAUTH-REFRESH-TURN-COMPLETE"-EXPIRED = ("error", 401, "authentication_error", "OAuth token has expired")SLOW_TOKEN_ENDPOINT_S = 2.0-# Red on main for a tracked, open bug. Strict: XPASS fails, forcing the entry out with the fix.-KNOWN: dict[str, str] = {- "aux_call_shares_expired_token": (- "#120815 a stale credential pool (the auxiliary title call's) persists the spent refresh token "- "over the rotation the main turn just committed"),+CASES = {+ "main_turn_only": {"aux_401": False, "clock_expired": False},+ # Regression for #120815: a stale credential pool (the auxiliary title call's) persisted the+ # spent refresh token over the rotation the main turn had just committed.+ "aux_call_shares_expired_token": {"aux_401": True, "clock_expired": False},+ "expired_by_clock_refreshes_before_first_call": {"aux_401": False, "clock_expired": True},}@@ -43,35 +59,38 @@ def _has_tool_result(body: dict) -> bool:for m in body.get("messages") or [])-def _run_turn(tmp_path, *, aux_401: bool):+def _run_turn(tmp_path, *, aux_401: bool, clock_expired: bool):canary = f"CANARY-{uuid.uuid4().hex[:10]}"note = tmp_path / "note.txt"note.write_text(canary, encoding="utf-8")- # Race order that loses the login on main, pinned with events: the auxiliary (title) call is- # sent with the expired bearer before the main turn refreshes, and its 401 lands while the+ # Race order that lost the login in #120815, pinned with events: the auxiliary (title) call+ # is sent with the expired bearer before the main turn refreshes, and its 401 lands while the# main turn's refresh POST is in flight (the vendor token endpoint answers slowly).aux_sent, refresh_in_flight, aux_answered, aux_settled = (threading.Event() for _ in range(4))aux_answered_at: list[int] = []- def answer_aux() -> tuple:+ def answer_aux():aux_answered_at.append(time.time_ns())aux_answered.set()return EXPIRED- def decide(record: dict) -> tuple:- body, bearer = record["body"], record["bearer"] or record["x_api_key"]+ def decide(record: dict):+ body, bearer = record["body"], credential(record)if not body.get("tools"): # auxiliary call (title generation)if aux_401 and bearer == OLD_ACCESS:aux_sent.set()- return ("hold", refresh_in_flight, ("call", answer_aux))- return ("text", "OAuth refresh title")+ return Hold(refresh_in_flight, answer_aux)+ return text("OAuth refresh title")+ if bearer == OLD_ACCESS and clock_expired:+ return EXPIRED # a clock-expired token reached the wire: the assertions below name itif not _has_tool_result(body):- return ("tool", "read_file", {"path": str(note)})+ return tool("read_file", {"path": str(note)})if bearer == OLD_ACCESS:- return ("hold", aux_sent, EXPIRED) if aux_401 else EXPIRED- return ("hold", aux_settled, ("text", FINAL)) if aux_401 else ("text", FINAL)+ return Hold(aux_sent, EXPIRED) if aux_401 else EXPIRED+ return Hold(aux_settled, text(FINAL)) if aux_401 else text(FINAL)- rig = start_anthropic_rig(tmp_path, decide, title_generation=aux_401)+ expires = int(time.time() * 1000) - 60_000 if clock_expired else None+ rig = start_anthropic_rig(tmp_path, decide, title_generation=aux_401, expires_at_ms=expires)def slow_token_endpoint(_grant) -> None:refresh_in_flight.set()@@ -101,19 +120,16 @@ def _run_turn(tmp_path, *, aux_401: bool):return rig, proc, canary[email protected]("case", [- pytest.param("main_turn_only", id="main_turn_only"),- pytest.param("aux_call_shares_expired_token", id="aux_call_shares_expired_token",- marks=pytest.mark.xfail(strict=True, reason=KNOWN["aux_call_shares_expired_token"])),-])[email protected]("case", list(CASES))def test_expired_oauth_token_mid_turn_refreshes_once_and_persists(case: str, tmp_path) -> None:- rig, proc, canary = _run_turn(tmp_path, aux_401=case != "main_turn_only")+ rig, proc, canary = _run_turn(tmp_path, **CASES[case])out = f"exit={proc.returncode}\nstdout:\n{proc.stdout[-1500:]}\nstderr:\n{proc.stderr[-2500:]}"mains = rig.messages.main_requests()grants = rig.tokens.refresh_grants()assert proc.returncode == 0 and FINAL in proc.stdout, f"turn did not deliver the answer\n{out}"assert not rig.proxy.refused or all("claude" not in r and "anthropic" not in r for r in rig.proxy.refused)+ assert not rig.messages.schema_errors(), f"request bodies violate the SDK schema: {rig.messages.schema_errors()}"assert len(grants) == 1 and grants[0].status == 200, (f"expected exactly one successful refresh grant, got {[(g.presented, g.status, g.error) for g in grants]}")assert grants[0].presented == rig.seed_refresh, "the refresh spent a token other than the stored one"@@ -121,8 +137,12 @@ def test_expired_oauth_token_mid_turn_refreshes_once_and_persists(case: str, tmptool_rounds = [r for r in mains if _has_tool_result(r["body"])]assert any(canary in str(r["body"]) for r in tool_rounds), "the tool result never reached the model"- assert [r["bearer"] or r["x_api_key"] for r in tool_rounds][-1] == new_access, (+ assert [credential(r) for r in tool_rounds][-1] == new_access, ("the retried request did not carry the refreshed bearer")+ if CASES[case]["clock_expired"]:+ stale = [i for i, r in enumerate(rig.messages.requests) if credential(r) == OLD_ACCESS]+ assert not stale, (+ f"a token already expired by the clock was sent (requests {stale}); the refresh must precede the call")row = rig.pool_row("e1")assert rig.tokens.is_live(row.get("refresh_token", "")), (diff --git a/tests/e2e/core/providers/test_oauth_shared_pool.py b/tests/e2e/core/providers/test_oauth_shared_pool.pyindex 68d7043e6ed..bb6e7932ad4 100644--- a/tests/e2e/core/providers/test_oauth_shared_pool.py+++ b/tests/e2e/core/providers/test_oauth_shared_pool.py@@ -10,8 +10,8 @@ answered with the new bearer, and the refresh token on disk still live.Everything is real Hermes (pool, persistence, locking, the Anthropic OAuthrefresh over TLS through the intercepting proxy); only the vendor endpoints are-loopback fakes. The single-process variant of the stale-writer bug (#120815) is-covered as a strict xfail in test_oauth_anthropic_refresh.py.+loopback fakes. The single-process variant of the stale-writer bug (#120815, fixed)+is pinned by test_oauth_anthropic_refresh.py."""from __future__ import annotations@@ -21,11 +21,19 @@ import threadingimport pytest-from tests.e2e.core.providers._oauth_helpers import OLD_ACCESS, run_hermes, start_anthropic_rig, wait_until+from tests.e2e.core.providers._oauth_helpers import (+ EXPIRED,+ OLD_ACCESS,+ Hold,+ credential,+ run_hermes,+ start_anthropic_rig,+ text,+ wait_until,+)pytestmark = pytest.mark.skipif(not sys.platform.startswith("linux"), reason="tagged-tree cleanup uses /proc")-EXPIRED = ("error", 401, "authentication_error", "OAuth token has expired")SLOW_TOKEN_ENDPOINT_S = 2.0 # vendor latency window while both processes contend, not synchronization@@ -38,22 +46,22 @@ def test_concurrent_refresh_across_processes_spends_the_token_once(tmp_path) ->rejected: list[str] = []lock = threading.Lock()- def reject(who: str) -> tuple:+ def reject(who: str):with lock:rejected.append(who)if len(rejected) >= 2:both_rejected.set()return EXPIRED- def decide(record: dict) -> tuple:- who, bearer = _who(record), record["bearer"] or record["x_api_key"]+ def decide(record: dict):+ who, bearer = _who(record), credential(record)if bearer != OLD_ACCESS:- return ("text", f"ANSWER-{who}")+ return text(f"ANSWER-{who}")if who == "B":b_arrived.set()- return ("call", lambda: reject("B"))+ return lambda: reject("B")# A's 401 is released only once B's expired call is in, so both hit the expiry together.- return ("hold", b_arrived, ("call", lambda: reject("A")))+ return Hold(b_arrived, lambda: reject("A"))rig = start_anthropic_rig(tmp_path, decide, title_generation=False)@@ -83,14 +91,14 @@ def test_concurrent_refresh_across_processes_spends_the_token_once(tmp_path) ->grants = rig.tokens.refresh_grants()summary = [(g.presented, g.status, g.error) for g in grants]assert sorted(rejected) == ["A", "B"], f"setup: both processes must see the 401 (saw {rejected})"+ assert not rig.messages.schema_errors(), f"request bodies violate the SDK schema: {rig.messages.schema_errors()}"assert [g.status for g in grants] == [200], (f"the single-use refresh token must be spent exactly once across processes; grants={summary}\n"f"{show('A', proc_a)}\n{show('B', proc_b)}")new_access, new_refresh = grants[0].issued_access_token, grants[0].issued_refresh_tokenfor name, proc in (("A", proc_a), ("B", proc_b)):assert proc.returncode == 0 and f"ANSWER-{name}" in proc.stdout, show(name, proc)- retried = {_who(r): r["bearer"] or r["x_api_key"] for r in rig.messages.main_requests()- if (r["bearer"] or r["x_api_key"]) != OLD_ACCESS}+ retried = {_who(r): credential(r) for r in rig.messages.main_requests() if credential(r) != OLD_ACCESS}assert retried == {"A": new_access, "B": new_access}, f"retries did not use the rotated bearer: {retried}"row = rig.pool_row("e1")assert row.get("refresh_token") == new_refresh and rig.tokens.is_live(new_refresh), (