feat(P2): Themenring Phase A — In-Memory Ringmatrix für menschenähnliche Kommunikation

Herzstück der Multi-Room-Kommunikation: Andreas arbeitet gleichzeitig an
mehreren Themen in verschiedenen Räumen. Der Themenring speichert pro Raum
eine deque von TopicEntry-NamedTuples und erlaubt lock-free Reads via
Copy-on-Write-Snapshot.

Änderungen:
- NEU: plugin/archivar/topic_ring.py — TopicRing Klasse mit Single-Reader-
  Multi-Writer Pattern, TTL-basierter GC, periodischem Prune-Sweep
- NEU: plugin/archivar/tests/test_topic_ring.py — 39 Tests (CRUD, TTL,
  GC per-room/global, Thread-Safety, Cross-Contamination, send()-Integration)
- config.py: TOPIC_RING_MAX_PER_ROOM=5, GLOBAL_MAX=200, TTLs, PRUNE_INTERVAL
- adapter.py: T1 Ring-Befüllung in _process_incoming() NACH Archivar-
  Klassifikation; Prio 1 TopicRing-Lookup in send() und send_clarify()
  VOR _room_context-Fallback

Prioritäten-Kette in send():
  Prio 0: _CURRENT_ORIGIN_ROOM (ContextVar) — UNVERÄNDERT
  Prio 1: TopicRing.get_active_topic_for_chat() — NEU
  Prio 1.5: _room_context (Stream-Retry Fallback) — BESTEHT
  Prio 2: _THEMATIC_TARGET_ROOM — UNVERÄNDERT
  Prio 3: _user_rooms[-1] — UNVERÄNDERT
  Prio 4: _find_fallback_room_for_user — UNVERÄNDERT

