The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
bound Relay stream aclose during cleanup
beardthelion161b0e04239c
diff --git a/agent/relay_llm.py b/agent/relay_llm.pyindex 4ba6f315caf..f1d731da5fa 100644--- a/agent/relay_llm.py+++ b/agent/relay_llm.py@@ -22,6 +22,10 @@ _PROVIDER_MESSAGE_EXTENSION_KEYS = frozenset({"reasoning_content", "reasoning_de_RELAY_INTERNAL_PROVIDER_HEADERS = frozenset({"x-dynamo-parent-session-id", "x-dynamo-session-id"})_LogicalCall = tuple[relay_runtime.RelayTurnContext, Any, str]+# Bound for awaiting a Relay stream's aclose() on the private loop: a wedged+# close must not hang the worker thread or hold the runtime lease forever.+_ACLOSE_TIMEOUT = 10.0+# api_mode -> (Relay operation name, codec class name on ``relay.codecs``)_RELAY_PROTOCOL_BY_API_MODE = {@@ -251,16 +255,31 @@ def stream_current(return managed.final_response if managed.final_response is not None else managed-def _aclose_on_loop(loop: asyncio.AbstractEventLoop, stream: Any) -> None:- """Await ``stream.aclose()`` on ``loop`` when the stream exposes one."""+def _aclose_on_loop(loop: asyncio.AbstractEventLoop, stream: Any) -> bool:+ """Await ``stream.aclose()`` on ``loop`` when the stream exposes one, bounded by+ ``_ACLOSE_TIMEOUT``. Returns False when the attempt is abandoned: the daemon+ thread still owns the running loop, so the caller must leave it open rather+ than ``loop.close()`` under it."""close = getattr(stream, "aclose", None)if not callable(close):- return+ return Trueasync def close_stream() -> None: # create the coroutine on ``loop``, not the caller's threadawait close()- loop.run_until_complete(close_stream())+ try:+ relay_runtime._run_on_daemon_thread(+ lambda: loop.run_until_complete(close_stream()),+ name="relay-llm-stream-aclose", timeout=_ACLOSE_TIMEOUT,+ timeout_message="Relay stream aclose did not finish; abandoning the close attempt",+ )+ except TimeoutError:+ logger.warning(+ "Relay stream aclose exceeded %ss; abandoning the close attempt and its private loop",+ _ACLOSE_TIMEOUT,+ )+ return False+ return Trueclass ManagedLlmStream(Iterator[Any]):@@ -494,10 +513,12 @@ class ManagedLlmStream(Iterator[Any]):try:if loop is not None:try:- _aclose_on_loop(loop, relay_stream)+ completed = _aclose_on_loop(loop, relay_stream)except Exception:logger.debug("Relay stream cleanup failed during provider fallback", exc_info=True)- loop.close()+ completed = True+ if completed:+ loop.close()self._finish_logical("success")finally:self._release_runtime_lease()@@ -527,15 +548,16 @@ class ManagedLlmStream(Iterator[Any]):self._prefetched_chunks.clear()try:loop, self._loop = self._loop, None+ close_loop = loop is not Noneif loop is None:self._close_provider_resources()else:try:- _aclose_on_loop(loop, self._stream)+ close_loop = _aclose_on_loop(loop, self._stream)except Exception as exc:self._keep_first_close_error(exc)self._finish_logical(logical_outcome)- if loop is not None:+ if close_loop:loop.close()finally:self._release_runtime_lease()diff --git a/tests/agent/test_relay_llm.py b/tests/agent/test_relay_llm.pyindex 1da0d13a6c2..c3f6997aaec 100644--- a/tests/agent/test_relay_llm.py+++ b/tests/agent/test_relay_llm.py@@ -886,6 +886,128 @@ def test_stream_flushes_buffered_provider_chunks_after_relay_failure(assert turn.logical_llm_calls == {}+def test_wedged_relay_aclose_does_not_block_stream_close(+ relay_turn, monkeypatch+):+ """close() on a live managed stream whose Relay aclose() never finishes+ abandons the attempt instead of hanging the caller; the runtime lease is+ released either way."""+ relay, turn = relay_turn+ monkeypatch.setattr(relay_llm, "_ACLOSE_TIMEOUT", 0.2)+ raw_chunks = [{"delta": "first"}, {"delta": "second"}]++ class _WedgedAclose:+ def __init__(self, agen):+ self._agen = agen++ def __aiter__(self):+ return self++ async def __anext__(self):+ return await self._agen.__anext__()++ async def aclose(self):+ await asyncio.Event().wait() # never completes++ async def yield_all(+ _name,+ request,+ callback,+ observe_chunk,+ finalizer,+ **_kwargs,+ ):+ async def generate():+ upstream = callback(request)+ yield await anext(upstream)+ yield await anext(upstream)++ return _WedgedAclose(generate())++ monkeypatch.setattr(relay.llm, "stream_execute", yield_all)+ stream = relay_llm.stream(+ {"model": "test-model", "messages": []},+ lambda _request: iter(raw_chunks),+ session_id="session-1",+ name="test-provider",+ model_name="test-model",+ finalizer=lambda: {"content": "complete"},+ metadata={+ "api_mode": "custom",+ "api_request_id": "request-wedged-aclose-close",+ },+ )++ assert next(stream) == raw_chunks[0]+ stream.close() # must return despite the wedged aclose+ assert stream._runtime_lease is None+ # shutdown() waits on _operations_idle before finishing; an abandoned close+ # must still release the operation lease so the runtime can drain.+ assert turn.lease.host._operations_idle.wait(timeout=1.0)+++def test_wedged_relay_aclose_does_not_block_provider_fallback(+ relay_turn, monkeypatch+):+ """A Relay stream whose aclose() never finishes must not wedge the provider+ fallback: the close is bounded, the private loop is abandoned rather than+ closed under a running attempt, pending provider chunks still deliver, and+ the runtime lease is released."""+ relay, turn = relay_turn+ monkeypatch.setattr(relay_llm, "_ACLOSE_TIMEOUT", 0.2)+ raw_chunks = [{"delta": "first"}, {"delta": "second"}]++ class _WedgedAclose:+ def __init__(self, agen):+ self._agen = agen++ def __aiter__(self):+ return self++ async def __anext__(self):+ return await self._agen.__anext__()++ async def aclose(self):+ await asyncio.Event().wait() # never completes++ async def fail_after_buffering(+ _name,+ request,+ callback,+ observe_chunk,+ finalizer,+ **_kwargs,+ ):+ async def generate():+ upstream = callback(request)+ await anext(upstream) # buffered via _raw_chunks, never yielded+ await anext(upstream) # buffered via _raw_chunks, never yielded+ with pytest.raises(StopAsyncIteration):+ await anext(upstream) # provider completed; chunks still undelivered+ raise RuntimeError("simulated Relay failure after buffering")+ yield # unreachable: keeps generate() an async generator++ return _WedgedAclose(generate())++ monkeypatch.setattr(relay.llm, "stream_execute", fail_after_buffering)+ stream = relay_llm.stream(+ {"model": "test-model", "messages": []},+ lambda _request: iter(raw_chunks),+ session_id="session-1",+ name="test-provider",+ model_name="test-model",+ finalizer=lambda: {"content": "complete"},+ metadata={+ "api_mode": "custom",+ "api_request_id": "request-wedged-aclose",+ },+ )++ assert list(stream) == raw_chunks+ assert turn.logical_llm_calls == {}+ assert stream._runtime_lease is None++