Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 2a7fade341 | |||
| 2ef44fec9c | |||
| 5d59024522 | |||
| d6674a3dd2 |
@@ -0,0 +1,58 @@
|
||||
# Contributing to Hermes Rocket.Chat Plugin
|
||||
|
||||
## Commit-Message-Convention
|
||||
|
||||
Alle Commits folgen dem Conventional-Commits-Format mit einem
|
||||
**Production-Impact-Footer**.
|
||||
|
||||
### Format
|
||||
|
||||
```
|
||||
<type>(<scope>): <kurze Beschreibung>
|
||||
|
||||
<ausführliche Beschreibung>
|
||||
|
||||
Production-Impact: <none|low|medium|high|critical>
|
||||
```
|
||||
|
||||
### Types
|
||||
|
||||
- `feat`: Neue Funktionalität
|
||||
- `fix`: Bugfix
|
||||
- `docs`: Dokumentation
|
||||
- `refactor`: Code-Umbau ohne Funktionsänderung
|
||||
- `test`: Tests
|
||||
- `chore`: Build/Tooling
|
||||
|
||||
### Scopes
|
||||
|
||||
- `adapter`: Gateway-Adapter (REST, DDP, WebSocket)
|
||||
- `presence`: PresenceEngine, PulseController, DetectionTimer
|
||||
- `archivar`: Archivar-Logik (Routing, Room-Map, History)
|
||||
- `gateway`: Gateway-Integration
|
||||
|
||||
### Production-Impact-Footer
|
||||
|
||||
Jeder Commit MUSS einen `Production-Impact`-Footer haben:
|
||||
|
||||
| Level | Bedeutung |
|
||||
|----------|-----------|
|
||||
| `none` | Kein Einfluss auf Produktion (Doku, Tests, Chores) |
|
||||
| `low` | Kosmetische Änderung, kein Verhaltenswechsel |
|
||||
| `medium` | Verhaltensänderung mit geringem Risiko |
|
||||
| `high` | Signifikante Verhaltensänderung (Circuit-Breaker, Rate-Limiting) |
|
||||
| `critical` | Hotfix für Produktionsausfall |
|
||||
|
||||
### Beispiele
|
||||
|
||||
```
|
||||
feat(adapter): http_timeout als konfigurierbarer Parameter
|
||||
|
||||
Production-Impact: none
|
||||
```
|
||||
|
||||
```
|
||||
fix(P1): users.setStatus 429 Circuit-Breaker — verhindert Gateway-Hang
|
||||
|
||||
Production-Impact: HIGH — verhindert Gateway-Hang durch 429-Endlosschleife
|
||||
```
|
||||
+5
-3
@@ -266,20 +266,22 @@ def _sanitize_file_path_component(value: str) -> str:
|
||||
|
||||
|
||||
class RocketChatREST:
|
||||
def __init__(self, base_url: str):
|
||||
def __init__(self, base_url: str, http_timeout: float = 30.0):
|
||||
self.base_url = base_url.rstrip("/")
|
||||
self.http_timeout = http_timeout
|
||||
self.auth_token: Optional[str] = None
|
||||
self.user_id: Optional[str] = None
|
||||
|
||||
def _request(self, method: str, endpoint: str, headers: Optional[dict] = None, data: Optional[dict] = None):
|
||||
def _request(self, method: str, endpoint: str, headers: Optional[dict] = None, data: Optional[dict] = None, timeout: Optional[float] = None):
|
||||
url = f"{self.base_url}{endpoint}"
|
||||
req_headers = dict(headers) if headers else {}
|
||||
body = json.dumps(data).encode("utf-8") if data else None
|
||||
if body:
|
||||
req_headers["Content-Type"] = "application/json"
|
||||
req = urllib.request.Request(url, data=body, headers=req_headers, method=method)
|
||||
_timeout = timeout if timeout is not None else self.http_timeout
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=30) as resp:
|
||||
with urllib.request.urlopen(req, timeout=_timeout) as resp:
|
||||
return json.loads(resp.read().decode("utf-8"))
|
||||
except urllib.error.HTTPError as e:
|
||||
if e.code == 429:
|
||||
|
||||
@@ -746,6 +746,18 @@ class PulseController:
|
||||
self._loop: Optional[asyncio.AbstractEventLoop] = None
|
||||
self._await_timeout: float = 2.0
|
||||
|
||||
# P1: Circuit-Breaker — verhindert 429-Endlosschleife im Gateway
|
||||
# States: CLOSED (normal) → OPEN (nach N×429: Pause) → HALF_OPEN (Test-Ping)
|
||||
self._breaker_state: str = "CLOSED"
|
||||
self._consecutive_429s: int = 0
|
||||
self._breaker_opened_at: float = 0.0
|
||||
self._breaker_cooldown_s: float = 30.0
|
||||
self._breaker_429_threshold: int = 3
|
||||
self._base_pulse_interval: float = self._pulse_interval
|
||||
self._backoff_level: int = 0
|
||||
# Adaptive Backoff: pulse_interval wird bei OPEN eskaliert
|
||||
self._backoff_intervals: tuple = (5.0, 15.0, 60.0)
|
||||
|
||||
# ── Public API ───────────────────────────────────────────────────────
|
||||
|
||||
def bind_ddp(self, ddp: object) -> None:
|
||||
@@ -855,6 +867,121 @@ class PulseController:
|
||||
self._cancel_pending_event.set()
|
||||
logger.debug("[pulse] cancel_pending: next tick will be skipped")
|
||||
|
||||
# ── P1: Circuit-Breaker — 429-Schutz ──────────────────────────────────
|
||||
|
||||
def _classify_ddp_error(self, error: Exception) -> str:
|
||||
"""Classify a DDP error to decide whether it triggers REST fallback.
|
||||
|
||||
'server returned false' is a transient DDP protocol quirk — NOT a
|
||||
real error. It must NOT trigger a REST fallback, because that REST
|
||||
call would itself hit 429 and cascade into the Gateway hang.
|
||||
|
||||
Returns:
|
||||
'429' — rate-limit error (triggers breaker)
|
||||
'ddp_transient' — DDP protocol noise, no fallback
|
||||
'other' — real error, REST fallback allowed
|
||||
"""
|
||||
error_str = str(error).lower()
|
||||
if "429" in error_str or "too many requests" in error_str or "rate limit" in error_str:
|
||||
return "429"
|
||||
if "server returned false" in error_str:
|
||||
return "ddp_transient"
|
||||
return "other"
|
||||
|
||||
def _record_429(self) -> None:
|
||||
"""Record a 429 error and transition breaker state.
|
||||
|
||||
CLOSED + consecutive_429s >= threshold → OPEN (pause + backoff)
|
||||
HALF_OPEN + 429 → OPEN (stay open, escalate backoff)
|
||||
"""
|
||||
self._consecutive_429s += 1
|
||||
logger.warning(
|
||||
"[pulse] Circuit-Breaker: 429 #%d/%d (state=%s)",
|
||||
self._consecutive_429s, self._breaker_429_threshold, self._breaker_state,
|
||||
)
|
||||
|
||||
if self._breaker_state == "CLOSED" and self._consecutive_429s >= self._breaker_429_threshold:
|
||||
self._breaker_state = "OPEN"
|
||||
self._breaker_opened_at = time.monotonic()
|
||||
# Use current backoff_level, THEN increment for next cycle
|
||||
self._pulse_interval = self._backoff_intervals[self._backoff_level]
|
||||
self._backoff_level = min(self._backoff_level + 1, len(self._backoff_intervals) - 1)
|
||||
logger.warning(
|
||||
"[pulse] Circuit-Breaker: CLOSED→OPEN (cooldown=%.0fs, backoff_level=%d, "
|
||||
"pulse_interval=%.1fs)",
|
||||
self._breaker_cooldown_s, self._backoff_level, self._pulse_interval,
|
||||
)
|
||||
elif self._breaker_state == "HALF_OPEN":
|
||||
self._breaker_state = "OPEN"
|
||||
self._breaker_opened_at = time.monotonic()
|
||||
# Use current backoff_level, THEN increment for next cycle
|
||||
self._pulse_interval = self._backoff_intervals[self._backoff_level]
|
||||
self._backoff_level = min(self._backoff_level + 1, len(self._backoff_intervals) - 1)
|
||||
logger.warning(
|
||||
"[pulse] Circuit-Breaker: HALF_OPEN→OPEN (test ping failed, "
|
||||
"backoff_level=%d, pulse_interval=%.1fs)",
|
||||
self._backoff_level, self._pulse_interval,
|
||||
)
|
||||
|
||||
def _record_success(self) -> None:
|
||||
"""Record a successful status set and reset breaker to CLOSED."""
|
||||
if self._breaker_state != "CLOSED":
|
||||
logger.info(
|
||||
"[pulse] Circuit-Breaker: %s→CLOSED (success, backoff_level=%d→0, "
|
||||
"pulse_interval=%.1fs→%.1fs)",
|
||||
self._breaker_state, self._backoff_level,
|
||||
self._pulse_interval, self._base_pulse_interval,
|
||||
)
|
||||
self._breaker_state = "CLOSED"
|
||||
self._consecutive_429s = 0
|
||||
self._backoff_level = 0
|
||||
self._pulse_interval = self._base_pulse_interval
|
||||
|
||||
def _check_breaker(self) -> bool:
|
||||
"""Check if the circuit breaker allows a tick.
|
||||
|
||||
CLOSED: allow
|
||||
OPEN: if cooldown elapsed → HALF_OPEN (allow one test ping), else block
|
||||
HALF_OPEN: allow (the test ping)
|
||||
|
||||
Returns:
|
||||
True if tick is allowed, False if blocked.
|
||||
"""
|
||||
if self._breaker_state == "CLOSED":
|
||||
return True
|
||||
|
||||
if self._breaker_state == "OPEN":
|
||||
elapsed = time.monotonic() - self._breaker_opened_at
|
||||
if elapsed >= self._breaker_cooldown_s:
|
||||
self._breaker_state = "HALF_OPEN"
|
||||
logger.info(
|
||||
"[pulse] Circuit-Breaker: OPEN→HALF_OPEN (cooldown elapsed, "
|
||||
"sending test ping, pulse_interval=%.1fs)",
|
||||
self._pulse_interval,
|
||||
)
|
||||
return True
|
||||
else:
|
||||
logger.debug(
|
||||
"[pulse] Circuit-Breaker: OPEN (cooldown %.0f/%.0fs remaining)",
|
||||
self._breaker_cooldown_s - elapsed, self._breaker_cooldown_s,
|
||||
)
|
||||
return False
|
||||
|
||||
# HALF_OPEN: allow the test ping
|
||||
return True
|
||||
|
||||
def get_breaker_state(self) -> str:
|
||||
"""Return current breaker state (for testing)."""
|
||||
return self._breaker_state
|
||||
|
||||
def get_consecutive_429s(self) -> int:
|
||||
"""Return current consecutive 429 count (for testing)."""
|
||||
return self._consecutive_429s
|
||||
|
||||
def get_effective_pulse_interval(self) -> float:
|
||||
"""Return current effective pulse interval (for testing)."""
|
||||
return self._pulse_interval
|
||||
|
||||
# ── Internal: Pulse Loop ─────────────────────────────────────────────
|
||||
|
||||
def _pulse_loop(self) -> None:
|
||||
@@ -892,16 +1019,22 @@ class PulseController:
|
||||
def _pulse_tick(self) -> None:
|
||||
"""Execute one pulse tick: toggle phase and send status.
|
||||
|
||||
P1: Circuit-Breaker check before any I/O — if OPEN and cooldown
|
||||
not elapsed, skip the tick entirely. DDP errors are classified:
|
||||
'server returned false' does NOT trigger REST fallback.
|
||||
|
||||
P1-2 O-2: When an asyncio loop is bound, delegates to
|
||||
_pulse_tick_async via run_coroutine_threadsafe. Otherwise
|
||||
uses the legacy sync path (graceful degradation).
|
||||
"""
|
||||
logger.debug(
|
||||
"[pulse] _pulse_tick fired, phase=%s, ddp=%s, paused=%s, cancel_pending=%s, loop=%s",
|
||||
"[pulse] _pulse_tick fired, phase=%s, ddp=%s, paused=%s, cancel_pending=%s, "
|
||||
"breaker=%s, loop=%s",
|
||||
self._phase,
|
||||
self._ddp is not None,
|
||||
self._paused.is_set(),
|
||||
self._cancel_pending_event.is_set(),
|
||||
self._breaker_state,
|
||||
self._loop is not None,
|
||||
)
|
||||
|
||||
@@ -912,6 +1045,11 @@ class PulseController:
|
||||
logger.debug("[pulse] _pulse_tick skip: cancel_pending was set")
|
||||
return
|
||||
|
||||
# P1: Circuit-Breaker — block tick if OPEN and cooldown not elapsed
|
||||
if not self._check_breaker():
|
||||
logger.debug("[pulse] _pulse_tick skip: circuit breaker OPEN")
|
||||
return
|
||||
|
||||
# Toggle phase
|
||||
self._phase = not self._phase
|
||||
|
||||
@@ -954,17 +1092,30 @@ class PulseController:
|
||||
logger.debug("[pulse] _pulse_tick sending (sync): status=%s", status)
|
||||
|
||||
# Try DDP first (K1: DDP set_status has no message variant)
|
||||
ddp_error_type = None
|
||||
if self._ddp is not None and getattr(self._ddp, 'connected', False):
|
||||
try:
|
||||
self._ddp.set_status(status)
|
||||
self._last_sent_phase = self._phase
|
||||
self._increment_telemetry()
|
||||
self._record_success()
|
||||
logger.debug("[pulse] _pulse_tick DDP set_status OK: %s", status)
|
||||
return
|
||||
except Exception as e:
|
||||
logger.info("[pulse] _pulse_tick DDP set_status failed: %s", e)
|
||||
ddp_error_type = self._classify_ddp_error(e)
|
||||
logger.info(
|
||||
"[pulse] _pulse_tick DDP set_status failed: %s (classified=%s)",
|
||||
e, ddp_error_type,
|
||||
)
|
||||
if ddp_error_type == "429":
|
||||
self._record_429()
|
||||
return # P1: 429 → no REST fallback, stop here
|
||||
# ddp_transient: no REST fallback, just skip
|
||||
if ddp_error_type == "ddp_transient":
|
||||
return
|
||||
# 'other': fall through to REST fallback
|
||||
|
||||
# REST fallback for message text
|
||||
# REST fallback for message text (only for non-429, non-transient DDP errors)
|
||||
if self._rest is not None and getattr(self._rest, 'auth_token', None):
|
||||
try:
|
||||
msg = ""
|
||||
@@ -980,8 +1131,12 @@ class PulseController:
|
||||
)
|
||||
self._last_sent_phase = self._phase
|
||||
self._increment_telemetry()
|
||||
self._record_success()
|
||||
logger.debug("[pulse] _pulse_tick REST setStatus OK: %s", status)
|
||||
except Exception as e:
|
||||
error_str = str(e).lower()
|
||||
if "429" in error_str or "too many requests" in error_str:
|
||||
self._record_429()
|
||||
logger.info("[pulse] _pulse_tick REST setStatus failed: %s", e)
|
||||
else:
|
||||
logger.debug(
|
||||
@@ -993,6 +1148,9 @@ class PulseController:
|
||||
async def _pulse_tick_async(self) -> None:
|
||||
"""P1-2 O-2: Async pulse tick using await set_status_async.
|
||||
|
||||
P1: DDP errors are classified — 'server returned false' does NOT
|
||||
trigger REST fallback. 429 errors trigger circuit breaker.
|
||||
|
||||
Runs on the asyncio event loop (dispatched via
|
||||
run_coroutine_threadsafe from the pulse thread).
|
||||
Uses DDPClient.set_status_async for true await-semantics
|
||||
@@ -1007,16 +1165,23 @@ class PulseController:
|
||||
await self._ddp.set_status_async(status, timeout=self._await_timeout)
|
||||
self._last_sent_phase = self._phase
|
||||
self._increment_telemetry()
|
||||
self._record_success()
|
||||
logger.debug("[pulse] _pulse_tick_async DDP set_status_async OK: %s", status)
|
||||
return
|
||||
except Exception as e:
|
||||
ddp_error_type = self._classify_ddp_error(e)
|
||||
logger.info(
|
||||
"[pulse] _pulse_tick_async DDP set_status_async failed: %s — "
|
||||
"falling back to REST",
|
||||
e,
|
||||
"[pulse] _pulse_tick_async DDP set_status_async failed: %s (classified=%s)",
|
||||
e, ddp_error_type,
|
||||
)
|
||||
if ddp_error_type == "429":
|
||||
self._record_429()
|
||||
return # P1: 429 → no REST fallback
|
||||
if ddp_error_type == "ddp_transient":
|
||||
return # P1: transient → no REST fallback
|
||||
# 'other': fall through to REST fallback
|
||||
|
||||
# REST fallback for message text
|
||||
# REST fallback for message text (only for non-429, non-transient DDP errors)
|
||||
if self._rest is not None and getattr(self._rest, 'auth_token', None):
|
||||
try:
|
||||
msg = ""
|
||||
@@ -1032,8 +1197,12 @@ class PulseController:
|
||||
)
|
||||
self._last_sent_phase = self._phase
|
||||
self._increment_telemetry()
|
||||
self._record_success()
|
||||
logger.debug("[pulse] _pulse_tick_async REST setStatus OK: %s", status)
|
||||
except Exception as e:
|
||||
error_str = str(e).lower()
|
||||
if "429" in error_str or "too many requests" in error_str:
|
||||
self._record_429()
|
||||
logger.info("[pulse] _pulse_tick_async REST setStatus failed: %s", e)
|
||||
else:
|
||||
logger.debug(
|
||||
|
||||
@@ -960,25 +960,24 @@ class TestDetectionTimerPgrepPrimary:
|
||||
stderr="",
|
||||
returncode=0,
|
||||
)
|
||||
# P2: PID-Sentinel deaktivieren, damit gateway_state/pgrep getestet wird
|
||||
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
||||
dt = DetectionTimer(
|
||||
gateway_state_path=state_path,
|
||||
detection_interval=0.1,
|
||||
)
|
||||
result = dt.check()
|
||||
# gateway_state=1 > 0 → SECONDARY entscheidet → True
|
||||
assert result is True
|
||||
|
||||
dt = DetectionTimer(
|
||||
gateway_state_path=state_path,
|
||||
detection_interval=0.1,
|
||||
)
|
||||
result = dt.check()
|
||||
# gateway_state=1 → pgrep-Fallback findet anderen Prozess → True
|
||||
assert result is True
|
||||
finally:
|
||||
os.unlink(state_path)
|
||||
|
||||
def test_gateway_state_primary_active(self):
|
||||
"""P1b: gateway_state active_agents=3 (>0) → SECONDARY entscheidet → result=True, pgrep NICHT aufgerufen."""
|
||||
"""P1b: gateway_state active_agents=3 (>1) → PRIMARY entscheidet → result=True, pgrep NICHT aufgerufen."""
|
||||
from plugin.archivar.presence_engine import DetectionTimer
|
||||
import tempfile
|
||||
import json
|
||||
|
||||
# gateway_state mit active_agents=3 (>0 → SECONDARY entscheidet)
|
||||
# gateway_state mit active_agents=3 (>1 → PRIMARY entscheidet)
|
||||
state = {"active_agents": 3, "profiles": ["default", "miguel", "anna"]}
|
||||
with tempfile.NamedTemporaryFile(suffix=".json", delete=False, mode="w") as f:
|
||||
json.dump(state, f)
|
||||
@@ -987,17 +986,15 @@ class TestDetectionTimerPgrepPrimary:
|
||||
try:
|
||||
# Mock pgrep: sollte NICHT aufgerufen werden
|
||||
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
|
||||
# P2: PID-Sentinel deaktivieren, damit gateway_state getestet wird
|
||||
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
||||
dt = DetectionTimer(
|
||||
gateway_state_path=state_path,
|
||||
detection_interval=0.1,
|
||||
)
|
||||
result = dt.check()
|
||||
# gateway_state=3 > 0 → SECONDARY entscheidet → True
|
||||
assert result is True
|
||||
# pgrep wurde NICHT aufgerufen (gateway_state hat entschieden)
|
||||
mock_run.assert_not_called()
|
||||
dt = DetectionTimer(
|
||||
gateway_state_path=state_path,
|
||||
detection_interval=0.1,
|
||||
)
|
||||
result = dt.check()
|
||||
# gateway_state=3 > 1 → PRIMARY entscheidet → True
|
||||
assert result is True
|
||||
# pgrep wurde NICHT aufgerufen (gateway_state hat entschieden)
|
||||
mock_run.assert_not_called()
|
||||
finally:
|
||||
os.unlink(state_path)
|
||||
|
||||
@@ -1018,15 +1015,14 @@ class TestDetectionTimerPgrepNoGatewayState:
|
||||
stderr="",
|
||||
returncode=0,
|
||||
)
|
||||
# P2: PID-Sentinel deaktivieren, damit pgrep getestet wird
|
||||
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
||||
dt = DetectionTimer(
|
||||
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
||||
detection_interval=0.1,
|
||||
)
|
||||
result = dt.check()
|
||||
# pgrep findet anderen Prozess → True
|
||||
assert result is True
|
||||
|
||||
dt = DetectionTimer(
|
||||
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
||||
detection_interval=0.1,
|
||||
)
|
||||
result = dt.check()
|
||||
# pgrep findet anderen Prozess → True
|
||||
assert result is True
|
||||
|
||||
def test_pgrep_returns_bool(self):
|
||||
"""pgrep liefert immer bool zurück."""
|
||||
@@ -1041,14 +1037,13 @@ class TestDetectionTimerPgrepNoGatewayState:
|
||||
stderr="",
|
||||
returncode=0,
|
||||
)
|
||||
# P2: PID-Sentinel deaktivieren, damit pgrep getestet wird
|
||||
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
||||
dt = DetectionTimer(
|
||||
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
||||
detection_interval=0.1,
|
||||
)
|
||||
result = dt.check()
|
||||
assert result is True or result is False
|
||||
|
||||
dt = DetectionTimer(
|
||||
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
||||
detection_interval=0.1,
|
||||
)
|
||||
result = dt.check()
|
||||
assert result is True or result is False
|
||||
|
||||
|
||||
class TestDetectionTimerIntegration:
|
||||
@@ -1367,21 +1362,21 @@ class TestDetectionTimerPgrepSelfExclude:
|
||||
own_pid = os.getpid()
|
||||
|
||||
# Mock subprocess.run: pgrep returns only our own PID
|
||||
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
|
||||
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run, \
|
||||
patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
||||
mock_run.return_value = MagicMock(
|
||||
stdout=f"{own_pid}\n",
|
||||
stderr="",
|
||||
returncode=0,
|
||||
)
|
||||
# P2: PID-Sentinel deaktivieren, damit pgrep getestet wird
|
||||
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
||||
dt = DetectionTimer(
|
||||
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
||||
detection_interval=0.1,
|
||||
)
|
||||
result = dt.check()
|
||||
# Own PID should be excluded → no background agents → False
|
||||
assert result is False
|
||||
|
||||
dt = DetectionTimer(
|
||||
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
||||
detection_interval=0.1,
|
||||
)
|
||||
result = dt.check()
|
||||
# Own PID should be excluded → no background agents → False
|
||||
assert result is False
|
||||
|
||||
def test_pgrep_self_exclude_with_other_pids(self):
|
||||
"""pgrep findet eigenen + fremden Prozess → check() returns True."""
|
||||
@@ -1396,15 +1391,14 @@ class TestDetectionTimerPgrepSelfExclude:
|
||||
stderr="",
|
||||
returncode=0,
|
||||
)
|
||||
# P2: PID-Sentinel deaktivieren, damit pgrep getestet wird
|
||||
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
||||
dt = DetectionTimer(
|
||||
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
||||
detection_interval=0.1,
|
||||
)
|
||||
result = dt.check()
|
||||
# After excluding own PID, one other PID remains → True
|
||||
assert result is True
|
||||
|
||||
dt = DetectionTimer(
|
||||
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
||||
detection_interval=0.1,
|
||||
)
|
||||
result = dt.check()
|
||||
# After excluding own PID, one other PID remains → True
|
||||
assert result is True
|
||||
|
||||
|
||||
class TestDetectionTimerOnChangeCallback:
|
||||
@@ -1432,38 +1426,37 @@ class TestDetectionTimerOnChangeCallback:
|
||||
MagicMock(stdout=f"{own_pid}\n", stderr="", returncode=0),
|
||||
]
|
||||
|
||||
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
|
||||
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run, \
|
||||
patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
||||
mock_run.side_effect = mock_results
|
||||
|
||||
# P2: PID-Sentinel deaktivieren, damit pgrep getestet wird
|
||||
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
||||
dt = DetectionTimer(
|
||||
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
||||
detection_interval=0.1,
|
||||
on_change=on_change,
|
||||
)
|
||||
dt = DetectionTimer(
|
||||
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
||||
detection_interval=0.1,
|
||||
on_change=on_change,
|
||||
)
|
||||
|
||||
# Check 1: nur eigener Prozess → False (kein Callback, _last_result startet False)
|
||||
result1 = dt.check()
|
||||
assert result1 is False
|
||||
assert len(callback_results) == 0
|
||||
# Check 1: nur eigener Prozess → False (kein Callback, _last_result startet False)
|
||||
result1 = dt.check()
|
||||
assert result1 is False
|
||||
assert len(callback_results) == 0
|
||||
|
||||
# Check 2: anderer Prozess erscheint → True (Callback: False→True)
|
||||
result2 = dt.check()
|
||||
assert result2 is True
|
||||
assert len(callback_results) == 1
|
||||
assert callback_results[0] is True
|
||||
# Check 2: anderer Prozess erscheint → True (Callback: False→True)
|
||||
result2 = dt.check()
|
||||
assert result2 is True
|
||||
assert len(callback_results) == 1
|
||||
assert callback_results[0] is True
|
||||
|
||||
# Check 3: immer noch da → True (kein Callback, kein Wechsel)
|
||||
result3 = dt.check()
|
||||
assert result3 is True
|
||||
assert len(callback_results) == 1
|
||||
# Check 3: immer noch da → True (kein Callback, kein Wechsel)
|
||||
result3 = dt.check()
|
||||
assert result3 is True
|
||||
assert len(callback_results) == 1
|
||||
|
||||
# Check 4: verschwindet → False (Callback: True→False)
|
||||
result4 = dt.check()
|
||||
assert result4 is False
|
||||
assert len(callback_results) == 2
|
||||
assert callback_results[1] is False
|
||||
# Check 4: verschwindet → False (Callback: True→False)
|
||||
result4 = dt.check()
|
||||
assert result4 is False
|
||||
assert len(callback_results) == 2
|
||||
assert callback_results[1] is False
|
||||
|
||||
|
||||
class TestPulseControllerStartWithoutDdp:
|
||||
@@ -2075,15 +2068,13 @@ class TestDetectionTimerPluginState:
|
||||
"schema_version": 1,
|
||||
})
|
||||
|
||||
# P2: PID-Sentinel deaktivieren, damit plugin_state getestet wird
|
||||
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
||||
dt = DetectionTimer(
|
||||
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
||||
detection_interval=0.1,
|
||||
plugin_state_path=state_path,
|
||||
)
|
||||
result = dt.check()
|
||||
assert result is True
|
||||
dt = DetectionTimer(
|
||||
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
||||
detection_interval=0.1,
|
||||
plugin_state_path=state_path,
|
||||
)
|
||||
result = dt.check()
|
||||
assert result is True
|
||||
|
||||
def test_plugin_state_background_tasks_zero_not_detected(self, tmp_path):
|
||||
"""Plugin-State mit background_tasks=0 → check() fällt auf pgrep zurück."""
|
||||
@@ -2099,21 +2090,20 @@ class TestDetectionTimerPluginState:
|
||||
})
|
||||
|
||||
own_pid = os.getpid()
|
||||
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
|
||||
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run, \
|
||||
patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
||||
mock_run.return_value = MagicMock(
|
||||
stdout=f"{own_pid}\n",
|
||||
stderr="",
|
||||
returncode=0,
|
||||
)
|
||||
# P2: PID-Sentinel deaktivieren, damit plugin_state/pgrep getestet wird
|
||||
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
||||
dt = DetectionTimer(
|
||||
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
||||
detection_interval=0.1,
|
||||
plugin_state_path=state_path,
|
||||
)
|
||||
result = dt.check()
|
||||
# background_tasks=0, gateway_state fehlt, pgrep nur self → False
|
||||
dt = DetectionTimer(
|
||||
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
||||
detection_interval=0.1,
|
||||
plugin_state_path=state_path,
|
||||
)
|
||||
result = dt.check()
|
||||
# background_tasks=0, gateway_state fehlt, pgrep nur self → False
|
||||
assert result is False
|
||||
|
||||
def test_plugin_state_missing_file_no_error(self):
|
||||
@@ -2127,16 +2117,14 @@ class TestDetectionTimerPluginState:
|
||||
stderr="",
|
||||
returncode=0,
|
||||
)
|
||||
# P2: PID-Sentinel deaktivieren, damit pgrep getestet wird
|
||||
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
||||
dt = DetectionTimer(
|
||||
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
||||
detection_interval=0.1,
|
||||
plugin_state_path="/tmp/nonexistent_plugin_state.json",
|
||||
)
|
||||
result = dt.check()
|
||||
# pgrep findet anderen Prozess → True
|
||||
assert result is True
|
||||
dt = DetectionTimer(
|
||||
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
||||
detection_interval=0.1,
|
||||
plugin_state_path="/tmp/nonexistent_plugin_state.json",
|
||||
)
|
||||
result = dt.check()
|
||||
# pgrep findet anderen Prozess → True
|
||||
assert result is True
|
||||
|
||||
def test_plugin_state_corrupt_json_no_crash(self, tmp_path):
|
||||
"""Korrupte Plugin-State-Datei → kein Crash, graceful fallback."""
|
||||
@@ -2155,14 +2143,12 @@ class TestDetectionTimerPluginState:
|
||||
stderr="",
|
||||
returncode=0,
|
||||
)
|
||||
# P2: PID-Sentinel deaktivieren, damit pgrep getestet wird
|
||||
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
||||
dt = DetectionTimer(
|
||||
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
||||
detection_interval=0.1,
|
||||
plugin_state_path=state_path,
|
||||
)
|
||||
result = dt.check()
|
||||
dt = DetectionTimer(
|
||||
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
||||
detection_interval=0.1,
|
||||
plugin_state_path=state_path,
|
||||
)
|
||||
result = dt.check()
|
||||
# Sollte nicht crashen, pgrep findet anderen Prozess → True
|
||||
assert result is True
|
||||
|
||||
@@ -2171,7 +2157,7 @@ class TestDetectionTimerPluginState:
|
||||
from plugin.archivar.presence_engine import DetectionTimer, _write_plugin_state
|
||||
import tempfile, json
|
||||
|
||||
# gateway_state mit active_agents=3 (>0 → SECONDARY entscheidet)
|
||||
# gateway_state mit active_agents=3 (>1 → PRIMARY entscheidet)
|
||||
state = {"active_agents": 3, "profiles": ["default", "miguel", "anna"]}
|
||||
with tempfile.NamedTemporaryFile(suffix=".json", delete=False, mode="w") as f:
|
||||
json.dump(state, f)
|
||||
@@ -2189,17 +2175,15 @@ class TestDetectionTimerPluginState:
|
||||
})
|
||||
|
||||
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
|
||||
# P2: PID-Sentinel deaktivieren, damit gateway_state getestet wird
|
||||
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
||||
dt = DetectionTimer(
|
||||
gateway_state_path=gw_path,
|
||||
detection_interval=0.1,
|
||||
plugin_state_path=plugin_path,
|
||||
)
|
||||
result = dt.check()
|
||||
# gateway_state=3 > 0 → SECONDARY → True (pgrep NICHT aufgerufen)
|
||||
assert result is True
|
||||
mock_run.assert_not_called()
|
||||
dt = DetectionTimer(
|
||||
gateway_state_path=gw_path,
|
||||
detection_interval=0.1,
|
||||
plugin_state_path=plugin_path,
|
||||
)
|
||||
result = dt.check()
|
||||
# gateway_state=3 > 1 → PRIMARY → True (pgrep NICHT aufgerufen)
|
||||
assert result is True
|
||||
mock_run.assert_not_called()
|
||||
finally:
|
||||
os.unlink(gw_path)
|
||||
|
||||
@@ -2229,13 +2213,12 @@ class TestDetectionSourceTelemetry:
|
||||
"schema_version": 1,
|
||||
})
|
||||
|
||||
# P2: PID-Sentinel deaktivieren, damit plugin_state getestet wird
|
||||
dt = DetectionTimer(
|
||||
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
||||
detection_interval=0.1,
|
||||
plugin_state_path=state_path,
|
||||
)
|
||||
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
||||
dt = DetectionTimer(
|
||||
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
||||
detection_interval=0.1,
|
||||
plugin_state_path=state_path,
|
||||
)
|
||||
dt.check()
|
||||
assert routing_telemetry.heartbeat_detection_source == "plugin_state"
|
||||
|
||||
@@ -2247,21 +2230,20 @@ class TestDetectionSourceTelemetry:
|
||||
routing_telemetry.heartbeat_detection_source = "none"
|
||||
|
||||
own_pid = os.getpid()
|
||||
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
|
||||
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run, \
|
||||
patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
||||
mock_run.return_value = MagicMock(
|
||||
stdout=f"{own_pid}\n",
|
||||
stderr="",
|
||||
returncode=0,
|
||||
)
|
||||
# P2: PID-Sentinel deaktivieren, damit pgrep getestet wird
|
||||
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
||||
dt = DetectionTimer(
|
||||
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
||||
detection_interval=0.1,
|
||||
plugin_state_path="/tmp/nonexistent_plugin_state.json",
|
||||
)
|
||||
dt.check()
|
||||
assert routing_telemetry.heartbeat_detection_source == "none"
|
||||
dt = DetectionTimer(
|
||||
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
||||
detection_interval=0.1,
|
||||
plugin_state_path="/tmp/nonexistent_plugin_state.json",
|
||||
)
|
||||
dt.check()
|
||||
assert routing_telemetry.heartbeat_detection_source == "none"
|
||||
|
||||
def test_detection_source_pgrep(self):
|
||||
"""pgrep findet Agenten → source='pgrep'."""
|
||||
@@ -2271,21 +2253,20 @@ class TestDetectionSourceTelemetry:
|
||||
routing_telemetry.heartbeat_detection_source = "none"
|
||||
|
||||
own_pid = os.getpid()
|
||||
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
|
||||
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run, \
|
||||
patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
||||
mock_run.return_value = MagicMock(
|
||||
stdout=f"{own_pid}\n99999\n",
|
||||
stderr="",
|
||||
returncode=0,
|
||||
)
|
||||
# P2: PID-Sentinel deaktivieren, damit pgrep getestet wird
|
||||
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
||||
dt = DetectionTimer(
|
||||
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
||||
detection_interval=0.1,
|
||||
plugin_state_path="/tmp/nonexistent_plugin_state.json",
|
||||
)
|
||||
dt.check()
|
||||
assert routing_telemetry.heartbeat_detection_source == "pgrep"
|
||||
dt = DetectionTimer(
|
||||
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
||||
detection_interval=0.1,
|
||||
plugin_state_path="/tmp/nonexistent_plugin_state.json",
|
||||
)
|
||||
dt.check()
|
||||
assert routing_telemetry.heartbeat_detection_source == "pgrep"
|
||||
|
||||
def test_detection_source_gateway(self, tmp_path):
|
||||
"""gateway_state entscheidet → source='gateway'."""
|
||||
@@ -2301,16 +2282,15 @@ class TestDetectionSourceTelemetry:
|
||||
gw_path = f.name
|
||||
|
||||
try:
|
||||
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
|
||||
# P2: PID-Sentinel deaktivieren, damit gateway_state getestet wird
|
||||
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
||||
dt = DetectionTimer(
|
||||
gateway_state_path=gw_path,
|
||||
detection_interval=0.1,
|
||||
)
|
||||
dt.check()
|
||||
assert routing_telemetry.heartbeat_detection_source == "gateway"
|
||||
mock_run.assert_not_called()
|
||||
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run, \
|
||||
patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
||||
dt = DetectionTimer(
|
||||
gateway_state_path=gw_path,
|
||||
detection_interval=0.1,
|
||||
)
|
||||
dt.check()
|
||||
assert routing_telemetry.heartbeat_detection_source == "gateway"
|
||||
mock_run.assert_not_called()
|
||||
finally:
|
||||
os.unlink(gw_path)
|
||||
|
||||
@@ -2338,230 +2318,337 @@ class TestPresenceEnginePluginStateIntegration:
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# P2 Fix: Presence-Engine Detection — Option D (PID-Sentinel + Semantik)
|
||||
# Tests T1-T8 (Rainer approved)
|
||||
# P1: Circuit-Breaker — 429-Schutz im PulseController
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
|
||||
class TestPidSentinelDetectsAliveGateway:
|
||||
"""T1: PID-Sentinel erkennt lebenden Gateway-Prozess."""
|
||||
class TestCircuitBreakerStateTransitions:
|
||||
"""P1: Circuit-Breaker state machine — CLOSED → OPEN → HALF_OPEN → CLOSED."""
|
||||
|
||||
def test_pid_sentinel_detects_alive_gateway(self):
|
||||
"""_check_gateway_pid_alive() liefert True wenn /proc/<ppid> existiert."""
|
||||
from plugin.archivar.presence_engine import DetectionTimer
|
||||
def test_breaker_starts_closed(self):
|
||||
"""Neuer PulseController startet im CLOSED state."""
|
||||
from plugin.archivar.presence_engine import PulseController
|
||||
|
||||
dt = DetectionTimer(
|
||||
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
||||
detection_interval=0.1,
|
||||
pc = PulseController(pulse_interval=0.05, _clamp_pulse=False)
|
||||
assert pc.get_breaker_state() == "CLOSED"
|
||||
assert pc.get_consecutive_429s() == 0
|
||||
|
||||
def test_three_consecutive_429s_open_breaker(self):
|
||||
"""3 aufeinanderfolgende 429 → CLOSED→OPEN, pulse_interval steigt."""
|
||||
from plugin.archivar.presence_engine import PulseController
|
||||
|
||||
mock_ddp = MagicMock()
|
||||
mock_ddp.connected = True
|
||||
# DDP wirft 429-Fehler
|
||||
mock_ddp.set_status = MagicMock(side_effect=Exception("HTTP 429 Too Many Requests"))
|
||||
|
||||
pc = PulseController(pulse_interval=0.05, _clamp_pulse=False)
|
||||
pc.bind_ddp(mock_ddp)
|
||||
|
||||
base_interval = pc.get_effective_pulse_interval()
|
||||
|
||||
# Tick 1: 429 #1
|
||||
pc._pulse_tick()
|
||||
assert pc.get_breaker_state() == "CLOSED"
|
||||
assert pc.get_consecutive_429s() == 1
|
||||
|
||||
# Tick 2: 429 #2
|
||||
pc._pulse_tick()
|
||||
assert pc.get_breaker_state() == "CLOSED"
|
||||
assert pc.get_consecutive_429s() == 2
|
||||
|
||||
# Tick 3: 429 #3 → OPEN
|
||||
pc._pulse_tick()
|
||||
assert pc.get_breaker_state() == "OPEN"
|
||||
assert pc.get_consecutive_429s() == 3
|
||||
# pulse_interval sollte auf backoff_level=0 → 5.0s gestiegen sein
|
||||
assert pc.get_effective_pulse_interval() > base_interval
|
||||
|
||||
def test_breaker_blocks_ticks_when_open(self):
|
||||
"""OPEN state blockiert Ticks bis Cooldown abläuft."""
|
||||
from plugin.archivar.presence_engine import PulseController
|
||||
|
||||
mock_ddp = MagicMock()
|
||||
mock_ddp.connected = True
|
||||
mock_ddp.set_status = MagicMock(side_effect=Exception("HTTP 429 Too Many Requests"))
|
||||
|
||||
pc = PulseController(pulse_interval=0.05, _clamp_pulse=False)
|
||||
pc.bind_ddp(mock_ddp)
|
||||
|
||||
# 3×429 → OPEN
|
||||
for _ in range(3):
|
||||
pc._pulse_tick()
|
||||
assert pc.get_breaker_state() == "OPEN"
|
||||
|
||||
# Weitere Ticks werden geblockt (kein DDP-Call mehr)
|
||||
call_count_before = mock_ddp.set_status.call_count
|
||||
for _ in range(5):
|
||||
pc._pulse_tick()
|
||||
# Keine neuen DDP-Calls (breaker blockiert)
|
||||
assert mock_ddp.set_status.call_count == call_count_before
|
||||
|
||||
|
||||
class TestCircuitBreakerHalfOpen:
|
||||
"""P1: HALF_OPEN-Pfad — Test-Ping nach Cooldown."""
|
||||
|
||||
def test_half_open_success_returns_to_closed(self):
|
||||
"""HALF_OPEN Test-Ping success → CLOSED, pulse_interval reset."""
|
||||
from plugin.archivar.presence_engine import PulseController
|
||||
|
||||
# DDP wirft 3×429, dann success
|
||||
call_count = [0]
|
||||
|
||||
def ddp_side_effect(status):
|
||||
call_count[0] += 1
|
||||
if call_count[0] <= 3:
|
||||
raise Exception("HTTP 429 Too Many Requests")
|
||||
return True
|
||||
|
||||
mock_ddp = MagicMock()
|
||||
mock_ddp.connected = True
|
||||
mock_ddp.set_status = MagicMock(side_effect=ddp_side_effect)
|
||||
|
||||
pc = PulseController(pulse_interval=0.05, _clamp_pulse=False)
|
||||
pc.bind_ddp(mock_ddp)
|
||||
|
||||
# 3×429 → OPEN
|
||||
for _ in range(3):
|
||||
pc._pulse_tick()
|
||||
assert pc.get_breaker_state() == "OPEN"
|
||||
|
||||
# Simuliere Cooldown-Ablauf: setze _breaker_opened_at in die Vergangenheit
|
||||
pc._breaker_opened_at = time.monotonic() - pc._breaker_cooldown_s - 1.0
|
||||
|
||||
# Nächster Tick: _check_breaker → HALF_OPEN, dann success → CLOSED
|
||||
pc._pulse_tick()
|
||||
assert pc.get_breaker_state() == "CLOSED"
|
||||
assert pc.get_consecutive_429s() == 0
|
||||
# pulse_interval zurück auf base
|
||||
assert pc.get_effective_pulse_interval() == 0.05
|
||||
|
||||
def test_half_open_429_returns_to_open(self):
|
||||
"""HALF_OPEN Test-Ping bekommt 429 → OPEN, backoff eskaliert."""
|
||||
from plugin.archivar.presence_engine import PulseController
|
||||
|
||||
# DDP wirft IMMER 429
|
||||
mock_ddp = MagicMock()
|
||||
mock_ddp.connected = True
|
||||
mock_ddp.set_status = MagicMock(side_effect=Exception("HTTP 429 Too Many Requests"))
|
||||
|
||||
pc = PulseController(pulse_interval=0.05, _clamp_pulse=False)
|
||||
pc.bind_ddp(mock_ddp)
|
||||
|
||||
# 3×429 → OPEN (backoff_level=0, pulse_interval=5.0)
|
||||
for _ in range(3):
|
||||
pc._pulse_tick()
|
||||
assert pc.get_breaker_state() == "OPEN"
|
||||
first_open_interval = pc.get_effective_pulse_interval()
|
||||
|
||||
# Simuliere Cooldown-Ablauf
|
||||
pc._breaker_opened_at = time.monotonic() - pc._breaker_cooldown_s - 1.0
|
||||
|
||||
# HALF_OPEN Test-Ping → 429 → OPEN again, backoff_level=1 → 15.0s
|
||||
pc._pulse_tick()
|
||||
assert pc.get_breaker_state() == "OPEN"
|
||||
assert pc.get_effective_pulse_interval() > first_open_interval
|
||||
|
||||
|
||||
class TestCircuitBreakerSustained429:
|
||||
"""P1: sustained-429 — adaptives pulse_interval steigt unter Last."""
|
||||
|
||||
def test_sustained_429_escalates_pulse_interval(self):
|
||||
"""Anhaltende 429 → pulse_interval: 1.5s → 5s → 15s → 60s."""
|
||||
from plugin.archivar.presence_engine import PulseController
|
||||
|
||||
mock_ddp = MagicMock()
|
||||
mock_ddp.connected = True
|
||||
mock_ddp.set_status = MagicMock(side_effect=Exception("HTTP 429 Too Many Requests"))
|
||||
|
||||
pc = PulseController(pulse_interval=1.5, _clamp_pulse=False)
|
||||
pc.bind_ddp(mock_ddp)
|
||||
|
||||
intervals_seen = [pc.get_effective_pulse_interval()]
|
||||
|
||||
# Zyklus 1: 3×429 → OPEN (backoff 0: 5.0s)
|
||||
for _ in range(3):
|
||||
pc._pulse_tick()
|
||||
intervals_seen.append(pc.get_effective_pulse_interval())
|
||||
|
||||
# Cooldown ablaufen lassen → HALF_OPEN → 429 → OPEN (backoff 1: 15.0s)
|
||||
pc._breaker_opened_at = time.monotonic() - pc._breaker_cooldown_s - 1.0
|
||||
pc._pulse_tick()
|
||||
intervals_seen.append(pc.get_effective_pulse_interval())
|
||||
|
||||
# Cooldown ablaufen lassen → HALF_OPEN → 429 → OPEN (backoff 2: 60.0s)
|
||||
pc._breaker_opened_at = time.monotonic() - pc._breaker_cooldown_s - 1.0
|
||||
pc._pulse_tick()
|
||||
intervals_seen.append(pc.get_effective_pulse_interval())
|
||||
|
||||
# Intervalle müssen monoton steigen
|
||||
for i in range(1, len(intervals_seen)):
|
||||
assert intervals_seen[i] >= intervals_seen[i - 1], (
|
||||
f"pulse_interval nicht monoton: {intervals_seen}"
|
||||
)
|
||||
|
||||
# Letztes Intervall sollte 60.0 sein (max backoff)
|
||||
assert intervals_seen[-1] == 60.0, (
|
||||
f"Erwartet 60.0s max backoff, bekam {intervals_seen[-1]}"
|
||||
)
|
||||
# Der Parent-PID (os.getppid()) existiert immer im Testprozess
|
||||
result = dt._check_gateway_pid_alive()
|
||||
assert result is True
|
||||
|
||||
def test_backoff_capped_at_max(self):
|
||||
"""Backoff-Level capped bei len(backoff_intervals)-1 (60s)."""
|
||||
from plugin.archivar.presence_engine import PulseController
|
||||
|
||||
mock_ddp = MagicMock()
|
||||
mock_ddp.connected = True
|
||||
mock_ddp.set_status = MagicMock(side_effect=Exception("HTTP 429 Too Many Requests"))
|
||||
|
||||
pc = PulseController(pulse_interval=1.5, _clamp_pulse=False)
|
||||
pc.bind_ddp(mock_ddp)
|
||||
|
||||
# 5 Zyklen OPEN→HALF_OPEN→OPEN (mehr als backoff_intervals Länge)
|
||||
for cycle in range(5):
|
||||
# 3×429 → OPEN
|
||||
for _ in range(3):
|
||||
pc._pulse_tick()
|
||||
# Cooldown ablaufen → HALF_OPEN → 429 → OPEN
|
||||
pc._breaker_opened_at = time.monotonic() - pc._breaker_cooldown_s - 1.0
|
||||
pc._pulse_tick()
|
||||
|
||||
# Sollte bei 60.0 gecapped sein, nicht höher
|
||||
assert pc.get_effective_pulse_interval() == 60.0
|
||||
|
||||
|
||||
class TestPidSentinelDeadGateway:
|
||||
"""T2: PID-Sentinel erkennt toten Gateway-Prozess."""
|
||||
class TestCircuitBreakerDdpErrorClassification:
|
||||
"""P1: DDP-Error-Klassifizierung — 'server returned false' kein REST-Fallback."""
|
||||
|
||||
def test_pid_sentinel_dead_gateway(self):
|
||||
"""_check_gateway_pid_alive() liefert False wenn /proc/<ppid> nicht existiert."""
|
||||
from plugin.archivar.presence_engine import DetectionTimer
|
||||
def test_server_returned_false_is_transient(self):
|
||||
"""'server returned false' wird als ddp_transient klassifiziert."""
|
||||
from plugin.archivar.presence_engine import PulseController
|
||||
|
||||
dt = DetectionTimer(
|
||||
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
||||
detection_interval=0.1,
|
||||
)
|
||||
# Mock: os.getppid() liefert eine nicht-existente PID
|
||||
with patch('plugin.archivar.presence_engine.os.getppid') as mock_getppid:
|
||||
mock_getppid.return_value = 999999 # nicht-existente PID
|
||||
result = dt._check_gateway_pid_alive()
|
||||
assert result is False
|
||||
pc = PulseController(pulse_interval=0.05, _clamp_pulse=False)
|
||||
result = pc._classify_ddp_error(Exception("DDP: server returned false"))
|
||||
assert result == "ddp_transient"
|
||||
|
||||
def test_429_error_is_classified_as_429(self):
|
||||
"""HTTP 429 wird als '429' klassifiziert."""
|
||||
from plugin.archivar.presence_engine import PulseController
|
||||
|
||||
pc = PulseController(pulse_interval=0.05, _clamp_pulse=False)
|
||||
result = pc._classify_ddp_error(Exception("HTTP 429 Too Many Requests"))
|
||||
assert result == "429"
|
||||
|
||||
def test_other_error_is_classified_as_other(self):
|
||||
"""Andere Fehler werden als 'other' klassifiziert."""
|
||||
from plugin.archivar.presence_engine import PulseController
|
||||
|
||||
pc = PulseController(pulse_interval=0.05, _clamp_pulse=False)
|
||||
result = pc._classify_ddp_error(Exception("Connection refused"))
|
||||
assert result == "other"
|
||||
|
||||
def test_ddp_transient_does_not_trigger_rest_fallback(self):
|
||||
"""'server returned false' DDP-Fehler → kein REST-Fallback, kein 429-Count."""
|
||||
from plugin.archivar.presence_engine import PulseController
|
||||
|
||||
mock_ddp = MagicMock()
|
||||
mock_ddp.connected = True
|
||||
mock_ddp.set_status = MagicMock(side_effect=Exception("DDP: server returned false"))
|
||||
|
||||
mock_rest = MagicMock()
|
||||
mock_rest.auth_token = "token"
|
||||
mock_rest.user_id = "user123"
|
||||
mock_rest._request = MagicMock(return_value={"success": True})
|
||||
|
||||
pc = PulseController(pulse_interval=0.05, _clamp_pulse=False)
|
||||
pc.bind_ddp(mock_ddp)
|
||||
pc.bind_rest(mock_rest)
|
||||
|
||||
# 10 Ticks mit 'server returned false' → kein REST-Fallback, kein 429
|
||||
for _ in range(10):
|
||||
pc._pulse_tick()
|
||||
|
||||
# REST wurde NICHT aufgerufen (kein Fallback)
|
||||
mock_rest._request.assert_not_called()
|
||||
# Kein 429 gezählt
|
||||
assert pc.get_consecutive_429s() == 0
|
||||
# Breaker bleibt CLOSED
|
||||
assert pc.get_breaker_state() == "CLOSED"
|
||||
|
||||
def test_429_ddp_error_does_not_trigger_rest_fallback(self):
|
||||
"""429 DDP-Fehler → kein REST-Fallback (verhindert Kaskade)."""
|
||||
from plugin.archivar.presence_engine import PulseController
|
||||
|
||||
mock_ddp = MagicMock()
|
||||
mock_ddp.connected = True
|
||||
mock_ddp.set_status = MagicMock(side_effect=Exception("HTTP 429 Too Many Requests"))
|
||||
|
||||
mock_rest = MagicMock()
|
||||
mock_rest.auth_token = "token"
|
||||
mock_rest.user_id = "user123"
|
||||
mock_rest._request = MagicMock(return_value={"success": True})
|
||||
|
||||
pc = PulseController(pulse_interval=0.05, _clamp_pulse=False)
|
||||
pc.bind_ddp(mock_ddp)
|
||||
pc.bind_rest(mock_rest)
|
||||
|
||||
# 3×429 DDP → OPEN, REST wurde NIE aufgerufen
|
||||
for _ in range(3):
|
||||
pc._pulse_tick()
|
||||
|
||||
# REST wurde NICHT aufgerufen (429 blockiert Fallback)
|
||||
mock_rest._request.assert_not_called()
|
||||
assert pc.get_breaker_state() == "OPEN"
|
||||
|
||||
|
||||
class TestGatewayStateThresholdZero:
|
||||
"""T3: gateway_state.json Schwelle >0 statt >1."""
|
||||
class TestCircuitBreakerRecordSuccess:
|
||||
"""P1: _record_success() resetet Breaker und pulse_interval."""
|
||||
|
||||
def test_gateway_state_threshold_zero(self):
|
||||
"""active_agents=1 → gateway_state erkennt als aktiv (Schwelle >0)."""
|
||||
from plugin.archivar.presence_engine import DetectionTimer
|
||||
import tempfile
|
||||
import json
|
||||
def test_record_success_resets_everything(self):
|
||||
"""_record_success() → CLOSED, 429s=0, backoff=0, pulse_interval=base."""
|
||||
from plugin.archivar.presence_engine import PulseController
|
||||
|
||||
# gateway_state mit active_agents=1 (war vorher >1, jetzt >0)
|
||||
state = {"active_agents": 1, "profiles": ["default"]}
|
||||
with tempfile.NamedTemporaryFile(suffix=".json", delete=False, mode="w") as f:
|
||||
json.dump(state, f)
|
||||
state_path = f.name
|
||||
pc = PulseController(pulse_interval=1.5, _clamp_pulse=False)
|
||||
|
||||
try:
|
||||
# Mock pgrep: findet nichts (damit gateway_state entscheidet)
|
||||
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
|
||||
mock_run.return_value = MagicMock(
|
||||
stdout="",
|
||||
stderr="",
|
||||
returncode=1,
|
||||
)
|
||||
# PID-Sentinel deaktivieren via Mock, damit gateway_state getestet wird
|
||||
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
||||
dt = DetectionTimer(
|
||||
gateway_state_path=state_path,
|
||||
detection_interval=0.1,
|
||||
)
|
||||
result = dt.check()
|
||||
# active_agents=1 > 0 → gateway_state erkennt als aktiv
|
||||
assert result is True
|
||||
finally:
|
||||
os.unlink(state_path)
|
||||
# Manuell in OPEN setzen
|
||||
pc._breaker_state = "OPEN"
|
||||
pc._consecutive_429s = 5
|
||||
pc._backoff_level = 2
|
||||
pc._pulse_interval = 60.0
|
||||
|
||||
pc._record_success()
|
||||
|
||||
class TestPgrepPatternMatchesGatewayRun:
|
||||
"""T4: pgrep-Pattern matcht 'gateway run'."""
|
||||
assert pc.get_breaker_state() == "CLOSED"
|
||||
assert pc.get_consecutive_429s() == 0
|
||||
assert pc.get_effective_pulse_interval() == 1.5
|
||||
|
||||
def test_pgrep_pattern_matches_gateway_run(self):
|
||||
"""pgrep -f 'hermes_cli|hermes chat|gateway run' findet Gateway-Prozess."""
|
||||
from plugin.archivar.presence_engine import DetectionTimer
|
||||
def test_success_after_open_resets_interval(self):
|
||||
"""Nach OPEN→HALF_OPEN→success: pulse_interval zurück auf base."""
|
||||
from plugin.archivar.presence_engine import PulseController
|
||||
|
||||
own_pid = os.getpid()
|
||||
call_count = [0]
|
||||
|
||||
# Mock pgrep: findet einen 'gateway run'-Prozess (nicht eigenen PID)
|
||||
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
|
||||
mock_run.return_value = MagicMock(
|
||||
stdout="12345\n", # anderer PID, nicht own_pid
|
||||
stderr="",
|
||||
returncode=0,
|
||||
)
|
||||
# PID-Sentinel + gateway_state deaktivieren, damit pgrep getestet wird
|
||||
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
||||
dt = DetectionTimer(
|
||||
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
||||
detection_interval=0.1,
|
||||
)
|
||||
result = dt.check()
|
||||
# pgrep findet 'gateway run'-Prozess → True
|
||||
assert result is True
|
||||
def ddp_side_effect(status):
|
||||
call_count[0] += 1
|
||||
if call_count[0] <= 3:
|
||||
raise Exception("HTTP 429 Too Many Requests")
|
||||
return True
|
||||
|
||||
# Prüfe dass das pgrep-Pattern 'gateway run' enthält
|
||||
call_args = mock_run.call_args[0][0]
|
||||
pattern_arg = None
|
||||
for i, arg in enumerate(call_args):
|
||||
if arg == "-f" and i + 1 < len(call_args):
|
||||
pattern_arg = call_args[i + 1]
|
||||
break
|
||||
assert pattern_arg is not None, "pgrep -f pattern not found in call"
|
||||
assert "gateway run" in pattern_arg, (
|
||||
f"Pattern should contain 'gateway run', got: {pattern_arg}"
|
||||
)
|
||||
mock_ddp = MagicMock()
|
||||
mock_ddp.connected = True
|
||||
mock_ddp.set_status = MagicMock(side_effect=ddp_side_effect)
|
||||
|
||||
pc = PulseController(pulse_interval=1.5, _clamp_pulse=False)
|
||||
pc.bind_ddp(mock_ddp)
|
||||
|
||||
class TestIdlePulseContinuesWhenGatewayAlive:
|
||||
"""T5: Gateway läuft, keine Subagenten → Detection='active', Status='online'."""
|
||||
# 3×429 → OPEN (pulse_interval=5.0)
|
||||
for _ in range(3):
|
||||
pc._pulse_tick()
|
||||
assert pc.get_breaker_state() == "OPEN"
|
||||
assert pc.get_effective_pulse_interval() == 5.0
|
||||
|
||||
def test_idle_pulse_continues_when_gateway_alive(self):
|
||||
"""PID-Sentinel erkennt Gateway → check()=True auch ohne Subagenten."""
|
||||
from plugin.archivar.presence_engine import DetectionTimer
|
||||
# Cooldown ablaufen → HALF_OPEN → success → CLOSED
|
||||
pc._breaker_opened_at = time.monotonic() - pc._breaker_cooldown_s - 1.0
|
||||
pc._pulse_tick()
|
||||
|
||||
# PID-Sentinel: Gateway lebt
|
||||
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=True):
|
||||
# gateway_state: active_agents=0 (keine Subagenten)
|
||||
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
|
||||
mock_run.return_value = MagicMock(
|
||||
stdout="",
|
||||
stderr="",
|
||||
returncode=1,
|
||||
)
|
||||
dt = DetectionTimer(
|
||||
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
||||
detection_interval=0.1,
|
||||
)
|
||||
result = dt.check()
|
||||
# Gateway lebt → detection=active, auch ohne Subagenten
|
||||
assert result is True, (
|
||||
"PID-Sentinel sollte Gateway als aktiv erkennen, "
|
||||
"auch wenn keine Subagenten laufen"
|
||||
)
|
||||
|
||||
|
||||
class TestSubagentActivityPulsesYellow:
|
||||
"""T6: Subagent-Aktivität → Puls gelb (Detection erkennt Subagenten)."""
|
||||
|
||||
def test_subagent_activity_pulses_yellow(self):
|
||||
"""gateway_state active_agents=2 → check()=True via gateway_state (Subagenten)."""
|
||||
from plugin.archivar.presence_engine import DetectionTimer
|
||||
import tempfile
|
||||
import json
|
||||
|
||||
# gateway_state mit active_agents=2 (Subagenten aktiv)
|
||||
state = {"active_agents": 2, "profiles": ["default", "miguel"]}
|
||||
with tempfile.NamedTemporaryFile(suffix=".json", delete=False, mode="w") as f:
|
||||
json.dump(state, f)
|
||||
state_path = f.name
|
||||
|
||||
try:
|
||||
# PID-Sentinel deaktivieren, gateway_state soll entscheiden
|
||||
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
||||
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
|
||||
mock_run.return_value = MagicMock(
|
||||
stdout="",
|
||||
stderr="",
|
||||
returncode=1,
|
||||
)
|
||||
dt = DetectionTimer(
|
||||
gateway_state_path=state_path,
|
||||
detection_interval=0.1,
|
||||
)
|
||||
result = dt.check()
|
||||
# active_agents=2 > 0 → gateway_state erkennt Subagenten
|
||||
assert result is True
|
||||
finally:
|
||||
os.unlink(state_path)
|
||||
|
||||
|
||||
class TestNoFalseActiveWhenGatewayDead:
|
||||
"""T7: Kein False-Positive wenn Gateway tot ist."""
|
||||
|
||||
def test_no_false_active_when_gateway_dead(self):
|
||||
"""PID-Sentinel tot + gateway_state=0 + pgrep=0 → check()=False."""
|
||||
from plugin.archivar.presence_engine import DetectionTimer
|
||||
|
||||
# Alle drei Signale negativ
|
||||
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
||||
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
|
||||
mock_run.return_value = MagicMock(
|
||||
stdout="",
|
||||
stderr="",
|
||||
returncode=1,
|
||||
)
|
||||
dt = DetectionTimer(
|
||||
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
||||
detection_interval=0.1,
|
||||
)
|
||||
result = dt.check()
|
||||
# Kein Gateway, keine Subagenten, kein pgrep → False
|
||||
assert result is False, (
|
||||
"Ohne Gateway-Prozess und ohne Subagenten darf "
|
||||
"keine Aktivität gemeldet werden"
|
||||
)
|
||||
|
||||
|
||||
class TestDetectionSourcePidSentinel:
|
||||
"""T8: detection_source='gateway_pid' wenn PID-Sentinel entscheidet."""
|
||||
|
||||
def test_detection_source_pid_sentinel(self):
|
||||
"""PID-Sentinel entscheidet → detection_source='gateway_pid'."""
|
||||
from plugin.archivar.presence_engine import DetectionTimer
|
||||
from plugin.archivar.routing_telemetry import routing_telemetry
|
||||
|
||||
routing_telemetry.heartbeat_detection_source = "none"
|
||||
|
||||
# PID-Sentinel: Gateway lebt → PRIMARY entscheidet
|
||||
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=True):
|
||||
dt = DetectionTimer(
|
||||
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
||||
detection_interval=0.1,
|
||||
)
|
||||
result = dt.check()
|
||||
assert result is True
|
||||
# detection_source muss 'gateway_pid' sein
|
||||
assert routing_telemetry.heartbeat_detection_source == "gateway_pid", (
|
||||
f"Erwartet 'gateway_pid', bekam "
|
||||
f"'{routing_telemetry.heartbeat_detection_source}'"
|
||||
)
|
||||
assert pc.get_breaker_state() == "CLOSED"
|
||||
assert pc.get_effective_pulse_interval() == 1.5
|
||||
|
||||
Reference in New Issue
Block a user