fix(P-108c): Send-Pfad-Härtung — Antwort-Ziel MUSS Origin-Raum sein
Root Cause (Rainer-Review t_cfe5d9d6): send()/send_clarify() nutzten
_THEMATIC_TARGET_ROOM als Prio-2-Zielraum. Bei Stream-Retry-Subtasks /
Token-Mismatch fielen Prio 0 (_CURRENT_ORIGIN_ROOM) und Prio 1
(_room_context-TTL) durch -> Prio 2 griff -> Antwort im falschen Raum
(Andreas-Fund 29.08. 10:50: ProtonBridge-Frage 69f8beae -> Antwort
6a19b0ff).
Fix:
1. send() + send_clarify(): _THEMATIC_TARGET_ROOM (Prio 2) entfernt für
user-basierte Antworten. Fallback ist jetzt der letzte bekannte Raum
des Users (user_rooms-Map) — NIEMALS der Archivar-Sticky-Target.
2. B2-Branch (Z.4122-4139): _THEMATIC_TARGET_ROOM.set('') +
_CURRENT_ORIGIN_ROOM.set(room_id) explizit — Sticky-Reset bei
Origin-Gewinnung (Defense-in-Depth).
Tests: test_p108c_send_path.py (5 Tests, RED->GREEN validiert).
PoC-Test 1 reproduzierte den Bug exakt (Log 'send via Archivar target:
user:testuser -> room_b') BEVOR der Fix griff.
This commit is contained in:
+46
-40
@@ -4137,6 +4137,14 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
# (Setter B) den Sticky NICHT ungeprüft erneuert.
|
||||
self._sticky_bypassed_this_turn = True
|
||||
_should_classify = False
|
||||
# P-108c: Defense-in-Depth — Sticky-Reset bei
|
||||
# Origin-Gewinnung. _THEMATIC_TARGET_ROOM darf keinen
|
||||
# stale Wert aus einem früheren Turn tragen, sonst
|
||||
# greift send() Prio 2 und leitet die Antwort in den
|
||||
# falschen Raum. _CURRENT_ORIGIN_ROOM explizit auf den
|
||||
# Origin-Raum setzen (konsistent mit Stay-Here-Logik).
|
||||
_THEMATIC_TARGET_ROOM.set("")
|
||||
_CURRENT_ORIGIN_ROOM.set(room_id)
|
||||
else:
|
||||
# Thema matcht → Sticky greift
|
||||
# V8.1.1 R1: Catch-All-Guard — nicht in Catch-All-Raum auto-routen
|
||||
@@ -8778,28 +8786,29 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
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)
|
||||
# P-108c: _THEMATIC_TARGET_ROOM (Archivar-Sticky-Target) darf
|
||||
# bei user-basierten Antworten NIEMALS als Zielraum greifen.
|
||||
# Der Wert kann aus einem früheren Turn (Feature-97) oder
|
||||
# einem fremden Task-Kontext stammen und würde die Antwort
|
||||
# in den falschen Raum leiten (Andreas-Fund 29.08. 10:50).
|
||||
# Prio 2 ist NUR für DIREKTE Raum-Chats / proaktive Nachrichten
|
||||
# gedacht — bei user:*-Antworten ist der letzte bekannte Raum
|
||||
# des Users (user_rooms-Map) die korrekte Fallback-Quelle.
|
||||
# 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:
|
||||
# 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)
|
||||
# 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:
|
||||
# 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}")
|
||||
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
|
||||
@@ -9193,28 +9202,25 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
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)
|
||||
# P-108c: _THEMATIC_TARGET_ROOM darf bei user-basierten
|
||||
# Clarify-Antworten NIEMALS als Zielraum greifen (gleiche
|
||||
# Bug-Klasse wie send()). Fallback ist der letzte bekannte
|
||||
# Raum des Users.
|
||||
# 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:
|
||||
# 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)
|
||||
# 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:
|
||||
# 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}")
|
||||
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.
|
||||
|
||||
@@ -0,0 +1,264 @@
|
||||
"""
|
||||
P-108c: Send-Pfad-Schutz — Antwort-Ziel MUSS Origin-Raum sein.
|
||||
|
||||
Root Cause (Rainer-Review t_cfe5d9d6): Der Dispatch-Pfad ist durch
|
||||
P-108/P-108a geschützt (B2-Bypass, _sticky_bypassed_this_turn), aber der
|
||||
SEND-Pfad löst das Ziel weiterhin über _THEMATIC_TARGET_ROOM auf.
|
||||
|
||||
send() in adapter.py nutzt _THEMATIC_TARGET_ROOM als Prio-2-Zielraum. Bei
|
||||
Stream-Retry-Subtasks / Token-Mismatch fallen Prio 0 (_CURRENT_ORIGIN_ROOM)
|
||||
und Prio 1 (_room_context-TTL) durch -> Prio 2 greift -> Antwort im falschen
|
||||
Raum.
|
||||
|
||||
Empirie (29.08., 10:50): ProtonBridge-Frage in 69f8beae -> Antwort in
|
||||
6a19b0ff (rocketchat-plugin). Beweis: msg=wjErDY7qLGwEGaZMQ.
|
||||
|
||||
Fix-Design (Rainer, verbindlich):
|
||||
1. B2-Branch (Z.4122-4139): _THEMATIC_TARGET_ROOM.set("") +
|
||||
_CURRENT_ORIGIN_ROOM.set(room_id) explizit — Sticky-Reset bei
|
||||
Origin-Gewinnung.
|
||||
2. send()-Haertung: Prio 2 (_THEMATIC_TARGET_ROOM) nur fuer DIREKTE
|
||||
Raum-Chats, NIEMALS fuer user-basierte Antworten (user:andreas etc.).
|
||||
|
||||
Diese Tests validieren H1/H2 BEVOR der Fix implementiert wird (RED).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
# Ensure the plugin package is importable (mirrors test_v8_3_4.py)
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
|
||||
|
||||
import plugin.adapter as adapter_mod # noqa: E402
|
||||
from test_v8_3_4 import _build_mock_adapter, _make_minimal_room_map_json # noqa: E402
|
||||
|
||||
|
||||
class TestP108cSendPath(unittest.TestCase):
|
||||
"""P-108c: send() darf bei user-basierten Antworten NICHT auf
|
||||
_THEMATIC_TARGET_ROOM (Prio 2) zurückgreifen."""
|
||||
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls._tmpdir = tempfile.TemporaryDirectory()
|
||||
cls._room_map_path = _make_minimal_room_map_json(cls._tmpdir.name)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls._tmpdir.cleanup()
|
||||
|
||||
def setUp(self):
|
||||
self.adapter, self.mock_rest = _build_mock_adapter(self._room_map_path)
|
||||
# _room_context ist ein globales Dict — pro Test leeren.
|
||||
with adapter_mod._room_context_lock:
|
||||
adapter_mod._room_context.clear()
|
||||
|
||||
def tearDown(self):
|
||||
# _CURRENT_TASK_TOKEN ist ein ContextVar — _set_room_context_origin
|
||||
# setzt ihn im Main-Thread. Zurücksetzen, damit er nicht in andere
|
||||
# Tests (test_v8_1_p1_contextvar) leakt.
|
||||
adapter_mod._CURRENT_TASK_TOKEN.set("")
|
||||
with adapter_mod._room_context_lock:
|
||||
adapter_mod._room_context.clear()
|
||||
|
||||
def _run_send(self, chat_id: str, content: str, origin: str = "",
|
||||
thematic: str = "", task_token: str = ""):
|
||||
"""send() in einem frischen asyncio-Task ausführen, mit explizit
|
||||
gesetzten ContextVars (task-lokal — müssen INNERHALB des Tasks
|
||||
gesetzt werden)."""
|
||||
async def _inner():
|
||||
adapter_mod._CURRENT_ORIGIN_ROOM.set(origin)
|
||||
adapter_mod._THEMATIC_TARGET_ROOM.set(thematic)
|
||||
adapter_mod._CURRENT_TASK_TOKEN.set(task_token)
|
||||
return await self.adapter.send(chat_id, content)
|
||||
|
||||
return asyncio.run(_inner())
|
||||
|
||||
def _posted_rooms(self):
|
||||
"""Räume, in die post_message aufgerufen wurde (in Reihenfolge)."""
|
||||
return [c[0][0] for c in self.mock_rest.post_message.call_args_list]
|
||||
|
||||
# ── Test 1 (RED): Stale _THEMATIC_TARGET_ROOM leitet user-Antwort um ──
|
||||
|
||||
def test_send_user_answer_ignores_stale_thematic_target(self):
|
||||
"""User-basierte Antwort mit stale _THEMATIC_TARGET_ROOM (room_b),
|
||||
aber leerem Origin/Context -> Antwort MUSS in den letzten bekannten
|
||||
Raum des Users (room_a), NICHT in room_b.
|
||||
|
||||
RED: aktueller Code greift auf Prio 2 (_THEMATIC_TARGET_ROOM) zurück
|
||||
und postet in room_b — FALSCH.
|
||||
"""
|
||||
# Letzter bekannter Raum des Users ist room_a.
|
||||
self.adapter._user_rooms["user:testuser"] = ["room_a"]
|
||||
|
||||
# Stale _THEMATIC_TARGET_ROOM aus einem früheren Turn (Feature-97).
|
||||
result = self._run_send(
|
||||
"user:testuser", "Hallo, hier ist die Antwort",
|
||||
origin="", thematic="room_b",
|
||||
)
|
||||
|
||||
self.assertTrue(result["success"], f"send() sollte erfolgreich sein: {result.get('error')}")
|
||||
rooms = self._posted_rooms()
|
||||
self.assertIn("room_a", rooms,
|
||||
"User-Antwort MUSS in den letzten bekannten Raum (room_a) gehen")
|
||||
self.assertNotIn("room_b", rooms,
|
||||
"User-Antwort darf NICHT über _THEMATIC_TARGET_ROOM in room_b landen")
|
||||
|
||||
# ── Test 2 (GREEN-Guard): Prio 0 gewinnt korrekt ─────────────────────
|
||||
|
||||
def test_send_user_answer_uses_origin_room_priority0(self):
|
||||
"""_CURRENT_ORIGIN_ROOM (Prio 0) gewinnt — auch wenn
|
||||
_THEMATIC_TARGET_ROOM gesetzt ist."""
|
||||
self.adapter._user_rooms["user:testuser"] = ["room_a"]
|
||||
|
||||
result = self._run_send(
|
||||
"user:testuser", "Antwort",
|
||||
origin="room_a", thematic="room_b",
|
||||
)
|
||||
|
||||
self.assertTrue(result["success"])
|
||||
rooms = self._posted_rooms()
|
||||
self.assertIn("room_a", rooms)
|
||||
self.assertNotIn("room_b", rooms,
|
||||
"Prio 0 (_CURRENT_ORIGIN_ROOM) muss _THEMATIC_TARGET_ROOM überstimmen")
|
||||
|
||||
# ── Test 3 (RED): _room_context-Fallback gewinnt korrekt ────────────
|
||||
|
||||
def test_send_user_answer_uses_room_context_fallback(self):
|
||||
"""_room_context (Prio 1) gewinnt — auch wenn _THEMATIC_TARGET_ROOM
|
||||
gesetzt ist. Simuliert Stream-Retry (kein Token im ContextVar)."""
|
||||
self.adapter._user_rooms["user:testuser"] = ["room_a"]
|
||||
|
||||
# Frischer _room_context-Slot für room_a (ohne Token-Match nötig).
|
||||
adapter_mod._set_room_context_origin("user:testuser", "room_a")
|
||||
|
||||
result = self._run_send(
|
||||
"user:testuser", "Antwort",
|
||||
origin="", thematic="room_b", task_token="",
|
||||
)
|
||||
|
||||
self.assertTrue(result["success"])
|
||||
rooms = self._posted_rooms()
|
||||
self.assertIn("room_a", rooms)
|
||||
self.assertNotIn("room_b", rooms,
|
||||
"Prio 1 (_room_context) muss _THEMATIC_TARGET_ROOM überstimmen")
|
||||
|
||||
# ── Test 4 (RED): Stream-Retry-Race — TTL-Fallback wählt frischesten ─
|
||||
|
||||
def test_stream_retry_ttl_fallback_chooses_freshest_slot(self):
|
||||
"""Stream-Retry in neuem asyncio-Task (kein _CURRENT_TASK_TOKEN):
|
||||
_room_context hat zwei Slots (room_a frisch, room_b alt) -> TTL-
|
||||
Fallback MUSS room_a wählen, NICHT room_b."""
|
||||
self.adapter._user_rooms["user:testuser"] = ["room_a"]
|
||||
|
||||
# room_a: frischer Slot (jetzt).
|
||||
adapter_mod._set_room_context_origin("user:testuser", "room_a")
|
||||
# room_b: alter Slot (Timestamp 40 Min zurück — TTL abgelaufen).
|
||||
old_ts = (__import__("datetime").datetime.now(
|
||||
__import__("datetime").timezone.utc)
|
||||
- __import__("datetime").timedelta(minutes=40)).isoformat()
|
||||
with adapter_mod._room_context_lock:
|
||||
adapter_mod._room_context["user:testuser"]["room_b"] = {
|
||||
"origin_room": "room_b",
|
||||
"task_token": "stale-token-b",
|
||||
"timestamp": old_ts,
|
||||
}
|
||||
|
||||
result = self._run_send(
|
||||
"user:testuser", "Antwort",
|
||||
origin="", thematic="", task_token="",
|
||||
)
|
||||
|
||||
self.assertTrue(result["success"])
|
||||
rooms = self._posted_rooms()
|
||||
self.assertIn("room_a", rooms,
|
||||
"TTL-Fallback muss den frischesten gültigen Slot (room_a) wählen")
|
||||
self.assertNotIn("room_b", rooms,
|
||||
"TTL-Fallback darf NICHT den abgelaufenen Slot (room_b) wählen")
|
||||
|
||||
|
||||
class TestP108cB2Reset(unittest.TestCase):
|
||||
"""P-108c Fix (a): B2-Branch setzt _THEMATIC_TARGET_ROOM explizit zurück.
|
||||
|
||||
Defense-in-Depth: Wenn der B2-Block (kein 100%-Keyword-Match) den Sticky
|
||||
ignoriert, muss _THEMATIC_TARGET_ROOM geleert und _CURRENT_ORIGIN_ROOM
|
||||
auf den Origin-Raum gesetzt werden — konsistent mit der Stay-Here-Logik.
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls._tmpdir = tempfile.TemporaryDirectory()
|
||||
cls._room_map_path = _make_minimal_room_map_json(cls._tmpdir.name)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls._tmpdir.cleanup()
|
||||
|
||||
def setUp(self):
|
||||
self.adapter, self.mock_rest = _build_mock_adapter(self._room_map_path)
|
||||
self.adapter.archivar.classify_and_route = __import__(
|
||||
"unittest.mock", fromlist=["AsyncMock"]).AsyncMock(return_value=None)
|
||||
self.adapter.handle_message = __import__(
|
||||
"unittest.mock", fromlist=["AsyncMock"]).AsyncMock()
|
||||
with adapter_mod._room_context_lock:
|
||||
adapter_mod._room_context.clear()
|
||||
|
||||
def tearDown(self):
|
||||
# _CURRENT_TASK_TOKEN zurücksetzen (leakt sonst in andere Tests).
|
||||
adapter_mod._CURRENT_TASK_TOKEN.set("")
|
||||
with adapter_mod._room_context_lock:
|
||||
adapter_mod._room_context.clear()
|
||||
|
||||
def _set_sticky(self, origin: str, target: str, target_name: str, topic: str):
|
||||
self.adapter._session_room_preferences[origin] = {
|
||||
"target_room": target,
|
||||
"target_name": target_name,
|
||||
"sticky_topic": topic,
|
||||
"expires_at": time.time() + 1800,
|
||||
}
|
||||
|
||||
def _msg(self, text: str, room: str) -> dict:
|
||||
return {
|
||||
"_id": "msg_p108c",
|
||||
"rid": room,
|
||||
"msg": text,
|
||||
"u": {"username": "testuser"},
|
||||
}
|
||||
|
||||
def test_b2_bypass_resets_thematic_target_room(self):
|
||||
"""B2-Bypass (kein 100%-Keyword-Match) -> _THEMATIC_TARGET_ROOM wird
|
||||
geleert und _CURRENT_ORIGIN_ROOM auf den Origin-Raum gesetzt."""
|
||||
self._set_sticky(
|
||||
"room_bat_team", "room_rc_plugin", "#Rocketchat-Plugin", "rocketchat-plugin"
|
||||
)
|
||||
|
||||
async def _process_and_capture():
|
||||
# Stale _THEMATIC_TARGET_ROOM simulieren (aus früherem Turn).
|
||||
adapter_mod._THEMATIC_TARGET_ROOM.set("room_rc_plugin")
|
||||
await self.adapter._process_incoming(
|
||||
self._msg("Pitfall in der neuen Architektur", "room_bat_team")
|
||||
)
|
||||
return {
|
||||
"origin": adapter_mod._CURRENT_ORIGIN_ROOM.get(),
|
||||
"thematic": adapter_mod._THEMATIC_TARGET_ROOM.get(),
|
||||
}
|
||||
|
||||
state = asyncio.run(_process_and_capture())
|
||||
|
||||
# B2-Bypass: kein Archivar-Routing.
|
||||
self.adapter.archivar.classify_and_route.assert_not_awaited()
|
||||
# _THEMATIC_TARGET_ROOM muss geleert sein (kein stale Zielraum).
|
||||
self.assertEqual(state["thematic"], "",
|
||||
"B2-Bypass muss _THEMATIC_TARGET_ROOM leeren (kein stale Zielraum)")
|
||||
# _CURRENT_ORIGIN_ROOM muss auf den Origin-Raum gesetzt sein.
|
||||
self.assertEqual(state["origin"], "room_bat_team",
|
||||
"B2-Bypass muss _CURRENT_ORIGIN_ROOM auf den Origin-Raum setzen")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user