Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
fix(app): protect Redis subscription cleanup from cancellation (#3158)
DiegoCluv7c76353a13f4e
diff --git a/src/agentscope/app/message_bus/_redis_message_bus.py b/src/agentscope/app/message_bus/_redis_message_bus.pyindex 89adcb0c0..c4d77f9a6 100644--- a/src/agentscope/app/message_bus/_redis_message_bus.py+++ b/src/agentscope/app/message_bus/_redis_message_bus.py@@ -614,8 +614,9 @@ class RedisMessageBus(MessageBus): # pylint: disable=too-many-public-methodscontinueyield json.loads(data)finally:- await pubsub.unsubscribe(key)- await pubsub.aclose()+ # Closing drops the subscription and returns the connection to+ # the pool; shield it so a cancelled consumer cannot leak it.+ await asyncio.shield(pubsub.aclose())# ------------------------------------------------------------------# Mode E — distributed lockdiff --git a/tests/service_message_bus_test.py b/tests/service_message_bus_test.pyindex 5484eb6fe..4b9a6a83a 100644--- a/tests/service_message_bus_test.py+++ b/tests/service_message_bus_test.py@@ -12,6 +12,7 @@ import asynciofrom contextlib import AsyncExitStackfrom typing import Anyfrom unittest import IsolatedAsyncioTestCase+from unittest.mock import patchimport fakeredis.aioredisfrom utils import AnyString@@ -252,6 +253,37 @@ class TestPubSubPrimitive(IsolatedAsyncioTestCase):await asyncio.wait_for(task, timeout=2.0)self.assertEqual([p["i"] for p in received], [1, 2])+ async def test_subscribe_cleanup_survives_cancellation(self) -> None:+ """A consumer cancelled again while closing the pubsub must not+ abort the close, otherwise the connection leaks from the pool."""+ ready, closing = asyncio.Event(), asyncio.Event()+ finish, released = asyncio.Event(), asyncio.Event()+ pubsub = self.fr.pubsub()+ original_aclose = pubsub.aclose++ async def _slow_aclose() -> None:+ closing.set()+ await finish.wait()+ await original_aclose()+ released.set()++ async def _consumer() -> None:+ async for _ in self.bus.subscribe("ch", on_ready=ready.set):+ pass++ pubsub.aclose = _slow_aclose+ with patch.object(self.fr, "pubsub", return_value=pubsub):+ task = asyncio.create_task(_consumer())+ await asyncio.wait_for(ready.wait(), timeout=2.0)+ task.cancel()+ await asyncio.wait_for(closing.wait(), timeout=2.0)+ task.cancel()+ with self.assertRaises(asyncio.CancelledError):+ await task++ finish.set()+ await asyncio.wait_for(released.wait(), timeout=2.0)+class TestLockPrimitive(IsolatedAsyncioTestCase):"""Mode E — distributed mutex semantics."""