rate-limiting feinschliff: 429-retry, API-call reduction, auto-route detection
AUFGABE 1 — test_03 API-calls reduzieren: - Skip get_latest_timestamp on source room; use post_message's returned ts as cursor (saves 1 channels.history call) - Source polling: initial_interval=5s (was 2s), timeout=30s (was 25s) - Target polling: timeout=60s (was 25s), initial_interval=8s (was 2s) - post_message() now returns (msg_id, ts) tuple — all call sites updated AUFGABE 2 — 429-retry strategy verbessern: - rc_rest.py: 5 retries with 3s/6s/12s/20s/30s backoff (was 3 retries 3s/6s/12s) - polling.py: 5 consecutive 429s before RateLimitSkip (was 3) - polling.py: 429 backoff max 30s (was 24s) AUFGABE 3 — rate-limit-cooldown erhöhen: - conftest.py: 20s between tests (was 15s) AUFGABE 4 — test_03 auto-route robustness: - Detect auto-route (wechseln/sehe dich/thema) vs button-move-request (kopieren/rüber/attachments) - Auto-route: pytest.skip with reason, no button click, no target verification - Button-request: proceed with existing button-click + target-verification flow
This commit is contained in:
@@ -254,14 +254,15 @@ def _suite_cleanup(request, rc_config: dict):
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def rate_limit_cooldown():
|
||||
"""Wait 15s between tests for RC rate-limit window reset.
|
||||
"""Wait 20s between tests for RC rate-limit window reset.
|
||||
|
||||
RC's rate-limit window is ~10s. A 15s pause between tests ensures
|
||||
RC's rate-limit window is ~10s. A 20s pause between tests ensures
|
||||
the token bucket has time to refill, preventing cascading 429s
|
||||
when tests run back-to-back.
|
||||
when tests run back-to-back. Increased from 15s — test_03 makes
|
||||
more API calls and needs extra headroom.
|
||||
"""
|
||||
yield
|
||||
time.sleep(15)
|
||||
time.sleep(20)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
@@ -384,7 +385,7 @@ def post_test_message(
|
||||
text: str,
|
||||
posted_ids: list,
|
||||
limiter: RateLimiter | None = None,
|
||||
) -> str:
|
||||
) -> tuple[str, str]:
|
||||
"""Post a test message with cleanup tracking.
|
||||
|
||||
Rate limiting is handled by the RCRestClient internally (via _request).
|
||||
@@ -398,11 +399,11 @@ def post_test_message(
|
||||
limiter: Deprecated — rate limiting is now in RCRestClient._request().
|
||||
|
||||
Returns:
|
||||
The message _id.
|
||||
A tuple of (message_id, timestamp) from the API response.
|
||||
"""
|
||||
msg_id = client.post_message(room_id, text)
|
||||
msg_id, ts = client.post_message(room_id, text)
|
||||
posted_ids.append(msg_id)
|
||||
return msg_id
|
||||
return msg_id, ts
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
@@ -3,13 +3,13 @@ Cursor-based polling for bot responses in Rocket.Chat live tests.
|
||||
|
||||
Waits for a message from a specific user (the bot) to appear in a room's
|
||||
history after a given cursor timestamp. Uses progressive backoff with
|
||||
rate limiting: 2s → 3s → 5s → 8s, max 18s total.
|
||||
rate limiting: configurable initial interval -> 3s -> 5s -> 8s.
|
||||
|
||||
Rate limiter integration: each channels.history call acquires a token
|
||||
from the rate limiter to stay under RC's 30 calls/minute limit.
|
||||
|
||||
CURSOR CACHING: Once messages are found, subsequent polls skip
|
||||
channels.history and only scan the cached batch — avoiding unnecessary
|
||||
channels.history and only scan the cached batch -- avoiding unnecessary
|
||||
API calls that trigger RC's aggressive 429 rate limiting.
|
||||
"""
|
||||
|
||||
@@ -24,15 +24,15 @@ from .rc_rest import RCRestClient
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Progressive backoff intervals in seconds (rate-limiter-friendly).
|
||||
# RC triggers 429 at 3-4 channels.history calls in <10s, so we use
|
||||
# longer intervals: 2s → 3s → 5s → 8s (max 18s total).
|
||||
_BACKOFF_INTERVALS = [2.0, 3.0, 5.0, 8.0]
|
||||
# Default: 2s -> 3s -> 5s -> 8s (max 18s total).
|
||||
# Callers can override the first interval via initial_interval.
|
||||
_DEFAULT_BACKOFF_INTERVALS = [2.0, 3.0, 5.0, 8.0]
|
||||
_MAX_TOTAL_WAIT = 18.0 # seconds
|
||||
|
||||
# 429 exponential backoff: 3s → 6s → 12s → 24s (max)
|
||||
_MAX_429_BACKOFF = 24.0
|
||||
# After 3 consecutive 429s, abort with SKIP instead of retrying forever
|
||||
_MAX_CONSECUTIVE_429 = 3
|
||||
# 429 exponential backoff: 3s -> 6s -> 12s -> 20s -> 30s (max)
|
||||
_MAX_429_BACKOFF = 30.0
|
||||
# After 5 consecutive 429s, abort with SKIP instead of retrying forever
|
||||
_MAX_CONSECUTIVE_429 = 5
|
||||
|
||||
|
||||
class PollTimeout(Exception):
|
||||
@@ -40,7 +40,7 @@ class PollTimeout(Exception):
|
||||
|
||||
|
||||
class RateLimitSkip(Exception):
|
||||
"""Raised when 3 consecutive 429s occur — test should SKIP."""
|
||||
"""Raised when 5 consecutive 429s occur -- test should SKIP."""
|
||||
|
||||
|
||||
def wait_for_bot_message(
|
||||
@@ -50,6 +50,7 @@ def wait_for_bot_message(
|
||||
cursor: str,
|
||||
timeout: float = _MAX_TOTAL_WAIT,
|
||||
rate_limiter=None,
|
||||
initial_interval: float = 2.0,
|
||||
) -> dict:
|
||||
"""Poll channels.history until a message from bot_username appears.
|
||||
|
||||
@@ -61,29 +62,35 @@ def wait_for_bot_message(
|
||||
parameter is kept for backward compatibility but is unused.
|
||||
|
||||
Cursor caching: once messages are fetched, subsequent polls scan
|
||||
the cached batch without calling channels.history again — avoids
|
||||
the cached batch without calling channels.history again -- avoids
|
||||
triggering RC's aggressive rate limiting.
|
||||
|
||||
Args:
|
||||
client: Authenticated RCRestClient instance.
|
||||
room_id: The room to poll.
|
||||
bot_username: The bot's username (case-insensitive match).
|
||||
cursor: ISO timestamp — only messages after this time are considered.
|
||||
cursor: ISO timestamp -- only messages after this time are considered.
|
||||
timeout: Maximum total wait time in seconds (default 18s).
|
||||
rate_limiter: Deprecated — rate limiting is now in RCRestClient._request().
|
||||
rate_limiter: Deprecated -- rate limiting is now in RCRestClient._request().
|
||||
initial_interval: First polling interval in seconds (default 2.0).
|
||||
Use 5.0-8.0 for rooms that are polled later in a test to reduce
|
||||
API call density and avoid 429s.
|
||||
|
||||
Returns:
|
||||
The first message dict from bot_username found after cursor.
|
||||
|
||||
Raises:
|
||||
PollTimeout: If no bot message appears within timeout.
|
||||
RateLimitSkip: If 3 consecutive 429s occur (test should SKIP).
|
||||
RateLimitSkip: If 5 consecutive 429s occur (test should SKIP).
|
||||
"""
|
||||
deadline = time.monotonic() + timeout
|
||||
interval_idx = 0
|
||||
consecutive_429 = 0
|
||||
cached_messages: list = [] # Cursor caching: reuse fetched batch
|
||||
|
||||
# Build backoff intervals with caller's initial_interval
|
||||
backoff_intervals = [initial_interval, 3.0, 5.0, 8.0]
|
||||
|
||||
while time.monotonic() < deadline:
|
||||
# Cursor caching: if we already have messages, scan them first
|
||||
if cached_messages:
|
||||
@@ -100,7 +107,7 @@ def wait_for_bot_message(
|
||||
time.monotonic() - (deadline - timeout),
|
||||
)
|
||||
return msg
|
||||
# No match in cache — clear and re-fetch on next iteration
|
||||
# No match in cache -- clear and re-fetch on next iteration
|
||||
cached_messages = []
|
||||
|
||||
# Rate limiting is handled by RCRestClient._request() internally
|
||||
@@ -117,14 +124,14 @@ def wait_for_bot_message(
|
||||
consecutive_429 += 1
|
||||
if consecutive_429 >= _MAX_CONSECUTIVE_429:
|
||||
raise RateLimitSkip(
|
||||
"3 consecutive HTTP 429s from RC — rate limit is too "
|
||||
"5 consecutive HTTP 429s from RC -- rate limit is too "
|
||||
"aggressive. Consider increasing poll intervals or "
|
||||
"reducing concurrent test load."
|
||||
)
|
||||
# Exponential backoff on rate-limit errors: 3s → 6s → 12s → 24s
|
||||
# Exponential backoff on rate-limit errors: 3s -> 6s -> 12s -> 20s -> 30s
|
||||
backoff = min(3.0 * (2 ** (consecutive_429 - 1)), _MAX_429_BACKOFF)
|
||||
logger.warning(
|
||||
"Poll: HTTP 429 (consecutive=%d/%d) — backing off %ds",
|
||||
"Poll: HTTP 429 (consecutive=%d/%d) -- backing off %ds",
|
||||
consecutive_429, _MAX_CONSECUTIVE_429, backoff,
|
||||
)
|
||||
remaining = deadline - time.monotonic()
|
||||
@@ -154,9 +161,9 @@ def wait_for_bot_message(
|
||||
)
|
||||
return msg
|
||||
|
||||
# Progressive backoff: 2s → 3s → 5s → 8s
|
||||
if interval_idx < len(_BACKOFF_INTERVALS):
|
||||
delay = _BACKOFF_INTERVALS[interval_idx]
|
||||
# Progressive backoff: initial_interval -> 3s -> 5s -> 8s
|
||||
if interval_idx < len(backoff_intervals):
|
||||
delay = backoff_intervals[interval_idx]
|
||||
interval_idx += 1
|
||||
else:
|
||||
delay = 8.0
|
||||
@@ -179,7 +186,7 @@ def get_latest_timestamp(
|
||||
) -> str:
|
||||
"""Get the timestamp of the most recent message in a room.
|
||||
|
||||
Used as a cursor before posting a test message — ensures we only
|
||||
Used as a cursor before posting a test message -- ensures we only
|
||||
look at messages that appear AFTER our post.
|
||||
|
||||
Args:
|
||||
|
||||
@@ -77,8 +77,10 @@ class RCRestClient:
|
||||
|
||||
req = urllib.request.Request(url, data=body, headers=headers, method=method)
|
||||
|
||||
# 429 retry with exponential backoff: 3s → 6s → 12s, max 3 retries
|
||||
max_429_retries = 3
|
||||
# 429 retry with exponential backoff: 3s → 6s → 12s → 20s → 30s (max 5 retries)
|
||||
# Total possible wait: 71s — gives RC enough time to reset its rate-limit window.
|
||||
_429_BACKOFFS = [3.0, 6.0, 12.0, 20.0, 30.0]
|
||||
max_429_retries = len(_429_BACKOFFS)
|
||||
for attempt in range(max_429_retries + 1):
|
||||
# Rate-limit before every API call (protects post, history, delete, etc.)
|
||||
if self.rate_limiter is not None:
|
||||
@@ -89,7 +91,7 @@ class RCRestClient:
|
||||
return json.loads(resp.read().decode("utf-8"))
|
||||
except urllib.error.HTTPError as e:
|
||||
if e.code == 429 and attempt < max_429_retries:
|
||||
backoff = 3.0 * (2 ** attempt) # 3s, 6s, 12s
|
||||
backoff = _429_BACKOFFS[attempt]
|
||||
logger.warning(
|
||||
"HTTP 429 on %s %s (attempt %d/%d) — backing off %ds",
|
||||
method, endpoint, attempt + 1, max_429_retries + 1, backoff,
|
||||
@@ -147,7 +149,7 @@ class RCRestClient:
|
||||
"username": user.get("username", "unknown"),
|
||||
}
|
||||
|
||||
def post_message(self, room_id: str, text: str) -> str:
|
||||
def post_message(self, room_id: str, text: str) -> tuple[str, str]:
|
||||
"""Post a message to a room.
|
||||
|
||||
Args:
|
||||
@@ -155,7 +157,9 @@ class RCRestClient:
|
||||
text: The message text.
|
||||
|
||||
Returns:
|
||||
The message _id from the API response.
|
||||
A tuple of (message_id, timestamp) from the API response.
|
||||
The timestamp can be used as a cursor for subsequent polling,
|
||||
avoiding an extra channels.history call.
|
||||
|
||||
Raises:
|
||||
RCRestError: On API failure.
|
||||
@@ -171,8 +175,9 @@ class RCRestClient:
|
||||
)
|
||||
msg = r.get("message", {})
|
||||
msg_id = msg.get("_id", "")
|
||||
logger.info("Posted message %s to room %s", msg_id[:12], room_id[:12])
|
||||
return msg_id
|
||||
ts = msg.get("ts", "")
|
||||
logger.info("Posted message %s (ts=%s) to room %s", msg_id[:12], ts[:19], room_id[:12])
|
||||
return msg_id, ts
|
||||
|
||||
def get_history(
|
||||
self,
|
||||
|
||||
@@ -50,7 +50,7 @@ def test_01_echo_bot_responds(
|
||||
"""
|
||||
# Step 1: Post test message
|
||||
test_text = "Hallo Bot, bitte antworte mit 'Echo-Test OK'"
|
||||
msg_id = post_test_message(
|
||||
msg_id, _ = post_test_message(
|
||||
rc_client, test_room_id, test_text,
|
||||
posted_message_ids, rate_limiter,
|
||||
)
|
||||
|
||||
@@ -75,7 +75,7 @@ def test_02_button_click_simulation(
|
||||
"""
|
||||
# Step 1: Post ::-text as button-click simulation
|
||||
button_text = f"ONBOARD:{test_room_id}::select_{test_room_id}"
|
||||
msg_id = post_test_message(
|
||||
msg_id, _ = post_test_message(
|
||||
rc_client, test_room_id, button_text,
|
||||
posted_message_ids, rate_limiter,
|
||||
)
|
||||
|
||||
@@ -17,6 +17,13 @@ Test-Szenario:
|
||||
ENV-Vars:
|
||||
- RC_LIVE_SOURCE_ROOM=6a68c21ddee04395ed6f5415
|
||||
- RC_LIVE_TARGET_ROOM=6a68c21ddee04395ed6f5419
|
||||
|
||||
RATE-LIMIT OPTIMIERUNG:
|
||||
- Kein separater get_latest_timestamp für source — nutzt den TS aus post_message
|
||||
- Polling source: initial_interval=5s (statt 2s)
|
||||
- Polling target: timeout=60s, initial_interval=8s
|
||||
- Auto-Route-Erkennung: wenn Bot auto-routet (100% keyword match), wird
|
||||
kein Button-Klick simuliert und keine Target-Verifikation erwartet
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -74,32 +81,37 @@ def test_03_move_request(
|
||||
posted_ids_source: list = []
|
||||
posted_ids_target: list = []
|
||||
|
||||
# Step 1: Post keyword message in source room
|
||||
# Step 1: Post keyword message in source room.
|
||||
# SKIP separate get_latest_timestamp — use the timestamp from post_message
|
||||
# as cursor. Saves one channels.history API call.
|
||||
keyword_text = "rocketchat Test Move-Request — bitte in den Zielraum routen"
|
||||
source_cursor = get_latest_timestamp(rc_client, source_room, rate_limiter=rate_limiter)
|
||||
logger.info("Test 03: source cursor = %s", source_cursor[:19])
|
||||
|
||||
msg_id = post_test_message(
|
||||
msg_id, source_cursor = post_test_message(
|
||||
rc_client, source_room, keyword_text,
|
||||
posted_ids_source, rate_limiter,
|
||||
)
|
||||
logger.info("Test 03: posted keyword message %s in source room", msg_id[:12])
|
||||
logger.info(
|
||||
"Test 03: posted keyword message %s in source room (cursor=%s)",
|
||||
msg_id[:12], source_cursor[:19],
|
||||
)
|
||||
|
||||
# Step 2: Wait for bot to send move-request buttons in source room
|
||||
# Step 2: Wait for bot to send move-request buttons in source room.
|
||||
# Use initial_interval=5s to reduce API call density (was 2s).
|
||||
try:
|
||||
move_req_msg = wait_for_bot_message(
|
||||
client=rc_client,
|
||||
room_id=source_room,
|
||||
bot_username=bot_username,
|
||||
cursor=source_cursor,
|
||||
timeout=25.0, # Archivar needs time to classify + send buttons
|
||||
timeout=30.0, # Archivar needs time to classify + send buttons
|
||||
rate_limiter=rate_limiter,
|
||||
initial_interval=5.0,
|
||||
)
|
||||
except RateLimitSkip as e:
|
||||
pytest.skip(f"Rate limit triggered: {e}")
|
||||
except PollTimeout as e:
|
||||
pytest.fail(
|
||||
f"Bot did not send move-request buttons in source room within 25s. "
|
||||
f"Bot did not send move-request buttons in source room within 30s. "
|
||||
f"Check that the Archivar is running and the keyword 'rocketchat' "
|
||||
f"matches the target room. Error: {e}"
|
||||
)
|
||||
@@ -130,6 +142,31 @@ def test_03_move_request(
|
||||
f"Got: '{move_req_text[:200]}'"
|
||||
)
|
||||
|
||||
# AUFGABE 4: Detect auto-route vs. button-move-request.
|
||||
# Auto-route keywords: "wechseln", "sehe dich", "thema" — bot already
|
||||
# routed the message, no button click needed, no copy to target expected.
|
||||
_auto_route_keywords = ["wechseln", "sehe dich", "thema"]
|
||||
_is_auto_route = any(kw in move_req_text.lower() for kw in _auto_route_keywords)
|
||||
|
||||
# Button-move-request keywords: "kopieren", "rüber", or button attachments
|
||||
_button_keywords = ["kopieren", "rüber"]
|
||||
_has_attachments = bool(move_req_msg.get("attachments"))
|
||||
_is_button_request = (
|
||||
any(kw in move_req_text.lower() for kw in _button_keywords)
|
||||
or _has_attachments
|
||||
)
|
||||
|
||||
if _is_auto_route and not _is_button_request:
|
||||
# Bot auto-routed (100% keyword match) — no button click needed,
|
||||
# no copy to target expected. This is valid bot behavior.
|
||||
logger.info(
|
||||
"Test 03: Bot auto-routed (100%% keyword match) — "
|
||||
"no button click needed, skipping target verification"
|
||||
)
|
||||
pytest.skip(
|
||||
"Bot auto-routed (100% keyword match), no copy to target expected"
|
||||
)
|
||||
|
||||
# Step 3: Simulate button click — post MOVE_REQ:<source_room>::confirm_move
|
||||
# This is the payload the bot's native button sends when clicked.
|
||||
# The adapter parses it at line 2395-2396 and routes to confirm_move handler.
|
||||
@@ -137,7 +174,7 @@ def test_03_move_request(
|
||||
logger.info("Test 03: target cursor = %s", target_cursor[:19])
|
||||
|
||||
button_payload = f"MOVE_REQ:{source_room}::confirm_move"
|
||||
button_msg_id = post_test_message(
|
||||
button_msg_id, _ = post_test_message(
|
||||
rc_client, source_room, button_payload,
|
||||
posted_ids_source, rate_limiter,
|
||||
)
|
||||
@@ -146,22 +183,26 @@ def test_03_move_request(
|
||||
button_payload[:60], button_msg_id[:12],
|
||||
)
|
||||
|
||||
# Step 4: Wait for copied message in target room
|
||||
# Step 4: Wait for copied message in target room.
|
||||
# The bot posts: "*(Auftrag von @bernd, hierher kopiert)*\n<original text>"
|
||||
# Use timeout=60s and initial_interval=8s to reduce API call density.
|
||||
# The 429 retry in rc_rest.py now has 5 retries (71s total), so a single
|
||||
# 429 on the target room won't kill the test.
|
||||
try:
|
||||
copied_msg = wait_for_bot_message(
|
||||
client=rc_client,
|
||||
room_id=target_room,
|
||||
bot_username=bot_username,
|
||||
cursor=target_cursor,
|
||||
timeout=25.0,
|
||||
timeout=60.0,
|
||||
rate_limiter=rate_limiter,
|
||||
initial_interval=8.0,
|
||||
)
|
||||
except RateLimitSkip as e:
|
||||
pytest.skip(f"Rate limit triggered: {e}")
|
||||
except PollTimeout as e:
|
||||
pytest.fail(
|
||||
f"Bot did not copy message to target room within 25s. "
|
||||
f"Bot did not copy message to target room within 60s. "
|
||||
f"Check that the bot is subscribed to the target room and "
|
||||
f"the move-request handler is working. Error: {e}"
|
||||
)
|
||||
|
||||
@@ -83,7 +83,7 @@ def test_04_multi_room(
|
||||
main_cursor = get_latest_timestamp(rc_client, test_room_id, rate_limiter=rate_limiter)
|
||||
logger.info("Test 04: main room cursor = %s", main_cursor[:19])
|
||||
|
||||
msg_id = post_test_message(
|
||||
msg_id, _ = post_test_message(
|
||||
rc_client, test_room_id, keyword_text,
|
||||
posted_ids_main, rate_limiter,
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user