Skip to content

Build and run agents you can see, understand and trust.

fix(message_bus): expire the in-memory try_lock claim after ttl_secs (#2654)

Lukas1f01e80ec815
diff --git a/src/agentscope/app/message_bus/_in_memory_message_bus.py b/src/agentscope/app/message_bus/_in_memory_message_bus.py
index 0d20e4480..f622725ae 100644
--- a/src/agentscope/app/message_bus/_in_memory_message_bus.py
+++ b/src/agentscope/app/message_bus/_in_memory_message_bus.py
@@ -17,8 +17,8 @@ dependency.
from __future__ import annotations
import asyncio
+import math
import time
-import uuid
from collections import defaultdict
from collections.abc import AsyncGenerator
from contextlib import asynccontextmanager
@@ -79,7 +79,9 @@ class InMemoryMessageBus(
# Mode E — locks: key -> asyncio.Lock
self._locks: dict[str, asyncio.Lock] = defaultdict(asyncio.Lock)
# Track which key is currently held so is_locked() works.
- self._lock_holders: dict[str, str] = {}
+ # key -> monotonic expiry deadline; ``acquire_lock`` has no
+ # lease, so it stores infinity.
+ self._lock_holders: dict[str, float] = {}
# Mode F — registry maps: namespace -> {field: value}
self._registries: dict[str, dict[str, str]] = defaultdict(dict)
@@ -379,9 +381,8 @@ class InMemoryMessageBus(
`None`: while the lock is held.
"""
lock = self._locks[key]
- token = uuid.uuid4().hex
async with lock:
- self._lock_holders[key] = token
+ self._lock_holders[key] = math.inf
try:
yield
finally:
@@ -398,13 +399,15 @@ class InMemoryMessageBus(
`bool`:
``True`` if some coroutine holds the lock.
"""
- return key in self._lock_holders
+ return self._lock_holders.get(key, 0.0) > time.monotonic()
async def try_lock(self, key: str, *, ttl_secs: int = 600) -> bool:
"""Non-blocking claim on ``key``. See base."""
- if key in self._lock_holders:
+ if self._lock_holders.get(key, 0.0) > time.monotonic():
return False
- self._lock_holders[key] = "1"
+ # The lease keeps a crashed holder from blocking the key
+ # forever, the contract the Redis bus gets from SET NX EX.
+ self._lock_holders[key] = time.monotonic() + ttl_secs
return True
async def unlock(self, key: str) -> None:
diff --git a/tests/in_memory_message_bus_test.py b/tests/in_memory_message_bus_test.py
index 0ee0c0579..8f5b8fc06 100644
--- a/tests/in_memory_message_bus_test.py
+++ b/tests/in_memory_message_bus_test.py
@@ -11,8 +11,10 @@ No external dependencies (no Redis, no fakeredis) — just asyncio.
import asyncio
from contextlib import AsyncExitStack
from unittest import IsolatedAsyncioTestCase
+from unittest.mock import patch
from agentscope.app.message_bus import InMemoryMessageBus
+from agentscope.app.message_bus import _in_memory_message_bus as _bus
class TestQueuePrimitive(IsolatedAsyncioTestCase):
@@ -285,6 +287,42 @@ class TestLockPrimitive(IsolatedAsyncioTestCase):
["first-in", "first-out", "second-in"],
)
+ async def test_try_lock_is_exclusive_until_unlocked(self) -> None:
+ """A second claim on a held key is refused; ``unlock`` frees it."""
+ self.assertTrue(await self.bus.try_lock("k", ttl_secs=10))
+ self.assertFalse(await self.bus.try_lock("k", ttl_secs=10))
+ self.assertTrue(await self.bus.is_locked("k"))
+
+ await self.bus.unlock("k")
+
+ self.assertFalse(await self.bus.is_locked("k"))
+ self.assertTrue(await self.bus.try_lock("k", ttl_secs=10))
+
+ async def test_try_lock_lease_expires_for_a_holder_that_crashed(
+ self,
+ ) -> None:
+ """A claim whose lease expired is claimable again."""
+ with patch.object(_bus.time, "monotonic") as monotonic:
+ monotonic.return_value = 1_000.0
+ self.assertTrue(await self.bus.try_lock("k", ttl_secs=600))
+ self.assertFalse(await self.bus.try_lock("k", ttl_secs=600))
+
+ # The holder is gone; ``unlock`` is never called.
+ monotonic.return_value = 1_000.0 + 600
+
+ self.assertFalse(await self.bus.is_locked("k"))
+ self.assertTrue(await self.bus.try_lock("k", ttl_secs=600))
+
+ async def test_acquire_lock_ignores_ttl_secs(self) -> None:
+ """``acquire_lock`` documents that it holds until the body ends."""
+ with patch.object(_bus.time, "monotonic") as monotonic:
+ monotonic.return_value = 1_000.0
+ async with self.bus.acquire_lock("k", ttl_secs=1):
+ monotonic.return_value = 1_000.0 + 3_600
+ self.assertTrue(await self.bus.is_locked("k"))
+ self.assertFalse(await self.bus.try_lock("k", ttl_secs=600))
+ self.assertFalse(await self.bus.is_locked("k"))
+
class TestRegistryPrimitive(IsolatedAsyncioTestCase):
"""Mode F — ``registry_*`` hash-keyed namespace operations."""