The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(platforms): irc/line/buzz identity-lock conflicts actually fire
teknium174a315bd32ad
diff --git a/plugins/platforms/buzz/adapter.py b/plugins/platforms/buzz/adapter.pyindex 242e2c20a08..de09a02aad4 100644--- a/plugins/platforms/buzz/adapter.py+++ b/plugins/platforms/buzz/adapter.py@@ -9,6 +9,7 @@ BUZZ_PRIVATE_KEY (nsec or hex): it reaches the CLI via the subprocess env and is"""import asyncio+import contextlibimport hashlibimport jsonimport logging@@ -669,7 +670,6 @@ class BuzzAdapter(BasePlatformAdapter):self._ws_task: Optional[asyncio.Task] = Noneself._ws_ready: Optional[asyncio.Event] = Noneself._membership_since = self._poll_count = 0- self._lock_key: Optional[str] = None# Channels the relay permanently rejected ("restricted"); persists across reconnects so we never re-subscribe.# channel_id -> { "chat_type", "last_ts", "seen": OrderedDict[event_id, None], "event_meta":# OrderedDict[event_id, (author_pubkey, content_snippet)], } event_meta backs NIP-10 reply-parent@@ -761,17 +761,9 @@ class BuzzAdapter(BasePlatformAdapter):self._display_name = str(profiles[0].get("display_name") or "").strip()self._self_npub = hex_to_npub(self._self_pubkey) or ""# Two profiles must not drive the same identity on one relay (duplicate replies, split de-dupe state).- try:- from gateway.status import acquire_scoped_lock- lock_key = f"{self.relay_url}:{self._self_pubkey}"- if not acquire_scoped_lock("buzz", lock_key):- return self._connect_failed(- "lock_conflict", "Buzz identity in use by another profile",- "Buzz: identity %s… on %s already in use by another profile", self._self_pubkey[:8], self.relay_url,- )- self._lock_key = lock_key- except ImportError:- self._lock_key = None # status module not available (e.g. tests)+ if not self._acquire_platform_lock(+ "buzz", f"{self.relay_url}:{self._self_pubkey}", f"Buzz identity {self._self_pubkey[:8]}… on {self.relay_url}"):+ return False# Map channel ids to names and pick the watch set.code, out, err = await self._run_cli(["channels", "list"])if code != 0:@@ -826,14 +818,8 @@ class BuzzAdapter(BasePlatformAdapter):async def disconnect(self) -> None:"""Stop the inbound transport and drop runtime state."""self._mark_disconnected()- lock_key = getattr(self, "_lock_key", None)- if lock_key:- try:- from gateway.status import release_scoped_lock- release_scoped_lock("buzz", lock_key)- except Exception:- pass- self._lock_key = None+ with contextlib.suppress(Exception):+ self._release_platform_lock()await self._cancel_task(self._ws_task)self._ws_task = Noneawait self._cancel_task(self._poll_task)diff --git a/plugins/platforms/irc/adapter.py b/plugins/platforms/irc/adapter.pyindex 775ddd34070..a5cd29340be 100644--- a/plugins/platforms/irc/adapter.py+++ b/plugins/platforms/irc/adapter.py@@ -158,15 +158,8 @@ class IRCAdapter(BasePlatformAdapter):logger.error("IRC: server and channel must be configured")return self._fail("config_missing", "IRC_SERVER and IRC_CHANNEL must be set", retryable=False)# Prevent two profiles from using the same IRC identity- try:- from gateway.status import acquire_scoped_lock- lock_key = f"{self.server}:{self.nickname}"- if not acquire_scoped_lock("irc", lock_key):- logger.error("IRC: %s@%s already in use by another profile", self.nickname, self.server)- return self._fail("lock_conflict", "IRC identity in use by another profile", retryable=False)- self._lock_key = lock_key- except ImportError:- self._lock_key = None # status module not available (e.g. tests)+ if not self._acquire_platform_lock("irc", f"{self.server}:{self.nickname}", f"IRC identity {self.nickname}@{self.server}"):+ return Falsetry:self._reader, self._writer = await asyncio.wait_for(asyncio.open_connection(self.server, self.port, ssl=_ssl_ctx(self.use_tls)), timeout=30.0)@@ -195,10 +188,8 @@ class IRCAdapter(BasePlatformAdapter):async def disconnect(self) -> None:"""Quit and close the connection."""- if getattr(self, "_lock_key", None):- with contextlib.suppress(Exception):- from gateway.status import release_scoped_lock- release_scoped_lock("irc", self._lock_key)+ with contextlib.suppress(Exception):+ self._release_platform_lock()self._mark_disconnected()if self._writer and not self._writer.is_closing():with contextlib.suppress(Exception):diff --git a/plugins/platforms/line/adapter.py b/plugins/platforms/line/adapter.pyindex 40abd2d5f4a..f894a175fff 100644--- a/plugins/platforms/line/adapter.py+++ b/plugins/platforms/line/adapter.py@@ -425,7 +425,6 @@ class LineAdapter(BasePlatformAdapter):self._cache = RequestCache()self._dedup = _MessageDeduplicator()self._bot_user_id: Optional[str] = None- self._lock_key: Optional[str] = Noneself._media_tokens: Dict[str, Tuple[str, float]] = {} # token → (path, expiry)self._media_temp_paths: Set[str] = set()self._media_ttl = MEDIA_TOKEN_TTL_SECONDS@@ -439,14 +438,9 @@ class LineAdapter(BasePlatformAdapter):if not self.channel_access_token or not self.channel_secret:return self._fail("config_missing", "LINE_CHANNEL_ACCESS_TOKEN and LINE_CHANNEL_SECRET must be set")# One profile per channel token; lock on a hash so the secret never hits disk.- try:- from gateway.status import acquire_scoped_lock- tok_hash = hashlib.sha256(self.channel_access_token.encode()).hexdigest()[:16]- if not acquire_scoped_lock("line", tok_hash):- return self._fail("lock_conflict", "LINE channel already in use by another profile")- self._lock_key = tok_hash- except ImportError:- self._lock_key = None+ tok_hash = hashlib.sha256(self.channel_access_token.encode()).hexdigest()[:16]+ if not self._acquire_platform_lock("line", tok_hash, "LINE channel"):+ return Falseself._client = _LineClient(self.channel_access_token)try: # best-effort self-userId for self-echo filtering (LINE rarely echoes anyway)self._bot_user_id = await self._client.get_bot_user_id()@@ -500,11 +494,8 @@ class LineAdapter(BasePlatformAdapter):_unlink_quietly(path)self._media_temp_paths.clear()self._media_tokens.clear()- if self._lock_key:- with contextlib.suppress(Exception):- from gateway.status import release_scoped_lock- release_scoped_lock("line", self._lock_key)- self._lock_key = None+ with contextlib.suppress(Exception):+ self._release_platform_lock()async def _handle_health(self, request) -> Any:from aiohttp import webdiff --git a/tests/gateway/test_buzz_adapter.py b/tests/gateway/test_buzz_adapter.pyindex bc7eb4e4591..0c732f3ba19 100644--- a/tests/gateway/test_buzz_adapter.py+++ b/tests/gateway/test_buzz_adapter.py@@ -3161,18 +3161,22 @@ class TestBuzzAdapterLifecycle:lambda platform, key: released.append((platform, key)),)adapter = _make_adapter()- adapter._lock_key = "wss://relay.example:" + SELF_PUBKEY+ adapter._platform_lock_scope = "buzz"+ adapter._platform_lock_identity = "wss://relay.example:" + SELF_PUBKEYawait adapter.disconnect()assert released == [("buzz", "wss://relay.example:" + SELF_PUBKEY)]- assert adapter._lock_key is None+ assert adapter._platform_lock_identity is None@pytest.mark.asyncioasync def test_connect_fails_when_identity_lock_held(self, monkeypatch):- """A second profile using the same relay+pubkey must fail fast."""+ """A second profile using the same relay+pubkey must fail fast. ``acquire_scoped_lock``+ returns ``(acquired, existing_record)`` — a bare truthiness check on that tuple never+ fires, so the mock returns the real contract."""import gateway.status as gateway_statusmonkeypatch.setattr(- gateway_status, "acquire_scoped_lock", lambda platform, key: False+ gateway_status, "acquire_scoped_lock",+ lambda scope, identity, metadata=None: (False, {"pid": 4242, "profile": "other"}),)adapter = _make_adapter()adapter.cli_path = "/fake/buzz"@@ -3184,7 +3188,11 @@ class TestBuzzAdapterLifecycle:)adapter._run_cli = cliassert await adapter.connect() is False- assert adapter._lock_key is None+ assert adapter._fatal_error_code == "buzz_lock"+ assert "other" in (adapter._fatal_error_message or "")+ assert adapter._platform_lock_identity == "https://test.relay:" + SELF_PUBKEY+ # channels list must never run: the conflict branch short-circuits connect()+ assert not any(call[0][:2] == ["channels", "list"] for call in cli.calls)# ── Credentials / requirements ────────────────────────────────────────────diff --git a/tests/gateway/test_irc_adapter.py b/tests/gateway/test_irc_adapter.pyindex e703f5e1fd3..7db8e115d4a 100644--- a/tests/gateway/test_irc_adapter.py+++ b/tests/gateway/test_irc_adapter.py@@ -66,6 +66,32 @@ class TestIRCAdapterInit:assert adapter.use_tls is True+class TestIRCAdapterLockConflict:++ @pytest.mark.asyncio+ async def test_connect_fails_when_identity_lock_held(self, monkeypatch):+ """``acquire_scoped_lock`` returns ``(acquired, existing)``; a live foreign holder must stop+ connect() before any socket is opened (the tuple is truthy, so a bare ``if not`` never fired)."""+ import gateway.status as gateway_status+ from gateway.config import PlatformConfig++ monkeypatch.setattr(+ gateway_status, "acquire_scoped_lock",+ lambda scope, identity, metadata=None: (False, {"pid": 4242, "profile": "other"}))+ opened = []++ async def _no_connect(*a, **k):+ opened.append(a)+ raise AssertionError("socket must not be opened on a lock conflict")+ monkeypatch.setattr(asyncio, "open_connection", _no_connect)+ adapter = IRCAdapter(PlatformConfig(enabled=True, extra={+ "server": "irc.example", "nickname": "hermes", "channel": "#x"}))+ assert await adapter.connect() is False+ assert adapter._fatal_error_code == "irc_lock"+ assert "other" in adapter._fatal_error_message+ assert opened == []++class TestIRCAdapterSend:@pytest.fixturediff --git a/tests/gateway/test_line_plugin.py b/tests/gateway/test_line_plugin.pyindex 4f076842b55..b5fe1623945 100644--- a/tests/gateway/test_line_plugin.py+++ b/tests/gateway/test_line_plugin.py@@ -412,6 +412,22 @@ class TestValidateConfig:class TestAdapterInit:+ @pytest.mark.asyncio+ async def test_connect_fails_when_channel_lock_held(self, monkeypatch):+ """``acquire_scoped_lock`` returns ``(acquired, existing)``; a live foreign holder must stop+ connect() before the LINE client is built (the tuple is truthy, so a bare ``if not`` never fired)."""+ import gateway.status as gateway_status+ from gateway.config import PlatformConfig++ monkeypatch.setattr(+ gateway_status, "acquire_scoped_lock",+ lambda scope, identity, metadata=None: (False, {"pid": 4242, "profile": "other"}))+ ad = LineAdapter(PlatformConfig(enabled=True, extra={"channel_access_token": "tok", "channel_secret": "sec"}))+ assert await ad.connect() is False+ assert ad._fatal_error_code == "line_lock"+ assert "other" in ad._fatal_error_message+ assert ad._client is None+def test_init_from_config_extra(self, monkeypatch):for k in ("LINE_CHANNEL_ACCESS_TOKEN", "LINE_CHANNEL_SECRET", "LINE_PORT"):monkeypatch.delenv(k, raising=False)