262 lines
9.3 KiB
Python
262 lines
9.3 KiB
Python
"""
|
|
V8.4.4: LLM-Timeout löst Red Flag aus statt blind STAY.
|
|
|
|
Rainer's Fix: Der llm_failed-Pfad in router.py route() soll bei >1
|
|
verfügbarem Raum UNCERTAIN → Red Flag auslösen, statt blind STAY.
|
|
|
|
Tests:
|
|
1. test_llm_timeout_triggers_red_flag — mock _llm_raw → None, expect is_red_flag=True
|
|
2. test_llm_timeout_telemetry_counter_increments — Counter 'llm_unavailable' +1
|
|
3. test_llm_timeout_single_room_stays — bei nur 1 Raum → stay_in_room (kein Red Flag)
|
|
4. Bestehende Tests dürfen nicht brechen (implizit durch Test-Suite)
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import json
|
|
import sys
|
|
import tempfile
|
|
from pathlib import Path
|
|
from typing import Optional
|
|
|
|
import pytest
|
|
|
|
sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
|
|
|
|
from plugin.archivar.router import BidirectionalRouter, RoutingDecision
|
|
from plugin.archivar.room_map import RoomMap
|
|
from plugin.archivar.classifier import IntentClassifier, EmbeddingClient
|
|
from plugin.archivar.archivar_state import ArchivarState
|
|
from plugin.archivar.routing_counter import routing_counter
|
|
|
|
|
|
# ── Helpers (same as test_v8_4.py) ──────────────────────────────────────────
|
|
|
|
|
|
class MockEmbeddingClient(EmbeddingClient):
|
|
"""Mock embedding client that returns fixed vectors."""
|
|
|
|
def get_embedding(self, text: str) -> Optional[list]:
|
|
return [0.1] * 768
|
|
|
|
|
|
def _make_multi_room_map() -> RoomMap:
|
|
"""Build a RoomMap with 3 non-catch-all rooms + 1 catch-all."""
|
|
tmp = tempfile.TemporaryDirectory()
|
|
map_path = Path(tmp.name) / "room-map.json"
|
|
|
|
test_data = {
|
|
"version": 5,
|
|
"rooms": {
|
|
"room_rc_plugin": {
|
|
"name": "#RC-Plugin",
|
|
"theme": "Rocket.Chat Plugin Entwicklung",
|
|
"description": "Entwicklung des Hermes Rocket.Chat Plugins",
|
|
"keywords_100": ["plugin", "rocketchat"],
|
|
"keywords_context": ["adapter", "gateway"],
|
|
"catch_all": False,
|
|
},
|
|
"room_lan_doku": {
|
|
"name": "#LAN-Doku",
|
|
"theme": "LAN Dokumentation",
|
|
"description": "Dokumentation des LAN-Netzwerks",
|
|
"keywords_100": ["dokumentation", "doku"],
|
|
"keywords_context": ["netzwerk", "lan"],
|
|
"catch_all": False,
|
|
},
|
|
"room_bat_team": {
|
|
"name": "#BAT-Team",
|
|
"theme": "BAT Team Koordination",
|
|
"description": "Koordination des BAT-Teams",
|
|
"keywords_100": ["bat", "team"],
|
|
"keywords_context": ["support", "hilfe"],
|
|
"catch_all": False,
|
|
},
|
|
"room_catchall": {
|
|
"name": "#CatchAll",
|
|
"theme": "Catch-all room",
|
|
"keywords_100": [],
|
|
"keywords_context": [],
|
|
"catch_all": True,
|
|
},
|
|
},
|
|
"excluded_rooms": [],
|
|
"butler_mode": "cognitive",
|
|
"fact_store_path": str(Path(tmp.name) / "docs"),
|
|
}
|
|
with open(map_path, "w") as f:
|
|
json.dump(test_data, f)
|
|
|
|
room_map = RoomMap.load(path=map_path)
|
|
room_map._tmpdir = tmp
|
|
return room_map
|
|
|
|
|
|
def _make_single_room_map() -> RoomMap:
|
|
"""Build a RoomMap with only 1 non-catch-all room + 1 catch-all."""
|
|
tmp = tempfile.TemporaryDirectory()
|
|
map_path = Path(tmp.name) / "room-map.json"
|
|
|
|
test_data = {
|
|
"version": 5,
|
|
"rooms": {
|
|
"room_rc_plugin": {
|
|
"name": "#RC-Plugin",
|
|
"theme": "Rocket.Chat Plugin Entwicklung",
|
|
"description": "Entwicklung des Hermes Rocket.Chat Plugins",
|
|
"keywords_100": ["plugin", "rocketchat"],
|
|
"keywords_context": ["adapter", "gateway"],
|
|
"catch_all": False,
|
|
},
|
|
"room_catchall": {
|
|
"name": "#CatchAll",
|
|
"theme": "Catch-all room",
|
|
"keywords_100": [],
|
|
"keywords_context": [],
|
|
"catch_all": True,
|
|
},
|
|
},
|
|
"excluded_rooms": [],
|
|
"butler_mode": "cognitive",
|
|
"fact_store_path": str(Path(tmp.name) / "docs"),
|
|
}
|
|
with open(map_path, "w") as f:
|
|
json.dump(test_data, f)
|
|
|
|
room_map = RoomMap.load(path=map_path)
|
|
room_map._tmpdir = tmp
|
|
return room_map
|
|
|
|
|
|
def _make_router(room_map: RoomMap, mock_llm_fn=None) -> BidirectionalRouter:
|
|
"""Build a BidirectionalRouter with mock classifier and state."""
|
|
mock_client = MockEmbeddingClient()
|
|
classifier = IntentClassifier(embedding_client=mock_client)
|
|
state = ArchivarState(state_file_path="/tmp/archivar_test_state.json")
|
|
import os as _os
|
|
try:
|
|
_os.remove("/tmp/archivar_test_state.json")
|
|
except FileNotFoundError:
|
|
pass
|
|
|
|
router = BidirectionalRouter(room_map, classifier, state)
|
|
|
|
if mock_llm_fn is not None:
|
|
classifier._llm_raw = mock_llm_fn
|
|
|
|
return router
|
|
|
|
|
|
# ── V8.4.4 Tests ────────────────────────────────────────────────────────────
|
|
|
|
|
|
class TestLLMTimeoutRedFlag:
|
|
"""LLM-Timeout (llm_failed) löst Red Flag aus bei >1 Raum."""
|
|
|
|
def test_llm_timeout_triggers_red_flag(self):
|
|
"""Mock _llm_raw → None (Timeout) → is_red_flag=True, red_flag_rooms non-empty."""
|
|
room_map = _make_multi_room_map()
|
|
|
|
async def mock_llm_none(prompt: str) -> Optional[str]:
|
|
return None # Simuliert LLM-Timeout/Ausfall
|
|
|
|
router = _make_router(room_map, mock_llm_none)
|
|
|
|
decision = asyncio.run(router.route(
|
|
"Generische Frage ohne klares Thema",
|
|
origin_room_id="room_rc_plugin",
|
|
))
|
|
|
|
assert decision.is_red_flag is True, (
|
|
f"Expected is_red_flag=True on LLM timeout, got {decision.is_red_flag}"
|
|
)
|
|
assert len(decision.red_flag_rooms) >= 2, (
|
|
f"Expected >=2 red_flag_rooms, got {len(decision.red_flag_rooms)}"
|
|
)
|
|
# red_flag_rooms should contain other rooms (not origin)
|
|
assert any("LAN-Doku" in r for r in decision.red_flag_rooms), (
|
|
f"Expected 'LAN-Doku' in red_flag_rooms: {decision.red_flag_rooms}"
|
|
)
|
|
assert any("BAT-Team" in r for r in decision.red_flag_rooms), (
|
|
f"Expected 'BAT-Team' in red_flag_rooms: {decision.red_flag_rooms}"
|
|
)
|
|
# Origin room should NOT be in red_flag_rooms
|
|
assert not any("RC-Plugin" in r for r in decision.red_flag_rooms), (
|
|
f"Origin room should not be in red_flag_rooms: {decision.red_flag_rooms}"
|
|
)
|
|
|
|
def test_llm_timeout_telemetry_counter_increments(self):
|
|
"""Counter 'llm_unavailable' wird bei LLM-Timeout inkrementiert."""
|
|
routing_counter.reset()
|
|
|
|
room_map = _make_multi_room_map()
|
|
|
|
async def mock_llm_none(prompt: str) -> Optional[str]:
|
|
return None
|
|
|
|
router = _make_router(room_map, mock_llm_none)
|
|
|
|
asyncio.run(router.route(
|
|
"Generische Frage",
|
|
origin_room_id="room_rc_plugin",
|
|
))
|
|
|
|
counts = routing_counter.get_counts()
|
|
assert counts.get("llm_unavailable", 0) >= 1, (
|
|
f"Expected llm_unavailable >= 1, got {counts}"
|
|
)
|
|
# red_flag_triggered should also be incremented (multi-room)
|
|
assert counts.get("red_flag_triggered", 0) >= 1, (
|
|
f"Expected red_flag_triggered >= 1, got {counts}"
|
|
)
|
|
|
|
def test_llm_timeout_single_room_stays(self):
|
|
"""Bei nur 1 verfügbarem Raum → stay_in_room (kein Red Flag)."""
|
|
room_map = _make_single_room_map()
|
|
|
|
async def mock_llm_none(prompt: str) -> Optional[str]:
|
|
return None
|
|
|
|
router = _make_router(room_map, mock_llm_none)
|
|
|
|
decision = asyncio.run(router.route(
|
|
"Generische Frage",
|
|
origin_room_id="room_rc_plugin",
|
|
))
|
|
|
|
# Only 1 non-catch-all room → no Red Flag, just stay
|
|
assert decision.is_red_flag is False, (
|
|
f"Expected is_red_flag=False with single room, got {decision.is_red_flag}"
|
|
)
|
|
assert decision.stay_in_room is True, (
|
|
f"Expected stay_in_room=True, got {decision.stay_in_room}"
|
|
)
|
|
|
|
def test_llm_timeout_red_flag_prompt_structured(self):
|
|
"""Red-Flag-Prompt bei LLM-Timeout ist korrekt strukturiert."""
|
|
room_map = _make_multi_room_map()
|
|
|
|
async def mock_llm_none(prompt: str) -> Optional[str]:
|
|
return None
|
|
|
|
router = _make_router(room_map, mock_llm_none)
|
|
|
|
decision = asyncio.run(router.route(
|
|
"Generische Frage ohne klares Thema",
|
|
origin_room_id="room_rc_plugin",
|
|
))
|
|
|
|
assert decision.is_red_flag is True
|
|
prompt = decision.red_flag_prompt
|
|
assert prompt is not None
|
|
assert "Router unsicher" in prompt, f"Prompt missing 'Router unsicher': {prompt}"
|
|
assert "ROOM:" in prompt, f"Prompt missing 'ROOM:': {prompt}"
|
|
# Should include other rooms
|
|
assert "LAN-Doku" in prompt, f"Prompt missing LAN-Doku: {prompt}"
|
|
assert "BAT-Team" in prompt, f"Prompt missing BAT-Team: {prompt}"
|
|
# Should NOT include origin room as option
|
|
assert "RC-Plugin" not in prompt or "Ursprungsraum" in prompt, (
|
|
f"Origin room should not be listed as option: {prompt}"
|
|
)
|