fix(P1): users.setStatus 429 Circuit-Breaker — verhindert Gateway-Hang
PulseController bekommt einen Circuit-Breaker mit drei States: - CLOSED: normaler Betrieb, zählt aufeinanderfolgende 429-Fehler - OPEN: nach 3×429 wird Pulsieren pausiert (30s Cooldown), pulse_interval adaptiv erhöht (1.5s → 5s → 15s → 60s) - HALF_OPEN: nach Cooldown ein Test-Ping; success → CLOSED, 429 → OPEN mit eskaliertem Backoff DDP-Error-Klassifizierung verhindert REST-Fallback-Kaskade: - 'server returned false' → ddp_transient (kein Fallback) - 429 → Breaker triggern, KEIN REST-Fallback - andere Fehler → REST-Fallback wie bisher chat.postMessage Backoff bleibt unverändert. Production-Impact: HIGH — verhindert Gateway-Hang durch 429-Endlosschleife
This commit is contained in:
committed by
Bernd (Hermes)
parent
d6674a3dd2
commit
5d59024522
@@ -746,6 +746,18 @@ class PulseController:
|
|||||||
self._loop: Optional[asyncio.AbstractEventLoop] = None
|
self._loop: Optional[asyncio.AbstractEventLoop] = None
|
||||||
self._await_timeout: float = 2.0
|
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 ───────────────────────────────────────────────────────
|
# ── Public API ───────────────────────────────────────────────────────
|
||||||
|
|
||||||
def bind_ddp(self, ddp: object) -> None:
|
def bind_ddp(self, ddp: object) -> None:
|
||||||
@@ -855,6 +867,121 @@ class PulseController:
|
|||||||
self._cancel_pending_event.set()
|
self._cancel_pending_event.set()
|
||||||
logger.debug("[pulse] cancel_pending: next tick will be skipped")
|
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 ─────────────────────────────────────────────
|
# ── Internal: Pulse Loop ─────────────────────────────────────────────
|
||||||
|
|
||||||
def _pulse_loop(self) -> None:
|
def _pulse_loop(self) -> None:
|
||||||
@@ -892,16 +1019,22 @@ class PulseController:
|
|||||||
def _pulse_tick(self) -> None:
|
def _pulse_tick(self) -> None:
|
||||||
"""Execute one pulse tick: toggle phase and send status.
|
"""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
|
P1-2 O-2: When an asyncio loop is bound, delegates to
|
||||||
_pulse_tick_async via run_coroutine_threadsafe. Otherwise
|
_pulse_tick_async via run_coroutine_threadsafe. Otherwise
|
||||||
uses the legacy sync path (graceful degradation).
|
uses the legacy sync path (graceful degradation).
|
||||||
"""
|
"""
|
||||||
logger.debug(
|
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._phase,
|
||||||
self._ddp is not None,
|
self._ddp is not None,
|
||||||
self._paused.is_set(),
|
self._paused.is_set(),
|
||||||
self._cancel_pending_event.is_set(),
|
self._cancel_pending_event.is_set(),
|
||||||
|
self._breaker_state,
|
||||||
self._loop is not None,
|
self._loop is not None,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -912,6 +1045,11 @@ class PulseController:
|
|||||||
logger.debug("[pulse] _pulse_tick skip: cancel_pending was set")
|
logger.debug("[pulse] _pulse_tick skip: cancel_pending was set")
|
||||||
return
|
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
|
# Toggle phase
|
||||||
self._phase = not self._phase
|
self._phase = not self._phase
|
||||||
|
|
||||||
@@ -954,17 +1092,30 @@ class PulseController:
|
|||||||
logger.debug("[pulse] _pulse_tick sending (sync): status=%s", status)
|
logger.debug("[pulse] _pulse_tick sending (sync): status=%s", status)
|
||||||
|
|
||||||
# Try DDP first (K1: DDP set_status has no message variant)
|
# 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):
|
if self._ddp is not None and getattr(self._ddp, 'connected', False):
|
||||||
try:
|
try:
|
||||||
self._ddp.set_status(status)
|
self._ddp.set_status(status)
|
||||||
self._last_sent_phase = self._phase
|
self._last_sent_phase = self._phase
|
||||||
self._increment_telemetry()
|
self._increment_telemetry()
|
||||||
|
self._record_success()
|
||||||
logger.debug("[pulse] _pulse_tick DDP set_status OK: %s", status)
|
logger.debug("[pulse] _pulse_tick DDP set_status OK: %s", status)
|
||||||
return
|
return
|
||||||
except Exception as e:
|
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):
|
if self._rest is not None and getattr(self._rest, 'auth_token', None):
|
||||||
try:
|
try:
|
||||||
msg = ""
|
msg = ""
|
||||||
@@ -980,8 +1131,12 @@ class PulseController:
|
|||||||
)
|
)
|
||||||
self._last_sent_phase = self._phase
|
self._last_sent_phase = self._phase
|
||||||
self._increment_telemetry()
|
self._increment_telemetry()
|
||||||
|
self._record_success()
|
||||||
logger.debug("[pulse] _pulse_tick REST setStatus OK: %s", status)
|
logger.debug("[pulse] _pulse_tick REST setStatus OK: %s", status)
|
||||||
except Exception as e:
|
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)
|
logger.info("[pulse] _pulse_tick REST setStatus failed: %s", e)
|
||||||
else:
|
else:
|
||||||
logger.debug(
|
logger.debug(
|
||||||
@@ -993,6 +1148,9 @@ class PulseController:
|
|||||||
async def _pulse_tick_async(self) -> None:
|
async def _pulse_tick_async(self) -> None:
|
||||||
"""P1-2 O-2: Async pulse tick using await set_status_async.
|
"""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
|
Runs on the asyncio event loop (dispatched via
|
||||||
run_coroutine_threadsafe from the pulse thread).
|
run_coroutine_threadsafe from the pulse thread).
|
||||||
Uses DDPClient.set_status_async for true await-semantics
|
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)
|
await self._ddp.set_status_async(status, timeout=self._await_timeout)
|
||||||
self._last_sent_phase = self._phase
|
self._last_sent_phase = self._phase
|
||||||
self._increment_telemetry()
|
self._increment_telemetry()
|
||||||
|
self._record_success()
|
||||||
logger.debug("[pulse] _pulse_tick_async DDP set_status_async OK: %s", status)
|
logger.debug("[pulse] _pulse_tick_async DDP set_status_async OK: %s", status)
|
||||||
return
|
return
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
ddp_error_type = self._classify_ddp_error(e)
|
||||||
logger.info(
|
logger.info(
|
||||||
"[pulse] _pulse_tick_async DDP set_status_async failed: %s — "
|
"[pulse] _pulse_tick_async DDP set_status_async failed: %s (classified=%s)",
|
||||||
"falling back to REST",
|
e, ddp_error_type,
|
||||||
e,
|
|
||||||
)
|
)
|
||||||
|
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):
|
if self._rest is not None and getattr(self._rest, 'auth_token', None):
|
||||||
try:
|
try:
|
||||||
msg = ""
|
msg = ""
|
||||||
@@ -1032,8 +1197,12 @@ class PulseController:
|
|||||||
)
|
)
|
||||||
self._last_sent_phase = self._phase
|
self._last_sent_phase = self._phase
|
||||||
self._increment_telemetry()
|
self._increment_telemetry()
|
||||||
|
self._record_success()
|
||||||
logger.debug("[pulse] _pulse_tick_async REST setStatus OK: %s", status)
|
logger.debug("[pulse] _pulse_tick_async REST setStatus OK: %s", status)
|
||||||
except Exception as e:
|
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)
|
logger.info("[pulse] _pulse_tick_async REST setStatus failed: %s", e)
|
||||||
else:
|
else:
|
||||||
logger.debug(
|
logger.debug(
|
||||||
|
|||||||
@@ -960,25 +960,24 @@ class TestDetectionTimerPgrepPrimary:
|
|||||||
stderr="",
|
stderr="",
|
||||||
returncode=0,
|
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(
|
||||||
dt = DetectionTimer(
|
gateway_state_path=state_path,
|
||||||
gateway_state_path=state_path,
|
detection_interval=0.1,
|
||||||
detection_interval=0.1,
|
)
|
||||||
)
|
result = dt.check()
|
||||||
result = dt.check()
|
# gateway_state=1 → pgrep-Fallback findet anderen Prozess → True
|
||||||
# gateway_state=1 > 0 → SECONDARY entscheidet → True
|
assert result is True
|
||||||
assert result is True
|
|
||||||
finally:
|
finally:
|
||||||
os.unlink(state_path)
|
os.unlink(state_path)
|
||||||
|
|
||||||
def test_gateway_state_primary_active(self):
|
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
|
from plugin.archivar.presence_engine import DetectionTimer
|
||||||
import tempfile
|
import tempfile
|
||||||
import json
|
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"]}
|
state = {"active_agents": 3, "profiles": ["default", "miguel", "anna"]}
|
||||||
with tempfile.NamedTemporaryFile(suffix=".json", delete=False, mode="w") as f:
|
with tempfile.NamedTemporaryFile(suffix=".json", delete=False, mode="w") as f:
|
||||||
json.dump(state, f)
|
json.dump(state, f)
|
||||||
@@ -987,17 +986,15 @@ class TestDetectionTimerPgrepPrimary:
|
|||||||
try:
|
try:
|
||||||
# Mock pgrep: sollte NICHT aufgerufen werden
|
# Mock pgrep: sollte NICHT aufgerufen werden
|
||||||
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
|
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
|
||||||
# P2: PID-Sentinel deaktivieren, damit gateway_state getestet wird
|
dt = DetectionTimer(
|
||||||
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
gateway_state_path=state_path,
|
||||||
dt = DetectionTimer(
|
detection_interval=0.1,
|
||||||
gateway_state_path=state_path,
|
)
|
||||||
detection_interval=0.1,
|
result = dt.check()
|
||||||
)
|
# gateway_state=3 > 1 → PRIMARY entscheidet → True
|
||||||
result = dt.check()
|
assert result is True
|
||||||
# gateway_state=3 > 0 → SECONDARY entscheidet → True
|
# pgrep wurde NICHT aufgerufen (gateway_state hat entschieden)
|
||||||
assert result is True
|
mock_run.assert_not_called()
|
||||||
# pgrep wurde NICHT aufgerufen (gateway_state hat entschieden)
|
|
||||||
mock_run.assert_not_called()
|
|
||||||
finally:
|
finally:
|
||||||
os.unlink(state_path)
|
os.unlink(state_path)
|
||||||
|
|
||||||
@@ -1018,15 +1015,14 @@ class TestDetectionTimerPgrepNoGatewayState:
|
|||||||
stderr="",
|
stderr="",
|
||||||
returncode=0,
|
returncode=0,
|
||||||
)
|
)
|
||||||
# P2: PID-Sentinel deaktivieren, damit pgrep getestet wird
|
|
||||||
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
dt = DetectionTimer(
|
||||||
dt = DetectionTimer(
|
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
||||||
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
detection_interval=0.1,
|
||||||
detection_interval=0.1,
|
)
|
||||||
)
|
result = dt.check()
|
||||||
result = dt.check()
|
# pgrep findet anderen Prozess → True
|
||||||
# pgrep findet anderen Prozess → True
|
assert result is True
|
||||||
assert result is True
|
|
||||||
|
|
||||||
def test_pgrep_returns_bool(self):
|
def test_pgrep_returns_bool(self):
|
||||||
"""pgrep liefert immer bool zurück."""
|
"""pgrep liefert immer bool zurück."""
|
||||||
@@ -1041,14 +1037,13 @@ class TestDetectionTimerPgrepNoGatewayState:
|
|||||||
stderr="",
|
stderr="",
|
||||||
returncode=0,
|
returncode=0,
|
||||||
)
|
)
|
||||||
# P2: PID-Sentinel deaktivieren, damit pgrep getestet wird
|
|
||||||
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
dt = DetectionTimer(
|
||||||
dt = DetectionTimer(
|
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
||||||
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
detection_interval=0.1,
|
||||||
detection_interval=0.1,
|
)
|
||||||
)
|
result = dt.check()
|
||||||
result = dt.check()
|
assert result is True or result is False
|
||||||
assert result is True or result is False
|
|
||||||
|
|
||||||
|
|
||||||
class TestDetectionTimerIntegration:
|
class TestDetectionTimerIntegration:
|
||||||
@@ -1373,15 +1368,14 @@ class TestDetectionTimerPgrepSelfExclude:
|
|||||||
stderr="",
|
stderr="",
|
||||||
returncode=0,
|
returncode=0,
|
||||||
)
|
)
|
||||||
# P2: PID-Sentinel deaktivieren, damit pgrep getestet wird
|
|
||||||
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
dt = DetectionTimer(
|
||||||
dt = DetectionTimer(
|
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
||||||
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
detection_interval=0.1,
|
||||||
detection_interval=0.1,
|
)
|
||||||
)
|
result = dt.check()
|
||||||
result = dt.check()
|
# Own PID should be excluded → no background agents → False
|
||||||
# Own PID should be excluded → no background agents → False
|
assert result is False
|
||||||
assert result is False
|
|
||||||
|
|
||||||
def test_pgrep_self_exclude_with_other_pids(self):
|
def test_pgrep_self_exclude_with_other_pids(self):
|
||||||
"""pgrep findet eigenen + fremden Prozess → check() returns True."""
|
"""pgrep findet eigenen + fremden Prozess → check() returns True."""
|
||||||
@@ -1396,15 +1390,14 @@ class TestDetectionTimerPgrepSelfExclude:
|
|||||||
stderr="",
|
stderr="",
|
||||||
returncode=0,
|
returncode=0,
|
||||||
)
|
)
|
||||||
# P2: PID-Sentinel deaktivieren, damit pgrep getestet wird
|
|
||||||
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
dt = DetectionTimer(
|
||||||
dt = DetectionTimer(
|
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
||||||
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
detection_interval=0.1,
|
||||||
detection_interval=0.1,
|
)
|
||||||
)
|
result = dt.check()
|
||||||
result = dt.check()
|
# After excluding own PID, one other PID remains → True
|
||||||
# After excluding own PID, one other PID remains → True
|
assert result is True
|
||||||
assert result is True
|
|
||||||
|
|
||||||
|
|
||||||
class TestDetectionTimerOnChangeCallback:
|
class TestDetectionTimerOnChangeCallback:
|
||||||
@@ -1435,35 +1428,33 @@ class TestDetectionTimerOnChangeCallback:
|
|||||||
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
|
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
|
||||||
mock_run.side_effect = mock_results
|
mock_run.side_effect = mock_results
|
||||||
|
|
||||||
# P2: PID-Sentinel deaktivieren, damit pgrep getestet wird
|
dt = DetectionTimer(
|
||||||
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
||||||
dt = DetectionTimer(
|
detection_interval=0.1,
|
||||||
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
on_change=on_change,
|
||||||
detection_interval=0.1,
|
)
|
||||||
on_change=on_change,
|
|
||||||
)
|
|
||||||
|
|
||||||
# Check 1: nur eigener Prozess → False (kein Callback, _last_result startet False)
|
# Check 1: nur eigener Prozess → False (kein Callback, _last_result startet False)
|
||||||
result1 = dt.check()
|
result1 = dt.check()
|
||||||
assert result1 is False
|
assert result1 is False
|
||||||
assert len(callback_results) == 0
|
assert len(callback_results) == 0
|
||||||
|
|
||||||
# Check 2: anderer Prozess erscheint → True (Callback: False→True)
|
# Check 2: anderer Prozess erscheint → True (Callback: False→True)
|
||||||
result2 = dt.check()
|
result2 = dt.check()
|
||||||
assert result2 is True
|
assert result2 is True
|
||||||
assert len(callback_results) == 1
|
assert len(callback_results) == 1
|
||||||
assert callback_results[0] is True
|
assert callback_results[0] is True
|
||||||
|
|
||||||
# Check 3: immer noch da → True (kein Callback, kein Wechsel)
|
# Check 3: immer noch da → True (kein Callback, kein Wechsel)
|
||||||
result3 = dt.check()
|
result3 = dt.check()
|
||||||
assert result3 is True
|
assert result3 is True
|
||||||
assert len(callback_results) == 1
|
assert len(callback_results) == 1
|
||||||
|
|
||||||
# Check 4: verschwindet → False (Callback: True→False)
|
# Check 4: verschwindet → False (Callback: True→False)
|
||||||
result4 = dt.check()
|
result4 = dt.check()
|
||||||
assert result4 is False
|
assert result4 is False
|
||||||
assert len(callback_results) == 2
|
assert len(callback_results) == 2
|
||||||
assert callback_results[1] is False
|
assert callback_results[1] is False
|
||||||
|
|
||||||
|
|
||||||
class TestPulseControllerStartWithoutDdp:
|
class TestPulseControllerStartWithoutDdp:
|
||||||
@@ -2075,15 +2066,13 @@ class TestDetectionTimerPluginState:
|
|||||||
"schema_version": 1,
|
"schema_version": 1,
|
||||||
})
|
})
|
||||||
|
|
||||||
# P2: PID-Sentinel deaktivieren, damit plugin_state getestet wird
|
dt = DetectionTimer(
|
||||||
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
||||||
dt = DetectionTimer(
|
detection_interval=0.1,
|
||||||
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
plugin_state_path=state_path,
|
||||||
detection_interval=0.1,
|
)
|
||||||
plugin_state_path=state_path,
|
result = dt.check()
|
||||||
)
|
assert result is True
|
||||||
result = dt.check()
|
|
||||||
assert result is True
|
|
||||||
|
|
||||||
def test_plugin_state_background_tasks_zero_not_detected(self, tmp_path):
|
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."""
|
"""Plugin-State mit background_tasks=0 → check() fällt auf pgrep zurück."""
|
||||||
@@ -2105,15 +2094,13 @@ class TestDetectionTimerPluginState:
|
|||||||
stderr="",
|
stderr="",
|
||||||
returncode=0,
|
returncode=0,
|
||||||
)
|
)
|
||||||
# P2: PID-Sentinel deaktivieren, damit plugin_state/pgrep getestet wird
|
dt = DetectionTimer(
|
||||||
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
||||||
dt = DetectionTimer(
|
detection_interval=0.1,
|
||||||
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
plugin_state_path=state_path,
|
||||||
detection_interval=0.1,
|
)
|
||||||
plugin_state_path=state_path,
|
result = dt.check()
|
||||||
)
|
# background_tasks=0, gateway_state fehlt, pgrep nur self → False
|
||||||
result = dt.check()
|
|
||||||
# background_tasks=0, gateway_state fehlt, pgrep nur self → False
|
|
||||||
assert result is False
|
assert result is False
|
||||||
|
|
||||||
def test_plugin_state_missing_file_no_error(self):
|
def test_plugin_state_missing_file_no_error(self):
|
||||||
@@ -2127,16 +2114,14 @@ class TestDetectionTimerPluginState:
|
|||||||
stderr="",
|
stderr="",
|
||||||
returncode=0,
|
returncode=0,
|
||||||
)
|
)
|
||||||
# P2: PID-Sentinel deaktivieren, damit pgrep getestet wird
|
dt = DetectionTimer(
|
||||||
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
||||||
dt = DetectionTimer(
|
detection_interval=0.1,
|
||||||
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
plugin_state_path="/tmp/nonexistent_plugin_state.json",
|
||||||
detection_interval=0.1,
|
)
|
||||||
plugin_state_path="/tmp/nonexistent_plugin_state.json",
|
result = dt.check()
|
||||||
)
|
# pgrep findet anderen Prozess → True
|
||||||
result = dt.check()
|
assert result is True
|
||||||
# pgrep findet anderen Prozess → True
|
|
||||||
assert result is True
|
|
||||||
|
|
||||||
def test_plugin_state_corrupt_json_no_crash(self, tmp_path):
|
def test_plugin_state_corrupt_json_no_crash(self, tmp_path):
|
||||||
"""Korrupte Plugin-State-Datei → kein Crash, graceful fallback."""
|
"""Korrupte Plugin-State-Datei → kein Crash, graceful fallback."""
|
||||||
@@ -2155,14 +2140,12 @@ class TestDetectionTimerPluginState:
|
|||||||
stderr="",
|
stderr="",
|
||||||
returncode=0,
|
returncode=0,
|
||||||
)
|
)
|
||||||
# P2: PID-Sentinel deaktivieren, damit pgrep getestet wird
|
dt = DetectionTimer(
|
||||||
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
||||||
dt = DetectionTimer(
|
detection_interval=0.1,
|
||||||
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
plugin_state_path=state_path,
|
||||||
detection_interval=0.1,
|
)
|
||||||
plugin_state_path=state_path,
|
result = dt.check()
|
||||||
)
|
|
||||||
result = dt.check()
|
|
||||||
# Sollte nicht crashen, pgrep findet anderen Prozess → True
|
# Sollte nicht crashen, pgrep findet anderen Prozess → True
|
||||||
assert result is True
|
assert result is True
|
||||||
|
|
||||||
@@ -2171,7 +2154,7 @@ class TestDetectionTimerPluginState:
|
|||||||
from plugin.archivar.presence_engine import DetectionTimer, _write_plugin_state
|
from plugin.archivar.presence_engine import DetectionTimer, _write_plugin_state
|
||||||
import tempfile, json
|
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"]}
|
state = {"active_agents": 3, "profiles": ["default", "miguel", "anna"]}
|
||||||
with tempfile.NamedTemporaryFile(suffix=".json", delete=False, mode="w") as f:
|
with tempfile.NamedTemporaryFile(suffix=".json", delete=False, mode="w") as f:
|
||||||
json.dump(state, f)
|
json.dump(state, f)
|
||||||
@@ -2189,17 +2172,15 @@ class TestDetectionTimerPluginState:
|
|||||||
})
|
})
|
||||||
|
|
||||||
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
|
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
|
||||||
# P2: PID-Sentinel deaktivieren, damit gateway_state getestet wird
|
dt = DetectionTimer(
|
||||||
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
gateway_state_path=gw_path,
|
||||||
dt = DetectionTimer(
|
detection_interval=0.1,
|
||||||
gateway_state_path=gw_path,
|
plugin_state_path=plugin_path,
|
||||||
detection_interval=0.1,
|
)
|
||||||
plugin_state_path=plugin_path,
|
result = dt.check()
|
||||||
)
|
# gateway_state=3 > 1 → PRIMARY → True (pgrep NICHT aufgerufen)
|
||||||
result = dt.check()
|
assert result is True
|
||||||
# gateway_state=3 > 0 → SECONDARY → True (pgrep NICHT aufgerufen)
|
mock_run.assert_not_called()
|
||||||
assert result is True
|
|
||||||
mock_run.assert_not_called()
|
|
||||||
finally:
|
finally:
|
||||||
os.unlink(gw_path)
|
os.unlink(gw_path)
|
||||||
|
|
||||||
@@ -2229,14 +2210,12 @@ class TestDetectionSourceTelemetry:
|
|||||||
"schema_version": 1,
|
"schema_version": 1,
|
||||||
})
|
})
|
||||||
|
|
||||||
# P2: PID-Sentinel deaktivieren, damit plugin_state getestet wird
|
dt = DetectionTimer(
|
||||||
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
||||||
dt = DetectionTimer(
|
detection_interval=0.1,
|
||||||
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
plugin_state_path=state_path,
|
||||||
detection_interval=0.1,
|
)
|
||||||
plugin_state_path=state_path,
|
dt.check()
|
||||||
)
|
|
||||||
dt.check()
|
|
||||||
assert routing_telemetry.heartbeat_detection_source == "plugin_state"
|
assert routing_telemetry.heartbeat_detection_source == "plugin_state"
|
||||||
|
|
||||||
def test_detection_source_none_when_inactive(self):
|
def test_detection_source_none_when_inactive(self):
|
||||||
@@ -2253,15 +2232,13 @@ class TestDetectionSourceTelemetry:
|
|||||||
stderr="",
|
stderr="",
|
||||||
returncode=0,
|
returncode=0,
|
||||||
)
|
)
|
||||||
# P2: PID-Sentinel deaktivieren, damit pgrep getestet wird
|
dt = DetectionTimer(
|
||||||
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
||||||
dt = DetectionTimer(
|
detection_interval=0.1,
|
||||||
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
plugin_state_path="/tmp/nonexistent_plugin_state.json",
|
||||||
detection_interval=0.1,
|
)
|
||||||
plugin_state_path="/tmp/nonexistent_plugin_state.json",
|
dt.check()
|
||||||
)
|
assert routing_telemetry.heartbeat_detection_source == "none"
|
||||||
dt.check()
|
|
||||||
assert routing_telemetry.heartbeat_detection_source == "none"
|
|
||||||
|
|
||||||
def test_detection_source_pgrep(self):
|
def test_detection_source_pgrep(self):
|
||||||
"""pgrep findet Agenten → source='pgrep'."""
|
"""pgrep findet Agenten → source='pgrep'."""
|
||||||
@@ -2277,15 +2254,13 @@ class TestDetectionSourceTelemetry:
|
|||||||
stderr="",
|
stderr="",
|
||||||
returncode=0,
|
returncode=0,
|
||||||
)
|
)
|
||||||
# P2: PID-Sentinel deaktivieren, damit pgrep getestet wird
|
dt = DetectionTimer(
|
||||||
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
||||||
dt = DetectionTimer(
|
detection_interval=0.1,
|
||||||
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
plugin_state_path="/tmp/nonexistent_plugin_state.json",
|
||||||
detection_interval=0.1,
|
)
|
||||||
plugin_state_path="/tmp/nonexistent_plugin_state.json",
|
dt.check()
|
||||||
)
|
assert routing_telemetry.heartbeat_detection_source == "pgrep"
|
||||||
dt.check()
|
|
||||||
assert routing_telemetry.heartbeat_detection_source == "pgrep"
|
|
||||||
|
|
||||||
def test_detection_source_gateway(self, tmp_path):
|
def test_detection_source_gateway(self, tmp_path):
|
||||||
"""gateway_state entscheidet → source='gateway'."""
|
"""gateway_state entscheidet → source='gateway'."""
|
||||||
@@ -2302,15 +2277,13 @@ class TestDetectionSourceTelemetry:
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
|
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
|
||||||
# P2: PID-Sentinel deaktivieren, damit gateway_state getestet wird
|
dt = DetectionTimer(
|
||||||
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
gateway_state_path=gw_path,
|
||||||
dt = DetectionTimer(
|
detection_interval=0.1,
|
||||||
gateway_state_path=gw_path,
|
)
|
||||||
detection_interval=0.1,
|
dt.check()
|
||||||
)
|
assert routing_telemetry.heartbeat_detection_source == "gateway"
|
||||||
dt.check()
|
mock_run.assert_not_called()
|
||||||
assert routing_telemetry.heartbeat_detection_source == "gateway"
|
|
||||||
mock_run.assert_not_called()
|
|
||||||
finally:
|
finally:
|
||||||
os.unlink(gw_path)
|
os.unlink(gw_path)
|
||||||
|
|
||||||
@@ -2338,230 +2311,337 @@ class TestPresenceEnginePluginStateIntegration:
|
|||||||
|
|
||||||
|
|
||||||
# ═══════════════════════════════════════════════════════════════════════════
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
# P2 Fix: Presence-Engine Detection — Option D (PID-Sentinel + Semantik)
|
# P1: Circuit-Breaker — 429-Schutz im PulseController
|
||||||
# Tests T1-T8 (Rainer approved)
|
|
||||||
# ═══════════════════════════════════════════════════════════════════════════
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
|
||||||
class TestPidSentinelDetectsAliveGateway:
|
class TestCircuitBreakerStateTransitions:
|
||||||
"""T1: PID-Sentinel erkennt lebenden Gateway-Prozess."""
|
"""P1: Circuit-Breaker state machine — CLOSED → OPEN → HALF_OPEN → CLOSED."""
|
||||||
|
|
||||||
def test_pid_sentinel_detects_alive_gateway(self):
|
def test_breaker_starts_closed(self):
|
||||||
"""_check_gateway_pid_alive() liefert True wenn /proc/<ppid> existiert."""
|
"""Neuer PulseController startet im CLOSED state."""
|
||||||
from plugin.archivar.presence_engine import DetectionTimer
|
from plugin.archivar.presence_engine import PulseController
|
||||||
|
|
||||||
dt = DetectionTimer(
|
pc = PulseController(pulse_interval=0.05, _clamp_pulse=False)
|
||||||
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
assert pc.get_breaker_state() == "CLOSED"
|
||||||
detection_interval=0.1,
|
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()
|
def test_backoff_capped_at_max(self):
|
||||||
assert result is True
|
"""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:
|
class TestCircuitBreakerDdpErrorClassification:
|
||||||
"""T2: PID-Sentinel erkennt toten Gateway-Prozess."""
|
"""P1: DDP-Error-Klassifizierung — 'server returned false' kein REST-Fallback."""
|
||||||
|
|
||||||
def test_pid_sentinel_dead_gateway(self):
|
def test_server_returned_false_is_transient(self):
|
||||||
"""_check_gateway_pid_alive() liefert False wenn /proc/<ppid> nicht existiert."""
|
"""'server returned false' wird als ddp_transient klassifiziert."""
|
||||||
from plugin.archivar.presence_engine import DetectionTimer
|
from plugin.archivar.presence_engine import PulseController
|
||||||
|
|
||||||
dt = DetectionTimer(
|
pc = PulseController(pulse_interval=0.05, _clamp_pulse=False)
|
||||||
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
result = pc._classify_ddp_error(Exception("DDP: server returned false"))
|
||||||
detection_interval=0.1,
|
assert result == "ddp_transient"
|
||||||
)
|
|
||||||
# Mock: os.getppid() liefert eine nicht-existente PID
|
def test_429_error_is_classified_as_429(self):
|
||||||
with patch('plugin.archivar.presence_engine.os.getppid') as mock_getppid:
|
"""HTTP 429 wird als '429' klassifiziert."""
|
||||||
mock_getppid.return_value = 999999 # nicht-existente PID
|
from plugin.archivar.presence_engine import PulseController
|
||||||
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("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:
|
class TestCircuitBreakerRecordSuccess:
|
||||||
"""T3: gateway_state.json Schwelle >0 statt >1."""
|
"""P1: _record_success() resetet Breaker und pulse_interval."""
|
||||||
|
|
||||||
def test_gateway_state_threshold_zero(self):
|
def test_record_success_resets_everything(self):
|
||||||
"""active_agents=1 → gateway_state erkennt als aktiv (Schwelle >0)."""
|
"""_record_success() → CLOSED, 429s=0, backoff=0, pulse_interval=base."""
|
||||||
from plugin.archivar.presence_engine import DetectionTimer
|
from plugin.archivar.presence_engine import PulseController
|
||||||
import tempfile
|
|
||||||
import json
|
|
||||||
|
|
||||||
# gateway_state mit active_agents=1 (war vorher >1, jetzt >0)
|
pc = PulseController(pulse_interval=1.5, _clamp_pulse=False)
|
||||||
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
|
|
||||||
|
|
||||||
try:
|
# Manuell in OPEN setzen
|
||||||
# Mock pgrep: findet nichts (damit gateway_state entscheidet)
|
pc._breaker_state = "OPEN"
|
||||||
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
|
pc._consecutive_429s = 5
|
||||||
mock_run.return_value = MagicMock(
|
pc._backoff_level = 2
|
||||||
stdout="",
|
pc._pulse_interval = 60.0
|
||||||
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)
|
|
||||||
|
|
||||||
|
pc._record_success()
|
||||||
|
|
||||||
class TestPgrepPatternMatchesGatewayRun:
|
assert pc.get_breaker_state() == "CLOSED"
|
||||||
"""T4: pgrep-Pattern matcht 'gateway run'."""
|
assert pc.get_consecutive_429s() == 0
|
||||||
|
assert pc.get_effective_pulse_interval() == 1.5
|
||||||
|
|
||||||
def test_pgrep_pattern_matches_gateway_run(self):
|
def test_success_after_open_resets_interval(self):
|
||||||
"""pgrep -f 'hermes_cli|hermes chat|gateway run' findet Gateway-Prozess."""
|
"""Nach OPEN→HALF_OPEN→success: pulse_interval zurück auf base."""
|
||||||
from plugin.archivar.presence_engine import DetectionTimer
|
from plugin.archivar.presence_engine import PulseController
|
||||||
|
|
||||||
own_pid = os.getpid()
|
call_count = [0]
|
||||||
|
|
||||||
# Mock pgrep: findet einen 'gateway run'-Prozess (nicht eigenen PID)
|
def ddp_side_effect(status):
|
||||||
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
|
call_count[0] += 1
|
||||||
mock_run.return_value = MagicMock(
|
if call_count[0] <= 3:
|
||||||
stdout="12345\n", # anderer PID, nicht own_pid
|
raise Exception("HTTP 429 Too Many Requests")
|
||||||
stderr="",
|
return True
|
||||||
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
|
|
||||||
|
|
||||||
# Prüfe dass das pgrep-Pattern 'gateway run' enthält
|
mock_ddp = MagicMock()
|
||||||
call_args = mock_run.call_args[0][0]
|
mock_ddp.connected = True
|
||||||
pattern_arg = None
|
mock_ddp.set_status = MagicMock(side_effect=ddp_side_effect)
|
||||||
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}"
|
|
||||||
)
|
|
||||||
|
|
||||||
|
pc = PulseController(pulse_interval=1.5, _clamp_pulse=False)
|
||||||
|
pc.bind_ddp(mock_ddp)
|
||||||
|
|
||||||
class TestIdlePulseContinuesWhenGatewayAlive:
|
# 3×429 → OPEN (pulse_interval=5.0)
|
||||||
"""T5: Gateway läuft, keine Subagenten → Detection='active', Status='online'."""
|
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):
|
# Cooldown ablaufen → HALF_OPEN → success → CLOSED
|
||||||
"""PID-Sentinel erkennt Gateway → check()=True auch ohne Subagenten."""
|
pc._breaker_opened_at = time.monotonic() - pc._breaker_cooldown_s - 1.0
|
||||||
from plugin.archivar.presence_engine import DetectionTimer
|
pc._pulse_tick()
|
||||||
|
|
||||||
# PID-Sentinel: Gateway lebt
|
assert pc.get_breaker_state() == "CLOSED"
|
||||||
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=True):
|
assert pc.get_effective_pulse_interval() == 1.5
|
||||||
# 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}'"
|
|
||||||
)
|
|
||||||
|
|||||||
Reference in New Issue
Block a user