fix(P1): _room_context als persistenter Fallback bei Stream-Retry ContextVar-Reset
Block A — send()/send_clarify() lesen _room_context:
- In send() (Z.6395-6421): nach ContextVar-Prio-0, vor thematic_target
und _user_rooms, _room_context[chat_id]["origin_room"] als Fallback.
- In send_clarify() (Z.6773-6803): gleicher Fallback nach ContextVar.
- Telemetrie: routing_counter.increment("contextvar_reset_fallback")
wenn dieser Pfad greift.
Block B — _room_context konsequent füllen (7 Stellen):
- _process_incoming (Z.1996-2002): IMMER setzen bei jeder Nachricht.
- Clarify dispatch (Z.2221-2225): pending["username"] → vcid.
- move_req confirm (Z.2327-2331): username → vcid.
- stay_here dispatch (Z.2538-2542): username → vcid.
- Widerspruch-Rückkehr (Z.2661-2665): username → vcid.
- Auto-Route (Z.2761-2765): username → vcid.
- Red Flag (Z.6349-6353): chat_id direkt (in send() verfügbar).
- Alle Zugriffe unter _room_context_lock (Thread-Safety).
Block C — Tests (test_v8_1_p1_contextvar.py):
- Test 6: send_with_empty_contextvar_falls_back_to_room_context
- Test 7: stream_retry_simulates_fresh_contextvar
- Beide: ContextVar leer, _room_context hat origin_room,
_user_rooms falsch/leer → korrektes Routing über _room_context.
Tests: 1332 passed, 3 pre-existing failures, 2 skipped.
This commit is contained in:
@@ -311,5 +311,178 @@ class TestDispatchTaskContextVar(unittest.TestCase):
|
||||
)
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════════
|
||||
# P1: _room_context als persistenter Fallback (Stream-Retry ContextVar-Reset)
|
||||
# ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestRoomContextFallback(unittest.TestCase):
|
||||
"""Tests für _room_context als Fallback bei ContextVar-Reset (P1)."""
|
||||
|
||||
def setUp(self):
|
||||
"""Build a minimal mock adapter for send() testing."""
|
||||
import threading
|
||||
from unittest.mock import MagicMock, AsyncMock
|
||||
|
||||
os.environ["MULTIROOM_AGENT"] = "true"
|
||||
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
|
||||
|
||||
self.adapter = RocketChatAdapter.__new__(RocketChatAdapter)
|
||||
self.adapter.config = MagicMock()
|
||||
self.adapter.config.extra = {}
|
||||
self.adapter.platform = "rocketchat"
|
||||
self.adapter.base_url = "https://rocket.example.com"
|
||||
self.adapter.user = "testbot"
|
||||
self.adapter.password = "testpass"
|
||||
self.adapter.rest = MagicMock(spec=RocketChatREST)
|
||||
self.adapter.rest.auth_token = "fake-token"
|
||||
self.adapter.rest.user_id = "fake-user-id"
|
||||
self.adapter.rest.post_message = MagicMock(return_value="msg_12345")
|
||||
self.adapter.ddp = None
|
||||
self.adapter._auth_token = None
|
||||
self.adapter._user_id = None
|
||||
self.adapter._rooms = []
|
||||
self.adapter._subscribed_rooms = set()
|
||||
self.adapter._listen_task = None
|
||||
self.adapter._status_timer = None
|
||||
self.adapter._last_activity = 0.0
|
||||
self.adapter._shutdown_event = threading.Event()
|
||||
self.adapter._room_info = {}
|
||||
self.adapter._pending_clarifies = {}
|
||||
self.adapter._user_rooms = {}
|
||||
self.adapter._rooms_with_pending_questions = set()
|
||||
self.adapter._excluded_room_ids = set()
|
||||
self.adapter._last_server_activity = 0.0
|
||||
self.adapter._health_check_timer = None
|
||||
self.adapter._last_ddp_ping_ok = False
|
||||
self.adapter._running = False
|
||||
self.adapter._pending_move_requests = {}
|
||||
self.adapter._session_room_preferences = {}
|
||||
self.adapter._recent_auto_routes = {}
|
||||
self.adapter._explicit_switch_sticky = {}
|
||||
self.adapter._clarify_state = {}
|
||||
self.adapter._pending_clarify_dispatch = {}
|
||||
self.adapter._onboarding_state = {}
|
||||
self.adapter._room_map_summary = ""
|
||||
self.adapter._post_message_with_retry = AsyncMock(return_value=True)
|
||||
self.adapter._find_fallback_room_for_user = MagicMock(return_value=None)
|
||||
self.adapter._replace_slash_with_double_colon = MagicMock(
|
||||
side_effect=lambda x: x
|
||||
)
|
||||
self.adapter._conversation_history = None # not needed for routing tests
|
||||
self.adapter._multiroom_context = None
|
||||
self.adapter.archivar = None
|
||||
|
||||
# Import module-level state
|
||||
from plugin.adapter import (
|
||||
_CURRENT_ORIGIN_ROOM,
|
||||
_THEMATIC_TARGET_ROOM,
|
||||
_room_context,
|
||||
_room_context_lock,
|
||||
_RED_FLAG_PENDING,
|
||||
)
|
||||
self._CURRENT_ORIGIN_ROOM = _CURRENT_ORIGIN_ROOM
|
||||
self._THEMATIC_TARGET_ROOM = _THEMATIC_TARGET_ROOM
|
||||
self._room_context = _room_context
|
||||
self._room_context_lock = _room_context_lock
|
||||
self._RED_FLAG_PENDING = _RED_FLAG_PENDING
|
||||
|
||||
def tearDown(self):
|
||||
"""Clean up module-level state between tests."""
|
||||
self._CURRENT_ORIGIN_ROOM.set("")
|
||||
self._THEMATIC_TARGET_ROOM.set("")
|
||||
self._RED_FLAG_PENDING.set({})
|
||||
with self._room_context_lock:
|
||||
self._room_context.clear()
|
||||
|
||||
# ── Test 6: send() mit leerer ContextVar fällt auf _room_context zurück ──
|
||||
|
||||
def test_send_with_empty_contextvar_falls_back_to_room_context(self):
|
||||
"""ContextVar leer, _room_context hat origin_room → send verwendet _room_context.
|
||||
|
||||
Szenario: Stream-Retry erzeugt neuen asyncio-Task. _CURRENT_ORIGIN_ROOM
|
||||
ist leer (nicht vererbt). _room_context (global dict) hat aber noch
|
||||
den origin_room aus _process_incoming. send() soll diesen Fallback nutzen.
|
||||
"""
|
||||
chat_id = "user:alice"
|
||||
correct_room = "room_correct_123"
|
||||
|
||||
# ContextVars sind LEER (simuliert Stream-Retry in neuem Task)
|
||||
self._CURRENT_ORIGIN_ROOM.set("")
|
||||
self._THEMATIC_TARGET_ROOM.set("")
|
||||
|
||||
# _room_context hat den korrekten Raum (wurde in _process_incoming gesetzt)
|
||||
with self._room_context_lock:
|
||||
self._room_context[chat_id] = {"origin_room": correct_room}
|
||||
|
||||
# _user_rooms ist LEER (kein Fallback über user_map)
|
||||
self.adapter._user_rooms = {}
|
||||
|
||||
# _find_fallback_room_for_user gibt None zurück (kein weiterer Fallback)
|
||||
self.adapter._find_fallback_room_for_user = MagicMock(return_value=None)
|
||||
|
||||
result = asyncio.run(
|
||||
self.adapter.send(chat_id=chat_id, content="Test response")
|
||||
)
|
||||
|
||||
# Verify: send() hat _post_message_with_retry mit dem korrekten Raum aufgerufen
|
||||
self.adapter._post_message_with_retry.assert_called_once()
|
||||
call_args = self.adapter._post_message_with_retry.call_args
|
||||
real_room_id = call_args[0][0]
|
||||
self.assertEqual(
|
||||
real_room_id, correct_room,
|
||||
f"send() sollte _room_context Fallback nutzen: {correct_room}, "
|
||||
f"bekam aber: {real_room_id}"
|
||||
)
|
||||
|
||||
# ── Test 7: Stream-Retry simuliert ContextVar-Reset ─────────────────
|
||||
|
||||
def test_stream_retry_simulates_fresh_contextvar(self):
|
||||
"""Simuliere ContextVar-Reset (leer), _room_context hat Wert,
|
||||
_user_rooms falsch → Korrektes Routing über _room_context.
|
||||
|
||||
Szenario: User ist in mehreren Räumen. _user_rooms hat den
|
||||
FALSCHEN Raum als letzten Eintrag. ContextVar ist leer (Reset).
|
||||
_room_context hat den KORREKTEN Raum. send() muss _room_context
|
||||
priorisieren, nicht _user_rooms[-1].
|
||||
"""
|
||||
chat_id = "user:bob"
|
||||
correct_room = "room_dm_bob"
|
||||
wrong_room = "room_general"
|
||||
|
||||
# ContextVars sind LEER (simuliert Stream-Retry in neuem Task)
|
||||
self._CURRENT_ORIGIN_ROOM.set("")
|
||||
self._THEMATIC_TARGET_ROOM.set("")
|
||||
|
||||
# _room_context hat den korrekten Raum
|
||||
with self._room_context_lock:
|
||||
self._room_context[chat_id] = {"origin_room": correct_room}
|
||||
|
||||
# _user_rooms hat den FALSCHEN Raum als letzten Eintrag
|
||||
self.adapter._user_rooms = {
|
||||
chat_id: [wrong_room, "room_other"]
|
||||
}
|
||||
|
||||
# _find_fallback_room_for_user gibt None zurück
|
||||
self.adapter._find_fallback_room_for_user = MagicMock(return_value=None)
|
||||
|
||||
result = asyncio.run(
|
||||
self.adapter.send(chat_id=chat_id, content="Test response")
|
||||
)
|
||||
|
||||
# Verify: send() hat _post_message_with_retry mit dem KORREKTEN Raum aufgerufen
|
||||
self.adapter._post_message_with_retry.assert_called_once()
|
||||
call_args = self.adapter._post_message_with_retry.call_args
|
||||
real_room_id = call_args[0][0]
|
||||
self.assertEqual(
|
||||
real_room_id, correct_room,
|
||||
f"send() sollte _room_context ({correct_room}) priorisieren, "
|
||||
f"nicht _user_rooms[-1] ({wrong_room}). Bekam: {real_room_id}"
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
Reference in New Issue
Block a user