Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 31 additions & 1 deletion gateway/platforms/qqbot/adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ def __init__(self, code, reason=""):
RATE_LIMIT_DELAY,
QUICK_DISCONNECT_THRESHOLD,
MAX_QUICK_DISCONNECT_COUNT,
MAX_RESUME_ATTEMPTS,
MAX_MESSAGE_LENGTH,
DEDUP_WINDOW_SECONDS,
DEDUP_MAX_SIZE,
Expand Down Expand Up @@ -205,6 +206,12 @@ def __init__(self, config: PlatformConfig):
self._heartbeat_interval: float = 30.0 # seconds, updated by Hello
self._session_id: Optional[str] = None
self._last_seq: Optional[int] = None
# Consecutive Resume attempts that have not yet been confirmed by a
# READY/RESUMED dispatch. Used to break the "stale session resume
# loop" where the server accepts Resume but immediately closes the
# WebSocket — without this counter the adapter retries Resume with
# the same expired session_id forever (see hermes-agent#22179).
self._resume_attempts: int = 0
self._chat_type_map: Dict[str, str] = {} # chat_id → "c2c"|"group"|"guild"|"dm"

# Request/response correlation
Expand Down Expand Up @@ -771,9 +778,29 @@ def _dispatch_payload(self, payload: Dict[str, Any]) -> None:
)
# Authenticate: send Resume if we have a session, else Identify.
# Use _create_task which is safe when no event loop is running (tests).
if self._session_id and self._last_seq is not None:
#
# Resume loop guard (hermes-agent#22179): if the previous Resume
# attempts never produced a RESUMED/READY dispatch (server accepted
# Resume then immediately closed the WebSocket), discard the stale
# session_id and fall back to a fresh Identify — otherwise the
# adapter would loop forever sending the same expired session_id.
if (
self._session_id
and self._last_seq is not None
and self._resume_attempts < MAX_RESUME_ATTEMPTS
):
self._resume_attempts += 1
self._create_task(self._send_resume())
else:
if self._resume_attempts >= MAX_RESUME_ATTEMPTS:
logger.warning(
"[%s] Resume failed %d times — discarding stale session_id and re-identifying",
self._log_tag,
Comment on lines 794 to +798
self._resume_attempts,
)
self._session_id = None
self._last_seq = None
self._resume_attempts = 0
self._create_task(self._send_identify())
return

