The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(buzz): a held busy burst is durable before the receive cursor passes it (#141378)
Teknium1338acd6ff63
diff --git a/gateway/session_ingress_burst.py b/gateway/session_ingress_burst.pyindex 79f35fd9507..2df1a94b1d9 100644--- a/gateway/session_ingress_burst.py+++ b/gateway/session_ingress_burst.py@@ -170,6 +170,31 @@ def _settle(burst, task):burst.done.set_result(None)+def _undurable(adapter):+ """Inputs the reader already returned on that are not committed yet: held bursts, burst commits+ and busy inputs released before their commit (``session_ingress._hold_until_committed``)."""+ pending = [burst.done for burst in adapter.__dict__.get('_shared_bursts', {}).values()]+ pending += [*adapter.__dict__.get('_shared_burst_commits', {}).values(),+ *adapter.__dict__.get('_uncommitted_inputs', ())]+ return [future for future in pending if not future.done()]+++async def when_returned_inputs_durable(adapter, persist):+ """Run ``persist()`` once every input a serial reader returned on is committed: a reader that+ saves its own receive cursor after the call returns (Buzz) must not advance it past a held burst,+ or a restart in the hold window loses it. Inline when nothing is pending; otherwise in a tracked+ task, so the reader reads on (a lost cursor write only replays inputs admission already holds)."""+ if not _undurable(adapter):+ await persist()+ return++ async def later():+ while pending := _undurable(adapter):+ await asyncio.wait(pending)+ await persist()+ _track(adapter, asyncio.create_task(later()))++def discard_busy_burst(adapter, session_key):"""``/stop`` / ``/new`` drop a held burst as main dropped its debounce buffer; nothing was ACKed."""burst = adapter.__dict__.get('_shared_bursts', {}).pop(session_key, None)diff --git a/plugins/platforms/buzz/adapter.py b/plugins/platforms/buzz/adapter.pyindex 3cbc40717bf..8a20c151e16 100644--- a/plugins/platforms/buzz/adapter.py+++ b/plugins/platforms/buzz/adapter.py@@ -68,6 +68,7 @@ from gateway.platforms.base import (from gateway.platforms.helpers import cancel_taskfrom gateway.platforms.event import MessageEvent, MessageTypefrom gateway.config import Platform+from plugins.platforms.buzz.buzz_cursors import _SEEN_CAP, BuzzCursorMixin_CHAT_KIND = 9 # ``messages get`` also returns housekeeping kinds, never dispatched@@ -96,9 +97,6 @@ def _escape_unresolved_presentation_mention(content: str, error: str) -> Optiona_FETCH_LIMIT = 50 # events per poll / seed call-_SEEN_CAP = 500 # per-channel de-dupe set bound (events)-_CURSOR_STATE_SUBDIR = "buzz" # per-channel cursors survive a restart under HERMES_HOME-_CURSOR_STATE_FILENAME = "channel-cursors.json"_DM_DISCOVERY_EVERY = 5 # re-run DM discovery every N poll sweeps_DEFAULT_POLL_INTERVAL = 4.0_MIN_POLL_INTERVAL = 1.0@@ -510,11 +508,10 @@ _MEDIA_KIND_PRIORITY = (("image", MessageType.PHOTO), ("audio", MessageType.AUDI_ATTACHMENT_KIND_TYPES = {"image": MessageType.PHOTO, "video": MessageType.VIDEO, "audio": MessageType.AUDIO, "document": MessageType.DOCUMENT}-class BuzzAdapter(BasePlatformAdapter):+class BuzzAdapter(BuzzCursorMixin, BasePlatformAdapter):"""Buzz adapter (WebSocket push with poll fallback) for the BasePlatformAdapter interface."""serial_receive_loop = True # WS listener and poll sweep both await each event batch before reading the next-def __init__(self, config, **kwargs):super().__init__(config=config, platform=Platform("buzz"))extra = getattr(config, "extra", {}) or {}@@ -1234,67 +1231,6 @@ class BuzzAdapter(BasePlatformAdapter):def _new_channel_state(self, chat_type: str) -> dict:return {"chat_type": chat_type, "last_ts": 0, "seen": OrderedDict(), "event_meta": OrderedDict()}- # ── Durable channel cursors ───────────────────────────────────────────-- @staticmethod- def _cursor_path() -> Path:- from hermes_constants import get_hermes_home- return get_hermes_home() / _CURSOR_STATE_SUBDIR / _CURSOR_STATE_FILENAME-- def _load_cursors(self) -> None:- """Read persisted cursors; another identity/relay's file is ignored (ids collide), failures seed from history."""- self._restored_cursors = {}- try:- if not (path := self._cursor_path()).exists():- return- data = json.loads(path.read_text(encoding="utf-8-sig"))- except Exception:- logger.debug("Buzz: could not read channel cursors", exc_info=True)- return- if not isinstance(data, dict) or data.get("identity") != self._self_pubkey or data.get("relay") != self.relay_url:- return- if not isinstance(channels := data.get("channels"), dict):- return- for channel_id, entry in channels.items():- if not isinstance(entry, dict):- continue- try:- last_ts = int(entry.get("last_ts") or 0)- except (TypeError, ValueError):- continue- raw_seen = entry.get("seen")- seen = [str(event_id) for event_id in raw_seen][-_SEEN_CAP:] if isinstance(raw_seen, list) else []- self._restored_cursors[str(channel_id)] = {"chat_type": str(entry.get("chat_type") or ""), "last_ts": last_ts, "seen": seen}-- def _cursor_payload(self) -> dict:- """Snapshot of every watched channel's cursor (taken on the loop: ``_channel_state`` is loop-owned)."""- channels = {- channel_id: {- "chat_type": state.get("chat_type") or "group", "last_ts": int(state.get("last_ts") or 0),- "seen": list(state.get("seen") or ()),- }- for channel_id, state in self._channel_state.items()- }- return {"identity": self._self_pubkey, "relay": self.relay_url, "channels": channels}-- def _save_cursors(self) -> None:- """Persist every watched channel's cursor. Never raises."""- self._write_cursors(self._cursor_path(), self._cursor_payload())-- @staticmethod- def _write_cursors(path: Path, payload: dict) -> None:- try:- from utils import atomic_json_write- atomic_json_write(path, payload, indent=None)- except Exception:- logger.debug("Buzz: could not persist channel cursors", exc_info=True)-- @staticmethod- def _cursor_mark(state: dict) -> tuple:- """Cheap change detector for one channel's cursor."""- seen = state.get("seen") or ()- return int(state.get("last_ts") or 0), len(seen), (next(reversed(seen), None) if seen else None)-def _restore_channel_state(self, channel_id: str, chat_type: str) -> bool:"""Install a persisted cursor (True when one existed): seeding would mark downtime arrivals as seen.@@ -1399,10 +1335,9 @@ class BuzzAdapter(BasePlatformAdapter):for event in events:await self._handle_event(channel_id, state, event)self._trim_seen(state)- if self._cursor_mark(state) != before:- # The write fsyncs + renames, and on the WebSocket transport this runs once per inbound event.- async with self._cursor_write_lock:- await asyncio.to_thread(self._write_cursors, self._cursor_path(), self._cursor_payload())+ if self._cursor_mark(state) != before: # never past a busy input held uncommitted (serial reader)+ from gateway.session_ingress_burst import when_returned_inputs_durable+ await when_returned_inputs_durable(self, self._persist_cursors)@staticmethoddef _parse_imeta_attachments(event: dict) -> tuple[list[dict], int]:diff --git a/plugins/platforms/buzz/buzz_cursors.py b/plugins/platforms/buzz/buzz_cursors.pynew file mode 100644index 00000000000..d10b84d8ef6--- /dev/null+++ b/plugins/platforms/buzz/buzz_cursors.py@@ -0,0 +1,78 @@+"""Durable per-channel receive cursors for the Buzz adapter (#90464): a restart resumes from the saved+cursor instead of reseeding from history and marking downtime arrivals as seen."""+import asyncio+import json+import logging+from pathlib import Path++logger = logging.getLogger(__name__)++_SEEN_CAP = 500 # per-channel de-dupe set bound (events)+_CURSOR_STATE_SUBDIR = "buzz" # per-channel cursors survive a restart under HERMES_HOME+_CURSOR_STATE_FILENAME = "channel-cursors.json"+++class BuzzCursorMixin:+ @staticmethod+ def _cursor_path() -> Path:+ from hermes_constants import get_hermes_home+ return get_hermes_home() / _CURSOR_STATE_SUBDIR / _CURSOR_STATE_FILENAME++ def _load_cursors(self) -> None:+ """Read persisted cursors; another identity/relay's file is ignored (ids collide), failures seed from history."""+ self._restored_cursors = {}+ try:+ if not (path := self._cursor_path()).exists():+ return+ data = json.loads(path.read_text(encoding="utf-8-sig"))+ except Exception:+ logger.debug("Buzz: could not read channel cursors", exc_info=True)+ return+ if not isinstance(data, dict) or data.get("identity") != self._self_pubkey or data.get("relay") != self.relay_url:+ return+ if not isinstance(channels := data.get("channels"), dict):+ return+ for channel_id, entry in channels.items():+ if not isinstance(entry, dict):+ continue+ try:+ last_ts = int(entry.get("last_ts") or 0)+ except (TypeError, ValueError):+ continue+ raw_seen = entry.get("seen")+ seen = [str(event_id) for event_id in raw_seen][-_SEEN_CAP:] if isinstance(raw_seen, list) else []+ self._restored_cursors[str(channel_id)] = {"chat_type": str(entry.get("chat_type") or ""), "last_ts": last_ts, "seen": seen}++ def _cursor_payload(self) -> dict:+ """Snapshot of every watched channel's cursor (taken on the loop: ``_channel_state`` is loop-owned)."""+ channels = {+ channel_id: {+ "chat_type": state.get("chat_type") or "group", "last_ts": int(state.get("last_ts") or 0),+ "seen": list(state.get("seen") or ()),+ }+ for channel_id, state in self._channel_state.items()+ }+ return {"identity": self._self_pubkey, "relay": self.relay_url, "channels": channels}++ def _save_cursors(self) -> None:+ """Persist every watched channel's cursor. Never raises."""+ self._write_cursors(self._cursor_path(), self._cursor_payload())++ @staticmethod+ def _write_cursors(path: Path, payload: dict) -> None:+ try:+ from utils import atomic_json_write+ atomic_json_write(path, payload, indent=None)+ except Exception:+ logger.debug("Buzz: could not persist channel cursors", exc_info=True)++ @staticmethod+ def _cursor_mark(state: dict) -> tuple:+ """Cheap change detector for one channel's cursor."""+ seen = state.get("seen") or ()+ return int(state.get("last_ts") or 0), len(seen), (next(reversed(seen), None) if seen else None)++ async def _persist_cursors(self) -> None:+ # The write fsyncs + renames, and on the WebSocket transport this runs once per inbound event.+ async with self._cursor_write_lock:+ await asyncio.to_thread(self._write_cursors, self._cursor_path(), self._cursor_payload())diff --git a/tests/gateway/test_busy_burst_serial_reader.py b/tests/gateway/test_busy_burst_serial_reader.pyindex 9320b7f9025..e3f09d8ee07 100644--- a/tests/gateway/test_busy_burst_serial_reader.py+++ b/tests/gateway/test_busy_burst_serial_reader.py@@ -281,6 +281,15 @@ async def test_restart_waits_for_a_direct_busy_input_queued_behind_a_slow_capturasync def test_buzz_split_text_merges_through_the_reader(monkeypatch):"""Buzz was left out of the #140973 serial-reader sweep: both the WS listener and the pollsweep await ``_handle_events`` before reading the next batch (#141378)."""+ adapter, state, source = _buzz(monkeypatch)+ owner = await _busy_owner(monkeypatch, adapter, source, busy_text_mode='queue')+ # as both readers do: the next batch only after the previous _handle_events returned+ await adapter._handle_events('chan', state, [_buzz_event(1, 'first half')])+ await adapter._handle_events('chan', state, [_buzz_event(2, 'second half')])+ assert await owner.settle(2) == [('first half\nsecond half', 0)]+++def _buzz(monkeypatch):from collections import OrderedDictfrom plugins.platforms.buzz.adapter import BuzzAdapter@@ -292,10 +301,24 @@ async def test_buzz_split_text_merges_through_the_reader(monkeypatch):adapter._resolve_user_name = _name # the CLI-backed resolver has no place in a unit teststate = {"chat_type": "dm", "last_ts": 0, "seen": OrderedDict(), "event_meta": OrderedDict()}adapter._channel_state['chan'] = state- source = adapter.build_source(chat_id='chan', chat_type='dm', user_id='aa11bb22')+ return adapter, state, adapter.build_source(chat_id='chan', chat_type='dm', user_id='aa11bb22')+++def _buzz_event(i, text):+ return {'id': f'e{i}', 'kind': 9, 'pubkey': 'aa11bb22', 'content': text, 'created_at': i}+++async def test_buzz_cursor_never_passes_a_held_burst(monkeypatch):+ """Buzz saves its receive cursor after ``_handle_events`` returns. A held busy input is not durable+ yet, so the saved cursor must not pass it: a restart inside the hold window would skip it."""+ adapter, state, source = _buzz(monkeypatch)owner = await _busy_owner(monkeypatch, adapter, source, busy_text_mode='queue')- event = lambda i, text: {'id': f'e{i}', 'kind': 9, 'pubkey': 'aa11bb22', 'content': text, 'created_at': i}- # as both readers do: the next batch only after the previous _handle_events returned- await adapter._handle_events('chan', state, [event(1, 'first half')])- await adapter._handle_events('chan', state, [event(2, 'second half')])- assert await owner.settle(2) == [('first half\nsecond half', 0)]+ saved = []+ monkeypatch.setattr(type(adapter), '_write_cursors', staticmethod(lambda path, payload: saved.append(+ (payload['channels']['chan']['last_ts'], holds_busy_burst(adapter, owner.key)))))+ await adapter._handle_events('chan', state, [_buzz_event(1, 'held')])+ assert owner.key in adapter._shared_bursts # returned with the input only held+ assert await owner.settle(2) == [('held', 0)]+ # The cursor naming event 1 was saved, and only once its burst had committed.+ assert [last_ts for last_ts, _ in saved] == [1] and not any(held for _, held in saved), saved