Skip to content

Commit a36d928

Browse files
committed
fix: enforce the sync monitor timeout
monitor_operation's timeout was never applied, because connect() blocks until the stream ends. A timer now closes the stream at the timeout and the call raises TimeoutError. A close during a reconnect backoff no longer reopens the stream.
1 parent 05cfe00 commit a36d928

3 files changed

Lines changed: 84 additions & 4 deletions

File tree

‎robosystems_client/clients/operation_client.py‎

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55

66
import asyncio
77
import logging
8+
import threading
89
from dataclasses import dataclass
910
from typing import Dict, Any, Optional, Callable, List, cast
1011
from datetime import datetime
@@ -67,7 +68,7 @@ class MonitorOptions:
6768

6869
on_progress: Optional[Callable[[OperationProgress], None]] = None
6970
on_queue_update: Optional[Callable[[int, int], None]] = None
70-
timeout: Optional[int] = None
71+
timeout: Optional[float] = None # seconds
7172
poll_interval: Optional[int] = None
7273

7374

@@ -132,8 +133,6 @@ def __init__(self, config: Dict[str, Any]):
132133
self.headers["X-API-Key"] = self.token
133134
self.active_operations: Dict[str, SSEClient] = {}
134135
# Thread safety for operations tracking
135-
import threading
136-
137136
self._lock = threading.Lock()
138137

139138
def monitor_operation(
@@ -225,13 +224,31 @@ def on_connection_error(err):
225224
sse_client.on("error", on_connection_error)
226225
sse_client.on("max_retries_exceeded", on_connection_error)
227226

227+
# connect() blocks, so the timeout closes the stream from a timer thread,
228+
# which ends the read and returns control here.
229+
timed_out = threading.Event()
230+
231+
def on_timeout():
232+
timed_out.set()
233+
sse_client.close()
234+
235+
timer = threading.Timer(options.timeout, on_timeout) if options.timeout else None
236+
228237
# Connect and monitor. Registered first so cancel_operation() can close
229238
# the stream; connect() blocks until the stream ends (or never opens).
230239
try:
231240
with self._lock:
232241
self.active_operations[operation_id] = sse_client
242+
if timer:
243+
timer.daemon = True
244+
timer.start()
233245
sse_client.connect(operation_id)
234246

247+
if not completed and timed_out.is_set():
248+
raise TimeoutError(
249+
f"Operation {operation_id} timed out after {options.timeout}s"
250+
)
251+
235252
if not completed:
236253
# The stream ended without a terminal event: no verdict to report,
237254
# and nothing left to wait on.
@@ -240,6 +257,8 @@ def on_connection_error(err):
240257
)
241258

242259
finally:
260+
if timer:
261+
timer.cancel()
243262
# Clean up with thread safety
244263
with self._lock:
245264
if operation_id in self.active_operations:

‎robosystems_client/clients/sse_client.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -268,6 +268,10 @@ def _handle_error(
268268

269269
time.sleep(delay_seconds)
270270

271+
# A close() during the backoff ends the reconnect.
272+
if self.closed:
273+
return
274+
271275
# Resume from last event if available
272276
resume_from = 0
273277
if self.last_event_id:

‎tests/test_operation_client_ops.py‎

Lines changed: 58 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,9 @@
77
Dataclass and enum tests already exist in tests/test_operation_client.py.
88
"""
99

10+
import threading
11+
import time
12+
1013
import pytest
1114
from unittest.mock import Mock, patch, MagicMock
1215
from robosystems_client.clients.operation_client import (
@@ -15,7 +18,7 @@
1518
OperationProgress,
1619
MonitorOptions,
1720
)
18-
from robosystems_client.clients.sse_client import SSEClient
21+
from robosystems_client.clients.sse_client import SSEClient, SSEConfig
1922
from robosystems_client.models.cancel_operation_response_canceloperation import (
2023
CancelOperationResponseCanceloperation,
2124
)
@@ -238,6 +241,60 @@ def fake_connect(op_id):
238241
# SSE client should have been closed
239242
fake_sse.close.assert_called()
240243

244+
@patch("robosystems_client.clients.operation_client.SSEClient")
245+
def test_monitor_timeout_closes_a_silent_stream(self, MockSSE, mock_config):
246+
"""A stream with no terminal event is closed at `timeout` and raises."""
247+
fake_sse = MagicMock(spec=SSEClient)
248+
closed = threading.Event()
249+
250+
# connect() blocks until the stream is closed, like a live stream would.
251+
fake_sse.connect.side_effect = lambda op_id: closed.wait(5)
252+
fake_sse.close.side_effect = closed.set
253+
MockSSE.return_value = fake_sse
254+
255+
client = OperationClient(mock_config)
256+
started = time.monotonic()
257+
with pytest.raises(TimeoutError, match="timed out after 0.1s"):
258+
client.monitor_operation("op-silent", MonitorOptions(timeout=0.1))
259+
260+
assert time.monotonic() - started < 2
261+
assert "op-silent" not in client.active_operations
262+
263+
@patch("robosystems_client.clients.operation_client.SSEClient")
264+
def test_monitor_completion_beats_timeout(self, MockSSE, mock_config):
265+
"""A run that finishes inside `timeout` returns its result."""
266+
fake_sse = MagicMock(spec=SSEClient)
267+
listeners = {}
268+
fake_sse.on.side_effect = lambda event, handler: listeners.__setitem__(
269+
event, handler
270+
)
271+
fake_sse.connect.side_effect = lambda op_id: listeners["operation_completed"](
272+
{"result": {"ok": True}}
273+
)
274+
MockSSE.return_value = fake_sse
275+
276+
client = OperationClient(mock_config)
277+
result = client.monitor_operation("op-fast", MonitorOptions(timeout=5))
278+
279+
assert result.status == OperationStatus.COMPLETED
280+
assert result.result == {"ok": True}
281+
282+
283+
@pytest.mark.unit
284+
class TestSSEReconnect:
285+
"""Test SSEClient's reconnect backoff."""
286+
287+
@patch("robosystems_client.clients.sse_client.time.sleep")
288+
def test_close_during_backoff_ends_the_reconnect(self, mock_sleep):
289+
"""A close() while the reconnect sleeps must not reopen the stream."""
290+
sse = SSEClient(SSEConfig(base_url="http://localhost:8000", max_retries=3))
291+
mock_sleep.side_effect = lambda _s: setattr(sse, "closed", True)
292+
293+
with patch.object(sse, "connect") as mock_connect:
294+
sse._handle_error(RuntimeError("dropped"), "op-1", 0)
295+
296+
mock_connect.assert_not_called()
297+
241298

242299
# ── get_operation_status ─────────────────────────────────────────────
243300

0 commit comments

Comments
 (0)