9798a3e8a0
Zweite Verteidigungslinie gegen die 110 Router-Timeouts/7d (Andreas-Direktive 01.09.): Stufe 4b prüft beim Start, dass Modell+Endpoint wirklich antworten (Smoke-Test), der Runtime-Watchdog misst die echte Router-Pipeline über record_attempt() nach jedem Live-Call. D1 Stufe 4b (self_check.py): - _probe_llm_room_e2e(): POST /api/generate mit Mini-Prompt, Latenz <= 15s - ComponentCheckResult + llm_room_e2e_ok / llm_room_e2e_latency_ms - ready = ... AND llm_room_e2e_ok; needs_warmup schliesst 4b-Fail ein - Prompt empirisch kalibriert (qwen2.5:7b): 'Antworte ausschließlich mit dem Wort STAY' statt naivem 'genau einem Wort: STAY' (lieferte 'Ok.') D2 Runtime-Watchdog (routing_counter.py + router.py + adapter.py): - RoutingCounter.record_attempt() + success_ratio(window_s, min_samples) (NEUE Methoden, increment() unverändert — P-019, 165 Call-Sites) - record_attempt() an success/timeout/exception-Branches (router.py Z.1670+) - _start_routing_watchdog() neben _start_self_check() in connect() - 5 Konstanten in config.py (Kalibrierungs-Kommentar 'nach 7 Tagen prüfen') K3 Cooldown (watchdog_alert.py, NEU): - 24h-Cooldown + persistentes Flag in ~/.hermes/hermes-agent/data/ routing_watchdog_alert.json (last_alert_ts, atomar via tmp+rename P-101) - logger.error (KEIN RC-Post, P-088-Lehre) D3 Tests: test_f92_self_check erweitert (TestStufe4bProbe, TestComponentCheckResult4b), test_f92_routing_counter.py (Window/Min-Samples/ Boundary/GC), test_f100_watchdog.py (Trigger/Cooldown/Min-Samples/Persistenz). D4 Verifikation: echte Probe gegen localhost:11434 (qwen2.5:7b) → ok=True, latency ~850ms. 98 Tests grün (F92/F93/F100 + Stufe4-Red-Flag). KEIN Push, KEIN Deploy — wartet auf QG-Freigabe Rainer.
383 lines
15 KiB
Python
383 lines
15 KiB
Python
"""
|
|
Feature 92 — Self-Check: 6-stufige Komponenten-Diagnose nach Gateway-Start.
|
|
|
|
Testkonzept (A1c-Pflicht):
|
|
1. check_components() klassifiziert die 6 Stufen korrekt.
|
|
2. Fehler-Stufen (1-3) → --repair-Meldung (build_report_message).
|
|
3. Warmup-Stufen (4-5) → Lade-Meldung (kein Fehler, kein silent).
|
|
4. Stufe 6 (alles OK) → silent (None).
|
|
5. Adapter-Verdrahtung: _start_self_check() ist nicht-blockierend,
|
|
überspringt bei MULTIROOM_AGENT=false, und _run_self_check() sendet die
|
|
Meldung an den Operator-DM (nicht an den Agenten).
|
|
|
|
Die Probes sind module-level Funktionen (self_check._probe_*), damit Tests sie
|
|
gezielt patchen können, ohne echte faiss/Ollama-Abhängigkeiten zu brauchen.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import sys
|
|
import time
|
|
from pathlib import Path
|
|
from unittest.mock import AsyncMock, MagicMock, patch
|
|
|
|
import pytest
|
|
|
|
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
|
|
|
|
from plugin.archivar.self_check import (
|
|
ComponentCheckResult,
|
|
build_report_message,
|
|
check_components,
|
|
SELF_CHECK_TIMEOUT_S,
|
|
)
|
|
|
|
|
|
def _result(**overrides) -> ComponentCheckResult:
|
|
base = dict(
|
|
faiss_importable=True,
|
|
index_loadable=True,
|
|
ollama_reachable=True,
|
|
llm_model_loaded=True,
|
|
embedding_ladbar=True,
|
|
ready=True,
|
|
llm_room_e2e_ok=True,
|
|
llm_room_e2e_latency_ms=123.0,
|
|
)
|
|
base.update(overrides)
|
|
# ready ist abgeleitet — neu berechnen, außer explizit gesetzt.
|
|
if "ready" not in overrides:
|
|
base["ready"] = (
|
|
base["faiss_importable"]
|
|
and base["index_loadable"]
|
|
and base["ollama_reachable"]
|
|
and base["llm_model_loaded"]
|
|
and base["embedding_ladbar"]
|
|
and base["llm_room_e2e_ok"]
|
|
)
|
|
return ComponentCheckResult(**base)
|
|
|
|
|
|
class TestComponentCheckResult:
|
|
"""Klassifikations-Logik: has_error / needs_warmup / ready."""
|
|
|
|
def test_ready_when_all_ok(self):
|
|
r = _result()
|
|
assert r.ready is True
|
|
assert r.has_error is False
|
|
assert r.needs_warmup is False
|
|
|
|
def test_error_when_faiss_missing(self):
|
|
r = _result(faiss_importable=False)
|
|
assert r.has_error is True
|
|
|
|
def test_error_when_index_missing(self):
|
|
r = _result(index_loadable=False)
|
|
assert r.has_error is True
|
|
|
|
def test_error_when_ollama_down(self):
|
|
r = _result(ollama_reachable=False)
|
|
assert r.has_error is True
|
|
|
|
def test_warmup_when_llm_model_missing(self):
|
|
r = _result(llm_model_loaded=False)
|
|
assert r.has_error is False
|
|
assert r.needs_warmup is True
|
|
|
|
def test_warmup_when_embedding_missing(self):
|
|
r = _result(embedding_ladbar=False)
|
|
assert r.has_error is False
|
|
assert r.needs_warmup is True
|
|
|
|
|
|
class TestCheckComponents:
|
|
"""check_components() kombiniert die 6 Stufen zur gemeinsamen Diagnose."""
|
|
|
|
def test_all_probes_ok(self):
|
|
with patch("plugin.archivar.self_check._probe_faiss_importable", return_value=True), \
|
|
patch("plugin.archivar.self_check._probe_index_loadable", return_value=True), \
|
|
patch("plugin.archivar.self_check._probe_ollama_reachable", return_value=True), \
|
|
patch("plugin.archivar.self_check._probe_models", return_value=["qwen2.5:7b", "nomic-embed-text"]), \
|
|
patch("plugin.archivar.self_check._probe_embedding", return_value=True), \
|
|
patch("plugin.archivar.self_check._probe_llm_room_e2e", return_value=(True, 123.0, "")):
|
|
r = check_components()
|
|
assert r.ready is True
|
|
assert r.faiss_importable and r.index_loadable and r.ollama_reachable
|
|
assert r.llm_model_loaded and r.embedding_ladbar
|
|
assert r.llm_room_e2e_ok is True
|
|
|
|
def test_faiss_missing_reports_error_stage1(self):
|
|
with patch("plugin.archivar.self_check._probe_faiss_importable", return_value=False), \
|
|
patch("plugin.archivar.self_check._probe_index_loadable", return_value=True), \
|
|
patch("plugin.archivar.self_check._probe_ollama_reachable", return_value=True), \
|
|
patch("plugin.archivar.self_check._probe_models", return_value=["qwen2.5:7b"]), \
|
|
patch("plugin.archivar.self_check._probe_embedding", return_value=True):
|
|
r = check_components()
|
|
assert r.faiss_importable is False
|
|
assert r.has_error is True
|
|
assert r.ready is False
|
|
|
|
def test_ollama_down_skips_model_and_embedding_probes(self):
|
|
"""Stufe 3 down → Stufen 4/5 werden nicht (sinnlos) geprüft."""
|
|
with patch("plugin.archivar.self_check._probe_faiss_importable", return_value=True), \
|
|
patch("plugin.archivar.self_check._probe_index_loadable", return_value=True), \
|
|
patch("plugin.archivar.self_check._probe_ollama_reachable", return_value=False), \
|
|
patch("plugin.archivar.self_check._probe_models") as mock_models, \
|
|
patch("plugin.archivar.self_check._probe_embedding") as mock_emb:
|
|
r = check_components()
|
|
assert r.ollama_reachable is False
|
|
assert r.llm_model_loaded is False
|
|
assert r.embedding_ladbar is False
|
|
assert r.has_error is True
|
|
mock_models.assert_not_called()
|
|
mock_emb.assert_not_called()
|
|
|
|
def test_llm_model_missing_is_warmup_not_error(self):
|
|
with patch("plugin.archivar.self_check._probe_faiss_importable", return_value=True), \
|
|
patch("plugin.archivar.self_check._probe_index_loadable", return_value=True), \
|
|
patch("plugin.archivar.self_check._probe_ollama_reachable", return_value=True), \
|
|
patch("plugin.archivar.self_check._probe_models", return_value=["nomic-embed-text"]), \
|
|
patch("plugin.archivar.self_check._probe_embedding", return_value=True):
|
|
r = check_components()
|
|
assert r.llm_model_loaded is False
|
|
assert r.has_error is False
|
|
assert r.needs_warmup is True
|
|
|
|
|
|
class TestBuildReportMessage:
|
|
"""User-Meldungen: silent bei OK, --repair bei Fehler, Laden bei Warmup."""
|
|
|
|
def test_ready_is_silent(self):
|
|
assert build_report_message(_result()) is None
|
|
|
|
def test_error_mentions_repair_command(self):
|
|
msg = build_report_message(_result(faiss_importable=False))
|
|
assert msg is not None
|
|
assert "./install.sh --repair" in msg
|
|
|
|
def test_warmup_message_is_not_error(self):
|
|
msg = build_report_message(_result(llm_model_loaded=False))
|
|
assert msg is not None
|
|
assert "./install.sh --repair" not in msg
|
|
assert "lade" in msg.lower() or "laden" in msg.lower()
|
|
|
|
def test_every_error_stage_mentions_repair(self):
|
|
"""Stufe 1, 2, 3 — jede Fehler-Stufe muss auf --repair verweisen."""
|
|
for overrides in (
|
|
{"faiss_importable": False},
|
|
{"index_loadable": False},
|
|
{"ollama_reachable": False},
|
|
):
|
|
msg = build_report_message(_result(**overrides))
|
|
assert msg is not None
|
|
assert "./install.sh --repair" in msg, f"Stufe {overrides} ohne --repair"
|
|
|
|
|
|
class TestAdapterSelfCheckWiring:
|
|
"""Adapter-Verdrahtung: nicht-blockierend, MULTIROOM-Guard, Operator-DM."""
|
|
|
|
def _make_adapter(self):
|
|
from plugin.adapter import RocketChatAdapter
|
|
adapter = RocketChatAdapter.__new__(RocketChatAdapter)
|
|
adapter.archivar = MagicMock()
|
|
adapter._room_info = {"dm_room": {"type": "d"}, "chan": {"type": "c"}}
|
|
adapter.rest = MagicMock()
|
|
adapter.rest.auth_token = "tok"
|
|
adapter._post_message_with_retry = AsyncMock(return_value="msg-id")
|
|
return adapter
|
|
|
|
def test_start_self_check_skips_when_not_multiroom(self):
|
|
adapter = self._make_adapter()
|
|
adapter.archivar = None
|
|
with patch("plugin.adapter._MULTIROOM", return_value=False), \
|
|
patch("plugin.adapter.asyncio.ensure_future") as mock_ef:
|
|
adapter._start_self_check()
|
|
mock_ef.assert_not_called()
|
|
|
|
def test_start_self_check_is_non_blocking(self):
|
|
adapter = self._make_adapter()
|
|
with patch("plugin.adapter._MULTIROOM", return_value=True), \
|
|
patch("plugin.adapter.asyncio.ensure_future") as mock_ef:
|
|
adapter._start_self_check()
|
|
mock_ef.assert_called_once()
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_run_self_check_error_sends_to_operator(self):
|
|
adapter = self._make_adapter()
|
|
result = _result(faiss_importable=False)
|
|
|
|
with patch("archivar.self_check.check_components", return_value=result), \
|
|
patch("archivar.self_check.build_report_message", return_value="REPAIR MSG"):
|
|
await adapter._run_self_check()
|
|
|
|
adapter._post_message_with_retry.assert_awaited_once()
|
|
args, _ = adapter._post_message_with_retry.call_args
|
|
assert args[0] == "dm_room" # Operator-DM, nicht Agent-Chat
|
|
assert args[1] == "REPAIR MSG"
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_run_self_check_ready_is_silent(self):
|
|
adapter = self._make_adapter()
|
|
result = _result()
|
|
|
|
with patch("archivar.self_check.check_components", return_value=result), \
|
|
patch("archivar.self_check.build_report_message", return_value=None):
|
|
await adapter._run_self_check()
|
|
|
|
adapter._post_message_with_retry.assert_not_called()
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_run_self_check_timeout_is_silent(self):
|
|
"""30s-Timeout → keine Meldung, kein Crash.
|
|
|
|
check_components() läuft via asyncio.to_thread (synchron in einem
|
|
Worker-Thread) — ein blockierender sync-Callable simuliert den Hänger.
|
|
"""
|
|
adapter = self._make_adapter()
|
|
|
|
def _slow():
|
|
time.sleep(10)
|
|
return _result()
|
|
|
|
with patch("archivar.self_check.check_components", side_effect=_slow), \
|
|
patch("archivar.self_check.SELF_CHECK_TIMEOUT_S", 0.05):
|
|
await adapter._run_self_check()
|
|
|
|
adapter._post_message_with_retry.assert_not_called()
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_run_self_check_no_operator_room_is_silent(self):
|
|
"""Kein DM-Raum → Meldung verworfen, kein Crash."""
|
|
adapter = self._make_adapter()
|
|
adapter._room_info = {"chan": {"type": "c"}}
|
|
result = _result(faiss_importable=False)
|
|
|
|
with patch("archivar.self_check.check_components", return_value=result), \
|
|
patch("archivar.self_check.build_report_message", return_value="REPAIR MSG"):
|
|
await adapter._run_self_check()
|
|
|
|
adapter._post_message_with_retry.assert_not_called()
|
|
|
|
def test_find_operator_room_returns_first_dm(self):
|
|
adapter = self._make_adapter()
|
|
assert adapter._find_operator_room() == "dm_room"
|
|
|
|
def test_find_operator_room_returns_none_without_dm(self):
|
|
adapter = self._make_adapter()
|
|
adapter._room_info = {"chan": {"type": "c"}}
|
|
assert adapter._find_operator_room() is None
|
|
|
|
def test_timeout_default_is_30s(self):
|
|
assert SELF_CHECK_TIMEOUT_S == 30.0
|
|
|
|
|
|
# ── F100: Stufe 4b — Router-E2E-Probe ──────────────────────────────────────
|
|
|
|
|
|
class TestStufe4bProbe:
|
|
"""_probe_llm_room_e2e(): POST /api/generate mit Mini-Prompt "STAY"."""
|
|
|
|
def test_probe_ok_on_stay_response(self):
|
|
from plugin.archivar.self_check import _probe_llm_room_e2e
|
|
|
|
class _Resp:
|
|
def read(self):
|
|
return b'{"response": "STAY"}'
|
|
|
|
def __enter__(self):
|
|
return self
|
|
|
|
def __exit__(self, *a):
|
|
return False
|
|
|
|
with patch("plugin.archivar.self_check.urllib.request.urlopen", return_value=_Resp()):
|
|
ok, latency_ms, detail = _probe_llm_room_e2e(
|
|
"http://localhost:11434", "qwen2.5:7b", 15.0
|
|
)
|
|
assert ok is True
|
|
assert latency_ms >= 0.0
|
|
assert detail == ""
|
|
|
|
def test_probe_ok_case_insensitive(self):
|
|
from plugin.archivar.self_check import _probe_llm_room_e2e
|
|
|
|
class _Resp:
|
|
def read(self):
|
|
return b'{"response": " stay "}'
|
|
|
|
def __enter__(self):
|
|
return self
|
|
|
|
def __exit__(self, *a):
|
|
return False
|
|
|
|
with patch("plugin.archivar.self_check.urllib.request.urlopen", return_value=_Resp()):
|
|
ok, _, _ = _probe_llm_room_e2e("http://localhost:11434", "qwen2.5:7b", 15.0)
|
|
assert ok is True
|
|
|
|
def test_probe_fail_on_garbage_response(self):
|
|
from plugin.archivar.self_check import _probe_llm_room_e2e
|
|
|
|
class _Resp:
|
|
def read(self):
|
|
return '{"response": "völlig anderer Text"}'.encode("utf-8")
|
|
|
|
def __enter__(self):
|
|
return self
|
|
|
|
def __exit__(self, *a):
|
|
return False
|
|
|
|
with patch("plugin.archivar.self_check.urllib.request.urlopen", return_value=_Resp()):
|
|
ok, _, detail = _probe_llm_room_e2e("http://localhost:11434", "qwen2.5:7b", 15.0)
|
|
assert ok is False
|
|
assert "unerwartete Antwort" in detail
|
|
|
|
def test_probe_fail_on_http_error(self):
|
|
from plugin.archivar.self_check import _probe_llm_room_e2e
|
|
import urllib.error
|
|
|
|
with patch(
|
|
"plugin.archivar.self_check.urllib.request.urlopen",
|
|
side_effect=urllib.error.URLError("connection refused"),
|
|
):
|
|
ok, latency_ms, detail = _probe_llm_room_e2e(
|
|
"http://localhost:11434", "qwen2.5:7b", 15.0
|
|
)
|
|
assert ok is False
|
|
assert latency_ms == 0.0
|
|
assert "Fehler" in detail
|
|
|
|
def test_probe_fail_on_timeout(self):
|
|
from plugin.archivar.self_check import _probe_llm_room_e2e
|
|
import socket
|
|
|
|
with patch(
|
|
"plugin.archivar.self_check.urllib.request.urlopen",
|
|
side_effect=socket.timeout("timed out"),
|
|
):
|
|
ok, _, _ = _probe_llm_room_e2e("http://localhost:11434", "qwen2.5:7b", 15.0)
|
|
assert ok is False
|
|
|
|
|
|
class TestComponentCheckResult4b:
|
|
"""Stufe 4b-Fail → needs_warmup=True, ready=False (Warmup, kein Fehler)."""
|
|
|
|
def test_4b_fail_is_warmup_not_error(self):
|
|
r = _result(llm_room_e2e_ok=False)
|
|
assert r.has_error is False
|
|
assert r.needs_warmup is True
|
|
assert r.ready is False
|
|
|
|
def test_4b_ok_ready(self):
|
|
r = _result(llm_room_e2e_ok=True)
|
|
assert r.ready is True
|
|
assert r.needs_warmup is False
|
|
|
|
def test_4b_fail_build_report_message_is_warmup(self):
|
|
msg = build_report_message(_result(llm_room_e2e_ok=False))
|
|
assert msg is not None
|
|
assert "./install.sh --repair" not in msg
|
|
assert "lade" in msg.lower() or "laden" in msg.lower()
|