"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(codex): classify stream HTTP failures
tyj147454413-cmdc7bff740b83b
diff --git a/agent/src/providers/openai_codex.py b/agent/src/providers/openai_codex.pyindex 67ceb8c71..2839b254b 100644--- a/agent/src/providers/openai_codex.py+++ b/agent/src/providers/openai_codex.py@@ -27,6 +27,24 @@ DEFAULT_CODEX_URL = "https://chatgpt.com/backend-api/codex/responses"DEFAULT_ORIGINATOR = "vibe-trading"+class CodexStreamError(RuntimeError):+ """Raised when the OpenAI Codex stream responds with an HTTP error.++ Subclasses ``RuntimeError`` to preserve the historical contract (callers+ historically caught ``RuntimeError`` here) but carries an explicit+ ``status_code`` so the upstream ``ProviderStreamError`` classification+ can distinguish transient (5xx/408/429) failures from deterministic+ 4xx that should not be retried. Without this, every Codex failure+ looked ``status_code=None`` → ``retryable=True`` and codex 400/401/403+ responses wasted a retry budget.+ """++ def __init__(self, status_code: int, detail: Any) -> None:+ self.status_code = int(status_code)+ message = f"OpenAI Codex HTTP {self.status_code}: {str(detail)[:500]}"+ super().__init__(message)++@dataclassclass CodexToolCall:"""Internal tool-call representation compatible with ChatLLM parsing."""@@ -402,7 +420,10 @@ class OpenAICodexLLM:with client.stream("POST", self.codex_url, headers=self._headers(), json=self._body(messages, stream=True)) as response:if response.status_code != 200:raw = response.read().decode("utf-8", "ignore")- raise RuntimeError(f"OpenAI Codex HTTP {response.status_code}: {raw[:500]}")+ # Raise the typed CodexStreamError (carries ``status_code``)+ # so ``ProviderStreamError.retryable`` can correctly classify+ # deterministic 4xx as non-retryable.+ raise CodexStreamError(response.status_code, raw)yield from _message_chunks_from_events(_events_from_lines(response.iter_lines()))def invoke(self, messages: list[dict[str, Any]], config: Optional[dict[str, Any]] = None) -> CodexAIMessage:diff --git a/agent/tests/test_openai_codex.py b/agent/tests/test_openai_codex.pyindex 751d2c179..94a44eb10 100644--- a/agent/tests/test_openai_codex.py+++ b/agent/tests/test_openai_codex.py@@ -8,8 +8,10 @@ from pathlib import Pathimport pytestfrom src.providers import llm as llm_mod+from src.providers.chat import ProviderStreamErrorfrom src.providers.openai_codex import (DEFAULT_CODEX_URL,+ CodexStreamError,OpenAICodexLLM,_events_from_lines,_message_chunks_from_events,@@ -147,3 +149,83 @@ def test_stream_non_200_response_raises_http_error(monkeypatch: pytest.MonkeyPatwith pytest.raises(RuntimeError, match="OpenAI Codex HTTP 401"):list(adapter.stream([{"role": "user", "content": "hello"}]))+++def test_stream_non_200_response_raises_typed_codex_stream_error(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Issue #7: a Codex 4xx raises ``CodexStreamError`` with ``status_code`` set.++ Regression: a plain ``RuntimeError`` carried no ``status_code`` attribute,+ so ``ProviderStreamError.status_code`` was ``None`` (retryable=True) for+ every codex error — including deterministic 400/401/403. The fix is a+ ``CodexStreamError(RuntimeError)`` subclass that exposes the upstream+ status so retry classification works correctly.+ """+ class _FakeResponse:+ status_code = 401++ def __enter__(self) -> "_FakeResponse":+ return self++ def __exit__(self, *args: object) -> None:+ return None++ def read(self) -> bytes:+ return b"unauthorized"++ class _FakeClient:+ def __init__(self, **kwargs: object) -> None:+ pass++ def __enter__(self) -> "_FakeClient":+ return self++ def __exit__(self, *args: object) -> None:+ return None++ def stream(self, *args: object, **kwargs: object) -> _FakeResponse:+ return _FakeResponse()++ import src.providers.openai_codex as codex_mod++ monkeypatch.setattr(codex_mod.httpx, "Client", _FakeClient)+ adapter = OpenAICodexLLM(model=DEFAULT_CODEX_MODEL)+ adapter._headers = lambda: {}++ with pytest.raises(CodexStreamError) as excinfo:+ list(adapter.stream([{"role": "user", "content": "hello"}]))++ # CodexStreamError carries the status_code so ProviderStreamError+ # classifies 401 as non-retryable downstream.+ assert excinfo.value.status_code == 401++ err = ProviderStreamError(+ provider="openai-codex",+ model=DEFAULT_CODEX_MODEL,+ original=excinfo.value,+ )+ assert err.status_code == 401+ assert err.retryable is False+++def test_codex_400_is_non_retryable_via_codex_stream_error() -> None:+ """Deterministic codex 400 is non-retryable through CodexStreamError."""+ err = ProviderStreamError(+ provider="openai-codex",+ model=DEFAULT_CODEX_MODEL,+ original=CodexStreamError(400, "bad request body"),+ )+ assert err.status_code == 400+ assert err.retryable is False+++def test_codex_500_is_retryable_via_codex_stream_error() -> None:+ """Transient codex 500 stays retryable."""+ err = ProviderStreamError(+ provider="openai-codex",+ model=DEFAULT_CODEX_MODEL,+ original=CodexStreamError(500, "boom"),+ )+ assert err.status_code == 500+ assert err.retryable is True