Expand All @@ -783,6 +810,7 @@ def _dispatch_payload(self, payload: Dict[str, Any]) -> None:
self._handle_ready(d)
elif t == "RESUMED":
logger.info("[%s] Session resumed", self._log_tag)
self._resume_attempts = 0
elif t in (
"C2C_MESSAGE_CREATE",
"GROUP_AT_MESSAGE_CREATE",
Expand All @@ -808,6 +836,8 @@ def _handle_ready(self, d: Any) -> None:
if isinstance(d, dict):
self._session_id = d.get("session_id")
logger.info("[%s] Ready, session_id=%s", self._log_tag, self._session_id)
# Fresh Identify succeeded — clear the resume failure counter.
self._resume_attempts = 0

# ------------------------------------------------------------------
# JSON helpers
Expand Down
7 changes: 7 additions & 0 deletions gateway/platforms/qqbot/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,13 @@
QUICK_DISCONNECT_THRESHOLD = 5.0 # seconds
MAX_QUICK_DISCONNECT_COUNT = 3

# After this many consecutive Resume attempts that never produced a
# RESUMED/READY dispatch, the adapter discards its stale session_id and
# falls back to a fresh Identify handshake. Without the cap, an expired
# session causes an infinite Resume loop because the QQ server accepts
# Resume then immediately closes the WebSocket (hermes-agent#22179).
MAX_RESUME_ATTEMPTS = 3

ONBOARD_POLL_INTERVAL = 2.0 # seconds between poll_bind_result calls
ONBOARD_API_TIMEOUT = 10.0

Expand Down
130 changes: 130 additions & 0 deletions tests/gateway/test_qqbot_resume_loop_fallback.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
"""Regression: stale session_id must not cause an infinite Resume loop.

Issue hermes-agent#22179: when the QQ server expires a session, accepting
a Resume but immediately closing the WebSocket, the adapter previously
kept retrying Resume with the same expired session_id forever. The fix
caps Resume attempts at MAX_RESUME_ATTEMPTS and then discards the stale
session, falling back to a fresh Identify.

Tests drive ``_dispatch_payload`` synchronously with op-10 Hello frames
(where the Resume vs Identify decision is made) and inspect adapter
state. ``_create_task`` no-ops when no event loop is running, so we don't
need to actually fire the network calls — we just verify the bookkeeping.
"""

from __future__ import annotations

import pytest

Comment on lines +17 to +18
from gateway.config import PlatformConfig


def _make_config(**extra):
return PlatformConfig(enabled=True, extra=extra)


def _make_adapter():
from gateway.platforms.qqbot import QQAdapter

return QQAdapter(_make_config(app_id="a", client_secret="b"))


def _hello(adapter):
adapter._dispatch_payload({"op": 10, "d": {"heartbeat_interval": 30000}})


class TestResumeLoopFallback:
def test_initial_attempt_counter_is_zero(self):
adapter = _make_adapter()
assert adapter._resume_attempts == 0

def test_resume_increments_attempt_counter(self):
adapter = _make_adapter()
adapter._session_id = "stale"
adapter._last_seq = 42
_hello(adapter)
assert adapter._resume_attempts == 1
# Session not yet discarded — under the threshold.
assert adapter._session_id == "stale"
assert adapter._last_seq == 42

def test_resume_loop_capped_then_falls_back_to_identify(self):
from gateway.platforms.qqbot.constants import MAX_RESUME_ATTEMPTS

adapter = _make_adapter()
adapter._session_id = "stale"
adapter._last_seq = 42
# Drive Hello until the cap is reached: each Hello increments the
# counter and re-tries Resume. The (cap+1)-th Hello must trip the
# guard and discard the stale session.
for _ in range(MAX_RESUME_ATTEMPTS):
_hello(adapter)
assert adapter._resume_attempts == MAX_RESUME_ATTEMPTS
assert adapter._session_id == "stale"

_hello(adapter)
assert adapter._session_id is None
assert adapter._last_seq is None
assert adapter._resume_attempts == 0

def test_resumed_dispatch_resets_counter(self):
adapter = _make_adapter()
adapter._session_id = "live"
adapter._last_seq = 7
_hello(adapter)
_hello(adapter)
assert adapter._resume_attempts == 2

adapter._dispatch_payload(
{"op": 0, "t": "RESUMED", "s": 8, "d": {}}
)
assert adapter._resume_attempts == 0
# Session must remain intact — RESUMED is the success signal.
assert adapter._session_id == "live"

def test_ready_dispatch_resets_counter(self):
adapter = _make_adapter()
adapter._session_id = "stale"
adapter._last_seq = 1
_hello(adapter)
_hello(adapter)
assert adapter._resume_attempts == 2

adapter._dispatch_payload(
{"op": 0, "t": "READY", "s": 1, "d": {"session_id": "fresh"}}
)
assert adapter._resume_attempts == 0
assert adapter._session_id == "fresh"

def test_no_session_picks_identify_without_consuming_attempts(self):
adapter = _make_adapter()
# No session_id / last_seq → Identify path, counter untouched.
_hello(adapter)
assert adapter._resume_attempts == 0

def test_after_fallback_subsequent_resume_starts_fresh(self):
from gateway.platforms.qqbot.constants import MAX_RESUME_ATTEMPTS

adapter = _make_adapter()
adapter._session_id = "stale"
adapter._last_seq = 42
for _ in range(MAX_RESUME_ATTEMPTS + 1):
_hello(adapter)
# Identify success arrives.
adapter._dispatch_payload(
{"op": 0, "t": "READY", "s": 1, "d": {"session_id": "new"}}
)
# New disconnect happens; Resume should now be tried again with
# the fresh session, starting from zero attempts.
adapter._last_seq = 1
_hello(adapter)
assert adapter._resume_attempts == 1
assert adapter._session_id == "new"


def test_max_resume_attempts_constant_exists_and_is_positive():
"""Source-level guard: future refactors must keep the cap configurable."""
from gateway.platforms.qqbot.constants import MAX_RESUME_ATTEMPTS

assert isinstance(MAX_RESUME_ATTEMPTS, int)
assert MAX_RESUME_ATTEMPTS >= 1
Loading