Skip to content

The agent that grows with you

fix(weixin): ret=-2 "prepare failed" that survives recovery is a session error, not a rate limit (#80125)

x7peepsbd39167c5656
diff --git a/gateway/platforms/weixin.py b/gateway/platforms/weixin.py
index eedb8abe0f0..1f1df222f2f 100644
--- a/gateway/platforms/weixin.py
+++ b/gateway/platforms/weixin.py
@@ -77,6 +77,16 @@ def _is_session_expired(resp: Dict[str, Any], ret: Any, errcode: Any) -> bool:
return SESSION_EXPIRED_ERRCODE in (ret, errcode) or _is_stale_session_ret(ret, errcode, resp.get("errmsg"))
+def _session_not_ready_error(ret: Any, errcode: Any, errmsg: Any) -> RuntimeError:
+ """The stale-session ``-2`` after the tokenless re-send is exhausted (or with no token to drop): iLink will not
+ prepare a bot-initiated send until this peer messages the bot again. Deterministic, so it is neither retried nor
+ fed to the rate-limit breaker (#80125). The text must not contain "rate limit" — ``classify_send_error`` would
+ route it back into the rate-limited redelivery lane."""
+ return RuntimeError(
+ f"iLink sendmessage session not ready: ret={ret} errcode={errcode} errmsg={errmsg or 'unknown error'}"
+ " — the user must send the bot a message first (or re-pair)")
+
+
def _make_ssl_connector() -> Optional["aiohttp.TCPConnector"]:
"""TCPConnector with certifi's CA bundle (``ilinkai.weixin.qq.com`` fails some system stores, e.g. Homebrew
OpenSSL); None without certifi so aiohttp's default (honors ``SSL_CERT_FILE`` under trust_env) applies.
@@ -968,9 +978,11 @@ class WeixinAdapter(OwnAccessPolicyMixin, BasePlatformAdapter):
return self._rate_limit_cooldown_remaining() > 0
async def _send_text_chunk(self, *, chat_id: str, chunk: str, context_token: Optional[str], client_id: str) -> None:
- """Send one text chunk with retry/backoff under the adapter-wide text gate. On session-expired (errcode -14)
- retry once *without* ``context_token`` — iLink accepts tokenless sends as a degraded fallback, which keeps cron
- pushes working when no user message refreshed the session."""
+ """Send one text chunk with retry/backoff under the adapter-wide text gate. A stale-session response (``-14``,
+ or ``-2`` with ``prepare failed``/``unknown error``) is re-sent once *without* ``context_token`` — iLink accepts
+ tokenless sends as a degraded fallback, which keeps cron pushes working when no user message refreshed the
+ session. A ``-2`` stale-session answer that survives that (or arrives with no token to drop) fails fast with
+ ``_session_not_ready_error`` instead of entering the retry ladder or the rate-limit breaker (#80125)."""
async with self._send_text_gate:
last_error: Optional[Exception] = None
retried_without_token = False
@@ -984,12 +996,16 @@ class WeixinAdapter(OwnAccessPolicyMixin, BasePlatformAdapter):
context_token=context_token, client_id=client_id)
ret, errcode = (resp.get("ret"), resp.get("errcode")) if resp and isinstance(resp, dict) else (None, None)
if (ret is not None and ret != 0) or (errcode is not None and errcode != 0):
+ errmsg = resp.get("errmsg") or resp.get("msg")
if _is_session_expired(resp, ret, errcode) and not retried_without_token and context_token:
retried_without_token, context_token = True, None
self._token_store._cache.pop(self._token_store._key(self._account_id, chat_id), None)
logger.warning("[%s] session expired for %s; retrying without context_token", self.name, _safe_id(chat_id))
continue
- errmsg = resp.get("errmsg") or resp.get("msg")
+ if _is_stale_session_ret(ret, errcode, errmsg):
+ # break, not raise: a raise here is caught below and re-enters the retry ladder.
+ last_error = _session_not_ready_error(ret, errcode, errmsg)
+ break
if ret != RATE_LIMIT_ERRCODE and errcode != RATE_LIMIT_ERRCODE:
raise RuntimeError(f"iLink sendmessage error: ret={ret} errcode={errcode} errmsg={errmsg or 'unknown error'}")
# Keep a descriptive error for when the loop exhausts while still limited.