test: replace false-green checks with behavioral coverage (#6282)
* test: replace false-green checks with behavioral coverage * test: complete behavior-focused audit coverage
This commit is contained in:
1 parent
c7ab7aa6da
commit
74942bd190
91 files changed
+1891
-1391
No files matched your search
@@ -1,11 +1,14 @@
|
||||
"""Test Azure OpenAI provider (Responses API via OpenAI SDK)."""
|
||||
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
from unittest.mock import AsyncMock, MagicMock, call, patch
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from openai import AsyncOpenAI
|
||||
|
||||
from nanobot.providers.azure_openai_provider import (
|
||||
AzureOpenAIProvider,
|
||||
@@ -79,79 +82,100 @@ def _install_fake_azure_identity(monkeypatch, credential_factory):
|
||||
monkeypatch.setitem(sys.modules, "azure.identity.aio", aio_mod)
|
||||
|
||||
|
||||
def test_init_missing_key_uses_aad_token_provider(monkeypatch):
|
||||
"""Empty api_key falls back to DefaultAzureCredential via _AzureTokenProvider."""
|
||||
credential_instance = MagicMock()
|
||||
credential_factory = MagicMock(return_value=credential_instance)
|
||||
_install_fake_azure_identity(monkeypatch, credential_factory)
|
||||
@pytest.fixture
|
||||
async def azure_wire_requests(monkeypatch):
|
||||
"""Inject only the HTTP transport; keep the SDK's request/auth path real."""
|
||||
requests: list[httpx.Request] = []
|
||||
|
||||
provider = AzureOpenAIProvider(
|
||||
api_key="", api_base="https://res.openai.azure.com",
|
||||
)
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
requests.append(request)
|
||||
body = json.loads(request.content)
|
||||
return httpx.Response(200, json={
|
||||
"id": f"resp_{len(requests)}", "object": "response", "created_at": 1,
|
||||
"status": "completed", "model": body["model"],
|
||||
"output": [{
|
||||
"type": "message", "id": f"msg_{len(requests)}",
|
||||
"role": "assistant", "status": "completed",
|
||||
"content": [{
|
||||
"type": "output_text", "text": f"reply {len(requests)}", "annotations": [],
|
||||
}],
|
||||
}],
|
||||
"usage": {"input_tokens": 10, "output_tokens": 5, "total_tokens": 15},
|
||||
})
|
||||
|
||||
assert provider._token_provider is not None
|
||||
assert isinstance(provider._token_provider, _AzureTokenProvider)
|
||||
# DefaultAzureCredential must have been instantiated exactly once
|
||||
credential_factory.assert_called_once_with()
|
||||
assert provider._token_provider._credential is credential_instance
|
||||
# The token provider must be wired into the OpenAI SDK as its
|
||||
# ``_api_key_provider`` callable — that's what the SDK invokes per
|
||||
# request to refresh the bearer token.
|
||||
assert provider._client._api_key_provider is provider._token_provider
|
||||
# Static api_key starts empty until the first refresh.
|
||||
assert provider._client.api_key == ""
|
||||
async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as http_client:
|
||||
def create_client(**kwargs):
|
||||
return AsyncOpenAI(http_client=http_client, **kwargs)
|
||||
|
||||
monkeypatch.setattr("nanobot.providers.azure_openai_provider.AsyncOpenAI", create_client)
|
||||
yield requests
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_aad_token_provider_wires_into_sdk_auth_headers(monkeypatch):
|
||||
"""Regression guard: the token provider must be wired into the
|
||||
OpenAI SDK so ``_refresh_api_key`` pulls a fresh token and the
|
||||
bearer ends up in ``auth_headers``. Without this, a refactor that
|
||||
constructs ``_AzureTokenProvider`` but forgets to pass it to
|
||||
``AsyncOpenAI`` would silently send unauthenticated requests.
|
||||
"""
|
||||
access_token = SimpleNamespace(token="token-A", expires_on=time.time() + 3600)
|
||||
async def test_aad_token_provider_sends_rotating_bearer_tokens_on_chat_requests(
|
||||
monkeypatch, azure_wire_requests,
|
||||
):
|
||||
credential_instance = MagicMock()
|
||||
credential_instance.get_token = AsyncMock(return_value=access_token)
|
||||
credential_instance.get_token = AsyncMock(side_effect=[
|
||||
SimpleNamespace(token="token-A", expires_on=time.time() + 3600),
|
||||
SimpleNamespace(token="token-B", expires_on=time.time() + 3600),
|
||||
])
|
||||
credential_instance.close = AsyncMock()
|
||||
credential_factory = MagicMock(return_value=credential_instance)
|
||||
_install_fake_azure_identity(monkeypatch, credential_factory)
|
||||
|
||||
provider = AzureOpenAIProvider(
|
||||
api_key="", api_base="https://res.openai.azure.com",
|
||||
api_key="", api_base="https://res.openai.azure.com", default_model="gpt-4o-deployment",
|
||||
)
|
||||
try:
|
||||
responses = [
|
||||
await provider.chat([{"role": "user", "content": f"turn {turn}"}])
|
||||
for turn in (1, 2)
|
||||
]
|
||||
finally:
|
||||
await provider.aclose()
|
||||
|
||||
assert provider._client.api_key == ""
|
||||
assert provider._client.auth_headers == {}
|
||||
|
||||
await provider._client._refresh_api_key()
|
||||
|
||||
assert provider._client.api_key == "token-A"
|
||||
assert provider._client.auth_headers == {"Authorization": "Bearer token-A"}
|
||||
credential_instance.get_token.assert_awaited_with(
|
||||
"https://cognitiveservices.azure.com/.default"
|
||||
assert [response.content for response in responses] == ["reply 1", "reply 2"]
|
||||
assert all(response.finish_reason == "stop" for response in responses)
|
||||
assert len(azure_wire_requests) == 2
|
||||
assert [request.headers.get("Authorization") for request in azure_wire_requests] == [
|
||||
"Bearer token-A", "Bearer token-B",
|
||||
]
|
||||
assert all(request.method == "POST" for request in azure_wire_requests)
|
||||
assert all(
|
||||
str(request.url) == "https://res.openai.azure.com/openai/v1/responses"
|
||||
for request in azure_wire_requests
|
||||
)
|
||||
|
||||
# Rotated token on second refresh proves per-request delegation (no client-side caching).
|
||||
credential_instance.get_token = AsyncMock(
|
||||
return_value=SimpleNamespace(token="token-B", expires_on=time.time() + 3600)
|
||||
)
|
||||
await provider._client._refresh_api_key()
|
||||
assert provider._client.auth_headers == {"Authorization": "Bearer token-B"}
|
||||
bodies = [json.loads(request.content) for request in azure_wire_requests]
|
||||
assert [body["model"] for body in bodies] == ["gpt-4o-deployment", "gpt-4o-deployment"]
|
||||
assert [body["input"][0]["content"][0]["text"] for body in bodies] == ["turn 1", "turn 2"]
|
||||
credential_factory.assert_called_once_with()
|
||||
assert credential_instance.get_token.await_args_list == [
|
||||
call("https://cognitiveservices.azure.com/.default"),
|
||||
call("https://cognitiveservices.azure.com/.default"),
|
||||
]
|
||||
|
||||
|
||||
def test_init_explicit_key_does_not_construct_credential(monkeypatch):
|
||||
"""Explicit api_key wins; DefaultAzureCredential must never be touched."""
|
||||
@pytest.mark.asyncio
|
||||
async def test_explicit_key_sends_bearer_without_constructing_credential(
|
||||
monkeypatch, azure_wire_requests,
|
||||
):
|
||||
"""Explicit api_key wins through chat(), without invoking Azure credentials."""
|
||||
credential_factory = MagicMock(side_effect=AssertionError(
|
||||
"DefaultAzureCredential must not be constructed when api_key is set"
|
||||
))
|
||||
_install_fake_azure_identity(monkeypatch, credential_factory)
|
||||
|
||||
provider = AzureOpenAIProvider(
|
||||
api_key="real-key", api_base="https://res.openai.azure.com",
|
||||
)
|
||||
try:
|
||||
response = await provider.chat([{"role": "user", "content": "hello"}])
|
||||
finally:
|
||||
await provider.aclose()
|
||||
|
||||
assert provider._token_provider is None
|
||||
assert response.content == "reply 1"
|
||||
assert response.finish_reason == "stop"
|
||||
assert len(azure_wire_requests) == 1
|
||||
assert azure_wire_requests[0].headers["Authorization"] == "Bearer real-key"
|
||||
credential_factory.assert_not_called()
|
||||
|
||||
|
||||
|
||||
@@ -168,22 +168,6 @@ class TestBuildKwargsExtraBody:
|
||||
assert body.get("custom_param") == "value"
|
||||
assert body["thinking"] == {"type": "enabled"}
|
||||
|
||||
def test_nested_extra_body_does_not_clobber_siblings(self) -> None:
|
||||
"""Nested dict merge should preserve sibling keys."""
|
||||
provider = _make_provider({
|
||||
"chat_template_kwargs": {"enable_thinking": False},
|
||||
})
|
||||
# Simulate internal code having set a sibling key
|
||||
# by manually calling _build_kwargs — the internal logic
|
||||
# doesn't set chat_template_kwargs, so we test the merge path
|
||||
# by having extra_body itself contain nested keys
|
||||
kwargs = provider._build_kwargs(
|
||||
messages=_simple_messages(),
|
||||
tools=None, model=None, max_tokens=100,
|
||||
temperature=0.1, reasoning_effort=None, tool_choice=None,
|
||||
)
|
||||
assert kwargs["extra_body"]["chat_template_kwargs"]["enable_thinking"] is False
|
||||
|
||||
def test_guided_json_injection(self) -> None:
|
||||
"""Real-world use case: vLLM guided decoding."""
|
||||
schema = {"type": "object", "properties": {"name": {"type": "string"}}}
|
||||
|
||||
@@ -12,11 +12,13 @@ from nanobot.providers import github_copilot_provider as gc
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_concurrent_token_refresh_fetches_once(monkeypatch):
|
||||
"""Two concurrent _get_copilot_access_token calls should trigger only one
|
||||
HTTP fetch when the token is expired, not two."""
|
||||
"""A competing caller waits for the in-flight exchange and reuses its token."""
|
||||
monkeypatch.setattr(gc, "_load_github_token", lambda: SimpleNamespace(access="github-token"))
|
||||
|
||||
fetch_count = 0
|
||||
entered = asyncio.Event()
|
||||
release = asyncio.Event()
|
||||
competing_started = asyncio.Event()
|
||||
|
||||
class FakeResponse:
|
||||
def raise_for_status(self):
|
||||
@@ -38,82 +40,37 @@ async def test_concurrent_token_refresh_fetches_once(monkeypatch):
|
||||
async def get(self, url, *, headers):
|
||||
nonlocal fetch_count
|
||||
fetch_count += 1
|
||||
# Simulate network latency so both coroutines overlap before the
|
||||
# lock serializes them.
|
||||
await asyncio.sleep(0.05)
|
||||
entered.set()
|
||||
await release.wait()
|
||||
return FakeResponse()
|
||||
|
||||
monkeypatch.setattr(gc.httpx, "AsyncClient", FakeAsyncClient)
|
||||
|
||||
provider = gc.GitHubCopilotProvider()
|
||||
# Force token expiry.
|
||||
provider._copilot_access_token = None
|
||||
provider._copilot_expires_at = 0.0
|
||||
|
||||
token_a, token_b = await asyncio.gather(
|
||||
provider._get_copilot_access_token(),
|
||||
provider._get_copilot_access_token(),
|
||||
)
|
||||
async def competing_call():
|
||||
# No suspension between this signal and entering the token path.
|
||||
competing_started.set()
|
||||
return await provider._get_copilot_access_token()
|
||||
|
||||
assert token_a == "copilot-token"
|
||||
assert token_b == "copilot-token"
|
||||
assert fetch_count == 1, (
|
||||
f"Expected exactly 1 token fetch under concurrency, got {fetch_count}"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_second_call_returns_cached_token_while_first_in_flight(monkeypatch):
|
||||
"""If task A is mid-fetch inside the lock, task B should wait, then find
|
||||
the cached token and skip the HTTP call entirely."""
|
||||
monkeypatch.setattr(gc, "_load_github_token", lambda: SimpleNamespace(access="github-token"))
|
||||
|
||||
fetch_count = 0
|
||||
|
||||
class FakeResponse:
|
||||
def raise_for_status(self):
|
||||
pass
|
||||
|
||||
def json(self):
|
||||
return {"token": "cached-token", "refresh_in": 1500}
|
||||
|
||||
class FakeAsyncClient:
|
||||
def __init__(self, *args, **kwargs):
|
||||
pass
|
||||
|
||||
async def __aenter__(self):
|
||||
return self
|
||||
|
||||
async def __aexit__(self, *args):
|
||||
return False
|
||||
|
||||
async def get(self, url, *, headers):
|
||||
nonlocal fetch_count
|
||||
fetch_count += 1
|
||||
await asyncio.sleep(0.1)
|
||||
return FakeResponse()
|
||||
|
||||
monkeypatch.setattr(gc.httpx, "AsyncClient", FakeAsyncClient)
|
||||
|
||||
provider = gc.GitHubCopilotProvider()
|
||||
provider._copilot_access_token = None
|
||||
provider._copilot_expires_at = 0.0
|
||||
|
||||
# Start task A, let it acquire the lock and begin the HTTP fetch.
|
||||
task_a = asyncio.create_task(provider._get_copilot_access_token())
|
||||
await asyncio.sleep(0.02) # task A is now inside the lock, mid-fetch
|
||||
tasks = [task_a]
|
||||
try:
|
||||
await asyncio.wait_for(entered.wait(), timeout=5)
|
||||
task_b = asyncio.create_task(competing_call())
|
||||
tasks.append(task_b)
|
||||
await asyncio.wait_for(competing_started.wait(), timeout=5)
|
||||
assert not task_a.done()
|
||||
assert not task_b.done()
|
||||
assert fetch_count == 1
|
||||
|
||||
# Task B starts while A is still in flight.
|
||||
token_b = await provider._get_copilot_access_token()
|
||||
token_a = await task_a
|
||||
|
||||
assert token_a == "cached-token"
|
||||
assert token_b == "cached-token"
|
||||
assert fetch_count == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_copilot_token_lock_exists():
|
||||
"""Provider should have an asyncio.Lock for token refresh."""
|
||||
provider = gc.GitHubCopilotProvider()
|
||||
assert isinstance(provider._copilot_token_lock, asyncio.Lock)
|
||||
release.set()
|
||||
tokens = await asyncio.wait_for(asyncio.gather(*tasks), timeout=5)
|
||||
assert tokens == ["copilot-token", "copilot-token"]
|
||||
assert fetch_count == 1
|
||||
finally:
|
||||
release.set()
|
||||
for task in tasks:
|
||||
if not task.done():
|
||||
task.cancel()
|
||||
await asyncio.gather(*tasks, return_exceptions=True)
|
||||
await provider.aclose()
|
||||
@@ -1,8 +1,12 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import sqlite3
|
||||
import threading
|
||||
from collections.abc import Callable, Iterator
|
||||
from contextlib import closing
|
||||
from dataclasses import asdict
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
@@ -127,18 +131,30 @@ async def test_observer_receives_every_retry_attempt(stream: bool) -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_observer_estimates_missing_success_usage_without_storing_content() -> None:
|
||||
provider = _SequenceProvider(iter([LLMResponse(content="hello")]))
|
||||
prompt = "observer-prompt-canary-38a7cf"
|
||||
reply = "observer-response-canary-92b6de"
|
||||
provider = _SequenceProvider(iter([LLMResponse(content=reply)]))
|
||||
events: list[LLMCallRecord] = []
|
||||
provider.set_llm_call_observer(events.append)
|
||||
|
||||
response = await provider.chat_with_retry(
|
||||
messages=[{"role": "user", "content": "hello"}],
|
||||
messages=[{"role": "user", "content": prompt}],
|
||||
)
|
||||
|
||||
assert response.content == reply
|
||||
assert response.finish_reason == "stop"
|
||||
assert provider.calls == 1
|
||||
assert len(events) == 1
|
||||
assert events[0].finish_reason == "stop"
|
||||
assert response.usage is not None
|
||||
assert response.usage.source == "estimated"
|
||||
assert response.usage.input_tokens > 0
|
||||
assert response.usage.output_tokens > 0
|
||||
assert response.usage.estimated_tokens == response.usage.total_tokens > 0
|
||||
assert events[0].usage == response.usage
|
||||
assert "content" not in LLMCallRecord.__dataclass_fields__
|
||||
serialized = json.dumps(asdict(events[0]))
|
||||
assert prompt not in serialized
|
||||
assert reply not in serialized
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -342,26 +358,40 @@ async def test_usage_fast_paths_skip_local_estimation(stream: bool, kind: str) -
|
||||
async def test_gateway_usage_observer_records_missing_usage_and_retry(
|
||||
monkeypatch, tmp_path, stream: bool,
|
||||
) -> None:
|
||||
prompt = "gateway-prompt-canary-f6d5a4"
|
||||
reply = "gateway-response-canary-27be91"
|
||||
error = "gateway-error-canary-64a8cd"
|
||||
store = LLMUsageStore(tmp_path / "usage.sqlite3")
|
||||
monkeypatch.setattr("nanobot.llm_usage.service.get_llm_usage_store", lambda: store)
|
||||
provider = _SequenceProvider(iter([
|
||||
LLMResponse(content="temporary failure", finish_reason="error", error_kind="timeout"),
|
||||
LLMResponse(content="hello"),
|
||||
LLMResponse(content=error, finish_reason="error", error_kind="timeout"),
|
||||
LLMResponse(content=reply),
|
||||
]))
|
||||
provider.set_llm_call_observer(record_llm_call)
|
||||
call = provider.chat_stream_with_retry if stream else provider.chat_with_retry
|
||||
try:
|
||||
with llm_usage_source("api"):
|
||||
response = await call(messages=[{"role": "user", "content": "hello"}])
|
||||
assert response.content == "hello"
|
||||
response = await call(messages=[{"role": "user", "content": prompt}])
|
||||
assert response.content == reply
|
||||
assert response.usage is not None and response.usage.source == "estimated"
|
||||
assert response.usage.input_tokens > 0
|
||||
assert response.usage.output_tokens > 0
|
||||
assert response.usage.estimated_tokens == response.usage.total_tokens > 0
|
||||
assert provider.calls == 2
|
||||
records = list(reversed(store.recent_calls()))
|
||||
with closing(sqlite3.connect(store.path)) as connection:
|
||||
connection.row_factory = sqlite3.Row
|
||||
records = [dict(row) for row in connection.execute("SELECT * FROM llm_calls ORDER BY id")]
|
||||
assert len(records) == 2
|
||||
assert [record["finish_reason"] for record in records] == ["error", "stop"]
|
||||
assert records[0]["error_kind"] == "timeout"
|
||||
assert all(record["source"] == "api" for record in records)
|
||||
assert all(record["stream"] == int(stream) for record in records)
|
||||
assert records[0]["total_tokens"] is None
|
||||
assert records[1]["total_tokens"] == response.usage.total_tokens
|
||||
assert records[1]["estimated_tokens"] == response.usage.estimated_tokens
|
||||
serialized = json.dumps(records)
|
||||
for canary in (prompt, reply, error):
|
||||
assert canary not in serialized
|
||||
finally:
|
||||
store.close()
|
||||
|
||||
|
||||
@@ -88,33 +88,19 @@ async def test_codex_provider_reuses_tls_context_for_concurrent_requests(monkeyp
|
||||
assert request_contexts == [context, context, context]
|
||||
|
||||
|
||||
class _WarningCaptureLogger:
|
||||
def __init__(self) -> None:
|
||||
self.calls: list[tuple[str, tuple[Any, ...]]] = []
|
||||
|
||||
def warning(self, *args: Any, **kwargs: Any) -> None:
|
||||
self.calls.append((args[0], args[1:]))
|
||||
|
||||
def exception(self, message: str, *args: Any, **kwargs: Any) -> None:
|
||||
raise AssertionError("Codex diagnostics must not log exception tracebacks")
|
||||
|
||||
|
||||
def _capture_codex_warnings(monkeypatch: pytest.MonkeyPatch) -> _WarningCaptureLogger:
|
||||
capture = _WarningCaptureLogger()
|
||||
monkeypatch.setattr("nanobot.providers.openai_codex_provider.logger", capture)
|
||||
return capture
|
||||
|
||||
|
||||
def test_codex_blank_timeout_root_cause_reproduction() -> None:
|
||||
"""Document why upstream produced a bare ``Error calling Codex:`` message."""
|
||||
exc = httpx.ReadTimeout("")
|
||||
legacy_content = f"Error calling Codex: {exc}"
|
||||
|
||||
assert str(exc) == ""
|
||||
assert legacy_content == "Error calling Codex: "
|
||||
legacy_response = provider_base.LLMResponse(content=legacy_content, finish_reason="error")
|
||||
assert legacy_response.error_kind is None
|
||||
assert legacy_response.error_should_retry is None
|
||||
@pytest.fixture
|
||||
def codex_warning_log(monkeypatch):
|
||||
monkeypatch.delenv("LANGFUSE_SECRET_KEY", raising=False)
|
||||
sink = io.StringIO()
|
||||
logger.enable("nanobot")
|
||||
handler_id = logger.add(
|
||||
sink, format="{message}", level="WARNING",
|
||||
filter="nanobot.providers.openai_codex_provider", backtrace=True, diagnose=True,
|
||||
)
|
||||
try:
|
||||
yield sink
|
||||
finally:
|
||||
logger.remove(handler_id)
|
||||
|
||||
|
||||
def test_codex_http_friendly_error_omits_raw_body() -> None:
|
||||
@@ -245,10 +231,9 @@ async def test_codex_title_failure_logs_request_purpose_and_safe_upstream_detail
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("failed_stage", ["codex_compaction", "codex_request"])
|
||||
async def test_codex_diagnostics_distinguish_compaction_from_following_request(
|
||||
monkeypatch, failed_stage,
|
||||
monkeypatch, codex_warning_log, failed_stage,
|
||||
) -> None:
|
||||
_mock_codex_token(monkeypatch)
|
||||
capture = _capture_codex_warnings(monkeypatch)
|
||||
state_provider = "openai_codex:https://chatgpt.com/backend-api/codex/responses"
|
||||
state = build_responses_state(
|
||||
provider=state_provider, model="gpt-5.6-sol",
|
||||
@@ -278,14 +263,17 @@ async def test_codex_diagnostics_distinguish_compaction_from_following_request(
|
||||
),
|
||||
)
|
||||
assert response.finish_reason == "error"
|
||||
template, args = capture.calls[-1]
|
||||
log = template.format(*args)
|
||||
logs = codex_warning_log.getvalue().splitlines()
|
||||
assert len(logs) == 1
|
||||
log = logs[0]
|
||||
assert f"stage={failed_stage}" in log
|
||||
assert f"compaction_applied={failed_stage == 'codex_request'}" in log
|
||||
assert "replayed=True" in log
|
||||
assert "reasoning_effort=low" in log
|
||||
assert "error_param=input[1].type" in log
|
||||
assert "request_id=req-compaction-test" in log
|
||||
assert "PRIVATE STATE" not in log
|
||||
assert "Traceback" not in log
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -623,47 +611,38 @@ async def test_codex_provider_passes_proxy_to_oauth_and_response_request(monkeyp
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_codex_timeout_error_writes_diagnostic_log(monkeypatch) -> None:
|
||||
log_capture = _capture_codex_warnings(monkeypatch)
|
||||
async def test_codex_timeout_error_writes_diagnostic_log(monkeypatch, codex_warning_log) -> None:
|
||||
_mock_codex_token(monkeypatch)
|
||||
prompt = "timeout-prompt-canary-38bc7a"
|
||||
|
||||
async def fake_request(*args: Any, **kwargs: Any):
|
||||
async def fake_request(_url, _headers, body, **_kwargs):
|
||||
assert body["input"][0]["content"][0]["text"] == prompt
|
||||
raise httpx.ReadTimeout("")
|
||||
|
||||
monkeypatch.setattr("nanobot.providers.openai_codex_provider._request_codex", fake_request)
|
||||
|
||||
provider = OpenAICodexProvider()
|
||||
response = await provider.chat([{"role": "user", "content": "hello"}])
|
||||
response = await provider.chat(
|
||||
[{"role": "user", "content": prompt}],
|
||||
model="openai-codex/gpt-5.6-sol", reasoning_effort="high",
|
||||
)
|
||||
|
||||
assert response.content == (
|
||||
"Error calling Codex (ReadTimeout): timed out waiting for response"
|
||||
)
|
||||
assert log_capture.calls == [
|
||||
(
|
||||
"Codex API request failed: stage={} type={} kind={} retryable={} status={} "
|
||||
"error_type={} error_code={} retry_after={} summary={} "
|
||||
"model={} reasoning_effort={} replayed={} compaction_applied={} "
|
||||
"error_param={} error_message={} request_id={}",
|
||||
(
|
||||
"codex_request",
|
||||
"ReadTimeout",
|
||||
"timeout",
|
||||
True,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
"ReadTimeout timeout",
|
||||
"gpt-5.6-sol",
|
||||
None,
|
||||
False,
|
||||
False,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
),
|
||||
)
|
||||
]
|
||||
logs = codex_warning_log.getvalue().splitlines()
|
||||
assert len(logs) == 1
|
||||
log = logs[0]
|
||||
for field in (
|
||||
"Codex API request failed", "stage=codex_request", "type=ReadTimeout",
|
||||
"kind=timeout", "retryable=True", "status=None", "error_type=None",
|
||||
"error_code=None", "retry_after=None", "summary=ReadTimeout timeout",
|
||||
"model=gpt-5.6-sol", "reasoning_effort=high", "replayed=False",
|
||||
"compaction_applied=False", "error_param=None", "error_message=None", "request_id=None",
|
||||
):
|
||||
assert field in log
|
||||
assert prompt not in log
|
||||
assert "Traceback" not in log
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -751,50 +730,60 @@ async def test_codex_http_error_preserves_status_and_retry_after(monkeypatch) ->
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_codex_http_diagnostic_log_omits_raw_body(monkeypatch) -> None:
|
||||
log_capture = _capture_codex_warnings(monkeypatch)
|
||||
async def test_codex_http_diagnostic_log_omits_raw_body(monkeypatch, codex_warning_log) -> None:
|
||||
_mock_codex_token(monkeypatch)
|
||||
original_client = httpx.AsyncClient
|
||||
prompt = "http-prompt-canary-471fde"
|
||||
upstream_body = "http-upstream-body-canary-639ca2"
|
||||
requests: list[httpx.Request] = []
|
||||
|
||||
async def fake_request(*args: Any, **kwargs: Any):
|
||||
raise _CodexHTTPError(
|
||||
_friendly_error(500, "raw upstream body with PRIVATE PROMPT MUST NOT APPEAR"),
|
||||
status_code=500,
|
||||
error_type="server_error",
|
||||
error_code="overloaded",
|
||||
)
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
requests.append(request)
|
||||
assert prompt.encode() in request.content
|
||||
return httpx.Response(500, headers={
|
||||
"retry-after": "2.5", "x-request-id": "req-http-diagnostic",
|
||||
}, json={
|
||||
"error": {
|
||||
"type": "server_error", "code": "overloaded",
|
||||
"param": "input[0].content", "message": upstream_body,
|
||||
},
|
||||
"private": upstream_body,
|
||||
})
|
||||
|
||||
monkeypatch.setattr("nanobot.providers.openai_codex_provider._request_codex", fake_request)
|
||||
def fake_client(**kwargs):
|
||||
return original_client(transport=httpx.MockTransport(handler))
|
||||
|
||||
monkeypatch.setattr("nanobot.providers.openai_codex_provider.httpx.AsyncClient", fake_client)
|
||||
provider = OpenAICodexProvider()
|
||||
response = await provider.chat([{"role": "user", "content": "hello"}])
|
||||
|
||||
assert response.content == "Error calling Codex (CodexHTTPError): HTTP 500: Codex API request failed"
|
||||
assert log_capture.calls == [
|
||||
(
|
||||
"Codex API request failed: stage={} type={} kind={} retryable={} status={} "
|
||||
"error_type={} error_code={} retry_after={} summary={} "
|
||||
"model={} reasoning_effort={} replayed={} compaction_applied={} "
|
||||
"error_param={} error_message={} request_id={}",
|
||||
(
|
||||
"codex_request",
|
||||
"CodexHTTPError",
|
||||
"http",
|
||||
True,
|
||||
500,
|
||||
"server_error",
|
||||
"overloaded",
|
||||
None,
|
||||
"HTTP 500 type=server_error code=overloaded",
|
||||
"gpt-5.6-sol",
|
||||
None,
|
||||
False,
|
||||
False,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
),
|
||||
try:
|
||||
response = await provider.chat(
|
||||
[{"role": "user", "content": prompt}],
|
||||
model="openai-codex/gpt-5.6-sol", reasoning_effort="high",
|
||||
)
|
||||
]
|
||||
finally:
|
||||
await provider.aclose()
|
||||
|
||||
assert len(requests) == 1
|
||||
assert response.finish_reason == "error"
|
||||
assert response.content == "Error calling Codex (CodexHTTPError): HTTP 500: Codex API request failed"
|
||||
assert response.error_status_code == 500
|
||||
assert response.error_should_retry is True
|
||||
logs = codex_warning_log.getvalue().splitlines()
|
||||
assert len(logs) == 1
|
||||
log = logs[0]
|
||||
for field in (
|
||||
"Codex API request failed", "stage=codex_request", "type=CodexHTTPError",
|
||||
"kind=http", "retryable=True", "status=500", "error_type=server_error",
|
||||
"error_code=overloaded", "retry_after=2.5",
|
||||
"summary=HTTP 500 type=server_error code=overloaded", "model=gpt-5.6-sol",
|
||||
"reasoning_effort=high", "replayed=False", "compaction_applied=False",
|
||||
"error_param=input[0].content", "error_message=None", "request_id=req-http-diagnostic",
|
||||
):
|
||||
assert field in log
|
||||
for secret in (prompt, upstream_body):
|
||||
assert secret not in log
|
||||
assert secret not in response.content
|
||||
assert "Traceback" not in log
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
|
||||
@@ -62,17 +62,18 @@ class TestSanitizeSurrogatesDeep:
|
||||
"role": "user",
|
||||
"content": [
|
||||
{"type": "text", "text": "hello \ud83e world"},
|
||||
{"type": "text", "text": "normal"},
|
||||
{"type": "text", "text": "normal 🤖"},
|
||||
],
|
||||
}
|
||||
cleaned = sanitize_surrogates_deep(dirty)
|
||||
assert cleaned is not dirty # rebuilt
|
||||
first = cleaned["content"][0]["text"]
|
||||
assert "\ud83e" not in first
|
||||
assert cleaned["content"][1]["text"] == "normal 🤖"
|
||||
# Full payload must be UTF-8 encodable.
|
||||
import json
|
||||
|
||||
json.dumps(cleaned).encode("utf-8")
|
||||
json.dumps(cleaned, ensure_ascii=False).encode("utf-8")
|
||||
|
||||
def test_paired_surrogates_in_list_collapse_to_emoji(self):
|
||||
dirty = ["a", "b \ud83e\udd16", "c"]
|
||||
@@ -150,13 +151,16 @@ class TestProviderSanitizeEmptyContent:
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": [
|
||||
{"type": "text", "text": "answer with a lone \ud83e half"},
|
||||
{"type": "text", "text": "answer with a lone \ud83e half and paired \ud83e\udd16"},
|
||||
],
|
||||
},
|
||||
]
|
||||
cleaned = LLMProvider._sanitize_empty_content(messages)
|
||||
# This is the operation that previously raised UnicodeEncodeError.
|
||||
json.dumps({"model": "x", "messages": cleaned}).encode("utf-8")
|
||||
json.dumps({"model": "x", "messages": cleaned}, ensure_ascii=False).encode("utf-8")
|
||||
assert cleaned[0]["content"] == "You are a 🐱 assistant."
|
||||
assert cleaned[1]["content"] == "🤖 fixed?"
|
||||
assert cleaned[2]["content"][0]["text"] == "answer with a lone \ufffd half and paired 🤖"
|
||||
|
||||
|
||||
class TestBackwardCompatReExport:
|
||||
|
||||
@@ -418,38 +418,6 @@ def test_resolver_keeps_enabled_and_limits_on_effective_config() -> None:
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_openai_retries_on_5xx_then_succeeds(audio_file: Path) -> None:
|
||||
"""Transient 503 is retried; a subsequent 200 yields the text."""
|
||||
provider = OpenAITranscriptionProvider(api_key="sk-test")
|
||||
post = AsyncMock(side_effect=[_response(503), _response(200, {"text": "hello"})])
|
||||
with patch("httpx.AsyncClient.post", post), patch("asyncio.sleep", AsyncMock()):
|
||||
result = await provider.transcribe(audio_file)
|
||||
assert result == "hello"
|
||||
assert post.await_count == 2
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_openai_retries_on_429_then_succeeds(audio_file: Path) -> None:
|
||||
provider = OpenAITranscriptionProvider(api_key="sk-test")
|
||||
post = AsyncMock(side_effect=[_response(429), _response(200, {"text": "rate ok"})])
|
||||
with patch("httpx.AsyncClient.post", post), patch("asyncio.sleep", AsyncMock()):
|
||||
result = await provider.transcribe(audio_file)
|
||||
assert result == "rate ok"
|
||||
assert post.await_count == 2
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_openai_retries_on_connect_error(audio_file: Path) -> None:
|
||||
"""Network-level transient errors are retried."""
|
||||
provider = OpenAITranscriptionProvider(api_key="sk-test")
|
||||
post = AsyncMock(side_effect=[httpx.ConnectError("boom"), _response(200, {"text": "ok"})])
|
||||
with patch("httpx.AsyncClient.post", post), patch("asyncio.sleep", AsyncMock()):
|
||||
result = await provider.transcribe(audio_file)
|
||||
assert result == "ok"
|
||||
assert post.await_count == 2
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_openai_does_not_retry_on_auth_error(audio_file: Path) -> None:
|
||||
"""401 is the user's misconfiguration — retrying wastes time and rate-limit quota."""
|
||||
|
||||
Reference in new issue
Block a user