feat(archivar): Telemetrie um STAY/UNSICHER/TIMEOUT-Unterscheidung erweitern

Auftrag t_5e4863c6 — Routing-Telemetrie differenziert jetzt:
- llm_stay_sicher  — LLM sagte STAY (sicher), kein Red Flag, kein Cloud-Call
- llm_unsicher     — LLM sagte UNSICHER, Red Flag (Cloud-Call)
- llm_timeout      — LLM timeoutete (separat von llm_unavailable)
- cloud_call_stay  — Cloud-Agent endete mit STAY (Cloud-Call ohne Routing-Effekt)
- cloud_call_route — Cloud-Agent entschied ROUTE (Cloud-Call mit Wirkung)
- no_llm_needed    — Nachricht vor Stufe 4 entschieden (FAISS/Keyword/Smalltalk)

Abwärtskompatibel: llm_stay und llm_unavailable bleiben unverändert.
::status zeigt die neuen Zähler in einer Routing-Telemetrie-Sektion.
10 neue Tests (test_telemetry_stay_unsicher_timeout.py).
This commit is contained in:
Bernd (Hermes)
2026-09-02 15:36:05 +02:00
parent 21b1fd4e13
commit 00aecfaa7b
5 changed files with 355 additions and 2 deletions
@@ -0,0 +1,304 @@
"""
Telemetrie-Erweiterung: STAY/UNSICHER/TIMEOUT-Unterscheidung (Auftrag t_5e4863c6).
Die bisherige Telemetrie zählte nur llm_stay, llm_unavailable, red_flag_triggered.
Diese Erweiterung unterscheidet:
1. llm_stay_sicher — LLM sagte STAY (sicher), kein Red Flag, kein Cloud-Call
2. llm_unsicher — LLM sagte UNSICHER, Red Flag (Cloud-Call)
3. llm_timeout — LLM timeoutete (separater Zähler, nicht mit llm_unavailable vermischt)
4. cloud_call_stay — Cloud-Agent endete mit STAY (Cloud-Call ohne Routing-Effekt)
5. cloud_call_route — Cloud-Agent entschied ROUTE (Cloud-Call mit Wirkung)
6. no_llm_needed — Nachricht wurde vor Stufe 4 entschieden (FAISS/Keyword/Smalltalk)
Abwärtskompatibilität: llm_stay und llm_unavailable bleiben unverändert.
"""
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
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
class MockEmbeddingClient(EmbeddingClient):
def get_embedding(self, text: str) -> Optional[list]:
return [0.1] * 768
def _make_room_map(non_catchall: int) -> RoomMap:
"""Baut eine RoomMap mit N Nicht-Catch-All-Räumen + 1 Catch-All."""
tmp = tempfile.TemporaryDirectory()
map_path = Path(tmp.name) / "room-map.json"
rooms = {}
for i in range(non_catchall):
rooms[f"room_{i}"] = {
"name": f"#Raum{i}",
"theme": f"Thema {i}",
"description": f"Beschreibung {i}",
"keywords_100": [f"kw{i}"],
"keywords_context": [],
"catch_all": False,
}
rooms["room_catchall"] = {
"name": "#CatchAll",
"theme": "Catch-all room",
"keywords_100": [],
"keywords_context": [],
"catch_all": True,
}
test_data = {
"version": 5,
"rooms": rooms,
"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:
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
# ── Zähler 1: llm_stay_sicher ────────────────────────────────────────────────
class TestLlmStaySicher:
"""STAY (sicher) inkrementiert llm_stay_sicher, NICHT red_flag_triggered."""
def test_stay_increments_llm_stay_sicher(self):
routing_counter.reset()
room_map = _make_room_map(non_catchall=5)
async def mock_llm_stay(prompt: str) -> str:
return "STAY"
router = _make_router(room_map, mock_llm_stay)
asyncio.run(router.route("Generische Frage", origin_room_id="room_0"))
counts = routing_counter.get_counts()
assert counts.get("llm_stay_sicher", 0) >= 1, (
f"Expected llm_stay_sicher >= 1, got {counts}"
)
# Abwärtskompatibilität: llm_stay bleibt ebenfalls inkrementiert.
assert counts.get("llm_stay", 0) >= 1
# Kein Red Flag → kein Cloud-Call.
assert counts.get("red_flag_triggered", 0) == 0
# ── Zähler 2: llm_unsicher ───────────────────────────────────────────────────
class TestLlmUnsicher:
"""UNSICHER inkrementiert llm_unsicher + red_flag_triggered."""
def test_unsicher_increments_llm_unsicher(self):
routing_counter.reset()
room_map = _make_room_map(non_catchall=2)
async def mock_llm_unsicher(prompt: str) -> str:
return "UNSICHER"
router = _make_router(room_map, mock_llm_unsicher)
asyncio.run(router.route("Mehrdeutige Nachricht", origin_room_id="room_0"))
counts = routing_counter.get_counts()
assert counts.get("llm_unsicher", 0) >= 1, (
f"Expected llm_unsicher >= 1, got {counts}"
)
assert counts.get("red_flag_triggered", 0) >= 1
# ── Zähler 3: llm_timeout ────────────────────────────────────────────────────
class TestLlmTimeout:
"""Timeout inkrementiert llm_timeout (separat von llm_unavailable)."""
def test_timeout_increments_llm_timeout(self):
"""Echter asyncio.TimeoutError → llm_timeout + llm_unavailable."""
routing_counter.reset()
room_map = _make_room_map(non_catchall=5)
async def mock_llm_timeout(prompt: str) -> str:
raise asyncio.TimeoutError()
router = _make_router(room_map, mock_llm_timeout)
asyncio.run(router.route("Generische Frage", origin_room_id="room_0"))
counts = routing_counter.get_counts()
# llm_timeout wird bei echtem Timeout inkrementiert.
assert counts.get("llm_timeout", 0) >= 1, (
f"Expected llm_timeout >= 1, got {counts}"
)
# llm_unavailable bleibt der Umbrella-Zähler (Abwärtskompatibilität).
assert counts.get("llm_unavailable", 0) >= 1
def test_timeout_counter_distinct_from_unavailable(self):
"""llm_timeout ist ein eigener Key, unabhängig von llm_unavailable."""
routing_counter.reset()
# Direkt: der Zähler ist ein separater Key im Counter-Dict.
routing_counter.increment("llm_timeout")
routing_counter.increment("llm_unavailable")
counts = routing_counter.get_counts()
assert counts["llm_timeout"] == 1
assert counts["llm_unavailable"] == 1
# ── Zähler 4 + 5: cloud_call_stay / cloud_call_route ────────────────────────
class TestCloudCallCounters:
"""Cloud-Call-Ergebnis wird als stay/route unterschieden."""
def test_cloud_call_counters_are_distinct_keys(self):
routing_counter.reset()
routing_counter.increment("cloud_call_stay")
routing_counter.increment("cloud_call_route")
counts = routing_counter.get_counts()
assert counts["cloud_call_stay"] == 1
assert counts["cloud_call_route"] == 1
# ── Zähler 6: no_llm_needed ─────────────────────────────────────────────────
class TestNoLlmNeeded:
"""Nachricht vor Stufe 4 entschieden → no_llm_needed."""
def test_smalltalk_increments_no_llm_needed(self):
"""Smalltalk (Embedding-Vorfilter) → no_llm_needed, kein LLM-Call."""
routing_counter.reset()
room_map = _make_room_map(non_catchall=3)
# Mock classifier: Smalltalk mit hoher Konfidenz.
from plugin.archivar.classifier import ClassificationResult
class SmalltalkClassifier(IntentClassifier):
def __init__(self):
super().__init__(embedding_client=MockEmbeddingClient())
self._initialized = True
async def classify(self, text):
return ClassificationResult(
category="smalltalk", confidence=0.95, all_scores={}
)
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, SmalltalkClassifier(), state)
asyncio.run(router.route("Hallo, wie geht's?", origin_room_id="room_0"))
counts = routing_counter.get_counts()
assert counts.get("no_llm_needed", 0) >= 1, (
f"Expected no_llm_needed >= 1, got {counts}"
)
# ── Abwärtskompatibilität ────────────────────────────────────────────────────
class TestBackwardCompatibility:
"""Bestehende Zähler llm_stay / llm_unavailable bleiben intakt."""
def test_llm_stay_still_incremented(self):
routing_counter.reset()
room_map = _make_room_map(non_catchall=5)
async def mock_llm_stay(prompt: str) -> str:
return "STAY"
router = _make_router(room_map, mock_llm_stay)
asyncio.run(router.route("Generische Frage", origin_room_id="room_0"))
counts = routing_counter.get_counts()
assert counts.get("llm_stay", 0) >= 1
def test_llm_unavailable_still_incremented(self):
routing_counter.reset()
room_map = _make_room_map(non_catchall=5)
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_0"))
counts = routing_counter.get_counts()
assert counts.get("llm_unavailable", 0) >= 1
# ── ::status zeigt die neuen Zähler ──────────────────────────────────────────
class TestStatusTextRoutingCounts:
"""build_status_text zeigt die STAY/UNSICHER/TIMEOUT-Sektion."""
def test_status_shows_all_six_counters(self):
from plugin.archivar.inline_commands import build_status_text
counts = {
"llm_stay_sicher": 10,
"llm_unsicher": 3,
"llm_timeout": 5,
"cloud_call_stay": 7,
"cloud_call_route": 1,
"no_llm_needed": 20,
}
text = build_status_text(
room_count=3,
archivar_active=True,
butler_mode="cognitive",
routing_counts=counts,
)
assert "Routing-Telemetrie" in text
assert "LLM STAY (sicher):** 10" in text
assert "LLM UNSICHER:** 3" in text
assert "LLM Timeout:** 5" in text
assert "Cloud-Call → STAY:** 7" in text
assert "Cloud-Call → ROUTE:** 1" in text
assert "Ohne LLM entschieden:** 20" in text
def test_status_without_counts_omits_section(self):
from plugin.archivar.inline_commands import build_status_text
text = build_status_text(room_count=3, archivar_active=True)
assert "Routing-Telemetrie" not in text