feat(F071,F068,F070): Welle 2 — Refactor-Audit, Stabilitaets-Monitor, Contract-Test-Framework @implements: [F-071] [F-068] [F-070]
This commit is contained in:
@@ -0,0 +1,314 @@
|
||||
"""F068 — 7-Tage-Stabilitätstest mit erweiterter Telemetrie.
|
||||
|
||||
Sammelt über 7 Tage Telemetrie-Daten und erstellt danach (oder manuell)
|
||||
einen Stabilitaets-Bericht.
|
||||
|
||||
Gesammelte Metriken:
|
||||
- Uptime (Startzeitpunkt des Tests + Laufzeit in Sekunden/Tagen)
|
||||
- Message-Count (Anzahl verarbeiteter eingehender Nachrichten)
|
||||
- Error-Count (Anzahl aufgetretener Fehler/Exceptions im Plugin)
|
||||
- Restart-Count (Anzahl Gateway-/Adapter-Neustarts während des Tests)
|
||||
|
||||
Start: inline Command `::stability-test`
|
||||
Bericht: automatisch nach 7 Tagen ODER manuell via `::stability-report`
|
||||
|
||||
Persistenz: State wird in einer JSON-Datei gehalten (maschinen-spezifisch,
|
||||
NICHT committen — siehe .gitignore / data-Pfad).
|
||||
|
||||
@implements: [F-068]
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
from enum import Enum
|
||||
from pathlib import Path
|
||||
from typing import Dict, Optional
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# ── Konfiguration ──────────────────────────────────────────────────────────
|
||||
|
||||
# Dauer des Testfensters (Default: 7 Tage). In Sekunden.
|
||||
STABILITY_WINDOW_S: float = float(os.getenv("ARCHIVAR_STABILITY_WINDOW_S", str(7 * 24 * 3600)))
|
||||
|
||||
# Persistenz-Pfad (maschinen-spezifisch — analog archivar-state.json).
|
||||
STABILITY_STATE_PATH: str = os.path.expanduser(
|
||||
os.getenv("ARCHIVAR_STABILITY_STATE_PATH", "~/.hermes/hermes-agent/data/stability-monitor.json")
|
||||
)
|
||||
|
||||
# Feature-Flag: Telemetrie-Sampling global ein/aus.
|
||||
STABILITY_ENABLED: bool = os.getenv("ARCHIVAR_STABILITY_ENABLED", "true").strip().lower() not in ("false", "0", "no", "off")
|
||||
|
||||
|
||||
class StabilityStatus(Enum):
|
||||
"""Zustand des Stabilitätstests."""
|
||||
|
||||
INACTIVE = "inactive" # kein Test gestartet
|
||||
RUNNING = "running" # Test läuft (innerhalb des Fensters)
|
||||
COMPLETED = "completed" # Testfenster abgelaufen, Bericht fällig
|
||||
REPORTED = "reported" # Bericht erstellt
|
||||
|
||||
|
||||
class StabilityMonitor:
|
||||
"""Überwacht die Plugin-Stabilität über 7 Tage (oder konfigurierbares Fenster).
|
||||
|
||||
Thread-sicher via GIL (single-writer Kontext — wie routing_counter).
|
||||
Persistiert den State über Neustarts hinweg in einer JSON-Datei.
|
||||
"""
|
||||
|
||||
def __init__(self, state_path: Optional[str] = None) -> None:
|
||||
self._state_path = state_path or STABILITY_STATE_PATH
|
||||
self._status: StabilityStatus = StabilityStatus.INACTIVE
|
||||
self._started_at: Optional[float] = None
|
||||
self._restarts_at_start: int = 0
|
||||
# Zähler
|
||||
self._message_count: int = 0
|
||||
self._error_count: int = 0
|
||||
self._restart_count: int = 0
|
||||
# Zusätzliche Telemetrie (erweitert): letzte Activity-Timestamps
|
||||
self._last_message_ts: Optional[float] = None
|
||||
self._last_error_ts: Optional[float] = None
|
||||
# Anzahl Fehler-Meldungen, die nach dem Bericht aufgetreten sind
|
||||
self._errors_since_report: int = 0
|
||||
self._loaded = False
|
||||
|
||||
# ── State-Persistenz ────────────────────────────────────────────────
|
||||
|
||||
def _to_dict(self) -> Dict[str, object]:
|
||||
return {
|
||||
"status": self._status.value,
|
||||
"started_at": self._started_at,
|
||||
"restarts_at_start": self._restarts_at_start,
|
||||
"message_count": self._message_count,
|
||||
"error_count": self._error_count,
|
||||
"restart_count": self._restart_count,
|
||||
"last_message_ts": self._last_message_ts,
|
||||
"last_error_ts": self._last_error_ts,
|
||||
"errors_since_report": self._errors_since_report,
|
||||
}
|
||||
|
||||
def _from_dict(self, data: Dict[str, object]) -> None:
|
||||
try:
|
||||
self._status = StabilityStatus(data.get("status", "inactive"))
|
||||
except ValueError:
|
||||
self._status = StabilityStatus.INACTIVE
|
||||
self._started_at = data.get("started_at")
|
||||
self._restarts_at_start = int(data.get("restarts_at_start", 0))
|
||||
self._message_count = int(data.get("message_count", 0))
|
||||
self._error_count = int(data.get("error_count", 0))
|
||||
self._restart_count = int(data.get("restart_count", 0))
|
||||
self._last_message_ts = data.get("last_message_ts")
|
||||
self._last_error_ts = data.get("last_error_ts")
|
||||
self._errors_since_report = int(data.get("errors_since_report", 0))
|
||||
|
||||
def load(self) -> bool:
|
||||
"""Lade den persistierten Test-State. True bei Erfolg (oder neu)."""
|
||||
try:
|
||||
path = Path(self._state_path)
|
||||
if not path.exists():
|
||||
self._loaded = True
|
||||
return True
|
||||
with path.open("r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
self._from_dict(data)
|
||||
self._loaded = True
|
||||
return True
|
||||
except (json.JSONDecodeError, OSError, TypeError) as e:
|
||||
logger.warning("[f068] Stabilitäts-State nicht ladbar (%s): %s", self._state_path, e)
|
||||
self._loaded = False
|
||||
return False
|
||||
|
||||
def save(self) -> bool:
|
||||
"""Schreibe den State zurück in die JSON-Datei."""
|
||||
try:
|
||||
path = Path(self._state_path)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
tmp = path.with_suffix(path.suffix + ".tmp")
|
||||
with tmp.open("w", encoding="utf-8") as f:
|
||||
json.dump(self._to_dict(), f, indent=2, ensure_ascii=False)
|
||||
tmp.replace(path)
|
||||
return True
|
||||
except OSError as e:
|
||||
logger.warning("[f068] Stabilitäts-State nicht schreibbar: %s", e)
|
||||
return False
|
||||
|
||||
# ── Test-Lifecycle ──────────────────────────────────────────────────
|
||||
|
||||
def start(self, restart_count_hint: int = 0) -> str:
|
||||
"""Startet (oder setzt fort) den Stabilitätstest.
|
||||
|
||||
Bei Erst-Start wird der Countdown auf STABILITY_WINDOW_S gesetzt.
|
||||
Bei laufendem Test wird das Fenster NICHT neu gestartet (die bereits
|
||||
gesammelten Daten bleiben relevant).
|
||||
"""
|
||||
if self._status == StabilityStatus.RUNNING and self._started_at is not None:
|
||||
remaining = self.seconds_remaining()
|
||||
return (
|
||||
f"Stabilitätstest läuft bereits (noch {self._format_duration(remaining)}). "
|
||||
f"Gesammelt: {self._message_count} Messages, "
|
||||
f"{self._error_count} Fehler, {self._restart_count} Restarts."
|
||||
)
|
||||
self._status = StabilityStatus.RUNNING
|
||||
self._started_at = time.time()
|
||||
self._restarts_at_start = restart_count_hint
|
||||
# Restart-Count relativ zum Teststart zurücksetzen
|
||||
self._restart_count = 0
|
||||
self._message_count = 0
|
||||
self._error_count = 0
|
||||
self._errors_since_report = 0
|
||||
self.save()
|
||||
return (
|
||||
f"🟢 Stabilitätstest gestartet. Fenster: "
|
||||
f"{self._format_duration(STABILITY_WINDOW_S)}. "
|
||||
f"Bericht: automatisch nach Ablauf oder manuell via ::stability-report."
|
||||
)
|
||||
|
||||
def seconds_remaining(self) -> float:
|
||||
"""Verbleibende Sekunden bis zum Bericht (0 wenn abgelaufen)."""
|
||||
if self._started_at is None:
|
||||
return 0.0
|
||||
elapsed = time.time() - self._started_at
|
||||
remaining = STABILITY_WINDOW_S - elapsed
|
||||
return max(remaining, 0.0)
|
||||
|
||||
def is_completed(self) -> bool:
|
||||
"""True wenn der Test lief und das Fenster abgelaufen ist."""
|
||||
return (
|
||||
self._status == StabilityStatus.RUNNING
|
||||
and self._started_at is not None
|
||||
and time.time() - self._started_at >= STABILITY_WINDOW_S
|
||||
)
|
||||
|
||||
# ── Telemetrie-Sampling ──────────────────────────────────────────────
|
||||
|
||||
def record_message(self) -> None:
|
||||
"""Zählt eine verarbeitete eingehende Nachricht (während laufendem Test)."""
|
||||
if not STABILITY_ENABLED or self._status != StabilityStatus.RUNNING:
|
||||
return
|
||||
self._message_count += 1
|
||||
self._last_message_ts = time.time()
|
||||
|
||||
def record_error(self) -> None:
|
||||
"""Zählt einen Plugin-Fehler (während laufendem Test)."""
|
||||
if not STABILITY_ENABLED or self._status != StabilityStatus.RUNNING:
|
||||
return
|
||||
self._error_count += 1
|
||||
self._last_error_ts = time.time()
|
||||
|
||||
def record_restart(self) -> None:
|
||||
"""Zählt einen Neustart (während laufendem Test)."""
|
||||
if not STABILITY_ENABLED or self._status != StabilityStatus.RUNNING:
|
||||
return
|
||||
self._restart_count += 1
|
||||
self.save()
|
||||
|
||||
# ── Bericht ──────────────────────────────────────────────────────────
|
||||
|
||||
@staticmethod
|
||||
def _format_duration(seconds: float) -> str:
|
||||
seconds = max(0.0, float(seconds))
|
||||
days = int(seconds // 86400)
|
||||
hours = int((seconds % 86400) // 3600)
|
||||
mins = int((seconds % 3600) // 60)
|
||||
secs = int(seconds % 60)
|
||||
return f"{days}d {hours:02d}h {mins:02d}m {secs:02d}s"
|
||||
|
||||
@staticmethod
|
||||
def _format_uptime(started_at: float) -> str:
|
||||
return StabilityMonitor._format_duration(time.time() - started_at)
|
||||
|
||||
def build_report(self) -> str:
|
||||
"""Baut den Stabilitaets-Bericht als Mensch-lesbaren Markdown-String."""
|
||||
uptime = self._format_uptime(self._started_at) if self._started_at else "—"
|
||||
if self._started_at:
|
||||
start_iso = datetime.fromtimestamp(self._started_at, tz=timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC")
|
||||
else:
|
||||
start_iso = "—"
|
||||
ratio_success = 0.0
|
||||
total = self._message_count + self._error_count
|
||||
if total:
|
||||
ratio_success = self._message_count / total
|
||||
stability_pct = 100.0 * ratio_success
|
||||
|
||||
lines = [
|
||||
"## 📈 Stabilitätsbericht (F068)",
|
||||
"",
|
||||
f"**Status:** {self._status.value}",
|
||||
f"**Teststart:** {start_iso}",
|
||||
f"**Uptime (im Testfenster):** {uptime}",
|
||||
f"**Fenster:** {self._format_duration(STABILITY_WINDOW_S)}",
|
||||
f"**Verbleibend:** {self._format_duration(self.seconds_remaining()) if self._status == StabilityStatus.RUNNING else '—'}",
|
||||
"",
|
||||
"**Telemetrie:**",
|
||||
f"- Nachrichten verarbeitet: {self._message_count}",
|
||||
f"- Fehler: {self._error_count}",
|
||||
f"- Neustarts: {self._restart_count}",
|
||||
f"- Stabilität: {stability_pct:.1f}%",
|
||||
"",
|
||||
"**Bewertung:**",
|
||||
]
|
||||
if self._status == StabilityStatus.INACTIVE:
|
||||
lines.append("Kein Test aktiv. Start mit `::stability-test`.")
|
||||
elif self._status in (StabilityStatus.COMPLETED, StabilityStatus.REPORTED) or self.is_completed():
|
||||
# is_completed() = Fenster abgelaufen, auch wenn Status noch RUNNING
|
||||
if self._error_count == 0 and self._restart_count == 0:
|
||||
lines.append("🟢 Stabil über das gesamte Testfenster — keine Fehler, keine Neustarts.")
|
||||
elif self._error_count <= 3 and self._restart_count == 0:
|
||||
lines.append("🟡 Stabil mit wenigen Fehlern (keine Neustarts). Fehler-Pfade prüfen.")
|
||||
else:
|
||||
lines.append("🔴 Instabil — hohe Fehler- oder Neustart-Rate. Sofort analysieren (P-Klasse).")
|
||||
else:
|
||||
lines.append(f"Noch {self._format_duration(self.seconds_remaining())} bis zum Bericht.")
|
||||
return "\n".join(lines)
|
||||
|
||||
def generate_report_snapshot(self) -> str:
|
||||
"""Erzeugt den Bericht UND markiert den Test als REPORTED (endgültig).
|
||||
|
||||
Der Wechsel auf REPORTED erfolgt nur, wenn das Testfenster abgelaufen
|
||||
ist — ein manueller Bericht während des Laufs bleibt RUNNING.
|
||||
"""
|
||||
report = self.build_report()
|
||||
if self._status == StabilityStatus.RUNNING and self.is_completed():
|
||||
self._status = StabilityStatus.REPORTED
|
||||
self.save()
|
||||
return report
|
||||
|
||||
def reset(self) -> None:
|
||||
"""Setzt den Test vollständig zurück (für ::stability-test Neu-Start)."""
|
||||
self._status = StabilityStatus.INACTIVE
|
||||
self._started_at = None
|
||||
self._restarts_at_start = 0
|
||||
self._message_count = 0
|
||||
self._error_count = 0
|
||||
self._restart_count = 0
|
||||
self._errors_since_report = 0
|
||||
self._last_message_ts = None
|
||||
self._last_error_ts = None
|
||||
self.save()
|
||||
|
||||
# ── Abfragen für Status-Anzeige ─────────────────────────────────────
|
||||
|
||||
@property
|
||||
def status(self) -> StabilityStatus:
|
||||
return self._status
|
||||
|
||||
@property
|
||||
def message_count(self) -> int:
|
||||
return self._message_count
|
||||
|
||||
@property
|
||||
def error_count(self) -> int:
|
||||
return self._error_count
|
||||
|
||||
@property
|
||||
def restart_count(self) -> int:
|
||||
return self._restart_count
|
||||
|
||||
|
||||
# Modul-Level-Singleton — analog routing_telemetry/routing_counter.
|
||||
stability_monitor = StabilityMonitor()
|
||||
Reference in New Issue
Block a user