fix(presence): WV-002 REST-Exception-Logging verfeinern (_rest_set_status)
Cooldown nur bei ECHTEM HTTP 429 (Status-Code-Pruefung), nicht bei String-Matching '429' im Exception-Text (Phantom-429er: DDP-Timeouts, REST-Token-Errors wurden faelschlich als 429 klassifiziert). - _extract_http_status_code(): HTTP-Status aus HTTPError/RateLimitError/ __cause__-Kette/Status-Attributen ermitteln - _is_http_429(): echte 429-Pruefung (Status-Code oder RateLimitError-Typ) - Logging: Exception-Typ + volle Message + HTTP-Status-Code (statt nur '429') - Retry-Pfad: gleiche 429-Pruefung + korrektes Logging - 3 bestehende Phantom-429-Tests auf RocketChatRateLimitError umgestellt - 16 neue Unit-Tests (test_wv002_rest_exception_logging.py) Tests: 1865 passed, 37 skipped, 11 xfailed (1 pre-existing order-dependent failure in test_user_visible.py, unrelated — verifiziert auf clean HEAD).
This commit is contained in:
@@ -797,11 +797,16 @@ class TestPresenceEngineWithDDP:
|
||||
assert engine._mediator._ddp_sender is None
|
||||
|
||||
def test_rest_429_triggers_ddp_on_rest_429(self):
|
||||
"""REST 429 → ddp_sender.on_rest_429() wird aufgerufen."""
|
||||
"""REST 429 → ddp_sender.on_rest_429() wird aufgerufen.
|
||||
|
||||
WV-002: Nutzt einen ECHTEN HTTP 429 (RocketChatRateLimitError),
|
||||
nicht einen String '429' im Exception-Text (Phantom-429).
|
||||
"""
|
||||
from plugin.adapter import RocketChatRateLimitError
|
||||
adapter, ddp = _make_mock_adapter()
|
||||
rest = _make_mock_rest()
|
||||
# Simuliere 429
|
||||
rest._request = MagicMock(side_effect=Exception("HTTP 429 Too Many Requests"))
|
||||
# Simuliere echten HTTP 429 via RocketChatRateLimitError
|
||||
rest._request = MagicMock(side_effect=RocketChatRateLimitError("HTTP 429"))
|
||||
engine = PresenceEngine(rest=rest, use_ddp=True, adapter=adapter)
|
||||
|
||||
# Setze ddp_sender Mock
|
||||
|
||||
@@ -413,8 +413,9 @@ class TestRestBackoffActivation:
|
||||
|
||||
def test_429_sets_cooldown(self):
|
||||
"""429-Antwort → rest_cooldown_until gesetzt."""
|
||||
from plugin.adapter import RocketChatRateLimitError
|
||||
rest = _make_mock_rest()
|
||||
rest._request.side_effect = Exception("HTTP 429 Too Many Requests")
|
||||
rest._request.side_effect = RocketChatRateLimitError("HTTP 429 Too Many Requests")
|
||||
engine = _make_engine(rest=rest, away_grace_s=0.05)
|
||||
engine.on_pre_gateway_dispatch()
|
||||
time.sleep(0.2)
|
||||
@@ -424,8 +425,9 @@ class TestRestBackoffActivation:
|
||||
|
||||
def test_429_telemetry_counted(self):
|
||||
"""Telemetrie zählt 429 + cooldown_set_count."""
|
||||
from plugin.adapter import RocketChatRateLimitError
|
||||
rest = _make_mock_rest()
|
||||
rest._request.side_effect = Exception("HTTP 429 Too Many Requests")
|
||||
rest._request.side_effect = RocketChatRateLimitError("HTTP 429 Too Many Requests")
|
||||
engine = _make_engine(rest=rest, away_grace_s=0.05)
|
||||
engine.on_pre_gateway_dispatch()
|
||||
time.sleep(0.2)
|
||||
@@ -883,8 +885,9 @@ class TestHttp429Handling:
|
||||
"""HTTP 429 von users.setStatus — kein Crash, Cooldown gesetzt."""
|
||||
|
||||
def test_429_no_crash_status_unchanged(self):
|
||||
from plugin.adapter import RocketChatRateLimitError
|
||||
rest = _make_mock_rest()
|
||||
rest._request.side_effect = Exception("HTTP 429 Too Many Requests")
|
||||
rest._request.side_effect = RocketChatRateLimitError("HTTP 429 Too Many Requests")
|
||||
engine = _make_engine(rest=rest, away_grace_s=0.05)
|
||||
engine.on_pre_gateway_dispatch()
|
||||
assert engine.get_status() == "BUSY"
|
||||
@@ -894,13 +897,14 @@ class TestHttp429Handling:
|
||||
assert engine.get_counters()["main_agent"] == 1
|
||||
|
||||
def test_429_retry_on_next_hook(self):
|
||||
from plugin.adapter import RocketChatRateLimitError
|
||||
rest = _make_mock_rest()
|
||||
call_count = [0]
|
||||
|
||||
def _side_effect(*args, **kwargs):
|
||||
call_count[0] += 1
|
||||
if call_count[0] == 1:
|
||||
raise Exception("HTTP 429 Too Many Requests")
|
||||
raise RocketChatRateLimitError("HTTP 429 Too Many Requests")
|
||||
return {"success": True}
|
||||
|
||||
rest._request.side_effect = _side_effect
|
||||
@@ -917,8 +921,9 @@ class TestHttp429Handling:
|
||||
assert call_count[0] == 2
|
||||
|
||||
def test_429_telemetry_counted(self):
|
||||
from plugin.adapter import RocketChatRateLimitError
|
||||
rest = _make_mock_rest()
|
||||
rest._request.side_effect = Exception("HTTP 429 Too Many Requests")
|
||||
rest._request.side_effect = RocketChatRateLimitError("HTTP 429 Too Many Requests")
|
||||
engine = _make_engine(rest=rest, away_grace_s=0.05)
|
||||
engine.on_pre_gateway_dispatch()
|
||||
time.sleep(0.2)
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
"""
|
||||
WV-002: REST-Exception-Logging verfeinern (_rest_set_status).
|
||||
|
||||
Tests für:
|
||||
- (a) Echter HTTP 429 → Cooldown + korrektes Logging (Typ + Message + Status-Code).
|
||||
- (b) DDP-Timeout-Exception → KEIN Cooldown, korrekte Typ/Status-Logs.
|
||||
- (c) Exception ohne HTTP-Code → kein 429-Cooldown (Phantom-429-Schutz).
|
||||
|
||||
Kern: Cooldown wird NUR bei echtem HTTP 429 (Status-Code-Prüfung) getriggert,
|
||||
nicht bei beliebigen Exceptions mit '429' im Text.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
import urllib.error
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
|
||||
|
||||
from plugin.archivar.presence_engine import PresenceEngine
|
||||
from plugin.adapter import RocketChatRateLimitError
|
||||
|
||||
|
||||
def _make_mock_rest():
|
||||
rest = MagicMock()
|
||||
rest.auth_token = "test-token"
|
||||
rest.user_id = "test-user"
|
||||
rest._request = MagicMock()
|
||||
return rest
|
||||
|
||||
|
||||
def _make_engine(rest):
|
||||
return PresenceEngine(rest=rest, use_ddp=False)
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# (a) Echter HTTP 429 → Cooldown + korrektes Logging
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestReal429Cooldown:
|
||||
def test_http_error_429_triggers_cooldown(self):
|
||||
"""Echter HTTPError(429) → Cooldown gesetzt, Telemetrie 429 inkrementiert."""
|
||||
rest = _make_mock_rest()
|
||||
rest._request = MagicMock(
|
||||
side_effect=urllib.error.HTTPError(
|
||||
"https://rocketchat/api/v1/users.setStatus", 429,
|
||||
"Too Many Requests", {}, None,
|
||||
)
|
||||
)
|
||||
engine = _make_engine(rest)
|
||||
|
||||
result = engine._rest_set_status("online", "")
|
||||
|
||||
assert result is False
|
||||
assert engine._telemetry_rest_429 == 1
|
||||
assert engine._telemetry_rest_errors == 0
|
||||
# Cooldown wurde gesetzt (Rückkanal)
|
||||
assert engine._mediator._consecutive_429s == 1
|
||||
assert engine._mediator._rest_cooldown_until > 0.0
|
||||
|
||||
def test_rate_limit_error_triggers_cooldown(self):
|
||||
"""RocketChatRateLimitError → Cooldown gesetzt (per Definition 429)."""
|
||||
rest = _make_mock_rest()
|
||||
rest._request = MagicMock(side_effect=RocketChatRateLimitError("HTTP 429"))
|
||||
engine = _make_engine(rest)
|
||||
|
||||
result = engine._rest_set_status("busy", "arbeitet")
|
||||
|
||||
assert result is False
|
||||
assert engine._telemetry_rest_429 == 1
|
||||
assert engine._mediator._consecutive_429s == 1
|
||||
|
||||
def test_429_logs_type_message_and_status(self):
|
||||
"""429-Log enthält Exception-Typ, Message UND HTTP-Status-Code."""
|
||||
import logging
|
||||
from plugin.archivar import presence_engine as pe
|
||||
rest = _make_mock_rest()
|
||||
rest._request = MagicMock(
|
||||
side_effect=urllib.error.HTTPError(
|
||||
"https://rocketchat/api/v1/users.setStatus", 429,
|
||||
"Too Many Requests", {}, None,
|
||||
)
|
||||
)
|
||||
engine = _make_engine(rest)
|
||||
|
||||
with patch.object(pe.logger, "warning") as mock_warn:
|
||||
engine._rest_set_status("online", "")
|
||||
|
||||
# Mindestens ein Warning-Log mit '429' und 'HTTPError' (Exception-Typ)
|
||||
logged = [str(c) for c in mock_warn.call_args_list]
|
||||
assert any("429" in l for l in logged)
|
||||
assert any("HTTPError" in l for l in logged), (
|
||||
f"Erwartet Exception-Typ 'HTTPError' im Log, bekam: {logged}"
|
||||
)
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# (b) DDP-Timeout-Exception → KEIN Cooldown
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestDDPTimeoutNoCooldown:
|
||||
def test_ddp_timeout_no_cooldown(self):
|
||||
"""DDP-Timeout-Exception → KEIN Cooldown, KEIN 429-Telemetrie."""
|
||||
rest = _make_mock_rest()
|
||||
# DDP-Timeout: Exception mit '429' NICHT im Text, aber ein Timeout-Typ.
|
||||
# Simuliere einen Timeout, der früher fälschlich als 429 klassifiziert
|
||||
# werden konnte (z.B. wenn der Text '429' enthielt).
|
||||
rest._request = MagicMock(side_effect=TimeoutError("DDP timeout after 1.0s"))
|
||||
engine = _make_engine(rest)
|
||||
|
||||
result = engine._rest_set_status("online", "")
|
||||
|
||||
assert result is False
|
||||
assert engine._telemetry_rest_429 == 0
|
||||
assert engine._telemetry_rest_errors >= 1
|
||||
# KEIN Cooldown
|
||||
assert engine._mediator._consecutive_429s == 0
|
||||
assert engine._mediator._rest_cooldown_until == 0.0
|
||||
|
||||
def test_phantom_429_in_text_no_cooldown(self):
|
||||
"""Exception mit '429' im TEXT (aber kein HTTP-Code) → KEIN Cooldown.
|
||||
|
||||
Das ist der Kern des Phantom-429-Bugs: DDP-Timeouts und REST-Token-Errors
|
||||
enthielten '429' im Text und wurden fälschlich als 429 klassifiziert.
|
||||
"""
|
||||
rest = _make_mock_rest()
|
||||
rest._request = MagicMock(
|
||||
side_effect=Exception("REST token error: request 429 rejected")
|
||||
)
|
||||
engine = _make_engine(rest)
|
||||
|
||||
result = engine._rest_set_status("online", "")
|
||||
|
||||
assert result is False
|
||||
assert engine._telemetry_rest_429 == 0
|
||||
assert engine._telemetry_rest_errors >= 1
|
||||
assert engine._mediator._consecutive_429s == 0
|
||||
assert engine._mediator._rest_cooldown_until == 0.0
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# (c) Exception ohne HTTP-Code → kein 429-Cooldown
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestNoHttpCodeNoCooldown:
|
||||
def test_generic_exception_no_cooldown(self):
|
||||
"""Generische Exception ohne HTTP-Code → kein 429-Cooldown."""
|
||||
rest = _make_mock_rest()
|
||||
rest._request = MagicMock(side_effect=ValueError("some error"))
|
||||
engine = _make_engine(rest)
|
||||
|
||||
result = engine._rest_set_status("online", "")
|
||||
|
||||
assert result is False
|
||||
assert engine._telemetry_rest_429 == 0
|
||||
assert engine._mediator._consecutive_429s == 0
|
||||
|
||||
def test_http_500_no_cooldown(self):
|
||||
"""HTTP 500 (kein 429) → kein 429-Cooldown, aber als Error gezählt."""
|
||||
rest = _make_mock_rest()
|
||||
rest._request = MagicMock(
|
||||
side_effect=urllib.error.HTTPError(
|
||||
"https://rocketchat/api/v1/users.setStatus", 500,
|
||||
"Internal Server Error", {}, None,
|
||||
)
|
||||
)
|
||||
engine = _make_engine(rest)
|
||||
|
||||
result = engine._rest_set_status("online", "")
|
||||
|
||||
assert result is False
|
||||
assert engine._telemetry_rest_429 == 0
|
||||
assert engine._mediator._consecutive_429s == 0
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Helper-Unit-Tests: _extract_http_status_code / _is_http_429
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestHttpStatusExtraction:
|
||||
def test_extract_from_httperror(self):
|
||||
exc = urllib.error.HTTPError("url", 429, "Too Many Requests", {}, None)
|
||||
assert PresenceEngine._extract_http_status_code(exc) == 429
|
||||
|
||||
def test_extract_from_rate_limit_error(self):
|
||||
exc = RocketChatRateLimitError("HTTP 429")
|
||||
assert PresenceEngine._extract_http_status_code(exc) == 429
|
||||
|
||||
def test_extract_from_cause_chain(self):
|
||||
cause = urllib.error.HTTPError("url", 429, "Too Many Requests", {}, None)
|
||||
exc = RuntimeError("wrapped")
|
||||
exc.__cause__ = cause
|
||||
assert PresenceEngine._extract_http_status_code(exc) == 429
|
||||
|
||||
def test_extract_none_for_generic(self):
|
||||
exc = ValueError("no code here")
|
||||
assert PresenceEngine._extract_http_status_code(exc) is None
|
||||
|
||||
def test_extract_from_status_code_attr(self):
|
||||
class FakeExc(Exception):
|
||||
status_code = 503
|
||||
assert PresenceEngine._extract_http_status_code(FakeExc()) == 503
|
||||
|
||||
def test_is_http_429_true_for_429(self):
|
||||
assert PresenceEngine._is_http_429(ValueError("x"), 429) is True
|
||||
|
||||
def test_is_http_429_false_for_other(self):
|
||||
assert PresenceEngine._is_http_429(ValueError("x"), 500) is False
|
||||
|
||||
def test_is_http_429_false_for_none(self):
|
||||
assert PresenceEngine._is_http_429(ValueError("429 in text"), None) is False
|
||||
|
||||
def test_is_http_429_true_for_rate_limit_error(self):
|
||||
assert PresenceEngine._is_http_429(RocketChatRateLimitError("x"), None) is True
|
||||
Reference in New Issue
Block a user