From 036c35e5647cfd9b564abd569cab0b4346269958 Mon Sep 17 00:00:00 2001 From: HenriqueAssumpcao Date: Tue, 10 Nov 2026 20:05:51 -0300 Subject: [PATCH 1/2] fix(lm): don't replay successful completions when usage is missing OpenAILM.generate read `ret.usage.prompt_tokens` inside its retry block. With OpenAI-compatible providers that omit the optional `usage` field, a successful (billed) completion raised AttributeError, was retried retries+1 times, and was finally discarded as a ConnectionError. OpenAIEmbedding.embed_batch had the same problem with `total_tokens`. - Only the request itself is retried; once it succeeds, missing or partial usage is reported as None token counts instead of an error. The ensemble logs a warning through the island logger. - Responses with no choices (or the wrong number of embedding vectors) raise a clear EmptyResponseError and are still retried. - Non-retryable client errors (400/401/403/404/422) fail immediately instead of going through the backoff loop; 429/5xx are still retried. - Update BaseLM/BaseEnsemble/BaseEmbedding hints to Optional[int] token counts, and fix the ensemble's mis-ordered return annotation. - Add offline tests using the real AsyncOpenAI client over httpx.MockTransport fixtures, counting HTTP attempts. Refs #9 Co-Authored-By: Claude Opus 5.5 --- src/codeevolve/lm/base.py | 26 ++-- src/codeevolve/lm/openai.py | 147 ++++++++++++++---- tests/test_lm.py | 298 +++++++++++++++++++++++++++++++++++- 3 files changed, 426 insertions(+), 45 deletions(-) diff --git a/src/codeevolve/lm/base.py b/src/codeevolve/lm/base.py index a1fb99f..ed1b63f 100644 --- a/src/codeevolve/lm/base.py +++ b/src/codeevolve/lm/base.py @@ -11,14 +11,16 @@ # ===--------------------------------------------------------------------------------------===# from abc import ABC, abstractmethod -from typing import Dict, List, Tuple +from typing import Dict, List, Optional, Tuple class BaseLM(ABC): """Abstract base class for language models.""" @abstractmethod - async def generate(self, messages: List[Dict[str, str]]) -> Tuple[str, int, int]: + async def generate( + self, messages: List[Dict[str, str]] + ) -> Tuple[str, Optional[int], Optional[int]]: """Generates a response from the language model. Args: @@ -27,8 +29,8 @@ async def generate(self, messages: List[Dict[str, str]]) -> Tuple[str, int, int] Returns: A tuple containing: - Generated text response - - Number of prompt tokens used - - Number of completion tokens used + - Number of prompt tokens used (None if not reported) + - Number of completion tokens used (None if not reported) """ pass @@ -37,7 +39,9 @@ class BaseEnsemble(ABC): """Abstract base class for language model ensembles.""" @abstractmethod - async def generate(self, messages: List[Dict[str, str]]) -> Tuple[int, str, int, int]: + async def generate( + self, messages: List[Dict[str, str]] + ) -> Tuple[int, str, Optional[int], Optional[int]]: """Generates a response using a model from the ensemble. Args: @@ -47,8 +51,8 @@ async def generate(self, messages: List[Dict[str, str]]) -> Tuple[int, str, int, A tuple containing: - Selected model ID - Generated text response - - Number of prompt tokens used - - Number of completion tokens used + - Number of prompt tokens used (None if not reported) + - Number of completion tokens used (None if not reported) """ pass @@ -57,7 +61,7 @@ class BaseEmbedding(ABC): """Abstract base class for embedding models.""" @abstractmethod - async def embed(self, text: str) -> Tuple[List[float], int]: + async def embed(self, text: str) -> Tuple[List[float], Optional[int]]: """Computes embeddings for a single text input. Args: @@ -66,12 +70,12 @@ async def embed(self, text: str) -> Tuple[List[float], int]: Returns: A tuple containing: - List of embedding values - - Number of tokens used + - Number of tokens used (None if not reported) """ pass @abstractmethod - async def embed_batch(self, texts: List[str]) -> Tuple[List[List[float]], int]: + async def embed_batch(self, texts: List[str]) -> Tuple[List[List[float]], Optional[int]]: """Computes embeddings for multiple text inputs. Args: @@ -80,6 +84,6 @@ async def embed_batch(self, texts: List[str]) -> Tuple[List[List[float]], int]: Returns: A tuple containing: - List of embedding vectors - - Total number of tokens used + - Total number of tokens used (None if not reported) """ pass diff --git a/src/codeevolve/lm/openai.py b/src/codeevolve/lm/openai.py index 35c6891..1958ff2 100644 --- a/src/codeevolve/lm/openai.py +++ b/src/codeevolve/lm/openai.py @@ -20,6 +20,7 @@ from uuid import uuid4 import httpx +import openai from openai import AsyncOpenAI from codeevolve.lm.base import BaseEmbedding, BaseEnsemble, BaseLM @@ -30,6 +31,42 @@ ) from codeevolve.utils.parsing import find_evolve_block_spans +# --------------------------------------------------------------------------- +# Response helpers +# --------------------------------------------------------------------------- + +# Client errors that will fail the same way on every attempt (bad request, bad +# credentials, unknown model, ...). Retrying them only wastes time. +_NON_RETRYABLE_ERRORS: Tuple[type, ...] = ( + openai.BadRequestError, + openai.AuthenticationError, + openai.PermissionDeniedError, + openai.NotFoundError, + openai.UnprocessableEntityError, +) + + +class EmptyResponseError(RuntimeError): + """Raised when a provider returns a response without any generated output.""" + + +def _get_usage_count(usage: Any, name: str) -> Optional[int]: + """Reads a token count from an optional usage object. + + Usage metadata is optional for many OpenAI-compatible providers and gateways, + so a missing usage object or field must not be treated as a failed request. + + Args: + usage: The ``usage`` attribute of an SDK response (may be None). + name: Name of the token-count field to read. + + Returns: + The token count, or None if the provider did not report it. + """ + value: Any = getattr(usage, name, None) + return value if isinstance(value, int) else None + + # --------------------------------------------------------------------------- # Language model classes # --------------------------------------------------------------------------- @@ -100,9 +137,16 @@ def __post_init__(self): api_key=self.api_key, base_url=self.api_base, http_client=http_client ) - async def generate(self, messages: List[Dict[str, str]]) -> Tuple[str, int, int]: + async def generate( + self, messages: List[Dict[str, str]] + ) -> Tuple[str, Optional[int], Optional[int]]: """Generates a response from the language model. + A request is retried (with exponential backoff) only when it fails or returns + no choices. A successful completion is never replayed because of missing + usage metadata: token counts are reported as None instead. Client errors + that cannot succeed on retry (e.g. 400, 401, 404) fail immediately. + Args: messages: List of message dictionaries with 'role' and 'content' keys following the OpenAI chat format. @@ -110,11 +154,12 @@ async def generate(self, messages: List[Dict[str, str]]) -> Tuple[str, int, int] Returns: A tuple containing: - Generated text response - - Number of prompt tokens used - - Number of completion tokens used + - Number of prompt tokens used (None if not reported by the provider) + - Number of completion tokens used (None if not reported by the provider) Raises: - ConnectionError: If all retry attempts fail to get a response. + ConnectionError: If the request fails with a non-retryable error, or if + all retry attempts fail to get a response. """ params: Dict[str, Any] = { "model": self.model_name, @@ -130,20 +175,33 @@ async def generate(self, messages: List[Dict[str, str]]) -> Tuple[str, int, int] for attempt in range(self.retries + 1): try: ret = await self.client.chat.completions.create(**params) - content: str = ret.choices[0].message.content - content = content if content is not None else "" - return (content, ret.usage.prompt_tokens, ret.usage.completion_tokens) + if not getattr(ret, "choices", None): + raise EmptyResponseError("Provider returned a response with no choices.") + except _NON_RETRYABLE_ERRORS as err: + raise ConnectionError( + f"Failed to fetch LM response (non-retryable error: {str(err)})." + ) from err except Exception as err: if attempt < self.retries: await asyncio.sleep(retry_delay) retry_delay = retry_delay << 1 - else: - raise ConnectionError( - ( - f"Failed to fetch LM response after {self.retries+1} attempts" - f"(Error:{str(err)})." - ) + continue + raise ConnectionError( + ( + f"Failed to fetch LM response after {self.retries+1} attempts " + f"(Error: {str(err)})." ) + ) from err + + # The request succeeded: from here on nothing may trigger a retry. + message: Any = getattr(ret.choices[0], "message", None) + content: Optional[str] = getattr(message, "content", None) + usage: Any = getattr(ret, "usage", None) + return ( + content if content is not None else "", + _get_usage_count(usage, "prompt_tokens"), + _get_usage_count(usage, "completion_tokens"), + ) @dataclass @@ -412,7 +470,9 @@ def configure_mocks(self, start_marker: str, end_marker: str) -> None: model.start_marker = start_marker model.end_marker = end_marker - async def generate(self, messages: List[Dict[str, str]]) -> Tuple[int, int, str, int]: + async def generate( + self, messages: List[Dict[str, str]] + ) -> Tuple[int, str, Optional[int], Optional[int]]: """Generates a response using a randomly selected model from the ensemble. Args: @@ -422,8 +482,8 @@ async def generate(self, messages: List[Dict[str, str]]) -> Tuple[int, int, str, A tuple containing: - Selected model ID (index in the ensemble) - Generated text response - - Number of prompt tokens used - - Number of completion tokens used + - Number of prompt tokens used (None if not reported by the provider) + - Number of completion tokens used (None if not reported by the provider) Raises: ConnectionError: If the selected model fails to generate a response. @@ -440,6 +500,11 @@ async def generate(self, messages: List[Dict[str, str]]) -> Tuple[int, int, str, f" and {compl_tok} completion tokens." ) ) + if prompt_tok is None or compl_tok is None: + self.logger.warning( + f"{self.models[model_id]} did not report full token usage; " + "recording missing counts as None." + ) return (model_id, response, prompt_tok, compl_tok) @@ -504,19 +569,23 @@ def __post_init__(self): api_key=self.api_key, base_url=self.api_base, http_client=http_client ) - async def embed_batch(self, texts: List[str]) -> Tuple[List[List[float]], int]: + async def embed_batch(self, texts: List[str]) -> Tuple[List[List[float]], Optional[int]]: """Computes embeddings for multiple text inputs in a single request. + As in `OpenAILM.generate`, missing usage metadata never causes a retry, + and non-retryable client errors fail immediately. + Args: texts: List of text strings to embed. Returns: A tuple containing: - List of embedding vectors (each vector is a list of floats) - - Total number of tokens used + - Total number of tokens used (None if not reported by the provider) Raises: - ConnectionError: If all retry attempts fail to get a response. + ConnectionError: If the request fails with a non-retryable error, or if + all retry attempts fail to get a response. """ params: Dict[str, Any] = { "model": self.model_name, @@ -531,24 +600,36 @@ async def embed_batch(self, texts: List[str]) -> Tuple[List[List[float]], int]: for attempt in range(self.retries + 1): try: response = await self.client.embeddings.create(**params) - embeddings = [data.embedding for data in response.data] - total_tokens = response.usage.total_tokens - - if len(texts) == 1: - return (embeddings[0], total_tokens) - return (embeddings, total_tokens) - + data: Any = getattr(response, "data", None) + if not data or len(data) != len(texts): + raise EmptyResponseError( + f"Provider returned {len(data) if data else 0} embeddings " + f"for {len(texts)} inputs." + ) + embeddings: List[List[float]] = [item.embedding for item in data] + except _NON_RETRYABLE_ERRORS as err: + raise ConnectionError( + f"Failed to compute embeddings (non-retryable error: {str(err)})." + ) from err except Exception as err: if attempt < self.retries: await asyncio.sleep(retry_delay) retry_delay = retry_delay << 1 - else: - raise ConnectionError( - f"Failed to compute embeddings after {self.retries + 1} attempts " - f"(Error: {str(err)})." - ) + continue + raise ConnectionError( + f"Failed to compute embeddings after {self.retries + 1} attempts " + f"(Error: {str(err)})." + ) from err + + # The request succeeded: from here on nothing may trigger a retry. + total_tokens: Optional[int] = _get_usage_count( + getattr(response, "usage", None), "total_tokens" + ) + if len(texts) == 1: + return (embeddings[0], total_tokens) + return (embeddings, total_tokens) - async def embed(self, text: str) -> Tuple[List[float], int]: + async def embed(self, text: str) -> Tuple[List[float], Optional[int]]: """Computes embeddings for a single text input. Args: @@ -557,7 +638,7 @@ async def embed(self, text: str) -> Tuple[List[float], int]: Returns: A tuple containing: - List of embedding values (floats) - - Number of tokens used + - Number of tokens used (None if not reported by the provider) Raises: ConnectionError: If all retry attempts fail to get a response. diff --git a/tests/test_lm.py b/tests/test_lm.py index 42d653c..9d9fee0 100644 --- a/tests/test_lm.py +++ b/tests/test_lm.py @@ -10,12 +10,18 @@ # # ===--------------------------------------------------------------------------------------===# -from typing import Any, Dict, List, Optional, Tuple, Union +import asyncio +import json +import logging +from typing import Any, Callable, Dict, List, Optional, Tuple, Union +import httpx import pytest +from openai import AsyncOpenAI from codeevolve.lm.openai import ( MockOpenAILM, + OpenAIEmbedding, OpenAIEnsemble, OpenAILM, _create_lm_from_config, @@ -224,3 +230,293 @@ def test_configure_mocks(self): if isinstance(model, MockOpenAILM): assert model.start_marker == "// START" assert model.end_marker == "// END" + + +# --------------------------------------------------------------------------- +# Offline provider fixtures for OpenAILM / OpenAIEmbedding +# --------------------------------------------------------------------------- + +_MESSAGES: List[Dict[str, str]] = [{"role": "user", "content": "hello"}] + + +def _make_completion_body( + content: Optional[str] = "ok", + usage: Optional[Dict[str, int]] = None, + include_usage_key: bool = True, + num_choices: int = 1, +) -> Dict[str, Any]: + """Builds a chat.completion JSON body as returned by an OpenAI-compatible API.""" + body: Dict[str, Any] = { + "id": "chatcmpl-test", + "object": "chat.completion", + "created": 0, + "model": "test-model", + "choices": [ + { + "index": i, + "message": {"role": "assistant", "content": content}, + "finish_reason": "stop", + } + for i in range(num_choices) + ], + } + if include_usage_key: + body["usage"] = usage + return body + + +def _make_embedding_body( + num_vectors: int = 1, + usage: Optional[Dict[str, int]] = None, + include_usage_key: bool = True, +) -> Dict[str, Any]: + """Builds an embeddings JSON body as returned by an OpenAI-compatible API.""" + body: Dict[str, Any] = { + "object": "list", + "model": "test-embedding", + "data": [ + {"object": "embedding", "index": i, "embedding": [0.1 * (i + 1), 0.2]} + for i in range(num_vectors) + ], + } + if include_usage_key: + body["usage"] = usage + return body + + +_USAGE: Dict[str, int] = {"prompt_tokens": 11, "completion_tokens": 7, "total_tokens": 18} + + +class _FakeProvider: + """Serves a scripted sequence of HTTP responses and counts requests.""" + + def __init__(self, responses: List[Tuple[int, Dict[str, Any]]]): + self.responses: List[Tuple[int, Dict[str, Any]]] = responses + self.calls: int = 0 + + def handler(self, request: httpx.Request) -> httpx.Response: + status, body = self.responses[min(self.calls, len(self.responses) - 1)] + self.calls += 1 + return httpx.Response(status, content=json.dumps(body).encode()) + + def client(self) -> AsyncOpenAI: + # max_retries=0 disables the SDK's own retries so that only the + # wrapper's retry loop is under test. + return AsyncOpenAI( + api_key="test_key", + base_url="http://fake-provider.test/v1", + max_retries=0, + http_client=httpx.AsyncClient(transport=httpx.MockTransport(self.handler)), + ) + + +def _error_body(status: int) -> Dict[str, Any]: + return {"error": {"message": f"simulated {status}", "type": "test", "code": None}} + + +@pytest.fixture +def no_backoff(monkeypatch): + """Makes the wrapper's exponential backoff instantaneous.""" + + async def _instant(_delay: float) -> None: + return None + + monkeypatch.setattr("codeevolve.lm.openai.asyncio.sleep", _instant) + + +def _make_lm(provider: _FakeProvider, retries: int = 3) -> OpenAILM: + lm: OpenAILM = OpenAILM( + model_name="test-model", api_key="test_key", api_base="http://x", retries=retries + ) + lm.client = provider.client() + return lm + + +def _make_embedding(provider: _FakeProvider, retries: int = 3) -> OpenAIEmbedding: + emb: OpenAIEmbedding = OpenAIEmbedding( + model_name="test-embedding", api_key="test_key", api_base="http://x", retries=retries + ) + emb.client = provider.client() + return emb + + +class TestOpenAILMUsageMetadata: + """Usage metadata is optional and must never cause a successful request to be replayed.""" + + @pytest.mark.asyncio + async def test_reported_usage_is_returned(self, no_backoff): + provider = _FakeProvider([(200, _make_completion_body(usage=_USAGE))]) + result = await _make_lm(provider).generate(_MESSAGES) + assert result == ("ok", 11, 7) + assert provider.calls == 1 + + @pytest.mark.asyncio + async def test_absent_usage_key_is_not_retried(self, no_backoff): + provider = _FakeProvider([(200, _make_completion_body(include_usage_key=False))]) + result = await _make_lm(provider).generate(_MESSAGES) + assert result == ("ok", None, None) + assert provider.calls == 1 + + @pytest.mark.asyncio + async def test_null_usage_is_not_retried(self, no_backoff): + provider = _FakeProvider([(200, _make_completion_body(usage=None))]) + result = await _make_lm(provider).generate(_MESSAGES) + assert result == ("ok", None, None) + assert provider.calls == 1 + + @pytest.mark.asyncio + async def test_partial_usage(self, no_backoff): + provider = _FakeProvider([(200, _make_completion_body(usage={"prompt_tokens": 5}))]) + result = await _make_lm(provider).generate(_MESSAGES) + assert result == ("ok", 5, None) + assert provider.calls == 1 + + @pytest.mark.asyncio + async def test_null_content_becomes_empty_string(self, no_backoff): + provider = _FakeProvider([(200, _make_completion_body(content=None, usage=_USAGE))]) + result = await _make_lm(provider).generate(_MESSAGES) + assert result == ("", 11, 7) + assert provider.calls == 1 + + +class TestOpenAILMRetries: + """Retry behaviour for empty responses and provider errors.""" + + @pytest.mark.asyncio + async def test_empty_choices_retried_until_exhausted(self, no_backoff): + provider = _FakeProvider([(200, _make_completion_body(num_choices=0, usage=_USAGE))]) + with pytest.raises(ConnectionError, match="no choices"): + await _make_lm(provider, retries=2).generate(_MESSAGES) + assert provider.calls == 3 + + @pytest.mark.asyncio + async def test_empty_choices_then_success(self, no_backoff): + provider = _FakeProvider( + [ + (200, _make_completion_body(num_choices=0)), + (200, _make_completion_body(usage=_USAGE)), + ] + ) + result = await _make_lm(provider).generate(_MESSAGES) + assert result == ("ok", 11, 7) + assert provider.calls == 2 + + @pytest.mark.asyncio + @pytest.mark.parametrize("status", [429, 500, 503]) + async def test_transient_errors_are_retried(self, no_backoff, status): + provider = _FakeProvider( + [(status, _error_body(status)), (200, _make_completion_body(usage=_USAGE))] + ) + result = await _make_lm(provider).generate(_MESSAGES) + assert result == ("ok", 11, 7) + assert provider.calls == 2 + + @pytest.mark.asyncio + async def test_persistent_transient_error_exhausts_retries(self, no_backoff): + provider = _FakeProvider([(500, _error_body(500))]) + with pytest.raises(ConnectionError, match="after 4 attempts"): + await _make_lm(provider, retries=3).generate(_MESSAGES) + assert provider.calls == 4 + + @pytest.mark.asyncio + @pytest.mark.parametrize("status", [400, 401, 403, 404, 422]) + async def test_non_retryable_errors_fail_fast(self, no_backoff, status): + provider = _FakeProvider([(status, _error_body(status))]) + with pytest.raises(ConnectionError, match="non-retryable"): + await _make_lm(provider, retries=3).generate(_MESSAGES) + assert provider.calls == 1 + + @pytest.mark.asyncio + async def test_backoff_is_exponential(self, monkeypatch): + delays: List[float] = [] + + async def _record(delay: float) -> None: + delays.append(delay) + + monkeypatch.setattr("codeevolve.lm.openai.asyncio.sleep", _record) + provider = _FakeProvider([(500, _error_body(500))]) + with pytest.raises(ConnectionError): + await _make_lm(provider, retries=3).generate(_MESSAGES) + assert delays == [1, 2, 4] + + +class TestOpenAIEnsembleUsageWarning: + """The ensemble surfaces missing usage metadata through its logger.""" + + def _make_ensemble(self, provider: _FakeProvider, logger: logging.Logger) -> OpenAIEnsemble: + ensemble = OpenAIEnsemble( + models_cfg=[{"model_name": "test-model", "retries": 0}], + api_key="test_key", + api_base="http://x", + logger=logger, + ) + ensemble.models[0].client = provider.client() + return ensemble + + @pytest.mark.asyncio + async def test_missing_usage_logs_warning(self, caplog): + logger = logging.getLogger("test_lm.ensemble.missing") + provider = _FakeProvider([(200, _make_completion_body(include_usage_key=False))]) + with caplog.at_level(logging.WARNING, logger=logger.name): + result = await self._make_ensemble(provider, logger).generate(_MESSAGES) + assert result == (0, "ok", None, None) + assert provider.calls == 1 + assert any("did not report full token usage" in r.message for r in caplog.records) + + @pytest.mark.asyncio + async def test_reported_usage_logs_no_warning(self, caplog): + logger = logging.getLogger("test_lm.ensemble.reported") + provider = _FakeProvider([(200, _make_completion_body(usage=_USAGE))]) + with caplog.at_level(logging.WARNING, logger=logger.name): + result = await self._make_ensemble(provider, logger).generate(_MESSAGES) + assert result == (0, "ok", 11, 7) + assert not [r for r in caplog.records if r.levelno >= logging.WARNING] + + +class TestOpenAIEmbedding: + """Usage handling and retries for the embedding wrapper.""" + + @pytest.mark.asyncio + async def test_single_text_with_usage(self, no_backoff): + provider = _FakeProvider( + [(200, _make_embedding_body(usage={"prompt_tokens": 3, "total_tokens": 3}))] + ) + embedding, tokens = await _make_embedding(provider).embed("hello") + assert embedding == [0.1, 0.2] + assert tokens == 3 + assert provider.calls == 1 + + @pytest.mark.asyncio + async def test_missing_usage_is_not_retried(self, no_backoff): + provider = _FakeProvider([(200, _make_embedding_body(include_usage_key=False))]) + embedding, tokens = await _make_embedding(provider).embed("hello") + assert embedding == [0.1, 0.2] + assert tokens is None + assert provider.calls == 1 + + @pytest.mark.asyncio + async def test_batch_returns_all_vectors(self, no_backoff): + provider = _FakeProvider([(200, _make_embedding_body(num_vectors=2, usage=None))]) + embeddings, tokens = await _make_embedding(provider).embed_batch(["a", "b"]) + assert len(embeddings) == 2 + assert tokens is None + assert provider.calls == 1 + + @pytest.mark.asyncio + async def test_wrong_vector_count_is_retried(self, no_backoff): + provider = _FakeProvider( + [ + (200, _make_embedding_body(num_vectors=1)), + (200, _make_embedding_body(num_vectors=2)), + ] + ) + embeddings, _ = await _make_embedding(provider).embed_batch(["a", "b"]) + assert len(embeddings) == 2 + assert provider.calls == 2 + + @pytest.mark.asyncio + async def test_non_retryable_error_fails_fast(self, no_backoff): + provider = _FakeProvider([(401, _error_body(401))]) + with pytest.raises(ConnectionError, match="non-retryable"): + await _make_embedding(provider).embed("hello") + assert provider.calls == 1 From f0c4e22ef165123be5946a144a3dc2387d929d9b Mon Sep 17 00:00:00 2001 From: HenriqueAssumpcao Date: Tue, 10 Nov 2026 20:05:51 -0300 Subject: [PATCH 2/2] test(logging): fix race in test_queue_handler_truncated mp.Queue.put() hands items to a background feeder thread, so calling get_nowait() immediately afterwards intermittently raised queue.Empty (failing ~80% of local runs). Wait for the item with a timeout instead. Co-Authored-By: Claude Opus 5.5 --- tests/test_logging.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/test_logging.py b/tests/test_logging.py index 157da18..21d1cfe 100644 --- a/tests/test_logging.py +++ b/tests/test_logging.py @@ -202,7 +202,9 @@ def test_queue_handler_truncated(self, tmp_path: Path): ) logger.info(long_msg) - queued: str = queue.get_nowait() + # mp.Queue.put() hands items to a background feeder thread, so the message may + # not be readable yet; get_nowait() here would race that thread. + queued: str = queue.get(timeout=5) assert "[TRUNCATED]" in queued, "Queue log should truncate long messages"