Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 14 additions & 6 deletions agentdock/stream_buffer.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ def __init__(self, emit, interval=0.1, max_bytes=16384):
self.parts = []
self.size = 0
self.timer = None
self._timer_generation = 0
self.failure = None

def push(self, kind, payload):
Expand Down Expand Up @@ -44,15 +45,22 @@ def push(self, kind, payload):
if self.size >= self.max_bytes:
self.flush()
elif self.timer is None:
self.timer = threading.Timer(self.interval, self._tick)
self._timer_generation += 1
generation = self._timer_generation
self.timer = threading.Timer(
self.interval, lambda: self._tick(generation)
)
self.timer.daemon = True
self.timer.start()

def _tick(self):
try:
self.flush()
except Exception as error:
with self.lock:
def _tick(self, generation):
with self.lock:
# A cancelled timer may already be waiting to acquire this lock.
if self.timer is None or generation != self._timer_generation:
return
try:
self.flush()
except Exception as error:
self.failure = error

def flush(self):
Expand Down
34 changes: 34 additions & 0 deletions tests/test_stream_buffer.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import threading
import unittest
from unittest.mock import Mock, patch

from agentdock.stream_buffer import StreamBuffer

Expand Down Expand Up @@ -37,3 +38,36 @@ def test_last_delta_is_visible_without_waiting_for_another_event(self):
buffer.push("reasoning_chunk", {"text": "A visible progress summary"})
self.assertTrue(received.wait(0.5))
buffer.close()

def test_stale_timer_does_not_flush_replacement_batch(self):
events = []
with patch("agentdock.stream_buffer.threading.Timer") as timer_factory:
first, second = Mock(), Mock()
timer_factory.side_effect = [first, second]
buffer = StreamBuffer(lambda *args: events.append(args))
buffer.push("reasoning_chunk", {"text": "first"})
old_callback = timer_factory.call_args.args[1]
buffer.push("tool_call", {"name": "fixture"})
first.cancel.assert_called_once()
buffer.push("reasoning_chunk", {"text": "second"})
new_callback = timer_factory.call_args.args[1]

# Simulate a callback already dispatched before cancellation.
old_callback()
self.assertEqual(
events,
[
("reasoning_chunk", {"text": "first"}),
("tool_call", {"name": "fixture"}),
],
)
second.cancel.assert_not_called()
self.assertIs(buffer.timer, second)
buffer.push("reasoning_chunk", {"text": " batch"})
new_callback()
buffer.close()
self.assertEqual(
events[-1], ("reasoning_chunk", {"text": "second batch"})
)
self.assertEqual(len(events), 3)
self.assertEqual(timer_factory.call_count, 2)