fix(P1): F6 Nachbesserung — 4 fehlende _room_context Stellen + Inkonsistenz + Tests

P0: 4 ungepatchte _CURRENT_ORIGIN_ROOM.set() Stellen mit _room_context gefüllt:
- Z.2924: topic_scoped_sticky match → target_room_id
- Z.2969: topic_scoped_sticky (zweiter Branch) → target_room_id
- Z.3141: Auto-Route (V8.1 P1 path) → target_room_id
- Z.3196: Default-Origin (stay_in_room) → room_id

P1: send_clarify() Reihenfolge getauscht:
- _room_context VOR _THEMATIC_TARGET_ROOM (exakt wie in send())

P1: Helper-Funktion _set_room_context_origin() eingeführt:
- Atomare setdefault + Index-Zuweisung unter _room_context_lock
- An allen 10 Stellen verwendet (9 _CURRENT_ORIGIN_ROOM.set() + 1 initial set)

P1: 3 neue Tests:
- Test 8: send_clarify mit leerer ContextVar → _room_context Fallback
- Test 9: Concurrency — 10 parallele Tasks, 5 set + 5 read
- Test 10: Stale-Entry — _room_context gewinnt gegen _user_rooms
This commit is contained in:
Bernd (Hermes)
2026-07-26 10:34:00 +02:00
parent fdc755a87e
commit bf67761a57
2 changed files with 193 additions and 46 deletions
+48 -46
View File
@@ -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)