123 lines
4.5 KiB
Python
123 lines
4.5 KiB
Python
"""
|
|
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).
|
|
"""
|
|
# @implements: [F-100] — Watchdog-Alert Cooldown
|
|
|
|
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())
|