From 01847f1fc34ad1b77d1ff8887d95e6001ebed3ba Mon Sep 17 00:00:00 2001 From: VascoSch92 Date: Thu, 27 Aug 2026 19:41:51 +0200 Subject: [PATCH 1/2] fix(agent-server): stop fanning streaming deltas out to every subscriber StreamingDeltaEvent is published straight to the conversation PubSub, which notified every subscriber with no kind filter. Consumers sized for conversation events therefore received traffic proportional to tokens: WebhookSubscriber POSTed each delta to the configured endpoint, and TelemetrySubscriber counted each one into event_count_bucket. Make delta delivery opt-in on the Subscriber base class and consult it in PubSub.__call__. The live WebSocket - the one consumer token streaming exists for - opts in; everything else, including subscribers added later, is excluded by default. Fixes #4672 Fixes #4673 --- .../openhands/agent_server/pub_sub.py | 19 ++++++++- .../openhands/agent_server/sockets.py | 4 ++ .../telemetry/test_telemetry_subscriber.py | 25 +++++++++++- tests/agent_server/test_event_streaming.py | 40 ++++++++++++++++++- tests/agent_server/test_webhook_subscriber.py | 35 +++++++++++++++- 5 files changed, 118 insertions(+), 5 deletions(-) diff --git a/openhands-agent-server/openhands/agent_server/pub_sub.py b/openhands-agent-server/openhands/agent_server/pub_sub.py index ed6802f0052..d3539622f4a 100644 --- a/openhands-agent-server/openhands/agent_server/pub_sub.py +++ b/openhands-agent-server/openhands/agent_server/pub_sub.py @@ -1,9 +1,10 @@ import asyncio from abc import ABC, abstractmethod from dataclasses import dataclass, field -from typing import TypeVar +from typing import ClassVar, TypeVar from uuid import UUID, uuid4 +from openhands.sdk.event import StreamingDeltaEvent from openhands.sdk.logger import get_logger @@ -13,6 +14,13 @@ class Subscriber[T](ABC): + # Streaming deltas arrive at token rate and are transport-only: they are + # published straight to the bus and never persisted to + # ConversationState.events. Consumers sized for conversation events opt in + # explicitly, so a subscriber added later cannot inherit that traffic -- + # and the content it carries -- by default. + receives_streaming_deltas: ClassVar[bool] = False + @abstractmethod async def __call__(self, event: T): """Invoke this subscriber""" @@ -83,10 +91,17 @@ async def __call__(self, event: T) -> None: Subscribers are notified concurrently so a slow client cannot block delivery to others. Each callback runs in its own error-handling wrapper to preserve fault isolation. + Streaming deltas go only to subscribers that set + ``receives_streaming_deltas``; see :class:`Subscriber`. Args: event: The event to pass to all callbacks """ - subscribers = list(self._subscribers.items()) + is_delta = isinstance(event, StreamingDeltaEvent) + subscribers = [ + (subscriber_id, subscriber) + for subscriber_id, subscriber in self._subscribers.items() + if subscriber.receives_streaming_deltas or not is_delta + ] if not subscribers: return diff --git a/openhands-agent-server/openhands/agent_server/sockets.py b/openhands-agent-server/openhands/agent_server/sockets.py index 6640e8c3dea..e333655c939 100644 --- a/openhands-agent-server/openhands/agent_server/sockets.py +++ b/openhands-agent-server/openhands/agent_server/sockets.py @@ -539,6 +539,10 @@ def _is_websocket_connected(websocket: WebSocket) -> bool: class _WebSocketSubscriber(Subscriber): """WebSocket subscriber for conversation events.""" + # The live socket is what token streaming is for: this is the one consumer + # that wants deltas. + receives_streaming_deltas = True + websocket: WebSocket async def __call__(self, event: Event): diff --git a/tests/agent_server/telemetry/test_telemetry_subscriber.py b/tests/agent_server/telemetry/test_telemetry_subscriber.py index 4d1295c37fb..abc4b76a88d 100644 --- a/tests/agent_server/telemetry/test_telemetry_subscriber.py +++ b/tests/agent_server/telemetry/test_telemetry_subscriber.py @@ -13,7 +13,11 @@ ConversationTelemetryContext, TelemetrySubscriber, ) -from openhands.sdk.event import AgentErrorEvent, ConversationStateUpdateEvent +from openhands.sdk.event import ( + AgentErrorEvent, + ConversationStateUpdateEvent, + StreamingDeltaEvent, +) from openhands.sdk.event.conversation_error import ConversationErrorEvent from openhands.sdk.event.error_classification import ErrorClassification, FailureKind @@ -660,3 +664,22 @@ def test_is_automation_is_derived_from_allowlisted_tags(tags, is_automation): ) assert context.is_automation is is_automation + + +async def test_event_count_ignores_streaming_deltas(factory): + """``event_count_bucket`` must mean the same thing with streaming on or off. + + The counter is incremented for every event the subscriber sees, and the + subscriber shares the bus that carries token deltas -- so the bucket used to + scale with model verbosity rather than conversation activity, making a + streamed and a non-streamed conversation incomparable. + """ + sink = CollectingSink() + sub = make_subscriber(sink, factory) + pub_sub: PubSub = PubSub() + pub_sub.subscribe(sub) + + for _ in range(50): + await pub_sub(StreamingDeltaEvent(content="tok")) + + assert sub._event_count == 0 diff --git a/tests/agent_server/test_event_streaming.py b/tests/agent_server/test_event_streaming.py index caab441261a..91cb60b00c5 100644 --- a/tests/agent_server/test_event_streaming.py +++ b/tests/agent_server/test_event_streaming.py @@ -33,7 +33,22 @@ def _make_chunk( class _CollectorSubscriber(Subscriber): - """Subscriber that collects events for assertions.""" + """Subscriber that opts into deltas and collects events for assertions.""" + + receives_streaming_deltas = True + + def __init__(self): + self.events: list[Event] = [] + + async def __call__(self, event: Event): + self.events.append(event) + + async def close(self): + pass + + +class _PlainSubscriber(Subscriber): + """Subscriber that keeps the default: it must never observe a delta.""" def __init__(self): self.events: list[Event] = [] @@ -292,3 +307,26 @@ async def test_multiple_chunks_produce_multiple_events(event_service, tmp_path): delta_events = [e for e in collector.events if isinstance(e, StreamingDeltaEvent)] assert len(delta_events) == 4 assert [e.content for e in delta_events] == words + + +@pytest.mark.asyncio +async def test_deltas_only_reach_subscribers_that_opted_in(event_service, tmp_path): + """Deltas are transport-only, so the bus must not fan them out by default. + + ``StreamingDeltaEvent`` is published straight to the shared ``PubSub``, which + used to notify every subscriber with no kind filter. That handed token-rate + traffic to consumers sized for conversation events -- webhooks POSTed each + delta and telemetry counted it. Delivery is opt-in so a subscriber added + later cannot inherit the behaviour by accident. + """ + streaming = _CollectorSubscriber() + plain = _PlainSubscriber() + event_service._pub_sub.subscribe(streaming) + event_service._pub_sub.subscribe(plain) + + callback = await _start_and_capture_callback(event_service, tmp_path) + callback(_make_chunk(content="Hello")) + await asyncio.sleep(0.05) + + assert [e for e in streaming.events if isinstance(e, StreamingDeltaEvent)] + assert not [e for e in plain.events if isinstance(e, StreamingDeltaEvent)] diff --git a/tests/agent_server/test_webhook_subscriber.py b/tests/agent_server/test_webhook_subscriber.py index 2c134e127f1..b2a86757d5a 100644 --- a/tests/agent_server/test_webhook_subscriber.py +++ b/tests/agent_server/test_webhook_subscriber.py @@ -23,8 +23,10 @@ ) from openhands.agent_server.event_service import EventService from openhands.agent_server.models import StoredConversation +from openhands.agent_server.pub_sub import PubSub from openhands.agent_server.utils import utc_now -from openhands.sdk import LLM, Agent +from openhands.sdk import LLM, Agent, Event +from openhands.sdk.event import StreamingDeltaEvent from openhands.sdk.event.llm_convertible import MessageEvent from openhands.sdk.llm.message import Message, TextContent from openhands.sdk.workspace import LocalWorkspace @@ -1557,3 +1559,34 @@ async def _broken_call(self, event): usage_id="webhook-error", initial_text=None, ) + + +@pytest.mark.asyncio +async def test_streaming_deltas_never_reach_webhook( + mock_event_service, webhook_spec, sample_conversation_id +): + """A streamed response must not add a single POST over a non-streamed one. + + Webhooks subscribe to the same bus that carries ``StreamingDeltaEvent``, so + before delivery became opt-in every token was enqueued and shipped -- a + continuous POST loop for the duration of each streamed response, carrying + unmasked model text to a configured endpoint. + """ + subscriber = WebhookSubscriber( + conversation_id=sample_conversation_id, + service=mock_event_service, + spec=webhook_spec, + ) + pub_sub: PubSub[Event] = PubSub() + pub_sub.subscribe(subscriber) + + with patch.object(subscriber, "_post_events", new_callable=AsyncMock) as post: + # Comfortably past event_buffer_size: a filter that only trimmed the + # batch would still flush here. + for _ in range(webhook_spec.event_buffer_size + 2): + await pub_sub(StreamingDeltaEvent(content="tok")) + + assert subscriber.queue == [] + post.assert_not_called() + + subscriber._cancel_flush_timer() From 1f2aef96cf7f7f20dacb79bf887a75c4792a6ed3 Mon Sep 17 00:00:00 2001 From: VascoSch92 Date: Thu, 27 Aug 2026 19:47:47 +0200 Subject: [PATCH 2/2] refactor(agent-server): trim comments and narrow the delta filter Cut the explanatory comments and test docstrings down to one line each, and only rebuild the subscriber list when the event is actually a delta so the common path keeps its original behaviour. --- .../openhands/agent_server/pub_sub.py | 17 ++++---------- .../openhands/agent_server/sockets.py | 3 +-- .../telemetry/test_telemetry_subscriber.py | 8 +------ tests/agent_server/test_event_streaming.py | 22 ++++--------------- tests/agent_server/test_webhook_subscriber.py | 11 ++-------- 5 files changed, 12 insertions(+), 49 deletions(-) diff --git a/openhands-agent-server/openhands/agent_server/pub_sub.py b/openhands-agent-server/openhands/agent_server/pub_sub.py index d3539622f4a..080113f42f5 100644 --- a/openhands-agent-server/openhands/agent_server/pub_sub.py +++ b/openhands-agent-server/openhands/agent_server/pub_sub.py @@ -14,11 +14,7 @@ class Subscriber[T](ABC): - # Streaming deltas arrive at token rate and are transport-only: they are - # published straight to the bus and never persisted to - # ConversationState.events. Consumers sized for conversation events opt in - # explicitly, so a subscriber added later cannot inherit that traffic -- - # and the content it carries -- by default. + # Deltas arrive at token rate; consumers opt in rather than inherit them. receives_streaming_deltas: ClassVar[bool] = False @abstractmethod @@ -91,17 +87,12 @@ async def __call__(self, event: T) -> None: Subscribers are notified concurrently so a slow client cannot block delivery to others. Each callback runs in its own error-handling wrapper to preserve fault isolation. - Streaming deltas go only to subscribers that set - ``receives_streaming_deltas``; see :class:`Subscriber`. Args: event: The event to pass to all callbacks """ - is_delta = isinstance(event, StreamingDeltaEvent) - subscribers = [ - (subscriber_id, subscriber) - for subscriber_id, subscriber in self._subscribers.items() - if subscriber.receives_streaming_deltas or not is_delta - ] + subscribers = list(self._subscribers.items()) + if isinstance(event, StreamingDeltaEvent): + subscribers = [s for s in subscribers if s[1].receives_streaming_deltas] if not subscribers: return diff --git a/openhands-agent-server/openhands/agent_server/sockets.py b/openhands-agent-server/openhands/agent_server/sockets.py index e333655c939..f009c3dcef4 100644 --- a/openhands-agent-server/openhands/agent_server/sockets.py +++ b/openhands-agent-server/openhands/agent_server/sockets.py @@ -539,8 +539,7 @@ def _is_websocket_connected(websocket: WebSocket) -> bool: class _WebSocketSubscriber(Subscriber): """WebSocket subscriber for conversation events.""" - # The live socket is what token streaming is for: this is the one consumer - # that wants deltas. + # The live socket is what token streaming is for. receives_streaming_deltas = True websocket: WebSocket diff --git a/tests/agent_server/telemetry/test_telemetry_subscriber.py b/tests/agent_server/telemetry/test_telemetry_subscriber.py index abc4b76a88d..e4f7e16eb95 100644 --- a/tests/agent_server/telemetry/test_telemetry_subscriber.py +++ b/tests/agent_server/telemetry/test_telemetry_subscriber.py @@ -667,13 +667,7 @@ def test_is_automation_is_derived_from_allowlisted_tags(tags, is_automation): async def test_event_count_ignores_streaming_deltas(factory): - """``event_count_bucket`` must mean the same thing with streaming on or off. - - The counter is incremented for every event the subscriber sees, and the - subscriber shares the bus that carries token deltas -- so the bucket used to - scale with model verbosity rather than conversation activity, making a - streamed and a non-streamed conversation incomparable. - """ + """Deltas must not inflate event_count_bucket (regression for #4673).""" sink = CollectingSink() sub = make_subscriber(sink, factory) pub_sub: PubSub = PubSub() diff --git a/tests/agent_server/test_event_streaming.py b/tests/agent_server/test_event_streaming.py index 91cb60b00c5..d9122e5632c 100644 --- a/tests/agent_server/test_event_streaming.py +++ b/tests/agent_server/test_event_streaming.py @@ -47,17 +47,10 @@ async def close(self): pass -class _PlainSubscriber(Subscriber): - """Subscriber that keeps the default: it must never observe a delta.""" +class _PlainSubscriber(_CollectorSubscriber): + """Collector that keeps the default: it must never observe a delta.""" - def __init__(self): - self.events: list[Event] = [] - - async def __call__(self, event: Event): - self.events.append(event) - - async def close(self): - pass + receives_streaming_deltas = False @pytest.fixture @@ -311,14 +304,7 @@ async def test_multiple_chunks_produce_multiple_events(event_service, tmp_path): @pytest.mark.asyncio async def test_deltas_only_reach_subscribers_that_opted_in(event_service, tmp_path): - """Deltas are transport-only, so the bus must not fan them out by default. - - ``StreamingDeltaEvent`` is published straight to the shared ``PubSub``, which - used to notify every subscriber with no kind filter. That handed token-rate - traffic to consumers sized for conversation events -- webhooks POSTed each - delta and telemetry counted it. Delivery is opt-in so a subscriber added - later cannot inherit the behaviour by accident. - """ + """Deltas reach only subscribers that opted in, never the rest of the bus.""" streaming = _CollectorSubscriber() plain = _PlainSubscriber() event_service._pub_sub.subscribe(streaming) diff --git a/tests/agent_server/test_webhook_subscriber.py b/tests/agent_server/test_webhook_subscriber.py index b2a86757d5a..3b57d3b39df 100644 --- a/tests/agent_server/test_webhook_subscriber.py +++ b/tests/agent_server/test_webhook_subscriber.py @@ -1565,13 +1565,7 @@ async def _broken_call(self, event): async def test_streaming_deltas_never_reach_webhook( mock_event_service, webhook_spec, sample_conversation_id ): - """A streamed response must not add a single POST over a non-streamed one. - - Webhooks subscribe to the same bus that carries ``StreamingDeltaEvent``, so - before delivery became opt-in every token was enqueued and shipped -- a - continuous POST loop for the duration of each streamed response, carrying - unmasked model text to a configured endpoint. - """ + """No StreamingDeltaEvent is enqueued or POSTed (regression for #4672).""" subscriber = WebhookSubscriber( conversation_id=sample_conversation_id, service=mock_event_service, @@ -1581,8 +1575,7 @@ async def test_streaming_deltas_never_reach_webhook( pub_sub.subscribe(subscriber) with patch.object(subscriber, "_post_events", new_callable=AsyncMock) as post: - # Comfortably past event_buffer_size: a filter that only trimmed the - # batch would still flush here. + # Past event_buffer_size: an unfiltered queue would flush here. for _ in range(webhook_spec.event_buffer_size + 2): await pub_sub(StreamingDeltaEvent(content="tok"))