Files
PaperClip/services/hermes/patch_hermes_retries.py

162 lines
5.8 KiB
Python

#!/usr/bin/env python3
"""
Patch Hermes' provider retry behaviour for MiniMax M Plan throttling.
MiniMax M Plan answers HTTP 429 / error 2062 ("M Plan rate limit reached")
when RPM/TPM is exceeded and recovers "within about one minute". Hermes'
default backoff for a generic 429 is `jittered_backoff(retry_count,
base_delay=2.0, max_delay=60.0)`, i.e. ~2s, 4s, 8s — all inside the
throttled window, so a run with a large context fails after a few seconds
even though waiting ~60s would have succeeded.
This patch:
1. Adds a generic-429 long backoff schedule to agent/retry_utils.py
(20s -> 45s -> 75s -> 90s -> 120s, jittered) used whenever a 429 is
classified as a rate limit and the provider sent no Retry-After.
2. Raises agent.api_max_retries in the Hermes config so all backoff steps
are reachable.
Idempotent: re-running is a no-op.
"""
from __future__ import annotations
import glob
import os
import re
import sys
MARKER = "[paperclip-patch] generic-429 backoff"
GENERIC_CONST_ANCHOR = "_ZAI_CODING_OVERLOAD_SHORT_ATTEMPTS = 3\n"
GENERIC_CONST_BLOCK = GENERIC_CONST_ANCHOR + f"""
# {MARKER}
# Long backoff for plain provider 429s (no Retry-After header). MiniMax M
# Plan throttles on RPM/TPM and recovers "within about one minute", so the
# short 2s/4s/8s default schedule always retries inside the throttled
# window and gives up too early.
_GENERIC_RATE_LIMIT_LONG_BACKOFF = (20.0, 45.0, 75.0, 90.0, 120.0, 150.0)
"""
ADAPTIVE_FUNC_ANCHOR = (
" if not is_zai_coding_overload_error(base_url=base_url, model=model, error=error):\n"
" return default_wait, None\n"
)
ADAPTIVE_FUNC_PATCHED = (
" if not is_zai_coding_overload_error(base_url=base_url, model=model, error=error):\n"
f" # {MARKER}\n"
" if getattr(error, \"status_code\", None) == 429:\n"
" idx = min(max(attempt - 1, 0), len(_GENERIC_RATE_LIMIT_LONG_BACKOFF) - 1)\n"
" base_delay = _GENERIC_RATE_LIMIT_LONG_BACKOFF[idx]\n"
" return (\n"
" jittered_backoff(1, base_delay=base_delay, max_delay=base_delay, jitter_ratio=0.2),\n"
" \"generic_rate_limit_long\",\n"
" )\n"
" return default_wait, None\n"
)
def find_site_packages() -> str | None:
candidates = []
try:
import agent # noqa: F401 (only works inside the venv)
candidates.append(os.path.dirname(os.path.dirname(os.path.abspath(agent.__file__))))
except Exception:
pass
candidates.extend(
glob.glob("/opt/hermes-venv/lib/python*/site-packages")
+ glob.glob("/usr/lib/python3*/site-packages")
+ glob.glob("/usr/local/lib/python3*/site-packages")
)
for path in candidates:
if path and os.path.isdir(os.path.join(path, "agent")):
return path
return None
def patch_retry_utils(site_packages: str) -> bool:
target = os.path.join(site_packages, "agent", "retry_utils.py")
with open(target, "r", encoding="utf-8") as handle:
content = handle.read()
if MARKER in content:
print(f"[patch-retries] already patched: {target}")
return True
if GENERIC_CONST_ANCHOR not in content or ADAPTIVE_FUNC_ANCHOR not in content:
print(f"[patch-retries] anchors not found in {target} (Hermes version changed?)")
return False
backup = target + ".paperclip.bak"
if not os.path.exists(backup):
with open(backup, "w", encoding="utf-8") as handle:
handle.write(content)
content = content.replace(GENERIC_CONST_ANCHOR, GENERIC_CONST_BLOCK, 1)
content = content.replace(ADAPTIVE_FUNC_ANCHOR, ADAPTIVE_FUNC_PATCHED, 1)
with open(target, "w", encoding="utf-8") as handle:
handle.write(content)
print(f"[patch-retries] patched generic 429 backoff: {target}")
return True
def patch_conversation_loop(site_packages: str) -> bool:
"""Surface the generic long-backoff policy in status/log lines."""
target = os.path.join(site_packages, "agent", "conversation_loop.py")
with open(target, "r", encoding="utf-8") as handle:
content = handle.read()
if MARKER + " status" in content:
print(f"[patch-retries] status hook already patched: {target}")
return True
anchor = (
' if _backoff_policy == "zai_coding_overload_long":\n'
' _policy_note = " (Z.AI Coding overload adaptive long backoff)"\n'
)
if anchor not in content:
print(f"[patch-retries] status hook anchor not found in {target}")
return False
patched = anchor + (
f' elif _backoff_policy == "generic_rate_limit_long": # {MARKER} status\n'
' _policy_note = " (provider rate limit, long backoff)"\n'
)
content = content.replace(anchor, patched, 1)
with open(target, "w", encoding="utf-8") as handle:
handle.write(content)
print(f"[patch-retries] patched status note: {target}")
return True
def main() -> int:
site_packages = find_site_packages()
if not site_packages:
print("[patch-retries] ERROR: could not locate Hermes site-packages")
return 1
ok = patch_retry_utils(site_packages)
ok = patch_conversation_loop(site_packages) and ok
# Byte-compile so a syntax error surfaces immediately instead of at spawn
# time.
import py_compile
for rel in ("agent/retry_utils.py", "agent/conversation_loop.py"):
path = os.path.join(site_packages, rel)
try:
py_compile.compile(path, doraise=True)
print(f"[patch-retries] compile ok: {rel}")
except py_compile.PyCompileError as exc:
print(f"[patch-retries] COMPILE ERROR in {rel}: {exc}")
ok = False
return 0 if ok else 1
if __name__ == "__main__":
sys.exit(main())