Skip to content

The agent that grows with you

fix(discord): backfill stops re-dispatching a message once its turn delivered, and bounds the rest

teknium18c6881231a15
diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.py
index 11293895a2c..f2e056188a5 100644
--- a/hermes_cli/config_defaults.py
+++ b/hermes_cli/config_defaults.py
@@ -1471,6 +1471,7 @@ DEFAULT_CONFIG = {
"window_seconds": 21600, # only inspect messages from the last 6 hours
"limit": 100, # global cap on messages scanned per reconnect
"max_dispatches": 10, # cap on recovered messages dispatched per reconnect
+ "max_attempts": 3, # lifetime re-dispatch cap for one message, whatever its outcome
},
"reactions": True, # add πŸ‘€/βœ…/❌ reactions to messages during processing
# Gateway transport health probe: inspects the WebSocket's ready/open/heartbeat state (never
diff --git a/plugins/platforms/discord/adapter.py b/plugins/platforms/discord/adapter.py
index 5f50aa1f71f..676432eaaed 100644
--- a/plugins/platforms/discord/adapter.py
+++ b/plugins/platforms/discord/adapter.py
@@ -504,6 +504,11 @@ class _DiscordNonConversationalMessageTracker:
return str(message_id or "") in self._ids
+def _discord_snowflake_time(snowflake: int) -> dt.datetime:
+ """UTC creation time encoded in a Discord snowflake (ms since 2015-01-01 in the top 42 bits)."""
+ return dt.datetime.fromtimestamp(((snowflake >> 22) + 1420070400000) / 1000, tz=dt.timezone.utc)
+
+
def _metadata_marks_nonconversational(metadata: Optional[Dict[str, Any]]) -> bool:
"""Return True when an outbound send was explicitly marked as status-only."""
if not isinstance(metadata, dict):
@@ -2174,6 +2179,13 @@ class DiscordAdapter(DiscordMediaMixin, BasePlatformAdapter):
return self._missed_message_backfill_number(
"max_dispatches", "DISCORD_MISSED_MESSAGE_BACKFILL_MAX_DISPATCHES", 10, int, 1, 100)
+ def _missed_message_backfill_max_attempts(self) -> int:
+ """Lifetime re-dispatch ceiling for ONE message, independent of completion state:
+ ``max_dispatches`` caps a scan, not a row, so without this any message whose completion
+ can never be recorded is re-run on every reconnect (#113631)."""
+ return self._missed_message_backfill_number(
+ "max_attempts", "DISCORD_MISSED_MESSAGE_BACKFILL_MAX_ATTEMPTS", 3, int, 1, 100)
+
def _ensure_missed_message_backfill_task(self) -> asyncio.Task:
"""Return the active recovery task, or start one when none is running."""
task = self._missed_message_backfill_task
@@ -2338,20 +2350,25 @@ class DiscordAdapter(DiscordMediaMixin, BasePlatformAdapter):
iterators = next_round
async def _iter_channel_and_thread_messages(self, channel: Any, *, limit: int, after: Any, seen_channels: set[str]):
- """Yield history from a channel plus active/recent archived child threads."""
+ """Yield history from a channel plus active/recent archived child threads. ``after`` is the
+ scan-window floor; a stored cursor may only narrow it, never widen it, and it is never
+ inherited by child threads (each thread has its own cursor)."""
channel_key = str(getattr(channel, "id", ""))
if not channel_key or channel_key in seen_channels:
return
seen_channels.add(channel_key)
+ channel_after = after
cursor = self._discord_recovery_cursor(channel_key)
if cursor:
with suppress(ValueError, TypeError):
- after = discord.Object(id=int(cursor))
+ cursor_id = int(cursor)
+ if not isinstance(after, dt.datetime) or _discord_snowflake_time(cursor_id) > after:
+ channel_after = discord.Object(id=cursor_id)
history = getattr(channel, "history", None)
if callable(history):
try:
# Fetch the latest N then restore order; oldest_first=True could starve newer work forever.
- history_iter = history(limit=limit, after=after, oldest_first=False)
+ history_iter = history(limit=limit, after=channel_after, oldest_first=False)
messages = []
async for message in history_iter: # type: ignore[attr-defined]
messages.append(message)
@@ -2414,6 +2431,8 @@ class DiscordAdapter(DiscordMediaMixin, BasePlatformAdapter):
return False
if self._discord_message_has_active_claim(str(getattr(message, "id", ""))):
return False
+ if self._discord_message_attempts_exhausted(str(getattr(message, "id", ""))):
+ return False
# A success reaction is only an ack, not evidence the substantive response completed.
return not await self._message_has_non_down_bot_response(message)
@@ -2488,8 +2507,15 @@ class DiscordAdapter(DiscordMediaMixin, BasePlatformAdapter):
now = self._utc_now_iso()
def _op(conn):
- existing = conn.execute("SELECT status FROM discord_messages WHERE message_id=?", (message_id,)).fetchone()
- final_status = existing[0] if existing and existing[0] == "responded" else status
+ existing = conn.execute(
+ "SELECT status, updated_at FROM discord_messages WHERE message_id=?", (message_id,),
+ ).fetchone()
+ # "discovered" only says the scan saw the row: it never overwrites a completed row or an
+ # in-flight claim (queued/processing) β€” the active-claim guard reads that status and its
+ # original updated_at, so a died dispatch still expires after the 10-minute window.
+ keep = bool(existing) and (existing[0] == "responded" or status == "discovered")
+ final_status = existing[0] if keep else status
+ updated_at = (existing[1] or now) if keep else now
conn.execute(
"""
INSERT INTO discord_messages (message_id, channel_id, thread_id, parent_channel_id, author_id, created_at, status, updated_at)
@@ -2503,7 +2529,7 @@ class DiscordAdapter(DiscordMediaMixin, BasePlatformAdapter):
status=?,
updated_at=excluded.updated_at
""",
- (message_id, channel_id, thread_id, parent_id, author_id, created_text, final_status, now, final_status),
+ (message_id, channel_id, thread_id, parent_id, author_id, created_text, final_status, updated_at, final_status),
)
self._with_discord_recovery_db(_op)
@@ -2515,15 +2541,18 @@ class DiscordAdapter(DiscordMediaMixin, BasePlatformAdapter):
if not message_id:
return
now = self._utc_now_iso()
+ # ``attempts`` counts dispatches (the "queued" transition) so max_attempts is a ceiling on
+ # how many times one message is re-run, not on how many state transitions it saw.
+ dispatched = 1 if status == "queued" else 0
def _op(conn):
conn.execute(
"""
UPDATE discord_messages
- SET status=?, attempts=attempts+1, last_attempt_at=?, last_error=?, updated_at=?
+ SET status=?, attempts=attempts+?, last_attempt_at=?, last_error=?, updated_at=?
WHERE message_id=?
""",
- (status, now, error, now, message_id),
+ (status, dispatched, now, error, now, message_id),
)
self._with_discord_recovery_db(_op)
@@ -2550,8 +2579,20 @@ class DiscordAdapter(DiscordMediaMixin, BasePlatformAdapter):
message_id = str(getattr(getattr(event, "raw_message", None), "id", "") or getattr(event, "message_id", "") or "")
if not message_id:
return
- status = "processed" if outcome == ProcessingOutcome.SUCCESS else ("cancelled" if outcome == ProcessingOutcome.CANCELLED else "failed")
now = self._utc_now_iso()
+ if outcome == ProcessingOutcome.SUCCESS:
+ # SUCCESS means the base delivered the final (or the stream already had). Attribute it
+ # to the inbound id here: streamed/edited finals, fresh-final sends and media-only replies
+ # carry no reply anchor (reply_to_mode "off" never does), so the send-path ledger writer
+ # cannot mark the row and backfill would re-dispatch it on every reconnect (#113631).
+ def _complete(conn):
+ conn.execute(
+ "UPDATE discord_messages SET status='responded', replied=1, updated_at=? WHERE message_id=?",
+ (now, message_id),
+ )
+ self._with_discord_recovery_db(_complete)
+ return
+ status = "cancelled" if outcome == ProcessingOutcome.CANCELLED else "failed"
def _op(conn):
conn.execute(
@@ -2636,6 +2677,23 @@ class DiscordAdapter(DiscordMediaMixin, BasePlatformAdapter):
return bool(row and row[0] in {"queued", "processing"} and row[1] >= cutoff)
return bool(self._with_discord_recovery_db(_op, default=True))
+ def _discord_message_attempts_exhausted(self, message_id: str) -> bool:
+ """True once a row has been dispatched ``max_attempts`` times (any outcome)."""
+ if not message_id:
+ return False
+ cap = self._missed_message_backfill_max_attempts()
+
+ def _op(conn):
+ row = conn.execute("SELECT attempts FROM discord_messages WHERE message_id=?", (message_id,)).fetchone()
+ return bool(row and int(row[0] or 0) >= cap)
+ exhausted = bool(self._with_discord_recovery_db(_op, default=False))
+ if exhausted:
+ logger.debug(
+ "[%s] Not re-dispatching Discord message %s: missed_message_backfill.max_attempts (%d) reached",
+ self.name, message_id, cap,
+ )
+ return exhausted
+
def _record_recovery_scan_start(self, channels: set[str]) -> str:
scan_id = f"{int(time.time() * 1000)}-{os.getpid()}"
now = self._utc_now_iso()
diff --git a/tests/gateway/test_discord_missed_message_backfill.py b/tests/gateway/test_discord_missed_message_backfill.py
index e90a265f98f..1d7d422f6bb 100644
--- a/tests/gateway/test_discord_missed_message_backfill.py
+++ b/tests/gateway/test_discord_missed_message_backfill.py
@@ -303,6 +303,7 @@ def test_default_config_exposes_missed_message_backfill_settings():
"window_seconds": 21600,
"limit": 100,
"max_dispatches": 10,
+ "max_attempts": 3,
}
@@ -494,3 +495,90 @@ async def test_iter_candidates_skips_obfuscated_channel_on_explicit_ids(adapter,
got = [msg.id async for msg in adapter._iter_missed_message_backfill_candidates({"1", "2"})]
assert got == [11]
+
+
+def test_success_outcome_completes_row_without_reply_anchor(adapter):
+ """A delivered final with no Discord reply anchor (reply_to_mode=off, streamed edit, media-only
+ reply) must still complete the ledger row, or backfill re-dispatches it on every reconnect."""
+ message = make_message(message_id=93)
+ event = MessageEvent(text=message.content, message_type=MessageType.TEXT, raw_message=message, message_id="93")
+
+ adapter._record_discord_processing_start(event, emoji_ack=False)
+ adapter._record_discord_processing_complete(event, ProcessingOutcome.SUCCESS)
+ assert adapter._discord_message_is_persistently_complete("93") is True
+
+ failed = make_message(message_id=94)
+ failed_event = MessageEvent(text=failed.content, message_type=MessageType.TEXT, raw_message=failed, message_id="94")
+ adapter._record_discord_processing_start(failed_event, emoji_ack=False)
+ adapter._record_discord_processing_complete(failed_event, ProcessingOutcome.FAILURE)
+ assert adapter._discord_message_is_persistently_complete("94") is False
+
+
+async def test_redispatch_of_one_message_is_bounded(adapter, monkeypatch):
+ """A row that never completes is dispatched at most max_attempts times across scans, and a scan
+ must not erase the in-flight claim of a dispatch that has not finished yet."""
+ bot_user = adapter._client.user
+ message = make_message(message_id=95, content=f"<@{bot_user.id}> please ingest", mentions=[bot_user])
+
+ async def fake_candidates(_channels):
+ yield message
+
+ monkeypatch.setattr(adapter, "_iter_missed_message_backfill_candidates", fake_candidates)
+ monkeypatch.setattr(adapter, "_missed_message_backfill_channels", lambda: {"123"})
+ monkeypatch.setattr(adapter, "_missed_message_backfill_max_attempts", lambda: 2)
+
+ # Dispatch leaves the row 'processing' (turn still running): back-to-back scans re-offer it.
+ async def dispatch_and_stay_processing(msg, **_kwargs):
+ adapter._record_discord_message_seen(msg, status="processing")
+ return True
+
+ adapter._handle_message = AsyncMock(side_effect=dispatch_and_stay_processing)
+ for _ in range(3):
+ adapter._dedup.discard("95")
+ await adapter._run_missed_message_backfill()
+ assert adapter._handle_message.await_count == 1 # active claim survives the scan's 'discovered' write
+
+ # Claim expired (turn died): the lifetime cap still bounds total re-dispatch.
+ def _expire(conn):
+ conn.execute("UPDATE discord_messages SET status='failed' WHERE message_id='95'")
+ adapter._with_discord_recovery_db(_expire)
+ adapter._handle_message = AsyncMock(return_value=True)
+ for _ in range(4):
+ adapter._dedup.discard("95")
+ await adapter._run_missed_message_backfill()
+ adapter._with_discord_recovery_db(_expire)
+ assert adapter._handle_message.await_count == 1 # attempts: 1 (above) + 1 == max_attempts
+
+
+async def test_stored_cursor_cannot_widen_scan_window_or_leak_into_threads(adapter):
+ """after = max(cursor, now - window): an old cursor must not resurrect messages outside the window,
+ and a parent channel's cursor is never applied to its child threads."""
+ class RecordingChannel(FakeChannel):
+ def __init__(self, *args, threads=(), **kwargs):
+ super().__init__(*args, **kwargs)
+ self.threads = list(threads)
+ self.seen_after = []
+
+ def history(self, **kwargs):
+ self.seen_after.append(kwargs["after"])
+ return super().history(**kwargs)
+
+ thread = RecordingChannel(channel_id=456, parent_id=123)
+ channel = RecordingChannel(channel_id=123, threads=[thread])
+ window_floor = datetime.now(timezone.utc) - dt.timedelta(hours=1)
+ old_cursor = ((int((window_floor - dt.timedelta(hours=11)).timestamp() * 1000) - 1420070400000) << 22)
+ fresh_cursor = ((int((window_floor + dt.timedelta(minutes=30)).timestamp() * 1000) - 1420070400000) << 22)
+
+ adapter._advance_discord_recovery_cursor("123", str(old_cursor))
+ async for _ in adapter._iter_channel_and_thread_messages(channel, limit=10, after=window_floor, seen_channels=set()):
+ pass
+ assert channel.seen_after == [window_floor] # stale cursor ignored
+ assert thread.seen_after == [window_floor] # parent's cursor not inherited
+
+ adapter._advance_discord_recovery_cursor("123", str(fresh_cursor))
+ async for _ in adapter._iter_channel_and_thread_messages(channel, limit=10, after=window_floor, seen_channels=set()):
+ pass
+ assert not isinstance(channel.seen_after[-1], dt.datetime) # newer cursor narrows (discord.Object)
+ assert thread.seen_after[-1] == window_floor
diff --git a/website/docs/user-guide/messaging/discord.md b/website/docs/user-guide/messaging/discord.md
index 56ffb706d25..b3446600d2a 100644
--- a/website/docs/user-guide/messaging/discord.md
+++ b/website/docs/user-guide/messaging/discord.md
@@ -373,6 +373,7 @@ discord:
window_seconds: 21600 # Look back at most 6 hours
limit: 100 # Global scan cap per reconnect
max_dispatches: 10 # Recovery dispatch cap per reconnect
+ max_attempts: 3 # Lifetime re-dispatch cap per message
channel_prompts: {} # Per-channel ephemeral system prompts
voice_channel_inactivity_timeout_seconds: 300 # Set 0 to stay in VC until explicit /voice leave
voice_playback_timeout_seconds: 120 # Minimum playback watchdog; long clips get duration+padding
@@ -558,9 +559,12 @@ discord:
window_seconds: 3600
limit: 100
max_dispatches: 10
+ max_attempts: 3
```
-If `channels` is empty, Hermes uses `discord.free_response_channels`. Set it to `"*"` only when the bot should inspect every reachable server text channel. The recovery ledger is stored per profile under `gateway/discord_message_recovery.db`, preventing a successfully answered message from being replayed again after a later restart.
+If `channels` is empty, Hermes uses `discord.free_response_channels`. Set it to `"*"` only when the bot should inspect every reachable server text channel. The recovery ledger is stored per profile under `gateway/discord_message_recovery.db`, preventing a successfully answered message from being replayed again after a later restart. A message counts as answered once its turn delivered a final reply, whether or not that reply carried a Discord reply reference (`reply_to_mode: "off"`, streamed replies and media-only replies included).
+
+`max_dispatches` caps one scan; `max_attempts` (default 3) caps how many times a single message can ever be re-dispatched, so a message whose turn keeps failing is not re-run on every reconnect. `window_seconds` is always honoured: the per-channel scan cursor can narrow a scan but never reaches further back than the window.
#### `group_sessions_per_user`