Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

fix(llm): close the upstream generator in RateLimitedLLMWrapper stream/astream (#6805)

LearningCircuit2360114bfc8c
diff --git a/src/local_deep_research/web_search_engines/rate_limiting/llm/wrapper.py b/src/local_deep_research/web_search_engines/rate_limiting/llm/wrapper.py
index cbdd6b7783..f9b92847da 100644
--- a/src/local_deep_research/web_search_engines/rate_limiting/llm/wrapper.py
+++ b/src/local_deep_research/web_search_engines/rate_limiting/llm/wrapper.py
@@ -2,6 +2,7 @@
Rate-limited wrapper for LLM calls.
"""
+import inspect
from typing import Optional
from urllib.parse import urlparse
@@ -265,18 +266,107 @@ def create_rate_limited_llm_wrapper(base_llm, provider: Optional[str] = None):
self._scrub_or_raise(e)
chunks = iter(self._call_rate_limited(_source))
- while True:
- # Only the advance is guarded, and `yield` stays outside the
- # `try`: a handler that encloses the yield also catches
- # whatever the CONSUMER throws back in, which would scrub an
- # unrelated caller-side failure as if it were a provider 429.
- try:
- chunk = next(chunks)
- except StopIteration:
+ try:
+ while True:
+ # Only the advance is guarded, and `yield` stays outside the
+ # inner `try`: a handler that encloses the yield also catches
+ # whatever the CONSUMER throws back in, which would scrub an
+ # unrelated caller-side failure as if it were a provider 429.
+ # The outer handler only closes the upstream and
+ # re-raises the same object it caught, so a consumer
+ # `throw()` still propagates untouched to the caller.
+ try:
+ chunk = next(chunks)
+ except StopIteration:
+ break
+ except Exception as e:
+ self._scrub_or_raise(e)
+ yield chunk
+ except BaseException as exc:
+ # Close the upstream generator on ANY exit — early consumer
+ # close (GeneratorExit lands at the yield above) or an
+ # exception — so its connection does not linger until GC
+ # (#6607).
+ self._close_upstream(chunks, exc)
+ raise
+ self._close_upstream(chunks, None)
+
+ def _close_upstream(self, chunks, body_exc):
+ """Close a sync upstream iterator after stream() stops.
+
+ The upstream's own cleanup can raise (e.g. a LangChain callback
+ handler failing in on_llm_error), and that text may carry
+ provider or credential material, so any close failure is
+ handled by ``_handle_close_error`` rather than left to
+ propagate raw. Only an explicit consumer close (GeneratorExit)
+ still surfaces the (scrubbed) close failure; a normal
+ exhaustion or an unrelated body exception both keep the close
+ failure out of the caller's way. The attribute lookup itself
+ is inside the guarded try: a proxy whose ``__getattr__`` raises
+ must not replace whatever is already propagating. Tolerant of
+ non-generator iterables (mocks, list-backed sources) that have
+ no close().
+ """
+ try:
+ closer = getattr(chunks, "close", None)
+ if closer is None:
return
- except Exception as e:
- self._scrub_or_raise(e)
- yield chunk
+ closer()
+ except Exception as close_exc:
+ self._handle_close_error(close_exc, body_exc)
+
+ async def _aclose_upstream(self, chunks, body_exc):
+ """Async twin of _close_upstream() for astream()."""
+ # Skip an upstream that is already finished or mid-close: at
+ # loop shutdown / cyclic GC the event loop's asyncgen finalizer
+ # may already be running its aclose(), and a second one raises
+ # "aclose(): asynchronous generator is already running".
+ # Only the order where the loop's aclose starts first can be
+ # guarded here. When this aclose starts first and the
+ # upstream's cleanup suspends (e.g. an async callback handler
+ # awaiting in on_llm_error), the loop's own later aclose hits
+ # that RuntimeError inside asyncio and is logged by the loop's
+ # exception handler. That is benign: the upstream is still
+ # closed exactly once, and the log carries no provider text.
+ # It needs a consumer that abandons astream() without aclose().
+ #
+ # All the lookups below (ag_running, ag_frame, aclose) live
+ # inside this same guarded try as the close call itself: a
+ # proxy whose __getattr__ raises must not replace whatever
+ # exception is already propagating.
+ try:
+ if getattr(chunks, "ag_running", False) is True:
+ return
+ if inspect.isasyncgen(chunks) and chunks.ag_frame is None:
+ return
+ acloser = getattr(chunks, "aclose", None)
+ if acloser is None:
+ return
+ result = acloser()
+ # Plain callables (e.g. a Mock source) return a
+ # non-awaitable; only real coroutines are awaited.
+ if inspect.isawaitable(result):
+ await result
+ except Exception as close_exc:
+ self._handle_close_error(close_exc, body_exc)
+
+ def _handle_close_error(self, close_exc, body_exc):
+ """Decide whether a close() failure should surface.
+
+ Only an explicit consumer close (``body_exc`` is
+ ``GeneratorExit``) keeps the current scrub-and-raise
+ behaviour. A normal exhaustion (``body_exc`` is ``None``) or
+ any other in-flight exception must not be replaced by the
+ close failure: it is logged at debug with the close
+ exception's type name only and dropped.
+ """
+ if isinstance(body_exc, GeneratorExit):
+ self._scrub_or_raise(close_exc)
+ return
+ logger.debug(
+ "Suppressed {} while closing the upstream stream",
+ type(close_exc).__name__,
+ )
async def astream(self, *args, **kwargs):
"""Async generator implementing LangChain's astream contract:
@@ -298,15 +388,25 @@ def create_rate_limited_llm_wrapper(base_llm, provider: Optional[str] = None):
except Exception as e:
self._scrub_or_raise(e)
- while True:
- # `yield` deliberately outside the `try`; see stream().
- try:
- chunk = await chunks.__anext__()
- except StopAsyncIteration:
- return
- except Exception as e:
- self._scrub_or_raise(e)
- yield chunk
+ try:
+ while True:
+ # `yield` deliberately outside the inner `try`; see
+ # stream(). The outer handler re-raises the same object,
+ # so a consumer `throw()` still propagates untouched.
+ try:
+ chunk = await chunks.__anext__()
+ except StopAsyncIteration:
+ break
+ except Exception as e:
+ self._scrub_or_raise(e)
+ yield chunk
+ except BaseException as exc:
+ # Async twin of stream()'s cleanup: close the upstream
+ # async generator on any exit instead of leaking the
+ # connection until GC or loop shutdown (#6607).
+ await self._aclose_upstream(chunks, exc)
+ raise
+ await self._aclose_upstream(chunks, None)
async def _acall_rate_limited(self, call):
"""Async variant of _call_rate_limited."""
diff --git a/tests/test_llm_rate_limiting.py b/tests/test_llm_rate_limiting.py
index 91ec7b9ec4..a6c330e83c 100644
--- a/tests/test_llm_rate_limiting.py
+++ b/tests/test_llm_rate_limiting.py
@@ -3,7 +3,7 @@ Tests for LLM rate limiting functionality.
"""
import pytest
-from unittest.mock import Mock, patch
+from unittest.mock import AsyncMock, Mock, patch
from langchain_core.messages import AIMessage
from tests.test_utils import add_src_to_path
@@ -514,3 +514,610 @@ class TestRateLimitedWrapperReviewFixes:
assert captured[:1] == [{"tags": ["shared"]}]
assert captured[1:] == [{"metadata": 1}, {"metadata": 2}]
+
+
+class TestStreamUpstreamLifetime:
+ """Upstream generator lifetime in stream()/astream() (#6607).
+
+ The `yield` stays outside the scrub region so a consumer `throw()` is
+ not scrubbed as a provider error; the wrapper must nonetheless close
+ the upstream generator on early consumer close instead of leaking the
+ connection until GC.
+
+ Every test holds each upstream generator the wrapper creates in an
+ outer list: otherwise CPython refcounting closes the upstream as soon
+ as the wrapper's frame is freed, and the assertions would pass with
+ the explicit close removed.
+ """
+
+ FAKE_KEY = "sk-" + "a1b2c3d4e5f6g7h8i9j0" # 20+ chars: real key shape
+
+ @pytest.fixture
+ def mock_llm(self):
+ llm = Mock()
+ llm.model_name = "test-model"
+ llm.base_url = "https://api.example.com"
+ return llm
+
+ def _wrapper(self, mock_llm):
+ return create_rate_limited_llm_wrapper(mock_llm, provider="openai")
+
+ @staticmethod
+ def _tracked(factory, upstream):
+ def tracked(*args, **kwargs):
+ gen = factory(*args, **kwargs)
+ upstream.append(gen)
+ return gen
+
+ return tracked
+
+ def test_stream_closes_upstream_on_consumer_close(self, mock_llm):
+ events: list[str] = []
+ upstream: list = []
+
+ def source(*args, **kwargs):
+ try:
+ for chunk in ["c1", "c2", "c3"]:
+ events.append(f"yield:{chunk}")
+ yield chunk
+ finally:
+ events.append("upstream_closed")
+
+ mock_llm.stream = self._tracked(source, upstream)
+ gen = self._wrapper(mock_llm).stream("prompt")
+
+ assert next(gen) == "c1"
+ gen.close()
+
+ assert len(upstream) == 1
+ assert events == ["yield:c1", "upstream_closed"]
+
+ def test_astream_closes_upstream_on_consumer_close(self, mock_llm):
+ import asyncio
+
+ events: list[str] = []
+ # Hold every upstream generator the wrapper creates so GC/loop
+ # shutdown cannot close it behind our back — the WRAPPER must be
+ # the one issuing the aclose.
+ upstream: list = []
+
+ async def source(*args, **kwargs):
+ try:
+ for chunk in ["c1", "c2", "c3"]:
+ events.append(f"yield:{chunk}")
+ yield chunk
+ finally:
+ events.append("upstream_closed")
+
+ mock_llm.astream = self._tracked(source, upstream)
+
+ async def run():
+ gen = self._wrapper(mock_llm).astream("prompt")
+ assert await gen.__anext__() == "c1"
+ await gen.aclose()
+ # Snapshot INSIDE the loop: loop shutdown finalizes any
+ # leftover async generators, which would mask a leak.
+ return list(events)
+
+ assert asyncio.run(run()) == ["yield:c1", "upstream_closed"]
+
+ def test_consumer_throw_is_not_scrubbed_and_still_closes_upstream(
+ self, mock_llm
+ ):
+ """A consumer-thrown error must propagate as itself (not be scrubbed
+ as a provider failure — hence the 429-shaped message), and the
+ upstream generator must still be closed on the way out."""
+ events: list[str] = []
+ upstream: list = []
+
+ def source(*args, **kwargs):
+ try:
+ yield "c1"
+ yield "c2"
+ finally:
+ events.append("upstream_closed")
+
+ mock_llm.stream = self._tracked(source, upstream)
+ gen = self._wrapper(mock_llm).stream("prompt")
+ assert next(gen) == "c1"
+
+ thrown = ValueError("Error: 429 quota exceeded, from my own loop")
+ with pytest.raises(ValueError) as exc_info:
+ gen.throw(thrown)
+
+ assert exc_info.value is thrown
+ assert len(upstream) == 1
+ assert events == ["upstream_closed"]
+
+ def test_async_consumer_throw_is_not_scrubbed_and_still_closes_upstream(
+ self, mock_llm
+ ):
+ """Async twin of
+ test_consumer_throw_is_not_scrubbed_and_still_closes_upstream: a
+ consumer-thrown error must propagate as itself (not be scrubbed as
+ a provider failure — hence the 429-shaped message), and the
+ upstream async generator must still be closed on the way out."""
+ import asyncio
+
+ events: list[str] = []
+ upstream: list = []
+
+ async def source(*args, **kwargs):
+ try:
+ yield "c1"
+ yield "c2"
+ finally:
+ events.append("upstream_closed")
+
+ mock_llm.astream = self._tracked(source, upstream)
+
+ async def run():
+ gen = self._wrapper(mock_llm).astream("prompt")
+ assert await gen.__anext__() == "c1"
+
+ thrown = ValueError("Error: 429 quota exceeded, from my own loop")
+ with pytest.raises(ValueError) as exc_info:
+ await gen.athrow(thrown)
+
+ # Checked INSIDE the loop: loop shutdown finalizes leftover
+ # async generators, which would mask a missing close.
+ assert exc_info.value is thrown
+ assert len(upstream) == 1
+ assert events == ["upstream_closed"]
+
+ asyncio.run(run())
+
+ def test_astream_cancellation_closes_upstream(self, mock_llm):
+ """Cancelling the task consuming astream() must still close the
+ upstream. The upstream here is a plain custom async iterator (not
+ an async generator): __anext__ returns immediately on the first
+ call and suspends in a long asyncio.sleep() on the second, so the
+ task can be cancelled while genuinely awaiting inside the
+ wrapper's astream(). The sleep duration is irrelevant to wall
+ time — cancellation fires long before it could ever elapse — so
+ this is not flaky."""
+ import asyncio
+
+ class SleepingUpstream:
+ """Not an async generator: exercises the aclose() branch of
+ _aclose_upstream() that isn't gated by inspect.isasyncgen()/
+ ag_frame, per the wrapper's own support for non-generator
+ async iterables (mocks, custom iterators)."""
+
+ def __init__(self):
+ self.calls = 0
+ self.aclose_called = False
+
+ def __aiter__(self):
+ return self
+
+ async def __anext__(self):
+ self.calls += 1
+ if self.calls == 1:
+ return "c1"
+ await asyncio.sleep(3600)
+ return "c2" # pragma: no cover - never reached
+
+ async def aclose(self):
+ self.aclose_called = True
+
+ upstream = SleepingUpstream()
+ mock_llm.astream = Mock(return_value=upstream)
+
+ async def run():
+ gen = self._wrapper(mock_llm).astream("prompt")
+ first_chunk_seen = asyncio.Event()
+ consumed: list = []
+
+ async def consume():
+ async for chunk in gen:
+ consumed.append(chunk)
+ first_chunk_seen.set()
+
+ task = asyncio.create_task(consume())
+ await first_chunk_seen.wait()
+ task.cancel()
+
+ with pytest.raises(asyncio.CancelledError):
+ await task
+
+ # Checked INSIDE the loop: loop shutdown finalizes leftover
+ # async generators/tasks, which would mask a missing close.
+ assert consumed == ["c1"]
+ assert upstream.aclose_called
+
+ asyncio.run(run())
+
+ def test_stream_upstream_cleanup_error_does_not_replace_consumer_throw(
+ self, mock_llm
+ ):
+ upstream: list = []
+ fake_key = self.FAKE_KEY
+
+ def source(*args, **kwargs):
+ try:
+ yield "c1"
+ yield "c2"
+ finally:
+ raise RuntimeError(f"Error: 429 cleanup, key {fake_key}")
+
+ mock_llm.stream = self._tracked(source, upstream)
+ gen = self._wrapper(mock_llm).stream("prompt")
+ assert next(gen) == "c1"
+
+ thrown = KeyError("consumer-side failure")
+ with pytest.raises(KeyError) as exc_info:
+ gen.throw(thrown)
+
+ assert exc_info.value is thrown
+ assert upstream[0].gi_frame is None # upstream was still closed
+
+ def test_stream_upstream_cleanup_error_on_close_is_scrubbed(self, mock_llm):
+ upstream: list = []
+ fake_key = self.FAKE_KEY
+
+ def source(*args, **kwargs):
+ try:
+ yield "c1"
+ yield "c2"
+ finally:
+ raise RuntimeError(f"Error: 429 cleanup, key {fake_key}")
+
+ mock_llm.stream = self._tracked(source, upstream)
+ gen = self._wrapper(mock_llm).stream("prompt")
+ assert next(gen) == "c1"
+
+ with pytest.raises(Exception) as exc_info:
+ gen.close()
+
+ assert fake_key not in str(exc_info.value)
+ assert exc_info.value.__cause__ is None
+ assert exc_info.value.__suppress_context__
+
+ def test_astream_upstream_cleanup_error_does_not_replace_consumer_throw(
+ self, mock_llm
+ ):
+ import asyncio
+
+ upstream: list = []
+ fake_key = self.FAKE_KEY
+
+ async def source(*args, **kwargs):
+ try:
+ yield "c1"
+ yield "c2"
+ finally:
+ raise RuntimeError(f"Error: 429 cleanup, key {fake_key}")
+
+ mock_llm.astream = self._tracked(source, upstream)
+ thrown = KeyError("consumer-side failure")
+
+ async def run():
+ gen = self._wrapper(mock_llm).astream("prompt")
+ assert await gen.__anext__() == "c1"
+ with pytest.raises(KeyError) as exc_info:
+ await gen.athrow(thrown)
+ # Checked INSIDE the loop: loop shutdown finalizes leftover
+ # async generators, which would mask a missing close.
+ assert upstream[0].ag_frame is None
+ return exc_info.value
+
+ raised = asyncio.run(run())
+ assert raised is thrown
+
+ def test_astream_upstream_cleanup_error_on_close_is_scrubbed(
+ self, mock_llm
+ ):
+ import asyncio
+
+ upstream: list = []
+ fake_key = self.FAKE_KEY
+
+ async def source(*args, **kwargs):
+ try:
+ yield "c1"
+ yield "c2"
+ finally:
+ raise RuntimeError(f"Error: 429 cleanup, key {fake_key}")
+
+ mock_llm.astream = self._tracked(source, upstream)
+
+ async def run():
+ gen = self._wrapper(mock_llm).astream("prompt")
+ assert await gen.__anext__() == "c1"
+ with pytest.raises(Exception) as exc_info:
+ await gen.aclose()
+ return exc_info.value
+
+ raised = asyncio.run(run())
+ assert fake_key not in str(raised)
+ assert raised.__cause__ is None
+ assert raised.__suppress_context__
+
+ def test_astream_tolerates_non_awaitable_aclose(self, mock_llm):
+ """A source whose aclose() is a plain callable (e.g. a Mock) must
+ not make the wrapper await a non-awaitable."""
+ import asyncio
+
+ class Source:
+ def __init__(self):
+ self.aclose = Mock(return_value=None)
+
+ def __aiter__(self):
+ return self
+
+ async def __anext__(self):
+ return "c1"
+
+ source = Source()
+ mock_llm.astream = Mock(return_value=source)
+
+ async def run():
+ gen = self._wrapper(mock_llm).astream("prompt")
+ assert await gen.__anext__() == "c1"
+ await gen.aclose()
+
+ asyncio.run(run())
+ source.aclose.assert_called_once_with()
+
+ def test_astream_skips_aclose_on_running_upstream(self, mock_llm):
+ """An upstream already mid-aclose (ag_running, e.g. being finalized
+ by the loop at shutdown / cyclic GC) must not get a second aclose,
+ which raises "asynchronous generator is already running"."""
+ import asyncio
+
+ class Source:
+ ag_running = False
+
+ def __init__(self):
+ self.aclose = AsyncMock()
+
+ def __aiter__(self):
+ return self
+
+ async def __anext__(self):
+ return "c1"
+
+ source = Source()
+ mock_llm.astream = Mock(return_value=source)
+
+ async def run():
+ gen = self._wrapper(mock_llm).astream("prompt")
+ assert await gen.__anext__() == "c1"
+ source.ag_running = True
+ await gen.aclose()
+
+ asyncio.run(run())
+ source.aclose.assert_not_called()
+
+ def test_stream_returns_all_chunks_when_close_raises_on_exhaustion(
+ self, mock_llm
+ ):
+ """A close() failure after the stream body already finished
+ successfully must not fail an otherwise-successful stream (#6805
+ R2): a non-generator source makes the exhaustion path (no
+ GeneratorExit involved) distinct from the consumer-close tests
+ above."""
+
+ class It:
+ def __init__(self, values):
+ self._it = iter(values)
+
+ def __iter__(self):
+ return self
+
+ def __next__(self):
+ return next(self._it)
+
+ def close(self):
+ raise RuntimeError("benign close failure")
+
+ mock_llm.stream = Mock(return_value=It([1, 2]))
+
+ assert list(self._wrapper(mock_llm).stream("prompt")) == [1, 2]
+
+ def test_astream_returns_all_chunks_when_aclose_raises_on_exhaustion(
+ self, mock_llm
+ ):
+ """Async twin of
+ test_stream_returns_all_chunks_when_close_raises_on_exhaustion:
+ a non-async-generator source (so the ag_frame guard never
+ applies) whose aclose() raises after the body finished must not
+ fail the astream."""
+ import asyncio
+
+ class It:
+ def __init__(self, values):
+ self._it = iter(values)
+
+ def __aiter__(self):
+ return self
+
+ async def __anext__(self):
+ try:
+ return next(self._it)
+ except StopIteration:
+ raise StopAsyncIteration
+
+ async def aclose(self):
+ raise RuntimeError("benign close failure")
+
+ mock_llm.astream = Mock(return_value=It([1, 2]))
+
+ async def run():
+ return [x async for x in self._wrapper(mock_llm).astream("prompt")]
+
+ assert asyncio.run(run()) == [1, 2]
+
+ def test_stream_closes_upstream_on_normal_exhaustion(self, mock_llm):
+ """The upstream is closed even when the stream runs to completion
+ with no consumer interruption at all — a recording (non-raising)
+ close makes the call itself observable, independent of whether a
+ close failure would have been suppressed."""
+
+ closed = []
+
+ class It:
+ def __init__(self, values):
+ self._it = iter(values)
+
+ def __iter__(self):
+ return self
+
+ def __next__(self):
+ return next(self._it)
+
+ def close(self):
+ closed.append(1)
+
+ mock_llm.stream = Mock(return_value=It(["c1", "c2"]))
+
+ assert list(self._wrapper(mock_llm).stream("prompt")) == ["c1", "c2"]
+ assert closed == [1]
+
+ def test_astream_closes_upstream_on_normal_exhaustion(self, mock_llm):
+ """Async twin of test_stream_closes_upstream_on_normal_exhaustion."""
+ import asyncio
+
+ closed = []
+
+ class It:
+ def __init__(self, values):
+ self._it = iter(values)
+
+ def __aiter__(self):
+ return self
+
+ async def __anext__(self):
+ try:
+ return next(self._it)
+ except StopIteration:
+ raise StopAsyncIteration
+
+ async def aclose(self):
+ closed.append(1)
+
+ mock_llm.astream = Mock(return_value=It(["c1", "c2"]))
+
+ async def run():
+ return [x async for x in self._wrapper(mock_llm).astream("prompt")]
+
+ assert asyncio.run(run()) == ["c1", "c2"]
+ assert closed == [1]
+
+ def test_stream_close_lookup_error_does_not_replace_consumer_throw(
+ self, mock_llm
+ ):
+ """A proxy whose __getattr__ raises when the wrapper probes for
+ close() must not replace the consumer's thrown exception: the
+ getattr lookup has to live inside the same guarded try as the
+ close() call itself (#6805 R4)."""
+
+ class BadCloseProxy:
+ def __init__(self, values):
+ self._it = iter(values)
+
+ def __iter__(self):
+ return self
+
+ def __next__(self):
+ return next(self._it)
+
+ def __getattr__(self, name):
+ raise RuntimeError(f"proxy __getattr__ blew up on {name!r}")
+
+ mock_llm.stream = Mock(return_value=BadCloseProxy(["c1", "c2"]))
+ gen = self._wrapper(mock_llm).stream("prompt")
+ assert next(gen) == "c1"
+
+ thrown = KeyError("consumer-side failure")
+ with pytest.raises(KeyError) as exc_info:
+ gen.throw(thrown)
+ assert exc_info.value is thrown
+
+ def test_astream_close_lookup_error_does_not_replace_consumer_throw(
+ self, mock_llm
+ ):
+ """Async twin of
+ test_stream_close_lookup_error_does_not_replace_consumer_throw:
+ the proxy's __getattr__ blows up on the ag_running/aclose probes
+ too, not just close()."""
+ import asyncio
+
+ class BadAcloseProxy:
+ def __init__(self, values):
+ self._it = iter(values)
+
+ def __aiter__(self):
+ return self
+
+ async def __anext__(self):
+ try:
+ return next(self._it)
+ except StopIteration:
+ raise StopAsyncIteration
+
+ def __getattr__(self, name):
+ raise RuntimeError(f"proxy __getattr__ blew up on {name!r}")
+
+ mock_llm.astream = Mock(return_value=BadAcloseProxy(["c1", "c2"]))
+ thrown = KeyError("consumer-side failure")
+
+ async def run():
+ gen = self._wrapper(mock_llm).astream("prompt")
+ assert await gen.__anext__() == "c1"
+ with pytest.raises(KeyError) as exc_info:
+ await gen.athrow(thrown)
+ return exc_info.value
+
+ raised = asyncio.run(run())
+ assert raised is thrown
+
+ def test_astream_skips_aclose_when_upstream_already_finished(
+ self, mock_llm
+ ):
+ """When the upstream is a real async generator that has already
+ run to completion (ag_frame is None), aclose() must not be
+ called on it again (#6805 R5). A plain custom Source class (as
+ used above for the ag_running guard) never satisfies
+ ``inspect.isasyncgen``, so this needs a Mock built with ``spec``
+ on a genuinely exhausted async generator instance: Mock copies
+ the spec object's ``__class__``, which makes
+ ``inspect.isasyncgen()`` (an isinstance check) see it as a real
+ async generator while still letting the test observe whether
+ aclose() was called."""
+ import asyncio
+ import inspect
+
+ async def real_source():
+ yield "c1"
+
+ async def run():
+ real = real_source()
+ assert await real.__anext__() == "c1"
+ with pytest.raises(StopAsyncIteration):
+ await real.__anext__()
+ assert inspect.isasyncgen(real)
+ assert real.ag_frame is None
+
+ proxy = Mock(spec=real)
+ proxy.ag_running = False
+ proxy.ag_frame = None
+ proxy.aclose = AsyncMock()
+ proxy.__anext__ = AsyncMock(
+ side_effect=["c1", StopAsyncIteration()]
+ )
+
+ class Aiter:
+ def __aiter__(self):
+ return proxy
+
+ mock_llm.astream = Mock(return_value=Aiter())
+ gen = self._wrapper(mock_llm).astream("prompt")
+ assert await gen.__anext__() == "c1"
+ with pytest.raises(StopAsyncIteration):
+ await gen.__anext__()
+
+ proxy.aclose.assert_not_called()
+
+ asyncio.run(run())