@@ -393,11 +393,24 @@ async def request_mock_async(self, mock_request: MockRequestInput) -> MockRespon
393393 f"[ProtobufCommunicator] Creating mock request with requestId: { request_id } , testId: { mock_request .test_id } "
394394 )
395395
396- # Send and wait for response
397- await self ._send_protobuf_message (sdk_message )
398- response = await self ._receive_response (request_id )
396+ # Pre-register event BEFORE sending message to avoid race condition where
397+ # CLI responds before _wait_for_response registers the event
398+ if self ._background_reader_thread and self ._background_reader_thread .is_alive ():
399+ with self ._response_lock :
400+ self ._response_events [request_id ] = threading .Event ()
399401
400- return response
402+ try :
403+ # Send and wait for response
404+ await self ._send_protobuf_message (sdk_message )
405+ response = await self ._receive_response (request_id )
406+ return response
407+ except Exception :
408+ # Clean up pre-registered event on failure
409+ if self ._background_reader_thread and self ._background_reader_thread .is_alive ():
410+ with self ._response_lock :
411+ self ._response_events .pop (request_id , None )
412+ self ._response_data .pop (request_id , None )
413+ raise
401414
402415 def request_mock_sync (self , mock_request : MockRequestInput ) -> MockResponseOutput :
403416 """Request mocked response data from CLI (synchronous).
@@ -595,14 +608,17 @@ async def _receive_response(self, request_id: str) -> MockResponseOutput:
595608 def _wait_for_response (self , request_id : str ) -> MockResponseOutput :
596609 """Wait for a response from the background reader thread.
597610
598- Registers an event for the request_id, waits for the background reader
611+ Uses a pre-registered event for the request_id (registered before sending
612+ the message to avoid race conditions), waits for the background reader
599613 to signal it, then retrieves the response.
600614 """
601- event = threading .Event ()
602-
603- # Register the event for this request
615+ # Use pre-registered event, or create one as fallback
604616 with self ._response_lock :
605- self ._response_events [request_id ] = event
617+ event = self ._response_events .get (request_id )
618+ if not event :
619+ # Fallback: register now (shouldn't happen in normal flow)
620+ event = threading .Event ()
621+ self ._response_events [request_id ] = event
606622
607623 try :
608624 # Wait for the background reader to signal us
0 commit comments