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,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())
|
||||
Reference in New Issue
Block a user