fix: P0 — ContextVar-Verlust im Drain-Task (Agent antwortete im Quellraum statt Target-Raum nach Auto-Route)

This commit is contained in:
Bernd (Hermes)
2026-07-20 13:19:15 +02:00
parent 01a799c57a
commit 15057373ae
2 changed files with 347 additions and 2 deletions
+32 -2
View File
@@ -2664,7 +2664,25 @@ class RocketChatAdapter(BasePlatformAdapter):
raw_message=msg_obj,
)
event.source = source
await self.handle_message(event)
# ── V8.1 P1: ContextVar-Snapshot für Drain-Task ──────────
# contextvars.copy_context() friert die aktuellen ContextVar-Werte
# (_CURRENT_ORIGIN_ROOM, _THEMATIC_TARGET_ROOM) ein. handle_message()
# erzeugt intern asyncio.create_task (Drain-Task), der ContextVars
# vom aufrufenden Task erbt. Ohne Snapshot kann der Drain-Task
# veraltete Werte einer vorherigen Nachricht erben (Race Condition
# bei zwei schnellen Nachrichten hintereinander).
ctx = contextvars.copy_context()
# V8.1 P1 diagnostic: log dispatch context
_origin = _CURRENT_ORIGIN_ROOM.get()
_target = _THEMATIC_TARGET_ROOM.get()
logger.info(
"V8.1 P1 dispatch: chat_id=%s → target_room=%s, "
"_CURRENT_ORIGIN_ROOM=%s, _THEMATIC_TARGET_ROOM=%s",
virtual_chat_id, _target if _target else room_id,
_origin[:8] if _origin else "",
_target[:8] if _target else "",
)
await ctx.run(self.handle_message, event)
except Exception as e:
logger.error("[rocketchat] handle_message error: %s", e)
# Fallback: Wenn COMMAND fehlschlägt (z.B. nach Gateway-Neustart
@@ -3490,7 +3508,19 @@ class RocketChatAdapter(BasePlatformAdapter):
raw_message=msg_obj,
)
event.source = source
await self.handle_message(event)
# ── V8.1 P1: ContextVar-Snapshot für Drain-Task ──────────
ctx = contextvars.copy_context()
# V8.1 P1 diagnostic: log dispatch context
_origin = _CURRENT_ORIGIN_ROOM.get()
_target = _THEMATIC_TARGET_ROOM.get()
logger.info(
"V8.1 P1 dispatch: chat_id=%s → target_room=%s, "
"_CURRENT_ORIGIN_ROOM=%s, _THEMATIC_TARGET_ROOM=%s",
virtual_chat_id, _target if _target else room_id,
_origin[:8] if _origin else "",
_target[:8] if _target else "",
)
await ctx.run(self.handle_message, event)
except Exception as e:
logger.error("[rocketchat] handle_message error: %s", e)
# Fallback: Wenn COMMAND fehlschlägt
@@ -0,0 +1,315 @@
"""
V8.1 P1: ContextVar-Verlust im Drain-Task — Tests.
Root Cause: Bei zwei schnellen Nachrichten hintereinander erbt der
Drain-Task von Nachricht 2 die ContextVar-Werte von Nachricht 1
(Race Condition im asyncio-Task-Kontext).
Fix: contextvars.copy_context() vor handle_message() einfrieren,
damit der Drain-Task die korrekten ContextVar-Werte für seine
Nachricht bekommt.
Tests:
1. test_dispatch_task_contextvar: Zwei schnelle Nachrichten, zweite
wird geroutet, ContextVar hat korrekten Target-Raum.
2. test_dispatch_task_no_inherit: Drain-Task erbt NICHT ContextVar
von vorheriger Nachricht.
"""
from __future__ import annotations
import asyncio
import contextvars
import os
import sys
import unittest
from pathlib import Path
from unittest.mock import MagicMock, AsyncMock, patch
# Ensure the plugin package is importable
sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
class TestDispatchTaskContextVar(unittest.TestCase):
"""Tests für ContextVar-Isolation im Dispatch-Task (V8.1 P1)."""
def setUp(self):
"""Set up isolated ContextVars for each test."""
# Create fresh ContextVars (same names as in adapter.py)
self._CURRENT_ORIGIN_ROOM = contextvars.ContextVar(
"_rocketchat_origin_room", default=""
)
self._THEMATIC_TARGET_ROOM = contextvars.ContextVar(
"_rocketchat_thematic_target_room", default=""
)
# ── Test 1: Zwei schnelle Nachrichten, ContextVar korrekt ──────────
def test_dispatch_task_contextvar_two_fast_messages(self):
"""Zwei schnelle Nachrichten: zweite geroutet, ContextVar hat korrekten Target-Raum.
Szenario (Rainers Diagnose):
1. Nachricht 1: aus RC-Plugin → _CURRENT_ORIGIN_ROOM = "room_rc_plugin"
2. Nachricht 2: aus DM → 100%-Keyword matcht → Auto-Route zu DM
→ _CURRENT_ORIGIN_ROOM = "room_dm_user"
3. BUG: Drain-Task von Nachricht 2 erbt "room_rc_plugin" von Nachricht 1
4. Resultat: Agent antwortet im RC-Plugin statt im DM
Mit copy_context(): Drain-Task 2 bekommt "room_dm_user".
"""
# Nachricht 1: RC-Plugin Raum (stay in room)
msg1_origin = "room_rc_plugin"
msg1_target = ""
# Nachricht 2: DM → 100%-Keyword → Auto-Route zu DM
msg2_origin = "room_dm_user"
msg2_target = "room_dm_user" # Ziel = DM (wo geantwortet werden soll)
# ── Phase 1: Nachricht 1 setzt ContextVars ──
self._CURRENT_ORIGIN_ROOM.set(msg1_origin)
self._THEMATIC_TARGET_ROOM.set(msg1_target)
# Snapshot für Nachricht 1 (wie copy_context() im Fix)
ctx1 = contextvars.copy_context()
# ── Phase 2: Nachricht 2 setzt ContextVars (überschreibt) ──
self._CURRENT_ORIGIN_ROOM.set(msg2_target) # Auto-Route: Zielraum = DM
self._THEMATIC_TARGET_ROOM.set(msg2_target)
# Snapshot für Nachricht 2
ctx2 = contextvars.copy_context()
# ── Verifikation: Context 1 hat Werte von Nachricht 1 ──
self.assertEqual(
ctx1[self._CURRENT_ORIGIN_ROOM], msg1_origin,
"Context 1: _CURRENT_ORIGIN_ROOM sollte msg1_origin (RC-Plugin) sein"
)
self.assertEqual(
ctx1[self._THEMATIC_TARGET_ROOM], msg1_target,
"Context 1: _THEMATIC_TARGET_ROOM sollte leer sein"
)
# ── Verifikation: Context 2 hat Werte von Nachricht 2 ──
self.assertEqual(
ctx2[self._CURRENT_ORIGIN_ROOM], msg2_target,
"Context 2: _CURRENT_ORIGIN_ROOM sollte msg2_target (DM) sein"
)
self.assertEqual(
ctx2[self._THEMATIC_TARGET_ROOM], msg2_target,
"Context 2: _THEMATIC_TARGET_ROOM sollte msg2_target (DM) sein"
)
# ── Verifikation: Context 2 hat NICHT Werte von Nachricht 1 ──
self.assertNotEqual(
ctx2[self._CURRENT_ORIGIN_ROOM], msg1_origin,
"Context 2: _CURRENT_ORIGIN_ROOM darf NICHT msg1_origin (RC-Plugin) sein — "
"das ist der Bug: Drain-Task erbt falschen Raum"
)
# ── Test 2: Drain-Task erbt NICHT von vorheriger Nachricht ─────────
def test_dispatch_task_no_inherit_from_previous_message(self):
"""Drain-Task erbt NICHT ContextVar von vorheriger Nachricht.
Ohne copy_context() würde der Drain-Task die ContextVars vom
umgebenden Task erben. Wenn Nachricht 1 noch im Drain-Task
läuft und Nachricht 2 dispatched wird, könnte der Drain-Task
von Nachricht 2 die Werte von Nachricht 1 erben.
Mit copy_context() wird der Snapshot EINGEFROREN — der
Drain-Task bekommt IMMER die Werte seiner eigenen Nachricht.
"""
# Nachricht 1: RC-Plugin (kein Routing, stay in room)
msg1_origin = "room_rc_plugin"
self._CURRENT_ORIGIN_ROOM.set(msg1_origin)
self._THEMATIC_TARGET_ROOM.set("")
# Snapshot 1
ctx1 = contextvars.copy_context()
# Nachricht 2: DM → Auto-Route zu DM (anderer Raum!)
msg2_target = "room_dm_user"
self._CURRENT_ORIGIN_ROOM.set(msg2_target)
self._THEMATIC_TARGET_ROOM.set(msg2_target)
# Snapshot 2
ctx2 = contextvars.copy_context()
# ── Verifikation: Context 1 ist unverändert ──
# Auch nachdem Nachricht 2 die ContextVars überschrieben hat,
# behält ctx1 die Werte von Nachricht 1.
self.assertEqual(
ctx1[self._CURRENT_ORIGIN_ROOM], msg1_origin,
"ctx1 behält msg1_origin (RC-Plugin) — Snapshot ist eingefroren"
)
self.assertEqual(
ctx1[self._THEMATIC_TARGET_ROOM], "",
"ctx1 behält leeren Target — Snapshot ist eingefroren"
)
# ── Verifikation: Context 2 hat korrekte Werte ──
self.assertEqual(
ctx2[self._CURRENT_ORIGIN_ROOM], msg2_target,
"ctx2 hat msg2_target (DM) — Auto-Route Zielraum"
)
# ── Verifikation: Kein Cross-Contamination ──
self.assertNotEqual(
ctx1[self._CURRENT_ORIGIN_ROOM],
ctx2[self._CURRENT_ORIGIN_ROOM],
"ctx1 (RC-Plugin) und ctx2 (DM) haben unterschiedliche "
"_CURRENT_ORIGIN_ROOM Werte — keine Cross-Contamination"
)
# ── Test 3: copy_context isoliert korrekt ──────────────────────────
def test_copy_context_isolates_correctly(self):
"""copy_context() isoliert ContextVars korrekt zwischen zwei Tasks."""
# Setze initiale Werte
self._CURRENT_ORIGIN_ROOM.set("room_a")
self._THEMATIC_TARGET_ROOM.set("")
# Snapshot vor Änderung
ctx_before = contextvars.copy_context()
# Ändere Werte
self._CURRENT_ORIGIN_ROOM.set("room_b")
self._THEMATIC_TARGET_ROOM.set("room_b")
# Snapshot nach Änderung
ctx_after = contextvars.copy_context()
# ctx_before hat alte Werte
self.assertEqual(ctx_before[self._CURRENT_ORIGIN_ROOM], "room_a")
self.assertEqual(ctx_before[self._THEMATIC_TARGET_ROOM], "")
# ctx_after hat neue Werte
self.assertEqual(ctx_after[self._CURRENT_ORIGIN_ROOM], "room_b")
self.assertEqual(ctx_after[self._THEMATIC_TARGET_ROOM], "room_b")
# ── Test 4: Async-Task mit copy_context ────────────────────────────
def test_async_task_with_copy_context(self):
"""Async-Task mit copy_context() behält korrekte ContextVar-Werte."""
async def _run():
results = []
async def drain_task(ctx, expected_origin, task_id):
"""Simulierter Drain-Task — läuft im captured context."""
# Synchroner Teil: via ctx.run() damit ContextVar korrekt ist
def _work():
origin = ctx.run(self._CURRENT_ORIGIN_ROOM.get)
target = ctx.run(self._THEMATIC_TARGET_ROOM.get)
return (task_id, origin, target)
# run_in_executor erbt KEINE ContextVars → ctx.run() nötig
loop = asyncio.get_event_loop()
tid, origin, target = await loop.run_in_executor(None, _work)
results.append((f"{tid}_sync", origin, target))
# Async-Teil: ctx.run() für korrekte ContextVar-Werte
origin2 = ctx.run(self._CURRENT_ORIGIN_ROOM.get)
target2 = ctx.run(self._THEMATIC_TARGET_ROOM.get)
results.append((f"{task_id}_async", origin2, target2))
# Nachricht 1: RC-Plugin (stay in room)
self._CURRENT_ORIGIN_ROOM.set("room_rc_plugin")
self._THEMATIC_TARGET_ROOM.set("")
ctx1 = contextvars.copy_context()
# Nachricht 2: DM → Auto-Route zu DM
self._CURRENT_ORIGIN_ROOM.set("room_dm_user")
self._THEMATIC_TARGET_ROOM.set("room_dm_user")
ctx2 = contextvars.copy_context()
# Starte beide Drain-Tasks parallel
t1 = asyncio.create_task(
drain_task(ctx1, "room_rc_plugin", "msg1")
)
t2 = asyncio.create_task(
drain_task(ctx2, "room_dm_user", "msg2")
)
await asyncio.gather(t1, t2)
return results
results = asyncio.run(_run())
# Verifiziere: msg1 hat RC-Plugin, msg2 hat DM
for task_id, origin, target in results:
if "msg1" in task_id:
self.assertEqual(
origin, "room_rc_plugin",
f"Task {task_id}: origin sollte room_rc_plugin sein"
)
elif "msg2" in task_id:
self.assertEqual(
origin, "room_dm_user",
f"Task {task_id}: origin sollte room_dm_user sein"
)
# ── Test 5: Ohne copy_context → Race Condition ────────────────────
def test_without_copy_context_race_condition(self):
"""Ohne copy_context() kann der Drain-Task falsche Werte erben.
Dieser Test demonstriert die Race Condition: Wenn zwei Nachrichten
schnell hintereinander kommen und die ContextVars überschreiben,
sieht der zweite Drain-Task die Werte der ersten Nachricht.
"""
# Nachricht 1: RC-Plugin (stay in room)
self._CURRENT_ORIGIN_ROOM.set("room_rc_plugin")
self._THEMATIC_TARGET_ROOM.set("")
# OHNE copy_context: "Drain-Task 1" liest direkt
drain1_origin = self._CURRENT_ORIGIN_ROOM.get()
drain1_target = self._THEMATIC_TARGET_ROOM.get()
# Nachricht 2: DM → Auto-Route zu DM (überschreibt ContextVars)
self._CURRENT_ORIGIN_ROOM.set("room_dm_user")
self._THEMATIC_TARGET_ROOM.set("room_dm_user")
# OHNE copy_context: "Drain-Task 2" liest direkt
drain2_origin = self._CURRENT_ORIGIN_ROOM.get()
drain2_target = self._THEMATIC_TARGET_ROOM.get()
# Drain-Task 1: korrekt (weil vor Überschreibung gelesen)
self.assertEqual(drain1_origin, "room_rc_plugin")
self.assertEqual(drain1_target, "")
# Drain-Task 2: korrekt (weil nach Überschreibung gelesen)
self.assertEqual(drain2_origin, "room_dm_user")
self.assertEqual(drain2_target, "room_dm_user")
# ABER: Wenn Drain-Task 1 verzögert läuft (asyncio) und
# ContextVars NACH der Überschreibung liest → falsche Werte!
# Genau DAS verhindert copy_context().
# Simuliere verzögertes Lesen (wie im echten Drain-Task):
# Nachricht 1 setzt ContextVars
self._CURRENT_ORIGIN_ROOM.set("room_rc_plugin")
self._THEMATIC_TARGET_ROOM.set("")
# Nachricht 2 überschreibt (Auto-Route)
self._CURRENT_ORIGIN_ROOM.set("room_dm_user")
self._THEMATIC_TARGET_ROOM.set("room_dm_user")
# Drain-Task 1 liest verzögert → FALSCHE Werte!
delayed_origin = self._CURRENT_ORIGIN_ROOM.get()
delayed_target = self._THEMATIC_TARGET_ROOM.get()
# Das ist der BUG: delayed_origin ist "room_dm_user" statt "room_rc_plugin"
self.assertNotEqual(
delayed_origin, "room_rc_plugin",
"BUG: Drain-Task 1 sieht Werte von Nachricht 2 (room_dm_user) — "
"genau das verhindert copy_context()"
)
self.assertEqual(
delayed_origin, "room_dm_user",
"Drain-Task 1 hat fälschlich Werte von Nachricht 2 geerbt"
)
if __name__ == "__main__":
unittest.main()