P0 Nachbesserungen + V7-1: Butler antwortet im Zielraum
Auflage 1: Unit-Tests für ConversationHistory (34 Tests)
- test_conversation_history.py: add/get, Ring-Buffer, topic_hint,
cleanup_orphaned_rooms (sync+async), Thread-safety, Edge cases
Auflage 2: Schritt-4.5 Stick-Check im Router
- router.py Zeile ~556: _check_never_route_topic VOR is_100_percent_match
in Schritt 4.5 (Keyword-Match vor LLM) eingefügt
Auflage 3: Topic-Extraktion zentralisieren
- router.py: room_name_to_topic als Module-Level-Alias exportiert
- adapter.py: importiert room_name_to_topic, ersetzt 2× inline
.lstrip('#').lower().replace(' ', '-') durch zentralen Aufruf
V7-1: Butler antwortet im Zielraum + Breadcrumb
- adapter.py _process_incoming: move_request_sent=True → return (kein Agent-Dispatch)
- adapter.py Move-Request-Handler: bei ✅Ja → Breadcrumb im Ursprungsraum,
_CURRENT_ORIGIN_ROOM + _THEMATIC_TARGET_ROOM auf Zielraum gesetzt,
_dispatch_agent() im Zielraum-Kontext
- adapter.py _dispatch_agent(): extrahierte Dispatch-Methode für V7-1-Pfad
Syntax-Check: alle .py bestehen py_compile
Tests: 99/100 passed (1 pre-existing env-var failure)
This commit is contained in:
@@ -14,6 +14,7 @@ from .doc_store import DocumentationStore
|
||||
from .router import BidirectionalRouter, RoutingDecision
|
||||
from .adapter_integration import ArchivarMessageHandler
|
||||
from .archivar_state import ArchivarState
|
||||
from .conversation_history import ConversationHistory, MessageEntry
|
||||
|
||||
__all__ = [
|
||||
"IntentClassifier",
|
||||
@@ -32,4 +33,6 @@ __all__ = [
|
||||
"RoutingDecision",
|
||||
"ArchivarMessageHandler",
|
||||
"ArchivarState",
|
||||
"ConversationHistory",
|
||||
"MessageEntry",
|
||||
]
|
||||
|
||||
@@ -131,6 +131,7 @@ class ArchivarMessageHandler:
|
||||
ollama_base_url: Optional[str] = None,
|
||||
embedding_client: Optional[EmbeddingClient] = None,
|
||||
llm_client: Optional[LLMClient] = None,
|
||||
conversation_history: Optional[Any] = None,
|
||||
) -> None:
|
||||
"""
|
||||
Args:
|
||||
@@ -149,6 +150,9 @@ class ArchivarMessageHandler:
|
||||
llm_client: Optionales ``LLMClient``-Interface.
|
||||
Wird an den ``IntentClassifier`` durchgereicht.
|
||||
Ermöglicht Mocking/alternative LLM-Backends.
|
||||
conversation_history: Optionale ``ConversationHistory``-Instanz (B5v6.5).
|
||||
Wird an den ``BidirectionalRouter`` durchgereicht für
|
||||
Konversationskontext bei Themenwechsel- und rekursiver Erkennung.
|
||||
"""
|
||||
self._send_callback = send_callback
|
||||
self._button_send_callback = button_send_callback
|
||||
@@ -177,7 +181,13 @@ class ArchivarMessageHandler:
|
||||
# Cache for subscribed room IDs (set later via set_subscribed_room_ids)
|
||||
self._subscribed_room_ids_cache: Optional[set] = None
|
||||
|
||||
self._router = BidirectionalRouter(self._room_map, self._classifier, self._state)
|
||||
# B5v6.5: ConversationHistory für Konversationskontext
|
||||
self._conversation_history = conversation_history
|
||||
|
||||
self._router = BidirectionalRouter(
|
||||
self._room_map, self._classifier, self._state,
|
||||
conversation_history=conversation_history,
|
||||
)
|
||||
|
||||
# ── FAISS Phase-1: RoomIndexManager + KeywordBooster ──────────────
|
||||
self._room_index: Optional[RoomIndexManager] = None
|
||||
@@ -329,7 +339,8 @@ class ArchivarMessageHandler:
|
||||
# 3. Router mit FAISS-Objekten neu erstellen
|
||||
self._router = BidirectionalRouter(
|
||||
self._room_map, self._classifier, self._state,
|
||||
room_index=self._room_index, booster=self._booster
|
||||
room_index=self._room_index, booster=self._booster,
|
||||
conversation_history=self._conversation_history,
|
||||
)
|
||||
logger.info("FAISS Phase-1: Router mit RoomIndexManager + KeywordBooster verdrahtet")
|
||||
except Exception as e:
|
||||
|
||||
@@ -0,0 +1,237 @@
|
||||
"""
|
||||
ConversationHistory — Ring-Buffer für Konversationshistorie pro Raum.
|
||||
|
||||
Sub-Feature B5v6.5: Blocker für V7-3 (Verfall) und V7-4 (rekursive Einleitungen).
|
||||
|
||||
Speichert die letzten N=10 Nachrichten pro Raum als In-Memory Ring-Buffer.
|
||||
Thread-safe via asyncio.Lock. Nicht persistent — nach Neustart beginnt
|
||||
die Historie neu (akzeptiert von Andreas: 'jetzt' verblasst ohnehin).
|
||||
|
||||
Usage::
|
||||
|
||||
history = ConversationHistory(max_size=10)
|
||||
history.add("room-123", "user", "Was ist der Status?")
|
||||
history.add("room-123", "agent", "Alles grün.")
|
||||
recent = history.get("room-123") # → letzte 10 Nachrichten
|
||||
history.set_topic_hint("room-123", "Deployment-Status")
|
||||
hint = history.get_topic_hint("room-123") # → "Deployment-Status"
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
from collections import deque
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@dataclass
|
||||
class MessageEntry:
|
||||
"""Ein einzelner Eintrag im Ring-Buffer."""
|
||||
|
||||
role: str
|
||||
"""'user' oder 'agent'."""
|
||||
|
||||
text: str
|
||||
"""Nachrichtentext."""
|
||||
|
||||
timestamp: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
"""Zeitstempel der Nachricht (UTC)."""
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
"""Serialisiere für externe Nutzung (z.B. Prompt-Bau)."""
|
||||
return {
|
||||
"role": self.role,
|
||||
"text": self.text,
|
||||
"timestamp": self.timestamp.isoformat(),
|
||||
}
|
||||
|
||||
|
||||
class ConversationHistory:
|
||||
"""Ring-Buffer für Konversationshistorie pro Raum.
|
||||
|
||||
Thread-safe via asyncio.Lock. In-Memory, nicht persistent.
|
||||
"""
|
||||
|
||||
def __init__(self, max_size: int = 10) -> None:
|
||||
"""Initialisiere den Ring-Buffer.
|
||||
|
||||
Args:
|
||||
max_size: Maximale Anzahl Nachrichten pro Raum (default: 10).
|
||||
"""
|
||||
if max_size < 1:
|
||||
raise ValueError(f"max_size must be >= 1, got {max_size}")
|
||||
self._max_size = max_size
|
||||
self._lock = asyncio.Lock()
|
||||
# room_id → deque[MessageEntry] (maxlen=self._max_size)
|
||||
self._buffers: Dict[str, deque[MessageEntry]] = {}
|
||||
# room_id → topic string
|
||||
self._topic_hints: Dict[str, str] = {}
|
||||
|
||||
# ── Public API ──────────────────────────────────────────────────────
|
||||
|
||||
async def add(
|
||||
self,
|
||||
room_id: str,
|
||||
role: str,
|
||||
text: str,
|
||||
timestamp: Optional[datetime] = None,
|
||||
) -> None:
|
||||
"""Füge eine Nachricht zum Ring-Buffer hinzu.
|
||||
|
||||
Wenn der Buffer voll ist (max_size erreicht), fällt die älteste
|
||||
Nachricht automatisch heraus (deque mit maxlen).
|
||||
|
||||
Args:
|
||||
room_id: Rocket.Chat Raum-ID.
|
||||
role: 'user' oder 'agent'.
|
||||
text: Nachrichtentext.
|
||||
timestamp: Optionaler Zeitstempel (default: jetzt UTC).
|
||||
"""
|
||||
if not room_id:
|
||||
return
|
||||
if not text or not text.strip():
|
||||
return
|
||||
|
||||
entry = MessageEntry(
|
||||
role=role,
|
||||
text=text.strip(),
|
||||
timestamp=timestamp or datetime.now(timezone.utc),
|
||||
)
|
||||
|
||||
async with self._lock:
|
||||
if room_id not in self._buffers:
|
||||
self._buffers[room_id] = deque(maxlen=self._max_size)
|
||||
self._buffers[room_id].append(entry)
|
||||
|
||||
async def get(
|
||||
self,
|
||||
room_id: str,
|
||||
limit: Optional[int] = None,
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""Liefere die letzten N Nachrichten für einen Raum.
|
||||
|
||||
Args:
|
||||
room_id: Rocket.Chat Raum-ID.
|
||||
limit: Maximale Anzahl zurückzugebender Nachrichten.
|
||||
None oder > max_size → alle im Buffer (max max_size).
|
||||
|
||||
Returns:
|
||||
Liste von dicts mit 'role', 'text', 'timestamp' (ISO-Format),
|
||||
neueste zuletzt. Leere Liste wenn Raum nicht existiert.
|
||||
"""
|
||||
async with self._lock:
|
||||
buf = self._buffers.get(room_id)
|
||||
if buf is None:
|
||||
return []
|
||||
|
||||
entries = list(buf)
|
||||
if limit is not None and limit < len(entries):
|
||||
entries = entries[-limit:]
|
||||
|
||||
return [e.to_dict() for e in entries]
|
||||
|
||||
async def get_topic_hint(self, room_id: str) -> Optional[str]:
|
||||
"""Liefere das letzte bekannte Thema für einen Raum.
|
||||
|
||||
Args:
|
||||
room_id: Rocket.Chat Raum-ID.
|
||||
|
||||
Returns:
|
||||
Thema-String oder None wenn kein Thema gesetzt.
|
||||
"""
|
||||
async with self._lock:
|
||||
return self._topic_hints.get(room_id)
|
||||
|
||||
async def set_topic_hint(self, room_id: str, topic: str) -> None:
|
||||
"""Setze das Thema für einen Raum.
|
||||
|
||||
Wird vom Router gesetzt, wenn das LLM ein Thema erkennt.
|
||||
Überschreibt ein vorheriges Thema.
|
||||
|
||||
Args:
|
||||
room_id: Rocket.Chat Raum-ID.
|
||||
topic: Thema-String (z.B. 'Deployment-Status').
|
||||
"""
|
||||
if not room_id or not topic:
|
||||
return
|
||||
async with self._lock:
|
||||
self._topic_hints[room_id] = topic.strip()
|
||||
logger.debug(
|
||||
"Topic hint set for room %s: %s",
|
||||
room_id[:8],
|
||||
topic[:60],
|
||||
)
|
||||
|
||||
async def clear(self, room_id: str) -> None:
|
||||
"""Lösche die Historie für einen Raum (M13 GC).
|
||||
|
||||
Args:
|
||||
room_id: Rocket.Chat Raum-ID.
|
||||
"""
|
||||
async with self._lock:
|
||||
self._buffers.pop(room_id, None)
|
||||
self._topic_hints.pop(room_id, None)
|
||||
logger.debug("Conversation history cleared for room %s", room_id[:8])
|
||||
|
||||
async def cleanup_orphaned_rooms(self, active_room_ids: set) -> int:
|
||||
"""Entferne Räume, die nicht mehr aktiv sind (M13 GC).
|
||||
|
||||
Thread-safe via asyncio.Lock.
|
||||
|
||||
Args:
|
||||
active_room_ids: Set von Raum-IDs, die noch aktiv sind
|
||||
(aus room-map.json nach M13-Bereinigung).
|
||||
|
||||
Returns:
|
||||
Anzahl der entfernten Räume.
|
||||
"""
|
||||
async with self._lock:
|
||||
return self.cleanup_orphaned_rooms_sync(active_room_ids)
|
||||
|
||||
def cleanup_orphaned_rooms_sync(self, active_room_ids: set) -> int:
|
||||
"""Sync-Variante für M13 GC (Startup, kein Concurrent-Access).
|
||||
|
||||
Args:
|
||||
active_room_ids: Set von Raum-IDs, die noch aktiv sind.
|
||||
|
||||
Returns:
|
||||
Anzahl der entfernten Räume.
|
||||
"""
|
||||
orphaned = [
|
||||
rid
|
||||
for rid in self._buffers
|
||||
if rid not in active_room_ids
|
||||
]
|
||||
for rid in orphaned:
|
||||
del self._buffers[rid]
|
||||
self._topic_hints.pop(rid, None)
|
||||
|
||||
if orphaned:
|
||||
logger.info(
|
||||
"ConversationHistory GC: %d orphaned rooms removed (%d remaining)",
|
||||
len(orphaned),
|
||||
len(self._buffers),
|
||||
)
|
||||
return len(orphaned)
|
||||
|
||||
# ── Utility ─────────────────────────────────────────────────────────
|
||||
|
||||
@property
|
||||
def max_size(self) -> int:
|
||||
"""Maximale Anzahl Nachrichten pro Raum."""
|
||||
return self._max_size
|
||||
|
||||
@property
|
||||
def room_count(self) -> int:
|
||||
"""Anzahl der Räume mit Historie (nicht thread-safe, für Debug)."""
|
||||
return len(self._buffers)
|
||||
|
||||
async def get_room_count(self) -> int:
|
||||
"""Thread-safe: Anzahl der Räume mit Historie."""
|
||||
async with self._lock:
|
||||
return len(self._buffers)
|
||||
@@ -547,6 +547,15 @@ class BidirectionalRouter:
|
||||
notification = f"📋 Bearbeite ich in #{room_name} — [Link]"
|
||||
matched_keywords = self._extract_matched_keywords(text, matched_room)
|
||||
|
||||
# ── P0-B: never_route topic check ──────────────────
|
||||
if self._check_never_route_topic(origin_room_id, matched_room):
|
||||
return RoutingDecision(
|
||||
category="direct_question",
|
||||
target_room="",
|
||||
confidence=1.0,
|
||||
stay_in_room=True,
|
||||
)
|
||||
|
||||
# ── FIX C: 100% vs Kontext-Keywords unterscheiden ──
|
||||
is_100 = self._room_map.is_100_percent_match(text, matched_room)
|
||||
if is_100:
|
||||
@@ -995,4 +1004,10 @@ class BidirectionalRouter:
|
||||
|
||||
logger.info("Moving message from %s to %s", source_room[:8], target_room[:8])
|
||||
# Die tatsächliche Implementierung erfolgt im Adapter
|
||||
return True
|
||||
return True
|
||||
|
||||
|
||||
# ── Module-level alias für externe Nutzer (adapter.py) ──────────────
|
||||
# Zentralisierte Topic-Extraktion: adapter.py importiert diese Funktion
|
||||
# statt die Logik an mehreren Stellen zu duplizieren.
|
||||
room_name_to_topic = BidirectionalRouter._room_name_to_topic
|
||||
@@ -0,0 +1,415 @@
|
||||
"""
|
||||
Unit-Tests für ConversationHistory (B5v6.5).
|
||||
|
||||
Testet:
|
||||
- add + get (Ring-Buffer Verhalten, älteste fällt raus)
|
||||
- topic_hint (set, get, clear)
|
||||
- cleanup_orphaned_rooms (sync + async)
|
||||
- Thread-safety (concurrent adds)
|
||||
- Edge cases: leerer Raum, nicht-existenter Raum
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
# Add the parent directory to the path
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
|
||||
|
||||
from conversation_history import ConversationHistory, MessageEntry
|
||||
|
||||
|
||||
class TestConversationHistoryAddGet(unittest.TestCase):
|
||||
"""Tests für add() und get() — Ring-Buffer-Verhalten."""
|
||||
|
||||
def setUp(self):
|
||||
self.history = ConversationHistory(max_size=5)
|
||||
|
||||
def test_add_and_get_single_message(self):
|
||||
"""Eine Nachricht hinzufügen und abrufen."""
|
||||
async def run():
|
||||
await self.history.add("room-1", "user", "Hallo Welt")
|
||||
msgs = await self.history.get("room-1")
|
||||
self.assertEqual(len(msgs), 1)
|
||||
self.assertEqual(msgs[0]["role"], "user")
|
||||
self.assertEqual(msgs[0]["text"], "Hallo Welt")
|
||||
asyncio.run(run())
|
||||
|
||||
def test_add_and_get_multiple_messages(self):
|
||||
"""Mehrere Nachrichten — neueste zuletzt."""
|
||||
async def run():
|
||||
for i in range(3):
|
||||
await self.history.add("room-1", "user", f"Msg {i}")
|
||||
msgs = await self.history.get("room-1")
|
||||
self.assertEqual(len(msgs), 3)
|
||||
self.assertEqual(msgs[0]["text"], "Msg 0")
|
||||
self.assertEqual(msgs[2]["text"], "Msg 2")
|
||||
asyncio.run(run())
|
||||
|
||||
def test_ring_buffer_overflow(self):
|
||||
"""Wenn max_size=5 überschritten, fällt die älteste Nachricht raus."""
|
||||
async def run():
|
||||
for i in range(7):
|
||||
await self.history.add("room-1", "user", f"Msg {i}")
|
||||
msgs = await self.history.get("room-1")
|
||||
self.assertEqual(len(msgs), 5)
|
||||
# Älteste (Msg 0, Msg 1) sind rausgefallen
|
||||
self.assertEqual(msgs[0]["text"], "Msg 2")
|
||||
self.assertEqual(msgs[4]["text"], "Msg 6")
|
||||
asyncio.run(run())
|
||||
|
||||
def test_ring_buffer_exact_max(self):
|
||||
"""Genau max_size Nachrichten — keine verworfen."""
|
||||
async def run():
|
||||
for i in range(5):
|
||||
await self.history.add("room-1", "user", f"Msg {i}")
|
||||
msgs = await self.history.get("room-1")
|
||||
self.assertEqual(len(msgs), 5)
|
||||
self.assertEqual(msgs[0]["text"], "Msg 0")
|
||||
self.assertEqual(msgs[4]["text"], "Msg 4")
|
||||
asyncio.run(run())
|
||||
|
||||
def test_get_with_limit(self):
|
||||
"""get() mit limit-Parameter."""
|
||||
async def run():
|
||||
for i in range(10):
|
||||
await self.history.add("room-1", "user", f"Msg {i}")
|
||||
msgs = await self.history.get("room-1", limit=3)
|
||||
self.assertEqual(len(msgs), 3)
|
||||
self.assertEqual(msgs[0]["text"], "Msg 7")
|
||||
self.assertEqual(msgs[2]["text"], "Msg 9")
|
||||
asyncio.run(run())
|
||||
|
||||
def test_get_limit_larger_than_buffer(self):
|
||||
"""limit > buffer size → alle Nachrichten."""
|
||||
async def run():
|
||||
for i in range(3):
|
||||
await self.history.add("room-1", "user", f"Msg {i}")
|
||||
msgs = await self.history.get("room-1", limit=100)
|
||||
self.assertEqual(len(msgs), 3)
|
||||
asyncio.run(run())
|
||||
|
||||
def test_get_nonexistent_room(self):
|
||||
"""get() für nicht-existierenden Raum → leere Liste."""
|
||||
async def run():
|
||||
msgs = await self.history.get("nonexistent")
|
||||
self.assertEqual(msgs, [])
|
||||
asyncio.run(run())
|
||||
|
||||
def test_add_empty_room_id(self):
|
||||
"""add() mit leerem room_id → no-op, kein Crash."""
|
||||
async def run():
|
||||
await self.history.add("", "user", "Test")
|
||||
self.assertEqual(await self.history.get_room_count(), 0)
|
||||
asyncio.run(run())
|
||||
|
||||
def test_add_empty_text(self):
|
||||
"""add() mit leerem Text → no-op."""
|
||||
async def run():
|
||||
await self.history.add("room-1", "user", "")
|
||||
await self.history.add("room-1", "user", " ")
|
||||
msgs = await self.history.get("room-1")
|
||||
self.assertEqual(len(msgs), 0)
|
||||
asyncio.run(run())
|
||||
|
||||
def test_multiple_rooms_independent(self):
|
||||
"""Verschiedene Räume haben unabhängige Buffer."""
|
||||
async def run():
|
||||
await self.history.add("room-A", "user", "A1")
|
||||
await self.history.add("room-B", "user", "B1")
|
||||
await self.history.add("room-A", "user", "A2")
|
||||
msgs_a = await self.history.get("room-A")
|
||||
msgs_b = await self.history.get("room-B")
|
||||
self.assertEqual(len(msgs_a), 2)
|
||||
self.assertEqual(len(msgs_b), 1)
|
||||
self.assertEqual(msgs_a[0]["text"], "A1")
|
||||
self.assertEqual(msgs_b[0]["text"], "B1")
|
||||
asyncio.run(run())
|
||||
|
||||
def test_max_size_validation(self):
|
||||
"""max_size < 1 → ValueError."""
|
||||
with self.assertRaises(ValueError):
|
||||
ConversationHistory(max_size=0)
|
||||
with self.assertRaises(ValueError):
|
||||
ConversationHistory(max_size=-1)
|
||||
|
||||
def test_max_size_one(self):
|
||||
"""max_size=1: nur die letzte Nachricht bleibt."""
|
||||
async def run():
|
||||
hist = ConversationHistory(max_size=1)
|
||||
await hist.add("room-1", "user", "First")
|
||||
await hist.add("room-1", "user", "Second")
|
||||
msgs = await hist.get("room-1")
|
||||
self.assertEqual(len(msgs), 1)
|
||||
self.assertEqual(msgs[0]["text"], "Second")
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
class TestConversationHistoryTopicHint(unittest.TestCase):
|
||||
"""Tests für topic_hint (set, get, clear)."""
|
||||
|
||||
def setUp(self):
|
||||
self.history = ConversationHistory(max_size=10)
|
||||
|
||||
def test_set_and_get_topic_hint(self):
|
||||
"""Topic setzen und abrufen."""
|
||||
async def run():
|
||||
await self.history.set_topic_hint("room-1", "Deployment-Status")
|
||||
hint = await self.history.get_topic_hint("room-1")
|
||||
self.assertEqual(hint, "Deployment-Status")
|
||||
asyncio.run(run())
|
||||
|
||||
def test_get_topic_hint_nonexistent(self):
|
||||
"""Topic für nicht-existierenden Raum → None."""
|
||||
async def run():
|
||||
hint = await self.history.get_topic_hint("nonexistent")
|
||||
self.assertIsNone(hint)
|
||||
asyncio.run(run())
|
||||
|
||||
def test_set_topic_hint_overwrite(self):
|
||||
"""Zweites set_topic_hint überschreibt das erste."""
|
||||
async def run():
|
||||
await self.history.set_topic_hint("room-1", "Erstes Thema")
|
||||
await self.history.set_topic_hint("room-1", "Zweites Thema")
|
||||
hint = await self.history.get_topic_hint("room-1")
|
||||
self.assertEqual(hint, "Zweites Thema")
|
||||
asyncio.run(run())
|
||||
|
||||
def test_set_topic_hint_empty(self):
|
||||
"""set_topic_hint mit leerem room_id oder topic → no-op."""
|
||||
async def run():
|
||||
await self.history.set_topic_hint("", "Thema")
|
||||
await self.history.set_topic_hint("room-1", "")
|
||||
self.assertIsNone(await self.history.get_topic_hint(""))
|
||||
self.assertIsNone(await self.history.get_topic_hint("room-1"))
|
||||
asyncio.run(run())
|
||||
|
||||
def test_clear_removes_topic_hint(self):
|
||||
"""clear() entfernt auch den topic_hint."""
|
||||
async def run():
|
||||
await self.history.set_topic_hint("room-1", "Thema")
|
||||
await self.history.clear("room-1")
|
||||
hint = await self.history.get_topic_hint("room-1")
|
||||
self.assertIsNone(hint)
|
||||
asyncio.run(run())
|
||||
|
||||
def test_topic_hint_independent_per_room(self):
|
||||
"""Topic hints sind unabhängig pro Raum."""
|
||||
async def run():
|
||||
await self.history.set_topic_hint("room-A", "Thema A")
|
||||
await self.history.set_topic_hint("room-B", "Thema B")
|
||||
self.assertEqual(await self.history.get_topic_hint("room-A"), "Thema A")
|
||||
self.assertEqual(await self.history.get_topic_hint("room-B"), "Thema B")
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
class TestConversationHistoryCleanup(unittest.TestCase):
|
||||
"""Tests für cleanup_orphaned_rooms (sync + async)."""
|
||||
|
||||
def setUp(self):
|
||||
self.history = ConversationHistory(max_size=10)
|
||||
|
||||
def test_cleanup_sync_removes_orphaned(self):
|
||||
"""Sync-Cleanup entfernt Räume, die nicht in active_room_ids sind."""
|
||||
async def run():
|
||||
await self.history.add("room-1", "user", "Msg")
|
||||
await self.history.add("room-2", "user", "Msg")
|
||||
await self.history.add("room-3", "user", "Msg")
|
||||
await self.history.set_topic_hint("room-1", "T1")
|
||||
await self.history.set_topic_hint("room-2", "T2")
|
||||
asyncio.run(run())
|
||||
|
||||
removed = self.history.cleanup_orphaned_rooms_sync({"room-1"})
|
||||
self.assertEqual(removed, 2) # room-2 und room-3 entfernt
|
||||
|
||||
async def check():
|
||||
msgs = await self.history.get("room-1")
|
||||
self.assertEqual(len(msgs), 1) # room-1 bleibt
|
||||
msgs2 = await self.history.get("room-2")
|
||||
self.assertEqual(len(msgs2), 0) # room-2 entfernt
|
||||
hint = await self.history.get_topic_hint("room-2")
|
||||
self.assertIsNone(hint) # topic_hint auch entfernt
|
||||
asyncio.run(check())
|
||||
|
||||
def test_cleanup_sync_no_orphans(self):
|
||||
"""Sync-Cleanup wenn alle Räume aktiv sind → 0 entfernt."""
|
||||
async def run():
|
||||
await self.history.add("room-1", "user", "Msg")
|
||||
await self.history.add("room-2", "user", "Msg")
|
||||
asyncio.run(run())
|
||||
|
||||
removed = self.history.cleanup_orphaned_rooms_sync({"room-1", "room-2"})
|
||||
self.assertEqual(removed, 0)
|
||||
|
||||
def test_cleanup_sync_empty_active_set(self):
|
||||
"""Sync-Cleanup mit leerem active_room_ids → alle entfernt."""
|
||||
async def run():
|
||||
await self.history.add("room-1", "user", "Msg")
|
||||
await self.history.add("room-2", "user", "Msg")
|
||||
asyncio.run(run())
|
||||
|
||||
removed = self.history.cleanup_orphaned_rooms_sync(set())
|
||||
self.assertEqual(removed, 2)
|
||||
|
||||
def test_cleanup_async_removes_orphaned(self):
|
||||
"""Async-Cleanup (via Lock) entfernt verwaiste Räume."""
|
||||
async def run():
|
||||
await self.history.add("room-1", "user", "Msg")
|
||||
await self.history.add("room-2", "user", "Msg")
|
||||
removed = await self.history.cleanup_orphaned_rooms({"room-1"})
|
||||
self.assertEqual(removed, 1)
|
||||
msgs = await self.history.get("room-1")
|
||||
self.assertEqual(len(msgs), 1)
|
||||
msgs2 = await self.history.get("room-2")
|
||||
self.assertEqual(len(msgs2), 0)
|
||||
asyncio.run(run())
|
||||
|
||||
def test_cleanup_async_no_orphans(self):
|
||||
"""Async-Cleanup wenn alle Räume aktiv → 0 entfernt."""
|
||||
async def run():
|
||||
await self.history.add("room-1", "user", "Msg")
|
||||
removed = await self.history.cleanup_orphaned_rooms({"room-1"})
|
||||
self.assertEqual(removed, 0)
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
class TestConversationHistoryThreadSafety(unittest.TestCase):
|
||||
"""Tests für Thread-safety (concurrent adds)."""
|
||||
|
||||
def setUp(self):
|
||||
self.history = ConversationHistory(max_size=100)
|
||||
|
||||
def test_concurrent_adds_same_room(self):
|
||||
"""Viele concurrent adds in denselben Raum — keine Korruption."""
|
||||
async def add_many(room_id, prefix, count):
|
||||
for i in range(count):
|
||||
await self.history.add(room_id, "user", f"{prefix}-{i}")
|
||||
|
||||
async def run():
|
||||
tasks = [
|
||||
add_many("room-1", "A", 50),
|
||||
add_many("room-1", "B", 50),
|
||||
add_many("room-1", "C", 50),
|
||||
]
|
||||
await asyncio.gather(*tasks)
|
||||
msgs = await self.history.get("room-1")
|
||||
# 150 adds, max_size=100 → 100 messages
|
||||
self.assertEqual(len(msgs), 100)
|
||||
asyncio.run(run())
|
||||
|
||||
def test_concurrent_adds_different_rooms(self):
|
||||
"""Concurrent adds in verschiedene Räume — keine Cross-Contamination."""
|
||||
async def add_many(room_id, count):
|
||||
for i in range(count):
|
||||
await self.history.add(room_id, "user", f"msg-{i}")
|
||||
|
||||
async def run():
|
||||
tasks = [
|
||||
add_many("room-A", 30),
|
||||
add_many("room-B", 30),
|
||||
add_many("room-C", 30),
|
||||
]
|
||||
await asyncio.gather(*tasks)
|
||||
self.assertEqual(len(await self.history.get("room-A")), 30)
|
||||
self.assertEqual(len(await self.history.get("room-B")), 30)
|
||||
self.assertEqual(len(await self.history.get("room-C")), 30)
|
||||
asyncio.run(run())
|
||||
|
||||
def test_concurrent_add_and_get(self):
|
||||
"""Gleichzeitiges add() und get() — keine Deadlocks."""
|
||||
async def adder():
|
||||
for i in range(50):
|
||||
await self.history.add("room-1", "user", f"msg-{i}")
|
||||
await asyncio.sleep(0)
|
||||
|
||||
async def reader():
|
||||
for _ in range(25):
|
||||
await self.history.get("room-1")
|
||||
await asyncio.sleep(0)
|
||||
|
||||
async def run():
|
||||
await asyncio.gather(adder(), reader())
|
||||
msgs = await self.history.get("room-1")
|
||||
self.assertEqual(len(msgs), 50)
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
class TestConversationHistoryEdgeCases(unittest.TestCase):
|
||||
"""Edge-Case-Tests."""
|
||||
|
||||
def setUp(self):
|
||||
self.history = ConversationHistory(max_size=10)
|
||||
|
||||
def test_clear_nonexistent_room(self):
|
||||
"""clear() für nicht-existierenden Raum → no-op, kein Crash."""
|
||||
async def run():
|
||||
await self.history.clear("nonexistent")
|
||||
self.assertEqual(await self.history.get_room_count(), 0)
|
||||
asyncio.run(run())
|
||||
|
||||
def test_clear_then_reuse_room(self):
|
||||
"""Nach clear() kann derselbe Raum wieder verwendet werden."""
|
||||
async def run():
|
||||
await self.history.add("room-1", "user", "Msg 1")
|
||||
await self.history.clear("room-1")
|
||||
await self.history.add("room-1", "user", "Msg 2")
|
||||
msgs = await self.history.get("room-1")
|
||||
self.assertEqual(len(msgs), 1)
|
||||
self.assertEqual(msgs[0]["text"], "Msg 2")
|
||||
asyncio.run(run())
|
||||
|
||||
def test_room_count_property(self):
|
||||
"""room_count Property (nicht thread-safe, für Debug)."""
|
||||
async def run():
|
||||
self.assertEqual(self.history.room_count, 0)
|
||||
await self.history.add("room-1", "user", "Msg")
|
||||
self.assertEqual(self.history.room_count, 1)
|
||||
await self.history.add("room-2", "user", "Msg")
|
||||
self.assertEqual(self.history.room_count, 2)
|
||||
asyncio.run(run())
|
||||
|
||||
def test_get_room_count_async(self):
|
||||
"""Thread-safe get_room_count()."""
|
||||
async def run():
|
||||
self.assertEqual(await self.history.get_room_count(), 0)
|
||||
await self.history.add("room-1", "user", "Msg")
|
||||
self.assertEqual(await self.history.get_room_count(), 1)
|
||||
asyncio.run(run())
|
||||
|
||||
def test_messageentry_to_dict(self):
|
||||
"""MessageEntry.to_dict() liefert korrekte Struktur."""
|
||||
from datetime import datetime, timezone
|
||||
ts = datetime(2026, 7, 13, 12, 0, 0, tzinfo=timezone.utc)
|
||||
entry = MessageEntry(role="user", text="Test", timestamp=ts)
|
||||
d = entry.to_dict()
|
||||
self.assertEqual(d["role"], "user")
|
||||
self.assertEqual(d["text"], "Test")
|
||||
self.assertTrue(d["timestamp"].startswith("2026-07-13"))
|
||||
|
||||
def test_messageentry_default_timestamp(self):
|
||||
"""MessageEntry ohne timestamp → jetzt UTC."""
|
||||
entry = MessageEntry(role="user", text="Test")
|
||||
self.assertIsNotNone(entry.timestamp)
|
||||
d = entry.to_dict()
|
||||
self.assertIn("timestamp", d)
|
||||
|
||||
def test_add_with_custom_timestamp(self):
|
||||
"""add() mit explizitem timestamp."""
|
||||
from datetime import datetime, timezone
|
||||
async def run():
|
||||
ts = datetime(2025, 1, 1, tzinfo=timezone.utc)
|
||||
await self.history.add("room-1", "user", "Old msg", timestamp=ts)
|
||||
msgs = await self.history.get("room-1")
|
||||
self.assertEqual(msgs[0]["timestamp"], "2025-01-01T00:00:00+00:00")
|
||||
asyncio.run(run())
|
||||
|
||||
def test_max_size_property(self):
|
||||
"""max_size Property."""
|
||||
self.assertEqual(self.history.max_size, 10)
|
||||
hist2 = ConversationHistory(max_size=3)
|
||||
self.assertEqual(hist2.max_size, 3)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user