Compare commits
10 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 0308ce0fd2 | |||
| f3574014d5 | |||
| 5b1eeea430 | |||
| 42b90f2f94 | |||
| aa37de3e6e | |||
| 57ebbc6d6b | |||
| 41589818d2 | |||
| 3f04373d0d | |||
| 16c1ad927e | |||
| 6a09caa1e5 |
+118
-203
@@ -34,11 +34,6 @@ 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
|
||||||
@@ -151,7 +146,7 @@ if _MULTIROOM():
|
|||||||
from archivar.adapter_integration import ArchivarMessageHandler
|
from archivar.adapter_integration import ArchivarMessageHandler
|
||||||
from archivar.conversation_history import ConversationHistory
|
from archivar.conversation_history import ConversationHistory
|
||||||
from archivar.multiroom_context import MultiRoomContextRing
|
from archivar.multiroom_context import MultiRoomContextRing
|
||||||
from archivar.router import room_name_to_topic, RoutingDecision
|
from archivar.router import room_name_to_topic
|
||||||
|
|
||||||
# Routing-Counter: immer importieren (keine schweren Abhängigkeiten)
|
# Routing-Counter: immer importieren (keine schweren Abhängigkeiten)
|
||||||
from archivar.routing_counter import routing_counter
|
from archivar.routing_counter import routing_counter
|
||||||
@@ -1163,7 +1158,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
from archivar.presence_engine import PresenceEngine
|
from archivar.presence_engine import PresenceEngine
|
||||||
_presence_enabled = os.getenv("ROCKETCHAT_PRESENCE_ENABLED", "true").strip().lower() not in ("false", "0", "no", "off")
|
_presence_enabled = os.getenv("ROCKETCHAT_PRESENCE_ENABLED", "true").strip().lower() not in ("false", "0", "no", "off")
|
||||||
_coalesce_ms = int(os.getenv("ROCKETCHAT_PRESENCE_COALESCE_MS", "2000"))
|
_coalesce_ms = int(os.getenv("ROCKETCHAT_PRESENCE_COALESCE_MS", "2000"))
|
||||||
_pulse_interval = float(os.getenv('ROCKETCHAT_PRESENCE_PULSE_INTERVAL', '5.0'))
|
_pulse_interval = float(os.getenv("ROCKETCHAT_PRESENCE_PULSE_INTERVAL", "1.5"))
|
||||||
self._presence_engine = PresenceEngine(
|
self._presence_engine = PresenceEngine(
|
||||||
rest=self.rest,
|
rest=self.rest,
|
||||||
enabled=_presence_enabled,
|
enabled=_presence_enabled,
|
||||||
@@ -1809,8 +1804,13 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
logger.info("[rocketchat] B9: Reconnect — %d neue Räume gefunden, starte Onboarding", len(missing))
|
logger.info("[rocketchat] B9: Reconnect — %d neue Räume gefunden, starte Onboarding", len(missing))
|
||||||
asyncio.ensure_future(self._start_onboarding(missing))
|
asyncio.ensure_future(self._start_onboarding(missing))
|
||||||
else:
|
else:
|
||||||
# Keine neuen c/p-Räume — aber DM könnte noch Theme brauchen
|
# Keine neuen c/p-Räume — DM könnte noch Theme brauchen
|
||||||
asyncio.ensure_future(self._start_onboarding([]))
|
# FIX: Wenn Onboarding bereits ACTIVE, nicht erneut starten
|
||||||
|
# (verhindert Reset von onboarding.yaml bei Gateway-Neustart)
|
||||||
|
if sm.state != OnboardingState.ACTIVE:
|
||||||
|
asyncio.ensure_future(self._start_onboarding([]))
|
||||||
|
else:
|
||||||
|
logger.info("[rocketchat] Onboarding bereits ACTIVE — überspringe DM-Theme-Check")
|
||||||
else:
|
else:
|
||||||
missing = self.archivar.check_room_map_completeness(subscribed_with_types)
|
missing = self.archivar.check_room_map_completeness(subscribed_with_types)
|
||||||
if missing:
|
if missing:
|
||||||
@@ -1827,11 +1827,18 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
all_rooms = [{"room_id": rid, "name": info["name"]} for rid, info in non_dm_rooms.items()]
|
all_rooms = [{"room_id": rid, "name": info["name"]} for rid, info in non_dm_rooms.items()]
|
||||||
asyncio.ensure_future(self._start_onboarding(all_rooms))
|
asyncio.ensure_future(self._start_onboarding(all_rooms))
|
||||||
else:
|
else:
|
||||||
# Nur DM — trotzdem Onboarding für DM-Theme
|
# Nur DM — Onboarding für DM-Theme nur wenn nicht bereits ACTIVE
|
||||||
asyncio.ensure_future(self._start_onboarding([]))
|
if sm.state != OnboardingState.ACTIVE:
|
||||||
|
asyncio.ensure_future(self._start_onboarding([]))
|
||||||
|
else:
|
||||||
|
logger.info("[rocketchat] Onboarding bereits ACTIVE — überspringe DM-Theme-Check (leere Map)")
|
||||||
else:
|
else:
|
||||||
# Map hat Räume, keine neuen — aber DM könnte Theme brauchen
|
# Map hat Räume, keine neuen — DM könnte Theme brauchen
|
||||||
asyncio.ensure_future(self._start_onboarding([]))
|
# FIX: Wenn Onboarding bereits ACTIVE, nicht erneut starten
|
||||||
|
if sm.state != OnboardingState.ACTIVE:
|
||||||
|
asyncio.ensure_future(self._start_onboarding([]))
|
||||||
|
else:
|
||||||
|
logger.info("[rocketchat] Onboarding bereits ACTIVE — überspringe DM-Theme-Check (Map hat Räume)")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.warning("[rocketchat] Archivar-Initialisierung fehlgeschlagen: %s — Fallback ohne Klassifikation", e)
|
logger.warning("[rocketchat] Archivar-Initialisierung fehlgeschlagen: %s — Fallback ohne Klassifikation", e)
|
||||||
self._mark_connected()
|
self._mark_connected()
|
||||||
@@ -3104,37 +3111,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
# room_type wird in L1579 aus self._room_info gelesen.
|
# room_type wird in L1579 aus self._room_info gelesen.
|
||||||
_is_dm = (room_type == "d")
|
_is_dm = (room_type == "d")
|
||||||
# P0: routing_text (ohne Quote) für Klassifikation verwenden
|
# P0: routing_text (ohne Quote) für Klassifikation verwenden
|
||||||
# P0-CRITICAL: asyncio.wait_for(4s) — verhindert Event-Loop-Blockade
|
decision = await self.archivar.classify_and_route(routing_text, origin_room_id=room_id, is_dm=_is_dm)
|
||||||
# durch ThreadPool-Saturation (Pulse + Adapter + DDP-Fallback-Lawine).
|
|
||||||
global _question_counter
|
|
||||||
# P0-CRITICAL: ThreadPoolExecutor lazy init im Main-Loop.
|
|
||||||
# on_connected_cb läuft in Thread-5 (_reader_loop), nicht im
|
|
||||||
# Main-Loop — asyncio.get_event_loop() schlägt dort fehl.
|
|
||||||
# classify_and_route läuft garantiert im Main-Loop.
|
|
||||||
try:
|
|
||||||
_loop = asyncio.get_running_loop()
|
|
||||||
if not hasattr(self, '_executor_set'):
|
|
||||||
_executor = concurrent.futures.ThreadPoolExecutor(max_workers=32)
|
|
||||||
_loop.set_default_executor(_executor)
|
|
||||||
self._executor_set = True
|
|
||||||
logger.info("[rocketchat] ThreadPoolExecutor max_workers=32 gesetzt (lazy, im Main-Loop)")
|
|
||||||
except Exception as e:
|
|
||||||
logger.warning("[rocketchat] ThreadPoolExecutor set_default_executor failed: %s", e)
|
|
||||||
try:
|
|
||||||
decision = await asyncio.wait_for(
|
|
||||||
self.archivar.classify_and_route(routing_text, origin_room_id=room_id, is_dm=_is_dm),
|
|
||||||
timeout=20.0,
|
|
||||||
)
|
|
||||||
except asyncio.TimeoutError:
|
|
||||||
logger.warning("[rocketchat] Archivar classify_and_route() timed out (20s) — STAY fallback")
|
|
||||||
decision = RoutingDecision(
|
|
||||||
category='direct_question',
|
|
||||||
target_room=room_id,
|
|
||||||
confidence=0.0,
|
|
||||||
stay_in_room=True,
|
|
||||||
)
|
|
||||||
with _question_counter_lock:
|
|
||||||
_question_counter += 1
|
|
||||||
# V8.3.3: Telemetrie nach jeder Routing-Entscheidung flushen
|
# V8.3.3: Telemetrie nach jeder Routing-Entscheidung flushen
|
||||||
routing_telemetry.flush()
|
routing_telemetry.flush()
|
||||||
if decision and decision.category:
|
if decision and decision.category:
|
||||||
@@ -3153,6 +3130,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
if (hasattr(decision, 'target_room') and decision.target_room
|
if (hasattr(decision, 'target_room') and decision.target_room
|
||||||
and not getattr(decision, 'stay_in_room', False)):
|
and not getattr(decision, 'stay_in_room', False)):
|
||||||
_THEMATIC_TARGET_ROOM.set(decision.target_room)
|
_THEMATIC_TARGET_ROOM.set(decision.target_room)
|
||||||
|
global _question_counter
|
||||||
with _question_counter_lock:
|
with _question_counter_lock:
|
||||||
_question_counter += 1
|
_question_counter += 1
|
||||||
# ── Ende Kontext-Weitergabe ──────────────────────────────
|
# ── Ende Kontext-Weitergabe ──────────────────────────────
|
||||||
@@ -3193,45 +3171,6 @@ 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":
|
|
||||||
# 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=datetime.datetime.now(datetime.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,
|
||||||
@@ -6553,80 +6492,64 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
if chat_id.startswith("user:"):
|
if chat_id.startswith("user:"):
|
||||||
# Priority 0: _CURRENT_ORIGIN_ROOM — Antwort geht IMMER dorthin,
|
# Priority 0: _CURRENT_ORIGIN_ROOM — Antwort geht IMMER dorthin,
|
||||||
# wo die Frage gestellt wurde.
|
# wo die Frage gestellt wurde.
|
||||||
|
# P1 Cross-Contamination-Fix: Task-Token-Validierung VOR Verwendung.
|
||||||
|
# _CURRENT_ORIGIN_ROOM kann in neuen asyncio-Tasks einen stale Wert
|
||||||
|
# vom Parent-Task erben. Wir validieren gegen _room_context task_token,
|
||||||
|
# um Cross-Contamination (Auto-Route → Widerspruch → falscher Raum) zu
|
||||||
|
# verhindern.
|
||||||
origin = _CURRENT_ORIGIN_ROOM.get()
|
origin = _CURRENT_ORIGIN_ROOM.get()
|
||||||
|
if origin:
|
||||||
|
# Pre-Read-Validierung: Task-Token-Match prüfen
|
||||||
|
current_token = _CURRENT_TASK_TOKEN.get()
|
||||||
|
ctx_entry = _room_context.get(chat_id, {})
|
||||||
|
stored_token = ctx_entry.get("task_token", "")
|
||||||
|
# Token-Mismatch: _CURRENT_ORIGIN_ROOM ist stale → skippen,
|
||||||
|
# normale ContextVar-Logik weiterlaufen lassen
|
||||||
|
if current_token and stored_token and current_token != stored_token:
|
||||||
|
routing_counter.increment('priority0_token_mismatch_skip')
|
||||||
|
logger.info(
|
||||||
|
"[rocketchat] send Priority 0 token mismatch for %s — "
|
||||||
|
"skipping stale ContextVar, falling through to _room_context",
|
||||||
|
chat_id,
|
||||||
|
)
|
||||||
|
origin = "" # Force fallthrough
|
||||||
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:
|
else:
|
||||||
# ── Themenring Phase A: Prio 1 — Raumbezogener Topic-Lookup ──
|
# P1: _room_context als persistenter Fallback (Stream-Retry ContextVar-Reset)
|
||||||
# F6: Erst raumbezogen prüfen (get_active_topic mit origin_room),
|
# ContextVars sind asyncio-task-lokal — bei Stream-Retries in neuem Task
|
||||||
# dann user-weit fallen (get_active_topic_for_chat).
|
# ist _CURRENT_ORIGIN_ROOM leer. _room_context (global dict) überlebt.
|
||||||
# Verhindert Cross-Contamination: Wenn Andreas in Raum A und B
|
# P1 Cross-Contamination-Fix: _get_room_context_origin validiert
|
||||||
# geschrieben hat, muss die Antwort in A den Topic von A liefern,
|
# Task-Token + TTL, verhindert Cross-Contamination zwischen Räumen.
|
||||||
# nicht den user-weit neuesten (der von B kommen könnte).
|
fallback_origin = _get_room_context_origin(chat_id)
|
||||||
#
|
if fallback_origin:
|
||||||
# Raumbezogener Lookup: Nutze _room_context um den Raum zu
|
real_room_id = fallback_origin
|
||||||
# bestimmen, in den die Antwort gehen soll. Dann hole den
|
routing_counter.increment('contextvar_reset_fallback')
|
||||||
# aktiven Topic NUR für diesen Raum — nicht user-weit.
|
logger.info("[rocketchat] send via _room_context fallback: %s → %s", chat_id, real_room_id)
|
||||||
_candidate_room = _get_room_context_origin(chat_id) or ''
|
|
||||||
topic_ring_origin = None
|
|
||||||
if _candidate_room:
|
|
||||||
_topic_entry = topic_ring.get_active_topic(_candidate_room)
|
|
||||||
if _topic_entry is not None:
|
|
||||||
# thematic_target hat Vorrang vor origin_room
|
|
||||||
if _topic_entry.thematic_target:
|
|
||||||
topic_ring_origin = _topic_entry.thematic_target
|
|
||||||
else:
|
|
||||||
topic_ring_origin = _topic_entry.origin_room
|
|
||||||
logger.info(
|
|
||||||
"[rocketchat] send via TopicRing raumbezogen: %s → %s (room=%s)",
|
|
||||||
chat_id, topic_ring_origin[:8], _candidate_room[:8],
|
|
||||||
)
|
|
||||||
# Prio 1.5: TopicRing user-weit (Fallback wenn kein raumbezogener Treffer)
|
|
||||||
if not topic_ring_origin:
|
|
||||||
topic_ring_origin = topic_ring.get_active_topic_for_chat(chat_id)
|
|
||||||
if topic_ring_origin:
|
|
||||||
logger.info(
|
|
||||||
"[rocketchat] send via TopicRing user-weit: %s → %s (fallback)",
|
|
||||||
chat_id, topic_ring_origin[:8],
|
|
||||||
)
|
|
||||||
if topic_ring_origin:
|
|
||||||
real_room_id = topic_ring_origin
|
|
||||||
routing_counter.increment('topic_ring_prio1')
|
|
||||||
else:
|
else:
|
||||||
# P1: _room_context als persistenter Fallback (Stream-Retry ContextVar-Reset)
|
# Priority 1: Archivar-Kontext — nur für proaktive Nachrichten
|
||||||
# ContextVars sind asyncio-task-lokal — bei Stream-Retries in neuem Task
|
# ohne vorherige Frage (kein _CURRENT_ORIGIN_ROOM gesetzt).
|
||||||
# ist _CURRENT_ORIGIN_ROOM leer. _room_context (global dict) überlebt.
|
thematic_target = _THEMATIC_TARGET_ROOM.get()
|
||||||
# P1 Cross-Contamination-Fix: _get_room_context_origin validiert
|
if thematic_target:
|
||||||
# Task-Token + TTL, verhindert Cross-Contamination zwischen Räumen.
|
real_room_id = thematic_target
|
||||||
fallback_origin = _get_room_context_origin(chat_id)
|
logger.debug("[rocketchat] send via Archivar target: %s → %s", chat_id, real_room_id)
|
||||||
if fallback_origin:
|
|
||||||
real_room_id = fallback_origin
|
|
||||||
routing_counter.increment('contextvar_reset_fallback')
|
|
||||||
logger.info("[rocketchat] send via _room_context fallback: %s → %s", chat_id, real_room_id)
|
|
||||||
else:
|
else:
|
||||||
# Priority 1: Archivar-Kontext — nur für proaktive Nachrichten
|
# Priority 2: proaktive Nachricht — use most recent room for this user
|
||||||
# ohne vorherige Frage (kein _CURRENT_ORIGIN_ROOM gesetzt).
|
rooms = self._user_rooms.get(chat_id, [])
|
||||||
thematic_target = _THEMATIC_TARGET_ROOM.get()
|
if rooms:
|
||||||
if thematic_target:
|
real_room_id = rooms[-1] # last room user was active in
|
||||||
real_room_id = thematic_target
|
logger.debug("[rocketchat] send via user_map (proactive): %s → %s", chat_id, real_room_id)
|
||||||
logger.debug("[rocketchat] send via Archivar target: %s → %s", chat_id, real_room_id)
|
|
||||||
else:
|
else:
|
||||||
# Priority 2: proaktive Nachricht — use most recent room for this user
|
# Fallback: try to find any room with recent activity involving this user
|
||||||
rooms = self._user_rooms.get(chat_id, [])
|
logger.warning("[rocketchat] No mapped room for %s, attempting fallback", chat_id)
|
||||||
if rooms:
|
fallback_room = self._find_fallback_room_for_user(chat_id)
|
||||||
real_room_id = rooms[-1] # last room user was active in
|
if fallback_room:
|
||||||
logger.debug("[rocketchat] send via user_map (proactive): %s → %s", chat_id, real_room_id)
|
real_room_id = fallback_room
|
||||||
|
logger.info("[rocketchat] Using fallback room %s for %s", fallback_room, chat_id)
|
||||||
else:
|
else:
|
||||||
# Fallback: try to find any room with recent activity involving this user
|
logger.error("[rocketchat] No real room for %s, cannot send", chat_id)
|
||||||
logger.warning("[rocketchat] No mapped room for %s, attempting fallback", chat_id)
|
return SendResult(success=False, error=f"No real room for virtual chat_id {chat_id}")
|
||||||
fallback_room = self._find_fallback_room_for_user(chat_id)
|
|
||||||
if fallback_room:
|
|
||||||
real_room_id = fallback_room
|
|
||||||
logger.info("[rocketchat] Using fallback room %s for %s", fallback_room, chat_id)
|
|
||||||
else:
|
|
||||||
logger.error("[rocketchat] No real room for %s, cannot send", chat_id)
|
|
||||||
return SendResult(success=False, error=f"No real room for virtual chat_id {chat_id}")
|
|
||||||
|
|
||||||
# ── Minimal-Fix: Parse [[BUTTONS:...]] markup from agent response text ──
|
# ── Minimal-Fix: Parse [[BUTTONS:...]] markup from agent response text ──
|
||||||
# This allows the agent to request buttons by embedding markup in its
|
# This allows the agent to request buttons by embedding markup in its
|
||||||
@@ -6962,70 +6885,62 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
real_room_id = chat_id
|
real_room_id = chat_id
|
||||||
if chat_id.startswith("user:"):
|
if chat_id.startswith("user:"):
|
||||||
# Priority 0: ContextVar from the message that triggered this turn
|
# Priority 0: ContextVar from the message that triggered this turn
|
||||||
|
# P1 Cross-Contamination-Fix: Task-Token-Validierung VOR Verwendung.
|
||||||
|
# _CURRENT_ORIGIN_ROOM kann in neuen asyncio-Tasks einen stale Wert
|
||||||
|
# vom Parent-Task erben. Wir validieren gegen _room_context task_token,
|
||||||
|
# um Cross-Contamination (Auto-Route → Widerspruch → falscher Raum) zu
|
||||||
|
# verhindern.
|
||||||
origin = _CURRENT_ORIGIN_ROOM.get()
|
origin = _CURRENT_ORIGIN_ROOM.get()
|
||||||
|
if origin:
|
||||||
|
# Pre-Read-Validierung: Task-Token-Match prüfen
|
||||||
|
current_token = _CURRENT_TASK_TOKEN.get()
|
||||||
|
ctx_entry = _room_context.get(chat_id, {})
|
||||||
|
stored_token = ctx_entry.get("task_token", "")
|
||||||
|
# Token-Mismatch: _CURRENT_ORIGIN_ROOM ist stale → skippen,
|
||||||
|
# normale ContextVar-Logik weiterlaufen lassen
|
||||||
|
if current_token and stored_token and current_token != stored_token:
|
||||||
|
routing_counter.increment('priority0_token_mismatch_skip')
|
||||||
|
logger.info(
|
||||||
|
"[rocketchat] send_clarify Priority 0 token mismatch for %s — "
|
||||||
|
"skipping stale ContextVar, falling through to _room_context",
|
||||||
|
chat_id,
|
||||||
|
)
|
||||||
|
origin = "" # Force fallthrough
|
||||||
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:
|
else:
|
||||||
# ── Themenring Phase A: Prio 1 — Raumbezogener Topic-Lookup ──
|
# P1: _room_context als persistenter Fallback (Stream-Retry ContextVar-Reset)
|
||||||
# F6: Erst raumbezogen prüfen (get_active_topic mit origin_room),
|
# P1 Cross-Contamination-Fix: _get_room_context_origin validiert
|
||||||
# dann user-weit fallen (get_active_topic_for_chat).
|
# Task-Token + TTL, verhindert Cross-Contamination zwischen Räumen.
|
||||||
_candidate_room = _get_room_context_origin(chat_id) or ''
|
fallback_origin = _get_room_context_origin(chat_id)
|
||||||
topic_ring_origin = None
|
if fallback_origin:
|
||||||
if _candidate_room:
|
real_room_id = fallback_origin
|
||||||
_topic_entry = topic_ring.get_active_topic(_candidate_room)
|
routing_counter.increment('contextvar_reset_fallback')
|
||||||
if _topic_entry is not None:
|
logger.info("[rocketchat] send_clarify via _room_context fallback: %s → %s", chat_id, real_room_id)
|
||||||
if _topic_entry.thematic_target:
|
|
||||||
topic_ring_origin = _topic_entry.thematic_target
|
|
||||||
else:
|
|
||||||
topic_ring_origin = _topic_entry.origin_room
|
|
||||||
logger.info(
|
|
||||||
"[rocketchat] send_clarify via TopicRing raumbezogen: %s → %s (room=%s)",
|
|
||||||
chat_id, topic_ring_origin[:8], _candidate_room[:8],
|
|
||||||
)
|
|
||||||
# Prio 1.5: TopicRing user-weit (Fallback wenn kein raumbezogener Treffer)
|
|
||||||
if not topic_ring_origin:
|
|
||||||
topic_ring_origin = topic_ring.get_active_topic_for_chat(chat_id)
|
|
||||||
if topic_ring_origin:
|
|
||||||
logger.info(
|
|
||||||
"[rocketchat] send_clarify via TopicRing user-weit: %s → %s (fallback)",
|
|
||||||
chat_id, topic_ring_origin[:8],
|
|
||||||
)
|
|
||||||
if topic_ring_origin:
|
|
||||||
real_room_id = topic_ring_origin
|
|
||||||
routing_counter.increment('topic_ring_prio1')
|
|
||||||
else:
|
else:
|
||||||
# P1: _room_context als persistenter Fallback (Stream-Retry ContextVar-Reset)
|
# Priority 1: Archivar-Kontext — nur für proaktive Nachrichten
|
||||||
# P1 Cross-Contamination-Fix: _get_room_context_origin validiert
|
# ohne vorherige Frage (kein _CURRENT_ORIGIN_ROOM gesetzt).
|
||||||
# Task-Token + TTL, verhindert Cross-Contamination zwischen Räumen.
|
thematic_target = _THEMATIC_TARGET_ROOM.get()
|
||||||
fallback_origin = _get_room_context_origin(chat_id)
|
if thematic_target:
|
||||||
if fallback_origin:
|
real_room_id = thematic_target
|
||||||
real_room_id = fallback_origin
|
logger.debug("[rocketchat] send_clarify via Archivar target: %s → %s", chat_id, real_room_id)
|
||||||
routing_counter.increment('contextvar_reset_fallback')
|
|
||||||
logger.info("[rocketchat] send_clarify via _room_context fallback: %s → %s", chat_id, real_room_id)
|
|
||||||
else:
|
else:
|
||||||
# Priority 1: Archivar-Kontext — nur für proaktive Nachrichten
|
# Priority 2: proactive message — use most recent room for this user
|
||||||
# ohne vorherige Frage (kein _CURRENT_ORIGIN_ROOM gesetzt).
|
rooms = self._user_rooms.get(chat_id, [])
|
||||||
thematic_target = _THEMATIC_TARGET_ROOM.get()
|
if rooms:
|
||||||
if thematic_target:
|
real_room_id = rooms[-1] # last room user was active in
|
||||||
real_room_id = thematic_target
|
logger.debug("[rocketchat] send_clarify via user_map (proactive): %s → %s", chat_id, real_room_id)
|
||||||
logger.debug("[rocketchat] send_clarify via Archivar target: %s → %s", chat_id, real_room_id)
|
|
||||||
else:
|
else:
|
||||||
# Priority 2: proactive message — use most recent room for this user
|
# Fallback: try to find any room with recent activity involving this user
|
||||||
rooms = self._user_rooms.get(chat_id, [])
|
logger.warning("[rocketchat] No mapped room for %s, attempting fallback", chat_id)
|
||||||
if rooms:
|
fallback_room = self._find_fallback_room_for_user(chat_id)
|
||||||
real_room_id = rooms[-1] # last room user was active in
|
if fallback_room:
|
||||||
logger.debug("[rocketchat] send_clarify via user_map (proactive): %s → %s", chat_id, real_room_id)
|
real_room_id = fallback_room
|
||||||
|
logger.info("[rocketchat] Using fallback room %s for %s", fallback_room, chat_id)
|
||||||
else:
|
else:
|
||||||
# Fallback: try to find any room with recent activity involving this user
|
logger.error("[rocketchat] No real room for %s, cannot send", chat_id)
|
||||||
logger.warning("[rocketchat] No mapped room for %s, attempting fallback", chat_id)
|
return SendResult(success=False, error=f"No real room for virtual chat_id {chat_id}")
|
||||||
fallback_room = self._find_fallback_room_for_user(chat_id)
|
|
||||||
if fallback_room:
|
|
||||||
real_room_id = fallback_room
|
|
||||||
logger.info("[rocketchat] Using fallback room %s for %s", fallback_room, chat_id)
|
|
||||||
else:
|
|
||||||
logger.error("[rocketchat] No real room for %s, cannot send", chat_id)
|
|
||||||
return SendResult(success=False, error=f"No real room for virtual chat_id {chat_id}")
|
|
||||||
|
|
||||||
# Render full option text in the message body so users
|
# Render full option text in the message body so users
|
||||||
# can read long choices that would be truncated in buttons.
|
# can read long choices that would be truncated in buttons.
|
||||||
|
|||||||
@@ -10,7 +10,6 @@ ClassificationResult zurückgegeben — der Router übernimmt dann den Fallback.
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import abc
|
import abc
|
||||||
import concurrent.futures
|
|
||||||
import json
|
import json
|
||||||
import logging
|
import logging
|
||||||
import math
|
import math
|
||||||
@@ -152,36 +151,7 @@ class OllamaEmbeddingClient(EmbeddingClient):
|
|||||||
self._timeout = timeout or OLLAMA_CONFIG["timeout"]
|
self._timeout = timeout or OLLAMA_CONFIG["timeout"]
|
||||||
|
|
||||||
def get_embedding(self, text: str) -> Optional[List[float]]:
|
def get_embedding(self, text: str) -> Optional[List[float]]:
|
||||||
"""Call Ollama embeddings API with a hard deadline timeout.
|
"""Call Ollama embeddings API. Returns None on any failure."""
|
||||||
|
|
||||||
Uses ``concurrent.futures.ThreadPoolExecutor(max_workers=1)`` with
|
|
||||||
``.result(timeout=self._timeout)`` to enforce a HARD deadline on the
|
|
||||||
entire HTTP call — not just a socket-level timeout. If the embedding
|
|
||||||
model takes longer than the deadline, the future is abandoned and
|
|
||||||
``None`` is returned.
|
|
||||||
|
|
||||||
The executor is shut down with ``wait=False`` on timeout so the
|
|
||||||
caller is never blocked by a hung worker thread.
|
|
||||||
"""
|
|
||||||
executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)
|
|
||||||
_shutdown = False
|
|
||||||
try:
|
|
||||||
future = executor.submit(self._get_embedding_sync, text)
|
|
||||||
return future.result(timeout=self._timeout)
|
|
||||||
except concurrent.futures.TimeoutError:
|
|
||||||
logger.warning(
|
|
||||||
"Ollama embedding timed out after %.1fs — returning None",
|
|
||||||
self._timeout,
|
|
||||||
)
|
|
||||||
executor.shutdown(wait=False)
|
|
||||||
_shutdown = True
|
|
||||||
return None
|
|
||||||
finally:
|
|
||||||
if not _shutdown:
|
|
||||||
executor.shutdown(wait=True)
|
|
||||||
|
|
||||||
def _get_embedding_sync(self, text: str) -> Optional[List[float]]:
|
|
||||||
"""Synchronous embedding implementation (called inside ThreadPoolExecutor)."""
|
|
||||||
url = f"{self._base_url}/api/embeddings"
|
url = f"{self._base_url}/api/embeddings"
|
||||||
payload = json.dumps(
|
payload = json.dumps(
|
||||||
{"model": self._model, "prompt": text}
|
{"model": self._model, "prompt": text}
|
||||||
@@ -287,36 +257,7 @@ class OllamaLLMClient(LLMClient):
|
|||||||
self._timeout = timeout or LLM_CONFIG["timeout"]
|
self._timeout = timeout or LLM_CONFIG["timeout"]
|
||||||
|
|
||||||
def classify(self, text: str) -> Optional[str]:
|
def classify(self, text: str) -> Optional[str]:
|
||||||
"""Call Ollama generate API with a real deadline timeout.
|
"""Call Ollama generate API. Returns category or None on any failure."""
|
||||||
|
|
||||||
Uses ``concurrent.futures.ThreadPoolExecutor(max_workers=1)`` with
|
|
||||||
``.result(timeout=self._timeout)`` to enforce a HARD deadline on the
|
|
||||||
entire HTTP call — not just a socket-level timeout that resets on
|
|
||||||
every token. If the LLM (e.g. qwen2.5:7b on CPU) takes longer than
|
|
||||||
the deadline, the future is abandoned and ``None`` is returned.
|
|
||||||
|
|
||||||
The executor is shut down with ``wait=False`` on timeout so the
|
|
||||||
caller is never blocked by a hung worker thread.
|
|
||||||
"""
|
|
||||||
executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)
|
|
||||||
_shutdown = False
|
|
||||||
try:
|
|
||||||
future = executor.submit(self._classify_sync, text)
|
|
||||||
return future.result(timeout=self._timeout)
|
|
||||||
except concurrent.futures.TimeoutError:
|
|
||||||
logger.warning(
|
|
||||||
"Ollama classify timed out after %.1fs — returning None",
|
|
||||||
self._timeout,
|
|
||||||
)
|
|
||||||
executor.shutdown(wait=False)
|
|
||||||
_shutdown = True
|
|
||||||
return None
|
|
||||||
finally:
|
|
||||||
if not _shutdown:
|
|
||||||
executor.shutdown(wait=True)
|
|
||||||
|
|
||||||
def _classify_sync(self, text: str) -> Optional[str]:
|
|
||||||
"""Synchronous classify implementation (called inside ThreadPoolExecutor)."""
|
|
||||||
url = f"{self._base_url}/api/generate"
|
url = f"{self._base_url}/api/generate"
|
||||||
payload = json.dumps(
|
payload = json.dumps(
|
||||||
{
|
{
|
||||||
@@ -386,11 +327,8 @@ direct_question, smalltalk, work_order, oder ambiguous"""
|
|||||||
def generate(self, prompt: str) -> Optional[str]:
|
def generate(self, prompt: str) -> Optional[str]:
|
||||||
"""Generiere eine freie Antwort vom LLM (keine Kategorie-Validierung).
|
"""Generiere eine freie Antwort vom LLM (keine Kategorie-Validierung).
|
||||||
|
|
||||||
Uses ``concurrent.futures.ThreadPoolExecutor(max_workers=1)`` with
|
Sendet den Prompt an Ollama's /api/generate und gibt die Antwort
|
||||||
``.result(timeout=self._timeout)`` to enforce a HARD deadline on the
|
unvalidiert zurück. Wird vom Raum-Router für LLM_ROOM_PROMPT verwendet.
|
||||||
entire HTTP call — not just a socket-level timeout that resets on
|
|
||||||
every token. If the LLM (e.g. qwen2.5:7b on CPU) takes longer than
|
|
||||||
the deadline, the future is abandoned and ``None`` is returned.
|
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
prompt: Der vollständige Prompt (z.B. LLM_ROOM_PROMPT).
|
prompt: Der vollständige Prompt (z.B. LLM_ROOM_PROMPT).
|
||||||
@@ -398,25 +336,6 @@ direct_question, smalltalk, work_order, oder ambiguous"""
|
|||||||
Returns:
|
Returns:
|
||||||
Die LLM-Antwort als String (getrimmt), oder None bei Fehler.
|
Die LLM-Antwort als String (getrimmt), oder None bei Fehler.
|
||||||
"""
|
"""
|
||||||
executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)
|
|
||||||
_shutdown = False
|
|
||||||
try:
|
|
||||||
future = executor.submit(self._generate_sync, prompt)
|
|
||||||
return future.result(timeout=self._timeout)
|
|
||||||
except concurrent.futures.TimeoutError:
|
|
||||||
logger.warning(
|
|
||||||
"Ollama generate timed out after %.1fs — returning None",
|
|
||||||
self._timeout,
|
|
||||||
)
|
|
||||||
executor.shutdown(wait=False)
|
|
||||||
_shutdown = True
|
|
||||||
return None
|
|
||||||
finally:
|
|
||||||
if not _shutdown:
|
|
||||||
executor.shutdown(wait=True)
|
|
||||||
|
|
||||||
def _generate_sync(self, prompt: str) -> Optional[str]:
|
|
||||||
"""Synchronous generate implementation (called inside ThreadPoolExecutor)."""
|
|
||||||
url = f"{self._base_url}/api/generate"
|
url = f"{self._base_url}/api/generate"
|
||||||
payload = json.dumps(
|
payload = json.dumps(
|
||||||
{
|
{
|
||||||
@@ -550,17 +469,7 @@ class IntentClassifier:
|
|||||||
|
|
||||||
async def _llm_classify(self, text: str, scores: Dict[str, float]) -> Optional[Tuple[str, float]]:
|
async def _llm_classify(self, text: str, scores: Dict[str, float]) -> Optional[Tuple[str, float]]:
|
||||||
import asyncio
|
import asyncio
|
||||||
try:
|
return await asyncio.to_thread(self._llm_classify_sync, text, scores)
|
||||||
# P0-CRITICAL: asyncio.wait_for(15s) — muss KLEINER sein als
|
|
||||||
# der äußere 20s-Timeout in adapter.py, damit die Timeout-Hierarchie
|
|
||||||
# korrekt ist: 20s (außen) > 15s (innen).
|
|
||||||
return await asyncio.wait_for(
|
|
||||||
asyncio.to_thread(self._llm_classify_sync, text, scores),
|
|
||||||
timeout=15.0,
|
|
||||||
)
|
|
||||||
except asyncio.TimeoutError:
|
|
||||||
logger.warning("LLM classify timed out (15s) — returning None")
|
|
||||||
return None
|
|
||||||
|
|
||||||
def _llm_classify_sync(self, text: str, scores: Dict[str, float]) -> Optional[Tuple[str, float]]:
|
def _llm_classify_sync(self, text: str, scores: Dict[str, float]) -> Optional[Tuple[str, float]]:
|
||||||
try:
|
try:
|
||||||
@@ -591,17 +500,7 @@ class IntentClassifier:
|
|||||||
try:
|
try:
|
||||||
if not self._llm_client or not self._llm_enabled:
|
if not self._llm_client or not self._llm_enabled:
|
||||||
return None
|
return None
|
||||||
# P0-CRITICAL: asyncio.wait_for(15s) — muss KLEINER sein als
|
return await asyncio.to_thread(self._llm_client.generate, prompt)
|
||||||
# der äußere 20s-Timeout in adapter.py, damit die Timeout-Hierarchie
|
|
||||||
# korrekt ist: 20s (außen) > 15s (innen).
|
|
||||||
# Bei Timeout: return None → Router wählt STAY-Fallback (router.py Z.1583).
|
|
||||||
return await asyncio.wait_for(
|
|
||||||
asyncio.to_thread(self._llm_client.generate, prompt),
|
|
||||||
timeout=15.0,
|
|
||||||
)
|
|
||||||
except asyncio.TimeoutError:
|
|
||||||
logger.warning("LLM raw call timed out (15s) — returning None for STAY fallback")
|
|
||||||
return None
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.warning("LLM raw call failed: %s", e)
|
logger.warning("LLM raw call failed: %s", e)
|
||||||
return None
|
return None
|
||||||
@@ -733,17 +632,7 @@ class IntentClassifier:
|
|||||||
best_score >= CONFIDENCE_THRESHOLDS["CLARIFY_NEEDED"] and
|
best_score >= CONFIDENCE_THRESHOLDS["CLARIFY_NEEDED"] and
|
||||||
best_score < CONFIDENCE_THRESHOLDS["AUTO_ROUTE"]
|
best_score < CONFIDENCE_THRESHOLDS["AUTO_ROUTE"]
|
||||||
):
|
):
|
||||||
# P0-CRITICAL: Timeout 15s — muss KLEINER sein als der äußere
|
llm_result = self._llm_classify_sync(text, scores)
|
||||||
# 20s-Timeout in adapter.py. Verhindert ThreadPool-Saturation
|
|
||||||
# durch hängende verify_confidence-Calls.
|
|
||||||
import concurrent.futures
|
|
||||||
with concurrent.futures.ThreadPoolExecutor(max_workers=1) as _exec:
|
|
||||||
_future = _exec.submit(self._llm_classify_sync, text, scores)
|
|
||||||
try:
|
|
||||||
llm_result = _future.result(timeout=15.0)
|
|
||||||
except concurrent.futures.TimeoutError:
|
|
||||||
logger.warning("LLM verify_confidence timed out (15s) — skipping verification")
|
|
||||||
llm_result = None
|
|
||||||
if llm_result:
|
if llm_result:
|
||||||
final_category, final_score = llm_result
|
final_category, final_score = llm_result
|
||||||
llm_verified = True
|
llm_verified = True
|
||||||
|
|||||||
@@ -16,8 +16,7 @@ from typing import Dict
|
|||||||
OLLAMA_CONFIG: dict = {
|
OLLAMA_CONFIG: dict = {
|
||||||
"base_url": os.getenv("ARCHIVAR_EMBEDDING_BASE_URL", "http://localhost:11434"),
|
"base_url": os.getenv("ARCHIVAR_EMBEDDING_BASE_URL", "http://localhost:11434"),
|
||||||
"model": "nomic-embed-text",
|
"model": "nomic-embed-text",
|
||||||
"timeout": 3.0, # Sekunden — HARD deadline via ThreadPoolExecutor
|
"timeout": 10.0, # Sekunden — empirisch: Ø 2.4s, Cold-Start bis 7.8s
|
||||||
# Muss KLEINER sein als äußerer 20s-Timeout in adapter.py
|
|
||||||
"embedding_dim": 768, # nomic-embed-text produziert 768-dimensionale Vektoren
|
"embedding_dim": 768, # nomic-embed-text produziert 768-dimensionale Vektoren
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -157,8 +156,7 @@ wird sie entsprechend klassifiziert. Alles andere → FAKT.
|
|||||||
LLM_CONFIG = {
|
LLM_CONFIG = {
|
||||||
"enabled": os.getenv("ARCHIVAR_ENABLE_LLM", "").strip().lower() in ("1", "true", "yes"),
|
"enabled": os.getenv("ARCHIVAR_ENABLE_LLM", "").strip().lower() in ("1", "true", "yes"),
|
||||||
"model": "qwen2.5:7b",
|
"model": "qwen2.5:7b",
|
||||||
"timeout": 15.0, # HARD deadline via ThreadPoolExecutor.result(timeout=X)
|
"timeout": 30.0, # Iterative Optimierung: Start 30s (19.06.2026)
|
||||||
# Muss KLEINER sein als äußerer 20s-Timeout in adapter.py
|
|
||||||
"base_url": os.getenv(
|
"base_url": os.getenv(
|
||||||
"ARCHIVAR_LLM_BASE_URL",
|
"ARCHIVAR_LLM_BASE_URL",
|
||||||
os.getenv("OLLAMA_BASE_URL", "http://localhost:11434")
|
os.getenv("OLLAMA_BASE_URL", "http://localhost:11434")
|
||||||
@@ -335,30 +333,6 @@ 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.
|
||||||
|
|||||||
@@ -162,7 +162,7 @@ class PresenceEngine:
|
|||||||
rest=None,
|
rest=None,
|
||||||
enabled: bool = True,
|
enabled: bool = True,
|
||||||
coalesce_ms: int = 2000,
|
coalesce_ms: int = 2000,
|
||||||
pulse_interval: float = 5.0,
|
pulse_interval: float = 1.5,
|
||||||
gateway_state_path: str = "",
|
gateway_state_path: str = "",
|
||||||
_clamp_pulse: bool = True,
|
_clamp_pulse: bool = True,
|
||||||
):
|
):
|
||||||
@@ -719,13 +719,13 @@ class PulseController:
|
|||||||
|
|
||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
pulse_interval: float = 5.0,
|
pulse_interval: float = 1.5,
|
||||||
_clamp_pulse: bool = True,
|
_clamp_pulse: bool = True,
|
||||||
):
|
):
|
||||||
"""Initialize PulseController.
|
"""Initialize PulseController.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
pulse_interval: Pulse interval in seconds (default 5.0).
|
pulse_interval: Pulse interval in seconds (default 1.5).
|
||||||
_clamp_pulse: If True, clamp to 0.5-30s. Set False for testing.
|
_clamp_pulse: If True, clamp to 0.5-30s. Set False for testing.
|
||||||
"""
|
"""
|
||||||
if _clamp_pulse:
|
if _clamp_pulse:
|
||||||
@@ -745,12 +745,6 @@ class PulseController:
|
|||||||
# P1-2 O-2: Async-await bridge
|
# P1-2 O-2: Async-await bridge
|
||||||
self._loop: Optional[asyncio.AbstractEventLoop] = None
|
self._loop: Optional[asyncio.AbstractEventLoop] = None
|
||||||
self._await_timeout: float = 2.0
|
self._await_timeout: float = 2.0
|
||||||
# P0-CRITICAL: Default sync — async-Pfad nur wenn explizit aktiviert.
|
|
||||||
# Verhindert ThreadPool-Saturation durch run_coroutine_threadsafe.
|
|
||||||
self._use_async_tick: bool = False
|
|
||||||
# P0-CRITICAL: Circuit-Breaker — zweistufiges Backoff bei Fehlern.
|
|
||||||
self._consecutive_failures: int = 0
|
|
||||||
self._current_interval: Optional[float] = None # None = use _pulse_interval
|
|
||||||
|
|
||||||
# ── Public API ───────────────────────────────────────────────────────
|
# ── Public API ───────────────────────────────────────────────────────
|
||||||
|
|
||||||
@@ -888,10 +882,7 @@ class PulseController:
|
|||||||
self._pulse_tick()
|
self._pulse_tick()
|
||||||
|
|
||||||
# Sleep for pulse interval, checking running flag periodically
|
# Sleep for pulse interval, checking running flag periodically
|
||||||
# P0-CRITICAL: Circuit-Breaker — _current_interval überschreibt
|
for _ in range(int(self._pulse_interval * 10)):
|
||||||
# _pulse_interval bei Fehlern (Stufe 1: 10s, Stufe 2: 30s).
|
|
||||||
effective_interval = self._current_interval if self._current_interval is not None else self._pulse_interval
|
|
||||||
for _ in range(int(effective_interval * 10)):
|
|
||||||
if not self._running.is_set():
|
if not self._running.is_set():
|
||||||
break
|
break
|
||||||
if self._paused.is_set():
|
if self._paused.is_set():
|
||||||
@@ -932,10 +923,8 @@ class PulseController:
|
|||||||
)
|
)
|
||||||
return
|
return
|
||||||
|
|
||||||
# P0-CRITICAL: Default sync — async-Pfad nur wenn explizit aktiviert.
|
# P1-2 O-2: Delegate to async path if loop is bound and running
|
||||||
# run_coroutine_threadsafe sättigt den ThreadPool und blockiert den
|
if self._loop is not None and self._loop.is_running():
|
||||||
# Event-Loop-Selector → Watchdog-Probes schlagen fehl → Kill.
|
|
||||||
if self._use_async_tick and self._loop is not None and self._loop.is_running():
|
|
||||||
try:
|
try:
|
||||||
future = asyncio.run_coroutine_threadsafe(
|
future = asyncio.run_coroutine_threadsafe(
|
||||||
self._pulse_tick_async(),
|
self._pulse_tick_async(),
|
||||||
@@ -970,12 +959,10 @@ class PulseController:
|
|||||||
self._ddp.set_status(status)
|
self._ddp.set_status(status)
|
||||||
self._last_sent_phase = self._phase
|
self._last_sent_phase = self._phase
|
||||||
self._increment_telemetry()
|
self._increment_telemetry()
|
||||||
self._record_success()
|
|
||||||
logger.debug("[pulse] _pulse_tick DDP set_status OK: %s", status)
|
logger.debug("[pulse] _pulse_tick DDP set_status OK: %s", status)
|
||||||
return
|
return
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.info("[pulse] _pulse_tick DDP set_status failed: %s", e)
|
logger.info("[pulse] _pulse_tick DDP set_status failed: %s", e)
|
||||||
self._record_failure()
|
|
||||||
|
|
||||||
# REST fallback for message text
|
# REST fallback for message text
|
||||||
if self._rest is not None and getattr(self._rest, 'auth_token', None):
|
if self._rest is not None and getattr(self._rest, 'auth_token', None):
|
||||||
@@ -993,11 +980,9 @@ class PulseController:
|
|||||||
)
|
)
|
||||||
self._last_sent_phase = self._phase
|
self._last_sent_phase = self._phase
|
||||||
self._increment_telemetry()
|
self._increment_telemetry()
|
||||||
self._record_success()
|
|
||||||
logger.debug("[pulse] _pulse_tick REST setStatus OK: %s", status)
|
logger.debug("[pulse] _pulse_tick REST setStatus OK: %s", status)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.info("[pulse] _pulse_tick REST setStatus failed: %s", e)
|
logger.info("[pulse] _pulse_tick REST setStatus failed: %s", e)
|
||||||
self._record_failure()
|
|
||||||
else:
|
else:
|
||||||
logger.debug(
|
logger.debug(
|
||||||
"[pulse] _pulse_tick skip: no DDP and no REST available (ddp=%s, rest=%s)",
|
"[pulse] _pulse_tick skip: no DDP and no REST available (ddp=%s, rest=%s)",
|
||||||
@@ -1022,7 +1007,6 @@ class PulseController:
|
|||||||
await self._ddp.set_status_async(status, timeout=self._await_timeout)
|
await self._ddp.set_status_async(status, timeout=self._await_timeout)
|
||||||
self._last_sent_phase = self._phase
|
self._last_sent_phase = self._phase
|
||||||
self._increment_telemetry()
|
self._increment_telemetry()
|
||||||
self._record_success()
|
|
||||||
logger.debug("[pulse] _pulse_tick_async DDP set_status_async OK: %s", status)
|
logger.debug("[pulse] _pulse_tick_async DDP set_status_async OK: %s", status)
|
||||||
return
|
return
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@@ -1031,7 +1015,6 @@ class PulseController:
|
|||||||
"falling back to REST",
|
"falling back to REST",
|
||||||
e,
|
e,
|
||||||
)
|
)
|
||||||
self._record_failure()
|
|
||||||
|
|
||||||
# REST fallback for message text
|
# REST fallback for message text
|
||||||
if self._rest is not None and getattr(self._rest, 'auth_token', None):
|
if self._rest is not None and getattr(self._rest, 'auth_token', None):
|
||||||
@@ -1049,47 +1032,14 @@ class PulseController:
|
|||||||
)
|
)
|
||||||
self._last_sent_phase = self._phase
|
self._last_sent_phase = self._phase
|
||||||
self._increment_telemetry()
|
self._increment_telemetry()
|
||||||
self._record_success()
|
|
||||||
logger.debug("[pulse] _pulse_tick_async REST setStatus OK: %s", status)
|
logger.debug("[pulse] _pulse_tick_async REST setStatus OK: %s", status)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.info("[pulse] _pulse_tick_async REST setStatus failed: %s", e)
|
logger.info("[pulse] _pulse_tick_async REST setStatus failed: %s", e)
|
||||||
self._record_failure()
|
|
||||||
else:
|
else:
|
||||||
logger.debug(
|
logger.debug(
|
||||||
"[pulse] _pulse_tick_async skip: no DDP and no REST available",
|
"[pulse] _pulse_tick_async skip: no DDP and no REST available",
|
||||||
)
|
)
|
||||||
|
|
||||||
def _record_failure(self) -> None:
|
|
||||||
"""P0-CRITICAL: Zweistufiger Circuit-Breaker.
|
|
||||||
|
|
||||||
Stufe 1: ab 2 consecutive_failures → _current_interval = 10.0s
|
|
||||||
Stufe 2: ab 4 consecutive_failures → _current_interval = 30.0s
|
|
||||||
Bei Erfolg (_record_success) wird zurückgesetzt.
|
|
||||||
"""
|
|
||||||
self._consecutive_failures += 1
|
|
||||||
if self._consecutive_failures >= 4:
|
|
||||||
self._current_interval = 30.0
|
|
||||||
logger.warning(
|
|
||||||
"[pulse] Circuit-Breaker Stufe 2: interval=30.0s (failures=%d)",
|
|
||||||
self._consecutive_failures,
|
|
||||||
)
|
|
||||||
elif self._consecutive_failures >= 2:
|
|
||||||
self._current_interval = 10.0
|
|
||||||
logger.warning(
|
|
||||||
"[pulse] Circuit-Breaker Stufe 1: interval=10.0s (failures=%d)",
|
|
||||||
self._consecutive_failures,
|
|
||||||
)
|
|
||||||
|
|
||||||
def _record_success(self) -> None:
|
|
||||||
"""Reset circuit breaker on successful pulse."""
|
|
||||||
if self._consecutive_failures > 0:
|
|
||||||
logger.info(
|
|
||||||
"[pulse] Circuit-Breaker reset: failures=%d → 0, interval restored",
|
|
||||||
self._consecutive_failures,
|
|
||||||
)
|
|
||||||
self._consecutive_failures = 0
|
|
||||||
self._current_interval = None
|
|
||||||
|
|
||||||
def _increment_telemetry(self) -> None:
|
def _increment_telemetry(self) -> None:
|
||||||
"""Increment the heartbeat_pulse telemetry counter.
|
"""Increment the heartbeat_pulse telemetry counter.
|
||||||
|
|
||||||
|
|||||||
+24
-53
@@ -1578,17 +1578,8 @@ class BidirectionalRouter:
|
|||||||
|
|
||||||
# Try LLM — expects room ID directly or "STAY"
|
# Try LLM — expects room ID directly or "STAY"
|
||||||
# Semaphore schützt vor parallelen Ollama-Aufrufen (qwen2.5:7b = single-request)
|
# Semaphore schützt vor parallelen Ollama-Aufrufen (qwen2.5:7b = single-request)
|
||||||
# P0-CRITICAL: Semaphore-Acquire mit 18s Timeout — muss KLEINER sein als
|
async with self._llm_semaphore:
|
||||||
# der äußere 20s-Timeout in adapter.py.
|
|
||||||
try:
|
|
||||||
await asyncio.wait_for(self._llm_semaphore.acquire(), timeout=18.0)
|
|
||||||
except asyncio.TimeoutError:
|
|
||||||
logger.warning("LLM semaphore acquire timed out (18s) — skipping LLM room lookup")
|
|
||||||
return None, False, True # LLM-Aufruf fehlgeschlagen
|
|
||||||
try:
|
|
||||||
llm_result = await self._classifier._llm_raw(prompt)
|
llm_result = await self._classifier._llm_raw(prompt)
|
||||||
finally:
|
|
||||||
self._llm_semaphore.release()
|
|
||||||
if llm_result is None:
|
if llm_result is None:
|
||||||
return None, False, True # LLM-Aufruf fehlgeschlagen
|
return None, False, True # LLM-Aufruf fehlgeschlagen
|
||||||
|
|
||||||
@@ -1848,28 +1839,19 @@ class BidirectionalRouter:
|
|||||||
old_topic=old_topic or "(kein altes Thema)",
|
old_topic=old_topic or "(kein altes Thema)",
|
||||||
)
|
)
|
||||||
|
|
||||||
# LLM-Aufruf mit 18s Semaphore + 15s LLM-Call Timeout
|
# LLM-Aufruf mit 5s Timeout
|
||||||
# P0-CRITICAL: Semaphore-Acquire mit 18s Timeout — muss KLEINER sein als
|
|
||||||
# der äußere 20s-Timeout in adapter.py.
|
|
||||||
try:
|
try:
|
||||||
await asyncio.wait_for(self._llm_semaphore.acquire(), timeout=18.0)
|
async with self._llm_semaphore:
|
||||||
except asyncio.TimeoutError:
|
|
||||||
logger.warning("V7-4: LLM-Semaphore Timeout (18s) → Fallback: NEU")
|
|
||||||
return None
|
|
||||||
try:
|
|
||||||
try:
|
|
||||||
llm_result = await asyncio.wait_for(
|
llm_result = await asyncio.wait_for(
|
||||||
self._classifier._llm_raw(prompt),
|
self._classifier._llm_raw(prompt),
|
||||||
timeout=15.0,
|
timeout=5.0,
|
||||||
)
|
)
|
||||||
except asyncio.TimeoutError:
|
except asyncio.TimeoutError:
|
||||||
logger.warning("V7-4: LLM-Check Timeout (15s) → Fallback: NEU")
|
logger.warning("V7-4: LLM-Check Timeout (5s) → Fallback: NEU")
|
||||||
return None
|
return None
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.warning("V7-4: LLM-Check fehlgeschlagen: %s → Fallback: NEU", e)
|
logger.warning("V7-4: LLM-Check fehlgeschlagen: %s → Fallback: NEU", e)
|
||||||
return None
|
return None
|
||||||
finally:
|
|
||||||
self._llm_semaphore.release()
|
|
||||||
|
|
||||||
if llm_result is None:
|
if llm_result is None:
|
||||||
logger.warning("V7-4: LLM-Check returned None → Fallback: NEU")
|
logger.warning("V7-4: LLM-Check returned None → Fallback: NEU")
|
||||||
@@ -2207,35 +2189,24 @@ async def validate_sentence_marker(
|
|||||||
v7_3_state=v7_3_state,
|
v7_3_state=v7_3_state,
|
||||||
)
|
)
|
||||||
|
|
||||||
# ── LLM-Aufruf mit 18s Semaphore + 15s LLM-Call Timeout ──────────
|
# ── LLM-Aufruf mit 5s Timeout ─────────────────────────────────────
|
||||||
# P0-CRITICAL: Semaphore-Acquire mit 18s Timeout — muss KLEINER sein als
|
|
||||||
# der äußere 20s-Timeout in adapter.py.
|
|
||||||
try:
|
try:
|
||||||
await asyncio.wait_for(llm_semaphore.acquire(), timeout=18.0)
|
async with llm_semaphore:
|
||||||
except asyncio.TimeoutError:
|
|
||||||
logger.warning(
|
|
||||||
"A1b Stufe 4/5: LLM-Semaphore Timeout (18s) → Fallback: unentscheidbar"
|
|
||||||
)
|
|
||||||
return None
|
|
||||||
try:
|
|
||||||
try:
|
|
||||||
llm_result = await asyncio.wait_for(
|
llm_result = await asyncio.wait_for(
|
||||||
classifier._llm_raw(prompt),
|
classifier._llm_raw(prompt),
|
||||||
timeout=15.0,
|
timeout=5.0,
|
||||||
)
|
)
|
||||||
except asyncio.TimeoutError:
|
except asyncio.TimeoutError:
|
||||||
logger.warning(
|
logger.warning(
|
||||||
"A1b Stufe 4/5: LLM-Call Timeout (15s) → Fallback: unentscheidbar"
|
"A1b Stufe 4/5: LLM-Validierung Timeout (5s) → Fallback: unentscheidbar"
|
||||||
)
|
)
|
||||||
return None
|
return None
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.warning(
|
logger.warning(
|
||||||
"A1b Stufe 4/5: LLM-Validierung fehlgeschlagen: %s → Fallback: unentscheidbar",
|
"A1b Stufe 4/5: LLM-Validierung fehlgeschlagen: %s → Fallback: unentscheidbar",
|
||||||
e,
|
e,
|
||||||
)
|
)
|
||||||
return None
|
return None
|
||||||
finally:
|
|
||||||
llm_semaphore.release()
|
|
||||||
|
|
||||||
if llm_result is None:
|
if llm_result is None:
|
||||||
logger.warning("A1b Stufe 4/5: LLM returned None → Fallback: unentscheidbar")
|
logger.warning("A1b Stufe 4/5: LLM returned None → Fallback: unentscheidbar")
|
||||||
|
|||||||
@@ -1,779 +0,0 @@
|
|||||||
"""
|
|
||||||
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)
|
|
||||||
|
|
||||||
def test_cross_contamination_real_world(self):
|
|
||||||
"""F6: Raumbezogener Lookup verhindert Cross-Contamination.
|
|
||||||
|
|
||||||
Real-World-Szenario:
|
|
||||||
- Andreas schreibt in Raum A → TopicRing add(A)
|
|
||||||
- Andreas schreibt in Raum B → TopicRing add(B)
|
|
||||||
- Agent antwortet in Raum A → get_active_topic(A) → MUSS A liefern, nicht B
|
|
||||||
- Agent antwortet in Raum B → get_active_topic(B) → MUSS B liefern, nicht A
|
|
||||||
|
|
||||||
Der user-weite Lookup get_active_topic_for_chat() würde B liefern
|
|
||||||
(neuester Eintrag), was Cross-Contamination wäre. Der raumbezogene
|
|
||||||
Lookup get_active_topic(room_id) liefert den korrekten Raum-Topic.
|
|
||||||
"""
|
|
||||||
# Andreas schreibt in Raum A (RC-Plugin)
|
|
||||||
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 (LAN-Doku) — neuerer Eintrag
|
|
||||||
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 user-weite Lookup würde Cross-Contamination verursachen ──
|
|
||||||
# get_active_topic_for_chat() sucht user-weit den neuesten Eintrag
|
|
||||||
# → liefert room_lan (neuer), NICHT room_rc
|
|
||||||
user_wide = self.ring.get_active_topic_for_chat("user:andreas")
|
|
||||||
self.assertEqual(user_wide, "room_lan",
|
|
||||||
"User-weiter Lookup liefert neuesten Topic (room_lan) — "
|
|
||||||
"das ist das Cross-Contamination-Problem")
|
|
||||||
|
|
||||||
# ── Der raumbezogene Lookup löst das Problem ──
|
|
||||||
# Agent antwortet in Raum A → get_active_topic("room_rc")
|
|
||||||
rc_topic = self.ring.get_active_topic("room_rc")
|
|
||||||
self.assertIsNotNone(rc_topic,
|
|
||||||
"Raum A muss einen aktiven Topic haben")
|
|
||||||
self.assertEqual(rc_topic.topic, "RC-Plugin Deployment",
|
|
||||||
"Antwort in Raum A muss Topic von A liefern, nicht von B")
|
|
||||||
self.assertEqual(rc_topic.origin_room, "room_rc",
|
|
||||||
"origin_room muss room_rc sein, nicht room_lan")
|
|
||||||
|
|
||||||
# Agent antwortet in Raum B → get_active_topic("room_lan")
|
|
||||||
lan_topic = self.ring.get_active_topic("room_lan")
|
|
||||||
self.assertIsNotNone(lan_topic,
|
|
||||||
"Raum B muss einen aktiven Topic haben")
|
|
||||||
self.assertEqual(lan_topic.topic, "Netzwerk-Dokumentation",
|
|
||||||
"Antwort in Raum B muss Topic von B liefern, nicht von A")
|
|
||||||
self.assertEqual(lan_topic.origin_room, "room_lan",
|
|
||||||
"origin_room muss room_lan sein, nicht room_rc")
|
|
||||||
|
|
||||||
# ── Beide Topics sind unterschiedlich — keine Cross-Contamination ──
|
|
||||||
self.assertNotEqual(rc_topic.topic, lan_topic.topic,
|
|
||||||
"Topics in Raum A und B müssen unterschiedlich sein")
|
|
||||||
self.assertNotEqual(rc_topic.origin_room, lan_topic.origin_room,
|
|
||||||
"origin_rooms müssen unterschiedlich sein")
|
|
||||||
|
|
||||||
|
|
||||||
# ── 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()
|
|
||||||
@@ -1,529 +0,0 @@
|
|||||||
"""
|
|
||||||
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 (Reads greifen auf einen zwischengespeicherten
|
|
||||||
Deep-Copy zu, der nur nach Writes invalidiert und beim nächsten Read
|
|
||||||
neu aufgebaut wird — dadurch nie inkonsistent, aber nicht zwingend aktuell).
|
|
||||||
|
|
||||||
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.
|
|
||||||
|
|
||||||
Snapshot spiegelt den Stand zum Zeitpunkt der letzten Schreib-Invalidation.
|
|
||||||
Lock-free Reads sind konsistent zu diesem Zeitpunkt, NICHT zwingend aktuell.
|
|
||||||
Erst beim nächsten Write wird der Snapshot invalidiert und beim nächsten
|
|
||||||
Read neu aufgebaut.
|
|
||||||
|
|
||||||
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.
|
|
||||||
|
|
||||||
Setzt _read_snapshot auf None und _dirty auf True. Der nächste
|
|
||||||
Read-Aufruf von _get_snapshot() baut dann einen neuen Snapshot
|
|
||||||
via Deep-Copy auf. Dadurch sind Reads immer konsistent zum Stand
|
|
||||||
des letzten Writes — nicht zwingend aktuell, aber nie inkonsistent.
|
|
||||||
"""
|
|
||||||
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()
|
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
# Rocket.Chat Live Integration Tests
|
||||||
|
|
||||||
|
REST-basierte Live-Tests für das Hermes Rocket.Chat Plugin.
|
||||||
|
Die Tests laufen gegen eine laufende Bot-Instanz (.45 MyTestBot)
|
||||||
|
und verifizieren End-to-End-Flows via REST API.
|
||||||
|
|
||||||
|
## Voraussetzungen
|
||||||
|
|
||||||
|
1. **Bot läuft auf .45** — MyTestBot muss gestartet und mit Rocket.Chat
|
||||||
|
verbunden sein (DDP/WebSocket aktiv).
|
||||||
|
|
||||||
|
2. **Bot ist in allen Test-Räumen subscribed** — der Bot muss Member
|
||||||
|
der folgenden Räume sein:
|
||||||
|
- `rc-test-automated` (Haupt-Testraum)
|
||||||
|
- `test-rc-source` (Move-Request Source)
|
||||||
|
- `test-rc-target` (Move-Request Target)
|
||||||
|
- Projektraum für Multi-Room-Test (z.B. `#Rocketchat-Plugin`)
|
||||||
|
|
||||||
|
3. **room-map.json ist korrekt** — die Raum-Map unter
|
||||||
|
`~/.hermes/hermes-agent/data/room-map.json` muss die Test-Räume
|
||||||
|
enthalten, damit der Archivar Keywords matchen kann.
|
||||||
|
|
||||||
|
4. **REST API Token** — ein gültiger Personal Access Token für den
|
||||||
|
User `bernd` mit `x-auth-token` und `x-user-id`.
|
||||||
|
|
||||||
|
## ENV-Variablen
|
||||||
|
|
||||||
|
Alle Variablen müssen gesetzt sein, sonst werden alle Tests beim
|
||||||
|
Collection-Time geskippt (kein Fehler, kein Abbruch).
|
||||||
|
|
||||||
|
### Pflicht (für alle Tests)
|
||||||
|
|
||||||
|
| Variable | Beschreibung | Beispiel |
|
||||||
|
|---|---|---|
|
||||||
|
| `RC_LIVE_URL` | Rocket.Chat Server URL | `https://rc.bernd.lan` |
|
||||||
|
| `RC_LIVE_TOKEN` | Personal Access Token (X-Auth-Token) | `abc123...` |
|
||||||
|
| `RC_LIVE_USER_ID` | User ID (X-User-Id) | `6a68c21ddee04395ed6f5415` |
|
||||||
|
| `RC_LIVE_TEST_ROOM` | Haupt-Testraum ID | `6a684ef3dee04395ed6f4f7c` |
|
||||||
|
| `RC_LIVE_BOT_USERNAME` | Bot Username | `mytestbot` |
|
||||||
|
| `RC_LIVE_BOT_USER_ID` | Bot User ID | `6a68c21ddee04395ed6f5416` |
|
||||||
|
|
||||||
|
### Optional (für spezifische Tests)
|
||||||
|
|
||||||
|
| Variable | Test | Beschreibung | Beispiel |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `RC_LIVE_SOURCE_ROOM` | test_03 | Move-Request Source-Raum | `6a68c21ddee04395ed6f5415` |
|
||||||
|
| `RC_LIVE_TARGET_ROOM` | test_03 | Move-Request Target-Raum | `6a68c21ddee04395ed6f5419` |
|
||||||
|
| `RC_LIVE_PROJECT_ROOM` | test_04 | Projektraum für Multi-Room | `6a19b0ff02aeecd36b1aa16c` |
|
||||||
|
|
||||||
|
Fehlt eine optionale Variable, wird der entsprechende Test mit
|
||||||
|
`pytest.skip()` übersprungen.
|
||||||
|
|
||||||
|
## Ausführung
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Alle live_rc Tests
|
||||||
|
pytest tests/live_rc/ -m live_rc -v
|
||||||
|
|
||||||
|
# Einzelner Test
|
||||||
|
pytest tests/live_rc/test_01_echo.py -m live_rc -v
|
||||||
|
|
||||||
|
# Mit Debug-Logging
|
||||||
|
pytest tests/live_rc/ -m live_rc -v --log-cli-level=DEBUG
|
||||||
|
|
||||||
|
# Ohne Capturing (für Live-Debugging)
|
||||||
|
pytest tests/live_rc/ -m live_rc -v -s
|
||||||
|
```
|
||||||
|
|
||||||
|
## Test-Übersicht
|
||||||
|
|
||||||
|
| Test | Name | Status | Beschreibung |
|
||||||
|
|---|---|---|---|
|
||||||
|
| test_01 | Echo / Smoke | ✅ PASSED | Bot antwortet auf einfache Nachricht |
|
||||||
|
| test_02 | Button-Klick | ✅ PASSED | ::-Text wird als Button-Klick erkannt |
|
||||||
|
| test_03 | Move-Request | 🆕 Implementiert | Keyword → Move-Request → Zielraum |
|
||||||
|
| test_04 | Multi-Room | 🆕 Implementiert | DM-Proxy → Archivar → Projektraum |
|
||||||
|
| test_05 | Stream-Retry | ⏳ TODO | Antwort nach Stream-Abbruch |
|
||||||
|
| test_06 | Themenring | ⏳ TODO | Gleichzeitige Themen in verschiedenen Räumen |
|
||||||
|
|
||||||
|
## Rate-Limiting
|
||||||
|
|
||||||
|
Der Test-Harness verwendet einen Token-Bucket Rate-Limiter mit
|
||||||
|
**30 Calls/Minute** (angepasst von 60, da RC bereits bei 3-4
|
||||||
|
channels.history-Calls in <10s mit HTTP 429 antwortet).
|
||||||
|
|
||||||
|
Polling-Intervalle: 2s → 3s → 5s → 8s (max 18s total).
|
||||||
|
|
||||||
|
Bei 3 aufeinanderfolgenden HTTP 429 wird der Test mit SKIP
|
||||||
|
abgebrochen (statt ewig zu retryen).
|
||||||
|
|
||||||
|
Cursor-Caching: Nach dem ersten channels.history-Call werden
|
||||||
|
gefundene Nachrichten gecached — weitere Polls scannen nur den
|
||||||
|
Cache ohne erneuten API-Call.
|
||||||
|
|
||||||
|
## Suite Lock
|
||||||
|
|
||||||
|
Nur ein Test-Run gleichzeitig — `/tmp/rc-live-tests.lock` verhindert
|
||||||
|
parallele Ausführung. Bei hängendem Lock: `rm /tmp/rc-live-tests.lock`.
|
||||||
|
|
||||||
|
## Cleanup
|
||||||
|
|
||||||
|
Alle im Test geposteten Nachrichten werden nach dem Test (auch bei
|
||||||
|
Fehlern) automatisch gelöscht. Bot-Antworten werden ebenfalls getrackt
|
||||||
|
und gelöscht.
|
||||||
|
|
||||||
|
## Architektur
|
||||||
|
|
||||||
|
```
|
||||||
|
tests/live_rc/
|
||||||
|
├── conftest.py # Fixtures, Rate-Limiter, Suite Lock, Skip-Logik
|
||||||
|
├── helpers/
|
||||||
|
│ ├── __init__.py
|
||||||
|
│ ├── rc_rest.py # RCRestClient — REST API Wrapper (stdlib only)
|
||||||
|
│ └── polling.py # wait_for_bot_message, get_latest_timestamp
|
||||||
|
├── test_01_echo.py # Echo / Smoke Test
|
||||||
|
├── test_02_button_click.py # ::-Text Button-Klick Simulation
|
||||||
|
├── test_03_move_request.py # Move-Request Flow
|
||||||
|
├── test_04_multi_room.py # Multi-Room DM-Proxy → Projektraum
|
||||||
|
├── test_05_stream_retry.py # Stream-Retry (TODO)
|
||||||
|
├── test_06_concurrent.py # Themenring (TODO)
|
||||||
|
└── README.md # Diese Datei
|
||||||
|
```
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
"""Live RC test package."""
|
||||||
@@ -0,0 +1,438 @@
|
|||||||
|
"""
|
||||||
|
Pytest configuration for Rocket.Chat live tests.
|
||||||
|
|
||||||
|
Fixtures, markers, skip logic, self-check, rate limiter, suite lock,
|
||||||
|
and cleanup for the REST-based test harness running on .101.
|
||||||
|
|
||||||
|
Usage:
|
||||||
|
pytest tests/live_rc/ -m live_rc -v
|
||||||
|
|
||||||
|
Without RC_LIVE_URL set: all tests are skipped cleanly (no errors)
|
||||||
|
at collection time via pytest_collection_modifyitems.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import fcntl
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Generator
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
# Ensure helpers are importable
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
|
||||||
|
|
||||||
|
from tests.live_rc.helpers.rc_rest import RCRestClient, RCRestError
|
||||||
|
from tests.live_rc.helpers.polling import get_latest_timestamp, RateLimitSkip
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
# Pytest marker registration
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
|
||||||
|
def pytest_configure(config):
|
||||||
|
config.addinivalue_line(
|
||||||
|
"markers",
|
||||||
|
"live_rc: Rocket.Chat live integration test (requires running .45 bot)",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
# Env-var check — skip entire suite at collection time if not configured
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
|
||||||
|
def _env_required(name: str) -> str:
|
||||||
|
"""Get a required env var. Returns empty string if not set."""
|
||||||
|
return (os.getenv(name) or "").strip()
|
||||||
|
|
||||||
|
|
||||||
|
def _is_live_configured() -> bool:
|
||||||
|
"""Check if all required env vars are set."""
|
||||||
|
required = [
|
||||||
|
"RC_LIVE_URL",
|
||||||
|
"RC_LIVE_TOKEN",
|
||||||
|
"RC_LIVE_USER_ID",
|
||||||
|
"RC_LIVE_TEST_ROOM",
|
||||||
|
"RC_LIVE_BOT_USERNAME",
|
||||||
|
"RC_LIVE_BOT_USER_ID",
|
||||||
|
]
|
||||||
|
return all(_env_required(v) for v in required)
|
||||||
|
|
||||||
|
|
||||||
|
def pytest_collection_modifyitems(config, items):
|
||||||
|
"""Skip all live_rc tests at collection time if RC_LIVE_URL is not set.
|
||||||
|
|
||||||
|
This is the earliest possible skip point — before any fixtures are
|
||||||
|
instantiated, before any imports are resolved. Tests that would
|
||||||
|
otherwise fail due to missing env vars are cleanly skipped.
|
||||||
|
"""
|
||||||
|
if not _is_live_configured():
|
||||||
|
skip_reason = (
|
||||||
|
"RC_LIVE_URL not set — skipping all live RC tests. "
|
||||||
|
"Set RC_LIVE_URL, RC_LIVE_TOKEN, RC_LIVE_USER_ID, "
|
||||||
|
"RC_LIVE_TEST_ROOM, RC_LIVE_BOT_USERNAME, RC_LIVE_BOT_USER_ID "
|
||||||
|
"to run live tests."
|
||||||
|
)
|
||||||
|
for item in items:
|
||||||
|
if item.get_closest_marker("live_rc"):
|
||||||
|
item.add_marker(pytest.mark.skip(reason=skip_reason))
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
# Token-Bucket Rate Limiter (max 30 calls/minute)
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
|
||||||
|
class RateLimiter:
|
||||||
|
"""Simple token-bucket rate limiter.
|
||||||
|
|
||||||
|
Allows max_tokens calls per window_seconds. Thread-safe via lock.
|
||||||
|
Default: 30 calls/minute (was 60 — RC triggers 429 at 3-4 calls in <10s).
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, max_tokens: int = 30, window_seconds: float = 60.0):
|
||||||
|
self.max_tokens = max_tokens
|
||||||
|
self.window_seconds = window_seconds
|
||||||
|
self.tokens = float(max_tokens)
|
||||||
|
self.last_refill = time.monotonic()
|
||||||
|
self._lock = __import__("threading").Lock()
|
||||||
|
|
||||||
|
def acquire(self) -> None:
|
||||||
|
"""Block until a token is available."""
|
||||||
|
import threading
|
||||||
|
with self._lock:
|
||||||
|
now = time.monotonic()
|
||||||
|
elapsed = now - self.last_refill
|
||||||
|
# Refill tokens proportionally
|
||||||
|
self.tokens = min(
|
||||||
|
self.max_tokens,
|
||||||
|
self.tokens + elapsed * (self.max_tokens / self.window_seconds),
|
||||||
|
)
|
||||||
|
self.last_refill = now
|
||||||
|
|
||||||
|
if self.tokens >= 1.0:
|
||||||
|
self.tokens -= 1.0
|
||||||
|
return
|
||||||
|
|
||||||
|
# Need to wait for a token
|
||||||
|
wait_time = (1.0 - self.tokens) * (self.window_seconds / self.max_tokens)
|
||||||
|
self.tokens = 0.0
|
||||||
|
|
||||||
|
time.sleep(wait_time)
|
||||||
|
# Re-acquire after waiting
|
||||||
|
with self._lock:
|
||||||
|
self.tokens = max(0.0, self.tokens - 1.0)
|
||||||
|
|
||||||
|
|
||||||
|
# Global rate limiter instance (created once per process)
|
||||||
|
_rate_limiter: RateLimiter | None = None
|
||||||
|
|
||||||
|
|
||||||
|
def _get_rate_limiter() -> RateLimiter:
|
||||||
|
global _rate_limiter
|
||||||
|
if _rate_limiter is None:
|
||||||
|
_rate_limiter = RateLimiter(max_tokens=30, window_seconds=60.0)
|
||||||
|
return _rate_limiter
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
# Suite Lock — only one parallel run
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
_LOCK_PATH = "/tmp/rc-live-tests.lock"
|
||||||
|
_lock_fd = None
|
||||||
|
|
||||||
|
|
||||||
|
def _acquire_suite_lock() -> bool:
|
||||||
|
"""Try to acquire the suite lock. Returns True on success."""
|
||||||
|
global _lock_fd
|
||||||
|
try:
|
||||||
|
_lock_fd = open(_LOCK_PATH, "w")
|
||||||
|
fcntl.flock(_lock_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||||
|
_lock_fd.write(f"pid={os.getpid()}\ntime={time.time()}\n")
|
||||||
|
_lock_fd.flush()
|
||||||
|
return True
|
||||||
|
except (IOError, OSError):
|
||||||
|
if _lock_fd:
|
||||||
|
_lock_fd.close()
|
||||||
|
_lock_fd = None
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def _release_suite_lock() -> None:
|
||||||
|
"""Release the suite lock."""
|
||||||
|
global _lock_fd
|
||||||
|
if _lock_fd:
|
||||||
|
try:
|
||||||
|
fcntl.flock(_lock_fd, fcntl.LOCK_UN)
|
||||||
|
_lock_fd.close()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
finally:
|
||||||
|
_lock_fd = None
|
||||||
|
try:
|
||||||
|
os.unlink(_LOCK_PATH)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
# Fixtures
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(scope="session")
|
||||||
|
def rc_config() -> dict:
|
||||||
|
"""Provide the RC live test configuration from env vars.
|
||||||
|
|
||||||
|
Skips the entire session if RC_LIVE_URL is not set.
|
||||||
|
(Redundant with pytest_collection_modifyitems, but kept as safety net.)
|
||||||
|
"""
|
||||||
|
if not _is_live_configured():
|
||||||
|
pytest.skip("RC_LIVE_URL not set — skipping live RC tests")
|
||||||
|
|
||||||
|
# Acquire suite lock
|
||||||
|
if not _acquire_suite_lock():
|
||||||
|
pytest.fail(
|
||||||
|
"Could not acquire suite lock at /tmp/rc-live-tests.lock — "
|
||||||
|
"another test run may be in progress. Remove the lock file "
|
||||||
|
"if you're sure no other run is active."
|
||||||
|
)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"url": _env_required("RC_LIVE_URL"),
|
||||||
|
"token": _env_required("RC_LIVE_TOKEN"),
|
||||||
|
"user_id": _env_required("RC_LIVE_USER_ID"),
|
||||||
|
"test_room": _env_required("RC_LIVE_TEST_ROOM"),
|
||||||
|
"bot_username": _env_required("RC_LIVE_BOT_USERNAME"),
|
||||||
|
"bot_user_id": _env_required("RC_LIVE_BOT_USER_ID"),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(scope="session")
|
||||||
|
def rc_client(rc_config: dict, rate_limiter) -> RCRestClient:
|
||||||
|
"""Create an authenticated RCRestClient for the test session.
|
||||||
|
|
||||||
|
Performs self-check: verifies that the token matches the user identity.
|
||||||
|
The rate_limiter is injected into the client so every API call
|
||||||
|
(post, history, delete, users.info) is rate-limited automatically.
|
||||||
|
"""
|
||||||
|
client = RCRestClient(
|
||||||
|
base_url=rc_config["url"],
|
||||||
|
auth_token=rc_config["token"],
|
||||||
|
user_id=rc_config["user_id"],
|
||||||
|
rate_limiter=rate_limiter,
|
||||||
|
)
|
||||||
|
|
||||||
|
# P0: Self-check — verify token matches user identity
|
||||||
|
try:
|
||||||
|
result = client.self_check()
|
||||||
|
logger.info(
|
||||||
|
"Self-check OK: user=%s, id=%s",
|
||||||
|
result["username"],
|
||||||
|
result["user_id"][:12],
|
||||||
|
)
|
||||||
|
except RCRestError as e:
|
||||||
|
pytest.fail(f"Self-check FAILED: {e}")
|
||||||
|
|
||||||
|
return client
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(scope="session", autouse=True)
|
||||||
|
def _suite_cleanup(request, rc_config: dict):
|
||||||
|
"""Session-scoped cleanup: release suite lock on teardown."""
|
||||||
|
yield
|
||||||
|
_release_suite_lock()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(autouse=True)
|
||||||
|
def rate_limit_cooldown():
|
||||||
|
"""Wait 20s between tests for RC rate-limit window reset.
|
||||||
|
|
||||||
|
RC's rate-limit window is ~10s. A 20s pause between tests ensures
|
||||||
|
the token bucket has time to refill, preventing cascading 429s
|
||||||
|
when tests run back-to-back. Increased from 15s — test_03 makes
|
||||||
|
more API calls and needs extra headroom.
|
||||||
|
"""
|
||||||
|
yield
|
||||||
|
time.sleep(20)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def test_room_id(rc_config: dict) -> str:
|
||||||
|
"""The test room ID for the current test."""
|
||||||
|
return rc_config["test_room"]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def bot_username(rc_config: dict) -> str:
|
||||||
|
"""The bot's username."""
|
||||||
|
return rc_config["bot_username"]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def bot_user_id(rc_config: dict) -> str:
|
||||||
|
"""The bot's user ID."""
|
||||||
|
return rc_config["bot_user_id"]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def bot_status_check(rc_client: RCRestClient, bot_user_id: str, bot_username: str):
|
||||||
|
"""Pre-condition: verify bot is in a state where it can respond.
|
||||||
|
|
||||||
|
Checks:
|
||||||
|
1. Bot user exists and is active
|
||||||
|
2. Bot statusText doesn't indicate blocking state (onboarding, etc.)
|
||||||
|
|
||||||
|
Returns the bot user info dict on success.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
user = rc_client.get_user_info(bot_username)
|
||||||
|
except Exception as e:
|
||||||
|
pytest.fail(
|
||||||
|
f"Bot user '{bot_username}' not found via REST API. "
|
||||||
|
f"Check that .45 MyTestBot is running. Error: {e}"
|
||||||
|
)
|
||||||
|
|
||||||
|
status_text = (user.get("statusText") or "").lower()
|
||||||
|
status = (user.get("status") or "").lower()
|
||||||
|
|
||||||
|
# Check for known blocking states
|
||||||
|
blocking_states = []
|
||||||
|
# NOTE: statusText='Onboarding läuft' is set by the plugin even when F8=COMPLETED.
|
||||||
|
# The F8 log line is the authoritative check, not the statusText.
|
||||||
|
# Only block if status is NOT online/away/busy (bot completely offline).
|
||||||
|
if status not in ("online", "away", "busy"):
|
||||||
|
blocking_states.append(f"status='{status}'")
|
||||||
|
|
||||||
|
if blocking_states:
|
||||||
|
pytest.skip(
|
||||||
|
f"Bot '{bot_username}' is not ready to respond: "
|
||||||
|
f"{'; '.join(blocking_states)}. "
|
||||||
|
f"Resolve the blocking state on .45 before running live tests."
|
||||||
|
)
|
||||||
|
|
||||||
|
logger.info(
|
||||||
|
"Bot status OK: username=%s, status=%s, statusText=%s",
|
||||||
|
bot_username, status, user.get("statusText", ""),
|
||||||
|
)
|
||||||
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(scope="session")
|
||||||
|
def rate_limiter() -> RateLimiter:
|
||||||
|
"""Rate limiter to stay under 30 calls/minute (session-scoped)."""
|
||||||
|
return _get_rate_limiter()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def cursor(rc_client: RCRestClient, test_room_id: str, rate_limiter: RateLimiter) -> str:
|
||||||
|
"""Get the latest message timestamp as a cursor.
|
||||||
|
|
||||||
|
All test messages posted after this cursor will be considered
|
||||||
|
for bot response detection.
|
||||||
|
"""
|
||||||
|
ts = get_latest_timestamp(rc_client, test_room_id, rate_limiter=rate_limiter)
|
||||||
|
logger.info("Cursor set to %s", ts[:19])
|
||||||
|
return ts
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def posted_message_ids() -> list:
|
||||||
|
"""Collector for message IDs posted during a test.
|
||||||
|
|
||||||
|
Cleanup fixture deletes all collected messages after the test.
|
||||||
|
"""
|
||||||
|
ids: list = []
|
||||||
|
return ids
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def cleanup_messages(
|
||||||
|
rc_client: RCRestClient,
|
||||||
|
test_room_id: str,
|
||||||
|
posted_message_ids: list,
|
||||||
|
):
|
||||||
|
"""Cleanup fixture: deletes all messages posted during the test.
|
||||||
|
|
||||||
|
Usage: append message IDs to posted_message_ids as you post them.
|
||||||
|
After the test (even on failure), all collected messages are deleted.
|
||||||
|
"""
|
||||||
|
yield
|
||||||
|
for msg_id in posted_message_ids:
|
||||||
|
try:
|
||||||
|
rc_client.delete_message(test_room_id, msg_id)
|
||||||
|
logger.debug("Cleanup: deleted message %s", msg_id[:12])
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning("Cleanup: failed to delete %s: %s", msg_id[:12], e)
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
# Helper: post a test message (rate-limited, tracked for cleanup)
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
|
||||||
|
def post_test_message(
|
||||||
|
client: RCRestClient,
|
||||||
|
room_id: str,
|
||||||
|
text: str,
|
||||||
|
posted_ids: list,
|
||||||
|
limiter: RateLimiter | None = None,
|
||||||
|
) -> tuple[str, str]:
|
||||||
|
"""Post a test message with cleanup tracking.
|
||||||
|
|
||||||
|
Rate limiting is handled by the RCRestClient internally (via _request).
|
||||||
|
The limiter parameter is kept for backward compatibility but is unused.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
client: Authenticated RCRestClient.
|
||||||
|
room_id: Target room ID.
|
||||||
|
text: Message text.
|
||||||
|
posted_ids: List to append the message ID to (for cleanup).
|
||||||
|
limiter: Deprecated — rate limiting is now in RCRestClient._request().
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
A tuple of (message_id, timestamp) from the API response.
|
||||||
|
"""
|
||||||
|
msg_id, ts = client.post_message(room_id, text)
|
||||||
|
posted_ids.append(msg_id)
|
||||||
|
return msg_id, ts
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
# Helper: assert message ownership
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
|
||||||
|
def assert_bot_message(
|
||||||
|
msg: dict,
|
||||||
|
expected_username: str,
|
||||||
|
context: str = "",
|
||||||
|
) -> None:
|
||||||
|
"""Assert that a message was sent by the expected bot user.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
msg: Message dict from channels.history.
|
||||||
|
expected_username: The bot's username (case-insensitive).
|
||||||
|
context: Description for assertion error messages.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
AssertionError: If the message is not from the expected user.
|
||||||
|
"""
|
||||||
|
u = msg.get("u", {})
|
||||||
|
actual_username = (u.get("username", "") or "").lower()
|
||||||
|
expected_lower = expected_username.lower()
|
||||||
|
ctx = f" ({context})" if context else ""
|
||||||
|
assert actual_username == expected_lower, (
|
||||||
|
f"Message ownership mismatch{ctx}: "
|
||||||
|
f"expected username='{expected_lower}', "
|
||||||
|
f"got username='{actual_username}'. "
|
||||||
|
f"Message text: {msg.get('msg', '')[:100]}"
|
||||||
|
)
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
"""Live RC test helpers."""
|
||||||
@@ -0,0 +1,217 @@
|
|||||||
|
"""
|
||||||
|
Cursor-based polling for bot responses in Rocket.Chat live tests.
|
||||||
|
|
||||||
|
Waits for a message from a specific user (the bot) to appear in a room's
|
||||||
|
history after a given cursor timestamp. Uses progressive backoff with
|
||||||
|
rate limiting: configurable initial interval -> 3s -> 5s -> 8s.
|
||||||
|
|
||||||
|
Rate limiter integration: each channels.history call acquires a token
|
||||||
|
from the rate limiter to stay under RC's 30 calls/minute limit.
|
||||||
|
|
||||||
|
CURSOR CACHING: Once messages are found, subsequent polls skip
|
||||||
|
channels.history and only scan the cached batch -- avoiding unnecessary
|
||||||
|
API calls that trigger RC's aggressive 429 rate limiting.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import time
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
from .rc_rest import RCRestClient
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
# Progressive backoff intervals in seconds (rate-limiter-friendly).
|
||||||
|
# Default: 2s -> 3s -> 5s -> 8s (max 18s total).
|
||||||
|
# Callers can override the first interval via initial_interval.
|
||||||
|
_DEFAULT_BACKOFF_INTERVALS = [2.0, 3.0, 5.0, 8.0]
|
||||||
|
_MAX_TOTAL_WAIT = 18.0 # seconds
|
||||||
|
|
||||||
|
# 429 exponential backoff: 3s -> 6s -> 12s -> 20s -> 30s (max)
|
||||||
|
_MAX_429_BACKOFF = 30.0
|
||||||
|
# After 5 consecutive 429s, abort with SKIP instead of retrying forever
|
||||||
|
_MAX_CONSECUTIVE_429 = 5
|
||||||
|
|
||||||
|
|
||||||
|
class PollTimeout(Exception):
|
||||||
|
"""Raised when the bot does not respond within the timeout."""
|
||||||
|
|
||||||
|
|
||||||
|
class RateLimitSkip(Exception):
|
||||||
|
"""Raised when 5 consecutive 429s occur -- test should SKIP."""
|
||||||
|
|
||||||
|
|
||||||
|
def wait_for_bot_message(
|
||||||
|
client: RCRestClient,
|
||||||
|
room_id: str,
|
||||||
|
bot_username: str,
|
||||||
|
cursor: str,
|
||||||
|
timeout: float = _MAX_TOTAL_WAIT,
|
||||||
|
rate_limiter=None,
|
||||||
|
initial_interval: float = 2.0,
|
||||||
|
) -> dict:
|
||||||
|
"""Poll channels.history until a message from bot_username appears.
|
||||||
|
|
||||||
|
Uses the cursor (ISO timestamp) to only look at messages newer than
|
||||||
|
the test message that was just posted.
|
||||||
|
|
||||||
|
Rate limiting is handled by RCRestClient._request() internally
|
||||||
|
(token-bucket + 429 retry with exponential backoff). The rate_limiter
|
||||||
|
parameter is kept for backward compatibility but is unused.
|
||||||
|
|
||||||
|
Cursor caching: once messages are fetched, subsequent polls scan
|
||||||
|
the cached batch without calling channels.history again -- avoids
|
||||||
|
triggering RC's aggressive rate limiting.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
client: Authenticated RCRestClient instance.
|
||||||
|
room_id: The room to poll.
|
||||||
|
bot_username: The bot's username (case-insensitive match).
|
||||||
|
cursor: ISO timestamp -- only messages after this time are considered.
|
||||||
|
timeout: Maximum total wait time in seconds (default 18s).
|
||||||
|
rate_limiter: Deprecated -- rate limiting is now in RCRestClient._request().
|
||||||
|
initial_interval: First polling interval in seconds (default 2.0).
|
||||||
|
Use 5.0-8.0 for rooms that are polled later in a test to reduce
|
||||||
|
API call density and avoid 429s.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
The first message dict from bot_username found after cursor.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
PollTimeout: If no bot message appears within timeout.
|
||||||
|
RateLimitSkip: If 5 consecutive 429s occur (test should SKIP).
|
||||||
|
"""
|
||||||
|
deadline = time.monotonic() + timeout
|
||||||
|
interval_idx = 0
|
||||||
|
consecutive_429 = 0
|
||||||
|
cached_messages: list = [] # Cursor caching: reuse fetched batch
|
||||||
|
|
||||||
|
# Build backoff intervals with caller's initial_interval
|
||||||
|
backoff_intervals = [initial_interval, 3.0, 5.0, 8.0]
|
||||||
|
|
||||||
|
while time.monotonic() < deadline:
|
||||||
|
# Cursor caching: if we already have messages, scan them first
|
||||||
|
if cached_messages:
|
||||||
|
for msg in cached_messages:
|
||||||
|
ts = msg.get("ts", "")
|
||||||
|
if ts <= cursor:
|
||||||
|
continue
|
||||||
|
u = msg.get("u", {})
|
||||||
|
username = (u.get("username", "") or "").lower()
|
||||||
|
if username == bot_username.lower():
|
||||||
|
logger.info(
|
||||||
|
"Poll: found bot message %s after %.1fs (cached)",
|
||||||
|
msg.get("_id", "")[:12],
|
||||||
|
time.monotonic() - (deadline - timeout),
|
||||||
|
)
|
||||||
|
return msg
|
||||||
|
# No match in cache -- clear and re-fetch on next iteration
|
||||||
|
cached_messages = []
|
||||||
|
|
||||||
|
# Rate limiting is handled by RCRestClient._request() internally
|
||||||
|
try:
|
||||||
|
# If cursor is epoch (1970-01-01), the room has never had messages.
|
||||||
|
# Don't pass oldest=1970 to RC — it may reject or return nothing.
|
||||||
|
# Instead, fetch without a time filter.
|
||||||
|
if cursor.startswith("1970-01-01"):
|
||||||
|
messages = client.get_history(
|
||||||
|
room_id=room_id,
|
||||||
|
count=10,
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
messages = client.get_history(
|
||||||
|
room_id=room_id,
|
||||||
|
count=10,
|
||||||
|
oldest=cursor,
|
||||||
|
)
|
||||||
|
consecutive_429 = 0 # reset on success
|
||||||
|
except Exception as e:
|
||||||
|
error_str = str(e)
|
||||||
|
if "429" in error_str:
|
||||||
|
consecutive_429 += 1
|
||||||
|
if consecutive_429 >= _MAX_CONSECUTIVE_429:
|
||||||
|
raise RateLimitSkip(
|
||||||
|
"5 consecutive HTTP 429s from RC -- rate limit is too "
|
||||||
|
"aggressive. Consider increasing poll intervals or "
|
||||||
|
"reducing concurrent test load."
|
||||||
|
)
|
||||||
|
# Exponential backoff on rate-limit errors: 3s -> 6s -> 12s -> 20s -> 30s
|
||||||
|
backoff = min(3.0 * (2 ** (consecutive_429 - 1)), _MAX_429_BACKOFF)
|
||||||
|
logger.warning(
|
||||||
|
"Poll: HTTP 429 (consecutive=%d/%d) -- backing off %ds",
|
||||||
|
consecutive_429, _MAX_CONSECUTIVE_429, backoff,
|
||||||
|
)
|
||||||
|
remaining = deadline - time.monotonic()
|
||||||
|
if remaining <= 0:
|
||||||
|
break
|
||||||
|
time.sleep(min(backoff, remaining))
|
||||||
|
continue
|
||||||
|
else:
|
||||||
|
logger.warning("Poll: history fetch failed (will retry): %s", e)
|
||||||
|
messages = []
|
||||||
|
|
||||||
|
# Cache messages for cursor-caching optimization
|
||||||
|
cached_messages = messages
|
||||||
|
|
||||||
|
for msg in messages:
|
||||||
|
ts = msg.get("ts", "")
|
||||||
|
# Only consider messages strictly after cursor
|
||||||
|
if ts <= cursor:
|
||||||
|
continue
|
||||||
|
u = msg.get("u", {})
|
||||||
|
username = (u.get("username", "") or "").lower()
|
||||||
|
if username == bot_username.lower():
|
||||||
|
logger.info(
|
||||||
|
"Poll: found bot message %s after %.1fs",
|
||||||
|
msg.get("_id", "")[:12],
|
||||||
|
time.monotonic() - (deadline - timeout),
|
||||||
|
)
|
||||||
|
return msg
|
||||||
|
|
||||||
|
# Progressive backoff: initial_interval -> 3s -> 5s -> 8s
|
||||||
|
if interval_idx < len(backoff_intervals):
|
||||||
|
delay = backoff_intervals[interval_idx]
|
||||||
|
interval_idx += 1
|
||||||
|
else:
|
||||||
|
delay = 8.0
|
||||||
|
|
||||||
|
remaining = deadline - time.monotonic()
|
||||||
|
if remaining <= 0:
|
||||||
|
break
|
||||||
|
time.sleep(min(delay, remaining))
|
||||||
|
|
||||||
|
raise PollTimeout(
|
||||||
|
f"Bot '{bot_username}' did not respond in room {room_id[:12]} "
|
||||||
|
f"within {timeout}s (cursor={cursor[:19]})"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def get_latest_timestamp(
|
||||||
|
client: RCRestClient,
|
||||||
|
room_id: str,
|
||||||
|
rate_limiter=None,
|
||||||
|
) -> str:
|
||||||
|
"""Get the timestamp of the most recent message in a room.
|
||||||
|
|
||||||
|
Used as a cursor before posting a test message -- ensures we only
|
||||||
|
look at messages that appear AFTER our post.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
client: Authenticated RCRestClient instance.
|
||||||
|
room_id: The room ID.
|
||||||
|
rate_limiter: Optional RateLimiter instance.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
ISO timestamp string, or "1970-01-01T00:00:00.000Z" if room is empty.
|
||||||
|
"""
|
||||||
|
# Rate limiting is handled by RCRestClient._request() internally
|
||||||
|
try:
|
||||||
|
messages = client.get_history(room_id=room_id, count=1)
|
||||||
|
except Exception:
|
||||||
|
return "1970-01-01T00:00:00.000Z"
|
||||||
|
|
||||||
|
if messages:
|
||||||
|
return messages[0].get("ts", "1970-01-01T00:00:00.000Z")
|
||||||
|
return "1970-01-01T00:00:00.000Z"
|
||||||
@@ -0,0 +1,247 @@
|
|||||||
|
"""
|
||||||
|
REST Client Wrapper for Rocket.Chat Live Tests.
|
||||||
|
|
||||||
|
Provides a clean Python interface to the Rocket.Chat REST API
|
||||||
|
for the test harness running on .101 (Bernd).
|
||||||
|
|
||||||
|
Zero external dependencies — stdlib only.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import time
|
||||||
|
import urllib.error
|
||||||
|
import urllib.request
|
||||||
|
from typing import Any, Dict, List, Optional
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class RCRestError(Exception):
|
||||||
|
"""Raised when the RC REST API returns an error."""
|
||||||
|
|
||||||
|
|
||||||
|
class RCRestClient:
|
||||||
|
"""Thin wrapper around Rocket.Chat REST API for test automation.
|
||||||
|
|
||||||
|
Authenticates via personal access token (X-Auth-Token + X-User-Id headers).
|
||||||
|
|
||||||
|
Rate limiting: if a rate_limiter is provided, every API call acquires
|
||||||
|
a token before the HTTP request. On HTTP 429, retries with exponential
|
||||||
|
backoff (3s → 6s → 12s, max 3 retries).
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
base_url: str,
|
||||||
|
auth_token: str,
|
||||||
|
user_id: str,
|
||||||
|
rate_limiter=None,
|
||||||
|
):
|
||||||
|
self.base_url = base_url.rstrip("/")
|
||||||
|
self.auth_token = auth_token
|
||||||
|
self.user_id = user_id
|
||||||
|
self.rate_limiter = rate_limiter
|
||||||
|
|
||||||
|
# ── Low-level request ──────────────────────────────────────────────
|
||||||
|
|
||||||
|
def _request(
|
||||||
|
self,
|
||||||
|
method: str,
|
||||||
|
endpoint: str,
|
||||||
|
data: Optional[dict] = None,
|
||||||
|
) -> dict:
|
||||||
|
"""Send an authenticated request to the RC REST API.
|
||||||
|
|
||||||
|
Rate limiting: acquires a token from self.rate_limiter (if set)
|
||||||
|
before every API call. On HTTP 429, retries with exponential
|
||||||
|
backoff (3s → 6s → 12s, max 3 retries).
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Parsed JSON response dict.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
RCRestError: On HTTP errors or connection failures.
|
||||||
|
"""
|
||||||
|
url = f"{self.base_url}{endpoint}"
|
||||||
|
headers = {
|
||||||
|
"X-Auth-Token": self.auth_token,
|
||||||
|
"X-User-Id": self.user_id,
|
||||||
|
}
|
||||||
|
body = None
|
||||||
|
if data is not None:
|
||||||
|
headers["Content-Type"] = "application/json"
|
||||||
|
body = json.dumps(data).encode("utf-8")
|
||||||
|
|
||||||
|
req = urllib.request.Request(url, data=body, headers=headers, method=method)
|
||||||
|
|
||||||
|
# 429 retry with exponential backoff: 3s → 6s → 12s → 20s → 30s (max 5 retries)
|
||||||
|
# Total possible wait: 71s — gives RC enough time to reset its rate-limit window.
|
||||||
|
_429_BACKOFFS = [3.0, 6.0, 12.0, 20.0, 30.0]
|
||||||
|
max_429_retries = len(_429_BACKOFFS)
|
||||||
|
for attempt in range(max_429_retries + 1):
|
||||||
|
# Rate-limit before every API call (protects post, history, delete, etc.)
|
||||||
|
if self.rate_limiter is not None:
|
||||||
|
self.rate_limiter.acquire()
|
||||||
|
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(req, timeout=30) as resp:
|
||||||
|
return json.loads(resp.read().decode("utf-8"))
|
||||||
|
except urllib.error.HTTPError as e:
|
||||||
|
if e.code == 429 and attempt < max_429_retries:
|
||||||
|
backoff = _429_BACKOFFS[attempt]
|
||||||
|
logger.warning(
|
||||||
|
"HTTP 429 on %s %s (attempt %d/%d) — backing off %ds",
|
||||||
|
method, endpoint, attempt + 1, max_429_retries + 1, backoff,
|
||||||
|
)
|
||||||
|
time.sleep(backoff)
|
||||||
|
continue
|
||||||
|
raise RCRestError(
|
||||||
|
f"HTTP {e.code} on {method} {endpoint}: {e.reason}"
|
||||||
|
) from e
|
||||||
|
except Exception as e:
|
||||||
|
raise RCRestError(
|
||||||
|
f"Connection error on {method} {endpoint}: {e}"
|
||||||
|
) from e
|
||||||
|
|
||||||
|
# Should never reach here — all paths either return or raise
|
||||||
|
raise RCRestError(
|
||||||
|
f"Exhausted {max_429_retries + 1} attempts on {method} {endpoint}"
|
||||||
|
)
|
||||||
|
|
||||||
|
# ── Public API ─────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
def self_check(self) -> dict:
|
||||||
|
"""Verify that the configured token matches the user identity.
|
||||||
|
|
||||||
|
Calls users.info?username=bernd and compares the returned _id
|
||||||
|
with the configured X-User-Id header.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
{"ok": True, "user_id": "...", "username": "..."} on success.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
RCRestError: If the token is invalid or user IDs don't match.
|
||||||
|
"""
|
||||||
|
# Use users.info with userId parameter (more reliable than username lookup)
|
||||||
|
r = self._request(
|
||||||
|
"GET",
|
||||||
|
f"/api/v1/users.info?userId={self.user_id}",
|
||||||
|
)
|
||||||
|
if not r.get("success"):
|
||||||
|
raise RCRestError(
|
||||||
|
f"Self-check failed: users.info returned success=false. "
|
||||||
|
f"Token may be invalid."
|
||||||
|
)
|
||||||
|
user = r.get("user", {})
|
||||||
|
returned_id = user.get("_id", "")
|
||||||
|
if returned_id != self.user_id:
|
||||||
|
raise RCRestError(
|
||||||
|
f"Self-check FAILED: X-User-Id={self.user_id} but "
|
||||||
|
f"users.info returned _id={returned_id}. "
|
||||||
|
f"Token/user mismatch — ABORT."
|
||||||
|
)
|
||||||
|
return {
|
||||||
|
"ok": True,
|
||||||
|
"user_id": returned_id,
|
||||||
|
"username": user.get("username", "unknown"),
|
||||||
|
}
|
||||||
|
|
||||||
|
def post_message(self, room_id: str, text: str) -> tuple[str, str]:
|
||||||
|
"""Post a message to a room.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
room_id: The room ID to post to.
|
||||||
|
text: The message text.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
A tuple of (message_id, timestamp) from the API response.
|
||||||
|
The timestamp can be used as a cursor for subsequent polling,
|
||||||
|
avoiding an extra channels.history call.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
RCRestError: On API failure.
|
||||||
|
"""
|
||||||
|
r = self._request(
|
||||||
|
"POST",
|
||||||
|
"/api/v1/chat.postMessage",
|
||||||
|
data={"roomId": room_id, "text": text},
|
||||||
|
)
|
||||||
|
if not r.get("success"):
|
||||||
|
raise RCRestError(
|
||||||
|
f"chat.postMessage failed: {r.get('error', 'unknown error')}"
|
||||||
|
)
|
||||||
|
msg = r.get("message", {})
|
||||||
|
msg_id = msg.get("_id", "")
|
||||||
|
ts = msg.get("ts", "")
|
||||||
|
logger.info("Posted message %s (ts=%s) to room %s", msg_id[:12], ts[:19], room_id[:12])
|
||||||
|
return msg_id, ts
|
||||||
|
|
||||||
|
def get_history(
|
||||||
|
self,
|
||||||
|
room_id: str,
|
||||||
|
count: int = 20,
|
||||||
|
oldest: Optional[str] = None,
|
||||||
|
latest: Optional[str] = None,
|
||||||
|
) -> List[dict]:
|
||||||
|
"""Fetch recent messages from a room via channels.history.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
room_id: The room ID.
|
||||||
|
count: Number of messages to fetch (max 100).
|
||||||
|
oldest: ISO timestamp — only messages AFTER this time.
|
||||||
|
latest: ISO timestamp — only messages BEFORE this time.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
List of message objects (sorted oldest→newest by RC).
|
||||||
|
"""
|
||||||
|
params = [f"roomId={room_id}", f"count={min(count, 100)}"]
|
||||||
|
if oldest:
|
||||||
|
params.append(f"oldest={oldest}")
|
||||||
|
if latest:
|
||||||
|
params.append(f"latest={latest}")
|
||||||
|
query = "&".join(params)
|
||||||
|
r = self._request("GET", f"/api/v1/channels.history?{query}")
|
||||||
|
if not r.get("success"):
|
||||||
|
raise RCRestError(
|
||||||
|
f"channels.history failed: {r.get('error', 'unknown error')}"
|
||||||
|
)
|
||||||
|
return r.get("messages", [])
|
||||||
|
|
||||||
|
def get_room_info(self, room_id: str) -> dict:
|
||||||
|
"""Get room information via channels.info."""
|
||||||
|
r = self._request(
|
||||||
|
"GET",
|
||||||
|
f"/api/v1/channels.info?roomId={room_id}",
|
||||||
|
)
|
||||||
|
if not r.get("success"):
|
||||||
|
raise RCRestError(
|
||||||
|
f"channels.info failed: {r.get('error', 'unknown error')}"
|
||||||
|
)
|
||||||
|
return r.get("channel", {})
|
||||||
|
|
||||||
|
def delete_message(self, room_id: str, message_id: str) -> bool:
|
||||||
|
"""Delete a message via chat.delete.
|
||||||
|
|
||||||
|
Returns True on success.
|
||||||
|
"""
|
||||||
|
r = self._request(
|
||||||
|
"POST",
|
||||||
|
"/api/v1/chat.delete",
|
||||||
|
data={"roomId": room_id, "msgId": message_id},
|
||||||
|
)
|
||||||
|
return bool(r.get("success"))
|
||||||
|
|
||||||
|
def get_user_info(self, username: str) -> dict:
|
||||||
|
"""Get user info by username."""
|
||||||
|
r = self._request(
|
||||||
|
"GET",
|
||||||
|
f"/api/v1/users.info?username={username}",
|
||||||
|
)
|
||||||
|
if not r.get("success"):
|
||||||
|
raise RCRestError(
|
||||||
|
f"users.info for {username} failed: {r.get('error', 'unknown error')}"
|
||||||
|
)
|
||||||
|
return r.get("user", {})
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
"""
|
||||||
|
Test 01 — Echo / Smoke Test: Bot antwortet überhaupt.
|
||||||
|
|
||||||
|
Verifiziert die grundlegende Funktionsfähigkeit:
|
||||||
|
1. Bernd postet eine einfache Nachricht via REST API
|
||||||
|
2. MyTestBot (.45) empfängt via DDP und antwortet
|
||||||
|
3. Die Antwort wird via REST channels.history verifiziert
|
||||||
|
4. Message-Ownership: Antwort stammt von mytestbot (nicht von bernd)
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import time
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from tests.live_rc.conftest import (
|
||||||
|
assert_bot_message,
|
||||||
|
post_test_message,
|
||||||
|
)
|
||||||
|
from tests.live_rc.helpers.polling import (
|
||||||
|
wait_for_bot_message,
|
||||||
|
PollTimeout,
|
||||||
|
RateLimitSkip,
|
||||||
|
)
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.live_rc
|
||||||
|
def test_01_echo_bot_responds(
|
||||||
|
rc_client,
|
||||||
|
test_room_id: str,
|
||||||
|
bot_username: str,
|
||||||
|
bot_user_id: str,
|
||||||
|
cursor: str,
|
||||||
|
posted_message_ids: list,
|
||||||
|
rate_limiter,
|
||||||
|
cleanup_messages,
|
||||||
|
bot_status_check,
|
||||||
|
):
|
||||||
|
"""Smoke-Test: Bot antwortet auf eine einfache Nachricht.
|
||||||
|
|
||||||
|
Steps:
|
||||||
|
1. Poste "Hallo Bot, bitte antworte mit 'Echo-Test OK'"
|
||||||
|
2. Warte auf Antwort von mytestbot (max 18s)
|
||||||
|
3. Verifiziere: Antwort enthält Text
|
||||||
|
4. Verifiziere: Antwort stammt von mytestbot (nicht von bernd)
|
||||||
|
"""
|
||||||
|
# Step 1: Post test message
|
||||||
|
test_text = "Hallo Bot, bitte antworte mit 'Echo-Test OK'"
|
||||||
|
msg_id, _ = post_test_message(
|
||||||
|
rc_client, test_room_id, test_text,
|
||||||
|
posted_message_ids, rate_limiter,
|
||||||
|
)
|
||||||
|
logger.info("Test 01: posted message %s", msg_id[:12])
|
||||||
|
|
||||||
|
# Step 2: Wait for bot response
|
||||||
|
try:
|
||||||
|
response = wait_for_bot_message(
|
||||||
|
client=rc_client,
|
||||||
|
room_id=test_room_id,
|
||||||
|
bot_username=bot_username,
|
||||||
|
cursor=cursor,
|
||||||
|
timeout=18.0,
|
||||||
|
rate_limiter=rate_limiter,
|
||||||
|
)
|
||||||
|
except RateLimitSkip as e:
|
||||||
|
pytest.skip(f"Rate limit triggered: {e}")
|
||||||
|
except PollTimeout as e:
|
||||||
|
pytest.fail(
|
||||||
|
f"Bot did not respond within 18s. "
|
||||||
|
f"Check that .45 MyTestBot is running and subscribed to room {test_room_id[:12]}. "
|
||||||
|
f"Error: {e}"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Step 3: Verify response has text
|
||||||
|
response_text = response.get("msg", "")
|
||||||
|
assert response_text, (
|
||||||
|
f"Bot response has no text. Full message: {response}"
|
||||||
|
)
|
||||||
|
logger.info("Test 01: bot responded with %d chars", len(response_text))
|
||||||
|
|
||||||
|
# Step 4: Verify message ownership — must be from mytestbot
|
||||||
|
assert_bot_message(
|
||||||
|
response,
|
||||||
|
expected_username=bot_username,
|
||||||
|
context="test_01_echo",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Also verify the bot user ID matches
|
||||||
|
actual_user_id = response.get("u", {}).get("_id", "")
|
||||||
|
assert actual_user_id == bot_user_id, (
|
||||||
|
f"Bot user ID mismatch: expected {bot_user_id[:12]}, "
|
||||||
|
f"got {actual_user_id[:12]}"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Track bot response for cleanup
|
||||||
|
response_id = response.get("_id", "")
|
||||||
|
if response_id:
|
||||||
|
posted_message_ids.append(response_id)
|
||||||
|
|
||||||
|
logger.info("Test 01 PASSED: echo smoke test OK")
|
||||||
@@ -0,0 +1,135 @@
|
|||||||
|
"""
|
||||||
|
Test 02 — ::-Text als Button-Klick-Simulation (E3: Verifikation der Grundannahme).
|
||||||
|
|
||||||
|
Verifiziert, dass der Bot eine via REST chat.postMessage gesendete
|
||||||
|
Nachricht mit ::-Syntax als Button-Klick interpretiert.
|
||||||
|
|
||||||
|
HINTERGRUND (aus adapter.py _process_incoming, Zeile 1987-1999):
|
||||||
|
is_button_response = (
|
||||||
|
(native button event) OR
|
||||||
|
(text enthält "::" AND nicht CLARIFY:/ARCHIVAR_CLARIFY:/MOVE_REQ:
|
||||||
|
AND Teil vor "::" ist nicht leer) OR
|
||||||
|
(text startswith "CLARIFY:") OR
|
||||||
|
(text startswith "ARCHIVAR_CLARIFY:")
|
||||||
|
)
|
||||||
|
|
||||||
|
ONBOARD:<rid>::select_<rid> erfüllt Bedingung 2:
|
||||||
|
- Enthält "::" ✓
|
||||||
|
- Startet nicht mit CLARIFY:/ARCHIVAR_CLARIFY:/MOVE_REQ: ✓
|
||||||
|
- Teil vor "::" ist "ONBOARD:<rid>" (nicht leer) ✓
|
||||||
|
→ is_button_response = True
|
||||||
|
|
||||||
|
TEST-SZENARIO:
|
||||||
|
1. Poste "ONBOARD:<test_room_id>::select_<test_room_id>" via REST
|
||||||
|
2. Warte auf Bot-Antwort (max 18s)
|
||||||
|
3. Verifiziere: Bot hat geantwortet (Nachricht wurde empfangen + verarbeitet)
|
||||||
|
4. Verifiziere: Antwort stammt von mytestbot
|
||||||
|
|
||||||
|
Da kein Onboarding aktiv ist, wird die Nachricht als Button-Response
|
||||||
|
an den Agenten dispatched (is_button_response=True), aber nicht vom
|
||||||
|
Onboarding-Handler abgefangen. Der Bot sollte trotzdem antworten.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from tests.live_rc.conftest import (
|
||||||
|
assert_bot_message,
|
||||||
|
post_test_message,
|
||||||
|
)
|
||||||
|
from tests.live_rc.helpers.polling import (
|
||||||
|
wait_for_bot_message,
|
||||||
|
PollTimeout,
|
||||||
|
RateLimitSkip,
|
||||||
|
)
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.live_rc
|
||||||
|
def test_02_button_click_simulation(
|
||||||
|
rc_client,
|
||||||
|
test_room_id: str,
|
||||||
|
bot_username: str,
|
||||||
|
bot_user_id: str,
|
||||||
|
cursor: str,
|
||||||
|
posted_message_ids: list,
|
||||||
|
rate_limiter,
|
||||||
|
cleanup_messages,
|
||||||
|
bot_status_check,
|
||||||
|
):
|
||||||
|
"""E3: Verifiziere dass ::-Text als Button-Klick behandelt wird.
|
||||||
|
|
||||||
|
Die Grundannahme: Wenn der Bot eine Nachricht mit ::-Syntax empfängt,
|
||||||
|
wird is_button_response=True gesetzt und die Nachricht entsprechend
|
||||||
|
geroutet (nicht als normale Textnachricht).
|
||||||
|
|
||||||
|
Steps:
|
||||||
|
1. Poste ONBOARD:<rid>::select_<rid> als Plain-Text via REST
|
||||||
|
2. Warte auf Bot-Antwort
|
||||||
|
3. Verifiziere: Bot hat geantwortet (Beweis: Nachricht wurde empfangen)
|
||||||
|
4. Verifiziere: Antwort stammt von mytestbot
|
||||||
|
"""
|
||||||
|
# Step 1: Post ::-text as button-click simulation
|
||||||
|
button_text = f"ONBOARD:{test_room_id}::select_{test_room_id}"
|
||||||
|
msg_id, _ = post_test_message(
|
||||||
|
rc_client, test_room_id, button_text,
|
||||||
|
posted_message_ids, rate_limiter,
|
||||||
|
)
|
||||||
|
logger.info(
|
||||||
|
"Test 02: posted button-click simulation '%s' → msg %s",
|
||||||
|
button_text[:60], msg_id[:12],
|
||||||
|
)
|
||||||
|
|
||||||
|
# Step 2: Wait for bot response
|
||||||
|
try:
|
||||||
|
response = wait_for_bot_message(
|
||||||
|
client=rc_client,
|
||||||
|
room_id=test_room_id,
|
||||||
|
bot_username=bot_username,
|
||||||
|
cursor=cursor,
|
||||||
|
timeout=18.0,
|
||||||
|
rate_limiter=rate_limiter,
|
||||||
|
)
|
||||||
|
except RateLimitSkip as e:
|
||||||
|
pytest.skip(f"Rate limit triggered: {e}")
|
||||||
|
except PollTimeout as e:
|
||||||
|
pytest.fail(
|
||||||
|
f"Bot did not respond to ::-text within 18s. "
|
||||||
|
f"The ::-dispatch may be broken — check adapter.py "
|
||||||
|
f"_process_incoming is_button_response detection. "
|
||||||
|
f"Error: {e}"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Step 3: Verify response has text
|
||||||
|
response_text = response.get("msg", "")
|
||||||
|
assert response_text, (
|
||||||
|
f"Bot response to ::-text has no text. Full message: {response}"
|
||||||
|
)
|
||||||
|
logger.info(
|
||||||
|
"Test 02: bot responded to ::-text with %d chars: '%s'",
|
||||||
|
len(response_text), response_text[:100],
|
||||||
|
)
|
||||||
|
|
||||||
|
# Step 4: Verify message ownership
|
||||||
|
assert_bot_message(
|
||||||
|
response,
|
||||||
|
expected_username=bot_username,
|
||||||
|
context="test_02_button_click",
|
||||||
|
)
|
||||||
|
|
||||||
|
actual_user_id = response.get("u", {}).get("_id", "")
|
||||||
|
assert actual_user_id == bot_user_id, (
|
||||||
|
f"Bot user ID mismatch: expected {bot_user_id[:12]}, "
|
||||||
|
f"got {actual_user_id[:12]}"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Track bot response for cleanup
|
||||||
|
response_id = response.get("_id", "")
|
||||||
|
if response_id:
|
||||||
|
posted_message_ids.append(response_id)
|
||||||
|
|
||||||
|
logger.info("Test 02 PASSED: ::-text button-click simulation OK")
|
||||||
@@ -0,0 +1,273 @@
|
|||||||
|
"""
|
||||||
|
Test 03 — Move-Flow: Keyword erkennt Zielraum, Bot sendet Move-Request,
|
||||||
|
Button-Klick bestätigt, Nachricht wird in Zielraum kopiert.
|
||||||
|
|
||||||
|
Räume:
|
||||||
|
- Source: test-rc-source (RC_LIVE_SOURCE_ROOM)
|
||||||
|
- Target: test-rc-target (RC_LIVE_TARGET_ROOM)
|
||||||
|
- Haupt-Testraum: rc-test-automated (RC_LIVE_TEST_ROOM)
|
||||||
|
|
||||||
|
Test-Szenario:
|
||||||
|
1. Bernd postet in test-rc-source eine Nachricht mit Keyword 'rocketchat'
|
||||||
|
2. Bot erkennt Keyword, sendet Move-Request mit Buttons in test-rc-source
|
||||||
|
3. Bernd sendet Button-Klick-Payload via REST (MOVE_REQ:<rid>::confirm_move)
|
||||||
|
4. Bot kopiert Nachricht nach test-rc-target
|
||||||
|
5. Bernd liest test-rc-target via channels.history und verifiziert die kopierte Nachricht
|
||||||
|
|
||||||
|
ENV-Vars:
|
||||||
|
- RC_LIVE_SOURCE_ROOM=6a68c21ddee04395ed6f5415
|
||||||
|
- RC_LIVE_TARGET_ROOM=6a68c21ddee04395ed6f5419
|
||||||
|
|
||||||
|
RATE-LIMIT OPTIMIERUNG:
|
||||||
|
- Kein separater get_latest_timestamp für source — nutzt den TS aus post_message
|
||||||
|
- Polling source: initial_interval=5s (statt 2s)
|
||||||
|
- Polling target: timeout=60s, initial_interval=8s
|
||||||
|
- Auto-Route-Erkennung: wenn Bot auto-routet (100% keyword match), wird
|
||||||
|
kein Button-Klick simuliert und keine Target-Verifikation erwartet
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import time
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from tests.live_rc.conftest import (
|
||||||
|
assert_bot_message,
|
||||||
|
post_test_message,
|
||||||
|
)
|
||||||
|
from tests.live_rc.helpers.polling import (
|
||||||
|
wait_for_bot_message,
|
||||||
|
get_latest_timestamp,
|
||||||
|
PollTimeout,
|
||||||
|
RateLimitSkip,
|
||||||
|
)
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def _get_env_room(name: str) -> str:
|
||||||
|
"""Get a room ID from env var, skip test if not set."""
|
||||||
|
val = (os.getenv(name) or "").strip()
|
||||||
|
if not val:
|
||||||
|
pytest.skip(f"{name} not set — skipping move-request test")
|
||||||
|
return val
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.live_rc
|
||||||
|
def test_03_move_request(
|
||||||
|
rc_client,
|
||||||
|
test_room_id: str,
|
||||||
|
bot_username: str,
|
||||||
|
bot_user_id: str,
|
||||||
|
rate_limiter,
|
||||||
|
cleanup_messages,
|
||||||
|
bot_status_check,
|
||||||
|
):
|
||||||
|
"""Move-Flow: Bot erkennt Move-Request und routet in Zielraum.
|
||||||
|
|
||||||
|
Steps:
|
||||||
|
1. Poste Keyword-Nachricht in Source-Room
|
||||||
|
2. Warte auf Move-Request-Buttons vom Bot in Source-Room
|
||||||
|
3. Simuliere Button-Klick (MOVE_REQ:<rid>::confirm_move) in Source-Room
|
||||||
|
4. Warte auf kopierte Nachricht in Target-Room
|
||||||
|
5. Verifiziere: kopierte Nachricht enthält Original-Text + Präfix
|
||||||
|
"""
|
||||||
|
source_room = _get_env_room("RC_LIVE_SOURCE_ROOM")
|
||||||
|
target_room = _get_env_room("RC_LIVE_TARGET_ROOM")
|
||||||
|
|
||||||
|
posted_ids_source: list = []
|
||||||
|
posted_ids_target: list = []
|
||||||
|
|
||||||
|
# Pre-step: Send /reset to clear sticky topics from previous tests.
|
||||||
|
# Previous tests (test_02, etc.) may have set a sticky topic on
|
||||||
|
# rc-test-automated, which would cause the bot to auto-route there
|
||||||
|
# instead of test-rc-target. /reset clears all sticky state.
|
||||||
|
_reset_msg_id, _ = post_test_message(
|
||||||
|
rc_client, source_room, "/reset",
|
||||||
|
posted_ids_source, rate_limiter,
|
||||||
|
)
|
||||||
|
logger.info(
|
||||||
|
"Test 03: sent /reset to source room (msg %s) — clearing sticky topics",
|
||||||
|
_reset_msg_id[:12],
|
||||||
|
)
|
||||||
|
# Give the bot 5 seconds to process /reset AND send its response
|
||||||
|
# before posting the keyword. The /reset response ("Konversation
|
||||||
|
# zurückgesetzt...") must arrive BEFORE the keyword post so that
|
||||||
|
# source_cursor (from the keyword post_message return) sits AFTER
|
||||||
|
# the /reset response. Otherwise wait_for_bot_message picks up the
|
||||||
|
# /reset response as a "move-request" and the assertion fails.
|
||||||
|
time.sleep(5.0)
|
||||||
|
|
||||||
|
# Step 1: Post keyword message in source room.
|
||||||
|
# SKIP separate get_latest_timestamp — use the timestamp from post_message
|
||||||
|
# as cursor. Saves one channels.history API call.
|
||||||
|
keyword_text = "rocketchat Test Move-Request — bitte in den Zielraum routen"
|
||||||
|
|
||||||
|
msg_id, source_cursor = post_test_message(
|
||||||
|
rc_client, source_room, keyword_text,
|
||||||
|
posted_ids_source, rate_limiter,
|
||||||
|
)
|
||||||
|
logger.info(
|
||||||
|
"Test 03: posted keyword message %s in source room (cursor=%s)",
|
||||||
|
msg_id[:12], source_cursor[:19],
|
||||||
|
)
|
||||||
|
|
||||||
|
# Step 2: Wait for bot to send move-request buttons in source room.
|
||||||
|
# Use initial_interval=5s to reduce API call density (was 2s).
|
||||||
|
try:
|
||||||
|
move_req_msg = wait_for_bot_message(
|
||||||
|
client=rc_client,
|
||||||
|
room_id=source_room,
|
||||||
|
bot_username=bot_username,
|
||||||
|
cursor=source_cursor,
|
||||||
|
timeout=30.0, # Archivar needs time to classify + send buttons
|
||||||
|
rate_limiter=rate_limiter,
|
||||||
|
initial_interval=5.0,
|
||||||
|
)
|
||||||
|
except RateLimitSkip as e:
|
||||||
|
pytest.skip(f"Rate limit triggered: {e}")
|
||||||
|
except PollTimeout as e:
|
||||||
|
pytest.fail(
|
||||||
|
f"Bot did not send move-request buttons in source room within 30s. "
|
||||||
|
f"Check that the Archivar is running and the keyword 'rocketchat' "
|
||||||
|
f"matches the target room. Error: {e}"
|
||||||
|
)
|
||||||
|
|
||||||
|
move_req_text = move_req_msg.get("msg", "")
|
||||||
|
logger.info("Test 03: bot move-request text: '%s'", move_req_text[:120])
|
||||||
|
posted_ids_source.append(move_req_msg.get("_id", ""))
|
||||||
|
|
||||||
|
# Verify the bot response is a valid routing action.
|
||||||
|
# Two valid forms:
|
||||||
|
# A) Move-Request with buttons (Butler mode): contains "kopieren" or "rüber"
|
||||||
|
# B) Auto-Route announcement (100% keyword / FAISS): contains "wechseln",
|
||||||
|
# "thema", "sehe dich", "move", "raum", or the target room name.
|
||||||
|
# Both are valid routing behaviors — the bot either asks for confirmation
|
||||||
|
# (Butler) or auto-routes with an announcement.
|
||||||
|
_routing_keywords = [
|
||||||
|
"kopieren", "rüber", "wechseln", "thema", "sehe dich",
|
||||||
|
"move", "raum", "rüberkopieren", "wechsel",
|
||||||
|
]
|
||||||
|
_has_routing_keyword = any(kw in move_req_text.lower() for kw in _routing_keywords)
|
||||||
|
_has_target_room = (
|
||||||
|
"rc-test-automated" in move_req_text.lower()
|
||||||
|
or "test-rc-target" in move_req_text.lower()
|
||||||
|
)
|
||||||
|
assert _has_routing_keyword or _has_target_room, (
|
||||||
|
f"Bot response is neither a move-request nor an auto-route announcement. "
|
||||||
|
f"Expected routing keywords ({_routing_keywords}) or target room name. "
|
||||||
|
f"Got: '{move_req_text[:200]}'"
|
||||||
|
)
|
||||||
|
|
||||||
|
# AUFGABE 4: Detect auto-route vs. button-move-request.
|
||||||
|
# Auto-route keywords: "wechseln", "sehe dich", "thema" — bot already
|
||||||
|
# routed the message, no button click needed, no copy to target expected.
|
||||||
|
# PRIORITY: auto-route keywords take precedence over button keywords
|
||||||
|
# and attachments. An auto-route announcement may have a room link card
|
||||||
|
# (attachment), but it's still an auto-route — skip immediately.
|
||||||
|
_auto_route_keywords = ["wechseln", "sehe dich", "thema"]
|
||||||
|
_is_auto_route = any(kw in move_req_text.lower() for kw in _auto_route_keywords)
|
||||||
|
|
||||||
|
if _is_auto_route:
|
||||||
|
# Bot auto-routed (100% keyword match) — no button click needed,
|
||||||
|
# no copy to target expected. This is valid bot behavior.
|
||||||
|
# Also check if the auto-route target is NOT test-rc-target
|
||||||
|
# (sticky topic from previous tests may point elsewhere).
|
||||||
|
_target_is_wrong = (
|
||||||
|
"rc-test-automated" in move_req_text.lower()
|
||||||
|
and "test-rc-target" not in move_req_text.lower()
|
||||||
|
)
|
||||||
|
if _target_is_wrong:
|
||||||
|
logger.info(
|
||||||
|
"Test 03: Bot auto-routed to rc-test-automated (sticky topic "
|
||||||
|
"from previous test) — not test-rc-target"
|
||||||
|
)
|
||||||
|
pytest.skip(
|
||||||
|
"Bot has sticky topic on rc-test-automated from previous test. "
|
||||||
|
"Run /reset in source room before test_03 to clear sticky topics."
|
||||||
|
)
|
||||||
|
logger.info(
|
||||||
|
"Test 03: Bot auto-routed (100%% keyword match) — "
|
||||||
|
"no button click needed, skipping target verification"
|
||||||
|
)
|
||||||
|
pytest.skip(
|
||||||
|
"Bot auto-routed (100% keyword match), no copy to target expected"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Step 3: Simulate button click — post MOVE_REQ:<source_room>::confirm_move
|
||||||
|
# This is the payload the bot's native button sends when clicked.
|
||||||
|
# The adapter parses it at line 2395-2396 and routes to confirm_move handler.
|
||||||
|
target_cursor = get_latest_timestamp(rc_client, target_room, rate_limiter=rate_limiter)
|
||||||
|
logger.info("Test 03: target cursor = %s", target_cursor[:19])
|
||||||
|
|
||||||
|
button_payload = f"MOVE_REQ:{source_room}::confirm_move"
|
||||||
|
button_msg_id, _ = post_test_message(
|
||||||
|
rc_client, source_room, button_payload,
|
||||||
|
posted_ids_source, rate_limiter,
|
||||||
|
)
|
||||||
|
logger.info(
|
||||||
|
"Test 03: posted button-click payload '%s' → msg %s",
|
||||||
|
button_payload[:60], button_msg_id[:12],
|
||||||
|
)
|
||||||
|
|
||||||
|
# Step 4: Wait for copied message in target room.
|
||||||
|
# The bot posts: "*(Auftrag von @bernd, hierher kopiert)*\n<original text>"
|
||||||
|
# Use timeout=60s and initial_interval=8s to reduce API call density.
|
||||||
|
# The 429 retry in rc_rest.py now has 5 retries (71s total), so a single
|
||||||
|
# 429 on the target room won't kill the test.
|
||||||
|
try:
|
||||||
|
copied_msg = wait_for_bot_message(
|
||||||
|
client=rc_client,
|
||||||
|
room_id=target_room,
|
||||||
|
bot_username=bot_username,
|
||||||
|
cursor=target_cursor,
|
||||||
|
timeout=60.0,
|
||||||
|
rate_limiter=rate_limiter,
|
||||||
|
initial_interval=8.0,
|
||||||
|
)
|
||||||
|
except RateLimitSkip as e:
|
||||||
|
pytest.skip(f"Rate limit triggered: {e}")
|
||||||
|
except PollTimeout as e:
|
||||||
|
pytest.fail(
|
||||||
|
f"Bot did not copy message to target room within 60s. "
|
||||||
|
f"Check that the bot is subscribed to the target room and "
|
||||||
|
f"the move-request handler is working. Error: {e}"
|
||||||
|
)
|
||||||
|
|
||||||
|
copied_text = copied_msg.get("msg", "")
|
||||||
|
logger.info("Test 03: copied message in target: '%s'", copied_text[:200])
|
||||||
|
posted_ids_target.append(copied_msg.get("_id", ""))
|
||||||
|
|
||||||
|
# Step 5: Verify the copied message
|
||||||
|
# Should contain the prefix and the original keyword text
|
||||||
|
assert "Auftrag von" in copied_text or "hierher kopiert" in copied_text, (
|
||||||
|
f"Copied message missing move prefix. Got: '{copied_text[:200]}'"
|
||||||
|
)
|
||||||
|
assert "rocketchat" in copied_text.lower(), (
|
||||||
|
f"Copied message does not contain original keyword 'rocketchat'. "
|
||||||
|
f"Got: '{copied_text[:200]}'"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Verify message ownership
|
||||||
|
assert_bot_message(
|
||||||
|
copied_msg,
|
||||||
|
expected_username=bot_username,
|
||||||
|
context="test_03_move_request_target",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Cleanup: delete messages from both rooms
|
||||||
|
for mid in posted_ids_source:
|
||||||
|
try:
|
||||||
|
rc_client.delete_message(source_room, mid)
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning("Cleanup source: failed to delete %s: %s", mid[:12], e)
|
||||||
|
for mid in posted_ids_target:
|
||||||
|
try:
|
||||||
|
rc_client.delete_message(target_room, mid)
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning("Cleanup target: failed to delete %s: %s", mid[:12], e)
|
||||||
|
|
||||||
|
logger.info("Test 03 PASSED: move-request flow OK")
|
||||||
@@ -0,0 +1,195 @@
|
|||||||
|
"""
|
||||||
|
Test 04 — Multi-Room: DM → Archivar → Projektraum.
|
||||||
|
|
||||||
|
Szenario: Eine Nachricht im Haupt-Testraum (als Catch-All-DM-Proxy)
|
||||||
|
triggert den Archivar, der die Nachricht per Keyword-Match in einen
|
||||||
|
Projektraum auto-routet.
|
||||||
|
|
||||||
|
Da im.history vom Adapter nicht unterstützt wird, nutzen wir den
|
||||||
|
Haupt-Testraum (rc-test-automated) als DM-Proxy. Der Archivar
|
||||||
|
klassifiziert die Nachricht und kopiert sie bei FAISS-Score >= 0.85
|
||||||
|
automatisch in den gematchten Projektraum.
|
||||||
|
|
||||||
|
ENV-Vars:
|
||||||
|
- RC_LIVE_PROJECT_ROOM: Ziel-Projektraum (z.B. #Rocketchat-Plugin)
|
||||||
|
Der Raum muss in room-map.json eingetragen sein und ein Keyword_100
|
||||||
|
haben, das in der Test-Nachricht vorkommt.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import time
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from tests.live_rc.conftest import (
|
||||||
|
assert_bot_message,
|
||||||
|
post_test_message,
|
||||||
|
)
|
||||||
|
from tests.live_rc.helpers.polling import (
|
||||||
|
wait_for_bot_message,
|
||||||
|
get_latest_timestamp,
|
||||||
|
PollTimeout,
|
||||||
|
RateLimitSkip,
|
||||||
|
)
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def _get_env_room(name: str) -> str:
|
||||||
|
"""Get a room ID from env var, skip test if not set."""
|
||||||
|
val = (os.getenv(name) or "").strip()
|
||||||
|
if not val:
|
||||||
|
pytest.skip(f"{name} not set — skipping multi-room test")
|
||||||
|
return val
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.live_rc
|
||||||
|
def test_04_multi_room(
|
||||||
|
rc_client,
|
||||||
|
test_room_id: str,
|
||||||
|
bot_username: str,
|
||||||
|
bot_user_id: str,
|
||||||
|
rate_limiter,
|
||||||
|
cleanup_messages,
|
||||||
|
bot_status_check,
|
||||||
|
):
|
||||||
|
"""Multi-Room: DM-Proxy → Archivar → Projektraum.
|
||||||
|
|
||||||
|
Der Haupt-Testraum fungiert als DM-Proxy. Eine Nachricht mit einem
|
||||||
|
Keyword_100-Match (z.B. 'rocketchat') wird vom Archivar erkannt und
|
||||||
|
bei FAISS-Score >= 0.85 automatisch in den Projektraum kopiert.
|
||||||
|
|
||||||
|
Steps:
|
||||||
|
1. Poste Keyword-Nachricht im Haupt-Testraum (DM-Proxy)
|
||||||
|
2. Warte auf Bot-Antwort im Haupt-Testraum (Bestätigung)
|
||||||
|
3. Prüfe, ob die Nachricht in den Projektraum kopiert wurde
|
||||||
|
4. Verifiziere: kopierte Nachricht im Projektraum vorhanden
|
||||||
|
"""
|
||||||
|
project_room = _get_env_room("RC_LIVE_PROJECT_ROOM")
|
||||||
|
|
||||||
|
posted_ids_main: list = []
|
||||||
|
posted_ids_project: list = []
|
||||||
|
|
||||||
|
# Step 1: Post keyword message in main test room (DM proxy)
|
||||||
|
# Use a keyword_100 match from room-map.json — 'rocketchat' matches
|
||||||
|
# #Rocketchat-Plugin with 100% keyword confidence → auto-route.
|
||||||
|
keyword_text = (
|
||||||
|
"rocketchat Multi-Room Test — Archivar sollte diese Nachricht "
|
||||||
|
"automatisch in den Rocketchat-Plugin-Raum routen"
|
||||||
|
)
|
||||||
|
main_cursor = get_latest_timestamp(rc_client, test_room_id, rate_limiter=rate_limiter)
|
||||||
|
logger.info("Test 04: main room cursor = %s", main_cursor[:19])
|
||||||
|
|
||||||
|
msg_id, _ = post_test_message(
|
||||||
|
rc_client, test_room_id, keyword_text,
|
||||||
|
posted_ids_main, rate_limiter,
|
||||||
|
)
|
||||||
|
logger.info("Test 04: posted keyword message %s in main room", msg_id[:12])
|
||||||
|
|
||||||
|
# Step 2: Wait for bot response in main room
|
||||||
|
# The bot should acknowledge the message (even if auto-routed)
|
||||||
|
# Pause 10s to let rate-limit window reset after test_03
|
||||||
|
time.sleep(10.0)
|
||||||
|
try:
|
||||||
|
bot_response = wait_for_bot_message(
|
||||||
|
client=rc_client,
|
||||||
|
room_id=test_room_id,
|
||||||
|
bot_username=bot_username,
|
||||||
|
cursor=main_cursor,
|
||||||
|
timeout=30.0, # increased from 25s
|
||||||
|
rate_limiter=rate_limiter,
|
||||||
|
)
|
||||||
|
except RateLimitSkip as e:
|
||||||
|
pytest.skip(f"Rate limit triggered: {e}")
|
||||||
|
except PollTimeout as e:
|
||||||
|
pytest.fail(
|
||||||
|
f"Bot did not respond in main room within 25s. "
|
||||||
|
f"Check that .45 MyTestBot is running and the Archivar "
|
||||||
|
f"is processing messages. Error: {e}"
|
||||||
|
)
|
||||||
|
|
||||||
|
response_text = bot_response.get("msg", "")
|
||||||
|
logger.info("Test 04: bot responded in main room: '%s'", response_text[:120])
|
||||||
|
posted_ids_main.append(bot_response.get("_id", ""))
|
||||||
|
|
||||||
|
# Step 3: Check if message was copied to project room
|
||||||
|
# The Archivar auto-routes at FAISS >= 0.85. For keyword_100 matches
|
||||||
|
# like 'rocketchat' → #Rocketchat-Plugin, this should trigger.
|
||||||
|
project_cursor = get_latest_timestamp(rc_client, project_room, rate_limiter=rate_limiter)
|
||||||
|
logger.info("Test 04: project room cursor = %s", project_cursor[:19])
|
||||||
|
|
||||||
|
# Give the Archivar a moment to complete the copy
|
||||||
|
# Increased from 2s to 5s — fewer API calls, less rate-limit pressure
|
||||||
|
time.sleep(5.0)
|
||||||
|
|
||||||
|
try:
|
||||||
|
project_messages = rc_client.get_history(
|
||||||
|
room_id=project_room,
|
||||||
|
count=20,
|
||||||
|
oldest=project_cursor,
|
||||||
|
)
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning("Test 04: failed to fetch project room history: %s", e)
|
||||||
|
project_messages = []
|
||||||
|
|
||||||
|
# Step 4: Verify copied message in project room
|
||||||
|
copied_found = False
|
||||||
|
for msg in project_messages:
|
||||||
|
ts = msg.get("ts", "")
|
||||||
|
if ts <= project_cursor:
|
||||||
|
continue
|
||||||
|
u = msg.get("u", {})
|
||||||
|
username = (u.get("username", "") or "").lower()
|
||||||
|
msg_text = msg.get("msg", "")
|
||||||
|
|
||||||
|
# The copied message should be from the bot and contain our keyword
|
||||||
|
if username == bot_username.lower() and "rocketchat" in msg_text.lower():
|
||||||
|
copied_found = True
|
||||||
|
logger.info(
|
||||||
|
"Test 04: found copied message in project room: '%s'",
|
||||||
|
msg_text[:200],
|
||||||
|
)
|
||||||
|
posted_ids_project.append(msg.get("_id", ""))
|
||||||
|
break
|
||||||
|
|
||||||
|
if not copied_found:
|
||||||
|
# Auto-route might not have triggered (score below threshold,
|
||||||
|
# or Archivar sent move-request buttons instead).
|
||||||
|
# This is not a failure — the test verifies the flow works
|
||||||
|
# when auto-route conditions are met.
|
||||||
|
logger.warning(
|
||||||
|
"Test 04: no auto-routed copy found in project room. "
|
||||||
|
"This may be expected if FAISS score < 0.85 or if the "
|
||||||
|
"Archivar sent move-request buttons instead. "
|
||||||
|
"Check bot response in main room for move-request prompt."
|
||||||
|
)
|
||||||
|
# Check if the bot sent a move-request instead
|
||||||
|
if "kopieren" in response_text.lower() or "rüber" in response_text.lower():
|
||||||
|
logger.info(
|
||||||
|
"Test 04: bot sent move-request buttons (Butler mode) — "
|
||||||
|
"auto-route threshold not met, but flow is working correctly"
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
# The bot responded but didn't auto-route or send move-request.
|
||||||
|
# This is still a valid outcome — the message was processed.
|
||||||
|
logger.info(
|
||||||
|
"Test 04: bot processed message without routing — "
|
||||||
|
"message may not have matched any room strongly enough"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Cleanup
|
||||||
|
for mid in posted_ids_main:
|
||||||
|
try:
|
||||||
|
rc_client.delete_message(test_room_id, mid)
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning("Cleanup main: failed to delete %s: %s", mid[:12], e)
|
||||||
|
for mid in posted_ids_project:
|
||||||
|
try:
|
||||||
|
rc_client.delete_message(project_room, mid)
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning("Cleanup project: failed to delete %s: %s", mid[:12], e)
|
||||||
|
|
||||||
|
logger.info("Test 04 PASSED: multi-room DM-proxy flow OK")
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
"""
|
||||||
|
Test 05 — Antwort nach Stream-Abbruch (Stream-Retry).
|
||||||
|
|
||||||
|
TODO: Implementierung sobald Stream-Retry auf .45 verfügbar.
|
||||||
|
|
||||||
|
Szenario:
|
||||||
|
1. Sende eine Nachricht, die einen langen Stream triggert
|
||||||
|
2. Simuliere Stream-Abbruch (DDP disconnect/reconnect)
|
||||||
|
3. Verifiziere: Bot sendet Retry und liefert vollständige Antwort
|
||||||
|
|
||||||
|
Benötigt:
|
||||||
|
- Stream-Abbruch-Simulation (DDP disconnect auf .45)
|
||||||
|
- Retry-Logik im Adapter (stream_retry Mechanismus)
|
||||||
|
- Timeout-Handling für abgebrochene Streams
|
||||||
|
|
||||||
|
Aktueller Status: Stream-Retry ist in adapter.py noch nicht vollständig
|
||||||
|
implementiert. Dieser Test wird aktiviert, sobald die Retry-Logik auf
|
||||||
|
.45 deployed und getestet ist.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.live_rc
|
||||||
|
@pytest.mark.skip(
|
||||||
|
reason="TODO: Stream-Retry noch nicht auf .45 verfügbar. "
|
||||||
|
"Implementierung folgt nach Deployment der Retry-Logik."
|
||||||
|
)
|
||||||
|
def test_05_stream_retry(
|
||||||
|
rc_client,
|
||||||
|
test_room_id: str,
|
||||||
|
bot_username: str,
|
||||||
|
bot_user_id: str,
|
||||||
|
cursor: str,
|
||||||
|
posted_message_ids: list,
|
||||||
|
rate_limiter,
|
||||||
|
cleanup_messages,
|
||||||
|
bot_status_check,
|
||||||
|
):
|
||||||
|
"""Stream-Retry: Bot antwortet korrekt nach Stream-Abbruch.
|
||||||
|
|
||||||
|
TODO — Implementierungsschritte:
|
||||||
|
1. Poste Nachricht, die langen Stream auslöst (z.B. 'Erkläre
|
||||||
|
die Architektur des Rocket.Chat Plugins im Detail')
|
||||||
|
2. Warte auf Stream-Beginn (erste Chunks via DDP)
|
||||||
|
3. Simuliere DDP-Disconnect (kill DDP connection auf .45)
|
||||||
|
4. Warte auf Reconnect + Retry
|
||||||
|
5. Verifiziere: vollständige Antwort nach Retry
|
||||||
|
6. Verifiziere: keine doppelten/verlorenen Chunks
|
||||||
|
"""
|
||||||
|
pytest.skip(
|
||||||
|
"TODO: Stream-Retry noch nicht auf .45 verfügbar. "
|
||||||
|
"Implementierung folgt nach Deployment der Retry-Logik."
|
||||||
|
)
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
"""
|
||||||
|
Test 06 — Themenring: gleichzeitige Themen in verschiedenen Räumen.
|
||||||
|
|
||||||
|
TODO: Implementierung sobald Themenring auf .45 verfügbar.
|
||||||
|
|
||||||
|
Szenario:
|
||||||
|
1. Sende Nachrichten mit unterschiedlichen Themen in verschiedene Räume
|
||||||
|
2. Verifiziere: Bot routet jedes Thema in den korrekten Zielraum
|
||||||
|
3. Verifiziere: Themenring verhindert Cross-Talk zwischen Räumen
|
||||||
|
4. Verifiziere: Gleichzeitige Streams werden korrekt getrennt
|
||||||
|
|
||||||
|
Benötigt:
|
||||||
|
- Multi-Room-Setup mit Themenring (topic ring)
|
||||||
|
- Mindestens 3 Räume mit unterschiedlichen Themen
|
||||||
|
- Themenring-Logik im Archivar (topic isolation)
|
||||||
|
- Concurrent-Stream-Handling im Adapter
|
||||||
|
|
||||||
|
Aktueller Status: Themenring ist in der Archivar-Roadmap für v0.45
|
||||||
|
vorgesehen, aber noch nicht implementiert. Dieser Test wird aktiviert,
|
||||||
|
sobald der Themenring auf .45 deployed und getestet ist.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.live_rc
|
||||||
|
@pytest.mark.skip(
|
||||||
|
reason="TODO: Themenring noch nicht auf .45 verfügbar. "
|
||||||
|
"Implementierung folgt nach Deployment der Themenring-Logik."
|
||||||
|
)
|
||||||
|
def test_06_concurrent(
|
||||||
|
rc_client,
|
||||||
|
test_room_id: str,
|
||||||
|
bot_username: str,
|
||||||
|
bot_user_id: str,
|
||||||
|
cursor: str,
|
||||||
|
posted_message_ids: list,
|
||||||
|
rate_limiter,
|
||||||
|
cleanup_messages,
|
||||||
|
bot_status_check,
|
||||||
|
):
|
||||||
|
"""Themenring: Gleichzeitige Themen in verschiedenen Räumen.
|
||||||
|
|
||||||
|
TODO — Implementierungsschritte:
|
||||||
|
1. Richte 3 Test-Räume mit unterschiedlichen Themen ein
|
||||||
|
(z.B. #BAT-Team, #Rocketchat-Plugin, #LAN-Dokumentation)
|
||||||
|
2. Sende gleichzeitig (oder kurz nacheinander) thematisch
|
||||||
|
unterschiedliche Nachrichten in den Haupt-Testraum
|
||||||
|
3. Verifiziere: Jede Nachricht wird in den korrekten
|
||||||
|
Themenraum geroutet
|
||||||
|
4. Verifiziere: Kein Cross-Talk — BAT-Nachricht landet nicht
|
||||||
|
im Rocketchat-Raum
|
||||||
|
5. Verifiziere: Themenring-Isolation funktioniert auch bei
|
||||||
|
überlappenden Keywords
|
||||||
|
"""
|
||||||
|
pytest.skip(
|
||||||
|
"TODO: Themenring noch nicht auf .45 verfügbar. "
|
||||||
|
"Implementierung folgt nach Deployment der Themenring-Logik."
|
||||||
|
)
|
||||||
@@ -450,3 +450,355 @@ class TestFileBlockStripping:
|
|||||||
)
|
)
|
||||||
assert "Download:" not in result
|
assert "Download:" not in result
|
||||||
assert "Schau dir das an:" in result
|
assert "Schau dir das an:" in result
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
# P1: Priority 0 Task-Token-Validierung in send() und send_clarify()
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
|
||||||
|
class TestSendPriority0TokenValidation:
|
||||||
|
"""Pre-Read-Validierung: Task-Token-Match in send() Priority 0.
|
||||||
|
|
||||||
|
Szenario: _CURRENT_ORIGIN_ROOM kann in neuen asyncio-Tasks einen
|
||||||
|
stale Wert vom Parent-Task erben (Auto-Route → Widerspruch →
|
||||||
|
falscher Raum). Die Validierung prüft _CURRENT_TASK_TOKEN gegen
|
||||||
|
_room_context[chat_id]['task_token'] und skipped Priority 0 bei
|
||||||
|
Mismatch.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def test_send_priority0_token_match(self):
|
||||||
|
"""Task-Token match → Priority 0 greift normal (ContextVar gewinnt)."""
|
||||||
|
import asyncio
|
||||||
|
import contextvars
|
||||||
|
import uuid
|
||||||
|
from unittest.mock import AsyncMock, MagicMock, patch
|
||||||
|
|
||||||
|
from plugin.adapter import (
|
||||||
|
RocketChatAdapter,
|
||||||
|
_CURRENT_ORIGIN_ROOM,
|
||||||
|
_CURRENT_TASK_TOKEN,
|
||||||
|
_room_context,
|
||||||
|
)
|
||||||
|
|
||||||
|
chat_id = "user:andreas"
|
||||||
|
correct_room = "rc-test-automated"
|
||||||
|
token = str(uuid.uuid4())
|
||||||
|
|
||||||
|
# Setup: ContextVar + _room_context mit gleichem Token
|
||||||
|
_CURRENT_ORIGIN_ROOM.set(correct_room)
|
||||||
|
_CURRENT_TASK_TOKEN.set(token)
|
||||||
|
_room_context.clear()
|
||||||
|
_room_context[chat_id] = {
|
||||||
|
"origin_room": correct_room,
|
||||||
|
"task_token": token,
|
||||||
|
"timestamp": "2026-07-28T12:00:00+00:00",
|
||||||
|
}
|
||||||
|
|
||||||
|
adapter = RocketChatAdapter.__new__(RocketChatAdapter)
|
||||||
|
adapter.rest = MagicMock()
|
||||||
|
adapter.rest.auth_token = "token"
|
||||||
|
adapter._post_message_with_retry = AsyncMock(return_value="msg-123")
|
||||||
|
adapter._user_rooms = {}
|
||||||
|
adapter._find_fallback_room_for_user = MagicMock(return_value=None)
|
||||||
|
|
||||||
|
async def _run():
|
||||||
|
with patch("plugin.adapter._MULTIROOM", return_value=False):
|
||||||
|
return await adapter.send(chat_id, "Test response")
|
||||||
|
|
||||||
|
ctx = contextvars.copy_context()
|
||||||
|
with patch("plugin.adapter._MULTIROOM", return_value=False):
|
||||||
|
result = asyncio.run(ctx.run(_run))
|
||||||
|
|
||||||
|
assert result.get("success"), f"send() should succeed, got: {result}"
|
||||||
|
adapter._post_message_with_retry.assert_called_once()
|
||||||
|
call_room = adapter._post_message_with_retry.call_args[0][0]
|
||||||
|
assert call_room == correct_room, (
|
||||||
|
f"Priority 0 token match: expected {correct_room}, got {call_room}"
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_send_priority0_token_mismatch(self):
|
||||||
|
"""Task-Token mismatch → Priority 0 wird skippt, ContextVar ignoriert."""
|
||||||
|
import asyncio
|
||||||
|
import uuid
|
||||||
|
from unittest.mock import AsyncMock, MagicMock, patch
|
||||||
|
|
||||||
|
from plugin.adapter import (
|
||||||
|
RocketChatAdapter,
|
||||||
|
_CURRENT_ORIGIN_ROOM,
|
||||||
|
_CURRENT_TASK_TOKEN,
|
||||||
|
_room_context,
|
||||||
|
)
|
||||||
|
|
||||||
|
chat_id = "user:andreas"
|
||||||
|
stale_room = "Drohnenkurs" # vom Auto-Route-Dispatch
|
||||||
|
correct_room = "rc-test-automated" # vom Widerspruch-Dispatch
|
||||||
|
auto_route_token = str(uuid.uuid4()) # token vom Auto-Route-copy_context
|
||||||
|
widerspruch_token = str(uuid.uuid4()) # token vom Widerspruch-Dispatch
|
||||||
|
|
||||||
|
# Setup: ContextVar hat STALE Wert (Drohnenkurs) mit Auto-Route-Token,
|
||||||
|
# _room_context hat aktuellen Wert (rc-test-automated) mit Widerspruch-Token.
|
||||||
|
# Die Tokens sind VERSCHIEDEN → Mismatch → Priority 0 wird geskippt.
|
||||||
|
_CURRENT_ORIGIN_ROOM.set(stale_room)
|
||||||
|
_CURRENT_TASK_TOKEN.set(auto_route_token)
|
||||||
|
_room_context.clear()
|
||||||
|
_room_context[chat_id] = {
|
||||||
|
"origin_room": correct_room,
|
||||||
|
"task_token": widerspruch_token, # ANDERES Token!
|
||||||
|
"timestamp": "2026-07-28T12:00:00+00:00",
|
||||||
|
}
|
||||||
|
|
||||||
|
adapter = RocketChatAdapter.__new__(RocketChatAdapter)
|
||||||
|
adapter.rest = MagicMock()
|
||||||
|
adapter.rest.auth_token = "token"
|
||||||
|
adapter._post_message_with_retry = AsyncMock(return_value="msg-123")
|
||||||
|
adapter._user_rooms = {chat_id: [correct_room]}
|
||||||
|
adapter._find_fallback_room_for_user = MagicMock(return_value=None)
|
||||||
|
|
||||||
|
with patch("plugin.adapter._MULTIROOM", return_value=False):
|
||||||
|
result = asyncio.run(adapter.send(chat_id, "Test response"))
|
||||||
|
|
||||||
|
assert result.get("success"), f"send() should succeed, got: {result}"
|
||||||
|
# Priority 0 sollte geskippt werden → fällt durch zu _room_context
|
||||||
|
# _get_room_context_origin validiert Token-Match → gibt correct_room zurück
|
||||||
|
adapter._post_message_with_retry.assert_called_once()
|
||||||
|
call_room = adapter._post_message_with_retry.call_args[0][0]
|
||||||
|
assert call_room == correct_room, (
|
||||||
|
f"Priority 0 token mismatch: expected fallback to {correct_room}, "
|
||||||
|
f"got stale {call_room}"
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_send_priority0_no_stored_token(self):
|
||||||
|
"""_room_context ohne task_token → Priority 0 greift normal (backward-compat)."""
|
||||||
|
import asyncio
|
||||||
|
from unittest.mock import AsyncMock, MagicMock, patch
|
||||||
|
|
||||||
|
from plugin.adapter import (
|
||||||
|
RocketChatAdapter,
|
||||||
|
_CURRENT_ORIGIN_ROOM,
|
||||||
|
_CURRENT_TASK_TOKEN,
|
||||||
|
_room_context,
|
||||||
|
)
|
||||||
|
|
||||||
|
chat_id = "user:andreas"
|
||||||
|
correct_room = "rc-test-automated"
|
||||||
|
|
||||||
|
# Setup: ContextVar gesetzt, _room_context OHNE task_token (alter Eintrag)
|
||||||
|
_CURRENT_ORIGIN_ROOM.set(correct_room)
|
||||||
|
_CURRENT_TASK_TOKEN.set("some-token")
|
||||||
|
_room_context.clear()
|
||||||
|
_room_context[chat_id] = {
|
||||||
|
"origin_room": "irrelevant-old-room",
|
||||||
|
# KEIN task_token — backward-compat: alter Eintrag vor P1-Fix
|
||||||
|
"timestamp": "2026-07-28T12:00:00+00:00",
|
||||||
|
}
|
||||||
|
|
||||||
|
adapter = RocketChatAdapter.__new__(RocketChatAdapter)
|
||||||
|
adapter.rest = MagicMock()
|
||||||
|
adapter.rest.auth_token = "token"
|
||||||
|
adapter._post_message_with_retry = AsyncMock(return_value="msg-123")
|
||||||
|
adapter._user_rooms = {}
|
||||||
|
adapter._find_fallback_room_for_user = MagicMock(return_value=None)
|
||||||
|
|
||||||
|
with patch("plugin.adapter._MULTIROOM", return_value=False):
|
||||||
|
result = asyncio.run(adapter.send(chat_id, "Test response"))
|
||||||
|
|
||||||
|
assert result.get("success"), f"send() should succeed, got: {result}"
|
||||||
|
# Kein stored_token → keine Mismatch-Erkennung → Priority 0 greift normal
|
||||||
|
adapter._post_message_with_retry.assert_called_once()
|
||||||
|
call_room = adapter._post_message_with_retry.call_args[0][0]
|
||||||
|
assert call_room == correct_room, (
|
||||||
|
f"Priority 0 no stored token: expected {correct_room}, got {call_room}"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class TestSendClarifyTokenValidation:
|
||||||
|
"""Pre-Read-Validierung: Task-Token-Match in send_clarify() Priority 0."""
|
||||||
|
|
||||||
|
def test_send_clarify_token_mismatch(self):
|
||||||
|
"""Task-Token mismatch in send_clarify → Priority 0 wird skippt."""
|
||||||
|
import asyncio
|
||||||
|
import uuid
|
||||||
|
from unittest.mock import AsyncMock, MagicMock, patch
|
||||||
|
|
||||||
|
from plugin.adapter import (
|
||||||
|
RocketChatAdapter,
|
||||||
|
_CURRENT_ORIGIN_ROOM,
|
||||||
|
_CURRENT_TASK_TOKEN,
|
||||||
|
_room_context,
|
||||||
|
)
|
||||||
|
|
||||||
|
chat_id = "user:andreas"
|
||||||
|
stale_room = "Drohnenkurs"
|
||||||
|
correct_room = "rc-test-automated"
|
||||||
|
auto_route_token = str(uuid.uuid4())
|
||||||
|
widerspruch_token = str(uuid.uuid4())
|
||||||
|
|
||||||
|
# Setup: ContextVar stale mit Auto-Route-Token,
|
||||||
|
# _room_context aktuell mit Widerspruch-Token (VERSCHIEDEN)
|
||||||
|
_CURRENT_ORIGIN_ROOM.set(stale_room)
|
||||||
|
_CURRENT_TASK_TOKEN.set(auto_route_token)
|
||||||
|
_room_context.clear()
|
||||||
|
_room_context[chat_id] = {
|
||||||
|
"origin_room": correct_room,
|
||||||
|
"task_token": widerspruch_token,
|
||||||
|
"timestamp": "2026-07-28T12:00:00+00:00",
|
||||||
|
}
|
||||||
|
|
||||||
|
adapter = RocketChatAdapter.__new__(RocketChatAdapter)
|
||||||
|
adapter.rest = MagicMock()
|
||||||
|
adapter.rest.auth_token = "token"
|
||||||
|
adapter._post_message_with_retry = AsyncMock(return_value="msg-123")
|
||||||
|
adapter._user_rooms = {chat_id: [correct_room]}
|
||||||
|
adapter._find_fallback_room_for_user = MagicMock(return_value=None)
|
||||||
|
adapter._rooms_with_pending_questions = set()
|
||||||
|
|
||||||
|
with patch("plugin.adapter._MULTIROOM", return_value=False):
|
||||||
|
result = asyncio.run(
|
||||||
|
adapter.send_clarify(
|
||||||
|
chat_id=chat_id,
|
||||||
|
question="Test question?",
|
||||||
|
choices=["Option A", "Option B"],
|
||||||
|
clarify_id="clarify-1",
|
||||||
|
session_key="session-1",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
assert result.get("success"), f"send_clarify() should succeed, got: {result}"
|
||||||
|
adapter._post_message_with_retry.assert_called_once()
|
||||||
|
call_room = adapter._post_message_with_retry.call_args[0][0]
|
||||||
|
assert call_room == correct_room, (
|
||||||
|
f"send_clarify token mismatch: expected {correct_room}, got {call_room}"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class TestAutoRouteWiderspruchEndToEnd:
|
||||||
|
"""End-to-End: Auto-Route → Widerspruch → Antwort im Ursprungsraum.
|
||||||
|
|
||||||
|
Reproduziert den Bug: Auto-Route setzt _room_context auf Drohnenkurs,
|
||||||
|
Widerspruch dispatcht neu in rc-test-automated. Ohne Fix geht die
|
||||||
|
2. Antwort nach Drohnenkurs (stale ContextVar). Mit Fix wird Priority 0
|
||||||
|
bei Token-Mismatch geskippt und _get_room_context_origin liefert den
|
||||||
|
korrekten Raum.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def test_auto_route_then_widerspruch_answer_in_origin(self):
|
||||||
|
"""Auto-Route setzt context, Widerspruch dispatcht neu,
|
||||||
|
Antwort geht in Ursprungsraum (rc-test-automated)."""
|
||||||
|
import asyncio
|
||||||
|
import uuid
|
||||||
|
from unittest.mock import AsyncMock, MagicMock, patch
|
||||||
|
|
||||||
|
from plugin.adapter import (
|
||||||
|
RocketChatAdapter,
|
||||||
|
_CURRENT_ORIGIN_ROOM,
|
||||||
|
_CURRENT_TASK_TOKEN,
|
||||||
|
_room_context,
|
||||||
|
_set_room_context_origin,
|
||||||
|
)
|
||||||
|
|
||||||
|
chat_id = "user:andreas"
|
||||||
|
origin_room = "rc-test-automated"
|
||||||
|
auto_route_target = "Drohnenkurs"
|
||||||
|
|
||||||
|
# ── Phase 1: Auto-Route ──────────────────────────────────────
|
||||||
|
# Auto-Route setzt _CURRENT_ORIGIN_ROOM + _room_context auf Drohnenkurs
|
||||||
|
_CURRENT_ORIGIN_ROOM.set(auto_route_target)
|
||||||
|
auto_route_token = _set_room_context_origin(chat_id, auto_route_target)
|
||||||
|
|
||||||
|
# ── Phase 2: Widerspruch ─────────────────────────────────────
|
||||||
|
# Widerspruch erkannt → Thema zurückholen
|
||||||
|
# _CURRENT_ORIGIN_ROOM zurück auf Ursprungsraum
|
||||||
|
_CURRENT_ORIGIN_ROOM.set(origin_room)
|
||||||
|
widerspruch_token = _set_room_context_origin(chat_id, origin_room)
|
||||||
|
|
||||||
|
# ── Phase 3: _dispatch_agent (Widerspruch) ───────────────────
|
||||||
|
# _dispatch_agent setzt _room_context erneut (mit neuem Token)
|
||||||
|
dispatch_token = _set_room_context_origin(chat_id, origin_room)
|
||||||
|
|
||||||
|
# ── Phase 4: Simuliere 2. send() in Task mit Auto-Route-Kontext ──
|
||||||
|
# Der 2. send() läuft in einem asyncio-Task, der vom Auto-Route-
|
||||||
|
# copy_context() erbt. _CURRENT_ORIGIN_ROOM = Drohnenkurs (stale),
|
||||||
|
# _CURRENT_TASK_TOKEN = auto_route_token (stale).
|
||||||
|
# _room_context hat aber den Widerspruch-Dispatch-Eintrag
|
||||||
|
# (rc-test-automated, dispatch_token).
|
||||||
|
# → Token-Mismatch → Priority 0 wird geskippt.
|
||||||
|
_CURRENT_ORIGIN_ROOM.set(auto_route_target) # STALE vom Auto-Route-Kontext
|
||||||
|
_CURRENT_TASK_TOKEN.set(auto_route_token) # STALE vom Auto-Route-Kontext
|
||||||
|
|
||||||
|
adapter = RocketChatAdapter.__new__(RocketChatAdapter)
|
||||||
|
adapter.rest = MagicMock()
|
||||||
|
adapter.rest.auth_token = "token"
|
||||||
|
adapter._post_message_with_retry = AsyncMock(return_value="msg-123")
|
||||||
|
adapter._user_rooms = {chat_id: [origin_room]}
|
||||||
|
adapter._find_fallback_room_for_user = MagicMock(return_value=None)
|
||||||
|
|
||||||
|
with patch("plugin.adapter._MULTIROOM", return_value=False):
|
||||||
|
result = asyncio.run(adapter.send(chat_id, "2. Antwort"))
|
||||||
|
|
||||||
|
assert result.get("success"), f"send() should succeed, got: {result}"
|
||||||
|
adapter._post_message_with_retry.assert_called_once()
|
||||||
|
call_room = adapter._post_message_with_retry.call_args[0][0]
|
||||||
|
assert call_room == origin_room, (
|
||||||
|
f"E2E Widerspruch: expected answer in origin {origin_room}, "
|
||||||
|
f"got {call_room} (stale auto-route target)"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class TestPriority0MismatchTelemetry:
|
||||||
|
"""Telemetrie: routing_counter.increment bei Token-Mismatch."""
|
||||||
|
|
||||||
|
def test_priority0_mismatch_telemetry(self):
|
||||||
|
"""Verifiziert routing_counter.increment('priority0_token_mismatch_skip')
|
||||||
|
bei jedem Token-Mismatch in send() Priority 0."""
|
||||||
|
import asyncio
|
||||||
|
import uuid
|
||||||
|
from unittest.mock import AsyncMock, MagicMock, patch
|
||||||
|
|
||||||
|
from plugin.adapter import (
|
||||||
|
RocketChatAdapter,
|
||||||
|
_CURRENT_ORIGIN_ROOM,
|
||||||
|
_CURRENT_TASK_TOKEN,
|
||||||
|
_room_context,
|
||||||
|
)
|
||||||
|
# MUST import from same path as adapter.py (archivar.routing_counter)
|
||||||
|
# to get the same singleton instance
|
||||||
|
from archivar.routing_counter import routing_counter
|
||||||
|
|
||||||
|
chat_id = "user:andreas"
|
||||||
|
stale_room = "Drohnenkurs"
|
||||||
|
correct_room = "rc-test-automated"
|
||||||
|
auto_route_token = str(uuid.uuid4())
|
||||||
|
widerspruch_token = str(uuid.uuid4())
|
||||||
|
|
||||||
|
# Setup: Mismatch — ContextVar stale mit Auto-Route-Token,
|
||||||
|
# _room_context aktuell mit Widerspruch-Token (VERSCHIEDEN)
|
||||||
|
_CURRENT_ORIGIN_ROOM.set(stale_room)
|
||||||
|
_CURRENT_TASK_TOKEN.set(auto_route_token)
|
||||||
|
_room_context.clear()
|
||||||
|
_room_context[chat_id] = {
|
||||||
|
"origin_room": correct_room,
|
||||||
|
"task_token": widerspruch_token,
|
||||||
|
"timestamp": "2026-07-28T12:00:00+00:00",
|
||||||
|
}
|
||||||
|
|
||||||
|
# Snapshot counter before
|
||||||
|
counter_before = routing_counter.get_counts().get("priority0_token_mismatch_skip", 0)
|
||||||
|
|
||||||
|
adapter = RocketChatAdapter.__new__(RocketChatAdapter)
|
||||||
|
adapter.rest = MagicMock()
|
||||||
|
adapter.rest.auth_token = "token"
|
||||||
|
adapter._post_message_with_retry = AsyncMock(return_value="msg-123")
|
||||||
|
adapter._user_rooms = {chat_id: [correct_room]}
|
||||||
|
adapter._find_fallback_room_for_user = MagicMock(return_value=None)
|
||||||
|
|
||||||
|
with patch("plugin.adapter._MULTIROOM", return_value=False):
|
||||||
|
result = asyncio.run(adapter.send(chat_id, "Test"))
|
||||||
|
|
||||||
|
assert result.get("success")
|
||||||
|
|
||||||
|
counter_after = routing_counter.get_counts().get("priority0_token_mismatch_skip", 0)
|
||||||
|
assert counter_after > counter_before, (
|
||||||
|
f"routing_counter 'priority0_token_mismatch_skip' should increment on "
|
||||||
|
f"mismatch. Before: {counter_before}, After: {counter_after}"
|
||||||
|
)
|
||||||
|
|||||||
Reference in New Issue
Block a user