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:
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user