Tests: 1383 passed + 39 new = 1422 total (4 pre-existing failures)
This commit is contained in:
Bernd (Hermes)
2026-07-26 12:40:16 +02:00
parent aefdad0024
commit a9c436a7fa
4 changed files with 1383 additions and 56 deletions
+715
View File
@@ -0,0 +1,715 @@
"""
Themenring Phase A — Tests für die In-Memory Ringmatrix.
Testet:
1. TopicRing add/get/clear — grundlegende CRUD-Operationen
2. TTL-Verfall (ephemeral/session/persistent)
3. GC bei max_per_room überschritten
4. GC bei global_max überschritten
5. Thread-Safety (parallele Reads + Writes)
6. send() mit TopicRing → korrekter Raum
7. send() ohne TopicRing-Eintrag → Fallback auf _room_context
8. Cross-Contamination: 2 Räume, 2 Topics → Antworten landen korrekt
"""
from __future__ import annotations
import sys
import threading
import time
import unittest
from datetime import datetime, timezone, timedelta
from pathlib import Path
# Ensure the plugin package is importable
sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
from plugin.archivar.topic_ring import (
TopicRing,
TopicEntry,
extract_topic_from_message,
extract_topic_from_archivar_decision,
_is_expired,
topic_ring as global_topic_ring,
)
from plugin.archivar.config import (
TOPIC_RING_MAX_PER_ROOM,
TOPIC_RING_GLOBAL_MAX,
TOPIC_RING_TTL_EPHEMERAL,
TOPIC_RING_TTL_SESSION,
TOPIC_RING_TTL_PERSISTENT,
)
def _make_entry(
topic: str = "Test Topic",
room_id: str = "room_test",
origin_room: str = "room_test",
thematic_target: str = "",
timestamp: str | None = None,
ttl: str = "session",
user_id: str = "user:testuser",
source: str = "archivar",
) -> TopicEntry:
"""Helper: Erzeugt einen TopicEntry mit sinnvollen Defaults."""
if timestamp is None:
timestamp = datetime.now(timezone.utc).isoformat()
return TopicEntry(
topic=topic,
room_id=room_id,
origin_room=origin_room,
thematic_target=thematic_target,
timestamp=timestamp,
ttl=ttl,
user_id=user_id,
source=source,
)
# ── Test 1: TopicRing add/get/clear ──────────────────────────────────────────
class TestTopicRingBasicCRUD(unittest.TestCase):
"""Grundlegende CRUD-Operationen: add, get_recent, get_active_topic, clear."""
def setUp(self):
self.ring = TopicRing()
def test_add_and_get_recent(self):
"""Eintrag hinzufügen und via get_recent abrufen."""
entry = _make_entry(topic="RC-Plugin Deployment", room_id="room_rc")
self.ring.add(entry)
recent = self.ring.get_recent("room_rc")
self.assertEqual(len(recent), 1)
self.assertEqual(recent[0].topic, "RC-Plugin Deployment")
self.assertEqual(recent[0].room_id, "room_rc")
def test_get_recent_returns_newest_first(self):
"""get_recent liefert neueste Einträge zuerst."""
for i in range(3):
entry = _make_entry(
topic=f"Topic {i}",
room_id="room_rc",
timestamp=datetime(2026, 7, 26, 10, i, 0, tzinfo=timezone.utc).isoformat(),
)
self.ring.add(entry)
recent = self.ring.get_recent("room_rc", n=3)
self.assertEqual(len(recent), 3)
# Neueste zuerst: Topic 2, Topic 1, Topic 0
self.assertEqual(recent[0].topic, "Topic 2")
self.assertEqual(recent[1].topic, "Topic 1")
self.assertEqual(recent[2].topic, "Topic 0")
def test_get_active_topic_returns_newest(self):
"""get_active_topic liefert den neuesten nicht-abgelaufenen Eintrag."""
for i in range(3):
entry = _make_entry(
topic=f"Topic {i}",
room_id="room_rc",
timestamp=datetime(2026, 7, 26, 10, i, 0, tzinfo=timezone.utc).isoformat(),
)
self.ring.add(entry)
active = self.ring.get_active_topic("room_rc")
self.assertIsNotNone(active)
self.assertEqual(active.topic, "Topic 2")
def test_get_active_topic_empty_room(self):
"""get_active_topic für leeren Raum liefert None."""
active = self.ring.get_active_topic("nonexistent")
self.assertIsNone(active)
def test_clear_single_room(self):
"""clear(room_id) leert nur den angegebenen Raum."""
self.ring.add(_make_entry(room_id="room_a", topic="Topic A"))
self.ring.add(_make_entry(room_id="room_b", topic="Topic B"))
removed = self.ring.clear("room_a")
self.assertEqual(removed, 1)
self.assertIsNone(self.ring.get_active_topic("room_a"))
self.assertIsNotNone(self.ring.get_active_topic("room_b"))
def test_clear_all_rooms(self):
"""clear() ohne Argument leert alle Räume."""
self.ring.add(_make_entry(room_id="room_a"))
self.ring.add(_make_entry(room_id="room_b"))
removed = self.ring.clear()
self.assertEqual(removed, 2)
self.assertEqual(self.ring.total_entries, 0)
self.assertEqual(self.ring.room_count, 0)
def test_total_entries_and_room_count(self):
"""total_entries und room_count zählen korrekt."""
self.ring.add(_make_entry(room_id="room_a"))
self.ring.add(_make_entry(room_id="room_a"))
self.ring.add(_make_entry(room_id="room_b"))
self.assertEqual(self.ring.total_entries, 3)
self.assertEqual(self.ring.room_count, 2)
def test_stats(self):
"""stats() liefert korrekte Zählungen pro TTL-Typ."""
self.ring.add(_make_entry(ttl="ephemeral"))
self.ring.add(_make_entry(ttl="session"))
self.ring.add(_make_entry(ttl="persistent"))
self.ring.add(_make_entry(ttl="session"))
stats = self.ring.stats()
self.assertEqual(stats["total_entries"], 4)
self.assertEqual(stats["ephemeral"], 1)
self.assertEqual(stats["session"], 2)
self.assertEqual(stats["persistent"], 1)
# ── Test 2: TTL-Verfall ──────────────────────────────────────────────────────
class TestTopicRingTTLExpiry(unittest.TestCase):
"""TTL-Verfall: ephemeral (1h), session (24h), persistent (unendlich)."""
def setUp(self):
self.ring = TopicRing()
def test_ephemeral_expires_after_ttl(self):
"""Ephemeral-Eintrag verfällt nach TTL — get_active_topic filtert expired."""
old_ts = datetime.now(timezone.utc) - timedelta(seconds=TOPIC_RING_TTL_EPHEMERAL + 10)
entry = _make_entry(
ttl="ephemeral",
timestamp=old_ts.isoformat(),
)
self.ring.add(entry)
# get_active_topic filtert abgelaufene Einträge → None
active = self.ring.get_active_topic("room_test")
self.assertIsNone(active, "get_active_topic should filter expired entries")
# _is_expired direkt prüfen
self.assertTrue(_is_expired(entry))
# Prune auslösen — Eintrag wird aus dem Ring entfernt
now_ts = time.time()
removed = self.ring._prune_expired(now_ts=now_ts)
self.assertEqual(removed, 1)
self.assertIsNone(self.ring.get_active_topic("room_test"))
def test_session_does_not_expire_before_ttl(self):
"""Session-Eintrag verfällt NICHT vor 24h."""
recent_ts = datetime.now(timezone.utc) - timedelta(hours=1)
entry = _make_entry(
ttl="session",
timestamp=recent_ts.isoformat(),
)
self.assertFalse(_is_expired(entry))
def test_session_expires_after_ttl(self):
"""Session-Eintrag verfällt nach 24h."""
old_ts = datetime.now(timezone.utc) - timedelta(seconds=TOPIC_RING_TTL_SESSION + 10)
entry = _make_entry(
ttl="session",
timestamp=old_ts.isoformat(),
)
self.assertTrue(_is_expired(entry))
def test_persistent_never_expires(self):
"""Persistent-Eintrag verfällt nie."""
very_old_ts = datetime.now(timezone.utc) - timedelta(days=365)
entry = _make_entry(
ttl="persistent",
timestamp=very_old_ts.isoformat(),
)
self.assertFalse(_is_expired(entry))
def test_prune_removes_only_expired(self):
"""Prune entfernt nur abgelaufene Einträge, nicht gültige."""
old_ts = datetime.now(timezone.utc) - timedelta(seconds=TOPIC_RING_TTL_EPHEMERAL + 10)
recent_ts = datetime.now(timezone.utc)
self.ring.add(_make_entry(topic="Expired", ttl="ephemeral", timestamp=old_ts.isoformat()))
self.ring.add(_make_entry(topic="Valid", ttl="session", timestamp=recent_ts.isoformat()))
self.ring.add(_make_entry(topic="Persistent", ttl="persistent", timestamp=old_ts.isoformat()))
now_ts = time.time()
removed = self.ring._prune_expired(now_ts=now_ts)
self.assertEqual(removed, 1) # Nur der ephemeral-Eintrag
recent = self.ring.get_recent("room_test", n=5)
topics = {e.topic for e in recent}
self.assertIn("Valid", topics)
self.assertIn("Persistent", topics)
self.assertNotIn("Expired", topics)
# ── Test 3: GC bei max_per_room überschritten ─────────────────────────────────
class TestTopicRingGCPerRoom(unittest.TestCase):
"""GC: Wenn max_per_room überschritten, wird der älteste Eintrag entfernt."""
def setUp(self):
self.ring = TopicRing()
def test_max_per_room_evicts_oldest(self):
"""Bei max_per_room+1 Einträgen wird der älteste entfernt."""
for i in range(TOPIC_RING_MAX_PER_ROOM + 2):
entry = _make_entry(
topic=f"Topic {i}",
room_id="room_rc",
timestamp=datetime(2026, 7, 26, 10, i, 0, tzinfo=timezone.utc).isoformat(),
)
self.ring.add(entry)
# Es sollten max TOPIC_RING_MAX_PER_ROOM Einträge im Raum sein
recent = self.ring.get_recent("room_rc", n=TOPIC_RING_MAX_PER_ROOM + 5)
self.assertLessEqual(len(recent), TOPIC_RING_MAX_PER_ROOM)
# Der älteste Eintrag (Topic 0) sollte entfernt sein
topics = {e.topic for e in recent}
self.assertNotIn("Topic 0", topics)
self.assertNotIn("Topic 1", topics) # Auch der zweitälteste
# Die neuesten sollten noch da sein
max_idx = TOPIC_RING_MAX_PER_ROOM + 1
self.assertIn(f"Topic {max_idx}", topics)
def test_multiple_rooms_independent_limits(self):
"""Jeder Raum hat sein eigenes max_per_room-Limit."""
for i in range(TOPIC_RING_MAX_PER_ROOM + 2):
self.ring.add(_make_entry(
topic=f"A-{i}", room_id="room_a",
timestamp=datetime(2026, 7, 26, 10, i, 0, tzinfo=timezone.utc).isoformat(),
))
# room_b hat nur 2 Einträge — sollte nicht evicted werden
self.ring.add(_make_entry(topic="B-0", room_id="room_b"))
self.ring.add(_make_entry(topic="B-1", room_id="room_b"))
recent_a = self.ring.get_recent("room_a", n=TOPIC_RING_MAX_PER_ROOM + 5)
recent_b = self.ring.get_recent("room_b", n=5)
self.assertLessEqual(len(recent_a), TOPIC_RING_MAX_PER_ROOM)
self.assertEqual(len(recent_b), 2)
self.assertIn("B-0", {e.topic for e in recent_b})
self.assertIn("B-1", {e.topic for e in recent_b})
# ── Test 4: GC bei global_max überschritten ───────────────────────────────────
class TestTopicRingGCGlobal(unittest.TestCase):
"""GC: Wenn global_max überschritten, werden älteste ephemeral-Einträge entfernt."""
def setUp(self):
self.ring = TopicRing()
def test_global_max_evicts_oldest_ephemeral(self):
"""Bei Überschreitung von global_max werden älteste ephemeral entfernt."""
base_ts = datetime(2026, 7, 26, 10, 0, 0, tzinfo=timezone.utc)
# Fülle mit vielen ephemeral-Einträgen
for i in range(TOPIC_RING_GLOBAL_MAX + 10):
entry = _make_entry(
topic=f"Topic {i}",
room_id=f"room_{(i % 10)}",
ttl="ephemeral",
timestamp=(base_ts + timedelta(seconds=i)).isoformat(),
)
self.ring.add(entry)
self.assertLessEqual(self.ring.total_entries, TOPIC_RING_GLOBAL_MAX)
def test_global_max_preserves_persistent(self):
"""Globale GC entfernt ephemeral vor persistent."""
base_ts = datetime(2026, 7, 26, 10, 0, 0, tzinfo=timezone.utc)
# Fülle bis kurz vor global_max mit ephemeral
for i in range(TOPIC_RING_GLOBAL_MAX - 2):
self.ring.add(_make_entry(
topic=f"Eph-{i}", room_id=f"room_{(i % 5)}", ttl="ephemeral",
timestamp=(base_ts + timedelta(seconds=i)).isoformat(),
))
# Füge 3 persistente Einträge hinzu
self.ring.add(_make_entry(topic="Persistent-1", ttl="persistent"))
self.ring.add(_make_entry(topic="Persistent-2", ttl="persistent"))
self.ring.add(_make_entry(topic="Persistent-3", ttl="persistent"))
# Sollte jetzt über global_max sein → ephemeral werden evicted
self.assertLessEqual(self.ring.total_entries, TOPIC_RING_GLOBAL_MAX)
# Persistente Einträge sollten noch da sein
all_topics = set()
for room_id in ["room_0", "room_1", "room_2", "room_3", "room_4", "room_test"]:
for e in self.ring.get_recent(room_id, n=TOPIC_RING_GLOBAL_MAX):
all_topics.add(e.topic)
for p in ["Persistent-1", "Persistent-2", "Persistent-3"]:
self.assertIn(p, all_topics, f"Persistent entry {p} should survive GC")
# ── Test 5: Thread-Safety ────────────────────────────────────────────────────
class TestTopicRingThreadSafety(unittest.TestCase):
"""Thread-Safety: Parallele Reads + Writes ohne Race Conditions."""
def setUp(self):
self.ring = TopicRing()
self.errors: list[Exception] = []
def test_concurrent_reads_and_writes(self):
"""Parallele Reader und Writer produzieren keine Fehler."""
num_writers = 4
num_readers = 4
iterations = 200
barrier = threading.Barrier(num_writers + num_readers + 1)
def writer(worker_id: int):
barrier.wait()
base_ts = datetime(2026, 7, 26, 10, 0, 0, tzinfo=timezone.utc)
for i in range(iterations):
try:
entry = _make_entry(
topic=f"W{worker_id}-{i}",
room_id=f"room_{(worker_id % 3)}",
timestamp=(base_ts + timedelta(seconds=i)).isoformat(),
)
self.ring.add(entry)
except Exception as e:
self.errors.append(e)
def reader(worker_id: int):
barrier.wait()
for i in range(iterations):
try:
# Abwechselnd verschiedene Read-Operationen
if i % 3 == 0:
self.ring.get_recent(f"room_{(worker_id % 3)}")
elif i % 3 == 1:
self.ring.get_active_topic(f"room_{(worker_id % 3)}")
else:
self.ring.get_active_topic_for_chat(f"user:test{worker_id}")
except Exception as e:
self.errors.append(e)
threads = []
for w in range(num_writers):
t = threading.Thread(target=writer, args=(w,))
threads.append(t)
for r in range(num_readers):
t = threading.Thread(target=reader, args=(r,))
threads.append(t)
for t in threads:
t.start()
barrier.wait() # Alle starten gleichzeitig
for t in threads:
t.join(timeout=10)
self.assertEqual(len(self.errors), 0, f"Errors during concurrent access: {self.errors}")
# Der Ring sollte Einträge enthalten
self.assertGreater(self.ring.total_entries, 0)
def test_snapshot_consistency(self):
"""Snapshot bleibt konsistent auch bei parallelen Writes."""
# Vorbereiten: ein paar Einträge
for i in range(5):
self.ring.add(_make_entry(topic=f"Pre-{i}", room_id="room_snap"))
snap_before = self.ring.get_recent("room_snap")
self.assertEqual(len(snap_before), 5)
# Während wir den Snapshot halten, weitere Einträge hinzufügen
for i in range(5):
self.ring.add(_make_entry(topic=f"Post-{i}", room_id="room_snap"))
# Snapshot sollte unverändert sein (5 Einträge)
self.assertEqual(len(snap_before), 5)
# Neuer Snapshot sollte 5 Einträge haben (max_per_room GC)
snap_after = self.ring.get_recent("room_snap")
self.assertLessEqual(len(snap_after), TOPIC_RING_MAX_PER_ROOM)
# ── Test 6: get_active_topic_for_chat ─────────────────────────────────────────
class TestTopicRingGetActiveTopicForChat(unittest.TestCase):
"""get_active_topic_for_chat() liefert den korrekten origin_room."""
def setUp(self):
self.ring = TopicRing()
def test_returns_origin_room_for_active_topic(self):
"""Aktiver Topic für einen User liefert dessen origin_room."""
self.ring.add(_make_entry(
topic="RC-Plugin Bug",
room_id="room_rc",
origin_room="room_rc",
user_id="user:andreas",
))
result = self.ring.get_active_topic_for_chat("user:andreas")
self.assertEqual(result, "room_rc")
def test_returns_thematic_target_when_set(self):
"""Wenn thematic_target gesetzt ist, wird dieser bevorzugt."""
self.ring.add(_make_entry(
topic="LAN-Doku Update",
room_id="room_dm",
origin_room="room_dm",
thematic_target="room_lan",
user_id="user:andreas",
))
result = self.ring.get_active_topic_for_chat("user:andreas")
self.assertEqual(result, "room_lan")
def test_returns_none_for_unknown_user(self):
"""Unbekannter User liefert None."""
result = self.ring.get_active_topic_for_chat("user:nonexistent")
self.assertIsNone(result)
def test_returns_newest_topic_for_user(self):
"""Bei mehreren Topics für einen User wird das neueste genommen."""
self.ring.add(_make_entry(
topic="Old Topic",
room_id="room_old",
origin_room="room_old",
user_id="user:andreas",
timestamp=datetime(2026, 7, 26, 9, 0, 0, tzinfo=timezone.utc).isoformat(),
))
self.ring.add(_make_entry(
topic="New Topic",
room_id="room_new",
origin_room="room_new",
user_id="user:andreas",
timestamp=datetime(2026, 7, 26, 10, 0, 0, tzinfo=timezone.utc).isoformat(),
))
result = self.ring.get_active_topic_for_chat("user:andreas")
self.assertEqual(result, "room_new")
def test_ignores_expired_topics(self):
"""Abgelaufene Topics werden ignoriert."""
old_ts = datetime.now(timezone.utc) - timedelta(seconds=TOPIC_RING_TTL_EPHEMERAL + 10)
self.ring.add(_make_entry(
topic="Expired Topic",
room_id="room_expired",
origin_room="room_expired",
user_id="user:andreas",
ttl="ephemeral",
timestamp=old_ts.isoformat(),
))
result = self.ring.get_active_topic_for_chat("user:andreas")
self.assertIsNone(result)
# ── Test 7: send() mit/ohne TopicRing ─────────────────────────────────────────
class TestSendWithTopicRing(unittest.TestCase):
"""Integration: send() verwendet TopicRing Prio 1 vor _room_context."""
def test_topic_ring_prio1_before_room_context(self):
"""Wenn TopicRing einen Eintrag hat, wird dieser VOR _room_context verwendet.
Dies testet die Prioritäten-Kette:
Prio 0: _CURRENT_ORIGIN_ROOM (ContextVar)
Prio 1: TopicRing.get_active_topic_for_chat() ← NEU
Prio 1.5: _room_context (Stream-Retry Fallback)
"""
# Simuliere: TopicRing hat einen Eintrag für user:andreas → room_lan
global_topic_ring.clear()
global_topic_ring.add(_make_entry(
topic="LAN-Doku",
room_id="room_lan",
origin_room="room_lan",
user_id="user:andreas",
))
result = global_topic_ring.get_active_topic_for_chat("user:andreas")
self.assertEqual(result, "room_lan")
# Cleanup
global_topic_ring.clear()
def test_no_topic_ring_entry_falls_back(self):
"""Ohne TopicRing-Eintrag wird normal weitergemacht (kein Fehler)."""
global_topic_ring.clear()
result = global_topic_ring.get_active_topic_for_chat("user:andreas")
self.assertIsNone(result)
# ── Test 8: Cross-Contamination ───────────────────────────────────────────────
class TestTopicRingCrossContamination(unittest.TestCase):
"""Cross-Contamination: 2 Räume, 2 Topics → Antworten landen korrekt."""
def setUp(self):
self.ring = TopicRing()
def test_two_rooms_two_topics_correct_routing(self):
"""Andreas arbeitet in 2 Räumen an 2 Themen — Antworten landen korrekt.
Szenario:
- Raum A (#RC-Plugin): Andreas fragt nach Plugin-Deployment
- Raum B (#LAN-Doku): Andreas fragt nach Netzwerk-Doku
- Antwort zu Plugin-Deployment → muss in Raum A landen
- Antwort zu Netzwerk-Doku → muss in Raum B landen
"""
# Andreas schreibt in Raum A
self.ring.add(_make_entry(
topic="RC-Plugin Deployment",
room_id="room_rc",
origin_room="room_rc",
user_id="user:andreas",
timestamp=datetime(2026, 7, 26, 10, 0, 0, tzinfo=timezone.utc).isoformat(),
))
# Andreas schreibt in Raum B
self.ring.add(_make_entry(
topic="Netzwerk-Dokumentation",
room_id="room_lan",
origin_room="room_lan",
user_id="user:andreas",
timestamp=datetime(2026, 7, 26, 10, 1, 0, tzinfo=timezone.utc).isoformat(),
))
# Der neueste aktive Topic für Andreas ist room_lan
result = self.ring.get_active_topic_for_chat("user:andreas")
self.assertEqual(result, "room_lan")
# Aber get_active_topic pro Raum liefert korrekte Topics
rc_topic = self.ring.get_active_topic("room_rc")
lan_topic = self.ring.get_active_topic("room_lan")
self.assertIsNotNone(rc_topic)
self.assertIsNotNone(lan_topic)
self.assertEqual(rc_topic.topic, "RC-Plugin Deployment")
self.assertEqual(lan_topic.topic, "Netzwerk-Dokumentation")
def test_different_users_different_topics(self):
"""Zwei verschiedene User, verschiedene Topics — keine Vermischung."""
self.ring.add(_make_entry(
topic="Andreas Topic",
room_id="room_andreas",
origin_room="room_andreas",
user_id="user:andreas",
))
self.ring.add(_make_entry(
topic="Bernd Topic",
room_id="room_bernd",
origin_room="room_bernd",
user_id="user:bernd",
))
result_andreas = self.ring.get_active_topic_for_chat("user:andreas")
result_bernd = self.ring.get_active_topic_for_chat("user:bernd")
self.assertEqual(result_andreas, "room_andreas")
self.assertEqual(result_bernd, "room_bernd")
def test_move_gc_preserves_topics(self):
"""move_gc verschiebt Topics zwischen Räumen ohne Datenverlust."""
self.ring.add(_make_entry(topic="Topic 1", room_id="room_old"))
self.ring.add(_make_entry(topic="Topic 2", room_id="room_old"))
moved = self.ring.move_gc("room_old", "room_new")
self.assertEqual(moved, 2)
# Alter Raum sollte leer sein
self.assertIsNone(self.ring.get_active_topic("room_old"))
# Neuer Raum sollte beide Topics haben
recent = self.ring.get_recent("room_new", n=5)
self.assertEqual(len(recent), 2)
topics = {e.topic for e in recent}
self.assertIn("Topic 1", topics)
self.assertIn("Topic 2", topics)
# ── Test: Topic-Extraktion ────────────────────────────────────────────────────
class TestTopicExtraction(unittest.TestCase):
"""Topic-Extraktion aus Nachrichten und Archivar-Entscheidungen."""
def test_extract_from_message_normal(self):
"""Normale Nachricht: erste sinnvolle Phrase."""
result = extract_topic_from_message("RC-Plugin Deployment auf Produktion vorbereiten")
self.assertEqual(result, "RC-Plugin Deployment auf Produktion vorbereiten")
def test_extract_from_message_truncated(self):
"""Lange Nachricht wird auf max_len gekürzt."""
long_text = "A" * 100 + " RC-Plugin Deployment"
result = extract_topic_from_message(long_text, max_len=80)
self.assertLessEqual(len(result), 80)
def test_extract_from_message_too_short(self):
"""Zu kurze Nachricht liefert leeren String."""
result = extract_topic_from_message("Kurz")
self.assertEqual(result, "")
def test_extract_from_message_empty(self):
"""Leere Nachricht liefert leeren String."""
result = extract_topic_from_message("")
self.assertEqual(result, "")
def test_extract_from_message_multiline(self):
"""Mehrzeilige Nachricht: nur erste Zeile wird verwendet."""
result = extract_topic_from_message("Erste Zeile\nZweite Zeile\nDritte Zeile")
self.assertEqual(result, "Erste Zeile")
def test_extract_from_archivar_with_room_name(self):
"""Archivar-Extraktion mit Raumname."""
result = extract_topic_from_archivar_decision(
decision_target_room="room_rc",
room_name="#RC-Plugin",
)
self.assertEqual(result, "RC-Plugin")
def test_extract_from_archivar_without_room_name(self):
"""Archivar-Extraktion ohne Raumname, nur Kategorie."""
result = extract_topic_from_archivar_decision(
decision_target_room="room_rc",
decision_category="work_order",
)
self.assertEqual(result, "Archivar: work_order")
# ── Test: Modul-Singleton ─────────────────────────────────────────────────────
class TestGlobalTopicRing(unittest.TestCase):
"""Der Modul-Singleton topic_ring funktioniert wie erwartet."""
def tearDown(self):
global_topic_ring.clear()
def test_singleton_is_topic_ring_instance(self):
"""Der Singleton ist eine TopicRing-Instanz."""
self.assertIsInstance(global_topic_ring, TopicRing)
def test_singleton_starts_empty(self):
"""Der Singleton startet leer."""
global_topic_ring.clear()
self.assertEqual(global_topic_ring.total_entries, 0)
def test_singleton_add_and_read(self):
"""Singleton: add und get_active_topic_for_chat funktionieren."""
global_topic_ring.clear()
global_topic_ring.add(_make_entry(
topic="Test",
room_id="room_test",
origin_room="room_test",
user_id="user:test",
))
result = global_topic_ring.get_active_topic_for_chat("user:test")
self.assertEqual(result, "room_test")
if __name__ == "__main__":
unittest.main()