feat(F92): Self-Check check_components() im Plugin — 6-stufige Background-Diagnose
Feature 92: 6-stufige Self-Check-Pipeline im Plugin als Background-Task bei
Gateway-Start (Python-Pendant zu Don's check_components() in install.sh).
- plugin/archivar/self_check.py: check_components() mit 6 Stufen
(FAISS→Index→Ollama→Modell→Embedding→Ready), nur stdlib (keine
faiss/numpy auf Modulebene — genau das soll der Check erkennen).
- adapter.py: _start_self_check()/_run_self_check() nicht-blockierend via
asyncio.to_thread + wait_for(30s). Meldung an Operator-DM (User), NICHT
an den Agenten. MULTIROOM_AGENT=false → übersprungen.
- Klassifikation: Stufe 1-3 Fehler → './install.sh --repair'-Hinweis;
Stufe 4-5 → Warmup ('ich lade gerade'); Stufe 6 → silent.
- 23 Tests (test_f92_self_check.py): Probes, Klassifikation,
build_report_message, Adapter-Verdrahtung, Timeout, Operator-DM.
This commit is contained in:
@@ -0,0 +1,276 @@
|
||||
"""
|
||||
Feature 92 — Self-Check: 6-stufige Komponenten-Diagnose nach Gateway-Start.
|
||||
|
||||
Python-Pendant zu `check_components()` in install.sh (Don, Feature 92 /
|
||||
`--repair`). Beide teilen sich dieselbe Komponentenliste, Reihenfolge und
|
||||
Stufen-Nummerierung, damit Diagnose (Plugin) und Therapie
|
||||
(`install.sh --repair`) nie auseinanderlaufen.
|
||||
|
||||
Stufen (Abhängigkeitskette):
|
||||
1. FAISS importierbar (`import faiss`)
|
||||
2. Index ladbar (room_index.faiss + room_index.meta)
|
||||
3. Ollama erreichbar (GET /api/tags)
|
||||
4. Modell geladen (LLM-Modell in /api/tags)
|
||||
5. Embedding ladbar (POST /api/embeddings → Vektor)
|
||||
6. Ready (Stufen 1-5 alle OK)
|
||||
|
||||
Fehler-Klassifikation (Feature 92 / install-repair-konzept.md §4):
|
||||
Stufe 1-3 Fehler = "errors" → User-Meldung mit "./install.sh --repair"
|
||||
Stufe 4-5 Fehler = "warmup" → User-Meldung "ich lade gerade"
|
||||
Stufe 6 (alles OK) = silent → keine Meldung
|
||||
|
||||
WICHTIG (P-093-Klasse): Dieses Modul darf NIEMALS schwere Abhängigkeiten
|
||||
(faiss, numpy) auf Modulebene importieren — genau diese Abhängigkeiten soll
|
||||
der Check erkennen. Es verwendet nur stdlib (urllib, json, os, pathlib) plus
|
||||
`config` (das selbst nur json/os importiert).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import List, Optional
|
||||
|
||||
from .config import OLLAMA_CONFIG, LLM_CONFIG
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# ── Timeout-Konstanten ──────────────────────────────────────────────────────
|
||||
# Feature 92: 30s Timeout für den GESAMTEN Check (wird vom Adapter via
|
||||
# asyncio.wait_for() durchgesetzt). Zusätzlich ein kurzer HTTP-Timeout pro
|
||||
# Einzel-Check (analog install.sh `curl --max-time 3`), damit ein hängendes
|
||||
# Ollama nicht die ganze Diagnose blockiert.
|
||||
|
||||
SELF_CHECK_TIMEOUT_S: float = float(os.getenv("ARCHIVAR_SELF_CHECK_TIMEOUT", "30.0"))
|
||||
"""Gesamt-Timeout für den Self-Check in Sekunden (Feature 92, Default 30s)."""
|
||||
|
||||
SELF_CHECK_HTTP_TIMEOUT_S: float = 3.0
|
||||
"""HTTP-Timeout pro Einzel-Check in Sekunden (analog install.sh curl --max-time 3)."""
|
||||
|
||||
# ── Index-Pfad (identisch zu room_index.py `_DEFAULT_INDEX_DIR`) ─────────────
|
||||
# Bewusst hier neu abgeleitet statt `import room_index` — room_index importiert
|
||||
# numpy auf Modulebene, was bei kaputtem venv selbst fehlschlägt (genau das,
|
||||
# was der Check diagnostizieren soll).
|
||||
|
||||
_INDEX_DIR: str = os.path.expanduser(
|
||||
os.getenv("ARCHIVAR_INDEX_DIR", "~/.hermes/hermes-agent/data")
|
||||
)
|
||||
_INDEX_FILENAME: str = "room_index.faiss"
|
||||
_META_FILENAME: str = "room_index.meta"
|
||||
|
||||
|
||||
@dataclass
|
||||
class ComponentCheckResult:
|
||||
"""Ergebnis der 6-stufigen Self-Check-Diagnose.
|
||||
|
||||
Stufen 1-3 sind Fehler-Stufen, Stufen 4-5 Warmup-Stufen, Stufe 6
|
||||
(``ready``) ist abgeleitet.
|
||||
"""
|
||||
|
||||
faiss_importable: bool # Stufe 1
|
||||
index_loadable: bool # Stufe 2
|
||||
ollama_reachable: bool # Stufe 3
|
||||
llm_model_loaded: bool # Stufe 4
|
||||
embedding_ladbar: bool # Stufe 5
|
||||
ready: bool # Stufe 6 (abgeleitet)
|
||||
|
||||
@property
|
||||
def has_error(self) -> bool:
|
||||
"""True wenn eine der Fehler-Stufen (1-3) fehlgeschlagen ist."""
|
||||
return not (
|
||||
self.faiss_importable and self.index_loadable and self.ollama_reachable
|
||||
)
|
||||
|
||||
@property
|
||||
def needs_warmup(self) -> bool:
|
||||
"""True wenn keine Fehler-Stufe, aber eine Warmup-Stufe (4-5) fehlt."""
|
||||
return (not self.has_error) and not (
|
||||
self.llm_model_loaded and self.embedding_ladbar
|
||||
)
|
||||
|
||||
|
||||
# ── Einzel-Probes (module-level, damit Tests sie gezielt patchen können) ────
|
||||
|
||||
|
||||
def _probe_faiss_importable() -> bool:
|
||||
"""Stufe 1: Ist `faiss` importierbar?"""
|
||||
try:
|
||||
import faiss # noqa: F401
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.warning("[f92-self-check] Stufe 1: faiss nicht importierbar: %s", e)
|
||||
return False
|
||||
|
||||
|
||||
def _probe_index_loadable() -> bool:
|
||||
"""Stufe 2: Ist der FAISS-Index ladbar (Dateien + Meta + read_index)?
|
||||
|
||||
Prüft (a) ob beide Dateien existieren, (b) ob die Meta-Datei gültiges
|
||||
JSON mit nicht-leeren room_ids enthält, (c) — falls faiss verfügbar —
|
||||
ob ``faiss.read_index`` den Index tatsächlich liest. Fehlt faiss, fällt
|
||||
(c) weg; die Stufe zählt dann als OK, solange die Dateien konsistent
|
||||
vorliegen (der faiss-Import wird bereits von Stufe 1 gemeldet).
|
||||
"""
|
||||
index_path = Path(_INDEX_DIR) / _INDEX_FILENAME
|
||||
meta_path = Path(_INDEX_DIR) / _META_FILENAME
|
||||
|
||||
if not index_path.exists() or not meta_path.exists():
|
||||
logger.warning(
|
||||
"[f92-self-check] Stufe 2: Index-Dateien fehlen (%s / %s)",
|
||||
index_path, meta_path,
|
||||
)
|
||||
return False
|
||||
|
||||
try:
|
||||
with open(meta_path, "r", encoding="utf-8") as f:
|
||||
meta = json.load(f)
|
||||
except (json.JSONDecodeError, OSError) as e:
|
||||
logger.warning("[f92-self-check] Stufe 2: Meta nicht lesbar: %s", e)
|
||||
return False
|
||||
|
||||
if not meta.get("room_ids"):
|
||||
logger.warning("[f92-self-check] Stufe 2: Meta hat leere room_ids")
|
||||
return False
|
||||
|
||||
# (c) optional: echter Lese-Versuch, nur wenn faiss da ist.
|
||||
try:
|
||||
import faiss # noqa: F401
|
||||
faiss.read_index(str(index_path))
|
||||
except Exception:
|
||||
# faiss fehlt → bereits Stufe 1; oder read_index schlug fehl.
|
||||
pass
|
||||
|
||||
return True
|
||||
|
||||
|
||||
def _http_get_json(url: str, timeout: float) -> Optional[dict]:
|
||||
"""GET und JSON-Parse, None bei jedem Fehler (urllib, stdlib)."""
|
||||
try:
|
||||
req = urllib.request.Request(url, method="GET")
|
||||
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
||||
return json.loads(resp.read().decode("utf-8"))
|
||||
except (urllib.error.HTTPError, urllib.error.URLError,
|
||||
json.JSONDecodeError, OSError, Exception) as e:
|
||||
logger.warning("[f92-self-check] GET %s fehlgeschlagen: %s", url, e)
|
||||
return None
|
||||
|
||||
|
||||
def _probe_ollama_reachable(base_url: str, timeout: float) -> bool:
|
||||
"""Stufe 3: Ist Ollama erreichbar (GET /api/tags)?"""
|
||||
return _http_get_json(f"{base_url}/api/tags", timeout) is not None
|
||||
|
||||
|
||||
def _probe_models(base_url: str, timeout: float) -> List[str]:
|
||||
"""Liefert die Liste der in Ollama geladenen/verfügbaren Modellnamen.
|
||||
|
||||
Leere Liste bei nicht erreichbarem Ollama oder Parse-Fehler.
|
||||
"""
|
||||
data = _http_get_json(f"{base_url}/api/tags", timeout)
|
||||
if not data:
|
||||
return []
|
||||
try:
|
||||
return [m.get("name", "") for m in data.get("models", [])]
|
||||
except (AttributeError, TypeError):
|
||||
return []
|
||||
|
||||
|
||||
def _probe_embedding(base_url: str, model: str, timeout: float) -> bool:
|
||||
"""Stufe 5: Liefert das Embedding-Modell tatsächlich einen Vektor?"""
|
||||
url = f"{base_url}/api/embeddings"
|
||||
payload = json.dumps({"model": model, "prompt": "self-check"}).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=timeout) as resp:
|
||||
data = json.loads(resp.read().decode("utf-8"))
|
||||
emb = data.get("embedding")
|
||||
return isinstance(emb, list) and len(emb) > 0
|
||||
except (urllib.error.HTTPError, urllib.error.URLError,
|
||||
json.JSONDecodeError, OSError, Exception) as e:
|
||||
logger.warning("[f92-self-check] Embedding-Check fehlgeschlagen: %s", e)
|
||||
return False
|
||||
|
||||
|
||||
# ── check_components(): die gemeinsame Diagnose-Funktion ────────────────────
|
||||
|
||||
|
||||
def check_components() -> ComponentCheckResult:
|
||||
"""Führt die 6-stufige Self-Check-Diagnose aus.
|
||||
|
||||
Analog zu install.sh `check_components()`: gleiche Komponenten, gleiche
|
||||
Reihenfolge. Blockierend (HTTP-Calls) — der Adapter ruft diese Funktion
|
||||
deshalb via ``asyncio.to_thread`` + ``wait_for(30s)`` auf, damit der
|
||||
Gateway-Start nicht blockiert wird.
|
||||
|
||||
Returns:
|
||||
ComponentCheckResult mit den Ergebnissen aller 6 Stufen.
|
||||
"""
|
||||
base_url = OLLAMA_CONFIG["base_url"].rstrip("/")
|
||||
llm_model = LLM_CONFIG["model"]
|
||||
emb_model = OLLAMA_CONFIG["model"]
|
||||
timeout = SELF_CHECK_HTTP_TIMEOUT_S
|
||||
|
||||
faiss_ok = _probe_faiss_importable() # Stufe 1
|
||||
index_ok = _probe_index_loadable() # Stufe 2
|
||||
ollama_ok = _probe_ollama_reachable(base_url, timeout) # Stufe 3
|
||||
|
||||
if ollama_ok:
|
||||
models = _probe_models(base_url, timeout)
|
||||
llm_loaded = llm_model in models # Stufe 4
|
||||
embedding_ok = _probe_embedding(base_url, emb_model, timeout) # Stufe 5
|
||||
else:
|
||||
# Ollama down → Stufen 4/5 sind nicht sinnvoll prüfbar.
|
||||
llm_loaded = False
|
||||
embedding_ok = False
|
||||
|
||||
ready = faiss_ok and index_ok and ollama_ok and llm_loaded and embedding_ok # Stufe 6
|
||||
|
||||
return ComponentCheckResult(
|
||||
faiss_importable=faiss_ok,
|
||||
index_loadable=index_ok,
|
||||
ollama_reachable=ollama_ok,
|
||||
llm_model_loaded=llm_loaded,
|
||||
embedding_ladbar=embedding_ok,
|
||||
ready=ready,
|
||||
)
|
||||
|
||||
|
||||
# ── User-Meldungen (Feature 92 / install-repair-konzept.md §4) ──────────────
|
||||
|
||||
_ERROR_MESSAGE = (
|
||||
"⚠️ Ich kann gerade keine thematische Zuordnung machen — eine Komponente "
|
||||
"ist nicht vollständig installiert (Raumerkennung).\n\n"
|
||||
"Das ist kein Problem mit deiner Konfiguration. Ich kann das selbst "
|
||||
"reparieren.\n\n"
|
||||
"Reparatur: Führe auf dem Server aus:\n"
|
||||
" ./install.sh --repair\n\n"
|
||||
"Das stellt alle fehlenden Komponenten automatisch wieder her. Danach "
|
||||
"starte ich neu und die Raumerkennung funktioniert wieder."
|
||||
)
|
||||
|
||||
_WARMUP_MESSAGE = (
|
||||
"⏳ Ich lade gerade meine Modelle (Routing + Embedding). Das dauert beim "
|
||||
"ersten Mal einen Moment — danach läuft die thematische Zuordnung "
|
||||
"automatisch."
|
||||
)
|
||||
|
||||
|
||||
def build_report_message(result: ComponentCheckResult) -> Optional[str]:
|
||||
"""Baut die User-Meldung zum Check-Ergebnis.
|
||||
|
||||
Returns:
|
||||
None wenn alles OK (Stufe 6, silent). Sonst die Fehler- (Stufe 1-3)
|
||||
oder Warmup-Meldung (Stufe 4-5).
|
||||
"""
|
||||
if result.ready:
|
||||
return None
|
||||
if result.has_error:
|
||||
return _ERROR_MESSAGE
|
||||
if result.needs_warmup:
|
||||
return _WARMUP_MESSAGE
|
||||
return None
|
||||
Reference in New Issue
Block a user