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:
@@ -34,6 +34,11 @@ class RocketChatRateLimitError(Exception):
|
|||||||
"""HTTP 429 Too Many Requests from Rocket.Chat REST API."""
|
"""HTTP 429 Too Many Requests from Rocket.Chat REST API."""
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
# ── Themenring Phase A: In-Memory Ringmatrix ──────────────────────────────
|
||||||
|
# Import des Modul-Singletons — wird in _process_incoming() befüllt und
|
||||||
|
# in send() als Prio 1 gelesen.
|
||||||
|
from archivar.topic_ring import topic_ring, TopicEntry, extract_topic_from_message
|
||||||
|
|
||||||
# ── Room context (global dict statt ContextVar — ContextVars sind asyncio-task-lokal,
|
# ── Room context (global dict statt ContextVar — ContextVars sind asyncio-task-lokal,
|
||||||
# aber der Agent läuft in einem separaten Task und sieht sie nicht) ──
|
# aber der Agent läuft in einem separaten Task und sieht sie nicht) ──
|
||||||
# P1: Cross-Contamination-Fix — Task-Token + TTL-Sweep
|
# P1: Cross-Contamination-Fix — Task-Token + TTL-Sweep
|
||||||
@@ -3159,6 +3164,46 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
logger.info("ROUTING BYPASS: reason=exception_fallback, origin_room=%s", room_id)
|
logger.info("ROUTING BYPASS: reason=exception_fallback, origin_room=%s", room_id)
|
||||||
logger.debug("[rocketchat] Archivar classification skipped: %s", e)
|
logger.debug("[rocketchat] Archivar classification skipped: %s", e)
|
||||||
|
|
||||||
|
# ── Themenring Phase A: T1 — Ring-Befüllung NACH Archivar-Klassifikation ──
|
||||||
|
# Filter: nur wenn nicht smalltalk und topic > 8 Zeichen.
|
||||||
|
# Topic wird aus Archivar-Klassifikation extrahiert (Andreas F-A).
|
||||||
|
if decision and decision.category and decision.category != "smalltalk":
|
||||||
|
import datetime as _dt # lokaler Import — verhindert UnboundLocalError
|
||||||
|
# Topic aus Archivar-Entscheidung extrahieren
|
||||||
|
target_name = getattr(decision, 'move_request_target_name', '')
|
||||||
|
target_room = getattr(decision, 'target_room', '')
|
||||||
|
archivar_topic = ""
|
||||||
|
if target_name:
|
||||||
|
archivar_topic = target_name.lstrip('#')
|
||||||
|
elif target_room:
|
||||||
|
archivar_topic = f"Archivar: {decision.category}"
|
||||||
|
# Fallback: Topic aus Nachrichtentext extrahieren
|
||||||
|
if not archivar_topic or len(archivar_topic) <= 8:
|
||||||
|
archivar_topic = extract_topic_from_message(routing_text)
|
||||||
|
# TTL: persistent bei hoher Konfidenz (butler/stay/alarm), sonst session
|
||||||
|
ttl = "session"
|
||||||
|
if decision.confidence >= 0.9:
|
||||||
|
ttl = "persistent"
|
||||||
|
elif decision.category == "ambiguous":
|
||||||
|
ttl = "ephemeral"
|
||||||
|
if archivar_topic and len(archivar_topic) > 8:
|
||||||
|
entry = TopicEntry(
|
||||||
|
topic=archivar_topic,
|
||||||
|
room_id=room_id,
|
||||||
|
origin_room=room_id,
|
||||||
|
thematic_target=target_room if target_room and target_room != room_id else "",
|
||||||
|
timestamp=_dt.datetime.now(_dt.timezone.utc).isoformat(),
|
||||||
|
ttl=ttl,
|
||||||
|
user_id=f"user:{username}",
|
||||||
|
source="archivar",
|
||||||
|
)
|
||||||
|
topic_ring.add(entry)
|
||||||
|
logger.debug(
|
||||||
|
"[rocketchat] Themenring T1: Added topic='%s' room=%s ttl=%s",
|
||||||
|
archivar_topic[:40], room_id[:8], ttl,
|
||||||
|
)
|
||||||
|
# ── Ende Themenring T1 ──────────────────────────────────────────────
|
||||||
|
|
||||||
# ── User-Flow C: Nachricht kopieren, Antwort IMMER hier ────────
|
# ── User-Flow C: Nachricht kopieren, Antwort IMMER hier ────────
|
||||||
# V7-1: Wenn move_request_sent=True, KEIN Agent-Dispatch.
|
# V7-1: Wenn move_request_sent=True, KEIN Agent-Dispatch.
|
||||||
# Der Agent wird erst nach Button-Bestätigung (✅Ja) dispatched,
|
# Der Agent wird erst nach Button-Bestätigung (✅Ja) dispatched,
|
||||||
@@ -6491,6 +6536,23 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
if origin:
|
if origin:
|
||||||
real_room_id = origin
|
real_room_id = origin
|
||||||
logger.debug("[rocketchat] send via ContextVar: %s → %s", chat_id, real_room_id)
|
logger.debug("[rocketchat] send via ContextVar: %s → %s", chat_id, real_room_id)
|
||||||
|
else:
|
||||||
|
# ── Themenring Phase A: Prio 1 — Aktives Thema für diesen Chat ──
|
||||||
|
# Der Themenring speichert, in welchem Raum ein Thema aktiv ist.
|
||||||
|
# Wenn der Agent zu einem Thema antwortet, das im Ring registriert
|
||||||
|
# ist, wird die Antwort in den registrierten Raum gesendet.
|
||||||
|
# Dies ist das Herzstück der menschenähnlichen Kommunikation:
|
||||||
|
# Andreas arbeitet gleichzeitig an mehreren Themen in verschiedenen
|
||||||
|
# Räumen — der Themenring stellt sicher, dass Antworten im richtigen
|
||||||
|
# Raum landen.
|
||||||
|
topic_ring_origin = topic_ring.get_active_topic_for_chat(chat_id)
|
||||||
|
if topic_ring_origin:
|
||||||
|
real_room_id = topic_ring_origin
|
||||||
|
routing_counter.increment('topic_ring_prio1')
|
||||||
|
logger.info(
|
||||||
|
"[rocketchat] send via TopicRing Prio 1: %s → %s (active topic)",
|
||||||
|
chat_id, real_room_id[:8],
|
||||||
|
)
|
||||||
else:
|
else:
|
||||||
# P1: _room_context als persistenter Fallback (Stream-Retry ContextVar-Reset)
|
# P1: _room_context als persistenter Fallback (Stream-Retry ContextVar-Reset)
|
||||||
# ContextVars sind asyncio-task-lokal — bei Stream-Retries in neuem Task
|
# ContextVars sind asyncio-task-lokal — bei Stream-Retries in neuem Task
|
||||||
@@ -6864,6 +6926,16 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
if origin:
|
if origin:
|
||||||
real_room_id = origin
|
real_room_id = origin
|
||||||
logger.debug("[rocketchat] send_clarify via ContextVar: %s → %s", chat_id, real_room_id)
|
logger.debug("[rocketchat] send_clarify via ContextVar: %s → %s", chat_id, real_room_id)
|
||||||
|
else:
|
||||||
|
# ── Themenring Phase A: Prio 1 — Aktives Thema für diesen Chat ──
|
||||||
|
topic_ring_origin = topic_ring.get_active_topic_for_chat(chat_id)
|
||||||
|
if topic_ring_origin:
|
||||||
|
real_room_id = topic_ring_origin
|
||||||
|
routing_counter.increment('topic_ring_prio1')
|
||||||
|
logger.info(
|
||||||
|
"[rocketchat] send_clarify via TopicRing Prio 1: %s → %s (active topic)",
|
||||||
|
chat_id, real_room_id[:8],
|
||||||
|
)
|
||||||
else:
|
else:
|
||||||
# P1: _room_context als persistenter Fallback (Stream-Retry ContextVar-Reset)
|
# P1: _room_context als persistenter Fallback (Stream-Retry ContextVar-Reset)
|
||||||
# P1 Cross-Contamination-Fix: _get_room_context_origin validiert
|
# P1 Cross-Contamination-Fix: _get_room_context_origin validiert
|
||||||
|
|||||||
@@ -333,6 +333,30 @@ RED_FLAG_TIMEOUT: float = float(os.getenv(
|
|||||||
))
|
))
|
||||||
"""Timeout für Red-Flag-Agent-Entscheidung in Sekunden. Default: 30.0."""
|
"""Timeout für Red-Flag-Agent-Entscheidung in Sekunden. Default: 30.0."""
|
||||||
|
|
||||||
|
# ── Themenring Phase A: In-Memory Ringmatrix ────────────────────────────────
|
||||||
|
# Herzstück der menschenähnlichen 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.
|
||||||
|
|
||||||
|
TOPIC_RING_MAX_PER_ROOM: int = 5
|
||||||
|
"""Maximale Anzahl von Topic-Einträgen pro Raum im Ring."""
|
||||||
|
|
||||||
|
TOPIC_RING_GLOBAL_MAX: int = 200
|
||||||
|
"""Globale Obergrenze für alle Topic-Einträge über alle Räume hinweg."""
|
||||||
|
|
||||||
|
TOPIC_RING_TTL_EPHEMERAL: float = 3600.0
|
||||||
|
"""TTL für 'ephemeral'-Einträge in Sekunden (1 Stunde)."""
|
||||||
|
|
||||||
|
TOPIC_RING_TTL_SESSION: float = 86400.0
|
||||||
|
"""TTL für 'session'-Einträge in Sekunden (24 Stunden)."""
|
||||||
|
|
||||||
|
TOPIC_RING_TTL_PERSISTENT: float = float('inf')
|
||||||
|
"""TTL für 'persistent'-Einträge (unendlich — kein automatischer Verfall)."""
|
||||||
|
|
||||||
|
TOPIC_RING_PRUNE_INTERVAL: float = 300.0
|
||||||
|
"""Intervall für den periodischen TTL-Sweep in Sekunden (5 Minuten)."""
|
||||||
|
|
||||||
# ── 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.
|
||||||
|
|||||||
@@ -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()
|
||||||
@@ -0,0 +1,516 @@
|
|||||||
|
"""
|
||||||
|
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.
|
||||||
|
|
||||||
|
Architektur:
|
||||||
|
- Single-Reader-Multi-Writer Pattern: _lock schützt Schreibzugriffe,
|
||||||
|
_read_snapshot erlaubt lock-free Reads via copy-on-write.
|
||||||
|
- GC-Strategie: Beim Insert werden max_per_room und global_max geprüft,
|
||||||
|
älteste ephemeral-Einträge werden zuerst entfernt.
|
||||||
|
- Periodischer TTL-Sweep: Alle 5 Minuten werden abgelaufene Einträge entfernt.
|
||||||
|
|
||||||
|
Integration:
|
||||||
|
- _process_incoming() füllt den Ring NACH Archivar-Klassifikation (T1).
|
||||||
|
- send() liest den Ring (Prio 1) VOR _room_context-Fallback.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import copy
|
||||||
|
import logging
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
from collections import deque
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from typing import Dict, List, NamedTuple, Optional
|
||||||
|
|
||||||
|
from .config import (
|
||||||
|
TOPIC_RING_GLOBAL_MAX,
|
||||||
|
TOPIC_RING_MAX_PER_ROOM,
|
||||||
|
TOPIC_RING_PRUNE_INTERVAL,
|
||||||
|
TOPIC_RING_TTL_EPHEMERAL,
|
||||||
|
TOPIC_RING_TTL_PERSISTENT,
|
||||||
|
TOPIC_RING_TTL_SESSION,
|
||||||
|
)
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
# ── TopicEntry NamedTuple ────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
class TopicEntry(NamedTuple):
|
||||||
|
"""Ein einzelner Eintrag im Themenring.
|
||||||
|
|
||||||
|
Attributes:
|
||||||
|
topic: Das extrahierte Thema (z.B. "RC-Plugin Deployment", "LAN-Doku Update").
|
||||||
|
room_id: Die Rocket.Chat Raum-ID, in der das Thema aktiv ist.
|
||||||
|
origin_room: Der Ursprungsraum, aus dem die Nachricht kam.
|
||||||
|
thematic_target: Der thematische Zielraum (aus Archivar-Klassifikation).
|
||||||
|
timestamp: ISO-8601-Zeitstempel der Erstellung.
|
||||||
|
ttl: 'ephemeral' (1h), 'session' (24h) oder 'persistent' (unendlich).
|
||||||
|
user_id: Der Benutzer, der die Nachricht gesendet hat (z.B. "user:andreas").
|
||||||
|
source: 'archivar' (aus Klassifikation), 'message' (aus Nachrichtentext),
|
||||||
|
oder 'manual' (manuell gesetzt).
|
||||||
|
"""
|
||||||
|
topic: str
|
||||||
|
room_id: str
|
||||||
|
origin_room: str
|
||||||
|
thematic_target: str
|
||||||
|
timestamp: str
|
||||||
|
ttl: str # 'ephemeral' | 'session' | 'persistent'
|
||||||
|
user_id: str
|
||||||
|
source: str # 'archivar' | 'message' | 'manual'
|
||||||
|
|
||||||
|
|
||||||
|
# ── TTL-Mapping ───────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
_TTL_SECONDS: Dict[str, float] = {
|
||||||
|
"ephemeral": TOPIC_RING_TTL_EPHEMERAL,
|
||||||
|
"session": TOPIC_RING_TTL_SESSION,
|
||||||
|
"persistent": TOPIC_RING_TTL_PERSISTENT,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _is_expired(entry: TopicEntry, now_ts: Optional[float] = None) -> bool:
|
||||||
|
"""Prüft, ob ein TopicEntry TTL-abgelaufen ist.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
entry: Der zu prüfende Eintrag.
|
||||||
|
now_ts: Aktueller Unix-Timestamp (für Testbarkeit).
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
True wenn der Eintrag abgelaufen ist.
|
||||||
|
"""
|
||||||
|
ttl_seconds = _TTL_SECONDS.get(entry.ttl, TOPIC_RING_TTL_EPHEMERAL)
|
||||||
|
if ttl_seconds == float("inf"):
|
||||||
|
return False
|
||||||
|
if now_ts is None:
|
||||||
|
now_ts = time.time()
|
||||||
|
try:
|
||||||
|
created = datetime.fromisoformat(entry.timestamp)
|
||||||
|
created_ts = created.timestamp()
|
||||||
|
except (ValueError, TypeError):
|
||||||
|
return True # unparseable timestamp → als expired behandeln
|
||||||
|
return (now_ts - created_ts) > ttl_seconds
|
||||||
|
|
||||||
|
|
||||||
|
# ── Topic-Extraktion ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
def extract_topic_from_message(text: str, max_len: int = 80, min_len: int = 8) -> str:
|
||||||
|
"""Extrahiert ein Topic aus einem Nachrichtentext.
|
||||||
|
|
||||||
|
Für nicht-Archivar-Nachrichten: erste sinnvolle Phrase aus dem Text.
|
||||||
|
Filtert Zeilenumbrüche, überflüssige Whitespaces und kürzt auf max_len.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
text: Der Nachrichtentext.
|
||||||
|
max_len: Maximale Länge des extrahierten Topics.
|
||||||
|
min_len: Minimale Länge — kürzere Texte werden verworfen.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Extrahiertes Topic oder leerer String wenn zu kurz.
|
||||||
|
"""
|
||||||
|
if not text:
|
||||||
|
return ""
|
||||||
|
# Erste Zeile, Zeilenumbrüche ersetzen
|
||||||
|
first_line = text.split("\n")[0].strip()
|
||||||
|
# Auf max_len kürzen, aber an Wortgrenze
|
||||||
|
if len(first_line) > max_len:
|
||||||
|
# An letztem Leerzeichen vor max_len abschneiden
|
||||||
|
truncated = first_line[:max_len]
|
||||||
|
last_space = truncated.rfind(" ")
|
||||||
|
if last_space > min_len:
|
||||||
|
first_line = truncated[:last_space]
|
||||||
|
else:
|
||||||
|
first_line = truncated
|
||||||
|
# Mindestlänge prüfen
|
||||||
|
if len(first_line) < min_len:
|
||||||
|
return ""
|
||||||
|
return first_line
|
||||||
|
|
||||||
|
|
||||||
|
def extract_topic_from_archivar_decision(
|
||||||
|
decision_target_room: str,
|
||||||
|
decision_category: str = "",
|
||||||
|
room_name: str = "",
|
||||||
|
) -> str:
|
||||||
|
"""Extrahiert ein Topic aus einer Archivar-Routing-Entscheidung.
|
||||||
|
|
||||||
|
Bei Archivar decision=butler/stay/alarm → topic = target room name
|
||||||
|
oder klassifizierter Intent.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
decision_target_room: Zielraum-ID aus der RoutingDecision.
|
||||||
|
decision_category: Kategorie (direct_question, work_order, etc.).
|
||||||
|
room_name: Anzeigename des Zielraums.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Extrahiertes Topic oder leerer String.
|
||||||
|
"""
|
||||||
|
if room_name:
|
||||||
|
return room_name.lstrip("#")
|
||||||
|
if decision_category:
|
||||||
|
return f"Archivar: {decision_category}"
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
# ── TopicRing Klasse ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
class TopicRing:
|
||||||
|
"""In-Memory Ringmatrix für Multi-Topic-Kommunikation.
|
||||||
|
|
||||||
|
Single-Reader-Multi-Writer Pattern:
|
||||||
|
- _lock schützt _rings + _dirty bei Schreibzugriffen.
|
||||||
|
- _read_snapshot erlaubt lock-free Reads via copy-on-write.
|
||||||
|
- Beim Write: with _lock: mutate, _dirty=True, _read_snapshot=None.
|
||||||
|
- Beim Read: snap=_read_snapshot; if None: with _lock: deepcopy, set snapshot.
|
||||||
|
|
||||||
|
Usage::
|
||||||
|
|
||||||
|
ring = TopicRing()
|
||||||
|
ring.add(entry)
|
||||||
|
active = ring.get_active_topic_for_chat("user:andreas")
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self._rings: Dict[str, deque[TopicEntry]] = {}
|
||||||
|
self._lock = threading.Lock()
|
||||||
|
self._read_snapshot: Optional[Dict[str, deque[TopicEntry]]] = None
|
||||||
|
self._dirty: bool = False
|
||||||
|
self._last_prune: float = time.time()
|
||||||
|
self._total_entries: int = 0
|
||||||
|
|
||||||
|
# ── Snapshot-Helfer ──────────────────────────────────────────────────
|
||||||
|
|
||||||
|
def _get_snapshot(self) -> Dict[str, deque[TopicEntry]]:
|
||||||
|
"""Liefert einen lock-free lesbaren Snapshot der Ring-Daten.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Deep-Copy der _rings-Datenstruktur.
|
||||||
|
"""
|
||||||
|
snap = self._read_snapshot
|
||||||
|
if snap is not None:
|
||||||
|
return snap
|
||||||
|
with self._lock:
|
||||||
|
snap = copy.deepcopy(self._rings)
|
||||||
|
self._read_snapshot = snap
|
||||||
|
self._dirty = False
|
||||||
|
return snap
|
||||||
|
|
||||||
|
def _invalidate_snapshot(self) -> None:
|
||||||
|
"""Invalidiert den Read-Snapshot nach einem Schreibzugriff."""
|
||||||
|
self._read_snapshot = None
|
||||||
|
self._dirty = True
|
||||||
|
|
||||||
|
# ── GC / Pruning ─────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
def _prune_expired(self, now_ts: Optional[float] = None) -> int:
|
||||||
|
"""Entfernt alle TTL-abgelaufenen Einträge aus allen Räumen.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
now_ts: Aktueller Unix-Timestamp (für Testbarkeit).
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Anzahl der entfernten Einträge.
|
||||||
|
"""
|
||||||
|
if now_ts is None:
|
||||||
|
now_ts = time.time()
|
||||||
|
removed = 0
|
||||||
|
with self._lock:
|
||||||
|
for room_id in list(self._rings.keys()):
|
||||||
|
dq = self._rings[room_id]
|
||||||
|
new_dq = deque(
|
||||||
|
entry for entry in dq if not _is_expired(entry, now_ts)
|
||||||
|
)
|
||||||
|
removed += len(dq) - len(new_dq)
|
||||||
|
if new_dq:
|
||||||
|
self._rings[room_id] = new_dq
|
||||||
|
else:
|
||||||
|
del self._rings[room_id]
|
||||||
|
self._total_entries -= removed
|
||||||
|
self._invalidate_snapshot()
|
||||||
|
if removed:
|
||||||
|
logger.debug(
|
||||||
|
"TopicRing: Pruned %d expired entries, %d remaining",
|
||||||
|
removed, self._total_entries,
|
||||||
|
)
|
||||||
|
return removed
|
||||||
|
|
||||||
|
def _gc_global(self) -> int:
|
||||||
|
"""Entfernt älteste ephemeral-Einträge wenn global_max überschritten.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Anzahl der entfernten Einträge.
|
||||||
|
"""
|
||||||
|
removed = 0
|
||||||
|
while self._total_entries > TOPIC_RING_GLOBAL_MAX:
|
||||||
|
# Finde den ältesten ephemeral-Eintrag über alle Räume
|
||||||
|
oldest_ephemeral: Optional[tuple[str, TopicEntry]] = None
|
||||||
|
oldest_ts = float("inf")
|
||||||
|
for room_id, dq in list(self._rings.items()):
|
||||||
|
for entry in dq:
|
||||||
|
if entry.ttl == "ephemeral":
|
||||||
|
try:
|
||||||
|
ts = datetime.fromisoformat(entry.timestamp).timestamp()
|
||||||
|
except (ValueError, TypeError):
|
||||||
|
ts = 0
|
||||||
|
if ts < oldest_ts:
|
||||||
|
oldest_ts = ts
|
||||||
|
oldest_ephemeral = (room_id, entry)
|
||||||
|
if oldest_ephemeral is None:
|
||||||
|
# Keine ephemeral-Einträge mehr → ältesten session-Eintrag nehmen
|
||||||
|
for room_id, dq in list(self._rings.items()):
|
||||||
|
for entry in dq:
|
||||||
|
if entry.ttl == "session":
|
||||||
|
try:
|
||||||
|
ts = datetime.fromisoformat(entry.timestamp).timestamp()
|
||||||
|
except (ValueError, TypeError):
|
||||||
|
ts = 0
|
||||||
|
if ts < oldest_ts:
|
||||||
|
oldest_ts = ts
|
||||||
|
oldest_ephemeral = (room_id, entry)
|
||||||
|
if oldest_ephemeral is None:
|
||||||
|
break # Nichts mehr zu entfernen
|
||||||
|
room_id, entry = oldest_ephemeral
|
||||||
|
dq = self._rings[room_id]
|
||||||
|
try:
|
||||||
|
dq.remove(entry)
|
||||||
|
except ValueError:
|
||||||
|
pass # Race: bereits entfernt
|
||||||
|
if not dq:
|
||||||
|
del self._rings[room_id]
|
||||||
|
self._total_entries -= 1
|
||||||
|
removed += 1
|
||||||
|
return removed
|
||||||
|
|
||||||
|
def _gc_room(self, room_id: str) -> int:
|
||||||
|
"""Entfernt ältesten Eintrag eines Raums wenn max_per_room überschritten.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
room_id: Die Raum-ID.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Anzahl der entfernten Einträge (0 oder 1).
|
||||||
|
"""
|
||||||
|
dq = self._rings.get(room_id)
|
||||||
|
if dq is None or len(dq) <= TOPIC_RING_MAX_PER_ROOM:
|
||||||
|
return 0
|
||||||
|
# Ältesten Eintrag entfernen (links = älteste)
|
||||||
|
dq.popleft()
|
||||||
|
self._total_entries -= 1
|
||||||
|
if not dq:
|
||||||
|
del self._rings[room_id]
|
||||||
|
return 1
|
||||||
|
|
||||||
|
def _maybe_prune(self) -> None:
|
||||||
|
"""Periodischer TTL-Sweep (alle PRUNE_INTERVAL Sekunden)."""
|
||||||
|
now = time.time()
|
||||||
|
if now - self._last_prune >= TOPIC_RING_PRUNE_INTERVAL:
|
||||||
|
self._prune_expired(now_ts=now)
|
||||||
|
self._last_prune = now
|
||||||
|
|
||||||
|
# ── Public API ────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
def add(self, entry: TopicEntry) -> None:
|
||||||
|
"""Fügt einen TopicEntry in den Ring ein.
|
||||||
|
|
||||||
|
Führt GC durch:
|
||||||
|
1. Periodischer TTL-Sweep (alle 5 Min).
|
||||||
|
2. max_per_room-Prüfung → ältesten Eintrag des Raums entfernen.
|
||||||
|
3. global_max-Prüfung → älteste ephemeral-Einträge entfernen.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
entry: Der einzufügende TopicEntry.
|
||||||
|
"""
|
||||||
|
with self._lock:
|
||||||
|
self._maybe_prune()
|
||||||
|
if entry.room_id not in self._rings:
|
||||||
|
self._rings[entry.room_id] = deque()
|
||||||
|
self._rings[entry.room_id].append(entry)
|
||||||
|
self._total_entries += 1
|
||||||
|
# GC: max_per_room
|
||||||
|
self._gc_room(entry.room_id)
|
||||||
|
# GC: global_max
|
||||||
|
self._gc_global()
|
||||||
|
self._invalidate_snapshot()
|
||||||
|
logger.debug(
|
||||||
|
"TopicRing: Added topic='%s' room=%s ttl=%s (total=%d)",
|
||||||
|
entry.topic[:40], entry.room_id[:8], entry.ttl, self._total_entries,
|
||||||
|
)
|
||||||
|
|
||||||
|
def get_recent(self, room_id: str, n: int = 5) -> List[TopicEntry]:
|
||||||
|
"""Liefert die n neuesten Topic-Einträge für einen Raum.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
room_id: Die Raum-ID.
|
||||||
|
n: Anzahl der zurückzugebenden Einträge.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Liste der neuesten TopicEntry-Objekte (neueste zuerst).
|
||||||
|
"""
|
||||||
|
snap = self._get_snapshot()
|
||||||
|
dq = snap.get(room_id, deque())
|
||||||
|
# Neueste zuerst (rechts = neueste)
|
||||||
|
return list(reversed(list(dq)))[:n]
|
||||||
|
|
||||||
|
def get_active_topic(self, room_id: str) -> Optional[TopicEntry]:
|
||||||
|
"""Liefert den aktuell aktiven Topic für einen Raum.
|
||||||
|
|
||||||
|
Der aktive Topic ist der neueste nicht-abgelaufene Eintrag.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
room_id: Die Raum-ID.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Den aktiven TopicEntry oder None.
|
||||||
|
"""
|
||||||
|
snap = self._get_snapshot()
|
||||||
|
dq = snap.get(room_id, deque())
|
||||||
|
if not dq:
|
||||||
|
return None
|
||||||
|
# Neuesten Eintrag nehmen (rechts)
|
||||||
|
entry = dq[-1]
|
||||||
|
if _is_expired(entry):
|
||||||
|
return None
|
||||||
|
return entry
|
||||||
|
|
||||||
|
def get_active_topic_for_chat(self, chat_id: str) -> Optional[str]:
|
||||||
|
"""Liefert den origin_room für den aktiven Topic eines Chats.
|
||||||
|
|
||||||
|
Wird von send() als Prio 1 verwendet: Wenn der Themenring einen
|
||||||
|
aktiven Topic für diesen chat_id hat → verwende dessen origin_room.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
chat_id: Der virtuelle Chat-ID (z.B. "user:andreas").
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
origin_room des aktiven Topics oder None.
|
||||||
|
"""
|
||||||
|
snap = self._get_snapshot()
|
||||||
|
# Suche in allen Räumen nach Einträgen für diesen user_id
|
||||||
|
best_entry: Optional[TopicEntry] = None
|
||||||
|
best_ts = 0.0
|
||||||
|
for room_id, dq in snap.items():
|
||||||
|
for entry in dq:
|
||||||
|
if entry.user_id == chat_id and not _is_expired(entry):
|
||||||
|
try:
|
||||||
|
ts = datetime.fromisoformat(entry.timestamp).timestamp()
|
||||||
|
except (ValueError, TypeError):
|
||||||
|
ts = 0
|
||||||
|
if ts > best_ts:
|
||||||
|
best_ts = ts
|
||||||
|
best_entry = entry
|
||||||
|
if best_entry is None:
|
||||||
|
return None
|
||||||
|
# Priorität: thematic_target (wenn gesetzt) > origin_room
|
||||||
|
if best_entry.thematic_target:
|
||||||
|
return best_entry.thematic_target
|
||||||
|
return best_entry.origin_room
|
||||||
|
|
||||||
|
def clear(self, room_id: Optional[str] = None) -> int:
|
||||||
|
"""Leert den Ring für einen Raum oder alle Räume.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
room_id: Raum-ID zum Leeren, oder None für alle Räume.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Anzahl der entfernten Einträge.
|
||||||
|
"""
|
||||||
|
with self._lock:
|
||||||
|
if room_id is None:
|
||||||
|
removed = self._total_entries
|
||||||
|
self._rings.clear()
|
||||||
|
self._total_entries = 0
|
||||||
|
else:
|
||||||
|
dq = self._rings.pop(room_id, deque())
|
||||||
|
removed = len(dq)
|
||||||
|
self._total_entries -= removed
|
||||||
|
self._invalidate_snapshot()
|
||||||
|
return removed
|
||||||
|
|
||||||
|
def move_gc(self, from_room: str, to_room: str) -> int:
|
||||||
|
"""Verschiebt alle Einträge von einem Raum in einen anderen.
|
||||||
|
|
||||||
|
Nützlich wenn ein Raum umbenannt oder zusammengeführt wird.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
from_room: Quell-Raum-ID.
|
||||||
|
to_room: Ziel-Raum-ID.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Anzahl der verschobenen Einträge.
|
||||||
|
"""
|
||||||
|
with self._lock:
|
||||||
|
dq = self._rings.pop(from_room, deque())
|
||||||
|
if not dq:
|
||||||
|
return 0
|
||||||
|
if to_room not in self._rings:
|
||||||
|
self._rings[to_room] = deque()
|
||||||
|
# Einträge mit aktualisierter room_id neu erstellen
|
||||||
|
moved = 0
|
||||||
|
for entry in dq:
|
||||||
|
new_entry = TopicEntry(
|
||||||
|
topic=entry.topic,
|
||||||
|
room_id=to_room,
|
||||||
|
origin_room=entry.origin_room,
|
||||||
|
thematic_target=entry.thematic_target,
|
||||||
|
timestamp=entry.timestamp,
|
||||||
|
ttl=entry.ttl,
|
||||||
|
user_id=entry.user_id,
|
||||||
|
source=entry.source,
|
||||||
|
)
|
||||||
|
self._rings[to_room].append(new_entry)
|
||||||
|
moved += 1
|
||||||
|
self._invalidate_snapshot()
|
||||||
|
return moved
|
||||||
|
|
||||||
|
@property
|
||||||
|
def total_entries(self) -> int:
|
||||||
|
"""Gesamtanzahl der Einträge über alle Räume."""
|
||||||
|
return self._total_entries
|
||||||
|
|
||||||
|
@property
|
||||||
|
def room_count(self) -> int:
|
||||||
|
"""Anzahl der Räume mit Einträgen."""
|
||||||
|
snap = self._get_snapshot()
|
||||||
|
return len(snap)
|
||||||
|
|
||||||
|
def stats(self) -> Dict[str, int]:
|
||||||
|
"""Liefert Statistiken über den Ring-Zustand.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Dict mit total_entries, room_count, und counts pro TTL-Typ.
|
||||||
|
"""
|
||||||
|
snap = self._get_snapshot()
|
||||||
|
ephemeral = 0
|
||||||
|
session = 0
|
||||||
|
persistent = 0
|
||||||
|
for dq in snap.values():
|
||||||
|
for entry in dq:
|
||||||
|
if entry.ttl == "ephemeral":
|
||||||
|
ephemeral += 1
|
||||||
|
elif entry.ttl == "session":
|
||||||
|
session += 1
|
||||||
|
elif entry.ttl == "persistent":
|
||||||
|
persistent += 1
|
||||||
|
return {
|
||||||
|
"total_entries": self._total_entries,
|
||||||
|
"room_count": len(snap),
|
||||||
|
"ephemeral": ephemeral,
|
||||||
|
"session": session,
|
||||||
|
"persistent": persistent,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# ── Modul-Singleton ───────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
# Globale Instanz — wird von adapter.py importiert und verwendet.
|
||||||
|
# Tests können eigene Instanzen erstellen.
|
||||||
|
topic_ring = TopicRing()
|
||||||
Reference in New Issue
Block a user