From f3574014d5bc5c9d7d8b45c629aea0c01c9aae2e Mon Sep 17 00:00:00 2001 From: "Bernd (Hermes)" Date: Tue, 28 Jul 2026 20:04:01 +0200 Subject: [PATCH] fix: Priority 0 Task-Token-Validierung in send() und send_clarify() MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bug: Nach Auto-Route + Widerspruch ging die 2. send()-Antwort in den falschen Raum (Auto-Route-Ziel statt Ursprungsraum). Root Cause: _CURRENT_ORIGIN_ROOM kann in neuen asyncio-Tasks einen stale Wert vom Parent-Task erben (Auto-Route-copy_context). send() Priority 0 verwendete diesen Wert blind, ohne den Task-Token gegen _room_context zu validieren. Fix: - send() Priority 0: Pre-Read-Validierung — _CURRENT_TASK_TOKEN gegen _room_context[chat_id]['task_token'] prüfen. Bei Mismatch Priority 0 skippen, normale ContextVar-Logik weiterlaufen lassen. - send_clarify() Priority 0: analoge Validierung. - Telemetrie: routing_counter.increment('priority0_token_mismatch_skip') bei jedem Mismatch. - Backward-Compat: _room_context-Einträge ohne task_token werden wie 'kein Token' behandelt (Priority 0 greift normal). Tests (6 neu, alle grün): - test_send_priority0_token_match - test_send_priority0_token_mismatch - test_send_priority0_no_stored_token - test_send_clarify_token_mismatch - test_auto_route_then_widerspruch_answer_in_origin (E2E) - test_priority0_mismatch_telemetry Keine Änderungen an _set_room_context_origin / _get_room_context_origin oder den 10 _CURRENT_ORIGIN_ROOM.set-Stellen. --- plugin/adapter.py | 40 +++++ tests/test_adapter.py | 352 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 392 insertions(+) diff --git a/plugin/adapter.py b/plugin/adapter.py index ddf4a29..c616a2a 100644 --- a/plugin/adapter.py +++ b/plugin/adapter.py @@ -6499,7 +6499,27 @@ class RocketChatAdapter(BasePlatformAdapter): 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) @@ -6872,7 +6892,27 @@ class RocketChatAdapter(BasePlatformAdapter): real_room_id = chat_id if chat_id.startswith("user:"): # Priority 0: ContextVar from the message that triggered this turn + # P1 Cross-Contamination-Fix: Task-Token-Validierung VOR Verwendung. + # _CURRENT_ORIGIN_ROOM kann in neuen asyncio-Tasks einen stale Wert + # vom Parent-Task erben. Wir validieren gegen _room_context task_token, + # um Cross-Contamination (Auto-Route → Widerspruch → falscher Raum) zu + # verhindern. origin = _CURRENT_ORIGIN_ROOM.get() + if origin: + # Pre-Read-Validierung: Task-Token-Match prüfen + current_token = _CURRENT_TASK_TOKEN.get() + ctx_entry = _room_context.get(chat_id, {}) + stored_token = ctx_entry.get("task_token", "") + # Token-Mismatch: _CURRENT_ORIGIN_ROOM ist stale → skippen, + # normale ContextVar-Logik weiterlaufen lassen + if current_token and stored_token and current_token != stored_token: + routing_counter.increment('priority0_token_mismatch_skip') + logger.info( + "[rocketchat] send_clarify Priority 0 token mismatch for %s — " + "skipping stale ContextVar, falling through to _room_context", + chat_id, + ) + origin = "" # Force fallthrough if origin: real_room_id = origin logger.debug("[rocketchat] send_clarify via ContextVar: %s → %s", chat_id, real_room_id) diff --git a/tests/test_adapter.py b/tests/test_adapter.py index 82556f2..591bddc 100644 --- a/tests/test_adapter.py +++ b/tests/test_adapter.py @@ -450,3 +450,355 @@ class TestFileBlockStripping: ) assert "Download:" not in result assert "Schau dir das an:" in result + + +# ═══════════════════════════════════════════════════════════════════════════ +# P1: Priority 0 Task-Token-Validierung in send() und send_clarify() +# ═══════════════════════════════════════════════════════════════════════════ + + +class TestSendPriority0TokenValidation: + """Pre-Read-Validierung: Task-Token-Match in send() Priority 0. + + Szenario: _CURRENT_ORIGIN_ROOM kann in neuen asyncio-Tasks einen + stale Wert vom Parent-Task erben (Auto-Route → Widerspruch → + falscher Raum). Die Validierung prüft _CURRENT_TASK_TOKEN gegen + _room_context[chat_id]['task_token'] und skipped Priority 0 bei + Mismatch. + """ + + def test_send_priority0_token_match(self): + """Task-Token match → Priority 0 greift normal (ContextVar gewinnt).""" + import asyncio + import contextvars + import uuid + from unittest.mock import AsyncMock, MagicMock, patch + + from plugin.adapter import ( + RocketChatAdapter, + _CURRENT_ORIGIN_ROOM, + _CURRENT_TASK_TOKEN, + _room_context, + ) + + chat_id = "user:andreas" + correct_room = "rc-test-automated" + token = str(uuid.uuid4()) + + # Setup: ContextVar + _room_context mit gleichem Token + _CURRENT_ORIGIN_ROOM.set(correct_room) + _CURRENT_TASK_TOKEN.set(token) + _room_context.clear() + _room_context[chat_id] = { + "origin_room": correct_room, + "task_token": token, + "timestamp": "2026-07-28T12:00:00+00:00", + } + + adapter = RocketChatAdapter.__new__(RocketChatAdapter) + adapter.rest = MagicMock() + adapter.rest.auth_token = "token" + adapter._post_message_with_retry = AsyncMock(return_value="msg-123") + adapter._user_rooms = {} + adapter._find_fallback_room_for_user = MagicMock(return_value=None) + + async def _run(): + with patch("plugin.adapter._MULTIROOM", return_value=False): + return await adapter.send(chat_id, "Test response") + + ctx = contextvars.copy_context() + with patch("plugin.adapter._MULTIROOM", return_value=False): + result = asyncio.run(ctx.run(_run)) + + assert result.get("success"), f"send() should succeed, got: {result}" + adapter._post_message_with_retry.assert_called_once() + call_room = adapter._post_message_with_retry.call_args[0][0] + assert call_room == correct_room, ( + f"Priority 0 token match: expected {correct_room}, got {call_room}" + ) + + def test_send_priority0_token_mismatch(self): + """Task-Token mismatch → Priority 0 wird skippt, ContextVar ignoriert.""" + import asyncio + import uuid + from unittest.mock import AsyncMock, MagicMock, patch + + from plugin.adapter import ( + RocketChatAdapter, + _CURRENT_ORIGIN_ROOM, + _CURRENT_TASK_TOKEN, + _room_context, + ) + + chat_id = "user:andreas" + stale_room = "Drohnenkurs" # vom Auto-Route-Dispatch + correct_room = "rc-test-automated" # vom Widerspruch-Dispatch + auto_route_token = str(uuid.uuid4()) # token vom Auto-Route-copy_context + widerspruch_token = str(uuid.uuid4()) # token vom Widerspruch-Dispatch + + # Setup: ContextVar hat STALE Wert (Drohnenkurs) mit Auto-Route-Token, + # _room_context hat aktuellen Wert (rc-test-automated) mit Widerspruch-Token. + # Die Tokens sind VERSCHIEDEN → Mismatch → Priority 0 wird geskippt. + _CURRENT_ORIGIN_ROOM.set(stale_room) + _CURRENT_TASK_TOKEN.set(auto_route_token) + _room_context.clear() + _room_context[chat_id] = { + "origin_room": correct_room, + "task_token": widerspruch_token, # ANDERES Token! + "timestamp": "2026-07-28T12:00:00+00:00", + } + + adapter = RocketChatAdapter.__new__(RocketChatAdapter) + adapter.rest = MagicMock() + adapter.rest.auth_token = "token" + adapter._post_message_with_retry = AsyncMock(return_value="msg-123") + adapter._user_rooms = {chat_id: [correct_room]} + adapter._find_fallback_room_for_user = MagicMock(return_value=None) + + with patch("plugin.adapter._MULTIROOM", return_value=False): + result = asyncio.run(adapter.send(chat_id, "Test response")) + + assert result.get("success"), f"send() should succeed, got: {result}" + # Priority 0 sollte geskippt werden → fällt durch zu _room_context + # _get_room_context_origin validiert Token-Match → gibt correct_room zurück + adapter._post_message_with_retry.assert_called_once() + call_room = adapter._post_message_with_retry.call_args[0][0] + assert call_room == correct_room, ( + f"Priority 0 token mismatch: expected fallback to {correct_room}, " + f"got stale {call_room}" + ) + + def test_send_priority0_no_stored_token(self): + """_room_context ohne task_token → Priority 0 greift normal (backward-compat).""" + import asyncio + from unittest.mock import AsyncMock, MagicMock, patch + + from plugin.adapter import ( + RocketChatAdapter, + _CURRENT_ORIGIN_ROOM, + _CURRENT_TASK_TOKEN, + _room_context, + ) + + chat_id = "user:andreas" + correct_room = "rc-test-automated" + + # Setup: ContextVar gesetzt, _room_context OHNE task_token (alter Eintrag) + _CURRENT_ORIGIN_ROOM.set(correct_room) + _CURRENT_TASK_TOKEN.set("some-token") + _room_context.clear() + _room_context[chat_id] = { + "origin_room": "irrelevant-old-room", + # KEIN task_token — backward-compat: alter Eintrag vor P1-Fix + "timestamp": "2026-07-28T12:00:00+00:00", + } + + adapter = RocketChatAdapter.__new__(RocketChatAdapter) + adapter.rest = MagicMock() + adapter.rest.auth_token = "token" + adapter._post_message_with_retry = AsyncMock(return_value="msg-123") + adapter._user_rooms = {} + adapter._find_fallback_room_for_user = MagicMock(return_value=None) + + with patch("plugin.adapter._MULTIROOM", return_value=False): + result = asyncio.run(adapter.send(chat_id, "Test response")) + + assert result.get("success"), f"send() should succeed, got: {result}" + # Kein stored_token → keine Mismatch-Erkennung → Priority 0 greift normal + adapter._post_message_with_retry.assert_called_once() + call_room = adapter._post_message_with_retry.call_args[0][0] + assert call_room == correct_room, ( + f"Priority 0 no stored token: expected {correct_room}, got {call_room}" + ) + + +class TestSendClarifyTokenValidation: + """Pre-Read-Validierung: Task-Token-Match in send_clarify() Priority 0.""" + + def test_send_clarify_token_mismatch(self): + """Task-Token mismatch in send_clarify → Priority 0 wird skippt.""" + import asyncio + import uuid + from unittest.mock import AsyncMock, MagicMock, patch + + from plugin.adapter import ( + RocketChatAdapter, + _CURRENT_ORIGIN_ROOM, + _CURRENT_TASK_TOKEN, + _room_context, + ) + + chat_id = "user:andreas" + stale_room = "Drohnenkurs" + correct_room = "rc-test-automated" + auto_route_token = str(uuid.uuid4()) + widerspruch_token = str(uuid.uuid4()) + + # Setup: ContextVar stale mit Auto-Route-Token, + # _room_context aktuell mit Widerspruch-Token (VERSCHIEDEN) + _CURRENT_ORIGIN_ROOM.set(stale_room) + _CURRENT_TASK_TOKEN.set(auto_route_token) + _room_context.clear() + _room_context[chat_id] = { + "origin_room": correct_room, + "task_token": widerspruch_token, + "timestamp": "2026-07-28T12:00:00+00:00", + } + + adapter = RocketChatAdapter.__new__(RocketChatAdapter) + adapter.rest = MagicMock() + adapter.rest.auth_token = "token" + adapter._post_message_with_retry = AsyncMock(return_value="msg-123") + adapter._user_rooms = {chat_id: [correct_room]} + adapter._find_fallback_room_for_user = MagicMock(return_value=None) + adapter._rooms_with_pending_questions = set() + + with patch("plugin.adapter._MULTIROOM", return_value=False): + result = asyncio.run( + adapter.send_clarify( + chat_id=chat_id, + question="Test question?", + choices=["Option A", "Option B"], + clarify_id="clarify-1", + session_key="session-1", + ) + ) + + assert result.get("success"), f"send_clarify() should succeed, got: {result}" + adapter._post_message_with_retry.assert_called_once() + call_room = adapter._post_message_with_retry.call_args[0][0] + assert call_room == correct_room, ( + f"send_clarify token mismatch: expected {correct_room}, got {call_room}" + ) + + +class TestAutoRouteWiderspruchEndToEnd: + """End-to-End: Auto-Route → Widerspruch → Antwort im Ursprungsraum. + + Reproduziert den Bug: Auto-Route setzt _room_context auf Drohnenkurs, + Widerspruch dispatcht neu in rc-test-automated. Ohne Fix geht die + 2. Antwort nach Drohnenkurs (stale ContextVar). Mit Fix wird Priority 0 + bei Token-Mismatch geskippt und _get_room_context_origin liefert den + korrekten Raum. + """ + + def test_auto_route_then_widerspruch_answer_in_origin(self): + """Auto-Route setzt context, Widerspruch dispatcht neu, + Antwort geht in Ursprungsraum (rc-test-automated).""" + import asyncio + import uuid + from unittest.mock import AsyncMock, MagicMock, patch + + from plugin.adapter import ( + RocketChatAdapter, + _CURRENT_ORIGIN_ROOM, + _CURRENT_TASK_TOKEN, + _room_context, + _set_room_context_origin, + ) + + chat_id = "user:andreas" + origin_room = "rc-test-automated" + auto_route_target = "Drohnenkurs" + + # ── Phase 1: Auto-Route ────────────────────────────────────── + # Auto-Route setzt _CURRENT_ORIGIN_ROOM + _room_context auf Drohnenkurs + _CURRENT_ORIGIN_ROOM.set(auto_route_target) + auto_route_token = _set_room_context_origin(chat_id, auto_route_target) + + # ── Phase 2: Widerspruch ───────────────────────────────────── + # Widerspruch erkannt → Thema zurückholen + # _CURRENT_ORIGIN_ROOM zurück auf Ursprungsraum + _CURRENT_ORIGIN_ROOM.set(origin_room) + widerspruch_token = _set_room_context_origin(chat_id, origin_room) + + # ── Phase 3: _dispatch_agent (Widerspruch) ─────────────────── + # _dispatch_agent setzt _room_context erneut (mit neuem Token) + dispatch_token = _set_room_context_origin(chat_id, origin_room) + + # ── Phase 4: Simuliere 2. send() in Task mit Auto-Route-Kontext ── + # Der 2. send() läuft in einem asyncio-Task, der vom Auto-Route- + # copy_context() erbt. _CURRENT_ORIGIN_ROOM = Drohnenkurs (stale), + # _CURRENT_TASK_TOKEN = auto_route_token (stale). + # _room_context hat aber den Widerspruch-Dispatch-Eintrag + # (rc-test-automated, dispatch_token). + # → Token-Mismatch → Priority 0 wird geskippt. + _CURRENT_ORIGIN_ROOM.set(auto_route_target) # STALE vom Auto-Route-Kontext + _CURRENT_TASK_TOKEN.set(auto_route_token) # STALE vom Auto-Route-Kontext + + adapter = RocketChatAdapter.__new__(RocketChatAdapter) + adapter.rest = MagicMock() + adapter.rest.auth_token = "token" + adapter._post_message_with_retry = AsyncMock(return_value="msg-123") + adapter._user_rooms = {chat_id: [origin_room]} + adapter._find_fallback_room_for_user = MagicMock(return_value=None) + + with patch("plugin.adapter._MULTIROOM", return_value=False): + result = asyncio.run(adapter.send(chat_id, "2. Antwort")) + + assert result.get("success"), f"send() should succeed, got: {result}" + adapter._post_message_with_retry.assert_called_once() + call_room = adapter._post_message_with_retry.call_args[0][0] + assert call_room == origin_room, ( + f"E2E Widerspruch: expected answer in origin {origin_room}, " + f"got {call_room} (stale auto-route target)" + ) + + +class TestPriority0MismatchTelemetry: + """Telemetrie: routing_counter.increment bei Token-Mismatch.""" + + def test_priority0_mismatch_telemetry(self): + """Verifiziert routing_counter.increment('priority0_token_mismatch_skip') + bei jedem Token-Mismatch in send() Priority 0.""" + import asyncio + import uuid + from unittest.mock import AsyncMock, MagicMock, patch + + from plugin.adapter import ( + RocketChatAdapter, + _CURRENT_ORIGIN_ROOM, + _CURRENT_TASK_TOKEN, + _room_context, + ) + # MUST import from same path as adapter.py (archivar.routing_counter) + # to get the same singleton instance + from archivar.routing_counter import routing_counter + + chat_id = "user:andreas" + stale_room = "Drohnenkurs" + correct_room = "rc-test-automated" + auto_route_token = str(uuid.uuid4()) + widerspruch_token = str(uuid.uuid4()) + + # Setup: Mismatch — ContextVar stale mit Auto-Route-Token, + # _room_context aktuell mit Widerspruch-Token (VERSCHIEDEN) + _CURRENT_ORIGIN_ROOM.set(stale_room) + _CURRENT_TASK_TOKEN.set(auto_route_token) + _room_context.clear() + _room_context[chat_id] = { + "origin_room": correct_room, + "task_token": widerspruch_token, + "timestamp": "2026-07-28T12:00:00+00:00", + } + + # Snapshot counter before + counter_before = routing_counter.get_counts().get("priority0_token_mismatch_skip", 0) + + adapter = RocketChatAdapter.__new__(RocketChatAdapter) + adapter.rest = MagicMock() + adapter.rest.auth_token = "token" + adapter._post_message_with_retry = AsyncMock(return_value="msg-123") + adapter._user_rooms = {chat_id: [correct_room]} + adapter._find_fallback_room_for_user = MagicMock(return_value=None) + + with patch("plugin.adapter._MULTIROOM", return_value=False): + result = asyncio.run(adapter.send(chat_id, "Test")) + + assert result.get("success") + + counter_after = routing_counter.get_counts().get("priority0_token_mismatch_skip", 0) + assert counter_after > counter_before, ( + f"routing_counter 'priority0_token_mismatch_skip' should increment on " + f"mismatch. Before: {counter_before}, After: {counter_after}" + )