fix: prevent cancellation scope corruption by exitting in LIFO and handling exceptions

This commit is contained in:
Omar Aburub
2025-10-23 15:34:47 +03:00
parent 23ea754061
commit 8f060ee2fa
2 changed files with 26 additions and 19 deletions

View File

@@ -1556,11 +1556,13 @@ async def chat_completion(
log.info("Chat processing was cancelled")
try:
event_emitter = get_event_emitter(metadata)
await event_emitter(
await asyncio.shield(event_emitter(
{"type": "chat:tasks:cancel"},
)
))
except Exception as e:
pass
finally:
raise # re-raise to ensure proper task cancellation handling
except Exception as e:
log.debug(f"Error processing chat payload: {e}")
if metadata.get("chat_id") and metadata.get("message_id"):
@@ -1591,7 +1593,7 @@ async def chat_completion(
finally:
try:
if mcp_clients := metadata.get("mcp_clients"):
for client in mcp_clients.values():
for client in reversed(mcp_clients.values()):
await client.disconnect()
except Exception as e:
log.debug(f"Error cleaning up: {e}")