@@ -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 :
0 commit comments