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:
Bernd (Hermes)
2026-09-02 06:30:09 +02:00
parent 6edf167fd0
commit 9798a3e8a0
9 changed files with 902 additions and 9 deletions
+241
View File
@@ -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()
@@ -0,0 +1,131 @@
"""
F100 — RoutingCounter-Erweiterung: record_attempt() + success_ratio().
Testkonzept (D3):
1. record_attempt_window: Attempts im Fenster zählen, ältere nicht.
2. min_samples_guard: < min_samples → None.
3. threshold_boundary: ratio exakt an der Schwelle.
4. window_gc: Einträge älter als window_s werden beim Lesen gefiltert.
5. Rückwärts-Kompatibilität: increment() unverändert (P-019).
"""
from __future__ import annotations
import sys
from pathlib import Path
import pytest
sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
from plugin.archivar.routing_counter import RoutingCounter
@pytest.fixture
def counter():
return RoutingCounter()
class TestRecordAttemptWindow:
"""Attempts im Fenster zählen, ältere nicht."""
def test_all_in_window_ratio_1(self, counter):
for i in range(10):
counter.record_attempt(True, timestamp=1000.0 + i)
ratio = counter.success_ratio(window_s=3600.0, min_samples=10, now=1000.0 + 10)
assert ratio == 1.0
def test_old_attempts_excluded(self, counter):
# 5 Attempts vor dem Fenster, 5 im Fenster.
# now=1000, window=100 → cutoff=900. Alte Attempts bei 0..4 (< 900).
for i in range(5):
counter.record_attempt(False, timestamp=0.0 + i) # alt (vor Fenster)
for i in range(5):
counter.record_attempt(True, timestamp=1000.0 + i) # im Fenster
ratio = counter.success_ratio(window_s=100.0, min_samples=5, now=1000.0 + 5)
assert ratio == 1.0 # nur die 5 im Fenster zählen
def test_mixed_ratio(self, counter):
# 8 Erfolge + 2 Fehler = 0.8
for i in range(8):
counter.record_attempt(True, timestamp=1000.0 + i)
for i in range(2):
counter.record_attempt(False, timestamp=1000.0 + 8 + i)
ratio = counter.success_ratio(window_s=3600.0, min_samples=10, now=1000.0 + 10)
assert ratio == pytest.approx(0.8)
class TestMinSamplesGuard:
"""< min_samples → None (K2)."""
def test_three_attempts_returns_none(self, counter):
for i in range(3):
counter.record_attempt(True, timestamp=1000.0 + i)
ratio = counter.success_ratio(window_s=3600.0, min_samples=10, now=1000.0 + 3)
assert ratio is None
def test_exactly_min_samples_returns_ratio(self, counter):
for i in range(10):
counter.record_attempt(True, timestamp=1000.0 + i)
ratio = counter.success_ratio(window_s=3600.0, min_samples=10, now=1000.0 + 10)
assert ratio == 1.0
def test_zero_attempts_returns_none(self, counter):
assert counter.success_ratio(window_s=3600.0, min_samples=10, now=1000.0) is None
class TestThresholdBoundary:
"""ratio exakt an der Schwelle (0.79 → trigger, 0.81 → kein trigger)."""
def test_ratio_079(self, counter):
# 79 Erfolge + 21 Fehler = 0.79
for i in range(79):
counter.record_attempt(True, timestamp=1000.0 + i)
for i in range(21):
counter.record_attempt(False, timestamp=1000.0 + 79 + i)
ratio = counter.success_ratio(window_s=3600.0, min_samples=100, now=1000.0 + 100)
assert ratio == pytest.approx(0.79)
def test_ratio_081(self, counter):
# 81 Erfolge + 19 Fehler = 0.81
for i in range(81):
counter.record_attempt(True, timestamp=1000.0 + i)
for i in range(19):
counter.record_attempt(False, timestamp=1000.0 + 81 + i)
ratio = counter.success_ratio(window_s=3600.0, min_samples=100, now=1000.0 + 100)
assert ratio == pytest.approx(0.81)
class TestWindowGC:
"""Einträge älter als window_s werden beim Lesen gefiltert (Ring-Buffer)."""
def test_gc_removes_old_entries(self, counter):
for i in range(10):
counter.record_attempt(True, timestamp=1000.0 + i)
# Nach dem Lesen mit engem Fenster sind die alten Einträge weg.
# now=2000, window=1 → cutoff=1999. Alle Attempts (1000..1009) < 1999.
counter.success_ratio(window_s=1.0, min_samples=1, now=2000.0)
# attempt_count mit engem Fenster → 0 (alle gefiltert).
assert counter.attempt_count(window_s=1.0, now=2000.0) == 0
def test_gc_keeps_recent_entries(self, counter):
for i in range(10):
counter.record_attempt(True, timestamp=1000.0 + i)
counter.success_ratio(window_s=3600.0, min_samples=1, now=1000.0 + 10)
assert counter.attempt_count(window_s=3600.0, now=1000.0 + 10) == 10
class TestBackwardCompatibility:
"""increment() bleibt unverändert (P-019 — 165 Call-Sites)."""
def test_increment_still_works(self, counter):
counter.increment("llm_room_lookup_timeout")
counter.increment("llm_room_lookup_timeout")
assert counter.get_counts()["llm_room_lookup_timeout"] == 2
def test_reset_clears_both(self, counter):
counter.increment("foo")
counter.record_attempt(True, timestamp=1000.0)
counter.reset()
assert counter.get_counts() == {}
assert counter.attempt_count(window_s=3600.0, now=1000.0) == 0
+116 -1
View File
@@ -42,6 +42,8 @@ def _result(**overrides) -> ComponentCheckResult:
llm_model_loaded=True,
embedding_ladbar=True,
ready=True,
llm_room_e2e_ok=True,
llm_room_e2e_latency_ms=123.0,
)
base.update(overrides)
# ready ist abgeleitet — neu berechnen, außer explizit gesetzt.
@@ -52,6 +54,7 @@ def _result(**overrides) -> ComponentCheckResult:
and base["ollama_reachable"]
and base["llm_model_loaded"]
and base["embedding_ladbar"]
and base["llm_room_e2e_ok"]
)
return ComponentCheckResult(**base)
@@ -96,11 +99,13 @@ class TestCheckComponents:
patch("plugin.archivar.self_check._probe_index_loadable", return_value=True), \
patch("plugin.archivar.self_check._probe_ollama_reachable", return_value=True), \
patch("plugin.archivar.self_check._probe_models", return_value=["qwen2.5:7b", "nomic-embed-text"]), \
patch("plugin.archivar.self_check._probe_embedding", return_value=True):
patch("plugin.archivar.self_check._probe_embedding", return_value=True), \
patch("plugin.archivar.self_check._probe_llm_room_e2e", return_value=(True, 123.0, "")):
r = check_components()
assert r.ready is True
assert r.faiss_importable and r.index_loadable and r.ollama_reachable
assert r.llm_model_loaded and r.embedding_ladbar
assert r.llm_room_e2e_ok is True
def test_faiss_missing_reports_error_stage1(self):
with patch("plugin.archivar.self_check._probe_faiss_importable", return_value=False), \
@@ -265,3 +270,113 @@ class TestAdapterSelfCheckWiring:
def test_timeout_default_is_30s(self):
assert SELF_CHECK_TIMEOUT_S == 30.0
# ── F100: Stufe 4b — Router-E2E-Probe ──────────────────────────────────────
class TestStufe4bProbe:
"""_probe_llm_room_e2e(): POST /api/generate mit Mini-Prompt "STAY"."""
def test_probe_ok_on_stay_response(self):
from plugin.archivar.self_check import _probe_llm_room_e2e
class _Resp:
def read(self):
return b'{"response": "STAY"}'
def __enter__(self):
return self
def __exit__(self, *a):
return False
with patch("plugin.archivar.self_check.urllib.request.urlopen", return_value=_Resp()):
ok, latency_ms, detail = _probe_llm_room_e2e(
"http://localhost:11434", "qwen2.5:7b", 15.0
)
assert ok is True
assert latency_ms >= 0.0
assert detail == ""
def test_probe_ok_case_insensitive(self):
from plugin.archivar.self_check import _probe_llm_room_e2e
class _Resp:
def read(self):
return b'{"response": " stay "}'
def __enter__(self):
return self
def __exit__(self, *a):
return False
with patch("plugin.archivar.self_check.urllib.request.urlopen", return_value=_Resp()):
ok, _, _ = _probe_llm_room_e2e("http://localhost:11434", "qwen2.5:7b", 15.0)
assert ok is True
def test_probe_fail_on_garbage_response(self):
from plugin.archivar.self_check import _probe_llm_room_e2e
class _Resp:
def read(self):
return '{"response": "völlig anderer Text"}'.encode("utf-8")
def __enter__(self):
return self
def __exit__(self, *a):
return False
with patch("plugin.archivar.self_check.urllib.request.urlopen", return_value=_Resp()):
ok, _, detail = _probe_llm_room_e2e("http://localhost:11434", "qwen2.5:7b", 15.0)
assert ok is False
assert "unerwartete Antwort" in detail
def test_probe_fail_on_http_error(self):
from plugin.archivar.self_check import _probe_llm_room_e2e
import urllib.error
with patch(
"plugin.archivar.self_check.urllib.request.urlopen",
side_effect=urllib.error.URLError("connection refused"),
):
ok, latency_ms, detail = _probe_llm_room_e2e(
"http://localhost:11434", "qwen2.5:7b", 15.0
)
assert ok is False
assert latency_ms == 0.0
assert "Fehler" in detail
def test_probe_fail_on_timeout(self):
from plugin.archivar.self_check import _probe_llm_room_e2e
import socket
with patch(
"plugin.archivar.self_check.urllib.request.urlopen",
side_effect=socket.timeout("timed out"),
):
ok, _, _ = _probe_llm_room_e2e("http://localhost:11434", "qwen2.5:7b", 15.0)
assert ok is False
class TestComponentCheckResult4b:
"""Stufe 4b-Fail → needs_warmup=True, ready=False (Warmup, kein Fehler)."""
def test_4b_fail_is_warmup_not_error(self):
r = _result(llm_room_e2e_ok=False)
assert r.has_error is False
assert r.needs_warmup is True
assert r.ready is False
def test_4b_ok_ready(self):
r = _result(llm_room_e2e_ok=True)
assert r.ready is True
assert r.needs_warmup is False
def test_4b_fail_build_report_message_is_warmup(self):
msg = build_report_message(_result(llm_room_e2e_ok=False))
assert msg is not None
assert "./install.sh --repair" not in msg
assert "lade" in msg.lower() or "laden" in msg.lower()