""" 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() """ # @implements: [F-092] — Routing-Counter 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()