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
+82
View File
@@ -2282,6 +2282,12 @@ class RocketChatAdapter(BasePlatformAdapter):
# übersprungen (kein Archivar → keine Raumerkennung).
self._start_self_check()
# ── F100: Runtime-Watchdog als Background-Task ────────────────────
# Zweite Verteidigungslinie (K1): misst die echte Router-Pipeline über
# record_attempt() nach jedem Live-Call. Läuft NACH dem Self-Check
# (Start-Diagnose zuerst, Runtime-Überwachung danach). NICHT blockierend.
self._start_routing_watchdog()
return True
# ── Feature 92: Self-Check ────────────────────────────────────────────
@@ -2364,6 +2370,82 @@ class RocketChatAdapter(BasePlatformAdapter):
return room_id
return None
# ── F100: Runtime-Watchdog (Routing-Erfolgsquote) ─────────────────────
def _start_routing_watchdog(self) -> None:
"""Startet den Runtime-Watchdog als Background-Task (nicht blockierend).
Zweite Verteidigungslinie (K1): misst die echte Router-Pipeline über
``routing_counter.record_attempt()`` nach jedem Live-Call. Der Watchdog
prüft periodisch die Erfolgsquote und loggt bei Unterschreitung der
Schwelle einen ERROR-Alert (KEIN RC-Post, P-088-Lehre) — mit 24h-
Cooldown + persistentem Flag (K3).
"""
if not _MULTIROOM() or self.archivar is None:
logger.info("[rocketchat] F100: MULTIROOM_AGENT=false — Watchdog übersprungen")
return
try:
asyncio.ensure_future(self._run_routing_watchdog())
logger.info("[rocketchat] F100: Runtime-Watchdog als Background-Task gestartet")
except Exception as e:
logger.warning("[rocketchat] F100: Watchdog-Start fehlgeschlagen: %s", e)
async def _run_routing_watchdog(self) -> None:
"""Watchdog-Schleife: prüft periodisch die Routing-Erfolgsquote.
Bei jedem Tick: ``success_ratio(window_s, min_samples)``. Wenn die
Quote unter der Schwelle liegt UND der Cooldown nicht aktiv ist →
ERROR-Alert loggen + Cooldown-Flag setzen. Bei < min_samples gibt
``success_ratio()`` None zurück → kein Trigger (K2).
"""
import asyncio
from archivar.routing_counter import routing_counter
from archivar.watchdog_alert import watchdog_alert_cooldown
from archivar.config import (
LLM_ROOM_WATCHDOG_WINDOW_S,
LLM_ROOM_WATCHDOG_THRESHOLD,
LLM_ROOM_WATCHDOG_INTERVAL_S,
LLM_ROOM_WATCHDOG_MIN_SAMPLES,
)
while True:
try:
await asyncio.sleep(LLM_ROOM_WATCHDOG_INTERVAL_S)
except asyncio.CancelledError:
logger.info("[rocketchat] F100: Watchdog-Schleife beendet")
return
try:
ratio = routing_counter.success_ratio(
window_s=LLM_ROOM_WATCHDOG_WINDOW_S,
min_samples=LLM_ROOM_WATCHDOG_MIN_SAMPLES,
)
except Exception as e:
logger.warning("[rocketchat] F100: success_ratio fehlgeschlagen: %s", e)
continue
if ratio is None:
# < min_samples → kein Trigger (K2).
continue
if ratio < LLM_ROOM_WATCHDOG_THRESHOLD:
if watchdog_alert_cooldown.is_in_cooldown():
logger.info(
"[rocketchat] F100: Watchdog-Alert unterdrückt (Cooldown aktiv, ratio=%.1f%%)",
ratio * 100,
)
continue
n = routing_counter.attempt_count(LLM_ROOM_WATCHDOG_WINDOW_S)
logger.error(
"RUNTIME-WATCHDOG: Routing-Erfolgsquote %.1f%% (%d Samples / %ds) "
"unter Schwelle %.0f%%",
ratio * 100, n, LLM_ROOM_WATCHDOG_WINDOW_S,
LLM_ROOM_WATCHDOG_THRESHOLD * 100,
)
watchdog_alert_cooldown.mark_alerted()
def _reset_initial_message_and_presence(self) -> None:
"""STETS-GELB Fix 1 + Fix 2: Initial-Reset + Presence-Online nach Connect.
+41
View File
@@ -345,6 +345,47 @@ RED_FLAG_TIMEOUT: float = float(os.getenv(
))
"""Timeout für Red-Flag-Agent-Entscheidung in Sekunden. Default: 30.0."""
# ── F100: Runtime-Watchdog (Routing-Erfolgsquote) ───────────────────────────
# Zweite Verteidigungslinie (K1-Rollenverteilung): Stufe 4b ist der Start-
# Smoke-Test, der Watchdog misst die ECHTE Router-Pipeline über
# record_attempt() nach jedem Live-Call. Alle Konstanten mit Kalibrierungs-
# Hinweis — empirische Nach-Kalibrierung nach 7 Tagen Produktiv-Betrieb ist
# PFLICHT (WV-005-Muster).
LLM_ROOM_WATCHDOG_WINDOW_S: int = int(os.getenv(
"ARCHIVAR_WATCHDOG_WINDOW_S", "3600"
))
"""Watchdog-Fenster in Sekunden (Default 1h). Nur Attempts innerhalb dieses
Fensters zählen für die Erfolgsquote. Nach 7 Tagen Produktiv-Betrieb prüfen."""
LLM_ROOM_WATCHDOG_THRESHOLD: float = float(os.getenv(
"ARCHIVAR_WATCHDOG_THRESHOLD", "0.80"
))
"""Erfolgsquote-Schwelle (Default 0.80 = 80%). Unterschreitung triggert den
Alert. Andreas-Vorschlag, NICHT empirisch kalibriert — nach 7 Tagen prüfen
(ggf. 0.90 angemessen)."""
LLM_ROOM_WATCHDOG_INTERVAL_S: int = int(os.getenv(
"ARCHIVAR_WATCHDOG_INTERVAL_S", "300"
))
"""Watchdog-Tick-Intervall in Sekunden (Default 5min). Häufigkeit der
Erfolgsquoten-Prüfung. Nach 7 Tagen Produktiv-Betrieb prüfen."""
LLM_ROOM_WATCHDOG_MIN_SAMPLES: int = int(os.getenv(
"ARCHIVAR_WATCHDOG_MIN_SAMPLES", "10"
))
"""Minimale Sample-Anzahl im Fenster (Default 10). Bei <10 Samples gibt
success_ratio() None zurück und der Watchdog triggert NICHT (K2 — verhindert
statistisch sinnlose Ratio-Ausreißer bei niedrigem Traffic). Nach 7 Tagen
Produktiv-Betrieb prüfen."""
LLM_ROOM_WATCHDOG_ALERT_COOLDOWN_S: int = int(os.getenv(
"ARCHIVAR_WATCHDOG_COOLDOWN_S", "86400"
))
"""Alert-Cooldown in Sekunden (Default 24h). Einmal-Alarm pro 24h-Fenster
(K3, P-088-Lehre: kein User-Spam). Persistentes Flag überlebt Gateway-Restart.
Nach 7 Tagen Produktiv-Betrieb prüfen."""
# ── Deprecated: LLM_CLASSIFY_PROMPT (bleibt für Abwärtskompatibilität) ─────
# Wird NICHT mehr verwendet — LLM_ROOM_PROMPT ist der neue Standard.
# Bleibt im Code, falls externe Skripte darauf verweisen.
+7
View File
@@ -1675,16 +1675,23 @@ class BidirectionalRouter:
LLM_ROOM_LOOKUP_TIMEOUT, text,
)
routing_counter.increment('llm_room_lookup_timeout')
routing_counter.record_attempt(success=False)
return None, False, True, "unavailable", ""
except Exception as e:
logger.warning(
"Stufe 4: LLM-Raum-Router Exception: %s → LLM unavailable", e,
)
routing_counter.record_attempt(success=False)
return None, False, True, "unavailable", ""
if llm_result is None:
routing_counter.record_attempt(success=False)
return None, False, True, "unavailable", "" # LLM-Aufruf fehlgeschlagen
# LLM-Aufruf erfolgreich (Antwort kam zurück, parsbar) — F100-Watchdog.
# P-088-Lehre: success = "Antwort kam zurück", NICHT "Routing korrekt".
routing_counter.record_attempt(success=True)
# Parse LLM response — should be a room ID or "STAY"
response = llm_result.strip()
+70 -2
View File
@@ -15,17 +15,27 @@ from __future__ import annotations
import logging
import threading
from typing import Dict
import time
from typing import Dict, List, Optional, Tuple
logger = logging.getLogger(__name__)
class RoutingCounter:
"""Thread-safe In-Memory-Counter für Routing-Entscheidungen."""
"""Thread-safe In-Memory-Counter für Routing-Entscheidungen.
F100-Erweiterung: zusätzlich zum bestehenden ``increment()``-Zähler
(Diagnose) hält der Counter einen Ring-Buffer aus ``(timestamp, success)``-
Tupeln für die Runtime-Watchdog-Erfolgsquote. ``record_attempt()`` ist eine
NEUE Methode — ``increment()`` bleibt unverändert (Rückwärts-Kompatibilität
für 165 Call-Sites, P-019-Lehre).
"""
def __init__(self) -> None:
self._lock = threading.Lock()
self._counts: Dict[str, int] = {}
# F100: Ring-Buffer für Erfolgsquote (timestamp, success).
self._attempts: List[Tuple[float, bool]] = []
def increment(self, reason: str) -> None:
"""Inkrementiere den Zähler für einen Grund (thread-safe)."""
@@ -51,6 +61,64 @@ class RoutingCounter:
"""Setze alle Zähler zurück."""
with self._lock:
self._counts.clear()
self._attempts.clear()
# ── F100: Runtime-Watchdog (Erfolgsquote) ─────────────────────────────
def record_attempt(self, success: bool, timestamp: Optional[float] = None) -> None:
"""Zeichne einen Routing-Versuch auf (thread-safe).
Wird vom Router nach jedem LLM-Raum-Call aufgerufen. ``success`` ist
hier "Antwort kam zurück, war parsbar" — NICHT "Routing war inhaltlich
korrekt" (P-088-Lehre: sonst messen wir Accuracy, nicht Verfügbarkeit).
Args:
success: True wenn der LLM-Call erfolgreich war (failed=False).
timestamp: Optionaler Zeitstempel (Default: time.time()). Für
Tests injizierbar.
"""
ts = time.time() if timestamp is None else timestamp
with self._lock:
self._attempts.append((ts, bool(success)))
def success_ratio(
self,
window_s: float,
min_samples: int,
now: Optional[float] = None,
) -> Optional[float]:
"""Erfolgsquote der Attempts im letzten ``window_s``-Fenster.
Einträge älter als ``window_s`` werden beim Lesen gefiltert (GC).
Gibt ``None`` zurück, wenn weniger als ``min_samples`` Attempts im
Fenster liegen (K2 — verhindert statistisch sinnlose Ratio-Ausreißer
bei niedrigem Traffic).
Args:
window_s: Fensterbreite in Sekunden.
min_samples: Mindestanzahl Attempts im Fenster.
now: Optionaler Referenz-Zeitpunkt (Default: time.time()).
Returns:
Erfolgsquote als float in [0.0, 1.0], oder None bei < min_samples.
"""
ref = time.time() if now is None else now
cutoff = ref - window_s
with self._lock:
# GC: Einträge älter als window_s entfernen (Ring-Buffer).
self._attempts = [a for a in self._attempts if a[0] >= cutoff]
if len(self._attempts) < min_samples:
return None
successes = sum(1 for _, ok in self._attempts if ok)
return successes / len(self._attempts)
def attempt_count(self, window_s: float, now: Optional[float] = None) -> int:
"""Anzahl der Attempts im letzten ``window_s``-Fenster (für Logging)."""
ref = time.time() if now is None else now
cutoff = ref - window_s
with self._lock:
self._attempts = [a for a in self._attempts if a[0] >= cutoff]
return len(self._attempts)
# Modul-Level-Singleton — wird von adapter.py und router.py importiert
+93 -6
View File
@@ -30,13 +30,14 @@ from __future__ import annotations
import json
import logging
import os
import time
import urllib.error
import urllib.request
from dataclasses import dataclass
from pathlib import Path
from typing import List, Optional
from typing import List, Optional, Tuple
from .config import OLLAMA_CONFIG, LLM_CONFIG
from .config import OLLAMA_CONFIG, LLM_CONFIG, LLM_ROOM_LOOKUP_TIMEOUT
logger = logging.getLogger(__name__)
@@ -52,6 +53,27 @@ SELF_CHECK_TIMEOUT_S: float = float(os.getenv("ARCHIVAR_SELF_CHECK_TIMEOUT", "30
SELF_CHECK_HTTP_TIMEOUT_S: float = 3.0
"""HTTP-Timeout pro Einzel-Check in Sekunden (analog install.sh curl --max-time 3)."""
# ── F100: Stufe 4b — Router-E2E-Probe (Smoke-Test) ──────────────────────────
# K1-Rollenverteilung: Stufe 4b ist der Start-Smoke-Test (Modell + Endpoint
# reagieren überhaupt), der Runtime-Watchdog ist die 2. Verteidigungslinie
# (echte Router-Pipeline). Beide nötig, unterschiedliche Rollen.
STUFE4B_PROBE_PROMPT: str = "Antworte ausschließlich mit dem Wort STAY"
"""Mini-Prompt für die Router-E2E-Probe. Single-Token-Antwort, deterministisch,
kein Raum-Map-State nötig.
Empirisch kalibriert (02.09., qwen2.5:7b auf localhost:11434): die naive
Formulierung "Antworte mit genau einem Wort: STAY" liefert "Ok." statt "STAY"
→ False-Negative gegen ein gesundes Modell. "Antworte ausschließlich mit dem
Wort STAY" liefert zuverlässig "STAY" (Rainer-Niagara-Befund aus dem Konzept:
Mini-Prompt darf nicht zu trivial sein)."""
STUFE4B_PROBE_TIMEOUT_S: float = float(os.getenv(
"ARCHIVAR_STUFE4B_TIMEOUT", str(LLM_ROOM_LOOKUP_TIMEOUT)
))
"""HTTP-Timeout der Stufe-4b-Probe. Default identisch zu
LLM_ROOM_LOOKUP_TIMEOUT (15s), NICHT höher (K1)."""
# ── Index-Pfad (identisch zu room_index.py `_DEFAULT_INDEX_DIR`) ─────────────
# Bewusst hier neu abgeleitet statt `import room_index` — room_index importiert
# numpy auf Modulebene, was bei kaputtem venv selbst fehlschlägt (genau das,
@@ -69,7 +91,10 @@ class ComponentCheckResult:
"""Ergebnis der 6-stufigen Self-Check-Diagnose.
Stufen 1-3 sind Fehler-Stufen, Stufen 4-5 Warmup-Stufen, Stufe 6
(``ready``) ist abgeleitet.
(``ready``) ist abgeleitet. Stufe 4b (F100) ist eine zusätzliche
Warmup-Stufe: sie misst einen externen Endpoint, der temporär
unerreichbar sein kann (K1-Rollenverteilung) — bei 4b-Fail also
Warmup-Meldung, nicht Repair-Meldung.
"""
faiss_importable: bool # Stufe 1
@@ -78,6 +103,8 @@ class ComponentCheckResult:
llm_model_loaded: bool # Stufe 4
embedding_ladbar: bool # Stufe 5
ready: bool # Stufe 6 (abgeleitet)
llm_room_e2e_ok: bool = False # Stufe 4b (F100)
llm_room_e2e_latency_ms: float = 0.0 # Stufe 4b (F100)
@property
def has_error(self) -> bool:
@@ -88,9 +115,9 @@ class ComponentCheckResult:
@property
def needs_warmup(self) -> bool:
"""True wenn keine Fehler-Stufe, aber eine Warmup-Stufe (4-5) fehlt."""
"""True wenn keine Fehler-Stufe, aber eine Warmup-Stufe (4-5, 4b) fehlt."""
return (not self.has_error) and not (
self.llm_model_loaded and self.embedding_ladbar
self.llm_model_loaded and self.embedding_ladbar and self.llm_room_e2e_ok
)
@@ -196,6 +223,51 @@ def _probe_embedding(base_url: str, model: str, timeout: float) -> bool:
return False
def _probe_llm_room_e2e(
base_url: str,
model: str,
timeout: float,
) -> Tuple[bool, float, str]:
"""Stufe 4b (F100): Router-E2E-Probe — POST /api/generate mit Mini-Prompt.
Smoke-Test (K1): prüft, dass Modell + Endpoint überhaupt antworten.
Antwort-Validierung: enthält "STAY" (case-insensitive trim) UND Latenz
≤ timeout. Bei jedem Fehler (HTTP, Timeout, Parse): ok=False.
Args:
base_url: Ollama-Basis-URL (ohne trailing slash).
model: LLM-Modellname (aus LLM_CONFIG).
timeout: HTTP-Timeout in Sekunden.
Returns:
(ok: bool, latency_ms: float, detail: str)
"""
url = f"{base_url}/api/generate"
payload = json.dumps({
"model": model,
"prompt": STUFE4B_PROBE_PROMPT,
"stream": False,
}).encode("utf-8")
headers = {"Content-Type": "application/json"}
t0 = time.monotonic()
try:
req = urllib.request.Request(url, data=payload, headers=headers, method="POST")
with urllib.request.urlopen(req, timeout=timeout) as resp:
data = json.loads(resp.read().decode("utf-8"))
latency_ms = (time.monotonic() - t0) * 1000.0
except (urllib.error.HTTPError, urllib.error.URLError) as e:
return False, 0.0, f"HTTP/URL-Fehler: {e}"
except (json.JSONDecodeError, OSError, Exception) as e:
return False, 0.0, f"Fehler: {e}"
response = (data.get("response") or "").strip()
if "STAY" not in response.upper():
return False, latency_ms, f"unerwartete Antwort: {response[:60]!r}"
if latency_ms > timeout * 1000.0:
return False, latency_ms, f"Latenz {latency_ms:.0f}ms > {timeout*1000:.0f}ms"
return True, latency_ms, ""
# ── check_components(): die gemeinsame Diagnose-Funktion ────────────────────
@@ -228,7 +300,20 @@ def check_components() -> ComponentCheckResult:
llm_loaded = False
embedding_ok = False
ready = faiss_ok and index_ok and ollama_ok and llm_loaded and embedding_ok # Stufe 6
# Stufe 4b (F100): Router-E2E-Probe — nur wenn Ollama erreichbar UND
# Modell geladen (sonst nicht ausführbar → ok=False, latency_ms=0).
if ollama_ok and llm_loaded:
e2e_ok, e2e_latency_ms, _e2e_detail = _probe_llm_room_e2e(
base_url, llm_model, STUFE4B_PROBE_TIMEOUT_S
)
else:
e2e_ok = False
e2e_latency_ms = 0.0
ready = (
faiss_ok and index_ok and ollama_ok and llm_loaded and embedding_ok
and e2e_ok # Stufe 6 + 4b
)
return ComponentCheckResult(
faiss_importable=faiss_ok,
@@ -237,6 +322,8 @@ def check_components() -> ComponentCheckResult:
llm_model_loaded=llm_loaded,
embedding_ladbar=embedding_ok,
ready=ready,
llm_room_e2e_ok=e2e_ok,
llm_room_e2e_latency_ms=e2e_latency_ms,
)
+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()
+121
View File
@@ -0,0 +1,121 @@
"""
F100 — Persistentes Cooldown-Flag für den Runtime-Watchdog-Alert (K3).
Verhindert Re-Alert-Spam: der Watchdog darf höchstens einmal pro
``LLM_ROOM_WATCHDOG_ALERT_COOLDOWN_S`` (Default 24h) einen Alert loggen.
Das Flag wird in ``~/.hermes/hermes-agent/data/routing_watchdog_alert.json``
persistiert (``last_alert_ts``) und überlebt damit Gateway-Restarts.
P-088-Lehre: Der Alert selbst ist ein ``logger.error(...)`` — KEIN RC-Post,
KEIN User-Spam. Dieses Modul stellt nur die Cooldown-Buchhaltung bereit.
Persistenz-Pattern: atomar via tmp+rename (P-101), best-effort (nie fatal).
"""
from __future__ import annotations
import json
import logging
import os
import time
from typing import Callable, Optional
logger = logging.getLogger(__name__)
# Persistenz-Pfad (analog ARCHIVAR_STATE_PATH / ADAPTIVE_TIMEOUT_STATE_PATH).
WATCHDOG_ALERT_STATE_PATH: str = os.path.expanduser(
os.getenv(
"ARCHIVAR_WATCHDOG_ALERT_STATE_PATH",
"~/.hermes/hermes-agent/data/routing_watchdog_alert.json",
)
)
class WatchdogAlertCooldown:
"""Persistentes Cooldown-Flag für den Runtime-Watchdog-Alert.
Thread-sicher über ein internes Lock. ``is_in_cooldown()`` prüft, ob seit
dem letzten Alert weniger als ``cooldown_s`` Sekunden vergangen sind.
``mark_alerted()`` setzt ``last_alert_ts`` auf jetzt und persistiert.
"""
def __init__(
self,
cooldown_s: float = 86400.0,
state_path: Optional[str] = WATCHDOG_ALERT_STATE_PATH,
clock: Callable[[], float] = time.time,
) -> None:
import threading
self._cooldown_s = cooldown_s
self._state_path = state_path
self._clock = clock
self._lock = threading.Lock()
self._last_alert_ts: Optional[float] = None
if self._state_path:
self._load()
def is_in_cooldown(self, now: Optional[float] = None) -> bool:
"""True wenn der letzte Alert weniger als ``cooldown_s`` her ist."""
ref = self._clock() if now is None else now
with self._lock:
if self._last_alert_ts is None:
return False
return (ref - self._last_alert_ts) < self._cooldown_s
def mark_alerted(self, now: Optional[float] = None) -> None:
"""Setze ``last_alert_ts`` auf jetzt und persistiere (best-effort)."""
ref = self._clock() if now is None else now
with self._lock:
self._last_alert_ts = ref
self._save_locked()
@property
def last_alert_ts(self) -> Optional[float]:
with self._lock:
return self._last_alert_ts
# ── Persistenz (P-101: atomar via tmp+rename) ────────────────────────
def _save_locked(self) -> None:
if not self._state_path:
return
try:
data = {"last_alert_ts": self._last_alert_ts}
directory = os.path.dirname(self._state_path)
os.makedirs(directory, exist_ok=True)
tmp_path = self._state_path + ".tmp"
with open(tmp_path, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False)
os.replace(tmp_path, self._state_path)
except Exception as e: # Persistenz ist best-effort, nie fatal.
logger.warning("F100: Watchdog-Alert-Persistenz fehlgeschlagen: %s", e)
def _load(self) -> None:
if not self._state_path or not os.path.exists(self._state_path):
return
try:
with open(self._state_path, "r", encoding="utf-8") as f:
data = json.load(f)
ts = data.get("last_alert_ts")
self._last_alert_ts = float(ts) if ts is not None else None
logger.info(
"F100: Watchdog-Alert-Cooldown geladen (last_alert_ts=%s)",
self._last_alert_ts,
)
except Exception as e:
logger.warning("F100: Watchdog-Alert-State laden fehlgeschlagen: %s", e)
# Modul-Level-Singleton — wird von adapter.py importiert.
# Cooldown aus config.py (env-gesteuert), damit die Konstante die einzige
# Wahrheitsquelle ist (kein hartcodierter 86400-Default an zwei Stellen).
def _default_cooldown_s() -> float:
try:
from .config import LLM_ROOM_WATCHDOG_ALERT_COOLDOWN_S
return float(LLM_ROOM_WATCHDOG_ALERT_COOLDOWN_S)
except Exception:
return 86400.0
watchdog_alert_cooldown = WatchdogAlertCooldown(cooldown_s=_default_cooldown_s())