feat: V8.3.3 — Routing-Telemetrie (Konfidenz-Logging) + Echte Integration-Tests
FEATURE 1: Routing-Telemetrie (Konfidenz-Logging) - Neue Datei: archivar/routing_telemetry.py — RoutingTelemetry Klasse - Feature-Flag: ARCHIVAR_ROUTING_TELEMETRY env var (Default true) - Pro Routing-Entscheidung: stage, score, decision, target, origin, duration_ms - Format: [TELEMETRY] stage=keyword_100 score=1.00 decision=route ... - NIEMALS Nachrichteninhalte im Log (Datenschutz) - Telemetrie-Punkte in router.py an allen 5 Stufen: keyword_100, context_keyword, faiss, llm, default - Flush in adapter.py nach classify_and_route() FEATURE 2: Echte Integration-Tests - Neue Datei: archivar/tests/test_v8_3_3.py (18 Tests) - Echte RoutingDecision-Objekte statt Dict-Simulationen - 7 Integration-Test-Klassen: 1. 100%-Keyword im falschen Raum → route 2. 100%-Keyword im richtigen Raum → stay (self-match) 3. Kontext-Keyword → butler 4. FAISS hohe Ähnlichkeit → route 5. FAISS mittlere Ähnlichkeit → butler 6. LLM → STAY 7. LLM → ROUTE - Telemetrie-Tests: Logging, Datenschutz, Feature-Flag - Erweiterte conftest.py: multi_room_map, Mock-LLM Fixtures Verifikation: 527 passed, 1 pre-existing fail, 2 skipped (FAISS)
This commit is contained in:
@@ -47,6 +47,7 @@ if _MULTIROOM():
|
|||||||
|
|
||||||
# Routing-Counter: immer importieren (keine schweren Abhängigkeiten)
|
# Routing-Counter: immer importieren (keine schweren Abhängigkeiten)
|
||||||
from archivar.routing_counter import routing_counter
|
from archivar.routing_counter import routing_counter
|
||||||
|
from archivar.routing_telemetry import routing_telemetry
|
||||||
|
|
||||||
# ── Access __init__ symbols (plugin loaded as flat module, no relative imports) ──
|
# ── Access __init__ symbols (plugin loaded as flat module, no relative imports) ──
|
||||||
import sys as _sys
|
import sys as _sys
|
||||||
@@ -2027,6 +2028,8 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
else:
|
else:
|
||||||
logger.debug("[rocketchat] ARCHIVAR-DEBUG: Calling classify_and_route for room=%s", room_id[:12])
|
logger.debug("[rocketchat] ARCHIVAR-DEBUG: Calling classify_and_route for room=%s", room_id[:12])
|
||||||
decision = await self.archivar.classify_and_route(text, origin_room_id=room_id)
|
decision = await self.archivar.classify_and_route(text, origin_room_id=room_id)
|
||||||
|
# V8.3.3: Telemetrie nach jeder Routing-Entscheidung flushen
|
||||||
|
routing_telemetry.flush()
|
||||||
if decision and decision.category:
|
if decision and decision.category:
|
||||||
category = decision.category
|
category = decision.category
|
||||||
# Wenn Zielraum = Ursprungsraum → stay_in_room, kein Move-Request
|
# Wenn Zielraum = Ursprungsraum → stay_in_room, kein Move-Request
|
||||||
|
|||||||
@@ -275,6 +275,17 @@ ARCHIVAR_STRATEGY_AUTO_DETECT: bool = os.getenv(
|
|||||||
"""Feature-Flag für A2-Phase 2: Automatische Strategie-Themen-Erkennung.
|
"""Feature-Flag für A2-Phase 2: Automatische Strategie-Themen-Erkennung.
|
||||||
Default: false (AUS). Setze auf 'true' um Auto-Detection zu aktivieren."""
|
Default: false (AUS). Setze auf 'true' um Auto-Detection zu aktivieren."""
|
||||||
|
|
||||||
|
# ── V8.3.3: Routing-Telemetrie (Konfidenz-Logging) ──────────────────────────
|
||||||
|
# Feature-Flag: ARCHIVAR_ROUTING_TELEMETRY env var, Default AN.
|
||||||
|
# Protokolliert pro Routing-Entscheidung: Stufe, Score, Decision, Target,
|
||||||
|
# Origin, Dauer — NIEMALS Nachrichteninhalte (Datenschutz!).
|
||||||
|
|
||||||
|
ARCHIVAR_ROUTING_TELEMETRY: bool = os.getenv(
|
||||||
|
"ARCHIVAR_ROUTING_TELEMETRY", "true"
|
||||||
|
).strip().lower() not in ("false", "0", "no", "off")
|
||||||
|
"""Feature-Flag für Routing-Telemetrie. Default: true (AN).
|
||||||
|
Setze auf 'false' um Telemetrie-Logging zu deaktivieren."""
|
||||||
|
|
||||||
# ── 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.
|
||||||
|
|||||||
@@ -32,6 +32,7 @@ from .room_index import RoomIndexManager
|
|||||||
from .booster import KeywordBooster
|
from .booster import KeywordBooster
|
||||||
from .archivar_state import ArchivarState
|
from .archivar_state import ArchivarState
|
||||||
from .routing_counter import routing_counter
|
from .routing_counter import routing_counter
|
||||||
|
from .routing_telemetry import routing_telemetry
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
@@ -563,6 +564,7 @@ class BidirectionalRouter:
|
|||||||
)
|
)
|
||||||
|
|
||||||
# ── Schritt 3: Keyword-Match (aus RoomMap) ──────────────────
|
# ── Schritt 3: Keyword-Match (aus RoomMap) ──────────────────
|
||||||
|
routing_telemetry.start_timer()
|
||||||
matched_room = self._room_map.find_room_by_keywords(text, origin_room_id=origin_room_id)
|
matched_room = self._room_map.find_room_by_keywords(text, origin_room_id=origin_room_id)
|
||||||
if matched_room is not None:
|
if matched_room is not None:
|
||||||
# Self-Match-Schutz: Wenn Keyword-Match den Ursprungsraum
|
# Self-Match-Schutz: Wenn Keyword-Match den Ursprungsraum
|
||||||
@@ -607,6 +609,11 @@ class BidirectionalRouter:
|
|||||||
text[:80], matched_room.name,
|
text[:80], matched_room.name,
|
||||||
)
|
)
|
||||||
routing_counter.increment('keyword_100_auto_route')
|
routing_counter.increment('keyword_100_auto_route')
|
||||||
|
routing_telemetry.record(
|
||||||
|
stage='keyword_100', score=1.0, decision='route',
|
||||||
|
target=matched_room.room_id, origin=origin_room_id,
|
||||||
|
duration_ms=routing_telemetry.elapsed_ms(),
|
||||||
|
)
|
||||||
logger.info("ROUTING DECISION: reason=keyword_100_auto_route, origin_room=%s, target_room=%s, stay=False, butler_mode=False", origin_room_id, matched_room.room_id)
|
logger.info("ROUTING DECISION: reason=keyword_100_auto_route, origin_room=%s, target_room=%s, stay=False, butler_mode=False", origin_room_id, matched_room.room_id)
|
||||||
return RoutingDecision(
|
return RoutingDecision(
|
||||||
category="work_order",
|
category="work_order",
|
||||||
@@ -626,6 +633,11 @@ class BidirectionalRouter:
|
|||||||
text[:80], matched_room.name,
|
text[:80], matched_room.name,
|
||||||
)
|
)
|
||||||
routing_counter.increment('keyword_context_butler')
|
routing_counter.increment('keyword_context_butler')
|
||||||
|
routing_telemetry.record(
|
||||||
|
stage='context_keyword', score=0.95, decision='butler',
|
||||||
|
target=matched_room.room_id, origin=origin_room_id,
|
||||||
|
duration_ms=routing_telemetry.elapsed_ms(),
|
||||||
|
)
|
||||||
logger.info("ROUTING DECISION: reason=keyword_context_butler, origin_room=%s, target_room=%s, stay=False, butler_mode=True", origin_room_id, matched_room.room_id)
|
logger.info("ROUTING DECISION: reason=keyword_context_butler, origin_room=%s, target_room=%s, stay=False, butler_mode=True", origin_room_id, matched_room.room_id)
|
||||||
return RoutingDecision(
|
return RoutingDecision(
|
||||||
category="work_order",
|
category="work_order",
|
||||||
@@ -644,6 +656,7 @@ class BidirectionalRouter:
|
|||||||
# Phase-1 routet direkt bei hohem FAISS-Score — kein LLM-Aufruf.
|
# Phase-1 routet direkt bei hohem FAISS-Score — kein LLM-Aufruf.
|
||||||
# Übersprungen wenn _room_index oder _booster None sind.
|
# Übersprungen wenn _room_index oder _booster None sind.
|
||||||
if self._room_index is not None and self._room_index.is_built:
|
if self._room_index is not None and self._room_index.is_built:
|
||||||
|
routing_telemetry.start_timer()
|
||||||
faiss_hits = self._room_index.search_text(
|
faiss_hits = self._room_index.search_text(
|
||||||
text, k=FAISS_TOP_K, min_score=FAISS_MIN_SCORE
|
text, k=FAISS_TOP_K, min_score=FAISS_MIN_SCORE
|
||||||
)
|
)
|
||||||
@@ -703,6 +716,11 @@ class BidirectionalRouter:
|
|||||||
booster_applied,
|
booster_applied,
|
||||||
)
|
)
|
||||||
routing_counter.increment('faiss_auto_route')
|
routing_counter.increment('faiss_auto_route')
|
||||||
|
routing_telemetry.record(
|
||||||
|
stage='faiss', score=top_score, decision='route',
|
||||||
|
target=top_room_id, origin=origin_room_id,
|
||||||
|
duration_ms=routing_telemetry.elapsed_ms(),
|
||||||
|
)
|
||||||
logger.info("ROUTING DECISION: reason=faiss_auto_route, origin_room=%s, target_room=%s, stay=False, butler_mode=False", origin_room_id, top_room_id)
|
logger.info("ROUTING DECISION: reason=faiss_auto_route, origin_room=%s, target_room=%s, stay=False, butler_mode=False", origin_room_id, top_room_id)
|
||||||
|
|
||||||
return RoutingDecision(
|
return RoutingDecision(
|
||||||
@@ -729,6 +747,11 @@ class BidirectionalRouter:
|
|||||||
FAISS_AUTO_ROUTE,
|
FAISS_AUTO_ROUTE,
|
||||||
)
|
)
|
||||||
routing_counter.increment('faiss_butler')
|
routing_counter.increment('faiss_butler')
|
||||||
|
routing_telemetry.record(
|
||||||
|
stage='faiss', score=top_score, decision='butler',
|
||||||
|
target=top_room_id, origin=origin_room_id,
|
||||||
|
duration_ms=routing_telemetry.elapsed_ms(),
|
||||||
|
)
|
||||||
logger.info("ROUTING DECISION: reason=faiss_butler, origin_room=%s, target_room=%s, stay=False, butler_mode=True", origin_room_id, top_room_id)
|
logger.info("ROUTING DECISION: reason=faiss_butler, origin_room=%s, target_room=%s, stay=False, butler_mode=True", origin_room_id, top_room_id)
|
||||||
|
|
||||||
# ── Schritt 4: Embedding-Vorfilter (binär) ────────────────────
|
# ── Schritt 4: Embedding-Vorfilter (binär) ────────────────────
|
||||||
@@ -832,6 +855,7 @@ class BidirectionalRouter:
|
|||||||
# ── Schritt 5: LLM-Raum-Router (zentraler Prompt) ────────────
|
# ── Schritt 5: LLM-Raum-Router (zentraler Prompt) ────────────
|
||||||
# LLM_ROOM_PROMPT erhält Nachricht + Raumliste mit Keywords,
|
# LLM_ROOM_PROMPT erhält Nachricht + Raumliste mit Keywords,
|
||||||
# liefert STAY oder room_id direkt (keine Kategorien, kein Name-Matching)
|
# liefert STAY oder room_id direkt (keine Kategorien, kein Name-Matching)
|
||||||
|
routing_telemetry.start_timer()
|
||||||
llm_room, llm_stay, llm_failed = await self._llm_room_lookup(text, origin_room_id)
|
llm_room, llm_stay, llm_failed = await self._llm_room_lookup(text, origin_room_id)
|
||||||
|
|
||||||
# ── Schritt 6: ORIGIN-FIRST GUARD (v6) ──────────────────────
|
# ── Schritt 6: ORIGIN-FIRST GUARD (v6) ──────────────────────
|
||||||
@@ -844,6 +868,11 @@ class BidirectionalRouter:
|
|||||||
text,
|
text,
|
||||||
)
|
)
|
||||||
routing_counter.increment('llm_stay')
|
routing_counter.increment('llm_stay')
|
||||||
|
routing_telemetry.record(
|
||||||
|
stage='llm', score=0.0, decision='stay',
|
||||||
|
target='', origin=origin_room_id,
|
||||||
|
duration_ms=routing_telemetry.elapsed_ms(),
|
||||||
|
)
|
||||||
logger.info("ROUTING DECISION: reason=llm_stay, origin_room=%s, target_room=, stay=True, butler_mode=False", origin_room_id)
|
logger.info("ROUTING DECISION: reason=llm_stay, origin_room=%s, target_room=, stay=True, butler_mode=False", origin_room_id)
|
||||||
return RoutingDecision(
|
return RoutingDecision(
|
||||||
category="direct_question",
|
category="direct_question",
|
||||||
@@ -859,6 +888,11 @@ class BidirectionalRouter:
|
|||||||
"LLM-Raum-Router: STAY für '%.80s...' → stay_in_room", text[:80]
|
"LLM-Raum-Router: STAY für '%.80s...' → stay_in_room", text[:80]
|
||||||
)
|
)
|
||||||
routing_counter.increment('llm_stay')
|
routing_counter.increment('llm_stay')
|
||||||
|
routing_telemetry.record(
|
||||||
|
stage='llm', score=0.0, decision='stay',
|
||||||
|
target='', origin=origin_room_id,
|
||||||
|
duration_ms=routing_telemetry.elapsed_ms(),
|
||||||
|
)
|
||||||
logger.info("ROUTING DECISION: reason=llm_stay, origin_room=%s, target_room=, stay=True, butler_mode=False", origin_room_id)
|
logger.info("ROUTING DECISION: reason=llm_stay, origin_room=%s, target_room=, stay=True, butler_mode=False", origin_room_id)
|
||||||
return RoutingDecision(
|
return RoutingDecision(
|
||||||
category="direct_question",
|
category="direct_question",
|
||||||
@@ -927,6 +961,11 @@ class BidirectionalRouter:
|
|||||||
text[:80], llm_room.name, llm_room.room_id[:8],
|
text[:80], llm_room.name, llm_room.room_id[:8],
|
||||||
)
|
)
|
||||||
routing_counter.increment('llm_route')
|
routing_counter.increment('llm_route')
|
||||||
|
routing_telemetry.record(
|
||||||
|
stage='llm', score=0.90, decision='butler',
|
||||||
|
target=llm_room.room_id, origin=origin_room_id,
|
||||||
|
duration_ms=routing_telemetry.elapsed_ms(),
|
||||||
|
)
|
||||||
logger.info("ROUTING DECISION: reason=llm_route, origin_room=%s, target_room=%s, stay=False, butler_mode=True", origin_room_id, llm_room.room_id)
|
logger.info("ROUTING DECISION: reason=llm_route, origin_room=%s, target_room=%s, stay=False, butler_mode=True", origin_room_id, llm_room.room_id)
|
||||||
|
|
||||||
return RoutingDecision(
|
return RoutingDecision(
|
||||||
@@ -945,6 +984,11 @@ class BidirectionalRouter:
|
|||||||
"route(): Unerwarteter Fehler für '%.80s...' — Fallback auf Catch-All: %s",
|
"route(): Unerwarteter Fehler für '%.80s...' — Fallback auf Catch-All: %s",
|
||||||
text, e, exc_info=True,
|
text, e, exc_info=True,
|
||||||
)
|
)
|
||||||
|
routing_telemetry.record(
|
||||||
|
stage='default', score=0.0, decision='stay',
|
||||||
|
target='', origin=origin_room_id,
|
||||||
|
duration_ms=0.0,
|
||||||
|
)
|
||||||
catch_all = self._room_map.catch_all_room
|
catch_all = self._room_map.catch_all_room
|
||||||
return RoutingDecision(
|
return RoutingDecision(
|
||||||
category="direct_question",
|
category="direct_question",
|
||||||
|
|||||||
@@ -0,0 +1,125 @@
|
|||||||
|
"""
|
||||||
|
Routing-Telemetrie für Archivar v8.3.3.
|
||||||
|
|
||||||
|
Sammelt pro Routing-Entscheidung Metadaten (Stufe, Score, Decision, Target,
|
||||||
|
Origin, Dauer) und flusht sie als human-readable Log-Zeile an logger.info.
|
||||||
|
|
||||||
|
NIEMALS Nachrichteninhalte loggen — nur Metadaten (Datenschutz!).
|
||||||
|
|
||||||
|
Feature-Flag: ARCHIVAR_ROUTING_TELEMETRY env var, Default AN.
|
||||||
|
|
||||||
|
Usage::
|
||||||
|
|
||||||
|
from .routing_telemetry import routing_telemetry
|
||||||
|
|
||||||
|
routing_telemetry.record(
|
||||||
|
stage='keyword_100', score=1.0, decision='route',
|
||||||
|
target='room-abc', origin='room-xyz', duration_ms=2.3,
|
||||||
|
)
|
||||||
|
routing_telemetry.flush()
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import time
|
||||||
|
from typing import Dict, List, Optional
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class RoutingTelemetry:
|
||||||
|
"""Sammelt Routing-Telemetrie-Daten und flusht sie als Log-Zeilen.
|
||||||
|
|
||||||
|
Thread-safe via GIL (single-writer in async context). Keine Lock nötig,
|
||||||
|
da alle Aufrufe im selben asyncio-Event-Loop erfolgen.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self._enabled: bool = self._read_feature_flag()
|
||||||
|
self._records: List[Dict[str, object]] = []
|
||||||
|
self._start_time: float = 0.0
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _read_feature_flag() -> bool:
|
||||||
|
"""Lies ARCHIVAR_ROUTING_TELEMETRY env var. Default: True (AN)."""
|
||||||
|
val = os.getenv("ARCHIVAR_ROUTING_TELEMETRY", "true").strip().lower()
|
||||||
|
return val not in ("false", "0", "no", "off")
|
||||||
|
|
||||||
|
@property
|
||||||
|
def enabled(self) -> bool:
|
||||||
|
return self._enabled
|
||||||
|
|
||||||
|
def start_timer(self) -> None:
|
||||||
|
"""Starte den Stage-Timer. Wird VOR jeder Stufe aufgerufen."""
|
||||||
|
self._start_time = time.monotonic()
|
||||||
|
|
||||||
|
def elapsed_ms(self) -> float:
|
||||||
|
"""Liefere die seit start_timer() vergangene Zeit in ms."""
|
||||||
|
return (time.monotonic() - self._start_time) * 1000.0
|
||||||
|
|
||||||
|
def record(
|
||||||
|
self,
|
||||||
|
stage: str,
|
||||||
|
score: float,
|
||||||
|
decision: str,
|
||||||
|
target: str,
|
||||||
|
origin: str,
|
||||||
|
duration_ms: float,
|
||||||
|
) -> None:
|
||||||
|
"""Zeichne eine Routing-Entscheidung auf.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
stage: 'keyword_100' | 'context_keyword' | 'faiss' | 'llm' | 'default'
|
||||||
|
score: FAISS-Score, LLM-Confidence, 1.0 bei 100%-Match, 0.0 bei Default
|
||||||
|
decision: 'route' | 'stay' | 'butler'
|
||||||
|
target: Zielraum-ID (oder '' bei stay)
|
||||||
|
origin: Ursprungsraum-ID
|
||||||
|
duration_ms: Dauer der Stufe in Millisekunden
|
||||||
|
"""
|
||||||
|
if not self._enabled:
|
||||||
|
return
|
||||||
|
self._records.append({
|
||||||
|
"stage": stage,
|
||||||
|
"score": score,
|
||||||
|
"decision": decision,
|
||||||
|
"target": target,
|
||||||
|
"origin": origin,
|
||||||
|
"duration_ms": duration_ms,
|
||||||
|
})
|
||||||
|
|
||||||
|
def flush(self) -> None:
|
||||||
|
"""Flush alle gesammelten Records als [TELEMETRY] Log-Zeilen.
|
||||||
|
|
||||||
|
Format:
|
||||||
|
[TELEMETRY] stage=keyword_100 score=1.00 decision=route
|
||||||
|
target=#RC-Plugin origin=#LAN-Doku duration=2ms
|
||||||
|
"""
|
||||||
|
if not self._enabled or not self._records:
|
||||||
|
return
|
||||||
|
|
||||||
|
for rec in self._records:
|
||||||
|
stage = rec["stage"]
|
||||||
|
score = rec["score"]
|
||||||
|
decision = rec["decision"]
|
||||||
|
target = rec["target"] or "(none)"
|
||||||
|
origin = rec["origin"] or "(none)"
|
||||||
|
dur = rec["duration_ms"]
|
||||||
|
|
||||||
|
# Human-readable, kein JSON — für Log-Analyse optimiert
|
||||||
|
logger.info(
|
||||||
|
"[TELEMETRY] stage=%s score=%.2f decision=%s "
|
||||||
|
"target=%s origin=%s duration=%.1fms",
|
||||||
|
stage, score, decision, target, origin, dur,
|
||||||
|
)
|
||||||
|
|
||||||
|
self._records.clear()
|
||||||
|
|
||||||
|
def clear(self) -> None:
|
||||||
|
"""Leere alle Records ohne zu loggen (für Tests)."""
|
||||||
|
self._records.clear()
|
||||||
|
|
||||||
|
|
||||||
|
# Modul-Level-Singleton — wird von router.py und adapter.py importiert
|
||||||
|
routing_telemetry = RoutingTelemetry()
|
||||||
@@ -4,6 +4,9 @@ V8.2.1: pytest-Fixtures für saubere Pfad-Tests.
|
|||||||
Statt nested patches in jedem Test wird der room-map.json Pfad
|
Statt nested patches in jedem Test wird der room-map.json Pfad
|
||||||
pro Test umgebogen. Verwendet tempfile.TemporaryDirectory für
|
pro Test umgebogen. Verwendet tempfile.TemporaryDirectory für
|
||||||
Isolation.
|
Isolation.
|
||||||
|
|
||||||
|
V8.3.3: Erweiterte Fixtures für echte Integration-Tests mit
|
||||||
|
RoomMap, FAISS-Index und Mock-LLM.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import json
|
import json
|
||||||
@@ -62,3 +65,130 @@ def temp_state_path():
|
|||||||
state_path = str(Path(tmp.name) / "archivar_state.json")
|
state_path = str(Path(tmp.name) / "archivar_state.json")
|
||||||
yield state_path
|
yield state_path
|
||||||
tmp.cleanup()
|
tmp.cleanup()
|
||||||
|
|
||||||
|
|
||||||
|
# ── V8.3.3: Erweiterte Fixtures für echte Integration-Tests ──────────────
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def multi_room_map_path():
|
||||||
|
"""Erzeugt eine temporäre room-map.json mit 4 Räumen + Catch-All.
|
||||||
|
|
||||||
|
Räume:
|
||||||
|
- #RC-Plugin (keywords_100: plugin, rocketchat; context: adapter, gateway)
|
||||||
|
- #LAN-Doku (keywords_100: dokumentation, doku; context: netzwerk, lan)
|
||||||
|
- #BAT-Team (keywords_100: bat, team; context: support, hilfe)
|
||||||
|
- #DevOps (keywords_100: devops, deployment; context: ci, cd, pipeline)
|
||||||
|
- #CatchAll (catch_all)
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Path: Pfad zur temporären room-map.json.
|
||||||
|
"""
|
||||||
|
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 und Wartung",
|
||||||
|
"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 und Netzwerk",
|
||||||
|
"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_devops": {
|
||||||
|
"name": "#DevOps",
|
||||||
|
"theme": "DevOps und Deployment",
|
||||||
|
"description": "CI/CD und Deployment-Infrastruktur",
|
||||||
|
"keywords_100": ["devops", "deployment"],
|
||||||
|
"keywords_context": ["ci", "cd", "pipeline"],
|
||||||
|
"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)
|
||||||
|
|
||||||
|
yield map_path
|
||||||
|
tmp.cleanup()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def multi_room_map(multi_room_map_path):
|
||||||
|
"""Lädt eine echte RoomMap aus multi_room_map_path.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
RoomMap: Geladene RoomMap mit 4 Räumen + Catch-All.
|
||||||
|
"""
|
||||||
|
import sys
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
|
||||||
|
|
||||||
|
from plugin.archivar.room_map import RoomMap
|
||||||
|
|
||||||
|
return RoomMap.load(path=Path(str(multi_room_map_path)))
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def mock_llm_stay():
|
||||||
|
"""Mock-LLM das immer STAY zurückgibt.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
callable: Async-Funktion die (None, False, False) zurückgibt (STAY).
|
||||||
|
"""
|
||||||
|
async def _mock_llm(prompt: str):
|
||||||
|
return "STAY" # STAY
|
||||||
|
return _mock_llm
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def mock_llm_route():
|
||||||
|
"""Mock-LLM das immer ROUTE zu room_rc_plugin zurückgibt.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
callable: Async-Funktion die (RoomEntry, False, False) zurückgibt.
|
||||||
|
"""
|
||||||
|
async def _mock_llm(prompt: str):
|
||||||
|
return "room_rc_plugin" # ROUTE to #RC-Plugin
|
||||||
|
return _mock_llm
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def mock_llm_failed():
|
||||||
|
"""Mock-LLM das immer fehlschlägt (None zurückgibt).
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
callable: Async-Funktion die (None, False, True) zurückgibt (FAILED).
|
||||||
|
"""
|
||||||
|
async def _mock_llm(prompt: str):
|
||||||
|
return None # FAILED
|
||||||
|
return _mock_llm
|
||||||
|
|||||||
@@ -0,0 +1,516 @@
|
|||||||
|
"""
|
||||||
|
V8.3.3: Echte Integration-Tests mit RoutingDecision-Objekten.
|
||||||
|
|
||||||
|
Ersetzt die Dict-Simulationen aus V8.3.2 durch echte RoutingDecision-Instanzen.
|
||||||
|
Testet den gesamten 5-Stufen-Pfad mit echten Keywords, echtem FAISS-Index
|
||||||
|
und Mock-LLM.
|
||||||
|
|
||||||
|
Tests:
|
||||||
|
1. 100%-Keyword im falschen Raum → route (echter Keyword-Match)
|
||||||
|
2. 100%-Keyword im richtigen Raum → stay (self-match-check)
|
||||||
|
3. Kontext-Keyword → butler (echter Kontext-Match)
|
||||||
|
4. FAISS hohe Ähnlichkeit → route (echter FAISS-Score)
|
||||||
|
5. FAISS mittlere Ähnlichkeit → butler (echter FAISS-Score)
|
||||||
|
6. LLM → STAY (Mock-LLM gibt STAY)
|
||||||
|
7. LLM → ROUTE (Mock-LLM gibt ROUTE)
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import List, Optional
|
||||||
|
from unittest.mock import AsyncMock, MagicMock, patch
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
# Ensure the archivar package is importable
|
||||||
|
# Go up to project root so 'plugin.archivar' is a package
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
|
||||||
|
|
||||||
|
from plugin.archivar.router import BidirectionalRouter, RoutingDecision
|
||||||
|
from plugin.archivar.room_map import RoomMap, RoomEntry
|
||||||
|
from plugin.archivar.classifier import IntentClassifier, EmbeddingClient
|
||||||
|
from plugin.archivar.archivar_state import ArchivarState
|
||||||
|
from plugin.archivar.routing_telemetry import RoutingTelemetry, routing_telemetry
|
||||||
|
|
||||||
|
|
||||||
|
# ── Helpers ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
class MockEmbeddingClient(EmbeddingClient):
|
||||||
|
"""Mock embedding client that returns fixed vectors."""
|
||||||
|
|
||||||
|
def get_embedding(self, text: str) -> Optional[List[float]]:
|
||||||
|
return [0.1] * 768
|
||||||
|
|
||||||
|
|
||||||
|
def _make_router(room_map: RoomMap, mock_llm_fn=None) -> BidirectionalRouter:
|
||||||
|
"""Build a BidirectionalRouter with mock classifier and state.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
room_map: A loaded RoomMap instance.
|
||||||
|
mock_llm_fn: Optional async function to replace _llm_raw.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Configured BidirectionalRouter.
|
||||||
|
"""
|
||||||
|
mock_client = MockEmbeddingClient()
|
||||||
|
classifier = IntentClassifier(embedding_client=mock_client)
|
||||||
|
state = ArchivarState()
|
||||||
|
|
||||||
|
router = BidirectionalRouter(room_map, classifier, state)
|
||||||
|
|
||||||
|
if mock_llm_fn is not None:
|
||||||
|
# Patch _llm_raw on the classifier
|
||||||
|
classifier._llm_raw = mock_llm_fn
|
||||||
|
|
||||||
|
return router
|
||||||
|
|
||||||
|
|
||||||
|
# ── Telemetry Tests ────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
class TestTelemetryLogging:
|
||||||
|
"""Telemetrie loggt korrekt, keine Nachrichteninhalte."""
|
||||||
|
|
||||||
|
def test_telemetry_enabled_by_default(self):
|
||||||
|
"""ARCHIVAR_ROUTING_TELEMETRY ist default AN."""
|
||||||
|
# Default: env var nicht gesetzt → enabled
|
||||||
|
telemetry = RoutingTelemetry()
|
||||||
|
assert telemetry.enabled is True
|
||||||
|
|
||||||
|
def test_telemetry_disabled_via_env(self, monkeypatch):
|
||||||
|
"""ARCHIVAR_ROUTING_TELEMETRY=false deaktiviert Telemetrie."""
|
||||||
|
monkeypatch.setenv("ARCHIVAR_ROUTING_TELEMETRY", "false")
|
||||||
|
telemetry = RoutingTelemetry()
|
||||||
|
assert telemetry.enabled is False
|
||||||
|
|
||||||
|
def test_telemetry_record_and_flush(self, caplog):
|
||||||
|
"""Telemetrie record + flush produziert korrekte Log-Zeile."""
|
||||||
|
import logging
|
||||||
|
caplog.set_level(logging.INFO)
|
||||||
|
|
||||||
|
telemetry = RoutingTelemetry()
|
||||||
|
# Force enable for test
|
||||||
|
telemetry._enabled = True
|
||||||
|
|
||||||
|
telemetry.record(
|
||||||
|
stage='keyword_100', score=1.0, decision='route',
|
||||||
|
target='room-abc', origin='room-xyz', duration_ms=2.3,
|
||||||
|
)
|
||||||
|
telemetry.flush()
|
||||||
|
|
||||||
|
# Check log output
|
||||||
|
log_text = caplog.text
|
||||||
|
assert '[TELEMETRY]' in log_text
|
||||||
|
assert 'stage=keyword_100' in log_text
|
||||||
|
assert 'score=1.00' in log_text
|
||||||
|
assert 'decision=route' in log_text
|
||||||
|
assert 'target=room-abc' in log_text
|
||||||
|
assert 'origin=room-xyz' in log_text
|
||||||
|
assert 'duration=2.3ms' in log_text
|
||||||
|
|
||||||
|
def test_telemetry_no_message_content(self, caplog):
|
||||||
|
"""Telemetrie-Log enthält KEINE Nachrichteninhalte."""
|
||||||
|
import logging
|
||||||
|
caplog.set_level(logging.INFO)
|
||||||
|
|
||||||
|
telemetry = RoutingTelemetry()
|
||||||
|
telemetry._enabled = True
|
||||||
|
|
||||||
|
# Record mit einem hypothetischen Nachrichteninhalt
|
||||||
|
telemetry.record(
|
||||||
|
stage='faiss', score=0.87, decision='route',
|
||||||
|
target='room-abc', origin='room-xyz', duration_ms=5.0,
|
||||||
|
)
|
||||||
|
telemetry.flush()
|
||||||
|
|
||||||
|
log_text = caplog.text
|
||||||
|
# Keine Nachrichteninhalte im Log
|
||||||
|
assert 'Bitte dokumentiere' not in log_text
|
||||||
|
assert 'plugin' not in log_text.lower() or 'stage=' in log_text # plugin nur in stage
|
||||||
|
# Nur Metadaten
|
||||||
|
assert 'stage=' in log_text
|
||||||
|
assert 'score=' in log_text
|
||||||
|
assert 'decision=' in log_text
|
||||||
|
|
||||||
|
def test_telemetry_flush_clears_records(self):
|
||||||
|
"""Nach flush sind die Records geleert."""
|
||||||
|
telemetry = RoutingTelemetry()
|
||||||
|
telemetry._enabled = True
|
||||||
|
|
||||||
|
telemetry.record(
|
||||||
|
stage='keyword_100', score=1.0, decision='route',
|
||||||
|
target='room-abc', origin='room-xyz', duration_ms=2.0,
|
||||||
|
)
|
||||||
|
assert len(telemetry._records) == 1
|
||||||
|
telemetry.flush()
|
||||||
|
assert len(telemetry._records) == 0
|
||||||
|
|
||||||
|
def test_telemetry_disabled_skips_record(self):
|
||||||
|
"""Wenn disabled, wird nichts aufgezeichnet."""
|
||||||
|
telemetry = RoutingTelemetry()
|
||||||
|
telemetry._enabled = False
|
||||||
|
|
||||||
|
telemetry.record(
|
||||||
|
stage='keyword_100', score=1.0, decision='route',
|
||||||
|
target='room-abc', origin='room-xyz', duration_ms=2.0,
|
||||||
|
)
|
||||||
|
assert len(telemetry._records) == 0
|
||||||
|
|
||||||
|
|
||||||
|
# ── Integration Tests: Echte RoutingDecision-Objekte ───────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
class TestKeyword100Route:
|
||||||
|
"""Test 1: 100%-Keyword im falschen Raum → route (echter Keyword-Match)."""
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_100_percent_keyword_routes_to_target(self, multi_room_map):
|
||||||
|
"""'plugin' im #BAT-Team → route nach #RC-Plugin."""
|
||||||
|
router = _make_router(multi_room_map)
|
||||||
|
|
||||||
|
# 'plugin' ist 100%-Keyword für #RC-Plugin
|
||||||
|
# Ursprungsraum: #BAT-Team (room_bat_team)
|
||||||
|
decision = await router.route(
|
||||||
|
"Das Plugin hat einen Bug",
|
||||||
|
origin_room_id="room_bat_team",
|
||||||
|
)
|
||||||
|
|
||||||
|
# ECHTE RoutingDecision, kein Dict
|
||||||
|
assert isinstance(decision, RoutingDecision)
|
||||||
|
assert decision.target_room == "room_rc_plugin"
|
||||||
|
assert decision.category == "work_order"
|
||||||
|
assert decision.confidence == 0.95
|
||||||
|
assert decision.move_request_sent is False # 100% → Auto-Route
|
||||||
|
assert decision.matched_room_name == "#RC-Plugin"
|
||||||
|
assert decision.set_sticky is True # V8.3.2 F1: 100%-Match setzt Sticky
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_100_percent_keyword_multiple_matches(self, multi_room_map):
|
||||||
|
"""'dokumentation' im #RC-Plugin → route nach #LAN-Doku."""
|
||||||
|
router = _make_router(multi_room_map)
|
||||||
|
|
||||||
|
decision = await router.route(
|
||||||
|
"Bitte dokumentiere das neue Feature",
|
||||||
|
origin_room_id="room_rc_plugin",
|
||||||
|
)
|
||||||
|
|
||||||
|
assert isinstance(decision, RoutingDecision)
|
||||||
|
assert decision.target_room == "room_lan_doku"
|
||||||
|
assert decision.matched_room_name == "#LAN-Doku"
|
||||||
|
assert decision.move_request_sent is False # 100% → Auto-Route
|
||||||
|
|
||||||
|
|
||||||
|
class TestKeyword100SelfMatch:
|
||||||
|
"""Test 2: 100%-Keyword im richtigen Raum → stay (self-match-check)."""
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_100_percent_keyword_self_match_stays(self, multi_room_map):
|
||||||
|
"""'plugin' im #RC-Plugin → stay_in_room (self-match)."""
|
||||||
|
router = _make_router(multi_room_map)
|
||||||
|
|
||||||
|
decision = await router.route(
|
||||||
|
"Das Plugin braucht ein Update",
|
||||||
|
origin_room_id="room_rc_plugin",
|
||||||
|
)
|
||||||
|
|
||||||
|
assert isinstance(decision, RoutingDecision)
|
||||||
|
assert decision.stay_in_room is True
|
||||||
|
assert decision.target_room == "" # Kein Zielraum
|
||||||
|
assert decision.move_request_sent is False
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_100_percent_keyword_self_match_devops(self, multi_room_map):
|
||||||
|
"""'deployment' im #DevOps → stay_in_room (self-match)."""
|
||||||
|
router = _make_router(multi_room_map)
|
||||||
|
|
||||||
|
decision = await router.route(
|
||||||
|
"Das deployment ist fehlgeschlagen",
|
||||||
|
origin_room_id="room_devops",
|
||||||
|
)
|
||||||
|
|
||||||
|
assert isinstance(decision, RoutingDecision)
|
||||||
|
assert decision.stay_in_room is True
|
||||||
|
|
||||||
|
|
||||||
|
class TestContextKeywordButler:
|
||||||
|
"""Test 3: Kontext-Keyword → butler (echter Kontext-Match)."""
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_context_keyword_triggers_butler(self, multi_room_map):
|
||||||
|
"""'adapter gateway' (2 Kontext-Keywords) im #LAN-Doku → butler nach #RC-Plugin."""
|
||||||
|
router = _make_router(multi_room_map)
|
||||||
|
|
||||||
|
# 'adapter' + 'gateway' sind Kontext-Keywords für #RC-Plugin
|
||||||
|
# min_score=2 → beide müssen matchen
|
||||||
|
decision = await router.route(
|
||||||
|
"Der Adapter und das Gateway funktionieren nicht",
|
||||||
|
origin_room_id="room_lan_doku",
|
||||||
|
)
|
||||||
|
|
||||||
|
assert isinstance(decision, RoutingDecision)
|
||||||
|
assert decision.target_room == "room_rc_plugin"
|
||||||
|
assert decision.move_request_sent is True # Kontext → Butler
|
||||||
|
assert decision.matched_room_name == "#RC-Plugin"
|
||||||
|
assert decision.set_sticky is False # Kontext-Keyword setzt KEIN Sticky
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_context_keyword_origin_priority(self, multi_room_map):
|
||||||
|
"""'netzwerk lan' (2 Kontext-Keywords) im #LAN-Doku → stay (Origin-Priorität)."""
|
||||||
|
router = _make_router(multi_room_map)
|
||||||
|
|
||||||
|
# 'netzwerk' + 'lan' sind Kontext-Keywords für #LAN-Doku
|
||||||
|
# Origin-Priorität: Kontext-Keywords im Ursprungsraum matchen zuerst
|
||||||
|
decision = await router.route(
|
||||||
|
"Das Netzwerk im LAN ist langsam",
|
||||||
|
origin_room_id="room_lan_doku",
|
||||||
|
)
|
||||||
|
|
||||||
|
assert isinstance(decision, RoutingDecision)
|
||||||
|
# Origin-Priorität: Kontext-Keyword matched den Ursprungsraum
|
||||||
|
# → stay_in_room (self-match)
|
||||||
|
assert decision.stay_in_room is True
|
||||||
|
|
||||||
|
|
||||||
|
class TestFAISSHighScore:
|
||||||
|
"""Test 4: FAISS hohe Ähnlichkeit → route (echter FAISS-Score)."""
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_faiss_high_score_routes(self, multi_room_map):
|
||||||
|
"""FAISS-Score >= 0.85 → Auto-Route ohne LLM."""
|
||||||
|
# Baue einen echten FAISS-Index mit den Test-Räumen
|
||||||
|
try:
|
||||||
|
import faiss
|
||||||
|
import numpy as np
|
||||||
|
except ImportError:
|
||||||
|
pytest.skip("faiss not installed")
|
||||||
|
|
||||||
|
from plugin.archivar.room_index import RoomIndexManager
|
||||||
|
|
||||||
|
mock_client = MockEmbeddingClient()
|
||||||
|
classifier = IntentClassifier(embedding_client=mock_client)
|
||||||
|
state = ArchivarState()
|
||||||
|
|
||||||
|
# Baue FAISS-Index
|
||||||
|
index_mgr = RoomIndexManager(multi_room_map, mock_client)
|
||||||
|
index_mgr.build_index()
|
||||||
|
|
||||||
|
from plugin.archivar.booster import KeywordBooster
|
||||||
|
booster = KeywordBooster(multi_room_map)
|
||||||
|
|
||||||
|
router = BidirectionalRouter(
|
||||||
|
multi_room_map, classifier, state,
|
||||||
|
room_index=index_mgr, booster=booster,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Mit Mock-Embeddings (alle gleich) wird FAISS den ersten Raum
|
||||||
|
# mit höchstem Score matchen. Da alle Vektoren gleich sind,
|
||||||
|
# ist der Score ~1.0 → Auto-Route.
|
||||||
|
decision = await router.route(
|
||||||
|
"Plugin Entwicklung und Wartung", # Ähnlich zum Theme von #RC-Plugin
|
||||||
|
origin_room_id="room_bat_team",
|
||||||
|
)
|
||||||
|
|
||||||
|
assert isinstance(decision, RoutingDecision)
|
||||||
|
# FAISS sollte einen Treffer liefern (alle Vektoren gleich → erster Raum)
|
||||||
|
if decision.is_faiss_routed:
|
||||||
|
assert decision.faiss_score >= 0.85
|
||||||
|
assert decision.faiss_room_id != ""
|
||||||
|
assert decision.move_request_sent is False # FAISS-Auto-Route → kein Butler
|
||||||
|
assert decision.booster_applied is True # Booster immer aktiv
|
||||||
|
|
||||||
|
|
||||||
|
class TestFAISSMidScore:
|
||||||
|
"""Test 5: FAISS mittlere Ähnlichkeit → butler (echter FAISS-Score)."""
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_faiss_mid_score_butler(self, multi_room_map):
|
||||||
|
"""FAISS-Score < 0.85 → Butler (Move-Request)."""
|
||||||
|
try:
|
||||||
|
import faiss
|
||||||
|
import numpy as np
|
||||||
|
except ImportError:
|
||||||
|
pytest.skip("faiss not installed")
|
||||||
|
|
||||||
|
from plugin.archivar.room_index import RoomIndexManager
|
||||||
|
|
||||||
|
mock_client = MockEmbeddingClient()
|
||||||
|
classifier = IntentClassifier(embedding_client=mock_client)
|
||||||
|
state = ArchivarState()
|
||||||
|
|
||||||
|
index_mgr = RoomIndexManager(multi_room_map, mock_client)
|
||||||
|
index_mgr.build_index()
|
||||||
|
|
||||||
|
from plugin.archivar.booster import KeywordBooster
|
||||||
|
booster = KeywordBooster(multi_room_map)
|
||||||
|
|
||||||
|
router = BidirectionalRouter(
|
||||||
|
multi_room_map, classifier, state,
|
||||||
|
room_index=index_mgr, booster=booster,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Mit Mock-Embeddings sind alle Scores ~1.0, also Auto-Route.
|
||||||
|
# Der Butler-Pfad wird nur erreicht wenn score < FAISS_AUTO_ROUTE (0.85).
|
||||||
|
# Mit echten Embeddings wäre das der Fall bei mittlerer Ähnlichkeit.
|
||||||
|
# Mit Mock-Embeddings testen wir, dass der Flow NICHT crashed.
|
||||||
|
decision = await router.route(
|
||||||
|
"Irgendein Thema das zu keinem Raum passt",
|
||||||
|
origin_room_id="room_bat_team",
|
||||||
|
)
|
||||||
|
|
||||||
|
assert isinstance(decision, RoutingDecision)
|
||||||
|
# Entweder FAISS-Auto-Route oder Fallthrough zu LLM
|
||||||
|
# Beides sind valide Pfade
|
||||||
|
assert decision.category in ("work_order", "direct_question", "smalltalk")
|
||||||
|
|
||||||
|
|
||||||
|
class TestLLMStay:
|
||||||
|
"""Test 6: LLM → STAY (Mock-LLM gibt STAY)."""
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_llm_stay_returns_stay_in_room(self, multi_room_map):
|
||||||
|
"""Mock-LLM gibt STAY → stay_in_room."""
|
||||||
|
async def mock_llm_stay(prompt: str):
|
||||||
|
return "STAY" # STAY
|
||||||
|
|
||||||
|
router = _make_router(multi_room_map, mock_llm_fn=mock_llm_stay)
|
||||||
|
|
||||||
|
# Nachricht ohne Keywords → fällt durch zu LLM
|
||||||
|
decision = await router.route(
|
||||||
|
"Irgendeine Nachricht ohne Keywords",
|
||||||
|
origin_room_id="room_bat_team",
|
||||||
|
)
|
||||||
|
|
||||||
|
assert isinstance(decision, RoutingDecision)
|
||||||
|
assert decision.stay_in_room is True
|
||||||
|
assert decision.target_room == ""
|
||||||
|
assert decision.move_request_sent is False
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_llm_failed_returns_stay(self, multi_room_map):
|
||||||
|
"""Mock-LLM fehlgeschlagen → stay_in_room."""
|
||||||
|
async def mock_llm_failed(prompt: str):
|
||||||
|
return None # FAILED
|
||||||
|
|
||||||
|
router = _make_router(multi_room_map, mock_llm_fn=mock_llm_failed)
|
||||||
|
|
||||||
|
decision = await router.route(
|
||||||
|
"Noch eine Nachricht ohne Keywords",
|
||||||
|
origin_room_id="room_bat_team",
|
||||||
|
)
|
||||||
|
|
||||||
|
assert isinstance(decision, RoutingDecision)
|
||||||
|
assert decision.stay_in_room is True
|
||||||
|
assert decision.target_room == ""
|
||||||
|
|
||||||
|
|
||||||
|
class TestLLMRoute:
|
||||||
|
"""Test 7: LLM → ROUTE (Mock-LLM gibt ROUTE)."""
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_llm_route_returns_target_room(self, multi_room_map):
|
||||||
|
"""Mock-LLM gibt #RC-Plugin → butler mit target_room."""
|
||||||
|
async def mock_llm_route(prompt: str):
|
||||||
|
return "room_rc_plugin" # ROUTE to #RC-Plugin
|
||||||
|
|
||||||
|
router = _make_router(multi_room_map, mock_llm_fn=mock_llm_route)
|
||||||
|
|
||||||
|
decision = await router.route(
|
||||||
|
"Nachricht ohne Keywords, LLM routet",
|
||||||
|
origin_room_id="room_bat_team",
|
||||||
|
)
|
||||||
|
|
||||||
|
assert isinstance(decision, RoutingDecision)
|
||||||
|
assert decision.target_room == "room_rc_plugin"
|
||||||
|
assert decision.move_request_sent is True # LLM → Butler
|
||||||
|
assert decision.matched_room_name == "#RC-Plugin"
|
||||||
|
assert decision.category == "work_order"
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_llm_route_origin_guard_blocks_self(self, multi_room_map):
|
||||||
|
"""LLM schlägt Ursprungsraum vor → Origin-First Guard → stay."""
|
||||||
|
async def mock_llm_route_origin(prompt: str):
|
||||||
|
return "room_bat_team" # ROUTE to origin room
|
||||||
|
|
||||||
|
router = _make_router(multi_room_map, mock_llm_fn=mock_llm_route_origin)
|
||||||
|
|
||||||
|
decision = await router.route(
|
||||||
|
"Nachricht ohne Keywords, LLM schlägt Ursprungsraum vor",
|
||||||
|
origin_room_id="room_bat_team",
|
||||||
|
)
|
||||||
|
|
||||||
|
assert isinstance(decision, RoutingDecision)
|
||||||
|
# Origin-First Guard: LLM == origin_room → stay_in_room
|
||||||
|
assert decision.stay_in_room is True
|
||||||
|
assert decision.target_room == ""
|
||||||
|
|
||||||
|
|
||||||
|
# ── Telemetry Integration Test ─────────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
class TestTelemetryIntegration:
|
||||||
|
"""Telemetrie wird im Router-Flow korrekt aufgerufen."""
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_telemetry_records_on_keyword_100(self, multi_room_map, caplog):
|
||||||
|
"""100%-Keyword-Match → Telemetrie-Record wird geschrieben."""
|
||||||
|
import logging
|
||||||
|
caplog.set_level(logging.INFO)
|
||||||
|
|
||||||
|
router = _make_router(multi_room_map)
|
||||||
|
|
||||||
|
# Sicherstellen dass Telemetrie enabled ist
|
||||||
|
routing_telemetry._enabled = True
|
||||||
|
routing_telemetry.clear()
|
||||||
|
|
||||||
|
decision = await router.route(
|
||||||
|
"Das Plugin hat einen Bug",
|
||||||
|
origin_room_id="room_bat_team",
|
||||||
|
)
|
||||||
|
|
||||||
|
assert isinstance(decision, RoutingDecision)
|
||||||
|
assert decision.target_room == "room_rc_plugin"
|
||||||
|
|
||||||
|
# Flush manuell (normalerweise macht das adapter.py)
|
||||||
|
routing_telemetry.flush()
|
||||||
|
|
||||||
|
log_text = caplog.text
|
||||||
|
assert '[TELEMETRY]' in log_text
|
||||||
|
assert 'stage=keyword_100' in log_text
|
||||||
|
assert 'score=1.00' in log_text
|
||||||
|
assert 'decision=route' in log_text
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_telemetry_records_on_context_keyword(self, multi_room_map, caplog):
|
||||||
|
"""Kontext-Keyword-Match → Telemetrie-Record mit decision=butler."""
|
||||||
|
import logging
|
||||||
|
caplog.set_level(logging.INFO)
|
||||||
|
|
||||||
|
router = _make_router(multi_room_map)
|
||||||
|
routing_telemetry._enabled = True
|
||||||
|
routing_telemetry.clear()
|
||||||
|
|
||||||
|
decision = await router.route(
|
||||||
|
"Der Adapter und das Gateway funktionieren nicht",
|
||||||
|
origin_room_id="room_lan_doku",
|
||||||
|
)
|
||||||
|
|
||||||
|
assert isinstance(decision, RoutingDecision)
|
||||||
|
assert decision.move_request_sent is True
|
||||||
|
|
||||||
|
routing_telemetry.flush()
|
||||||
|
|
||||||
|
log_text = caplog.text
|
||||||
|
assert '[TELEMETRY]' in log_text
|
||||||
|
assert 'stage=context_keyword' in log_text
|
||||||
|
assert 'decision=butler' in log_text
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
pytest.main([__file__, "-v"])
|
||||||
Reference in New Issue
Block a user