-
Notifications
You must be signed in to change notification settings - Fork 848
FIX Harden prompt target cancellation cleanup #2483
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Roman Lutz (romanlutz)
wants to merge
1
commit into
microsoft:main
Choose a base branch
from
romanlutz:romanlutz-cancellation-hardening
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+122
−30
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change | ||||||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
@@ -418,10 +418,14 @@ async def _send_prompt_to_target_async(self, *, normalized_conversation: list[Me | |||||||||||||||||||||||||||||||||||
| connection = await self._connect_async(conversation_id=conversation_id) | ||||||||||||||||||||||||||||||||||||
| self._existing_conversation[conversation_id] = connection | ||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||
| # Only send config when creating a new connection | ||||||||||||||||||||||||||||||||||||
| await self.send_config_async(conversation_id=conversation_id, conversation=normalized_conversation) | ||||||||||||||||||||||||||||||||||||
| # Give the server a moment to process the session update | ||||||||||||||||||||||||||||||||||||
| await asyncio.sleep(0.5) | ||||||||||||||||||||||||||||||||||||
| try: | ||||||||||||||||||||||||||||||||||||
| # Only send config when creating a new connection | ||||||||||||||||||||||||||||||||||||
| await self.send_config_async(conversation_id=conversation_id, conversation=normalized_conversation) | ||||||||||||||||||||||||||||||||||||
| # Give the server a moment to process the session update | ||||||||||||||||||||||||||||||||||||
| await asyncio.sleep(0.5) | ||||||||||||||||||||||||||||||||||||
| except BaseException: | ||||||||||||||||||||||||||||||||||||
| await self.cleanup_conversation_async(conversation_id) | ||||||||||||||||||||||||||||||||||||
| raise | ||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||
| response_type = request.converted_value_data_type | ||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||
|
|
@@ -486,14 +490,13 @@ async def cleanup_conversation_async(self, conversation_id: str) -> None: | |||||||||||||||||||||||||||||||||||
| Args: | ||||||||||||||||||||||||||||||||||||
| conversation_id (str): The conversation ID to disconnect from. | ||||||||||||||||||||||||||||||||||||
| """ | ||||||||||||||||||||||||||||||||||||
| connection = self._existing_conversation.get(conversation_id) | ||||||||||||||||||||||||||||||||||||
| connection = self._existing_conversation.pop(conversation_id, None) | ||||||||||||||||||||||||||||||||||||
| if connection: | ||||||||||||||||||||||||||||||||||||
| try: | ||||||||||||||||||||||||||||||||||||
| await connection.close() | ||||||||||||||||||||||||||||||||||||
| logger.info(f"Disconnected from {self._endpoint} with conversation ID: {conversation_id}") | ||||||||||||||||||||||||||||||||||||
| except Exception as e: | ||||||||||||||||||||||||||||||||||||
| logger.warning(f"Error closing connection for {conversation_id}: {e}") | ||||||||||||||||||||||||||||||||||||
| del self._existing_conversation[conversation_id] | ||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||
| async def _connect_async(self, *, conversation_id: str) -> Any: | ||||||||||||||||||||||||||||||||||||
| """ | ||||||||||||||||||||||||||||||||||||
|
|
@@ -777,24 +780,22 @@ async def send_text_async( | |||||||||||||||||||||||||||||||||||
| connection = self._get_connection(conversation_id=conversation_id) | ||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||
| # Start listening for responses | ||||||||||||||||||||||||||||||||||||
| receive_tasks = asyncio.create_task(self.receive_events_async(conversation_id=conversation_id)) | ||||||||||||||||||||||||||||||||||||
| receive_task = asyncio.create_task(self.receive_events_async(conversation_id=conversation_id)) | ||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||
| logger.info(f"Sending text message: {text}") | ||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||
| # Send conversation item | ||||||||||||||||||||||||||||||||||||
| await connection.conversation.item.create( | ||||||||||||||||||||||||||||||||||||
| item={ | ||||||||||||||||||||||||||||||||||||
| "type": "message", | ||||||||||||||||||||||||||||||||||||
| "role": "user", | ||||||||||||||||||||||||||||||||||||
| "content": [{"type": "input_text", "text": text}], | ||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||
| ) | ||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||
| # Request response from model | ||||||||||||||||||||||||||||||||||||
| await self.send_response_create_async(conversation_id=conversation_id) | ||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||
| # Wait for response - receive_events has its own soft-finish logic | ||||||||||||||||||||||||||||||||||||
| result = await receive_tasks | ||||||||||||||||||||||||||||||||||||
| try: | ||||||||||||||||||||||||||||||||||||
| await connection.conversation.item.create( | ||||||||||||||||||||||||||||||||||||
| item={ | ||||||||||||||||||||||||||||||||||||
| "type": "message", | ||||||||||||||||||||||||||||||||||||
| "role": "user", | ||||||||||||||||||||||||||||||||||||
| "content": [{"type": "input_text", "text": text}], | ||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||
| ) | ||||||||||||||||||||||||||||||||||||
| await self.send_response_create_async(conversation_id=conversation_id) | ||||||||||||||||||||||||||||||||||||
| result = await receive_task | ||||||||||||||||||||||||||||||||||||
| finally: | ||||||||||||||||||||||||||||||||||||
| await self._cancel_receive_task_async(receive_task=receive_task) | ||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||
| if not result.audio_bytes: | ||||||||||||||||||||||||||||||||||||
| raise RuntimeError("No audio received from the server.") | ||||||||||||||||||||||||||||||||||||
|
|
@@ -827,7 +828,7 @@ async def send_audio_async( | |||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||
| audio_content, num_channels, sample_width, frame_rate = await asyncio.to_thread(self._read_wav_file, filename) | ||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||
| receive_tasks = asyncio.create_task(self.receive_events_async(conversation_id=conversation_id)) | ||||||||||||||||||||||||||||||||||||
| receive_task = asyncio.create_task(self.receive_events_async(conversation_id=conversation_id)) | ||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||
| try: | ||||||||||||||||||||||||||||||||||||
| audio_base64 = base64.b64encode(audio_content).decode("utf-8") | ||||||||||||||||||||||||||||||||||||
|
|
@@ -841,23 +842,29 @@ async def send_audio_async( | |||||||||||||||||||||||||||||||||||
| "content": [{"type": "input_audio", "audio": audio_base64}], | ||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||
| ) | ||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||
| logger.debug("Sending response.create") | ||||||||||||||||||||||||||||||||||||
| await self.send_response_create_async(conversation_id=conversation_id) | ||||||||||||||||||||||||||||||||||||
| logger.debug("Waiting for response events...") | ||||||||||||||||||||||||||||||||||||
| result = await receive_task | ||||||||||||||||||||||||||||||||||||
| except Exception as e: | ||||||||||||||||||||||||||||||||||||
| logger.error(f"Error sending audio: {e}") | ||||||||||||||||||||||||||||||||||||
| raise | ||||||||||||||||||||||||||||||||||||
| finally: | ||||||||||||||||||||||||||||||||||||
| await self._cancel_receive_task_async(receive_task=receive_task) | ||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||
| logger.debug("Sending response.create") | ||||||||||||||||||||||||||||||||||||
| await self.send_response_create_async(conversation_id=conversation_id) | ||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||
| logger.debug("Waiting for response events...") | ||||||||||||||||||||||||||||||||||||
| # Wait for response - receive_events has its own soft-finish logic | ||||||||||||||||||||||||||||||||||||
| result = await receive_tasks | ||||||||||||||||||||||||||||||||||||
| if not result.audio_bytes: | ||||||||||||||||||||||||||||||||||||
| raise RuntimeError("No audio received from the server.") | ||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||
| output_audio_path = await self.save_audio_async(result.audio_bytes, num_channels, sample_width, frame_rate) | ||||||||||||||||||||||||||||||||||||
| return output_audio_path, result | ||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||
| async def _cancel_receive_task_async(self, *, receive_task: asyncio.Task[RealtimeTargetResult]) -> None: | ||||||||||||||||||||||||||||||||||||
| """Cancel and retrieve an unfinished Realtime receive task.""" | ||||||||||||||||||||||||||||||||||||
| if receive_task.done(): | ||||||||||||||||||||||||||||||||||||
| return | ||||||||||||||||||||||||||||||||||||
| receive_task.cancel() | ||||||||||||||||||||||||||||||||||||
| await asyncio.gather(receive_task, return_exceptions=True) | ||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||
|
Comment on lines
+861
to
+867
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
so exceptions from tasks that are already completed are still retrieved |
||||||||||||||||||||||||||||||||||||
| async def _construct_message_from_response_async(self, response: Any, request: Any) -> Message: | ||||||||||||||||||||||||||||||||||||
| """ | ||||||||||||||||||||||||||||||||||||
| Not used in RealtimeTarget - message construction handled by receive_events. | ||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Could we shield and finish
connection.close()before propagating cancellation? Since the connection is popped first, cancellation duringclose()can leave the socket open with no remaining handle for later cleanup.