diff --git a/plugin/archivar/adaptive_timeout.py b/plugin/archivar/adaptive_timeout.py index a31ed63..4ff173a 100644 --- a/plugin/archivar/adaptive_timeout.py +++ b/plugin/archivar/adaptive_timeout.py @@ -365,6 +365,13 @@ class AdaptiveLLMTimeout: self._n = float(data.get("n", 0.0)) self._mean = float(data.get("mean", 0.0)) self._m2 = float(data.get("m2", 0.0)) + # F4: Negative n-Werte aus korrupten States sanitizen — n ist ein + # effektiver Stichprobenumfang und darf nie < 0 sein (würde sonst + # als Index/Iteration zu Fehlverhalten führen). + if self._n < 0.0: + self._n = 0.0 + if self._m2 < 0.0: + self._m2 = 0.0 self._last_ts = data.get("last_ts") mk = data.get("model_key") self._model_key = tuple(mk) if mk else None diff --git a/plugin/archivar/classifier.py b/plugin/archivar/classifier.py index a8c9c7e..59c208e 100644 --- a/plugin/archivar/classifier.py +++ b/plugin/archivar/classifier.py @@ -251,11 +251,12 @@ class OllamaLLMClient(LLMClient): Args: base_url: Ollama base URL (default from ``config.LLM_CONFIG``). model: LLM model (default from ``config.LLM_CONFIG``). - timeout: Request timeout in seconds (default from ``config.LLM_CONFIG``). + timeout: Deprecated/ignored. Der Timeout wird seit F93 adaptiv + über ``adaptive_timeout.current_timeout()`` bestimmt; der + Parameter bleibt nur für API-Kompatibilität erhalten. """ 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) @@ -263,10 +264,9 @@ class OllamaLLMClient(LLMClient): """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). + (``adaptive_timeout.current_timeout()``) bezogen. 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. @@ -302,8 +302,12 @@ class OllamaLLMClient(LLMClient): logger.warning("Ollama request failed: %s", e) return None except (json.JSONDecodeError, TypeError, ValueError) as e: + # F6a: Parse-Fehler = kaputtes Modell/Endpoint (Server liefert Müll + # oder Verarbeitungsfehler) → success=False, damit der + # Eskalations-Streak getriggert wird (Spec: Eskalation bei + # "Modell-/Endpoint-Problem"). duration = time.monotonic() - t0 - adaptive_timeout.record(duration, success=True) + adaptive_timeout.record(duration, success=False) logger.error("Ollama response parse error: %s", e) return None except Exception as e: diff --git a/plugin/archivar/tests/test_f93_adaptive_timeout.py b/plugin/archivar/tests/test_f93_adaptive_timeout.py index 1346a41..3b075e7 100644 --- a/plugin/archivar/tests/test_f93_adaptive_timeout.py +++ b/plugin/archivar/tests/test_f93_adaptive_timeout.py @@ -305,3 +305,27 @@ class TestPersistence: 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 diff --git a/plugin/archivar/tests/test_f93_classifier_f6a.py b/plugin/archivar/tests/test_f93_classifier_f6a.py new file mode 100644 index 0000000..808f7f7 --- /dev/null +++ b/plugin/archivar/tests/test_f93_classifier_f6a.py @@ -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