Skip to content

Commit b0a9afc

Browse files
authored
fix: give up on a monitored operation at its timeout, not 30s later (#236)
## Summary Final fixes from the 2.6.0 verification pass. The main one: #234's `monitor_operation(timeout=…)` raised `TimeoutError` about 30 seconds late. Its timer closed the stream from another thread, but that does not wake a socket read that is already blocked. The read only returned when the stream's own 30-second read timeout ran out, even with the server sending keepalives. #234's tests replaced the stream with a mock, so they never touched a real socket. ## Changes - **`OperationClient.monitor_operation`:** with a `timeout`, the stream is read on a worker thread, and the caller waits on an event set by a terminal event or by the stream ending. The timeout now fires on time. A finished run returns at once, even if the server holds the socket open after the terminal event. Without a `timeout`, the call reads the stream on the calling thread as before. - **GraphQL reads (`GraphQLClient`):** the resolved token now replaces any credential in the static headers, so exactly one is sent, as the REST writes already do. Before, a static `X-API-Key` plus a `token_provider` JWT sent both headers. - **`create_report`:** `period_start` / `period_end` are annotated `str | datetime.date`, which is what they already accepted. ## Compatibility Rides in the next client release with #235. That release is a **minor** (2.7.0) because #235 adds a facade parameter. This PR changes no signatures; the annotation change only widens a type. ## Testing - **New:** `test_monitor_timeout_fires_on_time_over_a_real_socket` runs a local SSE server that holds the stream open with keepalives. `timeout=1` now raises in about 1 s; without the fix the same test fails after 31 s. - **New:** two `GraphQLClient` tests check that exactly one credential is sent. Both fail without the fix. - **`just test-all`:** 654 passed, 17 skipped; ruff, format and basedpyright are clean. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
2 parents 6774cbf + 386a2df commit b0a9afc

5 files changed

Lines changed: 104 additions & 23 deletions

File tree

‎robosystems_client/clients/ledger_client.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2503,8 +2503,8 @@ def create_report(
25032503
graph_id: str,
25042504
name: str,
25052505
mapping_id: str,
2506-
period_start: str,
2507-
period_end: str,
2506+
period_start: str | datetime.date,
2507+
period_end: str | datetime.date,
25082508
taxonomy_id: str = "rs-gaap",
25092509
period_type: str = "quarterly",
25102510
comparative: bool = True,

‎robosystems_client/clients/operation_client.py‎

Lines changed: 23 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,8 @@ def monitor_operation(
150150
result = OperationResult(operation_id=operation_id, status=OperationStatus.PENDING)
151151
completed = False
152152
error = None
153+
# Set by a terminal event, or when the stream ends without one.
154+
settled = threading.Event()
153155

154156
# Set up SSE connection with event replay from the beginning
155157
# This handles the race condition where the operation may have already completed.
@@ -189,6 +191,7 @@ def on_operation_completed(data):
189191
result.completed_at = datetime.now()
190192
result.execution_time_ms = data.get("execution_time_ms")
191193
completed = True
194+
settled.set()
192195

193196
def on_operation_error(err):
194197
nonlocal completed, error
@@ -197,12 +200,14 @@ def on_operation_error(err):
197200
result.completed_at = datetime.now()
198201
error = Exception(result.error)
199202
completed = True
203+
settled.set()
200204

201205
def on_operation_cancelled(_data=None):
202206
nonlocal completed
203207
result.status = OperationStatus.CANCELLED
204208
result.completed_at = datetime.now()
205209
completed = True
210+
settled.set()
206211

207212
def on_connection_error(err):
208213
nonlocal completed, error
@@ -211,6 +216,7 @@ def on_connection_error(err):
211216
result.completed_at = datetime.now()
212217
error = err if isinstance(err, Exception) else Exception(str(err))
213218
completed = True
219+
settled.set()
214220

215221
# Register event handlers
216222
sse_client.on(EventType.OPERATION_STARTED.value, on_operation_started)
@@ -224,30 +230,28 @@ def on_connection_error(err):
224230
sse_client.on("error", on_connection_error)
225231
sse_client.on("max_retries_exceeded", on_connection_error)
226232

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
233+
def read_stream():
234+
try:
235+
sse_client.connect(operation_id)
236+
finally:
237+
settled.set()
236238

237239
# Connect and monitor. Registered first so cancel_operation() can close
238-
# the stream; connect() blocks until the stream ends (or never opens).
240+
# the stream.
239241
try:
240242
with self._lock:
241243
self.active_operations[operation_id] = sse_client
242-
if timer:
243-
timer.daemon = True
244-
timer.start()
245-
sse_client.connect(operation_id)
246-
247-
if not completed and timed_out.is_set():
248-
raise TimeoutError(
249-
f"Operation {operation_id} timed out after {options.timeout}s"
250-
)
244+
if options.timeout:
245+
# connect() blocks on the socket, and closing the stream from another
246+
# thread does not wake that read, so the stream is read on a worker
247+
# and the timeout is kept here.
248+
threading.Thread(target=read_stream, daemon=True).start()
249+
if not settled.wait(options.timeout):
250+
raise TimeoutError(
251+
f"Operation {operation_id} timed out after {options.timeout}s"
252+
)
253+
else:
254+
read_stream()
251255

252256
if not completed:
253257
# The stream ended without a terminal event: no verdict to report,
@@ -257,8 +261,6 @@ def on_timeout():
257261
)
258262

259263
finally:
260-
if timer:
261-
timer.cancel()
262264
# Clean up with thread safety
263265
with self._lock:
264266
if operation_id in self.active_operations:

‎robosystems_client/graphql/client.py‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,14 @@ def __init__(
9090
# use cases, but we keep the routing symmetric with the TS
9191
# client so a caller that forwards a JWT (e.g. a backend
9292
# proxying a request-scoped token) still works.
93+
#
94+
# The resolved token replaces any credential the static headers carry,
95+
# as the REST writes do, so exactly one is sent.
96+
self._headers = {
97+
k: v
98+
for k, v in self._headers.items()
99+
if k.lower() not in ("x-api-key", "authorization")
100+
}
93101
if token.startswith("rfs"):
94102
self._headers["X-API-Key"] = token
95103
else:

‎tests/test_auth_header_resolution.py‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
from robosystems_client.clients.operation_client import OperationClient
1616
from robosystems_client.clients.retry import RetryingClient
1717
from robosystems_client.clients.sse_client import SSEClient, event_error_message
18+
from robosystems_client.graphql.client import GraphQLClient
1819
from robosystems_client.clients.token_utils import (
1920
apply_auth_header,
2021
resolve_auth_headers,
@@ -153,3 +154,35 @@ def test_status_call_uses_provider_credential(self, mock_config):
153154
passed = mock_get.call_args.kwargs["client"]
154155
assert passed.get_httpx_client().headers["X-API-Key"] == "rfs_fresh"
155156
assert isinstance(passed.get_httpx_client(), RetryingClient)
157+
158+
159+
@pytest.mark.unit
160+
class TestGraphQLClientCredential:
161+
"""GraphQL reads send exactly one credential, as the REST writes do."""
162+
163+
def test_resolved_jwt_replaces_a_static_api_key(self):
164+
# A facade with a static `rfs` key in its headers and a token_provider
165+
# handing out JWTs: the resolved JWT is the one sent.
166+
client = GraphQLClient(
167+
"http://localhost:8000",
168+
token="eyJ.jwt",
169+
headers={"X-API-Key": "rfs_static", "X-Trace": "1"},
170+
)
171+
172+
assert client._headers == {
173+
"Content-Type": "application/json",
174+
"X-Trace": "1",
175+
"Authorization": "Bearer eyJ.jwt",
176+
}
177+
178+
def test_resolved_api_key_replaces_a_static_bearer(self):
179+
client = GraphQLClient(
180+
"http://localhost:8000",
181+
token="rfs_key",
182+
headers={"authorization": "Bearer stale"},
183+
)
184+
185+
assert client._headers == {
186+
"Content-Type": "application/json",
187+
"X-API-Key": "rfs_key",
188+
}

‎tests/test_operation_client_ops.py‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99

1010
import threading
1111
import time
12+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
1213

1314
import pytest
1415
from unittest.mock import Mock, patch, MagicMock
@@ -260,6 +261,43 @@ def test_monitor_timeout_closes_a_silent_stream(self, MockSSE, mock_config):
260261
assert time.monotonic() - started < 2
261262
assert "op-silent" not in client.active_operations
262263

264+
def test_monitor_timeout_fires_on_time_over_a_real_socket(self, mock_config):
265+
"""A blocked socket read must not hold the timeout to the stream's own
266+
30s read timeout: a server that keeps the stream open with keepalives
267+
and never finishes is given up on at `timeout`."""
268+
stop = threading.Event()
269+
270+
class KeepaliveStream(BaseHTTPRequestHandler):
271+
def do_GET(self):
272+
self.send_response(200)
273+
self.send_header("Content-Type", "text/event-stream")
274+
self.end_headers()
275+
while not stop.is_set():
276+
try:
277+
self.wfile.write(b": keepalive\n\n")
278+
self.wfile.flush()
279+
except OSError:
280+
return
281+
stop.wait(0.5)
282+
283+
def log_message(self, *args):
284+
pass
285+
286+
server = ThreadingHTTPServer(("127.0.0.1", 0), KeepaliveStream)
287+
server.daemon_threads = True
288+
threading.Thread(target=server.serve_forever, daemon=True).start()
289+
try:
290+
config = {**mock_config, "base_url": f"http://127.0.0.1:{server.server_port}"}
291+
client = OperationClient(config)
292+
started = time.monotonic()
293+
with pytest.raises(TimeoutError, match="timed out after 1s"):
294+
client.monitor_operation("op-open", MonitorOptions(timeout=1))
295+
assert time.monotonic() - started < 5
296+
finally:
297+
stop.set()
298+
server.shutdown()
299+
server.server_close()
300+
263301
@patch("robosystems_client.clients.operation_client.SSEClient")
264302
def test_monitor_completion_beats_timeout(self, MockSSE, mock_config):
265303
"""A run that finishes inside `timeout` returns its result."""

0 commit comments

Comments
 (0)