Skip to content

The agent that grows with you

test: providers-openai E2E review fixes: decoys on the custom: slug path, fail-fast strict endpoint, Responses faults, KNOWN hygiene

teknium1b1d70cc5a149
diff --git a/tests/e2e/core/providers/_openai_helpers.py b/tests/e2e/core/providers/_openai_helpers.py
index 3beed0cec08..d9061f7a99e 100644
--- a/tests/e2e/core/providers/_openai_helpers.py
+++ b/tests/e2e/core/providers/_openai_helpers.py
@@ -15,10 +15,12 @@ import sqlite3
import subprocess
import sys
import time
+from contextlib import contextmanager
from dataclasses import dataclass
from pathlib import Path
-from typing import Any, Callable
+from typing import Any, Callable, Iterator
+import pytest
import yaml
REPO_ROOT = Path(__file__).resolve().parents[4]
@@ -26,6 +28,73 @@ TURN_TIMEOUT = 150.0
_SECRET_ENV_SUFFIXES = ("_API_KEY", "_TOKEN", "_SECRET", "_ACCESS_KEY")
_PASSTHROUGH_ENV = frozenset({"PATH", "LANG", "LANGUAGE", "USER", "LOGNAME", "SHELL", "TMPDIR", "TZ"})
+
+# KNOWN-bug plumbing ------------------------------------------------------------------
+
+
+class HarnessError(RuntimeError):
+ """The harness broke (a process died, a reply or event never came, a turn overran its
+ budget). Never an ``AssertionError``, so a KNOWN strict xfail can never excuse it."""
+
+
+class KnownBugError(AssertionError):
+ """Raised ONLY from inside ``bug_assertions()``: the one exception a KNOWN strict xfail
+ accepts. Preconditions, waits and teardown outside that block fail the test for real."""
+
+
+def known_marks(known: dict[str, str], name: str) -> list:
+ """Marks for a scenario: a strict xfail while ``name`` is in ``known`` (red the moment
+ the bug is fixed, forcing the entry out), nothing once it is gone."""
+ if name not in known:
+ return []
+ return [pytest.mark.xfail(strict=True, raises=KnownBugError, reason=known[name])]
+
+
+@contextmanager
+def bug_assertions() -> Iterator[None]:
+ """Wrap ONLY the final behavioural assertions that name the bug, after every wait has
+ settled; an ``AssertionError`` raised inside becomes a ``KnownBugError``."""
+ try:
+ yield
+ except KnownBugError:
+ raise
+ except AssertionError as exc:
+ raise KnownBugError(str(exc)) from exc
+
+
+# Vendor-boundary sitecustomize shims ---------------------------------------------------
+
+_CHAIN_ORIGINAL_SITECUSTOMIZE = '''\
+def _chain_original_sitecustomize():
+ """This shim dir is first on PYTHONPATH and shadows any sitecustomize the interpreter
+ already had (a venv or distro one): find the next one on sys.path and run it too."""
+ import importlib.machinery
+ import importlib.util
+ import os
+ import sys
+
+ here = os.path.dirname(os.path.abspath(__file__))
+ rest = [p for p in sys.path if os.path.abspath(p or os.curdir) != here]
+ spec = importlib.machinery.PathFinder.find_spec("sitecustomize", rest)
+ if spec is None or spec.loader is None:
+ return
+ module = importlib.util.module_from_spec(spec)
+ sys.modules["_e2e_original_sitecustomize"] = module
+ spec.loader.exec_module(module)
+
+
+_chain_original_sitecustomize()
+'''
+
+
+def write_sitecustomize_shim(shim_dir: Path, body: str) -> Path:
+ """Write ``body`` as ``shim_dir/sitecustomize.py`` after a prologue that chain-imports
+ the interpreter's original ``sitecustomize`` (the shim must not shadow it)."""
+ shim_dir.mkdir(parents=True, exist_ok=True)
+ (shim_dir / "sitecustomize.py").write_text(_CHAIN_ORIGINAL_SITECUSTOMIZE + "\n\n" + body, encoding="utf-8")
+ return shim_dir
+
+
# One tool Hermes always offers on the CLI toolset and that has an observable,
# side-effect-free result: the model reads a file the fixture wrote.
READ_TOOL = "read_file"
@@ -56,7 +125,7 @@ class Home:
credential env would silently reroute the child."""
import pwd # the suite is Linux-gated
- real_root = Path(pwd.getpwuid(os.getuid()).pw_dir, ".hermes").resolve()
+ real_root = Path(pwd.getpwuid(os.getuid()).pw_dir, ".hermes").resolve() # windows-footgun: ok — every file here is skipif(not linux)
fixture = self.hermes_home.resolve()
assert fixture != real_root and fixture.parent != real_root / "profiles", "fixture is a live home"
env = {k: v for k, v in os.environ.items()
@@ -148,12 +217,21 @@ def oneshot(h: Home, prompt: str, *args: str, resume: str | None = None, timeout
argv = ["-z", prompt, "--usage-file", str(usage_file), *args]
if resume:
argv += ["--resume", resume]
- proc = subprocess.run(hermes_argv(*argv), cwd=h.project, env=h.env(env), capture_output=True, text=True,
- timeout=timeout, stdin=subprocess.DEVNULL)
+ proc = subprocess.run(hermes_argv(*argv), cwd=h.project, env=h.env(env), capture_output=True,
+ text=True, encoding="utf-8", errors="replace", timeout=timeout, stdin=subprocess.DEVNULL)
usage = json.loads(usage_file.read_text(encoding="utf-8")) if usage_file.exists() else {}
return Run(proc, usage)
+def bounded_turn(h: Home, prompt: str, budget: float, **kw: Any) -> Run:
+ """One ``oneshot`` turn that must finish inside ``budget`` seconds; overrunning it is a
+ ``HarnessError`` (never an ``AssertionError`` a KNOWN xfail could swallow)."""
+ try:
+ return oneshot(h, prompt, timeout=budget, **kw)
+ except subprocess.TimeoutExpired as exc:
+ raise HarnessError(f"turn {prompt!r} still running after {budget}s") from exc
+
+
def wait_until(pred: Callable[[], Any], timeout: float, what: str, interval: float = 0.05) -> Any:
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
@@ -161,7 +239,7 @@ def wait_until(pred: Callable[[], Any], timeout: float, what: str, interval: flo
if value:
return value
time.sleep(interval)
- raise AssertionError(f"timed out after {timeout}s waiting for {what}")
+ raise HarnessError(f"timed out after {timeout}s waiting for {what}")
# Persisted state ---------------------------------------------------------------------
diff --git a/tests/e2e/core/providers/_openai_tui.py b/tests/e2e/core/providers/_openai_tui.py
index 632cfdc7bcb..8ff1184cb5f 100644
--- a/tests/e2e/core/providers/_openai_tui.py
+++ b/tests/e2e/core/providers/_openai_tui.py
@@ -12,7 +12,7 @@ import time
from pathlib import Path
from typing import Any, Callable
-from tests.e2e.core.providers._openai_helpers import Home
+from tests.e2e.core.providers._openai_helpers import HarnessError, Home
class TuiGateway:
@@ -23,6 +23,9 @@ class TuiGateway:
self._stderr = open(self.stderr_path, "wb") # noqa: SIM115 - closed in close()
self.proc = subprocess.Popen([sys.executable, "-m", "tui_gateway.entry"], cwd=h.project, env=env,
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=self._stderr, bufsize=0)
+ if self.proc.stdin is None or self.proc.stdout is None:
+ raise HarnessError("tui_gateway spawned without stdio pipes")
+ self._stdin, self._stdout = self.proc.stdin, self.proc.stdout
self._ids = itertools.count(1)
self._cv = threading.Condition()
self._responses: dict[int, dict[str, Any]] = {}
@@ -30,8 +33,7 @@ class TuiGateway:
threading.Thread(target=self._read, name="tui-rpc", daemon=True).start()
def _read(self) -> None:
- assert self.proc.stdout is not None
- for raw in iter(self.proc.stdout.readline, b""):
+ for raw in iter(self._stdout.readline, b""):
try:
frame = json.loads(raw)
except json.JSONDecodeError:
@@ -47,20 +49,19 @@ class TuiGateway:
def call(self, method: str, params: dict[str, Any] | None = None, timeout: float = 90.0) -> dict[str, Any]:
rid = next(self._ids)
- assert self.proc.stdin is not None
- self.proc.stdin.write(json.dumps({"jsonrpc": "2.0", "id": rid, "method": method,
- "params": params or {}}).encode() + b"\n")
- self.proc.stdin.flush()
+ self._stdin.write(json.dumps({"jsonrpc": "2.0", "id": rid, "method": method,
+ "params": params or {}}).encode() + b"\n")
+ self._stdin.flush()
deadline = time.monotonic() + timeout
with self._cv:
while rid not in self._responses:
left = deadline - time.monotonic()
if left <= 0 or self.proc.poll() is not None:
- raise AssertionError(f"no reply to {method} (rc={self.proc.poll()}){self.tail()}")
+ raise HarnessError(f"no reply to {method} (rc={self.proc.poll()}){self.tail()}")
self._cv.wait(min(left, 0.5))
frame = self._responses.pop(rid)
if "error" in frame:
- raise AssertionError(f"{method} -> {frame['error']}{self.tail()}")
+ raise HarnessError(f"{method} -> {frame['error']}{self.tail()}")
return frame["result"]
def wait_event(self, pred: Callable[[dict[str, Any]], bool], timeout: float, start: int = 0) -> dict[str, Any]:
@@ -75,14 +76,15 @@ class TuiGateway:
return {**ev, "_i": seen - 1}
left = deadline - time.monotonic()
if left <= 0 or self.proc.poll() is not None:
- raise AssertionError(f"event never arrived within {timeout}s{self.tail()}")
+ raise HarnessError(f"event never arrived within {timeout}s{self.tail()}")
self._cv.wait(min(left, 0.5))
def turn(self, sid: str, text: str, timeout: float = 120.0) -> str:
"""Submit one prompt and return the completed assistant text once the session settles."""
start = len(self.events)
reply = self.call("prompt.submit", {"session_id": sid, "text": text})
- assert reply.get("status") == "streaming", reply
+ if reply.get("status") != "streaming":
+ raise HarnessError(f"prompt.submit did not start streaming: {reply}{self.tail()}")
done = self.wait_event(lambda e: e.get("type") == "message.complete" and e.get("session_id") == sid,
timeout, start)
self.wait_event(lambda e: e.get("type") == "session.info" and e.get("session_id") == sid
@@ -93,8 +95,7 @@ class TuiGateway:
def close(self, timeout: float = 30.0) -> int | None:
try:
- assert self.proc.stdin is not None
- self.proc.stdin.close()
+ self._stdin.close()
return self.proc.wait(timeout=timeout)
except (OSError, subprocess.TimeoutExpired):
self.proc.kill()
diff --git a/tests/e2e/core/providers/test_chat_custom_endpoint.py b/tests/e2e/core/providers/test_chat_custom_endpoint.py
index 92d6f97d580..132e3cf1c39 100644
--- a/tests/e2e/core/providers/test_chat_custom_endpoint.py
+++ b/tests/e2e/core/providers/test_chat_custom_endpoint.py
@@ -4,7 +4,11 @@
query found in messages``). The fake enforces that rule on every main request while
the session goes through a tool continuation, a stream that drops mid-tool-call and
is retried, and a ``--resume`` of the result: no request may ever lack the user turn
- (#120828 reports one escaping on a continuation/retry path).
+ (#120828 reports one escaping on a continuation/retry path). Ollama answers that
+ refusal with a 500, which Hermes (correctly, it cannot tell) treats as a transient
+ outage and keeps retrying under ``agent.auto_recovery_cycles`` for minutes; the test
+ turns that recovery off and bounds each turn, and checks the recorded requests FIRST so
+ a regression fails in seconds naming the request that lost the user turn.
* A tool call whose ``arguments`` are unrepairable JSON must be repaired or surfaced —
the model has to learn its call did not run (a tool result naming the failure) or the
turn has to fail visibly. Silently dropping the call and re-asking the identical
@@ -19,24 +23,30 @@ import pytest
from tests.e2e.core.providers._openai_helpers import (
READ_TOOL,
+ HarnessError,
Home,
+ bug_assertions,
chat_messages,
custom_chat_config,
db_tool_calls,
db_messages,
+ bounded_turn,
+ known_marks,
oneshot,
)
from tests.fakes.providers.chat_variants import CDropToolCall, CText, CTools, FakeChatVariantServer
pytestmark = pytest.mark.skipif(not sys.platform.startswith("linux"), reason="subprocess harness is Linux-gated")
+STRICT_TURN_BUDGET = 60.0
+
KNOWN: dict[str, str] = {
"unrepairable_args_surfaced": "#119389 unrepairable tool_call arguments silently dropped, turn reports success",
}
def known(name: str) -> list:
- return [pytest.mark.xfail(strict=True, raises=AssertionError, reason=KNOWN[name])] if name in KNOWN else []
+ return known_marks(KNOWN, name)
def test_ollama_strict_endpoint_always_receives_the_user_turn(tmp_path) -> None:
@@ -49,16 +59,26 @@ def test_ollama_strict_endpoint_always_receives_the_user_turn(tmp_path) -> None:
CTools([(READ_TOOL, {"path": "a.txt"})]), # resumed session continues with a tool
CText("SECOND-DONE"),
]
+ overrun: HarnessError | None = None
with FakeChatVariantServer(script, strict_user_turn=True) as srv:
- h.write(custom_chat_config(srv.base_url, model="qwen3:27b"), dotenv={"OPENAI_API_KEY": "ollama"})
+ cfg = custom_chat_config(srv.base_url, model="qwen3:27b")
+ # The strict 500 is retryable to Hermes; no minutes-long auto-recovery on a regression.
+ cfg["agent"] = {"auto_recovery_cycles": 0}
+ h.write(cfg, dotenv={"OPENAI_API_KEY": "ollama"})
(h.project / "a.txt").write_text("CANARY-A\n", encoding="utf-8")
(h.project / "b.txt").write_text("CANARY-B\n", encoding="utf-8")
- first = oneshot(h, "read a.txt then b.txt")
- second = oneshot(h, "read a.txt again", resume=first.session_id)
+ try:
+ first = bounded_turn(h, "read a.txt then b.txt", STRICT_TURN_BUDGET)
+ second = bounded_turn(h, "read a.txt again", STRICT_TURN_BUDGET, resume=first.session_id)
+ except HarnessError as exc:
+ overrun = exc
records = srv.main_records()
- no_user = [i for i, r in enumerate(records) if not chat_messages(r["body"], "user")]
- assert no_user == [], f"requests {no_user} carried no user message (Ollama answers 500)"
+ no_user = [(i, [m.get("role") for m in chat_messages(r["body"])]) for i, r in enumerate(records)
+ if not chat_messages(r["body"], "user")]
+ assert no_user == [], f"requests (index, roles) {no_user} carried no user message (Ollama answers 500)"
+ if overrun is not None:
+ raise overrun
assert first.proc.returncode == 0 and first.stdout.strip() == "FIRST-DONE", first.describe()
assert second.proc.returncode == 0 and second.stdout.strip() == "SECOND-DONE", second.describe()
assert [r["response"] for r in records] == [type(s).__name__ for s in script], "precondition: script consumed"
@@ -83,6 +103,7 @@ def test_unrepairable_tool_arguments_are_surfaced_not_dropped(tmp_path, finish)
m.get("role") == "tool" or "write_file" in str(m.get("content") or "")
for m in mains[1]["messages"][len(mains[0]["messages"]):])
failed_visibly = run.proc.returncode != 0 or run.usage.get("failed")
- assert told or failed_visibly, (
- "the unparseable write_file call vanished: the next request never told the model it did not run "
- f"and the turn reported success ({run.stdout.strip()!r}); out.md={(h.project / 'out.md').read_text()!r}")
+ with bug_assertions():
+ assert told or failed_visibly, (
+ "the unparseable write_file call vanished: the next request never told the model it did not run "
+ f"and the turn reported success ({run.stdout.strip()!r}); out.md={(h.project / 'out.md').read_text()!r}")
diff --git a/tests/e2e/core/providers/test_chat_errors.py b/tests/e2e/core/providers/test_chat_errors.py
index c909c1570aa..c3c434502d1 100644
--- a/tests/e2e/core/providers/test_chat_errors.py
+++ b/tests/e2e/core/providers/test_chat_errors.py
@@ -24,9 +24,11 @@ import pytest
from tests.e2e.core.providers._openai_helpers import (
Home,
+ bug_assertions,
custom_chat_config,
db_messages,
db_tool_calls,
+ known_marks,
oneshot,
tool_call_args,
)
@@ -41,8 +43,8 @@ from tests.fakes.providers.chat_variants import (
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.
+# Scenario -> "#issue one-line symptom" for scenarios red on origin/main (strict xfail that
+# only a KnownBugError from bug_assertions() satisfies; see known_marks).
KNOWN: dict[str, str] = {
"in_stream_ban_fails_once": "#121270 in-stream error code 403 ignored: ban retried, reported as temporarily unavailable",
}
@@ -55,8 +57,7 @@ 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 []
+ return known_marks(KNOWN, name)
def _home(tmp_path, srv: FakeChatVariantServer, **config) -> Home:
@@ -145,8 +146,10 @@ def test_in_stream_upstream_ban_fails_once_and_visibly(tmp_path, _) -> None:
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()}"
+ assert records, f"precondition: the endpoint was reached: {run.describe()}"
+ with bug_assertions():
+ 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_chat_reasoning_variants.py b/tests/e2e/core/providers/test_chat_reasoning_variants.py
index feaa20fd13c..06c6c98a85f 100644
--- a/tests/e2e/core/providers/test_chat_reasoning_variants.py
+++ b/tests/e2e/core/providers/test_chat_reasoning_variants.py
@@ -24,9 +24,11 @@ import pytest
from tests.e2e.core.providers._openai_helpers import (
READ_TOOL,
Home,
+ bug_assertions,
chat_messages,
custom_chat_config,
db_messages,
+ known_marks,
oneshot,
)
from tests.e2e.core.providers._openai_tui import TuiGateway
@@ -41,7 +43,7 @@ KNOWN: dict[str, str] = {
def known(name: str) -> list:
- return [pytest.mark.xfail(strict=True, raises=AssertionError, reason=KNOWN[name])] if name in KNOWN else []
+ return known_marks(KNOWN, name)
def _rd(tag: str, text: str | None = None) -> list[dict]:
@@ -148,4 +150,5 @@ def test_long_session_does_not_wedge_on_replayed_reasoning_budget(tmp_path, scen
rejected = [i for i, r in enumerate(records) if r.get("response") == "route_rejection"]
assert rejected, "precondition: the replayed total crossed the route budget at least once"
missing = [i for i in range(turns) if f"ANSWER-{i}" not in answers[i]]
- assert not missing, f"turns {missing} were not answered once replayed reasoning passed the budget: {answers}"
+ with bug_assertions():
+ assert not missing, f"turns {missing} were not answered once replayed reasoning passed the budget: {answers}"
diff --git a/tests/e2e/core/providers/test_fallback_providers.py b/tests/e2e/core/providers/test_fallback_providers.py
index bd6e4a1292e..dd7527d43f1 100644
--- a/tests/e2e/core/providers/test_fallback_providers.py
+++ b/tests/e2e/core/providers/test_fallback_providers.py
@@ -6,9 +6,10 @@ 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 that answers turn 1 and then every request with 503 is tried on turn 2
+ (a ``--resume``), then that turn is answered by the configured fallback, which receives
+ the FULL conversation (system prompt, turn 1's prompt and answer, turn 2's prompt) 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).
@@ -19,7 +20,6 @@ from __future__ import annotations
import base64
import json
import socket
-import subprocess
import sys
import threading
import time
@@ -31,66 +31,80 @@ import pytest
from tests.e2e.core.providers._openai_helpers import (
Home,
+ bounded_turn,
+ bug_assertions,
chat_messages,
custom_chat_config,
db_messages,
- oneshot,
+ known_marks,
)
from tests.fakes.fake_llm_provider import FakeLLMServer
-from tests.fakes.providers.chat_variants import CError, FakeChatVariantServer
+from tests.fakes.providers.chat_variants import CError, CText, 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.
+# Scenario -> "#issue one-line symptom" for scenarios red on origin/main (strict xfail that
+# only a KnownBugError from bug_assertions() satisfies; see known_marks).
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"
+FIRST_PROMPT = "CANARY-FIRST what is two plus two"
+# A primary that is never abandoned for the fallback keeps backing off for minutes, so a
+# turn overrunning this is a HarnessError (a real failure even under a KNOWN xfail).
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 []
+ return known_marks(KNOWN, name)
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:
+def _turns(body: dict) -> list[tuple[str, str]]:
+ """``(role, text)`` of every non-system message: the conversation a request carries."""
+ return [(m["role"], str(m.get("content") or "")) for m in chat_messages(body) if m.get("role") != "system"]
+
+
+def test_persistent_primary_503_is_answered_by_fallback_with_full_conversation(tmp_path) -> None:
+ def answer_once_then_503(_record: dict) -> CText | CError:
+ if not primary.main_records()[:-1]: # this request is the only one so far: turn 1
+ return CText("FIRST-ON-PRIMARY")
return CError(503, "Service temporarily unavailable", code="service_unavailable")
- with FakeChatVariantServer(always_503) as primary, FakeLLMServer(default_text="FROM-FALLBACK") as fallback:
+ with FakeChatVariantServer(answer_once_then_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)
+ first = bounded_turn(h, FIRST_PROMPT, TURN_BUDGET)
+ assert first.proc.returncode == 0 and first.stdout.strip() == "FIRST-ON-PRIMARY", first.describe()
+ run = bounded_turn(h, PROMPT, TURN_BUDGET, resume=first.session_id)
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 len(primary_mains) >= 2, "the primary was never tried on turn 2"
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")
+ fb = fallback_mains[0]
+ assert fb.get("model") == FALLBACK_MODEL, fb.get("model")
+ # The fallback gets the whole conversation, not just the prompt that failed over.
+ system = chat_messages(fb, "system")
+ assert system and str(system[0].get("content") or "").strip() and chat_messages(fb)[0] is system[0], (
+ f"fallback request carries no leading system prompt: {chat_messages(fb)[:1]}")
+ want = [("user", FIRST_PROMPT), ("assistant", "FIRST-ON-PRIMARY"), ("user", PROMPT)]
+ canaries = [(role, next((w for _r, w in want if w in text), None)) for role, text in _turns(fb)]
+ assert [c for c in canaries if c[1]] == want, _turns(fb)
+ # Exactly what the primary was last asked, minus nothing.
+ assert _turns(fb) == _turns(primary_mains[-1]), (_turns(fb), _turns(primary_mains[-1]))
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 "")]
@@ -179,12 +193,13 @@ def test_primary_credential_resolution_failure_falls_back(tmp_path, portal_kind:
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)
+ run = bounded_turn(h, PROMPT, TURN_BUDGET, 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()
+ with bug_assertions():
+ 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
index 7e7c2de60b7..1bd64eee9ea 100644
--- a/tests/e2e/core/providers/test_openai_codex_pool.py
+++ b/tests/e2e/core/providers/test_openai_codex_pool.py
@@ -33,7 +33,14 @@ from urllib.parse import parse_qs
import pytest
-from tests.e2e.core.providers._openai_helpers import REPO_ROOT, Home, oneshot
+from tests.e2e.core.providers._openai_helpers import (
+ REPO_ROOT,
+ Home,
+ bug_assertions,
+ known_marks,
+ oneshot,
+ write_sitecustomize_shim,
+)
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")
@@ -44,8 +51,7 @@ KNOWN: dict[str, str] = {
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 []
+ return known_marks(KNOWN, name)
TOKEN_URL = "https://auth.openai.com/oauth/token"
@@ -164,8 +170,7 @@ def _pool_store(a: dict[str, str], b: dict[str, str], now: float) -> dict[str, A
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")
+ write_sitecustomize_shim(tmp_path / "shim", _SHIM)
return h
@@ -230,10 +235,11 @@ def test_dead_grant_on_independent_login_keeps_login_a(tmp_path, scenario) -> No
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)}")
+ with bug_assertions():
+ 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:
diff --git a/tests/e2e/core/providers/test_openai_pricing.py b/tests/e2e/core/providers/test_openai_pricing.py
index 942772cf5b6..14562b262b8 100644
--- a/tests/e2e/core/providers/test_openai_pricing.py
+++ b/tests/e2e/core/providers/test_openai_pricing.py
@@ -11,8 +11,11 @@ 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.
+row (credentialed from ``.env``) is the control that prices from the same catalog. Two relays
+serving a catalog model id are decoys that must NOT borrow its prices: ``myrelay`` (a plain
+``myrelay`` row) and one keyed ``deepseek`` — a built-in, non-aggregator provider name, so its
+row takes the same ``custom:<key>`` slug path as the twin. Prices must follow the upstream a
+row actually talks to, not the ``custom:`` slug shape.
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
@@ -31,7 +34,13 @@ from typing import Any
import pytest
-from tests.e2e.core.providers._openai_helpers import REPO_ROOT, Home
+from tests.e2e.core.providers._openai_helpers import (
+ REPO_ROOT,
+ Home,
+ bug_assertions,
+ known_marks,
+ write_sitecustomize_shim,
+)
from tests.e2e.core.providers._openai_tui import TuiGateway
pytestmark = pytest.mark.skipif(not sys.platform.startswith("linux"), reason="subprocess harness is Linux-gated")
@@ -42,8 +51,7 @@ KNOWN: dict[str, str] = {
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 []
+ return known_marks(KNOWN, name)
VENDOR_ORIGIN = "https://openrouter.ai"
@@ -55,6 +63,9 @@ CATALOG = [
]
TWIN_MODELS = [mid for mid, _p, _c in CATALOG]
RELAY_MODEL = TWIN_MODELS[-1]
+# (config key, picker slug) of each decoy relay. ``deepseek`` collides with a built-in
+# non-aggregator provider, so its row is ``custom:deepseek`` -- the twin's slug shape.
+DECOYS = [("myrelay", "myrelay"), ("deepseek", "custom:deepseek")]
_SHIM = '''\
"""E2E vendor-boundary shim: route a hard-coded vendor origin to a loopback fake."""
@@ -154,8 +165,7 @@ def _closed_port() -> socket.socket:
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")
+ write_sitecustomize_shim(tmp_path / "shim", _SHIM)
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}",
@@ -166,11 +176,14 @@ def _home(tmp_path: Path, catalog: FakeCatalog, dead: socket.socket) -> _ShimHom
"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]},
+ # Decoys: serve a catalog model id, but are relays with no price catalog of their own.
+ **{key: {"name": f"Relay {key}", "base_url": f"{catalog.origin}/relay/v1",
+ "api_key": "sk-relay-fake", "models": [RELAY_MODEL]} for key, _slug in DECOYS},
},
- }, dotenv={"OPENROUTER_API_KEY": "sk-or-fake-builtin"})
+ }, dotenv={"OPENROUTER_API_KEY": "sk-or-fake-builtin",
+ # The picker lists a providers: entry keyed by a built-in name only while that
+ # built-in is credentialed; this makes the custom:deepseek decoy row appear.
+ "DEEPSEEK_API_KEY": "sk-ds-fake-builtin"})
return h
@@ -230,13 +243,15 @@ def test_builtin_aggregator_row_prices_from_catalog(picker) -> None:
_expected_price(mid)), (mid, priced[mid])
-def test_relay_without_catalog_gets_no_borrowed_prices(picker) -> None:
[email protected]("slug", [slug for _key, slug in DECOYS])
+def test_relay_without_catalog_gets_no_borrowed_prices(picker, slug: str) -> 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."""
+ a catalog model id but must not borrow the aggregator's prices -- including the
+ ``custom:deepseek`` row, whose slug has the same ``custom:<key>`` shape as the twin."""
payload, _requests = picker
- relay = _row(payload, "myrelay")
+ relay = _row(payload, slug)
assert relay is not None and RELAY_MODEL in (relay.get("models") or []), payload.get("providers")
- assert _priced(relay) == {}, relay.get("pricing")
+ assert _priced(relay) == {}, f"{slug} (upstream: the relay) borrowed prices: {relay.get('pricing')}"
@pytest.mark.parametrize("scenario", [pytest.param("custom_twin_priced", marks=known("custom_twin_priced"))])
@@ -247,9 +262,10 @@ def test_config_defined_twin_row_is_priced_like_the_aggregator(picker, scenario)
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)
+ with bug_assertions():
+ 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)
diff --git a/tests/e2e/core/providers/test_openai_responses.py b/tests/e2e/core/providers/test_openai_responses.py
index e6d369efd98..a1fea2e56d3 100644
--- a/tests/e2e/core/providers/test_openai_responses.py
+++ b/tests/e2e/core/providers/test_openai_responses.py
@@ -15,7 +15,10 @@ Proven here:
``function_call_output`` with its own ``call_id`` and its own result, persisted once;
* a stale encrypted blob rejected with HTTP 400 ``invalid_encrypted_content`` is
stripped and the SAME primary is retried (no fallback, no give-up) — and the HTTP-200
- soft-failure twin of that rejection must behave the same (#120399).
+ soft-failure twin of that rejection must behave the same (#120399);
+* a stream that dies mid-``function_call`` (arguments half streamed, no terminal event) is
+ retried without running the half call, and the completed call runs EXACTLY once;
+* a 429 carrying ``Retry-After`` is retried after the advertised wait, and answers once.
"""
from __future__ import annotations
@@ -28,10 +31,14 @@ import pytest
from tests.e2e.core.providers._openai_helpers import (
READ_TOOL,
Home,
+ bug_assertions,
db_messages,
+ db_tool_calls,
+ known_marks,
oneshot,
responses_input_items,
responses_provider_config,
+ tool_call_args,
)
from tests.e2e.core.providers._openai_tui import TuiGateway
from tests.fakes.fake_llm_provider import FakeLLMServer
@@ -47,16 +54,15 @@ from tests.fakes.providers.openai_responses import (
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.
+# Scenario -> "#issue one-line symptom" for scenarios red on origin/main (strict xfail that
+# only a KnownBugError from bug_assertions() satisfies; see known_marks).
KNOWN: dict[str, str] = {
"soft_failure_recovers_on_primary": "#120399 HTTP-200 invalid_encrypted_content skips replay-strip recovery",
}
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 []
+ return known_marks(KNOWN, name)
def _encs(body: dict) -> list:
@@ -152,10 +158,11 @@ def test_rejected_encrypted_replay_is_stripped_and_primary_retried(tmp_path, rej
fallback_mains = fallback.main_requests()
assert _encs(mains[1]) == ["ENC-STALE"], "precondition: the resumed turn replays the stale blob"
- assert fallback_mains == [], f"fallback engaged instead of replay recovery: {run.describe()}"
- assert len(mains) == 3, [m.get("input") for m in mains]
- assert _encs(mains[2]) == [], "the retry must drop the rejected blob"
- assert run.proc.returncode == 0 and _answer(run) == "RECOVERED-ON-PRIMARY", run.describe()
+ with bug_assertions():
+ assert fallback_mains == [], f"fallback engaged instead of replay recovery: {run.describe()}"
+ assert len(mains) == 3, [m.get("input") for m in mains]
+ assert _encs(mains[2]) == [], "the retry must drop the rejected blob"
+ assert run.proc.returncode == 0 and _answer(run) == "RECOVERED-ON-PRIMARY", run.describe()
def test_tui_gateway_session_replays_reasoning_across_turns(tmp_path) -> None:
@@ -176,3 +183,65 @@ def test_tui_gateway_session_replays_reasoning_across_turns(tmp_path) -> None:
invalid = srv.invalid_requests()
assert invalid == [], invalid
assert len(mains) == 2 and _encs(mains[1]) == ["ENC-T1"], [m.get("input") for m in mains]
+
+
+def _main_records(srv: FakeResponsesServer) -> list[dict]:
+ return [r for r in srv.requests if r["kind"] == "main"]
+
+
+def test_stream_drop_mid_function_call_runs_the_call_once(tmp_path) -> None:
+ """The first stream emits ``response.created``, the ``function_call`` item and HALF its
+ arguments, then the socket closes (no ``.done``, no ``response.completed``)."""
+ command = "echo ran >> count.txt"
+ script = [
+ Turn([FunctionCall("terminal", '{"command": "echo ran >> cou')], drop_after_events=3),
+ Turn([FunctionCall("terminal", {"command": command})]),
+ Turn([Message("TOOL-DONE")]),
+ ]
+ h = Home(tmp_path)
+ with FakeResponsesServer(script) as srv:
+ cfg = responses_provider_config(srv.base_url)
+ cfg["approvals"] = {"mode": "off"}
+ h.write(cfg)
+ run = oneshot(h, "append a line to count.txt", env={"TERMINAL_ENV": "local"})
+ mains = srv.main_requests()
+ invalid = srv.invalid_requests()
+
+ assert run.proc.returncode == 0 and _answer(run) == "TOOL-DONE", run.describe()
+ assert len(mains) == 3, [m.get("input") for m in mains]
+ assert invalid == [], invalid
+ 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 half call never reaches the wire: the retry resends exactly the first request's input.
+ assert mains[1]["input"] == mains[0]["input"], (mains[0]["input"], mains[1]["input"])
+ # The final request replays exactly one call and its one result.
+ calls = responses_input_items(mains[2], "function_call")
+ outputs = responses_input_items(mains[2], "function_call_output")
+ assert [json.loads(c["arguments"]) for c in calls] == [{"command": command}], calls
+ assert [o["call_id"] for o in outputs] == [c["call_id"] for c in calls], outputs
+ persisted = db_tool_calls(db_messages(h, run.session_id))
+ assert [tool_call_args(c) for c in persisted] == [{"command": command}], persisted
+
+
+def test_rate_limit_retry_after_is_honoured(tmp_path) -> None:
+ """HTTP 429 + ``Retry-After: 4`` (clearly above the generic 2-3 s first backoff): the
+ retry waits the advertised time, resends the same input, and the turn answers once."""
+ retry_after = 4.0
+ script = [HttpError(429, "Rate limit reached for requests", code="rate_limit_exceeded", type="requests",
+ retry_after=retry_after),
+ Turn([Message("AFTER-RATE-LIMIT")])]
+ h = Home(tmp_path)
+ with FakeResponsesServer(script) as srv:
+ h.write(responses_provider_config(srv.base_url))
+ run = oneshot(h, "say hello")
+ records = _main_records(srv)
+
+ assert run.proc.returncode == 0 and _answer(run) == "AFTER-RATE-LIMIT", run.describe()
+ assert [r["response"] for r in records] == ["HttpError", "Turn"], run.describe()
+ gap = records[1]["t"] - records[0]["t"]
+ assert gap >= retry_after - 0.1, f"retried {gap:.2f}s after a 429 advertising Retry-After {retry_after}s"
+ assert records[1]["body"]["input"] == records[0]["body"]["input"]
+ answers = [r for r in db_messages(h, run.session_id)
+ if r["role"] == "assistant" and "AFTER-RATE-LIMIT" in (r.get("content") or "")]
+ assert len(answers) == 1, db_messages(h, run.session_id)
diff --git a/tests/fakes/providers/chat_variants.py b/tests/fakes/providers/chat_variants.py
index ea70466ae97..2792b222e6e 100644
--- a/tests/fakes/providers/chat_variants.py
+++ b/tests/fakes/providers/chat_variants.py
@@ -7,7 +7,7 @@ routes that bend the base dialect:
message (streamed as ``delta.reasoning_details``) that the client must replay, and
provider errors delivered as an ``{"error": {...}}`` chunk INSIDE a 200 SSE stream
(an upstream ban or moderation block after the stream opened);
-* DeepSeek-style ``reasoning_content`` (and the ``reasoning`` alias) deltas;
+* DeepSeek-style ``reasoning_content`` deltas;
* Ollama / llama.cpp / custom servers: ``strict_user_turn`` reproduces Ollama's
renderer refusing a payload with no ``user`` message (HTTP 500
``no user query found in messages``); ``reasoning_budget_chars`` reproduces a route
@@ -43,11 +43,10 @@ MODEL_ID = "fake-model"
@dataclass
class CText:
- """Assistant text; optional reasoning in any of the dialect's three fields."""
+ """Assistant text; optional reasoning as ``reasoning_content`` or ``reasoning_details``."""
text: str
reasoning_content: str | None = None
- reasoning: str | None = None
reasoning_details: list[dict[str, Any]] | None = None
prompt_tokens: int = 100
completion_tokens: int = 20
@@ -74,10 +73,9 @@ class CError:
@dataclass
class CStreamError:
- """HTTP 200, stream opens, optional partial text, then an in-stream ``error`` object."""
+ """HTTP 200, stream opens, then an in-stream ``error`` object."""
error: dict[str, Any] = field(default_factory=lambda: {"code": 403, "message": "scripted in-stream error"})
- partial_text: str = ""
@dataclass
@@ -163,10 +161,6 @@ class FakeChatVariantServer:
def proxy_url(self) -> str:
return f"http://127.0.0.1:{self.port}"
- def push(self, *steps: Step) -> None:
- with self._lock:
- self._script.extend(steps)
-
def _next(self, record: dict[str, Any]) -> Step:
if self._responder is not None:
return self._responder(record)
@@ -278,8 +272,6 @@ def _handler_for(server: FakeChatVariantServer) -> type[BaseHTTPRequestHandler]:
self._start_sse()
self._sse(_chunk({"role": "assistant", "content": ""}))
if isinstance(step, CStreamError):
- if step.partial_text:
- self._sse(_chunk({"content": step.partial_text}))
self.wfile.write(f"data: {json.dumps({'error': step.error})}\n\n".encode())
self.wfile.flush()
self.close_connection = True
@@ -312,8 +304,6 @@ def _handler_for(server: FakeChatVariantServer) -> type[BaseHTTPRequestHandler]:
def _stream_reasoning(self, step: CText | CTools) -> None:
if step.reasoning_content:
self._sse(_chunk({"reasoning_content": step.reasoning_content}))
- if isinstance(step, CText) and step.reasoning:
- self._sse(_chunk({"reasoning": step.reasoning}))
if step.reasoning_details:
self._sse(_chunk({"reasoning_details": step.reasoning_details}))
diff --git a/tests/fakes/providers/openai_responses.py b/tests/fakes/providers/openai_responses.py
index 9f160225cad..42542c2b0d2 100644
--- a/tests/fakes/providers/openai_responses.py
+++ b/tests/fakes/providers/openai_responses.py
@@ -20,28 +20,16 @@ api.openai.com ``/v1/responses``, Responses-speaking relays). One real HTTP serv
Main-turn requests (those carrying ``tools``) consume the script in order; tool-less
requests (title generation and other auxiliary calls, on ``/responses`` or
``/chat/completions``) get a canned answer and never eat a scripted turn.
-
-Record mode (manual, never run by the suite — no paid call is ever made by tests)::
-
- python -m tests.fakes.providers.openai_responses record \\
- --upstream https://api.openai.com/v1 --out tests/fakes/providers/cassettes/openai/<name>.json
-
-starts a pass-through proxy on 127.0.0.1; point a Hermes home's ``base_url`` at it,
-run one turn, and the proxy writes a *sanitized* cassette (auth headers dropped,
-``encrypted_content`` and ids replaced with stable placeholders, bodies kept). A
-cassette's recorded event list can be replayed with ``Cassette(path)`` in a script.
"""
from __future__ import annotations
import json
-import re
import threading
import time
import uuid
from dataclasses import dataclass, field
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
-from pathlib import Path
from typing import Any, Callable, Union
from openai.types.responses import (
@@ -127,14 +115,7 @@ class HttpError:
retry_after: float | None = None
-@dataclass
-class Cassette:
- """Replay the event list of a sanitized cassette written by record mode."""
-
- path: Path
-
-
-Step = Union[Turn, SoftFail, HttpError, Cassette]
+Step = Union[Turn, SoftFail, HttpError]
Responder = Callable[[dict[str, Any]], Step]
_REQUEST_ADAPTER = TypeAdapter(ResponseCreateParamsStreaming)
@@ -335,10 +316,6 @@ class FakeResponsesServer:
assert self._server is not None, "server not started"
return f"http://127.0.0.1:{self._server.server_address[1]}/v1"
- def push(self, *steps: Step) -> None:
- with self._lock:
- self._script.extend(steps)
-
def next_step(self, record: dict[str, Any]) -> Step:
if self._responder is not None:
return self._responder(record)
@@ -417,8 +394,6 @@ def _handler_for(server: FakeResponsesServer) -> type[BaseHTTPRequestHandler]:
return
if isinstance(step, SoftFail):
events, limit = soft_fail_events(step), None
- elif isinstance(step, Cassette):
- events, limit = json.loads(Path(step.path).read_text(encoding="utf-8"))["events"], None
else:
events, limit = turn_events(step), step.drop_after_events
self.send_response(200)
@@ -454,67 +429,3 @@ def _handler_for(server: FakeResponsesServer) -> type[BaseHTTPRequestHandler]:
self.close_connection = True
return Handler
-
-
-# Record mode (manual) ------------------------------------------------------------
-
-_SECRETISH = re.compile(r"(sk-[A-Za-z0-9_-]{8,}|eyJ[A-Za-z0-9_.-]{20,})")
-
-
-def sanitize_event(event: dict[str, Any], counter: list[int]) -> dict[str, Any]:
- """Replace opaque/secret-bearing values with stable placeholders (recursive)."""
- def walk(v: Any, key: str = "") -> Any:
- if isinstance(v, dict):
- return {k: walk(x, k) for k, x in v.items()}
- if isinstance(v, list):
- return [walk(x) for x in v]
- if isinstance(v, str):
- if key == "encrypted_content":
- counter[0] += 1
- return f"ENC-PLACEHOLDER-{counter[0]}"
- return _SECRETISH.sub("REDACTED", v)
- return v
- return walk(event)
-
-
-def record_proxy(upstream: str, out: Path, port: int = 0) -> None: # pragma: no cover - manual tool
- """Pass-through proxy that writes one sanitized cassette per ``/responses`` call."""
- import httpx
-
- def handler_cls() -> type[BaseHTTPRequestHandler]:
- class H(BaseHTTPRequestHandler):
- def do_POST(self) -> None: # noqa: N802
- raw = self.rfile.read(int(self.headers.get("Content-Length", 0) or 0))
- headers = {k: v for k, v in self.headers.items() if k.lower() in {"authorization", "content-type"}}
- url = upstream.rstrip("/") + self.path.removeprefix("/v1")
- events: list[dict[str, Any]] = []
- self.send_response(200)
- self.send_header("Content-Type", "text/event-stream")
- self.end_headers()
- with httpx.stream("POST", url, content=raw, headers=headers, timeout=300) as resp:
- for line in resp.iter_lines():
- if line.startswith("data: ") and line != "data: [DONE]":
- events.append(json.loads(line[6:]))
- self.wfile.write((line + "\n").encode())
- self.wfile.flush()
- counter = [0]
- out.write_text(json.dumps({
- "request": sanitize_event(json.loads(raw or b"{}"), counter),
- "events": [sanitize_event(e, counter) for e in events]}, indent=1), encoding="utf-8")
- return H
-
- srv = ThreadingHTTPServer(("127.0.0.1", port), handler_cls())
- print(f"recording proxy on http://127.0.0.1:{srv.server_address[1]}/v1 -> {upstream}", flush=True)
- srv.serve_forever()
-
-
-if __name__ == "__main__": # pragma: no cover - manual entry point
- import argparse
-
- ap = argparse.ArgumentParser()
- ap.add_argument("mode", choices=["record"])
- ap.add_argument("--upstream", required=True)
- ap.add_argument("--out", required=True, type=Path)
- ap.add_argument("--port", type=int, default=0)
- ns = ap.parse_args()
- record_proxy(ns.upstream, ns.out, ns.port)