From 9aabf831ad733a1e2a13f92a60cf3bfb32b73022 Mon Sep 17 00:00:00 2001 From: fei <204683769+feiiiiii5@users.noreply.github.com> Date: Thu, 19 Nov 2026 19:50:46 -0800 Subject: [PATCH 1/4] fix(cohere): handle cancellation and forward stream attributes Signed-off-by: fei <204683769+feiiiiii5@users.noreply.github.com> --- .../integrations/cohere/test_cohere.py | 134 +++++++++++++++++- .../braintrust/integrations/cohere/tracing.py | 61 +++++++- 2 files changed, 185 insertions(+), 10 deletions(-) diff --git a/py/src/braintrust/integrations/cohere/test_cohere.py b/py/src/braintrust/integrations/cohere/test_cohere.py index e88f0526e..65c4cad2f 100644 --- a/py/src/braintrust/integrations/cohere/test_cohere.py +++ b/py/src/braintrust/integrations/cohere/test_cohere.py @@ -484,12 +484,14 @@ def test_wrap_cohere_chat_stream_v1_sync(memory_logger): start = time.time() events = [] - for event in client.chat_stream( + stream = client.chat_stream( model=CHAT_MODEL, message="Say hi in one word.", max_tokens=8, - ): + ) + for event in stream: events.append(event) + stream.close() end = time.time() assert events @@ -574,9 +576,10 @@ def test_wrap_cohere_chat_stream_v2_sync_context_manager(memory_logger): ) as stream: for event in stream: events.append(event) + break end = time.time() - assert events + assert len(events) == 1 spans = memory_logger.pop() assert len(spans) == 1 @@ -778,3 +781,128 @@ def test_cohere_integration_setup_patches_audio_transcriptions(memory_logger, cl class TestAutoInstrumentCohere: def test_auto_instrument_cohere(self): verify_autoinstrument_script("test_auto_cohere.py") + + +def test_wrap_cohere_async_chat_cancellation_records_error(memory_logger): + from unittest.mock import patch + + from cohere.base_client import AsyncBaseCohere + + assert not memory_logger.pop() + + async def _cancelled_chat(*args, **kwargs): + raise asyncio.CancelledError("request was cancelled") + + async def _run(): + with patch.object(AsyncBaseCohere, "chat", _cancelled_chat): + client = wrap_cohere(_v1_async_client()) + await client.chat(model=CHAT_MODEL, message="hello") + + with pytest.raises(asyncio.CancelledError): + asyncio.run(_run()) + + spans = memory_logger.pop() + assert len(spans) == 1 + assert "request was cancelled" in spans[0].get("error", "") + assert spans[0]["metrics"]["end"] >= spans[0]["metrics"]["start"] + + +def test_wrap_cohere_async_chat_stream_cancellation_records_error(memory_logger): + from unittest.mock import patch + + from cohere.base_client import AsyncBaseCohere + + assert not memory_logger.pop() + + class _MockStream: + def __aiter__(self): + return self + + async def __anext__(self): + raise asyncio.CancelledError("stream was cancelled") + + async def _run(): + with patch.object(AsyncBaseCohere, "chat_stream", lambda *a, **kw: _MockStream()): + client = wrap_cohere(_v1_async_client()) + stream = await client.chat_stream(model=CHAT_MODEL, message="hello") + async for _ in stream: + pass + + with pytest.raises(asyncio.CancelledError): + asyncio.run(_run()) + + spans = memory_logger.pop() + assert len(spans) == 1 + assert "stream was cancelled" in spans[0].get("error", "") + assert spans[0]["metrics"]["end"] >= spans[0]["metrics"]["start"] + + +def test_wrap_cohere_chat_stream_close_error_records_error(memory_logger): + from unittest.mock import patch + + from cohere.base_client import BaseCohere + + assert not memory_logger.pop() + + class _MockSyncStream: + def __init__(self): + self.custom_attr = "custom_value" + + def __iter__(self): + return self + + def __next__(self): + return {"event_type": "text-generation", "text": "hello"} + + def close(self): + raise RuntimeError("close failed") + + with patch.object(BaseCohere, "chat_stream", lambda *a, **kw: _MockSyncStream()): + client = wrap_cohere(_v1_client()) + stream = client.chat_stream(model=CHAT_MODEL, message="hello") + assert stream.custom_attr == "custom_value" + next(stream) + with pytest.raises(RuntimeError, match="close failed"): + stream.close() + + spans = memory_logger.pop() + assert len(spans) == 1 + assert "close failed" in spans[0].get("error", "") + assert spans[0]["metrics"]["end"] >= spans[0]["metrics"]["start"] + + +def test_wrap_cohere_async_chat_stream_aclose_error_records_error(memory_logger): + from unittest.mock import patch + + from cohere.base_client import AsyncBaseCohere + + assert not memory_logger.pop() + + class _MockAsyncStream: + def __init__(self): + self.custom_async_attr = "async_value" + + def __aiter__(self): + return self + + async def __anext__(self): + return {"event_type": "text-generation", "text": "hello"} + + async def aclose(self): + raise asyncio.CancelledError("aclose was cancelled") + + async def _run(): + with patch.object(AsyncBaseCohere, "chat_stream", lambda *a, **kw: _MockAsyncStream()): + client = wrap_cohere(_v1_async_client()) + stream = await client.chat_stream(model=CHAT_MODEL, message="hello") + assert stream.custom_async_attr == "async_value" + await stream.__anext__() + await stream.aclose() + + with pytest.raises(asyncio.CancelledError): + asyncio.run(_run()) + + spans = memory_logger.pop() + assert len(spans) == 1 + assert "aclose was cancelled" in spans[0].get("error", "") + assert spans[0]["metrics"]["end"] >= spans[0]["metrics"]["start"] diff --git a/py/src/braintrust/integrations/cohere/tracing.py b/py/src/braintrust/integrations/cohere/tracing.py index 174dda911..a57edbb34 100644 --- a/py/src/braintrust/integrations/cohere/tracing.py +++ b/py/src/braintrust/integrations/cohere/tracing.py @@ -10,6 +10,7 @@ derived from ``usage`` / ``meta.billed_units`` / ``meta.tokens``. """ +import asyncio import logging import time from typing import Any @@ -696,7 +697,7 @@ async def _trace_async_call(name: str, span_input: Any, metadata: dict[str, Any] start_time = time.time() try: result = await wrapped(*args, **kwargs) - except Exception as error: + except (Exception, asyncio.CancelledError) as error: _log_error_and_end_span(span, error) raise @@ -794,7 +795,7 @@ async def _async_chat_stream_wrapper(wrapped, instance, args, kwargs): # noqa: start_time = time.time() try: iterator = wrapped(*args, **kwargs) - except Exception as error: + except (Exception, asyncio.CancelledError) as error: _log_error_and_end_span(span, error) raise @@ -803,7 +804,7 @@ async def _async_chat_stream_wrapper(wrapped, instance, args, kwargs): # noqa: if hasattr(iterator, "__await__"): try: iterator = await iterator - except Exception as error: + except (Exception, asyncio.CancelledError) as error: _log_error_and_end_span(span, error) raise @@ -824,6 +825,9 @@ def __init__(self, iterator: Any, span: Any, start_time: float): self._chunks: list[Any] = [] self._finished = False + def __getattr__(self, name: str) -> Any: + return getattr(self._iterator, name) + def _record(self, event: Any) -> None: if self._first_token_time is None: self._first_token_time = time.time() @@ -867,7 +871,11 @@ def __exit__(self, exc_type, exc_value, traceback): context_manager = getattr(self, "_context_manager", self._iterator) exit_method = getattr(context_manager, "__exit__", None) if exit_method is not None: - suppress = bool(exit_method(exc_type, exc_value, traceback)) + try: + suppress = bool(exit_method(exc_type, exc_value, traceback)) + except (Exception, asyncio.CancelledError) as error: + self._finish(error=error) + raise if exc_value is not None: self._finish(error=exc_value) else: @@ -883,12 +891,23 @@ def __next__(self): except StopIteration: self._finish() raise - except Exception as error: + except (Exception, asyncio.CancelledError) as error: self._finish(error=error) raise self._record(event) return event + def close(self) -> None: + close_method = getattr(self._iterator, "close", None) + try: + if callable(close_method): + close_method() + except (Exception, asyncio.CancelledError) as error: + self._finish(error=error) + raise + else: + self._finish() + class _AsyncTracedChatStream(_ChatStreamTracker): """Async counterpart of :class:`_TracedChatStream`.""" @@ -906,7 +925,11 @@ async def __aexit__(self, exc_type, exc_value, traceback): context_manager = getattr(self, "_context_manager", self._iterator) aexit = getattr(context_manager, "__aexit__", None) if aexit is not None: - suppress = bool(await aexit(exc_type, exc_value, traceback)) + try: + suppress = bool(await aexit(exc_type, exc_value, traceback)) + except (Exception, asyncio.CancelledError) as error: + self._finish(error=error) + raise if exc_value is not None: self._finish(error=exc_value) else: @@ -922,12 +945,36 @@ async def __anext__(self): except StopAsyncIteration: self._finish() raise - except Exception as error: + except (Exception, asyncio.CancelledError) as error: self._finish(error=error) raise self._record(event) return event + async def aclose(self) -> None: + aclose_method = getattr(self._iterator, "aclose", None) + try: + if callable(aclose_method): + res = aclose_method() + if hasattr(res, "__await__"): + await res + except (Exception, asyncio.CancelledError) as error: + self._finish(error=error) + raise + else: + self._finish() + + def close(self) -> None: + close_method = getattr(self._iterator, "close", None) + try: + if callable(close_method): + close_method() + except (Exception, asyncio.CancelledError) as error: + self._finish(error=error) + raise + else: + self._finish() + # --------------------------------------------------------------------------- # Manual wrapping — `wrap_cohere(client)` From 0f4d2fa8f86ca261703354cc0548a0a5f519308f Mon Sep 17 00:00:00 2001 From: fei <204683769+feiiiiii5@users.noreply.github.com> Date: Fri, 20 Nov 2026 02:42:50 -0800 Subject: [PATCH 2/4] test(cohere): cover explicit close on a real partially-read stream Drive the checked-in cassette recording instead of a hand-written stand-in: consume a real stream up to its first text event, close it, and assert the span is finished from the chunks read so far. The same test fails on main, where _TracedChatStream has no close(). --- .../integrations/cohere/test_cohere.py | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/py/src/braintrust/integrations/cohere/test_cohere.py b/py/src/braintrust/integrations/cohere/test_cohere.py index 65c4cad2f..0aff1e990 100644 --- a/py/src/braintrust/integrations/cohere/test_cohere.py +++ b/py/src/braintrust/integrations/cohere/test_cohere.py @@ -520,6 +520,38 @@ def test_wrap_cohere_chat_stream_v1_sync(memory_logger): assert metrics.get("completion_tokens", 0) > 0 +# Same request as the exhaustive test above; only the consumption differs. +@pytest.mark.vcr +@pytest.mark.parametrize("vcr_cassette_name", ["test_wrap_cohere_chat_stream_v1_sync"], ids=["shared"]) +def test_wrap_cohere_chat_stream_v1_sync_close_finalizes_partially_read_stream(memory_logger, vcr_cassette_name): + assert not memory_logger.pop() + client = wrap_cohere(_v1_client()) + + stream = client.chat_stream( + model=CHAT_MODEL, + message="Say hi in one word.", + max_tokens=8, + ) + first = next(stream) + assert first is not None + # Stop as soon as some text arrives, leaving the stream unfinished. + for event in stream: + if getattr(event, "event_type", None) == "text-generation": + break + + stream.close() + + # The explicit close finishes the span from the chunks read so far, without + # waiting for the stream to be exhausted. + spans = memory_logger.pop() + assert len(spans) == 1 + span = spans[0] + assert span["span_attributes"]["name"] == "cohere.chat_stream" + assert not span.get("error") + assert span["metrics"]["start"] <= span["metrics"]["end"] + assert span["output"] + + @pytest.mark.vcr def test_wrap_cohere_chat_stream_v2_sync(memory_logger): assert not memory_logger.pop() From 06f991e9bdb777413e1c5cf180c4c6b9da07e198 Mon Sep 17 00:00:00 2001 From: fei <204683769+feiiiiii5@users.noreply.github.com> Date: Fri, 20 Nov 2026 03:18:24 -0800 Subject: [PATCH 3/4] fix(integrations): name the exception type when it carries no message A CancelledError raised by Task.cancel() has an empty str(), so the span exported error: "" and lost what ended it. Fall back to the type name and cover the message-less cancellation in the cohere stream tests. --- .../integrations/cohere/test_cohere.py | 25 +++++++++++++++++++ py/src/braintrust/integrations/utils.py | 10 ++++++-- 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/py/src/braintrust/integrations/cohere/test_cohere.py b/py/src/braintrust/integrations/cohere/test_cohere.py index 0aff1e990..86c4b70cc 100644 --- a/py/src/braintrust/integrations/cohere/test_cohere.py +++ b/py/src/braintrust/integrations/cohere/test_cohere.py @@ -839,6 +839,31 @@ async def _run(): assert spans[0]["metrics"]["end"] >= spans[0]["metrics"]["start"] +def test_wrap_cohere_async_chat_message_less_cancellation_records_error(memory_logger): + from unittest.mock import patch + + from cohere.base_client import AsyncBaseCohere + + assert not memory_logger.pop() + + async def _cancelled_chat(*args, **kwargs): + raise asyncio.CancelledError + + async def _run(): + with patch.object(AsyncBaseCohere, "chat", _cancelled_chat): + client = wrap_cohere(_v1_async_client()) + await client.chat(model=CHAT_MODEL, message="hello") + + with pytest.raises(asyncio.CancelledError): + asyncio.run(_run()) + + spans = memory_logger.pop() + assert len(spans) == 1 + # A cancellation raised without a message must still name what ended the span. + assert spans[0].get("error") == "CancelledError" + assert spans[0]["metrics"]["end"] >= spans[0]["metrics"]["start"] + + def test_wrap_cohere_async_chat_stream_cancellation_records_error(memory_logger): from unittest.mock import patch diff --git a/py/src/braintrust/integrations/utils.py b/py/src/braintrust/integrations/utils.py index adf42f4be..47be26413 100644 --- a/py/src/braintrust/integrations/utils.py +++ b/py/src/braintrust/integrations/utils.py @@ -821,6 +821,12 @@ def _log_and_end_span( def _log_error_and_end_span(span: Span, error: BaseException) -> None: - """Log an error to *span* and immediately end it.""" - span.log(error=error) + """Log an error to *span* and immediately end it. + + ``str()`` of an exception raised without a message — a bare ``CancelledError`` + from ``Task.cancel()``, for example — is empty, which would export an empty + ``error`` field. Fall back to the type name so the span still records what + ended it. + """ + span.log(error=error if str(error) else type(error).__name__) span.end() From 2b7f7ecb7aba77b91f3f9ffbe541e04696992b85 Mon Sep 17 00:00:00 2001 From: fei <204683769+feiiiiii5@users.noreply.github.com> Date: Fri, 20 Nov 2026 04:22:52 -0800 Subject: [PATCH 4/4] fix(integrations): contain a failing __str__ in the error helper --- py/src/braintrust/integrations/test_utils.py | 15 +++++++++++++++ py/src/braintrust/integrations/utils.py | 10 ++++++++-- 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/py/src/braintrust/integrations/test_utils.py b/py/src/braintrust/integrations/test_utils.py index dc890f1a6..c426a6f57 100644 --- a/py/src/braintrust/integrations/test_utils.py +++ b/py/src/braintrust/integrations/test_utils.py @@ -548,6 +548,21 @@ def test_log_error_and_end_span_logs_error_then_ends(): span.end.assert_called_once_with() +def test_log_error_and_end_span_survives_an_unprintable_error(): + class Unprintable(Exception): + def __str__(self): + raise RuntimeError("cannot render") + + span = unittest.mock.Mock() + + _log_error_and_end_span(span, Unprintable()) + + # The probe must not escape before the span is ended; the type name still says + # what ended it. + span.log.assert_called_once_with(error="Unprintable") + span.end.assert_called_once_with() + + def test_merge_timing_and_usage_metrics(monkeypatch): monkeypatch.setattr("braintrust.integrations.utils.time.time", lambda: 15.0) diff --git a/py/src/braintrust/integrations/utils.py b/py/src/braintrust/integrations/utils.py index 47be26413..5cd0353fb 100644 --- a/py/src/braintrust/integrations/utils.py +++ b/py/src/braintrust/integrations/utils.py @@ -826,7 +826,13 @@ def _log_error_and_end_span(span: Span, error: BaseException) -> None: ``str()`` of an exception raised without a message — a bare ``CancelledError`` from ``Task.cancel()``, for example — is empty, which would export an empty ``error`` field. Fall back to the type name so the span still records what - ended it. + ended it. ``str()`` can also raise, for an exception with a broken + ``__str__``, and that must not stop the span from ending: the probe is + contained and the type name is used instead. """ - span.log(error=error if str(error) else type(error).__name__) + try: + message = str(error) + except Exception: + message = "" + span.log(error=error if message else type(error).__name__) span.end()