8b106f50b4
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
308 lines
13 KiB
Python
308 lines
13 KiB
Python
"""
|
||
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
|