Compare commits
26 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 9798a3e8a0 | |||
| 6edf167fd0 | |||
| 766aa7ece6 | |||
| 3aa1c5ac7f | |||
| a3758954f8 | |||
| 209daf87bc | |||
| 230edb9fdb | |||
| 39999b38ae | |||
| 8db5d795c5 | |||
| 4dae58c813 | |||
| 25cfc66c78 | |||
| 02200b2bcf | |||
| ab7291edf1 | |||
| 6066ef6160 | |||
| db89212549 | |||
| 7ec5ca0c2c | |||
| 6449af02e7 | |||
| 702941ea01 | |||
| a4a50e8aa2 | |||
| abe2657727 | |||
| 12314cffd9 | |||
| 11bf55994e | |||
| 19d2301eb9 | |||
| b8f4628a1a | |||
| 0c1c1b42a2 | |||
| 3d7482a13b |
@@ -1,9 +1,9 @@
|
|||||||
# Projekt-STATUS — Hermes Rocket.Chat Plugin
|
# Projekt-STATUS — Hermes Rocket.Chat Plugin
|
||||||
> **Stand:** 31. August 2026 — F93 Adaptiver LLM-Timeout implementiert (selbstkalibrierend, Welford + Toleranzband, ersetzt starre 30s)
|
> **Stand:** 1. September 2026 (06:30) — Merge `fix/reasoning-glm53-none-mapping` nach main (F93 Adaptiver LLM-Timeout, QG-freigegeben Rainer Round 2, PUSH-FREIGABE t_25f5aff0). F93-Commits: `8b106f5` (feat: selbstkalibrierend Welford + Toleranzband), `656fe38` (docs), `daa1d05` (fix: QG Round-1 — 3 Push-Blocker F6a/F6b/F4). Zuvor (31.08. 20:45): `02200b2` (fix(install): F98 Auto-Update-Check in bootstrap_repo() — bei JEDEM Lauf auf neuere Gitea-Version prüfen; Andreas-Direktive 31.08.). Vorher (18:35): `7ec5ca0` (fix: F98-Wizard-Review Round 2). Vorher (18:00): F98-Guided-Setup-Wizard `12314cf` + `a4a50e8`. Davor: `b8f4628` (WV-002), `cc41c46` (Fix C/P-168), `19d2301` (Merge nach main).
|
||||||
> **Letzter Commit:** `8b106f5` — feat(F93): Adaptiver LLM-Timeout — selbstkalibrierend (Welford + Toleranzband)
|
> **Letzter fachlicher Commit:** `daa1d05` — fix(F93): QG Round-1 — 3 Push-Blocker behoben (F6a Parse-Fehler→success=False, F6b Dead-Code self._timeout entfernt, F4 negative-n-Sanitizer)
|
||||||
> **Gitea-Remote:** ⏳ Lokal voraus — `8b106f5` noch nicht gepusht (KEIN Push vor Rainer-QG, P-078)
|
> **Gitea-Remote:** ⏳ Lokal voraus — Merge-Commit + `02200b2`/`7ec5ca0` (F98) noch nicht gepusht; Push nach main folgt in diesem Deploy-Lauf
|
||||||
> **Deployment:** ⏳ Ausstehend — F93 (`8b106f5`) + `3ad0c55` (adapter.py) + `7a8d0c5`/`1aa028b` (install.sh) + `6def904` (archivar/presence_engine.py — braucht Gateway-Restart) noch nicht auf .101 deployt. Deployment via `install.sh --update-only --no-restart` (P-115). KEIN Gateway-Restart — Bernd macht den Restart per Preflight-Briefing (P-111).
|
> **Deployment:** ⏳ Ausstehend — F93 (`adaptive_timeout.py` + `classifier.py`) + `3ad0c55` (adapter.py) + `7a8d0c5`/`1aa028b` (install.sh) + `6def904`/`b8f4628` (archivar/presence_engine.py, braucht Gateway-Restart) + `cc41c46` (adapter.py, Fix C/P-168) noch nicht auf .101 deployt. Deployment via `install.sh --update-only --no-restart` (P-115). KEIN Gateway-Restart — Bernd macht den Restart per Preflight-Briefing (P-111).
|
||||||
> **Uncommitted:** `_apply_patches.py` + `plugin/archivar/presence_engine.py.bak` (untracked, nicht Teil von F93)
|
> **Uncommitted:** Keine (nach diesem Merge-Commit)
|
||||||
> **Deployment-Pfad:** `~/.hermes/plugins/platforms/rocketchat/`
|
> **Deployment-Pfad:** `~/.hermes/plugins/platforms/rocketchat/`
|
||||||
> **Dev-Repo-Pfad:** `~/projekte/Hermes_rocket.chat_Plugin/plugin/`
|
> **Dev-Repo-Pfad:** `~/projekte/Hermes_rocket.chat_Plugin/plugin/`
|
||||||
|
|
||||||
@@ -27,12 +27,22 @@
|
|||||||
|
|
||||||
| Commit | Beschreibung | Datum |
|
| Commit | Beschreibung | Datum |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
|
| `daa1d05` | fix(F93): QG Round-1 — 3 Push-Blocker behoben (F6a Parse-Fehler→success=False, F6b Dead-Code self._timeout entfernt, F4 negative-n-Sanitizer) | 01.09. |
|
||||||
|
| `656fe38` | docs: STATUS.md — F93 Adaptiver LLM-Timeout dokumentiert (8b106f5) | 31.08. |
|
||||||
| `8b106f5` | feat(F93): Adaptiver LLM-Timeout — selbstkalibrierend (Welford + Toleranzband, ersetzt starre 30s; 24 A1c-Tests) | 31.08. |
|
| `8b106f5` | feat(F93): Adaptiver LLM-Timeout — selbstkalibrierend (Welford + Toleranzband, ersetzt starre 30s; 24 A1c-Tests) | 31.08. |
|
||||||
|
| `6066ef6` | feat(F-119): MAIL_DETAIL-Button-Handler + Thread-Reply (tmid) — Proton-Mail-Ergebnis-Karte | 31.08. |
|
||||||
|
| `19d2301` | merge: Fix C (::reasoning Wire-Wert + Probe-Warnung, P-168) nach main | 31.08. |
|
||||||
|
| `cc41c46` | fix(reasoning): ::reasoning status zeigt Wire-Wert + Probe-Warnung (Fix C, P-168; adapter.py + Tests, Branch fix/reasoning-glm53-none-mapping) | 31.08. |
|
||||||
|
| `b8f4628` | fix(presence): WV-002 REST-Exception-Logging verfeinern (_rest_set_status; +319/−18, 218-Z.-Test) (QG Rainer APPROVED) | 31.08. |
|
||||||
|
| `3d7482a` | docs: STATUS.md — Verifikations-Heartbeat 30.08. (P-164-Rollover quittiert) + Docs-Commits 0f8dc6d/562cf11/5a6de60 ergänzt, 29.08.-Reihenfolge korrigiert | 30.08. |
|
||||||
|
| `5a6de60` | docs: STATUS.md — Status-Text-Fix (6def904) + F97-Design-Doku (12b73d3) dokumentiert | 29.08. |
|
||||||
| `12b73d3` | docs: F97 Design-Analyse Kanban-Worker-Presence (Rainer, 40 KB — Basis für F97-Implementierung nach Andreas-Freigabe) | 29.08. |
|
| `12b73d3` | docs: F97 Design-Analyse Kanban-Worker-Presence (Rainer, 40 KB — Basis für F97-Implementierung nach Andreas-Freigabe) | 29.08. |
|
||||||
| `6def904` | fix(presence): GREEN-Phasen sagen 'Hauptagent verfuegbar' statt 'beschaeftigt' (Andreas-Fund 16:14, Rainer-QG APPROVED, 6 Unit-Tests) | 29.08. |
|
| `6def904` | fix(presence): GREEN-Phasen sagen 'Hauptagent verfuegbar' statt 'beschaeftigt' (Andreas-Fund 16:14, Rainer-QG APPROVED, 6 Unit-Tests) | 29.08. |
|
||||||
|
| `562cf11` | docs: STATUS.md — install.sh-Härtungen dokumentiert (P-146/1aa028b-Kopf, 7a8d0c5+1aa028b-Tabelle) | 29.08. |
|
||||||
|
| `1aa028b` | fix(install): P-147 HOME-Absicherung — Agent-Kontext-Guard (guard_home() warnt weich vor Fehl-Deploy ins Profil-Home, P-119-Klasse) | 29.08. |
|
||||||
|
| `0f8dc6d` | docs: STATUS.md — Raum-Routing-Fix dokumentiert (P-108c 3ad0c55 + P-143 7a8d0c5) | 29.08. |
|
||||||
| `3ad0c55` | fix(P-108c): Send-Pfad-Härtung — Antwort-Ziel MUSS Origin-Raum sein (P-145) | 29.08. |
|
| `3ad0c55` | fix(P-108c): Send-Pfad-Härtung — Antwort-Ziel MUSS Origin-Raum sein (P-145) | 29.08. |
|
||||||
| `7a8d0c5` | fix(install): P-143 Toolset-Registrierung nach platform_toolsets.rocketchat statt legacy top-level toolsets | 29.08. |
|
| `7a8d0c5` | fix(install): P-143 Toolset-Registrierung nach platform_toolsets.rocketchat statt legacy top-level toolsets | 29.08. |
|
||||||
| `1aa028b` | fix(install): P-147 HOME-Absicherung — Agent-Kontext-Guard (guard_home() warnt weich vor Fehl-Deploy ins Profil-Home, P-119-Klasse) | 29.08. |
|
|
||||||
| `9746f34` | docs: STATUS.md inhaltlich wiederhergestellt aus 275f067, ergänzt um 22 Commits (26.08.-27.08., inkl. 30681e1+677fdec) | 28.08. |
|
| `9746f34` | docs: STATUS.md inhaltlich wiederhergestellt aus 275f067, ergänzt um 22 Commits (26.08.-27.08., inkl. 30681e1+677fdec) | 28.08. |
|
||||||
| `677fdec` | docs: Rainer-Architekturanalysen hinzugefügt (Butler-Lernkonzept V1+V2, P-108 Szenario B) | 27.08. |
|
| `677fdec` | docs: Rainer-Architekturanalysen hinzugefügt (Butler-Lernkonzept V1+V2, P-108 Szenario B) | 27.08. |
|
||||||
| `30681e1` | fix(install): P-116 Stale-Check um Timestamp ergänzt | 27.08. |
|
| `30681e1` | fix(install): P-116 Stale-Check um Timestamp ergänzt | 27.08. |
|
||||||
|
|||||||
+1568
-134
File diff suppressed because it is too large
Load Diff
+239
-3
@@ -29,7 +29,7 @@ import urllib.parse
|
|||||||
import urllib.request
|
import urllib.request
|
||||||
import urllib.error
|
import urllib.error
|
||||||
import uuid
|
import uuid
|
||||||
from typing import Any, Dict, List, Optional
|
from typing import Any, Callable, Dict, List, Optional
|
||||||
|
|
||||||
|
|
||||||
class RocketChatRateLimitError(Exception):
|
class RocketChatRateLimitError(Exception):
|
||||||
@@ -423,10 +423,27 @@ def _sanitize_file_path_component(value: str) -> str:
|
|||||||
|
|
||||||
|
|
||||||
class RocketChatREST:
|
class RocketChatREST:
|
||||||
|
# P-171: Re-Auth-Throttle — verhindert einen Re-Login-Sturm, wenn viele
|
||||||
|
# REST-Calls (z.B. 211× users.setStatus) gleichzeitig auf einen abgelaufenen
|
||||||
|
# Token treffen. Nur der erste 401 innerhalb des Fensters triggert einen
|
||||||
|
# Re-Login; die übrigen Calls loggen und returnen None (der nächste Puls
|
||||||
|
# mit frischem Token greift dann).
|
||||||
|
_REAUTH_THROTTLE_SECONDS = 30.0
|
||||||
|
|
||||||
def __init__(self, base_url: str):
|
def __init__(self, base_url: str):
|
||||||
self.base_url = base_url.rstrip("/")
|
self.base_url = base_url.rstrip("/")
|
||||||
self.auth_token: Optional[str] = None
|
self.auth_token: Optional[str] = None
|
||||||
self.user_id: Optional[str] = None
|
self.user_id: Optional[str] = None
|
||||||
|
# Re-Auth-Callback (vom Adapter verdrahtet): liefert True bei Erfolg.
|
||||||
|
self._reauth_callback: Optional[Callable[[], bool]] = None
|
||||||
|
# RLock (nicht Lock): der Retry nach Re-Auth ruft _request() rekursiv
|
||||||
|
# auf, das bei erneutem 401 denselben Lock re-akquiriert (P-104-Klasse).
|
||||||
|
self._reauth_lock = threading.RLock()
|
||||||
|
self._last_reauth_ts = 0.0
|
||||||
|
|
||||||
|
def set_reauth_callback(self, callback: "Callable[[], bool]") -> None:
|
||||||
|
"""Verdrahtet den Re-Auth-Callback (Adapter-seitig, kennt user/password)."""
|
||||||
|
self._reauth_callback = callback
|
||||||
|
|
||||||
def _request(self, method: str, endpoint: str, headers: Optional[dict] = None, data: Optional[dict] = None):
|
def _request(self, method: str, endpoint: str, headers: Optional[dict] = None, data: Optional[dict] = None):
|
||||||
url = f"{self.base_url}{endpoint}"
|
url = f"{self.base_url}{endpoint}"
|
||||||
@@ -443,6 +460,27 @@ class RocketChatREST:
|
|||||||
raise RocketChatRateLimitError(
|
raise RocketChatRateLimitError(
|
||||||
f"HTTP 429 on {method} {endpoint}"
|
f"HTTP 429 on {method} {endpoint}"
|
||||||
) from e
|
) from e
|
||||||
|
# P-171: HTTP 401 = Token abgelaufen → Re-Auth + EIN Retry.
|
||||||
|
# Vorher war 401 ein stiller Antwort-Verlust (post_message → None →
|
||||||
|
# SendResult(success=False)). Jetzt wird der Token erneuert und der
|
||||||
|
# SAME Request mit frischem Token wiederholt.
|
||||||
|
if e.code == 401 and self._reauth_callback is not None:
|
||||||
|
with self._reauth_lock:
|
||||||
|
now = time.time()
|
||||||
|
if now - self._last_reauth_ts > self._REAUTH_THROTTLE_SECONDS:
|
||||||
|
self._last_reauth_ts = now
|
||||||
|
try:
|
||||||
|
if self._reauth_callback():
|
||||||
|
# Headers mit FRISCHEM Token neu bauen — die
|
||||||
|
# übergebenen headers tragen noch den alten.
|
||||||
|
_retry_headers = dict(headers) if headers else {}
|
||||||
|
if self.auth_token:
|
||||||
|
_retry_headers["X-Auth-Token"] = self.auth_token
|
||||||
|
if self.user_id:
|
||||||
|
_retry_headers["X-User-Id"] = self.user_id
|
||||||
|
return self._request(method, endpoint, _retry_headers, data)
|
||||||
|
except Exception as _reauth_err:
|
||||||
|
logger.warning("REST re-auth failed: %s", _reauth_err)
|
||||||
# P2-Fix: HTTP 4xx als warning, 5xx als error (vorher nur debug)
|
# P2-Fix: HTTP 4xx als warning, 5xx als error (vorher nur debug)
|
||||||
if 400 <= e.code < 500:
|
if 400 <= e.code < 500:
|
||||||
logger.warning("REST %s %s HTTP %d: %s", method, endpoint, e.code, e)
|
logger.warning("REST %s %s HTTP %d: %s", method, endpoint, e.code, e)
|
||||||
@@ -507,9 +545,17 @@ class RocketChatREST:
|
|||||||
return None
|
return None
|
||||||
return r.get("members", [])
|
return r.get("members", [])
|
||||||
|
|
||||||
def post_message(self, room_id: str, text: str, attachments: Optional[List[dict]] = None) -> Optional[str]:
|
def post_message(self, room_id: str, text: str, attachments: Optional[List[dict]] = None, tmid: Optional[str] = None) -> Optional[str]:
|
||||||
"""Post a message via REST API POST /api/v1/chat.postMessage.
|
"""Post a message via REST API POST /api/v1/chat.postMessage.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
room_id: Target room.
|
||||||
|
text: Message text.
|
||||||
|
attachments: Optional Rocket.Chat attachments (buttons).
|
||||||
|
tmid: Optional parent message id → post as a thread reply under
|
||||||
|
that message (F-119: mail details hang as a thread under the
|
||||||
|
result card).
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
The message ``_id`` from the API response on success, ``None`` on failure.
|
The message ``_id`` from the API response on success, ``None`` on failure.
|
||||||
V8.3.1 F1: Return message_id for target_message_id tracking.
|
V8.3.1 F1: Return message_id for target_message_id tracking.
|
||||||
@@ -519,6 +565,8 @@ class RocketChatREST:
|
|||||||
payload = {"roomId": room_id, "text": text}
|
payload = {"roomId": room_id, "text": text}
|
||||||
if attachments:
|
if attachments:
|
||||||
payload["attachments"] = attachments
|
payload["attachments"] = attachments
|
||||||
|
if tmid:
|
||||||
|
payload["tmid"] = tmid
|
||||||
r = self._request("POST", "/api/v1/chat.postMessage", headers={
|
r = self._request("POST", "/api/v1/chat.postMessage", headers={
|
||||||
"X-Auth-Token": self.auth_token,
|
"X-Auth-Token": self.auth_token,
|
||||||
"X-User-Id": self.user_id,
|
"X-User-Id": self.user_id,
|
||||||
@@ -1319,6 +1367,11 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
self.user = _get_config_str(config, "user", "ROCKETCHAT_USER")
|
self.user = _get_config_str(config, "user", "ROCKETCHAT_USER")
|
||||||
self.password = _get_config_str(config, "password", "ROCKETCHAT_PASSWORD")
|
self.password = _get_config_str(config, "password", "ROCKETCHAT_PASSWORD")
|
||||||
self.rest = RocketChatREST(self.base_url)
|
self.rest = RocketChatREST(self.base_url)
|
||||||
|
# P-171: Re-Auth-Callback verdrahten — bei HTTP 401 (Token abgelaufen)
|
||||||
|
# erneuert der REST-Client den Token über diesen Callback und retried
|
||||||
|
# den Request. Ohne dies war ein abgelaufener Token ein stiller
|
||||||
|
# Antwort-Verlust (post_message → None → SendResult(success=False)).
|
||||||
|
self.rest.set_reauth_callback(self._reauth_rest)
|
||||||
self.ddp: Optional[DDPClient] = None
|
self.ddp: Optional[DDPClient] = None
|
||||||
self._auth_token: Optional[str] = None
|
self._auth_token: Optional[str] = None
|
||||||
self._user_id: Optional[str] = None
|
self._user_id: Optional[str] = None
|
||||||
@@ -1585,6 +1638,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
self, room_id: str, text: str,
|
self, room_id: str, text: str,
|
||||||
attachments: Optional[List[dict]] = None,
|
attachments: Optional[List[dict]] = None,
|
||||||
max_retries: int = 3,
|
max_retries: int = 3,
|
||||||
|
tmid: Optional[str] = None,
|
||||||
) -> Optional[str]:
|
) -> Optional[str]:
|
||||||
"""Send chat.postMessage with exponential backoff on HTTP 429.
|
"""Send chat.postMessage with exponential backoff on HTTP 429.
|
||||||
|
|
||||||
@@ -1601,7 +1655,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
delays = [2, 4, 8]
|
delays = [2, 4, 8]
|
||||||
for attempt in range(max_retries + 1):
|
for attempt in range(max_retries + 1):
|
||||||
try:
|
try:
|
||||||
return self.rest.post_message(room_id, text, attachments=attachments)
|
return self.rest.post_message(room_id, text, attachments=attachments, tmid=tmid)
|
||||||
except RocketChatRateLimitError:
|
except RocketChatRateLimitError:
|
||||||
if attempt < max_retries:
|
if attempt < max_retries:
|
||||||
delay = delays[min(attempt, len(delays) - 1)]
|
delay = delays[min(attempt, len(delays) - 1)]
|
||||||
@@ -1621,6 +1675,32 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
return None
|
return None
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _load_mail_details(mail_hash_value: str) -> Optional[dict]:
|
||||||
|
"""@implements F-119 — liest den Details-Record einer Proton-Mail.
|
||||||
|
|
||||||
|
Der Proton-Mail-Trigger persistiert die Details unter
|
||||||
|
``<real_home>/.config/hermes/proton/details/<hash>.json``. Dieser
|
||||||
|
Handler liest dieselbe Datei (deterministischer Pfad, keine
|
||||||
|
Cross-Plugin-Import-Kopplung). ``HERMES_REAL_HOME`` hat Vorrang vor
|
||||||
|
``expanduser("~")`` (P-119: der Gateway läuft mit Profil-HOME).
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Das Record-Dict oder ``None`` wenn nicht vorhanden/unlesbar.
|
||||||
|
"""
|
||||||
|
import json as _json
|
||||||
|
real_home = os.getenv("HERMES_REAL_HOME") or os.path.expanduser("~")
|
||||||
|
path = os.path.join(
|
||||||
|
real_home, ".config", "hermes", "proton", "details",
|
||||||
|
f"{mail_hash_value}.json",
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
with open(path, "r", encoding="utf-8") as fh:
|
||||||
|
data = _json.load(fh)
|
||||||
|
except (OSError, ValueError):
|
||||||
|
return None
|
||||||
|
return data if isinstance(data, dict) else None
|
||||||
|
|
||||||
def _sync_room_map_with_membership(self) -> None:
|
def _sync_room_map_with_membership(self) -> None:
|
||||||
"""M13: Garbage-Collect room-map.json + FAISS + Booster + State gegen tatsächliche Mitgliedschaft.
|
"""M13: Garbage-Collect room-map.json + FAISS + Booster + State gegen tatsächliche Mitgliedschaft.
|
||||||
|
|
||||||
@@ -2202,6 +2282,12 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
# übersprungen (kein Archivar → keine Raumerkennung).
|
# übersprungen (kein Archivar → keine Raumerkennung).
|
||||||
self._start_self_check()
|
self._start_self_check()
|
||||||
|
|
||||||
|
# ── F100: Runtime-Watchdog als Background-Task ────────────────────
|
||||||
|
# Zweite Verteidigungslinie (K1): misst die echte Router-Pipeline über
|
||||||
|
# record_attempt() nach jedem Live-Call. Läuft NACH dem Self-Check
|
||||||
|
# (Start-Diagnose zuerst, Runtime-Überwachung danach). NICHT blockierend.
|
||||||
|
self._start_routing_watchdog()
|
||||||
|
|
||||||
return True
|
return True
|
||||||
|
|
||||||
# ── Feature 92: Self-Check ────────────────────────────────────────────
|
# ── Feature 92: Self-Check ────────────────────────────────────────────
|
||||||
@@ -2284,6 +2370,82 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
return room_id
|
return room_id
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
# ── F100: Runtime-Watchdog (Routing-Erfolgsquote) ─────────────────────
|
||||||
|
|
||||||
|
def _start_routing_watchdog(self) -> None:
|
||||||
|
"""Startet den Runtime-Watchdog als Background-Task (nicht blockierend).
|
||||||
|
|
||||||
|
Zweite Verteidigungslinie (K1): misst die echte Router-Pipeline über
|
||||||
|
``routing_counter.record_attempt()`` nach jedem Live-Call. Der Watchdog
|
||||||
|
prüft periodisch die Erfolgsquote und loggt bei Unterschreitung der
|
||||||
|
Schwelle einen ERROR-Alert (KEIN RC-Post, P-088-Lehre) — mit 24h-
|
||||||
|
Cooldown + persistentem Flag (K3).
|
||||||
|
"""
|
||||||
|
if not _MULTIROOM() or self.archivar is None:
|
||||||
|
logger.info("[rocketchat] F100: MULTIROOM_AGENT=false — Watchdog übersprungen")
|
||||||
|
return
|
||||||
|
|
||||||
|
try:
|
||||||
|
asyncio.ensure_future(self._run_routing_watchdog())
|
||||||
|
logger.info("[rocketchat] F100: Runtime-Watchdog als Background-Task gestartet")
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning("[rocketchat] F100: Watchdog-Start fehlgeschlagen: %s", e)
|
||||||
|
|
||||||
|
async def _run_routing_watchdog(self) -> None:
|
||||||
|
"""Watchdog-Schleife: prüft periodisch die Routing-Erfolgsquote.
|
||||||
|
|
||||||
|
Bei jedem Tick: ``success_ratio(window_s, min_samples)``. Wenn die
|
||||||
|
Quote unter der Schwelle liegt UND der Cooldown nicht aktiv ist →
|
||||||
|
ERROR-Alert loggen + Cooldown-Flag setzen. Bei < min_samples gibt
|
||||||
|
``success_ratio()`` None zurück → kein Trigger (K2).
|
||||||
|
"""
|
||||||
|
import asyncio
|
||||||
|
from archivar.routing_counter import routing_counter
|
||||||
|
from archivar.watchdog_alert import watchdog_alert_cooldown
|
||||||
|
from archivar.config import (
|
||||||
|
LLM_ROOM_WATCHDOG_WINDOW_S,
|
||||||
|
LLM_ROOM_WATCHDOG_THRESHOLD,
|
||||||
|
LLM_ROOM_WATCHDOG_INTERVAL_S,
|
||||||
|
LLM_ROOM_WATCHDOG_MIN_SAMPLES,
|
||||||
|
)
|
||||||
|
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
await asyncio.sleep(LLM_ROOM_WATCHDOG_INTERVAL_S)
|
||||||
|
except asyncio.CancelledError:
|
||||||
|
logger.info("[rocketchat] F100: Watchdog-Schleife beendet")
|
||||||
|
return
|
||||||
|
|
||||||
|
try:
|
||||||
|
ratio = routing_counter.success_ratio(
|
||||||
|
window_s=LLM_ROOM_WATCHDOG_WINDOW_S,
|
||||||
|
min_samples=LLM_ROOM_WATCHDOG_MIN_SAMPLES,
|
||||||
|
)
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning("[rocketchat] F100: success_ratio fehlgeschlagen: %s", e)
|
||||||
|
continue
|
||||||
|
|
||||||
|
if ratio is None:
|
||||||
|
# < min_samples → kein Trigger (K2).
|
||||||
|
continue
|
||||||
|
|
||||||
|
if ratio < LLM_ROOM_WATCHDOG_THRESHOLD:
|
||||||
|
if watchdog_alert_cooldown.is_in_cooldown():
|
||||||
|
logger.info(
|
||||||
|
"[rocketchat] F100: Watchdog-Alert unterdrückt (Cooldown aktiv, ratio=%.1f%%)",
|
||||||
|
ratio * 100,
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
|
||||||
|
n = routing_counter.attempt_count(LLM_ROOM_WATCHDOG_WINDOW_S)
|
||||||
|
logger.error(
|
||||||
|
"RUNTIME-WATCHDOG: Routing-Erfolgsquote %.1f%% (%d Samples / %ds) "
|
||||||
|
"unter Schwelle %.0f%%",
|
||||||
|
ratio * 100, n, LLM_ROOM_WATCHDOG_WINDOW_S,
|
||||||
|
LLM_ROOM_WATCHDOG_THRESHOLD * 100,
|
||||||
|
)
|
||||||
|
watchdog_alert_cooldown.mark_alerted()
|
||||||
|
|
||||||
def _reset_initial_message_and_presence(self) -> None:
|
def _reset_initial_message_and_presence(self) -> None:
|
||||||
"""STETS-GELB Fix 1 + Fix 2: Initial-Reset + Presence-Online nach Connect.
|
"""STETS-GELB Fix 1 + Fix 2: Initial-Reset + Presence-Online nach Connect.
|
||||||
|
|
||||||
@@ -2603,6 +2765,38 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
return True
|
return True
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
def _reauth_rest(self) -> bool:
|
||||||
|
"""P-171: REST-Token erneuern (Re-Login) nach HTTP 401.
|
||||||
|
|
||||||
|
Wird vom RocketChatREST._request() bei einem 401 aufgerufen. Führt
|
||||||
|
einen vollständigen REST-Login mit den gespeicherten Credentials aus
|
||||||
|
und aktualisiert auth_token/user_id auf dem REST-Client UND dem
|
||||||
|
Adapter (_auth_token/_user_id). Der DDP-Stream bleibt unangetastet —
|
||||||
|
er lebt über den Resume-Token weiter und ist von einem REST-Token-
|
||||||
|
Ablauf nicht betroffen.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
True bei erfolgreichem Re-Login, False sonst.
|
||||||
|
"""
|
||||||
|
if not self.user or not self.password:
|
||||||
|
logger.warning("[rocketchat] P-171: Re-Auth ohne Credentials — skip")
|
||||||
|
return False
|
||||||
|
try:
|
||||||
|
if not self.rest.login(self.user, self.password):
|
||||||
|
logger.error("[rocketchat] P-171: REST re-login failed")
|
||||||
|
return False
|
||||||
|
self._auth_token = self.rest.auth_token
|
||||||
|
self._user_id = self.rest.user_id
|
||||||
|
logger.info(
|
||||||
|
"[rocketchat] P-171: REST-Token erneuert (Re-Login nach 401) — "
|
||||||
|
"auth_token=%s, user_id=%s",
|
||||||
|
bool(self.rest.auth_token), bool(self.rest.user_id),
|
||||||
|
)
|
||||||
|
return True
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning("[rocketchat] P-171: Re-Auth exception: %s", e)
|
||||||
|
return False
|
||||||
|
|
||||||
async def _reconnect_ddp(self) -> bool:
|
async def _reconnect_ddp(self) -> bool:
|
||||||
"""Bug 7: DDP-Reconnect mit M13 GC.
|
"""Bug 7: DDP-Reconnect mit M13 GC.
|
||||||
|
|
||||||
@@ -3128,6 +3322,48 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
return
|
return
|
||||||
# ── Ende CLARIFY Plain-Digit Text Intercept ─────────────────────
|
# ── Ende CLARIFY Plain-Digit Text Intercept ─────────────────────
|
||||||
|
|
||||||
|
# ── F-119: MAIL_DETAIL Button-Klick (Proton-Mail-Ergebnis-Karte) ──
|
||||||
|
# Der Proton-Mail-Trigger postet eine Ergebnis-Karte mit einem
|
||||||
|
# "Details abrufen"-Button (Payload ``MAIL_DETAIL:<hash>::Details abrufen``).
|
||||||
|
# Der Klick liest den Details-Record aus
|
||||||
|
# <real_home>/.config/hermes/proton/details/<hash>.json und postet die
|
||||||
|
# Details als Thread-Antwort unter der Karte (tmid = card_message_id).
|
||||||
|
# Andreas-Korrektur 31.08.: Thread bleibt Teil der Lösung — Details
|
||||||
|
# hängen visuell an der Karte, der Hauptkanal bleibt flach.
|
||||||
|
if text.startswith("MAIL_DETAIL:"):
|
||||||
|
routing_counter.increment('mail_detail_bypass')
|
||||||
|
logger.info("ROUTING BYPASS: reason=mail_detail_bypass, origin_room=%s", room_id)
|
||||||
|
try:
|
||||||
|
# Payload: MAIL_DETAIL:<hash>::Details abrufen
|
||||||
|
_md_body = text.split("::", 1)[0] # MAIL_DETAIL:<hash>
|
||||||
|
_md_hash = _md_body.split(":", 1)[1].strip()
|
||||||
|
_md_record = self._load_mail_details(_md_hash)
|
||||||
|
if _md_record:
|
||||||
|
_md_text = _md_record.get("details", "") or "Keine Details verfügbar."
|
||||||
|
_md_subject = _md_record.get("subject", "")
|
||||||
|
_md_sender = _md_record.get("sender", "")
|
||||||
|
_md_lines = []
|
||||||
|
if _md_subject:
|
||||||
|
_md_lines.append(f"📧 **{_md_subject}**")
|
||||||
|
if _md_sender:
|
||||||
|
_md_lines.append(f"Von: {_md_sender}")
|
||||||
|
if _md_lines:
|
||||||
|
_md_lines.append("")
|
||||||
|
_md_lines.append(_md_text)
|
||||||
|
_md_tmid = _md_record.get("card_message_id", "") or None
|
||||||
|
await self._post_message_with_retry(
|
||||||
|
room_id, "\n".join(_md_lines), tmid=_md_tmid
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
await self._post_message_with_retry(
|
||||||
|
room_id, "Keine Details verfügbar."
|
||||||
|
)
|
||||||
|
except Exception as _md_exc:
|
||||||
|
logger.warning("[rocketchat] MAIL_DETAIL handler failed: %s", _md_exc)
|
||||||
|
self._abort_early_seed_presence()
|
||||||
|
return
|
||||||
|
# ── Ende F-119 MAIL_DETAIL Button-Klick ─────────────────────────
|
||||||
|
|
||||||
# ── CLARIFY Response Handling ───────────────────────────────────
|
# ── CLARIFY Response Handling ───────────────────────────────────
|
||||||
# Handle CLARIFY button responses: CLARIFY:<clarify_id>:<choice> or CLARIFY:<clarify_id>:other
|
# Handle CLARIFY button responses: CLARIFY:<clarify_id>:<choice> or CLARIFY:<clarify_id>:other
|
||||||
# V8.2.1 A2: Handle ARCHIVAR_CLARIFY (Nachklärung) responses
|
# V8.2.1 A2: Handle ARCHIVAR_CLARIFY (Nachklärung) responses
|
||||||
|
|||||||
@@ -345,6 +345,47 @@ RED_FLAG_TIMEOUT: float = float(os.getenv(
|
|||||||
))
|
))
|
||||||
"""Timeout für Red-Flag-Agent-Entscheidung in Sekunden. Default: 30.0."""
|
"""Timeout für Red-Flag-Agent-Entscheidung in Sekunden. Default: 30.0."""
|
||||||
|
|
||||||
|
# ── F100: Runtime-Watchdog (Routing-Erfolgsquote) ───────────────────────────
|
||||||
|
# Zweite Verteidigungslinie (K1-Rollenverteilung): Stufe 4b ist der Start-
|
||||||
|
# Smoke-Test, der Watchdog misst die ECHTE Router-Pipeline über
|
||||||
|
# record_attempt() nach jedem Live-Call. Alle Konstanten mit Kalibrierungs-
|
||||||
|
# Hinweis — empirische Nach-Kalibrierung nach 7 Tagen Produktiv-Betrieb ist
|
||||||
|
# PFLICHT (WV-005-Muster).
|
||||||
|
|
||||||
|
LLM_ROOM_WATCHDOG_WINDOW_S: int = int(os.getenv(
|
||||||
|
"ARCHIVAR_WATCHDOG_WINDOW_S", "3600"
|
||||||
|
))
|
||||||
|
"""Watchdog-Fenster in Sekunden (Default 1h). Nur Attempts innerhalb dieses
|
||||||
|
Fensters zählen für die Erfolgsquote. Nach 7 Tagen Produktiv-Betrieb prüfen."""
|
||||||
|
|
||||||
|
LLM_ROOM_WATCHDOG_THRESHOLD: float = float(os.getenv(
|
||||||
|
"ARCHIVAR_WATCHDOG_THRESHOLD", "0.80"
|
||||||
|
))
|
||||||
|
"""Erfolgsquote-Schwelle (Default 0.80 = 80%). Unterschreitung triggert den
|
||||||
|
Alert. Andreas-Vorschlag, NICHT empirisch kalibriert — nach 7 Tagen prüfen
|
||||||
|
(ggf. 0.90 angemessen)."""
|
||||||
|
|
||||||
|
LLM_ROOM_WATCHDOG_INTERVAL_S: int = int(os.getenv(
|
||||||
|
"ARCHIVAR_WATCHDOG_INTERVAL_S", "300"
|
||||||
|
))
|
||||||
|
"""Watchdog-Tick-Intervall in Sekunden (Default 5min). Häufigkeit der
|
||||||
|
Erfolgsquoten-Prüfung. Nach 7 Tagen Produktiv-Betrieb prüfen."""
|
||||||
|
|
||||||
|
LLM_ROOM_WATCHDOG_MIN_SAMPLES: int = int(os.getenv(
|
||||||
|
"ARCHIVAR_WATCHDOG_MIN_SAMPLES", "10"
|
||||||
|
))
|
||||||
|
"""Minimale Sample-Anzahl im Fenster (Default 10). Bei <10 Samples gibt
|
||||||
|
success_ratio() None zurück und der Watchdog triggert NICHT (K2 — verhindert
|
||||||
|
statistisch sinnlose Ratio-Ausreißer bei niedrigem Traffic). Nach 7 Tagen
|
||||||
|
Produktiv-Betrieb prüfen."""
|
||||||
|
|
||||||
|
LLM_ROOM_WATCHDOG_ALERT_COOLDOWN_S: int = int(os.getenv(
|
||||||
|
"ARCHIVAR_WATCHDOG_COOLDOWN_S", "86400"
|
||||||
|
))
|
||||||
|
"""Alert-Cooldown in Sekunden (Default 24h). Einmal-Alarm pro 24h-Fenster
|
||||||
|
(K3, P-088-Lehre: kein User-Spam). Persistentes Flag überlebt Gateway-Restart.
|
||||||
|
Nach 7 Tagen Produktiv-Betrieb prüfen."""
|
||||||
|
|
||||||
# ── Deprecated: LLM_CLASSIFY_PROMPT (bleibt für Abwärtskompatibilität) ─────
|
# ── Deprecated: LLM_CLASSIFY_PROMPT (bleibt für Abwärtskompatibilität) ─────
|
||||||
# Wird NICHT mehr verwendet — LLM_ROOM_PROMPT ist der neue Standard.
|
# Wird NICHT mehr verwendet — LLM_ROOM_PROMPT ist der neue Standard.
|
||||||
# Bleibt im Code, falls externe Skripte darauf verweisen.
|
# Bleibt im Code, falls externe Skripte darauf verweisen.
|
||||||
|
|||||||
@@ -3128,13 +3128,67 @@ class PresenceEngine:
|
|||||||
self._status = "BUSY"
|
self._status = "BUSY"
|
||||||
# AWAY existiert nicht mehr als interner Status — wird über get_visible_status()
|
# AWAY existiert nicht mehr als interner Status — wird über get_visible_status()
|
||||||
|
|
||||||
# ── Schicht 3: REST-Sender (fire-and-forget, fast unverändert aus V9) ─
|
# ── Schicht 3: REST-Sender (fire-and-forget, fast unverändert aus V9) ──
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _extract_http_status_code(exc: BaseException) -> Optional[int]:
|
||||||
|
"""Extrahiere den HTTP-Status-Code aus einer Exception (falls vorhanden).
|
||||||
|
|
||||||
|
WV-002: Statt den String '429' im Exception-Text zu vermuten, wird der
|
||||||
|
echte HTTP-Status-Code ermittelt. Prüf-Reihenfolge:
|
||||||
|
|
||||||
|
1. ``urllib.error.HTTPError`` → ``.code`` (echter HTTP-Status).
|
||||||
|
2. ``RocketChatRateLimitError`` → 429 (per Definition HTTP 429).
|
||||||
|
Per Typname geprüft, um einen Circular-Import (adapter ↔
|
||||||
|
presence_engine) zu vermeiden.
|
||||||
|
3. ``__cause__``-Kette (``raise ... from e``) → HTTPError/429.
|
||||||
|
4. ``.status_code`` / ``.status`` / ``.code``-Attribute (falls gesetzt).
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
int HTTP-Status-Code oder ``None`` wenn keiner ermittelbar ist.
|
||||||
|
"""
|
||||||
|
# 1. Direkt HTTPError
|
||||||
|
if isinstance(exc, urllib.error.HTTPError):
|
||||||
|
return exc.code
|
||||||
|
# 2. RocketChatRateLimitError (immer 429)
|
||||||
|
if type(exc).__name__ == "RocketChatRateLimitError":
|
||||||
|
return 429
|
||||||
|
# 3. __cause__-Kette
|
||||||
|
cause = exc.__cause__
|
||||||
|
while cause is not None:
|
||||||
|
if isinstance(cause, urllib.error.HTTPError):
|
||||||
|
return cause.code
|
||||||
|
if type(cause).__name__ == "RocketChatRateLimitError":
|
||||||
|
return 429
|
||||||
|
cause = cause.__cause__
|
||||||
|
# 4. Status-Attribute
|
||||||
|
for attr in ("status_code", "status", "code"):
|
||||||
|
val = getattr(exc, attr, None)
|
||||||
|
if isinstance(val, int):
|
||||||
|
return val
|
||||||
|
return None
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _is_http_429(exc: BaseException, http_code: Optional[int]) -> bool:
|
||||||
|
"""True NUR bei echtem HTTP 429 (Status-Code-Prüfung).
|
||||||
|
|
||||||
|
WV-002: Kein String-Matching auf '429' im Exception-Text — das
|
||||||
|
klassifizierte DDP-Timeouts und REST-Token-Errors fälschlich als 429
|
||||||
|
(Phantom-429er).
|
||||||
|
"""
|
||||||
|
if http_code == 429:
|
||||||
|
return True
|
||||||
|
# Fallback: RocketChatRateLimitError ist per Definition 429.
|
||||||
|
return type(exc).__name__ == "RocketChatRateLimitError"
|
||||||
|
|
||||||
def _rest_set_status(self, status: str, message: str) -> bool:
|
def _rest_set_status(self, status: str, message: str) -> bool:
|
||||||
"""Sende users.setStatus via REST (synchron).
|
"""Sende users.setStatus via REST (synchron).
|
||||||
|
|
||||||
Wird vom Mediator in einem fire-and-forget Daemon-Thread aufgerufen.
|
Wird vom Mediator in einem fire-and-forget Daemon-Thread aufgerufen.
|
||||||
Bei 429: setzt Mediator-Cooldown (Rückkanal).
|
Bei ECHTEM HTTP 429 (Status-Code-Prüfung): setzt Mediator-Cooldown
|
||||||
|
(Rückkanal). Andere Exceptions (DDP-Timeout, Token-Error, etc.)
|
||||||
|
triggern KEINEN Cooldown — nur korrektes Logging (Typ + Message +
|
||||||
|
HTTP-Status-Code).
|
||||||
|
|
||||||
POST /api/v1/users.setStatus
|
POST /api/v1/users.setStatus
|
||||||
Body: {"status": "...", "message": "..."}
|
Body: {"status": "...", "message": "..."}
|
||||||
@@ -3181,8 +3235,12 @@ class PresenceEngine:
|
|||||||
return True
|
return True
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
error_str = str(e).lower()
|
# WV-002: Exception-Typ, volle Message UND HTTP-Status-Code loggen.
|
||||||
if "429" in error_str or "too many requests" in error_str:
|
exc_type = type(e).__name__
|
||||||
|
http_code = self._extract_http_status_code(e)
|
||||||
|
is_429 = self._is_http_429(e, http_code)
|
||||||
|
|
||||||
|
if is_429:
|
||||||
self._telemetry_rest_429 += 1
|
self._telemetry_rest_429 += 1
|
||||||
# V10: Setze Mediator-Cooldown (Rückkanal) — jetzt mit exp. Backoff
|
# V10: Setze Mediator-Cooldown (Rückkanal) — jetzt mit exp. Backoff
|
||||||
self._mediator.set_rest_cooldown()
|
self._mediator.set_rest_cooldown()
|
||||||
@@ -3193,18 +3251,21 @@ class PresenceEngine:
|
|||||||
if self._mediator._clarify_modal:
|
if self._mediator._clarify_modal:
|
||||||
self._mediator._on_modal_pulse_fail()
|
self._mediator._on_modal_pulse_fail()
|
||||||
logger.warning(
|
logger.warning(
|
||||||
"[presence-v10] REST 429 — Cooldown gesetzt, "
|
"[presence-v10] REST 429 (HTTP %s) — Cooldown gesetzt, "
|
||||||
"Status %s verworfen", status
|
"Status %s verworfen (exc=%s: %s)",
|
||||||
|
http_code, status, exc_type, e,
|
||||||
)
|
)
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
# Kein echter 429 — KEIN Cooldown (Phantom-429-Schutz).
|
||||||
self._telemetry_rest_errors += 1
|
self._telemetry_rest_errors += 1
|
||||||
# P-050: Modal-Puls-Fail signalisieren
|
# P-050: Modal-Puls-Fail signalisieren
|
||||||
if self._mediator._clarify_modal:
|
if self._mediator._clarify_modal:
|
||||||
self._mediator._on_modal_pulse_fail()
|
self._mediator._on_modal_pulse_fail()
|
||||||
logger.warning(
|
logger.warning(
|
||||||
"[presence-v10] REST-Fehler (1. Versuch): %s — retry in %.1fs",
|
"[presence-v10] REST-Fehler (1. Versuch): exc=%s, http_code=%s, "
|
||||||
e, self.RETRY_DELAY_S,
|
"msg=%s — retry in %.1fs",
|
||||||
|
exc_type, http_code, e, self.RETRY_DELAY_S,
|
||||||
)
|
)
|
||||||
|
|
||||||
# Ein Retry nach 2s
|
# Ein Retry nach 2s
|
||||||
@@ -3230,11 +3291,23 @@ class PresenceEngine:
|
|||||||
)
|
)
|
||||||
return True
|
return True
|
||||||
except Exception as e2:
|
except Exception as e2:
|
||||||
self._telemetry_rest_errors += 1
|
# WV-002: Auch im Retry Typ + Message + HTTP-Status-Code loggen.
|
||||||
|
exc_type2 = type(e2).__name__
|
||||||
|
http_code2 = self._extract_http_status_code(e2)
|
||||||
|
is_429_2 = self._is_http_429(e2, http_code2)
|
||||||
|
if is_429_2:
|
||||||
|
self._telemetry_rest_429 += 1
|
||||||
|
self._mediator.set_rest_cooldown()
|
||||||
|
if self._ddp_sender is not None:
|
||||||
|
self._ddp_sender.on_rest_429()
|
||||||
|
else:
|
||||||
|
self._telemetry_rest_errors += 1
|
||||||
# P-050: Modal-Puls-Fail signalisieren
|
# P-050: Modal-Puls-Fail signalisieren
|
||||||
if self._mediator._clarify_modal:
|
if self._mediator._clarify_modal:
|
||||||
self._mediator._on_modal_pulse_fail()
|
self._mediator._on_modal_pulse_fail()
|
||||||
logger.warning(
|
logger.warning(
|
||||||
"[presence-v10] REST-Fehler (Retry): %s — aufgegeben", e2
|
"[presence-v10] REST-Fehler (Retry): exc=%s, http_code=%s, "
|
||||||
|
"msg=%s — aufgegeben",
|
||||||
|
exc_type2, http_code2, e2,
|
||||||
)
|
)
|
||||||
return False
|
return False
|
||||||
|
|||||||
@@ -1675,16 +1675,23 @@ class BidirectionalRouter:
|
|||||||
LLM_ROOM_LOOKUP_TIMEOUT, text,
|
LLM_ROOM_LOOKUP_TIMEOUT, text,
|
||||||
)
|
)
|
||||||
routing_counter.increment('llm_room_lookup_timeout')
|
routing_counter.increment('llm_room_lookup_timeout')
|
||||||
|
routing_counter.record_attempt(success=False)
|
||||||
return None, False, True, "unavailable", ""
|
return None, False, True, "unavailable", ""
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.warning(
|
logger.warning(
|
||||||
"Stufe 4: LLM-Raum-Router Exception: %s → LLM unavailable", e,
|
"Stufe 4: LLM-Raum-Router Exception: %s → LLM unavailable", e,
|
||||||
)
|
)
|
||||||
|
routing_counter.record_attempt(success=False)
|
||||||
return None, False, True, "unavailable", ""
|
return None, False, True, "unavailable", ""
|
||||||
|
|
||||||
if llm_result is None:
|
if llm_result is None:
|
||||||
|
routing_counter.record_attempt(success=False)
|
||||||
return None, False, True, "unavailable", "" # LLM-Aufruf fehlgeschlagen
|
return None, False, True, "unavailable", "" # LLM-Aufruf fehlgeschlagen
|
||||||
|
|
||||||
|
# LLM-Aufruf erfolgreich (Antwort kam zurück, parsbar) — F100-Watchdog.
|
||||||
|
# P-088-Lehre: success = "Antwort kam zurück", NICHT "Routing korrekt".
|
||||||
|
routing_counter.record_attempt(success=True)
|
||||||
|
|
||||||
# Parse LLM response — should be a room ID or "STAY"
|
# Parse LLM response — should be a room ID or "STAY"
|
||||||
response = llm_result.strip()
|
response = llm_result.strip()
|
||||||
|
|
||||||
|
|||||||
@@ -15,17 +15,27 @@ from __future__ import annotations
|
|||||||
|
|
||||||
import logging
|
import logging
|
||||||
import threading
|
import threading
|
||||||
from typing import Dict
|
import time
|
||||||
|
from typing import Dict, List, Optional, Tuple
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
class RoutingCounter:
|
class RoutingCounter:
|
||||||
"""Thread-safe In-Memory-Counter für Routing-Entscheidungen."""
|
"""Thread-safe In-Memory-Counter für Routing-Entscheidungen.
|
||||||
|
|
||||||
|
F100-Erweiterung: zusätzlich zum bestehenden ``increment()``-Zähler
|
||||||
|
(Diagnose) hält der Counter einen Ring-Buffer aus ``(timestamp, success)``-
|
||||||
|
Tupeln für die Runtime-Watchdog-Erfolgsquote. ``record_attempt()`` ist eine
|
||||||
|
NEUE Methode — ``increment()`` bleibt unverändert (Rückwärts-Kompatibilität
|
||||||
|
für 165 Call-Sites, P-019-Lehre).
|
||||||
|
"""
|
||||||
|
|
||||||
def __init__(self) -> None:
|
def __init__(self) -> None:
|
||||||
self._lock = threading.Lock()
|
self._lock = threading.Lock()
|
||||||
self._counts: Dict[str, int] = {}
|
self._counts: Dict[str, int] = {}
|
||||||
|
# F100: Ring-Buffer für Erfolgsquote (timestamp, success).
|
||||||
|
self._attempts: List[Tuple[float, bool]] = []
|
||||||
|
|
||||||
def increment(self, reason: str) -> None:
|
def increment(self, reason: str) -> None:
|
||||||
"""Inkrementiere den Zähler für einen Grund (thread-safe)."""
|
"""Inkrementiere den Zähler für einen Grund (thread-safe)."""
|
||||||
@@ -51,6 +61,64 @@ class RoutingCounter:
|
|||||||
"""Setze alle Zähler zurück."""
|
"""Setze alle Zähler zurück."""
|
||||||
with self._lock:
|
with self._lock:
|
||||||
self._counts.clear()
|
self._counts.clear()
|
||||||
|
self._attempts.clear()
|
||||||
|
|
||||||
|
# ── F100: Runtime-Watchdog (Erfolgsquote) ─────────────────────────────
|
||||||
|
|
||||||
|
def record_attempt(self, success: bool, timestamp: Optional[float] = None) -> None:
|
||||||
|
"""Zeichne einen Routing-Versuch auf (thread-safe).
|
||||||
|
|
||||||
|
Wird vom Router nach jedem LLM-Raum-Call aufgerufen. ``success`` ist
|
||||||
|
hier "Antwort kam zurück, war parsbar" — NICHT "Routing war inhaltlich
|
||||||
|
korrekt" (P-088-Lehre: sonst messen wir Accuracy, nicht Verfügbarkeit).
|
||||||
|
|
||||||
|
Args:
|
||||||
|
success: True wenn der LLM-Call erfolgreich war (failed=False).
|
||||||
|
timestamp: Optionaler Zeitstempel (Default: time.time()). Für
|
||||||
|
Tests injizierbar.
|
||||||
|
"""
|
||||||
|
ts = time.time() if timestamp is None else timestamp
|
||||||
|
with self._lock:
|
||||||
|
self._attempts.append((ts, bool(success)))
|
||||||
|
|
||||||
|
def success_ratio(
|
||||||
|
self,
|
||||||
|
window_s: float,
|
||||||
|
min_samples: int,
|
||||||
|
now: Optional[float] = None,
|
||||||
|
) -> Optional[float]:
|
||||||
|
"""Erfolgsquote der Attempts im letzten ``window_s``-Fenster.
|
||||||
|
|
||||||
|
Einträge älter als ``window_s`` werden beim Lesen gefiltert (GC).
|
||||||
|
Gibt ``None`` zurück, wenn weniger als ``min_samples`` Attempts im
|
||||||
|
Fenster liegen (K2 — verhindert statistisch sinnlose Ratio-Ausreißer
|
||||||
|
bei niedrigem Traffic).
|
||||||
|
|
||||||
|
Args:
|
||||||
|
window_s: Fensterbreite in Sekunden.
|
||||||
|
min_samples: Mindestanzahl Attempts im Fenster.
|
||||||
|
now: Optionaler Referenz-Zeitpunkt (Default: time.time()).
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Erfolgsquote als float in [0.0, 1.0], oder None bei < min_samples.
|
||||||
|
"""
|
||||||
|
ref = time.time() if now is None else now
|
||||||
|
cutoff = ref - window_s
|
||||||
|
with self._lock:
|
||||||
|
# GC: Einträge älter als window_s entfernen (Ring-Buffer).
|
||||||
|
self._attempts = [a for a in self._attempts if a[0] >= cutoff]
|
||||||
|
if len(self._attempts) < min_samples:
|
||||||
|
return None
|
||||||
|
successes = sum(1 for _, ok in self._attempts if ok)
|
||||||
|
return successes / len(self._attempts)
|
||||||
|
|
||||||
|
def attempt_count(self, window_s: float, now: Optional[float] = None) -> int:
|
||||||
|
"""Anzahl der Attempts im letzten ``window_s``-Fenster (für Logging)."""
|
||||||
|
ref = time.time() if now is None else now
|
||||||
|
cutoff = ref - window_s
|
||||||
|
with self._lock:
|
||||||
|
self._attempts = [a for a in self._attempts if a[0] >= cutoff]
|
||||||
|
return len(self._attempts)
|
||||||
|
|
||||||
|
|
||||||
# Modul-Level-Singleton — wird von adapter.py und router.py importiert
|
# Modul-Level-Singleton — wird von adapter.py und router.py importiert
|
||||||
|
|||||||
@@ -30,13 +30,14 @@ from __future__ import annotations
|
|||||||
import json
|
import json
|
||||||
import logging
|
import logging
|
||||||
import os
|
import os
|
||||||
|
import time
|
||||||
import urllib.error
|
import urllib.error
|
||||||
import urllib.request
|
import urllib.request
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import List, Optional
|
from typing import List, Optional, Tuple
|
||||||
|
|
||||||
from .config import OLLAMA_CONFIG, LLM_CONFIG
|
from .config import OLLAMA_CONFIG, LLM_CONFIG, LLM_ROOM_LOOKUP_TIMEOUT
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
@@ -52,6 +53,27 @@ SELF_CHECK_TIMEOUT_S: float = float(os.getenv("ARCHIVAR_SELF_CHECK_TIMEOUT", "30
|
|||||||
SELF_CHECK_HTTP_TIMEOUT_S: float = 3.0
|
SELF_CHECK_HTTP_TIMEOUT_S: float = 3.0
|
||||||
"""HTTP-Timeout pro Einzel-Check in Sekunden (analog install.sh curl --max-time 3)."""
|
"""HTTP-Timeout pro Einzel-Check in Sekunden (analog install.sh curl --max-time 3)."""
|
||||||
|
|
||||||
|
# ── F100: Stufe 4b — Router-E2E-Probe (Smoke-Test) ──────────────────────────
|
||||||
|
# K1-Rollenverteilung: Stufe 4b ist der Start-Smoke-Test (Modell + Endpoint
|
||||||
|
# reagieren überhaupt), der Runtime-Watchdog ist die 2. Verteidigungslinie
|
||||||
|
# (echte Router-Pipeline). Beide nötig, unterschiedliche Rollen.
|
||||||
|
|
||||||
|
STUFE4B_PROBE_PROMPT: str = "Antworte ausschließlich mit dem Wort STAY"
|
||||||
|
"""Mini-Prompt für die Router-E2E-Probe. Single-Token-Antwort, deterministisch,
|
||||||
|
kein Raum-Map-State nötig.
|
||||||
|
|
||||||
|
Empirisch kalibriert (02.09., qwen2.5:7b auf localhost:11434): die naive
|
||||||
|
Formulierung "Antworte mit genau einem Wort: STAY" liefert "Ok." statt "STAY"
|
||||||
|
→ False-Negative gegen ein gesundes Modell. "Antworte ausschließlich mit dem
|
||||||
|
Wort STAY" liefert zuverlässig "STAY" (Rainer-Niagara-Befund aus dem Konzept:
|
||||||
|
Mini-Prompt darf nicht zu trivial sein)."""
|
||||||
|
|
||||||
|
STUFE4B_PROBE_TIMEOUT_S: float = float(os.getenv(
|
||||||
|
"ARCHIVAR_STUFE4B_TIMEOUT", str(LLM_ROOM_LOOKUP_TIMEOUT)
|
||||||
|
))
|
||||||
|
"""HTTP-Timeout der Stufe-4b-Probe. Default identisch zu
|
||||||
|
LLM_ROOM_LOOKUP_TIMEOUT (15s), NICHT höher (K1)."""
|
||||||
|
|
||||||
# ── Index-Pfad (identisch zu room_index.py `_DEFAULT_INDEX_DIR`) ─────────────
|
# ── Index-Pfad (identisch zu room_index.py `_DEFAULT_INDEX_DIR`) ─────────────
|
||||||
# Bewusst hier neu abgeleitet statt `import room_index` — room_index importiert
|
# Bewusst hier neu abgeleitet statt `import room_index` — room_index importiert
|
||||||
# numpy auf Modulebene, was bei kaputtem venv selbst fehlschlägt (genau das,
|
# numpy auf Modulebene, was bei kaputtem venv selbst fehlschlägt (genau das,
|
||||||
@@ -69,7 +91,10 @@ class ComponentCheckResult:
|
|||||||
"""Ergebnis der 6-stufigen Self-Check-Diagnose.
|
"""Ergebnis der 6-stufigen Self-Check-Diagnose.
|
||||||
|
|
||||||
Stufen 1-3 sind Fehler-Stufen, Stufen 4-5 Warmup-Stufen, Stufe 6
|
Stufen 1-3 sind Fehler-Stufen, Stufen 4-5 Warmup-Stufen, Stufe 6
|
||||||
(``ready``) ist abgeleitet.
|
(``ready``) ist abgeleitet. Stufe 4b (F100) ist eine zusätzliche
|
||||||
|
Warmup-Stufe: sie misst einen externen Endpoint, der temporär
|
||||||
|
unerreichbar sein kann (K1-Rollenverteilung) — bei 4b-Fail also
|
||||||
|
Warmup-Meldung, nicht Repair-Meldung.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
faiss_importable: bool # Stufe 1
|
faiss_importable: bool # Stufe 1
|
||||||
@@ -78,6 +103,8 @@ class ComponentCheckResult:
|
|||||||
llm_model_loaded: bool # Stufe 4
|
llm_model_loaded: bool # Stufe 4
|
||||||
embedding_ladbar: bool # Stufe 5
|
embedding_ladbar: bool # Stufe 5
|
||||||
ready: bool # Stufe 6 (abgeleitet)
|
ready: bool # Stufe 6 (abgeleitet)
|
||||||
|
llm_room_e2e_ok: bool = False # Stufe 4b (F100)
|
||||||
|
llm_room_e2e_latency_ms: float = 0.0 # Stufe 4b (F100)
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def has_error(self) -> bool:
|
def has_error(self) -> bool:
|
||||||
@@ -88,9 +115,9 @@ class ComponentCheckResult:
|
|||||||
|
|
||||||
@property
|
@property
|
||||||
def needs_warmup(self) -> bool:
|
def needs_warmup(self) -> bool:
|
||||||
"""True wenn keine Fehler-Stufe, aber eine Warmup-Stufe (4-5) fehlt."""
|
"""True wenn keine Fehler-Stufe, aber eine Warmup-Stufe (4-5, 4b) fehlt."""
|
||||||
return (not self.has_error) and not (
|
return (not self.has_error) and not (
|
||||||
self.llm_model_loaded and self.embedding_ladbar
|
self.llm_model_loaded and self.embedding_ladbar and self.llm_room_e2e_ok
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -196,6 +223,51 @@ def _probe_embedding(base_url: str, model: str, timeout: float) -> bool:
|
|||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def _probe_llm_room_e2e(
|
||||||
|
base_url: str,
|
||||||
|
model: str,
|
||||||
|
timeout: float,
|
||||||
|
) -> Tuple[bool, float, str]:
|
||||||
|
"""Stufe 4b (F100): Router-E2E-Probe — POST /api/generate mit Mini-Prompt.
|
||||||
|
|
||||||
|
Smoke-Test (K1): prüft, dass Modell + Endpoint überhaupt antworten.
|
||||||
|
Antwort-Validierung: enthält "STAY" (case-insensitive trim) UND Latenz
|
||||||
|
≤ timeout. Bei jedem Fehler (HTTP, Timeout, Parse): ok=False.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
base_url: Ollama-Basis-URL (ohne trailing slash).
|
||||||
|
model: LLM-Modellname (aus LLM_CONFIG).
|
||||||
|
timeout: HTTP-Timeout in Sekunden.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
(ok: bool, latency_ms: float, detail: str)
|
||||||
|
"""
|
||||||
|
url = f"{base_url}/api/generate"
|
||||||
|
payload = json.dumps({
|
||||||
|
"model": model,
|
||||||
|
"prompt": STUFE4B_PROBE_PROMPT,
|
||||||
|
"stream": False,
|
||||||
|
}).encode("utf-8")
|
||||||
|
headers = {"Content-Type": "application/json"}
|
||||||
|
t0 = time.monotonic()
|
||||||
|
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"))
|
||||||
|
latency_ms = (time.monotonic() - t0) * 1000.0
|
||||||
|
except (urllib.error.HTTPError, urllib.error.URLError) as e:
|
||||||
|
return False, 0.0, f"HTTP/URL-Fehler: {e}"
|
||||||
|
except (json.JSONDecodeError, OSError, Exception) as e:
|
||||||
|
return False, 0.0, f"Fehler: {e}"
|
||||||
|
|
||||||
|
response = (data.get("response") or "").strip()
|
||||||
|
if "STAY" not in response.upper():
|
||||||
|
return False, latency_ms, f"unerwartete Antwort: {response[:60]!r}"
|
||||||
|
if latency_ms > timeout * 1000.0:
|
||||||
|
return False, latency_ms, f"Latenz {latency_ms:.0f}ms > {timeout*1000:.0f}ms"
|
||||||
|
return True, latency_ms, ""
|
||||||
|
|
||||||
|
|
||||||
# ── check_components(): die gemeinsame Diagnose-Funktion ────────────────────
|
# ── check_components(): die gemeinsame Diagnose-Funktion ────────────────────
|
||||||
|
|
||||||
|
|
||||||
@@ -228,7 +300,20 @@ def check_components() -> ComponentCheckResult:
|
|||||||
llm_loaded = False
|
llm_loaded = False
|
||||||
embedding_ok = False
|
embedding_ok = False
|
||||||
|
|
||||||
ready = faiss_ok and index_ok and ollama_ok and llm_loaded and embedding_ok # Stufe 6
|
# Stufe 4b (F100): Router-E2E-Probe — nur wenn Ollama erreichbar UND
|
||||||
|
# Modell geladen (sonst nicht ausführbar → ok=False, latency_ms=0).
|
||||||
|
if ollama_ok and llm_loaded:
|
||||||
|
e2e_ok, e2e_latency_ms, _e2e_detail = _probe_llm_room_e2e(
|
||||||
|
base_url, llm_model, STUFE4B_PROBE_TIMEOUT_S
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
e2e_ok = False
|
||||||
|
e2e_latency_ms = 0.0
|
||||||
|
|
||||||
|
ready = (
|
||||||
|
faiss_ok and index_ok and ollama_ok and llm_loaded and embedding_ok
|
||||||
|
and e2e_ok # Stufe 6 + 4b
|
||||||
|
)
|
||||||
|
|
||||||
return ComponentCheckResult(
|
return ComponentCheckResult(
|
||||||
faiss_importable=faiss_ok,
|
faiss_importable=faiss_ok,
|
||||||
@@ -237,6 +322,8 @@ def check_components() -> ComponentCheckResult:
|
|||||||
llm_model_loaded=llm_loaded,
|
llm_model_loaded=llm_loaded,
|
||||||
embedding_ladbar=embedding_ok,
|
embedding_ladbar=embedding_ok,
|
||||||
ready=ready,
|
ready=ready,
|
||||||
|
llm_room_e2e_ok=e2e_ok,
|
||||||
|
llm_room_e2e_latency_ms=e2e_latency_ms,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,241 @@
|
|||||||
|
"""
|
||||||
|
F100 — Runtime-Watchdog: Trigger, Cooldown, Min-Samples-Guard, Persistenz.
|
||||||
|
|
||||||
|
Testkonzept (D3):
|
||||||
|
1. Trigger: success_ratio unter Schwelle → ERROR-Alert + Cooldown gesetzt.
|
||||||
|
2. Cooldown: zweiter Trigger innerhalb 24h → kein zweites Alert.
|
||||||
|
3. Min-Samples-Guard: ratio=None → kein Alert.
|
||||||
|
4. Persistenz: Cooldown-Flag überlebt "Restart" (load from file).
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
from unittest.mock import AsyncMock, MagicMock, patch
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
|
||||||
|
|
||||||
|
from plugin.archivar.watchdog_alert import WatchdogAlertCooldown
|
||||||
|
|
||||||
|
|
||||||
|
# ── WatchdogAlertCooldown (K3: persistentes Cooldown-Flag) ─────────────────
|
||||||
|
|
||||||
|
|
||||||
|
class TestWatchdogAlertCooldown:
|
||||||
|
"""Cooldown-Buchhaltung: is_in_cooldown / mark_alerted / Persistenz."""
|
||||||
|
|
||||||
|
def test_not_in_cooldown_initially(self):
|
||||||
|
c = WatchdogAlertCooldown(cooldown_s=86400.0, state_path=None)
|
||||||
|
assert c.is_in_cooldown(now=1000.0) is False
|
||||||
|
|
||||||
|
def test_in_cooldown_after_mark(self):
|
||||||
|
c = WatchdogAlertCooldown(cooldown_s=86400.0, state_path=None)
|
||||||
|
c.mark_alerted(now=1000.0)
|
||||||
|
assert c.is_in_cooldown(now=1000.0) is True
|
||||||
|
assert c.is_in_cooldown(now=1000.0 + 86399.0) is True
|
||||||
|
|
||||||
|
def test_cooldown_expires(self):
|
||||||
|
c = WatchdogAlertCooldown(cooldown_s=86400.0, state_path=None)
|
||||||
|
c.mark_alerted(now=1000.0)
|
||||||
|
assert c.is_in_cooldown(now=1000.0 + 86400.0) is False
|
||||||
|
|
||||||
|
def test_persistence_survives_restart(self, tmp_path):
|
||||||
|
state_path = str(tmp_path / "routing_watchdog_alert.json")
|
||||||
|
c1 = WatchdogAlertCooldown(cooldown_s=86400.0, state_path=state_path)
|
||||||
|
c1.mark_alerted(now=1000.0)
|
||||||
|
|
||||||
|
# "Restart": neue Instanz lädt aus derselben Datei.
|
||||||
|
c2 = WatchdogAlertCooldown(cooldown_s=86400.0, state_path=state_path)
|
||||||
|
assert c2.last_alert_ts == pytest.approx(1000.0)
|
||||||
|
assert c2.is_in_cooldown(now=1000.0 + 100.0) is True
|
||||||
|
|
||||||
|
def test_persistence_file_content(self, tmp_path):
|
||||||
|
state_path = str(tmp_path / "routing_watchdog_alert.json")
|
||||||
|
c = WatchdogAlertCooldown(cooldown_s=86400.0, state_path=state_path)
|
||||||
|
c.mark_alerted(now=1234.5)
|
||||||
|
with open(state_path, "r", encoding="utf-8") as f:
|
||||||
|
data = json.load(f)
|
||||||
|
assert data["last_alert_ts"] == pytest.approx(1234.5)
|
||||||
|
|
||||||
|
def test_missing_file_is_not_in_cooldown(self, tmp_path):
|
||||||
|
state_path = str(tmp_path / "does_not_exist.json")
|
||||||
|
c = WatchdogAlertCooldown(cooldown_s=86400.0, state_path=state_path)
|
||||||
|
assert c.is_in_cooldown(now=1000.0) is False
|
||||||
|
|
||||||
|
|
||||||
|
# ── Adapter-Watchdog-Schleife (Trigger / Cooldown / Min-Samples-Guard) ──────
|
||||||
|
|
||||||
|
|
||||||
|
class TestRoutingWatchdogLoop:
|
||||||
|
"""_run_routing_watchdog(): Trigger-Logik mit Cooldown + Min-Samples."""
|
||||||
|
|
||||||
|
def _make_adapter(self):
|
||||||
|
from plugin.adapter import RocketChatAdapter
|
||||||
|
adapter = RocketChatAdapter.__new__(RocketChatAdapter)
|
||||||
|
adapter.archivar = MagicMock()
|
||||||
|
return adapter
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_trigger_logs_error_and_sets_cooldown(self):
|
||||||
|
adapter = self._make_adapter()
|
||||||
|
|
||||||
|
# success_ratio liefert 0.5 (unter Schwelle 0.8), Cooldown inaktiv.
|
||||||
|
fake_counter = MagicMock()
|
||||||
|
fake_counter.success_ratio.return_value = 0.5
|
||||||
|
fake_counter.attempt_count.return_value = 10
|
||||||
|
|
||||||
|
# Stateful Cooldown: nach dem ersten mark_alerted() aktiv (wie echt).
|
||||||
|
state = {"alerted": False}
|
||||||
|
|
||||||
|
class _FakeCooldown:
|
||||||
|
def is_in_cooldown(self):
|
||||||
|
return state["alerted"]
|
||||||
|
|
||||||
|
def mark_alerted(self):
|
||||||
|
state["alerted"] = True
|
||||||
|
|
||||||
|
fake_cooldown = _FakeCooldown()
|
||||||
|
|
||||||
|
with patch("archivar.routing_counter.routing_counter", fake_counter), \
|
||||||
|
patch("archivar.watchdog_alert.watchdog_alert_cooldown", fake_cooldown), \
|
||||||
|
patch("archivar.config.LLM_ROOM_WATCHDOG_INTERVAL_S", 0), \
|
||||||
|
patch("archivar.config.LLM_ROOM_WATCHDOG_WINDOW_S", 3600), \
|
||||||
|
patch("archivar.config.LLM_ROOM_WATCHDOG_THRESHOLD", 0.80), \
|
||||||
|
patch("archivar.config.LLM_ROOM_WATCHDOG_MIN_SAMPLES", 10), \
|
||||||
|
patch("plugin.adapter.logger") as mock_logger:
|
||||||
|
import asyncio
|
||||||
|
task = asyncio.ensure_future(adapter._run_routing_watchdog())
|
||||||
|
# Ein Tick abwarten, dann abbrechen.
|
||||||
|
await asyncio.sleep(0.05)
|
||||||
|
task.cancel()
|
||||||
|
try:
|
||||||
|
await task
|
||||||
|
except asyncio.CancelledError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
assert state["alerted"] is True
|
||||||
|
# ERROR-Alert wurde geloggt (genau einmal — Cooldown greift danach).
|
||||||
|
error_calls = [
|
||||||
|
c for c in mock_logger.error.call_args_list
|
||||||
|
if "RUNTIME-WATCHDOG" in str(c.args[0])
|
||||||
|
]
|
||||||
|
assert len(error_calls) == 1
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_cooldown_suppresses_second_alert(self):
|
||||||
|
adapter = self._make_adapter()
|
||||||
|
|
||||||
|
fake_counter = MagicMock()
|
||||||
|
fake_counter.success_ratio.return_value = 0.5
|
||||||
|
fake_counter.attempt_count.return_value = 10
|
||||||
|
fake_cooldown = MagicMock()
|
||||||
|
fake_cooldown.is_in_cooldown.return_value = True # Cooldown aktiv
|
||||||
|
|
||||||
|
with patch("archivar.routing_counter.routing_counter", fake_counter), \
|
||||||
|
patch("archivar.watchdog_alert.watchdog_alert_cooldown", fake_cooldown), \
|
||||||
|
patch("archivar.config.LLM_ROOM_WATCHDOG_INTERVAL_S", 0), \
|
||||||
|
patch("archivar.config.LLM_ROOM_WATCHDOG_WINDOW_S", 3600), \
|
||||||
|
patch("archivar.config.LLM_ROOM_WATCHDOG_THRESHOLD", 0.80), \
|
||||||
|
patch("archivar.config.LLM_ROOM_WATCHDOG_MIN_SAMPLES", 10), \
|
||||||
|
patch("plugin.adapter.logger") as mock_logger:
|
||||||
|
import asyncio
|
||||||
|
task = asyncio.ensure_future(adapter._run_routing_watchdog())
|
||||||
|
await asyncio.sleep(0.05)
|
||||||
|
task.cancel()
|
||||||
|
try:
|
||||||
|
await task
|
||||||
|
except asyncio.CancelledError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
fake_cooldown.mark_alerted.assert_not_called()
|
||||||
|
assert not any(
|
||||||
|
"RUNTIME-WATCHDOG" in str(c.args[0])
|
||||||
|
for c in mock_logger.error.call_args_list
|
||||||
|
)
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_min_samples_guard_no_alert(self):
|
||||||
|
adapter = self._make_adapter()
|
||||||
|
|
||||||
|
fake_counter = MagicMock()
|
||||||
|
fake_counter.success_ratio.return_value = None # < min_samples (K2)
|
||||||
|
fake_cooldown = MagicMock()
|
||||||
|
fake_cooldown.is_in_cooldown.return_value = False
|
||||||
|
|
||||||
|
with patch("archivar.routing_counter.routing_counter", fake_counter), \
|
||||||
|
patch("archivar.watchdog_alert.watchdog_alert_cooldown", fake_cooldown), \
|
||||||
|
patch("archivar.config.LLM_ROOM_WATCHDOG_INTERVAL_S", 0), \
|
||||||
|
patch("archivar.config.LLM_ROOM_WATCHDOG_WINDOW_S", 3600), \
|
||||||
|
patch("archivar.config.LLM_ROOM_WATCHDOG_THRESHOLD", 0.80), \
|
||||||
|
patch("archivar.config.LLM_ROOM_WATCHDOG_MIN_SAMPLES", 10), \
|
||||||
|
patch("plugin.adapter.logger") as mock_logger:
|
||||||
|
import asyncio
|
||||||
|
task = asyncio.ensure_future(adapter._run_routing_watchdog())
|
||||||
|
await asyncio.sleep(0.05)
|
||||||
|
task.cancel()
|
||||||
|
try:
|
||||||
|
await task
|
||||||
|
except asyncio.CancelledError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
fake_cooldown.mark_alerted.assert_not_called()
|
||||||
|
assert not any(
|
||||||
|
"RUNTIME-WATCHDOG" in str(c.args[0])
|
||||||
|
for c in mock_logger.error.call_args_list
|
||||||
|
)
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_ratio_above_threshold_no_alert(self):
|
||||||
|
adapter = self._make_adapter()
|
||||||
|
|
||||||
|
fake_counter = MagicMock()
|
||||||
|
fake_counter.success_ratio.return_value = 0.95 # über Schwelle
|
||||||
|
fake_cooldown = MagicMock()
|
||||||
|
fake_cooldown.is_in_cooldown.return_value = False
|
||||||
|
|
||||||
|
with patch("archivar.routing_counter.routing_counter", fake_counter), \
|
||||||
|
patch("archivar.watchdog_alert.watchdog_alert_cooldown", fake_cooldown), \
|
||||||
|
patch("archivar.config.LLM_ROOM_WATCHDOG_INTERVAL_S", 0), \
|
||||||
|
patch("archivar.config.LLM_ROOM_WATCHDOG_WINDOW_S", 3600), \
|
||||||
|
patch("archivar.config.LLM_ROOM_WATCHDOG_THRESHOLD", 0.80), \
|
||||||
|
patch("archivar.config.LLM_ROOM_WATCHDOG_MIN_SAMPLES", 10), \
|
||||||
|
patch("plugin.adapter.logger") as mock_logger:
|
||||||
|
import asyncio
|
||||||
|
task = asyncio.ensure_future(adapter._run_routing_watchdog())
|
||||||
|
await asyncio.sleep(0.05)
|
||||||
|
task.cancel()
|
||||||
|
try:
|
||||||
|
await task
|
||||||
|
except asyncio.CancelledError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
fake_cooldown.mark_alerted.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
|
class TestStartRoutingWatchdog:
|
||||||
|
"""_start_routing_watchdog(): nicht-blockierend, MULTIROOM-Guard."""
|
||||||
|
|
||||||
|
def _make_adapter(self):
|
||||||
|
from plugin.adapter import RocketChatAdapter
|
||||||
|
adapter = RocketChatAdapter.__new__(RocketChatAdapter)
|
||||||
|
adapter.archivar = MagicMock()
|
||||||
|
return adapter
|
||||||
|
|
||||||
|
def test_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_routing_watchdog()
|
||||||
|
mock_ef.assert_not_called()
|
||||||
|
|
||||||
|
def test_starts_when_multiroom(self):
|
||||||
|
adapter = self._make_adapter()
|
||||||
|
with patch("plugin.adapter._MULTIROOM", return_value=True), \
|
||||||
|
patch("plugin.adapter.asyncio.ensure_future") as mock_ef:
|
||||||
|
adapter._start_routing_watchdog()
|
||||||
|
mock_ef.assert_called_once()
|
||||||
@@ -0,0 +1,131 @@
|
|||||||
|
"""
|
||||||
|
F100 — RoutingCounter-Erweiterung: record_attempt() + success_ratio().
|
||||||
|
|
||||||
|
Testkonzept (D3):
|
||||||
|
1. record_attempt_window: Attempts im Fenster zählen, ältere nicht.
|
||||||
|
2. min_samples_guard: < min_samples → None.
|
||||||
|
3. threshold_boundary: ratio exakt an der Schwelle.
|
||||||
|
4. window_gc: Einträge älter als window_s werden beim Lesen gefiltert.
|
||||||
|
5. Rückwärts-Kompatibilität: increment() unverändert (P-019).
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
|
||||||
|
|
||||||
|
from plugin.archivar.routing_counter import RoutingCounter
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def counter():
|
||||||
|
return RoutingCounter()
|
||||||
|
|
||||||
|
|
||||||
|
class TestRecordAttemptWindow:
|
||||||
|
"""Attempts im Fenster zählen, ältere nicht."""
|
||||||
|
|
||||||
|
def test_all_in_window_ratio_1(self, counter):
|
||||||
|
for i in range(10):
|
||||||
|
counter.record_attempt(True, timestamp=1000.0 + i)
|
||||||
|
ratio = counter.success_ratio(window_s=3600.0, min_samples=10, now=1000.0 + 10)
|
||||||
|
assert ratio == 1.0
|
||||||
|
|
||||||
|
def test_old_attempts_excluded(self, counter):
|
||||||
|
# 5 Attempts vor dem Fenster, 5 im Fenster.
|
||||||
|
# now=1000, window=100 → cutoff=900. Alte Attempts bei 0..4 (< 900).
|
||||||
|
for i in range(5):
|
||||||
|
counter.record_attempt(False, timestamp=0.0 + i) # alt (vor Fenster)
|
||||||
|
for i in range(5):
|
||||||
|
counter.record_attempt(True, timestamp=1000.0 + i) # im Fenster
|
||||||
|
ratio = counter.success_ratio(window_s=100.0, min_samples=5, now=1000.0 + 5)
|
||||||
|
assert ratio == 1.0 # nur die 5 im Fenster zählen
|
||||||
|
|
||||||
|
def test_mixed_ratio(self, counter):
|
||||||
|
# 8 Erfolge + 2 Fehler = 0.8
|
||||||
|
for i in range(8):
|
||||||
|
counter.record_attempt(True, timestamp=1000.0 + i)
|
||||||
|
for i in range(2):
|
||||||
|
counter.record_attempt(False, timestamp=1000.0 + 8 + i)
|
||||||
|
ratio = counter.success_ratio(window_s=3600.0, min_samples=10, now=1000.0 + 10)
|
||||||
|
assert ratio == pytest.approx(0.8)
|
||||||
|
|
||||||
|
|
||||||
|
class TestMinSamplesGuard:
|
||||||
|
"""< min_samples → None (K2)."""
|
||||||
|
|
||||||
|
def test_three_attempts_returns_none(self, counter):
|
||||||
|
for i in range(3):
|
||||||
|
counter.record_attempt(True, timestamp=1000.0 + i)
|
||||||
|
ratio = counter.success_ratio(window_s=3600.0, min_samples=10, now=1000.0 + 3)
|
||||||
|
assert ratio is None
|
||||||
|
|
||||||
|
def test_exactly_min_samples_returns_ratio(self, counter):
|
||||||
|
for i in range(10):
|
||||||
|
counter.record_attempt(True, timestamp=1000.0 + i)
|
||||||
|
ratio = counter.success_ratio(window_s=3600.0, min_samples=10, now=1000.0 + 10)
|
||||||
|
assert ratio == 1.0
|
||||||
|
|
||||||
|
def test_zero_attempts_returns_none(self, counter):
|
||||||
|
assert counter.success_ratio(window_s=3600.0, min_samples=10, now=1000.0) is None
|
||||||
|
|
||||||
|
|
||||||
|
class TestThresholdBoundary:
|
||||||
|
"""ratio exakt an der Schwelle (0.79 → trigger, 0.81 → kein trigger)."""
|
||||||
|
|
||||||
|
def test_ratio_079(self, counter):
|
||||||
|
# 79 Erfolge + 21 Fehler = 0.79
|
||||||
|
for i in range(79):
|
||||||
|
counter.record_attempt(True, timestamp=1000.0 + i)
|
||||||
|
for i in range(21):
|
||||||
|
counter.record_attempt(False, timestamp=1000.0 + 79 + i)
|
||||||
|
ratio = counter.success_ratio(window_s=3600.0, min_samples=100, now=1000.0 + 100)
|
||||||
|
assert ratio == pytest.approx(0.79)
|
||||||
|
|
||||||
|
def test_ratio_081(self, counter):
|
||||||
|
# 81 Erfolge + 19 Fehler = 0.81
|
||||||
|
for i in range(81):
|
||||||
|
counter.record_attempt(True, timestamp=1000.0 + i)
|
||||||
|
for i in range(19):
|
||||||
|
counter.record_attempt(False, timestamp=1000.0 + 81 + i)
|
||||||
|
ratio = counter.success_ratio(window_s=3600.0, min_samples=100, now=1000.0 + 100)
|
||||||
|
assert ratio == pytest.approx(0.81)
|
||||||
|
|
||||||
|
|
||||||
|
class TestWindowGC:
|
||||||
|
"""Einträge älter als window_s werden beim Lesen gefiltert (Ring-Buffer)."""
|
||||||
|
|
||||||
|
def test_gc_removes_old_entries(self, counter):
|
||||||
|
for i in range(10):
|
||||||
|
counter.record_attempt(True, timestamp=1000.0 + i)
|
||||||
|
# Nach dem Lesen mit engem Fenster sind die alten Einträge weg.
|
||||||
|
# now=2000, window=1 → cutoff=1999. Alle Attempts (1000..1009) < 1999.
|
||||||
|
counter.success_ratio(window_s=1.0, min_samples=1, now=2000.0)
|
||||||
|
# attempt_count mit engem Fenster → 0 (alle gefiltert).
|
||||||
|
assert counter.attempt_count(window_s=1.0, now=2000.0) == 0
|
||||||
|
|
||||||
|
def test_gc_keeps_recent_entries(self, counter):
|
||||||
|
for i in range(10):
|
||||||
|
counter.record_attempt(True, timestamp=1000.0 + i)
|
||||||
|
counter.success_ratio(window_s=3600.0, min_samples=1, now=1000.0 + 10)
|
||||||
|
assert counter.attempt_count(window_s=3600.0, now=1000.0 + 10) == 10
|
||||||
|
|
||||||
|
|
||||||
|
class TestBackwardCompatibility:
|
||||||
|
"""increment() bleibt unverändert (P-019 — 165 Call-Sites)."""
|
||||||
|
|
||||||
|
def test_increment_still_works(self, counter):
|
||||||
|
counter.increment("llm_room_lookup_timeout")
|
||||||
|
counter.increment("llm_room_lookup_timeout")
|
||||||
|
assert counter.get_counts()["llm_room_lookup_timeout"] == 2
|
||||||
|
|
||||||
|
def test_reset_clears_both(self, counter):
|
||||||
|
counter.increment("foo")
|
||||||
|
counter.record_attempt(True, timestamp=1000.0)
|
||||||
|
counter.reset()
|
||||||
|
assert counter.get_counts() == {}
|
||||||
|
assert counter.attempt_count(window_s=3600.0, now=1000.0) == 0
|
||||||
@@ -42,6 +42,8 @@ def _result(**overrides) -> ComponentCheckResult:
|
|||||||
llm_model_loaded=True,
|
llm_model_loaded=True,
|
||||||
embedding_ladbar=True,
|
embedding_ladbar=True,
|
||||||
ready=True,
|
ready=True,
|
||||||
|
llm_room_e2e_ok=True,
|
||||||
|
llm_room_e2e_latency_ms=123.0,
|
||||||
)
|
)
|
||||||
base.update(overrides)
|
base.update(overrides)
|
||||||
# ready ist abgeleitet — neu berechnen, außer explizit gesetzt.
|
# ready ist abgeleitet — neu berechnen, außer explizit gesetzt.
|
||||||
@@ -52,6 +54,7 @@ def _result(**overrides) -> ComponentCheckResult:
|
|||||||
and base["ollama_reachable"]
|
and base["ollama_reachable"]
|
||||||
and base["llm_model_loaded"]
|
and base["llm_model_loaded"]
|
||||||
and base["embedding_ladbar"]
|
and base["embedding_ladbar"]
|
||||||
|
and base["llm_room_e2e_ok"]
|
||||||
)
|
)
|
||||||
return ComponentCheckResult(**base)
|
return ComponentCheckResult(**base)
|
||||||
|
|
||||||
@@ -96,11 +99,13 @@ class TestCheckComponents:
|
|||||||
patch("plugin.archivar.self_check._probe_index_loadable", 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_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_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_embedding", return_value=True), \
|
||||||
|
patch("plugin.archivar.self_check._probe_llm_room_e2e", return_value=(True, 123.0, "")):
|
||||||
r = check_components()
|
r = check_components()
|
||||||
assert r.ready is True
|
assert r.ready is True
|
||||||
assert r.faiss_importable and r.index_loadable and r.ollama_reachable
|
assert r.faiss_importable and r.index_loadable and r.ollama_reachable
|
||||||
assert r.llm_model_loaded and r.embedding_ladbar
|
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):
|
def test_faiss_missing_reports_error_stage1(self):
|
||||||
with patch("plugin.archivar.self_check._probe_faiss_importable", return_value=False), \
|
with patch("plugin.archivar.self_check._probe_faiss_importable", return_value=False), \
|
||||||
@@ -265,3 +270,113 @@ class TestAdapterSelfCheckWiring:
|
|||||||
|
|
||||||
def test_timeout_default_is_30s(self):
|
def test_timeout_default_is_30s(self):
|
||||||
assert SELF_CHECK_TIMEOUT_S == 30.0
|
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()
|
||||||
|
|||||||
@@ -797,11 +797,16 @@ class TestPresenceEngineWithDDP:
|
|||||||
assert engine._mediator._ddp_sender is None
|
assert engine._mediator._ddp_sender is None
|
||||||
|
|
||||||
def test_rest_429_triggers_ddp_on_rest_429(self):
|
def test_rest_429_triggers_ddp_on_rest_429(self):
|
||||||
"""REST 429 → ddp_sender.on_rest_429() wird aufgerufen."""
|
"""REST 429 → ddp_sender.on_rest_429() wird aufgerufen.
|
||||||
|
|
||||||
|
WV-002: Nutzt einen ECHTEN HTTP 429 (RocketChatRateLimitError),
|
||||||
|
nicht einen String '429' im Exception-Text (Phantom-429).
|
||||||
|
"""
|
||||||
|
from plugin.adapter import RocketChatRateLimitError
|
||||||
adapter, ddp = _make_mock_adapter()
|
adapter, ddp = _make_mock_adapter()
|
||||||
rest = _make_mock_rest()
|
rest = _make_mock_rest()
|
||||||
# Simuliere 429
|
# Simuliere echten HTTP 429 via RocketChatRateLimitError
|
||||||
rest._request = MagicMock(side_effect=Exception("HTTP 429 Too Many Requests"))
|
rest._request = MagicMock(side_effect=RocketChatRateLimitError("HTTP 429"))
|
||||||
engine = PresenceEngine(rest=rest, use_ddp=True, adapter=adapter)
|
engine = PresenceEngine(rest=rest, use_ddp=True, adapter=adapter)
|
||||||
|
|
||||||
# Setze ddp_sender Mock
|
# Setze ddp_sender Mock
|
||||||
|
|||||||
@@ -413,8 +413,9 @@ class TestRestBackoffActivation:
|
|||||||
|
|
||||||
def test_429_sets_cooldown(self):
|
def test_429_sets_cooldown(self):
|
||||||
"""429-Antwort → rest_cooldown_until gesetzt."""
|
"""429-Antwort → rest_cooldown_until gesetzt."""
|
||||||
|
from plugin.adapter import RocketChatRateLimitError
|
||||||
rest = _make_mock_rest()
|
rest = _make_mock_rest()
|
||||||
rest._request.side_effect = Exception("HTTP 429 Too Many Requests")
|
rest._request.side_effect = RocketChatRateLimitError("HTTP 429 Too Many Requests")
|
||||||
engine = _make_engine(rest=rest, away_grace_s=0.05)
|
engine = _make_engine(rest=rest, away_grace_s=0.05)
|
||||||
engine.on_pre_gateway_dispatch()
|
engine.on_pre_gateway_dispatch()
|
||||||
time.sleep(0.2)
|
time.sleep(0.2)
|
||||||
@@ -424,8 +425,9 @@ class TestRestBackoffActivation:
|
|||||||
|
|
||||||
def test_429_telemetry_counted(self):
|
def test_429_telemetry_counted(self):
|
||||||
"""Telemetrie zählt 429 + cooldown_set_count."""
|
"""Telemetrie zählt 429 + cooldown_set_count."""
|
||||||
|
from plugin.adapter import RocketChatRateLimitError
|
||||||
rest = _make_mock_rest()
|
rest = _make_mock_rest()
|
||||||
rest._request.side_effect = Exception("HTTP 429 Too Many Requests")
|
rest._request.side_effect = RocketChatRateLimitError("HTTP 429 Too Many Requests")
|
||||||
engine = _make_engine(rest=rest, away_grace_s=0.05)
|
engine = _make_engine(rest=rest, away_grace_s=0.05)
|
||||||
engine.on_pre_gateway_dispatch()
|
engine.on_pre_gateway_dispatch()
|
||||||
time.sleep(0.2)
|
time.sleep(0.2)
|
||||||
@@ -883,8 +885,9 @@ class TestHttp429Handling:
|
|||||||
"""HTTP 429 von users.setStatus — kein Crash, Cooldown gesetzt."""
|
"""HTTP 429 von users.setStatus — kein Crash, Cooldown gesetzt."""
|
||||||
|
|
||||||
def test_429_no_crash_status_unchanged(self):
|
def test_429_no_crash_status_unchanged(self):
|
||||||
|
from plugin.adapter import RocketChatRateLimitError
|
||||||
rest = _make_mock_rest()
|
rest = _make_mock_rest()
|
||||||
rest._request.side_effect = Exception("HTTP 429 Too Many Requests")
|
rest._request.side_effect = RocketChatRateLimitError("HTTP 429 Too Many Requests")
|
||||||
engine = _make_engine(rest=rest, away_grace_s=0.05)
|
engine = _make_engine(rest=rest, away_grace_s=0.05)
|
||||||
engine.on_pre_gateway_dispatch()
|
engine.on_pre_gateway_dispatch()
|
||||||
assert engine.get_status() == "BUSY"
|
assert engine.get_status() == "BUSY"
|
||||||
@@ -894,13 +897,14 @@ class TestHttp429Handling:
|
|||||||
assert engine.get_counters()["main_agent"] == 1
|
assert engine.get_counters()["main_agent"] == 1
|
||||||
|
|
||||||
def test_429_retry_on_next_hook(self):
|
def test_429_retry_on_next_hook(self):
|
||||||
|
from plugin.adapter import RocketChatRateLimitError
|
||||||
rest = _make_mock_rest()
|
rest = _make_mock_rest()
|
||||||
call_count = [0]
|
call_count = [0]
|
||||||
|
|
||||||
def _side_effect(*args, **kwargs):
|
def _side_effect(*args, **kwargs):
|
||||||
call_count[0] += 1
|
call_count[0] += 1
|
||||||
if call_count[0] == 1:
|
if call_count[0] == 1:
|
||||||
raise Exception("HTTP 429 Too Many Requests")
|
raise RocketChatRateLimitError("HTTP 429 Too Many Requests")
|
||||||
return {"success": True}
|
return {"success": True}
|
||||||
|
|
||||||
rest._request.side_effect = _side_effect
|
rest._request.side_effect = _side_effect
|
||||||
@@ -917,8 +921,9 @@ class TestHttp429Handling:
|
|||||||
assert call_count[0] == 2
|
assert call_count[0] == 2
|
||||||
|
|
||||||
def test_429_telemetry_counted(self):
|
def test_429_telemetry_counted(self):
|
||||||
|
from plugin.adapter import RocketChatRateLimitError
|
||||||
rest = _make_mock_rest()
|
rest = _make_mock_rest()
|
||||||
rest._request.side_effect = Exception("HTTP 429 Too Many Requests")
|
rest._request.side_effect = RocketChatRateLimitError("HTTP 429 Too Many Requests")
|
||||||
engine = _make_engine(rest=rest, away_grace_s=0.05)
|
engine = _make_engine(rest=rest, away_grace_s=0.05)
|
||||||
engine.on_pre_gateway_dispatch()
|
engine.on_pre_gateway_dispatch()
|
||||||
time.sleep(0.2)
|
time.sleep(0.2)
|
||||||
|
|||||||
@@ -0,0 +1,218 @@
|
|||||||
|
"""
|
||||||
|
WV-002: REST-Exception-Logging verfeinern (_rest_set_status).
|
||||||
|
|
||||||
|
Tests für:
|
||||||
|
- (a) Echter HTTP 429 → Cooldown + korrektes Logging (Typ + Message + Status-Code).
|
||||||
|
- (b) DDP-Timeout-Exception → KEIN Cooldown, korrekte Typ/Status-Logs.
|
||||||
|
- (c) Exception ohne HTTP-Code → kein 429-Cooldown (Phantom-429-Schutz).
|
||||||
|
|
||||||
|
Kern: Cooldown wird NUR bei echtem HTTP 429 (Status-Code-Prüfung) getriggert,
|
||||||
|
nicht bei beliebigen Exceptions mit '429' im Text.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sys
|
||||||
|
import urllib.error
|
||||||
|
from pathlib import Path
|
||||||
|
from unittest.mock import MagicMock, patch
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
|
||||||
|
|
||||||
|
from plugin.archivar.presence_engine import PresenceEngine
|
||||||
|
from plugin.adapter import RocketChatRateLimitError
|
||||||
|
|
||||||
|
|
||||||
|
def _make_mock_rest():
|
||||||
|
rest = MagicMock()
|
||||||
|
rest.auth_token = "test-token"
|
||||||
|
rest.user_id = "test-user"
|
||||||
|
rest._request = MagicMock()
|
||||||
|
return rest
|
||||||
|
|
||||||
|
|
||||||
|
def _make_engine(rest):
|
||||||
|
return PresenceEngine(rest=rest, use_ddp=False)
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
# (a) Echter HTTP 429 → Cooldown + korrektes Logging
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
class TestReal429Cooldown:
|
||||||
|
def test_http_error_429_triggers_cooldown(self):
|
||||||
|
"""Echter HTTPError(429) → Cooldown gesetzt, Telemetrie 429 inkrementiert."""
|
||||||
|
rest = _make_mock_rest()
|
||||||
|
rest._request = MagicMock(
|
||||||
|
side_effect=urllib.error.HTTPError(
|
||||||
|
"https://rocketchat/api/v1/users.setStatus", 429,
|
||||||
|
"Too Many Requests", {}, None,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
engine = _make_engine(rest)
|
||||||
|
|
||||||
|
result = engine._rest_set_status("online", "")
|
||||||
|
|
||||||
|
assert result is False
|
||||||
|
assert engine._telemetry_rest_429 == 1
|
||||||
|
assert engine._telemetry_rest_errors == 0
|
||||||
|
# Cooldown wurde gesetzt (Rückkanal)
|
||||||
|
assert engine._mediator._consecutive_429s == 1
|
||||||
|
assert engine._mediator._rest_cooldown_until > 0.0
|
||||||
|
|
||||||
|
def test_rate_limit_error_triggers_cooldown(self):
|
||||||
|
"""RocketChatRateLimitError → Cooldown gesetzt (per Definition 429)."""
|
||||||
|
rest = _make_mock_rest()
|
||||||
|
rest._request = MagicMock(side_effect=RocketChatRateLimitError("HTTP 429"))
|
||||||
|
engine = _make_engine(rest)
|
||||||
|
|
||||||
|
result = engine._rest_set_status("busy", "arbeitet")
|
||||||
|
|
||||||
|
assert result is False
|
||||||
|
assert engine._telemetry_rest_429 == 1
|
||||||
|
assert engine._mediator._consecutive_429s == 1
|
||||||
|
|
||||||
|
def test_429_logs_type_message_and_status(self):
|
||||||
|
"""429-Log enthält Exception-Typ, Message UND HTTP-Status-Code."""
|
||||||
|
import logging
|
||||||
|
from plugin.archivar import presence_engine as pe
|
||||||
|
rest = _make_mock_rest()
|
||||||
|
rest._request = MagicMock(
|
||||||
|
side_effect=urllib.error.HTTPError(
|
||||||
|
"https://rocketchat/api/v1/users.setStatus", 429,
|
||||||
|
"Too Many Requests", {}, None,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
engine = _make_engine(rest)
|
||||||
|
|
||||||
|
with patch.object(pe.logger, "warning") as mock_warn:
|
||||||
|
engine._rest_set_status("online", "")
|
||||||
|
|
||||||
|
# Mindestens ein Warning-Log mit '429' und 'HTTPError' (Exception-Typ)
|
||||||
|
logged = [str(c) for c in mock_warn.call_args_list]
|
||||||
|
assert any("429" in l for l in logged)
|
||||||
|
assert any("HTTPError" in l for l in logged), (
|
||||||
|
f"Erwartet Exception-Typ 'HTTPError' im Log, bekam: {logged}"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
# (b) DDP-Timeout-Exception → KEIN Cooldown
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
class TestDDPTimeoutNoCooldown:
|
||||||
|
def test_ddp_timeout_no_cooldown(self):
|
||||||
|
"""DDP-Timeout-Exception → KEIN Cooldown, KEIN 429-Telemetrie."""
|
||||||
|
rest = _make_mock_rest()
|
||||||
|
# DDP-Timeout: Exception mit '429' NICHT im Text, aber ein Timeout-Typ.
|
||||||
|
# Simuliere einen Timeout, der früher fälschlich als 429 klassifiziert
|
||||||
|
# werden konnte (z.B. wenn der Text '429' enthielt).
|
||||||
|
rest._request = MagicMock(side_effect=TimeoutError("DDP timeout after 1.0s"))
|
||||||
|
engine = _make_engine(rest)
|
||||||
|
|
||||||
|
result = engine._rest_set_status("online", "")
|
||||||
|
|
||||||
|
assert result is False
|
||||||
|
assert engine._telemetry_rest_429 == 0
|
||||||
|
assert engine._telemetry_rest_errors >= 1
|
||||||
|
# KEIN Cooldown
|
||||||
|
assert engine._mediator._consecutive_429s == 0
|
||||||
|
assert engine._mediator._rest_cooldown_until == 0.0
|
||||||
|
|
||||||
|
def test_phantom_429_in_text_no_cooldown(self):
|
||||||
|
"""Exception mit '429' im TEXT (aber kein HTTP-Code) → KEIN Cooldown.
|
||||||
|
|
||||||
|
Das ist der Kern des Phantom-429-Bugs: DDP-Timeouts und REST-Token-Errors
|
||||||
|
enthielten '429' im Text und wurden fälschlich als 429 klassifiziert.
|
||||||
|
"""
|
||||||
|
rest = _make_mock_rest()
|
||||||
|
rest._request = MagicMock(
|
||||||
|
side_effect=Exception("REST token error: request 429 rejected")
|
||||||
|
)
|
||||||
|
engine = _make_engine(rest)
|
||||||
|
|
||||||
|
result = engine._rest_set_status("online", "")
|
||||||
|
|
||||||
|
assert result is False
|
||||||
|
assert engine._telemetry_rest_429 == 0
|
||||||
|
assert engine._telemetry_rest_errors >= 1
|
||||||
|
assert engine._mediator._consecutive_429s == 0
|
||||||
|
assert engine._mediator._rest_cooldown_until == 0.0
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
# (c) Exception ohne HTTP-Code → kein 429-Cooldown
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
class TestNoHttpCodeNoCooldown:
|
||||||
|
def test_generic_exception_no_cooldown(self):
|
||||||
|
"""Generische Exception ohne HTTP-Code → kein 429-Cooldown."""
|
||||||
|
rest = _make_mock_rest()
|
||||||
|
rest._request = MagicMock(side_effect=ValueError("some error"))
|
||||||
|
engine = _make_engine(rest)
|
||||||
|
|
||||||
|
result = engine._rest_set_status("online", "")
|
||||||
|
|
||||||
|
assert result is False
|
||||||
|
assert engine._telemetry_rest_429 == 0
|
||||||
|
assert engine._mediator._consecutive_429s == 0
|
||||||
|
|
||||||
|
def test_http_500_no_cooldown(self):
|
||||||
|
"""HTTP 500 (kein 429) → kein 429-Cooldown, aber als Error gezählt."""
|
||||||
|
rest = _make_mock_rest()
|
||||||
|
rest._request = MagicMock(
|
||||||
|
side_effect=urllib.error.HTTPError(
|
||||||
|
"https://rocketchat/api/v1/users.setStatus", 500,
|
||||||
|
"Internal Server Error", {}, None,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
engine = _make_engine(rest)
|
||||||
|
|
||||||
|
result = engine._rest_set_status("online", "")
|
||||||
|
|
||||||
|
assert result is False
|
||||||
|
assert engine._telemetry_rest_429 == 0
|
||||||
|
assert engine._mediator._consecutive_429s == 0
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
# Helper-Unit-Tests: _extract_http_status_code / _is_http_429
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
class TestHttpStatusExtraction:
|
||||||
|
def test_extract_from_httperror(self):
|
||||||
|
exc = urllib.error.HTTPError("url", 429, "Too Many Requests", {}, None)
|
||||||
|
assert PresenceEngine._extract_http_status_code(exc) == 429
|
||||||
|
|
||||||
|
def test_extract_from_rate_limit_error(self):
|
||||||
|
exc = RocketChatRateLimitError("HTTP 429")
|
||||||
|
assert PresenceEngine._extract_http_status_code(exc) == 429
|
||||||
|
|
||||||
|
def test_extract_from_cause_chain(self):
|
||||||
|
cause = urllib.error.HTTPError("url", 429, "Too Many Requests", {}, None)
|
||||||
|
exc = RuntimeError("wrapped")
|
||||||
|
exc.__cause__ = cause
|
||||||
|
assert PresenceEngine._extract_http_status_code(exc) == 429
|
||||||
|
|
||||||
|
def test_extract_none_for_generic(self):
|
||||||
|
exc = ValueError("no code here")
|
||||||
|
assert PresenceEngine._extract_http_status_code(exc) is None
|
||||||
|
|
||||||
|
def test_extract_from_status_code_attr(self):
|
||||||
|
class FakeExc(Exception):
|
||||||
|
status_code = 503
|
||||||
|
assert PresenceEngine._extract_http_status_code(FakeExc()) == 503
|
||||||
|
|
||||||
|
def test_is_http_429_true_for_429(self):
|
||||||
|
assert PresenceEngine._is_http_429(ValueError("x"), 429) is True
|
||||||
|
|
||||||
|
def test_is_http_429_false_for_other(self):
|
||||||
|
assert PresenceEngine._is_http_429(ValueError("x"), 500) is False
|
||||||
|
|
||||||
|
def test_is_http_429_false_for_none(self):
|
||||||
|
assert PresenceEngine._is_http_429(ValueError("429 in text"), None) is False
|
||||||
|
|
||||||
|
def test_is_http_429_true_for_rate_limit_error(self):
|
||||||
|
assert PresenceEngine._is_http_429(RocketChatRateLimitError("x"), None) is True
|
||||||
@@ -0,0 +1,121 @@
|
|||||||
|
"""
|
||||||
|
F100 — Persistentes Cooldown-Flag für den Runtime-Watchdog-Alert (K3).
|
||||||
|
|
||||||
|
Verhindert Re-Alert-Spam: der Watchdog darf höchstens einmal pro
|
||||||
|
``LLM_ROOM_WATCHDOG_ALERT_COOLDOWN_S`` (Default 24h) einen Alert loggen.
|
||||||
|
Das Flag wird in ``~/.hermes/hermes-agent/data/routing_watchdog_alert.json``
|
||||||
|
persistiert (``last_alert_ts``) und überlebt damit Gateway-Restarts.
|
||||||
|
|
||||||
|
P-088-Lehre: Der Alert selbst ist ein ``logger.error(...)`` — KEIN RC-Post,
|
||||||
|
KEIN User-Spam. Dieses Modul stellt nur die Cooldown-Buchhaltung bereit.
|
||||||
|
|
||||||
|
Persistenz-Pattern: atomar via tmp+rename (P-101), best-effort (nie fatal).
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import time
|
||||||
|
from typing import Callable, Optional
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
# Persistenz-Pfad (analog ARCHIVAR_STATE_PATH / ADAPTIVE_TIMEOUT_STATE_PATH).
|
||||||
|
WATCHDOG_ALERT_STATE_PATH: str = os.path.expanduser(
|
||||||
|
os.getenv(
|
||||||
|
"ARCHIVAR_WATCHDOG_ALERT_STATE_PATH",
|
||||||
|
"~/.hermes/hermes-agent/data/routing_watchdog_alert.json",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class WatchdogAlertCooldown:
|
||||||
|
"""Persistentes Cooldown-Flag für den Runtime-Watchdog-Alert.
|
||||||
|
|
||||||
|
Thread-sicher über ein internes Lock. ``is_in_cooldown()`` prüft, ob seit
|
||||||
|
dem letzten Alert weniger als ``cooldown_s`` Sekunden vergangen sind.
|
||||||
|
``mark_alerted()`` setzt ``last_alert_ts`` auf jetzt und persistiert.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
cooldown_s: float = 86400.0,
|
||||||
|
state_path: Optional[str] = WATCHDOG_ALERT_STATE_PATH,
|
||||||
|
clock: Callable[[], float] = time.time,
|
||||||
|
) -> None:
|
||||||
|
import threading
|
||||||
|
|
||||||
|
self._cooldown_s = cooldown_s
|
||||||
|
self._state_path = state_path
|
||||||
|
self._clock = clock
|
||||||
|
self._lock = threading.Lock()
|
||||||
|
self._last_alert_ts: Optional[float] = None
|
||||||
|
if self._state_path:
|
||||||
|
self._load()
|
||||||
|
|
||||||
|
def is_in_cooldown(self, now: Optional[float] = None) -> bool:
|
||||||
|
"""True wenn der letzte Alert weniger als ``cooldown_s`` her ist."""
|
||||||
|
ref = self._clock() if now is None else now
|
||||||
|
with self._lock:
|
||||||
|
if self._last_alert_ts is None:
|
||||||
|
return False
|
||||||
|
return (ref - self._last_alert_ts) < self._cooldown_s
|
||||||
|
|
||||||
|
def mark_alerted(self, now: Optional[float] = None) -> None:
|
||||||
|
"""Setze ``last_alert_ts`` auf jetzt und persistiere (best-effort)."""
|
||||||
|
ref = self._clock() if now is None else now
|
||||||
|
with self._lock:
|
||||||
|
self._last_alert_ts = ref
|
||||||
|
self._save_locked()
|
||||||
|
|
||||||
|
@property
|
||||||
|
def last_alert_ts(self) -> Optional[float]:
|
||||||
|
with self._lock:
|
||||||
|
return self._last_alert_ts
|
||||||
|
|
||||||
|
# ── Persistenz (P-101: atomar via tmp+rename) ────────────────────────
|
||||||
|
|
||||||
|
def _save_locked(self) -> None:
|
||||||
|
if not self._state_path:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
data = {"last_alert_ts": self._last_alert_ts}
|
||||||
|
directory = os.path.dirname(self._state_path)
|
||||||
|
os.makedirs(directory, exist_ok=True)
|
||||||
|
tmp_path = self._state_path + ".tmp"
|
||||||
|
with open(tmp_path, "w", encoding="utf-8") as f:
|
||||||
|
json.dump(data, f, ensure_ascii=False)
|
||||||
|
os.replace(tmp_path, self._state_path)
|
||||||
|
except Exception as e: # Persistenz ist best-effort, nie fatal.
|
||||||
|
logger.warning("F100: Watchdog-Alert-Persistenz fehlgeschlagen: %s", e)
|
||||||
|
|
||||||
|
def _load(self) -> None:
|
||||||
|
if not self._state_path or not os.path.exists(self._state_path):
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
with open(self._state_path, "r", encoding="utf-8") as f:
|
||||||
|
data = json.load(f)
|
||||||
|
ts = data.get("last_alert_ts")
|
||||||
|
self._last_alert_ts = float(ts) if ts is not None else None
|
||||||
|
logger.info(
|
||||||
|
"F100: Watchdog-Alert-Cooldown geladen (last_alert_ts=%s)",
|
||||||
|
self._last_alert_ts,
|
||||||
|
)
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning("F100: Watchdog-Alert-State laden fehlgeschlagen: %s", e)
|
||||||
|
|
||||||
|
|
||||||
|
# Modul-Level-Singleton — wird von adapter.py importiert.
|
||||||
|
# Cooldown aus config.py (env-gesteuert), damit die Konstante die einzige
|
||||||
|
# Wahrheitsquelle ist (kein hartcodierter 86400-Default an zwei Stellen).
|
||||||
|
def _default_cooldown_s() -> float:
|
||||||
|
try:
|
||||||
|
from .config import LLM_ROOM_WATCHDOG_ALERT_COOLDOWN_S
|
||||||
|
return float(LLM_ROOM_WATCHDOG_ALERT_COOLDOWN_S)
|
||||||
|
except Exception:
|
||||||
|
return 86400.0
|
||||||
|
|
||||||
|
|
||||||
|
watchdog_alert_cooldown = WatchdogAlertCooldown(cooldown_s=_default_cooldown_s())
|
||||||
@@ -4,3 +4,5 @@ numpy>=1.24.0
|
|||||||
faiss-cpu>=1.7.4
|
faiss-cpu>=1.7.4
|
||||||
# F6: snowballstemmer replaces Eigenbau-Stemmer (Rainer review)
|
# F6: snowballstemmer replaces Eigenbau-Stemmer (Rainer review)
|
||||||
snowballstemmer>=3.0.0
|
snowballstemmer>=3.0.0
|
||||||
|
# F8: onboarding_state.py persistiert State als YAML (yaml.dump/safe_load)
|
||||||
|
PyYAML>=6.0
|
||||||
|
|||||||
@@ -0,0 +1,18 @@
|
|||||||
|
# Setup-Voraussetzungen (vom Wizard gelesen — F98 Flow-Spec §0.2)
|
||||||
|
# Format: modulname|pip_name|min_version|severity|required_if
|
||||||
|
# severity: HARD = muss da sein (Abbruch), SOFT = Auto-Install in Phase 7
|
||||||
|
# required_if (F98 P-178, Cascade-Matrix §3.3):
|
||||||
|
# always = IMMER installieren (Core, keine Bedingung)
|
||||||
|
# multiroom = nur wenn RC_MULTIROOM=true (FAISS/Embedding-Index)
|
||||||
|
# local_inf = nur wenn LOCAL_INFERENCE_AVAILABLE=true
|
||||||
|
#
|
||||||
|
# Diese Datei ist die EINE Wahrheits-Quelle für Installer-Voraussetzungen.
|
||||||
|
# Wenn ein neues Plugin-Feature ein Modul braucht, hier ergänzen — der
|
||||||
|
# Installer erkennt es automatisch, ohne dass install.sh angefasst wird.
|
||||||
|
|
||||||
|
faiss-cpu|faiss-cpu|1.7.4|SOFT|multiroom
|
||||||
|
numpy|numpy|1.24.0|SOFT|multiroom
|
||||||
|
snowballstemmer|snowballstemmer|2.2.0|SOFT|always
|
||||||
|
httpx|httpx|0.25.0|HARD|always
|
||||||
|
requests|requests|2.31.0|HARD|always
|
||||||
|
yaml|PyYAML|6.0|HARD|always
|
||||||
@@ -0,0 +1,279 @@
|
|||||||
|
"""
|
||||||
|
F98: compute_cascade() Decision-Matrix Tests (TDD).
|
||||||
|
|
||||||
|
Testet die zentrale Cascade-Funktion (Provider × Multiroom → Folgeaktionen)
|
||||||
|
aus Rainers Architektur-Konzept §3.3. Die Matrix ist die Single Source of Truth
|
||||||
|
für Ollama-Install, Modell-Pull und faiss/numpy-Install.
|
||||||
|
|
||||||
|
Matrix (verbindlich):
|
||||||
|
ollama + multiroom → Ollama JA, qwen2.5:7b + nomic-embed-text, faiss JA
|
||||||
|
ollama + single → Ollama JA, nomic-embed-text only, faiss NEIN
|
||||||
|
custom (DGX) + multiroom → Ollama NEIN, keine Modelle, faiss JA
|
||||||
|
custom (DGX) + single → Ollama NEIN, keine Modelle, faiss NEIN
|
||||||
|
openrouter + * → Ollama NEIN, keine Modelle, faiss nur multiroom
|
||||||
|
ollama-cloud + * → Ollama NEIN, keine Modelle, faiss nur multiroom
|
||||||
|
none + * → Ollama NEIN, keine Modelle, faiss nur multiroom
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import subprocess
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
|
||||||
|
INSTALL_SH = Path(__file__).resolve().parents[1] / "install.sh"
|
||||||
|
|
||||||
|
|
||||||
|
def _read_install_sh() -> str:
|
||||||
|
return INSTALL_SH.read_text()
|
||||||
|
|
||||||
|
|
||||||
|
def _extract_functions(*names: str) -> str:
|
||||||
|
"""Extrahiert Funktions-Definitionen (plus log-Helfer) aus install.sh,
|
||||||
|
OHNE den Hauptfluss auszuführen. Gibt ein bash-Snippet zurück."""
|
||||||
|
content = INSTALL_SH.read_text()
|
||||||
|
lines = content.splitlines()
|
||||||
|
|
||||||
|
def _find_func(name: str) -> tuple[int, int] | None:
|
||||||
|
start = None
|
||||||
|
for i, line in enumerate(lines):
|
||||||
|
if line.startswith(f"{name}()"):
|
||||||
|
start = i
|
||||||
|
break
|
||||||
|
if start is None:
|
||||||
|
return None
|
||||||
|
end = start
|
||||||
|
for j in range(start + 1, len(lines)):
|
||||||
|
if lines[j].strip() == "}":
|
||||||
|
end = j
|
||||||
|
break
|
||||||
|
return start, end
|
||||||
|
|
||||||
|
header_parts = []
|
||||||
|
for helper in ("mask_secrets", "log", "warn", "err", "ok", "banner", "die"):
|
||||||
|
r = _find_func(helper)
|
||||||
|
if r:
|
||||||
|
header_parts.append("\n".join(lines[r[0]:r[1] + 1]))
|
||||||
|
header = "C_RESET=''; C_BLUE=''; C_GREEN=''; C_YELLOW=''; C_RED=''; C_BOLD=''\n\n" + "\n\n".join(header_parts)
|
||||||
|
|
||||||
|
funcs = []
|
||||||
|
for name in names:
|
||||||
|
r = _find_func(name)
|
||||||
|
if r:
|
||||||
|
funcs.append("\n".join(lines[r[0]:r[1] + 1]))
|
||||||
|
return header + "\n\n" + "\n\n".join(funcs) + "\n"
|
||||||
|
|
||||||
|
|
||||||
|
def _run_cascade(provider: str, multiroom: str) -> tuple[str, str, int]:
|
||||||
|
"""Führt compute_cascade() mit gegebenem Provider/Multiroom aus und gibt
|
||||||
|
(stdout, stderr, rc) zurück."""
|
||||||
|
snippet = (
|
||||||
|
_extract_functions("effective_multiroom", "compute_cascade")
|
||||||
|
+ f"PROVIDER='{provider}'\n"
|
||||||
|
+ f"RC_MULTIROOM='{multiroom}'\n"
|
||||||
|
+ "compute_cascade\n"
|
||||||
|
+ "echo \"OLLAMA_INSTALL_REQUIRED=$OLLAMA_INSTALL_REQUIRED\"\n"
|
||||||
|
+ "echo \"FAISS_REQUIRED=$FAISS_REQUIRED\"\n"
|
||||||
|
+ "echo \"MODEL_PULL_REQUIRED=${MODEL_PULL_REQUIRED[*]}\"\n"
|
||||||
|
+ "echo \"ARCHIVAR_BASE_URL=$ARCHIVAR_BASE_URL\"\n"
|
||||||
|
)
|
||||||
|
env = {"PATH": "/usr/bin:/bin:/usr/local/bin", "HOME": "/tmp/f98-cascade-home"}
|
||||||
|
result = subprocess.run(
|
||||||
|
["bash", "-c", snippet],
|
||||||
|
capture_output=True, text=True, env=env, timeout=30,
|
||||||
|
)
|
||||||
|
return result.stdout, result.stderr, result.returncode
|
||||||
|
|
||||||
|
|
||||||
|
def _parse(out: str) -> dict:
|
||||||
|
d = {}
|
||||||
|
for line in out.splitlines():
|
||||||
|
if "=" in line and not line.startswith("Cascade:"):
|
||||||
|
k, v = line.split("=", 1)
|
||||||
|
d[k] = v
|
||||||
|
return d
|
||||||
|
|
||||||
|
|
||||||
|
class TestComputeCascadeMatrix:
|
||||||
|
"""Jede Zelle der Cascade-Matrix §3.3 wird explizit abgeklopft."""
|
||||||
|
|
||||||
|
def test_ollama_multiroom(self):
|
||||||
|
out, err, rc = _run_cascade("ollama", "true")
|
||||||
|
d = _parse(out)
|
||||||
|
assert rc == 0, f"compute_cascade crashte:\n{out}\n{err}"
|
||||||
|
assert d["OLLAMA_INSTALL_REQUIRED"] == "true"
|
||||||
|
assert d["FAISS_REQUIRED"] == "true"
|
||||||
|
assert "qwen2.5:7b" in d["MODEL_PULL_REQUIRED"]
|
||||||
|
assert "nomic-embed-text" in d["MODEL_PULL_REQUIRED"]
|
||||||
|
# B15: lokales Ollama → Archivar zeigt auf localhost:11434
|
||||||
|
assert d["ARCHIVAR_BASE_URL"] == "http://localhost:11434"
|
||||||
|
|
||||||
|
def test_ollama_single(self):
|
||||||
|
out, err, rc = _run_cascade("ollama", "false")
|
||||||
|
d = _parse(out)
|
||||||
|
assert rc == 0
|
||||||
|
assert d["OLLAMA_INSTALL_REQUIRED"] == "true"
|
||||||
|
assert d["FAISS_REQUIRED"] == "false"
|
||||||
|
assert "nomic-embed-text" in d["MODEL_PULL_REQUIRED"]
|
||||||
|
assert "qwen2.5:7b" not in d["MODEL_PULL_REQUIRED"]
|
||||||
|
|
||||||
|
def test_custom_dgx_multiroom(self):
|
||||||
|
out, err, rc = _run_cascade("custom", "true")
|
||||||
|
d = _parse(out)
|
||||||
|
assert rc == 0
|
||||||
|
assert d["OLLAMA_INSTALL_REQUIRED"] == "false"
|
||||||
|
assert d["FAISS_REQUIRED"] == "true"
|
||||||
|
assert d["MODEL_PULL_REQUIRED"] == ""
|
||||||
|
|
||||||
|
def test_custom_dgx_single(self):
|
||||||
|
out, err, rc = _run_cascade("custom", "false")
|
||||||
|
d = _parse(out)
|
||||||
|
assert rc == 0
|
||||||
|
assert d["OLLAMA_INSTALL_REQUIRED"] == "false"
|
||||||
|
assert d["FAISS_REQUIRED"] == "false"
|
||||||
|
assert d["MODEL_PULL_REQUIRED"] == ""
|
||||||
|
|
||||||
|
def test_openrouter_multiroom(self):
|
||||||
|
out, err, rc = _run_cascade("openrouter", "true")
|
||||||
|
d = _parse(out)
|
||||||
|
assert rc == 0
|
||||||
|
assert d["OLLAMA_INSTALL_REQUIRED"] == "false"
|
||||||
|
assert d["FAISS_REQUIRED"] == "true"
|
||||||
|
assert d["MODEL_PULL_REQUIRED"] == ""
|
||||||
|
|
||||||
|
def test_openrouter_single(self):
|
||||||
|
out, err, rc = _run_cascade("openrouter", "false")
|
||||||
|
d = _parse(out)
|
||||||
|
assert rc == 0
|
||||||
|
assert d["OLLAMA_INSTALL_REQUIRED"] == "false"
|
||||||
|
assert d["FAISS_REQUIRED"] == "false"
|
||||||
|
assert d["MODEL_PULL_REQUIRED"] == ""
|
||||||
|
|
||||||
|
def test_ollama_cloud_multiroom(self):
|
||||||
|
out, err, rc = _run_cascade("ollama-cloud", "true")
|
||||||
|
d = _parse(out)
|
||||||
|
assert rc == 0
|
||||||
|
assert d["OLLAMA_INSTALL_REQUIRED"] == "false"
|
||||||
|
assert d["FAISS_REQUIRED"] == "true"
|
||||||
|
assert d["MODEL_PULL_REQUIRED"] == ""
|
||||||
|
|
||||||
|
def test_ollama_cloud_single(self):
|
||||||
|
out, err, rc = _run_cascade("ollama-cloud", "false")
|
||||||
|
d = _parse(out)
|
||||||
|
assert rc == 0
|
||||||
|
assert d["OLLAMA_INSTALL_REQUIRED"] == "false"
|
||||||
|
assert d["FAISS_REQUIRED"] == "false"
|
||||||
|
assert d["MODEL_PULL_REQUIRED"] == ""
|
||||||
|
|
||||||
|
def test_none_multiroom(self):
|
||||||
|
out, err, rc = _run_cascade("none", "true")
|
||||||
|
d = _parse(out)
|
||||||
|
assert rc == 0
|
||||||
|
assert d["OLLAMA_INSTALL_REQUIRED"] == "false"
|
||||||
|
assert d["FAISS_REQUIRED"] == "true"
|
||||||
|
assert d["MODEL_PULL_REQUIRED"] == ""
|
||||||
|
|
||||||
|
def test_none_single(self):
|
||||||
|
out, err, rc = _run_cascade("none", "false")
|
||||||
|
d = _parse(out)
|
||||||
|
assert rc == 0
|
||||||
|
assert d["OLLAMA_INSTALL_REQUIRED"] == "false"
|
||||||
|
assert d["FAISS_REQUIRED"] == "false"
|
||||||
|
assert d["MODEL_PULL_REQUIRED"] == ""
|
||||||
|
|
||||||
|
|
||||||
|
class TestCascadeIntegration:
|
||||||
|
"""Strukturelle Invarianten: die drei unkonditionalen Stellen sind jetzt
|
||||||
|
conditional auf die Cascade-Flags."""
|
||||||
|
|
||||||
|
def test_compute_cascade_function_exists(self):
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert "compute_cascade()" in content
|
||||||
|
|
||||||
|
def test_effective_multiroom_function_exists(self):
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert "effective_multiroom()" in content
|
||||||
|
|
||||||
|
def test_archivar_base_url_remote_provider(self):
|
||||||
|
"""B15: Remote-Provider (custom/DGX) → ARCHIVAR_BASE_URL = Provider-URL."""
|
||||||
|
snippet = (
|
||||||
|
_extract_functions("effective_multiroom", "compute_cascade")
|
||||||
|
+ "PROVIDER='custom'\n"
|
||||||
|
+ "PROVIDER_BASE_URL='http://192.168.180.46:7999/v1'\n"
|
||||||
|
+ "RC_MULTIROOM='true'\n"
|
||||||
|
+ "compute_cascade\n"
|
||||||
|
+ "echo \"ARCHIVAR_BASE_URL=$ARCHIVAR_BASE_URL\"\n"
|
||||||
|
)
|
||||||
|
env = {"PATH": "/usr/bin:/bin:/usr/local/bin", "HOME": "/tmp/f98-cascade-home"}
|
||||||
|
result = subprocess.run(
|
||||||
|
["bash", "-c", snippet],
|
||||||
|
capture_output=True, text=True, env=env, timeout=30,
|
||||||
|
)
|
||||||
|
assert result.returncode == 0, f"compute_cascade crashte:\n{result.stdout}\n{result.stderr}"
|
||||||
|
assert "ARCHIVAR_BASE_URL=http://192.168.180.46:7999/v1" in result.stdout
|
||||||
|
|
||||||
|
def test_archivar_base_url_cloud_provider_fallback(self):
|
||||||
|
"""B15: Cloud-Provider ohne PROVIDER_BASE_URL → Fallback localhost."""
|
||||||
|
snippet = (
|
||||||
|
_extract_functions("effective_multiroom", "compute_cascade")
|
||||||
|
+ "PROVIDER='openrouter'\n"
|
||||||
|
+ "PROVIDER_BASE_URL=''\n"
|
||||||
|
+ "RC_MULTIROOM='true'\n"
|
||||||
|
+ "compute_cascade\n"
|
||||||
|
+ "echo \"ARCHIVAR_BASE_URL=$ARCHIVAR_BASE_URL\"\n"
|
||||||
|
)
|
||||||
|
env = {"PATH": "/usr/bin:/bin:/usr/local/bin", "HOME": "/tmp/f98-cascade-home"}
|
||||||
|
result = subprocess.run(
|
||||||
|
["bash", "-c", snippet],
|
||||||
|
capture_output=True, text=True, env=env, timeout=30,
|
||||||
|
)
|
||||||
|
assert result.returncode == 0
|
||||||
|
assert "ARCHIVAR_BASE_URL=http://localhost:11434" in result.stdout
|
||||||
|
|
||||||
|
def test_ollama_install_conditional(self):
|
||||||
|
"""install_system_deps: Ollama-Block in `if $OLLAMA_INSTALL_REQUIRED`."""
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert "OLLAMA_INSTALL_REQUIRED" in content
|
||||||
|
# Der Ollama-Install-Block muss conditional sein.
|
||||||
|
assert "if $OLLAMA_INSTALL_REQUIRED; then" in content
|
||||||
|
|
||||||
|
def test_model_pull_uses_array(self):
|
||||||
|
"""Hauptfluss iteriert über MODEL_PULL_REQUIRED, nicht hardcoded Liste."""
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert 'for m in "${MODEL_PULL_REQUIRED[@]}"' in content
|
||||||
|
# Die alte hardcoded Schleife darf nicht mehr im Hauptfluss stehen.
|
||||||
|
assert 'for m in qwen2.5:7b nomic-embed-text; do' not in content
|
||||||
|
|
||||||
|
def test_install_python_deps_function_exists(self):
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert "install_python_deps()" in content
|
||||||
|
|
||||||
|
def test_no_python3_pip_in_wizard_phase7(self):
|
||||||
|
"""P-179: Phase 7 nutzt kein `python3 -m pip install` mehr."""
|
||||||
|
content = _read_install_sh()
|
||||||
|
# Nur noch der pipx-Fallback in install_system_deps darf python3 -m pip nutzen.
|
||||||
|
# Der Wizard-Phase-7-Block darf es nicht mehr.
|
||||||
|
assert "python3 -m pip install --quiet" not in content
|
||||||
|
|
||||||
|
def test_loginctl_timeout(self):
|
||||||
|
"""P-182: loginctl enable-linger mit timeout 10."""
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert "timeout 10 sudo loginctl enable-linger" in content
|
||||||
|
|
||||||
|
def test_no_naked_secret_refs(self):
|
||||||
|
"""P-177 A2: keine nackten `[ -z "$VAR" ]` Secret-Refs mehr."""
|
||||||
|
import re
|
||||||
|
content = _read_install_sh()
|
||||||
|
# Nackte Secret-Refs (ohne ${VAR:-}) dürfen nicht mehr existieren.
|
||||||
|
assert not re.search(r'\[ -z "\$[A-Z_]+(_KEY|_PASSWORD|_USER_ID)"', content)
|
||||||
|
|
||||||
|
def test_setup_requirements_has_required_if(self):
|
||||||
|
"""P-178: setup_requirements.txt hat required_if-Spalte."""
|
||||||
|
req = Path(__file__).resolve().parents[1] / "setup_requirements.txt"
|
||||||
|
content = req.read_text()
|
||||||
|
assert "required_if" in content
|
||||||
|
assert "faiss-cpu|faiss-cpu|1.7.4|SOFT|multiroom" in content
|
||||||
|
assert "numpy|numpy|1.24.0|SOFT|multiroom" in content
|
||||||
|
assert "snowballstemmer|snowballstemmer|2.2.0|SOFT|always" in content
|
||||||
@@ -0,0 +1,293 @@
|
|||||||
|
"""
|
||||||
|
F98-I2: B16 State-Konsistenz (effective_multiroom) + B20 systemd-Machine-Fix Tests.
|
||||||
|
|
||||||
|
Testet die Iteration-2-Fixes aus Rainers Architektur-Review:
|
||||||
|
1. B16: effective_multiroom() liest Multiroom-Wahrheit aus EINER Quelle
|
||||||
|
(env MULTIROOM_AGENT → .env → RC_MULTIROOM → Default true).
|
||||||
|
2. B20: gateway_systemctl_v2() nutzt im sudo-Kontext --machine=<user>@.host.
|
||||||
|
3. B18: check_components() setzt REPAIR_UNIT_MISSING bei fehlender Unit.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import subprocess
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
|
||||||
|
INSTALL_SH = Path(__file__).resolve().parents[1] / "install.sh"
|
||||||
|
|
||||||
|
|
||||||
|
def _read_install_sh() -> str:
|
||||||
|
return INSTALL_SH.read_text()
|
||||||
|
|
||||||
|
|
||||||
|
def _extract_functions(*names: str) -> str:
|
||||||
|
"""Extrahiert Funktions-Definitionen (plus log-Helfer) aus install.sh."""
|
||||||
|
content = INSTALL_SH.read_text()
|
||||||
|
lines = content.splitlines()
|
||||||
|
|
||||||
|
def _find_func(name: str) -> tuple[int, int] | None:
|
||||||
|
start = None
|
||||||
|
for i, line in enumerate(lines):
|
||||||
|
if line.startswith(f"{name}()"):
|
||||||
|
start = i
|
||||||
|
break
|
||||||
|
if start is None:
|
||||||
|
return None
|
||||||
|
end = start
|
||||||
|
for j in range(start + 1, len(lines)):
|
||||||
|
if lines[j].strip() == "}":
|
||||||
|
end = j
|
||||||
|
break
|
||||||
|
return start, end
|
||||||
|
|
||||||
|
header_parts = []
|
||||||
|
for helper in ("mask_secrets", "log", "warn", "err", "ok", "banner", "die"):
|
||||||
|
r = _find_func(helper)
|
||||||
|
if r:
|
||||||
|
header_parts.append("\n".join(lines[r[0]:r[1] + 1]))
|
||||||
|
header = "C_RESET=''; C_BLUE=''; C_GREEN=''; C_YELLOW=''; C_RED=''; C_BOLD=''\n\n" + "\n\n".join(header_parts)
|
||||||
|
|
||||||
|
funcs = []
|
||||||
|
for name in names:
|
||||||
|
r = _find_func(name)
|
||||||
|
if r:
|
||||||
|
funcs.append("\n".join(lines[r[0]:r[1] + 1]))
|
||||||
|
return header + "\n\n" + "\n\n".join(funcs) + "\n"
|
||||||
|
|
||||||
|
|
||||||
|
def _run_bash(snippet: str, extra_env: dict | None = None) -> tuple[str, str, int]:
|
||||||
|
env = {
|
||||||
|
"PATH": "/usr/bin:/bin:/usr/local/bin",
|
||||||
|
"HOME": "/tmp/f98-i2-home",
|
||||||
|
}
|
||||||
|
if extra_env:
|
||||||
|
env.update(extra_env)
|
||||||
|
result = subprocess.run(
|
||||||
|
["bash", "-c", snippet],
|
||||||
|
capture_output=True, text=True, env=env, timeout=30,
|
||||||
|
)
|
||||||
|
return result.stdout, result.stderr, result.returncode
|
||||||
|
|
||||||
|
|
||||||
|
class TestEffectiveMultiroom:
|
||||||
|
"""B16: effective_multiroom() — eine Wahrheitsquelle für Multiroom."""
|
||||||
|
|
||||||
|
def test_env_multiroom_agent_wins(self):
|
||||||
|
snippet = (
|
||||||
|
_extract_functions("effective_multiroom")
|
||||||
|
+ "MULTIROOM_AGENT='false'\n"
|
||||||
|
+ "RC_MULTIROOM='true'\n"
|
||||||
|
+ "echo \"RESULT=$(effective_multiroom)\"\n"
|
||||||
|
)
|
||||||
|
out, err, rc = _run_bash(snippet)
|
||||||
|
assert rc == 0, f"effective_multiroom crashte:\n{out}\n{err}"
|
||||||
|
assert "RESULT=false" in out, f"env MULTIROOM_AGENT=false sollte gewinnen:\n{out}"
|
||||||
|
|
||||||
|
def test_dotenv_multiroom_agent_wins_over_rc(self):
|
||||||
|
"""MULTIROOM_AGENT=false in .env gewinnt über RC_MULTIROOM=true."""
|
||||||
|
import tempfile, os
|
||||||
|
with tempfile.TemporaryDirectory() as d:
|
||||||
|
hermes_dir = os.path.join(d, ".hermes")
|
||||||
|
os.makedirs(hermes_dir)
|
||||||
|
envfile = os.path.join(hermes_dir, ".env")
|
||||||
|
with open(envfile, "w") as f:
|
||||||
|
f.write("MULTIROOM_AGENT=false\n")
|
||||||
|
snippet = (
|
||||||
|
_extract_functions("effective_multiroom")
|
||||||
|
+ f"HOME='{d}'\n"
|
||||||
|
+ "RC_MULTIROOM='true'\n"
|
||||||
|
+ "echo \"RESULT=$(effective_multiroom)\"\n"
|
||||||
|
)
|
||||||
|
out, err, rc = _run_bash(snippet)
|
||||||
|
assert rc == 0
|
||||||
|
assert "RESULT=false" in out, f".env MULTIROOM_AGENT=false sollte gewinnen:\n{out}\n{err}"
|
||||||
|
|
||||||
|
def test_rc_multiroom_used_when_no_env(self):
|
||||||
|
snippet = (
|
||||||
|
_extract_functions("effective_multiroom")
|
||||||
|
+ "RC_MULTIROOM='false'\n"
|
||||||
|
+ "echo \"RESULT=$(effective_multiroom)\"\n"
|
||||||
|
)
|
||||||
|
out, err, rc = _run_bash(snippet)
|
||||||
|
assert rc == 0
|
||||||
|
assert "RESULT=false" in out, f"RC_MULTIROOM=false sollte gewinnen:\n{out}"
|
||||||
|
|
||||||
|
def test_default_true_when_nothing_set(self):
|
||||||
|
snippet = (
|
||||||
|
_extract_functions("effective_multiroom")
|
||||||
|
+ "echo \"RESULT=$(effective_multiroom)\"\n"
|
||||||
|
)
|
||||||
|
out, err, rc = _run_bash(snippet)
|
||||||
|
assert rc == 0
|
||||||
|
assert "RESULT=true" in out, f"Default sollte true sein:\n{out}"
|
||||||
|
|
||||||
|
|
||||||
|
class TestGatewaySystemctlV2:
|
||||||
|
"""B20: gateway_systemctl_v2() — Cross-User-fähiger systemctl-Wrapper."""
|
||||||
|
|
||||||
|
def test_function_exists(self):
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert "gateway_systemctl_v2()" in content
|
||||||
|
|
||||||
|
def test_uses_machine_transport(self):
|
||||||
|
"""Der Machine-Transport --machine=<user>@.host muss im Code stehen."""
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert "--machine=" in content
|
||||||
|
assert "@.host" in content
|
||||||
|
|
||||||
|
def test_derives_sudo_user(self):
|
||||||
|
"""SUDO_USER-Ableitung muss vorhanden sein."""
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert "SUDO_USER" in content
|
||||||
|
|
||||||
|
def test_non_root_uses_plain_user(self):
|
||||||
|
"""Nicht-root: systemctl --user (kein Machine-Transport)."""
|
||||||
|
# Simuliere nicht-root: id -u liefert 1000, USER=bernd.
|
||||||
|
import tempfile, os
|
||||||
|
fake_id = "#!/bin/bash\nif [ \"$1\" = \"-u\" ]; then echo 1000; exit 0; fi\nexit 0\n"
|
||||||
|
fake_systemctl = "#!/bin/bash\necho \"ARGS=$*\"\n"
|
||||||
|
with tempfile.TemporaryDirectory() as d:
|
||||||
|
id_path = os.path.join(d, "id")
|
||||||
|
sc_path = os.path.join(d, "systemctl")
|
||||||
|
with open(id_path, "w") as f:
|
||||||
|
f.write(fake_id)
|
||||||
|
with open(sc_path, "w") as f:
|
||||||
|
f.write(fake_systemctl)
|
||||||
|
os.chmod(id_path, 0o755)
|
||||||
|
os.chmod(sc_path, 0o755)
|
||||||
|
snippet = (
|
||||||
|
_extract_functions("gateway_systemctl_v2")
|
||||||
|
+ "USER='bernd'\n"
|
||||||
|
+ "gateway_systemctl_v2 is-active hermes-gateway\n"
|
||||||
|
)
|
||||||
|
out, err, rc = _run_bash(snippet, extra_env={"PATH": f"{d}:/usr/bin:/bin"})
|
||||||
|
# Nicht-root → systemctl --user is-active hermes-gateway
|
||||||
|
assert "--user" in out, f"Nicht-root sollte --user nutzen:\n{out}\n{err}"
|
||||||
|
assert "--machine=" not in out, f"Nicht-root darf keinen Machine-Transport nutzen:\n{out}"
|
||||||
|
|
||||||
|
def test_root_uses_machine_transport(self):
|
||||||
|
"""Root + SUDO_USER → --machine=<user>@.host --user."""
|
||||||
|
import tempfile, os
|
||||||
|
fake_id = "#!/bin/bash\nif [ \"$1\" = \"-u\" ]; then echo 0; exit 0; fi\nexit 0\n"
|
||||||
|
fake_systemctl = "#!/bin/bash\necho \"ARGS=$*\"\n"
|
||||||
|
with tempfile.TemporaryDirectory() as d:
|
||||||
|
id_path = os.path.join(d, "id")
|
||||||
|
sc_path = os.path.join(d, "systemctl")
|
||||||
|
with open(id_path, "w") as f:
|
||||||
|
f.write(fake_id)
|
||||||
|
with open(sc_path, "w") as f:
|
||||||
|
f.write(fake_systemctl)
|
||||||
|
os.chmod(id_path, 0o755)
|
||||||
|
os.chmod(sc_path, 0o755)
|
||||||
|
snippet = (
|
||||||
|
_extract_functions("gateway_systemctl_v2")
|
||||||
|
+ "USER='root'\n"
|
||||||
|
+ "SUDO_USER='bernd'\n"
|
||||||
|
+ "gateway_systemctl_v2 is-active hermes-gateway\n"
|
||||||
|
)
|
||||||
|
out, err, rc = _run_bash(snippet, extra_env={"PATH": f"{d}:/usr/bin:/bin"})
|
||||||
|
assert "--machine=bernd@.host" in out, f"Root sollte Machine-Transport nutzen:\n{out}\n{err}"
|
||||||
|
assert "--user" in out, f"Root sollte --user behalten:\n{out}"
|
||||||
|
|
||||||
|
|
||||||
|
class TestRepairUnitMissing:
|
||||||
|
"""B18: check_components() setzt REPAIR_UNIT_MISSING bei fehlender Unit."""
|
||||||
|
|
||||||
|
def test_repair_unit_missing_flag_declared(self):
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert "REPAIR_UNIT_MISSING" in content
|
||||||
|
|
||||||
|
def test_check_components_checks_unit_file(self):
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert "hermes-gateway.service" in content
|
||||||
|
assert "Stufe 8" in content
|
||||||
|
|
||||||
|
def test_repair_components_has_stage_8(self):
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert "Reparatur Stufe 8" in content
|
||||||
|
|
||||||
|
|
||||||
|
class TestAskWithHelp:
|
||||||
|
"""B9/B10/B11: ask_with_help() — [H]-Hilfe + J/N-Konsistenz."""
|
||||||
|
|
||||||
|
def test_ask_with_help_function_exists(self):
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert "ask_with_help()" in content
|
||||||
|
|
||||||
|
def test_ask_with_help_yes(self):
|
||||||
|
snippet = (
|
||||||
|
_extract_functions("ask_with_help")
|
||||||
|
+ "GUIDED_DEFAULTS=false\n"
|
||||||
|
+ "LANG_CHOICE='de'\n"
|
||||||
|
+ "declare -A T\n"
|
||||||
|
+ "T[de_ask_suffix]=' [J/N/H]: '\n"
|
||||||
|
+ "ask_with_help MY_VAR 'Frage?' 'false' 'Hilfetext' <<< 'J'\n"
|
||||||
|
+ "echo \"MY_VAR=$MY_VAR\"\n"
|
||||||
|
)
|
||||||
|
out, err, rc = _run_bash(snippet)
|
||||||
|
assert rc == 0, f"ask_with_help crashte:\n{out}\n{err}"
|
||||||
|
assert "MY_VAR=true" in out, f"J sollte true setzen:\n{out}"
|
||||||
|
|
||||||
|
def test_ask_with_help_no(self):
|
||||||
|
snippet = (
|
||||||
|
_extract_functions("ask_with_help")
|
||||||
|
+ "GUIDED_DEFAULTS=false\n"
|
||||||
|
+ "LANG_CHOICE='de'\n"
|
||||||
|
+ "declare -A T\n"
|
||||||
|
+ "T[de_ask_suffix]=' [J/N/H]: '\n"
|
||||||
|
+ "ask_with_help MY_VAR 'Frage?' 'true' 'Hilfetext' <<< 'N'\n"
|
||||||
|
+ "echo \"MY_VAR=$MY_VAR\"\n"
|
||||||
|
)
|
||||||
|
out, err, rc = _run_bash(snippet)
|
||||||
|
assert rc == 0
|
||||||
|
assert "MY_VAR=false" in out, f"N sollte false setzen:\n{out}"
|
||||||
|
|
||||||
|
def test_ask_with_help_shows_help_then_accepts(self):
|
||||||
|
"""H zeigt Hilfe, dann J wird akzeptiert."""
|
||||||
|
snippet = (
|
||||||
|
_extract_functions("ask_with_help")
|
||||||
|
+ "GUIDED_DEFAULTS=false\n"
|
||||||
|
+ "LANG_CHOICE='de'\n"
|
||||||
|
+ "declare -A T\n"
|
||||||
|
+ "T[de_ask_suffix]=' [J/N/H]: '\n"
|
||||||
|
+ "ask_with_help MY_VAR 'Frage?' 'false' 'HILFETEXT-MARKER' <<< $'H\\nJ'\n"
|
||||||
|
+ "echo \"MY_VAR=$MY_VAR\"\n"
|
||||||
|
)
|
||||||
|
out, err, rc = _run_bash(snippet)
|
||||||
|
assert rc == 0
|
||||||
|
assert "HILFETEXT-MARKER" in out, f"H sollte Hilfe zeigen:\n{out}\n{err}"
|
||||||
|
assert "MY_VAR=true" in out, f"J nach H sollte true setzen:\n{out}"
|
||||||
|
|
||||||
|
def test_ask_with_help_default_on_empty(self):
|
||||||
|
snippet = (
|
||||||
|
_extract_functions("ask_with_help")
|
||||||
|
+ "GUIDED_DEFAULTS=false\n"
|
||||||
|
+ "LANG_CHOICE='de'\n"
|
||||||
|
+ "declare -A T\n"
|
||||||
|
+ "T[de_ask_suffix]=' [J/N/H]: '\n"
|
||||||
|
+ "ask_with_help MY_VAR 'Frage?' 'true' 'Hilfetext' <<< ''\n"
|
||||||
|
+ "echo \"MY_VAR=$MY_VAR\"\n"
|
||||||
|
)
|
||||||
|
out, err, rc = _run_bash(snippet)
|
||||||
|
assert rc == 0
|
||||||
|
assert "MY_VAR=true" in out, f"Default sollte bei leerer Eingabe greifen:\n{out}"
|
||||||
|
|
||||||
|
def test_language_pack_has_help_keys(self):
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert "T[de_multiroom_help]" in content
|
||||||
|
assert "T[en_multiroom_help]" in content
|
||||||
|
assert "T[de_profile_help]" in content
|
||||||
|
assert "T[en_profile_help]" in content
|
||||||
|
assert "T[de_ask_suffix]" in content
|
||||||
|
assert "T[en_ask_suffix]" in content
|
||||||
|
|
||||||
|
def test_de_uses_jn_not_yn(self):
|
||||||
|
"""B11: DE-Dialoge nutzen J)/N(), nicht Y)/N()."""
|
||||||
|
content = _read_install_sh()
|
||||||
|
# Der DE-Multiroom-Text darf kein Y) mehr enthalten.
|
||||||
|
assert "J) Ja" in content
|
||||||
|
# EN behält Y/N (korrekt).
|
||||||
|
assert "Y) Yes" in content
|
||||||
@@ -0,0 +1,266 @@
|
|||||||
|
"""
|
||||||
|
F98-I3: B22 Aktivitätsindikator + B23 dynamische LLM-Auswahl Tests.
|
||||||
|
|
||||||
|
Testet die Iteration-3-Fixes aus Andreas' Re-Test (01.09.):
|
||||||
|
1. B22: run_activity() — Fortschritts-Anzeige [~]→[+]→[-] für lange Schritte
|
||||||
|
(insb. `hermes gateway install`). Andreas' Terminal-Abbruch war Folge
|
||||||
|
fehlender Anzeige.
|
||||||
|
2. B23: fetch_available_models()/preferred_models()/resolve_model()/select_model()
|
||||||
|
— dynamische LLM-Auswahl statt hartcodiertem `nemotron-3-super` (P-175).
|
||||||
|
Provider-abhängig: bei Remote-Provider (DGX/Ollama-Cloud) KEINE lokalen
|
||||||
|
Modelle abfragen (P-180/P-181).
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import subprocess
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
|
||||||
|
INSTALL_SH = Path(__file__).resolve().parents[1] / "install.sh"
|
||||||
|
|
||||||
|
|
||||||
|
def _read_install_sh() -> str:
|
||||||
|
return INSTALL_SH.read_text()
|
||||||
|
|
||||||
|
|
||||||
|
def _extract_functions(*names: str) -> str:
|
||||||
|
"""Extrahiert Funktions-Definitionen (plus log-Helfer) aus install.sh,
|
||||||
|
OHNE den Hauptfluss auszuführen. Gibt ein bash-Snippet zurück."""
|
||||||
|
content = INSTALL_SH.read_text()
|
||||||
|
lines = content.splitlines()
|
||||||
|
|
||||||
|
def _find_func(name: str) -> tuple[int, int] | None:
|
||||||
|
start = None
|
||||||
|
for i, line in enumerate(lines):
|
||||||
|
if line.startswith(f"{name}()"):
|
||||||
|
start = i
|
||||||
|
break
|
||||||
|
if start is None:
|
||||||
|
return None
|
||||||
|
end = start
|
||||||
|
for j in range(start + 1, len(lines)):
|
||||||
|
if lines[j].strip() == "}":
|
||||||
|
end = j
|
||||||
|
break
|
||||||
|
return start, end
|
||||||
|
|
||||||
|
header_parts = []
|
||||||
|
for helper in ("mask_secrets", "log", "warn", "err", "ok", "banner", "die", "ask"):
|
||||||
|
r = _find_func(helper)
|
||||||
|
if r:
|
||||||
|
header_parts.append("\n".join(lines[r[0]:r[1] + 1]))
|
||||||
|
header = "C_RESET=''; C_BLUE=''; C_GREEN=''; C_YELLOW=''; C_RED=''; C_BOLD=''\n\n" + "\n\n".join(header_parts)
|
||||||
|
|
||||||
|
funcs = []
|
||||||
|
for name in names:
|
||||||
|
r = _find_func(name)
|
||||||
|
if r:
|
||||||
|
funcs.append("\n".join(lines[r[0]:r[1] + 1]))
|
||||||
|
return header + "\n\n" + "\n\n".join(funcs) + "\n"
|
||||||
|
|
||||||
|
|
||||||
|
def _run_bash(snippet: str, extra_env: dict | None = None) -> tuple[str, str, int]:
|
||||||
|
env = {
|
||||||
|
"PATH": "/usr/bin:/bin:/usr/local/bin",
|
||||||
|
"HOME": "/tmp/f98-i3-home",
|
||||||
|
}
|
||||||
|
if extra_env:
|
||||||
|
env.update(extra_env)
|
||||||
|
result = subprocess.run(
|
||||||
|
["bash", "-c", snippet],
|
||||||
|
capture_output=True, text=True, env=env, timeout=30,
|
||||||
|
)
|
||||||
|
return result.stdout, result.stderr, result.returncode
|
||||||
|
|
||||||
|
|
||||||
|
class TestB22RunActivity:
|
||||||
|
"""B22: run_activity() — Fortschritts-Anzeige für lange Schritte."""
|
||||||
|
|
||||||
|
def test_run_activity_function_exists(self):
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert "run_activity()" in content
|
||||||
|
|
||||||
|
def test_run_activity_success_returns_zero(self):
|
||||||
|
snippet = (
|
||||||
|
_extract_functions("run_activity")
|
||||||
|
+ "DRY_RUN=false\n"
|
||||||
|
+ "run_activity 'test-cmd' true\n"
|
||||||
|
+ "echo \"RC=$?\"\n"
|
||||||
|
)
|
||||||
|
out, err, rc = _run_bash(snippet)
|
||||||
|
assert rc == 0, f"run_activity crashte:\n{out}\n{err}"
|
||||||
|
assert "RC=0" in out, f"true sollte rc=0 liefern:\n{out}"
|
||||||
|
|
||||||
|
def test_run_activity_failure_returns_nonzero(self):
|
||||||
|
snippet = (
|
||||||
|
_extract_functions("run_activity")
|
||||||
|
+ "DRY_RUN=false\n"
|
||||||
|
+ "run_activity 'test-cmd' false\n"
|
||||||
|
+ "echo \"RC=$?\"\n"
|
||||||
|
)
|
||||||
|
out, err, rc = _run_bash(snippet)
|
||||||
|
assert rc == 0
|
||||||
|
assert "RC=1" in out, f"false sollte rc=1 liefern:\n{out}"
|
||||||
|
|
||||||
|
def test_run_activity_dry_run_prints_only(self):
|
||||||
|
snippet = (
|
||||||
|
_extract_functions("run_activity")
|
||||||
|
+ "DRY_RUN=true\n"
|
||||||
|
+ "run_activity 'test-cmd' echo hello\n"
|
||||||
|
)
|
||||||
|
out, err, rc = _run_bash(snippet)
|
||||||
|
assert rc == 0
|
||||||
|
assert "[dry]" in out, f"dry-run sollte [dry] ausgeben:\n{out}"
|
||||||
|
|
||||||
|
def test_run_activity_uses_spinner_chars(self):
|
||||||
|
"""B22: Spinner-Zeichen [~]→[+]→[-] müssen im Code stehen."""
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert "'~'" in content
|
||||||
|
assert "'+'" in content
|
||||||
|
assert "'-'" in content
|
||||||
|
|
||||||
|
def test_gateway_install_uses_run_activity(self):
|
||||||
|
"""B22: `hermes gateway install` muss run_activity nutzen (nicht nackt)."""
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert 'run_activity "hermes gateway install"' in content
|
||||||
|
# Der nackte Aufruf ohne run_activity darf nicht mehr existieren.
|
||||||
|
assert 'if ! "$VENV_PY" -m hermes_cli.main gateway install; then' not in content
|
||||||
|
|
||||||
|
def test_ollama_pull_uses_run_activity(self):
|
||||||
|
"""B22: ollama pull im Hauptfluss nutzt run_activity (kein tail-Pipe)."""
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert 'run_activity "ollama pull $m" ollama pull "$m"' in content
|
||||||
|
# Der alte tail-Pipe (maskiert Exit-Code, P-109) darf nicht mehr stehen.
|
||||||
|
assert 'ollama pull "$m" 2>&1 | tail -1' not in content
|
||||||
|
|
||||||
|
|
||||||
|
class TestB23DynamicModelSelection:
|
||||||
|
"""B23: dynamische LLM-Auswahl statt hartcodiertem Default (P-175)."""
|
||||||
|
|
||||||
|
def test_no_hardcoded_default_model(self):
|
||||||
|
"""B23: KEIN hartcodiertes nemotron-3-super als Default mehr."""
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert 'DEFAULT_MODEL_NAME="nemotron-3-super"' not in content
|
||||||
|
assert 'MODEL_NAME="${MODEL_NAME:-$DEFAULT_MODEL_NAME}"' not in content
|
||||||
|
|
||||||
|
def test_fetch_available_models_function_exists(self):
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert "fetch_available_models()" in content
|
||||||
|
|
||||||
|
def test_preferred_models_function_exists(self):
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert "preferred_models()" in content
|
||||||
|
|
||||||
|
def test_resolve_model_function_exists(self):
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert "resolve_model()" in content
|
||||||
|
|
||||||
|
def test_select_model_function_exists(self):
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert "select_model()" in content
|
||||||
|
|
||||||
|
def test_fetch_available_models_provider_dependent(self):
|
||||||
|
"""B23/P-180/181: Remote-Provider fragen KEINE lokalen Modelle ab."""
|
||||||
|
content = _read_install_sh()
|
||||||
|
# ollama → lokale /api/tags
|
||||||
|
assert "http://localhost:11434/api/tags" in content
|
||||||
|
# custom → Provider-Base-URL /models (DGX), NICHT localhost
|
||||||
|
assert '${base_url%/}/models' in content
|
||||||
|
# ollama-cloud → ollama.com/v1/models (Remote)
|
||||||
|
assert "https://ollama.com/v1/models" in content
|
||||||
|
|
||||||
|
def test_preferred_models_ollama(self):
|
||||||
|
snippet = (
|
||||||
|
_extract_functions("preferred_models")
|
||||||
|
+ "preferred_models ollama\n"
|
||||||
|
)
|
||||||
|
out, err, rc = _run_bash(snippet)
|
||||||
|
assert rc == 0
|
||||||
|
assert "qwen2.5:7b" in out
|
||||||
|
|
||||||
|
def test_preferred_models_custom(self):
|
||||||
|
snippet = (
|
||||||
|
_extract_functions("preferred_models")
|
||||||
|
+ "preferred_models custom\n"
|
||||||
|
)
|
||||||
|
out, err, rc = _run_bash(snippet)
|
||||||
|
assert rc == 0
|
||||||
|
assert "deepseek-v4-flash" in out
|
||||||
|
|
||||||
|
def test_preferred_models_none_empty(self):
|
||||||
|
snippet = (
|
||||||
|
_extract_functions("preferred_models")
|
||||||
|
+ "preferred_models none\n"
|
||||||
|
)
|
||||||
|
out, err, rc = _run_bash(snippet)
|
||||||
|
assert rc == 0
|
||||||
|
assert out.strip() == ""
|
||||||
|
|
||||||
|
def test_resolve_model_preference_match(self):
|
||||||
|
"""B23: resolve_model wählt den ersten Präferenz-Treffer."""
|
||||||
|
snippet = (
|
||||||
|
_extract_functions("fetch_available_models", "preferred_models", "resolve_model")
|
||||||
|
+ "fetch_available_models() { printf 'deepseek-v4-flash\\ndeepseek-v4-pro\\nqwen3\\n'; }\n"
|
||||||
|
+ "resolve_model custom 'http://x/v1' ''\n"
|
||||||
|
)
|
||||||
|
out, err, rc = _run_bash(snippet)
|
||||||
|
assert rc == 0
|
||||||
|
assert "deepseek-v4-flash" in out
|
||||||
|
|
||||||
|
def test_resolve_model_no_preference_falls_back_to_first(self):
|
||||||
|
snippet = (
|
||||||
|
_extract_functions("fetch_available_models", "preferred_models", "resolve_model")
|
||||||
|
+ "fetch_available_models() { printf 'foo-model\\nbar-model\\n'; }\n"
|
||||||
|
+ "resolve_model custom 'http://x/v1' ''\n"
|
||||||
|
)
|
||||||
|
out, err, rc = _run_bash(snippet)
|
||||||
|
assert rc == 0
|
||||||
|
assert "foo-model" in out
|
||||||
|
|
||||||
|
def test_resolve_model_empty_returns_empty(self):
|
||||||
|
snippet = (
|
||||||
|
_extract_functions("fetch_available_models", "preferred_models", "resolve_model")
|
||||||
|
+ "fetch_available_models() { :; }\n"
|
||||||
|
+ "resolve_model custom 'http://x/v1' ''\n"
|
||||||
|
)
|
||||||
|
out, err, rc = _run_bash(snippet)
|
||||||
|
assert rc == 0
|
||||||
|
assert out.strip() == ""
|
||||||
|
|
||||||
|
def test_select_model_guided_defaults_sets_model(self):
|
||||||
|
"""B23: select_model im GUIDED_DEFAULTS-Modus setzt MODEL_NAME dynamisch."""
|
||||||
|
snippet = (
|
||||||
|
_extract_functions("fetch_available_models", "preferred_models", "resolve_model", "select_model")
|
||||||
|
+ "GUIDED_DEFAULTS=true\n"
|
||||||
|
+ "fetch_available_models() { printf 'deepseek-v4-flash\\ndeepseek-v4-pro\\n'; }\n"
|
||||||
|
+ "select_model custom 'http://x/v1' ''\n"
|
||||||
|
+ "echo \"MODEL_NAME=$MODEL_NAME\"\n"
|
||||||
|
)
|
||||||
|
out, err, rc = _run_bash(snippet)
|
||||||
|
assert rc == 0
|
||||||
|
assert "MODEL_NAME=deepseek-v4-flash" in out
|
||||||
|
|
||||||
|
def test_select_model_no_models_manual_fallback(self):
|
||||||
|
"""B23: keine Modelle → manuelle Eingabe (kein hartcodiertes Default)."""
|
||||||
|
snippet = (
|
||||||
|
_extract_functions("fetch_available_models", "preferred_models", "resolve_model", "select_model")
|
||||||
|
+ "GUIDED_DEFAULTS=true\n"
|
||||||
|
+ "fetch_available_models() { :; }\n"
|
||||||
|
+ "select_model custom 'http://x/v1' ''\n"
|
||||||
|
)
|
||||||
|
out, err, rc = _run_bash(snippet)
|
||||||
|
assert rc == 0
|
||||||
|
assert "Modell-Abfrage fehlgeschlagen" in out
|
||||||
|
|
||||||
|
def test_wizard_has_model_selection_phase(self):
|
||||||
|
"""B23: Wizard ruft select_model auf (Phase 5.5)."""
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert "select_model \"$PROVIDER\"" in content
|
||||||
|
|
||||||
|
def test_main_flow_resolves_model_dynamically(self):
|
||||||
|
"""B23: Hauptfluss nutzt resolve_model als non-interactive Fallback."""
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert 'MODEL_NAME="$(resolve_model "$PROVIDER"' in content
|
||||||
@@ -0,0 +1,561 @@
|
|||||||
|
"""
|
||||||
|
F98: Guided Setup Wizard — install.sh Tests (TDD).
|
||||||
|
|
||||||
|
Testet die F98-Wizard-Schicht (additiv zu install.sh):
|
||||||
|
1. Provider-Freiheit: KEIN hardcoded provider=ollama-cloud (Root-Cause A)
|
||||||
|
2. Provider-Detection P1-P6 (detect_provider)
|
||||||
|
3. Layout-Detection (detect_install_layout)
|
||||||
|
4. Key-Zwang entschärft (Root-Cause D): KEIN `die "Abbruch: erforderliche Secrets fehlen"`
|
||||||
|
bei lokaler Inference
|
||||||
|
5. Wizard-Flags (--guided/--defaults/--resume) geparst
|
||||||
|
6. Sprach-Pack (DE/EN) vorhanden
|
||||||
|
7. Secret-Maskierung (mask_secrets)
|
||||||
|
8. setup_requirements.txt als Single Source of Truth
|
||||||
|
9. Selbsterklärend-Regel: Ausweich-Optionen (SKIP), kein Abbruch ohne Cloud-Key
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import re
|
||||||
|
import subprocess
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
|
||||||
|
INSTALL_SH = Path(__file__).resolve().parents[1] / "install.sh"
|
||||||
|
SETUP_REQ = Path(__file__).resolve().parents[1] / "setup_requirements.txt"
|
||||||
|
|
||||||
|
|
||||||
|
def _read_install_sh() -> str:
|
||||||
|
return INSTALL_SH.read_text()
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
# Test 1: Syntax
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
|
||||||
|
class TestInstallShSyntax:
|
||||||
|
def test_bash_syntax_ok(self):
|
||||||
|
if not INSTALL_SH.exists():
|
||||||
|
pytest.skip("install.sh nicht gefunden")
|
||||||
|
result = subprocess.run(
|
||||||
|
["bash", "-n", str(INSTALL_SH)],
|
||||||
|
capture_output=True, text=True,
|
||||||
|
)
|
||||||
|
assert result.returncode == 0, f"bash -n failed:\n{result.stderr}"
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
# Test 2: Provider-Freiheit (Root-Cause A) — kein hardcoded ollama-cloud
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
|
||||||
|
class TestProviderFreedom:
|
||||||
|
def test_no_hardcoded_provider_ollama_cloud(self):
|
||||||
|
"""write_config_yaml darf KEIN `local provider="ollama-cloud"` mehr haben."""
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert 'local provider="ollama-cloud"' not in content, (
|
||||||
|
"hardcoded provider=ollama-cloud noch vorhanden (Root-Cause A)"
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_detect_provider_function_exists(self):
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert "detect_provider()" in content, "detect_provider() fehlt"
|
||||||
|
|
||||||
|
def test_detect_provider_has_p1_p6(self):
|
||||||
|
"""Detection-Reihenfolge P1-P6 muss vorhanden sein."""
|
||||||
|
content = _read_install_sh()
|
||||||
|
for marker in ["P1", "P2", "P3", "P4", "P6"]:
|
||||||
|
assert marker in content, f"Detection-Marker {marker} fehlt"
|
||||||
|
|
||||||
|
def test_detect_provider_local_ollama_no_key(self):
|
||||||
|
"""P1 (lokales Ollama) → provider=ollama, KEIN Key."""
|
||||||
|
content = _read_install_sh()
|
||||||
|
# P1-Block muss PROVIDER=ollama + PROVIDER_NEEDS_KEY=false setzen
|
||||||
|
assert "PROVIDER=\"ollama\"" in content
|
||||||
|
assert "PROVIDER_NEEDS_KEY=false" in content
|
||||||
|
|
||||||
|
def test_verify_installation_provider_compare_not_string_equality(self):
|
||||||
|
"""verify_installation nutzt Provider-Vergleich, nicht String-Gleichheit (Root-Cause I)."""
|
||||||
|
content = _read_install_sh()
|
||||||
|
# Der alte hardcoded Check `grep -q "^ provider: ollama-cloud"` darf nicht mehr da sein
|
||||||
|
assert 'grep -q "^ provider: ollama-cloud"' not in content, (
|
||||||
|
"verify_installation prüft noch hardcoded ollama-cloud (Root-Cause I)"
|
||||||
|
)
|
||||||
|
# Neuer Provider-Vergleich (case mit gültigen Providern)
|
||||||
|
assert "ollama|custom|openrouter|ollama-cloud" in content
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
# Test 3: Key-Zwang entschärft (Root-Cause D)
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
|
||||||
|
class TestNoKeyCoercion:
|
||||||
|
def test_no_die_abort_secrets_missing(self):
|
||||||
|
"""KEIN `die "Abbruch: erforderliche Secrets fehlen"` mehr (Root-Cause D)."""
|
||||||
|
content = _read_install_sh()
|
||||||
|
# Der alte Hardabort (exakt diese die-Zeile) darf nicht mehr existieren.
|
||||||
|
# Der neue die-Aufruf enthält den Zusatz "(oder nutze --guided)".
|
||||||
|
assert 'die "Abbruch: erforderliche Secrets fehlen"\n' not in content, (
|
||||||
|
"Key-Zwang-Hardabort noch vorhanden (Root-Cause D)"
|
||||||
|
)
|
||||||
|
# Der neue die-Aufruf verweist auf --guided (Ausweich statt Abbruch).
|
||||||
|
assert 'die "Abbruch: erforderliche Secrets fehlen (oder nutze --guided)"' in content
|
||||||
|
|
||||||
|
def test_cloud_key_only_for_cloud_provider(self):
|
||||||
|
"""Cloud-Key NUR bei Cloud-Provider (ollama-cloud/openrouter)."""
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert 'PROVIDER" = "ollama-cloud"' in content or 'PROVIDER" = "ollama-cloud"' in content
|
||||||
|
assert "OPENROUTER_API_KEY fehlt" in content
|
||||||
|
|
||||||
|
def test_guided_skips_password_userid_check(self):
|
||||||
|
"""Im Guided-Modus werden Password/User-ID im Dialog abgefragt, nicht erzwungen."""
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert "if ! $GUIDED; then" in content
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
# Test 4: Wizard-Flags
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
|
||||||
|
class TestWizardFlags:
|
||||||
|
def test_guided_flag_parsed(self):
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert "--guided) GUIDED=true" in content
|
||||||
|
|
||||||
|
def test_defaults_flag_parsed(self):
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert "--defaults) GUIDED_DEFAULTS=true" in content
|
||||||
|
|
||||||
|
def test_resume_flag_parsed(self):
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert "--resume) RESUME=true" in content
|
||||||
|
|
||||||
|
def test_guided_flag_declared(self):
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert "GUIDED=false" in content
|
||||||
|
assert "GUIDED_DEFAULTS=false" in content
|
||||||
|
assert "RESUME=false" in content
|
||||||
|
|
||||||
|
def test_run_guided_wizard_function_exists(self):
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert "run_guided_wizard()" in content
|
||||||
|
|
||||||
|
def test_wizard_dispatched_in_main_flow(self):
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert "if $GUIDED; then" in content
|
||||||
|
assert "run_guided_wizard" in content
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
# Test 5: Sprach-Pack (DE/EN)
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
|
||||||
|
class TestLanguagePack:
|
||||||
|
def test_language_pack_declared(self):
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert "declare -A T" in content
|
||||||
|
|
||||||
|
def test_de_en_strings_present(self):
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert "T[de_lang_q]" in content
|
||||||
|
assert "T[en_lang_q]" in content
|
||||||
|
assert "T[de_multiroom_q]" in content
|
||||||
|
assert "T[en_multiroom_q]" in content
|
||||||
|
|
||||||
|
def test_language_selection_phase0(self):
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert "LANG_CHOICE" in content
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
# Test 6: Secret-Maskierung
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
|
||||||
|
class TestSecretMasking:
|
||||||
|
def test_mask_secrets_function_exists(self):
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert "mask_secrets()" in content
|
||||||
|
|
||||||
|
def test_mask_secrets_filters_keys(self):
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert "OPENROUTER_API_KEY" in content
|
||||||
|
assert "OLLAMA_CLOUD_API_KEY" in content
|
||||||
|
assert "ROCKETCHAT_PASSWORD" in content
|
||||||
|
assert "***masked***" in content
|
||||||
|
|
||||||
|
def test_password_read_silent(self):
|
||||||
|
"""Kennwort-Eingabe nutzt read -s (unsichtbar)."""
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert "read -rs" in content or "read -s" in content
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
# Test 7: setup_requirements.txt (Single Source of Truth)
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
|
||||||
|
class TestSetupRequirements:
|
||||||
|
def test_setup_requirements_exists(self):
|
||||||
|
assert SETUP_REQ.exists(), "setup_requirements.txt fehlt"
|
||||||
|
|
||||||
|
def test_setup_requirements_format(self):
|
||||||
|
"""Format: modulname|pip_name|min_version|severity|required_if (F98 P-178)."""
|
||||||
|
for line in SETUP_REQ.read_text().splitlines():
|
||||||
|
line = line.strip()
|
||||||
|
if not line or line.startswith("#"):
|
||||||
|
continue
|
||||||
|
parts = line.split("|")
|
||||||
|
assert len(parts) == 5, f"Zeile hat nicht 5 Felder: {line}"
|
||||||
|
assert parts[3] in ("HARD", "SOFT"), f"severity ungültig: {line}"
|
||||||
|
assert parts[4] in ("always", "multiroom", "local_inf"), (
|
||||||
|
f"required_if ungültig: {line}"
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_wizard_reads_setup_requirements(self):
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert "setup_requirements.txt" in content
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
# Test 8: Selbsterklärend-Regel (Ausweich-Optionen, kein Abbruch)
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
|
||||||
|
class TestSelfExplainingRule:
|
||||||
|
def test_skip_option_present(self):
|
||||||
|
"""Ausweich-Option 'SKIP' (Später konfigurieren) vorhanden."""
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert "SKIP" in content
|
||||||
|
|
||||||
|
def test_allow_skip_parameter(self):
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert "allow_skip" in content
|
||||||
|
|
||||||
|
def test_p6_recommendation_block_no_abort(self):
|
||||||
|
"""P6 (nichts erkannt) → Empfehlungs-Block, KEIN Abbruch."""
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert "Empfohlene Reihenfolge" in content
|
||||||
|
|
||||||
|
def test_missing_requirements_collected(self):
|
||||||
|
"""Defizite werden gesammelt (MISSING_REQUIREMENTS), nicht einzeln abgebrochen."""
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert "MISSING_REQUIREMENTS" in content
|
||||||
|
|
||||||
|
def test_backup_dir_p164(self):
|
||||||
|
"""Backup vor schreibender Phase (P-164)."""
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert "hermes-install-backup" in content
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
# Test 9: Layout-Detection (V1.3-korrigiert §7.7)
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
|
||||||
|
class TestLayoutDetection:
|
||||||
|
def test_detect_install_layout_exists(self):
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert "detect_install_layout()" in content
|
||||||
|
|
||||||
|
def test_layout_values(self):
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert "root_fhs" in content
|
||||||
|
assert "pipx" in content
|
||||||
|
assert "user_space" in content
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
# Test 10: Proof-Run + Abschluss (Phase 10/11)
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
|
||||||
|
class TestProofAndSummary:
|
||||||
|
def test_proof_run_function_exists(self):
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert "run_proof_and_summary()" in content
|
||||||
|
|
||||||
|
def test_proof_checks_gateway_and_health(self):
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert "gateway_is_active" in content
|
||||||
|
assert "/health" in content
|
||||||
|
|
||||||
|
def test_nachhol_liste(self):
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert "Nachhol-Liste" in content
|
||||||
|
|
||||||
|
def test_resume_repair_hints(self):
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert "--guided --resume" in content
|
||||||
|
assert "--repair" in content
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
# Test 11: Verhaltens-Tests (nicht String-Grep) — führen die Funktionen aus.
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
|
||||||
|
def _extract_functions(*names: str) -> str:
|
||||||
|
"""Extrahiert die Funktions-Definitionen (plus log-Helfer + Farben) aus
|
||||||
|
install.sh, OHNE den Hauptfluss auszuführen. Gibt ein bash-Snippet zurück,
|
||||||
|
das in einer Subshell gesourced werden kann.
|
||||||
|
"""
|
||||||
|
content = INSTALL_SH.read_text()
|
||||||
|
lines = content.splitlines()
|
||||||
|
|
||||||
|
def _find_func(name: str) -> tuple[int, int] | None:
|
||||||
|
start = None
|
||||||
|
for i, line in enumerate(lines):
|
||||||
|
if line.startswith(f"{name}()"):
|
||||||
|
start = i
|
||||||
|
break
|
||||||
|
if start is None:
|
||||||
|
return None
|
||||||
|
end = start
|
||||||
|
for j in range(start + 1, len(lines)):
|
||||||
|
if lines[j].strip() == "}":
|
||||||
|
end = j
|
||||||
|
break
|
||||||
|
return start, end
|
||||||
|
|
||||||
|
# log-Helfer: die Funktions-Definitionen direkt suchen.
|
||||||
|
header_parts = []
|
||||||
|
for helper in ("mask_secrets", "log", "warn", "err", "ok", "banner", "die"):
|
||||||
|
r = _find_func(helper)
|
||||||
|
if r:
|
||||||
|
header_parts.append("\n".join(lines[r[0]:r[1] + 1]))
|
||||||
|
# Farben: leer lassen (unset Variablen expandieren zu "" ohne set -u).
|
||||||
|
header = "C_RESET=''; C_BLUE=''; C_GREEN=''; C_YELLOW=''; C_RED=''; C_BOLD=''\n\n" + "\n\n".join(header_parts)
|
||||||
|
|
||||||
|
funcs = []
|
||||||
|
for name in names:
|
||||||
|
r = _find_func(name)
|
||||||
|
if r:
|
||||||
|
funcs.append("\n".join(lines[r[0]:r[1] + 1]))
|
||||||
|
return header + "\n\n" + "\n\n".join(funcs) + "\n"
|
||||||
|
|
||||||
|
|
||||||
|
def _run_bash(snippet: str, extra_env: dict | None = None) -> tuple[str, str, int]:
|
||||||
|
"""Führt ein bash-Snippet in einer isolierten Subshell aus."""
|
||||||
|
env = {
|
||||||
|
"PATH": "/usr/bin:/bin:/usr/local/bin",
|
||||||
|
"HOME": "/tmp/f98-test-home",
|
||||||
|
}
|
||||||
|
if extra_env:
|
||||||
|
env.update(extra_env)
|
||||||
|
result = subprocess.run(
|
||||||
|
["bash", "-c", snippet],
|
||||||
|
capture_output=True, text=True, env=env, timeout=30,
|
||||||
|
)
|
||||||
|
return result.stdout, result.stderr, result.returncode
|
||||||
|
|
||||||
|
|
||||||
|
class TestDetectProviderBehavior:
|
||||||
|
"""detect_provider() muss tatsächlich die richtigen Variablen setzen."""
|
||||||
|
|
||||||
|
def test_p1_local_ollama_sets_provider(self):
|
||||||
|
# Simuliere lokales Ollama: curl auf localhost:11434 liefert 200.
|
||||||
|
import tempfile, os
|
||||||
|
fake_curl = "#!/bin/bash\nif [[ \"$*\" == *\"localhost:11434\"* ]]; then exit 0; fi\nexit 1\n"
|
||||||
|
with tempfile.TemporaryDirectory() as d:
|
||||||
|
curl_path = os.path.join(d, "curl")
|
||||||
|
with open(curl_path, "w") as f:
|
||||||
|
f.write(fake_curl)
|
||||||
|
os.chmod(curl_path, 0o755)
|
||||||
|
snippet = (
|
||||||
|
_extract_functions("detect_provider")
|
||||||
|
+ "detect_provider\n"
|
||||||
|
+ "echo \"PROVIDER=$PROVIDER\"\n"
|
||||||
|
+ "echo \"NEEDS_KEY=$PROVIDER_NEEDS_KEY\"\n"
|
||||||
|
+ "echo \"DETECTED=$DETECTED_PROVIDER\"\n"
|
||||||
|
+ "echo \"LOCAL=$LOCAL_INFERENCE_AVAILABLE\"\n"
|
||||||
|
)
|
||||||
|
out, err, rc = _run_bash(snippet, extra_env={"PATH": f"{d}:/usr/bin:/bin"})
|
||||||
|
assert "PROVIDER=ollama" in out, f"P1 sollte provider=ollama setzen:\n{out}\n{err}"
|
||||||
|
assert "NEEDS_KEY=false" in out, f"P1 braucht keinen Key:\n{out}"
|
||||||
|
assert "DETECTED=P1" in out, f"P1 sollte DETECTED_PROVIDER=P1 setzen:\n{out}"
|
||||||
|
assert "LOCAL=true" in out, f"P1 ist lokale Inference:\n{out}"
|
||||||
|
|
||||||
|
def test_p6_nothing_detected_sets_none(self):
|
||||||
|
# Kein Ollama, kein DGX, keine env-Keys → P6, provider=none, KEIN Abbruch.
|
||||||
|
import tempfile, os
|
||||||
|
fake_curl = "#!/bin/bash\nexit 1\n"
|
||||||
|
with tempfile.TemporaryDirectory() as d:
|
||||||
|
curl_path = os.path.join(d, "curl")
|
||||||
|
with open(curl_path, "w") as f:
|
||||||
|
f.write(fake_curl)
|
||||||
|
os.chmod(curl_path, 0o755)
|
||||||
|
snippet = (
|
||||||
|
_extract_functions("detect_provider")
|
||||||
|
+ "detect_provider\n"
|
||||||
|
+ "echo \"PROVIDER=$PROVIDER\"\n"
|
||||||
|
+ "echo \"DETECTED=$DETECTED_PROVIDER\"\n"
|
||||||
|
)
|
||||||
|
out, err, rc = _run_bash(snippet, extra_env={"PATH": f"{d}:/usr/bin:/bin"})
|
||||||
|
assert "PROVIDER=none" in out, f"P6 sollte provider=none setzen:\n{out}\n{err}"
|
||||||
|
assert "DETECTED=P6" in out, f"P6 sollte DETECTED_PROVIDER=P6 setzen:\n{out}"
|
||||||
|
assert rc == 0, "P6 darf NICHT abbrechen"
|
||||||
|
|
||||||
|
|
||||||
|
class TestMaskSecretsBehavior:
|
||||||
|
"""mask_secrets() muss Secrets tatsächlich maskieren."""
|
||||||
|
|
||||||
|
def test_mask_secrets_masks_known_keys(self):
|
||||||
|
snippet = (
|
||||||
|
_extract_functions("mask_secrets")
|
||||||
|
+ "OPENROUTER_API_KEY='sk-secret-123'\n"
|
||||||
|
+ "OLLAMA_CLOUD_API_KEY='cloud-secret-456'\n"
|
||||||
|
+ "ROCKETCHAT_PASSWORD='pw-secret-789'\n"
|
||||||
|
+ "echo \"$(mask_secrets 'key=sk-secret-123 pw=pw-secret-789')\"\n"
|
||||||
|
)
|
||||||
|
out, err, rc = _run_bash(snippet)
|
||||||
|
assert "sk-secret-123" not in out, f"OPENROUTER_API_KEY nicht maskiert:\n{out}\n{err}"
|
||||||
|
assert "pw-secret-789" not in out, f"ROCKETCHAT_PASSWORD nicht maskiert:\n{out}"
|
||||||
|
assert "***masked***" in out, f"Maskierung fehlt:\n{out}"
|
||||||
|
|
||||||
|
|
||||||
|
class TestMarkPhaseBehavior:
|
||||||
|
"""mark_phase()/read_install_state() müssen State persistieren."""
|
||||||
|
|
||||||
|
def test_mark_and_read_phase_roundtrip(self):
|
||||||
|
import tempfile, os
|
||||||
|
with tempfile.TemporaryDirectory() as d:
|
||||||
|
state_file = os.path.join(d, "state.json")
|
||||||
|
snippet = (
|
||||||
|
_extract_functions("mark_phase", "read_install_state")
|
||||||
|
+ f"INSTALL_STATE_FILE='{state_file}'\n"
|
||||||
|
+ "mark_phase 5 'rc-verbindung'\n"
|
||||||
|
+ "INSTALL_PHASE_LAST_DONE=0\n"
|
||||||
|
+ "read_install_state\n"
|
||||||
|
+ "echo \"PHASE=$INSTALL_PHASE_LAST_DONE\"\n"
|
||||||
|
)
|
||||||
|
out, err, rc = _run_bash(snippet)
|
||||||
|
assert "PHASE=5" in out, f"State-Roundtrip fehlgeschlagen:\n{out}\n{err}"
|
||||||
|
|
||||||
|
|
||||||
|
class TestPhaseDoneBehavior:
|
||||||
|
"""phase_done() muss die --resume-Skip-Logik korrekt treiben."""
|
||||||
|
|
||||||
|
def test_phase_done_true_when_phase_completed(self):
|
||||||
|
snippet = (
|
||||||
|
_extract_functions("phase_done")
|
||||||
|
+ "INSTALL_PHASE_LAST_DONE=5\n"
|
||||||
|
+ "if phase_done 4; then echo 'SKIP_4=yes'; else echo 'SKIP_4=no'; fi\n"
|
||||||
|
+ "if phase_done 5; then echo 'SKIP_5=yes'; else echo 'SKIP_5=no'; fi\n"
|
||||||
|
+ "if phase_done 6; then echo 'SKIP_6=yes'; else echo 'SKIP_6=no'; fi\n"
|
||||||
|
)
|
||||||
|
out, err, rc = _run_bash(snippet)
|
||||||
|
assert "SKIP_4=yes" in out, f"Phase 4 sollte übersprungen werden:\n{out}\n{err}"
|
||||||
|
assert "SKIP_5=yes" in out, f"Phase 5 (== last_done) sollte übersprungen werden:\n{out}"
|
||||||
|
assert "SKIP_6=no" in out, f"Phase 6 (> last_done) darf NICHT übersprungen werden:\n{out}"
|
||||||
|
|
||||||
|
def test_phase_done_false_when_no_state(self):
|
||||||
|
snippet = (
|
||||||
|
_extract_functions("phase_done")
|
||||||
|
+ "INSTALL_PHASE_LAST_DONE=0\n"
|
||||||
|
+ "if phase_done 1; then echo 'SKIP=yes'; else echo 'SKIP=no'; fi\n"
|
||||||
|
)
|
||||||
|
out, err, rc = _run_bash(snippet)
|
||||||
|
assert "SKIP=no" in out, f"Phase 1 darf bei last_done=0 nicht übersprungen werden:\n{out}\n{err}"
|
||||||
|
|
||||||
|
def test_mark_phase_called_after_every_phase(self):
|
||||||
|
"""Jede Phase 0-9 muss einen mark_phase-Aufruf haben (Skip-Logik-Voraussetzung)."""
|
||||||
|
content = _read_install_sh()
|
||||||
|
import re
|
||||||
|
# mark_phase N "label" — N von 0 bis 9
|
||||||
|
calls = re.findall(r"mark_phase\s+(\d+)\s+\"", content)
|
||||||
|
phases = {int(n) for n in calls}
|
||||||
|
assert phases == set(range(0, 10)), (
|
||||||
|
f"mark_phase fehlt für Phasen: {sorted(set(range(0,10)) - phases)}"
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_phase_done_guard_wraps_each_phase(self):
|
||||||
|
"""Jede Phase 1-8 muss einen `if phase_done N`-Skip-Guard haben."""
|
||||||
|
content = _read_install_sh()
|
||||||
|
import re
|
||||||
|
guards = {int(n) for n in re.findall(r"if phase_done (\d+); then", content)}
|
||||||
|
assert guards == set(range(1, 9)), (
|
||||||
|
f"phase_done-Guard fehlt für Phasen: {sorted(set(range(1,9)) - guards)}"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class TestAskBehavior:
|
||||||
|
"""ask() muss Default/Ausweich/SKIP korrekt setzen (nicht nur String-Grep)."""
|
||||||
|
|
||||||
|
def test_ask_uses_default_on_empty_input(self):
|
||||||
|
snippet = (
|
||||||
|
_extract_functions("ask")
|
||||||
|
+ "GUIDED_DEFAULTS=false\n"
|
||||||
|
+ "ask MY_VAR 'Frage?' 'default-val' false <<< ''\n"
|
||||||
|
+ "echo \"MY_VAR=$MY_VAR\"\n"
|
||||||
|
)
|
||||||
|
out, err, rc = _run_bash(snippet)
|
||||||
|
assert "MY_VAR=default-val" in out, f"Default nicht gesetzt:\n{out}\n{err}"
|
||||||
|
|
||||||
|
def test_ask_sets_skip_on_empty_with_allow_skip(self):
|
||||||
|
snippet = (
|
||||||
|
_extract_functions("ask")
|
||||||
|
+ "GUIDED_DEFAULTS=false\n"
|
||||||
|
+ "ask MY_VAR 'Frage?' '' true <<< ''\n"
|
||||||
|
+ "echo \"MY_VAR=$MY_VAR\"\n"
|
||||||
|
)
|
||||||
|
out, err, rc = _run_bash(snippet)
|
||||||
|
assert "MY_VAR=SKIP" in out, f"SKIP-Ausweich nicht gesetzt:\n{out}\n{err}"
|
||||||
|
|
||||||
|
def test_ask_uses_typed_input(self):
|
||||||
|
snippet = (
|
||||||
|
_extract_functions("ask")
|
||||||
|
+ "GUIDED_DEFAULTS=false\n"
|
||||||
|
+ "ask MY_VAR 'Frage?' 'default-val' false <<< 'typed-value'\n"
|
||||||
|
+ "echo \"MY_VAR=$MY_VAR\"\n"
|
||||||
|
)
|
||||||
|
out, err, rc = _run_bash(snippet)
|
||||||
|
assert "MY_VAR=typed-value" in out, f"Eingabe nicht übernommen:\n{out}\n{err}"
|
||||||
|
|
||||||
|
def test_ask_defaults_mode_uses_default_without_prompt(self):
|
||||||
|
snippet = (
|
||||||
|
_extract_functions("ask")
|
||||||
|
+ "GUIDED_DEFAULTS=true\n"
|
||||||
|
+ "ask MY_VAR 'Frage?' 'default-val' false\n"
|
||||||
|
+ "echo \"MY_VAR=$MY_VAR\"\n"
|
||||||
|
)
|
||||||
|
out, err, rc = _run_bash(snippet)
|
||||||
|
assert "MY_VAR=default-val" in out, f"--defaults sollte Default ohne Prompt setzen:\n{out}\n{err}"
|
||||||
|
|
||||||
|
|
||||||
|
class TestCheckGiteaSshKeyBehavior:
|
||||||
|
"""check_gitea_ssh_key() darf im Guided-Modus bei fehlendem Key NICHT abbrechen."""
|
||||||
|
|
||||||
|
def test_guided_missing_key_returns_zero(self):
|
||||||
|
# Im Guided-Modus + fehlendem Key → return 0 (kein die-Abbruch).
|
||||||
|
snippet = (
|
||||||
|
_extract_functions("check_gitea_ssh_key")
|
||||||
|
+ "GUIDED=true\n"
|
||||||
|
+ "HOME=/tmp/f98-no-key-home\n"
|
||||||
|
+ "check_gitea_ssh_key\n"
|
||||||
|
+ "echo \"RC=$?\"\n"
|
||||||
|
)
|
||||||
|
out, err, rc = _run_bash(snippet)
|
||||||
|
assert "RC=0" in out, f"Guided-Modus darf bei fehlendem Key nicht abbrechen:\n{out}\n{err}"
|
||||||
|
|
||||||
|
def test_non_guided_missing_key_aborts(self):
|
||||||
|
# Ohne Guided-Modus + fehlendem Key → die() → exit 1.
|
||||||
|
snippet = (
|
||||||
|
_extract_functions("check_gitea_ssh_key")
|
||||||
|
+ "GUIDED=false\n"
|
||||||
|
+ "HOME=/tmp/f98-no-key-home\n"
|
||||||
|
+ "check_gitea_ssh_key\n"
|
||||||
|
+ "echo \"RC=$?\"\n"
|
||||||
|
)
|
||||||
|
out, err, rc = _run_bash(snippet)
|
||||||
|
assert rc != 0, f"Non-Guided-Modus sollte bei fehlendem Key abbrechen:\n{out}\n{err}"
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -33,9 +33,11 @@ def _read_install_sh() -> str:
|
|||||||
|
|
||||||
def _extract_update_only_section(content: str) -> str:
|
def _extract_update_only_section(content: str) -> str:
|
||||||
"""Extrahiert den --update-only Block aus install.sh."""
|
"""Extrahiert den --update-only Block aus install.sh."""
|
||||||
# Der Block beginnt bei 'if $UPDATE_ONLY; then' und endet bei 'fi' vor dem Hauptfluss
|
# Der Block beginnt bei 'if $UPDATE_ONLY; then' und endet bei 'fi' vor dem Hauptfluss.
|
||||||
|
# F98: compute_cascade() steht jetzt zwischen dem --update-only Block und dem
|
||||||
|
# Hauptfluss-Marker '# 1. System-Dependencies' — die Regex toleriert das.
|
||||||
match = re.search(
|
match = re.search(
|
||||||
r'if \$UPDATE_ONLY; then.*?(?=\nfi\n\n# 1\. System-Dependencies|\nfi\n\nexit 0)',
|
r'if \$UPDATE_ONLY; then.*?(?=\nfi\n\n# (?:F98: compute_cascade|1\. System-Dependencies)|\nfi\n\nexit 0)',
|
||||||
content,
|
content,
|
||||||
re.DOTALL,
|
re.DOTALL,
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -0,0 +1,201 @@
|
|||||||
|
"""
|
||||||
|
P-171: REST-Re-Auth bei HTTP 401 (Token-Ablauf).
|
||||||
|
|
||||||
|
Root Cause A (31.08.): Der Rocket.Chat REST-Auth-Token lief nach ~8,5h ab.
|
||||||
|
Jeder REST-Call (users.setStatus, chat.postMessage) lieferte HTTP 401, und
|
||||||
|
`RocketChatREST._request()` loggte das nur als Warning und returnete None.
|
||||||
|
`post_message()` → None → `send()` → SendResult(success=False) — die Antwort
|
||||||
|
war STILL verloren. Es gab keinen Re-Login-Pfad im Plugin.
|
||||||
|
|
||||||
|
Fix: `_request()` erkennt 401, ruft den Re-Auth-Callback (Adapter-seitig,
|
||||||
|
kennt user/password), erneuert den Token und retried den SAME Request mit
|
||||||
|
frischem Token. Ein 30s-Throttle verhindert einen Re-Login-Sturm, wenn viele
|
||||||
|
Calls gleichzeitig auf einen abgelaufenen Token treffen.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import time
|
||||||
|
from unittest.mock import MagicMock, patch
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from plugin.adapter import RocketChatREST
|
||||||
|
|
||||||
|
|
||||||
|
def _make_rest() -> RocketChatREST:
|
||||||
|
rest = RocketChatREST("https://rc.example.com")
|
||||||
|
rest.auth_token = "old-token"
|
||||||
|
rest.user_id = "old-user-id"
|
||||||
|
return rest
|
||||||
|
|
||||||
|
|
||||||
|
class TestRESTReauthOn401:
|
||||||
|
def test_401_triggers_reauth_and_retry_succeeds(self):
|
||||||
|
"""401 → Re-Auth-Callback → Retry mit frischem Token → Erfolg."""
|
||||||
|
rest = _make_rest()
|
||||||
|
reauth_called = {"n": 0}
|
||||||
|
|
||||||
|
def _reauth() -> bool:
|
||||||
|
reauth_called["n"] += 1
|
||||||
|
rest.auth_token = "fresh-token"
|
||||||
|
rest.user_id = "fresh-user-id"
|
||||||
|
return True
|
||||||
|
|
||||||
|
rest.set_reauth_callback(_reauth)
|
||||||
|
|
||||||
|
# Erster Call: 401, zweiter Call (Retry): 200 mit Payload.
|
||||||
|
responses = [
|
||||||
|
_http_error(401),
|
||||||
|
_http_ok({"success": True, "message": {"_id": "msg-1"}}),
|
||||||
|
]
|
||||||
|
|
||||||
|
with patch("plugin.adapter.urllib.request.urlopen") as urlopen:
|
||||||
|
urlopen.side_effect = responses
|
||||||
|
result = rest._request(
|
||||||
|
"POST", "/api/v1/chat.postMessage",
|
||||||
|
headers={"X-Auth-Token": "old-token", "X-User-Id": "old-user-id"},
|
||||||
|
data={"roomId": "r1", "text": "hi"},
|
||||||
|
)
|
||||||
|
|
||||||
|
assert result == {"success": True, "message": {"_id": "msg-1"}}
|
||||||
|
assert reauth_called["n"] == 1, "Re-Auth-Callback muss genau 1x feuern"
|
||||||
|
|
||||||
|
def test_401_without_callback_returns_none(self):
|
||||||
|
"""Ohne Re-Auth-Callback bleibt 401 ein None (kein Crash)."""
|
||||||
|
rest = _make_rest()
|
||||||
|
# Kein set_reauth_callback → kein Retry.
|
||||||
|
with patch("plugin.adapter.urllib.request.urlopen") as urlopen:
|
||||||
|
urlopen.side_effect = _http_error(401)
|
||||||
|
result = rest._request("POST", "/api/v1/chat.postMessage", data={})
|
||||||
|
assert result is None
|
||||||
|
|
||||||
|
def test_reauth_failure_returns_none(self):
|
||||||
|
"""Re-Auth schlägt fehl → None (kein Endlos-Retry)."""
|
||||||
|
rest = _make_rest()
|
||||||
|
rest.set_reauth_callback(lambda: False)
|
||||||
|
with patch("plugin.adapter.urllib.request.urlopen") as urlopen:
|
||||||
|
urlopen.side_effect = _http_error(401)
|
||||||
|
result = rest._request("POST", "/api/v1/chat.postMessage", data={})
|
||||||
|
assert result is None
|
||||||
|
|
||||||
|
def test_throttle_prevents_reauth_storm(self):
|
||||||
|
"""Zweiter 401 innerhalb des Throttle-Fensters triggert KEINEN Re-Login."""
|
||||||
|
rest = _make_rest()
|
||||||
|
reauth_called = {"n": 0}
|
||||||
|
|
||||||
|
def _reauth() -> bool:
|
||||||
|
reauth_called["n"] += 1
|
||||||
|
rest.auth_token = "fresh-token"
|
||||||
|
return True
|
||||||
|
|
||||||
|
rest.set_reauth_callback(_reauth)
|
||||||
|
|
||||||
|
# Beide Calls liefern 401 (Retry schlägt auch fehl).
|
||||||
|
with patch("plugin.adapter.urllib.request.urlopen") as urlopen:
|
||||||
|
urlopen.side_effect = _http_error(401)
|
||||||
|
rest._request("POST", "/api/v1/users.setStatus", data={})
|
||||||
|
rest._request("POST", "/api/v1/users.setStatus", data={})
|
||||||
|
|
||||||
|
# Nur der ERSTE 401 darf den Re-Auth triggern (Throttle 30s).
|
||||||
|
assert reauth_called["n"] == 1, (
|
||||||
|
f"Throttle verletzt: {reauth_called['n']} Re-Auths statt 1"
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_throttle_resets_after_window(self):
|
||||||
|
"""Nach Ablauf des Throttle-Fensters darf erneut re-authentifiziert werden."""
|
||||||
|
rest = _make_rest()
|
||||||
|
reauth_called = {"n": 0}
|
||||||
|
|
||||||
|
def _reauth() -> bool:
|
||||||
|
reauth_called["n"] += 1
|
||||||
|
rest.auth_token = "fresh-token"
|
||||||
|
return True
|
||||||
|
|
||||||
|
rest.set_reauth_callback(_reauth)
|
||||||
|
|
||||||
|
with patch("plugin.adapter.urllib.request.urlopen") as urlopen:
|
||||||
|
urlopen.side_effect = _http_error(401)
|
||||||
|
rest._request("POST", "/api/v1/users.setStatus", data={})
|
||||||
|
|
||||||
|
# Fenster künstlich ablaufen lassen.
|
||||||
|
rest._last_reauth_ts -= (rest._REAUTH_THROTTLE_SECONDS + 1.0)
|
||||||
|
|
||||||
|
with patch("plugin.adapter.urllib.request.urlopen") as urlopen:
|
||||||
|
urlopen.side_effect = _http_error(401)
|
||||||
|
rest._request("POST", "/api/v1/users.setStatus", data={})
|
||||||
|
|
||||||
|
assert reauth_called["n"] == 2, (
|
||||||
|
f"Throttle-Reset fehlgeschlagen: {reauth_called['n']} Re-Auths statt 2"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class TestAdapterReauthCallback:
|
||||||
|
def test_reauth_rest_updates_tokens(self):
|
||||||
|
"""_reauth_rest() erneuert REST-Token + Adapter-Token."""
|
||||||
|
from plugin.adapter import RocketChatAdapter
|
||||||
|
|
||||||
|
adapter = RocketChatAdapter.__new__(RocketChatAdapter)
|
||||||
|
adapter.user = "testuser"
|
||||||
|
adapter.password = "testpass"
|
||||||
|
adapter.rest = MagicMock()
|
||||||
|
adapter.rest.login = MagicMock(return_value=True)
|
||||||
|
adapter.rest.auth_token = "fresh-token"
|
||||||
|
adapter.rest.user_id = "fresh-user-id"
|
||||||
|
adapter._auth_token = "old-token"
|
||||||
|
adapter._user_id = "old-user-id"
|
||||||
|
|
||||||
|
result = adapter._reauth_rest()
|
||||||
|
|
||||||
|
assert result is True
|
||||||
|
adapter.rest.login.assert_called_once_with("testuser", "testpass")
|
||||||
|
assert adapter._auth_token == "fresh-token"
|
||||||
|
assert adapter._user_id == "fresh-user-id"
|
||||||
|
|
||||||
|
def test_reauth_rest_no_credentials(self):
|
||||||
|
"""Ohne Credentials → False, kein Login-Versuch."""
|
||||||
|
from plugin.adapter import RocketChatAdapter
|
||||||
|
|
||||||
|
adapter = RocketChatAdapter.__new__(RocketChatAdapter)
|
||||||
|
adapter.user = ""
|
||||||
|
adapter.password = ""
|
||||||
|
adapter.rest = MagicMock()
|
||||||
|
|
||||||
|
result = adapter._reauth_rest()
|
||||||
|
|
||||||
|
assert result is False
|
||||||
|
adapter.rest.login.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
|
def _http_error(code: int):
|
||||||
|
"""Erzeugt eine urllib.error.HTTPError-Instanz für den Mock."""
|
||||||
|
import urllib.error
|
||||||
|
|
||||||
|
return urllib.error.HTTPError(
|
||||||
|
url="https://rc.example.com/api/v1/x",
|
||||||
|
code=code,
|
||||||
|
msg="Unauthorized" if code == 401 else "Error",
|
||||||
|
hdrs={},
|
||||||
|
fp=None,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _http_ok(payload: dict):
|
||||||
|
"""Erzeugt ein Context-Manager-fähiges Response-Objekt für den Mock."""
|
||||||
|
import io
|
||||||
|
|
||||||
|
class _FakeResp:
|
||||||
|
def __init__(self, body: bytes):
|
||||||
|
self._body = body
|
||||||
|
|
||||||
|
def __enter__(self):
|
||||||
|
return self
|
||||||
|
|
||||||
|
def __exit__(self, *args):
|
||||||
|
return False
|
||||||
|
|
||||||
|
def read(self) -> bytes:
|
||||||
|
return self._body
|
||||||
|
|
||||||
|
return _FakeResp(json.dumps(payload).encode("utf-8"))
|
||||||
Reference in New Issue
Block a user