Merge fix/reasoning-glm53-none-mapping: F93 Adaptiver LLM-Timeout (QG-freigegeben, Rainer Round 2)
# Conflicts: # STATUS.md
This commit is contained in:
@@ -0,0 +1,331 @@
|
||||
"""
|
||||
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
|
||||
|
||||
def test_load_sanitizes_negative_n(self, tmp_path):
|
||||
"""F4: Negative n-Werte aus korrupten States werden auf 0.0 gesetzt."""
|
||||
import json as _json
|
||||
state_path = str(tmp_path / "adaptive_timeout_state.json")
|
||||
_json.dump(
|
||||
{"n": -5.0, "mean": 3.0, "m2": -1.0, "model_key": ["http://x", "m"]},
|
||||
open(state_path, "w"),
|
||||
)
|
||||
t = _make(state_path=state_path)
|
||||
assert t.n == 0.0
|
||||
assert t.current_timeout() == 30.0 # n<1 → Failsafe
|
||||
|
||||
def test_load_sanitizes_negative_m2(self, tmp_path):
|
||||
"""F4: Negative m2 (Varianz-Summe) wird auf 0.0 gesetzt."""
|
||||
import json as _json
|
||||
state_path = str(tmp_path / "adaptive_timeout_state.json")
|
||||
_json.dump(
|
||||
{"n": 4.0, "mean": 5.0, "m2": -3.0, "model_key": ["http://x", "m"]},
|
||||
open(state_path, "w"),
|
||||
)
|
||||
t = _make(state_path=state_path)
|
||||
assert t.n == 4.0
|
||||
assert t.stddev == 0.0 # m2=0 → std=0
|
||||
@@ -0,0 +1,130 @@
|
||||
"""
|
||||
F93 — F6a-Fix: JSON-Parse-Fehler in _call_generate → success=False.
|
||||
|
||||
Rainer-QG Round 1 (Befund F6a): json.JSONDecodeError/TypeError/ValueError
|
||||
wurden fälschlich als success=True gewertet. Semantisch korrekt ist
|
||||
success=False, damit ein kaputtes Modell/Endpoint den Eskalations-Streak
|
||||
triggert (Spec: Eskalation bei "Modell-/Endpoint-Problem").
|
||||
|
||||
Diese Tests verifizieren, dass der Parse-Fehler-Pfad in
|
||||
``OllamaLLMClient._call_generate`` den adaptiven Timeout mit
|
||||
``success=False`` speist (und nicht mehr ``success=True``).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
|
||||
|
||||
from plugin.archivar import classifier as classifier_mod
|
||||
from plugin.archivar.classifier import OllamaLLMClient
|
||||
|
||||
|
||||
class _FakeResponse:
|
||||
"""Context-Manager-Response, dessen read() einen gegebenen Body liefert."""
|
||||
|
||||
def __init__(self, body: bytes):
|
||||
self._body = body
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc):
|
||||
return False
|
||||
|
||||
def read(self) -> bytes:
|
||||
return self._body
|
||||
|
||||
|
||||
def _make_client():
|
||||
"""OllamaLLMClient ohne echten Netzwerkzugriff (nur für _call_generate)."""
|
||||
return OllamaLLMClient(base_url="http://localhost:11434", model="qwen2.5:7b")
|
||||
|
||||
|
||||
class TestF6aParseErrorRecordsFailure:
|
||||
def test_json_decode_error_records_failure(self):
|
||||
"""JSONDecodeError (Server liefert Müll) → success=False."""
|
||||
client = _make_client()
|
||||
# urlopen liefert ungültiges JSON → json.loads wirft JSONDecodeError.
|
||||
with mock.patch.object(
|
||||
classifier_mod.urllib.request, "urlopen",
|
||||
return_value=_FakeResponse(b"not-json{{{"),
|
||||
), mock.patch.object(
|
||||
classifier_mod.adaptive_timeout, "current_timeout", return_value=30.0
|
||||
), mock.patch.object(
|
||||
classifier_mod.adaptive_timeout, "record"
|
||||
) as mock_record:
|
||||
result = client._call_generate("test prompt")
|
||||
|
||||
assert result is None
|
||||
# record wurde mit success=False aufgerufen (F6a-Fix).
|
||||
mock_record.assert_called_once()
|
||||
_, kwargs = mock_record.call_args
|
||||
assert kwargs["success"] is False
|
||||
|
||||
def test_type_error_records_failure(self):
|
||||
"""TypeError (Verarbeitungsfehler) → success=False."""
|
||||
client = _make_client()
|
||||
# json.loads wirft TypeError (z.B. wenn resp.read() kein str/bytes liefert).
|
||||
with mock.patch.object(
|
||||
classifier_mod.urllib.request, "urlopen",
|
||||
return_value=_FakeResponse(b"{}"),
|
||||
), mock.patch.object(
|
||||
classifier_mod.adaptive_timeout, "current_timeout", return_value=30.0
|
||||
), mock.patch.object(
|
||||
classifier_mod.json, "loads", side_effect=TypeError("bad type")
|
||||
), mock.patch.object(
|
||||
classifier_mod.adaptive_timeout, "record"
|
||||
) as mock_record:
|
||||
result = client._call_generate("test prompt")
|
||||
|
||||
assert result is None
|
||||
mock_record.assert_called_once()
|
||||
_, kwargs = mock_record.call_args
|
||||
assert kwargs["success"] is False
|
||||
|
||||
def test_value_error_records_failure(self):
|
||||
"""ValueError (z.B. falsches Format) → success=False."""
|
||||
client = _make_client()
|
||||
# json.loads wirft ValueError bei ungültigem JSON-Format.
|
||||
with mock.patch.object(
|
||||
classifier_mod.urllib.request, "urlopen",
|
||||
return_value=_FakeResponse(b"{}"),
|
||||
), mock.patch.object(
|
||||
classifier_mod.adaptive_timeout, "current_timeout", return_value=30.0
|
||||
), mock.patch.object(
|
||||
classifier_mod.json, "loads", side_effect=ValueError("bad value")
|
||||
), mock.patch.object(
|
||||
classifier_mod.adaptive_timeout, "record"
|
||||
) as mock_record:
|
||||
result = client._call_generate("test prompt")
|
||||
|
||||
assert result is None
|
||||
mock_record.assert_called_once()
|
||||
_, kwargs = mock_record.call_args
|
||||
assert kwargs["success"] is False
|
||||
|
||||
def test_valid_json_records_success(self):
|
||||
"""Gegenprobe: gültiges JSON → success=True (kein Regression)."""
|
||||
client = _make_client()
|
||||
valid_body = json.dumps({"response": "direct_question"}).encode("utf-8")
|
||||
with mock.patch.object(
|
||||
classifier_mod.urllib.request, "urlopen",
|
||||
return_value=_FakeResponse(valid_body),
|
||||
), mock.patch.object(
|
||||
classifier_mod.adaptive_timeout, "current_timeout", return_value=30.0
|
||||
), mock.patch.object(
|
||||
classifier_mod.adaptive_timeout, "record"
|
||||
) as mock_record:
|
||||
result = client._call_generate("test prompt")
|
||||
|
||||
assert result == "direct_question"
|
||||
mock_record.assert_called_once()
|
||||
_, kwargs = mock_record.call_args
|
||||
assert kwargs["success"] is True
|
||||
Reference in New Issue
Block a user