feat(F100): Self-Check Stufe 4b (Router-E2E) + Runtime-Watchdog
Zweite Verteidigungslinie gegen die 110 Router-Timeouts/7d (Andreas-Direktive 01.09.): Stufe 4b prüft beim Start, dass Modell+Endpoint wirklich antworten (Smoke-Test), der Runtime-Watchdog misst die echte Router-Pipeline über record_attempt() nach jedem Live-Call. D1 Stufe 4b (self_check.py): - _probe_llm_room_e2e(): POST /api/generate mit Mini-Prompt, Latenz <= 15s - ComponentCheckResult + llm_room_e2e_ok / llm_room_e2e_latency_ms - ready = ... AND llm_room_e2e_ok; needs_warmup schliesst 4b-Fail ein - Prompt empirisch kalibriert (qwen2.5:7b): 'Antworte ausschließlich mit dem Wort STAY' statt naivem 'genau einem Wort: STAY' (lieferte 'Ok.') D2 Runtime-Watchdog (routing_counter.py + router.py + adapter.py): - RoutingCounter.record_attempt() + success_ratio(window_s, min_samples) (NEUE Methoden, increment() unverändert — P-019, 165 Call-Sites) - record_attempt() an success/timeout/exception-Branches (router.py Z.1670+) - _start_routing_watchdog() neben _start_self_check() in connect() - 5 Konstanten in config.py (Kalibrierungs-Kommentar 'nach 7 Tagen prüfen') K3 Cooldown (watchdog_alert.py, NEU): - 24h-Cooldown + persistentes Flag in ~/.hermes/hermes-agent/data/ routing_watchdog_alert.json (last_alert_ts, atomar via tmp+rename P-101) - logger.error (KEIN RC-Post, P-088-Lehre) D3 Tests: test_f92_self_check erweitert (TestStufe4bProbe, TestComponentCheckResult4b), test_f92_routing_counter.py (Window/Min-Samples/ Boundary/GC), test_f100_watchdog.py (Trigger/Cooldown/Min-Samples/Persistenz). D4 Verifikation: echte Probe gegen localhost:11434 (qwen2.5:7b) → ok=True, latency ~850ms. 98 Tests grün (F92/F93/F100 + Stufe4-Red-Flag). KEIN Push, KEIN Deploy — wartet auf QG-Freigabe Rainer.
This commit is contained in:
@@ -0,0 +1,241 @@
|
||||
"""
|
||||
F100 — Runtime-Watchdog: Trigger, Cooldown, Min-Samples-Guard, Persistenz.
|
||||
|
||||
Testkonzept (D3):
|
||||
1. Trigger: success_ratio unter Schwelle → ERROR-Alert + Cooldown gesetzt.
|
||||
2. Cooldown: zweiter Trigger innerhalb 24h → kein zweites Alert.
|
||||
3. Min-Samples-Guard: ratio=None → kein Alert.
|
||||
4. Persistenz: Cooldown-Flag überlebt "Restart" (load from file).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
|
||||
|
||||
from plugin.archivar.watchdog_alert import WatchdogAlertCooldown
|
||||
|
||||
|
||||
# ── WatchdogAlertCooldown (K3: persistentes Cooldown-Flag) ─────────────────
|
||||
|
||||
|
||||
class TestWatchdogAlertCooldown:
|
||||
"""Cooldown-Buchhaltung: is_in_cooldown / mark_alerted / Persistenz."""
|
||||
|
||||
def test_not_in_cooldown_initially(self):
|
||||
c = WatchdogAlertCooldown(cooldown_s=86400.0, state_path=None)
|
||||
assert c.is_in_cooldown(now=1000.0) is False
|
||||
|
||||
def test_in_cooldown_after_mark(self):
|
||||
c = WatchdogAlertCooldown(cooldown_s=86400.0, state_path=None)
|
||||
c.mark_alerted(now=1000.0)
|
||||
assert c.is_in_cooldown(now=1000.0) is True
|
||||
assert c.is_in_cooldown(now=1000.0 + 86399.0) is True
|
||||
|
||||
def test_cooldown_expires(self):
|
||||
c = WatchdogAlertCooldown(cooldown_s=86400.0, state_path=None)
|
||||
c.mark_alerted(now=1000.0)
|
||||
assert c.is_in_cooldown(now=1000.0 + 86400.0) is False
|
||||
|
||||
def test_persistence_survives_restart(self, tmp_path):
|
||||
state_path = str(tmp_path / "routing_watchdog_alert.json")
|
||||
c1 = WatchdogAlertCooldown(cooldown_s=86400.0, state_path=state_path)
|
||||
c1.mark_alerted(now=1000.0)
|
||||
|
||||
# "Restart": neue Instanz lädt aus derselben Datei.
|
||||
c2 = WatchdogAlertCooldown(cooldown_s=86400.0, state_path=state_path)
|
||||
assert c2.last_alert_ts == pytest.approx(1000.0)
|
||||
assert c2.is_in_cooldown(now=1000.0 + 100.0) is True
|
||||
|
||||
def test_persistence_file_content(self, tmp_path):
|
||||
state_path = str(tmp_path / "routing_watchdog_alert.json")
|
||||
c = WatchdogAlertCooldown(cooldown_s=86400.0, state_path=state_path)
|
||||
c.mark_alerted(now=1234.5)
|
||||
with open(state_path, "r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
assert data["last_alert_ts"] == pytest.approx(1234.5)
|
||||
|
||||
def test_missing_file_is_not_in_cooldown(self, tmp_path):
|
||||
state_path = str(tmp_path / "does_not_exist.json")
|
||||
c = WatchdogAlertCooldown(cooldown_s=86400.0, state_path=state_path)
|
||||
assert c.is_in_cooldown(now=1000.0) is False
|
||||
|
||||
|
||||
# ── Adapter-Watchdog-Schleife (Trigger / Cooldown / Min-Samples-Guard) ──────
|
||||
|
||||
|
||||
class TestRoutingWatchdogLoop:
|
||||
"""_run_routing_watchdog(): Trigger-Logik mit Cooldown + Min-Samples."""
|
||||
|
||||
def _make_adapter(self):
|
||||
from plugin.adapter import RocketChatAdapter
|
||||
adapter = RocketChatAdapter.__new__(RocketChatAdapter)
|
||||
adapter.archivar = MagicMock()
|
||||
return adapter
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_trigger_logs_error_and_sets_cooldown(self):
|
||||
adapter = self._make_adapter()
|
||||
|
||||
# success_ratio liefert 0.5 (unter Schwelle 0.8), Cooldown inaktiv.
|
||||
fake_counter = MagicMock()
|
||||
fake_counter.success_ratio.return_value = 0.5
|
||||
fake_counter.attempt_count.return_value = 10
|
||||
|
||||
# Stateful Cooldown: nach dem ersten mark_alerted() aktiv (wie echt).
|
||||
state = {"alerted": False}
|
||||
|
||||
class _FakeCooldown:
|
||||
def is_in_cooldown(self):
|
||||
return state["alerted"]
|
||||
|
||||
def mark_alerted(self):
|
||||
state["alerted"] = True
|
||||
|
||||
fake_cooldown = _FakeCooldown()
|
||||
|
||||
with patch("archivar.routing_counter.routing_counter", fake_counter), \
|
||||
patch("archivar.watchdog_alert.watchdog_alert_cooldown", fake_cooldown), \
|
||||
patch("archivar.config.LLM_ROOM_WATCHDOG_INTERVAL_S", 0), \
|
||||
patch("archivar.config.LLM_ROOM_WATCHDOG_WINDOW_S", 3600), \
|
||||
patch("archivar.config.LLM_ROOM_WATCHDOG_THRESHOLD", 0.80), \
|
||||
patch("archivar.config.LLM_ROOM_WATCHDOG_MIN_SAMPLES", 10), \
|
||||
patch("plugin.adapter.logger") as mock_logger:
|
||||
import asyncio
|
||||
task = asyncio.ensure_future(adapter._run_routing_watchdog())
|
||||
# Ein Tick abwarten, dann abbrechen.
|
||||
await asyncio.sleep(0.05)
|
||||
task.cancel()
|
||||
try:
|
||||
await task
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
|
||||
assert state["alerted"] is True
|
||||
# ERROR-Alert wurde geloggt (genau einmal — Cooldown greift danach).
|
||||
error_calls = [
|
||||
c for c in mock_logger.error.call_args_list
|
||||
if "RUNTIME-WATCHDOG" in str(c.args[0])
|
||||
]
|
||||
assert len(error_calls) == 1
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_cooldown_suppresses_second_alert(self):
|
||||
adapter = self._make_adapter()
|
||||
|
||||
fake_counter = MagicMock()
|
||||
fake_counter.success_ratio.return_value = 0.5
|
||||
fake_counter.attempt_count.return_value = 10
|
||||
fake_cooldown = MagicMock()
|
||||
fake_cooldown.is_in_cooldown.return_value = True # Cooldown aktiv
|
||||
|
||||
with patch("archivar.routing_counter.routing_counter", fake_counter), \
|
||||
patch("archivar.watchdog_alert.watchdog_alert_cooldown", fake_cooldown), \
|
||||
patch("archivar.config.LLM_ROOM_WATCHDOG_INTERVAL_S", 0), \
|
||||
patch("archivar.config.LLM_ROOM_WATCHDOG_WINDOW_S", 3600), \
|
||||
patch("archivar.config.LLM_ROOM_WATCHDOG_THRESHOLD", 0.80), \
|
||||
patch("archivar.config.LLM_ROOM_WATCHDOG_MIN_SAMPLES", 10), \
|
||||
patch("plugin.adapter.logger") as mock_logger:
|
||||
import asyncio
|
||||
task = asyncio.ensure_future(adapter._run_routing_watchdog())
|
||||
await asyncio.sleep(0.05)
|
||||
task.cancel()
|
||||
try:
|
||||
await task
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
|
||||
fake_cooldown.mark_alerted.assert_not_called()
|
||||
assert not any(
|
||||
"RUNTIME-WATCHDOG" in str(c.args[0])
|
||||
for c in mock_logger.error.call_args_list
|
||||
)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_min_samples_guard_no_alert(self):
|
||||
adapter = self._make_adapter()
|
||||
|
||||
fake_counter = MagicMock()
|
||||
fake_counter.success_ratio.return_value = None # < min_samples (K2)
|
||||
fake_cooldown = MagicMock()
|
||||
fake_cooldown.is_in_cooldown.return_value = False
|
||||
|
||||
with patch("archivar.routing_counter.routing_counter", fake_counter), \
|
||||
patch("archivar.watchdog_alert.watchdog_alert_cooldown", fake_cooldown), \
|
||||
patch("archivar.config.LLM_ROOM_WATCHDOG_INTERVAL_S", 0), \
|
||||
patch("archivar.config.LLM_ROOM_WATCHDOG_WINDOW_S", 3600), \
|
||||
patch("archivar.config.LLM_ROOM_WATCHDOG_THRESHOLD", 0.80), \
|
||||
patch("archivar.config.LLM_ROOM_WATCHDOG_MIN_SAMPLES", 10), \
|
||||
patch("plugin.adapter.logger") as mock_logger:
|
||||
import asyncio
|
||||
task = asyncio.ensure_future(adapter._run_routing_watchdog())
|
||||
await asyncio.sleep(0.05)
|
||||
task.cancel()
|
||||
try:
|
||||
await task
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
|
||||
fake_cooldown.mark_alerted.assert_not_called()
|
||||
assert not any(
|
||||
"RUNTIME-WATCHDOG" in str(c.args[0])
|
||||
for c in mock_logger.error.call_args_list
|
||||
)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_ratio_above_threshold_no_alert(self):
|
||||
adapter = self._make_adapter()
|
||||
|
||||
fake_counter = MagicMock()
|
||||
fake_counter.success_ratio.return_value = 0.95 # über Schwelle
|
||||
fake_cooldown = MagicMock()
|
||||
fake_cooldown.is_in_cooldown.return_value = False
|
||||
|
||||
with patch("archivar.routing_counter.routing_counter", fake_counter), \
|
||||
patch("archivar.watchdog_alert.watchdog_alert_cooldown", fake_cooldown), \
|
||||
patch("archivar.config.LLM_ROOM_WATCHDOG_INTERVAL_S", 0), \
|
||||
patch("archivar.config.LLM_ROOM_WATCHDOG_WINDOW_S", 3600), \
|
||||
patch("archivar.config.LLM_ROOM_WATCHDOG_THRESHOLD", 0.80), \
|
||||
patch("archivar.config.LLM_ROOM_WATCHDOG_MIN_SAMPLES", 10), \
|
||||
patch("plugin.adapter.logger") as mock_logger:
|
||||
import asyncio
|
||||
task = asyncio.ensure_future(adapter._run_routing_watchdog())
|
||||
await asyncio.sleep(0.05)
|
||||
task.cancel()
|
||||
try:
|
||||
await task
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
|
||||
fake_cooldown.mark_alerted.assert_not_called()
|
||||
|
||||
|
||||
class TestStartRoutingWatchdog:
|
||||
"""_start_routing_watchdog(): nicht-blockierend, MULTIROOM-Guard."""
|
||||
|
||||
def _make_adapter(self):
|
||||
from plugin.adapter import RocketChatAdapter
|
||||
adapter = RocketChatAdapter.__new__(RocketChatAdapter)
|
||||
adapter.archivar = MagicMock()
|
||||
return adapter
|
||||
|
||||
def test_skips_when_not_multiroom(self):
|
||||
adapter = self._make_adapter()
|
||||
adapter.archivar = None
|
||||
with patch("plugin.adapter._MULTIROOM", return_value=False), \
|
||||
patch("plugin.adapter.asyncio.ensure_future") as mock_ef:
|
||||
adapter._start_routing_watchdog()
|
||||
mock_ef.assert_not_called()
|
||||
|
||||
def test_starts_when_multiroom(self):
|
||||
adapter = self._make_adapter()
|
||||
with patch("plugin.adapter._MULTIROOM", return_value=True), \
|
||||
patch("plugin.adapter.asyncio.ensure_future") as mock_ef:
|
||||
adapter._start_routing_watchdog()
|
||||
mock_ef.assert_called_once()
|
||||
Reference in New Issue
Block a user