Compare commits
8 Commits
main
...
407014db98
| Author | SHA1 | Date | |
|---|---|---|---|
| 407014db98 | |||
| d265624f1c | |||
| 4bfac6a689 | |||
| 1969887eb7 | |||
| 6990419bd0 | |||
| 82c2713929 | |||
| 99fa42df33 | |||
| a9c436a7fa |
+206
-76
@@ -34,6 +34,11 @@ class RocketChatRateLimitError(Exception):
|
||||
"""HTTP 429 Too Many Requests from Rocket.Chat REST API."""
|
||||
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,
|
||||
# aber der Agent läuft in einem separaten Task und sieht sie nicht) ──
|
||||
# P1: Cross-Contamination-Fix — Task-Token + TTL-Sweep
|
||||
@@ -146,7 +151,7 @@ if _MULTIROOM():
|
||||
from archivar.adapter_integration import ArchivarMessageHandler
|
||||
from archivar.conversation_history import ConversationHistory
|
||||
from archivar.multiroom_context import MultiRoomContextRing
|
||||
from archivar.router import room_name_to_topic
|
||||
from archivar.router import room_name_to_topic, RoutingDecision
|
||||
|
||||
# Routing-Counter: immer importieren (keine schweren Abhängigkeiten)
|
||||
from archivar.routing_counter import routing_counter
|
||||
@@ -1158,7 +1163,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
from archivar.presence_engine import PresenceEngine
|
||||
_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"))
|
||||
_pulse_interval = float(os.getenv("ROCKETCHAT_PRESENCE_PULSE_INTERVAL", "1.5"))
|
||||
_pulse_interval = float(os.getenv('ROCKETCHAT_PRESENCE_PULSE_INTERVAL', '5.0'))
|
||||
self._presence_engine = PresenceEngine(
|
||||
rest=self.rest,
|
||||
enabled=_presence_enabled,
|
||||
@@ -3099,7 +3104,37 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
# room_type wird in L1579 aus self._room_info gelesen.
|
||||
_is_dm = (room_type == "d")
|
||||
# P0: routing_text (ohne Quote) für Klassifikation verwenden
|
||||
decision = await self.archivar.classify_and_route(routing_text, origin_room_id=room_id, is_dm=_is_dm)
|
||||
# P0-CRITICAL: asyncio.wait_for(4s) — verhindert Event-Loop-Blockade
|
||||
# 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
|
||||
routing_telemetry.flush()
|
||||
if decision and decision.category:
|
||||
@@ -3118,7 +3153,6 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
if (hasattr(decision, 'target_room') and decision.target_room
|
||||
and not getattr(decision, 'stay_in_room', False)):
|
||||
_THEMATIC_TARGET_ROOM.set(decision.target_room)
|
||||
global _question_counter
|
||||
with _question_counter_lock:
|
||||
_question_counter += 1
|
||||
# ── Ende Kontext-Weitergabe ──────────────────────────────
|
||||
@@ -3159,6 +3193,45 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
logger.info("ROUTING BYPASS: reason=exception_fallback, origin_room=%s", room_id)
|
||||
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 ────────
|
||||
# V7-1: Wenn move_request_sent=True, KEIN Agent-Dispatch.
|
||||
# Der Agent wird erst nach Button-Bestätigung (✅Ja) dispatched,
|
||||
@@ -3326,8 +3399,6 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
|
||||
# Dispatch to gateway handler via base-class handle_message
|
||||
try:
|
||||
from datetime import datetime
|
||||
|
||||
message_type = self._message_type_for(is_button_response)
|
||||
# ── Archivar-Kontext-Weitergabe: Frage-Nr + Zielraum im Prompt ──
|
||||
target_room_id = _THEMATIC_TARGET_ROOM.get()
|
||||
@@ -3378,7 +3449,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
text=contextualized_text,
|
||||
message_type=message_type,
|
||||
message_id=msg_id,
|
||||
timestamp=datetime.fromtimestamp(time.time()),
|
||||
timestamp=datetime.datetime.fromtimestamp(time.time()),
|
||||
raw_message=msg_obj,
|
||||
)
|
||||
event.source = source
|
||||
@@ -4546,8 +4617,6 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
|
||||
# Dispatch to gateway handler via base-class handle_message
|
||||
try:
|
||||
from datetime import datetime
|
||||
|
||||
message_type = self._message_type_for(is_button_response)
|
||||
# ── Archivar-Kontext-Weitergabe: Frage-Nr + Zielraum im Prompt ──
|
||||
target_room_id = _THEMATIC_TARGET_ROOM.get()
|
||||
@@ -4581,7 +4650,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
text=contextualized_text,
|
||||
message_type=message_type,
|
||||
message_id=msg_id,
|
||||
timestamp=datetime.fromtimestamp(time.time()),
|
||||
timestamp=datetime.datetime.fromtimestamp(time.time()),
|
||||
raw_message=msg_obj,
|
||||
)
|
||||
event.source = source
|
||||
@@ -5251,7 +5320,6 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
create_and_verify_fact_store,
|
||||
get_default_fact_store_path,
|
||||
)
|
||||
from datetime import datetime, timezone
|
||||
|
||||
# Option 1: Standard
|
||||
if "Standard" in choice or "1️⃣" in choice or choice == "1":
|
||||
@@ -5290,7 +5358,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
# Option 4: Keine Sammlung
|
||||
elif "Keine" in choice or "4️⃣" in choice or choice == "4":
|
||||
strategy = "none"
|
||||
now_iso = datetime.now(timezone.utc).isoformat()
|
||||
now_iso = datetime.datetime.now(datetime.timezone.utc).isoformat()
|
||||
self.archivar._room_map.set_fact_store_strategy(strategy)
|
||||
self.archivar._room_map.set_fact_store_created_at(now_iso)
|
||||
from archivar.room_map import RoomMap
|
||||
@@ -5321,7 +5389,6 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
create_and_verify_fact_store,
|
||||
verify_existing_fact_store,
|
||||
)
|
||||
from datetime import datetime, timezone
|
||||
|
||||
validation = validate_fact_store_path(single_line)
|
||||
if not validation["valid"]:
|
||||
@@ -5341,7 +5408,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
return
|
||||
|
||||
strategy = "manual"
|
||||
now_iso = datetime.now(timezone.utc).isoformat()
|
||||
now_iso = datetime.datetime.now(datetime.timezone.utc).isoformat()
|
||||
self.archivar._room_map.set_fact_store_strategy(strategy)
|
||||
self.archivar._room_map.set_fact_store_created_at(now_iso)
|
||||
from archivar.room_map import RoomMap
|
||||
@@ -5365,8 +5432,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
|
||||
def _save_fakt_store(self, strategy: str, path: str, operator_room_id: str) -> None:
|
||||
"""Hilfsfunktion: FAKT-Store in room-map.json speichern + doc_store aktualisieren."""
|
||||
from datetime import datetime, timezone
|
||||
now_iso = datetime.now(timezone.utc).isoformat()
|
||||
now_iso = datetime.datetime.now(datetime.timezone.utc).isoformat()
|
||||
self.archivar._room_map.set_fact_store_strategy(strategy)
|
||||
self.archivar._room_map.set_fact_store_created_at(now_iso)
|
||||
from archivar.room_map import RoomMap
|
||||
@@ -6492,39 +6558,75 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
real_room_id = origin
|
||||
logger.debug("[rocketchat] send via ContextVar: %s → %s", chat_id, real_room_id)
|
||||
else:
|
||||
# P1: _room_context als persistenter Fallback (Stream-Retry ContextVar-Reset)
|
||||
# ContextVars sind asyncio-task-lokal — bei Stream-Retries in neuem Task
|
||||
# ist _CURRENT_ORIGIN_ROOM leer. _room_context (global dict) überlebt.
|
||||
# P1 Cross-Contamination-Fix: _get_room_context_origin validiert
|
||||
# Task-Token + TTL, verhindert Cross-Contamination zwischen Räumen.
|
||||
fallback_origin = _get_room_context_origin(chat_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:
|
||||
# Priority 1: Archivar-Kontext — nur für proaktive Nachrichten
|
||||
# ohne vorherige Frage (kein _CURRENT_ORIGIN_ROOM gesetzt).
|
||||
thematic_target = _THEMATIC_TARGET_ROOM.get()
|
||||
if thematic_target:
|
||||
real_room_id = thematic_target
|
||||
logger.debug("[rocketchat] send via Archivar target: %s → %s", chat_id, real_room_id)
|
||||
else:
|
||||
# Priority 2: proaktive Nachricht — use most recent room for this user
|
||||
rooms = self._user_rooms.get(chat_id, [])
|
||||
if rooms:
|
||||
real_room_id = rooms[-1] # last room user was active in
|
||||
logger.debug("[rocketchat] send via user_map (proactive): %s → %s", chat_id, real_room_id)
|
||||
# ── Themenring Phase A: Prio 1 — Raumbezogener Topic-Lookup ──
|
||||
# F6: Erst raumbezogen prüfen (get_active_topic mit origin_room),
|
||||
# dann user-weit fallen (get_active_topic_for_chat).
|
||||
# Verhindert Cross-Contamination: Wenn Andreas in Raum A und B
|
||||
# geschrieben hat, muss die Antwort in A den Topic von A liefern,
|
||||
# nicht den user-weit neuesten (der von B kommen könnte).
|
||||
#
|
||||
# Raumbezogener Lookup: Nutze _room_context um den Raum zu
|
||||
# bestimmen, in den die Antwort gehen soll. Dann hole den
|
||||
# aktiven Topic NUR für diesen Raum — nicht user-weit.
|
||||
_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:
|
||||
# Fallback: try to find any room with recent activity involving this user
|
||||
logger.warning("[rocketchat] No mapped room for %s, attempting fallback", 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)
|
||||
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:
|
||||
# P1: _room_context als persistenter Fallback (Stream-Retry ContextVar-Reset)
|
||||
# ContextVars sind asyncio-task-lokal — bei Stream-Retries in neuem Task
|
||||
# ist _CURRENT_ORIGIN_ROOM leer. _room_context (global dict) überlebt.
|
||||
# P1 Cross-Contamination-Fix: _get_room_context_origin validiert
|
||||
# Task-Token + TTL, verhindert Cross-Contamination zwischen Räumen.
|
||||
fallback_origin = _get_room_context_origin(chat_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:
|
||||
# Priority 1: Archivar-Kontext — nur für proaktive Nachrichten
|
||||
# ohne vorherige Frage (kein _CURRENT_ORIGIN_ROOM gesetzt).
|
||||
thematic_target = _THEMATIC_TARGET_ROOM.get()
|
||||
if thematic_target:
|
||||
real_room_id = thematic_target
|
||||
logger.debug("[rocketchat] send via Archivar target: %s → %s", chat_id, real_room_id)
|
||||
else:
|
||||
# Priority 2: proaktive Nachricht — use most recent room for this user
|
||||
rooms = self._user_rooms.get(chat_id, [])
|
||||
if rooms:
|
||||
real_room_id = rooms[-1] # last room user was active in
|
||||
logger.debug("[rocketchat] send via user_map (proactive): %s → %s", chat_id, real_room_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}")
|
||||
# Fallback: try to find any room with recent activity involving this user
|
||||
logger.warning("[rocketchat] No mapped room for %s, attempting fallback", 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 ──
|
||||
# This allows the agent to request buttons by embedding markup in its
|
||||
@@ -6865,37 +6967,65 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
real_room_id = origin
|
||||
logger.debug("[rocketchat] send_clarify via ContextVar: %s → %s", chat_id, real_room_id)
|
||||
else:
|
||||
# P1: _room_context als persistenter Fallback (Stream-Retry ContextVar-Reset)
|
||||
# P1 Cross-Contamination-Fix: _get_room_context_origin validiert
|
||||
# Task-Token + TTL, verhindert Cross-Contamination zwischen Räumen.
|
||||
fallback_origin = _get_room_context_origin(chat_id)
|
||||
if fallback_origin:
|
||||
real_room_id = fallback_origin
|
||||
routing_counter.increment('contextvar_reset_fallback')
|
||||
logger.info("[rocketchat] send_clarify via _room_context fallback: %s → %s", chat_id, real_room_id)
|
||||
else:
|
||||
# Priority 1: Archivar-Kontext — nur für proaktive Nachrichten
|
||||
# ohne vorherige Frage (kein _CURRENT_ORIGIN_ROOM gesetzt).
|
||||
thematic_target = _THEMATIC_TARGET_ROOM.get()
|
||||
if thematic_target:
|
||||
real_room_id = thematic_target
|
||||
logger.debug("[rocketchat] send_clarify via Archivar target: %s → %s", chat_id, real_room_id)
|
||||
else:
|
||||
# Priority 2: proactive message — use most recent room for this user
|
||||
rooms = self._user_rooms.get(chat_id, [])
|
||||
if rooms:
|
||||
real_room_id = rooms[-1] # last room user was active in
|
||||
logger.debug("[rocketchat] send_clarify via user_map (proactive): %s → %s", chat_id, real_room_id)
|
||||
# ── Themenring Phase A: Prio 1 — Raumbezogener Topic-Lookup ──
|
||||
# F6: Erst raumbezogen prüfen (get_active_topic mit origin_room),
|
||||
# dann user-weit fallen (get_active_topic_for_chat).
|
||||
_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:
|
||||
if _topic_entry.thematic_target:
|
||||
topic_ring_origin = _topic_entry.thematic_target
|
||||
else:
|
||||
# Fallback: try to find any room with recent activity involving this user
|
||||
logger.warning("[rocketchat] No mapped room for %s, attempting fallback", 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)
|
||||
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:
|
||||
# P1: _room_context als persistenter Fallback (Stream-Retry ContextVar-Reset)
|
||||
# P1 Cross-Contamination-Fix: _get_room_context_origin validiert
|
||||
# Task-Token + TTL, verhindert Cross-Contamination zwischen Räumen.
|
||||
fallback_origin = _get_room_context_origin(chat_id)
|
||||
if fallback_origin:
|
||||
real_room_id = fallback_origin
|
||||
routing_counter.increment('contextvar_reset_fallback')
|
||||
logger.info("[rocketchat] send_clarify via _room_context fallback: %s → %s", chat_id, real_room_id)
|
||||
else:
|
||||
# Priority 1: Archivar-Kontext — nur für proaktive Nachrichten
|
||||
# ohne vorherige Frage (kein _CURRENT_ORIGIN_ROOM gesetzt).
|
||||
thematic_target = _THEMATIC_TARGET_ROOM.get()
|
||||
if thematic_target:
|
||||
real_room_id = thematic_target
|
||||
logger.debug("[rocketchat] send_clarify via Archivar target: %s → %s", chat_id, real_room_id)
|
||||
else:
|
||||
# Priority 2: proactive message — use most recent room for this user
|
||||
rooms = self._user_rooms.get(chat_id, [])
|
||||
if rooms:
|
||||
real_room_id = rooms[-1] # last room user was active in
|
||||
logger.debug("[rocketchat] send_clarify via user_map (proactive): %s → %s", chat_id, real_room_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}")
|
||||
# Fallback: try to find any room with recent activity involving this user
|
||||
logger.warning("[rocketchat] No mapped room for %s, attempting fallback", 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
|
||||
# can read long choices that would be truncated in buttons.
|
||||
|
||||
@@ -10,6 +10,7 @@ ClassificationResult zurückgegeben — der Router übernimmt dann den Fallback.
|
||||
from __future__ import annotations
|
||||
|
||||
import abc
|
||||
import concurrent.futures
|
||||
import json
|
||||
import logging
|
||||
import math
|
||||
@@ -151,7 +152,36 @@ class OllamaEmbeddingClient(EmbeddingClient):
|
||||
self._timeout = timeout or OLLAMA_CONFIG["timeout"]
|
||||
|
||||
def get_embedding(self, text: str) -> Optional[List[float]]:
|
||||
"""Call Ollama embeddings API. Returns None on any failure."""
|
||||
"""Call Ollama embeddings API with a hard deadline timeout.
|
||||
|
||||
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"
|
||||
payload = json.dumps(
|
||||
{"model": self._model, "prompt": text}
|
||||
@@ -257,7 +287,36 @@ class OllamaLLMClient(LLMClient):
|
||||
self._timeout = timeout or LLM_CONFIG["timeout"]
|
||||
|
||||
def classify(self, text: str) -> Optional[str]:
|
||||
"""Call Ollama generate API. Returns category or None on any failure."""
|
||||
"""Call Ollama generate API with a real deadline timeout.
|
||||
|
||||
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"
|
||||
payload = json.dumps(
|
||||
{
|
||||
@@ -282,7 +341,7 @@ class OllamaLLMClient(LLMClient):
|
||||
if not response_text:
|
||||
logger.error("Ollama returned empty response")
|
||||
return None
|
||||
|
||||
|
||||
# Trim whitespace and normalize category
|
||||
category = response_text.strip().lower()
|
||||
if category in ("direct_question", "smalltalk", "work_order", "ambiguous"):
|
||||
@@ -327,8 +386,11 @@ direct_question, smalltalk, work_order, oder ambiguous"""
|
||||
def generate(self, prompt: str) -> Optional[str]:
|
||||
"""Generiere eine freie Antwort vom LLM (keine Kategorie-Validierung).
|
||||
|
||||
Sendet den Prompt an Ollama's /api/generate und gibt die Antwort
|
||||
unvalidiert zurück. Wird vom Raum-Router für LLM_ROOM_PROMPT verwendet.
|
||||
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.
|
||||
|
||||
Args:
|
||||
prompt: Der vollständige Prompt (z.B. LLM_ROOM_PROMPT).
|
||||
@@ -336,6 +398,25 @@ direct_question, smalltalk, work_order, oder ambiguous"""
|
||||
Returns:
|
||||
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"
|
||||
payload = json.dumps(
|
||||
{
|
||||
@@ -469,7 +550,17 @@ class IntentClassifier:
|
||||
|
||||
async def _llm_classify(self, text: str, scores: Dict[str, float]) -> Optional[Tuple[str, float]]:
|
||||
import asyncio
|
||||
return await asyncio.to_thread(self._llm_classify_sync, text, scores)
|
||||
try:
|
||||
# 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]]:
|
||||
try:
|
||||
@@ -500,7 +591,17 @@ class IntentClassifier:
|
||||
try:
|
||||
if not self._llm_client or not self._llm_enabled:
|
||||
return None
|
||||
return await asyncio.to_thread(self._llm_client.generate, prompt)
|
||||
# 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).
|
||||
# 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:
|
||||
logger.warning("LLM raw call failed: %s", e)
|
||||
return None
|
||||
@@ -632,7 +733,17 @@ class IntentClassifier:
|
||||
best_score >= CONFIDENCE_THRESHOLDS["CLARIFY_NEEDED"] and
|
||||
best_score < CONFIDENCE_THRESHOLDS["AUTO_ROUTE"]
|
||||
):
|
||||
llm_result = self._llm_classify_sync(text, scores)
|
||||
# P0-CRITICAL: Timeout 15s — muss KLEINER sein als der äußere
|
||||
# 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:
|
||||
final_category, final_score = llm_result
|
||||
llm_verified = True
|
||||
|
||||
@@ -16,7 +16,8 @@ from typing import Dict
|
||||
OLLAMA_CONFIG: dict = {
|
||||
"base_url": os.getenv("ARCHIVAR_EMBEDDING_BASE_URL", "http://localhost:11434"),
|
||||
"model": "nomic-embed-text",
|
||||
"timeout": 10.0, # Sekunden — empirisch: Ø 2.4s, Cold-Start bis 7.8s
|
||||
"timeout": 3.0, # Sekunden — HARD deadline via ThreadPoolExecutor
|
||||
# Muss KLEINER sein als äußerer 20s-Timeout in adapter.py
|
||||
"embedding_dim": 768, # nomic-embed-text produziert 768-dimensionale Vektoren
|
||||
}
|
||||
|
||||
@@ -156,7 +157,8 @@ wird sie entsprechend klassifiziert. Alles andere → FAKT.
|
||||
LLM_CONFIG = {
|
||||
"enabled": os.getenv("ARCHIVAR_ENABLE_LLM", "").strip().lower() in ("1", "true", "yes"),
|
||||
"model": "qwen2.5:7b",
|
||||
"timeout": 30.0, # Iterative Optimierung: Start 30s (19.06.2026)
|
||||
"timeout": 15.0, # HARD deadline via ThreadPoolExecutor.result(timeout=X)
|
||||
# Muss KLEINER sein als äußerer 20s-Timeout in adapter.py
|
||||
"base_url": os.getenv(
|
||||
"ARCHIVAR_LLM_BASE_URL",
|
||||
os.getenv("OLLAMA_BASE_URL", "http://localhost:11434")
|
||||
@@ -333,6 +335,30 @@ RED_FLAG_TIMEOUT: float = float(os.getenv(
|
||||
))
|
||||
"""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) ─────
|
||||
# Wird NICHT mehr verwendet — LLM_ROOM_PROMPT ist der neue Standard.
|
||||
# Bleibt im Code, falls externe Skripte darauf verweisen.
|
||||
|
||||
@@ -162,7 +162,7 @@ class PresenceEngine:
|
||||
rest=None,
|
||||
enabled: bool = True,
|
||||
coalesce_ms: int = 2000,
|
||||
pulse_interval: float = 1.5,
|
||||
pulse_interval: float = 5.0,
|
||||
gateway_state_path: str = "",
|
||||
_clamp_pulse: bool = True,
|
||||
):
|
||||
@@ -719,13 +719,13 @@ class PulseController:
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
pulse_interval: float = 1.5,
|
||||
pulse_interval: float = 5.0,
|
||||
_clamp_pulse: bool = True,
|
||||
):
|
||||
"""Initialize PulseController.
|
||||
|
||||
Args:
|
||||
pulse_interval: Pulse interval in seconds (default 1.5).
|
||||
pulse_interval: Pulse interval in seconds (default 5.0).
|
||||
_clamp_pulse: If True, clamp to 0.5-30s. Set False for testing.
|
||||
"""
|
||||
if _clamp_pulse:
|
||||
@@ -745,6 +745,12 @@ class PulseController:
|
||||
# P1-2 O-2: Async-await bridge
|
||||
self._loop: Optional[asyncio.AbstractEventLoop] = None
|
||||
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 ───────────────────────────────────────────────────────
|
||||
|
||||
@@ -882,7 +888,10 @@ class PulseController:
|
||||
self._pulse_tick()
|
||||
|
||||
# Sleep for pulse interval, checking running flag periodically
|
||||
for _ in range(int(self._pulse_interval * 10)):
|
||||
# P0-CRITICAL: Circuit-Breaker — _current_interval überschreibt
|
||||
# _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():
|
||||
break
|
||||
if self._paused.is_set():
|
||||
@@ -923,8 +932,10 @@ class PulseController:
|
||||
)
|
||||
return
|
||||
|
||||
# P1-2 O-2: Delegate to async path if loop is bound and running
|
||||
if self._loop is not None and self._loop.is_running():
|
||||
# P0-CRITICAL: Default sync — async-Pfad nur wenn explizit aktiviert.
|
||||
# run_coroutine_threadsafe sättigt den ThreadPool und blockiert den
|
||||
# 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:
|
||||
future = asyncio.run_coroutine_threadsafe(
|
||||
self._pulse_tick_async(),
|
||||
@@ -959,10 +970,12 @@ class PulseController:
|
||||
self._ddp.set_status(status)
|
||||
self._last_sent_phase = self._phase
|
||||
self._increment_telemetry()
|
||||
self._record_success()
|
||||
logger.debug("[pulse] _pulse_tick DDP set_status OK: %s", status)
|
||||
return
|
||||
except Exception as e:
|
||||
logger.info("[pulse] _pulse_tick DDP set_status failed: %s", e)
|
||||
self._record_failure()
|
||||
|
||||
# REST fallback for message text
|
||||
if self._rest is not None and getattr(self._rest, 'auth_token', None):
|
||||
@@ -980,9 +993,11 @@ class PulseController:
|
||||
)
|
||||
self._last_sent_phase = self._phase
|
||||
self._increment_telemetry()
|
||||
self._record_success()
|
||||
logger.debug("[pulse] _pulse_tick REST setStatus OK: %s", status)
|
||||
except Exception as e:
|
||||
logger.info("[pulse] _pulse_tick REST setStatus failed: %s", e)
|
||||
self._record_failure()
|
||||
else:
|
||||
logger.debug(
|
||||
"[pulse] _pulse_tick skip: no DDP and no REST available (ddp=%s, rest=%s)",
|
||||
@@ -1007,6 +1022,7 @@ class PulseController:
|
||||
await self._ddp.set_status_async(status, timeout=self._await_timeout)
|
||||
self._last_sent_phase = self._phase
|
||||
self._increment_telemetry()
|
||||
self._record_success()
|
||||
logger.debug("[pulse] _pulse_tick_async DDP set_status_async OK: %s", status)
|
||||
return
|
||||
except Exception as e:
|
||||
@@ -1015,6 +1031,7 @@ class PulseController:
|
||||
"falling back to REST",
|
||||
e,
|
||||
)
|
||||
self._record_failure()
|
||||
|
||||
# REST fallback for message text
|
||||
if self._rest is not None and getattr(self._rest, 'auth_token', None):
|
||||
@@ -1032,14 +1049,47 @@ class PulseController:
|
||||
)
|
||||
self._last_sent_phase = self._phase
|
||||
self._increment_telemetry()
|
||||
self._record_success()
|
||||
logger.debug("[pulse] _pulse_tick_async REST setStatus OK: %s", status)
|
||||
except Exception as e:
|
||||
logger.info("[pulse] _pulse_tick_async REST setStatus failed: %s", e)
|
||||
self._record_failure()
|
||||
else:
|
||||
logger.debug(
|
||||
"[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:
|
||||
"""Increment the heartbeat_pulse telemetry counter.
|
||||
|
||||
|
||||
+52
-23
@@ -1578,8 +1578,17 @@ class BidirectionalRouter:
|
||||
|
||||
# Try LLM — expects room ID directly or "STAY"
|
||||
# Semaphore schützt vor parallelen Ollama-Aufrufen (qwen2.5:7b = single-request)
|
||||
async with self._llm_semaphore:
|
||||
# P0-CRITICAL: Semaphore-Acquire mit 18s Timeout — muss KLEINER sein als
|
||||
# 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)
|
||||
finally:
|
||||
self._llm_semaphore.release()
|
||||
if llm_result is None:
|
||||
return None, False, True # LLM-Aufruf fehlgeschlagen
|
||||
|
||||
@@ -1839,19 +1848,28 @@ class BidirectionalRouter:
|
||||
old_topic=old_topic or "(kein altes Thema)",
|
||||
)
|
||||
|
||||
# LLM-Aufruf mit 5s Timeout
|
||||
# LLM-Aufruf mit 18s Semaphore + 15s LLM-Call Timeout
|
||||
# P0-CRITICAL: Semaphore-Acquire mit 18s Timeout — muss KLEINER sein als
|
||||
# der äußere 20s-Timeout in adapter.py.
|
||||
try:
|
||||
async with self._llm_semaphore:
|
||||
await asyncio.wait_for(self._llm_semaphore.acquire(), timeout=18.0)
|
||||
except asyncio.TimeoutError:
|
||||
logger.warning("V7-4: LLM-Semaphore Timeout (18s) → Fallback: NEU")
|
||||
return None
|
||||
try:
|
||||
try:
|
||||
llm_result = await asyncio.wait_for(
|
||||
self._classifier._llm_raw(prompt),
|
||||
timeout=5.0,
|
||||
timeout=15.0,
|
||||
)
|
||||
except asyncio.TimeoutError:
|
||||
logger.warning("V7-4: LLM-Check Timeout (5s) → Fallback: NEU")
|
||||
return None
|
||||
except Exception as e:
|
||||
logger.warning("V7-4: LLM-Check fehlgeschlagen: %s → Fallback: NEU", e)
|
||||
return None
|
||||
except asyncio.TimeoutError:
|
||||
logger.warning("V7-4: LLM-Check Timeout (15s) → Fallback: NEU")
|
||||
return None
|
||||
except Exception as e:
|
||||
logger.warning("V7-4: LLM-Check fehlgeschlagen: %s → Fallback: NEU", e)
|
||||
return None
|
||||
finally:
|
||||
self._llm_semaphore.release()
|
||||
|
||||
if llm_result is None:
|
||||
logger.warning("V7-4: LLM-Check returned None → Fallback: NEU")
|
||||
@@ -2189,24 +2207,35 @@ async def validate_sentence_marker(
|
||||
v7_3_state=v7_3_state,
|
||||
)
|
||||
|
||||
# ── LLM-Aufruf mit 5s Timeout ─────────────────────────────────────
|
||||
# ── LLM-Aufruf mit 18s Semaphore + 15s LLM-Call Timeout ──────────
|
||||
# P0-CRITICAL: Semaphore-Acquire mit 18s Timeout — muss KLEINER sein als
|
||||
# der äußere 20s-Timeout in adapter.py.
|
||||
try:
|
||||
async with llm_semaphore:
|
||||
llm_result = await asyncio.wait_for(
|
||||
classifier._llm_raw(prompt),
|
||||
timeout=5.0,
|
||||
)
|
||||
await asyncio.wait_for(llm_semaphore.acquire(), timeout=18.0)
|
||||
except asyncio.TimeoutError:
|
||||
logger.warning(
|
||||
"A1b Stufe 4/5: LLM-Validierung Timeout (5s) → Fallback: unentscheidbar"
|
||||
)
|
||||
return None
|
||||
except Exception as e:
|
||||
logger.warning(
|
||||
"A1b Stufe 4/5: LLM-Validierung fehlgeschlagen: %s → Fallback: unentscheidbar",
|
||||
e,
|
||||
"A1b Stufe 4/5: LLM-Semaphore Timeout (18s) → Fallback: unentscheidbar"
|
||||
)
|
||||
return None
|
||||
try:
|
||||
try:
|
||||
llm_result = await asyncio.wait_for(
|
||||
classifier._llm_raw(prompt),
|
||||
timeout=15.0,
|
||||
)
|
||||
except asyncio.TimeoutError:
|
||||
logger.warning(
|
||||
"A1b Stufe 4/5: LLM-Call Timeout (15s) → Fallback: unentscheidbar"
|
||||
)
|
||||
return None
|
||||
except Exception as e:
|
||||
logger.warning(
|
||||
"A1b Stufe 4/5: LLM-Validierung fehlgeschlagen: %s → Fallback: unentscheidbar",
|
||||
e,
|
||||
)
|
||||
return None
|
||||
finally:
|
||||
llm_semaphore.release()
|
||||
|
||||
if llm_result is None:
|
||||
logger.warning("A1b Stufe 4/5: LLM returned None → Fallback: unentscheidbar")
|
||||
|
||||
@@ -0,0 +1,779 @@
|
||||
"""
|
||||
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()
|
||||
@@ -0,0 +1,529 @@
|
||||
"""
|
||||
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,210 @@
|
||||
"""
|
||||
P0: Test that _process_incoming() does not crash with UnboundLocalError.
|
||||
|
||||
Root cause: local `from datetime import datetime` inside _process_incoming()
|
||||
shadowed the module-level `import datetime`. Python's scoping rules treat
|
||||
`datetime` as a local variable for the ENTIRE function, so any use of
|
||||
`datetime.datetime.now()` BEFORE the local import raises UnboundLocalError.
|
||||
|
||||
This test verifies that _process_incoming() can be called with a minimal
|
||||
mock message without hitting the UnboundLocalError.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock, AsyncMock
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
|
||||
|
||||
def _build_minimal_adapter():
|
||||
"""Build a RocketChatAdapter with minimal mocks for _process_incoming."""
|
||||
os.environ["MULTIROOM_AGENT"] = "true"
|
||||
os.environ["ARCHIVAR_ROOM_MAP_PATH"] = "/tmp/test_p0_datetime_room_map.json"
|
||||
os.environ["ARCHIVAR_STATE_PATH"] = "/tmp/test_p0_datetime_state.json"
|
||||
os.environ["ROCKETCHAT_BASE_URL"] = "https://rocket.example.com"
|
||||
os.environ["ROCKETCHAT_USER"] = "testbot"
|
||||
os.environ["ROCKETCHAT_PASSWORD"] = "testpass"
|
||||
|
||||
from plugin.adapter import RocketChatAdapter, RocketChatREST
|
||||
from plugin.archivar.conversation_history import ConversationHistory
|
||||
from plugin.archivar.multiroom_context import MultiRoomContextRing
|
||||
from plugin.archivar.adapter_integration import ArchivarMessageHandler
|
||||
from plugin.archivar.room_map import RoomMap
|
||||
|
||||
adapter = RocketChatAdapter.__new__(RocketChatAdapter)
|
||||
|
||||
adapter.config = MagicMock()
|
||||
adapter.config.extra = {}
|
||||
adapter.platform = "rocketchat"
|
||||
adapter.base_url = os.getenv("ROCKETCHAT_BASE_URL", "")
|
||||
adapter.user = os.getenv("ROCKETCHAT_USER", "")
|
||||
adapter.password = os.getenv("ROCKETCHAT_PASSWORD", "")
|
||||
adapter.rest = RocketChatREST(adapter.base_url)
|
||||
adapter.ddp = None
|
||||
adapter._auth_token = None
|
||||
adapter._user_id = None
|
||||
adapter._rooms = []
|
||||
adapter._subscribed_rooms = set()
|
||||
adapter._listen_task = None
|
||||
adapter._status_timer = None
|
||||
adapter._last_activity = 0.0
|
||||
adapter._shutdown_event = threading.Event()
|
||||
adapter._room_info = {}
|
||||
adapter._pending_clarifies = {}
|
||||
adapter._user_rooms = {}
|
||||
adapter._rooms_with_pending_questions = set()
|
||||
adapter._excluded_room_ids = set()
|
||||
adapter._last_server_activity = 0.0
|
||||
adapter._health_check_timer = None
|
||||
adapter._last_ddp_ping_ok = False
|
||||
adapter._running = False
|
||||
|
||||
adapter._conversation_history = ConversationHistory(max_size=10)
|
||||
adapter._multiroom_context = MultiRoomContextRing(max_entries=10)
|
||||
adapter.archivar = ArchivarMessageHandler(
|
||||
send_callback=lambda *a, **kw: None,
|
||||
button_send_callback=lambda *a, **kw: None,
|
||||
conversation_history=adapter._conversation_history,
|
||||
)
|
||||
|
||||
# Create a minimal room-map.json
|
||||
tmpdir = tempfile.mkdtemp()
|
||||
room_map_path = Path(tmpdir) / "room-map.json"
|
||||
import json
|
||||
room_map_data = {
|
||||
"version": 5,
|
||||
"rooms": {
|
||||
"room_test": {
|
||||
"name": "#Test-Room",
|
||||
"theme": "Test Room",
|
||||
"keywords_100": [],
|
||||
"keywords_context": [],
|
||||
"catch_all": True,
|
||||
},
|
||||
},
|
||||
"excluded_rooms": [],
|
||||
"butler_mode": "cognitive",
|
||||
"fact_store_path": str(Path(tmpdir) / "docs"),
|
||||
}
|
||||
room_map_path.write_text(json.dumps(room_map_data))
|
||||
adapter.archivar._room_map = RoomMap.load(room_map_path)
|
||||
|
||||
adapter._pending_move_requests = {}
|
||||
adapter._session_room_preferences = {}
|
||||
adapter._recent_auto_routes = {}
|
||||
adapter._explicit_switch_sticky = {}
|
||||
adapter._clarify_state = {}
|
||||
adapter._pending_clarify_dispatch = {}
|
||||
adapter._onboarding_state = {}
|
||||
adapter._room_map_summary = ""
|
||||
|
||||
# Mock the REST client
|
||||
mock_rest = MagicMock(spec=RocketChatREST)
|
||||
mock_rest.auth_token = "fake-token"
|
||||
mock_rest.user_id = "fake-user-id"
|
||||
mock_rest.post_message = MagicMock(return_value="msg_12345")
|
||||
mock_rest.get_rooms = MagicMock(return_value=[
|
||||
{"id": "room_test", "name": "Test-Room", "type": "c"},
|
||||
])
|
||||
adapter.rest = mock_rest
|
||||
|
||||
adapter._room_info = {
|
||||
"room_test": {"name": "Test-Room", "type": "c"},
|
||||
}
|
||||
|
||||
# Mock _dispatch_agent and handle_message
|
||||
adapter._dispatch_agent = AsyncMock()
|
||||
adapter.handle_message = AsyncMock()
|
||||
|
||||
# Initialize Archivar
|
||||
asyncio.run(adapter.archivar.initialize())
|
||||
|
||||
# Mock gateway types
|
||||
import plugin.adapter as _adapter_mod
|
||||
_adapter_mod.MessageType = type('MessageType', (), {
|
||||
'TEXT': 'text', 'BUTTON_CLICK': 'button_click',
|
||||
})
|
||||
_adapter_mod.MessageEvent = type('MessageEvent', (), {
|
||||
'__init__': lambda self, **kw: setattr(self, '__dict__', kw),
|
||||
})
|
||||
_adapter_mod.SessionSource = type('SessionSource', (), {
|
||||
'__init__': lambda self, **kw: setattr(self, '__dict__', kw),
|
||||
})
|
||||
_adapter_mod.Platform = str
|
||||
_adapter_mod.PlatformConfig = type('PlatformConfig', (), {
|
||||
'__init__': lambda self, **kw: setattr(self, '__dict__', kw),
|
||||
})
|
||||
|
||||
return adapter
|
||||
|
||||
|
||||
class TestP0DatetimeUnboundLocalError(unittest.TestCase):
|
||||
"""P0: _process_incoming() must not crash with UnboundLocalError.
|
||||
|
||||
The bug: local `from datetime import datetime` inside _process_incoming()
|
||||
shadowed the module-level `import datetime`. Python treats `datetime` as
|
||||
a local variable for the ENTIRE function scope, so any use of
|
||||
`datetime.datetime.now()` BEFORE the local import raises UnboundLocalError.
|
||||
|
||||
This test calls _process_incoming() with a minimal mock message and
|
||||
verifies no UnboundLocalError is raised.
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.adapter = _build_minimal_adapter()
|
||||
|
||||
def test_process_incoming_no_unbound_local_error(self):
|
||||
"""_process_incoming() should not raise UnboundLocalError for datetime."""
|
||||
msg_obj = {
|
||||
"_id": "msg_test_001",
|
||||
"rid": "room_test",
|
||||
"msg": "Hallo, das ist eine Test-Nachricht",
|
||||
"u": {"username": "andreas", "_id": "user_andreas"},
|
||||
}
|
||||
|
||||
# This should NOT raise UnboundLocalError
|
||||
try:
|
||||
asyncio.run(self.adapter._process_incoming(msg_obj))
|
||||
except UnboundLocalError as e:
|
||||
self.fail(
|
||||
f"_process_incoming() raised UnboundLocalError: {e}\n"
|
||||
"Root cause: local 'from datetime import datetime' shadows "
|
||||
"module-level 'import datetime'."
|
||||
)
|
||||
|
||||
def test_process_incoming_with_button_response_no_unbound_local_error(self):
|
||||
"""Button response path should also not raise UnboundLocalError."""
|
||||
msg_obj = {
|
||||
"_id": "msg_btn_001",
|
||||
"rid": "room_test",
|
||||
"msg": "FAKT::1",
|
||||
"u": {"username": "andreas", "_id": "user_andreas"},
|
||||
}
|
||||
|
||||
try:
|
||||
asyncio.run(self.adapter._process_incoming(msg_obj))
|
||||
except UnboundLocalError as e:
|
||||
self.fail(
|
||||
f"_process_incoming() raised UnboundLocalError on button path: {e}"
|
||||
)
|
||||
|
||||
def test_datetime_module_still_accessible(self):
|
||||
"""Verify that datetime.datetime.now() works (module-level import intact)."""
|
||||
import datetime
|
||||
result = datetime.datetime.now(datetime.timezone.utc)
|
||||
self.assertIsNotNone(result)
|
||||
# Verify it's a datetime object, not a module
|
||||
self.assertTrue(hasattr(result, 'isoformat'))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user