diff --git a/plugin/adapter.py b/plugin/adapter.py index dc09b1b..f5e640c 100644 --- a/plugin/adapter.py +++ b/plugin/adapter.py @@ -37,6 +37,19 @@ class RocketChatRateLimitError(Exception): _room_context: Dict[str, Dict[str, str]] = {} # chat_id → {thematic_target, origin_room} _room_context_lock = threading.Lock() + +def _set_room_context_origin(chat_id: str, room_id: str) -> None: + """Atomar _room_context[chat_id][\"origin_room\"] = room_id setzen. + + Helper-Funktion für alle 9 Stellen, die _CURRENT_ORIGIN_ROOM.set() + aufrufen. Stellt sicher, dass der persistente Fallback (_room_context) + immer synchron mit der ContextVar gesetzt wird — keine Race-Condition + durch getrenntes setdefault + Index-Zuweisung. + """ + with _room_context_lock: + ctx = _room_context.setdefault(chat_id, {}) + ctx["origin_room"] = room_id + def _MULTIROOM() -> bool: """Laufzeit-Auswertung von MULTIROOM_AGENT (nicht beim Import, da .env via systemd EnvironmentFile erst später geladen wird).""" return os.getenv("MULTIROOM_AGENT", "true").strip().lower() not in ("false", "0", "no", "off") @@ -1997,9 +2010,7 @@ class RocketChatAdapter(BasePlatformAdapter): # ContextVars sind asyncio-task-lokal — bei Stream-Retries in neuem Task # geht _CURRENT_ORIGIN_ROOM verloren. _room_context (global dict) überlebt. virtual_chat_id = f"user:{username}" - with _room_context_lock: - ctx = _room_context.setdefault(virtual_chat_id, {}) - ctx["origin_room"] = room_id + _set_room_context_origin(virtual_chat_id, room_id) # ── V8.6 P1a: PresenceEngine — mark_busy_started (Honeymoon-Timer) ── # Graceful degradation: wenn _presence_engine nicht existiert @@ -2219,10 +2230,7 @@ class RocketChatAdapter(BasePlatformAdapter): _CURRENT_ORIGIN_ROOM.set(room_id) _THEMATIC_TARGET_ROOM.set("") # P1: _room_context als persistenter Fallback - vcid = f"user:{pending['username']}" - with _room_context_lock: - ctx = _room_context.setdefault(vcid, {}) - ctx["origin_room"] = room_id + _set_room_context_origin(f"user:{pending['username']}", room_id) routing_counter.increment('archivar_clarify_dispatched') logger.info( "[rocketchat] FIX 2: Clarify dispatch — " @@ -2325,10 +2333,7 @@ class RocketChatAdapter(BasePlatformAdapter): _CURRENT_ORIGIN_ROOM.set(move_req["target_room"]) _THEMATIC_TARGET_ROOM.set(move_req["target_room"]) # P1: _room_context als persistenter Fallback - vcid = f"user:{username}" - with _room_context_lock: - ctx = _room_context.setdefault(vcid, {}) - ctx["origin_room"] = move_req["target_room"] + _set_room_context_origin(f"user:{username}", move_req["target_room"]) forwarded = True feedback_type = "confirm" # ── V8.3-5: Topic für Sticky extrahieren ────────────── @@ -2536,10 +2541,7 @@ class RocketChatAdapter(BasePlatformAdapter): # _CURRENT_ORIGIN_ROOM: User stays HERE (origin room) _CURRENT_ORIGIN_ROOM.set(room_id) # P1: _room_context als persistenter Fallback - vcid = f"user:{username}" - with _room_context_lock: - ctx = _room_context.setdefault(vcid, {}) - ctx["origin_room"] = room_id + _set_room_context_origin(f"user:{username}", room_id) # _THEMATIC_TARGET_ROOM: NOT set — no topic change await self._dispatch_agent( text=origin_text, @@ -2659,10 +2661,7 @@ class RocketChatAdapter(BasePlatformAdapter): _CURRENT_ORIGIN_ROOM.set(origin_room_id) _THEMATIC_TARGET_ROOM.set("") # P1: _room_context als persistenter Fallback - vcid = f"user:{username}" - with _room_context_lock: - ctx = _room_context.setdefault(vcid, {}) - ctx["origin_room"] = origin_room_id + _set_room_context_origin(f"user:{username}", origin_room_id) # d. Sticky löschen self._session_room_preferences.pop(origin_room_id, None) # e. Ring: move_gc(target → origin) — Rückholung @@ -2759,10 +2758,7 @@ class RocketChatAdapter(BasePlatformAdapter): _CURRENT_ORIGIN_ROOM.set(target_room_id) _THEMATIC_TARGET_ROOM.set(target_room_id) # P1: _room_context als persistenter Fallback - vcid = f"user:{username}" - with _room_context_lock: - ctx = _room_context.setdefault(vcid, {}) - ctx["origin_room"] = target_room_id + _set_room_context_origin(f"user:{username}", target_room_id) # b. Sticky setzen: 30 Min, sticky_topic = 'explizit-wechsel' self._session_room_preferences[room_id] = { "target_room": target_room_id, @@ -2923,6 +2919,8 @@ class RocketChatAdapter(BasePlatformAdapter): await self._post_message_with_retry(target_room_id, target_txt) _CURRENT_ORIGIN_ROOM.set(target_room_id) _THEMATIC_TARGET_ROOM.set(target_room_id) + # P1: _room_context als persistenter Fallback + _set_room_context_origin(f"user:{username}", target_room_id) routing_counter.increment('session_sticky_auto_route') logger.info( "[rocketchat] V8.3-5: Topic-Scoped Sticky active — " @@ -2968,6 +2966,8 @@ class RocketChatAdapter(BasePlatformAdapter): await self._post_message_with_retry(target_room_id, target_txt) _CURRENT_ORIGIN_ROOM.set(target_room_id) _THEMATIC_TARGET_ROOM.set(target_room_id) + # P1: _room_context als persistenter Fallback + _set_room_context_origin(f"user:{username}", target_room_id) routing_counter.increment('session_sticky_auto_route') logger.info( "[rocketchat] V8.3-5: Topic-Scoped Sticky active — " @@ -3140,6 +3140,8 @@ class RocketChatAdapter(BasePlatformAdapter): # Setze _CURRENT_ORIGIN_ROOM auf Zielraum → Agent antwortet dort _CURRENT_ORIGIN_ROOM.set(target_room_id) _THEMATIC_TARGET_ROOM.set(target_room_id) + # P1: _room_context als persistenter Fallback + _set_room_context_origin(f"user:{username}", target_room_id) forwarded = True routing_counter.increment('auto_route_dispatched') logger.info( @@ -3194,6 +3196,8 @@ class RocketChatAdapter(BasePlatformAdapter): # ── _CURRENT_ORIGIN_ROOM setzen ────────────────────────────────── if not forwarded: _CURRENT_ORIGIN_ROOM.set(room_id) + # P1: _room_context als persistenter Fallback + _set_room_context_origin(f"user:{username}", room_id) # ── V8.4: Red Flag — Pre-Dispatch-Hook ────────────────────────── # Wenn der Archivar Red Flag gesetzt hat (is_red_flag=True), @@ -6348,9 +6352,7 @@ class RocketChatAdapter(BasePlatformAdapter): _THEMATIC_TARGET_ROOM.set(target_room_id) # P1: _room_context als persistenter Fallback if chat_id.startswith("user:"): - with _room_context_lock: - ctx = _room_context.setdefault(chat_id, {}) - ctx["origin_room"] = target_room_id + _set_room_context_origin(chat_id, target_room_id) # Strip ROOM: prefix from content content = _strip_red_flag_prefix(content) # ── Ring-Feedback: Agent-Entscheidung trainieren ── @@ -6764,33 +6766,33 @@ class RocketChatAdapter(BasePlatformAdapter): # 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: Archivar-Kontext — wenn der Archivar einen thematischen - # Zielraum gesetzt hat, geht die Antwort dorthin (Agent-Autonomie). - thematic_target = _THEMATIC_TARGET_ROOM.get() - if thematic_target and thematic_target != _CURRENT_ORIGIN_ROOM.get(): - real_room_id = thematic_target - logger.debug("[rocketchat] send via Archivar target: %s → %s", chat_id, real_room_id) + # Priority 0: ContextVar from the message that triggered this turn + origin = _CURRENT_ORIGIN_ROOM.get() + if origin: + real_room_id = origin + logger.debug("[rocketchat] send_clarify via ContextVar: %s → %s", chat_id, real_room_id) else: - # Priority 1: ContextVar from the message that triggered this turn - origin = _CURRENT_ORIGIN_ROOM.get() - if origin: - real_room_id = origin - logger.debug("[rocketchat] send via ContextVar: %s → %s", chat_id, real_room_id) + # P1: _room_context als persistenter Fallback (Stream-Retry ContextVar-Reset) + with _room_context_lock: + ctx = _room_context.get(chat_id, {}) + fallback_origin = ctx.get("origin_room", "") + 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: - # P1: _room_context als persistenter Fallback (Stream-Retry ContextVar-Reset) - with _room_context_lock: - ctx = _room_context.get(chat_id, {}) - fallback_origin = ctx.get("origin_room", "") - 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) + # 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 via user_map (proactive): %s → %s", chat_id, real_room_id) + logger.debug("[rocketchat] send_clarify via user_map (proactive): %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) diff --git a/plugin/archivar/tests/test_v8_1_p1_contextvar.py b/plugin/archivar/tests/test_v8_1_p1_contextvar.py index 538f52e..64fed36 100644 --- a/plugin/archivar/tests/test_v8_1_p1_contextvar.py +++ b/plugin/archivar/tests/test_v8_1_p1_contextvar.py @@ -483,6 +483,151 @@ class TestRoomContextFallback(unittest.TestCase): f"nicht _user_rooms[-1] ({wrong_room}). Bekam: {real_room_id}" ) + # ── Test 8: send_clarify mit leerer ContextVar → _room_context Fallback ── + + def test_send_clarify_with_empty_contextvar_falls_back_to_room_context(self): + """send_clarify() mit leerer ContextVar → _room_context Fallback. + + Deckt die Inkonsistenz ab: send_clarify() hatte _THEMATIC_TARGET_ROOM + VOR _room_context geprüft (falsch). Nach dem Fix prüft send_clarify() + _CURRENT_ORIGIN_ROOM → _room_context → _THEMATIC_TARGET_ROOM, + exakt wie send(). + """ + chat_id = "user:alice" + correct_room = "room_clarify_123" + thematic_room = "room_thematic_456" + + # ContextVars sind LEER (simuliert Stream-Retry in neuem Task) + self._CURRENT_ORIGIN_ROOM.set("") + self._THEMATIC_TARGET_ROOM.set(thematic_room) # Archivar hat thematischen Zielraum + + # _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 + self.adapter._user_rooms = {} + self.adapter._find_fallback_room_for_user = MagicMock(return_value=None) + + result = asyncio.run( + self.adapter.send_clarify( + chat_id=chat_id, + question="Test question?", + choices=["Yes", "No"], + clarify_id="clarify_001", + session_key="session_001", + ) + ) + + # Verify: send_clarify() hat _post_message_with_retry mit dem + # _room_context Fallback aufgerufen, NICHT mit _THEMATIC_TARGET_ROOM. + 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_clarify() sollte _room_context ({correct_room}) priorisieren, " + f"nicht _THEMATIC_TARGET_ROOM ({thematic_room}). Bekam: {real_room_id}" + ) + + # ── Test 9: Concurrency — 10 parallele Tasks, konsistente Werte ───── + + def test_concurrency_parallel_set_and_read(self): + """10 parallele Tasks: 5 set + 5 read, alle sehen konsistenten Wert. + + Stresstest für _set_room_context_origin() und _room_context_lock. + Keine Race-Condition: alle Reader sehen den zuletzt geschriebenen Wert. + """ + chat_id = "user:concurrent" + base_room = "room_concurrent" + + async def _run(): + results = [] + + async def setter(room_suffix: str): + """Setze _room_context auf einen bestimmten Raum.""" + room = f"{base_room}_{room_suffix}" + from plugin.adapter import _set_room_context_origin + _set_room_context_origin(chat_id, room) + results.append(("set", room_suffix, room)) + + async def reader(expected_suffix: str): + """Lies _room_context und prüfe Konsistenz.""" + from plugin.adapter import _room_context, _room_context_lock + with _room_context_lock: + ctx = _room_context.get(chat_id, {}) + origin = ctx.get("origin_room", "") + results.append(("read", expected_suffix, origin)) + + # 5 Setter + 5 Reader parallel starten + tasks = [] + for i in range(5): + tasks.append(asyncio.create_task(setter(f"s{i}"))) + for i in range(5): + tasks.append(asyncio.create_task(reader(f"s{i}"))) + + await asyncio.gather(*tasks) + return results + + results = asyncio.run(_run()) + + # Alle Setter haben ihren Wert gesetzt + setters = [r for r in results if r[0] == "set"] + self.assertEqual(len(setters), 5, "Alle 5 Setter sollten durchlaufen") + + # Alle Reader haben einen nicht-leeren Wert gesehen + readers = [r for r in results if r[0] == "read"] + self.assertEqual(len(readers), 5, "Alle 5 Reader sollten durchlaufen") + for _, _, origin in readers: + self.assertTrue( + origin.startswith(base_room), + f"Reader sollte einen Raum mit Präfix {base_room} sehen, " + f"bekam: {origin}" + ) + + # ── Test 10: Stale-Entry — _room_context gewinnt gegen _user_rooms ── + + def test_stale_entry_room_context_wins_over_user_rooms(self): + """_room_context hat Raum X, _user_rooms hat Raum Y, ContextVar leer + → _room_context gewinnt (Doku-Test). + + Szenario: User war zuletzt in Raum Y (_user_rooms[-1]), aber die + aktuelle Frage kam aus Raum X (_room_context). ContextVar ist leer + (Stream-Retry). send() muss _room_context priorisieren. + """ + chat_id = "user:stale" + room_context_room = "room_X_correct" + user_rooms_room = "room_Y_wrong" + + # ContextVars sind LEER + self._CURRENT_ORIGIN_ROOM.set("") + self._THEMATIC_TARGET_ROOM.set("") + + # _room_context hat Raum X (korrekt) + with self._room_context_lock: + self._room_context[chat_id] = {"origin_room": room_context_room} + + # _user_rooms hat Raum Y (falsch, veraltet) + self.adapter._user_rooms = { + chat_id: [user_rooms_room] + } + + 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 _room_context (Raum X) verwendet, nicht _user_rooms (Raum Y) + 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, room_context_room, + f"send() sollte _room_context ({room_context_room}) priorisieren, " + f"nicht _user_rooms[-1] ({user_rooms_room}). Bekam: {real_room_id}" + ) + if __name__ == "__main__": unittest.main()