9798a3e8a0
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.
126 lines
4.6 KiB
Python
126 lines
4.6 KiB
Python
"""
|
|
Routing-Counter für Archivar v7 — empirische Daten für V8-Refactoring.
|
|
|
|
Zählt JEDE Routing-Entscheidung und JEDEN Bypass.
|
|
In-Memory (nicht persistent). Nach Neustart beginnt Zählung neu.
|
|
|
|
Usage::
|
|
|
|
from archivar.routing_counter import routing_counter
|
|
routing_counter.increment('dm_routing_skipped')
|
|
routing_counter.log_counts()
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
import threading
|
|
import time
|
|
from typing import Dict, List, Optional, Tuple
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
class RoutingCounter:
|
|
"""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)."""
|
|
with self._lock:
|
|
self._counts[reason] = self._counts.get(reason, 0) + 1
|
|
|
|
def get_counts(self) -> Dict[str, int]:
|
|
"""Gibt eine Kopie aller Zählerstände zurück."""
|
|
with self._lock:
|
|
return dict(self._counts)
|
|
|
|
def log_counts(self) -> None:
|
|
"""Logge alle Zählerstände auf INFO-Level."""
|
|
counts = self.get_counts()
|
|
total = sum(counts.values())
|
|
logger.info(
|
|
"Routing counter (total=%d): %s",
|
|
total,
|
|
", ".join(f"{k}={v}" for k, v in sorted(counts.items())),
|
|
)
|
|
|
|
def reset(self) -> None:
|
|
"""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
|
|
routing_counter = RoutingCounter()
|