perf: reduce memory copies across files, sessions, and model requests (#6581)
This commit is contained in:
1 parent
e40d2e5027
commit
1a89a25abd
16 files changed
+3080
-427
No files matched your search
@@ -1,10 +1,18 @@
|
||||
import asyncio
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import textwrap
|
||||
import weakref
|
||||
from collections.abc import AsyncIterator, Awaitable, Callable
|
||||
|
||||
import httpx
|
||||
import openai
|
||||
import pytest
|
||||
from agent.runner_helpers import failed_test_consolidator
|
||||
from loguru import logger
|
||||
from openai import AsyncOpenAI
|
||||
|
||||
from nanobot.agent.hook import AgentHook
|
||||
@@ -259,3 +267,646 @@ async def test_chat_only_provider_still_has_a_timeout(monkeypatch, finalize):
|
||||
assert result.stop_reason == ("max_iterations" if finalize else "error")
|
||||
if finalize:
|
||||
assert result.final_content == "Tool budget exhausted."
|
||||
|
||||
|
||||
def _chat_event(delta=None, *, finish=None, usage=None):
|
||||
event = {
|
||||
"id": "synthetic", "object": "chat.completion.chunk", "created": 0,
|
||||
"model": "synthetic", "choices": [],
|
||||
}
|
||||
if delta is not None:
|
||||
event["choices"] = [{"index": 0, "delta": delta, "finish_reason": finish}]
|
||||
if usage is not None:
|
||||
event["usage"] = usage
|
||||
return event
|
||||
|
||||
|
||||
def _bad_chat_event(kind):
|
||||
if kind == "usage":
|
||||
return _chat_event(usage={"prompt_tokens": "invalid", "completion_tokens": 1, "total_tokens": 2})
|
||||
return _chat_event({"tool_calls": [{
|
||||
"index": [0], "id": "bad", "type": "function",
|
||||
"function": {"name": "bad_tool", "arguments": "{}"},
|
||||
}]})
|
||||
|
||||
|
||||
class _ControlledChatStream(_EventStream):
|
||||
def __init__(self, events, *, disconnect=False, pause_at=None, close_error=None):
|
||||
super().__init__(events)
|
||||
self.disconnect = disconnect
|
||||
self.pause_at = pause_at
|
||||
self.close_error = close_error
|
||||
self.reached_pause = asyncio.Event()
|
||||
self.release = asyncio.Event()
|
||||
self.sent = 0
|
||||
self.close_calls = 0
|
||||
|
||||
async def aclose(self):
|
||||
self.close_calls += 1
|
||||
self.closed = True
|
||||
if self.close_error is not None:
|
||||
raise self.close_error
|
||||
|
||||
async def __aiter__(self):
|
||||
for index, event in enumerate(self.events):
|
||||
if index == self.pause_at:
|
||||
self.reached_pause.set()
|
||||
await self.release.wait()
|
||||
self.sent += 1
|
||||
yield f"data: {json.dumps(event)}\n\n".encode()
|
||||
if self.disconnect:
|
||||
raise ConnectionError("synthetic connection lost")
|
||||
yield b"data: [DONE]\n\n"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def chat_sdk():
|
||||
clients = []
|
||||
|
||||
def make(streams):
|
||||
requests = []
|
||||
|
||||
def handler(request):
|
||||
requests.append(request)
|
||||
assert json.loads(request.content)["stream"] is True
|
||||
return httpx.Response(
|
||||
200, headers={"content-type": "text/event-stream"},
|
||||
stream=streams[len(requests) - 1],
|
||||
)
|
||||
|
||||
client = AsyncOpenAI(
|
||||
api_key="synthetic", base_url="https://synthetic.invalid/v1", max_retries=0,
|
||||
http_client=httpx.AsyncClient(transport=httpx.MockTransport(handler)),
|
||||
)
|
||||
clients.append(client)
|
||||
provider = OpenAICompatProvider(
|
||||
api_key="synthetic", default_model="synthetic",
|
||||
model_api=ModelAPICapabilities(("chat_completions",), "chat_completions"),
|
||||
)
|
||||
provider._client = client
|
||||
provider._CHAT_RETRY_DELAYS = (0,)
|
||||
return provider, requests
|
||||
|
||||
yield make
|
||||
for client in clients:
|
||||
await client.close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("first_bad", ["usage", "index"])
|
||||
async def test_chat_parse_failure_waits_for_all_live_deltas(chat_sdk, first_bad):
|
||||
other_bad = "index" if first_bad == "usage" else "usage"
|
||||
stream = _ControlledChatStream([
|
||||
_bad_chat_event(first_bad), _bad_chat_event(other_bad),
|
||||
_chat_event({
|
||||
"content": "later", "reasoning_content": "thought",
|
||||
"tool_calls": [{"index": 1, "id": "good", "type": "function",
|
||||
"function": {"name": "tool", "arguments": "{}"}}],
|
||||
}),
|
||||
_chat_event({}, finish="stop"),
|
||||
], pause_at=3)
|
||||
provider, _ = chat_sdk([stream])
|
||||
callbacks = []
|
||||
|
||||
async def content(value):
|
||||
callbacks.append(("content", value))
|
||||
|
||||
async def thinking(value):
|
||||
callbacks.append(("thinking", value))
|
||||
|
||||
async def tool(value):
|
||||
callbacks.append(("tool", value))
|
||||
|
||||
task = asyncio.create_task(provider.chat_stream(
|
||||
[{"role": "user", "content": "work"}], on_content_delta=content,
|
||||
on_thinking_delta=thinking, on_tool_call_delta=tool,
|
||||
))
|
||||
try:
|
||||
await asyncio.wait_for(stream.reached_pause.wait(), timeout=1)
|
||||
assert not task.done()
|
||||
assert callbacks == [
|
||||
("tool", {"index": [0], "call_id": "bad", "name": "bad_tool", "arguments_delta": "{}"}),
|
||||
("content", "later"), ("thinking", "thought"),
|
||||
("tool", {"index": 1, "call_id": "good", "name": "tool", "arguments_delta": "{}"}),
|
||||
]
|
||||
stream.release.set()
|
||||
result = await task
|
||||
finally:
|
||||
if not task.done():
|
||||
task.cancel()
|
||||
await asyncio.gather(task, return_exceptions=True)
|
||||
|
||||
assert result.finish_reason == "error"
|
||||
assert ("invalid literal" if first_bad == "usage" else "unhashable type") in result.content
|
||||
assert stream.closed
|
||||
|
||||
|
||||
@pytest.mark.parametrize("bad", ["usage", "index"])
|
||||
@pytest.mark.parametrize("interruption", ["disconnect", "eof", "disconnect-after-finish"])
|
||||
async def test_chat_interruption_precedes_parse_failure_and_retries(chat_sdk, bad, interruption):
|
||||
events = [_bad_chat_event(bad), _chat_event({"reasoning_content": "before retry"})]
|
||||
if interruption == "disconnect-after-finish":
|
||||
events.append(_chat_event({}, finish="stop"))
|
||||
first = _ControlledChatStream(events, disconnect=interruption != "eof")
|
||||
second = _ControlledChatStream([
|
||||
_chat_event({"content": "recovered"}), _chat_event({}, finish="stop"),
|
||||
_chat_event(usage={"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15}),
|
||||
])
|
||||
provider, requests = chat_sdk([first, second])
|
||||
thinking, content = [], []
|
||||
|
||||
async def on_thinking(value):
|
||||
thinking.append(value)
|
||||
|
||||
async def on_content(value):
|
||||
content.append(value)
|
||||
|
||||
result = await provider.chat_stream_with_retry(
|
||||
[{"role": "user", "content": "work"}],
|
||||
on_thinking_delta=on_thinking, on_content_delta=on_content,
|
||||
)
|
||||
assert len(requests) == 2
|
||||
assert thinking == ["before retry"]
|
||||
assert content == ["recovered"]
|
||||
assert result.finish_reason == "stop" and result.content == "recovered"
|
||||
assert result.usage is not None and result.usage.total_tokens == 15
|
||||
assert first.closed and second.closed
|
||||
|
||||
|
||||
async def test_chat_content_after_parse_failure_preserves_retry_guard(chat_sdk):
|
||||
first = _ControlledChatStream([
|
||||
_bad_chat_event("usage"), _chat_event({"content": "already shown"}),
|
||||
], disconnect=True)
|
||||
provider, requests = chat_sdk([first])
|
||||
content = []
|
||||
|
||||
async def on_content(value):
|
||||
content.append(value)
|
||||
|
||||
result = await provider.chat_stream_with_retry(
|
||||
[{"role": "user", "content": "work"}], on_content_delta=on_content,
|
||||
)
|
||||
assert len(requests) == 1 and content == ["already shown"]
|
||||
assert result.error_kind == "connection" and "synthetic connection lost" in result.content
|
||||
assert first.closed
|
||||
|
||||
|
||||
@pytest.mark.parametrize("parse_first", [False, True])
|
||||
async def test_chat_callback_error_closes_stream(chat_sdk, parse_first):
|
||||
prefix = [_bad_chat_event("usage")] if parse_first else []
|
||||
stream = _ControlledChatStream(prefix + [
|
||||
_chat_event({"content": "fail callback"}), _chat_event({}, finish="stop"),
|
||||
])
|
||||
provider, _ = chat_sdk([stream])
|
||||
|
||||
async def on_content(value):
|
||||
raise RuntimeError("callback failed")
|
||||
|
||||
result = await provider.chat_stream(
|
||||
[{"role": "user", "content": "work"}], on_content_delta=on_content,
|
||||
)
|
||||
assert result.finish_reason == "error" and "callback failed" in result.content
|
||||
assert stream.sent == len(prefix) + 1 and stream.closed
|
||||
|
||||
|
||||
@pytest.mark.parametrize("parse_first", [False, True])
|
||||
@pytest.mark.parametrize("blocked", ["read", "callback"])
|
||||
async def test_chat_cancel_closes_stream(chat_sdk, blocked, parse_first):
|
||||
prefix = [_bad_chat_event("usage")] if parse_first else []
|
||||
stream = _ControlledChatStream(prefix + [
|
||||
_chat_event({"content": "wait"}), _chat_event({}, finish="stop"),
|
||||
], pause_at=len(prefix) if blocked == "read" else None)
|
||||
provider, _ = chat_sdk([stream])
|
||||
callback_started = asyncio.Event()
|
||||
|
||||
async def on_content(value):
|
||||
callback_started.set()
|
||||
await asyncio.Event().wait()
|
||||
|
||||
task = asyncio.create_task(provider.chat_stream(
|
||||
[{"role": "user", "content": "work"}], on_content_delta=on_content,
|
||||
))
|
||||
try:
|
||||
started = stream.reached_pause if blocked == "read" else callback_started
|
||||
await asyncio.wait_for(started.wait(), timeout=1)
|
||||
task.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await task
|
||||
assert stream.closed
|
||||
finally:
|
||||
if not task.done():
|
||||
task.cancel()
|
||||
await asyncio.gather(task, return_exceptions=True)
|
||||
|
||||
|
||||
async def test_chat_timeout_after_parse_failure_wins_and_closes(chat_sdk, monkeypatch):
|
||||
monkeypatch.setenv("NANOBOT_STREAM_IDLE_TIMEOUT_S", "0.05")
|
||||
stream = _ControlledChatStream([
|
||||
_bad_chat_event("usage"), _chat_event({}, finish="stop"),
|
||||
], pause_at=1)
|
||||
provider, _ = chat_sdk([stream])
|
||||
result = await provider.chat_stream([{"role": "user", "content": "work"}])
|
||||
assert result.error_kind == "timeout"
|
||||
assert stream.closed
|
||||
|
||||
|
||||
async def test_chat_sdk_error_after_parse_failure_wins_and_closes(chat_sdk):
|
||||
stream = _ControlledChatStream([
|
||||
_bad_chat_event("usage"), {"error": {"message": "provider stream error", "code": "bad_stream"}},
|
||||
_chat_event({}, finish="stop"),
|
||||
])
|
||||
provider, _ = chat_sdk([stream])
|
||||
result = await provider.chat_stream([{"role": "user", "content": "work"}])
|
||||
assert result.finish_reason == "error" and "provider stream error" in result.content
|
||||
assert result.error_code == "bad_stream"
|
||||
assert stream.sent == 2 and stream.closed
|
||||
|
||||
|
||||
@pytest.mark.parametrize("bad", [False, True])
|
||||
async def test_chat_sdk_chunks_are_not_retained_during_stream(chat_sdk, monkeypatch, bad):
|
||||
stream = _ControlledChatStream([
|
||||
_chat_event({"content": "first"}),
|
||||
_bad_chat_event("usage") if bad else _chat_event({"content": "second"}),
|
||||
_chat_event({"content": "third"}), _chat_event({"content": "fourth"}),
|
||||
_chat_event({}, finish="stop", usage={
|
||||
"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15,
|
||||
}),
|
||||
])
|
||||
provider, _ = chat_sdk([stream])
|
||||
references = []
|
||||
released = []
|
||||
deltas = []
|
||||
original_add = OpenAICompatProvider._ChatStreamAccumulator.add
|
||||
|
||||
def track_add(accumulator, chunk):
|
||||
references.append(weakref.ref(chunk))
|
||||
original_add(accumulator, chunk)
|
||||
|
||||
monkeypatch.setattr(OpenAICompatProvider._ChatStreamAccumulator, "add", track_add)
|
||||
|
||||
async def on_content(value):
|
||||
deltas.append(value)
|
||||
if value == "fourth":
|
||||
released.extend(ref() is None for ref in references[:2])
|
||||
|
||||
result = await provider.chat_stream(
|
||||
[{"role": "user", "content": "work"}], on_content_delta=on_content,
|
||||
)
|
||||
assert released == [True, True]
|
||||
assert deltas == (["first", "third", "fourth"] if bad else ["first", "second", "third", "fourth"])
|
||||
assert result.finish_reason == ("error" if bad else "stop")
|
||||
if not bad:
|
||||
assert result.content == "".join(deltas)
|
||||
assert result.usage is not None and result.usage.total_tokens == 15
|
||||
assert stream.closed
|
||||
|
||||
|
||||
async def test_chat_sdk_normal_deltas_usage_and_tool_metadata(chat_sdk):
|
||||
stream = _ControlledChatStream([
|
||||
_chat_event({
|
||||
"content": "hello ", "reasoning_content": "think ",
|
||||
"tool_calls": [{
|
||||
"index": 0, "id": "call_1", "type": "function",
|
||||
"function": {"name": "write_file", "arguments": '{"path":', "vendor_fn": "f"},
|
||||
"extra_content": {"google": {"thought_signature": "signed"}},
|
||||
"vendor_call": "c",
|
||||
}],
|
||||
}),
|
||||
_chat_event({
|
||||
"content": "world", "reasoning": "more",
|
||||
"tool_calls": [{"index": 0, "function": {"arguments": '"a.txt"}'}}],
|
||||
}),
|
||||
_chat_event({"tool_calls": [{
|
||||
"index": 1, "id": "call_1", "type": "function",
|
||||
"function": {"name": "read_file", "arguments": '{"path":"b.txt"}'},
|
||||
}]}),
|
||||
_chat_event({}, finish="tool_calls"),
|
||||
_chat_event(usage={
|
||||
"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 16,
|
||||
"prompt_tokens_details": {"cached_tokens": 3},
|
||||
}),
|
||||
])
|
||||
provider, requests = chat_sdk([stream])
|
||||
callbacks = []
|
||||
|
||||
async def content(value):
|
||||
callbacks.append(("content", value))
|
||||
|
||||
async def thinking(value):
|
||||
callbacks.append(("thinking", value))
|
||||
|
||||
async def tool(value):
|
||||
callbacks.append(("tool", value))
|
||||
|
||||
result = await provider.chat_stream(
|
||||
[{"role": "user", "content": "work"}], on_content_delta=content,
|
||||
on_thinking_delta=thinking, on_tool_call_delta=tool,
|
||||
)
|
||||
assert callbacks == [
|
||||
("content", "hello "), ("thinking", "think "),
|
||||
("tool", {"index": 0, "call_id": "call_1", "name": "write_file", "arguments_delta": '{"path":'}),
|
||||
("content", "world"), ("thinking", "more"),
|
||||
("tool", {"index": 0, "call_id": "", "name": "", "arguments_delta": '"a.txt"}'}),
|
||||
("tool", {"index": 1, "call_id": "call_1", "name": "read_file", "arguments_delta": '{"path":"b.txt"}'}),
|
||||
]
|
||||
assert len(requests) == 1 and stream.closed
|
||||
assert result.finish_reason == "tool_calls"
|
||||
assert result.content == "hello world" and result.reasoning_content == "think more"
|
||||
assert result.usage is not None
|
||||
assert (result.usage.input_tokens, result.usage.output_tokens, result.usage.total_tokens) == (10, 5, 16)
|
||||
assert result.usage.cache_read_tokens == 3
|
||||
first, second = result.tool_calls
|
||||
assert (first.id, first.name, first.arguments) == ("call_1", "write_file", {"path": "a.txt"})
|
||||
assert first.extra_content == {"google": {"thought_signature": "signed"}}
|
||||
assert first.provider_specific_fields == {"vendor_call": "c"}
|
||||
assert first.function_provider_specific_fields == {"vendor_fn": "f"}
|
||||
assert second.id and second.id != first.id
|
||||
assert (second.name, second.arguments) == ("read_file", {"path": "b.txt"})
|
||||
|
||||
|
||||
async def test_chat_sdk_mistral_thinking_and_legacy_function_call(chat_sdk):
|
||||
stream = _ControlledChatStream([
|
||||
_chat_event({
|
||||
"content": [
|
||||
{"type": "thinking", "thinking": [{"type": "text", "text": "ponder"}]},
|
||||
{"type": "text", "text": "hello"},
|
||||
],
|
||||
"function_call": {"name": "old_tool", "arguments": '{"n":'},
|
||||
}),
|
||||
_chat_event({"function_call": {"arguments": "1}"}}, finish="function_call"),
|
||||
_chat_event(usage={"prompt_tokens": 4, "completion_tokens": 2, "total_tokens": 6}),
|
||||
])
|
||||
provider, _ = chat_sdk([stream])
|
||||
callbacks = []
|
||||
|
||||
async def content(value):
|
||||
callbacks.append(("content", value))
|
||||
|
||||
async def thinking(value):
|
||||
callbacks.append(("thinking", value))
|
||||
|
||||
async def tool(value):
|
||||
callbacks.append(("tool", value))
|
||||
|
||||
result = await provider.chat_stream(
|
||||
[{"role": "user", "content": "work"}], on_content_delta=content,
|
||||
on_thinking_delta=thinking, on_tool_call_delta=tool,
|
||||
)
|
||||
assert callbacks == [
|
||||
("content", "hello"), ("thinking", "ponder"),
|
||||
("tool", {"index": 0, "call_id": "", "name": "old_tool", "arguments_delta": '{"n":'}),
|
||||
("tool", {"index": 0, "call_id": "", "name": "", "arguments_delta": "1}"}),
|
||||
]
|
||||
assert result.finish_reason == "function_call" and result.content == "hello"
|
||||
assert result.reasoning_content == "ponder"
|
||||
assert len(result.tool_calls) == 1
|
||||
assert result.tool_calls[0].name == "old_tool" and result.tool_calls[0].arguments == {"n": 1}
|
||||
assert result.usage is not None and result.usage.total_tokens == 6
|
||||
assert stream.closed
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def cleanup_warnings():
|
||||
messages = []
|
||||
sink = logger.add(messages.append, format="{message}", level="WARNING")
|
||||
try:
|
||||
yield messages
|
||||
finally:
|
||||
logger.remove(sink)
|
||||
|
||||
|
||||
def _require_minimum_sdk_for_iterator_close_failure():
|
||||
# SDK 2.24 closes inside its iterator and masks these errors before the
|
||||
# provider's cleanup runs. That pre-existing SDK behavior is outside this fix.
|
||||
if openai.__version__ != "2.8.0":
|
||||
pytest.skip("this regression targets the 2.8.0 SDK's caller-owned close")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("blocked", ["read", "callback"])
|
||||
async def test_chat_cancel_wins_over_close_error_without_retry(chat_sdk, cleanup_warnings, blocked):
|
||||
if blocked == "read":
|
||||
_require_minimum_sdk_for_iterator_close_failure()
|
||||
stream = _ControlledChatStream([
|
||||
_chat_event({"content": "waiting"}), _chat_event({}, finish="stop"),
|
||||
], pause_at=0 if blocked == "read" else None, close_error=httpx.CloseError("connection reset"))
|
||||
retry = _ControlledChatStream([_chat_event({"content": "unexpected"}, finish="stop")])
|
||||
provider, requests = chat_sdk([stream, retry])
|
||||
callback_started = asyncio.Event()
|
||||
|
||||
async def on_content(value):
|
||||
if value == "waiting":
|
||||
callback_started.set()
|
||||
await asyncio.Event().wait()
|
||||
|
||||
task = asyncio.create_task(provider.chat_stream_with_retry(
|
||||
[{"role": "user", "content": "work"}], on_content_delta=on_content,
|
||||
))
|
||||
try:
|
||||
started = stream.reached_pause if blocked == "read" else callback_started
|
||||
await asyncio.wait_for(started.wait(), timeout=5)
|
||||
task.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await task
|
||||
finally:
|
||||
if not task.done():
|
||||
task.cancel()
|
||||
await asyncio.gather(task, return_exceptions=True)
|
||||
|
||||
assert len(requests) == 1 and stream.closed and stream.close_calls == 1
|
||||
assert any("connection reset" in message for message in cleanup_warnings)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("parse_first", [False, True])
|
||||
async def test_chat_provider_error_wins_over_close_error_without_retry(
|
||||
chat_sdk, cleanup_warnings, parse_first,
|
||||
):
|
||||
_require_minimum_sdk_for_iterator_close_failure()
|
||||
prefix = [_bad_chat_event("usage")] if parse_first else []
|
||||
stream = _ControlledChatStream(prefix + [{"error": {
|
||||
"message": "quota exhausted", "type": "insufficient_quota", "code": "insufficient_quota",
|
||||
}}], close_error=httpx.CloseError("connection reset"))
|
||||
retry = _ControlledChatStream([_chat_event({"content": "unexpected"}, finish="stop")])
|
||||
provider, requests = chat_sdk([stream, retry])
|
||||
|
||||
result = await provider.chat_stream_with_retry([{"role": "user", "content": "work"}])
|
||||
|
||||
assert result.finish_reason == "error"
|
||||
assert result.error_type == result.error_code == "insufficient_quota"
|
||||
assert "quota exhausted" in result.content
|
||||
assert len(requests) == 1 and stream.closed and stream.close_calls == 1
|
||||
assert any("connection reset" in message for message in cleanup_warnings)
|
||||
|
||||
|
||||
async def test_chat_disconnect_wins_over_close_error_and_still_retries(chat_sdk, cleanup_warnings):
|
||||
_require_minimum_sdk_for_iterator_close_failure()
|
||||
first = _ControlledChatStream([
|
||||
_bad_chat_event("usage"), _chat_event({"reasoning_content": "thinking"}),
|
||||
], disconnect=True, close_error=httpx.CloseError("connection reset"))
|
||||
second = _ControlledChatStream([_chat_event({"content": "recovered"}, finish="stop")])
|
||||
provider, requests = chat_sdk([first, second])
|
||||
|
||||
result = await provider.chat_stream_with_retry([{"role": "user", "content": "work"}])
|
||||
|
||||
assert result.finish_reason == "stop" and result.content == "recovered"
|
||||
assert len(requests) == 2 and first.closed and second.closed
|
||||
assert any("after ConnectionError: connection reset" in message for message in cleanup_warnings)
|
||||
|
||||
|
||||
async def test_chat_timeout_wins_over_close_error(chat_sdk, cleanup_warnings, monkeypatch):
|
||||
_require_minimum_sdk_for_iterator_close_failure()
|
||||
monkeypatch.setenv("NANOBOT_STREAM_IDLE_TIMEOUT_S", "0.05")
|
||||
stream = _ControlledChatStream([
|
||||
_bad_chat_event("usage"), _chat_event({}, finish="stop"),
|
||||
], pause_at=1, close_error=httpx.CloseError("connection reset"))
|
||||
provider, requests = chat_sdk([stream])
|
||||
|
||||
result = await provider.chat_stream([{"role": "user", "content": "work"}])
|
||||
|
||||
assert result.error_kind == "timeout" and len(requests) == 1 and stream.closed
|
||||
assert any("connection reset" in message for message in cleanup_warnings)
|
||||
|
||||
|
||||
async def test_chat_callback_error_wins_over_close_error(chat_sdk, cleanup_warnings):
|
||||
stream = _ControlledChatStream([
|
||||
_bad_chat_event("usage"), _chat_event({"content": "fail"}),
|
||||
], close_error=httpx.CloseError("connection reset"))
|
||||
provider, requests = chat_sdk([stream])
|
||||
|
||||
async def on_content(value):
|
||||
raise RuntimeError("callback failed")
|
||||
|
||||
result = await provider.chat_stream(
|
||||
[{"role": "user", "content": "work"}], on_content_delta=on_content,
|
||||
)
|
||||
assert result.finish_reason == "error" and "callback failed" in result.content
|
||||
assert len(requests) == 1 and stream.closed and stream.close_calls == 1
|
||||
assert any("connection reset" in message for message in cleanup_warnings)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("close_fails", [False, True])
|
||||
@pytest.mark.parametrize("error_type", [RuntimeError, ConnectionError])
|
||||
async def test_chat_callback_error_does_not_retry_without_images(chat_sdk, close_fails, error_type):
|
||||
stream = _ControlledChatStream(
|
||||
[_chat_event({"reasoning_content": "thinking"})],
|
||||
close_error=httpx.CloseError("connection reset") if close_fails else None,
|
||||
)
|
||||
retry = _ControlledChatStream([_chat_event({"content": "unexpected"}, finish="stop")])
|
||||
provider, requests = chat_sdk([stream, retry])
|
||||
messages = [{"role": "user", "content": [
|
||||
{"type": "text", "text": "work"},
|
||||
{"type": "image_url", "image_url": {"url": "data:image/png;base64,AA=="}},
|
||||
]}]
|
||||
original = json.loads(json.dumps(messages))
|
||||
|
||||
async def on_thinking(_value):
|
||||
raise error_type("callback failed")
|
||||
|
||||
result = await provider.chat_stream_with_retry(messages, on_thinking_delta=on_thinking)
|
||||
|
||||
assert result.finish_reason == "error" and "callback failed" in result.content
|
||||
assert len(requests) == 1
|
||||
assert messages == original
|
||||
assert stream.closed
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mode", ["success", "quota", "cancel"])
|
||||
def test_langfuse_async_openai_chat_stream(mode):
|
||||
if importlib.util.find_spec("langfuse") is None:
|
||||
pytest.skip("optional Langfuse dependency is not installed")
|
||||
if mode == "quota":
|
||||
_require_minimum_sdk_for_iterator_close_failure()
|
||||
|
||||
# Langfuse instruments OpenAI globally; isolate those hooks in a child.
|
||||
script = textwrap.dedent("""
|
||||
import asyncio
|
||||
import runpy
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import httpx
|
||||
import langfuse.openai as langfuse_openai
|
||||
from nanobot.providers.openai_compat_provider import OpenAICompatProvider
|
||||
from nanobot.providers.registry import ModelAPICapabilities
|
||||
|
||||
test_file = Path(sys.argv[2]).resolve()
|
||||
sys.path.insert(0, str(test_file.parent.parent))
|
||||
helpers = runpy.run_path(str(test_file))
|
||||
event, stream_type = helpers["_chat_event"], helpers["_ControlledChatStream"]
|
||||
mode = sys.argv[1]
|
||||
starts, ends = [], []
|
||||
|
||||
class Generation:
|
||||
def update(self, **kwargs):
|
||||
return self
|
||||
def end(self):
|
||||
ends.append(True)
|
||||
class Tracer:
|
||||
def start_observation(self, **kwargs):
|
||||
starts.append(True)
|
||||
return Generation()
|
||||
langfuse_openai.get_client = lambda **kwargs: Tracer()
|
||||
|
||||
events = ([{"error": {"message": "quota exhausted", "type": "insufficient_quota",
|
||||
"code": "insufficient_quota"}}] if mode == "quota" else
|
||||
[event({"content": "complete"}, finish="stop")])
|
||||
stream = stream_type(events, close_error=(
|
||||
httpx.CloseError("connection reset") if mode != "success" else None))
|
||||
requests = []
|
||||
def handler(request):
|
||||
requests.append(request)
|
||||
reply = stream if len(requests) == 1 else stream_type([
|
||||
event({"content": "unexpected retry"}, finish="stop")])
|
||||
return httpx.Response(200, headers={"content-type": "text/event-stream"}, stream=reply)
|
||||
|
||||
async def main():
|
||||
client = langfuse_openai.AsyncOpenAI(
|
||||
api_key="synthetic", base_url="https://synthetic.invalid/v1", max_retries=0,
|
||||
http_client=httpx.AsyncClient(transport=httpx.MockTransport(handler), trust_env=False))
|
||||
provider = OpenAICompatProvider(
|
||||
api_key="synthetic", default_model="synthetic",
|
||||
model_api=ModelAPICapabilities(("chat_completions",), "chat_completions"))
|
||||
provider._client = client
|
||||
provider._CHAT_RETRY_DELAYS = (0,)
|
||||
try:
|
||||
if mode == "cancel":
|
||||
started = asyncio.Event()
|
||||
async def on_content(value):
|
||||
started.set()
|
||||
await asyncio.Event().wait()
|
||||
task = asyncio.create_task(provider.chat_stream_with_retry(
|
||||
[{"role": "user", "content": "work"}], on_content_delta=on_content))
|
||||
await asyncio.wait_for(started.wait(), timeout=5)
|
||||
task.cancel()
|
||||
try:
|
||||
await task
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError("caller cancellation was lost")
|
||||
else:
|
||||
result = await provider.chat_stream_with_retry(
|
||||
[{"role": "user", "content": "work"}])
|
||||
if mode == "success":
|
||||
assert result.finish_reason == "stop" and result.content == "complete"
|
||||
else:
|
||||
assert result.finish_reason == "error"
|
||||
assert result.error_type == result.error_code == "insufficient_quota"
|
||||
assert len(requests) == 1 and stream.closed and stream.close_calls == 1
|
||||
assert len(starts) == len(ends) == 1
|
||||
finally:
|
||||
await client.close()
|
||||
asyncio.run(main())
|
||||
""")
|
||||
env = {
|
||||
key: os.environ[key]
|
||||
for key in (
|
||||
"PATH", "SYSTEMROOT", "WINDIR", "TEMP", "TMP", "HOME", "USERPROFILE", "APPDATA",
|
||||
"LOCALAPPDATA", "PYTHONPATH", "PYTHONDONTWRITEBYTECODE", "LD_LIBRARY_PATH",
|
||||
)
|
||||
if key in os.environ
|
||||
}
|
||||
result = subprocess.run(
|
||||
[sys.executable, "-B", "-c", script, mode, __file__], env=env,
|
||||
capture_output=True, text=True, timeout=30, check=False,
|
||||
creationflags=subprocess.CREATE_NO_WINDOW if sys.platform == "win32" else 0,
|
||||
)
|
||||
assert result.returncode == 0, result.stdout + result.stderr
|
||||
@@ -4,6 +4,7 @@ import asyncio
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from openai.types.chat import ChatCompletion, ChatCompletionChunk
|
||||
|
||||
@@ -121,6 +122,20 @@ def _chat_chunk(delta, finish=None, usage=None) -> ChatCompletionChunk:
|
||||
})
|
||||
|
||||
|
||||
class _FakeChatStream:
|
||||
def __init__(self, iterator):
|
||||
self.iterator = iterator
|
||||
self.close_error = None
|
||||
|
||||
def __aiter__(self):
|
||||
return self.iterator.__aiter__()
|
||||
|
||||
async def close(self):
|
||||
await self.iterator.aclose()
|
||||
if self.close_error is not None:
|
||||
raise self.close_error
|
||||
|
||||
|
||||
def _fake_chat_stream(text: str = "ok"):
|
||||
async def _stream():
|
||||
yield _chat_chunk({"content": text})
|
||||
@@ -128,7 +143,7 @@ def _fake_chat_stream(text: str = "ok"):
|
||||
"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15,
|
||||
})
|
||||
|
||||
return _stream()
|
||||
return _FakeChatStream(_stream())
|
||||
|
||||
|
||||
def _fake_chat_stream_reasoning_chunks():
|
||||
@@ -142,7 +157,7 @@ def _fake_chat_stream_reasoning_chunks():
|
||||
"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15,
|
||||
})
|
||||
|
||||
return _stream()
|
||||
return _FakeChatStream(_stream())
|
||||
|
||||
|
||||
def _fake_chat_stream_tool_call_chunks():
|
||||
@@ -163,7 +178,7 @@ def _fake_chat_stream_tool_call_chunks():
|
||||
"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15,
|
||||
})
|
||||
|
||||
return _stream()
|
||||
return _FakeChatStream(_stream())
|
||||
|
||||
|
||||
def _fake_chat_stream_legacy_function_call_chunks():
|
||||
@@ -178,7 +193,34 @@ def _fake_chat_stream_legacy_function_call_chunks():
|
||||
"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15,
|
||||
})
|
||||
|
||||
return _stream()
|
||||
return _FakeChatStream(_stream())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("close_error", [
|
||||
httpx.CloseError("connection reset"), TimeoutError("cleanup deadline"),
|
||||
], ids=["close-error", "close-timeout"])
|
||||
@pytest.mark.parametrize("with_image", [False, True], ids=["text", "image"])
|
||||
async def test_stream_close_only_error_is_visible_without_retry(close_error, with_image):
|
||||
stream = _fake_chat_stream("complete")
|
||||
stream.close_error = close_error
|
||||
content = [{"type": "text", "text": "work"}]
|
||||
if with_image:
|
||||
content.append({"type": "image_url", "image_url": {"url": "data:image/png;base64,AA=="}})
|
||||
messages = [{"role": "user", "content": content}]
|
||||
with patch("nanobot.providers.openai_compat_provider.AsyncOpenAI") as mock_openai:
|
||||
create = AsyncMock(return_value=stream)
|
||||
mock_openai.return_value.chat.completions.create = create
|
||||
provider = OpenAICompatProvider(
|
||||
api_key="synthetic", default_model="synthetic",
|
||||
model_api=ModelAPICapabilities(("chat_completions",), "chat_completions"),
|
||||
)
|
||||
provider._CHAT_RETRY_DELAYS = (0,)
|
||||
result = await provider.chat_stream_with_retry(messages)
|
||||
|
||||
assert result.finish_reason == "error" and str(close_error) in result.content
|
||||
assert result.error_kind == "cleanup" and result.error_should_retry is False
|
||||
assert create.await_count == 1
|
||||
assert messages[0]["content"] == content
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -390,6 +432,9 @@ class _FakeResponsesError(Exception):
|
||||
|
||||
|
||||
class _StalledStream:
|
||||
async def close(self):
|
||||
pass
|
||||
|
||||
def __aiter__(self):
|
||||
return self
|
||||
|
||||
|
||||
@@ -954,6 +954,37 @@ class TestResponsesConversationState:
|
||||
}
|
||||
assert "lossy public transcript" not in str(items)
|
||||
|
||||
@pytest.mark.parametrize("last_system, expected", [
|
||||
("latest instructions", "latest instructions"),
|
||||
([{"type": "text", "text": "not a string"}], ""),
|
||||
])
|
||||
def test_replay_uses_the_latest_system_message(self, last_system, expected):
|
||||
state = build_responses_state(
|
||||
provider="openai:test", model="test-model",
|
||||
input_items=[{"role": "user", "content": "accepted"}], output_items=[],
|
||||
).with_pending_messages([{"role": "user", "content": "new"}])
|
||||
messages = [
|
||||
{"role": "system", "content": "old instructions"},
|
||||
{"role": "user", "content": "historical"},
|
||||
{"role": "system", "content": last_system},
|
||||
]
|
||||
|
||||
instructions, items, replayed = prepare_responses_input(
|
||||
messages, state=state, provider="openai:test", model="test-model",
|
||||
)
|
||||
assert replayed is True
|
||||
assert instructions == expected
|
||||
assert items == [
|
||||
{"role": "user", "content": "accepted"},
|
||||
{"role": "user", "content": [{"type": "input_text", "text": "new"}]},
|
||||
]
|
||||
|
||||
fallback_instructions, fallback_items, replayed = prepare_responses_input(
|
||||
messages, state=state, provider="openai:other", model="test-model",
|
||||
)
|
||||
assert replayed is False
|
||||
assert (fallback_instructions, fallback_items) == convert_messages(messages)
|
||||
|
||||
def test_replayed_and_delta_reasoning_items_keep_array_content(self):
|
||||
# Regression for PR #5214: token consolidation clears
|
||||
# ``provider_state``, so the next turn converts the full history
|
||||
|
||||
@@ -23,6 +23,7 @@ class _AsyncStream:
|
||||
def __init__(self, chunks: list[Any]) -> None:
|
||||
self._chunks = chunks
|
||||
self._idx = 0
|
||||
self.close = AsyncMock()
|
||||
|
||||
def __aiter__(self) -> _AsyncStream:
|
||||
return self
|
||||
@@ -82,15 +83,17 @@ async def test_openai_compat_stream_ignores_invalid_idle_timeout_env(monkeypatch
|
||||
"model": "test-model",
|
||||
"choices": [{"index": 0, "delta": {"content": "ok"}, "finish_reason": "stop"}],
|
||||
})
|
||||
stream = _AsyncStream([chunk])
|
||||
provider._client = SimpleNamespace(
|
||||
chat=SimpleNamespace(completions=SimpleNamespace(
|
||||
create=AsyncMock(return_value=_AsyncStream([chunk])),
|
||||
create=AsyncMock(return_value=stream),
|
||||
)),
|
||||
)
|
||||
|
||||
result = await provider.chat_stream(messages=[{"role": "user", "content": "hi"}])
|
||||
|
||||
assert result.content == "ok"
|
||||
stream.close.assert_awaited_once()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
|
||||
Reference in new issue
Block a user