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:
Bernd (Hermes)
2026-07-26 10:08:31 +02:00
parent 7498b41675
commit fdc755a87e
2 changed files with 267 additions and 36 deletions
+94 -36
View File
@@ -1993,6 +1993,14 @@ class RocketChatAdapter(BasePlatformAdapter):
room_type = self._room_info.get(room_id, {}).get("type", "unknown")
logger.info("[rocketchat] Message from %s in %s [%s]: %s", username, room_name, room_type, text[:80])
# ── P1: _room_context als persistenter Fallback (Stream-Retry ContextVar-Reset) ──
# 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
# ── V8.6 P1a: PresenceEngine — mark_busy_started (Honeymoon-Timer) ──
# Graceful degradation: wenn _presence_engine nicht existiert
# (z.B. in Tests die __new__ statt __init__ verwenden), skip.
@@ -2210,6 +2218,11 @@ class RocketChatAdapter(BasePlatformAdapter):
if pending:
_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
routing_counter.increment('archivar_clarify_dispatched')
logger.info(
"[rocketchat] FIX 2: Clarify dispatch — "
@@ -2311,6 +2324,11 @@ class RocketChatAdapter(BasePlatformAdapter):
# 1️⃣ Rüber → Antwort im Zielraum (V8.1 P3: echtes Move, kein Copy)
_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"]
forwarded = True
feedback_type = "confirm"
# ── V8.3-5: Topic für Sticky extrahieren ──────────────
@@ -2517,6 +2535,11 @@ class RocketChatAdapter(BasePlatformAdapter):
return
# _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
# _THEMATIC_TARGET_ROOM: NOT set — no topic change
await self._dispatch_agent(
text=origin_text,
@@ -2635,6 +2658,11 @@ class RocketChatAdapter(BasePlatformAdapter):
# c. _CURRENT_ORIGIN_ROOM zurück auf Ursprungsraum
_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
# d. Sticky löschen
self._session_room_preferences.pop(origin_room_id, None)
# e. Ring: move_gc(target → origin) — Rückholung
@@ -2730,6 +2758,11 @@ class RocketChatAdapter(BasePlatformAdapter):
# a. _CURRENT_ORIGIN_ROOM auf Zielraum setzen
_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
# b. Sticky setzen: 30 Min, sticky_topic = 'explizit-wechsel'
self._session_room_preferences[room_id] = {
"target_room": target_room_id,
@@ -6313,6 +6346,11 @@ class RocketChatAdapter(BasePlatformAdapter):
# Route: Antwort geht in den Zielraum
_CURRENT_ORIGIN_ROOM.set(target_room_id)
_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
# Strip ROOM: prefix from content
content = _strip_red_flag_prefix(content)
# ── Ring-Feedback: Agent-Entscheidung trainieren ──
@@ -6359,28 +6397,39 @@ class RocketChatAdapter(BasePlatformAdapter):
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.
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 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
@@ -6724,25 +6773,34 @@ class RocketChatAdapter(BasePlatformAdapter):
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)
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)
if origin:
real_room_id = origin
logger.debug("[rocketchat] send via ContextVar: %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)
# 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:
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}")
# 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)
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}")
# Render full option text in the message body so users
# can read long choices that would be truncated in buttons.