Skip to content

"Vibe-Trading: Your Personal Trading Agent"

Merge PR #2099: supervise silent streams without dropping chunks or session context

Haozhe Wu67f7b22a9ef2
diff --cc agent/src/providers/chat.py
index d250a1d46,338e8ca0e..5fe2726d9
--- a/agent/src/providers/chat.py
+++ b/agent/src/providers/chat.py
@@@ -11,7 -11,6 +11,7 @@@ import inspec
import logging
import os
import re
- import time as _time
++from contextlib import closing
from dataclasses import dataclass, field
from typing import Any, Callable, Dict, List, Optional
@@@ -512,6 -512,6 +513,9 @@@ class ChatLLM
Parsed ``LLMResponse``.
"""
accumulated = None
++ cancelled = False
++ cancelled_usage = None
++ interrupted = None
try:
available = offered_tools(tools) if tools else []
llm = self._llm.bind_tools(available) if available else self._llm
@@@ -522,45 -522,45 +526,46 @@@
possible_dsml_text = True
cancelled = False
cancelled_usage = None
- last_chunk_ts = _time.monotonic()
- for chunk in llm.stream(messages, config=config, **call_kwargs):
- now = _time.monotonic()
- if idle_timeout_s and now - last_chunk_ts > idle_timeout_s:
- # No delta for too long: the provider is stalled, not
- # thinking. Raising a bare TimeoutError lets the wrapper
- # below convert it into a retryable ProviderStreamError.
- raise TimeoutError(
- f"no stream delta for {idle_timeout_s:.0f}s"
- )
- last_chunk_ts = now
- if should_cancel and should_cancel():
- cancelled = True
- # This chunk already arrived. Preserve any reported usage
- # while still dropping its text and tool-call deltas.
- if getattr(chunk, "usage_metadata", None):
- usage_chunk = chunk if accumulated is None else accumulated + chunk
- cancelled_usage = usage_chunk.usage_metadata
- break
- if getattr(chunk, "additional_kwargs", {}).get("provider_waiting") is True and on_waiting_chunk:
- on_waiting_chunk()
- chunk_text = _text_content(chunk.content)
- if chunk_text and on_text_chunk:
- if possible_dsml_text:
- pending_text += chunk_text
- if _is_possible_dsml_tool_call_prefix(pending_text):
- pass
+ interrupted: Optional["StreamInterrupted"] = None
+ stream_chunks = supervised_pulls(
+ llm.stream(messages, config=config, **call_kwargs),
+ idle_timeout_s=idle_timeout_s,
+ total_timeout_s=timeout,
+ should_cancel=should_cancel,
+ )
- for chunk in stream_chunks:
- if should_cancel and should_cancel():
- cancelled = True
- # This chunk already arrived. Preserve any reported usage
- # while still dropping its text and tool-call deltas.
- if getattr(chunk, "usage_metadata", None):
- usage_chunk = chunk if accumulated is None else accumulated + chunk
- cancelled_usage = usage_chunk.usage_metadata
- break
- if getattr(chunk, "additional_kwargs", {}).get("provider_waiting") is True and on_waiting_chunk:
- on_waiting_chunk()
- chunk_text = _text_content(chunk.content)
- if chunk_text and on_text_chunk:
- if possible_dsml_text:
- pending_text += chunk_text
- if _is_possible_dsml_tool_call_prefix(pending_text):
- pass
++ with closing(stream_chunks):
++ for chunk in stream_chunks:
++ if should_cancel and should_cancel():
++ cancelled = True
++ # This chunk already arrived. Preserve any reported usage
++ # while still dropping its text and tool-call deltas.
++ if getattr(chunk, "usage_metadata", None):
++ usage_chunk = chunk if accumulated is None else accumulated + chunk
++ cancelled_usage = usage_chunk.usage_metadata
++ break
++ if getattr(chunk, "additional_kwargs", {}).get("provider_waiting") is True and on_waiting_chunk:
++ on_waiting_chunk()
++ chunk_text = _text_content(chunk.content)
++ if chunk_text and on_text_chunk:
++ if possible_dsml_text:
++ pending_text += chunk_text
++ if _is_possible_dsml_tool_call_prefix(pending_text):
++ pass
++ else:
++ possible_dsml_text = False
++ on_text_chunk(pending_text)
++ pending_text = ""
else:
-- possible_dsml_text = False
-- on_text_chunk(pending_text)
-- pending_text = ""
-- else:
-- on_text_chunk(chunk_text)
-- reasoning = getattr(chunk, "additional_kwargs", {}).get("reasoning_content")
-- if reasoning and not chunk.content and on_reasoning_chunk:
-- on_reasoning_chunk(reasoning)
-- accumulated = chunk if accumulated is None else accumulated + chunk
++ on_text_chunk(chunk_text)
++ reasoning = getattr(chunk, "additional_kwargs", {}).get("reasoning_content")
++ if reasoning and not chunk.content and on_reasoning_chunk:
++ on_reasoning_chunk(reasoning)
++ accumulated = chunk if accumulated is None else accumulated + chunk
if accumulated is None:
- if cancelled:
+ if cancelled or interrupted is not None:
+ # Stopping is not a compatibility case: falling back to a
+ # plain invoke here would resend the request the caller
+ # just asked to abandon.
return LLMResponse(
content="", tool_calls=[], finish_reason="stop",
usage_metadata=cancelled_usage,
@@@ -586,8 -586,31 +591,32 @@@
if pending_text and not (response.has_tool_calls and response.content == ""):
on_text_chunk(pending_text)
return response
+ except StreamInterrupted as stop:
+ interrupted = stop
+ if stop.reason == "cancelled":
+ # A user stop is not an outage. Hand back whatever arrived
+ # rather than raising, and never fall back to a second request.
+ if cancelled_usage is None and getattr(stop.pending, "usage_metadata", None):
+ cancelled_usage = stop.pending.usage_metadata
+ response = (
+ self._parse_response(accumulated)
+ if accumulated is not None
+ else LLMResponse(content="", tool_calls=[], finish_reason="stop")
+ )
+ if cancelled_usage is not None:
+ response.usage_metadata = cancelled_usage
+ return response
+ _cfg = get_env_config()
+ provider = _cfg.llm.langchain_provider.strip().lower() or "openai"
+ model = self.model_name or _cfg.llm.langchain_model_name.strip() or "(unset)"
+ raise ProviderStreamError(
+ provider=provider, model=model,
+ original=TimeoutError(f"provider stream stopped: {stop.reason}"),
+ usage_metadata=getattr(accumulated, "usage_metadata", None),
+ ) from stop
except Exception as exc:
- if _is_no_stream_chunk_error(exc):
- if _is_no_stream_chunk_error(exc) and interrupted is None and not cancelled:
++ if (_is_no_stream_chunk_error(exc) and accumulated is None
++ and interrupted is None and not cancelled):
# Provider streamed zero chunks (endpoint lacks real SSE); a
# non-streaming invoke still returns a valid response.
logger.warning(
diff --cc agent/src/providers/stream_guard.py
index 000000000,ea9462035..d913c1de8
mode 000000,100644..100644
--- a/agent/src/providers/stream_guard.py
+++ b/agent/src/providers/stream_guard.py
@@@ -1,0 -1,167 +1,202 @@@
+ """Supervise a provider stream whose next chunk may never arrive.
+
+ A synchronous provider iterator blocks inside ``next()`` while the wire is
+ silent, so a caller that polls a timeout or a cancel flag *after* each chunk
+ never gets to poll at all. This races the pull against the idle deadline, the
-total deadline and a cancel predicate, and when that race is lost it closes the
-iterator before reporting the interruption.
++total deadline and a cancel predicate, and requests iterator cleanup when the
++wait is interrupted.
+
-Closing is the point. Abandoning the pull and returning would leave the
-transport open and make the caller believe the stream stopped when only its
-consumer did.
++Closing is best effort for a synchronous iterator already inside next(). The
++caller stops waiting promptly; the pull thread closes a busy iterator when it
++returns. Adapters remain responsible for bounding their underlying socket I/O.
+ """
+
+ from __future__ import annotations
+
++import contextvars
++import inspect
+ import queue
+ import threading
+ import time
+ from typing import Any, Callable, Iterator, Optional
+
+ #: Sentinel for "the iterator is exhausted".
+ _EXHAUSTED = object()
+
+ #: How long a close is given to take effect before it is left to the adapter.
+ _CLOSE_JOIN_SECONDS = 2.0
+
+
+ class StreamInterrupted(Exception):
+ """A stream was stopped before it delivered a usable answer.
+
+ Carries the reason so the caller can tell a user stop from a stall, and
+ whether any partial output was already handed out, because that decides
+ whether a fallback request would replay a turn the user has already seen.
+ """
+
+ def __init__(self, reason: str, *, emitted: bool = False, pending: Any = None) -> None:
+ super().__init__(reason)
+ self.reason = reason
+ self.emitted = emitted
+ #: A chunk the provider had already produced when the stream stopped.
+ #: Its usage was billed, so the caller keeps it even though its text
+ #: and tool calls are dropped.
+ self.pending = pending
+
+
+ class _Puller:
+ """Move items off a blocking iterator one at a time onto a queue."""
+
+ def __init__(self, iterator: Iterator[Any], out: "queue.Queue[Any]") -> None:
+ self._iterator = iterator
+ self._out = out
+ self._stop = threading.Event()
- self._thread = threading.Thread(target=self._run, daemon=True, name="stream-pull")
++ self._close_lock = threading.Lock()
++ self._closed = False
++ context = contextvars.copy_context()
++ self._thread = threading.Thread(
++ target=context.run, args=(self._run,), daemon=True, name="stream-pull"
++ )
+ self._thread.start()
+
+ def _run(self) -> None:
- while not self._stop.is_set():
- try:
- item = next(self._iterator)
- except StopIteration:
- self._put(_EXHAUSTED)
- return
- except BaseException as exc: # noqa: BLE001 - forwarded to the caller
- self._put(exc)
++ try:
++ while not self._stop.is_set():
++ try:
++ item = next(self._iterator)
++ except StopIteration:
++ self._put(_EXHAUSTED)
++ return
++ except BaseException as exc: # noqa: BLE001 - forwarded to caller
++ self._put(exc)
++ return
++ self._put(item)
++ finally:
++ # A busy generator rejects cross-thread close(). Once next() returns,
++ # this owning thread can release it, even after the caller has left.
++ self._close_once()
++
++ def _close_once(self) -> None:
++ with self._close_lock:
++ if self._closed:
+ return
- self._put(item)
++ close = getattr(self._iterator, "close", None)
++ if callable(close):
++ try:
++ close()
++ except BaseException:
++ return
++ self._closed = True
+
+ def _put(self, item: Any) -> None:
- try:
- self._out.put(item, timeout=1.0)
- except queue.Full:
- return
++ # Backpressure must never discard text, usage, errors or EOF. Polling
++ # permits cancellation while a slow consumer leaves the slot occupied.
++ while not self._stop.is_set():
++ try:
++ self._out.put(item, timeout=0.05)
++ return
++ except queue.Full:
++ continue
+
+ def stop(self) -> None:
+ self._stop.set()
+
+ def close_iterator(self) -> None:
+ """Close the underlying iterator, bounded so a busy generator cannot hang us."""
- close = getattr(self._iterator, "close", None)
- if not callable(close):
++ # Never close a generator concurrently with its owner. Besides raising
++ # "generator already executing", concurrent finalization is unsafe in
++ # some Python runtimes. The owner closes it in _run's finally block.
++ if inspect.isgenerator(self._iterator) or self._closed:
+ return
- # A generator that is mid-execution cannot be closed from here; that is
- # a limitation of the synchronous iterator protocol, not a decision to
- # leave the transport open, so it is attempted and bounded either way.
++ if not callable(getattr(self._iterator, "close", None)):
++ return
++ # Custom adapters may expose a close that unblocks next(). Bound that
++ # operation too; the caller must not hang inside adapter cleanup.
+ done = threading.Event()
+
+ def _attempt() -> None:
+ try:
- close()
++ self._close_once()
+ except BaseException: # noqa: BLE001 - best effort release
+ pass
+ finally:
+ done.set()
+
+ worker = threading.Thread(target=_attempt, daemon=True, name="stream-close")
+ worker.start()
+ done.wait(_CLOSE_JOIN_SECONDS)
+
+
+ def supervised_pulls(
+ iterator: Iterator[Any],
+ *,
+ idle_timeout_s: Optional[float] = None,
+ total_timeout_s: Optional[float] = None,
+ should_cancel: Optional[Callable[[], bool]] = None,
+ poll_interval_s: float = 0.05,
+ ) -> Iterator[Any]:
+ """Yield items while the stream can still make progress.
+
+ Raises :class:`StreamInterrupted` when the idle deadline passes with no
+ chunk, the total deadline expires, or ``should_cancel`` turns true. The
- iterator is closed before the exception leaves, and any item that was
- already queued is discarded rather than delivered late.
++ iterator receives a bounded cleanup attempt; a busy generator is closed
++ by its owning thread when next() returns. Queued late text is not emitted.
+ """
+ if idle_timeout_s is None and total_timeout_s is None and should_cancel is None:
+ yield from iterator
+ return
+
+ out: "queue.Queue[Any]" = queue.Queue(maxsize=1)
++ if should_cancel is not None and should_cancel():
++ raise StreamInterrupted("cancelled")
+ puller = _Puller(iterator, out)
+ started = time.monotonic()
+ last_chunk = started
+ emitted = False
+
+ def interrupt(reason: str) -> StreamInterrupted:
+ # Take whatever the provider already produced: it was billed, so its
+ # usage belongs on the response even though its text is dropped.
+ try:
+ pending = out.get_nowait()
+ except queue.Empty:
+ pending = None
+ if pending is _EXHAUSTED or isinstance(pending, BaseException):
+ pending = None
+ return StreamInterrupted(reason, emitted=emitted, pending=pending)
+
+ try:
+ while True:
+ now = time.monotonic()
+ remaining: Optional[float] = None
+ if idle_timeout_s is not None:
+ remaining = max(0.0, idle_timeout_s - (now - last_chunk))
+ if total_timeout_s is not None:
+ budget = max(0.0, total_timeout_s - (now - started))
+ remaining = budget if remaining is None else min(remaining, budget)
+ if remaining is not None and remaining <= 0:
- raise interrupt("idle timeout" if idle_timeout_s is not None else "total timeout")
++ total_expired = total_timeout_s is not None and now - started >= total_timeout_s
++ raise interrupt("total timeout" if total_expired else "idle timeout")
+ wait = poll_interval_s if remaining is None else min(poll_interval_s, remaining)
+ try:
+ item = out.get(timeout=wait)
+ except queue.Empty:
+ # Nothing arrived in this window, so the only thing that can
+ # still make progress is stopping. A chunk that has already
+ # arrived is always preferred, because it was already billed
+ # and the consumer keeps its usage even while dropping text.
+ if should_cancel is not None and should_cancel():
+ raise interrupt("cancelled")
+ continue
+ if item is _EXHAUSTED:
+ return
+ if isinstance(item, BaseException):
+ raise item
- last_chunk = time.monotonic()
+ emitted = True
+ yield item
++ # Time spent in the consumer is not provider silence.
++ last_chunk = time.monotonic()
+ finally:
+ puller.stop()
+ puller.close_iterator()
diff --cc agent/tests/test_chat_stream_interruption.py
index 000000000,a0b996495..7a4a6e19c
mode 000000,100644..100644
--- a/agent/tests/test_chat_stream_interruption.py
+++ b/agent/tests/test_chat_stream_interruption.py
@@@ -1,0 -1,184 +1,253 @@@
+ """A silent provider stream must be interruptible and must release its transport.
+
+ The old loop checked the idle timeout and the cancel predicate only *after* a
+ chunk arrived, so a provider that stopped sending held the caller forever and a
+ stop request could not reach it. These tests pin the supervision contract: the
+ wait for the next chunk is raced against the deadline and the cancel signal,
+ and stopping really closes the stream rather than abandoning a thread.
+ """
+
+ from __future__ import annotations
+
+ import threading
+ import time
+ from typing import Any
+
+ import pytest
+
+ from src.providers.chat import ChatLLM
+
+
+ class _Chunk:
+ def __init__(self, content: str = "", finish_reason: str = "stop") -> None:
+ self.content = content
+ self.tool_calls: list[dict[str, Any]] = []
+ self.additional_kwargs: dict[str, Any] = {}
+ self.response_metadata = {"finish_reason": finish_reason}
+ self.usage_metadata = None
+
+ def __add__(self, other: "_Chunk") -> "_Chunk":
+ return _Chunk(self.content + other.content, other.response_metadata.get("finish_reason", "stop"))
+
+
+ class _SilentStream:
+ """A stream whose first chunk only arrives when the test releases it."""
+
+ def __init__(self, *, chunk: _Chunk | None = None, hold: float = 3.0) -> None:
+ self.chunk = chunk
+ self.hold = hold
+ self.closed = False
+ self.close_count = 0
+ self.released = threading.Event()
+
+ def __iter__(self):
+ return self
+
+ def __next__(self) -> _Chunk:
+ if self.closed:
+ raise StopIteration
+ if not self.released.wait(self.hold):
+ raise StopIteration
+ if self.closed:
+ raise StopIteration
+ if self.chunk is None:
+ raise StopIteration
+ chunk, self.chunk = self.chunk, None
+ return chunk
+
+ def close(self) -> None:
+ self.closed = True
+ self.close_count += 1
+ self.released.set()
+
+
+ class _FakeLLM:
+ def __init__(self, stream: _SilentStream) -> None:
+ self.stream_obj = stream
+ self.invoke_called = 0
+
+ def bind_tools(self, tools):
+ return self
+
+ def stream(self, messages, config=None, **kwargs):
+ return self.stream_obj
+
+ def invoke(self, messages, config=None, **kwargs):
+ self.invoke_called += 1
+ return _Chunk("fallback")
+
+
+ def _client(stream: _SilentStream) -> ChatLLM:
+ client = ChatLLM.__new__(ChatLLM)
+ client.model_name = "fake"
+ client._llm = _FakeLLM(stream)
+ return client
+
+
+ def test_idle_timeout_interrupts_a_silent_stream() -> None:
+ stream = _SilentStream()
+ started = time.monotonic()
+
+ with pytest.raises(Exception):
+ _client(stream).stream_chat(
+ [{"role": "user", "content": "hi"}],
+ idle_timeout_s=0.15,
+ )
+
+ assert time.monotonic() - started < 5
+ assert stream.closed, "the stream must be closed, not merely abandoned"
+
+
+ def test_cancel_interrupts_a_silent_stream() -> None:
+ stream = _SilentStream()
+ cancel = threading.Event()
+ threading.Timer(0.15, cancel.set).start()
+ started = time.monotonic()
+
+ response = _client(stream).stream_chat(
+ [{"role": "user", "content": "hi"}],
+ should_cancel=cancel.is_set,
+ )
+
+ assert time.monotonic() - started < 5
+ assert stream.closed
+ assert response.content == ""
+
+
+ def test_total_timeout_interrupts_a_silent_stream() -> None:
+ stream = _SilentStream()
+ started = time.monotonic()
+
+ with pytest.raises(Exception):
+ _client(stream).stream_chat(
+ [{"role": "user", "content": "hi"}],
+ timeout=1,
+ )
+
+ assert time.monotonic() - started < 5
+ assert stream.closed
+
+
+ def test_no_replay_after_an_interrupted_stream() -> None:
+ """A cancelled or timed-out stream must not fall back and resend the request."""
+ stream = _SilentStream()
+ client = _client(stream)
+ cancel = threading.Event()
+ threading.Timer(0.1, cancel.set).start()
+
+ client.stream_chat([{"role": "user", "content": "hi"}], should_cancel=cancel.is_set)
+
+ assert client._llm.invoke_called == 0
+
+
+ def test_no_replay_after_partial_output() -> None:
+ """Once text has been emitted a fallback invoke would replay the turn."""
+ stream = _SilentStream(chunk=_Chunk("partial"))
+ client = _client(stream)
+
+ with pytest.raises(Exception):
+ client.stream_chat(
+ [{"role": "user", "content": "hi"}],
+ on_text_chunk=lambda text: None,
+ idle_timeout_s=0.2,
+ )
+
+ assert client._llm.invoke_called == 0
+
+
+ def test_a_late_chunk_after_cancel_never_reaches_the_caller() -> None:
+ stream = _SilentStream()
+ client = _client(stream)
+ cancel = threading.Event()
+ threading.Timer(0.1, cancel.set).start()
+ seen: list[str] = []
+
+ client.stream_chat(
+ [{"role": "user", "content": "hi"}],
+ on_text_chunk=seen.append,
+ should_cancel=cancel.is_set,
+ )
+ stream.released.set()
+ time.sleep(0.2)
+
+ assert seen == []
+
+
+ def test_a_delivered_stream_still_reports_its_answer() -> None:
+ stream = _SilentStream(chunk=_Chunk("hello"))
+ stream.released.set()
+ client = _client(stream)
+
+ response = client.stream_chat([{"role": "user", "content": "hi"}], idle_timeout_s=5)
+
+ assert response.content == "hello"
+ assert client._llm.invoke_called == 0
++
++
++def test_slow_consumer_preserves_every_chunk_and_eof():
++ from src.providers.stream_guard import supervised_pulls
++
++ chunks = supervised_pulls(iter(range(4)), idle_timeout_s=0.2)
++ assert next(chunks) == 0
++ time.sleep(1.2) # Exceeds the old queue put timeout and idle threshold.
++ assert list(chunks) == [1, 2, 3]
++
++
++def test_pull_thread_keeps_session_context():
++ import contextvars
++ from src.providers.stream_guard import supervised_pulls
++
++ session = contextvars.ContextVar("test_stream_session", default=None)
++ token = session.set("session-123")
++ try:
++ def stream():
++ yield session.get()
++ assert list(supervised_pulls(stream(), idle_timeout_s=1)) == ["session-123"]
++ finally:
++ session.reset(token)
++
++
++def test_busy_generator_is_closed_when_pending_pull_returns():
++ from src.providers.stream_guard import StreamInterrupted, supervised_pulls
++
++ released, closed = threading.Event(), threading.Event()
++ def stream():
++ try:
++ released.wait(2)
++ yield "late"
++ finally:
++ closed.set()
++ try:
++ with pytest.raises(StreamInterrupted, match="idle timeout"):
++ list(supervised_pulls(stream(), idle_timeout_s=0.05))
++ finally:
++ released.set()
++ assert closed.wait(2)
++
++
++def test_consumer_exception_closes_stream():
++ stream = _SilentStream(chunk=_Chunk("hello"))
++ stream.released.set()
++ def fail(text):
++ raise RuntimeError("consumer failed")
++ with pytest.raises(Exception, match="consumer failed"):
++ _client(stream).stream_chat([], idle_timeout_s=1, on_text_chunk=fail)
++ assert stream.closed
++
++
++def test_partial_stream_no_chunk_error_never_replays():
++ from langchain_core.messages import AIMessageChunk
++ class Provider:
++ invoke_called = False
++ def stream(self, *args, **kwargs):
++ yield AIMessageChunk(content="partial")
++ raise ValueError("No generation chunks were returned")
++ def invoke(self, *args, **kwargs):
++ self.invoke_called = True
++ return AIMessageChunk(content="replayed")
++ provider = Provider()
++ client = _client(_SilentStream())
++ client._llm = provider
++ with pytest.raises(Exception):
++ client.stream_chat([], idle_timeout_s=1)
++ assert not provider.invoke_called