From 54edbb57f732d3e169648ced904a446ba17d4606 Mon Sep 17 00:00:00 2001 From: "Bernd (Hermes)" Date: Thu, 30 Jul 2026 08:59:19 +0200 Subject: [PATCH] =?UTF-8?q?P5=20V9.x:=20P1a/P1b/P1c=20=E2=80=94=20Gate-Rel?= =?UTF-8?q?ease-Symmetrie,=20Sweep-Cancel,=20Re-create-Guard?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit P1a: try/finally in send() und send_clarify() für symmetrisches Gate-Release - _gate_acquired Flag trackt ob try_acquire den Eintrag erstellt hat - finally-Block released nur wenn _gate_acquired=True und task_token gesetzt - Verhindert hängende Gate-Einträge bei Exceptions in send()/send_clarify() P1b: _gate_sweep_task.cancel() in disconnect() - Sweep-Loop wird vor _mark_disconnected() gecancelled - self._running = False gesetzt (Sweep-Loop prüft _running Flag) - Verhindert dass Sweep-Task nach disconnect() weiterläuft P1c: Sweep-Task-Check vor Re-create in connect() - Prüft ob _gate_sweep_task existiert und nicht done() ist - Cancelled alten Task vor create_task() des neuen - Verhindert doppelte Sweep-Tasks bei Reconnect --- plugin/adapter.py | 690 ++++++++++++++++++++++++---------------------- 1 file changed, 365 insertions(+), 325 deletions(-) diff --git a/plugin/adapter.py b/plugin/adapter.py index 4451e29..62c1492 100644 --- a/plugin/adapter.py +++ b/plugin/adapter.py @@ -1932,6 +1932,9 @@ class RocketChatAdapter(BasePlatformAdapter): self._running = True self._listen_task = asyncio.create_task(self._listen_loop()) # P5 V9.x W2: OutboundGate Sweep-Loop (asyncio.create_task, nicht threading.Timer) + # ── P1c: Sweep-Task-Check vor Re-create ── + if self._gate_sweep_task is not None and not self._gate_sweep_task.done(): + self._gate_sweep_task.cancel() self._gate_sweep_task = asyncio.create_task(self._gate_sweep_loop()) self._last_activity = time.time() logger.info("[rocketchat] Listen loop started, _running=%s", self._running) @@ -6512,6 +6515,12 @@ class RocketChatAdapter(BasePlatformAdapter): return text async def disconnect(self) -> None: + # ── P1b: Gate-Sweep-Task sauber beenden ── + if hasattr(self, '_gate_sweep_task') and self._gate_sweep_task is not None: + self._gate_sweep_task.cancel() + self._gate_sweep_task = None + self._running = False # P1b: Sweep-Loop nutzt _running Flag + self._mark_disconnected() self._shutdown_event.set() if self._status_timer: @@ -6599,6 +6608,7 @@ class RocketChatAdapter(BasePlatformAdapter): if origin: _gate_room_id = origin task_token = _CURRENT_TASK_TOKEN.get() + _gate_acquired = False # P1a: track whether WE created the gate entry if task_token and hasattr(self, '_outbound_gate') and self._outbound_gate is not None: from archivar.outbound_gate import GateDecision decision = await self._outbound_gate.try_acquire(_gate_room_id, task_token) @@ -6635,225 +6645,239 @@ class RocketChatAdapter(BasePlatformAdapter): _gate_room_id[:8], active_name, ) return SendResult(success=True, message_id="quick_reply") + # Fell through: decision.allow is True — track if WE created the entry + # (gate_clear = we own it; same_room_same_token = someone else owns it) + _gate_acquired = (decision.reason == "gate_clear") - # ── P1-6: ::-Prefix für Dangerous-Command-Meldungen ────────── - # Hermes Core sendet Meldungen mit /approve, /deny etc. - # Rocket.Chat unterstützt keine /-Befehle → :: Varianten einsetzen. - content = self._replace_slash_with_double_colon(content) + # ── P1a: try/finally für symmetrisches Gate-Release ───────── + # Bei Exception in send() hängt sonst der Gate-Eintrag. + try: + # ── P1-6: ::-Prefix für Dangerous-Command-Meldungen ────────── + # Hermes Core sendet Meldungen mit /approve, /deny etc. + # Rocket.Chat unterstützt keine /-Befehle → :: Varianten einsetzen. + content = self._replace_slash_with_double_colon(content) - # ── Virtual → Real Room Translation ───────────────────────── - # chat_id from Hermes session is virtual (e.g. "user:alice"). - # We must resolve it to a real Rocket.Chat room_id for REST API. - real_room_id = chat_id - if chat_id.startswith("user:"): - # Priority 0: _CURRENT_ORIGIN_ROOM — Antwort geht IMMER dorthin, - # wo die Frage gestellt wurde. - # P1 Cross-Contamination-Fix: Task-Token-Validierung VOR Verwendung. - # _CURRENT_ORIGIN_ROOM kann in neuen asyncio-Tasks einen stale Wert - # vom Parent-Task erben. Wir validieren gegen _room_context task_token, - # um Cross-Contamination (Auto-Route → Widerspruch → falscher Raum) zu - # verhindern. - origin = _CURRENT_ORIGIN_ROOM.get() - if origin: - # Pre-Read-Validierung: Task-Token-Match prüfen - current_token = _CURRENT_TASK_TOKEN.get() - ctx_entry = _room_context.get(chat_id, {}) - stored_token = ctx_entry.get("task_token", "") - # Token-Mismatch: _CURRENT_ORIGIN_ROOM ist stale → skippen, - # normale ContextVar-Logik weiterlaufen lassen - if current_token and stored_token and current_token != stored_token: - routing_counter.increment('priority0_token_mismatch_skip') - logger.info( - "[rocketchat] send Priority 0 token mismatch for %s — " - "skipping stale ContextVar, falling through to _room_context", - chat_id, - ) - origin = "" # Force fallthrough - if origin: - 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) + # ── Virtual → Real Room Translation ───────────────────────── + # chat_id from Hermes session is virtual (e.g. "user:alice"). + # We must resolve it to a real Rocket.Chat room_id for REST API. + real_room_id = chat_id + if chat_id.startswith("user:"): + # Priority 0: _CURRENT_ORIGIN_ROOM — Antwort geht IMMER dorthin, + # wo die Frage gestellt wurde. + # P1 Cross-Contamination-Fix: Task-Token-Validierung VOR Verwendung. + # _CURRENT_ORIGIN_ROOM kann in neuen asyncio-Tasks einen stale Wert + # vom Parent-Task erben. Wir validieren gegen _room_context task_token, + # um Cross-Contamination (Auto-Route → Widerspruch → falscher Raum) zu + # verhindern. + origin = _CURRENT_ORIGIN_ROOM.get() + if origin: + # Pre-Read-Validierung: Task-Token-Match prüfen + current_token = _CURRENT_TASK_TOKEN.get() + ctx_entry = _room_context.get(chat_id, {}) + stored_token = ctx_entry.get("task_token", "") + # Token-Mismatch: _CURRENT_ORIGIN_ROOM ist stale → skippen, + # normale ContextVar-Logik weiterlaufen lassen + if current_token and stored_token and current_token != stored_token: + routing_counter.increment('priority0_token_mismatch_skip') + logger.info( + "[rocketchat] send Priority 0 token mismatch for %s — " + "skipping stale ContextVar, falling through to _room_context", + chat_id, + ) + origin = "" # Force fallthrough + if origin: + real_room_id = origin + logger.debug("[rocketchat] send via ContextVar: %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) + # 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 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) + # 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: - # 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) + # 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 - # response text, without requiring the gateway to pass metadata. - # Syntax: [[BUTTONS:yes_no]]Your question here[[/BUTTONS]] - # [[BUTTONS:custom]]Option A|Option B|Option C[[/BUTTONS]] - _btn_re = re.compile( - r'\[\[BUTTONS:(?P