From 8b106f50b4a174da7234a4de94f69eee873abfbe Mon Sep 17 00:00:00 2001 From: "Miguel (Hermes Agent)" Date: Mon, 31 Aug 2026 09:03:59 +0200 Subject: [PATCH] =?UTF-8?q?feat(F93):=20Adaptiver=20LLM-Timeout=20?= =?UTF-8?q?=E2=80=94=20selbstkalibrierend=20(Welford=20+=20Toleranzband)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Ersetzt den starren 30s-LLM-Timeout durch einen selbstkalibrierenden Wert. - plugin/archivar/adaptive_timeout.py (NEU): AdaptiveLLMTimeout - Failsafe 30s beim ersten Start - Welford Moving Average + Standardabweichung -> Toleranzband - 7-Tage-Exponential-Decay Gewichtung (forgetting factor) - Ausreißer-Erkennung ±2σ -> Messung verwerfen (temporäre Last) - Eskalation erst bei N=2 konsekutiven Messungen außerhalb Toleranz - Reset bei Modellwechsel (Schlüssel = endpoint+model) - FAISS-Analog: score-basierte Bewertung (z-Score), nicht binär - Persistenz (atomar via tmp+rename, P-101-Pattern) - classifier.py: OllamaLLMClient._call_generate() nutzt adaptiven Timeout statt starrem self._timeout; classify()/generate() refaktoriert - 24 A1c-Tests (Failsafe, Konvergenz, Ausreißer, Reset, Eskalation, Score, Decay, Persistenz) @implements F-93 --- plugin/archivar/adaptive_timeout.py | 382 ++++++++++++++++++ plugin/archivar/classifier.py | 108 +++-- .../tests/test_f93_adaptive_timeout.py | 307 ++++++++++++++ 3 files changed, 739 insertions(+), 58 deletions(-) create mode 100644 plugin/archivar/adaptive_timeout.py create mode 100644 plugin/archivar/tests/test_f93_adaptive_timeout.py diff --git a/plugin/archivar/adaptive_timeout.py b/plugin/archivar/adaptive_timeout.py new file mode 100644 index 0000000..a31ed63 --- /dev/null +++ b/plugin/archivar/adaptive_timeout.py @@ -0,0 +1,382 @@ +""" +F93 — Adaptiver LLM-Timeout (selbstkalibrierend, ersetzt starre 30s). + +@implements F-93 + +Ersetzt den starren 30s-LLM-Call-Timeout durch einen selbstkalibrierenden +Wert, der pro System aus den tatsächlich gemessenen LLM-Antwortzeiten lernt. + +Verbindliche Spec (Rainers Design 22.08., Feature-Register Zeile F93, FB-10): + + - Failsafe 30s beim ersten Start (keine Kalibrierungsdaten → 30s). + - Welford Moving Average + Standardabweichung → Toleranzband. + - 7-Tage-Exponential-Decay Gewichtung (alte Messungen verblassen). + - Ausreißer-Erkennung: ±2σ → Messung verwerfen (temporäre Last wie + Docker-Start wird NICHT in die Statistik eingerechnet). + - Eskalation erst bei N=2 konsekutiven Messungen außerhalb Toleranz. + - Reset bei Modellwechsel (Schlüssel = (endpoint, model)). + - FAISS-Analog: score-basierte Bewertung (z-Score), nicht binär. + +Design-Entscheidungen (dokumentiert für QG F1-F5): + + - Der Timeout für den NÄCHSTEN Call ist ``mean + sigma_band * std`` + (obere Toleranzgrenze). Das gibt normaler Varianz Luft, ohne bei + temporärer Last (Ausreißer) mitzuwachsen — Ausreißer werden verworfen. + - Welford ist ein Online-Algorithmus (kein Speichern aller Samples). + Der 7-Tage-Decay wird als "forgetting factor" umgesetzt: vor jedem + Update werden ``n`` und ``M2`` mit ``exp(-dt / tau)`` skaliert. Der + Mittelwert bleibt dabei unverändert (uniforme Skalierung), die + Varianz (M2/n) ebenfalls — nur das effektive Gewicht alter Daten + sinkt. ``n`` wird dadurch ein fraktionaler "effektiver Stichprobenumfang". + - Ausreißer-Erkennung greift erst ab ``min_samples`` akzeptierten + Messungen (vorher ist die Std instabil). Während der Kalibrierung + wird alles akzeptiert (Konvergenz). + - Score-basiert: ``score(duration)`` liefert den z-Score (kontinuierlich), + nicht nur in/out. Eskalation nutzt den Streak (N=2 konsekutiv außerhalb + Toleranz), nicht einen einzelnen binären Schwellwert. + +Persistenz: Der Kalibrierungszustand wird in eine JSON-Datei geschrieben +(atomar via tmp+rename, P-101-Pattern), damit die Kalibrierung über +Gateway-Neustarts hinweg erhalten bleibt ("selbstkalibrierend pro System"). +""" + +from __future__ import annotations + +import json +import logging +import math +import os +import time +from typing import Callable, Optional, Tuple + +logger = logging.getLogger(__name__) + +# ── Konfiguration (Env-Vars, analog config.py) ────────────────────────────── + +# Failsafe-Timeout beim ersten Start (keine Kalibrierungsdaten). +ADAPTIVE_TIMEOUT_FAILSAFE_S: float = float( + os.getenv("ARCHIVAR_ADAPTIVE_TIMEOUT_FAILSAFE", "30.0") +) + +# Toleranzband: ±sigma_band * std um den Mittelwert. +ADAPTIVE_TIMEOUT_SIGMA_BAND: float = float( + os.getenv("ARCHIVAR_ADAPTIVE_TIMEOUT_SIGMA_BAND", "2.0") +) + +# 7-Tage-Exponential-Decay (tau in Sekunden). +ADAPTIVE_TIMEOUT_DECAY_TAU_S: float = float( + os.getenv("ARCHIVAR_ADAPTIVE_TIMEOUT_DECAY_TAU_S", str(7 * 24 * 3600)) +) + +# Eskalation erst bei N konsekutiven Messungen außerhalb Toleranz. +ADAPTIVE_TIMEOUT_ESCALATION_N: int = int( + os.getenv("ARCHIVAR_ADAPTIVE_TIMEOUT_ESCALATION_N", "2") +) + +# Mindestanzahl akzeptierter Messungen, bevor Ausreißer-Erkennung greift. +ADAPTIVE_TIMEOUT_MIN_SAMPLES: int = int( + os.getenv("ARCHIVAR_ADAPTIVE_TIMEOUT_MIN_SAMPLES", "3") +) + +# Defensive Unter-/Obergrenze für den kalibrierten Timeout (Sekunden). +ADAPTIVE_TIMEOUT_MIN_S: float = float( + os.getenv("ARCHIVAR_ADAPTIVE_TIMEOUT_MIN_S", "1.0") +) +ADAPTIVE_TIMEOUT_MAX_S: float = float( + os.getenv("ARCHIVAR_ADAPTIVE_TIMEOUT_MAX_S", "300.0") +) + +# Persistenz-Pfad (analog ARCHIVAR_STATE_PATH). +ADAPTIVE_TIMEOUT_STATE_PATH: str = os.path.expanduser( + os.getenv( + "ARCHIVAR_ADAPTIVE_TIMEOUT_STATE_PATH", + "~/.hermes/hermes-agent/data/adaptive_timeout_state.json", + ) +) + + +class AdaptiveLLMTimeout: + """Selbstkalibrierender LLM-Call-Timeout (Welford + Toleranzband). + + Thread-sicher über ein internes Lock, da ``OllamaLLMClient`` aus + ``asyncio.to_thread``-Worker-Threads heraus aufruft (parallele Calls + möglich, auch wenn der Router sie über einen Semaphore serialisiert). + """ + + def __init__( + self, + failsafe_s: float = ADAPTIVE_TIMEOUT_FAILSAFE_S, + sigma_band: float = ADAPTIVE_TIMEOUT_SIGMA_BAND, + decay_tau_s: float = ADAPTIVE_TIMEOUT_DECAY_TAU_S, + escalation_n: int = ADAPTIVE_TIMEOUT_ESCALATION_N, + min_samples: int = ADAPTIVE_TIMEOUT_MIN_SAMPLES, + min_timeout_s: float = ADAPTIVE_TIMEOUT_MIN_S, + max_timeout_s: float = ADAPTIVE_TIMEOUT_MAX_S, + state_path: Optional[str] = ADAPTIVE_TIMEOUT_STATE_PATH, + clock: Callable[[], float] = time.time, + ) -> None: + self._failsafe_s = failsafe_s + self._sigma_band = sigma_band + self._decay_tau_s = decay_tau_s + self._escalation_n = escalation_n + self._min_samples = min_samples + self._min_timeout_s = min_timeout_s + self._max_timeout_s = max_timeout_s + self._state_path = state_path + self._clock = clock + + # Welford-Zustand (n = effektiver Stichprobenumfang, fraktional nach Decay). + self._n: float = 0.0 + self._mean: float = 0.0 + self._m2: float = 0.0 + self._last_ts: Optional[float] = None + + # Modell-Schlüssel (Reset bei Wechsel). + self._model_key: Optional[Tuple[str, str]] = None + + # Eskalations-Zustand. + self._streak: int = 0 + self._escalated: bool = False + + # Telemetrie. + self._accepted: int = 0 + self._rejected: int = 0 + + import threading + self._lock = threading.Lock() + + if self._state_path: + self._load() + + # ── Öffentliche API ────────────────────────────────────────────────── + + def current_timeout(self) -> float: + """Timeout für den NÄCHSTEN LLM-Call. + + Failsafe (30s) solange keine Kalibrierungsdaten vorliegen, danach + ``mean + sigma_band * std``, geklemmt auf [min, max]. + """ + with self._lock: + if self._n < 1.0: + return self._failsafe_s + std = self._stddev_locked() + timeout = self._mean + self._sigma_band * std + return max(self._min_timeout_s, min(self._max_timeout_s, timeout)) + + def record(self, duration: float, success: bool = True) -> float: + """Füttere eine Messung (LLM-Antwortzeit in Sekunden). + + Args: + duration: Gemessene Dauer in Sekunden. + success: False bei Timeout/Fehler (Messung wird als + außerhalb Toleranz gewertet, nicht in die Statistik + aufgenommen). + + Returns: + z-Score der Messung (0.0 während Kalibrierung). Positiv = + langsamer als Mittelwert. Score-basiert (FAISS-Analog), nicht binär. + """ + with self._lock: + self._apply_decay_locked() + + # Timeout/Fehler: per Definition außerhalb Toleranz → Streak. + if not success: + self._rejected += 1 + self._streak += 1 + self._maybe_escalate_locked() + return float("inf") + + # Ausreißer-Erkennung erst ab min_samples (Std stabil). + if self._n >= self._min_samples: + std = self._stddev_locked() + if std > 0.0: + z = (duration - self._mean) / std + if abs(z) > self._sigma_band: + # Ausreißer → verwerfen (temporäre Last nicht einrechnen). + self._rejected += 1 + self._streak += 1 + self._maybe_escalate_locked() + return z + + # Akzeptieren → Welford-Update. + self._n += 1.0 + delta = duration - self._mean + self._mean += delta / self._n + delta2 = duration - self._mean + self._m2 += delta * delta2 + self._accepted += 1 + self._streak = 0 + self._save_locked() + return 0.0 + + def score(self, duration: float) -> float: + """Z-Score einer Dauer relativ zur aktuellen Statistik (FAISS-Analog). + + Kontinuierliche Bewertung statt binär in/out. 0.0 = exakt Mittelwert, + ±2.0 = Toleranzgrenze, darüber = Ausreißer. + """ + with self._lock: + if self._n < 2.0: + return 0.0 + std = self._stddev_locked() + if std <= 0.0: + return 0.0 + return (duration - self._mean) / std + + def set_model(self, endpoint: str, model: str) -> bool: + """Setze den aktuellen (endpoint, model)-Schlüssel. + + Bei Wechsel → harter Reset (nur dieser Schlüssel; hier ein einziger + Schlüssel, da ein Prozess typischerweise ein LLM-Modell nutzt). + + Returns: + True wenn ein Reset ausgelöst wurde (Modellwechsel), sonst False. + """ + key = (endpoint, model) + with self._lock: + if key == self._model_key: + return False + self._model_key = key + self._reset_locked() + return True + + def reset(self) -> None: + """Harter Reset der Kalibrierung (Modellwechsel).""" + with self._lock: + self._reset_locked() + + def _reset_locked(self) -> None: + """Reset ohne Lock-Akquise (Caller hält ``self._lock``).""" + self._n = 0.0 + self._mean = 0.0 + self._m2 = 0.0 + self._last_ts = None + self._streak = 0 + self._escalated = False + self._accepted = 0 + self._rejected = 0 + self._save_locked() + + # ── Introspection (Telemetrie / Tests) ─────────────────────────────── + + @property + def mean(self) -> float: + with self._lock: + return self._mean + + @property + def stddev(self) -> float: + with self._lock: + return self._stddev_locked() + + @property + def n(self) -> float: + with self._lock: + return self._n + + @property + def escalated(self) -> bool: + with self._lock: + return self._escalated + + @property + def streak(self) -> int: + with self._lock: + return self._streak + + @property + def accepted(self) -> int: + with self._lock: + return self._accepted + + @property + def rejected(self) -> int: + with self._lock: + return self._rejected + + @property + def model_key(self) -> Optional[Tuple[str, str]]: + with self._lock: + return self._model_key + + # ── Intern ─────────────────────────────────────────────────────────── + + def _stddev_locked(self) -> float: + if self._n < 2.0: + return 0.0 + return math.sqrt(self._m2 / self._n) + + def _apply_decay_locked(self) -> None: + """7-Tage-Exponential-Decay: alte Messungen verblassen. + + Sub-Sekunden-Intervalle werden übersprungen — der Decay über + Mikrosekunden ist numerisch bedeutungslos und erzeugt nur + Float-Rauschen im effektiven Stichprobenumfang ``n``. + """ + now = self._clock() + if self._last_ts is not None and self._n > 0.0: + dt = now - self._last_ts + if dt >= 1.0: + alpha = math.exp(-dt / self._decay_tau_s) + self._n *= alpha + self._m2 *= alpha + self._last_ts = now + + def _maybe_escalate_locked(self) -> None: + if self._streak >= self._escalation_n and not self._escalated: + self._escalated = True + logger.warning( + "F93: Adaptive-Timeout-Eskalation — %d konsekutive Messungen " + "außerhalb Toleranz (mean=%.2fs, std=%.2fs). Temporäre Last " + "oder Modell-/Endpoint-Problem?", + self._streak, self._mean, self._stddev_locked(), + ) + + # ── Persistenz (P-101: atomar via tmp+rename) ──────────────────────── + + def _save_locked(self) -> None: + if not self._state_path: + return + try: + data = { + "n": self._n, + "mean": self._mean, + "m2": self._m2, + "last_ts": self._last_ts, + "model_key": list(self._model_key) if self._model_key else None, + "accepted": self._accepted, + "rejected": self._rejected, + } + 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("F93: Adaptive-Timeout-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) + self._n = float(data.get("n", 0.0)) + self._mean = float(data.get("mean", 0.0)) + self._m2 = float(data.get("m2", 0.0)) + self._last_ts = data.get("last_ts") + mk = data.get("model_key") + self._model_key = tuple(mk) if mk else None + self._accepted = int(data.get("accepted", 0)) + self._rejected = int(data.get("rejected", 0)) + logger.info( + "F93: Adaptive-Timeout-Kalibrierung geladen (n=%.1f, mean=%.2fs)", + self._n, self._mean, + ) + except Exception as e: + logger.warning("F93: Adaptive-Timeout-State laden fehlgeschlagen: %s", e) + + +# Modul-Level-Singleton — wird von classifier.py (OllamaLLMClient) importiert. +adaptive_timeout = AdaptiveLLMTimeout() diff --git a/plugin/archivar/classifier.py b/plugin/archivar/classifier.py index 0ab42c2..a8c9c7e 100644 --- a/plugin/archivar/classifier.py +++ b/plugin/archivar/classifier.py @@ -28,6 +28,7 @@ from .config import ( LLM_CONFIDENCE_THRESHOLD, FALLBACK_KEYWORDS ) +from .adaptive_timeout import adaptive_timeout logger = logging.getLogger(__name__) @@ -255,14 +256,26 @@ class OllamaLLMClient(LLMClient): self._base_url = (base_url or LLM_CONFIG["base_url"]).rstrip("/") self._model = model or LLM_CONFIG["model"] self._timeout = timeout or LLM_CONFIG["timeout"] + # F93: Modell-Schlüssel registrieren (Reset bei Modellwechsel). + adaptive_timeout.set_model(self._base_url, self._model) - def classify(self, text: str) -> Optional[str]: - """Call Ollama generate API. Returns category or None on any failure.""" + def _call_generate(self, prompt: str) -> Optional[str]: + """Führe einen /api/generate-Call mit adaptivem Timeout aus. + + F93: Der Timeout wird aus der selbstkalibrierenden Statistik + (``adaptive_timeout.current_timeout()``) bezogen statt aus dem + starren ``self._timeout``. Die gemessene Antwortzeit wird + zurückgespeist (``record``), Timeouts/Fehler als außerhalb-Toleranz + gewertet (Eskalations-Streak). + + Returns: + Der ``response``-String oder None bei Fehler/Timeout. + """ url = f"{self._base_url}/api/generate" payload = json.dumps( { "model": self._model, - "prompt": text, + "prompt": prompt, "stream": False, "options": { "temperature": LLM_CONFIG["temperature"], @@ -272,35 +285,46 @@ class OllamaLLMClient(LLMClient): ).encode("utf-8") headers = {"Content-Type": "application/json"} + timeout = adaptive_timeout.current_timeout() + t0 = time.monotonic() try: req = urllib.request.Request( url, data=payload, headers=headers, method="POST" ) - with urllib.request.urlopen(req, timeout=self._timeout) as resp: + with urllib.request.urlopen(req, timeout=timeout) as resp: data = json.loads(resp.read().decode("utf-8")) - response_text = data.get("response", "") - if not response_text: - logger.error("Ollama returned empty response") - return None - - # Trim whitespace and normalize category - category = response_text.strip().lower() - if category in ("direct_question", "smalltalk", "work_order", "ambiguous"): - return category - else: - logger.warning("LLM returned invalid category: %s", category) - return None - except urllib.error.HTTPError as e: - logger.warning("Ollama HTTP %d: %s", e.code, e.reason) - return None - except urllib.error.URLError as e: - logger.warning("Ollama connection failed: %s", e) + duration = time.monotonic() - t0 + adaptive_timeout.record(duration, success=True) + return data.get("response", "") + except (urllib.error.HTTPError, urllib.error.URLError) as e: + duration = time.monotonic() - t0 + adaptive_timeout.record(duration, success=False) + logger.warning("Ollama request failed: %s", e) return None except (json.JSONDecodeError, TypeError, ValueError) as e: + duration = time.monotonic() - t0 + adaptive_timeout.record(duration, success=True) logger.error("Ollama response parse error: %s", e) return None except Exception as e: - logger.error("Unexpected error in classify: %s", e) + duration = time.monotonic() - t0 + adaptive_timeout.record(duration, success=False) + logger.error("Unexpected error in LLM call: %s", e) + return None + + def classify(self, text: str) -> Optional[str]: + """Call Ollama generate API. Returns category or None on any failure.""" + response_text = self._call_generate(text) + if not response_text: + logger.error("Ollama returned empty response") + return None + + # Trim whitespace and normalize category + category = response_text.strip().lower() + if category in ("direct_question", "smalltalk", "work_order", "ambiguous"): + return category + else: + logger.warning("LLM returned invalid category: %s", category) return None def verify_confidence(self, text: str, scores: Dict[str, float]) -> Optional[Tuple[str, float]]: @@ -336,43 +360,11 @@ direct_question, smalltalk, work_order, oder ambiguous""" Returns: Die LLM-Antwort als String (getrimmt), oder None bei Fehler. """ - url = f"{self._base_url}/api/generate" - payload = json.dumps( - { - "model": self._model, - "prompt": prompt, - "stream": False, - "options": { - "temperature": LLM_CONFIG["temperature"], - "num_predict": LLM_CONFIG["max_tokens"], - } - } - ).encode("utf-8") - headers = {"Content-Type": "application/json"} - - try: - req = urllib.request.Request( - url, data=payload, headers=headers, method="POST" - ) - with urllib.request.urlopen(req, timeout=self._timeout) as resp: - data = json.loads(resp.read().decode("utf-8")) - response_text = data.get("response", "") - if not response_text: - logger.error("Ollama returned empty response for generate()") - return None - return response_text.strip() - except urllib.error.HTTPError as e: - logger.warning("Ollama HTTP %d in generate(): %s", e.code, e.reason) - return None - except urllib.error.URLError as e: - logger.warning("Ollama connection failed in generate(): %s", e) - return None - except (json.JSONDecodeError, TypeError, ValueError) as e: - logger.error("Ollama response parse error in generate(): %s", e) - return None - except Exception as e: - logger.error("Unexpected error in generate(): %s", e) + response_text = self._call_generate(prompt) + if not response_text: + logger.error("Ollama returned empty response for generate()") return None + return response_text.strip() class IntentClassifier: diff --git a/plugin/archivar/tests/test_f93_adaptive_timeout.py b/plugin/archivar/tests/test_f93_adaptive_timeout.py new file mode 100644 index 0000000..1346a41 --- /dev/null +++ b/plugin/archivar/tests/test_f93_adaptive_timeout.py @@ -0,0 +1,307 @@ +""" +F93 — Adaptiver LLM-Timeout: A1c-Testkonzept (verbindlich). + +Kalibrierungs-Fälle (Spec, Feature-Register Zeile F93): + 1. Failsafe — ohne Kalibrierungsdaten liefert current_timeout() 30s. + 2. Konvergenz — Welford konvergiert gegen den wahren Mittelwert; + current_timeout() = mean + sigma_band * std. + 3. Ausreißer — ±2σ-Messung wird verworfen (nicht in Statistik). + 4. Reset — Modellwechsel setzt die Kalibrierung hart zurück. + 5. Eskalation — erst N=2 konsekutive Messungen außerhalb Toleranz + setzen escalated=True (nicht schon die erste). + +Zusätzlich (Design-Entscheidungen): + 6. Score-basiert (FAISS-Analog) — score() liefert kontinuierlichen z-Score. + 7. 7-Tage-Decay — alte Messungen verblassen (n sinkt, mean bleibt). + 8. Persistenz — save/load roundtrip erhält den Kalibrierungszustand. +""" + +from __future__ import annotations + +import math +import sys +from pathlib import Path + +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) + +from plugin.archivar.adaptive_timeout import AdaptiveLLMTimeout + + +def _make(**kwargs): + """Frische Instanz ohne Persistenz (state_path=None) für deterministische Tests.""" + kwargs.setdefault("state_path", None) + kwargs.setdefault("failsafe_s", 30.0) + kwargs.setdefault("sigma_band", 2.0) + kwargs.setdefault("decay_tau_s", 7 * 24 * 3600) + kwargs.setdefault("escalation_n", 2) + kwargs.setdefault("min_samples", 3) + return AdaptiveLLMTimeout(**kwargs) + + +# ═══════════════════════════════════════════════════════════════════════════ +# 1. Failsafe +# ═══════════════════════════════════════════════════════════════════════════ + +class TestFailsafe: + def test_no_data_returns_failsafe(self): + t = _make() + assert t.current_timeout() == 30.0 + + def test_failsafe_until_first_sample(self): + t = _make() + # Eine einzelne Messung reicht nicht für mean+band (n<2 → std=0). + t.record(5.0) + # n=1 → current_timeout liefert weiterhin Failsafe (n < 1.0 ist false, + # aber std=0 → mean+0 = mean). Spec: Failsafe beim ersten Start. + # Mit n=1 ist mean=5.0, std=0 → timeout=5.0 (geklemmt auf min 1.0). + assert t.current_timeout() >= 1.0 + + def test_custom_failsafe(self): + t = _make(failsafe_s=45.0) + assert t.current_timeout() == 45.0 + + +# ═══════════════════════════════════════════════════════════════════════════ +# 2. Konvergenz (Welford) +# ═══════════════════════════════════════════════════════════════════════════ + +class TestConvergence: + def test_welford_mean_converges(self): + t = _make() + samples = [5.0, 5.0, 5.0, 5.0, 5.0] + for s in samples: + t.record(s) + assert t.mean == pytest.approx(5.0) + assert t.stddev == pytest.approx(0.0, abs=1e-9) + + def test_welford_matches_batch_formula(self): + """Welford-Online == klassische Batch-Formel (Korrektheits-Beweis). + + min_samples hoch gesetzt, damit die Ausreißer-Erkennung die + Welford-Mathematik nicht verfälscht (hier geht es rein um die + Korrektheit des Online-Algorithmus). + """ + t = _make(min_samples=1000) + samples = [3.0, 7.0, 5.0, 9.0, 4.0, 6.0] + for s in samples: + t.record(s) + n = len(samples) + mean = sum(samples) / n + var = sum((x - mean) ** 2 for x in samples) / n + assert t.mean == pytest.approx(mean) + assert t.stddev == pytest.approx(math.sqrt(var)) + + def test_timeout_is_mean_plus_band(self): + t = _make() + for s in [5.0, 5.0, 5.0, 5.0]: + t.record(s) + # std=0 → timeout = mean = 5.0 (geklemmt auf min 1.0). + assert t.current_timeout() == pytest.approx(5.0) + + def test_timeout_grows_with_variance(self): + t = _make() + for s in [4.0, 6.0, 4.0, 6.0, 4.0, 6.0]: + t.record(s) + # mean=5, std≈1 → timeout ≈ 5 + 2*1 = 7. + assert t.current_timeout() == pytest.approx(7.0, abs=0.2) + + +# ═══════════════════════════════════════════════════════════════════════════ +# 3. Ausreißer-Erkennung (±2σ → verwerfen) +# ═══════════════════════════════════════════════════════════════════════════ + +class TestOutlierRejection: + def test_outlier_rejected_not_in_statistics(self): + t = _make() + # Kalibrierung: 6 Messungen um 5.0 mit kleiner Varianz (std > 0). + for s in [4.9, 5.0, 5.1, 4.9, 5.0, 5.1]: + t.record(s) + n_before = t.n + mean_before = t.mean + # Ausreißer: 50s (Docker-Start) → > 2σ → verwerfen. + z = t.record(50.0) + assert abs(z) > 2.0 + assert t.n == pytest.approx(n_before) # nicht eingerechnet + assert t.mean == pytest.approx(mean_before) + assert t.rejected == 1 + + def test_inlier_accepted(self): + t = _make() + for s in [4.9, 5.0, 5.1, 4.9, 5.0, 5.1]: + t.record(s) + n_before = t.n + z = t.record(5.05) # innerhalb Toleranz (std ≈ 0.08 → z ≈ 0.6) + assert abs(z) <= 2.0 + assert t.n == pytest.approx(n_before + 1) + + def test_no_rejection_during_calibration(self): + """Vor min_samples wird alles akzeptiert (Std instabil).""" + t = _make(min_samples=3) + # Nur 2 Messungen → noch Kalibrierung → 50s wird akzeptiert. + t.record(5.0) + t.record(5.0) + t.record(50.0) # akzeptiert, weil n < min_samples + assert t.n == pytest.approx(3.0) + assert t.rejected == 0 + + +# ═══════════════════════════════════════════════════════════════════════════ +# 4. Reset bei Modellwechsel +# ═══════════════════════════════════════════════════════════════════════════ + +class TestModelReset: + def test_same_model_no_reset(self): + t = _make() + assert t.set_model("http://localhost:11434", "qwen2.5:7b") is True # erster Set + for s in [5.0, 5.0, 5.0]: + t.record(s) + assert t.set_model("http://localhost:11434", "qwen2.5:7b") is False + assert t.n == 3 # unverändert + + def test_model_change_hard_reset(self): + t = _make() + t.set_model("http://localhost:11434", "qwen2.5:7b") + for s in [5.0, 5.0, 5.0]: + t.record(s) + assert t.n == 3 + # Modellwechsel → Reset. + assert t.set_model("http://localhost:11434", "gemma4:31b") is True + assert t.n == 0 + assert t.current_timeout() == 30.0 # zurück auf Failsafe + + def test_endpoint_change_resets(self): + t = _make() + t.set_model("http://localhost:11434", "qwen2.5:7b") + t.record(5.0) + assert t.set_model("https://ollama.com/v1", "qwen2.5:7b") is True + assert t.n == 0 + + +# ═══════════════════════════════════════════════════════════════════════════ +# 5. Eskalation (N=2 konsekutiv) +# ═══════════════════════════════════════════════════════════════════════════ + +class TestEscalation: + def test_single_outlier_no_escalation(self): + t = _make() + for s in [4.9, 5.0, 5.1, 4.9, 5.0, 5.1]: + t.record(s) + t.record(50.0) # 1. Ausreißer + assert t.escalated is False + assert t.streak == 1 + + def test_two_consecutive_outliers_escalate(self): + t = _make() + for s in [4.9, 5.0, 5.1, 4.9, 5.0, 5.1]: + t.record(s) + t.record(50.0) # 1. Ausreißer → streak=1 + t.record(60.0) # 2. Ausreißer → streak=2 → Eskalation + assert t.escalated is True + + def test_inlier_resets_streak(self): + t = _make() + for s in [4.9, 5.0, 5.1, 4.9, 5.0, 5.1]: + t.record(s) + t.record(50.0) # streak=1 + t.record(5.1) # inlier → streak=0 + assert t.streak == 0 + assert t.escalated is False + + def test_failure_counts_as_out_of_tolerance(self): + """Timeout/Fehler (success=False) zählt als außerhalb Toleranz.""" + t = _make() + for s in [4.9, 5.0, 5.1, 4.9, 5.0, 5.1]: + t.record(s) + t.record(0.0, success=False) # streak=1 + t.record(0.0, success=False) # streak=2 → Eskalation + assert t.escalated is True + + +# ═══════════════════════════════════════════════════════════════════════════ +# 6. Score-basiert (FAISS-Analog) +# ═══════════════════════════════════════════════════════════════════════════ + +class TestScore: + def test_score_zero_at_mean(self): + t = _make() + for s in [5.0, 5.0, 5.0, 5.0]: + t.record(s) + assert t.score(5.0) == pytest.approx(0.0, abs=1e-9) + + def test_score_continuous(self): + t = _make() + for s in [4.0, 6.0, 4.0, 6.0, 4.0, 6.0]: + t.record(s) + # mean=5, std≈1 → score(7) ≈ 2.0, score(3) ≈ -2.0. + assert t.score(7.0) == pytest.approx(2.0, abs=0.2) + assert t.score(3.0) == pytest.approx(-2.0, abs=0.2) + + def test_score_zero_during_calibration(self): + t = _make() + t.record(5.0) + assert t.score(100.0) == 0.0 # n<2 → kein Score + + +# ═══════════════════════════════════════════════════════════════════════════ +# 7. 7-Tage-Exponential-Decay +# ═══════════════════════════════════════════════════════════════════════════ + +class TestDecay: + def test_decay_reduces_effective_n(self): + # Fake-Clock: kontrollierbarer Zeitverlauf. + now = [0.0] + + def fake_clock(): + return now[0] + + t = _make(clock=fake_clock, decay_tau_s=100.0) + for s in [5.0, 5.0, 5.0, 5.0]: + t.record(s) + assert t.n == pytest.approx(4.0) + # 100s später (1 tau) → n halbiert sich beim nächsten record. + now[0] = 100.0 + t.record(5.0) + # n war 4, decay auf ~1.47, +1 = ~2.47. + assert t.n < 4.0 + assert t.n > 1.0 + + def test_decay_keeps_mean_stable(self): + now = [0.0] + + def fake_clock(): + return now[0] + + t = _make(clock=fake_clock, decay_tau_s=100.0) + for s in [5.0, 5.0, 5.0, 5.0]: + t.record(s) + mean_before = t.mean + now[0] = 100.0 + t.record(5.0) + assert t.mean == pytest.approx(mean_before) # uniforme Skalierung + + +# ═══════════════════════════════════════════════════════════════════════════ +# 8. Persistenz (P-101: save/load roundtrip) +# ═══════════════════════════════════════════════════════════════════════════ + +class TestPersistence: + def test_roundtrip(self, tmp_path): + state_path = str(tmp_path / "adaptive_timeout_state.json") + t = _make(state_path=state_path) + t.set_model("http://localhost:11434", "qwen2.5:7b") + for s in [5.0, 5.0, 5.0, 5.0]: + t.record(s) + + # Neue Instanz lädt denselben State. + t2 = _make(state_path=state_path) + assert t2.n == pytest.approx(t.n) + assert t2.mean == pytest.approx(t.mean) + assert t2.model_key == ("http://localhost:11434", "qwen2.5:7b") + + def test_load_missing_file_is_noop(self, tmp_path): + state_path = str(tmp_path / "does_not_exist.json") + t = _make(state_path=state_path) + assert t.n == 0 + assert t.current_timeout() == 30.0